diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8080550965220de73d49127fb56d8497440c44d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras' Distribution Strategy library.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distribute_coordinator_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distribute_coordinator_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5256924b7cffb333e319ac2b9937d7588c479c1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distribute_coordinator_utils.py @@ -0,0 +1,675 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities related to distribute coordinator. + +The module is used only for utils to support legacy TF1 code path involving +distribute coordinator, and is not expected to change in any way. This is +subject to cleanup once TF1 is no longer supported. + +TODO(rchao): Remove this module once TF1 is not supported. +""" + +import copy +import json +import os +import threading +import time +from tensorflow.core.protobuf import cluster_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import monitored_session +from tensorflow.python.training import server_lib + +_worker_context = threading.local() +_thread_local = threading.local() + + +def get_current_worker_context(): + """Returns the current task context.""" + try: + return _worker_context.current + except AttributeError: + return None + + +class _TaskType(object): + PS = "ps" + WORKER = "worker" + CHIEF = "chief" + EVALUATOR = "evaluator" + CLIENT = "client" + + +def _get_num_workers(cluster_spec): + """Gets number of workers including chief.""" + if not cluster_spec: + return 0 + return len(cluster_spec.as_dict().get(_TaskType.WORKER, [])) + len( + cluster_spec.as_dict().get(_TaskType.CHIEF, [])) + + +class _WorkerContext(object): + """The worker context class. + + This context object provides configuration information for each task. One + context manager with a worker context object will be created per + invocation to the `worker_fn` where `get_current_worker_context` can be called + to access the worker context object. + """ + + def __init__(self, + strategy, + cluster_spec, + task_type, + task_id, + session_config=None, + rpc_layer="grpc", + worker_barrier=None): + """Initialize the worker context object. + + Args: + strategy: a `DistributionStrategy` object. + cluster_spec: a ClusterSpec object. It can be empty or None in the local + training case. + task_type: a string indicating the role of the corresponding task, such as + "worker" or "ps". It can be None if it is local training or in-graph + replicated training. + task_id: an integer indicating id of the corresponding task. It can be + None if it is local training or in-graph replicated training. + session_config: an optional `tf.compat.v1.ConfigProto` object. + rpc_layer: optional string specifying the RPC protocol for communication + with worker masters. If None or empty, hosts in the `cluster_spec` will + be used directly. + worker_barrier: optional, the barrier object for worker synchronization. + """ + self._strategy = strategy + self._cluster_spec = cluster_spec + self._task_type = task_type + self._task_id = task_id + self._session_config = session_config + self._worker_barrier = worker_barrier + self._rpc_layer = rpc_layer + self._master_target = self._get_master_target() + self._num_workers = _get_num_workers(cluster_spec) + self._is_chief_node = self._is_chief() + + def _debug_message(self): + if self._cluster_spec: + return "[cluster_spec: %r, task_type: %r, task_id: %r]" % ( + self._cluster_spec, self.task_type, self.task_id) + else: + return "[local]" + + def __enter__(self): + old_context = get_current_worker_context() + if old_context: + raise ValueError( + "You cannot run distribute coordinator in a `worker_fn`.\t" + + self._debug_message()) + # pylint: disable=protected-access + _worker_context.current = self + + def __exit__(self, unused_exception_type, unused_exception_value, + unused_traceback): + # pylint: disable=protected-access + _worker_context.current = None + + def _get_master_target(self): + """Return the master target for a task.""" + # If cluster_spec is None or empty, we use local master. + if not self._cluster_spec or self._task_type == _TaskType.EVALUATOR: + return "" + + # If task_type is None, then it is in-graph replicated training. In this + # case we use the chief or first worker's master target. + if not self._task_type: + if _TaskType.CHIEF in self._cluster_spec.jobs: + task_type = _TaskType.CHIEF + task_id = 0 + else: + assert _TaskType.WORKER in self._cluster_spec.jobs + task_type = _TaskType.WORKER + task_id = 0 + else: + task_type = self._task_type + task_id = self._task_id + + prefix = "" + if self._rpc_layer: + prefix = self._rpc_layer + "://" + return prefix + self._cluster_spec.job_tasks(task_type)[task_id or 0] + + def _is_chief(self): + """Return whether the task is the chief worker.""" + if (not self._cluster_spec or + self._task_type in [_TaskType.CHIEF, _TaskType.EVALUATOR, None]): + return True + + # If not local and chief not in the cluster_spec, use the first worker as + # chief. + if (_TaskType.CHIEF not in self._cluster_spec.jobs and + self._task_type == _TaskType.WORKER and self._task_id == 0): + return True + return False + + def wait_for_other_workers(self): + """Waits for other workers to reach the same call to this method. + + Raises: + ValueError: if `worker_barrier` is not passed to the __init__ method. + """ + if not self._worker_barrier: + # TODO(yuefengz): we should throw an error in independent worker mode. + return + self._worker_barrier.wait() + + def session_creator(self, + scaffold=None, + config=None, + checkpoint_dir=None, + checkpoint_filename_with_path=None, + max_wait_secs=7200): + """Returns a session creator. + + The returned session creator will be configured with the correct master + target and session configs. It will also run either init ops or ready ops + by querying the `strategy` object when `create_session` is called on it. + + Args: + scaffold: A `Scaffold` used for gathering or building supportive ops. If + not specified a default one is created. It's used to finalize the graph. + config: `ConfigProto` proto used to configure the session. + checkpoint_dir: A string. Optional path to a directory where to restore + variables. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + Only one of `checkpoint_dir` or `checkpoint_filename_with_path` can be + specified. + max_wait_secs: Maximum time to wait for the session to become available. + + Returns: + a descendant of SessionCreator. + """ + if config: + session_config = copy.deepcopy(config) + session_config.MergeFrom(self._session_config) + else: + session_config = self._session_config + + if not self._strategy or self._strategy.extended.experimental_should_init: + logging.info("Creating chief session creator with config: %r", config) + return monitored_session.ChiefSessionCreator( + scaffold, + master=self.master_target, + config=session_config, + checkpoint_dir=checkpoint_dir, + checkpoint_filename_with_path=checkpoint_filename_with_path) + else: + logging.info("Creating worker session creator with config: %r", config) + return monitored_session.WorkerSessionCreator( + scaffold, + master=self.master_target, + config=session_config, + max_wait_secs=max_wait_secs) + + @property + def session_config(self): + return copy.deepcopy(self._session_config) + + @property + def has_barrier(self): + """Whether the barrier is set or not.""" + return self._worker_barrier is not None + + @property + def distributed_mode(self): + """Whether it is distributed training or not.""" + return bool(self._cluster_spec) and self._task_type != _TaskType.EVALUATOR + + @property + def cluster_spec(self): + """Returns a copy of the cluster_spec object.""" + return copy.deepcopy(self._cluster_spec) + + @property + def task_type(self): + """Returns the role of the corresponding task.""" + return self._task_type + + @property + def task_id(self): + """Returns the id or index of the corresponding task.""" + return self._task_id + + @property + def master_target(self): + """Returns the session master for the corresponding task to connect to.""" + return self._master_target + + @property + def is_chief(self): + """Returns whether the task is a chief node.""" + return self._is_chief_node + + @property + def num_workers(self): + """Returns number of workers in the cluster, including chief.""" + return self._num_workers + + @property + def experimental_should_init(self): + """Whether to run init ops.""" + return self._strategy.extended.experimental_should_init + + @property + def should_checkpoint(self): + """Whether to save checkpoint.""" + return self._strategy.extended.should_checkpoint + + @property + def should_save_summary(self): + """Whether to save summaries.""" + return self._strategy.extended.should_save_summary + + +def _run_single_worker(worker_fn, + strategy, + cluster_spec, + task_type, + task_id, + session_config, + rpc_layer="", + worker_barrier=None, + coord=None): + """Runs a single worker by calling `worker_fn` under context.""" + session_config = copy.deepcopy(session_config) + strategy = copy.deepcopy(strategy) + # If there is an EVALUATOR task, we run single-machine eval on that task. + if task_type == _TaskType.EVALUATOR: + # It is possible to not have a strategy object for EVALUATOR task. + if strategy: + strategy.configure(session_config) + else: + assert strategy + strategy.configure(session_config, cluster_spec, task_type, task_id) + + context = _WorkerContext( + strategy, + cluster_spec, + task_type, + task_id, + session_config=session_config, + rpc_layer=rpc_layer, + worker_barrier=worker_barrier) + with context: + if coord: + with coord.stop_on_exception(): + return worker_fn(strategy) + else: + return worker_fn(strategy) + + +def _split_cluster_for_evaluator(cluster_spec, task_type): + """Split the cluster for evaluator since it needn't talk to other tasks.""" + # Splitting the cluster is important to prevent the evaluator from talking to + # other tasks in the cluster. Since we allow evaluator not to use + # distribution strategies and as a result ops in the evaluator task may have + # unspecified devices. Those ops may end up on other tasks if we don't split + # the cluster. + # Note: if you bypass distribute coordinator and bring the cluster yourself, + # you can equivalently set device filters to split clusters. This is already + # done by distribution strategy's `update_config_proto` method. + new_cluster_spec = normalize_cluster_spec(cluster_spec).as_dict() + if task_type == _TaskType.EVALUATOR: + assert _TaskType.EVALUATOR in new_cluster_spec + new_cluster_spec = { + _TaskType.EVALUATOR: new_cluster_spec[_TaskType.EVALUATOR] + } + else: + new_cluster_spec.pop(_TaskType.EVALUATOR, None) + return normalize_cluster_spec(new_cluster_spec) + + +def _run_std_server(cluster_spec=None, + task_type=None, + task_id=None, + session_config=None, + rpc_layer=None, + environment=None): + """Runs a standard server.""" + # Check if the Server is already running. If so, assert that no configuration + # options have changed, and return the existing Server. This allows us to + # call `run_distribute_coordinator` multiple times. + if getattr(_thread_local, "server", None) is not None: + assert _thread_local.cluster_spec == cluster_spec + assert _thread_local.task_type == task_type + assert _thread_local.task_id == task_id + assert _thread_local.session_config_str == repr(session_config) + assert _thread_local.rpc_layer == rpc_layer + assert _thread_local.environment == environment + return _thread_local.server + else: + # This method is not thread-safe. + _thread_local.server_started = True + _thread_local.cluster_spec = cluster_spec + _thread_local.task_type = task_type + _thread_local.task_id = task_id + _thread_local.session_config_str = repr(session_config) + _thread_local.rpc_layer = rpc_layer + _thread_local.environment = environment + + assert cluster_spec + target = cluster_spec.task_address(task_type, task_id) + if rpc_layer: + target = rpc_layer + "://" + target + + class _FakeServer(object): + """A fake server that runs a master session.""" + + def start(self): + # A tensorflow server starts when a remote session is created. + logging.info( + "Creating a remote session to start a TensorFlow server, " + "target = %r, session_config=%r", target, session_config) + session.Session(target=target, config=session_config) + + def join(self): + while True: + time.sleep(5) + + if environment == "google": + server = _FakeServer() + else: + if session_config: + logging.info( + "Starting standard TensorFlow server, target = %r, session_config= " + "%r", target, session_config) + else: + logging.info("Starting standard TensorFlow server, target = %r", target) + cluster_spec = _split_cluster_for_evaluator(cluster_spec, task_type) + server = server_lib.Server( + cluster_spec, + job_name=task_type, + task_index=task_id, + config=session_config, + protocol=rpc_layer) + + server.start() + _thread_local.server = server + return server + + +def _configure_session_config_for_std_servers(strategy, eval_strategy, + session_config, cluster_spec, + task_type, task_id): + # pylint: disable=g-doc-args + """Call strategy's `configure` to mutate the session_config. + + The session_config is currently needed as default config for a TensorFlow + server. In the future, we should be able to remove this method and only pass + the session config to a client session. + """ + if task_type == _TaskType.EVALUATOR: + if eval_strategy: + eval_strategy.configure(session_config=session_config) + else: + # The strategy may be shared in standalone client mode. + strategy = copy.deepcopy(strategy) + strategy.configure( + session_config=session_config, + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id) + # Remove the device filters specific to the strategy, so that the + # TensorFlow server brought up with one strategy can be used by other + # strategies. The device filters can be set in the client side as well. + del session_config.device_filters[:] + + +# TODO(yuefengz): propagate cluster_spec in the STANDALONE_CLIENT mode. +# TODO(yuefengz): we may need a smart way to figure out whether the current task +# is the special task when we support cluster_spec propagation. +def run_distribute_coordinator(worker_fn, + strategy, + eval_fn=None, + eval_strategy=None, + cluster_spec=None, + task_type=None, + task_id=None, + session_config=None, + rpc_layer="grpc"): + """Runs the coordinator for distributed TensorFlow. + + This function runs a split coordinator for distributed TensorFlow in its + default mode, i.e the STANDALONE_CLIENT mode. Given a `cluster_spec` + specifying server addresses and their roles in a cluster, this coordinator + will figure out how to set them up, give the underlying function the right + targets for master sessions via a scope object and coordinate their training. + The cluster consisting of standard servers needs to be brought up either with + the standard server binary or with a binary running distribute coordinator + with `task_type` set to non-client type which will then turn into standard + servers. + + In addition to be the distribute coordinator, this is also the source of + configurations for each job in the distributed training. As there are multiple + ways to configure a distributed TensorFlow cluster, its context object + provides these configurations so that users or higher-level APIs don't have to + figure out the configuration for each job by themselves. + + In the between-graph replicated training, this coordinator will create + multiple threads and each calls the `worker_fn` which is supposed to create + its own graph and connect to one worker master given by its context object. In + the in-graph replicated training, it has only one thread calling this + `worker_fn`. + + Another mode is the INDEPENDENT_WORKER mode where each server runs a + distribute coordinator which will start a standard server and optionally runs + `worker_fn` depending whether it is between-graph training or in-graph + replicated training. + + The `strategy` object is expected to be a DistributionStrategy object which + has implemented methods needed by distributed coordinator such as + `configure(session_config, cluster_spec, task_type, task_id)` which configures + the strategy object for a specific task and `experimental_should_init` + property which instructs the distribute coordinator whether to run init ops + for a task. The distribute coordinator will make a copy of the `strategy` + object, call its `configure` method and pass it to `worker_fn` as an argument. + + The `worker_fn` defines the training logic and is called under its own + worker context which can be accessed to via `get_current_worker_context`. A + worker context provides access to configurations for each task, e.g. the + task_type, task_id, master target and so on. Since `worker_fn` will be called + in a thread and possibly multiple times, caller should be careful when it + accesses global data. For example, it is unsafe to define flags in a + `worker_fn` or to define different environment variables for different + `worker_fn`s. + + The `worker_fn` for the between-graph replication is defined as if there is + only one worker corresponding to the `worker_fn` and possibly ps jobs. For + example, when training with parameter servers, it assigns variables to + parameter servers and all other operations to that worker. In the in-graph + replication case, the `worker_fn` has to define operations for all worker + jobs. Using a distribution strategy can simplify the `worker_fn` by not having + to worry about the replication and device assignment of variables and + operations. + + This method is intended to be invoked by high-level APIs so that users don't + have to explicitly call it to run this coordinator. For those who don't use + high-level APIs, to change a program to use this coordinator, wrap everything + in a the program after global data definitions such as commandline flag + definition into the `worker_fn` and get task-specific configurations from + the worker context. + + The `cluster_spec` can be either passed by the argument or parsed from the + "TF_CONFIG" environment variable. Example of a TF_CONFIG: + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + os.environ['TF_CONFIG'] = json.dumps({'cluster': cluster}) + ``` + + If `cluster_spec` is not given in any format, it becomes local training and + this coordinator will connect to a local session. + + For evaluation, if "evaluator" exists in the cluster_spec, a separate thread + will be created to call `eval_fn` with its `task_type` set to "evaluator". If + `eval_fn` is not defined, fall back to `worker_fn`. This implies that + evaluation will be done on a single machine if there is an "evaluator" task. + If "evaluator" doesn't exist in the cluster_spec, it entirely depends on the + `worker_fn` for how to do evaluation. + + Args: + worker_fn: the function to be called. The function should accept a + `strategy` object and will be given access to a context object via a + context manager scope. + strategy: a DistributionStrategy object specifying whether it should run + between-graph replicated training or not, whether to run init ops, etc. + This object will also be configured given `session_config`, + `cluster_spec`, `task_type` and `task_id`. + eval_fn: optional function for "evaluator" task. If `eval_fn` is not passed + in but a "evaluator" task is found in the `cluster_spec`, the `worker_fn` + will be used for this task. + eval_strategy: optional DistributionStrategy object for "evaluator" task. + cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and roles + in a cluster. If not set or empty, fall back to local training. + task_type: the current task type, optional if this is a client. + task_id: the current task id, optional if this is a client. + session_config: an optional `tf.compat.v1.ConfigProto` object which will be + passed to `strategy`'s `configure` method and used to create a session. + rpc_layer: optional string, the protocol for RPC, e.g. "grpc". + + Raises: + ValueError: if `cluster_spec` is supplied but not a dict or a ClusterDef or + a ClusterSpec. + + Returns: + In the client job, return the value returned by `worker_fn` if + it is in-graph replication or INDEPENDENT_WORKER mode; return None + otherwise. + """ + tf_config = json.loads(os.environ.get("TF_CONFIG", "{}")) + rpc_layer = tf_config.get("rpc_layer", rpc_layer) + environment = tf_config.get("environment", None) + + if not cluster_spec: + cluster_spec = tf_config.get("cluster", {}) + task_env = tf_config.get("task", {}) + if task_env: + task_type = task_env.get("type", task_type) + task_id = int(task_env.get("index", task_id)) + + if cluster_spec: + # TODO(yuefengz): validate cluster_spec. + cluster_spec = normalize_cluster_spec(cluster_spec) + elif hasattr(strategy.extended, "_cluster_resolver"): + cluster_resolver = strategy.extended._cluster_resolver # pylint: disable=protected-access + task_type = cluster_resolver.task_type + task_id = cluster_resolver.task_id + rpc_layer = cluster_resolver.rpc_layer or rpc_layer + environment = cluster_resolver.environment + cluster_spec = cluster_resolver.cluster_spec() + + # Setting the session config is necessary for some strategies such as + # CollectiveAllReduceStrategy. + session_config = session_config or config_pb2.ConfigProto( + allow_soft_placement=True) + + if cluster_spec: + logging.info( + "Running Distribute Coordinator with cluster_spec = %r, " + "task_type = %r, task_id = %r, environment = %r, rpc_layer = %r", + cluster_spec.as_dict(), task_type, task_id, environment, rpc_layer) + + if not cluster_spec: + # `mode` is ignored in the local case. + logging.info("Running local Distribute Coordinator.") + _run_single_worker(worker_fn, strategy, None, None, None, session_config, + rpc_layer) + if eval_fn: + _run_single_worker(eval_fn, eval_strategy, None, None, None, + session_config, rpc_layer) + else: + logging.warning("Skipped evaluation since `eval_fn` is not passed in.") + else: + if not eval_fn: + logging.warning("`eval_fn` is not passed in. The `worker_fn` will be " + "used if an \"evaluator\" task exists in the cluster.") + eval_fn = eval_fn or worker_fn + if not eval_strategy: + logging.warning("`eval_strategy` is not passed in. No distribution " + "strategy will be used for evaluation.") + + # Every one starts a standard server, get session config from `configure` + # method. + _configure_session_config_for_std_servers(strategy, eval_strategy, + session_config, cluster_spec, + task_type, task_id) + + if (task_type != _TaskType.EVALUATOR and + not getattr(strategy.extended, "_std_server_started", False)): + # Right now, with eager mode, context is configured with a std server at + # the very beginning while with graph mode the std server is started when + # distribute coordinator is called. We should consolidate these two paths. + server = _run_std_server( + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id, + session_config=session_config, + rpc_layer=rpc_layer, + environment=environment) + if task_type in [_TaskType.CHIEF, _TaskType.WORKER]: + if strategy.extended.experimental_between_graph: + # All jobs run `worker_fn` if between-graph. + return _run_single_worker(worker_fn, strategy, cluster_spec, task_type, + task_id, session_config, rpc_layer) + else: + # Only one node runs `worker_fn` if in-graph. + context = _WorkerContext(strategy, cluster_spec, task_type, task_id) + if context.is_chief: + return _run_single_worker(worker_fn, strategy, cluster_spec, None, + None, session_config, rpc_layer) + else: + server.join() + elif task_type == _TaskType.EVALUATOR: + return _run_single_worker(eval_fn, eval_strategy, cluster_spec, task_type, + task_id, session_config, rpc_layer) + else: + if task_type != _TaskType.PS: + raise ValueError("Unexpected task_type: %r" % task_type) + server.join() + + +def normalize_cluster_spec(cluster_spec): + """Makes `cluster_spec` into a `ClusterSpec` object. + + Args: + cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the + cluster configurations. + + Returns: + a `ClusterSpec` object. + + Raises: + ValueError: if `cluster_spec` is not a dict or a `ClusterSpec` or a + `ClusterDef`. + """ + if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)): + return server_lib.ClusterSpec(cluster_spec) + elif not isinstance(cluster_spec, server_lib.ClusterSpec): + raise ValueError( + "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a " + "`tf.train.ClusterDef` object") + return cluster_spec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_file_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..93615bbc67bc1f1bf43bdbd999cdef016d1c5343 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_file_utils.py @@ -0,0 +1,146 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities that help manage directory path in distributed settings. + +In multi-worker training, the need to write a file to distributed file +location often requires only one copy done by one worker despite many workers +that are involved in training. The option to only perform saving by chief is +not feasible for a couple of reasons: 1) Chief and workers may each contain +a client that runs the same piece of code and it's preferred not to make +any distinction between the code run by chief and other workers, and 2) +saving of model or model's related information may require SyncOnRead +variables to be read, which needs the cooperation of all workers to perform +all-reduce. + +This set of utility is used so that only one copy is written to the needed +directory, by supplying a temporary write directory path for workers that don't +need to save, and removing the temporary directory once file writing is done. + +Example usage: +``` +# Before using a directory to write file to. +self.log_write_dir = write_dirpath(self.log_dir, get_distribution_strategy()) +# Now `self.log_write_dir` can be safely used to write file to. + +... + +# After the file is written to the directory. +remove_temp_dirpath(self.log_dir, get_distribution_strategy()) + +``` + +Experimental. API is subject to change. +""" + +import os + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.lib.io import file_io + + +def _get_base_dirpath(strategy): + task_id = strategy.extended._task_id # pylint: disable=protected-access + return 'workertemp_' + str(task_id) + + +def _is_temp_dir(dirpath, strategy): + return dirpath.endswith(_get_base_dirpath(strategy)) + + +def _get_temp_dir(dirpath, strategy): + if _is_temp_dir(dirpath, strategy): + temp_dir = dirpath + else: + temp_dir = os.path.join(dirpath, _get_base_dirpath(strategy)) + file_io.recursive_create_dir_v2(temp_dir) + return temp_dir + + +def write_dirpath(dirpath, strategy): + """Returns the writing dir that should be used to save file distributedly. + + `dirpath` would be created if it doesn't exist. + + Args: + dirpath: Original dirpath that would be used without distribution. + strategy: The tf.distribute strategy object currently used. + + Returns: + The writing dir path that should be used to save with distribution. + """ + if strategy is None: + # Infer strategy from `distribute_lib` if not given. + strategy = distribute_lib.get_strategy() + if strategy is None: + # If strategy is still not available, this is not in distributed training. + # Fallback to original dirpath. + return dirpath + if not strategy.extended._in_multi_worker_mode(): # pylint: disable=protected-access + return dirpath + if strategy.extended.should_checkpoint: + return dirpath + # If this worker is not chief and hence should not save file, save it to a + # temporary directory to be removed later. + return _get_temp_dir(dirpath, strategy) + + +def remove_temp_dirpath(dirpath, strategy): + """Removes the temp path after writing is finished. + + Args: + dirpath: Original dirpath that would be used without distribution. + strategy: The tf.distribute strategy object currently used. + """ + if strategy is None: + # Infer strategy from `distribute_lib` if not given. + strategy = distribute_lib.get_strategy() + if strategy is None: + # If strategy is still not available, this is not in distributed training. + # Fallback to no-op. + return + # TODO(anjalisridhar): Consider removing the check for multi worker mode since + # it is redundant when used with the should_checkpoint property. + if (strategy.extended._in_multi_worker_mode() and # pylint: disable=protected-access + not strategy.extended.should_checkpoint): + # If this worker is not chief and hence should not save file, remove + # the temporary directory. + file_io.delete_recursively(_get_temp_dir(dirpath, strategy)) + + +def write_filepath(filepath, strategy): + """Returns the writing file path to be used to save file distributedly. + + Directory to contain `filepath` would be created if it doesn't exist. + + Args: + filepath: Original filepath that would be used without distribution. + strategy: The tf.distribute strategy object currently used. + + Returns: + The writing filepath that should be used to save file with distribution. + """ + dirpath = os.path.dirname(filepath) + base = os.path.basename(filepath) + return os.path.join(write_dirpath(dirpath, strategy), base) + + +def remove_temp_dir_with_filepath(filepath, strategy): + """Removes the temp path for file after writing is finished. + + Args: + filepath: Original filepath that would be used without distribution. + strategy: The tf.distribute strategy object currently used. + """ + remove_temp_dirpath(os.path.dirname(filepath), strategy) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f40fd5fdbf803de425f9a9e27d4608ba58c90d49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils.py @@ -0,0 +1,65 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities related to distributed training.""" +# pylint:disable=protected-access + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import values as values_lib +from tensorflow.python.keras import backend +from tensorflow.python.ops import variables + + +# TODO(b/118776054): Currently we support global batch size for TPUStrategy and +# core MirroredStrategy only. Remove this check when contrib MirroredStrategy is +# no longer needed. +def global_batch_size_supported(distribution_strategy): + return distribution_strategy.extended._global_batch_size # pylint: disable=protected-access + + +def call_replica_local_fn(fn, *args, **kwargs): + """Call a function that uses replica-local variables. + + This function correctly handles calling `fn` in a cross-replica + context. + + Args: + fn: The function to call. + *args: Positional arguments to the `fn`. + **kwargs: Keyword argument to `fn`. + + Returns: + The result of calling `fn`. + """ + # TODO(b/132666209): Remove this function when we support assign_* + # for replica-local variables. + strategy = None + if 'strategy' in kwargs: + strategy = kwargs.pop('strategy') + else: + if distribute_lib.has_strategy(): + strategy = distribute_lib.get_strategy() + + # TODO(b/120571621): TPUStrategy does not implement replica-local variables. + is_tpu = backend.is_tpu_strategy(strategy) + if ((not is_tpu) and strategy and distribute_lib.in_cross_replica_context()): + with strategy.scope(): + return strategy.extended.call_for_each_replica(fn, args, kwargs) + return fn(*args, **kwargs) + + +def is_distributed_variable(v): + """Returns whether `v` is a distributed variable.""" + return (isinstance(v, values_lib.DistributedValues) and + isinstance(v, variables.Variable)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d6d38570dcbf5ebca090ca30233cfbc809face --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/distributed_training_utils_v1.py @@ -0,0 +1,1148 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities related to distributed training.""" +# pylint:disable=protected-access + +import functools + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.distribute import reduce_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks +from tensorflow.python.keras import metrics as metrics_module +from tensorflow.python.keras import optimizers +from tensorflow.python.keras.distribute import distribute_coordinator_utils as dc +from tensorflow.python.keras.distribute import distributed_training_utils as dist_utils +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest + + +def set_weights(distribution_strategy, dist_model, weights): + """Sets the weights of the replicated models. + + The weights of the replicated models are set to the weights of the original + model. The weights of the replicated model are Mirrored variables and hence + we need to use the `update` call within a DistributionStrategy scope. + + Args: + distribution_strategy: DistributionStrategy used to distribute training + and validation. + dist_model: The replicated models on the different devices. + weights: The weights of the original model. + """ + assign_ops = [] + for layer in dist_model.layers: + num_param = len(layer.weights) + layer_weights = weights[:num_param] + for sw, w in zip(layer.weights, layer_weights): + if ops.executing_eagerly_outside_functions(): + sw.assign(w) + else: + assign_ops.append(distribution_strategy.unwrap(sw.assign(w))) + weights = weights[num_param:] + + if not ops.executing_eagerly_outside_functions(): + backend.get_session(assign_ops).run(assign_ops) + + +def unwrap_values(distribution_strategy, grouped_inputs, grouped_outputs, + grouped_updates=None, grouped_session_args=None, + with_loss_tensor=False): + """Unwrap the list of values contained in the PerReplica parameters. + + This function calls `flatten_per_replica_values` to parse each of the input + parameters into a list of values on the different devices. If we set + `with_loss_tensor` to be True, we also call `reduce` on the list of losses on + the different devices to give us one loss tensor. + + Args: + distribution_strategy: DistributionStrategy used to distribute training and + validation. + grouped_inputs: PerReplica inputs returned from the train or test function + that we ran on each device. + grouped_outputs: PerReplica outputs returned from the train or test function + that we ran on each device. + grouped_updates: PerReplica updates returned from the train or test function + that we ran on each device. + grouped_session_args: PerReplica session args returned from the train or + test function that we ran on each device. + with_loss_tensor: Boolean that indicates if we need to add the reduced loss + tensor as one of the outputs. + + Returns: + Values of each of the PerReplica parameters. + + """ + # Unwrap per device values returned from each model's train function. + # This will be used to construct the main train function. + all_inputs = flatten_per_replica_values(distribution_strategy, + grouped_inputs) + all_outputs = unwrap_outputs(distribution_strategy, grouped_outputs, + with_loss_tensor) + + if grouped_updates: + all_updates = flatten_per_replica_values(distribution_strategy, + grouped_updates) + else: + all_updates = None + + all_session_args = {} + if grouped_session_args: + grouped_feed_dict = grouped_session_args.get('feed_dict') + if grouped_feed_dict: + all_session_args['feed_dict'] = flatten_per_replica_values( + distribution_strategy, grouped_feed_dict) + + grouped_fetches = grouped_session_args.get('fetches') + if grouped_fetches: + all_session_args['fetches'] = flatten_per_replica_values( + distribution_strategy, grouped_fetches) + + # TODO(priyag): Return only non empty/None values + return all_inputs, all_outputs, all_updates, all_session_args + + +def unwrap_output_dict(strategy, grouped_outputs, mode): + """Unwrap the list of outputs contained in the PerReplica parameters.""" + if mode == ModeKeys.PREDICT: + return flatten_per_replica_values(strategy, grouped_outputs) + + # In the case of fit/eval, the grouped_outputs is a dict, whereas in predict, + # the output is as same structure as model output. They need to be treated + # differently + total_loss = strategy.reduce(reduce_util.ReduceOp.SUM, + grouped_outputs['total_loss'][0], axis=None) + output_losses = flatten_per_replica_values(strategy, + grouped_outputs['output_losses']) + metrics = flatten_per_replica_values(strategy, + grouped_outputs['metrics']) + batch_size = strategy.reduce(reduce_util.ReduceOp.SUM, + grouped_outputs['batch_size'], axis=None) + if (backend.is_tpu_strategy(strategy) and + ops.executing_eagerly_outside_functions()): + # Choose 1 value per replica in the TPU case since all replicas produce the + # same output. + # We only do this in eager mode for now since this function is used in + # both graph and eager mode and in the graph case we currently don't use + # experimental_run so would need to be removed when we converge the graph + # code path as well. + output_losses = output_losses[::strategy.num_replicas_in_sync] + metrics = metrics[::strategy.num_replicas_in_sync] + return {'total_loss': [total_loss], + 'output_losses': output_losses, + 'metrics': metrics, + 'batch_size': batch_size} + + +def unwrap_outputs(distribution_strategy, grouped_outputs, + with_loss_tensor=False): + """Unwrap the list of outputs contained in the PerReplica parameters. + + This function calls `flatten_per_replica_values` to parse each of the input + parameters into a list of outputs on the different devices. If we set + `with_loss_tensor` to be True, we also call `reduce` on the list of losses on + the different devices to give us one loss tensor. + + Args: + distribution_strategy: DistributionStrategy used to distribute training and + validation. + grouped_outputs: PerReplica outputs returned from the train or test function + that we ran on each device. + with_loss_tensor: Boolean that indicates if we need to add the reduced loss + tensor as one of the outputs. + + Returns: + Values of each of the PerReplica outputs. + + """ + if not with_loss_tensor: + return flatten_per_replica_values(distribution_strategy, + grouped_outputs) + + if not isinstance(grouped_outputs, list): + grouped_outputs = [grouped_outputs] + # reduce loss tensor before adding it to the list of fetches + loss = distribution_strategy.reduce(reduce_util.ReduceOp.SUM, + grouped_outputs[0], axis=None) + all_outputs = flatten_per_replica_values(distribution_strategy, + grouped_outputs[1:]) + if (backend.is_tpu_strategy(distribution_strategy) and + ops.executing_eagerly_outside_functions()): + # Choose 1 value per replica in the TPU case since all replicas produce the + # same output. + # We only do this in eager mode for now since this function is used in + # both graph and eager mode and in the graph case we currently don't use + # experimental_run so would need to be removed when we converge the graph + # code path as well. + all_outputs = all_outputs[::distribution_strategy.num_replicas_in_sync] + return [loss] + all_outputs + + +def flatten_per_replica_values(distribution_strategy, per_replica_values): + """Unwraps and flattens a nest of PerReplica parameters. + + PerReplica values have one value associated with each device. Each entry in + the PerReplica dict has a device `key` and the corresponding value on the + device as the `value`. In this function we take a PerReplica value or a list + of PerReplica values and return all the values in the PerReplica dict. + + Args: + distribution_strategy: DistributionStrategy used to distribute training and + validation. + per_replica_values: List of PerReplica object or a single PerReplica object. + + Returns: + List of values of all the PerReplica objects. + + """ + # pylint: disable=g-complex-comprehension + # This function takes a PerReplica object or a list of PerReplica objects and + # returns all the values associated with it. + return [e for flattened in nest.flatten(per_replica_values) + for e in distribution_strategy.unwrap(flattened)] + + +def validate_callbacks(input_callbacks, optimizer): + """Validate whether given callbacks are supported by DistributionStrategy. + + Args: + input_callbacks: List of callbacks passed by the user to fit. + optimizer: Optimizer instance used to train the model. + + Raises: + ValueError: If `LearningRateScheduler` or `ReduceLROnPlateau` is one of the + callbacks passed. + ValueError: If `write_grads` is one of the parameters passed as part of the + TensorBoard callback. + """ + if input_callbacks: + for callback in input_callbacks: + if isinstance(callback, (callbacks.LearningRateScheduler, + callbacks.ReduceLROnPlateau)): + + if not isinstance(optimizer, optimizer_v2.OptimizerV2): + raise ValueError('You must specify a Keras Optimizer V2 when using ' + '%s callback with DistributionStrategy.' % callback) + + # If users want to use the TensorBoard callback they cannot use certain + # features of the callback that involve accessing model attributes and + # running ops. + if isinstance(callback, callbacks.TensorBoard): + if getattr(callback, 'write_grads', False): + logging.warning( + UserWarning( + '`write_grads` in the TensorBoard callback is not supported ' + 'when using DistributionStrategy. Setting `write_grads` ' + 'to `False`.')) + callback.write_grads = False + + +def validate_distributed_dataset_inputs(distribution_strategy, x, y, + sample_weights=None): + """Validate all the components of a DistributedValue Dataset input. + + Args: + distribution_strategy: The current DistributionStrategy used to call + `fit`/`evaluate`. + x: Input Dataset DistributedValue object. For example, when we use + `MirroredStrategy` this is a PerReplica object with a tensor for each + device set in the dict. x can also be a tuple or dict. The keys of the + dict should match the names of the input layers of the model. + y: Target Dataset DistributedValue object. For example, when we use + `MirroredStrategy` this is a PerReplica object with a tensor for each + device set in the dict. y can also be a tuple or dict. The keys of the + dict should match the names of the output layers of the model. + sample_weights: Sample weights Dataset DistributedValue object. For example, + when we use `MirroredStrategy` this is a PerReplica object with a tensor + for each device set in the dict. + + Returns: + The unwrapped values list of the x and y DistributedValues inputs. + + Raises: + ValueError: If x and y do not have support for being evaluated as tensors. + or if x and y contain elements that are not tensors or if x and y + contain elements that have a shape or dtype mismatch. + """ + # If the input and target used to call the model are not dataset tensors, + # we need to raise an error. When using a DistributionStrategy, the input + # and targets to a model should be from a `tf.data.Dataset`. + + # If each element of x and y are not tensors, we cannot standardize and + # validate the input and targets. + x_values_list = validate_per_replica_inputs(distribution_strategy, x) + + if y is not None: + y_values_list = validate_per_replica_inputs(distribution_strategy, y) + else: + y_values_list = None + + if sample_weights is not None: + sample_weights_list = validate_per_replica_inputs(distribution_strategy, + sample_weights) + else: + sample_weights_list = None + + # Return the unwrapped values to avoid calling `unwrap` a second time. + return x_values_list, y_values_list, sample_weights_list + + +def validate_per_replica_inputs(distribution_strategy, x): + """Validates PerReplica dataset input list. + + Args: + distribution_strategy: The current DistributionStrategy used to call + `fit`, `evaluate` and `predict`. + x: A list of PerReplica objects that represent the input or + target values. + + Returns: + List containing the first element of each of the PerReplica objects in + the input list. + + Raises: + ValueError: If any of the objects in the `per_replica_list` is not a tensor. + + """ + # Convert the inputs and targets into a list of PerReplica objects. + per_replica_list = nest.flatten(x, expand_composites=True) + x_values_list = [] + for x in per_replica_list: + # At this point x should contain only tensors. + x_values = distribution_strategy.unwrap(x) + for value in x_values: + if not tensor_util.is_tf_type(value): + raise ValueError('Dataset input to the model should be tensors instead ' + 'they are of type {}'.format(type(value))) + + if not context.executing_eagerly(): + # Validate that the shape and dtype of all the elements in x are the same. + validate_all_tensor_shapes(x, x_values) + validate_all_tensor_types(x, x_values) + + x_values_list.append(x_values[0]) + return x_values_list + + +def validate_all_tensor_types(x, x_values): + x_dtype = x_values[0].dtype + for i in range(1, len(x_values)): + if x_dtype != x_values[i].dtype: + raise ValueError('Input tensor dtypes do not match for distributed tensor' + ' inputs {}'.format(x)) + + +def validate_all_tensor_shapes(x, x_values): + # Validate that the shape of all the elements in x have the same shape + x_shape = x_values[0].shape.as_list() + for i in range(1, len(x_values)): + if x_shape != x_values[i].shape.as_list(): + raise ValueError('Input tensor shapes do not match for distributed tensor' + ' inputs {}'.format(x)) + + +def _wait_for_variable_initialization(session): + """Utility to wait for variables to be initialized.""" + all_variables = backend._get_variables(backend.get_graph()) # pylint: disable=protected-access + candidate_vars = [] + for v in all_variables: + if not getattr(v, '_keras_initialized', False): + candidate_vars.append(v) + + if not candidate_vars: + return + + while True: + is_initialized = session.run( + [variable_v1.is_variable_initialized(v) for v in candidate_vars]) + uninitialized_vars = [] + for flag, v in zip(is_initialized, candidate_vars): + if not flag: + uninitialized_vars.append(v) + v._keras_initialized = True # pylint: disable=protected-access + if not uninitialized_vars: + break + + +def init_restore_or_wait_for_variables(): + """Initialize or restore variables or wait for variables to be initialized.""" + backend._initialize_variables(backend._get_session()) # pylint: disable=protected-access + + +def validate_inputs(x, y): + """Validate inputs when using DistributionStrategy. + + Args: + x: Model Inputs. + y: Model Targets. + + Raises: + ValueError: if input is not a Dataset or a numpy array(when we use + MirroredStrategy). + """ + if (isinstance(x, iterator_ops.Iterator) or + isinstance(y, iterator_ops.Iterator)): + raise ValueError('`DistributionStrategy` does not support inputs of type ' + 'Iterator. You must pass a `tf.data.Dataset` object or a ' + 'numpy array as input.') + + +def is_dataset_shape_fully_defined(dataset): + """Returns whether a dataset contains a final partial batch.""" + shapes = nest.flatten(dataset_ops.get_legacy_output_shapes(dataset)) + unknown_shapes = [s for s in shapes if not s.is_fully_defined()] + return not unknown_shapes + + +def process_batch_and_step_size(strategy, + inputs, + batch_size, + steps_per_epoch, + mode, + validation_split=0.): + """Process the batch size and step size based on input and dist strategy.""" + first_x_value = nest.flatten(inputs)[0] + if isinstance(first_x_value, np.ndarray): + num_samples = first_x_value.shape[0] + if validation_split and 0. < validation_split < 1.: + num_samples = int(num_samples * (1 - validation_split)) + # Until support for partial batch is implemented across all + # functions and distribution strategy, we pass `mode` to selectively + # relax the constraint to consume all the training samples. + steps_per_epoch, batch_size = get_input_params( + strategy, num_samples, steps_per_epoch, batch_size, mode=mode) + return batch_size, steps_per_epoch + + +def get_input_params(distribution_strategy, + num_samples, + steps, + batch_size, + mode=None): + """Calculate the number of batches and steps/steps_per_epoch. + + Args: + distribution_strategy: The DistributionStrategy used to compile the model. + num_samples: The number of samples from which we determine the batch size + and steps. + steps: The specified number of steps. + batch_size: The specified batch_size. + mode: ModeKey representing whether input will be used for training, + evaluation, or prediction. This is used to relax the constraints on + consuming all the training samples to keep compatibility till we support + partial batches. If none, then partial batches are not allowed. + + Returns: + steps: The steps or steps_per_epoch argument depending on if a user is + calling `fit`, `evaluate` or `predict`. If the is_training flag is set + we don't require the number of samples to be used completely. + batch_size: The batch size to be used in model iterations. + + Raises: + ValueError: If the number of batches or steps evaluates to 0. + + """ + # TODO(b/118776054): Use global batch size for Keras/DS support. + # Currently this is only supported in TPUStrategy and CoreMirroredStrategy. + use_per_replica_batch = not dist_utils.global_batch_size_supported( + distribution_strategy) + + # TODO(b/128995245): In eager mode, uneven batch sizes are allowed except for + # `fit()` on TPUStrategy. + # In graph mode, the zero batch case in batch norm is not handled due to + # XLA-GPU regression. Uneven batch sizes are not allowed except + # for `test()` and `predict()` on TPUStrategy. + if context.executing_eagerly(): + allow_partial_batch = ( + mode != ModeKeys.TRAIN or + not backend.is_tpu_strategy(distribution_strategy)) + else: + allow_partial_batch = ( + mode == ModeKeys.TRAIN or + ((mode == ModeKeys.PREDICT or mode == ModeKeys.TEST) and + backend.is_tpu_strategy(distribution_strategy))) + + if steps is None: + if batch_size is None: + # If neither the batch size or number of steps are set. We choose the + # global batch size as the minimum of number of samples and 32. 32 is + # chosen to provide backward compatibility. + global_batch_size = min(num_samples, 32) + else: + # If the user provided the batch size we need to handle the case + # between different strategies that use the global/per-replica batch size + global_batch_size = batch_size + if use_per_replica_batch: + global_batch_size *= distribution_strategy.num_replicas_in_sync + if allow_partial_batch: + steps = np.ceil(num_samples / global_batch_size).astype(int) + else: + if num_samples % global_batch_size: + raise ValueError('The number of samples %s is not divisible by ' + 'batch size %s.' % (num_samples, global_batch_size)) + steps = num_samples // global_batch_size + else: + if batch_size is None: + # We calculate the batch size based on the number of steps specified + if num_samples % steps: + raise ValueError('The number of samples %s is not divisible by ' + 'steps %s. Please change the number of steps to a ' + 'value that can consume all the samples' % ( + num_samples, steps)) + global_batch_size = num_samples // steps + else: + # If the user provided the batch size we need to handle the case + # between different strategies that use the global/per-replica batch size + global_batch_size = batch_size + if use_per_replica_batch: + global_batch_size *= distribution_strategy.num_replicas_in_sync + + min_num_samples = global_batch_size * steps + if allow_partial_batch: + min_num_samples = global_batch_size * (steps-1) + 1 if steps > 1 else 0 + + if num_samples < min_num_samples: + raise ValueError('Number of samples %s is less than samples required ' + 'for specified batch_size %s and steps %s' % ( + num_samples, global_batch_size, steps)) + + # We need to return the per replica or global batch size based on the strategy + if use_per_replica_batch: + if global_batch_size % distribution_strategy.num_replicas_in_sync: + raise ValueError( + 'The batch size (%s) could not be sharded evenly across the sync ' + 'replicas (%s) in the distribution strategy.' % ( + global_batch_size, distribution_strategy.num_replicas_in_sync)) + batch_size = global_batch_size // distribution_strategy.num_replicas_in_sync + else: + batch_size = global_batch_size + + return steps, batch_size + + +def get_batch_dimension(iterator): + shapes = nest.flatten(dataset_ops.get_legacy_output_shapes(iterator)) + # Take the batch size from the first element, as it should be the same for + # all. + dims = shapes[0].dims + return dims[0] if dims else None + + +def get_iterator(dataset, distribution_strategy): + with distribution_strategy.scope(): + iterator = distribution_strategy.make_dataset_iterator(dataset) + initialize_iterator(iterator, distribution_strategy) + return iterator + + +def initialize_iterator(iterator, distribution_strategy): + with distribution_strategy.scope(): + init_op = control_flow_ops.group(iterator.initializer) + if not context.executing_eagerly(): + backend.get_session((init_op,)).run(init_op) + + +def _get_input_from_iterator(iterator, model): + """Get elements from the iterator and verify the input shape and type.""" + next_element = iterator.get_next() + + # `len(nest.flatten(x))` is going to not count empty elements such as {}. + # len(nest.flatten([[0,1,2], {}])) is 3 and not 4. The `next_element` is + # going to get flattened in `_prepare_feed_values` to work around that. Empty + # elements are going to get filtered out as part of the flattening. + if len(nest.flatten(next_element)) == len(model.inputs): + x = next_element + y = None + sample_weights = None + elif len(nest.flatten(next_element)) == (len(model.inputs) + + len(model.outputs)): + x, y = next_element + sample_weights = None + else: + x, y, sample_weights = next_element + + # Validate that all the elements in x and y are of the same type and shape. + validate_distributed_dataset_inputs( + model._distribution_strategy, x, y, sample_weights) + return x, y, sample_weights + + +def _prepare_feed_values(model, inputs, targets, sample_weights, mode): + """Prepare feed values to the model execution function. + + Args: + model: Model to prepare feed values for. + inputs: List or dict of model inputs. + targets: Optional list of model targets. + sample_weights: Optional list of sample weight arrays. + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + + Returns: + Feed values for the model in the given mode. + """ + strategy = model._distribution_strategy + inputs, targets, sample_weights = _get_input_from_iterator(inputs, model) + if backend.is_tpu_strategy(strategy): + if sample_weights is not None: + raise ValueError('TPUStrategy does not support sample weights.') + + # When the inputs are dict, then we want to flatten it in the same order as + # the input layers, such that the data are fed into the input layers in the + # correct order. + if isinstance(inputs, dict): + inputs = [inputs[key] for key in model._feed_input_names] + if is_distributing_by_cloning(model): + inputs = flatten_per_replica_values(strategy, inputs) + targets = flatten_per_replica_values(strategy, targets) + # Expand 1-dimensional inputs. + # TODO(b/124535720): Remove once this standarize data logic is shared with + # main flow. + inputs, targets = nest.map_structure( + training_utils_v1.standardize_single_array, (inputs, targets)) + else: + inputs = training_utils_v1.ModelInputs(inputs).as_list() + + if mode == ModeKeys.PREDICT: + sample_weights = [] + targets = [] + elif sample_weights is not None and is_distributing_by_cloning(model): + if context.executing_eagerly() and not model._compile_distribution: + raise NotImplementedError('`sample_weight` is not supported when using ' + 'tf.distribute.Strategy in eager mode and ' + 'cloning=True.') + sample_weights = flatten_per_replica_values(strategy, sample_weights) + + ins = [inputs, targets, sample_weights] + return tuple(ins) + + +def is_distributing_by_cloning(model): + """Decide whether this model is going to be distributed via cloning. + + We are going to distribute the model by cloning in graph mode. + + Args: + model: Keras model to distribute. + + Returns: + True if the `model` is going to be distributed using cloning and False + otherwise. + """ + if (backend.is_tpu_strategy(model._distribution_strategy) and + context.executing_eagerly): # b/137580852 + return False + elif ops.executing_eagerly_outside_functions(): + return bool(model._compile_distribution) + return True + + +def _custom_compile_for_predict(model): + """Custom compile for TPU predict mode.""" + if not model.built: + # Model is not compilable because it does not know its number of inputs + # and outputs, nor their shapes and names. We will compile after the first + # time the model gets called on training data. + return + model._is_compiled = True + model.total_loss = None + model.train_function = None + model.test_function = None + model.predict_function = None + + +def _build_network_on_replica(model, mode, inputs=None, targets=None): + """Build an updated model on replicas. + + We create a new Keras model while sharing the variables from the old graph. + Building a new sub-graph is required since the original keras model creates + placeholders for the input and the output that are not accessible till we + call iterator.get_next() inside the step_fn for `fit`/`evaluate`/`predict`. + + The sharing of weights and layers between the old and the new model guarantee + that we're using Strategy variables and any updates on either model are + reflected correctly in callbacks and loop iterations. + + We need to make sure we share the optimizers between the old and the new model + as well so that optimizer state is not lost if the user is running fit + multiple times. + + Args: + model: Model to be replicated across Replicas + mode: Which of fit/eval/predict is building the distributed network + inputs: Input variables to be passed to the model + targets: Target tensor to be passed to model.compile + + Returns: + A new model with shared layers with the old model. + """ + # Need to do imports here since we run into a circular dependency error. + from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top + from tensorflow.python.keras.engine import sequential # pylint: disable=g-import-not-at-top + + # We rely on the internal methods to avoid having share_weights weights in the + # public API. + if isinstance(model, sequential.Sequential): + updated_model = models._clone_sequential_model( + model, input_tensors=inputs, layer_fn=models.share_weights) + else: + updated_model = models._clone_functional_model( + model, input_tensors=inputs, layer_fn=models.share_weights) + # Callable losses added directly to a functional Model need to be added + # here. + updated_model._callable_losses = model._callable_losses + + # Recast all low precision outputs back to float32 since we only casted + # the inputs to bfloat16 and not targets. This is done so that we can preserve + # precision when calculating the loss value. + def _upcast_low_precision_outputs(output): + if output.dtype == dtypes.bfloat16: + return math_ops.cast(output, dtypes.float32) + else: + return output + updated_model.outputs = [_upcast_low_precision_outputs(o) + for o in updated_model.outputs] + + if isinstance(targets, tuple): + targets = nest.flatten(targets) + + if mode == ModeKeys.PREDICT and inputs is not None: # TPU predict case + _custom_compile_for_predict(updated_model) + else: + updated_model.compile( + model.optimizer, + model.loss, + metrics=metrics_module.clone_metrics(model._compile_metrics), + loss_weights=model.loss_weights, + sample_weight_mode=model.sample_weight_mode, + weighted_metrics=metrics_module.clone_metrics( + model._compile_weighted_metrics), + target_tensors=targets) + return updated_model + + +def _build_distributed_network(model, strategy, mode, inputs=None, + targets=None): + """Create a cloned model on each replica.""" + with backend.get_graph().as_default(), strategy.scope(): + distributed_model = strategy.extended.call_for_each_replica( + _build_network_on_replica, + args=(model, mode, inputs, targets)) + set_distributed_model(model, mode, distributed_model) + + +def _clone_and_build_model(model, mode, inputs=None, targets=None): + """Clone and build the given keras_model.""" + # We need to set the import here since we run into a circular dependency + # error. + from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top + cloned_model = models.clone_model(model, input_tensors=inputs) + + # Compile and build model. + if isinstance(model.optimizer, optimizers.TFOptimizer): + optimizer = model.optimizer + else: + optimizer_config = model.optimizer.get_config() + optimizer = model.optimizer.__class__.from_config(optimizer_config) + + # Recast all low precision outputs back to float32 since we only casted + # the inputs to bfloat16 and not targets. This is done so that we can preserve + # precision when calculating the loss value. + def _upcast_low_precision_outputs(output): + if output.dtype == dtypes.bfloat16: + return math_ops.cast(output, dtypes.float32) + else: + return output + cloned_model.outputs = [_upcast_low_precision_outputs(o) + for o in cloned_model.outputs] + + if isinstance(targets, tuple): + targets = nest.flatten(targets) + if mode == ModeKeys.PREDICT and inputs is not None: # TPU predict case + _custom_compile_for_predict(cloned_model) + else: + cloned_model.compile( + optimizer, + model.loss, + metrics=metrics_module.clone_metrics(model._compile_metrics), + loss_weights=model.loss_weights, + sample_weight_mode=model.sample_weight_mode, + weighted_metrics=metrics_module.clone_metrics( + model._compile_weighted_metrics), + target_tensors=targets) + return cloned_model + + +def clone_model_on_replicas(model, strategy, mode, inputs=None, targets=None): + """Create a cloned model on each replica.""" + with backend.get_graph().as_default(), strategy.scope(): + distributed_model = strategy.extended.call_for_each_replica( + _clone_and_build_model, args=(model, mode, inputs, targets)) + set_distributed_model(model, mode, distributed_model) + if mode == ModeKeys.TRAIN: + model._make_callback_model(distributed_model) + + +def _make_execution_function(model, mode): + """Makes or reuses function to run one step of distributed model execution.""" + if is_distributing_by_cloning(model): + return _make_execution_function_with_cloning(model, mode) + + distributed_function = get_distributed_function(model, mode) + if distributed_function: + return distributed_function + + distribution_function = _make_execution_function_without_cloning(model, mode) + set_distributed_function(model, mode, distribution_function) + return distribution_function + + +def _make_execution_function_without_cloning(model, mode): + """Creates a function to run one step of distributed model execution.""" + strategy = model._distribution_strategy + + with strategy.scope(): + per_replica_function = _make_replica_execution_function(model, mode) + + def distributed_function(input_fn): + """A single step of the distributed execution across replicas.""" + x, y, sample_weights = input_fn() + # Call `Model.{train,test,predict}_on_batch` on every replica passing + # PerReplicas as arguments. On every replica inside this call, each + # PerReplica object will return the value for that replica. The outputs + # are PerReplicas too. + outputs = strategy.run(per_replica_function, args=(x, y, sample_weights)) + # Out of PerReplica outputs reduce or pick values to return. + all_outputs = unwrap_outputs( + strategy, outputs, with_loss_tensor=(mode != ModeKeys.PREDICT)) + return all_outputs + + if not model.run_eagerly: + distributed_function = def_function.function(distributed_function) + def execution_function(input_fn): + # `numpy` translates Tensors to values in Eager mode. + return [out.numpy() for out in distributed_function(input_fn)] + else: + execution_function = distributed_function + + return execution_function + + +def _make_replica_execution_function(model, mode): + """A single step of the distributed execution on a replica.""" + if mode == ModeKeys.TRAIN: + func = model.train_on_batch + elif mode == ModeKeys.TEST: + func = model.test_on_batch + else: + + def predict_on_batch(x, y=None, sample_weights=None): + del y, sample_weights + return model.predict_on_batch(x) + + func = predict_on_batch + + if mode != ModeKeys.PREDICT: + # `reset_metrics` is set to False to maintain stateful metrics across + # batch-level calls. + func = functools.partial(func, reset_metrics=False) + + return func + + +def _make_replicated_models_with_cloning(model, mode): + """Build models on each replica.""" + strategy = model._distribution_strategy + + # If distributed_model is not built, create one for `mode`. + if model._compile_distribution: + clone_model_on_replicas(model, strategy, mode) + else: + _build_distributed_network(model, strategy, mode) + + +def _make_execution_function_with_cloning(model, mode): + """Clones or re-uses models to run one step of distributed model execution.""" + distributed_model = get_distributed_model(model, mode) + # TODO(b/134069401): Create a cache for the distributed model and exec + # function that incorporates additional attributes to be part of the cache key + # than just the mode. + # If distributed model for a particular `mode` is already built, use the + # `_distribution_function` on that distributed model. + # If you have updated the sample_weight_mode on the model, then you will need + # to recompile metrics and recreate the execution function. This is indicated + # by the `_recompile_exec_function` property. + if (distributed_model and hasattr(distributed_model, '_distribution_function') + and not (hasattr(distributed_model, '_recompile_exec_function') and + distributed_model._recompile_exec_function)): + return distributed_model._distributed_function + + if not distributed_model: + _make_replicated_models_with_cloning(model, mode) + distributed_model = get_distributed_model(model, mode) + assert distributed_model + + # Also create an execution function on that distributed model. + if context.executing_eagerly(): + distributed_function = _make_eager_execution_function(model, mode) + else: + distributed_function = _make_graph_execution_function(model, mode) + + # We cache the distributed execution function on the model since creating + # distributed models and execution functions are expensive. + distributed_model._distributed_function = distributed_function + distributed_model._recompile_exec_function = False + return distributed_function + + +def _make_graph_execution_function(model, mode): + """Makes function to run one step of distributed model in graph mode.""" + + def _per_replica_function(model): + f = model._make_execution_function(mode) + return (f.inputs, f.outputs, f.updates_op, f.session_kwargs) + + strategy = model._distribution_strategy + with strategy.scope(): + # Create train ops on each of the devices when we call + # `_per_replica_fit_function`. + (grouped_inputs, grouped_outputs, grouped_updates, + grouped_session_args) = strategy.extended.call_for_each_replica( + _per_replica_function, args=(get_distributed_model(model, mode),)) + + # Initialize the variables in the replicated model. This is necessary for + # multi-worker training because on some workers, initialization is not + # needed. This method does initialization or waiting for initialization + # according to the context object of distribute coordinator. + init_restore_or_wait_for_variables() + + # Unwrap all the per device values returned from `call_for_each_replica`. + # Unwrapping per device values gives you a list of values that can be + # used to construct a new train function that is composed of update ops on + # all the devices over which the model is distributed. + (all_inputs, all_outputs, all_updates, all_session_args) = unwrap_values( + strategy, + grouped_inputs, + grouped_outputs, + grouped_updates, + grouped_session_args, + with_loss_tensor=(mode != ModeKeys.PREDICT)) + + return backend.function( + all_inputs, + all_outputs, + updates=all_updates, + name='distributed_{}_function'.format(mode), + **all_session_args) + + +def _make_eager_execution_function(model, mode): + """Makes function to run one step of distributed model eager execution.""" + def _per_replica_function(model): + f = model._make_execution_function(mode) + return (f.inputs, f.outputs) + + # NOTE(priyag): Try creating a new FuncGraph within DS scope instead of using + # the global one. + strategy = model._distribution_strategy + global_graph = backend.get_graph() + + with global_graph.as_default(), strategy.scope(): + # First we gather the relevant portions of the model across all replicas. + # `backend._scratch_graph(global_graph)` signals to Keras that it should not + # lift to a separate graph when creating the per-replica functions. + with backend._scratch_graph(global_graph): + # Create train ops on each of the devices when we call + # `_per_replica_fit_function`. + grouped = strategy.extended.call_for_each_replica( + _per_replica_function, args=(get_distributed_model(model, mode),)) + grouped_inputs, grouped_outputs = grouped + + # Unwrap all the per device values returned from `call_for_each_replica`. + # Unwrapping per device values gives you a list of values that can be + # used to construct a new train function that is composed of + # inputs/outputs on all the devices over which the model is distributed. + (all_inputs, all_outputs, _, _) = unwrap_values( + strategy, + grouped_inputs, + grouped_outputs, + with_loss_tensor=(mode != ModeKeys.PREDICT)) + + # Finally, a joint Keras function is created; this one will be created in + # a separate FuncGraph. + return backend.function( + all_inputs, + all_outputs, + name='eager_distributed_{}_function'.format(mode)) + + +def _copy_weights_to_distributed_model(original_model, mode): + """Copies weights from original model to distributed models.""" + strategy = original_model._distribution_strategy + distributed_model = get_distributed_model(original_model, mode) + if strategy: + # Copy the weights from the original model to each of the replicated + # models. + orig_model_weights = original_model.get_weights() + first_model = strategy.unwrap(distributed_model)[0] + set_weights(strategy, first_model, orig_model_weights) + + +def _copy_weights_to_original_model(model, mode): + """Copies weights from first distributed model back to original model.""" + if model._distribution_strategy and mode == ModeKeys.TRAIN: + distributed_model = get_distributed_model(model, mode) + updated_weights = model._distribution_strategy.unwrap( + distributed_model)[0].get_weights() + model.set_weights(updated_weights) + + +def _per_replica_aggregate_batch(strategy, batch_outs, model, mode): + """Aggregates the per-replica batch-level outputs from a distributed step.""" + if strategy is not None and mode == ModeKeys.PREDICT: + total_batch_outs = [] + for i in range(len(model.outputs)): + num_replicas = strategy.num_replicas_in_sync + nested_outs = batch_outs[i * num_replicas:i * num_replicas + num_replicas] + total_batch_outs.append( + concat_along_batch_dimension(nest.flatten(nested_outs))) + return total_batch_outs + return batch_outs + + +def _reset_metrics(model): + if model._distribution_strategy: + for mode in [ModeKeys.TRAIN, ModeKeys.TEST, ModeKeys.PREDICT]: + distributed_model = get_distributed_model(model, mode) + if distributed_model: + first_model = model._distribution_strategy.unwrap(distributed_model)[0] + first_model.reset_metrics() + + +def get_distributed_model(model, mode): + key = _generate_cache_key(mode) + return model._distributed_model_cache.get(key, None) + + +def set_distributed_model(model, mode, distributed_model): + key = _generate_cache_key(mode) + model._distributed_model_cache[key] = distributed_model + + +def get_distributed_function(model, mode): + key = _generate_cache_key(mode) + return model._distributed_function_cache.get(key, None) + + +def set_distributed_function(model, mode, distributed_function): + key = _generate_cache_key(mode) + model._distributed_function_cache[key] = distributed_function + + +def _generate_cache_key(mode): + key = hash(mode) + return key + + +@tf_contextlib.contextmanager +def distributed_scope(strategy, learning_phase): + with strategy.scope(), backend.learning_phase_scope(learning_phase): + yield + + +def is_current_worker_chief(): + return dc.get_current_worker_context().is_chief + + +def filter_distributed_callbacks(callbacks_list, model): + """Filter Callbacks based on the worker context when running multi-worker. + + Args: + callbacks_list: A list of `Callback` instances. + model: Keras model instance. + + Returns: + The list of `Callback` instances that should be run on this worker. + """ + + if not model._in_multi_worker_mode(): + raise ValueError( + 'filter_distributed_callbacks() should only be called when Keras ' + 'is in multi worker mode.') + + callbacks_list = callbacks_list or [] + if not [ + c for c in callbacks_list if isinstance(c, callbacks.ModelCheckpoint) + ]: + # TODO(rchao): Consider providing a ModelCheckpoint here if the user + # fails to (possibly with tempfile directory). + logging.warning('ModelCheckpoint callback is not provided. ' + 'Workers will need to restart training if any fails.') + + if callbacks_list is None or is_current_worker_chief(): + return callbacks_list + + # Some Callbacks should only run on the chief worker. + return [ + callback for callback in callbacks_list if not callback._chief_worker_only + ] # pylint: disable=protected-access + + +def _update_sample_weight_modes(model, mode, sample_weights): + """Update sample_weight_mode of the distributed model.""" + if is_distributing_by_cloning(model): + distributed_model = get_distributed_model(model, mode) + if not distributed_model: + _make_replicated_models_with_cloning(model, mode) + distributed_model = get_distributed_model(model, mode) + distributed_model._recompile_exec_function = any( + [e.sample_weights_mismatch() for e in model._training_endpoints]) + + if sample_weights: + distributed_models = flatten_per_replica_values( + model._distribution_strategy, distributed_model) + # sample_weights is a tuple of 1 list where the number of elements in the + # list is equal to the number of replicas in sync. + sample_weights = sample_weights[0] + if sample_weights and None not in sample_weights: + for m, sw in zip(distributed_models, sample_weights): + m._update_sample_weight_modes(sample_weights=[sw]) + + +def concat_along_batch_dimension(outputs): + """Concats prediction outputs along the batch dimension.""" + if isinstance(outputs[0], sparse_tensor.SparseTensor): + return sparse_ops.sparse_concat_v2(axis=0, sp_inputs=outputs) + if isinstance(outputs[0], ragged_tensor.RaggedTensor): + return array_ops.concat(outputs, axis=0) + return np.concatenate(outputs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/worker_training_state.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/worker_training_state.py new file mode 100644 index 0000000000000000000000000000000000000000..2064ad057b01dd4d20181c387a2ac76c817f61df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/distribute/worker_training_state.py @@ -0,0 +1,143 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training state management.""" + +import os +from tensorflow.python.checkpoint import checkpoint as trackable_util +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.keras import backend +from tensorflow.python.keras.distribute import distributed_file_utils +from tensorflow.python.keras.utils import mode_keys +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables + +# Constant for `tf.keras.Model` attribute to store the epoch at which the most +# recently saved checkpoint was saved. +CKPT_SAVED_EPOCH = '_ckpt_saved_epoch' + +CKPT_SAVED_EPOCH_UNUSED_VALUE = -1 + + +class WorkerTrainingState(object): + """Training state management class. + + This class provides apis for backing up and restoring the training state. + This allows model and epoch information to be saved periodically and restore + for fault-tolerance, also known as preemption-recovery purpose. + """ + + def __init__(self, model, checkpoint_dir): + self._model = model + + # The epoch at which the checkpoint is saved. Used for fault-tolerance. + # GPU device only has int64 dtype registered VarHandleOp. + self._ckpt_saved_epoch = variables.Variable( + initial_value=constant_op.constant( + CKPT_SAVED_EPOCH_UNUSED_VALUE, dtype=dtypes.int64), + name='ckpt_saved_epoch') + + # Variable initialization. + backend.set_value(self._ckpt_saved_epoch, CKPT_SAVED_EPOCH_UNUSED_VALUE) + + # _ckpt_saved_epoch gets tracked and is included in the checkpoint file + # when backing up. + checkpoint = trackable_util.Checkpoint( + model=self._model, ckpt_saved_epoch=self._ckpt_saved_epoch) + + # If this is single-worker training, checkpoint_dir are the same for + # write_checkpoint_manager and read_checkpoint_manager. + # + # If this is multi-worker training, and this worker should not + # save checkpoint, we replace the write_checkpoint_manager's checkpoint_dir + # with a temp filepath, so it writes to a file that will be removed at the + # end of back_up() call. This is necessary because the SyncOnReadVariable + # needs to be synced across all the workers in order to be read, and all + # workers need to perform `save()`. + # But all workers should restore from the same checkpoint_dir as passed in + # read_checkpoint_manager. + self.read_checkpoint_manager = checkpoint_management.CheckpointManager( + checkpoint, + directory=os.path.join(checkpoint_dir, 'chief'), + max_to_keep=1) + write_checkpoint_dir = distributed_file_utils.write_dirpath( + checkpoint_dir, self._model.distribute_strategy) + if self._model.distribute_strategy.extended.should_checkpoint: + self.write_checkpoint_manager = self.read_checkpoint_manager + else: + self.write_checkpoint_manager = checkpoint_management.CheckpointManager( + checkpoint, directory=write_checkpoint_dir, max_to_keep=1) + + def back_up(self, epoch): + """Back up the current state of training into a checkpoint file. + + Args: + epoch: The current epoch information to be saved. + """ + backend.set_value(self._ckpt_saved_epoch, epoch) + # Save the model plus CKPT_SAVED_EPOCH variable. + if self.write_checkpoint_manager.save(): + distributed_file_utils.remove_temp_dirpath( + self.write_checkpoint_manager.directory, + self._model.distribute_strategy) + + def restore(self): + """Restore the training state from the backed up checkpoint file. + + Returns: + True if the training state is successfully restored. False if the training + state doesn't need to be restored, or error occurred so it can't. + """ + self.read_checkpoint_manager.restore_or_initialize() + + def delete_backup(self): + """Delete the backup directories. + + Delete the backup directories which should not exist after `fit()` + successfully finishes. + """ + if self.write_checkpoint_manager is self.read_checkpoint_manager: + try: + file_io.delete_recursively_v2(self.write_checkpoint_manager.directory) + except errors.NotFoundError: + pass + + def maybe_load_initial_epoch_from_ckpt(self, initial_epoch, mode): + """Maybe load initial epoch from ckpt considering possible worker recovery. + + When `_ckpt_saved_epoch` attribute exists and is not + `CKPT_SAVED_EPOCH_UNUSED_VALUE`, this is under multi-worker training setting + and indicates the worker is recovering from previous failure. In this case, + infer `initial_epoch` from `self._ckpt_saved_epoch` to continue previous + unfinished training from certain epoch. + + Args: + initial_epoch: The original initial_epoch user passes in in `fit()`. + mode: The mode for running `model.fit()`. + + Returns: + If the training is recovering from previous failure under multi-worker + training setting, return the epoch the training is supposed to continue + at. Otherwise, return the `initial_epoch` the user passes in. + """ + + epoch = backend.eval(self._ckpt_saved_epoch) + if mode == mode_keys.ModeKeys.TRAIN and epoch >= 0: + # The most recently saved epoch is one epoch prior to the epoch it + # failed at, so return the value of 'self._ckpt_saved_epoch' plus one. + return epoch + 1 + return initial_epoch diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f5cbfdf92e0a0997a6117c35d92f01256c7d4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer.py @@ -0,0 +1,3271 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Contains the base Layer class, from which all layers inherit.""" + +import collections +import copy +import functools +import itertools +import threading +import warnings +import weakref + +import numpy as np + +from google.protobuf import json_format +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python import tf2 +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.engine import node as node_module +from tensorflow.python.keras.mixed_precision import autocast_variable +from tensorflow.python.keras.mixed_precision import loss_scale_optimizer +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import object_identity +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.generic_utils import to_snake_case # pylint: disable=unused-import +from tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list # pylint: disable=unused-import +from tensorflow.python.module import module +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.numpy_ops import np_arrays +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import get_canonical_name_for_symbol +from tensorflow.tools.docs import doc_controls + +# A module that only depends on `keras.layers` import these from here. + +# pylint: disable=g-inconsistent-quotes +metrics_mod = generic_utils.LazyLoader( + "metrics_mod", globals(), + "tensorflow.python.keras.metrics") +# pylint: enable=g-inconsistent-quotes + +# Prefix that is added to the TF op layer names. +_TF_OP_LAYER_NAME_PREFIX = 'tf_op_layer_' + +# TODO(mdan): Should we have a single generic type for types that can be passed +# to tf.cast? +_AUTOCAST_TYPES = (tensor_lib.Tensor, sparse_tensor.SparseTensor, + ragged_tensor.RaggedTensor) + + +class Layer(module.Module, version_utils.LayerVersionSelector): + """This is the class from which all layers inherit. + + A layer is a callable object that takes as input one or more tensors and + that outputs one or more tensors. It involves *computation*, defined + in the `call()` method, and a *state* (weight variables), defined + either in the constructor `__init__()` or in the `build()` method. + + Users will just instantiate a layer and then treat it as a callable. + + Args: + trainable: Boolean, whether the layer's variables should be trainable. + name: String name of the layer. + dtype: The dtype of the layer's computations and weights. Can also be a + `tf.keras.mixed_precision.Policy`, which allows the computation and weight + dtype to differ. Default of `None` means to use + `tf.keras.mixed_precision.global_policy()`, which is a float32 policy + unless set to different value. + dynamic: Set this to `True` if your layer should only be run eagerly, and + should not be used to generate a static computation graph. + This would be the case for a Tree-RNN or a recursive network, + for example, or generally for any layer that manipulates tensors + using Python control flow. If `False`, we assume that the layer can + safely be used to generate a static computation graph. + + Attributes: + name: The name of the layer (string). + dtype: The dtype of the layer's weights. + variable_dtype: Alias of `dtype`. + compute_dtype: The dtype of the layer's computations. Layers automatically + cast inputs to this dtype which causes the computations and output to also + be in this dtype. When mixed precision is used with a + `tf.keras.mixed_precision.Policy`, this will be different than + `variable_dtype`. + dtype_policy: The layer's dtype policy. See the + `tf.keras.mixed_precision.Policy` documentation for details. + trainable_weights: List of variables to be included in backprop. + non_trainable_weights: List of variables that should not be + included in backprop. + weights: The concatenation of the lists trainable_weights and + non_trainable_weights (in this order). + trainable: Whether the layer should be trained (boolean), i.e. whether + its potentially-trainable weights should be returned as part of + `layer.trainable_weights`. + input_spec: Optional (list of) `InputSpec` object(s) specifying the + constraints on inputs that can be accepted by the layer. + + We recommend that descendants of `Layer` implement the following methods: + + * `__init__()`: Defines custom layer attributes, and creates layer state + variables that do not depend on input shapes, using `add_weight()`. + * `build(self, input_shape)`: This method can be used to create weights that + depend on the shape(s) of the input(s), using `add_weight()`. `__call__()` + will automatically build the layer (if it has not been built yet) by + calling `build()`. + * `call(self, inputs, *args, **kwargs)`: Called in `__call__` after making + sure `build()` has been called. `call()` performs the logic of applying the + layer to the input tensors (which should be passed in as argument). + Two reserved keyword arguments you can optionally use in `call()` are: + - `training` (boolean, whether the call is in inference mode or training + mode). See more details in [the layer/model subclassing guide]( + https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_training_argument_in_the_call_method) + - `mask` (boolean tensor encoding masked timesteps in the input, used + in RNN layers). See more details in [the layer/model subclassing guide]( + https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_mask_argument_in_the_call_method) + A typical signature for this method is `call(self, inputs)`, and user could + optionally add `training` and `mask` if the layer need them. `*args` and + `**kwargs` is only useful for future extension when more input parameters + are planned to be added. + * `get_config(self)`: Returns a dictionary containing the configuration used + to initialize this layer. If the keys differ from the arguments + in `__init__`, then override `from_config(self)` as well. + This method is used when saving + the layer or a model that contains this layer. + + Examples: + + Here's a basic example: a layer with two variables, `w` and `b`, + that returns `y = w . x + b`. + It shows how to implement `build()` and `call()`. + Variables set as attributes of a layer are tracked as weights + of the layers (in `layer.weights`). + + ```python + class SimpleDense(Layer): + + def __init__(self, units=32): + super(SimpleDense, self).__init__() + self.units = units + + def build(self, input_shape): # Create the state of the layer (weights) + w_init = tf.random_normal_initializer() + self.w = tf.Variable( + initial_value=w_init(shape=(input_shape[-1], self.units), + dtype='float32'), + trainable=True) + b_init = tf.zeros_initializer() + self.b = tf.Variable( + initial_value=b_init(shape=(self.units,), dtype='float32'), + trainable=True) + + def call(self, inputs): # Defines the computation from inputs to outputs + return tf.matmul(inputs, self.w) + self.b + + # Instantiates the layer. + linear_layer = SimpleDense(4) + + # This will also call `build(input_shape)` and create the weights. + y = linear_layer(tf.ones((2, 2))) + assert len(linear_layer.weights) == 2 + + # These weights are trainable, so they're listed in `trainable_weights`: + assert len(linear_layer.trainable_weights) == 2 + ``` + + Note that the method `add_weight()` offers a shortcut to create weights: + + ```python + class SimpleDense(Layer): + + def __init__(self, units=32): + super(SimpleDense, self).__init__() + self.units = units + + def build(self, input_shape): + self.w = self.add_weight(shape=(input_shape[-1], self.units), + initializer='random_normal', + trainable=True) + self.b = self.add_weight(shape=(self.units,), + initializer='random_normal', + trainable=True) + + def call(self, inputs): + return tf.matmul(inputs, self.w) + self.b + ``` + + Besides trainable weights, updated via backpropagation during training, + layers can also have non-trainable weights. These weights are meant to + be updated manually during `call()`. Here's a example layer that computes + the running sum of its inputs: + + ```python + class ComputeSum(Layer): + + def __init__(self, input_dim): + super(ComputeSum, self).__init__() + # Create a non-trainable weight. + self.total = tf.Variable(initial_value=tf.zeros((input_dim,)), + trainable=False) + + def call(self, inputs): + self.total.assign_add(tf.reduce_sum(inputs, axis=0)) + return self.total + + my_sum = ComputeSum(2) + x = tf.ones((2, 2)) + + y = my_sum(x) + print(y.numpy()) # [2. 2.] + + y = my_sum(x) + print(y.numpy()) # [4. 4.] + + assert my_sum.weights == [my_sum.total] + assert my_sum.non_trainable_weights == [my_sum.total] + assert my_sum.trainable_weights == [] + ``` + + For more information about creating layers, see the guide + [Making new Layers and Models via subclassing]( + https://www.tensorflow.org/guide/keras/custom_layers_and_models) + """ + + # See tf.Module for the usage of this property. + # The key for _obj_reference_counts_dict is a Trackable, which could be a + # variable or layer etc. tf.Module._flatten will fail to flatten the key + # since it is trying to convert Trackable to a string. This attribute can be + # ignored even after the fix of nest lib, since the trackable object should + # already been available as individual attributes. _obj_reference_counts_dict + # just contains a copy of them. + _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain( + ('_obj_reference_counts_dict',), + module.Module._TF_MODULE_IGNORED_PROPERTIES + )) + + # When loading from a SavedModel, Layers typically can be revived into a + # generic Layer wrapper. Sometimes, however, layers may implement methods + # that go beyond this wrapper, as in the case of PreprocessingLayers' + # `adapt` method. When this is the case, layer implementers can override + # must_restore_from_config to return True; layers with this property must + # be restored into their actual objects (and will fail if the object is + # not available to the restoration code). + _must_restore_from_config = False + + def _get_cell_name(self): + canonical_name = get_canonical_name_for_symbol( + self.__class__, api_name='keras', add_prefix_to_v1_names=True) + if canonical_name is not None: + return 'tf.{}'.format(canonical_name) + return self.__class__.__module__ + '.' + self.__class__.__name__ + + def _instrument_layer_creation(self): + self._instrumented_keras_api = False + self._instrumented_keras_layer_class = False + self._instrumented_keras_model_class = False + if not getattr(self, '_disable_keras_instrumentation', False): + self._instrumented_keras_api = True + if getattr(self, '_is_model_for_instrumentation', False): + self._instrumented_keras_model_class = True + else: + self._instrumented_keras_layer_class = True + + @trackable.no_automatic_dependency_tracking + def __init__(self, + trainable=True, + name=None, + dtype=None, + dynamic=False, + **kwargs): + self._instrument_layer_creation() + + # These properties should be set by the user via keyword arguments. + # note that 'dtype', 'input_shape' and 'batch_input_shape' + # are only applicable to input layers: do not pass these keywords + # to non-input layers. + allowed_kwargs = { + 'input_dim', + 'input_shape', + 'batch_input_shape', + 'batch_size', + 'weights', + 'activity_regularizer', + 'autocast', + 'implementation', + } + # Validate optional keyword arguments. + generic_utils.validate_kwargs(kwargs, allowed_kwargs) + + # Mutable properties + # Indicates whether the layer's weights are updated during training + # and whether the layer's updates are run during training. + self._trainable = trainable + # A stateful layer is a layer whose updates are run during inference too, + # for instance stateful RNNs. + self._stateful = False + # Indicates whether `build` needs to be called upon layer call, to create + # the layer's weights. + self.built = False + # Provides information about which inputs are compatible with the layer. + self._input_spec = None + + # SavedModel-related attributes. + # Record the build input shape for loading purposes. + # TODO(kathywu): Move this to Layer._set_save_spec once cl/290121460 is + # submitted. + self._build_input_shape = None + self._saved_model_inputs_spec = None + + # `Layer.compute_mask` will be called at the end of `Layer.__call__` if + # `Layer.compute_mask` is overridden, or if the `Layer` subclass sets + # `self.supports_masking=True`. + self._supports_masking = not generic_utils.is_default(self.compute_mask) + + self._init_set_name(name) + self._activity_regularizer = regularizers.get( + kwargs.pop('activity_regularizer', None)) + self._maybe_create_attribute('_trainable_weights', []) + self._maybe_create_attribute('_non_trainable_weights', []) + self._updates = [] + # Object to store all thread local layer properties. + self._thread_local = threading.local() + # A list of zero-argument lambdas which return Tensors, used for variable + # regularizers. + self._callable_losses = [] + # A list of symbolic Tensors containing activity regularizers and losses + # manually added through `add_loss` in graph-building mode. + self._losses = [] + # A list of metric instances corresponding to the symbolic metric tensors + # added using the `add_metric` API. + self._metrics = [] + # Ensures the same metric is not added multiple times in `MirroredStrategy`. + self._metrics_lock = threading.Lock() + + # Both graph and subclassed networks have a dtype policy. For graph + # networks, the policy's compute and variable dtypes are ignored. Such + # networks only use the policy if it is a PolicyV1, in which case it uses + # the PolicyV1's loss_scale (Policy does not have a loss_scale). For + # subclassed networks, the compute and variable dtypes are used as like any + # ordinary layer. + self._set_dtype_policy(dtype) + # Boolean indicating whether the layer automatically casts its inputs to the + # layer's compute_dtype. + self._autocast = kwargs.get('autocast', + base_layer_utils.v2_dtype_behavior_enabled()) + + # Tracks `TrackableDataStructure`s, `Module`s, and `Layer`s. + # Ordered by when the object was assigned as an attr. + # Entries are unique. + self._maybe_create_attribute('_self_tracked_trackables', []) + + # These lists will be filled via successive calls + # to self._add_inbound_node(). + # Used in symbolic mode only, only in conjunction with graph-networks + self._inbound_nodes_value = [] + self._outbound_nodes_value = [] + + self._init_call_fn_args() + + # Whether the `call` method can be used to build a TF graph without issues. + # This attribute has no effect if the model is created using the Functional + # API. Instead, `model.dynamic` is determined based on the internal layers. + self._dynamic = dynamic + + # Manage input shape information if passed. + if 'input_dim' in kwargs and 'input_shape' not in kwargs: + # Backwards compatibility: alias 'input_dim' to 'input_shape'. + kwargs['input_shape'] = (kwargs['input_dim'],) + if 'input_shape' in kwargs or 'batch_input_shape' in kwargs: + # In this case we will later create an input layer + # to insert before the current layer + if 'batch_input_shape' in kwargs: + batch_input_shape = tuple(kwargs['batch_input_shape']) + elif 'input_shape' in kwargs: + if 'batch_size' in kwargs: + batch_size = kwargs['batch_size'] + else: + batch_size = None + batch_input_shape = (batch_size,) + tuple(kwargs['input_shape']) + self._batch_input_shape = batch_input_shape + + # Manage initial weight values if passed. + self._initial_weights = kwargs.get('weights', None) + + # Whether the layer will track any layers that is set as attribute on itself + # as sub-layers, the weights from the sub-layers will be included in the + # parent layer's variables() as well. + # Default to True, which means auto tracking is turned on. Certain subclass + # might want to turn it off, like Sequential model. + self._auto_track_sub_layers = True + + # For backwards compat reasons, most built-in layers do not guarantee + # That they will 100% preserve the structure of input args when saving + # / loading configs. E.g. they may un-nest an arg that is + # a list with one element. + self._preserve_input_structure_in_config = False + + @trackable.no_automatic_dependency_tracking + @generic_utils.default + def build(self, input_shape): + """Creates the variables of the layer (optional, for subclass implementers). + + This is a method that implementers of subclasses of `Layer` or `Model` + can override if they need a state-creation step in-between + layer instantiation and layer call. + + This is typically used to create the weights of `Layer` subclasses. + + Args: + input_shape: Instance of `TensorShape`, or list of instances of + `TensorShape` if the layer expects a list of inputs + (one instance per input). + """ + # Only record the build input shapes of overridden build methods. + if not hasattr(self.build, '_is_default'): + self._build_input_shape = input_shape + self.built = True + + @doc_controls.for_subclass_implementers + def call(self, inputs, *args, **kwargs): # pylint: disable=unused-argument + """This is where the layer's logic lives. + + Note here that `call()` method in `tf.keras` is little bit different + from `keras` API. In `keras` API, you can pass support masking for + layers as additional arguments. Whereas `tf.keras` has `compute_mask()` + method to support masking. + + Args: + inputs: Input tensor, or dict/list/tuple of input tensors. + The first positional `inputs` argument is subject to special rules: + - `inputs` must be explicitly passed. A layer cannot have zero + arguments, and `inputs` cannot be provided via the default value + of a keyword argument. + - NumPy array or Python scalar values in `inputs` get cast as tensors. + - Keras mask metadata is only collected from `inputs`. + - Layers are built (`build(input_shape)` method) + using shape info from `inputs` only. + - `input_spec` compatibility is only checked against `inputs`. + - Mixed precision input casting is only applied to `inputs`. + If a layer has tensor arguments in `*args` or `**kwargs`, their + casting behavior in mixed precision should be handled manually. + - The SavedModel input specification is generated using `inputs` only. + - Integration with various ecosystem packages like TFMOT, TFLite, + TF.js, etc is only supported for `inputs` and not for tensors in + positional and keyword arguments. + *args: Additional positional arguments. May contain tensors, although + this is not recommended, for the reasons above. + **kwargs: Additional keyword arguments. May contain tensors, although + this is not recommended, for the reasons above. + The following optional keyword arguments are reserved: + - `training`: Boolean scalar tensor of Python boolean indicating + whether the `call` is meant for training or inference. + - `mask`: Boolean input mask. If the layer's `call()` method takes a + `mask` argument, its default value will be set to the mask generated + for `inputs` by the previous layer (if `input` did come from a layer + that generated a corresponding mask, i.e. if it came from a Keras + layer with masking support). + + Returns: + A tensor or list/tuple of tensors. + """ + return inputs + + @doc_controls.for_subclass_implementers + def _add_trackable(self, trackable_object, trainable): + """Adds a Trackable object to this layer's state. + + Args: + trackable_object: The tf.tracking.Trackable object to add. + trainable: Boolean, whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) or + "non_trainable_variables" (e.g. BatchNorm mean and variance). + + Returns: + The TrackableWeightHandler used to track this object. + """ + if isinstance(trackable_object, base_layer_utils.TrackableWeightHandler): + handler = trackable_object + else: + handler = base_layer_utils.TrackableWeightHandler(trackable_object) + if trainable: + self._trainable_weights.append(handler) + else: + self._non_trainable_weights.append(handler) + return handler + + @doc_controls.for_subclass_implementers + def add_weight(self, + name=None, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=None, + constraint=None, + use_resource=None, + synchronization=tf_variables.VariableSynchronization.AUTO, + aggregation=tf_variables.VariableAggregation.NONE, + **kwargs): + """Adds a new variable to the layer. + + Args: + name: Variable name. + shape: Variable shape. Defaults to scalar if unspecified. + dtype: The type of the variable. Defaults to `self.dtype`. + initializer: Initializer instance (callable). + regularizer: Regularizer instance (callable). + trainable: Boolean, whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) + or "non_trainable_variables" (e.g. BatchNorm mean and variance). + Note that `trainable` cannot be `True` if `synchronization` + is set to `ON_READ`. + constraint: Constraint instance (callable). + use_resource: Whether to use `ResourceVariable`. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. If `synchronization` is set to `ON_READ`, + `trainable` must not be set to `True`. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + **kwargs: Additional keyword arguments. Accepted values are `getter`, + `collections`, `experimental_autocast` and `caching_device`. + + Returns: + The variable created. + + Raises: + ValueError: When giving unsupported dtype and no initializer or when + trainable has been set to True with synchronization set as `ON_READ`. + """ + if shape is None: + shape = () + kwargs.pop('partitioner', None) # Ignored. + # Validate optional keyword arguments. + for kwarg in kwargs: + if kwarg not in ['collections', 'experimental_autocast', + 'caching_device', 'getter']: + raise TypeError('Unknown keyword argument:', kwarg) + collections_arg = kwargs.pop('collections', None) + # 'experimental_autocast' can be set to False by the caller to indicate an + # AutoCastVariable should never be created. + autocast = kwargs.pop('experimental_autocast', True) + # See the docstring for tf.Variable about the details for caching_device. + caching_device = kwargs.pop('caching_device', None) + + if dtype is None: + dtype = self.dtype or backend.floatx() + dtype = dtypes.as_dtype(dtype) + if self._dtype_policy.variable_dtype is None: + # The policy is "_infer", so we infer the policy from the variable dtype. + self._set_dtype_policy(policy.Policy(dtype.base_dtype.name)) + initializer = initializers.get(initializer) + regularizer = regularizers.get(regularizer) + constraint = constraints.get(constraint) + + if synchronization == tf_variables.VariableSynchronization.ON_READ: + if trainable: + raise ValueError( + 'Synchronization value can be set to ' + 'VariableSynchronization.ON_READ only for non-trainable variables. ' + 'You have specified trainable=True and ' + 'synchronization=VariableSynchronization.ON_READ.') + else: + # Set trainable to be false when variable is to be synced on read. + trainable = False + elif trainable is None: + trainable = True + + # Initialize variable when no initializer provided + if initializer is None: + # If dtype is DT_FLOAT, provide a uniform unit scaling initializer + if dtype.is_floating: + initializer = initializers.get('glorot_uniform') + # If dtype is DT_INT/DT_UINT, provide a default value `zero` + # If dtype is DT_BOOL, provide a default value `FALSE` + elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool: + initializer = initializers.get('zeros') + # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? + elif 'getter' not in kwargs: + # When `getter` is specified, it's possibly fine for `initializer` to be + # None since it's up to the custom `getter` to raise error in case it + # indeed needs `initializer`. + raise ValueError('An initializer for variable %s of type %s is required' + ' for layer %s' % (name, dtype.base_dtype, self.name)) + + getter = kwargs.pop('getter', base_layer_utils.make_variable) + if (autocast and + self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype + and dtype.is_floating): + old_getter = getter + # Wrap variable constructor to return an AutoCastVariable. + def getter(*args, **kwargs): # pylint: disable=function-redefined + variable = old_getter(*args, **kwargs) + return autocast_variable.create_autocast_variable(variable) + # Also the caching_device does not work with the mixed precision API, + # disable it if it is specified. + # TODO(b/142020079): Reenable it once the bug is fixed. + if caching_device is not None: + tf_logging.warning( + '`caching_device` does not work with mixed precision API. Ignoring ' + 'user specified `caching_device`.') + caching_device = None + + variable = self._add_variable_with_custom_getter( + name=name, + shape=shape, + # TODO(allenl): a `make_variable` equivalent should be added as a + # `Trackable` method. + getter=getter, + # Manage errors in Layer rather than Trackable. + overwrite=True, + initializer=initializer, + dtype=dtype, + constraint=constraint, + trainable=trainable, + use_resource=use_resource, + collections=collections_arg, + synchronization=synchronization, + aggregation=aggregation, + caching_device=caching_device) + if regularizer is not None: + # TODO(fchollet): in the future, this should be handled at the + # level of variable creation, and weight regularization losses + # should be variable attributes. + name_in_scope = variable.name[:variable.name.find(':')] + self._handle_weight_regularization(name_in_scope, + variable, + regularizer) + if base_layer_utils.is_split_variable(variable): + for v in variable: + backend.track_variable(v) + if trainable: + self._trainable_weights.append(v) + else: + self._non_trainable_weights.append(v) + else: + backend.track_variable(variable) + if trainable: + self._trainable_weights.append(variable) + else: + self._non_trainable_weights.append(variable) + return variable + + @generic_utils.default + def get_config(self): + """Returns the config of the layer. + + A layer config is a Python dictionary (serializable) + containing the configuration of a layer. + The same layer can be reinstantiated later + (without its trained weights) from this configuration. + + The config of a layer does not include connectivity + information, nor the layer class name. These are handled + by `Network` (one layer of abstraction above). + + Note that `get_config()` does not guarantee to return a fresh copy of dict + every time it is called. The callers should make a copy of the returned dict + if they want to modify it. + + Returns: + Python dictionary. + """ + all_args = tf_inspect.getfullargspec(self.__init__).args + config = { + 'name': self.name, + 'trainable': self.trainable, + } + if hasattr(self, '_batch_input_shape'): + config['batch_input_shape'] = self._batch_input_shape + config['dtype'] = policy.serialize(self._dtype_policy) + if hasattr(self, 'dynamic'): + # Only include `dynamic` in the `config` if it is `True` + if self.dynamic: + config['dynamic'] = self.dynamic + elif 'dynamic' in all_args: + all_args.remove('dynamic') + expected_args = config.keys() + # Finds all arguments in the `__init__` that are not in the config: + extra_args = [arg for arg in all_args if arg not in expected_args] + # Check that either the only argument in the `__init__` is `self`, + # or that `get_config` has been overridden: + if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'): + raise NotImplementedError('Layer %s has arguments in `__init__` and ' + 'therefore must override `get_config`.' % + self.__class__.__name__) + return config + + @classmethod + def from_config(cls, config): + """Creates a layer from its config. + + This method is the reverse of `get_config`, + capable of instantiating the same layer from the config + dictionary. It does not handle layer connectivity + (handled by Network), nor weights (handled by `set_weights`). + + Args: + config: A Python dictionary, typically the + output of get_config. + + Returns: + A layer instance. + """ + return cls(**config) + + def compute_output_shape(self, input_shape): + """Computes the output shape of the layer. + + If the layer has not been built, this method will call `build` on the + layer. This assumes that the layer will later be used with inputs that + match the input shape provided here. + + Args: + input_shape: Shape tuple (tuple of integers) + or list of shape tuples (one per output tensor of the layer). + Shape tuples can include None for free dimensions, + instead of an integer. + + Returns: + An input shape tuple. + """ + if context.executing_eagerly(): + # In this case we build the model first in order to do shape inference. + # This is acceptable because the framework only calls + # `compute_output_shape` on shape values that the layer would later be + # built for. It would however cause issues in case a user attempts to + # use `compute_output_shape` manually with shapes that are incompatible + # with the shape the Layer will be called on (these users will have to + # implement `compute_output_shape` themselves). + self._maybe_build(input_shape) + with func_graph.FuncGraph(str(self.name) + '_scratch_graph').as_default(): + input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) + def _make_placeholder_like(shape): + ph = backend.placeholder(shape=shape, dtype=self.dtype) + ph._keras_mask = None + return ph + inputs = nest.map_structure(_make_placeholder_like, input_shape) + try: + outputs = self(inputs, training=False) + except TypeError as e: + raise NotImplementedError( + 'We could not automatically infer the static shape of the ' + 'layer\'s output. Please implement the ' + '`compute_output_shape` method on your layer (%s).' % + self.__class__.__name__) from e + return nest.map_structure(lambda t: t.shape, outputs) + raise NotImplementedError( + 'Please run in eager mode or implement the `compute_output_shape` ' + 'method on your layer (%s).' % self.__class__.__name__) + + @doc_controls.for_subclass_implementers + def compute_output_signature(self, input_signature): + """Compute the output tensor signature of the layer based on the inputs. + + Unlike a TensorShape object, a TensorSpec object contains both shape + and dtype information for a tensor. This method allows layers to provide + output dtype information if it is different from the input dtype. + For any layer that doesn't implement this function, + the framework will fall back to use `compute_output_shape`, and will + assume that the output dtype matches the input dtype. + + Args: + input_signature: Single TensorSpec or nested structure of TensorSpec + objects, describing a candidate input for the layer. + + Returns: + Single TensorSpec or nested structure of TensorSpec objects, describing + how the layer would transform the provided input. + + Raises: + TypeError: If input_signature contains a non-TensorSpec object. + """ + def check_type_return_shape(s): + if not isinstance(s, tensor_lib.TensorSpec): + raise TypeError('Only TensorSpec signature types are supported, ' + 'but saw signature entry: {}.'.format(s)) + return s.shape + input_shape = nest.map_structure(check_type_return_shape, input_signature) + output_shape = self.compute_output_shape(input_shape) + dtype = self._compute_dtype + if dtype is None: + input_dtypes = [s.dtype for s in nest.flatten(input_signature)] + # Default behavior when self.dtype is None, is to use the first input's + # dtype. + dtype = input_dtypes[0] + return nest.map_structure( + lambda s: tensor_lib.TensorSpec(dtype=dtype, shape=s), + output_shape) + + def _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs): + if self.dynamic: + # We will use static shape inference to return symbolic tensors + # matching the specifications of the layer outputs. + # Since `self.dynamic` is True, we will never attempt to + # run the underlying TF graph (which is disconnected). + # TODO(fchollet): consider py_func as an alternative, which + # would enable us to run the underlying graph if needed. + input_signature = nest.map_structure( + lambda x: tensor_lib.TensorSpec(shape=x.shape, dtype=x.dtype), + inputs) + output_signature = self.compute_output_signature(input_signature) + return nest.map_structure(keras_tensor.KerasTensor, output_signature) + else: + return self._infer_output_signature(inputs, args, kwargs, input_masks) + + def _infer_output_signature(self, inputs, args, kwargs, input_masks): + """TODO(kaftan): Docstring.""" + + call_fn = self.call + # Wrapping `call` function in autograph to allow for dynamic control + # flow and control dependencies in call. We are limiting this to + # subclassed layers as autograph is strictly needed only for + # subclassed layers and models. + # tf_convert will respect the value of autograph setting in the + # enclosing tf.function, if any. + if (base_layer_utils.is_subclassed(self) and + not base_layer_utils.from_saved_model(self)): + call_fn = autograph.tf_convert(self.call, ag_ctx.control_status_ctx()) + + # We enter a scratch graph and build placeholder inputs inside of it that + # match the input args. + # We then call the layer inside of the scratch graph to identify the + # output signatures, then we build KerasTensors corresponding to those + # outputs. + scratch_graph = func_graph.FuncGraph(str(self.name) + '_scratch_graph') + with scratch_graph.as_default(): + inputs = nest.map_structure( + keras_tensor.keras_tensor_to_placeholder, inputs) + args = nest.map_structure( + keras_tensor.keras_tensor_to_placeholder, args) + kwargs = nest.map_structure( + keras_tensor.keras_tensor_to_placeholder, kwargs) + input_masks = nest.map_structure( + keras_tensor.keras_tensor_to_placeholder, input_masks) + + with backend.name_scope(self._name_scope()): # pylint: disable=not-callable + with autocast_variable.enable_auto_cast_variables( + self._compute_dtype_object): + # Build layer if applicable (if the `build` method has been + # overridden). + # TODO(kaftan): do we maybe_build here, or have we already done it? + self._maybe_build(inputs) + inputs = self._maybe_cast_inputs(inputs) + outputs = call_fn(inputs, *args, **kwargs) + + self._handle_activity_regularization(inputs, outputs) + self._set_mask_metadata(inputs, outputs, input_masks, + build_graph=False) + outputs = nest.map_structure( + keras_tensor.keras_tensor_from_tensor, outputs) + + if hasattr(self, '_set_inputs') and not self.inputs: + # TODO(kaftan): figure out if we need to do this at all + # Subclassed network: explicitly set metadata normally set by + # a call to self._set_inputs(). + self._set_inputs(inputs, outputs) + del scratch_graph + return outputs + + @generic_utils.default + def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument + """Computes an output mask tensor. + + Args: + inputs: Tensor or list of tensors. + mask: Tensor or list of tensors. + + Returns: + None or a tensor (or list of tensors, + one per output tensor of the layer). + """ + if not self._supports_masking: + if any(m is not None for m in nest.flatten(mask)): + raise TypeError('Layer ' + self.name + ' does not support masking, ' + 'but was passed an input_mask: ' + str(mask)) + # masking not explicitly supported: return None as mask. + return None + # if masking is explicitly supported, by default + # carry over the input mask + return mask + + def __call__(self, *args, **kwargs): + """Wraps `call`, applying pre- and post-processing steps. + + Args: + *args: Positional arguments to be passed to `self.call`. + **kwargs: Keyword arguments to be passed to `self.call`. + + Returns: + Output tensor(s). + + Note: + - The following optional keyword arguments are reserved for specific uses: + * `training`: Boolean scalar tensor of Python boolean indicating + whether the `call` is meant for training or inference. + * `mask`: Boolean input mask. + - If the layer's `call` method takes a `mask` argument (as some Keras + layers do), its default value will be set to the mask generated + for `inputs` by the previous layer (if `input` did come from + a layer that generated a corresponding mask, i.e. if it came from + a Keras layer with masking support. + - If the layer is not built, the method will call `build`. + + Raises: + ValueError: if the layer's `call` method returns None (an invalid value). + RuntimeError: if `super().__init__()` was not called in the constructor. + """ + if not hasattr(self, '_thread_local'): + raise RuntimeError( + 'You must call `super().__init__()` in the layer constructor.') + + # `inputs` (the first arg in the method spec) is special cased in + # layer call due to historical reasons. + # This special casing currently takes the form of: + # - 'inputs' must be explicitly passed. A layer cannot have zero arguments, + # and inputs cannot have been provided via the default value of a kwarg. + # - numpy/scalar values in `inputs` get converted to tensors + # - implicit masks / mask metadata are only collected from 'inputs` + # - Layers are built using shape info from 'inputs' only + # - input_spec compatibility is only checked against `inputs` + # - mixed precision casting (autocast) is only applied to `inputs`, + # not to any other argument. + # - setting the SavedModel saving spec. + inputs, args, kwargs = self._split_out_first_arg(args, kwargs) + input_list = nest.flatten(inputs) + + # Functional Model construction mode is invoked when `Layer`s are called on + # symbolic `KerasTensor`s, i.e.: + # >> inputs = tf.keras.Input(10) + # >> outputs = MyLayer()(inputs) # Functional construction mode. + # >> model = tf.keras.Model(inputs, outputs) + if _in_functional_construction_mode(self, inputs, args, kwargs, input_list): + return self._functional_construction_call(inputs, args, kwargs, + input_list) + + # Maintains info about the `Layer.call` stack. + call_context = base_layer_utils.call_context() + + # Accept NumPy and scalar inputs by converting to Tensors. + if any(isinstance(x, ( + np_arrays.ndarray, np.ndarray, float, int)) for x in input_list): + inputs = nest.map_structure(_convert_numpy_or_python_types, inputs) + input_list = nest.flatten(inputs) + + # Handle `mask` propagation from previous layer to current layer. Masks can + # be propagated explicitly via the `mask` argument, or implicitly via + # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed + # explicitly take priority. + input_masks, mask_is_implicit = self._get_input_masks( + inputs, input_list, args, kwargs) + if self._expects_mask_arg and mask_is_implicit: + kwargs['mask'] = input_masks + + # Training mode for `Layer.call` is set via (in order of priority): + # (1) The `training` argument passed to this `Layer.call`, if it is not None + # (2) The training mode of an outer `Layer.call`. + # (3) The default mode set by `tf.keras.backend.set_learning_phase` (if set) + # (4) Any non-None default value for `training` specified in the call + # signature + # (5) False (treating the layer as if it's in inference) + args, kwargs, training_mode = self._set_training_mode( + args, kwargs, call_context) + + # Losses are cleared for all sublayers on the outermost `Layer.call`. + # Losses are not cleared on inner `Layer.call`s, because sublayers can be + # called multiple times. + if not call_context.in_call: + self._clear_losses() + + eager = context.executing_eagerly() + with call_context.enter( + layer=self, + inputs=inputs, + build_graph=not eager, + training=training_mode): + + input_spec.assert_input_compatibility(self.input_spec, inputs, self.name) + if eager: + call_fn = self.call + name_scope = self._name + else: + name_scope = self._name_scope() # Avoid autoincrementing. # pylint: disable=not-callable + call_fn = self._autographed_call() + + with ops.name_scope_v2(name_scope): + if not self.built: + self._maybe_build(inputs) + + if self._autocast: + inputs = self._maybe_cast_inputs(inputs, input_list) + + with autocast_variable.enable_auto_cast_variables( + self._compute_dtype_object): + outputs = call_fn(inputs, *args, **kwargs) + + if self._activity_regularizer: + self._handle_activity_regularization(inputs, outputs) + if self._supports_masking: + self._set_mask_metadata(inputs, outputs, input_masks, not eager) + if self._saved_model_inputs_spec is None: + self._set_save_spec(inputs) + + return outputs + + def _functional_construction_call(self, inputs, args, kwargs, input_list): + call_context = base_layer_utils.call_context() + + # Accept NumPy and scalar inputs by converting to Tensors. + if any(isinstance(x, ( + np_arrays.ndarray, np.ndarray, float, int)) for x in input_list): + + def _convert_non_tensor(x): + # Don't call `ops.convert_to_tensor` on all `inputs` because + # `SparseTensors` can't be converted to `Tensor`. + if isinstance(x, (np_arrays.ndarray, np.ndarray, float, int)): + return tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + return x + + inputs = nest.map_structure(_convert_non_tensor, inputs) + input_list = nest.flatten(inputs) + + # Handle `mask` propagation from previous layer to current layer. Masks can + # be propagated explicitly via the `mask` argument, or implicitly via + # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed + # explicitly take priority. + mask_arg_passed_by_framework = False + input_masks, mask_is_implicit = self._get_input_masks( + inputs, input_list, args, kwargs) + if self._expects_mask_arg and mask_is_implicit: + kwargs['mask'] = input_masks + mask_arg_passed_by_framework = True + + # If `training` argument is None or not explicitly passed, + # propagate `training` value from this layer's calling layer. + training_value = None + training_arg_passed_by_framework = False + # Priority 1: `training` was explicitly passed a non-None value. + if self._call_arg_was_passed('training', args, kwargs): + training_value = self._get_call_arg_value('training', args, kwargs) + if not self._expects_training_arg: + kwargs.pop('training') + + if training_value is None: + # Priority 2: `training` was passed to a parent layer. + if call_context.training is not None: + training_value = call_context.training + # Priority 3: `learning_phase()` has been set. + elif backend.global_learning_phase_is_set(): + training_value = backend.learning_phase() + # Force the training_value to be bool type which matches to the contract + # for layer/model call args. + if tensor_util.is_tf_type(training_value): + training_value = math_ops.cast(training_value, dtypes.bool) + else: + training_value = bool(training_value) + # Priority 4: trace layer with the default training argument specified + # in the `call` signature (or in inference mode if the `call` signature + # specifies no non-None default). + else: + training_value = self._default_training_arg + # In cases (2), (3), (4) the training argument is passed automatically + # by the framework, and will not be hard-coded into the model. + if self._expects_training_arg: + args, kwargs = self._set_call_arg_value('training', training_value, + args, kwargs) + training_arg_passed_by_framework = True + + with call_context.enter( + layer=self, inputs=inputs, build_graph=True, training=training_value): + # Check input assumptions set after layer building, e.g. input shape. + outputs = self._keras_tensor_symbolic_call( + inputs, input_masks, args, kwargs) + + if outputs is None: + raise ValueError('A layer\'s `call` method should return a ' + 'Tensor or a list of Tensors, not None ' + '(layer: ' + self.name + ').') + if training_arg_passed_by_framework: + args, kwargs = self._set_call_arg_value( + 'training', None, args, kwargs, pop_kwarg_if_none=True) + if mask_arg_passed_by_framework: + kwargs.pop('mask') + # Node connectivity does not special-case the first argument. + outputs = self._set_connectivity_metadata((inputs,) + args, kwargs, + outputs) + return outputs + + def _set_training_mode(self, args, kwargs, call_context): + training_mode = None + if self._expects_training_arg: + # (1) `training` was passed to this `Layer.call`. + if self._call_arg_was_passed('training', args, kwargs): + training_mode = self._get_call_arg_value('training', args, kwargs) + # If no `training` arg was passed, or `None` was explicitly passed, + # the framework will make a decision about the training mode is. + if training_mode is None: + call_ctx_training = call_context.training + # (2) `training` mode is inferred from an outer `Layer.call`. + if call_ctx_training is not None: + training_mode = call_ctx_training + # (3) User set `tf.keras.backend.set_learning_phase`. + elif backend.global_learning_phase_is_set(): + training_mode = backend.learning_phase() + # Ensure value is a `bool` or `tf.bool`. + if isinstance(training_mode, bool): + pass + elif tensor_util.is_tf_type(training_mode): + training_mode = math_ops.cast(training_mode, dtypes.bool) + else: + training_mode = bool(training_mode) + # (4) We default to using `call`'s default value for `training`, + # or treating the layer as if it is in inference if no non-None default + # is specified in the `call` signature. + else: + training_mode = self._default_training_arg + + # For case (2), (3), (4) `training` arg is passed by framework. + args, kwargs = self._set_call_arg_value('training', training_mode, args, + kwargs) + else: + if 'training' in kwargs: + # `training` was passed to this `Layer` but is not needed for + # `Layer.call`. It will set the default mode for inner `Layer.call`s. + training_mode = kwargs.pop('training') + else: + # Grab the current `training` mode from any outer `Layer.call`. + training_mode = call_context.training + + return args, kwargs, training_mode + + def _autographed_call(self): + # Wrapping `call` function in autograph to allow for dynamic control + # flow and control dependencies in call. We are limiting this to + # subclassed layers as autograph is strictly needed only for + # subclassed layers and models. + # tf_convert will respect the value of autograph setting in the + # enclosing tf.function, if any. + if (base_layer_utils.is_subclassed(self) and + not base_layer_utils.from_saved_model(self)): + return autograph.tf_convert(self.call, ag_ctx.control_status_ctx()) + else: + return self.call + + @property + def dtype(self): + """The dtype of the layer weights. + + This is equivalent to `Layer.dtype_policy.variable_dtype`. Unless + mixed precision is used, this is the same as `Layer.compute_dtype`, the + dtype of the layer's computations. + """ + return self._dtype_policy.variable_dtype + + @property + def name(self): + """Name of the layer (string), set in the constructor.""" + return self._name + + @property + def supports_masking(self): + """Whether this layer supports computing a mask using `compute_mask`.""" + return self._supports_masking + + @supports_masking.setter + def supports_masking(self, value): + self._supports_masking = value + + @property + def dynamic(self): + """Whether the layer is dynamic (eager-only); set in the constructor.""" + return any(layer._dynamic for layer in self._flatten_layers()) + + @property + @doc_controls.do_not_doc_inheritable + def stateful(self): + return any(layer._stateful for layer in self._flatten_layers()) + + @stateful.setter + def stateful(self, value): + self._stateful = value + + @property + def trainable(self): + return self._trainable + + @trainable.setter + def trainable(self, value): + for layer in self._flatten_layers(): + layer._trainable = value + + @property + def activity_regularizer(self): + """Optional regularizer function for the output of this layer.""" + return self._activity_regularizer + + @activity_regularizer.setter + def activity_regularizer(self, regularizer): + """Optional regularizer function for the output of this layer.""" + self._activity_regularizer = regularizer + + @property + def input_spec(self): + """`InputSpec` instance(s) describing the input format for this layer. + + When you create a layer subclass, you can set `self.input_spec` to enable + the layer to run input compatibility checks when it is called. + Consider a `Conv2D` layer: it can only be called on a single input tensor + of rank 4. As such, you can set, in `__init__()`: + + ```python + self.input_spec = tf.keras.layers.InputSpec(ndim=4) + ``` + + Now, if you try to call the layer on an input that isn't rank 4 + (for instance, an input of shape `(2,)`, it will raise a nicely-formatted + error: + + ``` + ValueError: Input 0 of layer conv2d is incompatible with the layer: + expected ndim=4, found ndim=1. Full shape received: [2] + ``` + + Input checks that can be specified via `input_spec` include: + - Structure (e.g. a single input, a list of 2 inputs, etc) + - Shape + - Rank (ndim) + - Dtype + + For more information, see `tf.keras.layers.InputSpec`. + + Returns: + A `tf.keras.layers.InputSpec` instance, or nested structure thereof. + """ + return self._input_spec + + @input_spec.setter + # Must be decorated to prevent tracking, since the input_spec can be nested + # InputSpec objects. + @trackable.no_automatic_dependency_tracking + def input_spec(self, value): + for v in nest.flatten(value): + if v is not None and not isinstance(v, InputSpec): + raise TypeError('Layer input_spec must be an instance of InputSpec. ' + 'Got: {}'.format(v)) + self._input_spec = value + + @property + def trainable_weights(self): + """List of all trainable weights tracked by this layer. + + Trainable weights are updated via gradient descent during training. + + Returns: + A list of trainable variables. + """ + if self.trainable: + children_weights = self._gather_children_attribute('trainable_variables') + return self._dedup_weights(self._trainable_weights + children_weights) + else: + return [] + + @property + def non_trainable_weights(self): + """List of all non-trainable weights tracked by this layer. + + Non-trainable weights are *not* updated during training. They are expected + to be updated manually in `call()`. + + Returns: + A list of non-trainable variables. + """ + if self.trainable: + children_weights = self._gather_children_attribute( + 'non_trainable_variables') + non_trainable_weights = self._non_trainable_weights + children_weights + else: + children_weights = self._gather_children_attribute('variables') + non_trainable_weights = ( + self._trainable_weights + self._non_trainable_weights + + children_weights) + return self._dedup_weights(non_trainable_weights) + + @property + def weights(self): + """Returns the list of all layer variables/weights. + + Returns: + A list of variables. + """ + return self.trainable_weights + self.non_trainable_weights + + @property + @doc_controls.do_not_generate_docs + def updates(self): + warnings.warn('`layer.updates` will be removed in a future version. ' + 'This property should not be used in TensorFlow 2.0, ' + 'as `updates` are applied automatically.') + return [] + + @property + def losses(self): + """List of losses added using the `add_loss()` API. + + Variable regularization tensors are created when this property is accessed, + so it is eager safe: accessing `losses` under a `tf.GradientTape` will + propagate gradients back to the corresponding variables. + + Examples: + + >>> class MyLayer(tf.keras.layers.Layer): + ... def call(self, inputs): + ... self.add_loss(tf.abs(tf.reduce_mean(inputs))) + ... return inputs + >>> l = MyLayer() + >>> l(np.ones((10, 1))) + >>> l.losses + [1.0] + + >>> inputs = tf.keras.Input(shape=(10,)) + >>> x = tf.keras.layers.Dense(10)(inputs) + >>> outputs = tf.keras.layers.Dense(1)(x) + >>> model = tf.keras.Model(inputs, outputs) + >>> # Activity regularization. + >>> len(model.losses) + 0 + >>> model.add_loss(tf.abs(tf.reduce_mean(x))) + >>> len(model.losses) + 1 + + >>> inputs = tf.keras.Input(shape=(10,)) + >>> d = tf.keras.layers.Dense(10, kernel_initializer='ones') + >>> x = d(inputs) + >>> outputs = tf.keras.layers.Dense(1)(x) + >>> model = tf.keras.Model(inputs, outputs) + >>> # Weight regularization. + >>> model.add_loss(lambda: tf.reduce_mean(d.kernel)) + >>> model.losses + [] + + Returns: + A list of tensors. + """ + collected_losses = [] + for layer in self._flatten_layers(): + # If any eager losses are present, we assume the model to be part of an + # eager training loop (either a custom one or the one used when + # `run_eagerly=True`) and so we always return just the eager losses. + if layer._eager_losses: + # Filter placeholder losses that may have been added by revived layers. + # (see base_layer_utils for details). + if (layer._eager_losses[0] is + not base_layer_utils.REVIVED_LOSS_PLACEHOLDER): + collected_losses.extend(layer._eager_losses) + else: + collected_losses.extend(layer._losses) + for regularizer in layer._callable_losses: + loss_tensor = regularizer() + if loss_tensor is not None: + collected_losses.append(loss_tensor) + return collected_losses + + def add_loss(self, losses, **kwargs): + """Add loss tensor(s), potentially dependent on layer inputs. + + Some losses (for instance, activity regularization losses) may be dependent + on the inputs passed when calling a layer. Hence, when reusing the same + layer on different inputs `a` and `b`, some entries in `layer.losses` may + be dependent on `a` and some on `b`. This method automatically keeps track + of dependencies. + + This method can be used inside a subclassed layer or model's `call` + function, in which case `losses` should be a Tensor or list of Tensors. + + Example: + + ```python + class MyLayer(tf.keras.layers.Layer): + def call(self, inputs): + self.add_loss(tf.abs(tf.reduce_mean(inputs))) + return inputs + ``` + + This method can also be called directly on a Functional Model during + construction. In this case, any loss Tensors passed to this Model must + be symbolic and be able to be traced back to the model's `Input`s. These + losses become part of the model's topology and are tracked in `get_config`. + + Example: + + ```python + inputs = tf.keras.Input(shape=(10,)) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + # Activity regularization. + model.add_loss(tf.abs(tf.reduce_mean(x))) + ``` + + If this is not the case for your loss (if, for example, your loss references + a `Variable` of one of the model's layers), you can wrap your loss in a + zero-argument lambda. These losses are not tracked as part of the model's + topology since they can't be serialized. + + Example: + + ```python + inputs = tf.keras.Input(shape=(10,)) + d = tf.keras.layers.Dense(10) + x = d(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + # Weight regularization. + model.add_loss(lambda: tf.reduce_mean(d.kernel)) + ``` + + Args: + losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses + may also be zero-argument callables which create a loss tensor. + **kwargs: Additional keyword arguments for backward compatibility. + Accepted values: + inputs - Deprecated, will be automatically inferred. + """ + kwargs.pop('inputs', None) + if kwargs: + raise TypeError('Unknown keyword arguments: %s' % (kwargs.keys(),)) + + def _tag_callable(loss): + """Tags callable loss tensor as `_unconditional_loss`.""" + if callable(loss): + # We run the loss without autocasting, as regularizers are often + # numerically unstable in float16. + with autocast_variable.enable_auto_cast_variables(None): + loss = loss() + if loss is None: + return None # Will be filtered out when computing the .losses property + if not tensor_util.is_tf_type(loss): + loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( + loss, dtype=backend.floatx() + ) + loss._unconditional_loss = True # pylint: disable=protected-access + return loss + + losses = nest.flatten(losses) + + callable_losses = [] + eager_losses = [] + symbolic_losses = [] + for loss in losses: + if callable(loss): + callable_losses.append(functools.partial(_tag_callable, loss)) + continue + if loss is None: + continue + if not tensor_util.is_tf_type(loss) and not isinstance( + loss, keras_tensor.KerasTensor): + loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( + loss, dtype=backend.floatx() + ) + # TF Functions should take the eager path. + if ((tf_utils.is_symbolic_tensor(loss) or + isinstance(loss, keras_tensor.KerasTensor)) and + not base_layer_utils.is_in_tf_function()): + symbolic_losses.append(loss) + elif tensor_util.is_tf_type(loss): + eager_losses.append(loss) + + self._callable_losses.extend(callable_losses) + + in_call_context = base_layer_utils.call_context().in_call + if eager_losses and not in_call_context: + raise ValueError( + 'Expected a symbolic Tensors or a callable for the loss value. ' + 'Please wrap your loss computation in a zero argument `lambda`.') + + self._eager_losses.extend(eager_losses) + + for symbolic_loss in symbolic_losses: + if getattr(self, '_is_graph_network', False): + self._graph_network_add_loss(symbolic_loss) + else: + # Possible a loss was added in a Layer's `build`. + self._losses.append(symbolic_loss) + + def _clear_losses(self): + """Used every step in eager to reset losses.""" + # Set to thread local directly to avoid Layer.__setattr__ overhead. + if not getattr(self, '_self_tracked_trackables', + None): # Fast path for single Layer. + self._thread_local._eager_losses = [] + else: + for layer in self._flatten_layers(): + layer._thread_local._eager_losses = [] + + @property + def metrics(self): + """List of metrics added using the `add_metric()` API. + + Example: + + >>> input = tf.keras.layers.Input(shape=(3,)) + >>> d = tf.keras.layers.Dense(2) + >>> output = d(input) + >>> d.add_metric(tf.reduce_max(output), name='max') + >>> d.add_metric(tf.reduce_min(output), name='min') + >>> [m.name for m in d.metrics] + ['max', 'min'] + + Returns: + A list of `Metric` objects. + """ + collected_metrics = [] + for layer in self._flatten_layers(): + with layer._metrics_lock: + collected_metrics.extend(layer._metrics) + return collected_metrics + + def add_metric(self, value, name=None, **kwargs): + """Adds metric tensor to the layer. + + This method can be used inside the `call()` method of a subclassed layer + or model. + + ```python + class MyMetricLayer(tf.keras.layers.Layer): + def __init__(self): + super(MyMetricLayer, self).__init__(name='my_metric_layer') + self.mean = tf.keras.metrics.Mean(name='metric_1') + + def call(self, inputs): + self.add_metric(self.mean(inputs)) + self.add_metric(tf.reduce_sum(inputs), name='metric_2') + return inputs + ``` + + This method can also be called directly on a Functional Model during + construction. In this case, any tensor passed to this Model must + be symbolic and be able to be traced back to the model's `Input`s. These + metrics become part of the model's topology and are tracked when you + save the model via `save()`. + + ```python + inputs = tf.keras.Input(shape=(10,)) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + model.add_metric(math_ops.reduce_sum(x), name='metric_1') + ``` + + Note: Calling `add_metric()` with the result of a metric object on a + Functional Model, as shown in the example below, is not supported. This is + because we cannot trace the metric result tensor back to the model's inputs. + + ```python + inputs = tf.keras.Input(shape=(10,)) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1') + ``` + + Args: + value: Metric tensor. + name: String metric name. + **kwargs: Additional keyword arguments for backward compatibility. + Accepted values: + `aggregation` - When the `value` tensor provided is not the result of + calling a `keras.Metric` instance, it will be aggregated by default + using a `keras.Metric.Mean`. + """ + kwargs_keys = list(kwargs.keys()) + if (len(kwargs_keys) > 1 or + (len(kwargs_keys) == 1 and kwargs_keys[0] != 'aggregation')): + raise TypeError('Unknown keyword arguments: ', str(kwargs.keys())) + + from_metric_obj = hasattr(value, '_metric_obj') + is_symbolic = isinstance(value, keras_tensor.KerasTensor) + in_call_context = base_layer_utils.call_context().in_call + + if name is None and not from_metric_obj: + # Eg. `self.add_metric(math_ops.reduce_sum(x))` + # In eager mode, we use metric name to lookup a metric. Without a name, + # a new Mean metric wrapper will be created on every model/layer call. + # So, we raise an error when no name is provided. + # We will do the same for symbolic mode for consistency although a name + # will be generated if no name is provided. + + # We will not raise this error in the foll use case for the sake of + # consistency as name in provided in the metric constructor. + # mean = metrics.Mean(name='my_metric') + # model.add_metric(mean(outputs)) + raise ValueError('Please provide a name for your metric like ' + '`self.add_metric(tf.reduce_sum(inputs), ' + 'name=\'mean_activation\')`') + elif from_metric_obj: + name = value._metric_obj.name + + if not in_call_context and not is_symbolic: + raise ValueError('Expected a symbolic Tensor for the metric value, ' + 'received: ' + str(value)) + + # If a metric was added in a Layer's `call` or `build`. + if in_call_context or not getattr(self, '_is_graph_network', False): + # TF Function path should take the eager path. + + # If the given metric is available in `metrics` list we just update state + # on it, otherwise we create a new metric instance and + # add it to the `metrics` list. + metric_obj = getattr(value, '_metric_obj', None) + # Tensors that come from a Metric object already updated the Metric state. + should_update_state = not metric_obj + name = metric_obj.name if metric_obj else name + + with self._metrics_lock: + match = self._get_existing_metric(name) + if match: + metric_obj = match + elif metric_obj: + self._metrics.append(metric_obj) + else: + # Build the metric object with the value's dtype if it defines one + metric_obj = metrics_mod.Mean( + name=name, dtype=getattr(value, 'dtype', None)) + self._metrics.append(metric_obj) + + if should_update_state: + metric_obj(value) + else: + if from_metric_obj: + raise ValueError('Using the result of calling a `Metric` object ' + 'when calling `add_metric` on a Functional ' + 'Model is not supported. Please pass the ' + 'Tensor to monitor directly.') + + # Insert layers into the Keras Graph Network. + aggregation = None if from_metric_obj else 'mean' + self._graph_network_add_metric(value, aggregation, name) + + @doc_controls.do_not_doc_inheritable + def add_update(self, updates, inputs=None): + """Add update op(s), potentially dependent on layer inputs. + + Weight updates (for instance, the updates of the moving mean and variance + in a BatchNormalization layer) may be dependent on the inputs passed + when calling a layer. Hence, when reusing the same layer on + different inputs `a` and `b`, some entries in `layer.updates` may be + dependent on `a` and some on `b`. This method automatically keeps track + of dependencies. + + This call is ignored when eager execution is enabled (in that case, variable + updates are run on the fly and thus do not need to be tracked for later + execution). + + Args: + updates: Update op, or list/tuple of update ops, or zero-arg callable + that returns an update op. A zero-arg callable should be passed in + order to disable running the updates by setting `trainable=False` + on this Layer, when executing in Eager mode. + inputs: Deprecated, will be automatically inferred. + """ + if inputs is not None: + tf_logging.warning( + '`add_update` `inputs` kwarg has been deprecated. You no longer need ' + 'to pass a value to `inputs` as it is being automatically inferred.') + call_context = base_layer_utils.call_context() + # No need to run updates during Functional API construction. + if call_context.in_keras_graph: + return + + # Callable updates are disabled by setting `trainable=False`. + if not call_context.frozen: + for update in nest.flatten(updates): + if callable(update): + update() # pylint: disable=not-callable + + def set_weights(self, weights): + """Sets the weights of the layer, from NumPy arrays. + + The weights of a layer represent the state of the layer. This function + sets the weight values from numpy arrays. The weight values should be + passed in the order they are created by the layer. Note that the layer's + weights must be instantiated before calling this function, by calling + the layer. + + For example, a `Dense` layer returns a list of two values: the kernel matrix + and the bias vector. These can be used to set the weights of another + `Dense` layer: + + >>> layer_a = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(1.)) + >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) + >>> layer_a.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + >>> layer_b = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(2.)) + >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) + >>> layer_b.get_weights() + [array([[2.], + [2.], + [2.]], dtype=float32), array([0.], dtype=float32)] + >>> layer_b.set_weights(layer_a.get_weights()) + >>> layer_b.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + + Args: + weights: a list of NumPy arrays. The number + of arrays and their shape must match + number of the dimensions of the weights + of the layer (i.e. it should match the + output of `get_weights`). + + Raises: + ValueError: If the provided weights list does not match the + layer's specifications. + """ + params = self.weights + + expected_num_weights = 0 + for param in params: + if isinstance(param, base_layer_utils.TrackableWeightHandler): + expected_num_weights += param.num_tensors + else: + expected_num_weights += 1 + + if expected_num_weights != len(weights): + raise ValueError( + 'You called `set_weights(weights)` on layer "%s" ' + 'with a weight list of length %s, but the layer was ' + 'expecting %s weights. Provided weights: %s...' % + (self.name, len(weights), expected_num_weights, str(weights)[:50])) + + weight_index = 0 + weight_value_tuples = [] + for param in params: + if isinstance(param, base_layer_utils.TrackableWeightHandler): + num_tensors = param.num_tensors + tensors = weights[weight_index:weight_index + num_tensors] + param.set_weights(tensors) + weight_index += num_tensors + else: + weight = weights[weight_index] + weight_shape = weight.shape if hasattr(weight, 'shape') else () + ref_shape = param.shape + if not ref_shape.is_compatible_with(weight_shape): + raise ValueError( + 'Layer weight shape %s not compatible with provided weight ' + 'shape %s' % (ref_shape, weight_shape)) + weight_value_tuples.append((param, weight)) + weight_index += 1 + + backend.batch_set_value(weight_value_tuples) + + # Perform any layer defined finalization of the layer state. + for layer in self._flatten_layers(): + layer.finalize_state() + + def get_weights(self): + """Returns the current weights of the layer, as NumPy arrays. + + The weights of a layer represent the state of the layer. This function + returns both trainable and non-trainable weight values associated with this + layer as a list of NumPy arrays, which can in turn be used to load state + into similarly parameterized layers. + + For example, a `Dense` layer returns a list of two values: the kernel matrix + and the bias vector. These can be used to set the weights of another + `Dense` layer: + + >>> layer_a = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(1.)) + >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) + >>> layer_a.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + >>> layer_b = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(2.)) + >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) + >>> layer_b.get_weights() + [array([[2.], + [2.], + [2.]], dtype=float32), array([0.], dtype=float32)] + >>> layer_b.set_weights(layer_a.get_weights()) + >>> layer_b.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + + Returns: + Weights values as a list of NumPy arrays. + """ + weights = self.weights + output_weights = [] + for weight in weights: + if isinstance(weight, base_layer_utils.TrackableWeightHandler): + output_weights.extend(weight.get_tensors()) + else: + output_weights.append(weight) + return backend.batch_get_value(output_weights) + + @doc_controls.do_not_generate_docs + def finalize_state(self): + """Finalizes the layers state after updating layer weights. + + This function can be subclassed in a layer and will be called after updating + a layer weights. It can be overridden to finalize any additional layer state + after a weight update. + """ + pass + + @doc_controls.do_not_generate_docs + def get_updates_for(self, inputs): + """Deprecated, do NOT use! + + Retrieves updates relevant to a specific set of inputs. + + Args: + inputs: Input tensor or list/tuple of input tensors. + + Returns: + List of update ops of the layer that depend on `inputs`. + """ + warnings.warn('`layer.get_updates_for` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.updates` method instead.') + return self.updates + + @doc_controls.do_not_generate_docs + def get_losses_for(self, inputs): + """Deprecated, do NOT use! + + Retrieves losses relevant to a specific set of inputs. + + Args: + inputs: Input tensor or list/tuple of input tensors. + + Returns: + List of loss tensors of the layer that depend on `inputs`. + """ + warnings.warn('`layer.get_losses_for` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.losses` instead.') + return self.losses + + @doc_controls.do_not_doc_inheritable + def get_input_mask_at(self, node_index): + """Retrieves the input mask tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A mask tensor + (or list of tensors if the layer has multiple inputs). + """ + inputs = self.get_input_at(node_index) + if isinstance(inputs, list): + return [getattr(x, '_keras_mask', None) for x in inputs] + else: + return getattr(inputs, '_keras_mask', None) + + @doc_controls.do_not_doc_inheritable + def get_output_mask_at(self, node_index): + """Retrieves the output mask tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A mask tensor + (or list of tensors if the layer has multiple outputs). + """ + output = self.get_output_at(node_index) + if isinstance(output, list): + return [getattr(x, '_keras_mask', None) for x in output] + else: + return getattr(output, '_keras_mask', None) + + @property + @doc_controls.do_not_doc_inheritable + def input_mask(self): + """Retrieves the input mask tensor(s) of a layer. + + Only applicable if the layer has exactly one inbound node, + i.e. if it is connected to one incoming layer. + + Returns: + Input mask tensor (potentially None) or list of input + mask tensors. + + Raises: + AttributeError: if the layer is connected to + more than one incoming layers. + """ + inputs = self.input + if isinstance(inputs, list): + return [getattr(x, '_keras_mask', None) for x in inputs] + else: + return getattr(inputs, '_keras_mask', None) + + @property + @doc_controls.do_not_doc_inheritable + def output_mask(self): + """Retrieves the output mask tensor(s) of a layer. + + Only applicable if the layer has exactly one inbound node, + i.e. if it is connected to one incoming layer. + + Returns: + Output mask tensor (potentially None) or list of output + mask tensors. + + Raises: + AttributeError: if the layer is connected to + more than one incoming layers. + """ + output = self.output + if isinstance(output, list): + return [getattr(x, '_keras_mask', None) for x in output] + else: + return getattr(output, '_keras_mask', None) + + @doc_controls.do_not_doc_inheritable + def get_input_shape_at(self, node_index): + """Retrieves the input shape(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A shape tuple + (or list of shape tuples if the layer has multiple inputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'input_shapes', + 'input shape') + + @doc_controls.do_not_doc_inheritable + def get_output_shape_at(self, node_index): + """Retrieves the output shape(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A shape tuple + (or list of shape tuples if the layer has multiple outputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'output_shapes', + 'output shape') + + @doc_controls.do_not_doc_inheritable + def get_input_at(self, node_index): + """Retrieves the input tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first input node of the layer. + + Returns: + A tensor (or list of tensors if the layer has multiple inputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'input_tensors', + 'input') + + @doc_controls.do_not_doc_inheritable + def get_output_at(self, node_index): + """Retrieves the output tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first output node of the layer. + + Returns: + A tensor (or list of tensors if the layer has multiple outputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'output_tensors', + 'output') + + @property + def input(self): + """Retrieves the input tensor(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer. + + Returns: + Input tensor or list of input tensors. + + Raises: + RuntimeError: If called in Eager mode. + AttributeError: If no inbound nodes are found. + """ + if not self._inbound_nodes: + raise AttributeError('Layer ' + self.name + + ' is not connected, no input to return.') + return self._get_node_attribute_at_index(0, 'input_tensors', 'input') + + @property + def output(self): + """Retrieves the output tensor(s) of a layer. + + Only applicable if the layer has exactly one output, + i.e. if it is connected to one incoming layer. + + Returns: + Output tensor or list of output tensors. + + Raises: + AttributeError: if the layer is connected to more than one incoming + layers. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('Layer ' + self.name + ' has no inbound nodes.') + return self._get_node_attribute_at_index(0, 'output_tensors', 'output') + + @property + @doc_controls.do_not_doc_inheritable + def input_shape(self): + """Retrieves the input shape(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer, or if all inputs + have the same shape. + + Returns: + Input shape, as an integer shape tuple + (or list of shape tuples, one tuple per input tensor). + + Raises: + AttributeError: if the layer has no defined input_shape. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('The layer has never been called ' + 'and thus has no defined input shape.') + all_input_shapes = set( + [str(node.input_shapes) for node in self._inbound_nodes]) + if len(all_input_shapes) == 1: + return self._inbound_nodes[0].input_shapes + else: + raise AttributeError('The layer "' + str(self.name) + + ' has multiple inbound nodes, ' + 'with different input shapes. Hence ' + 'the notion of "input shape" is ' + 'ill-defined for the layer. ' + 'Use `get_input_shape_at(node_index)` ' + 'instead.') + + def count_params(self): + """Count the total number of scalars composing the weights. + + Returns: + An integer count. + + Raises: + ValueError: if the layer isn't yet built + (in which case its weights aren't yet defined). + """ + if not self.built: + if getattr(self, '_is_graph_network', False): + with tf_utils.maybe_init_scope(self): + self._maybe_build(self.inputs) + else: + raise ValueError('You tried to call `count_params` on ' + self.name + + ', but the layer isn\'t built. ' + 'You can build it manually via: `' + self.name + + '.build(batch_input_shape)`.') + return layer_utils.count_params(self.weights) + + @property + @doc_controls.do_not_doc_inheritable + def output_shape(self): + """Retrieves the output shape(s) of a layer. + + Only applicable if the layer has one output, + or if all outputs have the same shape. + + Returns: + Output shape, as an integer shape tuple + (or list of shape tuples, one tuple per output tensor). + + Raises: + AttributeError: if the layer has no defined output shape. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('The layer has never been called ' + 'and thus has no defined output shape.') + all_output_shapes = set( + [str(node.output_shapes) for node in self._inbound_nodes]) + if len(all_output_shapes) == 1: + return self._inbound_nodes[0].output_shapes + else: + raise AttributeError('The layer "%s"' + ' has multiple inbound nodes, ' + 'with different output shapes. Hence ' + 'the notion of "output shape" is ' + 'ill-defined for the layer. ' + 'Use `get_output_shape_at(node_index)` ' + 'instead.' % self.name) + + @property + @doc_controls.do_not_doc_inheritable + def inbound_nodes(self): + """Deprecated, do NOT use! Only for compatibility with external Keras.""" + return self._inbound_nodes + + @property + @doc_controls.do_not_doc_inheritable + def outbound_nodes(self): + """Deprecated, do NOT use! Only for compatibility with external Keras.""" + return self._outbound_nodes + + ############################################################################## + # Methods & attributes below are public aliases of other methods. # + ############################################################################## + + @doc_controls.do_not_doc_inheritable + def apply(self, inputs, *args, **kwargs): + """Deprecated, do NOT use! + + This is an alias of `self.__call__`. + + Args: + inputs: Input tensor(s). + *args: additional positional arguments to be passed to `self.call`. + **kwargs: additional keyword arguments to be passed to `self.call`. + + Returns: + Output tensor(s). + """ + warnings.warn('`layer.apply` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.__call__` method instead.') + return self.__call__(inputs, *args, **kwargs) + + @doc_controls.do_not_doc_inheritable + def add_variable(self, *args, **kwargs): + """Deprecated, do NOT use! Alias for `add_weight`.""" + warnings.warn('`layer.add_variable` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.add_weight` method instead.') + return self.add_weight(*args, **kwargs) + + @property + @doc_controls.do_not_generate_docs + def variables(self): + """Returns the list of all layer variables/weights. + + Alias of `self.weights`. + + Note: This will not track the weights of nested `tf.Modules` that are not + themselves Keras layers. + + Returns: + A list of variables. + """ + return self.weights + + @property + @doc_controls.do_not_generate_docs + def trainable_variables(self): + return self.trainable_weights + + @property + @doc_controls.do_not_generate_docs + def non_trainable_variables(self): + return self.non_trainable_weights + + ############################################################################## + # Methods & attributes below are all private and only used by the framework. # + ############################################################################## + + @property + def _inbound_nodes(self): + return self._inbound_nodes_value + + @_inbound_nodes.setter + @trackable.no_automatic_dependency_tracking + def _inbound_nodes(self, value): + self._inbound_nodes_value = value + + @property + def _outbound_nodes(self): + return self._outbound_nodes_value + + @_outbound_nodes.setter + @trackable.no_automatic_dependency_tracking + def _outbound_nodes(self, value): + self._outbound_nodes_value = value + + def _set_dtype_policy(self, dtype): + """Sets self._dtype_policy.""" + if isinstance(dtype, policy.Policy): + self._dtype_policy = dtype + elif isinstance(dtype, dict): + self._dtype_policy = policy.deserialize(dtype) + elif isinstance(dtype, str) and dtype in ('mixed_float16', + 'mixed_bfloat16'): + # The isinstance check is required since np.dtype raises an error if + # compared to a non-dtype string. + self._dtype_policy = policy.Policy(dtype) + elif dtype: + self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name) + else: + self._dtype_policy = policy.global_policy() + if (self._dtype_policy.name == 'mixed_float16' and + not loss_scale_optimizer.strategy_supports_loss_scaling()): + # Although only loss scaling doesn't support certain strategies, to avoid + # confusion, we disallow the 'mixed_float16' policy with unsupported + # strategies. This is because 'mixed_float16' requires loss scaling for + # numeric stability. + strategy = distribute_lib.get_strategy() + raise ValueError('Mixed precision is not supported with the ' + 'tf.distribute.Strategy: %s. Either stop using mixed ' + 'precision by removing the use of the "%s" policy or ' + 'use a different Strategy, e.g. a MirroredStrategy.' % + (strategy.__class__.__name__, self._dtype_policy.name)) + + # Performance optimization: cache the compute dtype as a Dtype object or + # None, so that str to Dtype conversion doesn't happen in Layer.__call__. + # TODO(b/157486353): Investigate returning DTypes in Policy. + if self._dtype_policy.compute_dtype: + self._compute_dtype_object = dtypes.as_dtype( + self._dtype_policy.compute_dtype) + else: + self._compute_dtype_object = None + + @property + def dtype_policy(self): + """The dtype policy associated with this layer. + + This is an instance of a `tf.keras.mixed_precision.Policy`. + """ + return self._dtype_policy + + @property + def compute_dtype(self): + """The dtype of the layer's computations. + + This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless + mixed precision is used, this is the same as `Layer.dtype`, the dtype of + the weights. + + Layers automatically cast their inputs to the compute dtype, which causes + computations and the output to be in the compute dtype as well. This is done + by the base Layer class in `Layer.__call__`, so you do not have to insert + these casts if implementing your own layer. + + Layers often perform certain internal computations in higher precision when + `compute_dtype` is float16 or bfloat16 for numeric stability. The output + will still typically be float16 or bfloat16 in such cases. + + Returns: + The layer's compute dtype. + """ + return self._dtype_policy.compute_dtype + + @property + def _compute_dtype(self): + """Deprecated alias of `compute_dtype`.""" + return self._dtype_policy.compute_dtype + + @property + def variable_dtype(self): + """Alias of `Layer.dtype`, the dtype of the weights.""" + return self.dtype + + def _maybe_cast_inputs(self, inputs, input_list=None): + """Maybe casts the inputs to the compute dtype. + + If self._compute_dtype is floating-point, and self_autocast is True, + floating-point inputs are casted to self._compute_dtype. + + Args: + inputs: Input tensor, or structure of input tensors. + input_list: Flat list of input tensors. + + Returns: + `inputs`, but tensors may have been casted to self._compute_dtype + """ + if not input_list: + input_list = nest.flatten(inputs) + + compute_dtype_object = self._compute_dtype_object + should_autocast = ( + self._autocast and compute_dtype_object and + compute_dtype_object.is_floating) + + if (should_autocast and + any(map(self._should_cast_single_input, input_list))): + # Only perform expensive `nest` operation when needed. + return nest.map_structure(self._cast_single_input, inputs) + else: + return inputs + + def _should_cast_single_input(self, x): + if isinstance(x, _AUTOCAST_TYPES): + return (self._compute_dtype_object and + x.dtype != self._compute_dtype_object and x.dtype.is_floating) + return False + + def _cast_single_input(self, x): + """Cast a single Tensor or TensorSpec to the compute dtype.""" + if self._should_cast_single_input(x): + return math_ops.cast(x, self._compute_dtype_object) + else: + return x + + # _dtype used to be an attribute set in the constructor. We still expose it + # because some clients still use it. + # TODO(reedwm): Deprecate, then remove the _dtype property. + @property + def _dtype(self): + # This is equivalent to returning self.dtype . We do not return self.dtype + # as it would cause infinite recursion in a few subclasses, which override + # "dtype" to return self._dtype. + return self._dtype_policy.variable_dtype + + @_dtype.setter + def _dtype(self, value): + value = dtypes.as_dtype(value).name + self._set_dtype_policy(policy.Policy(value)) + + def _name_scope(self): # pylint: disable=method-hidden + if not tf2.enabled(): + return self.name + name_scope = self.name + current_name_scope = ops.get_name_scope() + if current_name_scope: + name_scope = current_name_scope + '/' + name_scope + if name_scope: + # Note that the trailing `/` prevents autogenerated + # numerical suffixes to get appended. It will also fully reset + # nested name scope (i.e. the outer name scope has no effect). + name_scope += '/' + return name_scope + + def _init_set_name(self, name, zero_based=True): + if not name: + self._name = backend.unique_object_name( + generic_utils.to_snake_case(self.__class__.__name__), + zero_based=zero_based) + else: + backend.observe_object_name(name) + self._name = name + + def _get_existing_metric(self, name=None): + match = [m for m in self._metrics if m.name == name] + if not match: + return + if len(match) > 1: + raise ValueError( + 'Please provide different names for the metrics you have added. ' + 'We found {} metrics with the name: "{}"'.format(len(match), name)) + return match[0] + + def _handle_weight_regularization(self, name, variable, regularizer): + """Create lambdas which compute regularization losses.""" + + def _loss_for_variable(v): + """Creates a regularization loss `Tensor` for variable `v`.""" + with backend.name_scope(name + '/Regularizer'): + regularization = regularizer(v) + return regularization + + if base_layer_utils.is_split_variable(variable): + for v in variable: + self.add_loss(functools.partial(_loss_for_variable, v)) + else: + self.add_loss(functools.partial(_loss_for_variable, variable)) + + def _handle_activity_regularization(self, inputs, outputs): + # Apply activity regularization. + # Note that it should be applied every time the layer creates a new + # output, since it is output-specific. + if self._activity_regularizer: + output_list = nest.flatten(outputs) + with backend.name_scope('ActivityRegularizer'): + for output in output_list: + activity_loss = self._activity_regularizer(output) + batch_size = math_ops.cast( + array_ops.shape(output)[0], activity_loss.dtype) + # Make activity regularization strength batch-agnostic. + mean_activity_loss = activity_loss / batch_size + self.add_loss(mean_activity_loss) + + def _set_mask_metadata(self, inputs, outputs, previous_mask, build_graph): + # Many `Layer`s don't need to call `compute_mask`. + # This method is optimized to do as little work as needed for the common + # case. + if not self._supports_masking: + return + + flat_outputs = nest.flatten(outputs) + + mask_already_computed = ( + getattr(self, '_compute_output_and_mask_jointly', False) or + all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs)) + if mask_already_computed: + if build_graph: + self._set_mask_keras_history_checked(flat_outputs) + return + + output_masks = self.compute_mask(inputs, previous_mask) + if output_masks is None: + return + + flat_masks = nest.flatten(output_masks) + for tensor, mask in zip(flat_outputs, flat_masks): + try: + tensor._keras_mask = mask + except AttributeError: + # C Type such as np.ndarray. + pass + + if build_graph: + self._set_mask_keras_history_checked(flat_outputs) + + def _set_mask_keras_history_checked(self, flat_outputs): + for output in flat_outputs: + if getattr(output, '_keras_mask', None) is not None: + # Do not track masks for `TensorFlowOpLayer` construction. + output._keras_mask._keras_history_checked = True + + def _get_input_masks(self, inputs, input_list, args, kwargs): + if not self._supports_masking and not self._expects_mask_arg: + # Input masks only need to be retrieved if they are needed for `call` + # or `compute_mask`. + input_masks = None + implicit_mask = False + elif self._call_arg_was_passed('mask', args, kwargs): + input_masks = self._get_call_arg_value('mask', args, kwargs) + implicit_mask = False + else: + input_masks = [getattr(t, '_keras_mask', None) for t in input_list] + if all(mask is None for mask in input_masks): + input_masks = None + implicit_mask = False + else: + # Only do expensive `nest` op when masking is actually being used. + input_masks = nest.pack_sequence_as(inputs, input_masks) + implicit_mask = True + return input_masks, implicit_mask + + def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False): + # Performance optimization: do no work in most common case. + if not args and not kwargs: + return False + + if arg_name in kwargs: + return True + call_fn_args = self._call_fn_args + if not inputs_in_args: + # Ignore `inputs` arg. + call_fn_args = call_fn_args[1:] + return arg_name in dict(zip(call_fn_args, args)) + + def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False): + if arg_name in kwargs: + return kwargs[arg_name] + call_fn_args = self._call_fn_args + if not inputs_in_args: + # Ignore `inputs` arg. + call_fn_args = call_fn_args[1:] + args_dict = dict(zip(call_fn_args, args)) + return args_dict[arg_name] + + def _set_call_arg_value( + self, arg_name, new_value, args, + kwargs, inputs_in_args=False, pop_kwarg_if_none=False): + arg_pos = self._call_fn_arg_positions.get(arg_name, None) + if arg_pos is not None: + if not inputs_in_args: + # Ignore `inputs` arg. + arg_pos = arg_pos - 1 + if len(args) > arg_pos: + args = list(args) + args[arg_pos] = new_value + return tuple(args), kwargs + if new_value is None and pop_kwarg_if_none: + kwargs.pop(arg_name, None) + else: + kwargs[arg_name] = new_value + return args, kwargs + + def _set_connectivity_metadata(self, args, kwargs, outputs): + # If the layer returns tensors from its inputs unmodified, + # we copy them to avoid loss of KerasHistory metadata. + flat_outputs = nest.flatten(outputs) + flat_inputs = nest.flatten((args, kwargs)) + input_ids_set = {id(i) for i in flat_inputs} + outputs_copy = [] + for x in flat_outputs: + if id(x) in input_ids_set: + with backend.name_scope(self.name): + x = array_ops.identity(x) + outputs_copy.append(x) + outputs = nest.pack_sequence_as(outputs, outputs_copy) + + # Create node, Node wires itself to inbound and outbound layers. + # The Node constructor actually updates this layer's self._inbound_nodes, + # sets _keras_history on the outputs, and adds itself to the + # `_outbound_nodes` of the layers that produced the inputs to this + # layer call. + node_module.Node(self, call_args=args, call_kwargs=kwargs, outputs=outputs) + return outputs + + def _get_node_attribute_at_index(self, node_index, attr, attr_name): + """Private utility to retrieves an attribute (e.g. inputs) from a node. + + This is used to implement the methods: + - get_input_shape_at + - get_output_shape_at + - get_input_at + etc... + + Args: + node_index: Integer index of the node from which + to retrieve the attribute. + attr: Exact node attribute name. + attr_name: Human-readable attribute name, for error messages. + + Returns: + The layer's attribute `attr` at the node of index `node_index`. + + Raises: + RuntimeError: If the layer has no inbound nodes, or if called in Eager + mode. + ValueError: If the index provided does not match any node. + """ + if not self._inbound_nodes: + raise RuntimeError('The layer has never been called ' + 'and thus has no defined ' + attr_name + '.') + if not len(self._inbound_nodes) > node_index: + raise ValueError('Asked to get ' + attr_name + ' at node ' + + str(node_index) + ', but the layer has only ' + + str(len(self._inbound_nodes)) + ' inbound nodes.') + values = getattr(self._inbound_nodes[node_index], attr) + if isinstance(values, list) and len(values) == 1: + return values[0] + else: + return values + + def _maybe_build(self, inputs): + # Check input assumptions set before layer building, e.g. input rank. + if not self.built: + input_spec.assert_input_compatibility( + self.input_spec, inputs, self.name) + input_list = nest.flatten(inputs) + if input_list and self._dtype_policy.compute_dtype is None: + try: + dtype = input_list[0].dtype.base_dtype.name + except AttributeError: + pass + else: + self._set_dtype_policy(policy.Policy(dtype)) + input_shapes = None + # Converts Tensors / CompositeTensors to TensorShapes. + if all(hasattr(x, 'shape') for x in input_list): + input_shapes = tf_utils.get_shapes(inputs) + else: + # Converts input shape to TensorShapes. + try: + input_shapes = tf_utils.convert_shapes(inputs, to_tuples=False) + except ValueError: + pass + # Only call `build` if the user has manually overridden the build method. + if not hasattr(self.build, '_is_default'): + # Any setup work performed only once should happen in an `init_scope` + # to avoid creating symbolic Tensors that will later pollute any eager + # operations. + with tf_utils.maybe_init_scope(self): + self.build(input_shapes) # pylint:disable=not-callable + # We must set also ensure that the layer is marked as built, and the build + # shape is stored since user defined build functions may not be calling + # `super.build()` + Layer.build(self, input_shapes) + + # Optionally load weight values specified at layer instantiation. + if self._initial_weights is not None: + with ops.init_scope(): + # Using `init_scope` since we want variable assignment in + # `set_weights` to be treated like variable initialization. + self.set_weights(self._initial_weights) + self._initial_weights = None + + def _symbolic_call(self, inputs): + input_shapes = nest.map_structure(lambda x: x.shape, inputs) + output_shapes = self.compute_output_shape(input_shapes) + # Convert to TensorShape so that nest.map_structure will not map into + # individual dim of the shape. + output_shapes = tf_utils.convert_shapes(output_shapes, to_tuples=False) + + def _make_placeholder_like(shape): + ph = backend.placeholder(shape=shape, dtype=self.dtype) + ph._keras_mask = None + return ph + return nest.map_structure(_make_placeholder_like, output_shapes) + + def _get_trainable_state(self): + """Get the `trainable` state of each sublayer. + + Returns: + A dict mapping all sublayers to their `trainable` value. + """ + trainable_state = weakref.WeakKeyDictionary() + for layer in self._flatten_layers(): + trainable_state[layer] = layer.trainable + return trainable_state + + def _set_trainable_state(self, trainable_state): + """Set `trainable` state for each sublayer.""" + for layer in self._flatten_layers(): + if layer in trainable_state: + layer.trainable = trainable_state[layer] + + @property + def _obj_reference_counts(self): + """A dictionary counting the number of attributes referencing an object.""" + self._maybe_create_attribute('_obj_reference_counts_dict', + object_identity.ObjectIdentityDictionary()) + return self._obj_reference_counts_dict + + @trackable.no_automatic_dependency_tracking + def _maybe_create_attribute(self, name, default_value): + """Create the attribute with the default value if it hasn't been created. + + This is useful for fields that is used for tracking purpose, + _trainable_weights, or _layers. Note that user could create a layer subclass + and assign an internal field before invoking the Layer.__init__(), the + __setattr__() need to create the tracking fields and __init__() need to not + override them. + + Args: + name: String, the name of the attribute. + default_value: Object, the default value of the attribute. + """ + if not hasattr(self, name): + self.__setattr__(name, default_value) + + def __delattr__(self, name): + # For any super.__delattr__() call, we will directly use the implementation + # in Trackable and skip the behavior in AutoTrackable. The Layer was + # originally use Trackable as base class, the change of using Module as base + # class forced us to have AutoTrackable in the class hierarchy. + # + # TODO(b/180760306) Keeping the status quo of skipping _delattr__ and + # __setattr__ in AutoTrackable may be unsustainable. + existing_value = getattr(self, name, None) + + # If this value is replacing an existing object assigned to an attribute, we + # should clean it out to avoid leaking memory. First we check if there are + # other attributes referencing it. + reference_counts = self._obj_reference_counts + if existing_value not in reference_counts: + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + return + + reference_count = reference_counts[existing_value] + if reference_count > 1: + # There are other remaining references. We can't remove this object from + # _layers etc. + reference_counts[existing_value] = reference_count - 1 + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + return + else: + # This is the last remaining reference. + del reference_counts[existing_value] + + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + + if (isinstance(existing_value, Layer) + or base_layer_utils.has_weights(existing_value)): + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_self_tracked_trackables', + [l for l in self._self_tracked_trackables if l is not existing_value]) + if isinstance(existing_value, tf_variables.Variable): + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_trainable_weights', + [w for w in self._trainable_weights if w is not existing_value]) + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_non_trainable_weights', + [w for w in self._non_trainable_weights if w is not existing_value]) + + def __setattr__(self, name, value): + if (name == '_self_setattr_tracking' or + not getattr(self, '_self_setattr_tracking', True) or + # Exclude @property.setters from tracking + hasattr(self.__class__, name)): + try: + super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call + except AttributeError: + raise AttributeError( + ('Can\'t set the attribute "{}", likely because it conflicts with ' + 'an existing read-only @property of the object. Please choose a ' + 'different name.').format(name)) + return + + # Wraps data structures in `Trackable`, unwraps `NoDependency` objects. + value = data_structures.sticky_attribute_assignment( + trackable=self, value=value, name=name) + + reference_counts = self._obj_reference_counts + reference_counts[value] = reference_counts.get(value, 0) + 1 + + # Clean out the old attribute, which clears _layers and _trainable_weights + # if necessary. + try: + self.__delattr__(name) + except AttributeError: + pass + + # Keep track of metric instance created in subclassed layer. + for val in nest.flatten(value): + if isinstance(val, metrics_mod.Metric) and hasattr(self, '_metrics'): + self._metrics.append(val) + + # Append value to self._self_tracked_trackables if relevant + if (getattr(self, '_auto_track_sub_layers', True) and + (isinstance(value, module.Module) or + base_layer_utils.has_weights(value))): + self._maybe_create_attribute('_self_tracked_trackables', []) + # We need to check object identity to avoid de-duplicating empty + # container types which compare equal. + if not any((layer is value for layer in self._self_tracked_trackables)): + self._self_tracked_trackables.append(value) + if hasattr(value, '_use_resource_variables'): + # Legacy layers (V1 tf.layers) must always use + # resource variables. + value._use_resource_variables = True + + # Append value to list of trainable / non-trainable weights if relevant + # TODO(b/125122625): This won't pick up on any variables added to a + # list/dict after creation. + for val in nest.flatten(value, expand_composites=True): + if not isinstance(val, tf_variables.Variable): + continue + + # Users may add extra weights/variables + # simply by assigning them to attributes (invalid for graph networks) + self._maybe_create_attribute('_trainable_weights', []) + self._maybe_create_attribute('_non_trainable_weights', []) + if val.trainable: + if any(val is w for w in self._trainable_weights): + continue + self._trainable_weights.append(val) + else: + if any(val is w for w in self._non_trainable_weights): + continue + self._non_trainable_weights.append(val) + + backend.track_variable(val) + + # TODO(b/180760306) Skip the auto trackable from tf.Module to keep status + # quo. See the comment at __delattr__. + super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call + + def _gather_children_attribute(self, attribute): + assert attribute in { + 'variables', 'trainable_variables', 'non_trainable_variables' + } + if hasattr(self, '_self_tracked_trackables'): + nested_layers = self._flatten_modules(include_self=False, recursive=False) + return list( + itertools.chain.from_iterable( + getattr(layer, attribute) for layer in nested_layers)) + return [] + + def _flatten_layers(self, recursive=True, include_self=True): + for m in self._flatten_modules( + recursive=recursive, include_self=include_self): + if isinstance(m, Layer): + yield m + + def _flatten_modules(self, recursive=True, include_self=True): + """Flattens `tf.Module` instances (excluding `Metrics`). + + Args: + recursive: Whether to recursively flatten through submodules. + include_self: Whether to include this `Layer` instance. + + Yields: + `tf.Module` instance tracked by this `Layer`. + """ + if include_self: + yield self + + # Only instantiate set and deque if needed. + trackables = getattr(self, '_self_tracked_trackables', None) + if trackables: + seen_object_ids = set() + deque = collections.deque(trackables) + while deque: + trackable_obj = deque.popleft() + trackable_id = id(trackable_obj) + if trackable_id in seen_object_ids: + continue + seen_object_ids.add(trackable_id) + + # Metrics are not considered part of the Layer's topology. + if (isinstance(trackable_obj, module.Module) and + not isinstance(trackable_obj, metrics_mod.Metric)): + yield trackable_obj + # Introspect recursively through sublayers. + if recursive: + subtrackables = getattr(trackable_obj, '_self_tracked_trackables', + None) + if subtrackables: + deque.extendleft(reversed(subtrackables)) + elif isinstance(trackable_obj, data_structures.TrackableDataStructure): + # Data structures are introspected even with `recursive=False`. + tracked_values = trackable_obj._values + if tracked_values: + deque.extendleft(reversed(tracked_values)) + + # This is a hack so that the is_layer (within + # training/trackable/layer_utils.py) check doesn't get the weights attr. + # TODO(b/110718070): Remove when fixed. + def _is_layer(self): + return True + + def _init_call_fn_args(self, expects_training_arg=None): + # Clear cached call function arguments. + self.__class__._call_full_argspec.fget.cache.pop(self, None) + self.__class__._call_fn_args.fget.cache.pop(self, None) + self.__class__._call_accepts_kwargs.fget.cache.pop(self, None) + + call_fn_args = self._call_fn_args + call_fn_args += self._call_full_argspec.kwonlyargs or [] + if expects_training_arg is None: + self._expects_training_arg = ('training' in call_fn_args or + self._call_accepts_kwargs) + else: + # Use value encoded into the metadata when loading from the SavedModel. + self._expects_training_arg = expects_training_arg + # The default training arg will be any (non-None) default specified in the + # method signature, or None if no value is specified. + call_fn_arg_defaults = self._call_fn_arg_defaults.copy() + call_fn_arg_defaults.update(self._call_full_argspec.kwonlydefaults or {}) + self._default_training_arg = call_fn_arg_defaults.get('training') + + self._expects_mask_arg = ('mask' in call_fn_args or + self._call_accepts_kwargs) + + @property + @layer_utils.cached_per_instance + def _call_full_argspec(self): + # Argspec inspection is expensive and the call spec is used often, so it + # makes sense to cache the result. + return tf_inspect.getfullargspec(self.call) + + @property + @layer_utils.cached_per_instance + def _call_fn_args(self): + all_args = self._call_full_argspec.args + # Scrub `self` that appears if a decorator was applied. + if all_args and all_args[0] == 'self': + return all_args[1:] + return all_args + + @property + @layer_utils.cached_per_instance + def _call_fn_arg_defaults(self): + call_fn_args = self._call_fn_args + call_fn_defaults = self._call_full_argspec.defaults or [] + defaults = dict() + + # The call arg defaults are an n-tuple of the last n elements of the args + # list. (n = # of elements that have a default argument) + for i in range(-1 * len(call_fn_defaults), 0): + defaults[call_fn_args[i]] = call_fn_defaults[i] + return defaults + + @property + @layer_utils.cached_per_instance + def _call_fn_arg_positions(self): + call_fn_arg_positions = dict() + for pos, arg in enumerate(self._call_fn_args): + call_fn_arg_positions[arg] = pos + return call_fn_arg_positions + + @property + @layer_utils.cached_per_instance + def _call_accepts_kwargs(self): + return self._call_full_argspec.varkw is not None + + @property + def _eager_losses(self): + # A list of loss values containing activity regularizers and losses + # manually added through `add_loss` during eager execution. It is cleared + # after every batch. + # Because we plan on eventually allowing a same model instance to be trained + # in eager mode or graph mode alternatively, we need to keep track of + # eager losses and symbolic losses via separate attributes. + if not hasattr(self._thread_local, '_eager_losses'): + self._thread_local._eager_losses = [] + return self._thread_local._eager_losses + + @_eager_losses.setter + def _eager_losses(self, losses): + self._thread_local._eager_losses = losses + + def _dedup_weights(self, weights): + """Dedupe weights while maintaining order as much as possible.""" + output, seen_ids = [], set() + for w in weights: + if id(w) not in seen_ids: + output.append(w) + # Track the Variable's identity to avoid __eq__ issues. + seen_ids.add(id(w)) + + return output + + def _split_out_first_arg(self, args, kwargs): + # Grab the argument corresponding to the first argument in the + # layer's `call` method spec. This will either be the first positional + # argument, or it will be provided as a keyword argument. + if args: + inputs = args[0] + args = args[1:] + elif self._call_fn_args[0] in kwargs: + kwargs = copy.copy(kwargs) + inputs = kwargs.pop(self._call_fn_args[0]) + else: + raise ValueError( + 'The first argument to `Layer.call` must always be passed.') + return inputs, args, kwargs + + # SavedModel properties. Please see keras/saving/saved_model for details. + + @trackable.no_automatic_dependency_tracking + def _set_save_spec(self, inputs): + if self._saved_model_inputs_spec is not None: + return # Already set. + + self._saved_model_inputs_spec = nest.map_structure(tf_utils.get_tensor_spec, + inputs) + + def _get_save_spec(self, dynamic_batch=True): + if self._saved_model_inputs_spec is None: + return None + + return nest.map_structure( + lambda t: tf_utils.get_tensor_spec(t, dynamic_batch=dynamic_batch), + self._saved_model_inputs_spec) + + @property + def _trackable_saved_model_saver(self): + return layer_serialization.LayerSavedModelSaver(self) + + @property + def _object_identifier(self): + return self._trackable_saved_model_saver.object_identifier + + @property + def _tracking_metadata(self): + """Info about this layer to be saved into the SavedModel.""" + return self._trackable_saved_model_saver.tracking_metadata + + def _trackable_children(self, save_type='checkpoint', **kwargs): + if save_type == 'savedmodel': + cache = kwargs['cache'] + # TODO(b/213628533): This must be called before super() to ensure + # that any input shape changes are applied before getting the config of + # the model. + children = self._trackable_saved_model_saver.trackable_children(cache) + else: + children = {} + children.update(super()._trackable_children(save_type, **kwargs)) + return children + + @property + def _use_input_spec_as_call_signature(self): + # Whether input spec can be used as the call signature when tracing the + # Layer for SavedModel. By default, this is set to `True` for layers + # exported from the Keras library, because the layers more rigidly define + # the `input_specs` property (many custom layers only set the `ndims`) + return get_canonical_name_for_symbol(type(self), + api_name='keras') is not None + + def __getstate__(self): + # Override to support `copy.deepcopy` and pickling. + # Thread-local objects cannot be copied in Python 3, so pop these. + # Thread-local objects are used to cache losses in MirroredStrategy, and + # so shouldn't be copied. + state = self.__dict__.copy() + state.pop('_thread_local', None) + state.pop('_metrics_lock', None) + return state + + def __setstate__(self, state): + state['_thread_local'] = threading.local() + state['_metrics_lock'] = threading.Lock() + # Bypass Trackable logic as `__dict__` already contains this info. + object.__setattr__(self, '__dict__', state) + + +class TensorFlowOpLayer(Layer): + """Wraps a TensorFlow Operation in a Layer. + + This class is used internally by the Functional API. When a user + uses a raw TensorFlow Operation on symbolic tensors originating + from an `Input` Layer, the resultant operation will be wrapped + with this Layer object in order to make the operation compatible + with the Keras API. + + This Layer will create a new, identical operation (except for inputs + and outputs) every time it is called. If `run_eagerly` is `True`, + the op creation and calculation will happen inside an Eager function. + + Instances of this Layer are created when `autolambda` is called, which + is whenever a Layer's `__call__` encounters symbolic inputs that do + not have Keras metadata, or when a Network's `__init__` encounters + outputs that do not have Keras metadata. + + Attributes: + node_def: String, the serialized NodeDef of the Op this layer will wrap. + name: String, the name of the Layer. + constants: Dict of NumPy arrays, the values of any Tensors needed for this + Operation that do not originate from a Keras `Input` Layer. Since all + placeholders must come from Keras `Input` Layers, these Tensors must be + treated as constant in the Functional API. + trainable: Bool, whether this Layer is trainable. Currently Variables are + not supported, and so this parameter has no effect. + dtype: The default dtype of this Layer. Inherited from `Layer` and has no + effect on this class, however is used in `get_config`. + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, + node_def, + name, + constants=None, + trainable=True, + dtype=None): + # Pass autocast=False, as if inputs are cast, input types might not match + # Operation type. + super(TensorFlowOpLayer, self).__init__( + name=_TF_OP_LAYER_NAME_PREFIX + name, trainable=trainable, dtype=dtype, + autocast=False) + if isinstance(node_def, dict): + self.node_def = json_format.ParseDict(node_def, node_def_pb2.NodeDef()) + else: + if not isinstance(node_def, bytes): + node_def = node_def.encode('utf-8') + self.node_def = node_def_pb2.NodeDef.FromString(node_def) + # JSON serialization stringifies keys which are integer input indices. + self.constants = ({ + int(index): constant for index, constant in constants.items() + } if constants is not None else {}) + # Layer uses original op unless it is called on new inputs. + # This means `built` is not set in `__call__`. + self.built = True + + # Do not individually trace TensorflowOpLayers in the SavedModel. + self._must_restore_from_config = True + + def call(self, inputs): + if context.executing_eagerly(): + return self._defun_call(inputs) + return self._make_op(inputs) + + def _make_node_def(self, graph): + node_def = node_def_pb2.NodeDef() + node_def.CopyFrom(self.node_def) + # Used in TPUReplicateContext to indicate whether this node has been cloned + # and to not add TPU attributes. + node_def.attr['_cloned'].b = True + node_def.name = graph.unique_name(node_def.name) + return node_def + + def _make_op(self, inputs): + inputs = nest.flatten(inputs) + graph = inputs[0].graph + node_def = self._make_node_def(graph) + with graph.as_default(): + for index, constant in self.constants.items(): + # Recreate constant in graph to add distribution context. + value = tensor_util.constant_value(constant) + if value is not None: + constant = constant_op.constant(value, name=node_def.input[index]) + inputs.insert(index, constant) + # TODO(b/183990973): We should drop or consolidate these private api calls + # for adding an op to the graph and recording its gradient. + c_op = ops._create_c_op(graph, node_def, inputs, control_inputs=[]) + op = graph._create_op_from_tf_operation(c_op) + op._control_flow_post_processing() + + # Record the gradient because custom-made ops don't go through the + # code-gen'd eager call path + op_type = compat.as_str(op.op_def.name) + attr_names = [compat.as_str(attr.name) for attr in op.op_def.attr] + attrs = [] + for attr_name in attr_names: + attrs.append(attr_name) + attrs.append(op.get_attr(attr_name)) + attrs = tuple(attrs) + backprop.record_gradient(op_type, op.inputs, attrs, op.outputs) + + if len(op.outputs) == 1: + return op.outputs[0] + return op.outputs + + @def_function.function + def _defun_call(self, inputs): + """Wraps the op creation method in an Eager function for `run_eagerly`.""" + return self._make_op(inputs) + + def get_config(self): + config = super(TensorFlowOpLayer, self).get_config() + config.update({ + # `__init__` prefixes the name. Revert to the constructor argument. + 'name': config['name'][len(_TF_OP_LAYER_NAME_PREFIX):], + 'node_def': json_format.MessageToDict(self.node_def), + 'constants': { + i: backend.get_value(c) for i, c in self.constants.items() + } + }) + return config + + +class AddLoss(Layer): + """Adds its inputs as a loss. + + Attributes: + unconditional: Whether or not the loss should be conditioned on the inputs. + """ + + def __init__(self, unconditional, **kwargs): + # Pass autocast=False, as there is no reason to cast loss to a different + # dtype. + kwargs['autocast'] = False + super(AddLoss, self).__init__(**kwargs) + self.unconditional = unconditional + + def call(self, inputs): + self.add_loss(inputs, inputs=(not self.unconditional)) + return inputs + + def get_config(self): + config = super(AddLoss, self).get_config() + config.update({'unconditional': self.unconditional}) + return config + + +class AddMetric(Layer): + """Adds its inputs as a metric. + + Attributes: + aggregation: 'mean' or None. How the inputs should be aggregated. + metric_name: The name to use for this metric. + """ + + def __init__(self, aggregation=None, metric_name=None, **kwargs): + super(AddMetric, self).__init__(**kwargs) + self.aggregation = aggregation + self.metric_name = metric_name + + def call(self, inputs): + self.add_metric(inputs, aggregation=self.aggregation, name=self.metric_name) + return inputs + + def get_config(self): + config = super(AddMetric, self).get_config() + config.update({ + 'aggregation': self.aggregation, + 'metric_name': self.metric_name + }) + return config + + +def _in_functional_construction_mode(layer, inputs, args, kwargs, input_list): # pylint: disable=unused-argument + """Check the arguments to see if we are constructing a functional model.""" + # We are constructing a functional model if any of the inputs + # are KerasTensors + return any( + isinstance(tensor, keras_tensor.KerasTensor) + for tensor in nest.flatten([inputs, args, kwargs])) + + +def _convert_numpy_or_python_types(x): + if isinstance(x, (np_arrays.ndarray, np.ndarray, float, int)): + return tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + return x + + +# Avoid breaking users who directly import this symbol from this file. +# TODO(fchollet): remove this. +InputSpec = input_spec.InputSpec # pylint:disable=invalid-name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd0b92d37711c34521ad4eb40ae469d89eaf680 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_utils.py @@ -0,0 +1,900 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains private utilities used mainly by the base Layer class.""" + +import functools +import threading + +from tensorflow.python import tf2 +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.trackable import base as tracking +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import nest + +_call_context = threading.local() + + +def create_mean_metric(value, name=None): + # import keras will import base_layer and then this module, and metric relies + # on base_layer, which result into a cyclic dependency. + from tensorflow.python.keras import metrics as metrics_module # pylint: disable=g-import-not-at-top + metric_obj = metrics_module.Mean(name=name, dtype=value.dtype) + return metric_obj, metric_obj(value) + + +def make_variable(name, + shape=None, + dtype=dtypes.float32, + initializer=None, + trainable=None, + caching_device=None, + validate_shape=True, + constraint=None, + use_resource=None, + collections=None, + synchronization=tf_variables.VariableSynchronization.AUTO, + aggregation=tf_variables.VariableAggregation.NONE, + partitioner=None): # pylint: disable=unused-argument + """Temporary util to create a variable (relies on `variable_scope.variable`). + + Some reuse-related technicalities prevent us from using + `variable_scope.get_variable()` directly, so we use a subcomponent + that has fewer constraints (`variable_scope.variable()`). + + In the longer term, it seems like a similar "default variable creator" method + should exist in `Trackable` instead. When this happens, we can get + rid of this temporary solution. + + TODO(fchollet): remove this method when no longer needed. + + Args: + name: Variable name. + shape: Variable shape. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + initializer: Initializer instance (callable). + trainable: Whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) + or "non_trainable_variables" (e.g. BatchNorm mean, stddev). + Note, if the current variable scope is marked as non-trainable + then this parameter is ignored and any added variables are also + marked as non-trainable. `trainable` defaults to `True` unless + `synchronization` is set to `ON_READ`. + caching_device: Passed to `tf.Variable`. + validate_shape: Passed to `tf.Variable`. + constraint: Constraint instance (callable). + use_resource: Whether to use a `ResourceVariable`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. If `synchronization` is set to `ON_READ`, + `trainable` must not be set to `True`. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + partitioner: Not handled at this time. + + Returns: + Variable instance. + """ + initializing_from_value = False + if initializer is not None and not callable(initializer): + initializing_from_value = True + + if initializing_from_value: + init_val = initializer + variable_dtype = None + else: + # Instantiate initializer if provided initializer is a type object. + if tf_inspect.isclass(initializer): + initializer = initializer() + init_val = functools.partial(initializer, shape, dtype=dtype) + variable_dtype = dtype.base_dtype + if use_resource is None: + use_resource = True + + # TODO(apassos,rohanj) figure out how to remove collections from here so we + # can remove the V1. + variable_shape = tensor_shape.TensorShape(shape) + return variable_v1.VariableV1( + initial_value=init_val, + name=name, + trainable=trainable, + caching_device=caching_device, + dtype=variable_dtype, + validate_shape=validate_shape, + constraint=constraint, + use_resource=use_resource, + collections=collections, + synchronization=synchronization, + aggregation=aggregation, + shape=variable_shape if variable_shape else None) + + +def collect_previous_mask(input_tensors): + """Retrieves the output mask(s) of the previous node. + + Args: + input_tensors: An arbitrary structure of Tensors. + + Returns: + A mask tensor or list of mask tensors. + """ + + def _collect_previous_mask(x): + return getattr(x, '_keras_mask', None) + + return nest.map_structure(_collect_previous_mask, input_tensors) + + +def have_all_keras_metadata(tensors): + return all(hasattr(x, '_keras_history') for x in nest.flatten(tensors)) + + +def generate_placeholders_from_shape(shape): + return array_ops.placeholder(shape=shape, dtype=backend.floatx()) + + +def create_keras_history(tensors): + """Wraps TensorFlow Operations for compatibility with the Functional API. + + This method checks to see if a Tensor in `tensors` is missing Keras metadata + and has its origin in a Keras `Input` Layer. If so, this method will replace + the raw TensorFlow Operations that created this tensor with + `TensorFlowOpLayer` instances that create identical operations. + + Any Tensors not originating from a Keras `Input` Layer will be treated as + constants when constructing `TensorFlowOpLayer` instances. + + Args: + tensors: A structure of Tensors, some of which come from raw TensorFlow + operations and need to have Keras metadata assigned to them. + + Returns: + created_layers: List. The `TensorFlowOpLayer` instances created to wrap + the raw Tensorflow operations. + """ + _, created_layers = _create_keras_history_helper(tensors, set(), []) + return created_layers + + +# Unsafe Internal attribute. +# If True, Keras will not evaluate the constant-foldable inputs to tf op +# layers in TF1 graphs. This *might* speed up model construction time in +# certain settings, but it means +# the models will not be serializable/deserializable via get_config +# (Only via Savedmodels). It may also change the semantics of whether +# generated random numbers are generated once and re-used, or recomputed +# each time. +# Note: This path triggers for TPUEstimators / xla compiled graphs regardless +# of this setting. +_UNSAFE_GRAPH_OP_LAYER_CREATION = False + + +def _create_keras_history_helper(tensors, processed_ops, created_layers): + """Helper method for `create_keras_history`. + + Args: + tensors: A structure of Tensors for which to create Keras metadata. + processed_ops: Set. TensorFlow operations that have already been wrapped in + `TensorFlowOpLayer` instances. + created_layers: List. The `TensorFlowOpLayer` instances created. + + Returns: + Tuple. First element is the updated set of TensorFlow Operations that + have been wrapped in `TensorFlowOpLayer` instances. Second element is + a list of the `TensorFlowOpLayer` instances created. + """ + if ops.executing_eagerly_outside_functions(): + raise ValueError( + '`create_keras_history` should only be called if eager is disabled!') + # Import of `base_layer` needed in order to create `TensorFlowOpLayer`. + # Cannot be imported at top because of circular dependencies. + # TODO(omalleyt): Resolve circular dependency. + from tensorflow.python.keras.engine import base_layer # pylint: disable=g-import-not-at-top + tensor_list = nest.flatten(tensors) + sparse_ops = [] + ragged_tensors = [] + for tensor in tensor_list: + if getattr(tensor, '_keras_history', None) is not None: + continue + if isinstance( + tensor, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + sparse_ops.append(tensor.op) + continue + if tf_utils.is_ragged(tensor): + # Ragged tensors don't have an op property + ragged_tensors.append(tensor) + continue + op = tensor.op # The Op that created this Tensor. + if op not in processed_ops: + # Recursively set `_keras_history`. + op_inputs = list(op.inputs) + constants = {} + layer_inputs = [] + for i, op_input in enumerate(op_inputs): + if uses_keras_history(op_input): + layer_inputs.append(op_input) + else: + # Treat any value not originating from a `keras.Input` as + # a constant. Variables cannot be supported. + ds_with_session = ( + distribute_lib.in_cross_replica_context() and + not ops.executing_eagerly_outside_functions()) + using_xla = control_flow_util.GraphOrParentsInXlaContext( + ops.get_default_graph()) + if ds_with_session or using_xla or _UNSAFE_GRAPH_OP_LAYER_CREATION: + # In Legacy Graph mode, evaluating here makes Session be + # configured improperly. The downside of this is that saving + # via `get_config` breaks, but SavedModel still works. + constants[i] = op_input + else: + with ops.init_scope(): + constants[i] = backend.function([], op_input)([]) + layer_inputs = unnest_if_single_tensor(layer_inputs) + processed_ops, created_layers = _create_keras_history_helper( + layer_inputs, processed_ops, created_layers) + name = op.name + node_def = op.node_def.SerializeToString() + op_layer = base_layer.TensorFlowOpLayer( + node_def, constants=constants, name=name) + created_layers.append(op_layer) + op_layer._set_connectivity_metadata( # pylint: disable=protected-access + args=(layer_inputs,), + kwargs={}, + outputs=op.outputs) + processed_ops.update([op]) + if sparse_ops or ragged_tensors: + lambda_example = """ + weights_mult = lambda x: tf.sparse.sparse_dense_matmul(x, weights) + output = tf.keras.layers.Lambda(weights_mult)(input) + """ + raise ValueError( + 'Tensorflow ops that generate ragged or sparse tensor ' + 'outputs are currently not supported by Keras automatic ' + 'op wrapping. Please wrap these ops in a Lambda layer: ' + '\n\n```\n{example}\n```\n' + 'Sparse ops encountered: {sparse_ops}\n' + 'Ragged tensors encountered: {ragged_tensors}\n'.format( + example=lambda_example, + sparse_ops=str(sparse_ops), + ragged_tensors=str(ragged_tensors))) + return processed_ops, created_layers + + +def unnest_if_single_tensor(input_tensors): + # Preserve compatibility with older configs + flat_input_tensors = nest.flatten(input_tensors) + # If this is a single element but not a dict, unwrap. If this is a dict, + # assume the first layer expects a dict (as is the case with a + # DenseFeatures layer); pass through. + if not isinstance(input_tensors, dict) and len(flat_input_tensors) == 1: + input_tensors = flat_input_tensors[0] + return input_tensors + + +def needs_keras_history(tensors, ignore_call_context=False): + """Check if any Tensors need to be wrapped in TensorFlowOpLayers. + + This will never return True inside a sublayer, because sublayers + do not need to create Keras History. Otherwise, this returns True + if one or more of `tensors` originates from a `keras.Input` and + does not have `_keras_history` set. + + Args: + tensors: An arbitrary nested structure of Tensors. + ignore_call_context: Whether to ignore the check of if currently + outside of a `call` context. This is `True` when creating + KerasHistory inside `Node`, where we always know that Tensors + are being used with the Functional API. + + Returns: + Bool, whether at least one Tensor needs to be wrapped. + """ + input_tensors = nest.flatten(tensors) + if call_context().in_call and not ignore_call_context: + return False + if all( + getattr(tensor, '_keras_history', None) is not None + for tensor in input_tensors): + # KerasHistory already set. + return False + return uses_keras_history(tensors) + + +def is_in_keras_graph(): + """Returns if currently executing inside of a Keras graph.""" + return call_context().in_keras_graph + + +def is_in_eager_or_tf_function(): + """Returns if in eager mode or inside of a tf.function.""" + return context.executing_eagerly() or is_in_tf_function() + + +def is_in_tf_function(): + """Returns if inside of a tf.function.""" + # Check if running in V1 graph mode. + if not ops.executing_eagerly_outside_functions(): + return False + if not ops.inside_function(): + return False + # Check if inside Keras FuncGraph. + if is_in_keras_graph(): + return False + # Check for a v1 `wrap_function` FuncGraph. + graph = ops.get_default_graph() + if (getattr(graph, 'name', False) and + graph.name.startswith('wrapped_function')): + return False + return True + + +def uses_keras_history(tensors): + """Check if at least one Tensor originates from a `keras.Input`. + + This is `True` if at least one Tensor has its origin in a `keras.Input`. + Any Tensor that originates from a `keras.Input` will have a dependency + Tensor with a `_keras_history` attribute attached. Tensors that have + already been checked to not originate from a `keras.Input` + are marked as `_keras_history_checked`. + + Args: + tensors: An arbitrary nested structure of Tensors. + + Returns: + Bool, whether at least one Tensor originates from a `keras.Input`. + """ + checked_tensors = set() + tensors_to_check = nest.flatten(tensors) + + while tensors_to_check: + new_tensors_to_check = [] + for tensor in tensors_to_check: + if id(tensor) in checked_tensors: + continue + + checked_tensors.add(id(tensor)) + + if getattr(tensor, '_keras_history_checked', None) is not None: + continue + if getattr(tensor, '_keras_history', None) is not None: + return True + + try: + new_tensors_to_check.extend(tensor.op.inputs) + except AttributeError: + # In case `tensor` is a Variable created in an Eager context. + pass + + tensors_to_check = new_tensors_to_check + + # Mark that these Tensors have been checked once for `_keras_history`, + # and should not be checked again for performance reasons. + mark_checked(tensors) + return False + + +def mark_checked(tensors): + """Marks that these Tensors should not be tracked. + + This prevents Layers from attempting to create TensorFlowOpLayers + for these Tensors. + + Args: + tensors: An arbitrary structure of Tensors. + """ + + def _mark_checked(tensor): + tensor._keras_history_checked = True # pylint: disable=protected-access + + nest.map_structure(_mark_checked, tensors) + + +def call_context(): + """Returns currently active `CallContext`.""" + call_ctx = getattr(_call_context, 'call_context', None) + if call_ctx is None: + call_ctx = CallContext() + _call_context.call_context = call_ctx + return call_ctx + + +class CallContext(object): + """Keeps track of properties currently inside a Layer/Model's `call`. + + Attributes: + in_call: Whether currently inside the `call` of a Layer. + layer: The `Layer` whose `call` is currently active. + inputs: The inputs to the currently active `Layer`. + build_graph: Whether currently inside a Graph or FuncGraph. + training: Whether currently executing in training or inference mode. + saving: Whether currently saving to SavedModel. + frozen: Whether currently executing inside a `Layer` with `trainable` set to + `False`. + in_keras_graph: Whether executing inside the Keras Graph. + """ + + def __init__(self): + # Handle `in_call` separately as it is the most-read attr and reading it is + # on the hot path. + self.in_call = False + self._state = { + 'layer': None, + 'inputs': None, + 'build_graph': False, + 'training': None, + 'saving': None + } + # TODO(b/150169018): This logic can be replaced after the Functional API + # refactor. + self._in_keras_graph = False + + def enter(self, layer, inputs, build_graph, training, saving=None): + """Push a Layer and its inputs and state onto the current call context. + + Args: + layer: The `Layer` whose `call` is currently active. + inputs: The inputs to the currently active `Layer`. + build_graph: Whether currently inside a Graph or FuncGraph. + training: Whether currently executing in training or inference mode. + saving: Whether currently saving to SavedModel. + + Returns: + Context manager. + """ + state = { + 'layer': layer, + 'inputs': inputs, + 'build_graph': build_graph, + 'training': training, + 'saving': saving + } + return CallContextManager(self, state) + + @property + def layer(self): + return self._state['layer'] + + @property + def inputs(self): + return self._state['inputs'] + + @property + def build_graph(self): + return self._state['build_graph'] + + @property + def training(self): + return self._state['training'] + + @property + def saving(self): + return self._state['saving'] + + @property + def frozen(self): + layer = self._state['layer'] + if not layer: + return False + return not layer.trainable + + @property + def in_keras_graph(self): + # Returns True even if in a subgraph of the Keras graph, such as those + # created by control flow ops. + if context.executing_eagerly(): + return False + return (self._in_keras_graph or + getattr(backend.get_graph(), 'name', None) == 'keras_graph') + + +class CallContextManager(object): + """Context manager for `CallContext`.""" + + def __init__(self, call_ctx, state): + self._call_ctx = call_ctx + self._state = state + self._build_graph = state['build_graph'] + + def __enter__(self): + call_ctx = self._call_ctx + self._prev_in_call = call_ctx.in_call + self._prev_state = call_ctx._state + + call_ctx.in_call = True + call_ctx._state = self._state + + # TODO(b/150169018): This logic can be removed after the Functional API + # refactor. + if self._build_graph: + self._prev_in_keras_graph = call_ctx._in_keras_graph + call_ctx._in_keras_graph = ( + call_ctx._in_keras_graph or + getattr(backend.get_graph(), 'name', None) == 'keras_graph') + + def __exit__(self, *exc_info): + call_ctx = self._call_ctx + call_ctx.in_call = self._prev_in_call + call_ctx._state = self._prev_state + + if self._build_graph: + call_ctx._in_keras_graph = self._prev_in_keras_graph + + +def training_arg_passed_to_call(argspec, args, kwargs): + """Returns whether a user passed the `training` argument in `__call__`.""" + # `argspec.args` starts with ['self', 'inputs'] + full_args = dict(zip(argspec.args[2:], args)) + full_args.update(kwargs) + return 'training' in full_args and full_args['training'] is not None + + +def is_subclassed(layer): + """Returns True if the object is a subclassed layer or subclassed model.""" + return (layer.__module__.find('keras.engine') == -1 and + layer.__module__.find('keras.layers') == -1) + + +def from_saved_model(layer): + """Returns whether the layer is loaded from a SavedModel.""" + return layer.__module__.find('keras.saving.saved_model') != -1 + + +def check_graph_consistency(tensor=None, method='add_loss', force_raise=False): + """Checks that tensors passed to `add_*` method match the Keras graph. + + When one of the `add_*` method is called inside a V2 conditional branch, + the underlying tensor gets created in a FuncGraph managed by control_flow_v2. + We need to raise clear error messages in such cases. + + Args: + tensor: Tensor to check, or `False` if it is known that an error + should be raised. + method: Caller method, one of {'add_metric', 'add_loss', 'add_update'}. + force_raise: If an error should be raised regardless of `tensor`. + + Raises: + RuntimeError: In case of an out-of-graph tensor. + """ + if (force_raise or + (ops.executing_eagerly_outside_functions() and + hasattr(tensor, 'graph') and tensor.graph.is_control_flow_graph)): + if method == 'activity_regularizer': + bad_example = """ + class TestModel(tf.keras.Model): + + def __init__(self): + super(TestModel, self).__init__(name='test_model') + self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') + + def call(self, x, training=None): + if training: + return self.dense(x) + else: + return self.dense(x) + """ + correct_example = """ + class TestModel(tf.keras.Model): + + def __init__(self): + super(TestModel, self).__init__(name='test_model') + self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2') + + def call(self, x, training=None): + return self.dense(x) + """ + raise RuntimeError( + 'You are using a layer with `activity_regularizer` in a control flow ' + 'branch, e.g.:\n{bad_example}\nThis is currently not supported. ' + 'Please move your call to the layer with `activity_regularizer` out ' + 'of the control flow branch, e.g.:\n{correct_example}\n' + 'You can also resolve this by marking your outer model/layer dynamic' + ' (eager-only) by passing `dynamic=True` to the layer constructor. ' + 'Any kind of control flow is supported with dynamic layers. ' + 'Note that using `dynamic=True` requires you to implement static ' + 'shape inference in the `compute_output_shape(input_shape)` ' + 'method.'.format( + bad_example=bad_example, correct_example=correct_example)) + + if method == 'add_metric': + bad_example = """ + def call(self, inputs, training=None): + if training: + metric = compute_metric(inputs) + self.add_metric(metric, name='my_metric', aggregation='mean') + return inputs + """ + correct_example = """ + def call(self, inputs, training=None): + if training: + metric = compute_metric(inputs) + else: + metric = 0. + self.add_metric(metric, name='my_metric', aggregation='mean') + return inputs + """ + elif method == 'add_loss': + bad_example = """ + def call(self, inputs, training=None): + if training: + loss = compute_loss(inputs) + self.add_loss(loss) + return inputs + """ + correct_example = """ + def call(self, inputs, training=None): + if training: + loss = compute_loss(inputs) + else: + loss = 0. + self.add_loss(loss) + return inputs + """ + else: + bad_example = """ + def call(self, inputs, training=None): + if training: + self.add_update(self.w.assign_add(1)) + return inputs + """ + correct_example = """ + def call(self, inputs, training=None): + if training: + increment = 1 + else: + increment = 0 + self.add_update(self.w.assign_add(increment)) + return inputs + """ + raise RuntimeError( + 'You are using the method `{method}` in a control flow branch ' + 'in your layer, e.g.:\n{bad_example}\n' + 'This is not currently supported. ' + 'Please move your call to {method} out of the control flow branch, ' + 'e.g.:\n{correct_example}\n' + 'You can also resolve this by marking your layer ' + 'as dynamic (eager-only) by passing ' + '`dynamic=True` to the layer constructor. ' + 'Any kind of control flow is supported with dynamic layers. ' + 'Note that using `dynamic=True` requires you ' + 'to implement static shape inference ' + 'in the `compute_output_shape(input_shape)` method.'.format( + method=method, + bad_example=bad_example, + correct_example=correct_example)) + + +def mark_as_return(outputs, acd): + """Marks `outputs` as the return values for automatic control deps.""" + + def _mark_as_return(tensor): + """Marks `tensor` as the return value for automatic control deps.""" + if not tensor_util.is_tf_type(tensor): + return tensor + + # pylint: disable=protected-access + return_tensor = acd.mark_as_return(tensor) + if getattr(tensor, '_keras_mask', None) is not None: + return_tensor._keras_mask = acd.mark_as_return(tensor._keras_mask) + else: + return_tensor._keras_mask = None + + # Handle TensorFlow Probability attached metadata. + # TODO(b/132076537): Remove this once TFP uses `CompositeTensor`. + if getattr(tensor, '_tfp_distribution', None) is not None: + return_tensor._tfp_distribution = tensor._tfp_distribution + + return return_tensor + # pylint: enable=protected-access + + return nest.map_structure(_mark_as_return, outputs) + + +V2_DTYPE_BEHAVIOR = None + + +def enable_v2_dtype_behavior(): + """Enable the V2 dtype behavior for Keras layers. + + By default, the V2 dtype behavior is enabled in TensorFlow 2, so this function + is only useful if `tf.compat.v1.disable_v2_behavior` has been called. Since + mixed precision requires V2 dtype behavior to be enabled, this function allows + you to use mixed precision in Keras layers if `disable_v2_behavior` has been + called. + + When enabled, the dtype of Keras layers defaults to floatx (which is typically + float32) instead of None. In addition, layers will automatically cast + floating-point inputs to the layer's dtype. + + >>> x = tf.ones((4, 4, 4, 4), dtype='float64') + >>> layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2) + >>> print(layer.dtype) # float32 since V2 dtype behavior is enabled + float32 + >>> y = layer(x) # Layer casts inputs since V2 dtype behavior is enabled + >>> print(y.dtype.name) + float32 + + A layer author can opt-out their layer from the automatic input casting by + passing `autocast=False` to the base Layer's constructor. This disables the + autocasting part of the V2 behavior for that layer, but not the defaulting to + floatx part of the V2 behavior. + + When a global `tf.keras.mixed_precision.Policy` is set, a Keras layer's dtype + will default to the global policy instead of floatx. Layers will automatically + cast inputs to the policy's compute_dtype. + """ + global V2_DTYPE_BEHAVIOR + V2_DTYPE_BEHAVIOR = True + + +def disable_v2_dtype_behavior(): + """Disables the V2 dtype behavior for Keras layers. + + See `tf.compat.v1.keras.layers.enable_v2_dtype_behavior`. + """ + global V2_DTYPE_BEHAVIOR + V2_DTYPE_BEHAVIOR = False + + +def v2_dtype_behavior_enabled(): + """Returns True if the V2 dtype behavior is enabled.""" + if V2_DTYPE_BEHAVIOR is None: + return tf2.enabled() + return V2_DTYPE_BEHAVIOR + + +class TrackableWeightHandler(object): + """Keras wrapper for handling tracking.Trackable object saving and restoring. + + This class handles Trackables in both V1 and V2 modes, ensuring that they can + be saved and restored with the correct data and without adding additional ops + on every save. + + Attributes: + trackable: The trackable to wrap. + num_tensors: The number of tensors that this trackable requires for saving. + """ + + def __init__(self, trackable): + if not isinstance(trackable, tracking.Trackable): + raise ValueError('%s is not a Trackable object.' % (trackable,)) + self._trackable = trackable + self._distribute_strategy = distribute_lib.get_strategy() + + saveables = saveable_object_util.saveable_objects_from_trackable( + trackable).values() + # 'Saveables' won't exist when we're passed a legacy TF1 table like + # a StaticHashTable. + if not saveables: + self._num_tensors = 0 + self._setter = lambda weights: None + self._getter = lambda: [] + + elif len(saveables) == 1: + saveable = list(saveables)[0] + + if ops.executing_eagerly_outside_functions(): + # If we're in eager mode, we need to defer calling the Trackable's + # saveable() callable until data export time. + # However, it is safe to call the saveable as many times as we want, so + # we will call it now to figure out how many tensors this Trackable will + # produce. + self._saveable = saveable + self._num_tensors = len(self._saveable().specs) + self._setter = lambda weights: self._saveable().restore(weights, None) + self._getter = lambda: [spec.tensor for spec in self._saveable().specs] + else: + # If we're in Graph mode, we need to evaluate the Saveable only once and + # cache the resulting restore graph. Failing to do this will result in + # new assignment ops being added to the graph each time set_weights() is + # called. + self._placeholder_tensors = [] + self._saveable = saveable() + self._num_tensors = len(self._saveable.specs) + for spec in self._saveable.specs: + tensor = spec.tensor + self._placeholder_tensors.append( + array_ops.placeholder(tensor.dtype, tensor.shape)) + self._assign_op = self._saveable.restore(self._placeholder_tensors, + None) + self._setter = self._set_weights_v1 + self._getter = lambda: [spec.tensor for spec in self._saveable.specs] + else: + raise ValueError('Only Trackables with one Saveable are supported. ' + 'The Trackable %s has %d Saveables.' % + (trackable, len(saveables))) + + @property + def num_tensors(self): + return self._num_tensors + + def set_weights(self, weights): + if len(weights) != self._num_tensors: + raise ValueError( + ('Weight handler for trackable %s received the wrong number of ' + + 'weights: expected %s, got %s.') % + (self._trackable, self._num_tensors, len(weights))) + self._setter(weights) + + def get_tensors(self): + return self._getter() + + def _set_weights_v1(self, weights): + feed_dict = {} + for idx, tensor in enumerate(weights): + feed_dict[self._placeholder_tensors[idx]] = tensor + backend.get_session().run(self._assign_op, feed_dict) + + +class StaticTableHandler(TrackableWeightHandler): + """Wrapper for handling weight collection for static hash tables.""" + + def __init__(self, getter_lambda): # pylint: disable=super-init-not-called + self._num_tensors = 2 + self._getter = getter_lambda + self._distribute_strategy = distribute_lib.get_strategy() + + def raise_error(_): + raise RuntimeError('This layer contains a static lookup table, which ' + 'cannot be changed via set_weights().') + + self._setter = raise_error + + +def no_ragged_support(inputs, layer_name): + input_list = nest.flatten(inputs) + if any(isinstance(x, ragged_tensor.RaggedTensor) for x in input_list): + raise ValueError('Layer %s does not support RaggedTensors as input. ' + 'Inputs received: %s. You can try converting your ' + 'input to an uniform tensor.' % (layer_name, inputs)) + + +def is_split_variable(v): + """Returns True if `v` is either a PartionedVariable or a ShardedVariable.""" + return hasattr(v, '_variable_list') or hasattr(v, '_variables') + + +def has_weights(obj): + obj_type = type(obj) + return (hasattr(obj_type, 'trainable_weights') and + hasattr(obj_type, 'non_trainable_weights') and + not isinstance(obj, type)) + + +# TODO(kathywu): This is a temporary hack. When a network of layers is revived +# from SavedModel, only the top-level layer will have losses. This causes issues +# in eager mode because the child layers may have graph losses +# (thus model.losses returns a mix of Eager and graph tensors). To fix this, +# whenever eager losses are added to one layer, add eager losses to all +# child layers. This causes `.losses` to only return eager losses. +REVIVED_LOSS_PLACEHOLDER = ( + 'This layer\'s losses have been added to the parent layer.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..3cb10b362125b46e24ff5fab85ac63d816eedb0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_layer_v1.py @@ -0,0 +1,2411 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Contains the base Layer class, from which all layers inherit.""" + +import collections +import functools +import itertools +import threading +import warnings + +import numpy as np + +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.mixed_precision import autocast_variable +from tensorflow.python.keras.mixed_precision import loss_scale_optimizer +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import object_identity +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +# A module that only depends on `keras.layers` import these from here. +from tensorflow.python.keras.utils.generic_utils import to_snake_case # pylint: disable=unused-import +from tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list # pylint: disable=unused-import +from tensorflow.python.module import module +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + + +# pylint: disable=g-classes-have-attributes +class Layer(base_layer.Layer): + """Base layer class. + + This is the class from which all layers inherit. + + A layer is a class implementing common neural networks operations, such + as convolution, batch norm, etc. These operations require managing weights, + losses, updates, and inter-layer connectivity. + + Users will just instantiate a layer and then treat it as a callable. + + We recommend that descendants of `Layer` implement the following methods: + + * `__init__()`: Save configuration in member variables + * `build()`: Called once from `__call__`, when we know the shapes of inputs + and `dtype`. Should have the calls to `add_weight()`, and then + call the super's `build()` (which sets `self.built = True`, which is + nice in case the user wants to call `build()` manually before the + first `__call__`). + * `call()`: Called in `__call__` after making sure `build()` has been called + once. Should actually perform the logic of applying the layer to the + input tensors (which should be passed in as the first argument). + + Args: + trainable: Boolean, whether the layer's variables should be trainable. + name: String name of the layer. + dtype: The dtype of the layer's computations and weights (default of + `None` means use `tf.keras.backend.floatx` in TensorFlow 2, or the type + of the first input in TensorFlow 1). + dynamic: Set this to `True` if your layer should only be run eagerly, and + should not be used to generate a static computation graph. + This would be the case for a Tree-RNN or a recursive network, + for example, or generally for any layer that manipulates tensors + using Python control flow. If `False`, we assume that the layer can + safely be used to generate a static computation graph. + + Attributes: + name: The name of the layer (string). + dtype: The dtype of the layer's computations and weights. If mixed + precision is used with a `tf.keras.mixed_precision.Policy`, this is + instead just the dtype of the layer's weights, as the computations are + done in a different dtype. + updates: List of update ops of this layer. + losses: List of losses added by this layer. + trainable_weights: List of variables to be included in backprop. + non_trainable_weights: List of variables that should not be + included in backprop. + weights: The concatenation of the lists trainable_weights and + non_trainable_weights (in this order). + trainable: Whether the layer should be trained (boolean). + input_spec: Optional (list of) `InputSpec` object(s) specifying the + constraints on inputs that can be accepted by the layer. + + Each layer has a dtype, which is typically the dtype of the layer's + computations and variables. A layer's dtype can be queried via the + `Layer.dtype` property. The dtype is specified with the `dtype` constructor + argument. In TensorFlow 2, the dtype defaults to `tf.keras.backend.floatx()` + if no dtype is passed. `floatx()` itself defaults to "float32". Additionally, + layers will cast their inputs to the layer's dtype in TensorFlow 2. When mixed + precision is used, layers may have different computation and variable dtypes. + See `tf.keras.mixed_precision.Policy` for details on layer dtypes. + """ + + # See tf.Module for the usage of this property. + # The key for _obj_reference_counts_dict is a Trackable, which could be a + # variable or layer etc. tf.Module._flatten will fail to flatten the key + # since it is trying to convert Trackable to a string. This attribute can be + # ignored even after the fix of nest lib, since the trackable object should + # already been available as individual attributes. _obj_reference_counts_dict + # just contains a copy of them. + _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain( + ('_obj_reference_counts_dict',), + module.Module._TF_MODULE_IGNORED_PROPERTIES + )) + + @trackable.no_automatic_dependency_tracking + def __init__(self, trainable=True, name=None, dtype=None, dynamic=False, + **kwargs): + self._instrument_layer_creation() + + # These properties should be set by the user via keyword arguments. + # note that 'dtype', 'input_shape' and 'batch_input_shape' + # are only applicable to input layers: do not pass these keywords + # to non-input layers. + allowed_kwargs = { + 'input_dim', 'input_shape', 'batch_input_shape', 'batch_size', + 'weights', 'activity_regularizer', 'autocast', 'implementation' + } + # Validate optional keyword arguments. + generic_utils.validate_kwargs(kwargs, allowed_kwargs) + + # Mutable properties + # Indicates whether the layer's weights are updated during training + # and whether the layer's updates are run during training. + self._trainable = trainable + # A stateful layer is a layer whose updates are run during inference too, + # for instance stateful RNNs. + self._stateful = False + # Indicates whether `build` needs to be called upon layer call, to create + # the layer's weights. + self.built = False + self._build_input_shape = None + # Provides information about which inputs are compatible with the layer. + self._input_spec = None + self.supports_masking = False + + self._init_set_name(name) + self._activity_regularizer = regularizers.get( + kwargs.pop('activity_regularizer', None)) + self._maybe_create_attribute('_trainable_weights', []) + self._maybe_create_attribute('_non_trainable_weights', []) + self._updates = [] + # Object to store all thread local layer properties. + self._thread_local = threading.local() + # A list of zero-argument lambdas which return Tensors, used for variable + # regularizers. + self._callable_losses = [] + # A list of symbolic Tensors containing activity regularizers and losses + # manually added through `add_loss` in graph-building mode. + self._losses = [] + # A list of metric instances corresponding to the symbolic metric tensors + # added using the `add_metric` API. + self._metrics = [] + + # Both graph and subclassed networks have a dtype policy. For graph + # networks, the policy's compute and variable dtypes are ignored. Such + # networks only use the policy if it is a PolicyV1, in which case it uses + # the PolicyV1's loss_scale (Policy does not have a loss_scale). For + # subclassed networks, the compute and variable dtypes are used as like any + # ordinary layer. + self._set_dtype_policy(dtype) + # Boolean indicating whether the layer automatically casts its inputs to the + # layer's compute_dtype. + self._autocast = kwargs.get('autocast', + base_layer_utils.v2_dtype_behavior_enabled()) + + # Dependencies tracked via attribute assignment. + # All layers in order of horizontal graph traversal. + # Entries are unique. For models includes input and output layers. + self._maybe_create_attribute('_self_tracked_trackables', []) + + # These lists will be filled via successive calls + # to self._add_inbound_node(). + # Used in symbolic mode only, only in conjunction with graph-networks + self._inbound_nodes_value = [] + self._outbound_nodes_value = [] + + self._init_call_fn_args() + + # Whether the `call` method can be used to build a TF graph without issues. + # This attribute has no effect if the model is created using the Functional + # API. Instead, `model.dynamic` is determined based on the internal layers. + self._dynamic = dynamic + + # Manage input shape information if passed. + if 'input_dim' in kwargs and 'input_shape' not in kwargs: + # Backwards compatibility: alias 'input_dim' to 'input_shape'. + kwargs['input_shape'] = (kwargs['input_dim'],) + if 'input_shape' in kwargs or 'batch_input_shape' in kwargs: + # In this case we will later create an input layer + # to insert before the current layer + if 'batch_input_shape' in kwargs: + batch_input_shape = tuple(kwargs['batch_input_shape']) + elif 'input_shape' in kwargs: + if 'batch_size' in kwargs: + batch_size = kwargs['batch_size'] + else: + batch_size = None + batch_input_shape = (batch_size,) + tuple(kwargs['input_shape']) + self._batch_input_shape = batch_input_shape + + # Manage initial weight values if passed. + self._initial_weights = kwargs.get('weights', None) + + # Whether the layer will track any layers that is set as attribute on itself + # as sub-layers, the weights from the sub-layers will be included in the + # parent layer's variables() as well. + # Default to True, which means auto tracking is turned on. Certain subclass + # might want to turn it off, like Sequential model. + self._auto_track_sub_layers = True + + # Mark this layer as having been originally built as a tf1 layer/model + self._originally_built_as_v1 = True + + # For backwards compat reasons, most built-in layers do not guarantee + # That they will 100% preserve the structure of input args when saving + # / loading configs. E.g. they may un-nest an arg that is + # a list with one element. + self._preserve_input_structure_in_config = False + + @trackable.no_automatic_dependency_tracking + @generic_utils.default + def build(self, input_shape): + """Creates the variables of the layer (optional, for subclass implementers). + + This is a method that implementers of subclasses of `Layer` or `Model` + can override if they need a state-creation step in-between + layer instantiation and layer call. + + This is typically used to create the weights of `Layer` subclasses. + + Args: + input_shape: Instance of `TensorShape`, or list of instances of + `TensorShape` if the layer expects a list of inputs + (one instance per input). + """ + if not hasattr(self.build, '_is_default'): + self._build_input_shape = input_shape + self.built = True + + @doc_controls.for_subclass_implementers + def call(self, inputs, **kwargs): # pylint: disable=unused-argument + """This is where the layer's logic lives. + + Args: + inputs: Input tensor, or list/tuple of input tensors. + **kwargs: Additional keyword arguments. + + Returns: + A tensor or list/tuple of tensors. + """ + return inputs + + @doc_controls.for_subclass_implementers + def _add_trackable(self, trackable_object, trainable): + """Adds a Trackable object to this layer's state. + + Args: + trackable_object: The tf.tracking.Trackable object to add. + trainable: Boolean, whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) or + "non_trainable_variables" (e.g. BatchNorm mean and variance). + + Returns: + The TrackableWeightHandler used to track this object. + """ + if isinstance(trackable_object, base_layer_utils.TrackableWeightHandler): + handler = trackable_object + else: + handler = base_layer_utils.TrackableWeightHandler(trackable_object) + if trainable: + self._trainable_weights.append(handler) + else: + self._non_trainable_weights.append(handler) + return handler + + @doc_controls.for_subclass_implementers + def add_weight(self, + name=None, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=None, + constraint=None, + partitioner=None, + use_resource=None, + synchronization=tf_variables.VariableSynchronization.AUTO, + aggregation=tf_variables.VariableAggregation.NONE, + **kwargs): + """Adds a new variable to the layer. + + Args: + name: Variable name. + shape: Variable shape. Defaults to scalar if unspecified. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + initializer: Initializer instance (callable). + regularizer: Regularizer instance (callable). + trainable: Boolean, whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) + or "non_trainable_variables" (e.g. BatchNorm mean and variance). + Note that `trainable` cannot be `True` if `synchronization` + is set to `ON_READ`. + constraint: Constraint instance (callable). + partitioner: Partitioner to be passed to the `Trackable` API. + use_resource: Whether to use `ResourceVariable`. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. If `synchronization` is set to `ON_READ`, + `trainable` must not be set to `True`. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + **kwargs: Additional keyword arguments. Accepted values are `getter`, + `collections`, `experimental_autocast` and `caching_device`. + + Returns: + The created variable. Usually either a `Variable` or `ResourceVariable` + instance. If `partitioner` is not `None`, a `PartitionedVariable` + instance is returned. + + Raises: + RuntimeError: If called with partitioned variable regularization and + eager execution is enabled. + ValueError: When giving unsupported dtype and no initializer or when + trainable has been set to True with synchronization set as `ON_READ`. + """ + if shape is None: + shape = () + # Validate optional keyword arguments. + for kwarg in kwargs: + if kwarg not in ['getter', 'collections', 'experimental_autocast', + 'caching_device']: + raise TypeError('Unknown keyword argument:', kwarg) + has_custom_getter = 'getter' in kwargs + getter = kwargs.pop('getter', base_layer_utils.make_variable) + collections_arg = kwargs.pop('collections', None) + # 'experimental_autocast' can be set to False by the caller to indicate an + # AutoCastVariable should never be created. + autocast = kwargs.pop('experimental_autocast', True) + # See the docstring for tf.Variable about the details for caching_device. + caching_device = kwargs.pop('caching_device', None) + + if dtype is None: + dtype = self.dtype or backend.floatx() + dtype = dtypes.as_dtype(dtype) + if self._dtype_policy.variable_dtype is None: + # The policy is "_infer", so we infer the policy from the variable dtype. + self._set_dtype_policy(policy.Policy(dtype.base_dtype.name)) + initializer = initializers.get(initializer) + regularizer = regularizers.get(regularizer) + constraint = constraints.get(constraint) + + if synchronization == tf_variables.VariableSynchronization.ON_READ: + if trainable: + raise ValueError( + 'Synchronization value can be set to ' + 'VariableSynchronization.ON_READ only for non-trainable variables. ' + 'You have specified trainable=True and ' + 'synchronization=VariableSynchronization.ON_READ.') + else: + # Set trainable to be false when variable is to be synced on read. + trainable = False + elif trainable is None: + trainable = True + + # Initialize variable when no initializer provided + if initializer is None: + # If dtype is DT_FLOAT, provide a uniform unit scaling initializer + if dtype.is_floating: + initializer = initializers.get('glorot_uniform') + # If dtype is DT_INT/DT_UINT, provide a default value `zero` + # If dtype is DT_BOOL, provide a default value `FALSE` + elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool: + initializer = initializers.zeros() + # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? + elif not has_custom_getter: + # When `getter` is specified, it's possibly fine for `initializer` to be + # None since it's up to the custom `getter` to raise error in case it + # indeed needs `initializer`. + raise ValueError('An initializer for variable %s of type %s is required' + ' for layer %s' % (name, dtype.base_dtype, self.name)) + + if (autocast and + self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype + and dtype.is_floating): + # Wrap 'getter' with a version that returns an AutoCastVariable. + old_getter = getter + def getter(*args, **kwargs): # pylint: disable=function-redefined + variable = old_getter(*args, **kwargs) + return autocast_variable.create_autocast_variable(variable) + # Also the caching_device does not work with the mixed precision API, + # disable it if it is specified. + # TODO(b/142020079): Reenable it once the bug is fixed. + if caching_device is not None: + tf_logging.warning( + '`caching_device` does not work with mixed precision API. Ignoring ' + 'user specified `caching_device`.') + caching_device = None + + variable = self._add_variable_with_custom_getter( + name=name, + shape=shape, + # TODO(allenl): a `make_variable` equivalent should be added as a + # `Trackable` method. + getter=getter, + # Manage errors in Layer rather than Trackable. + overwrite=True, + initializer=initializer, + dtype=dtype, + constraint=constraint, + trainable=trainable, + partitioner=partitioner, + use_resource=use_resource, + collections=collections_arg, + synchronization=synchronization, + aggregation=aggregation, + caching_device=caching_device) + if regularizer is not None: + # TODO(fchollet): in the future, this should be handled at the + # level of variable creation, and weight regularization losses + # should be variable attributes. + name_in_scope = variable.name[:variable.name.find(':')] + self._handle_weight_regularization(name_in_scope, + variable, + regularizer) + if base_layer_utils.is_split_variable(variable): + for v in variable: + backend.track_variable(v) + if trainable: + self._trainable_weights.append(v) + else: + self._non_trainable_weights.append(v) + else: + backend.track_variable(variable) + if trainable: + self._trainable_weights.append(variable) + else: + self._non_trainable_weights.append(variable) + return variable + + @generic_utils.default + def get_config(self): + """Returns the config of the layer. + + A layer config is a Python dictionary (serializable) + containing the configuration of a layer. + The same layer can be reinstantiated later + (without its trained weights) from this configuration. + + The config of a layer does not include connectivity + information, nor the layer class name. These are handled + by `Network` (one layer of abstraction above). + + Returns: + Python dictionary. + """ + all_args = tf_inspect.getfullargspec(self.__init__).args + config = {'name': self.name, 'trainable': self.trainable} + if hasattr(self, '_batch_input_shape'): + config['batch_input_shape'] = self._batch_input_shape + config['dtype'] = policy.serialize(self._dtype_policy) + if hasattr(self, 'dynamic'): + # Only include `dynamic` in the `config` if it is `True` + if self.dynamic: + config['dynamic'] = self.dynamic + elif 'dynamic' in all_args: + all_args.remove('dynamic') + expected_args = config.keys() + # Finds all arguments in the `__init__` that are not in the config: + extra_args = [arg for arg in all_args if arg not in expected_args] + # Check that either the only argument in the `__init__` is `self`, + # or that `get_config` has been overridden: + if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'): + raise NotImplementedError('Layers with arguments in `__init__` must ' + 'override `get_config`.') + return config + + @classmethod + def from_config(cls, config): + """Creates a layer from its config. + + This method is the reverse of `get_config`, + capable of instantiating the same layer from the config + dictionary. It does not handle layer connectivity + (handled by Network), nor weights (handled by `set_weights`). + + Args: + config: A Python dictionary, typically the + output of get_config. + + Returns: + A layer instance. + """ + return cls(**config) + + def compute_output_shape(self, input_shape): + """Computes the output shape of the layer. + + If the layer has not been built, this method will call `build` on the + layer. This assumes that the layer will later be used with inputs that + match the input shape provided here. + + Args: + input_shape: Shape tuple (tuple of integers) + or list of shape tuples (one per output tensor of the layer). + Shape tuples can include None for free dimensions, + instead of an integer. + + Returns: + An input shape tuple. + """ + if context.executing_eagerly(): + # In this case we build the model first in order to do shape inference. + # This is acceptable because the framework only calls + # `compute_output_shape` on shape values that the layer would later be + # built for. It would however cause issues in case a user attempts to + # use `compute_output_shape` manually with shapes that are incompatible + # with the shape the Layer will be called on (these users will have to + # implement `compute_output_shape` themselves). + self._maybe_build(input_shape) + with ops.get_default_graph().as_default(): + graph = func_graph.FuncGraph('graph') + with graph.as_default(): + input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) + inputs = nest.map_structure( + base_layer_utils.generate_placeholders_from_shape, input_shape) + try: + outputs = self(inputs, training=False) + except TypeError as e: + raise NotImplementedError( + 'We could not automatically infer the static shape of the ' + 'layer\'s output. Please implement the ' + '`compute_output_shape` method on your layer (%s).' % + self.__class__.__name__) from e + return nest.map_structure(lambda t: t.shape, outputs) + raise NotImplementedError + + @doc_controls.for_subclass_implementers + def compute_output_signature(self, input_signature): + """Compute the output tensor signature of the layer based on the inputs. + + Unlike a TensorShape object, a TensorSpec object contains both shape + and dtype information for a tensor. This method allows layers to provide + output dtype information if it is different from the input dtype. + For any layer that doesn't implement this function, + the framework will fall back to use `compute_output_shape`, and will + assume that the output dtype matches the input dtype. + + Args: + input_signature: Single TensorSpec or nested structure of TensorSpec + objects, describing a candidate input for the layer. + + Returns: + Single TensorSpec or nested structure of TensorSpec objects, describing + how the layer would transform the provided input. + + Raises: + TypeError: If input_signature contains a non-TensorSpec object. + """ + def check_type_return_shape(s): + if not isinstance(s, tensor.TensorSpec): + raise TypeError('Only TensorSpec signature types are supported, ' + 'but saw signature entry: {}.'.format(s)) + return s.shape + input_shape = nest.map_structure(check_type_return_shape, input_signature) + output_shape = self.compute_output_shape(input_shape) + dtype = self._compute_dtype + if dtype is None: + input_dtypes = [s.dtype for s in nest.flatten(input_signature)] + # Default behavior when self.dtype is None, is to use the first input's + # dtype. + dtype = input_dtypes[0] + return nest.map_structure( + lambda s: tensor.TensorSpec(dtype=dtype, shape=s), + output_shape) + + @generic_utils.default + def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument + """Computes an output mask tensor. + + Args: + inputs: Tensor or list of tensors. + mask: Tensor or list of tensors. + + Returns: + None or a tensor (or list of tensors, + one per output tensor of the layer). + """ + if not self.supports_masking: + if any(m is not None for m in nest.flatten(mask)): + raise TypeError('Layer ' + self.name + ' does not support masking, ' + 'but was passed an input_mask: ' + str(mask)) + # masking not explicitly supported: return None as mask. + return None + # if masking is explicitly supported, by default + # carry over the input mask + return mask + + def __call__(self, *args, **kwargs): + """Wraps `call`, applying pre- and post-processing steps. + + Args: + *args: Positional arguments to be passed to `self.call`. + **kwargs: Keyword arguments to be passed to `self.call`. + + Returns: + Output tensor(s). + + Note: + - The following optional keyword arguments are reserved for specific uses: + * `training`: Boolean scalar tensor of Python boolean indicating + whether the `call` is meant for training or inference. + * `mask`: Boolean input mask. + - If the layer's `call` method takes a `mask` argument (as some Keras + layers do), its default value will be set to the mask generated + for `inputs` by the previous layer (if `input` did come from + a layer that generated a corresponding mask, i.e. if it came from + a Keras layer with masking support. + + Raises: + ValueError: if the layer's `call` method returns None (an invalid value). + RuntimeError: if `super().__init__()` was not called in the constructor. + """ + self._assert_built_as_v1() + + if not hasattr(self, '_thread_local'): + raise RuntimeError( + 'You must call `super().__init__()` in the layer constructor.') + + # Grab the first positional or keyword argument. + if args: + inputs = args[0] + args = args[1:] + elif self._call_fn_args[0] in kwargs: + inputs = kwargs.pop(self._call_fn_args[0]) + else: + raise ValueError( + 'The first argument to `Layer.call` must always be passed.') + + call_context = base_layer_utils.call_context() + input_list = nest.flatten(inputs) + + # We will attempt to build a TF graph if & only if all inputs are symbolic. + # This is always the case in graph mode. It can also be the case in eager + # mode when all inputs can be traced back to `keras.Input()` (when building + # models using the functional API). + build_graph = tf_utils.are_all_symbolic_tensors(input_list) + + # Accept NumPy and scalar inputs by converting to Tensors. + if any(isinstance(x, (np.ndarray, float, int)) for x in input_list): + def _convert_non_tensor(x): + # Don't call `tensor_conversion.convert_to_tensor` on all `inputs` + # because `SparseTensors` can't be converted to `Tensor`. + if isinstance(x, (np.ndarray, float, int)): + return tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + return x + inputs = nest.map_structure(_convert_non_tensor, inputs) + input_list = nest.flatten(inputs) + + # Handle `mask` propagation from previous layer to current layer. Masks can + # be propagated explicitly via the `mask` argument, or implicitly via + # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed + # explicitly take priority. + mask_arg_passed_by_framework = False + input_masks = self._collect_input_masks(inputs, args, kwargs) + if (self._expects_mask_arg and input_masks is not None and + not self._call_arg_was_passed('mask', args, kwargs)): + mask_arg_passed_by_framework = True + kwargs['mask'] = input_masks + + # If `training` argument is None or not explicitly passed, + # propagate `training` value from this layer's calling layer. + training_value = None + training_arg_passed_by_framework = False + # Priority 1: `training` was explicitly passed. + if self._call_arg_was_passed('training', args, kwargs): + training_value = self._get_call_arg_value('training', args, kwargs) + if not self._expects_training_arg: + kwargs.pop('training') + + if training_value is None: + # Priority 2: `training` was passed to a parent layer. + if call_context.training is not None: + training_value = call_context.training + # Priority 3a: `learning_phase()` has been set. + elif backend.global_learning_phase_is_set(): + training_value = backend.learning_phase() + # Priority 3b: Pass the `learning_phase()` if in the Keras FuncGraph. + elif build_graph: + with backend.get_graph().as_default(): + if base_layer_utils.is_in_keras_graph(): + training_value = backend.learning_phase() + + if self._expects_training_arg and training_value is not None: + # Force the training_value to be bool type which matches to the contract + # for layer/model call args. + if tensor_util.is_tf_type(training_value): + training_value = math_ops.cast(training_value, dtypes.bool) + else: + training_value = bool(training_value) + args, kwargs = self._set_call_arg_value( + 'training', training_value, args, kwargs) + training_arg_passed_by_framework = True + + # Only create Keras history if at least one tensor originates from a + # `keras.Input`. Otherwise this Layer may be being used outside the Keras + # framework. + if build_graph and base_layer_utils.needs_keras_history(inputs): + base_layer_utils.create_keras_history(inputs) + + with call_context.enter(self, inputs, build_graph, training_value): + # Check input assumptions set after layer building, e.g. input shape. + if build_graph: + # Symbolic execution on symbolic tensors. We will attempt to build + # the corresponding TF subgraph inside `backend.get_graph()` + input_spec.assert_input_compatibility(self.input_spec, inputs, + self.name) + graph = backend.get_graph() + with graph.as_default(), backend.name_scope(self._name_scope()): # pylint: disable=not-callable + # Build layer if applicable (if the `build` method has been + # overridden). + self._maybe_build(inputs) + cast_inputs = self._maybe_cast_inputs(inputs) + + # Wrapping `call` function in autograph to allow for dynamic control + # flow and control dependencies in call. We are limiting this to + # subclassed layers as autograph is strictly needed only for + # subclassed layers and models. + # tf_convert will respect the value of autograph setting in the + # enclosing tf.function, if any. + if (base_layer_utils.is_subclassed(self) and + not base_layer_utils.from_saved_model(self)): + call_fn = autograph.tf_convert( + self.call, ag_ctx.control_status_ctx()) + else: + call_fn = self.call + + if not self.dynamic: + try: + with autocast_variable.enable_auto_cast_variables( + self._compute_dtype_object): + outputs = call_fn(cast_inputs, *args, **kwargs) + + except errors.OperatorNotAllowedInGraphError as e: + raise TypeError('You are attempting to use Python control ' + 'flow in a layer that was not declared to be ' + 'dynamic. Pass `dynamic=True` to the class ' + 'constructor.\nEncountered error:\n"""\n' + + str(e) + '\n"""') + else: + # We will use static shape inference to return symbolic tensors + # matching the specifications of the layer outputs. + # Since `self.dynamic` is True, we will never attempt to + # run the underlying TF graph (which is disconnected). + # TODO(fchollet): consider py_func as an alternative, which + # would enable us to run the underlying graph if needed. + outputs = self._symbolic_call(inputs) + + if outputs is None: + raise ValueError('A layer\'s `call` method should return a ' + 'Tensor or a list of Tensors, not None ' + '(layer: ' + self.name + ').') + if base_layer_utils.have_all_keras_metadata(inputs): + if training_arg_passed_by_framework: + args, kwargs = self._set_call_arg_value( + 'training', None, args, kwargs, pop_kwarg_if_none=True) + if mask_arg_passed_by_framework: + kwargs.pop('mask') + outputs = self._set_connectivity_metadata((inputs,) + args, kwargs, + outputs) + self._handle_activity_regularization(inputs, outputs) + self._set_mask_metadata(inputs, outputs, input_masks) + if hasattr(self, '_set_inputs') and not self.inputs: + # Subclassed network: explicitly set metadata normally set by + # a call to self._set_inputs(). + # TODO(b/120997007): This should be done in Eager as well, but + # causes garbage collection issues because of the placeholders + # created on the default Keras graph. + self._set_inputs(inputs, outputs) + else: + # Eager execution on data tensors. + with backend.name_scope(self._name_scope()): # pylint: disable=not-callable + self._maybe_build(inputs) + cast_inputs = self._maybe_cast_inputs(inputs) + with autocast_variable.enable_auto_cast_variables( + self._compute_dtype_object): + outputs = self.call(cast_inputs, *args, **kwargs) + self._handle_activity_regularization(inputs, outputs) + self._set_mask_metadata(inputs, outputs, input_masks) + + return outputs + + def _assert_built_as_v1(self): + if not hasattr(self, '_originally_built_as_v1'): + raise ValueError( + 'Your Layer or Model is in an invalid state. ' + 'This can happen for the following cases:\n ' + '1. You might be interleaving estimator/non-estimator models or ' + 'interleaving models/layers made in tf.compat.v1.Graph.as_default() ' + 'with models/layers created outside of it. ' + 'Converting a model to an estimator (via model_to_estimator) ' + 'invalidates all models/layers made before the conversion (even ' + 'if they were not the model converted to an estimator). ' + 'Similarly, making a layer or a model inside a ' + 'a tf.compat.v1.Graph invalidates all layers/models you previously ' + 'made outside of the graph.\n' + '2. You might be using a custom keras layer implementation with ' + ' custom __init__ which didn\'t call super().__init__. ' + ' Please check the implementation of %s and its bases.' % + (type(self),)) + + @property + def dtype(self): + return self._dtype_policy.variable_dtype + + @property + def name(self): + return self._name + + @property + def dynamic(self): + return any(layer._dynamic for layer in self._flatten_layers()) + + @property + @doc_controls.do_not_generate_docs + def stateful(self): + return any(layer._stateful for layer in self._flatten_layers()) + + @stateful.setter + def stateful(self, value): + self._stateful = value + + @property + def trainable(self): + return self._trainable + + @trainable.setter + def trainable(self, value): + self._trainable = value + for layer in getattr(self, '_self_tracked_trackables', []): + layer.trainable = value + + @property + def activity_regularizer(self): + """Optional regularizer function for the output of this layer.""" + return self._activity_regularizer + + @activity_regularizer.setter + def activity_regularizer(self, regularizer): + """Optional regularizer function for the output of this layer.""" + self._activity_regularizer = regularizer + + @property + def input_spec(self): + return self._input_spec + + @input_spec.setter + # Must be decorated to prevent tracking, since the input_spec can be nested + # InputSpec objects. + @trackable.no_automatic_dependency_tracking + def input_spec(self, value): + for v in nest.flatten(value): + if v is not None and not isinstance(v, base_layer.InputSpec): + raise TypeError('Layer input_spec must be an instance of InputSpec. ' + 'Got: {}'.format(v)) + self._input_spec = value + + @property + def updates(self): + collected_updates = [] + all_layers = self._flatten_layers() + with backend.get_graph().as_default(): + for layer in all_layers: + if not layer.trainable and not layer.stateful: + continue + for u in layer._updates: + if callable(u): + try: + u = u() + except ValueError as e: + if 'InaccessibleTensorError' in type(e).__name__: + # For one specific case of error we try to raise + # a more meaningful error message about the graph if we can. + # This error is an internal TF symbol that is not + # publicly exposed, so we check the name directly rather + # than using a direct import. + base_layer_utils.check_graph_consistency( + method='add_update', force_raise=True) + raise # check_graph_consistency may not always raise. + base_layer_utils.check_graph_consistency(u, method='add_update') + collected_updates.append(u) + return collected_updates + + @property + def losses(self): + """Losses which are associated with this `Layer`. + + Variable regularization tensors are created when this property is accessed, + so it is eager safe: accessing `losses` under a `tf.GradientTape` will + propagate gradients back to the corresponding variables. + + Returns: + A list of tensors. + """ + collected_losses = [] + all_layers = self._flatten_layers() + for layer in all_layers: + # If any eager losses are present, we assume the model to be part of an + # eager training loop (either a custom one or the one used when + # `run_eagerly=True`) and so we always return just the eager losses. + collected_losses.extend(layer._losses) + for regularizer in layer._callable_losses: + loss_tensor = regularizer() + if loss_tensor is not None: + collected_losses.append(loss_tensor) + return collected_losses + + @doc_controls.for_subclass_implementers + def add_loss(self, losses, inputs=None): + """Add loss tensor(s), potentially dependent on layer inputs. + + Some losses (for instance, activity regularization losses) may be dependent + on the inputs passed when calling a layer. Hence, when reusing the same + layer on different inputs `a` and `b`, some entries in `layer.losses` may + be dependent on `a` and some on `b`. This method automatically keeps track + of dependencies. + + This method can be used inside a subclassed layer or model's `call` + function, in which case `losses` should be a Tensor or list of Tensors. + + Example: + + ```python + class MyLayer(tf.keras.layers.Layer): + def call(inputs, self): + self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True) + return inputs + ``` + + This method can also be called directly on a Functional Model during + construction. In this case, any loss Tensors passed to this Model must + be symbolic and be able to be traced back to the model's `Input`s. These + losses become part of the model's topology and are tracked in `get_config`. + + Example: + + ```python + inputs = tf.keras.Input(shape=(10,)) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + # Activity regularization. + model.add_loss(tf.abs(tf.reduce_mean(x))) + ``` + + If this is not the case for your loss (if, for example, your loss references + a `Variable` of one of the model's layers), you can wrap your loss in a + zero-argument lambda. These losses are not tracked as part of the model's + topology since they can't be serialized. + + Example: + + ```python + inputs = tf.keras.Input(shape=(10,)) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Dense(1)(x) + model = tf.keras.Model(inputs, outputs) + # Weight regularization. + model.add_loss(lambda: tf.reduce_mean(x.kernel)) + ``` + + The `get_losses_for` method allows to retrieve the losses relevant to a + specific set of inputs. + + Args: + losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses + may also be zero-argument callables which create a loss tensor. + inputs: Ignored when executing eagerly. If anything other than None is + passed, it signals the losses are conditional on some of the layer's + inputs, and thus they should only be run where these inputs are + available. This is the case for activity regularization losses, for + instance. If `None` is passed, the losses are assumed + to be unconditional, and will apply across all dataflows of the layer + (e.g. weight regularization losses). + """ + def _tag_unconditional(loss): + """Process the loss and tag it by setting loss._unconditional_loss.""" + if callable(loss): + # We run the loss without autocasting, as regularizers are often + # numerically unstable in float16. + with autocast_variable.enable_auto_cast_variables(None): + loss = loss() + if loss is None: + return None # Will be filtered out when computing the .losses property + if not tensor_util.is_tf_type(loss): + loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( + loss, dtype=backend.floatx() + ) + loss._unconditional_loss = (inputs is None) # pylint: disable=protected-access + return loss + + losses = nest.flatten(losses) + + callable_losses = [] + symbolic_losses = [] + for loss in losses: + if callable(loss): + callable_losses.append(functools.partial(_tag_unconditional, loss)) + continue + if loss is None: + continue + if not tensor_util.is_tf_type(loss): + loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( + loss, dtype=backend.floatx() + ) + # TF Functions should take the eager path. + if (tf_utils.is_symbolic_tensor(loss) and + not base_layer_utils.is_in_tf_function()): + symbolic_losses.append(_tag_unconditional(loss)) + base_layer_utils.check_graph_consistency(loss, method='add_loss') + + self._callable_losses.extend(callable_losses) + + in_call_context = base_layer_utils.call_context().in_call + + if in_call_context: + for symbolic_loss in symbolic_losses: + self._losses.append(symbolic_loss) + else: + for symbolic_loss in symbolic_losses: + if getattr(self, '_is_graph_network', False): + self._graph_network_add_loss(symbolic_loss) + else: + # Possible a loss was added in a Layer's `build`. + self._losses.append(symbolic_loss) + + @property + def metrics(self): + collected_metrics = [] + for layer in self._flatten_layers(): + collected_metrics.extend(layer._metrics) + return collected_metrics + + @doc_controls.for_subclass_implementers + def add_metric(self, value, aggregation=None, name=None): + """Adds metric tensor to the layer. + + Args: + value: Metric tensor. + aggregation: Sample-wise metric reduction function. If `aggregation=None`, + it indicates that the metric tensor provided has been aggregated + already. eg, `bin_acc = BinaryAccuracy(name='acc')` followed by + `model.add_metric(bin_acc(y_true, y_pred))`. If aggregation='mean', the + given metric tensor will be sample-wise reduced using `mean` function. + eg, `model.add_metric(tf.reduce_sum(outputs), name='output_mean', + aggregation='mean')`. + name: String metric name. + + Raises: + ValueError: If `aggregation` is anything other than None or `mean`. + """ + if aggregation is not None and aggregation != 'mean': + raise ValueError( + 'We currently support only `mean` sample-wise metric aggregation. ' + 'You provided aggregation=`%s`' % aggregation) + + from_metric_obj = hasattr(value, '_metric_obj') + is_symbolic = tf_utils.is_symbolic_tensor(value) + in_call_context = base_layer_utils.call_context().in_call + + if name is None and not from_metric_obj: + # Eg. `self.add_metric(math_ops.reduce_sum(x), aggregation='mean')` + # In eager mode, we use metric name to lookup a metric. Without a name, + # a new Mean metric wrapper will be created on every model/layer call. + # So, we raise an error when no name is provided. + # We will do the same for symbolic mode for consistency although a name + # will be generated if no name is provided. + + # We will not raise this error in the foll use case for the sake of + # consistency as name in provided in the metric constructor. + # mean = metrics.Mean(name='my_metric') + # model.add_metric(mean(outputs)) + raise ValueError('Please provide a name for your metric like ' + '`self.add_metric(tf.reduce_sum(inputs), ' + 'name=\'mean_activation\', aggregation=\'mean\')`') + elif from_metric_obj: + name = value._metric_obj.name + + if in_call_context: + # TF Function path should take the eager path. + self._symbolic_add_metric(value, aggregation, name) + else: + if not is_symbolic: + raise ValueError('Expected a symbolic Tensor for the metric value, ' + 'received: ' + str(value)) + + # Possible a metric was added in a Layer's `build`. + if not getattr(self, '_is_graph_network', False): + with backend.get_graph().as_default(): + self._symbolic_add_metric(value, aggregation, name) + return + + if from_metric_obj: + raise ValueError('Using the result of calling a `Metric` object ' + 'when calling `add_metric` on a Functional ' + 'Model is not supported. Please pass the ' + 'Tensor to monitor directly.') + + # Insert layers into the Keras Graph Network. + self._graph_network_add_metric(value, aggregation, name) + + @doc_controls.for_subclass_implementers + def add_update(self, updates, inputs=None): + """Add update op(s), potentially dependent on layer inputs. + + Weight updates (for instance, the updates of the moving mean and variance + in a BatchNormalization layer) may be dependent on the inputs passed + when calling a layer. Hence, when reusing the same layer on + different inputs `a` and `b`, some entries in `layer.updates` may be + dependent on `a` and some on `b`. This method automatically keeps track + of dependencies. + + The `get_updates_for` method allows to retrieve the updates relevant to a + specific set of inputs. + + This call is ignored when eager execution is enabled (in that case, variable + updates are run on the fly and thus do not need to be tracked for later + execution). + + Args: + updates: Update op, or list/tuple of update ops, or zero-arg callable + that returns an update op. A zero-arg callable should be passed in + order to disable running the updates by setting `trainable=False` + on this Layer, when executing in Eager mode. + inputs: Deprecated, will be automatically inferred. + """ + if inputs is not None: + tf_logging.warning( + '`add_update` `inputs` kwarg has been deprecated. You no longer need ' + 'to pass a value to `inputs` as it is being automatically inferred.') + call_context = base_layer_utils.call_context() + + if (distribute_lib.has_strategy() and + distribute_lib.in_cross_replica_context() and + # When saving the model, the distribution strategy context should be + # ignored, following the default path for adding updates. + not call_context.saving): + # Updates don't need to be run in a cross-replica context. + return + + updates = generic_utils.to_list(updates) + + if call_context.in_call: + relevant_inputs = call_context.inputs + else: + inbound_nodes = getattr(self, '_inbound_nodes', []) + relevant_inputs = [node.input_tensors for node in inbound_nodes] + + def process_update(x): + """Standardize update ops. + + Args: + x: Tensor, op, or callable. + + Returns: + An update op. + """ + if callable(x): + update = lambda: process_update(x()) + return update() + elif isinstance(x, ops.Operation): + update = x + elif hasattr(x, 'op'): + update = x.op + else: + update = tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + + reachable = tf_utils.get_reachable_from_inputs(relevant_inputs, [update]) + update._unconditional_update = update not in reachable + return update + + updates = [process_update(x) for x in updates] + self._updates.extend(updates) + + def set_weights(self, weights): + """Sets the weights of the layer, from Numpy arrays. + + The weights of a layer represent the state of the layer. This function + sets the weight values from numpy arrays. The weight values should be + passed in the order they are created by the layer. Note that the layer's + weights must be instantiated before calling this function by calling + the layer. + + For example, a Dense layer returns a list of two values-- per-output + weights and the bias value. These can be used to set the weights of another + Dense layer: + + >>> a = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(1.)) + >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]])) + >>> a.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + >>> b = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(2.)) + >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]])) + >>> b.get_weights() + [array([[2.], + [2.], + [2.]], dtype=float32), array([0.], dtype=float32)] + >>> b.set_weights(a.get_weights()) + >>> b.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + + Args: + weights: a list of Numpy arrays. The number + of arrays and their shape must match + number of the dimensions of the weights + of the layer (i.e. it should match the + output of `get_weights`). + + Raises: + ValueError: If the provided weights list does not match the + layer's specifications. + """ + params = self.weights + + expected_num_weights = 0 + for param in params: + if isinstance(param, base_layer_utils.TrackableWeightHandler): + expected_num_weights += param.num_tensors + else: + expected_num_weights += 1 + + if expected_num_weights != len(weights): + raise ValueError( + 'You called `set_weights(weights)` on layer "%s" ' + 'with a weight list of length %s, but the layer was ' + 'expecting %s weights. Provided weights: %s...' % + (self.name, len(weights), expected_num_weights, str(weights)[:50])) + + weight_index = 0 + weight_value_tuples = [] + for param in params: + if isinstance(param, base_layer_utils.TrackableWeightHandler): + num_tensors = param.num_tensors + tensors = weights[weight_index:weight_index + num_tensors] + param.set_weights(tensors) + weight_index += num_tensors + else: + weight = weights[weight_index] + weight_shape = weight.shape if hasattr(weight, 'shape') else () + ref_shape = param.shape + if not ref_shape.is_compatible_with(weight_shape): + raise ValueError( + 'Layer weight shape %s not compatible with provided weight ' + 'shape %s' % (ref_shape, weight_shape)) + weight_value_tuples.append((param, weight)) + weight_index += 1 + + backend.batch_set_value(weight_value_tuples) + + def get_weights(self): + """Returns the current weights of the layer. + + The weights of a layer represent the state of the layer. This function + returns both trainable and non-trainable weight values associated with this + layer as a list of Numpy arrays, which can in turn be used to load state + into similarly parameterized layers. + + For example, a Dense layer returns a list of two values-- per-output + weights and the bias value. These can be used to set the weights of another + Dense layer: + + >>> a = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(1.)) + >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]])) + >>> a.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + >>> b = tf.keras.layers.Dense(1, + ... kernel_initializer=tf.constant_initializer(2.)) + >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]])) + >>> b.get_weights() + [array([[2.], + [2.], + [2.]], dtype=float32), array([0.], dtype=float32)] + >>> b.set_weights(a.get_weights()) + >>> b.get_weights() + [array([[1.], + [1.], + [1.]], dtype=float32), array([0.], dtype=float32)] + + Returns: + Weights values as a list of numpy arrays. + """ + weights = self.weights + output_weights = [] + for weight in weights: + if isinstance(weight, base_layer_utils.TrackableWeightHandler): + output_weights.extend(weight.get_tensors()) + else: + output_weights.append(weight) + return backend.batch_get_value(output_weights) + + def get_updates_for(self, inputs): + """Retrieves updates relevant to a specific set of inputs. + + Args: + inputs: Input tensor or list/tuple of input tensors. + + Returns: + List of update ops of the layer that depend on `inputs`. + """ + if inputs is None: + # Requesting unconditional updates. + return [u for u in self.updates if u._unconditional_update] + + # Requesting input-conditional updates. + updates = [u for u in self.updates if not u._unconditional_update] + inputs = nest.flatten(inputs) + reachable = tf_utils.get_reachable_from_inputs(inputs, updates) + return [u for u in updates if u in reachable] + + def get_losses_for(self, inputs): + """Retrieves losses relevant to a specific set of inputs. + + Args: + inputs: Input tensor or list/tuple of input tensors. + + Returns: + List of loss tensors of the layer that depend on `inputs`. + """ + if inputs is None: + # Requesting unconditional losses. + return [l for l in self.losses if l._unconditional_loss] + + # Requesting input-conditional losses. + losses = [l for l in self.losses if not l._unconditional_loss] + inputs = nest.flatten(inputs) + reachable = tf_utils.get_reachable_from_inputs(inputs, losses) + return [l for l in losses if l in reachable] + + def get_input_mask_at(self, node_index): + """Retrieves the input mask tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A mask tensor + (or list of tensors if the layer has multiple inputs). + """ + inputs = self.get_input_at(node_index) + if isinstance(inputs, list): + return [getattr(x, '_keras_mask', None) for x in inputs] + else: + return getattr(inputs, '_keras_mask', None) + + def get_output_mask_at(self, node_index): + """Retrieves the output mask tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A mask tensor + (or list of tensors if the layer has multiple outputs). + """ + output = self.get_output_at(node_index) + if isinstance(output, list): + return [getattr(x, '_keras_mask', None) for x in output] + else: + return getattr(output, '_keras_mask', None) + + @property + def input_mask(self): + """Retrieves the input mask tensor(s) of a layer. + + Only applicable if the layer has exactly one inbound node, + i.e. if it is connected to one incoming layer. + + Returns: + Input mask tensor (potentially None) or list of input + mask tensors. + + Raises: + AttributeError: if the layer is connected to + more than one incoming layers. + """ + inputs = self.input + if isinstance(inputs, list): + return [getattr(x, '_keras_mask', None) for x in inputs] + else: + return getattr(inputs, '_keras_mask', None) + + @property + def output_mask(self): + """Retrieves the output mask tensor(s) of a layer. + + Only applicable if the layer has exactly one inbound node, + i.e. if it is connected to one incoming layer. + + Returns: + Output mask tensor (potentially None) or list of output + mask tensors. + + Raises: + AttributeError: if the layer is connected to + more than one incoming layers. + """ + output = self.output + if isinstance(output, list): + return [getattr(x, '_keras_mask', None) for x in output] + else: + return getattr(output, '_keras_mask', None) + + def get_input_shape_at(self, node_index): + """Retrieves the input shape(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A shape tuple + (or list of shape tuples if the layer has multiple inputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'input_shapes', + 'input shape') + + def get_output_shape_at(self, node_index): + """Retrieves the output shape(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first time the layer was called. + + Returns: + A shape tuple + (or list of shape tuples if the layer has multiple outputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'output_shapes', + 'output shape') + + def get_input_at(self, node_index): + """Retrieves the input tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first input node of the layer. + + Returns: + A tensor (or list of tensors if the layer has multiple inputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'input_tensors', + 'input') + + def get_output_at(self, node_index): + """Retrieves the output tensor(s) of a layer at a given node. + + Args: + node_index: Integer, index of the node + from which to retrieve the attribute. + E.g. `node_index=0` will correspond to the + first output node of the layer. + + Returns: + A tensor (or list of tensors if the layer has multiple outputs). + + Raises: + RuntimeError: If called in Eager mode. + """ + return self._get_node_attribute_at_index(node_index, 'output_tensors', + 'output') + + @property + def input(self): + """Retrieves the input tensor(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer. + + Returns: + Input tensor or list of input tensors. + + Raises: + RuntimeError: If called in Eager mode. + AttributeError: If no inbound nodes are found. + """ + if not self._inbound_nodes: + raise AttributeError('Layer ' + self.name + + ' is not connected, no input to return.') + return self._get_node_attribute_at_index(0, 'input_tensors', 'input') + + @property + def output(self): + """Retrieves the output tensor(s) of a layer. + + Only applicable if the layer has exactly one output, + i.e. if it is connected to one incoming layer. + + Returns: + Output tensor or list of output tensors. + + Raises: + AttributeError: if the layer is connected to more than one incoming + layers. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('Layer ' + self.name + ' has no inbound nodes.') + return self._get_node_attribute_at_index(0, 'output_tensors', 'output') + + @property + def input_shape(self): + """Retrieves the input shape(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer, or if all inputs + have the same shape. + + Returns: + Input shape, as an integer shape tuple + (or list of shape tuples, one tuple per input tensor). + + Raises: + AttributeError: if the layer has no defined input_shape. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('The layer has never been called ' + 'and thus has no defined input shape.') + all_input_shapes = set( + [str(node.input_shapes) for node in self._inbound_nodes]) + if len(all_input_shapes) == 1: + return self._inbound_nodes[0].input_shapes + else: + raise AttributeError('The layer "' + str(self.name) + + ' has multiple inbound nodes, ' + 'with different input shapes. Hence ' + 'the notion of "input shape" is ' + 'ill-defined for the layer. ' + 'Use `get_input_shape_at(node_index)` ' + 'instead.') + + def count_params(self): + """Count the total number of scalars composing the weights. + + Returns: + An integer count. + + Raises: + ValueError: if the layer isn't yet built + (in which case its weights aren't yet defined). + """ + if not self.built: + if getattr(self, '_is_graph_network', False): + with tf_utils.maybe_init_scope(self): + self._maybe_build(self.inputs) + else: + raise ValueError('You tried to call `count_params` on ' + self.name + + ', but the layer isn\'t built. ' + 'You can build it manually via: `' + self.name + + '.build(batch_input_shape)`.') + return layer_utils.count_params(self.weights) + + @property + def output_shape(self): + """Retrieves the output shape(s) of a layer. + + Only applicable if the layer has one output, + or if all outputs have the same shape. + + Returns: + Output shape, as an integer shape tuple + (or list of shape tuples, one tuple per output tensor). + + Raises: + AttributeError: if the layer has no defined output shape. + RuntimeError: if called in Eager mode. + """ + if not self._inbound_nodes: + raise AttributeError('The layer has never been called ' + 'and thus has no defined output shape.') + all_output_shapes = set( + [str(node.output_shapes) for node in self._inbound_nodes]) + if len(all_output_shapes) == 1: + return self._inbound_nodes[0].output_shapes + else: + raise AttributeError('The layer "%s"' + ' has multiple inbound nodes, ' + 'with different output shapes. Hence ' + 'the notion of "output shape" is ' + 'ill-defined for the layer. ' + 'Use `get_output_shape_at(node_index)` ' + 'instead.' % self.name) + + @property + @doc_controls.do_not_doc_inheritable + def inbound_nodes(self): + """Deprecated, do NOT use! Only for compatibility with external Keras.""" + return self._inbound_nodes + + @property + @doc_controls.do_not_doc_inheritable + def outbound_nodes(self): + """Deprecated, do NOT use! Only for compatibility with external Keras.""" + return self._outbound_nodes + + ############################################################################## + # Methods & attributes below are public aliases of other methods. # + ############################################################################## + + @doc_controls.do_not_doc_inheritable + def apply(self, inputs, *args, **kwargs): + """Deprecated, do NOT use! + + This is an alias of `self.__call__`. + + Args: + inputs: Input tensor(s). + *args: additional positional arguments to be passed to `self.call`. + **kwargs: additional keyword arguments to be passed to `self.call`. + + Returns: + Output tensor(s). + """ + warnings.warn('`layer.apply` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.__call__` method instead.') + return self.__call__(inputs, *args, **kwargs) + + @doc_controls.do_not_doc_inheritable + def add_variable(self, *args, **kwargs): + """Deprecated, do NOT use! Alias for `add_weight`.""" + warnings.warn('`layer.add_variable` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `layer.add_weight` method instead.') + return self.add_weight(*args, **kwargs) + + @property + def variables(self): + """Returns the list of all layer variables/weights. + + Alias of `self.weights`. + + Returns: + A list of variables. + """ + return self.weights + + @property + def trainable_variables(self): + return self.trainable_weights + + @property + def non_trainable_variables(self): + return self.non_trainable_weights + + ############################################################################## + # Methods & attributes below are all private and only used by the framework. # + ############################################################################## + + @property + def _inbound_nodes(self): + return self._inbound_nodes_value + + @_inbound_nodes.setter + @trackable.no_automatic_dependency_tracking + def _inbound_nodes(self, value): + self._inbound_nodes_value = value + + @property + def _outbound_nodes(self): + return self._outbound_nodes_value + + @_outbound_nodes.setter + @trackable.no_automatic_dependency_tracking + def _outbound_nodes(self, value): + self._outbound_nodes_value = value + + def _set_dtype_policy(self, dtype): + """Sets self._dtype_policy.""" + if isinstance(dtype, policy.Policy): + self._dtype_policy = dtype + elif isinstance(dtype, dict): + self._dtype_policy = policy.deserialize(dtype) + elif isinstance(dtype, str) and dtype in ('mixed_float16', + 'mixed_bfloat16'): + # The isinstance check is required since np.dtype raises an error if + # compared to a non-dtype string. + self._dtype_policy = policy.Policy(dtype) + elif dtype: + self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name) + else: + self._dtype_policy = policy.global_policy() + if (self._dtype_policy.name == 'mixed_float16' and + not loss_scale_optimizer.strategy_supports_loss_scaling()): + # Although only loss scaling doesn't support certain strategies, to avoid + # confusion, we disallow the 'mixed_float16' policy with unsupported + # strategies. This is because 'mixed_float16' requires loss scaling for + # numeric stability. + strategy = distribute_lib.get_strategy() + raise ValueError('Mixed precision is not supported with the ' + 'tf.distribute.Strategy: %s. Either stop using mixed ' + 'precision by removing the use of the "%s" policy or ' + 'use a different Strategy, e.g. a MirroredStrategy.' % + (strategy.__class__.__name__, self._dtype_policy.name)) + + # Performance optimization: cache the compute dtype as a Dtype object or + # None, so that str to Dtype conversion doesn't happen in Layer.__call__. + if self._dtype_policy.compute_dtype: + self._compute_dtype_object = dtypes.as_dtype( + self._dtype_policy.compute_dtype) + else: + self._compute_dtype_object = None + + # TODO(reedwm): Expose this property? + @property + def _compute_dtype(self): + """The layer's compute dtype. + + Unless mixed-precision is used, this is the same as `Layer.dtype`. + + If self._autocast is True, layer's will cast floating-point inputs to this. + + Returns: + The layer's compute dtype. + """ + return self._dtype_policy.compute_dtype + + def _maybe_cast_inputs(self, inputs): + """Maybe casts the inputs to the compute dtype. + + If self._compute_dtype is floating-point, and self_autocast is True, + floating-point inputs are casted to self._compute_dtype. + + Args: + inputs: Input tensor, or structure of input tensors. + + Returns: + `inputs`, but tensors may have been casted to self._compute_dtype + """ + compute_dtype = self._compute_dtype + if (self._autocast and compute_dtype and + dtypes.as_dtype(compute_dtype).is_floating): + def f(x): + """Cast a single Tensor or TensorSpec to the compute dtype.""" + cast_types = (tensor.Tensor, sparse_tensor.SparseTensor, + ragged_tensor.RaggedTensor) + if (isinstance(x, cast_types) and x.dtype.is_floating and + x.dtype.base_dtype.name != compute_dtype): + return math_ops.cast(x, compute_dtype) + elif isinstance(x, tensor.TensorSpec) and x.dtype.is_floating: + # Inputs may be TensorSpecs when this function is called from + # model._set_inputs. + return tensor.TensorSpec(x.shape, compute_dtype, x.name) + else: + return x + return nest.map_structure(f, inputs) + else: + return inputs + + # _dtype used to be an attribute set in the constructor. We still expose it + # because some clients still use it. + # TODO(reedwm): Deprecate, then remove the _dtype property. + @property + def _dtype(self): + # This is equivalent to returning self.dtype . We do not return self.dtype + # as it would cause infinite recursion in a few subclasses, which override + # "dtype" to return self._dtype. + return self._dtype_policy.variable_dtype + + @_dtype.setter + def _dtype(self, value): + value = dtypes.as_dtype(value).name + self._set_dtype_policy(policy.Policy(value)) + + def _name_scope(self): # pylint: disable=method-hidden + return self.name + + def _init_set_name(self, name, zero_based=True): + if not name: + self._name = backend.unique_object_name( + generic_utils.to_snake_case(self.__class__.__name__), + zero_based=zero_based) + else: + self._name = name + + def _get_existing_metric(self, name=None): + match = [m for m in self._metrics if m.name == name] + if not match: + return + if len(match) > 1: + raise ValueError( + 'Please provide different names for the metrics you have added. ' + 'We found {} metrics with the name: "{}"'.format(len(match), name)) + return match[0] + + def _symbolic_add_metric(self, value, aggregation=None, name=None): + base_layer_utils.check_graph_consistency(value, method='add_metric') + match = self._get_existing_metric(name) + if aggregation is None: + # Iterate over the metrics and check if the given metric exists already. + # This can happen when a metric instance is created in subclassed model + # layer `__init__` and we have tracked that instance already in + # model.__setattr__. + if match: + result_tensor = value + metric_obj = match + elif hasattr(value, '_metric_obj'): + # We track the instance using the metadata on the result tensor. + result_tensor = value + metric_obj = result_tensor._metric_obj + self._metrics.append(metric_obj) + else: + raise ValueError( + 'We do not support adding an aggregated metric result tensor that ' + 'is not the output of a `tf.keras.metrics.Metric` metric instance. ' + 'Without having access to the metric instance we cannot reset the ' + 'state of a metric after every epoch during training. You can ' + 'create a `tf.keras.metrics.Metric` instance and pass the result ' + 'here or pass an un-aggregated result with `aggregation` parameter ' + 'set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs)' + ', name=\'mean_activation\', aggregation=\'mean\')`') + else: + # If a non-aggregated tensor is given as input (ie. `aggregation` is + # explicitly set to `mean`), we wrap the tensor in `Mean` metric. + if match: + result_tensor = match(value) + metric_obj = match + else: + metric_obj, result_tensor = base_layer_utils.create_mean_metric( + value, name) + self._metrics.append(metric_obj) + + def _handle_weight_regularization(self, name, variable, regularizer): + """Create lambdas which compute regularization losses.""" + + def _loss_for_variable(v): + """Creates a regularization loss `Tensor` for variable `v`.""" + with backend.name_scope(name + '/Regularizer'): + regularization = regularizer(v) + return regularization + + if base_layer_utils.is_split_variable(variable): + for v in variable: + self.add_loss(functools.partial(_loss_for_variable, v)) + else: + self.add_loss(functools.partial(_loss_for_variable, variable)) + + def _handle_activity_regularization(self, inputs, outputs): + # Apply activity regularization. + # Note that it should be applied every time the layer creates a new + # output, since it is output-specific. + if self._activity_regularizer: + output_list = nest.flatten(outputs) + with backend.name_scope('ActivityRegularizer'): + for output in output_list: + activity_loss = self._activity_regularizer(output) + batch_size = math_ops.cast( + array_ops.shape(output)[0], activity_loss.dtype) + # Make activity regularization strength batch-agnostic. + mean_activity_loss = activity_loss / batch_size + base_layer_utils.check_graph_consistency( + mean_activity_loss, method='activity_regularizer') + self.add_loss(mean_activity_loss, inputs=inputs) + + def _set_mask_metadata(self, inputs, outputs, previous_mask): + flat_outputs = nest.flatten(outputs) + + mask_already_computed = ( + getattr(self, '_compute_output_and_mask_jointly', False) or + all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs)) + + # Only compute the mask if the Layer explicitly supports masking or has + # overridden `compute_mask`. + should_compute_mask = ( + hasattr(self, 'compute_mask') and + (self.supports_masking or + not getattr(self.compute_mask, '_is_default', False))) + + if mask_already_computed: + flat_masks = [getattr(x, '_keras_mask', None) for x in flat_outputs] + elif not should_compute_mask: + flat_masks = [None for _ in flat_outputs] + else: + output_masks = self.compute_mask(inputs, previous_mask) + # `compute_mask` can return a single `None` even when a Layer + # has multiple outputs. + if output_masks is None: + flat_masks = [None for _ in flat_outputs] + else: + flat_masks = nest.flatten(output_masks) + + for output, mask in zip(flat_outputs, flat_masks): + try: + output._keras_mask = mask + except AttributeError: + # C Type such as np.ndarray. + pass + + if tf_utils.are_all_symbolic_tensors(flat_outputs): + for output in flat_outputs: + if getattr(output, '_keras_mask', None) is not None: + # Do not track masks for `TensorFlowOpLayer` construction. + output._keras_mask._keras_history_checked = True + + def _collect_input_masks(self, inputs, args, kwargs): + """Checks if `mask` argument was passed, else gathers mask from inputs.""" + if self._call_arg_was_passed('mask', args, kwargs): + return self._get_call_arg_value('mask', args, kwargs) + + if not self._should_compute_mask: + return None + + input_masks = nest.map_structure(lambda t: getattr(t, '_keras_mask', None), + inputs) + if generic_utils.is_all_none(input_masks): + return None + return input_masks + + def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False): + if arg_name in kwargs: + return True + call_fn_args = self._call_fn_args + if not inputs_in_args: + # Ignore `inputs` arg. + call_fn_args = call_fn_args[1:] + if arg_name in dict(zip(call_fn_args, args)): + return True + return False + + def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False): + if arg_name in kwargs: + return kwargs[arg_name] + call_fn_args = self._call_fn_args + if not inputs_in_args: + # Ignore `inputs` arg. + call_fn_args = call_fn_args[1:] + args_dict = dict(zip(call_fn_args, args)) + return args_dict[arg_name] + + def _set_call_arg_value( + self, arg_name, new_value, args, + kwargs, inputs_in_args=False, pop_kwarg_if_none=False): + arg_pos = self._call_fn_arg_positions.get(arg_name, None) + if arg_pos is not None: + if not inputs_in_args: + # Ignore `inputs` arg. + arg_pos = arg_pos - 1 + if len(args) > arg_pos: + args = list(args) + args[arg_pos] = new_value + return args, kwargs + if new_value is None and pop_kwarg_if_none: + kwargs.pop(arg_name, None) + else: + kwargs[arg_name] = new_value + return args, kwargs + + def _get_node_attribute_at_index(self, node_index, attr, attr_name): + """Private utility to retrieves an attribute (e.g. inputs) from a node. + + This is used to implement the methods: + - get_input_shape_at + - get_output_shape_at + - get_input_at + etc... + + Args: + node_index: Integer index of the node from which + to retrieve the attribute. + attr: Exact node attribute name. + attr_name: Human-readable attribute name, for error messages. + + Returns: + The layer's attribute `attr` at the node of index `node_index`. + + Raises: + RuntimeError: If the layer has no inbound nodes, or if called in Eager + mode. + ValueError: If the index provided does not match any node. + """ + if not self._inbound_nodes: + raise RuntimeError('The layer has never been called ' + 'and thus has no defined ' + attr_name + '.') + if not len(self._inbound_nodes) > node_index: + raise ValueError('Asked to get ' + attr_name + ' at node ' + + str(node_index) + ', but the layer has only ' + + str(len(self._inbound_nodes)) + ' inbound nodes.') + values = getattr(self._inbound_nodes[node_index], attr) + if isinstance(values, list) and len(values) == 1: + return values[0] + else: + return values + + def _maybe_build(self, inputs): + # Check input assumptions set before layer building, e.g. input rank. + if not self.built: + input_spec.assert_input_compatibility( + self.input_spec, inputs, self.name) + input_list = nest.flatten(inputs) + if input_list and self._dtype_policy.compute_dtype is None: + try: + dtype = input_list[0].dtype.base_dtype.name + except AttributeError: + pass + else: + self._set_dtype_policy(policy.Policy(dtype)) + input_shapes = None + if all(hasattr(x, 'shape') for x in input_list): + input_shapes = nest.map_structure(lambda x: x.shape, inputs) + # Only call `build` if the user has manually overridden the build method. + if not hasattr(self.build, '_is_default'): + # Any setup work performed only once should happen in an `init_scope` + # to avoid creating symbolic Tensors that will later pollute any eager + # operations. + with tf_utils.maybe_init_scope(self): + self.build(input_shapes) + # We must set also ensure that the layer is marked as built, and the build + # shape is stored since user defined build functions may not be calling + # `super.build()` + Layer.build(self, input_shapes) + + # Optionally load weight values specified at layer instantiation. + if self._initial_weights is not None: + self.set_weights(self._initial_weights) + self._initial_weights = None + + def _symbolic_call(self, inputs): + input_shapes = nest.map_structure(lambda x: x.shape, inputs) + output_shapes = self.compute_output_shape(input_shapes) + + def _make_placeholder_like(shape): + ph = backend.placeholder(shape=shape, dtype=self.dtype) + ph._keras_mask = None + return ph + + return nest.map_structure(_make_placeholder_like, output_shapes) + + def _get_trainable_state(self): + """Get the `trainable` state of each sublayer. + + Returns: + A dict mapping all sublayers to their `trainable` value. + """ + layers = self._flatten_layers(include_self=False, recursive=False) + trainable_state = {self: self.trainable} + for l in layers: + trainable_state.update(l._get_trainable_state()) + return trainable_state + + def _set_trainable_state(self, trainable_state): + """Set `trainable` state for each sublayer.""" + if self in trainable_state: + self.trainable = trainable_state[self] + layers = self._flatten_layers(include_self=False, recursive=False) + for l in layers: + if l in trainable_state: + l._set_trainable_state(trainable_state) + + @property + def _obj_reference_counts(self): + """A dictionary counting the number of attributes referencing an object.""" + self._maybe_create_attribute('_obj_reference_counts_dict', + object_identity.ObjectIdentityDictionary()) + return self._obj_reference_counts_dict + + @trackable.no_automatic_dependency_tracking + def _maybe_create_attribute(self, name, default_value): + """Create the attribute with the default value if it hasn't been created. + + This is useful for fields that is used for tracking purpose, + _trainable_weights, or _layers. Note that user could create a layer subclass + and assign an internal field before invoking the Layer.__init__(), the + __setattr__() need to create the tracking fields and __init__() need to not + override them. + + Args: + name: String, the name of the attribute. + default_value: Object, the default value of the attribute. + """ + if not hasattr(self, name): + self.__setattr__(name, default_value) + + def __delattr__(self, name): + # For any super.__delattr__() call, we will directly use the implementation + # in Trackable and skip the behavior in AutoTrackable. The Layer was + # originally use Trackable as base class, the change of using Module as base + # class forced us to have AutoTrackable in the class hierarchy. + # + # TODO(b/180760306) Keeping the status quo of skipping _delattr__ and + # __setattr__ in AutoTrackable may be unsustainable. + existing_value = getattr(self, name, None) + + # If this value is replacing an existing object assigned to an attribute, we + # should clean it out to avoid leaking memory. First we check if there are + # other attributes referencing it. + reference_counts = self._obj_reference_counts + if existing_value not in reference_counts: + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + return + + reference_count = reference_counts[existing_value] + if reference_count > 1: + # There are other remaining references. We can't remove this object from + # _layers etc. + reference_counts[existing_value] = reference_count - 1 + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + return + else: + # This is the last remaining reference. + del reference_counts[existing_value] + + super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call + + if (isinstance(existing_value, Layer) + or base_layer_utils.has_weights(existing_value)): + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_self_tracked_trackables', + [l for l in self._self_tracked_trackables if l is not existing_value]) + if isinstance(existing_value, tf_variables.Variable): + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_trainable_weights', + [w for w in self._trainable_weights if w is not existing_value]) + super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call + '_non_trainable_weights', + [w for w in self._non_trainable_weights if w is not existing_value]) + + def __setattr__(self, name, value): + if (name == '_self_setattr_tracking' or + not getattr(self, '_self_setattr_tracking', True) or + # Exclude @property.setters from tracking + hasattr(self.__class__, name)): + try: + super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call + except AttributeError: + raise AttributeError( + ('Can\'t set the attribute "{}", likely because it conflicts with ' + 'an existing read-only @property of the object. Please choose a ' + 'different name.').format(name)) + return + + # Keep track of trackable objects, for the needs of `Network.save_weights`. + value = data_structures.sticky_attribute_assignment( + trackable=self, value=value, name=name) + + reference_counts = self._obj_reference_counts + reference_counts[value] = reference_counts.get(value, 0) + 1 + + # Clean out the old attribute, which clears _layers and _trainable_weights + # if necessary. + try: + self.__delattr__(name) + except AttributeError: + pass + + # Keep track of metric instance created in subclassed layer. + from tensorflow.python.keras import metrics as metrics_module # pylint: disable=g-import-not-at-top + for val in nest.flatten(value): + if isinstance(val, metrics_module.Metric) and hasattr(self, '_metrics'): + self._metrics.append(val) + + # TODO(scottzhu): Need to track Module object as well for weight tracking. + # Be careful about metric if it becomes a Module in future. + # Append value to self._layers if relevant + if (getattr(self, '_auto_track_sub_layers', True) and + (isinstance(value, Layer) or base_layer_utils.has_weights(value))): + self._maybe_create_attribute('_self_tracked_trackables', []) + # We need to check object identity to avoid de-duplicating empty + # container types which compare equal. + if not any((layer is value for layer in self._self_tracked_trackables)): + self._self_tracked_trackables.append(value) + if hasattr(value, '_use_resource_variables'): + # Legacy layers (V1 tf.layers) must always use + # resource variables. + value._use_resource_variables = True + + # Append value to list of trainable / non-trainable weights if relevant + # TODO(b/125122625): This won't pick up on any variables added to a + # list/dict after creation. + for val in nest.flatten(value): + if not isinstance(val, tf_variables.Variable): + continue + + # Users may add extra weights/variables + # simply by assigning them to attributes (invalid for graph networks) + self._maybe_create_attribute('_trainable_weights', []) + self._maybe_create_attribute('_non_trainable_weights', []) + if val.trainable: + if any(val is w for w in self._trainable_weights): + continue + self._trainable_weights.append(val) + else: + if any(val is w for w in self._non_trainable_weights): + continue + self._non_trainable_weights.append(val) + + backend.track_variable(val) + + # TODO(b/180760306) Skip the auto trackable from tf.Module to keep status + # quo. See the comment at __delattr__. + super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call + + # This is a hack so that the is_layer (within + # training/trackable/layer_utils.py) check doesn't get the weights attr. + # TODO(b/110718070): Remove when fixed. + def _is_layer(self): + return True + + def _init_call_fn_args(self, expects_training_arg=None): + # Clear cached call function arguments. + self.__class__._call_full_argspec.fget.cache.pop(self, None) + self.__class__._call_fn_args.fget.cache.pop(self, None) + self.__class__._call_accepts_kwargs.fget.cache.pop(self, None) + + call_fn_args = self._call_fn_args + if expects_training_arg is None: + self._expects_training_arg = ('training' in call_fn_args or + self._call_accepts_kwargs) + else: + # Use value encoded into the metadata when loading from the SavedModel. + self._expects_training_arg = expects_training_arg + self._expects_mask_arg = ('mask' in call_fn_args or + self._call_accepts_kwargs) + + @property + @layer_utils.cached_per_instance + def _call_full_argspec(self): + # Argspec inspection is expensive and the call spec is used often, so it + # makes sense to cache the result. + return tf_inspect.getfullargspec(self.call) + + @property + @layer_utils.cached_per_instance + def _call_fn_args(self): + all_args = self._call_full_argspec.args + # Scrub `self` that appears if a decorator was applied. + if all_args and all_args[0] == 'self': + return all_args[1:] + return all_args + + @property + @layer_utils.cached_per_instance + def _call_fn_arg_positions(self): + call_fn_arg_positions = dict() + for pos, arg in enumerate(self._call_fn_args): + call_fn_arg_positions[arg] = pos + return call_fn_arg_positions + + @property + @layer_utils.cached_per_instance + def _call_accepts_kwargs(self): + return self._call_full_argspec.varkw is not None + + @property + @layer_utils.cached_per_instance + def _should_compute_mask(self): + return ('mask' in self._call_fn_args or + getattr(self, 'compute_mask', None) is not None) + + def _dedup_weights(self, weights): + """Dedupe weights while maintaining order as much as possible.""" + output, seen_ids = [], set() + for w in weights: + if id(w) not in seen_ids: + output.append(w) + # Track the Variable's identity to avoid __eq__ issues. + seen_ids.add(id(w)) + + return output + + # SavedModel properties. Please see keras/saving/saved_model for details. + + @property + def _trackable_saved_model_saver(self): + return layer_serialization.LayerSavedModelSaver(self) + + @property + def _object_identifier(self): + return self._trackable_saved_model_saver.object_identifier + + @property + def _tracking_metadata(self): + return self._trackable_saved_model_saver.tracking_metadata + + def _trackable_children(self, save_type='checkpoint', **kwargs): + if save_type == 'savedmodel': + cache = kwargs['cache'] + # TODO(b/213628533): This must be called before super() to ensure + # that any input shape changes are applied before getting the config of + # the model. + children = self._trackable_saved_model_saver.trackable_children(cache) + else: + children = {} + children.update(super()._trackable_children(save_type, **kwargs)) + return children + + def __getstate__(self): + # Override to support `copy.deepcopy` and pickling. + # Thread-local objects cannot be copied in Python 3, so pop these. + # Thread-local objects are used to cache losses in MirroredStrategy, and + # so shouldn't be copied. + state = self.__dict__.copy() + state.pop('_thread_local', None) + return state + + def __setstate__(self, state): + state['_thread_local'] = threading.local() + # Bypass Trackable logic as `__dict__` already contains this info. + object.__setattr__(self, '__dict__', state) + + +class KerasHistory( + collections.namedtuple('KerasHistory', + ['layer', 'node_index', 'tensor_index'])): + """Tracks the Layer call that created a Tensor, for Keras Graph Networks. + + During construction of Keras Graph Networks, this metadata is added to + each Tensor produced as the output of a Layer, starting with an + `InputLayer`. This allows Keras to track how each Tensor was produced, and + this information is later retraced by the `keras.engine.Network` class to + reconstruct the Keras Graph Network. + + Attributes: + layer: The Layer that produced the Tensor. + node_index: The specific call to the Layer that produced this Tensor. Layers + can be called multiple times in order to share weights. A new node is + created every time a Tensor is called. + tensor_index: The output index for this Tensor. Always zero if the Layer + that produced this Tensor only has one output. Nested structures of + Tensors are deterministically assigned an index via `nest.flatten`. + """ + # Added to maintain memory and performance characteristics of `namedtuple` + # while subclassing. + __slots__ = () + + +# Avoid breaking users who directly import this symbol from this file. +# TODO(fchollet): remove this. +InputSpec = input_spec.InputSpec # pylint:disable=invalid-name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_preprocessing_layer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_preprocessing_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..bde3f322b484689b150b755b3bb13f4622b0ba59 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/base_preprocessing_layer.py @@ -0,0 +1,619 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains the base ProcessingLayer and a subclass that uses Combiners.""" + +import abc +import collections + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import data_adapter +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.trackable import base as trackable + + +class PreprocessingLayer(Layer, metaclass=abc.ABCMeta): + """Base class for Preprocessing Layers. + + **Don't use this class directly: it's an abstract base class!** You may + be looking for one of the many built-in + [preprocessing layers](https://keras.io/guides/preprocessing_layers/) + instead. + + Preprocessing layers are layers whose state gets computed before model + training starts. They do not get updated during training. + Most preprocessing layers implement an `adapt()` method for state computation. + + The `PreprocessingLayer` class is the base class you would subclass to + implement your own preprocessing layers. + + Attributes: + streaming: Whether a layer can be adapted multiple times without resetting + the state of the layer. + """ + _must_restore_from_config = True + + def __init__(self, streaming=True, **kwargs): + super(PreprocessingLayer, self).__init__(**kwargs) + self._streaming = streaming + self._is_compiled = False + self._is_adapted = False + + # Sets `is_adapted=False` when `reset_state` is called. + self._reset_state_impl = self.reset_state + self.reset_state = self._reset_state_wrapper + + self._adapt_function = None + + @property + def streaming(self): + """Whether `adapt` can be called twice without resetting the state.""" + return self._streaming + + @property + def is_adapted(self): + """Whether the layer has been fit to data already.""" + return self._is_adapted + + def update_state(self, data): + """Accumulates statistics for the preprocessing layer. + + Arguments: + data: A mini-batch of inputs to the layer. + """ + raise NotImplementedError + + def reset_state(self): # pylint: disable=method-hidden + """Resets the statistics of the preprocessing layer.""" + raise NotImplementedError + + def merge_state(self, layers): + """Merge the statistics of multiple preprocessing layers. + + This layer will contain the merged state. + + Arguments: + layers: Layers whose statistics should be merge with the statistics of + this layer. + """ + raise NotImplementedError + + def finalize_state(self): + """Finalize the statistics for the preprocessing layer. + + This method is called at the end of `adapt` or after restoring a serialized + preprocessing layer's state. This method handles any one-time operations + that should occur on the layer's state before `Layer.__call__`. + """ + pass + + def make_adapt_function(self): + """Creates a function to execute one step of `adapt`. + + This method can be overridden to support custom adapt logic. + This method is called by `PreprocessingLayer.adapt`. + + Typically, this method directly controls `tf.function` settings, + and delegates the actual state update logic to + `PreprocessingLayer.update_state`. + + This function is cached the first time `PreprocessingLayer.adapt` + is called. The cache is cleared whenever `PreprocessingLayer.compile` + is called. + + Returns: + Function. The function created by this method should accept a + `tf.data.Iterator`, retrieve a batch, and update the state of the + layer. + """ + if self._adapt_function is not None: + return self._adapt_function + + def adapt_step(iterator): + data = next(iterator) + self._adapt_maybe_build(data) + self.update_state(data) + + if self._steps_per_execution.numpy().item() == 1: + adapt_fn = adapt_step + else: + + def adapt_fn(iterator): + for _ in math_ops.range(self._steps_per_execution): + adapt_step(iterator) + + if not self._run_eagerly: + adapt_fn = def_function.function(adapt_fn) + + self._adapt_function = adapt_fn + return self._adapt_function + + def compile(self, run_eagerly=None, steps_per_execution=None): + """Configures the layer for `adapt`. + + Arguments: + run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s logic + will not be wrapped in a `tf.function`. Recommended to leave this as + `None` unless your `Model` cannot be run inside a `tf.function`. + steps_per_execution: Int. Defaults to 1. The number of batches to run + during each `tf.function` call. Running multiple batches inside a + single `tf.function` call can greatly improve performance on TPUs or + small models with a large Python overhead. + """ + if steps_per_execution is None: + steps_per_execution = 1 + self._configure_steps_per_execution(steps_per_execution) + + if run_eagerly is None: + run_eagerly = self.dynamic + self._run_eagerly = run_eagerly + + self._is_compiled = True + + def adapt(self, data, batch_size=None, steps=None, reset_state=True): + """Fits the state of the preprocessing layer to the data being passed. + + After calling `adapt` on a layer, a preprocessing layer's state will not + update during training. In order to make preprocessing layers efficient in + any distribution context, they are kept constant with respect to any + compiled `tf.Graph`s that call the layer. This does not affect the layer use + when adapting each layer only once, but if you adapt a layer multiple times + you will need to take care to re-compile any compiled functions as follows: + + * If you are adding a preprocessing layer to a `keras.Model`, you need to + call `model.compile` after each subsequent call to `adapt`. + * If you are calling a preprocessing layer inside `tf.data.Dataset.map`, + you should call `map` again on the input `tf.data.Dataset` after each + `adapt`. + * If you are using a `tf.function` directly which calls a preprocessing + layer, you need to call `tf.function` again on your callable after + each subsequent call to `adapt`. + + `tf.keras.Model` example with multiple adapts: + + >>> layer = tf.keras.layers.experimental.preprocessing.Normalization( + ... axis=None) + >>> layer.adapt([0, 2]) + >>> model = tf.keras.Sequential(layer) + >>> model.predict([0, 1, 2]) + array([-1., 0., 1.], dtype=float32) + >>> layer.adapt([-1, 1]) + >>> model.compile() # This is needed to re-compile model.predict! + >>> model.predict([0, 1, 2]) + array([0., 1., 2.], dtype=float32) + + `tf.data.Dataset` example with multiple adapts: + + >>> layer = tf.keras.layers.experimental.preprocessing.Normalization( + ... axis=None) + >>> layer.adapt([0, 2]) + >>> input_ds = tf.data.Dataset.range(3) + >>> normalized_ds = input_ds.map(layer) + >>> list(normalized_ds.as_numpy_iterator()) + [array([-1.], dtype=float32), + array([0.], dtype=float32), + array([1.], dtype=float32)] + >>> layer.adapt([-1, 1]) + >>> normalized_ds = input_ds.map(layer) # Re-map over the input dataset. + >>> list(normalized_ds.as_numpy_iterator()) + [array([0.], dtype=float32), + array([1.], dtype=float32), + array([2.], dtype=float32)] + + Arguments: + data: The data to train on. It can be passed either as a tf.data + Dataset, or as a numpy array. + batch_size: Integer or `None`. + Number of samples per state update. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of datasets, generators, or `keras.utils.Sequence` instances + (since they generate batches). + steps: Integer or `None`. + Total number of steps (batches of samples) + When training with input tensors such as + TensorFlow data tensors, the default `None` is equal to + the number of samples in your dataset divided by + the batch size, or 1 if that cannot be determined. If x is a + `tf.data` dataset, and 'steps' is None, the epoch will run until + the input dataset is exhausted. When passing an infinitely + repeating dataset, you must specify the `steps` argument. This + argument is not supported with array inputs. + reset_state: Optional argument specifying whether to clear the state of + the layer at the start of the call to `adapt`, or whether to start + from the existing state. This argument may not be relevant to all + preprocessing layers: a subclass of PreprocessingLayer may choose to + throw if 'reset_state' is set to False. + """ + _disallow_inside_tf_function('adapt') + if not version_utils.should_use_v2(): + raise RuntimeError('`adapt` is only supported in tensorflow v2.') # pylint: disable=g-doc-exception + if not self.streaming and self._is_adapted and not reset_state: + raise ValueError('{} does not supporting calling `adapt` twice without ' + 'resetting the state.'.format(self.__class__.__name__)) + if not self._is_compiled: + self.compile() # Compile with defaults. + if self.built and reset_state: + self.reset_state() + data_handler = data_adapter.DataHandler( + data, + batch_size=batch_size, + steps_per_epoch=steps, + epochs=1, + steps_per_execution=self._steps_per_execution, + distribute=False) + self._adapt_function = self.make_adapt_function() + for _, iterator in data_handler.enumerate_epochs(): + with data_handler.catch_stop_iteration(): + for _ in data_handler.steps(): + self._adapt_function(iterator) + if data_handler.should_sync: + context.async_wait() + self.finalize_state() + self._is_adapted = True + + def _reset_state_wrapper(self): + """Calls `reset_state` and sets `adapted` to `False`.""" + self._reset_state_impl() + self._is_adapted = False + + @trackable.no_automatic_dependency_tracking + def _configure_steps_per_execution(self, steps_per_execution): + self._steps_per_execution = variables.Variable( + steps_per_execution, + dtype='int64', + aggregation=variables.VariableAggregationV2.ONLY_FIRST_REPLICA) + + # TODO(omalleyt): Unify this logic with `Layer._maybe_build`. + def _adapt_maybe_build(self, data): + if not self.built: + try: + # If this is a Numpy array or tensor, we can get shape from .shape. + # If not, an attribute error will be thrown. + data_shape = data.shape + data_shape_nones = tuple([None] * len(data.shape)) + except AttributeError: + # The input has an unknown number of dimensions. + data_shape = None + data_shape_nones = None + + # TODO (b/159261555): move this to base layer build. + batch_input_shape = getattr(self, '_batch_input_shape', None) + if batch_input_shape is None: + # Set the number of dimensions. + self._batch_input_shape = data_shape_nones + self.build(data_shape) + self.built = True + + +# TODO(omalleyt): This class will be gradually replaced. +class CombinerPreprocessingLayer(PreprocessingLayer): + """Base class for PreprocessingLayers that do computation using a Combiner. + + This class provides several helper methods to make creating a + PreprocessingLayer easier. It assumes that the core of your computation will + be done via a Combiner object. Subclassing this class to create a + PreprocessingLayer allows your layer to be compatible with distributed + computation. + + This class is compatible with Tensorflow 2.0+. + """ + + def __init__(self, combiner, **kwargs): + super(CombinerPreprocessingLayer, self).__init__(**kwargs) + self.state_variables = collections.OrderedDict() + self._combiner = combiner + self._adapt_accumulator = None + + def reset_state(self): # pylint: disable=method-hidden + self._adapt_accumulator = None + + @trackable.no_automatic_dependency_tracking + def update_state(self, data): + if self._adapt_accumulator is None: + self._adapt_accumulator = self._get_accumulator() + self._adapt_accumulator = self._combiner.compute(data, + self._adapt_accumulator) + + def merge_state(self, layers): + accumulators = ([self._get_accumulator()] + + [l._get_accumulator() for l in layers]) # pylint: disable=protected-access + merged_accumulator = self._combiner.merge(accumulators) + self._set_accumulator(merged_accumulator) + + def finalize_state(self): + if self._adapt_accumulator is not None: + self._set_accumulator(self._adapt_accumulator) + + def compile(self, run_eagerly=None, steps_per_execution=None): + # TODO(omalleyt): Remove this once sublayers are switched to new APIs. + if run_eagerly is None: + run_eagerly = True + super(CombinerPreprocessingLayer, self).compile( + run_eagerly=run_eagerly, steps_per_execution=steps_per_execution) + + def adapt(self, data, batch_size=None, steps=None, reset_state=True): + if not reset_state: + self._adapt_accumulator = self._combiner.restore(self._restore_updates()) + super(CombinerPreprocessingLayer, self).adapt( + data, batch_size=batch_size, steps=steps, reset_state=reset_state) + + def _add_state_variable(self, + name, + shape, + dtype, + initializer=None, + partitioner=None, + use_resource=None, + **kwargs): + """Add a variable that can hold state which is updated during adapt(). + + Args: + name: Variable name. + shape: Variable shape. Defaults to scalar if unspecified. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + initializer: initializer instance (callable). + partitioner: Partitioner to be passed to the `Trackable` API. + use_resource: Whether to use `ResourceVariable` + **kwargs: Additional keyword arguments. Accepted values are `getter` and + `collections`. + + Returns: + The created variable. + """ + weight = self.add_weight( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=None, + trainable=False, + constraint=None, + partitioner=partitioner, + use_resource=use_resource, + **kwargs) + # TODO(momernick): Do not allow collisions here. + self.state_variables[name] = weight + return weight + + def _restore_updates(self): + """Recreates a dict of updates from the layer's weights.""" + data_dict = {} + for name, var in self.state_variables.items(): + data_dict[name] = var.numpy() + return data_dict + + def _get_accumulator(self): + if self._is_adapted: + return self._combiner.restore(self._restore_updates()) + else: + return None + + def _set_accumulator(self, accumulator): + updates = self._combiner.extract(accumulator) + self._set_state_variables(updates) + self._adapt_accumulator = None # Reset accumulator from adapt. + + def _set_state_variables(self, updates): + """Directly update the internal state of this Layer. + + This method expects a string-keyed dict of {state_variable_name: state}. The + precise nature of the state, and the names associated, are describe by + the subclasses of CombinerPreprocessingLayer. + + Args: + updates: A string keyed dict of weights to update. + + Raises: + RuntimeError: if 'build()' was not called before 'set_processing_state'. + """ + # TODO(momernick): Do we need to do any more input sanitization? + if not self.built: + raise RuntimeError('_set_state_variables() must be called after build().') + + with ops.init_scope(): + for var_name, value in updates.items(): + self.state_variables[var_name].assign(value) + + +def convert_to_list(values, sparse_default_value=None): + """Convert a TensorLike, CompositeTensor, or ndarray into a Python list.""" + if tf_utils.is_ragged(values): + # There is a corner case when dealing with ragged tensors: if you get an + # actual RaggedTensor (not a RaggedTensorValue) passed in non-eager mode, + # you can't call to_list() on it without evaluating it first. However, + # because we don't yet fully support composite tensors across Keras, + # backend.get_value() won't evaluate the tensor. + # TODO(momernick): Get Keras to recognize composite tensors as Tensors + # and then replace this with a call to backend.get_value. + if (isinstance(values, ragged_tensor.RaggedTensor) and + not context.executing_eagerly()): + values = backend.get_session(values).run(values) + values = values.to_list() + + if isinstance(values, + (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + if sparse_default_value is None: + if dtypes.as_dtype(values.values.dtype) == dtypes.string: + sparse_default_value = '' + else: + sparse_default_value = -1 + dense_tensor = sparse_ops.sparse_tensor_to_dense( + values, default_value=sparse_default_value) + values = backend.get_value(dense_tensor) + + if isinstance(values, tensor.Tensor): + values = backend.get_value(values) + + # We may get passed a ndarray or the code above may give us a ndarray. + # In either case, we want to force it into a standard python list. + if isinstance(values, np.ndarray): + values = values.tolist() + + return values + + +# TODO(omalleyt): This class will be gradually replaced. +class Combiner(object): + """Functional object that defines a shardable computation. + + This object defines functions required to create and manipulate data objects. + These data objects, referred to below as 'accumulators', are computation- + specific and may be implemented alongside concrete subclasses of Combiner + (if necessary - some computations may be simple enough that standard Python + types can be used as accumulators). + + The intent for this class is that by describing computations in this way, we + can arbitrarily shard a dataset, perform computations on a subset, and then + merge the computation into a final result. This enables distributed + computation. + + The combiner itself does not own any state - all computational state is owned + by the accumulator objects. This is so that we can have an arbitrary number of + Combiners (thus sharding the computation N ways) without risking any change + to the underlying computation. These accumulator objects are uniquely + associated with each Combiner; a Combiner defines what the accumulator object + should be and will only work with accumulators of that type. + """ + __metaclass__ = abc.ABCMeta + + def __repr__(self): + return '<{}>'.format(self.__class__.__name__) + + @abc.abstractmethod + def compute(self, batch_values, accumulator=None): + """Compute a step in this computation, returning a new accumulator. + + This method computes a step of the computation described by this Combiner. + If an accumulator is passed, the data in that accumulator is also used; so + compute(batch_values) results in f(batch_values), while + compute(batch_values, accumulator) results in + merge(f(batch_values), accumulator). + + Args: + batch_values: A list of ndarrays representing the values of the inputs for + this step of the computation. + accumulator: the current accumulator. Can be None. + + Returns: + An accumulator that includes the passed batch of inputs. + """ + pass + + @abc.abstractmethod + def merge(self, accumulators): + """Merge several accumulators to a single accumulator. + + This method takes the partial values in several accumulators and combines + them into a single accumulator. This computation must not be order-specific + (that is, merge([a, b]) must return the same result as merge([b, a]). + + Args: + accumulators: the accumulators to merge, as a list. + + Returns: + A merged accumulator. + """ + pass + + @abc.abstractmethod + def extract(self, accumulator): + """Convert an accumulator into a dict of output values. + + Args: + accumulator: The accumulator to convert. + + Returns: + A dict of ndarrays representing the data in this accumulator. + """ + pass + + @abc.abstractmethod + def restore(self, output): + """Create an accumulator based on 'output'. + + This method creates a new accumulator with identical internal state to the + one used to create the data in 'output'. This means that if you do + + output_data = combiner.extract(accumulator_1) + accumulator_2 = combiner.restore(output_data) + + then accumulator_1 and accumulator_2 will have identical internal state, and + computations using either of them will be equivalent. + + Args: + output: The data output from a previous computation. Should be in the same + form as provided by 'extract_output'. + + Returns: + A new accumulator. + """ + pass + + @abc.abstractmethod + def serialize(self, accumulator): + """Serialize an accumulator for a remote call. + + This function serializes an accumulator to be sent to a remote process. + + Args: + accumulator: The accumulator to serialize. + + Returns: + A byte string representing the passed accumulator. + """ + pass + + @abc.abstractmethod + def deserialize(self, encoded_accumulator): + """Deserialize an accumulator received from 'serialize()'. + + This function deserializes an accumulator serialized by 'serialize()'. + + Args: + encoded_accumulator: A byte string representing an accumulator. + + Returns: + The accumulator represented by the passed byte_string. + """ + pass + + +def _disallow_inside_tf_function(method_name): + """Disallow calling a method inside a `tf.function`.""" + if ops.inside_function(): + error_msg = ( + 'Detected a call to `PreprocessingLayer.{method_name}` inside a ' + '`tf.function`. `PreprocessingLayer.{method_name} is a high-level ' + 'endpoint that manages its own `tf.function`. Please move the call ' + 'to `PreprocessingLayer.{method_name}` outside of all enclosing ' + '`tf.function`s. Note that you can call a `PreprocessingLayer` ' + 'directly on `Tensor`s inside a `tf.function` like: `layer(x)`, ' + 'or update its state like: `layer.update_state(x)`.').format( + method_name=method_name) + raise RuntimeError(error_msg) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/compile_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..81f202d4d8b043018f5fafc771729f36ce0f5083 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/compile_utils.py @@ -0,0 +1,726 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilites for `Model.compile`.""" + +import copy + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.keras import losses as losses_mod +from tensorflow.python.keras import metrics as metrics_mod +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest + + +class Container(object): + """Base Container class.""" + + def __init__(self, output_names=None): + self._output_names = output_names + + def build(self, y_pred): + if self._output_names is None: + # In Subclass API, output names like 'output_1' are used for + # `Metric` names. + self._output_names = create_pseudo_output_names(y_pred) + + def _conform_to_outputs(self, outputs, struct): + """Convenience method to conform `struct` to `outputs` structure. + + Mappings performed: + + (1) Map a dict to a list of outputs, using the output names. + (2) Fill missing keys in a dict w/ `None`s. + (3) Map a single item to all outputs. + + Args: + outputs: Model predictions. + struct: Arbitrary nested structure (e.g. of labels, sample_weights, + losses, or metrics). + + Returns: + Mapping of `struct` to `outputs` structure. + """ + struct = map_to_output_names(outputs, self._output_names, struct) + struct = map_missing_dict_keys(outputs, struct) + # Allow passing one object that applies to all outputs. + if not nest.is_nested(struct) and nest.is_nested(outputs): + struct = nest.map_structure(lambda _: struct, outputs) + return struct + + def _maybe_broadcast_to_outputs(self, outputs, objects): + """Determines if losses / metrics should be applied to all outputs. + + NOTE: This method should only be called for Metrics / Losses, not for + y_true / sample_weight. + + Args: + outputs: Model predictions. + objects: Arbitrary nested structure (e.g. of losses or metrics) + + Returns: + Arbitrary nested structure of objects, maybe copied to each output. + + Applies a Loss / Metric to all outputs. + """ + if not self._should_broadcast(objects): + return objects + + # When there is more than one Model output, this is needed to keep + # each Metric / Loss separate. When there is only one Model output, + # the user-supplied object should be used. + should_copy_objects = len(nest.flatten(outputs)) > 1 + + def _broadcast_fn(): + if should_copy_objects: + return nest.map_structure(self._copy_object, objects) + return objects + + return nest.map_structure(lambda _: _broadcast_fn(), outputs) + + def _should_broadcast(self, objects): + raise NotImplementedError + + def _copy_object(self, obj): + raise NotImplementedError + + +class LossesContainer(Container): + """A container class for losses passed to `Model.compile`.""" + + def __init__(self, losses, loss_weights=None, output_names=None): + super(LossesContainer, self).__init__(output_names=output_names) + + # Keep user-supplied values untouched for recompiling and serialization. + self._user_losses = losses + self._user_loss_weights = loss_weights + + self._losses = losses + self._loss_weights = loss_weights + self._per_output_metrics = None # Per-output losses become metrics. + self._loss_metric = metrics_mod.Mean(name='loss') # Total loss. + self._built = False + + @property + def metrics(self): + """Per-output loss metrics.""" + if not self._built: + return [] + per_output_metrics = [ + metric_obj for metric_obj in nest.flatten(self._per_output_metrics) + if metric_obj is not None + ] + return [self._loss_metric] + per_output_metrics + + def build(self, y_pred): + """One-time setup of loss objects.""" + super(LossesContainer, self).build(y_pred) + + self._losses = self._maybe_broadcast_to_outputs(y_pred, self._losses) + self._losses = self._conform_to_outputs(y_pred, self._losses) + self._losses = nest.map_structure(self._get_loss_object, self._losses) + self._losses = nest.flatten(self._losses) + + self._loss_weights = self._maybe_broadcast_to_outputs( + y_pred, self._loss_weights) + self._loss_weights = self._conform_to_outputs(y_pred, self._loss_weights) + self._loss_weights = nest.flatten(self._loss_weights) + + self._create_metrics() + self._built = True + + @property + def built(self): + return self._built + + def _create_metrics(self): + """Creates per-output loss metrics, but only for multi-output Models.""" + if len(self._output_names) == 1: + self._per_output_metrics = [None] + else: + self._per_output_metrics = [] + for loss_obj, output_name in zip(self._losses, self._output_names): + if loss_obj is None: + self._per_output_metrics.append(None) + else: + self._per_output_metrics.append( + metrics_mod.Mean(output_name + '_loss')) + + def __call__(self, + y_true, + y_pred, + sample_weight=None, + regularization_losses=None): + """Computes the overall loss. + + Args: + y_true: An arbitrary structure of Tensors representing the ground truth. + y_pred: An arbitrary structure of Tensors representing a Model's outputs. + sample_weight: An arbitrary structure of Tensors representing the + per-sample loss weights. If one Tensor is passed, it is used for all + losses. If multiple Tensors are passed, the structure should match + `y_pred`. + regularization_losses: Additional losses to be added to the total loss. + + Returns: + Tuple of `(total_loss, per_output_loss_list)` + """ + y_true = self._conform_to_outputs(y_pred, y_true) + sample_weight = self._conform_to_outputs(y_pred, sample_weight) + + if not self._built: + self.build(y_pred) + + y_pred = nest.flatten(y_pred) + y_true = nest.flatten(y_true) + sample_weight = nest.flatten(sample_weight) + + loss_values = [] # Used for gradient calculation. + loss_metric_values = [] # Used for loss metric calculation. + batch_dim = None + zip_args = (y_true, y_pred, sample_weight, self._losses, self._loss_weights, + self._per_output_metrics) + for y_t, y_p, sw, loss_obj, loss_weight, metric_obj in zip(*zip_args): + if y_t is None or loss_obj is None: # Ok to have no loss for an output. + continue + + y_t, y_p, sw = match_dtype_and_rank(y_t, y_p, sw) + sw = apply_mask(y_p, sw, get_mask(y_p)) + loss_value = loss_obj(y_t, y_p, sample_weight=sw) + + loss_metric_value = loss_value + # Correct for the `Mean` loss metrics counting each replica as a batch. + if loss_obj.reduction == losses_utils.ReductionV2.SUM: + loss_metric_value *= distribute_lib.get_strategy().num_replicas_in_sync + + if batch_dim is None: + if tf_utils.is_ragged(y_t): + batch_dim = y_t.nrows() + else: + batch_dim = array_ops.shape(y_t)[0] + + if metric_obj is not None: + metric_obj.update_state(loss_metric_value, sample_weight=batch_dim) + + if loss_weight is not None: + loss_value *= loss_weight + loss_metric_value *= loss_weight + + if (loss_obj.reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE or + loss_obj.reduction == losses_utils.ReductionV2.AUTO): + loss_value = losses_utils.scale_loss_for_distribution(loss_value) + + loss_values.append(loss_value) + loss_metric_values.append(loss_metric_value) + + if regularization_losses: + regularization_losses = losses_utils.cast_losses_to_common_dtype( + regularization_losses) + reg_loss = math_ops.add_n(regularization_losses) + loss_metric_values.append(reg_loss) + loss_values.append(losses_utils.scale_loss_for_distribution(reg_loss)) + + if loss_values: + loss_metric_values = losses_utils.cast_losses_to_common_dtype( + loss_metric_values) + total_loss_metric_value = math_ops.add_n(loss_metric_values) + self._loss_metric.update_state( + total_loss_metric_value, sample_weight=batch_dim) + + loss_values = losses_utils.cast_losses_to_common_dtype(loss_values) + total_loss = math_ops.add_n(loss_values) + return total_loss + else: + # Ok for a model to have no compiled loss. + return array_ops.zeros(shape=()) + + def reset_state(self): + """Resets the state of loss metrics.""" + if not self._built: + return + metrics = [self._loss_metric] + nest.flatten(self._per_output_metrics) + for metric_obj in metrics: + if metric_obj is not None: + metric_obj.reset_state() + + def _get_loss_object(self, loss): + """Returns a `Loss` object. + + Converts the user-supplied loss to a `Loss` object. Also allows + `SUM_OVER_BATCH_SIZE` reduction to be used for this loss. + + Args: + loss: A string, function, or `Loss` object. + + Returns: + A `Loss` object. + """ + if loss is None: + return None # Ok to have no loss for an output. + + loss = losses_mod.get(loss) + if not isinstance(loss, losses_mod.Loss): + loss_name = get_custom_object_name(loss) + if loss_name is None: + raise ValueError('Loss should be a callable, found: {}'.format(loss)) + loss = losses_mod.LossFunctionWrapper(loss, name=loss_name) + loss._allow_sum_over_batch_size = True # pylint: disable=protected-access + return loss + + def _should_broadcast(self, obj): + return not nest.is_nested(obj) + + def _copy_object(self, obj): + return obj # Losses don't need to be copied. + + +class MetricsContainer(Container): + """A container class for metrics passed to `Model.compile`.""" + + def __init__(self, metrics=None, weighted_metrics=None, output_names=None, + from_serialized=False): + """Initializes a container for metrics. + + Arguments: + metrics: see the `metrics` argument from `tf.keras.Model.compile`. + weighted_metrics: see the `weighted_metrics` argument from + `tf.keras.Model.compile`. + output_names: A list of strings of names of outputs for the model. + from_serialized: Whether the model being compiled is from a serialized + model. Used to avoid redundantly applying pre-processing renaming + steps. + """ + super(MetricsContainer, self).__init__(output_names=output_names) + + # Keep user-supplied values untouched for recompiling and serialization. + self._user_metrics = metrics + self._user_weighted_metrics = weighted_metrics + + self._metrics = metrics + self._weighted_metrics = weighted_metrics + self._built = False + + self._from_serialized = from_serialized + + @property + def metrics(self): + """All metrics in this container.""" + if not self._built: + return [] + return self._metrics_in_order + + @property + def unweighted_metrics(self): + """Metrics in this container that should not be passed `sample_weight`.""" + if not self._built: + return None + return nest.flatten(self._metrics) + + @property + def weighted_metrics(self): + """Metrics in this container that should be passed `sample_weight`.""" + if not self._built: + return None + return nest.flatten(self._weighted_metrics) + + def build(self, y_pred, y_true): + """One-time setup of metric objects.""" + super(MetricsContainer, self).build(y_pred) + + self._metrics = self._maybe_broadcast_to_outputs(y_pred, self._metrics) + self._metrics = self._conform_to_outputs(y_pred, self._metrics) + + self._weighted_metrics = self._maybe_broadcast_to_outputs( + y_pred, self._weighted_metrics) + self._weighted_metrics = self._conform_to_outputs(y_pred, + self._weighted_metrics) + + # Standardize on tuple since `tf.data` turns lists into `Tensor`s. + y_pred = nest.list_to_tuple(y_pred) + y_true = nest.list_to_tuple(y_true) + self._metrics = nest.list_to_tuple(self._metrics) + self._weighted_metrics = nest.list_to_tuple(self._weighted_metrics) + + # Convert to `Metric` objects, potentially disambiguating based on output + # properties. + self._metrics = nest.map_structure_up_to(y_pred, self._get_metric_objects, + self._metrics, y_true, y_pred) + self._weighted_metrics = nest.map_structure_up_to(y_pred, + self._get_metric_objects, + self._weighted_metrics, + y_true, y_pred) + + self._metrics = nest.flatten_up_to(y_pred, self._metrics, check_types=False) + self._weighted_metrics = nest.flatten_up_to( + y_pred, self._weighted_metrics, check_types=False) + + # Assumes metrics, weighted_metrics have been flattened up to outputs. + # + # If we are loading a model that has been already serialized, we do not + # want to re-apply any pre-processing metric renaming steps. + if not self._from_serialized: + self._set_metric_names() + self._create_ordered_metrics() + self._built = True + + @property + def built(self): + return self._built + + def _set_metric_names(self): + """Sets unique metric names.""" + # For multi-output models, prepend the output name to the metric name. + # For weighted metrics, prepend "weighted_" if the name would be non-unique. + # pylint: disable=protected-access + metric_names = set() + is_multi_output = len(self._output_names) > 1 + zip_args = (self._output_names, self._metrics, self._weighted_metrics) + for output_name, output_metrics, weighted_output_metrics in zip(*zip_args): + for m in output_metrics: + if m is None: + continue + if is_multi_output: + m._name = output_name + '_' + m._name + if m._name in metric_names: + raise ValueError('Found two metrics with the same name: {}'.format( + m._name)) + metric_names.add(m._name) + + for wm in weighted_output_metrics: + if wm is None: + continue + if is_multi_output: + if output_name + '_' + wm._name in metric_names: + wm._name = output_name + '_weighted_' + wm._name + else: + wm._name = output_name + '_' + wm._name + elif wm._name in metric_names: + wm._name = 'weighted_' + wm._name + + if wm._name in metric_names: + raise ValueError('Found two metrics with the same name: {}'.format( + wm._name)) + metric_names.add(wm._name) + # pylint: enable=protected-access + + def _create_ordered_metrics(self): + """Cache the flat order needed when returning metrics, for backwards compat.""" + self._metrics_in_order = [] + for output_metrics, output_weighted_metrics in zip(self._metrics, + self._weighted_metrics): + for m in nest.flatten(output_metrics): + if m is not None: + self._metrics_in_order.append(m) + for wm in nest.flatten(output_weighted_metrics): + if wm is not None: + self._metrics_in_order.append(wm) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Updates the state of per-output metrics.""" + y_true = self._conform_to_outputs(y_pred, y_true) + sample_weight = self._conform_to_outputs(y_pred, sample_weight) + + if not self._built: + self.build(y_pred, y_true) + + y_pred = nest.flatten(y_pred) + y_true = nest.flatten(y_true) if y_true is not None else [] + sample_weight = nest.flatten(sample_weight) + + zip_args = (y_true, y_pred, sample_weight, self._metrics, + self._weighted_metrics) + for y_t, y_p, sw, metric_objs, weighted_metric_objs in zip(*zip_args): + # Ok to have no metrics for an output. + if (y_t is None or (all(m is None for m in metric_objs) and + all(wm is None for wm in weighted_metric_objs))): + continue + + y_t, y_p, sw = match_dtype_and_rank(y_t, y_p, sw) + mask = get_mask(y_p) + sw = apply_mask(y_p, sw, mask) + + for metric_obj in metric_objs: + if metric_obj is None: + continue + metric_obj.update_state(y_t, y_p, sample_weight=mask) + + for weighted_metric_obj in weighted_metric_objs: + if weighted_metric_obj is None: + continue + weighted_metric_obj.update_state(y_t, y_p, sample_weight=sw) + + def reset_state(self): + """Resets the state of all `Metric`s in this container.""" + if self._built: + metrics = self._metrics_in_order + else: + # If the user supplied `Metric` objects directly, we should + # reset those. This could also contain `str`s or `function`s + # though. + metrics = nest.flatten(self._user_metrics) + nest.flatten( + self._user_weighted_metrics) + + for metric_obj in metrics: + if isinstance(metric_obj, metrics_mod.Metric): + metric_obj.reset_state() + + def _get_metric_objects(self, metrics, y_t, y_p): + """Convert user-supplied metrics to `Metric` objects.""" + metrics = nest.flatten(metrics) + return [self._get_metric_object(m, y_t, y_p) for m in metrics] + + def _get_metric_object(self, metric, y_t, y_p): + """Converts user-supplied metric to a `Metric` object. + + Args: + metric: A string, function, or `Metric` object. + y_t: Sample of label. + y_p: Sample of output. + + Returns: + A `Metric` object. + """ + if metric is None: + return None # Ok to have no metric for an output. + + # Convenience feature for selecting b/t binary, categorical, + # and sparse categorical. + if str(metric).lower() not in ['accuracy', 'acc', 'crossentropy', 'ce']: + metric_obj = metrics_mod.get(metric) + else: + y_t_rank = len(y_t.shape.as_list()) + y_p_rank = len(y_p.shape.as_list()) + y_t_last_dim = y_t.shape.as_list()[-1] + y_p_last_dim = y_p.shape.as_list()[-1] + + is_binary = y_p_last_dim == 1 + is_sparse_categorical = ( + y_t_rank < y_p_rank or y_t_last_dim == 1 and y_p_last_dim > 1) + + if str(metric).lower() in ['accuracy', 'acc']: + if is_binary: + metric_obj = metrics_mod.binary_accuracy + elif is_sparse_categorical: + metric_obj = metrics_mod.sparse_categorical_accuracy + else: + metric_obj = metrics_mod.categorical_accuracy + else: + if is_binary: + metric_obj = metrics_mod.binary_crossentropy + elif is_sparse_categorical: + metric_obj = metrics_mod.sparse_categorical_crossentropy + else: + metric_obj = metrics_mod.categorical_crossentropy + + if isinstance(metric_obj, losses_mod.Loss): + metric_obj._allow_sum_over_batch_size = True # pylint: disable=protected-access + + if not isinstance(metric_obj, metrics_mod.Metric): + if isinstance(metric, str): + metric_name = metric + else: + metric_name = get_custom_object_name(metric) + if metric_name is None: + raise ValueError( + 'Metric should be a callable, found: {}'.format(metric)) + + metric_obj = metrics_mod.MeanMetricWrapper(metric_obj, name=metric_name) + + return metric_obj + + def _should_broadcast(self, obj): + # e.g. 'mse'. + if not nest.is_nested(obj): + return True + # e.g. ['mse'] or ['mse', 'mae']. + return (isinstance(obj, (list, tuple)) and + not any(nest.is_nested(o) for o in obj)) + + def _copy_object(self, obj): + if isinstance(obj, metrics_mod.Metric): + return obj.__class__.from_config(obj.get_config()) + return obj # Can be a function or `None`. + + +def create_pseudo_output_names(outputs): + """Create pseudo output names for a subclassed Model.""" + return _create_pseudo_names(outputs, prefix='output_') + + +def create_pseudo_input_names(inputs): + """Create pseudo input names for a subclassed Model.""" + return _create_pseudo_names(inputs, prefix='input_') + + +def _create_pseudo_names(tensors, prefix): + """Creates pseudo {input | output} names for subclassed Models. + + Warning: this function should only be used to define default + names for `Metics` and `SavedModel`. No other use cases should + rely on a `Model`'s input or output names. + + Example with dict: + + `{'a': [x1, x2], 'b': x3}` becomes: + `['a_1', 'a_2', 'b']` + + Example with list: + + `[x, y]` becomes: + `['output_1', 'output_2']` + + Args: + tensors: `Model`'s outputs or inputs. + prefix: 'output_' for outputs, 'input_' for inputs. + + Returns: + Flattened list of pseudo names. + """ + + def one_index(ele): + # Start with "output_1" instead of "output_0". + if isinstance(ele, int): + return ele + 1 + return ele + + flat_paths = list(nest.yield_flat_paths(tensors)) + flat_paths = nest.map_structure(one_index, flat_paths) + names = [] + for path in flat_paths: + if not path: + name = prefix + '1' # Single output. + else: + name = '_'.join(str(p) for p in path) + if isinstance(path[0], int): + name = prefix + name + names.append(name) + return names + + +def map_to_output_names(y_pred, output_names, struct): + """Maps a dict to a list using `output_names` as keys. + + This is a convenience feature only. When a `Model`'s outputs + are a list, you can specify per-output losses and metrics as + a dict, where the keys are the output names. If you specify + per-output losses and metrics via the same structure as the + `Model`'s outputs (recommended), no mapping is performed. + + For the Functional API, the output names are the names of the + last layer of each output. For the Subclass API, the output names + are determined by `create_pseudo_output_names` (For example: + `['output_1', 'output_2']` for a list of outputs). + + This mapping preserves backwards compatibility for `compile` and + `fit`. + + Args: + y_pred: Sample outputs of the Model, to determine if this convenience + feature should be applied (`struct` is returned unmodified if `y_pred` + isn't a flat list). + output_names: List. The names of the outputs of the Model. + struct: The structure to map. + + Returns: + `struct` mapped to a list in same order as `output_names`. + """ + single_output = not nest.is_nested(y_pred) + outputs_are_flat_list = (not single_output and + isinstance(y_pred, (list, tuple)) and + not any(nest.is_nested(y_p) for y_p in y_pred)) + + if (single_output or outputs_are_flat_list) and isinstance(struct, dict): + output_names = output_names or create_pseudo_output_names(y_pred) + struct = copy.copy(struct) + new_struct = [struct.pop(name, None) for name in output_names] + if struct: + raise ValueError('Found unexpected keys that do not correspond ' + 'to any Model output: {}. Expected: {}'.format( + struct.keys(), output_names)) + if len(new_struct) == 1: + return new_struct[0] + return new_struct + else: + return struct + + +def map_missing_dict_keys(y_pred, struct): + """Replaces missing dict keys in `struct` with `None` placeholders.""" + if not isinstance(y_pred, dict) or not isinstance(struct, dict): + return struct + for k in y_pred.keys(): + if k not in struct: + struct[k] = None + return struct + + +def match_dtype_and_rank(y_t, y_p, sw): + """Match dtype and rank of predictions.""" + if y_t.shape.rank == 1 and y_p.shape.rank == 2: + y_t = array_ops.expand_dims_v2(y_t, axis=-1) + if sw is not None: + if sw.shape.rank == 1 and y_p.shape.rank == 2: + sw = array_ops.expand_dims_v2(sw, axis=-1) + + # Dtype. + # This is required mainly for custom loss functions which do not take care + # casting dtypes. + if ((y_t.dtype.is_floating and y_p.dtype.is_floating) or + (y_t.dtype.is_integer and y_p.dtype.is_integer)): + y_t = math_ops.cast(y_t, y_p.dtype) + + if sw is not None: + sw = math_ops.cast(sw, y_p.dtype) + return y_t, y_p, sw + + +def get_mask(y_p): + """Returns Keras mask from tensor.""" + return getattr(y_p, '_keras_mask', None) + + +def apply_mask(y_p, sw, mask): + """Applies any mask on predictions to sample weights.""" + if mask is not None: + mask = math_ops.cast(mask, y_p.dtype) + if sw is not None: + mask, _, sw = ( + losses_utils.squeeze_or_expand_dimensions(mask, sample_weight=sw)) + sw *= mask + else: + sw = mask + return sw + + +def get_custom_object_name(obj): + """Returns the name to use for a custom loss or metric callable. + + Args: + obj: Custom loss of metric callable + + Returns: + Name to use, or `None` if the object was not recognized. + """ + if hasattr(obj, 'name'): # Accept `Loss` instance as `Metric`. + return obj.name + elif hasattr(obj, '__name__'): # Function. + return obj.__name__ + elif hasattr(obj, '__class__'): # Class instance. + return generic_utils.to_snake_case(obj.__class__.__name__) + else: # Unrecognized object. + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/data_adapter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/data_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..f48da337048157dd8dabb396e148635a9ba75e99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/data_adapter.py @@ -0,0 +1,1696 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adapter module that convert different input data objects into tf.dataset.""" + +import abc +import contextlib +import functools +import itertools +import math +import random + +import numpy as np + +from tensorflow.python.data.experimental.ops import cardinality +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import input_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.utils import data_utils +from tensorflow.python.keras.utils import dataset_creator +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import script_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest + + +class DataAdapter(object, metaclass=abc.ABCMeta): + """Base class for input data adapter. + + In TF 2.0, tf.data is the preferred API for user to feed in data. In order + to simplify the training code path, all the input data object will be + converted to `tf.data.Dataset` if possible. + + Note that since this class is mainly targeted for TF 2.0, it might have a lot + of assumptions under the hood, eg eager context by default, distribution + strategy, etc. In the meantime, some legacy feature support might be dropped, + eg, Iterator from dataset API in v1, etc. + + The sample usage of this class is like: + + ``` + x = tf.data.Dataset.range(100) + adapter_cls = [NumpyArrayDataAdapter, ..., DatasetAdapter] + applicable_adapters = [cls for cls in adapter_cls if cls.can_handle(x)] + if len(applicable_adapters) != 1: + raise ValueError("Expect only one adapter class to handle the input") + + dataset = applicable_adapters[0](x).get_dataset() + for data in dataset: + # training + ``` + """ + + @staticmethod + def can_handle(x, y=None): + """Whether the current DataAdapter could handle the input x and y. + + Structure wise, x and y can be single object, or list of objects if there + multiple input/output, or dictionary of objects when the intput/output are + named. + + Args: + x: input features. + y: target labels. Note that y could be None in the case of prediction. + + Returns: + boolean + """ + raise NotImplementedError + + @abc.abstractmethod + def __init__(self, x, y=None, **kwargs): + """Create a DataAdapter based on data inputs. + + The caller must make sure to call `can_handle()` first before invoking this + method. Provide unsupported data type will result into unexpected behavior. + + Args: + x: input features. + y: target labels. Note that y could be None in the case of prediction. + **kwargs: Other keyword arguments for DataAdapter during the construction + of the tf.dataset.Dataset. For example: + - Numpy data might have `sample_weights` which will be used for + weighting the loss function during training. + - Numpy data might need to have `batch_size` parameter when constructing + the dataset and iterator. + - Certain input might need to be distribution strategy aware. When + `distribution_strategy` is passed, the created dataset need to respect + the strategy. + DataAdapter might choose to ignore any keyword argument if it doesn't + use it, or raise exception if any required argument is not provide. + """ + if not self.can_handle(x, y): + raise ValueError("{} Cannot handle input {}, {}".format( + self.__class__, x, y)) + + @abc.abstractmethod + def get_dataset(self): + """Get a dataset instance for the current DataAdapter. + + Note that the dataset returned does not repeat for epoch, so caller might + need to create new iterator for the same dataset at the beginning of the + epoch. This behavior might change in future. + + Returns: + An tf.dataset.Dataset. Caller might use the dataset in different + context, eg iter(dataset) in eager to get the value directly, or in graph + mode, provide the iterator tensor to Keras model function. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_size(self): + """Return the size (number of batches) for the dataset created. + + For certain type of the data input, the number of batches is known, eg for + Numpy data, the size is same as (number_of_element / batch_size). Whereas + for dataset or python generator, the size is unknown since it may or may not + have a end state. + + Returns: + int, the number of batches for the dataset, or None if it is unknown. The + caller could use this to control the loop of training, show progress bar, + or handle unexpected StopIteration error. + """ + raise NotImplementedError + + @abc.abstractmethod + def batch_size(self): + """Return the batch size of the dataset created. + + For certain type of the data input, the batch size is known, and even + required, like numpy array. Where as for dataset, the batch is unknown + unless we take a peek. + + Returns: + int, the batch size of the dataset, or None if it is unknown. + """ + raise NotImplementedError + + def representative_batch_size(self): + """Return a representative size for batches in the dataset. + + This is not guaranteed to be the batch size for all batches in the + dataset. It just needs to be a rough approximation for batch sizes in + the dataset. + + Returns: + int, a representative size for batches found in the dataset, + or None if it is unknown. + """ + return self.batch_size() + + @abc.abstractmethod + def has_partial_batch(self): + """Whether the dataset has partial batch at the end.""" + raise NotImplementedError + + @abc.abstractmethod + def partial_batch_size(self): + """The size of the final partial batch for dataset. + + Will return None if has_partial_batch is False or batch_size is None. + """ + raise NotImplementedError + + @abc.abstractmethod + def should_recreate_iterator(self): + """Returns whether a new iterator should be created every epoch.""" + raise NotImplementedError + + def get_samples(self): + """Returns number of samples in the data, or `None`.""" + if not self.get_size() or not self.batch_size(): + return None + total_sample = self.get_size() * self.batch_size() + if self.has_partial_batch(): + total_sample -= (self.batch_size() - self.partial_batch_size()) + return total_sample + + def on_epoch_end(self): + """A hook called after each epoch.""" + pass + + +class TensorLikeDataAdapter(DataAdapter): + """Adapter that handles Tensor-like objects, e.g. EagerTensor and NumPy.""" + + @staticmethod + def can_handle(x, y=None): + # TODO(kaftan): Check performance implications of using a flatten + # here for other types of inputs. + flat_inputs = nest.flatten(x) + if y is not None: + flat_inputs += nest.flatten(y) + + tensor_types = _get_tensor_types() + + def _is_tensor(v): + if isinstance(v, tensor_types): + return True + return False + + return all(_is_tensor(v) for v in flat_inputs) + + def __init__(self, + x, + y=None, + sample_weights=None, + sample_weight_modes=None, + batch_size=None, + epochs=1, + steps=None, + shuffle=False, + **kwargs): + super(TensorLikeDataAdapter, self).__init__(x, y, **kwargs) + x, y, sample_weights = _process_tensorlike((x, y, sample_weights)) + sample_weight_modes = broadcast_sample_weight_modes( + sample_weights, sample_weight_modes) + + # If sample_weights are not specified for an output use 1.0 as weights. + (sample_weights, _, _) = training_utils.handle_partial_sample_weights( + y, sample_weights, sample_weight_modes, check_all_flat=True) + + inputs = pack_x_y_sample_weight(x, y, sample_weights) + + num_samples = set(int(i.shape[0]) for i in nest.flatten(inputs)).pop() + _check_data_cardinality(inputs) + + # If batch_size is not passed but steps is, calculate from the input data. + # Default to 32 for backwards compat. + if not batch_size: + batch_size = int(math.ceil(num_samples / steps)) if steps else 32 + + self._size = int(math.ceil(num_samples / batch_size)) + self._batch_size = batch_size + + num_full_batches = int(num_samples // batch_size) + self._partial_batch_size = num_samples % batch_size + + if isinstance(shuffle, str): + shuffle = shuffle.lower() + + self._shuffle = shuffle + # Vectorized version of shuffle. + # This is a performance improvement over using `from_tensor_slices`. + # The indices of the data are shuffled and batched, and these indices + # are then zipped with the data and used to extract a batch of the data + # at each step. The performance improvements here come from: + # 1. vectorized batch using gather + # 2. parallelized map + # 3. pipelined permutation generation + # 4. optimized permutation batching + # 5. disabled static optimizations + + indices_dataset = dataset_ops.DatasetV2.range(1) + if shuffle != "batch": + indices_dataset = indices_dataset.repeat(epochs) + + def permutation(_): + # It turns out to be more performant to make a new set of indices rather + # than reusing the same range Tensor. (presumably because of buffer + # forwarding.) + indices = math_ops.range(num_samples, dtype=dtypes.int64) + if shuffle and shuffle != "batch": + indices = random_ops.random_shuffle(indices) + return indices + + # We prefetch a single element. Computing large permutations can take quite + # a while so we don't want to wait for prefetching over an epoch boundary to + # trigger the next permutation. On the other hand, too many simultaneous + # shuffles can contend on a hardware level and degrade all performance. + indices_dataset = indices_dataset.map(permutation).prefetch(1) + + def slice_batch_indices(indices): + """Convert a Tensor of indices into a dataset of batched indices. + + This step can be accomplished in several ways. The most natural is to + slice the Tensor in a Dataset map. (With a condition on the upper index to + handle the partial batch.) However it turns out that coercing the Tensor + into a shape which is divisible by the batch size (and handling the last + partial batch separately) allows for a much more favorable memory access + pattern and improved performance. + + Args: + indices: Tensor which determines the data order for an entire epoch. + + Returns: + A Dataset of batched indices. + """ + num_in_full_batch = num_full_batches * batch_size + first_k_indices = array_ops.slice(indices, [0], [num_in_full_batch]) + first_k_indices = array_ops.reshape( + first_k_indices, [num_full_batches, batch_size]) + + flat_dataset = dataset_ops.DatasetV2.from_tensor_slices(first_k_indices) + if self._partial_batch_size: + index_remainder = dataset_ops.DatasetV2.from_tensors(array_ops.slice( + indices, [num_in_full_batch], [self._partial_batch_size])) + flat_dataset = flat_dataset.concatenate(index_remainder) + + if shuffle == "batch": + # 1024 is a magic constant that has not been properly evaluated + flat_dataset = flat_dataset.shuffle(1024).repeat(epochs) + return flat_dataset + + indices_dataset = indices_dataset.flat_map(slice_batch_indices) + + dataset = self.slice_inputs(indices_dataset, inputs) + + if shuffle == "batch": + def shuffle_batch(*batch): + return nest.map_structure(random_ops.random_shuffle, batch) + dataset = dataset.map(shuffle_batch) + + self._dataset = dataset + + def slice_inputs(self, indices_dataset, inputs): + """Slice inputs into a Dataset of batches. + + Given a Dataset of batch indices and the unsliced inputs, + this step slices the inputs in a parallelized fashion + and produces a dataset of input batches. + + Args: + indices_dataset: A Dataset of batched indices + inputs: A python data structure that contains the inputs, targets, + and possibly sample weights. + + Returns: + A Dataset of input batches matching the batch indices. + """ + dataset = dataset_ops.DatasetV2.zip(( + indices_dataset, + dataset_ops.DatasetV2.from_tensors(inputs).repeat() + )) + + def grab_batch(i, data): + return nest.map_structure(lambda d: array_ops.gather(d, i, axis=0), data) + + dataset = dataset.map( + grab_batch, num_parallel_calls=dataset_ops.AUTOTUNE) + + # Default optimizations are disabled to avoid the overhead of (unnecessary) + # input pipeline graph serialization and deserialization + options = options_lib.Options() + options.experimental_optimization.apply_default_optimizations = False + if self._shuffle: + # See b/141490660 for more details. + options.experimental_external_state_policy = ( + options_lib.ExternalStatePolicy.IGNORE) + dataset = dataset.with_options(options) + return dataset + + def get_dataset(self): + return self._dataset + + def get_size(self): + return self._size + + def batch_size(self): + return self._batch_size + + def has_partial_batch(self): + return self._partial_batch_size > 0 + + def partial_batch_size(self): + return self._partial_batch_size or None + + def should_recreate_iterator(self): + # An infinite dataset is always created here. + return False + + +class GenericArrayLikeDataAdapter(TensorLikeDataAdapter): + """Adapter that handles array-like data without forcing it into memory. + + This adapter handles array-like datasets that may be too big to fully + fit into memory. + + Specifically, this adapter handles any Python class which implements: + `__get_item__`, `__len__`, `shape`, and `dtype` with the same meanings + as Numpy, but it ignores any case where all the inputs are Tensors or Numpy + arrays (because that case is handled by the base TensorLikeDataAdapter). + + It ignores scipy sparse matrices and Composite Tensors because those are + handled by the CompositeTensorDataAdapter. + + It also does not handle lists/tuples of scalars, because those are handled + by the ListsOfScalarsDataAdapter. + """ + + @staticmethod + def can_handle(x, y=None): + flat_inputs = nest.flatten(x) + if y is not None: + flat_inputs += nest.flatten(y) + + def _is_array_like(v): + """Return True if v is a Tensor, array, or is array-like.""" + return ( + hasattr(v, "__getitem__") and + hasattr(v, "shape") and + hasattr(v, "dtype") and + hasattr(v, "__len__") + ) + + if (not TensorLikeDataAdapter.can_handle(x, y) and + not CompositeTensorDataAdapter.can_handle(x, y)): + return all(_is_array_like(v) for v in flat_inputs) + else: + return False + + def __init__(self, *args, **kwargs): + logging.warning( + "Keras is training/fitting/evaluating on array-like data. Keras may " + "not be optimized for this format, so if your input data format is " + "supported by TensorFlow I/O (https://github.com/tensorflow/io) we " + "recommend using that to load a Dataset instead.") + + super(GenericArrayLikeDataAdapter, self).__init__(*args, **kwargs) + + def slice_inputs(self, indices_dataset, inputs): + """Slice inputs into a Dataset of batches. + + Given a Dataset of batch indices and the unsliced inputs, + this step slices the inputs in a parallelized fashion + and produces a dataset of input batches. + + Args: + indices_dataset: A Dataset of batched indices + inputs: A python data structure that contains the inputs, targets, + and possibly sample weights. + + Returns: + A Dataset of input batches matching the batch indices. + """ + flat_inputs = nest.flatten(inputs) + def dynamic_shape_like(t): + shape = list(t.shape) + shape[0] = None + return tuple(shape) + + flat_dtypes = [inp.dtype for inp in flat_inputs] + contiguous = True + if self._shuffle and self._shuffle != "batch": + contiguous = False + + def grab_batch(indices): + """Grab a batch of data from the inputs.""" + # This uses a py_function to avoid converting the array-like + # into a Tensor before slicing it, because converting the array-like + # to a Tensor may force it into memory.. + def py_method(ind): + def slice_array(data): + return training_utils.slice_arrays(data, ind.numpy(), + contiguous=contiguous) + return [slice_array(inp) for inp in flat_inputs] + + flat_out = script_ops.eager_py_func(py_method, [indices], flat_dtypes) + for v, original_inp in zip(flat_out, flat_inputs): + v.set_shape(dynamic_shape_like(original_inp)) + return nest.pack_sequence_as(inputs, flat_out) + + dataset = indices_dataset.map( + grab_batch, num_parallel_calls=dataset_ops.AUTOTUNE) + + return dataset + + +class DatasetCreatorAdapter(DataAdapter): + """Adapter that handles dataset functions.""" + + def __init__(self, x, y, steps=None, distribution_strategy=None, **kwargs): + super(DatasetCreatorAdapter, self).__init__(x, **kwargs) + + if not isinstance(x, dataset_creator.DatasetCreator): + raise TypeError("The input of a `DatasetCreatorAdapter` should be a " + "`DatasetCreator` but it received type {}.".format( + type(x))) + if steps is None: + raise ValueError("When using a " + "`tf.keras.utils.experimental.DatasetCreator`, " + "`steps_per_epoch`, `validation_steps` or `steps` " + "argument must be provided in `Model.fit`, " + "`Model.evaluate`, or `Model.predict`.") + self.dataset_creator = x + self.steps = steps + self.strategy = distribution_strategy + + @staticmethod + def can_handle(x, y=None): + if isinstance(x, dataset_creator.DatasetCreator): + assert y is None + return True + + def should_recreate_iterator(self): + # We expect users to shuffle the dataset in their `dataset_fn` supplied to + # `DatasetCreator`. Since that is a buffered shuffle, we intend to not reset + # the dataset so the batches that are not shuffled can still be pulled. + return False + + def get_size(self): + return None # To be inferred by `DataHandler`. + + def get_dataset(self): + return self.strategy.distribute_datasets_from_function( + self.dataset_creator, options=self.dataset_creator.input_options) + + def batch_size(self): + raise NotImplementedError() + + def has_partial_batch(self): + raise NotImplementedError() + + def partial_batch_size(self): + raise NotImplementedError() + + +class CompositeTensorDataAdapter(DataAdapter): + """Adapter that handles composite tensor.""" + + @staticmethod + def can_handle(x, y=None): + flat_inputs = nest.flatten(x) + if y is not None: + flat_inputs += nest.flatten(y) + + def _is_composite(v): + # Dataset/iterator/DistributedDataset inherits from CompositeTensor but + # should be handled by DatasetAdapter and GeneratorAdapter. + if (tf_utils.is_extension_type(v) and + not isinstance(v, + (dataset_ops.DatasetV2, iterator_ops.IteratorBase)) and + not _is_distributed_dataset(v)): + return True + # Support Scipy sparse tensors if scipy is installed + return _is_scipy_sparse(v) + + def _is_tensor_or_composite(v): + if isinstance(v, (tensor.Tensor, np.ndarray)): + return True + return _is_composite(v) + + return (any(_is_composite(v) for v in flat_inputs) and + all(_is_tensor_or_composite(v) for v in flat_inputs)) + + def __init__(self, + x, + y=None, + sample_weights=None, + sample_weight_modes=None, + batch_size=None, + steps=None, + shuffle=False, + **kwargs): + super(CompositeTensorDataAdapter, self).__init__(x, y, **kwargs) + x, y, sample_weights = _process_tensorlike((x, y, sample_weights)) + sample_weight_modes = broadcast_sample_weight_modes( + sample_weights, sample_weight_modes) + + # If sample_weights are not specified for an output use 1.0 as weights. + (sample_weights, _, _) = training_utils.handle_partial_sample_weights( + y, sample_weights, sample_weight_modes, check_all_flat=True) + + inputs = pack_x_y_sample_weight(x, y, sample_weights) + + dataset = dataset_ops.DatasetV2.from_tensor_slices(inputs) + num_samples = int(nest.flatten(x)[0].shape[0]) + if shuffle: + dataset = dataset.shuffle(num_samples) + + # If batch_size is not passed but steps is, calculate from the input data. + # Default to 32 for backwards compat. + if not batch_size: + batch_size = int(math.ceil(num_samples / steps)) if steps else 32 + + dataset = dataset.batch(batch_size) + self._size = int(math.ceil(num_samples / batch_size)) + self._batch_size = batch_size + self._has_partial_batch = (self._size != (num_samples // batch_size)) + + self._partial_batch_size = None + if self._has_partial_batch: + self._partial_batch_size = ( + num_samples - (self._size - 1) * self._batch_size) + + self._dataset = dataset + + def get_dataset(self): + return self._dataset + + def get_size(self): + return self._size + + def batch_size(self): + return self._batch_size + + def has_partial_batch(self): + return self._has_partial_batch + + def partial_batch_size(self): + return self._partial_batch_size + + def should_recreate_iterator(self): + return True + + +class ListsOfScalarsDataAdapter(DataAdapter): + """Adapter that handles lists of scalars and lists of lists of scalars.""" + + @staticmethod + def can_handle(x, y=None): + handles_x = ListsOfScalarsDataAdapter._is_list_of_scalars(x) + handles_y = True + if y is not None: + handles_y = ListsOfScalarsDataAdapter._is_list_of_scalars(y) + return handles_x and handles_y + + @staticmethod + def _is_list_of_scalars(inp): + if isinstance(inp, (float, int, str, bytes, bytearray)): + return True + if isinstance(inp, (list, tuple)) and inp: + return ListsOfScalarsDataAdapter._is_list_of_scalars(inp[0]) + return False + + def __init__(self, + x, + y=None, + sample_weights=None, + sample_weight_modes=None, + batch_size=None, + shuffle=False, + **kwargs): + super(ListsOfScalarsDataAdapter, self).__init__(x, y, **kwargs) + x = np.asarray(x) + if y is not None: + y = np.asarray(y) + if sample_weights is not None: + sample_weights = np.asarray(sample_weights) + sample_weight_modes = broadcast_sample_weight_modes( + sample_weights, sample_weight_modes) + + self._internal_adapter = TensorLikeDataAdapter( + x, + y=y, + sample_weights=sample_weights, + sample_weight_modes=sample_weight_modes, + batch_size=batch_size, + shuffle=shuffle, + **kwargs) + + def get_dataset(self): + return self._internal_adapter.get_dataset() + + def get_size(self): + return self._internal_adapter.get_size() + + def batch_size(self): + return self._internal_adapter.batch_size() + + def has_partial_batch(self): + return self._internal_adapter.has_partial_batch() + + def partial_batch_size(self): + return self._internal_adapter.partial_batch_size() + + def should_recreate_iterator(self): + return True + + +class DatasetAdapter(DataAdapter): + """Adapter that handles `tf.data.Dataset`.""" + + @staticmethod + def can_handle(x, y=None): + return (isinstance(x, (data_types.DatasetV1, data_types.DatasetV2)) or + _is_distributed_dataset(x)) + + def __init__(self, + x, + y=None, + sample_weights=None, + steps=None, + **kwargs): + super(DatasetAdapter, self).__init__(x, y, **kwargs) + # Note that the dataset instance is immutable, its fine to reuse the user + # provided dataset. + self._dataset = x + + # The user-provided steps. + self._user_steps = steps + + self._validate_args(y, sample_weights, steps) + + def get_dataset(self): + return self._dataset + + def get_size(self): + return # Inferred in `DataHandler`. + + def batch_size(self): + return None + + def has_partial_batch(self): + return False + + def partial_batch_size(self): + return None + + def should_recreate_iterator(self): + # Since DistributedDatasets have no cardinality, the user must provide + # all steps that need to be run, calling `.repeat()` as needed. + if _is_distributed_dataset(self._dataset): + return False + + # If user doesn't supply `steps`, or if they supply `steps` that + # exactly equals the size of the `Dataset`, create a new iterator + # each epoch. + return (self._user_steps is None or + cardinality.cardinality(self._dataset).numpy() == self._user_steps) + + def _validate_args(self, y, sample_weights, steps): + """Validates `__init__` arguments.""" + # Arguments that shouldn't be passed. + if not is_none_or_empty(y): + raise ValueError("`y` argument is not supported when using " + "dataset as input.") + if not is_none_or_empty(sample_weights): + raise ValueError("`sample_weight` argument is not supported when using " + "dataset as input.") + + if steps is None: + if _is_distributed_dataset(self._dataset): + raise ValueError("When providing a distributed dataset, you must " + "specify the number of steps to run.") + + size = cardinality.cardinality(self._dataset).numpy() + if size == cardinality.INFINITE and steps is None: + raise ValueError( + "When providing an infinite dataset, you must specify " + "the number of steps to run (if you did not intend to " + "create an infinite dataset, make sure to not call " + "`repeat()` on the dataset).") + + +class GeneratorDataAdapter(DataAdapter): + """Adapter that handles python generators and iterators.""" + + @staticmethod + def can_handle(x, y=None): + return ((hasattr(x, "__next__") or hasattr(x, "next")) + and hasattr(x, "__iter__") + and not isinstance(x, data_utils.Sequence)) + + def __init__(self, + x, + y=None, + sample_weights=None, + workers=1, + use_multiprocessing=False, + max_queue_size=10, + model=None, + **kwargs): + # Generators should never shuffle as exhausting the generator in order to + # shuffle the batches is inefficient. + kwargs.pop("shuffle", None) + + if not is_none_or_empty(y): + raise ValueError("`y` argument is not supported when using " + "python generator as input.") + if not is_none_or_empty(sample_weights): + raise ValueError("`sample_weight` argument is not supported when using " + "python generator as input.") + + super(GeneratorDataAdapter, self).__init__(x, y, **kwargs) + + # Since we have to know the dtype of the python generator when we build the + # dataset, we have to look at a batch to infer the structure. + peek, x = self._peek_and_restore(x) + peek = self._standardize_batch(peek) + peek = _process_tensorlike(peek) + + # Need to build the Model on concrete input shapes. + if model is not None and not model.built: + concrete_x, _, _ = unpack_x_y_sample_weight(peek) + model.distribute_strategy.run( + lambda x: model(x, training=False), args=(concrete_x,)) + + self._first_batch_size = int(nest.flatten(peek)[0].shape[0]) + + def _get_dynamic_shape(t): + shape = t.shape + # Unknown number of dimensions, `as_list` cannot be called. + if shape.rank is None: + return shape + return tensor_shape.TensorShape([None for _ in shape.as_list()]) + + output_shapes = nest.map_structure(_get_dynamic_shape, peek) + output_types = nest.map_structure(lambda t: t.dtype, peek) + + # Note that dataset API takes a callable that creates a generator object, + # rather than generator itself, which is why we define a function here. + generator_fn = self._handle_multiprocessing(x, workers, use_multiprocessing, + max_queue_size) + + def wrapped_generator(): + for data in generator_fn(): + yield self._standardize_batch(data) + + dataset = dataset_ops.DatasetV2.from_generator( + wrapped_generator, output_types, output_shapes=output_shapes) + + if workers == 1 and not use_multiprocessing: + dataset = dataset.prefetch(1) + + self._dataset = dataset + + def _standardize_batch(self, data): + """Standardizes a batch output by a generator.""" + # Removes `None`s. + x, y, sample_weight = unpack_x_y_sample_weight(data) + data = pack_x_y_sample_weight(x, y, sample_weight) + + data = nest.list_to_tuple(data) + + def _convert_dtype(t): + if (isinstance(t, np.ndarray) and issubclass(t.dtype.type, np.floating)): + return np.array(t, dtype=backend.floatx()) + return t + + data = nest.map_structure(_convert_dtype, data) + return data + + @staticmethod + def _peek_and_restore(x): + peek = next(x) + return peek, itertools.chain([peek], x) + + def _handle_multiprocessing(self, x, workers, use_multiprocessing, + max_queue_size): + """Create a callable, possibly including an Enqueuer.""" + if workers > 1 or (workers > 0 and use_multiprocessing): + def generator_fn(): + enqueuer = data_utils.GeneratorEnqueuer( + x, use_multiprocessing=use_multiprocessing) + enqueuer.start(workers=workers, max_queue_size=max_queue_size) + return enqueuer.get() + else: + generator_fn = lambda: x + return generator_fn + + def get_dataset(self): + return self._dataset + + def get_size(self): + return None + + def batch_size(self): + return None + + def representative_batch_size(self): + return self._first_batch_size + + def has_partial_batch(self): + return False + + def partial_batch_size(self): + return + + def should_recreate_iterator(self): + return False + + +class KerasSequenceAdapter(GeneratorDataAdapter): + """Adapter that handles `keras.utils.Sequence`.""" + + @staticmethod + def can_handle(x, y=None): + return isinstance(x, data_utils.Sequence) + + def __init__(self, + x, + y=None, + sample_weights=None, + shuffle=False, + workers=1, + use_multiprocessing=False, + max_queue_size=10, + model=None, + **kwargs): + if not is_none_or_empty(y): + raise ValueError("`y` argument is not supported when using " + "`keras.utils.Sequence` as input.") + if not is_none_or_empty(sample_weights): + raise ValueError("`sample_weight` argument is not supported when using " + "`keras.utils.Sequence` as input.") + + self._size = len(x) + self._shuffle_sequence = shuffle + self._keras_sequence = x + self._enqueuer = None + super(KerasSequenceAdapter, self).__init__( + x, + shuffle=False, # Shuffle is handed in the _make_callable override. + workers=workers, + use_multiprocessing=use_multiprocessing, + max_queue_size=max_queue_size, + model=model, + **kwargs) + + @staticmethod + def _peek_and_restore(x): + return x[0], x + + def _handle_multiprocessing(self, x, workers, use_multiprocessing, + max_queue_size): + if workers > 1 or (workers > 0 and use_multiprocessing): + def generator_fn(): + self._enqueuer = data_utils.OrderedEnqueuer( + x, use_multiprocessing=use_multiprocessing, + shuffle=self._shuffle_sequence) + self._enqueuer.start(workers=workers, max_queue_size=max_queue_size) + return self._enqueuer.get() + else: + def generator_fn(): + order = range(len(x)) + if self._shuffle_sequence: + # Match the shuffle convention in OrderedEnqueuer. + order = list(order) + random.shuffle(order) + + for i in order: + yield x[i] + + return generator_fn + + def get_size(self): + return self._size + + def should_recreate_iterator(self): + return True + + def on_epoch_end(self): + if self._enqueuer: + self._enqueuer.stop() + self._keras_sequence.on_epoch_end() + + +ALL_ADAPTER_CLS = [ + ListsOfScalarsDataAdapter, TensorLikeDataAdapter, + GenericArrayLikeDataAdapter, DatasetAdapter, GeneratorDataAdapter, + KerasSequenceAdapter, CompositeTensorDataAdapter, DatasetCreatorAdapter +] + + +def select_data_adapter(x, y): + """Selects a data adapter than can handle a given x and y.""" + adapter_cls = [cls for cls in ALL_ADAPTER_CLS if cls.can_handle(x, y)] + if not adapter_cls: + # TODO(scottzhu): This should be a less implementation-specific error. + raise ValueError( + "Failed to find data adapter that can handle " + "input: {}, {}".format( + _type_name(x), _type_name(y))) + elif len(adapter_cls) > 1: + raise RuntimeError( + "Data adapters should be mutually exclusive for " + "handling inputs. Found multiple adapters {} to handle " + "input: {}, {}".format( + adapter_cls, _type_name(x), _type_name(y))) + return adapter_cls[0] + + +def _type_name(x): + """Generates a description of the type of an object.""" + if isinstance(x, dict): + key_types = set(_type_name(key) for key in x.keys()) + val_types = set(_type_name(key) for key in x.values()) + return "({} containing {} keys and {} values)".format( + type(x), key_types, val_types) + if isinstance(x, (list, tuple)): + types = set(_type_name(val) for val in x) + return "({} containing values of types {})".format( + type(x), types) + return str(type(x)) + + +def _process_tensorlike(inputs): + """Process tensor-like inputs. + + This function: + + (1) Converts `Numpy` arrays to `Tensor`s. + (2) Converts `Scipy` sparse matrices to `SparseTensor`s. + (2) Converts `list`s to `tuple`s (for `tf.data` support). + + Args: + inputs: Structure of `Tensor`s, `NumPy` arrays, or tensor-like. + + Returns: + Structure of `Tensor`s or tensor-like. + """ + + def _convert_numpy_and_scipy(x): + if isinstance(x, np.ndarray): + dtype = None + if issubclass(x.dtype.type, np.floating): + dtype = backend.floatx() + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + x, dtype=dtype + ) + elif _is_scipy_sparse(x): + return _scipy_sparse_to_sparse_tensor(x) + return x + + inputs = nest.map_structure(_convert_numpy_and_scipy, inputs) + return nest.list_to_tuple(inputs) + + +def is_none_or_empty(inputs): + # util method to check if the input is a None or a empty list. + # the python "not" check will raise an error like below if the input is a + # numpy array + # "The truth value of an array with more than one element is ambiguous. + # Use a.any() or a.all()" + return inputs is None or not nest.flatten(inputs) + + +def broadcast_sample_weight_modes(target_structure, sample_weight_modes): + """Match sample_weight_modes structure with output structure.""" + if target_structure is None or not nest.flatten(target_structure): + return sample_weight_modes + + if isinstance(sample_weight_modes, str): + if isinstance(target_structure, dict): + return {key: sample_weight_modes for key in target_structure.keys()} + return [sample_weight_modes for _ in target_structure] + + if sample_weight_modes: + try: + nest.assert_same_structure( + training_utils.list_to_tuple(target_structure), + training_utils.list_to_tuple(sample_weight_modes)) + except (ValueError, TypeError): + target_str = str(nest.map_structure(lambda _: "...", target_structure)) + mode_str = str(nest.map_structure(lambda _: "...", sample_weight_modes)) + + # Attempt to coerce sample_weight_modes to the target structure. This + # implicitly depends on the fact that Model flattens outputs for its + # internal representation. + try: + sample_weight_modes = nest.pack_sequence_as( + target_structure, nest.flatten(sample_weight_modes)) + logging.warning( + "sample_weight modes were coerced from\n {}\n to \n {}" + .format(target_str, mode_str)) + except (ValueError, TypeError): + raise ValueError( + "Unable to match target structure and sample_weight_modes " + "structure:\n {}\n to \n {}".format(target_str, mode_str)) + + return sample_weight_modes + + +class DataHandler(object): + """Handles iterating over epoch-level `tf.data.Iterator` objects.""" + + def __init__(self, + x, + y=None, + sample_weight=None, + batch_size=None, + steps_per_epoch=None, + initial_epoch=0, + epochs=1, + shuffle=False, + class_weight=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + model=None, + steps_per_execution=None, + distribute=True): + """Initializes a `DataHandler`. + + Arguments: + x: See `Model.fit`. + y: See `Model.fit`. + sample_weight: See `Model.fit`. + batch_size: See `Model.fit`. + steps_per_epoch: See `Model.fit`. + initial_epoch: See `Model.fit`. + epochs: See `Model.fit`. + shuffle: See `Model.fit`. + class_weight: See `Model.fit`. + max_queue_size: See `Model.fit`. + workers: See `Model.fit`. + use_multiprocessing: See `Model.fit`. + model: The `Model` instance. Needed in order to correctly `build` the + `Model` using generator-like inputs (see `GeneratorDataAdapter`). + steps_per_execution: See `Model.compile`. + distribute: Whether to distribute the `tf.dataset`. + `PreprocessingLayer.adapt` does not support distributed datasets, + `Model` should always set this to `True`. + """ + + self._initial_epoch = initial_epoch + self._epochs = epochs + self._insufficient_data = False + self._model = model + + # `steps_per_execution_value` is the cached initial value. + # `steps_per_execution` is mutable and may be changed by the DataAdapter + # to handle partial executions. + if steps_per_execution is None: + self._steps_per_execution = 1 + self._steps_per_execution_value = 1 + else: + self._steps_per_execution = steps_per_execution + self._steps_per_execution_value = steps_per_execution.numpy().item() + + adapter_cls = select_data_adapter(x, y) + self._adapter = adapter_cls( + x, + y, + batch_size=batch_size, + steps=steps_per_epoch, + epochs=epochs - initial_epoch, + sample_weights=sample_weight, + shuffle=shuffle, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + distribution_strategy=distribute_lib.get_strategy(), + model=model) + + strategy = distribute_lib.get_strategy() + + self._current_step = 0 + self._step_increment = self._steps_per_execution_value - 1 + self._insufficient_data = False + + self._configure_dataset_and_inferred_steps(strategy, x, steps_per_epoch, + class_weight, distribute) + + def _configure_dataset_and_inferred_steps(self, strategy, x, steps_per_epoch, + class_weight, distribute): + """Configure the `_dataset` and `_inferred_steps` attributes.""" + del x + dataset = self._adapter.get_dataset() + if class_weight: + dataset = dataset.map(_make_class_weight_map_fn(class_weight)) + self._inferred_steps = self._infer_steps(steps_per_epoch, dataset) + + # `PreprocessingLayer.adapt` does not currently support distributed + # datasets, so we pass `distribute=False` there. + if distribute and not _is_distributed_dataset(dataset): + dataset = strategy.experimental_distribute_dataset(dataset) + self._dataset = dataset + self._validate_data_handler() + + def enumerate_epochs(self): + """Yields `(epoch, tf.data.Iterator)`.""" + with self._truncate_execution_to_epoch(): + data_iterator = iter(self._dataset) + for epoch in range(self._initial_epoch, self._epochs): + if self._insufficient_data: # Set by `catch_stop_iteration`. + break + if self._adapter.should_recreate_iterator(): + data_iterator = iter(self._dataset) + yield epoch, data_iterator + self._adapter.on_epoch_end() + + @contextlib.contextmanager + def _truncate_execution_to_epoch(self): + """Truncates steps per execution to at most one epoch.""" + should_truncate = ( + self._inferred_steps is not None and + self._steps_per_execution_value > self._inferred_steps) + original_value = self._steps_per_execution_value + try: + if should_truncate: + self._steps_per_execution.assign(self._inferred_steps) + self._steps_per_execution_value = self._inferred_steps + yield + finally: + if should_truncate: + self._steps_per_execution.assign(original_value) + self._steps_per_execution_value = original_value + + def sync(self): + context.async_wait() + + @contextlib.contextmanager + def catch_stop_iteration(self): + """Catches errors when an iterator runs out of data.""" + try: + yield + self.sync() + except (StopIteration, errors.OutOfRangeError): + if self._inferred_steps is None: + self._inferred_steps = self._current_step + else: + self._insufficient_data = True + total_epochs = self._epochs - self._initial_epoch + logging.warning( + "Your input ran out of data; interrupting training. " + "Make sure that your dataset or generator can generate at " + "least `steps_per_epoch * epochs` batches (in this case, " + "{} batches). You may need to use the repeat() function " + "when building your dataset.".format(total_epochs * + self._inferred_steps)) + + def steps(self): + """Yields steps for the current epoch.""" + self._current_step = 0 + # `self._inferred_steps` can be changed by `catch_stop_iteration`. + while (self._inferred_steps is None or + self._current_step < self._inferred_steps): + if self._insufficient_data: # Set by `catch_stop_iteration`. + break + + can_run_full_execution = ( + self._steps_per_execution_value == 1 or + self._inferred_steps is None or + self._inferred_steps - self._current_step >= + self._steps_per_execution_value) + + if can_run_full_execution: + self._step_increment = self._steps_per_execution_value - 1 + yield self._current_step + self._current_step += self._steps_per_execution_value + else: + # Last partial execution. + steps_remaining = self._inferred_steps - self._current_step + self._steps_per_execution.assign(steps_remaining) + self._step_increment = steps_remaining - 1 + yield self._current_step + self._current_step += steps_remaining + self._steps_per_execution.assign(self._steps_per_execution_value) + + @property + def step_increment(self): + """The number to increment the step for `on_batch_end` methods.""" + return self._step_increment + + @property + def inferred_steps(self): + """The inferred steps per epoch of the created `Dataset`. + + This will be `None` in the case where: + + (1) A `Dataset` of unknown cardinality was passed to the `DataHandler`, and + (2) `steps_per_epoch` was not provided, and + (3) The first epoch of iteration has not yet completed. + + Returns: + The inferred steps per epoch of the created `Dataset`. + """ + return self._inferred_steps + + @property + def should_sync(self): + # Catch OutOfRangeError for Datasets of unknown size. + # This blocks until the batch has finished executing. + # TODO(b/150292341): Allow multiple async steps here. + return self._inferred_steps is None + + def _log_indefinite_training_warning(self): + logging.warning("The training loop will run indefinitely since you have " + "set `steps_per_epoch=-1`. Please use batch-level " + "callbacks to save checkpoints or log training progress, " + "etc") + + def _infer_steps(self, steps, dataset): + """Infers steps_per_epoch needed to loop through a dataset.""" + if steps == -1: + self._log_indefinite_training_warning() + return None + + if steps is not None: + return steps + + adapter_steps = self._adapter.get_size() + if adapter_steps is not None: + return adapter_steps + + size = cardinality.cardinality(dataset) + if size == cardinality.INFINITE and steps is None: + raise ValueError( + "When passing an infinitely repeating dataset, please specify a " + "`steps_per_epoch` value so that epoch level " + "callbacks continue to work. The value can be arbitrary, or a number " + "that you think correctly defines the size of an epoch. " + "Epoch-level callbacks will then be called at this interval.") + if size >= 0: + return size.numpy().item() + return None + + @property + def _samples(self): + return self._adapter.get_samples() + + def _validate_data_handler(self): + # TODO(b/152094471): Support this with DistIter.get_next_as_optional. + if self._steps_per_execution_value > 1 and self._inferred_steps is None: + raise ValueError( + "Could not infer the size of the data. With " + "`steps_per_execution > 1`, you must specify the number of steps " + "to run.") + + +class _ClusterCoordinatorDataHandler(DataHandler): + """A `DataHandler` that is compatible with `ClusterCoordinator`.""" + + def __init__(self, x, y=None, **kwargs): + if not isinstance(x, dataset_creator.DatasetCreator): + x = self._convert_to_dataset_creator(x, y, **kwargs) + + super().__init__(x=x, **kwargs) + + def _convert_to_dataset_creator(self, x, y, **kwargs): + """Converts non-tf.data.Dataset to `DatasetCreator` instances.""" + + def _dataset_fn(input_context): + del input_context + data_adapter_cls = select_data_adapter(x, y) + return data_adapter_cls(x=x, y=y, **kwargs).get_dataset() + + # This check is needed because types like `tf.data.Dataset` don't work with + # PSS yet. So only apply this logic to the types we can support. + if (isinstance(x, _get_tensor_types()) and + isinstance(y, _get_tensor_types())): + return dataset_creator.DatasetCreator(_dataset_fn) + else: + raise NotImplementedError( + "Only `tf.keras.utils.experimental.DatasetCreator`, `tf.Tensor`, " + "numpy arrays and pandas dataframes are supported types at this " + "time.") + + def _configure_dataset_and_inferred_steps(self, strategy, x, steps_per_epoch, + class_weight, distribute): + if not isinstance(x, dataset_creator.DatasetCreator): + raise TypeError("When using `ParameterServerStrategy`, `x` must be a " + "`DatasetCreator`.") + + def per_worker_dataset_fn(): + + return strategy.distribute_datasets_from_function( + x, options=x.input_options) + + self._dataset = self._model._cluster_coordinator.create_per_worker_dataset( # pylint: disable=protected-access + per_worker_dataset_fn) + + if steps_per_epoch == -1: + self._inferred_steps = None + self._log_indefinite_training_warning() + else: + self._inferred_steps = steps_per_epoch + + def sync(self): + self._model._cluster_coordinator.join() # pylint: disable=protected-access + + +def get_data_handler(*args, **kwargs): + if getattr(kwargs["model"], "_cluster_coordinator", None): + return _ClusterCoordinatorDataHandler(*args, **kwargs) + return DataHandler(*args, **kwargs) + + +def _make_class_weight_map_fn(class_weight): + """Applies class weighting to a `Dataset`. + + The `Dataset` is assumed to be in format `(x, y)` or `(x, y, sw)`, where + `y` must be a single `Tensor`. + + Args: + class_weight: A map where the keys are integer class ids and values are + the class weights, e.g. `{0: 0.2, 1: 0.6, 2: 0.3}` + + Returns: + A function that can be used with `tf.data.Dataset.map` to apply class + weighting. + """ + class_ids = list(sorted(class_weight.keys())) + expected_class_ids = list(range(len(class_ids))) + if class_ids != expected_class_ids: + error_msg = ( + "Expected `class_weight` to be a dict with keys from 0 to one less " + "than the number of classes, found {}").format(class_weight) + raise ValueError(error_msg) + + class_weight_tensor = tensor_conversion.convert_to_tensor_v2_with_dispatch( + [class_weight[int(c)] for c in class_ids] + ) + + def _class_weights_map_fn(*data): + """Convert `class_weight` to `sample_weight`.""" + x, y, sw = unpack_x_y_sample_weight(data) + + if nest.is_nested(y): + raise ValueError( + "`class_weight` is only supported for Models with a single output.") + + if y.shape.rank > 2: + raise ValueError("`class_weight` not supported for " + "3+ dimensional targets.") + + y_classes = smart_cond.smart_cond( + y.shape.rank == 2 and backend.shape(y)[1] > 1, + lambda: backend.argmax(y, axis=1), + lambda: math_ops.cast(backend.reshape(y, (-1,)), dtypes.int64)) + + cw = array_ops.gather_v2(class_weight_tensor, y_classes) + if sw is not None: + cw = math_ops.cast(cw, sw.dtype) + sw, cw = expand_1d((sw, cw)) + # `class_weight` and `sample_weight` are multiplicative. + sw = sw * cw + else: + sw = cw + + return x, y, sw + + return _class_weights_map_fn + + +def expand_1d(data): + """Expands 1-dimensional `Tensor`s into 2-dimensional `Tensor`s.""" + + def _expand_single_1d_tensor(t): + # Leaves `CompositeTensor`s as-is. + if (isinstance(t, tensor.Tensor) and + isinstance(t.shape, tensor_shape.TensorShape) and t.shape.rank == 1): + return array_ops.expand_dims_v2(t, axis=-1) + return t + + return nest.map_structure(_expand_single_1d_tensor, data) + + +def train_validation_split(arrays, validation_split): + """Split arrays into train and validation subsets in deterministic order. + + The last part of data will become validation data. + + Args: + arrays: Tensors to split. Allowed inputs are arbitrarily nested structures + of Tensors and NumPy arrays. + validation_split: Float between 0 and 1. The proportion of the dataset to + include in the validation split. The rest of the dataset will be included + in the training split. + Returns: + `(train_arrays, validation_arrays)` + """ + + def _can_split(t): + tensor_types = _get_tensor_types() + return isinstance(t, tensor_types) or t is None + + flat_arrays = nest.flatten(arrays) + unsplitable = [type(t) for t in flat_arrays if not _can_split(t)] + if unsplitable: + raise ValueError( + "`validation_split` is only supported for Tensors or NumPy " + "arrays, found following types in the input: {}".format(unsplitable)) + + if all(t is None for t in flat_arrays): + return arrays, arrays + + first_non_none = None + for t in flat_arrays: + if t is not None: + first_non_none = t + break + + # Assumes all arrays have the same batch shape or are `None`. + batch_dim = int(first_non_none.shape[0]) + split_at = int(math.floor(batch_dim * (1. - validation_split))) + + if split_at == 0 or split_at == batch_dim: + raise ValueError( + "Training data contains {batch_dim} samples, which is not sufficient " + "to split it into a validation and training set as specified by " + "`validation_split={validation_split}`. Either provide more data, or a " + "different value for the `validation_split` argument." .format( + batch_dim=batch_dim, validation_split=validation_split)) + + def _split(t, start, end): + if t is None: + return t + return t[start:end] + + train_arrays = nest.map_structure( + functools.partial(_split, start=0, end=split_at), arrays) + val_arrays = nest.map_structure( + functools.partial(_split, start=split_at, end=batch_dim), arrays) + + return train_arrays, val_arrays + + +def unpack_x_y_sample_weight(data): + """Unpacks user-provided data tuple. + + This is a convenience utility to be used when overriding + `Model.train_step`, `Model.test_step`, or `Model.predict_step`. + This utility makes it easy to support data of the form `(x,)`, + `(x, y)`, or `(x, y, sample_weight)`. + + Standalone usage: + + >>> features_batch = tf.ones((10, 5)) + >>> labels_batch = tf.zeros((10, 5)) + >>> data = (features_batch, labels_batch) + >>> # `y` and `sample_weight` will default to `None` if not provided. + >>> x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data) + >>> sample_weight is None + True + + Example in overridden `Model.train_step`: + + ```python + class MyModel(tf.keras.Model): + + def train_step(self, data): + # If `sample_weight` is not provided, all samples will be weighted + # equally. + x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data) + + with tf.GradientTape() as tape: + y_pred = self(x, training=True) + loss = self.compiled_loss( + y, y_pred, sample_weight, regularization_losses=self.losses) + trainable_variables = self.trainable_variables + gradients = tape.gradient(loss, trainable_variables) + self.optimizer.apply_gradients(zip(gradients, trainable_variables)) + + self.compiled_metrics.update_state(y, y_pred, sample_weight) + return {m.name: m.result() for m in self.metrics} + ``` + + Args: + data: A tuple of the form `(x,)`, `(x, y)`, or `(x, y, sample_weight)`. + + Returns: + The unpacked tuple, with `None`s for `y` and `sample_weight` if they are not + provided. + """ + if not isinstance(data, tuple): + return (data, None, None) + elif len(data) == 1: + return (data[0], None, None) + elif len(data) == 2: + return (data[0], data[1], None) + elif len(data) == 3: + return (data[0], data[1], data[2]) + else: + error_msg = ("Data is expected to be in format `x`, `(x,)`, `(x, y)`, " + "or `(x, y, sample_weight)`, found: {}").format(data) + raise ValueError(error_msg) + + +def pack_x_y_sample_weight(x, y=None, sample_weight=None): + """Packs user-provided data into a tuple. + + This is a convenience utility for packing data into the tuple formats + that `Model.fit` uses. + + Standalone usage: + + >>> x = tf.ones((10, 1)) + >>> data = tf.keras.utils.pack_x_y_sample_weight(x) + >>> isinstance(data, tf.Tensor) + True + >>> y = tf.ones((10, 1)) + >>> data = tf.keras.utils.pack_x_y_sample_weight(x, y) + >>> isinstance(data, tuple) + True + >>> x, y = data + + Args: + x: Features to pass to `Model`. + y: Ground-truth targets to pass to `Model`. + sample_weight: Sample weight for each element. + + Returns: + Tuple in the format used in `Model.fit`. + """ + if y is None: + # For single x-input, we do no tuple wrapping since in this case + # there is no ambiguity. This also makes NumPy and Dataset + # consistent in that the user does not have to wrap their Dataset + # data in an unecessary tuple + if not nest.is_nested(x): + return x + else: + return (x,) + elif sample_weight is None: + return (x, y) + else: + return (x, y, sample_weight) + + +def single_batch_iterator(strategy, + x, + y=None, + sample_weight=None, + class_weight=None): + """Creates a single-batch dataset.""" + x, y, sample_weight = _process_tensorlike((x, y, sample_weight)) + if y is None: + data = (x,) + elif sample_weight is None: + data = (x, y) + else: + data = (x, y, sample_weight) + + _check_data_cardinality(data) + dataset = dataset_ops.DatasetV2.from_tensors(data) + if class_weight: + dataset = dataset.map(_make_class_weight_map_fn(class_weight)) + dataset = strategy.experimental_distribute_dataset(dataset) + return iter(dataset) + + +def _check_data_cardinality(data): + num_samples = set(int(i.shape[0]) for i in nest.flatten(data)) + if len(num_samples) > 1: + msg = "Data cardinality is ambiguous:\n" + for label, single_data in zip(["x", "y", "sample_weight"], data): + msg += " {} sizes: {}\n".format( + label, ", ".join(str(i.shape[0]) for i in nest.flatten(single_data))) + msg += "Make sure all arrays contain the same number of samples." + raise ValueError(msg) + + +def _get_tensor_types(): + try: + import pandas as pd # pylint: disable=g-import-not-at-top + + return (tensor.Tensor, np.ndarray, pd.Series, pd.DataFrame) + except ImportError: + return (tensor.Tensor, np.ndarray) + + +def _is_scipy_sparse(x): + try: + from scipy.sparse import issparse # pylint: disable=g-import-not-at-top + + return issparse(x) + except ImportError: + return False + + +def _scipy_sparse_to_sparse_tensor(t): + """Converts a SciPy sparse matrix to a SparseTensor.""" + sparse_coo = t.tocoo() + row, col = sparse_coo.row, sparse_coo.col + data, shape = sparse_coo.data, sparse_coo.shape + if issubclass(data.dtype.type, np.floating): + data = data.astype(backend.floatx()) + indices = np.concatenate( + (np.expand_dims(row, axis=1), np.expand_dims(col, axis=1)), axis=1) + return sparse_tensor.SparseTensor(indices, data, shape) + + +def _is_distributed_dataset(ds): + return isinstance(ds, input_lib.DistributedDatasetInterface) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/functional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..920f934eb43dfd99b1ee289e3b8a39c7f59c8ee8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/functional.py @@ -0,0 +1,1447 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""A `Network` is way to compose layers: the topological form of a `Model`.""" + +import collections +import copy +import itertools +import warnings + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import input_layer as input_layer_module +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.engine import node as node_module +from tensorflow.python.keras.engine import training as training_lib +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.saving.saved_model import network_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + + +# pylint: disable=g-classes-have-attributes +class Functional(training_lib.Model): + """A `Functional` model is a `Model` defined as a directed graph of layers. + + Three types of `Model` exist: subclassed `Model`, `Functional` model, + and `Sequential` (a special case of `Functional`). + In general, more Keras features are supported with `Functional` + than with subclassed `Model`s, specifically: + + - Model cloning (`keras.models.clone`) + - Serialization (`model.get_config()/from_config`, `model.to_json()` + - Whole-model saving (`model.save()`) + + A `Functional` model can be instantiated by passing two arguments to + `__init__`. The first argument is the `keras.Input` Tensors that represent + the inputs to the model. The second argument specifies the output + tensors that represent the outputs of this model. Both arguments can be a + nested structure of tensors. + + Example: + + ``` + inputs = {'x1': keras.Input(shape=(10,)), 'x2': keras.Input(shape=(1,))} + t = keras.layers.Dense(1, activation='relu')(inputs['x1']) + outputs = keras.layers.Add()([t, inputs['x2']) + model = keras.Model(inputs, outputs) + ``` + + A `Functional` model constructed using the Functional API can also include raw + TensorFlow functions, with the exception of functions that create Variables + or assign ops. + + Example: + + ``` + inputs = keras.Input(shape=(10,)) + x = keras.layers.Dense(1)(inputs) + outputs = tf.nn.relu(x) + model = keras.Model(inputs, outputs) + ``` + + Args: + inputs: List of input tensors (must be created via `tf.keras.Input()`). + outputs: List of output tensors. + name: String, optional. Name of the model. + trainable: Boolean, optional. If the model's variables should be trainable. + """ + + # See tf.Module for the usage of this property. + # The key of _layer_call_argspecs is a layer. tf.Module._flatten will fail to + # flatten the key since it is trying to convert Trackable/Layer to a string. + _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain( + ('_layer_call_argspecs', '_compiled_trainable_state', + '_output_mask_cache', '_output_tensor_cache', '_output_shape_cache'), + training_lib.Model._TF_MODULE_IGNORED_PROPERTIES + )) + + @trackable.no_automatic_dependency_tracking + def __init__(self, inputs, outputs, name=None, trainable=True, + **kwargs): + # This is used by the Model class, since we have some logic to swap the + # class in the __new__ method, which will lead to __init__ get invoked + # twice. Using the skip_init to skip one of the invocation of __init__ to + # avoid any side effects + skip_init = kwargs.pop('skip_init', False) + if skip_init: + return + generic_utils.validate_kwargs(kwargs, {}) + super(Functional, self).__init__(name=name, trainable=trainable) + self._init_graph_network(inputs, outputs) + + @trackable.no_automatic_dependency_tracking + def _init_graph_network(self, inputs, outputs): + # This method is needed for Sequential to reinitialize graph network when + # layer is added or removed. + self._is_graph_network = True + + # Normalize and set self.inputs, self.outputs. + if isinstance(inputs, list) and len(nest.flatten(inputs)) == 1: + inputs = inputs[0] + if isinstance(outputs, list) and len(nest.flatten(outputs)) == 1: + outputs = outputs[0] + self._nested_inputs = inputs + self._nested_outputs = outputs + self.inputs = nest.flatten(inputs) + self.outputs = nest.flatten(outputs) + + # Models constructed with a single Tensor or list of Tensors can + # be called with a dict, where the keys of the dict are the names + # of the `Input` objects. Extra keys are ignored with warning. + if not nest.is_nested(self._nested_inputs): + self._enable_dict_to_input_mapping = True + elif (isinstance(self._nested_inputs, (list, tuple)) and + not any(nest.is_nested(t) for t in self._nested_inputs)): + self._enable_dict_to_input_mapping = True + elif (isinstance(self._nested_inputs, dict) and + not any(nest.is_nested(t) for t in self._nested_inputs.values())): + self._enable_dict_to_input_mapping = True + else: + self._enable_dict_to_input_mapping = False + + if not ops.executing_eagerly_outside_functions(): + if any(not hasattr(tensor, '_keras_history') for tensor in self.outputs): + base_layer_utils.create_keras_history(self._nested_outputs) + + self._validate_graph_inputs_and_outputs() + + # A Network does not create weights of its own, thus it is already + # built. + self.built = True + self._build_input_shape = nest.map_structure(lambda x: x.shape, inputs) + self._compute_output_and_mask_jointly = True + # `_expects_training_arg` is True since the `training` argument is always + # present in the signature of the `call` method of a graph network. + self._expects_training_arg = True + self._expects_mask_arg = True + # A graph network does not autocast inputs, as its layers will cast them + # instead. + self._autocast = False + + self._input_layers = [] + self._output_layers = [] + self._input_coordinates = [] + self._output_coordinates = [] + + # This is for performance optimization when calling the Network on new + # inputs. Every time the Network is called on a set on input tensors, + # we compute the output tensors, output masks and output shapes in one pass, + # then cache them here. When any of these outputs is queried later, we + # retrieve it from there instead of recomputing it. + self._output_mask_cache = {} + self._output_tensor_cache = {} + self._output_shape_cache = {} + + # Build self._output_layers: + for x in self.outputs: + layer, node_index, tensor_index = x._keras_history # pylint: disable=protected-access + self._output_layers.append(layer) + self._output_coordinates.append((layer, node_index, tensor_index)) + + # Build self._input_layers: + for x in self.inputs: + layer, node_index, tensor_index = x._keras_history # pylint: disable=protected-access + # It's supposed to be an input layer, so only one node + # and one tensor output. + assert node_index == 0 + assert tensor_index == 0 + self._input_layers.append(layer) + self._input_coordinates.append((layer, node_index, tensor_index)) + + # Keep track of the network's nodes and layers. + nodes, nodes_by_depth, layers, _ = _map_graph_network( + self.inputs, self.outputs) + self._network_nodes = nodes + self._nodes_by_depth = nodes_by_depth + self._self_tracked_trackables = layers + self._layer_call_argspecs = {} + for layer in self._self_tracked_trackables: + self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call) + + # Build self.input_names and self.output_names. + self._set_output_names() + self.input_names = [] + self._feed_input_names = [] + self._feed_inputs = [] + self._feed_input_shapes = [] + for layer in self._input_layers: + self.input_names.append(layer.name) + if layer.is_placeholder: + self._feed_input_names.append(layer.name) + # Use batch_input_shape here because non-eager composite tensors may not + # have a shape attribute that's meaningful (sparse, for instance, has + # a tensor that's non-constant and needs to be fed). This means that + # input layers that create placeholders will need to have the + # batch_input_shape attr to allow for input shape validation. + self._feed_input_shapes.append(layer._batch_input_shape) + self._feed_inputs.append(layer.input) + + self._compute_tensor_usage_count() + self._set_save_spec(self._nested_inputs) + tf_utils.assert_no_legacy_layers(self.layers) + + @property + def input(self): + """Retrieves the input tensor(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer. + + Returns: + Input tensor or list of input tensors. + + Raises: + RuntimeError: If called in Eager mode. + AttributeError: If no inbound nodes are found. + """ + return self._nested_inputs + + @property + def input_shape(self): + """Retrieves the input shape(s) of a layer. + + Only applicable if the layer has exactly one input, + i.e. if it is connected to one incoming layer, or if all inputs + have the same shape. + + Returns: + Input shape, as an integer shape tuple + (or list of shape tuples, one tuple per input tensor). + + Raises: + AttributeError: if the layer has no defined input_shape. + RuntimeError: if called in Eager mode. + """ + return nest.map_structure(backend.int_shape, self.input) + + @property + def input_spec(self): + if hasattr(self, '_manual_input_spec'): + return self._manual_input_spec + if (isinstance(self._nested_inputs, (dict, list, tuple)) and + len(self._nested_inputs) != len(self.inputs)): + # Case where we have a nested structure. + # In such a case we can't safely run any checks. + return None + if isinstance(self._nested_inputs, dict): + # Case where `_nested_inputs` is a plain dict of Inputs. + names = sorted(self._nested_inputs.keys()) + return [input_spec.InputSpec( + shape=shape_with_no_batch_size(self._nested_inputs[name]), + allow_last_axis_squeeze=True, name=name) for name in names] + else: + # Single input, or list / tuple of inputs. + # The data may be passed as a dict keyed by input name. + return [input_spec.InputSpec( + shape=shape_with_no_batch_size(x), allow_last_axis_squeeze=True, + name=x._keras_history.layer.name) for x in self.inputs] + + @input_spec.setter + def input_spec(self, value): + self._manual_input_spec = value + + @property + def output(self): + """Retrieves the output tensor(s) of a layer. + + Only applicable if the layer has exactly one output, + i.e. if it is connected to one incoming layer. + + Returns: + Output tensor or list of output tensors. + + Raises: + AttributeError: if the layer is connected to more than one incoming + layers. + RuntimeError: if called in Eager mode. + """ + return self._nested_outputs + + @property + def output_shape(self): + """Retrieves the output shape(s) of a layer. + + Only applicable if the layer has one output, + or if all outputs have the same shape. + + Returns: + Output shape, as an integer shape tuple + (or list of shape tuples, one tuple per output tensor). + + Raises: + AttributeError: if the layer has no defined output shape. + RuntimeError: if called in Eager mode. + """ + return nest.map_structure(backend.int_shape, self.output) + + def _set_output_names(self): + """Assigns unique names to the Network's outputs. + + Output layers with multiple output tensors would otherwise lead to duplicate + names in self.output_names. + """ + uniquified = [] + output_names = set() + prefix_count = {} + for layer in self._output_layers: + proposal = layer.name + while proposal in output_names: + existing_count = prefix_count.get(layer.name, 1) + proposal = '{}_{}'.format(layer.name, existing_count) + prefix_count[layer.name] = existing_count + 1 + output_names.add(proposal) + uniquified.append(proposal) + self.output_names = uniquified + + @property + def _layer_checkpoint_dependencies(self): + """Dictionary of layer dependencies to be included in the checkpoint.""" + weight_layer_index = 0 + + dependencies = collections.OrderedDict() + for layer_index, layer in enumerate(self.layers): + try: + if layer.weights: + # Keep a separate index for layers which have weights. This allows + # users to insert Layers without weights anywhere in the network + # without breaking checkpoints. + dependencies['layer_with_weights-%d' % weight_layer_index] = layer + weight_layer_index += 1 + except ValueError: + # The layer might have weights, but may not be built yet. We just treat + # it as layer without weight. + pass + + # Even if it doesn't have weights, we should still track everything in + # case it has/will have Trackable dependencies. + dependencies['layer-%d' % layer_index] = layer + return dependencies + + def _trackable_children(self, + save_type=trackable.SaveType.CHECKPOINT, + **kwargs): + dependencies = self._layer_checkpoint_dependencies + dependencies.update( + super(Functional, self)._trackable_children(save_type, **kwargs)) + return dependencies + + def _lookup_dependency(self, name): + layer_dependencies = self._layer_checkpoint_dependencies + if name in layer_dependencies: + return layer_dependencies[name] + return super(Functional, self)._lookup_dependency(name) + + def _handle_deferred_layer_dependencies(self, layers): + """Handles layer checkpoint dependencies that are added after init.""" + layer_checkpoint_dependencies = self._layer_checkpoint_dependencies + layer_to_name = {v: k for k, v in layer_checkpoint_dependencies.items()} + for layer in layers: + if layer in layer_to_name: + self._handle_deferred_dependencies(name=layer_to_name[layer], + trackable=layer) + + @property + def _should_compute_mask(self): + return True + + def compute_mask(self, inputs, mask): + # TODO(omalleyt): b/123540974 This function is not really safe to call + # by itself because it will duplicate any updates and losses in graph + # mode by `call`ing the Layers again. + output_tensors = self._run_internal_graph(inputs, mask=mask) + return nest.map_structure(lambda t: getattr(t, '_keras_mask', None), + output_tensors) + + @doc_controls.do_not_doc_inheritable + def call(self, inputs, training=None, mask=None): + """Calls the model on new inputs. + + In this case `call` just reapplies + all ops in the graph to the new inputs + (e.g. build a new computational graph from the provided inputs). + + Args: + inputs: A tensor or list of tensors. + training: Boolean or boolean scalar tensor, indicating whether to run + the `Network` in training mode or inference mode. + mask: A mask or list of masks. A mask can be + either a tensor or None (no mask). + + Returns: + A tensor if there is a single output, or + a list of tensors if there are more than one outputs. + """ + return self._run_internal_graph( + inputs, training=training, mask=mask) + + def compute_output_shape(self, input_shape): + # Convert any shapes in tuple format to TensorShapes. + input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) + + if len(nest.flatten(input_shape)) != len(nest.flatten(self._input_layers)): + raise ValueError('Invalid input_shape argument ' + str(input_shape) + + ': model has ' + str(len(self._input_layers)) + + ' tensor inputs.') + + # Use the tuple of TensorShape as the cache key, since tuple is hashable + # and can be used as hash key. + try: + cache_key = tuple(tf_utils.convert_shapes(input_shape, to_tuples=True)) + if cache_key in self._output_shape_cache: + # Cache hit. Return shapes as TensorShapes. + return self._output_shape_cache[cache_key] + except ValueError: + # In case there are unknown TensorShape, eg for sparse tensor input, + # We skip the caching since the shape is unknown. + pass + + layers_to_output_shapes = {} + for layer, shape in zip(self._input_layers, nest.flatten(input_shape)): + # It's an input layer: then `compute_output_shape` is identity, + # and there is only one node and one tensor.. + shape_key = layer.name + '_0_0' + layers_to_output_shapes[shape_key] = shape + + depth_keys = list(self._nodes_by_depth.keys()) + depth_keys.sort(reverse=True) + # Iterate over nodes, by depth level. + if len(depth_keys) > 1: + for depth in depth_keys: + nodes = self._nodes_by_depth[depth] + for node in nodes: + layer = node.layer + if layer in self._input_layers: + # We've already covered the input layers + # a few lines above. + continue + # Get the input shapes for the first argument of the node + layer_input_shapes = [] + layer_inputs = node.call_args[0] + for layer_input in nest.flatten(layer_inputs): + kh = layer_input._keras_history + input_layer_key = kh.layer.name + '_%s_%s' % (kh.node_index, + kh.tensor_index) + layer_input_shapes.append(layers_to_output_shapes[input_layer_key]) + layer_input_shapes = nest.pack_sequence_as(layer_inputs, + layer_input_shapes) + # Layers expect shapes to be tuples for `compute_output_shape`. + layer_input_shapes = tf_utils.convert_shapes( + layer_input_shapes, to_tuples=True) + layer_output_shapes = layer.compute_output_shape(layer_input_shapes) + # Convert back to TensorShapes. + layer_output_shapes = tf_utils.convert_shapes( + layer_output_shapes, to_tuples=False) + + node_index = layer._inbound_nodes.index(node) # pylint: disable=protected-access + for j, shape in enumerate(nest.flatten(layer_output_shapes)): + shape_key = layer.name + '_%s_%s' % (node_index, j) + layers_to_output_shapes[shape_key] = shape + + # Read final output shapes from layers_to_output_shapes. + output_shapes = [] + for i in range(len(self._output_layers)): + layer, node_index, tensor_index = self._output_coordinates[i] + shape_key = layer.name + '_%s_%s' % (node_index, tensor_index) + output_shapes.append(layers_to_output_shapes[shape_key]) + output_shapes = nest.pack_sequence_as(self._nested_outputs, output_shapes) + # Store in cache. + self._output_shape_cache[cache_key] = output_shapes + + # Return shapes as TensorShapes. + return output_shapes + + def _init_set_name(self, name, zero_based=True): + if not name: + cls_name = self.__class__.__name__ + if self.__class__ == Functional: + # Hide the functional class name from user, since its not a public + # visible class. Use "Model" instead, + cls_name = 'Model' + self._name = backend.unique_object_name( + generic_utils.to_snake_case(cls_name), + zero_based=zero_based) + else: + self._name = name + + def _run_internal_graph(self, inputs, training=None, mask=None): + """Computes output tensors for new inputs. + + # Note: + - Can be run on non-Keras tensors. + + Args: + inputs: Tensor or nested structure of Tensors. + training: Boolean learning phase. + mask: (Optional) Tensor or nested structure of Tensors. + + Returns: + output_tensors + """ + inputs = self._flatten_to_reference_inputs(inputs) + if mask is None: + masks = [None] * len(inputs) + else: + masks = self._flatten_to_reference_inputs(mask) + for input_t, mask in zip(inputs, masks): + input_t._keras_mask = mask + + # Dictionary mapping reference tensors to computed tensors. + tensor_dict = {} + tensor_usage_count = self._tensor_usage_count + for x, y in zip(self.inputs, inputs): + y = self._conform_to_reference_input(y, ref_input=x) + x_id = str(id(x)) + tensor_dict[x_id] = [y] * tensor_usage_count[x_id] + + nodes_by_depth = self._nodes_by_depth + depth_keys = list(nodes_by_depth.keys()) + depth_keys.sort(reverse=True) + + for depth in depth_keys: + nodes = nodes_by_depth[depth] + for node in nodes: + if node.is_input: + continue # Input tensors already exist. + + if any(t_id not in tensor_dict for t_id in node.flat_input_ids): + continue # Node is not computable, try skipping. + + args, kwargs = node.map_arguments(tensor_dict) + outputs = node.layer(*args, **kwargs) + + # Update tensor_dict. + for x_id, y in zip(node.flat_output_ids, nest.flatten(outputs)): + tensor_dict[x_id] = [y] * tensor_usage_count[x_id] + + output_tensors = [] + for x in self.outputs: + x_id = str(id(x)) + assert x_id in tensor_dict, 'Could not compute output ' + str(x) + output_tensors.append(tensor_dict[x_id].pop()) + + return nest.pack_sequence_as(self._nested_outputs, output_tensors) + + def _flatten_to_reference_inputs(self, tensors): + """Maps `tensors` to their respective `keras.Input`.""" + if self._enable_dict_to_input_mapping and isinstance(tensors, dict): + ref_inputs = self._nested_inputs + if not nest.is_nested(ref_inputs): + ref_inputs = [self._nested_inputs] + if isinstance(ref_inputs, dict): + # In the case that the graph is constructed with dict input tensors, + # We will use the original dict key to map with the keys in the input + # data. Note that the model.inputs is using nest.flatten to process the + # input tensors, which means the dict input tensors are ordered by their + # keys. + ref_input_names = sorted(ref_inputs.keys()) + else: + ref_input_names = [inp._keras_history.layer.name for inp in ref_inputs] + + # Raise an warning if there are more input data comparing to input tensor + if len(tensors) > len(ref_input_names): + warnings.warn( + 'Input dict contained keys {} which did not match any model input. ' + 'They will be ignored by the model.'.format( + [n for n in tensors.keys() if n not in ref_input_names]) + ) + + try: + # Flatten in the order `Input`s were passed during Model construction. + return [tensors[n] for n in ref_input_names] + except KeyError: + # TODO(b/151582614) + return nest.flatten(tensors) + + # Otherwise both self.inputs and tensors will already be in same order. + return nest.flatten(tensors) + + def _conform_to_reference_input(self, tensor, ref_input): + """Set shape and dtype based on `keras.Input`s.""" + if isinstance(tensor, tensor_lib.Tensor): + # Allow (None,) and (None, 1) Tensors to be passed interchangeably. Use + # the shape specified by the `keras.Input`. + t_shape = tensor.shape + t_rank = t_shape.rank + ref_shape = ref_input.shape + ref_rank = ref_shape.rank + keras_history = getattr(tensor, '_keras_history', None) + if t_rank is not None and ref_rank is not None: + # Should squeeze last dimension. + # True if tensor is (BATCH, ..., 1) and reference is (BATCH, ...). + if (t_rank == ref_rank + 1 and t_shape[-1] == 1): + tensor = array_ops.squeeze_v2(tensor, axis=-1) + # Should expand last_dimension. + # True if tensor is (BATCH, ...) and reference is (BATCH, ..., 1). + elif (t_rank == ref_rank - 1 and ref_shape[-1] == 1): + tensor = array_ops.expand_dims_v2(tensor, axis=-1) + if keras_history is not None: # Restore keras history. + tensor._keras_history = keras_history + + # Add shape hints to Tensors that may have None shape dims but have shapes + # defined by the `keras.Input` (not applicable in eager mode). + if not context.executing_eagerly(): + try: + tensor.set_shape(tensor.shape.merge_with(ref_input.shape)) + except ValueError: + logging.warning( + 'Model was constructed with shape {} for input {}, but it was ' + 'called on an input with incompatible shape {}.'.format( + ref_input.shape, ref_input, tensor.shape)) + + # Dtype casting. + tensor = math_ops.cast(tensor, dtype=ref_input.dtype) + elif tf_utils.is_extension_type(tensor): + # Dtype casting (If the extension type has a non-variant dtype and + # supports being cast) + ref_input_dtype = getattr(ref_input, 'dtype', None) + if ref_input_dtype is not None and ref_input_dtype != dtypes.variant: + tensor = math_ops.cast(tensor, dtype=ref_input_dtype) + + return tensor + + def get_config(self): + return copy.deepcopy(get_network_config(self)) + + @classmethod + def from_config(cls, config, custom_objects=None): + """Instantiates a Model from its config (output of `get_config()`). + + Args: + config: Model config dictionary. + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + + Returns: + A model instance. + + Raises: + ValueError: In case of improperly formatted config dict. + """ + with generic_utils.SharedObjectLoadingScope(): + input_tensors, output_tensors, created_layers = reconstruct_from_config( + config, custom_objects) + model = cls(inputs=input_tensors, outputs=output_tensors, + name=config.get('name')) + connect_ancillary_layers(model, created_layers) + return model + + def _validate_graph_inputs_and_outputs(self): + """Validates the inputs and outputs of a Graph Network.""" + # Check for redundancy in inputs. + if len({id(i) for i in self.inputs}) != len(self.inputs): + raise ValueError('The list of inputs passed to the model ' + 'is redundant. ' + 'All inputs should only appear once.' + ' Found: ' + str(self.inputs)) + + for x in self.inputs: + # Check that x has appropriate `_keras_history` metadata. + if not hasattr(x, '_keras_history'): + cls_name = self.__class__.__name__ + raise ValueError('Input tensors to a ' + cls_name + ' ' + + 'must come from `tf.keras.Input`. ' + 'Received: ' + str(x) + + ' (missing previous layer metadata).') + # Check that x is an input tensor. + # pylint: disable=protected-access + layer = x._keras_history.layer + if len(layer._inbound_nodes) > 1 or ( + layer._inbound_nodes and not layer._inbound_nodes[0].is_input): + cls_name = self.__class__.__name__ + logging.warning(cls_name + ' model inputs must come from ' + '`tf.keras.Input` (thus holding past layer metadata), ' + 'they cannot be the output of ' + 'a previous non-Input layer. ' + 'Here, a tensor specified as ' + 'input to "' + self.name + '" was not an Input tensor, ' + 'it was generated by layer ' + layer.name + '.\n' + 'Note that input tensors are ' + 'instantiated via `tensor = tf.keras.Input(shape)`.\n' + 'The tensor that caused the issue was: ' + str(x.name)) + + # Check compatibility of batch sizes of Input Layers. + input_batch_sizes = [ + training_utils.get_static_batch_size(x._keras_history.layer) + for x in self.inputs + ] + consistent_batch_size = None + for batch_size in input_batch_sizes: + if batch_size is not None: + if (consistent_batch_size is not None and + batch_size != consistent_batch_size): + raise ValueError('The specified batch sizes of the Input Layers' + ' are incompatible. Found batch sizes: {}'.format( + input_batch_sizes)) + consistent_batch_size = batch_size + + for x in self.outputs: + if not hasattr(x, '_keras_history'): + cls_name = self.__class__.__name__ + raise ValueError('Output tensors of a ' + cls_name + ' model must be ' + 'the output of a TensorFlow `Layer` ' + '(thus holding past layer metadata). Found: ' + str(x)) + + def _insert_layers(self, layers, relevant_nodes=None): + """Inserts Layers into the Network after Network creation. + + This is only valid for Keras Graph Networks. Layers added via this function + will be included in the `call` computation and `get_config` of this Network. + They will not be added to the Network's outputs. + + + Args: + layers: Arbitrary nested structure of Layers. Layers must be reachable + from one or more of the `keras.Input` Tensors that correspond to this + Network's inputs. + relevant_nodes: Nodes from the Layers that should be considered part of + this Network. If `None`, all Nodes will be considered part of this + Network. + + Raises: + ValueError: If the layers depend on `Input`s not found in this Model. + """ + layers = nest.flatten(layers) + tf_utils.assert_no_legacy_layers(layers) + node_to_depth = {} + for depth, nodes in self._nodes_by_depth.items(): + node_to_depth.update({node: depth for node in nodes}) + # The nodes of these Layers that are relevant to this Network. If not + # provided, assume all Nodes are relevant + if not relevant_nodes: + relevant_nodes = nest.flatten([layer._inbound_nodes for layer in layers]) + network_nodes = set(relevant_nodes + list(node_to_depth.keys())) + + def _get_min_depth(node): + """Gets the minimum depth at which node can be computed.""" + min_depth = 0 + for layer, node_id, _, _ in node.iterate_inbound(): + inbound_node = layer._inbound_nodes[node_id] + if inbound_node in node_to_depth: + min_depth = min(min_depth, node_to_depth[inbound_node]) + elif inbound_node not in network_nodes: + continue + else: + # Previous relevant nodes haven't been processed yet. + return None + # New node is one shallower than its shallowest input. + return min_depth - 1 + + # Insert nodes into `_nodes_by_depth` and other node attrs. + unprocessed_nodes = copy.copy(relevant_nodes) + i = 0 + while unprocessed_nodes: + i += 1 + # Do a sanity check. This can occur if `Input`s from outside this Model + # are being relied on. + if i > 10000: + raise ValueError('Layers could not be added due to missing ' + 'dependencies.') + + node = unprocessed_nodes.pop(0) + depth = _get_min_depth(node) + if depth is None: # Defer until inbound nodes are processed. + unprocessed_nodes.append(node) + continue + node_key = _make_node_key(node.layer.name, + node.layer._inbound_nodes.index(node)) + if node_key not in self._network_nodes: + node_to_depth[node] = depth + self._network_nodes.add(node_key) + self._nodes_by_depth[depth].append(node) + + # Insert layers and update other layer attrs. + layer_set = set(self._self_tracked_trackables) + deferred_layers = [] + for layer in layers: + if layer not in layer_set: + self._self_tracked_trackables.append(layer) + deferred_layers.append(layer) + self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call) + layer_set.add(layer) + self._handle_deferred_layer_dependencies(deferred_layers) + + self._compute_tensor_usage_count() + + def _compute_tensor_usage_count(self): + """Compute the #. of tensor usages for all the output tensors of layers. + + The computed tensor usage count is saved as `self._tensor_usage_count`. This + is later used for saving memory in eager computation by releasing + no-longer-needed tensors as early as possible. + """ + tensor_usage_count = collections.Counter() + available_tensors = set(str(id(tensor)) for tensor in self.inputs) + + depth_keys = list(self._nodes_by_depth.keys()) + depth_keys.sort(reverse=True) + depth_keys = depth_keys[1:] + + for depth in depth_keys: + for node in self._nodes_by_depth[depth]: + input_tensors = { + str(id(tensor)) for tensor in nest.flatten(node.keras_inputs) + } + if input_tensors.issubset(available_tensors): + for tensor in nest.flatten(node.keras_inputs): + tensor_usage_count[str(id(tensor))] += 1 + + for output_tensor in nest.flatten(node.outputs): + available_tensors.add(str(id(output_tensor))) + + for tensor in self.outputs: + tensor_usage_count[str(id(tensor))] += 1 + + self._tensor_usage_count = tensor_usage_count + + def _assert_weights_created(self): + # Override the implementation in Model. + # The Functional model should always have weight created already. + return + + def _graph_network_add_loss(self, symbolic_loss): + new_nodes, new_layers = _map_subgraph_network(self.inputs, [symbolic_loss]) + # Losses must be keyed on inputs no matter what in order to be supported in + # DistributionStrategy. + add_loss_layer = base_layer.AddLoss( + unconditional=False, dtype=symbolic_loss.dtype) + add_loss_layer(symbolic_loss) + new_nodes.extend(add_loss_layer.inbound_nodes) + new_layers.append(add_loss_layer) + self._insert_layers(new_layers, new_nodes) + + def _graph_network_add_metric(self, value, aggregation, name): + new_nodes, new_layers = _map_subgraph_network(self.inputs, [value]) + add_metric_layer = base_layer.AddMetric( + aggregation, name, dtype=value.dtype) + add_metric_layer(value) + new_nodes.extend(add_metric_layer.inbound_nodes) + new_layers.append(add_metric_layer) + self._insert_layers(new_layers, new_nodes) + + @property + def _trackable_saved_model_saver(self): + return network_serialization.NetworkSavedModelSaver(self) + + def _get_save_spec(self, dynamic_batch=True): + if getattr(self, '_has_explicit_input_shape', True): + # Functional models and Sequential models that have an explicit input + # shape should use the batch size set by the input layer. + dynamic_batch = False + return super(Functional, self)._get_save_spec(dynamic_batch) + + +def _make_node_key(layer_name, node_index): + return layer_name + '_ib-' + str(node_index) + + +def _map_graph_network(inputs, outputs): + """Validates a network's topology and gather its layers and nodes. + + Args: + inputs: List of input tensors. + outputs: List of outputs tensors. + + Returns: + A tuple `(nodes, nodes_by_depth, layers, layers_by_depth)`. + - nodes: list of Node instances. + - nodes_by_depth: dict mapping ints (depth) to lists of node instances. + - layers: list of Layer instances. + - layers_by_depth: dict mapping ints (depth) to lists of layer instances. + + Raises: + ValueError: In case the network is not valid (e.g. disconnected graph). + """ + # "depth" is number of layers between output Node and the Node. + # Nodes are ordered from inputs -> outputs. + nodes_in_decreasing_depth, layer_indices = _build_map(outputs) + network_nodes = { + _make_node_key(node.layer.name, node.layer._inbound_nodes.index(node)) + for node in nodes_in_decreasing_depth + } + + nodes_depths = {} # dict {node: depth value} + layers_depths = {} # dict {layer: depth value} + + for node in reversed(nodes_in_decreasing_depth): + # If the depth is not set, the node has no outbound nodes (depth 0). + depth = nodes_depths.setdefault(node, 0) + + # Update the depth of the corresponding layer + previous_depth = layers_depths.get(node.layer, 0) + # If we've seen this layer before at a higher depth, + # we should use that depth instead of the node depth. + # This is necessary for shared layers that have inputs at different + # depth levels in the graph. + depth = max(depth, previous_depth) + layers_depths[node.layer] = depth + nodes_depths[node] = depth + + # Update the depth of inbound nodes. + # The "depth" of a node is the max of the depths + # of all nodes it is connected to + 1. + for node_dep in node.parent_nodes: + previous_depth = nodes_depths.get(node_dep, 0) + nodes_depths[node_dep] = max(depth + 1, previous_depth) + + # Handle inputs that are not connected to outputs. + # We do not error out here because the inputs may be used to compute losses + # and metrics. + for input_t in inputs: + input_layer = input_t._keras_history[0] + if input_layer not in layers_depths: + layers_depths[input_layer] = 0 + layer_indices[input_layer] = -1 + nodes_depths[input_layer._inbound_nodes[0]] = 0 + network_nodes.add(_make_node_key(input_layer.name, 0)) + + # Build a dict {depth: list of nodes with this depth} + nodes_by_depth = collections.defaultdict(list) + for node, depth in nodes_depths.items(): + nodes_by_depth[depth].append(node) + + # Build a dict {depth: list of layers with this depth} + layers_by_depth = collections.defaultdict(list) + for layer, depth in layers_depths.items(): + layers_by_depth[depth].append(layer) + + # Get sorted list of layer depths. + depth_keys = list(layers_by_depth.keys()) + depth_keys.sort(reverse=True) + + # Set self.layers ordered by depth. + layers = [] + for depth in depth_keys: + layers_for_depth = layers_by_depth[depth] + # Network.layers needs to have a deterministic order: + # here we order them by traversal order. + layers_for_depth.sort(key=lambda x: layer_indices[x]) + layers.extend(layers_for_depth) + + # Get sorted list of node depths. + depth_keys = list(nodes_by_depth.keys()) + depth_keys.sort(reverse=True) + + # Check that all tensors required are computable. + # computable_tensors: all tensors in the graph + # that can be computed from the inputs provided. + computable_tensors = set() + for x in inputs: + computable_tensors.add(id(x)) + + layers_with_complete_input = [] # To provide a better error msg. + for depth in depth_keys: + for node in nodes_by_depth[depth]: + layer = node.layer + if layer and not node.is_input: + for x in nest.flatten(node.keras_inputs): + if id(x) not in computable_tensors: + raise ValueError('Graph disconnected: ' + 'cannot obtain value for tensor ' + str(x) + + ' at layer "' + layer.name + '". ' + 'The following previous layers ' + 'were accessed without issue: ' + + str(layers_with_complete_input)) + for x in nest.flatten(node.outputs): + computable_tensors.add(id(x)) + layers_with_complete_input.append(layer.name) + + # Ensure name unicity, which will be crucial for serialization + # (since serialized nodes refer to layers by their name). + all_names = [layer.name for layer in layers] + for name in all_names: + if all_names.count(name) != 1: + raise ValueError('The name "' + name + '" is used ' + + str(all_names.count(name)) + ' times in the model. ' + 'All layer names should be unique.') + return network_nodes, nodes_by_depth, layers, layers_by_depth + + +def _build_map(outputs): + """This method topologically sorts nodes in order from inputs to outputs. + + It uses a depth-first search to topologically sort nodes that appear in the + _keras_history connectivity metadata of `outputs`. + + Args: + outputs: the output tensors whose _keras_history metadata should be walked. + This may be an arbitrary nested structure. + + Returns: + A tuple like (ordered_nodes, layer_to_first_traversal_index) + ordered_nodes: list of nodes appearing in the keras history, topologically + sorted from original inputs to the `outputs`. + (If outputs have different sets of ancestors, the inputs to one output + may appear after a different output). + layer_to_first_traversal_index: + A dict mapping layer to the traversal index in the DFS where it is + seen. Note: if a layer is shared by several nodes, the dict will only + store the index corresponding to the *first* time the layer seen. + """ + finished_nodes = set() + nodes_in_progress = set() + nodes_in_decreasing_depth = [] # nodes from inputs -> outputs. + layer_indices = {} # layer -> in traversal order. + for output in nest.flatten(outputs): + _build_map_helper(output, finished_nodes, nodes_in_progress, + nodes_in_decreasing_depth, layer_indices) + return nodes_in_decreasing_depth, layer_indices + + +def _build_map_helper(tensor, finished_nodes, nodes_in_progress, + nodes_in_decreasing_depth, layer_indices): + """Recursive helper for `_build_map`.""" + layer, node_index, _ = tensor._keras_history # pylint: disable=protected-access + node = layer._inbound_nodes[node_index] # pylint: disable=protected-access + + # Don't repeat work for shared subgraphs + if node in finished_nodes: + return + + # Prevent cycles. + if node in nodes_in_progress: + raise ValueError('The tensor ' + str(tensor) + ' at layer "' + layer.name + + '" is part of a cycle.') + + # Store the traversal order for layer sorting. + if layer not in layer_indices: + layer_indices[layer] = len(layer_indices) + + # Propagate to all previous tensors connected to this node. + nodes_in_progress.add(node) + if not node.is_input: + for tensor in node.keras_inputs: + _build_map_helper(tensor, finished_nodes, nodes_in_progress, + nodes_in_decreasing_depth, layer_indices) + + finished_nodes.add(node) + nodes_in_progress.remove(node) + nodes_in_decreasing_depth.append(node) + + +def _map_subgraph_network(inputs, outputs): + """Returns the nodes and layers in the topology from `inputs` to `outputs`. + + Args: + inputs: List of input tensors. + outputs: List of output tensors. + + Returns: + A tuple of List{Node] and List[Layer]. + """ + if not ops.executing_eagerly_outside_functions(): + base_layer_utils.create_keras_history(outputs) + # Keep only nodes and layers in the topology between inputs and outputs. + _, nodes_by_depth, layers, _ = _map_graph_network(inputs, outputs) + return nest.flatten([nodes for nodes in nodes_by_depth.values()]), layers + + +def _should_skip_first_node(layer): + """Returns True if the first layer node should not be saved or loaded.""" + # Networks that are constructed with an Input layer/shape start with a + # pre-existing node linking their input to output. This node is excluded from + # the network config. + if layer._self_tracked_trackables: + return (isinstance(layer, Functional) and + # Filter out Sequential models without an input shape. + isinstance(layer._self_tracked_trackables[0], + input_layer_module.InputLayer)) + else: + return isinstance(layer, Functional) + + +def connect_ancillary_layers(model, created_layers): + """Adds layers that are not connected to the outputs to the model.""" + # Layers not connected to outputs, such as those added in `add_loss`. + ancillary_layers = [ + layer for layer in created_layers.values() if layer not in model.layers + ] + if ancillary_layers: + relevant_nodes = nest.flatten([ + layer.inbound_nodes[1:] + if _should_skip_first_node(layer) else layer.inbound_nodes + for layer in created_layers.values() + ]) + model._insert_layers(ancillary_layers, relevant_nodes) + return model + + +def reconstruct_from_config(config, custom_objects=None, created_layers=None): + """Reconstructs graph from config object. + + Args: + config: Dictionary returned from Network.get_config() + custom_objects: Optional dictionary mapping names (strings) to custom + classes or functions to be considered during deserialization. + created_layers: Optional dictionary mapping names to Layer objects. Any + layer not in this dictionary will be created and added to the dict. + This function will add new nodes to all layers (excluding InputLayers), + instead of re-using pre-existing nodes in the layers. + + Returns: + Tuple of (input tensors, output tensors, dictionary of created layers) + """ + # Layer instances created during the graph reconstruction process. + created_layers = created_layers or collections.OrderedDict() + + # Maps input data (tuple of inbound layer name, node index) from the config + # to node indices in the newly generated model. The node indices may be + # different if the layers have already been called previously. + node_index_map = {} + node_count_by_layer = {} + + # Dictionary mapping layer instances to + # node data that specifies a layer call. + # It acts as a queue that maintains any unprocessed + # layer call until it becomes possible to process it + # (i.e. until the input tensors to the call all exist). + unprocessed_nodes = {} + + def add_unprocessed_node(layer, node_data): + if layer not in unprocessed_nodes: + unprocessed_nodes[layer] = [node_data] + else: + unprocessed_nodes[layer].append(node_data) + + def get_node_index(layer, config_node_index): + """Returns node index in layer (might differ from config_node_index).""" + if isinstance(layer, input_layer_module.InputLayer): + return 0 + return node_index_map.get((layer.name, config_node_index), None) + + def _deserialize_keras_tensors(kwargs, layer_map): + """Deserializes Keras Tensors passed to `call`..""" + + def _deserialize_keras_tensor(t): + """Deserializes a single Keras Tensor passed to `call`.""" + if isinstance(t, tf_utils.ListWrapper): + t = t.as_list() + layer_name = t[0] + node_index = t[1] + tensor_index = t[2] + + layer = layer_map[layer_name] + new_node_index = get_node_index(layer, node_index) + if new_node_index is None: + # The inbound node may not have been processed yet, + # (This can happen e.g. if it depends on a different set + # of inputs than those that have been processed already). + # raise an IndexError so that the current node puts itself + # back on the unprocessed queue. + # Caution: This may lead to infinite loops for malformed + # network configurations! (or when there is a bug in + # the network config loading code). + raise IndexError + node = layer._inbound_nodes[new_node_index] + return nest.flatten(node.outputs)[tensor_index] + return t + + kwargs = tf_utils.convert_inner_node_data(kwargs, wrap=True) + return nest.map_structure(_deserialize_keras_tensor, kwargs) + + def process_node(layer, node_data): + """Deserialize a node. + + Args: + layer: layer instance. + node_data: Nested structure of `ListWrapper`. + + Raises: + ValueError: In case of improperly formatted `node_data`. + """ + input_tensors = [] + for input_data in nest.flatten(node_data): + input_data = input_data.as_list() + inbound_layer_name = input_data[0] + inbound_node_index = input_data[1] + inbound_tensor_index = input_data[2] + if len(input_data) == 3: + kwargs = {} + elif len(input_data) == 4: + kwargs = input_data[3] + try: + kwargs = _deserialize_keras_tensors(kwargs, created_layers) + except IndexError: + # Happens if keras tensors in kwargs are still unprocessed + add_unprocessed_node(layer, node_data) + return + else: + raise ValueError('Improperly formatted model config.') + + if inbound_layer_name != node_module._CONSTANT_VALUE: + inbound_layer = created_layers[inbound_layer_name] + inbound_node_index = get_node_index(inbound_layer, inbound_node_index) + + if inbound_node_index is None: + add_unprocessed_node(layer, node_data) + return + inbound_node = inbound_layer._inbound_nodes[inbound_node_index] + input_tensors.append( + nest.flatten(inbound_node.outputs)[inbound_tensor_index]) + else: + # We received a constant w/ no Keras history attached + input_tensors.append(inbound_tensor_index) + input_tensors = nest.pack_sequence_as(node_data, input_tensors) + # Call layer on its inputs, thus creating the node + # and building the layer if needed. + if input_tensors is not None: + if not layer._preserve_input_structure_in_config: + input_tensors = ( + base_layer_utils.unnest_if_single_tensor(input_tensors)) + output_tensors = layer(input_tensors, **kwargs) + + # Update node index map. + output_index = nest.flatten(output_tensors)[0]._keras_history.node_index + node_index_map[(layer.name, node_count_by_layer[layer])] = output_index + node_count_by_layer[layer] += 1 + + def process_layer(layer_data): + """Deserializes a layer, then call it on appropriate inputs. + + Args: + layer_data: layer config dict. + + Raises: + ValueError: In case of improperly formatted `layer_data` dict. + """ + layer_name = layer_data['name'] + + if layer_name in created_layers: + layer = created_layers[layer_name] + else: + # Instantiate layer. + from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top + + layer = deserialize_layer(layer_data, custom_objects=custom_objects) + created_layers[layer_name] = layer + + node_count_by_layer[layer] = int(_should_skip_first_node(layer)) + + # Gather layer inputs and convert to `ListWrapper` objects. + inbound_nodes_data = layer_data['inbound_nodes'] + inbound_nodes_data = tf_utils.convert_inner_node_data( + inbound_nodes_data, wrap=True) + for node_data in inbound_nodes_data: + # We don't process nodes (i.e. make layer calls) + # on the fly because the inbound node may not yet exist, + # in case of layer shared at different topological depths + # (e.g. a model such as A(B(A(B(x))))) + add_unprocessed_node(layer, node_data) + + # First, we create all layers and enqueue nodes to be processed + for layer_data in config['layers']: + process_layer(layer_data) + # Then we process nodes in order of layer depth. + # Nodes that cannot yet be processed (if the inbound node + # does not yet exist) are re-enqueued, and the process + # is repeated until all nodes are processed. + while unprocessed_nodes: + for layer_data in config['layers']: + layer = created_layers[layer_data['name']] + if layer in unprocessed_nodes: + for node_data in unprocessed_nodes.pop(layer): + process_node(layer, node_data) + + input_tensors = [] + output_tensors = [] + + input_layers = tf_utils.convert_inner_node_data( + config['input_layers'], wrap=True) + for layer_data in nest.flatten(input_layers): + layer_name, node_index, tensor_index = layer_data.as_list() + assert layer_name in created_layers + layer = created_layers[layer_name] + node_index = get_node_index(layer, node_index) + layer_output_tensors = layer._inbound_nodes[node_index].output_tensors + input_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) + + output_layers = tf_utils.convert_inner_node_data( + config['output_layers'], wrap=True) + for layer_data in nest.flatten(output_layers): + layer_name, node_index, tensor_index = layer_data.as_list() + assert layer_name in created_layers + layer = created_layers[layer_name] + node_index = get_node_index(layer, node_index) + layer_output_tensors = layer._inbound_nodes[node_index].output_tensors + output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) + + input_tensors = nest.pack_sequence_as(input_layers, input_tensors) + output_tensors = nest.pack_sequence_as(output_layers, output_tensors) + return input_tensors, output_tensors, created_layers + + +def get_network_config(network, serialize_layer_fn=None): + """Builds the config, which consists of the node graph and serialized layers. + + Args: + network: A Network object. + serialize_layer_fn: Function used to serialize layers. + + Returns: + Config dictionary. + """ + serialize_layer_fn = ( + serialize_layer_fn or generic_utils.serialize_keras_object) + config = { + 'name': network.name, + } + node_conversion_map = {} + for layer in network.layers: + kept_nodes = 1 if _should_skip_first_node(layer) else 0 + for original_node_index, node in enumerate(layer._inbound_nodes): + node_key = _make_node_key(layer.name, original_node_index) + if node_key in network._network_nodes: + node_conversion_map[node_key] = kept_nodes + kept_nodes += 1 + layer_configs = [] + + with generic_utils.SharedObjectSavingScope(): + for layer in network.layers: # From the earliest layers on. + filtered_inbound_nodes = [] + for original_node_index, node in enumerate(layer._inbound_nodes): + node_key = _make_node_key(layer.name, original_node_index) + if node_key in network._network_nodes and not node.is_input: + # The node is relevant to the model: + # add to filtered_inbound_nodes. + node_data = node.serialize(_make_node_key, node_conversion_map) + filtered_inbound_nodes.append(node_data) + + layer_config = serialize_layer_fn(layer) + layer_config['name'] = layer.name + layer_config['inbound_nodes'] = filtered_inbound_nodes + layer_configs.append(layer_config) + config['layers'] = layer_configs + + # Gather info about inputs and outputs. + model_inputs = [] + for i in range(len(network._input_layers)): + layer, node_index, tensor_index = network._input_coordinates[i] + node_key = _make_node_key(layer.name, node_index) + if node_key not in network._network_nodes: + continue + new_node_index = node_conversion_map[node_key] + model_inputs.append( + tf_utils.ListWrapper([layer.name, new_node_index, tensor_index])) + model_inputs = nest.pack_sequence_as(network._nested_inputs, model_inputs) + # Preserve external Keras compat for Models with single input. + if not nest.is_nested(model_inputs): + model_inputs = [model_inputs] + model_inputs = tf_utils.convert_inner_node_data(model_inputs) + config['input_layers'] = model_inputs + + model_outputs = [] + for i in range(len(network._output_layers)): + layer, node_index, tensor_index = network._output_coordinates[i] + node_key = _make_node_key(layer.name, node_index) + if node_key not in network._network_nodes: + continue + new_node_index = node_conversion_map[node_key] + model_outputs.append( + tf_utils.ListWrapper([layer.name, new_node_index, tensor_index])) + model_outputs = nest.pack_sequence_as(network._nested_outputs, model_outputs) + # Preserve external Keras compat for Models with single output. + if not nest.is_nested(model_outputs): + model_outputs = [model_outputs] + model_outputs = tf_utils.convert_inner_node_data(model_outputs) + config['output_layers'] = model_outputs + return config + + +def shape_with_no_batch_size(x): + if x.shape.rank is None: + return None + shape = x.shape.as_list() + if shape: + shape[0] = None + return shape + + +class ModuleWrapper(base_layer.Layer): + """Wrapper for `tf.Module`s to support the Functional and Sequential API.""" + + def __init__(self, module, method_name=None, **kwargs): + """Initializes the wrapper Layer for this module. + + Args: + module: The `tf.Module` instance to be wrapped. + method_name: (Optional) str. The name of the method to use as the forward + pass of the module. If not set, defaults to '__call__' if defined, or + 'call'. + **kwargs: Additional keywrod arguments. See `tf.keras.layers.Layer`. + + Raises: + ValueError: If `method` is not defined on `module`. + """ + super(ModuleWrapper, self).__init__(**kwargs) + if method_name is None: + if hasattr(module, '__call__'): + method_name = '__call__' + elif hasattr(module, 'call'): + method_name = 'call' + if method_name is None or not hasattr(module, method_name): + raise ValueError('{} is not defined on object {}'.format( + method_name, module)) + + self._module = module + self._method_name = method_name + + # Check if module.__call__ has a `training` arg or accepts `**kwargs`. + method = getattr(module, method_name) + method_arg_spec = tf_inspect.getfullargspec(method) + self._expects_training_arg = ('training' in method_arg_spec.args or + method_arg_spec.varkw is not None) + self._expects_mask_arg = ('mask' in method_arg_spec.args or + method_arg_spec.varkw is not None) + + def call(self, *args, **kwargs): + if 'training' in kwargs and not self._expects_training_arg: + kwargs.pop('training') + if 'mask' in kwargs and not self._expects_mask_arg: + kwargs.pop('mask') + return getattr(self._module, self._method_name)(*args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_layer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..6af2f52896d15b09e2a93f1bf4a3914da39316e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_layer.py @@ -0,0 +1,391 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Input layer code (`Input` and `InputLayer`).""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.keras import backend +from tensorflow.python.keras.distribute import distributed_training_utils +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.engine import node as node_module +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.utils import tf_utils + + +def _assert_other_arg_none(arg_name, arg): + if arg is not None: + raise ValueError('When `type_spec` is not None, all other args ' + 'except `name` must be None, ' + 'but %s is not None.' % arg_name) + + +class InputLayer(base_layer.Layer): + """Layer to be used as an entry point into a Network (a graph of layers). + + It can either wrap an existing tensor (pass an `input_tensor` argument) + or create a placeholder tensor (pass arguments `input_shape`, and + optionally, `dtype`). + + It is generally recommend to use the functional layer API via `Input`, + (which creates an `InputLayer`) without directly using `InputLayer`. + + When using InputLayer with Keras Sequential model, it can be skipped by + moving the input_shape parameter to the first layer after the InputLayer. + + This class can create placeholders for tf.Tensors, tf.SparseTensors, and + tf.RaggedTensors by choosing 'sparse=True' or 'ragged=True'. Note that + 'sparse' and 'ragged' can't be configured to True at same time. + Usage: + + ```python + # With explicit InputLayer. + model = tf.keras.Sequential([ + tf.keras.layers.InputLayer(input_shape=(4,)), + tf.keras.layers.Dense(8)]) + model.compile(tf.optimizers.RMSprop(0.001), loss='mse') + model.fit(np.zeros((10, 4)), + np.ones((10, 8))) + + # Without InputLayer and let the first layer to have the input_shape. + # Keras will add a input for the model behind the scene. + model = tf.keras.Sequential([ + tf.keras.layers.Dense(8, input_shape=(4,))]) + model.compile(tf.optimizers.RMSprop(0.001), loss='mse') + model.fit(np.zeros((10, 4)), + np.ones((10, 8))) + ``` + + Args: + input_shape: Shape tuple (not including the batch axis), or `TensorShape` + instance (not including the batch axis). + batch_size: Optional input batch size (integer or None). + dtype: Optional datatype of the input. When not provided, the Keras + default float type will be used. + input_tensor: Optional tensor to use as layer input. If set, the layer + will use the `tf.TypeSpec` of this tensor rather + than creating a new placeholder tensor. + sparse: Boolean, whether the placeholder created is meant to be sparse. + Default to False. + ragged: Boolean, whether the placeholder created is meant to be ragged. + In this case, values of 'None' in the 'shape' argument represent + ragged dimensions. For more information about RaggedTensors, see + [this guide](https://www.tensorflow.org/guide/ragged_tensors). + Default to False. + type_spec: A `tf.TypeSpec` object to create Input from. This `tf.TypeSpec` + represents the entire batch. When provided, all other args except + name must be None. + name: Optional name of the layer (string). + """ + + def __init__(self, + input_shape=None, + batch_size=None, + dtype=None, + input_tensor=None, + sparse=None, + name=None, + ragged=None, + type_spec=None, + **kwargs): + self._init_input_shape = input_shape + self._init_batch_size = batch_size + self._init_dtype = dtype + self._init_sparse = sparse + self._init_ragged = ragged + self._init_type_spec = type_spec + + strategy = distribute_lib.get_strategy() + if strategy and batch_size is not None and \ + distributed_training_utils.global_batch_size_supported(strategy): + if batch_size % strategy.num_replicas_in_sync != 0: + raise ValueError('The `batch_size` argument ({}) must be divisible by ' + 'the number of replicas ({})'.format( + batch_size, strategy.num_replicas_in_sync)) + batch_size = batch_size // strategy.num_replicas_in_sync + + if 'batch_input_shape' in kwargs: + batch_input_shape = kwargs.pop('batch_input_shape') + if input_shape and batch_input_shape: + raise ValueError('Only provide the input_shape OR ' + 'batch_input_shape argument to ' + 'InputLayer, not both at the same time.') + # Set the input shape and batch size from the batch_input_shape. + # Note that batch_input_shape can be None (unknown rank) or [] (scalar), + # in which case the batch size must be None. + if batch_input_shape: + batch_size = batch_input_shape[0] + input_shape = batch_input_shape[1:] + if kwargs: + raise ValueError('Unrecognized keyword arguments:', kwargs.keys()) + + if sparse and ragged: + raise ValueError( + 'Cannot set both sparse and ragged to True in a Keras input.') + + if not name: + prefix = 'input' + name = prefix + '_' + str(backend.get_uid(prefix)) + + if not dtype: + if input_tensor is None: + dtype = backend.floatx() + else: + dtype = backend.dtype(input_tensor) + elif input_tensor is not None and input_tensor.dtype != dtype: + raise ValueError('`input_tensor.dtype` differs from `dtype`: %s vs. %s' % + (input_tensor.dtype, dtype)) + super(InputLayer, self).__init__(dtype=dtype, name=name) + self.built = True + self.sparse = True if sparse else False + self.ragged = True if ragged else False + self.batch_size = batch_size + self.supports_masking = True + + if isinstance(input_shape, tensor_shape.TensorShape): + input_shape = tuple(input_shape.as_list()) + elif isinstance(input_shape, int): + input_shape = (input_shape,) + + if type_spec is not None: + args_that_must_be_none = [ + ('(input_)shape', self._init_input_shape), + ('batch_size', self._init_batch_size), + ('dtype', self._init_dtype), + ('input_tensor', input_tensor), + ('sparse', self._init_sparse), + ('ragged', self._init_ragged), + ] + for arg_name, arg in args_that_must_be_none: + _assert_other_arg_none(arg_name, arg) + if not ops.executing_eagerly_outside_functions(): + raise ValueError('Creating Keras inputs from a type_spec is only ' + 'supported when eager execution is enabled.') + input_tensor = keras_tensor.keras_tensor_from_type_spec(type_spec) + if isinstance(input_tensor, keras_tensor.SparseKerasTensor): + self.sparse = True + if isinstance(input_tensor, keras_tensor.RaggedKerasTensor): + self.ragged = True + self.is_placeholder = True + try: + self._batch_input_shape = tuple(input_tensor.shape.as_list()) + except ValueError: + # If the shape cannot be represented as a tuple (e.g. unknown rank) + self._batch_input_shape = None + elif input_tensor is None: + if input_shape is not None: + batch_input_shape = (batch_size,) + tuple(input_shape) + else: + batch_input_shape = None + graph = backend.get_graph() + with graph.as_default(): + input_tensor = backend.placeholder( + shape=batch_input_shape, + dtype=dtype, + name=self.name, + sparse=sparse, + ragged=ragged) + + self.is_placeholder = True + self._batch_input_shape = batch_input_shape + else: + if ops.executing_eagerly_outside_functions(): + if not isinstance(input_tensor, keras_tensor.KerasTensor): + input_tensor = keras_tensor.keras_tensor_from_tensor(input_tensor) + else: + if not tf_utils.is_symbolic_tensor(input_tensor): + raise ValueError('You should not pass an EagerTensor to `Input`. ' + 'For example, instead of creating an ' + 'InputLayer, you should instantiate your model and ' + 'directly call it on your input.') + self.is_placeholder = False + try: + self._batch_input_shape = tuple(input_tensor.shape.as_list()) + except ValueError: + # If the shape cannot be represented as a tuple (e.g. unknown rank) + self._batch_input_shape = None + # Create an input node. + input_tensor._keras_mask = None + node_module.Node(layer=self, outputs=input_tensor) + + # Store type spec + if isinstance(input_tensor, keras_tensor.KerasTensor) or ( + tf_utils.is_extension_type(input_tensor)): + self._type_spec = input_tensor._type_spec # pylint: disable=protected-access + else: + self._type_spec = tensor_spec.TensorSpec( + shape=input_tensor.shape, dtype=input_tensor.dtype, name=self.name) + + def get_config(self): + if self._init_type_spec is not None: + config = { + 'name': self.name, + 'type_spec': self._init_type_spec + } + else: + config = { + 'batch_input_shape': self._batch_input_shape, + 'dtype': self.dtype, + 'sparse': self.sparse, + 'ragged': self.ragged, + 'name': self.name, + } + return config + + @property + def _trackable_saved_model_saver(self): + return layer_serialization.InputLayerSavedModelSaver(self) + + +def Input( # pylint: disable=invalid-name + shape=None, + batch_size=None, + name=None, + dtype=None, + sparse=None, + tensor=None, + ragged=None, + type_spec=None, + **kwargs): + """`Input()` is used to instantiate a Keras tensor. + + A Keras tensor is a symbolic tensor-like object, + which we augment with certain attributes that allow us to build a Keras model + just by knowing the inputs and outputs of the model. + + For instance, if `a`, `b` and `c` are Keras tensors, + it becomes possible to do: + `model = Model(input=[a, b], output=c)` + + Args: + shape: A shape tuple (integers), not including the batch size. + For instance, `shape=(32,)` indicates that the expected input + will be batches of 32-dimensional vectors. Elements of this tuple + can be None; 'None' elements represent dimensions where the shape is + not known. + batch_size: optional static batch size (integer). + name: An optional name string for the layer. + Should be unique in a model (do not reuse the same name twice). + It will be autogenerated if it isn't provided. + dtype: The data type expected by the input, as a string + (`float32`, `float64`, `int32`...) + sparse: A boolean specifying whether the placeholder to be created is + sparse. Only one of 'ragged' and 'sparse' can be True. Note that, + if `sparse` is False, sparse tensors can still be passed into the + input - they will be densified with a default value of 0. + tensor: Optional existing tensor to wrap into the `Input` layer. + If set, the layer will use the `tf.TypeSpec` of this tensor rather + than creating a new placeholder tensor. + ragged: A boolean specifying whether the placeholder to be created is + ragged. Only one of 'ragged' and 'sparse' can be True. In this case, + values of 'None' in the 'shape' argument represent ragged dimensions. + For more information about RaggedTensors, see + [this guide](https://www.tensorflow.org/guide/ragged_tensors). + type_spec: A `tf.TypeSpec` object to create the input placeholder from. + When provided, all other args except name must be None. + **kwargs: deprecated arguments support. Supports `batch_shape` and + `batch_input_shape`. + + Returns: + A `tensor`. + + Example: + + ```python + # this is a logistic regression in Keras + x = Input(shape=(32,)) + y = Dense(16, activation='softmax')(x) + model = Model(x, y) + ``` + + Note that even if eager execution is enabled, + `Input` produces a symbolic tensor-like object (i.e. a placeholder). + This symbolic tensor-like object can be used with lower-level + TensorFlow ops that take tensors as inputs, as such: + + ```python + x = Input(shape=(32,)) + y = tf.square(x) # This op will be treated like a layer + model = Model(x, y) + ``` + + (This behavior does not work for higher-order TensorFlow APIs such as + control flow and being directly watched by a `tf.GradientTape`). + + However, the resulting model will not track any variables that were + used as inputs to TensorFlow ops. All variable usages must happen within + Keras layers to make sure they will be tracked by the model's weights. + + The Keras Input can also create a placeholder from an arbitrary `tf.TypeSpec`, + e.g: + + ```python + x = Input(type_spec=tf.RaggedTensorSpec(shape=[None, None], + dtype=tf.float32, ragged_rank=1)) + y = x.values + model = Model(x, y) + ``` + When passing an arbitrary `tf.TypeSpec`, it must represent the signature of an + entire batch instead of just one example. + + Raises: + ValueError: If both `sparse` and `ragged` are provided. + ValueError: If both `shape` and (`batch_input_shape` or `batch_shape`) are + provided. + ValueError: If `shape`, `tensor` and `type_spec` are None. + ValueError: If arguments besides `type_spec` are non-None while `type_spec` + is passed. + ValueError: if any unrecognized parameters are provided. + """ + if sparse and ragged: + raise ValueError( + 'Cannot set both sparse and ragged to True in a Keras input.') + + input_layer_config = {'name': name, 'dtype': dtype, 'sparse': sparse, + 'ragged': ragged, 'input_tensor': tensor, + 'type_spec': type_spec} + + batch_input_shape = kwargs.pop('batch_input_shape', + kwargs.pop('batch_shape', None)) + if shape is not None and batch_input_shape is not None: + raise ValueError('Only provide the `shape` OR `batch_input_shape` argument ' + 'to Input, not both at the same time.') + if (batch_input_shape is None and shape is None and tensor is None + and type_spec is None): + raise ValueError('Please provide to Input a `shape`' + ' or a `tensor` or a `type_spec` argument. Note that ' + '`shape` does not include the batch ' + 'dimension.') + if kwargs: + raise ValueError('Unrecognized keyword arguments:', kwargs.keys()) + + if batch_input_shape: + shape = batch_input_shape[1:] + input_layer_config.update({'batch_input_shape': batch_input_shape}) + else: + input_layer_config.update( + {'batch_size': batch_size, 'input_shape': shape}) + input_layer = InputLayer(**input_layer_config) + + # Return tensor including `_keras_history`. + # Note that in this case train_output and test_output are the same pointer. + outputs = input_layer._inbound_nodes[0].outputs + if isinstance(outputs, list) and len(outputs) == 1: + return outputs[0] + else: + return outputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_spec.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..27dac2998a1332177295935f116e58b64ed6fb26 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/input_spec.py @@ -0,0 +1,281 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=g-classes-have-attributes +"""Contains the InputSpec class.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.keras import backend +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['layers.InputSpec']) +class InputSpec(object): + """Specifies the rank, dtype and shape of every input to a layer. + + Layers can expose (if appropriate) an `input_spec` attribute: + an instance of `InputSpec`, or a nested structure of `InputSpec` instances + (one per input tensor). These objects enable the layer to run input + compatibility checks for input structure, input rank, input shape, and + input dtype. + + A None entry in a shape is compatible with any dimension, + a None shape is compatible with any shape. + + Args: + dtype: Expected DataType of the input. + shape: Shape tuple, expected shape of the input + (may include None for unchecked axes). Includes the batch size. + ndim: Integer, expected rank of the input. + max_ndim: Integer, maximum rank of the input. + min_ndim: Integer, minimum rank of the input. + axes: Dictionary mapping integer axes to + a specific dimension value. + allow_last_axis_squeeze: If True, then allow inputs of rank N+1 as long + as the last axis of the input is 1, as well as inputs of rank N-1 + as long as the last axis of the spec is 1. + name: Expected key corresponding to this input when passing data as + a dictionary. + + Example: + + ```python + class MyLayer(Layer): + def __init__(self): + super(MyLayer, self).__init__() + # The layer will accept inputs with shape (?, 28, 28) & (?, 28, 28, 1) + # and raise an appropriate error message otherwise. + self.input_spec = InputSpec( + shape=(None, 28, 28, 1), + allow_last_axis_squeeze=True) + ``` + """ + + def __init__(self, + dtype=None, + shape=None, + ndim=None, + max_ndim=None, + min_ndim=None, + axes=None, + allow_last_axis_squeeze=False, + name=None): + self.dtype = dtypes.as_dtype(dtype).name if dtype is not None else None + shape = tensor_shape.TensorShape(shape) + if shape.rank is None: + shape = None + else: + shape = tuple(shape.as_list()) + if shape is not None: + self.ndim = len(shape) + self.shape = shape + else: + self.ndim = ndim + self.shape = None + self.max_ndim = max_ndim + self.min_ndim = min_ndim + self.name = name + self.allow_last_axis_squeeze = allow_last_axis_squeeze + try: + axes = axes or {} + self.axes = {int(k): axes[k] for k in axes} + except (ValueError, TypeError): + raise TypeError('The keys in axes must be integers.') + + if self.axes and (self.ndim is not None or self.max_ndim is not None): + max_dim = (self.ndim if self.ndim else self.max_ndim) - 1 + max_axis = max(self.axes) + if max_axis > max_dim: + raise ValueError('Axis {} is greater than the maximum allowed value: {}' + .format(max_axis, max_dim)) + + def __repr__(self): + spec = [('dtype=' + str(self.dtype)) if self.dtype else '', + ('shape=' + str(self.shape)) if self.shape else '', + ('ndim=' + str(self.ndim)) if self.ndim else '', + ('max_ndim=' + str(self.max_ndim)) if self.max_ndim else '', + ('min_ndim=' + str(self.min_ndim)) if self.min_ndim else '', + ('axes=' + str(self.axes)) if self.axes else ''] + return 'InputSpec(%s)' % ', '.join(x for x in spec if x) + + def get_config(self): + return { + 'dtype': self.dtype, + 'shape': self.shape, + 'ndim': self.ndim, + 'max_ndim': self.max_ndim, + 'min_ndim': self.min_ndim, + 'axes': self.axes} + + @classmethod + def from_config(cls, config): + return cls(**config) + + +def to_tensor_shape(spec): + """Returns a tf.TensorShape object that matches the shape specifications. + + If the InputSpec's shape or ndim is defined, this method will return a fully + or partially-known shape. Otherwise, the returned TensorShape is None. + + Args: + spec: an InputSpec object. + + Returns: + a tf.TensorShape object + """ + if spec.ndim is None and spec.shape is None: + return tensor_shape.TensorShape(None) + elif spec.shape is not None: + return tensor_shape.TensorShape(spec.shape) + else: + shape = [None] * spec.ndim + for a in spec.axes: + shape[a] = spec.axes[a] # Assume that axes is defined + return tensor_shape.TensorShape(shape) + + +def assert_input_compatibility(input_spec, inputs, layer_name): + """Checks compatibility between the layer and provided inputs. + + This checks that the tensor(s) `inputs` verify the input assumptions + of a layer (if any). If not, a clear and actional exception gets raised. + + Args: + input_spec: An InputSpec instance, list of InputSpec instances, a nested + structure of InputSpec instances, or None. + inputs: Input tensor, list of input tensors, or a nested structure of + input tensors. + layer_name: String, name of the layer (for error message formatting). + + Raises: + ValueError: in case of mismatch between + the provided inputs and the expectations of the layer. + """ + if not input_spec: + return + + input_spec = nest.flatten(input_spec) + if isinstance(inputs, dict): + # Flatten `inputs` by reference order if input spec names are provided + names = [spec.name for spec in input_spec] + if all(names): + list_inputs = [] + for name in names: + if name not in inputs: + raise ValueError('Missing data for input "%s". ' + 'You passed a data dictionary with keys %s. ' + 'Expected the following keys: %s' % + (name, list(inputs.keys()), names)) + list_inputs.append(inputs[name]) + inputs = list_inputs + + inputs = nest.flatten(inputs) + for x in inputs: + # Having a shape/dtype is the only commonality of the various tensor-like + # objects that may be passed. The most common kind of invalid type we are + # guarding for is a Layer instance (Functional API), which does not + # have a `shape` attribute. + if not hasattr(x, 'shape'): + raise TypeError('Inputs to a layer should be tensors. Got: %s' % (x,)) + + if len(inputs) != len(input_spec): + raise ValueError('Layer ' + layer_name + ' expects ' + + str(len(input_spec)) + ' input(s), ' + 'but it received ' + str(len(inputs)) + + ' input tensors. Inputs received: ' + str(inputs)) + for input_index, (x, spec) in enumerate(zip(inputs, input_spec)): + if spec is None: + continue + + shape = tensor_shape.TensorShape(x.shape) + if shape.rank is None: + return + # Check ndim. + if spec.ndim is not None and not spec.allow_last_axis_squeeze: + ndim = shape.rank + if ndim != spec.ndim: + raise ValueError('Input ' + str(input_index) + ' of layer ' + + layer_name + ' is incompatible with the layer: ' + 'expected ndim=' + str(spec.ndim) + ', found ndim=' + + str(ndim) + '. Full shape received: ' + + str(tuple(shape))) + if spec.max_ndim is not None: + ndim = x.shape.rank + if ndim is not None and ndim > spec.max_ndim: + raise ValueError('Input ' + str(input_index) + ' of layer ' + + layer_name + ' is incompatible with the layer: ' + 'expected max_ndim=' + str(spec.max_ndim) + + ', found ndim=' + str(ndim)) + if spec.min_ndim is not None: + ndim = x.shape.rank + if ndim is not None and ndim < spec.min_ndim: + raise ValueError('Input ' + str(input_index) + ' of layer ' + + layer_name + ' is incompatible with the layer: ' + ': expected min_ndim=' + str(spec.min_ndim) + + ', found ndim=' + str(ndim) + + '. Full shape received: ' + + str(tuple(shape))) + # Check dtype. + if spec.dtype is not None: + if x.dtype.name != spec.dtype: + raise ValueError('Input ' + str(input_index) + ' of layer ' + + layer_name + ' is incompatible with the layer: ' + 'expected dtype=' + str(spec.dtype) + + ', found dtype=' + str(x.dtype)) + + # Check specific shape axes. + shape_as_list = shape.as_list() + if spec.axes: + for axis, value in spec.axes.items(): + if hasattr(value, 'value'): + value = value.value + if value is not None and shape_as_list[int(axis)] not in {value, None}: + raise ValueError( + 'Input ' + str(input_index) + ' of layer ' + layer_name + ' is' + ' incompatible with the layer: expected axis ' + str(axis) + + ' of input shape to have value ' + str(value) + + ' but received input with shape ' + display_shape(x.shape)) + # Check shape. + if spec.shape is not None and shape.rank is not None: + spec_shape = spec.shape + if spec.allow_last_axis_squeeze: + if shape_as_list and shape_as_list[-1] == 1: + shape_as_list = shape_as_list[:-1] + if spec_shape and spec_shape[-1] == 1: + spec_shape = spec_shape[:-1] + for spec_dim, dim in zip(spec_shape, shape_as_list): + if spec_dim is not None and dim is not None: + if spec_dim != dim: + raise ValueError('Input ' + str(input_index) + + ' is incompatible with layer ' + layer_name + + ': expected shape=' + str(spec.shape) + + ', found shape=' + display_shape(x.shape)) + + +def display_shape(shape): + return str(tuple(shape.as_list())) + + +def to_tensor_spec(input_spec, default_dtype=None): + """Converts a Keras InputSpec object to a TensorSpec.""" + default_dtype = default_dtype or backend.floatx() + if isinstance(input_spec, InputSpec): + dtype = input_spec.dtype or default_dtype + return tensor_spec.TensorSpec(to_tensor_shape(input_spec), dtype) + return tensor_spec.TensorSpec(None, default_dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/keras_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/keras_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..2735c83370ab698a68b4fcf78b1dbbb98d4d008f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/keras_tensor.py @@ -0,0 +1,611 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras Input Tensor used to track functional API Topology.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec as type_spec_module +from tensorflow.python.keras.utils import object_identity +from tensorflow.python.ops import array_ops +from tensorflow.python.ops.ragged import ragged_operators # pylint: disable=unused-import +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import nest + +# pylint: disable=g-classes-have-attributes + + +# Tensorflow tensors have a maximum rank of 254 +# (See `MaxDimensions()` in //tensorflow/core/framework/tensor_shape.h ) +# So we do not try to infer values for int32 tensors larger than this, +# As they cannot represent shapes. +_MAX_TENSOR_RANK = 254 + + +class KerasTensor(object): + """A representation of a Keras in/output during Functional API construction. + + `KerasTensor`s are tensor-like objects that represent the symbolic inputs + and outputs of Keras layers during Functional model construction. They are + comprised of the `tf.TypeSpec` of the (Composite)Tensor that will be + consumed/produced in the corresponding location of the Functional model. + + KerasTensors are intended as a private API, so users should never need to + directly instantiate `KerasTensor`s. + + **Building Functional Models with KerasTensors** + `tf.keras.Input` produces `KerasTensor`s that represent the symbolic inputs + to your model. + + Passing a `KerasTensor` to a `tf.keras.Layer` `__call__` lets the layer know + that you are building a Functional model. The layer __call__ will + infer the output signature and return `KerasTensor`s with `tf.TypeSpec`s + corresponding to the symbolic outputs of that layer call. These output + `KerasTensor`s will have all of the internal KerasHistory metadata attached + to them that Keras needs to construct a Functional Model. + + Currently, layers infer the output signature by: + * creating a scratch `FuncGraph` + * making placeholders in the scratch graph that match the input typespecs + * Calling `layer.call` on these placeholders + * extracting the signatures of the outputs before clearing the scratch graph + + (Note: names assigned to KerasTensors by this process are not guaranteed to + be unique, and are subject to implementation details). + + `tf.nest` methods are used to insure all of the inputs/output data + structures get maintained, with elements swapped between KerasTensors and + placeholders. + + In rare cases (such as when directly manipulating shapes using Keras layers), + the layer may be able to partially infer the value of the output in addition + to just inferring the signature. + When this happens, the returned KerasTensor will also contain the inferred + value information. Follow-on layers can use this information. + during their own output signature inference. + E.g. if one layer produces a symbolic `KerasTensor` that the next layer uses + as the shape of its outputs, partially knowing the value helps infer the + output shape. + + **Automatically converting TF APIs to layers**: + If you passing a `KerasTensor` to a TF API that supports dispatching, + Keras will automatically turn that API call into a lambda + layer in the Functional model, and return KerasTensors representing the + symbolic outputs. + + Most TF APIs that take only tensors as input and produce output tensors + will support dispatching. + + Calling a `tf.function` does not support dispatching, so you cannot pass + `KerasTensor`s as inputs to a `tf.function`. + + Higher-order APIs that take methods which produce tensors (e.g. `tf.while`, + `tf.map_fn`, `tf.cond`) also do not currently support dispatching. So, you + cannot directly pass KerasTensors as inputs to these APIs either. If you + want to use these APIs inside of a Functional model, you must put them inside + of a custom layer. + + Args: + type_spec: The `tf.TypeSpec` for the symbolic input created by + `tf.keras.Input`, or symbolically inferred for the output + during a symbolic layer `__call__`. + inferred_value: (Optional) a non-symbolic static value, possibly partially + specified, that could be symbolically inferred for the outputs during + a symbolic layer `__call__`. This will generally only happen when + grabbing and manipulating `tf.int32` shapes directly as tensors. + Statically inferring values in this way and storing them in the + KerasTensor allows follow-on layers to infer output signatures + more effectively. (e.g. when using a symbolic shape tensor to later + construct a tensor with that shape). + name: (optional) string name for this KerasTensor. Names automatically + generated by symbolic layer `__call__`s are not guaranteed to be unique, + and are subject to implementation details. + """ + + def __init__(self, type_spec, inferred_value=None, name=None): + """Constructs a KerasTensor.""" + if not isinstance(type_spec, type_spec_module.TypeSpec): + raise ValueError('KerasTensors must be constructed with a `tf.TypeSpec`.') + + self._type_spec = type_spec + self._inferred_value = inferred_value + self._name = name + + @property + def type_spec(self): + """Returns the `tf.TypeSpec` symbolically inferred for this Keras output.""" + return self._type_spec + + @property + def shape(self): + """Returns the `TensorShape` symbolically inferred for this Keras output.""" + # TODO(kaftan): This is only valid for normal/sparse/ragged tensors. + # may need to raise an error when it's not valid for a type_spec, + # but some keras code (e.g. build-related stuff) will likely fail when + # it can't access shape or dtype + return self._type_spec._shape # pylint: disable=protected-access + + @classmethod + def from_tensor(cls, tensor): + """Convert a traced (composite)tensor to a representative KerasTensor.""" + if isinstance(tensor, tensor_lib.Tensor): + name = getattr(tensor, 'name', None) + type_spec = type_spec_module.type_spec_from_value(tensor) + inferred_value = None + if (type_spec.dtype == dtypes.int32 and type_spec.shape.rank is not None + and type_spec.shape.rank < 2): + # If this tensor might be representing shape information, + # (dtype=int32, rank of 0 or 1, not too large to represent a shape) + # we attempt to capture any value information tensorflow's + # shape handling can extract from the current scratch graph. + # + # Even though keras layers each trace in their own scratch + # graph, this shape value info extraction allows us to capture + # a sizable and useful subset of the C++ shape value inference TF can do + # if all tf ops appear in the same graph when using shape ops. + # + # Examples of things this cannot infer concrete dimensions for + # that the full single-graph C++ shape inference sometimes can are: + # * cases where the shape tensor is cast out of int32 before being + # manipulated w/ floating point numbers then converted back + # * cases where int32 tensors w/ rank >= 2 are manipulated before being + # used as a shape tensor + # * cases where int32 tensors too large to represent shapes are + # manipulated to a smaller size before being used as a shape tensor + inferred_value = array_ops.ones(shape=tensor).shape + if inferred_value.dims: + inferred_value = inferred_value.as_list() + if len(inferred_value) > _MAX_TENSOR_RANK: + inferred_value = None + else: + inferred_value = None + + return KerasTensor(type_spec, inferred_value=inferred_value, name=name) + else: + # Fallback to the generic arbitrary-typespec KerasTensor + name = getattr(tensor, 'name', None) + type_spec = type_spec_module.type_spec_from_value(tensor) + return cls(type_spec, name=name) + + @classmethod + def from_type_spec(cls, type_spec, name=None): + return cls(type_spec=type_spec, name=name) + + def _to_placeholder(self): + """Convert this KerasTensor to a placeholder in a graph.""" + # If there is an inferred value for this tensor, inject the inferred value + if self._inferred_value is not None: + # If we suspect this KerasTensor might be representing a shape tensor, + # and we were able to extract value information with TensorFlow's shape + # handling when making the KerasTensor, we construct the placeholder by + # re-injecting the inferred value information into the graph. We + # do this injection through the shape of a placeholder, because that + # allows us to specify partially-unspecified shape values. + # + # See the comment on value extraction inside `from_tensor` for more info. + inferred_value = array_ops.shape( + array_ops.placeholder( + shape=self._inferred_value, dtype=dtypes.int32)) + if self.type_spec.shape.rank == 0: + # `tf.shape` always returns a rank-1, we may need to turn it back to a + # scalar. + inferred_value = inferred_value[0] + return inferred_value + + # Use the generic conversion from typespec to a placeholder. + def component_to_placeholder(component): + return array_ops.placeholder(component.dtype, component.shape) + + return nest.map_structure( + component_to_placeholder, self.type_spec, expand_composites=True) + + def get_shape(self) -> tensor_shape.TensorShape: + return self.shape + + def __len__(self): + raise TypeError('Keras symbolic inputs/outputs do not ' + 'implement `__len__`. You may be ' + 'trying to pass Keras symbolic inputs/outputs ' + 'to a TF API that does not register dispatching, ' + 'preventing Keras from automatically ' + 'converting the API call to a lambda layer ' + 'in the Functional Model. This error will also get raised ' + 'if you try asserting a symbolic input/output directly.') + + @property + def op(self): + raise TypeError('Keras symbolic inputs/outputs do not ' + 'implement `op`. You may be ' + 'trying to pass Keras symbolic inputs/outputs ' + 'to a TF API that does not register dispatching, ' + 'preventing Keras from automatically ' + 'converting the API call to a lambda layer ' + 'in the Functional Model.') + + def __hash__(self): + raise TypeError('Tensors are unhashable. (%s)' + 'Instead, use tensor.ref() as the key.' % self) + + # Note: This enables the KerasTensor's overloaded "right" binary + # operators to run when the left operand is an ndarray, because it + # accords the Tensor class higher priority than an ndarray, or a + # numpy matrix. + # In the future explore chaning this to using numpy's __numpy_ufunc__ + # mechanism, which allows more control over how Tensors interact + # with ndarrays. + __array_priority__ = 100 + + def __array__(self): + raise TypeError( + 'Cannot convert a symbolic Keras input/output to a numpy array. ' + 'This error may indicate that you\'re trying to pass a symbolic value ' + 'to a NumPy call, which is not supported. Or, ' + 'you may be trying to pass Keras symbolic inputs/outputs ' + 'to a TF API that does not register dispatching, ' + 'preventing Keras from automatically ' + 'converting the API call to a lambda layer ' + 'in the Functional Model.') + + @property + def is_tensor_like(self): + return True + + def set_shape(self, shape): + """Updates the shape of this KerasTensor. Mimics `tf.Tensor.set_shape()`.""" + if not isinstance(shape, tensor_shape.TensorShape): + shape = tensor_shape.TensorShape(shape) + if shape.dims is not None: + dim_list = [dim.value for dim in shape.dims] + for dim in range(len(dim_list)): + if dim_list[dim] is None and self.shape.dims is not None: + dim_list[dim] = self.shape.dims[dim] + shape = tensor_shape.TensorShape(dim_list) + if not self.shape.is_compatible_with(shape): + raise ValueError( + "Keras symbolic input/output's shape %s is not" + "compatible with supplied shape %s" % + (self.shape, shape)) + else: + self._type_spec._shape = shape # pylint: disable=protected-access + + def __str__(self): + symbolic_description = '' + inferred_value_string = '' + name_string = '' + + if hasattr(self, '_keras_history'): + layer = self._keras_history.layer + symbolic_description = ( + ', description="created by layer \'%s\'"' % (layer.name,)) + if self._inferred_value is not None: + inferred_value_string = ( + ', inferred_value=%s' % self._inferred_value) + if self.name is not None: + name_string = ', name=\'%s\'' % self._name + return 'KerasTensor(type_spec=%s%s%s%s)' % ( + self.type_spec, inferred_value_string, + name_string, symbolic_description) + + def __repr__(self): + symbolic_description = '' + inferred_value_string = '' + if isinstance(self.type_spec, tensor_lib.TensorSpec): + type_spec_string = 'shape=%s dtype=%s' % (self.shape, self.dtype.name) + else: + type_spec_string = 'type_spec=%s' % self.type_spec + + if hasattr(self, '_keras_history'): + layer = self._keras_history.layer + symbolic_description = ' (created by layer \'%s\')' % (layer.name,) + if self._inferred_value is not None: + inferred_value_string = ( + ' inferred_value=%s' % self._inferred_value) + return '' % ( + type_spec_string, inferred_value_string, symbolic_description) + + @property + def dtype(self): + """Returns the `dtype` symbolically inferred for this Keras output.""" + # TODO(kaftan): This is only valid for normal/sparse/ragged tensors. + # may need to raise an error when it's not valid for a type_spec, + # but some keras code (e.g. build-related stuff) will likely fail when + # it can't access shape or dtype + return self._type_spec._dtype # pylint: disable=protected-access + + def ref(self): + """Returns a hashable reference object to this KerasTensor. + + The primary use case for this API is to put KerasTensors in a + set/dictionary. We can't put tensors in a set/dictionary as + `tensor.__hash__()` is not available and tensor equality (`==`) is supposed + to produce a tensor representing if the two inputs are equal. + + See the documentation of `tf.Tensor.ref()` for more info. + """ + return object_identity.Reference(self) + + def __iter__(self): + shape = None + if self.shape.ndims is not None: + shape = [dim.value for dim in self.shape.dims] + + if shape is None: + raise TypeError('Cannot iterate over a Tensor with unknown shape.') + if not shape: + raise TypeError('Cannot iterate over a scalar.') + if shape[0] is None: + raise TypeError( + 'Cannot iterate over a Tensor with unknown first dimension.') + return _KerasTensorIterator(self, shape[0]) + + @property + def name(self): + """Returns the (non-unique, optional) name of this symbolic Keras value.""" + return self._name + + @classmethod + def _overload_all_operators(cls, tensor_class): # pylint: disable=invalid-name + """Register overloads for all operators.""" + for operator in tensor_lib.Tensor.OVERLOADABLE_OPERATORS: + cls._overload_operator(tensor_class, operator) + + # We include `experimental_ref` for versions of TensorFlow that + # still include the deprecated method in Tensors. + if hasattr(tensor_class, 'experimental_ref'): + cls._overload_operator(tensor_class, 'experimental_ref') + + @classmethod + def _overload_operator(cls, tensor_class, operator): # pylint: disable=invalid-name + """Overload an operator with the same implementation as a base Tensor class. + + We pull the operator out of the class dynamically to avoid ordering issues. + + Args: + tensor_class: The (Composite)Tensor to get the method from. + operator: string. The operator name. + """ + tensor_oper = getattr(tensor_class, operator) + + # Compatibility with Python 2: + # Python 2 unbound methods have type checks for the first arg, + # so we need to extract the underlying function + tensor_oper = getattr(tensor_oper, '__func__', tensor_oper) + + setattr(cls, operator, tensor_oper) + + +KerasTensor._overload_all_operators(tensor_lib.Tensor) # pylint: disable=protected-access + + +class SparseKerasTensor(KerasTensor): + """A specialized KerasTensor representation for `tf.sparse.SparseTensor`s. + + Specifically, it specializes the conversion to a placeholder in order + to maintain dense shape information. + """ + + def _to_placeholder(self): + spec = self.type_spec + + # nest.map_structure loses dense shape information for sparse tensors. + # So, we special-case sparse placeholder creation. + # This only preserves shape information for top-level sparse tensors; + # not for sparse tensors that are nested inside another composite + # tensor. + return array_ops.sparse_placeholder(dtype=spec.dtype, shape=spec.shape) + + +class RaggedKerasTensor(KerasTensor): + """A specialized KerasTensor representation for `tf.RaggedTensor`s. + + Specifically, it: + + 1. Specializes the conversion to a placeholder in order + to maintain shape information for non-ragged dimensions. + 2. Overloads the KerasTensor's operators with the RaggedTensor versions + when they don't match the `tf.Tensor` versions + 3. Exposes some of the instance method/attribute that are unique to + the RaggedTensor API (such as ragged_rank). + """ + + def _to_placeholder(self): + ragged_spec = self.type_spec + if ragged_spec.ragged_rank == 0 or ragged_spec.shape.rank is None: + return super(RaggedKerasTensor, self)._to_placeholder() + + flat_shape = ragged_spec.shape[ragged_spec.ragged_rank:] + result = array_ops.placeholder(ragged_spec.dtype, flat_shape) + + known_num_splits = [] + prod = 1 + for axis_size in ragged_spec.shape: + if prod is not None: + if axis_size is None or ( + getattr(axis_size, 'value', True) is None): + prod = None + else: + prod = prod * axis_size + known_num_splits.append(prod) + + for axis in range(ragged_spec.ragged_rank, 0, -1): + axis_size = ragged_spec.shape[axis] + if axis_size is None or (getattr(axis_size, 'value', True) is None): + num_splits = known_num_splits[axis-1] + if num_splits is not None: + num_splits = num_splits + 1 + splits = array_ops.placeholder( + ragged_spec.row_splits_dtype, [num_splits]) + result = ragged_tensor.RaggedTensor.from_row_splits( + result, splits, validate=False) + else: + rowlen = constant_op.constant(axis_size, ragged_spec.row_splits_dtype) + result = ragged_tensor.RaggedTensor.from_uniform_row_length( + result, rowlen, validate=False) + return result + + @property + def ragged_rank(self): + return self.type_spec.ragged_rank + +# Overload slicing +RaggedKerasTensor._overload_operator(ragged_tensor.RaggedTensor, '__getitem__') # pylint: disable=protected-access + +# Overload math ops +RaggedKerasTensor._overload_operator(ragged_tensor.RaggedTensor, '__add__') # pylint: disable=protected-access +RaggedKerasTensor._overload_operator(ragged_tensor.RaggedTensor, '__radd__') # pylint: disable=protected-access +RaggedKerasTensor._overload_operator(ragged_tensor.RaggedTensor, '__mul__') # pylint: disable=protected-access +RaggedKerasTensor._overload_operator(ragged_tensor.RaggedTensor, '__rmul__') # pylint: disable=protected-access + + +# TODO(b/161487382): +# Special-case user-registered symbolic objects (registered by the +# private `register_symbolic_tensor_type` method) by passing them between +# scratch graphs directly. +# This is needed to not break Tensorflow probability +# while they finish migrating to composite tensors. +class UserRegisteredSpec(type_spec_module.TypeSpec): + """TypeSpec to represent user-registered symbolic objects.""" + + def __init__(self, shape, dtype): + self.shape = shape + self._dtype = dtype + self.dtype = dtype + + def _component_specs(self): + raise NotImplementedError + + def _from_components(self, components): + raise NotImplementedError + + def _serialize(self): + raise NotImplementedError + + def _to_components(self, value): + raise NotImplementedError + + def value_type(self): + raise NotImplementedError + + +# TODO(b/161487382): +# Special-case user-registered symbolic objects (registered by the +# private `register_symbolic_tensor_type` method) by passing them between +# scratch graphs directly. +# This is needed to not break Tensorflow probability +# while they finish migrating to composite tensors. +class UserRegisteredTypeKerasTensor(KerasTensor): + """KerasTensor that represents legacy register_symbolic_tensor_type.""" + + def __init__(self, user_registered_symbolic_object): + x = user_registered_symbolic_object + self._user_registered_symbolic_object = x + type_spec = UserRegisteredSpec(x.shape, x.dtype) + name = getattr(x, 'name', None) + + super(UserRegisteredTypeKerasTensor, self).__init__(type_spec, name) + + @classmethod + def from_tensor(cls, tensor): + return cls(tensor) + + @classmethod + def from_type_spec(cls, type_spec, name=None): + raise NotImplementedError('You cannot instantiate a KerasTensor ' + 'directly from TypeSpec: %s' % type_spec) + + def _to_placeholder(self): + return self._user_registered_symbolic_object + + +class _KerasTensorIterator(object): + """Iterates over the leading dim of a KerasTensor. Performs 0 error checks.""" + + def __init__(self, tensor, dim0): + self._tensor = tensor + self._index = 0 + self._limit = dim0 + + def __iter__(self): + return self + + def __next__(self): + if self._index == self._limit: + raise StopIteration + result = self._tensor[self._index] + self._index += 1 + return result + + +# Specify the mappings of tensor class to KerasTensor class. +# This is specifically a list instead of a dict for now because +# 1. we do a check w/ isinstance because a key lookup based on class +# would miss subclasses +# 2. a list allows us to control lookup ordering +# We include tensor.Tensor -> KerasTensor in the first position as a fastpath, +# *and* include object -> KerasTensor at the end as a catch-all. +# We can re-visit these choices in the future as needed. +keras_tensor_classes = [ + (tensor_lib.Tensor, KerasTensor), + (sparse_tensor.SparseTensor, SparseKerasTensor), + (ragged_tensor.RaggedTensor, RaggedKerasTensor), + (object, KerasTensor) +] + + +def register_keras_tensor_specialization(cls, keras_tensor_subclass): + """Register a specialized KerasTensor subclass for a Tensor type.""" + # We always leave (object, KerasTensor) at the end as a generic fallback + keras_tensor_classes.insert(-1, (cls, keras_tensor_subclass)) + + +def keras_tensor_to_placeholder(x): + """Construct a graph placeholder to represent a KerasTensor when tracing.""" + if isinstance(x, KerasTensor): + return x._to_placeholder() # pylint: disable=protected-access + else: + return x + + +def keras_tensor_from_tensor(tensor): + """Convert a traced (composite)tensor to a representative KerasTensor.""" + # Create a specialized KerasTensor that supports instance methods, + # operators, and additional value inference if possible + keras_tensor_cls = None + for tensor_type, cls in keras_tensor_classes: + if isinstance(tensor, tensor_type): + keras_tensor_cls = cls + break + + out = keras_tensor_cls.from_tensor(tensor) + + if hasattr(tensor, '_keras_mask'): + out._keras_mask = keras_tensor_from_tensor(tensor._keras_mask) # pylint: disable=protected-access + return out + + +def keras_tensor_from_type_spec(type_spec, name=None): + """Convert a TypeSpec to a representative KerasTensor.""" + # Create a specialized KerasTensor that supports instance methods, + # operators, and additional value inference if possible + keras_tensor_cls = None + value_type = type_spec.value_type + for tensor_type, cls in keras_tensor_classes: + if issubclass(value_type, tensor_type): + keras_tensor_cls = cls + break + + return keras_tensor_cls.from_type_spec(type_spec, name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/node.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/node.py new file mode 100644 index 0000000000000000000000000000000000000000..c4d409a74d7d9663fc49442ce68c1eaea903eaac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/node.py @@ -0,0 +1,290 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=g-classes-have-attributes +"""Contains the `Node` class.""" + +import collections +import copy +import json +import numpy as np + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.saving.saved_model import json_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.util import nest + +_CONSTANT_VALUE = '_CONSTANT_VALUE' + + +class Node: + """A `Node` describes the connectivity between two layers. + + Each time a layer is connected to some new input, + a node is added to `layer._inbound_nodes`. + Each time the output of a layer is used by another layer, + a node is added to `layer._outbound_nodes`. + + Args: + layer: The Layer for the Layer.__call__ this node represents. + call_args: The positional arguments the Layer was called with. + call_kwargs: The keyword arguments the Layer was called with. + outputs: The outputs of the Layer.__call__ + """ + + def __init__(self, + layer, + call_args=None, + call_kwargs=None, + outputs=None): + call_args = [] if call_args is None else call_args + call_kwargs = {} if call_kwargs is None else call_kwargs + outputs = [] if outputs is None else outputs + + self.layer = layer + self.is_input = not call_args and not call_kwargs + + # These arguments are user-provided. Copy the structures here so that + # future user modifications do not affect the node's metadata. + # We copy using map_structure rather than python's shallow or deep copy, + # because the args can be data structures (so shallow copy is + # insufficient), but individual values might not support copy.copy + # or be too expensive to deep copy. + call_args = nest.map_structure(lambda t: t, call_args) + call_kwargs = nest.map_structure(lambda t: t, call_kwargs) + self.outputs = nest.map_structure(lambda t: t, outputs) + self.call_args = call_args + self.call_kwargs = call_kwargs + + # Cached for performance. + self._flat_arguments = nest.flatten((self.call_args, self.call_kwargs)) + # Used to avoid expensive `nest` operations in the most common case. + self._single_positional_tensor_passed = (not self.call_kwargs and len( + self.call_args) == 1 and tensor_util.is_tf_type(self.call_args[0])) + + if not ops.executing_eagerly_outside_functions(): + # Create TensorFlowOpLayers if needed (in TF1) + for obj in self._flat_arguments: + if (isinstance(obj, tensor_lib.Tensor) and + base_layer_utils.needs_keras_history( + obj, ignore_call_context=True)): + base_layer_utils.create_keras_history(obj) + + self._keras_inputs = [] + self._keras_inputs_ids_and_indices = [] + for i, ele in enumerate(self._flat_arguments): + if is_keras_tensor(ele): + self._keras_inputs.append(ele) + kt_id = str(id(ele)) + kt_index = i + self._keras_inputs_ids_and_indices.append((kt_id, kt_index)) + + # Wire up Node to Layers. + self.layer._inbound_nodes.append(self) + for kt in self.keras_inputs: + inbound_layer = kt._keras_history.layer + if inbound_layer is not None: # `None` for `Input` tensors. + inbound_layer._outbound_nodes.append(self) + + # Set metadata on outputs. + node_index = len(self.layer._inbound_nodes) - 1 + for i, tensor in enumerate(nest.flatten(outputs)): + tensor._keras_history = KerasHistory( + layer=layer, node_index=node_index, tensor_index=i) + + # Cached for performance. + self.flat_input_ids = [str(id(t)) for t in self._keras_inputs] + self.flat_output_ids = [str(id(t)) for t in nest.flatten(self.outputs)] + + @property + def keras_inputs(self): + """Tensors input to this node that can be traced back to a `keras.Input`.""" + return self._keras_inputs + + @property + def parent_nodes(self): + """Returns all the `Node`s whose output this node immediately depends on.""" + node_deps = [] + for kt in self.keras_inputs: + layer = kt._keras_history.layer + node_index = kt._keras_history.node_index + if layer is not None: # `None` for `Input` tensors. + node_deps.append(layer._inbound_nodes[node_index]) + return node_deps + + def iterate_inbound(self): + """Yields tuples representing the data inbound from other nodes. + + Yields: + tuples like: (inbound_layer, node_index, tensor_index, tensor). + """ + for kt in self.keras_inputs: + keras_history = kt._keras_history + layer = keras_history.layer + node_index = keras_history.node_index + tensor_index = keras_history.tensor_index + yield layer, node_index, tensor_index, kt + + def map_arguments(self, tensor_dict): + """Maps Keras Tensors to computed Tensors using `tensor_dict`.""" + if self._single_positional_tensor_passed: + # Performance optimization for most common case. + kt_id, _ = self._keras_inputs_ids_and_indices[0] + return (tensor_dict[kt_id].pop(),), {} + else: + flat_arguments = copy.copy(self._flat_arguments) + for kt_id, kt_index in self._keras_inputs_ids_and_indices: + flat_arguments[kt_index] = tensor_dict[kt_id].pop() + + args, kwargs = nest.pack_sequence_as((self.call_args, self.call_kwargs), + flat_arguments) + return args, kwargs + + def serialize(self, make_node_key, node_conversion_map): + """Serializes `Node` for Functional API's `get_config`.""" + # Serialization still special-cases first argument. + args, kwargs = self.call_args, self.call_kwargs + inputs, args, kwargs = self.layer._split_out_first_arg(args, kwargs) + + # Treat everything other than first argument as a kwarg. + arguments = dict(zip(self.layer._call_fn_args[1:], args)) + arguments.update(kwargs) + kwargs = arguments + + def _serialize_keras_tensor(t): + """Serializes a single Tensor passed to `call`.""" + if hasattr(t, '_keras_history'): + kh = t._keras_history + node_index = kh.node_index + node_key = make_node_key(kh.layer.name, node_index) + new_node_index = node_conversion_map.get(node_key, 0) + return [kh.layer.name, new_node_index, kh.tensor_index] + + if isinstance(t, np.ndarray): + return t.tolist() + + if isinstance(t, tensor_lib.Tensor): + return backend.get_value(t).tolist() + + return t + + kwargs = nest.map_structure(_serialize_keras_tensor, kwargs) + try: + json.dumps(kwargs, default=json_utils.get_json_type) + except TypeError: + kwarg_types = nest.map_structure(type, kwargs) + raise TypeError('Layer ' + self.layer.name + + ' was passed non-JSON-serializable arguments. ' + + 'Arguments had types: ' + + str(kwarg_types) + '. They cannot be serialized out ' + 'when saving the model.') + + # `kwargs` is added to each Tensor in the first arg. This should be + # changed in a future version of the serialization format. + def serialize_first_arg_tensor(t): + if is_keras_tensor(t): + kh = t._keras_history + node_index = kh.node_index + node_key = make_node_key(kh.layer.name, node_index) + new_node_index = node_conversion_map.get(node_key, 0) + data = [kh.layer.name, new_node_index, kh.tensor_index, kwargs] + else: + # If an element in the first call argument did not originate as a + # keras tensor and is a constant value, we save it using the format + # ['_CONSTANT_VALUE', -1, serializaed_tensor_or_python_constant] + # (potentially including serialized kwargs in an optional 4th argument + data = [_CONSTANT_VALUE, -1, _serialize_keras_tensor(t), kwargs] + return tf_utils.ListWrapper(data) + + data = nest.map_structure(serialize_first_arg_tensor, inputs) + if (not nest.is_nested(data) and + not self.layer._preserve_input_structure_in_config): + data = [data] + data = tf_utils.convert_inner_node_data(data) + return data + + ############################################################# + # Properties for Backwards compatibility. + # These only check the first input argument + # As nodes are internal, they may be removed in the future. + ############################################################# + + @property + def input_tensors(self): + if self.is_input: + return [self.outputs] # Used in `Layer.input`. + return self.call_args[0] + + @property + def output_tensors(self): + if self.is_input: + return [self.outputs] # Used in `Layer.input`. + return self.outputs + + @property + def input_shapes(self): + input_shapes = nest.map_structure(backend.int_shape, self.input_tensors) + if len(input_shapes) == 1 and not self.is_input: + return input_shapes[0] + return input_shapes + + @property + def output_shapes(self): + return nest.map_structure(backend.int_shape, self.output_tensors) + + @property + def outbound_layer(self): + return self.layer + + @property + def inbound_layers(self): + if self.is_input: + return [] + inbound_layers = nest.map_structure(lambda t: t._keras_history.layer, + self.call_args[0]) + return inbound_layers + + +class KerasHistory( + collections.namedtuple('KerasHistory', + ['layer', 'node_index', 'tensor_index'])): + """Tracks the Layer call that created a Tensor, for Keras Graph Networks. + + During construction of Keras Graph Networks, this metadata is added to + each Tensor produced as the output of a Layer, starting with an + `InputLayer`. This allows Keras to track how each Tensor was produced, and + this information is later retraced by the `keras.engine.Network` class to + reconstruct the Keras Graph Network. + + Attributes: + layer: The Layer that produced the Tensor. + node_index: The specific call to the Layer that produced this Tensor. Layers + can be called multiple times in order to share weights. A new node is + created every time a Layer is called. + tensor_index: The output index for this Tensor. Always zero if the Layer + that produced this Tensor only has one output. Nested structures of + Tensors are deterministically assigned an index via `nest.flatten`. + """ + # Added to maintain memory and performance characteristics of `namedtuple` + # while subclassing. + __slots__ = () + + +def is_keras_tensor(obj): + return hasattr(obj, '_keras_history') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/partial_batch_padding_handler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/partial_batch_padding_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9f431a15cbcd7de53a5c83e32ed67cdb0b91d8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/partial_batch_padding_handler.py @@ -0,0 +1,107 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility object to handler partial batches for TPUStrategy.""" +# pylint: disable=protected-access + +import numpy as np + +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest + + +class PartialBatchPaddingHandler(object): + """A container that holds info about partial batches for `predict()`.""" + + def __init__(self, output_shape): + self.padded_batch_size = 0 + self.padding_mask = array_ops.zeros(0) + self.output_shape = output_shape + + def get_real_batch_size(self, dataset_batch): + """Returns the number of elements in a potentially partial batch.""" + if isinstance(dataset_batch, (tuple, list)): + dataset_batch = dataset_batch[0] + + assert nest.flatten(dataset_batch) + + def _find_any_tensor(batch_features): + tensors = [ + x for x in nest.flatten(batch_features) if tensor_util.is_tf_type(x) + ] + if not tensors: + raise ValueError('Cannot find any Tensor in features dict.') + return tensors[0] + + return backend.cast(backend.shape(_find_any_tensor(dataset_batch))[0], + dtype='int64') + + def update_mask(self, padding_mask, dataset_batch): + """Calculate and cache the amount of padding required for a batch.""" + original_batch_size = self.get_real_batch_size(dataset_batch) + missing_count = self.padded_batch_size - original_batch_size + mask = backend.concatenate([array_ops.ones(original_batch_size), + array_ops.zeros(missing_count)], axis=0) + return backend.concatenate([padding_mask, mask], axis=0) + + def pad_batch(self, *dataset_batch_elements): + """Pads out the batch dimension of a tensor to the complete batch size.""" + def _pad(batch): + """Helper function to pad nested data within each batch elements.""" + padded_dict_batch = {} + if isinstance(batch, dict): + for key, value in batch.items(): + padded_dict_batch[key] = _pad(value) + return padded_dict_batch + + rank = len(batch.shape) + assert rank > 0 + missing_count = (self.padded_batch_size - + self.get_real_batch_size(batch)) + padding = backend.stack([[0, missing_count]] + [[0, 0]] * (rank - 1)) + return array_ops.pad(batch, padding, 'constant') + + if len(dataset_batch_elements) == 1: + return _pad(dataset_batch_elements[0]) + + batch_elements = [] + for batch_element in dataset_batch_elements: + batch_elements.append(_pad(batch_element)) + return tuple(batch_elements) + + def apply_mask(self, prediction_result): + """Removes prediction output that corresponds to padded input.""" + padding_mask = backend.get_value(self.padding_mask) + assert len(padding_mask.shape) == 1 + + if len(self.output_shape) == 1: + prediction = np.take(prediction_result, + np.nonzero( + padding_mask[:len(prediction_result)]), + axis=0) + if prediction.shape[0] == 1: + prediction = np.squeeze(prediction, axis=0) + return prediction + + else: + predictions = [] + for i in range(len(self.output_shape)): + prediction = prediction_result[i] + prediction = np.take(prediction, np.nonzero( + padding_mask[:len(prediction)]), axis=0) + predictions.append(np.squeeze(prediction)) + + return predictions diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/saving.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/saving.py new file mode 100644 index 0000000000000000000000000000000000000000..ff32c3f792bcbbce756b1e09d4f772a352accc4b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/saving.py @@ -0,0 +1,21 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Model saving utilities. + +Everything has been moved to keras/saving/. This file will be deleted soon. +""" + +from tensorflow.python.keras.saving import * # pylint: disable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/sequential.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..0f46e17d37837de81bc55686f3ec00b809f49533 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/sequential.py @@ -0,0 +1,571 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Home of the `Sequential` model.""" + +import copy +import warnings + +from tensorflow.python import tf2 +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import layers as layer_module +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import functional +from tensorflow.python.keras.engine import input_layer +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.saving.saved_model import model_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.module import module +from tensorflow.python.ops.numpy_ops import np_arrays +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest + + +SINGLE_LAYER_OUTPUT_ERROR_MSG = ('All layers in a Sequential model should have ' + 'a single output tensor. For multi-output ' + 'layers, use the functional API.') + + +class Sequential(functional.Functional): + """`Sequential` groups a linear stack of layers into a `tf.keras.Model`. + + `Sequential` provides training and inference features on this model. + + Examples: + + >>> # Optionally, the first layer can receive an `input_shape` argument: + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) + >>> # Afterwards, we do automatic shape inference: + >>> model.add(tf.keras.layers.Dense(4)) + + >>> # This is identical to the following: + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.Input(shape=(16,))) + >>> model.add(tf.keras.layers.Dense(8)) + + >>> # Note that you can also omit the `input_shape` argument. + >>> # In that case the model doesn't have any weights until the first call + >>> # to a training/evaluation method (since it isn't yet built): + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Dense(8)) + >>> model.add(tf.keras.layers.Dense(4)) + >>> # model.weights not created yet + + >>> # Whereas if you specify the input shape, the model gets built + >>> # continuously as you are adding layers: + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) + >>> model.add(tf.keras.layers.Dense(4)) + >>> len(model.weights) + 4 + + >>> # When using the delayed-build pattern (no input shape specified), you can + >>> # choose to manually build your model by calling + >>> # `build(batch_input_shape)`: + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Dense(8)) + >>> model.add(tf.keras.layers.Dense(4)) + >>> model.build((None, 16)) + >>> len(model.weights) + 4 + + ```python + # Note that when using the delayed-build pattern (no input shape specified), + # the model gets built the first time you call `fit`, `eval`, or `predict`, + # or the first time you call the model on some input data. + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(8)) + model.add(tf.keras.layers.Dense(1)) + model.compile(optimizer='sgd', loss='mse') + # This builds the model for the first time: + model.fit(x, y, batch_size=32, epochs=10) + ``` + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, layers=None, name=None): + """Creates a `Sequential` model instance. + + Args: + layers: Optional list of layers to add to the model. + name: Optional name for the model. + """ + # Skip the init in FunctionalModel since model doesn't have input/output yet + super(functional.Functional, self).__init__( # pylint: disable=bad-super-call + name=name, autocast=False) + self.supports_masking = True + self._compute_output_and_mask_jointly = True + self._auto_track_sub_layers = False + self._inferred_input_shape = None + self._has_explicit_input_shape = False + self._input_dtype = None + self._layer_call_argspecs = {} + self._created_nodes = set() + # Flag that indicate whether the sequential network topology has been + # created. It is false when there isn't any layer, or the layers doesn't + # have input shape. + self._graph_initialized = False + + # Unfortunately some Sequential models using custom layers or FeatureColumn + # layers have multiple inputs. This is fundamentally incompatible with + # most of the Sequential API, and we have to disable a number of features + # for such models. + self._use_legacy_deferred_behavior = False + + # Add to the model any layers passed to the constructor. + if layers: + if not isinstance(layers, (list, tuple)): + layers = [layers] + for layer in layers: + self.add(layer) + + @property + def layers(self): + # Historically, `sequential.layers` only returns layers that were added + # via `add`, and omits the auto-generated `InputLayer` that comes at the + # bottom of the stack. + # `Trackable` manages the `_layers` attributes and does filtering + # over it. + layers = super(Sequential, self).layers + if layers and isinstance(layers[0], input_layer.InputLayer): + return layers[1:] + return layers[:] + + @trackable.no_automatic_dependency_tracking + def add(self, layer): + """Adds a layer instance on top of the layer stack. + + Args: + layer: layer instance. + + Raises: + TypeError: If `layer` is not a layer instance. + ValueError: In case the `layer` argument does not + know its input shape. + ValueError: In case the `layer` argument has + multiple output tensors, or is already connected + somewhere else (forbidden in `Sequential` models). + """ + # If we are passed a Keras tensor created by keras.Input(), we can extract + # the input layer from its keras history and use that without any loss of + # generality. + if hasattr(layer, '_keras_history'): + origin_layer = layer._keras_history[0] + if isinstance(origin_layer, input_layer.InputLayer): + layer = origin_layer + logging.warning( + 'Please add `keras.layers.InputLayer` instead of `keras.Input` to ' + 'Sequential model. `keras.Input` is intended to be used by ' + 'Functional model.') + + if isinstance(layer, module.Module): + if not isinstance(layer, base_layer.Layer): + layer = functional.ModuleWrapper(layer) + else: + raise TypeError('The added layer must be ' + 'an instance of class Layer. ' + 'Found: ' + str(layer)) + + tf_utils.assert_no_legacy_layers([layer]) + if not self._is_layer_name_unique(layer): + raise ValueError('All layers added to a Sequential model ' + 'should have unique names. Name "%s" is already the name' + ' of a layer in this model. Update the `name` argument ' + 'to pass a unique name.' % (layer.name,)) + + self.built = False + set_inputs = False + self._maybe_create_attribute('_self_tracked_trackables', []) + if not self._self_tracked_trackables: + if isinstance(layer, input_layer.InputLayer): + # Case where the user passes an Input or InputLayer layer via `add`. + set_inputs = True + else: + batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer) + if batch_shape: + # Instantiate an input layer. + x = input_layer.Input( + batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input') + # This will build the current layer + # and create the node connecting the current layer + # to the input layer we just created. + layer(x) + set_inputs = True + + if set_inputs: + outputs = nest.flatten(layer._inbound_nodes[-1].outputs) + if len(outputs) != 1: + raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) + self.outputs = outputs + self.inputs = layer_utils.get_source_inputs(self.outputs[0]) + self.built = True + self._has_explicit_input_shape = True + + elif self.outputs: + # If the model is being built continuously on top of an input layer: + # refresh its output. + output_tensor = layer(self.outputs[0]) + if len(nest.flatten(output_tensor)) != 1: + raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) + self.outputs = [output_tensor] + self.built = True + + if set_inputs or self._graph_initialized: + self._init_graph_network(self.inputs, self.outputs) + self._graph_initialized = True + else: + self._self_tracked_trackables.append(layer) + self._handle_deferred_layer_dependencies([layer]) + + self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call) + + @trackable.no_automatic_dependency_tracking + def pop(self): + """Removes the last layer in the model. + + Raises: + TypeError: if there are no layers in the model. + """ + if not self.layers: + raise TypeError('There are no layers in the model.') + + layer = self._self_tracked_trackables.pop() + self._layer_call_argspecs.pop(layer) + if not self.layers: + self.outputs = None + self.inputs = None + self.built = False + self._inferred_input_shape = None + self._has_explicit_input_shape = False + self._graph_initialized = False + elif self._graph_initialized: + self.layers[-1]._outbound_nodes = [] + self.outputs = [self.layers[-1].output] + self._init_graph_network(self.inputs, self.outputs) + self.built = True + + @trackable.no_automatic_dependency_tracking + def _build_graph_network_for_inferred_shape(self, + input_shape, + input_dtype=None): + if input_shape is None or not self.layers: + return + if not tf2.enabled() or not ops.executing_eagerly_outside_functions(): + # This behavior is disabled in V1 or when eager execution is disabled. + return + if (not self._has_explicit_input_shape and + not self._use_legacy_deferred_behavior): + # Determine whether the input shape is novel, i.e. whether the model + # should be rebuilt. + input_shape = tuple(input_shape) + if self._inferred_input_shape is None: + new_shape = input_shape + else: + new_shape = relax_input_shape(self._inferred_input_shape, input_shape) + if (new_shape is not None and new_shape != self._inferred_input_shape): + # A novel shape has been received: we need to rebuild the model. + # In case we are inside a graph function, we step out of it. + with ops.init_scope(): + inputs = input_layer.Input( + batch_shape=new_shape, + dtype=input_dtype, + name=self.layers[0].name + '_input') + layer_input = inputs + created_nodes = set() + for layer in self.layers: + # Clear nodes previously created via this method. This prevents + # node accumulation and ensures that e.g. `layer.output` is + # always connected to `model.inputs` + # (this is important e.g. for the feature extraction use case). + # We don't just do `layer._inbound_nodes = []` in order + # not to break shared layers added to Sequential models (which is + # technically illegal as per the `add()` docstring, + # but wasn't previously disabled). + clear_previously_created_nodes(layer, self._created_nodes) + try: + # Create Functional API connection by calling the current layer + layer_output = layer(layer_input) + except: # pylint:disable=bare-except + # Functional API calls may fail for a number of reasons: + # 1) The layer may be buggy. In this case it will be easier for + # the user to debug if we fail on the first call on concrete data, + # instead of our own call on a symbolic input. + # 2) The layer is dynamic (graph-incompatible) and hasn't + # overridden `compute_output_shape`. In this case, it is + # impossible to build a graph network. + # 3) The layer is otherwise incompatible with the Functional API + # (e.g. this is the case for some probabilistic layers that rely + # on hacks and that do not return tensors). + # In all these cases, we should avoid creating a graph network + # (or we simply can't). + self._use_legacy_deferred_behavior = True + return + if len(nest.flatten(layer_output)) != 1: + raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) + # Keep track of nodes just created above + track_nodes_created_by_last_call(layer, created_nodes) + layer_input = layer_output + outputs = layer_output + self._created_nodes = created_nodes + try: + # Initialize a graph Network. This call will never fail for + # a stack of valid Keras layers. + # However some users have layers that are fundamentally incompatible + # with the Functional API, which do not return tensors. In this + # case, we fall back to the legacy deferred behavior. + # TODO(fchollet): consider raising here, as we should not be + # supporting such layers. + self._init_graph_network(inputs, outputs) + self._graph_initialized = True + except: # pylint:disable=bare-except + self._use_legacy_deferred_behavior = True + self._inferred_input_shape = new_shape + + @generic_utils.default + def build(self, input_shape=None): + if self._graph_initialized: + self._init_graph_network(self.inputs, self.outputs) + else: + if input_shape is None: + raise ValueError('You must provide an `input_shape` argument.') + self._build_graph_network_for_inferred_shape(input_shape) + if not self.built: + input_shape = tuple(input_shape) + self._build_input_shape = input_shape + super(Sequential, self).build(input_shape) + self.built = True + + def call(self, inputs, training=None, mask=None): # pylint: disable=redefined-outer-name + # If applicable, update the static input shape of the model. + if not self._has_explicit_input_shape: + if not tensor_util.is_tf_type(inputs) and not isinstance( + inputs, np_arrays.ndarray): + # This is a Sequential with mutiple inputs. This is technically an + # invalid use case of Sequential, but we tolerate it for backwards + # compatibility. + self._use_legacy_deferred_behavior = True + self._build_input_shape = nest.map_structure(_get_shape_tuple, inputs) + if tf2.enabled(): + logging.warning('Layers in a Sequential model should only have a ' + 'single input tensor, but we receive a %s input: %s' + '\nConsider rewriting this model with the Functional ' + 'API.' % (type(inputs), inputs)) + else: + self._build_graph_network_for_inferred_shape(inputs.shape, inputs.dtype) + + if self._graph_initialized: + if not self.built: + self._init_graph_network(self.inputs, self.outputs) + return super(Sequential, self).call(inputs, training=training, mask=mask) + + outputs = inputs # handle the corner case where self.layers is empty + for layer in self.layers: + # During each iteration, `inputs` are the inputs to `layer`, and `outputs` + # are the outputs of `layer` applied to `inputs`. At the end of each + # iteration `inputs` is set to `outputs` to prepare for the next layer. + kwargs = {} + argspec = self._layer_call_argspecs[layer].args + if 'mask' in argspec: + kwargs['mask'] = mask + if 'training' in argspec: + kwargs['training'] = training + + outputs = layer(inputs, **kwargs) + + if len(nest.flatten(outputs)) != 1: + raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) + # `outputs` will be the inputs to the next layer. + inputs = outputs + mask = getattr(outputs, '_keras_mask', None) + return outputs + + def compute_output_shape(self, input_shape): + shape = input_shape + for layer in self.layers: + shape = layer.compute_output_shape(shape) + return shape + + def compute_mask(self, inputs, mask): + # TODO(omalleyt): b/123540974 This function is not really safe to call + # by itself because it will duplicate any updates and losses in graph + # mode by `call`ing the Layers again. + outputs = self.call(inputs, mask=mask) # pylint: disable=unexpected-keyword-arg + return getattr(outputs, '_keras_mask', None) + + def predict_proba(self, x, batch_size=32, verbose=0): + """Generates class probability predictions for the input samples. + + The input samples are processed batch by batch. + + Args: + x: input data, as a Numpy array or list of Numpy arrays + (if the model has multiple inputs). + batch_size: integer. + verbose: verbosity mode, 0 or 1. + + Returns: + A Numpy array of probability predictions. + """ + warnings.warn('`model.predict_proba()` is deprecated and ' + 'will be removed after 2021-01-01. ' + 'Please use `model.predict()` instead.') + preds = self.predict(x, batch_size, verbose) + if preds.min() < 0. or preds.max() > 1.: + logging.warning('Network returning invalid probability values. ' + 'The last layer might not normalize predictions ' + 'into probabilities ' + '(like softmax or sigmoid would).') + return preds + + def predict_classes(self, x, batch_size=32, verbose=0): + """Generate class predictions for the input samples. + + The input samples are processed batch by batch. + + Args: + x: input data, as a Numpy array or list of Numpy arrays + (if the model has multiple inputs). + batch_size: integer. + verbose: verbosity mode, 0 or 1. + + Returns: + A numpy array of class predictions. + """ + warnings.warn('`model.predict_classes()` is deprecated and ' + 'will be removed after 2021-01-01. ' + 'Please use instead:' + '* `np.argmax(model.predict(x), axis=-1)`, ' + ' if your model does multi-class classification ' + ' (e.g. if it uses a `softmax` last-layer activation).' + '* `(model.predict(x) > 0.5).astype("int32")`, ' + ' if your model does binary classification ' + ' (e.g. if it uses a `sigmoid` last-layer activation).') + proba = self.predict(x, batch_size=batch_size, verbose=verbose) + if proba.shape[-1] > 1: + return proba.argmax(axis=-1) + else: + return (proba > 0.5).astype('int32') + + def get_config(self): + layer_configs = [] + for layer in super(Sequential, self).layers: + # `super().layers` include the InputLayer if available (it is filtered out + # of `self.layers`). Note that `self._self_tracked_trackables` is managed + # by the tracking infrastructure and should not be used. + layer_configs.append(generic_utils.serialize_keras_object(layer)) + config = { + 'name': self.name, + 'layers': copy.deepcopy(layer_configs) + } + if not self._is_graph_network and self._build_input_shape is not None: + config['build_input_shape'] = self._build_input_shape + return config + + @classmethod + def from_config(cls, config, custom_objects=None): + if 'name' in config: + name = config['name'] + build_input_shape = config.get('build_input_shape') + layer_configs = config['layers'] + else: + name = None + build_input_shape = None + layer_configs = config + model = cls(name=name) + for layer_config in layer_configs: + layer = layer_module.deserialize(layer_config, + custom_objects=custom_objects) + model.add(layer) + if (not model.inputs and build_input_shape and + isinstance(build_input_shape, (tuple, list))): + model.build(build_input_shape) + return model + + @property + def input_spec(self): + if hasattr(self, '_manual_input_spec'): + return self._manual_input_spec + if self.layers and hasattr(self.layers[0], 'input_spec'): + return self.layers[0].input_spec + return None + + @input_spec.setter + def input_spec(self, value): + self._manual_input_spec = value + + @property + def _trackable_saved_model_saver(self): + return model_serialization.SequentialSavedModelSaver(self) + + def _is_layer_name_unique(self, layer): + for ref_layer in self.layers: + if layer.name == ref_layer.name and ref_layer is not layer: + return False + return True + + def _assert_weights_created(self): + if self._graph_initialized: + return + # When the graph has not been initialized, use the Model's implementation to + # to check if the weights has been created. + super(functional.Functional, self)._assert_weights_created() # pylint: disable=bad-super-call + + +def _get_shape_tuple(t): + if hasattr(t, 'shape'): + shape = t.shape + if isinstance(shape, tuple): + return shape + if shape.rank is not None: + return tuple(shape.as_list()) + return None + return None + + +def relax_input_shape(shape_1, shape_2): + if shape_1 is None or shape_2 is None: + return None + if len(shape_1) != len(shape_2): + return None + return tuple(None if d1 != d2 else d1 for d1, d2 in zip(shape_1, shape_2)) + + +def clear_previously_created_nodes(layer, created_nodes): + """Remove nodes from `created_nodes` from the layer's inbound_nodes.""" + for node in layer._inbound_nodes: + prev_layers = node.inbound_layers + for prev_layer in nest.flatten(prev_layers): + prev_layer._outbound_nodes = [ + n for n in prev_layer._outbound_nodes + if n not in created_nodes] + layer._inbound_nodes = [ + n for n in layer._inbound_nodes if n not in created_nodes] + + +def track_nodes_created_by_last_call(layer, created_nodes): + """Adds to `created_nodes` the nodes created by the last call to `layer`.""" + if not layer._inbound_nodes: + return + created_nodes.add(layer._inbound_nodes[-1]) + prev_layers = layer._inbound_nodes[-1].inbound_layers + for prev_layer in nest.flatten(prev_layers): + if prev_layer._outbound_nodes: + created_nodes.add(prev_layer._outbound_nodes[-1]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training.py new file mode 100644 index 0000000000000000000000000000000000000000..1e94ca45aef0d13162032e15ea0a7228d7fa5298 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training.py @@ -0,0 +1,2998 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training-related part of the Keras engine.""" + +import copy +import itertools +import json +import os +import warnings +import weakref + +from tensorflow.python.autograph.lang import directives +from tensorflow.python.checkpoint import checkpoint as trackable_utils +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import values as ds_values +from tensorflow.python.distribute.coordinator import cluster_coordinator +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import errors +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks as callbacks_module +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras import optimizers +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import compile_utils +from tensorflow.python.keras.engine import data_adapter +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.mixed_precision import loss_scale_optimizer as lso +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.saving import hdf5_format +from tensorflow.python.keras.saving import save +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import json_utils +from tensorflow.python.keras.saving.saved_model import model_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite +from tensorflow.python.keras.utils.io_utils import path_to_string +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace +from tensorflow.python.saved_model import constants as sm_constants +from tensorflow.python.saved_model import loader_impl as sm_loader +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.tools.docs import doc_controls + + +# pylint: disable=g-import-not-at-top +try: + import h5py +except ImportError: + h5py = None +# pylint: enable=g-import-not-at-top + + +def disable_multi_worker(method): + """Decorator that disallows multi-worker use of `method`.""" + + def _method_wrapper(self, *args, **kwargs): + if self._in_multi_worker_mode(): # pylint: disable=protected-access + raise ValueError('{} is not supported in multi-worker mode.'.format( + method.__name__)) + return method(self, *args, **kwargs) + + return tf_decorator.make_decorator( + target=method, decorator_func=_method_wrapper) + + +def inject_functional_model_class(cls): + """Inject `Functional` into the hierarchy of this class if needed.""" + from tensorflow.python.keras.engine import functional # pylint: disable=g-import-not-at-top + from tensorflow.python.keras.engine import training_v1 # pylint: disable=g-import-not-at-top + if cls == Model or cls == training_v1.Model: + return functional.Functional + # In case there is any multiple inheritance, we stop injecting the + # class if keras model is not in its class hierarchy. + if cls == object: + return object + + cls.__bases__ = tuple(inject_functional_model_class(base) + for base in cls.__bases__) + # Trigger any `__new__` class swapping that needed to happen on `Functional` + # but did not because functional was not in the class hierarchy. + cls.__new__(cls) + + return cls + + +def is_functional_model_init_params(args, kwargs): + return (len(args) == 2 or + len(args) == 1 and 'outputs' in kwargs or + 'inputs' in kwargs and 'outputs' in kwargs) + + +class Model(base_layer.Layer, version_utils.ModelVersionSelector): + """`Model` groups layers into an object with training and inference features. + + Args: + inputs: The input(s) of the model: a `keras.Input` object or list of + `keras.Input` objects. + outputs: The output(s) of the model. See Functional API example below. + name: String, the name of the model. + + There are two ways to instantiate a `Model`: + + 1 - With the "Functional API", where you start from `Input`, + you chain layer calls to specify the model's forward pass, + and finally you create your model from inputs and outputs: + + ```python + import tensorflow as tf + + inputs = tf.keras.Input(shape=(3,)) + x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) + outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) + model = tf.keras.Model(inputs=inputs, outputs=outputs) + ``` + + Note: Only dicts, lists, and tuples of input tensors are supported. Nested + inputs are not supported (e.g. lists of list or dicts of dict). + + 2 - By subclassing the `Model` class: in that case, you should define your + layers in `__init__` and you should implement the model's forward pass + in `call`. + + ```python + import tensorflow as tf + + class MyModel(tf.keras.Model): + + def __init__(self): + super(MyModel, self).__init__() + self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) + self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) + + def call(self, inputs): + x = self.dense1(inputs) + return self.dense2(x) + + model = MyModel() + ``` + + If you subclass `Model`, you can optionally have + a `training` argument (boolean) in `call`, which you can use to specify + a different behavior in training and inference: + + ```python + import tensorflow as tf + + class MyModel(tf.keras.Model): + + def __init__(self): + super(MyModel, self).__init__() + self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) + self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) + self.dropout = tf.keras.layers.Dropout(0.5) + + def call(self, inputs, training=False): + x = self.dense1(inputs) + if training: + x = self.dropout(x, training=training) + return self.dense2(x) + + model = MyModel() + ``` + + Once the model is created, you can config the model with losses and metrics + with `model.compile()`, train the model with `model.fit()`, or use the model + to do prediction with `model.predict()`. + """ + _TF_MODULE_IGNORED_PROPERTIES = frozenset( + itertools.chain(('_train_counter', '_test_counter', '_predict_counter', + '_steps_per_execution'), + base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES)) # pylint: disable=protected-access + + def __new__(cls, *args, **kwargs): + # Signature detection + if is_functional_model_init_params(args, kwargs) and cls == Model: + # Functional model + from tensorflow.python.keras.engine import functional # pylint: disable=g-import-not-at-top + return functional.Functional(skip_init=True, *args, **kwargs) + else: + return super(Model, cls).__new__(cls, *args, **kwargs) + + @trackable.no_automatic_dependency_tracking + def __init__(self, *args, **kwargs): + self._is_model_for_instrumentation = True + + # Special case for Subclassed Functional Model, which we couldn't detect + # when __new__ is called. We only realize it is a functional model when it + # calls super.__init__ with input and output tensor. + from tensorflow.python.keras.engine import functional # pylint: disable=g-import-not-at-top + if (is_functional_model_init_params(args, kwargs) and + not isinstance(self, functional.Functional)): + # Filter the kwargs for multiple inheritance. + supported_kwargs = ['inputs', 'outputs', 'name', 'trainable', 'skip_init'] + model_kwargs = {k: kwargs[k] for k in kwargs if k in supported_kwargs} + other_kwargs = {k: kwargs[k] for k in kwargs if k not in supported_kwargs} + inject_functional_model_class(self.__class__) + functional.Functional.__init__(self, *args, **model_kwargs) + + # In case there is any multiple inheritance here, we need to call the + # __init__ for any class that appears after the Functional class. + clz_to_init = [] + found_functional_class = False + for clz in self.__class__.__bases__: + if issubclass(clz, functional.Functional): + found_functional_class = True + continue + if found_functional_class: + clz_to_init.append(clz) + + if clz_to_init: + for clz in clz_to_init: + clz.__init__(self, *args, **other_kwargs) + elif other_kwargs: + # In case there are unused kwargs, we should raise an error to user, in + # case they have a typo in the param name. + raise TypeError( + 'The following keyword arguments aren\'t supported: {}'.format( + other_kwargs)) + return + + # The following are implemented as property functions: + # self.trainable_weights + # self.non_trainable_weights + # `inputs` / `outputs` will only appear in kwargs if either are misspelled. + generic_utils.validate_kwargs(kwargs, { + 'trainable', 'dtype', 'dynamic', 'name', 'autocast', 'inputs', 'outputs' + }) + super(Model, self).__init__(**kwargs) + # By default, Model is a subclass model, which is not in graph network. + self._is_graph_network = False + + self.inputs = None + self.outputs = None + self.input_names = None + self.output_names = None + # stop_training is used by callback to stop training when error happens + self.stop_training = False + self.history = None + # These objects are used in the default `Model.compile`. They are not + # guaranteed to be set after `Model.compile` is called, as users can + # override compile with custom logic. + self.compiled_loss = None + self.compiled_metrics = None + + # This is True for Sequential networks and Functional networks. + self._compute_output_and_mask_jointly = False + + # Don't reset compilation if already done. This may occur if calling + # `__init__` (or `_init_graph_network`) on an already-compiled model + # such as a Sequential model. Sequential models may need to rebuild + # themselves after compilation. + self._maybe_create_attribute('_is_compiled', False) + self._maybe_create_attribute('optimizer', None) + + # Model must be created under scope of DistStrat it will be trained with. + if distribute_lib.has_strategy(): + self._distribution_strategy = distribute_lib.get_strategy() + else: + self._distribution_strategy = None + + self._cluster_coordinator = None + + # Defaults to value of `tf.config.experimental_functions_run_eagerly`. + self._run_eagerly = None + # Initialize cache attrs. + self._reset_compile_cache() + + # Fault-tolerance handler. Set in `ModelCheckpoint`. + self._training_state = None + self._saved_model_inputs_spec = None + self._checkpoint = trackable_utils.Checkpoint(root=weakref.ref(self)) + + self._steps_per_execution = None + + self._init_batch_counters() + self._base_model_initialized = True + + @trackable.no_automatic_dependency_tracking + def _init_batch_counters(self): + # Untracked Variables, used to keep track of mini-batches seen in `fit`, + # `evaluate`, and `predict`. + agg = variables.VariableAggregationV2.ONLY_FIRST_REPLICA + self._train_counter = variables.Variable(0, dtype='int64', aggregation=agg) + self._test_counter = variables.Variable(0, dtype='int64', aggregation=agg) + self._predict_counter = variables.Variable( + 0, dtype='int64', aggregation=agg) + + def __setattr__(self, name, value): + if not getattr(self, '_self_setattr_tracking', True): + super(Model, self).__setattr__(name, value) + return + + if all( + isinstance(v, (base_layer.Layer, variables.Variable)) or + base_layer_utils.has_weights(v) for v in nest.flatten(value)): + try: + self._base_model_initialized + except AttributeError: + raise RuntimeError( + 'It looks like you are subclassing `Model` and you ' + 'forgot to call `super().__init__()`.' + ' Always start with this line.') + + super(Model, self).__setattr__(name, value) + + @generic_utils.default + def build(self, input_shape): + """Builds the model based on input shapes received. + + This is to be used for subclassed models, which do not know at instantiation + time what their inputs look like. + + This method only exists for users who want to call `model.build()` in a + standalone way (as a substitute for calling the model on real data to + build it). It will never be called by the framework (and thus it will + never throw unexpected errors in an unrelated workflow). + + Args: + input_shape: Single tuple, TensorShape, or list/dict of shapes, where + shapes are tuples, integers, or TensorShapes. + + Raises: + ValueError: + 1. In case of invalid user-provided data (not of type tuple, + list, TensorShape, or dict). + 2. If the model requires call arguments that are agnostic + to the input shapes (positional or kwarg in call signature). + 3. If not all layers were properly built. + 4. If float type inputs are not supported within the layers. + + In each of these cases, the user should build their model by calling it + on real tensor data. + """ + if self._is_graph_network: + super(Model, self).build(input_shape) + return + + if input_shape is None: + raise ValueError('Input shape must be defined when calling build on a ' + 'model subclass network.') + valid_types = (tuple, list, tensor_shape.TensorShape, dict) + if not isinstance(input_shape, valid_types): + raise ValueError('Specified input shape is not one of the valid types. ' + 'Please specify a batch input shape of type tuple or ' + 'list of input shapes. User provided ' + 'input type: {}'.format(type(input_shape))) + + if input_shape and not self.inputs: + # We create placeholders for the `None`s in the shape and build the model + # in a Graph. Since tf.Variable is compatible with both eager execution + # and graph building, the variables created after building the model in + # a Graph are still valid when executing eagerly. + if context.executing_eagerly(): + graph = func_graph.FuncGraph('build_graph') + else: + graph = backend.get_graph() + with graph.as_default(): + if (isinstance(input_shape, list) and + all(d is None or isinstance(d, int) for d in input_shape)): + input_shape = tuple(input_shape) + if isinstance(input_shape, list): + x = [base_layer_utils.generate_placeholders_from_shape(shape) + for shape in input_shape] + elif isinstance(input_shape, dict): + x = { + k: base_layer_utils.generate_placeholders_from_shape(shape) + for k, shape in input_shape.items() + } + else: + x = base_layer_utils.generate_placeholders_from_shape(input_shape) + + kwargs = {} + call_signature = self._call_full_argspec + call_args = call_signature.args + # Exclude `self`, `inputs`, and any argument with a default value. + if len(call_args) > 2: + if call_signature.defaults: + call_args = call_args[2:-len(call_signature.defaults)] + else: + call_args = call_args[2:] + for arg in call_args: + if arg == 'training': + # Case where `training` is a positional arg with no default. + kwargs['training'] = False + else: + # Has invalid call signature with unknown positional arguments. + raise ValueError( + 'Currently, you cannot build your model if it has ' + 'positional or keyword arguments that are not ' + 'inputs to the model, but are required for its ' + '`call` method. Instead, in order to instantiate ' + 'and build your model, `call` your model on real ' + 'tensor data with all expected call arguments.') + elif len(call_args) < 2: + # Signature without `inputs`. + raise ValueError('You can only call `build` on a model if its `call` ' + 'method accepts an `inputs` argument.') + try: + self.call(x, **kwargs) + except (errors.InvalidArgumentError, TypeError): + raise ValueError('You cannot build your model by calling `build` ' + 'if your layers do not support float type inputs. ' + 'Instead, in order to instantiate and build your ' + 'model, `call` your model on real tensor data (of ' + 'the correct dtype).') + super(Model, self).build(input_shape) + + @doc_controls.doc_in_current_and_subclasses + def call(self, inputs, training=None, mask=None): + """Calls the model on new inputs. + + In this case `call` just reapplies + all ops in the graph to the new inputs + (e.g. build a new computational graph from the provided inputs). + + Note: This method should not be called directly. It is only meant to be + overridden when subclassing `tf.keras.Model`. + To call a model on an input, always use the `__call__` method, + i.e. `model(inputs)`, which relies on the underlying `call` method. + + Args: + inputs: Input tensor, or dict/list/tuple of input tensors. + training: Boolean or boolean scalar tensor, indicating whether to run + the `Network` in training mode or inference mode. + mask: A mask or list of masks. A mask can be + either a tensor or None (no mask). + + Returns: + A tensor if there is a single output, or + a list of tensors if there are more than one outputs. + """ + raise NotImplementedError('When subclassing the `Model` class, you should ' + 'implement a `call` method.') + + def compile(self, + optimizer='rmsprop', + loss=None, + metrics=None, + loss_weights=None, + weighted_metrics=None, + run_eagerly=None, + steps_per_execution=None, + **kwargs): + """Configures the model for training. + + Args: + optimizer: String (name of optimizer) or optimizer instance. See + `tf.keras.optimizers`. + loss: String (name of objective function), objective function or + `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective + function is any callable with the signature `loss = fn(y_true, + y_pred)`, where y_true = ground truth values with shape = + `[batch_size, d0, .. dN]`, except sparse loss functions such as sparse + categorical crossentropy where shape = `[batch_size, d0, .. dN-1]`. + y_pred = predicted values with shape = `[batch_size, d0, .. dN]`. It + returns a weighted loss float tensor. If a custom `Loss` instance is + used and reduction is set to `None`, return value has the shape + `[batch_size, d0, .. dN-1]` i.e. per-sample or per-timestep loss + values; otherwise, it is a scalar. If the model has multiple outputs, + you can use a different loss on each output by passing a dictionary + or a list of losses. The loss value that will be minimized by the + model will then be the sum of all individual losses, unless + `loss_weights` is specified. + metrics: List of metrics to be evaluated by the model during training + and testing. Each of this can be a string (name of a built-in + function), function or a `tf.keras.metrics.Metric` instance. See + `tf.keras.metrics`. Typically you will use `metrics=['accuracy']`. A + function is any callable with the signature `result = fn(y_true, + y_pred)`. To specify different metrics for different outputs of a + multi-output model, you could also pass a dictionary, such as + `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`. + You can also pass a list to specify a metric or a list of metrics + for each output, such as `metrics=[['accuracy'], ['accuracy', 'mse']]` + or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the + strings 'accuracy' or 'acc', we convert this to one of + `tf.keras.metrics.BinaryAccuracy`, + `tf.keras.metrics.CategoricalAccuracy`, + `tf.keras.metrics.SparseCategoricalAccuracy` based on the loss + function used and the model output shape. We do a similar + conversion for the strings 'crossentropy' and 'ce' as well. + loss_weights: Optional list or dictionary specifying scalar coefficients + (Python floats) to weight the loss contributions of different model + outputs. The loss value that will be minimized by the model will then + be the *weighted sum* of all individual losses, weighted by the + `loss_weights` coefficients. + If a list, it is expected to have a 1:1 mapping to the model's + outputs. If a dict, it is expected to map output names (strings) + to scalar coefficients. + weighted_metrics: List of metrics to be evaluated and weighted by + `sample_weight` or `class_weight` during training and testing. + run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s + logic will not be wrapped in a `tf.function`. Recommended to leave + this as `None` unless your `Model` cannot be run inside a + `tf.function`. `run_eagerly=True` is not supported when using + `tf.distribute.experimental.ParameterServerStrategy`. + steps_per_execution: Int. Defaults to 1. The number of batches to + run during each `tf.function` call. Running multiple batches + inside a single `tf.function` call can greatly improve performance + on TPUs or small models with a large Python overhead. + At most, one full epoch will be run each + execution. If a number larger than the size of the epoch is passed, + the execution will be truncated to the size of the epoch. + Note that if `steps_per_execution` is set to `N`, + `Callback.on_batch_begin` and `Callback.on_batch_end` methods + will only be called every `N` batches + (i.e. before/after each `tf.function` execution). + **kwargs: Arguments supported for backwards compatibility only. + + Raises: + ValueError: In case of invalid arguments for + `optimizer`, `loss` or `metrics`. + """ + with self.distribute_strategy.scope(): + if 'experimental_steps_per_execution' in kwargs: + logging.warning('The argument `steps_per_execution` is no longer ' + 'experimental. Pass `steps_per_execution` instead of ' + '`experimental_steps_per_execution`.') + if not steps_per_execution: + steps_per_execution = kwargs.pop('experimental_steps_per_execution') + + # When compiling from an already-serialized model, we do not want to + # reapply some processing steps (e.g. metric renaming for multi-output + # models, which have prefixes added for each corresponding output name). + from_serialized = kwargs.pop('from_serialized', False) + + self._validate_compile(optimizer, metrics, **kwargs) + self._run_eagerly = run_eagerly + + self.optimizer = self._get_optimizer(optimizer) + self.compiled_loss = compile_utils.LossesContainer( + loss, loss_weights, output_names=self.output_names) + self.compiled_metrics = compile_utils.MetricsContainer( + metrics, weighted_metrics, output_names=self.output_names, + from_serialized=from_serialized) + + self._configure_steps_per_execution(steps_per_execution or 1) + + # Initializes attrs that are reset each time `compile` is called. + self._reset_compile_cache() + self._is_compiled = True + + self.loss = loss or {} # Backwards compat. + + def _get_optimizer(self, optimizer): + """Wraps `optimizer` in `LossScaleOptimizer` if necessary.""" + # The deprecated PolicyV1 has a loss_scale, which we use for backwards + # compatibility to match TF 2.3 behavior. The new Policy does not have a + # loss_scale, so we use dynamic loss scaling if the mixed_float16 policy is + # used. + if isinstance(self._dtype_policy, policy.PolicyV1): + loss_scale = self._dtype_policy.loss_scale + elif self._dtype_policy.name == 'mixed_float16': + loss_scale = 'dynamic' + else: + loss_scale = None + + def _get_single_optimizer(opt): + opt = optimizers.get(opt) + if (loss_scale is not None and + not isinstance(opt, lso.LossScaleOptimizer)): + if loss_scale == 'dynamic': + opt = lso.LossScaleOptimizer(opt) + else: + opt = lso.LossScaleOptimizerV1(opt, loss_scale) + return opt + + return nest.map_structure(_get_single_optimizer, optimizer) + + @trackable.no_automatic_dependency_tracking + def _reset_compile_cache(self): + self.train_function = None + self.test_function = None + self.predict_function = None + # Used to cache the `tf.function`'ed `train_function` to be logged in + # TensorBoard, since the original `train_function` is not necessarily + # a `tf.function` (e.g., with ParameterServerStrategy, the `train_function` + # is a scheduling of the actual training function to a remote worker). + self.train_tf_function = None + + # Used to cache `trainable` attr of `Layer`s for `fit`. + self._compiled_trainable_state = self._get_trainable_state() + + @trackable.no_automatic_dependency_tracking + def _configure_steps_per_execution(self, steps_per_execution): + self._steps_per_execution = variables.Variable( + steps_per_execution, + dtype='int64', + aggregation=variables.VariableAggregationV2.ONLY_FIRST_REPLICA) + + @property + def _should_compute_mask(self): + return False + + @property + def metrics(self): + """Returns the model's metrics added using `compile`, `add_metric` APIs. + + Note: Metrics passed to `compile()` are available only after a `keras.Model` + has been trained/evaluated on actual data. + + Examples: + + >>> inputs = tf.keras.layers.Input(shape=(3,)) + >>> outputs = tf.keras.layers.Dense(2)(inputs) + >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) + >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) + >>> [m.name for m in model.metrics] + [] + + >>> x = np.random.random((2, 3)) + >>> y = np.random.randint(0, 2, (2, 2)) + >>> model.fit(x, y) + >>> [m.name for m in model.metrics] + ['loss', 'mae'] + + >>> inputs = tf.keras.layers.Input(shape=(3,)) + >>> d = tf.keras.layers.Dense(2, name='out') + >>> output_1 = d(inputs) + >>> output_2 = d(inputs) + >>> model = tf.keras.models.Model( + ... inputs=inputs, outputs=[output_1, output_2]) + >>> model.add_metric( + ... tf.reduce_sum(output_2), name='mean', aggregation='mean') + >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) + >>> model.fit(x, (y, y)) + >>> [m.name for m in model.metrics] + ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', + 'out_1_acc', 'mean'] + + """ + metrics = [] + if self._is_compiled: + # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects + # so that attr names are not load-bearing. + if self.compiled_loss is not None: + metrics += self.compiled_loss.metrics + if self.compiled_metrics is not None: + metrics += self.compiled_metrics.metrics + + for l in self._flatten_layers(): + metrics.extend(l._metrics) # pylint: disable=protected-access + return metrics + + @property + def metrics_names(self): + """Returns the model's display labels for all outputs. + + Note: `metrics_names` are available only after a `keras.Model` has been + trained/evaluated on actual data. + + Examples: + + >>> inputs = tf.keras.layers.Input(shape=(3,)) + >>> outputs = tf.keras.layers.Dense(2)(inputs) + >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) + >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) + >>> model.metrics_names + [] + + >>> x = np.random.random((2, 3)) + >>> y = np.random.randint(0, 2, (2, 2)) + >>> model.fit(x, y) + >>> model.metrics_names + ['loss', 'mae'] + + >>> inputs = tf.keras.layers.Input(shape=(3,)) + >>> d = tf.keras.layers.Dense(2, name='out') + >>> output_1 = d(inputs) + >>> output_2 = d(inputs) + >>> model = tf.keras.models.Model( + ... inputs=inputs, outputs=[output_1, output_2]) + >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) + >>> model.fit(x, (y, y)) + >>> model.metrics_names + ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', + 'out_1_acc'] + + """ + + # This property includes all output names including `loss` and per-output + # losses for backward compatibility. + return [m.name for m in self.metrics] + + @property + def distribute_strategy(self): + """The `tf.distribute.Strategy` this model was created under.""" + return self._distribution_strategy or distribute_lib.get_strategy() + + @property + def run_eagerly(self): + """Settable attribute indicating whether the model should run eagerly. + + Running eagerly means that your model will be run step by step, + like Python code. Your model might run slower, but it should become easier + for you to debug it by stepping into individual layer calls. + + By default, we will attempt to compile your model to a static graph to + deliver the best execution performance. + + Returns: + Boolean, whether the model should run eagerly. + """ + if self.dynamic and self._run_eagerly is False: # pylint:disable=g-bool-id-comparison + # TODO(fchollet): consider using py_func to enable this. + raise ValueError('Your model contains layers that can only be ' + 'successfully run in eager execution (layers ' + 'constructed with `dynamic=True`). ' + 'You cannot set `run_eagerly=False`.') + + if self._cluster_coordinator and self._run_eagerly: + raise ValueError('When using `Model` with `ParameterServerStrategy`, ' + '`run_eagerly` is not supported.') + + # Run eagerly logic, by priority: + # (1) Dynamic models must be run eagerly. + # (2) Explicitly setting run_eagerly causes a Model to be run eagerly. + # (3) Not explicitly setting run_eagerly defaults to TF's global setting. + return (self.dynamic or self._run_eagerly or + (def_function.functions_run_eagerly() and + self._run_eagerly is None)) + + @run_eagerly.setter + def run_eagerly(self, value): + self._run_eagerly = value + + def train_step(self, data): + """The logic for one training step. + + This method can be overridden to support custom training logic. + For concrete examples of how to override this method see + [Customizing what happends in fit](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). + This method is called by `Model.make_train_function`. + + This method should contain the mathematical logic for one step of training. + This typically includes the forward pass, loss calculation, backpropagation, + and metric updates. + + Configuration details for *how* this logic is run (e.g. `tf.function` and + `tf.distribute.Strategy` settings), should be left to + `Model.make_train_function`, which can also be overridden. + + Args: + data: A nested structure of `Tensor`s. + + Returns: + A `dict` containing values that will be passed to + `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the + values of the `Model`'s metrics are returned. Example: + `{'loss': 0.2, 'accuracy': 0.7}`. + + """ + # These are the only transformations `Model.fit` applies to user-input + # data when a `tf.data.Dataset` is provided. + data = data_adapter.expand_1d(data) + x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) + # Run forward pass. + with backprop.GradientTape() as tape: + y_pred = self(x, training=True) + loss = self.compiled_loss( + y, y_pred, sample_weight, regularization_losses=self.losses) + # Run backwards pass. + self.optimizer.minimize(loss, self.trainable_variables, tape=tape) + self.compiled_metrics.update_state(y, y_pred, sample_weight) + # Collect metrics to return + return_metrics = {} + for metric in self.metrics: + result = metric.result() + if isinstance(result, dict): + return_metrics.update(result) + else: + return_metrics[metric.name] = result + return return_metrics + + def make_train_function(self): + """Creates a function that executes one step of training. + + This method can be overridden to support custom training logic. + This method is called by `Model.fit` and `Model.train_on_batch`. + + Typically, this method directly controls `tf.function` and + `tf.distribute.Strategy` settings, and delegates the actual training + logic to `Model.train_step`. + + This function is cached the first time `Model.fit` or + `Model.train_on_batch` is called. The cache is cleared whenever + `Model.compile` is called. + + Returns: + Function. The function created by this method should accept a + `tf.data.Iterator`, and return a `dict` containing values that will + be passed to `tf.keras.Callbacks.on_train_batch_end`, such as + `{'loss': 0.2, 'accuracy': 0.7}`. + """ + if self.train_function is not None: + return self.train_function + + def step_function(model, iterator): + """Runs a single training step.""" + + def run_step(data): + outputs = model.train_step(data) + # Ensure counter is updated only if `train_step` succeeds. + with ops.control_dependencies(_minimum_control_deps(outputs)): + model._train_counter.assign_add(1) # pylint: disable=protected-access + return outputs + + data = next(iterator) + outputs = model.distribute_strategy.run(run_step, args=(data,)) + outputs = reduce_per_replica( + outputs, self.distribute_strategy, reduction='first') + write_scalar_summaries(outputs, step=model._train_counter) # pylint: disable=protected-access + return outputs + + if self._steps_per_execution.numpy().item() == 1: + + def train_function(iterator): + """Runs a training execution with one step.""" + return step_function(self, iterator) + + else: + + def train_function(iterator): + """Runs a training execution with multiple steps.""" + for _ in math_ops.range(self._steps_per_execution): + outputs = step_function(self, iterator) + return outputs + + if not self.run_eagerly: + train_function = def_function.function( + train_function, experimental_relax_shapes=True) + self.train_tf_function = train_function + + self.train_function = train_function + + if self._cluster_coordinator: + self.train_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda + train_function, args=(iterator,)) + + return self.train_function + + def fit(self, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose='auto', + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_batch_size=None, + validation_freq=1, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + """Trains the model for a fixed number of epochs (iterations on a dataset). + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. Should return a tuple + of either `(inputs, targets)` or + `(inputs, targets, sample_weights)`. + - A generator or `keras.utils.Sequence` returning `(inputs, targets)` + or `(inputs, targets, sample_weights)`. + - A `tf.keras.utils.experimental.DatasetCreator`, which wraps a + callable that takes a single argument of type + `tf.distribute.InputContext`, and returns a `tf.data.Dataset`. + `DatasetCreator` should be used when users prefer to specify the + per-replica batching and sharding logic for the `Dataset`. + See `tf.keras.utils.experimental.DatasetCreator` doc for more + information. + A more detailed description of unpacking behavior for iterator types + (Dataset, generator, Sequence) is given below. If using + `tf.distribute.experimental.ParameterServerStrategy`, only + `DatasetCreator` type is supported for `x`. + y: Target data. Like the input data `x`, + it could be either Numpy array(s) or TensorFlow tensor(s). + It should be consistent with `x` (you cannot have Numpy inputs and + tensor targets, or inversely). If `x` is a dataset, generator, + or `keras.utils.Sequence` instance, `y` should + not be specified (since targets will be obtained from `x`). + batch_size: Integer or `None`. + Number of samples per gradient update. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of datasets, generators, or `keras.utils.Sequence` instances + (since they generate batches). + epochs: Integer. Number of epochs to train the model. + An epoch is an iteration over the entire `x` and `y` + data provided. + Note that in conjunction with `initial_epoch`, + `epochs` is to be understood as "final epoch". + The model is not trained for a number of iterations + given by `epochs`, but merely until the epoch + of index `epochs` is reached. + verbose: 'auto', 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = progress bar, 2 = one line per epoch. + 'auto' defaults to 1 for most cases, but 2 when used with + `ParameterServerStrategy`. Note that the progress bar is not + particularly useful when logged to a file, so verbose=2 is + recommended when not running interactively (eg, in a production + environment). + callbacks: List of `keras.callbacks.Callback` instances. + List of callbacks to apply during training. + See `tf.keras.callbacks`. Note `tf.keras.callbacks.ProgbarLogger` + and `tf.keras.callbacks.History` callbacks are created automatically + and need not be passed into `model.fit`. + `tf.keras.callbacks.ProgbarLogger` is created or not based on + `verbose` argument to `model.fit`. + Callbacks with batch-level calls are currently unsupported with + `tf.distribute.experimental.ParameterServerStrategy`, and users are + advised to implement epoch-level calls instead with an appropriate + `steps_per_epoch` value. + validation_split: Float between 0 and 1. + Fraction of the training data to be used as validation data. + The model will set apart this fraction of the training data, + will not train on it, and will evaluate + the loss and any model metrics + on this data at the end of each epoch. + The validation data is selected from the last samples + in the `x` and `y` data provided, before shuffling. This argument is + not supported when `x` is a dataset, generator or + `keras.utils.Sequence` instance. + `validation_split` is not yet supported with + `tf.distribute.experimental.ParameterServerStrategy`. + validation_data: Data on which to evaluate + the loss and any model metrics at the end of each epoch. + The model will not be trained on this data. Thus, note the fact + that the validation loss of data provided using `validation_split` + or `validation_data` is not affected by regularization layers like + noise and dropout. + `validation_data` will override `validation_split`. + `validation_data` could be: + - A tuple `(x_val, y_val)` of Numpy arrays or tensors. + - A tuple `(x_val, y_val, val_sample_weights)` of NumPy arrays. + - A `tf.data.Dataset`. + - A Python generator or `keras.utils.Sequence` returning + `(inputs, targets)` or `(inputs, targets, sample_weights)`. + `validation_data` is not yet supported with + `tf.distribute.experimental.ParameterServerStrategy`. + shuffle: Boolean (whether to shuffle the training data + before each epoch) or str (for 'batch'). This argument is ignored + when `x` is a generator or an object of tf.data.Dataset. + 'batch' is a special option for dealing + with the limitations of HDF5 data; it shuffles in batch-sized + chunks. Has no effect when `steps_per_epoch` is not `None`. + class_weight: Optional dictionary mapping class indices (integers) + to a weight (float) value, used for weighting the loss function + (during training only). + This can be useful to tell the model to + "pay more attention" to samples from + an under-represented class. + sample_weight: Optional Numpy array of weights for + the training samples, used for weighting the loss function + (during training only). You can either pass a flat (1D) + Numpy array with the same length as the input samples + (1:1 mapping between weights and samples), + or in the case of temporal data, + you can pass a 2D array with shape + `(samples, sequence_length)`, + to apply a different weight to every timestep of every sample. This + argument is not supported when `x` is a dataset, generator, or + `keras.utils.Sequence` instance, instead provide the sample_weights + as the third element of `x`. + initial_epoch: Integer. + Epoch at which to start training + (useful for resuming a previous training run). + steps_per_epoch: Integer or `None`. + Total number of steps (batches of samples) + before declaring one epoch finished and starting the + next epoch. When training with input tensors such as + TensorFlow data tensors, the default `None` is equal to + the number of samples in your dataset divided by + the batch size, or 1 if that cannot be determined. If x is a + `tf.data` dataset, and 'steps_per_epoch' + is None, the epoch will run until the input dataset is exhausted. + When passing an infinitely repeating dataset, you must specify the + `steps_per_epoch` argument. If `steps_per_epoch=-1` the training + will run indefinitely with an infinitely repeating dataset. + This argument is not supported with array inputs. + When using `tf.distribute.experimental.ParameterServerStrategy`: + * `steps_per_epoch=None` is not supported. + validation_steps: Only relevant if `validation_data` is provided and + is a `tf.data` dataset. Total number of steps (batches of + samples) to draw before stopping when performing validation + at the end of every epoch. If 'validation_steps' is None, validation + will run until the `validation_data` dataset is exhausted. In the + case of an infinitely repeated dataset, it will run into an + infinite loop. If 'validation_steps' is specified and only part of + the dataset will be consumed, the evaluation will start from the + beginning of the dataset at each epoch. This ensures that the same + validation samples are used every time. + validation_batch_size: Integer or `None`. + Number of samples per validation batch. + If unspecified, will default to `batch_size`. + Do not specify the `validation_batch_size` if your data is in the + form of datasets, generators, or `keras.utils.Sequence` instances + (since they generate batches). + validation_freq: Only relevant if validation data is provided. Integer + or `collections.abc.Container` instance (e.g. list, tuple, etc.). + If an integer, specifies how many training epochs to run before a + new validation run is performed, e.g. `validation_freq=2` runs + validation every 2 epochs. If a Container, specifies the epochs on + which to run validation, e.g. `validation_freq=[1, 2, 10]` runs + validation at the end of the 1st, 2nd, and 10th epochs. + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. + If unspecified, `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up + when using process-based threading. If unspecified, `workers` + will default to 1. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to + the generator as they can't be passed easily to children processes. + + Unpacking behavior for iterator-like inputs: + A common pattern is to pass a tf.data.Dataset, generator, or + tf.keras.utils.Sequence to the `x` argument of fit, which will in fact + yield not only features (x) but optionally targets (y) and sample weights. + Keras requires that the output of such iterator-likes be unambiguous. The + iterator should return a tuple of length 1, 2, or 3, where the optional + second and third elements will be used for y and sample_weight + respectively. Any other type provided will be wrapped in a length one + tuple, effectively treating everything as 'x'. When yielding dicts, they + should still adhere to the top-level tuple structure. + e.g. `({"x0": x0, "x1": x1}, y)`. Keras will not attempt to separate + features, targets, and weights from the keys of a single dict. + A notable unsupported data type is the namedtuple. The reason is that + it behaves like both an ordered datatype (tuple) and a mapping + datatype (dict). So given a namedtuple of the form: + `namedtuple("example_tuple", ["y", "x"])` + it is ambiguous whether to reverse the order of the elements when + interpreting the value. Even worse is a tuple of the form: + `namedtuple("other_tuple", ["x", "y", "z"])` + where it is unclear if the tuple was intended to be unpacked into x, y, + and sample_weight or passed through as a single element to `x`. As a + result the data processing code will simply raise a ValueError if it + encounters a namedtuple. (Along with instructions to remedy the issue.) + + Returns: + A `History` object. Its `History.history` attribute is + a record of training loss values and metrics values + at successive epochs, as well as validation loss values + and validation metrics values (if applicable). + + Raises: + RuntimeError: 1. If the model was never compiled or, + 2. If `model.fit` is wrapped in `tf.function`. + + ValueError: In case of mismatch between the provided input data + and what the model expects or when the input data is empty. + """ + # Legacy graph support is contained in `training_v1.Model`. + version_utils.disallow_legacy_graph('Model', 'fit') + self._assert_compile_was_called() + self._check_call_args('fit') + _disallow_inside_tf_function('fit') + + if verbose == 'auto': + if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access + verbose = 2 # Default to epoch-level logging for PSStrategy. + else: + verbose = 1 # Default to batch-level logging otherwise. + + if validation_split: + # Create the validation data using the training data. Only supported for + # `Tensor` and `NumPy` input. + (x, y, sample_weight), validation_data = ( + data_adapter.train_validation_split( + (x, y, sample_weight), validation_split=validation_split)) + + if validation_data: + val_x, val_y, val_sample_weight = ( + data_adapter.unpack_x_y_sample_weight(validation_data)) + + if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access + self._cluster_coordinator = cluster_coordinator.ClusterCoordinator( + self.distribute_strategy) + + with self.distribute_strategy.scope(), \ + training_utils.RespectCompiledTrainableState(self): + # Creates a `tf.data.Dataset` and handles batch and epoch iteration. + data_handler = data_adapter.get_data_handler( + x=x, + y=y, + sample_weight=sample_weight, + batch_size=batch_size, + steps_per_epoch=steps_per_epoch, + initial_epoch=initial_epoch, + epochs=epochs, + shuffle=shuffle, + class_weight=class_weight, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + model=self, + steps_per_execution=self._steps_per_execution) + + # Container that configures and calls `tf.keras.Callback`s. + if not isinstance(callbacks, callbacks_module.CallbackList): + callbacks = callbacks_module.CallbackList( + callbacks, + add_history=True, + add_progbar=verbose != 0, + model=self, + verbose=verbose, + epochs=epochs, + steps=data_handler.inferred_steps) + + self.stop_training = False + self.train_function = self.make_train_function() + self._train_counter.assign(0) + callbacks.on_train_begin() + training_logs = None + # Handle fault-tolerance for multi-worker. + # TODO(omalleyt): Fix the ordering issues that mean this has to + # happen after `callbacks.on_train_begin`. + data_handler._initial_epoch = ( # pylint: disable=protected-access + self._maybe_load_initial_epoch_from_ckpt(initial_epoch)) + logs = None + for epoch, iterator in data_handler.enumerate_epochs(): + self.reset_metrics() + callbacks.on_epoch_begin(epoch) + with data_handler.catch_stop_iteration(): + for step in data_handler.steps(): + with trace.Trace( + 'train', + epoch_num=epoch, + step_num=step, + batch_size=batch_size, + _r=1): + callbacks.on_train_batch_begin(step) + tmp_logs = self.train_function(iterator) + if data_handler.should_sync: + context.async_wait() + logs = tmp_logs # No error, now safe to assign to logs. + end_step = step + data_handler.step_increment + callbacks.on_train_batch_end(end_step, logs) + if self.stop_training: + break + + logs = tf_utils.sync_to_numpy_or_python_type(logs) + if logs is None: + raise ValueError('Expect x to be a non-empty array or dataset.') + epoch_logs = copy.copy(logs) + + # Run validation. + if validation_data and self._should_eval(epoch, validation_freq): + # Create data_handler for evaluation and cache it. + if getattr(self, '_eval_data_handler', None) is None: + self._eval_data_handler = data_adapter.get_data_handler( + x=val_x, + y=val_y, + sample_weight=val_sample_weight, + batch_size=validation_batch_size or batch_size, + steps_per_epoch=validation_steps, + initial_epoch=0, + epochs=1, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + model=self, + steps_per_execution=self._steps_per_execution) + val_logs = self.evaluate( + x=val_x, + y=val_y, + sample_weight=val_sample_weight, + batch_size=validation_batch_size or batch_size, + steps=validation_steps, + callbacks=callbacks, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + return_dict=True, + _use_cached_eval_dataset=True) + val_logs = {'val_' + name: val for name, val in val_logs.items()} + epoch_logs.update(val_logs) + + callbacks.on_epoch_end(epoch, epoch_logs) + training_logs = epoch_logs + if self.stop_training: + break + + # If eval data_hanlder exists, delete it after all epochs are done. + if getattr(self, '_eval_data_handler', None) is not None: + del self._eval_data_handler + callbacks.on_train_end(logs=training_logs) + return self.history + + def test_step(self, data): + """The logic for one evaluation step. + + This method can be overridden to support custom evaluation logic. + This method is called by `Model.make_test_function`. + + This function should contain the mathematical logic for one step of + evaluation. + This typically includes the forward pass, loss calculation, and metrics + updates. + + Configuration details for *how* this logic is run (e.g. `tf.function` and + `tf.distribute.Strategy` settings), should be left to + `Model.make_test_function`, which can also be overridden. + + Args: + data: A nested structure of `Tensor`s. + + Returns: + A `dict` containing values that will be passed to + `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the + values of the `Model`'s metrics are returned. + """ + data = data_adapter.expand_1d(data) + x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) + + y_pred = self(x, training=False) + # Updates stateful loss metrics. + self.compiled_loss( + y, y_pred, sample_weight, regularization_losses=self.losses) + self.compiled_metrics.update_state(y, y_pred, sample_weight) + # Collect metrics to return + return_metrics = {} + for metric in self.metrics: + result = metric.result() + if isinstance(result, dict): + return_metrics.update(result) + else: + return_metrics[metric.name] = result + return return_metrics + + def make_test_function(self): + """Creates a function that executes one step of evaluation. + + This method can be overridden to support custom evaluation logic. + This method is called by `Model.evaluate` and `Model.test_on_batch`. + + Typically, this method directly controls `tf.function` and + `tf.distribute.Strategy` settings, and delegates the actual evaluation + logic to `Model.test_step`. + + This function is cached the first time `Model.evaluate` or + `Model.test_on_batch` is called. The cache is cleared whenever + `Model.compile` is called. + + Returns: + Function. The function created by this method should accept a + `tf.data.Iterator`, and return a `dict` containing values that will + be passed to `tf.keras.Callbacks.on_test_batch_end`. + """ + if self.test_function is not None: + return self.test_function + + def step_function(model, iterator): + """Runs a single evaluation step.""" + + def run_step(data): + outputs = model.test_step(data) + # Ensure counter is updated only if `test_step` succeeds. + with ops.control_dependencies(_minimum_control_deps(outputs)): + model._test_counter.assign_add(1) # pylint: disable=protected-access + return outputs + + data = next(iterator) + outputs = model.distribute_strategy.run(run_step, args=(data,)) + outputs = reduce_per_replica( + outputs, self.distribute_strategy, reduction='first') + return outputs + + if self._steps_per_execution.numpy().item() == 1: + + def test_function(iterator): + """Runs an evaluation execution with one step.""" + return step_function(self, iterator) + + else: + + def test_function(iterator): + """Runs an evaluation execution with multiple steps.""" + for _ in math_ops.range(self._steps_per_execution): + outputs = step_function(self, iterator) + return outputs + + if not self.run_eagerly: + test_function = def_function.function( + test_function, experimental_relax_shapes=True) + + self.test_function = test_function + + if self._cluster_coordinator: + self.test_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda + test_function, args=(iterator,)) + + return self.test_function + + def evaluate(self, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + return_dict=False, + **kwargs): + """Returns the loss value & metrics values for the model in test mode. + + Computation is done in batches (see the `batch_size` arg.) + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. Should return a tuple + of either `(inputs, targets)` or + `(inputs, targets, sample_weights)`. + - A generator or `keras.utils.Sequence` returning `(inputs, targets)` + or `(inputs, targets, sample_weights)`. + A more detailed description of unpacking behavior for iterator types + (Dataset, generator, Sequence) is given in the `Unpacking behavior + for iterator-like inputs` section of `Model.fit`. + y: Target data. Like the input data `x`, it could be either Numpy + array(s) or TensorFlow tensor(s). It should be consistent with `x` + (you cannot have Numpy inputs and tensor targets, or inversely). If + `x` is a dataset, generator or `keras.utils.Sequence` instance, `y` + should not be specified (since targets will be obtained from the + iterator/dataset). + batch_size: Integer or `None`. Number of samples per batch of + computation. If unspecified, `batch_size` will default to 32. Do not + specify the `batch_size` if your data is in the form of a dataset, + generators, or `keras.utils.Sequence` instances (since they generate + batches). + verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar. + sample_weight: Optional Numpy array of weights for the test samples, + used for weighting the loss function. You can either pass a flat (1D) + Numpy array with the same length as the input samples + (1:1 mapping between weights and samples), or in the case of + temporal data, you can pass a 2D array with shape `(samples, + sequence_length)`, to apply a different weight to every timestep + of every sample. This argument is not supported when `x` is a + dataset, instead pass sample weights as the third element of `x`. + steps: Integer or `None`. Total number of steps (batches of samples) + before declaring the evaluation round finished. Ignored with the + default value of `None`. If x is a `tf.data` dataset and `steps` is + None, 'evaluate' will run until the dataset is exhausted. This + argument is not supported with array inputs. + callbacks: List of `keras.callbacks.Callback` instances. List of + callbacks to apply during evaluation. See + [callbacks](/api_docs/python/tf/keras/callbacks). + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. If unspecified, + `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up when using process-based + threading. If unspecified, `workers` will default to 1. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to the + generator as they can't be passed easily to children processes. + return_dict: If `True`, loss and metric results are returned as a dict, + with each key being the name of the metric. If `False`, they are + returned as a list. + **kwargs: Unused at this time. + + See the discussion of `Unpacking behavior for iterator-like inputs` for + `Model.fit`. + + `Model.evaluate` is not yet supported with + `tf.distribute.experimental.ParameterServerStrategy`. + + Returns: + Scalar test loss (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + RuntimeError: If `model.evaluate` is wrapped in `tf.function`. + ValueError: in case of invalid arguments. + """ + version_utils.disallow_legacy_graph('Model', 'evaluate') + self._assert_compile_was_called() + self._check_call_args('evaluate') + _disallow_inside_tf_function('evaluate') + use_cached_eval_dataset = kwargs.pop('_use_cached_eval_dataset', False) + if kwargs: + raise TypeError('Invalid keyword arguments: %s' % (kwargs,)) + + if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access + self._cluster_coordinator = cluster_coordinator.ClusterCoordinator( + self.distribute_strategy) + + with self.distribute_strategy.scope(): + # Use cached evaluation data only when it's called in `Model.fit` + if (use_cached_eval_dataset + and getattr(self, '_eval_data_handler', None) is not None): + data_handler = self._eval_data_handler + else: + # Creates a `tf.data.Dataset` and handles batch and epoch iteration. + data_handler = data_adapter.get_data_handler( + x=x, + y=y, + sample_weight=sample_weight, + batch_size=batch_size, + steps_per_epoch=steps, + initial_epoch=0, + epochs=1, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + model=self, + steps_per_execution=self._steps_per_execution) + + # Container that configures and calls `tf.keras.Callback`s. + if not isinstance(callbacks, callbacks_module.CallbackList): + callbacks = callbacks_module.CallbackList( + callbacks, + add_history=True, + add_progbar=verbose != 0, + model=self, + verbose=verbose, + epochs=1, + steps=data_handler.inferred_steps) + + logs = {} + self.test_function = self.make_test_function() + self._test_counter.assign(0) + callbacks.on_test_begin() + for _, iterator in data_handler.enumerate_epochs(): # Single epoch. + self.reset_metrics() + with data_handler.catch_stop_iteration(): + for step in data_handler.steps(): + with trace.Trace('test', step_num=step, _r=1): + callbacks.on_test_batch_begin(step) + tmp_logs = self.test_function(iterator) + if data_handler.should_sync: + context.async_wait() + logs = tmp_logs # No error, now safe to assign to logs. + end_step = step + data_handler.step_increment + callbacks.on_test_batch_end(end_step, logs) + logs = tf_utils.sync_to_numpy_or_python_type(logs) + callbacks.on_test_end(logs=logs) + + if return_dict: + return logs + else: + return flatten_metrics_in_order(logs, self.metrics_names) + + def predict_step(self, data): + """The logic for one inference step. + + This method can be overridden to support custom inference logic. + This method is called by `Model.make_predict_function`. + + This method should contain the mathematical logic for one step of inference. + This typically includes the forward pass. + + Configuration details for *how* this logic is run (e.g. `tf.function` and + `tf.distribute.Strategy` settings), should be left to + `Model.make_predict_function`, which can also be overridden. + + Args: + data: A nested structure of `Tensor`s. + + Returns: + The result of one inference step, typically the output of calling the + `Model` on data. + """ + data = data_adapter.expand_1d(data) + x, _, _ = data_adapter.unpack_x_y_sample_weight(data) + return self(x, training=False) + + def make_predict_function(self): + """Creates a function that executes one step of inference. + + This method can be overridden to support custom inference logic. + This method is called by `Model.predict` and `Model.predict_on_batch`. + + Typically, this method directly controls `tf.function` and + `tf.distribute.Strategy` settings, and delegates the actual evaluation + logic to `Model.predict_step`. + + This function is cached the first time `Model.predict` or + `Model.predict_on_batch` is called. The cache is cleared whenever + `Model.compile` is called. + + Returns: + Function. The function created by this method should accept a + `tf.data.Iterator`, and return the outputs of the `Model`. + """ + if self.predict_function is not None: + return self.predict_function + + def step_function(model, iterator): + """Runs a single evaluation step.""" + + def run_step(data): + outputs = model.predict_step(data) + # Ensure counter is updated only if `test_step` succeeds. + with ops.control_dependencies(_minimum_control_deps(outputs)): + model._predict_counter.assign_add(1) # pylint: disable=protected-access + return outputs + + data = next(iterator) + outputs = model.distribute_strategy.run(run_step, args=(data,)) + outputs = reduce_per_replica( + outputs, self.distribute_strategy, reduction='concat') + return outputs + + if (self._steps_per_execution is None or + self._steps_per_execution.numpy().item() == 1): + + def predict_function(iterator): + """Runs an evaluation execution with one step.""" + return step_function(self, iterator) + + else: + + def predict_function(iterator): + """Runs an evaluation execution with multiple steps.""" + outputs = step_function(self, iterator) + for _ in math_ops.range(self._steps_per_execution - 1): + directives.set_loop_options( + shape_invariants=[( + t, tf_utils.get_tensor_spec(t, dynamic_batch=True).shape) + for t in nest.flatten(outputs)]) + step_outputs = step_function(self, iterator) + outputs = nest.map_structure(lambda t1, t2: concat([t1, t2]), outputs, + step_outputs) + return outputs + + if not self.run_eagerly: + predict_function = def_function.function( + predict_function, experimental_relax_shapes=True) + + self.predict_function = predict_function + return self.predict_function + + def predict(self, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + """Generates output predictions for the input samples. + + Computation is done in batches. This method is designed for performance in + large scale inputs. For small amount of inputs that fit in one batch, + directly using `__call__` is recommended for faster execution, e.g., + `model(x)`, or `model(x, training=False)` if you have layers such as + `tf.keras.layers.BatchNormalization` that behaves differently during + inference. Also, note the fact that test loss is not affected by + regularization layers like noise and dropout. + + Args: + x: Input samples. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A `tf.data` dataset. + - A generator or `keras.utils.Sequence` instance. + A more detailed description of unpacking behavior for iterator types + (Dataset, generator, Sequence) is given in the `Unpacking behavior + for iterator-like inputs` section of `Model.fit`. + batch_size: Integer or `None`. + Number of samples per batch. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of dataset, generators, or `keras.utils.Sequence` instances + (since they generate batches). + verbose: Verbosity mode, 0 or 1. + steps: Total number of steps (batches of samples) + before declaring the prediction round finished. + Ignored with the default value of `None`. If x is a `tf.data` + dataset and `steps` is None, `predict` will + run until the input dataset is exhausted. + callbacks: List of `keras.callbacks.Callback` instances. + List of callbacks to apply during prediction. + See [callbacks](/api_docs/python/tf/keras/callbacks). + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. + If unspecified, `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up when using + process-based threading. If unspecified, `workers` will default + to 1. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to + the generator as they can't be passed easily to children processes. + + See the discussion of `Unpacking behavior for iterator-like inputs` for + `Model.fit`. Note that Model.predict uses the same interpretation rules as + `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all + three methods. + + Returns: + Numpy array(s) of predictions. + + Raises: + RuntimeError: If `model.predict` is wrapped in `tf.function`. + ValueError: In case of mismatch between the provided + input data and the model's expectations, + or in case a stateful model receives a number of samples + that is not a multiple of the batch size. + """ + version_utils.disallow_legacy_graph('Model', 'predict') + self._check_call_args('predict') + _disallow_inside_tf_function('predict') + + # TODO(yashkatariya): Cache model on the coordinator for faster prediction. + # If running under PSS, then swap it with OneDeviceStrategy so that + # execution will run on the coordinator. + original_pss_strategy = None + if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access + original_pss_strategy = self.distribute_strategy + self._distribution_strategy = None + + # Cluster coordinator is set by `.fit()` and `.evaluate()` which is not + # needed in `.predict()` because all the predictions happen on the + # coordinator/locally. + if self._cluster_coordinator: + self._cluster_coordinator = None + + outputs = None + with self.distribute_strategy.scope(): + # Creates a `tf.data.Dataset` and handles batch and epoch iteration. + dataset_types = (data_types.DatasetV1, data_types.DatasetV2) + if (self._in_multi_worker_mode() or _is_tpu_multi_host( + self.distribute_strategy)) and isinstance(x, dataset_types): + try: + options = options_lib.Options() + data_option = options_lib.AutoShardPolicy.DATA + options.experimental_distribute.auto_shard_policy = data_option + x = x.with_options(options) + except ValueError: + warnings.warn('Using Model.predict with ' + 'MultiWorkerDistributionStrategy or TPUStrategy and ' + 'AutoShardPolicy.FILE might lead to out-of-order result' + '. Consider setting it to AutoShardPolicy.DATA.') + + data_handler = data_adapter.get_data_handler( + x=x, + batch_size=batch_size, + steps_per_epoch=steps, + initial_epoch=0, + epochs=1, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + model=self, + steps_per_execution=self._steps_per_execution) + + # Container that configures and calls `tf.keras.Callback`s. + if not isinstance(callbacks, callbacks_module.CallbackList): + callbacks = callbacks_module.CallbackList( + callbacks, + add_history=True, + add_progbar=verbose != 0, + model=self, + verbose=verbose, + epochs=1, + steps=data_handler.inferred_steps) + + self.predict_function = self.make_predict_function() + self._predict_counter.assign(0) + callbacks.on_predict_begin() + batch_outputs = None + for _, iterator in data_handler.enumerate_epochs(): # Single epoch. + with data_handler.catch_stop_iteration(): + for step in data_handler.steps(): + callbacks.on_predict_batch_begin(step) + tmp_batch_outputs = self.predict_function(iterator) + if data_handler.should_sync: + context.async_wait() + batch_outputs = tmp_batch_outputs # No error, now safe to assign. + if outputs is None: + outputs = nest.map_structure(lambda batch_output: [batch_output], + batch_outputs) + else: + nest.map_structure_up_to( + batch_outputs, + lambda output, batch_output: output.append(batch_output), + outputs, batch_outputs) + end_step = step + data_handler.step_increment + callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs}) + if batch_outputs is None: + raise ValueError('Expect x to be a non-empty array or dataset.') + callbacks.on_predict_end() + all_outputs = nest.map_structure_up_to(batch_outputs, concat, outputs) + + # If originally PSS strategy was used, then replace it back since predict + # is running under `OneDeviceStrategy` after the swap and once its done + # we need to replace it back to PSS again. + if original_pss_strategy is not None: + self._distribution_strategy = original_pss_strategy + + return tf_utils.sync_to_numpy_or_python_type(all_outputs) + + def reset_metrics(self): + """Resets the state of all the metrics in the model. + + Examples: + + >>> inputs = tf.keras.layers.Input(shape=(3,)) + >>> outputs = tf.keras.layers.Dense(2)(inputs) + >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) + >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) + + >>> x = np.random.random((2, 3)) + >>> y = np.random.randint(0, 2, (2, 2)) + >>> _ = model.fit(x, y, verbose=0) + >>> assert all(float(m.result()) for m in model.metrics) + + >>> model.reset_metrics() + >>> assert all(float(m.result()) == 0 for m in model.metrics) + + """ + for m in self.metrics: + m.reset_state() + + def train_on_batch(self, + x, + y=None, + sample_weight=None, + class_weight=None, + reset_metrics=True, + return_dict=False): + """Runs a single gradient update on a single batch of data. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + y: Target data. Like the input data `x`, it could be either Numpy + array(s) or TensorFlow tensor(s). It should be consistent with `x` + (you cannot have Numpy inputs and tensor targets, or inversely). + sample_weight: Optional array of the same length as x, containing + weights to apply to the model's loss for each sample. In the case of + temporal data, you can pass a 2D array with shape (samples, + sequence_length), to apply a different weight to every timestep of + every sample. + class_weight: Optional dictionary mapping class indices (integers) to a + weight (float) to apply to the model's loss for the samples from this + class during training. This can be useful to tell the model to "pay + more attention" to samples from an under-represented class. + reset_metrics: If `True`, the metrics returned will be only for this + batch. If `False`, the metrics will be statefully accumulated across + batches. + return_dict: If `True`, loss and metric results are returned as a dict, + with each key being the name of the metric. If `False`, they are + returned as a list. + + Returns: + Scalar training loss + (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + RuntimeError: If `model.train_on_batch` is wrapped in `tf.function`. + ValueError: In case of invalid user-provided arguments. + """ + self._assert_compile_was_called() + self._check_call_args('train_on_batch') + _disallow_inside_tf_function('train_on_batch') + with self.distribute_strategy.scope(), \ + training_utils.RespectCompiledTrainableState(self): + iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, + y, sample_weight, + class_weight) + self.train_function = self.make_train_function() + logs = self.train_function(iterator) + + if reset_metrics: + self.reset_metrics() + logs = tf_utils.sync_to_numpy_or_python_type(logs) + if return_dict: + return logs + else: + return flatten_metrics_in_order(logs, self.metrics_names) + + def test_on_batch(self, + x, + y=None, + sample_weight=None, + reset_metrics=True, + return_dict=False): + """Test the model on a single batch of samples. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays (in case the + model has multiple inputs). + - A TensorFlow tensor, or a list of tensors (in case the model has + multiple inputs). + - A dict mapping input names to the corresponding array/tensors, if + the model has named inputs. + y: Target data. Like the input data `x`, it could be either Numpy + array(s) or TensorFlow tensor(s). It should be consistent with `x` + (you cannot have Numpy inputs and tensor targets, or inversely). + sample_weight: Optional array of the same length as x, containing + weights to apply to the model's loss for each sample. In the case of + temporal data, you can pass a 2D array with shape (samples, + sequence_length), to apply a different weight to every timestep of + every sample. + reset_metrics: If `True`, the metrics returned will be only for this + batch. If `False`, the metrics will be statefully accumulated across + batches. + return_dict: If `True`, loss and metric results are returned as a dict, + with each key being the name of the metric. If `False`, they are + returned as a list. + + Returns: + Scalar test loss (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + RuntimeError: If `model.test_on_batch` is wrapped in `tf.function`. + ValueError: In case of invalid user-provided arguments. + """ + self._assert_compile_was_called() + self._check_call_args('test_on_batch') + _disallow_inside_tf_function('test_on_batch') + with self.distribute_strategy.scope(): + iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, + y, sample_weight) + self.test_function = self.make_test_function() + logs = self.test_function(iterator) + + if reset_metrics: + self.reset_metrics() + logs = tf_utils.sync_to_numpy_or_python_type(logs) + if return_dict: + return logs + else: + return flatten_metrics_in_order(logs, self.metrics_names) + + def predict_on_batch(self, x): + """Returns predictions for a single batch of samples. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays (in case the + model has multiple inputs). + - A TensorFlow tensor, or a list of tensors (in case the model has + multiple inputs). + + Returns: + Numpy array(s) of predictions. + + Raises: + RuntimeError: If `model.predict_on_batch` is wrapped in `tf.function`. + ValueError: In case of mismatch between given number of inputs and + expectations of the model. + """ + self._check_call_args('predict_on_batch') + _disallow_inside_tf_function('predict_on_batch') + with self.distribute_strategy.scope(): + iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x) + self.predict_function = self.make_predict_function() + outputs = self.predict_function(iterator) + return tf_utils.sync_to_numpy_or_python_type(outputs) + + def fit_generator(self, + generator, + steps_per_epoch=None, + epochs=1, + verbose=1, + callbacks=None, + validation_data=None, + validation_steps=None, + validation_freq=1, + class_weight=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + shuffle=True, + initial_epoch=0): + """Fits the model on data yielded batch-by-batch by a Python generator. + + DEPRECATED: + `Model.fit` now supports generators, so there is no longer any need to use + this endpoint. + """ + warnings.warn('`Model.fit_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.fit`, which supports generators.') + return self.fit( + generator, + steps_per_epoch=steps_per_epoch, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_data=validation_data, + validation_steps=validation_steps, + validation_freq=validation_freq, + class_weight=class_weight, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + shuffle=shuffle, + initial_epoch=initial_epoch) + + def evaluate_generator(self, + generator, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + verbose=0): + """Evaluates the model on a data generator. + + DEPRECATED: + `Model.evaluate` now supports generators, so there is no longer any need + to use this endpoint. + """ + warnings.warn('`Model.evaluate_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.evaluate`, which supports generators.') + self._check_call_args('evaluate_generator') + + return self.evaluate( + generator, + steps=steps, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + verbose=verbose, + callbacks=callbacks) + + def predict_generator(self, + generator, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + verbose=0): + """Generates predictions for the input samples from a data generator. + + DEPRECATED: + `Model.predict` now supports generators, so there is no longer any need + to use this endpoint. + """ + warnings.warn('`Model.predict_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.predict`, which supports generators.') + return self.predict( + generator, + steps=steps, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + verbose=verbose, + callbacks=callbacks) + + ###################################################################### + # Functions below are not training related. They are for model weights + # tracking, save/load, serialization, etc. + ###################################################################### + + @property + def trainable_weights(self): + self._assert_weights_created() + if not self._trainable: + return [] + trainable_variables = [] + for trackable_obj in self._self_tracked_trackables: + trainable_variables += trackable_obj.trainable_variables + trainable_variables += self._trainable_weights + return self._dedup_weights(trainable_variables) + + @property + def non_trainable_weights(self): + self._assert_weights_created() + non_trainable_variables = [] + for trackable_obj in self._self_tracked_trackables: + non_trainable_variables += trackable_obj.non_trainable_variables + + if not self._trainable: + # Return order is all trainable vars, then all non-trainable vars. + trainable_variables = [] + for trackable_obj in self._self_tracked_trackables: + trainable_variables += trackable_obj.trainable_variables + + non_trainable_variables = ( + trainable_variables + self._trainable_weights + + non_trainable_variables + self._non_trainable_weights) + else: + non_trainable_variables = ( + non_trainable_variables + self._non_trainable_weights) + + return self._dedup_weights(non_trainable_variables) + + def get_weights(self): + """Retrieves the weights of the model. + + Returns: + A flat list of Numpy arrays. + """ + with self.distribute_strategy.scope(): + return super(Model, self).get_weights() + + def save(self, + filepath, + overwrite=True, + include_optimizer=True, + save_format=None, + signatures=None, + options=None, + save_traces=True): + # pylint: disable=line-too-long + """Saves the model to Tensorflow SavedModel or a single HDF5 file. + + Please see `tf.keras.models.save_model` or the + [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) + for details. + + Args: + filepath: String, PathLike, path to SavedModel or H5 file to save the + model. + overwrite: Whether to silently overwrite any existing file at the + target location, or provide the user with a manual prompt. + include_optimizer: If True, save optimizer's state together. + save_format: Either `'tf'` or `'h5'`, indicating whether to save the + model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, + and 'h5' in TF 1.X. + signatures: Signatures to save with the SavedModel. Applicable to the + 'tf' format only. Please see the `signatures` argument in + `tf.saved_model.save` for details. + options: (only applies to SavedModel format) + `tf.saved_model.SaveOptions` object that specifies options for + saving to SavedModel. + save_traces: (only applies to SavedModel format) When enabled, the + SavedModel will store the function traces for each layer. This + can be disabled, so that only the configs of each layer are stored. + Defaults to `True`. Disabling this will decrease serialization time + and reduce file size, but it requires that all custom layers/models + implement a `get_config()` method. + + Example: + + ```python + from keras.models import load_model + + model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' + del model # deletes the existing model + + # returns a compiled model + # identical to the previous one + model = load_model('my_model.h5') + ``` + """ + # pylint: enable=line-too-long + save.save_model(self, filepath, overwrite, include_optimizer, save_format, + signatures, options, save_traces) + + def save_weights(self, + filepath, + overwrite=True, + save_format=None, + options=None): + """Saves all layer weights. + + Either saves in HDF5 or in TensorFlow format based on the `save_format` + argument. + + When saving in HDF5 format, the weight file has: + - `layer_names` (attribute), a list of strings + (ordered names of model layers). + - For every layer, a `group` named `layer.name` + - For every such layer group, a group attribute `weight_names`, + a list of strings + (ordered names of weights tensor of the layer). + - For every weight in the layer, a dataset + storing the weight value, named after the weight tensor. + + When saving in TensorFlow format, all objects referenced by the network are + saved in the same format as `tf.train.Checkpoint`, including any `Layer` + instances or `Optimizer` instances assigned to object attributes. For + networks constructed from inputs and outputs using `tf.keras.Model(inputs, + outputs)`, `Layer` instances used by the network are tracked/saved + automatically. For user-defined classes which inherit from `tf.keras.Model`, + `Layer` instances must be assigned to object attributes, typically in the + constructor. See the documentation of `tf.train.Checkpoint` and + `tf.keras.Model` for details. + + While the formats are the same, do not mix `save_weights` and + `tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should be + loaded using `Model.load_weights`. Checkpoints saved using + `tf.train.Checkpoint.save` should be restored using the corresponding + `tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over + `save_weights` for training checkpoints. + + The TensorFlow format matches objects and variables by starting at a root + object, `self` for `save_weights`, and greedily matching attribute + names. For `Model.save` this is the `Model`, and for `Checkpoint.save` this + is the `Checkpoint` even if the `Checkpoint` has a model attached. This + means saving a `tf.keras.Model` using `save_weights` and loading into a + `tf.train.Checkpoint` with a `Model` attached (or vice versa) will not match + the `Model`'s variables. See the [guide to training + checkpoints](https://www.tensorflow.org/guide/checkpoint) for details + on the TensorFlow format. + + Args: + filepath: String or PathLike, path to the file to save the weights to. + When saving in TensorFlow format, this is the prefix used for + checkpoint files (multiple files are generated). Note that the '.h5' + suffix causes weights to be saved in HDF5 format. + overwrite: Whether to silently overwrite any existing file at the + target location, or provide the user with a manual prompt. + save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or + '.keras' will default to HDF5 if `save_format` is `None`. Otherwise + `None` defaults to 'tf'. + options: Optional `tf.train.CheckpointOptions` object that specifies + options for saving weights. + + Raises: + ImportError: If h5py is not available when attempting to save in HDF5 + format. + ValueError: For invalid/unknown format arguments. + """ + self._assert_weights_created() + filepath = path_to_string(filepath) + filepath_is_h5 = saving_utils.is_hdf5_filepath(filepath) + if save_format is None: + if filepath_is_h5: + save_format = 'h5' + else: + save_format = 'tf' + else: + user_format = save_format.lower().strip() + if user_format in ('tensorflow', 'tf'): + save_format = 'tf' + elif user_format in ('hdf5', 'h5', 'keras'): + save_format = 'h5' + else: + raise ValueError( + 'Unknown format "%s". Was expecting one of {"tf", "h5"}.' % ( + save_format,)) + if save_format == 'tf' and filepath_is_h5: + raise ValueError( + ('save_weights got save_format="tf"/"tensorflow", but the ' + 'filepath ("%s") looks like an HDF5 file. Omit the ".h5"/".keras" ' + 'when saving in TensorFlow format.') + % filepath) + + if save_format == 'h5' and h5py is None: + raise ImportError( + '`save_weights` requires h5py when saving in hdf5.') + if save_format == 'tf': + check_filepath = filepath + '.index' + else: + check_filepath = filepath + # If file exists and should not be overwritten: + if not overwrite and os.path.isfile(check_filepath): + proceed = ask_to_proceed_with_overwrite(check_filepath) + if not proceed: + return + if save_format == 'h5': + with h5py.File(filepath, 'w') as f: + hdf5_format.save_weights_to_hdf5_group(f, self.layers) + else: + if not context.executing_eagerly(): + # Call `get_session` to initialize any uninitialized variables. + backend.get_session() + self._checkpoint.write(filepath, options=options) + # Record this checkpoint so it's visible from tf.train.latest_checkpoint. + checkpoint_management.update_checkpoint_state_internal( + save_dir=os.path.dirname(filepath), + model_checkpoint_path=filepath, + save_relative_paths=True, + all_model_checkpoint_paths=[filepath]) + + def load_weights(self, + filepath, + by_name=False, + skip_mismatch=False, + options=None): + """Loads all layer weights, either from a TensorFlow or an HDF5 weight file. + + If `by_name` is False weights are loaded based on the network's + topology. This means the architecture should be the same as when the weights + were saved. Note that layers that don't have weights are not taken into + account in the topological ordering, so adding or removing layers is fine as + long as they don't have weights. + + If `by_name` is True, weights are loaded into layers only if they share the + same name. This is useful for fine-tuning or transfer-learning models where + some of the layers have changed. + + Only topological loading (`by_name=False`) is supported when loading weights + from the TensorFlow format. Note that topological loading differs slightly + between TensorFlow and HDF5 formats for user-defined classes inheriting from + `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the + TensorFlow format loads based on the object-local names of attributes to + which layers are assigned in the `Model`'s constructor. + + Args: + filepath: String, path to the weights file to load. For weight files in + TensorFlow format, this is the file prefix (the same as was passed + to `save_weights`). This can also be a path to a SavedModel + saved from `model.save`. + by_name: Boolean, whether to load weights by name or by topological + order. Only topological loading is supported for weight files in + TensorFlow format. + skip_mismatch: Boolean, whether to skip loading of layers where there is + a mismatch in the number of weights, or a mismatch in the shape of + the weight (only valid when `by_name=True`). + options: Optional `tf.train.CheckpointOptions` object that specifies + options for loading weights. + + Returns: + When loading a weight file in TensorFlow format, returns the same status + object as `tf.train.Checkpoint.restore`. When graph building, restore + ops are run automatically as soon as the network is built (on first call + for user-defined classes inheriting from `Model`, immediately if it is + already built). + + When loading weights in HDF5 format, returns `None`. + + Raises: + ImportError: If h5py is not available and the weight file is in HDF5 + format. + ValueError: If `skip_mismatch` is set to `True` when `by_name` is + `False`. + """ + if backend.is_tpu_strategy(self._distribution_strategy): + if (self._distribution_strategy.extended.steps_per_run > 1 and + (not saving_utils.is_hdf5_filepath(filepath))): + raise ValueError('Load weights is not yet supported with TPUStrategy ' + 'with steps_per_run greater than 1.') + if skip_mismatch and not by_name: + raise ValueError( + 'When calling model.load_weights, skip_mismatch can only be set to ' + 'True when by_name is True.') + + filepath, save_format = _detect_save_format(filepath) + if save_format == 'tf': + status = self._checkpoint.read(filepath, options) + if by_name: + raise NotImplementedError( + 'Weights may only be loaded based on topology into Models when ' + 'loading TensorFlow-formatted weights (got by_name=True to ' + 'load_weights).') + if not context.executing_eagerly(): + session = backend.get_session() + # Restore existing variables (if any) immediately, and set up a + # streaming restore for any variables created in the future. + trackable_utils.streaming_restore(status=status, session=session) + status.assert_nontrivial_match() + else: + status = None + if h5py is None: + raise ImportError( + '`load_weights` requires h5py when loading weights from HDF5.') + if not self._is_graph_network and not self.built: + raise ValueError( + 'Unable to load weights saved in HDF5 format into a subclassed ' + 'Model which has not created its variables yet. Call the Model ' + 'first, then load the weights.') + self._assert_weights_created() + with h5py.File(filepath, 'r') as f: + if 'layer_names' not in f.attrs and 'model_weights' in f: + f = f['model_weights'] + if by_name: + hdf5_format.load_weights_from_hdf5_group_by_name( + f, self.layers, skip_mismatch=skip_mismatch) + else: + hdf5_format.load_weights_from_hdf5_group(f, self.layers) + + # Perform any layer defined finalization of the layer state. + for layer in self.layers: + layer.finalize_state() + return status + + def _updated_config(self): + """Util shared between different serialization methods. + + Returns: + Model config with Keras version information added. + """ + from tensorflow.python.keras import __version__ as keras_version # pylint: disable=g-import-not-at-top + + config = self.get_config() + model_config = { + 'class_name': self.__class__.__name__, + 'config': config, + 'keras_version': keras_version, + 'backend': backend.backend() + } + return model_config + + def get_config(self): + raise NotImplementedError + + @classmethod + def from_config(cls, config, custom_objects=None): + # `from_config` assumes `cls` is either `Functional` or a child class of + # `Functional`. In the case that `cls` is meant to behave like a child class + # of `Functional` but only inherits from the `Model` class, we have to call + # `cls(...)` instead of `Functional.from_config`. + from tensorflow.python.keras.engine import functional # pylint: disable=g-import-not-at-top + with generic_utils.SharedObjectLoadingScope(): + input_tensors, output_tensors, created_layers = ( + functional.reconstruct_from_config(config, custom_objects)) + # Initialize a model belonging to `cls`, which can be user-defined or + # `Functional`. + model = cls(inputs=input_tensors, outputs=output_tensors, + name=config.get('name')) + functional.connect_ancillary_layers(model, created_layers) + return model + + def to_json(self, **kwargs): + """Returns a JSON string containing the network configuration. + + To load a network from a JSON save file, use + `keras.models.model_from_json(json_string, custom_objects={})`. + + Args: + **kwargs: Additional keyword arguments + to be passed to `json.dumps()`. + + Returns: + A JSON string. + """ + model_config = self._updated_config() + return json.dumps( + model_config, default=json_utils.get_json_type, **kwargs) + + def to_yaml(self, **kwargs): + """Returns a yaml string containing the network configuration. + + Note: Since TF 2.6, this method is no longer supported and will raise a + RuntimeError. + + To load a network from a yaml save file, use + `keras.models.model_from_yaml(yaml_string, custom_objects={})`. + + `custom_objects` should be a dictionary mapping + the names of custom losses / layers / etc to the corresponding + functions / classes. + + Args: + **kwargs: Additional keyword arguments + to be passed to `yaml.dump()`. + + Returns: + A YAML string. + + Raises: + RuntimeError: announces that the method poses a security risk + """ + raise RuntimeError( + 'Method `model.to_yaml()` has been removed due to security risk of ' + 'arbitrary code execution. Please use `model.to_json()` instead.' + ) + + def reset_states(self): + for layer in self.layers: + if hasattr(layer, 'reset_states') and getattr(layer, 'stateful', False): + layer.reset_states() + + @property + @doc_controls.do_not_generate_docs + def state_updates(self): + """Deprecated, do NOT use! + + Returns the `updates` from all layers that are stateful. + + This is useful for separating training updates and + state updates, e.g. when we need to update a layer's internal state + during prediction. + + Returns: + A list of update ops. + """ + warnings.warn('`Model.state_updates` will be removed in a future version. ' + 'This property should not be used in TensorFlow 2.0, ' + 'as `updates` are applied automatically.') + state_updates = [] + for layer in self.layers: + if getattr(layer, 'stateful', False): + if hasattr(layer, 'updates'): + state_updates += layer.updates + return state_updates + + @property + def weights(self): + """Returns the list of all layer variables/weights. + + Note: This will not track the weights of nested `tf.Modules` that are not + themselves Keras layers. + + Returns: + A list of variables. + """ + return self._dedup_weights(self._undeduplicated_weights) + + @property + def _undeduplicated_weights(self): + """Returns the undeduplicated list of all layer variables/weights.""" + self._assert_weights_created() + weights = [] + for layer in self._self_tracked_trackables: + weights += layer.variables + weights += (self._trainable_weights + self._non_trainable_weights) + return weights + + def summary(self, line_length=None, positions=None, print_fn=None): + """Prints a string summary of the network. + + Args: + line_length: Total length of printed lines + (e.g. set this to adapt the display to different + terminal window sizes). + positions: Relative or absolute positions of log elements + in each line. If not provided, + defaults to `[.33, .55, .67, 1.]`. + print_fn: Print function to use. Defaults to `print`. + It will be called on each line of the summary. + You can set it to a custom function + in order to capture the string summary. + + Raises: + ValueError: if `summary()` is called before the model is built. + """ + if not self.built: + raise ValueError('This model has not yet been built. ' + 'Build the model first by calling `build()` or calling ' + '`fit()` with some data, or specify ' + 'an `input_shape` argument in the first layer(s) for ' + 'automatic build.') + layer_utils.print_summary(self, + line_length=line_length, + positions=positions, + print_fn=print_fn) + + @property + def layers(self): + return list(self._flatten_layers(include_self=False, recursive=False)) + + def get_layer(self, name=None, index=None): + """Retrieves a layer based on either its name (unique) or index. + + If `name` and `index` are both provided, `index` will take precedence. + Indices are based on order of horizontal graph traversal (bottom-up). + + Args: + name: String, name of layer. + index: Integer, index of layer. + + Returns: + A layer instance. + + Raises: + ValueError: In case of invalid layer name or index. + """ + # TODO(fchollet): We could build a dictionary based on layer names + # since they are constant, but we have not done that yet. + if index is not None and name is not None: + raise ValueError('Provide only a layer name or a layer index.') + + if index is not None: + if len(self.layers) <= index: + raise ValueError('Was asked to retrieve layer at index ' + str(index) + + ' but model only has ' + str(len(self.layers)) + + ' layers.') + else: + return self.layers[index] + + if name is not None: + for layer in self.layers: + if layer.name == name: + return layer + raise ValueError('No such layer: ' + name + '.') + raise ValueError('Provide either a layer name or layer index.') + + @trackable.no_automatic_dependency_tracking + def _set_save_spec(self, inputs): + if self._saved_model_inputs_spec is not None: + return # Already set. + + input_names = self.input_names + if not input_names: + input_names = compile_utils.create_pseudo_input_names(inputs) + + flat_inputs = nest.flatten(inputs) + specs = [] + for name, tensor in zip(input_names, flat_inputs): + specs.append( + tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)) + specs = nest.pack_sequence_as(inputs, specs) + + self._saved_model_inputs_spec = specs + + # Store the input shapes + if (self.__class__.__name__ == 'Sequential' and + self._build_input_shape is None): + self._build_input_shape = nest.map_structure( + lambda x: None if x is None else x.shape, specs) + + def _assert_weights_created(self): + """Asserts that all the weights for the model have been created. + + For a non-dynamic model, the weights must already be created after the + layer has been called. For a dynamic model, the exact list of weights can + never be known for certain since it may change at any time during execution. + + We run this check right before accessing weights or getting the Numpy value + for the current weights. Otherwise, if the layer has never been called, + the user would just get an empty list, which is misleading. + + Raises: + ValueError: if the weights of the network has not yet been created. + """ + if self.dynamic: + return + + if ('build' in self.__class__.__dict__ and + self.__class__ != Model and + not self.built): + # For any model that has customized build() method but hasn't + # been invoked yet, this will cover both sequential and subclass model. + # Also make sure to exclude Model class itself which has build() defined. + raise ValueError('Weights for model %s have not yet been created. ' + 'Weights are created when the Model is first called on ' + 'inputs or `build()` is called with an `input_shape`.' % + self.name) + + def _check_call_args(self, method_name): + """Check that `call` has only one positional arg.""" + # Always allow first arg, regardless of arg name. + fullargspec = self._call_full_argspec + if fullargspec.defaults: + positional_args = fullargspec.args[:-len(fullargspec.defaults)] + else: + positional_args = fullargspec.args + if 'training' in positional_args: + positional_args.remove('training') + + # self and first arg can be positional. + if len(positional_args) > 2: + extra_args = positional_args[2:] + raise ValueError( + 'Models passed to `' + method_name + '` can only have `training` ' + 'and the first argument in `call` as positional arguments, ' + 'found: ' + str(extra_args) + '.') + + def _validate_compile(self, optimizer, metrics, **kwargs): + """Performs validation checks for the default `compile`.""" + if any( + isinstance(opt, optimizer_v1.Optimizer) + for opt in nest.flatten(optimizer)): + raise ValueError( + '`tf.compat.v1.keras` Optimizer (', optimizer, ') is ' + 'not supported when eager execution is enabled. Use a ' + '`tf.keras` Optimizer instead, or disable eager ' + 'execution.') + + kwargs.pop('cloning', None) # Legacy DistStrat argument, never used. + kwargs.pop('experimental_run_tf_function', None) # Always `True`. + if kwargs.pop('distribute', None) is not None: + raise ValueError( + 'Distribute argument in compile is not available in TF 2.0 please ' + 'create the model under the distribution strategy scope.') + if kwargs.pop('target_tensors', None) is not None: + raise ValueError( + 'target_tensors argument is not supported when executing eagerly.') + invalid_kwargs = set(kwargs) - {'sample_weight_mode'} + if invalid_kwargs: + raise TypeError('Invalid keyword argument(s) in `compile`: %s' % + (invalid_kwargs,)) + + # Model must be created and compiled with the same DistStrat. + if self.built and distribute_lib.has_strategy(): + strategy = distribute_lib.get_strategy() + for v in self.variables: + if not strategy.extended.variable_created_in_scope(v): + raise ValueError( + 'Variable (%s) was not created in the distribution strategy ' + 'scope of (%s). It is most likely due to not all layers or ' + 'the model or optimizer being created outside the distribution ' + 'strategy scope. Try to make sure your code looks similar ' + 'to the following.\n' + 'with strategy.scope():\n' + ' model=_create_model()\n' + ' model.compile(...)' % (v, strategy)) + + # Model metrics must be created in the same distribution strategy scope + # as the model. + strategy = self.distribute_strategy + for metric in nest.flatten(metrics): + for v in getattr(metric, 'variables', []): + if not strategy.extended.variable_created_in_scope(v): + raise ValueError( + 'Metric (%s) passed to model.compile was created inside of a ' + 'different distribution strategy scope than the model. All ' + 'metrics must be created in the same distribution strategy ' + 'scope as the model (in this case %s). If you pass in a string ' + 'identifier for a metric to compile the metric will ' + 'automatically be created in the correct distribution ' + 'strategy scope.' % (metric, strategy) + ) + + # Model metrics must be created in the same distribution strategy scope + # as the model. + for opt in nest.flatten(optimizer): + for v in getattr(opt, '_weights', []): + if not strategy.extended.variable_created_in_scope(v): + raise ValueError( + 'Optimizer (%s) passed to model.compile was created inside of a ' + 'different distribution strategy scope than the model. All ' + 'optimizers must be created in the same distribution strategy ' + 'scope as the model (in this case %s). If you pass in a string ' + 'identifier for an optimizer to compile the optimizer will ' + 'automatically be created in the correct distribution ' + 'strategy scope.' % (opt, strategy)) + + def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch): + """Maybe load initial epoch from ckpt considering possible worker recovery. + + Refer to tensorflow/python/keras/distribute/worker_training_state.py + for more information. + + Args: + initial_epoch: The original initial_epoch user passes in in `fit()`. + + Returns: + If the training is recovering from previous failure under multi-worker + training setting, return the epoch the training is supposed to continue + at. Otherwise, return the `initial_epoch` the user passes in. + """ + if self._training_state is not None: + return self._training_state.maybe_load_initial_epoch_from_ckpt( + initial_epoch, mode=ModeKeys.TRAIN) + return initial_epoch + + def _assert_compile_was_called(self): + # Checks whether `compile` has been called. If it has been called, + # then the optimizer is set. This is different from whether the + # model is compiled + # (i.e. whether the model is built and its inputs/outputs are set). + if not self._is_compiled: + raise RuntimeError('You must compile your model before ' + 'training/testing. ' + 'Use `model.compile(optimizer, loss)`.') + + def _set_inputs(self, inputs, outputs=None, training=None): + """This method is for compat with Modelv1. Only inputs are needed here.""" + self._set_save_spec(inputs) + + @property + def _trackable_saved_model_saver(self): + return model_serialization.ModelSavedModelSaver(self) + + def _trackable_children(self, save_type='checkpoint', **kwargs): + if save_type == 'savedmodel': + # SavedModel needs to ignore the execution functions. + train_function = self.train_function + test_function = self.test_function + predict_function = self.predict_function + train_tf_function = self.train_tf_function + self.train_function = None + self.test_function = None + self.predict_function = None + self.train_tf_function = None + + children = super(Model, self)._trackable_children(save_type, **kwargs) + + if save_type == 'savedmodel': + self.train_function = train_function + self.test_function = test_function + self.predict_function = predict_function + self.train_tf_function = train_tf_function + + return children + + def _should_eval(self, epoch, validation_freq): + epoch = epoch + 1 # one-index the user-facing epoch. + if isinstance(validation_freq, int): + return epoch % validation_freq == 0 + elif isinstance(validation_freq, list): + return epoch in validation_freq + else: + raise ValueError('Expected `validation_freq` to be a list or int.') + + ###################################################################### + # Functions below exist only as v1 / v2 compatibility shims. + ###################################################################### + + def _get_compile_args(self, user_metrics=True): + """Used for saving or cloning a Model. + + Args: + user_metrics: Whether to return user-supplied metrics or `Metric` objects. + Defaults to returning the user-supplied metrics. + + Returns: + Dictionary of arguments that were used when compiling the model. + """ + self._assert_compile_was_called() + # pylint: disable=protected-access + + saved_metrics = self.compiled_metrics._user_metrics + saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics + + if not user_metrics: + if saved_metrics is not None: + saved_metrics = self.compiled_metrics._metrics + if saved_weighted_metrics is not None: + saved_weighted_metrics = self.compiled_metrics._weighted_metrics + + compile_args = { + 'optimizer': self.optimizer, + 'loss': self.compiled_loss._user_losses, + 'metrics': saved_metrics, + 'weighted_metrics': saved_weighted_metrics, + 'loss_weights': self.compiled_loss._user_loss_weights, + } + # pylint: enable=protected-access + return compile_args + + def _get_callback_model(self): + return self + + def _in_multi_worker_mode(self): + return self.distribute_strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access + + @property + def _compile_was_called(self): + return self._is_compiled + + +def reduce_per_replica(values, strategy, reduction='first'): + """Reduce PerReplica objects. + + Args: + values: Structure of `PerReplica` objects or `Tensor`s. `Tensor`s are + returned as-is. + strategy: `tf.distribute.Strategy` object. + reduction: One of 'first', 'concat'. + + Returns: + Structure of `Tensor`s. + """ + + def _reduce(v): + """Reduce a single `PerReplica` object.""" + if reduction == 'concat' and _collective_all_reduce_multi_worker(strategy): + return _multi_worker_concat(v, strategy) + if not _is_per_replica_instance(v): + return v + elif reduction == 'first': + return strategy.unwrap(v)[0] + elif reduction == 'concat': + if _is_tpu_multi_host(strategy): + return _tpu_multi_host_concat(v, strategy) + else: + return concat(strategy.unwrap(v)) + else: + raise ValueError('`reduction` must be "first" or "concat".') + + return nest.map_structure(_reduce, values) + + +def concat(tensors, axis=0): + """Concats `tensor`s along `axis`.""" + if isinstance(tensors[0], sparse_tensor.SparseTensor): + return sparse_ops.sparse_concat_v2(axis=axis, sp_inputs=tensors) + elif _is_scalar(tensors[0]): + return array_ops_stack.stack(tensors, axis=axis) + else: + return array_ops.concat(tensors, axis=axis) + + +def _is_tpu_multi_host(strategy): + return (backend.is_tpu_strategy(strategy) and + strategy.extended.num_hosts > 1) + + +def _tpu_multi_host_concat(v, strategy): + """Correctly order TPU PerReplica objects.""" + replicas = strategy.unwrap(v) + # When distributed datasets are created from Tensors / NumPy, + # TPUStrategy.experimental_distribute_dataset shards data in + # (Replica, Host) order, and TPUStrategy.unwrap returns it in + # (Host, Replica) order. + # TODO(b/150317897): Figure out long-term plan here. + num_replicas_per_host = strategy.extended.num_replicas_per_host + ordered_replicas = [] + for replica_id in range(num_replicas_per_host): + ordered_replicas += replicas[replica_id::num_replicas_per_host] + return concat(ordered_replicas) + + +def _collective_all_reduce_multi_worker(strategy): + return (isinstance(strategy, + collective_all_reduce_strategy.CollectiveAllReduceStrategy) + ) and strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access + + +# TODO(wxinyi): merge this with _tpu_multi_host_concat once we have all_gather +# for all strategies +def _multi_worker_concat(v, strategy): + """Order PerReplica objects for CollectiveAllReduceStrategy and concat.""" + replicas = strategy.gather(v, axis=0) + # v might not have the same shape on different replicas + if _is_per_replica_instance(v): + shapes = array_ops.concat([ + array_ops.expand_dims_v2(array_ops.shape(single_value)[0], axis=0) + for single_value in v.values + ], + axis=0) + all_shapes = strategy.gather(shapes, axis=0) + else: + # v is a tensor. This may happen when, say, we have 2x1 multi-worker. + all_shapes = strategy.gather( + array_ops.expand_dims_v2(array_ops.shape(v)[0], axis=0), axis=0) + + replicas = array_ops.split( + replicas, + num_or_size_splits=all_shapes, + num=strategy.num_replicas_in_sync) + ordered_replicas = [] + num_replicas_per_worker = len(strategy.extended.worker_devices) + for replica_id in range(num_replicas_per_worker): + ordered_replicas += replicas[replica_id::num_replicas_per_worker] + return concat(ordered_replicas) + + +def _is_scalar(x): + return isinstance( + x, (tensor_lib.Tensor, variables.Variable)) and x.shape.rank == 0 + + +def write_scalar_summaries(logs, step): + for name, value in logs.items(): + if _is_scalar(value): + summary_ops_v2.scalar('batch_' + name, value, step=step) + + +def _minimum_control_deps(outputs): + """Returns the minimum control dependencies to ensure step succeeded.""" + if context.executing_eagerly(): + return [] # Control dependencies not needed. + outputs = nest.flatten(outputs, expand_composites=True) + for out in outputs: + # Variables can't be control dependencies. + if not isinstance(out, variables.Variable): + return [out] # Return first Tensor or Op from outputs. + return [] # No viable Tensor or Op to use for control deps. + + +def _disallow_inside_tf_function(method_name): + if ops.inside_function(): + error_msg = ( + 'Detected a call to `Model.{method_name}` inside a `tf.function`. ' + '`Model.{method_name} is a high-level endpoint that manages its own ' + '`tf.function`. Please move the call to `Model.{method_name}` outside ' + 'of all enclosing `tf.function`s. Note that you can call a `Model` ' + 'directly on `Tensor`s inside a `tf.function` like: `model(x)`.' + ).format(method_name=method_name) + raise RuntimeError(error_msg) + + +def _detect_save_format(filepath): + """Returns path to weights file and save format.""" + + filepath = path_to_string(filepath) + if saving_utils.is_hdf5_filepath(filepath): + return filepath, 'h5' + + # Filepath could be a TensorFlow checkpoint file prefix or SavedModel + # directory. It's possible for filepath to be both a prefix and directory. + # Prioritize checkpoint over SavedModel. + if _is_readable_tf_checkpoint(filepath): + save_format = 'tf' + elif sm_loader.contains_saved_model(filepath): + ckpt_path = os.path.join(filepath, sm_constants.VARIABLES_DIRECTORY, + sm_constants.VARIABLES_FILENAME) + if _is_readable_tf_checkpoint(ckpt_path): + filepath = ckpt_path + save_format = 'tf' + else: + raise ValueError('Unable to load weights. filepath {} appears to be a ' + 'SavedModel directory, but checkpoint either doesn\'t ' + 'exist, or is incorrectly formatted.'.format(filepath)) + else: + # Not a TensorFlow checkpoint. This filepath is likely an H5 file that + # doesn't have the hdf5/keras extensions. + save_format = 'h5' + return filepath, save_format + + +def _is_readable_tf_checkpoint(filepath): + try: + py_checkpoint_reader.NewCheckpointReader(filepath) + return True + except errors_impl.DataLossError: + # The checkpoint is not readable in TensorFlow format. + return False + + +def flatten_metrics_in_order(logs, metrics_names): + """Turns the `logs` dict into a list as per key order of `metrics_names`.""" + results = [] + for name in metrics_names: + if name in logs: + results.append(logs[name]) + for key in sorted(logs.keys()): + if key not in metrics_names: + results.append(logs[key]) + if len(results) == 1: + return results[0] + return results + + +def _is_per_replica_instance(obj): + return (isinstance(obj, ds_values.DistributedValues) and + isinstance(obj, composite_tensor.CompositeTensor)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_arrays_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_arrays_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9998dbead48496d83aeb62c1e0558bc5256488 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_arrays_v1.py @@ -0,0 +1,709 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Part of the Keras training engine related to plain array data.""" +# pylint: disable=protected-access + +import functools + +import numpy as np + +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks as cbks +from tensorflow.python.keras.distribute import distributed_training_utils_v1 +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.utils.generic_utils import make_batches +from tensorflow.python.keras.utils.generic_utils import slice_arrays +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest + +try: + from scipy.sparse import issparse # pylint: disable=g-import-not-at-top +except ImportError: + issparse = None + + +def model_iteration(model, + inputs, + targets=None, + sample_weights=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + val_inputs=None, + val_targets=None, + val_sample_weights=None, + shuffle=True, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + mode=ModeKeys.TRAIN, + validation_in_fit=False, + prepared_feed_values_from_dataset=False, + steps_name='steps', + **kwargs): + """Loop function for arrays of data with modes TRAIN/TEST/PREDICT. + + Args: + model: Keras Model instance. + inputs: Either a list or dictionary of arrays, or a dataset instance. + targets: List/dictionary of input arrays. + sample_weights: Optional list of sample weight arrays. + batch_size: Integer batch size or None if unknown. + epochs: Number of times to iterate over the data + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = progress bar, 2 = one line per epoch. + Note that the progress bar is not particularly useful when + logged to a file, so verbose=2 is recommended when not running + interactively (eg, in a production environment). + callbacks: List of callbacks to be called during training + val_inputs: Either a list or dictionary of arrays, or a dataset instance. + val_targets: List/dictionary of target arrays. + val_sample_weights: Optional list of sample weight arrays. + shuffle: Whether to shuffle the data at the beginning of each epoch + concatenation of list the display names of the outputs of `f` and the + list of display names of the outputs of `f_val`. + initial_epoch: Epoch at which to start training (useful for resuming a + previous training run) + steps_per_epoch: Total number of steps (batches of samples) before + declaring one epoch finished and starting the next epoch. Ignored with + the default value of `None`. + validation_steps: Number of steps to run validation for (only if doing + validation from data tensors). Ignored with the default value of + `None`. + validation_freq: Only relevant if validation data is provided. Integer or + `collections.abc.Container` instance (e.g. list, tuple, etc.). If an + integer, specifies how many training epochs to run before a new + validation run is performed, e.g. `validation_freq=2` runs + validation every 2 epochs. If a Container, specifies the epochs on + which to run validation, e.g. `validation_freq=[1, 2, 10]` runs + validation at the end of the 1st, 2nd, and 10th epochs. + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + validation_in_fit: if true, then this method is invoked from within + training iteration (for validation). In the case where `val_inputs` is + a dataset, this flag indicates that its iterator and feed values are + already created so should properly reuse resources. + prepared_feed_values_from_dataset: if True, `inputs` is a list of feed + tensors returned from `_prepare_feed_values` call on the validation + dataset, so do not call it again on `inputs`. Should only be used for + inline validation (i.e., only if `validation_in_fit` is also True). + steps_name: The string name of the steps argument, either `steps`, + `validation_steps`, or `steps_per_epoch`. Only used for error message + formatting. + **kwargs: Additional arguments for backwards compatibility. + + Returns: + - In TRAIN mode: `History` object. + - In TEST mode: Evaluation metrics. + - In PREDICT mode: Outputs of the Model called on inputs. + + Raises: + ValueError: in case of invalid arguments. + """ + # Backwards compatibility. + if 'steps' in kwargs: + steps_per_epoch = kwargs.pop('steps') + if kwargs: + raise TypeError('Unknown arguments: %s' % (kwargs,)) + + # In case we were passed a dataset, we extract symbolic tensors from it. + reset_dataset_after_each_epoch = False + input_iterator = None + is_dataset = isinstance(inputs, + (data_types.DatasetV1, data_types.DatasetV2)) + # TODO(fchollet): consider moving `steps_per_epoch` inference to + # _standardize_user_data and set reset_dataset_after_each_epoch as an + # attribute on the dataset instance. + if is_dataset: + if steps_per_epoch is None: + reset_dataset_after_each_epoch = True + steps_per_epoch = training_utils_v1.infer_steps_for_dataset( + model, inputs, steps_per_epoch, epochs=epochs, steps_name=steps_name) + input_iterator = _get_iterator(inputs, model._distribution_strategy) + + # Enter tf.distribute.Strategy scope. + if model._distribution_strategy: + scope = distributed_training_utils_v1.distributed_scope( + strategy=model._distribution_strategy, + learning_phase=(1 if mode == ModeKeys.TRAIN else 0)) + scope.__enter__() + + use_steps = is_dataset or steps_per_epoch is not None + do_validation = val_inputs is not None + + # Prepare input data. + inputs = input_iterator or inputs + if validation_in_fit and prepared_feed_values_from_dataset: + # When invoking validation in training loop, avoid creating iterator and + # list of feed values for the same validation dataset multiple times (which + # essentially would call `iterator.get_next()` that slows down execution and + # leads to OOM errors eventually. + ins = inputs + else: + ins = _prepare_feed_values(model, inputs, targets, sample_weights, mode) + # `ins` is a function when a distribute strategy is used in Eager mode. In + # that case `is_dataset` is True. The code branches that have requirements + # about the type of `ins` do not trigger in the distributed case. + + if not is_dataset: + num_samples_or_steps = _get_num_samples_or_steps(ins, batch_size, + steps_per_epoch) + else: + num_samples_or_steps = steps_per_epoch + + # Update sample_weight_mode of the model if sample_weights is specified by the + # user. We need to call this function after we have a handle on the inputs + # (both numpy arrays and datasets) in order to determine if the user has + # specified sample_weights. + _update_sample_weight_mode(model, mode, ins) + + # Get step function and loop type. As part of building the execution + # function we recompile the metrics based on the updated + # sample_weight_mode value. + f = _make_execution_function(model, mode) + + # Prepare validation data. Hold references to the iterator and the input list + # to properly reinitialize and reuse in multiple validation passes. + val_iterator = None + if isinstance(val_inputs, (data_types.DatasetV1, data_types.DatasetV2)): + if validation_steps is None: + # Because we pass an iterator feed instead of a Dataset to the eval + # model_iteration() call, it will not trigger the dataset-input path + # that determines the number of steps required. To avoid this issue, + # set validation_steps here if validation_steps is None. + validation_steps = training_utils_v1.infer_steps_for_dataset( + model, + val_inputs, + validation_steps, + epochs=epochs, + steps_name='validation_steps') + val_iterator = _get_iterator(val_inputs, model._distribution_strategy) + val_inputs = _prepare_feed_values( + model, val_iterator, val_targets, val_sample_weights, ModeKeys.TEST) + # Get num steps for printing. + val_samples_or_steps = validation_steps + else: + # Get num samples for printing. + val_samples_or_steps = val_inputs and nest.flatten( + val_inputs)[0].shape[0] or None + + if mode == ModeKeys.TRAIN and verbose: + _print_train_info(num_samples_or_steps, val_samples_or_steps, is_dataset) + + # Configure callbacks. + count_mode = 'steps' if use_steps else 'samples' + callbacks = cbks.configure_callbacks( + callbacks, + model, + do_validation=do_validation, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + samples=num_samples_or_steps, + count_mode=count_mode, + verbose=verbose, + mode=mode) + + # Find beforehand arrays that need sparse-to-dense conversion. + if issparse is not None and not use_steps: + indices_for_conversion_to_dense = [] + feed = _get_model_feed(model, mode) + for i, (input_data, feed_tensor) in enumerate(zip(ins, feed)): + if issparse(input_data) and not backend.is_sparse(feed_tensor): + indices_for_conversion_to_dense.append(i) + + # Select aggregation method. + if mode == ModeKeys.PREDICT: + aggregator = training_utils_v1.OutputsAggregator( + use_steps, + num_samples=None if steps_per_epoch else num_samples_or_steps, + steps=steps_per_epoch) + else: + aggregator = training_utils_v1.MetricsAggregator( + use_steps, + num_samples=None if steps_per_epoch else num_samples_or_steps, + steps=steps_per_epoch) + + if model._compile_distribution: + distributed_training_utils_v1._copy_weights_to_distributed_model( + model, mode) + + callbacks.model.stop_training = False + callbacks._call_begin_hook(mode) + + initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode) + + for epoch in range(initial_epoch, epochs): + if callbacks.model.stop_training: + break + + # Setup work for each epoch + epoch_logs = {} + if mode != ModeKeys.PREDICT: + # Collecting and resetting metrics has non-zero cost and will needlessly + # slow down model.predict. + model.reset_metrics() + if mode == ModeKeys.TRAIN: + callbacks.on_epoch_begin(epoch, epoch_logs) + + if use_steps: + # Step-wise loop. + if steps_per_epoch is None: + # Loop over dataset until `OutOfRangeError` is raised. + target_steps = np.inf + else: + # Loop over dataset for the specified number of steps. + target_steps = steps_per_epoch + + step = 0 + while step < target_steps: + batch_logs = {'batch': step, 'size': 1} + callbacks._call_batch_hook(mode, 'begin', step, batch_logs) + + # Get outputs. + try: + # `ins` can be callable in tf.distribute.Strategy + eager case. + if not callable(ins) or (model._distribution_strategy and + not distributed_training_utils_v1 + .is_distributing_by_cloning(model)): + actual_inputs = ins + else: + actual_inputs = ins() + batch_outs = f(actual_inputs) + except errors.OutOfRangeError: + if is_dataset: + # The dataset passed by the user ran out of batches. + # Now we know the cardinality of the dataset. + # If steps_per_epoch was specified, then running out of data is + # unexpected, so we stop training and inform the user. + if steps_per_epoch: + callbacks.model.stop_training = True + logging.warning( + 'Your dataset ran out of data; interrupting training. ' + 'Make sure that your dataset can generate at least ' + '`%s * epochs` batches (in this case, %d batches). ' + 'You may need to use the repeat() function when ' + 'building your dataset.' + % (steps_name, steps_per_epoch * epochs)) + elif step > 0: + steps_per_epoch = step + aggregator.steps = steps_per_epoch + else: + # We ran out of batches while the user passed an iterator (legacy). + callbacks.model.stop_training = True + logging.warning( + 'Your dataset iterator ran out of data; ' + 'interrupting training. Make sure that your iterator ' + 'can generate at least `%s * epochs` ' + 'batches (in this case, %d batches). You may need to' + 'use the repeat() function when building your ' + 'dataset.' % (steps_name, steps_per_epoch * epochs)) + break + + if not isinstance(batch_outs, list): + batch_outs = [batch_outs] + + if model._distribution_strategy: + batch_outs = ( + distributed_training_utils_v1._per_replica_aggregate_batch( + model._distribution_strategy, batch_outs, model, mode)) + + # Aggregate results. + if step == 0: + aggregator.create(batch_outs) + aggregator.aggregate(batch_outs) + + # Callbacks batch end. + batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) + callbacks._call_batch_hook(mode, 'end', step, batch_logs) + step += 1 + + if callbacks.model.stop_training: + break + else: + # Sample-wise loop. + index_array = np.arange(num_samples_or_steps) + if shuffle == 'batch': + index_array = training_utils_v1.batch_shuffle(index_array, batch_size) + elif shuffle: + np.random.shuffle(index_array) + batches = make_batches(num_samples_or_steps, batch_size) + for batch_index, (batch_start, batch_end) in enumerate(batches): + batch_ids = index_array[batch_start:batch_end] + # Slice into a batch. + if len(batches) == 1: + # If we only have one batch, do not slice. This takes care of + # composite tensors in non-Dataset modes; we currently don't support + # slicing them. + # TODO(b/133517906): Add slicing support. + ins_batch = ins + else: + try: + if ins and isinstance(ins[-1], int): + # Do not slice the training phase flag. + ins_batch = slice_arrays(ins[:-1], batch_ids) + [ins[-1]] + else: + ins_batch = slice_arrays(ins, batch_ids) + except TypeError: + raise TypeError('TypeError while preparing batch. ' + 'If using HDF5 input data, ' + 'pass shuffle="batch".') + + # Sparse to dense conversion. + if issparse is not None: + for i in indices_for_conversion_to_dense: + ins_batch[i] = ins_batch[i].toarray() + + # Callbacks batch_begin. + batch_logs = {'batch': batch_index, 'size': len(batch_ids)} + callbacks._call_batch_hook(mode, 'begin', batch_index, batch_logs) + + # Get outputs. + batch_outs = f(ins_batch) + if not isinstance(batch_outs, list): + batch_outs = [batch_outs] + + # Aggregate results. + if batch_index == 0: + aggregator.create(batch_outs) + aggregator.aggregate(batch_outs, batch_start, batch_end) + + # Callbacks batch end. + batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) + callbacks._call_batch_hook(mode, 'end', batch_index, batch_logs) + + if callbacks.model.stop_training: + break + + aggregator.finalize() + results = aggregator.results + epoch_logs = cbks.make_logs(model, epoch_logs, results, mode) + if len(results) == 1: + results = results[0] + + # Run the test loop every `validation_freq` epochs during training. + if (do_validation and + training_utils_v1.should_run_validation(validation_freq, epoch) and + not callbacks.model.stop_training): + + if model._compile_distribution: + # Since we create a new clone from the original model we need to copy + # the weights back to the original model before we can run validation. + distributed_training_utils_v1._copy_weights_to_original_model( + model, ModeKeys.TRAIN) + + val_results = model_iteration( + model, + val_inputs, + targets=val_targets, + sample_weights=val_sample_weights, + batch_size=batch_size, + steps_per_epoch=validation_steps, + callbacks=callbacks, + verbose=0, + mode=ModeKeys.TEST, + validation_in_fit=True, + prepared_feed_values_from_dataset=(val_iterator is not None), + steps_name='validation_steps') + if not isinstance(val_results, list): + val_results = [val_results] + epoch_logs = cbks.make_logs( + model, epoch_logs, val_results, mode, prefix='val_') + if val_iterator and epoch < epochs - 1: + _reinitialize_iterator(val_iterator, model._distribution_strategy) + + if mode == ModeKeys.TRAIN: + # Epochs only apply to `fit`. + callbacks.on_epoch_end(epoch, epoch_logs) + + # Reinitialize dataset iterator for the next epoch. + if reset_dataset_after_each_epoch and epoch < epochs - 1: + _reinitialize_iterator(input_iterator, model._distribution_strategy) + + model._successful_loop_finish = True + callbacks._call_end_hook(mode) + + if model._distribution_strategy: + if model._compile_distribution: + # TODO(priyag, psv): Copy back metrics to the original model as well? + distributed_training_utils_v1._copy_weights_to_original_model(model, mode) + scope.__exit__(None, None, None) + + if mode == ModeKeys.TRAIN: + return model.history + return results + + +def _get_model_feed(model, mode): + if mode == ModeKeys.PREDICT: + feed = model._feed_inputs + else: + feed = ( + model._feed_inputs + model._feed_targets + model._feed_sample_weights) + return feed + + +def _print_train_info(num_samples_or_steps, val_samples_or_steps, is_dataset): + increment = 'steps' if is_dataset else 'samples' + msg = 'Train on {0} {increment}'.format( + num_samples_or_steps, increment=increment) + if val_samples_or_steps: + msg += ', validate on {0} {increment}'.format( + val_samples_or_steps, increment=increment) + print(msg) + + +def _get_num_samples_or_steps(ins, batch_size, steps_per_epoch): + """Returns total number of samples (when training in batch mode) or steps.""" + if steps_per_epoch: + return steps_per_epoch + return training_utils_v1.check_num_samples(ins, batch_size, steps_per_epoch, + 'steps_per_epoch') + + +def _prepare_feed_values(model, inputs, targets, sample_weights, mode): + """Prepare feed values to the model execution function. + + Args: + model: Model to prepare feed values for. + inputs: List or dict of model inputs. + targets: Optional list of model targets. + sample_weights: Optional list of sample weight arrays. + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + + Returns: + Feed values for the model in the given mode. + """ + if model._distribution_strategy: + if isinstance(inputs, (data_types.DatasetV1, data_types.DatasetV2)): + inputs = distributed_training_utils_v1.get_iterator( + inputs, model._distribution_strategy) + + def get_distributed_inputs(): + return distributed_training_utils_v1._prepare_feed_values( + model, inputs, targets, sample_weights, mode) + + # In the eager case, we want to call the input method per step, so return + # a lambda from here that can be called. Note that this is applicable only + # in Distribution Strategy case as it follows the same code path for both + # eager and graph modes. + # TODO(priyag,omalleyt): Either we should move the training DS with + # IteratorBase to use training_generator code path, or figure out how to + # set a symbolic Iterator out of a Dataset when in eager mode. + if context.executing_eagerly(): + return get_distributed_inputs + else: + return get_distributed_inputs() + + if isinstance(inputs, (data_types.DatasetV1, data_types.DatasetV2, + iterator_ops.Iterator)): + inputs, targets, sample_weights = model._standardize_user_data( + inputs, + extract_tensors_from_dataset=True) + + inputs = training_utils_v1.ModelInputs(inputs).as_list() + targets = list(targets or []) + sample_weights = list(sample_weights or []) + ins = inputs + targets + sample_weights + if mode == ModeKeys.TRAIN and not isinstance( + backend.symbolic_learning_phase(), int): + ins += [True] # Add learning phase value. + return ins + + +def _get_iterator(inputs, distribution_strategy=None): + if distribution_strategy: + return distributed_training_utils_v1.get_iterator( + inputs, distribution_strategy) + return training_utils_v1.get_iterator(inputs) + + +def _reinitialize_iterator(iterator, distribution_strategy=None): + if distribution_strategy: + distributed_training_utils_v1.initialize_iterator( + iterator, distribution_strategy) + else: + training_utils_v1.initialize_iterator(iterator) + + +def _make_execution_function(model, mode): + """Makes function to run one step of model execution.""" + if model._distribution_strategy: + return distributed_training_utils_v1._make_execution_function(model, mode) + return model._make_execution_function(mode) + + +def _update_sample_weight_mode(model, mode, inputs): + """Updates the sample_weight_mode of a given model.""" + # Add a quick return to prevent us from calling model._feed_targets that + # accesses certain model properties that may not be set in the `PREDICT` mode. + if mode == ModeKeys.PREDICT: + return + + sample_weights = None + # `inputs` is the model's inputs + targets + sample_weights + + # learning phase placeholder if specified. To update the sample_weight_mode + # we need to determine if the user has passed sample weights as part of the + # input. + if not callable(inputs): + sample_weights = inputs[len(model._feed_inputs) + len(model._feed_targets):] + has_learning_phase_pl = (mode == ModeKeys.TRAIN and + not isinstance(backend.symbolic_learning_phase(), + int)) + if has_learning_phase_pl: + sample_weights = sample_weights[:-1] + model._update_sample_weight_modes(sample_weights=sample_weights) + + # Call the DistributionStrategy specific function to update the + # sample_weight_mode on the model. + if model._distribution_strategy: + distributed_training_utils_v1._update_sample_weight_modes(model, mode, + sample_weights) + +# For backwards compatibility for internal users of these loops. +fit_loop = functools.partial(model_iteration, mode=ModeKeys.TRAIN) +test_loop = functools.partial( + model_iteration, mode=ModeKeys.TEST, shuffle=False) +predict_loop = functools.partial( + model_iteration, mode=ModeKeys.PREDICT, shuffle=False) + + +class ArrayLikeTrainingLoop(training_utils_v1.TrainingLoop): + """TrainingLoop that handle inputs like array. + + This is the default handler for most of the input data types, includes + symbolic tensors or Numpy array-like, Datasets and iterators in graph mode + (since they generate symbolic tensors). This Function is used to handle model + with `run_eagerly` = False. + """ + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, + steps_per_epoch, x) + + x, y, sample_weights = model._standardize_user_data( + x, + y, + sample_weight=sample_weight, + class_weight=class_weight, + batch_size=batch_size, + check_steps=True, + steps_name='steps_per_epoch', + steps=steps_per_epoch, + validation_split=validation_split, + shuffle=shuffle) + + if validation_data: + val_x, val_y, val_sample_weights = model._prepare_validation_data( + validation_data, batch_size, validation_steps) + elif validation_split and 0. < validation_split < 1.: + (x, y, sample_weights, val_x, val_y, val_sample_weights + ) = training_utils_v1.split_training_and_validation_data( + x, y, sample_weights, validation_split) + else: + if validation_steps: + raise ValueError('`validation_steps` should not be specified if ' + '`validation_data` is None.') + val_x, val_y, val_sample_weights = None, None, None + + return fit_loop( + model, + inputs=x, + targets=y, + sample_weights=sample_weights, + batch_size=batch_size, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + val_inputs=val_x, + val_targets=val_y, + val_sample_weights=val_sample_weights, + shuffle=shuffle, + initial_epoch=initial_epoch, + steps_per_epoch=steps_per_epoch, + validation_steps=validation_steps, + validation_freq=validation_freq, + steps_name='steps_per_epoch') + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + x, y, sample_weights = model._standardize_user_data( + x, + y, + sample_weight=sample_weight, + batch_size=batch_size, + check_steps=True, + steps_name='steps', + steps=steps) + return test_loop( + model, + inputs=x, + targets=y, + sample_weights=sample_weights, + batch_size=batch_size, + verbose=verbose, + steps=steps, + callbacks=callbacks) + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + x, _, _ = model._standardize_user_data( + x, check_steps=True, steps_name='steps', steps=steps) + return predict_loop( + model, + x, + batch_size=batch_size, + verbose=verbose, + steps=steps, + callbacks=callbacks) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_distributed_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_distributed_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3477464dbb4fc080c1d6f8321517d3651babb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_distributed_v1.py @@ -0,0 +1,794 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Part of the Keras training engine related to distributed training.""" +# pylint: disable=protected-access + +import numpy as np +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import reduce_util as ds_reduce_util +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks as cbks +from tensorflow.python.keras.distribute import distribute_coordinator_utils as dc +from tensorflow.python.keras.distribute import distributed_training_utils_v1 as dist_utils +from tensorflow.python.keras.engine import partial_batch_padding_handler as padding_util +from tensorflow.python.keras.engine import training_arrays_v1 +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.utils.generic_utils import Progbar +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.platform import tf_logging as logging + + +def _per_replica_execution_function(model, mode): + exec_func = model._make_execution_function(mode) + return (exec_func.inputs, exec_func.outputs, exec_func.updates_op, + exec_func.session_kwargs) + + +def _build_model(strategy, model, mode, inputs, targets=None): + if model._compile_distribution: + dist_utils.clone_model_on_replicas( + model, strategy, mode, inputs=inputs, targets=targets) + else: + dist_utils._build_distributed_network(model, strategy, mode, inputs, + targets) + + +def _make_train_step_fn(model, mode, strategy, output_labels): + """Create step fn. + + Args: + model: a Keras Model instance. + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + strategy: a `tf.distribute.Strategy` instance. + output_labels: the output labels for the step function. + + Returns: + A step function to run by `tf.distribute.Strategy`. + """ + + def _step_fn(ctx, inputs): + """A step fn that returns update ops.""" + if isinstance(inputs, (tuple, list)) and len(inputs) == 2: + inputs, targets = inputs + else: + targets = None + + # When input feature is a dictionary of tensors, dictionary is flattended + # to an array and passed as a model input. This results in input mismatch + # when model input layer names are not sorted in alphabetical order as + # `nest.flatten()`sorts dictionary elements by keys. As so, transform input + # tensors into an array and order it along `model._feed_input_names`. + if isinstance(inputs, dict): + inputs = [inputs[input_name] for input_name in model._feed_input_names] + + _build_model(strategy, model, mode, inputs, targets) + + (grouped_inputs, grouped_outputs, grouped_updates, + grouped_session_args) = strategy.extended.call_for_each_replica( + _per_replica_execution_function, + args=(dist_utils.get_distributed_model(model, mode), mode)) + (all_inputs, all_outputs, all_updates, + all_session_args) = dist_utils.unwrap_values(strategy, grouped_inputs, + grouped_outputs, + grouped_updates, + grouped_session_args) + combined_fn = backend.function( + all_inputs, + all_outputs, + updates=all_updates, + name='distributed_' + str(mode) + '_function', + **all_session_args) + + for label, output in zip(output_labels, combined_fn.outputs): + if label == 'loss': + reduce_op = ds_reduce_util.ReduceOp.SUM + else: + # We reduce all other metrics using mean for now. This is temporary + # workaround until new metrics are in place. + reduce_op = ds_reduce_util.ReduceOp.MEAN + ctx.set_last_step_output(label, output, reduce_op) + + # TODO(priyag, sourabhbajaj): Ignoring these things from the combined_fn: + # feed_dict, session kwargs, run options, run_metadata for now. These should + # be handled appropriately + return combined_fn.updates_op + + return _step_fn + + +def experimental_tpu_fit_loop(model, + dataset, + epochs=100, + verbose=1, + callbacks=None, + initial_epoch=0, + steps_per_epoch=None, + val_dataset=None, + validation_steps=None, + validation_freq=1): + """Fit loop for training with TPU tf.distribute.Strategy. + + Args: + model: Keras Model instance. + dataset: Dataset that returns inputs and targets + epochs: Number of times to iterate over the data + verbose: Integer, Verbosity mode, 0, 1 or 2 + callbacks: List of callbacks to be called during training + initial_epoch: Epoch at which to start training + (useful for resuming a previous training run) + steps_per_epoch: Total number of steps (batches of samples) + before declaring one epoch finished and starting the + next epoch. Ignored with the default value of `None`. + val_dataset: Dataset for validation data. + validation_steps: Number of steps to run validation for + (only if doing validation from data tensors). + Ignored with the default value of `None`. + validation_freq: Only relevant if validation data is provided. Integer or + `collections.abc.Container` instance (e.g. list, tuple, etc.). If an + integer, specifies how many training epochs to run before a new + validation run is performed, e.g. `validation_freq=2` runs + validation every 2 epochs. If a Container, specifies the epochs on + which to run validation, e.g. `validation_freq=[1, 2, 10]` runs + validation at the end of the 1st, 2nd, and 10th epochs. + + Returns: + Returns `None`. + + Raises: + ValueError: in case of invalid arguments. + """ + mode = ModeKeys.TRAIN + + current_strategy = model._distribution_strategy + iteration_value = min(steps_per_epoch, + current_strategy.extended.steps_per_run) + steps_per_run = backend.variable( + value=iteration_value, + dtype='int32', + name='steps_per_run') + + # TODO(fchollet): add support for `steps_per_epoch=None` in TPU loops. + iterator = dist_utils.get_iterator(dataset, current_strategy) + + scope = dist_utils.distributed_scope( + strategy=current_strategy, learning_phase=1) + scope.__enter__() + + out_labels = model.metrics_names or [] + + step_fn = _make_train_step_fn(model, ModeKeys.TRAIN, current_strategy, + out_labels) + + # Add initial dummy values for loss and other metric tensors. + initial_loop_values = {} + initial_loop_values['loss'] = constant_op.constant(1e7) + for m in model._get_training_eval_metrics(): + tensor = m.result() + initial_loop_values[m.name] = array_ops.zeros(tensor.shape, tensor.dtype) + + ctx = current_strategy.extended.experimental_run_steps_on_iterator( + step_fn, iterator, iterations=steps_per_run, + initial_loop_values=initial_loop_values) + train_op = ctx.run_op + output_tensors = ctx.last_step_outputs + + do_validation = bool(validation_steps) + + if model._compile_distribution: + dist_utils._copy_weights_to_distributed_model(model, mode) + + callbacks = cbks.configure_callbacks( + callbacks, + model, + do_validation=do_validation, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + verbose=verbose, + count_mode='steps', + mode=mode) + + # Calculate the steps each time on the device. + steps_to_run = ([current_strategy.extended.steps_per_run] * + (steps_per_epoch // + current_strategy.extended.steps_per_run)) + if steps_per_epoch % current_strategy.extended.steps_per_run: + steps_to_run.append( + steps_per_epoch % current_strategy.extended.steps_per_run) + target_steps = len(steps_to_run) + + callbacks._call_begin_hook(mode) + + initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode) + + for epoch in range(initial_epoch, epochs): + dist_utils._reset_metrics(model) + callbacks.on_epoch_begin(epoch) + epoch_logs = {} + step_index = 0 + prev_step_count = None + current_step = 0 + while current_step < target_steps: + step_count = steps_to_run[current_step] + batch_logs = {'batch': step_index, 'size': 1, 'num_steps': step_count} + callbacks._call_batch_hook(mode, 'begin', step_index, batch_logs) + if prev_step_count is None or step_count != prev_step_count: + backend.get_session().run(steps_per_run.assign(step_count)) + prev_step_count = step_count + try: + _, outputs = backend.batch_get_value([train_op, output_tensors]) + except errors.OutOfRangeError: + logging.warning('Your dataset iterator ran out of data; ' + 'interrupting training. Make sure that your dataset ' + 'can generate at least `steps_per_epoch * epochs` ' + 'batches (in this case, %d batches).' % + steps_per_epoch * epochs) + break + + batch_logs.update(outputs) + callbacks._call_batch_hook(mode, 'end', step_index, batch_logs) + step_index = step_index + step_count + current_step += 1 + + if callbacks.model.stop_training: + break + + if (do_validation and + training_utils_v1.should_run_validation(validation_freq, epoch)): + logging.info('Running validation at fit epoch: %s', epoch) + + if model._compile_distribution: + # Since we create a new clone from the original model we need to copy + # the weights back to the original model before we can run validation. + dist_utils._copy_weights_to_original_model(model, ModeKeys.TRAIN) + + val_outs = experimental_tpu_test_loop( # pylint: disable=undefined-variable + model, + val_dataset, + steps=validation_steps, + verbose=verbose, + callbacks=callbacks) + if not isinstance(val_outs, list): + val_outs = [val_outs] + # Same labels assumed. + for label, val_out in zip(out_labels, val_outs): + epoch_logs['val_' + label] = val_out + + callbacks.on_epoch_end(epoch, epoch_logs) + if callbacks.model.stop_training: + break + model._successful_loop_finish = True + callbacks._call_end_hook(mode) + + if model._compile_distribution: + # Copy the weights back from the replicated model to the original model. + dist_utils._copy_weights_to_original_model(model, ModeKeys.TRAIN) + scope.__exit__(None, None, None) + return model.history + + +def experimental_tpu_test_loop(model, + dataset, + verbose=0, + steps=None, + callbacks=None): + """Test loop for evaluating with TPU tf.distribute.Strategy. + + Args: + model: Keras Model instance. + dataset: Dataset for input data. + verbose: Integer, Verbosity mode 0 or 1. + steps: Total number of steps (batches of samples) + before declaring predictions finished. + Ignored with the default value of `None`. + callbacks: List of callbacks to be called during training + + Returns: + Scalar loss (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the outputs. + """ + mode = ModeKeys.TEST + current_strategy = model._distribution_strategy + iterator = dist_utils.get_iterator(dataset, current_strategy) + + scope = dist_utils.distributed_scope( + strategy=current_strategy, learning_phase=0) + scope.__enter__() + + out_labels = model.metrics_names + + def _test_step_fn(inputs): + """A fn that returns output of single test step.""" + if isinstance(inputs, (tuple, list)) and len(inputs) == 2: + inputs, targets = inputs + else: + targets = None + + (distribute_lib.get_replica_context().merge_call( + _build_model, args=(model, mode, inputs, targets))) + + (_, outputs, updates, _) = _per_replica_execution_function( + dist_utils.get_distributed_model(model, mode), mode) + with ops.control_dependencies([updates]): + return [array_ops.identity(out) for out in outputs] + + test_input_data = iterator.get_next() + per_replica_outputs = current_strategy.run( + _test_step_fn, args=(test_input_data,)) + output_tensors = {} + for label, output in zip(out_labels, per_replica_outputs): + if label == 'loss': + reduce_op = ds_reduce_util.ReduceOp.SUM + else: + # We reduce all other metrics using mean for now. This is temporary + # workaround until new metrics are in place. + reduce_op = ds_reduce_util.ReduceOp.MEAN + output_tensors[label] = current_strategy.reduce(reduce_op, output, + axis=None) + test_op = control_flow_ops.group(list(output_tensors.values())) + + if verbose >= 1: + progbar = Progbar(target=steps) + + if model._compile_distribution: + dist_utils._copy_weights_to_distributed_model(model, mode) + + dist_utils._reset_metrics(model) + + callbacks = cbks.configure_callbacks( + callbacks, + model, + do_validation=False, + epochs=1, + steps_per_epoch=steps, + verbose=verbose, + count_mode='steps', + mode=ModeKeys.TEST) + callbacks._call_begin_hook(mode) + + outs = [0.] * len(model.metrics_names) + if steps is not None: + target_steps = steps + else: + raise ValueError('Number of steps could not be inferred from the data, ' + 'please pass the steps argument.') + + current_step = 0 + while current_step < target_steps: + batch_logs = {'batch': current_step, 'size': 1} + callbacks._call_batch_hook(mode, 'begin', current_step, batch_logs) + try: + _, batch_outs = backend.batch_get_value([test_op, output_tensors]) + except errors.OutOfRangeError: + warning_msg = ( + 'Make sure that your dataset can generate at least ' + '`steps` batches (in this case, {} batches).'.format(steps)) + + logging.warning('Your dataset iterator ran out of data; ' + 'interrupting evaluation. ' + warning_msg) + target_steps = current_step + break + for i, label in enumerate(model.metrics_names): + if i == 0: + # Loss is stateless metrics. + outs[i] += batch_outs[label] + else: + # For all stateful metrics, the aggregation is handled by mirrored vars. + outs[i] = batch_outs[label] + + batch_logs = cbks.make_logs(model, batch_logs, outs, mode) + callbacks._call_batch_hook(mode, 'end', current_step, batch_logs) + if verbose == 1: + progbar.update(current_step + 1) + current_step += 1 + + if verbose >= 1: + # Progress bar finishes at the end. + progbar.update(target_steps) + callbacks._call_end_hook(mode) + + scope.__exit__(None, None, None) + if len(outs) >= 0: + outs[0] /= (target_steps) + + if len(outs) == 1: + return outs[0] + return outs + + +def experimental_tpu_predict_loop(model, + dataset, + verbose=0, + steps=None, + callbacks=None): + """Predict loop for predicting with TPU tf.distribute.Strategy. + + Args: + model: Keras Model instance. + dataset: Dataset for input data. + verbose: Integer, Verbosity mode 0 or 1. + steps: Total number of steps (batches of samples) + before declaring `_predict_loop` finished. + Ignored with the default value of `None`. + callbacks: List of callbacks to be called during training + + Returns: + Array of predictions (if the model has a single output) + or list of arrays of predictions + (if the model has multiple outputs). + """ + mode = ModeKeys.PREDICT + dataset_fully_shaped = dist_utils.is_dataset_shape_fully_defined(dataset) + padding_handler = None + if not dataset_fully_shaped: + # TODO(hongjunchoi): Investigate whether operations from + # PartialBatchPaddingHandler are unnecessarily pruned out + # during graph optimization. + padding_handler = padding_util.PartialBatchPaddingHandler( + model._feed_output_shapes) + batch_size, _, prefetch_buffer = input_lib._get_dataset_attributes(dataset) + padding_handler.padded_batch_size = batch_size + padding_handler.padding_mask = dataset.reduce(padding_handler.padding_mask, + padding_handler.update_mask) + + dataset = dataset.map(padding_handler.pad_batch) + dataset = dataset.unbatch() + # Upon this point, it is guaranteed that the dataset does not + # have partial batches. Thus, we set `drop_remainder=True` to + # get static shape information about the elements in the dataset. + dataset = dataset.batch(batch_size, drop_remainder=True) + + if prefetch_buffer is not None: + dataset = dataset.prefetch(prefetch_buffer) + + current_strategy = model._distribution_strategy + iterator = dist_utils.get_iterator(dataset, current_strategy) + + scope = dist_utils.distributed_scope( + strategy=current_strategy, learning_phase=0) + scope.__enter__() + + def _predict_step_fn(inputs): + """A fn that returns output of single prediction step.""" + + (distribute_lib.get_replica_context().merge_call( + _build_model, args=(model, mode, inputs))) + + (_, outputs, updates, _) = _per_replica_execution_function( + dist_utils.get_distributed_model(model, mode), mode) + + with ops.control_dependencies([updates]): + return [array_ops.identity(out) for out in outputs] + + # TODO(hongjunchoi): When numpy array is passed as an input to `predict()` + # use numpy arrays directly to avoid cumulating unnecessary input pipeline + # ops. + predict_input_data = iterator.get_next() + per_replica_outputs = current_strategy.run( + _predict_step_fn, args=(predict_input_data,)) + output_tensors = dist_utils.flatten_per_replica_values( + current_strategy, per_replica_outputs) + + if verbose >= 1: + progbar = Progbar(target=steps) + + if model._compile_distribution: + dist_utils._copy_weights_to_distributed_model(model, mode) + + dist_utils._reset_metrics(model) + + callbacks = cbks.configure_callbacks( + callbacks, + model, + do_validation=False, + epochs=1, + steps_per_epoch=steps, + verbose=verbose, + count_mode='steps', + mode=mode) + callbacks._call_begin_hook(mode) + + # Since we do not know how many samples we will see, we cannot pre-allocate + # the returned Numpy arrays. Instead, we store one array per batch seen + # and concatenate them upon returning. + num_model_outputs = len(model.output_names) + unconcatenated_outs = [[] for _ in range(num_model_outputs)] + if steps is not None: + target_steps = steps + else: + raise ValueError('Number of steps could not be inferred from the data, ' + 'please pass the steps argument.') + + current_step = 0 + while current_step < target_steps: + batch_logs = {'batch': current_step, 'size': 1} + callbacks._call_batch_hook(mode, 'begin', current_step, batch_logs) + try: + predict_ops = control_flow_ops.group(output_tensors) + _, batch_outs = backend.batch_get_value([predict_ops, output_tensors]) + + except errors.OutOfRangeError: + warning_msg = ( + 'Make sure that your dataset can generate at least ' + '`steps` batches (in this case, {} batches).'.format(steps)) + + logging.warning('Your dataset iterator ran out of data; ' + 'interrupting evaluation. ' + warning_msg) + break + + # TODO(priyag): maybe need to unwrap the outputs first for MirroredStrategy. + for i in range(num_model_outputs): + output_start_index = i * current_strategy.num_replicas_in_sync + output_end_index = ( + output_start_index + current_strategy.num_replicas_in_sync) + single_model_output = batch_outs[output_start_index:output_end_index] + unconcatenated_outs[i].extend(single_model_output) + + batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) + callbacks._call_batch_hook(mode, 'end', current_step, batch_logs) + if verbose == 1: + progbar.update(current_step + 1) + current_step += 1 + + if verbose >= 1: + # Progress bar finishes at the end. + progbar.update(current_step) + + callbacks._call_end_hook(mode) + + scope.__exit__(None, None, None) + + if len(unconcatenated_outs) == 1: + prediction_result = np.concatenate(unconcatenated_outs[0], axis=0) + else: + prediction_result = [ + np.concatenate(out, axis=0) for out in unconcatenated_outs + ] + + if padding_handler: + prediction_result = padding_handler.apply_mask(prediction_result) + + return prediction_result + + +class DistributionSingleWorkerTrainingLoop(training_utils_v1.TrainingLoop): + """Training loop for distribution strategy with single worker.""" + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + **kwargs): + """Fit loop for Distribution Strategies.""" + dist_utils.validate_callbacks(input_callbacks=callbacks, + optimizer=model.optimizer) + dist_utils.validate_inputs(x, y) + + batch_size, steps_per_epoch = dist_utils.process_batch_and_step_size( + model._distribution_strategy, + x, + batch_size, + steps_per_epoch, + ModeKeys.TRAIN, + validation_split=validation_split) + batch_size = model._validate_or_infer_batch_size( + batch_size, steps_per_epoch, x) + dataset = model._distribution_standardize_user_data( + x, y, + sample_weight=sample_weight, + class_weight=class_weight, + batch_size=batch_size, + validation_split=validation_split, + shuffle=shuffle, + epochs=epochs) + if not dist_utils.is_distributing_by_cloning(model): + with model._distribution_strategy.scope(): + (dataset, _, _) = model._standardize_user_data( + dataset, + sample_weight=sample_weight, + class_weight=class_weight, + batch_size=batch_size, + validation_split=validation_split, + shuffle=shuffle) + + val_dataset = None + if validation_data: + val_x, val_y, val_sample_weights = ( + training_utils_v1.unpack_validation_data(validation_data)) + dist_utils.validate_inputs(val_x, val_y) + _, validation_steps = dist_utils.process_batch_and_step_size( + model._distribution_strategy, val_x, batch_size, validation_steps, + ModeKeys.TEST) + + val_dataset = model._distribution_standardize_user_data( + val_x, val_y, + sample_weight=val_sample_weights, + class_weight=None, + batch_size=batch_size, + validation_split=validation_split, + shuffle=shuffle, + allow_partial_batch=True) + elif validation_split: + raise ValueError('validation_split argument is not supported with ' + 'distribution strategies.') + + if backend.is_tpu_strategy(model._distribution_strategy): + steps_per_epoch = training_utils_v1.infer_steps_for_dataset( + model, dataset, steps_per_epoch, epochs, steps_name='steps_per_epoch') + if steps_per_epoch is None: + raise ValueError('Number of steps could not be inferred from the data, ' + 'please pass the steps_per_epoch argument.') + + if not context.executing_eagerly(): + # Run TPU training in a custom loop in graph mode. + return experimental_tpu_fit_loop( + model, + dataset, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + val_dataset=val_dataset, + initial_epoch=initial_epoch, + steps_per_epoch=steps_per_epoch, + validation_steps=validation_steps, + validation_freq=validation_freq) + + return training_arrays_v1.fit_loop( + model, + dataset, + batch_size=batch_size, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + val_inputs=val_dataset, + shuffle=shuffle, + initial_epoch=initial_epoch, + steps_per_epoch=steps_per_epoch, + validation_steps=validation_steps, + validation_freq=validation_freq, + steps_name='steps_per_epoch') + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + **kwargs): + """Evaluate loop for Distribution Strategies.""" + dist_utils.validate_inputs(x, y) + batch_size, steps = dist_utils.process_batch_and_step_size( + model._distribution_strategy, x, batch_size, steps, ModeKeys.TEST) + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + dataset = model._distribution_standardize_user_data( + x, y, + sample_weight=sample_weight, + batch_size=batch_size, + allow_partial_batch=True) + + if backend.is_tpu_strategy(model._distribution_strategy): + steps = training_utils_v1.infer_steps_for_dataset( + model, dataset, steps, steps_name='steps') + if steps is None: + raise ValueError('Number of steps could not be inferred from the data, ' + 'please pass the steps argument.') + + if not context.executing_eagerly(): + # Run TPU evaluation in a custom loop in graph mode. + return experimental_tpu_test_loop( + model, dataset, verbose=verbose, steps=steps, callbacks=callbacks) + + return training_arrays_v1.test_loop( + model, + inputs=dataset, + batch_size=batch_size, + verbose=verbose, + steps=steps, + callbacks=callbacks) + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + **kwargs): + """Predict loop for Distribution Strategies.""" + dist_utils.validate_inputs(x=x, y=None) + batch_size, steps = dist_utils.process_batch_and_step_size( + model._distribution_strategy, x, batch_size, steps, ModeKeys.PREDICT) + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + dataset = model._distribution_standardize_user_data( + x, + batch_size=batch_size, + allow_partial_batch=True) + if backend.is_tpu_strategy(model._distribution_strategy): + steps = training_utils_v1.infer_steps_for_dataset( + model, dataset, steps, steps_name='steps') + if steps is None: + raise ValueError('Number of steps could not be inferred from the data, ' + 'please pass the steps argument.') + if not context.executing_eagerly(): + return experimental_tpu_predict_loop( + model, dataset, verbose=verbose, steps=steps, callbacks=callbacks) + return training_arrays_v1.predict_loop( + model, + dataset, + batch_size=batch_size, + verbose=verbose, + steps=steps, + callbacks=callbacks) + + +def _train_with_multi_worker(method): + """Decorator that handles multi worker training with distribution strategy.""" + + def wrapper(model, **kwargs): + def _worker_fn(_): + callbacks = kwargs.pop('callbacks', None) + filtered_callbacks = dist_utils.filter_distributed_callbacks( + callbacks, model) + kwargs['callbacks'] = filtered_callbacks + return method(model, **kwargs) + + return dc.run_distribute_coordinator( + _worker_fn, + model._distribution_strategy) + + return wrapper + + +class DistributionMultiWorkerTrainingLoop(training_utils_v1.TrainingLoop): + """Training loop for distribution strategy with multiple worker.""" + + def __init__(self, single_worker_loop): + self._single_worker_loop = single_worker_loop + + def fit(self, *args, **kwargs): + return _train_with_multi_worker(self._single_worker_loop.fit)( + *args, **kwargs) + + def evaluate(self, *args, **kwargs): + return _train_with_multi_worker(self._single_worker_loop.evaluate)( + *args, **kwargs) + + def predict(self, *args, **kwargs): + # Currently predict is still using the single worker implementation. + return self._single_worker_loop.predict(*args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_eager_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_eager_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..4390559f2fedd353c683a43d15dcb3a6217c6597 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_eager_v1.py @@ -0,0 +1,370 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras training and evaluation routines for eager execution.""" +# pylint: disable=protected-access + +import numpy as np + +from tensorflow.python.eager.backprop import GradientTape +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.mixed_precision import loss_scale_optimizer +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest + + +def _eager_loss_fn(outputs, targets, loss_fn, output_name): + with backend.name_scope(output_name + '_loss'): + loss = loss_fn(targets, outputs) + return loss + + +def _eager_metrics_fn(model, outputs, targets, sample_weights=None, masks=None): + """Calculates the metrics for each output of the given model. + + Args: + model: The model on which metrics are being calculated. + outputs: The outputs of the given model. + targets: The predictions or targets of the given model. + sample_weights: Optional list of sample weights for each output. + masks: Optional list of masks for each output. + + Returns: + Returns the metric results for each output of the model. + """ + outputs = nest.flatten(outputs) + targets = nest.flatten(targets) + # Invoke all(weighted and unweighted) metrics. + metric_results = [] + if targets: + # Insert None values corresponding to the targets that need to be skipped + # on the model. + if len(model._targets) != len(targets): + new_targets = [ + None if t is None else targets.pop(0) for t in model._targets + ] + targets = new_targets + + metric_results = model._handle_metrics( + outputs, + targets=targets, + sample_weights=sample_weights, + masks=masks, + return_weighted_and_unweighted_metrics=True, + skip_target_masks=model._prepare_skip_target_masks()) + + # Add metric results from the `add_metric` metrics. + metric_results.extend([ + m.result() + for m in model.metrics + if m not in model._compile_metric_functions + ]) + return metric_results + + +def _model_loss(model, + inputs, + targets, + output_loss_metrics=None, + sample_weights=None, + training=False): + """Calculates the loss for a given model. + + Args: + model: The model on which metrics are being calculated. + inputs: Either a dictionary of inputs to the model or a list of input + arrays. + targets: List of target arrays. + output_loss_metrics: List of metrics that are used to aggregated output + loss values. + sample_weights: Optional list of sample weight arrays. + training: Whether the model should be run in inference or training mode. + + Returns: + Returns the model output, total loss, loss value calculated using the + specified loss function and masks for each output. The total loss includes + regularization losses and applies masking and sample weighting + to the loss value. + """ + # TODO(psv): Dedup code here with graph mode prepare_total_loss() fn. + # Used to keep track of the total loss value (stateless). + # eg., total_loss = loss_weight_1 * output_1_loss_fn(...) + + # loss_weight_2 * output_2_loss_fn(...) + + # layer losses. + total_loss = 0 + kwargs = {} + if model._expects_training_arg: + kwargs['training'] = training + if len(inputs) == 1 and not isinstance(inputs, dict): + inputs = inputs[0] + + # Allow mixed `NumPy` and `EagerTensor` input here. + if any( + isinstance(input_t, (np.ndarray, float, int)) + for input_t in nest.flatten(inputs)): + inputs = nest.map_structure( + tensor_conversion.convert_to_tensor_v2_with_dispatch, inputs + ) + + outs = model(inputs, **kwargs) + outs = nest.flatten(outs) + + if targets: + targets = training_utils_v1.cast_if_floating_dtype_and_mismatch( + targets, outs) + # TODO(sallymatson/psv): check if we should do same mismatch fix for weights + if sample_weights: + new_sample_weights = [] + for val in sample_weights: + if val is not None: + new_sample_weights.append(training_utils_v1.cast_if_floating_dtype( + tensor_conversion.convert_to_tensor_v2_with_dispatch(val))) + else: + new_sample_weights.append(None) + sample_weights = new_sample_weights + + masks = [getattr(t, '_keras_mask', None) for t in outs] + targets = nest.flatten(targets) + + # Used to keep track of individual output losses. + output_losses = [] + + with backend.name_scope('loss'): + loss_fns = [ + loss_fn for loss_fn in model.loss_functions if loss_fn is not None + ] + custom_losses = model.losses # Regularization losses + + if not loss_fns and not custom_losses: + if training: + raise ValueError('The model cannot be trained ' + 'because it has no loss to optimize.') + else: + raise ValueError('The model cannot be evaluated ' + 'because it has no loss to compute.') + + for i, loss_fn in enumerate(loss_fns): + weights = sample_weights[i] if sample_weights else None + mask = masks[i] + with backend.name_scope(model.output_names[i] + '_loss'): + if mask is not None: + mask = math_ops.cast(mask, outs[i].dtype) + # Update weights with mask. + if weights is None: + weights = mask + else: + # Update dimensions of weights to match with mask if possible. + weights = math_ops.cast(weights, outs[i].dtype) + mask, _, weights = ( + losses_utils.squeeze_or_expand_dimensions( + mask, sample_weight=weights)) + weights *= mask + + if hasattr(loss_fn, 'reduction'): + per_sample_losses = loss_fn.call(targets[i], outs[i]) + weighted_losses = losses_utils.compute_weighted_loss( + per_sample_losses, + sample_weight=weights, + reduction=losses_utils.ReductionV2.NONE) + loss_reduction = loss_fn.reduction + + # `AUTO` loss reduction defaults to `SUM_OVER_BATCH_SIZE` for all + # compile use cases. + if loss_reduction == losses_utils.ReductionV2.AUTO: + loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE + + # Compute the stateless loss value. + output_loss = losses_utils.reduce_weighted_loss( + weighted_losses, reduction=loss_reduction) + else: + # Compute the stateless loss value for a custom loss class. + # Here we assume that the class takes care of loss reduction + # because if this class returns a vector value we cannot + # differentiate between use case where a custom optimizer + # expects a vector loss value vs unreduced per-sample loss value. + output_loss = loss_fn(targets[i], outs[i], sample_weight=weights) + loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE + + # If the number of outputs is 1 then we don't append the loss metric + # associated with each model output. When there are multiple outputs + # associated with a model, each output's loss is calculated and returned + # as part of the loss_metrics. + if len(model.outputs) > 1: + # Keep track of the stateful output loss result. + output_losses.append(output_loss_metrics[i](output_loss)) + + # Scale output loss for distribution. For custom losses we assume + # reduction was mean. + if loss_reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE: + output_loss = losses_utils.scale_loss_for_distribution(output_loss) + total_loss += model._loss_weights_list[i] * output_loss + + # Add regularization losses + if custom_losses: + total_loss += losses_utils.scale_loss_for_distribution( + math_ops.add_n(custom_losses)) + return outs, total_loss, output_losses, masks + + +def _process_single_batch(model, + inputs, + targets, + output_loss_metrics=None, + sample_weights=None, + training=False): + """Calculate the loss and gradient for one input batch. + + The model weights are updated if training is set to True. + + Args: + model: Model whose loss has to be calculated. + inputs: List of input arrays. + targets: List of target arrays. + output_loss_metrics: List of metrics that are used to aggregated output + loss values. + sample_weights: Optional list of sample weight arrays. + training: The boolean represents if the weights of the model are updated. + 'fit' methods will set this to True while 'evaluate' methods will + set this to False. + + Returns: + output of the model, total loss, the loss and the mask + associated with each output. + + Raises: + ValueError: If the model has no loss to optimize. + """ + with backend.eager_learning_phase_scope(1 if training else 0), \ + training_utils.RespectCompiledTrainableState(model): + with GradientTape() as tape: + outs, total_loss, output_losses, masks = ( + _model_loss( + model, + inputs, + targets, + output_loss_metrics=output_loss_metrics, + sample_weights=sample_weights, + training=training)) + if isinstance(model.optimizer, loss_scale_optimizer.LossScaleOptimizer): + scaled_total_loss = model.optimizer.get_scaled_loss(total_loss) + else: + scaled_total_loss = total_loss + if training: + trainable_weights = model.trainable_weights + if trainable_weights: + # TODO(tanzheny) b/132690565: Provide mechanism for user to override + # model.train_on_batch. + if hasattr(model, '_backwards'): + model._backwards(tape, scaled_total_loss) + else: + grads = tape.gradient(scaled_total_loss, trainable_weights) + if isinstance(model.optimizer, + loss_scale_optimizer.LossScaleOptimizer): + grads = model.optimizer.get_unscaled_gradients(grads) + model.optimizer.apply_gradients(zip(grads, trainable_weights)) + else: + logging.warning('The list of trainable weights is empty. Make sure that' + ' you are not setting model.trainable to False before ' + 'compiling the model.') + return outs, total_loss, output_losses, masks + + +def train_on_batch(model, + inputs, + targets, + sample_weights=None, + output_loss_metrics=None): + """Calculates the loss and gradient updates for one input batch. + + Args: + model: Model whose loss has to be calculated. + inputs: Input batch data. + targets: Target batch data. + sample_weights: Sample weight batch data. + output_loss_metrics: List of metrics that are used to aggregated output + loss values. + + Returns: + Dict with three items: + 'total_loss': list with a single tensor for overall loss, + 'output_losses': list of tensors for loss corresponding to each of the + model output. Could be a empty list when model has only one output. + 'metrics': list of tensors for metric specified. + """ + inputs = training_utils_v1.cast_to_model_input_dtypes(inputs, model) + outs, total_loss, output_losses, masks = ( + _process_single_batch( + model, + inputs, + targets, + sample_weights=sample_weights, + training=True, + output_loss_metrics=output_loss_metrics)) + if not isinstance(outs, list): + outs = [outs] + metrics_results = _eager_metrics_fn( + model, outs, targets, sample_weights=sample_weights, masks=masks) + total_loss = nest.flatten(total_loss) + return {'total_loss': total_loss, + 'output_losses': output_losses, + 'metrics': metrics_results} + + +def test_on_batch(model, + inputs, + targets, + sample_weights=None, + output_loss_metrics=None): + """Calculates the loss for one input batch. + + Args: + model: Model whose loss has to be calculated. + inputs: Input batch data. + targets: Target batch data. + sample_weights: Sample weight batch data. + output_loss_metrics: List of metrics that are used to aggregated output + loss values. + + Returns: + Dict with three items: + 'total_loss': single tensor for overall loss, + 'output_losses': list of tensors for loss corresponding to each of the + model output. Could be a empty list when model has only one output. + 'metrics': list of tensors for metric specified. + """ + inputs = training_utils_v1.cast_to_model_input_dtypes(inputs, model) + + with backend.eager_learning_phase_scope(0): + outs, total_loss, output_losses, masks = ( + _model_loss( + model, + inputs, + targets, + sample_weights=sample_weights, + training=False, + output_loss_metrics=output_loss_metrics)) + if not isinstance(outs, list): + outs = [outs] + metrics_results = _eager_metrics_fn( + model, outs, targets, sample_weights=sample_weights, masks=masks) + total_loss = nest.flatten(total_loss) + + return {'total_loss': total_loss, + 'output_losses': output_losses, + 'metrics': metrics_results} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_generator_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_generator_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..a24b32369d83940c1921b13ff0340af89e6edcc1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_generator_v1.py @@ -0,0 +1,829 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Part of the Keras training engine related to Python generators of array data. +""" +# pylint: disable=protected-access + +import functools +import math + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks as cbks +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.utils import data_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest + + +def model_iteration(model, + data, + steps_per_epoch=None, + epochs=1, + verbose=1, + callbacks=None, + validation_data=None, + validation_steps=None, + validation_freq=1, + class_weight=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + shuffle=False, + initial_epoch=0, + mode=ModeKeys.TRAIN, + batch_size=None, + steps_name='steps', + **kwargs): + """Loop function for arrays of data with modes TRAIN/TEST/PREDICT. + + Args: + model: Keras Model instance. + data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or + `(x, y, sample_weights)`) or a generator or + `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. + steps_per_epoch: Total number of steps (batches of samples) before + declaring one epoch finished and starting the next epoch. Ignored with + the default value of `None`. + epochs: Number of times to iterate over the data. + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = progress bar, 2 = one line per epoch. + Note that the progress bar is not particularly useful when + logged to a file, so verbose=2 is recommended when not running + interactively (eg, in a production environment). + callbacks: List of callbacks to be called during training. + validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or + `(x, y)` or `(x, y, sample_weights)`) or a generator or + `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. + validation_steps: Total number of steps (batches of samples) before + declaring validation finished. + validation_freq: Only relevant if validation data is provided. Integer or + `collections.abc.Container` instance (e.g. list, tuple, etc.). If an + integer, specifies how many training epochs to run before a new + validation run is performed, e.g. `validation_freq=2` runs + validation every 2 epochs. If a Container, specifies the epochs on + which to run validation, e.g. `validation_freq=[1, 2, 10]` runs + validation at the end of the 1st, 2nd, and 10th epochs. + class_weight: Dictionary mapping class indices to a weight for the class. + max_queue_size: Integer. Maximum size for the generator queue. If + unspecified, `max_queue_size` will default to 10. + workers: Integer. Maximum number of processes to spin up when using + process-based threading. If unspecified, `workers` will default to 1. If + 0, will execute the generator on the main thread. + use_multiprocessing: Boolean. If `True`, use process-based threading. If + unspecified, `use_multiprocessing` will default to `False`. Note that + because this implementation relies on multiprocessing, you should not + pass non-picklable arguments to the generator as they can't be passed + easily to children processes. + shuffle: Boolean. Whether to shuffle the order of the batches at the + beginning of each epoch. Only used with instances of `Sequence` + (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not + `None`. + initial_epoch: Epoch at which to start training (useful for resuming a + previous training run). + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + batch_size: Integer batch size or None if unknown. Will only be used if + `data` is in NumPy/Tensor format. + steps_name: The string name of the steps argument, either `steps`, + `validation_steps`, or `steps_per_epoch`. Only used for error message + formatting. + **kwargs: Additional arguments for backwards compatibility. `steps` is + accepted as an alias for `steps_per_epoch`. + + Returns: + - In TRAIN mode: `History` object. + - In TEST mode: Evaluation metrics. + - In PREDICT mode: Outputs of the Model called on inputs. + + Raises: + ValueError: in case of invalid arguments. + """ + if 'steps' in kwargs: + steps_per_epoch = kwargs['steps'] + + # Determine the number of steps per epoch and whether we should reset the + # dataset at the end of each epoch. + reset_dataset_after_each_epoch = False + original_dataset = None + is_dataset = isinstance(data, (data_types.DatasetV2, data_types.DatasetV1)) + if is_dataset: + original_dataset = data + if steps_per_epoch is None: + reset_dataset_after_each_epoch = True + steps_per_epoch = training_utils_v1.infer_steps_for_dataset( + model, data, steps_per_epoch, epochs=epochs, steps_name=steps_name) + + # Convert to a format that supports `next(generator)`. + generator, steps_per_epoch = convert_to_generator_like( + data, + steps_per_epoch=steps_per_epoch, + batch_size=batch_size, + epochs=epochs - initial_epoch, + shuffle=shuffle) + + do_validation = validation_data is not None + is_sequence = isinstance(generator, data_utils.Sequence) + _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers, + steps_per_epoch, validation_data, validation_steps, mode, + kwargs) + + batch_function = _make_execution_function( + model, mode, class_weight=class_weight) + + # Create the queue for the generator. + enqueuer = None + if not is_dataset: + generator, enqueuer = _make_enqueued_generator( + generator, + workers=workers, + use_multiprocessing=use_multiprocessing, + max_queue_size=max_queue_size, + shuffle=shuffle) + + num_samples_or_steps, use_steps = _get_num_samples_or_steps( + data, steps_per_epoch) + + count_mode = 'steps' if use_steps else 'samples' + callbacks = cbks.configure_callbacks( + callbacks, + model, + do_validation=do_validation, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + batch_size=batch_size, + samples=num_samples_or_steps, + count_mode=count_mode, + verbose=verbose, + mode=mode) + + if mode == ModeKeys.PREDICT: + aggregator = training_utils_v1.OutputsAggregator( + True, steps=steps_per_epoch) + else: + aggregator = training_utils_v1.MetricsAggregator( + True, steps=steps_per_epoch) + + should_set_learning_phase = context.executing_eagerly() and model.run_eagerly + if should_set_learning_phase: + learning_phase_scope = backend.eager_learning_phase_scope( + 1 if mode == ModeKeys.TRAIN else 0) + learning_phase_scope.__enter__() + + callbacks.model.stop_training = False + callbacks._call_begin_hook(mode) + + initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode) + + for epoch in range(initial_epoch, epochs): + if callbacks.model.stop_training: + break + + # Setup work for each epoch. + model.reset_metrics() + epoch_logs = {} + if mode == ModeKeys.TRAIN: + callbacks.on_epoch_begin(epoch, epoch_logs) + + if steps_per_epoch is None: + # Loop over dataset until `OutOfRangeError` is raised. + target_steps = np.inf + else: + # Loop over dataset for the specified number of steps. + target_steps = steps_per_epoch + + step = 0 + while step < target_steps: + batch_data = _get_next_batch(generator) + if batch_data is None: + if is_dataset: + # The dataset passed by the user ran out of batches. + # Now we know the cardinality of the dataset. + # If steps_per_epoch was specified, then running out of data is + # unexpected, so we stop training and inform the user. + if steps_per_epoch: + callbacks.model.stop_training = True + logging.warning( + 'Your dataset ran out of data; interrupting training. ' + 'Make sure that your dataset can generate at least ' + '`%s * epochs` batches (in this case, %d batches). ' + 'You may need to use the repeat() function when ' + 'building your dataset.' + % (steps_name, steps_per_epoch * epochs)) + elif step > 0: + steps_per_epoch = step + aggregator.steps = steps_per_epoch + else: + # We ran out of batches while the user passed an iterator (legacy). + callbacks.model.stop_training = True + logging.warning( + 'Your dataset iterator ran out of data; ' + 'interrupting training. Make sure that your iterator ' + 'can generate at least `%s * epochs` ' + 'batches (in this case, %d batches). You may need to' + 'use the repeat() function when building your ' + 'dataset.' % (steps_name, steps_per_epoch * epochs)) + break + + # `batch_size` used for validation data if validation + # data is NumPy/EagerTensors. + batch_size = int(nest.flatten(batch_data)[0].shape[0]) + + # Callbacks batch begin. + batch_logs = {'batch': step, 'size': batch_size} + callbacks._call_batch_hook(mode, 'begin', step, batch_logs) + + is_deferred = not model._is_compiled + batch_outs = batch_function(*batch_data) + if not isinstance(batch_outs, list): + batch_outs = [batch_outs] + + if step == 0: + aggregator.create(batch_outs) + + if is_deferred: + # Set callbacks params. We do this here when model is compiled only + # in the first iteration of this loop (deferred build scenario). + cbks.set_callback_parameters( + callbacks, + model, + do_validation=do_validation, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + samples=num_samples_or_steps, + verbose=verbose, + mode=mode) + + # Aggregate results. + aggregator.aggregate(batch_outs) + + # Callbacks batch end. + batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) + callbacks._call_batch_hook(mode, 'end', step, batch_logs) + step += 1 + + if callbacks.model.stop_training: + break + + aggregator.finalize() + results = aggregator.results + epoch_logs = cbks.make_logs(model, epoch_logs, results, mode) + if len(results) == 1: + results = results[0] + + # Run the test loop every epoch during training. + if (do_validation and + training_utils_v1.should_run_validation(validation_freq, epoch) and + not callbacks.model.stop_training): + val_results = model_iteration( + model, + validation_data, + steps_per_epoch=validation_steps, + batch_size=batch_size, + class_weight=class_weight, + workers=workers, + use_multiprocessing=use_multiprocessing, + max_queue_size=max_queue_size, + callbacks=callbacks, + verbose=verbose, + mode=ModeKeys.TEST, + steps_name='validation_steps') + + if not isinstance(val_results, list): + val_results = [val_results] + epoch_logs = cbks.make_logs( + model, epoch_logs, val_results, mode, prefix='val_') + + if mode == ModeKeys.TRAIN: + # Epochs only apply to `fit`. + callbacks.on_epoch_end(epoch, epoch_logs) + + # Recreate dataset iterator for the next epoch. + if reset_dataset_after_each_epoch and epoch < epochs - 1: + generator = dataset_ops.make_one_shot_iterator(original_dataset) + + model._successful_loop_finish = True + callbacks._call_end_hook(mode) + + if enqueuer is not None: + enqueuer.stop() + + if should_set_learning_phase: + learning_phase_scope.__exit__(None, None, None) + + if mode == ModeKeys.TRAIN: + return model.history + return results + + +# Maintain compatibility with the existing names. +fit_generator = functools.partial(model_iteration, mode=ModeKeys.TRAIN) +evaluate_generator = functools.partial( + model_iteration, mode=ModeKeys.TEST, shuffle=False) +predict_generator = functools.partial( + model_iteration, mode=ModeKeys.PREDICT, shuffle=False) + + +def _get_next_batch(generator): + """Retrieves the next batch of input data.""" + try: + generator_output = next(generator) + except (StopIteration, errors.OutOfRangeError): + return None + + if not isinstance(generator_output, tuple): + # Always wrap in a tuple. + generator_output = (generator_output,) + if len(generator_output) not in [1, 2, 3]: + raise ValueError( + 'Output of generator should be a tuple of 1 or 2 or 3 ' + 'elements: (input,) or (input, target) or ' + '(input, target, sample_weights). Received {}'.format(generator_output)) + return generator_output + + +def _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers, + steps_per_epoch, validation_data, validation_steps, + mode, kwargs): + """Raises errors if arguments are invalid. + + Args: + is_sequence: Boolean, whether data is a `keras.utils.data_utils.Sequence` + instance. + is_dataset: Boolean, whether data is a dataset instance. + use_multiprocessing: Boolean. If `True`, use process-based threading. If + unspecified, `use_multiprocessing` will default to `False`. Note that + because this implementation relies on multiprocessing, you should not pass + non-picklable arguments to the generator as they can't be passed easily to + children processes. + workers: Integer. Maximum number of processes to spin up when using + process-based threading. If unspecified, `workers` will default to 1. If + 0, will execute the generator on the main thread. + steps_per_epoch: Total number of steps (batches of samples) before declaring + one epoch finished and starting the next epoch. Ignored with the default + value of `None`. + validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, + y)` or `(x, y, sample_weights)`) or a generator or + `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. + validation_steps: Total number of steps (batches of samples) before + declaring validation finished. + mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. + kwargs: Additional arguments for backwards compatibility. + + Raises: + ValueError: If `steps_per_epoch` or `validation_steps` are not passed + for data types that require them, or if unrecognized keyword + arguments are passed. + """ + if not is_sequence and use_multiprocessing and workers > 1: + logging.warning( + UserWarning('Using a generator with `use_multiprocessing=True`' + ' and multiple workers may duplicate your data.' + ' Please consider using the `keras.utils.Sequence`' + ' class.')) + + if steps_per_epoch is None and not is_dataset: + arg_name = 'steps_per_epoch' if mode == ModeKeys.TRAIN else 'steps' + raise ValueError('Please specify the number of steps via the ' + '`{}` argument.'.format(arg_name)) + + val_gen = ( + data_utils.is_generator_or_sequence(validation_data) or + isinstance(validation_data, iterator_ops.IteratorBase)) + if (val_gen and not isinstance(validation_data, data_utils.Sequence) and + not validation_steps): + raise ValueError('Please specify the `validation_steps` argument.') + + if any(k != 'steps' for k in kwargs): + raise ValueError('Invalid arguments passed: {}'.format( + [k for k in kwargs if k != 'steps'])) + + +def convert_to_generator_like(data, + batch_size=None, + steps_per_epoch=None, + epochs=1, + shuffle=False): + """Make a generator out of NumPy or EagerTensor inputs. + + Args: + data: Either a generator or `keras.utils.data_utils.Sequence` object or + `Dataset`, `Iterator`, or a {1,2,3}-tuple of NumPy arrays or EagerTensors. + If a tuple, the elements represent `(x, y, sample_weights)` and may be + `None` or `[None]`. + batch_size: Used when creating a generator out of tuples of NumPy arrays or + EagerTensors. + steps_per_epoch: Steps of the generator to run each epoch. If `None` the + number of steps will be read from the data (for + `keras.utils.data_utils.Sequence` types). + epochs: Total number of epochs to run. + shuffle: Whether the data should be shuffled. + + Returns: + - Generator, `keras.utils.data_utils.Sequence`, or `Iterator`. + + Raises: + - ValueError: If `batch_size` is not provided for NumPy or EagerTensor + inputs. + """ + if isinstance(data, tuple): + # Scrub `Nones` that might have been passed for `targets`, `sample_weights`. + data = tuple( + ele for ele in data if not all(e is None for e in nest.flatten(ele))) + + if data_utils.is_generator_or_sequence(data) or isinstance( + data, iterator_ops.IteratorBase): + if isinstance(data, data_utils.Sequence): + if steps_per_epoch is None: + steps_per_epoch = len(data) + return data, steps_per_epoch + if isinstance(data, data_types.DatasetV2): + return dataset_ops.make_one_shot_iterator(data), steps_per_epoch + + # Create generator from NumPy or EagerTensor Input. + num_samples = int(nest.flatten(data)[0].shape[0]) + if batch_size is None: + raise ValueError( + 'When passing input data as arrays, do not specify ' + '`steps_per_epoch`/`steps` argument. Please use `batch_size` instead.') + steps_per_epoch = int(math.ceil(num_samples / batch_size)) + + def _gen(data): + """Makes a generator out of a structure of NumPy/EagerTensors.""" + index_array = np.arange(num_samples) + for _ in range(epochs): + if shuffle: + np.random.shuffle(index_array) + batches = generic_utils.make_batches(num_samples, batch_size) + for (batch_start, batch_end) in batches: + batch_ids = index_array[batch_start:batch_end] + flat_batch_data = training_utils.slice_arrays( + nest.flatten(data), batch_ids, contiguous=(not shuffle)) + yield nest.pack_sequence_as(data, flat_batch_data) + + return _gen(data), steps_per_epoch + + +def _make_enqueued_generator(generator, + workers=1, + use_multiprocessing=False, + max_queue_size=10, + shuffle=False): + """Create a buffered queue of next elements of the generator.""" + is_sequence = isinstance(generator, data_utils.Sequence) + enqueuer = None + if workers > 0: + if is_sequence: + enqueuer = data_utils.OrderedEnqueuer( + generator, use_multiprocessing=use_multiprocessing, shuffle=shuffle) + else: + enqueuer = data_utils.GeneratorEnqueuer( + generator, use_multiprocessing=use_multiprocessing) + enqueuer.start(workers=workers, max_queue_size=max_queue_size) + output_generator = enqueuer.get() + else: + if is_sequence: + output_generator = data_utils.iter_sequence_infinite(generator) + else: + output_generator = generator + return output_generator, enqueuer + + +def _make_execution_function(model, mode, class_weight=None): + """Makes function to run one step of model execution.""" + if mode == ModeKeys.TRAIN: + f = functools.partial(model.train_on_batch, class_weight=class_weight) + elif mode == ModeKeys.TEST: + f = model.test_on_batch + else: + # Match signature of other modes to allow + # 1, 2, or 3-tuples from generator + def predict_on_batch(x, y=None, sample_weights=None): # pylint: disable=unused-argument + return model.predict_on_batch(x) + + f = predict_on_batch + + # Maintain stateful metrics across batch-level calls. + if mode != ModeKeys.PREDICT: + f = functools.partial(f, reset_metrics=False) + + return f + + +def _get_num_samples_or_steps(data, steps_per_epoch): + """Returns number of samples or steps, and whether to use steps count mode.""" + flat_inputs = nest.flatten(data) + if hasattr(flat_inputs[0], 'shape'): + return int(flat_inputs[0].shape[0]), False + return steps_per_epoch, True + + +class GeneratorOrSequenceTrainingLoop(training_utils_v1.TrainingLoop): + """Generator-like. + + Input is Python generator, or Sequence object. + + The difference between this class and `GeneratorLikeTrainingFunction` is that + this class only handles inputs that with x, y and sample_weight fused into one + param. + """ + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) + training_utils_v1.check_generator_arguments( + y, sample_weight, validation_split=validation_split) + return fit_generator( + model, + x, + steps_per_epoch=steps_per_epoch, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_data=validation_data, + validation_steps=validation_steps, + validation_freq=validation_freq, + class_weight=class_weight, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + shuffle=shuffle, + initial_epoch=initial_epoch, + steps_name='steps_per_epoch') + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + model._validate_or_infer_batch_size(batch_size, steps, x) + training_utils_v1.check_generator_arguments(y, sample_weight) + return evaluate_generator( + model, + x, + steps=steps, + verbose=verbose, + callbacks=callbacks, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing) + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + model._validate_or_infer_batch_size(batch_size, steps, x) + return predict_generator( + model, + x, + steps=steps, + verbose=verbose, + callbacks=callbacks, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing) + + +class EagerDatasetOrIteratorTrainingLoop(training_utils_v1.TrainingLoop): + """A non-distributed Dataset or iterator in eager execution.""" + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + **kwargs): + model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) + # Make sure that y, sample_weights, validation_split are not passed. + training_utils_v1.validate_dataset_input(x, y, sample_weight, + validation_split) + if (isinstance(x, (data_types.DatasetV1, data_types.DatasetV2)) and + shuffle): + training_utils_v1.verify_dataset_shuffled(x) + + return fit_generator( + model, + x, + steps_per_epoch=steps_per_epoch, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_data=validation_data, + validation_steps=validation_steps, + validation_freq=validation_freq, + class_weight=class_weight, + workers=0, + shuffle=shuffle, + initial_epoch=initial_epoch, + steps_name='steps_per_epoch') + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + **kwargs): + model._validate_or_infer_batch_size(batch_size, steps, x) + # Make sure that y, sample_weights, validation_split are not passed. + training_utils_v1.validate_dataset_input(x, y, sample_weight) + return evaluate_generator( + model, x, steps=steps, verbose=verbose, workers=0, callbacks=callbacks) + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + **kwargs): + model._validate_or_infer_batch_size(batch_size, steps, x) + return predict_generator( + model, x, steps=steps, verbose=verbose, workers=0, callbacks=callbacks) + + +class GeneratorLikeTrainingLoop(training_utils_v1.TrainingLoop): + """TrainingLoop that handle inputs like python generator. + + This is the default handler for most of the input data types, includes + symbolic tensors or Numpy array-like, Datasets and iterators in graph mode + (since they generate symbolic tensors). This Function is used to handle model + with `run_eagerly` = True. + """ + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, + steps_per_epoch, x) + x, y, sample_weights = model._standardize_user_data( + x, + y, + sample_weight=sample_weight, + class_weight=class_weight, + batch_size=batch_size, + check_steps=True, + steps_name='steps_per_epoch', + steps=steps_per_epoch, + validation_split=validation_split, + shuffle=shuffle) + + if validation_data: + validation_data = model._prepare_validation_data(validation_data, + batch_size, + validation_steps) + elif validation_split and 0. < validation_split < 1.: + (x, y, sample_weights, val_x, val_y, + val_sample_weights) = ( + training_utils_v1.split_training_and_validation_data( + x, y, sample_weights, validation_split)) + validation_data = (val_x, val_y, val_sample_weights) + else: + if validation_steps: + raise ValueError('`validation_steps` should not be specified if ' + '`validation_data` is None.') + + return fit_generator( + model, (x, y, sample_weights), + steps_per_epoch=steps_per_epoch, + batch_size=batch_size, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_data=validation_data, + validation_steps=validation_steps, + validation_freq=validation_freq, + workers=0, + shuffle=shuffle, + initial_epoch=initial_epoch, + steps_name='steps_per_epoch') + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + x, y, sample_weights = model._standardize_user_data( + x, + y, + sample_weight=sample_weight, + batch_size=batch_size, + check_steps=True, + steps_name='steps', + steps=steps) + return evaluate_generator( + model, (x, y, sample_weights), + steps=steps, + batch_size=batch_size, + verbose=verbose, + workers=0, + callbacks=callbacks) + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + **kwargs): + batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) + x, _, _ = model._standardize_user_data( + x, check_steps=True, steps_name='steps', steps=steps) + return predict_generator( + model, + x, + steps=steps, + batch_size=batch_size, + verbose=verbose, + workers=0, + callbacks=callbacks) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca70099e066fd2e37ab81c6d183651d68fc3fe29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils.py @@ -0,0 +1,222 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training-related utilities.""" + +import numpy as np + +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest + + +def slice_arrays(arrays, indices, contiguous=True): + """Slices batches out of provided arrays (workaround for eager tensors). + + Unfortunately eager tensors don't have the same slicing behavior as + Numpy arrays (they follow the same slicing behavior as symbolic TF tensors), + hence we cannot use `generic_utils.slice_arrays` directly + and we have to implement this workaround based on `concat`. This has a + performance cost. + + Args: + arrays: Single array or list of arrays. + indices: List of indices in the array that should be included in the output + batch. + contiguous: Boolean flag indicating whether the indices are contiguous. + + Returns: + Slice of data (either single array or list of arrays). + """ + converted_to_list = False + if not isinstance(arrays, list): + converted_to_list = True + arrays = [arrays] + if any(tensor_util.is_tf_type(x) for x in arrays): + if not contiguous: + entries = [[x[i:i + 1] for i in indices] for x in arrays] + slices = [array_ops.concat(x, axis=0) for x in entries] + else: + slices = [x[indices[0]:indices[-1] + 1] for x in arrays] + else: + slices = generic_utils.slice_arrays(arrays, indices) + + if converted_to_list: + slices = slices[0] + return slices + + +def handle_partial_sample_weights(outputs, sample_weights, sample_weight_modes, + check_all_flat=False): + """Adds 1.0 as sample weights for the outputs for which there is no weight. + + Args: + outputs: List of model outputs. + sample_weights: List of sample weight inputs. + sample_weight_modes: List of sample weight modes or None. + check_all_flat: Ensure that inputs are not nested structures. This is not + a free check, so we may not want to run it eagerly every iteration. + + Returns: + Tuple of sample weights, one sample weight for every output, and booleans + describing the raw sample weights. + """ + any_sample_weight = sample_weights is not None and any( + w is not None for w in sample_weights) + partial_sample_weight = any_sample_weight and any( + w is None for w in sample_weights) + + if not any_sample_weight: + return None, any_sample_weight, partial_sample_weight + + if not partial_sample_weight: + return sample_weights, any_sample_weight, partial_sample_weight + + if check_all_flat: + nest.assert_same_structure( + list_to_tuple(sample_weights), + list_to_tuple(nest.flatten(sample_weights))) + nest.assert_same_structure( + list_to_tuple(outputs), + list_to_tuple(nest.flatten(outputs))) + if sample_weight_modes is not None: + nest.assert_same_structure( + sample_weight_modes, nest.flatten(sample_weight_modes)) + + new_sample_weights = [] + for i, sw in enumerate(sample_weights): + if sw is None: + as_numpy = isinstance(outputs[i], np.ndarray) + output = outputs[i] + output_shape = output.shape if as_numpy else array_ops.shape(output) + + is_temporal = ( + sample_weight_modes is not None and + sample_weight_modes[i] == 'temporal') + sw_shape = (output_shape[0], + output_shape[1]) if is_temporal else (output_shape[0],) + + new_sample_weights.append( + np.ones(sw_shape) if as_numpy else array_ops.ones(sw_shape)) + + else: + new_sample_weights.append(sw) + return (list_to_tuple(new_sample_weights), + any_sample_weight, partial_sample_weight) + + +class RespectCompiledTrainableState(object): + """Set and restore trainable state if it has changed since compile. + + The keras API guarantees that the value of each Layer's `trainable` property + at `Model.compile` time will be used when training that model. In order to + respect this requirement, it may be necessary to set the trainable value of + layers to their compile time values before beginning a training endpoint and + restore the values before returing from said endpoint. This scope checks if + any layer's trainable state has changed since Model compile, and performs this + set and un-set bookkeeping. + + However, the trainable state of a layer changes quite infrequently, if ever, + for many kinds of workflows. Moreover, updating every layer in a model is an + expensive operation. As a result, we will only explicitly set and unset the + trainable state of a model if a trainable value has changed since compile. + """ + + def __init__(self, model): + self._model = model + self._current_trainable_state = None + self._compiled_trainable_state = None + self._should_set_trainable = False + + def __enter__(self): + self._current_trainable_state = self._model._get_trainable_state() # pylint: disable=protected-access + self._compiled_trainable_state = self._model._compiled_trainable_state # pylint: disable=protected-access + + # Check to see if any layer's trainable state has changed since `compile`. + for layer, trainable in self._compiled_trainable_state.items(): + if (layer in self._current_trainable_state and + trainable != self._current_trainable_state[layer]): + self._should_set_trainable = True + break + + # If so, restore the model to its compiled state. + if self._should_set_trainable: + self._model._set_trainable_state(self._compiled_trainable_state) # pylint: disable=protected-access + + def __exit__(self, type_arg, value_arg, traceback_arg): + # If we set the values to their compiled state in __enter__, we need to + # restore the original values before leaving the scope. + if self._should_set_trainable: + self._model._set_trainable_state(self._current_trainable_state) # pylint: disable=protected-access + return False # False values do not suppress exceptions + + +# Allow use of methods not exposed to the user. +# pylint: disable=protected-access +def get_input_shape_and_dtype(layer): + """Retrieves input shape and input dtype of layer if applicable. + + Args: + layer: Layer (or model) instance. + + Returns: + Tuple (input_shape, input_dtype). Both could be None if the layer + does not have a defined input shape. + + Raises: + ValueError: in case an empty Sequential or Functional model is passed. + """ + + def _is_graph_model(layer): + return ((hasattr(layer, '_is_graph_network') and layer._is_graph_network) or + layer.__class__.__name__ == 'Sequential') + + # In case of nested models: recover the first layer + # of the deepest model to infer input shape and dtype. + # Subclassed Models may not have been built so can't be checked. + while _is_graph_model(layer): + if not layer.layers: + raise ValueError('An empty Model cannot be used as a Layer.') + layer = layer.layers[0] + + if getattr(layer, '_batch_input_shape', None): + return layer._batch_input_shape, layer.dtype + return None, None + + +# pylint: enable=protected-access + + +def get_static_batch_size(layer): + """Gets the static batch size of a Layer. + + Args: + layer: a `Layer` instance. + + Returns: + The static batch size of a Layer. + """ + batch_input_shape, _ = get_input_shape_and_dtype(layer) + if batch_input_shape is not None: + return tensor_shape.Dimension(batch_input_shape[0]).value + return None + + +def list_to_tuple(maybe_list): + """Datasets will stack the list of tensor, so switch them to tuples.""" + if isinstance(maybe_list, list): + return tuple(maybe_list) + return maybe_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0a896212d31e38441be6975f8b08d4e32d432d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_utils_v1.py @@ -0,0 +1,1963 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Training-related utilities.""" + +import abc +import atexit +import collections +import functools +import multiprocessing.pool +import threading +import time + +import numpy as np + +from tensorflow.core.framework import graph_pb2 +from tensorflow.python import tf2 +from tensorflow.python.data.experimental.ops import cardinality +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import callbacks as cbks +from tensorflow.python.keras import losses +from tensorflow.python.keras import metrics as metrics_module +from tensorflow.python.keras.utils import data_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest + + +def is_composite_or_composite_value(tensor): + """Returns true if 'tensor' is a CompositeTensor or a CT Value object.""" + # TODO(b/125094323): This should be isinstance(CompositeTensor) or + # isinstance(CompositeTensorValue) once we support that. + return isinstance( + tensor, + (composite_tensor.CompositeTensor, sparse_tensor.SparseTensorValue, + ragged_tensor_value.RaggedTensorValue)) + + +class Aggregator(object, metaclass=abc.ABCMeta): + """Abstract base class used to aggregate batch-level outputs of a loop. + + Attributes: + use_steps: Whether the loop is using `step` or `batch_size`. + num_samples: Total number of samples: `batch_size * num_batches`. + steps: Total number of steps. + batch_size: Batch size. It is used for validation checks between inputs and + outputs. + results: What to return at the end of the aggregation loop. + """ + + def __init__(self, use_steps, num_samples=None, steps=None, batch_size=None): + self.use_steps = use_steps + self.num_samples = num_samples + self.steps = steps + self.batch_size = batch_size + self.results = [] + + @abc.abstractmethod + def create(self, batch_outs): + """Creates the initial results from the first batch outputs. + + Args: + batch_outs: A list of batch-level outputs. + """ + raise NotImplementedError('Must be implemented in subclasses.') + + @abc.abstractmethod + def aggregate(self, batch_outs, batch_start=None, batch_end=None): + """Aggregates batch-level results into total results. + + Args: + batch_outs: A list of batch-level outputs. + batch_start: The start index of this batch. Always `None` if `use_steps` + is `True`. + batch_end: The end index of this batch. Always `None` if `use_steps` is + `True`. + """ + raise NotImplementedError('Must be implemented in subclasses.') + + @abc.abstractmethod + def finalize(self): + """Prepares the total results to be returned.""" + raise NotImplementedError('Must be implemented in subclasses.') + + +class MetricsAggregator(Aggregator): + """Aggregator that calculates loss and metrics info. + + Attributes: + use_steps: Whether the loop is using `step` or `batch_size`. + num_samples: Total number of samples: `batch_size*num_batches`. + steps: Total number of steps, ie number of times to iterate over a dataset + to cover all samples. + """ + + def __init__(self, use_steps, num_samples=None, steps=None): + super(MetricsAggregator, self).__init__( + use_steps=use_steps, + num_samples=num_samples, + steps=steps, + batch_size=None) + + def create(self, batch_outs): + self.results = [0.] * len(batch_outs) + + def aggregate(self, batch_outs, batch_start=None, batch_end=None): + # Loss. + if self.use_steps: + self.results[0] += batch_outs[0] + else: + self.results[0] += batch_outs[0] * (batch_end - batch_start) + # Metrics (always stateful, just grab current values.) + self.results[1:] = batch_outs[1:] + + def finalize(self): + if not self.results: + raise ValueError('Empty training data.') + self.results[0] /= (self.num_samples or self.steps) + + +def _append_sparse_tensor_value(target, to_append): + """Append sparse tensor value objects.""" + # Make sure the sparse tensors are of the same size (except for the 0th dim). + if len(target.dense_shape) != len(to_append.dense_shape): + raise RuntimeError( + 'Unable to concatenate %s and %s. The inner dense shapes do not ' + 'have the same number of dimensions (%s vs %s)' % + (target, to_append, target.dense_shape, to_append.dense_shape)) + + if target.dense_shape[1:] != to_append.dense_shape[1:]: + raise RuntimeError( + 'Unable to concatenate %s and %s. The inner dense shapes do not ' + 'match inner dimensions (%s vs %s)' % + (target, to_append, target.dense_shape[1:], to_append.dense_shape[1:])) + + # Add the to_append indices to target, updating the 0th value, and keeping + # track of the maximum so we know the final dense_shape of this tensor. + base_dim0_value = target.dense_shape[0] + max_dim0_value = target.dense_shape[0] + new_indices = target.indices + for index in to_append.indices: + # Here, we iterate through the sparse indices of the tensor to append. For + # each index, we update its zeroth value (the batch index) by adding the + # number of batch items in the tensor we are appending to (so an index + # of [0, 0, 1] for a value that is being appended to a tensor with 0th dim + # size 3 would become [3, 0, 1].) + index[0] += base_dim0_value + max_dim0_value = max(max_dim0_value, index[0]) + new_indices = np.append(new_indices, [index], axis=0) + + # Extend the values array to contain all of the appended values. These will + # be in the same order as the indices added above. + new_values = np.concatenate((target.values, to_append.values), axis=0) + + # Create a new dense shape by replacing the value for the 0th dimension + # with the new max dim0 value. + new_dense_shape = list(target.dense_shape) + new_dense_shape[0] = max_dim0_value + 1 + new_dense_shape = tuple(new_dense_shape) + + return sparse_tensor.SparseTensorValue( + indices=new_indices, values=new_values, dense_shape=new_dense_shape) + + +def _append_ragged_tensor_value(target, to_append): + """Append ragged tensor value objects.""" + # Make sure the ragged tensors are of the same size (save for the 0th dim). + if len(target.shape) != len(to_append.shape): + raise RuntimeError('Unable to concatenate %s and %s' % (target, to_append)) + + if target.shape[1:] != to_append.shape[1:]: + raise RuntimeError('Unable to concatenate %s and %s' % (target, to_append)) + + adjusted_row_splits = to_append.row_splits[1:] + target.row_splits[-1] + new_row_splits = np.append(target.row_splits, adjusted_row_splits) + if isinstance(target.values, ragged_tensor_value.RaggedTensorValue): + new_values = _append_ragged_tensor_value(target.values, to_append.values) + else: + new_values = np.concatenate((target.values, to_append.values), axis=0) + + return ragged_tensor_value.RaggedTensorValue(new_values, new_row_splits) + + +def _append_composite_tensor(target, to_append): + """Helper function to append composite tensors to each other in the 0 axis. + + In order to support batching within a fit/evaluate/predict call, we need + to be able to aggregate within a CompositeTensor. Unfortunately, the CT + API currently does not make this easy - especially in V1 mode, where we're + working with CompositeTensor Value objects that have no connection with the + CompositeTensors that created them. + + Args: + target: CompositeTensor or CompositeTensor value object that will be + appended to. + to_append: CompositeTensor or CompositeTensor value object to append to. + 'target'. + + Returns: + A CompositeTensor or CompositeTensor value object. + + Raises: + RuntimeError: if concatenation is not possible. + """ + if type(target) is not type(to_append): + raise RuntimeError('Unable to concatenate %s and %s' % + (type(target), type(to_append))) + + # Perform type-specific concatenation. + # TODO(b/125094323): This should be replaced by a simple call to + # target.append() that should work on all of the below classes. + + # If we're seeing a CompositeTensor here, we know it's because we're in + # Eager mode (or else we'd have evaluated the CT to a CT Value object + # already). Therefore, it's safe to call concat() on it without evaluating + # the result any further. If not - that is, if we're seeing a + # SparseTensorValue or a RaggedTensorValue - we need to hand-update it + # since we're outside of the graph anyways. + if isinstance(target, sparse_tensor.SparseTensor): + # We need to invoke the sparse version of concatenate here - tf.concat + # won't work. + return sparse_ops.sparse_concat(sp_inputs=[target, to_append], axis=0) + elif isinstance(target, ragged_tensor.RaggedTensor): + return array_ops.concat([target, to_append], axis=0) + elif isinstance(target, sparse_tensor.SparseTensorValue): + return _append_sparse_tensor_value(target, to_append) + elif isinstance(target, ragged_tensor_value.RaggedTensorValue): + return _append_ragged_tensor_value(target, to_append) + else: + raise RuntimeError('Attempted to concatenate unsupported object %s.' % + type(target)) + + +class ConcatAggregator(Aggregator): + """Combine tensor-likes which cannot be merged on the fly. + + This class expects to aggregate a single tensor-like rather than a nested + structure of tensor-likes. + """ + + def __init__(self, batch_size): + self.composite = None + super(ConcatAggregator, self).__init__( + use_steps=True, num_samples=None, steps=None, batch_size=batch_size) + + def create(self, batch_element): + self.composite = is_composite_or_composite_value(batch_element) + + def aggregate(self, batch_element, batch_start=None, batch_end=None): + + # TODO(psv): Add num_samples check here to detect when output batch + # #samples is < batch size and != input batch #samples. + if self.batch_size and self.batch_size < batch_element.shape[0]: + raise ValueError( + 'Mismatch between expected batch size and model output batch size. ' + 'Output shape = {}, expected output shape = shape {}'.format( + batch_element.shape, + (self.batch_size,) + batch_element.shape[1:])) + self.results.append(batch_element) + + def finalize(self): + # Special case of single batch inference which skips a copy. + if len(self.results) == 1: + self.results = self.results[0] + + elif self.composite: + # TODO(taylorrobie): efficiently concatenate. + results = self.results[0] + for r in self.results[1:]: + results = _append_composite_tensor(results, r) + self.results = results + + else: + self.results = np.concatenate(self.results, axis=0) + + +_COPY_THREADS = 4 +_COPY_POOL = None + + +def get_copy_pool(): + """Shared threadpool for copying arrays. + + Pool instantiation takes ~ 2ms, so a singleton pool is used rather than + creating a pool per SliceAggregator. + + Returns: + The global copy threadpool. + """ + global _COPY_POOL + if _COPY_POOL is None: + _COPY_POOL = multiprocessing.pool.ThreadPool(_COPY_THREADS) + atexit.register(_COPY_POOL.close) + return _COPY_POOL + + +class SliceAggregator(Aggregator): + """Combine arrays where the final size is known. + + This class expects to aggregate a single tensor-like rather than a nested + structure of tensor-likes. + + NumPy copies are an operation that threads handle quite well because all of + the heavy lifting is in c and does not need the GIL. Moreover, we can perform + lock-free writes to the same buffer in multiple threads because the nature of + result aggregation guarantees that either the indices are disjoint or the + aggregator will throw an exception in finalize. Moreover, because aggregation + is performed on the slowest varying dimension, assignments for a given batch + will write to contiguous blocks of memory, further minimizing contention. + + There is, however, some scheduling and context switching overhead which will + offset the gains from pipelining the slice assignment. Below a given threshold + it is faster to simply assign in the main thread rather than enqueue the + assignment in a side thread. The exact threshold will vary from system to + system, but the time is not very sensitive to the exact transition so a value + of 2 ** 14 was chosen which should be reasonable on most systems. + """ + + _BINARY_SIZE_THRESHOLD = 2 ** 14 + _MAX_COPY_SECONDS = 300 + + def __init__(self, num_samples, batch_size): + self._async_copies = [] + self._pool = get_copy_pool() + self._errors = [] + super(SliceAggregator, self).__init__( + use_steps=False, + num_samples=num_samples, + steps=None, + batch_size=batch_size) + + def create(self, batch_element): + # This step does not need to be pipelined because NumPy empty array + # initialization is effectively instantaneous. + shape = (self.num_samples,) + batch_element.shape[1:] + dtype = batch_element.dtype + + self.results = np.empty(shape=shape, dtype=dtype) + + def aggregate(self, batch_element, batch_start, batch_end): + # Fail early. + if self._errors: + raise self._errors[0] + + # In the special case of single batch inference, no copy is needed. + if batch_end - batch_start == self.num_samples: + if self.num_samples != batch_element.shape[0]: + raise ValueError( + 'Mismatch between expected batch size and model output batch size. ' + 'Output shape = {}, expected output shape = shape {}'.format( + batch_element.shape, self.results.shape)) + + self.results = batch_element + return + + # This is an approximate threshold, so we don't need to consider the number + # of bytes per element. + num_elements = np.prod(batch_element.shape) + if num_elements < self._BINARY_SIZE_THRESHOLD: + self.results[batch_start:batch_end] = batch_element + else: + is_finished = threading.Event() + self._pool.apply_async( + self._slice_assign, + args=(batch_element, batch_start, batch_end, is_finished)) + self._async_copies.append(is_finished) + + def _slice_assign(self, batch_element, batch_start, batch_end, is_finished): + """Legacy utility method to slice input arrays.""" + try: + self.results[batch_start:batch_end] = batch_element + + except Exception as e: # pylint: disable=broad-except + # `_slice_assign` should only be called in threads and exceptions raised + # in threads do not carry over to the main thread. So instead we perform a + # a broad catch in the thread and then store the exception to be re-raised + # in the main thread. + self._errors.append(e) + + finally: + is_finished.set() + + def finalize(self): + start_time = time.time() + for is_finished in self._async_copies: + timeout = max([0., self._MAX_COPY_SECONDS - (time.time() - start_time)]) + if not is_finished.wait(timeout): + raise ValueError('Timed out waiting for copy to complete.') + + if self._errors: + raise self._errors[0] + + +class OutputsAggregator(Aggregator): + """Aggregator that concatenates outputs.""" + + _structure = None + + def create(self, batch_outs): + # SparseTensorValue is a named tuple which nest will flatten, so we need + # to guard it to properly handle the structure. + self._structure = nest.get_traverse_shallow_structure( + lambda x: not is_composite_or_composite_value(x), batch_outs) + batch_outs = nest.flatten_up_to(self._structure, batch_outs) + + for batch_element in batch_outs: + if is_composite_or_composite_value(batch_element): + # If the output is not a ndarray, it will be either a composite tensor + # or a composite tensor's Value object. In either case, we can't + # allocate an array to hold the object - we'll handle it later. + self.results.append(ConcatAggregator(self.batch_size)) + elif isinstance(batch_element, np.ndarray): + self.results.append( + (ConcatAggregator(self.batch_size) if self.use_steps else + SliceAggregator(self.num_samples, self.batch_size))) + else: + # This is not a ndarray, a CompositeTensor, or a CompositeTensorValue. + # Fail fast rather than trying to concatenate it. + raise RuntimeError('Attempted to aggregate unsupported object {}.' + .format(batch_element)) + + self.results[-1].create(batch_element) + + def aggregate(self, batch_outs, batch_start=None, batch_end=None): + batch_outs = nest.flatten_up_to(self._structure, batch_outs) + for batch_element, result in zip(batch_outs, self.results): + result.aggregate(batch_element, batch_start, batch_end) + + def finalize(self): + for result in self.results: + result.finalize() + self.results = [i.results for i in self.results] + self.results = nest.pack_sequence_as(self._structure, self.results) + + +def get_progbar(model, count_mode, include_metrics=True): + """Get Progbar.""" + if include_metrics: + stateful_metric_names = getattr(model, 'metrics_names', None) + if stateful_metric_names: + stateful_metric_names = stateful_metric_names[1:] # Exclude `loss` + else: + stateful_metric_names = None + return cbks.ProgbarLogger(count_mode, stateful_metrics=stateful_metric_names) + + +def check_num_samples(ins, batch_size=None, steps=None, steps_name='steps'): + """Determine the number of samples provided for training and evaluation. + + The number of samples is not defined when running with `steps`, + in which case the number of samples is set to `None`. + + Args: + ins: List of tensors to be fed to the Keras function. + batch_size: Integer batch size or `None` if not defined. + steps: Total number of steps (batches of samples) before declaring + `_predict_loop` finished. Ignored with the default value of `None`. + steps_name: The public API's parameter name for `steps`. + + Raises: + ValueError: when `steps` is `None` and the attribute `ins.shape` + does not exist. Also raises ValueError when `steps` is not `None` + and `batch_size` is not `None` because they are mutually + exclusive. + + Returns: + When steps is `None`, returns the number of samples to be + processed based on the size of the first dimension of the + first input numpy array. When steps is not `None` and + `batch_size` is `None`, returns `None`. + """ + if steps is not None and batch_size is not None: + raise ValueError('If ' + steps_name + + ' is set, the `batch_size` must be None.') + if check_steps_argument(ins, steps, steps_name): + return None + + if hasattr(ins[0], 'shape'): + return int(ins[0].shape[0]) + return None # Edge case where ins == [static_learning_phase] + + +def standardize_single_array(x, expected_shape=None): + """Expand data of shape (x,) to (x, 1), unless len(expected_shape)==1.""" + if x is None: + return None + + if is_composite_or_composite_value(x): + return x + + if isinstance(x, int): + raise ValueError( + 'Expected an array data type but received an integer: {}'.format(x)) + + if (x.shape is not None and len(x.shape) == 1 and + (expected_shape is None or len(expected_shape) != 1)): + if tensor_util.is_tf_type(x): + x = array_ops.expand_dims(x, axis=1) + else: + x = np.expand_dims(x, 1) + return x + + +def get_composite_shape(tensor): + """Returns the shape of the passed composite tensor.""" + if isinstance(tensor, sparse_tensor.SparseTensorValue): + # SparseTensorValues use a 'dense_shape' attribute + return tensor.dense_shape + else: + return tensor.shape + + +def standardize_input_data(data, + names, + shapes=None, + check_batch_axis=True, + exception_prefix=''): + """Normalizes inputs and targets provided by users. + + Users may pass data as a list of arrays, dictionary of arrays, + or as a single array. We normalize this to an ordered list of + arrays (same order as `names`), while checking that the provided + arrays have shapes that match the network's expectations. + + Args: + data: User-provided input data (polymorphic). + names: List of expected array names. + shapes: Optional list of expected array shapes. + check_batch_axis: Boolean; whether to check that the batch axis of the + arrays matches the expected value found in `shapes`. + exception_prefix: String prefix used for exception formatting. + + Returns: + List of standardized input arrays (one array per model input). + + Raises: + ValueError: in case of improperly formatted user-provided data. + """ + try: + data_len = len(data) + except TypeError: + # For instance if data is `None` or a symbolic Tensor. + data_len = None + + if not names: + if data_len and not isinstance(data, dict): + raise ValueError( + 'Error when checking model ' + exception_prefix + ': ' + 'expected no data, but got:', data) + return [] + if data is None: + return [None for _ in range(len(names))] + + if isinstance(data, dict): + try: + data = [ + data[x].values + if data[x].__class__.__name__ == 'DataFrame' else data[x] + for x in names + ] + except KeyError as e: + raise ValueError('No data provided for "' + e.args[0] + '". Need data ' + 'for each key in: ' + str(names)) + elif isinstance(data, (list, tuple)): + if isinstance(data[0], (list, tuple)): + data = [np.asarray(d) for d in data] + elif len(names) == 1 and isinstance(data[0], (float, int)): + data = [np.asarray(data)] + else: + data = [ + x.values if x.__class__.__name__ == 'DataFrame' else x for x in data + ] + else: + data = data.values if data.__class__.__name__ == 'DataFrame' else data + data = [data] + + if shapes is not None: + data = [ + standardize_single_array(x, shape) for (x, shape) in zip(data, shapes) + ] + else: + data = [standardize_single_array(x) for x in data] + + if len(data) != len(names): + if data and hasattr(data[0], 'shape'): + raise ValueError('Error when checking model ' + exception_prefix + + ': the list of Numpy arrays that you are passing to ' + 'your model is not the size the model expected. ' + 'Expected to see ' + str(len(names)) + ' array(s), ' + + 'for inputs ' + str(names) + ' but instead got the ' + 'following list of ' + str(len(data)) + ' arrays: ' + + str(data)[:200] + '...') + elif len(names) > 1: + raise ValueError('Error when checking model ' + exception_prefix + + ': you are passing a list as input to your model, ' + 'but the model expects a list of ' + str(len(names)) + + ' Numpy arrays instead. The list you passed was: ' + + str(data)[:200]) + elif len(data) == 1 and not hasattr(data[0], 'shape'): + raise TypeError('Error when checking model ' + exception_prefix + + ': data should be a Numpy array, or list/dict of ' + 'Numpy arrays. Found: ' + str(data)[:200] + '...') + elif len(names) == 1: + data = [np.asarray(data)] + + # Check shapes compatibility. + if shapes: + for i in range(len(names)): + if shapes[i] is not None: + if tensor_util.is_tf_type(data[i]): + tensorshape = data[i].shape + if not tensorshape: + continue + data_shape = tuple(tensorshape.as_list()) + elif is_composite_or_composite_value(data[i]): + tensorshape = get_composite_shape(data[i]) + data_shape = tuple(tensorshape.as_list()) + else: + data_shape = data[i].shape + + shape = shapes[i] + if len(data_shape) != len(shape): + raise ValueError('Error when checking ' + exception_prefix + + ': expected ' + names[i] + ' to have ' + + str(len(shape)) + ' dimensions, but got array ' + 'with shape ' + str(data_shape)) + if not check_batch_axis: + data_shape = data_shape[1:] + shape = shape[1:] + for dim, ref_dim in zip(data_shape, shape): + if ref_dim != dim and ref_dim is not None and dim is not None: + raise ValueError('Error when checking ' + exception_prefix + + ': expected ' + names[i] + ' to have shape ' + + str(shape) + ' but got array with shape ' + + str(data_shape)) + return data + + +def standardize_sample_or_class_weights(x_weight, output_names, weight_type): + """Maps `sample_weight` or `class_weight` to model outputs. + + Args: + x_weight: User-provided `sample_weight` or `class_weight` argument. + output_names: List of output names (strings) in the model. + weight_type: A string used purely for exception printing. + + Returns: + A list of `sample_weight` or `class_weight` where there are exactly + one element per model output. + + Raises: + ValueError: In case of invalid user-provided argument. + """ + if x_weight is None or (isinstance(x_weight, (list, tuple)) and + len(x_weight) == 0): # pylint: disable=g-explicit-length-test + return [None for _ in output_names] + if len(output_names) == 1: + if isinstance(x_weight, (list, tuple)) and len(x_weight) == 1: + return x_weight + if isinstance(x_weight, dict) and output_names[0] in x_weight: + return [x_weight[output_names[0]]] + else: + return [x_weight] + if isinstance(x_weight, (list, tuple)): + if len(x_weight) != len(output_names): + raise ValueError('Provided `' + weight_type + '` was a list of ' + + str(len(x_weight)) + ' elements, but the model has ' + + str(len(output_names)) + ' outputs. ' + 'You should provide one `' + weight_type + '`' + 'array per model output.') + return x_weight + if isinstance(x_weight, collections.abc.Mapping): + generic_utils.check_for_unexpected_keys(weight_type, x_weight, output_names) + x_weights = [] + for name in output_names: + x_weights.append(x_weight.get(name)) + return x_weights + else: + raise TypeError('The model has multiple outputs, so `' + weight_type + '` ' + 'should be either a list or a dict. ' + 'Provided `' + weight_type + '` type not understood: ' + + str(x_weight)) + + +def standardize_class_weights(class_weight, output_names): + return standardize_sample_or_class_weights(class_weight, output_names, + 'class_weight') + + +def standardize_sample_weights(sample_weight, output_names): + return standardize_sample_or_class_weights(sample_weight, output_names, + 'sample_weight') + + +def check_array_lengths(inputs, targets, weights=None): + """Does user input validation for numpy arrays. + + Args: + inputs: list of Numpy arrays of inputs. + targets: list of Numpy arrays of targets. + weights: list of Numpy arrays of sample weights. + + Raises: + ValueError: in case of incorrectly formatted data. + """ + + def is_tensor_or_composite_tensor(x): + return tensor_util.is_tf_type(x) or is_composite_or_composite_value(x) + + def set_of_lengths(x): + # Returns a set with the variation between + # different shapes, with None => 0 + if x is None: + return {} + else: + return set([ + y.shape[0] + for y in x + if y is not None and not is_tensor_or_composite_tensor(y) + ]) + + set_x = set_of_lengths(inputs) + set_y = set_of_lengths(targets) + set_w = set_of_lengths(weights) + if len(set_x) > 1: + raise ValueError('All input arrays (x) should have ' + 'the same number of samples. Got array shapes: ' + + str([x.shape for x in inputs])) + if len(set_y) > 1: + raise ValueError('All target arrays (y) should have ' + 'the same number of samples. Got array shapes: ' + + str([y.shape for y in targets])) + if set_x and set_y and list(set_x)[0] != list(set_y)[0]: + raise ValueError('Input arrays should have ' + 'the same number of samples as target arrays. ' + 'Found ' + str(list(set_x)[0]) + ' input samples ' + 'and ' + str(list(set_y)[0]) + ' target samples.') + if len(set_w) > 1: + raise ValueError('All sample_weight arrays should have ' + 'the same number of samples. Got array shapes: ' + + str([w.shape for w in weights])) + if set_y and set_w and list(set_y)[0] != list(set_w)[0]: + raise ValueError('Sample_weight arrays should have ' + 'the same number of samples as target arrays. Got ' + + str(list(set_y)[0]) + ' input samples and ' + + str(list(set_w)[0]) + ' target samples.') + + +def check_loss_and_target_compatibility(targets, loss_fns, output_shapes): + """Does validation on the compatibility of targets and loss functions. + + This helps prevent users from using loss functions incorrectly. This check + is purely for UX purposes. + + Args: + targets: list of Numpy arrays of targets. + loss_fns: list of loss functions. + output_shapes: list of shapes of model outputs. + + Raises: + ValueError: if a loss function or target array + is incompatible with an output. + """ + key_loss_fns = { + losses.mean_squared_error, losses.binary_crossentropy, + losses.categorical_crossentropy + } + key_loss_classes = (losses.MeanSquaredError, losses.BinaryCrossentropy, + losses.CategoricalCrossentropy) + for y, loss, shape in zip(targets, loss_fns, output_shapes): + if y is None or loss is None or tensor_util.is_tf_type(y): + continue + if losses.is_categorical_crossentropy(loss): + if y.shape[-1] == 1: + raise ValueError('You are passing a target array of shape ' + + str(y.shape) + + ' while using as loss `categorical_crossentropy`. ' + '`categorical_crossentropy` expects ' + 'targets to be binary matrices (1s and 0s) ' + 'of shape (samples, classes). ' + 'If your targets are integer classes, ' + 'you can convert them to the expected format via:\n' + '```\n' + 'from keras.utils import to_categorical\n' + 'y_binary = to_categorical(y_int)\n' + '```\n' + '\n' + 'Alternatively, you can use the loss function ' + '`sparse_categorical_crossentropy` instead, ' + 'which does expect integer targets.') + + is_loss_wrapper = isinstance(loss, losses.LossFunctionWrapper) + if (isinstance(loss, key_loss_classes) or (is_loss_wrapper and + (loss.fn in key_loss_fns))): + for target_dim, out_dim in zip(y.shape[1:], shape[1:]): + if out_dim is not None and target_dim != out_dim: + loss_name = loss.name + if loss_name is None: + loss_type = loss.fn if is_loss_wrapper else type(loss) + loss_name = loss_type.__name__ + raise ValueError('A target array with shape ' + str(y.shape) + + ' was passed for an output of shape ' + str(shape) + + ' while using as loss `' + loss_name + '`. ' + 'This loss expects targets to have the same shape ' + 'as the output.') + + +def collect_per_output_metric_info(metrics, + output_names, + output_shapes, + loss_fns, + from_serialized=False, + is_weighted=False): + """Maps metric names and functions to model outputs. + + Args: + metrics: a list or a list of lists or a dict of metric functions. + output_names: a list of the names (strings) of model outputs. + output_shapes: a list of the shapes (strings) of model outputs. + loss_fns: a list of the loss functions corresponding to the model outputs. + from_serialized: whether the model the metrics are being sourced from is + being initialized from a serialized format. + is_weighted: Boolean indicating whether the given metrics are weighted. + + Returns: + A list (one entry per model output) of dicts. + For instance, if the model has 2 outputs, and for the first output + we want to compute "binary_accuracy" and "binary_crossentropy", + and just "binary_accuracy" for the second output, + the list would look like: `[{ + 'acc': binary_accuracy(), + 'ce': binary_crossentropy(), + }, { + 'acc': binary_accuracy(), + }]` + + Raises: + TypeError: if an incorrect type is passed for the `metrics` argument. + """ + if not metrics: + return [{} for _ in output_names] + + if isinstance(metrics, list): + any_sub_list = any(isinstance(m, list) for m in metrics) + if any_sub_list: + if len(metrics) != len(output_names): + raise ValueError('When passing a list of lists as `metrics`, ' + 'it should have one entry per model output. ' + 'The model has ' + str(len(output_names)) + + ' outputs, but you passed metrics=' + str(metrics)) + # User has provided a list of len = len(outputs). + nested_metrics = [generic_utils.to_list(m) for m in metrics] + else: + # If it is a single list we then apply all metrics to all outputs. + if len(output_names) > 1: + nested_metrics = [] + for _ in output_names: + nested_metrics.append( + [metrics_module.clone_metric(m) for m in metrics]) + else: + nested_metrics = [metrics] + elif isinstance(metrics, collections.abc.Mapping): + generic_utils.check_for_unexpected_keys('metrics', metrics, output_names) + nested_metrics = [] + for name in output_names: + output_metrics = generic_utils.to_list(metrics.get(name, [])) + nested_metrics.append(output_metrics) + else: + raise TypeError('Type of `metrics` argument not understood. ' + 'Expected a list or dictionary, found: ' + str(metrics)) + + per_output_metrics = [] + for i, metrics in enumerate(nested_metrics): + metrics_dict = collections.OrderedDict() + for metric in metrics: + metric_name = get_metric_name(metric, is_weighted) + metric_fn = get_metric_function( + metric, output_shape=output_shapes[i], loss_fn=loss_fns[i]) + metric_fn._from_serialized = from_serialized # pylint: disable=protected-access + + # If the metric function is not stateful, we create a stateful version. + if not isinstance(metric_fn, metrics_module.Metric): + metric_fn = metrics_module.MeanMetricWrapper( + metric_fn, name=metric_name) + # If the metric is being revived from something stateless, such as a + # string (e.g. "accuracy"), we may need to later reapply transformations + # such as renaming. + metric_fn._from_serialized = False # pylint: disable=protected-access + metrics_dict[metric_name] = metric_fn + per_output_metrics.append(metrics_dict) + + return per_output_metrics + + +def batch_shuffle(index_array, batch_size): + """Shuffles an array in a batch-wise fashion. + + Useful for shuffling HDF5 arrays + (where one cannot access arbitrary indices). + + Args: + index_array: array of indices to be shuffled. + batch_size: integer. + + Returns: + The `index_array` array, shuffled in a batch-wise fashion. + """ + batch_count = int(len(index_array) / batch_size) + # to reshape we need to be cleanly divisible by batch size + # we stash extra items and reappend them after shuffling + last_batch = index_array[batch_count * batch_size:] + index_array = index_array[:batch_count * batch_size] + index_array = index_array.reshape((batch_count, batch_size)) + np.random.shuffle(index_array) + index_array = index_array.flatten() + return np.append(index_array, last_batch) + + +def standardize_weights(y, + sample_weight=None, + class_weight=None, + sample_weight_mode=None): + """Performs sample weight validation and standardization. + + Everything gets normalized to a single sample-wise (or timestep-wise) + weight array. If both `sample_weight` and `class_weight` are provided, + the weights are multiplied. + + Args: + y: Numpy array or Tensor of model targets to be weighted. + sample_weight: User-provided `sample_weight` argument. + class_weight: User-provided `class_weight` argument. + sample_weight_mode: One of `None` or `"temporal"`. `"temporal"` indicated + that we expect 2D weight data that will be applied to the last 2 + dimensions of the targets (i.e. we are weighting timesteps, not + samples). + + Returns: + A numpy array of target weights, one entry per sample to weight. + + Raises: + ValueError: In case of invalid user-provided arguments. + """ + # Iterator may return sample_weight as 1-tuple + if isinstance(sample_weight, tuple): + sample_weight = sample_weight[0] + if sample_weight_mode is not None and sample_weight_mode != 'samplewise': + if sample_weight_mode != 'temporal': + raise ValueError('"sample_weight_mode ' + 'should be None or "temporal". ' + 'Found: ' + str(sample_weight_mode)) + if len(y.shape) < 3: + raise ValueError('Found a sample_weight array for ' + 'an input with shape ' + str(y.shape) + '. ' + 'Timestep-wise sample weighting (use of ' + 'sample_weight_mode="temporal") is restricted to ' + 'outputs that are at least 3D, i.e. that have ' + 'a time dimension.') + if sample_weight is not None and len(sample_weight.shape) != 2: + raise ValueError('Found a sample_weight array with shape ' + + str(sample_weight.shape) + '. ' + 'In order to use timestep-wise sample weighting, ' + 'you should pass a 2D sample_weight array.') + else: + if sample_weight is not None and len(sample_weight.shape) != 1: + raise ValueError( + 'Found a sample_weight array with shape {}. In order to ' + 'use timestep-wise sample weights, you should specify ' + 'sample_weight_mode="temporal" in compile(); founssd "{}" ' + 'instead. If you just mean to use sample-wise weights, ' + 'make sure your sample_weight array is 1D.'.format( + sample_weight.shape, sample_weight_mode)) + + if sample_weight is not None: + if len(sample_weight.shape) > len(y.shape): + raise ValueError('Found a sample_weight with shape' + + str(sample_weight.shape) + '.' + 'Expected sample_weight with rank ' + 'less than or equal to ' + str(len(y.shape))) + + if (not tensor_util.is_tf_type(sample_weight) and + y.shape[:sample_weight.ndim] != sample_weight.shape): + raise ValueError('Found a sample_weight array with shape ' + + str(sample_weight.shape) + ' for an input with shape ' + + str(y.shape) + '. ' + 'sample_weight cannot be broadcast.') + + # Class weights applied per-sample. + class_sample_weight = None + if isinstance(class_weight, dict): + if len(y.shape) > 2: + raise ValueError('`class_weight` not supported for ' + '3+ dimensional targets.') + + if tensor_util.is_tf_type(y): + # Few classes are expected, so densifying is reasonable. + keys = np.array(sorted(class_weight.keys())) + values = np.array([class_weight[i] for i in keys]) + weight_vector = np.zeros(np.max(keys) + 1) + weight_vector[:] = np.nan + weight_vector[keys] = values + + y_classes = smart_cond.smart_cond( + len(y.shape.as_list()) == 2 and backend.shape(y)[1] > 1, + lambda: backend.argmax(y, axis=1), + lambda: math_ops.cast(backend.reshape(y, (-1,)), dtypes.int64)) + class_sample_weight = array_ops.gather(weight_vector, y_classes) + gen_array_ops.check_numerics( + class_sample_weight, + 'Invalid classes or class weights detected. NaN values indicate that ' + 'an appropriate class weight could not be determined.') + class_sample_weight = math_ops.cast(class_sample_weight, backend.floatx()) + if sample_weight is not None: + sample_weight = math_ops.cast( + tensor_conversion.convert_to_tensor_v2_with_dispatch(sample_weight), + backend.floatx(), + ) + else: + y_classes = y + if len(y.shape) == 2: + if y.shape[1] > 1: + y_classes = np.argmax(y, axis=1) + elif y.shape[1] == 1: + y_classes = np.reshape(y, y.shape[0]) + + class_sample_weight = np.asarray( + [class_weight[cls] for cls in y_classes if cls in class_weight]) + + if len(class_sample_weight) != len(y_classes): + # subtract the sets to pick all missing classes + existing_classes = set(y_classes) + existing_class_weight = set(class_weight.keys()) + raise ValueError( + '`class_weight` must contain all classes in the data.' + ' The classes %s exist in the data but not in ' + '`class_weight`.' % (existing_classes - existing_class_weight)) + + if class_sample_weight is not None and sample_weight is not None: + # Multiply weights if both are provided. + return class_sample_weight * sample_weight + if sample_weight is not None: + return sample_weight + if class_sample_weight is not None: + return class_sample_weight + return None + + +def has_symbolic_tensors(ls): + if context.executing_eagerly(): + return False + return has_tensors(ls) + + +def has_tensors(ls): + """Returns true if `ls` contains tensors.""" + # Note: at some point in time ragged tensors didn't count as tensors, so this + # returned false for ragged tensors. Making this return true fails some tests + # which would then require a steps_per_epoch argument. + if isinstance(ls, (list, tuple)): + return any( + tensor_util.is_tf_type(v) and + not isinstance(v, ragged_tensor.RaggedTensor) for v in ls) + if isinstance(ls, dict): + return any( + tensor_util.is_tf_type(v) and + not isinstance(v, ragged_tensor.RaggedTensor) + for _, v in ls.items()) + return tensor_util.is_tf_type(ls) and not isinstance( + ls, ragged_tensor.RaggedTensor) + + +def get_metric_name(metric, weighted=False): + """Returns the name corresponding to the given metric input. + + Args: + metric: Metric function name or reference. + weighted: Boolean indicating if the given metric is weighted. + + Returns: + The metric name. + """ + if tf2.enabled(): + # We keep the string that the user has set in compile as the metric name. + if isinstance(metric, str): + return metric + + metric = metrics_module.get(metric) + return metric.name if hasattr(metric, 'name') else metric.__name__ + else: + metric_name_prefix = 'weighted_' if weighted else '' + if metric in ('accuracy', 'acc', 'crossentropy', 'ce'): + if metric in ('accuracy', 'acc'): + suffix = 'acc' + elif metric in ('crossentropy', 'ce'): + suffix = 'ce' + else: + metric_fn = metrics_module.get(metric) + # Get metric name as string + if hasattr(metric_fn, 'name'): + suffix = metric_fn.name + else: + suffix = metric_fn.__name__ + metric_name = metric_name_prefix + suffix + return metric_name + + +def get_metric_function(metric, output_shape=None, loss_fn=None): + """Returns the metric function corresponding to the given metric input. + + Args: + metric: Metric function name or reference. + output_shape: The shape of the output that this metric will be calculated + for. + loss_fn: The loss function used. + + Returns: + The metric function. + """ + if metric not in ['accuracy', 'acc', 'crossentropy', 'ce']: + return metrics_module.get(metric) + + is_sparse_categorical_crossentropy = ( + isinstance(loss_fn, losses.SparseCategoricalCrossentropy) or + (isinstance(loss_fn, losses.LossFunctionWrapper) and + loss_fn.fn == losses.sparse_categorical_crossentropy)) + + is_binary_crossentropy = ( + isinstance(loss_fn, losses.BinaryCrossentropy) or + (isinstance(loss_fn, losses.LossFunctionWrapper) and + loss_fn.fn == losses.binary_crossentropy)) + + if metric in ['accuracy', 'acc']: + if output_shape[-1] == 1 or is_binary_crossentropy: + return metrics_module.binary_accuracy + elif is_sparse_categorical_crossentropy: + return metrics_module.sparse_categorical_accuracy + # If the output_shape[-1] is not 1, then we know output is `categorical`. + # We assume it is sparse categorical only if loss is explicitly given + # as sparse categorical crossentropy loss. + return metrics_module.categorical_accuracy + else: + if output_shape[-1] == 1 or is_binary_crossentropy: + return metrics_module.binary_crossentropy + elif is_sparse_categorical_crossentropy: + return metrics_module.sparse_categorical_crossentropy + return metrics_module.categorical_crossentropy + + +def call_metric_function(metric_fn, + y_true, + y_pred=None, + weights=None, + mask=None): + """Invokes metric function and returns the metric result tensor.""" + if mask is not None: + mask = math_ops.cast(mask, y_pred.dtype) + if weights is None: + # Use mask as sample weight. + weights = mask + else: + # Update dimensions of weights to match with mask. + weights = math_ops.cast(weights, dtype=y_pred.dtype) + mask, _, weights = losses_utils.squeeze_or_expand_dimensions( + mask, sample_weight=weights) + weights *= mask + + if y_pred is not None: + return metric_fn(y_true, y_pred, sample_weight=weights) + # `Mean` metric only takes a single value. + return metric_fn(y_true, sample_weight=weights) + + +def get_loss_function(loss): + """Returns the loss corresponding to the loss input in `compile` API.""" + if loss is None or isinstance(loss, losses.Loss): + return loss + + if tf_inspect.isclass(loss) and issubclass(loss, losses.Loss): + # It is not safe to assume that the loss takes no constructor arguments. + raise ValueError( + 'Received uninstantiated Loss class: {}\nPlease call loss ""classes ' + 'before passing them to Model.compile.'.format(loss)) + + # Deserialize loss configuration, if needed. + if isinstance(loss, collections.abc.Mapping): + loss = losses.get(loss) + + # Custom callable class. + if callable(loss) and not hasattr(loss, '__name__'): + return loss + + # Wrap loss function with signature `(y_true, y_pred, **kwargs)` + # in `LossFunctionWrapper` class. + loss_fn = losses.get(loss) + + # For losses which are given as strings/functions in the compile API, + # we always set the loss reduction type to be `SUM_OVER_BATCH_SIZE` + # (both in distribution strategy context and otherwise). + return losses.LossFunctionWrapper( + loss_fn, + name=loss_fn.__name__, + reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE) + + +def validate_dataset_input(x, y, sample_weight, validation_split=None): + """Validates user input arguments when a dataset iterator is passed. + + Args: + x: Input data. A `tf.data` dataset or iterator. + y: Target data. It could be either Numpy array(s) or TensorFlow tensor(s). + Expected to be `None` when `x` is a dataset iterator. + sample_weight: An optional sample-weight array passed by the user to weight + the importance of each sample in `x`. Expected to be `None` when `x` is a + dataset iterator + validation_split: Float between 0 and 1. Fraction of the training data to be + used as validation data. Expected to be `None` when `x` is a dataset + iterator. + + Raises: + ValueError: if argument `y` or `sample_weight` or `validation_split` are + provided by user. + """ + if y is not None: + raise ValueError('You passed a dataset or dataset iterator (%s) as ' + 'input `x` to your model. In that case, you should ' + 'not specify a target (`y`) argument, since the dataset ' + 'or dataset iterator generates both input data and ' + 'target data. ' + 'Received: %s' % (x, y)) + if sample_weight is not None: + raise ValueError('`sample_weight` argument is not supported when input ' + '`x` is a dataset or a dataset iterator. Instead, you' + 'can provide sample_weight as the third element of your' + 'dataset, i.e. (inputs, targets, sample_weight). ' + 'Received: x=%s, sample_weight=%s' % (x, sample_weight)) + if validation_split is not None and validation_split != 0.0: + raise ValueError( + '`validation_split` argument is not supported when ' + 'input `x` is a dataset or a dataset iterator. ' + 'Received: x=%s, validation_split=%f' % (x, validation_split)) + + +def validate_input_types(inp, orig_inp, allow_dict=True, field_name='inputs'): + """Helper function to validate either inputs or targets.""" + if isinstance(inp, (list, tuple)): + if not all(isinstance(v, np.ndarray) or + tensor_util.is_tf_type(v) for v in inp): + raise ValueError( + 'Please provide as model inputs either a single array or a list of ' + 'arrays. You passed: {}={}'.format(field_name, str(orig_inp))) + elif isinstance(inp, dict): + if not allow_dict: + raise ValueError( + 'You cannot pass a dictionary as model {}.'.format(field_name)) + elif not isinstance(inp, np.ndarray) and not tensor_util.is_tf_type(inp): + raise ValueError( + 'Please provide as model inputs either a single array or a list of ' + 'arrays. You passed: {}={}'.format(field_name, orig_inp)) + + +def check_generator_arguments(y=None, sample_weight=None, + validation_split=None): + """Validates arguments passed when using a generator.""" + if y is not None: + raise ValueError('`y` argument is not supported when data is' + 'a generator or Sequence instance. Instead pass targets' + ' as the second element of the generator.') + if sample_weight is not None: + raise ValueError('`sample_weight` argument is not supported when data is' + 'a generator or Sequence instance. Instead pass sample' + ' weights as the third element of the generator.') + if validation_split: + raise ValueError('If your data is in the form of a Python generator, ' + 'you cannot use `validation_split`.') + + +def check_steps_argument(input_data, steps, steps_name): + """Validates `steps` argument based on input data's type. + + The cases when `steps` value must be provided are when + 1. input data passed is an iterator. + 2. model was built on top of symbolic tensors, input data is not + required and is `None`. + 3. input data passed is a symbolic tensor. + + Args: + input_data: Input data. Can be Numpy array(s) or TensorFlow tensor(s) or + tf.data.Dataset iterator or `None`. + steps: Integer or `None`. Total number of steps (batches of samples) to + execute. + steps_name: The public API's parameter name for `steps`. + + Returns: + boolean, True if `steps` argument is required, else False. + + Raises: + ValueError: if `steps` argument is required for given input data type + but not provided. + """ + is_x_iterator = isinstance( + input_data, (iterator_ops.Iterator, iterator_ops.IteratorBase)) + if (input_data is None or is_x_iterator or has_symbolic_tensors(input_data) or + (isinstance(input_data, list) and not input_data)): + if steps is None: + input_type_str = 'a Dataset iterator' if is_x_iterator else 'data tensors' + raise ValueError('When using {input_type} as input to a model, you should' + ' specify the `{steps_name}` argument.'.format( + input_type=input_type_str, steps_name=steps_name)) + return True + + if isinstance(input_data, (data_types.DatasetV1, data_types.DatasetV2)): + return True + + if steps is not None: + list_types = (np.ndarray, list, tuple) + if (isinstance(input_data, list_types) or + (isinstance(input_data, dict) and + any(isinstance(v, list_types) for v in input_data.values()))): + logging.warning('When passing input data as arrays, do not specify ' + '`steps_per_epoch`/`steps` argument. ' + 'Please use `batch_size` instead.') + return False + + +def cast_single_tensor(x, dtype=None): + if isinstance(x, np.ndarray): + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + dtype = dtype or backend.floatx() + if x.dtype.is_floating: + return math_ops.cast(x, dtype=dtype) + return x + + +def cast_if_floating_dtype_and_mismatch(targets, outputs): + """Returns target data tensors using correct datatype. + + Checks that each target and output pair are the same datatype. If not, casts + the target to the output's datatype. + + Args: + targets: tensor or list of targets. + outputs: tensor or list of outputs. + + Returns: + Targets in appropriate datatype. + """ + if tensor_util.is_tf_type(targets): + # There is one target, so output[0] should be the only output. + return cast_single_tensor(targets, dtype=outputs[0].dtype) + new_targets = [] + for target, out in zip(targets, outputs): + if isinstance(target, np.ndarray): + target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target) + if target.dtype != out.dtype: + new_targets.append(cast_single_tensor(target, dtype=out.dtype)) + else: + new_targets.append(target) + return new_targets + + +def cast_if_floating_dtype(x, dtype=None): + """Casts the given data tensors to the default floating point type. + + Casts only if the input is already a floating point type. + Args: + x: tensor or list/tuple of tensors. + dtype: The dtype to which Tensors should be cast. + + Returns: + Converted input. + """ + return nest.map_structure(functools.partial(cast_single_tensor, dtype=dtype), + x) + + +def cast_to_model_input_dtypes(x, model): + """Casts the given data tensors to the dtypes of the model inputs. + + Args: + x: tensor or list/tuple of tensors. + model: The model. + + Returns: + Converted input. Each tensor is casted to the corresponding input in + `model.inputs`. + """ + input_dtypes = nest.map_structure(lambda t: t.dtype, model.inputs) + return nest.map_structure(math_ops.cast, x, input_dtypes) + + +def prepare_sample_weight_modes(training_endpoints, sample_weight_mode): + """Prepares sample weight modes for the model. + + Args: + training_endpoints: List of model _TrainingEndpoints. + sample_weight_mode: sample weight mode user input passed from compile API. + + Raises: + ValueError: In case of invalid `sample_weight_mode` input. + """ + + if isinstance(sample_weight_mode, collections.abc.Mapping): + generic_utils.check_for_unexpected_keys( + 'sample_weight_mode', sample_weight_mode, + [e.output_name for e in training_endpoints]) + + for end_point in training_endpoints: + if not end_point.should_skip_target_weights(): + if end_point.output_name not in sample_weight_mode: + raise ValueError('Output ' + end_point.output_name + + 'missing from `_sample_weight_modes` dictionary') + else: + end_point.sample_weight_mode = sample_weight_mode.get( + end_point.output_name) + elif isinstance(sample_weight_mode, (list, tuple)): + if len(sample_weight_mode) != len(training_endpoints): + raise ValueError('When passing a list as sample_weight_mode, ' + 'it should have one entry per model output. ' + 'The model has ' + str(len(training_endpoints)) + + ' outputs, but you passed ' + + str(len(sample_weight_mode)) + '_sample_weight_modes.') + for mode, endpoint in zip(sample_weight_mode, training_endpoints): + if not endpoint.should_skip_target_weights(): + endpoint.sample_weight_mode = mode + else: + for endpoint in training_endpoints: + if not endpoint.should_skip_target_weights(): + endpoint.sample_weight_mode = sample_weight_mode + + +def prepare_loss_functions(loss, output_names): + """Converts loss to a list of loss functions. + + Args: + loss: String (name of objective function), objective function or + `tf.losses.Loss` instance. See `tf.losses`. If the model has multiple + outputs, you can use a different loss on each output by passing a + dictionary or a list of losses. The loss value that will be minimized by + the model will then be the sum of all individual losses. + output_names: List of model output names. + + Returns: + A list of loss objective functions. + + Raises: + ValueError: If loss is a dict with keys not in model output names, + or if loss is a list with len not equal to model outputs. + """ + if isinstance(loss, collections.abc.Mapping): + generic_utils.check_for_unexpected_keys('loss', loss, output_names) + loss_functions = [] + for name in output_names: + if name not in loss: + logging.warning( + 'Output {0} missing from loss dictionary. We assume ' + 'this was done on purpose. The fit and evaluate APIs will not be ' + 'expecting any data to be passed to {0}.'.format(name)) + loss_functions.append(get_loss_function(loss.get(name, None))) + elif isinstance(loss, str): + loss_functions = [get_loss_function(loss) for _ in output_names] + elif isinstance(loss, collections.abc.Sequence): + if len(loss) != len(output_names): + raise ValueError('When passing a list as loss, it should have one entry ' + 'per model outputs. The model has {} outputs, but you ' + 'passed loss={}'.format(len(output_names), loss)) + loss_functions = nest.map_structure(get_loss_function, loss) + else: + loss_functions = [get_loss_function(loss) for _ in range(len(output_names))] + + return loss_functions + + +def prepare_loss_weights(training_endpoints, loss_weights=None): + """Converts loss weights to a list of loss weights. + + The result loss weights will be populated on the training endpoint. + + Args: + training_endpoints: List of model training endpoints. + loss_weights: Optional list or dictionary specifying scalar coefficients + (Python floats) to weight the loss contributions of different model + outputs. The loss value that will be minimized by the model will then be + the *weighted sum* of all individual losses, weighted by the + `loss_weights` coefficients. If a list, it is expected to have a 1:1 + mapping to the model's outputs. If a dict, it is expected to map + output names (strings) to scalar coefficients. + + Raises: + ValueError: If loss weight is a dict with key not in model output names, + or if loss is a list with len not equal to model outputs. + """ + if loss_weights is None: + for e in training_endpoints: + e.loss_weight = 1. + elif isinstance(loss_weights, collections.abc.Mapping): + generic_utils.check_for_unexpected_keys( + 'loss_weights', loss_weights, + [e.output_name for e in training_endpoints]) + for e in training_endpoints: + e.loss_weight = loss_weights.get(e.output_name, 1.) + elif isinstance(loss_weights, list): + if len(loss_weights) != len(training_endpoints): + raise ValueError('When passing a list as loss_weights, ' + 'it should have one entry per model output. ' + 'The model has ' + str(len(training_endpoints)) + + ' outputs, but you passed loss_weights=' + + str(loss_weights)) + for w, e in zip(loss_weights, training_endpoints): + e.loss_weight = w + else: + raise TypeError('Could not interpret loss_weights argument: ' + + str(loss_weights) + ' - expected a list of dicts.') + + +# TODO(rohanj): This is a hack to get around not depending on feature_column and +# create a cyclical dependency. Figure out a cleaner solution +def is_feature_layer(layer): + """Returns whether `layer` is a FeatureLayer or not.""" + return getattr(layer, '_is_feature_layer', False) + + +def is_eager_dataset_or_iterator(data): + return context.executing_eagerly() and isinstance( + data, (data_types.DatasetV1, data_types.DatasetV2, + iterator_ops.IteratorBase)) + + +# pylint: disable=protected-access +def get_dataset_graph_def(dataset): + if context.executing_eagerly(): + graph_def_str = dataset._as_serialized_graph().numpy() + else: + graph_def_str = backend.get_value(dataset._as_serialized_graph()) + return graph_pb2.GraphDef().FromString(graph_def_str) + + +def verify_dataset_shuffled(x): + """Verifies that the dataset is shuffled. + + Args: + x: Dataset passed as an input to the model. + + Returns: + boolean, whether the input dataset is shuffled or not. + """ + assert isinstance(x, data_types.DatasetV2) + graph_def = get_dataset_graph_def(x) + for node in graph_def.node: + if node.op.startswith('ShuffleDataset'): + return True + # Also check graph_def.library.function for ds.interleave or ds.flat_map + for function in graph_def.library.function: + for node in function.node_def: + if node.op.startswith('ShuffleDataset'): + return True + logging.warning('Expected a shuffled dataset but input dataset `x` is ' + 'not shuffled. Please invoke `shuffle()` on input dataset.') + return False + + +def is_dataset_or_iterator(data): + return isinstance(data, (data_types.DatasetV1, data_types.DatasetV2, + iterator_ops.Iterator, iterator_ops.IteratorBase)) + + +def get_iterator(dataset): + """Create and initialize an iterator from a dataset.""" + if context.executing_eagerly(): + iterator = dataset_ops.make_one_shot_iterator(dataset) + else: + iterator = dataset_ops.make_initializable_iterator(dataset) + initialize_iterator(iterator) + return iterator + + +def initialize_iterator(iterator): + if not context.executing_eagerly(): + init_op = iterator.initializer + backend.get_session((init_op,)).run(init_op) + + +def extract_tensors_from_dataset(dataset): + """Extract a tuple of tensors `inputs, targets, sample_weight` from a dataset. + + Args: + dataset: Dataset instance. + + Returns: + Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None. + """ + iterator = get_iterator(dataset) + inputs, targets, sample_weight = unpack_iterator_input(iterator) + return inputs, targets, sample_weight + + +def unpack_iterator_input(iterator): + """Convert a dataset iterator to a tuple of tensors `x, y, sample_weights`. + + Args: + iterator: Instance of a dataset iterator. + + Returns: + Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None. + """ + try: + next_element = iterator.get_next() + except errors.OutOfRangeError: + raise RuntimeError('Your dataset iterator ran out of data; ' + 'Make sure that your dataset can generate ' + 'required number of samples.') + + if isinstance(next_element, (list, tuple)): + if len(next_element) not in [2, 3]: + raise ValueError( + 'Please provide model inputs as a list or tuple of 2 or 3 ' + 'elements: (input, target) or (input, target, sample_weights) ' + 'Received %s' % next_element) + if len(next_element) == 2: + x, y = next_element + weights = None + else: + x, y, weights = next_element + else: + x = next_element + y = None + weights = None + return x, y, weights + + +def infer_steps_for_dataset(model, + dataset, + steps, + epochs=1, + steps_name='steps'): + """Infers steps_per_epoch needed to loop through a dataset. + + Args: + model: Keras model instance. + dataset: Input data of type tf.data.Dataset. + steps: Number of steps to draw from the dataset (may be None if unknown). + epochs: Number of times to iterate over the dataset. + steps_name: The string name of the steps argument, either `steps`, + `validation_steps`, or `steps_per_epoch`. Only used for error message + formatting. + + Returns: + Integer or `None`. Inferred number of steps to loop through the dataset. + `None` is returned if 1) the size of the dataset is unknown and `steps` was + not specified, or 2) this is multi-worker training and auto sharding is + enabled. + + Raises: + ValueError: In case of invalid argument values. + """ + assert isinstance(dataset, data_types.DatasetV2) + if (model._in_multi_worker_mode() and + (dataset.options().experimental_distribute.auto_shard_policy != + options_lib.AutoShardPolicy.OFF)): + # If the dataset would be auto-sharded, we should not infer a local + # steps_per_epoch due to the possible inbalanced sharding between workers. + return None + + size = backend.get_value(cardinality.cardinality(dataset)) + if size == cardinality.INFINITE and steps is None: + raise ValueError('When passing an infinitely repeating dataset, you ' + 'must specify the `%s` argument.' % (steps_name,)) + if size >= 0: + if steps is not None and steps * epochs > size: + if epochs > 1: + raise ValueError('The dataset you passed contains %s batches, but you ' + 'passed `epochs=%s` and `%s=%s`, which is a total of ' + '%s steps. We cannot draw that many steps from this ' + 'dataset. We suggest to set `%s=%s`.' % + (size, epochs, steps_name, steps, steps * epochs, + steps_name, size // epochs)) + else: + raise ValueError('The dataset you passed contains %s batches, but you ' + 'passed `%s=%s`. We cannot draw that many steps from ' + 'this dataset. We suggest to set `%s=%s`.' % + (size, steps_name, steps, steps_name, size)) + if steps is None: + if size >= 0: + return size + return None + return steps + + +class ModelInputs(object): + """Encapsulates model inputs. + + Allows for transforming model inputs while keeping the same structure. + """ + + def __init__(self, inputs): + self._inputs = inputs + self._is_dict = isinstance(self._inputs, dict) + self._is_single_input = not isinstance(self._inputs, (list, tuple, dict)) + + self._flattened_inputs = [] + self._input_names = [] + + if self._is_dict: + for k in sorted(self._inputs.keys()): + self._flattened_inputs.append(self._inputs[k]) + self._input_names.append(k) + else: + self._flattened_inputs = nest.flatten(self._inputs) + self._input_names = [ + 'input_%d' % (i + 1) for i in range(len(self._flattened_inputs)) + ] + + def get_input_names(self): + """Returns keys to name inputs by. + + In case inputs provided were a list, tuple or single entry, we make up a + key 'input_%d'. For dictionary case, we return a sorted list of keys. + """ + return self._input_names + + def get_symbolic_inputs(self, return_single_as_list=False): + """Returns inputs to be set as self.inputs for a model.""" + # TODO(karmel): There is a side-effect here where what you get + # with as_list and as_dict depends on whether you have called this + # method first, since it modifies in place. + for i, (k, v) in enumerate(zip(self._input_names, self._flattened_inputs)): + if isinstance(v, (list, float, int)): + v = np.asarray(v) + if v.ndim == 1: + v = np.expand_dims(v, 1) + + if isinstance(v, np.ndarray): + # We fix the placeholder shape except the batch size. + # This is suboptimal, but it is the best we can do with the info + # we have. The user should call `model._set_inputs(placeholders)` + # to specify custom placeholders if the need arises. + shape = (None,) + tuple(v.shape[1:]) + if shape == (None,): + shape = (None, 1) + dtype = dtypes.as_dtype(v.dtype) + if dtype.is_floating: + dtype = backend.floatx() + v = backend.placeholder(shape=shape, name=k, dtype=dtype) + elif isinstance(v, tensor_spec.TensorSpec): + shape = (None,) + tuple(v.shape.as_list()[1:]) + if shape == (None,): + shape = (None, 1) + v = backend.placeholder(shape=shape, name=k, dtype=v.dtype) + + self._flattened_inputs[i] = v + + if self._is_dict: + return dict(zip(self._input_names, self._flattened_inputs)) + if self._is_single_input and not return_single_as_list: + return self._flattened_inputs[0] + return self._flattened_inputs + + def as_dict(self): + """An iterable over a dictionary version of inputs.""" + for k, v in zip(self._input_names, self._flattened_inputs): + yield k, v + + def as_list(self): + """Returning the inputs as a list.""" + return self._flattened_inputs + + +# Allow use of methods not exposed to the user. +# pylint: disable=protected-access + + +# pylint: enable=protected-access + + +def generic_output_names(outputs_list): + return ['output_%d' % (i + 1) for i in range(len(outputs_list))] + + +def should_run_validation(validation_freq, epoch): + """Checks if validation should be run this epoch. + + Args: + validation_freq: Integer or list. If an integer, specifies how many training + epochs to run before a new validation run is performed. If a list, + specifies the epochs on which to run validation. + epoch: Integer, the number of the training epoch just completed. + + Returns: + Bool, True if validation should be run. + + Raises: + ValueError: if `validation_freq` is an Integer and less than 1, or if + it is neither an Integer nor a Sequence. + """ + # `epoch` is 0-indexed internally but 1-indexed in the public API. + one_indexed_epoch = epoch + 1 + + if isinstance(validation_freq, int): + if validation_freq < 1: + raise ValueError('`validation_freq` can not be less than 1.') + return one_indexed_epoch % validation_freq == 0 + + if not isinstance(validation_freq, collections.abc.Container): + raise ValueError('`validation_freq` must be an Integer or ' + '`collections.abc.Container` (e.g. list, tuple, etc.)') + return one_indexed_epoch in validation_freq + + +def split_training_and_validation_data(x, y, sample_weights, validation_split): + """Split input data into train/eval section based on validation_split.""" + if has_symbolic_tensors(x): + raise ValueError('If your data is in the form of symbolic tensors, ' + 'you cannot use `validation_split`.') + if hasattr(x[0], 'shape'): + split_at = int(x[0].shape[0] * (1. - validation_split)) + else: + split_at = int(len(x[0]) * (1. - validation_split)) + x, val_x = (generic_utils.slice_arrays(x, 0, split_at), + generic_utils.slice_arrays(x, split_at)) + y, val_y = (generic_utils.slice_arrays(y, 0, split_at), + generic_utils.slice_arrays(y, split_at)) + if sample_weights: + sample_weights, val_sample_weights = ( + generic_utils.slice_arrays(sample_weights, 0, split_at), + generic_utils.slice_arrays(sample_weights, split_at), + ) + else: + val_sample_weights = None + return x, y, sample_weights, val_x, val_y, val_sample_weights + + +def unpack_validation_data(validation_data, raise_if_ambiguous=True): + """Unpack validation data based input type. + + The validation data is not touched if its dataset or dataset iterator. + For other type of input (Numpy or tensor), it will be unpacked into tuple of + 3 which is x, y and sample weights. + + Args: + validation_data: dataset, dataset iterator, or numpy, tensor tuple. + raise_if_ambiguous: boolean on whether to fail if validation_data cannot be + parsed. Otherwise simply return validation_data, None, None and defer the + decision to the caller. + + Returns: + tuple of 3, (x, y, sample_weights) for numpy and tensor input. + """ + if (isinstance(validation_data, (iterator_ops.Iterator, + iterator_ops.IteratorBase, + data_types.DatasetV2, + data_utils.Sequence)) + or not hasattr(validation_data, '__len__')): + val_x = validation_data + val_y = None + val_sample_weight = None + elif len(validation_data) == 2: + try: + val_x, val_y = validation_data # pylint: disable=unpacking-non-sequence + val_sample_weight = None + except ValueError: + val_x, val_y, val_sample_weight = validation_data, None, None + elif len(validation_data) == 3: + try: + val_x, val_y, val_sample_weight = validation_data # pylint: disable=unpacking-non-sequence + except ValueError: + val_x, val_y, val_sample_weight = validation_data, None, None + else: + if raise_if_ambiguous: + raise ValueError( + 'When passing a `validation_data` argument, ' + 'it must contain either 2 items (x_val, y_val), ' + 'or 3 items (x_val, y_val, val_sample_weights), ' + 'or alternatively it could be a dataset or a ' + 'dataset or a dataset iterator. ' + 'However we received `validation_data=%s`' % validation_data) + val_x, val_y, val_sample_weight = validation_data, None, None + return val_x, val_y, val_sample_weight + + +class TrainingLoop(object): + """TrainingLoop is a wrapper class around the training logic. + + This class is trying to encapsulate the different logic of fit/eval/predict + with regard to different data input and model condition. + + Note that TrainingLoop is stateless, which means it doesn't contain any + internal field and can be reused with different model and inputs. + """ + + def fit(self, + model, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + **kwargs): + """Train the model with the inputs and targets.""" + raise NotImplementedError() + + def evaluate(self, + model, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + **kwargs): + """Returns the loss value & metrics values for the model in test mode.""" + raise NotImplementedError() + + def predict(self, + model, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + **kwargs): + raise NotImplementedError() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..f0843908e4b8233c26e51cd235fdad4a40950f42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/engine/training_v1.py @@ -0,0 +1,3216 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""V1 Training-related part of the Keras engine.""" + +import collections +import warnings + +import numpy as np + +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import parameter_server_strategy +from tensorflow.python.distribute import parameter_server_strategy_v2 +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.keras import backend +from tensorflow.python.keras import losses +from tensorflow.python.keras import metrics as metrics_module +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras import optimizers +from tensorflow.python.keras.distribute import distributed_training_utils +from tensorflow.python.keras.distribute import distributed_training_utils_v1 +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import training as training_lib +from tensorflow.python.keras.engine import training_arrays_v1 +from tensorflow.python.keras.engine import training_distributed_v1 +from tensorflow.python.keras.engine import training_eager_v1 +from tensorflow.python.keras.engine import training_generator_v1 +from tensorflow.python.keras.engine import training_utils +from tensorflow.python.keras.engine import training_utils_v1 +from tensorflow.python.keras.mixed_precision import loss_scale_optimizer +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import model_serialization +from tensorflow.python.keras.utils import data_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest + +try: + from scipy.sparse import issparse # pylint: disable=g-import-not-at-top +except ImportError: + issparse = None + + +class Model(training_lib.Model): + """`Model` groups layers into an object with training and inference features. + + There are two ways to instantiate a `Model`: + + 1 - With the "functional API", where you start from `Input`, + you chain layer calls to specify the model's forward pass, + and finally you create your model from inputs and outputs: + + ```python + import tensorflow as tf + + inputs = tf.keras.Input(shape=(3,)) + x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) + outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) + model = tf.keras.Model(inputs=inputs, outputs=outputs) + ``` + + 2 - By subclassing the `Model` class: in that case, you should define your + layers in `__init__` and you should implement the model's forward pass + in `call`. + + ```python + import tensorflow as tf + + class MyModel(tf.keras.Model): + + def __init__(self): + super(MyModel, self).__init__() + self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) + self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) + + def call(self, inputs): + x = self.dense1(inputs) + return self.dense2(x) + + model = MyModel() + ``` + + If you subclass `Model`, you can optionally have + a `training` argument (boolean) in `call`, which you can use to specify + a different behavior in training and inference: + + ```python + import tensorflow as tf + + class MyModel(tf.keras.Model): + + def __init__(self): + super(MyModel, self).__init__() + self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) + self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) + self.dropout = tf.keras.layers.Dropout(0.5) + + def call(self, inputs, training=False): + x = self.dense1(inputs) + if training: + x = self.dropout(x, training=training) + return self.dense2(x) + + model = MyModel() + ``` + """ + + def __init__(self, *args, **kwargs): + super(Model, self).__init__(*args, **kwargs) + # initializing _distribution_strategy here since it is possible to call + # predict on a model without compiling it. + self._distribution_strategy = None + self._compile_time_distribution_strategy = None + if (ops.executing_eagerly_outside_functions() and + distribute_lib.has_strategy()): + self._set_strategy( + distribute_lib.get_strategy()) + + # This flag is used to track if the user is using the deprecated path of + # passing distribution strategy to compile rather than creating the model + # under distribution strategy scope. + self._compile_distribution = False + + self._run_eagerly = None + self._experimental_run_tf_function = ( + ops.executing_eagerly_outside_functions()) + + self._v1_compile_was_called = False + + def _init_batch_counters(self): + pass # Batch counters should not be created in legacy graph mode. + + @trackable.no_automatic_dependency_tracking + def _set_strategy(self, strategy): + self._compile_time_distribution_strategy = strategy + + def get_weights(self): + """Retrieves the weights of the model. + + Returns: + A flat list of Numpy arrays. + """ + strategy = (self._distribution_strategy or + self._compile_time_distribution_strategy) + if strategy: + with strategy.scope(): + return base_layer.Layer.get_weights(self) + return base_layer.Layer.get_weights(self) + + def load_weights(self, filepath, by_name=False, skip_mismatch=False): + """Loads all layer weights, either from a TensorFlow or an HDF5 weight file. + + If `by_name` is False weights are loaded based on the network's + topology. This means the architecture should be the same as when the weights + were saved. Note that layers that don't have weights are not taken into + account in the topological ordering, so adding or removing layers is fine as + long as they don't have weights. + + If `by_name` is True, weights are loaded into layers only if they share the + same name. This is useful for fine-tuning or transfer-learning models where + some of the layers have changed. + + Only topological loading (`by_name=False`) is supported when loading weights + from the TensorFlow format. Note that topological loading differs slightly + between TensorFlow and HDF5 formats for user-defined classes inheriting from + `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the + TensorFlow format loads based on the object-local names of attributes to + which layers are assigned in the `Model`'s constructor. + + Args: + filepath: String, path to the weights file to load. For weight files in + TensorFlow format, this is the file prefix (the same as was passed + to `save_weights`). + by_name: Boolean, whether to load weights by name or by topological + order. Only topological loading is supported for weight files in + TensorFlow format. + skip_mismatch: Boolean, whether to skip loading of layers where there is + a mismatch in the number of weights, or a mismatch in the shape of + the weight (only valid when `by_name=True`). + + Returns: + When loading a weight file in TensorFlow format, returns the same status + object as `tf.train.Checkpoint.restore`. When graph building, restore + ops are run automatically as soon as the network is built (on first call + for user-defined classes inheriting from `Model`, immediately if it is + already built). + + When loading weights in HDF5 format, returns `None`. + + Raises: + ImportError: If h5py is not available and the weight file is in HDF5 + format. + ValueError: If `skip_mismatch` is set to `True` when `by_name` is + `False`. + """ + if backend.is_tpu_strategy(self._distribution_strategy): + if (self._distribution_strategy.extended.steps_per_run > 1 and + (not saving_utils.is_hdf5_filepath(filepath))): # pylint: disable=protected-access + raise ValueError('Load weights is not yet supported with TPUStrategy ' + 'with steps_per_run greater than 1.') + return super(Model, self).load_weights(filepath, by_name, skip_mismatch) + + @trackable.no_automatic_dependency_tracking + def compile(self, + optimizer='rmsprop', + loss=None, + metrics=None, + loss_weights=None, + sample_weight_mode=None, + weighted_metrics=None, + target_tensors=None, + distribute=None, + **kwargs): + """Configures the model for training. + + Args: + optimizer: String (name of optimizer) or optimizer instance. + See `tf.keras.optimizers`. + loss: String (name of objective function), objective function or + `tf.keras.losses.Loss` instance. See `tf.keras.losses`. An objective + function is any callable with the signature + `scalar_loss = fn(y_true, y_pred)`. If the model has multiple + outputs, you can use a different loss on each output by passing a + dictionary or a list of losses. The loss value that will be + minimized by the model will then be the sum of all individual + losses. + metrics: List of metrics to be evaluated by the model during training + and testing. Typically you will use `metrics=['accuracy']`. + To specify different metrics for different outputs of a + multi-output model, you could also pass a dictionary, such as + `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`. + You can also pass a list (len = len(outputs)) of lists of metrics + such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or + `metrics=['accuracy', ['accuracy', 'mse']]`. + loss_weights: Optional list or dictionary specifying scalar + coefficients (Python floats) to weight the loss contributions + of different model outputs. + The loss value that will be minimized by the model + will then be the *weighted sum* of all individual losses, + weighted by the `loss_weights` coefficients. + If a list, it is expected to have a 1:1 mapping + to the model's outputs. If a tensor, it is expected to map + output names (strings) to scalar coefficients. + sample_weight_mode: If you need to do timestep-wise + sample weighting (2D weights), set this to `"temporal"`. + `None` defaults to sample-wise weights (1D). + If the model has multiple outputs, you can use a different + `sample_weight_mode` on each output by passing a + dictionary or a list of modes. + weighted_metrics: List of metrics to be evaluated and weighted + by sample_weight or class_weight during training and testing. + target_tensors: By default, Keras will create placeholders for the + model's target, which will be fed with the target data during + training. If instead you would like to use your own + target tensors (in turn, Keras will not expect external + Numpy data for these targets at training time), you + can specify them via the `target_tensors` argument. It can be + a single tensor (for a single-output model), a list of tensors, + or a dict mapping output names to target tensors. + distribute: NOT SUPPORTED IN TF 2.0, please create and compile the + model under distribution strategy scope instead of passing it to + compile. + **kwargs: Any additional arguments. + + Raises: + ValueError: In case of invalid arguments for + `optimizer`, `loss`, `metrics` or `sample_weight_mode`. + """ + self._assert_built_as_v1() + self._run_eagerly = kwargs.pop('run_eagerly', None) + self._experimental_run_tf_function = kwargs.pop( + 'experimental_run_tf_function', True) + self._v1_compile_was_called = True + + # Prepare Session arguments (legacy). + kwargs.pop('cloning', None) # Legacy DistStrat argument, never used. + self._from_serialized = kwargs.pop('from_serialized', False) + allowed_kwargs = {'feed_dict', 'fetches', 'options', 'run_metadata'} + unknown_kwargs = set(kwargs.keys()) - allowed_kwargs + if unknown_kwargs: + raise TypeError( + 'Invalid keyword argument(s) in `compile`: %s' % (unknown_kwargs,)) + self._function_kwargs = kwargs + if self._function_kwargs: + self._experimental_run_tf_function = False + if self.run_eagerly: + raise ValueError( + 'Session keyword arguments are not supported ' + 'when `run_eagerly=True`. You passed the following ' + 'Session arguments: %s' % (self._function_kwargs,)) + + self._set_optimizer(optimizer) + is_any_keras_optimizer_v1 = any( + (isinstance(opt, optimizer_v1.Optimizer) + and not isinstance(opt, optimizer_v1.TFOptimizer) + ) for opt in nest.flatten(self.optimizer)) + + if is_any_keras_optimizer_v1 and ops.executing_eagerly_outside_functions(): + raise ValueError('`tf.compat.v1.keras` Optimizer (', optimizer, ') is ' + 'not supported when eager execution is enabled. Use a ' + '`tf.keras` Optimizer instead, or disable eager ' + 'execution.') + + if ((target_tensors is not None) + or not ops.executing_eagerly_outside_functions()): + # Fallback out of things that aren't supported with v2 loops + self._experimental_run_tf_function = False + + if distribute is not None: + if tf2.enabled() or self._experimental_run_tf_function: + raise ValueError( + 'Distribute argument in compile is not available in TF 2.0 please ' + 'create the model under the distribution strategy scope.') + logging.warning('Distribute argument in compile is deprecated please ' + 'create the model under the distribution strategy scope.') + self._distribution_strategy = distribute + self._compile_distribution = True + else: + if distribute_lib.has_strategy(): + # When the user builds the model in the DS scope and cross replica + # context we want distribution strategy to be set but when building the + # replica copies of the models internally we should not be compiling + # with distribution strategy and use the default compilation path. + if distribute_lib.in_cross_replica_context(): + self._distribution_strategy = ( + distribute_lib.get_strategy()) + + if isinstance(self._distribution_strategy, + parameter_server_strategy.ParameterServerStrategyV1): + raise NotImplementedError( + '`tf.compat.v1.distribute.experimental.ParameterServerStrategy` ' + 'currently only works with the tf.Estimator API') + + if isinstance(self._distribution_strategy, + parameter_server_strategy_v2.ParameterServerStrategyV2): + raise NotImplementedError( + '`tf.distribute.experimental.ParameterServerStrategy` is only ' + 'supported in TF2.') + + if not self._experimental_run_tf_function: + self._validate_compile_param_for_distribution_strategy(self.run_eagerly, + sample_weight_mode, + target_tensors, + weighted_metrics) + # We've disabled automatic dependency tracking for this method, but do want + # to add a checkpoint dependency on the optimizer if it's trackable. + if isinstance(self.optimizer, trackable.Trackable): + self._track_trackable( + self.optimizer, name='optimizer', overwrite=True) + self.loss = loss or {} + self.loss_weights = loss_weights + self.sample_weight_mode = sample_weight_mode + self._compile_metrics = metrics or [] + self._compile_weighted_metrics = weighted_metrics + if self.run_eagerly and target_tensors is not None: + raise ValueError( + 'target_tensors argument is not supported when ' + 'running a model eagerly.') + + # _training_endpoints contains a list of _TrainingEndpoint object, which has + # all the model output/target/loss and related metadata. + self._training_endpoints = [] + + # Used to freeze the behavior of the Model once `compile` has been called. + self._compiled_trainable_state = self._get_trainable_state() + + # Set tf.distribute.Strategy specific parameters. + self._distributed_model_cache = {} + self._distributed_function_cache = {} + + # Clear any `_eager_losses` that was added. + self._clear_losses() + + if (not context.executing_eagerly() and + self._distribution_strategy is not None): + # Ensures a Session is created and configured correctly for Distribution + # Strategy. + backend.configure_and_create_distributed_session( + self._distribution_strategy) + # Initialize model metric attributes. + self._init_metric_attributes() + if not self.built or not self.inputs or not self.outputs: + # Model is not compilable because it does not know its number of inputs + # and outputs, nor their shapes and names. We will compile after the first + # time the model gets called on training data. + return + self._is_compiled = True + + # Prepare list of loss functions, same size of model outputs. + self.loss_functions = training_utils_v1.prepare_loss_functions( + self.loss, self.output_names) + + target_tensors = self._process_target_tensor_for_compile(target_tensors) + + for o, n, l, t in zip(self.outputs, self.output_names, + self.loss_functions, target_tensors): + endpoint = _TrainingEndpoint(o, n, l) + endpoint.create_training_target(t, run_eagerly=self.run_eagerly) + self._training_endpoints.append(endpoint) + + # Prepare list loss weights, same size of model outputs. + training_utils_v1.prepare_loss_weights(self._training_endpoints, + loss_weights) + + # Initialization for Eager mode execution. + if self.run_eagerly: + self._compile_eagerly(metrics, weighted_metrics, sample_weight_mode) + return + + with backend.get_graph().as_default(): + # Save all metric attributes per output of the model. + self._cache_output_metric_attributes(metrics, weighted_metrics) + + # Set metric attributes on model. + self._set_metric_attributes() + + # Invoke metric functions (unweighted) for all the outputs. + self._handle_metrics( + self.outputs, + targets=self._targets, + skip_target_masks=self._prepare_skip_target_masks(), + masks=self._prepare_output_masks()) + + # Prepare sample weight modes. List with the same length as model outputs. + training_utils_v1.prepare_sample_weight_modes( + self._training_endpoints, sample_weight_mode) + + # Creates the model loss and weighted metrics sub-graphs. + self._compile_weights_loss_and_weighted_metrics() + + # Functions for train, test and predict will + # be compiled lazily when required. + # This saves time when the user is not using all functions. + self.train_function = None + self.test_function = None + self.predict_function = None + + # Collected trainable weights, sorted in topological order. + self._collected_trainable_weights = self.trainable_weights + + # Validate all variables were correctly created in distribution scope. + if self._distribution_strategy and not self._compile_distribution: + for v in self.variables: + strategy = self._distribution_strategy + if not strategy.extended.variable_created_in_scope(v): + raise ValueError( + 'Variable (%s) was not created in the distribution strategy ' + 'scope of (%s). It is most likely due to not all layers or ' + 'the model or optimizer being created outside the distribution ' + 'strategy scope. Try to make sure your code looks similar ' + 'to the following.\n' + 'with strategy.scope():\n' + ' model=_create_model()\n' + ' model.compile(...)'% (v, strategy)) + + @trackable.no_automatic_dependency_tracking + def _init_distributed_function_cache_if_not_compiled(self): + if not hasattr(self, '_distributed_function_cache'): + self._distributed_function_cache = {} + + @property + def metrics(self): + """Returns the model's metrics added using `compile`, `add_metric` APIs.""" + metrics = [] + if self._is_compiled: + if not hasattr(self, '_v1_compile_was_called'): + # See b/155687393 for more details, the model is created as a v2 + # instance but converted to v1. Fallback to use base Model to retrieve + # the metrics. + return super(Model, self).metrics + metrics += self._compile_metric_functions + metrics.extend(self._metrics) + metrics.extend( + _get_metrics_from_layers( + list(self._flatten_layers(include_self=False, recursive=False)))) + return metrics + + @property + def metrics_names(self): + """Returns the model's display labels for all outputs.""" + + # This property includes all output names including `loss` and per-output + # losses for backward compatibility. + metrics_names = ['loss'] + if self._is_compiled: + if not hasattr(self, '_v1_compile_was_called'): + # See b/155687393 for more details, the model is created as a v2 + # instance but converted to v1. Fallback to use base Model to retrieve + # the metrics name + return super(Model, self).metrics_names + + # Add output loss metric names to the metric names list. + if len(self._training_endpoints) > 1: + metrics_names.extend([ + e.loss_name() + for e in self._training_endpoints + if not e.should_skip_target() + ]) + + # Add all metric names. + metrics_names += [m.name for m in self.metrics] + return metrics_names + + @property + def run_eagerly(self): + """Settable attribute indicating whether the model should run eagerly. + + Running eagerly means that your model will be run step by step, + like Python code. Your model might run slower, but it should become easier + for you to debug it by stepping into individual layer calls. + + By default, we will attempt to compile your model to a static graph to + deliver the best execution performance. + + Returns: + Boolean, whether the model should run eagerly. + """ + if self._run_eagerly is True and not context.executing_eagerly(): + raise ValueError('You can only set `run_eagerly=True` if eager execution ' + 'is enabled.') + if not self.dynamic: + if self._run_eagerly is None: + # Respect `tf.config.run_functions_eagerly` unless + # `run_eagerly` was explicitly passed to `compile`. + return def_function.functions_run_eagerly() + else: + return self._run_eagerly + else: + if not context.executing_eagerly(): + raise ValueError('Your model contains layers that can only be ' + 'successfully run in eager execution (layers ' + 'constructed with `dynamic=True`). ' + 'You must enable eager execution with ' + '`tf.enable_eager_execution()`.') + if self._run_eagerly is False: + # TODO(fchollet): consider using py_func to enable this. + raise ValueError('Your model contains layers that can only be ' + 'successfully run in eager execution (layers ' + 'constructed with `dynamic=True`). ' + 'You cannot set `run_eagerly=False`.') + return context.executing_eagerly() + + @run_eagerly.setter + def run_eagerly(self, value): + self._run_eagerly = value + + def _select_training_loop(self, inputs): + """Select training loop for fit/eval/predict based on the inputs.""" + # TODO(kaftan) or TODO(scottzhu): This check should eventually be nicely + # integrated into the data adapters in the v2 loop. We can't do this yet + # because we currently have to fall back for unhandled data types. + if isinstance(inputs, (iterator_ops.Iterator, + iterator_ops.IteratorBase)): + raise ValueError('For performance reasons Keras `fit`, `evaluate` and' + '`predict` accept tf.data `Datasets` as input but not ' + 'iterators that have been manually generated from ' + 'Datasets by users. Please directly pass in the ' + 'original `Dataset` object instead of passing in ' + '`iter(dataset)`.') + + # Case 1: distribution strategy. + if self._distribution_strategy: + if self._in_multi_worker_mode(): + return training_distributed_v1.DistributionMultiWorkerTrainingLoop( + training_distributed_v1.DistributionSingleWorkerTrainingLoop()) + else: + return training_distributed_v1.DistributionSingleWorkerTrainingLoop() + + # Case 2: generator-like. Input is Python generator, or Sequence object, + # or a non-distributed Dataset or iterator in eager execution. + if data_utils.is_generator_or_sequence(inputs): + return training_generator_v1.GeneratorOrSequenceTrainingLoop() + if training_utils_v1.is_eager_dataset_or_iterator(inputs): + return training_generator_v1.EagerDatasetOrIteratorTrainingLoop() + + # Case 3: Symbolic tensors or Numpy array-like. + # This includes Datasets and iterators in graph mode (since they + # generate symbolic tensors). + if self.run_eagerly: + return training_generator_v1.GeneratorLikeTrainingLoop() + else: + return training_arrays_v1.ArrayLikeTrainingLoop() + + def fit(self, + x=None, + y=None, + batch_size=None, + epochs=1, + verbose=1, + callbacks=None, + validation_split=0., + validation_data=None, + shuffle=True, + class_weight=None, + sample_weight=None, + initial_epoch=0, + steps_per_epoch=None, + validation_steps=None, + validation_freq=1, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + **kwargs): + """Trains the model for a fixed number of epochs (iterations on a dataset). + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. Should return a tuple + of either `(inputs, targets)` or + `(inputs, targets, sample_weights)`. + - A generator or `keras.utils.Sequence` returning `(inputs, targets)` + or `(inputs, targets, sample weights)`. + y: Target data. Like the input data `x`, + it could be either Numpy array(s) or TensorFlow tensor(s). + It should be consistent with `x` (you cannot have Numpy inputs and + tensor targets, or inversely). If `x` is a dataset, generator, + or `keras.utils.Sequence` instance, `y` should + not be specified (since targets will be obtained from `x`). + batch_size: Integer or `None`. + Number of samples per gradient update. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of symbolic tensors, datasets, + generators, or `keras.utils.Sequence` instances (since they generate + batches). + epochs: Integer. Number of epochs to train the model. + An epoch is an iteration over the entire `x` and `y` + data provided. + Note that in conjunction with `initial_epoch`, + `epochs` is to be understood as "final epoch". + The model is not trained for a number of iterations + given by `epochs`, but merely until the epoch + of index `epochs` is reached. + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = progress bar, 2 = one line per epoch. + Note that the progress bar is not particularly useful when + logged to a file, so verbose=2 is recommended when not running + interactively (eg, in a production environment). + callbacks: List of `keras.callbacks.Callback` instances. + List of callbacks to apply during training. + See `tf.keras.callbacks`. + validation_split: Float between 0 and 1. + Fraction of the training data to be used as validation data. + The model will set apart this fraction of the training data, + will not train on it, and will evaluate + the loss and any model metrics + on this data at the end of each epoch. + The validation data is selected from the last samples + in the `x` and `y` data provided, before shuffling. This argument is + not supported when `x` is a dataset, generator or + `keras.utils.Sequence` instance. + validation_data: Data on which to evaluate + the loss and any model metrics at the end of each epoch. + The model will not be trained on this data. + `validation_data` will override `validation_split`. + `validation_data` could be: + - tuple `(x_val, y_val)` of Numpy arrays or tensors + - tuple `(x_val, y_val, val_sample_weights)` of Numpy arrays + - dataset + For the first two cases, `batch_size` must be provided. + For the last case, `validation_steps` could be provided. + shuffle: Boolean (whether to shuffle the training data + before each epoch) or str (for 'batch'). + 'batch' is a special option for dealing with the + limitations of HDF5 data; it shuffles in batch-sized chunks. + Has no effect when `steps_per_epoch` is not `None`. + class_weight: Optional dictionary mapping class indices (integers) + to a weight (float) value, used for weighting the loss function + (during training only). + This can be useful to tell the model to + "pay more attention" to samples from + an under-represented class. + sample_weight: Optional Numpy array of weights for + the training samples, used for weighting the loss function + (during training only). You can either pass a flat (1D) + Numpy array with the same length as the input samples + (1:1 mapping between weights and samples), + or in the case of temporal data, + you can pass a 2D array with shape + `(samples, sequence_length)`, + to apply a different weight to every timestep of every sample. + In this case you should make sure to specify + `sample_weight_mode="temporal"` in `compile()`. This argument is not + supported when `x` is a dataset, generator, or + `keras.utils.Sequence` instance, instead provide the sample_weights + as the third element of `x`. + initial_epoch: Integer. + Epoch at which to start training + (useful for resuming a previous training run). + steps_per_epoch: Integer or `None`. + Total number of steps (batches of samples) + before declaring one epoch finished and starting the + next epoch. When training with input tensors such as + TensorFlow data tensors, the default `None` is equal to + the number of samples in your dataset divided by + the batch size, or 1 if that cannot be determined. If x is a + `tf.data` dataset, and 'steps_per_epoch' + is None, the epoch will run until the input dataset is exhausted. + This argument is not supported with array inputs. + validation_steps: Only relevant if `validation_data` is provided and + is a `tf.data` dataset. Total number of steps (batches of + samples) to draw before stopping when performing validation + at the end of every epoch. If 'validation_steps' is None, validation + will run until the `validation_data` dataset is exhausted. In the + case of a infinite dataset, it will run into a infinite loop. + If 'validation_steps' is specified and only part of the dataset + will be consumed, the evaluation will start from the beginning of + the dataset at each epoch. This ensures that the same validation + samples are used every time. + validation_freq: Only relevant if validation data is provided. Integer + or `collections.abc.Container` instance (e.g. list, tuple, etc.). + If an integer, specifies how many training epochs to run before a + new validation run is performed, e.g. `validation_freq=2` runs + validation every 2 epochs. If a Container, specifies the epochs on + which to run validation, e.g. `validation_freq=[1, 2, 10]` runs + validation at the end of the 1st, 2nd, and 10th epochs. + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. + If unspecified, `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up + when using process-based threading. If unspecified, `workers` + will default to 1. If 0, will execute the generator on the main + thread. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to + the generator as they can't be passed easily to children processes. + **kwargs: Used for backwards compatibility. + + Returns: + A `History` object. Its `History.history` attribute is + a record of training loss values and metrics values + at successive epochs, as well as validation loss values + and validation metrics values (if applicable). + + Raises: + RuntimeError: If the model was never compiled. + ValueError: In case of mismatch between the provided input data + and what the model expects. + """ + self._assert_built_as_v1() + # Legacy support + if 'nb_epoch' in kwargs: + logging.warning( + 'The `nb_epoch` argument in `fit` has been renamed `epochs`.') + epochs = kwargs.pop('nb_epoch') + if kwargs: + raise TypeError('Unrecognized keyword arguments: ' + str(kwargs)) + self._assert_compile_was_called() + self._check_call_args('fit') + + func = self._select_training_loop(x) + return func.fit( + self, + x=x, + y=y, + batch_size=batch_size, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_split=validation_split, + validation_data=validation_data, + shuffle=shuffle, + class_weight=class_weight, + sample_weight=sample_weight, + initial_epoch=initial_epoch, + steps_per_epoch=steps_per_epoch, + validation_steps=validation_steps, + validation_freq=validation_freq, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing) + + def evaluate(self, + x=None, + y=None, + batch_size=None, + verbose=1, + sample_weight=None, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + """Returns the loss value & metrics values for the model in test mode. + + Computation is done in batches (see the `batch_size` arg.) + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. + - A generator or `keras.utils.Sequence` instance. + y: Target data. Like the input data `x`, + it could be either Numpy array(s) or TensorFlow tensor(s). + It should be consistent with `x` (you cannot have Numpy inputs and + tensor targets, or inversely). + If `x` is a dataset, generator or + `keras.utils.Sequence` instance, `y` should not be specified (since + targets will be obtained from the iterator/dataset). + batch_size: Integer or `None`. + Number of samples per batch of computation. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of symbolic tensors, dataset, + generators, or `keras.utils.Sequence` instances (since they generate + batches). + verbose: 0 or 1. Verbosity mode. + 0 = silent, 1 = progress bar. + sample_weight: Optional Numpy array of weights for + the test samples, used for weighting the loss function. + You can either pass a flat (1D) + Numpy array with the same length as the input samples + (1:1 mapping between weights and samples), + or in the case of temporal data, + you can pass a 2D array with shape + `(samples, sequence_length)`, + to apply a different weight to every timestep of every sample. + In this case you should make sure to specify + `sample_weight_mode="temporal"` in `compile()`. This argument is not + supported when `x` is a dataset, instead pass + sample weights as the third element of `x`. + steps: Integer or `None`. + Total number of steps (batches of samples) + before declaring the evaluation round finished. + Ignored with the default value of `None`. + If x is a `tf.data` dataset and `steps` is + None, 'evaluate' will run until the dataset is exhausted. + This argument is not supported with array inputs. + callbacks: List of `keras.callbacks.Callback` instances. + List of callbacks to apply during evaluation. + See [callbacks](/api_docs/python/tf/keras/callbacks). + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. + If unspecified, `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up when using + process-based threading. If unspecified, `workers` will default + to 1. If 0, will execute the generator on the main thread. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to + the generator as they can't be passed easily to children processes. + + Returns: + Scalar test loss (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + ValueError: in case of invalid arguments. + """ + self._assert_built_as_v1() + self._assert_compile_was_called() + self._check_call_args('evaluate') + + func = self._select_training_loop(x) + return func.evaluate( + self, + x=x, + y=y, + batch_size=batch_size, + verbose=verbose, + sample_weight=sample_weight, + steps=steps, + callbacks=callbacks, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing) + + def predict(self, + x, + batch_size=None, + verbose=0, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False): + """Generates output predictions for the input samples. + + Computation is done in batches (see the `batch_size` arg.) + + Args: + x: Input samples. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A `tf.data` dataset. + - A generator or `keras.utils.Sequence` instance. + batch_size: Integer or `None`. + Number of samples per batch of computation. + If unspecified, `batch_size` will default to 32. + Do not specify the `batch_size` if your data is in the + form of symbolic tensors, dataset, + generators, or `keras.utils.Sequence` instances (since they generate + batches). + verbose: Verbosity mode, 0 or 1. + steps: Total number of steps (batches of samples) + before declaring the prediction round finished. + Ignored with the default value of `None`. If x is a `tf.data` + dataset and `steps` is None, `predict` will + run until the input dataset is exhausted. + callbacks: List of `keras.callbacks.Callback` instances. + List of callbacks to apply during prediction. + See [callbacks](/api_docs/python/tf/keras/callbacks). + max_queue_size: Integer. Used for generator or `keras.utils.Sequence` + input only. Maximum size for the generator queue. + If unspecified, `max_queue_size` will default to 10. + workers: Integer. Used for generator or `keras.utils.Sequence` input + only. Maximum number of processes to spin up when using + process-based threading. If unspecified, `workers` will default + to 1. If 0, will execute the generator on the main thread. + use_multiprocessing: Boolean. Used for generator or + `keras.utils.Sequence` input only. If `True`, use process-based + threading. If unspecified, `use_multiprocessing` will default to + `False`. Note that because this implementation relies on + multiprocessing, you should not pass non-picklable arguments to + the generator as they can't be passed easily to children processes. + + + Returns: + Numpy array(s) of predictions. + + Raises: + ValueError: In case of mismatch between the provided + input data and the model's expectations, + or in case a stateful model receives a number of samples + that is not a multiple of the batch size. + """ + self._assert_built_as_v1() + self._check_call_args('predict') + + func = self._select_training_loop(x) + return func.predict( + self, + x=x, + batch_size=batch_size, + verbose=verbose, + steps=steps, + callbacks=callbacks, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing) + + def reset_metrics(self): + """Resets the state of metrics.""" + metrics = self._get_training_eval_metrics() + for m in metrics: + m.reset_state() + + # Reset metrics on all the distributed (cloned) models. + if self._distribution_strategy: + distributed_training_utils_v1._reset_metrics(self) # pylint: disable=protected-access + + def train_on_batch(self, + x, + y=None, + sample_weight=None, + class_weight=None, + reset_metrics=True): + """Runs a single gradient update on a single batch of data. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. + y: Target data. Like the input data `x`, it could be either Numpy + array(s) or TensorFlow tensor(s). It should be consistent with `x` + (you cannot have Numpy inputs and tensor targets, or inversely). If + `x` is a dataset, `y` should not be specified + (since targets will be obtained from the iterator). + sample_weight: Optional array of the same length as x, containing + weights to apply to the model's loss for each sample. In the case of + temporal data, you can pass a 2D array with shape (samples, + sequence_length), to apply a different weight to every timestep of + every sample. In this case you should make sure to specify + sample_weight_mode="temporal" in compile(). This argument is not + supported when `x` is a dataset. + class_weight: Optional dictionary mapping class indices (integers) to a + weight (float) to apply to the model's loss for the samples from this + class during training. This can be useful to tell the model to "pay + more attention" to samples from an under-represented class. + reset_metrics: If `True`, the metrics returned will be only for this + batch. If `False`, the metrics will be statefully accumulated across + batches. + + Returns: + Scalar training loss + (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + ValueError: In case of invalid user-provided arguments. + """ + self._assert_compile_was_called() + self._check_call_args('train_on_batch') + + # If at this point we are in the replica context, then it is okay to execute + # the Eager code path. The expected way to get here is to call `fit` that + # calls `train_on_batch` on each replica. + if (self._distribution_strategy and + distribute_lib.in_cross_replica_context()): + raise NotImplementedError('`train_on_batch` is not supported for models ' + 'distributed with tf.distribute.Strategy.') + # Validate and standardize user data. + x, y, sample_weights = self._standardize_user_data( + x, y, sample_weight=sample_weight, class_weight=class_weight, + extract_tensors_from_dataset=True) + + # If `self._distribution_strategy` is True, then we are in a replica context + # at this point because of the check above. `train_on_batch` is being run + # for each replica by `self._distribution_strategy` and the same code path + # as Eager is expected to be taken. + if self.run_eagerly or self._distribution_strategy: + output_dict = training_eager_v1.train_on_batch( + self, + x, + y, + sample_weights=sample_weights, + output_loss_metrics=self._output_loss_metrics) + outputs = (output_dict['total_loss'] + output_dict['output_losses'] + + output_dict['metrics']) + outputs = [_non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access + else: + x = training_utils_v1.ModelInputs(x).as_list() + ins = x + list(y or []) + list(sample_weights or []) + + if not isinstance(backend.symbolic_learning_phase(), int): + ins += [True] # Add learning phase value. + + self._update_sample_weight_modes(sample_weights=sample_weights) + self._make_train_function() + outputs = self.train_function(ins) # pylint: disable=not-callable + + if reset_metrics: + self.reset_metrics() + + if len(outputs) == 1: + return outputs[0] + return outputs + + def test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True): + """Test the model on a single batch of samples. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. + y: Target data. Like the input data `x`, + it could be either Numpy array(s) or TensorFlow tensor(s). + It should be consistent with `x` (you cannot have Numpy inputs and + tensor targets, or inversely). If `x` is a dataset `y` should + not be specified (since targets will be obtained from the iterator). + sample_weight: Optional array of the same length as x, containing + weights to apply to the model's loss for each sample. + In the case of temporal data, you can pass a 2D array + with shape (samples, sequence_length), + to apply a different weight to every timestep of every sample. + In this case you should make sure to specify + sample_weight_mode="temporal" in compile(). This argument is not + supported when `x` is a dataset. + reset_metrics: If `True`, the metrics returned will be only for this + batch. If `False`, the metrics will be statefully accumulated across + batches. + + Returns: + Scalar test loss (if the model has a single output and no metrics) + or list of scalars (if the model has multiple outputs + and/or metrics). The attribute `model.metrics_names` will give you + the display labels for the scalar outputs. + + Raises: + ValueError: In case of invalid user-provided arguments. + """ + self._assert_compile_was_called() + self._check_call_args('test_on_batch') + + if (self._distribution_strategy and + distribute_lib.in_cross_replica_context()): + raise NotImplementedError('`test_on_batch` is not supported for models ' + 'distributed with tf.distribute.Strategy.') + # Validate and standardize user data. + x, y, sample_weights = self._standardize_user_data( + x, y, sample_weight=sample_weight, extract_tensors_from_dataset=True) + + # If `self._distribution_strategy` is True, then we are in a replica context + # at this point. + if self.run_eagerly or self._distribution_strategy: + output_dict = training_eager_v1.test_on_batch( + self, + x, + y, + sample_weights=sample_weights, + output_loss_metrics=self._output_loss_metrics) + outputs = (output_dict['total_loss'] + output_dict['output_losses'] + + output_dict['metrics']) + outputs = [_non_none_constant_value(v) for v in outputs] # pylint: disable=protected-access + else: + x = training_utils_v1.ModelInputs(x).as_list() + inputs = x + list(y or []) + list(sample_weights or []) + + self._update_sample_weight_modes(sample_weights=sample_weights) + self._make_test_function() + outputs = self.test_function(inputs) # pylint: disable=not-callable + + if reset_metrics: + self.reset_metrics() + + if len(outputs) == 1: + return outputs[0] + return outputs + + def predict_on_batch(self, x): + """Returns predictions for a single batch of samples. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A `tf.data` dataset. + + Returns: + Numpy array(s) of predictions. + + Raises: + ValueError: In case of mismatch between given number of inputs and + expectations of the model. + """ + self._check_call_args('predict_on_batch') + + if (self._distribution_strategy and + distribute_lib.in_cross_replica_context()): + raise NotImplementedError( + '`predict_on_batch` is not supported for models distributed with' + ' tf.distribute.Strategy.') + # Validate and standardize user data. + inputs, _, _ = self._standardize_user_data( + x, extract_tensors_from_dataset=True) + # If `self._distribution_strategy` is True, then we are in a replica context + # at this point. + if self.run_eagerly or self._distribution_strategy: + inputs = training_utils_v1.cast_if_floating_dtype(inputs) + if isinstance(inputs, collections.abc.Sequence): + # Unwrap lists with only one input, as we do when training on batch + if len(inputs) == 1: + inputs = inputs[0] + + return self(inputs) # pylint: disable=not-callable + + self._make_predict_function() + outputs = self.predict_function(inputs) + + if len(outputs) == 1: + return outputs[0] + return outputs + + def fit_generator(self, + generator, + steps_per_epoch=None, + epochs=1, + verbose=1, + callbacks=None, + validation_data=None, + validation_steps=None, + validation_freq=1, + class_weight=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + shuffle=True, + initial_epoch=0): + """Fits the model on data yielded batch-by-batch by a Python generator. + + DEPRECATED: + `Model.fit` now supports generators, so there is no longer any need to use + this endpoint. + """ + warnings.warn('`model.fit_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.fit`, which supports generators.') + return self.fit( + generator, + steps_per_epoch=steps_per_epoch, + epochs=epochs, + verbose=verbose, + callbacks=callbacks, + validation_data=validation_data, + validation_steps=validation_steps, + validation_freq=validation_freq, + class_weight=class_weight, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + shuffle=shuffle, + initial_epoch=initial_epoch) + + def evaluate_generator(self, + generator, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + verbose=0): + """Evaluates the model on a data generator. + + DEPRECATED: + `Model.evaluate` now supports generators, so there is no longer any need + to use this endpoint. + """ + warnings.warn('`Model.evaluate_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.evaluate`, which supports generators.') + self._check_call_args('evaluate_generator') + + return self.evaluate( + generator, + steps=steps, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + verbose=verbose, + callbacks=callbacks) + + def predict_generator(self, + generator, + steps=None, + callbacks=None, + max_queue_size=10, + workers=1, + use_multiprocessing=False, + verbose=0): + """Generates predictions for the input samples from a data generator. + + DEPRECATED: + `Model.predict` now supports generators, so there is no longer any need + to use this endpoint. + """ + warnings.warn('`Model.predict_generator` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `Model.predict`, which supports generators.') + return self.predict( + generator, + steps=steps, + max_queue_size=max_queue_size, + workers=workers, + use_multiprocessing=use_multiprocessing, + verbose=verbose, + callbacks=callbacks) + + def _check_call_args(self, method_name): + """Check that `call` has only one positional arg.""" + # Always allow first arg, regardless of arg name. + fullargspec = self._call_full_argspec + if fullargspec.defaults: + positional_args = fullargspec.args[:-len(fullargspec.defaults)] + else: + positional_args = fullargspec.args + if 'training' in positional_args: + positional_args.remove('training') + + # self and first arg can be positional. + if len(positional_args) > 2: + extra_args = positional_args[2:] + raise ValueError( + 'Models passed to `' + method_name + '` can only have `training` ' + 'and the first argument in `call` as positional arguments, ' + 'found: ' + str(extra_args) + '.') + + def _set_optimizer(self, optimizer): + """Sets self.optimizer. + + Sets self.optimizer to `optimizer`, potentially wrapping it with a + LossScaleOptimizer. + + Args: + optimizer: The optimizer(s) to assign to self.optimizer. + """ + if isinstance(optimizer, (list, tuple)): + self.optimizer = [optimizers.get(opt) for opt in optimizer] + else: + self.optimizer = optimizers.get(optimizer) + + if isinstance(self._dtype_policy, policy.PolicyV1): + loss_scale = self._dtype_policy.loss_scale + elif self._dtype_policy.name == 'mixed_float16': + loss_scale = 'dynamic' + else: + loss_scale = None + + if (loss_scale is not None and + not isinstance(self.optimizer, + loss_scale_optimizer.LossScaleOptimizer)): + if isinstance(self.optimizer, list): + raise ValueError('When a dtype policy with a loss scale is used, you ' + 'can only pass a single optimizer. Using policy %s ' + 'and got optimizers: %s' % + self._dtype_policy, self.optimizer) + if not isinstance(self.optimizer, optimizer_v2.OptimizerV2): + raise ValueError('"optimizer" must be an instance of ' + 'tf.keras.optimizers.Optimizer when a dype policy ' + 'with a loss scale used, but got: %s. Using policy: ' + '%s' % + (self.optimizer, self._dtype_policy)) + if loss_scale == 'dynamic': + self.optimizer = loss_scale_optimizer.LossScaleOptimizer(self.optimizer) + else: + self.optimizer = loss_scale_optimizer.LossScaleOptimizerV1( + self.optimizer, loss_scale) + + def _prepare_validation_data(self, validation_data, batch_size, + validation_steps): + """Unpack and check the validation data.""" + val_x, val_y, val_sample_weights = training_utils_v1.unpack_validation_data( + validation_data) + return self._standardize_user_data( + val_x, + val_y, + sample_weight=val_sample_weights, + batch_size=batch_size, + steps=validation_steps, + steps_name='validation_steps') + + def _validate_compile_param_for_distribution_strategy( + self, run_eagerly, sample_weight_mode, target_tensors, weighted_metrics): + # Validate that arguments passed by the user to `compile` are supported by + # tf.distribute.Strategy. + if self._distribution_strategy: + if sample_weight_mode: + raise NotImplementedError('sample_weight_mode is not supported with ' + 'tf.distribute.Strategy.') + if weighted_metrics: + raise NotImplementedError('weighted_metrics is not supported with ' + 'tf.distribute.Strategy.') + if target_tensors: + raise ValueError('target_tensors is not supported with ' + 'tf.distribute.Strategy.') + + if run_eagerly: + raise ValueError( + 'We currently do not support enabling `run_eagerly` with ' + 'distribution strategy.') + + if (distributed_training_utils_v1.is_distributing_by_cloning(self) and + (not self.built or not self.inputs or not self.outputs)): + raise ValueError( + 'We currently do not support distribution strategy with a ' + '`Sequential` model that is created without `input_shape`/' + '`input_dim` set in its first layer or a subclassed model.') + + def _process_target_tensor_for_compile(self, target_tensors): + if self.run_eagerly: + # target tensor is not supported with run_eagerly. Create a list with None + # as placeholder for each output. + return [None for _ in self.output_names] + + if target_tensors is not None and not (isinstance(target_tensors, list) and + target_tensors == []): # pylint: disable=g-explicit-bool-comparison + if isinstance(target_tensors, list): + if len(target_tensors) != len(self.outputs): + raise ValueError( + 'When passing a list as `target_tensors`, ' + 'it should have one entry per model output. ' + 'The model has %s outputs, but you passed target_tensors=%s' % + (len(self.outputs), target_tensors)) + elif isinstance(target_tensors, dict): + unexpected_target_tensor_names = set(target_tensors.keys()).difference( + self.output_names) + if unexpected_target_tensor_names: + raise ValueError( + 'Unknown entry in `target_tensors` dictionary: "{name}". ' + 'Only expected the following keys: {keys}'.format( + name=unexpected_target_tensor_names, + keys=str(self.output_names))) + tmp_target_tensors = [] + for name in self.output_names: + tmp_target_tensors.append(target_tensors.get(name, None)) + target_tensors = tmp_target_tensors + elif tensor_util.is_tf_type(target_tensors): + target_tensors = [target_tensors] + else: + raise TypeError('Expected `target_tensors` to be a list or tuple or ' + 'dict or a single tensor, but got:', target_tensors) + else: + # In case target tensor is empty or None, create a list with Nones + # that has same length as self.output_names. With that, the None check of + # target tensor can be skipped downstream. + target_tensors = [None for _ in self.output_names] + return target_tensors + + def _compile_eagerly(self, metrics, weighted_metrics, sample_weight_mode): + # Prepare sample weight modes. List with the same length as model outputs. + training_utils_v1.prepare_sample_weight_modes( + self._training_endpoints, sample_weight_mode) + # Prepare sample weights. + self._prepare_sample_weights() + # Save all metric attributes per output of the model. + self._cache_output_metric_attributes(metrics, weighted_metrics) + self.total_loss = None + # Set metric attributes on model. + self._set_metric_attributes() + + self._collected_trainable_weights = self.trainable_weights + + def _update_sample_weight_modes(self, sample_weights=None): + """Updates sample weight modes based on training/eval inputs. + + Sample weight placeholders will be created for all or no outputs + based on whether sample_weight is provided for any output. + + If model contains `_sample_weight_modes` we check if the input + `sample_weights` corresponds to the sample weight modes. + 1. Set sample weight mode to be 'temporal' for output i, if `compile` + sample_weight_mode was set to `temporal` and sample weight inputs + are given for one or more outputs. + 2. Set sample weight mode to be 'samplewise' for output i, if `compile` + sample_weight_mode was not set and sample weight inputs are given for + one or more outputs. + 3. Reset sample weight mode to None for output i if sample weight mode + was set but there is no sample weight input. + + Args: + sample_weights: List of sample weights of the same length as model outputs + or None. + """ + if not self._is_compiled: + return + if sample_weights and any(s is not None for s in sample_weights): + for endpoint in self._training_endpoints: + endpoint.sample_weight_mode = ( + endpoint.sample_weight_mode or 'samplewise') + else: + for endpoint in self._training_endpoints: + endpoint.sample_weight_mode = None + + def _recompile_weights_loss_and_weighted_metrics(self): + if not self._is_compiled: + return False + recompile = any( + e.sample_weights_mismatch() for e in self._training_endpoints) + + if recompile: + self._compile_weights_loss_and_weighted_metrics() + return recompile + + @trackable.no_automatic_dependency_tracking + def _compile_weights_loss_and_weighted_metrics(self, sample_weights=None): + """Compiles the model loss and weighted metric sub-graphs. + + This may be used to set graph tensors as sample weights (instead of creating + placeholders). This functionality is necessary for + `tf.keras.estimator.model_to_estimator`, which calls Keras models in a v1 + graph, and creates iterator tensors for inputs, targets, and sample weights. + + Args: + sample_weights: List of tensors to use as the sample weights. Must be the + same length as the number of outputs. If left as `None`, placeholders + are used instead. + """ + with backend.get_graph().as_default(): + if sample_weights is not None: + self._update_sample_weight_modes(sample_weights) + self._prepare_sample_weights(sample_weights) + + masks = self._prepare_output_masks() + + # Compute weighted metrics. + self._handle_metrics( + self.outputs, + targets=self._targets, + skip_target_masks=self._prepare_skip_target_masks(), + sample_weights=self.sample_weights, + masks=masks, + return_weighted_metrics=True) + + # Compute total loss. + # Used to keep track of the total loss value (stateless). + # eg., total_loss = loss_weight_1 * output_1_loss_fn(...) + + # loss_weight_2 * output_2_loss_fn(...) + + # layer losses. + self.total_loss = self._prepare_total_loss(masks) + + def _prepare_skip_target_masks(self): + """Boolean mask for whether the target in the output list should be skipped. + + If the loss function corresponding to a model output is None, then this + output will be skipped during total loss calculation and feed targets + preparation. + + Returns: + A boolean list for whether the corresponding target in the output list + should be skipped during loss calculation. + """ + return [l is None for l in self.loss_functions] + + def _prepare_output_masks(self): + """Returns masks corresponding to model outputs.""" + return [getattr(x, '_keras_mask', None) for x in self.outputs] + + def _prepare_total_loss(self, masks): + """Computes total loss from loss functions. + + Args: + masks: List of mask values corresponding to each model output. + + Returns: + A list of loss weights of python floats. + + Raises: + TypeError: If model run_eagerly is True. + """ + if self.run_eagerly: + raise TypeError('total loss can not be computed when compiled with ' + 'run_eagerly = True.') + loss_list = [] + with backend.name_scope('loss'): + for endpoint, mask in zip(self._training_endpoints, masks): + if endpoint.should_skip_target(): + continue + y_true = endpoint.training_target.target + y_pred = endpoint.output + loss_fn = endpoint.loss_fn + loss_weight = endpoint.loss_weight + loss_name = endpoint.loss_name() + sample_weight = endpoint.sample_weight + + with backend.name_scope(loss_name): + if mask is not None: + mask = math_ops.cast(mask, y_pred.dtype) + # Update weights with mask. + if sample_weight is None: + sample_weight = mask + else: + # Update dimensions of weights to match with mask if possible. + mask, _, sample_weight = ( + losses_utils.squeeze_or_expand_dimensions( + mask, sample_weight=sample_weight)) + sample_weight *= mask + + if hasattr(loss_fn, 'reduction'): + per_sample_losses = loss_fn.call(y_true, y_pred) + weighted_losses = losses_utils.compute_weighted_loss( + per_sample_losses, + sample_weight=sample_weight, + reduction=losses_utils.ReductionV2.NONE) + loss_reduction = loss_fn.reduction + + # `AUTO` loss reduction defaults to `SUM_OVER_BATCH_SIZE` for all + # compile use cases. + if loss_reduction == losses_utils.ReductionV2.AUTO: + loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE + + # Compute the stateless loss value. + output_loss = losses_utils.reduce_weighted_loss( + weighted_losses, reduction=loss_reduction) + else: + # Compute the stateless loss value for a custom loss class. + # Here we assume that the class takes care of loss reduction + # because if this class returns a vector value we cannot + # differentiate between use case where a custom optimizer + # expects a vector loss value vs unreduced per-sample loss value. + output_loss = loss_fn(y_true, y_pred, sample_weight=sample_weight) + loss_reduction = losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE + + if len(self.outputs) > 1: + # Keep track of stateful result tensor for the loss. + endpoint.output_loss_metric(output_loss) + + # Scale output loss for distribution. For custom losses we assume + # reduction was mean. + if loss_reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE: + output_loss = losses_utils.scale_loss_for_distribution(output_loss) + + loss_list.append(loss_weight * output_loss) + if not loss_list and not self.losses: + raise ValueError('The model cannot be compiled ' + 'because it has no loss to optimize.') + + # Add regularization penalties and other layer-specific losses. + custom_losses = self.get_losses_for(None) + self.get_losses_for( + self.inputs) + if custom_losses: + total_custom_loss = math_ops.add_n( + losses_utils.cast_losses_to_common_dtype(custom_losses)) + loss_list.append( + losses_utils.scale_loss_for_distribution(total_custom_loss)) + + loss_list = losses_utils.cast_losses_to_common_dtype(loss_list) + if loss_list: + total_loss = math_ops.add_n(loss_list) + else: + total_loss = 0. + return total_loss + + def _get_callback_model(self): + """Returns the Callback Model for this Model.""" + + if hasattr(self, '_replicated_model') and self._replicated_model: + # When using training_distributed, we set the callback model + # to an instance of the `DistributedModel` that we create in + # the `compile` call. The `DistributedModel` is initialized + # with the first replicated model. We need to set the callback + # model to a DistributedModel to allow us to override saving + # and loading weights when we checkpoint the model during training. + return self._replicated_model + if hasattr(self, 'callback_model') and self.callback_model: + return self.callback_model + return self + + @trackable.no_automatic_dependency_tracking + def _make_callback_model(self, grouped_model): + first_replicated_model = self._distribution_strategy.unwrap( + grouped_model)[0] + # We initialize the callback model with the first replicated model. + self._replicated_model = DistributedCallbackModel(first_replicated_model) + self._replicated_model.set_original_model(self) + + def _validate_or_infer_batch_size(self, batch_size, steps, x): + """Validates that the `batch_size` provided is consistent with InputLayer. + + It's possible that the user specified a static batch size in their + InputLayer. If so, this method checks the provided `batch_size` and `x` + arguments are consistent with this static batch size. Also, if + `batch_size` is `None`, this method will attempt to infer the batch size + from the static batch size of the InputLayer. Lastly, ValueError will be + raised if `x` is a tf.data.Dataset and `batch_size` is specified as we + expect users to provide batched datasets. + + Args: + batch_size: The batch_size provided as an argument to + fit/evaluate/predict. + steps: The steps provided as an argument to fit/evaluate/predict. + x: The data passed as `x` to fit/evaluate/predict. + + Returns: + The validated batch_size, auto-inferred from the first layer if not + provided. + """ + if (isinstance(x, (data_types.DatasetV1, + data_types.DatasetV2, + data_utils.Sequence)) or + tf_inspect.isgenerator(x)): + if batch_size is not None: + raise ValueError( + 'The `batch_size` argument must not be specified for the given ' + 'input type. Received input: {}, batch_size: {}'.format( + x, batch_size)) + return + + # Avoids the override in Sequential.layers which filters Input layers. + # (Which are often the very layers that we're after.) + layers = self._flatten_layers(include_self=False, recursive=False) + first_layer = next(layers, None) + if first_layer: + # The per-replica static batch size. + static_batch_size = training_utils.get_static_batch_size(first_layer) + if static_batch_size is not None: + + # Determine number of times the user-supplied batch size will be split. + if (self._distribution_strategy and + distributed_training_utils.global_batch_size_supported( + self._distribution_strategy)): + num_splits_for_ds = self._distribution_strategy.num_replicas_in_sync + else: + num_splits_for_ds = 1 + + # Check `batch_size` argument is consistent with InputLayer. + if batch_size is not None: + if batch_size % num_splits_for_ds != 0: + raise ValueError('The `batch_size` argument ({}) must be divisible ' + 'the by number of replicas ({})'.format( + batch_size, num_splits_for_ds)) + per_replica_batch_size = batch_size // num_splits_for_ds + + if per_replica_batch_size != static_batch_size: + raise ValueError('The `batch_size` argument value {} is ' + 'incompatible with the specified batch size of ' + 'your Input Layer: {}'.format( + per_replica_batch_size, static_batch_size)) + + # Check Dataset/Iterator batch size is consistent with InputLayer. + if isinstance(x, (data_types.DatasetV2, iterator_ops.Iterator, + iterator_ops.IteratorBase)): + ds_batch_size = tensor_shape.Dimension( + nest.flatten(dataset_ops.get_legacy_output_shapes(x))[0][0]).value + if ds_batch_size is not None: + if ds_batch_size % num_splits_for_ds != 0: + raise ValueError( + 'The batch output shape of your `Dataset` {} ' + 'cannot be divisible by number of replicas {}'.format( + ds_batch_size, num_splits_for_ds)) + + ds_per_replica_batch_size = ds_batch_size // num_splits_for_ds + if ds_per_replica_batch_size != static_batch_size: + raise ValueError('The batch output shape of your `Dataset` is ' + '{}, which is incompatible with the specified ' + 'batch size of your Input Layer: {}'.format( + ds_per_replica_batch_size, + static_batch_size)) + + # Set inferred batch size from the InputLayer. + if steps is None: + batch_size = static_batch_size * num_splits_for_ds + + if batch_size is None and steps is None: + # Backwards compatibility + batch_size = 32 + return batch_size + + def _prepare_sample_weights(self, sample_weights=None): + """Sets sample weight attribute on the model.""" + # List with the same length as model outputs. + if sample_weights is not None: + if len(sample_weights) != len(self._training_endpoints): + raise ValueError('Provided sample weights must have same length as the ' + 'number of outputs. Expected: {}, got: {}.'.format( + len(self._training_endpoints), + len(sample_weights))) + else: + sample_weights = [None] * len(self._training_endpoints) + for endpoint, weight in zip(self._training_endpoints, sample_weights): + endpoint.populate_sample_weight(weight, endpoint.sample_weight_mode) + + def _cache_output_metric_attributes(self, metrics, weighted_metrics): + """Caches metric name and function attributes for every model output.""" + output_shapes = [] + for output in self.outputs: + if output is None or output.shape.rank is None: + output_shapes.append(None) + else: + output_shapes.append(output.shape.as_list()) + self._per_output_metrics = training_utils_v1.collect_per_output_metric_info( + metrics, self.output_names, output_shapes, self.loss_functions, + from_serialized=self._from_serialized) + self._per_output_weighted_metrics = ( + training_utils_v1.collect_per_output_metric_info( + weighted_metrics, + self.output_names, + output_shapes, + self.loss_functions, + from_serialized=self._from_serialized, + is_weighted=True)) + + def _add_unique_metric_name(self, metric_name, metric_fn, output_index): + """Makes the metric name unique. + + If there are multiple outputs for which the metrics are calculated, the + metric names have to be made unique by appending an integer. + + Args: + metric_name: Metric name that corresponds to the metric specified by the + user. For example: 'acc'. + metric_fn: The Metric object. + output_index: The index of the model output for which the metric name is + being added. + + Returns: + string, name of the model's unique metric name + """ + # For multi-output models, prepend the output names to the metric name. + if len(self.output_names) > 1: + # If we're loading from an already-serialized model, we've already + # prepended the output name, and we don't want to do it again. + # + # Alternatively, we may be receiving a stateless metric (e.g. the string + # "accuracy") rather than a `Metric` object, in which case we want to + # prepend the output name even if we are loading a serialized model. + if not getattr(metric_fn, '_from_serialized', False): + metric_name = '%s_%s' % (self.output_names[output_index], metric_name) + + j = 1 + base_metric_name = metric_name + while metric_name in self.metrics_names: + metric_name = '%s_%d' % (base_metric_name, j) + j += 1 + + return metric_name + + def _init_metric_attributes(self): + """Initialized model metric attributes.""" + # List of stateful metric functions. Used for resetting metric state during + # training/eval. + self._compile_metric_functions = [] + + def _set_per_output_metric_attributes(self, metrics_dict, output_index): + """Sets the metric attributes on the model for the given output. + + Args: + metrics_dict: A dict with metric names as keys and metric fns as values. + output_index: The index of the model output for which the metric + attributes are added. + + Returns: + Metrics dict updated with unique metric names as keys. + """ + updated_metrics_dict = collections.OrderedDict() + for metric_name, metric_fn in metrics_dict.items(): + metric_name = self._add_unique_metric_name( + metric_name, metric_fn, output_index) + + # Update the name on the metric class to be the unique generated name. + metric_fn._name = metric_name # pylint: disable=protected-access + updated_metrics_dict[metric_name] = metric_fn + # Keep track of metric name and function. + self._compile_metric_functions.append(metric_fn) + return updated_metrics_dict + + def _set_metric_attributes(self): + """Sets the metric attributes on the model for all the model outputs.""" + updated_per_output_metrics = [] + updated_per_output_weighted_metrics = [] + for i, endpoint in enumerate(self._training_endpoints): + if endpoint.should_skip_target(): + updated_per_output_metrics.append(self._per_output_metrics[i]) + updated_per_output_weighted_metrics.append( + self._per_output_weighted_metrics[i]) + continue + updated_per_output_metrics.append( + self._set_per_output_metric_attributes(self._per_output_metrics[i], + i)) + updated_per_output_weighted_metrics.append( + self._set_per_output_metric_attributes( + self._per_output_weighted_metrics[i], i)) + + # Create a metric wrapper for each output loss. This computes mean of an + # output loss across mini-batches (irrespective of how we reduce within a + # batch). + if len(self._training_endpoints) > 1: + for endpoint in self._training_endpoints: + if not endpoint.should_skip_target(): + endpoint.output_loss_metric = metrics_module.Mean( + name=endpoint.loss_name()) + + self._per_output_metrics = updated_per_output_metrics + self._per_output_weighted_metrics = updated_per_output_weighted_metrics + + def _handle_per_output_metrics(self, + metrics_dict, + y_true, + y_pred, + mask, + weights=None): + """Calls metric functions for a single output. + + Args: + metrics_dict: A dict with metric names as keys and metric fns as values. + y_true: Target output. + y_pred: Predicted output. + mask: Computed mask value for the current output. + weights: Weights to be applied on the current output. + + Returns: + A list of metric result tensors. + """ + metric_results = [] + for metric_name, metric_fn in metrics_dict.items(): + with backend.name_scope(metric_name): + metric_result = training_utils_v1.call_metric_function( + metric_fn, y_true, y_pred, weights=weights, mask=mask) + metric_results.append(metric_result) + return metric_results + + def _handle_metrics(self, + outputs, + targets=None, + skip_target_masks=None, + sample_weights=None, + masks=None, + return_weighted_metrics=False, + return_weighted_and_unweighted_metrics=False): + """Handles calling metric functions. + + Args: + outputs: List of outputs (predictions). + targets: List of targets. + skip_target_masks: Optional. List of boolean for whether the corresponding + target should be ignored or not. + sample_weights: Optional list of sample weight arrays. + masks: List of computed output mask values. + return_weighted_metrics: Flag that indicates whether weighted metrics + should be computed instead of unweighted metrics. This flag is ignored + when `return_weighted_and_unweighted_metrics` is enabled. + return_weighted_and_unweighted_metrics: Flag that is used to indicate + whether both weighted and unweighted metrics should be computed. When + this is not enabled, we use `return_weighted_metrics` param to indicate + whether weighted or unweighted metrics should be returned. + + Returns: + A list of metric result tensors. + """ + # TODO(scottzhu): Update this to use the new training_endpoints. Currently + # the eager and graph logic is bit different. + skip_target_masks = skip_target_masks or [False] * len(outputs) + metric_results = [] + with backend.name_scope('metrics'): + # Invoke all metrics added using `compile`. + for i in range(len(outputs)): + if skip_target_masks[i]: + continue + output = outputs[i] if outputs else None + target = targets[i] if targets else None + output_mask = masks[i] if masks else None + + if (return_weighted_and_unweighted_metrics or + not return_weighted_metrics): + metric_results.extend( + self._handle_per_output_metrics(self._per_output_metrics[i], + target, output, output_mask)) + if return_weighted_and_unweighted_metrics or return_weighted_metrics: + metric_results.extend( + self._handle_per_output_metrics( + self._per_output_weighted_metrics[i], + target, + output, + output_mask, + weights=sample_weights[i] if sample_weights else None)) + return metric_results + + def _check_trainable_weights_consistency(self): + """Check trainable weights count consistency. + + This will raise a warning if `trainable_weights` and + `_collected_trainable_weights` are inconsistent (i.e. have different + number of parameters). + Inconsistency will typically arise when one modifies `model.trainable` + without calling `model.compile` again. + """ + if not hasattr(self, '_collected_trainable_weights'): + return + + if len(self.trainable_weights) != len(self._collected_trainable_weights): + logging.log_first_n( + logging.WARN, 'Discrepancy between trainable weights and collected' + ' trainable weights, did you set `model.trainable`' + ' without calling `model.compile` after ?', 1) + + def _make_train_function(self): + has_recompiled = self._recompile_weights_loss_and_weighted_metrics() + self._check_trainable_weights_consistency() + if isinstance(self.optimizer, list): + raise ValueError('The `optimizer` in `compile` should be a single ' + 'optimizer.') + # If we have re-compiled the loss/weighted metric sub-graphs then create + # train function even if one exists already. This is because + # `_feed_sample_weights` list has been updated on re-compile. + if getattr(self, 'train_function', None) is None or has_recompiled: + # Restore the compiled trainable state. + current_trainable_state = self._get_trainable_state() + self._set_trainable_state(self._compiled_trainable_state) + + inputs = (self._feed_inputs + + self._feed_targets + + self._feed_sample_weights) + if not isinstance(backend.symbolic_learning_phase(), int): + inputs += [backend.symbolic_learning_phase()] + + with backend.get_graph().as_default(): + with backend.name_scope('training'): + # Training updates + updates = self.optimizer.get_updates( + params=self._collected_trainable_weights, loss=self.total_loss) + # Unconditional updates + updates += self.get_updates_for(None) + # Conditional updates relevant to this model + updates += self.get_updates_for(self.inputs) + + metrics = self._get_training_eval_metrics() + metrics_tensors = [ + m._call_result for m in metrics if hasattr(m, '_call_result') # pylint: disable=protected-access + ] + + with backend.name_scope('training'): + # Gets loss and metrics. Updates weights at each call. + fn = backend.function( + inputs, [self.total_loss] + metrics_tensors, + updates=updates, + name='train_function', + **self._function_kwargs) + setattr(self, 'train_function', fn) + + # Restore the current trainable state + self._set_trainable_state(current_trainable_state) + + def _make_test_function(self): + has_recompiled = self._recompile_weights_loss_and_weighted_metrics() + # If we have re-compiled the loss/weighted metric sub-graphs then create + # test function even if one exists already. This is because + # `_feed_sample_weights` list has been updated on re-compile. + if getattr(self, 'test_function', None) is None or has_recompiled: + inputs = (self._feed_inputs + + self._feed_targets + + self._feed_sample_weights) + + with backend.get_graph().as_default(): + metrics = self._get_training_eval_metrics() + metrics_tensors = [ + m._call_result for m in metrics if hasattr(m, '_call_result') # pylint: disable=protected-access + ] + + with backend.name_scope('evaluation'): + updates = self.state_updates + # Return loss and metrics, no gradient updates. + # Does update the network states. + fn = backend.function( + inputs, [self.total_loss] + metrics_tensors, + updates=updates, + name='test_function', + **self._function_kwargs) + setattr(self, 'test_function', fn) + + def _make_predict_function(self): + if not hasattr(self, 'predict_function'): + self.predict_function = None + if self.predict_function is None: + inputs = self._feed_inputs + # Gets network outputs. Does not update weights. + # Does update the network states. + kwargs = getattr(self, '_function_kwargs', {}) + with backend.name_scope(ModeKeys.PREDICT): + self.predict_function = backend.function( + inputs, + self.outputs, + updates=self.state_updates, + name='predict_function', + **kwargs) + + def _make_execution_function(self, mode): + if mode == ModeKeys.TRAIN: + self._make_train_function() + return self.train_function + if mode == ModeKeys.TEST: + self._make_test_function() + return self.test_function + if mode == ModeKeys.PREDICT: + self._make_predict_function() + return self.predict_function + + def _distribution_standardize_user_data(self, + x, + y=None, + sample_weight=None, + class_weight=None, + batch_size=None, + validation_split=0, + shuffle=False, + epochs=1, + allow_partial_batch=False): + """Runs validation checks on input and target data passed by the user. + + This is called when using tf.distribute.Strategy to train, evaluate or serve + the model. + + Args: + x: Input data. A numpy array or `tf.data` dataset. + y: Target data. A numpy array or None if x is a `tf.data` dataset. + sample_weight: An optional sample-weight array passed by the user to + weight the importance of each sample in `x`. + class_weight: An optional class-weight array by the user to + weight the importance of samples in `x` based on the class they belong + to, as conveyed by `y`. + batch_size: Integer batch size. If provided, it is used to run additional + validation checks on stateful models. + validation_split: Float between 0 and 1. + Fraction of the training data to be used as validation data. + shuffle: Boolean whether to shuffle the training data before each epoch. + epochs: Integer epochs. If > 1, repeat the numpy training data epochs + times when converting to training dataset. + allow_partial_batch: Boolean whether to enforce that all batches have the + same size. + + Returns: + Dataset instance. + + Raises: + ValueError: In case of invalid user-provided data. + RuntimeError: If the model was never compiled. + """ + if class_weight: + raise NotImplementedError('`class_weight` is currently not supported ' + 'when using tf.distribute.Strategy.') + + if (sample_weight is not None and sample_weight.all() and + backend.is_tpu_strategy(self._distribution_strategy)): + raise NotImplementedError('`sample_weight` is currently not supported ' + 'when using TPUStrategy.') + + # Validates `steps` and `shuffle` arguments right at the beginning + # since we use it to construct the dataset object. + # TODO(anjalisridhar): Remove this check once we refactor the + # _standardize_user_data code path. This check is already present elsewhere + # in the codebase. + if isinstance(x, data_types.DatasetV2): + if shuffle: + training_utils_v1.verify_dataset_shuffled(x) + + strategy = self._distribution_strategy + with strategy.scope(): + # We should be sure to call get_session() inside the strategy.scope() + # so the strategy can affect the session options. + if ops.executing_eagerly_outside_functions(): + session = None + else: + session = backend.get_session() + + first_x_value = nest.flatten(x)[0] + if isinstance(first_x_value, np.ndarray): + x = training_utils.list_to_tuple(x) + if y is not None: + y = training_utils.list_to_tuple(y) + if sample_weight is not None: + sample_weight = training_utils.list_to_tuple(sample_weight) + in_tuple = (x, y, sample_weight) + else: + in_tuple = (x, y) + else: + in_tuple = x + + ds = strategy.extended.experimental_make_numpy_dataset(in_tuple, + session=session) + if shuffle: + # We want a buffer size that is larger than the batch size provided by + # the user and provides sufficient randomness. Note that larger + # numbers introduce more memory usage based on the size of each + # sample. + ds = ds.shuffle(max(1024, batch_size * 8)) + if epochs > 1: + ds = ds.repeat(epochs) + + # We need to use the drop_remainder argument to get a known static + # input shape which is required for TPUs. + drop_remainder = (not allow_partial_batch and + strategy.extended.experimental_require_static_shapes) + + # TODO(b/131720208): We still drop remainder here if number of examples + # is divisible by batch size, as sometimes dynamic padder will time out + # with keras.metrics.CategoricalAccuracy() metric. + if backend.is_tpu_strategy(strategy) and not drop_remainder: + dataset_size = first_x_value.shape[0] + if dataset_size % batch_size == 0: + drop_remainder = True + + x = ds.batch(batch_size, drop_remainder=drop_remainder) + else: + assert isinstance(x, data_types.DatasetV2) + training_utils_v1.validate_dataset_input(x, y, sample_weight, + validation_split) + return x + + def _standardize_user_data(self, + x, + y=None, + sample_weight=None, + class_weight=None, + batch_size=None, + check_steps=False, + steps_name='steps', + steps=None, + validation_split=0, + shuffle=False, + extract_tensors_from_dataset=False): + """Runs validation checks on input and target data passed by the user. + + Also standardizes the data to lists of arrays, in order. + + Also builds and compiles the model on the fly if it is a subclassed model + that has never been called before (and thus has no inputs/outputs). + + This is a purely internal method, subject to refactoring at any time. + + Args: + x: Input data. It could be: + - A Numpy array (or array-like), or a list of arrays + (in case the model has multiple inputs). + - A TensorFlow tensor, or a list of tensors + (in case the model has multiple inputs). + - A dict mapping input names to the corresponding array/tensors, + if the model has named inputs. + - A `tf.data` dataset. + y: Target data. Like the input data `x`, + it could be either Numpy array(s) or TensorFlow tensor(s). + It should be consistent with `x` (you cannot have Numpy inputs and + tensor targets, or inversely). If `x` is a dataset, `y` should not be + specified (since targets will be obtained from the iterator). + sample_weight: An optional sample-weight array passed by the user to + weight the importance of each sample in `x`. + class_weight: An optional class-weight array by the user to + weight the importance of samples in `x` based on the class they belong + to, as conveyed by `y`. If both `sample_weight` and `class_weight` are + provided, the weights are multiplied. + batch_size: Integer batch size. If provided, it is used to run additional + validation checks on stateful models. + check_steps: boolean, True if we want to check for validity of `steps` and + False, otherwise. For example, when we are standardizing one batch of + data for train_on_batch/predict_on_batch/test_on_batch APIs, `steps` + value is not required and we should not check for its validity in these + cases. + steps_name: The public API's parameter name for `steps`. + steps: Integer or `None`. Total number of steps (batches of samples) to + execute. + validation_split: Float between 0 and 1. + Fraction of the training data to be used as validation data. + shuffle: Boolean whether to shuffle the training data before each epoch. + extract_tensors_from_dataset: Boolean. When `x` is a dataset instance, + this indicates whether to extract actual tensors from the dataset or + instead output the dataset instance itself. + Set to True when calling from `train_on_batch`/etc. + + Returns: + A tuple of 3: inputs (arrays or dicts, depending on whether `x` was a dict + or not), target arrays, sample-weight arrays. + If the model's input and targets are symbolic, these lists are empty + (since the model takes no user-provided data, instead the data comes + from the symbolic inputs/targets). + + Raises: + ValueError: In case of invalid user-provided data. + RuntimeError: If the model was never compiled. + """ + if isinstance(x, (data_types.DatasetV1, data_types.DatasetV2)): + # Graph mode dataset. We'll pass the dataset as-is (unless + # `extract_tensors_from_dataset` is True, in which case we extract + # the tensors from the dataset and we output them. + training_utils_v1.validate_dataset_input(x, y, sample_weight, + validation_split) + if shuffle: + training_utils_v1.verify_dataset_shuffled(x) + + is_dataset = True + if extract_tensors_from_dataset: + # We do this for `train_on_batch`/etc. + x, y, sample_weight = training_utils_v1.extract_tensors_from_dataset(x) + elif isinstance(x, iterator_ops.Iterator): + # Graph mode iterator. We extract the symbolic tensors. + training_utils_v1.validate_dataset_input(x, y, sample_weight, + validation_split) + iterator = x + x, y, sample_weight = training_utils_v1.unpack_iterator_input(iterator) + is_dataset = True + else: + is_dataset = False + + # Validates `steps` argument based on x's type. + if check_steps: + training_utils_v1.check_steps_argument(x, steps, steps_name) + + # First, we build the model on the fly if necessary. + if not self.inputs: + all_inputs, y_input, dict_inputs = self._build_model_with_inputs(x, y) + is_build_called = True + else: + all_inputs = [] + # Whether this is a subclassed model that expects dictionary inputs + # rather than list inputs (e.g. FeatureColumn-based models). + dict_inputs = isinstance(self.inputs, dict) + is_build_called = False + y_input = y + + # Second, we compile the model on the fly if necessary, mostly for subclass + # models. + is_compile_called = False + if not self._is_compiled and self.optimizer: + self._compile_from_inputs(all_inputs, y_input, x, y) + is_compile_called = True + + # In graph mode, if we had just set inputs and targets as symbolic tensors + # by invoking build and compile on the model respectively, we do not have to + # feed anything to the model. Model already has input and target data as + # part of the graph. + # Note: in this case, `any` and `all` are equivalent since we disallow + # mixed symbolic/value inputs. + + # self.run_eagerly is not free to compute, so we want to reuse the value. + run_eagerly = self.run_eagerly + + if (not run_eagerly and is_build_called and is_compile_called and + not is_dataset and any(_is_symbolic_tensor(v) for v in all_inputs)): + return [], [], None + + return self._standardize_tensors( + x, y, sample_weight, + run_eagerly=run_eagerly, + dict_inputs=dict_inputs, + is_dataset=is_dataset, + class_weight=class_weight, + batch_size=batch_size) + + def _standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs, + is_dataset, class_weight=None, batch_size=None): + if run_eagerly: + # In eager mode, do not do shape validation + # since the network has no input nodes (placeholders) to be fed. + feed_input_names = self.input_names + feed_input_shapes = None + elif not self._is_graph_network: + # Case: symbolic-mode subclassed network. Do not do shape validation. + feed_input_names = self._feed_input_names + feed_input_shapes = None + else: + # Case: symbolic-mode graph network. + # In this case, we run extensive shape validation checks. + feed_input_names = self._feed_input_names + feed_input_shapes = self._feed_input_shapes + + # Standardize the inputs. + if not isinstance(x, (data_types.DatasetV1, data_types.DatasetV2)): + # TODO(fchollet): run static checks with dataset output shape(s). + x = training_utils_v1.standardize_input_data( + x, + feed_input_names, + feed_input_shapes, + check_batch_axis=False, # Don't enforce the batch size. + exception_prefix='input') + + # Get typespecs for the input data and sanitize it if necessary. + # TODO(momernick): This should be capable of doing full input validation + # at all times - validate that this is so and refactor the standardization + # code. + if isinstance(x, data_types.DatasetV2): + x_shapes = dataset_ops.get_structure(x) + if isinstance(x_shapes, tuple): + # If the output of a Dataset is a tuple, we assume it's either of the + # form (x_data, y_data) or (x_data, y_data, sample_weights). In either + # case, we only care about x_data here. + x_shapes = x_shapes[0] + else: + flat_inputs = nest.flatten(x, expand_composites=False) + flat_expected_inputs = nest.flatten(self.inputs, expand_composites=False) + converted_x = [] + for (a, b) in zip(flat_inputs, flat_expected_inputs): + converted_x.append(_convert_scipy_sparse_tensor(a, b)) + x = nest.pack_sequence_as(x, converted_x, expand_composites=False) + + def _type_spec_from_value(value): + """Grab type_spec without converting array-likes to tensors.""" + if tf_utils.is_extension_type(value): + return value._type_spec # pylint: disable=protected-access + # Get a TensorSpec for array-like data without + # converting the data to a Tensor + if hasattr(value, 'shape') and hasattr(value, 'dtype'): + return tensor_spec.TensorSpec(value.shape, value.dtype) + else: + return type_spec.type_spec_from_value(value) + + x_shapes = nest.map_structure(_type_spec_from_value, x) + + flat_inputs = nest.flatten(x_shapes, expand_composites=False) + flat_expected_inputs = nest.flatten(self.inputs, expand_composites=False) + for (a, b) in zip(flat_inputs, flat_expected_inputs): + nest.assert_same_structure(a, b, expand_composites=True) + + if y is not None: + # Prepare self._sample_weight_modes. List with the same length as + # model outputs. + training_utils_v1.prepare_sample_weight_modes(self._training_endpoints, + self.sample_weight_mode) + feed_output_names = self._feed_output_names + feed_sample_weight_modes = self._sample_weight_modes + if not self._is_graph_network: + feed_output_shapes = None + else: + feed_output_shapes = self._feed_output_shapes + + # Standardize the outputs. + y = training_utils_v1.standardize_input_data( + y, + feed_output_names, + # Don't enforce target shapes to match output shapes. + # Precise checks will be run in `check_loss_and_target_compatibility`. + shapes=None, + check_batch_axis=False, # Don't enforce the batch size. + exception_prefix='target') + + # Generate sample-wise weight values given the `sample_weight` and + # `class_weight` arguments. + sample_weights = training_utils_v1.standardize_sample_weights( + sample_weight, feed_output_names) + class_weights = training_utils_v1.standardize_class_weights( + class_weight, feed_output_names) + + sample_weights = [ + training_utils_v1.standardize_weights(ref, sw, cw, mode) + for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights, + feed_sample_weight_modes) + ] + # Check that all arrays have the same length. + if not self._distribution_strategy: + training_utils_v1.check_array_lengths(x, y, sample_weights) + if self._is_graph_network and not run_eagerly: + # Additional checks to avoid users mistakenly using improper loss fns. + training_utils_v1.check_loss_and_target_compatibility( + y, self._feed_loss_fns, feed_output_shapes) + + sample_weights, _, _ = training_utils.handle_partial_sample_weights( + y, sample_weights, feed_sample_weight_modes, check_all_flat=True) + else: + y = [] + sample_weights = None + + if self.stateful and batch_size and not is_dataset: + # Check that for stateful networks, number of samples is a multiple + # of the static batch size. + if x[0].shape[0] % batch_size != 0: + raise ValueError('In a stateful network, ' + 'you should only pass inputs with ' + 'a number of samples that can be ' + 'divided by the batch size. Found: ' + + str(x[0].shape[0]) + ' samples') + + # If dictionary inputs were provided, we return a dictionary as well. + if dict_inputs and not isinstance(x, (data_types.DatasetV1, + data_types.DatasetV2)): + x = dict(zip(feed_input_names, x)) + return x, y, sample_weights + + def _build_model_with_inputs(self, inputs, targets): + """Build the model (set model inputs/outputs), mainly for subclass model.""" + processed_inputs = [] + is_dict_inputs = False + orig_inputs = inputs + # We need to use `inputs` to set the model inputs. + # If input data is a dataset iterator in graph mode or if it is an eager + # iterator and only one batch of samples is required, we fetch the data + # tensors from the iterator and then standardize them. + if isinstance(inputs, (data_types.DatasetV1, data_types.DatasetV2)): + inputs, targets, _ = training_utils_v1.extract_tensors_from_dataset( + inputs) + # We type-check that `inputs` and `targets` are either single arrays + # or lists of arrays, and extract a flat list of inputs from the passed + # structure. + training_utils_v1.validate_input_types(inputs, orig_inputs) + + if isinstance(inputs, (list, tuple)): + processed_inputs += list(inputs) + elif isinstance(inputs, dict): + is_dict_inputs = True + keys = sorted(inputs.keys()) + processed_inputs = [inputs[k] for k in keys] + else: + processed_inputs.append(inputs) + # Now that we have a flat set of inputs, we make sure that none of them + # are CompositeTensors or CompositeTensorValues of any type (or scipy + # sparse arrays, which we treat as SparseTensor values). We cannot safely + # infer input data from an arbitrary composite tensor, so we don't try - + # users should explicitly add composite tensor inputs to their subclassed + # models. + for input_tensor in processed_inputs: + if training_utils_v1.is_composite_or_composite_value(input_tensor): + # TODO(b/132691975): Document subclass-model CT input handling. + raise ValueError( + 'All SparseTensor and RaggedTensor inputs must be explicitly ' + 'declared using a keras.Input() with sparse=True or ragged=True. ' + 'We found an undeclared input %s. For Sequential models, please ' + 'add a keras.Input() as your first Layer. For subclassed models, ' + 'please call self._set_inputs() on your input set, which you can ' + 'create using keras.Input() for each input to your model.' % + (input_tensor,)) + # Build the model using the retrieved inputs (value or symbolic). + # If values are generated from a dataset, then in symbolic-mode + # placeholders will be created to match the value shapes. + if isinstance(orig_inputs, (data_types.DatasetV1, data_types.DatasetV2, + iterator_ops.Iterator)): + if not self.inputs: + # For subclassed models, a robust input spec is not available so we + # must cast to the model dtype. + inputs = training_utils_v1.cast_if_floating_dtype(inputs, self.dtype) + + def create_tensor_spec(t): + return tensor_spec.TensorSpec(t.shape, t.dtype) + + cast_inputs = nest.map_structure(create_tensor_spec, inputs) + elif training_utils_v1.has_tensors(inputs): + cast_inputs = training_utils_v1.cast_if_floating_dtype(inputs) + else: + cast_inputs = inputs + self._set_inputs(cast_inputs) + return processed_inputs, targets, is_dict_inputs + + def _compile_from_inputs(self, all_inputs, target, orig_inputs, orig_target): + if target is not None: + # We need to use `y` to set the model targets. + if training_utils_v1.has_tensors(target): + target = training_utils_v1.cast_if_floating_dtype_and_mismatch( + target, self.outputs) + training_utils_v1.validate_input_types( + target, orig_target, allow_dict=False, field_name='target') + if isinstance(target, (list, tuple)): + all_inputs += list(target) + else: + all_inputs.append(target) + # Type check that all inputs are *either* value *or* symbolic. + # TODO(fchollet): this check could be removed in Eager mode? + if any(tensor_util.is_tf_type(v) for v in all_inputs): + if not all(tensor_util.is_tf_type(v) for v in all_inputs): + raise ValueError('Do not pass inputs that mix Numpy arrays and ' + 'TensorFlow tensors. ' + 'You passed: x=' + str(orig_inputs) + + '; y=' + str(orig_target)) + is_dataset = isinstance(orig_inputs, (data_types.DatasetV1, + data_types.DatasetV2, + iterator_ops.Iterator)) + if is_dataset or context.executing_eagerly(): + target_tensors = None + else: + # Handle target tensors if any passed. + if target is not None: + if not isinstance(target, (list, tuple)): + target = [target] + target_tensors = [v for v in target if _is_symbolic_tensor(v)] + else: + target_tensors = None + + self.compile( + optimizer=self.optimizer, + loss=self.loss, + metrics=self._compile_metrics, + weighted_metrics=self._compile_weighted_metrics, + loss_weights=self.loss_weights, + target_tensors=target_tensors, + sample_weight_mode=self.sample_weight_mode, + run_eagerly=self.run_eagerly, + experimental_run_tf_function=self._experimental_run_tf_function) + + # TODO(omalleyt): Consider changing to a more descriptive function name. + def _set_inputs(self, inputs, outputs=None, training=None): + """Set model's input and output specs based on the input data received. + + This is to be used for Model subclasses, which do not know at instantiation + time what their inputs look like. + + Args: + inputs: Single array, or list of arrays. The arrays could be placeholders, + Numpy arrays, data tensors, or TensorSpecs. + - if placeholders: the model is built on top of these placeholders, + and we expect Numpy data to be fed for them when calling `fit`/etc. + - if Numpy data or TensorShapes: we create placeholders matching the + TensorShapes or shapes of the Numpy arrays. We expect Numpy data to be + fed for these placeholders when calling `fit`/etc. + - if data tensors: the model is built on top of these tensors. + We do not expect any Numpy data to be provided when calling `fit`/etc. + outputs: None, a data tensor, or a list of tensors. If None, the + outputs will be determined by invoking `self.call()`, otherwise the + provided value will be used. + training: Boolean or None. Only relevant in symbolic mode. Specifies + whether to build the model's graph in inference mode (False), training + mode (True), or using the Keras learning phase (None). + Raises: + ValueError: If dict inputs are passed to a Sequential Model where the + first layer isn't FeatureLayer. + """ + self._set_save_spec(inputs) + inputs = self._set_input_attrs(inputs) + + if outputs is None: + kwargs = {} + if self._expects_training_arg: + # In V2 mode, feeding `training=None` is not allowed because any value + # explicitly passed by the user is respected, even `None`.` + if training is None and not ops.executing_eagerly_outside_functions(): + training = backend.learning_phase() + if training is not None: + kwargs['training'] = training + try: + outputs = self(inputs, **kwargs) + except NotImplementedError: + # This Model or a submodel is dynamic and hasn't overridden + # `compute_output_shape`. + outputs = None + + self._set_output_attrs(outputs) + + @trackable.no_automatic_dependency_tracking + def _set_input_attrs(self, inputs): + """Sets attributes related to the inputs of the Model.""" + if self.inputs: + raise ValueError('Model inputs are already set.') + + if self.__class__.__name__ == 'Sequential' and not self.built: + if tensor_util.is_tf_type(inputs): + input_shape = (None,) + tuple(inputs.shape.as_list()[1:]) + elif isinstance(inputs, tensor_shape.TensorShape): + input_shape = (None,) + tuple(inputs.as_list()[1:]) + elif isinstance(inputs, dict): + # We assert that the first layer is a FeatureLayer. + if not training_utils_v1.is_feature_layer(self.layers[0]): + raise ValueError('Passing a dictionary input to a Sequential Model ' + 'which doesn\'t have FeatureLayer as the first layer' + ' is an error.') + input_shape = (None,) + else: + input_shape = (None,) + tuple(inputs.shape[1:]) + self._build_input_shape = input_shape + + # Cast inputs to the compute dtype. This is primarily used + # when saving to determine the correct dtype in the input signature. + inputs = self._maybe_cast_inputs(inputs) + + # On-the-fly setting of symbolic model inputs (either by using the tensor + # provided, or by creating a placeholder if Numpy data was provided). + model_inputs = training_utils_v1.ModelInputs(inputs) + inputs = model_inputs.get_symbolic_inputs() + self.inputs = model_inputs.get_symbolic_inputs(return_single_as_list=True) + self.input_names = model_inputs.get_input_names() + + self._feed_inputs = [] + self._feed_input_names = [] + self._feed_input_shapes = [] + + for k, v in model_inputs.as_dict(): + if backend.is_placeholder(v): + self._feed_input_names.append(k) + self._feed_inputs.append(v) + self._feed_input_shapes.append(backend.int_shape(v)) + + return inputs + + @trackable.no_automatic_dependency_tracking + def _set_output_attrs(self, outputs): + """Sets attributes related to the outputs of the Model.""" + # NOTE(taylorrobie): This convention cannot be changed without updating the + # data adapter since it assumes nest.flatten ordering. + outputs = nest.flatten(outputs) + self.outputs = outputs + self.output_names = training_utils_v1.generic_output_names(outputs) + # TODO(scottzhu): Should we cleanup the self._training_endpoints here? + self.built = True + + @property + def _targets(self): + """The output target tensors for the model.""" + return [ + e.training_target.target + for e in self._training_endpoints + if e.has_training_target() + ] + + @property + def _feed_targets(self): + return [ + e.training_target.target + for e in self._training_endpoints + if e.has_feedable_training_target() + ] + + @property + def _feed_output_names(self): + return [ + e.output_name + for e in self._training_endpoints + if e.has_feedable_training_target() + ] + + @property + def _feed_output_shapes(self): + return [ + e.feed_output_shape + for e in self._training_endpoints + if e.has_feedable_training_target() + ] + + @property + def _feed_loss_fns(self): + return [ + e.loss_fn + for e in self._training_endpoints + if e.has_feedable_training_target() + ] + + @property + def _loss_weights_list(self): + return [e.loss_weight for e in self._training_endpoints] + + @property + def _output_loss_metrics(self): + if hasattr(self, '_training_endpoints'): + return [ + e.output_loss_metric + for e in self._training_endpoints + if e.output_loss_metric is not None + ] + return None + + @property + def sample_weights(self): + return [e.sample_weight for e in self._training_endpoints] + + @property + def _sample_weight_modes(self): + return [e.sample_weight_mode for e in self._training_endpoints] + + @property + def _feed_sample_weights(self): + return [e.sample_weight for e in self._training_endpoints + if e.sample_weight is not None] + + def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch, mode): + """Maybe load initial epoch from ckpt considering possible worker recovery. + + Refer to tensorflow/python/keras/distribute/worker_training_state.py + for more information. + + Args: + initial_epoch: The original initial_epoch user passes in in `fit()`. + mode: The mode for running `model.fit()`. + + Returns: + If the training is recovering from previous failure under multi-worker + training setting, return the epoch the training is supposed to continue + at. Otherwise, return the `initial_epoch` the user passes in. + """ + if self._training_state is not None: + return self._training_state.maybe_load_initial_epoch_from_ckpt( + initial_epoch, mode) + return initial_epoch + + def _get_training_eval_metrics(self): + """Returns all the metrics that are to be reported. + + This includes the output loss metrics, compile metrics/weighted metrics, + add_metric metrics. + """ + metrics = [] + metrics.extend(getattr(self, '_output_loss_metrics', None) or []) + metrics.extend(getattr(self, 'metrics', None) or []) + return metrics + + def _assert_compile_was_called(self): + # Checks whether `compile` has been called. If it has been called, + # then the optimizer is set. This is different from whether the + # model is compiled + # (i.e. whether the model is built and its inputs/outputs are set). + if not self._compile_was_called: + raise RuntimeError('You must compile your model before ' + 'training/testing. ' + 'Use `model.compile(optimizer, loss)`.') + + def _in_multi_worker_mode(self): + """Method to infer if this `Model` is working in multi-worker settings. + + Multi-worker training refers to the setup where the training is + distributed across multiple workers, as opposed to the case where + only a local process performs the training. This function is + used to infer for example whether or not a distribute coordinator + should be run, and thus TensorFlow servers should be started for + communication with other servers in the cluster, or whether or not + saving/restoring checkpoints is relevant for preemption fault tolerance. + + Experimental. Signature and implementation are subject to change. + + Returns: + Whether this model indicates it's working in multi-worker settings. + """ + strategy = self._distribution_strategy + + # Otherwise, use the strategy whose scope this is in. + if not strategy and distribute_lib.has_strategy(): + strategy = distribute_lib.get_strategy() + return strategy and strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access + + @property + def _trackable_saved_model_saver(self): + return model_serialization.ModelSavedModelSaver(self) + + def _get_compile_args(self, user_metrics=True): + del user_metrics + self._assert_compile_was_called() + kwargs = { + 'loss': self.loss, + 'metrics': self._compile_metrics, + 'loss_weights': self.loss_weights, + 'sample_weight_mode': self.sample_weight_mode, + 'weighted_metrics': self._compile_weighted_metrics, + } + return kwargs + + @property + def _compile_was_called(self): + return self._v1_compile_was_called + + +class DistributedCallbackModel(Model): + """Model that is used for callbacks with tf.distribute.Strategy.""" + + def __init__(self, model): + super(DistributedCallbackModel, self).__init__() + self.optimizer = model.optimizer + + def set_original_model(self, orig_model): + self._original_model = orig_model + + def save_weights(self, filepath, overwrite=True, save_format=None): + self._replicated_model.save_weights(filepath, overwrite=overwrite, + save_format=save_format) + + def save(self, filepath, overwrite=True, include_optimizer=True): + # save weights from the distributed model to the original model + distributed_model_weights = self.get_weights() + self._original_model.set_weights(distributed_model_weights) + # TODO(anjalisridhar): Do we need to save the original model here? + # Saving the first replicated model works as well. + self._original_model.save(filepath, overwrite=True, include_optimizer=False) + + def load_weights(self, filepath, by_name=False): + self._original_model.load_weights(filepath, by_name=False) + # Copy the weights from the original model to each of the replicated models. + orig_model_weights = self._original_model.get_weights() + distributed_training_utils_v1.set_weights( + self._original_model._distribution_strategy, self, # pylint: disable=protected-access + orig_model_weights) + + def __getattr__(self, item): + # Allowed attributes of the model that can be accessed by the user + # during a callback. + if item not in ('_setattr_tracking', '_layers'): + logging.warning('You are accessing attribute ' + item + ' of the ' + 'DistributedCallbackModel that may not have been set ' + 'correctly.') + return super(DistributedCallbackModel, self).__getattr__(item) + + +class _TrainingEndpoint(object): + """A container for the training output/target and related entities. + + In the case of model with multiple outputs, there is a one-to-one mapping + between model output (y_pred), model target (y_true), loss, metrics etc. + By unifying these entities into one class, different entity can access + information between each other, rather than currently access different list of + attributes of the model. + """ + + def __init__(self, + output, + output_name, + loss_fn, + loss_weight=None, + training_target=None, + output_loss_metric=None, + sample_weight=None, + sample_weight_mode=None): + """Initialize the _TrainingEndpoint. + + Note that the output and output_name should be stable as long as the model + structure doesn't change. The training_target suppose to be mutable since + the information is provided via `compile()` + + Args: + output: the output tensor of the model. + output_name: the unique name of the output tensor. + loss_fn: the loss function for the output tensor. + loss_weight: float, the weights for the loss. + training_target: the _TrainingTarget for the model. + output_loss_metric: the metric object for the loss function. + sample_weight: the weights for how a sample is weighted during metric and + loss calculation. Could be None. + sample_weight_mode: string, 'temporal', 'samplewise' or None. The mode for + how the sample_weight is populated. + """ + self._output = output + self._output_name = output_name + self._loss_fn = loss_fn + self._loss_weight = loss_weight + self._training_target = training_target + self._output_loss_metric = output_loss_metric + self._sample_weight = sample_weight + self._sample_weight_mode = sample_weight_mode + + @property + def output(self): + return self._output + + @property + def output_name(self): + return self._output_name + + @property + def shape(self): + return backend.int_shape(self.output) + + @property + def loss_fn(self): + return self._loss_fn + + @property + def loss_weight(self): + return self._loss_weight + + @loss_weight.setter + def loss_weight(self, value): + self._loss_weight = value + + @property + def training_target(self): + return self._training_target + + @training_target.setter + def training_target(self, value): + self._training_target = value + + def create_training_target(self, target, run_eagerly=False): + """Create training_target instance and update the self.training_target. + + Note that the input target should just be a tensor or None, and + corresponding training target will be created based on the output and + loss_fn. + + Args: + target: the target tensor for the current output. Could be None. + run_eagerly: boolean, whether the model is in run_eagerly mode. + + Raises: + ValueError if the training_target field for the current instance has + already been populated. + """ + if self.has_training_target(): + raise ValueError('The training_target field for the _TrainingEndpoint ' + 'instance has already been populated') + if run_eagerly: + # When run_eagerly, the target tensor is ignored, and the None placeholder + # is created instead. + self.training_target = _TrainingTarget( + None, feedable=True, skip_target_weights=False) + return + + if self.should_skip_target(): + self.training_target = _TrainingTarget(None) + else: + if target is not None and not backend.is_placeholder(target): + feedable = False + skip_target_weights = True + else: + feedable = True + skip_target_weights = False + + if target is None: + target_dtype = losses.LABEL_DTYPES_FOR_LOSSES.get( + self.loss_fn, backend.dtype(self.output)) + + target = backend.placeholder( + ndim=len(self.shape), + name=self.output_name + '_target', + sparse=backend.is_sparse(self.output), + dtype=target_dtype) + + self.training_target = _TrainingTarget( + target, + feedable=feedable, + skip_target_weights=skip_target_weights) + + @property + def output_loss_metric(self): + return self._output_loss_metric + + @output_loss_metric.setter + def output_loss_metric(self, value): + self._output_loss_metric = value + + @property + def sample_weight(self): + return self._sample_weight + + @sample_weight.setter + def sample_weight(self, value): + self._sample_weight = value + + @property + def sample_weight_mode(self): + return self._sample_weight_mode + + @sample_weight_mode.setter + def sample_weight_mode(self, value): + self._sample_weight_mode = value + + def should_skip_target(self): + return self._loss_fn is None + + def should_skip_target_weights(self): + return (self.should_skip_target() or self.training_target is None or + self.training_target.skip_target_weights) + + def has_training_target(self): + return self.training_target is not None + + def has_feedable_training_target(self): + return (not self.should_skip_target() and + self.training_target is not None and self.training_target.feedable) + + def loss_name(self): + if self._loss_fn is not None: + return self._output_name + '_loss' + return None + + @property + def feed_output_shape(self): + """The output shape for the feedable target.""" + if not self.has_feedable_training_target(): + return None + + if ((isinstance(self.loss_fn, losses.LossFunctionWrapper) and + self.loss_fn.fn == losses.sparse_categorical_crossentropy)) or ( + isinstance(self.loss_fn, losses.SparseCategoricalCrossentropy)): + if backend.image_data_format() == 'channels_first': + return (self.shape[0], 1) + self.shape[2:] + else: + return self.shape[:-1] + (1,) + elif (not isinstance(self.loss_fn, losses.Loss) or + (isinstance(self.loss_fn, losses.LossFunctionWrapper) and + (getattr(losses, self.loss_fn.fn.__name__, None) is None))): + # If the given loss is not an instance of the `Loss` class (custom + # class) or if the loss function that is wrapped is not in the + # `losses` module, then it is a user-defined loss and we make no + # assumptions about it. + return None + else: + return self.shape + + def sample_weights_mismatch(self): + """Check if the sample weight and the mode match or not.""" + # If there is a mismatch between sample weight mode and the placeholders + # created, then recompile the sub-graphs that depend on sample weights. + return ( + (self.sample_weight_mode is not None and self.sample_weight is None) or + (self.sample_weight_mode is None and self.sample_weight is not None)) + + def populate_sample_weight(self, sample_weight, sample_weight_mode): + """Populate the sample weight and based on the sample weight mode.""" + if (sample_weight is None and + (self.should_skip_target_weights() or sample_weight_mode is None or + context.executing_eagerly())): + self._sample_weight = None + return + + assert sample_weight_mode in ['temporal', 'samplewise'] + if sample_weight_mode == 'temporal': + default_value = [[1.]] + shape = [None, None] + else: + # sample_weight_mode == 'samplewise' + default_value = [1.] + shape = [None] + + if sample_weight is not None: + if not sample_weight.shape.is_compatible_with(shape): + raise ValueError('Received sample weight with shape {}. Expected shape ' + '{}.'.format(sample_weight.shape, shape)) + self._sample_weight = sample_weight + else: + self._sample_weight = array_ops.placeholder_with_default( + constant_op.constant(default_value, dtype=backend.floatx()), + shape=shape, + name=self.output_name + '_sample_weights') + + +class _TrainingTarget(object): + """Container for a target tensor (y_true) and its metadata (shape, loss...). + + Args: + target: A target tensor for the model. It may be `None` if the + output is excluded from loss computation. It is still kept as None + since each output of the model should have a corresponding target. If + the target is None, the rest of the attributes will be None as well. + feedable: Boolean, whether the target is feedable (requires data to be + passed in `fit` or `train_on_batch`), or not (model compiled with + `target_tensors` argument). + skip_target_weights: Boolean, whether the target should be skipped during + weights calculation. + """ + + def __init__(self, target, feedable=False, skip_target_weights=True): + self._target = target + self._feedable = feedable + self._skip_target_weights = skip_target_weights + + @property + def target(self): + return self._target + + @property + def feedable(self): + return self._feedable + + @property + def skip_target_weights(self): + return self._skip_target_weights + + +def _is_symbolic_tensor(x): + return tensor_util.is_tf_type(x) + + +def _convert_scipy_sparse_tensor(value, expected_input): + """Handle scipy sparse tensor conversions. + + This method takes a value 'value' and returns the proper conversion. If + value is a scipy sparse tensor and the expected input is a dense tensor, + we densify 'value'. If value is a scipy sparse tensor and the expected input + is a TF SparseTensor, we convert 'value' to a SparseTensor. If 'value' is + not a scipy sparse tensor, or scipy is not imported, we pass it through + unchanged. + + Args: + value: An object that may be a scipy sparse tensor + expected_input: The expected input placeholder. + + Returns: + The possibly-converted 'value'. + """ + if issparse is not None and issparse(value): + if backend.is_sparse(expected_input): + sparse_coo = value.tocoo() + row, col = sparse_coo.row, sparse_coo.col + data, shape = sparse_coo.data, sparse_coo.shape + indices = np.concatenate((np.expand_dims(row, 1), np.expand_dims(col, 1)), + 1) + return sparse_tensor.SparseTensor(indices, data, shape) + else: + if ops.executing_eagerly_outside_functions(): + # In TF2 we do not silently densify sparse matrices. + raise ValueError('A SciPy sparse matrix was passed to a model ' + 'that expects dense inputs. Please densify your ' + 'inputs first, such as by calling `x.toarray().') + return value.toarray() + else: + return value + + +def _get_metrics_from_layers(layers): + """Returns list of metrics from the given layers. + + This will not include the `compile` metrics of a model layer. + + Args: + layers: List of layers. + + Returns: + List of metrics. + """ + metrics = [] + layers = layer_utils.filter_empty_layer_containers(layers) + for layer in layers: + if isinstance(layer, Model): + # We cannot call 'metrics' on the model because we do not want to + # include the metrics that were added in compile API of a nested model. + metrics.extend(layer._metrics) # pylint: disable=protected-access + metrics.extend(_get_metrics_from_layers(layer.layers)) + else: + metrics.extend(layer.metrics) + return metrics + + +def _non_none_constant_value(v): + constant_value = tensor_util.constant_value(v) + return constant_value if constant_value is not None else v diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..deba75c8b7e1a2cc4a8035fb41488ad2a7694c49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/__init__.py @@ -0,0 +1,187 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras initializer serialization / deserialization.""" + +import threading + +from tensorflow.python import tf2 +from tensorflow.python.keras.initializers import initializers_v1 +from tensorflow.python.keras.initializers import initializers_v2 +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_inspect as inspect +from tensorflow.python.ops import init_ops + + +# LOCAL.ALL_OBJECTS is meant to be a global mutable. Hence we need to make it +# thread-local to avoid concurrent mutations. +LOCAL = threading.local() + + +def populate_deserializable_objects(): + """Populates dict ALL_OBJECTS with every built-in initializer. + """ + global LOCAL + if not hasattr(LOCAL, 'ALL_OBJECTS'): + LOCAL.ALL_OBJECTS = {} + LOCAL.GENERATED_WITH_V2 = None + + if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf2.enabled(): + # Objects dict is already generated for the proper TF version: + # do nothing. + return + + LOCAL.ALL_OBJECTS = {} + LOCAL.GENERATED_WITH_V2 = tf2.enabled() + + # Compatibility aliases (need to exist in both V1 and V2). + LOCAL.ALL_OBJECTS['ConstantV2'] = initializers_v2.Constant + LOCAL.ALL_OBJECTS['GlorotNormalV2'] = initializers_v2.GlorotNormal + LOCAL.ALL_OBJECTS['GlorotUniformV2'] = initializers_v2.GlorotUniform + LOCAL.ALL_OBJECTS['HeNormalV2'] = initializers_v2.HeNormal + LOCAL.ALL_OBJECTS['HeUniformV2'] = initializers_v2.HeUniform + LOCAL.ALL_OBJECTS['IdentityV2'] = initializers_v2.Identity + LOCAL.ALL_OBJECTS['LecunNormalV2'] = initializers_v2.LecunNormal + LOCAL.ALL_OBJECTS['LecunUniformV2'] = initializers_v2.LecunUniform + LOCAL.ALL_OBJECTS['OnesV2'] = initializers_v2.Ones + LOCAL.ALL_OBJECTS['OrthogonalV2'] = initializers_v2.Orthogonal + LOCAL.ALL_OBJECTS['RandomNormalV2'] = initializers_v2.RandomNormal + LOCAL.ALL_OBJECTS['RandomUniformV2'] = initializers_v2.RandomUniform + LOCAL.ALL_OBJECTS['TruncatedNormalV2'] = initializers_v2.TruncatedNormal + LOCAL.ALL_OBJECTS['VarianceScalingV2'] = initializers_v2.VarianceScaling + LOCAL.ALL_OBJECTS['ZerosV2'] = initializers_v2.Zeros + + # Out of an abundance of caution we also include these aliases that have + # a non-zero probability of having been included in saved configs in the past. + LOCAL.ALL_OBJECTS['glorot_normalV2'] = initializers_v2.GlorotNormal + LOCAL.ALL_OBJECTS['glorot_uniformV2'] = initializers_v2.GlorotUniform + LOCAL.ALL_OBJECTS['he_normalV2'] = initializers_v2.HeNormal + LOCAL.ALL_OBJECTS['he_uniformV2'] = initializers_v2.HeUniform + LOCAL.ALL_OBJECTS['lecun_normalV2'] = initializers_v2.LecunNormal + LOCAL.ALL_OBJECTS['lecun_uniformV2'] = initializers_v2.LecunUniform + + if tf2.enabled(): + # For V2, entries are generated automatically based on the content of + # initializers_v2.py. + v2_objs = {} + base_cls = initializers_v2.Initializer + generic_utils.populate_dict_with_module_objects( + v2_objs, + [initializers_v2], + obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls)) + for key, value in v2_objs.items(): + LOCAL.ALL_OBJECTS[key] = value + # Functional aliases. + LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value + else: + # V1 initializers. + v1_objs = { + 'Constant': init_ops.Constant, + 'GlorotNormal': init_ops.GlorotNormal, + 'GlorotUniform': init_ops.GlorotUniform, + 'Identity': init_ops.Identity, + 'Ones': init_ops.Ones, + 'Orthogonal': init_ops.Orthogonal, + 'VarianceScaling': init_ops.VarianceScaling, + 'Zeros': init_ops.Zeros, + 'HeNormal': initializers_v1.HeNormal, + 'HeUniform': initializers_v1.HeUniform, + 'LecunNormal': initializers_v1.LecunNormal, + 'LecunUniform': initializers_v1.LecunUniform, + 'RandomNormal': initializers_v1.RandomNormal, + 'RandomUniform': initializers_v1.RandomUniform, + 'TruncatedNormal': initializers_v1.TruncatedNormal, + } + for key, value in v1_objs.items(): + LOCAL.ALL_OBJECTS[key] = value + # Functional aliases. + LOCAL.ALL_OBJECTS[generic_utils.to_snake_case(key)] = value + + # More compatibility aliases. + LOCAL.ALL_OBJECTS['normal'] = LOCAL.ALL_OBJECTS['random_normal'] + LOCAL.ALL_OBJECTS['uniform'] = LOCAL.ALL_OBJECTS['random_uniform'] + LOCAL.ALL_OBJECTS['one'] = LOCAL.ALL_OBJECTS['ones'] + LOCAL.ALL_OBJECTS['zero'] = LOCAL.ALL_OBJECTS['zeros'] + + +# For backwards compatibility, we populate this file with the objects +# from ALL_OBJECTS. We make no guarantees as to whether these objects will +# using their correct version. +populate_deserializable_objects() +globals().update(LOCAL.ALL_OBJECTS) + +# Utility functions + + +def serialize(initializer): + return generic_utils.serialize_keras_object(initializer) + + +def deserialize(config, custom_objects=None): + """Return an `Initializer` object from its config.""" + populate_deserializable_objects() + return generic_utils.deserialize_keras_object( + config, + module_objects=LOCAL.ALL_OBJECTS, + custom_objects=custom_objects, + printable_module_name='initializer') + + +def get(identifier): + """Retrieve a Keras initializer by the identifier. + + The `identifier` may be the string name of a initializers function or class ( + case-sensitively). + + >>> identifier = 'Ones' + >>> tf.keras.initializers.deserialize(identifier) + <...keras.initializers.initializers_v2.Ones...> + + You can also specify `config` of the initializer to this function by passing + dict containing `class_name` and `config` as an identifier. Also note that the + `class_name` must map to a `Initializer` class. + + >>> cfg = {'class_name': 'Ones', 'config': {}} + >>> tf.keras.initializers.deserialize(cfg) + <...keras.initializers.initializers_v2.Ones...> + + In the case that the `identifier` is a class, this method will return a new + instance of the class by its constructor. + + Args: + identifier: String or dict that contains the initializer name or + configurations. + + Returns: + Initializer instance base on the input identifier. + + Raises: + ValueError: If the input identifier is not a supported type or in a bad + format. + """ + + if identifier is None: + return None + if isinstance(identifier, dict): + return deserialize(identifier) + elif isinstance(identifier, str): + identifier = str(identifier) + return deserialize(identifier) + elif callable(identifier): + if inspect.isclass(identifier): + identifier = identifier() + return identifier + else: + raise ValueError('Could not interpret initializer identifier: ' + + str(identifier)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..38cc0cee4ce15ea8a93b49542595fc8f0bda8419 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v1.py @@ -0,0 +1,90 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras initializers for TF 1.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import init_ops + + +_v1_zeros_initializer = init_ops.Zeros +_v1_ones_initializer = init_ops.Ones +_v1_constant_initializer = init_ops.Constant +_v1_variance_scaling_initializer = init_ops.VarianceScaling +_v1_orthogonal_initializer = init_ops.Orthogonal +_v1_identity = init_ops.Identity +_v1_glorot_uniform_initializer = init_ops.GlorotUniform +_v1_glorot_normal_initializer = init_ops.GlorotNormal + + +class RandomNormal(init_ops.RandomNormal): + + def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=dtypes.float32): + super(RandomNormal, self).__init__( + mean=mean, stddev=stddev, seed=seed, dtype=dtype) + + +class RandomUniform(init_ops.RandomUniform): + + def __init__(self, minval=-0.05, maxval=0.05, seed=None, + dtype=dtypes.float32): + super(RandomUniform, self).__init__( + minval=minval, maxval=maxval, seed=seed, dtype=dtype) + + +class TruncatedNormal(init_ops.TruncatedNormal): + + def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=dtypes.float32): + super(TruncatedNormal, self).__init__( + mean=mean, stddev=stddev, seed=seed, dtype=dtype) + + +class LecunNormal(init_ops.VarianceScaling): + + def __init__(self, seed=None): + super(LecunNormal, self).__init__( + scale=1., mode='fan_in', distribution='truncated_normal', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class LecunUniform(init_ops.VarianceScaling): + + def __init__(self, seed=None): + super(LecunUniform, self).__init__( + scale=1., mode='fan_in', distribution='uniform', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class HeNormal(init_ops.VarianceScaling): + + def __init__(self, seed=None): + super(HeNormal, self).__init__( + scale=2., mode='fan_in', distribution='truncated_normal', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class HeUniform(init_ops.VarianceScaling): + + def __init__(self, seed=None): + super(HeUniform, self).__init__( + scale=2., mode='fan_in', distribution='uniform', seed=seed) + + def get_config(self): + return {'seed': self.seed} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..ba0a932aaf5b884bf7e774b6e15464eadad0cb49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/initializers/initializers_v2.py @@ -0,0 +1,981 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras initializers for TF 2.""" +# pylint: disable=g-classes-have-attributes + +import math + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.keras import backend +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import stateless_random_ops + +_PARTITION_SHAPE = 'partition_shape' +_PARTITION_OFFSET = 'partition_offset' + + +class Initializer(object): + """Initializer base class: all Keras initializers inherit from this class. + + Initializers should implement a `__call__` method with the following + signature: + + ```python + def __call__(self, shape, dtype=None, **kwargs): + # returns a tensor of shape `shape` and dtype `dtype` + # containing values drawn from a distribution of your choice. + ``` + + Optionally, you an also implement the method `get_config` and the class + method `from_config` in order to support serialization -- just like with + any Keras object. + + Here's a simple example: a random normal initializer. + + ```python + import tensorflow as tf + + class ExampleRandomNormal(tf.keras.initializers.Initializer): + + def __init__(self, mean, stddev): + self.mean = mean + self.stddev = stddev + + def __call__(self, shape, dtype=None, **kwargs): + return tf.random.normal( + shape, mean=self.mean, stddev=self.stddev, dtype=dtype) + + def get_config(self): # To support serialization + return {"mean": self.mean, "stddev": self.stddev} + ``` + + Note that we don't have to implement `from_config` in the example above since + the constructor arguments of the class the keys in the config returned by + `get_config` are the same. In this case, the default `from_config` + works fine. + """ + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. + **kwargs: Additional keyword arguments. + """ + raise NotImplementedError + + def get_config(self): + """Returns the configuration of the initializer as a JSON-serializable dict. + + Returns: + A JSON-serializable Python dict. + """ + return {} + + @classmethod + def from_config(cls, config): + """Instantiates an initializer from a configuration dictionary. + + Example: + + ```python + initializer = RandomUniform(-1, 1) + config = initializer.get_config() + initializer = RandomUniform.from_config(config) + ``` + + Args: + config: A Python dictionary, the output of `get_config`. + + Returns: + A `tf.keras.initializers.Initializer` instance. + """ + config.pop('dtype', None) + return cls(**config) + + +class Zeros(Initializer): + """Initializer that generates tensors initialized to 0. + + Also available via the shortcut function `tf.keras.initializers.zeros`. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.Zeros() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.Zeros() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + """ + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are + supported. If not specified, `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`). + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _get_dtype(dtype) + if not dtype.is_numpy_compatible or dtype == dtypes.string: + raise ValueError('Expected numeric or boolean dtype, got %s.' % dtype) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + return array_ops.zeros(shape, dtype) + + +class Ones(Initializer): + """Initializer that generates tensors initialized to 1. + + Also available via the shortcut function `tf.keras.initializers.ones`. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.Ones() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.Ones() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + """ + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are + supported. If not specified, `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`). + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _get_dtype(dtype) + if not dtype.is_numpy_compatible or dtype == dtypes.string: + raise ValueError('Expected numeric or boolean dtype, got %s.' % dtype) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + return array_ops.ones(shape, dtype) + + +class Constant(Initializer): + """Initializer that generates tensors with constant values. + + Also available via the shortcut function `tf.keras.initializers.constant`. + + Only scalar values are allowed. + The constant value provided must be convertible to the dtype requested + when calling the initializer. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.Constant(3.) + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.Constant(3.) + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + value: A Python scalar. + """ + + def __init__(self, value=0): + self.value = value + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized to `self.value`. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. If not specified, + `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`). + **kwargs: Additional keyword arguments. + """ + del kwargs + return constant_op.constant( + self.value, dtype=_get_dtype(dtype), shape=shape) + + def get_config(self): + return {'value': self.value} + + +class RandomUniform(Initializer): + """Initializer that generates tensors with a uniform distribution. + + Also available via the shortcut function + `tf.keras.initializers.random_uniform`. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.) + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.) + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + minval: A python scalar or a scalar tensor. Lower bound of the range of + random values to generate (inclusive). + maxval: A python scalar or a scalar tensor. Upper bound of the range of + random values to generate (exclusive). + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + """ + + def __init__(self, minval=-0.05, maxval=0.05, seed=None): + self.minval = minval + self.maxval = maxval + self.seed = seed + self._random_generator = _RandomGenerator(seed) + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point and integer + types are supported. If not specified, + `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`). + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _get_dtype(dtype) + if not dtype.is_floating and not dtype.is_integer: + raise ValueError('Expected float or integer dtype, got %s.' % dtype) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + return self._random_generator.random_uniform(shape, self.minval, + self.maxval, dtype) + + def get_config(self): + return { + 'minval': self.minval, + 'maxval': self.maxval, + 'seed': self.seed + } + + +class RandomNormal(Initializer): + """Initializer that generates tensors with a normal distribution. + + Also available via the shortcut function + `tf.keras.initializers.random_normal`. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.) + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.) + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + mean: a python scalar or a scalar tensor. Mean of the random values to + generate. + stddev: a python scalar or a scalar tensor. Standard deviation of the random + values to generate. + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + """ + + def __init__(self, mean=0.0, stddev=0.05, seed=None): + self.mean = mean + self.stddev = stddev + self.seed = seed + self._random_generator = _RandomGenerator(seed) + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized to random normal values. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point types are + supported. If not specified, `tf.keras.backend.floatx()` is used, which + default to `float32` unless you configured it otherwise (via + `tf.keras.backend.set_floatx(float_dtype)`) + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _assert_float_dtype(_get_dtype(dtype)) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + return self._random_generator.random_normal(shape, self.mean, self.stddev, + dtype) + + def get_config(self): + return { + 'mean': self.mean, + 'stddev': self.stddev, + 'seed': self.seed + } + + +class TruncatedNormal(Initializer): + """Initializer that generates a truncated normal distribution. + + Also available via the shortcut function + `tf.keras.initializers.truncated_normal`. + + The values generated are similar to values from a + `tf.keras.initializers.RandomNormal` initializer except that values more + than two standard deviations from the mean are + discarded and re-drawn. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.) + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.) + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + mean: a python scalar or a scalar tensor. Mean of the random values + to generate. + stddev: a python scalar or a scalar tensor. Standard deviation of the + random values to generate before truncation. + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + """ + + def __init__(self, mean=0.0, stddev=0.05, seed=None): + self.mean = mean + self.stddev = stddev + self.seed = seed + self._random_generator = _RandomGenerator(seed) + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized to random normal values (truncated). + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point types are + supported. If not specified, `tf.keras.backend.floatx()` is used, which + default to `float32` unless you configured it otherwise (via + `tf.keras.backend.set_floatx(float_dtype)`) + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _assert_float_dtype(_get_dtype(dtype)) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + return self._random_generator.truncated_normal(shape, self.mean, + self.stddev, dtype) + + def get_config(self): + return { + 'mean': self.mean, + 'stddev': self.stddev, + 'seed': self.seed + } + + +class VarianceScaling(Initializer): + """Initializer capable of adapting its scale to the shape of weights tensors. + + Also available via the shortcut function + `tf.keras.initializers.variance_scaling`. + + With `distribution="truncated_normal" or "untruncated_normal"`, samples are + drawn from a truncated/untruncated normal distribution with a mean of zero and + a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)`, + where `n` is: + + - number of input units in the weight tensor, if `mode="fan_in"` + - number of output units, if `mode="fan_out"` + - average of the numbers of input and output units, if `mode="fan_avg"` + + With `distribution="uniform"`, samples are drawn from a uniform distribution + within `[-limit, limit]`, where `limit = sqrt(3 * scale / n)`. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.VarianceScaling( + ... scale=0.1, mode='fan_in', distribution='uniform') + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.VarianceScaling( + ... scale=0.1, mode='fan_in', distribution='uniform') + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + scale: Scaling factor (positive float). + mode: One of "fan_in", "fan_out", "fan_avg". + distribution: Random distribution to use. One of "truncated_normal", + "untruncated_normal" and "uniform". + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + """ + + def __init__(self, + scale=1.0, + mode='fan_in', + distribution='truncated_normal', + seed=None): + if scale <= 0.: + raise ValueError('`scale` must be positive float.') + if mode not in {'fan_in', 'fan_out', 'fan_avg'}: + raise ValueError('Invalid `mode` argument:', mode) + distribution = distribution.lower() + # Compatibility with keras-team/keras. + if distribution == 'normal': + distribution = 'truncated_normal' + if distribution not in {'uniform', 'truncated_normal', + 'untruncated_normal'}: + raise ValueError('Invalid `distribution` argument:', distribution) + self.scale = scale + self.mode = mode + self.distribution = distribution + self.seed = seed + self._random_generator = _RandomGenerator(seed) + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point types are + supported. If not specified, `tf.keras.backend.floatx()` is used, which + default to `float32` unless you configured it otherwise (via + `tf.keras.backend.set_floatx(float_dtype)`) + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs) + dtype = _assert_float_dtype(_get_dtype(dtype)) + scale = self.scale + fan_in, fan_out = _compute_fans(shape) + if _PARTITION_SHAPE in kwargs: + shape = kwargs[_PARTITION_SHAPE] + if self.mode == 'fan_in': + scale /= max(1., fan_in) + elif self.mode == 'fan_out': + scale /= max(1., fan_out) + else: + scale /= max(1., (fan_in + fan_out) / 2.) + if self.distribution == 'truncated_normal': + # constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.) + stddev = math.sqrt(scale) / .87962566103423978 + return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype) + elif self.distribution == 'untruncated_normal': + stddev = math.sqrt(scale) + return self._random_generator.random_normal(shape, 0.0, stddev, dtype) + else: + limit = math.sqrt(3.0 * scale) + return self._random_generator.random_uniform(shape, -limit, limit, dtype) + + def get_config(self): + return { + 'scale': self.scale, + 'mode': self.mode, + 'distribution': self.distribution, + 'seed': self.seed + } + + +class Orthogonal(Initializer): + """Initializer that generates an orthogonal matrix. + + Also available via the shortcut function `tf.keras.initializers.orthogonal`. + + If the shape of the tensor to initialize is two-dimensional, it is initialized + with an orthogonal matrix obtained from the QR decomposition of a matrix of + random numbers drawn from a normal distribution. + If the matrix has fewer rows than columns then the output will have orthogonal + rows. Otherwise, the output will have orthogonal columns. + + If the shape of the tensor to initialize is more than two-dimensional, + a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])` + is initialized, where `n` is the length of the shape vector. + The matrix is subsequently reshaped to give a tensor of the desired shape. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.Orthogonal() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.Orthogonal() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + gain: multiplicative factor to apply to the orthogonal matrix + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) + ([pdf](https://arxiv.org/pdf/1312.6120.pdf)) + """ + + def __init__(self, gain=1.0, seed=None): + self.gain = gain + self.seed = seed + self._random_generator = _RandomGenerator(seed) + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized to an orthogonal matrix. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point types are + supported. If not specified, `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`) + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs, support_partition=False) + dtype = _assert_float_dtype(_get_dtype(dtype)) + # Check the shape + if len(shape) < 2: + raise ValueError('The tensor to initialize must be ' + 'at least two-dimensional') + # Flatten the input shape with the last dimension remaining + # its original shape so it works for conv2d + num_rows = 1 + for dim in shape[:-1]: + num_rows *= dim + num_cols = shape[-1] + flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows)) + + # Generate a random matrix + a = self._random_generator.random_normal(flat_shape, dtype=dtype) + # Compute the qr factorization + q, r = gen_linalg_ops.qr(a, full_matrices=False) + # Make Q uniform + d = array_ops.tensor_diag_part(r) + q *= math_ops.sign(d) + if num_rows < num_cols: + q = array_ops.matrix_transpose(q) + return self.gain * array_ops.reshape(q, shape) + + def get_config(self): + return {'gain': self.gain, 'seed': self.seed} + + +class Identity(Initializer): + """Initializer that generates the identity matrix. + + Also available via the shortcut function `tf.keras.initializers.identity`. + + Only usable for generating 2D matrices. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.Identity() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.Identity() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + gain: Multiplicative factor to apply to the identity matrix. + """ + + def __init__(self, gain=1.0): + self.gain = gain + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized to a 2D identity matrix. + + Args: + shape: Shape of the tensor. It should have exactly rank 2. + dtype: Optional dtype of the tensor. Only floating point types are + supported. If not specified, `tf.keras.backend.floatx()` is used, + which default to `float32` unless you configured it otherwise + (via `tf.keras.backend.set_floatx(float_dtype)`) + **kwargs: Additional keyword arguments. + """ + _validate_kwargs(self.__class__.__name__, kwargs, support_partition=False) + dtype = _assert_float_dtype(_get_dtype(dtype)) + if len(shape) != 2: + raise ValueError( + 'Identity matrix initializer can only be used for 2D matrices.') + initializer = linalg_ops.eye(*shape, dtype=dtype) + return self.gain * initializer + + def get_config(self): + return {'gain': self.gain} + + +class GlorotUniform(VarianceScaling): + """The Glorot uniform initializer, also called Xavier uniform initializer. + + Also available via the shortcut function + `tf.keras.initializers.glorot_uniform`. + + Draws samples from a uniform distribution within `[-limit, limit]`, where + `limit = sqrt(6 / (fan_in + fan_out))` (`fan_in` is the number of input units + in the weight tensor and `fan_out` is the number of output units). + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.GlorotUniform() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.GlorotUniform() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) + ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) + """ + + def __init__(self, seed=None): + super(GlorotUniform, self).__init__( + scale=1.0, + mode='fan_avg', + distribution='uniform', + seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class GlorotNormal(VarianceScaling): + """The Glorot normal initializer, also called Xavier normal initializer. + + Also available via the shortcut function + `tf.keras.initializers.glorot_normal`. + + Draws samples from a truncated normal distribution centered on 0 with `stddev + = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number of input units in + the weight tensor and `fan_out` is the number of output units in the weight + tensor. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.GlorotNormal() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.GlorotNormal() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) + ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) + """ + + def __init__(self, seed=None): + super(GlorotNormal, self).__init__( + scale=1.0, + mode='fan_avg', + distribution='truncated_normal', + seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class LecunNormal(VarianceScaling): + """Lecun normal initializer. + + Also available via the shortcut function + `tf.keras.initializers.lecun_normal`. + + Initializers allow you to pre-specify an initialization strategy, encoded in + the Initializer object, without knowing the shape and dtype of the variable + being initialized. + + Draws samples from a truncated normal distribution centered on 0 with `stddev + = sqrt(1 / fan_in)` where `fan_in` is the number of input units in the weight + tensor. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.LecunNormal() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.LecunNormal() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. Used to seed the random generator. + + References: + - Self-Normalizing Neural Networks, + [Klambauer et al., 2017] + (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) + ([pdf] + (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) + - Efficient Backprop, + [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) + """ + + def __init__(self, seed=None): + super(LecunNormal, self).__init__( + scale=1., mode='fan_in', distribution='truncated_normal', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class LecunUniform(VarianceScaling): + """Lecun uniform initializer. + + Also available via the shortcut function + `tf.keras.initializers.lecun_uniform`. + + Draws samples from a uniform distribution within `[-limit, limit]`, + where `limit = sqrt(3 / fan_in)` (`fan_in` is the number of input units in the + weight tensor). + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.LecunUniform() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.LecunUniform() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + - Self-Normalizing Neural Networks, + [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long + ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) + - Efficient Backprop, + [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) + """ + + def __init__(self, seed=None): + super(LecunUniform, self).__init__( + scale=1., mode='fan_in', distribution='uniform', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class HeNormal(VarianceScaling): + """He normal initializer. + + Also available via the shortcut function + `tf.keras.initializers.he_normal`. + + It draws samples from a truncated normal distribution centered on 0 with + `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of input units in the + weight tensor. + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.HeNormal() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.HeNormal() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long + ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) + """ + + def __init__(self, seed=None): + super(HeNormal, self).__init__( + scale=2., mode='fan_in', distribution='truncated_normal', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +class HeUniform(VarianceScaling): + """He uniform variance scaling initializer. + + Also available via the shortcut function + `tf.keras.initializers.he_uniform`. + + Draws samples from a uniform distribution within `[-limit, limit]`, where + `limit = sqrt(6 / fan_in)` (`fan_in` is the number of input units in the + weight tensor). + + Examples: + + >>> # Standalone usage: + >>> initializer = tf.keras.initializers.HeUniform() + >>> values = initializer(shape=(2, 2)) + + >>> # Usage in a Keras layer: + >>> initializer = tf.keras.initializers.HeUniform() + >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer) + + Args: + seed: A Python integer. An initializer created with a given seed will + always produce the same random tensor for a given shape and dtype. + + References: + [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long + ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) + """ + + def __init__(self, seed=None): + super(HeUniform, self).__init__( + scale=2., mode='fan_in', distribution='uniform', seed=seed) + + def get_config(self): + return {'seed': self.seed} + + +def _get_dtype(dtype): + if dtype is None: + dtype = backend.floatx() + return dtypes.as_dtype(dtype) + + +def _assert_float_dtype(dtype): + """Validate and return floating point type based on `dtype`. + + `dtype` must be a floating point type. + + Args: + dtype: The data type to validate. + + Returns: + Validated type. + + Raises: + ValueError: if `dtype` is not a floating point type. + """ + dtype = dtypes.as_dtype(dtype) + if not dtype.is_floating: + raise ValueError('Expected floating point type, got %s.' % dtype) + return dtype + + +class _RandomGenerator(object): + """Random generator that selects appropriate random ops.""" + + def __init__(self, seed=None): + super(_RandomGenerator, self).__init__() + if seed is not None: + # Stateless random ops requires 2-int seed. + self.seed = [seed, 0] + else: + self.seed = None + + def random_normal(self, shape, mean=0.0, stddev=1, dtype=dtypes.float32): + """A deterministic random normal if seed is passed.""" + if self.seed: + op = stateless_random_ops.stateless_random_normal + else: + op = random_ops.random_normal + return op( + shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) + + def random_uniform(self, shape, minval, maxval, dtype): + """A deterministic random uniform if seed is passed.""" + if self.seed: + op = stateless_random_ops.stateless_random_uniform + else: + op = random_ops.random_uniform + return op( + shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed) + + def truncated_normal(self, shape, mean, stddev, dtype): + """A deterministic truncated normal if seed is passed.""" + if self.seed: + op = stateless_random_ops.stateless_truncated_normal + else: + op = random_ops.truncated_normal + return op( + shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) + + +def _compute_fans(shape): + """Computes the number of input and output units for a weight shape. + + Args: + shape: Integer shape tuple or TF tensor shape. + + Returns: + A tuple of integer scalars (fan_in, fan_out). + """ + if len(shape) < 1: # Just to avoid errors for constants. + fan_in = fan_out = 1 + elif len(shape) == 1: + fan_in = fan_out = shape[0] + elif len(shape) == 2: + fan_in = shape[0] + fan_out = shape[1] + else: + # Assuming convolution kernels (2D, 3D, or more). + # kernel shape: (..., input_depth, depth) + receptive_field_size = 1 + for dim in shape[:-2]: + receptive_field_size *= dim + fan_in = shape[-2] * receptive_field_size + fan_out = shape[-1] * receptive_field_size + return int(fan_in), int(fan_out) + + +def _validate_kwargs(cls_name, kwargs, support_partition=True): + for kwarg in kwargs: + if kwarg not in [_PARTITION_SHAPE, _PARTITION_OFFSET]: + raise TypeError('Unknown keyword arguments: %s' % kwarg) + elif not support_partition: + raise ValueError('%s initializer doesn\'t support partition-related ' + 'arguments' % cls_name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..889e9d181fb3afa452a612a288aea0a6f6dc0db5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/__init__.py @@ -0,0 +1,187 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras layers API.""" + +from tensorflow.python import tf2 + +# Generic layers. +# pylint: disable=g-bad-import-order +# pylint: disable=g-import-not-at-top +from tensorflow.python.keras.engine.input_layer import Input +from tensorflow.python.keras.engine.input_layer import InputLayer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.base_preprocessing_layer import PreprocessingLayer + +# Advanced activations. +from tensorflow.python.keras.layers.advanced_activations import LeakyReLU +from tensorflow.python.keras.layers.advanced_activations import PReLU +from tensorflow.python.keras.layers.advanced_activations import ELU +from tensorflow.python.keras.layers.advanced_activations import ReLU +from tensorflow.python.keras.layers.advanced_activations import ThresholdedReLU +from tensorflow.python.keras.layers.advanced_activations import Softmax + +# Convolution layers. +from tensorflow.python.keras.layers.convolutional import Conv1D +from tensorflow.python.keras.layers.convolutional import Conv2D +from tensorflow.python.keras.layers.convolutional import Conv3D +from tensorflow.python.keras.layers.convolutional import Conv1DTranspose +from tensorflow.python.keras.layers.convolutional import Conv2DTranspose +from tensorflow.python.keras.layers.convolutional import Conv3DTranspose +from tensorflow.python.keras.layers.convolutional import SeparableConv1D +from tensorflow.python.keras.layers.convolutional import SeparableConv2D + +# Convolution layer aliases. +from tensorflow.python.keras.layers.convolutional import Convolution1D +from tensorflow.python.keras.layers.convolutional import Convolution2D +from tensorflow.python.keras.layers.convolutional import Convolution3D +from tensorflow.python.keras.layers.convolutional import Convolution2DTranspose +from tensorflow.python.keras.layers.convolutional import Convolution3DTranspose +from tensorflow.python.keras.layers.convolutional import SeparableConvolution1D +from tensorflow.python.keras.layers.convolutional import SeparableConvolution2D +from tensorflow.python.keras.layers.convolutional import DepthwiseConv2D + +# Image processing layers. +from tensorflow.python.keras.layers.convolutional import UpSampling1D +from tensorflow.python.keras.layers.convolutional import UpSampling2D +from tensorflow.python.keras.layers.convolutional import UpSampling3D +from tensorflow.python.keras.layers.convolutional import ZeroPadding1D +from tensorflow.python.keras.layers.convolutional import ZeroPadding2D +from tensorflow.python.keras.layers.convolutional import ZeroPadding3D +from tensorflow.python.keras.layers.convolutional import Cropping1D +from tensorflow.python.keras.layers.convolutional import Cropping2D +from tensorflow.python.keras.layers.convolutional import Cropping3D + +# Core layers. +from tensorflow.python.keras.layers.core import Masking +from tensorflow.python.keras.layers.core import Dropout +from tensorflow.python.keras.layers.core import SpatialDropout1D +from tensorflow.python.keras.layers.core import SpatialDropout2D +from tensorflow.python.keras.layers.core import SpatialDropout3D +from tensorflow.python.keras.layers.core import Activation +from tensorflow.python.keras.layers.core import Reshape +from tensorflow.python.keras.layers.core import Permute +from tensorflow.python.keras.layers.core import Flatten +from tensorflow.python.keras.layers.core import RepeatVector +from tensorflow.python.keras.layers.core import Lambda +from tensorflow.python.keras.layers.core import Dense +from tensorflow.python.keras.layers.core import ActivityRegularization + +# Dense Attention layers. +from tensorflow.python.keras.layers.dense_attention import AdditiveAttention +from tensorflow.python.keras.layers.dense_attention import Attention + +# Embedding layers. +from tensorflow.python.keras.layers.embeddings import Embedding + +# Merge layers. +from tensorflow.python.keras.layers.merge import Add +from tensorflow.python.keras.layers.merge import Subtract +from tensorflow.python.keras.layers.merge import Multiply +from tensorflow.python.keras.layers.merge import Average +from tensorflow.python.keras.layers.merge import Maximum +from tensorflow.python.keras.layers.merge import Minimum +from tensorflow.python.keras.layers.merge import Concatenate +from tensorflow.python.keras.layers.merge import Dot +from tensorflow.python.keras.layers.merge import add +from tensorflow.python.keras.layers.merge import subtract +from tensorflow.python.keras.layers.merge import multiply +from tensorflow.python.keras.layers.merge import average +from tensorflow.python.keras.layers.merge import maximum +from tensorflow.python.keras.layers.merge import minimum +from tensorflow.python.keras.layers.merge import concatenate +from tensorflow.python.keras.layers.merge import dot + +# Pooling layers. +from tensorflow.python.keras.layers.pooling import MaxPooling1D +from tensorflow.python.keras.layers.pooling import MaxPooling2D +from tensorflow.python.keras.layers.pooling import MaxPooling3D +from tensorflow.python.keras.layers.pooling import AveragePooling1D +from tensorflow.python.keras.layers.pooling import AveragePooling2D +from tensorflow.python.keras.layers.pooling import AveragePooling3D +from tensorflow.python.keras.layers.pooling import GlobalAveragePooling1D +from tensorflow.python.keras.layers.pooling import GlobalAveragePooling2D +from tensorflow.python.keras.layers.pooling import GlobalAveragePooling3D +from tensorflow.python.keras.layers.pooling import GlobalMaxPooling1D +from tensorflow.python.keras.layers.pooling import GlobalMaxPooling2D +from tensorflow.python.keras.layers.pooling import GlobalMaxPooling3D + +# Pooling layer aliases. +from tensorflow.python.keras.layers.pooling import MaxPool1D +from tensorflow.python.keras.layers.pooling import MaxPool2D +from tensorflow.python.keras.layers.pooling import MaxPool3D +from tensorflow.python.keras.layers.pooling import AvgPool1D +from tensorflow.python.keras.layers.pooling import AvgPool2D +from tensorflow.python.keras.layers.pooling import AvgPool3D +from tensorflow.python.keras.layers.pooling import GlobalAvgPool1D +from tensorflow.python.keras.layers.pooling import GlobalAvgPool2D +from tensorflow.python.keras.layers.pooling import GlobalAvgPool3D +from tensorflow.python.keras.layers.pooling import GlobalMaxPool1D +from tensorflow.python.keras.layers.pooling import GlobalMaxPool2D +from tensorflow.python.keras.layers.pooling import GlobalMaxPool3D + +# Recurrent layers. +from tensorflow.python.keras.layers.recurrent import RNN +from tensorflow.python.keras.layers.recurrent import AbstractRNNCell +from tensorflow.python.keras.layers.recurrent import StackedRNNCells +from tensorflow.python.keras.layers.recurrent import SimpleRNNCell +from tensorflow.python.keras.layers.recurrent import PeepholeLSTMCell +from tensorflow.python.keras.layers.recurrent import SimpleRNN + +if tf2.enabled(): + from tensorflow.python.keras.layers.recurrent import GRU as GRUV1 + from tensorflow.python.keras.layers.recurrent import GRUCell as GRUCellV1 + from tensorflow.python.keras.layers.recurrent import LSTM as LSTMV1 + from tensorflow.python.keras.layers.recurrent import LSTMCell as LSTMCellV1 +else: + from tensorflow.python.keras.layers.recurrent import GRU + from tensorflow.python.keras.layers.recurrent import GRUCell + from tensorflow.python.keras.layers.recurrent import LSTM + from tensorflow.python.keras.layers.recurrent import LSTMCell + GRUV1 = GRU + GRUCellV1 = GRUCell + LSTMV1 = LSTM + LSTMCellV1 = LSTMCell + +# Convolutional-recurrent layers. +from tensorflow.python.keras.layers.convolutional_recurrent import ConvLSTM2D + +# # RNN Cell wrappers. +from tensorflow.python.keras.layers.rnn_cell_wrapper_v2 import DeviceWrapper +from tensorflow.python.keras.layers.rnn_cell_wrapper_v2 import DropoutWrapper +from tensorflow.python.keras.layers.rnn_cell_wrapper_v2 import ResidualWrapper + +# Serialization functions +from tensorflow.python.keras.layers import serialization +from tensorflow.python.keras.layers.serialization import deserialize +from tensorflow.python.keras.layers.serialization import serialize + + +class VersionAwareLayers(object): + """Utility to be used internally to access layers in a V1/V2-aware fashion. + + When using layers within the Keras codebase, under the constraint that + e.g. `layers.BatchNormalization` should be the `BatchNormalization` version + corresponding to the current runtime (TF1 or TF2), do not simply access + `layers.BatchNormalization` since it would ignore e.g. an early + `compat.v2.disable_v2_behavior()` call. Instead, use an instance + of `VersionAwareLayers` (which you can use just like the `layers` module). + """ + + def __getattr__(self, name): + serialization.populate_deserializable_objects() + if name in serialization.LOCAL.ALL_OBJECTS: + return serialization.LOCAL.ALL_OBJECTS[name] + return super(VersionAwareLayers, self).__getattr__(name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/advanced_activations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/advanced_activations.py new file mode 100644 index 0000000000000000000000000000000000000000..4adc3bed950888527b9417fe98e3b6a14651db1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/advanced_activations.py @@ -0,0 +1,442 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Layers that act as activation functions.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.framework import dtypes +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import math_ops + + +def get_globals(): + return globals() + + +class LeakyReLU(Layer): + """Leaky version of a Rectified Linear Unit. + + It allows a small gradient when the unit is not active: + + ``` + f(x) = alpha * x if x < 0 + f(x) = x if x >= 0 + ``` + + Usage: + + >>> layer = tf.keras.layers.LeakyReLU() + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [-0.9, -0.3, 0.0, 2.0] + >>> layer = tf.keras.layers.LeakyReLU(alpha=0.1) + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [-0.3, -0.1, 0.0, 2.0] + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the batch axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + alpha: Float >= 0. Negative slope coefficient. Default to 0.3. + + """ + + def __init__(self, alpha=0.3, **kwargs): + super(LeakyReLU, self).__init__(**kwargs) + if alpha is None: + raise ValueError('The alpha value of a Leaky ReLU layer ' + 'cannot be None, needs a float. ' + 'Got %s' % alpha) + self.supports_masking = True + self.alpha = backend.cast_to_floatx(alpha) + + def call(self, inputs): + return backend.relu(inputs, alpha=self.alpha) + + def get_config(self): + config = {'alpha': float(self.alpha)} + base_config = super(LeakyReLU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape + + +class PReLU(Layer): + """Parametric Rectified Linear Unit. + + It follows: + + ``` + f(x) = alpha * x for x < 0 + f(x) = x for x >= 0 + ``` + + where `alpha` is a learned array with the same shape as x. + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + alpha_initializer: Initializer function for the weights. + alpha_regularizer: Regularizer for the weights. + alpha_constraint: Constraint for the weights. + shared_axes: The axes along which to share learnable + parameters for the activation function. + For example, if the incoming feature maps + are from a 2D convolution + with output shape `(batch, height, width, channels)`, + and you wish to share parameters across space + so that each filter only has one set of parameters, + set `shared_axes=[1, 2]`. + """ + + def __init__(self, + alpha_initializer='zeros', + alpha_regularizer=None, + alpha_constraint=None, + shared_axes=None, + **kwargs): + super(PReLU, self).__init__(**kwargs) + self.supports_masking = True + self.alpha_initializer = initializers.get(alpha_initializer) + self.alpha_regularizer = regularizers.get(alpha_regularizer) + self.alpha_constraint = constraints.get(alpha_constraint) + if shared_axes is None: + self.shared_axes = None + elif not isinstance(shared_axes, (list, tuple)): + self.shared_axes = [shared_axes] + else: + self.shared_axes = list(shared_axes) + + @tf_utils.shape_type_conversion + def build(self, input_shape): + param_shape = list(input_shape[1:]) + if self.shared_axes is not None: + for i in self.shared_axes: + param_shape[i - 1] = 1 + self.alpha = self.add_weight( + shape=param_shape, + name='alpha', + initializer=self.alpha_initializer, + regularizer=self.alpha_regularizer, + constraint=self.alpha_constraint) + # Set input spec + axes = {} + if self.shared_axes: + for i in range(1, len(input_shape)): + if i not in self.shared_axes: + axes[i] = input_shape[i] + self.input_spec = InputSpec(ndim=len(input_shape), axes=axes) + self.built = True + + def call(self, inputs): + pos = backend.relu(inputs) + neg = -self.alpha * backend.relu(-inputs) + return pos + neg + + def get_config(self): + config = { + 'alpha_initializer': initializers.serialize(self.alpha_initializer), + 'alpha_regularizer': regularizers.serialize(self.alpha_regularizer), + 'alpha_constraint': constraints.serialize(self.alpha_constraint), + 'shared_axes': self.shared_axes + } + base_config = super(PReLU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape + + +class ELU(Layer): + """Exponential Linear Unit. + + It follows: + + ``` + f(x) = alpha * (exp(x) - 1.) for x < 0 + f(x) = x for x >= 0 + ``` + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + alpha: Scale for the negative factor. + """ + + def __init__(self, alpha=1.0, **kwargs): + super(ELU, self).__init__(**kwargs) + if alpha is None: + raise ValueError('Alpha of an ELU layer cannot be None, ' + 'requires a float. Got %s' % alpha) + self.supports_masking = True + self.alpha = backend.cast_to_floatx(alpha) + + def call(self, inputs): + return backend.elu(inputs, self.alpha) + + def get_config(self): + config = {'alpha': float(self.alpha)} + base_config = super(ELU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape + + +class ThresholdedReLU(Layer): + """Thresholded Rectified Linear Unit. + + It follows: + + ``` + f(x) = x for x > theta + f(x) = 0 otherwise` + ``` + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + theta: Float >= 0. Threshold location of activation. + """ + + def __init__(self, theta=1.0, **kwargs): + super(ThresholdedReLU, self).__init__(**kwargs) + if theta is None: + raise ValueError('Theta of a Thresholded ReLU layer cannot be ' + 'None, requires a float. Got %s' % theta) + if theta < 0: + raise ValueError('The theta value of a Thresholded ReLU layer ' + 'should be >=0, got %s' % theta) + self.supports_masking = True + self.theta = backend.cast_to_floatx(theta) + + def call(self, inputs): + theta = math_ops.cast(self.theta, inputs.dtype) + return inputs * math_ops.cast(math_ops.greater(inputs, theta), inputs.dtype) + + def get_config(self): + config = {'theta': float(self.theta)} + base_config = super(ThresholdedReLU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape + + +def _large_compatible_negative(tensor_type): + """Large negative number as Tensor. + + This function is necessary because the standard value for epsilon + in this module (-1e9) cannot be represented using tf.float16 + + Args: + tensor_type: a dtype to determine the type. + + Returns: + a large negative number. + """ + if tensor_type == dtypes.float16: + return dtypes.float16.min + return -1e9 + + +class Softmax(Layer): + """Softmax activation function. + + Example without mask: + + >>> inp = np.asarray([1., 2., 1.]) + >>> layer = tf.keras.layers.Softmax() + >>> layer(inp).numpy() + array([0.21194157, 0.5761169 , 0.21194157], dtype=float32) + >>> mask = np.asarray([True, False, True], dtype=bool) + >>> layer(inp, mask).numpy() + array([0.5, 0. , 0.5], dtype=float32) + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + axis: Integer, or list of Integers, axis along which the softmax + normalization is applied. + Call arguments: + inputs: The inputs, or logits to the softmax layer. + mask: A boolean mask of the same shape as `inputs`. Defaults to `None`. The + mask specifies 1 to keep and 0 to mask. + + Returns: + softmaxed output with the same shape as `inputs`. + """ + + def __init__(self, axis=-1, **kwargs): + super(Softmax, self).__init__(**kwargs) + self.supports_masking = True + self.axis = axis + + def call(self, inputs, mask=None): + if mask is not None: + # Since mask is 1.0 for positions we want to keep and 0.0 for + # masked positions, this operation will create a tensor which is 0.0 for + # positions we want to attend and -1e.9 for masked positions. + adder = (1.0 - math_ops.cast(mask, inputs.dtype)) * ( + _large_compatible_negative(inputs.dtype)) + + # Since we are adding it to the raw scores before the softmax, this is + # effectively the same as removing these entirely. + inputs += adder + if isinstance(self.axis, (tuple, list)): + if len(self.axis) > 1: + return math_ops.exp(inputs - math_ops.reduce_logsumexp( + inputs, axis=self.axis, keepdims=True)) + else: + return backend.softmax(inputs, axis=self.axis[0]) + return backend.softmax(inputs, axis=self.axis) + + def get_config(self): + config = {'axis': self.axis} + base_config = super(Softmax, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape + + +class ReLU(Layer): + """Rectified Linear Unit activation function. + + With default values, it returns element-wise `max(x, 0)`. + + Otherwise, it follows: + + ``` + f(x) = max_value if x >= max_value + f(x) = x if threshold <= x < max_value + f(x) = negative_slope * (x - threshold) otherwise + ``` + + Usage: + + >>> layer = tf.keras.layers.ReLU() + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [0.0, 0.0, 0.0, 2.0] + >>> layer = tf.keras.layers.ReLU(max_value=1.0) + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [0.0, 0.0, 0.0, 1.0] + >>> layer = tf.keras.layers.ReLU(negative_slope=1.0) + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [-3.0, -1.0, 0.0, 2.0] + >>> layer = tf.keras.layers.ReLU(threshold=1.5) + >>> output = layer([-3.0, -1.0, 1.0, 2.0]) + >>> list(output.numpy()) + [0.0, 0.0, 0.0, 2.0] + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the batch axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as the input. + + Args: + max_value: Float >= 0. Maximum activation value. Default to None, which + means unlimited. + negative_slope: Float >= 0. Negative slope coefficient. Default to 0. + threshold: Float >= 0. Threshold value for thresholded activation. Default + to 0. + """ + + def __init__(self, max_value=None, negative_slope=0, threshold=0, **kwargs): + super(ReLU, self).__init__(**kwargs) + if max_value is not None and max_value < 0.: + raise ValueError('max_value of a ReLU layer cannot be a negative ' + 'value. Got: %s' % max_value) + if negative_slope is None or negative_slope < 0.: + raise ValueError('negative_slope of a ReLU layer cannot be a negative ' + 'value. Got: %s' % negative_slope) + if threshold is None or threshold < 0.: + raise ValueError('threshold of a ReLU layer cannot be a negative ' + 'value. Got: %s' % threshold) + + self.supports_masking = True + if max_value is not None: + max_value = backend.cast_to_floatx(max_value) + self.max_value = max_value + self.negative_slope = backend.cast_to_floatx(negative_slope) + self.threshold = backend.cast_to_floatx(threshold) + + def call(self, inputs): + # alpha is used for leaky relu slope in activations instead of + # negative_slope. + return backend.relu(inputs, + alpha=self.negative_slope, + max_value=self.max_value, + threshold=self.threshold) + + def get_config(self): + config = { + 'max_value': self.max_value, + 'negative_slope': self.negative_slope, + 'threshold': self.threshold + } + base_config = super(ReLU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + return input_shape diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional.py new file mode 100644 index 0000000000000000000000000000000000000000..b2eb7089b6d095655a378f569b0ac10135c296df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional.py @@ -0,0 +1,3409 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras convolution layers and image transformation layers.""" + +import functools + +from tensorflow.python.eager import context +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +# imports for backwards namespace compatibility +# pylint: disable=unused-import +from tensorflow.python.keras.layers.pooling import AveragePooling1D +from tensorflow.python.keras.layers.pooling import AveragePooling2D +from tensorflow.python.keras.layers.pooling import AveragePooling3D +from tensorflow.python.keras.layers.pooling import MaxPooling1D +from tensorflow.python.keras.layers.pooling import MaxPooling2D +from tensorflow.python.keras.layers.pooling import MaxPooling3D +# pylint: enable=unused-import +from tensorflow.python.keras.utils import conv_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import nn +from tensorflow.python.ops import nn_ops +# pylint: disable=g-classes-have-attributes + + +class Conv(Layer): + """Abstract N-D convolution layer (private, used as implementation base). + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Note: layer attributes cannot be modified after the layer has been called + once (except the `trainable` attribute). + + Args: + rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). Could be "None", eg in the case of + depth wise convolution. + kernel_size: An integer or tuple/list of n integers, specifying the + length of the convolution window. + strides: An integer or tuple/list of n integers, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"`, `"same"`, or `"causal"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros + evenly to the left/right or up/down of the input such that output has the + same height/width dimension as the input. `"causal"` results in causal + (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, ..., channels)` while `channels_first` corresponds to + inputs with shape `(batch_size, channels, ...)`. + Note: `channels_first` is only available on GPUs. + dilation_rate: An integer or tuple/list of n integers, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + groups: A positive integer specifying the number of groups in which the + input is split along the channel axis. Each group is convolved + separately with `filters / groups` filters. The output is the + concatenation of all the `groups` results along the channel axis. + Input channels and `filters` must both be divisible by `groups`. + activation: Activation function to use. + If you don't specify anything, no activation is applied. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. If None, the + default initializer (glorot_uniform) will be used. + bias_initializer: An initializer for the bias vector. If None, the default + initializer (zeros) will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + """ + + def __init__(self, + rank, + filters, + kernel_size, + strides=1, + padding='valid', + data_format=None, + dilation_rate=1, + groups=1, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + conv_op=None, + **kwargs): + super(Conv, self).__init__( + trainable=trainable, + name=name, + activity_regularizer=regularizers.get(activity_regularizer), + **kwargs) + self.rank = rank + + if isinstance(filters, float): + filters = int(filters) + if filters is not None and filters < 0: + raise ValueError(f'Received a negative value for `filters`.' + f'Was expecting a positive value, got {filters}.') + self.filters = filters + self.groups = groups or 1 + self.kernel_size = conv_utils.normalize_tuple( + kernel_size, rank, 'kernel_size') + self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') + self.padding = conv_utils.normalize_padding(padding) + self.data_format = conv_utils.normalize_data_format(data_format) + self.dilation_rate = conv_utils.normalize_tuple( + dilation_rate, rank, 'dilation_rate') + + self.activation = activations.get(activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.bias_initializer = initializers.get(bias_initializer) + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + self.kernel_constraint = constraints.get(kernel_constraint) + self.bias_constraint = constraints.get(bias_constraint) + self.input_spec = InputSpec(min_ndim=self.rank + 2) + + self._validate_init() + self._is_causal = self.padding == 'causal' + self._channels_first = self.data_format == 'channels_first' + self._tf_data_format = conv_utils.convert_data_format( + self.data_format, self.rank + 2) + + def _validate_init(self): + if self.filters is not None and self.filters % self.groups != 0: + raise ValueError( + 'The number of filters must be evenly divisible by the number of ' + 'groups. Received: groups={}, filters={}'.format( + self.groups, self.filters)) + + if not all(self.kernel_size): + raise ValueError('The argument `kernel_size` cannot contain 0(s). ' + 'Received: %s' % (self.kernel_size,)) + + if not all(self.strides): + raise ValueError('The argument `strides` cannot contains 0(s). ' + 'Received: %s' % (self.strides,)) + + if (self.padding == 'causal' and not isinstance(self, + (Conv1D, SeparableConv1D))): + raise ValueError('Causal padding is only supported for `Conv1D`' + 'and `SeparableConv1D`.') + + def build(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + input_channel = self._get_input_channel(input_shape) + if input_channel % self.groups != 0: + raise ValueError( + 'The number of input channels must be evenly divisible by the number ' + 'of groups. Received groups={}, but the input has {} channels ' + '(full input shape is {}).'.format(self.groups, input_channel, + input_shape)) + kernel_shape = self.kernel_size + (input_channel // self.groups, + self.filters) + + self.kernel = self.add_weight( + name='kernel', + shape=kernel_shape, + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + trainable=True, + dtype=self.dtype) + if self.use_bias: + self.bias = self.add_weight( + name='bias', + shape=(self.filters,), + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + trainable=True, + dtype=self.dtype) + else: + self.bias = None + channel_axis = self._get_channel_axis() + self.input_spec = InputSpec(min_ndim=self.rank + 2, + axes={channel_axis: input_channel}) + + # Convert Keras formats to TF native formats. + if self.padding == 'causal': + tf_padding = 'VALID' # Causal padding handled in `call`. + elif isinstance(self.padding, str): + tf_padding = self.padding.upper() + else: + tf_padding = self.padding + tf_dilations = list(self.dilation_rate) + tf_strides = list(self.strides) + + tf_op_name = self.__class__.__name__ + if tf_op_name == 'Conv1D': + tf_op_name = 'conv1d' # Backwards compat. + + self._convolution_op = functools.partial( + nn_ops.convolution_v2, + strides=tf_strides, + padding=tf_padding, + dilations=tf_dilations, + data_format=self._tf_data_format, + name=tf_op_name) + self.built = True + + def call(self, inputs): + input_shape = inputs.shape + + if self._is_causal: # Apply causal padding to inputs for Conv1D. + inputs = array_ops.pad(inputs, self._compute_causal_padding(inputs)) + + outputs = self._convolution_op(inputs, self.kernel) + + if self.use_bias: + output_rank = outputs.shape.rank + if self.rank == 1 and self._channels_first: + # nn.bias_add does not accept a 1D input tensor. + bias = array_ops.reshape(self.bias, (1, self.filters, 1)) + outputs += bias + else: + # Handle multiple batch dimensions. + if output_rank is not None and output_rank > 2 + self.rank: + + def _apply_fn(o): + return nn.bias_add(o, self.bias, data_format=self._tf_data_format) + + outputs = conv_utils.squeeze_batch_dims( + outputs, _apply_fn, inner_rank=self.rank + 1) + else: + outputs = nn.bias_add( + outputs, self.bias, data_format=self._tf_data_format) + + if not context.executing_eagerly(): + # Infer the static output shape: + out_shape = self.compute_output_shape(input_shape) + outputs.set_shape(out_shape) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + def _spatial_output_shape(self, spatial_input_shape): + return [ + conv_utils.conv_output_length( + length, + self.kernel_size[i], + padding=self.padding, + stride=self.strides[i], + dilation=self.dilation_rate[i]) + for i, length in enumerate(spatial_input_shape) + ] + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + batch_rank = len(input_shape) - self.rank - 1 + if self.data_format == 'channels_last': + return tensor_shape.TensorShape( + input_shape[:batch_rank] + + self._spatial_output_shape(input_shape[batch_rank:-1]) + + [self.filters]) + else: + return tensor_shape.TensorShape( + input_shape[:batch_rank] + [self.filters] + + self._spatial_output_shape(input_shape[batch_rank + 1:])) + + def _recreate_conv_op(self, inputs): # pylint: disable=unused-argument + return False + + def get_config(self): + config = { + 'filters': + self.filters, + 'kernel_size': + self.kernel_size, + 'strides': + self.strides, + 'padding': + self.padding, + 'data_format': + self.data_format, + 'dilation_rate': + self.dilation_rate, + 'groups': + self.groups, + 'activation': + activations.serialize(self.activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint) + } + base_config = super(Conv, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + def _compute_causal_padding(self, inputs): + """Calculates padding for 'causal' option for 1-d conv layers.""" + left_pad = self.dilation_rate[0] * (self.kernel_size[0] - 1) + if getattr(inputs.shape, 'ndims', None) is None: + batch_rank = 1 + else: + batch_rank = len(inputs.shape) - 2 + if self.data_format == 'channels_last': + causal_padding = [[0, 0]] * batch_rank + [[left_pad, 0], [0, 0]] + else: + causal_padding = [[0, 0]] * batch_rank + [[0, 0], [left_pad, 0]] + return causal_padding + + def _get_channel_axis(self): + if self.data_format == 'channels_first': + return -1 - self.rank + else: + return -1 + + def _get_input_channel(self, input_shape): + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined. Found `None`.') + return int(input_shape[channel_axis]) + + def _get_padding_op(self): + if self.padding == 'causal': + op_padding = 'valid' + else: + op_padding = self.padding + if not isinstance(op_padding, (list, tuple)): + op_padding = op_padding.upper() + return op_padding + + +class Conv1D(Conv): + """1D convolution layer (e.g. temporal convolution). + + This layer creates a convolution kernel that is convolved + with the layer input over a single spatial (or temporal) dimension + to produce a tensor of outputs. + If `use_bias` is True, a bias vector is created and added to the outputs. + Finally, if `activation` is not `None`, + it is applied to the outputs as well. + + When using this layer as the first layer in a model, + provide an `input_shape` argument + (tuple of integers or `None`, e.g. + `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors, + or `(None, 128)` for variable-length sequences of 128-dimensional vectors. + + Examples: + + >>> # The inputs are 128-length vectors with 10 timesteps, and the batch size + >>> # is 4. + >>> input_shape = (4, 10, 128) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv1D( + ... 32, 3, activation='relu',input_shape=input_shape[1:])(x) + >>> print(y.shape) + (4, 8, 32) + + >>> # With extended batch shape [4, 7] (e.g. weather data where batch + >>> # dimensions correspond to spatial location and the third dimension + >>> # corresponds to time.) + >>> input_shape = (4, 7, 10, 128) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv1D( + ... 32, 3, activation='relu', input_shape=input_shape[2:])(x) + >>> print(y.shape) + (4, 7, 8, 32) + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of a single integer, + specifying the length of the 1D convolution window. + strides: An integer or tuple/list of a single integer, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"`, `"same"` or `"causal"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + `"causal"` results in causal (dilated) convolutions, e.g. `output[t]` + does not depend on `input[t+1:]`. Useful when modeling temporal data + where the model should not violate the temporal order. + See [WaveNet: A Generative Model for Raw Audio, section + 2.1](https://arxiv.org/abs/1609.03499). + data_format: A string, + one of `channels_last` (default) or `channels_first`. + dilation_rate: an integer or tuple/list of a single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + groups: A positive integer specifying the number of groups in which the + input is split along the channel axis. Each group is convolved + separately with `filters / groups` filters. The output is the + concatenation of all the `groups` results along the channel axis. + Input channels and `filters` must both be divisible by `groups`. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix ( + see `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector ( + see `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation") ( + see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 3+D tensor with shape: `batch_shape + (steps, input_dim)` + + Output shape: + 3+D tensor with shape: `batch_shape + (new_steps, filters)` + `steps` value might have changed due to padding or strides. + + Returns: + A tensor of rank 3 representing + `activation(conv1d(inputs, kernel) + bias)`. + + Raises: + ValueError: when both `strides > 1` and `dilation_rate > 1`. + """ + + def __init__(self, + filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + groups=1, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv1D, self).__init__( + rank=1, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + groups=groups, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + +class Conv2D(Conv): + """2D convolution layer (e.g. spatial convolution over images). + + This layer creates a convolution kernel that is convolved + with the layer input to produce a tensor of + outputs. If `use_bias` is True, + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + When using this layer as the first layer in a model, + provide the keyword argument `input_shape` + (tuple of integers or `None`, does not include the sample axis), + e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures + in `data_format="channels_last"`. You can use `None` when + a dimension has variable size. + + Examples: + + >>> # The inputs are 28x28 RGB images with `channels_last` and the batch + >>> # size is 4. + >>> input_shape = (4, 28, 28, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv2D( + ... 2, 3, activation='relu', input_shape=input_shape[1:])(x) + >>> print(y.shape) + (4, 26, 26, 2) + + >>> # With `dilation_rate` as 2. + >>> input_shape = (4, 28, 28, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv2D( + ... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape[1:])(x) + >>> print(y.shape) + (4, 24, 24, 2) + + >>> # With `padding` as "same". + >>> input_shape = (4, 28, 28, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv2D( + ... 2, 3, activation='relu', padding="same", input_shape=input_shape[1:])(x) + >>> print(y.shape) + (4, 28, 28, 2) + + >>> # With extended batch shape [4, 7]: + >>> input_shape = (4, 7, 28, 28, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv2D( + ... 2, 3, activation='relu', input_shape=input_shape[2:])(x) + >>> print(y.shape) + (4, 7, 26, 26, 2) + + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number of + output filters in the convolution). + kernel_size: An integer or tuple/list of 2 integers, specifying the height + and width of the 2D convolution window. Can be a single integer to specify + the same value for all spatial dimensions. + strides: An integer or tuple/list of 2 integers, specifying the strides of + the convolution along the height and width. Can be a single integer to + specify the same value for all spatial dimensions. Specifying any stride + value != 1 is incompatible with specifying any `dilation_rate` value != 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. `channels_last` corresponds + to inputs with shape `(batch_size, height, width, channels)` while + `channels_first` corresponds to inputs with shape `(batch_size, channels, + height, width)`. It defaults to the `image_data_format` value found in + your Keras config file at `~/.keras/keras.json`. If you never set it, then + it will be `channels_last`. + dilation_rate: an integer or tuple/list of 2 integers, specifying the + dilation rate to use for dilated convolution. Can be a single integer to + specify the same value for all spatial dimensions. Currently, specifying + any `dilation_rate` value != 1 is incompatible with specifying any stride + value != 1. + groups: A positive integer specifying the number of groups in which the + input is split along the channel axis. Each group is convolved separately + with `filters / groups` filters. The output is the concatenation of all + the `groups` results along the channel axis. Input channels and `filters` + must both be divisible by `groups`. + activation: Activation function to use. If you don't specify anything, no + activation is applied (see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix (see + `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector (see + `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to the `kernel` weights + matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector (see + `keras.regularizers`). + activity_regularizer: Regularizer function applied to the output of the + layer (its "activation") (see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix (see + `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector (see + `keras.constraints`). + Input shape: + 4+D tensor with shape: `batch_shape + (channels, rows, cols)` if + `data_format='channels_first'` + or 4+D tensor with shape: `batch_shape + (rows, cols, channels)` if + `data_format='channels_last'`. + Output shape: + 4+D tensor with shape: `batch_shape + (filters, new_rows, new_cols)` if + `data_format='channels_first'` or 4+D tensor with shape: `batch_shape + + (new_rows, new_cols, filters)` if `data_format='channels_last'`. `rows` + and `cols` values might have changed due to padding. + + Returns: + A tensor of rank 4+ representing + `activation(conv2d(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is `"causal"`. + ValueError: when both `strides > 1` and `dilation_rate > 1`. + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1), + groups=1, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv2D, self).__init__( + rank=2, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + groups=groups, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + +class Conv3D(Conv): + """3D convolution layer (e.g. spatial convolution over volumes). + + This layer creates a convolution kernel that is convolved + with the layer input to produce a tensor of + outputs. If `use_bias` is True, + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + When using this layer as the first layer in a model, + provide the keyword argument `input_shape` + (tuple of integers or `None`, does not include the sample axis), + e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes + with a single channel, + in `data_format="channels_last"`. + + Examples: + + >>> # The inputs are 28x28x28 volumes with a single channel, and the + >>> # batch size is 4 + >>> input_shape =(4, 28, 28, 28, 1) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv3D( + ... 2, 3, activation='relu', input_shape=input_shape[1:])(x) + >>> print(y.shape) + (4, 26, 26, 26, 2) + + >>> # With extended batch shape [4, 7], e.g. a batch of 4 videos of 3D frames, + >>> # with 7 frames per video. + >>> input_shape = (4, 7, 28, 28, 28, 1) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Conv3D( + ... 2, 3, activation='relu', input_shape=input_shape[2:])(x) + >>> print(y.shape) + (4, 7, 26, 26, 26, 2) + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number of + output filters in the convolution). + kernel_size: An integer or tuple/list of 3 integers, specifying the depth, + height and width of the 3D convolution window. Can be a single integer to + specify the same value for all spatial dimensions. + strides: An integer or tuple/list of 3 integers, specifying the strides of + the convolution along each spatial dimension. Can be a single integer to + specify the same value for all spatial dimensions. Specifying any stride + value != 1 is incompatible with specifying any `dilation_rate` value != 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. `channels_last` corresponds + to inputs with shape `batch_shape + (spatial_dim1, spatial_dim2, + spatial_dim3, channels)` while `channels_first` corresponds to inputs with + shape `batch_shape + (channels, spatial_dim1, spatial_dim2, + spatial_dim3)`. It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. If you never set it, then it + will be "channels_last". + dilation_rate: an integer or tuple/list of 3 integers, specifying the + dilation rate to use for dilated convolution. Can be a single integer to + specify the same value for all spatial dimensions. Currently, specifying + any `dilation_rate` value != 1 is incompatible with specifying any stride + value != 1. + groups: A positive integer specifying the number of groups in which the + input is split along the channel axis. Each group is convolved separately + with `filters / groups` filters. The output is the concatenation of all + the `groups` results along the channel axis. Input channels and `filters` + must both be divisible by `groups`. + activation: Activation function to use. If you don't specify anything, no + activation is applied (see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix (see + `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector (see + `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to the `kernel` weights + matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector (see + `keras.regularizers`). + activity_regularizer: Regularizer function applied to the output of the + layer (its "activation") (see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix (see + `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector (see + `keras.constraints`). + Input shape: + 5+D tensor with shape: `batch_shape + (channels, conv_dim1, conv_dim2, + conv_dim3)` if data_format='channels_first' + or 5+D tensor with shape: `batch_shape + (conv_dim1, conv_dim2, conv_dim3, + channels)` if data_format='channels_last'. + Output shape: + 5+D tensor with shape: `batch_shape + (filters, new_conv_dim1, + new_conv_dim2, new_conv_dim3)` if data_format='channels_first' + or 5+D tensor with shape: `batch_shape + (new_conv_dim1, new_conv_dim2, + new_conv_dim3, filters)` if data_format='channels_last'. `new_conv_dim1`, + `new_conv_dim2` and `new_conv_dim3` values might have changed due to + padding. + + Returns: + A tensor of rank 5+ representing + `activation(conv3d(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides > 1` and `dilation_rate > 1`. + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1, 1), + groups=1, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv3D, self).__init__( + rank=3, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + groups=groups, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + +class Conv1DTranspose(Conv1D): + """Transposed convolution layer (sometimes called Deconvolution). + + The need for transposed convolutions generally arises + from the desire to use a transformation going in the opposite direction + of a normal convolution, i.e., from something that has the shape of the + output of some convolution to something that has the shape of its input + while maintaining a connectivity pattern that is compatible with + said convolution. + + When using this layer as the first layer in a model, + provide the keyword argument `input_shape` + (tuple of integers or `None`, does not include the sample axis), + e.g. `input_shape=(128, 3)` for data with 128 time steps and 3 channels. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer length of the 1D convolution window. + strides: An integer specifying the stride of the convolution along the + time dimension. Specifying a stride value != 1 is incompatible with + specifying a `dilation_rate` value != 1. Defaults to 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + output_padding: An integer specifying the amount of padding along + the time dimension of the output tensor. + The amount of output padding must be lower than the stride. + If set to `None` (default), the output shape is inferred. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch_size, channels, length)`. + dilation_rate: an integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying a `dilation_rate` value != 1 is + incompatible with specifying a stride value != 1. + Also dilation rate larger than 1 is not currently supported. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix ( + see `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector ( + see `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation") (see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 3D tensor with shape: + `(batch_size, steps, channels)` + + Output shape: + 3D tensor with shape: + `(batch_size, new_steps, filters)` + If `output_padding` is specified: + ``` + new_timesteps = ((timesteps - 1) * strides + kernel_size - + 2 * padding + output_padding) + ``` + + Returns: + A tensor of rank 3 representing + `activation(conv1dtranspose(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + + References: + - [A guide to convolution arithmetic for deep learning]( + https://arxiv.org/abs/1603.07285v1) + - [Deconvolutional Networks]( + https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) + """ + + def __init__(self, + filters, + kernel_size, + strides=1, + padding='valid', + output_padding=None, + data_format=None, + dilation_rate=1, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv1DTranspose, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + self.output_padding = output_padding + if self.output_padding is not None: + self.output_padding = conv_utils.normalize_tuple( + self.output_padding, 1, 'output_padding') + for stride, out_pad in zip(self.strides, self.output_padding): + if out_pad >= stride: + raise ValueError('Stride ' + str(self.strides) + ' must be ' + 'greater than output padding ' + + str(self.output_padding)) + + def build(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + if len(input_shape) != 3: + raise ValueError('Inputs should have rank 3. Received input shape: ' + + str(input_shape)) + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined. Found `None`.') + input_dim = int(input_shape[channel_axis]) + self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim}) + kernel_shape = self.kernel_size + (self.filters, input_dim) + + self.kernel = self.add_weight( + name='kernel', + shape=kernel_shape, + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + trainable=True, + dtype=self.dtype) + if self.use_bias: + self.bias = self.add_weight( + name='bias', + shape=(self.filters,), + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + trainable=True, + dtype=self.dtype) + else: + self.bias = None + self.built = True + + def call(self, inputs): + inputs_shape = array_ops.shape(inputs) + batch_size = inputs_shape[0] + if self.data_format == 'channels_first': + t_axis = 2 + else: + t_axis = 1 + + length = inputs_shape[t_axis] + if self.output_padding is None: + output_padding = None + else: + output_padding = self.output_padding[0] + + # Infer the dynamic output shape: + out_length = conv_utils.deconv_output_length( + length, self.kernel_size[0], padding=self.padding, + output_padding=output_padding, stride=self.strides[0], + dilation=self.dilation_rate[0]) + if self.data_format == 'channels_first': + output_shape = (batch_size, self.filters, out_length) + else: + output_shape = (batch_size, out_length, self.filters) + data_format = conv_utils.convert_data_format(self.data_format, ndim=3) + + output_shape_tensor = array_ops_stack.stack(output_shape) + outputs = nn_ops.conv1d_transpose( + inputs, + self.kernel, + output_shape_tensor, + strides=self.strides, + padding=self.padding.upper(), + data_format=data_format, + dilations=self.dilation_rate) + + if not context.executing_eagerly(): + # Infer the static output shape: + out_shape = self.compute_output_shape(inputs.shape) + outputs.set_shape(out_shape) + + if self.use_bias: + outputs = nn.bias_add( + outputs, + self.bias, + data_format=data_format) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + output_shape = list(input_shape) + if self.data_format == 'channels_first': + c_axis, t_axis = 1, 2 + else: + c_axis, t_axis = 2, 1 + + if self.output_padding is None: + output_padding = None + else: + output_padding = self.output_padding[0] + output_shape[c_axis] = self.filters + output_shape[t_axis] = conv_utils.deconv_output_length( + output_shape[t_axis], + self.kernel_size[0], + padding=self.padding, + output_padding=output_padding, + stride=self.strides[0], + dilation=self.dilation_rate[0]) + return tensor_shape.TensorShape(output_shape) + + def get_config(self): + config = super(Conv1DTranspose, self).get_config() + config['output_padding'] = self.output_padding + return config + + +class Conv2DTranspose(Conv2D): + """Transposed convolution layer (sometimes called Deconvolution). + + The need for transposed convolutions generally arises + from the desire to use a transformation going in the opposite direction + of a normal convolution, i.e., from something that has the shape of the + output of some convolution to something that has the shape of its input + while maintaining a connectivity pattern that is compatible with + said convolution. + + When using this layer as the first layer in a model, + provide the keyword argument `input_shape` + (tuple of integers or `None`, does not include the sample axis), + e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures + in `data_format="channels_last"`. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + output_padding: An integer or tuple/list of 2 integers, + specifying the amount of padding along the height and width + of the output tensor. + Can be a single integer to specify the same value for all + spatial dimensions. + The amount of output padding along a given dimension must be + lower than the stride along that same dimension. + If set to `None` (default), the output shape is inferred. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + dilation_rate: an integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix ( + see `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector ( + see `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation") (see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 4D tensor with shape: + `(batch_size, channels, rows, cols)` if data_format='channels_first' + or 4D tensor with shape: + `(batch_size, rows, cols, channels)` if data_format='channels_last'. + + Output shape: + 4D tensor with shape: + `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first' + or 4D tensor with shape: + `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. + `rows` and `cols` values might have changed due to padding. + If `output_padding` is specified: + ``` + new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + + output_padding[0]) + new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + + output_padding[1]) + ``` + + Returns: + A tensor of rank 4 representing + `activation(conv2dtranspose(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + + References: + - [A guide to convolution arithmetic for deep + learning](https://arxiv.org/abs/1603.07285v1) + - [Deconvolutional + Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + output_padding=None, + data_format=None, + dilation_rate=(1, 1), + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv2DTranspose, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + self.output_padding = output_padding + if self.output_padding is not None: + self.output_padding = conv_utils.normalize_tuple( + self.output_padding, 2, 'output_padding') + for stride, out_pad in zip(self.strides, self.output_padding): + if out_pad >= stride: + raise ValueError('Stride ' + str(self.strides) + ' must be ' + 'greater than output padding ' + + str(self.output_padding)) + + def build(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + if len(input_shape) != 4: + raise ValueError('Inputs should have rank 4. Received input ' + 'shape: ' + str(input_shape)) + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined. Found `None`.') + input_dim = int(input_shape[channel_axis]) + self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) + kernel_shape = self.kernel_size + (self.filters, input_dim) + + self.kernel = self.add_weight( + name='kernel', + shape=kernel_shape, + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + trainable=True, + dtype=self.dtype) + if self.use_bias: + self.bias = self.add_weight( + name='bias', + shape=(self.filters,), + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + trainable=True, + dtype=self.dtype) + else: + self.bias = None + self.built = True + + def call(self, inputs): + inputs_shape = array_ops.shape(inputs) + batch_size = inputs_shape[0] + if self.data_format == 'channels_first': + h_axis, w_axis = 2, 3 + else: + h_axis, w_axis = 1, 2 + + # Use the constant height and weight when possible. + # TODO(scottzhu): Extract this into a utility function that can be applied + # to all convolutional layers, which currently lost the static shape + # information due to tf.shape(). + height, width = None, None + if inputs.shape.rank is not None: + dims = inputs.shape.as_list() + height = dims[h_axis] + width = dims[w_axis] + height = height if height is not None else inputs_shape[h_axis] + width = width if width is not None else inputs_shape[w_axis] + + kernel_h, kernel_w = self.kernel_size + stride_h, stride_w = self.strides + + if self.output_padding is None: + out_pad_h = out_pad_w = None + else: + out_pad_h, out_pad_w = self.output_padding + + # Infer the dynamic output shape: + out_height = conv_utils.deconv_output_length(height, + kernel_h, + padding=self.padding, + output_padding=out_pad_h, + stride=stride_h, + dilation=self.dilation_rate[0]) + out_width = conv_utils.deconv_output_length(width, + kernel_w, + padding=self.padding, + output_padding=out_pad_w, + stride=stride_w, + dilation=self.dilation_rate[1]) + if self.data_format == 'channels_first': + output_shape = (batch_size, self.filters, out_height, out_width) + else: + output_shape = (batch_size, out_height, out_width, self.filters) + + output_shape_tensor = array_ops_stack.stack(output_shape) + outputs = backend.conv2d_transpose( + inputs, + self.kernel, + output_shape_tensor, + strides=self.strides, + padding=self.padding, + data_format=self.data_format, + dilation_rate=self.dilation_rate) + + if not context.executing_eagerly(): + # Infer the static output shape: + out_shape = self.compute_output_shape(inputs.shape) + outputs.set_shape(out_shape) + + if self.use_bias: + outputs = nn.bias_add( + outputs, + self.bias, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + output_shape = list(input_shape) + if self.data_format == 'channels_first': + c_axis, h_axis, w_axis = 1, 2, 3 + else: + c_axis, h_axis, w_axis = 3, 1, 2 + + kernel_h, kernel_w = self.kernel_size + stride_h, stride_w = self.strides + + if self.output_padding is None: + out_pad_h = out_pad_w = None + else: + out_pad_h, out_pad_w = self.output_padding + + output_shape[c_axis] = self.filters + output_shape[h_axis] = conv_utils.deconv_output_length( + output_shape[h_axis], + kernel_h, + padding=self.padding, + output_padding=out_pad_h, + stride=stride_h, + dilation=self.dilation_rate[0]) + output_shape[w_axis] = conv_utils.deconv_output_length( + output_shape[w_axis], + kernel_w, + padding=self.padding, + output_padding=out_pad_w, + stride=stride_w, + dilation=self.dilation_rate[1]) + return tensor_shape.TensorShape(output_shape) + + def get_config(self): + config = super(Conv2DTranspose, self).get_config() + config['output_padding'] = self.output_padding + return config + + +class Conv3DTranspose(Conv3D): + """Transposed convolution layer (sometimes called Deconvolution). + + The need for transposed convolutions generally arises + from the desire to use a transformation going in the opposite direction + of a normal convolution, i.e., from something that has the shape of the + output of some convolution to something that has the shape of its input + while maintaining a connectivity pattern that is compatible with + said convolution. + + When using this layer as the first layer in a model, + provide the keyword argument `input_shape` + (tuple of integers or `None`, does not include the sample axis), + e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels + if `data_format="channels_last"`. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the convolution along the depth, height + and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + output_padding: An integer or tuple/list of 3 integers, + specifying the amount of padding along the depth, height, and + width. + Can be a single integer to specify the same value for all + spatial dimensions. + The amount of output padding along a given dimension must be + lower than the stride along that same dimension. + If set to `None` (default), the output shape is inferred. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, depth, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + dilation_rate: an integer or tuple/list of 3 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix ( + see `keras.initializers`). Defaults to 'glorot_uniform'. + bias_initializer: Initializer for the bias vector ( + see `keras.initializers`). Defaults to 'zeros'. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix ( + see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation") ( + see `keras.regularizers`). + kernel_constraint: Constraint function applied to the kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 5D tensor with shape: + `(batch_size, channels, depth, rows, cols)` if data_format='channels_first' + or 5D tensor with shape: + `(batch_size, depth, rows, cols, channels)` if data_format='channels_last'. + + Output shape: + 5D tensor with shape: + `(batch_size, filters, new_depth, new_rows, new_cols)` if + data_format='channels_first' + or 5D tensor with shape: + `(batch_size, new_depth, new_rows, new_cols, filters)` if + data_format='channels_last'. + `depth` and `rows` and `cols` values might have changed due to padding. + If `output_padding` is specified:: + ``` + new_depth = ((depth - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + + output_padding[0]) + new_rows = ((rows - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + + output_padding[1]) + new_cols = ((cols - 1) * strides[2] + kernel_size[2] - 2 * padding[2] + + output_padding[2]) + ``` + + Returns: + A tensor of rank 5 representing + `activation(conv3dtranspose(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + + References: + - [A guide to convolution arithmetic for deep + learning](https://arxiv.org/abs/1603.07285v1) + - [Deconvolutional + Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + output_padding=None, + data_format=None, + dilation_rate=(1, 1, 1), + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Conv3DTranspose, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activations.get(activation), + use_bias=use_bias, + kernel_initializer=initializers.get(kernel_initializer), + bias_initializer=initializers.get(bias_initializer), + kernel_regularizer=regularizers.get(kernel_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + kernel_constraint=constraints.get(kernel_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + self.output_padding = output_padding + if self.output_padding is not None: + self.output_padding = conv_utils.normalize_tuple( + self.output_padding, 3, 'output_padding') + for stride, out_pad in zip(self.strides, self.output_padding): + if out_pad >= stride: + raise ValueError('Stride ' + str(self.strides) + ' must be ' + 'greater than output padding ' + + str(self.output_padding)) + + def build(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + if len(input_shape) != 5: + raise ValueError('Inputs should have rank 5, received input shape:', + str(input_shape)) + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined, found None: ' + str(input_shape)) + input_dim = int(input_shape[channel_axis]) + kernel_shape = self.kernel_size + (self.filters, input_dim) + self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) + + self.kernel = self.add_weight( + 'kernel', + shape=kernel_shape, + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + trainable=True, + dtype=self.dtype) + if self.use_bias: + self.bias = self.add_weight( + 'bias', + shape=(self.filters,), + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + trainable=True, + dtype=self.dtype) + else: + self.bias = None + self.built = True + + def call(self, inputs): + inputs_shape = array_ops.shape(inputs) + batch_size = inputs_shape[0] + if self.data_format == 'channels_first': + d_axis, h_axis, w_axis = 2, 3, 4 + else: + d_axis, h_axis, w_axis = 1, 2, 3 + + depth = inputs_shape[d_axis] + height = inputs_shape[h_axis] + width = inputs_shape[w_axis] + + kernel_d, kernel_h, kernel_w = self.kernel_size + stride_d, stride_h, stride_w = self.strides + + if self.output_padding is None: + out_pad_d = out_pad_h = out_pad_w = None + else: + out_pad_d, out_pad_h, out_pad_w = self.output_padding + + # Infer the dynamic output shape: + out_depth = conv_utils.deconv_output_length(depth, + kernel_d, + padding=self.padding, + output_padding=out_pad_d, + stride=stride_d) + out_height = conv_utils.deconv_output_length(height, + kernel_h, + padding=self.padding, + output_padding=out_pad_h, + stride=stride_h) + out_width = conv_utils.deconv_output_length(width, + kernel_w, + padding=self.padding, + output_padding=out_pad_w, + stride=stride_w) + if self.data_format == 'channels_first': + output_shape = (batch_size, self.filters, out_depth, out_height, + out_width) + strides = (1, 1, stride_d, stride_h, stride_w) + else: + output_shape = (batch_size, out_depth, out_height, out_width, + self.filters) + strides = (1, stride_d, stride_h, stride_w, 1) + + output_shape_tensor = array_ops_stack.stack(output_shape) + outputs = nn.conv3d_transpose( + inputs, + self.kernel, + output_shape_tensor, + strides, + data_format=conv_utils.convert_data_format(self.data_format, ndim=5), + padding=self.padding.upper()) + + if not context.executing_eagerly(): + # Infer the static output shape: + out_shape = self.compute_output_shape(inputs.shape) + outputs.set_shape(out_shape) + + if self.use_bias: + outputs = nn.bias_add( + outputs, + self.bias, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + output_shape = list(input_shape) + if self.data_format == 'channels_first': + c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4 + else: + c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3 + + kernel_d, kernel_h, kernel_w = self.kernel_size + stride_d, stride_h, stride_w = self.strides + + if self.output_padding is None: + out_pad_d = out_pad_h = out_pad_w = None + else: + out_pad_d, out_pad_h, out_pad_w = self.output_padding + + output_shape[c_axis] = self.filters + output_shape[d_axis] = conv_utils.deconv_output_length( + output_shape[d_axis], + kernel_d, + padding=self.padding, + output_padding=out_pad_d, + stride=stride_d) + output_shape[h_axis] = conv_utils.deconv_output_length( + output_shape[h_axis], + kernel_h, + padding=self.padding, + output_padding=out_pad_h, + stride=stride_h) + output_shape[w_axis] = conv_utils.deconv_output_length( + output_shape[w_axis], + kernel_w, + padding=self.padding, + output_padding=out_pad_w, + stride=stride_w) + return tensor_shape.TensorShape(output_shape) + + def get_config(self): + config = super(Conv3DTranspose, self).get_config() + config.pop('dilation_rate') + config['output_padding'] = self.output_padding + return config + + +class SeparableConv(Conv): + """Abstract base layer for separable nD convolution. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, ..., channels)` while `channels_first` corresponds to + inputs with shape `(batch_size, channels, ...)`. + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer ( + 'glorot_uniform') will be used. + pointwise_initializer: An initializer for the pointwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer + ('glorot_uniform') will be used. + bias_initializer: An initializer for the bias vector. If None, the default + initializer ('zeros') will be used (see `keras.initializers`). + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel. + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer`. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` the weights of this layer will be marked as + trainable (and listed in `layer.trainable_weights`). + """ + + def __init__(self, + rank, + filters, + kernel_size, + strides=1, + padding='valid', + data_format=None, + dilation_rate=1, + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer='glorot_uniform', + pointwise_initializer='glorot_uniform', + bias_initializer='zeros', + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(SeparableConv, self).__init__( + rank=rank, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activations.get(activation), + use_bias=use_bias, + bias_initializer=initializers.get(bias_initializer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + self.depth_multiplier = depth_multiplier + self.depthwise_initializer = initializers.get(depthwise_initializer) + self.pointwise_initializer = initializers.get(pointwise_initializer) + self.depthwise_regularizer = regularizers.get(depthwise_regularizer) + self.pointwise_regularizer = regularizers.get(pointwise_regularizer) + self.depthwise_constraint = constraints.get(depthwise_constraint) + self.pointwise_constraint = constraints.get(pointwise_constraint) + + def build(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined. Found `None`.') + input_dim = int(input_shape[channel_axis]) + self.input_spec = InputSpec(ndim=self.rank + 2, + axes={channel_axis: input_dim}) + depthwise_kernel_shape = self.kernel_size + (input_dim, + self.depth_multiplier) + pointwise_kernel_shape = ( + 1,) * self.rank + (self.depth_multiplier * input_dim, self.filters) + + self.depthwise_kernel = self.add_weight( + name='depthwise_kernel', + shape=depthwise_kernel_shape, + initializer=self.depthwise_initializer, + regularizer=self.depthwise_regularizer, + constraint=self.depthwise_constraint, + trainable=True, + dtype=self.dtype) + self.pointwise_kernel = self.add_weight( + name='pointwise_kernel', + shape=pointwise_kernel_shape, + initializer=self.pointwise_initializer, + regularizer=self.pointwise_regularizer, + constraint=self.pointwise_constraint, + trainable=True, + dtype=self.dtype) + if self.use_bias: + self.bias = self.add_weight( + name='bias', + shape=(self.filters,), + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + trainable=True, + dtype=self.dtype) + else: + self.bias = None + self.built = True + + def call(self, inputs): + raise NotImplementedError + + def get_config(self): + config = { + 'filters': + self.filters, + 'kernel_size': + self.kernel_size, + 'strides': + self.strides, + 'padding': + self.padding, + 'data_format': + self.data_format, + 'depth_multiplier': + self.depth_multiplier, + 'dilation_rate': + self.dilation_rate, + 'activation': + activations.serialize(self.activation), + 'use_bias': + self.use_bias, + 'depthwise_initializer': + initializers.serialize(self.depthwise_initializer), + 'pointwise_initializer': + initializers.serialize(self.pointwise_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'depthwise_regularizer': + regularizers.serialize(self.depthwise_regularizer), + 'pointwise_regularizer': + regularizers.serialize(self.pointwise_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'depthwise_constraint': + constraints.serialize(self.depthwise_constraint), + 'pointwise_constraint': + constraints.serialize(self.pointwise_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint) + } + base_config = super(SeparableConv, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SeparableConv1D(SeparableConv): + """Depthwise separable 1D convolution. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A single integer specifying the spatial + dimensions of the filters. + strides: A single integer specifying the strides + of the convolution. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"`, `"same"`, or `"causal"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. `"causal"` results in causal + (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch_size, channels, length)`. + dilation_rate: A single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer ( + 'glorot_uniform') will be used. + pointwise_initializer: An initializer for the pointwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer + ('glorot_uniform') will be used. + bias_initializer: An initializer for the bias vector. If None, the default + initializer ('zeros') will be used (see `keras.initializers`). + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel (see `keras.regularizers`). + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel (see `keras.regularizers`). + bias_regularizer: Optional regularizer for the bias vector ( + see `keras.regularizers`). + activity_regularizer: Optional regularizer function for the output ( + see `keras.regularizers`). + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training ( + see `keras.constraints`). + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer` ( + see `keras.constraints`). + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer` ( + see `keras.constraints`). + trainable: Boolean, if `True` the weights of this layer will be marked as + trainable (and listed in `layer.trainable_weights`). + + Input shape: + 3D tensor with shape: + `(batch_size, channels, steps)` if data_format='channels_first' + or 5D tensor with shape: + `(batch_size, steps, channels)` if data_format='channels_last'. + + Output shape: + 3D tensor with shape: + `(batch_size, filters, new_steps)` if data_format='channels_first' + or 3D tensor with shape: + `(batch_size, new_steps, filters)` if data_format='channels_last'. + `new_steps` value might have changed due to padding or strides. + + Returns: + A tensor of rank 3 representing + `activation(separableconv1d(inputs, kernel) + bias)`. + + Raises: + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + """ + + def __init__(self, + filters, + kernel_size, + strides=1, + padding='valid', + data_format=None, + dilation_rate=1, + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer='glorot_uniform', + pointwise_initializer='glorot_uniform', + bias_initializer='zeros', + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + **kwargs): + super(SeparableConv1D, self).__init__( + rank=1, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activations.get(activation), + use_bias=use_bias, + depthwise_initializer=initializers.get(depthwise_initializer), + pointwise_initializer=initializers.get(pointwise_initializer), + bias_initializer=initializers.get(bias_initializer), + depthwise_regularizer=regularizers.get(depthwise_regularizer), + pointwise_regularizer=regularizers.get(pointwise_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + depthwise_constraint=constraints.get(depthwise_constraint), + pointwise_constraint=constraints.get(pointwise_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + def call(self, inputs): + if self.padding == 'causal': + inputs = array_ops.pad(inputs, self._compute_causal_padding(inputs)) + if self.data_format == 'channels_last': + strides = (1,) + self.strides * 2 + (1,) + spatial_start_dim = 1 + else: + strides = (1, 1) + self.strides * 2 + spatial_start_dim = 2 + + # Explicitly broadcast inputs and kernels to 4D. + # TODO(fchollet): refactor when a native separable_conv1d op is available. + inputs = array_ops.expand_dims(inputs, spatial_start_dim) + depthwise_kernel = array_ops.expand_dims(self.depthwise_kernel, 0) + pointwise_kernel = array_ops.expand_dims(self.pointwise_kernel, 0) + dilation_rate = (1,) + self.dilation_rate + + if self.padding == 'causal': + op_padding = 'valid' + else: + op_padding = self.padding + outputs = nn.separable_conv2d( + inputs, + depthwise_kernel, + pointwise_kernel, + strides=strides, + padding=op_padding.upper(), + rate=dilation_rate, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + if self.use_bias: + outputs = nn.bias_add( + outputs, + self.bias, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + outputs = array_ops.squeeze(outputs, [spatial_start_dim]) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + +class SeparableConv2D(SeparableConv): + """Depthwise separable 2D convolution. + + Separable convolutions consist of first performing + a depthwise spatial convolution + (which acts on each input channel separately) + followed by a pointwise convolution which mixes the resulting + output channels. The `depth_multiplier` argument controls how many + output channels are generated per input channel in the depthwise step. + + Intuitively, separable convolutions can be understood as + a way to factorize a convolution kernel into two smaller kernels, + or as an extreme version of an Inception block. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. Current implementation only supports equal + length strides in the row and column dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + depth_multiplier: The number of depthwise convolution output channels + for each input channel. + The total number of depthwise convolution output + channels will be equal to `filters_in * depth_multiplier`. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + depthwise_initializer: An initializer for the depthwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer ( + 'glorot_uniform') will be used. + pointwise_initializer: An initializer for the pointwise convolution kernel ( + see `keras.initializers`). If None, then the default initializer + ('glorot_uniform') will be used. + bias_initializer: An initializer for the bias vector. If None, the default + initializer ('zeros') will be used (see `keras.initializers`). + depthwise_regularizer: Regularizer function applied to + the depthwise kernel matrix (see `keras.regularizers`). + pointwise_regularizer: Regularizer function applied to + the pointwise kernel matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation") ( + see `keras.regularizers`). + depthwise_constraint: Constraint function applied to + the depthwise kernel matrix ( + see `keras.constraints`). + pointwise_constraint: Constraint function applied to + the pointwise kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 4D tensor with shape: + `(batch_size, channels, rows, cols)` if data_format='channels_first' + or 4D tensor with shape: + `(batch_size, rows, cols, channels)` if data_format='channels_last'. + + Output shape: + 4D tensor with shape: + `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first' + or 4D tensor with shape: + `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. + `rows` and `cols` values might have changed due to padding. + + Returns: + A tensor of rank 4 representing + `activation(separableconv2d(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1), + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer='glorot_uniform', + pointwise_initializer='glorot_uniform', + bias_initializer='zeros', + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + **kwargs): + super(SeparableConv2D, self).__init__( + rank=2, + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activations.get(activation), + use_bias=use_bias, + depthwise_initializer=initializers.get(depthwise_initializer), + pointwise_initializer=initializers.get(pointwise_initializer), + bias_initializer=initializers.get(bias_initializer), + depthwise_regularizer=regularizers.get(depthwise_regularizer), + pointwise_regularizer=regularizers.get(pointwise_regularizer), + bias_regularizer=regularizers.get(bias_regularizer), + activity_regularizer=regularizers.get(activity_regularizer), + depthwise_constraint=constraints.get(depthwise_constraint), + pointwise_constraint=constraints.get(pointwise_constraint), + bias_constraint=constraints.get(bias_constraint), + **kwargs) + + def call(self, inputs): + # Apply the actual ops. + if self.data_format == 'channels_last': + strides = (1,) + self.strides + (1,) + else: + strides = (1, 1) + self.strides + outputs = nn.separable_conv2d( + inputs, + self.depthwise_kernel, + self.pointwise_kernel, + strides=strides, + padding=self.padding.upper(), + rate=self.dilation_rate, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + if self.use_bias: + outputs = nn.bias_add( + outputs, + self.bias, + data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) + + if self.activation is not None: + return self.activation(outputs) + return outputs + + +class DepthwiseConv2D(Conv2D): + """Depthwise 2D convolution. + + Depthwise convolution is a type of convolution in which a single convolutional + filter is apply to each input channel (i.e. in a depthwise way). + You can understand depthwise convolution as being + the first step in a depthwise separable convolution. + + It is implemented via the following steps: + + - Split the input into individual channels. + - Convolve each input with the layer's kernel (called a depthwise kernel). + - Stack the convolved outputs together (along the channels axis). + + Unlike a regular 2D convolution, depthwise convolution does not mix + information across different input channels. + + The `depth_multiplier` argument controls how many + output channels are generated per input channel in the depthwise step. + + Args: + kernel_size: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: one of `'valid'` or `'same'` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding with zeros evenly + to the left/right or up/down of the input such that output has the same + height/width dimension as the input. + depth_multiplier: The number of depthwise convolution output channels + for each input channel. + The total number of depthwise convolution output + channels will be equal to `filters_in * depth_multiplier`. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be 'channels_last'. + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + activation: Activation function to use. + If you don't specify anything, no activation is applied ( + see `keras.activations`). + use_bias: Boolean, whether the layer uses a bias vector. + depthwise_initializer: Initializer for the depthwise kernel matrix ( + see `keras.initializers`). If None, the default initializer ( + 'glorot_uniform') will be used. + bias_initializer: Initializer for the bias vector ( + see `keras.initializers`). If None, the default initializer ( + 'zeros') will bs used. + depthwise_regularizer: Regularizer function applied to + the depthwise kernel matrix (see `keras.regularizers`). + bias_regularizer: Regularizer function applied to the bias vector ( + see `keras.regularizers`). + activity_regularizer: Regularizer function applied to + the output of the layer (its 'activation') ( + see `keras.regularizers`). + depthwise_constraint: Constraint function applied to + the depthwise kernel matrix ( + see `keras.constraints`). + bias_constraint: Constraint function applied to the bias vector ( + see `keras.constraints`). + + Input shape: + 4D tensor with shape: + `[batch_size, channels, rows, cols]` if data_format='channels_first' + or 4D tensor with shape: + `[batch_size, rows, cols, channels]` if data_format='channels_last'. + + Output shape: + 4D tensor with shape: + `[batch_size, channels * depth_multiplier, new_rows, new_cols]` if + data_format='channels_first' or 4D tensor with shape: + `[batch_size, new_rows, new_cols, channels * depth_multiplier]` if + data_format='channels_last'. `rows` and `cols` values might have + changed due to padding. + + Returns: + A tensor of rank 4 representing + `activation(depthwiseconv2d(inputs, kernel) + bias)`. + + Raises: + ValueError: if `padding` is "causal". + ValueError: when both `strides` > 1 and `dilation_rate` > 1. + """ + + def __init__(self, + kernel_size, + strides=(1, 1), + padding='valid', + depth_multiplier=1, + data_format=None, + dilation_rate=(1, 1), + activation=None, + use_bias=True, + depthwise_initializer='glorot_uniform', + bias_initializer='zeros', + depthwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + bias_constraint=None, + **kwargs): + super(DepthwiseConv2D, self).__init__( + filters=None, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + bias_constraint=bias_constraint, + **kwargs) + self.depth_multiplier = depth_multiplier + self.depthwise_initializer = initializers.get(depthwise_initializer) + self.depthwise_regularizer = regularizers.get(depthwise_regularizer) + self.depthwise_constraint = constraints.get(depthwise_constraint) + self.bias_initializer = initializers.get(bias_initializer) + + def build(self, input_shape): + if len(input_shape) < 4: + raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' + 'Received input shape:', str(input_shape)) + input_shape = tensor_shape.TensorShape(input_shape) + channel_axis = self._get_channel_axis() + if input_shape.dims[channel_axis].value is None: + raise ValueError('The channel dimension of the inputs to ' + '`DepthwiseConv2D` ' + 'should be defined. Found `None`.') + input_dim = int(input_shape[channel_axis]) + depthwise_kernel_shape = (self.kernel_size[0], + self.kernel_size[1], + input_dim, + self.depth_multiplier) + + self.depthwise_kernel = self.add_weight( + shape=depthwise_kernel_shape, + initializer=self.depthwise_initializer, + name='depthwise_kernel', + regularizer=self.depthwise_regularizer, + constraint=self.depthwise_constraint) + + if self.use_bias: + self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), + initializer=self.bias_initializer, + name='bias', + regularizer=self.bias_regularizer, + constraint=self.bias_constraint) + else: + self.bias = None + # Set input spec. + self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) + self.built = True + + def call(self, inputs): + outputs = backend.depthwise_conv2d( + inputs, + self.depthwise_kernel, + strides=self.strides, + padding=self.padding, + dilation_rate=self.dilation_rate, + data_format=self.data_format) + + if self.use_bias: + outputs = backend.bias_add( + outputs, + self.bias, + data_format=self.data_format) + + if self.activation is not None: + return self.activation(outputs) + + return outputs + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if self.data_format == 'channels_first': + rows = input_shape[2] + cols = input_shape[3] + out_filters = input_shape[1] * self.depth_multiplier + elif self.data_format == 'channels_last': + rows = input_shape[1] + cols = input_shape[2] + out_filters = input_shape[3] * self.depth_multiplier + + rows = conv_utils.conv_output_length(rows, self.kernel_size[0], + self.padding, + self.strides[0], + self.dilation_rate[0]) + cols = conv_utils.conv_output_length(cols, self.kernel_size[1], + self.padding, + self.strides[1], + self.dilation_rate[1]) + if self.data_format == 'channels_first': + return (input_shape[0], out_filters, rows, cols) + elif self.data_format == 'channels_last': + return (input_shape[0], rows, cols, out_filters) + + def get_config(self): + config = super(DepthwiseConv2D, self).get_config() + config.pop('filters') + config.pop('kernel_initializer') + config.pop('kernel_regularizer') + config.pop('kernel_constraint') + config['depth_multiplier'] = self.depth_multiplier + config['depthwise_initializer'] = initializers.serialize( + self.depthwise_initializer) + config['depthwise_regularizer'] = regularizers.serialize( + self.depthwise_regularizer) + config['depthwise_constraint'] = constraints.serialize( + self.depthwise_constraint) + return config + + +class UpSampling1D(Layer): + """Upsampling layer for 1D inputs. + + Repeats each temporal step `size` times along the time axis. + + Examples: + + >>> input_shape = (2, 2, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> print(x) + [[[ 0 1 2] + [ 3 4 5]] + [[ 6 7 8] + [ 9 10 11]]] + >>> y = tf.keras.layers.UpSampling1D(size=2)(x) + >>> print(y) + tf.Tensor( + [[[ 0 1 2] + [ 0 1 2] + [ 3 4 5] + [ 3 4 5]] + [[ 6 7 8] + [ 6 7 8] + [ 9 10 11] + [ 9 10 11]]], shape=(2, 4, 3), dtype=int64) + + Args: + size: Integer. Upsampling factor. + + Input shape: + 3D tensor with shape: `(batch_size, steps, features)`. + + Output shape: + 3D tensor with shape: `(batch_size, upsampled_steps, features)`. + """ + + def __init__(self, size=2, **kwargs): + super(UpSampling1D, self).__init__(**kwargs) + self.size = int(size) + self.input_spec = InputSpec(ndim=3) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + size = self.size * input_shape[1] if input_shape[1] is not None else None + return tensor_shape.TensorShape([input_shape[0], size, input_shape[2]]) + + def call(self, inputs): + output = backend.repeat_elements(inputs, self.size, axis=1) + return output + + def get_config(self): + config = {'size': self.size} + base_config = super(UpSampling1D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class UpSampling2D(Layer): + """Upsampling layer for 2D inputs. + + Repeats the rows and columns of the data + by `size[0]` and `size[1]` respectively. + + Examples: + + >>> input_shape = (2, 2, 1, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> print(x) + [[[[ 0 1 2]] + [[ 3 4 5]]] + [[[ 6 7 8]] + [[ 9 10 11]]]] + >>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x) + >>> print(y) + tf.Tensor( + [[[[ 0 1 2] + [ 0 1 2]] + [[ 3 4 5] + [ 3 4 5]]] + [[[ 6 7 8] + [ 6 7 8]] + [[ 9 10 11] + [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64) + + Args: + size: Int, or tuple of 2 integers. + The upsampling factors for rows and columns. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + interpolation: A string, one of `nearest` or `bilinear`. + + Input shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, rows, cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, rows, cols)` + + Output shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, upsampled_rows, upsampled_cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, upsampled_rows, upsampled_cols)` + """ + + def __init__(self, + size=(2, 2), + data_format=None, + interpolation='nearest', + **kwargs): + super(UpSampling2D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + self.size = conv_utils.normalize_tuple(size, 2, 'size') + if interpolation not in {'nearest', 'bilinear'}: + raise ValueError('`interpolation` argument should be one of `"nearest"` ' + 'or `"bilinear"`.') + self.interpolation = interpolation + self.input_spec = InputSpec(ndim=4) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + height = self.size[0] * input_shape[ + 2] if input_shape[2] is not None else None + width = self.size[1] * input_shape[ + 3] if input_shape[3] is not None else None + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], height, width]) + else: + height = self.size[0] * input_shape[ + 1] if input_shape[1] is not None else None + width = self.size[1] * input_shape[ + 2] if input_shape[2] is not None else None + return tensor_shape.TensorShape( + [input_shape[0], height, width, input_shape[3]]) + + def call(self, inputs): + return backend.resize_images( + inputs, self.size[0], self.size[1], self.data_format, + interpolation=self.interpolation) + + def get_config(self): + config = { + 'size': self.size, + 'data_format': self.data_format, + 'interpolation': self.interpolation + } + base_config = super(UpSampling2D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class UpSampling3D(Layer): + """Upsampling layer for 3D inputs. + + Repeats the 1st, 2nd and 3rd dimensions + of the data by `size[0]`, `size[1]` and `size[2]` respectively. + + Examples: + + >>> input_shape = (2, 1, 2, 1, 3) + >>> x = tf.constant(1, shape=input_shape) + >>> y = tf.keras.layers.UpSampling3D(size=2)(x) + >>> print(y.shape) + (2, 2, 4, 2, 3) + + Args: + size: Int, or tuple of 3 integers. + The upsampling factors for dim1, dim2 and dim3. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, dim1, dim2, dim3, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, dim1, dim2, dim3)` + + Output shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` + """ + + def __init__(self, size=(2, 2, 2), data_format=None, **kwargs): + self.data_format = conv_utils.normalize_data_format(data_format) + self.size = conv_utils.normalize_tuple(size, 3, 'size') + self.input_spec = InputSpec(ndim=5) + super(UpSampling3D, self).__init__(**kwargs) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + dim1 = self.size[0] * input_shape[ + 2] if input_shape[2] is not None else None + dim2 = self.size[1] * input_shape[ + 3] if input_shape[3] is not None else None + dim3 = self.size[2] * input_shape[ + 4] if input_shape[4] is not None else None + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], dim1, dim2, dim3]) + else: + dim1 = self.size[0] * input_shape[ + 1] if input_shape[1] is not None else None + dim2 = self.size[1] * input_shape[ + 2] if input_shape[2] is not None else None + dim3 = self.size[2] * input_shape[ + 3] if input_shape[3] is not None else None + return tensor_shape.TensorShape( + [input_shape[0], dim1, dim2, dim3, input_shape[4]]) + + def call(self, inputs): + return backend.resize_volumes( + inputs, self.size[0], self.size[1], self.size[2], self.data_format) + + def get_config(self): + config = {'size': self.size, 'data_format': self.data_format} + base_config = super(UpSampling3D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class ZeroPadding1D(Layer): + """Zero-padding layer for 1D input (e.g. temporal sequence). + + Examples: + + >>> input_shape = (2, 2, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> print(x) + [[[ 0 1 2] + [ 3 4 5]] + [[ 6 7 8] + [ 9 10 11]]] + >>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x) + >>> print(y) + tf.Tensor( + [[[ 0 0 0] + [ 0 0 0] + [ 0 1 2] + [ 3 4 5] + [ 0 0 0] + [ 0 0 0]] + [[ 0 0 0] + [ 0 0 0] + [ 6 7 8] + [ 9 10 11] + [ 0 0 0] + [ 0 0 0]]], shape=(2, 6, 3), dtype=int64) + + Args: + padding: Int, or tuple of int (length 2), or dictionary. + - If int: + How many zeros to add at the beginning and end of + the padding dimension (axis 1). + - If tuple of int (length 2): + How many zeros to add at the beginning and the end of + the padding dimension (`(left_pad, right_pad)`). + + Input shape: + 3D tensor with shape `(batch_size, axis_to_pad, features)` + + Output shape: + 3D tensor with shape `(batch_size, padded_axis, features)` + """ + + def __init__(self, padding=1, **kwargs): + super(ZeroPadding1D, self).__init__(**kwargs) + self.padding = conv_utils.normalize_tuple(padding, 2, 'padding') + self.input_spec = InputSpec(ndim=3) + + def compute_output_shape(self, input_shape): + if input_shape[1] is not None: + length = input_shape[1] + self.padding[0] + self.padding[1] + else: + length = None + return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) + + def call(self, inputs): + return backend.temporal_padding(inputs, padding=self.padding) + + def get_config(self): + config = {'padding': self.padding} + base_config = super(ZeroPadding1D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class ZeroPadding2D(Layer): + """Zero-padding layer for 2D input (e.g. picture). + + This layer can add rows and columns of zeros + at the top, bottom, left and right side of an image tensor. + + Examples: + + >>> input_shape = (1, 1, 2, 2) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> print(x) + [[[[0 1] + [2 3]]]] + >>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x) + >>> print(y) + tf.Tensor( + [[[[0 0] + [0 0] + [0 0] + [0 0]] + [[0 0] + [0 1] + [2 3] + [0 0]] + [[0 0] + [0 0] + [0 0] + [0 0]]]], shape=(1, 3, 4, 2), dtype=int64) + + Args: + padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. + - If int: the same symmetric padding + is applied to height and width. + - If tuple of 2 ints: + interpreted as two different + symmetric padding values for height and width: + `(symmetric_height_pad, symmetric_width_pad)`. + - If tuple of 2 tuples of 2 ints: + interpreted as + `((top_pad, bottom_pad), (left_pad, right_pad))` + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, rows, cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, rows, cols)` + + Output shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, padded_rows, padded_cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, padded_rows, padded_cols)` + """ + + def __init__(self, padding=(1, 1), data_format=None, **kwargs): + super(ZeroPadding2D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + if isinstance(padding, int): + self.padding = ((padding, padding), (padding, padding)) + elif hasattr(padding, '__len__'): + if len(padding) != 2: + raise ValueError('`padding` should have two elements. ' + 'Found: ' + str(padding)) + height_padding = conv_utils.normalize_tuple(padding[0], 2, + '1st entry of padding') + width_padding = conv_utils.normalize_tuple(padding[1], 2, + '2nd entry of padding') + self.padding = (height_padding, width_padding) + else: + raise ValueError('`padding` should be either an int, ' + 'a tuple of 2 ints ' + '(symmetric_height_pad, symmetric_width_pad), ' + 'or a tuple of 2 tuples of 2 ints ' + '((top_pad, bottom_pad), (left_pad, right_pad)). ' + 'Found: ' + str(padding)) + self.input_spec = InputSpec(ndim=4) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + if input_shape[2] is not None: + rows = input_shape[2] + self.padding[0][0] + self.padding[0][1] + else: + rows = None + if input_shape[3] is not None: + cols = input_shape[3] + self.padding[1][0] + self.padding[1][1] + else: + cols = None + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], rows, cols]) + elif self.data_format == 'channels_last': + if input_shape[1] is not None: + rows = input_shape[1] + self.padding[0][0] + self.padding[0][1] + else: + rows = None + if input_shape[2] is not None: + cols = input_shape[2] + self.padding[1][0] + self.padding[1][1] + else: + cols = None + return tensor_shape.TensorShape( + [input_shape[0], rows, cols, input_shape[3]]) + + def call(self, inputs): + return backend.spatial_2d_padding( + inputs, padding=self.padding, data_format=self.data_format) + + def get_config(self): + config = {'padding': self.padding, 'data_format': self.data_format} + base_config = super(ZeroPadding2D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class ZeroPadding3D(Layer): + """Zero-padding layer for 3D data (spatial or spatio-temporal). + + Examples: + + >>> input_shape = (1, 1, 2, 2, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x) + >>> print(y.shape) + (1, 5, 6, 6, 3) + + Args: + padding: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. + - If int: the same symmetric padding + is applied to height and width. + - If tuple of 3 ints: + interpreted as two different + symmetric padding values for height and width: + `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`. + - If tuple of 3 tuples of 2 ints: + interpreted as + `((left_dim1_pad, right_dim1_pad), (left_dim2_pad, + right_dim2_pad), (left_dim3_pad, right_dim3_pad))` + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad, + depth)` + - If `data_format` is `"channels_first"`: + `(batch_size, depth, first_axis_to_pad, second_axis_to_pad, + third_axis_to_pad)` + + Output shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad, + depth)` + - If `data_format` is `"channels_first"`: + `(batch_size, depth, first_padded_axis, second_padded_axis, + third_axis_to_pad)` + """ + + def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): + super(ZeroPadding3D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + if isinstance(padding, int): + self.padding = ((padding, padding), (padding, padding), (padding, + padding)) + elif hasattr(padding, '__len__'): + if len(padding) != 3: + raise ValueError('`padding` should have 3 elements. ' + 'Found: ' + str(padding)) + dim1_padding = conv_utils.normalize_tuple(padding[0], 2, + '1st entry of padding') + dim2_padding = conv_utils.normalize_tuple(padding[1], 2, + '2nd entry of padding') + dim3_padding = conv_utils.normalize_tuple(padding[2], 2, + '3rd entry of padding') + self.padding = (dim1_padding, dim2_padding, dim3_padding) + else: + raise ValueError( + '`padding` should be either an int, ' + 'a tuple of 3 ints ' + '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), ' + 'or a tuple of 3 tuples of 2 ints ' + '((left_dim1_pad, right_dim1_pad),' + ' (left_dim2_pad, right_dim2_pad),' + ' (left_dim3_pad, right_dim2_pad)). ' + 'Found: ' + str(padding)) + self.input_spec = InputSpec(ndim=5) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + if input_shape[2] is not None: + dim1 = input_shape[2] + self.padding[0][0] + self.padding[0][1] + else: + dim1 = None + if input_shape[3] is not None: + dim2 = input_shape[3] + self.padding[1][0] + self.padding[1][1] + else: + dim2 = None + if input_shape[4] is not None: + dim3 = input_shape[4] + self.padding[2][0] + self.padding[2][1] + else: + dim3 = None + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], dim1, dim2, dim3]) + elif self.data_format == 'channels_last': + if input_shape[1] is not None: + dim1 = input_shape[1] + self.padding[0][0] + self.padding[0][1] + else: + dim1 = None + if input_shape[2] is not None: + dim2 = input_shape[2] + self.padding[1][0] + self.padding[1][1] + else: + dim2 = None + if input_shape[3] is not None: + dim3 = input_shape[3] + self.padding[2][0] + self.padding[2][1] + else: + dim3 = None + return tensor_shape.TensorShape( + [input_shape[0], dim1, dim2, dim3, input_shape[4]]) + + def call(self, inputs): + return backend.spatial_3d_padding( + inputs, padding=self.padding, data_format=self.data_format) + + def get_config(self): + config = {'padding': self.padding, 'data_format': self.data_format} + base_config = super(ZeroPadding3D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Cropping1D(Layer): + """Cropping layer for 1D input (e.g. temporal sequence). + + It crops along the time dimension (axis 1). + + Examples: + + >>> input_shape = (2, 3, 2) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> print(x) + [[[ 0 1] + [ 2 3] + [ 4 5]] + [[ 6 7] + [ 8 9] + [10 11]]] + >>> y = tf.keras.layers.Cropping1D(cropping=1)(x) + >>> print(y) + tf.Tensor( + [[[2 3]] + [[8 9]]], shape=(2, 1, 2), dtype=int64) + + Args: + cropping: Int or tuple of int (length 2) + How many units should be trimmed off at the beginning and end of + the cropping dimension (axis 1). + If a single int is provided, the same value will be used for both. + + Input shape: + 3D tensor with shape `(batch_size, axis_to_crop, features)` + + Output shape: + 3D tensor with shape `(batch_size, cropped_axis, features)` + """ + + def __init__(self, cropping=(1, 1), **kwargs): + super(Cropping1D, self).__init__(**kwargs) + self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping') + self.input_spec = InputSpec(ndim=3) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if input_shape[1] is not None: + length = input_shape[1] - self.cropping[0] - self.cropping[1] + else: + length = None + return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) + + def call(self, inputs): + if self.cropping[1] == 0: + return inputs[:, self.cropping[0]:, :] + else: + return inputs[:, self.cropping[0]:-self.cropping[1], :] + + def get_config(self): + config = {'cropping': self.cropping} + base_config = super(Cropping1D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Cropping2D(Layer): + """Cropping layer for 2D input (e.g. picture). + + It crops along spatial dimensions, i.e. height and width. + + Examples: + + >>> input_shape = (2, 28, 28, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x) + >>> print(y.shape) + (2, 24, 20, 3) + + Args: + cropping: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. + - If int: the same symmetric cropping + is applied to height and width. + - If tuple of 2 ints: + interpreted as two different + symmetric cropping values for height and width: + `(symmetric_height_crop, symmetric_width_crop)`. + - If tuple of 2 tuples of 2 ints: + interpreted as + `((top_crop, bottom_crop), (left_crop, right_crop))` + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch_size, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, rows, cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, rows, cols)` + + Output shape: + 4D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, cropped_rows, cropped_cols, channels)` + - If `data_format` is `"channels_first"`: + `(batch_size, channels, cropped_rows, cropped_cols)` + """ + + def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): + super(Cropping2D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + if isinstance(cropping, int): + self.cropping = ((cropping, cropping), (cropping, cropping)) + elif hasattr(cropping, '__len__'): + if len(cropping) != 2: + raise ValueError('`cropping` should have two elements. ' + 'Found: ' + str(cropping)) + height_cropping = conv_utils.normalize_tuple(cropping[0], 2, + '1st entry of cropping') + width_cropping = conv_utils.normalize_tuple(cropping[1], 2, + '2nd entry of cropping') + self.cropping = (height_cropping, width_cropping) + else: + raise ValueError('`cropping` should be either an int, ' + 'a tuple of 2 ints ' + '(symmetric_height_crop, symmetric_width_crop), ' + 'or a tuple of 2 tuples of 2 ints ' + '((top_crop, bottom_crop), (left_crop, right_crop)). ' + 'Found: ' + str(cropping)) + self.input_spec = InputSpec(ndim=4) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + # pylint: disable=invalid-unary-operand-type + if self.data_format == 'channels_first': + return tensor_shape.TensorShape([ + input_shape[0], input_shape[1], + input_shape[2] - self.cropping[0][0] - self.cropping[0][1] + if input_shape[2] else None, + input_shape[3] - self.cropping[1][0] - self.cropping[1][1] + if input_shape[3] else None + ]) + else: + return tensor_shape.TensorShape([ + input_shape[0], + input_shape[1] - self.cropping[0][0] - self.cropping[0][1] + if input_shape[1] else None, + input_shape[2] - self.cropping[1][0] - self.cropping[1][1] + if input_shape[2] else None, input_shape[3] + ]) + # pylint: enable=invalid-unary-operand-type + + def call(self, inputs): + # pylint: disable=invalid-unary-operand-type + if self.data_format == 'channels_first': + if self.cropping[0][1] == self.cropping[1][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] + elif self.cropping[0][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: + -self.cropping[1][1]] + elif self.cropping[1][1] == 0: + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:] + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:-self.cropping[1][1]] + else: + if self.cropping[0][1] == self.cropping[1][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] + elif self.cropping[0][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: + -self.cropping[1][1], :] + elif self.cropping[1][1] == 0: + return inputs[:, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:, :] + return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ + 1][0]:-self.cropping[1][1], :] # pylint: disable=invalid-unary-operand-type + # pylint: enable=invalid-unary-operand-type + + def get_config(self): + config = {'cropping': self.cropping, 'data_format': self.data_format} + base_config = super(Cropping2D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Cropping3D(Layer): + """Cropping layer for 3D data (e.g. spatial or spatio-temporal). + + Examples: + + >>> input_shape = (2, 28, 28, 10, 3) + >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) + >>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x) + >>> print(y.shape) + (2, 24, 20, 6, 3) + + Args: + cropping: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. + - If int: the same symmetric cropping + is applied to depth, height, and width. + - If tuple of 3 ints: interpreted as two different + symmetric cropping values for depth, height, and width: + `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`. + - If tuple of 3 tuples of 2 ints: interpreted as + `((left_dim1_crop, right_dim1_crop), (left_dim2_crop, + right_dim2_crop), (left_dim3_crop, right_dim3_crop))` + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop, + depth)` + - If `data_format` is `"channels_first"`: + `(batch_size, depth, first_axis_to_crop, second_axis_to_crop, + third_axis_to_crop)` + + Output shape: + 5D tensor with shape: + - If `data_format` is `"channels_last"`: + `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis, + depth)` + - If `data_format` is `"channels_first"`: + `(batch_size, depth, first_cropped_axis, second_cropped_axis, + third_cropped_axis)` + """ + + def __init__(self, + cropping=((1, 1), (1, 1), (1, 1)), + data_format=None, + **kwargs): + super(Cropping3D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + if isinstance(cropping, int): + self.cropping = ((cropping, cropping), (cropping, cropping), (cropping, + cropping)) + elif hasattr(cropping, '__len__'): + if len(cropping) != 3: + raise ValueError('`cropping` should have 3 elements. ' + 'Found: ' + str(cropping)) + dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, + '1st entry of cropping') + dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, + '2nd entry of cropping') + dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2, + '3rd entry of cropping') + self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping) + else: + raise ValueError( + '`cropping` should be either an int, ' + 'a tuple of 3 ints ' + '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), ' + 'or a tuple of 3 tuples of 2 ints ' + '((left_dim1_crop, right_dim1_crop),' + ' (left_dim2_crop, right_dim2_crop),' + ' (left_dim3_crop, right_dim2_crop)). ' + 'Found: ' + str(cropping)) + self.input_spec = InputSpec(ndim=5) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + # pylint: disable=invalid-unary-operand-type + if self.data_format == 'channels_first': + if input_shape[2] is not None: + dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] + else: + dim1 = None + if input_shape[3] is not None: + dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] + else: + dim2 = None + if input_shape[4] is not None: + dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] + else: + dim3 = None + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], dim1, dim2, dim3]) + elif self.data_format == 'channels_last': + if input_shape[1] is not None: + dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] + else: + dim1 = None + if input_shape[2] is not None: + dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] + else: + dim2 = None + if input_shape[3] is not None: + dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] + else: + dim3 = None + return tensor_shape.TensorShape( + [input_shape[0], dim1, dim2, dim3, input_shape[4]]) + # pylint: enable=invalid-unary-operand-type + + def call(self, inputs): + # pylint: disable=invalid-unary-operand-type + if self.data_format == 'channels_first': + if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, + self.cropping[2][0]:] + elif self.cropping[0][1] == self.cropping[1][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, + self.cropping[2][0]:-self.cropping[2][1]] + elif self.cropping[1][1] == self.cropping[2][1] == 0: + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:, self.cropping[2][0]:] + elif self.cropping[0][1] == self.cropping[2][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: + -self.cropping[1][1], self.cropping[2][0]:] + elif self.cropping[0][1] == 0: + return inputs[:, :, self.cropping[0][0]:, self.cropping[1][ + 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]] + elif self.cropping[1][1] == 0: + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. + cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] + elif self.cropping[2][1] == 0: + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. + cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:] + return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][ + 0]:-self.cropping[2][1]] + else: + if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, + self.cropping[2][0]:, :] + elif self.cropping[0][1] == self.cropping[1][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, + self.cropping[2][0]:-self.cropping[2][1], :] + elif self.cropping[1][1] == self.cropping[2][1] == 0: + return inputs[:, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:, self.cropping[2][0]:, :] + elif self.cropping[0][1] == self.cropping[2][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: + -self.cropping[1][1], self.cropping[2][0]:, :] + elif self.cropping[0][1] == 0: + return inputs[:, self.cropping[0][0]:, self.cropping[1][ + 0]:-self.cropping[1][1], self.cropping[2][0]: + -self.cropping[2][1], :] + elif self.cropping[1][1] == 0: + return inputs[:, self.cropping[0][ + 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: + -self.cropping[2][1], :] + elif self.cropping[2][1] == 0: + return inputs[:, self.cropping[0][0]:-self.cropping[0][1], + self.cropping[1][0]:-self.cropping[1][1], self.cropping[ + 2][0]:, :] + return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ + 1][0]:-self.cropping[1][1], self.cropping[2][0]: # pylint: disable=invalid-unary-operand-type + -self.cropping[2][1], :] # pylint: disable=invalid-unary-operand-type + # pylint: enable=invalid-unary-operand-type + + def get_config(self): + config = {'cropping': self.cropping, 'data_format': self.data_format} + base_config = super(Cropping3D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +# Aliases + +Convolution1D = Conv1D +Convolution2D = Conv2D +Convolution3D = Conv3D +SeparableConvolution1D = SeparableConv1D +SeparableConvolution2D = SeparableConv2D +Convolution2DTranspose = Conv2DTranspose +Convolution3DTranspose = Conv3DTranspose +Deconvolution2D = Deconv2D = Conv2DTranspose +Deconvolution3D = Deconv3D = Conv3DTranspose diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional_recurrent.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional_recurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..15a38060a644aa7edf1527b72a084a1d09240ac7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/convolutional_recurrent.py @@ -0,0 +1,1028 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=g-classes-have-attributes +"""Convolutional-recurrent layers.""" + +import numpy as np + +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.layers.recurrent import DropoutRNNCellMixin +from tensorflow.python.keras.layers.recurrent import RNN +from tensorflow.python.keras.utils import conv_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops + + +class ConvRNN2D(RNN): + """Base class for convolutional-recurrent layers. + + Args: + cell: A RNN cell instance. A RNN cell is a class that has: + - a `call(input_at_t, states_at_t)` method, returning + `(output_at_t, states_at_t_plus_1)`. The call method of the + cell can also take the optional argument `constants`, see + section "Note on passing external constants" below. + - a `state_size` attribute. This can be a single integer + (single state) in which case it is + the number of channels of the recurrent state + (which should be the same as the number of channels of the cell + output). This can also be a list/tuple of integers + (one size per state). In this case, the first entry + (`state_size[0]`) should be the same as + the size of the cell output. + return_sequences: Boolean. Whether to return the last output. + in the output sequence, or the full sequence. + return_state: Boolean. Whether to return the last state + in addition to the output. + go_backwards: Boolean (default False). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + input_shape: Use this argument to specify the shape of the + input when this layer is the first one in a model. + + Call arguments: + inputs: A 5D tensor. + mask: Binary tensor of shape `(samples, timesteps)` indicating whether + a given timestep should be masked. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is for use with cells that use dropout. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + constants: List of constant tensors to be passed to the cell at each + timestep. + + Input shape: + 5D tensor with shape: + `(samples, timesteps, channels, rows, cols)` + if data_format='channels_first' or 5D tensor with shape: + `(samples, timesteps, rows, cols, channels)` + if data_format='channels_last'. + + Output shape: + - If `return_state`: a list of tensors. The first tensor is + the output. The remaining tensors are the last states, + each 4D tensor with shape: + `(samples, filters, new_rows, new_cols)` + if data_format='channels_first' + or 4D tensor with shape: + `(samples, new_rows, new_cols, filters)` + if data_format='channels_last'. + `rows` and `cols` values might have changed due to padding. + - If `return_sequences`: 5D tensor with shape: + `(samples, timesteps, filters, new_rows, new_cols)` + if data_format='channels_first' + or 5D tensor with shape: + `(samples, timesteps, new_rows, new_cols, filters)` + if data_format='channels_last'. + - Else, 4D tensor with shape: + `(samples, filters, new_rows, new_cols)` + if data_format='channels_first' + or 4D tensor with shape: + `(samples, new_rows, new_cols, filters)` + if data_format='channels_last'. + + Masking: + This layer supports masking for input data with a variable number + of timesteps. + + Note on using statefulness in RNNs: + You can set RNN layers to be 'stateful', which means that the states + computed for the samples in one batch will be reused as initial states + for the samples in the next batch. This assumes a one-to-one mapping + between samples in different successive batches. + To enable statefulness: + - Specify `stateful=True` in the layer constructor. + - Specify a fixed batch size for your model, by passing + - If sequential model: + `batch_input_shape=(...)` to the first layer in your model. + - If functional model with 1 or more Input layers: + `batch_shape=(...)` to all the first layers in your model. + This is the expected shape of your inputs + *including the batch size*. + It should be a tuple of integers, + e.g. `(32, 10, 100, 100, 32)`. + Note that the number of rows and columns should be specified + too. + - Specify `shuffle=False` when calling fit(). + To reset the states of your model, call `.reset_states()` on either + a specific layer, or on your entire model. + + Note on specifying the initial state of RNNs: + You can specify the initial state of RNN layers symbolically by + calling them with the keyword argument `initial_state`. The value of + `initial_state` should be a tensor or list of tensors representing + the initial state of the RNN layer. + You can specify the initial state of RNN layers numerically by + calling `reset_states` with the keyword argument `states`. The value of + `states` should be a numpy array or list of numpy arrays representing + the initial state of the RNN layer. + + Note on passing external constants to RNNs: + You can pass "external" constants to the cell using the `constants` + keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This + requires that the `cell.call` method accepts the same keyword argument + `constants`. Such constants can be used to condition the cell + transformation on additional static inputs (not changing over time), + a.k.a. an attention mechanism. + """ + + def __init__(self, + cell, + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + **kwargs): + if unroll: + raise TypeError('Unrolling isn\'t possible with ' + 'convolutional RNNs.') + if isinstance(cell, (list, tuple)): + # The StackedConvRNN2DCells isn't implemented yet. + raise TypeError('It is not possible at the moment to' + 'stack convolutional cells.') + super(ConvRNN2D, self).__init__(cell, + return_sequences, + return_state, + go_backwards, + stateful, + unroll, + **kwargs) + self.input_spec = [InputSpec(ndim=5)] + self.states = None + self._num_constants = None + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + + cell = self.cell + if cell.data_format == 'channels_first': + rows = input_shape[3] + cols = input_shape[4] + elif cell.data_format == 'channels_last': + rows = input_shape[2] + cols = input_shape[3] + rows = conv_utils.conv_output_length(rows, + cell.kernel_size[0], + padding=cell.padding, + stride=cell.strides[0], + dilation=cell.dilation_rate[0]) + cols = conv_utils.conv_output_length(cols, + cell.kernel_size[1], + padding=cell.padding, + stride=cell.strides[1], + dilation=cell.dilation_rate[1]) + + if cell.data_format == 'channels_first': + output_shape = input_shape[:2] + (cell.filters, rows, cols) + elif cell.data_format == 'channels_last': + output_shape = input_shape[:2] + (rows, cols, cell.filters) + + if not self.return_sequences: + output_shape = output_shape[:1] + output_shape[2:] + + if self.return_state: + output_shape = [output_shape] + if cell.data_format == 'channels_first': + output_shape += [(input_shape[0], cell.filters, rows, cols) + for _ in range(2)] + elif cell.data_format == 'channels_last': + output_shape += [(input_shape[0], rows, cols, cell.filters) + for _ in range(2)] + return output_shape + + @tf_utils.shape_type_conversion + def build(self, input_shape): + # Note input_shape will be list of shapes of initial states and + # constants if these are passed in __call__. + if self._num_constants is not None: + constants_shape = input_shape[-self._num_constants:] # pylint: disable=E1130 + else: + constants_shape = None + + if isinstance(input_shape, list): + input_shape = input_shape[0] + + batch_size = input_shape[0] if self.stateful else None + self.input_spec[0] = InputSpec(shape=(batch_size, None) + input_shape[2:5]) + + # allow cell (if layer) to build before we set or validate state_spec + if isinstance(self.cell, Layer): + step_input_shape = (input_shape[0],) + input_shape[2:] + if constants_shape is not None: + self.cell.build([step_input_shape] + constants_shape) + else: + self.cell.build(step_input_shape) + + # set or validate state_spec + if hasattr(self.cell.state_size, '__len__'): + state_size = list(self.cell.state_size) + else: + state_size = [self.cell.state_size] + + if self.state_spec is not None: + # initial_state was passed in call, check compatibility + if self.cell.data_format == 'channels_first': + ch_dim = 1 + elif self.cell.data_format == 'channels_last': + ch_dim = 3 + if [spec.shape[ch_dim] for spec in self.state_spec] != state_size: + raise ValueError( + 'An initial_state was passed that is not compatible with ' + '`cell.state_size`. Received `state_spec`={}; ' + 'However `cell.state_size` is ' + '{}'.format([spec.shape for spec in self.state_spec], + self.cell.state_size)) + else: + if self.cell.data_format == 'channels_first': + self.state_spec = [InputSpec(shape=(None, dim, None, None)) + for dim in state_size] + elif self.cell.data_format == 'channels_last': + self.state_spec = [InputSpec(shape=(None, None, None, dim)) + for dim in state_size] + if self.stateful: + self.reset_states() + self.built = True + + def get_initial_state(self, inputs): + # (samples, timesteps, rows, cols, filters) + initial_state = backend.zeros_like(inputs) + # (samples, rows, cols, filters) + initial_state = backend.sum(initial_state, axis=1) + shape = list(self.cell.kernel_shape) + shape[-1] = self.cell.filters + initial_state = self.cell.input_conv(initial_state, + array_ops.zeros(tuple(shape), + initial_state.dtype), + padding=self.cell.padding) + + if hasattr(self.cell.state_size, '__len__'): + return [initial_state for _ in self.cell.state_size] + else: + return [initial_state] + + def call(self, + inputs, + mask=None, + training=None, + initial_state=None, + constants=None): + # note that the .build() method of subclasses MUST define + # self.input_spec and self.state_spec with complete input shapes. + inputs, initial_state, constants = self._process_inputs( + inputs, initial_state, constants) + + if isinstance(mask, list): + mask = mask[0] + timesteps = backend.int_shape(inputs)[1] + + kwargs = {} + if generic_utils.has_arg(self.cell.call, 'training'): + kwargs['training'] = training + + if constants: + if not generic_utils.has_arg(self.cell.call, 'constants'): + raise ValueError('RNN cell does not support constants') + + def step(inputs, states): + constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type + states = states[:-self._num_constants] # pylint: disable=invalid-unary-operand-type + return self.cell.call(inputs, states, constants=constants, **kwargs) + else: + def step(inputs, states): + return self.cell.call(inputs, states, **kwargs) + + last_output, outputs, states = backend.rnn(step, + inputs, + initial_state, + constants=constants, + go_backwards=self.go_backwards, + mask=mask, + input_length=timesteps) + if self.stateful: + updates = [ + backend.update(self_state, state) + for self_state, state in zip(self.states, states) + ] + self.add_update(updates) + + if self.return_sequences: + output = outputs + else: + output = last_output + + if self.return_state: + if not isinstance(states, (list, tuple)): + states = [states] + else: + states = list(states) + return [output] + states + else: + return output + + def reset_states(self, states=None): + if not self.stateful: + raise AttributeError('Layer must be stateful.') + input_shape = self.input_spec[0].shape + state_shape = self.compute_output_shape(input_shape) + if self.return_state: + state_shape = state_shape[0] + if self.return_sequences: + state_shape = state_shape[:1].concatenate(state_shape[2:]) + if None in state_shape: + raise ValueError('If a 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 `batch_input_shape` ' + 'argument to your first layer.\n' + '- If using the functional API, specify ' + 'the time dimension by passing a ' + '`batch_shape` argument to your Input layer.\n' + 'The same thing goes for the number of rows and ' + 'columns.') + + # helper function + def get_tuple_shape(nb_channels): + result = list(state_shape) + if self.cell.data_format == 'channels_first': + result[1] = nb_channels + elif self.cell.data_format == 'channels_last': + result[3] = nb_channels + else: + raise KeyError + return tuple(result) + + # initialize state if None + if self.states[0] is None: + if hasattr(self.cell.state_size, '__len__'): + self.states = [backend.zeros(get_tuple_shape(dim)) + for dim in self.cell.state_size] + else: + self.states = [backend.zeros(get_tuple_shape(self.cell.state_size))] + elif states is None: + if hasattr(self.cell.state_size, '__len__'): + for state, dim in zip(self.states, self.cell.state_size): + backend.set_value(state, np.zeros(get_tuple_shape(dim))) + else: + backend.set_value(self.states[0], + np.zeros(get_tuple_shape(self.cell.state_size))) + else: + if not isinstance(states, (list, tuple)): + states = [states] + if len(states) != len(self.states): + raise ValueError('Layer ' + self.name + ' expects ' + + str(len(self.states)) + ' states, ' + + 'but it received ' + str(len(states)) + + ' state values. Input received: ' + str(states)) + for index, (value, state) in enumerate(zip(states, self.states)): + if hasattr(self.cell.state_size, '__len__'): + dim = self.cell.state_size[index] + else: + dim = self.cell.state_size + if value.shape != get_tuple_shape(dim): + raise ValueError('State ' + str(index) + + ' is incompatible with layer ' + + self.name + ': expected shape=' + + str(get_tuple_shape(dim)) + + ', found shape=' + str(value.shape)) + # TODO(anjalisridhar): consider batch calls to `set_value`. + backend.set_value(state, value) + + +class ConvLSTM2DCell(DropoutRNNCellMixin, Layer): + """Cell class for the ConvLSTM2D layer. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of n integers, specifying the + dimensions of the convolution window. + strides: An integer or tuple/list of n integers, + specifying the strides of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + dilation_rate: An integer or tuple/list of n integers, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + activation: Activation function to use. + If you don't specify anything, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + unit_forget_bias: Boolean. + If True, add 1 to the bias of the forget gate at initialization. + Use in combination with `bias_initializer="zeros"`. + This is recommended in [Jozefowicz et al., 2015]( + http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + Call arguments: + inputs: A 4D tensor. + states: List of state tensors corresponding to the previous timestep. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. Only relevant when `dropout` or + `recurrent_dropout` is used. + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1), + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + super(ConvLSTM2DCell, self).__init__(**kwargs) + self.filters = filters + self.kernel_size = conv_utils.normalize_tuple(kernel_size, 2, 'kernel_size') + self.strides = conv_utils.normalize_tuple(strides, 2, 'strides') + self.padding = conv_utils.normalize_padding(padding) + self.data_format = conv_utils.normalize_data_format(data_format) + self.dilation_rate = conv_utils.normalize_tuple(dilation_rate, 2, + 'dilation_rate') + self.activation = activations.get(activation) + self.recurrent_activation = activations.get(recurrent_activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + self.unit_forget_bias = unit_forget_bias + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + self.state_size = (self.filters, self.filters) + + def build(self, input_shape): + + if self.data_format == 'channels_first': + channel_axis = 1 + else: + channel_axis = -1 + if input_shape[channel_axis] is None: + raise ValueError('The channel dimension of the inputs ' + 'should be defined. Found `None`.') + input_dim = input_shape[channel_axis] + kernel_shape = self.kernel_size + (input_dim, self.filters * 4) + self.kernel_shape = kernel_shape + recurrent_kernel_shape = self.kernel_size + (self.filters, self.filters * 4) + + self.kernel = self.add_weight(shape=kernel_shape, + initializer=self.kernel_initializer, + name='kernel', + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint) + self.recurrent_kernel = self.add_weight( + shape=recurrent_kernel_shape, + initializer=self.recurrent_initializer, + name='recurrent_kernel', + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint) + + if self.use_bias: + if self.unit_forget_bias: + + def bias_initializer(_, *args, **kwargs): + return backend.concatenate([ + self.bias_initializer((self.filters,), *args, **kwargs), + initializers.get('ones')((self.filters,), *args, **kwargs), + self.bias_initializer((self.filters * 2,), *args, **kwargs), + ]) + else: + bias_initializer = self.bias_initializer + self.bias = self.add_weight( + shape=(self.filters * 4,), + name='bias', + initializer=bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint) + else: + self.bias = None + self.built = True + + def call(self, inputs, states, training=None): + h_tm1 = states[0] # previous memory state + c_tm1 = states[1] # previous carry state + + # dropout matrices for input units + dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=4) + # dropout matrices for recurrent units + rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( + h_tm1, training, count=4) + + if 0 < self.dropout < 1.: + inputs_i = inputs * dp_mask[0] + inputs_f = inputs * dp_mask[1] + inputs_c = inputs * dp_mask[2] + inputs_o = inputs * dp_mask[3] + else: + inputs_i = inputs + inputs_f = inputs + inputs_c = inputs + inputs_o = inputs + + if 0 < self.recurrent_dropout < 1.: + h_tm1_i = h_tm1 * rec_dp_mask[0] + h_tm1_f = h_tm1 * rec_dp_mask[1] + h_tm1_c = h_tm1 * rec_dp_mask[2] + h_tm1_o = h_tm1 * rec_dp_mask[3] + else: + h_tm1_i = h_tm1 + h_tm1_f = h_tm1 + h_tm1_c = h_tm1 + h_tm1_o = h_tm1 + + (kernel_i, kernel_f, + kernel_c, kernel_o) = array_ops.split(self.kernel, 4, axis=3) + (recurrent_kernel_i, + recurrent_kernel_f, + recurrent_kernel_c, + recurrent_kernel_o) = array_ops.split(self.recurrent_kernel, 4, axis=3) + + if self.use_bias: + bias_i, bias_f, bias_c, bias_o = array_ops.split(self.bias, 4) + else: + bias_i, bias_f, bias_c, bias_o = None, None, None, None + + x_i = self.input_conv(inputs_i, kernel_i, bias_i, padding=self.padding) + x_f = self.input_conv(inputs_f, kernel_f, bias_f, padding=self.padding) + x_c = self.input_conv(inputs_c, kernel_c, bias_c, padding=self.padding) + x_o = self.input_conv(inputs_o, kernel_o, bias_o, padding=self.padding) + h_i = self.recurrent_conv(h_tm1_i, recurrent_kernel_i) + h_f = self.recurrent_conv(h_tm1_f, recurrent_kernel_f) + h_c = self.recurrent_conv(h_tm1_c, recurrent_kernel_c) + h_o = self.recurrent_conv(h_tm1_o, recurrent_kernel_o) + + i = self.recurrent_activation(x_i + h_i) + f = self.recurrent_activation(x_f + h_f) + c = f * c_tm1 + i * self.activation(x_c + h_c) + o = self.recurrent_activation(x_o + h_o) + h = o * self.activation(c) + return h, [h, c] + + def input_conv(self, x, w, b=None, padding='valid'): + conv_out = backend.conv2d(x, w, strides=self.strides, + padding=padding, + data_format=self.data_format, + dilation_rate=self.dilation_rate) + if b is not None: + conv_out = backend.bias_add(conv_out, b, + data_format=self.data_format) + return conv_out + + def recurrent_conv(self, x, w): + conv_out = backend.conv2d(x, w, strides=(1, 1), + padding='same', + data_format=self.data_format) + return conv_out + + def get_config(self): + config = {'filters': self.filters, + 'kernel_size': self.kernel_size, + 'strides': self.strides, + 'padding': self.padding, + 'data_format': self.data_format, + 'dilation_rate': self.dilation_rate, + 'activation': activations.serialize(self.activation), + 'recurrent_activation': activations.serialize( + self.recurrent_activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize( + self.kernel_initializer), + 'recurrent_initializer': initializers.serialize( + self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'unit_forget_bias': self.unit_forget_bias, + 'kernel_regularizer': regularizers.serialize( + self.kernel_regularizer), + 'recurrent_regularizer': regularizers.serialize( + self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'kernel_constraint': constraints.serialize( + self.kernel_constraint), + 'recurrent_constraint': constraints.serialize( + self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout} + base_config = super(ConvLSTM2DCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class ConvLSTM2D(ConvRNN2D): + """2D Convolutional LSTM layer. + + A convolutional LSTM is similar to an LSTM, but the input transformations + and recurrent transformations are both convolutional. This layer is typically + used to process timeseries of images (i.e. video-like data). + + It is known to perform well for weather data forecasting, + using inputs that are timeseries of 2D grids of sensor values. + It isn't usually applied to regular video data, due to its high computational + cost. + + Args: + filters: Integer, the dimensionality of the output space + (i.e. the number of output filters in the convolution). + kernel_size: An integer or tuple/list of n integers, specifying the + dimensions of the convolution window. + strides: An integer or tuple/list of n integers, + specifying the strides of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, time, ..., channels)` + while `channels_first` corresponds to + inputs with shape `(batch, time, channels, ...)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + dilation_rate: An integer or tuple/list of n integers, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + activation: Activation function to use. + By default hyperbolic tangent activation function is applied + (`tanh(x)`). + recurrent_activation: Activation function to use + for the recurrent step. + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + unit_forget_bias: Boolean. + If True, add 1 to the bias of the forget gate at initialization. + Use in combination with `bias_initializer="zeros"`. + This is recommended in [Jozefowicz et al., 2015]( + http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + return_sequences: Boolean. Whether to return the last output + in the output sequence, or the full sequence. (default False) + return_state: Boolean Whether to return the last state + in addition to the output. (default False) + go_backwards: Boolean (default False). + If True, process the input sequence backwards. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + Call arguments: + inputs: A 5D float tensor (see input shape description below). + mask: Binary tensor of shape `(samples, timesteps)` indicating whether + a given timestep should be masked. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is only relevant if `dropout` or `recurrent_dropout` + are set. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + + Input shape: + - If data_format='channels_first' + 5D tensor with shape: + `(samples, time, channels, rows, cols)` + - If data_format='channels_last' + 5D tensor with shape: + `(samples, time, rows, cols, channels)` + + Output shape: + - If `return_state`: a list of tensors. The first tensor is + the output. The remaining tensors are the last states, + each 4D tensor with shape: + `(samples, filters, new_rows, new_cols)` + if data_format='channels_first' + or 4D tensor with shape: + `(samples, new_rows, new_cols, filters)` + if data_format='channels_last'. + `rows` and `cols` values might have changed due to padding. + - If `return_sequences`: 5D tensor with shape: + `(samples, timesteps, filters, new_rows, new_cols)` + if data_format='channels_first' + or 5D tensor with shape: + `(samples, timesteps, new_rows, new_cols, filters)` + if data_format='channels_last'. + - Else, 4D tensor with shape: + `(samples, filters, new_rows, new_cols)` + if data_format='channels_first' + or 4D tensor with shape: + `(samples, new_rows, new_cols, filters)` + if data_format='channels_last'. + + Raises: + ValueError: in case of invalid constructor arguments. + + References: + - [Shi et al., 2015](http://arxiv.org/abs/1506.04214v1) + (the current implementation does not include the feedback loop on the + cells output). + + Example: + + ```python + steps = 10 + height = 32 + width = 32 + input_channels = 3 + output_channels = 6 + + inputs = tf.keras.Input(shape=(steps, height, width, input_channels)) + layer = tf.keras.layers.ConvLSTM2D(filters=output_channels, kernel_size=3) + outputs = layer(inputs) + ``` + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1), + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + dropout=0., + recurrent_dropout=0., + **kwargs): + cell = ConvLSTM2DCell(filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + recurrent_activation=recurrent_activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + recurrent_initializer=recurrent_initializer, + bias_initializer=bias_initializer, + unit_forget_bias=unit_forget_bias, + kernel_regularizer=kernel_regularizer, + recurrent_regularizer=recurrent_regularizer, + bias_regularizer=bias_regularizer, + kernel_constraint=kernel_constraint, + recurrent_constraint=recurrent_constraint, + bias_constraint=bias_constraint, + dropout=dropout, + recurrent_dropout=recurrent_dropout, + dtype=kwargs.get('dtype')) + super(ConvLSTM2D, self).__init__(cell, + return_sequences=return_sequences, + return_state=return_state, + go_backwards=go_backwards, + stateful=stateful, + **kwargs) + self.activity_regularizer = regularizers.get(activity_regularizer) + + def call(self, inputs, mask=None, training=None, initial_state=None): + return super(ConvLSTM2D, self).call(inputs, + mask=mask, + training=training, + initial_state=initial_state) + + @property + def filters(self): + return self.cell.filters + + @property + def kernel_size(self): + return self.cell.kernel_size + + @property + def strides(self): + return self.cell.strides + + @property + def padding(self): + return self.cell.padding + + @property + def data_format(self): + return self.cell.data_format + + @property + def dilation_rate(self): + return self.cell.dilation_rate + + @property + def activation(self): + return self.cell.activation + + @property + def recurrent_activation(self): + return self.cell.recurrent_activation + + @property + def use_bias(self): + return self.cell.use_bias + + @property + def kernel_initializer(self): + return self.cell.kernel_initializer + + @property + def recurrent_initializer(self): + return self.cell.recurrent_initializer + + @property + def bias_initializer(self): + return self.cell.bias_initializer + + @property + def unit_forget_bias(self): + return self.cell.unit_forget_bias + + @property + def kernel_regularizer(self): + return self.cell.kernel_regularizer + + @property + def recurrent_regularizer(self): + return self.cell.recurrent_regularizer + + @property + def bias_regularizer(self): + return self.cell.bias_regularizer + + @property + def kernel_constraint(self): + return self.cell.kernel_constraint + + @property + def recurrent_constraint(self): + return self.cell.recurrent_constraint + + @property + def bias_constraint(self): + return self.cell.bias_constraint + + @property + def dropout(self): + return self.cell.dropout + + @property + def recurrent_dropout(self): + return self.cell.recurrent_dropout + + def get_config(self): + config = {'filters': self.filters, + 'kernel_size': self.kernel_size, + 'strides': self.strides, + 'padding': self.padding, + 'data_format': self.data_format, + 'dilation_rate': self.dilation_rate, + 'activation': activations.serialize(self.activation), + 'recurrent_activation': activations.serialize( + self.recurrent_activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize( + self.kernel_initializer), + 'recurrent_initializer': initializers.serialize( + self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'unit_forget_bias': self.unit_forget_bias, + 'kernel_regularizer': regularizers.serialize( + self.kernel_regularizer), + 'recurrent_regularizer': regularizers.serialize( + self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': regularizers.serialize( + self.activity_regularizer), + 'kernel_constraint': constraints.serialize( + self.kernel_constraint), + 'recurrent_constraint': constraints.serialize( + self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout} + base_config = super(ConvLSTM2D, self).get_config() + del base_config['cell'] + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config): + return cls(**config) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/core.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/core.py new file mode 100644 index 0000000000000000000000000000000000000000..c9be0a3cc5ba10fef8cd7816d06661e781020e41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/core.py @@ -0,0 +1,1825 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Core Keras layers.""" + +import copy +import functools +import operator +import sys +import textwrap +import types as python_types +import warnings + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend as K +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.keras.utils import conv_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import standard_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops.ragged import ragged_getitem +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import get_canonical_name_for_symbol +from tensorflow.python.util.tf_export import get_symbol_from_name + + +# pylint: disable=g-classes-have-attributes +class Masking(Layer): + """Masks a sequence by using a mask value to skip timesteps. + + For each timestep in the input tensor (dimension #1 in the tensor), + if all values in the input tensor at that timestep + are equal to `mask_value`, then the timestep will be masked (skipped) + in all downstream layers (as long as they support masking). + + If any downstream layer does not support masking yet receives such + an input mask, an exception will be raised. + + Example: + + Consider a Numpy data array `x` of shape `(samples, timesteps, features)`, + to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you + lack data for these timesteps. You can: + + - Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.` + - Insert a `Masking` layer with `mask_value=0.` before the LSTM layer: + + ```python + samples, timesteps, features = 32, 10, 8 + inputs = np.random.random([samples, timesteps, features]).astype(np.float32) + inputs[:, 3, :] = 0. + inputs[:, 5, :] = 0. + + model = tf.keras.models.Sequential() + model.add(tf.keras.layers.Masking(mask_value=0., + input_shape=(timesteps, features))) + model.add(tf.keras.layers.LSTM(32)) + + output = model(inputs) + # The time step 3 and 5 will be skipped from LSTM calculation. + ``` + + See [the masking and padding guide]( + https://www.tensorflow.org/guide/keras/masking_and_padding) + for more details. + """ + + def __init__(self, mask_value=0., **kwargs): + super(Masking, self).__init__(**kwargs) + self.supports_masking = True + self.mask_value = mask_value + self._compute_output_and_mask_jointly = True + + def compute_mask(self, inputs, mask=None): + return K.any(math_ops.not_equal(inputs, self.mask_value), axis=-1) + + def call(self, inputs): + boolean_mask = K.any( + math_ops.not_equal(inputs, self.mask_value), axis=-1, keepdims=True) + outputs = inputs * math_ops.cast(boolean_mask, inputs.dtype) + # Compute the mask and outputs simultaneously. + outputs._keras_mask = array_ops.squeeze(boolean_mask, axis=-1) # pylint: disable=protected-access + return outputs + + def compute_output_shape(self, input_shape): + return input_shape + + def get_config(self): + config = {'mask_value': self.mask_value} + base_config = super(Masking, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Dropout(Layer): + """Applies Dropout to the input. + + The Dropout layer randomly sets input units to 0 with a frequency of `rate` + at each step during training time, which helps prevent overfitting. + Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over + all inputs is unchanged. + + Note that the Dropout layer only applies when `training` is set to True + such that no values are dropped during inference. When using `model.fit`, + `training` will be appropriately set to True automatically, and in other + contexts, you can set the kwarg explicitly to True when calling the layer. + + (This is in contrast to setting `trainable=False` for a Dropout layer. + `trainable` does not affect the layer's behavior, as Dropout does + not have any variables/weights that can be frozen during training.) + + >>> tf.random.set_seed(0) + >>> layer = tf.keras.layers.Dropout(.2, input_shape=(2,)) + >>> data = np.arange(10).reshape(5, 2).astype(np.float32) + >>> print(data) + [[0. 1.] + [2. 3.] + [4. 5.] + [6. 7.] + [8. 9.]] + >>> outputs = layer(data, training=True) + >>> print(outputs) + tf.Tensor( + [[ 0. 1.25] + [ 2.5 3.75] + [ 5. 6.25] + [ 7.5 8.75] + [10. 0. ]], shape=(5, 2), dtype=float32) + + Args: + rate: Float between 0 and 1. Fraction of the input units to drop. + noise_shape: 1D integer tensor representing the shape of the + binary dropout mask that will be multiplied with the input. + For instance, if your inputs have shape + `(batch_size, timesteps, features)` and + you want the dropout mask to be the same for all timesteps, + you can use `noise_shape=(batch_size, 1, features)`. + seed: A Python integer to use as random seed. + + Call arguments: + inputs: Input tensor (of any rank). + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (doing nothing). + """ + + def __init__(self, rate, noise_shape=None, seed=None, **kwargs): + super(Dropout, self).__init__(**kwargs) + if isinstance(rate, (int, float)) and not 0 <= rate <= 1: + raise ValueError(f'Invalid value {rate} received for ' + f'`rate`, expected a value between 0 and 1.') + self.rate = rate + self.noise_shape = noise_shape + self.seed = seed + self.supports_masking = True + + def _get_noise_shape(self, inputs): + # Subclasses of `Dropout` may implement `_get_noise_shape(self, inputs)`, + # which will override `self.noise_shape`, and allows for custom noise + # shapes with dynamically sized inputs. + if self.noise_shape is None: + return None + + concrete_inputs_shape = array_ops.shape(inputs) + noise_shape = [] + for i, value in enumerate(self.noise_shape): + noise_shape.append(concrete_inputs_shape[i] if value is None else value) + return tensor_conversion.convert_to_tensor_v2_with_dispatch(noise_shape) + + def call(self, inputs, training=None): + if training is None: + training = K.learning_phase() + + def dropped_inputs(): + return nn.dropout( + inputs, + noise_shape=self._get_noise_shape(inputs), + seed=self.seed, + rate=self.rate) + + output = control_flow_util.smart_cond(training, dropped_inputs, + lambda: array_ops.identity(inputs)) + return output + + def compute_output_shape(self, input_shape): + return input_shape + + def get_config(self): + config = { + 'rate': self.rate, + 'noise_shape': self.noise_shape, + 'seed': self.seed + } + base_config = super(Dropout, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SpatialDropout1D(Dropout): + """Spatial 1D version of Dropout. + + This version performs the same function as Dropout, however, it drops + entire 1D feature maps instead of individual elements. If adjacent frames + within feature maps are strongly correlated (as is normally the case in + early convolution layers) then regular dropout will not regularize the + activations and will otherwise just result in an effective learning rate + decrease. In this case, SpatialDropout1D will help promote independence + between feature maps and should be used instead. + + Args: + rate: Float between 0 and 1. Fraction of the input units to drop. + + Call arguments: + inputs: A 3D tensor. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (doing nothing). + + Input shape: + 3D tensor with shape: + `(samples, timesteps, channels)` + + Output shape: + Same as input. + + References: + - [Efficient Object Localization Using Convolutional + Networks](https://arxiv.org/abs/1411.4280) + """ + + def __init__(self, rate, **kwargs): + super(SpatialDropout1D, self).__init__(rate, **kwargs) + self.input_spec = InputSpec(ndim=3) + + def _get_noise_shape(self, inputs): + input_shape = array_ops.shape(inputs) + noise_shape = (input_shape[0], 1, input_shape[2]) + return noise_shape + + +class SpatialDropout2D(Dropout): + """Spatial 2D version of Dropout. + + This version performs the same function as Dropout, however, it drops + entire 2D feature maps instead of individual elements. If adjacent pixels + within feature maps are strongly correlated (as is normally the case in + early convolution layers) then regular dropout will not regularize the + activations and will otherwise just result in an effective learning rate + decrease. In this case, SpatialDropout2D will help promote independence + between feature maps and should be used instead. + + Args: + rate: Float between 0 and 1. Fraction of the input units to drop. + data_format: 'channels_first' or 'channels_last'. + In 'channels_first' mode, the channels dimension + (the depth) is at index 1, + in 'channels_last' mode is it at index 3. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Call arguments: + inputs: A 4D tensor. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (doing nothing). + + Input shape: + 4D tensor with shape: + `(samples, channels, rows, cols)` if data_format='channels_first' + or 4D tensor with shape: + `(samples, rows, cols, channels)` if data_format='channels_last'. + + Output shape: + Same as input. + + References: + - [Efficient Object Localization Using Convolutional + Networks](https://arxiv.org/abs/1411.4280) + """ + + def __init__(self, rate, data_format=None, **kwargs): + super(SpatialDropout2D, self).__init__(rate, **kwargs) + if data_format is None: + data_format = K.image_data_format() + if data_format not in {'channels_last', 'channels_first'}: + raise ValueError('data_format must be in ' + '{"channels_last", "channels_first"}') + self.data_format = data_format + self.input_spec = InputSpec(ndim=4) + + def _get_noise_shape(self, inputs): + input_shape = array_ops.shape(inputs) + if self.data_format == 'channels_first': + return (input_shape[0], input_shape[1], 1, 1) + elif self.data_format == 'channels_last': + return (input_shape[0], 1, 1, input_shape[3]) + + +class SpatialDropout3D(Dropout): + """Spatial 3D version of Dropout. + + This version performs the same function as Dropout, however, it drops + entire 3D feature maps instead of individual elements. If adjacent voxels + within feature maps are strongly correlated (as is normally the case in + early convolution layers) then regular dropout will not regularize the + activations and will otherwise just result in an effective learning rate + decrease. In this case, SpatialDropout3D will help promote independence + between feature maps and should be used instead. + + Args: + rate: Float between 0 and 1. Fraction of the input units to drop. + data_format: 'channels_first' or 'channels_last'. + In 'channels_first' mode, the channels dimension (the depth) + is at index 1, in 'channels_last' mode is it at index 4. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Call arguments: + inputs: A 5D tensor. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (doing nothing). + + Input shape: + 5D tensor with shape: + `(samples, channels, dim1, dim2, dim3)` if data_format='channels_first' + or 5D tensor with shape: + `(samples, dim1, dim2, dim3, channels)` if data_format='channels_last'. + + Output shape: + Same as input. + + References: + - [Efficient Object Localization Using Convolutional + Networks](https://arxiv.org/abs/1411.4280) + """ + + def __init__(self, rate, data_format=None, **kwargs): + super(SpatialDropout3D, self).__init__(rate, **kwargs) + if data_format is None: + data_format = K.image_data_format() + if data_format not in {'channels_last', 'channels_first'}: + raise ValueError('data_format must be in ' + '{"channels_last", "channels_first"}') + self.data_format = data_format + self.input_spec = InputSpec(ndim=5) + + def _get_noise_shape(self, inputs): + input_shape = array_ops.shape(inputs) + if self.data_format == 'channels_first': + return (input_shape[0], input_shape[1], 1, 1, 1) + elif self.data_format == 'channels_last': + return (input_shape[0], 1, 1, 1, input_shape[4]) + + +class Activation(Layer): + """Applies an activation function to an output. + + Args: + activation: Activation function, such as `tf.nn.relu`, or string name of + built-in activation function, such as "relu". + + Usage: + + >>> layer = tf.keras.layers.Activation('relu') + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [0.0, 0.0, 0.0, 2.0] + >>> layer = tf.keras.layers.Activation(tf.nn.relu) + >>> output = layer([-3.0, -1.0, 0.0, 2.0]) + >>> list(output.numpy()) + [0.0, 0.0, 0.0, 2.0] + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the batch axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as input. + """ + + def __init__(self, activation, **kwargs): + super(Activation, self).__init__(**kwargs) + self.supports_masking = True + self.activation = activations.get(activation) + + def call(self, inputs): + return self.activation(inputs) + + def compute_output_shape(self, input_shape): + return input_shape + + def get_config(self): + config = {'activation': activations.serialize(self.activation)} + base_config = super(Activation, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Reshape(Layer): + """Layer that reshapes inputs into the given shape. + + Input shape: + Arbitrary, although all dimensions in the input shape must be known/fixed. + Use the keyword argument `input_shape` (tuple of integers, does not include + the samples/batch size axis) when using this layer as the first layer + in a model. + + Output shape: + `(batch_size,) + target_shape` + + Example: + + >>> # as first layer in a Sequential model + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,))) + >>> # model.output_shape == (None, 3, 4), `None` is the batch size. + >>> model.output_shape + (None, 3, 4) + + >>> # as intermediate layer in a Sequential model + >>> model.add(tf.keras.layers.Reshape((6, 2))) + >>> model.output_shape + (None, 6, 2) + + >>> # also supports shape inference using `-1` as dimension + >>> model.add(tf.keras.layers.Reshape((-1, 2, 2))) + >>> model.output_shape + (None, 3, 2, 2) + """ + + def __init__(self, target_shape, **kwargs): + """Creates a `tf.keras.layers.Reshape` layer instance. + + Args: + target_shape: Target shape. Tuple of integers, does not include the + samples dimension (batch size). + **kwargs: Any additional layer keyword arguments. + """ + super(Reshape, self).__init__(**kwargs) + self.target_shape = tuple(target_shape) + + def _fix_unknown_dimension(self, input_shape, output_shape): + """Find and replace a missing dimension in an output shape. + + This is a near direct port of the internal Numpy function + `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c` + + Args: + input_shape: Shape of array being reshaped + output_shape: Desired shape of the array with at most + a single -1 which indicates a dimension that should be + derived from the input shape. + + Returns: + The new output shape with a -1 replaced with its computed value. + + Raises: + ValueError: If the total array size of the output_shape is + different than the input_shape, or more than one unknown dimension + is specified. + """ + output_shape = list(output_shape) + msg = ('total size of new array must be unchanged, ' + 'input_shape = {}, output_shape = {}' + .format(input_shape, output_shape)) + + known, unknown = 1, None + for index, dim in enumerate(output_shape): + if dim < 0: + if unknown is None: + unknown = index + else: + raise ValueError('Can only specify one unknown dimension.') + else: + known *= dim + + original = np.prod(input_shape, dtype=int) + if unknown is not None: + if known == 0 or original % known != 0: + raise ValueError(msg) + output_shape[unknown] = original // known + elif original != known: + raise ValueError(msg) + return output_shape + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if None in input_shape[1:]: + output_shape = [input_shape[0]] + # input shape (partially) unknown? replace -1's with None's + output_shape += tuple(s if s != -1 else None for s in self.target_shape) + else: + output_shape = [input_shape[0]] + output_shape += self._fix_unknown_dimension(input_shape[1:], + self.target_shape) + return tensor_shape.TensorShape(output_shape) + + def call(self, inputs): + result = array_ops.reshape( + inputs, (array_ops.shape(inputs)[0],) + self.target_shape) + if not context.executing_eagerly(): + # Set the static shape for the result since it might lost during array_ops + # reshape, eg, some `None` dim in the result could be inferred. + result.set_shape(self.compute_output_shape(inputs.shape)) + return result + + def get_config(self): + config = {'target_shape': self.target_shape} + base_config = super(Reshape, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Permute(Layer): + """Permutes the dimensions of the input according to a given pattern. + + Useful e.g. connecting RNNs and convnets. + + Example: + + ```python + model = Sequential() + model.add(Permute((2, 1), input_shape=(10, 64))) + # now: model.output_shape == (None, 64, 10) + # note: `None` is the batch dimension + ``` + + Args: + dims: Tuple of integers. Permutation pattern does not include the + samples dimension. Indexing starts at 1. + For instance, `(2, 1)` permutes the first and second dimensions + of the input. + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same as the input shape, but with the dimensions re-ordered according + to the specified pattern. + """ + + def __init__(self, dims, **kwargs): + super(Permute, self).__init__(**kwargs) + self.dims = tuple(dims) + if sorted(dims) != list(range(1, len(dims) + 1)): + raise ValueError( + 'Invalid permutation `dims` for Permute Layer: %s. ' + 'The set of indices in `dims` must be consecutive and start from 1.' % + (dims,)) + self.input_spec = InputSpec(ndim=len(self.dims) + 1) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + output_shape = copy.copy(input_shape) + for i, dim in enumerate(self.dims): + target_dim = input_shape[dim] + output_shape[i + 1] = target_dim + return tensor_shape.TensorShape(output_shape) + + def call(self, inputs): + return array_ops.transpose(inputs, perm=(0,) + self.dims) + + def get_config(self): + config = {'dims': self.dims} + base_config = super(Permute, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Flatten(Layer): + """Flattens the input. Does not affect the batch size. + + Note: If inputs are shaped `(batch,)` without a feature axis, then + flattening adds an extra channel dimension and output shape is `(batch, 1)`. + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, ..., channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, ...)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Example: + + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Conv2D(64, 3, 3, input_shape=(3, 32, 32))) + >>> model.output_shape + (None, 1, 10, 64) + + >>> model.add(Flatten()) + >>> model.output_shape + (None, 640) + + """ + + def __init__(self, data_format=None, **kwargs): + super(Flatten, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(min_ndim=1) + self._channels_first = self.data_format == 'channels_first' + + def call(self, inputs): + if self._channels_first: + rank = inputs.shape.rank + if rank and rank > 1: + # Switch to channels-last format. + permutation = [0] + permutation.extend(range(2, rank)) + permutation.append(1) + inputs = array_ops.transpose(inputs, perm=permutation) + + if context.executing_eagerly(): + # Full static shape is guaranteed to be available. + # Performance: Using `constant_op` is much faster than passing a list. + flattened_shape = constant_op.constant([inputs.shape[0], -1]) + return array_ops.reshape(inputs, flattened_shape) + else: + input_shape = inputs.shape + rank = input_shape.rank + if rank == 1: + return array_ops.expand_dims_v2(inputs, axis=1) + else: + batch_dim = tensor_shape.dimension_value(input_shape[0]) + non_batch_dims = input_shape[1:] + # Reshape in a way that preserves as much shape info as possible. + if non_batch_dims.is_fully_defined(): + last_dim = int(functools.reduce(operator.mul, non_batch_dims)) + flattened_shape = constant_op.constant([-1, last_dim]) + elif batch_dim is not None: + flattened_shape = constant_op.constant([int(batch_dim), -1]) + else: + flattened_shape = [array_ops.shape_v2(inputs)[0], -1] + return array_ops.reshape(inputs, flattened_shape) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if not input_shape: + output_shape = tensor_shape.TensorShape([1]) + else: + output_shape = [input_shape[0]] + if np.all(input_shape[1:]): + output_shape += [np.prod(input_shape[1:], dtype=int)] + else: + output_shape += [None] + return tensor_shape.TensorShape(output_shape) + + def get_config(self): + config = super(Flatten, self).get_config() + config.update({'data_format': self.data_format}) + return config + + +class RepeatVector(Layer): + """Repeats the input n times. + + Example: + + ```python + model = Sequential() + model.add(Dense(32, input_dim=32)) + # now: model.output_shape == (None, 32) + # note: `None` is the batch dimension + + model.add(RepeatVector(3)) + # now: model.output_shape == (None, 3, 32) + ``` + + Args: + n: Integer, repetition factor. + + Input shape: + 2D tensor of shape `(num_samples, features)`. + + Output shape: + 3D tensor of shape `(num_samples, n, features)`. + """ + + def __init__(self, n, **kwargs): + super(RepeatVector, self).__init__(**kwargs) + self.n = n + if not isinstance(n, int): + raise TypeError(f'Expected an integer value for `n`, got {type(n)}.') + self.input_spec = InputSpec(ndim=2) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + return tensor_shape.TensorShape([input_shape[0], self.n, input_shape[1]]) + + def call(self, inputs): + return K.repeat(inputs, self.n) + + def get_config(self): + config = {'n': self.n} + base_config = super(RepeatVector, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Lambda(Layer): + """Wraps arbitrary expressions as a `Layer` object. + + The `Lambda` layer exists so that arbitrary expressions can be used + as a `Layer` when constructing `Sequential` + and Functional API models. `Lambda` layers are best suited for simple + operations or quick experimentation. For more advanced use cases, follow + [this guide](https://www.tensorflow.org/guide/keras/custom_layers_and_models) + for subclassing `tf.keras.layers.Layer`. + + WARNING: `tf.keras.layers.Lambda` layers have (de)serialization limitations! + + The main reason to subclass `tf.keras.layers.Layer` instead of using a + `Lambda` layer is saving and inspecting a Model. `Lambda` layers + are saved by serializing the Python bytecode, which is fundamentally + non-portable. They should only be loaded in the same environment where + they were saved. Subclassed layers can be saved in a more portable way + by overriding their `get_config` method. Models that rely on + subclassed Layers are also often easier to visualize and reason about. + + Examples: + + ```python + # add a x -> x^2 layer + model.add(Lambda(lambda x: x ** 2)) + ``` + ```python + # add a layer that returns the concatenation + # of the positive part of the input and + # the opposite of the negative part + + def antirectifier(x): + x -= K.mean(x, axis=1, keepdims=True) + x = K.l2_normalize(x, axis=1) + pos = K.relu(x) + neg = K.relu(-x) + return K.concatenate([pos, neg], axis=1) + + model.add(Lambda(antirectifier)) + ``` + + Variables: + While it is possible to use Variables with Lambda layers, this practice is + discouraged as it can easily lead to bugs. For instance, consider the + following layer: + + ```python + scale = tf.Variable(1.) + scale_layer = tf.keras.layers.Lambda(lambda x: x * scale) + ``` + + Because scale_layer does not directly track the `scale` variable, it will + not appear in `scale_layer.trainable_weights` and will therefore not be + trained if `scale_layer` is used in a Model. + + A better pattern is to write a subclassed Layer: + + ```python + class ScaleLayer(tf.keras.layers.Layer): + def __init__(self): + super(ScaleLayer, self).__init__() + self.scale = tf.Variable(1.) + + def call(self, inputs): + return inputs * self.scale + ``` + + In general, Lambda layers can be convenient for simple stateless + computation, but anything more complex should use a subclass Layer instead. + + Args: + function: The function to be evaluated. Takes input tensor as first + argument. + output_shape: Expected output shape from function. This argument can be + inferred if not explicitly provided. Can be a tuple or function. If a + tuple, it only specifies the first dimension onward; + sample dimension is assumed either the same as the input: `output_shape = + (input_shape[0], ) + output_shape` or, the input is `None` and + the sample dimension is also `None`: `output_shape = (None, ) + + output_shape` If a function, it specifies the entire shape as a function + of the + input shape: `output_shape = f(input_shape)` + mask: Either None (indicating no masking) or a callable with the same + signature as the `compute_mask` layer method, or a tensor that will be + returned as output mask regardless of what the input is. + arguments: Optional dictionary of keyword arguments to be passed to the + function. + + Input shape: + Arbitrary. Use the keyword argument input_shape (tuple of + integers, does not include the samples axis) when using this layer as the + first layer in a model. + + Output shape: + Specified by `output_shape` argument + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, function, output_shape=None, mask=None, arguments=None, + **kwargs): + super(Lambda, self).__init__(**kwargs) + + self.arguments = arguments or {} + self.function = function + + if mask is not None: + self.supports_masking = True + self.mask = mask + self._output_shape = output_shape + + # Warning on every invocation will be quite irksome in Eager mode. + self._already_warned = False + + function_args = tf_inspect.getfullargspec(function).args + self._fn_expects_training_arg = 'training' in function_args + self._fn_expects_mask_arg = 'mask' in function_args + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if self._output_shape is None: + # Make use of existing autocomputation but provide Lambda-specific + # error message. This is always safe to run even when the outer context + # is Graph mode because Lambda layers don't have side effects such as + # `add_loss`. + with context.eager_mode(): + try: + return super(Lambda, self).compute_output_shape(input_shape) + except NotImplementedError: + raise NotImplementedError( + 'We could not automatically infer the shape of the Lambda\'s ' + 'output. Please specify `output_shape` for this Lambda.') + + if callable(self._output_shape): + output_shapes = self._output_shape(input_shape) + return tf_utils.convert_shapes(output_shapes, to_tuples=False) + + # Output shapes are passed directly and don't include batch dimension. + input_tensor_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) + batch_size = nest.flatten(input_tensor_shape)[0][0] if input_shape else None + + def _add_batch(shape): + return tensor_shape.TensorShape([batch_size] + shape.as_list()) + + output_shapes = tf_utils.convert_shapes(self._output_shape, to_tuples=False) + return nest.map_structure(_add_batch, output_shapes) + + def call(self, inputs, mask=None, training=None): + # We must copy for thread safety, but it only needs to be a shallow copy. + kwargs = {k: v for k, v in self.arguments.items()} + if self._fn_expects_mask_arg: + kwargs['mask'] = mask + if self._fn_expects_training_arg: + kwargs['training'] = training + + created_variables = [] + def _variable_creator(next_creator, **kwargs): + var = next_creator(**kwargs) + created_variables.append(var) + return var + + with backprop.GradientTape(watch_accessed_variables=True) as tape,\ + variable_scope.variable_creator_scope(_variable_creator): + result = self.function(inputs, **kwargs) + self._check_variables(created_variables, tape.watched_variables()) + return result + + def _check_variables(self, created_variables, accessed_variables): + if not created_variables and not accessed_variables: + # In the common case that a Lambda layer does not touch a Variable, we + # don't want to incur the runtime cost of assembling any state used for + # checking only to immediately discard it. + return + + tracked_weights = set(v.ref() for v in self.weights) + untracked_new_vars = [ + v for v in created_variables if v.ref() not in tracked_weights + ] + if untracked_new_vars: + variable_str = '\n'.join(' {}'.format(i) for i in untracked_new_vars) + error_str = textwrap.dedent( + ''' + The following Variables were created within a Lambda layer ({name}) + but are not tracked by said layer: + {variable_str} + The layer cannot safely ensure proper Variable reuse across multiple + calls, and consquently this behavior is disallowed for safety. Lambda + layers are not well suited to stateful computation; instead, writing a + subclassed Layer is the recommend way to define layers with + Variables.''' + ).format(name=self.name, variable_str=variable_str) + raise ValueError(error_str) + + untracked_used_vars = [ + v for v in accessed_variables if v.ref() not in tracked_weights + ] + if untracked_used_vars and not self._already_warned: + variable_str = '\n'.join(' {}'.format(i) for i in untracked_used_vars) + self._warn(textwrap.dedent( + ''' + The following Variables were used a Lambda layer's call ({name}), but + are not present in its tracked objects: + {variable_str} + It is possible that this is intended behavior, but it is more likely + an omission. This is a strong indication that this layer should be + formulated as a subclassed Layer rather than a Lambda layer.''' + ).format(name=self.name, variable_str=variable_str)) + self._already_warned = True + + def _warn(self, msg): + # This method will be overridden in a unit test to raise an error, because + # self.assertWarns is not universally implemented. + return tf_logging.warning(msg) + + def compute_mask(self, inputs, mask=None): + if callable(self.mask): + return self.mask(inputs, mask) + return self.mask + + def get_config(self): + function_config = self._serialize_function_to_config(self.function) + output_shape_config = self._serialize_function_to_config(self._output_shape, + allow_raw=True) + config = { + 'function': function_config[0], + 'function_type': function_config[1], + 'module': function_config[2], + 'output_shape': output_shape_config[0], + 'output_shape_type': output_shape_config[1], + 'output_shape_module': output_shape_config[2], + } + if self.mask is not None: + mask_config = self._serialize_function_to_config(self.mask) + config.update({ + 'mask': mask_config[0], + 'mask_type': mask_config[1], + 'mask_module': mask_config[2] + }) + config['arguments'] = self.arguments + + base_config = super(Lambda, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + def _serialize_function_to_config(self, inputs, allow_raw=False): + if isinstance(inputs, python_types.LambdaType): + output = generic_utils.func_dump(inputs) + output_type = 'lambda' + module = inputs.__module__ + elif callable(inputs): + output = inputs.__name__ + output_type = 'function' + module = inputs.__module__ + elif allow_raw: + output = inputs + output_type = 'raw' + module = None + else: + raise ValueError( + 'Invalid input for serialization, type: %s ' % type(inputs)) + + return output, output_type, module + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() + function = cls._parse_function_from_config( + config, custom_objects, 'function', 'module', 'function_type') + + output_shape = cls._parse_function_from_config( + config, custom_objects, 'output_shape', 'output_shape_module', + 'output_shape_type') + if 'mask' in config: + mask = cls._parse_function_from_config( + config, custom_objects, 'mask', 'mask_module', 'mask_type') + else: + mask = None + + config['function'] = function + config['output_shape'] = output_shape + config['mask'] = mask + + # If arguments were numpy array, they have been saved as + # list. We need to recover the ndarray + if 'arguments' in config: + for key in config['arguments']: + if isinstance(config['arguments'][key], dict): + arg_dict = config['arguments'][key] + if 'type' in arg_dict and arg_dict['type'] == 'ndarray': + # Overwrite the argument with its numpy translation + config['arguments'][key] = np.array(arg_dict['value']) + + return cls(**config) + + @classmethod + def _parse_function_from_config( + cls, config, custom_objects, func_attr_name, module_attr_name, + func_type_attr_name): + globs = globals().copy() + module = config.pop(module_attr_name, None) + if module in sys.modules: + globs.update(sys.modules[module].__dict__) + elif module is not None: + # Note: we don't know the name of the function if it's a lambda. + warnings.warn('{} is not loaded, but a Lambda layer uses it. ' + 'It may cause errors.'.format(module) + , UserWarning) + if custom_objects: + globs.update(custom_objects) + function_type = config.pop(func_type_attr_name) + if function_type == 'function': + # Simple lookup in custom objects + function = generic_utils.deserialize_keras_object( + config[func_attr_name], + custom_objects=custom_objects, + printable_module_name='function in Lambda layer') + elif function_type == 'lambda': + # Unsafe deserialization from bytecode + function = generic_utils.func_load( + config[func_attr_name], globs=globs) + elif function_type == 'raw': + function = config[func_attr_name] + else: + raise TypeError('Unknown function type:', function_type) + return function + + +class Dense(Layer): + """Just your regular densely-connected NN layer. + + `Dense` implements the operation: + `output = activation(dot(input, kernel) + bias)` + where `activation` is the element-wise activation function + passed as the `activation` argument, `kernel` is a weights matrix + created by the layer, and `bias` is a bias vector created by the layer + (only applicable if `use_bias` is `True`). These are all attributes of + `Dense`. + + Note: If the input to the layer has a rank greater than 2, then `Dense` + computes the dot product between the `inputs` and the `kernel` along the + last axis of the `inputs` and axis 0 of the `kernel` (using `tf.tensordot`). + For example, if input has dimensions `(batch_size, d0, d1)`, + then we create a `kernel` with shape `(d1, units)`, and the `kernel` operates + along axis 2 of the `input`, on every sub-tensor of shape `(1, 1, d1)` + (there are `batch_size * d0` such sub-tensors). + The output in this case will have shape `(batch_size, d0, units)`. + + Besides, layer attributes cannot be modified after the layer has been called + once (except the `trainable` attribute). + When a popular kwarg `input_shape` is passed, then keras will create + an input layer to insert before the current layer. This can be treated + equivalent to explicitly defining an `InputLayer`. + + Example: + + >>> # Create a `Sequential` model and add a Dense layer as the first layer. + >>> model = tf.keras.models.Sequential() + >>> model.add(tf.keras.Input(shape=(16,))) + >>> model.add(tf.keras.layers.Dense(32, activation='relu')) + >>> # Now the model will take as input arrays of shape (None, 16) + >>> # and output arrays of shape (None, 32). + >>> # Note that after the first layer, you don't need to specify + >>> # the size of the input anymore: + >>> model.add(tf.keras.layers.Dense(32)) + >>> model.output_shape + (None, 32) + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + If you don't specify anything, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix. + bias_initializer: Initializer for the bias vector. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation"). + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + + Input shape: + N-D tensor with shape: `(batch_size, ..., input_dim)`. + The most common situation would be + a 2D input with shape `(batch_size, input_dim)`. + + Output shape: + N-D tensor with shape: `(batch_size, ..., units)`. + For instance, for a 2D input with shape `(batch_size, input_dim)`, + the output would have shape `(batch_size, units)`. + """ + + def __init__(self, + units, + activation=None, + use_bias=True, + kernel_initializer='glorot_uniform', + bias_initializer='zeros', + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + **kwargs): + super(Dense, self).__init__( + activity_regularizer=activity_regularizer, **kwargs) + + self.units = int(units) if not isinstance(units, int) else units + if self.units < 0: + raise ValueError(f'Received an invalid value for `units`, expected ' + f'a positive integer, got {units}.') + self.activation = activations.get(activation) + self.use_bias = use_bias + self.kernel_initializer = initializers.get(kernel_initializer) + self.bias_initializer = initializers.get(bias_initializer) + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + self.kernel_constraint = constraints.get(kernel_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.input_spec = InputSpec(min_ndim=2) + self.supports_masking = True + + def build(self, input_shape): + dtype = dtypes.as_dtype(self.dtype or K.floatx()) + if not (dtype.is_floating or dtype.is_complex): + raise TypeError('Unable to build `Dense` layer with non-floating point ' + 'dtype %s' % (dtype,)) + + input_shape = tensor_shape.TensorShape(input_shape) + last_dim = tensor_shape.dimension_value(input_shape[-1]) + if last_dim is None: + raise ValueError('The last dimension of the inputs to `Dense` ' + 'should be defined. Found `None`.') + self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim}) + self.kernel = self.add_weight( + 'kernel', + shape=[last_dim, self.units], + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + dtype=self.dtype, + trainable=True) + if self.use_bias: + self.bias = self.add_weight( + 'bias', + shape=[self.units,], + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + dtype=self.dtype, + trainable=True) + else: + self.bias = None + self.built = True + + def call(self, inputs): + if inputs.dtype.base_dtype != self._compute_dtype_object.base_dtype: + inputs = math_ops.cast(inputs, dtype=self._compute_dtype_object) + + rank = inputs.shape.rank + if rank == 2 or rank is None: + # We use embedding_lookup_sparse as a more efficient matmul operation for + # large sparse input tensors. The op will result in a sparse gradient, as + # opposed to sparse_ops.sparse_tensor_dense_matmul which results in dense + # gradients. This can lead to sigfinicant speedups, see b/171762937. + if isinstance(inputs, sparse_tensor.SparseTensor): + # We need to fill empty rows, as the op assumes at least one id per row. + inputs, _ = sparse_ops.sparse_fill_empty_rows(inputs, 0) + # We need to do some munging of our input to use the embedding lookup as + # a matrix multiply. We split our input matrix into separate ids and + # weights tensors. The values of the ids tensor should be the column + # indices of our input matrix and the values of the weights tensor + # can continue to the actual matrix weights. + # The column arrangement of ids and weights + # will be summed over and does not matter. See the documentation for + # sparse_ops.sparse_tensor_dense_matmul a more detailed explanation + # of the inputs to both ops. + ids = sparse_tensor.SparseTensor( + indices=inputs.indices, + values=inputs.indices[:, 1], + dense_shape=inputs.dense_shape) + weights = inputs + outputs = embedding_ops.embedding_lookup_sparse_v2( + self.kernel, ids, weights, combiner='sum') + else: + outputs = gen_math_ops.MatMul(a=inputs, b=self.kernel) + # Broadcast kernel to inputs. + else: + outputs = standard_ops.tensordot(inputs, self.kernel, [[rank - 1], [0]]) + # Reshape the output back to the original ndim of the input. + if not context.executing_eagerly(): + shape = inputs.shape.as_list() + output_shape = shape[:-1] + [self.kernel.shape[-1]] + outputs.set_shape(output_shape) + + if self.use_bias: + outputs = nn_ops.bias_add(outputs, self.bias) + + if self.activation is not None: + outputs = self.activation(outputs) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + input_shape = input_shape.with_rank_at_least(2) + if tensor_shape.dimension_value(input_shape[-1]) is None: + raise ValueError( + 'The innermost dimension of input_shape must be defined, but saw: %s' + % (input_shape,)) + return input_shape[:-1].concatenate(self.units) + + def get_config(self): + config = super(Dense, self).get_config() + config.update({ + 'units': self.units, + 'activation': activations.serialize(self.activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize(self.kernel_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': constraints.serialize(self.kernel_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint) + }) + return config + + +class ActivityRegularization(Layer): + """Layer that applies an update to the cost function based input activity. + + Args: + l1: L1 regularization factor (positive float). + l2: L2 regularization factor (positive float). + + Input shape: + Arbitrary. Use the keyword argument `input_shape` + (tuple of integers, does not include the samples axis) + when using this layer as the first layer in a model. + + Output shape: + Same shape as input. + """ + + def __init__(self, l1=0., l2=0., **kwargs): + super(ActivityRegularization, self).__init__( + activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs) + self.supports_masking = True + self.l1 = l1 + self.l2 = l2 + + def compute_output_shape(self, input_shape): + return input_shape + + def get_config(self): + config = {'l1': self.l1, 'l2': self.l2} + base_config = super(ActivityRegularization, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class TFOpLambda(Layer): + """Wraps TF API symbols in a `Layer` object. + + It is inserted by the Functional API construction whenever users call + a supported TF symbol on KerasTensors. + + Like Lambda layers, this layer tries to raise warnings when it detects users + explicitly use variables in the call. (To let them know + that the layer will not capture the variables). + + This is useful in the case where users do something like: + x = keras.Input(...) + y = tf.Variable(...) + out = x * tf_variable + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, function, **kwargs): + self.function = function + self.symbol = ( + get_canonical_name_for_symbol(self.function, + add_prefix_to_v1_names=True) or + get_canonical_name_for_symbol(self.function, + api_name='keras', + add_prefix_to_v1_names=True)) + if 'name' not in kwargs: + # Generate a name. + # TFOpLambda layers avoid already-observed names, + # because users cannot easily control the generated names. + # Without this avoidance, users would be more likely to run + # into unavoidable duplicate layer name collisions. + # (For standard layers users could just set `name` when creating the + # layer to work around a collision, but they can't do that for + # auto-generated layers) + if self.symbol: + name = 'tf.' + self.symbol + else: + name = self.function.__name__ + kwargs['name'] = K.unique_object_name( + name, zero_based=True, avoid_observed_names=True) + kwargs['autocast'] = False + + # Decorate the function to produce this layer's call method + def _call_wrapper(*args, **kwargs): + return self._call_wrapper(*args, **kwargs) + self.call = tf_decorator.make_decorator(function, _call_wrapper) + + # Do not individually trace op layers in the SavedModel. + self._must_restore_from_config = True + + super(TFOpLambda, self).__init__(**kwargs) + + # Preserve all argument data structures when saving/loading a config + # (e.g., don't unnest lists that contain one element) + self._preserve_input_structure_in_config = True + + # Warning on every invocation will be quite irksome in Eager mode. + self._already_warned = False + + self._expects_training_arg = False + self._expects_mask_arg = False + + def _call_wrapper(self, *args, **kwargs): + created_variables = [] + def _variable_creator(next_creator, **creator_kwargs): + var = next_creator(**creator_kwargs) + created_variables.append(var) + return var + + with backprop.GradientTape(watch_accessed_variables=True) as tape, \ + variable_scope.variable_creator_scope(_variable_creator): + # We explicitly drop `name` arguments here, + # to guard against the case where an op explicitly has a + # `name` passed (which is susceptible to producing + # multiple ops w/ the same name when the layer is reused) + kwargs.pop('name', None) + result = self.function(*args, **kwargs) + self._check_variables(created_variables, tape.watched_variables()) + return result + + def _check_variables(self, created_variables, accessed_variables): + if not created_variables and not accessed_variables: + # In the common case that a Lambda layer does not touch a Variable, we + # don't want to incur the runtime cost of assembling any state used for + # checking only to immediately discard it. + return + + tracked_weights = set(v.ref() for v in self.weights) + untracked_new_vars = [ + v for v in created_variables if v.ref() not in tracked_weights + ] + if untracked_new_vars: + variable_str = '\n'.join(' {}'.format(i) for i in untracked_new_vars) + error_str = textwrap.dedent( + ''' + The following Variables were created within a Lambda layer ({name}) + but are not tracked by said layer: + {variable_str} + The layer cannot safely ensure proper Variable reuse across multiple + calls, and consquently this behavior is disallowed for safety. Lambda + layers are not well suited to stateful computation; instead, writing a + subclassed Layer is the recommend way to define layers with + Variables.''' + ).format(name=self.name, variable_str=variable_str) + raise ValueError(error_str) + + untracked_used_vars = [ + v for v in accessed_variables if v.ref() not in tracked_weights + ] + if untracked_used_vars and not self._already_warned: + variable_str = '\n'.join(' {}'.format(i) for i in untracked_used_vars) + self._warn(textwrap.dedent( + ''' + The following Variables were used a Lambda layer's call ({name}), but + are not present in its tracked objects: + {variable_str} + It is possible that this is intended behavior, but it is more likely + an omission. This is a strong indication that this layer should be + formulated as a subclassed Layer rather than a Lambda layer.''' + ).format(name=self.name, variable_str=variable_str)) + self._already_warned = True + + def _warn(self, msg): + # This method will be overridden in a unit test to raise an error, because + # self.assertWarns is not universally implemented. + return tf_logging.warning(msg) + + def get_config(self): + if not self.symbol: + raise ValueError('This Keras op layer was generated from %s, a method ' + 'that is not an exposed in the TensorFlow API. This ' + 'may have happened if the method was explicitly ' + 'decorated to add dispatching support, and it was used ' + 'during Functional model construction. ' + 'To ensure cross-version compatibility of Keras models ' + 'that use op layers, only op layers produced from ' + 'exported TF API symbols can be serialized.' + % self.function) + config = { + 'function': self.symbol + } + + base_config = super(TFOpLambda, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() + symbol_name = config['function'] + function = get_symbol_from_name(symbol_name) + if not function: + raise ValueError( + 'TF symbol `tf.%s` could not be found.' % symbol_name) + + config['function'] = function + + return cls(**config) + + +class KerasOpDispatcher(dispatch.GlobalOpDispatcher): + """A global dispatcher that allows building a functional model with TF Ops.""" + + def handle(self, op, args, kwargs): + """Handle the specified operation with the specified arguments.""" + if any( + isinstance(x, keras_tensor.KerasTensor) + for x in nest.flatten([args, kwargs])): + return TFOpLambda(op)(*args, **kwargs) + else: + return self.NOT_SUPPORTED + +KerasOpDispatcher().register() + + +def _slice_to_dict(x): + if isinstance(x, slice): + return {'start': x.start, 'stop': x.stop, 'step': x.step} + return x + + +def _dict_to_slice(x): + if isinstance(x, dict): + return slice(x['start'], x['stop'], x['step']) + return x + + +class SlicingOpLambda(TFOpLambda): + """Wraps TF API symbols in a `Layer` object. + + It is inserted by the Functional API construction whenever users call + a supported TF symbol on KerasTensors. + + Like Lambda layers, this layer tries to raise warnings when it detects users + explicitly use variables in the call. (To let them know + that the layer will not capture the variables). + + This is useful in the case where users do something like: + x = keras.Input(...) + y = tf.Variable(...) + out = x * tf_variable + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, function, **kwargs): + super(SlicingOpLambda, self).__init__(function, **kwargs) + + original_call = self.call + # Decorate the function to produce this layer's call method + def _call_wrapper(*args, **kwargs): + # Turn any slice dicts in the args back into `slice` objects. + # This conversion cannot use nest.flatten/map_structure, + # because dicts are flattened by nest while slices aren't. + # So, map_structure would only see the individual elements in the + # dict. + # This can't use map_structure_up_to either because the 'shallowness' of + # the shallow tree would have to vary depending on if only one dim or + # multiple are being sliced. + new_args = [] + for arg in args: + arg = _dict_to_slice(arg) + if isinstance(arg, (list, tuple)): + new_arg = [] + for sub_arg in arg: + new_arg.append(_dict_to_slice(sub_arg)) + arg = new_arg + new_args.append(arg) + + # Handle the kwargs too. + new_kwargs = {} + for key, value in kwargs.items(): + value = _dict_to_slice(value) + if isinstance(value, (list, tuple)): + new_value = [] + for v in value: + new_value.append(_dict_to_slice(v)) + value = new_value + new_kwargs[key] = value + + return original_call(*new_args, **new_kwargs) + self.call = tf_decorator.make_decorator(original_call, _call_wrapper) + + +class TFSlicingOpDispatcher(dispatch.OpDispatcher): + """A global dispatcher that allows building a functional model with TF Ops.""" + + def __init__(self, op): + self.op = op + + def handle(self, args, kwargs): + """Handle the specified operation with the specified arguments.""" + args = nest.map_structure(_slice_to_dict, args) + kwargs = nest.map_structure(_slice_to_dict, kwargs) + if any( + isinstance(x, keras_tensor.KerasTensor) + for x in nest.flatten([args, kwargs])): + return SlicingOpLambda(self.op)(*args, **kwargs) + else: + return self.NOT_SUPPORTED + +for slicing_op in [ + array_ops._slice_helper, # pylint: disable=protected-access + array_ops.boolean_mask, + array_ops.boolean_mask_v2, + ragged_getitem.ragged_tensor_getitem +]: + TFSlicingOpDispatcher(slicing_op).register(slicing_op) + + +class InstanceProperty(Layer): + """Wraps an instance property access (e.g. `x.foo`) in a Keras Layer. + + This layer takes an attribute name `attr_name` in the constructor and, + when called on input tensor `obj` returns `obj.attr_name`. + + KerasTensors specialized for specific extension types use it to + represent instance property accesses on the represented object in the + case where the property needs to be dynamically accessed as opposed to + being statically computed from the typespec, e.g. + + x = keras.Input(..., ragged=True) + out = x.flat_values + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, attr_name, **kwargs): + self.attr_name = attr_name + + if 'name' not in kwargs: + kwargs['name'] = K.unique_object_name( + 'input.' + self.attr_name, zero_based=True, avoid_observed_names=True) + kwargs['autocast'] = False + + # Do not individually trace op layers in the SavedModel. + self._must_restore_from_config = True + + super(InstanceProperty, self).__init__(**kwargs) + + # Preserve all argument data structures when saving/loading a config + # (e.g., don't unnest lists that contain one element) + self._preserve_input_structure_in_config = True + + def call(self, obj): + return getattr(obj, self.attr_name) + + def get_config(self): + config = { + 'attr_name': self.attr_name + } + base_config = super(InstanceProperty, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + return cls(**config) + + +class InstanceMethod(InstanceProperty): + """Wraps an instance method access (e.g. `x.foo(arg)` in a Keras Layer. + + This layer takes an attribute name `attr_name` in the constructor and, + when called on input tensor `obj` with additional arguments `args` and + `kwargs` returns `obj.attr_name(*args, **kwargs)`. + + KerasTensors specialized for specific extension types use it to + represent dynamic instance method calls on the represented object, e.g. + + x = keras.Input(..., ragged=True) + new_values = keras.Input(...) + out = x.with_values(new_values) + """ + + def call(self, obj, args, kwargs): + method = getattr(obj, self.attr_name) + return method(*args, **kwargs) + + +def _delegate_property(keras_tensor_cls, property_name): # pylint: disable=invalid-name + """Register property on a KerasTensor class. + + Calling this multiple times with the same arguments should be a no-op. + + This method exposes a property on the KerasTensor class that will use an + `InstanceProperty` layer to access the property on the represented + intermediate values in the model. + + Args: + keras_tensor_cls: The KerasTensor subclass that should expose the property. + property_name: The name of the property to expose and delegate to the + represented (Composite)Tensor. + """ + # We use a lambda because we can't create a Keras layer at import time + # due to dynamic layer class versioning. + property_access = property(lambda self: InstanceProperty(property_name)(self)) # pylint: disable=unnecessary-lambda + setattr(keras_tensor_cls, property_name, property_access) + + +def _delegate_method(keras_tensor_cls, method_name): # pylint: disable=invalid-name + """Register method on a KerasTensor class. + + Calling this function times with the same arguments should be a no-op. + + This method exposes an instance method on the KerasTensor class that will use + an `InstanceMethod` layer to run the desired method on the represented + intermediate values in the model. + + Args: + keras_tensor_cls: The KerasTensor subclass that should expose the property. + method_name: The name of the method to expose and delegate to the + represented (Composite)Tensor. + """ + def delegate(self, *args, **kwargs): + return InstanceMethod(method_name)(self, args, kwargs) + setattr(keras_tensor_cls, method_name, delegate) + +# We do not support the `uniform_row_length` property because it +# returns either `None` or an int tensor, and code that relies on it tends +# to check `is None` directly. Delegating it here would always return a +# `KerasTensor`, regardless of what can be statically inferred. This would +# never equal `None`, breaking code that expects it to be partially-static +# in unpredictable ways. +for ragged_property in [ + 'values', + 'flat_values', + 'row_splits', + 'nested_row_splits' +]: + _delegate_property(keras_tensor.RaggedKerasTensor, ragged_property) + +for ragged_method_name in [ + 'value_rowids', + 'nested_value_rowids', + 'nrows', + 'row_starts', + 'row_limits', + 'row_lengths', + 'nested_row_lengths', + 'bounding_shape', + 'with_values', + 'with_flat_values', + 'with_row_splits_dtype', + 'merge_dims', + 'to_tensor', + 'to_sparse', +]: + _delegate_method(keras_tensor.RaggedKerasTensor, ragged_method_name) + +for sparse_property in [ + 'indices', + 'values', +]: + _delegate_property(keras_tensor.SparseKerasTensor, sparse_property) + +for sparse_method in [ + 'with_values', +]: + _delegate_method(keras_tensor.SparseKerasTensor, sparse_method) + + +class ClassMethod(Layer): + """Wraps a TF API Class's class method in a `Layer` object. + + It is inserted by the Functional API construction whenever users call + a supported TF Class's class method on KerasTensors. + + This is useful in the case where users do something like: + x = keras.Input(...) + y = keras.Input(...) + out = tf.RaggedTensor.from_row_splits(x, y) + """ + + @trackable.no_automatic_dependency_tracking + def __init__(self, cls_ref, method_name, **kwargs): + self.cls_ref = cls_ref + self.method_name = method_name + self.cls_symbol = ( + get_canonical_name_for_symbol(self.cls_ref, + add_prefix_to_v1_names=True) or + get_canonical_name_for_symbol(self.cls_ref, + api_name='keras', + add_prefix_to_v1_names=True)) + if 'name' not in kwargs: + kwargs['name'] = K.unique_object_name( + 'tf.' + self.cls_symbol + '.' + self.method_name, zero_based=True, + avoid_observed_names=True) + kwargs['autocast'] = False + + # Do not individually trace op layers in the SavedModel. + self._must_restore_from_config = True + + super(ClassMethod, self).__init__(**kwargs) + + # Preserve all argument data structures when saving/loading a config + # (e.g., don't unnest lists that contain one element) + self._preserve_input_structure_in_config = True + + self._expects_training_arg = False + self._expects_mask_arg = False + + def call(self, args, kwargs): + return getattr(self.cls_ref, self.method_name)(*args, **kwargs) + + def get_config(self): + if not self.cls_symbol: + raise ValueError('This Keras class method conversion tried to convert ' + 'a method belonging to class %s, a class ' + 'that is not an exposed in the TensorFlow API. ' + 'To ensure cross-version compatibility of Keras models ' + 'that use op layers, only op layers produced from ' + 'exported TF API symbols can be serialized.' + % self.cls_symbol) + config = { + 'cls_symbol': self.cls_symbol, + 'method_name': self.method_name + } + + base_config = super(ClassMethod, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() + symbol_name = config.pop('cls_symbol') + cls_ref = get_symbol_from_name(symbol_name) + if not cls_ref: + raise ValueError( + 'TF symbol `tf.%s` could not be found.' % symbol_name) + + config['cls_ref'] = cls_ref + + return cls(**config) + + +class TFClassMethodDispatcher(dispatch.OpDispatcher): + """A class method dispatcher that allows building a functional model with TF class methods.""" + + def __init__(self, cls, method_name): + self.cls = cls + self.method_name = method_name + + def handle(self, args, kwargs): + """Handle the specified operation with the specified arguments.""" + if any( + isinstance(x, keras_tensor.KerasTensor) + for x in nest.flatten([args, kwargs])): + return ClassMethod(self.cls, self.method_name)(args[1:], kwargs) + else: + return self.NOT_SUPPORTED + +for ragged_class_method in [ + 'from_value_rowids', + 'from_row_splits', + 'from_row_lengths', + 'from_row_starts', + 'from_row_limits', + 'from_uniform_row_length', + 'from_nested_value_rowids', + 'from_nested_row_splits', + 'from_nested_row_lengths', + 'from_tensor', + 'from_sparse', +]: + TFClassMethodDispatcher( + ragged_tensor.RaggedTensor, ragged_class_method).register( + getattr(ragged_tensor.RaggedTensor, ragged_class_method)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/dense_attention.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/dense_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..08dd07c89fc9f7b9ac866879c43b74c40f9e7099 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/dense_attention.py @@ -0,0 +1,519 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Attention layers that can be used in sequence DNN/CNN models. + +This file follows the terminology of https://arxiv.org/abs/1706.03762 Figure 2. +Attention is formed by three tensors: Query, Key and Value. +""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn + + +class BaseDenseAttention(Layer): + """Base Attention class for Dense networks. + + This class is suitable for Dense or CNN networks, and not for RNN networks. + + Implementations of attention mechanisms should inherit from this class, and + reuse the `apply_attention_scores()` method. + + Args: + causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such + that position `i` cannot attend to positions `j > i`. This prevents the + flow of information from the future towards the past. + dropout: Float between 0 and 1. Fraction of the units to drop for the + attention scores. + + Call Args: + + inputs: List of the following tensors: + * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. + * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. + * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not + given, will use `value` for both `key` and `value`, which is the + most common case. + mask: List of the following tensors: + * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. + If given, the output will be zero at the positions where + `mask==False`. + * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. + If given, will apply the mask such that values at positions where + `mask==False` do not contribute to the result. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (no dropout). + return_attention_scores: bool, it `True`, returns the attention scores + (after masking and softmax) as an additional output argument. + + Output: + + Attention outputs of shape `[batch_size, Tq, dim]`. + [Optional] Attention scores after masking and softmax with shape + `[batch_size, Tq, Tv]`. + """ + + def __init__(self, causal=False, dropout=0.0, + **kwargs): + super(BaseDenseAttention, self).__init__(**kwargs) + self.causal = causal + self.dropout = dropout + self.supports_masking = True + + def _calculate_scores(self, query, key): + """Calculates attention scores. + + Args: + query: Query tensor of shape `[batch_size, Tq, dim]`. + key: Key tensor of shape `[batch_size, Tv, dim]`. + + Returns: + Tensor of shape `[batch_size, Tq, Tv]`. + """ + return NotImplementedError + + def _apply_scores(self, scores, value, scores_mask=None, training=None): + """Applies attention scores to the given value tensor. + + To use this method in your attention layer, follow the steps: + + * Use `query` tensor of shape `[batch_size, Tq]` and `key` tensor of shape + `[batch_size, Tv]` to calculate the attention `scores`. + * Pass `scores` and `value` tensors to this method. The method applies + `scores_mask`, calculates `attention_distribution = softmax(scores)`, then + returns `matmul(attention_distribution, value). + * Apply `query_mask` and return the result. + + Args: + scores: Scores float tensor of shape `[batch_size, Tq, Tv]`. + value: Value tensor of shape `[batch_size, Tv, dim]`. + scores_mask: A boolean mask `Tensor` of shape `[batch_size, 1, Tv]` or + `[batch_size, Tq, Tv]`. If given, scores at positions where + `scores_mask==False` do not contribute to the result. It must contain + at least one `True` value in each line along the last dimension. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (no dropout). + + Returns: + Tensor of shape `[batch_size, Tq, dim]`. + Attention scores after masking and softmax with shape + `[batch_size, Tq, Tv]`. + """ + if scores_mask is not None: + padding_mask = math_ops.logical_not(scores_mask) + # Bias so padding positions do not contribute to attention distribution. + # Note 65504. is the max float16 value. + if scores.dtype is dtypes.float16: + scores -= 65504. * math_ops.cast(padding_mask, dtype=scores.dtype) + else: + scores -= 1.e9 * math_ops.cast(padding_mask, dtype=scores.dtype) + if training is None: + training = backend.learning_phase() + weights = nn.softmax(scores) + + def dropped_weights(): + return nn.dropout(weights, rate=self.dropout) + + weights = control_flow_util.smart_cond(training, dropped_weights, + lambda: array_ops.identity(weights)) + return math_ops.matmul(weights, value), weights + + # TODO(b/125916026): Consider exposing a __call__ method with named args. + def call(self, + inputs, + mask=None, + training=None, + return_attention_scores=False): + self._validate_call_args(inputs=inputs, mask=mask) + q = inputs[0] + v = inputs[1] + k = inputs[2] if len(inputs) > 2 else v + q_mask = mask[0] if mask else None + v_mask = mask[1] if mask else None + scores = self._calculate_scores(query=q, key=k) + if v_mask is not None: + # Mask of shape [batch_size, 1, Tv]. + v_mask = array_ops.expand_dims(v_mask, axis=-2) + if self.causal: + # Creates a lower triangular mask, so position i cannot attend to + # positions j>i. This prevents the flow of information from the future + # into the past. + scores_shape = array_ops.shape(scores) + # causal_mask_shape = [1, Tq, Tv]. + causal_mask_shape = array_ops.concat( + [array_ops.ones_like(scores_shape[:-2]), scores_shape[-2:]], + axis=0) + causal_mask = _lower_triangular_mask(causal_mask_shape) + else: + causal_mask = None + scores_mask = _merge_masks(v_mask, causal_mask) + result, attention_scores = self._apply_scores( + scores=scores, value=v, scores_mask=scores_mask, training=training) + if q_mask is not None: + # Mask of shape [batch_size, Tq, 1]. + q_mask = array_ops.expand_dims(q_mask, axis=-1) + result *= math_ops.cast(q_mask, dtype=result.dtype) + if return_attention_scores: + return result, attention_scores + return result + + def compute_mask(self, inputs, mask=None): + self._validate_call_args(inputs=inputs, mask=mask) + if mask: + q_mask = mask[0] + if q_mask is None: + return None + return tensor_conversion.convert_to_tensor_v2_with_dispatch(q_mask) + return None + + def _validate_call_args(self, inputs, mask): + """Validates arguments of the call method.""" + class_name = self.__class__.__name__ + if not isinstance(inputs, list): + raise ValueError( + '{} layer must be called on a list of inputs, namely [query, value] ' + 'or [query, value, key].'.format(class_name)) + if len(inputs) < 2 or len(inputs) > 3: + raise ValueError( + '{} layer accepts inputs list of length 2 or 3, ' + 'namely [query, value] or [query, value, key]. ' + 'Given length: {}'.format(class_name, len(inputs))) + if mask: + if not isinstance(mask, list): + raise ValueError( + '{} layer mask must be a list, ' + 'namely [query_mask, value_mask].'.format(class_name)) + if len(mask) < 2 or len(mask) > len(inputs): + raise ValueError( + '{} layer mask must be a list of length 2, namely [query_mask, ' + 'value_mask]. Given length: {}'.format(class_name, len(mask))) + + def get_config(self): + config = { + 'causal': self.causal, + 'dropout': self.dropout, + } + base_config = super(BaseDenseAttention, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Attention(BaseDenseAttention): + """Dot-product attention layer, a.k.a. Luong-style attention. + + Inputs are `query` tensor of shape `[batch_size, Tq, dim]`, `value` tensor of + shape `[batch_size, Tv, dim]` and `key` tensor of shape + `[batch_size, Tv, dim]`. The calculation follows the steps: + + 1. Calculate scores with shape `[batch_size, Tq, Tv]` as a `query`-`key` dot + product: `scores = tf.matmul(query, key, transpose_b=True)`. + 2. Use scores to calculate a distribution with shape + `[batch_size, Tq, Tv]`: `distribution = tf.nn.softmax(scores)`. + 3. Use `distribution` to create a linear combination of `value` with + shape `[batch_size, Tq, dim]`: + `return tf.matmul(distribution, value)`. + + Args: + use_scale: If `True`, will create a scalar variable to scale the attention + scores. + causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such + that position `i` cannot attend to positions `j > i`. This prevents the + flow of information from the future towards the past. + dropout: Float between 0 and 1. Fraction of the units to drop for the + attention scores. + + Call Args: + + inputs: List of the following tensors: + * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. + * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. + * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not + given, will use `value` for both `key` and `value`, which is the + most common case. + mask: List of the following tensors: + * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. + If given, the output will be zero at the positions where + `mask==False`. + * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. + If given, will apply the mask such that values at positions where + `mask==False` do not contribute to the result. + return_attention_scores: bool, it `True`, returns the attention scores + (after masking and softmax) as an additional output argument. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (no dropout). + + Output: + + Attention outputs of shape `[batch_size, Tq, dim]`. + [Optional] Attention scores after masking and softmax with shape + `[batch_size, Tq, Tv]`. + + The meaning of `query`, `value` and `key` depend on the application. In the + case of text similarity, for example, `query` is the sequence embeddings of + the first piece of text and `value` is the sequence embeddings of the second + piece of text. `key` is usually the same tensor as `value`. + + Here is a code example for using `Attention` in a CNN+Attention network: + + ```python + # Variable-length int sequences. + query_input = tf.keras.Input(shape=(None,), dtype='int32') + value_input = tf.keras.Input(shape=(None,), dtype='int32') + + # Embedding lookup. + token_embedding = tf.keras.layers.Embedding(input_dim=1000, output_dim=64) + # Query embeddings of shape [batch_size, Tq, dimension]. + query_embeddings = token_embedding(query_input) + # Value embeddings of shape [batch_size, Tv, dimension]. + value_embeddings = token_embedding(value_input) + + # CNN layer. + cnn_layer = tf.keras.layers.Conv1D( + filters=100, + kernel_size=4, + # Use 'same' padding so outputs have the same shape as inputs. + padding='same') + # Query encoding of shape [batch_size, Tq, filters]. + query_seq_encoding = cnn_layer(query_embeddings) + # Value encoding of shape [batch_size, Tv, filters]. + value_seq_encoding = cnn_layer(value_embeddings) + + # Query-value attention of shape [batch_size, Tq, filters]. + query_value_attention_seq = tf.keras.layers.Attention()( + [query_seq_encoding, value_seq_encoding]) + + # Reduce over the sequence axis to produce encodings of shape + # [batch_size, filters]. + query_encoding = tf.keras.layers.GlobalAveragePooling1D()( + query_seq_encoding) + query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( + query_value_attention_seq) + + # Concatenate query and document encodings to produce a DNN input layer. + input_layer = tf.keras.layers.Concatenate()( + [query_encoding, query_value_attention]) + + # Add DNN layers, and create Model. + # ... + ``` + """ + + def __init__(self, use_scale=False, **kwargs): + super(Attention, self).__init__(**kwargs) + self.use_scale = use_scale + + def build(self, input_shape): + """Creates scale variable if use_scale==True.""" + if self.use_scale: + self.scale = self.add_weight( + name='scale', + shape=(), + initializer=init_ops.ones_initializer(), + dtype=self.dtype, + trainable=True) + else: + self.scale = None + super(Attention, self).build(input_shape) + + def _calculate_scores(self, query, key): + """Calculates attention scores as a query-key dot product. + + Args: + query: Query tensor of shape `[batch_size, Tq, dim]`. + key: Key tensor of shape `[batch_size, Tv, dim]`. + Returns: + Tensor of shape `[batch_size, Tq, Tv]`. + """ + scores = math_ops.matmul(query, key, transpose_b=True) + if self.scale is not None: + scores *= self.scale + return scores + + def get_config(self): + config = {'use_scale': self.use_scale} + base_config = super(Attention, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class AdditiveAttention(BaseDenseAttention): + """Additive attention layer, a.k.a. Bahdanau-style attention. + + Inputs are `query` tensor of shape `[batch_size, Tq, dim]`, `value` tensor of + shape `[batch_size, Tv, dim]` and `key` tensor of shape + `[batch_size, Tv, dim]`. The calculation follows the steps: + + 1. Reshape `query` and `value` into shapes `[batch_size, Tq, 1, dim]` + and `[batch_size, 1, Tv, dim]` respectively. + 2. Calculate scores with shape `[batch_size, Tq, Tv]` as a non-linear + sum: `scores = tf.reduce_sum(tf.tanh(query + value), axis=-1)` + 3. Use scores to calculate a distribution with shape + `[batch_size, Tq, Tv]`: `distribution = tf.nn.softmax(scores)`. + 4. Use `distribution` to create a linear combination of `value` with + shape `[batch_size, Tq, dim]`: + `return tf.matmul(distribution, value)`. + + Args: + use_scale: If `True`, will create a variable to scale the attention scores. + causal: Boolean. Set to `True` for decoder self-attention. Adds a mask such + that position `i` cannot attend to positions `j > i`. This prevents the + flow of information from the future towards the past. + dropout: Float between 0 and 1. Fraction of the units to drop for the + attention scores. + + Call Args: + + inputs: List of the following tensors: + * query: Query `Tensor` of shape `[batch_size, Tq, dim]`. + * value: Value `Tensor` of shape `[batch_size, Tv, dim]`. + * key: Optional key `Tensor` of shape `[batch_size, Tv, dim]`. If not + given, will use `value` for both `key` and `value`, which is the + most common case. + mask: List of the following tensors: + * query_mask: A boolean mask `Tensor` of shape `[batch_size, Tq]`. + If given, the output will be zero at the positions where + `mask==False`. + * value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`. + If given, will apply the mask such that values at positions where + `mask==False` do not contribute to the result. + training: Python boolean indicating whether the layer should behave in + training mode (adding dropout) or in inference mode (no dropout). + return_attention_scores: bool, it `True`, returns the attention scores + (after masking and softmax) as an additional output argument. + + Output: + + Attention outputs of shape `[batch_size, Tq, dim]`. + [Optional] Attention scores after masking and softmax with shape + `[batch_size, Tq, Tv]`. + + The meaning of `query`, `value` and `key` depend on the application. In the + case of text similarity, for example, `query` is the sequence embeddings of + the first piece of text and `value` is the sequence embeddings of the second + piece of text. `key` is usually the same tensor as `value`. + + Here is a code example for using `AdditiveAttention` in a CNN+Attention + network: + + ```python + # Variable-length int sequences. + query_input = tf.keras.Input(shape=(None,), dtype='int32') + value_input = tf.keras.Input(shape=(None,), dtype='int32') + + # Embedding lookup. + token_embedding = tf.keras.layers.Embedding(max_tokens, dimension) + # Query embeddings of shape [batch_size, Tq, dimension]. + query_embeddings = token_embedding(query_input) + # Value embeddings of shape [batch_size, Tv, dimension]. + value_embeddings = token_embedding(value_input) + + # CNN layer. + cnn_layer = tf.keras.layers.Conv1D( + filters=100, + kernel_size=4, + # Use 'same' padding so outputs have the same shape as inputs. + padding='same') + # Query encoding of shape [batch_size, Tq, filters]. + query_seq_encoding = cnn_layer(query_embeddings) + # Value encoding of shape [batch_size, Tv, filters]. + value_seq_encoding = cnn_layer(value_embeddings) + + # Query-value attention of shape [batch_size, Tq, filters]. + query_value_attention_seq = tf.keras.layers.AdditiveAttention()( + [query_seq_encoding, value_seq_encoding]) + + # Reduce over the sequence axis to produce encodings of shape + # [batch_size, filters]. + query_encoding = tf.keras.layers.GlobalAveragePooling1D()( + query_seq_encoding) + query_value_attention = tf.keras.layers.GlobalAveragePooling1D()( + query_value_attention_seq) + + # Concatenate query and document encodings to produce a DNN input layer. + input_layer = tf.keras.layers.Concatenate()( + [query_encoding, query_value_attention]) + + # Add DNN layers, and create Model. + # ... + ``` + """ + + def __init__(self, use_scale=True, **kwargs): + super(AdditiveAttention, self).__init__(**kwargs) + self.use_scale = use_scale + + def build(self, input_shape): + v_shape = tensor_shape.TensorShape(input_shape[1]) + dim = v_shape[-1] + if isinstance(dim, tensor_shape.Dimension): + dim = dim.value + if self.use_scale: + self.scale = self.add_weight( + name='scale', + shape=[dim], + initializer=init_ops.glorot_uniform_initializer(), + dtype=self.dtype, + trainable=True) + else: + self.scale = None + super(AdditiveAttention, self).build(input_shape) + + def _calculate_scores(self, query, key): + """Calculates attention scores as a nonlinear sum of query and key. + + Args: + query: Query tensor of shape `[batch_size, Tq, dim]`. + key: Key tensor of shape `[batch_size, Tv, dim]`. + Returns: + Tensor of shape `[batch_size, Tq, Tv]`. + """ + # Reshape tensors to enable broadcasting. + # Reshape into [batch_size, Tq, 1, dim]. + q_reshaped = array_ops.expand_dims(query, axis=-2) + # Reshape into [batch_size, 1, Tv, dim]. + k_reshaped = array_ops.expand_dims(key, axis=-3) + if self.use_scale: + scale = self.scale + else: + scale = 1. + return math_ops.reduce_sum( + scale * math_ops.tanh(q_reshaped + k_reshaped), axis=-1) + + def get_config(self): + config = {'use_scale': self.use_scale} + base_config = super(AdditiveAttention, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +def _lower_triangular_mask(shape): + """Creates a lower-triangular boolean mask over the last 2 dimensions.""" + row_index = math_ops.cumsum( + array_ops.ones(shape=shape, dtype=dtypes.int32), axis=-2) + col_index = math_ops.cumsum( + array_ops.ones(shape=shape, dtype=dtypes.int32), axis=-1) + return math_ops.greater_equal(row_index, col_index) + + +def _merge_masks(x, y): + if x is None: + return y + if y is None: + return x + return math_ops.logical_and(x, y) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/embeddings.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a193cfd3de5bd082ff74a5406adf1b43b0cbb46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/embeddings.py @@ -0,0 +1,212 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Embedding layer.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import math_ops + + +class Embedding(Layer): + """Turns positive integers (indexes) into dense vectors of fixed size. + + e.g. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]` + + This layer can only be used as the first layer in a model. + + Example: + + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Embedding(1000, 64, input_length=10)) + >>> # The model will take as input an integer matrix of size (batch, + >>> # input_length), and the largest integer (i.e. word index) in the input + >>> # should be no larger than 999 (vocabulary size). + >>> # Now model.output_shape is (None, 10, 64), where `None` is the batch + >>> # dimension. + >>> input_array = np.random.randint(1000, size=(32, 10)) + >>> model.compile('rmsprop', 'mse') + >>> output_array = model.predict(input_array) + >>> print(output_array.shape) + (32, 10, 64) + + Args: + input_dim: Integer. Size of the vocabulary, + i.e. maximum integer index + 1. + output_dim: Integer. Dimension of the dense embedding. + embeddings_initializer: Initializer for the `embeddings` + matrix (see `keras.initializers`). + embeddings_regularizer: Regularizer function applied to + the `embeddings` matrix (see `keras.regularizers`). + embeddings_constraint: Constraint function applied to + the `embeddings` matrix (see `keras.constraints`). + mask_zero: Boolean, whether or not the input value 0 is a special "padding" + value that should be masked out. + This is useful when using recurrent layers + which may take variable length input. + If this is `True`, then all subsequent layers + in the model need to support masking or an exception will be raised. + If mask_zero is set to True, as a consequence, index 0 cannot be + used in the vocabulary (input_dim should equal size of + vocabulary + 1). + input_length: Length of input sequences, when it is constant. + This argument is required if you are going to connect + `Flatten` then `Dense` layers upstream + (without it, the shape of the dense outputs cannot be computed). + + Input shape: + 2D tensor with shape: `(batch_size, input_length)`. + + Output shape: + 3D tensor with shape: `(batch_size, input_length, output_dim)`. + + **Note on variable placement:** + By default, if a GPU is available, the embedding matrix will be placed on + the GPU. This achieves the best performance, but it might cause issues: + + - You may be using an optimizer that does not support sparse GPU kernels. + In this case you will see an error upon training your model. + - Your embedding matrix may be too large to fit on your GPU. In this case + you will see an Out Of Memory (OOM) error. + + In such cases, you should place the embedding matrix on the CPU memory. + You can do so with a device scope, as such: + + ```python + with tf.device('cpu:0'): + embedding_layer = Embedding(...) + embedding_layer.build() + ``` + + The pre-built `embedding_layer` instance can then be added to a `Sequential` + model (e.g. `model.add(embedding_layer)`), called in a Functional model + (e.g. `x = embedding_layer(x)`), or used in a subclassed model. + """ + + def __init__(self, + input_dim, + output_dim, + embeddings_initializer='uniform', + embeddings_regularizer=None, + activity_regularizer=None, + embeddings_constraint=None, + mask_zero=False, + input_length=None, + **kwargs): + if 'input_shape' not in kwargs: + if input_length: + kwargs['input_shape'] = (input_length,) + else: + kwargs['input_shape'] = (None,) + if input_dim <= 0 or output_dim <= 0: + raise ValueError('Both `input_dim` and `output_dim` should be positive, ' + 'found input_dim {} and output_dim {}'.format( + input_dim, output_dim)) + if (not base_layer_utils.v2_dtype_behavior_enabled() and + 'dtype' not in kwargs): + # In TF1, the dtype defaults to the input dtype which is typically int32, + # so explicitly set it to floatx + kwargs['dtype'] = backend.floatx() + # We set autocast to False, as we do not want to cast floating- point inputs + # to self.dtype. In call(), we cast to int32, and casting to self.dtype + # before casting to int32 might cause the int32 values to be different due + # to a loss of precision. + kwargs['autocast'] = False + super(Embedding, self).__init__(**kwargs) + + self.input_dim = input_dim + self.output_dim = output_dim + self.embeddings_initializer = initializers.get(embeddings_initializer) + self.embeddings_regularizer = regularizers.get(embeddings_regularizer) + self.activity_regularizer = regularizers.get(activity_regularizer) + self.embeddings_constraint = constraints.get(embeddings_constraint) + self.mask_zero = mask_zero + self.supports_masking = mask_zero + self.input_length = input_length + + @tf_utils.shape_type_conversion + def build(self, input_shape=None): + self.embeddings = self.add_weight( + shape=(self.input_dim, self.output_dim), + initializer=self.embeddings_initializer, + name='embeddings', + regularizer=self.embeddings_regularizer, + constraint=self.embeddings_constraint, + experimental_autocast=False) + self.built = True + + def compute_mask(self, inputs, mask=None): + if not self.mask_zero: + return None + return math_ops.not_equal(inputs, 0) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if self.input_length is None: + return input_shape + (self.output_dim,) + else: + # input_length can be tuple if input is 3D or higher + if isinstance(self.input_length, (list, tuple)): + in_lens = list(self.input_length) + else: + in_lens = [self.input_length] + if len(in_lens) != len(input_shape) - 1: + raise ValueError('"input_length" is %s, ' + 'but received input has shape %s' % (str( + self.input_length), str(input_shape))) + else: + for i, (s1, s2) in enumerate(zip(in_lens, input_shape[1:])): + if s1 is not None and s2 is not None and s1 != s2: + raise ValueError('"input_length" is %s, ' + 'but received input has shape %s' % (str( + self.input_length), str(input_shape))) + elif s1 is None: + in_lens[i] = s2 + return (input_shape[0],) + tuple(in_lens) + (self.output_dim,) + + def call(self, inputs): + dtype = backend.dtype(inputs) + if dtype != 'int32' and dtype != 'int64': + inputs = math_ops.cast(inputs, 'int32') + out = embedding_ops.embedding_lookup_v2(self.embeddings, inputs) + if self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype: + # Instead of casting the variable as in most layers, cast the output, as + # this is mathematically equivalent but is faster. + out = math_ops.cast(out, self._dtype_policy.compute_dtype) + return out + + def get_config(self): + config = { + 'input_dim': self.input_dim, + 'output_dim': self.output_dim, + 'embeddings_initializer': + initializers.serialize(self.embeddings_initializer), + 'embeddings_regularizer': + regularizers.serialize(self.embeddings_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'embeddings_constraint': + constraints.serialize(self.embeddings_constraint), + 'mask_zero': self.mask_zero, + 'input_length': self.input_length + } + base_config = super(Embedding, self).get_config() + return dict(list(base_config.items()) + list(config.items())) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a00f532bbb369bfae35c158092615d50c10130 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py @@ -0,0 +1,1373 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-classes-have-attributes +"""Module implementing RNN Cells. + +This module provides a number of basic commonly used RNN cells, such as LSTM +(Long Short Term Memory) or GRU (Gated Recurrent Unit), and a number of +operators that allow adding dropouts, projections, or embeddings for inputs. +Constructing multi-layer cells is supported by the class `MultiRNNCell`, or by +calling the `rnn` ops several times. +""" +import collections +import warnings + +from tensorflow.python.eager import context +from tensorflow.python.framework import config as tf_config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend +from tensorflow.python.keras import initializers +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.layers.legacy_rnn import rnn_cell_wrapper_impl +from tensorflow.python.keras.legacy_tf_layers import base as base_layer +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import partitioned_variables +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +_BIAS_VARIABLE_NAME = "bias" +_WEIGHTS_VARIABLE_NAME = "kernel" + +# This can be used with self.assertRaisesRegexp for assert_like_rnncell. +ASSERT_LIKE_RNNCELL_ERROR_REGEXP = "is not an RNNCell" + + +def _hasattr(obj, attr_name): + try: + getattr(obj, attr_name) + except AttributeError: + return False + else: + return True + + +def assert_like_rnncell(cell_name, cell): + """Raises a TypeError if cell is not like an RNNCell. + + NOTE: Do not rely on the error message (in particular in tests) which can be + subject to change to increase readability. Use + ASSERT_LIKE_RNNCELL_ERROR_REGEXP. + + Args: + cell_name: A string to give a meaningful error referencing to the name of + the functionargument. + cell: The object which should behave like an RNNCell. + + Raises: + TypeError: A human-friendly exception. + """ + conditions = [ + _hasattr(cell, "output_size"), + _hasattr(cell, "state_size"), + _hasattr(cell, "get_initial_state") or _hasattr(cell, "zero_state"), + callable(cell), + ] + errors = [ + "'output_size' property is missing", "'state_size' property is missing", + "either 'zero_state' or 'get_initial_state' method is required", + "is not callable" + ] + + if not all(conditions): + + errors = [error for error, cond in zip(errors, conditions) if not cond] + raise TypeError("The argument {!r} ({}) is not an RNNCell: {}.".format( + cell_name, cell, ", ".join(errors))) + + +def _concat(prefix, suffix, static=False): + """Concat that enables int, Tensor, or TensorShape values. + + This function takes a size specification, which can be an integer, a + TensorShape, or a Tensor, and converts it into a concatenated Tensor + (if static = False) or a list of integers (if static = True). + + Args: + prefix: The prefix; usually the batch size (and/or time step size). + (TensorShape, int, or Tensor.) + suffix: TensorShape, int, or Tensor. + static: If `True`, return a python list with possibly unknown dimensions. + Otherwise return a `Tensor`. + + Returns: + shape: the concatenation of prefix and suffix. + + Raises: + ValueError: if `suffix` is not a scalar or vector (or TensorShape). + ValueError: if prefix or suffix was `None` and asked for dynamic + Tensors out. + """ + if isinstance(prefix, tensor.Tensor): + p = prefix + p_static = tensor_util.constant_value(prefix) + if p.shape.ndims == 0: + p = array_ops.expand_dims(p, 0) + elif p.shape.ndims != 1: + raise ValueError("prefix tensor must be either a scalar or vector, " + "but saw tensor: %s" % p) + else: + p = tensor_shape.TensorShape(prefix) + p_static = p.as_list() if p.ndims is not None else None + p = ( + constant_op.constant(p.as_list(), dtype=dtypes.int32) + if p.is_fully_defined() else None) + if isinstance(suffix, tensor.Tensor): + s = suffix + s_static = tensor_util.constant_value(suffix) + if s.shape.ndims == 0: + s = array_ops.expand_dims(s, 0) + elif s.shape.ndims != 1: + raise ValueError("suffix tensor must be either a scalar or vector, " + "but saw tensor: %s" % s) + else: + s = tensor_shape.TensorShape(suffix) + s_static = s.as_list() if s.ndims is not None else None + s = ( + constant_op.constant(s.as_list(), dtype=dtypes.int32) + if s.is_fully_defined() else None) + + if static: + shape = tensor_shape.TensorShape(p_static).concatenate(s_static) + shape = shape.as_list() if shape.ndims is not None else None + else: + if p is None or s is None: + raise ValueError("Provided a prefix or suffix of None: %s and %s" % + (prefix, suffix)) + shape = array_ops.concat((p, s), 0) + return shape + + +def _zero_state_tensors(state_size, batch_size, dtype): + """Create tensors of zeros based on state_size, batch_size, and dtype.""" + + def get_state_shape(s): + """Combine s with batch_size to get a proper tensor shape.""" + c = _concat(batch_size, s) + size = array_ops.zeros(c, dtype=dtype) + if not context.executing_eagerly(): + c_static = _concat(batch_size, s, static=True) + size.set_shape(c_static) + return size + + return nest.map_structure(get_state_shape, state_size) + + +@tf_export(v1=["nn.rnn_cell.RNNCell"]) +class RNNCell(base_layer.Layer): + """Abstract object representing an RNN cell. + + Every `RNNCell` must have the properties below and implement `call` with + the signature `(output, next_state) = call(input, state)`. The optional + third input argument, `scope`, is allowed for backwards compatibility + purposes; but should be left off for new subclasses. + + This definition of cell differs from the definition used in the literature. + In the literature, 'cell' refers to an object with a single scalar output. + This definition refers to a horizontal array of such units. + + An RNN cell, in the most abstract setting, is anything that has + a state and performs some operation that takes a matrix of inputs. + This operation results in an output matrix with `self.output_size` columns. + If `self.state_size` is an integer, this operation also results in a new + state matrix with `self.state_size` columns. If `self.state_size` is a + (possibly nested tuple of) TensorShape object(s), then it should return a + matching structure of Tensors having shape `[batch_size].concatenate(s)` + for each `s` in `self.batch_size`. + """ + + def __init__(self, trainable=True, name=None, dtype=None, **kwargs): + super(RNNCell, self).__init__( + trainable=trainable, name=name, dtype=dtype, **kwargs) + # Attribute that indicates whether the cell is a TF RNN cell, due the slight + # difference between TF and Keras RNN cell. Notably the state is not wrapped + # in a list for TF cell where they are single tensor state, whereas keras + # cell will wrap the state into a list, and call() will have to unwrap them. + self._is_tf_rnn_cell = True + + def __call__(self, inputs, state, scope=None): + """Run this RNN cell on inputs, starting from the given state. + + Args: + inputs: `2-D` tensor with shape `[batch_size, input_size]`. + state: if `self.state_size` is an integer, this should be a `2-D Tensor` + with shape `[batch_size, self.state_size]`. Otherwise, if + `self.state_size` is a tuple of integers, this should be a tuple with + shapes `[batch_size, s] for s in self.state_size`. + scope: VariableScope for the created subgraph; defaults to class name. + + Returns: + A pair containing: + + - Output: A `2-D` tensor with shape `[batch_size, self.output_size]`. + - New state: Either a single `2-D` tensor, or a tuple of tensors matching + the arity and shapes of `state`. + """ + if scope is not None: + with vs.variable_scope( + scope, custom_getter=self._rnn_get_variable) as scope: + return super(RNNCell, self).__call__(inputs, state, scope=scope) + else: + scope_attrname = "rnncell_scope" + scope = getattr(self, scope_attrname, None) + if scope is None: + scope = vs.variable_scope( + vs.get_variable_scope(), custom_getter=self._rnn_get_variable) + setattr(self, scope_attrname, scope) + with scope: + return super(RNNCell, self).__call__(inputs, state) + + def _rnn_get_variable(self, getter, *args, **kwargs): + variable = getter(*args, **kwargs) + if ops.executing_eagerly_outside_functions(): + trainable = variable.trainable + else: + trainable = ( + variable in tf_variables.trainable_variables() or + (base_layer_utils.is_split_variable(variable) and + list(variable)[0] in tf_variables.trainable_variables())) + if trainable and all(variable is not v for v in self._trainable_weights): + self._trainable_weights.append(variable) + elif not trainable and all( + variable is not v for v in self._non_trainable_weights): + self._non_trainable_weights.append(variable) + return variable + + @property + def state_size(self): + """size(s) of state(s) used by this cell. + + It can be represented by an Integer, a TensorShape or a tuple of Integers + or TensorShapes. + """ + raise NotImplementedError("Abstract method") + + @property + def output_size(self): + """Integer or TensorShape: size of outputs produced by this cell.""" + raise NotImplementedError("Abstract method") + + def build(self, _): + # This tells the parent Layer object that it's OK to call + # self.add_variable() inside the call() method. + pass + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + if inputs is not None: + # Validate the given batch_size and dtype against inputs if provided. + inputs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + inputs, name="inputs" + ) + if batch_size is not None: + if tensor_util.is_tf_type(batch_size): + static_batch_size = tensor_util.constant_value( + batch_size, partial=True) + else: + static_batch_size = batch_size + if inputs.shape.dims[0].value != static_batch_size: + raise ValueError( + "batch size from input tensor is different from the " + "input param. Input tensor batch: {}, batch_size: {}".format( + inputs.shape.dims[0].value, batch_size)) + + if dtype is not None and inputs.dtype != dtype: + raise ValueError( + "dtype from input tensor is different from the " + "input param. Input tensor dtype: {}, dtype: {}".format( + inputs.dtype, dtype)) + + batch_size = inputs.shape.dims[0].value or array_ops.shape(inputs)[0] + dtype = inputs.dtype + if batch_size is None or dtype is None: + raise ValueError( + "batch_size and dtype cannot be None while constructing initial " + "state: batch_size={}, dtype={}".format(batch_size, dtype)) + return self.zero_state(batch_size, dtype) + + def zero_state(self, batch_size, dtype): + """Return zero-filled state tensor(s). + + Args: + batch_size: int, float, or unit Tensor representing the batch size. + dtype: the data type to use for the state. + + Returns: + If `state_size` is an int or TensorShape, then the return value is a + `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. + + If `state_size` is a nested list or tuple, then the return value is + a nested list or tuple (of the same structure) of `2-D` tensors with + the shapes `[batch_size, s]` for each s in `state_size`. + """ + # Try to use the last cached zero_state. This is done to avoid recreating + # zeros, especially when eager execution is enabled. + state_size = self.state_size + is_eager = context.executing_eagerly() + if is_eager and _hasattr(self, "_last_zero_state"): + (last_state_size, last_batch_size, last_dtype, + last_output) = getattr(self, "_last_zero_state") + if (last_batch_size == batch_size and last_dtype == dtype and + last_state_size == state_size): + return last_output + with backend.name_scope(type(self).__name__ + "ZeroState"): + output = _zero_state_tensors(state_size, batch_size, dtype) + if is_eager: + self._last_zero_state = (state_size, batch_size, dtype, output) + return output + + # TODO(b/134773139): Remove when contrib RNN cells implement `get_config` + def get_config(self): # pylint: disable=useless-super-delegation + return super(RNNCell, self).get_config() + + @property + def _use_input_spec_as_call_signature(self): + # We do not store the shape information for the state argument in the call + # function for legacy RNN cells, so do not generate an input signature. + return False + + +class LayerRNNCell(RNNCell): + """Subclass of RNNCells that act like proper `tf.Layer` objects. + + For backwards compatibility purposes, most `RNNCell` instances allow their + `call` methods to instantiate variables via `tf.compat.v1.get_variable`. The + underlying + variable scope thus keeps track of any variables, and returning cached + versions. This is atypical of `tf.layer` objects, which separate this + part of layer building into a `build` method that is only called once. + + Here we provide a subclass for `RNNCell` objects that act exactly as + `Layer` objects do. They must provide a `build` method and their + `call` methods do not access Variables `tf.compat.v1.get_variable`. + """ + + def __call__(self, inputs, state, scope=None, *args, **kwargs): + """Run this RNN cell on inputs, starting from the given state. + + Args: + inputs: `2-D` tensor with shape `[batch_size, input_size]`. + state: if `self.state_size` is an integer, this should be a `2-D Tensor` + with shape `[batch_size, self.state_size]`. Otherwise, if + `self.state_size` is a tuple of integers, this should be a tuple with + shapes `[batch_size, s] for s in self.state_size`. + scope: optional cell scope. + *args: Additional positional arguments. + **kwargs: Additional keyword arguments. + + Returns: + A pair containing: + + - Output: A `2-D` tensor with shape `[batch_size, self.output_size]`. + - New state: Either a single `2-D` tensor, or a tuple of tensors matching + the arity and shapes of `state`. + """ + # Bypass RNNCell's variable capturing semantics for LayerRNNCell. + # Instead, it is up to subclasses to provide a proper build + # method. See the class docstring for more details. + return base_layer.Layer.__call__( + self, inputs, state, scope=scope, *args, **kwargs) + + +@tf_export(v1=["nn.rnn_cell.BasicRNNCell"]) +class BasicRNNCell(LayerRNNCell): + """The most basic RNN cell. + + Note that this cell is not optimized for performance. Please use + `tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU. + + Args: + num_units: int, The number of units in the RNN cell. + activation: Nonlinearity to use. Default: `tanh`. It could also be string + that is within Keras activation function names. + reuse: (optional) Python boolean describing whether to reuse variables in an + existing scope. If not `True`, and the existing scope already has the + given variables, an error is raised. + name: String, the name of the layer. Layers with the same name will share + weights, but to avoid mistakes we require reuse=True in such cases. + dtype: Default dtype of the layer (default of `None` means use the type of + the first input). Required when `build` is called before `call`. + **kwargs: Dict, keyword named properties for common layer attributes, like + `trainable` etc when constructing the cell from configs of get_config(). + """ + + def __init__(self, + num_units, + activation=None, + reuse=None, + name=None, + dtype=None, + **kwargs): + warnings.warn("`tf.nn.rnn_cell.BasicRNNCell` is deprecated and will be " + "removed in a future version. This class " + "is equivalent as `tf.keras.layers.SimpleRNNCell`, " + "and will be replaced by that in Tensorflow 2.0.") + super(BasicRNNCell, self).__init__( + _reuse=reuse, name=name, dtype=dtype, **kwargs) + _check_supported_dtypes(self.dtype) + if context.executing_eagerly() and tf_config.list_logical_devices("GPU"): + logging.warning( + "%s: Note that this cell is not optimized for performance. " + "Please use tf.contrib.cudnn_rnn.CudnnRNNTanh for better " + "performance on GPU.", self) + + # Inputs must be 2-dimensional. + self.input_spec = input_spec.InputSpec(ndim=2) + + self._num_units = num_units + if activation: + self._activation = activations.get(activation) + else: + self._activation = math_ops.tanh + + @property + def state_size(self): + return self._num_units + + @property + def output_size(self): + return self._num_units + + @tf_utils.shape_type_conversion + def build(self, inputs_shape): + if inputs_shape[-1] is None: + raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % + str(inputs_shape)) + _check_supported_dtypes(self.dtype) + + input_depth = inputs_shape[-1] + self._kernel = self.add_variable( + _WEIGHTS_VARIABLE_NAME, + shape=[input_depth + self._num_units, self._num_units]) + self._bias = self.add_variable( + _BIAS_VARIABLE_NAME, + shape=[self._num_units], + initializer=init_ops.zeros_initializer(dtype=self.dtype)) + + self.built = True + + def call(self, inputs, state): + """Most basic RNN: output = new_state = act(W * input + U * state + B).""" + _check_rnn_cell_input_dtypes([inputs, state]) + gate_inputs = math_ops.matmul( + array_ops.concat([inputs, state], 1), self._kernel) + gate_inputs = nn_ops.bias_add(gate_inputs, self._bias) + output = self._activation(gate_inputs) + return output, output + + def get_config(self): + config = { + "num_units": self._num_units, + "activation": activations.serialize(self._activation), + "reuse": self._reuse, + } + base_config = super(BasicRNNCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +@tf_export(v1=["nn.rnn_cell.GRUCell"]) +class GRUCell(LayerRNNCell): + """Gated Recurrent Unit cell. + + Note that this cell is not optimized for performance. Please use + `tf.contrib.cudnn_rnn.CudnnGRU` for better performance on GPU, or + `tf.contrib.rnn.GRUBlockCellV2` for better performance on CPU. + + Args: + num_units: int, The number of units in the GRU cell. + activation: Nonlinearity to use. Default: `tanh`. + reuse: (optional) Python boolean describing whether to reuse variables in an + existing scope. If not `True`, and the existing scope already has the + given variables, an error is raised. + kernel_initializer: (optional) The initializer to use for the weight and + projection matrices. + bias_initializer: (optional) The initializer to use for the bias. + name: String, the name of the layer. Layers with the same name will share + weights, but to avoid mistakes we require reuse=True in such cases. + dtype: Default dtype of the layer (default of `None` means use the type of + the first input). Required when `build` is called before `call`. + **kwargs: Dict, keyword named properties for common layer attributes, like + `trainable` etc when constructing the cell from configs of get_config(). + + References: + Learning Phrase Representations using RNN Encoder Decoder for Statistical + Machine Translation: + [Cho et al., 2014] + (https://aclanthology.coli.uni-saarland.de/papers/D14-1179/d14-1179) + ([pdf](http://emnlp2014.org/papers/pdf/EMNLP2014179.pdf)) + """ + + def __init__(self, + num_units, + activation=None, + reuse=None, + kernel_initializer=None, + bias_initializer=None, + name=None, + dtype=None, + **kwargs): + warnings.warn("`tf.nn.rnn_cell.GRUCell` is deprecated and will be removed " + "in a future version. This class " + "is equivalent as `tf.keras.layers.GRUCell`, " + "and will be replaced by that in Tensorflow 2.0.") + super(GRUCell, self).__init__( + _reuse=reuse, name=name, dtype=dtype, **kwargs) + _check_supported_dtypes(self.dtype) + + if context.executing_eagerly() and tf_config.list_logical_devices("GPU"): + logging.warning( + "%s: Note that this cell is not optimized for performance. " + "Please use tf.contrib.cudnn_rnn.CudnnGRU for better " + "performance on GPU.", self) + # Inputs must be 2-dimensional. + self.input_spec = input_spec.InputSpec(ndim=2) + + self._num_units = num_units + if activation: + self._activation = activations.get(activation) + else: + self._activation = math_ops.tanh + self._kernel_initializer = initializers.get(kernel_initializer) + self._bias_initializer = initializers.get(bias_initializer) + + @property + def state_size(self): + return self._num_units + + @property + def output_size(self): + return self._num_units + + @tf_utils.shape_type_conversion + def build(self, inputs_shape): + if inputs_shape[-1] is None: + raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % + str(inputs_shape)) + _check_supported_dtypes(self.dtype) + input_depth = inputs_shape[-1] + self._gate_kernel = self.add_variable( + "gates/%s" % _WEIGHTS_VARIABLE_NAME, + shape=[input_depth + self._num_units, 2 * self._num_units], + initializer=self._kernel_initializer) + self._gate_bias = self.add_variable( + "gates/%s" % _BIAS_VARIABLE_NAME, + shape=[2 * self._num_units], + initializer=(self._bias_initializer + if self._bias_initializer is not None else + init_ops.constant_initializer(1.0, dtype=self.dtype))) + self._candidate_kernel = self.add_variable( + "candidate/%s" % _WEIGHTS_VARIABLE_NAME, + shape=[input_depth + self._num_units, self._num_units], + initializer=self._kernel_initializer) + self._candidate_bias = self.add_variable( + "candidate/%s" % _BIAS_VARIABLE_NAME, + shape=[self._num_units], + initializer=(self._bias_initializer + if self._bias_initializer is not None else + init_ops.zeros_initializer(dtype=self.dtype))) + + self.built = True + + def call(self, inputs, state): + """Gated recurrent unit (GRU) with nunits cells.""" + _check_rnn_cell_input_dtypes([inputs, state]) + + gate_inputs = math_ops.matmul( + array_ops.concat([inputs, state], 1), self._gate_kernel) + gate_inputs = nn_ops.bias_add(gate_inputs, self._gate_bias) + + value = math_ops.sigmoid(gate_inputs) + r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) + + r_state = r * state + + candidate = math_ops.matmul( + array_ops.concat([inputs, r_state], 1), self._candidate_kernel) + candidate = nn_ops.bias_add(candidate, self._candidate_bias) + + c = self._activation(candidate) + new_h = u * state + (1 - u) * c + return new_h, new_h + + def get_config(self): + config = { + "num_units": self._num_units, + "kernel_initializer": initializers.serialize(self._kernel_initializer), + "bias_initializer": initializers.serialize(self._bias_initializer), + "activation": activations.serialize(self._activation), + "reuse": self._reuse, + } + base_config = super(GRUCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +_LSTMStateTuple = collections.namedtuple("LSTMStateTuple", ("c", "h")) + + +@tf_export(v1=["nn.rnn_cell.LSTMStateTuple"]) +class LSTMStateTuple(_LSTMStateTuple): + """Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state. + + Stores two elements: `(c, h)`, in that order. Where `c` is the hidden state + and `h` is the output. + + Only used when `state_is_tuple=True`. + """ + __slots__ = () + + @property + def dtype(self): + (c, h) = self + if c.dtype != h.dtype: + raise TypeError("Inconsistent internal state: %s vs %s" % + (str(c.dtype), str(h.dtype))) + return c.dtype + + +@tf_export(v1=["nn.rnn_cell.BasicLSTMCell"]) +class BasicLSTMCell(LayerRNNCell): + """DEPRECATED: Please use `tf.compat.v1.nn.rnn_cell.LSTMCell` instead. + + Basic LSTM recurrent network cell. + + The implementation is based on + + We add forget_bias (default: 1) to the biases of the forget gate in order to + reduce the scale of forgetting in the beginning of the training. + + It does not allow cell clipping, a projection layer, and does not + use peep-hole connections: it is the basic baseline. + + For advanced models, please use the full `tf.compat.v1.nn.rnn_cell.LSTMCell` + that follows. + + Note that this cell is not optimized for performance. Please use + `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or + `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for + better performance on CPU. + """ + + def __init__(self, + num_units, + forget_bias=1.0, + state_is_tuple=True, + activation=None, + reuse=None, + name=None, + dtype=None, + **kwargs): + """Initialize the basic LSTM cell. + + Args: + num_units: int, The number of units in the LSTM cell. + forget_bias: float, The bias added to forget gates (see above). Must set + to `0.0` manually when restoring from CudnnLSTM-trained checkpoints. + state_is_tuple: If True, accepted and returned states are 2-tuples of the + `c_state` and `m_state`. If False, they are concatenated along the + column axis. The latter behavior will soon be deprecated. + activation: Activation function of the inner states. Default: `tanh`. It + could also be string that is within Keras activation function names. + reuse: (optional) Python boolean describing whether to reuse variables in + an existing scope. If not `True`, and the existing scope already has + the given variables, an error is raised. + name: String, the name of the layer. Layers with the same name will share + weights, but to avoid mistakes we require reuse=True in such cases. + dtype: Default dtype of the layer (default of `None` means use the type of + the first input). Required when `build` is called before `call`. + **kwargs: Dict, keyword named properties for common layer attributes, like + `trainable` etc when constructing the cell from configs of get_config(). + When restoring from CudnnLSTM-trained checkpoints, must use + `CudnnCompatibleLSTMCell` instead. + """ + warnings.warn("`tf.nn.rnn_cell.BasicLSTMCell` is deprecated and will be " + "removed in a future version. This class " + "is equivalent as `tf.keras.layers.LSTMCell`, " + "and will be replaced by that in Tensorflow 2.0.") + super(BasicLSTMCell, self).__init__( + _reuse=reuse, name=name, dtype=dtype, **kwargs) + _check_supported_dtypes(self.dtype) + if not state_is_tuple: + logging.warning( + "%s: Using a concatenated state is slower and will soon be " + "deprecated. Use state_is_tuple=True.", self) + if context.executing_eagerly() and tf_config.list_logical_devices("GPU"): + logging.warning( + "%s: Note that this cell is not optimized for performance. " + "Please use tf.contrib.cudnn_rnn.CudnnLSTM for better " + "performance on GPU.", self) + + # Inputs must be 2-dimensional. + self.input_spec = input_spec.InputSpec(ndim=2) + + self._num_units = num_units + self._forget_bias = forget_bias + self._state_is_tuple = state_is_tuple + if activation: + self._activation = activations.get(activation) + else: + self._activation = math_ops.tanh + + @property + def state_size(self): + return (LSTMStateTuple(self._num_units, self._num_units) + if self._state_is_tuple else 2 * self._num_units) + + @property + def output_size(self): + return self._num_units + + @tf_utils.shape_type_conversion + def build(self, inputs_shape): + if inputs_shape[-1] is None: + raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % + str(inputs_shape)) + _check_supported_dtypes(self.dtype) + input_depth = inputs_shape[-1] + h_depth = self._num_units + self._kernel = self.add_variable( + _WEIGHTS_VARIABLE_NAME, + shape=[input_depth + h_depth, 4 * self._num_units]) + self._bias = self.add_variable( + _BIAS_VARIABLE_NAME, + shape=[4 * self._num_units], + initializer=init_ops.zeros_initializer(dtype=self.dtype)) + + self.built = True + + def call(self, inputs, state): + """Long short-term memory cell (LSTM). + + Args: + inputs: `2-D` tensor with shape `[batch_size, input_size]`. + state: An `LSTMStateTuple` of state tensors, each shaped `[batch_size, + num_units]`, if `state_is_tuple` has been set to `True`. Otherwise, a + `Tensor` shaped `[batch_size, 2 * num_units]`. + + Returns: + A pair containing the new hidden state, and the new state (either a + `LSTMStateTuple` or a concatenated state, depending on + `state_is_tuple`). + """ + _check_rnn_cell_input_dtypes([inputs, state]) + + sigmoid = math_ops.sigmoid + one = constant_op.constant(1, dtype=dtypes.int32) + # Parameters of gates are concatenated into one multiply for efficiency. + if self._state_is_tuple: + c, h = state + else: + c, h = array_ops.split(value=state, num_or_size_splits=2, axis=one) + + gate_inputs = math_ops.matmul( + array_ops.concat([inputs, h], 1), self._kernel) + gate_inputs = nn_ops.bias_add(gate_inputs, self._bias) + + # i = input_gate, j = new_input, f = forget_gate, o = output_gate + i, j, f, o = array_ops.split( + value=gate_inputs, num_or_size_splits=4, axis=one) + + forget_bias_tensor = constant_op.constant(self._forget_bias, dtype=f.dtype) + # Note that using `add` and `multiply` instead of `+` and `*` gives a + # performance improvement. So using those at the cost of readability. + add = math_ops.add + multiply = math_ops.multiply + new_c = add( + multiply(c, sigmoid(add(f, forget_bias_tensor))), + multiply(sigmoid(i), self._activation(j))) + new_h = multiply(self._activation(new_c), sigmoid(o)) + + if self._state_is_tuple: + new_state = LSTMStateTuple(new_c, new_h) + else: + new_state = array_ops.concat([new_c, new_h], 1) + return new_h, new_state + + def get_config(self): + config = { + "num_units": self._num_units, + "forget_bias": self._forget_bias, + "state_is_tuple": self._state_is_tuple, + "activation": activations.serialize(self._activation), + "reuse": self._reuse, + } + base_config = super(BasicLSTMCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +@tf_export(v1=["nn.rnn_cell.LSTMCell"]) +class LSTMCell(LayerRNNCell): + """Long short-term memory unit (LSTM) recurrent network cell. + + The default non-peephole implementation is based on (Gers et al., 1999). + The peephole implementation is based on (Sak et al., 2014). + + The class uses optional peep-hole connections, optional cell clipping, and + an optional projection layer. + + Note that this cell is not optimized for performance. Please use + `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or + `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for + better performance on CPU. + References: + Long short-term memory recurrent neural network architectures for large + scale acoustic modeling: + [Sak et al., 2014] + (https://www.isca-speech.org/archive/interspeech_2014/i14_0338.html) + ([pdf] + (https://www.isca-speech.org/archive/archive_papers/interspeech_2014/i14_0338.pdf)) + Learning to forget: + [Gers et al., 1999] + (http://digital-library.theiet.org/content/conferences/10.1049/cp_19991218) + ([pdf](https://arxiv.org/pdf/1409.2329.pdf)) + Long Short-Term Memory: + [Hochreiter et al., 1997] + (https://www.mitpressjournals.org/doi/abs/10.1162/neco.1997.9.8.1735) + ([pdf](http://ml.jku.at/publications/older/3504.pdf)) + """ + + def __init__(self, + num_units, + use_peepholes=False, + cell_clip=None, + initializer=None, + num_proj=None, + proj_clip=None, + num_unit_shards=None, + num_proj_shards=None, + forget_bias=1.0, + state_is_tuple=True, + activation=None, + reuse=None, + name=None, + dtype=None, + **kwargs): + """Initialize the parameters for an LSTM cell. + + Args: + num_units: int, The number of units in the LSTM cell. + use_peepholes: bool, set True to enable diagonal/peephole connections. + cell_clip: (optional) A float value, if provided the cell state is clipped + by this value prior to the cell output activation. + initializer: (optional) The initializer to use for the weight and + projection matrices. + num_proj: (optional) int, The output dimensionality for the projection + matrices. If None, no projection is performed. + proj_clip: (optional) A float value. If `num_proj > 0` and `proj_clip` is + provided, then the projected values are clipped elementwise to within + `[-proj_clip, proj_clip]`. + num_unit_shards: Deprecated, will be removed by Jan. 2017. Use a + variable_scope partitioner instead. + num_proj_shards: Deprecated, will be removed by Jan. 2017. Use a + variable_scope partitioner instead. + forget_bias: Biases of the forget gate are initialized by default to 1 in + order to reduce the scale of forgetting at the beginning of the + training. Must set it manually to `0.0` when restoring from CudnnLSTM + trained checkpoints. + state_is_tuple: If True, accepted and returned states are 2-tuples of the + `c_state` and `m_state`. If False, they are concatenated along the + column axis. This latter behavior will soon be deprecated. + activation: Activation function of the inner states. Default: `tanh`. It + could also be string that is within Keras activation function names. + reuse: (optional) Python boolean describing whether to reuse variables in + an existing scope. If not `True`, and the existing scope already has + the given variables, an error is raised. + name: String, the name of the layer. Layers with the same name will share + weights, but to avoid mistakes we require reuse=True in such cases. + dtype: Default dtype of the layer (default of `None` means use the type of + the first input). Required when `build` is called before `call`. + **kwargs: Dict, keyword named properties for common layer attributes, like + `trainable` etc when constructing the cell from configs of get_config(). + When restoring from CudnnLSTM-trained checkpoints, use + `CudnnCompatibleLSTMCell` instead. + """ + warnings.warn("`tf.nn.rnn_cell.LSTMCell` is deprecated and will be " + "removed in a future version. This class " + "is equivalent as `tf.keras.layers.LSTMCell`, " + "and will be replaced by that in Tensorflow 2.0.") + super(LSTMCell, self).__init__( + _reuse=reuse, name=name, dtype=dtype, **kwargs) + _check_supported_dtypes(self.dtype) + if not state_is_tuple: + logging.warning( + "%s: Using a concatenated state is slower and will soon be " + "deprecated. Use state_is_tuple=True.", self) + if num_unit_shards is not None or num_proj_shards is not None: + logging.warning( + "%s: The num_unit_shards and proj_unit_shards parameters are " + "deprecated and will be removed in Jan 2017. " + "Use a variable scope with a partitioner instead.", self) + if context.executing_eagerly() and tf_config.list_logical_devices("GPU"): + logging.warning( + "%s: Note that this cell is not optimized for performance. " + "Please use tf.contrib.cudnn_rnn.CudnnLSTM for better " + "performance on GPU.", self) + + # Inputs must be 2-dimensional. + self.input_spec = input_spec.InputSpec(ndim=2) + + self._num_units = num_units + self._use_peepholes = use_peepholes + self._cell_clip = cell_clip + self._initializer = initializers.get(initializer) + self._num_proj = num_proj + self._proj_clip = proj_clip + self._num_unit_shards = num_unit_shards + self._num_proj_shards = num_proj_shards + self._forget_bias = forget_bias + self._state_is_tuple = state_is_tuple + if activation: + self._activation = activations.get(activation) + else: + self._activation = math_ops.tanh + + if num_proj: + self._state_size = ( + LSTMStateTuple(num_units, num_proj) if state_is_tuple else num_units + + num_proj) + self._output_size = num_proj + else: + self._state_size = ( + LSTMStateTuple(num_units, num_units) if state_is_tuple else 2 * + num_units) + self._output_size = num_units + + @property + def state_size(self): + return self._state_size + + @property + def output_size(self): + return self._output_size + + @tf_utils.shape_type_conversion + def build(self, inputs_shape): + if inputs_shape[-1] is None: + raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % + str(inputs_shape)) + _check_supported_dtypes(self.dtype) + input_depth = inputs_shape[-1] + h_depth = self._num_units if self._num_proj is None else self._num_proj + maybe_partitioner = ( + partitioned_variables.fixed_size_partitioner(self._num_unit_shards) + if self._num_unit_shards is not None else None) + self._kernel = self.add_variable( + _WEIGHTS_VARIABLE_NAME, + shape=[input_depth + h_depth, 4 * self._num_units], + initializer=self._initializer, + partitioner=maybe_partitioner) + if self.dtype is None: + initializer = init_ops.zeros_initializer + else: + initializer = init_ops.zeros_initializer(dtype=self.dtype) + self._bias = self.add_variable( + _BIAS_VARIABLE_NAME, + shape=[4 * self._num_units], + initializer=initializer) + if self._use_peepholes: + self._w_f_diag = self.add_variable( + "w_f_diag", shape=[self._num_units], initializer=self._initializer) + self._w_i_diag = self.add_variable( + "w_i_diag", shape=[self._num_units], initializer=self._initializer) + self._w_o_diag = self.add_variable( + "w_o_diag", shape=[self._num_units], initializer=self._initializer) + + if self._num_proj is not None: + maybe_proj_partitioner = ( + partitioned_variables.fixed_size_partitioner(self._num_proj_shards) + if self._num_proj_shards is not None else None) + self._proj_kernel = self.add_variable( + "projection/%s" % _WEIGHTS_VARIABLE_NAME, + shape=[self._num_units, self._num_proj], + initializer=self._initializer, + partitioner=maybe_proj_partitioner) + + self.built = True + + def call(self, inputs, state): + """Run one step of LSTM. + + Args: + inputs: input Tensor, must be 2-D, `[batch, input_size]`. + state: if `state_is_tuple` is False, this must be a state Tensor, `2-D, + [batch, state_size]`. If `state_is_tuple` is True, this must be a tuple + of state Tensors, both `2-D`, with column sizes `c_state` and `m_state`. + + Returns: + A tuple containing: + + - A `2-D, [batch, output_dim]`, Tensor representing the output of the + LSTM after reading `inputs` when previous state was `state`. + Here output_dim is: + num_proj if num_proj was set, + num_units otherwise. + - Tensor(s) representing the new state of LSTM after reading `inputs` when + the previous state was `state`. Same type and shape(s) as `state`. + + Raises: + ValueError: If input size cannot be inferred from inputs via + static shape inference. + """ + _check_rnn_cell_input_dtypes([inputs, state]) + + num_proj = self._num_units if self._num_proj is None else self._num_proj + sigmoid = math_ops.sigmoid + + if self._state_is_tuple: + (c_prev, m_prev) = state + else: + c_prev = array_ops.slice(state, [0, 0], [-1, self._num_units]) + m_prev = array_ops.slice(state, [0, self._num_units], [-1, num_proj]) + + input_size = inputs.get_shape().with_rank(2).dims[1].value + if input_size is None: + raise ValueError("Could not infer input size from inputs.get_shape()[-1]") + + # i = input_gate, j = new_input, f = forget_gate, o = output_gate + lstm_matrix = math_ops.matmul( + array_ops.concat([inputs, m_prev], 1), self._kernel) + lstm_matrix = nn_ops.bias_add(lstm_matrix, self._bias) + + i, j, f, o = array_ops.split( + value=lstm_matrix, num_or_size_splits=4, axis=1) + # Diagonal connections + if self._use_peepholes: + c = ( + sigmoid(f + self._forget_bias + self._w_f_diag * c_prev) * c_prev + + sigmoid(i + self._w_i_diag * c_prev) * self._activation(j)) + else: + c = ( + sigmoid(f + self._forget_bias) * c_prev + + sigmoid(i) * self._activation(j)) + + if self._cell_clip is not None: + # pylint: disable=invalid-unary-operand-type + c = clip_ops.clip_by_value(c, -self._cell_clip, self._cell_clip) + # pylint: enable=invalid-unary-operand-type + if self._use_peepholes: + m = sigmoid(o + self._w_o_diag * c) * self._activation(c) + else: + m = sigmoid(o) * self._activation(c) + + if self._num_proj is not None: + m = math_ops.matmul(m, self._proj_kernel) + + if self._proj_clip is not None: + # pylint: disable=invalid-unary-operand-type + m = clip_ops.clip_by_value(m, -self._proj_clip, self._proj_clip) + # pylint: enable=invalid-unary-operand-type + + new_state = ( + LSTMStateTuple(c, m) + if self._state_is_tuple else array_ops.concat([c, m], 1)) + return m, new_state + + def get_config(self): + config = { + "num_units": self._num_units, + "use_peepholes": self._use_peepholes, + "cell_clip": self._cell_clip, + "initializer": initializers.serialize(self._initializer), + "num_proj": self._num_proj, + "proj_clip": self._proj_clip, + "num_unit_shards": self._num_unit_shards, + "num_proj_shards": self._num_proj_shards, + "forget_bias": self._forget_bias, + "state_is_tuple": self._state_is_tuple, + "activation": activations.serialize(self._activation), + "reuse": self._reuse, + } + base_config = super(LSTMCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class _RNNCellWrapperV1(RNNCell): + """Base class for cells wrappers V1 compatibility. + + This class along with `_RNNCellWrapperV2` allows to define cells wrappers that + are compatible with V1 and V2, and defines helper methods for this purpose. + """ + + def __init__(self, cell, *args, **kwargs): + super(_RNNCellWrapperV1, self).__init__(*args, **kwargs) + assert_like_rnncell("cell", cell) + self.cell = cell + if isinstance(cell, trackable.Trackable): + self._track_trackable(self.cell, name="cell") + + def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs): + """Calls the wrapped cell and performs the wrapping logic. + + This method is called from the wrapper's `call` or `__call__` methods. + + Args: + inputs: A tensor with wrapped cell's input. + state: A tensor or tuple of tensors with wrapped cell's state. + cell_call_fn: Wrapped cell's method to use for step computation (cell's + `__call__` or 'call' method). + **kwargs: Additional arguments. + + Returns: + A pair containing: + - Output: A tensor with cell's output. + - New state: A tensor or tuple of tensors with new wrapped cell's state. + """ + raise NotImplementedError + + def __call__(self, inputs, state, scope=None): + """Runs the RNN cell step computation. + + We assume that the wrapped RNNCell is being built within its `__call__` + method. We directly use the wrapped cell's `__call__` in the overridden + wrapper `__call__` method. + + This allows to use the wrapped cell and the non-wrapped cell equivalently + when using `__call__`. + + Args: + inputs: A tensor with wrapped cell's input. + state: A tensor or tuple of tensors with wrapped cell's state. + scope: VariableScope for the subgraph created in the wrapped cells' + `__call__`. + + Returns: + A pair containing: + + - Output: A tensor with cell's output. + - New state: A tensor or tuple of tensors with new wrapped cell's state. + """ + return self._call_wrapped_cell( + inputs, state, cell_call_fn=self.cell.__call__, scope=scope) + + def get_config(self): + config = { + "cell": { + "class_name": self.cell.__class__.__name__, + "config": self.cell.get_config() + }, + } + base_config = super(_RNNCellWrapperV1, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() + cell = config.pop("cell") + try: + assert_like_rnncell("cell", cell) + return cls(cell, **config) + except TypeError: + raise ValueError("RNNCellWrapper cannot reconstruct the wrapped cell. " + "Please overwrite the cell in the config with a RNNCell " + "instance.") + + +@tf_export(v1=["nn.rnn_cell.DropoutWrapper"]) +class DropoutWrapper(rnn_cell_wrapper_impl.DropoutWrapperBase, + _RNNCellWrapperV1): + """Operator adding dropout to inputs and outputs of the given cell.""" + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(DropoutWrapper, self).__init__(*args, **kwargs) + + __init__.__doc__ = rnn_cell_wrapper_impl.DropoutWrapperBase.__init__.__doc__ + + +@tf_export(v1=["nn.rnn_cell.ResidualWrapper"]) +class ResidualWrapper(rnn_cell_wrapper_impl.ResidualWrapperBase, + _RNNCellWrapperV1): + """RNNCell wrapper that ensures cell inputs are added to the outputs.""" + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(ResidualWrapper, self).__init__(*args, **kwargs) + + __init__.__doc__ = rnn_cell_wrapper_impl.ResidualWrapperBase.__init__.__doc__ + + +@tf_export(v1=["nn.rnn_cell.DeviceWrapper"]) +class DeviceWrapper(rnn_cell_wrapper_impl.DeviceWrapperBase, + _RNNCellWrapperV1): + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(DeviceWrapper, self).__init__(*args, **kwargs) + + __init__.__doc__ = rnn_cell_wrapper_impl.DeviceWrapperBase.__init__.__doc__ + + +@tf_export(v1=["nn.rnn_cell.MultiRNNCell"]) +class MultiRNNCell(RNNCell): + """RNN cell composed sequentially of multiple simple cells. + + Example: + + ```python + num_units = [128, 64] + cells = [BasicLSTMCell(num_units=n) for n in num_units] + stacked_rnn_cell = MultiRNNCell(cells) + ``` + """ + + def __init__(self, cells, state_is_tuple=True): + """Create a RNN cell composed sequentially of a number of RNNCells. + + Args: + cells: list of RNNCells that will be composed in this order. + state_is_tuple: If True, accepted and returned states are n-tuples, where + `n = len(cells)`. If False, the states are all concatenated along the + column axis. This latter behavior will soon be deprecated. + + Raises: + ValueError: if cells is empty (not allowed), or at least one of the cells + returns a state tuple but the flag `state_is_tuple` is `False`. + """ + logging.warning("`tf.nn.rnn_cell.MultiRNNCell` is deprecated. This class " + "is equivalent as `tf.keras.layers.StackedRNNCells`, " + "and will be replaced by that in Tensorflow 2.0.") + super(MultiRNNCell, self).__init__() + if not cells: + raise ValueError("Must specify at least one cell for MultiRNNCell.") + if not nest.is_nested(cells): + raise TypeError("cells must be a list or tuple, but saw: %s." % cells) + + if len(set(id(cell) for cell in cells)) < len(cells): + logging.log_first_n( + logging.WARN, "At least two cells provided to MultiRNNCell " + "are the same object and will share weights.", 1) + + self._cells = cells + for cell_number, cell in enumerate(self._cells): + # Add Trackable dependencies on these cells so their variables get + # saved with this object when using object-based saving. + if isinstance(cell, trackable.Trackable): + # TODO(allenl): Track down non-Trackable callers. + self._track_trackable(cell, name="cell-%d" % (cell_number,)) + self._state_is_tuple = state_is_tuple + if not state_is_tuple: + if any(nest.is_nested(c.state_size) for c in self._cells): + raise ValueError("Some cells return tuples of states, but the flag " + "state_is_tuple is not set. State sizes are: %s" % + str([c.state_size for c in self._cells])) + + @property + def state_size(self): + if self._state_is_tuple: + return tuple(cell.state_size for cell in self._cells) + else: + return sum(cell.state_size for cell in self._cells) + + @property + def output_size(self): + return self._cells[-1].output_size + + def zero_state(self, batch_size, dtype): + with backend.name_scope(type(self).__name__ + "ZeroState"): + if self._state_is_tuple: + return tuple(cell.zero_state(batch_size, dtype) for cell in self._cells) + else: + # We know here that state_size of each cell is not a tuple and + # presumably does not contain TensorArrays or anything else fancy + return super(MultiRNNCell, self).zero_state(batch_size, dtype) + + @property + def trainable_weights(self): + if not self.trainable: + return [] + weights = [] + for cell in self._cells: + if isinstance(cell, base_layer.Layer): + weights += cell.trainable_weights + return weights + + @property + def non_trainable_weights(self): + weights = [] + for cell in self._cells: + if isinstance(cell, base_layer.Layer): + weights += cell.non_trainable_weights + if not self.trainable: + trainable_weights = [] + for cell in self._cells: + if isinstance(cell, base_layer.Layer): + trainable_weights += cell.trainable_weights + return trainable_weights + weights + return weights + + def call(self, inputs, state): + """Run this multi-layer cell on inputs, starting from state.""" + cur_state_pos = 0 + cur_inp = inputs + new_states = [] + for i, cell in enumerate(self._cells): + with vs.variable_scope("cell_%d" % i): + if self._state_is_tuple: + if not nest.is_nested(state): + raise ValueError( + "Expected state to be a tuple of length %d, but received: %s" % + (len(self.state_size), state)) + cur_state = state[i] + else: + cur_state = array_ops.slice(state, [0, cur_state_pos], + [-1, cell.state_size]) + cur_state_pos += cell.state_size + cur_inp, new_state = cell(cur_inp, cur_state) + new_states.append(new_state) + + new_states = ( + tuple(new_states) if self._state_is_tuple else array_ops.concat( + new_states, 1)) + + return cur_inp, new_states + + +def _check_rnn_cell_input_dtypes(inputs): + """Check whether the input tensors are with supported dtypes. + + Default RNN cells only support floats and complex as its dtypes since the + activation function (tanh and sigmoid) only allow those types. This function + will throw a proper error message if the inputs is not in a supported type. + + Args: + inputs: tensor or nested structure of tensors that are feed to RNN cell as + input or state. + + Raises: + ValueError: if any of the input tensor are not having dtypes of float or + complex. + """ + for t in nest.flatten(inputs): + _check_supported_dtypes(t.dtype) + + +def _check_supported_dtypes(dtype): + if dtype is None: + return + dtype = dtypes.as_dtype(dtype) + if not (dtype.is_floating or dtype.is_complex): + raise ValueError("RNN cell only supports floating point inputs, " + "but saw dtype: %s" % dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..b07a97fa8db3d9d07735257f7e0e23b25dabcb56 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py @@ -0,0 +1,513 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module contains the implementation of RNN cell wrappers.""" +import hashlib +import numbers +import sys +import types as python_types +import warnings + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.util import nest + + +class DropoutWrapperBase(object): + """Operator adding dropout to inputs and outputs of the given cell.""" + + def __init__(self, + cell, + input_keep_prob=1.0, + output_keep_prob=1.0, + state_keep_prob=1.0, + variational_recurrent=False, + input_size=None, + dtype=None, + seed=None, + dropout_state_filter_visitor=None, + **kwargs): + """Create a cell with added input, state, and/or output dropout. + + If `variational_recurrent` is set to `True` (**NOT** the default behavior), + then the same dropout mask is applied at every step, as described in: + [A Theoretically Grounded Application of Dropout in Recurrent + Neural Networks. Y. Gal, Z. Ghahramani](https://arxiv.org/abs/1512.05287). + + Otherwise a different dropout mask is applied at every time step. + + Note, by default (unless a custom `dropout_state_filter` is provided), + the memory state (`c` component of any `LSTMStateTuple`) passing through + a `DropoutWrapper` is never modified. This behavior is described in the + above article. + + Args: + cell: an RNNCell, a projection to output_size is added to it. + input_keep_prob: unit Tensor or float between 0 and 1, input keep + probability; if it is constant and 1, no input dropout will be added. + output_keep_prob: unit Tensor or float between 0 and 1, output keep + probability; if it is constant and 1, no output dropout will be added. + state_keep_prob: unit Tensor or float between 0 and 1, output keep + probability; if it is constant and 1, no output dropout will be added. + State dropout is performed on the outgoing states of the cell. **Note** + the state components to which dropout is applied when `state_keep_prob` + is in `(0, 1)` are also determined by the argument + `dropout_state_filter_visitor` (e.g. by default dropout is never applied + to the `c` component of an `LSTMStateTuple`). + variational_recurrent: Python bool. If `True`, then the same dropout + pattern is applied across all time steps per run call. If this parameter + is set, `input_size` **must** be provided. + input_size: (optional) (possibly nested tuple of) `TensorShape` objects + containing the depth(s) of the input tensors expected to be passed in to + the `DropoutWrapper`. Required and used **iff** `variational_recurrent + = True` and `input_keep_prob < 1`. + dtype: (optional) The `dtype` of the input, state, and output tensors. + Required and used **iff** `variational_recurrent = True`. + seed: (optional) integer, the randomness seed. + dropout_state_filter_visitor: (optional), default: (see below). Function + that takes any hierarchical level of the state and returns a scalar or + depth=1 structure of Python booleans describing which terms in the state + should be dropped out. In addition, if the function returns `True`, + dropout is applied across this sublevel. If the function returns + `False`, dropout is not applied across this entire sublevel. + Default behavior: perform dropout on all terms except the memory (`c`) + state of `LSTMCellState` objects, and don't try to apply dropout to + `TensorArray` objects: ``` + def dropout_state_filter_visitor(s): + if isinstance(s, LSTMCellState): # Never perform dropout on the c + state. return LSTMCellState(c=False, h=True) + elif isinstance(s, TensorArray): return False return True ``` + **kwargs: dict of keyword arguments for base layer. + + Raises: + TypeError: if `cell` is not an `RNNCell`, or `keep_state_fn` is provided + but not `callable`. + ValueError: if any of the keep_probs are not between 0 and 1. + """ + super(DropoutWrapperBase, self).__init__(cell, dtype=dtype, **kwargs) + + if (dropout_state_filter_visitor is not None and + not callable(dropout_state_filter_visitor)): + raise TypeError("dropout_state_filter_visitor must be callable") + self._dropout_state_filter = ( + dropout_state_filter_visitor or _default_dropout_state_filter_visitor) + with ops.name_scope_v2("DropoutWrapperInit"): + + def tensor_and_const_value(v): + tensor_value = tensor_conversion.convert_to_tensor_v2_with_dispatch(v) + const_value = tensor_util.constant_value(tensor_value) + return (tensor_value, const_value) + + for prob, attr in [(input_keep_prob, "input_keep_prob"), + (state_keep_prob, "state_keep_prob"), + (output_keep_prob, "output_keep_prob")]: + tensor_prob, const_prob = tensor_and_const_value(prob) + if const_prob is not None: + if const_prob < 0 or const_prob > 1: + raise ValueError("Parameter %s must be between 0 and 1: %d" % + (attr, const_prob)) + setattr(self, "_%s" % attr, float(const_prob)) + else: + setattr(self, "_%s" % attr, tensor_prob) + + # Set variational_recurrent, seed before running the code below + self._variational_recurrent = variational_recurrent + self._input_size = input_size + self._seed = seed + + self._recurrent_input_noise = None + self._recurrent_state_noise = None + self._recurrent_output_noise = None + + if variational_recurrent: + if dtype is None: + raise ValueError( + "When variational_recurrent=True, dtype must be provided") + + def convert_to_batch_shape(s): + # Prepend a 1 for the batch dimension; for recurrent + # variational dropout we use the same dropout mask for all + # batch elements. + return array_ops.concat(([1], tensor_shape.TensorShape(s).as_list()), 0) + + def batch_noise(s, inner_seed): + shape = convert_to_batch_shape(s) + return random_ops.random_uniform(shape, seed=inner_seed, dtype=dtype) + + if (not isinstance(self._input_keep_prob, numbers.Real) or + self._input_keep_prob < 1.0): + if input_size is None: + raise ValueError( + "When variational_recurrent=True and input_keep_prob < 1.0 or " + "is unknown, input_size must be provided") + self._recurrent_input_noise = _enumerated_map_structure_up_to( + input_size, + lambda i, s: batch_noise(s, inner_seed=self._gen_seed("input", i)), + input_size) + self._recurrent_state_noise = _enumerated_map_structure_up_to( + cell.state_size, + lambda i, s: batch_noise(s, inner_seed=self._gen_seed("state", i)), + cell.state_size) + self._recurrent_output_noise = _enumerated_map_structure_up_to( + cell.output_size, + lambda i, s: batch_noise(s, inner_seed=self._gen_seed("output", i)), + cell.output_size) + + def _gen_seed(self, salt_prefix, index): + if self._seed is None: + return None + salt = "%s_%d" % (salt_prefix, index) + string = (str(self._seed) + salt).encode("utf-8") + return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF + + @property + def wrapped_cell(self): + return self.cell + + @property + def state_size(self): + return self.cell.state_size + + @property + def output_size(self): + return self.cell.output_size + + def build(self, inputs_shape): + self.cell.build(inputs_shape) + self.built = True + + def zero_state(self, batch_size, dtype): + with ops.name_scope_v2(type(self).__name__ + "ZeroState"): + return self.cell.zero_state(batch_size, dtype) + + def _variational_recurrent_dropout_value( + self, unused_index, value, noise, keep_prob): + """Performs dropout given the pre-calculated noise tensor.""" + # uniform [keep_prob, 1.0 + keep_prob) + random_tensor = keep_prob + noise + + # 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob) + binary_tensor = math_ops.floor(random_tensor) + ret = math_ops.divide(value, keep_prob) * binary_tensor + ret.set_shape(value.get_shape()) + return ret + + def _dropout(self, + values, + salt_prefix, + recurrent_noise, + keep_prob, + shallow_filtered_substructure=None): + """Decides whether to perform standard dropout or recurrent dropout.""" + + if shallow_filtered_substructure is None: + # Put something so we traverse the entire structure; inside the + # dropout function we check to see if leafs of this are bool or not. + shallow_filtered_substructure = values + + if not self._variational_recurrent: + + def dropout(i, do_dropout, v): + if not isinstance(do_dropout, bool) or do_dropout: + return nn_ops.dropout_v2( + v, rate=1. - keep_prob, seed=self._gen_seed(salt_prefix, i)) + else: + return v + + return _enumerated_map_structure_up_to( + shallow_filtered_substructure, dropout, + *[shallow_filtered_substructure, values]) + else: + + def dropout(i, do_dropout, v, n): + if not isinstance(do_dropout, bool) or do_dropout: + return self._variational_recurrent_dropout_value(i, v, n, keep_prob) + else: + return v + + return _enumerated_map_structure_up_to( + shallow_filtered_substructure, dropout, + *[shallow_filtered_substructure, values, recurrent_noise]) + + def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs): + """Runs the wrapped cell and applies dropout. + + Args: + inputs: A tensor with wrapped cell's input. + state: A tensor or tuple of tensors with wrapped cell's state. + cell_call_fn: Wrapped cell's method to use for step computation (cell's + `__call__` or 'call' method). + **kwargs: Additional arguments. + + Returns: + A pair containing: + + - Output: A tensor with cell's output. + - New state: A tensor or tuple of tensors with new wrapped cell's state. + """ + + def _should_dropout(p): + return (not isinstance(p, float)) or p < 1 + + if _should_dropout(self._input_keep_prob): + inputs = self._dropout(inputs, "input", self._recurrent_input_noise, + self._input_keep_prob) + output, new_state = cell_call_fn(inputs, state, **kwargs) + if _should_dropout(self._state_keep_prob): + # Identify which subsets of the state to perform dropout on and + # which ones to keep. + shallow_filtered_substructure = nest.get_traverse_shallow_structure( + self._dropout_state_filter, new_state) + new_state = self._dropout(new_state, "state", self._recurrent_state_noise, + self._state_keep_prob, + shallow_filtered_substructure) + if _should_dropout(self._output_keep_prob): + output = self._dropout(output, "output", self._recurrent_output_noise, + self._output_keep_prob) + return output, new_state + + def get_config(self): + """Returns the config of the dropout wrapper.""" + config = { + "input_keep_prob": self._input_keep_prob, + "output_keep_prob": self._output_keep_prob, + "state_keep_prob": self._state_keep_prob, + "variational_recurrent": self._variational_recurrent, + "input_size": self._input_size, + "seed": self._seed, + } + if self._dropout_state_filter != _default_dropout_state_filter_visitor: + function, function_type, function_module = _serialize_function_to_config( + self._dropout_state_filter) + config.update({"dropout_fn": function, + "dropout_fn_type": function_type, + "dropout_fn_module": function_module}) + base_config = super(DropoutWrapperBase, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + if "dropout_fn" in config: + config = config.copy() + dropout_state_filter = _parse_config_to_function( + config, custom_objects, "dropout_fn", "dropout_fn_type", + "dropout_fn_module") + config.pop("dropout_fn") + config["dropout_state_filter_visitor"] = dropout_state_filter + return super(DropoutWrapperBase, cls).from_config( + config, custom_objects=custom_objects) + + +class ResidualWrapperBase(object): + """RNNCell wrapper that ensures cell inputs are added to the outputs.""" + + def __init__(self, cell, residual_fn=None, **kwargs): + """Constructs a `ResidualWrapper` for `cell`. + + Args: + cell: An instance of `RNNCell`. + residual_fn: (Optional) The function to map raw cell inputs and raw cell + outputs to the actual cell outputs of the residual network. + Defaults to calling nest.map_structure on (lambda i, o: i + o), inputs + and outputs. + **kwargs: dict of keyword arguments for base layer. + """ + super(ResidualWrapperBase, self).__init__(cell, **kwargs) + self._residual_fn = residual_fn + + @property + def state_size(self): + return self.cell.state_size + + @property + def output_size(self): + return self.cell.output_size + + def zero_state(self, batch_size, dtype): + with ops.name_scope_v2(type(self).__name__ + "ZeroState"): + return self.cell.zero_state(batch_size, dtype) + + def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs): + """Run the cell and then apply the residual_fn on its inputs to its outputs. + + Args: + inputs: cell inputs. + state: cell state. + cell_call_fn: Wrapped cell's method to use for step computation (cell's + `__call__` or 'call' method). + **kwargs: Additional arguments passed to the wrapped cell's `call`. + + Returns: + Tuple of cell outputs and new state. + + Raises: + TypeError: If cell inputs and outputs have different structure (type). + ValueError: If cell inputs and outputs have different structure (value). + """ + outputs, new_state = cell_call_fn(inputs, state, **kwargs) + + # Ensure shapes match + def assert_shape_match(inp, out): + inp.get_shape().assert_is_compatible_with(out.get_shape()) + + def default_residual_fn(inputs, outputs): + nest.assert_same_structure(inputs, outputs) + nest.map_structure(assert_shape_match, inputs, outputs) + return nest.map_structure(lambda inp, out: inp + out, inputs, outputs) + + res_outputs = (self._residual_fn or default_residual_fn)(inputs, outputs) + return (res_outputs, new_state) + + def get_config(self): + """Returns the config of the residual wrapper.""" + if self._residual_fn is not None: + function, function_type, function_module = _serialize_function_to_config( + self._residual_fn) + config = { + "residual_fn": function, + "residual_fn_type": function_type, + "residual_fn_module": function_module + } + else: + config = {} + base_config = super(ResidualWrapperBase, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + if "residual_fn" in config: + config = config.copy() + residual_function = _parse_config_to_function(config, custom_objects, + "residual_fn", + "residual_fn_type", + "residual_fn_module") + config["residual_fn"] = residual_function + return super(ResidualWrapperBase, cls).from_config( + config, custom_objects=custom_objects) + + +class DeviceWrapperBase(object): + """Operator that ensures an RNNCell runs on a particular device.""" + + def __init__(self, cell, device, **kwargs): + """Construct a `DeviceWrapper` for `cell` with device `device`. + + Ensures the wrapped `cell` is called with `tf.device(device)`. + + Args: + cell: An instance of `RNNCell`. + device: A device string or function, for passing to `tf.device`. + **kwargs: dict of keyword arguments for base layer. + """ + super(DeviceWrapperBase, self).__init__(cell, **kwargs) + self._device = device + + @property + def state_size(self): + return self.cell.state_size + + @property + def output_size(self): + return self.cell.output_size + + def zero_state(self, batch_size, dtype): + with ops.name_scope_v2(type(self).__name__ + "ZeroState"): + with ops.device(self._device): + return self.cell.zero_state(batch_size, dtype) + + def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs): + """Run the cell on specified device.""" + with ops.device(self._device): + return cell_call_fn(inputs, state, **kwargs) + + def get_config(self): + config = {"device": self._device} + base_config = super(DeviceWrapperBase, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +def _serialize_function_to_config(function): + """Serialize the function for get_config().""" + if isinstance(function, python_types.LambdaType): + output = generic_utils.func_dump(function) + output_type = "lambda" + module = function.__module__ + elif callable(function): + output = function.__name__ + output_type = "function" + module = function.__module__ + else: + raise ValueError("Unrecognized function type for input: {}".format( + type(function))) + + return output, output_type, module + + +def _parse_config_to_function(config, custom_objects, func_attr_name, + func_type_attr_name, module_attr_name): + """Reconstruct the function from the config.""" + globs = globals() + module = config.pop(module_attr_name, None) + if module in sys.modules: + globs.update(sys.modules[module].__dict__) + elif module is not None: + # Note: we don't know the name of the function if it's a lambda. + warnings.warn("{} is not loaded, but a layer uses it. " + "It may cause errors.".format(module), UserWarning) + if custom_objects: + globs.update(custom_objects) + function_type = config.pop(func_type_attr_name) + if function_type == "function": + # Simple lookup in custom objects + function = generic_utils.deserialize_keras_object( + config[func_attr_name], + custom_objects=custom_objects, + printable_module_name="function in wrapper") + elif function_type == "lambda": + # Unsafe deserialization from bytecode + function = generic_utils.func_load( + config[func_attr_name], globs=globs) + else: + raise TypeError("Unknown function type:", function_type) + return function + + +def _default_dropout_state_filter_visitor(substate): + from tensorflow.python.keras.layers.legacy_rnn.rnn_cell_impl import LSTMStateTuple # pylint: disable=g-import-not-at-top + if isinstance(substate, LSTMStateTuple): + # Do not perform dropout on the memory state. + return LSTMStateTuple(c=False, h=True) + elif isinstance(substate, tensor_array_ops.TensorArray): + return False + return True + + +def _enumerated_map_structure_up_to(shallow_structure, map_fn, *args, **kwargs): + ix = [0] + + def enumerated_fn(*inner_args, **inner_kwargs): + r = map_fn(ix[0], *inner_args, **inner_kwargs) + ix[0] += 1 + return r + + return nest.map_structure_up_to(shallow_structure, enumerated_fn, *args, + **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/merge.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..68461de0841f2f8ff50b02ffbd171ba1902c7c6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/merge.py @@ -0,0 +1,949 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=not-callable +# pylint: disable=redefined-builtin +"""Layers that can merge several inputs into one.""" + +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn + + +class _Merge(Layer): + """Generic merge layer for elementwise merge functions. + + Used to implement `Sum`, `Average`, etc. + """ + + def __init__(self, **kwargs): + """Intializes a Merge layer. + + Args: + **kwargs: standard layer keyword arguments. + """ + super(_Merge, self).__init__(**kwargs) + self.supports_masking = True + + def _merge_function(self, inputs): + raise NotImplementedError + + def _compute_elemwise_op_output_shape(self, shape1, shape2): + """Computes the shape of the resultant of an elementwise operation. + + Args: + shape1: tuple or None. Shape of the first tensor + shape2: tuple or None. Shape of the second tensor + + Returns: + expected output shape when an element-wise operation is + carried out on 2 tensors with shapes shape1 and shape2. + tuple or None. + + Raises: + ValueError: if shape1 and shape2 are not compatible for + element-wise operations. + """ + if None in [shape1, shape2]: + return None + elif len(shape1) < len(shape2): + return self._compute_elemwise_op_output_shape(shape2, shape1) + elif not shape2: + return shape1 + output_shape = list(shape1[:-len(shape2)]) + for i, j in zip(shape1[-len(shape2):], shape2): + if i is None or j is None: + output_shape.append(None) + elif i == 1: + output_shape.append(j) + elif j == 1: + output_shape.append(i) + else: + if i != j: + raise ValueError( + 'Operands could not be broadcast ' + 'together with shapes ' + str(shape1) + ' ' + str(shape2)) + output_shape.append(i) + return tuple(output_shape) + + @tf_utils.shape_type_conversion + def build(self, input_shape): + # Used purely for shape validation. + if not isinstance(input_shape[0], tuple): + raise ValueError('A merge layer should be called on a list of inputs.') + if len(input_shape) < 2: + raise ValueError('A merge layer should be called ' + 'on a list of at least 2 inputs. ' + 'Got ' + str(len(input_shape)) + ' inputs.') + batch_sizes = {s[0] for s in input_shape if s} - {None} + if len(batch_sizes) > 1: + raise ValueError( + 'Can not merge tensors with different ' + 'batch sizes. Got tensors with shapes : ' + str(input_shape)) + if input_shape[0] is None: + output_shape = None + else: + output_shape = input_shape[0][1:] + for i in range(1, len(input_shape)): + if input_shape[i] is None: + shape = None + else: + shape = input_shape[i][1:] + output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) + # If the inputs have different ranks, we have to reshape them + # to make them broadcastable. + if None not in input_shape and len(set(map(len, input_shape))) == 1: + self._reshape_required = False + else: + self._reshape_required = True + + def call(self, inputs): + if not isinstance(inputs, (list, tuple)): + raise ValueError('A merge layer should be called on a list of inputs.') + if self._reshape_required: + reshaped_inputs = [] + input_ndims = list(map(backend.ndim, inputs)) + if None not in input_ndims: + # If ranks of all inputs are available, + # we simply expand each of them at axis=1 + # until all of them have the same rank. + max_ndim = max(input_ndims) + for x in inputs: + x_ndim = backend.ndim(x) + for _ in range(max_ndim - x_ndim): + x = array_ops.expand_dims(x, axis=1) + reshaped_inputs.append(x) + return self._merge_function(reshaped_inputs) + else: + # Transpose all inputs so that batch size is the last dimension. + # (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... , batch_size) + transposed = False + for x in inputs: + x_ndim = backend.ndim(x) + if x_ndim is None: + x_shape = array_ops.shape(x) + batch_size = x_shape[0] + new_shape = backend.concatenate( + [x_shape[1:], + array_ops.expand_dims(batch_size, axis=-1)]) + x_transposed = array_ops.reshape( + x, + array_ops_stack.stack( + [batch_size, math_ops.reduce_prod(x_shape[1:])], axis=0)) + x_transposed = array_ops.transpose(x_transposed, perm=(1, 0)) + x_transposed = array_ops.reshape(x_transposed, new_shape) + reshaped_inputs.append(x_transposed) + transposed = True + elif x_ndim > 1: + dims = list(range(1, x_ndim)) + [0] + reshaped_inputs.append(array_ops.transpose(x, perm=dims)) + transposed = True + else: + # We don't transpose inputs if they are 1D vectors or scalars. + reshaped_inputs.append(x) + y = self._merge_function(reshaped_inputs) + y_ndim = backend.ndim(y) + if transposed: + # If inputs have been transposed, we have to transpose the output too. + if y_ndim is None: + y_shape = array_ops.shape(y) + y_ndim = array_ops.shape(y_shape)[0] + batch_size = y_shape[y_ndim - 1] + new_shape = backend.concatenate([ + array_ops.expand_dims(batch_size, axis=-1), y_shape[:y_ndim - 1] + ]) + y = array_ops.reshape(y, (-1, batch_size)) + y = array_ops.transpose(y, perm=(1, 0)) + y = array_ops.reshape(y, new_shape) + elif y_ndim > 1: + dims = [y_ndim - 1] + list(range(y_ndim - 1)) + y = array_ops.transpose(y, perm=dims) + return y + else: + return self._merge_function(inputs) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if input_shape[0] is None: + output_shape = None + else: + output_shape = input_shape[0][1:] + for i in range(1, len(input_shape)): + if input_shape[i] is None: + shape = None + else: + shape = input_shape[i][1:] + output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) + batch_sizes = {s[0] for s in input_shape if s is not None} - {None} + if len(batch_sizes) == 1: + output_shape = (list(batch_sizes)[0],) + output_shape + else: + output_shape = (None,) + output_shape + return output_shape + + def compute_mask(self, inputs, mask=None): + if mask is None: + return None + if not isinstance(mask, (tuple, list)): + raise ValueError('`mask` should be a list.') + if not isinstance(inputs, (tuple, list)): + raise ValueError('`inputs` should be a list.') + if len(mask) != len(inputs): + raise ValueError('The lists `inputs` and `mask` ' + 'should have the same length.') + if all(m is None for m in mask): + return None + masks = [array_ops.expand_dims(m, axis=0) for m in mask if m is not None] + return backend.all( + backend.concatenate(masks, axis=0), axis=0, keepdims=False) + + +class Add(_Merge): + """Layer that adds a list of inputs. + + It takes as input a list of tensors, + all of the same shape, and returns + a single tensor (also of the same shape). + + Examples: + + >>> input_shape = (2, 3, 4) + >>> x1 = tf.random.normal(input_shape) + >>> x2 = tf.random.normal(input_shape) + >>> y = tf.keras.layers.Add()([x1, x2]) + >>> print(y.shape) + (2, 3, 4) + + Used in a functional model: + + >>> input1 = tf.keras.layers.Input(shape=(16,)) + >>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1) + >>> input2 = tf.keras.layers.Input(shape=(32,)) + >>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2) + >>> # equivalent to `added = tf.keras.layers.add([x1, x2])` + >>> added = tf.keras.layers.Add()([x1, x2]) + >>> out = tf.keras.layers.Dense(4)(added) + >>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + + """ + + def _merge_function(self, inputs): + output = inputs[0] + for i in range(1, len(inputs)): + output += inputs[i] + return output + + +class Subtract(_Merge): + """Layer that subtracts two inputs. + + It takes as input a list of tensors of size 2, + both of the same shape, and returns a single tensor, (inputs[0] - inputs[1]), + also of the same shape. + + Examples: + + ```python + import keras + + input1 = keras.layers.Input(shape=(16,)) + x1 = keras.layers.Dense(8, activation='relu')(input1) + input2 = keras.layers.Input(shape=(32,)) + x2 = keras.layers.Dense(8, activation='relu')(input2) + # Equivalent to subtracted = keras.layers.subtract([x1, x2]) + subtracted = keras.layers.Subtract()([x1, x2]) + + out = keras.layers.Dense(4)(subtracted) + model = keras.models.Model(inputs=[input1, input2], outputs=out) + ``` + """ + + @tf_utils.shape_type_conversion + def build(self, input_shape): + super(Subtract, self).build(input_shape) + if len(input_shape) != 2: + raise ValueError('A `Subtract` layer should be called ' + 'on exactly 2 inputs') + + def _merge_function(self, inputs): + if len(inputs) != 2: + raise ValueError('A `Subtract` layer should be called ' + 'on exactly 2 inputs') + return inputs[0] - inputs[1] + + +class Multiply(_Merge): + """Layer that multiplies (element-wise) a list of inputs. + + It takes as input a list of tensors, all of the same shape, and returns + a single tensor (also of the same shape). + + >>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1), + ... np.arange(5, 10).reshape(5, 1)]) + + + >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) + >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) + >>> multiplied = tf.keras.layers.Multiply()([x1, x2]) + >>> multiplied.shape + TensorShape([5, 8]) + """ + + def _merge_function(self, inputs): + output = inputs[0] + for i in range(1, len(inputs)): + output = output * inputs[i] + return output + + +class Average(_Merge): + """Layer that averages a list of inputs element-wise. + + It takes as input a list of tensors, all of the same shape, and returns + a single tensor (also of the same shape). + + Example: + + >>> x1 = np.ones((2, 2)) + >>> x2 = np.zeros((2, 2)) + >>> y = tf.keras.layers.Average()([x1, x2]) + >>> y.numpy().tolist() + [[0.5, 0.5], [0.5, 0.5]] + + Usage in a functional model: + + >>> input1 = tf.keras.layers.Input(shape=(16,)) + >>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1) + >>> input2 = tf.keras.layers.Input(shape=(32,)) + >>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2) + >>> avg = tf.keras.layers.Average()([x1, x2]) + >>> out = tf.keras.layers.Dense(4)(avg) + >>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + + Raises: + ValueError: If there is a shape mismatch between the inputs and the shapes + cannot be broadcasted to match. + """ + + def _merge_function(self, inputs): + output = inputs[0] + for i in range(1, len(inputs)): + output += inputs[i] + return output / len(inputs) + + +class Maximum(_Merge): + """Layer that computes the maximum (element-wise) a list of inputs. + + It takes as input a list of tensors, all of the same shape, and returns + a single tensor (also of the same shape). + + >>> tf.keras.layers.Maximum()([np.arange(5).reshape(5, 1), + ... np.arange(5, 10).reshape(5, 1)]) + + + >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) + >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) + >>> maxed = tf.keras.layers.Maximum()([x1, x2]) + >>> maxed.shape + TensorShape([5, 8]) + """ + + def _merge_function(self, inputs): + output = inputs[0] + for i in range(1, len(inputs)): + output = math_ops.maximum(output, inputs[i]) + return output + + +class Minimum(_Merge): + """Layer that computes the minimum (element-wise) a list of inputs. + + It takes as input a list of tensors, all of the same shape, and returns + a single tensor (also of the same shape). + + >>> tf.keras.layers.Minimum()([np.arange(5).reshape(5, 1), + ... np.arange(5, 10).reshape(5, 1)]) + + + >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) + >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) + >>> minned = tf.keras.layers.Minimum()([x1, x2]) + >>> minned.shape + TensorShape([5, 8]) + """ + + def _merge_function(self, inputs): + output = inputs[0] + for i in range(1, len(inputs)): + output = math_ops.minimum(output, inputs[i]) + return output + + +class Concatenate(_Merge): + """Layer that concatenates a list of inputs. + + It takes as input a list of tensors, all of the same shape except + for the concatenation axis, and returns a single tensor that is the + concatenation of all inputs. + + >>> x = np.arange(20).reshape(2, 2, 5) + >>> print(x) + [[[ 0 1 2 3 4] + [ 5 6 7 8 9]] + [[10 11 12 13 14] + [15 16 17 18 19]]] + >>> y = np.arange(20, 30).reshape(2, 1, 5) + >>> print(y) + [[[20 21 22 23 24]] + [[25 26 27 28 29]]] + >>> tf.keras.layers.Concatenate(axis=1)([x, y]) + + + >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) + >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) + >>> concatted = tf.keras.layers.Concatenate()([x1, x2]) + >>> concatted.shape + TensorShape([5, 16]) + + """ + + def __init__(self, axis=-1, **kwargs): + """Instantiates a Concatenate layer. + + >>> x = np.arange(20).reshape(2, 2, 5) + >>> print(x) + [[[ 0 1 2 3 4] + [ 5 6 7 8 9]] + [[10 11 12 13 14] + [15 16 17 18 19]]] + >>> y = np.arange(20, 30).reshape(2, 1, 5) + >>> print(y) + [[[20 21 22 23 24]] + [[25 26 27 28 29]]] + >>> tf.keras.layers.Concatenate(axis=1)([x, y]) + + + Args: + axis: Axis along which to concatenate. + **kwargs: standard layer keyword arguments. + """ + super(Concatenate, self).__init__(**kwargs) + self.axis = axis + self.supports_masking = True + self._reshape_required = False + + @tf_utils.shape_type_conversion + def build(self, input_shape): + # Used purely for shape validation. + if not isinstance(input_shape[0], tuple) or len(input_shape) < 1: + raise ValueError('A `Concatenate` layer should be called ' + 'on a list of at least 1 input.') + if all(shape is None for shape in input_shape): + return + reduced_inputs_shapes = [list(shape) for shape in input_shape] + shape_set = set() + for i in range(len(reduced_inputs_shapes)): + del reduced_inputs_shapes[i][self.axis] + shape_set.add(tuple(reduced_inputs_shapes[i])) + + if len(shape_set) != 1: + err_msg = ('A `Concatenate` layer requires inputs with matching shapes ' + 'except for the concat axis. Got inputs shapes: %s' % + input_shape) + # Make sure all the shapes have same ranks. + ranks = set(len(shape) for shape in shape_set) + if len(ranks) != 1: + raise ValueError(err_msg) + # Get the only rank for the set. + (rank,) = ranks + for axis in range(rank): + # Skip the Nones in the shape since they are dynamic, also the axis for + # concat has been removed above. + unique_dims = set( + shape[axis] for shape in shape_set if shape[axis] is not None) + if len(unique_dims) > 1: + raise ValueError(err_msg) + + def _merge_function(self, inputs): + return backend.concatenate(inputs, axis=self.axis) + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if ((not isinstance(input_shape, (tuple, list))) or + (not isinstance(input_shape[0], (tuple, list)))): + # The tf_utils.shape_type_conversion decorator turns tensorshapes + # into tuples, so we need to verify that `input_shape` is a list/tuple, + # *and* that the individual elements are themselves shape tuples. + raise ValueError('A `Concatenate` layer should be called ' + 'on a list of inputs.') + input_shapes = input_shape + output_shape = list(input_shapes[0]) + for shape in input_shapes[1:]: + if output_shape[self.axis] is None or shape[self.axis] is None: + output_shape[self.axis] = None + break + output_shape[self.axis] += shape[self.axis] + return tuple(output_shape) + + def compute_mask(self, inputs, mask=None): + if mask is None: + return None + if not isinstance(mask, (tuple, list)): + raise ValueError('`mask` should be a list.') + if not isinstance(inputs, (tuple, list)): + raise ValueError('`inputs` should be a list.') + if len(mask) != len(inputs): + raise ValueError('The lists `inputs` and `mask` ' + 'should have the same length.') + if all(m is None for m in mask): + return None + # Make a list of masks while making sure + # the dimensionality of each mask + # is the same as the corresponding input. + masks = [] + for input_i, mask_i in zip(inputs, mask): + if mask_i is None: + # Input is unmasked. Append all 1s to masks, + masks.append(array_ops.ones_like(input_i, dtype='bool')) + elif backend.ndim(mask_i) < backend.ndim(input_i): + # Mask is smaller than the input, expand it + masks.append(array_ops.expand_dims(mask_i, axis=-1)) + else: + masks.append(mask_i) + concatenated = backend.concatenate(masks, axis=self.axis) + return backend.all(concatenated, axis=-1, keepdims=False) + + def get_config(self): + config = { + 'axis': self.axis, + } + base_config = super(Concatenate, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Dot(_Merge): + """Layer that computes a dot product between samples in two tensors. + + E.g. if applied to a list of two tensors `a` and `b` of shape + `(batch_size, n)`, the output will be a tensor of shape `(batch_size, 1)` + where each entry `i` will be the dot product between + `a[i]` and `b[i]`. + + >>> x = np.arange(10).reshape(1, 5, 2) + >>> print(x) + [[[0 1] + [2 3] + [4 5] + [6 7] + [8 9]]] + >>> y = np.arange(10, 20).reshape(1, 2, 5) + >>> print(y) + [[[10 11 12 13 14] + [15 16 17 18 19]]] + >>> tf.keras.layers.Dot(axes=(1, 2))([x, y]) + + + >>> x1 = tf.keras.layers.Dense(8)(np.arange(10).reshape(5, 2)) + >>> x2 = tf.keras.layers.Dense(8)(np.arange(10, 20).reshape(5, 2)) + >>> dotted = tf.keras.layers.Dot(axes=1)([x1, x2]) + >>> dotted.shape + TensorShape([5, 1]) + + + """ + + def __init__(self, axes, normalize=False, **kwargs): + """Initializes a layer that computes the element-wise dot product. + + >>> x = np.arange(10).reshape(1, 5, 2) + >>> print(x) + [[[0 1] + [2 3] + [4 5] + [6 7] + [8 9]]] + >>> y = np.arange(10, 20).reshape(1, 2, 5) + >>> print(y) + [[[10 11 12 13 14] + [15 16 17 18 19]]] + >>> tf.keras.layers.Dot(axes=(1, 2))([x, y]) + + + Args: + axes: Integer or tuple of integers, + axis or axes along which to take the dot product. If a tuple, should + be two integers corresponding to the desired axis from the first input + and the desired axis from the second input, respectively. Note that the + size of the two selected axes must match. + normalize: Whether to L2-normalize samples along the + dot product axis before taking the dot product. + If set to True, then the output of the dot product + is the cosine proximity between the two samples. + **kwargs: Standard layer keyword arguments. + """ + super(Dot, self).__init__(**kwargs) + if not isinstance(axes, int): + if not isinstance(axes, (list, tuple)): + raise TypeError('Invalid type for `axes` - ' + 'should be a list or an int.') + if len(axes) != 2: + raise ValueError('Invalid format for `axes` - ' + 'should contain two elements.') + if not isinstance(axes[0], int) or not isinstance(axes[1], int): + raise ValueError('Invalid format for `axes` - ' + 'list elements should be "int".') + self.axes = axes + self.normalize = normalize + self.supports_masking = True + self._reshape_required = False + + @tf_utils.shape_type_conversion + def build(self, input_shape): + # Used purely for shape validation. + if not isinstance(input_shape[0], tuple) or len(input_shape) != 2: + raise ValueError('A `Dot` layer should be called ' + 'on a list of 2 inputs.') + shape1 = input_shape[0] + shape2 = input_shape[1] + if shape1 is None or shape2 is None: + return + if isinstance(self.axes, int): + if self.axes < 0: + axes = [self.axes % len(shape1), self.axes % len(shape2)] + else: + axes = [self.axes] * 2 + else: + axes = self.axes + if shape1[axes[0]] != shape2[axes[1]]: + raise ValueError('Dimension incompatibility ' + '%s != %s. ' % (shape1[axes[0]], shape2[axes[1]]) + + 'Layer shapes: %s, %s. ' % (shape1, shape2) + + 'Chosen axes: %s, %s' % (axes[0], axes[1])) + + def _merge_function(self, inputs): + base_layer_utils.no_ragged_support(inputs, self.name) + if len(inputs) != 2: + raise ValueError('A `Dot` layer should be called on exactly 2 inputs') + x1 = inputs[0] + x2 = inputs[1] + if isinstance(self.axes, int): + if self.axes < 0: + axes = [self.axes % backend.ndim(x1), self.axes % backend.ndim(x2)] + else: + axes = [self.axes] * 2 + else: + axes = [] + for i in range(len(self.axes)): + if self.axes[i] < 0: + axes.append(self.axes[i] % backend.ndim(inputs[i])) + else: + axes.append(self.axes[i]) + if self.normalize: + x1 = nn.l2_normalize(x1, axis=axes[0]) + x2 = nn.l2_normalize(x2, axis=axes[1]) + output = backend.batch_dot(x1, x2, axes) + return output + + @tf_utils.shape_type_conversion + def compute_output_shape(self, input_shape): + if not isinstance(input_shape, (tuple, list)) or len(input_shape) != 2: + raise ValueError('A `Dot` layer should be called ' + 'on a list of 2 inputs.') + shape1 = list(input_shape[0]) + shape2 = list(input_shape[1]) + if isinstance(self.axes, int): + if self.axes < 0: + axes = [self.axes % len(shape1), self.axes % len(shape2)] + else: + axes = [self.axes] * 2 + else: + axes = self.axes + shape1.pop(axes[0]) + shape2.pop(axes[1]) + shape2.pop(0) + output_shape = shape1 + shape2 + if len(output_shape) == 1: + output_shape += [1] + return tuple(output_shape) + + def compute_mask(self, inputs, mask=None): + return None + + def get_config(self): + config = { + 'axes': self.axes, + 'normalize': self.normalize, + } + base_config = super(Dot, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +def add(inputs, **kwargs): + """Functional interface to the `tf.keras.layers.Add` layer. + + Args: + inputs: A list of input tensors (at least 2) with the same shape. + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor as the sum of the inputs. It has the same shape as the inputs. + + Examples: + + >>> input_shape = (2, 3, 4) + >>> x1 = tf.random.normal(input_shape) + >>> x2 = tf.random.normal(input_shape) + >>> y = tf.keras.layers.add([x1, x2]) + >>> print(y.shape) + (2, 3, 4) + + Used in a functional model: + + >>> input1 = tf.keras.layers.Input(shape=(16,)) + >>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1) + >>> input2 = tf.keras.layers.Input(shape=(32,)) + >>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2) + >>> added = tf.keras.layers.add([x1, x2]) + >>> out = tf.keras.layers.Dense(4)(added) + >>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + + """ + return Add(**kwargs)(inputs) + + +def subtract(inputs, **kwargs): + """Functional interface to the `Subtract` layer. + + Args: + inputs: A list of input tensors (exactly 2). + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the difference of the inputs. + + Examples: + + ```python + import keras + + input1 = keras.layers.Input(shape=(16,)) + x1 = keras.layers.Dense(8, activation='relu')(input1) + input2 = keras.layers.Input(shape=(32,)) + x2 = keras.layers.Dense(8, activation='relu')(input2) + subtracted = keras.layers.subtract([x1, x2]) + + out = keras.layers.Dense(4)(subtracted) + model = keras.models.Model(inputs=[input1, input2], outputs=out) + ``` + """ + return Subtract(**kwargs)(inputs) + + +def multiply(inputs, **kwargs): + """Functional interface to the `Multiply` layer. + + Example: + + >>> x1 = np.arange(3.0) + >>> x2 = np.arange(3.0) + >>> tf.keras.layers.multiply([x1, x2]) + + + Usage in a functional model: + + >>> input1 = tf.keras.layers.Input(shape=(16,)) + >>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1) #shape=(None, 8) + >>> input2 = tf.keras.layers.Input(shape=(32,)) + >>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2) #shape=(None, 8) + >>> out = tf.keras.layers.multiply([x1,x2]) #shape=(None, 8) + >>> out = tf.keras.layers.Dense(4)(out) + >>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + + Args: + inputs: A list of input tensors (at least 2). + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the element-wise product of the inputs. + """ + return Multiply(**kwargs)(inputs) + + +def average(inputs, **kwargs): + """Functional interface to the `tf.keras.layers.Average` layer. + + Example: + + >>> x1 = np.ones((2, 2)) + >>> x2 = np.zeros((2, 2)) + >>> y = tf.keras.layers.Average()([x1, x2]) + >>> y.numpy().tolist() + [[0.5, 0.5], [0.5, 0.5]] + + Usage in a functional model: + + >>> input1 = tf.keras.layers.Input(shape=(16,)) + >>> x1 = tf.keras.layers.Dense(8, activation='relu')(input1) + >>> input2 = tf.keras.layers.Input(shape=(32,)) + >>> x2 = tf.keras.layers.Dense(8, activation='relu')(input2) + >>> avg = tf.keras.layers.Average()([x1, x2]) + >>> out = tf.keras.layers.Dense(4)(avg) + >>> model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + + Args: + inputs: A list of input tensors (at least 2). + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the average of the inputs. + + Raises: + ValueError: If there is a shape mismatch between the inputs and the shapes + cannot be broadcasted to match. + """ + return Average(**kwargs)(inputs) + + +def maximum(inputs, **kwargs): + """Functional interface to compute maximum (element-wise) list of `inputs`. + + This is equivalent to the `tf.keras.layers.Maximum` layer. + + For example: + + ```python + input1 = tf.keras.layers.Input(shape=(16,)) + x1 = tf.keras.layers.Dense(8, activation='relu')(input1) #shape=(None, 8) + input2 = tf.keras.layers.Input(shape=(32,)) + x2 = tf.keras.layers.Dense(8, activation='relu')(input2) #shape=(None, 8) + max_inp=tf.keras.layers.maximum([x1,x2]) #shape=(None, 8) + out = tf.keras.layers.Dense(4)(max_inp) + model = tf.keras.models.Model(inputs=[input1, input2], outputs=out) + ``` + + Args: + inputs: A list of input tensors (at least 2) of same shape. + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor (of same shape as input tensor) with the element-wise + maximum of the inputs. + + Raises: + ValueError: If input tensors are of different shape. + """ + return Maximum(**kwargs)(inputs) + + +def minimum(inputs, **kwargs): + """Functional interface to the `Minimum` layer. + + Args: + inputs: A list of input tensors (at least 2). + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the element-wise minimum of the inputs. + """ + return Minimum(**kwargs)(inputs) + + +def concatenate(inputs, axis=-1, **kwargs): + """Functional interface to the `Concatenate` layer. + + >>> x = np.arange(20).reshape(2, 2, 5) + >>> print(x) + [[[ 0 1 2 3 4] + [ 5 6 7 8 9]] + [[10 11 12 13 14] + [15 16 17 18 19]]] + >>> y = np.arange(20, 30).reshape(2, 1, 5) + >>> print(y) + [[[20 21 22 23 24]] + [[25 26 27 28 29]]] + >>> tf.keras.layers.concatenate([x, y], + ... axis=1) + + + Args: + inputs: A list of input tensors (at least 2). + axis: Concatenation axis. + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the concatenation of the inputs alongside axis `axis`. + """ + return Concatenate(axis=axis, **kwargs)(inputs) + + +def dot(inputs, axes, normalize=False, **kwargs): + """Functional interface to the `Dot` layer. + + Args: + inputs: A list of input tensors (at least 2). + axes: Integer or tuple of integers, + axis or axes along which to take the dot product. + normalize: Whether to L2-normalize samples along the + dot product axis before taking the dot product. + If set to True, then the output of the dot product + is the cosine proximity between the two samples. + **kwargs: Standard layer keyword arguments. + + Returns: + A tensor, the dot product of the samples from the inputs. + """ + return Dot(axes=axes, normalize=normalize, **kwargs)(inputs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/pooling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..61d24ee0acd2fad4a39c13a8ca91edf2b683351a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/pooling.py @@ -0,0 +1,1315 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Pooling layers.""" + +import functools + +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.utils import conv_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn + + +class Pooling1D(Layer): + """Pooling layer for arbitrary pooling functions, for 1D inputs. + + This class only exists for code reuse. It will never be an exposed API. + + Args: + pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. + pool_size: An integer or tuple/list of a single integer, + representing the size of the pooling window. + strides: An integer or tuple/list of a single integer, specifying the + strides of the pooling operation. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, steps, features)` while `channels_first` + corresponds to inputs with shape + `(batch, features, steps)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_function, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + super(Pooling1D, self).__init__(name=name, **kwargs) + if data_format is None: + data_format = backend.image_data_format() + if strides is None: + strides = pool_size + self.pool_function = pool_function + self.pool_size = conv_utils.normalize_tuple(pool_size, 1, 'pool_size') + self.strides = conv_utils.normalize_tuple(strides, 1, 'strides') + self.padding = conv_utils.normalize_padding(padding) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(ndim=3) + + def call(self, inputs): + pad_axis = 2 if self.data_format == 'channels_last' else 3 + inputs = array_ops.expand_dims(inputs, pad_axis) + outputs = self.pool_function( + inputs, + self.pool_size + (1,), + strides=self.strides + (1,), + padding=self.padding, + data_format=self.data_format) + return array_ops.squeeze(outputs, pad_axis) + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + steps = input_shape[2] + features = input_shape[1] + else: + steps = input_shape[1] + features = input_shape[2] + length = conv_utils.conv_output_length(steps, + self.pool_size[0], + self.padding, + self.strides[0]) + if self.data_format == 'channels_first': + return tensor_shape.TensorShape([input_shape[0], features, length]) + else: + return tensor_shape.TensorShape([input_shape[0], length, features]) + + def get_config(self): + config = { + 'strides': self.strides, + 'pool_size': self.pool_size, + 'padding': self.padding, + 'data_format': self.data_format, + } + base_config = super(Pooling1D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MaxPooling1D(Pooling1D): + """Max pooling operation for 1D temporal data. + + Downsamples the input representation by taking the maximum value over a + spatial window of size `pool_size`. The window is shifted by `strides`. The + resulting output, when using the `"valid"` padding option, has a shape of: + `output_shape = (input_shape - pool_size + 1) / strides)` + + The resulting output shape when using the `"same"` padding option is: + `output_shape = input_shape / strides` + + For example, for `strides=1` and `padding="valid"`: + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, + ... strides=1, padding='valid') + >>> max_pool_1d(x) + + + For example, for `strides=2` and `padding="valid"`: + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, + ... strides=2, padding='valid') + >>> max_pool_1d(x) + + + For example, for `strides=1` and `padding="same"`: + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, + ... strides=1, padding='same') + >>> max_pool_1d(x) + + + Args: + pool_size: Integer, size of the max pooling window. + strides: Integer, or None. Specifies how much the pooling window moves + for each pooling step. + If None, it will default to `pool_size`. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, steps, features)` while `channels_first` + corresponds to inputs with shape + `(batch, features, steps)`. + + Input shape: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, steps, features)`. + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, steps)`. + + Output shape: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, downsampled_steps, features)`. + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, downsampled_steps)`. + """ + + def __init__(self, pool_size=2, strides=None, + padding='valid', data_format='channels_last', **kwargs): + + super(MaxPooling1D, self).__init__( + functools.partial(backend.pool2d, pool_mode='max'), + pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + **kwargs) + + +class AveragePooling1D(Pooling1D): + """Average pooling for temporal data. + + Downsamples the input representation by taking the average value over the + window defined by `pool_size`. The window is shifted by `strides`. The + resulting output when using "valid" padding option has a shape of: + `output_shape = (input_shape - pool_size + 1) / strides)` + + The resulting output shape when using the "same" padding option is: + `output_shape = input_shape / strides` + + For example, for strides=1 and padding="valid": + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> x + + >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, + ... strides=1, padding='valid') + >>> avg_pool_1d(x) + + + For example, for strides=2 and padding="valid": + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> x + + >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, + ... strides=2, padding='valid') + >>> avg_pool_1d(x) + + + For example, for strides=1 and padding="same": + + >>> x = tf.constant([1., 2., 3., 4., 5.]) + >>> x = tf.reshape(x, [1, 5, 1]) + >>> x + + >>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2, + ... strides=1, padding='same') + >>> avg_pool_1d(x) + + + Args: + pool_size: Integer, size of the average pooling windows. + strides: Integer, or None. Factor by which to downscale. + E.g. 2 will halve the input. + If None, it will default to `pool_size`. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, steps, features)` while `channels_first` + corresponds to inputs with shape + `(batch, features, steps)`. + + Input shape: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, steps, features)`. + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, steps)`. + + Output shape: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, downsampled_steps, features)`. + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, downsampled_steps)`. + """ + + def __init__(self, pool_size=2, strides=None, + padding='valid', data_format='channels_last', **kwargs): + super(AveragePooling1D, self).__init__( + functools.partial(backend.pool2d, pool_mode='avg'), + pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + **kwargs) + + +class Pooling2D(Layer): + """Pooling layer for arbitrary pooling functions, for 2D inputs (e.g. images). + + This class only exists for code reuse. It will never be an exposed API. + + Args: + pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. + pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_function, pool_size, strides, + padding='valid', data_format=None, + name=None, **kwargs): + super(Pooling2D, self).__init__(name=name, **kwargs) + if data_format is None: + data_format = backend.image_data_format() + if strides is None: + strides = pool_size + self.pool_function = pool_function + self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size') + self.strides = conv_utils.normalize_tuple(strides, 2, 'strides') + self.padding = conv_utils.normalize_padding(padding) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(ndim=4) + + def call(self, inputs): + if self.data_format == 'channels_last': + pool_shape = (1,) + self.pool_size + (1,) + strides = (1,) + self.strides + (1,) + else: + pool_shape = (1, 1) + self.pool_size + strides = (1, 1) + self.strides + outputs = self.pool_function( + inputs, + ksize=pool_shape, + strides=strides, + padding=self.padding.upper(), + data_format=conv_utils.convert_data_format(self.data_format, 4)) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + rows = input_shape[2] + cols = input_shape[3] + else: + rows = input_shape[1] + cols = input_shape[2] + rows = conv_utils.conv_output_length(rows, self.pool_size[0], self.padding, + self.strides[0]) + cols = conv_utils.conv_output_length(cols, self.pool_size[1], self.padding, + self.strides[1]) + if self.data_format == 'channels_first': + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], rows, cols]) + else: + return tensor_shape.TensorShape( + [input_shape[0], rows, cols, input_shape[3]]) + + def get_config(self): + config = { + 'pool_size': self.pool_size, + 'padding': self.padding, + 'strides': self.strides, + 'data_format': self.data_format + } + base_config = super(Pooling2D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MaxPooling2D(Pooling2D): + """Max pooling operation for 2D spatial data. + + Downsamples the input along its spatial dimensions (height and width) + by taking the maximum value over an input window + (of size defined by `pool_size`) for each channel of the input. + The window is shifted by `strides` along each dimension. + + The resulting output, + when using the `"valid"` padding option, has a spatial shape + (number of rows or columns) of: + `output_shape = math.floor((input_shape - pool_size) / strides) + 1` + (when `input_shape >= pool_size`) + + The resulting output shape when using the `"same"` padding option is: + `output_shape = math.floor((input_shape - 1) / strides) + 1` + + For example, for `strides=(1, 1)` and `padding="valid"`: + + >>> x = tf.constant([[1., 2., 3.], + ... [4., 5., 6.], + ... [7., 8., 9.]]) + >>> x = tf.reshape(x, [1, 3, 3, 1]) + >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), + ... strides=(1, 1), padding='valid') + >>> max_pool_2d(x) + + + For example, for `strides=(2, 2)` and `padding="valid"`: + + >>> x = tf.constant([[1., 2., 3., 4.], + ... [5., 6., 7., 8.], + ... [9., 10., 11., 12.]]) + >>> x = tf.reshape(x, [1, 3, 4, 1]) + >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), + ... strides=(2, 2), padding='valid') + >>> max_pool_2d(x) + + + Usage Example: + + >>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]], + ... [[2.], [2.], [3.], [2.]], + ... [[4.], [1.], [1.], [1.]], + ... [[2.], [2.], [1.], [4.]]]]) + >>> output = tf.constant([[[[1], [0]], + ... [[0], [1]]]]) + >>> model = tf.keras.models.Sequential() + >>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), + ... input_shape=(4, 4, 1))) + >>> model.compile('adam', 'mean_squared_error') + >>> model.predict(input_image, steps=1) + array([[[[2.], + [4.]], + [[4.], + [4.]]]], dtype=float32) + + For example, for stride=(1, 1) and padding="same": + + >>> x = tf.constant([[1., 2., 3.], + ... [4., 5., 6.], + ... [7., 8., 9.]]) + >>> x = tf.reshape(x, [1, 3, 3, 1]) + >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), + ... strides=(1, 1), padding='same') + >>> max_pool_2d(x) + + + Args: + pool_size: integer or tuple of 2 integers, + window size over which to take the maximum. + `(2, 2)` will take the max value over a 2x2 pooling window. + If only one integer is specified, the same window length + will be used for both dimensions. + strides: Integer, tuple of 2 integers, or None. + Strides values. Specifies how far the pooling window moves + for each pooling step. If None, it will default to `pool_size`. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, rows, cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, rows, cols)`. + + Output shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`. + + Returns: + A tensor of rank 4 representing the maximum pooled values. See above for + output shape. + """ + + def __init__(self, + pool_size=(2, 2), + strides=None, + padding='valid', + data_format=None, + **kwargs): + super(MaxPooling2D, self).__init__( + nn.max_pool, + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, **kwargs) + + +class AveragePooling2D(Pooling2D): + """Average pooling operation for spatial data. + + Downsamples the input along its spatial dimensions (height and width) + by taking the average value over an input window + (of size defined by `pool_size`) for each channel of the input. + The window is shifted by `strides` along each dimension. + + The resulting output when using `"valid"` padding option has a shape + (number of rows or columns) of: + `output_shape = math.floor((input_shape - pool_size) / strides) + 1` + (when `input_shape >= pool_size`) + + The resulting output shape when using the `"same"` padding option is: + `output_shape = math.floor((input_shape - 1) / strides) + 1` + + For example, for `strides=(1, 1)` and `padding="valid"`: + + >>> x = tf.constant([[1., 2., 3.], + ... [4., 5., 6.], + ... [7., 8., 9.]]) + >>> x = tf.reshape(x, [1, 3, 3, 1]) + >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), + ... strides=(1, 1), padding='valid') + >>> avg_pool_2d(x) + + + For example, for `stride=(2, 2)` and `padding="valid"`: + + >>> x = tf.constant([[1., 2., 3., 4.], + ... [5., 6., 7., 8.], + ... [9., 10., 11., 12.]]) + >>> x = tf.reshape(x, [1, 3, 4, 1]) + >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), + ... strides=(2, 2), padding='valid') + >>> avg_pool_2d(x) + + + For example, for `strides=(1, 1)` and `padding="same"`: + + >>> x = tf.constant([[1., 2., 3.], + ... [4., 5., 6.], + ... [7., 8., 9.]]) + >>> x = tf.reshape(x, [1, 3, 3, 1]) + >>> avg_pool_2d = tf.keras.layers.AveragePooling2D(pool_size=(2, 2), + ... strides=(1, 1), padding='same') + >>> avg_pool_2d(x) + + + Args: + pool_size: integer or tuple of 2 integers, + factors by which to downscale (vertical, horizontal). + `(2, 2)` will halve the input in both spatial dimension. + If only one integer is specified, the same window length + will be used for both dimensions. + strides: Integer, tuple of 2 integers, or None. + Strides values. + If None, it will default to `pool_size`. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, rows, cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, rows, cols)`. + + Output shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`. + """ + + def __init__(self, + pool_size=(2, 2), + strides=None, + padding='valid', + data_format=None, + **kwargs): + super(AveragePooling2D, self).__init__( + nn.avg_pool, + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, **kwargs) + + +class Pooling3D(Layer): + """Pooling layer for arbitrary pooling functions, for 3D inputs. + + This class only exists for code reuse. It will never be an exposed API. + + Args: + pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`. + pool_size: An integer or tuple/list of 3 integers: + (pool_depth, pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` + while `channels_first` corresponds to + inputs with shape `(batch, channels, depth, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_function, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + super(Pooling3D, self).__init__(name=name, **kwargs) + if data_format is None: + data_format = backend.image_data_format() + if strides is None: + strides = pool_size + self.pool_function = pool_function + self.pool_size = conv_utils.normalize_tuple(pool_size, 3, 'pool_size') + self.strides = conv_utils.normalize_tuple(strides, 3, 'strides') + self.padding = conv_utils.normalize_padding(padding) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(ndim=5) + + def call(self, inputs): + pool_shape = (1,) + self.pool_size + (1,) + strides = (1,) + self.strides + (1,) + + if self.data_format == 'channels_first': + # TF does not support `channels_first` with 3D pooling operations, + # so we must handle this case manually. + # TODO(fchollet): remove this when TF pooling is feature-complete. + inputs = array_ops.transpose(inputs, (0, 2, 3, 4, 1)) + + outputs = self.pool_function( + inputs, + ksize=pool_shape, + strides=strides, + padding=self.padding.upper()) + + if self.data_format == 'channels_first': + outputs = array_ops.transpose(outputs, (0, 4, 1, 2, 3)) + return outputs + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + len_dim1 = input_shape[2] + len_dim2 = input_shape[3] + len_dim3 = input_shape[4] + else: + len_dim1 = input_shape[1] + len_dim2 = input_shape[2] + len_dim3 = input_shape[3] + len_dim1 = conv_utils.conv_output_length(len_dim1, self.pool_size[0], + self.padding, self.strides[0]) + len_dim2 = conv_utils.conv_output_length(len_dim2, self.pool_size[1], + self.padding, self.strides[1]) + len_dim3 = conv_utils.conv_output_length(len_dim3, self.pool_size[2], + self.padding, self.strides[2]) + if self.data_format == 'channels_first': + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3]) + else: + return tensor_shape.TensorShape( + [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]]) + + def get_config(self): + config = { + 'pool_size': self.pool_size, + 'padding': self.padding, + 'strides': self.strides, + 'data_format': self.data_format + } + base_config = super(Pooling3D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MaxPooling3D(Pooling3D): + """Max pooling operation for 3D data (spatial or spatio-temporal). + + Downsamples the input along its spatial dimensions (depth, height, and width) + by taking the maximum value over an input window + (of size defined by `pool_size`) for each channel of the input. + The window is shifted by `strides` along each dimension. + + Args: + pool_size: Tuple of 3 integers, + factors by which to downscale (dim1, dim2, dim3). + `(2, 2, 2)` will halve the size of the 3D input in each dimension. + strides: tuple of 3 integers, or None. Strides values. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` + + Output shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)` + + Example: + + ```python + depth = 30 + height = 30 + width = 30 + input_channels = 3 + + inputs = tf.keras.Input(shape=(depth, height, width, input_channels)) + layer = tf.keras.layers.MaxPooling3D(pool_size=3) + outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3) + ``` + """ + + def __init__(self, + pool_size=(2, 2, 2), + strides=None, + padding='valid', + data_format=None, + **kwargs): + super(MaxPooling3D, self).__init__( + nn.max_pool3d, + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, **kwargs) + + +class AveragePooling3D(Pooling3D): + """Average pooling operation for 3D data (spatial or spatio-temporal). + + Downsamples the input along its spatial dimensions (depth, height, and width) + by taking the average value over an input window + (of size defined by `pool_size`) for each channel of the input. + The window is shifted by `strides` along each dimension. + + Args: + pool_size: tuple of 3 integers, + factors by which to downscale (dim1, dim2, dim3). + `(2, 2, 2)` will halve the size of the 3D input in each dimension. + strides: tuple of 3 integers, or None. Strides values. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + + Input shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` + + Output shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)` + + Example: + + ```python + depth = 30 + height = 30 + width = 30 + input_channels = 3 + + inputs = tf.keras.Input(shape=(depth, height, width, input_channels)) + layer = tf.keras.layers.AveragePooling3D(pool_size=3) + outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3) + ``` + """ + + def __init__(self, + pool_size=(2, 2, 2), + strides=None, + padding='valid', + data_format=None, + **kwargs): + super(AveragePooling3D, self).__init__( + nn.avg_pool3d, + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, **kwargs) + + +class GlobalPooling1D(Layer): + """Abstract class for different global pooling 1D layers.""" + + def __init__(self, data_format='channels_last', keepdims=False, **kwargs): + super(GlobalPooling1D, self).__init__(**kwargs) + self.input_spec = InputSpec(ndim=3) + self.data_format = conv_utils.normalize_data_format(data_format) + self.keepdims = keepdims + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_first': + if self.keepdims: + return tensor_shape.TensorShape([input_shape[0], input_shape[1], 1]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[1]]) + else: + if self.keepdims: + return tensor_shape.TensorShape([input_shape[0], 1, input_shape[2]]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[2]]) + + def call(self, inputs): + raise NotImplementedError + + def get_config(self): + config = {'data_format': self.data_format, 'keepdims': self.keepdims} + base_config = super(GlobalPooling1D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class GlobalAveragePooling1D(GlobalPooling1D): + """Global average pooling operation for temporal data. + + Examples: + + >>> input_shape = (2, 3, 4) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.GlobalAveragePooling1D()(x) + >>> print(y.shape) + (2, 4) + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, steps, features)` while `channels_first` + corresponds to inputs with shape + `(batch, features, steps)`. + keepdims: A boolean, whether to keep the temporal dimension or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the temporal dimension are retained with + length 1. + The behavior is the same as for `tf.reduce_mean` or `np.mean`. + + Call arguments: + inputs: A 3D tensor. + mask: Binary tensor of shape `(batch_size, steps)` indicating whether + a given step should be masked (excluded from the average). + + Input shape: + - If `data_format='channels_last'`: + 3D tensor with shape: + `(batch_size, steps, features)` + - If `data_format='channels_first'`: + 3D tensor with shape: + `(batch_size, features, steps)` + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, features)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, 1, features)` + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, 1)` + """ + + def __init__(self, data_format='channels_last', **kwargs): + super(GlobalAveragePooling1D, self).__init__(data_format=data_format, + **kwargs) + self.supports_masking = True + + def call(self, inputs, mask=None): + steps_axis = 1 if self.data_format == 'channels_last' else 2 + if mask is not None: + mask = math_ops.cast(mask, inputs[0].dtype) + mask = array_ops.expand_dims( + mask, 2 if self.data_format == 'channels_last' else 1) + inputs *= mask + return backend.sum( + inputs, axis=steps_axis, + keepdims=self.keepdims) / math_ops.reduce_sum( + mask, axis=steps_axis, keepdims=self.keepdims) + else: + return backend.mean(inputs, axis=steps_axis, keepdims=self.keepdims) + + def compute_mask(self, inputs, mask=None): + return None + + +class GlobalMaxPooling1D(GlobalPooling1D): + """Global max pooling operation for 1D temporal data. + + Downsamples the input representation by taking the maximum value over + the time dimension. + + For example: + + >>> x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) + >>> x = tf.reshape(x, [3, 3, 1]) + >>> x + + >>> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D() + >>> max_pool_1d(x) + + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, steps, features)` while `channels_first` + corresponds to inputs with shape + `(batch, features, steps)`. + keepdims: A boolean, whether to keep the temporal dimension or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the temporal dimension are retained with + length 1. + The behavior is the same as for `tf.reduce_max` or `np.max`. + + Input shape: + - If `data_format='channels_last'`: + 3D tensor with shape: + `(batch_size, steps, features)` + - If `data_format='channels_first'`: + 3D tensor with shape: + `(batch_size, features, steps)` + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, features)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 3D tensor with shape `(batch_size, 1, features)` + - If `data_format='channels_first'`: + 3D tensor with shape `(batch_size, features, 1)` + """ + + def call(self, inputs): + steps_axis = 1 if self.data_format == 'channels_last' else 2 + return backend.max(inputs, axis=steps_axis, keepdims=self.keepdims) + + +class GlobalPooling2D(Layer): + """Abstract class for different global pooling 2D layers. + """ + + def __init__(self, data_format=None, keepdims=False, **kwargs): + super(GlobalPooling2D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(ndim=4) + self.keepdims = keepdims + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_last': + if self.keepdims: + return tensor_shape.TensorShape([input_shape[0], 1, 1, input_shape[3]]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[3]]) + else: + if self.keepdims: + return tensor_shape.TensorShape([input_shape[0], input_shape[1], 1, 1]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[1]]) + + def call(self, inputs): + raise NotImplementedError + + def get_config(self): + config = {'data_format': self.data_format, 'keepdims': self.keepdims} + base_config = super(GlobalPooling2D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class GlobalAveragePooling2D(GlobalPooling2D): + """Global average pooling operation for spatial data. + + Examples: + + >>> input_shape = (2, 4, 5, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.GlobalAveragePooling2D()(x) + >>> print(y.shape) + (2, 3) + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + keepdims: A boolean, whether to keep the spatial dimensions or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the spatial dimensions are retained with + length 1. + The behavior is the same as for `tf.reduce_mean` or `np.mean`. + + Input shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, rows, cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, rows, cols)`. + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, channels)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, 1, 1, channels)` + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, 1, 1)` + """ + + def call(self, inputs): + if self.data_format == 'channels_last': + return backend.mean(inputs, axis=[1, 2], keepdims=self.keepdims) + else: + return backend.mean(inputs, axis=[2, 3], keepdims=self.keepdims) + + +class GlobalMaxPooling2D(GlobalPooling2D): + """Global max pooling operation for spatial data. + + Examples: + + >>> input_shape = (2, 4, 5, 3) + >>> x = tf.random.normal(input_shape) + >>> y = tf.keras.layers.GlobalMaxPool2D()(x) + >>> print(y.shape) + (2, 3) + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, height, width)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + keepdims: A boolean, whether to keep the spatial dimensions or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the spatial dimensions are retained with + length 1. + The behavior is the same as for `tf.reduce_max` or `np.max`. + + Input shape: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, rows, cols, channels)`. + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, rows, cols)`. + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, channels)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 4D tensor with shape `(batch_size, 1, 1, channels)` + - If `data_format='channels_first'`: + 4D tensor with shape `(batch_size, channels, 1, 1)` + """ + + def call(self, inputs): + if self.data_format == 'channels_last': + return backend.max(inputs, axis=[1, 2], keepdims=self.keepdims) + else: + return backend.max(inputs, axis=[2, 3], keepdims=self.keepdims) + + +class GlobalPooling3D(Layer): + """Abstract class for different global pooling 3D layers.""" + + def __init__(self, data_format=None, keepdims=False, **kwargs): + super(GlobalPooling3D, self).__init__(**kwargs) + self.data_format = conv_utils.normalize_data_format(data_format) + self.input_spec = InputSpec(ndim=5) + self.keepdims = keepdims + + def compute_output_shape(self, input_shape): + input_shape = tensor_shape.TensorShape(input_shape).as_list() + if self.data_format == 'channels_last': + if self.keepdims: + return tensor_shape.TensorShape( + [input_shape[0], 1, 1, 1, input_shape[4]]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[4]]) + else: + if self.keepdims: + return tensor_shape.TensorShape( + [input_shape[0], input_shape[1], 1, 1, 1]) + else: + return tensor_shape.TensorShape([input_shape[0], input_shape[1]]) + + def call(self, inputs): + raise NotImplementedError + + def get_config(self): + config = {'data_format': self.data_format, 'keepdims': self.keepdims} + base_config = super(GlobalPooling3D, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class GlobalAveragePooling3D(GlobalPooling3D): + """Global Average pooling operation for 3D data. + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + keepdims: A boolean, whether to keep the spatial dimensions or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the spatial dimensions are retained with + length 1. + The behavior is the same as for `tf.reduce_mean` or `np.mean`. + + Input shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, channels)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 5D tensor with shape `(batch_size, 1, 1, 1, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape `(batch_size, channels, 1, 1, 1)` + """ + + def call(self, inputs): + if self.data_format == 'channels_last': + return backend.mean(inputs, axis=[1, 2, 3], keepdims=self.keepdims) + else: + return backend.mean(inputs, axis=[2, 3, 4], keepdims=self.keepdims) + + +class GlobalMaxPooling3D(GlobalPooling3D): + """Global Max pooling operation for 3D data. + + Args: + data_format: A string, + one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + while `channels_first` corresponds to inputs with shape + `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. + It defaults to the `image_data_format` value found in your + Keras config file at `~/.keras/keras.json`. + If you never set it, then it will be "channels_last". + keepdims: A boolean, whether to keep the spatial dimensions or not. + If `keepdims` is `False` (default), the rank of the tensor is reduced + for spatial dimensions. + If `keepdims` is `True`, the spatial dimensions are retained with + length 1. + The behavior is the same as for `tf.reduce_max` or `np.max`. + + Input shape: + - If `data_format='channels_last'`: + 5D tensor with shape: + `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape: + `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` + + Output shape: + - If `keepdims`=False: + 2D tensor with shape `(batch_size, channels)`. + - If `keepdims`=True: + - If `data_format='channels_last'`: + 5D tensor with shape `(batch_size, 1, 1, 1, channels)` + - If `data_format='channels_first'`: + 5D tensor with shape `(batch_size, channels, 1, 1, 1)` + """ + + def call(self, inputs): + if self.data_format == 'channels_last': + return backend.max(inputs, axis=[1, 2, 3], keepdims=self.keepdims) + else: + return backend.max(inputs, axis=[2, 3, 4], keepdims=self.keepdims) + + +# Aliases + +AvgPool1D = AveragePooling1D +MaxPool1D = MaxPooling1D +AvgPool2D = AveragePooling2D +MaxPool2D = MaxPooling2D +AvgPool3D = AveragePooling3D +MaxPool3D = MaxPooling3D +GlobalMaxPool1D = GlobalMaxPooling1D +GlobalMaxPool2D = GlobalMaxPooling2D +GlobalMaxPool3D = GlobalMaxPooling3D +GlobalAvgPool1D = GlobalAveragePooling1D +GlobalAvgPool2D = GlobalAveragePooling2D +GlobalAvgPool3D = GlobalAveragePooling3D diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/recurrent.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/recurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..94b85f29e693d971faaa254ae105f169b08a4894 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/recurrent.py @@ -0,0 +1,3084 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=g-classes-have-attributes +"""Recurrent layers and their base classes.""" + +import collections +import warnings + +import numpy as np + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend +from tensorflow.python.keras import constraints +from tensorflow.python.keras import initializers +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_spec import InputSpec +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + + +RECURRENT_DROPOUT_WARNING_MSG = ( + 'RNN `implementation=2` is not supported when `recurrent_dropout` is set. ' + 'Using `implementation=1`.') + + +class StackedRNNCells(Layer): + """Wrapper allowing a stack of RNN cells to behave as a single cell. + + Used to implement efficient stacked RNNs. + + Args: + cells: List of RNN cell instances. + + Examples: + + ```python + batch_size = 3 + sentence_max_length = 5 + n_features = 2 + new_shape = (batch_size, sentence_max_length, n_features) + x = tf.constant(np.reshape(np.arange(30), new_shape), dtype = tf.float32) + + rnn_cells = [tf.keras.layers.LSTMCell(128) for _ in range(2)] + stacked_lstm = tf.keras.layers.StackedRNNCells(rnn_cells) + lstm_layer = tf.keras.layers.RNN(stacked_lstm) + + result = lstm_layer(x) + ``` + """ + + def __init__(self, cells, **kwargs): + for cell in cells: + if not 'call' in dir(cell): + raise ValueError('All cells must have a `call` method. ' + 'received cells:', cells) + if not 'state_size' in dir(cell): + raise ValueError('All cells must have a ' + '`state_size` attribute. ' + 'received cells:', cells) + self.cells = cells + # reverse_state_order determines whether the state size will be in a reverse + # order of the cells' state. User might want to set this to True to keep the + # existing behavior. This is only useful when use RNN(return_state=True) + # since the state will be returned as the same order of state_size. + self.reverse_state_order = kwargs.pop('reverse_state_order', False) + if self.reverse_state_order: + logging.warning('reverse_state_order=True in StackedRNNCells will soon ' + 'be deprecated. Please update the code to work with the ' + 'natural order of states if you rely on the RNN states, ' + 'eg RNN(return_state=True).') + super(StackedRNNCells, self).__init__(**kwargs) + + @property + def state_size(self): + return tuple(c.state_size for c in + (self.cells[::-1] if self.reverse_state_order else self.cells)) + + @property + def output_size(self): + if getattr(self.cells[-1], 'output_size', None) is not None: + return self.cells[-1].output_size + elif _is_multiple_state(self.cells[-1].state_size): + return self.cells[-1].state_size[0] + else: + return self.cells[-1].state_size + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + initial_states = [] + for cell in self.cells[::-1] if self.reverse_state_order else self.cells: + get_initial_state_fn = getattr(cell, 'get_initial_state', None) + if get_initial_state_fn: + initial_states.append(get_initial_state_fn( + inputs=inputs, batch_size=batch_size, dtype=dtype)) + else: + initial_states.append(_generate_zero_filled_state_for_cell( + cell, inputs, batch_size, dtype)) + + return tuple(initial_states) + + def call(self, inputs, states, constants=None, training=None, **kwargs): + # Recover per-cell states. + state_size = (self.state_size[::-1] + if self.reverse_state_order else self.state_size) + nested_states = nest.pack_sequence_as(state_size, nest.flatten(states)) + + # Call the cells in order and store the returned states. + new_nested_states = [] + for cell, states in zip(self.cells, nested_states): + states = states if nest.is_nested(states) else [states] + # TF cell does not wrap the state into list when there is only one state. + is_tf_rnn_cell = getattr(cell, '_is_tf_rnn_cell', None) is not None + states = states[0] if len(states) == 1 and is_tf_rnn_cell else states + if generic_utils.has_arg(cell.call, 'training'): + kwargs['training'] = training + else: + kwargs.pop('training', None) + # Use the __call__ function for callable objects, eg layers, so that it + # will have the proper name scopes for the ops, etc. + cell_call_fn = cell.__call__ if callable(cell) else cell.call + if generic_utils.has_arg(cell.call, 'constants'): + inputs, states = cell_call_fn(inputs, states, + constants=constants, **kwargs) + else: + inputs, states = cell_call_fn(inputs, states, **kwargs) + new_nested_states.append(states) + + return inputs, nest.pack_sequence_as(state_size, + nest.flatten(new_nested_states)) + + @tf_utils.shape_type_conversion + def build(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + for cell in self.cells: + if isinstance(cell, Layer) and not cell.built: + with backend.name_scope(cell.name): + cell.build(input_shape) + cell.built = True + if getattr(cell, 'output_size', None) is not None: + output_dim = cell.output_size + elif _is_multiple_state(cell.state_size): + output_dim = cell.state_size[0] + else: + output_dim = cell.state_size + input_shape = tuple([input_shape[0]] + + tensor_shape.TensorShape(output_dim).as_list()) + self.built = True + + def get_config(self): + cells = [] + for cell in self.cells: + cells.append(generic_utils.serialize_keras_object(cell)) + config = {'cells': cells} + base_config = super(StackedRNNCells, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top + cells = [] + for cell_config in config.pop('cells'): + cells.append( + deserialize_layer(cell_config, custom_objects=custom_objects)) + return cls(cells, **config) + + +class RNN(Layer): + """Base class for recurrent layers. + + See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) + for details about the usage of RNN API. + + Args: + cell: A RNN cell instance or a list of RNN cell instances. + A RNN cell is a class that has: + - A `call(input_at_t, states_at_t)` method, returning + `(output_at_t, states_at_t_plus_1)`. The call method of the + cell can also take the optional argument `constants`, see + section "Note on passing external constants" below. + - A `state_size` attribute. This can be a single integer + (single state) in which case it is the size of the recurrent + state. This can also be a list/tuple of integers (one size per state). + The `state_size` can also be TensorShape or tuple/list of + TensorShape, to represent high dimension state. + - A `output_size` attribute. This can be a single integer or a + TensorShape, which represent the shape of the output. For backward + compatible reason, if this attribute is not available for the + cell, the value will be inferred by the first element of the + `state_size`. + - A `get_initial_state(inputs=None, batch_size=None, dtype=None)` + method that creates a tensor meant to be fed to `call()` as the + initial state, if the user didn't specify any initial state via other + means. The returned initial state should have a shape of + [batch_size, cell.state_size]. The cell might choose to create a + tensor full of zeros, or full of other values based on the cell's + implementation. + `inputs` is the input tensor to the RNN layer, which should + contain the batch size as its shape[0], and also dtype. Note that + the shape[0] might be `None` during the graph construction. Either + the `inputs` or the pair of `batch_size` and `dtype` are provided. + `batch_size` is a scalar tensor that represents the batch size + of the inputs. `dtype` is `tf.DType` that represents the dtype of + the inputs. + For backward compatibility, if this method is not implemented + by the cell, the RNN layer will create a zero filled tensor with the + size of [batch_size, cell.state_size]. + In the case that `cell` is a list of RNN cell instances, the cells + will be stacked on top of each other in the RNN, resulting in an + efficient stacked RNN. + return_sequences: Boolean (default `False`). Whether to return the last + output in the output sequence, or the full sequence. + return_state: Boolean (default `False`). Whether to return the last state + in addition to the output. + go_backwards: Boolean (default `False`). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default `False`). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + unroll: Boolean (default `False`). + If True, the network will be unrolled, else a symbolic loop will be used. + Unrolling can speed-up a RNN, although it tends to be more + memory-intensive. Unrolling is only suitable for short sequences. + time_major: The shape format of the `inputs` and `outputs` tensors. + If True, the inputs and outputs will be in shape + `(timesteps, batch, ...)`, whereas in the False case, it will be + `(batch, timesteps, ...)`. Using `time_major = True` is a bit more + efficient because it avoids transposes at the beginning and end of the + RNN calculation. However, most TensorFlow data is batch-major, so by + default this function accepts input and emits output in batch-major + form. + zero_output_for_mask: Boolean (default `False`). + Whether the output should use zeros for the masked timesteps. Note that + this field is only used when `return_sequences` is True and mask is + provided. It can useful if you want to reuse the raw output sequence of + the RNN without interference from the masked timesteps, eg, merging + bidirectional RNNs. + + Call arguments: + inputs: Input tensor. + mask: Binary tensor of shape `[batch_size, timesteps]` indicating whether + a given timestep should be masked. An individual `True` entry indicates + that the corresponding timestep should be utilized, while a `False` + entry indicates that the corresponding timestep should be ignored. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is for use with cells that use dropout. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + constants: List of constant tensors to be passed to the cell at each + timestep. + + Input shape: + N-D tensor with shape `[batch_size, timesteps, ...]` or + `[timesteps, batch_size, ...]` when time_major is True. + + Output shape: + - If `return_state`: a list of tensors. The first tensor is + the output. The remaining tensors are the last states, + each with shape `[batch_size, state_size]`, where `state_size` could + be a high dimension tensor shape. + - If `return_sequences`: N-D tensor with shape + `[batch_size, timesteps, output_size]`, where `output_size` could + be a high dimension tensor shape, or + `[timesteps, batch_size, output_size]` when `time_major` is True. + - Else, N-D tensor with shape `[batch_size, output_size]`, where + `output_size` could be a high dimension tensor shape. + + Masking: + This layer supports masking for input data with a variable number + of timesteps. To introduce masks to your data, + use an [tf.keras.layers.Embedding] layer with the `mask_zero` parameter + set to `True`. + + Note on using statefulness in RNNs: + You can set RNN layers to be 'stateful', which means that the states + computed for the samples in one batch will be reused as initial states + for the samples in the next batch. This assumes a one-to-one mapping + between samples in different successive batches. + + To enable statefulness: + - Specify `stateful=True` in the layer constructor. + - Specify a fixed batch size for your model, by passing + If sequential model: + `batch_input_shape=(...)` to the first layer in your model. + Else for functional model with 1 or more Input layers: + `batch_shape=(...)` to all the first layers in your model. + This is the expected shape of your inputs + *including the batch size*. + It should be a tuple of integers, e.g. `(32, 10, 100)`. + - Specify `shuffle=False` when calling `fit()`. + + To reset the states of your model, call `.reset_states()` on either + a specific layer, or on your entire model. + + Note on specifying the initial state of RNNs: + You can specify the initial state of RNN layers symbolically by + calling them with the keyword argument `initial_state`. The value of + `initial_state` should be a tensor or list of tensors representing + the initial state of the RNN layer. + + You can specify the initial state of RNN layers numerically by + calling `reset_states` with the keyword argument `states`. The value of + `states` should be a numpy array or list of numpy arrays representing + the initial state of the RNN layer. + + Note on passing external constants to RNNs: + You can pass "external" constants to the cell using the `constants` + keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This + requires that the `cell.call` method accepts the same keyword argument + `constants`. Such constants can be used to condition the cell + transformation on additional static inputs (not changing over time), + a.k.a. an attention mechanism. + + Examples: + + ```python + # First, let's define a RNN Cell, as a layer subclass. + + class MinimalRNNCell(keras.layers.Layer): + + def __init__(self, units, **kwargs): + self.units = units + self.state_size = units + super(MinimalRNNCell, self).__init__(**kwargs) + + def build(self, input_shape): + self.kernel = self.add_weight(shape=(input_shape[-1], self.units), + initializer='uniform', + name='kernel') + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units), + initializer='uniform', + name='recurrent_kernel') + self.built = True + + def call(self, inputs, states): + prev_output = states[0] + h = backend.dot(inputs, self.kernel) + output = h + backend.dot(prev_output, self.recurrent_kernel) + return output, [output] + + # Let's use this cell in a RNN layer: + + cell = MinimalRNNCell(32) + x = keras.Input((None, 5)) + layer = RNN(cell) + y = layer(x) + + # Here's how to use the cell to build a stacked RNN: + + cells = [MinimalRNNCell(32), MinimalRNNCell(64)] + x = keras.Input((None, 5)) + layer = RNN(cells) + y = layer(x) + ``` + """ + + def __init__(self, + cell, + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + time_major=False, + **kwargs): + if isinstance(cell, (list, tuple)): + cell = StackedRNNCells(cell) + if not 'call' in dir(cell): + raise ValueError('`cell` should have a `call` method. ' + 'The RNN was passed:', cell) + if not 'state_size' in dir(cell): + raise ValueError('The RNN cell should have ' + 'an attribute `state_size` ' + '(tuple of integers, ' + 'one integer per RNN state).') + # If True, the output for masked timestep will be zeros, whereas in the + # False case, output from previous timestep is returned for masked timestep. + self.zero_output_for_mask = kwargs.pop('zero_output_for_mask', False) + + if 'input_shape' not in kwargs and ( + 'input_dim' in kwargs or 'input_length' in kwargs): + input_shape = (kwargs.pop('input_length', None), + kwargs.pop('input_dim', None)) + kwargs['input_shape'] = input_shape + + super(RNN, self).__init__(**kwargs) + self.cell = cell + self.return_sequences = return_sequences + self.return_state = return_state + self.go_backwards = go_backwards + self.stateful = stateful + self.unroll = unroll + self.time_major = time_major + + self.supports_masking = True + # The input shape is unknown yet, it could have nested tensor inputs, and + # the input spec will be the list of specs for nested inputs, the structure + # of the input_spec will be the same as the input. + self.input_spec = None + self.state_spec = None + self._states = None + self.constants_spec = None + self._num_constants = 0 + + if stateful: + if distribute_lib.has_strategy(): + raise ValueError('RNNs with stateful=True not yet supported with ' + 'tf.distribute.Strategy.') + + @property + def _use_input_spec_as_call_signature(self): + if self.unroll: + # When the RNN layer is unrolled, the time step shape cannot be unknown. + # The input spec does not define the time step (because this layer can be + # called with any time step value, as long as it is not None), so it + # cannot be used as the call function signature when saving to SavedModel. + return False + return super(RNN, self)._use_input_spec_as_call_signature + + @property + def states(self): + if self._states is None: + state = nest.map_structure(lambda _: None, self.cell.state_size) + return state if nest.is_nested(self.cell.state_size) else [state] + return self._states + + @states.setter + # Automatic tracking catches "self._states" which adds an extra weight and + # breaks HDF5 checkpoints. + @trackable.no_automatic_dependency_tracking + def states(self, states): + self._states = states + + def compute_output_shape(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + # Check whether the input shape contains any nested shapes. It could be + # (tensor_shape(1, 2), tensor_shape(3, 4)) or (1, 2, 3) which is from numpy + # inputs. + try: + input_shape = tensor_shape.TensorShape(input_shape) + except (ValueError, TypeError): + # A nested tensor input + input_shape = nest.flatten(input_shape)[0] + + batch = input_shape[0] + time_step = input_shape[1] + if self.time_major: + batch, time_step = time_step, batch + + if _is_multiple_state(self.cell.state_size): + state_size = self.cell.state_size + else: + state_size = [self.cell.state_size] + + def _get_output_shape(flat_output_size): + output_dim = tensor_shape.TensorShape(flat_output_size).as_list() + if self.return_sequences: + if self.time_major: + output_shape = tensor_shape.TensorShape( + [time_step, batch] + output_dim) + else: + output_shape = tensor_shape.TensorShape( + [batch, time_step] + output_dim) + else: + output_shape = tensor_shape.TensorShape([batch] + output_dim) + return output_shape + + if getattr(self.cell, 'output_size', None) is not None: + # cell.output_size could be nested structure. + output_shape = nest.flatten(nest.map_structure( + _get_output_shape, self.cell.output_size)) + output_shape = output_shape[0] if len(output_shape) == 1 else output_shape + else: + # Note that state_size[0] could be a tensor_shape or int. + output_shape = _get_output_shape(state_size[0]) + + if self.return_state: + def _get_state_shape(flat_state): + state_shape = [batch] + tensor_shape.TensorShape(flat_state).as_list() + return tensor_shape.TensorShape(state_shape) + state_shape = nest.map_structure(_get_state_shape, state_size) + return generic_utils.to_list(output_shape) + nest.flatten(state_shape) + else: + return output_shape + + def compute_mask(self, inputs, mask): + # Time step masks must be the same for each input. + # This is because the mask for an RNN is of size [batch, time_steps, 1], + # and specifies which time steps should be skipped, and a time step + # must be skipped for all inputs. + # TODO(scottzhu): Should we accept multiple different masks? + mask = nest.flatten(mask)[0] + output_mask = mask if self.return_sequences else None + if self.return_state: + state_mask = [None for _ in self.states] + return [output_mask] + state_mask + else: + return output_mask + + def build(self, input_shape): + if isinstance(input_shape, list): + input_shape = input_shape[0] + # The input_shape here could be a nest structure. + + # do the tensor_shape to shapes here. The input could be single tensor, or a + # nested structure of tensors. + def get_input_spec(shape): + """Convert input shape to InputSpec.""" + if isinstance(shape, tensor_shape.TensorShape): + input_spec_shape = shape.as_list() + else: + input_spec_shape = list(shape) + batch_index, time_step_index = (1, 0) if self.time_major else (0, 1) + if not self.stateful: + input_spec_shape[batch_index] = None + input_spec_shape[time_step_index] = None + return InputSpec(shape=tuple(input_spec_shape)) + + def get_step_input_shape(shape): + if isinstance(shape, tensor_shape.TensorShape): + shape = tuple(shape.as_list()) + # remove the timestep from the input_shape + return shape[1:] if self.time_major else (shape[0],) + shape[2:] + + # Check whether the input shape contains any nested shapes. It could be + # (tensor_shape(1, 2), tensor_shape(3, 4)) or (1, 2, 3) which is from numpy + # inputs. + try: + input_shape = tensor_shape.TensorShape(input_shape) + except (ValueError, TypeError): + # A nested tensor input + pass + + if not nest.is_nested(input_shape): + # This indicates the there is only one input. + if self.input_spec is not None: + self.input_spec[0] = get_input_spec(input_shape) + else: + self.input_spec = [get_input_spec(input_shape)] + step_input_shape = get_step_input_shape(input_shape) + else: + if self.input_spec is not None: + self.input_spec[0] = nest.map_structure(get_input_spec, input_shape) + else: + self.input_spec = generic_utils.to_list( + nest.map_structure(get_input_spec, input_shape)) + step_input_shape = nest.map_structure(get_step_input_shape, input_shape) + + # allow cell (if layer) to build before we set or validate state_spec. + if isinstance(self.cell, Layer) and not self.cell.built: + with backend.name_scope(self.cell.name): + self.cell.build(step_input_shape) + self.cell.built = True + + # set or validate state_spec + if _is_multiple_state(self.cell.state_size): + state_size = list(self.cell.state_size) + else: + state_size = [self.cell.state_size] + + if self.state_spec is not None: + # initial_state was passed in call, check compatibility + self._validate_state_spec(state_size, self.state_spec) + else: + self.state_spec = [ + InputSpec(shape=[None] + tensor_shape.TensorShape(dim).as_list()) + for dim in state_size + ] + if self.stateful: + self.reset_states() + self.built = True + + @staticmethod + def _validate_state_spec(cell_state_sizes, init_state_specs): + """Validate the state spec between the initial_state and the state_size. + + Args: + cell_state_sizes: list, the `state_size` attribute from the cell. + init_state_specs: list, the `state_spec` from the initial_state that is + passed in `call()`. + + Raises: + ValueError: When initial state spec is not compatible with the state size. + """ + validation_error = ValueError( + 'An `initial_state` was passed that is not compatible with ' + '`cell.state_size`. Received `state_spec`={}; ' + 'however `cell.state_size` is ' + '{}'.format(init_state_specs, cell_state_sizes)) + flat_cell_state_sizes = nest.flatten(cell_state_sizes) + flat_state_specs = nest.flatten(init_state_specs) + + if len(flat_cell_state_sizes) != len(flat_state_specs): + raise validation_error + for cell_state_spec, cell_state_size in zip(flat_state_specs, + flat_cell_state_sizes): + if not tensor_shape.TensorShape( + # Ignore the first axis for init_state which is for batch + cell_state_spec.shape[1:]).is_compatible_with( + tensor_shape.TensorShape(cell_state_size)): + raise validation_error + + @doc_controls.do_not_doc_inheritable + def get_initial_state(self, inputs): + get_initial_state_fn = getattr(self.cell, 'get_initial_state', None) + + if nest.is_nested(inputs): + # The input are nested sequences. Use the first element in the seq to get + # batch size and dtype. + inputs = nest.flatten(inputs)[0] + + input_shape = array_ops.shape(inputs) + batch_size = input_shape[1] if self.time_major else input_shape[0] + dtype = inputs.dtype + if get_initial_state_fn: + init_state = get_initial_state_fn( + inputs=None, batch_size=batch_size, dtype=dtype) + else: + init_state = _generate_zero_filled_state(batch_size, self.cell.state_size, + dtype) + # Keras RNN expect the states in a list, even if it's a single state tensor. + if not nest.is_nested(init_state): + init_state = [init_state] + # Force the state to be a list in case it is a namedtuple eg LSTMStateTuple. + return list(init_state) + + def __call__(self, inputs, initial_state=None, constants=None, **kwargs): + inputs, initial_state, constants = _standardize_args(inputs, + initial_state, + constants, + self._num_constants) + + if initial_state is None and constants is None: + return super(RNN, self).__call__(inputs, **kwargs) + + # If any of `initial_state` or `constants` are specified and are Keras + # tensors, then add them to the inputs and temporarily modify the + # input_spec to include them. + + additional_inputs = [] + additional_specs = [] + if initial_state is not None: + additional_inputs += initial_state + self.state_spec = nest.map_structure( + lambda s: InputSpec(shape=backend.int_shape(s)), initial_state) + additional_specs += self.state_spec + if constants is not None: + additional_inputs += constants + self.constants_spec = [ + InputSpec(shape=backend.int_shape(constant)) for constant in constants + ] + self._num_constants = len(constants) + additional_specs += self.constants_spec + # additional_inputs can be empty if initial_state or constants are provided + # but empty (e.g. the cell is stateless). + flat_additional_inputs = nest.flatten(additional_inputs) + is_keras_tensor = backend.is_keras_tensor( + flat_additional_inputs[0]) if flat_additional_inputs else True + for tensor in flat_additional_inputs: + if backend.is_keras_tensor(tensor) != is_keras_tensor: + raise ValueError('The initial state or constants of an RNN' + ' layer cannot be specified with a mix of' + ' Keras tensors and non-Keras tensors' + ' (a "Keras tensor" is a tensor that was' + ' returned by a Keras layer, or by `Input`)') + + if is_keras_tensor: + # Compute the full input spec, including state and constants + full_input = [inputs] + additional_inputs + if self.built: + # Keep the input_spec since it has been populated in build() method. + full_input_spec = self.input_spec + additional_specs + else: + # The original input_spec is None since there could be a nested tensor + # input. Update the input_spec to match the inputs. + full_input_spec = generic_utils.to_list( + nest.map_structure(lambda _: None, inputs)) + additional_specs + # Perform the call with temporarily replaced input_spec + self.input_spec = full_input_spec + output = super(RNN, self).__call__(full_input, **kwargs) + # Remove the additional_specs from input spec and keep the rest. It is + # important to keep since the input spec was populated by build(), and + # will be reused in the stateful=True. + self.input_spec = self.input_spec[:-len(additional_specs)] + return output + else: + if initial_state is not None: + kwargs['initial_state'] = initial_state + if constants is not None: + kwargs['constants'] = constants + return super(RNN, self).__call__(inputs, **kwargs) + + def call(self, + inputs, + mask=None, + training=None, + initial_state=None, + constants=None): + # The input should be dense, padded with zeros. If a ragged input is fed + # into the layer, it is padded and the row lengths are used for masking. + inputs, row_lengths = backend.convert_inputs_if_ragged(inputs) + is_ragged_input = (row_lengths is not None) + self._validate_args_if_ragged(is_ragged_input, mask) + + inputs, initial_state, constants = self._process_inputs( + inputs, initial_state, constants) + + self._maybe_reset_cell_dropout_mask(self.cell) + if isinstance(self.cell, StackedRNNCells): + for cell in self.cell.cells: + self._maybe_reset_cell_dropout_mask(cell) + + if mask is not None: + # Time step masks must be the same for each input. + # TODO(scottzhu): Should we accept multiple different masks? + mask = nest.flatten(mask)[0] + + if nest.is_nested(inputs): + # In the case of nested input, use the first element for shape check. + input_shape = backend.int_shape(nest.flatten(inputs)[0]) + else: + input_shape = backend.int_shape(inputs) + timesteps = input_shape[0] if self.time_major else input_shape[1] + if self.unroll and timesteps is None: + raise ValueError('Cannot unroll a RNN if the ' + 'time dimension is undefined. \n' + '- If using a Sequential model, ' + 'specify the time dimension by passing ' + 'an `input_shape` or `batch_input_shape` ' + 'argument to your first layer. If your ' + 'first layer is an Embedding, you can ' + 'also use the `input_length` argument.\n' + '- If using the functional API, specify ' + 'the time dimension by passing a `shape` ' + 'or `batch_shape` argument to your Input layer.') + + kwargs = {} + if generic_utils.has_arg(self.cell.call, 'training'): + kwargs['training'] = training + + # TF RNN cells expect single tensor as state instead of list wrapped tensor. + is_tf_rnn_cell = getattr(self.cell, '_is_tf_rnn_cell', None) is not None + # Use the __call__ function for callable objects, eg layers, so that it + # will have the proper name scopes for the ops, etc. + cell_call_fn = self.cell.__call__ if callable(self.cell) else self.cell.call + if constants: + if not generic_utils.has_arg(self.cell.call, 'constants'): + raise ValueError('RNN cell does not support constants') + + def step(inputs, states): + constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type + states = states[:-self._num_constants] # pylint: disable=invalid-unary-operand-type + + states = states[0] if len(states) == 1 and is_tf_rnn_cell else states + output, new_states = cell_call_fn( + inputs, states, constants=constants, **kwargs) + if not nest.is_nested(new_states): + new_states = [new_states] + return output, new_states + else: + + def step(inputs, states): + states = states[0] if len(states) == 1 and is_tf_rnn_cell else states + output, new_states = cell_call_fn(inputs, states, **kwargs) + if not nest.is_nested(new_states): + new_states = [new_states] + return output, new_states + last_output, outputs, states = backend.rnn( + step, + inputs, + initial_state, + constants=constants, + go_backwards=self.go_backwards, + mask=mask, + unroll=self.unroll, + input_length=row_lengths if row_lengths is not None else timesteps, + time_major=self.time_major, + zero_output_for_mask=self.zero_output_for_mask) + + if self.stateful: + updates = [ + state_ops.assign(self_state, state) for self_state, state in zip( + nest.flatten(self.states), nest.flatten(states)) + ] + self.add_update(updates) + + if self.return_sequences: + output = backend.maybe_convert_to_ragged( + is_ragged_input, outputs, row_lengths, go_backwards=self.go_backwards) + else: + output = last_output + + if self.return_state: + if not isinstance(states, (list, tuple)): + states = [states] + else: + states = list(states) + return generic_utils.to_list(output) + states + else: + return output + + def _process_inputs(self, inputs, initial_state, constants): + # input shape: `(samples, time (padded with zeros), input_dim)` + # note that the .build() method of subclasses MUST define + # self.input_spec and self.state_spec with complete input shapes. + if (isinstance(inputs, collections.abc.Sequence) + and not isinstance(inputs, tuple)): + # get initial_state from full input spec + # as they could be copied to multiple GPU. + if not self._num_constants: + initial_state = inputs[1:] + else: + initial_state = inputs[1:-self._num_constants] + constants = inputs[-self._num_constants:] + if len(initial_state) == 0: + initial_state = None + inputs = inputs[0] + + if self.stateful: + if initial_state is not None: + # When layer is stateful and initial_state is provided, check if the + # recorded state is same as the default value (zeros). Use the recorded + # state if it is not same as the default. + non_zero_count = math_ops.add_n([math_ops.count_nonzero_v2(s) + for s in nest.flatten(self.states)]) + # Set strict = True to keep the original structure of the state. + initial_state = cond.cond(non_zero_count > 0, + true_fn=lambda: self.states, + false_fn=lambda: initial_state, + strict=True) + else: + initial_state = self.states + elif initial_state is None: + initial_state = self.get_initial_state(inputs) + + if len(initial_state) != len(self.states): + raise ValueError('Layer has ' + str(len(self.states)) + + ' states but was passed ' + str(len(initial_state)) + + ' initial states.') + return inputs, initial_state, constants + + def _validate_args_if_ragged(self, is_ragged_input, mask): + if not is_ragged_input: + return + + if mask is not None: + raise ValueError('The mask that was passed in was ' + str(mask) + + ' and cannot be applied to RaggedTensor inputs. Please ' + 'make sure that there is no mask passed in by upstream ' + 'layers.') + if self.unroll: + raise ValueError('The input received contains RaggedTensors and does ' + 'not support unrolling. Disable unrolling by passing ' + '`unroll=False` in the RNN Layer constructor.') + + def _maybe_reset_cell_dropout_mask(self, cell): + if isinstance(cell, DropoutRNNCellMixin): + cell.reset_dropout_mask() + cell.reset_recurrent_dropout_mask() + + def reset_states(self, states=None): + """Reset the recorded states for the stateful RNN layer. + + Can only be used when RNN layer is constructed with `stateful` = `True`. + Args: + states: Numpy arrays that contains the value for the initial state, which + will be feed to cell at the first time step. When the value is None, + zero filled numpy array will be created based on the cell state size. + + Raises: + AttributeError: When the RNN layer is not stateful. + ValueError: When the batch size of the RNN layer is unknown. + ValueError: When the input numpy array is not compatible with the RNN + layer state, either size wise or dtype wise. + """ + if not self.stateful: + raise AttributeError('Layer must be stateful.') + spec_shape = None + if self.input_spec is not None: + spec_shape = nest.flatten(self.input_spec[0])[0].shape + if spec_shape is None: + # It is possible to have spec shape to be None, eg when construct a RNN + # with a custom cell, or standard RNN layers (LSTM/GRU) which we only know + # it has 3 dim input, but not its full shape spec before build(). + batch_size = None + else: + batch_size = spec_shape[1] if self.time_major else spec_shape[0] + if not batch_size: + raise ValueError('If a 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 `batch_input_shape` ' + 'argument to your first layer.\n' + '- If using the functional API, specify ' + 'the batch size by passing a ' + '`batch_shape` argument to your Input layer.') + # initialize state if None + if nest.flatten(self.states)[0] is None: + if getattr(self.cell, 'get_initial_state', None): + flat_init_state_values = nest.flatten(self.cell.get_initial_state( + inputs=None, batch_size=batch_size, + dtype=self.dtype or backend.floatx())) + else: + flat_init_state_values = nest.flatten(_generate_zero_filled_state( + batch_size, self.cell.state_size, self.dtype or backend.floatx())) + flat_states_variables = nest.map_structure( + backend.variable, flat_init_state_values) + self.states = nest.pack_sequence_as(self.cell.state_size, + flat_states_variables) + if not nest.is_nested(self.states): + self.states = [self.states] + elif states is None: + for state, size in zip(nest.flatten(self.states), + nest.flatten(self.cell.state_size)): + backend.set_value( + state, + np.zeros([batch_size] + tensor_shape.TensorShape(size).as_list())) + else: + flat_states = nest.flatten(self.states) + flat_input_states = nest.flatten(states) + if len(flat_input_states) != len(flat_states): + raise ValueError('Layer ' + self.name + ' expects ' + + str(len(flat_states)) + ' states, ' + 'but it received ' + str(len(flat_input_states)) + + ' state values. Input received: ' + str(states)) + set_value_tuples = [] + for i, (value, state) in enumerate(zip(flat_input_states, + flat_states)): + if value.shape != state.shape: + raise ValueError( + 'State ' + str(i) + ' is incompatible with layer ' + + self.name + ': expected shape=' + str( + (batch_size, state)) + ', found shape=' + str(value.shape)) + set_value_tuples.append((state, value)) + backend.batch_set_value(set_value_tuples) + + def get_config(self): + config = { + 'return_sequences': self.return_sequences, + 'return_state': self.return_state, + 'go_backwards': self.go_backwards, + 'stateful': self.stateful, + 'unroll': self.unroll, + 'time_major': self.time_major + } + if self._num_constants: + config['num_constants'] = self._num_constants + if self.zero_output_for_mask: + config['zero_output_for_mask'] = self.zero_output_for_mask + + config['cell'] = generic_utils.serialize_keras_object(self.cell) + base_config = super(RNN, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top + cell = deserialize_layer(config.pop('cell'), custom_objects=custom_objects) + num_constants = config.pop('num_constants', 0) + layer = cls(cell, **config) + layer._num_constants = num_constants + return layer + + @property + def _trackable_saved_model_saver(self): + return layer_serialization.RNNSavedModelSaver(self) + + +class AbstractRNNCell(Layer): + """Abstract object representing an RNN cell. + + See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) + for details about the usage of RNN API. + + This is the base class for implementing RNN cells with custom behavior. + + Every `RNNCell` must have the properties below and implement `call` with + the signature `(output, next_state) = call(input, state)`. + + Examples: + + ```python + class MinimalRNNCell(AbstractRNNCell): + + def __init__(self, units, **kwargs): + self.units = units + super(MinimalRNNCell, self).__init__(**kwargs) + + @property + def state_size(self): + return self.units + + def build(self, input_shape): + self.kernel = self.add_weight(shape=(input_shape[-1], self.units), + initializer='uniform', + name='kernel') + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units), + initializer='uniform', + name='recurrent_kernel') + self.built = True + + def call(self, inputs, states): + prev_output = states[0] + h = backend.dot(inputs, self.kernel) + output = h + backend.dot(prev_output, self.recurrent_kernel) + return output, output + ``` + + This definition of cell differs from the definition used in the literature. + In the literature, 'cell' refers to an object with a single scalar output. + This definition refers to a horizontal array of such units. + + An RNN cell, in the most abstract setting, is anything that has + a state and performs some operation that takes a matrix of inputs. + This operation results in an output matrix with `self.output_size` columns. + If `self.state_size` is an integer, this operation also results in a new + state matrix with `self.state_size` columns. If `self.state_size` is a + (possibly nested tuple of) TensorShape object(s), then it should return a + matching structure of Tensors having shape `[batch_size].concatenate(s)` + for each `s` in `self.batch_size`. + """ + + def call(self, inputs, states): + """The function that contains the logic for one RNN step calculation. + + Args: + inputs: the input tensor, which is a slide from the overall RNN input by + the time dimension (usually the second dimension). + states: the state tensor from previous step, which has the same shape + as `(batch, state_size)`. In the case of timestep 0, it will be the + initial state user specified, or zero filled tensor otherwise. + + Returns: + A tuple of two tensors: + 1. output tensor for the current timestep, with size `output_size`. + 2. state tensor for next step, which has the shape of `state_size`. + """ + raise NotImplementedError('Abstract method') + + @property + def state_size(self): + """size(s) of state(s) used by this cell. + + It can be represented by an Integer, a TensorShape or a tuple of Integers + or TensorShapes. + """ + raise NotImplementedError('Abstract method') + + @property + def output_size(self): + """Integer or TensorShape: size of outputs produced by this cell.""" + raise NotImplementedError('Abstract method') + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype) + + +@doc_controls.do_not_generate_docs +class DropoutRNNCellMixin(object): + """Object that hold dropout related fields for RNN Cell. + + This class is not a standalone RNN cell. It suppose to be used with a RNN cell + by multiple inheritance. Any cell that mix with class should have following + fields: + dropout: a float number within range [0, 1). The ratio that the input + tensor need to dropout. + recurrent_dropout: a float number within range [0, 1). The ratio that the + recurrent state weights need to dropout. + This object will create and cache created dropout masks, and reuse them for + the incoming data, so that the same mask is used for every batch input. + """ + + def __init__(self, *args, **kwargs): + self._create_non_trackable_mask_cache() + super(DropoutRNNCellMixin, self).__init__(*args, **kwargs) + + @trackable.no_automatic_dependency_tracking + def _create_non_trackable_mask_cache(self): + """Create the cache for dropout and recurrent dropout mask. + + Note that the following two masks will be used in "graph function" mode, + e.g. these masks are symbolic tensors. In eager mode, the `eager_*_mask` + tensors will be generated differently than in the "graph function" case, + and they will be cached. + + Also note that in graph mode, we still cache those masks only because the + RNN could be created with `unroll=True`. In that case, the `cell.call()` + function will be invoked multiple times, and we want to ensure same mask + is used every time. + + Also the caches are created without tracking. Since they are not picklable + by python when deepcopy, we don't want `layer._obj_reference_counts_dict` + to track it by default. + """ + self._dropout_mask_cache = backend.ContextValueCache( + self._create_dropout_mask) + self._recurrent_dropout_mask_cache = backend.ContextValueCache( + self._create_recurrent_dropout_mask) + + def reset_dropout_mask(self): + """Reset the cached dropout masks if any. + + This is important for the RNN layer to invoke this in it `call()` method so + that the cached mask is cleared before calling the `cell.call()`. The mask + should be cached across the timestep within the same batch, but shouldn't + be cached between batches. Otherwise it will introduce unreasonable bias + against certain index of data within the batch. + """ + self._dropout_mask_cache.clear() + + def reset_recurrent_dropout_mask(self): + """Reset the cached recurrent dropout masks if any. + + This is important for the RNN layer to invoke this in it call() method so + that the cached mask is cleared before calling the cell.call(). The mask + should be cached across the timestep within the same batch, but shouldn't + be cached between batches. Otherwise it will introduce unreasonable bias + against certain index of data within the batch. + """ + self._recurrent_dropout_mask_cache.clear() + + def _create_dropout_mask(self, inputs, training, count=1): + return _generate_dropout_mask( + array_ops.ones_like(inputs), + self.dropout, + training=training, + count=count) + + def _create_recurrent_dropout_mask(self, inputs, training, count=1): + return _generate_dropout_mask( + array_ops.ones_like(inputs), + self.recurrent_dropout, + training=training, + count=count) + + def get_dropout_mask_for_cell(self, inputs, training, count=1): + """Get the dropout mask for RNN cell's input. + + It will create mask based on context if there isn't any existing cached + mask. If a new mask is generated, it will update the cache in the cell. + + Args: + inputs: The input tensor whose shape will be used to generate dropout + mask. + training: Boolean tensor, whether its in training mode, dropout will be + ignored in non-training mode. + count: Int, how many dropout mask will be generated. It is useful for cell + that has internal weights fused together. + Returns: + List of mask tensor, generated or cached mask based on context. + """ + if self.dropout == 0: + return None + init_kwargs = dict(inputs=inputs, training=training, count=count) + return self._dropout_mask_cache.setdefault(kwargs=init_kwargs) + + def get_recurrent_dropout_mask_for_cell(self, inputs, training, count=1): + """Get the recurrent dropout mask for RNN cell. + + It will create mask based on context if there isn't any existing cached + mask. If a new mask is generated, it will update the cache in the cell. + + Args: + inputs: The input tensor whose shape will be used to generate dropout + mask. + training: Boolean tensor, whether its in training mode, dropout will be + ignored in non-training mode. + count: Int, how many dropout mask will be generated. It is useful for cell + that has internal weights fused together. + Returns: + List of mask tensor, generated or cached mask based on context. + """ + if self.recurrent_dropout == 0: + return None + init_kwargs = dict(inputs=inputs, training=training, count=count) + return self._recurrent_dropout_mask_cache.setdefault(kwargs=init_kwargs) + + def __getstate__(self): + # Used for deepcopy. The caching can't be pickled by python, since it will + # contain tensor and graph. + state = super(DropoutRNNCellMixin, self).__getstate__() + state.pop('_dropout_mask_cache', None) + state.pop('_recurrent_dropout_mask_cache', None) + return state + + def __setstate__(self, state): + state['_dropout_mask_cache'] = backend.ContextValueCache( + self._create_dropout_mask) + state['_recurrent_dropout_mask_cache'] = backend.ContextValueCache( + self._create_recurrent_dropout_mask) + super(DropoutRNNCellMixin, self).__setstate__(state) + + +class SimpleRNNCell(DropoutRNNCellMixin, Layer): + """Cell class for SimpleRNN. + + See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) + for details about the usage of RNN API. + + This class processes one step within the whole time sequence input, whereas + `tf.keras.layer.SimpleRNN` processes the whole sequence. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, (default `True`), whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. Default: + `glorot_uniform`. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, used for the linear transformation of the recurrent state. + Default: `orthogonal`. + bias_initializer: Initializer for the bias vector. Default: `zeros`. + kernel_regularizer: Regularizer function applied to the `kernel` weights + matrix. Default: `None`. + recurrent_regularizer: Regularizer function applied to the + `recurrent_kernel` weights matrix. Default: `None`. + bias_regularizer: Regularizer function applied to the bias vector. Default: + `None`. + kernel_constraint: Constraint function applied to the `kernel` weights + matrix. Default: `None`. + recurrent_constraint: Constraint function applied to the `recurrent_kernel` + weights matrix. Default: `None`. + bias_constraint: Constraint function applied to the bias vector. Default: + `None`. + dropout: Float between 0 and 1. Fraction of the units to drop for the linear + transformation of the inputs. Default: 0. + recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for + the linear transformation of the recurrent state. Default: 0. + + Call arguments: + inputs: A 2D tensor, with shape of `[batch, feature]`. + states: A 2D tensor with shape of `[batch, units]`, which is the state from + the previous time step. For timestep 0, the initial state provided by user + will be feed to cell. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. Only relevant when `dropout` or + `recurrent_dropout` is used. + + Examples: + + ```python + inputs = np.random.random([32, 10, 8]).astype(np.float32) + rnn = tf.keras.layers.RNN(tf.keras.layers.SimpleRNNCell(4)) + + output = rnn(inputs) # The output has shape `[32, 4]`. + + rnn = tf.keras.layers.RNN( + tf.keras.layers.SimpleRNNCell(4), + return_sequences=True, + return_state=True) + + # whole_sequence_output has shape `[32, 10, 4]`. + # final_state has shape `[32, 4]`. + whole_sequence_output, final_state = rnn(inputs) + ``` + """ + + def __init__(self, + units, + activation='tanh', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + if units < 0: + raise ValueError(f'Received an invalid value for units, expected ' + f'a positive integer, got {units}.') + # By default use cached variable under v2 mode, see b/143699808. + if ops.executing_eagerly_outside_functions(): + self._enable_caching_device = kwargs.pop('enable_caching_device', True) + else: + self._enable_caching_device = kwargs.pop('enable_caching_device', False) + super(SimpleRNNCell, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + self.state_size = self.units + self.output_size = self.units + + @tf_utils.shape_type_conversion + def build(self, input_shape): + default_caching_device = _caching_device(self) + self.kernel = self.add_weight( + shape=(input_shape[-1], self.units), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + caching_device=default_caching_device) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint, + caching_device=default_caching_device) + if self.use_bias: + self.bias = self.add_weight( + shape=(self.units,), + name='bias', + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + caching_device=default_caching_device) + else: + self.bias = None + self.built = True + + def call(self, inputs, states, training=None): + prev_output = states[0] if nest.is_nested(states) else states + dp_mask = self.get_dropout_mask_for_cell(inputs, training) + rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( + prev_output, training) + + if dp_mask is not None: + h = backend.dot(inputs * dp_mask, self.kernel) + else: + h = backend.dot(inputs, self.kernel) + if self.bias is not None: + h = backend.bias_add(h, self.bias) + + if rec_dp_mask is not None: + prev_output = prev_output * rec_dp_mask + output = h + backend.dot(prev_output, self.recurrent_kernel) + if self.activation is not None: + output = self.activation(output) + + new_state = [output] if nest.is_nested(states) else output + return output, new_state + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype) + + def get_config(self): + config = { + 'units': + self.units, + 'activation': + activations.serialize(self.activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint), + 'dropout': + self.dropout, + 'recurrent_dropout': + self.recurrent_dropout + } + config.update(_config_for_enable_caching_device(self)) + base_config = super(SimpleRNNCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SimpleRNN(RNN): + """Fully-connected RNN where the output is to be fed back to input. + + See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn) + for details about the usage of RNN API. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass None, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, (default `True`), whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. Default: + `glorot_uniform`. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, used for the linear transformation of the recurrent state. + Default: `orthogonal`. + bias_initializer: Initializer for the bias vector. Default: `zeros`. + kernel_regularizer: Regularizer function applied to the `kernel` weights + matrix. Default: `None`. + recurrent_regularizer: Regularizer function applied to the + `recurrent_kernel` weights matrix. Default: `None`. + bias_regularizer: Regularizer function applied to the bias vector. Default: + `None`. + activity_regularizer: Regularizer function applied to the output of the + layer (its "activation"). Default: `None`. + kernel_constraint: Constraint function applied to the `kernel` weights + matrix. Default: `None`. + recurrent_constraint: Constraint function applied to the `recurrent_kernel` + weights matrix. Default: `None`. + bias_constraint: Constraint function applied to the bias vector. Default: + `None`. + dropout: Float between 0 and 1. + Fraction of the units to drop for the linear transformation of the inputs. + Default: 0. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for the linear transformation of the + recurrent state. Default: 0. + return_sequences: Boolean. Whether to return the last output + in the output sequence, or the full sequence. Default: `False`. + return_state: Boolean. Whether to return the last state + in addition to the output. Default: `False` + go_backwards: Boolean (default False). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + unroll: Boolean (default False). + If True, the network will be unrolled, + else a symbolic loop will be used. + Unrolling can speed-up a RNN, + although it tends to be more memory-intensive. + Unrolling is only suitable for short sequences. + + Call arguments: + inputs: A 3D tensor, with shape `[batch, timesteps, feature]`. + mask: Binary tensor of shape `[batch, timesteps]` indicating whether + a given timestep should be masked. An individual `True` entry indicates + that the corresponding timestep should be utilized, while a `False` entry + indicates that the corresponding timestep should be ignored. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is only relevant if `dropout` or + `recurrent_dropout` is used. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + + Examples: + + ```python + inputs = np.random.random([32, 10, 8]).astype(np.float32) + simple_rnn = tf.keras.layers.SimpleRNN(4) + + output = simple_rnn(inputs) # The output has shape `[32, 4]`. + + simple_rnn = tf.keras.layers.SimpleRNN( + 4, return_sequences=True, return_state=True) + + # whole_sequence_output has shape `[32, 10, 4]`. + # final_state has shape `[32, 4]`. + whole_sequence_output, final_state = simple_rnn(inputs) + ``` + """ + + def __init__(self, + units, + activation='tanh', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + **kwargs): + if 'implementation' in kwargs: + kwargs.pop('implementation') + logging.warning('The `implementation` argument ' + 'in `SimpleRNN` has been deprecated. ' + 'Please remove it from your layer call.') + if 'enable_caching_device' in kwargs: + cell_kwargs = {'enable_caching_device': + kwargs.pop('enable_caching_device')} + else: + cell_kwargs = {} + cell = SimpleRNNCell( + units, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + recurrent_initializer=recurrent_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + recurrent_regularizer=recurrent_regularizer, + bias_regularizer=bias_regularizer, + kernel_constraint=kernel_constraint, + recurrent_constraint=recurrent_constraint, + bias_constraint=bias_constraint, + dropout=dropout, + recurrent_dropout=recurrent_dropout, + dtype=kwargs.get('dtype'), + trainable=kwargs.get('trainable', True), + **cell_kwargs) + super(SimpleRNN, self).__init__( + cell, + return_sequences=return_sequences, + return_state=return_state, + go_backwards=go_backwards, + stateful=stateful, + unroll=unroll, + **kwargs) + self.activity_regularizer = regularizers.get(activity_regularizer) + self.input_spec = [InputSpec(ndim=3)] + + def call(self, inputs, mask=None, training=None, initial_state=None): + return super(SimpleRNN, self).call( + inputs, mask=mask, training=training, initial_state=initial_state) + + @property + def units(self): + return self.cell.units + + @property + def activation(self): + return self.cell.activation + + @property + def use_bias(self): + return self.cell.use_bias + + @property + def kernel_initializer(self): + return self.cell.kernel_initializer + + @property + def recurrent_initializer(self): + return self.cell.recurrent_initializer + + @property + def bias_initializer(self): + return self.cell.bias_initializer + + @property + def kernel_regularizer(self): + return self.cell.kernel_regularizer + + @property + def recurrent_regularizer(self): + return self.cell.recurrent_regularizer + + @property + def bias_regularizer(self): + return self.cell.bias_regularizer + + @property + def kernel_constraint(self): + return self.cell.kernel_constraint + + @property + def recurrent_constraint(self): + return self.cell.recurrent_constraint + + @property + def bias_constraint(self): + return self.cell.bias_constraint + + @property + def dropout(self): + return self.cell.dropout + + @property + def recurrent_dropout(self): + return self.cell.recurrent_dropout + + def get_config(self): + config = { + 'units': + self.units, + 'activation': + activations.serialize(self.activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint), + 'dropout': + self.dropout, + 'recurrent_dropout': + self.recurrent_dropout + } + base_config = super(SimpleRNN, self).get_config() + config.update(_config_for_enable_caching_device(self.cell)) + del base_config['cell'] + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config): + if 'implementation' in config: + config.pop('implementation') + return cls(**config) + + +class GRUCell(DropoutRNNCellMixin, Layer): + """Cell class for the GRU layer. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass None, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + Default: hard sigmoid (`hard_sigmoid`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + reset_after: GRU convention (whether to apply reset gate after or + before matrix multiplication). False = "before" (default), + True = "after" (CuDNN compatible). + + Call arguments: + inputs: A 2D tensor. + states: List of state tensors corresponding to the previous timestep. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. Only relevant when `dropout` or + `recurrent_dropout` is used. + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + reset_after=False, + **kwargs): + if units < 0: + raise ValueError(f'Received an invalid value for units, expected ' + f'a positive integer, got {units}.') + # By default use cached variable under v2 mode, see b/143699808. + if ops.executing_eagerly_outside_functions(): + self._enable_caching_device = kwargs.pop('enable_caching_device', True) + else: + self._enable_caching_device = kwargs.pop('enable_caching_device', False) + super(GRUCell, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.recurrent_activation = activations.get(recurrent_activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + + implementation = kwargs.pop('implementation', 1) + if self.recurrent_dropout != 0 and implementation != 1: + logging.debug(RECURRENT_DROPOUT_WARNING_MSG) + self.implementation = 1 + else: + self.implementation = implementation + self.reset_after = reset_after + self.state_size = self.units + self.output_size = self.units + + @tf_utils.shape_type_conversion + def build(self, input_shape): + input_dim = input_shape[-1] + default_caching_device = _caching_device(self) + self.kernel = self.add_weight( + shape=(input_dim, self.units * 3), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + caching_device=default_caching_device) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units * 3), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint, + caching_device=default_caching_device) + + if self.use_bias: + if not self.reset_after: + bias_shape = (3 * self.units,) + else: + # separate biases for input and recurrent kernels + # Note: the shape is intentionally different from CuDNNGRU biases + # `(2 * 3 * self.units,)`, so that we can distinguish the classes + # when loading and converting saved weights. + bias_shape = (2, 3 * self.units) + self.bias = self.add_weight(shape=bias_shape, + name='bias', + initializer=self.bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + caching_device=default_caching_device) + else: + self.bias = None + self.built = True + + def call(self, inputs, states, training=None): + h_tm1 = states[0] if nest.is_nested(states) else states # previous memory + + dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=3) + rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( + h_tm1, training, count=3) + + if self.use_bias: + if not self.reset_after: + input_bias, recurrent_bias = self.bias, None + else: + input_bias, recurrent_bias = array_ops_stack.unstack(self.bias) + + if self.implementation == 1: + if 0. < self.dropout < 1.: + inputs_z = inputs * dp_mask[0] + inputs_r = inputs * dp_mask[1] + inputs_h = inputs * dp_mask[2] + else: + inputs_z = inputs + inputs_r = inputs + inputs_h = inputs + + x_z = backend.dot(inputs_z, self.kernel[:, :self.units]) + x_r = backend.dot(inputs_r, self.kernel[:, self.units:self.units * 2]) + x_h = backend.dot(inputs_h, self.kernel[:, self.units * 2:]) + + if self.use_bias: + x_z = backend.bias_add(x_z, input_bias[:self.units]) + x_r = backend.bias_add(x_r, input_bias[self.units: self.units * 2]) + x_h = backend.bias_add(x_h, input_bias[self.units * 2:]) + + if 0. < self.recurrent_dropout < 1.: + h_tm1_z = h_tm1 * rec_dp_mask[0] + h_tm1_r = h_tm1 * rec_dp_mask[1] + h_tm1_h = h_tm1 * rec_dp_mask[2] + else: + h_tm1_z = h_tm1 + h_tm1_r = h_tm1 + h_tm1_h = h_tm1 + + recurrent_z = backend.dot(h_tm1_z, self.recurrent_kernel[:, :self.units]) + recurrent_r = backend.dot( + h_tm1_r, self.recurrent_kernel[:, self.units:self.units * 2]) + if self.reset_after and self.use_bias: + recurrent_z = backend.bias_add(recurrent_z, recurrent_bias[:self.units]) + recurrent_r = backend.bias_add( + recurrent_r, recurrent_bias[self.units:self.units * 2]) + + z = self.recurrent_activation(x_z + recurrent_z) + r = self.recurrent_activation(x_r + recurrent_r) + + # reset gate applied after/before matrix multiplication + if self.reset_after: + recurrent_h = backend.dot( + h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) + if self.use_bias: + recurrent_h = backend.bias_add( + recurrent_h, recurrent_bias[self.units * 2:]) + recurrent_h = r * recurrent_h + else: + recurrent_h = backend.dot( + r * h_tm1_h, self.recurrent_kernel[:, self.units * 2:]) + + hh = self.activation(x_h + recurrent_h) + else: + if 0. < self.dropout < 1.: + inputs = inputs * dp_mask[0] + + # inputs projected by all gate matrices at once + matrix_x = backend.dot(inputs, self.kernel) + if self.use_bias: + # biases: bias_z_i, bias_r_i, bias_h_i + matrix_x = backend.bias_add(matrix_x, input_bias) + + x_z, x_r, x_h = array_ops.split(matrix_x, 3, axis=-1) + + if self.reset_after: + # hidden state projected by all gate matrices at once + matrix_inner = backend.dot(h_tm1, self.recurrent_kernel) + if self.use_bias: + matrix_inner = backend.bias_add(matrix_inner, recurrent_bias) + else: + # hidden state projected separately for update/reset and new + matrix_inner = backend.dot( + h_tm1, self.recurrent_kernel[:, :2 * self.units]) + + recurrent_z, recurrent_r, recurrent_h = array_ops.split( + matrix_inner, [self.units, self.units, -1], axis=-1) + + z = self.recurrent_activation(x_z + recurrent_z) + r = self.recurrent_activation(x_r + recurrent_r) + + if self.reset_after: + recurrent_h = r * recurrent_h + else: + recurrent_h = backend.dot( + r * h_tm1, self.recurrent_kernel[:, 2 * self.units:]) + + hh = self.activation(x_h + recurrent_h) + # previous and candidate state mixed by update gate + h = z * h_tm1 + (1 - z) * hh + new_state = [h] if nest.is_nested(states) else h + return h, new_state + + def get_config(self): + config = { + 'units': self.units, + 'activation': activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': self.use_bias, + 'kernel_initializer': initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': initializers.serialize(self.bias_initializer), + 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': regularizers.serialize(self.bias_regularizer), + 'kernel_constraint': constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': constraints.serialize(self.bias_constraint), + 'dropout': self.dropout, + 'recurrent_dropout': self.recurrent_dropout, + 'implementation': self.implementation, + 'reset_after': self.reset_after + } + config.update(_config_for_enable_caching_device(self)) + base_config = super(GRUCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype) + + +class GRU(RNN): + """Gated Recurrent Unit - Cho et al. 2014. + + There are two variants. The default one is based on 1406.1078v3 and + has reset gate applied to hidden state before matrix multiplication. The + other one is based on original 1406.1078v1 and has the order reversed. + + The second variant is compatible with CuDNNGRU (GPU-only) and allows + inference on CPU. Thus it has separate biases for `kernel` and + `recurrent_kernel`. Use `'reset_after'=True` and + `recurrent_activation='sigmoid'`. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + Default: hard sigmoid (`hard_sigmoid`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation").. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + return_sequences: Boolean. Whether to return the last output + in the output sequence, or the full sequence. + return_state: Boolean. Whether to return the last state + in addition to the output. + go_backwards: Boolean (default False). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + unroll: Boolean (default False). + If True, the network will be unrolled, + else a symbolic loop will be used. + Unrolling can speed-up a RNN, + although it tends to be more memory-intensive. + Unrolling is only suitable for short sequences. + time_major: The shape format of the `inputs` and `outputs` tensors. + If True, the inputs and outputs will be in shape + `(timesteps, batch, ...)`, whereas in the False case, it will be + `(batch, timesteps, ...)`. Using `time_major = True` is a bit more + efficient because it avoids transposes at the beginning and end of the + RNN calculation. However, most TensorFlow data is batch-major, so by + default this function accepts input and emits output in batch-major + form. + reset_after: GRU convention (whether to apply reset gate after or + before matrix multiplication). False = "before" (default), + True = "after" (CuDNN compatible). + + Call arguments: + inputs: A 3D tensor. + mask: Binary tensor of shape `(samples, timesteps)` indicating whether + a given timestep should be masked. An individual `True` entry indicates + that the corresponding timestep should be utilized, while a `False` + entry indicates that the corresponding timestep should be ignored. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is only relevant if `dropout` or + `recurrent_dropout` is used. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + reset_after=False, + **kwargs): + implementation = kwargs.pop('implementation', 1) + if implementation == 0: + logging.warning('`implementation=0` has been deprecated, ' + 'and now defaults to `implementation=1`.' + 'Please update your layer call.') + if 'enable_caching_device' in kwargs: + cell_kwargs = {'enable_caching_device': + kwargs.pop('enable_caching_device')} + else: + cell_kwargs = {} + cell = GRUCell( + units, + activation=activation, + recurrent_activation=recurrent_activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + recurrent_initializer=recurrent_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + recurrent_regularizer=recurrent_regularizer, + bias_regularizer=bias_regularizer, + kernel_constraint=kernel_constraint, + recurrent_constraint=recurrent_constraint, + bias_constraint=bias_constraint, + dropout=dropout, + recurrent_dropout=recurrent_dropout, + implementation=implementation, + reset_after=reset_after, + dtype=kwargs.get('dtype'), + trainable=kwargs.get('trainable', True), + **cell_kwargs) + super(GRU, self).__init__( + cell, + return_sequences=return_sequences, + return_state=return_state, + go_backwards=go_backwards, + stateful=stateful, + unroll=unroll, + **kwargs) + self.activity_regularizer = regularizers.get(activity_regularizer) + self.input_spec = [InputSpec(ndim=3)] + + def call(self, inputs, mask=None, training=None, initial_state=None): + return super(GRU, self).call( + inputs, mask=mask, training=training, initial_state=initial_state) + + @property + def units(self): + return self.cell.units + + @property + def activation(self): + return self.cell.activation + + @property + def recurrent_activation(self): + return self.cell.recurrent_activation + + @property + def use_bias(self): + return self.cell.use_bias + + @property + def kernel_initializer(self): + return self.cell.kernel_initializer + + @property + def recurrent_initializer(self): + return self.cell.recurrent_initializer + + @property + def bias_initializer(self): + return self.cell.bias_initializer + + @property + def kernel_regularizer(self): + return self.cell.kernel_regularizer + + @property + def recurrent_regularizer(self): + return self.cell.recurrent_regularizer + + @property + def bias_regularizer(self): + return self.cell.bias_regularizer + + @property + def kernel_constraint(self): + return self.cell.kernel_constraint + + @property + def recurrent_constraint(self): + return self.cell.recurrent_constraint + + @property + def bias_constraint(self): + return self.cell.bias_constraint + + @property + def dropout(self): + return self.cell.dropout + + @property + def recurrent_dropout(self): + return self.cell.recurrent_dropout + + @property + def implementation(self): + return self.cell.implementation + + @property + def reset_after(self): + return self.cell.reset_after + + def get_config(self): + config = { + 'units': + self.units, + 'activation': + activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint), + 'dropout': + self.dropout, + 'recurrent_dropout': + self.recurrent_dropout, + 'implementation': + self.implementation, + 'reset_after': + self.reset_after + } + config.update(_config_for_enable_caching_device(self.cell)) + base_config = super(GRU, self).get_config() + del base_config['cell'] + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config): + if 'implementation' in config and config['implementation'] == 0: + config['implementation'] = 1 + return cls(**config) + + +class LSTMCell(DropoutRNNCellMixin, Layer): + """Cell class for the LSTM layer. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + Default: hard sigmoid (`hard_sigmoid`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + unit_forget_bias: Boolean. + If True, add 1 to the bias of the forget gate at initialization. + Setting it to true will also force `bias_initializer="zeros"`. + This is recommended in [Jozefowicz et al., 2015]( + http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + + Call arguments: + inputs: A 2D tensor. + states: List of state tensors corresponding to the previous timestep. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. Only relevant when `dropout` or + `recurrent_dropout` is used. + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + if units < 0: + raise ValueError(f'Received an invalid value for units, expected ' + f'a positive integer, got {units}.') + # By default use cached variable under v2 mode, see b/143699808. + if ops.executing_eagerly_outside_functions(): + self._enable_caching_device = kwargs.pop('enable_caching_device', True) + else: + self._enable_caching_device = kwargs.pop('enable_caching_device', False) + super(LSTMCell, self).__init__(**kwargs) + self.units = units + self.activation = activations.get(activation) + self.recurrent_activation = activations.get(recurrent_activation) + self.use_bias = use_bias + + self.kernel_initializer = initializers.get(kernel_initializer) + self.recurrent_initializer = initializers.get(recurrent_initializer) + self.bias_initializer = initializers.get(bias_initializer) + self.unit_forget_bias = unit_forget_bias + + self.kernel_regularizer = regularizers.get(kernel_regularizer) + self.recurrent_regularizer = regularizers.get(recurrent_regularizer) + self.bias_regularizer = regularizers.get(bias_regularizer) + + self.kernel_constraint = constraints.get(kernel_constraint) + self.recurrent_constraint = constraints.get(recurrent_constraint) + self.bias_constraint = constraints.get(bias_constraint) + + self.dropout = min(1., max(0., dropout)) + self.recurrent_dropout = min(1., max(0., recurrent_dropout)) + implementation = kwargs.pop('implementation', 1) + if self.recurrent_dropout != 0 and implementation != 1: + logging.debug(RECURRENT_DROPOUT_WARNING_MSG) + self.implementation = 1 + else: + self.implementation = implementation + self.state_size = [self.units, self.units] + self.output_size = self.units + + @tf_utils.shape_type_conversion + def build(self, input_shape): + default_caching_device = _caching_device(self) + input_dim = input_shape[-1] + self.kernel = self.add_weight( + shape=(input_dim, self.units * 4), + name='kernel', + initializer=self.kernel_initializer, + regularizer=self.kernel_regularizer, + constraint=self.kernel_constraint, + caching_device=default_caching_device) + self.recurrent_kernel = self.add_weight( + shape=(self.units, self.units * 4), + name='recurrent_kernel', + initializer=self.recurrent_initializer, + regularizer=self.recurrent_regularizer, + constraint=self.recurrent_constraint, + caching_device=default_caching_device) + + if self.use_bias: + if self.unit_forget_bias: + + def bias_initializer(_, *args, **kwargs): + return backend.concatenate([ + self.bias_initializer((self.units,), *args, **kwargs), + initializers.get('ones')((self.units,), *args, **kwargs), + self.bias_initializer((self.units * 2,), *args, **kwargs), + ]) + else: + bias_initializer = self.bias_initializer + self.bias = self.add_weight( + shape=(self.units * 4,), + name='bias', + initializer=bias_initializer, + regularizer=self.bias_regularizer, + constraint=self.bias_constraint, + caching_device=default_caching_device) + else: + self.bias = None + self.built = True + + def _compute_carry_and_output(self, x, h_tm1, c_tm1): + """Computes carry and output using split kernels.""" + x_i, x_f, x_c, x_o = x + h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1 + i = self.recurrent_activation( + x_i + backend.dot(h_tm1_i, self.recurrent_kernel[:, :self.units])) + f = self.recurrent_activation(x_f + backend.dot( + h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2])) + c = f * c_tm1 + i * self.activation(x_c + backend.dot( + h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3])) + o = self.recurrent_activation( + x_o + backend.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:])) + return c, o + + def _compute_carry_and_output_fused(self, z, c_tm1): + """Computes carry and output using fused kernels.""" + z0, z1, z2, z3 = z + i = self.recurrent_activation(z0) + f = self.recurrent_activation(z1) + c = f * c_tm1 + i * self.activation(z2) + o = self.recurrent_activation(z3) + return c, o + + def call(self, inputs, states, training=None): + h_tm1 = states[0] # previous memory state + c_tm1 = states[1] # previous carry state + + dp_mask = self.get_dropout_mask_for_cell(inputs, training, count=4) + rec_dp_mask = self.get_recurrent_dropout_mask_for_cell( + h_tm1, training, count=4) + + if self.implementation == 1: + if 0 < self.dropout < 1.: + inputs_i = inputs * dp_mask[0] + inputs_f = inputs * dp_mask[1] + inputs_c = inputs * dp_mask[2] + inputs_o = inputs * dp_mask[3] + else: + inputs_i = inputs + inputs_f = inputs + inputs_c = inputs + inputs_o = inputs + k_i, k_f, k_c, k_o = array_ops.split( + self.kernel, num_or_size_splits=4, axis=1) + x_i = backend.dot(inputs_i, k_i) + x_f = backend.dot(inputs_f, k_f) + x_c = backend.dot(inputs_c, k_c) + x_o = backend.dot(inputs_o, k_o) + if self.use_bias: + b_i, b_f, b_c, b_o = array_ops.split( + self.bias, num_or_size_splits=4, axis=0) + x_i = backend.bias_add(x_i, b_i) + x_f = backend.bias_add(x_f, b_f) + x_c = backend.bias_add(x_c, b_c) + x_o = backend.bias_add(x_o, b_o) + + if 0 < self.recurrent_dropout < 1.: + h_tm1_i = h_tm1 * rec_dp_mask[0] + h_tm1_f = h_tm1 * rec_dp_mask[1] + h_tm1_c = h_tm1 * rec_dp_mask[2] + h_tm1_o = h_tm1 * rec_dp_mask[3] + else: + h_tm1_i = h_tm1 + h_tm1_f = h_tm1 + h_tm1_c = h_tm1 + h_tm1_o = h_tm1 + x = (x_i, x_f, x_c, x_o) + h_tm1 = (h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o) + c, o = self._compute_carry_and_output(x, h_tm1, c_tm1) + else: + if 0. < self.dropout < 1.: + inputs = inputs * dp_mask[0] + z = backend.dot(inputs, self.kernel) + z += backend.dot(h_tm1, self.recurrent_kernel) + if self.use_bias: + z = backend.bias_add(z, self.bias) + + z = array_ops.split(z, num_or_size_splits=4, axis=1) + c, o = self._compute_carry_and_output_fused(z, c_tm1) + + h = o * self.activation(c) + return h, [h, c] + + def get_config(self): + config = { + 'units': + self.units, + 'activation': + activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'unit_forget_bias': + self.unit_forget_bias, + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint), + 'dropout': + self.dropout, + 'recurrent_dropout': + self.recurrent_dropout, + 'implementation': + self.implementation + } + config.update(_config_for_enable_caching_device(self)) + base_config = super(LSTMCell, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + def get_initial_state(self, inputs=None, batch_size=None, dtype=None): + return list(_generate_zero_filled_state_for_cell( + self, inputs, batch_size, dtype)) + + +class PeepholeLSTMCell(LSTMCell): + """Equivalent to LSTMCell class but adds peephole connections. + + Peephole connections allow the gates to utilize the previous internal state as + well as the previous hidden state (which is what LSTMCell is limited to). + This allows PeepholeLSTMCell to better learn precise timings over LSTMCell. + + From [Gers et al., 2002]( + http://www.jmlr.org/papers/volume3/gers02a/gers02a.pdf): + + "We find that LSTM augmented by 'peephole connections' from its internal + cells to its multiplicative gates can learn the fine distinction between + sequences of spikes spaced either 50 or 49 time steps apart without the help + of any short training exemplars." + + The peephole implementation is based on: + + [Sak et al., 2014](https://research.google.com/pubs/archive/43905.pdf) + + Example: + + ```python + # Create 2 PeepholeLSTMCells + peephole_lstm_cells = [PeepholeLSTMCell(size) for size in [128, 256]] + # Create a layer composed sequentially of the peephole LSTM cells. + layer = RNN(peephole_lstm_cells) + input = keras.Input((timesteps, input_dim)) + output = layer(input) + ``` + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + **kwargs): + warnings.warn('`tf.keras.experimental.PeepholeLSTMCell` is deprecated ' + 'and will be removed in a future version. ' + 'Please use tensorflow_addons.rnn.PeepholeLSTMCell ' + 'instead.') + super(PeepholeLSTMCell, self).__init__( + units=units, + activation=activation, + recurrent_activation=recurrent_activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + recurrent_initializer=recurrent_initializer, + bias_initializer=bias_initializer, + unit_forget_bias=unit_forget_bias, + kernel_regularizer=kernel_regularizer, + recurrent_regularizer=recurrent_regularizer, + bias_regularizer=bias_regularizer, + kernel_constraint=kernel_constraint, + recurrent_constraint=recurrent_constraint, + bias_constraint=bias_constraint, + dropout=dropout, + recurrent_dropout=recurrent_dropout, + implementation=kwargs.pop('implementation', 1), + **kwargs) + + def build(self, input_shape): + super(PeepholeLSTMCell, self).build(input_shape) + # The following are the weight matrices for the peephole connections. These + # are multiplied with the previous internal state during the computation of + # carry and output. + self.input_gate_peephole_weights = self.add_weight( + shape=(self.units,), + name='input_gate_peephole_weights', + initializer=self.kernel_initializer) + self.forget_gate_peephole_weights = self.add_weight( + shape=(self.units,), + name='forget_gate_peephole_weights', + initializer=self.kernel_initializer) + self.output_gate_peephole_weights = self.add_weight( + shape=(self.units,), + name='output_gate_peephole_weights', + initializer=self.kernel_initializer) + + def _compute_carry_and_output(self, x, h_tm1, c_tm1): + x_i, x_f, x_c, x_o = x + h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1 + i = self.recurrent_activation( + x_i + backend.dot(h_tm1_i, self.recurrent_kernel[:, :self.units]) + + self.input_gate_peephole_weights * c_tm1) + f = self.recurrent_activation(x_f + backend.dot( + h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2]) + + self.forget_gate_peephole_weights * c_tm1) + c = f * c_tm1 + i * self.activation(x_c + backend.dot( + h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3])) + o = self.recurrent_activation( + x_o + backend.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:]) + + self.output_gate_peephole_weights * c) + return c, o + + def _compute_carry_and_output_fused(self, z, c_tm1): + z0, z1, z2, z3 = z + i = self.recurrent_activation(z0 + + self.input_gate_peephole_weights * c_tm1) + f = self.recurrent_activation(z1 + + self.forget_gate_peephole_weights * c_tm1) + c = f * c_tm1 + i * self.activation(z2) + o = self.recurrent_activation(z3 + self.output_gate_peephole_weights * c) + return c, o + + +class LSTM(RNN): + """Long Short-Term Memory layer - Hochreiter 1997. + + Note that this cell is not optimized for performance on GPU. Please use + `tf.compat.v1.keras.layers.CuDNNLSTM` for better performance on GPU. + + Args: + units: Positive integer, dimensionality of the output space. + activation: Activation function to use. + Default: hyperbolic tangent (`tanh`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + recurrent_activation: Activation function to use + for the recurrent step. + Default: hard sigmoid (`hard_sigmoid`). + If you pass `None`, no activation is applied + (ie. "linear" activation: `a(x) = x`). + use_bias: Boolean, whether the layer uses a bias vector. + kernel_initializer: Initializer for the `kernel` weights matrix, + used for the linear transformation of the inputs.. + recurrent_initializer: Initializer for the `recurrent_kernel` + weights matrix, + used for the linear transformation of the recurrent state. + bias_initializer: Initializer for the bias vector. + unit_forget_bias: Boolean. + If True, add 1 to the bias of the forget gate at initialization. + Setting it to true will also force `bias_initializer="zeros"`. + This is recommended in [Jozefowicz et al., 2015]( + http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf). + kernel_regularizer: Regularizer function applied to + the `kernel` weights matrix. + recurrent_regularizer: Regularizer function applied to + the `recurrent_kernel` weights matrix. + bias_regularizer: Regularizer function applied to the bias vector. + activity_regularizer: Regularizer function applied to + the output of the layer (its "activation"). + kernel_constraint: Constraint function applied to + the `kernel` weights matrix. + recurrent_constraint: Constraint function applied to + the `recurrent_kernel` weights matrix. + bias_constraint: Constraint function applied to the bias vector. + dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the inputs. + recurrent_dropout: Float between 0 and 1. + Fraction of the units to drop for + the linear transformation of the recurrent state. + return_sequences: Boolean. Whether to return the last output. + in the output sequence, or the full sequence. + return_state: Boolean. Whether to return the last state + in addition to the output. + go_backwards: Boolean (default False). + If True, process the input sequence backwards and return the + reversed sequence. + stateful: Boolean (default False). If True, the last state + for each sample at index i in a batch will be used as initial + state for the sample of index i in the following batch. + unroll: Boolean (default False). + If True, the network will be unrolled, + else a symbolic loop will be used. + Unrolling can speed-up a RNN, + although it tends to be more memory-intensive. + Unrolling is only suitable for short sequences. + time_major: The shape format of the `inputs` and `outputs` tensors. + If True, the inputs and outputs will be in shape + `(timesteps, batch, ...)`, whereas in the False case, it will be + `(batch, timesteps, ...)`. Using `time_major = True` is a bit more + efficient because it avoids transposes at the beginning and end of the + RNN calculation. However, most TensorFlow data is batch-major, so by + default this function accepts input and emits output in batch-major + form. + + Call arguments: + inputs: A 3D tensor. + mask: Binary tensor of shape `(samples, timesteps)` indicating whether + a given timestep should be masked. An individual `True` entry indicates + that the corresponding timestep should be utilized, while a `False` + entry indicates that the corresponding timestep should be ignored. + training: Python boolean indicating whether the layer should behave in + training mode or in inference mode. This argument is passed to the cell + when calling it. This is only relevant if `dropout` or + `recurrent_dropout` is used. + initial_state: List of initial state tensors to be passed to the first + call of the cell. + """ + + def __init__(self, + units, + activation='tanh', + recurrent_activation='hard_sigmoid', + use_bias=True, + kernel_initializer='glorot_uniform', + recurrent_initializer='orthogonal', + bias_initializer='zeros', + unit_forget_bias=True, + kernel_regularizer=None, + recurrent_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + recurrent_constraint=None, + bias_constraint=None, + dropout=0., + recurrent_dropout=0., + return_sequences=False, + return_state=False, + go_backwards=False, + stateful=False, + unroll=False, + **kwargs): + implementation = kwargs.pop('implementation', 1) + if implementation == 0: + logging.warning('`implementation=0` has been deprecated, ' + 'and now defaults to `implementation=1`.' + 'Please update your layer call.') + if 'enable_caching_device' in kwargs: + cell_kwargs = {'enable_caching_device': + kwargs.pop('enable_caching_device')} + else: + cell_kwargs = {} + cell = LSTMCell( + units, + activation=activation, + recurrent_activation=recurrent_activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + recurrent_initializer=recurrent_initializer, + unit_forget_bias=unit_forget_bias, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + recurrent_regularizer=recurrent_regularizer, + bias_regularizer=bias_regularizer, + kernel_constraint=kernel_constraint, + recurrent_constraint=recurrent_constraint, + bias_constraint=bias_constraint, + dropout=dropout, + recurrent_dropout=recurrent_dropout, + implementation=implementation, + dtype=kwargs.get('dtype'), + trainable=kwargs.get('trainable', True), + **cell_kwargs) + super(LSTM, self).__init__( + cell, + return_sequences=return_sequences, + return_state=return_state, + go_backwards=go_backwards, + stateful=stateful, + unroll=unroll, + **kwargs) + self.activity_regularizer = regularizers.get(activity_regularizer) + self.input_spec = [InputSpec(ndim=3)] + + def call(self, inputs, mask=None, training=None, initial_state=None): + return super(LSTM, self).call( + inputs, mask=mask, training=training, initial_state=initial_state) + + @property + def units(self): + return self.cell.units + + @property + def activation(self): + return self.cell.activation + + @property + def recurrent_activation(self): + return self.cell.recurrent_activation + + @property + def use_bias(self): + return self.cell.use_bias + + @property + def kernel_initializer(self): + return self.cell.kernel_initializer + + @property + def recurrent_initializer(self): + return self.cell.recurrent_initializer + + @property + def bias_initializer(self): + return self.cell.bias_initializer + + @property + def unit_forget_bias(self): + return self.cell.unit_forget_bias + + @property + def kernel_regularizer(self): + return self.cell.kernel_regularizer + + @property + def recurrent_regularizer(self): + return self.cell.recurrent_regularizer + + @property + def bias_regularizer(self): + return self.cell.bias_regularizer + + @property + def kernel_constraint(self): + return self.cell.kernel_constraint + + @property + def recurrent_constraint(self): + return self.cell.recurrent_constraint + + @property + def bias_constraint(self): + return self.cell.bias_constraint + + @property + def dropout(self): + return self.cell.dropout + + @property + def recurrent_dropout(self): + return self.cell.recurrent_dropout + + @property + def implementation(self): + return self.cell.implementation + + def get_config(self): + config = { + 'units': + self.units, + 'activation': + activations.serialize(self.activation), + 'recurrent_activation': + activations.serialize(self.recurrent_activation), + 'use_bias': + self.use_bias, + 'kernel_initializer': + initializers.serialize(self.kernel_initializer), + 'recurrent_initializer': + initializers.serialize(self.recurrent_initializer), + 'bias_initializer': + initializers.serialize(self.bias_initializer), + 'unit_forget_bias': + self.unit_forget_bias, + 'kernel_regularizer': + regularizers.serialize(self.kernel_regularizer), + 'recurrent_regularizer': + regularizers.serialize(self.recurrent_regularizer), + 'bias_regularizer': + regularizers.serialize(self.bias_regularizer), + 'activity_regularizer': + regularizers.serialize(self.activity_regularizer), + 'kernel_constraint': + constraints.serialize(self.kernel_constraint), + 'recurrent_constraint': + constraints.serialize(self.recurrent_constraint), + 'bias_constraint': + constraints.serialize(self.bias_constraint), + 'dropout': + self.dropout, + 'recurrent_dropout': + self.recurrent_dropout, + 'implementation': + self.implementation + } + config.update(_config_for_enable_caching_device(self.cell)) + base_config = super(LSTM, self).get_config() + del base_config['cell'] + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config): + if 'implementation' in config and config['implementation'] == 0: + config['implementation'] = 1 + return cls(**config) + + +def _generate_dropout_mask(ones, rate, training=None, count=1): + def dropped_inputs(): + return backend.dropout(ones, rate) + + if count > 1: + return [ + backend.in_train_phase(dropped_inputs, ones, training=training) + for _ in range(count) + ] + return backend.in_train_phase(dropped_inputs, ones, training=training) + + +def _standardize_args(inputs, initial_state, constants, num_constants): + """Standardizes `__call__` to a single list of tensor inputs. + + When running a model loaded from a file, the input tensors + `initial_state` and `constants` can be passed to `RNN.__call__()` as part + of `inputs` instead of by the dedicated keyword arguments. This method + makes sure the arguments are separated and that `initial_state` and + `constants` are lists of tensors (or None). + + Args: + inputs: Tensor or list/tuple of tensors. which may include constants + and initial states. In that case `num_constant` must be specified. + initial_state: Tensor or list of tensors or None, initial states. + constants: Tensor or list of tensors or None, constant tensors. + num_constants: Expected number of constants (if constants are passed as + part of the `inputs` list. + + Returns: + inputs: Single tensor or tuple of tensors. + initial_state: List of tensors or None. + constants: List of tensors or None. + """ + if isinstance(inputs, list): + # There are several situations here: + # In the graph mode, __call__ will be only called once. The initial_state + # and constants could be in inputs (from file loading). + # In the eager mode, __call__ will be called twice, once during + # rnn_layer(inputs=input_t, constants=c_t, ...), and second time will be + # model.fit/train_on_batch/predict with real np data. In the second case, + # the inputs will contain initial_state and constants as eager tensor. + # + # For either case, the real input is the first item in the list, which + # could be a nested structure itself. Then followed by initial_states, which + # could be a list of items, or list of list if the initial_state is complex + # structure, and finally followed by constants which is a flat list. + assert initial_state is None and constants is None + if num_constants: + constants = inputs[-num_constants:] + inputs = inputs[:-num_constants] + if len(inputs) > 1: + initial_state = inputs[1:] + inputs = inputs[:1] + + if len(inputs) > 1: + inputs = tuple(inputs) + else: + inputs = inputs[0] + + def to_list_or_none(x): + if x is None or isinstance(x, list): + return x + if isinstance(x, tuple): + return list(x) + return [x] + + initial_state = to_list_or_none(initial_state) + constants = to_list_or_none(constants) + + return inputs, initial_state, constants + + +def _is_multiple_state(state_size): + """Check whether the state_size contains multiple states.""" + return (hasattr(state_size, '__len__') and + not isinstance(state_size, tensor_shape.TensorShape)) + + +def _generate_zero_filled_state_for_cell(cell, inputs, batch_size, dtype): + if inputs is not None: + batch_size = array_ops.shape(inputs)[0] + dtype = inputs.dtype + return _generate_zero_filled_state(batch_size, cell.state_size, dtype) + + +def _generate_zero_filled_state(batch_size_tensor, state_size, dtype): + """Generate a zero filled tensor with shape [batch_size, state_size].""" + if batch_size_tensor is None or dtype is None: + raise ValueError( + 'batch_size and dtype cannot be None while constructing initial state: ' + 'batch_size={}, dtype={}'.format(batch_size_tensor, dtype)) + + def create_zeros(unnested_state_size): + flat_dims = tensor_shape.TensorShape(unnested_state_size).as_list() + init_state_size = [batch_size_tensor] + flat_dims + return array_ops.zeros(init_state_size, dtype=dtype) + + if nest.is_nested(state_size): + return nest.map_structure(create_zeros, state_size) + else: + return create_zeros(state_size) + + +def _caching_device(rnn_cell): + """Returns the caching device for the RNN variable. + + This is useful for distributed training, when variable is not located as same + device as the training worker. By enabling the device cache, this allows + worker to read the variable once and cache locally, rather than read it every + time step from remote when it is needed. + + Note that this is assuming the variable that cell needs for each time step is + having the same value in the forward path, and only gets updated in the + backprop. It is true for all the default cells (SimpleRNN, GRU, LSTM). If the + cell body relies on any variable that gets updated every time step, then + caching device will cause it to read the stall value. + + Args: + rnn_cell: the rnn cell instance. + """ + if context.executing_eagerly(): + # caching_device is not supported in eager mode. + return None + if not getattr(rnn_cell, '_enable_caching_device', False): + return None + # Don't set a caching device when running in a loop, since it is possible that + # train steps could be wrapped in a tf.while_loop. In that scenario caching + # prevents forward computations in loop iterations from re-reading the + # updated weights. + if control_flow_util.IsInWhileLoop(ops.get_default_graph()): + logging.warning( + 'Variable read device caching has been disabled because the ' + 'RNN is in tf.while_loop loop context, which will cause ' + 'reading stalled value in forward path. This could slow down ' + 'the training due to duplicated variable reads. Please ' + 'consider updating your code to remove tf.while_loop if possible.') + return None + if (rnn_cell._dtype_policy.compute_dtype != + rnn_cell._dtype_policy.variable_dtype): + logging.warning( + 'Variable read device caching has been disabled since it ' + 'doesn\'t work with the mixed precision API. This is ' + 'likely to cause a slowdown for RNN training due to ' + 'duplicated read of variable for each timestep, which ' + 'will be significant in a multi remote worker setting. ' + 'Please consider disabling mixed precision API if ' + 'the performance has been affected.') + return None + # Cache the value on the device that access the variable. + return lambda op: op.device + + +def _config_for_enable_caching_device(rnn_cell): + """Return the dict config for RNN cell wrt to enable_caching_device field. + + Since enable_caching_device is a internal implementation detail for speed up + the RNN variable read when running on the multi remote worker setting, we + don't want this config to be serialized constantly in the JSON. We will only + serialize this field when a none default value is used to create the cell. + Args: + rnn_cell: the RNN cell for serialize. + + Returns: + A dict which contains the JSON config for enable_caching_device value or + empty dict if the enable_caching_device value is same as the default value. + """ + default_enable_caching_device = ops.executing_eagerly_outside_functions() + if rnn_cell._enable_caching_device != default_enable_caching_device: + return {'enable_caching_device': rnn_cell._enable_caching_device} + return {} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..44720fb0fa59b3a1688668fff74a553453e0b0b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py @@ -0,0 +1,131 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module implementing for RNN wrappers for TF v2.""" + +# Note that all the APIs under this module are exported as tf.nn.*. This is due +# to the fact that those APIs were from tf.nn.rnn_cell_impl. They are ported +# here to avoid the cyclic dependency issue for serialization. These APIs will +# probably be deprecated and removed in future since similar API is available in +# existing Keras RNN API. + + +from tensorflow.python.keras.layers import recurrent +from tensorflow.python.keras.layers.legacy_rnn import rnn_cell_wrapper_impl +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +class _RNNCellWrapperV2(recurrent.AbstractRNNCell): + """Base class for cells wrappers V2 compatibility. + + This class along with `rnn_cell_impl._RNNCellWrapperV1` allows to define + wrappers that are compatible with V1 and V2, and defines helper methods for + this purpose. + """ + + def __init__(self, cell, *args, **kwargs): + super(_RNNCellWrapperV2, self).__init__(*args, **kwargs) + self.cell = cell + cell_call_spec = tf_inspect.getfullargspec(cell.call) + self._expects_training_arg = ("training" in cell_call_spec.args) or ( + cell_call_spec.varkw is not None + ) + + def call(self, inputs, state, **kwargs): + """Runs the RNN cell step computation. + + When `call` is being used, we assume that the wrapper object has been built, + and therefore the wrapped cells has been built via its `build` method and + its `call` method can be used directly. + + This allows to use the wrapped cell and the non-wrapped cell equivalently + when using `call` and `build`. + + Args: + inputs: A tensor with wrapped cell's input. + state: A tensor or tuple of tensors with wrapped cell's state. + **kwargs: Additional arguments passed to the wrapped cell's `call`. + + Returns: + A pair containing: + + - Output: A tensor with cell's output. + - New state: A tensor or tuple of tensors with new wrapped cell's state. + """ + return self._call_wrapped_cell( + inputs, state, cell_call_fn=self.cell.call, **kwargs) + + def build(self, inputs_shape): + """Builds the wrapped cell.""" + self.cell.build(inputs_shape) + self.built = True + + def get_config(self): + config = { + "cell": { + "class_name": self.cell.__class__.__name__, + "config": self.cell.get_config() + }, + } + base_config = super(_RNNCellWrapperV2, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() + from tensorflow.python.keras.layers.serialization import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top + cell = deserialize_layer(config.pop("cell"), custom_objects=custom_objects) + return cls(cell, **config) + + +@deprecated(None, "Please use tf.keras.layers.RNN instead.") +@tf_export("nn.RNNCellDropoutWrapper", v1=[]) +class DropoutWrapper(rnn_cell_wrapper_impl.DropoutWrapperBase, + _RNNCellWrapperV2): + """Operator adding dropout to inputs and outputs of the given cell.""" + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(DropoutWrapper, self).__init__(*args, **kwargs) + if isinstance(self.cell, recurrent.LSTMCell): + raise ValueError("keras LSTM cell does not work with DropoutWrapper. " + "Please use LSTMCell(dropout=x, recurrent_dropout=y) " + "instead.") + + __init__.__doc__ = rnn_cell_wrapper_impl.DropoutWrapperBase.__init__.__doc__ + + +@deprecated(None, "Please use tf.keras.layers.RNN instead.") +@tf_export("nn.RNNCellResidualWrapper", v1=[]) +class ResidualWrapper(rnn_cell_wrapper_impl.ResidualWrapperBase, + _RNNCellWrapperV2): + """RNNCell wrapper that ensures cell inputs are added to the outputs.""" + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(ResidualWrapper, self).__init__(*args, **kwargs) + + __init__.__doc__ = rnn_cell_wrapper_impl.ResidualWrapperBase.__init__.__doc__ + + +@deprecated(None, "Please use tf.keras.layers.RNN instead.") +@tf_export("nn.RNNCellDeviceWrapper", v1=[]) +class DeviceWrapper(rnn_cell_wrapper_impl.DeviceWrapperBase, + _RNNCellWrapperV2): + """Operator that ensures an RNNCell runs on a particular device.""" + + def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation + super(DeviceWrapper, self).__init__(*args, **kwargs) + + __init__.__doc__ = rnn_cell_wrapper_impl.DeviceWrapperBase.__init__.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..65238330f93b297e6d1105fc9eeeefff624cab04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/layers/serialization.py @@ -0,0 +1,117 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Layer serialization/deserialization functions. +""" +# pylint: disable=wildcard-import +# pylint: disable=unused-import + +import threading + +from tensorflow.python import tf2 +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import input_layer +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.layers import advanced_activations +from tensorflow.python.keras.layers import convolutional +from tensorflow.python.keras.layers import convolutional_recurrent +from tensorflow.python.keras.layers import core +from tensorflow.python.keras.layers import dense_attention +from tensorflow.python.keras.layers import embeddings +from tensorflow.python.keras.layers import merge +from tensorflow.python.keras.layers import pooling +from tensorflow.python.keras.layers import recurrent +from tensorflow.python.keras.layers import rnn_cell_wrapper_v2 +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_inspect as inspect + +ALL_MODULES = (base_layer, input_layer, advanced_activations, convolutional, + convolutional_recurrent, core, dense_attention, + embeddings, merge, pooling, recurrent) +ALL_V2_MODULES = (rnn_cell_wrapper_v2,) +# ALL_OBJECTS is meant to be a global mutable. Hence we need to make it +# thread-local to avoid concurrent mutations. +LOCAL = threading.local() + + +def populate_deserializable_objects(): + """Populates dict ALL_OBJECTS with every built-in layer. + """ + global LOCAL + if not hasattr(LOCAL, 'ALL_OBJECTS'): + LOCAL.ALL_OBJECTS = {} + LOCAL.GENERATED_WITH_V2 = None + + if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf2.enabled(): + # Objects dict is already generated for the proper TF version: + # do nothing. + return + + LOCAL.ALL_OBJECTS = {} + LOCAL.GENERATED_WITH_V2 = tf2.enabled() + + base_cls = base_layer.Layer + generic_utils.populate_dict_with_module_objects( + LOCAL.ALL_OBJECTS, + ALL_MODULES, + obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls)) + + # Overwrite certain V1 objects with V2 versions + if tf2.enabled(): + generic_utils.populate_dict_with_module_objects( + LOCAL.ALL_OBJECTS, + ALL_V2_MODULES, + obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls)) + + # Prevent circular dependencies. + from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top + + LOCAL.ALL_OBJECTS['Input'] = input_layer.Input + LOCAL.ALL_OBJECTS['InputSpec'] = input_spec.InputSpec + LOCAL.ALL_OBJECTS['Functional'] = models.Functional + LOCAL.ALL_OBJECTS['Model'] = models.Model + LOCAL.ALL_OBJECTS['Sequential'] = models.Sequential + + # Merge layers, function versions. + LOCAL.ALL_OBJECTS['add'] = merge.add + LOCAL.ALL_OBJECTS['subtract'] = merge.subtract + LOCAL.ALL_OBJECTS['multiply'] = merge.multiply + LOCAL.ALL_OBJECTS['average'] = merge.average + LOCAL.ALL_OBJECTS['maximum'] = merge.maximum + LOCAL.ALL_OBJECTS['minimum'] = merge.minimum + LOCAL.ALL_OBJECTS['concatenate'] = merge.concatenate + LOCAL.ALL_OBJECTS['dot'] = merge.dot + + +def serialize(layer): + return generic_utils.serialize_keras_object(layer) + + +def deserialize(config, custom_objects=None): + """Instantiates a layer from a config dictionary. + + Args: + config: dict of the form {'class_name': str, 'config': dict} + custom_objects: dict mapping class names (or function names) + of custom (non-Keras) objects to class/functions + + Returns: + Layer instance (may be Model, Sequential, Network, Layer...) + """ + populate_deserializable_objects() + return generic_utils.deserialize_keras_object( + config, + module_objects=LOCAL.ALL_OBJECTS, + custom_objects=custom_objects, + printable_module_name='layer') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0225fbfa47a70888e32e2850b58c3689d9d6fd7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/base.py @@ -0,0 +1,604 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +# pylint: disable=g-classes-have-attributes +"""Contains the base Layer class, from which all layers inherit.""" +import copy +import warnings + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.legacy_tf_layers import variable_scope_shim +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest + +# Avoid breaking users who directly import this symbol from this file. +# TODO(fchollet): remove this. +InputSpec = base_layer.InputSpec # pylint: disable=invalid-name + +_KERAS_STYLE_SCOPE = False + + +@tf_contextlib.contextmanager +def keras_style_scope(): + """Use Keras-style variable management. + + All tf.layers and tf RNN cells created in this scope use Keras-style + variable management. Creating such layers with a scope= argument is + disallowed, and reuse=True is disallowed. + + The purpose of this scope is to allow users of existing layers to + slowly transition to a Keras layers API without breaking existing + functionality. + + One example of this is when using TensorFlow's RNN classes with Keras + Models or Networks. Because Keras models do not properly set variable + scopes, users of RNNs may either accidentally share scopes between two + different models, or get errors about variables that already exist. + + Example: + + ```python + class RNNModel(tf.keras.Model): + + def __init__(self, name): + super(RNNModel, self).__init__(name=name) + self.rnn = tf.compat.v1.nn.rnn_cell.MultiRNNCell( + [tf.compat.v1.nn.rnn_cell.LSTMCell(64) for _ in range(2)]) + + def call(self, input, state): + return self.rnn(input, state) + + model_1 = RNNModel("model_1") + model_2 = RNNModel("model_2") + + # OK + output_1, next_state_1 = model_1(input, state) + # Raises an error about trying to create an already existing variable. + output_2, next_state_2 = model_2(input, state) + ``` + + The solution is to wrap the model construction and execution in a keras-style + scope: + + ```python + with keras_style_scope(): + model_1 = RNNModel("model_1") + model_2 = RNNModel("model_2") + + # model_1 and model_2 are guaranteed to create their own variables. + output_1, next_state_1 = model_1(input, state) + output_2, next_state_2 = model_2(input, state) + + assert len(model_1.weights) > 0 + assert len(model_2.weights) > 0 + assert(model_1.weights != model_2.weights) + ``` + + Yields: + A keras layer style scope. + """ + global _KERAS_STYLE_SCOPE + stack = _KERAS_STYLE_SCOPE + _KERAS_STYLE_SCOPE = True + try: + yield + finally: + _KERAS_STYLE_SCOPE = stack + + +def set_keras_style(): + """Use Keras-style variable management. + + All tf.layers and tf RNN cells created after keras style ha been enabled + use Keras-style variable management. Creating such layers with a + scope= argument is disallowed, and reuse=True is disallowed. + + The purpose of this function is to allow users of existing layers to + slowly transition to Keras layers API without breaking existing + functionality. + + For more details, see the documentation for `keras_style_scope`. + + Note, once keras style has been set, it is set globally for the entire + program and cannot be unset. + + Example: + + ```python + set_keras_style() + + model_1 = RNNModel(name="model_1") + model_2 = RNNModel(name="model_2") + + # model_1 and model_2 are guaranteed to create their own variables. + output_1, next_state_1 = model_1(input, state) + output_2, next_state_2 = model_2(input, state) + + assert len(model_1.weights) > 0 + assert len(model_2.weights) > 0 + assert(model_1.weights != model_2.weights) + ``` + """ + global _KERAS_STYLE_SCOPE + _KERAS_STYLE_SCOPE = True + + +def _is_in_keras_style_scope(): + global _KERAS_STYLE_SCOPE + return _KERAS_STYLE_SCOPE + + +class Layer(base_layer.Layer): + """Base layer class. + + It is considered legacy, and we recommend the use of `tf.keras.layers.Layer` + instead. + + Args: + trainable: Boolean, whether the layer's variables should be trainable. + name: String name of the layer. + dtype: Default dtype of the layer's weights (default of `None` means use the + type of the first input). + + Read-only properties: + name: The name of the layer (string). + dtype: Default dtype of the layer's weights (default of `None` means use the + type of the first input). + trainable_variables: List of trainable variables. + non_trainable_variables: List of non-trainable variables. + variables: List of all variables of this layer, trainable and + non-trainable. + updates: List of update ops of this layer. + losses: List of losses added by this layer. + trainable_weights: List of variables to be included in backprop. + non_trainable_weights: List of variables that should not be + included in backprop. + weights: The concatenation of the lists trainable_weights and + non_trainable_weights (in this order). + + Mutable properties: + trainable: Whether the layer should be trained (boolean). + input_spec: Optional (list of) `InputSpec` object(s) specifying the + constraints on inputs that can be accepted by the layer. + """ + + def __init__(self, trainable=True, name=None, dtype=None, + **kwargs): + # For backwards compatibility, legacy layers do not use `ResourceVariable` + # by default. + self._use_resource_variables = False + scope = kwargs.pop('_scope', None) + self._reuse = kwargs.pop('_reuse', None) + + # Avoid an incorrect lint error + self._trainable_weights = [] + self.built = False + + if dtype is None: + # Indicates to infer dtype from inputs. When the V2 dtype behavior is + # enabled, Keras layers default their dtype to floatx instead, so we pass + # an "_infer" policy to keep the old V1 behavior. + dtype = policy.Policy('_infer') + + if 'autocast' not in kwargs: + kwargs['autocast'] = False + + # Mark that legacy layers should not be instrumented as Keras usage + self._disable_keras_instrumentation = True + + super(Layer, self).__init__(trainable=trainable, name=name, dtype=dtype, + **kwargs) + + if _is_in_keras_style_scope(): + if scope is not None: + raise ValueError( + 'scope argument not allowed when keras style layers are enabled, ' + 'but saw: {}'.format(scope)) + if self._reuse is not None: + raise ValueError( + 'reuse argument not allowed when keras style layers are enabled, ' + 'but saw: {}'.format(self._reuse)) + self._keras_style = True + else: + self._keras_style = False + + self._call_has_scope_arg = 'scope' in self._call_fn_args + if scope: + with vs.variable_scope(scope) as captured_scope: + self._scope = captured_scope + else: + self._scope = None + self._current_scope = None + + # We no longer track graph in tf.layers layers. This property is only kept to + # maintain API backward compatibility. + @property + def graph(self): + warnings.warn('`Layer.graph` is deprecated and ' + 'will be removed in a future version. ' + 'Please stop using this property because tf.layers layers no ' + 'longer track their graph.') + if context.executing_eagerly(): + raise RuntimeError('Layer.graph not supported when executing eagerly.') + return None + + def _init_set_name(self, name): + # Determine layer name (non-unique). + if isinstance(name, vs.VariableScope): + base_name = name.name + self._name, _ = self._make_unique_name() + else: + base_name = name + self._name = name + if not name: + self._name, base_name = self._make_unique_name() + self._base_name = base_name + + def _make_unique_name(self, name_uid_map=None, avoid_names=None, + namespace='', zero_based=False): + base_name = base_layer.to_snake_case(self.__class__.__name__) + name = backend.unique_object_name( + base_name, + name_uid_map=name_uid_map, + avoid_names=avoid_names, + namespace=namespace, + zero_based=zero_based) + return (name, base_name) + + @property + def scope_name(self): + if not self._scope: + raise ValueError('No name available for layer scope because the layer "' + + self._name + '" has not been used yet. The scope name ' + + ' is determined the first time the layer instance is ' + + 'called. You must therefore call the layer before ' + + 'querying `scope_name`.') + return self._scope.name + + def add_loss(self, losses, inputs=None): + previous_losses_length = len(self._losses) + previous_callable_losses_length = len(self._callable_losses) + super(Layer, self).add_loss(losses, inputs=inputs) + if not context.executing_eagerly(): + # TODO(fchollet): deprecate collection below. + new_losses = self._losses[previous_losses_length:] + new_callable_losses = self._callable_losses[ + previous_callable_losses_length:] + for regularizer in new_callable_losses: + loss_tensor = regularizer() + if loss_tensor is not None: + new_losses.append(loss_tensor) + _add_elements_to_collection( + new_losses, + ops.GraphKeys.REGULARIZATION_LOSSES) + + def _name_scope(self): # pylint: disable=method-hidden + """Determines op naming for the Layer.""" + if self._keras_style: + return super(Layer, self)._name_scope() + return self._current_scope.original_name_scope + + def _set_scope(self, scope=None): + if self._scope is None: + # If constructed with _scope=None, lazy setting of scope. + if self._reuse: + with vs.variable_scope( + scope if scope is not None else self._base_name) as captured_scope: + self._scope = captured_scope + else: + with vs.variable_scope( + scope, default_name=self._base_name) as captured_scope: + self._scope = captured_scope + + def add_weight(self, + name, + shape, + dtype=None, + initializer=None, + regularizer=None, + trainable=None, + constraint=None, + use_resource=None, + synchronization=vs.VariableSynchronization.AUTO, + aggregation=vs.VariableAggregation.NONE, + partitioner=None, + **kwargs): + """Adds a new variable to the layer, or gets an existing one; returns it. + + Args: + name: variable name. + shape: variable shape. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + initializer: initializer instance (callable). + regularizer: regularizer instance (callable). + trainable: whether the variable should be part of the layer's + "trainable_variables" (e.g. variables, biases) + or "non_trainable_variables" (e.g. BatchNorm mean, stddev). + Note, if the current variable scope is marked as non-trainable + then this parameter is ignored and any added variables are also + marked as non-trainable. `trainable` defaults to `True` unless + `synchronization` is set to `ON_READ`. + constraint: constraint instance (callable). + use_resource: Whether to use `ResourceVariable`. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. If `synchronization` is set to `ON_READ`, + `trainable` must not be set to `True`. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + partitioner: (optional) partitioner instance (callable). If + provided, when the requested variable is created it will be split + into multiple partitions according to `partitioner`. In this case, + an instance of `PartitionedVariable` is returned. Available + partitioners include `tf.compat.v1.fixed_size_partitioner` and + `tf.compat.v1.variable_axis_size_partitioner`. For more details, see + the documentation of `tf.compat.v1.get_variable` and the "Variable + Partitioners and Sharding" section of the API guide. + **kwargs: Additional keyword arguments. + + Returns: + The created variable. Usually either a `Variable` or `ResourceVariable` + instance. If `partitioner` is not `None`, a `PartitionedVariable` + instance is returned. + + Raises: + RuntimeError: If called with partitioned variable regularization and + eager execution is enabled. + ValueError: When trainable has been set to True with synchronization + set as `ON_READ`. + """ + for kwarg in kwargs: + if kwarg != 'experimental_autocast': + raise TypeError('Unknown keyword argument:', kwarg) + if self._keras_style: + return super(Layer, self).add_weight( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + trainable=trainable and self.trainable, + constraint=constraint, + use_resource=use_resource, + synchronization=vs.VariableSynchronization.AUTO, + aggregation=vs.VariableAggregation.NONE, + partitioner=partitioner, + **kwargs) + + if synchronization == vs.VariableSynchronization.ON_READ: + if trainable: + raise ValueError( + 'Synchronization value can be set to ' + 'VariableSynchronization.ON_READ only for non-trainable variables. ' + 'You have specified trainable=True and ' + 'synchronization=VariableSynchronization.ON_READ.') + else: + # Set trainable to be false when variable is to be synced on read. + trainable = False + elif trainable is None: + trainable = True + + def _should_add_regularizer(variable, existing_variable_set): + if base_layer_utils.is_split_variable(variable): + for var in variable: + if var in existing_variable_set: + return False + return True + else: + return variable not in existing_variable_set + + init_graph = None + if not context.executing_eagerly(): + default_graph = ops.get_default_graph() + if default_graph.building_function: + with ops.init_scope(): + # Retrieve the variables from the graph into which variables + # will be lifted; if initialization ops will be lifted into + # the eager context, then there is nothing to retrieve, since variable + # collections are not supported when eager execution is enabled. + if not context.executing_eagerly(): + init_graph = ops.get_default_graph() + existing_variables = set(tf_variables.global_variables()) + else: + # Initialization ops will not be lifted out of the default graph. + init_graph = default_graph + existing_variables = set(tf_variables.global_variables()) + + if dtype is None: + dtype = self.dtype or dtypes.float32 + + self._set_scope(None) + reuse = self.built or self._reuse + prev_len_trainable = len(self._trainable_weights) + with vs.variable_scope( + self._scope, reuse=reuse, auxiliary_name_scope=False) as scope: + self._current_scope = scope + with backend.name_scope(self._name_scope()): # pylint: disable=not-callable + use_resource = (use_resource or + self._use_resource_variables or + scope.use_resource) + if initializer is None: + initializer = scope.initializer + variable = super(Layer, self).add_weight( + name, + shape, + dtype=dtypes.as_dtype(dtype), + initializer=initializer, + trainable=trainable and self.trainable, + constraint=constraint, + partitioner=partitioner, + use_resource=use_resource, + synchronization=synchronization, + aggregation=aggregation, + getter=vs.get_variable, + **kwargs) + + if regularizer: + if (ops.executing_eagerly_outside_functions() + or _should_add_regularizer(variable, existing_variables)): + self._handle_weight_regularization(name, variable, regularizer) + var_store = vs._get_default_variable_store() # pylint: disable=protected-access + # When the shim to get variable scope working in TF2 is used, + # We need to explicitly make the shim track the regularization + # losses as the collections will not be accessible. + if hasattr(var_store, 'add_regularizer'): + var_store.add_regularizer(variable, regularizer) + + if init_graph is not None: + # Handle edge case where a custom getter has overridden `trainable`. + # There is one known occurrence of this, in unit test + # testBasicRNNCellNotTrainable in + # contrib.rnn.python.kernel_tests.core_rnn_cell_test + with init_graph.as_default(): + trainable_variables = tf_variables.trainable_variables() + if (trainable and self.trainable and + variable not in trainable_variables): + # A custom getter / variable scope overrode the trainable flag. + extra_trainable_vars = self._trainable_weights[prev_len_trainable:] + self._trainable_weights = self._trainable_weights[ + :prev_len_trainable] + self._non_trainable_weights += extra_trainable_vars + return variable + + def __call__(self, inputs, *args, **kwargs): + """Wraps `call`, applying pre- and post-processing steps. + + Args: + inputs: input tensor(s). + *args: additional positional arguments to be passed to `self.call`. + **kwargs: additional keyword arguments to be passed to `self.call`. + **Note**: kwarg `scope` is reserved for use by the layer. + + Returns: + Output tensor(s). + + Note: + - If the layer's `call` method takes a `scope` keyword argument, + this argument will be automatically set to the current variable scope. + - If the layer's `call` method takes a `mask` argument (as some Keras + layers do), its default value will be set to the mask generated + for `inputs` by the previous layer (if `input` did come from + a layer that generated a corresponding mask, i.e. if it came from + a Keras layer with masking support. + + Raises: + ValueError: if the layer's `call` method returns None (an invalid value). + """ + scope = kwargs.pop('scope', None) + + if self._keras_style: + if scope is not None: + raise ValueError( + 'scope argument not allowed when keras style layers are enabled, ' + 'but saw: {}'.format(scope)) + return super(Layer, self).__call__(inputs, *args, **kwargs) + + self._set_scope(scope) + + if self.built: + try: + # Some classes which inherit from Layer do not use its constructor, so + # rather than initializing to None we check for an AttributeError. + scope_context_manager = self._always_reuse_variable_scope # pylint: disable=access-member-before-definition + except AttributeError: + scope_context_manager = None + + if scope_context_manager is None: + # From this point we will always set reuse=True, so create a "final" + # variable scope with this setting. We avoid re-creating variable scopes + # after this point as an optimization. + scope_context_manager = vs.variable_scope( + self._scope, reuse=True, auxiliary_name_scope=False) + + # Do not cache variable scopes if Eager mode is enabled. If Eager mode + # is enabled then we don't want to reuse scopes because the cached scope + # might be from a FuncGraph or Eager scope we are no longer in. + if not ops.executing_eagerly_outside_functions(): + self._always_reuse_variable_scope = scope_context_manager + else: + scope_context_manager = vs.variable_scope( + self._scope, reuse=self._reuse, auxiliary_name_scope=False) + + with scope_context_manager as scope: + self._current_scope = scope + + try: + call_has_scope_arg = self._call_has_scope_arg + except AttributeError: + self._call_fn_args = variable_scope_shim.fn_args(self.call) + self._call_has_scope_arg = 'scope' in self._call_fn_args + call_has_scope_arg = self._call_has_scope_arg + if call_has_scope_arg: + kwargs['scope'] = scope + + # Actually call layer + outputs = super(Layer, self).__call__(inputs, *args, **kwargs) + + if not context.executing_eagerly(): + # Update global default collections. + _add_elements_to_collection(self.updates, ops.GraphKeys.UPDATE_OPS) + return outputs + + def __deepcopy__(self, memo): + no_copy = set(['_graph', '_thread_local', '_metrics_lock']) + shallow_copy = set(['_scope', '_always_reuse_variable_scope']) + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k in no_copy: + setattr(result, k, v) + elif k in shallow_copy: + setattr(result, k, copy.copy(v)) + elif base_layer.is_tensor_or_tensor_list(v): + setattr(result, k, v) + else: + setattr(result, k, copy.deepcopy(v, memo)) + return result + + def __setattr__(self, value, name): + # By-pass the automatic dependency tracking performed by the parent Layer. + super(trackable.Trackable, self).__setattr__(value, name) # pylint: disable=bad-super-call + + @property + def _is_legacy_layer(self): + """Used by keras to check compatibility. This should not be overridden.""" + return True + + +def _add_elements_to_collection(elements, collection_list): + if context.executing_eagerly(): + raise RuntimeError('Using collections from Layers not supported in Eager ' + 'mode. Tried to add %s to %s' % (elements, + collection_list)) + elements = nest.flatten(elements) + collection_list = nest.flatten(collection_list) + for name in collection_list: + collection = ops.get_collection_ref(name) + collection_set = {id(e) for e in collection} + for element in elements: + if id(element) not in collection_set: + collection.append(element) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/convolutional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/convolutional.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f91b12b8a098c45073586d33e1310b5f0d37e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/convolutional.py @@ -0,0 +1,1492 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +# pylint: disable=g-classes-have-attributes +"""Contains the convolutional layer classes and their functional aliases.""" +import warnings + +from tensorflow.python.keras import layers as keras_layers +from tensorflow.python.keras.legacy_tf_layers import base +from tensorflow.python.ops import init_ops + + +class Conv1D(keras_layers.Conv1D, base.Layer): + """1D convolution layer (e.g. temporal convolution). + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of a single integer, specifying the + length of the 1D convolution window. + strides: An integer or tuple/list of a single integer, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + dilation_rate: An integer or tuple/list of a single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Conv1D, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, **kwargs) + + +def conv1d(inputs, + filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for 1D convolution layer (e.g. temporal convolution). + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + inputs: Tensor input. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of a single integer, specifying the + length of the 1D convolution window. + strides: An integer or tuple/list of a single integer, + specifying the stride length of the convolution. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + dilation_rate: An integer or tuple/list of a single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any `strides` value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.conv1d` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.Conv1D` instead.') + layer = Conv1D( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +class Conv2D(keras_layers.Conv2D, base.Layer): + """2D convolution layer (e.g. spatial convolution over images). + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Conv2D, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, **kwargs) + + +def conv2d(inputs, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for the 2D convolution layer. + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + inputs: Tensor input. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of 2 integers, specifying the + height and width of the 2D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the convolution along the height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.conv2d` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.Conv2D` instead.') + layer = Conv2D( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +class Conv3D(keras_layers.Conv3D, base.Layer): + """3D convolution layer (e.g. spatial convolution over volumes). + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the convolution along the depth, + height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + dilation_rate: An integer or tuple/list of 3 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1, 1), + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Conv3D, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, **kwargs) + + +def conv3d(inputs, + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1, 1), + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for the 3D convolution layer. + + This layer creates a convolution kernel that is convolved + (actually cross-correlated) with the layer input to produce a tensor of + outputs. If `use_bias` is True (and a `bias_initializer` is provided), + a bias vector is created and added to the outputs. Finally, if + `activation` is not `None`, it is applied to the outputs as well. + + Args: + inputs: Tensor input. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the convolution along the depth, + height and width. + Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any stride value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + dilation_rate: An integer or tuple/list of 3 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.conv3d` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.Conv3D` instead.') + layer = Conv3D( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +class SeparableConv1D(keras_layers.SeparableConv1D, base.Layer): + """Depthwise separable 1D convolution. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A single integer specifying the spatial + dimensions of the filters. + strides: A single integer specifying the strides + of the convolution. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + dilation_rate: A single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel. + pointwise_initializer: An initializer for the pointwise convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel. + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer`. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer=None, + pointwise_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(SeparableConv1D, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activation, + use_bias=use_bias, + depthwise_initializer=depthwise_initializer, + pointwise_initializer=pointwise_initializer, + bias_initializer=bias_initializer, + depthwise_regularizer=depthwise_regularizer, + pointwise_regularizer=pointwise_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + depthwise_constraint=depthwise_constraint, + pointwise_constraint=pointwise_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + + +class SeparableConv2D(keras_layers.SeparableConv2D, base.Layer): + """Depthwise separable 2D convolution. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of 2 integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of 2 positive integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel. + pointwise_initializer: An initializer for the pointwise convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel. + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer`. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer=None, + pointwise_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(SeparableConv2D, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activation, + use_bias=use_bias, + depthwise_initializer=depthwise_initializer, + pointwise_initializer=pointwise_initializer, + bias_initializer=bias_initializer, + depthwise_regularizer=depthwise_regularizer, + pointwise_regularizer=pointwise_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + depthwise_constraint=depthwise_constraint, + pointwise_constraint=pointwise_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + + +def separable_conv1d(inputs, + filters, + kernel_size, + strides=1, + padding='valid', + data_format='channels_last', + dilation_rate=1, + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer=None, + pointwise_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for the depthwise separable 1D convolution layer. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + inputs: Input tensor. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A single integer specifying the spatial + dimensions of the filters. + strides: A single integer specifying the strides + of the convolution. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + dilation_rate: A single integer, specifying + the dilation rate to use for dilated convolution. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel. + pointwise_initializer: An initializer for the pointwise convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel. + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer`. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.separable_conv1d` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.SeparableConv1D` instead.') + layer = SeparableConv1D( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activation, + use_bias=use_bias, + depthwise_initializer=depthwise_initializer, + pointwise_initializer=pointwise_initializer, + bias_initializer=bias_initializer, + depthwise_regularizer=depthwise_regularizer, + pointwise_regularizer=pointwise_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + depthwise_constraint=depthwise_constraint, + pointwise_constraint=pointwise_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +def separable_conv2d(inputs, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + dilation_rate=(1, 1), + depth_multiplier=1, + activation=None, + use_bias=True, + depthwise_initializer=None, + pointwise_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + depthwise_regularizer=None, + pointwise_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + depthwise_constraint=None, + pointwise_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for the depthwise separable 2D convolution layer. + + This layer performs a depthwise convolution that acts separately on + channels, followed by a pointwise convolution that mixes channels. + If `use_bias` is True and a bias initializer is provided, + it adds a bias vector to the output. + It then optionally applies an activation function to produce the final output. + + Args: + inputs: Input tensor. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of 2 integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of 2 positive integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + Specifying any `stride` value != 1 is incompatible with specifying + any `dilation_rate` value != 1. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + + dilation_rate: An integer or tuple/list of 2 integers, specifying + the dilation rate to use for dilated convolution. + Can be a single integer to specify the same value for + all spatial dimensions. + Currently, specifying any `dilation_rate` value != 1 is + incompatible with specifying any stride value != 1. + depth_multiplier: The number of depthwise convolution output channels for + each input channel. The total number of depthwise convolution output + channels will be equal to `num_filters_in * depth_multiplier`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + depthwise_initializer: An initializer for the depthwise convolution kernel. + pointwise_initializer: An initializer for the pointwise convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + depthwise_regularizer: Optional regularizer for the depthwise + convolution kernel. + pointwise_regularizer: Optional regularizer for the pointwise + convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + depthwise_constraint: Optional projection function to be applied to the + depthwise kernel after being updated by an `Optimizer` (e.g. used for + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + pointwise_constraint: Optional projection function to be applied to the + pointwise kernel after being updated by an `Optimizer`. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.separable_conv2d` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.SeparableConv2D` instead.') + layer = SeparableConv2D( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + dilation_rate=dilation_rate, + depth_multiplier=depth_multiplier, + activation=activation, + use_bias=use_bias, + depthwise_initializer=depthwise_initializer, + pointwise_initializer=pointwise_initializer, + bias_initializer=bias_initializer, + depthwise_regularizer=depthwise_regularizer, + pointwise_regularizer=pointwise_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + depthwise_constraint=depthwise_constraint, + pointwise_constraint=pointwise_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +class Conv2DTranspose(keras_layers.Conv2DTranspose, base.Layer): + """Transposed 2D convolution layer (sometimes called 2D Deconvolution). + + The need for transposed convolutions generally arises + from the desire to use a transformation going in the opposite direction + of a normal convolution, i.e., from something that has the shape of the + output of some convolution to something that has the shape of its input + while maintaining a connectivity pattern that is compatible with + said convolution. + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of 2 positive integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of 2 positive integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Conv2DTranspose, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + + +def conv2d_transpose(inputs, + filters, + kernel_size, + strides=(1, 1), + padding='valid', + data_format='channels_last', + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for transposed 2D convolution layer. + + The need for transposed convolutions generally arises + from the desire to use a transformation going in the opposite direction + of a normal convolution, i.e., from something that has the shape of the + output of some convolution to something that has the shape of its input + while maintaining a connectivity pattern that is compatible with + said convolution. + + Args: + inputs: Input tensor. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of 2 positive integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of 2 positive integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + activation: Activation function. Set it to `None` to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If `None`, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.conv2d_transpose` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.Conv2DTranspose` instead.') + layer = Conv2DTranspose( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +class Conv3DTranspose(keras_layers.Conv3DTranspose, base.Layer): + """Transposed 3D convolution layer (sometimes called 3D Deconvolution). + + Args: + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: An integer or tuple/list of 3 integers, specifying the + depth, height and width of the 3D convolution window. + Can be a single integer to specify the same value for all spatial + dimensions. + strides: An integer or tuple/list of 3 integers, specifying the strides + of the convolution along the depth, height and width. + Can be a single integer to specify the same value for all spatial + dimensions. + padding: One of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + activation: Activation function. Set it to `None` to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If `None`, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + """ + + def __init__(self, + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Conv3DTranspose, self).__init__( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + + +def conv3d_transpose(inputs, + filters, + kernel_size, + strides=(1, 1, 1), + padding='valid', + data_format='channels_last', + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for transposed 3D convolution layer. + + Args: + inputs: Input tensor. + filters: Integer, the dimensionality of the output space (i.e. the number + of filters in the convolution). + kernel_size: A tuple or list of 3 positive integers specifying the spatial + dimensions of the filters. Can be a single integer to specify the same + value for all spatial dimensions. + strides: A tuple or list of 3 positive integers specifying the strides + of the convolution. Can be a single integer to specify the same value for + all spatial dimensions. + padding: one of `"valid"` or `"same"` (case-insensitive). + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + activation: Activation function. Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: An initializer for the convolution kernel. + bias_initializer: An initializer for the bias vector. If None, the default + initializer will be used. + kernel_regularizer: Optional regularizer for the convolution kernel. + bias_regularizer: Optional regularizer for the bias vector. + activity_regularizer: Optional regularizer function for the output. + kernel_constraint: Optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: Optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: A string, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.conv3d_transpose` is deprecated and ' + 'will be removed in a future version. ' + 'Please Use `tf.keras.layers.Conv3DTranspose` instead.') + layer = Conv3DTranspose( + filters=filters, + kernel_size=kernel_size, + strides=strides, + padding=padding, + data_format=data_format, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _reuse=reuse, + _scope=name) + return layer.apply(inputs) + + +# Aliases + +Convolution1D = Conv1D +Convolution2D = Conv2D +Convolution3D = Conv3D +SeparableConvolution2D = SeparableConv2D +Convolution2DTranspose = Deconvolution2D = Deconv2D = Conv2DTranspose +Convolution3DTranspose = Deconvolution3D = Deconv3D = Conv3DTranspose +convolution1d = conv1d +convolution2d = conv2d +convolution3d = conv3d +separable_convolution2d = separable_conv2d +convolution2d_transpose = deconvolution2d = deconv2d = conv2d_transpose +convolution3d_transpose = deconvolution3d = deconv3d = conv3d_transpose diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py new file mode 100644 index 0000000000000000000000000000000000000000..99d2c59ccadad89969b3fd2e638f86e3779217bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/core.py @@ -0,0 +1,328 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +# pylint: disable=g-classes-have-attributes +"""Contains the core layers: Dense, Dropout. + +Also contains their functional aliases. +""" +import warnings + +from tensorflow.python.keras import layers as keras_layers +from tensorflow.python.keras.legacy_tf_layers import base +from tensorflow.python.ops import init_ops + + +class Dense(keras_layers.Dense, base.Layer): + """Densely-connected layer class. + + This layer implements the operation: + `outputs = activation(inputs * kernel + bias)` + Where `activation` is the activation function passed as the `activation` + argument (if not `None`), `kernel` is a weights matrix created by the layer, + and `bias` is a bias vector created by the layer + (only if `use_bias` is `True`). + + Args: + units: Integer or Long, dimensionality of the output space. + activation: Activation function (callable). Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: Initializer function for the weight matrix. + If `None` (default), weights are initialized using the default + initializer used by `tf.compat.v1.get_variable`. + bias_initializer: Initializer function for the bias. + kernel_regularizer: Regularizer function for the weight matrix. + bias_regularizer: Regularizer function for the bias. + activity_regularizer: Regularizer function for the output. + kernel_constraint: An optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: An optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: String, the name of the layer. Layers with the same name will + share weights, but to avoid mistakes we require reuse=True in such cases. + _reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Properties: + units: Python integer, dimensionality of the output space. + activation: Activation function (callable). + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: Initializer instance (or name) for the kernel matrix. + bias_initializer: Initializer instance (or name) for the bias. + kernel_regularizer: Regularizer instance for the kernel matrix (callable) + bias_regularizer: Regularizer instance for the bias (callable). + activity_regularizer: Regularizer instance for the output (callable) + kernel_constraint: Constraint function for the kernel matrix. + bias_constraint: Constraint function for the bias. + kernel: Weight matrix (TensorFlow variable or tensor). + bias: Bias vector, if applicable (TensorFlow variable or tensor). + """ + + def __init__(self, units, + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + **kwargs): + super(Dense, self).__init__(units=units, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + **kwargs) + + +def dense( + inputs, units, + activation=None, + use_bias=True, + kernel_initializer=None, + bias_initializer=init_ops.zeros_initializer(), + kernel_regularizer=None, + bias_regularizer=None, + activity_regularizer=None, + kernel_constraint=None, + bias_constraint=None, + trainable=True, + name=None, + reuse=None): + """Functional interface for the densely-connected layer. + + This layer implements the operation: + `outputs = activation(inputs * kernel + bias)` + where `activation` is the activation function passed as the `activation` + argument (if not `None`), `kernel` is a weights matrix created by the layer, + and `bias` is a bias vector created by the layer + (only if `use_bias` is `True`). + + Args: + inputs: Tensor input. + units: Integer or Long, dimensionality of the output space. + activation: Activation function (callable). Set it to None to maintain a + linear activation. + use_bias: Boolean, whether the layer uses a bias. + kernel_initializer: Initializer function for the weight matrix. + If `None` (default), weights are initialized using the default + initializer used by `tf.compat.v1.get_variable`. + bias_initializer: Initializer function for the bias. + kernel_regularizer: Regularizer function for the weight matrix. + bias_regularizer: Regularizer function for the bias. + activity_regularizer: Regularizer function for the output. + kernel_constraint: An optional projection function to be applied to the + kernel after being updated by an `Optimizer` (e.g. used to implement + norm constraints or value constraints for layer weights). The function + must take as input the unprojected variable and must return the + projected variable (which must have the same shape). Constraints are + not safe to use when doing asynchronous distributed training. + bias_constraint: An optional projection function to be applied to the + bias after being updated by an `Optimizer`. + trainable: Boolean, if `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: String, the name of the layer. + reuse: Boolean, whether to reuse the weights of a previous layer + by the same name. + + Returns: + Output tensor the same shape as `inputs` except the last dimension is of + size `units`. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.dense` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.Dense` instead.') + layer = Dense(units, + activation=activation, + use_bias=use_bias, + kernel_initializer=kernel_initializer, + bias_initializer=bias_initializer, + kernel_regularizer=kernel_regularizer, + bias_regularizer=bias_regularizer, + activity_regularizer=activity_regularizer, + kernel_constraint=kernel_constraint, + bias_constraint=bias_constraint, + trainable=trainable, + name=name, + _scope=name, + _reuse=reuse) + return layer.apply(inputs) + + +class Dropout(keras_layers.Dropout, base.Layer): + """Applies Dropout to the input. + + Dropout consists in randomly setting a fraction `rate` of input units to 0 + at each update during training time, which helps prevent overfitting. + The units that are kept are scaled by `1 / (1 - rate)`, so that their + sum is unchanged at training time and inference time. + + Args: + rate: The dropout rate, between 0 and 1. E.g. `rate=0.1` would drop out + 10% of input units. + noise_shape: 1D tensor of type `int32` representing the shape of the + binary dropout mask that will be multiplied with the input. + For instance, if your inputs have shape + `(batch_size, timesteps, features)`, and you want the dropout mask + to be the same for all timesteps, you can use + `noise_shape=[batch_size, 1, features]`. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed`. + for behavior. + name: The name of the layer (string). + """ + + def __init__(self, rate=0.5, + noise_shape=None, + seed=None, + name=None, + **kwargs): + super(Dropout, self).__init__(rate=rate, + noise_shape=noise_shape, + seed=seed, + name=name, + **kwargs) + + def call(self, inputs, training=False): + return super(Dropout, self).call(inputs, training=training) + + +def dropout(inputs, + rate=0.5, + noise_shape=None, + seed=None, + training=False, + name=None): + """Applies Dropout to the input. + + Dropout consists in randomly setting a fraction `rate` of input units to 0 + at each update during training time, which helps prevent overfitting. + The units that are kept are scaled by `1 / (1 - rate)`, so that their + sum is unchanged at training time and inference time. + + Args: + inputs: Tensor input. + rate: The dropout rate, between 0 and 1. E.g. "rate=0.1" would drop out + 10% of input units. + noise_shape: 1D tensor of type `int32` representing the shape of the + binary dropout mask that will be multiplied with the input. + For instance, if your inputs have shape + `(batch_size, timesteps, features)`, and you want the dropout mask + to be the same for all timesteps, you can use + `noise_shape=[batch_size, 1, features]`. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` + for behavior. + training: Either a Python boolean, or a TensorFlow boolean scalar tensor + (e.g. a placeholder). Whether to return the output in training mode + (apply dropout) or in inference mode (return the input untouched). + name: The name of the layer (string). + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.dropout` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.Dropout` instead.') + layer = Dropout(rate, noise_shape=noise_shape, seed=seed, name=name) + return layer.apply(inputs, training=training) + + +class Flatten(keras_layers.Flatten, base.Layer): + """Flattens an input tensor while preserving the batch axis (axis 0). + + Args: + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, ..., channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, ...)`. + + Examples: + + ``` + x = tf.compat.v1.placeholder(shape=(None, 4, 4), dtype='float32') + y = Flatten()(x) + # now `y` has shape `(None, 16)` + + x = tf.compat.v1.placeholder(shape=(None, 3, None), dtype='float32') + y = Flatten()(x) + # now `y` has shape `(None, None)` + ``` + """ + pass + + +def flatten(inputs, name=None, data_format='channels_last'): + """Flattens an input tensor while preserving the batch axis (axis 0). + + Args: + inputs: Tensor input. + name: The name of the layer (string). + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + + Returns: + Reshaped tensor. + + Examples: + + ``` + x = tf.compat.v1.placeholder(shape=(None, 4, 4), dtype='float32') + y = flatten(x) + # now `y` has shape `(None, 16)` + + x = tf.compat.v1.placeholder(shape=(None, 3, None), dtype='float32') + y = flatten(x) + # now `y` has shape `(None, None)` + ``` + """ + warnings.warn('`tf.layers.flatten` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.Flatten` instead.') + layer = Flatten(name=name, data_format=data_format) + return layer.apply(inputs) + + +# Aliases + +FullyConnected = Dense +fully_connected = dense diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/pooling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..68849eb39a20bc5ecdceab71e6ff9105beeebd81 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/pooling.py @@ -0,0 +1,459 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +# pylint: disable=g-classes-have-attributes +"""Contains the pooling layer classes and their functional aliases.""" +import warnings + +from tensorflow.python.keras import layers as keras_layers +from tensorflow.python.keras.legacy_tf_layers import base + + +class AveragePooling1D(keras_layers.AveragePooling1D, base.Layer): + """Average Pooling layer for 1D inputs. + + Args: + pool_size: An integer or tuple/list of a single integer, + representing the size of the pooling window. + strides: An integer or tuple/list of a single integer, specifying the + strides of the pooling operation. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(AveragePooling1D, self).__init__( + pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + name=name, + **kwargs) + + +def average_pooling1d(inputs, pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Average Pooling layer for 1D inputs. + + Args: + inputs: The tensor over which to pool. Must have rank 3. + pool_size: An integer or tuple/list of a single integer, + representing the size of the pooling window. + strides: An integer or tuple/list of a single integer, specifying the + strides of the pooling operation. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + name: A string, the name of the layer. + + Returns: + The output tensor, of rank 3. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.average_pooling1d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.AveragePooling1D` instead.') + layer = AveragePooling1D(pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + return layer.apply(inputs) + + +class MaxPooling1D(keras_layers.MaxPooling1D, base.Layer): + """Max Pooling layer for 1D inputs. + + Args: + pool_size: An integer or tuple/list of a single integer, + representing the size of the pooling window. + strides: An integer or tuple/list of a single integer, specifying the + strides of the pooling operation. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(MaxPooling1D, self).__init__( + pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + name=name, + **kwargs) + + +def max_pooling1d(inputs, pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Max Pooling layer for 1D inputs. + + Args: + inputs: The tensor over which to pool. Must have rank 3. + pool_size: An integer or tuple/list of a single integer, + representing the size of the pooling window. + strides: An integer or tuple/list of a single integer, specifying the + strides of the pooling operation. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string, one of `channels_last` (default) or `channels_first`. + The ordering of the dimensions in the inputs. + `channels_last` corresponds to inputs with shape + `(batch, length, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, length)`. + name: A string, the name of the layer. + + Returns: + The output tensor, of rank 3. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.max_pooling1d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.MaxPooling1D` instead.') + layer = MaxPooling1D(pool_size=pool_size, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + return layer.apply(inputs) + + +class AveragePooling2D(keras_layers.AveragePooling2D, base.Layer): + """Average pooling layer for 2D inputs (e.g. images). + + Args: + pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(AveragePooling2D, self).__init__( + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, name=name, **kwargs) + + +def average_pooling2d(inputs, + pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Average pooling layer for 2D inputs (e.g. images). + + Args: + inputs: The tensor over which to pool. Must have rank 4. + pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + name: A string, the name of the layer. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.average_pooling2d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.AveragePooling2D` instead.') + layer = AveragePooling2D(pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, + name=name) + return layer.apply(inputs) + + +class MaxPooling2D(keras_layers.MaxPooling2D, base.Layer): + """Max pooling layer for 2D inputs (e.g. images). + + Args: + pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(MaxPooling2D, self).__init__( + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, name=name, **kwargs) + + +def max_pooling2d(inputs, + pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Max pooling layer for 2D inputs (e.g. images). + + Args: + inputs: The tensor over which to pool. Must have rank 4. + pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 2 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, height, width, channels)` while `channels_first` corresponds to + inputs with shape `(batch, channels, height, width)`. + name: A string, the name of the layer. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.max_pooling2d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.MaxPooling2D` instead.') + layer = MaxPooling2D(pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, + name=name) + return layer.apply(inputs) + + +class AveragePooling3D(keras_layers.AveragePooling3D, base.Layer): + """Average pooling layer for 3D inputs (e.g. volumes). + + Args: + pool_size: An integer or tuple/list of 3 integers: + (pool_depth, pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(AveragePooling3D, self).__init__( + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, name=name, **kwargs) + + +def average_pooling3d(inputs, + pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Average pooling layer for 3D inputs (e.g. volumes). + + Args: + inputs: The tensor over which to pool. Must have rank 5. + pool_size: An integer or tuple/list of 3 integers: + (pool_depth, pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + name: A string, the name of the layer. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.average_pooling3d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.AveragePooling3D` instead.') + layer = AveragePooling3D(pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, + name=name) + return layer.apply(inputs) + + +class MaxPooling3D(keras_layers.MaxPooling3D, base.Layer): + """Max pooling layer for 3D inputs (e.g. volumes). + + Args: + pool_size: An integer or tuple/list of 3 integers: + (pool_depth, pool_height, pool_width) + specifying the size of the pooling window. + Can be a single integer to specify the same value for + all spatial dimensions. + strides: An integer or tuple/list of 3 integers, + specifying the strides of the pooling operation. + Can be a single integer to specify the same value for + all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape + `(batch, depth, height, width, channels)` while `channels_first` + corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + name: A string, the name of the layer. + """ + + def __init__(self, pool_size, strides, + padding='valid', data_format='channels_last', + name=None, **kwargs): + if strides is None: + raise ValueError('Argument `strides` must not be None.') + super(MaxPooling3D, self).__init__( + pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, name=name, **kwargs) + + +def max_pooling3d(inputs, + pool_size, strides, + padding='valid', data_format='channels_last', + name=None): + """Max pooling layer for 3D inputs (e.g. + + volumes). + + Args: + inputs: The tensor over which to pool. Must have rank 5. + pool_size: An integer or tuple/list of 3 integers: (pool_depth, pool_height, + pool_width) specifying the size of the pooling window. Can be a single + integer to specify the same value for all spatial dimensions. + strides: An integer or tuple/list of 3 integers, specifying the strides of + the pooling operation. Can be a single integer to specify the same value + for all spatial dimensions. + padding: A string. The padding method, either 'valid' or 'same'. + Case-insensitive. + data_format: A string. The ordering of the dimensions in the inputs. + `channels_last` (default) and `channels_first` are supported. + `channels_last` corresponds to inputs with shape `(batch, depth, height, + width, channels)` while `channels_first` corresponds to inputs with shape + `(batch, channels, depth, height, width)`. + name: A string, the name of the layer. + + Returns: + Output tensor. + + Raises: + ValueError: if eager execution is enabled. + """ + warnings.warn('`tf.layers.max_pooling3d` is deprecated and ' + 'will be removed in a future version. ' + 'Please use `tf.keras.layers.MaxPooling3D` instead.') + layer = MaxPooling3D(pool_size=pool_size, strides=strides, + padding=padding, data_format=data_format, + name=name) + return layer.apply(inputs) + +# Aliases + +AvgPool2D = AveragePooling2D +MaxPool2D = MaxPooling2D +max_pool2d = max_pooling2d +avg_pool2d = average_pooling2d diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..ad827ea22a4036327d1990e6b37daf78c3b12749 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py @@ -0,0 +1,752 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +# pylint: disable=g-classes-have-attributes +"""Contains a shim to allow using TF1 get_variable code in TF2.""" +import functools + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.module import module +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_decorator + + +def as_shape(shape): + """Converts the given object to a TensorShape.""" + if isinstance(shape, tensor_shape.TensorShape): + return shape + else: + return tensor_shape.TensorShape(shape) + + +def _is_callable_object(obj): + return hasattr(obj, "__call__") and tf_inspect.ismethod(obj.__call__) + + +def _has_kwargs(fn): + """Returns whether the passed callable has **kwargs in its signature. + + Args: + fn: Function, or function-like object (e.g., result of `functools.partial`). + + Returns: + `bool`: if `fn` has **kwargs in its signature. + + Raises: + `TypeError`: If fn is not a Function, or function-like object. + """ + if isinstance(fn, functools.partial): + fn = fn.func + elif _is_callable_object(fn): + fn = fn.__call__ + elif not callable(fn): + raise TypeError( + "fn should be a function-like object, but is of type {}.".format( + type(fn))) + return tf_inspect.getfullargspec(fn).varkw is not None + + +def fn_args(fn): + """Get argument names for function-like object. + + Args: + fn: Function, or function-like object (e.g., result of `functools.partial`). + + Returns: + `tuple` of string argument names. + + Raises: + ValueError: if partial function has positionally bound arguments + """ + if isinstance(fn, functools.partial): + args = fn_args(fn.func) + args = [a for a in args[len(fn.args):] if a not in (fn.keywords or [])] + else: + if hasattr(fn, "__call__") and tf_inspect.ismethod(fn.__call__): + fn = fn.__call__ + args = tf_inspect.getfullargspec(fn).args + if _is_bound_method(fn) and args: + # If it's a bound method, it may or may not have a self/cls first + # argument; for example, self could be captured in *args. + # If it does have a positional argument, it is self/cls. + args.pop(0) + return tuple(args) + + +def _is_bound_method(fn): + _, fn = tf_decorator.unwrap(fn) + return tf_inspect.ismethod(fn) and (fn.__self__ is not None) + + +def validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name): + """Given user-provided variable properties, sets defaults and validates.""" + if aggregation is None: + aggregation = variables.VariableAggregation.NONE + else: + if not isinstance(aggregation, + (variables.VariableAggregation, + variables.VariableAggregationV2)): + try: + aggregation = variables.VariableAggregationV2(aggregation) + except ValueError: + raise ValueError( + "Invalid variable aggregation mode: {} for variable: {}".format( + aggregation, name)) + if synchronization is None: + synchronization = variables.VariableSynchronization.AUTO + else: + try: + synchronization = variables.VariableSynchronization(synchronization) + except ValueError: + raise ValueError( + "Invalid variable synchronization mode: {} for variable: {}".format( + synchronization, name)) + if trainable is None: + trainable = synchronization != variables.VariableSynchronization.ON_READ + return synchronization, aggregation, trainable + + +class _EagerVariableStore(object): + """TF2-compatible VariableStore that avoids collections & tracks regularizers. + + New variable names and new variables can be created; all stored + variables are initialized with the initializer passed to __init__. + + All variables get created in `tf.init_scope.` to avoid a bad + interaction between `tf.function` `FuncGraph` internals, Keras + Functional Models, and TPUStrategy variable initialization. + + Attributes: + vars: a dictionary with string names (same as passed in GetVar) as keys and + the corresponding TensorFlow Variables as values. + """ + + __slots__ = ["_vars", "_regularizers", "_store_eager_variables"] + + def __init__(self): + """Create a variable store.""" + self._vars = {} # A dictionary of the stored TensorFlow variables. + self._regularizers = {} # A dict mapping var names to their regularizers. + self._store_eager_variables = True + + def get_variable( + self, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + custom_getter=None, + constraint=None, + synchronization=vs.VariableSynchronization.AUTO, + aggregation=vs.VariableAggregation.NONE): + """Gets an existing variable with these parameters or create a new one. + + If a variable with the given name is already stored, we return the stored + variable. Otherwise, we create a new one. + + Set `reuse` to `True` when you only want to reuse existing Variables. + Set `reuse` to `False` when you only want to create new Variables. + Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want + variables to be created if they don't exist or returned if they do. + + If initializer is `None` (the default), the default initializer passed in + the constructor is used. If that one is `None` too, we use a new + `glorot_uniform_initializer`. If initializer is a Tensor, we use + it as a value and derive the shape from the initializer. + + If a partitioner is provided, a `PartitionedVariable` is returned. + Accessing this object as a `Tensor` returns the shards concatenated along + the partition axis. + + Some useful partitioners are available. See, e.g., + `variable_axis_size_partitioner` and `min_max_variable_partitioner`. + + Args: + name: The name of the new or existing variable. + shape: Shape of the new or existing variable. + dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). + initializer: Initializer for the variable. + regularizer: A (Tensor -> Tensor or None) function; the result of applying + it on a newly created variable will be added to the collection + GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. + reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of + variables. When eager execution is enabled this argument is always + forced to be False. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). `trainable` + defaults to `True`, unless `synchronization` is set to `ON_READ`, in + which case it defaults to `False`. + collections: List of graph collections keys to add the `Variable` to. + Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the `Variable` reside, to + deduplicate copying through `Switch` and other conditional statements. + partitioner: Optional callable that accepts a fully defined `TensorShape` + and dtype of the `Variable` to be created, and returns a list of + partitions for each axis (currently only one axis can be partitioned). + validate_shape: If False, allows the variable to be initialized with a + value of unknown shape. If True, the default, the shape of initial_value + must be known. + use_resource: If False, creates a regular Variable. If True, creates + instead an experimental ResourceVariable which has well-defined + semantics. Defaults to False (will later change to True). When eager + execution is enabled this argument is always forced to be true. + custom_getter: Callable that takes as a first argument the true getter, + and allows overwriting the internal get_variable method. The signature + of `custom_getter` should match that of this method, + but the most future-proof version will allow for changes: `def + custom_getter(getter, *args, **kwargs)`. Direct access to + all `get_variable` parameters is also allowed: `def + custom_getter(getter, name, *args, **kwargs)`. A simple identity + custom getter that simply creates variables with modified names is: + ```python + def custom_getter(getter, name, *args, **kwargs): return getter(name + + '_suffix', *args, **kwargs) ``` + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + Returns: + The created or existing `Variable` (or `PartitionedVariable`, if a + partitioner was used). + + Raises: + ValueError: when creating a new variable and shape is not declared, + when reusing a variable and specifying a conflicting shape, + or when violating reuse during variable creation. + RuntimeError: when eager execution is enabled and not called from an + EagerVariableStore. + """ + if custom_getter is not None and not callable(custom_getter): + raise ValueError("Passed a custom_getter which is not callable: %s" % + custom_getter) + + with ops.init_scope(): + if context.executing_eagerly(): + # Variable creation and initialization takes place in `init_scope`s; + # as such, if an `init_scope` lifts us into the eager context, then we + # need to use `ResourceVariable`s. + use_resource = True + + # Note that it's fine to reuse eager variables whose initialization was + # lifted from a function-building graph into the eager context (that's why + # the following clause is not wrapped in an `init_scope`); lifted variables + # are tracked by the graph's `VariableStore`. + if context.executing_eagerly(): + reuse = vs.AUTO_REUSE + + # If a *_ref type is passed in an error would be triggered further down the + # stack. We prevent this using base_dtype to get a non-ref version of the + # type, before doing anything else. When _ref types are removed in favor of + # resources, this line can be removed. + try: + dtype = dtype.base_dtype + except AttributeError: + # .base_dtype not existing means that we will try and use the raw dtype + # which was passed in - this might be a NumPy type which is valid. + pass + + # This is the main logic of get_variable. However, custom_getter + # may override this logic. So we save it as a callable and pass + # it to custom_getter. + # Note: the parameters of _true_getter, and their documentation, match + # *exactly* item-for-item with the docstring of this method. + def _true_getter( # pylint: disable=missing-docstring + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, # pylint: disable=unused-argument + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, # pylint: disable=unused-argument + constraint=None, + synchronization=vs.VariableSynchronization.AUTO, + aggregation=vs.VariableAggregation.NONE): + # Partitioned variable currently unsupported w/ the shim + if partitioner is not None: + raise ValueError( + "`partitioner` arg for `get_variable` is unsupported in TF2." + "File a bug if you need help. You passed %s" % partitioner) + + # Single variable case + if "%s/part_0" % name in self._vars: + raise ValueError( + "No partitioner was provided, but a partitioned version of the " + "variable was found: %s/part_0. Perhaps a variable of the same " + "name was already created with partitioning?" % name) + + return self._get_single_variable( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + caching_device=caching_device, + validate_shape=validate_shape, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + synchronization, aggregation, trainable = ( + validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name)) + + if custom_getter is not None: + # Handle backwards compatibility with getter arguments that were added + # to the API after users started writing custom getters. + custom_getter_kwargs = { + "getter": _true_getter, + "name": name, + "shape": shape, + "dtype": dtype, + "initializer": initializer, + "regularizer": regularizer, + "reuse": reuse, + "trainable": trainable, + "collections": collections, + "caching_device": caching_device, + "partitioner": partitioner, + "validate_shape": validate_shape, + "use_resource": use_resource, + "synchronization": synchronization, + "aggregation": aggregation, + } + # `fn_args` and `has_kwargs` can handle functions, `functools.partial`, + # `lambda`. + if ("constraint" in fn_args(custom_getter) or + _has_kwargs(custom_getter)): + custom_getter_kwargs["constraint"] = constraint + return custom_getter(**custom_getter_kwargs) + else: + return _true_getter( + name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + def _get_single_variable( + self, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + partition_info=None, + reuse=None, + trainable=None, + caching_device=None, + validate_shape=True, + constraint=None, + synchronization=vs.VariableSynchronization.AUTO, + aggregation=vs.VariableAggregation.NONE): + """Get or create a single Variable (e.g. + + a shard or entire variable). + + See the documentation of get_variable above (ignore partitioning components) + for details. + + Args: + name: see get_variable. + shape: see get_variable. + dtype: see get_variable. + initializer: see get_variable. + regularizer: see get_variable. + partition_info: _PartitionInfo object. + reuse: see get_variable. + trainable: see get_variable. + caching_device: see get_variable. + validate_shape: see get_variable. + constraint: see get_variable. + synchronization: see get_variable. + aggregation: see get_variable. + + Returns: + A Variable. See documentation of get_variable above. + + Raises: + ValueError: See documentation of get_variable above. + """ + # Set to true if initializer is a constant. + initializing_from_value = False + if initializer is not None and not callable(initializer): + initializing_from_value = True + if shape is not None and initializing_from_value: + raise ValueError("If initializer is a constant, do not specify shape.") + + dtype = dtypes.as_dtype(dtype) + shape = as_shape(shape) + + if name in self._vars: + # Here we handle the case when returning an existing variable. + if reuse is False: # pylint: disable=g-bool-id-comparison + err_msg = ("Variable %s already exists, disallowed." + " Did you mean to set reuse=True or " + "reuse=tf.AUTO_REUSE in VarScope?" % name) + # ResourceVariables don't have an op associated with so no traceback + raise ValueError(err_msg) + found_var = self._vars[name] + if not shape.is_compatible_with(found_var.get_shape()): + raise ValueError("Trying to share variable %s, but specified shape %s" + " and found shape %s." % + (name, shape, found_var.get_shape())) + if not dtype.is_compatible_with(found_var.dtype): + dtype_str = dtype.name + found_type_str = found_var.dtype.name + raise ValueError("Trying to share variable %s, but specified dtype %s" + " and found dtype %s." % + (name, dtype_str, found_type_str)) + return found_var + + # The code below handles only the case of creating a new variable. + if reuse is True: # pylint: disable=g-bool-id-comparison + raise ValueError("Variable %s does not exist, or was not created with " + "tf.get_variable(). Did you mean to set " + "reuse=tf.AUTO_REUSE in VarScope?" % name) + + # Create the tensor to initialize the variable with default value. + if initializer is None: + initializer, initializing_from_value = self._get_default_initializer( + name=name, shape=shape, dtype=dtype) + # Enter an init scope when creating the initializer. + with ops.init_scope(): + if initializing_from_value: + init_val = initializer + variable_dtype = None + else: + # Instantiate initializer if provided initializer is a type object. + if tf_inspect.isclass(initializer): + initializer = initializer() + if shape.is_fully_defined(): + if "partition_info" in tf_inspect.getargspec(initializer).args: + init_val = functools.partial(initializer, + shape.as_list(), + dtype=dtype, + partition_info=partition_info) + else: + init_val = functools.partial(initializer, + shape.as_list(), dtype=dtype) + variable_dtype = dtype.base_dtype + else: + init_val = initializer + variable_dtype = None + + # Create the variable (Always eagerly as a workaround for a strange + # tpu / funcgraph / keras functional model interaction ) + with ops.init_scope(): + v = variables.Variable( + initial_value=init_val, + name=name, + trainable=trainable, + caching_device=caching_device, + dtype=variable_dtype, + validate_shape=validate_shape, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + self._vars[name] = v + logging.vlog(1, "Created variable %s with shape %s and init %s", v.name, + format(shape), initializer) + + # Run the regularizer if requested and save the resulting loss. + if regularizer: + self.add_regularizer(v, regularizer) + + return v + + def add_regularizer(self, var, regularizer): + self._regularizers[var.name] = functools.partial(regularizer, var) + + # Initialize variable when no initializer provided + def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32): + """Provide a default initializer and a corresponding value. + + Args: + name: see get_variable. + shape: see get_variable. + dtype: see get_variable. + + Returns: + initializer and initializing_from_value. See get_variable above. + + Raises: + ValueError: When giving unsupported dtype. + """ + del shape + # If dtype is DT_FLOAT, provide a uniform unit scaling initializer + if dtype.is_floating: + initializer = init_ops.glorot_uniform_initializer() + initializing_from_value = False + # If dtype is DT_INT/DT_UINT, provide a default value `zero` + # If dtype is DT_BOOL, provide a default value `FALSE` + elif (dtype.is_integer or dtype.is_unsigned or dtype.is_bool or + dtype == dtypes.string): + initializer = init_ops.zeros_initializer() + initializing_from_value = False + # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? + else: + raise ValueError("An initializer for variable %s of %s is required" % + (name, dtype.base_dtype)) + + return initializer, initializing_from_value + + +class VariableAndLossTracker(module.Module): + """Module that has a scope to capture vars/losses made by `get_variable`.""" + + def __init__(self): + self._var_store = _EagerVariableStore() # pylint: disable=protected-access + self._variables = {} + + def _variable_creator(self, next_creator, **kwargs): + var = next_creator(**kwargs) + self._variables[var.name] = var + + return var + + @tf_contextlib.contextmanager + def scope(self): + with vs.variable_creator_scope( + self._variable_creator), vs.with_variable_store(self._var_store): + yield + + def get_regularization_losses(self): + # TODO(kaftan): Consider adding a regex scope like the collection access. + # But, < 40-50 usages of get_regularization_loss(es) with `scope` + # & possible to do manually? + losses = {} + for var_name, regularizer in self._var_store._regularizers.items(): # pylint: disable=protected-access + losses[var_name] = regularizer() + return losses + + +class VariableScopeWrapperLayer(base_layer.Layer): + """Wrapper Layer to capture `compat.v1.get_variable` and `compat.v1.layers`. + + See go/tf2-migration-model-bookkeeping for background. + + This shim layer allows using large sets of TF1 model-forward-pass code as a + Keras layer that works in TF2 with TF2 behaviors enabled. To use it, + override this class and put your TF1 model's forward pass inside your + implementation for `forward_pass`. + + Below are some examples, and then more details on the functionality of this + shhim layer to wrap TF1 model forward passes. + + Example of capturing tf.compat.v1.layer-based modeling code as a Keras layer: + + ```python + class WrappedDoubleDenseLayer(variable_scope_shim.VariableScopeWrapperLayer): + + def __init__(self, units, *args, **kwargs): + super().__init__(*args, **kwargs) + self.units = units + + def forward_pass(self, inputs, training=None): + out = tf.compat.v1.layers.dense( + inputs, self.units, name="dense_one", + kernel_initializer=init_ops.ones_initializer(), + kernel_regularizer="l2") + with variable_scope.variable_scope("nested_scope"): + out = tf.compat.v1.layers.dense( + out, self.units, name="dense_two", + kernel_initializer=init_ops.ones_initializer(), + kernel_regularizer="l2") + return out + + # Create a layer that can be used as a standard keras layer + layer = WrappedDoubleDenseLayer(10) + + # call the layer on inputs + layer(...) + + # Variables created/used within the scope will be tracked by the layer + layer.weights + layer.trainable_variables + + # Regularization losses will be captured in layer.losses after a call, + # just like any other Keras layer + reg_losses = layer.losses + ``` + + The solution is to wrap the model construction and execution in a keras-style + scope: + + ```python + class WrappedDoubleDenseLayer(variable_scope_shim.VariableScopeWrapperLayer): + + def __init__(self, units, *args, **kwargs): + super().__init__(*args, **kwargs) + self.units = units + + def forward_pass(self, inputs, training=None): + out = inputs + with tf.compat.v1.variable_scope("dense_one"): + # The weights are created with a `regularizer`, + # so the layer should track their regularization losses + kernel = tf.compat.v1.get_variable( + shape=[out.shape[-1], self.units], + regularizer=regularizers.L2(), + initializer=init_ops.ones_initializer(), + name="kernel") + bias = tf.compat.v1.get_variable( + shape=[self.units,], + initializer=init_ops.zeros_initializer(), + name="bias") + out = tf.compat.v1.math.matmul(out, kernel) + out = tf.compat.v1.nn.bias_add(out, bias) + with tf.compat.v1.variable_scope("nested_scope"): + with tf.compat.v1.variable_scope("dense_two"): + kernel = tf.compat.v1.get_variable( + shape=[out.shape[-1], self.units], + regularizer=regularizers.L2(), + initializer=init_ops.ones_initializer(), + name="kernel") + bias = tf.compat.v1.get_variable( + shape=[self.units,], + initializer=init_ops.zeros_initializer(), + name="bias") + out = tf.compat.v1.math.matmul(out, kernel) + out = tf.compat.v1.nn.bias_add(out, bias) + return out + + # Create a layer that can be used as a standard keras layer + layer = WrappedDoubleDenseLayer(10) + + # call the layer on inputs + layer(...) + + # Variables created/used within the scope will be tracked by the layer + layer.weights + layer.trainable_variables + + # Regularization losses will be captured in layer.losses after a call, + # just like any other Keras layer + reg_losses = layer.losses + ``` + + Regularization losses: + Any regularizers specified in the `get_variable` calls or `compat.v1.layer` + creations will get captured by this wrapper layer. Regularization losses + are accessible in `layer.losses` after a call just like in a standard + Keras layer, and will be captured by any model that includes this layer. + + Variable scope / variable reuse: + variable-scope based reuse in the `forward_pass` will be respected, + and work like variable-scope based reuse in TF1. + + Variable Names/Pre-trained checkpoint loading: + variable naming from get_variable and `compat.v1.layer` layers will match + the TF1 names, so you should be able to re-use your old name-based + checkpoints. + + Training Arg in `forward_pass`: + Keras will pass a `training` arg to this layer similarly to how it + passes `training` to other layers in TF2. See more details in the docs + on `tf.keras.layers.Layer` to understand what will be passed and when. + Note: tf.compat.v1.layers are usually not called with `training=None`, + so the training arg to `forward_pass` might not feed through to them + unless you pass it to their calls explicitly. + + Call signature of the forward pass: + The semantics of the forward pass signature roughly match the standard + Keras layer `call` signature, except that a `training` arg will *always* + be passed, so your `forward_pass` must accept either. + + Limitations: + * TF2 will not prune unused variable updates (or unused outputs). You may + need to adjust your forward pass code to avoid computations or variable + updates that you don't intend to use. (E.g. by adding a flag to the + `forward_pass` call signature and branching on it). + * Avoid Nesting variable creation in tf.function inside of `forward_pass` + While the layer may safetely be used from inside a `tf.function`, using + a function inside of `forward_pass` will break the variable scoping. + * TBD: Nesting keras layers/models or other `VariableScopeWrapperLayer`s + directly in `forward_pass` may not work correctly just yet. + Support for this/instructions for how to do this is sill being worked on. + + Coming soon: A better guide, testing/verification guide. + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + # Relies on keras layers tracking Modules + self.tracker = VariableAndLossTracker() + # May need to inspect func to see if it should pass a `training` arg or not + + def forward_pass(self, *args, **kwargs): + raise NotImplementedError + + def call(self, *args, **kwargs): + with self.tracker.scope(): + out = self.forward_pass(*args, **kwargs) + if not self._eager_losses: + # We have to record regularization losses in the call as if they + # are activity losses. + # So, don't double-count regularization losses if the layer is used + # multiple times in a model + for loss in self.tracker.get_regularization_losses().values(): + self.add_loss(loss) + return out diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e713e0dc6bb35fbbc38e4d0d2578be78927ae1f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/__init__.py @@ -0,0 +1,20 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras mixed precision API. + +See [the mixed precision guide]( + https://www.tensorflow.org/guide/keras/mixed_precision) to learn how to +use the API. +""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/autocast_variable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/autocast_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..37b4dbf2a4511c370993b710c7ba0acb574b1e5a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/autocast_variable.py @@ -0,0 +1,560 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains AutoCastVariable, a variable which automatically casts itself.""" + +import threading + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras.distribute import distributed_training_utils +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.types import core + + +# _autocast_dtype.dtype is the dtype AutoCastVariables should be cast to, or +# None if AutoCastVariables should not be cast. +_autocast_dtype = threading.local() + + +def numpy_text(tensor, is_repr=False): + """Human readable representation of a tensor's numpy value.""" + if tensor.dtype.is_numpy_compatible: + # pylint: disable=protected-access + text = repr(tensor._numpy()) if is_repr else str(tensor._numpy()) + # pylint: enable=protected-access + else: + text = '' + if '\n' in text: + text = '\n' + text + return text + + +class AutoCastVariable(variables.Variable, core.Tensor): + """Variable that will cast itself to a different dtype in applicable contexts. + + This class wraps a floating-point `tf.Variable`. It emulates the variable + interface and delegates to the wrapped variable, but it additionally will cast + the wrapped variable under an `enable_auto_cast_variables(dtype)` context + manager. + + For example: + + >>> v = tf.Variable(1.0, dtype=tf.float32) + >>> v = AutoCastVariable(v) + >>> tf.identity(v).dtype + tf.float32 + >>> with enable_auto_cast_variables(tf.float16): + ... tf.identity(v).dtype + tf.float16 + + The purpose of this class is to allow Keras layers to create variables in + float32, and automatically cast them to float16 or bfloat16 when the layer is + called. + """ + + def __init__(self, variable): + """Creates an AutoCastVariable instance. + + Args: + variable: A floating-point resource variable to wrap. + + Raises: + ValueError: If `variable` is not a floating-point resource variable + """ + if not isinstance(variable, variables.Variable): + raise ValueError('variable must be of type tf.ResourceVariable, but got: ' + '%s' % variable) + if not variable.dtype.is_floating: + raise ValueError('variable must be a floating point variable but has ' + 'type: %s' % variable.dtype.name) + self._variable = variable + # 'delegate' means AutoCastVariable.op return self._variable.op, which will + # raise an AttributeError in Eager (as intended). If set to any other value, + # AutoCastVariable.op returns that value instead, which is used to set the + # op attribute in AutoCastVariable.assign(). + self._op = 'delegate' + + def _should_cast(self): + """Returns True if this variable should be casted when accessed.""" + autocast_dtype = getattr(_autocast_dtype, 'dtype', None) + return autocast_dtype is not None and self.dtype != autocast_dtype + + @property + def dtype(self): + """The dtype of the underlying variable, before any casts are done.""" + return self._variable.dtype + + @property + def true_dtype(self): + """Deprecated alias of `dtype`.""" + return self._variable.dtype + + @property + def _cast_dtype(self): + dtype = getattr(_autocast_dtype, 'dtype', None) + return dtype or self._variable.dtype + + def value(self): + val = self._variable.value() + if not self._should_cast(): + return val + return math_ops.cast(val, self._cast_dtype) + + def read_value(self): + val = self._variable.read_value() + return math_ops.cast(val, self._cast_dtype) + + def sparse_read(self, indices, name=None): + """Reads the value of this variable sparsely, using `gather`.""" + val = self._variable.sparse_read(indices, name=name) + return math_ops.cast(val, self._cast_dtype) + + def gather_nd(self, indices, name=None): + """Gather slices of the variable into a Tensor.""" + val = self._variable.gather_nd(indices, name=name) + return math_ops.cast(val, self._cast_dtype) + + def __getattr__(self, name): + return getattr(self._variable, name) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts this variable to a tensor.""" + if as_ref: + # This ValueError should not occur in practice since it is impossible to + # pass as_ref=True using public APIs. + raise ValueError('Cannot convert AutoCastVariable to a tensor if ' + 'as_ref=True is passed to convert_to_tensor') + if not self._should_cast(): + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._variable, dtype=dtype, name=name + ) + if dtype is not None and not dtype.is_compatible_with(self._cast_dtype): + raise ValueError( + 'Incompatible type conversion requested to type {!r} for ' + 'AutoCastVariable which is casted to type {!r}'.format( + dtype.name, self._cast_dtype.name)) + val = tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._variable, dtype=self._variable.dtype, name=name + ) + return math_ops.cast(val, self._cast_dtype) + + def _should_act_as_resource_variable(self): + """Pass resource_variable_ops.is_resource_variable check.""" + pass + + def __repr__(self): + if context.executing_eagerly() and not self._in_graph_mode: + repr_str = ("') + return repr_str.format( + v=self, np_repr=numpy_text(self.read_value(), is_repr=True)) + else: + repr_str = ("') + return repr_str.format(v=self) + + # Method delegations: We delegate the following methods to self._variable. + # Each of these methods simply calls the same method on self._variable. The + # base Variable raises NotImplementedError for most of these, so we must + # override them. + # + # We do not define the following methods from Variable for the following + # reasons: + # * 'count_up_to': This method only applies to int variables, which cannot + # be wrapped with an AutoCastVariable. + # * 'ref': Instead we inherit the definition from Variable. + # If we defined and delegated to Variable, the ref of an AutoCastVariable + # would be the same as the ref of the underlying variable, which would be + # strange as they are different Python objects. + + def set_shape(self, shape): + return self._variable.set_shape(self, shape) + + @property + def trainable(self): + return self._variable.trainable + + @property + def synchronization(self): + return self._variable.synchronization + + @property + def aggregation(self): + return self._variable.aggregation + + def eval(self, session=None): + return self._variable.eval(session) + + def initialized_value(self): + return self._variable.initialized_value() + + @property + def initial_value(self): + return self._variable.initial_value + + @property + def constraint(self): + return self._variable.constraint + + def _apply_assign_update(self, + update_fn, + value, + use_locking=None, + name=None, + read_value=True): + # TODO(b/146181571): This logic can be simplified once + # DistributedVariable.assign returns a DistributedVariable. Currently for + # MirroredStrategy, it returns a Mirrored value. + if ops.executing_eagerly_outside_functions(): + assign_op = update_fn(value, use_locking, name, False) + if read_value: + # We create a new AutoCastVariable with the same underlying tf.Variable. + # The new AutoCastVariable is identical except the 'op' attribute is + # defined. This matches the behavior of tf.Variable.assign. + var = create_autocast_variable(self._variable) + var._op = assign_op # pylint:disable=protected-access + return var + return assign_op + + # Fallback to wrapping the returned variable in graph mode if possible + assign_var = update_fn(value, use_locking, name, read_value) + if read_value and resource_variable_ops.is_resource_variable(assign_var): + return create_autocast_variable(assign_var) + return assign_var + + def _apply_update(self, update_fn, *args, **kwargs): + update_var = update_fn(*args, **kwargs) + if ops.executing_eagerly_outside_functions(): + return self + + # Fallback to wrapping the returned variable in graph mode if possible + if resource_variable_ops.is_resource_variable(update_var): + return create_autocast_variable(update_var) + return update_var + + def assign(self, value, use_locking=None, name=None, read_value=True): + return self._apply_assign_update(self._variable.assign, value, use_locking, + name, read_value) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + return self._apply_assign_update(self._variable.assign_add, delta, + use_locking, name, read_value) + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + return self._apply_assign_update(self._variable.assign_sub, delta, + use_locking, name, read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_sub, sparse_delta, + use_locking, name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_add, sparse_delta, + use_locking, name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_max, sparse_delta, + use_locking, name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_min, sparse_delta, + use_locking, name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_mul, sparse_delta, + use_locking, name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_div, sparse_delta, + use_locking, name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.scatter_update, sparse_delta, + use_locking, name) + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + return self._apply_update(self._variable.batch_scatter_update, sparse_delta, + use_locking, name) + + def scatter_nd_sub(self, indices, updates, name=None): + return self._apply_update(self._variable.scatter_nd_sub, indices, updates, + name) + + def scatter_nd_add(self, indices, updates, name=None): + return self._apply_update(self._variable.scatter_nd_add, indices, updates, + name) + + def scatter_nd_update(self, indices, updates, name=None): + return self._apply_update(self._variable.scatter_nd_update, indices, + updates, name) + + def load(self, value, session=None): + return self._variable.load(value, session) + + @property + def name(self): + return self._variable.name + + @property + def _shared_name(self): + return self._variable._shared_name # pylint:disable=protected-access + + @property + def initializer(self): + return self._variable.initializer + + @property + def device(self): + return self._variable.device + + @property + def op(self): + if self._op == 'delegate': + return self._variable.op + return self._op + + def _as_graph_element(self): + graph_element = self._variable._as_graph_element() # pylint:disable=protected-access + if graph_element is None: + return self._op + return graph_element + + @property + def graph(self): + return self._variable.graph + + @property + def shape(self): + return self._variable.shape + + def get_shape(self) -> tensor_shape.TensorShape: + return self._variable.get_shape() + + def _gather_saveables_for_checkpoint(self): + # By delegating this method to the wrapped variable, checkpoints with + # AutoCastVariables are identical to checkpoints with normal variables. + # Therefore models checkpointed with AutoCastVariables can be restored on + # models with normal variables, and vice versa. + return self._variable._gather_saveables_for_checkpoint() # pylint:disable=protected-access + + def _export_to_saved_model_graph(self, object_map, tensor_map, options, + **kwargs): + # By delegating this method to the wrapped variable, SavedModel with + # AutoCastVariables are identical to SavedModel with normal variables. + resource_list = self._variable._export_to_saved_model_graph( # pylint:disable=protected-access + object_map, tensor_map, options, **kwargs) + object_map[self] = object_map[self._variable] + return resource_list + + # TODO(reedwm): Maybe encode the fact the variable is an AutoCastVariable in + # to_proto(). + def to_proto(self, export_scope=None): + return self._variable.to_proto(export_scope) + + def from_proto(self, variable_def, import_scope=None): + return self._variable.from_proto(variable_def, import_scope) + + # Delegate the private attributes _handle_name and _initializer_op to + # self._variable. SavedModel sets these attributes when loading a model. For + # example, it sets _handle_name here: + # https://github.com/tensorflow/tensorflow/blob/db26bd574fa95b5bdd53c08463dd19407cc0297e/tensorflow/python/keras/saving/saved_model/load.py#L211 + # We need to expose these attributes on AutoCastVariable as well for + # SavedModel to work properly. + # TODO(reedwm/kathywu): Find a better way to support SavedModel. Exposing + # private attributes is hacky and difficult to maintain. + @property + def _handle_name(self): + return self._variable._handle_name # pylint: disable=protected-access + + @_handle_name.setter + def _handle_name(self, handle_name): + self._variable._handle_name = handle_name # pylint: disable=protected-access + + @property + def _initializer_op(self): + return self._variable._initializer_op # pylint: disable=protected-access + + @_initializer_op.setter + def _initializer_op(self, initializer_op): + self._variable._initializer_op = initializer_op # pylint: disable=protected-access + + # Operator overloads: + # Note we only overload operators that support floating-point types, as + # non-float variables cannot be wrapped with an AutoCastVariable. + # Also note: We call read_value() instead of value(), because value() causes + # gradients not to work properly when TPUStrategy is used: b/143380936 + + def __add__(self, o): + return self.read_value() + o + + def __radd__(self, o): + return o + self.read_value() + + def __sub__(self, o): + return self.read_value() - o + + def __rsub__(self, o): + return o - self.read_value() + + def __mul__(self, o): + return self.read_value() * o + + def __rmul__(self, o): + return o * self.read_value() + + def __truediv__(self, o): + return self.read_value() / o + + def __rtruediv__(self, o): + return o / self.read_value() + + def __floordiv__(self, o): + return self.read_value() // o + + def __rfloordiv__(self, o): + return o // self.read_value() + + def __mod__(self, o): + return self.read_value() % o + + def __rmod__(self, o): + return o % self.read_value() + + def __lt__(self, o): + return self.read_value() < o + + def __le__(self, o): + return self.read_value() <= o + + def __gt__(self, o): + return self.read_value() > o + + def __ge__(self, o): + return self.read_value() >= o + + def __getitem__(self, o): + return self.read_value()[o] + + def __pow__(self, o, modulo=None): + return pow(self.read_value(), o, modulo) + + def __rpow__(self, o): + return pow(o, self.read_value()) + + def __neg__(self): + return -self.read_value() # pylint: disable=invalid-unary-operand-type + + def __abs__(self): + return abs(self.read_value()) + + def __div__(self, o): + try: + return self.read_value().__div__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rdiv__(self, o): + try: + return self.read_value().__rdiv__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __matmul__(self, o): + try: + return self.read_value().__matmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rmatmul__(self, o): + try: + return self.read_value().__rmatmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + # pylint: enable=multiple-statements + + +tensor_conversion_registry.register_tensor_conversion_function( + AutoCastVariable, AutoCastVariable._dense_var_to_tensor) # pylint:disable=protected-access + + +def create_autocast_variable(variable): + """Creates an AutoCastVariable that wraps another variable. + + This typically just returns `AutoCastVariable(variable)`. But, if the variable + is a DistributedVariable or one of its subclasses, we instead dynamically + create a class that subclasses from both AutoCastVariable and + variable.__class__. This is so the returned variable will still pass + `isinstance(variable, variable.__class__)`, which is required for + DistributedVariables and its subclasses to work properly. + + Args: + variable: A floating-point resource variable to wrap. + + Returns: + An AutoCastVariable that wraps the variable. + """ + if not distributed_training_utils.is_distributed_variable(variable): + return AutoCastVariable(variable) + + class AutoCastDistributedVariable(AutoCastVariable, variable.__class__): + """An AutoCastVariable that also subclasses from variable.__class__. + + variable.__class__ is either a DistributedVariable or an + AggregatingVariable. + """ + + def __repr__(self): + + # pylint: disable=missing-format-attribute + return ('' + ).format(v=self) + # pylint: enable=missing-format-attribute + + return AutoCastDistributedVariable(variable) + + +class enable_auto_cast_variables(object): # pylint:disable=invalid-name + """Context manager which enables the autocasting of `AutoCastVariable`s. + + Under this context manager, `AutoCastVariable`s will be cast to `dtype` if + `dtype` is floating-point. Otherwise, `AutoCastVariable`s will not be cast. + """ + + __slots__ = ['_dtype', '_prev_dtype'] + + def __init__(self, dtype): + if dtype and not dtype.is_floating: + dtype = None + self._dtype = dtype + + def __enter__(self): + self._prev_dtype = getattr(_autocast_dtype, 'dtype', None) + _autocast_dtype.dtype = self._dtype + + def __exit__(self, type_arg, value_arg, traceback_arg): + _autocast_dtype.dtype = self._prev_dtype diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/device_compatibility_check.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/device_compatibility_check.py new file mode 100644 index 0000000000000000000000000000000000000000..06c72706ecda0431b14f1f075f32dd4852c318e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/device_compatibility_check.py @@ -0,0 +1,147 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains function to log if devices are compatible with mixed precision.""" + +import itertools + +from tensorflow.python.framework import config +from tensorflow.python.platform import tf_logging + + +_COMPAT_CHECK_PREFIX = 'Mixed precision compatibility check (mixed_float16): ' +_COMPAT_CHECK_OK_PREFIX = _COMPAT_CHECK_PREFIX + 'OK' +_COMPAT_CHECK_WARNING_PREFIX = _COMPAT_CHECK_PREFIX + 'WARNING' +_COMPAT_CHECK_WARNING_SUFFIX = ( + 'If you will use compatible GPU(s) not attached to this host, e.g. by ' + 'running a multi-worker model, you can ignore this warning. This message ' + 'will only be logged once') + + +def _dedup_strings(device_strs): + """Groups together consecutive identical strings. + + For example, given: + ['GPU 1', 'GPU 2', 'GPU 2', 'GPU 3', 'GPU 3', 'GPU 3'] + This function returns: + ['GPU 1', 'GPU 2 (x2)', 'GPU 3 (x3)'] + + Args: + device_strs: A list of strings, each representing a device. + + Returns: + A copy of the input, but identical consecutive strings are merged into a + single string. + """ + new_device_strs = [] + for device_str, vals in itertools.groupby(device_strs): + num = len(list(vals)) + if num == 1: + new_device_strs.append(device_str) + else: + new_device_strs.append('%s (x%d)' % (device_str, num)) + return new_device_strs + + +def _log_device_compatibility_check(policy_name, gpu_details_list): + """Logs a compatibility check if the devices support the policy. + + Currently only logs for the policy mixed_float16. + + Args: + policy_name: The name of the dtype policy. + gpu_details_list: A list of dicts, one dict per GPU. Each dict + is the device details for a GPU, as returned by + `tf.config.experimental.get_device_details()`. + """ + if policy_name != 'mixed_float16': + # TODO(b/145686977): Log if the policy is 'mixed_bfloat16'. This requires + # checking if a TPU is available. + return + supported_device_strs = [] + unsupported_device_strs = [] + for details in gpu_details_list: + name = details.get('device_name', 'Unknown GPU') + cc = details.get('compute_capability') + if cc: + device_str = '%s, compute capability %s.%s' % (name, cc[0], cc[1]) + if cc >= (7, 0): + supported_device_strs.append(device_str) + else: + unsupported_device_strs.append(device_str) + else: + unsupported_device_strs.append( + name + ', no compute capability (probably not an Nvidia GPU)') + + if unsupported_device_strs: + warning_str = _COMPAT_CHECK_WARNING_PREFIX + '\n' + if supported_device_strs: + warning_str += ('Some of your GPUs may run slowly with dtype policy ' + 'mixed_float16 because they do not all have compute ' + 'capability of at least 7.0. Your GPUs:\n') + elif len(unsupported_device_strs) == 1: + warning_str += ('Your GPU may run slowly with dtype policy mixed_float16 ' + 'because it does not have compute capability of at least ' + '7.0. Your GPU:\n') + else: + warning_str += ('Your GPUs may run slowly with dtype policy ' + 'mixed_float16 because they do not have compute ' + 'capability of at least 7.0. Your GPUs:\n') + for device_str in _dedup_strings(supported_device_strs + + unsupported_device_strs): + warning_str += ' ' + device_str + '\n' + warning_str += ('See https://developer.nvidia.com/cuda-gpus for a list of ' + 'GPUs and their compute capabilities.\n') + warning_str += _COMPAT_CHECK_WARNING_SUFFIX + tf_logging.warning(warning_str) + elif not supported_device_strs: + tf_logging.warning( + '%s\n' + 'The dtype policy mixed_float16 may run slowly because ' + 'this machine does not have a GPU. Only Nvidia GPUs with ' + 'compute capability of at least 7.0 run quickly with ' + 'mixed_float16.\n%s' % (_COMPAT_CHECK_WARNING_PREFIX, + _COMPAT_CHECK_WARNING_SUFFIX)) + elif len(supported_device_strs) == 1: + tf_logging.info('%s\n' + 'Your GPU will likely run quickly with dtype policy ' + 'mixed_float16 as it has compute capability of at least ' + '7.0. Your GPU: %s' % (_COMPAT_CHECK_OK_PREFIX, + supported_device_strs[0])) + else: + tf_logging.info('%s\n' + 'Your GPUs will likely run quickly with dtype policy ' + 'mixed_float16 as they all have compute capability of at ' + 'least 7.0' % _COMPAT_CHECK_OK_PREFIX) + + +_logged_compatibility_check = False + + +def log_device_compatibility_check(policy_name): + """Logs a compatibility check if the devices support the policy. + + Currently only logs for the policy mixed_float16. A log is shown only the + first time this function is called. + + Args: + policy_name: The name of the dtype policy. + """ + global _logged_compatibility_check + if _logged_compatibility_check: + return + _logged_compatibility_check = True + gpus = config.list_physical_devices('GPU') + gpu_details_list = [config.get_device_details(g) for g in gpus] + _log_device_compatibility_check(policy_name, gpu_details_list) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/get_layer_policy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/get_layer_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1bcee88d6114e4fdee66617c28a062ba2b461033 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/get_layer_policy.py @@ -0,0 +1,39 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains the get_layer_policy function. + +This is a separate file from policy.py to avoid a circular dependency. +get_layer_policy() relies on base_layer.py, itself which relies on policy.py. +""" + +from tensorflow.python.keras.engine import base_layer + + +def get_layer_policy(layer): + """Returns the dtype policy of a layer. + + Warning: This function is deprecated. Use + `tf.keras.layers.Layer.dtype_policy` instead. + + Args: + layer: A `tf.keras.layers.Layer`. + + Returns: + The `tf.keras.mixed_precision.Policy` of the layer. + """ + if not isinstance(layer, base_layer.Layer): + raise ValueError('get_policy can only be called on a layer, but got: %s' + % (layer,)) + return layer.dtype_policy diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0733dcc81394307ac61299d8c8e261392a69fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale.py @@ -0,0 +1,58 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains keras-specific LossScale functionality. + +This functions cannot be in the non-keras loss_scale.py file since they depend +on keras, and files outside of keras should not depend on files inside keras. +""" + +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.training.experimental import loss_scale as loss_scale_module + + +def serialize(loss_scale): + return generic_utils.serialize_keras_object(loss_scale) + + +def deserialize(config, custom_objects=None): + loss_scale_module_objects = { + 'FixedLossScale': loss_scale_module.FixedLossScale, + 'DynamicLossScale': loss_scale_module.DynamicLossScale, + } + + return generic_utils.deserialize_keras_object( + config, + module_objects=loss_scale_module_objects, + custom_objects=custom_objects, + printable_module_name='loss scale' + ) + + +def get(identifier): + """Get a loss scale object.""" + if isinstance(identifier, dict): + return deserialize(identifier) + + if isinstance(identifier, (int, float)): + return loss_scale_module.FixedLossScale(identifier) + if identifier == 'dynamic': + return loss_scale_module.DynamicLossScale() + if isinstance(identifier, loss_scale_module.LossScale): + return identifier + elif identifier is None: + return None + else: + raise ValueError('Could not interpret loss scale identifier: %s' % + identifier) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..b889501526649183d158122e9aa9d61c46f2f517 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py @@ -0,0 +1,1136 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains the loss scaling optimizer class.""" + +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import mirrored_strategy +from tensorflow.python.distribute import one_device_strategy +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend +from tensorflow.python.keras import optimizers +from tensorflow.python.keras.mixed_precision import loss_scale as keras_loss_scale_module +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.optimizer_v2 import utils as optimizer_utils +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import base_delegate +from tensorflow.python.training.experimental import loss_scale as loss_scale_module +from tensorflow.python.training.experimental import mixed_precision +from tensorflow.python.util import nest + + +class _UnwrapPreventer(object): + """Wrapper that DistributionStrategy will not unwrap. + + Typically, DistributionStrategy will unwrap values when going from a cross- + replica context to a replica context via `call_for_each_replica`. This class + is a wrapper that DistributionStrategy will not unwrap, so it can be used to + prevent it from unwrapping a value. + + TODO(reedwm): Find/implement a better way of preventing values from being + unwrapped by DistributionStrategy + """ + + __slots__ = ['value'] + + def __init__(self, value): + self.value = value + + +def _is_all_finite(grads): + """Returns a scalar boolean tensor indicating if all gradients are finite.""" + def raw_values(g): + return g.values if isinstance(g, indexed_slices.IndexedSlices) else g + + is_finite_per_grad = [ + math_ops.reduce_all(math_ops.is_finite(raw_values(g))) + for g in grads + if g is not None + ] + return math_ops.reduce_all(is_finite_per_grad) + + +def _op_in_graph_mode(tensor): + """Returns the tensor's op in graph mode, or the tensor in eager mode. + + This is useful because sometimes an op is needed in graph mode instead of a + tensor. In eager mode, there are no ops. + + Args: + tensor: A tensor. + + Returns: + The tensor's op in graph mode. The tensor in eager mode. + """ + if context.executing_eagerly(): + return tensor + return tensor.op + + +def _assign_if_finite(var, value): + """Assigns a value to a variable if the value is finite.""" + return cond.cond( + math_ops.is_finite(value), lambda: _op_in_graph_mode(var.assign(value)), + control_flow_ops.no_op) + + +class _DynamicLossScaleState(trackable.Trackable): + """The state of a dynamic loss scale.""" + + def __init__(self, + initial_loss_scale, + growth_steps, + multiplier): + """Creates the dynamic loss scale.""" + super(_DynamicLossScaleState, self).__init__() + self._initial_loss_scale = float(initial_loss_scale) + self._growth_steps = int(growth_steps) + self._multiplier = float(multiplier) + + self._weights = {} + self._current_loss_scale = self._add_weight( + name='current_loss_scale', + dtype=dtypes.float32, + initial_value=self._initial_loss_scale) + # The number of consecutive steps with finite gradients since the last + # nonfinite gradient or change in loss scale. The name is 'good_steps' for + # backwards compatibility with older checkpoints. + self._counter = self._add_weight( + name='good_steps', dtype=dtypes.int64, initial_value=0) + + def _add_weight(self, name, initial_value, dtype=None): + """Adds a weight to this loss scale. + + Args: + name: Variable name. + initial_value: The variable's initial value. + dtype: The type of the variable. + + Returns: + A variable. + + Raises: + RuntimeError: If a weight with `name` has already been added. + """ + variable = variable_v1.VariableV1( + initial_value=initial_value, + name=name, + dtype=dtype, + trainable=False, + use_resource=True, + synchronization=variables.VariableSynchronization.AUTO, + # Set aggregation to NONE, as loss scaling variables should never be + # aggregated. + aggregation=variables.VariableAggregation.NONE) + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + + key = (name, graph_key) + self._weights[key] = variable + self._handle_deferred_dependencies(name=name, trackable=variable) + backend.track_variable(variable) + return variable + + def _trackable_children(self, + save_type=trackable.SaveType.CHECKPOINT, + **kwargs): + """From Trackable. Gather graph-specific weights to save.""" + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + weights = {} + for (name, g), v in sorted(self._weights.items(), key=lambda i: i[0][0]): + if g == graph_key: + weights[name] = v + weights.update( + super(_DynamicLossScaleState, + self)._trackable_children(save_type, **kwargs)) + return weights + + def _lookup_dependency(self, name): + """From Trackable. Find a weight in the current graph.""" + unconditional = super(_DynamicLossScaleState, self)._lookup_dependency(name) + if unconditional is not None: + return unconditional + if context.executing_eagerly(): + graph_key = None + else: + graph = ops.get_default_graph() + graph_key = graph._graph_key # pylint: disable=protected-access + return self._weights.get((name, graph_key), None) + + @property + def initial_loss_scale(self): + return self._initial_loss_scale + + @property + def growth_steps(self): + return self._growth_steps + + @property + def multiplier(self): + return self._multiplier + + @property + def current_loss_scale(self): + """Returns the current loss scale as a float32 `tf.Variable`.""" + return self._current_loss_scale + + @property + def counter(self): + """Returns the counter as a float32 `tf.Variable`.""" + return self._counter + + def __call__(self): + """Returns the current loss scale as a scalar `float32` tensor.""" + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._current_loss_scale + ) + + def update(self, grads): + """Updates the value of the loss scale. + + Args: + grads: A nested structure of unscaled gradients, each which is an + all-reduced gradient of the loss with respect to a weight. + + Returns: + update_op: In eager mode, None. In graph mode, an op to update the loss + scale. + should_apply_gradients: Either a bool or a scalar boolean tensor. If + False, the caller should skip applying `grads` to the variables this + step. + """ + grads = nest.flatten(grads) + if distribute_lib.has_strategy( + ) and distribute_lib.in_cross_replica_context(): + distribution = distribute_lib.get_strategy() + is_finite_per_replica = distribution.extended.call_for_each_replica( + _is_all_finite, args=(grads,)) + # Each replica computed the same `is_finite` value, since `grads` is + # all-reduced across replicas. Arbitrarily take `is_finite` from the first + # replica. + is_finite = ( + distribution.experimental_local_results(is_finite_per_replica)[0]) + else: + is_finite = _is_all_finite(grads) + + def update_if_finite_grads(): + """Update assuming the gradients are finite.""" + + def incr_loss_scale(): + new_loss_scale = self.current_loss_scale * self.multiplier + return control_flow_ops.group( + _assign_if_finite(self.current_loss_scale, new_loss_scale), + self.counter.assign(0)) + + return cond.cond( + self.counter + 1 >= self.growth_steps, + incr_loss_scale, + lambda: _op_in_graph_mode(self.counter.assign_add(1))) + + def update_if_not_finite_grads(): + """Update assuming the gradients are nonfinite.""" + + new_loss_scale = math_ops.maximum( + self.current_loss_scale / self.multiplier, 1) + return control_flow_ops.group( + self.counter.assign(0), + self.current_loss_scale.assign(new_loss_scale)) + + update_op = cond.cond(is_finite, update_if_finite_grads, + update_if_not_finite_grads) + should_apply_gradients = is_finite + return update_op, should_apply_gradients + + +# See LossScaleOptimizer docstring for why this is so big +_DEFAULT_INITIAL_SCALE = 2 ** 15 +_DEFAULT_GROWTH_STEPS = 2000 + + +# pylint: disable=g-classes-have-attributes +class LossScaleOptimizer(base_delegate.DelegatingTrackableMixin, + optimizer_v2.OptimizerV2): + """An optimizer that applies loss scaling to prevent numeric underflow. + + Loss scaling is a technique to prevent numeric underflow in intermediate + gradients when float16 is used. To prevent underflow, the loss is multiplied + (or "scaled") by a certain factor called the "loss scale", which causes + intermediate gradients to be scaled by the loss scale as well. The final + gradients are divided (or "unscaled") by the loss scale to bring them back to + their original value. + + `LossScaleOptimizer` wraps another optimizer and applies loss scaling to it. + By default, the loss scale is dynamically updated over time so you do not have + to choose the loss scale. The `minimize` method automatically scales the loss, + unscales the gradients, and updates the loss scale so all you have to do is + wrap your optimizer with a `LossScaleOptimizer` if you use `minimize`. For + example: + + >>> opt = tf.keras.optimizers.SGD(0.25) + >>> opt = tf.keras.mixed_precision.LossScaleOptimizer(opt) + >>> var = tf.Variable(1.) + >>> loss_fn = lambda: var ** 2 + >>> # 'minimize' applies loss scaling and updates the loss sale. + >>> opt.minimize(loss_fn, var_list=var) + >>> var.numpy() + 0.5 + + If a `tf.GradientTape` is used to compute gradients instead of `minimize`, you + must scale the loss and gradients manually. This can be done with the + `LossScaleOptimizer.get_scaled_loss` and + `LossScaleOptimizer.get_unscaled_gradients` methods. For example: + + >>> with tf.GradientTape() as tape: + ... loss = loss_fn() + ... scaled_loss = opt.get_scaled_loss(loss) + >>> scaled_grad = tape.gradient(scaled_loss, var) + >>> (grad,) = opt.get_unscaled_gradients([scaled_grad]) + >>> opt.apply_gradients([(grad, var)]) # Loss scale is updated here + >>> var.numpy() + 0.25 + + Warning: If you forget to call `get_scaled_loss` or `get_unscaled_gradients` + (or both) when using a `tf.GradientTape`, the model will likely converge to a + worse quality. Please make sure you call each function exactly once. + + When mixed precision with float16 is used, there is typically no risk of + underflow affecting model quality if loss scaling is properly used. See + [the mixed precision guide]( + https://www.tensorflow.org/guide/keras/mixed_precision) for more information + on how to use mixed precision. + + Args: + inner_optimizer: The `tf.keras.optimizers.Optimizer` instance to wrap. + dynamic: Bool indicating whether dynamic loss scaling is used. Defaults to + True. If True, the loss scale will be dynamically updated over time using + an algorithm that keeps the loss scale at approximately its optimal value. + If False, a single fixed loss scale is used and `initial_scale` must be + specified, which is used as the loss scale. Recommended to keep as True, + as choosing a fixed loss scale can be tricky. Currently, there is a small + performance overhead to dynamic loss scaling compared to fixed loss + scaling. + initial_scale: The initial loss scale. If `dynamic` is True, this defaults + to `2 ** 15`. If `dynamic` is False, this must be specified and acts as + the sole loss scale, as the loss scale does not change over time. When + dynamic loss scaling is used, is better for this to be a very high number, + because a loss scale that is too high gets lowered far more quickly than a + loss scale that is too low gets raised. + dynamic_growth_steps: With dynamic loss scaling, every + `dynamic_growth_steps` steps with finite gradients, the loss scale is + doubled. Defaults to 2000. If a nonfinite gradient is encountered, the + count is reset back to zero, gradients are skipped that step, and the loss + scale is halved. The count can be queried with + `LossScaleOptimizer.dynamic_counter`. This argument can only be specified + if `dynamic` is True. + + `LossScaleOptimizer` will occasionally skip applying gradients to the + variables, in which case the trainable variables will not change that step. + This is done because the dynamic loss scale will sometimes be raised too + high, causing overflow in the gradients. Typically, the first 2 to 15 steps of + the model are skipped as the initial loss scale is very high, but afterwards + steps will only be skipped on average 0.05% of the time (the fraction of steps + skipped is `1 / dynamic_growth_steps`). + + `LossScaleOptimizer` delegates all public `Optimizer` methods to the inner + optimizer. Additionally, in methods `minimize` and `get_gradients`, it scales + the loss and unscales the gradients. In methods `minimize` and + `apply_gradients`, it additionally updates the loss scale and skips applying + gradients if any gradient has a nonfinite value. + + ### Hyperparameters + + Hyperparameters can be accessed and set on the LossScaleOptimizer, which will + be delegated to the wrapped optimizer. + + >>> opt = tf.keras.optimizers.Adam(beta_1=0.8, epsilon=1e-5) + >>> opt = tf.keras.mixed_precision.LossScaleOptimizer(opt) + >>> opt.beta_1 # Equivalent to `opt.inner_optimizer.beta_1` + 0.8 + >>> opt.beta_1 = 0.7 # Equivalent to `opt.inner_optimizer.beta_1 = 0.7` + >>> opt.beta_1 + 0.7 + >>> opt.inner_optimizer.beta_1 + 0.7 + + However, accessing or setting non-hyperparameters is not delegated to the + LossScaleOptimizer. In an Adam optimizer, `beta_1` is a hyperparameter but + `epsilon` is not, as the Adam optimizer only calls `Optimizer._set_hyper` on + `beta_1`. + + >>> opt.inner_optimizer.epsilon + 1e-5 + >>> opt.epsilon + Traceback (most recent call last): + ... + AttributeError: 'LossScaleOptimizer' object has no attribute 'epsilon' + >>> opt.epsilon = 1e-4 # This does NOT set epsilon on `opt.inner_optimizer` + >>> opt.inner_optimizer.epsilon + >>> 1e-5 + + In the above example, despite epsilon being set on the LossScaleOptimizer, the + old epsilon value will still be used when training as epsilon was not set on + the inner optimizer. + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, inner_optimizer, dynamic=True, initial_scale=None, + dynamic_growth_steps=None): + if not isinstance(inner_optimizer, optimizer_v2.OptimizerV2): + raise TypeError('"inner_optimizer" must be an instance of OptimizerV2, ' + 'but got: %s' % inner_optimizer) + if not isinstance(dynamic, bool): + # Catch errors if a user incorrectly passes a string or float to the + # second argument argument, as this is commonly done for + # LossScaleOptimizerV1. + raise TypeError('"dynamic" argument to LossScaleOptimizer.__init__ must ' + 'be a bool, but got: %r' % (dynamic,)) + if isinstance(inner_optimizer, LossScaleOptimizer): + raise TypeError('LossScaleOptimizer cannot wrap another ' + 'LossScaleOptimizer, but got: %s' % (inner_optimizer,)) + self._raise_if_strategy_unsupported() + if getattr(inner_optimizer, '_is_wrapped_by_loss_scale_optimizer', False): + # TODO(reedwm): Maybe support this. The difficulty is that LSO has the + # same checkpoint format as the inner optimizer, so multiple LSOs wrapping + # the same optimizer causes the checkpointing logic to become confused. + raise ValueError('"inner_optimizer" is already wrapped by a ' + 'LossScaleOptimizer. An optimizer can only be wrapped ' + 'by a single LossScaleOptimizer') + self._optimizer = inner_optimizer + self._optimizer._is_wrapped_by_loss_scale_optimizer = True + + # We don't call super().__init__, since we do not want to call OptimizerV2's + # constructor. + base_delegate.DelegatingTrackableMixin.__init__(self, self._optimizer) + + if dynamic: + if initial_scale is None: + initial_scale = _DEFAULT_INITIAL_SCALE + if dynamic_growth_steps is None: + dynamic_growth_steps = _DEFAULT_GROWTH_STEPS + self._loss_scale = _DynamicLossScaleState( + initial_scale, dynamic_growth_steps, multiplier=2) + self._track_trackable(self._loss_scale, 'loss_scale') + else: + if initial_scale is None: + raise ValueError('"initial_scale" must be specified if "dynamic" is ' + 'False') + self._loss_scale = float(initial_scale) + if dynamic_growth_steps is not None: + raise ValueError('"dynamic_growth_steps" must be None if "dynamic" ' + 'is False, but got: %s' % (dynamic_growth_steps,)) + + # To support restoring TensorFlow 2.2 checkpoints. + self._track_trackable(FakeOptimizerForRestoration(self._optimizer), + 'base_optimizer') + + @property + def dynamic(self): + """Bool indicating whether dynamic loss scaling is used.""" + return isinstance(self._loss_scale, _DynamicLossScaleState) + + @property + def loss_scale(self): + """The current loss scale as a float32 scalar tensor.""" + if isinstance(self._loss_scale, _DynamicLossScaleState): + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._loss_scale.current_loss_scale + ) + else: + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._loss_scale + ) + + @property + def dynamic_counter(self): + """The number of steps since the loss scale was last increased or decreased. + + This is None if `LossScaleOptimizer.dynamic` is False. + + The counter is incremented every step. Once it reaches + `LossScaleOptimizer.dynamic_growth_steps`, the loss scale will be doubled + and the counter will be reset back to zero. If nonfinite gradients are + encountered, the loss scale will be halved and the counter will be reset + back to zero. + """ + if isinstance(self._loss_scale, _DynamicLossScaleState): + return self._loss_scale.counter + else: + return None + + @property + def initial_scale(self): + """The initial loss scale. + + If `LossScaleOptimizer.dynamic` is False, this is the same number as + `LossScaleOptimizer.loss_scale`, as the loss scale never changes. + """ + if isinstance(self._loss_scale, _DynamicLossScaleState): + return self._loss_scale.initial_loss_scale + else: + return self._loss_scale + + @property + def dynamic_growth_steps(self): + """The number of steps it takes to increase the loss scale. + + This is None if `LossScaleOptimizer.dynamic` is False. + + Every `dynamic_growth_steps` consecutive steps with finite gradients, the + loss scale is increased. + """ + if isinstance(self._loss_scale, _DynamicLossScaleState): + return self._loss_scale.growth_steps + else: + return None + + @property + def inner_optimizer(self): + """The optimizer that this LossScaleOptimizer is wrapping.""" + return self._optimizer + + def get_scaled_loss(self, loss): + """Scales the loss by the loss scale. + + This method is only needed if you compute gradients manually, e.g. with + `tf.GradientTape`. In that case, call this method to scale the loss before + passing the loss to `tf.GradientTape`. If you use + `LossScaleOptimizer.minimize` or `LossScaleOptimizer.get_gradients`, loss + scaling is automatically applied and this method is unneeded. + + If this method is called, `get_unscaled_gradients` should also be called. + See the `tf.keras.mixed_precision.LossScaleOptimizer` doc for + an example. + + Args: + loss: The loss, which will be multiplied by the loss scale. Can either be + a tensor or a callable returning a tensor. + + Returns: + `loss` multiplied by `LossScaleOptimizer.loss_scale`. + """ + if callable(loss): + def new_loss(): + loss_val = loss() + return loss_val * math_ops.cast(self.loss_scale, loss_val.dtype) + return new_loss + else: + return loss * math_ops.cast(self.loss_scale, loss.dtype) + + def get_unscaled_gradients(self, grads): + """Unscales the gradients by the loss scale. + + This method is only needed if you compute gradients manually, e.g. with + `tf.GradientTape`. In that case, call this method to unscale the gradients + after computing them with `tf.GradientTape`. If you use + `LossScaleOptimizer.minimize` or `LossScaleOptimizer.get_gradients`, loss + scaling is automatically applied and this method is unneeded. + + If this method is called, `get_scaled_loss` should also be called. See + the `tf.keras.mixed_precision.LossScaleOptimizer` doc for an + example. + + Args: + grads: A list of tensors, each which will be divided by the loss scale. + Can have None values, which are ignored. + + Returns: + A new list the same size as `grads`, where every non-None value in `grads` + is divided by `LossScaleOptimizer.loss_scale`. + """ + loss_scale_reciprocal = 1. / self.loss_scale + return [ + _multiply_gradient(g, loss_scale_reciprocal) if g is not None else None + for g in grads + ] + + def _compute_gradients(self, loss, var_list, grad_loss=None, tape=None): + tape = backprop.GradientTape() if tape is None else tape + with tape: + loss = self.get_scaled_loss(loss) + grads_and_vars = self._optimizer._compute_gradients( # pylint: disable=protected-access + loss, + var_list, + grad_loss, + tape=tape) + grads = [g for g, _ in grads_and_vars] + weights = [v for _, v in grads_and_vars] + unscaled_grads = self.get_unscaled_gradients(grads) + return list(zip(unscaled_grads, weights)) + + def get_gradients(self, loss, params): + loss = self.get_scaled_loss(loss) + grads = self._optimizer.get_gradients(loss, params) + return self.get_unscaled_gradients(grads) + + def _create_all_weights(self, var_list): + self._optimizer._create_all_weights(var_list) # pylint: disable=protected-access + + def apply_gradients(self, + grads_and_vars, + name=None, + experimental_aggregate_gradients=True): + if distribute_lib.in_cross_replica_context(): + raise ValueError('apply_gradients() must be called in a replica context.') + # We check for the strategy here despite already checking in the constructor + # as frequently the optimizer is created outside the strategy's scope. + self._raise_if_strategy_unsupported() + + grads_and_vars = optimizer_utils.filter_empty_gradients(grads_and_vars) + if experimental_aggregate_gradients: + # We must aggregate the gradients here instead of in + # self.optimizer.apply_gradients, so that any NaN or Inf gradients are + # propogated to each replica. If any replica has a NaN or Inf gradient, + # they must all have a NaN or Inf gradient so that they all skip the step. + # pylint: disable=protected-access + grads_and_vars = self._optimizer._transform_unaggregated_gradients( + grads_and_vars) + grads_and_vars = self._optimizer._aggregate_gradients(grads_and_vars) + # pylint: enable=protected-access + + grads_and_vars = tuple(grads_and_vars) + grads = [g for g, _ in grads_and_vars] + # We do not want DistributionStrategy to unwrap any MirroredVariables in + # grads_and_vars, because even in a replica context, the wrapped + # optimizer expects mirrored variables. So we wrap the variables with an + # _UnwrapPreventer, preventing DistributionStrategy from unwrapping the + # MirroredVariables. + wrapped_vars = _UnwrapPreventer([v for _, v in grads_and_vars]) + + def do_not_apply_fn(): + # Normally self._optimizer.iterations is incremented in + # self._optimizer.apply_gradients(). Since that is not called in this + # branch, we increment it here instead. + return self._optimizer.iterations.assign_add(1, read_value=False) + + def _if_should_apply_grads(grads): + if isinstance(self._loss_scale, _DynamicLossScaleState): + return self._loss_scale.update(grads) + else: + return (control_flow_ops.no_op(), True) + + if optimizer_utils.strategy_supports_no_merge_call(): + loss_scale_update_op, should_apply_grads = _if_should_apply_grads(grads) + def apply_fn(): + return self._apply_gradients(grads, wrapped_vars, name) + + maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn, + do_not_apply_fn) + return control_flow_ops.group(maybe_apply_op, loss_scale_update_op) + + else: + + def _apply_gradients_cross_replica(distribution, grads, wrapped_vars, + name): + loss_scale_update_op, should_apply_grads = _if_should_apply_grads(grads) + + def apply_fn(): + return distribution.extended.call_for_each_replica( + self._apply_gradients, + args=(grads, wrapped_vars, name)) + + # Note: We must call this cond() in a cross-replica context. + # DistributionStrategy does not support having a cond in a replica + # context with a branch that calls `merge_call`, and + # self._optimizer.apply_gradients calls `merge_call`. + maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn, + do_not_apply_fn) + return control_flow_ops.group(maybe_apply_op, loss_scale_update_op) + return distribute_lib.get_replica_context().merge_call( + _apply_gradients_cross_replica, + args=(grads, wrapped_vars, name)) + + def _apply_gradients(self, grads, wrapped_vars, name): + # Pass experimental_aggregate_gradients=False since LossScaleOptimizer + # already aggregated the gradients. + # TODO(reedwm): This will raise a fairly cryptic error message if + # self._optimizer.apply_gradients does not take + # experimental_aggregate_gradients. + return self._optimizer.apply_gradients( + list(zip(grads, wrapped_vars.value)), name, + experimental_aggregate_gradients=False) + + def get_config(self): + serialized_optimizer = optimizers.serialize(self._optimizer) + return { + 'inner_optimizer': serialized_optimizer, + 'dynamic': self.dynamic, + 'initial_scale': self.initial_scale, + 'dynamic_growth_steps': self.dynamic_growth_steps, + } + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() # Make a copy, since we mutate config + if 'loss_scale' in config: + # If loss_scale is in config, we assume we are deserializing a + # LossScaleOptimizer from TF 2.3 or below. We convert the config so it + # can be deserialized in the current LossScaleOptimizer. + loss_scale = keras_loss_scale_module.deserialize( + config.pop('loss_scale')) + if isinstance(loss_scale, loss_scale_module.FixedLossScale): + config['dynamic'] = False + config['initial_scale'] = loss_scale._loss_scale_value # pylint: disable=protected-access + elif isinstance(loss_scale, loss_scale_module.DynamicLossScale): + config['dynamic'] = True + config['initial_scale'] = loss_scale.initial_loss_scale + config['dynamic_growth_steps'] = loss_scale.increment_period + if loss_scale.multiplier != 2: + raise ValueError('Cannot deserialize LossScaleOptimizer with a ' + 'DynamicLossScale whose multiplier is not 2. Got ' + 'DynamicLossScale: %s' % (loss_scale,)) + else: + raise ValueError( + 'Serialized LossScaleOptimizers with a LossScale that is neither a ' + 'FixedLossScale nor a DynamicLossScale can no longer be ' + 'deserialized') + config['inner_optimizer'] = config.pop('optimizer') + config['inner_optimizer'] = optimizers.deserialize( + config['inner_optimizer'], custom_objects=custom_objects) + return cls(**config) + + def _raise_if_strategy_unsupported(self): + if not strategy_supports_loss_scaling(): + strategy = distribute_lib.get_strategy() + if isinstance(strategy, + (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1, + tpu_strategy.TPUStrategyV2)): + raise ValueError( + 'Loss scaling is not supported with TPUStrategy. Loss scaling is ' + 'unnecessary with TPUs, since they support bfloat16 instead of ' + 'float16 and bfloat16 does not require loss scaling. You should ' + 'remove the use of the LossScaleOptimizer when TPUs are used.') + else: + raise ValueError('Loss scaling is not supported with the ' + 'tf.distribute.Strategy: %s. Try using a different ' + 'Strategy, e.g. a MirroredStrategy' % + strategy.__class__.__name__) + + # Delegations: We delegate most OptimizerV2 methods to the wrapped optimizer + # below. + + @property + def iterations(self): + return self._optimizer.iterations + + @iterations.setter + def iterations(self, variable): + self._optimizer.iterations = variable + + def get_slot_names(self): + return self._optimizer.get_slot_names() + + def variables(self): + return self._optimizer.variables() + + @property + def weights(self): + return self._optimizer.weights + + def get_weights(self): + return self._optimizer.get_weights() + + def set_weights(self, weights): + return self._optimizer.set_weights(weights) + + @property + def clipnorm(self): + return self._optimizer.clipnorm + + @clipnorm.setter + def clipnorm(self, val): + self._optimizer.clipnorm = val + + @property + def global_clipnorm(self): + return self._optimizer.global_clipnorm + + @global_clipnorm.setter + def global_clipnorm(self, val): + self._optimizer.global_clipnorm = val + + @property + def clipvalue(self): + return self._optimizer.clipvalue + + @clipvalue.setter + def clipvalue(self, val): + self._optimizer.clipvalue = val + + def _aggregate_gradients(self, grads_and_vars): + return self._optimizer._aggregate_gradients(grads_and_vars) # pylint: disable=protected-access + + def _restore_slot_variable(self, slot_name, variable, slot_variable): + return self._optimizer._restore_slot_variable(slot_name, variable, # pylint: disable=protected-access + slot_variable) + + def _create_or_restore_slot_variable(self, slot_variable_position, slot_name, + variable): + return self._optimizer._create_or_restore_slot_variable( # pylint: disable=protected-access + slot_variable_position, slot_name, variable) + + def get_slot(self, var, slot_name): + return self._optimizer.get_slot(var, slot_name) + + def add_slot(self, var, slot_name, initializer='zeros'): + return self._optimizer.add_slot(var, slot_name, initializer) + + def __getattribute__(self, name): + try: + return object.__getattribute__(self, name) + except AttributeError as e: + if name == '_optimizer' or name == '_hyper': + # Avoid infinite recursion + raise e + + # Delegate hyperparameter accesses to inner optimizer. + if name == 'lr': + name = 'learning_rate' + if name in self._optimizer._hyper: + return self._optimizer._get_hyper(name) + raise e + + def __dir__(self): + result = set(super(LossScaleOptimizer, self).__dir__()) + if '_optimizer' in result: + result |= self._optimizer._hyper.keys() + if 'learning_rate' in self._optimizer._hyper.keys(): + result.add('lr') + return list(result) + + def __setattr__(self, name, value): + if name == 'lr': + name = 'learning_rate' + # Delegate setting hyperparameter to inner optimizer if the attribute does + # not exist on the LossScaleOptimizer + try: + # We cannot check for the 'iterations' attribute as it cannot be set after + # it is accessed. + if name != 'iterations': + object.__getattribute__(self, name) + has_attribute = True + except AttributeError: + has_attribute = False + if (name != '_optimizer' and name in self._optimizer._hyper + and not has_attribute): + self._optimizer._set_hyper(name, value) + else: + super(LossScaleOptimizer, self).__setattr__(name, value) + + # Explicitly delegate learning_rate. Normally hyperparameters are delegated in + # __getattribute__, but if a hyperparameter is not in self._optimizer._hyper + # (e.g. because self._optimizer itself wraps another optimizer), then it won't + # be delegated. Since learning_rate is a very commonly accessed + # hyperparameter, we delegate it here. + @property + def learning_rate(self): + return self._optimizer.learning_rate + + @learning_rate.setter + def learning_rate(self, value): + self._optimizer.learning_rate = value + + @property + def lr(self): + return self._optimizer.learning_rate + + @lr.setter + def lr(self, value): + self._optimizer.lr = value + + # We do not override some OptimizerV2 methods. For each, we describe why we do + # not delegate them to self._optimizer: + # * get_updates: get_updates() calls get_gradients(). Since we override + # get_gradients(), we cannot delegate get_updates() to self._optimizer, + # otherwise the overridden get_gradients() method would not be called. + # Luckily, get_updates() does not access any OptimizerV2 fields, so + # inheriting the OptimizerV2 version works fine. + # * minimize: We don't delegate for a similar as get_updates(): it calls + # both self._compute_gradients() and self.apply_gradients(), and both need + # to have the LossScaleOptimizer version called. + + # TODO(reedwm): Maybe throw an error if mixed precision is used without this + # optimizer being used. + + +class LossScaleOptimizerV1(LossScaleOptimizer): + """An deprecated optimizer that applies loss scaling. + + Warning: This class is deprecated and will be removed in a future version of + TensorFlow. Please use the non-experimental class + `tf.keras.mixed_precision.LossScaleOptimizer` instead. + + This class is identical to the non-experimental + `keras.mixed_precision.LossScaleOptimizer` except its constructor takes + different arguments. For this class (the experimental version), the + constructor takes a `loss_scale` argument. For the non-experimental class, + the constructor encodes the loss scaling information in multiple arguments. + Note that unlike this class, the non-experimental class does not accept a + `tf.compat.v1.mixed_precision.LossScale`, which is deprecated. + + If you currently use this class, you should switch to the non-experimental + `tf.keras.mixed_precision.LossScaleOptimizer` instead. We show several + examples of converting the use of the experimental class to the equivalent + non-experimental class. + + >>> # In all of the examples below, `opt1` and `opt2` are identical + >>> opt1 = tf.keras.mixed_precision.experimental.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), loss_scale='dynamic') + >>> opt2 = tf.keras.mixed_precision.LossScaleOptimizer( + ... tf.keras.optimizers.SGD()) + >>> assert opt1.get_config() == opt2.get_config() + + >>> opt1 = tf.keras.mixed_precision.experimental.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), loss_scale=123) + >>> # dynamic=False indicates to use fixed loss scaling. initial_scale=123 + >>> # refers to the initial loss scale, which is the single fixed loss scale + >>> # when dynamic=False. + >>> opt2 = tf.keras.mixed_precision.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), dynamic=False, initial_scale=123) + >>> assert opt1.get_config() == opt2.get_config() + + >>> loss_scale = tf.compat.v1.mixed_precision.experimental.DynamicLossScale( + ... initial_loss_scale=2048, increment_period=500) + >>> opt1 = tf.keras.mixed_precision.experimental.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), loss_scale=loss_scale) + >>> opt2 = tf.keras.mixed_precision.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), initial_scale=2048, + ... dynamic_growth_steps=500) + >>> assert opt1.get_config() == opt2.get_config() + + Make sure to also switch from this class to the non-experimental class in + isinstance checks, if you have any. If you do not do this, your model may run + into hard-to-debug issues, as the experimental `LossScaleOptimizer` subclasses + the non-experimental `LossScaleOptimizer`, but not vice versa. It is safe to + switch isinstance checks to the non-experimental `LossScaleOptimizer` even + before using the non-experimental `LossScaleOptimizer`. + + >>> opt1 = tf.keras.mixed_precision.experimental.LossScaleOptimizer( + ... tf.keras.optimizers.SGD(), loss_scale='dynamic') + >>> # The experimental class subclasses the non-experimental class + >>> isinstance(opt1, tf.keras.mixed_precision.LossScaleOptimizer) + True + >>> opt2 = tf.keras.mixed_precision.LossScaleOptimizer( + ... tf.keras.optimizers.SGD()) + >>> # The non-experimental class does NOT subclass the experimental class. + >>> isinstance(opt2, tf.keras.mixed_precision.experimental.LossScaleOptimizer) + False + + Args: + optimizer: The Optimizer instance to wrap. + loss_scale: The loss scale to scale the loss and gradients. This can + either be an int/float to use a fixed loss scale, the string "dynamic" + to use dynamic loss scaling, or an instance of a LossScale. The string + "dynamic" equivalent to passing `DynamicLossScale()`, and passing an + int/float is equivalent to passing a FixedLossScale with the given loss + scale. If a DynamicLossScale is passed, DynamicLossScale.multiplier must + be 2 (the default). + """ + + def __init__(self, optimizer, loss_scale): + warn_msg_prefix = ( + 'tf.keras.mixed_precision.experimental.LossScaleOptimizer is ' + 'deprecated. Please use tf.keras.mixed_precision.LossScaleOptimizer ' + 'instead. ') + + if isinstance(loss_scale, dict): + loss_scale = keras_loss_scale_module.deserialize(loss_scale) + + if isinstance(loss_scale, (int, float)): + tf_logging.warning( + warn_msg_prefix + 'For example:\n' + ' opt = tf.keras.mixed_precision.LossScaleOptimizer(' + 'opt, dynamic=False, initial_scale={})'.format(loss_scale)) + super(LossScaleOptimizerV1, self).__init__(optimizer, dynamic=False, + initial_scale=loss_scale) + elif isinstance(loss_scale, loss_scale_module.FixedLossScale): + ls_val = loss_scale._loss_scale_value # pylint: disable=protected-access + tf_logging.warning( + warn_msg_prefix + 'For example:\n' + ' opt = tf.keras.mixed_precision.LossScaleOptimizer(' + 'opt, dynamic=False, initial_scale={})'.format(ls_val)) + super(LossScaleOptimizerV1, self).__init__(optimizer, dynamic=False, + initial_scale=ls_val) + elif loss_scale == 'dynamic': + tf_logging.warning( + warn_msg_prefix + 'For example:\n' + ' opt = tf.keras.mixed_precision.LossScaleOptimizer(' + 'opt)') + super(LossScaleOptimizerV1, self).__init__(optimizer) + elif isinstance(loss_scale, loss_scale_module.DynamicLossScale): + kwargs = {} + extra_arguments = '' + if loss_scale.initial_loss_scale != _DEFAULT_INITIAL_SCALE: + kwargs['initial_scale'] = loss_scale.initial_loss_scale + extra_arguments += (', initial_scale=%s' % + loss_scale.initial_loss_scale) + if loss_scale.increment_period != _DEFAULT_GROWTH_STEPS: + kwargs['dynamic_growth_steps'] = loss_scale.increment_period + extra_arguments += (', dynamic_growth_steps=%s' % + loss_scale.increment_period) + if loss_scale.multiplier != 2: + raise ValueError('When passing a DynamicLossScale to "loss_scale", ' + 'DynamicLossScale.multiplier must be 2. Got: %s' + % (loss_scale,)) + tf_logging.warning( + warn_msg_prefix + + 'Note that the non-experimental LossScaleOptimizer does not take a ' + 'DynamicLossScale but instead takes the dynamic configuration ' + 'directly in the constructor. For example:\n' + ' opt = tf.keras.mixed_precision.LossScaleOptimizer(' + 'opt{})\n'.format(extra_arguments)) + super(LossScaleOptimizerV1, self).__init__(optimizer, **kwargs) + elif isinstance(loss_scale, loss_scale_module.LossScale): + raise TypeError('Passing a LossScale that is not a FixedLossScale or a ' + 'DynamicLossScale is no longer supported. Got: {}' + .format(loss_scale)) + else: + raise ValueError('Invalid value passed to loss_scale. loss_scale ' + 'must be the string "dynamic" (recommended), an int, ' + 'a float, a FixedLossScale, or a DynamicLossScale. Got ' + 'value: {}'.format(loss_scale)) + + @classmethod + def from_config(cls, config, custom_objects=None): + config = config.copy() # Make a copy, since we mutate config + + # If loss_scale is in config, we assume we are deserializing a + # LossScaleOptimizer from TF 2.3 or below. Otherwise, we assume we are + # deserializing a LossScaleOptimizer from TF 2.4 or above. + if 'loss_scale' in config: + config['loss_scale'] = keras_loss_scale_module.deserialize( + config['loss_scale']) + if (isinstance(config['loss_scale'], loss_scale_module.DynamicLossScale) + and config['loss_scale'].multiplier != 2): + raise ValueError('Cannot deserialize LossScaleOptimizer with a ' + 'DynamicLossScale whose multiplier is not 2. Got ' + 'DynamicLossScale: %s' % (config['loss_scale'],)) + config['optimizer'] = optimizers.deserialize( + config['optimizer'], custom_objects=custom_objects) + return cls(**config) + + # We convert the config, as generated by LossScaleOptimizer.get_config, to a + # version that can be passed to LossScaleOptimizerV1.__init__ + if config['dynamic']: + config['loss_scale'] = loss_scale_module.DynamicLossScale( + config['initial_scale'], config['dynamic_growth_steps'], multiplier=2) + else: + config['loss_scale'] = loss_scale_module.FixedLossScale( + config['initial_scale']) + + del config['dynamic'] + del config['initial_scale'] + del config['dynamic_growth_steps'] + config['optimizer'] = optimizers.deserialize( + config.pop('inner_optimizer'), custom_objects=custom_objects) + return cls(**config) + + +class FakeOptimizerForRestoration(trackable.Trackable): + """A fake optimizer used to support restoring TensorFlow 2.2 checkpoints. + + The checkpoint format for LossScaleOptimizers changed after TF 2.2. This class + exists to support restoring TF 2.2 checkpoints in newer version of TensorFlow. + + In TF 2.2, LossScaleOptimizer would track the wrapped optimizer by calling the + following in LossScaleOptimizer.__init__ + + ``` + self._track_trackable(self._optimizer, 'base_optimizer') + ``` + + This means a dependency from the LossScaleOptimizer to the wrapped optimizer + would be stored in the checkpoint. However now, the checkpoint format with a + LossScaleOptimizer is the same as the format without a LossScaleOptimizer, + except the loss scale is also stored. This means there is no dependency from + the LossScaleOptimizer to the wrapped optimizer. Instead, the + LossScaleOptimizer acts as if it is the wrapped optimizer, from a checkpoint's + perspective, by overriding all Trackable methods and delegating them to the + wrapped optimizer. + + To allow restoring TF 2.2. checkpoints, LossScaleOptimizer adds a dependency + on this class instead of the inner optimizer. When restored, this class will + instead restore the slot variables of the inner optimizer. Since this class + has no variables, it does not affect the checkpoint when saved. + """ + + def __init__(self, optimizer): + self._optimizer = optimizer + + def get_slot_names(self): + return self._optimizer.get_slot_names() + + def _create_or_restore_slot_variable(self, slot_variable_position, slot_name, + variable): + return self._optimizer._create_or_restore_slot_variable( # pylint: disable=protected-access + slot_variable_position, slot_name, variable) + + +mixed_precision.register_loss_scale_wrapper(optimizer_v2.OptimizerV2, + LossScaleOptimizerV1) + + +def _multiply_gradient(gradient, scale): + """Multiply a (possibly sparse) gradient by the given scale factor.""" + scale = math_ops.cast(scale, gradient.dtype) + if isinstance(gradient, indexed_slices.IndexedSlices): + return indexed_slices.IndexedSlices( + gradient.values * scale, + gradient.indices, + dense_shape=gradient.dense_shape) + else: + return gradient * scale + + +def strategy_supports_loss_scaling(): + """Returns True if the current Strategy supports loss scaling.""" + if not distribute_lib.has_strategy(): + return True + strategy = distribute_lib.get_strategy() + # Strategies are supported if either there is only one replica or if variables + # are replicated per device. Otherwise, the current model.fit() implementation + # and most custom training loops incorrectly unscale the gradients. Currently, + # gradients are unscaled once per compute replica, but they should be unscaled + # once per variable replica. When there is one variable replica for each + # compute replica, this works fine, but otherwise issues will occur. + # TODO(reedwm): Support all strategies. + return isinstance(strategy, ( + collective_all_reduce_strategy.CollectiveAllReduceStrategy, + collective_all_reduce_strategy.CollectiveAllReduceStrategyV1, + one_device_strategy.OneDeviceStrategy, + one_device_strategy.OneDeviceStrategyV1, + mirrored_strategy.MirroredStrategy, + mirrored_strategy.MirroredStrategyV1, + )) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/policy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..36e558bba666b8a1a8d7f00ed30457e9f482647b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/policy.py @@ -0,0 +1,582 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains the Policy class for mixed precision training.""" + +import contextlib + +from tensorflow.python.framework import dtypes +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.mixed_precision import device_compatibility_check +from tensorflow.python.keras.mixed_precision import loss_scale as keras_loss_scale_module +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.platform import tf_logging +from tensorflow.python.training.experimental import mixed_precision_global_state + + +# pylint: disable=g-classes-have-attributes +class Policy(object): + """A dtype policy for a Keras layer. + + A dtype policy determines a layer's computation and variable dtypes. Each + layer has a policy. Policies can be passed to the `dtype` argument of layer + constructors, or a global policy can be set with + `tf.keras.mixed_precision.set_global_policy`. + + Args: + name: The policy name, which determines the compute and variable dtypes. Can + be any dtype name, such as `'float32'` or `'float64'`, which causes both + the compute and variable dtypes will be that dtype. Can also be the string + `'mixed_float16'` or `'mixed_bfloat16'`, which causes the compute dtype to + be float16 or bfloat16 and the variable dtype to be float32. + + Typically you only need to interact with dtype policies when using mixed + precision, which is the use of float16 or bfloat16 for computations and + float32 for variables. This is why the term `mixed_precision` appears in the + API name. Mixed precision can be enabled by passing `'mixed_float16'` or + `'mixed_bfloat16'` to `tf.keras.mixed_precision.set_global_policy`. See [the + mixed precision guide](https://www.tensorflow.org/guide/keras/mixed_precision) + for more information on how to use mixed precision. + + >>> tf.keras.mixed_precision.set_global_policy('mixed_float16') + >>> layer1 = tf.keras.layers.Dense(10) + >>> layer1.dtype_policy # `layer1` will automatically use mixed precision + + >>> # Can optionally override layer to use float32 instead of mixed precision. + >>> layer2 = tf.keras.layers.Dense(10, dtype='float32') + >>> layer2.dtype_policy + + >>> # Set policy back to initial float32 for future examples. + >>> tf.keras.mixed_precision.set_global_policy('float32') + + In the example above, passing `dtype='float32'` to the layer is equivalent to + passing `dtype=tf.keras.mixed_precision.Policy('float32')`. In general, + passing a dtype policy name to a layer is equivalent to passing the + corresponding policy, so it is never necessary to explicitly construct a + `Policy` object. + + Note: `Model.compile` will automatically wrap an optimizer with a + `tf.keras.mixed_precision.LossScaleOptimizer` if you use the `'mixed_float16'` + policy. If you use a custom training loop instead of calling `Model.compile`, + you should explicitly use a `tf.keras.mixed_precision.LossScaleOptimizer` to + avoid numeric underflow with float16. + + ### How a layer uses its policy's compute dtype + + A layer casts its inputs to its compute dtype. This causes the layer's + computations and output to also be in the compute dtype. For example: + + >>> x = tf.ones((4, 4, 4, 4), dtype='float64') + >>> # `layer`'s policy defaults to float32. + >>> layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2) + >>> layer.compute_dtype # Equivalent to layer.dtype_policy.compute_dtype + 'float32' + >>> # `layer` casts its inputs to its compute dtype and does computations in + >>> # that dtype. + >>> y = layer(x) + >>> y.dtype + tf.float32 + + Note that the base `tf.keras.layers.Layer` class inserts the casts. If + subclassing your own layer, you do not have to insert any casts. + + Currently, only tensors in the first argument to the layer's `call` method are + casted (although this will likely be changed in a future minor release). For + example: + + >>> class MyLayer(tf.keras.layers.Layer): + ... # Bug! `b` will not be casted. + ... def call(self, a, b): + ... return a + 1., b + 1. + >>> a = tf.constant(1., dtype="float32") + >>> b = tf.constant(1., dtype="float32") + >>> layer = MyLayer(dtype="float64") + >>> x, y = layer(a, b) + >>> x.dtype + tf.float64 + >>> y.dtype + tf.float32 + + If writing your own layer with multiple inputs, you should either explicitly + cast other tensors to `self.compute_dtype` in `call` or accept all tensors in + the first argument as a list. + + The casting only occurs in TensorFlow 2. If + `tf.compat.v1.disable_v2_behavior()` has been called, you can enable the + casting behavior with `tf.compat.v1.keras.layers.enable_v2_dtype_behavior()`. + + ### How a layer uses its policy's variable dtype + + The default dtype of variables created by `tf.keras.layers.Layer.add_weight` + is the layer's policy's variable dtype. + + If a layer's compute and variable dtypes differ, `add_weight` will wrap + floating-point variables with a special wrapper called an `AutoCastVariable`. + `AutoCastVariable` is identical to the original variable except it casts + itself to the layer's compute dtype when used within `Layer.call`. This means + if you are writing a layer, you do not have to explicitly cast the variables + to the layer's compute dtype. For example: + + >>> class SimpleDense(tf.keras.layers.Layer): + ... + ... def build(self, input_shape): + ... # With mixed precision, self.kernel is a float32 AutoCastVariable + ... self.kernel = self.add_weight('kernel', (input_shape[-1], 10)) + ... + ... def call(self, inputs): + ... # With mixed precision, self.kernel will be casted to float16 + ... return tf.linalg.matmul(inputs, self.kernel) + ... + >>> layer = SimpleDense(dtype='mixed_float16') + >>> y = layer(tf.ones((10, 10))) + >>> y.dtype + tf.float16 + >>> layer.kernel.dtype + tf.float32 + + A layer author can prevent a variable from being wrapped with an + `AutoCastVariable` by passing `experimental_autocast=False` to `add_weight`, + which is useful if the float32 value of the variable must be accessed within + the layer. + + ### How to write a layer that supports mixed precision and float64. + + For the most part, layers will automatically support mixed precision and + float64 without any additional work, due to the fact the base layer + automatically casts inputs, creates variables of the correct type, and in the + case of mixed precision, wraps variables with `AutoCastVariables`. + + The primary case where you need extra work to support mixed precision or + float64 is when you create a new tensor, such as with `tf.ones` or + `tf.random.normal`, In such cases, you must create the tensor of the correct + dtype. For example, if you call `tf.random.normal`, you must pass the compute + dtype, which is the dtype the inputs have been casted to: + + >>> class AddRandom(tf.keras.layers.Layer): + ... + ... def call(self, inputs): + ... # We must pass `dtype=inputs.dtype`, otherwise a TypeError may + ... # occur when adding `inputs` to `rand`. + ... rand = tf.random.normal(shape=inputs.shape, dtype=inputs.dtype) + ... return inputs + rand + >>> layer = AddRandom(dtype='mixed_float16') + >>> y = layer(x) + >>> y.dtype + tf.float16 + + If you did not pass `dtype=inputs.dtype` to `tf.random.normal`, a + `TypeError` would have occurred. This is because the `tf.random.normal`'s + dtype defaults to `"float32"`, but the input dtype is float16. You cannot add + a float32 tensor with a float16 tensor. + """ + + def __init__(self, name): + if isinstance(name, dtypes.DType): + raise TypeError("'name' must be a string, not a DType. " + "Instead, pass DType.name. Got: %s" % (name.name,)) + elif not isinstance(name, str): + raise TypeError("'name' must be a string, but got: %s" % (name,)) + self._name = name + self._compute_dtype, self._variable_dtype = self._parse_name(name) + if name in ('mixed_float16', 'mixed_bloat16'): + device_compatibility_check.log_device_compatibility_check(name) + + def _parse_name(self, name): + """Parses a Policy name into a compute and variable dtype. + + Args: + name: The name of the policy: + + Returns: + The (compute_dtype, variable_dtype) pair. + """ + if name.endswith('_float32_vars'): + error_msg = ('Policies ending in \'_float32_vars\' have been removed ' + 'from TensorFlow.') + if name in ('infer_float32_vars', 'infer_with_float32_vars'): + error_msg += (' Please use the \'mixed_float16\' or \'mixed_bfloat16\' ' + 'policy instead.') + elif name == 'float16_with_float32_vars': + error_msg += (' Please use the \'mixed_float16\' policy instead.') + elif name == 'bfloat16_with_float32_vars': + error_msg += (' Please use the \'mixed_bfloat16\' policy instead.') + error_msg += ' Got policy name: \'%s\'' % name + raise ValueError(error_msg) + + if name == 'mixed_float16': + return 'float16', 'float32' + elif name == 'mixed_bfloat16': + return 'bfloat16', 'float32' + elif name == '_infer': + # The "_infer" policy exists only for compatibility with TF 1, where + # "_infer" is the default. The behavior matches the behavior of TF 1's + # behavior before policies were introduced. With "_infer", the computation + # and variable dtype are inferred from the first input the first time the + # layer is called. Once the layer is called for the first time, the + # layer's policy will change to the dtype of the first input, and it will + # no longer have the "_infer" policy. + # + # The infer policy should be considered an implementation detail and may + # be removed in the future. + return None, None + + try: + dtype = dtypes.as_dtype(name).name + except TypeError: + error = ("Cannot convert value %s to a mixed precision Policy. " + "Valid policies include 'mixed_float16', 'mixed_bfloat16', " + "and the name of any dtype such as 'float32'." % (name,)) + raise ValueError(error) + return dtype, dtype + + @property + def variable_dtype(self): + """The variable dtype of this policy. + + This is the dtype layers will create their variables in, unless a layer + explicitly chooses a different dtype. If this is different than + `Policy.compute_dtype`, Layers will cast variables to the compute dtype to + avoid type errors. + + Variable regularizers are run in the variable dtype, not the compute dtype. + + Returns: + The variable dtype of this policy, as a string. + """ + return self._variable_dtype + + @property + def compute_dtype(self): + """The compute dtype of this policy. + + This is the dtype layers will do their computations in. Typically layers + output tensors with the compute dtype as well. + + Note that even if the compute dtype is float16 or bfloat16, hardware devices + may not do individual adds, multiplies, and other fundamental operations in + float16 or bfloat16, but instead may do some of them in float32 for numeric + stability. The compute dtype is the dtype of the inputs and outputs of the + TensorFlow ops that the layer executes. Internally, many TensorFlow ops will + do certain internal calculations in float32 or some other device-internal + intermediate format with higher precision than float16/bfloat16, to increase + numeric stability. + + For example, a `tf.keras.layers.Dense` layer, when run on a GPU with a + float16 compute dtype, will pass float16 inputs to `tf.linalg.matmul`. But, + `tf.linalg.matmul` will do use float32 intermediate math. The performance + benefit of float16 is still apparent, due to increased memory bandwidth and + the fact modern GPUs have specialized hardware for computing matmuls on + float16 inputs while still keeping intermediate computations in float32. + + Returns: + The compute dtype of this policy, as a string. + """ + return self._compute_dtype + + @property + def name(self): + """Returns the name of this policy.""" + return self._name + + def __repr__(self): + return '' % self._name + + def get_config(self): + return {'name': self.name} + + @classmethod + def from_config(cls, config, custom_objects=None): + del custom_objects + if 'loss_scale' in config: + config = config.copy() + # Policy.get_config in TensorFlow 2.3 and below had a loss_scale. We + # silently drop it. + del config['loss_scale'] + return cls(**config) + + +class PolicyV1(Policy): + """A deprecated dtype policy for a Keras layer. + + Warning: This class is now deprecated and will be removed soon. Please use the + non-experimental class `tf.keras.mixed_precision.Policy` instead. + + The difference between this class and the non-experimental class is that this + class has a `loss_scale` field and the non-experimental class does not. The + loss scale is only used by `tf.keras.Model.compile`, which automatically wraps + the optimizer with a `LossScaleOptimizer` if the optimizer is not already a + `LossScaleOptimizer`. For the non-experimental Policy class, `Model.compile` + instead wraps the optimizer with a `LossScaleOptimizer` if `Policy.name` is + "mixed_float16". + + When deserializing objects with an experimental policy using functions like + `tf.keras.utils.deserialize_keras_object`, the policy will be deserialized as + the non-experimental `tf.keras.mixed_precision.Policy`, and the loss scale + will silently be dropped. This is so that SavedModels that are generated + with an experimental policy can be restored after the experimental policy is + removed. + """ + + def __init__(self, name, loss_scale='auto'): + """Constructs the policy. + + The `name` argument determines the compute and variable dtype, the default + loss scale, and has no additional effect on the Policy. The compute and + variable dtypes can only be specified through `name`, and cannot be + specified directly. + + Args: + name: A string. Can be one of the following values: + * Any dtype name, such as 'float32' or 'float64'. Both the variable and + compute dtypes will be that dtype. + * 'mixed_float16' or 'mixed_bfloat16': The compute dtype is float16 or + bfloat16, while the variable dtype is float32. With 'mixed_float16', + a dynamic loss scale is used. These policies are used for mixed + precision training. + loss_scale: A `tf.compat.v1.mixed_precision.LossScale`, an int (which + uses a `FixedLossScale`), the string "dynamic" (which uses a + `DynamicLossScale`), or None (which uses no loss scale). Defaults to + `"auto"`. In the `"auto"` case: 1) if `name` is `"mixed_float16"`, then + use `loss_scale="dynamic"`. 2) otherwise, do not use a loss scale. Only + `tf.keras.Model`s, not layers, use the loss scale, and it is only used + during `Model.fit`, `Model.train_on_batch`, and other similar methods. + """ + super(PolicyV1, self).__init__(name) + if loss_scale == 'auto': + loss_scale = 'dynamic' if name == 'mixed_float16' else None + self._using_default_loss_scale = True + else: + self._using_default_loss_scale = False + if loss_scale and self._compute_dtype not in (None, 'float16'): + tf_logging.warning( + 'Creating a Policy with a loss scale is only useful for ' + 'float16 policies. You passed loss_scale=%r for policy ' + '%s. Consider not passing any loss_scale instead.' % + (loss_scale, name)) + self._loss_scale = keras_loss_scale_module.get(loss_scale) + + @property + def loss_scale(self): + """Returns the loss scale of this Policy. + + Returns: + A `tf.compat.v1.mixed_precision.experimental.LossScale`, or None. + """ + return self._loss_scale + + def __repr__(self): + return '' % (self._name, self.loss_scale) + + def get_config(self): + config = { + 'name': self.name + } + if not self._using_default_loss_scale: + # We only include the loss scale if the default loss scale is not used. + # This allows us to change the loss scale config format without breaking + # users who use the default loss scale. + config['loss_scale'] = keras_loss_scale_module.serialize(self.loss_scale) + return config + + @classmethod + def from_config(cls, config, custom_objects=None): + if 'loss_scale' in config and isinstance(config['loss_scale'], dict): + config = config.copy() + config['loss_scale'] = keras_loss_scale_module.deserialize( + config['loss_scale'], custom_objects=custom_objects) + return cls(**config) + + +# The current global policy in effect. If None, it means the current value of +# floatx should be used as the policy if the V2 dtype behavior is enabled, +# or "_infer" otherwise. +# TODO(reedwm): Make this thread local? +_global_policy = None + + +def global_policy(): + """Returns the global dtype policy. + + The global policy is the default `tf.keras.mixed_precision.Policy` used for + layers, if no policy is passed to the layer constructor. If no policy has been + set with `keras.mixed_precision.set_global_policy`, this will return a policy + constructed from `tf.keras.backend.floatx()` (floatx defaults to float32). + + >>> tf.keras.mixed_precision.global_policy() + + >>> tf.keras.layers.Dense(10).dtype_policy # Defaults to the global policy + + + If TensorFlow 2 behavior has been disabled with + `tf.compat.v1.disable_v2_behavior()`, this will instead return a special + "_infer" policy which infers the dtype from the dtype of the first input the + first time the layer is called. This behavior matches the behavior that + existed in TensorFlow 1. + + See `tf.keras.mixed_precision.Policy` for more information on policies. + + Returns: + The global Policy. + """ + if _global_policy is None: + if base_layer_utils.v2_dtype_behavior_enabled(): + return Policy(backend.floatx()) + else: + return Policy('_infer') + return _global_policy + + +def _check_if_mixed_precision_graph_rewrite_is_enabled(policy): + if mixed_precision_global_state.is_mixed_precision_graph_rewrite_enabled(): + raise ValueError( + 'The global dtype policy cannot be set to "{policy.name}", because the ' + 'mixed precision graph rewrite has already been enabled.\n' + 'At most, one of the following can be called:\n\n' + ' 1. tf.compat.v1.train.enable_mixed_precision_graph_rewrite() ' + '(You called this first)\n' + ' 2. tf.keras.mixed_precision.experimental.set_global_policy() with a ' + 'mixed precision policy (You called this second)\n\n' + 'You called both functions, which is an error, because both functions ' + 'enable you to use mixed precision. If in doubt which function to use, ' + 'use the second, as it supports Eager execution and is more ' + 'customizable.'.format(policy=policy)) + + +def set_global_policy(policy): + """Sets the global dtype policy. + + The global policy is the default `tf.keras.mixed_precision.Policy` used for + layers, if no policy is passed to the layer constructor. + + >>> tf.keras.mixed_precision.set_global_policy('mixed_float16') + >>> tf.keras.mixed_precision.global_policy() + + >>> tf.keras.layers.Dense(10).dtype_policy + + >>> # Global policy is not used if a policy is directly passed to constructor + >>> tf.keras.layers.Dense(10, dtype='float64').dtype_policy + + >>> tf.keras.mixed_precision.set_global_policy('float32') + + If no global policy is set, layers will instead default to a Policy + constructed from `tf.keras.backend.floatx()`. + + To use mixed precision, the global policy should be set to `'mixed_float16'` + or `'mixed_bfloat16'`, so that every layer uses a 16-bit compute dtype and + float32 variable dtype by default. + + Only floating point policies can be set as the global policy, such as + `'float32'` and `'mixed_float16'`. Non-floating point policies such as + `'int32'` and `'complex64'` cannot be set as the global policy because most + layers do not support such policies. + + See `tf.keras.mixed_precision.Policy` for more information. + + Args: + policy: A Policy, or a string that will be converted to a Policy. Can also + be None, in which case the global policy will be constructed from + `tf.keras.backend.floatx()` + """ + global _global_policy + if not base_layer_utils.v2_dtype_behavior_enabled(): + raise ValueError('The global policy can only be set in TensorFlow 2 or if ' + 'V2 dtype behavior has been set. To enable V2 dtype ' + 'behavior, call ' + '"tf.compat.v1.keras.layers.enable_v2_dtype_behavior()"') + if policy is not None and not isinstance(policy, Policy): + policy = Policy(policy) + is_mixed_policy = (policy is not None and + policy.compute_dtype != policy.variable_dtype) + if is_mixed_policy: + _check_if_mixed_precision_graph_rewrite_is_enabled(policy) + if (policy is not None and policy.compute_dtype is not None and + not dtypes.as_dtype(policy.compute_dtype).is_floating): + raise ValueError('set_global_policy can only be used to set the global ' + 'policy to floating-point policies, such as "float32" and ' + '"mixed_float16", but got policy: %s' + % (policy.name,)) + _global_policy = policy + mixed_precision_global_state.set_using_mixed_precision_policy(is_mixed_policy) + + +# TODO(reedwm): Make this thread local +@contextlib.contextmanager +def policy_scope(policy): + """A context manager that sets the global Policy under it. + + Args: + policy: A Policy, or a string that will be converted to a Policy.. + + Yields: + Nothing. + """ + old_policy = _global_policy + try: + set_global_policy(policy) + yield + finally: + set_global_policy(old_policy) + + +def _is_convertible_to_dtype(dtype): + try: + dtypes.as_dtype(dtype) + return True + except TypeError: + return False + + +def _policy_equivalent_to_dtype(policy): + """Returns True if the Policy is equivalent to a single dtype. + + A policy is equivalent to a single dtype if the policy's compute and variable + dtypes are the same and the policy's type is Policy and not a subclass of + Policy (such as PolicyV1). + + The "_infer" policy is considered equivalent to a single dtype. + + Args: + policy: A Policy. + + Returns: + True, if the policy is equivalent to a single dtype. + """ + # We use type() instead of isinstance because a subclass of Policy is never + # equivalent to a dtype. + return (type(policy) == Policy and # pylint: disable=unidiomatic-typecheck + list(policy.get_config().keys()) == ['name'] and + (policy.name == '_infer' or _is_convertible_to_dtype(policy.name))) + + +def serialize(policy): + if _policy_equivalent_to_dtype(policy): + # We return either None or the policy name for compatibility with older + # versions of Keras. If the policy name is returned, it is a dtype string + # such as 'float32'. + return None if policy.name == '_infer' else policy.name + return generic_utils.serialize_keras_object(policy) + + +def deserialize(config, custom_objects=None): + if isinstance(config, str) and _is_convertible_to_dtype(config): + return Policy(config) + if config is None: + return Policy('_infer') + module_objects = {'Policy': Policy, 'PolicyV1': Policy} + return generic_utils.deserialize_keras_object( + config, + module_objects=module_objects, + custom_objects=custom_objects, + printable_module_name='dtype policy') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4cee06195e3920626a8b26eb53df5590a63d3e85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/mixed_precision/test_util.py @@ -0,0 +1,225 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains testing utilities related to mixed precision.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import custom_gradient +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest + + +def create_identity_with_grad_check_fn(expected_gradient, expected_dtype=None): + """Returns a function that asserts it's gradient has a certain value. + + This serves as a hook to assert intermediate gradients have a certain value. + This returns an identity function. The identity's gradient function is also + the identity function, except it asserts that the gradient equals + `expected_gradient` and has dtype `expected_dtype`. + + Args: + expected_gradient: The gradient function asserts that the gradient is this + value. + expected_dtype: The gradient function asserts the gradient has this dtype. + + Returns: + An identity function whose gradient function asserts the gradient has a + certain value. + """ + @custom_gradient.custom_gradient + def _identity_with_grad_check(x): + """Function that asserts it's gradient has a certain value.""" + x = array_ops.identity(x) + def grad(dx): + """Gradient function that asserts the gradient has a certain value.""" + if expected_dtype: + assert dx.dtype == expected_dtype, ( + 'dx.dtype should be %s but is: %s' % (expected_dtype, dx.dtype)) + expected_tensor = tensor_conversion.convert_to_tensor_v2_with_dispatch( + expected_gradient, dtype=dx.dtype, name='expected_gradient' + ) + # Control dependency is to ensure input is available. It's possible the + # dataset will throw a StopIteration to indicate there is no more data, in + # which case we don't want to run the assertion. + with ops.control_dependencies([x]): + assert_op = check_ops.assert_equal(dx, expected_tensor) + with ops.control_dependencies([assert_op]): + dx = array_ops.identity(dx) + return dx + return x, grad + # Keras sometimes has trouble serializing Lambda layers with a decorated + # function. So we define and return a non-decorated function. + def identity_with_grad_check(x): + return _identity_with_grad_check(x) + return identity_with_grad_check + + +def create_identity_with_nan_gradients_fn(have_nan_gradients): + """Returns a function that optionally has NaN gradients. + + This serves as a hook to introduce NaN gradients to a model. This returns an + identity function. The identity's gradient function will check if the boolean + tensor `have_nan_gradients` is True. If so, the gradient will be NaN. + Otherwise, the gradient will also be the identity. + + Args: + have_nan_gradients: A scalar boolean tensor. If True, gradients will be NaN. + Otherwise, the gradient function is the identity function. + + Returns: + An identity function whose gradient function will return NaNs, if + `have_nan_gradients` is True. + """ + @custom_gradient.custom_gradient + def _identity_with_nan_gradients(x): + """Function whose gradient is NaN iff `have_nan_gradients` is True.""" + x = array_ops.identity(x) + def grad(dx): + return cond.cond( + have_nan_gradients, + lambda: dx * float('NaN'), + lambda: dx + ) + return x, grad + # Keras sometimes has trouble serializing Lambda layers with a decorated + # function. So we define and return a non-decorated function. + def identity_with_nan_gradients(x): + return _identity_with_nan_gradients(x) + return identity_with_nan_gradients + + +class AssertTypeLayer(base_layer.Layer): + """A layer which asserts it's inputs are a certain type.""" + + def __init__(self, assert_type=None, **kwargs): + self._assert_type = (dtypes.as_dtype(assert_type).name if assert_type + else None) + super(AssertTypeLayer, self).__init__(**kwargs) + + def assert_input_types(self, inputs): + """Asserts `inputs` are of the correct type. Should be called in call().""" + if self._assert_type: + inputs_flattened = nest.flatten(inputs) + for inp in inputs_flattened: + assert inp.dtype.base_dtype == self._assert_type, ( + 'Input tensor has type %s which does not match assert type %s' % + (inp.dtype.name, self._assert_type)) + + +class MultiplyLayer(AssertTypeLayer): + """A layer which multiplies its input by a scalar variable.""" + + def __init__(self, + regularizer=None, + activity_regularizer=None, + use_operator=False, + var_name='v', + **kwargs): + """Initializes the MultiplyLayer. + + Args: + regularizer: The weight regularizer on the scalar variable. + activity_regularizer: The activity regularizer. + use_operator: If True, add using the * operator. If False, add using + tf.multiply. + var_name: The name of the variable. It can be useful to pass a name other + than 'v', to test having the attribute name (self.v) being different + from the variable name. + **kwargs: Passed to AssertTypeLayer constructor. + """ + self._regularizer = regularizer + if isinstance(regularizer, dict): + self._regularizer = regularizers.deserialize(regularizer, + custom_objects=globals()) + self._activity_regularizer = activity_regularizer + if isinstance(activity_regularizer, dict): + self._activity_regularizer = regularizers.deserialize( + activity_regularizer, custom_objects=globals()) + + self._use_operator = use_operator + self._var_name = var_name + super(MultiplyLayer, self).__init__( + activity_regularizer=self._activity_regularizer, **kwargs) + + def build(self, _): + self.v = self.add_weight( + self._var_name, (), initializer='ones', regularizer=self._regularizer) + self.built = True + + def call(self, inputs): + self.assert_input_types(inputs) + return self._multiply(inputs, self.v) + + def _multiply(self, x, y): + if self._use_operator: + return x * y + else: + return math_ops.multiply(x, y) + + def get_config(self): + config = super(MultiplyLayer, self).get_config() + config['regularizer'] = regularizers.serialize(self._regularizer) + config['activity_regularizer'] = regularizers.serialize( + self._activity_regularizer) + config['use_operator'] = self._use_operator + config['var_name'] = self._var_name + config['assert_type'] = self._assert_type + return config + + +class MultiplyLayerWithoutAutoCast(MultiplyLayer): + """Same as MultiplyLayer, but does not use AutoCastVariables.""" + + def build(self, _): + dtype = self.dtype + if dtype in ('float16', 'bfloat16'): + dtype = 'float32' + self.v = self.add_weight( + 'v', (), + initializer='ones', + dtype=dtype, + experimental_autocast=False, + regularizer=self._regularizer) + self.built = True + + def call(self, inputs): + self.assert_input_types(inputs) + assert self.v.dtype in (dtypes.float32, dtypes.float64) + return self._multiply(inputs, math_ops.cast(self.v, inputs.dtype)) + + +class IdentityRegularizer(regularizers.Regularizer): + + def __call__(self, x): + assert x.dtype == dtypes.float32 + return array_ops.identity(x) + + def get_config(self): + return {} + + +class ReduceSumRegularizer(regularizers.Regularizer): + + def __call__(self, x): + return math_ops.reduce_sum(x) + + def get_config(self): + return {} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adadelta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adadelta.py new file mode 100644 index 0000000000000000000000000000000000000000..f2264bd123543df471998eb90794db354512ce72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adadelta.py @@ -0,0 +1,149 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adadelta optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +import numpy as np +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.training import gen_training_ops + + +class Adadelta(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the Adadelta algorithm. + + Adadelta optimization is a stochastic gradient descent method that is based on + adaptive learning rate per dimension to address two drawbacks: + + - The continual decay of learning rates throughout training. + - The need for a manually selected global learning rate. + + Adadelta is a more robust extension of Adagrad that adapts learning rates + based on a moving window of gradient updates, instead of accumulating all + past gradients. This way, Adadelta continues learning even when many updates + have been done. Compared to Adagrad, in the original version of Adadelta you + don't have to set an initial learning rate. In this version, the initial + learning rate can be set, as in most other Keras optimizers. + + Args: + learning_rate: Initial value for the learning rate: + either a floating point value, + or a `tf.keras.optimizers.schedules.LearningRateSchedule` instance. + Defaults to 0.001. + Note that `Adadelta` tends to benefit from higher initial learning rate + values compared to other optimizers. + To match the exact form in the original paper, use 1.0. + rho: A `Tensor` or a floating point value. The decay rate. + epsilon: Small floating point value used to maintain numerical stability. + name: Optional name prefix for the operations created when applying + gradients. Defaults to `"Adadelta"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm and represents + the maximum norm of each parameter; + `"clipvalue"` (float) clips gradient by value and represents the + maximum absolute value of each parameter. + + Reference: + - [Zeiler, 2012](http://arxiv.org/abs/1212.5701) + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + rho=0.95, + epsilon=1e-7, + name='Adadelta', + **kwargs): + super(Adadelta, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('rho', rho) + self.epsilon = epsilon or backend_config.epsilon() + + def _create_slots(self, var_list): + # Separate for-loops to respect the ordering of slot variables from v1. + for v in var_list: + self.add_slot(v, 'accum_grad') + for v in var_list: + self.add_slot(v, 'accum_var') + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(Adadelta, self)._prepare_local(var_device, var_dtype, apply_state) + apply_state[(var_device, var_dtype)].update( + dict( + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + rho=array_ops.identity(self._get_hyper('rho', var_dtype)), + ) + ) + + def set_weights(self, weights): + params = self.weights + # Override set_weights for backward compatibility of Keras V1 optimizer + # since it does not include iteration at head of the weight list. Set + # iteration to 0. + if len(params) == len(weights) + 1: + weights = [np.array(0)] + weights + super(Adadelta, self).set_weights(weights) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + accum_grad = self.get_slot(var, 'accum_grad') + accum_var = self.get_slot(var, 'accum_var') + return gen_training_ops.ResourceApplyAdadelta( + var=var.handle, + accum=accum_grad.handle, + accum_update=accum_var.handle, + lr=coefficients['lr_t'], + rho=coefficients['rho'], + epsilon=coefficients['epsilon'], + grad=grad, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + accum_grad = self.get_slot(var, 'accum_grad') + accum_var = self.get_slot(var, 'accum_var') + return gen_training_ops.ResourceSparseApplyAdadelta( + var=var.handle, + accum=accum_grad.handle, + accum_update=accum_var.handle, + lr=coefficients['lr_t'], + rho=coefficients['rho'], + epsilon=coefficients['epsilon'], + grad=grad, + indices=indices, + use_locking=self._use_locking) + + def get_config(self): + config = super(Adadelta, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'rho': self._serialize_hyperparameter('rho'), + 'epsilon': self.epsilon, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adagrad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adagrad.py new file mode 100644 index 0000000000000000000000000000000000000000..c59e165db0240945a10850212c7e83262043e48e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adagrad.py @@ -0,0 +1,170 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adagrad optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.training import gen_training_ops + + +class Adagrad(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the Adagrad algorithm. + + Adagrad is an optimizer with parameter-specific learning rates, + which are adapted relative to how frequently a parameter gets + updated during training. The more updates a parameter receives, + the smaller the updates. + + Args: + learning_rate: Initial value for the learning rate: + either a floating point value, + or a `tf.keras.optimizers.schedules.LearningRateSchedule` instance. + Defaults to 0.001. + Note that `Adagrad` tends to benefit from higher initial learning rate + values compared to other optimizers. + To match the exact form in the original paper, use 1.0. + initial_accumulator_value: Floating point value. + Starting value for the accumulators (per-parameter momentum values). + Must be non-negative. + epsilon: Small floating point value used to maintain numerical stability. + name: Optional name prefix for the operations created when applying + gradients. Defaults to `"Adagrad"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm and represents + the maximum L2 norm of each weight variable; + `"clipvalue"` (float) clips gradient by value and represents the + maximum absolute value of each weight variable. + + Reference: + - [Duchi et al., 2011]( + http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf). + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + initial_accumulator_value=0.1, + epsilon=1e-7, + name='Adagrad', + **kwargs): + if initial_accumulator_value < 0.0: + raise ValueError('initial_accumulator_value must be non-negative: %s' % + initial_accumulator_value) + if epsilon is None: + epsilon = backend_config.epsilon() + super(Adagrad, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._initial_accumulator_value = initial_accumulator_value + self.epsilon = epsilon or backend_config.epsilon() + + def _create_slots(self, var_list): + for var in var_list: + dtype = var.dtype.base_dtype + init = init_ops.constant_initializer( + self._initial_accumulator_value, dtype=dtype) + self.add_slot(var, 'accumulator', init) + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(Adagrad, self)._prepare_local(var_device, var_dtype, apply_state) + apply_state[(var_device, var_dtype)].update( + dict( + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + neg_lr_t=-apply_state[(var_device, var_dtype)]['lr_t'], + zero=array_ops.zeros((), dtype=dtypes.int64), + ) + ) + + def set_weights(self, weights): + params = self.weights + # Override set_weights for backward compatibility of Keras V1 optimizer + # since it does not include iteration at head of the weight list. Set + # iteration to 0. + if len(params) == len(weights) + 1: + weights = [np.array(0)] + weights + super(Adagrad, self).set_weights(weights) + + @classmethod + def from_config(cls, config, custom_objects=None): + """Creates an optimizer from its config. + + This method is the reverse of `get_config`, + capable of instantiating the same optimizer from the config + dictionary. + + Args: + config: A Python dictionary, typically the output of get_config. + custom_objects: A Python dictionary mapping names to additional Python + objects used to create this optimizer, such as a function used for a + hyperparameter. + + Returns: + An optimizer instance. + """ + if 'initial_accumulator_value' not in config: + config['initial_accumulator_value'] = 0.1 + if 'lr' in config: + config['learning_rate'] = config.pop('lr') + return cls(**config) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + acc = self.get_slot(var, 'accumulator') + return gen_training_ops.ResourceApplyAdagradV2( + var=var.handle, + accum=acc.handle, + lr=coefficients['lr_t'], + epsilon=coefficients['epsilon'], + grad=grad, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + acc = self.get_slot(var, 'accumulator') + return gen_training_ops.ResourceSparseApplyAdagradV2( + var=var.handle, + accum=acc.handle, + lr=coefficients['lr_t'], + epsilon=coefficients['epsilon'], + grad=grad, + indices=indices, + use_locking=self._use_locking) + + def get_config(self): + config = super(Adagrad, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'initial_accumulator_value': self._initial_accumulator_value, + 'epsilon': self.epsilon, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adam.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1e90ad9088fe60f99ac00a361dc9690f9a3c47 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adam.py @@ -0,0 +1,480 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adam optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.eager import def_function +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.training import gen_training_ops + + +class Adam(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the Adam algorithm. + + Adam optimization is a stochastic gradient descent method that is based on + adaptive estimation of first-order and second-order moments. + + According to + [Kingma et al., 2014](http://arxiv.org/abs/1412.6980), + the method is "*computationally + efficient, has little memory requirement, invariant to diagonal rescaling of + gradients, and is well suited for problems that are large in terms of + data/parameters*". + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable + that takes no arguments and returns the actual value to use, The + learning rate. Defaults to 0.001. + beta_1: A float value or a constant float tensor, or a callable + that takes no arguments and returns the actual value to use. The + exponential decay rate for the 1st moment estimates. Defaults to 0.9. + beta_2: A float value or a constant float tensor, or a callable + that takes no arguments and returns the actual value to use, The + exponential decay rate for the 2nd moment estimates. Defaults to 0.999. + epsilon: A small constant for numerical stability. This epsilon is + "epsilon hat" in the Kingma and Ba paper (in the formula just before + Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to + 1e-7. + amsgrad: Boolean. Whether to apply AMSGrad variant of this algorithm from + the paper "On the Convergence of Adam and beyond". Defaults to `False`. + name: Optional name for the operations created when applying gradients. + Defaults to `"Adam"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Usage: + + >>> opt = tf.keras.optimizers.Adam(learning_rate=0.1) + >>> var1 = tf.Variable(10.0) + >>> loss = lambda: (var1 ** 2)/2.0 # d(loss)/d(var1) == var1 + >>> step_count = opt.minimize(loss, [var1]).numpy() + >>> # The first step is `-learning_rate*sign(grad)` + >>> var1.numpy() + 9.9 + + Reference: + - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) + - [Reddi et al., 2018]( + https://openreview.net/pdf?id=ryQu7f-RZ) for `amsgrad`. + + Notes: + + The default value of 1e-7 for epsilon might not be a good default in + general. For example, when training an Inception network on ImageNet a + current good choice is 1.0 or 0.1. Note that since Adam uses the + formulation just before Section 2.1 of the Kingma and Ba paper rather than + the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon + hat" in the paper. + + The sparse implementation of this algorithm (used when the gradient is an + IndexedSlices object, typically because of `tf.gather` or an embedding + lookup in the forward pass) does apply momentum to variable slices even if + they were not used in the forward pass (meaning they have a gradient equal + to zero). Momentum decay (beta1) is also applied to the entire momentum + accumulator. This means that the sparse behavior is equivalent to the dense + behavior (in contrast to some momentum implementations which ignore momentum + unless a variable slice was actually used). + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-7, + amsgrad=False, + name='Adam', + **kwargs): + super(Adam, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('beta_1', beta_1) + self._set_hyper('beta_2', beta_2) + self.epsilon = epsilon or backend_config.epsilon() + self.amsgrad = amsgrad + + def _create_slots(self, var_list): + # Create slots for the first and second moments. + # Separate for-loops to respect the ordering of slot variables from v1. + for var in var_list: + self.add_slot(var, 'm') + for var in var_list: + self.add_slot(var, 'v') + if self.amsgrad: + for var in var_list: + self.add_slot(var, 'vhat') + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(Adam, self)._prepare_local(var_device, var_dtype, apply_state) + + local_step = math_ops.cast(self.iterations + 1, var_dtype) + beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) + beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) + beta_1_power = math_ops.pow(beta_1_t, local_step) + beta_2_power = math_ops.pow(beta_2_t, local_step) + lr = (apply_state[(var_device, var_dtype)]['lr_t'] * + (math_ops.sqrt(1 - beta_2_power) / (1 - beta_1_power))) + apply_state[(var_device, var_dtype)].update( + dict( + lr=lr, + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + beta_1_t=beta_1_t, + beta_1_power=beta_1_power, + one_minus_beta_1_t=1 - beta_1_t, + beta_2_t=beta_2_t, + beta_2_power=beta_2_power, + one_minus_beta_2_t=1 - beta_2_t, + ) + ) + + def set_weights(self, weights): + params = self.weights + # If the weights are generated by Keras V1 optimizer, it includes vhats + # even without amsgrad, i.e, V1 optimizer has 3x + 1 variables, while V2 + # optimizer has 2x + 1 variables. Filter vhats out for compatibility. + num_vars = int((len(params) - 1) / 2) + if len(weights) == 3 * num_vars + 1: + weights = weights[:len(params)] + super(Adam, self).set_weights(weights) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + m = self.get_slot(var, 'm') + v = self.get_slot(var, 'v') + + if not self.amsgrad: + return gen_training_ops.ResourceApplyAdam( + var=var.handle, + m=m.handle, + v=v.handle, + beta1_power=coefficients['beta_1_power'], + beta2_power=coefficients['beta_2_power'], + lr=coefficients['lr_t'], + beta1=coefficients['beta_1_t'], + beta2=coefficients['beta_2_t'], + epsilon=coefficients['epsilon'], + grad=grad, + use_locking=self._use_locking) + else: + vhat = self.get_slot(var, 'vhat') + return gen_training_ops.ResourceApplyAdamWithAmsgrad( + var=var.handle, + m=m.handle, + v=v.handle, + vhat=vhat.handle, + beta1_power=coefficients['beta_1_power'], + beta2_power=coefficients['beta_2_power'], + lr=coefficients['lr_t'], + beta1=coefficients['beta_1_t'], + beta2=coefficients['beta_2_t'], + epsilon=coefficients['epsilon'], + grad=grad, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + # m_t = beta1 * m + (1 - beta1) * g_t + m = self.get_slot(var, 'm') + m_scaled_g_values = grad * coefficients['one_minus_beta_1_t'] + m_t = state_ops.assign(m, m * coefficients['beta_1_t'], + use_locking=self._use_locking) + with ops.control_dependencies([m_t]): + m_t = self._resource_scatter_add(m, indices, m_scaled_g_values) + + # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) + v = self.get_slot(var, 'v') + v_scaled_g_values = (grad * grad) * coefficients['one_minus_beta_2_t'] + v_t = state_ops.assign(v, v * coefficients['beta_2_t'], + use_locking=self._use_locking) + with ops.control_dependencies([v_t]): + v_t = self._resource_scatter_add(v, indices, v_scaled_g_values) + + if not self.amsgrad: + v_sqrt = math_ops.sqrt(v_t) + var_update = state_ops.assign_sub( + var, coefficients['lr'] * m_t / (v_sqrt + coefficients['epsilon']), + use_locking=self._use_locking) + return control_flow_ops.group(*[var_update, m_t, v_t]) + else: + v_hat = self.get_slot(var, 'vhat') + v_hat_t = math_ops.maximum(v_hat, v_t) + with ops.control_dependencies([v_hat_t]): + v_hat_t = state_ops.assign( + v_hat, v_hat_t, use_locking=self._use_locking) + v_hat_sqrt = math_ops.sqrt(v_hat_t) + var_update = state_ops.assign_sub( + var, + coefficients['lr'] * m_t / (v_hat_sqrt + coefficients['epsilon']), + use_locking=self._use_locking) + return control_flow_ops.group(*[var_update, m_t, v_t, v_hat_t]) + + def get_config(self): + config = super(Adam, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'beta_1': self._serialize_hyperparameter('beta_1'), + 'beta_2': self._serialize_hyperparameter('beta_2'), + 'epsilon': self.epsilon, + 'amsgrad': self.amsgrad, + }) + return config + + +class NonFusedAdam(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the Adam algorithm without fused kernels. + + Adam optimization is a stochastic gradient descent method that is based on + adaptive estimation of first-order and second-order moments. + According to the paper + [Adam: A Method for Stochastic Optimization. Kingma et al., + 2014](http://arxiv.org/abs/1412.6980), the method is "*computationally + efficient, has little memory requirement, invariant to diagonal rescaling of + gradients, and is well suited for problems that are large in terms of + data/parameters*". + + For AMSGrad see [On The Convergence Of Adam And Beyond. + Reddi et al., 5-8](https://openreview.net/pdf?id=ryQu7f-RZ). + + **If amsgrad = False**: + + initialize $m_0$ as 1st moment vector + initialize $v_0$ as 2nd moment vector + + The update rule for $\theta$ with gradient $g$ uses an optimization + described at the end of section 2 of the paper: + + $$lr_t = \mathrm{learning\_rate} * + \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ + $$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ + $$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$ + $$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$ + + **If amsgrad = True**: + + initialize $m_0$ as 1st moment vector + initialize $v_0$ as 2nd moment vector + initialize $\hat{v}_0$ as 2nd moment vector + + The update rule for $\theta$ with gradient $g$ uses an optimization + described at the end of section 2 of the paper: + + $$lr_t = \mathrm{learning\_rate} * + \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ + + $$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ + $$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$ + $$\hat{v}_t = \max(\hat{v}_{t-1}, v_t)$$ + $$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{\hat{v}_t} + \epsilon)$$ + + The default value of 1e-7 for epsilon might not be a good default in + general. For example, when training an Inception network on ImageNet a + current good choice is 1.0 or 0.1. Note that since Adam uses the + formulation just before Section 2.1 of the Kingma and Ba paper rather than + the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon + hat" in the paper. + + The sparse implementation of this algorithm (used when the gradient is an + IndexedSlices object, typically because of `tf.gather` or an embedding + lookup in the forward pass) does apply momentum to variable slices even if + they were not used in the forward pass (meaning they have a gradient equal + to zero). Momentum decay (beta1) is also applied to the entire momentum + accumulator. This means that the sparse behavior is equivalent to the dense + behavior (in contrast to some momentum implementations which ignore momentum + unless a variable slice was actually used). + + Usage: + + >>> opt = tf.keras.optimizers.Adam(learning_rate=0.1) + >>> var1 = tf.Variable(10.0) + >>> loss = lambda: (var1 ** 2)/2.0 # d(loss)/d(var1) == var1 + >>> step_count = opt.minimize(loss, [var1]).numpy() + >>> # The first step is `-learning_rate*sign(grad)` + >>> var1.numpy() + 9.9 + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-7, + amsgrad=False, + name='Adam', + **kwargs): + """Construct a new Adam optimizer. + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable that + takes no arguments and returns the actual value to use, The learning + rate. Defaults to 0.001. + beta_1: A float value or a constant float tensor, or a callable that takes + no arguments and returns the actual value to use. The exponential decay + rate for the 1st moment estimates. Defaults to 0.9. + beta_2: A float value or a constant float tensor, or a callable that takes + no arguments and returns the actual value to use, The exponential decay + rate for the 2nd moment estimates. Defaults to 0.999. + epsilon: A small constant for numerical stability. This epsilon is + "epsilon hat" in the Kingma and Ba paper (in the formula just before + Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to + 1e-7. + amsgrad: Boolean. Whether to apply AMSGrad variant of this algorithm from + the paper "On the Convergence of Adam and beyond". Defaults to `False`. + name: Optional name for the operations created when applying gradients. + Defaults to "Adam". + **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, + `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip + gradients by value, `decay` is included for backward compatibility to + allow time inverse decay of learning rate. `lr` is included for backward + compatibility, recommended to use `learning_rate` instead. + """ + + super(NonFusedAdam, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('beta_1', beta_1) + self._set_hyper('beta_2', beta_2) + self.epsilon = epsilon or backend_config.epsilon() + self.amsgrad = amsgrad + + def _create_slots(self, var_list): + # Create slots for the first and second moments. + # Separate for-loops to respect the ordering of slot variables from v1. + for var in var_list: + self.add_slot(var, 'm') + for var in var_list: + self.add_slot(var, 'v') + if self.amsgrad: + for var in var_list: + self.add_slot(var, 'vhat') + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(NonFusedAdam, self)._prepare_local(var_device, var_dtype, apply_state) + + local_step = math_ops.cast(self.iterations + 1, var_dtype) + beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) + beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) + beta_1_power = math_ops.pow(beta_1_t, local_step) + beta_2_power = math_ops.pow(beta_2_t, local_step) + lr = ( + apply_state[(var_device, var_dtype)]['lr_t'] * + (math_ops.sqrt(1 - beta_2_power) / (1 - beta_1_power))) + apply_state[(var_device, var_dtype)].update( + dict( + lr=lr, + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + beta_1_t=beta_1_t, + beta_1_power=beta_1_power, + one_minus_beta_1_t=1 - beta_1_t, + beta_2_t=beta_2_t, + beta_2_power=beta_2_power, + one_minus_beta_2_t=1 - beta_2_t, + ) + ) + + def set_weights(self, weights): + params = self.weights + # If the weights are generated by Keras V1 optimizer, it includes vhats + # even without amsgrad, i.e, V1 optimizer has 3x + 1 variables, while V2 + # optimizer has 2x + 1 variables. Filter vhats out for compatibility. + num_vars = int((len(params) - 1) / 2) + if len(weights) == 3 * num_vars + 1: + weights = weights[:len(params)] + super(NonFusedAdam, self).set_weights(weights) + + @def_function.function(jit_compile=True) + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) or + self._fallback_apply_state(var_device, var_dtype)) + + m = self.get_slot(var, 'm') + v = self.get_slot(var, 'v') + + alpha = ( + coefficients['lr_t'] * math_ops.sqrt(1 - coefficients['beta_2_power']) / + (1 - coefficients['beta_1_power'])) + m.assign_add((grad - m) * (1 - coefficients['beta_1_t'])) + v.assign_add((math_ops.square(grad) - v) * (1 - coefficients['beta_2_t'])) + if self.amsgrad: + vhat = self.get_slot(var, 'vhat') + vhat.assign(math_ops.maximum(vhat, v)) + v = vhat + var.assign_sub( + (m * alpha) / (math_ops.sqrt(v) - coefficients['epsilon'])) + + @def_function.function(jit_compile=True) + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) or + self._fallback_apply_state(var_device, var_dtype)) + + # m_t = beta1 * m + (1 - beta1) * g_t + m = self.get_slot(var, 'm') + m_scaled_g_values = grad * coefficients['one_minus_beta_1_t'] + m.assign(m * coefficients['beta_1_t']) + m.scatter_add(indexed_slices.IndexedSlices(m_scaled_g_values, indices)) + + # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) + v = self.get_slot(var, 'v') + v_scaled_g_values = (grad * grad) * coefficients['one_minus_beta_2_t'] + v.assign(v * coefficients['beta_2_t']) + v.scatter_add(indexed_slices.IndexedSlices(v_scaled_g_values, indices)) + + if not self.amsgrad: + var.assign_sub(coefficients['lr'] * m / + (math_ops.sqrt(v) + coefficients['epsilon'])) + else: + v_hat = self.get_slot(var, 'vhat') + v_hat.assign(math_ops.maximum(v_hat, v)) + var.assign_sub(coefficients['lr'] * m / + (math_ops.sqrt(v_hat) + coefficients['epsilon'])) + + def get_config(self): + config = super(NonFusedAdam, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'beta_1': self._serialize_hyperparameter('beta_1'), + 'beta_2': self._serialize_hyperparameter('beta_2'), + 'epsilon': self.epsilon, + 'amsgrad': self.amsgrad, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adamax.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adamax.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e009393a90614601312096b287f9cbb90282fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/adamax.py @@ -0,0 +1,187 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Adamax optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import gen_training_ops + + +class Adamax(optimizer_v2.OptimizerV2): + """Optimizer that implements the Adamax algorithm. + + It is a variant of Adam based on the infinity norm. + Default parameters follow those provided in the paper. + Adamax is sometimes superior to adam, specially in models with embeddings. + + Initialization: + + ```python + m = 0 # Initialize initial 1st moment vector + v = 0 # Initialize the exponentially weighted infinity norm + t = 0 # Initialize timestep + ``` + + The update rule for parameter `w` with gradient `g` is + described at the end of section 7.1 of the paper: + + ```python + t += 1 + m = beta1 * m + (1 - beta) * g + v = max(beta2 * v, abs(g)) + current_lr = learning_rate / (1 - beta1 ** t) + w = w - current_lr * m / (v + epsilon) + ``` + + Similarly to `Adam`, the epsilon is added for numerical stability + (especially to get rid of division by zero when `v_t == 0`). + + In contrast to `Adam`, the sparse implementation of this algorithm + (used when the gradient is an IndexedSlices object, typically because of + `tf.gather` or an embedding lookup in the forward pass) only updates + variable slices and corresponding `m_t`, `v_t` terms when that part of + the variable was used in the forward pass. This means that the sparse + behavior is contrast to the dense behavior (similar to some momentum + implementations which ignore momentum unless a variable slice was actually + used). + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`. The learning rate. + beta_1: A float value or a constant float tensor. The exponential decay + rate for the 1st moment estimates. + beta_2: A float value or a constant float tensor. The exponential decay + rate for the exponentially weighted infinity norm. + epsilon: A small constant for numerical stability. + name: Optional name for the operations created when applying gradients. + Defaults to `"Adamax"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Reference: + - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-7, + name='Adamax', + **kwargs): + super(Adamax, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('beta_1', beta_1) + self._set_hyper('beta_2', beta_2) + self.epsilon = epsilon or backend_config.epsilon() + + def _create_slots(self, var_list): + # Separate for-loops to respect the ordering of slot variables from v1. + for var in var_list: + self.add_slot(var, 'm') # Create slots for the first moments. + for var in var_list: + self.add_slot(var, 'v') # Create slots for the second moments. + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(Adamax, self)._prepare_local(var_device, var_dtype, apply_state) + + local_step = math_ops.cast(self.iterations + 1, var_dtype) + beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) + beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) + beta_1_power = math_ops.pow(beta_1_t, local_step) + lr_t = apply_state[(var_device, var_dtype)]['lr_t'] + + apply_state[(var_device, var_dtype)].update( + dict( + neg_scaled_lr=-lr_t / (1 - beta_1_power), + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + beta_1_t=beta_1_t, + beta_1_power=beta_1_power, + one_minus_beta_1_t=1 - beta_1_t, + beta_2_t=beta_2_t, + zero=array_ops.zeros((), dtype=dtypes.int64), + ) + ) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + m = self.get_slot(var, 'm') + v = self.get_slot(var, 'v') + return gen_training_ops.ResourceApplyAdaMax( + var=var.handle, + m=m.handle, + v=v.handle, + beta1_power=coefficients['beta_1_power'], + lr=coefficients['lr_t'], + beta1=coefficients['beta_1_t'], + beta2=coefficients['beta_2_t'], + epsilon=coefficients['epsilon'], + grad=grad, + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + # m_t = beta1 * m + (1 - beta1) * g_t + m = self.get_slot(var, 'm') + m_slice = array_ops.gather(m, indices, axis=coefficients['zero']) + m_t_slice = (m_slice * coefficients['beta_1_t'] + + grad * coefficients['one_minus_beta_1_t']) + with ops.control_dependencies([m_t_slice]): + m_t = self._resource_scatter_update(m, indices, m_t_slice) + + # u_t = max(beta2 * u, abs(g_t)) + v = self.get_slot(var, 'v') + v_slice = array_ops.gather(v, indices, axis=coefficients['zero']) + v_t_slice = math_ops.maximum(v_slice * coefficients['beta_2_t'], + math_ops.abs(grad)) + with ops.control_dependencies([v_t_slice]): + v_t = self._resource_scatter_update(v, indices, v_t_slice) + # theta_t = theta - lr / (1 - beta1^t) * m_t / u_t + var_slice = coefficients['neg_scaled_lr'] * ( + m_t_slice / (v_t_slice + coefficients['epsilon'])) + with ops.control_dependencies([var_slice]): + var_update = self._resource_scatter_add(var, indices, var_slice) + return control_flow_ops.group(*[var_update, m_t, v_t]) + + def get_config(self): + config = super(Adamax, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'beta_1': self._serialize_hyperparameter('beta_1'), + 'beta_2': self._serialize_hyperparameter('beta_2'), + 'epsilon': self.epsilon, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py new file mode 100644 index 0000000000000000000000000000000000000000..6e9ba7206ff7dbc754c0960decb8a037c514e5d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py @@ -0,0 +1,263 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ftrl-proximal optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.training import gen_training_ops + + +class Ftrl(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the FTRL algorithm. + + "Follow The Regularized Leader" (FTRL) is an optimization algorithm developed + at Google for click-through rate prediction in the early 2010s. It is most + suitable for shallow models with large and sparse feature spaces. + The algorithm is described by + [McMahan et al., 2013](https://research.google.com/pubs/archive/41159.pdf). + The Keras version has support for both online L2 regularization + (the L2 regularization described in the paper + above) and shrinkage-type L2 regularization + (which is the addition of an L2 penalty to the loss function). + + Initialization: + + ```python + n = 0 + sigma = 0 + z = 0 + ``` + + Update rule for one variable `w`: + + ```python + prev_n = n + n = n + g ** 2 + sigma = (sqrt(n) - sqrt(prev_n)) / lr + z = z + g - sigma * w + if abs(z) < lambda_1: + w = 0 + else: + w = (sgn(z) * lambda_1 - z) / ((beta + sqrt(n)) / alpha + lambda_2) + ``` + + Notation: + + - `lr` is the learning rate + - `g` is the gradient for the variable + - `lambda_1` is the L1 regularization strength + - `lambda_2` is the L2 regularization strength + + Check the documentation for the `l2_shrinkage_regularization_strength` + parameter for more details when shrinkage is enabled, in which case gradient + is replaced with a gradient with shrinkage. + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`. The learning rate. + learning_rate_power: A float value, must be less or equal to zero. + Controls how the learning rate decreases during training. Use zero for + a fixed learning rate. + initial_accumulator_value: The starting value for accumulators. + Only zero or positive values are allowed. + l1_regularization_strength: A float value, must be greater than or + equal to zero. Defaults to 0.0. + l2_regularization_strength: A float value, must be greater than or + equal to zero. Defaults to 0.0. + name: Optional name prefix for the operations created when applying + gradients. Defaults to `"Ftrl"`. + l2_shrinkage_regularization_strength: A float value, must be greater than + or equal to zero. This differs from L2 above in that the L2 above is a + stabilization penalty, whereas this L2 shrinkage is a magnitude penalty. + When input is sparse shrinkage will only happen on the active weights. + beta: A float value, representing the beta value from the paper. + Defaults to 0.0. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Reference: + - [McMahan et al., 2013]( + https://research.google.com/pubs/archive/41159.pdf) + """ + + def __init__(self, + learning_rate=0.001, + learning_rate_power=-0.5, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0, + name='Ftrl', + l2_shrinkage_regularization_strength=0.0, + beta=0.0, + **kwargs): + super(Ftrl, self).__init__(name, **kwargs) + + if initial_accumulator_value < 0.0: + raise ValueError( + 'initial_accumulator_value %f needs to be positive or zero' % + initial_accumulator_value) + if learning_rate_power > 0.0: + raise ValueError('learning_rate_power %f needs to be negative or zero' % + learning_rate_power) + if l1_regularization_strength < 0.0: + raise ValueError( + 'l1_regularization_strength %f needs to be positive or zero' % + l1_regularization_strength) + if l2_regularization_strength < 0.0: + raise ValueError( + 'l2_regularization_strength %f needs to be positive or zero' % + l2_regularization_strength) + if l2_shrinkage_regularization_strength < 0.0: + raise ValueError( + 'l2_shrinkage_regularization_strength %f needs to be positive' + ' or zero' % l2_shrinkage_regularization_strength) + + self._set_hyper('learning_rate', learning_rate) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('learning_rate_power', learning_rate_power) + self._set_hyper('l1_regularization_strength', l1_regularization_strength) + self._set_hyper('l2_regularization_strength', l2_regularization_strength) + self._set_hyper('beta', beta) + self._initial_accumulator_value = initial_accumulator_value + self._l2_shrinkage_regularization_strength = ( + l2_shrinkage_regularization_strength) + + def _create_slots(self, var_list): + # Create the "accum" and "linear" slots. + for var in var_list: + dtype = var.dtype.base_dtype + init = init_ops.constant_initializer( + self._initial_accumulator_value, dtype=dtype) + self.add_slot(var, 'accumulator', init) + self.add_slot(var, 'linear') + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(Ftrl, self)._prepare_local(var_device, var_dtype, apply_state) + apply_state[(var_device, var_dtype)].update( + dict( + learning_rate_power=array_ops.identity( + self._get_hyper('learning_rate_power', var_dtype)), + l1_regularization_strength=array_ops.identity( + self._get_hyper('l1_regularization_strength', var_dtype)), + l2_regularization_strength=array_ops.identity( + self._get_hyper('l2_regularization_strength', var_dtype)), + beta=array_ops.identity(self._get_hyper('beta', var_dtype)), + l2_shrinkage_regularization_strength=math_ops.cast( + self._l2_shrinkage_regularization_strength, var_dtype))) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + # Adjust L2 regularization strength to include beta to avoid the underlying + # TensorFlow ops needing to include it. + adjusted_l2_regularization_strength = ( + coefficients['l2_regularization_strength'] + coefficients['beta'] / + (2. * coefficients['lr_t'])) + + accum = self.get_slot(var, 'accumulator') + linear = self.get_slot(var, 'linear') + + if self._l2_shrinkage_regularization_strength <= 0.0: + return gen_training_ops.ResourceApplyFtrl( + var=var.handle, + accum=accum.handle, + linear=linear.handle, + grad=grad, + lr=coefficients['lr_t'], + l1=coefficients['l1_regularization_strength'], + l2=adjusted_l2_regularization_strength, + lr_power=coefficients['learning_rate_power'], + use_locking=self._use_locking) + else: + return gen_training_ops.ResourceApplyFtrlV2( + var=var.handle, + accum=accum.handle, + linear=linear.handle, + grad=grad, + lr=coefficients['lr_t'], + l1=coefficients['l1_regularization_strength'], + l2=adjusted_l2_regularization_strength, + l2_shrinkage=coefficients['l2_shrinkage_regularization_strength'], + lr_power=coefficients['learning_rate_power'], + use_locking=self._use_locking) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + # Adjust L2 regularization strength to include beta to avoid the underlying + # TensorFlow ops needing to include it. + adjusted_l2_regularization_strength = ( + coefficients['l2_regularization_strength'] + coefficients['beta'] / + (2. * coefficients['lr_t'])) + + accum = self.get_slot(var, 'accumulator') + linear = self.get_slot(var, 'linear') + + if self._l2_shrinkage_regularization_strength <= 0.0: + return gen_training_ops.ResourceSparseApplyFtrl( + var=var.handle, + accum=accum.handle, + linear=linear.handle, + grad=grad, + indices=indices, + lr=coefficients['lr_t'], + l1=coefficients['l1_regularization_strength'], + l2=adjusted_l2_regularization_strength, + lr_power=coefficients['learning_rate_power'], + use_locking=self._use_locking) + else: + return gen_training_ops.ResourceSparseApplyFtrlV2( + var=var.handle, + accum=accum.handle, + linear=linear.handle, + grad=grad, + indices=indices, + lr=coefficients['lr_t'], + l1=coefficients['l1_regularization_strength'], + l2=adjusted_l2_regularization_strength, + l2_shrinkage=coefficients['l2_shrinkage_regularization_strength'], + lr_power=coefficients['learning_rate_power'], + use_locking=self._use_locking) + + def get_config(self): + config = super(Ftrl, self).get_config() + config.update({ + 'learning_rate': + self._serialize_hyperparameter('learning_rate'), + 'decay': + self._initial_decay, + 'initial_accumulator_value': + self._initial_accumulator_value, + 'learning_rate_power': + self._serialize_hyperparameter('learning_rate_power'), + 'l1_regularization_strength': + self._serialize_hyperparameter('l1_regularization_strength'), + 'l2_regularization_strength': + self._serialize_hyperparameter('l2_regularization_strength'), + 'beta': + self._serialize_hyperparameter('beta'), + 'l2_shrinkage_regularization_strength': + self._l2_shrinkage_regularization_strength, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/gradient_descent.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/gradient_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4e01db426f8e63cd310b4a818669491af77731 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/gradient_descent.py @@ -0,0 +1,190 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SGD optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.framework import tensor +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.training import gen_training_ops + + +class SGD(optimizer_v2.OptimizerV2): + r"""Gradient descent (with momentum) optimizer. + + Update rule for parameter `w` with gradient `g` when `momentum` is 0: + + ```python + w = w - learning_rate * g + ``` + + Update rule when `momentum` is larger than 0: + + ```python + velocity = momentum * velocity - learning_rate * g + w = w + velocity + ``` + + When `nesterov=True`, this rule becomes: + + ```python + velocity = momentum * velocity - learning_rate * g + w = w + momentum * velocity - learning_rate * g + ``` + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable + that takes no arguments and returns the actual value to use. The + learning rate. Defaults to 0.01. + momentum: float hyperparameter >= 0 that accelerates gradient descent + in the relevant + direction and dampens oscillations. Defaults to 0, i.e., vanilla gradient + descent. + nesterov: boolean. Whether to apply Nesterov momentum. + Defaults to `False`. + name: Optional name prefix for the operations created when applying + gradients. Defaults to `"SGD"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Usage: + + >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1) + >>> var = tf.Variable(1.0) + >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1 + >>> step_count = opt.minimize(loss, [var]).numpy() + >>> # Step is `- learning_rate * grad` + >>> var.numpy() + 0.9 + + >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9) + >>> var = tf.Variable(1.0) + >>> val0 = var.value() + >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1 + >>> # First step is `- learning_rate * grad` + >>> step_count = opt.minimize(loss, [var]).numpy() + >>> val1 = var.value() + >>> (val0 - val1).numpy() + 0.1 + >>> # On later steps, step-size increases because of momentum + >>> step_count = opt.minimize(loss, [var]).numpy() + >>> val2 = var.value() + >>> (val1 - val2).numpy() + 0.18 + + Reference: + - For `nesterov=True`, See [Sutskever et al., 2013]( + http://jmlr.org/proceedings/papers/v28/sutskever13.pdf). + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.01, + momentum=0.0, + nesterov=False, + name="SGD", + **kwargs): + super(SGD, self).__init__(name, **kwargs) + self._set_hyper("learning_rate", kwargs.get("lr", learning_rate)) + self._set_hyper("decay", self._initial_decay) + + self._momentum = False + if isinstance( + momentum, tensor.Tensor) or callable(momentum) or momentum > 0: + self._momentum = True + if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1): + raise ValueError("`momentum` must be between [0, 1].") + self._set_hyper("momentum", momentum) + + self.nesterov = nesterov + + def _create_slots(self, var_list): + if self._momentum: + for var in var_list: + self.add_slot(var, "momentum") + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(SGD, self)._prepare_local(var_device, var_dtype, apply_state) + apply_state[(var_device, var_dtype)]["momentum"] = array_ops.identity( + self._get_hyper("momentum", var_dtype)) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + if self._momentum: + momentum_var = self.get_slot(var, "momentum") + return gen_training_ops.ResourceApplyKerasMomentum( + var=var.handle, + accum=momentum_var.handle, + lr=coefficients["lr_t"], + grad=grad, + momentum=coefficients["momentum"], + use_locking=self._use_locking, + use_nesterov=self.nesterov) + else: + return gen_training_ops.ResourceApplyGradientDescent( + var=var.handle, + alpha=coefficients["lr_t"], + delta=grad, + use_locking=self._use_locking) + + def _resource_apply_sparse_duplicate_indices(self, grad, var, indices, + **kwargs): + if self._momentum: + return super(SGD, self)._resource_apply_sparse_duplicate_indices( + grad, var, indices, **kwargs) + else: + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = (kwargs.get("apply_state", {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + return gen_resource_variable_ops.ResourceScatterAdd( + resource=var.handle, + indices=indices, + updates=-grad * coefficients["lr_t"]) + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + # This method is only needed for momentum optimization. + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + momentum_var = self.get_slot(var, "momentum") + return gen_training_ops.ResourceSparseApplyKerasMomentum( + var=var.handle, + accum=momentum_var.handle, + lr=coefficients["lr_t"], + grad=grad, + indices=indices, + momentum=coefficients["momentum"], + use_locking=self._use_locking, + use_nesterov=self.nesterov) + + def get_config(self): + config = super(SGD, self).get_config() + config.update({ + "learning_rate": self._serialize_hyperparameter("learning_rate"), + "decay": self._initial_decay, + "momentum": self._serialize_hyperparameter("momentum"), + "nesterov": self.nesterov, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..7c701e321c8df65ca0746b4ef4305d6573658070 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py @@ -0,0 +1,1056 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Various learning rate decay functions.""" + +import abc +import math + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_case +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.util import nest + + +class LearningRateSchedule(object): + """The learning rate schedule base class. + + You can use a learning rate schedule to modulate how the learning rate + of your optimizer changes over time. + + Several built-in learning rate schedules are available, such as + `tf.keras.optimizers.schedules.ExponentialDecay` or + `tf.keras.optimizers.schedules.PiecewiseConstantDecay`: + + ```python + lr_schedule = keras.optimizers.schedules.ExponentialDecay( + initial_learning_rate=1e-2, + decay_steps=10000, + decay_rate=0.9) + optimizer = keras.optimizers.SGD(learning_rate=lr_schedule) + ``` + + A `LearningRateSchedule` instance can be passed in as the `learning_rate` + argument of any optimizer. + + To implement your own schedule object, you should implement the `__call__` + method, which takes a `step` argument (scalar integer tensor, the + current training step count). + Like for any other Keras object, you can also optionally + make your object serializable by implementing the `get_config` + and `from_config` methods. + + Example: + + ```python + class MyLRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): + + def __init__(self, initial_learning_rate): + self.initial_learning_rate = initial_learning_rate + + def __call__(self, step): + return self.initial_learning_rate / (step + 1) + + optimizer = tf.keras.optimizers.SGD(learning_rate=MyLRSchedule(0.1)) + ``` + """ + + @abc.abstractmethod + def __call__(self, step): + raise NotImplementedError("Learning rate schedule must override __call__") + + @abc.abstractmethod + def get_config(self): + raise NotImplementedError("Learning rate schedule must override get_config") + + @classmethod + def from_config(cls, config): + """Instantiates a `LearningRateSchedule` from its config. + + Args: + config: Output of `get_config()`. + + Returns: + A `LearningRateSchedule` instance. + """ + return cls(**config) + + +class ExponentialDecay(LearningRateSchedule): + """A LearningRateSchedule that uses an exponential decay schedule. + + When training a model, it is often useful to lower the learning rate as + the training progresses. This schedule applies an exponential decay function + to an optimizer step, given a provided initial learning rate. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + return initial_learning_rate * decay_rate ^ (step / decay_steps) + ``` + + If the argument `staircase` is `True`, then `step / decay_steps` is + an integer division and the decayed learning rate follows a + staircase function. + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. + Example: When fitting a Keras model, decay every 100000 steps with a base + of 0.96: + + ```python + initial_learning_rate = 0.1 + lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( + initial_learning_rate, + decay_steps=100000, + decay_rate=0.96, + staircase=True) + + model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=lr_schedule), + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + + model.fit(data, labels, epochs=5) + ``` + + The learning rate schedule is also serializable and deserializable using + `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + decay_rate, + staircase=False, + name=None): + """Applies exponential decay to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a + Python number. The initial learning rate. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Must be positive. See the decay computation above. + decay_rate: A scalar `float32` or `float64` `Tensor` or a + Python number. The decay rate. + staircase: Boolean. If `True` decay the learning rate at discrete + intervals + name: String. Optional name of the operation. Defaults to + 'ExponentialDecay'. + """ + super(ExponentialDecay, self).__init__() + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.decay_rate = decay_rate + self.staircase = staircase + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "ExponentialDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + decay_steps = math_ops.cast(self.decay_steps, dtype) + decay_rate = math_ops.cast(self.decay_rate, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + p = global_step_recomp / decay_steps + if self.staircase: + p = math_ops.floor(p) + return math_ops.multiply( + initial_learning_rate, math_ops.pow(decay_rate, p), name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "decay_rate": self.decay_rate, + "staircase": self.staircase, + "name": self.name + } + + +class PiecewiseConstantDecay(LearningRateSchedule): + """A LearningRateSchedule that uses a piecewise constant decay schedule. + + The function returns a 1-arg callable to compute the piecewise constant + when passed the current optimizer step. This can be useful for changing the + learning rate value across different invocations of optimizer functions. + + Example: use a learning rate that's 1.0 for the first 100001 steps, 0.5 + for the next 10000 steps, and 0.1 for any additional steps. + + ```python + step = tf.Variable(0, trainable=False) + boundaries = [100000, 110000] + values = [1.0, 0.5, 0.1] + learning_rate_fn = keras.optimizers.schedules.PiecewiseConstantDecay( + boundaries, values) + + # Later, whenever we perform an optimization step, we pass in the step. + learning_rate = learning_rate_fn(step) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. The learning rate schedule is also serializable and + deserializable using `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as the boundary tensors. + + The output of the 1-arg function that takes the `step` + is `values[0]` when `step <= boundaries[0]`, + `values[1]` when `step > boundaries[0]` and `step <= boundaries[1]`, ..., + and values[-1] when `step > boundaries[-1]`. + """ + + def __init__( + self, + boundaries, + values, + name=None): + """Piecewise constant from boundaries and interval values. + + Args: + boundaries: A list of `Tensor`s or `int`s or `float`s with strictly + increasing entries, and with all elements having the same type as the + optimizer step. + values: A list of `Tensor`s or `float`s or `int`s that specifies the + values for the intervals defined by `boundaries`. It should have one + more element than `boundaries`, and all elements should have the same + type. + name: A string. Optional name of the operation. Defaults to + 'PiecewiseConstant'. + + Raises: + ValueError: if the number of elements in the lists do not match. + """ + super(PiecewiseConstantDecay, self).__init__() + + if len(boundaries) != len(values) - 1: + raise ValueError( + "The length of boundaries should be 1 less than the length of values") + + self.boundaries = boundaries + self.values = values + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "PiecewiseConstant"): + boundaries = nest.map_structure( + tensor_conversion.convert_to_tensor_v2_with_dispatch, + nest.flatten(self.boundaries), + ) + values = nest.map_structure( + tensor_conversion.convert_to_tensor_v2_with_dispatch, + nest.flatten(self.values), + ) + x_recomp = tensor_conversion.convert_to_tensor_v2_with_dispatch(step) + for i, b in enumerate(boundaries): + if b.dtype.base_dtype != x_recomp.dtype.base_dtype: + # We cast the boundaries to have the same type as the step + b = math_ops.cast(b, x_recomp.dtype.base_dtype) + boundaries[i] = b + pred_fn_pairs = [] + pred_fn_pairs.append((x_recomp <= boundaries[0], lambda: values[0])) + pred_fn_pairs.append((x_recomp > boundaries[-1], lambda: values[-1])) + for low, high, v in zip(boundaries[:-1], boundaries[1:], values[1:-1]): + # Need to bind v here; can do this with lambda v=v: ... + pred = (x_recomp > low) & (x_recomp <= high) + pred_fn_pairs.append((pred, lambda v=v: v)) + + # The default isn't needed here because our conditions are mutually + # exclusive and exhaustive, but tf.case requires it. + default = lambda: values[0] + return control_flow_case.case(pred_fn_pairs, default, exclusive=True) + + def get_config(self): + return { + "boundaries": self.boundaries, + "values": self.values, + "name": self.name + } + + +class PolynomialDecay(LearningRateSchedule): + """A LearningRateSchedule that uses a polynomial decay schedule. + + It is commonly observed that a monotonically decreasing learning rate, whose + degree of change is carefully chosen, results in a better performing model. + This schedule applies a polynomial decay function to an optimizer step, + given a provided `initial_learning_rate`, to reach an `end_learning_rate` + in the given `decay_steps`. + + It requires a `step` value to compute the decayed learning rate. You + can just pass a TensorFlow variable that you increment at each training + step. + + The schedule is a 1-arg callable that produces a decayed learning rate + when passed the current optimizer step. This can be useful for changing the + learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + step = min(step, decay_steps) + return ((initial_learning_rate - end_learning_rate) * + (1 - step / decay_steps) ^ (power) + ) + end_learning_rate + ``` + + If `cycle` is True then a multiple of `decay_steps` is used, the first one + that is bigger than `step`. + + ```python + def decayed_learning_rate(step): + decay_steps = decay_steps * ceil(step / decay_steps) + return ((initial_learning_rate - end_learning_rate) * + (1 - step / decay_steps) ^ (power) + ) + end_learning_rate + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. + Example: Fit a model while decaying from 0.1 to 0.01 in 10000 steps using + sqrt (i.e. power=0.5): + + ```python + ... + starter_learning_rate = 0.1 + end_learning_rate = 0.01 + decay_steps = 10000 + learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay( + starter_learning_rate, + decay_steps, + end_learning_rate, + power=0.5) + + model.compile(optimizer=tf.keras.optimizers.SGD( + learning_rate=learning_rate_fn), + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + + model.fit(data, labels, epochs=5) + ``` + + The learning rate schedule is also serializable and deserializable using + `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + end_learning_rate=0.0001, + power=1.0, + cycle=False, + name=None): + """Applies a polynomial decay to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a + Python number. The initial learning rate. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Must be positive. See the decay computation above. + end_learning_rate: A scalar `float32` or `float64` `Tensor` or a + Python number. The minimal end learning rate. + power: A scalar `float32` or `float64` `Tensor` or a + Python number. The power of the polynomial. Defaults to linear, 1.0. + cycle: A boolean, whether or not it should cycle beyond decay_steps. + name: String. Optional name of the operation. Defaults to + 'PolynomialDecay'. + """ + super(PolynomialDecay, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.end_learning_rate = end_learning_rate + self.power = power + self.cycle = cycle + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "PolynomialDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + end_learning_rate = math_ops.cast(self.end_learning_rate, dtype) + power = math_ops.cast(self.power, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + decay_steps_recomp = math_ops.cast(self.decay_steps, dtype) + if self.cycle: + # Find the first multiple of decay_steps that is bigger than + # global_step. If global_step is zero set the multiplier to 1 + multiplier = array_ops.where_v2( + math_ops.equal(global_step_recomp, 0), 1.0, + math_ops.ceil(global_step_recomp / self.decay_steps)) + decay_steps_recomp = math_ops.multiply(decay_steps_recomp, multiplier) + else: + # Make sure that the global_step used is not bigger than decay_steps. + global_step_recomp = math_ops.minimum(global_step_recomp, + decay_steps_recomp) + + p = math_ops.divide(global_step_recomp, decay_steps_recomp) + return math_ops.add( + math_ops.multiply(initial_learning_rate - end_learning_rate, + math_ops.pow(1 - p, power)), + end_learning_rate, + name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "end_learning_rate": self.end_learning_rate, + "power": self.power, + "cycle": self.cycle, + "name": self.name + } + + +class InverseTimeDecay(LearningRateSchedule): + """A LearningRateSchedule that uses an inverse time decay schedule. + + When training a model, it is often useful to lower the learning rate as + the training progresses. This schedule applies the inverse decay function + to an optimizer step, given a provided initial learning rate. + It requires a `step` value to compute the decayed learning rate. You can + just pass a TensorFlow variable that you increment at each training step. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + return initial_learning_rate / (1 + decay_rate * step / decay_step) + ``` + + or, if `staircase` is `True`, as: + + ```python + def decayed_learning_rate(step): + return initial_learning_rate / (1 + decay_rate * floor(step / decay_step)) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. + Example: Fit a Keras model when decaying 1/t with a rate of 0.5: + + ```python + ... + initial_learning_rate = 0.1 + decay_steps = 1.0 + decay_rate = 0.5 + learning_rate_fn = keras.optimizers.schedules.InverseTimeDecay( + initial_learning_rate, decay_steps, decay_rate) + + model.compile(optimizer=tf.keras.optimizers.SGD( + learning_rate=learning_rate_fn), + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + + model.fit(data, labels, epochs=5) + ``` + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + decay_rate, + staircase=False, + name=None): + """Applies inverse time decay to the initial learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a + Python number. The initial learning rate. + decay_steps: How often to apply decay. + decay_rate: A Python number. The decay rate. + staircase: Whether to apply decay in a discrete staircase, as opposed to + continuous, fashion. + name: String. Optional name of the operation. Defaults to + 'InverseTimeDecay'. + """ + super(InverseTimeDecay, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.decay_rate = decay_rate + self.staircase = staircase + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "InverseTimeDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + decay_steps = math_ops.cast(self.decay_steps, dtype) + decay_rate = math_ops.cast(self.decay_rate, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + p = global_step_recomp / decay_steps + if self.staircase: + p = math_ops.floor(p) + const = math_ops.cast(constant_op.constant(1), dtype) + denom = math_ops.add(const, math_ops.multiply(decay_rate, p)) + return math_ops.divide(initial_learning_rate, denom, name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "decay_rate": self.decay_rate, + "staircase": self.staircase, + "name": self.name + } + + +class CosineDecay(LearningRateSchedule): + """A LearningRateSchedule that uses a cosine decay schedule. + + See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983), + SGDR: Stochastic Gradient Descent with Warm Restarts. + + When training a model, it is often useful to lower the learning rate as + the training progresses. This schedule applies a cosine decay function + to an optimizer step, given a provided initial learning rate. + It requires a `step` value to compute the decayed learning rate. You can + just pass a TensorFlow variable that you increment at each training step. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + step = min(step, decay_steps) + cosine_decay = 0.5 * (1 + cos(pi * step / decay_steps)) + decayed = (1 - alpha) * cosine_decay + alpha + return initial_learning_rate * decayed + ``` + + Example usage: + ```python + decay_steps = 1000 + lr_decayed_fn = tf.keras.optimizers.schedules.CosineDecay( + initial_learning_rate, decay_steps) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. The learning rate schedule is also serializable and + deserializable using `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + alpha=0.0, + name=None): + """Applies cosine decay to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` Tensor or a + Python number. The initial learning rate. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Number of steps to decay over. + alpha: A scalar `float32` or `float64` Tensor or a Python number. + Minimum learning rate value as a fraction of initial_learning_rate. + name: String. Optional name of the operation. Defaults to 'CosineDecay'. + """ + super(CosineDecay, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.alpha = alpha + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "CosineDecay"): + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + decay_steps = math_ops.cast(self.decay_steps, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + global_step_recomp = math_ops.minimum(global_step_recomp, decay_steps) + completed_fraction = global_step_recomp / decay_steps + cosine_decayed = 0.5 * (1.0 + math_ops.cos( + constant_op.constant(math.pi) * completed_fraction)) + + decayed = (1 - self.alpha) * cosine_decayed + self.alpha + return math_ops.multiply(initial_learning_rate, decayed) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "alpha": self.alpha, + "name": self.name + } + + +class CosineDecayRestarts(LearningRateSchedule): + """A LearningRateSchedule that uses a cosine decay schedule with restarts. + + See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983), + SGDR: Stochastic Gradient Descent with Warm Restarts. + + When training a model, it is often useful to lower the learning rate as + the training progresses. This schedule applies a cosine decay function with + restarts to an optimizer step, given a provided initial learning rate. + It requires a `step` value to compute the decayed learning rate. You can + just pass a TensorFlow variable that you increment at each training step. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + + The learning rate multiplier first decays + from 1 to `alpha` for `first_decay_steps` steps. Then, a warm + restart is performed. Each new warm restart runs for `t_mul` times more + steps and with `m_mul` times smaller initial learning rate. + + Example usage: + ```python + first_decay_steps = 1000 + lr_decayed_fn = ( + tf.keras.optimizers.schedules.CosineDecayRestarts( + initial_learning_rate, + first_decay_steps)) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. The learning rate schedule is also serializable and + deserializable using `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + first_decay_steps, + t_mul=2.0, + m_mul=1.0, + alpha=0.0, + name=None): + """Applies cosine decay with restarts to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` Tensor or a Python + number. The initial learning rate. + first_decay_steps: A scalar `int32` or `int64` `Tensor` or a Python + number. Number of steps to decay over. + t_mul: A scalar `float32` or `float64` `Tensor` or a Python number. + Used to derive the number of iterations in the i-th period + m_mul: A scalar `float32` or `float64` `Tensor` or a Python number. + Used to derive the initial learning rate of the i-th period: + alpha: A scalar `float32` or `float64` Tensor or a Python number. + Minimum learning rate value as a fraction of the initial_learning_rate. + name: String. Optional name of the operation. Defaults to 'SGDRDecay'. + """ + super(CosineDecayRestarts, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.first_decay_steps = first_decay_steps + self._t_mul = t_mul + self._m_mul = m_mul + self.alpha = alpha + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "SGDRDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + first_decay_steps = math_ops.cast(self.first_decay_steps, dtype) + alpha = math_ops.cast(self.alpha, dtype) + t_mul = math_ops.cast(self._t_mul, dtype) + m_mul = math_ops.cast(self._m_mul, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + completed_fraction = global_step_recomp / first_decay_steps + + def compute_step(completed_fraction, geometric=False): + """Helper for `cond` operation.""" + if geometric: + i_restart = math_ops.floor( + math_ops.log(1.0 - completed_fraction * (1.0 - t_mul)) / + math_ops.log(t_mul)) + + sum_r = (1.0 - t_mul**i_restart) / (1.0 - t_mul) + completed_fraction = (completed_fraction - sum_r) / t_mul**i_restart + + else: + i_restart = math_ops.floor(completed_fraction) + completed_fraction -= i_restart + + return i_restart, completed_fraction + + i_restart, completed_fraction = cond.cond( + math_ops.equal(t_mul, 1.0), + lambda: compute_step(completed_fraction, geometric=False), + lambda: compute_step(completed_fraction, geometric=True)) + + m_fac = m_mul**i_restart + cosine_decayed = 0.5 * m_fac * (1.0 + math_ops.cos( + constant_op.constant(math.pi) * completed_fraction)) + decayed = (1 - alpha) * cosine_decayed + alpha + + return math_ops.multiply(initial_learning_rate, decayed, name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "first_decay_steps": self.first_decay_steps, + "t_mul": self._t_mul, + "m_mul": self._m_mul, + "alpha": self.alpha, + "name": self.name + } + + +# Note: this code is still used by V1 APIs. +class LinearCosineDecay(LearningRateSchedule): + """A LearningRateSchedule that uses a linear cosine decay schedule. + + See [Bello et al., ICML2017] Neural Optimizer Search with RL. + https://arxiv.org/abs/1709.07417 + + For the idea of warm starts here controlled by `num_periods`, + see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent + with Warm Restarts. https://arxiv.org/abs/1608.03983 + + Note that linear cosine decay is more aggressive than cosine decay and + larger initial learning rates can typically be used. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This schedule applies a linear cosine decay + function to an optimizer step, given a provided initial learning rate. + It requires a `step` value to compute the decayed learning rate. You can + just pass a TensorFlow variable that you increment at each training step. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + step = min(step, decay_steps) + linear_decay = (decay_steps - step) / decay_steps + cosine_decay = 0.5 * ( + 1 + cos(pi * 2 * num_periods * step / decay_steps)) + decayed = (alpha + linear_decay) * cosine_decay + beta + return initial_learning_rate * decayed + ``` + + Example usage: + ```python + decay_steps = 1000 + lr_decayed_fn = ( + tf.keras.experimental.LinearCosineDecay( + initial_learning_rate, decay_steps)) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. The learning rate schedule is also serializable and + deserializable using `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + num_periods=0.5, + alpha=0.0, + beta=0.001, + name=None): + """Applies linear cosine decay to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` Tensor or a Python + number. The initial learning rate. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Number of steps to decay over. + num_periods: Number of periods in the cosine part of the decay. + See computation above. + alpha: See computation above. + beta: See computation above. + name: String. Optional name of the operation. Defaults to + 'LinearCosineDecay'. + """ + super(LinearCosineDecay, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.num_periods = num_periods + self.alpha = alpha + self.beta = beta + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "LinearCosineDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + decay_steps = math_ops.cast(self.decay_steps, dtype) + num_periods = math_ops.cast(self.num_periods, dtype) + alpha = math_ops.cast(self.alpha, dtype) + beta = math_ops.cast(self.beta, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + global_step_recomp = math_ops.minimum(global_step_recomp, decay_steps) + linear_decayed = (decay_steps - global_step_recomp) / decay_steps + completed_fraction = global_step_recomp / decay_steps + fraction = 2.0 * num_periods * completed_fraction + cosine_decayed = 0.5 * ( + 1.0 + math_ops.cos(constant_op.constant(math.pi) * fraction)) + + linear_cosine_decayed = (alpha + linear_decayed) * cosine_decayed + beta + return math_ops.multiply(initial_learning_rate, linear_cosine_decayed, + name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "num_periods": self.num_periods, + "alpha": self.alpha, + "beta": self.beta, + "name": self.name + } + + +# Note: this code is still used by V1 APIs. +class NoisyLinearCosineDecay(LearningRateSchedule): + """A LearningRateSchedule that uses a noisy linear cosine decay schedule. + + See [Bello et al., ICML2017] Neural Optimizer Search with RL. + https://arxiv.org/abs/1709.07417 + + For the idea of warm starts here controlled by `num_periods`, + see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent + with Warm Restarts. https://arxiv.org/abs/1608.03983 + + Note that linear cosine decay is more aggressive than cosine decay and + larger initial learning rates can typically be used. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This schedule applies a noisy linear cosine decay + function to an optimizer step, given a provided initial learning rate. + It requires a `step` value to compute the decayed learning rate. You can + just pass a TensorFlow variable that you increment at each training step. + + The schedule a 1-arg callable that produces a decayed learning + rate when passed the current optimizer step. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + It is computed as: + + ```python + def decayed_learning_rate(step): + step = min(step, decay_steps) + linear_decay = (decay_steps - step) / decay_steps) + cosine_decay = 0.5 * ( + 1 + cos(pi * 2 * num_periods * step / decay_steps)) + decayed = (alpha + linear_decay + eps_t) * cosine_decay + beta + return initial_learning_rate * decayed + ``` + where eps_t is 0-centered gaussian noise with variance + initial_variance / (1 + global_step) ** variance_decay + + Example usage: + ```python + decay_steps = 1000 + lr_decayed_fn = ( + tf.keras.experimental.NoisyLinearCosineDecay( + initial_learning_rate, decay_steps)) + ``` + + You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` + as the learning rate. The learning rate schedule is also serializable and + deserializable using `tf.keras.optimizers.schedules.serialize` and + `tf.keras.optimizers.schedules.deserialize`. + + Returns: + A 1-arg callable learning rate schedule that takes the current optimizer + step and outputs the decayed learning rate, a scalar `Tensor` of the same + type as `initial_learning_rate`. + """ + + def __init__( + self, + initial_learning_rate, + decay_steps, + initial_variance=1.0, + variance_decay=0.55, + num_periods=0.5, + alpha=0.0, + beta=0.001, + name=None): + """Applies noisy linear cosine decay to the learning rate. + + Args: + initial_learning_rate: A scalar `float32` or `float64` Tensor or a Python + number. The initial learning rate. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Number of steps to decay over. + initial_variance: initial variance for the noise. See computation above. + variance_decay: decay for the noise's variance. See computation above. + num_periods: Number of periods in the cosine part of the decay. + See computation above. + alpha: See computation above. + beta: See computation above. + name: String. Optional name of the operation. Defaults to + 'NoisyLinearCosineDecay'. + """ + super(NoisyLinearCosineDecay, self).__init__() + + self.initial_learning_rate = initial_learning_rate + self.decay_steps = decay_steps + self.initial_variance = initial_variance + self.variance_decay = variance_decay + self.num_periods = num_periods + self.alpha = alpha + self.beta = beta + self.name = name + + def __call__(self, step): + with ops.name_scope_v2(self.name or "NoisyLinearCosineDecay") as name: + initial_learning_rate = ( + tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.initial_learning_rate, name="initial_learning_rate" + ) + ) + dtype = initial_learning_rate.dtype + decay_steps = math_ops.cast(self.decay_steps, dtype) + initial_variance = math_ops.cast(self.initial_variance, dtype) + variance_decay = math_ops.cast(self.variance_decay, dtype) + num_periods = math_ops.cast(self.num_periods, dtype) + alpha = math_ops.cast(self.alpha, dtype) + beta = math_ops.cast(self.beta, dtype) + + global_step_recomp = math_ops.cast(step, dtype) + global_step_recomp = math_ops.minimum(global_step_recomp, decay_steps) + linear_decayed = (decay_steps - global_step_recomp) / decay_steps + variance = initial_variance / ( + math_ops.pow(1.0 + global_step_recomp, variance_decay)) + std = math_ops.sqrt(variance) + noisy_linear_decayed = ( + linear_decayed + random_ops.random_normal( + linear_decayed.shape, stddev=std)) + + completed_fraction = global_step_recomp / decay_steps + fraction = 2.0 * num_periods * completed_fraction + cosine_decayed = 0.5 * ( + 1.0 + math_ops.cos(constant_op.constant(math.pi) * fraction)) + noisy_linear_cosine_decayed = ( + (alpha + noisy_linear_decayed) * cosine_decayed + beta) + + return math_ops.multiply( + initial_learning_rate, noisy_linear_cosine_decayed, name=name) + + def get_config(self): + return { + "initial_learning_rate": self.initial_learning_rate, + "decay_steps": self.decay_steps, + "initial_variance": self.initial_variance, + "variance_decay": self.variance_decay, + "num_periods": self.num_periods, + "alpha": self.alpha, + "beta": self.beta, + "name": self.name + } + + +def serialize(learning_rate_schedule): + return generic_utils.serialize_keras_object(learning_rate_schedule) + + +def deserialize(config, custom_objects=None): + return generic_utils.deserialize_keras_object( + config, + module_objects=globals(), + custom_objects=custom_objects, + printable_module_name="decay") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/legacy_learning_rate_decay.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/legacy_learning_rate_decay.py new file mode 100644 index 0000000000000000000000000000000000000000..d60879f76e9e41a0a757060c24fcee0c1203e5ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/legacy_learning_rate_decay.py @@ -0,0 +1,774 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Various learning rate decay functions.""" + +import functools + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["train.exponential_decay"]) +def exponential_decay(learning_rate, + global_step, + decay_steps, + decay_rate, + staircase=False, + name=None): + """Applies exponential decay to the learning rate. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies an exponential decay function + to a provided initial learning rate. It requires a `global_step` value to + compute the decayed learning rate. You can just pass a TensorFlow variable + that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + + ```python + decayed_learning_rate = learning_rate * + decay_rate ^ (global_step / decay_steps) + ``` + + If the argument `staircase` is `True`, then `global_step / decay_steps` is an + integer division and the decayed learning rate follows a staircase function. + + Example: decay every 100000 steps with a base of 0.96: + + ```python + ... + global_step = tf.Variable(0, trainable=False) + starter_learning_rate = 0.1 + learning_rate = tf.compat.v1.train.exponential_decay(starter_learning_rate, + global_step, + 100000, 0.96, staircase=True) + # Passing global_step to minimize() will increment it at each step. + learning_step = ( + tf.compat.v1.train.GradientDescentOptimizer(learning_rate) + .minimize(...my loss..., global_step=global_step) + ) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. Must not be negative. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Must + be positive. See the decay computation above. + decay_rate: A scalar `float32` or `float64` `Tensor` or a Python number. + The decay rate. + staircase: Boolean. If `True` decay the learning rate at discrete intervals + name: String. Optional name of the operation. Defaults to + 'ExponentialDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + + Raises: + ValueError: if `global_step` is not supplied. + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.ExponentialDecay( + learning_rate, decay_steps, decay_rate, staircase=staircase, name=name) + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.piecewise_constant_decay", "train.piecewise_constant"]) +def piecewise_constant(x, boundaries, values, name=None): + """Piecewise constant from boundaries and interval values. + + Example: use a learning rate that's 1.0 for the first 100001 steps, 0.5 + for the next 10000 steps, and 0.1 for any additional steps. + + ```python + global_step = tf.Variable(0, trainable=False) + boundaries = [100000, 110000] + values = [1.0, 0.5, 0.1] + learning_rate = tf.compat.v1.train.piecewise_constant(global_step, boundaries, + values) + + # Later, whenever we perform an optimization step, we increment global_step. + ``` + + Args: + x: A 0-D scalar `Tensor`. Must be one of the following types: `float32`, + `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`. + boundaries: A list of `Tensor`s or `int`s or `float`s with strictly + increasing entries, and with all elements having the same type as `x`. + values: A list of `Tensor`s or `float`s or `int`s that specifies the values + for the intervals defined by `boundaries`. It should have one more element + than `boundaries`, and all elements should have the same type. + name: A string. Optional name of the operation. Defaults to + 'PiecewiseConstant'. + + Returns: + A 0-D Tensor. Its value is `values[0]` when `x <= boundaries[0]`, + `values[1]` when `x > boundaries[0]` and `x <= boundaries[1]`, ..., + and values[-1] when `x > boundaries[-1]`. + + Raises: + ValueError: if types of `x` and `boundaries` do not match, or types of all + `values` do not match or + the number of elements in the lists does not match. + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + boundaries = nest.map_structure( + tensor_conversion.convert_to_tensor_v2_with_dispatch, + nest.flatten(boundaries), + ) + values = nest.map_structure( + tensor_conversion.convert_to_tensor_v2_with_dispatch, nest.flatten(values) + ) + x_recomp = tensor_conversion.convert_to_tensor_v2_with_dispatch(x) + # Avoid explicit conversion to x's dtype. This could result in faulty + # comparisons, for example if floats are converted to integers. + for i, b in enumerate(boundaries): + if b.dtype.base_dtype != x_recomp.dtype.base_dtype: + # We can promote int32 boundaries to int64 without loss of precision. + # This covers the most common case where the user passes in boundaries + # as an array of Python integers. + if (b.dtype.base_dtype == dtypes.int32 and + x_recomp.dtype.base_dtype == dtypes.int64): + b = math_ops.cast(b, x_recomp.dtype.base_dtype) + boundaries[i] = b + else: + raise ValueError( + "Boundaries (%s) must have the same dtype as x (%s)." % + (b.dtype.base_dtype, x_recomp.dtype.base_dtype)) + for v in values[1:]: + if v.dtype.base_dtype != values[0].dtype.base_dtype: + raise ValueError( + "Values must have elements all with the same dtype (%s vs %s)." % + (values[0].dtype.base_dtype, v.dtype.base_dtype)) + decayed_lr = learning_rate_schedule.PiecewiseConstantDecay( + boundaries, values, name=name) + if not context.executing_eagerly(): + decayed_lr = decayed_lr(x) + else: + decayed_lr = functools.partial(decayed_lr, x) + return decayed_lr + + +@tf_export(v1=["train.polynomial_decay"]) +def polynomial_decay(learning_rate, + global_step, + decay_steps, + end_learning_rate=0.0001, + power=1.0, + cycle=False, + name=None): + """Applies a polynomial decay to the learning rate. + + It is commonly observed that a monotonically decreasing learning rate, whose + degree of change is carefully chosen, results in a better performing model. + This function applies a polynomial decay function to a provided initial + `learning_rate` to reach an `end_learning_rate` in the given `decay_steps`. + + It requires a `global_step` value to compute the decayed learning rate. You + can just pass a TensorFlow variable that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + + ```python + global_step = min(global_step, decay_steps) + decayed_learning_rate = (learning_rate - end_learning_rate) * + (1 - global_step / decay_steps) ^ (power) + + end_learning_rate + + ``` + + If `cycle` is True then a multiple of `decay_steps` is used, the first one + that is bigger than `global_steps`. + + ```python + decay_steps = decay_steps * ceil(global_step / decay_steps) + decayed_learning_rate = (learning_rate - end_learning_rate) * + (1 - global_step / decay_steps) ^ (power) + + end_learning_rate + + ``` + + Example: decay from 0.1 to 0.01 in 10000 steps using sqrt (i.e. power=0.5): + + ```python + ... + global_step = tf.Variable(0, trainable=False) + starter_learning_rate = 0.1 + end_learning_rate = 0.01 + decay_steps = 10000 + learning_rate = tf.compat.v1.train.polynomial_decay(starter_learning_rate, + global_step, + decay_steps, end_learning_rate, + power=0.5) + # Passing global_step to minimize() will increment it at each step. + learning_step = ( + tf.compat.v1.train.GradientDescentOptimizer(learning_rate) + .minimize(...my loss..., global_step=global_step) + ) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. Must not be negative. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Must + be positive. See the decay computation above. + end_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python + number. The minimal end learning rate. + power: A scalar `float32` or `float64` `Tensor` or a Python number. The + power of the polynomial. Defaults to linear, 1.0. + cycle: A boolean, whether or not it should cycle beyond decay_steps. + name: String. Optional name of the operation. Defaults to + 'PolynomialDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + + Raises: + ValueError: if `global_step` is not supplied. + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.PolynomialDecay( + learning_rate, + decay_steps, + end_learning_rate=end_learning_rate, + power=power, + cycle=cycle, + name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.natural_exp_decay"]) +def natural_exp_decay(learning_rate, + global_step, + decay_steps, + decay_rate, + staircase=False, + name=None): + """Applies natural exponential decay to the initial learning rate. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies an exponential decay function + to a provided initial learning rate. It requires an `global_step` value to + compute the decayed learning rate. You can just pass a TensorFlow variable + that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + + ```python + decayed_learning_rate = learning_rate * exp(-decay_rate * global_step / + decay_step) + ``` + + or, if `staircase` is `True`, as: + + ```python + decayed_learning_rate = learning_rate * exp(-decay_rate * floor(global_step / + decay_step)) + ``` + + Example: decay exponentially with a base of 0.96: + + ```python + ... + global_step = tf.Variable(0, trainable=False) + learning_rate = 0.1 + decay_steps = 5 + k = 0.5 + learning_rate = tf.compat.v1.train.natural_exp_decay(learning_rate, + global_step, + decay_steps, k) + + # Passing global_step to minimize() will increment it at each step. + learning_step = ( + tf.compat.v1.train.GradientDescentOptimizer(learning_rate) + .minimize(...my loss..., global_step=global_step) + ) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. + The initial learning rate. + global_step: A Python number. Global step to use for the decay computation. + Must not be negative. + decay_steps: How often to apply decay. + decay_rate: A Python number. The decay rate. + staircase: Whether to apply decay in a discrete staircase, as opposed to + continuous, fashion. + name: String. Optional name of the operation. Defaults to + 'ExponentialTimeDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + + Raises: + ValueError: if `global_step` is not supplied. + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + natural_exp_rate = math_ops.exp(math_ops.negative(decay_rate)) + decayed_lr = learning_rate_schedule.ExponentialDecay( + learning_rate, + decay_steps, + natural_exp_rate, + staircase=staircase, + name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.inverse_time_decay"]) +def inverse_time_decay(learning_rate, + global_step, + decay_steps, + decay_rate, + staircase=False, + name=None): + """Applies inverse time decay to the initial learning rate. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies an inverse decay function + to a provided initial learning rate. It requires an `global_step` value to + compute the decayed learning rate. You can just pass a TensorFlow variable + that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + + ```python + decayed_learning_rate = learning_rate / (1 + decay_rate * global_step / + decay_step) + ``` + + or, if `staircase` is `True`, as: + + ```python + decayed_learning_rate = learning_rate / (1 + decay_rate * floor(global_step / + decay_step)) + ``` + + Example: decay 1/t with a rate of 0.5: + + ```python + ... + global_step = tf.Variable(0, trainable=False) + learning_rate = 0.1 + decay_steps = 1.0 + decay_rate = 0.5 + learning_rate = tf.compat.v1.train.inverse_time_decay(learning_rate, + global_step, + decay_steps, decay_rate) + + # Passing global_step to minimize() will increment it at each step. + learning_step = ( + tf.compat.v1.train.GradientDescentOptimizer(learning_rate) + .minimize(...my loss..., global_step=global_step) + ) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. + The initial learning rate. + global_step: A Python number. Global step to use for the decay computation. + Must not be negative. + decay_steps: How often to apply decay. + decay_rate: A Python number. The decay rate. + staircase: Whether to apply decay in a discrete staircase, as opposed to + continuous, fashion. + name: String. Optional name of the operation. Defaults to + 'InverseTimeDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + + Raises: + ValueError: if `global_step` is not supplied. + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.InverseTimeDecay( + learning_rate, decay_steps, decay_rate, staircase=staircase, name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.cosine_decay"]) +def cosine_decay(learning_rate, global_step, decay_steps, alpha=0.0, name=None): + """Applies cosine decay to the learning rate. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies a cosine decay function + to a provided initial learning rate. It requires a `global_step` value to + compute the decayed learning rate. You can just pass a TensorFlow variable + that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + ```python + global_step = min(global_step, decay_steps) + cosine_decay = 0.5 * (1 + cos(pi * global_step / decay_steps)) + decayed = (1 - alpha) * cosine_decay + alpha + decayed_learning_rate = learning_rate * decayed + ``` + + Example usage: + ```python + decay_steps = 1000 + lr_decayed = cosine_decay(learning_rate, global_step, decay_steps) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` Tensor or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Number + of steps to decay over. + alpha: A scalar `float32` or `float64` Tensor or a Python number. Minimum + learning rate value as a fraction of learning_rate. + name: String. Optional name of the operation. Defaults to 'CosineDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + Raises: + ValueError: if `global_step` is not supplied. + + References: + Stochastic Gradient Descent with Warm Restarts: + [Loshchilov et al., 2017] + (https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) + ([pdf](https://openreview.net/pdf?id=Skq89Scxx)) + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.CosineDecay( + learning_rate, decay_steps, alpha=alpha, name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.cosine_decay_restarts"]) +def cosine_decay_restarts(learning_rate, + global_step, + first_decay_steps, + t_mul=2.0, + m_mul=1.0, + alpha=0.0, + name=None): + """Applies cosine decay with restarts to the learning rate. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies a cosine decay function with + restarts to a provided initial learning rate. It requires a `global_step` + value to compute the decayed learning rate. You can just pass a TensorFlow + variable that you increment at each training step. + + The function returns the decayed learning rate while taking into account + possible warm restarts. The learning rate multiplier first decays + from 1 to `alpha` for `first_decay_steps` steps. Then, a warm + restart is performed. Each new warm restart runs for `t_mul` times more steps + and with `m_mul` times smaller initial learning rate. + + Example usage: + ```python + first_decay_steps = 1000 + lr_decayed = cosine_decay_restarts(learning_rate, global_step, + first_decay_steps) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` Tensor or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. + first_decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. + Number of steps to decay over. + t_mul: A scalar `float32` or `float64` `Tensor` or a Python number. Used to + derive the number of iterations in the i-th period + m_mul: A scalar `float32` or `float64` `Tensor` or a Python number. + Used to derive the initial learning rate of the i-th period: + alpha: A scalar `float32` or `float64` Tensor or a Python number. Minimum + learning rate value as a fraction of the learning_rate. + name: String. Optional name of the operation. Defaults to 'SGDRDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + Raises: + ValueError: if `global_step` is not supplied. + + References: + Stochastic Gradient Descent with Warm Restarts: + [Loshchilov et al., 2017] + (https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) + ([pdf](https://openreview.net/pdf?id=Skq89Scxx)) + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.CosineDecayRestarts( + learning_rate, + first_decay_steps, + t_mul=t_mul, + m_mul=m_mul, + alpha=alpha, + name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.linear_cosine_decay"]) +def linear_cosine_decay(learning_rate, + global_step, + decay_steps, + num_periods=0.5, + alpha=0.0, + beta=0.001, + name=None): + """Applies linear cosine decay to the learning rate. + + Note that linear cosine decay is more aggressive than cosine decay and + larger initial learning rates can typically be used. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies a linear cosine decay function + to a provided initial learning rate. It requires a `global_step` value to + compute the decayed learning rate. You can just pass a TensorFlow variable + that you increment at each training step. + + The function returns the decayed learning rate. It is computed as: + ```python + global_step = min(global_step, decay_steps) + linear_decay = (decay_steps - global_step) / decay_steps) + cosine_decay = 0.5 * ( + 1 + cos(pi * 2 * num_periods * global_step / decay_steps)) + decayed = (alpha + linear_decay) * cosine_decay + beta + decayed_learning_rate = learning_rate * decayed + ``` + + Example usage: + ```python + decay_steps = 1000 + lr_decayed = linear_cosine_decay(learning_rate, global_step, decay_steps) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` Tensor or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Number + of steps to decay over. + num_periods: Number of periods in the cosine part of the decay. See + computation above. + alpha: See computation above. + beta: See computation above. + name: String. Optional name of the operation. Defaults to + 'LinearCosineDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + Raises: + ValueError: if `global_step` is not supplied. + + References: + Neural Optimizer Search with Reinforcement Learning: + [Bello et al., 2017](http://proceedings.mlr.press/v70/bello17a.html) + ([pdf](http://proceedings.mlr.press/v70/bello17a/bello17a.pdf)) + Stochastic Gradient Descent with Warm Restarts: + [Loshchilov et al., 2017] + (https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) + ([pdf](https://openreview.net/pdf?id=Skq89Scxx)) + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.LinearCosineDecay( + learning_rate, + decay_steps, + num_periods=num_periods, + alpha=alpha, + beta=beta, + name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr + + +@tf_export(v1=["train.noisy_linear_cosine_decay"]) +def noisy_linear_cosine_decay(learning_rate, + global_step, + decay_steps, + initial_variance=1.0, + variance_decay=0.55, + num_periods=0.5, + alpha=0.0, + beta=0.001, + name=None): + """Applies noisy linear cosine decay to the learning rate. + + Note that linear cosine decay is more aggressive than cosine decay and + larger initial learning rates can typically be used. + + When training a model, it is often recommended to lower the learning rate as + the training progresses. This function applies a noisy linear + cosine decay function to a provided initial learning rate. + It requires a `global_step` value to compute the decayed learning rate. + You can just pass a TensorFlow variable that you increment at each + training step. + + The function returns the decayed learning rate. It is computed as: + ```python + global_step = min(global_step, decay_steps) + linear_decay = (decay_steps - global_step) / decay_steps) + cosine_decay = 0.5 * ( + 1 + cos(pi * 2 * num_periods * global_step / decay_steps)) + decayed = (alpha + linear_decay + eps_t) * cosine_decay + beta + decayed_learning_rate = learning_rate * decayed + ``` + where eps_t is 0-centered gaussian noise with variance + initial_variance / (1 + global_step) ** variance_decay + + Example usage: + ```python + decay_steps = 1000 + lr_decayed = noisy_linear_cosine_decay( + learning_rate, global_step, decay_steps) + ``` + + Args: + learning_rate: A scalar `float32` or `float64` Tensor or a Python number. + The initial learning rate. + global_step: A scalar `int32` or `int64` `Tensor` or a Python number. Global + step to use for the decay computation. + decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Number + of steps to decay over. + initial_variance: initial variance for the noise. See computation above. + variance_decay: decay for the noise's variance. See computation above. + num_periods: Number of periods in the cosine part of the decay. See + computation above. + alpha: See computation above. + beta: See computation above. + name: String. Optional name of the operation. Defaults to + 'NoisyLinearCosineDecay'. + + Returns: + A scalar `Tensor` of the same type as `learning_rate`. The decayed + learning rate. + Raises: + ValueError: if `global_step` is not supplied. + + References: + Neural Optimizer Search with Reinforcement Learning: + [Bello et al., 2017](http://proceedings.mlr.press/v70/bello17a.html) + ([pdf](http://proceedings.mlr.press/v70/bello17a/bello17a.pdf)) + Stochastic Gradient Descent with Warm Restarts: + [Loshchilov et al., 2017] + (https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) + ([pdf](https://openreview.net/pdf?id=Skq89Scxx)) + + @compatibility(eager) + When eager execution is enabled, this function returns a function which in + turn returns the decayed learning rate Tensor. This can be useful for changing + the learning rate value across different invocations of optimizer functions. + @end_compatibility + """ + decayed_lr = learning_rate_schedule.NoisyLinearCosineDecay( + learning_rate, + decay_steps, + initial_variance=initial_variance, + variance_decay=variance_decay, + num_periods=num_periods, + alpha=alpha, + beta=beta, + name=name) + + if not context.executing_eagerly(): + decayed_lr = decayed_lr(global_step) + else: + decayed_lr = functools.partial(decayed_lr, global_step) + return decayed_lr diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/nadam.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/nadam.py new file mode 100644 index 0000000000000000000000000000000000000000..1440c6aaaabf43d8176d93aed7a5c1b50db25d9f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/nadam.py @@ -0,0 +1,220 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Nadam optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variables as tf_variables + + +class Nadam(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the NAdam algorithm. + Much like Adam is essentially RMSprop with momentum, Nadam is Adam with + Nesterov momentum. + + Args: + learning_rate: A Tensor or a floating point value. The learning rate. + beta_1: A float value or a constant float tensor. The exponential decay + rate for the 1st moment estimates. + beta_2: A float value or a constant float tensor. The exponential decay + rate for the exponentially weighted infinity norm. + epsilon: A small constant for numerical stability. + name: Optional name for the operations created when applying gradients. + Defaults to `"Nadam"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Usage Example: + >>> opt = tf.keras.optimizers.Nadam(learning_rate=0.2) + >>> var1 = tf.Variable(10.0) + >>> loss = lambda: (var1 ** 2) / 2.0 + >>> step_count = opt.minimize(loss, [var1]).numpy() + >>> "{:.1f}".format(var1.numpy()) + 9.8 + + Reference: + - [Dozat, 2015](http://cs229.stanford.edu/proj2015/054_report.pdf). + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-7, + name='Nadam', + **kwargs): + # Backwards compatibility with keras NAdam optimizer. + kwargs['decay'] = kwargs.pop('schedule_decay', 0.004) + learning_rate = kwargs.get('lr', learning_rate) + if isinstance(learning_rate, learning_rate_schedule.LearningRateSchedule): + raise ValueError('The Nadam optimizer does not support ' + 'tf.keras.optimizers.LearningRateSchedules as the ' + 'learning rate.') + + super(Nadam, self).__init__(name, **kwargs) + self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) + self._set_hyper('decay', self._initial_decay) + self._set_hyper('beta_1', beta_1) + self._set_hyper('beta_2', beta_2) + self.epsilon = epsilon or backend_config.epsilon() + self._m_cache = None + + def _create_slots(self, var_list): + var_dtype = var_list[0].dtype.base_dtype + if self._m_cache is None: + self._m_cache = self.add_weight( + 'momentum_cache', + shape=[], + dtype=var_dtype, + initializer='ones', + trainable=False, + aggregation=tf_variables.VariableAggregation.ONLY_FIRST_REPLICA) + self._weights.append(self._m_cache) + # Separate for-loops to respect the ordering of slot variables from v1. + for var in var_list: + # Create slots for the first moments. + self.add_slot(var, 'm') + for var in var_list: + # Create slots for the second moments. + self.add_slot(var, 'v') + + def _prepare_local(self, var_device, var_dtype, apply_state): + lr_t = array_ops.identity(self._get_hyper('learning_rate', var_dtype)) + beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) + beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) + local_step = math_ops.cast(self.iterations + 1, var_dtype) + next_step = math_ops.cast(self.iterations + 2, var_dtype) + + decay_base = math_ops.cast(0.96, var_dtype) + + m_t = beta_1_t * (1. - 0.5 * ( + math_ops.pow(decay_base, self._initial_decay * local_step))) + m_t_1 = beta_1_t * (1. - 0.5 * ( + math_ops.pow(decay_base, self._initial_decay * next_step))) + + m_schedule_new = math_ops.cast(self._m_cache_read, var_dtype) * m_t + if var_dtype is self._m_cache.dtype: + m_schedule_new = array_ops.identity(state_ops.assign( + self._m_cache, m_schedule_new, use_locking=self._use_locking)) + m_schedule_next = m_schedule_new * m_t_1 + + apply_state[(var_device, var_dtype)] = dict( + lr_t=lr_t, + neg_lr_t=-lr_t, # pylint: disable=invalid-unary-operand-type + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + beta_1_t=beta_1_t, + beta_2_t=beta_2_t, + m_t=m_t, + m_t_1=m_t_1, + one_minus_beta_1_t=1 - beta_1_t, + one_minus_beta_2_t=1 - beta_2_t, + one_minus_m_t=1.0 - m_t, + one_minus_m_schedule_new=1.0 - m_schedule_new, + one_minus_m_schedule_next=1.0 - m_schedule_next, + v_t_prime_denominator=1.0 - math_ops.pow(beta_2_t, local_step), + ) + + def _prepare(self, var_list): + # Get the value of the momentum cache before starting to apply gradients. + self._m_cache_read = array_ops.identity(self._m_cache) + return super(Nadam, self)._prepare(var_list) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + m = self.get_slot(var, 'm') + v = self.get_slot(var, 'v') + + g_prime = grad / coefficients['one_minus_m_schedule_new'] + m_t = (coefficients['beta_1_t'] * m + + coefficients['one_minus_beta_1_t'] * grad) + m_t = state_ops.assign(m, m_t, use_locking=self._use_locking) + m_t_prime = m_t / coefficients['one_minus_m_schedule_next'] + v_t = (coefficients['beta_2_t'] * v + + coefficients['one_minus_beta_2_t'] * math_ops.square(grad)) + v_t = state_ops.assign(v, v_t, use_locking=self._use_locking) + v_t_prime = v_t / coefficients['v_t_prime_denominator'] + m_t_bar = (coefficients['one_minus_m_t'] * g_prime + + coefficients['m_t_1'] * m_t_prime) + var_t = var - coefficients['lr_t'] * m_t_bar / ( + math_ops.sqrt(v_t_prime) + coefficients['epsilon']) + return state_ops.assign(var, var_t, use_locking=self._use_locking).op + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + m = self.get_slot(var, 'm') + v = self.get_slot(var, 'v') + + g_prime = grad / coefficients['one_minus_m_schedule_new'] + + # m_t = beta1 * m + (1 - beta1) * g_t + m_scaled_g_values = grad * coefficients['one_minus_beta_1_t'] + m_t = state_ops.assign(m, m * coefficients['beta_1_t'], + use_locking=self._use_locking) + + with ops.control_dependencies([m_t]): + m_t = self._resource_scatter_add(m, indices, m_scaled_g_values) + m_t_slice = array_ops.gather(m_t, indices) + + m_t_prime = m_t_slice / coefficients['one_minus_m_schedule_next'] + m_t_bar = (coefficients['one_minus_m_t'] * g_prime + + coefficients['m_t_1'] * m_t_prime) + + # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) + v_scaled_g_values = (grad * grad) * coefficients['one_minus_beta_2_t'] + v_t = state_ops.assign(v, v * coefficients['beta_2_t'], + use_locking=self._use_locking) + + with ops.control_dependencies([v_t]): + v_t = self._resource_scatter_add(v, indices, v_scaled_g_values) + v_t_slice = array_ops.gather(v_t, indices) + + v_t_prime = v_t_slice / coefficients['v_t_prime_denominator'] + v_prime_sqrt_plus_eps = math_ops.sqrt(v_t_prime) + coefficients['epsilon'] + + var_update = self._resource_scatter_add( + var, indices, + coefficients['neg_lr_t'] * m_t_bar / v_prime_sqrt_plus_eps) + return control_flow_ops.group(*[var_update, m_t_bar, v_t]) + + def get_config(self): + config = super(Nadam, self).get_config() + config.update({ + 'learning_rate': self._serialize_hyperparameter('learning_rate'), + 'decay': self._initial_decay, + 'beta_1': self._serialize_hyperparameter('beta_1'), + 'beta_2': self._serialize_hyperparameter('beta_2'), + 'epsilon': self.epsilon, + }) + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d239d49951346a5523517c2950c56cca68c0fec3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py @@ -0,0 +1,1480 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Version 2 of class Optimizer.""" +# pylint: disable=g-bad-name + +import abc +import contextlib +import functools +import warnings + +from tensorflow.python.distribute import central_storage_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import parameter_server_strategy +from tensorflow.python.distribute import parameter_server_strategy_v2 +from tensorflow.python.distribute import values as ds_values +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import initializers +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule +from tensorflow.python.keras.optimizer_v2 import utils as optimizer_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import layer_utils +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gradients +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.saved_model import revived_types +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import nest + + +_DEFAULT_VALID_DTYPES = frozenset([ + dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, + dtypes.complex64, dtypes.complex128 +]) + + +def _deduplicate_indexed_slices(values, indices): + """Sums `values` associated with any non-unique `indices`. + + Args: + values: A `Tensor` with rank >= 1. + indices: A one-dimensional integer `Tensor`, indexing into the first + dimension of `values` (as in an IndexedSlices object). + + Returns: + A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a + de-duplicated version of `indices` and `summed_values` contains the sum of + `values` slices associated with each unique index. + """ + unique_indices, new_index_positions = array_ops.unique(indices) + summed_values = math_ops.unsorted_segment_sum( + values, new_index_positions, + array_ops.shape(unique_indices)[0]) + return (summed_values, unique_indices) + + +class NullContextmanager(object): + + def __init__(self, *args, **kwargs): + pass + + def __enter__(self): + pass + + def __exit__(self, type_arg, value_arg, traceback_arg): + return False # False values do not suppress exceptions + + +def name_scope_only_in_function_or_graph(name): + """Internal-only entry point for `name_scope*`. + + Enters a compat.v1.name_scope only when in a function or graph, + not when running fully eagerly. + + Args: + name: The name argument that is passed to the op function. + + Returns: + `name_scope*` context manager. + """ + if not context.executing_eagerly(): + return ops.name_scope_v1(name) + else: + return NullContextmanager() + + +class OptimizerV2(trackable.Trackable): + """Base class for Keras optimizers. + + You should not use this class directly, but instead instantiate one of its + subclasses such as `tf.keras.optimizers.SGD`, `tf.keras.optimizers.Adam`, etc. + + ### Usage + + ```python + # Create an optimizer with the desired parameters. + opt = tf.keras.optimizers.SGD(learning_rate=0.1) + # `loss` is a callable that takes no argument and returns the value + # to minimize. + loss = lambda: 3 * var1 * var1 + 2 * var2 * var2 + # In graph mode, returns op that minimizes the loss by updating the listed + # variables. + opt_op = opt.minimize(loss, var_list=[var1, var2]) + opt_op.run() + # In eager mode, simply call minimize to update the list of variables. + opt.minimize(loss, var_list=[var1, var2]) + ``` + + ### Usage in custom training loops + + In Keras models, sometimes variables are created when the model is first + called, instead of construction time. Examples include 1) sequential models + without input shape pre-defined, or 2) subclassed models. Pass var_list as + callable in these cases. + + Example: + + ```python + opt = tf.keras.optimizers.SGD(learning_rate=0.1) + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(num_hidden, activation='relu')) + model.add(tf.keras.layers.Dense(num_classes, activation='sigmoid')) + loss_fn = lambda: tf.keras.losses.mse(model(input), output) + var_list_fn = lambda: model.trainable_weights + for input, output in data: + opt.minimize(loss_fn, var_list_fn) + ``` + + ### Processing gradients before applying them + + Calling `minimize()` takes care of both computing the gradients and + applying them to the variables. If you want to process the gradients + before applying them you can instead use the optimizer in three steps: + + 1. Compute the gradients with `tf.GradientTape`. + 2. Process the gradients as you wish. + 3. Apply the processed gradients with `apply_gradients()`. + + Example: + + ```python + # Create an optimizer. + opt = tf.keras.optimizers.SGD(learning_rate=0.1) + + # Compute the gradients for a list of variables. + with tf.GradientTape() as tape: + loss = + vars = + grads = tape.gradient(loss, vars) + + # Process the gradients, for example cap them, etc. + # capped_grads = [MyCapper(g) for g in grads] + processed_grads = [process_gradient(g) for g in grads] + + # Ask the optimizer to apply the processed gradients. + opt.apply_gradients(zip(processed_grads, var_list)) + ``` + + ### Use with `tf.distribute.Strategy` + + This optimizer class is `tf.distribute.Strategy` aware, which means it + automatically sums gradients across all replicas. To average gradients, + you divide your loss by the global batch size, which is done + automatically if you use `tf.keras` built-in training or evaluation loops. + See the `reduction` argument of your loss which should be set to + `tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE` for averaging or + `tf.keras.losses.Reduction.SUM` for not. + + To aggregate gradients yourself, call `apply_gradients` with + `experimental_aggregate_gradients` set to False. This is useful if you need to + process aggregated gradients. + + If you are not using these and you want to average gradients, you should use + `tf.math.reduce_sum` to add up your per-example losses and then divide by the + global batch size. Note that when using `tf.distribute.Strategy`, the first + component of a tensor's shape is the *replica-local* batch size, which is off + by a factor equal to the number of replicas being used to compute a single + step. As a result, using `tf.math.reduce_mean` will give the wrong answer, + resulting in gradients that can be many times too big. + + ### Variable Constraints + + All Keras optimizers respect variable constraints. If constraint function is + passed to any variable, the constraint will be applied to the variable after + the gradient has been applied to the variable. + Important: If gradient is sparse tensor, variable constraint is not supported. + + ### Thread Compatibility + + The entire optimizer is currently thread compatible, not thread-safe. The user + needs to perform synchronization if necessary. + + ### Slots + + Many optimizer subclasses, such as `Adam` and `Adagrad` allocate and manage + additional variables associated with the variables to train. These are called + Slots. Slots have names and you can ask the optimizer for the names of + the slots that it uses. Once you have a slot name you can ask the optimizer + for the variable it created to hold the slot value. + + This can be useful if you want to log debug a training algorithm, report stats + about the slots, etc. + + ### Hyperparameters + + These are arguments passed to the optimizer subclass constructor + (the `__init__` method), and then passed to `self._set_hyper()`. + They can be either regular Python values (like 1.0), tensors, or + callables. If they are callable, the callable will be called during + `apply_gradients()` to get the value for the hyper parameter. + + Hyperparameters can be overwritten through user code: + + Example: + + ```python + # Create an optimizer with the desired parameters. + opt = tf.keras.optimizers.SGD(learning_rate=0.1) + # `loss` is a callable that takes no argument and returns the value + # to minimize. + loss = lambda: 3 * var1 + 2 * var2 + # In eager mode, simply call minimize to update the list of variables. + opt.minimize(loss, var_list=[var1, var2]) + # update learning rate + opt.learning_rate = 0.05 + opt.minimize(loss, var_list=[var1, var2]) + ``` + + ### Callable learning rate + + Optimizer accepts a callable learning rate in two ways. The first way is + through built-in or customized + `tf.keras.optimizers.schedules.LearningRateSchedule`. The schedule will be + called on each iteration with `schedule(iteration)`, a `tf.Variable` + owned by the optimizer. + + Example: + + >>> var = tf.Variable(np.random.random(size=(1,))) + >>> learning_rate = tf.keras.optimizers.schedules.ExponentialDecay( + ... initial_learning_rate=.01, decay_steps=20, decay_rate=.1) + >>> opt = tf.keras.optimizers.SGD(learning_rate=learning_rate) + >>> loss = lambda: 3 * var + >>> opt.minimize(loss, var_list=[var]) + >> var = tf.Variable(np.random.random(size=(1,))) + >>> def lr_callable(): + ... return .1 + >>> opt = tf.keras.optimizers.SGD(learning_rate=lr_callable) + >>> loss = lambda: 3 * var + >>> opt.minimize(loss, var_list=[var]) + = 0, received: {}".format(k, kwargs[k])) + if k == "lr": + warnings.warn( + "The `lr` argument is deprecated, use `learning_rate` instead.") + + self._use_locking = True + self._init_set_name(name) + self._hyper = {} + # dict: {variable name : {slot name : variable}} + self._slots = {} + self._slot_names = [] + self._weights = [] + self._iterations = None + + # For implementing Trackable. Stores information about how to restore + # slot variables which have not yet been created + # (trackable._CheckpointPosition objects). + # {slot_name : + # {_var_key(variable_to_train): [checkpoint_position, ... ], ... }, + # ... } + self._deferred_slot_restorations = {} + + decay = kwargs.pop("decay", 0.0) + if decay < 0.: + raise ValueError("decay cannot be less than 0: {}".format(decay)) + self._initial_decay = decay + + self._hypers_created = False + # Store the distribution strategy object if the optimizer is created inside + # strategy scope, so it could be used to create variables later. + if distribute_lib.has_strategy(): + self._distribution_strategy = distribute_lib.get_strategy() + else: + self._distribution_strategy = None + + # Configure gradient transformations. + if gradient_aggregator is None: + gradient_aggregator = optimizer_utils.all_reduce_sum_gradients + self.gradient_aggregator = gradient_aggregator + if gradient_transformers is None: + gradient_transformers = [] + self.gradient_transformers = gradient_transformers + self.clipnorm = kwargs.pop("clipnorm", None) + self.global_clipnorm = kwargs.pop("global_clipnorm", None) + if self.clipnorm is not None and self.global_clipnorm is not None: + raise ValueError("Cannot accept both `clipnorm` and `global_clipnorm`, " + "passed `clipnorm` {}, `global_clipnorm` {}".format( + self.clipnorm, self.global_clipnorm)) + self.clipvalue = kwargs.pop("clipvalue", None) + + @property + def clipnorm(self): + """`float` or `None`. If set, clips gradients to a maximum norm.""" + return self._clipnorm + + @property + def global_clipnorm(self): + """`float` or `None`. If set, clips gradients to a maximum norm.""" + return self._global_clipnorm + + @clipnorm.setter + def clipnorm(self, val): + if val is not None and self.gradient_transformers: + raise ValueError("`clipnorm` cannot be set when `gradient_transformers` " + "is set. Instead, use the `gradient_transformers` to " + "specify clipping and other transformations.") + self._clipnorm = val + self._clipnorm_fn = optimizer_utils.make_gradient_clipnorm_fn( + self._clipnorm) + + @global_clipnorm.setter + def global_clipnorm(self, val): + if val is not None and self.gradient_transformers: + raise ValueError("`clipnorm` cannot be set when `gradient_transformers` " + "is set. Instead, use the `gradient_transformers` to " + "specify clipping and other transformations.") + self._global_clipnorm = val + self._global_clipnorm_fn = optimizer_utils.make_global_gradient_clipnorm_fn( + self._global_clipnorm) + + @property + def clipvalue(self): + """`float` or `None`. If set, clips gradients to a maximum value.""" + return self._clipvalue + + @clipvalue.setter + def clipvalue(self, val): + if val is not None and self.gradient_transformers: + raise ValueError("`clipvalue` cannot be set when `gradient_transformers` " + "is set. Instead, use the `gradient_transformers` to " + "specify clipping and other transformations.") + self._clipvalue = val + self._clipvalue_fn = optimizer_utils.make_gradient_clipvalue_fn( + self._clipvalue) + + def _transform_loss(self, loss): + """Called in `.minimize` to transform loss before computing gradients.""" + return loss + + def _get_gradients(self, tape, loss, var_list, grad_loss=None): + """Called in `minimize` to compute gradients from loss.""" + grads = tape.gradient(loss, var_list, grad_loss) + return list(zip(grads, var_list)) + + def _transform_unaggregated_gradients(self, grads_and_vars): + """Called in `apply_gradients` before gradient aggregation.""" + return grads_and_vars + + def _aggregate_gradients(self, grads_and_vars): + """Called in `apply_gradients` to aggregate gradients across devices. + + Note that user subclasses may override this, so the interface should not be + changed. + + Args: + grads_and_vars: List of (gradient, variable) pairs. + + Returns: + A list of (aggregrated_gradient, variable) pairs. By default, this calls + `self.gradient_aggregator`. + """ + return self.gradient_aggregator(grads_and_vars) + + def _transform_gradients(self, grads_and_vars): + """Called in `apply_gradients` after aggregation.""" + if self._clipvalue is not None: + grads_and_vars = self._clipvalue_fn(grads_and_vars) + if self._clipnorm is not None: + grads_and_vars = self._clipnorm_fn(grads_and_vars) + if self._global_clipnorm is not None: + grads_and_vars = self._global_clipnorm_fn(grads_and_vars) + + for fn in self.gradient_transformers: + grads_and_vars = fn(grads_and_vars) + return grads_and_vars + + def minimize(self, loss, var_list, grad_loss=None, name=None, tape=None): + """Minimize `loss` by updating `var_list`. + + This method simply computes gradient using `tf.GradientTape` and calls + `apply_gradients()`. If you want to process the gradient before applying + then call `tf.GradientTape` and `apply_gradients()` explicitly instead + of using this function. + + Args: + loss: `Tensor` or callable. If a callable, `loss` should take no arguments + and return the value to minimize. If a `Tensor`, the `tape` argument + must be passed. + var_list: list or tuple of `Variable` objects to update to minimize + `loss`, or a callable returning the list or tuple of `Variable` objects. + Use callable when the variable list would otherwise be incomplete before + `minimize` since the variables are created at the first time `loss` is + called. + grad_loss: (Optional). A `Tensor` holding the gradient computed for + `loss`. + name: (Optional) str. Name for the returned operation. + tape: (Optional) `tf.GradientTape`. If `loss` is provided as a `Tensor`, + the tape that computed the `loss` must be provided. + + Returns: + An `Operation` that updates the variables in `var_list`. The `iterations` + will be automatically increased by 1. + + Raises: + ValueError: If some of the variables are not `Variable` objects. + + """ + grads_and_vars = self._compute_gradients( + loss, var_list=var_list, grad_loss=grad_loss, tape=tape) + return self.apply_gradients(grads_and_vars, name=name) + + def _compute_gradients(self, loss, var_list, grad_loss=None, tape=None): + """Compute gradients of `loss` for the variables in `var_list`. + + This is the first part of `minimize()`. It returns a list + of (gradient, variable) pairs where "gradient" is the gradient + for "variable". Note that "gradient" can be a `Tensor`, an + `IndexedSlices`, or `None` if there is no gradient for the + given variable. + + Args: + loss: `Tensor` or callable. If a callable, `loss` should take no + arguments and return the value to minimize. If a `Tensor`, the `tape` + argument must be passed. + var_list: list or tuple of `Variable` objects to update to minimize + `loss`, or a callable returning the list or tuple of `Variable` objects. + Use callable when the variable list would otherwise be incomplete before + `minimize` and the variables are created at the first time when `loss` + is called. + grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`. + tape: (Optional) `tf.GradientTape`. If `loss` is provided as a `Tensor`, + the tape that computed the `loss` must be provided. + + Returns: + A list of (gradient, variable) pairs. Variable is always present, but + gradient can be `None`. + + Raises: + TypeError: If `var_list` contains anything else than `Variable` objects. + ValueError: If some arguments are invalid, or var_list is None. + """ + # TODO(josh11b): Test that we handle weight decay in a reasonable way. + if not callable(loss) and tape is None: + raise ValueError("`tape` is required when a `Tensor` loss is passed.") + tape = tape if tape is not None else backprop.GradientTape() + + if callable(loss): + with tape: + if not callable(var_list): + tape.watch(var_list) + loss = loss() + if callable(var_list): + var_list = var_list() + + with tape: + loss = self._transform_loss(loss) + + var_list = nest.flatten(var_list) + with ops.name_scope_v2(self._name + "/gradients"): + grads_and_vars = self._get_gradients(tape, loss, var_list, grad_loss) + + self._assert_valid_dtypes([ + v for g, v in grads_and_vars + if g is not None and v.dtype != dtypes.resource + ]) + + return grads_and_vars + + def apply_gradients(self, + grads_and_vars, + name=None, + experimental_aggregate_gradients=True): + """Apply gradients to variables. + + This is the second part of `minimize()`. It returns an `Operation` that + applies gradients. + + The method sums gradients from all replicas in the presence of + `tf.distribute.Strategy` by default. You can aggregate gradients yourself by + passing `experimental_aggregate_gradients=False`. + + Example: + + ```python + grads = tape.gradient(loss, vars) + grads = tf.distribute.get_replica_context().all_reduce('sum', grads) + # Processing aggregated gradients. + optimizer.apply_gradients(zip(grads, vars), + experimental_aggregate_gradients=False) + + ``` + + Args: + grads_and_vars: List of (gradient, variable) pairs. + name: Optional name for the returned operation. Default to the name passed + to the `Optimizer` constructor. + experimental_aggregate_gradients: Whether to sum gradients from different + replicas in the presense of `tf.distribute.Strategy`. If False, it's + user responsibility to aggregate the gradients. Default to True. + + Returns: + An `Operation` that applies the specified gradients. The `iterations` + will be automatically increased by 1. + + Raises: + TypeError: If `grads_and_vars` is malformed. + ValueError: If none of the variables have gradients. + RuntimeError: If called in a cross-replica context. + """ + grads_and_vars = optimizer_utils.filter_empty_gradients(grads_and_vars) + var_list = [v for (_, v) in grads_and_vars] + + with ops.name_scope_v2(self._name): + # Create iteration if necessary. + with ops.init_scope(): + self._create_all_weights(var_list) + + if not grads_and_vars: + # Distribution strategy does not support reducing an empty list of + # gradients + return control_flow_ops.no_op() + + if distribute_lib.in_cross_replica_context(): + raise RuntimeError( + "`apply_gradients() cannot be called in cross-replica context. " + "Use `tf.distribute.Strategy.run` to enter replica " + "context.") + + strategy = distribute_lib.get_strategy() + if (not experimental_aggregate_gradients and strategy and + isinstance(strategy, + (parameter_server_strategy.ParameterServerStrategyV1, + parameter_server_strategy_v2.ParameterServerStrategyV2, + central_storage_strategy.CentralStorageStrategy, + central_storage_strategy.CentralStorageStrategyV1))): + raise NotImplementedError( + "`experimental_aggregate_gradients=False is not supported for " + "ParameterServerStrategy and CentralStorageStrategy") + + apply_state = self._prepare(var_list) + if experimental_aggregate_gradients: + grads_and_vars = self._transform_unaggregated_gradients(grads_and_vars) + grads_and_vars = self._aggregate_gradients(grads_and_vars) + grads_and_vars = self._transform_gradients(grads_and_vars) + + if optimizer_utils.strategy_supports_no_merge_call(): + return self._distributed_apply(strategy, grads_and_vars, name, + apply_state) + else: + return distribute_lib.get_replica_context().merge_call( + functools.partial(self._distributed_apply, apply_state=apply_state), + args=(grads_and_vars,), + kwargs={ + "name": name, + }) + + def _distributed_apply(self, distribution, grads_and_vars, name, apply_state): + """`apply_gradients` using a `DistributionStrategy`.""" + + def apply_grad_to_update_var(var, grad): + """Apply gradient to variable.""" + if isinstance(var, tensor.Tensor): + raise NotImplementedError("Trying to update a Tensor ", var) + + apply_kwargs = {} + if isinstance(grad, indexed_slices.IndexedSlices): + if var.constraint is not None: + raise RuntimeError( + "Cannot use a constraint function on a sparse variable.") + if "apply_state" in self._sparse_apply_args: + apply_kwargs["apply_state"] = apply_state + return self._resource_apply_sparse_duplicate_indices( + grad.values, var, grad.indices, **apply_kwargs) + + if "apply_state" in self._dense_apply_args: + apply_kwargs["apply_state"] = apply_state + update_op = self._resource_apply_dense(grad, var, **apply_kwargs) + if var.constraint is not None: + with ops.control_dependencies([update_op]): + return var.assign(var.constraint(var)) + else: + return update_op + + eagerly_outside_functions = ops.executing_eagerly_outside_functions() + update_ops = [] + with name_scope_only_in_function_or_graph(name or self._name): + for grad, var in grads_and_vars: + # Colocate the update with variables to avoid unnecessary communication + # delays. See b/136304694. + with distribution.extended.colocate_vars_with(var): + with name_scope_only_in_function_or_graph( + "update" if eagerly_outside_functions else "update_" + + var.op.name): + update_op = distribution.extended.update( + var, apply_grad_to_update_var, args=(grad,), group=False) + if distribute_lib.in_cross_replica_context(): + # In cross-replica context, extended.update returns a list of + # update ops from all replicas (group=False). + update_ops.extend(update_op) + else: + # In replica context, extended.update return the single update op + # of current replica. + update_ops.append(update_op) + + any_symbolic = any(isinstance(i, ops.Operation) or + tf_utils.is_symbolic_tensor(i) for i in update_ops) + if not context.executing_eagerly() or any_symbolic: + # If the current context is graph mode or any of the update ops are + # symbolic then the step update should be carried out under a graph + # context. (eager updates execute immediately) + with backend._current_graph(update_ops).as_default(): # pylint: disable=protected-access + with ops.control_dependencies([control_flow_ops.group(update_ops)]): + return self._iterations.assign_add(1, read_value=False) + + return self._iterations.assign_add(1) + + def get_gradients(self, loss, params): + """Returns gradients of `loss` with respect to `params`. + + Should be used only in legacy v1 graph mode. + + Args: + loss: Loss tensor. + params: List of variables. + + Returns: + List of gradient tensors. + + Raises: + ValueError: In case any gradient cannot be computed (e.g. if gradient + function not implemented). + """ + params = nest.flatten(params) + with backend.get_graph().as_default(), backend.name_scope(self._name + + "/gradients"): + grads = gradients.gradients(loss, params) + for grad, param in zip(grads, params): + if grad is None: + raise ValueError("Variable {} has `None` for gradient. " + "Please make sure that all of your ops have a " + "gradient defined (i.e. are differentiable). " + "Common ops without gradient: " + "K.argmax, K.round, K.eval.".format(param)) + return grads + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + grads_and_vars = list(zip(grads, params)) + self._assert_valid_dtypes([ + v for g, v in grads_and_vars + if g is not None and v.dtype != dtypes.resource + ]) + return [self.apply_gradients(grads_and_vars)] + + def _set_hyper(self, name, value): + """set hyper `name` to value. value can be callable, tensor, numeric.""" + if isinstance(value, trackable.Trackable): + self._track_trackable(value, name, overwrite=True) + if name not in self._hyper: + self._hyper[name] = value + else: + prev_value = self._hyper[name] + if (callable(prev_value) + or isinstance(prev_value, + (tensor.Tensor, int, float, + learning_rate_schedule.LearningRateSchedule)) + or isinstance(value, learning_rate_schedule.LearningRateSchedule)): + self._hyper[name] = value + else: + backend.set_value(self._hyper[name], value) + + def _get_hyper(self, name, dtype=None): + if not self._hypers_created: + self._create_hypers() + value = self._hyper[name] + if isinstance(value, learning_rate_schedule.LearningRateSchedule): + return value + if callable(value): + value = value() + if dtype: + return math_ops.cast(value, dtype) + else: + return value + + def _create_slots(self, var_list): + pass + + def _create_all_weights(self, var_list): + """Creates all weights, including iterations, hyperparameters and slot vars. + + This will add newly created variables to `optimizer.weights`. + + New variables are only created when this method is called the first time, or + when called with different variables in the var_list. + + Args: + var_list: list or tuple of `Variable` objects that will be minimized + using this optimizer. + """ + + _ = self.iterations + self._create_hypers() + self._create_slots(var_list) + + def __getattribute__(self, name): + """Overridden to support hyperparameter access.""" + try: + return super(OptimizerV2, self).__getattribute__(name) + except AttributeError as e: + # Needed to avoid infinite recursion with __setattr__. + if name == "_hyper": + raise e + # Backwards compatibility with Keras optimizers. + if name == "lr": + name = "learning_rate" + if name in self._hyper: + return self._get_hyper(name) + raise e + + def __dir__(self): + result = set(super(OptimizerV2, self).__dir__()) + if "_hyper" in result: + result |= self._hyper.keys() + if "learning_rate" in self._hyper.keys(): + result.add("lr") + return list(result) + + def __setattr__(self, name, value): + """Override setattr to support dynamic hyperparameter setting.""" + # Backwards compatibility with Keras optimizers. + if name == "lr": + name = "learning_rate" + if hasattr(self, "_hyper") and name in self._hyper: + self._set_hyper(name, value) + else: + super(OptimizerV2, self).__setattr__(name, value) + + def get_slot_names(self): + """A list of names for this optimizer's slots.""" + return self._slot_names + + def add_slot(self, var, slot_name, initializer="zeros", shape=None): + """Add a new slot variable for `var`. + + A slot variable is an additional variable associated with `var` to train. + It is allocated and managed by optimizers, e.g. `Adam`. + + Args: + var: a `Variable` object. + slot_name: name of the slot variable. + initializer: initializer of the slot variable + shape: (Optional) shape of the slot variable. If not set, it will default + to the shape of `var`. + + Returns: + A slot variable. + """ + if slot_name not in self._slot_names: + self._slot_names.append(slot_name) + var_key = _var_key(var) + slot_dict = self._slots.setdefault(var_key, {}) + weight = slot_dict.get(slot_name, None) + if weight is None: + if isinstance(initializer, str) or callable(initializer): + initializer = initializers.get(initializer) + if isinstance( + initializer, + trackable.CheckpointInitialValueCallable) or (shape is not None): + slot_shape = shape + else: + slot_shape = var.shape + initial_value = functools.partial( + initializer, shape=slot_shape, dtype=var.dtype) + else: + initial_value = initializer + + with self._distribution_strategy_scope(): + strategy = distribute_lib.get_strategy() + if not strategy.extended.variable_created_in_scope(var): + raise ValueError( + "Trying to create optimizer slot variable under the scope for " + "tf.distribute.Strategy ({}), which is different from the scope " + "used for the original variable ({}). Make sure the slot " + "variables are created under the same strategy scope. This may " + "happen if you're restoring from a checkpoint outside the scope" + .format(strategy, var)) + + with strategy.extended.colocate_vars_with(var): + weight = tf_variables.Variable( + name="%s/%s" % (var._shared_name, slot_name), # pylint: disable=protected-access + dtype=var.dtype, + trainable=False, + initial_value=initial_value) + backend.track_variable(weight) + slot_dict[slot_name] = weight + self._restore_slot_variable( + slot_name=slot_name, variable=var, + slot_variable=weight) + self._weights.append(weight) + return weight + + def get_slot(self, var, slot_name): + var_key = _var_key(var) + slot_dict = self._slots[var_key] + return slot_dict[slot_name] + + def _prepare(self, var_list): + keys = set() + for var in var_list: + if isinstance(var, ds_values.DistributedValues): + var_devices = var._devices # pylint: disable=protected-access + else: + var_devices = [var.device] + var_dtype = var.dtype.base_dtype + for var_device in var_devices: + keys.add((var_device, var_dtype)) + + apply_state = {} + for var_device, var_dtype in keys: + apply_state[(var_device, var_dtype)] = {} + with ops.device(var_device): + self._prepare_local(var_device, var_dtype, apply_state) + + return apply_state + + def _prepare_local(self, var_device, var_dtype, apply_state): + if "learning_rate" in self._hyper: + lr_t = array_ops.identity(self._decayed_lr(var_dtype)) + apply_state[(var_device, var_dtype)]["lr_t"] = lr_t + + def _fallback_apply_state(self, var_device, var_dtype): + """Compatibility for subclasses that don't pass apply_state through.""" + apply_state = {(var_device, var_dtype): {}} + self._prepare_local(var_device, var_dtype, apply_state) + return apply_state[(var_device, var_dtype)] + + def _create_hypers(self): + if self._hypers_created: + return + with self._distribution_strategy_scope(): + # Iterate hyper values deterministically. + for name, value in sorted(self._hyper.items()): + if isinstance( + value, (tensor.Tensor, tf_variables.Variable)) or callable(value): + # The check for `callable` covers the usage when `value` is a + # `LearningRateSchedule`, in which case it does not need to create a + # variable. + continue + else: + self._hyper[name] = self.add_weight( + name, + shape=[], + trainable=False, + initializer=value, + aggregation=tf_variables.VariableAggregation.ONLY_FIRST_REPLICA) + self._hypers_created = True + + @property + def iterations(self): + """Variable. The number of training steps this Optimizer has run.""" + if self._iterations is None: + with self._distribution_strategy_scope(): + self._iterations = self.add_weight( + "iter", + shape=[], + dtype=dtypes.int64, + trainable=False, + aggregation=tf_variables.VariableAggregation.ONLY_FIRST_REPLICA) + self._weights.append(self._iterations) + return self._iterations + + @iterations.setter + def iterations(self, variable): + if self._iterations is not None: + raise RuntimeError("Cannot set `iterations` to a new Variable after " + "the Optimizer weights have been created") + self._iterations = variable + self._weights.append(self._iterations) + + def _decayed_lr(self, var_dtype): + """Get decayed learning rate as a Tensor with dtype=var_dtype.""" + lr_t = self._get_hyper("learning_rate", var_dtype) + if isinstance(lr_t, learning_rate_schedule.LearningRateSchedule): + local_step = math_ops.cast(self.iterations, var_dtype) + lr_t = math_ops.cast(lr_t(local_step), var_dtype) + if self._initial_decay > 0.: + local_step = math_ops.cast(self.iterations, var_dtype) + decay_t = math_ops.cast(self._initial_decay, var_dtype) + lr_t = lr_t / (1. + decay_t * local_step) + return lr_t + + @abc.abstractmethod + def get_config(self): + """Returns the config of the optimizer. + + An optimizer config is a Python dictionary (serializable) + containing the configuration of an optimizer. + The same optimizer can be reinstantiated later + (without any saved state) from this configuration. + + Returns: + Python dictionary. + """ + config = {"name": self._name} + if self.clipnorm is not None: + config["clipnorm"] = self.clipnorm + if self.clipvalue is not None: + config["clipvalue"] = self.clipvalue + if self.global_clipnorm is not None: + config["global_clipnorm"] = self.global_clipnorm + return config + + @classmethod + def from_config(cls, config, custom_objects=None): + """Creates an optimizer from its config. + + This method is the reverse of `get_config`, + capable of instantiating the same optimizer from the config + dictionary. + + Args: + config: A Python dictionary, typically the output of get_config. + custom_objects: A Python dictionary mapping names to additional Python + objects used to create this optimizer, such as a function used for a + hyperparameter. + + Returns: + An optimizer instance. + """ + if "lr" in config: + config["learning_rate"] = config.pop("lr") + if "learning_rate" in config: + if isinstance(config["learning_rate"], dict): + config["learning_rate"] = learning_rate_schedule.deserialize( + config["learning_rate"], custom_objects=custom_objects) + return cls(**config) + + def _serialize_hyperparameter(self, hyperparameter_name): + """Serialize a hyperparameter that can be a float, callable, or Tensor.""" + value = self._hyper[hyperparameter_name] + if isinstance(value, learning_rate_schedule.LearningRateSchedule): + return learning_rate_schedule.serialize(value) + if callable(value): + return value() + if tensor_util.is_tf_type(value): + return backend.get_value(value) + return value + + def variables(self): + """Returns variables of this Optimizer based on the order created.""" + return self._weights + + @property + def weights(self): + """Returns variables of this Optimizer based on the order created.""" + return self._weights + + def get_weights(self): + """Returns the current weights of the optimizer. + + The weights of an optimizer are its state (ie, variables). + This function returns the weight values associated with this + optimizer as a list of Numpy arrays. The first value is always the + iterations count of the optimizer, followed by the optimizer's state + variables in the order they were created. The returned list can in turn + be used to load state into similarly parameterized optimizers. + + For example, the RMSprop optimizer for this simple model returns a list of + three values-- the iteration count, followed by the root-mean-square value + of the kernel and bias of the single Dense layer: + + >>> opt = tf.keras.optimizers.RMSprop() + >>> m = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> m.compile(opt, loss='mse') + >>> data = np.arange(100).reshape(5, 20) + >>> labels = np.zeros(5) + >>> results = m.fit(data, labels) # Training. + >>> len(opt.get_weights()) + 3 + + Returns: + Weights values as a list of numpy arrays. + """ + params = self.weights + return backend.batch_get_value(params) + + # TODO(tanzheny): Maybe share this logic with base_layer. + def set_weights(self, weights): + """Set the weights of the optimizer. + + The weights of an optimizer are its state (ie, variables). + This function takes the weight values associated with this + optimizer as a list of Numpy arrays. The first value is always the + iterations count of the optimizer, followed by the optimizer's state + variables in the order they are created. The passed values are used to set + the new state of the optimizer. + + For example, the RMSprop optimizer for this simple model takes a list of + three values-- the iteration count, followed by the root-mean-square value + of the kernel and bias of the single Dense layer: + + >>> opt = tf.keras.optimizers.RMSprop() + >>> m = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> m.compile(opt, loss='mse') + >>> data = np.arange(100).reshape(5, 20) + >>> labels = np.zeros(5) + >>> results = m.fit(data, labels) # Training. + >>> new_weights = [np.array(10), np.ones([20, 10]), np.zeros([10])] + >>> opt.set_weights(new_weights) + >>> opt.iterations + + + Args: + weights: weight values as a list of numpy arrays. + """ + params = self.weights + if len(params) != len(weights): + raise ValueError( + "You called `set_weights(weights)` on optimizer " + self._name + + " with a weight list of length " + str(len(weights)) + + ", but the optimizer was expecting " + str(len(params)) + + " weights. Provided weights: " + str(weights)[:50] + "...") + if not params: + return + weight_value_tuples = [] + param_values = backend.batch_get_value(params) + for pv, p, w in zip(param_values, params, weights): + if pv.shape != w.shape: + raise ValueError("Optimizer weight shape " + str(pv.shape) + + " not compatible with " + "provided weight shape " + str(w.shape)) + weight_value_tuples.append((p, w)) + backend.batch_set_value(weight_value_tuples) + + def add_weight(self, + name, + shape, + dtype=None, + initializer="zeros", + trainable=None, + synchronization=tf_variables.VariableSynchronization.AUTO, + aggregation=tf_variables.VariableAggregation.NONE): + + if dtype is None: + dtype = dtypes.float32 + if isinstance(initializer, str) or callable(initializer): + initializer = initializers.get(initializer) + + if synchronization == tf_variables.VariableSynchronization.ON_READ: + if trainable: + raise ValueError( + "Synchronization value can be set to " + "VariableSynchronization.ON_READ only for non-trainable variables. " + "You have specified trainable=True and " + "synchronization=VariableSynchronization.ON_READ.") + else: + # Set trainable to be false when variable is to be synced on read. + trainable = False + elif trainable is None: + trainable = True + + variable = self._add_variable_with_custom_getter( + name=name, + shape=shape, + getter=base_layer_utils.make_variable, + overwrite=True, + initializer=initializer, + dtype=dtype, + trainable=trainable, + use_resource=True, + synchronization=synchronization, + aggregation=aggregation) + backend.track_variable(variable) + + return variable + + def _init_set_name(self, name, zero_based=True): + if not name: + self._name = backend.unique_object_name( + generic_utils.to_snake_case(self.__class__.__name__), + zero_based=zero_based) + else: + self._name = name + + def _assert_valid_dtypes(self, tensors): + """Asserts tensors are all valid types (see `_valid_dtypes`). + + Args: + tensors: Tensors to check. + + Raises: + ValueError: If any tensor is not a valid type. + """ + valid_dtypes = self._valid_dtypes() + for t in tensors: + dtype = t.dtype.base_dtype + if dtype not in valid_dtypes: + raise ValueError("Invalid type %r for %s, expected: %s." % + (dtype, t.name, [v for v in valid_dtypes])) + + def _valid_dtypes(self): + """Valid types for loss, variables and gradients. + + Subclasses should override to allow other float types. + + Returns: + Valid types for loss, variables and gradients. + """ + return _DEFAULT_VALID_DTYPES + + def _call_if_callable(self, param): + """Call the function if param is callable.""" + return param() if callable(param) else param + + def _resource_apply_dense(self, grad, handle, apply_state): + """Add ops to apply dense gradients to the variable `handle`. + + Args: + grad: a `Tensor` representing the gradient. + handle: a `Tensor` of dtype `resource` which points to the variable to be + updated. + apply_state: A dict which is used across multiple apply calls. + + Returns: + An `Operation` which updates the value of the variable. + """ + raise NotImplementedError("Must be implemented in subclasses.") + + def _resource_apply_sparse_duplicate_indices(self, grad, handle, indices, + **kwargs): + """Add ops to apply sparse gradients to `handle`, with repeated indices. + + Optimizers which override this method must deal with repeated indices. See + the docstring of `_apply_sparse_duplicate_indices` for details. By default + the correct behavior, to sum non-unique indices and their associated + gradients, is enforced by first pre-processing `grad` and `indices` and + passing them on to `_resource_apply_sparse`. Optimizers which deal correctly + with duplicate indices may instead override this method to avoid the + overhead of summing. + + Args: + grad: a `Tensor` representing the gradient for the affected indices. + handle: a `Tensor` of dtype `resource` which points to the variable to be + updated. + indices: a `Tensor` of integral type representing the indices for which + the gradient is nonzero. Indices may be repeated. + **kwargs: May optionally contain `apply_state` + + Returns: + An `Operation` which updates the value of the variable. + """ + summed_grad, unique_indices = _deduplicate_indexed_slices( + values=grad, indices=indices) + return self._resource_apply_sparse(summed_grad, handle, unique_indices, + **kwargs) + + def _resource_apply_sparse(self, grad, handle, indices, apply_state): + """Add ops to apply sparse gradients to the variable `handle`. + + Similar to `_apply_sparse`, the `indices` argument to this method has been + de-duplicated. Optimizers which deal correctly with non-unique indices may + instead override `_resource_apply_sparse_duplicate_indices` to avoid this + overhead. + + Args: + grad: a `Tensor` representing the gradient for the affected indices. + handle: a `Tensor` of dtype `resource` which points to the variable to be + updated. + indices: a `Tensor` of integral type representing the indices for which + the gradient is nonzero. Indices are unique. + apply_state: A dict which is used across multiple apply calls. + + Returns: + An `Operation` which updates the value of the variable. + """ + raise NotImplementedError("Must be implemented in subclasses.") + + def _resource_scatter_add(self, x, i, v): + with ops.control_dependencies([ + gen_resource_variable_ops.ResourceScatterAdd( + resource=x.handle, indices=i, updates=v) + ]): + return x.value() + + def _resource_scatter_update(self, x, i, v): + with ops.control_dependencies( + [gen_resource_variable_ops.ResourceScatterUpdate( + resource=x.handle, indices=i, updates=v)]): + return x.value() + + @property + @layer_utils.cached_per_instance + def _dense_apply_args(self): + return tf_inspect.getfullargspec(self._resource_apply_dense).args + + @property + @layer_utils.cached_per_instance + def _sparse_apply_args(self): + return tf_inspect.getfullargspec(self._resource_apply_sparse).args + + # --------------- + # For implementing the trackable interface + # --------------- + + def _restore_slot_variable(self, slot_name, variable, slot_variable): + """Restore a newly created slot variable's value.""" + variable_key = _var_key(variable) + deferred_restorations = self._deferred_slot_restorations.get( + slot_name, {}).pop(variable_key, []) + # Iterate over restores, highest restore UID first to minimize the number + # of assignments. + deferred_restorations.sort(key=lambda position: position.restore_uid, + reverse=True) + for checkpoint_position in deferred_restorations: + checkpoint_position.restore(slot_variable) + + def _create_or_restore_slot_variable( + self, slot_variable_position, slot_name, variable): + """Restore a slot variable's value, possibly creating it. + + Called when a variable which has an associated slot variable is created or + restored. When executing eagerly, we create the slot variable with a + restoring initializer. + + No new variables are created when graph building. Instead, + _restore_slot_variable catches these after normal creation and adds restore + ops to the graph. This method is nonetheless important when graph building + for the case when a slot variable has already been created but `variable` + has just been added to a dependency graph (causing us to realize that the + slot variable needs to be restored). + + Args: + slot_variable_position: A `trackable._CheckpointPosition` object + indicating the slot variable `Trackable` object to be restored. + slot_name: The name of this `Optimizer`'s slot to restore into. + variable: The variable object this slot is being created for. + """ + variable_key = _var_key(variable) + slot_dict = self._slots.get(variable_key, {}) + slot_variable = slot_dict.get(slot_name, None) + if (slot_variable is None and context.executing_eagerly() and + slot_variable_position.is_simple_variable() + # Defer slot variable creation if there is an active variable creator + # scope. Generally we'd like to eagerly create/restore slot variables + # when possible, but this may mean that scopes intended to catch + # `variable` also catch its eagerly created slot variable + # unintentionally (specifically make_template would add a dependency on + # a slot variable if not for this case). Deferring is mostly harmless + # (aside from double initialization), and makes variable creator scopes + # behave the same way they do when graph building. + # + # One notable case is with distribution strategy, which uses variable + # creator scope but always desires the `variable` and the slot to use + # the same scope, thus we can safely eagerly create/restore slot + # variables. + and (not ops.get_default_graph()._variable_creator_stack or # pylint: disable=protected-access + self._distribution_strategy)): + initializer = trackable.CheckpointInitialValueCallable( + checkpoint_position=slot_variable_position) + slot_variable = self.add_slot( + var=variable, + initializer=initializer, + slot_name=slot_name, + shape=slot_variable_position.value_shape()) + # Slot variables are not owned by any one object (because we don't want to + # save the slot variable if the optimizer is saved without the non-slot + # variable, or if the non-slot variable is saved without the optimizer; + # it's a dependency hypergraph with edges of the form (optimizer, non-slot + # variable, variable)). So we don't _track_ slot variables anywhere, and + # instead special-case this dependency and otherwise pretend it's a normal + # graph. + if slot_variable is not None: + # If we've either made this slot variable, or if we've pulled out an + # existing slot variable, we should restore it. + slot_variable_position.restore(slot_variable) + else: + # We didn't make the slot variable. Defer restoring until it gets created + # normally. We keep a list rather than the one with the highest restore + # UID in case slot variables have their own dependencies, in which case + # those could differ between restores. + self._deferred_slot_restorations.setdefault( + slot_name, {}).setdefault(variable_key, []).append( + slot_variable_position) + + @contextlib.contextmanager + def _distribution_strategy_scope(self): + """Returns the `tf.distribute.Strategy` this optimizer was created under.""" + if self._distribution_strategy and not distribute_lib.has_strategy(): + with self._distribution_strategy.scope(): + yield self._distribution_strategy.scope() + else: + yield + + +def _var_key(var): + """Key for representing a primary variable, for looking up slots. + + In graph mode the name is derived from the var shared name. + In eager mode the name is derived from the var unique id. + If distribution strategy exists, get the primary variable first. + + Args: + var: the variable. + + Returns: + the unique name of the variable. + """ + + # pylint: disable=protected-access + # Get the distributed variable if it exists. + if hasattr(var, "_distributed_container"): + var = var._distributed_container() + if var._in_graph_mode: + return var._shared_name + return var._unique_id + + +def _get_slot_key_from_var(var, slot_name): + """Get the slot key for the variable: var_name/slot_name.""" + + name = _var_key(var) + return name + "/" + slot_name + + +class RestoredOptimizer(OptimizerV2): + """A non-functional Optimizer implementation for checkpoint compatibility. + + Holds slot variables and hyperparameters when an optimizer is restored from a + SavedModel. These variables may be referenced in functions along with ops + created by the original optimizer, but currently we do not support using the + optimizer object iself (e.g. through `apply_gradients`). + """ + # TODO(allenl): Make the restored optimizer functional by tracing its apply + # methods. + + def __init__(self): + super(RestoredOptimizer, self).__init__("RestoredOptimizer") + self._hypers_created = True + + def get_config(self): + # TODO(allenl): Save and restore the Optimizer's config + raise NotImplementedError( + "Restoring functional Optimizers from SavedModels is not currently " + "supported. Please file a feature request if this limitation bothers " + "you.") + +revived_types.register_revived_type( + "tf_deprecated_optimizer", + lambda obj: isinstance(obj, OptimizerV2), + versions=[revived_types.VersionedTypeRegistration( + object_factory=lambda proto: RestoredOptimizer(), + version=1, + min_producer_version=1, + min_consumer_version=1, + setter=RestoredOptimizer._set_hyper # pylint: disable=protected-access + )]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/rmsprop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/rmsprop.py new file mode 100644 index 0000000000000000000000000000000000000000..39fa85af7690b3b67be2f1eafb786e80aa7186ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/rmsprop.py @@ -0,0 +1,303 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""RMSprop optimizer implementation.""" +# pylint: disable=g-classes-have-attributes + +import numpy as np + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.training import gen_training_ops + + +class RMSprop(optimizer_v2.OptimizerV2): + r"""Optimizer that implements the RMSprop algorithm. + + The gist of RMSprop is to: + + - Maintain a moving (discounted) average of the square of gradients + - Divide the gradient by the root of this average + + This implementation of RMSprop uses plain momentum, not Nesterov momentum. + + The centered version additionally maintains a moving average of the + gradients, and uses that average to estimate the variance. + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable + that takes no arguments and returns the actual value to use. The + learning rate. Defaults to 0.001. + rho: Discounting factor for the history/coming gradient. Defaults to 0.9. + momentum: A scalar or a scalar `Tensor`. Defaults to 0.0. + epsilon: A small constant for numerical stability. This epsilon is + "epsilon hat" in the Kingma and Ba paper (in the formula just before + Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to + 1e-7. + centered: Boolean. If `True`, gradients are normalized by the estimated + variance of the gradient; if False, by the uncentered second moment. + Setting this to `True` may help with training, but is slightly more + expensive in terms of computation and memory. Defaults to `False`. + name: Optional name prefix for the operations created when applying + gradients. Defaults to `"RMSprop"`. + **kwargs: Keyword arguments. Allowed to be one of + `"clipnorm"` or `"clipvalue"`. + `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips + gradients by value. + + Note that in the dense implementation of this algorithm, variables and their + corresponding accumulators (momentum, gradient moving average, square + gradient moving average) will be updated even if the gradient is zero + (i.e. accumulators will decay, momentum will be applied). The sparse + implementation (used when the gradient is an `IndexedSlices` object, + typically because of `tf.gather` or an embedding lookup in the forward pass) + will not update variable slices or their accumulators unless those slices + were used in the forward pass (nor is there an "eventual" correction to + account for these omitted updates). This leads to more efficient updates for + large embedding lookup tables (where most of the slices are not accessed in + a particular graph execution), but differs from the published algorithm. + + Usage: + + >>> opt = tf.keras.optimizers.RMSprop(learning_rate=0.1) + >>> var1 = tf.Variable(10.0) + >>> loss = lambda: (var1 ** 2) / 2.0 # d(loss) / d(var1) = var1 + >>> step_count = opt.minimize(loss, [var1]).numpy() + >>> var1.numpy() + 9.683772 + + Reference: + - [Hinton, 2012]( + http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) + """ + + _HAS_AGGREGATE_GRAD = True + + def __init__(self, + learning_rate=0.001, + rho=0.9, + momentum=0.0, + epsilon=1e-7, + centered=False, + name="RMSprop", + **kwargs): + """Construct a new RMSprop optimizer. + + Args: + learning_rate: A `Tensor`, floating point value, or a schedule that is a + `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable + that takes no arguments and returns the actual value to use. The + learning rate. Defaults to 0.001. + rho: Discounting factor for the history/coming gradient. Defaults to 0.9. + momentum: A scalar or a scalar `Tensor`. Defaults to 0.0. + epsilon: A small constant for numerical stability. This epsilon is + "epsilon hat" in the Kingma and Ba paper (in the formula just before + Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to + 1e-7. + centered: Boolean. If `True`, gradients are normalized by the estimated + variance of the gradient; if False, by the uncentered second moment. + Setting this to `True` may help with training, but is slightly more + expensive in terms of computation and memory. Defaults to `False`. + name: Optional name prefix for the operations created when applying + gradients. Defaults to "RMSprop". + **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, + `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip + gradients by value, `decay` is included for backward compatibility to + allow time inverse decay of learning rate. `lr` is included for backward + compatibility, recommended to use `learning_rate` instead. + + @compatibility(eager) + When eager execution is enabled, `learning_rate`, `decay`, `momentum`, and + `epsilon` can each be a callable that takes no arguments and returns the + actual value to use. This can be useful for changing these values across + different invocations of optimizer functions. + @end_compatibility + """ + super(RMSprop, self).__init__(name, **kwargs) + self._set_hyper("learning_rate", kwargs.get("lr", learning_rate)) + self._set_hyper("decay", self._initial_decay) + self._set_hyper("rho", rho) + + self._momentum = False + if isinstance( + momentum, tensor.Tensor) or callable(momentum) or momentum > 0: + self._momentum = True + if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1): + raise ValueError("`momentum` must be between [0, 1].") + self._set_hyper("momentum", momentum) + + self.epsilon = epsilon or backend_config.epsilon() + self.centered = centered + + def _create_slots(self, var_list): + for var in var_list: + self.add_slot(var, "rms") + if self._momentum: + for var in var_list: + self.add_slot(var, "momentum") + if self.centered: + for var in var_list: + self.add_slot(var, "mg") + + def _prepare_local(self, var_device, var_dtype, apply_state): + super(RMSprop, self)._prepare_local(var_device, var_dtype, apply_state) + + rho = array_ops.identity(self._get_hyper("rho", var_dtype)) + apply_state[(var_device, var_dtype)].update( + dict( + neg_lr_t=-apply_state[(var_device, var_dtype)]["lr_t"], + epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.epsilon, var_dtype + ), + rho=rho, + momentum=array_ops.identity(self._get_hyper("momentum", var_dtype)), + one_minus_rho=1.0 - rho, + ) + ) + + def _resource_apply_dense(self, grad, var, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + rms = self.get_slot(var, "rms") + if self._momentum: + mom = self.get_slot(var, "momentum") + if self.centered: + mg = self.get_slot(var, "mg") + return gen_training_ops.ResourceApplyCenteredRMSProp( + var=var.handle, + mg=mg.handle, + ms=rms.handle, + mom=mom.handle, + lr=coefficients["lr_t"], + rho=coefficients["rho"], + momentum=coefficients["momentum"], + epsilon=coefficients["epsilon"], + grad=grad, + use_locking=self._use_locking) + else: + return gen_training_ops.ResourceApplyRMSProp( + var=var.handle, + ms=rms.handle, + mom=mom.handle, + lr=coefficients["lr_t"], + rho=coefficients["rho"], + momentum=coefficients["momentum"], + epsilon=coefficients["epsilon"], + grad=grad, + use_locking=self._use_locking) + else: + rms_t = (coefficients["rho"] * rms + + coefficients["one_minus_rho"] * math_ops.square(grad)) + rms_t = state_ops.assign(rms, rms_t, use_locking=self._use_locking) + denom_t = rms_t + if self.centered: + mg = self.get_slot(var, "mg") + mg_t = coefficients["rho"] * mg + coefficients["one_minus_rho"] * grad + mg_t = state_ops.assign(mg, mg_t, use_locking=self._use_locking) + denom_t = rms_t - math_ops.square(mg_t) + var_t = var - coefficients["lr_t"] * grad / ( + math_ops.sqrt(denom_t) + coefficients["epsilon"]) + return state_ops.assign(var, var_t, use_locking=self._use_locking).op + + def _resource_apply_sparse(self, grad, var, indices, apply_state=None): + var_device, var_dtype = var.device, var.dtype.base_dtype + coefficients = ((apply_state or {}).get((var_device, var_dtype)) + or self._fallback_apply_state(var_device, var_dtype)) + + rms = self.get_slot(var, "rms") + if self._momentum: + mom = self.get_slot(var, "momentum") + if self.centered: + mg = self.get_slot(var, "mg") + return gen_training_ops.ResourceSparseApplyCenteredRMSProp( + var=var.handle, + mg=mg.handle, + ms=rms.handle, + mom=mom.handle, + lr=coefficients["lr_t"], + rho=coefficients["rho"], + momentum=coefficients["momentum"], + epsilon=coefficients["epsilon"], + grad=grad, + indices=indices, + use_locking=self._use_locking) + else: + return gen_training_ops.ResourceSparseApplyRMSProp( + var=var.handle, + ms=rms.handle, + mom=mom.handle, + lr=coefficients["lr_t"], + rho=coefficients["rho"], + momentum=coefficients["momentum"], + epsilon=coefficients["epsilon"], + grad=grad, + indices=indices, + use_locking=self._use_locking) + else: + rms_scaled_g_values = (grad * grad) * coefficients["one_minus_rho"] + rms_t = state_ops.assign(rms, rms * coefficients["rho"], + use_locking=self._use_locking) + with ops.control_dependencies([rms_t]): + rms_t = self._resource_scatter_add(rms, indices, rms_scaled_g_values) + rms_slice = array_ops.gather(rms_t, indices) + denom_slice = rms_slice + if self.centered: + mg = self.get_slot(var, "mg") + mg_scaled_g_values = grad * coefficients["one_minus_rho"] + mg_t = state_ops.assign(mg, mg * coefficients["rho"], + use_locking=self._use_locking) + with ops.control_dependencies([mg_t]): + mg_t = self._resource_scatter_add(mg, indices, mg_scaled_g_values) + mg_slice = array_ops.gather(mg_t, indices) + denom_slice = rms_slice - math_ops.square(mg_slice) + var_update = self._resource_scatter_add( + var, indices, coefficients["neg_lr_t"] * grad / ( + math_ops.sqrt(denom_slice) + coefficients["epsilon"])) + if self.centered: + return control_flow_ops.group(*[var_update, rms_t, mg_t]) + return control_flow_ops.group(*[var_update, rms_t]) + + def set_weights(self, weights): + params = self.weights + # Override set_weights for backward compatibility of Keras V1 optimizer + # since it does not include iteration at head of the weight list. Set + # iteration to 0. + if len(params) == len(weights) + 1: + weights = [np.array(0)] + weights + super(RMSprop, self).set_weights(weights) + + def get_config(self): + config = super(RMSprop, self).get_config() + config.update({ + "learning_rate": self._serialize_hyperparameter("learning_rate"), + "decay": self._initial_decay, + "rho": self._serialize_hyperparameter("rho"), + "momentum": self._serialize_hyperparameter("momentum"), + "epsilon": self.epsilon, + "centered": self.centered, + }) + return config + + +RMSProp = RMSprop diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee3139c561b82d1b80137c96372fecfdda71e2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v2/utils.py @@ -0,0 +1,157 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Optimizer utilities.""" + +from tensorflow.python.distribute import central_storage_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import reduce_util as ds_reduce_util +from tensorflow.python.ops import clip_ops +from tensorflow.python.platform import tf_logging as logging + + +def all_reduce_sum_gradients(grads_and_vars): + """Returns all-reduced gradients aggregated via summation. + + Args: + grads_and_vars: List of (gradient, variable) pairs. + + Returns: + List of (gradient, variable) pairs where gradients have been all-reduced. + """ + grads_and_vars = list(grads_and_vars) + filtered_grads_and_vars = filter_empty_gradients(grads_and_vars) + if filtered_grads_and_vars: + if strategy_supports_no_merge_call(): + grads = [pair[0] for pair in filtered_grads_and_vars] + reduced = distribute_lib.get_strategy().extended._replica_ctx_all_reduce( # pylint: disable=protected-access + ds_reduce_util.ReduceOp.SUM, grads) + else: + # TODO(b/183257003): Remove this branch + reduced = distribute_lib.get_replica_context().merge_call( + _all_reduce_sum_fn, args=(filtered_grads_and_vars,)) + else: + reduced = [] + # Copy 'reduced' but add None gradients back in + reduced_with_nones = [] + reduced_pos = 0 + for g, v in grads_and_vars: + if g is None: + reduced_with_nones.append((None, v)) + else: + reduced_with_nones.append((reduced[reduced_pos], v)) + reduced_pos += 1 + assert reduced_pos == len(reduced), "Failed to add all gradients" + return reduced_with_nones + + +def filter_empty_gradients(grads_and_vars): + """Filter out `(grad, var)` pairs that have a gradient equal to `None`.""" + grads_and_vars = tuple(grads_and_vars) + if not grads_and_vars: + return grads_and_vars + + filtered = [] + vars_with_empty_grads = [] + for grad, var in grads_and_vars: + if grad is None: + vars_with_empty_grads.append(var) + else: + filtered.append((grad, var)) + filtered = tuple(filtered) + + if not filtered: + raise ValueError("No gradients provided for any variable: %s." % + ([v.name for _, v in grads_and_vars],)) + if vars_with_empty_grads: + logging.warning( + ("Gradients do not exist for variables %s when minimizing the loss."), + ([v.name for v in vars_with_empty_grads])) + return filtered + + +def make_gradient_clipnorm_fn(clipnorm): + """Creates a gradient transformation function for clipping by norm.""" + if clipnorm is None: + return lambda grads_and_vars: grads_and_vars + + def gradient_clipnorm_fn(grads_and_vars): + + if isinstance(distribute_lib.get_strategy(), + (central_storage_strategy.CentralStorageStrategy, + central_storage_strategy.CentralStorageStrategyV1)): + raise ValueError( + "`clipnorm` is not supported with `CenteralStorageStrategy`") + + clipped_grads_and_vars = [ + (clip_ops.clip_by_norm(g, clipnorm), v) for g, v in grads_and_vars + ] + return clipped_grads_and_vars + + return gradient_clipnorm_fn + + +def make_global_gradient_clipnorm_fn(clipnorm): + """Creates a gradient transformation function for clipping by norm.""" + if clipnorm is None: + return lambda grads_and_vars: grads_and_vars + + def gradient_clipnorm_fn(grads_and_vars): + + if isinstance(distribute_lib.get_strategy(), + (central_storage_strategy.CentralStorageStrategy, + central_storage_strategy.CentralStorageStrategyV1)): + raise ValueError( + "`global_clipnorm` is not supported with `CenteralStorageStrategy`") + + grads, variables = zip(*grads_and_vars) + clipped_grads, _ = clip_ops.clip_by_global_norm(grads, clipnorm) + clipped_grads_and_vars = list(zip(clipped_grads, variables)) + return clipped_grads_and_vars + + return gradient_clipnorm_fn + + +def make_gradient_clipvalue_fn(clipvalue): + """Creates a gradient transformation function for clipping by value.""" + if clipvalue is None: + return lambda grads_and_vars: grads_and_vars + + def gradient_clipvalue_fn(grads_and_vars): + + if isinstance(distribute_lib.get_strategy(), + (central_storage_strategy.CentralStorageStrategy, + central_storage_strategy.CentralStorageStrategyV1)): + raise ValueError( + "`clipvalue` is not supported with `CenteralStorageStrategy`") + + clipped_grads_and_vars = [(clip_ops.clip_by_value(g, -clipvalue, + clipvalue), v) + for g, v in grads_and_vars] + return clipped_grads_and_vars + + return gradient_clipvalue_fn + + +def _all_reduce_sum_fn(distribution, grads_and_vars): + return distribution.extended.batch_reduce_to(ds_reduce_util.ReduceOp.SUM, + grads_and_vars) + + +def strategy_supports_no_merge_call(): + """Returns if the current Strategy can operate in pure replica context.""" + if not distribute_lib.has_strategy(): + return True + strategy = distribute_lib.get_strategy() + return not strategy.extended._use_merge_call() # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizers.py new file mode 100644 index 0000000000000000000000000000000000000000..51fad0fc94790d143afa99f3581074781360ef03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizers.py @@ -0,0 +1,128 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=invalid-name +"""Built-in optimizer classes. + +For more examples see the base class `tf.keras.optimizers.Optimizer`. +""" + +from tensorflow.python.keras import backend +from tensorflow.python.keras.optimizer_v1 import Optimizer +from tensorflow.python.keras.optimizer_v1 import TFOptimizer +from tensorflow.python.keras.optimizer_v2 import adadelta as adadelta_v2 +from tensorflow.python.keras.optimizer_v2 import adagrad as adagrad_v2 +from tensorflow.python.keras.optimizer_v2 import adam as adam_v2 +from tensorflow.python.keras.optimizer_v2 import adamax as adamax_v2 +from tensorflow.python.keras.optimizer_v2 import ftrl +from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_v2 +from tensorflow.python.keras.optimizer_v2 import nadam as nadam_v2 +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.optimizer_v2 import rmsprop as rmsprop_v2 +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.training import optimizer as tf_optimizer_module + + +def serialize(optimizer): + """Serialize the optimizer configuration to JSON compatible python dict. + + The configuration can be used for persistence and reconstruct the `Optimizer` + instance again. + + >>> tf.keras.optimizers.serialize(tf.keras.optimizers.SGD()) + {'class_name': 'SGD', 'config': {'name': 'SGD', 'learning_rate': 0.01, + 'decay': 0.0, 'momentum': 0.0, + 'nesterov': False}} + + Args: + optimizer: An `Optimizer` instance to serialize. + + Returns: + Python dict which contains the configuration of the input optimizer. + """ + return serialize_keras_object(optimizer) + + +def deserialize(config, custom_objects=None): + """Inverse of the `serialize` function. + + Args: + config: Optimizer configuration dictionary. + custom_objects: Optional dictionary mapping names (strings) to custom + objects (classes and functions) to be considered during deserialization. + + Returns: + A Keras Optimizer instance. + """ + # loss_scale_optimizer has a direct dependency of optimizer, import here + # rather than top to avoid the cyclic dependency. + from tensorflow.python.keras.mixed_precision import loss_scale_optimizer # pylint: disable=g-import-not-at-top + all_classes = { + 'adadelta': adadelta_v2.Adadelta, + 'adagrad': adagrad_v2.Adagrad, + 'adam': adam_v2.Adam, + 'adamax': adamax_v2.Adamax, + 'nadam': nadam_v2.Nadam, + 'rmsprop': rmsprop_v2.RMSprop, + 'sgd': gradient_descent_v2.SGD, + 'ftrl': ftrl.Ftrl, + 'lossscaleoptimizer': loss_scale_optimizer.LossScaleOptimizer, + # LossScaleOptimizerV1 deserializes into LossScaleOptimizer, as + # LossScaleOptimizerV1 will be removed soon but deserializing it will + # still be supported. + 'lossscaleoptimizerv1': loss_scale_optimizer.LossScaleOptimizer, + } + + # Make deserialization case-insensitive for built-in optimizers. + if config['class_name'].lower() in all_classes: + config['class_name'] = config['class_name'].lower() + return deserialize_keras_object( + config, + module_objects=all_classes, + custom_objects=custom_objects, + printable_module_name='optimizer') + + +def get(identifier): + """Retrieves a Keras Optimizer instance. + + Args: + identifier: Optimizer identifier, one of + - String: name of an optimizer + - Dictionary: configuration dictionary. - Keras Optimizer instance (it + will be returned unchanged). - TensorFlow Optimizer instance (it + will be wrapped as a Keras Optimizer). + + Returns: + A Keras Optimizer instance. + + Raises: + ValueError: If `identifier` cannot be interpreted. + """ + if isinstance(identifier, (Optimizer, optimizer_v2.OptimizerV2)): + return identifier + # Wrap legacy TF optimizer instances + elif isinstance(identifier, tf_optimizer_module.Optimizer): + opt = TFOptimizer(identifier) + backend.track_tf_optimizer(opt) + return opt + elif isinstance(identifier, dict): + return deserialize(identifier) + elif isinstance(identifier, str): + config = {'class_name': str(identifier), 'config': {}} + return deserialize(config) + else: + raise ValueError( + 'Could not interpret optimizer identifier: {}'.format(identifier)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/projector_config_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/projector_config_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a11af924aa39892025b2f6d2eb869cafc61ac7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/projector_config_pb2.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/keras/protobuf/projector_config.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n7tensorflow/python/keras/protobuf/projector_config.proto\x12,third_party.tensorflow.python.keras.protobuf\">\n\x0eSpriteMetadata\x12\x12\n\nimage_path\x18\x01 \x01(\t\x12\x18\n\x10single_image_dim\x18\x02 \x03(\r\"\xcc\x01\n\rEmbeddingInfo\x12\x13\n\x0btensor_name\x18\x01 \x01(\t\x12\x15\n\rmetadata_path\x18\x02 \x01(\t\x12\x16\n\x0e\x62ookmarks_path\x18\x03 \x01(\t\x12\x14\n\x0ctensor_shape\x18\x04 \x03(\r\x12L\n\x06sprite\x18\x05 \x01(\x0b\x32<.third_party.tensorflow.python.keras.protobuf.SpriteMetadata\x12\x13\n\x0btensor_path\x18\x06 \x01(\t\"\x9f\x01\n\x0fProjectorConfig\x12\x1d\n\x15model_checkpoint_path\x18\x01 \x01(\t\x12O\n\nembeddings\x18\x02 \x03(\x0b\x32;.third_party.tensorflow.python.keras.protobuf.EmbeddingInfo\x12\x1c\n\x14model_checkpoint_dir\x18\x03 \x01(\tb\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.keras.protobuf.projector_config_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _SPRITEMETADATA._serialized_start=105 + _SPRITEMETADATA._serialized_end=167 + _EMBEDDINGINFO._serialized_start=170 + _EMBEDDINGINFO._serialized_end=374 + _PROJECTORCONFIG._serialized_start=377 + _PROJECTORCONFIG._serialized_end=536 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/saved_metadata_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/saved_metadata_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..01d90d40b88d6662a973c4676ac3086a71ea6c21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/saved_metadata_pb2.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/keras/protobuf/saved_metadata.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.python.keras.protobuf import versions_pb2 as tensorflow_dot_python_dot_keras_dot_protobuf_dot_versions__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n5tensorflow/python/keras/protobuf/saved_metadata.proto\x12,third_party.tensorflow.python.keras.protobuf\x1a/tensorflow/python/keras/protobuf/versions.proto\"Y\n\rSavedMetadata\x12H\n\x05nodes\x18\x01 \x03(\x0b\x32\x39.third_party.tensorflow.python.keras.protobuf.SavedObject\"\xa8\x01\n\x0bSavedObject\x12\x0f\n\x07node_id\x18\x02 \x01(\x05\x12\x11\n\tnode_path\x18\x03 \x01(\t\x12\x12\n\nidentifier\x18\x04 \x01(\t\x12\x10\n\x08metadata\x18\x05 \x01(\t\x12I\n\x07version\x18\x06 \x01(\x0b\x32\x38.third_party.tensorflow.python.keras.protobuf.VersionDefJ\x04\x08\x01\x10\x02\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.keras.protobuf.saved_metadata_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _SAVEDMETADATA._serialized_start=152 + _SAVEDMETADATA._serialized_end=241 + _SAVEDOBJECT._serialized_start=244 + _SAVEDOBJECT._serialized_end=412 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/versions_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/versions_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..33ae92399189a3acf8fa00a4e524f916e9b317bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/protobuf/versions_pb2.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/keras/protobuf/versions.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n/tensorflow/python/keras/protobuf/versions.proto\x12,third_party.tensorflow.python.keras.protobuf\"K\n\nVersionDef\x12\x10\n\x08producer\x18\x01 \x01(\x05\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\x05\x12\x15\n\rbad_consumers\x18\x03 \x03(\x05\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.keras.protobuf.versions_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _VERSIONDEF._serialized_start=97 + _VERSIONDEF._serialized_end=172 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/regularizers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/regularizers.py new file mode 100644 index 0000000000000000000000000000000000000000..634ea39f0e4bf61d667174219a3f51750cd00beb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/regularizers.py @@ -0,0 +1,369 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Built-in regularizers.""" +# pylint: disable=invalid-name + +import math + +from tensorflow.python.keras import backend +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.ops import math_ops + + +def _check_penalty_number(x): + """check penalty number availability, raise ValueError if failed.""" + if not isinstance(x, (float, int)): + raise ValueError(('Value: {} is not a valid regularization penalty number, ' + 'expected an int or float value').format(x)) + + if math.isinf(x) or math.isnan(x): + raise ValueError( + ('Value: {} is not a valid regularization penalty number, ' + 'a positive/negative infinity or NaN is not a property value' + ).format(x)) + + +def _none_to_default(inputs, default): + return default if inputs is None else default + + +class Regularizer(object): + """Regularizer base class. + + Regularizers allow you to apply penalties on layer parameters or layer + activity during optimization. These penalties are summed into the loss + function that the network optimizes. + + Regularization penalties are applied on a per-layer basis. The exact API will + depend on the layer, but many layers (e.g. `Dense`, `Conv1D`, `Conv2D` and + `Conv3D`) have a unified API. + + These layers expose 3 keyword arguments: + + - `kernel_regularizer`: Regularizer to apply a penalty on the layer's kernel + - `bias_regularizer`: Regularizer to apply a penalty on the layer's bias + - `activity_regularizer`: Regularizer to apply a penalty on the layer's output + + All layers (including custom layers) expose `activity_regularizer` as a + settable property, whether or not it is in the constructor arguments. + + The value returned by the `activity_regularizer` is divided by the input + batch size so that the relative weighting between the weight regularizers and + the activity regularizers does not change with the batch size. + + You can access a layer's regularization penalties by calling `layer.losses` + after calling the layer on inputs. + + ## Example + + >>> layer = tf.keras.layers.Dense( + ... 5, input_dim=5, + ... kernel_initializer='ones', + ... kernel_regularizer=tf.keras.regularizers.L1(0.01), + ... activity_regularizer=tf.keras.regularizers.L2(0.01)) + >>> tensor = tf.ones(shape=(5, 5)) * 2.0 + >>> out = layer(tensor) + + >>> # The kernel regularization term is 0.25 + >>> # The activity regularization term (after dividing by the batch size) is 5 + >>> tf.math.reduce_sum(layer.losses) + + + ## Available penalties + + ```python + tf.keras.regularizers.L1(0.3) # L1 Regularization Penalty + tf.keras.regularizers.L2(0.1) # L2 Regularization Penalty + tf.keras.regularizers.L1L2(l1=0.01, l2=0.01) # L1 + L2 penalties + ``` + + ## Directly calling a regularizer + + Compute a regularization loss on a tensor by directly calling a regularizer + as if it is a one-argument function. + + E.g. + >>> regularizer = tf.keras.regularizers.L2(2.) + >>> tensor = tf.ones(shape=(5, 5)) + >>> regularizer(tensor) + + + + ## Developing new regularizers + + Any function that takes in a weight matrix and returns a scalar + tensor can be used as a regularizer, e.g.: + + >>> @tf.keras.utils.register_keras_serializable(package='Custom', name='l1') + ... def l1_reg(weight_matrix): + ... return 0.01 * tf.math.reduce_sum(tf.math.abs(weight_matrix)) + ... + >>> layer = tf.keras.layers.Dense(5, input_dim=5, + ... kernel_initializer='ones', kernel_regularizer=l1_reg) + >>> tensor = tf.ones(shape=(5, 5)) + >>> out = layer(tensor) + >>> layer.losses + [] + + Alternatively, you can write your custom regularizers in an + object-oriented way by extending this regularizer base class, e.g.: + + >>> @tf.keras.utils.register_keras_serializable(package='Custom', name='l2') + ... class L2Regularizer(tf.keras.regularizers.Regularizer): + ... def __init__(self, l2=0.): # pylint: disable=redefined-outer-name + ... self.l2 = l2 + ... + ... def __call__(self, x): + ... return self.l2 * tf.math.reduce_sum(tf.math.square(x)) + ... + ... def get_config(self): + ... return {'l2': float(self.l2)} + ... + >>> layer = tf.keras.layers.Dense( + ... 5, input_dim=5, kernel_initializer='ones', + ... kernel_regularizer=L2Regularizer(l2=0.5)) + + >>> tensor = tf.ones(shape=(5, 5)) + >>> out = layer(tensor) + >>> layer.losses + [] + + ### A note on serialization and deserialization: + + Registering the regularizers as serializable is optional if you are just + training and executing models, exporting to and from SavedModels, or saving + and loading weight checkpoints. + + Registration is required for Keras `model_to_estimator`, saving and + loading models to HDF5 formats, Keras model cloning, some visualization + utilities, and exporting models to and from JSON. If using this functionality, + you must make sure any python process running your model has also defined + and registered your custom regularizer. + + `tf.keras.utils.register_keras_serializable` is only available in TF 2.1 and + beyond. In earlier versions of TensorFlow you must pass your custom + regularizer to the `custom_objects` argument of methods that expect custom + regularizers to be registered as serializable. + """ + + def __call__(self, x): + """Compute a regularization penalty from an input tensor.""" + return 0. + + @classmethod + def from_config(cls, config): + """Creates a regularizer from its config. + + This method is the reverse of `get_config`, + capable of instantiating the same regularizer from the config + dictionary. + + This method is used by Keras `model_to_estimator`, saving and + loading models to HDF5 formats, Keras model cloning, some visualization + utilities, and exporting models to and from JSON. + + Args: + config: A Python dictionary, typically the output of get_config. + + Returns: + A regularizer instance. + """ + return cls(**config) + + def get_config(self): + """Returns the config of the regularizer. + + An regularizer config is a Python dictionary (serializable) + containing all configuration parameters of the regularizer. + The same regularizer can be reinstantiated later + (without any saved state) from this configuration. + + This method is optional if you are just training and executing models, + exporting to and from SavedModels, or using weight checkpoints. + + This method is required for Keras `model_to_estimator`, saving and + loading models to HDF5 formats, Keras model cloning, some visualization + utilities, and exporting models to and from JSON. + + Returns: + Python dictionary. + """ + raise NotImplementedError(str(self) + ' does not implement get_config()') + + +class L1L2(Regularizer): + """A regularizer that applies both L1 and L2 regularization penalties. + + The L1 regularization penalty is computed as: + `loss = l1 * reduce_sum(abs(x))` + + The L2 regularization penalty is computed as + `loss = l2 * reduce_sum(square(x))` + + L1L2 may be passed to a layer as a string identifier: + + >>> dense = tf.keras.layers.Dense(3, kernel_regularizer='l1_l2') + + In this case, the default values used are `l1=0.01` and `l2=0.01`. + + Attributes: + l1: Float; L1 regularization factor. + l2: Float; L2 regularization factor. + """ + + def __init__(self, l1=0., l2=0.): # pylint: disable=redefined-outer-name + # The default value for l1 and l2 are different from the value in l1_l2 + # for backward compatibility reason. Eg, L1L2(l2=0.1) will only have l2 + # and no l1 penalty. + l1 = 0. if l1 is None else l1 + l2 = 0. if l2 is None else l2 + _check_penalty_number(l1) + _check_penalty_number(l2) + + self.l1 = backend.cast_to_floatx(l1) + self.l2 = backend.cast_to_floatx(l2) + + def __call__(self, x): + regularization = backend.constant(0., dtype=x.dtype) + if self.l1: + regularization += self.l1 * math_ops.reduce_sum(math_ops.abs(x)) + if self.l2: + regularization += self.l2 * math_ops.reduce_sum(math_ops.square(x)) + return regularization + + def get_config(self): + return {'l1': float(self.l1), 'l2': float(self.l2)} + + +class L1(Regularizer): + """A regularizer that applies a L1 regularization penalty. + + The L1 regularization penalty is computed as: + `loss = l1 * reduce_sum(abs(x))` + + L1 may be passed to a layer as a string identifier: + + >>> dense = tf.keras.layers.Dense(3, kernel_regularizer='l1') + + In this case, the default value used is `l1=0.01`. + + Attributes: + l1: Float; L1 regularization factor. + """ + + def __init__(self, l1=0.01, **kwargs): # pylint: disable=redefined-outer-name + l1 = kwargs.pop('l', l1) # Backwards compatibility + if kwargs: + raise TypeError('Argument(s) not recognized: %s' % (kwargs,)) + + l1 = 0.01 if l1 is None else l1 + _check_penalty_number(l1) + + self.l1 = backend.cast_to_floatx(l1) + + def __call__(self, x): + return self.l1 * math_ops.reduce_sum(math_ops.abs(x)) + + def get_config(self): + return {'l1': float(self.l1)} + + +class L2(Regularizer): + """A regularizer that applies a L2 regularization penalty. + + The L2 regularization penalty is computed as: + `loss = l2 * reduce_sum(square(x))` + + L2 may be passed to a layer as a string identifier: + + >>> dense = tf.keras.layers.Dense(3, kernel_regularizer='l2') + + In this case, the default value used is `l2=0.01`. + + Attributes: + l2: Float; L2 regularization factor. + """ + + def __init__(self, l2=0.01, **kwargs): # pylint: disable=redefined-outer-name + l2 = kwargs.pop('l', l2) # Backwards compatibility + if kwargs: + raise TypeError('Argument(s) not recognized: %s' % (kwargs,)) + + l2 = 0.01 if l2 is None else l2 + _check_penalty_number(l2) + + self.l2 = backend.cast_to_floatx(l2) + + def __call__(self, x): + return self.l2 * math_ops.reduce_sum(math_ops.square(x)) + + def get_config(self): + return {'l2': float(self.l2)} + + +def l1_l2(l1=0.01, l2=0.01): # pylint: disable=redefined-outer-name + r"""Create a regularizer that applies both L1 and L2 penalties. + + The L1 regularization penalty is computed as: + `loss = l1 * reduce_sum(abs(x))` + + The L2 regularization penalty is computed as: + `loss = l2 * reduce_sum(square(x))` + + Args: + l1: Float; L1 regularization factor. + l2: Float; L2 regularization factor. + + Returns: + An L1L2 Regularizer with the given regularization factors. + """ + return L1L2(l1=l1, l2=l2) + + +# Deserialization aliases. +l1 = L1 +l2 = L2 + + +def serialize(regularizer): + return serialize_keras_object(regularizer) + + +def deserialize(config, custom_objects=None): + if config == 'l1_l2': + # Special case necessary since the defaults used for "l1_l2" (string) + # differ from those of the L1L2 class. + return L1L2(l1=0.01, l2=0.01) + return deserialize_keras_object( + config, + module_objects=globals(), + custom_objects=custom_objects, + printable_module_name='regularizer') + + +def get(identifier): + """Retrieve a regularizer instance from a config or identifier.""" + if identifier is None: + return None + if isinstance(identifier, dict): + return deserialize(identifier) + elif isinstance(identifier, str): + return deserialize(str(identifier)) + elif callable(identifier): + return identifier + else: + raise ValueError( + 'Could not interpret regularizer identifier: {}'.format(identifier)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/hdf5_format.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/hdf5_format.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6bbc43320d0a46e741b9e6bbaf8078ae583e20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/hdf5_format.py @@ -0,0 +1,899 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Functions for saving and loading a Keras Model from HDF5 format.""" + +import json +import os + +import numpy as np + +from tensorflow.python.keras import backend +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras.saving import model_config as model_config_lib +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import json_utils +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite +from tensorflow.python.ops import variables as variables_module +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging + + +# pylint: disable=g-import-not-at-top +try: + import h5py + HDF5_OBJECT_HEADER_LIMIT = 64512 +except ImportError: + h5py = None +# pylint: enable=g-import-not-at-top + +# TODO(b/134426265): Switch back to single-quotes to match the rest of the file +# once the issue with copybara is fixed. +# pylint:disable=g-inconsistent-quotes +sequential_lib = LazyLoader( + "sequential_lib", globals(), + "tensorflow.python.keras.engine.sequential") +# pylint:enable=g-inconsistent-quotes + + +def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): + """Saves a model to a HDF5 file. + + The saved model contains: + - the model's configuration (topology) + - the model's weights + - the model's optimizer's state (if any) + + Thus the saved model can be reinstantiated in + the exact same state, without any of the code + used for model definition or training. + + Args: + model: Keras model instance to be saved. + filepath: One of the following: + - String, path where to save the model + - `h5py.File` object where to save the model + overwrite: Whether we should overwrite any existing + model at the target location, or instead + ask the user with a manual prompt. + include_optimizer: If True, save optimizer's state together. + + Raises: + ImportError: if h5py is not available. + """ + + if h5py is None: + raise ImportError('`save_model` requires h5py.') + + # TODO(psv) Add warning when we save models that contain non-serializable + # entities like metrics added using `add_metric` and losses added using + # `add_loss.` + if len(model.weights) != len(model._undeduplicated_weights): + logging.warning('Found duplicated `Variable`s in Model\'s `weights`. ' + 'This is usually caused by `Variable`s being shared by ' + 'Layers in the Model. These `Variable`s will be treated ' + 'as separate `Variable`s when the Model is restored. To ' + 'avoid this, please save with `save_format="tf"`.') + + if not isinstance(filepath, h5py.File): + # If file exists and should not be overwritten. + if not overwrite and os.path.isfile(filepath): + proceed = ask_to_proceed_with_overwrite(filepath) + if not proceed: + return + + # Try creating dir if not exist + dirpath = os.path.dirname(filepath) + if not os.path.exists(dirpath): + gfile.MakeDirs(dirpath) + + f = h5py.File(filepath, mode='w') + opened_new_file = True + else: + f = filepath + opened_new_file = False + + try: + model_metadata = saving_utils.model_metadata(model, include_optimizer) + for k, v in model_metadata.items(): + if isinstance(v, (dict, list, tuple)): + f.attrs[k] = json.dumps( + v, default=json_utils.get_json_type).encode('utf8') + else: + f.attrs[k] = v + + model_weights_group = f.create_group('model_weights') + model_layers = model.layers + save_weights_to_hdf5_group(model_weights_group, model_layers) + + # TODO(b/128683857): Add integration tests between tf.keras and external + # Keras, to avoid breaking TF.js users. + if (include_optimizer and model.optimizer and + not isinstance(model.optimizer, optimizer_v1.TFOptimizer)): + save_optimizer_weights_to_hdf5_group(f, model.optimizer) + + f.flush() + finally: + if opened_new_file: + f.close() + + +def load_model_from_hdf5(filepath, custom_objects=None, compile=True): # pylint: disable=redefined-builtin + """Loads a model saved via `save_model_to_hdf5`. + + Args: + filepath: One of the following: + - String, path to the saved model + - `h5py.File` object from which to load the model + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + compile: Boolean, whether to compile the model + after loading. + + Returns: + A Keras model instance. If an optimizer was found + as part of the saved model, the model is already + compiled. Otherwise, the model is uncompiled and + a warning will be displayed. When `compile` is set + to False, the compilation is omitted without any + warning. + + Raises: + ImportError: if h5py is not available. + ValueError: In case of an invalid savefile. + """ + if h5py is None: + raise ImportError('`load_model` requires h5py.') + + if not custom_objects: + custom_objects = {} + + opened_new_file = not isinstance(filepath, h5py.File) + if opened_new_file: + f = h5py.File(filepath, mode='r') + else: + f = filepath + + model = None + try: + # instantiate model + model_config = f.attrs.get('model_config') + if model_config is None: + raise ValueError('No model found in config file.') + if hasattr(model_config, 'decode'): + model_config = model_config.decode('utf-8') + model_config = json_utils.decode(model_config) + model = model_config_lib.model_from_config(model_config, + custom_objects=custom_objects) + + # set weights + load_weights_from_hdf5_group(f['model_weights'], model.layers) + + if compile: + # instantiate optimizer + training_config = f.attrs.get('training_config') + if hasattr(training_config, 'decode'): + training_config = training_config.decode('utf-8') + if training_config is None: + logging.warning('No training configuration found in the save file, so ' + 'the model was *not* compiled. Compile it manually.') + return model + training_config = json_utils.decode(training_config) + + # Compile model. + model.compile(**saving_utils.compile_args_from_training_config( + training_config, custom_objects), from_serialized=True) + saving_utils.try_build_compiled_arguments(model) + + # Set optimizer weights. + if 'optimizer_weights' in f: + try: + model.optimizer._create_all_weights(model.trainable_variables) + except (NotImplementedError, AttributeError): + logging.warning( + 'Error when creating the weights of optimizer {}, making it ' + 'impossible to restore the saved optimizer state. As a result, ' + 'your model is starting with a freshly initialized optimizer.') + + optimizer_weight_values = load_optimizer_weights_from_hdf5_group(f) + try: + model.optimizer.set_weights(optimizer_weight_values) + except ValueError: + logging.warning('Error in loading the saved optimizer ' + 'state. As a result, your model is ' + 'starting with a freshly initialized ' + 'optimizer.') + finally: + if opened_new_file: + f.close() + return model + + +def preprocess_weights_for_loading(layer, + weights, + original_keras_version=None, + original_backend=None): + """Preprocess layer weights between different Keras formats. + + Converts layers weights from Keras 1 format to Keras 2 and also weights of + CuDNN layers in Keras 2. + + Args: + layer: Layer instance. + weights: List of weights values (Numpy arrays). + original_keras_version: Keras version for the weights, as a string. + original_backend: Keras backend the weights were trained with, + as a string. + + Returns: + A list of weights values (Numpy arrays). + """ + def convert_nested_bidirectional(weights): + """Converts layers nested in `Bidirectional` wrapper. + + This function uses `preprocess_weights_for_loading()` for converting + layers. + + Args: + weights: List of weights values (Numpy arrays). + + Returns: + A list of weights values (Numpy arrays). + """ + num_weights_per_layer = len(weights) // 2 + forward_weights = preprocess_weights_for_loading( + layer.forward_layer, weights[:num_weights_per_layer], + original_keras_version, original_backend) + backward_weights = preprocess_weights_for_loading( + layer.backward_layer, weights[num_weights_per_layer:], + original_keras_version, original_backend) + return forward_weights + backward_weights + + def convert_nested_time_distributed(weights): + """Converts layers nested in `TimeDistributed` wrapper. + + This function uses `preprocess_weights_for_loading()` for converting nested + layers. + + Args: + weights: List of weights values (Numpy arrays). + + Returns: + A list of weights values (Numpy arrays). + """ + return preprocess_weights_for_loading( + layer.layer, weights, original_keras_version, original_backend) + + def convert_nested_model(weights): + """Converts layers nested in `Model` or `Sequential`. + + This function uses `preprocess_weights_for_loading()` for converting nested + layers. + + Args: + weights: List of weights values (Numpy arrays). + + Returns: + A list of weights values (Numpy arrays). + """ + trainable_weights = weights[:len(layer.trainable_weights)] + non_trainable_weights = weights[len(layer.trainable_weights):] + + new_trainable_weights = [] + new_non_trainable_weights = [] + + for sublayer in layer.layers: + num_trainable_weights = len(sublayer.trainable_weights) + num_non_trainable_weights = len(sublayer.non_trainable_weights) + if sublayer.weights: + preprocessed = preprocess_weights_for_loading( + layer=sublayer, + weights=(trainable_weights[:num_trainable_weights] + + non_trainable_weights[:num_non_trainable_weights]), + original_keras_version=original_keras_version, + original_backend=original_backend) + new_trainable_weights.extend(preprocessed[:num_trainable_weights]) + new_non_trainable_weights.extend(preprocessed[num_trainable_weights:]) + + trainable_weights = trainable_weights[num_trainable_weights:] + non_trainable_weights = non_trainable_weights[ + num_non_trainable_weights:] + + return new_trainable_weights + new_non_trainable_weights + + # Convert layers nested in Bidirectional/Model/Sequential. + # Both transformation should be ran for both Keras 1->2 conversion + # and for conversion of CuDNN layers. + if layer.__class__.__name__ == 'Bidirectional': + weights = convert_nested_bidirectional(weights) + if layer.__class__.__name__ == 'TimeDistributed': + weights = convert_nested_time_distributed(weights) + elif layer.__class__.__name__ in ['Model', 'Sequential', 'Functional']: + weights = convert_nested_model(weights) + + if original_keras_version == '1': + if layer.__class__.__name__ == 'TimeDistributed': + weights = preprocess_weights_for_loading( + layer.layer, weights, original_keras_version, original_backend) + + if layer.__class__.__name__ == 'Conv1D': + shape = weights[0].shape + # Handle Keras 1.1 format + if shape[:2] != (layer.kernel_size[0], 1) or shape[3] != layer.filters: + # Legacy shape: + # (filters, input_dim, filter_length, 1) + assert shape[0] == layer.filters and shape[2:] == (layer.kernel_size[0], + 1) + weights[0] = np.transpose(weights[0], (2, 3, 1, 0)) + weights[0] = weights[0][:, 0, :, :] + + if layer.__class__.__name__ == 'Conv2D': + if layer.data_format == 'channels_first': + # old: (filters, stack_size, kernel_rows, kernel_cols) + # new: (kernel_rows, kernel_cols, stack_size, filters) + weights[0] = np.transpose(weights[0], (2, 3, 1, 0)) + + if layer.__class__.__name__ == 'Conv2DTranspose': + if layer.data_format == 'channels_last': + # old: (kernel_rows, kernel_cols, stack_size, filters) + # new: (kernel_rows, kernel_cols, filters, stack_size) + weights[0] = np.transpose(weights[0], (0, 1, 3, 2)) + if layer.data_format == 'channels_first': + # old: (filters, stack_size, kernel_rows, kernel_cols) + # new: (kernel_rows, kernel_cols, filters, stack_size) + weights[0] = np.transpose(weights[0], (2, 3, 0, 1)) + + if layer.__class__.__name__ == 'Conv3D': + if layer.data_format == 'channels_first': + # old: (filters, stack_size, ...) + # new: (..., stack_size, filters) + weights[0] = np.transpose(weights[0], (2, 3, 4, 1, 0)) + + if layer.__class__.__name__ == 'GRU': + if len(weights) == 9: + kernel = np.concatenate([weights[0], weights[3], weights[6]], axis=-1) + recurrent_kernel = np.concatenate( + [weights[1], weights[4], weights[7]], axis=-1) + bias = np.concatenate([weights[2], weights[5], weights[8]], axis=-1) + weights = [kernel, recurrent_kernel, bias] + + if layer.__class__.__name__ == 'LSTM': + if len(weights) == 12: + # old: i, c, f, o + # new: i, f, c, o + kernel = np.concatenate( + [weights[0], weights[6], weights[3], weights[9]], axis=-1) + recurrent_kernel = np.concatenate( + [weights[1], weights[7], weights[4], weights[10]], axis=-1) + bias = np.concatenate( + [weights[2], weights[8], weights[5], weights[11]], axis=-1) + weights = [kernel, recurrent_kernel, bias] + + if layer.__class__.__name__ == 'ConvLSTM2D': + if len(weights) == 12: + kernel = np.concatenate( + [weights[0], weights[6], weights[3], weights[9]], axis=-1) + recurrent_kernel = np.concatenate( + [weights[1], weights[7], weights[4], weights[10]], axis=-1) + bias = np.concatenate( + [weights[2], weights[8], weights[5], weights[11]], axis=-1) + if layer.data_format == 'channels_first': + # old: (filters, stack_size, kernel_rows, kernel_cols) + # new: (kernel_rows, kernel_cols, stack_size, filters) + kernel = np.transpose(kernel, (2, 3, 1, 0)) + recurrent_kernel = np.transpose(recurrent_kernel, (2, 3, 1, 0)) + weights = [kernel, recurrent_kernel, bias] + + conv_layers = ['Conv1D', 'Conv2D', 'Conv3D', 'Conv2DTranspose', 'ConvLSTM2D'] + if layer.__class__.__name__ in conv_layers: + if backend.int_shape(layer.weights[0]) != weights[0].shape: + weights[0] = np.transpose(weights[0], (3, 2, 0, 1)) + if layer.__class__.__name__ == 'ConvLSTM2D': + weights[1] = np.transpose(weights[1], (3, 2, 0, 1)) + + # convert CuDNN layers + return _convert_rnn_weights(layer, weights) + + +def _convert_rnn_weights(layer, weights): + """Converts weights for RNN layers between native and CuDNN format. + + Input kernels for each gate are transposed and converted between Fortran + and C layout, recurrent kernels are transposed. For LSTM biases are summed/ + split in half, for GRU biases are reshaped. + + Weights can be converted in both directions between `LSTM` and`CuDNNSLTM` + and between `CuDNNGRU` and `GRU(reset_after=True)`. Default `GRU` is not + compatible with `CuDNNGRU`. + + For missing biases in `LSTM`/`GRU` (`use_bias=False`) no conversion is made. + + Args: + layer: Target layer instance. + weights: List of source weights values (input kernels, recurrent + kernels, [biases]) (Numpy arrays). + + Returns: + A list of converted weights values (Numpy arrays). + + Raises: + ValueError: for incompatible GRU layer/weights or incompatible biases + """ + + def transform_kernels(kernels, func, n_gates): + """Transforms kernel for each gate separately using given function. + + Args: + kernels: Stacked array of kernels for individual gates. + func: Function applied to kernel of each gate. + n_gates: Number of gates (4 for LSTM, 3 for GRU). + + Returns: + Stacked array of transformed kernels. + """ + return np.hstack([func(k) for k in np.hsplit(kernels, n_gates)]) + + def transpose_input(from_cudnn): + """Makes a function that transforms input kernels from/to CuDNN format. + + It keeps the shape, but changes between the layout (Fortran/C). Eg.: + + ``` + Keras CuDNN + [[0, 1, 2], <---> [[0, 2, 4], + [3, 4, 5]] [1, 3, 5]] + ``` + + It can be passed to `transform_kernels()`. + + Args: + from_cudnn: `True` if source weights are in CuDNN format, `False` + if they're in plain Keras format. + + Returns: + Function that converts input kernel to the other format. + """ + order = 'F' if from_cudnn else 'C' + + def transform(kernel): + return kernel.T.reshape(kernel.shape, order=order) + + return transform + + target_class = layer.__class__.__name__ + + # convert the weights between CuDNNLSTM and LSTM + if target_class in ['LSTM', 'CuDNNLSTM'] and len(weights) == 3: + # determine if we're loading a CuDNNLSTM layer + # from the number of bias weights: + # CuDNNLSTM has (units * 8) weights; while LSTM has (units * 4) + # if there's no bias weight in the file, skip this conversion + units = weights[1].shape[0] + bias_shape = weights[2].shape + n_gates = 4 + + if bias_shape == (2 * units * n_gates,): + source = 'CuDNNLSTM' + elif bias_shape == (units * n_gates,): + source = 'LSTM' + else: + raise ValueError('Invalid bias shape: ' + str(bias_shape)) + + def convert_lstm_weights(weights, from_cudnn=True): + """Converts the weights between CuDNNLSTM and LSTM. + + Args: + weights: Original weights. + from_cudnn: Indicates whether original weights are from CuDNN layer. + + Returns: + Updated weights compatible with LSTM. + """ + + # Transpose (and reshape) input and recurrent kernels + kernels = transform_kernels(weights[0], transpose_input(from_cudnn), + n_gates) + recurrent_kernels = transform_kernels(weights[1], lambda k: k.T, n_gates) + if from_cudnn: + # merge input and recurrent biases into a single set + biases = np.sum(np.split(weights[2], 2, axis=0), axis=0) + else: + # Split single set of biases evenly to two sets. The way of + # splitting doesn't matter as long as the two sets sum is kept. + biases = np.tile(0.5 * weights[2], 2) + return [kernels, recurrent_kernels, biases] + + if source != target_class: + weights = convert_lstm_weights(weights, from_cudnn=source == 'CuDNNLSTM') + + # convert the weights between CuDNNGRU and GRU(reset_after=True) + if target_class in ['GRU', 'CuDNNGRU'] and len(weights) == 3: + # We can determine the source of the weights from the shape of the bias. + # If there is no bias we skip the conversion since + # CuDNNGRU always has biases. + + units = weights[1].shape[0] + bias_shape = weights[2].shape + n_gates = 3 + + def convert_gru_weights(weights, from_cudnn=True): + """Converts the weights between CuDNNGRU and GRU. + + Args: + weights: Original weights. + from_cudnn: Indicates whether original weights are from CuDNN layer. + + Returns: + Updated weights compatible with GRU. + """ + + kernels = transform_kernels(weights[0], transpose_input(from_cudnn), + n_gates) + recurrent_kernels = transform_kernels(weights[1], lambda k: k.T, n_gates) + biases = np.array(weights[2]).reshape((2, -1) if from_cudnn else -1) + return [kernels, recurrent_kernels, biases] + + if bias_shape == (2 * units * n_gates,): + source = 'CuDNNGRU' + elif bias_shape == (2, units * n_gates): + source = 'GRU(reset_after=True)' + elif bias_shape == (units * n_gates,): + source = 'GRU(reset_after=False)' + else: + raise ValueError('Invalid bias shape: ' + str(bias_shape)) + + if target_class == 'CuDNNGRU': + target = 'CuDNNGRU' + elif layer.reset_after: + target = 'GRU(reset_after=True)' + else: + target = 'GRU(reset_after=False)' + + # only convert between different types + if source != target: + types = (source, target) + if 'GRU(reset_after=False)' in types: + raise ValueError('%s is not compatible with %s' % types) + if source == 'CuDNNGRU': + weights = convert_gru_weights(weights, from_cudnn=True) + elif source == 'GRU(reset_after=True)': + weights = convert_gru_weights(weights, from_cudnn=False) + + return weights + + +def save_optimizer_weights_to_hdf5_group(hdf5_group, optimizer): + """Saves optimizer weights of a optimizer to a HDF5 group. + + Args: + hdf5_group: HDF5 group. + optimizer: optimizer instance. + """ + + symbolic_weights = getattr(optimizer, 'weights') + if symbolic_weights: + weights_group = hdf5_group.create_group('optimizer_weights') + weight_names = [str(w.name).encode('utf8') for w in symbolic_weights] + save_attributes_to_hdf5_group(weights_group, 'weight_names', weight_names) + weight_values = backend.batch_get_value(symbolic_weights) + for name, val in zip(weight_names, weight_values): + param_dset = weights_group.create_dataset( + name, val.shape, dtype=val.dtype) + if not val.shape: + # scalar + param_dset[()] = val + else: + param_dset[:] = val + + +def load_optimizer_weights_from_hdf5_group(hdf5_group): + """Load optimizer weights from a HDF5 group. + + Args: + hdf5_group: A pointer to a HDF5 group. + + Returns: + data: List of optimizer weight names. + """ + weights_group = hdf5_group['optimizer_weights'] + optimizer_weight_names = load_attributes_from_hdf5_group( + weights_group, 'weight_names') + return [weights_group[weight_name] for weight_name in optimizer_weight_names] + + +def save_weights_to_hdf5_group(f, layers): + """Saves the weights of a list of layers to a HDF5 group. + + Args: + f: HDF5 group. + layers: List of layer instances. + """ + from tensorflow.python.keras import __version__ as keras_version # pylint: disable=g-import-not-at-top + + save_attributes_to_hdf5_group( + f, 'layer_names', [layer.name.encode('utf8') for layer in layers]) + f.attrs['backend'] = backend.backend().encode('utf8') + f.attrs['keras_version'] = str(keras_version).encode('utf8') + + # Sort model layers by layer name to ensure that group names are strictly + # growing to avoid prefix issues. + for layer in sorted(layers, key=lambda x: x.name): + g = f.create_group(layer.name) + weights = _legacy_weights(layer) + weight_values = backend.batch_get_value(weights) + weight_names = [w.name.encode('utf8') for w in weights] + save_attributes_to_hdf5_group(g, 'weight_names', weight_names) + for name, val in zip(weight_names, weight_values): + param_dset = g.create_dataset(name, val.shape, dtype=val.dtype) + if not val.shape: + # scalar + param_dset[()] = val + else: + param_dset[:] = val + + +def load_weights_from_hdf5_group(f, layers): + """Implements topological (order-based) weight loading. + + Args: + f: A pointer to a HDF5 group. + layers: a list of target layers. + + Raises: + ValueError: in case of mismatch between provided layers + and weights file. + """ + if 'keras_version' in f.attrs: + original_keras_version = f.attrs['keras_version'] + if hasattr(original_keras_version, 'decode'): + original_keras_version = original_keras_version.decode('utf8') + else: + original_keras_version = '1' + if 'backend' in f.attrs: + original_backend = f.attrs['backend'] + if hasattr(original_backend, 'decode'): + original_backend = original_backend.decode('utf8') + else: + original_backend = None + + filtered_layers = [] + for layer in layers: + weights = _legacy_weights(layer) + if weights: + filtered_layers.append(layer) + + layer_names = load_attributes_from_hdf5_group(f, 'layer_names') + filtered_layer_names = [] + for name in layer_names: + g = f[name] + weight_names = load_attributes_from_hdf5_group(g, 'weight_names') + if weight_names: + filtered_layer_names.append(name) + layer_names = filtered_layer_names + if len(layer_names) != len(filtered_layers): + raise ValueError('You are trying to load a weight file ' + 'containing ' + str(len(layer_names)) + + ' layers into a model with ' + str(len(filtered_layers)) + + ' layers.') + + # We batch weight value assignments in a single backend call + # which provides a speedup in TensorFlow. + weight_value_tuples = [] + for k, name in enumerate(layer_names): + g = f[name] + weight_names = load_attributes_from_hdf5_group(g, 'weight_names') + weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names] + layer = filtered_layers[k] + symbolic_weights = _legacy_weights(layer) + weight_values = preprocess_weights_for_loading( + layer, weight_values, original_keras_version, original_backend) + if len(weight_values) != len(symbolic_weights): + raise ValueError('Layer #' + str(k) + ' (named "' + layer.name + + '" in the current model) was found to ' + 'correspond to layer ' + name + ' in the save file. ' + 'However the new layer ' + layer.name + ' expects ' + + str(len(symbolic_weights)) + + ' weights, but the saved weights have ' + + str(len(weight_values)) + ' elements.') + weight_value_tuples += zip(symbolic_weights, weight_values) + backend.batch_set_value(weight_value_tuples) + + +def load_weights_from_hdf5_group_by_name( + f, layers, skip_mismatch=False): + """Implements name-based weight loading. + + (instead of topological weight loading). + + Layers that have no matching name are skipped. + + Args: + f: A pointer to a HDF5 group. + layers: a list of target layers. + skip_mismatch: Boolean, whether to skip loading of layers + where there is a mismatch in the number of weights, + or a mismatch in the shape of the weights. + + Raises: + ValueError: in case of mismatch between provided layers + and weights file and skip_match=False. + """ + if 'keras_version' in f.attrs: + original_keras_version = f.attrs['keras_version'] + if hasattr(original_keras_version, 'decode'): + original_keras_version = original_keras_version.decode('utf8') + else: + original_keras_version = '1' + if 'backend' in f.attrs: + original_backend = f.attrs['backend'] + if hasattr(original_backend, 'decode'): + original_backend = original_backend.decode('utf8') + else: + original_backend = None + + # New file format. + layer_names = load_attributes_from_hdf5_group(f, 'layer_names') + + # Reverse index of layer name to list of layers with name. + index = {} + for layer in layers: + if layer.name: + index.setdefault(layer.name, []).append(layer) + + # We batch weight value assignments in a single backend call + # which provides a speedup in TensorFlow. + weight_value_tuples = [] + for k, name in enumerate(layer_names): + g = f[name] + weight_names = load_attributes_from_hdf5_group(g, 'weight_names') + weight_values = [np.asarray(g[weight_name]) for weight_name in weight_names] + + for layer in index.get(name, []): + symbolic_weights = _legacy_weights(layer) + weight_values = preprocess_weights_for_loading( + layer, weight_values, original_keras_version, original_backend) + if len(weight_values) != len(symbolic_weights): + if skip_mismatch: + logging.warning('Skipping loading of weights for ' + 'layer {}'.format(layer.name) + ' due to mismatch ' + 'in number of weights ({} vs {}).'.format( + len(symbolic_weights), len(weight_values))) + continue + raise ValueError('Layer #' + str(k) + ' (named "' + layer.name + + '") expects ' + str(len(symbolic_weights)) + + ' weight(s), but the saved weights' + ' have ' + + str(len(weight_values)) + ' element(s).') + # Set values. + for i in range(len(weight_values)): + if backend.int_shape(symbolic_weights[i]) != weight_values[i].shape: + if skip_mismatch: + logging.warning('Skipping loading of weights for ' + 'layer {}'.format(layer.name) + ' due to ' + 'mismatch in shape ({} vs {}).'.format( + symbolic_weights[i].shape, + weight_values[i].shape)) + continue + raise ValueError('Layer #' + str(k) +' (named "' + layer.name + + '"), weight ' + str(symbolic_weights[i]) + + ' has shape {}'.format(backend.int_shape( + symbolic_weights[i])) + + ', but the saved weight has shape ' + + str(weight_values[i].shape) + '.') + + else: + weight_value_tuples.append((symbolic_weights[i], weight_values[i])) + backend.batch_set_value(weight_value_tuples) + + +def save_attributes_to_hdf5_group(group, name, data): + """Saves attributes (data) of the specified name into the HDF5 group. + + This method deals with an inherent problem of HDF5 file which is not + able to store data larger than HDF5_OBJECT_HEADER_LIMIT bytes. + + Args: + group: A pointer to a HDF5 group. + name: A name of the attributes to save. + data: Attributes data to store. + + Raises: + RuntimeError: If any single attribute is too large to be saved. + """ + # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` + # because in that case even chunking the array would not make the saving + # possible. + bad_attributes = [x for x in data if len(x) > HDF5_OBJECT_HEADER_LIMIT] + + # Expecting this to never be true. + if bad_attributes: + raise RuntimeError('The following attributes cannot be saved to HDF5 ' + 'file because they are larger than %d bytes: %s' % + (HDF5_OBJECT_HEADER_LIMIT, ', '.join(bad_attributes))) + + data_npy = np.asarray(data) + + num_chunks = 1 + chunked_data = np.array_split(data_npy, num_chunks) + + # This will never loop forever thanks to the test above. + while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data): + num_chunks += 1 + chunked_data = np.array_split(data_npy, num_chunks) + + if num_chunks > 1: + for chunk_id, chunk_data in enumerate(chunked_data): + group.attrs['%s%d' % (name, chunk_id)] = chunk_data + else: + group.attrs[name] = data + + +def load_attributes_from_hdf5_group(group, name): + """Loads attributes of the specified name from the HDF5 group. + + This method deals with an inherent problem + of HDF5 file which is not able to store + data larger than HDF5_OBJECT_HEADER_LIMIT bytes. + + Args: + group: A pointer to a HDF5 group. + name: A name of the attributes to load. + + Returns: + data: Attributes data. + """ + if name in group.attrs: + data = [ + n.decode('utf8') if hasattr(n, 'decode') else n + for n in group.attrs[name] + ] + else: + data = [] + chunk_id = 0 + while '%s%d' % (name, chunk_id) in group.attrs: + data.extend([ + n.decode('utf8') if hasattr(n, 'decode') else n + for n in group.attrs['%s%d' % (name, chunk_id)] + ]) + chunk_id += 1 + return data + + +def _legacy_weights(layer): + """DO NOT USE. + + For legacy reason, the layer.weights was in the order of + [self.trainable_weights + self.non_trainable_weights], and this order was + used for preserving the weights in h5 format. The new order of layer.weights + are the same as layer.get_weights() which is more intuitive for user. To + keep supporting the existing saved h5 file, this method should be used to + save/load weights. In future version, we will delete this method and + introduce a breaking change for h5 and stay with the new order for weights. + + Args: + layer: a `tf.keras.Model` or `tf.keras.layers.Layer` instance. + + Returns: + A list of variables with the order of trainable_weights, followed by + non_trainable_weights. + """ + weights = layer.trainable_weights + layer.non_trainable_weights + if any(not isinstance(w, variables_module.Variable) for w in weights): + raise NotImplementedError( + 'Save or restore weights that is not an instance of `tf.Variable` is ' + 'not supported in h5, use `save_format=\'tf\'` instead. Got a model ' + 'or layer {} with weights {}'.format(layer.__class__.__name__, weights)) + return weights diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/model_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..fc151339edbebaa9d201ec90cd153434ef9a55c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/model_config.py @@ -0,0 +1,100 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Functions that save the model's config into different formats.""" + +from tensorflow.python.keras.saving.saved_model import json_utils + + +def model_from_config(config, custom_objects=None): + """Instantiates a Keras model from its config. + + Usage: + ``` + # for a Functional API model + tf.keras.Model().from_config(model.get_config()) + + # for a Sequential model + tf.keras.Sequential().from_config(model.get_config()) + ``` + + Args: + config: Configuration dictionary. + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + + Returns: + A Keras model instance (uncompiled). + + Raises: + TypeError: if `config` is not a dictionary. + """ + if isinstance(config, list): + raise TypeError('`model_from_config` expects a dictionary, not a list. ' + 'Maybe you meant to use ' + '`Sequential.from_config(config)`?') + from tensorflow.python.keras.layers import deserialize # pylint: disable=g-import-not-at-top + return deserialize(config, custom_objects=custom_objects) + + +def model_from_yaml(yaml_string, custom_objects=None): + """Parses a yaml model configuration file and returns a model instance. + + Note: Since TF 2.6, this method is no longer supported and will raise a + RuntimeError. + + Args: + yaml_string: YAML string or open file encoding a model configuration. + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + + Returns: + A Keras model instance (uncompiled). + + Raises: + RuntimeError: announces that the method poses a security risk + """ + raise RuntimeError( + 'Method `model_from_yaml()` has been removed due to security risk of ' + 'arbitrary code execution. Please use `Model.to_json()` and ' + '`model_from_json()` instead.' + ) + + +def model_from_json(json_string, custom_objects=None): + """Parses a JSON model configuration string and returns a model instance. + + Usage: + + >>> model = tf.keras.Sequential([ + ... tf.keras.layers.Dense(5, input_shape=(3,)), + ... tf.keras.layers.Softmax()]) + >>> config = model.to_json() + >>> loaded_model = tf.keras.models.model_from_json(config) + + Args: + json_string: JSON string encoding a model configuration. + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + + Returns: + A Keras model instance (uncompiled). + """ + config = json_utils.decode(json_string) + from tensorflow.python.keras.layers import deserialize # pylint: disable=g-import-not-at-top + return deserialize(config, custom_objects=custom_objects) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/save.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/save.py new file mode 100644 index 0000000000000000000000000000000000000000..eee859233e5eba2c1c68cb0e39b9de50119b200b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/save.py @@ -0,0 +1,206 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras model saving code.""" + +from tensorflow.python import tf2 +from tensorflow.python.keras.saving import hdf5_format +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import load as saved_model_load +from tensorflow.python.keras.saving.saved_model import load_context +from tensorflow.python.keras.saving.saved_model import save as saved_model_save +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils.io_utils import path_to_string + +# pylint: disable=g-import-not-at-top +try: + import h5py +except ImportError: + h5py = None +# pylint: enable=g-import-not-at-top + + +def save_model(model, + filepath, + overwrite=True, + include_optimizer=True, + save_format=None, + signatures=None, + options=None, + save_traces=True): + # pylint: disable=line-too-long + """Saves a model as a TensorFlow SavedModel or HDF5 file. + + See the [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) + for details. + + Usage: + + >>> model = tf.keras.Sequential([ + ... tf.keras.layers.Dense(5, input_shape=(3,)), + ... tf.keras.layers.Softmax()]) + >>> model.save('/tmp/model') + >>> loaded_model = tf.keras.models.load_model('/tmp/model') + >>> x = tf.random.uniform((10, 3)) + >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) + + The SavedModel and HDF5 file contains: + + - the model's configuration (topology) + - the model's weights + - the model's optimizer's state (if any) + + Thus models can be reinstantiated in the exact same state, without any of the + code used for model definition or training. + + Note that the model weights may have different scoped names after being + loaded. Scoped names include the model/layer names, such as + `"dense_1/kernel:0"`. It is recommended that you use the layer properties to + access specific variables, e.g. `model.get_layer("dense_1").kernel`. + + __SavedModel serialization format__ + + Keras SavedModel uses `tf.saved_model.save` to save the model and all + trackable objects attached to the model (e.g. layers and variables). The model + config, weights, and optimizer are saved in the SavedModel. Additionally, for + every Keras layer attached to the model, the SavedModel stores: + + * the config and metadata -- e.g. name, dtype, trainable status + * traced call and loss functions, which are stored as TensorFlow subgraphs. + + The traced functions allow the SavedModel format to save and load custom + layers without the original class definition. + + You can choose to not save the traced functions by disabling the `save_traces` + option. This will decrease the time it takes to save the model and the + amount of disk space occupied by the output SavedModel. If you enable this + option, then you _must_ provide all custom class definitions when loading + the model. See the `custom_objects` argument in `tf.keras.models.load_model`. + + Args: + model: Keras model instance to be saved. + filepath: One of the following: + - String or `pathlib.Path` object, path where to save the model + - `h5py.File` object where to save the model + overwrite: Whether we should overwrite any existing model at the target + location, or instead ask the user with a manual prompt. + include_optimizer: If True, save optimizer's state together. + save_format: Either 'tf' or 'h5', indicating whether to save the model + to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' + in TF 1.X. + signatures: Signatures to save with the SavedModel. Applicable to the 'tf' + format only. Please see the `signatures` argument in + `tf.saved_model.save` for details. + options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` + object that specifies options for saving to SavedModel. + save_traces: (only applies to SavedModel format) When enabled, the + SavedModel will store the function traces for each layer. This + can be disabled, so that only the configs of each layer are stored. + Defaults to `True`. Disabling this will decrease serialization time and + reduce file size, but it requires that all custom layers/models + implement a `get_config()` method. + + Raises: + ImportError: If save format is hdf5, and h5py is not available. + """ + # pylint: enable=line-too-long + from tensorflow.python.keras.engine import sequential # pylint: disable=g-import-not-at-top + + default_format = 'tf' if tf2.enabled() else 'h5' + save_format = save_format or default_format + + filepath = path_to_string(filepath) + + # If the user has not already called fit or built the underlying metrics, we + # should do that before saving to ensure the metric names have all + # appropriate name transformations applied. + saving_utils.try_build_compiled_arguments(model) + + if (save_format == 'h5' or + (h5py is not None and isinstance(filepath, h5py.File)) or + saving_utils.is_hdf5_filepath(filepath)): + # TODO(b/130258301): add utility method for detecting model type. + if (not model._is_graph_network and # pylint:disable=protected-access + not isinstance(model, sequential.Sequential)): + raise NotImplementedError( + 'Saving the model to HDF5 format requires the model to be a ' + 'Functional model or a Sequential model. It does not work for ' + 'subclassed models, because such models are defined via the body of ' + 'a Python method, which isn\'t safely serializable. Consider saving ' + 'to the Tensorflow SavedModel format (by setting save_format="tf") ' + 'or using `save_weights`.') + hdf5_format.save_model_to_hdf5( + model, filepath, overwrite, include_optimizer) + else: + with generic_utils.SharedObjectSavingScope(): + saved_model_save.save(model, filepath, overwrite, include_optimizer, + signatures, options, save_traces) + + +def load_model(filepath, custom_objects=None, compile=True, options=None): # pylint: disable=redefined-builtin + """Loads a model saved via `model.save()`. + + Usage: + + >>> model = tf.keras.Sequential([ + ... tf.keras.layers.Dense(5, input_shape=(3,)), + ... tf.keras.layers.Softmax()]) + >>> model.save('/tmp/model') + >>> loaded_model = tf.keras.models.load_model('/tmp/model') + >>> x = tf.random.uniform((10, 3)) + >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) + + Note that the model weights may have different scoped names after being + loaded. Scoped names include the model/layer names, such as + `"dense_1/kernel:0"`. It is recommended that you use the layer properties to + access specific variables, e.g. `model.get_layer("dense_1").kernel`. + + Args: + filepath: One of the following: + - String or `pathlib.Path` object, path to the saved model + - `h5py.File` object from which to load the model + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + compile: Boolean, whether to compile the model + after loading. + options: Optional `tf.saved_model.LoadOptions` object that specifies + options for loading from SavedModel. + + Returns: + A Keras model instance. If the original model was compiled, and saved with + the optimizer, then the returned model will be compiled. Otherwise, the + model will be left uncompiled. In the case that an uncompiled model is + returned, a warning is displayed if the `compile` argument is set to + `True`. + + Raises: + ImportError: if loading from an hdf5 file and h5py is not available. + IOError: In case of an invalid savefile. + """ + with generic_utils.SharedObjectLoadingScope(): + with generic_utils.CustomObjectScope(custom_objects or {}): + with load_context.load_context(options): + if (h5py is not None and + (isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))): + return hdf5_format.load_model_from_hdf5(filepath, custom_objects, + compile) + + filepath = path_to_string(filepath) + if isinstance(filepath, str): + return saved_model_load.load(filepath, compile, options) + + raise IOError( + 'Unable to load model. Filepath is not an hdf5 file (or h5py is not ' + 'available) or SavedModel.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/base_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/base_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e24d2b6226b268e3d2be22f9fd9e6aa9612996 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/base_serialization.py @@ -0,0 +1,134 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper classes that list&validate all attributes to serialize to SavedModel.""" + +import abc + +from tensorflow.python.keras.saving.saved_model import json_utils +from tensorflow.python.keras.saving.saved_model import utils + + +class SavedModelSaver(object, metaclass=abc.ABCMeta): + """Saver defining the methods and properties used to serialize Keras objects. + """ + + def __init__(self, obj): + self.obj = obj + + @abc.abstractproperty + def object_identifier(self): + """String stored in object identifier field in the SavedModel proto. + + Returns: + A string with the object identifier, which is used at load time. + """ + raise NotImplementedError + + @property + def tracking_metadata(self): + """String stored in metadata field in the SavedModel proto. + + Returns: + A serialized JSON storing information necessary for recreating this layer. + """ + # TODO(kathywu): check that serialized JSON can be loaded (e.g., if an + # object is in the python property) + return json_utils.Encoder().encode(self.python_properties) + + def trackable_children(self, serialization_cache): + """Lists all Trackable children connected to this object.""" + if not utils.should_save_traces(): + return {} + + children = self.objects_to_serialize(serialization_cache) + children.update(self.functions_to_serialize(serialization_cache)) + return children + + @abc.abstractproperty + def python_properties(self): + """Returns dictionary of python properties to save in the metadata. + + This dictionary must be serializable and deserializable to/from JSON. + + When loading, the items in this dict are used to initialize the object and + define attributes in the revived object. + """ + raise NotImplementedError + + @abc.abstractmethod + def objects_to_serialize(self, serialization_cache): + """Returns dictionary of extra checkpointable objects to serialize. + + See `functions_to_serialize` for an explanation of this function's + effects. + + Args: + serialization_cache: Dictionary passed to all objects in the same object + graph during serialization. + + Returns: + A dictionary mapping attribute names to checkpointable objects. + """ + raise NotImplementedError + + @abc.abstractmethod + def functions_to_serialize(self, serialization_cache): + """Returns extra functions to include when serializing a Keras object. + + Normally, when calling exporting an object to SavedModel, only the + functions and objects defined by the user are saved. For example: + + ``` + obj = tf.Module() + obj.v = tf.Variable(1.) + + @tf.function + def foo(...): ... + + obj.foo = foo + + w = tf.Variable(1.) + + tf.saved_model.save(obj, 'path/to/saved/model') + loaded = tf.saved_model.load('path/to/saved/model') + + loaded.v # Variable with the same value as obj.v + loaded.foo # Equivalent to obj.foo + loaded.w # AttributeError + ``` + + Assigning trackable objects to attributes creates a graph, which is used for + both checkpointing and SavedModel serialization. + + When the graph generated from attribute tracking is insufficient, extra + objects and functions may be added at serialization time. For example, + most models do not have their call function wrapped with a @tf.function + decorator. This results in `model.call` not being saved. Since Keras objects + should be revivable from the SavedModel format, the call function is added + as an extra function to serialize. + + This function and `objects_to_serialize` is called multiple times when + exporting to SavedModel. Please use the cache to avoid generating new + functions and objects. A fresh cache is created for each SavedModel export. + + Args: + serialization_cache: Dictionary passed to all objects in the same object + graph during serialization. + + Returns: + A dictionary mapping attribute names to `Function` or + `ConcreteFunction`. + """ + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..fae2c1bd07bc581015f1a69baa675479c946af9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/constants.py @@ -0,0 +1,47 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Constants for Keras SavedModel serialization.""" + +# Namespace used to store all attributes added during serialization. +# e.g. the list of layers can be accessed using `loaded.keras_api.layers`, in an +# object loaded from `tf.saved_model.load()`. +KERAS_ATTR = 'keras_api' + +# Keys for the serialization cache. +# Maps to the keras serialization dict {Layer --> SerializedAttributes object} +KERAS_CACHE_KEY = 'keras_serialized_attributes' + + +# Name of Keras metadata file stored in the SavedModel. +SAVED_METADATA_PATH = 'keras_metadata.pb' + +# Names of SavedObject Keras identifiers. +INPUT_LAYER_IDENTIFIER = '_tf_keras_input_layer' +LAYER_IDENTIFIER = '_tf_keras_layer' +METRIC_IDENTIFIER = '_tf_keras_metric' +MODEL_IDENTIFIER = '_tf_keras_model' +NETWORK_IDENTIFIER = '_tf_keras_network' +RNN_LAYER_IDENTIFIER = '_tf_keras_rnn_layer' +SEQUENTIAL_IDENTIFIER = '_tf_keras_sequential' + +KERAS_OBJECT_IDENTIFIERS = ( + INPUT_LAYER_IDENTIFIER, + LAYER_IDENTIFIER, + METRIC_IDENTIFIER, + MODEL_IDENTIFIER, + NETWORK_IDENTIFIER, + RNN_LAYER_IDENTIFIER, + SEQUENTIAL_IDENTIFIER, +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/json_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/json_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..50ae3ddfe603485535b832cbc01c8745cbe34da5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/json_utils.py @@ -0,0 +1,144 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils for creating and loading the Layer metadata for SavedModel. + +These are required to retain the original format of the build input shape, since +layers and models may have different build behaviors depending on if the shape +is a list, tuple, or TensorShape. For example, Network.build() will create +separate inputs if the given input_shape is a list, and will create a single +input if the given shape is a tuple. +""" + +import collections +import enum +import json +import numpy as np +import wrapt + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.types import internal + + +class Encoder(json.JSONEncoder): + """JSON encoder and decoder that handles TensorShapes and tuples.""" + + def default(self, obj): # pylint: disable=method-hidden + """Encodes objects for types that aren't handled by the default encoder.""" + if isinstance(obj, tensor_shape.TensorShape): + items = obj.as_list() if obj.rank is not None else None + return {'class_name': 'TensorShape', 'items': items} + return get_json_type(obj) + + def encode(self, obj): + return super(Encoder, self).encode(_encode_tuple(obj)) + + +def _encode_tuple(x): + if isinstance(x, tuple): + return {'class_name': '__tuple__', + 'items': tuple(_encode_tuple(i) for i in x)} + elif isinstance(x, list): + return [_encode_tuple(i) for i in x] + elif isinstance(x, dict): + return {key: _encode_tuple(value) for key, value in x.items()} + else: + return x + + +def decode(json_string): + return json.loads(json_string, object_hook=_decode_helper) + + +def _decode_helper(obj): + """A decoding helper that is TF-object aware.""" + if isinstance(obj, dict) and 'class_name' in obj: + if obj['class_name'] == 'TensorShape': + return tensor_shape.TensorShape(obj['items']) + elif obj['class_name'] == 'TypeSpec': + return type_spec_registry.lookup(obj['type_spec'])._deserialize( # pylint: disable=protected-access + _decode_helper(obj['serialized'])) + elif obj['class_name'] == '__tuple__': + return tuple(_decode_helper(i) for i in obj['items']) + elif obj['class_name'] == '__ellipsis__': + return Ellipsis + return obj + + +def get_json_type(obj): + """Serializes any object to a JSON-serializable structure. + + Args: + obj: the object to serialize + + Returns: + JSON-serializable structure representing `obj`. + + Raises: + TypeError: if `obj` cannot be serialized. + """ + # if obj is a serializable Keras class instance + # e.g. optimizer, layer + if hasattr(obj, 'get_config'): + return {'class_name': obj.__class__.__name__, 'config': obj.get_config()} + + # if obj is any numpy type + if type(obj).__module__ == np.__name__: + if isinstance(obj, np.ndarray): + return obj.tolist() + else: + return obj.item() + + # misc functions (e.g. loss function) + if callable(obj): + return obj.__name__ + + # if obj is a python 'type' + if type(obj).__name__ == type.__name__: + return obj.__name__ + + if isinstance(obj, tensor_shape.Dimension): + return obj.value + + if isinstance(obj, tensor_shape.TensorShape): + return obj.as_list() + + if isinstance(obj, dtypes.DType): + return obj.name + + if isinstance(obj, collections.abc.Mapping): + return dict(obj) + + if obj is Ellipsis: + return {'class_name': '__ellipsis__'} + + if isinstance(obj, wrapt.ObjectProxy): + return obj.__wrapped__ + + if isinstance(obj, internal.TypeSpec): + try: + type_spec_name = type_spec_registry.get_name(type(obj)) + return {'class_name': 'TypeSpec', 'type_spec': type_spec_name, + 'serialized': obj._serialize()} # pylint: disable=protected-access + except ValueError: + raise ValueError('Unable to serialize {} to JSON, because the TypeSpec ' + 'class {} has not been registered.' + .format(obj, type(obj))) + + if isinstance(obj, enum.Enum): + return obj.value + + raise TypeError('Not JSON Serializable:', obj) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/layer_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/layer_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6f2c55615d63ec59ecc06131eb9ad09facbf7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/layer_serialization.py @@ -0,0 +1,175 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and functions implementing Layer SavedModel serialization.""" + +from tensorflow.python.keras.mixed_precision import policy +from tensorflow.python.keras.saving.saved_model import base_serialization +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import save_impl +from tensorflow.python.keras.saving.saved_model import serialized_attributes +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import nest + + +class LayerSavedModelSaver(base_serialization.SavedModelSaver): + """Implements Layer SavedModel serialization.""" + + @property + def object_identifier(self): + return constants.LAYER_IDENTIFIER + + @property + def python_properties(self): + # TODO(kathywu): Add python property validator + return self._python_properties_internal() + + def _python_properties_internal(self): + """Returns dictionary of all python properties.""" + # TODO(kathywu): Add support for metrics serialization. + # TODO(kathywu): Synchronize with the keras spec (go/keras-json-spec) once + # the python config serialization has caught up. + metadata = dict( + name=self.obj.name, + trainable=self.obj.trainable, + expects_training_arg=self.obj._expects_training_arg, # pylint: disable=protected-access + dtype=policy.serialize(self.obj._dtype_policy), # pylint: disable=protected-access + batch_input_shape=getattr(self.obj, '_batch_input_shape', None), + stateful=self.obj.stateful, + must_restore_from_config=self.obj._must_restore_from_config, # pylint: disable=protected-access + ) + + metadata.update(get_serialized(self.obj)) + if self.obj.input_spec is not None: + # Layer's input_spec has already been type-checked in the property setter. + metadata['input_spec'] = nest.map_structure( + lambda x: generic_utils.serialize_keras_object(x) if x else None, + self.obj.input_spec) + if (self.obj.activity_regularizer is not None and + hasattr(self.obj.activity_regularizer, 'get_config')): + metadata['activity_regularizer'] = generic_utils.serialize_keras_object( + self.obj.activity_regularizer) + if self.obj._build_input_shape is not None: # pylint: disable=protected-access + metadata['build_input_shape'] = self.obj._build_input_shape # pylint: disable=protected-access + return metadata + + def objects_to_serialize(self, serialization_cache): + return (self._get_serialized_attributes( + serialization_cache).objects_to_serialize) + + def functions_to_serialize(self, serialization_cache): + return (self._get_serialized_attributes( + serialization_cache).functions_to_serialize) + + def _get_serialized_attributes(self, serialization_cache): + """Generates or retrieves serialized attributes from cache.""" + keras_cache = serialization_cache.setdefault(constants.KERAS_CACHE_KEY, {}) + if self.obj in keras_cache: + return keras_cache[self.obj] + + serialized_attr = keras_cache[self.obj] = ( + serialized_attributes.SerializedAttributes.new(self.obj)) + + if (save_impl.should_skip_serialization(self.obj) or + self.obj._must_restore_from_config): # pylint: disable=protected-access + return serialized_attr + + object_dict, function_dict = self._get_serialized_attributes_internal( + serialization_cache) + + serialized_attr.set_and_validate_objects(object_dict) + serialized_attr.set_and_validate_functions(function_dict) + return serialized_attr + + def _get_serialized_attributes_internal(self, serialization_cache): + """Returns dictionary of serialized attributes.""" + objects = save_impl.wrap_layer_objects(self.obj, serialization_cache) + functions = save_impl.wrap_layer_functions(self.obj, serialization_cache) + # Attribute validator requires that the default save signature is added to + # function dict, even if the value is None. + functions['_default_save_signature'] = None + return objects, functions + + +# TODO(kathywu): Move serialization utils (and related utils from +# generic_utils.py) to a separate file. +def get_serialized(obj): + with generic_utils.skip_failed_serialization(): + # Store the config dictionary, which may be used when reviving the object. + # When loading, the program will attempt to revive the object from config, + # and if that fails, the object will be revived from the SavedModel. + return generic_utils.serialize_keras_object(obj) + + +class InputLayerSavedModelSaver(base_serialization.SavedModelSaver): + """InputLayer serialization.""" + + @property + def object_identifier(self): + return constants.INPUT_LAYER_IDENTIFIER + + @property + def python_properties(self): + + return dict( + class_name=type(self.obj).__name__, + name=self.obj.name, + dtype=self.obj.dtype, + sparse=self.obj.sparse, + ragged=self.obj.ragged, + batch_input_shape=self.obj._batch_input_shape, # pylint: disable=protected-access + config=self.obj.get_config()) + + def objects_to_serialize(self, serialization_cache): + return {} + + def functions_to_serialize(self, serialization_cache): + return {} + + +class RNNSavedModelSaver(LayerSavedModelSaver): + """RNN layer serialization.""" + + @property + def object_identifier(self): + return constants.RNN_LAYER_IDENTIFIER + + def _get_serialized_attributes_internal(self, serialization_cache): + objects, functions = ( + super(RNNSavedModelSaver, self)._get_serialized_attributes_internal( + serialization_cache)) + states = data_structures.wrap_or_unwrap(self.obj.states) + # SaveModel require all the objects to be Trackable when saving. + # If the states is still a tuple after wrap_or_unwrap, it means it doesn't + # contain any trackable item within it, eg empty tuple or (None, None) for + # stateless ConvLSTM2D. We convert them to list so that wrap_or_unwrap can + # make it a Trackable again for saving. When loaded, ConvLSTM2D is + # able to handle the tuple/list conversion. + if isinstance(states, tuple): + states = data_structures.wrap_or_unwrap(list(states)) + objects['states'] = states + return objects, functions + + +class IndexLookupLayerSavedModelSaver(LayerSavedModelSaver): + """Index lookup layer serialization.""" + + @property + def python_properties(self): + # TODO(kathywu): Add python property validator + metadata = self._python_properties_internal() + if metadata['config'].get('has_static_table', False): + metadata['config']['vocabulary'] = None + return metadata diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f55d86515a7248db27bd444919e8d94f6c7f28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load.py @@ -0,0 +1,1205 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras SavedModel deserialization.""" + +import os +import re +import types + +from google.protobuf import message + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.keras import backend +from tensorflow.python.keras import regularizers +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.protobuf import saved_metadata_pb2 +from tensorflow.python.keras.protobuf import versions_pb2 +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import json_utils +from tensorflow.python.keras.saving.saved_model import utils +from tensorflow.python.keras.saving.saved_model.serialized_attributes import CommonEndpoints +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import metrics_utils +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import load as tf_load +from tensorflow.python.saved_model import loader_impl +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.saved_model import revived_types +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import compat +from tensorflow.python.util import nest + +# To avoid circular dependencies between keras/engine and keras/saving, +# code in keras/saving must delay imports. + +# TODO(b/134426265): Switch back to single-quotes to match the rest of the file +# once the issue with copybara is fixed. +# pylint:disable=g-inconsistent-quotes +models_lib = LazyLoader("models_lib", globals(), + "tensorflow.python.keras.models") +base_layer = LazyLoader( + "base_layer", globals(), + "tensorflow.python.keras.engine.base_layer") +layers_module = LazyLoader( + "layers_module", globals(), + "tensorflow.python.keras.layers") +input_layer = LazyLoader( + "input_layer", globals(), + "tensorflow.python.keras.engine.input_layer") +functional_lib = LazyLoader( + "functional_lib", globals(), + "tensorflow.python.keras.engine.functional") +training_lib = LazyLoader( + "training_lib", globals(), + "tensorflow.python.keras.engine.training") +training_lib_v1 = LazyLoader( + "training_lib_v1", globals(), + "tensorflow.python.keras.engine.training_v1") +metrics = LazyLoader("metrics", globals(), + "tensorflow.python.keras.metrics") +recurrent = LazyLoader( + "recurrent", globals(), + "tensorflow.python.keras.layers.recurrent") +# pylint:enable=g-inconsistent-quotes + + +PUBLIC_ATTRIBUTES = CommonEndpoints.all_functions.union( + CommonEndpoints.all_checkpointable_objects) +PUBLIC_ATTRIBUTES.add(constants.KERAS_ATTR) + + +def load(path, compile=True, options=None): # pylint: disable=redefined-builtin + """Loads Keras objects from a SavedModel. + + Any Keras layer or model saved to the SavedModel will be loaded back + as Keras objects. Other objects are loaded as regular trackable objects (same + as `tf.saved_model.load`). + + Currently, Keras saving/loading only retains the Keras object's weights, + losses, and call function. + + The loaded model can be re-compiled, but the original optimizer, compiled loss + functions, and metrics are not retained. This is temporary, and `model.save` + will soon be able to serialize compiled models. + + Args: + path: Path to SavedModel. + compile: If true, compile the model after loading it. + options: Optional `tf.saved_model.LoadOptions` object that specifies + options for loading from SavedModel. + + + Returns: + Object loaded from SavedModel. + """ + # TODO(kathywu): Add saving/loading of optimizer, compiled losses and metrics. + # TODO(kathywu): Add code to load from objects that contain all endpoints + + # Look for metadata file or parse the SavedModel + metadata = saved_metadata_pb2.SavedMetadata() + meta_graph_def = loader_impl.parse_saved_model(path).meta_graphs[0] + object_graph_def = meta_graph_def.object_graph_def + path_to_metadata_pb = os.path.join(path, constants.SAVED_METADATA_PATH) + if gfile.Exists(path_to_metadata_pb): + try: + with gfile.GFile(path_to_metadata_pb, 'rb') as f: + file_content = f.read() + metadata.ParseFromString(file_content) + except message.DecodeError as e: + raise IOError('Cannot parse keras metadata {}: {}.' + .format(path_to_metadata_pb, str(e))) + else: + logging.warning('SavedModel saved prior to TF 2.5 detected when loading ' + 'Keras model. Please ensure that you are saving the model ' + 'with model.save() or tf.keras.models.save_model(), *NOT* ' + 'tf.saved_model.save(). To confirm, there should be a file ' + 'named "keras_metadata.pb" in the SavedModel directory.') + _read_legacy_metadata(object_graph_def, metadata) + + if not metadata.nodes: + # When there are no Keras objects, return the results from the core loader + return tf_load.load(path, options=options) + + # Recreate layers and metrics using the info stored in the metadata. + keras_loader = KerasObjectLoader(metadata, object_graph_def) + keras_loader.load_layers(compile=compile) + + # Generate a dictionary of all loaded nodes. + nodes_to_load = {'root': None} + for node_id, loaded_node in keras_loader.loaded_nodes.items(): + nodes_to_load[keras_loader.get_path(node_id)] = loaded_node + loaded = tf_load.load_partial(path, nodes_to_load, options=options) + + # Finalize the loaded layers and remove the extra tracked dependencies. + keras_loader.finalize_objects() + keras_loader.del_tracking() + + model = loaded['root'] + + # pylint: disable=protected-access + if isinstance(model, training_lib.Model) and compile: + # TODO(kathywu): Use compiled objects from SavedModel, instead of + # creating new objects from the training config. + training_config = model._serialized_attributes['metadata'].get( + 'training_config', None) + if training_config is not None: + model.compile(**saving_utils.compile_args_from_training_config( + training_config), from_serialized=True) + saving_utils.try_build_compiled_arguments(model) + if isinstance(model.optimizer, optimizer_v2.OptimizerV2): + if (model.optimizer.get_slot_names()): + logging.warning('Your optimizer uses slots. ' + 'Slots cannot be restored from saved_model, ' + 'as a result, your model is starting with ' + 'a new initialized optimizer.') + else: + logging.warning('No training configuration found in save file, so the ' + 'model was *not* compiled. Compile it manually.') + # pylint: enable=protected-access + + # Force variables and resources to initialize. + if not context.executing_eagerly(): + sess = backend.get_session() # Variables are initialized by this call. + sess.run(ops.get_collection(ops.GraphKeys.TABLE_INITIALIZERS)) + + return model + + +def _read_legacy_metadata(object_graph_def, metadata): + """Builds a KerasMetadata proto from the SavedModel ObjectGraphDef.""" + # Older SavedModels store the metadata directly in the proto instead of the + # separate pb file. + node_paths = _generate_object_paths(object_graph_def) + for node_id, proto in enumerate(object_graph_def.nodes): + if (proto.WhichOneof('kind') == 'user_object' and + proto.user_object.identifier in constants.KERAS_OBJECT_IDENTIFIERS): + if not proto.user_object.metadata: + raise ValueError('Unable to create a Keras model from this SavedModel. ' + 'This SavedModel was created with ' + '`tf.saved_model.save`, and lacks the Keras metadata.' + 'Please save your Keras model by calling `model.save`' + 'or `tf.keras.models.save_model`.') + metadata.nodes.add( + node_id=node_id, + node_path=node_paths[node_id], + version=versions_pb2.VersionDef( + producer=1, min_consumer=1, bad_consumers=[]), + identifier=proto.user_object.identifier, + metadata=proto.user_object.metadata) + + +def _generate_object_paths(object_graph_def): + """Traverses through an ObjectGraphDef and builds a map of all node paths.""" + paths = {0: 'root'} + nodes_to_visit = [0] + + while nodes_to_visit: + current_node = nodes_to_visit.pop() + current_path = paths[current_node] + for reference in object_graph_def.nodes[current_node].children: + if reference.node_id in paths: + continue + paths[reference.node_id] = '{}.{}'.format(current_path, + reference.local_name) + nodes_to_visit.append(reference.node_id) + + return paths + + +def _is_graph_network(layer): + """Determines whether the layer is a graph network.""" + # pylint: disable=protected-access + if isinstance(layer, RevivedNetwork): + return False + elif isinstance(layer, functional_lib.Functional): + return (layer._is_graph_network or + isinstance(layer, models_lib.Sequential)) + return False + + +class KerasObjectLoader(object): + """Loader that recreates Keras objects (e.g. layers, models). + + Layers and models are revived from either the config or SavedModel following + these rules: + 1. If object is a graph network (i.e. Sequential or Functional) then it will + be initialized using the structure from the config only after the children + layers have been created. Graph networks must be initialized with inputs + and outputs, so all child layers must be created beforehand. + 2. If object's config exists and the class can be found, then revive from + config. + 3. Object may have already been created if its parent was revived from config. + In this case, do nothing. + 4. If nothing of the above applies, compose the various artifacts from the + SavedModel to create a subclassed layer or model. At this time, custom + metrics are not supported. + + """ + + def __init__(self, metadata, object_graph_def): + self._metadata = {x.node_id: x for x in metadata.nodes} + self._proto = object_graph_def + + self._node_paths = {node_data.node_id: node_data.node_path + for node_data in metadata.nodes} + self.loaded_nodes = {} # Maps node path -> loaded node + + # Store all node ids that have already been traversed when tracking nodes + # that were recreated from the config. + self._traversed_nodes_from_config = set() + + # Maps model id -> (blank model obj, list of child layer or their node ids) + # This tracks all layers in functional and sequential models. These models + # are only reconstructed after all of their child layers have been created. + self.model_layer_dependencies = {} + self._models_to_reconstruct = [] + + def del_tracking(self): + """Removes tracked references that are only used when loading the model.""" + # Now that the node object has been fully loaded, and the checkpoint has + # been restored, the object no longer needs to track objects added from + # SerializedAttributes. (Note that saving a training checkpoint still + # functions correctly, because layers and variables are tracked separately + # by the Layer object.) + # TODO(kathywu): Instead of outright deleting these nodes (which would + # make restoring from a different checkpoint tricky), mark them as extra + # dependencies that are OK to overwrite. + for node in self.loaded_nodes.values(): + node = node[0] + if not isinstance(node, base_layer.Layer): + # Loaded nodes can contain other trackable objects created when + # loading layers from the config, such as variables. + continue + for name in PUBLIC_ATTRIBUTES: + node._delete_tracking(name) # pylint: disable=protected-access + + if isinstance(node, functional_lib.Functional): + # Delete the temporary layer dependencies, which were used to restore + # the checkpointed values. When the model is live, the user can delete + # or add layers to the model at any time, so these layer dependencies + # may be obsolete. + dependencies = list(node._self_unconditional_dependency_names) # pylint: disable=protected-access + for name in dependencies: + if re.match(r'^layer(_with_weights)?-[\d+]', name) is not None: + node._delete_tracking(name) # pylint: disable=protected-access + + def _add_children_recreated_from_config(self, obj, proto, node_id): + """Recursively records objects recreated from config.""" + # pylint: disable=protected-access + if node_id in self._traversed_nodes_from_config: + return + + parent_path = self._node_paths[node_id] + self._traversed_nodes_from_config.add(node_id) + obj._maybe_initialize_trackable() + if isinstance(obj, base_layer.Layer) and not obj.built: + metadata = json_utils.decode(self._metadata[node_id].metadata) + self._try_build_layer(obj, node_id, metadata.get('build_input_shape')) + + # Create list of all possible children + children = [] + # Look for direct children + for reference in proto.children: + obj_child = obj._lookup_dependency(reference.local_name) + children.append((obj_child, reference.node_id, reference.local_name)) + + # Add metrics that may have been added to the layer._metrics list. + # This is stored in the SavedModel as layer.keras_api.layer_metrics in + # SavedModels created after Tf 2.2. + metric_list_node_id = self._search_for_child_node( + node_id, [constants.KERAS_ATTR, 'layer_metrics']) + if metric_list_node_id is not None and hasattr(obj, '_metrics'): + obj_metrics = {m.name: m for m in obj._metrics} + for reference in self._proto.nodes[metric_list_node_id].children: + metric = obj_metrics.get(reference.local_name) + if metric is not None: + metric_path = '{}.layer_metrics.{}'.format(constants.KERAS_ATTR, + reference.local_name) + children.append((metric, reference.node_id, metric_path)) + + for (obj_child, child_id, child_name) in children: + child_proto = self._proto.nodes[child_id] + + if not isinstance(obj_child, trackable.Trackable): + continue + if (child_proto.user_object.identifier in + revived_types.registered_identifiers()): + setter = revived_types.get_setter(child_proto.user_object) + elif obj_child._object_identifier in constants.KERAS_OBJECT_IDENTIFIERS: + setter = _revive_setter + else: + setter = setattr + # pylint: enable=protected-access + + if child_id in self.loaded_nodes: + if self.loaded_nodes[child_id][0] is not obj_child: + # This means that the same trackable object is referenced by two + # different objects that were recreated from the config. + logging.warning( + 'Looks like there is an object (perhaps variable or ' + 'layer) that is shared between different layers/models. ' + 'This may cause issues when restoring the variable ' + 'values. Object: {}'.format(obj_child)) + continue + + # Overwrite variable names with the ones saved in the SavedModel. + if (child_proto.WhichOneof('kind') == 'variable' and + child_proto.variable.name): + obj_child._handle_name = child_proto.variable.name + ':0' # pylint: disable=protected-access + + if isinstance(obj_child, data_structures.TrackableDataStructure): + setter = lambda *args: None + + child_path = '{}.{}'.format(parent_path, child_name) + self._node_paths[child_id] = child_path + self._add_children_recreated_from_config( + obj_child, child_proto, child_id) + self.loaded_nodes[child_id] = obj_child, setter + + def load_layers(self, compile=True): # pylint: disable=redefined-builtin + """Load all layer nodes from the metadata.""" + # Load metrics after models and layers, since it's likely that models + # and layers will create the metric when initialized (this avoids wasting + # time by creating objects multiple times). + metric_list = [] + for node_metadata in self._metadata.values(): + if node_metadata.identifier == constants.METRIC_IDENTIFIER: + metric_list.append(node_metadata) + continue + + self.loaded_nodes[node_metadata.node_id] = self._load_layer( + node_metadata.node_id, node_metadata.identifier, + node_metadata.metadata) + + for node_metadata in metric_list: + try: + self.loaded_nodes[node_metadata.node_id] = self._load_layer( + node_metadata.node_id, node_metadata.identifier, + node_metadata.metadata) + except ValueError: + # Metrics are only needed when the model is compiled later. We ignore + # errors when trying to load custom metrics when `compile=False` until + # custom metrics are serialized properly (b/135550038). + if compile: + raise + logging.warning('Unable to restore custom metric. Please ensure that ' + 'the layer implements `get_config` and `from_config` ' + 'when saving. In addition, please use the ' + '`custom_objects` arg when calling `load_model()`.') + + def _load_layer(self, node_id, identifier, metadata): + """Load a single layer from a SavedUserObject proto.""" + metadata = json_utils.decode(metadata) + + # If node was already created + if node_id in self.loaded_nodes: + node, setter = self.loaded_nodes[node_id] + + # Revive setter requires the object to have a `_serialized_attributes` + # property. Add it here. + _maybe_add_serialized_attributes(node, metadata) + + config = metadata.get('config') + if _is_graph_network(node) and generic_utils.validate_config(config): + child_nodes = self._get_child_layer_node_ids(node_id) + self.model_layer_dependencies[node_id] = (node, child_nodes) + if not child_nodes: + self._models_to_reconstruct.append(node_id) + return node, setter + + # Detect whether this object can be revived from the config. If not, then + # revive from the SavedModel instead. + obj, setter = self._revive_from_config(identifier, metadata, node_id) + if obj is None: + obj, setter = revive_custom_object(identifier, metadata) + + # Add an attribute that stores the extra functions/objects saved in the + # SavedModel. Most of these functions/objects are ignored, but some are + # used later in the loading process (e.g. the list of regularization + # losses, or the training config of compiled models). + _maybe_add_serialized_attributes(obj, metadata) + return obj, setter + + def _revive_from_config(self, identifier, metadata, node_id): + """Revives a layer/model from config, or returns None.""" + if identifier == constants.METRIC_IDENTIFIER: + obj = self._revive_metric_from_config(metadata) + else: + obj = ( + self._revive_graph_network(identifier, metadata, node_id) or + self._revive_layer_or_model_from_config(metadata, node_id)) + + if obj is None: + return None, None + + setter = self._config_node_setter(_revive_setter) + self._add_children_recreated_from_config( + obj, self._proto.nodes[node_id], node_id) + return obj, setter + + def _revive_graph_network(self, identifier, metadata, node_id): + """Revives a graph network from config.""" + # Determine whether the metadata contains information for reviving a + # functional or Sequential model. + config = metadata.get('config') + if not generic_utils.validate_config(config): + return None + + class_name = compat.as_str(metadata['class_name']) + if generic_utils.get_registered_object(class_name) is not None: + return None + model_is_functional_or_sequential = ( + metadata.get('is_graph_network', False) or + class_name == 'Sequential' or + class_name == 'Functional') + if not model_is_functional_or_sequential: + return None + + # Revive functional and sequential models as blank model objects for now ( + # must be initialized to enable setattr tracking and attribute caching). + # Reconstruction of the network is deferred until all of the model's layers + # have been revived. + if class_name == 'Sequential': + model = models_lib.Sequential(name=config['name']) + # The model is a custom Sequential model. + elif identifier == constants.SEQUENTIAL_IDENTIFIER: + # Uses the custom class name, since the config does not have one. + model = models_lib.Sequential(name=class_name) + else: + model = models_lib.Functional( + inputs=[], outputs=[], name=config['name']) + + # Record this model and its layers. This will later be used to reconstruct + # the model. + layers = self._get_child_layer_node_ids(node_id) + self.model_layer_dependencies[node_id] = (model, layers) + if not layers: + self._models_to_reconstruct.append(node_id) + return model + + def _revive_layer_or_model_from_config(self, metadata, node_id): + """Revives a layer/custom model from config; returns None if infeasible.""" + # Check that the following requirements are met for reviving from config: + # 1. Object can be deserialized from config. + # 2. If the object needs to be built, then the build input shape can be + # found. + class_name = metadata.get('class_name') + config = metadata.get('config') + shared_object_id = metadata.get('shared_object_id') + must_restore_from_config = metadata.get('must_restore_from_config') + if not generic_utils.validate_config(config): + return None + + try: + obj = layers_module.deserialize( + generic_utils.serialize_keras_class_and_config( + class_name, config, shared_object_id=shared_object_id)) + except ValueError: + if must_restore_from_config: + raise RuntimeError( + 'Unable to restore a layer of class {cls}. Layers of ' + 'class {cls} require that the class be provided to ' + 'the model loading code, either by registering the ' + 'class using @keras.utils.register_keras_serializable ' + 'on the class def and including that file in your ' + 'program, or by passing the class in a ' + 'keras.utils.CustomObjectScope that wraps this load ' + 'call.'.format(cls=class_name)) + else: + return None + + # Use the dtype, name, and trainable status. Often times these are not + # specified in custom configs, so retrieve their values from the metadata. + # pylint: disable=protected-access + obj._name = metadata['name'] + if metadata.get('trainable') is not None: + obj.trainable = metadata['trainable'] + if metadata.get('dtype') is not None: + obj._set_dtype_policy(metadata['dtype']) + if metadata.get('stateful') is not None: + obj.stateful = metadata['stateful'] + # Restore model save spec for subclassed models. (layers do not store a + # SaveSpec) + if isinstance(obj, training_lib.Model): + save_spec = metadata.get('save_spec') + if save_spec is not None: + obj._set_save_spec(save_spec) + # pylint: enable=protected-access + + build_input_shape = metadata.get('build_input_shape') + built = self._try_build_layer(obj, node_id, build_input_shape) + + if not built: + # If the layer cannot be built, revive a custom layer instead. + return None + return obj + + def _revive_metric_from_config(self, metadata): + """Revives a metric object using the config saved in the metadata.""" + class_name = compat.as_str(metadata['class_name']) + config = metadata.get('config') + + if not generic_utils.validate_config(config): + return None + + try: + obj = metrics.deserialize( + generic_utils.serialize_keras_class_and_config(class_name, config)) + except ValueError: + return None + + build_input_shape = metadata.get('build_input_shape') + if build_input_shape is not None and hasattr(obj, '_build'): + obj._build(build_input_shape) # pylint: disable=protected-access + + return obj + + def _try_build_layer(self, obj, node_id, build_input_shape): + """Attempts to build the layer.""" + if obj.built or hasattr(obj.build, '_is_default'): + obj.built = True + return True + + if build_input_shape is None: + build_input_shape = self._infer_inputs(node_id, convert_to_shapes=True) + + if build_input_shape is not None: + obj.build(build_input_shape) + base_layer.Layer.build(obj, build_input_shape) + return True + + return False + + def _load_edges(self): + """Add edges for all nodes that are not waiting on initialization.""" + for node_id, proto in enumerate(self._proto.nodes): + if node_id not in self.model_layer_dependencies: + self._add_object_graph_edges(proto, node_id) + + def get_path(self, node_id): + return self._node_paths[node_id] + + def finalize_objects(self): + """Finish setting up Keras objects. + + This function is executed after all objects and functions have been created. + Call functions and losses are attached to each layer, and once all layers + have been fully set up, graph networks are initialized. + + Subclassed models that are revived from the SavedModel are treated like + layers, and have their call/loss functions attached here. + """ + # Finish setting up layers and subclassed models. This step attaches call + # functions and losses to each object, and sets model inputs/outputs. + layers_revived_from_config = [] + layers_revived_from_saved_model = [] + for node_id, (node, _) in self.loaded_nodes.items(): + if (not isinstance(node, base_layer.Layer) or + # Don't finalize models until all layers have finished loading. + node_id in self.model_layer_dependencies): + continue + + self._unblock_model_reconstruction(node_id, node) + + if isinstance(node, input_layer.InputLayer): + continue + elif isinstance(node, metrics.Metric): + continue + + if isinstance(node, (RevivedLayer, RevivedInputLayer)): + layers_revived_from_saved_model.append(node) + else: + layers_revived_from_config.append(node) + + _finalize_saved_model_layers(layers_revived_from_saved_model) + _finalize_config_layers(layers_revived_from_config) + + # Initialize graph networks, now that layer dependencies have been resolved. + self._reconstruct_all_models() + + def _unblock_model_reconstruction(self, layer_id, layer): + """Removes layer from blocking model reconstruction.""" + for model_id, v in self.model_layer_dependencies.items(): + _, layers = v + if layer_id not in layers: + continue + layers[layers.index(layer_id)] = layer + if all(isinstance(x, base_layer.Layer) for x in layers): + self._models_to_reconstruct.append(model_id) + + def _reconstruct_all_models(self): + """Reconstructs the network structure of all models.""" + all_initialized_models = set() + while self._models_to_reconstruct: + model_id = self._models_to_reconstruct.pop(0) + all_initialized_models.add(model_id) + model, layers = self.model_layer_dependencies[model_id] + self._reconstruct_model(model_id, model, layers) + _finalize_config_layers([model]) + + if all_initialized_models != set(self.model_layer_dependencies.keys()): + # This should not happen. + uninitialized_model_ids = ( + set(self.model_layer_dependencies.keys()) - all_initialized_models) + uninitialized_model_names = [ + self.model_layer_dependencies[model_id][0].name + for model_id in uninitialized_model_ids] + raise ValueError('Error when loading from SavedModel -- the following ' + 'models could not be initialized: {}' + .format(uninitialized_model_names)) + + def _reconstruct_model(self, model_id, model, layers): + """Reconstructs the network structure.""" + config = json_utils.decode(self._metadata[model_id].metadata)['config'] + + # Set up model inputs + if model.inputs: + # Inputs may already be created if the model is instantiated in another + # object's __init__. + pass + elif isinstance(model, models_lib.Sequential): + if not layers or not isinstance(layers[0], input_layer.InputLayer): + if config['layers'][0]['class_name'] == 'InputLayer': + layers.insert(0, input_layer.InputLayer.from_config( + config['layers'][0]['config'])) + elif 'batch_input_shape' in config['layers'][0]['config']: + batch_input_shape = config['layers'][0]['config']['batch_input_shape'] + layers.insert(0, input_layer.InputLayer( + input_shape=batch_input_shape[1:], + batch_size=batch_input_shape[0], + dtype=layers[0].dtype, + name=layers[0].name + '_input')) + model.__init__(layers, name=config['name']) + if not model.inputs: + first_layer = self._get_child_layer_node_ids(model_id)[0] + input_specs = self._infer_inputs(first_layer) + input_shapes = self._infer_inputs(first_layer, convert_to_shapes=True) + model._set_inputs(input_specs) # pylint: disable=protected-access + if not model.built and not isinstance(input_specs, dict): + model.build(input_shapes) + else: # Reconstruct functional model + (inputs, outputs, + created_layers) = functional_lib.reconstruct_from_config( + config, created_layers={layer.name: layer for layer in layers}) + model.__init__(inputs, outputs, name=config['name']) + functional_lib.connect_ancillary_layers(model, created_layers) + + # Set model dtype. + _set_network_attributes_from_metadata(model) + + # Unblock models that are dependent on this model. + self._unblock_model_reconstruction(model_id, model) + + def _get_child_layer_node_ids(self, node_id): + """Returns the node ids of each layer in a Sequential/Functional model.""" + # Sequential and Functional track layers with names following the format + # "layer-N". Use this to generate the list of layers. + num_layers = 0 + child_layers = {} + pattern = re.compile('layer-(\\d+)') + + for child in self._proto.nodes[node_id].children: + m = pattern.match(child.local_name) + if m is None: + continue + layer_n = int(m.group(1)) + num_layers = max(layer_n + 1, num_layers) + child_layers[layer_n] = child.node_id + + ordered = [] + for n in range(num_layers): + child = child_layers.get(n) + if child is None: + break + ordered.append(child) + return ordered + + def _search_for_child_node(self, parent_id, path_to_child): + """Returns node id of child node. + + A helper method for traversing the object graph proto. + + As an example, say that the object graph proto in the SavedModel contains an + object with the following child and grandchild attributes: + + `parent.child_a.child_b` + + This method can be used to retrieve the node id of `child_b` using the + parent's node id by calling: + + `_search_for_child_node(parent_id, ['child_a', 'child_b'])`. + + Args: + parent_id: node id of parent node + path_to_child: list of children names. + + Returns: + node_id of child, or None if child isn't found. + """ + if not path_to_child: + return parent_id + + for child in self._proto.nodes[parent_id].children: + if child.local_name == path_to_child[0]: + return self._search_for_child_node(child.node_id, path_to_child[1:]) + return None + + def _infer_inputs(self, layer_node_id, convert_to_shapes=False): + """Infers input shape of layer from SavedModel functions.""" + call_fn_id = self._search_for_child_node( + layer_node_id, ['call_and_return_all_conditional_losses']) + if call_fn_id is None: + return None + + concrete_functions = ( + self._proto.nodes[call_fn_id].function.concrete_functions) + if not concrete_functions: + return None + call_fn_name = concrete_functions[0] + call_fn_proto = self._proto.concrete_functions[call_fn_name] + structured_input_signature = nested_structure_coder.decode_proto( + call_fn_proto.canonicalized_input_signature) + inputs = structured_input_signature[0][0] + if convert_to_shapes: + return nest.map_structure(lambda spec: spec.shape, inputs) + else: + return inputs + + def _config_node_setter(self, setter): + """Creates edges for nodes that are recreated from config.""" + def setattr_wrapper(obj, name, value): + # Avoid overwriting attributes of objects recreated from the config. + if obj._lookup_dependency(name) is None: # pylint: disable=protected-access + setter(obj, name, value) + return setattr_wrapper + + +def _finalize_saved_model_layers(layers): + """Runs the final steps of loading Keras Layers from SavedModel.""" + # pylint: disable=protected-access + # 1. Set up call functions for all layers initialized from the SavedModel ( + # and not the config) + for layer in layers: + layer.built = True + layer_call = getattr(_get_keras_attr(layer), + 'call_and_return_conditional_losses', None) + if layer_call and layer_call.concrete_functions: + layer.call = utils.use_wrapped_call( + layer, layer_call, return_method=True) + expects_training_arg = layer._serialized_attributes['metadata'][ + 'expects_training_arg'] + if 'training' in layer_call.function_spec.arg_names: + # This could change the value of `expects_training_arg` if this layer + # doesn't expect a training arg, but has a child layer that does. + expects_training_arg = True + layer._init_call_fn_args(expects_training_arg) + else: + layer.call = types.MethodType( + _unable_to_call_layer_due_to_serialization_issue, layer) + + for layer in layers: + # 2. Set model inputs and outputs. + if isinstance(layer, RevivedNetwork): + _set_network_attributes_from_metadata(layer) + + if hasattr(_get_keras_attr(layer), 'call_and_return_conditional_losses'): + call_fn = _get_keras_attr(layer).call_and_return_conditional_losses + if not call_fn.concrete_functions: + continue + if call_fn.input_signature is None: + inputs = infer_inputs_from_restored_call_function(call_fn) + else: + inputs = call_fn.input_signature[0] + layer._set_inputs(inputs) # pylint: disable=protected-access + + # 3. Add losses that aren't generated by the layer.call function. + _restore_layer_unconditional_losses(layer) + _restore_layer_activation_loss(layer) + + # 4. Restore metrics list + _restore_layer_metrics(layer) + + # pylint: enable=protected-access + + +def _unable_to_call_layer_due_to_serialization_issue( + layer, *unused_args, **unused_kwargs): + """Replaces the `layer.call` if the layer was not fully serialized. + + Keras Model/Layer serialization is relatively relaxed because SavedModels + are not always loaded back as keras models. Thus, when there is an issue + tracing a non-signature function, a warning is logged instead of raising an + error. This results in a SavedModel where the model's call function is saved, + but the internal layer call functions are not. + + When deserialized with `tf.keras.models.load_model`, the internal layers + which do not have serialized call functions should raise an error when called. + + Args: + layer: Layer without the serialized call function. + + Raises: + ValueError + """ + + raise ValueError( + 'Cannot call custom layer {} of type {}, because the call function was ' + 'not serialized to the SavedModel.' + 'Please try one of the following methods to fix this issue:' + '\n\n(1) Implement `get_config` and `from_config` in the layer/model ' + 'class, and pass the object to the `custom_objects` argument when ' + 'loading the model. For more details, see: ' + 'https://www.tensorflow.org/guide/keras/save_and_serialize' + '\n\n(2) Ensure that the subclassed model or layer overwrites `call` ' + 'and not `__call__`. The input shape and dtype will be automatically ' + 'recorded when the object is called, and used when saving. To manually ' + 'specify the input shape/dtype, decorate the call function with ' + '`@tf.function(input_signature=...)`.'.format(layer.name, type(layer))) + + +def _finalize_config_layers(layers): + """Runs the final steps of loading Keras Layers from config.""" + for layer in layers: + # It is assumed that layers define their unconditional losses after being + # recreated from the config and built. The exceptions to this + # are Functional and Sequential models, which only store conditional losses + # (losses dependent on the inputs) in the config. Unconditional losses like + # weight regularization must be revived from the SavedModel. + if _is_graph_network(layer): + _restore_layer_unconditional_losses(layer) + + # Some layers, like Dense, record their activation loss function in the + # config. However, not all layers do this, so the activation loss may be + # missing when restored from the config/hdf5. + # TODO(kathywu): Investigate ways to improve the config to ensure consistent + # loading behavior between HDF5 and SavedModel. + _restore_layer_activation_loss(layer) + + # Restore metrics list. + _restore_layer_metrics(layer) + + # Restore RNN layer states. + if (isinstance(layer, recurrent.RNN) and + layer.stateful and + hasattr(_get_keras_attr(layer), 'states')): + layer.states = getattr(_get_keras_attr(layer), 'states', None) + for variable in nest.flatten(layer.states): + backend.track_variable(variable) + + # Perform any layer defined finalization of the layer state. + layer.finalize_state() + + +def _finalize_metric(metric): + metric.update_state = types.MethodType(metrics_utils.update_state_wrapper( + metric.keras_api.update_state), metric) + metric.result = metric.keras_api.result + + +def _restore_layer_unconditional_losses(layer): + """Restore unconditional losses from SavedModel.""" + if hasattr(_get_keras_attr(layer), 'layer_regularization_losses'): + losses = getattr(_get_keras_attr(layer), 'layer_regularization_losses', []) + else: + # Some earlier SavedModels may not have layer_regularization_losses + # serialized separately. Fall back to using the regularization_losses + # list if it does not exist. + losses = layer._serialized_attributes.get('regularization_losses', []) # pylint: disable=protected-access + for loss in losses: + layer.add_loss(loss) + + +def _restore_layer_activation_loss(layer): + """Restore actiation loss from SavedModel.""" + # Use wrapped activity regularizer function if the layer's activity + # regularizer wasn't created during initialization. + activity_regularizer = getattr(_get_keras_attr(layer), + 'activity_regularizer_fn', None) + if activity_regularizer and not layer.activity_regularizer: + try: + layer.activity_regularizer = activity_regularizer + except AttributeError: + # This may happen if a layer wrapper is saved with an activity + # regularizer. The wrapper object's activity regularizer is unsettable. + pass + + +def revive_custom_object(identifier, metadata): + """Revives object from SavedModel.""" + if ops.executing_eagerly_outside_functions(): + model_class = training_lib.Model + else: + model_class = training_lib_v1.Model + + revived_classes = { + constants.INPUT_LAYER_IDENTIFIER: ( + RevivedInputLayer, input_layer.InputLayer), + constants.LAYER_IDENTIFIER: (RevivedLayer, base_layer.Layer), + constants.MODEL_IDENTIFIER: (RevivedNetwork, model_class), + constants.NETWORK_IDENTIFIER: (RevivedNetwork, functional_lib.Functional), + constants.SEQUENTIAL_IDENTIFIER: (RevivedNetwork, models_lib.Sequential), + } + parent_classes = revived_classes.get(identifier, None) + + if parent_classes is not None: + parent_classes = revived_classes[identifier] + revived_cls = type( + compat.as_str(metadata['class_name']), parent_classes, {}) + return revived_cls._init_from_metadata(metadata) # pylint: disable=protected-access + else: + raise ValueError('Unable to restore custom object of type {} currently. ' + 'Please make sure that the layer implements `get_config`' + 'and `from_config` when saving. In addition, please use ' + 'the `custom_objects` arg when calling `load_model()`.' + .format(identifier)) + + +def _restore_layer_metrics(layer): + metrics_list = getattr(_get_keras_attr(layer), 'layer_metrics', {}) + layer_metrics = {m.name: m for m in layer._metrics} # pylint: disable=protected-access + for name, metric in metrics_list.items(): + if name not in layer_metrics: + # Metrics may be added during initialization/building of custom layers. + layer._metrics.append(metric) # pylint: disable=protected-access + + +# TODO(kathywu): Centrally define keys and functions for both serialization and +# deserialization. +class RevivedLayer(object): + """Keras layer loaded from a SavedModel.""" + + @classmethod + def _init_from_metadata(cls, metadata): + """Create revived layer from metadata stored in the SavedModel proto.""" + init_args = dict( + name=metadata['name'], + trainable=metadata['trainable']) + if metadata.get('dtype') is not None: + init_args['dtype'] = metadata['dtype'] + if metadata.get('batch_input_shape') is not None: + init_args['batch_input_shape'] = metadata['batch_input_shape'] + + revived_obj = cls(**init_args) + + with utils.no_automatic_dependency_tracking_scope(revived_obj): + # pylint:disable=protected-access + revived_obj._expects_training_arg = metadata['expects_training_arg'] + config = metadata.get('config') + if generic_utils.validate_config(config): + revived_obj._config = config + if metadata.get('input_spec') is not None: + revived_obj.input_spec = recursively_deserialize_keras_object( + metadata['input_spec'], + module_objects={'InputSpec': input_spec.InputSpec}) + if metadata.get('activity_regularizer') is not None: + revived_obj.activity_regularizer = regularizers.deserialize( + metadata['activity_regularizer']) + if metadata.get('_is_feature_layer') is not None: + revived_obj._is_feature_layer = metadata['_is_feature_layer'] + if metadata.get('stateful') is not None: + revived_obj.stateful = metadata['stateful'] + # pylint:enable=protected-access + + return revived_obj, _revive_setter + + @property + def keras_api(self): + return self._serialized_attributes.get(constants.KERAS_ATTR, None) + + def get_config(self): + if hasattr(self, '_config'): + return self._config + else: + raise NotImplementedError + + +def _revive_setter(layer, name, value): + """Setter function that saves some attributes to separate dictionary.""" + # Many attributes in the SavedModel conflict with properties defined in + # Layer and Model. Save these attributes to a separate dictionary. + if name in PUBLIC_ATTRIBUTES: + # pylint: disable=protected-access + if isinstance(value, trackable.Trackable): + layer._track_trackable(value, name=name) + layer._serialized_attributes[name] = value + # pylint: enable=protected-access + elif (isinstance(layer, functional_lib.Functional) and + re.match(r'^layer(_with_weights)?-[\d+]', name) is not None): + # Edges named "layer-n" or "layer_with_weights-n", which are tracked in + # network._track_layers, should not be added as an attribute. They should + # be temporarily added as a dependency so that checkpointed values can be + # restored. These dependencies are manually deleted in + # KerasObjectLoader.del_tracking. + + # Set `overwrite=True` in the case that `layer` already tracks a different + # layer-n. This may cause variable values to not be loaded properly in the + # original layer-n, but we already warn the users about this + # (ctrl-f "shared between different layers/models"). + layer._track_trackable(value, name, overwrite=True) # pylint: disable=protected-access + elif getattr(layer, name, None) is not None: + # Don't overwrite already defined attributes. + pass + else: + setattr(layer, name, value) + + +class RevivedInputLayer(object): + """InputLayer loaded from a SavedModel.""" + + @classmethod + def _init_from_metadata(cls, metadata): + """Revives the saved InputLayer from the Metadata.""" + init_args = dict( + name=metadata['name'], + dtype=metadata['dtype'], + sparse=metadata['sparse'], + ragged=metadata['ragged'], + batch_input_shape=metadata['batch_input_shape']) + revived_obj = cls(**init_args) + with utils.no_automatic_dependency_tracking_scope(revived_obj): + revived_obj._config = metadata['config'] # pylint:disable=protected-access + + return revived_obj, setattr + + def get_config(self): + return self._config + + +def recursively_deserialize_keras_object(config, module_objects=None): + """Deserialize Keras object from a nested structure.""" + if isinstance(config, dict): + if 'class_name' in config: + return generic_utils.deserialize_keras_object( + config, module_objects=module_objects) + else: + return {key: recursively_deserialize_keras_object(config[key], + module_objects) + for key in config} + if isinstance(config, (tuple, list)): + return [recursively_deserialize_keras_object(x, module_objects) + for x in config] + else: + raise ValueError('Unable to decode config: {}'.format(config)) + + +def get_common_shape(x, y): + """Find a `TensorShape` that is compatible with both `x` and `y`.""" + if x is None != y is None: + raise RuntimeError( + 'Cannot find a common shape when LHS shape is None but RHS shape ' + 'is not (or vice versa): %s vs. %s' % (x, y)) + if x is None: + return None # The associated input was not a Tensor, no shape generated. + if not isinstance(x, tensor_shape.TensorShape): + raise TypeError('Expected x to be a TensorShape but saw %s' % (x,)) + if not isinstance(y, tensor_shape.TensorShape): + raise TypeError('Expected y to be a TensorShape but saw %s' % (y,)) + if x.rank != y.rank or x.rank is None: + return tensor_shape.TensorShape(None) + dims = [] + for dim_x, dim_y in zip(x.dims, y.dims): + if (dim_x != dim_y + or tensor_shape.dimension_value(dim_x) is None + or tensor_shape.dimension_value(dim_y) is None): + dims.append(None) + else: + dims.append(tensor_shape.dimension_value(dim_x)) + return tensor_shape.TensorShape(dims) + + +def infer_inputs_from_restored_call_function(fn): + """Returns TensorSpec of inputs from a restored call function. + + Args: + fn: Restored layer call function. It is assumed that `fn` has at least + one concrete function and that the inputs are in the first argument. + + Returns: + TensorSpec of call function inputs. + """ + def common_spec(x, y): + common_shape = get_common_shape(x.shape, y.shape) + if isinstance(x, sparse_tensor.SparseTensorSpec): + return sparse_tensor.SparseTensorSpec(common_shape, x.dtype) + elif isinstance(x, ragged_tensor.RaggedTensorSpec): + return ragged_tensor.RaggedTensorSpec(common_shape, x.dtype) + return tensor_spec.TensorSpec(common_shape, x.dtype, x.name) + + spec = fn.concrete_functions[0].structured_input_signature[0][0] + for concrete in fn.concrete_functions[1:]: + spec2 = concrete.structured_input_signature[0][0] + spec = nest.map_structure(common_spec, spec, spec2) + return spec + + +class RevivedNetwork(RevivedLayer): + """Keras network of layers loaded from a SavedModel.""" + + @classmethod + def _init_from_metadata(cls, metadata): + """Create revived network from metadata stored in the SavedModel proto.""" + revived_obj = cls(name=metadata['name']) + + # Store attributes revived from SerializedAttributes in a un-tracked + # dictionary. The attributes are the ones listed in CommonEndpoints or + # "keras_api" for keras-specific attributes. + with utils.no_automatic_dependency_tracking_scope(revived_obj): + # pylint:disable=protected-access + revived_obj._expects_training_arg = metadata['expects_training_arg'] + config = metadata.get('config') + if generic_utils.validate_config(config): + revived_obj._config = config + + if metadata.get('activity_regularizer') is not None: + revived_obj.activity_regularizer = regularizers.deserialize( + metadata['activity_regularizer']) + # pylint:enable=protected-access + + return revived_obj, _revive_setter # pylint:disable=protected-access + + +def _set_network_attributes_from_metadata(revived_obj): + """Sets attributes recorded in the metadata.""" + with utils.no_automatic_dependency_tracking_scope(revived_obj): + # pylint:disable=protected-access + metadata = revived_obj._serialized_attributes['metadata'] + if metadata.get('dtype') is not None: + revived_obj._set_dtype_policy(metadata['dtype']) + revived_obj._trainable = metadata['trainable'] + # pylint:enable=protected-access + + +def _maybe_add_serialized_attributes(layer, metadata): + # Store attributes revived from SerializedAttributes in a un-tracked + # dictionary. The attributes are the ones listed in CommonEndpoints or + # "keras_api" for keras-specific attributes. + if not hasattr(layer, '_serialized_attributes'): + with utils.no_automatic_dependency_tracking_scope(layer): + layer._serialized_attributes = {'metadata': metadata} # pylint: disable=protected-access + + +def _get_keras_attr(layer): + return getattr(layer, '_serialized_attributes', {}).get(constants.KERAS_ATTR, + None) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load_context.py new file mode 100644 index 0000000000000000000000000000000000000000..03d48fb0c91f8c83edce62ee7d95ad6f13757859 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/load_context.py @@ -0,0 +1,63 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Context for storing options for loading a SavedModel.""" + +import contextlib +import threading + + +class LoadContext(threading.local): + """A context for loading a model.""" + + def __init__(self): + super(LoadContext, self).__init__() + self._entered_load_context = [] + self._load_options = None + + def set_load_options(self, load_options): + self._load_options = load_options + self._entered_load_context.append(True) + + def clear_load_options(self): + self._load_options = None + self._entered_load_context.pop() + + def load_options(self): + return self._load_options + + def in_load_context(self): + return self._entered_load_context + + +_load_context = LoadContext() + + +@contextlib.contextmanager +def load_context(load_options): + _load_context.set_load_options(load_options) + try: + yield + finally: + _load_context.clear_load_options() + + +def get_load_options(): + """Returns the load options under a load context.""" + return _load_context.load_options() + + +def in_load_context(): + """Returns whether under a load context.""" + return _load_context.in_load_context() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/metric_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/metric_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..f85dca5582a0a728710407ea5154aab97f1d53be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/metric_serialization.py @@ -0,0 +1,43 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and functions implementing Metrics SavedModel serialization.""" + +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.trackable import data_structures + + +class MetricSavedModelSaver(layer_serialization.LayerSavedModelSaver): + """Metric serialization.""" + + @property + def object_identifier(self): + return constants.METRIC_IDENTIFIER + + def _python_properties_internal(self): + metadata = dict( + class_name=generic_utils.get_registered_name(type(self.obj)), + name=self.obj.name, + dtype=self.obj.dtype) + metadata.update(layer_serialization.get_serialized(self.obj)) + if self.obj._build_input_shape is not None: # pylint: disable=protected-access + metadata['build_input_shape'] = self.obj._build_input_shape # pylint: disable=protected-access + return metadata + + def _get_serialized_attributes_internal(self, unused_serialization_cache): + return (dict(variables=data_structures.wrap_or_unwrap(self.obj.variables)), + dict()) # TODO(b/135550038): save functions to enable saving + # custom metrics. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/model_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/model_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..66284297e9e7cb7627658dbed12afc9fc47414de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/model_serialization.py @@ -0,0 +1,63 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and functions implementing to Model SavedModel serialization.""" + +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import layer_serialization +from tensorflow.python.keras.saving.saved_model import save_impl + + +class ModelSavedModelSaver(layer_serialization.LayerSavedModelSaver): + """Model SavedModel serialization.""" + + @property + def object_identifier(self): + return constants.MODEL_IDENTIFIER + + def _python_properties_internal(self): + metadata = super(ModelSavedModelSaver, self)._python_properties_internal() + # Network stateful property is dependent on the child layers. + metadata.pop('stateful') + metadata['is_graph_network'] = self.obj._is_graph_network # pylint: disable=protected-access + metadata['save_spec'] = self.obj._get_save_spec(dynamic_batch=False) # pylint: disable=protected-access + + metadata.update( + saving_utils.model_metadata( + self.obj, include_optimizer=True, require_config=False)) + return metadata + + def _get_serialized_attributes_internal(self, serialization_cache): + default_signature = None + + # Create a default signature function if this is the only object in the + # cache (i.e. this is the root level object). + if len(serialization_cache[constants.KERAS_CACHE_KEY]) == 1: + default_signature = save_impl.default_save_signature(self.obj) + + # Other than the default signature function, all other attributes match with + # the ones serialized by Layer. + objects, functions = ( + super(ModelSavedModelSaver, self)._get_serialized_attributes_internal( + serialization_cache)) + functions['_default_save_signature'] = default_signature + return objects, functions + + +class SequentialSavedModelSaver(ModelSavedModelSaver): + + @property + def object_identifier(self): + return constants.SEQUENTIAL_IDENTIFIER diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/network_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/network_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..510f0ea4c2252c838564bbc2c5a2e851d1dfea8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/network_serialization.py @@ -0,0 +1,27 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes and functions implementing to Network SavedModel serialization.""" + +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import model_serialization + + +# FunctionalModel serialization is pretty much the same as Model serialization. +class NetworkSavedModelSaver(model_serialization.ModelSavedModelSaver): + """Network serialization.""" + + @property + def object_identifier(self): + return constants.NETWORK_IDENTIFIER diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save.py new file mode 100644 index 0000000000000000000000000000000000000000..0e81f62fa33479180a773f3a949994fede5d4573 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save.py @@ -0,0 +1,124 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras SavedModel serialization.""" + +import os + +from tensorflow.python.keras import backend as K +from tensorflow.python.keras.protobuf import saved_metadata_pb2 +from tensorflow.python.keras.protobuf import versions_pb2 +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import save_impl +from tensorflow.python.keras.saving.saved_model import utils +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite +from tensorflow.python.platform import gfile +from tensorflow.python.saved_model import save as save_lib + +# To avoid circular dependencies between keras/engine and keras/saving, +# code in keras/saving must delay imports. + +base_layer = LazyLoader( + "base_layer", globals(), + "tensorflow.python.keras.engine.base_layer") +training_lib = LazyLoader( + "training_lib", globals(), + "tensorflow.python.keras.engine.training") + + +def save(model, filepath, overwrite, include_optimizer, signatures=None, + options=None, save_traces=True): + """Saves a model as a SavedModel to the filepath. + + Args: + model: Keras model instance to be saved. + filepath: String path to save the model. + overwrite: whether to overwrite the existing filepath. + include_optimizer: If True, save the model's optimizer state. + signatures: Signatures to save with the SavedModel. Applicable to the 'tf' + format only. Please see the `signatures` argument in `tf.saved_model.save` + for details. + options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` + object that specifies options for saving to SavedModel. + save_traces: (only applies to SavedModel format) When enabled, the + SavedModel will store the function traces for each layer. This + can be disabled, so that only the configs of each layer are stored. + Defaults to `True`. Disabling this will decrease serialization time + and reduce file size, but it requires that all custom layers/models + implement a `get_config()` method. + + Raises: + ValueError: if the model's inputs have not been defined. + """ + # If file exists and should not be overwritten. + if not overwrite and os.path.exists(filepath): + proceed = ask_to_proceed_with_overwrite(filepath) + if not proceed: + return + + if save_traces: + if save_impl.should_skip_serialization(model): + saving_utils.raise_model_input_error(model) + + if not include_optimizer: + orig_optimizer = model.optimizer + model.optimizer = None + # TODO(b/180760306) Change to del model.optimizer if Layer's __delattr__ + # calls AutoTrackable's __delattr__. + model._delete_tracking("optimizer") # pylint: disable=protected-access + + # Trace all functions and signatures with `training=0` instead of using an + # already-set learning phase placeholder. + # This is needed for compatibility reasons until learning phase setting + # is removed from the public apis. + with K.deprecated_internal_learning_phase_scope(0): + with utils.keras_option_scope(save_traces): + saved_nodes, node_paths = save_lib.save_and_return_nodes( + model, filepath, signatures, options) + + # Save all metadata to a separate file in the SavedModel directory. + metadata = generate_keras_metadata(saved_nodes, node_paths) + + with gfile.GFile( + os.path.join(filepath, constants.SAVED_METADATA_PATH), "wb") as w: + w.write(metadata.SerializeToString(deterministic=True)) + + if not include_optimizer: + model.optimizer = orig_optimizer + + +def generate_keras_metadata(saved_nodes, node_paths): + """Constructs a KerasMetadata proto with the metadata of each keras object.""" + metadata = saved_metadata_pb2.SavedMetadata() + + for node_id, node in enumerate(saved_nodes): + if isinstance(node, base_layer.Layer): + path = node_paths[node] + if not path: + node_path = "root" + else: + node_path = "root.{}".format( + ".".join([ref.name for ref in path])) + + metadata.nodes.add( + node_id=node_id, + node_path=node_path, + version=versions_pb2.VersionDef( + producer=1, min_consumer=1, bad_consumers=[]), + identifier=node._object_identifier, # pylint: disable=protected-access + metadata=node._tracking_metadata) # pylint: disable=protected-access + + return metadata diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..23240bacd420a7a570a0291954f8905566da4bc4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/save_impl.py @@ -0,0 +1,734 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras SavedModel serialization. + +TODO (kathywu): Move to layer_serialization.py. Some model-specific logic should +go to model_serialization.py. +""" + +import functools +import threading +import weakref + +from tensorflow.python.eager import def_function +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.keras import backend as K +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import input_spec +from tensorflow.python.keras.mixed_precision import autocast_variable +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import load as keras_load +from tensorflow.python.keras.saving.saved_model import serialized_attributes +from tensorflow.python.keras.saving.saved_model import utils +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator + + +# To avoid circular dependencies between keras/engine and keras/saving, +# code in keras/saving must delay imports. + +# TODO(b/134426265): Switch back to single-quotes to match the rest of the file +# once the issue with copybara is fixed. +# pylint:disable=g-inconsistent-quotes +base_layer = LazyLoader( + "base_layer", globals(), + "tensorflow.python.keras.engine.base_layer") +metrics = LazyLoader("metrics", globals(), + "tensorflow.python.keras.metrics") +input_layer = LazyLoader( + "input_layer", globals(), + "tensorflow.python.keras.engine.input_layer") +training_lib = LazyLoader( + "training_lib", globals(), + "tensorflow.python.keras.engine.training") +sequential_lib = LazyLoader( + "sequential_lib", globals(), + "tensorflow.python.keras.engine.sequential") +# pylint:enable=g-inconsistent-quotes + + +def should_skip_serialization(layer): + """Skip serializing extra objects and functions if layer inputs aren't set.""" + saved_model_input_spec_set = (isinstance(layer, training_lib.Model) and + layer._saved_model_inputs_spec is not None) # pylint: disable=protected-access + if not layer.built and not saved_model_input_spec_set: + logging.warning('Skipping full serialization of Keras layer {}, because ' + 'it is not built.'.format(layer)) + return True + return False + + +def wrap_layer_objects(layer, serialization_cache): + """Returns extra trackable objects to attach to the serialized layer. + + Args: + layer: Keras Layer object. + serialization_cache: Dictionary shared between all objects during + serialization. + + Returns: + A dictionary containing all checkpointable objects from a + SerializedAttributes object. See LayerAttributes and ModelAttributes for + entire list of objects + """ + # Wrap all regularization losses as tf.functions. + # First, generate list of all regularization losses in this layer and + # sublayers. + all_losses = layer._callable_losses[:] # pylint: disable=protected-access + for child_layer in utils.list_all_layers(layer): + all_losses.extend(child_layer._callable_losses) # pylint: disable=protected-access + # Next, wrap all loss functions as tf.functions. Use the serialization cache + # to store already-wrapped functions. + keras_loss_cache = serialization_cache.setdefault('keras_losses', {}) + wrapped_loss_functions = [] + for loss_fn in all_losses: + if loss_fn in keras_loss_cache: + wrapped_loss_functions.append(keras_loss_cache[loss_fn]) + else: + wrapped_loss = _wrap_unconditional_loss(loss_fn, len(keras_loss_cache)) + keras_loss_cache[loss_fn] = wrapped_loss + wrapped_loss_functions.append(wrapped_loss) + wrapped_layer_losses = [keras_loss_cache[fn] + for fn in layer._callable_losses[:]] # pylint: disable=protected-access + + layer_metrics = data_structures.wrap_or_unwrap( + {m.name: m for m in layer._metrics}) # pylint: disable=protected-access + return dict( + variables=data_structures.wrap_or_unwrap(layer.variables), + trainable_variables=data_structures.wrap_or_unwrap( + layer.trainable_variables), + non_trainable_variables=data_structures.wrap_or_unwrap( + layer.non_trainable_variables), + layers=data_structures.wrap_or_unwrap(utils.list_all_layers(layer)), + metrics=data_structures.wrap_or_unwrap(layer.metrics), + regularization_losses=data_structures.wrap_or_unwrap( + wrapped_loss_functions), + layer_regularization_losses=data_structures.wrap_or_unwrap( + wrapped_layer_losses), + layer_metrics=layer_metrics) + # pylint: disable=protected-access + + +def wrap_layer_functions(layer, serialization_cache): + """Returns dict of wrapped layer call function and losses in tf.functions. + + Args: + layer: Keras Layer object. + serialization_cache: Dictionary shared between all objects during + serialization. + + Returns: + A dictionary containing all keras tf.functions to serialize. See + LayerAttributes and ModelAttributes for the list of all attributes. + """ + # Since Sequential models may be modified in place using model.add() or + # model.pop(), don't use saved functions. + if (isinstance(layer, keras_load.RevivedLayer) and + not isinstance(layer, sequential_lib.Sequential)): + return {fn_name: getattr(layer.keras_api, fn_name, None) + for fn_name in serialized_attributes.LayerAttributes.all_functions} + + # Reset the losses of the layer and its children. The call function in each + # child layer is replaced with tf.functions. + original_fns = _replace_child_layer_functions(layer, serialization_cache) + original_losses = _reset_layer_losses(layer) + + # Wrap all the layer call and activity regularizer functions. + + # Use LayerCallCollection to ensure that all layer call functions (__call__, + # call with losses) are traced with the same inputs. + call_collection = LayerCallCollection(layer) + call_fn_with_losses = call_collection.add_function( + _wrap_call_and_conditional_losses(layer), + '{}_layer_call_and_return_conditional_losses'.format(layer.name), + # If any of this layer's child layers use the training arg, the traced + # call functions of this layer will have a training keyword argument. If + # the original layer does not expect the training arg, then it will have + # to be removed (by setting `match_layer_training_arg`). + match_layer_training_arg=True) + call_fn = call_collection.add_function( + _extract_outputs_from_fn(layer, call_fn_with_losses), + '{}_layer_call_fn'.format(layer.name), + # Since `call_fn` wraps call_fn_with_losses and not the original call + # function, `match_layer_training_arg` should be set to False. + match_layer_training_arg=False) + + fns = {'call_and_return_conditional_losses': call_fn_with_losses, + '__call__': call_fn} + + if layer._activity_regularizer is not None: # pylint: disable=protected-access + fns['activity_regularizer_fn'] = _wrap_activity_regularizer(layer) + fns['call_and_return_all_conditional_losses'] = ( + call_collection.add_function( + _append_activity_regularizer_loss( + layer, call_fn_with_losses, fns['activity_regularizer_fn']), + '{}_layer_call_and_return_all_conditional_losses'.format( + layer.name), + match_layer_training_arg=False)) + else: + fns['activity_regularizer_fn'] = None + fns['call_and_return_all_conditional_losses'] = call_fn_with_losses + + # Manually trigger traces before restoring the overwritten functions. The + # functions are traced within the layer call context to ensure that layer + # functions (e.g. add_loss) behave as though running in graph mode. + with tracing_scope(): + call_collection.trace_with_input_signature() + with base_layer_utils.call_context().enter( + layer, inputs=None, build_graph=True, training=None, saving=True): + for fn in fns.values(): + if fn is not None and fn.input_signature is not None: + if isinstance(fn, LayerCall): + fn = fn.wrapped_call + fn.get_concrete_function() + + # Restore overwritten functions and losses + _restore_child_layer_functions(original_fns) + _restore_layer_losses(original_losses) + + return fns + + +def default_save_signature(layer): + original_losses = _reset_layer_losses(layer) + fn = saving_utils.trace_model_call(layer) + fn.get_concrete_function() + _restore_layer_losses(original_losses) + return fn + + +def _replace_child_layer_functions(layer, serialization_cache): + """Replaces functions in the children layers with wrapped tf.functions. + + This step allows functions from parent layers to reference the wrapped + functions from their children layers instead of retracing the ops. + + This function also resets all losses stored in the layer. These are stored in + the returned dictionary. Use `_restore_child_layer_functions` to restore + the original attributes. + + Args: + layer: Keras Layer object. + serialization_cache: Dictionary shared between all objects during + serialization. + + Returns: + Dictionary mapping layer objects -> original functions and losses: + { Child layer 1: { + 'losses': Original losses, + 'call': Original call function + '_activity_regularizer': Original activity regularizer}, + Child layer 2: ... + } + """ + # pylint: disable=protected-access + original_fns = {} + + def replace_layer_functions(child_layer, serialized_fns): + """Replaces layer call and activity regularizer with wrapped functions.""" + original_fns[child_layer] = { + 'call': child_layer.call, + '_activity_regularizer': child_layer._activity_regularizer + } + with utils.no_automatic_dependency_tracking_scope(child_layer): + try: + child_layer._activity_regularizer = serialized_fns.get( + 'activity_regularizer_fn') + except AttributeError: + # Some layers have an unsettable activity regularizer. + pass + child_layer.call = utils.use_wrapped_call( + child_layer, + serialized_fns['call_and_return_conditional_losses'], + default_training_value=False) + + def replace_metric_functions(child_layer, serialized_fns): + """Replaces metric functions with wrapped functions.""" + original_fns[child_layer] = { + '__call__': child_layer.__call__, + 'result': child_layer.result, + 'update_state': child_layer.update_state + } + with utils.no_automatic_dependency_tracking_scope(child_layer): + child_layer.__call__ = serialized_fns['__call__'] + child_layer.result = serialized_fns['result'] + child_layer.update_state = serialized_fns['update_state'] + + for child_layer in utils.list_all_layers(layer): + if isinstance(child_layer, input_layer.InputLayer): + continue + + if child_layer not in serialization_cache[constants.KERAS_CACHE_KEY]: + serialized_functions = ( + child_layer._trackable_saved_model_saver._get_serialized_attributes( + serialization_cache).functions) + else: + serialized_functions = ( + serialization_cache[constants.KERAS_CACHE_KEY][child_layer].functions) + if not serialized_functions: + # This indicates either: + # - circular dependency, which means the current layer's functions + # should be wrapped first. + # - Child layer's inputs are not defined, so its functions have not been + # wrapped. In this case, no replacement is necessary so move on to the + # next child. + continue + + if isinstance(child_layer, metrics.Metric): + replace_metric_functions(child_layer, serialized_functions) + else: + replace_layer_functions(child_layer, serialized_functions) + + return original_fns + # pylint: enable=protected-access + + +def _restore_child_layer_functions(original_fns): + """Restores attributes replaced with `_replace_child_layer_functions`.""" + for child_layer, fns in original_fns.items(): + with utils.no_automatic_dependency_tracking_scope(child_layer): + for fn_name, fn in fns.items(): + try: + setattr(child_layer, fn_name, fn) # pylint: disable=protected-access + except AttributeError: + pass # In the case of _activity_regularizer, setting the attribute + # may be disallowed. + + +# pylint: disable=protected-access +def _reset_layer_losses(parent_layer): + """Resets losses of layer and its sublayers, and returns original losses.""" + losses_dict = {} + for layer in utils.list_all_layers_and_sublayers(parent_layer): + losses_dict[layer] = {'losses': layer._losses[:], + 'eager_losses': layer._eager_losses[:]} + with utils.no_automatic_dependency_tracking_scope(layer): + layer._losses = [] + layer._eager_losses = [] + return losses_dict + + +def _restore_layer_losses(losses_dict): + for layer in losses_dict: + with utils.no_automatic_dependency_tracking_scope(layer): + layer._losses = losses_dict[layer]['losses'] + layer._eager_losses = losses_dict[layer]['eager_losses'] +# pylint: enable=protected-access + + +class LayerTracingContext(threading.local): + + def __init__(self): + super(LayerTracingContext, self).__init__() + self.enable_call_tracing = False + self.trace_queue = [] + +_thread_local_data = LayerTracingContext() + + +@tf_contextlib.contextmanager +def tracing_scope(): + """Enables tracing scope.""" + # This enables the LayerCallCollection's tracing mechanism to trace all call + # functions in the collection. + previous_value = _thread_local_data.enable_call_tracing + previous_queue = _thread_local_data.trace_queue + try: + _thread_local_data.enable_call_tracing = True + _thread_local_data.trace_queue = [] + yield + finally: + # Run traces from the queue. + while _thread_local_data.trace_queue: + fn, args, kwargs, training = _thread_local_data.trace_queue.pop() + if training is not None: + with K.deprecated_internal_learning_phase_scope(training): + fn.get_concrete_function(*args, **kwargs) + else: + fn.get_concrete_function(*args, **kwargs) + _thread_local_data.trace_queue = previous_queue + _thread_local_data.enable_call_tracing = previous_value + + +def add_trace_to_queue(fn, args, kwargs, training=None): + if tracing_enabled(): + _thread_local_data.trace_queue.append( + (fn, args[:], kwargs.copy(), training)) + + +def tracing_enabled(): + """Whether to add extra traces to the queue.""" + return _thread_local_data.enable_call_tracing + + +class LayerCallCollection(object): + """Groups wrapped layer call functions. + + This is used to ensure that all layer call functions are traced with the same + inputs- + - call + - call_and_return_conditional_losses + - call_and_return_all_conditional_losses + """ + + def __init__(self, layer): + self.layer = layer + + self.layer_call_method = _get_layer_call_method(layer) + self._expects_training_arg = utils.layer_uses_training_bool(layer) + self._training_arg_index = utils.get_training_arg_index( + self.layer_call_method) + + # If the layer call function has kwargs, then the traced function cannot + # have an input signature. + arg_spec = tf_inspect.getfullargspec(self.layer_call_method) + self._has_kwargs = bool(self._expects_training_arg or + arg_spec.defaults or + arg_spec.kwonlyargs or + arg_spec.varkw) + + self._input_signature = self._generate_input_signature(layer) + self._functions = weakref.WeakValueDictionary() + + # Get the input argument name from the args. + args = arg_spec.args + if tf_inspect.ismethod(self.layer_call_method): + args = args[1:] + self._input_arg_name = args[0] if args else 'inputs' + + def _generate_input_signature(self, layer): + """Inspects layer object and returns the inferred input signature. + + Args: + layer: Layer object. + + Returns: + List of possibly nested TensorSpecs of the layer call function inputs. + The list does not contain the `training` argument. + """ + if (isinstance(layer.call, def_function.Function) and + layer.call.input_signature is not None): + return layer.call.input_signature + elif isinstance(layer, training_lib.Model): + return saving_utils.model_input_signature(layer) + elif (layer.input_spec is not None and + layer._use_input_spec_as_call_signature): # pylint: disable=protected-access + + def to_tensor_spec_or_none(x): + spec = input_spec.to_tensor_spec(x, layer._compute_dtype) # pylint: disable=protected-access + # If the shape is too general (e.g. multiple dimensions are allowed), + # return None so that separate functions can be generated for each + # inferred input signature. + # TODO(b/134962016): currently partial signatures are not supported. + if spec.shape == tensor_shape.TensorShape(None): + return None + return spec + input_signature = [nest.map_structure( + to_tensor_spec_or_none, layer.input_spec)] + + return input_signature + else: + return None + + def add_trace(self, *args, **kwargs): + """Traces all functions with the same args and kwargs. + + Args: + *args: Positional args passed to the original function. + **kwargs: Keyword args passed to the original function. + """ + args = list(args) + kwargs = kwargs.copy() + + for fn in self._functions.values(): + # TODO(kathywu): Replace arguments with broader shapes defined in the + # input signature. + if self._expects_training_arg: + def trace_with_training(value, fn=fn): + utils.set_training_arg(value, self._training_arg_index, args, kwargs) + add_trace_to_queue(fn, args, kwargs, value) + + trace_with_training(True) + trace_with_training(False) + else: + add_trace_to_queue(fn, args, kwargs) + + @property + def fn_input_signature(self): + """Returns input signature for the wrapped layer call function.""" + if self._has_kwargs: + # Input signatures may only describe tensor arguments and kwargs are not + # supported. + return None + if None in nest.flatten(self._input_signature): + # TODO(b/134962016): If input signature cannot be partially defined. + return None + return self._input_signature + + def training_arg_was_passed(self, args, kwargs): + if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access + return (utils.get_training_arg(self._training_arg_index, args, kwargs) + is not None) + else: + return self.layer._call_arg_was_passed( # pylint: disable=protected-access + 'training', args, kwargs, inputs_in_args=True) + + def get_training_arg_value(self, args, kwargs): + if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access + return utils.get_training_arg(self._training_arg_index, args, kwargs) + else: + return self.layer._get_call_arg_value( # pylint: disable=protected-access + 'training', args, kwargs, inputs_in_args=True) + + def get_input_arg_value(self, args, kwargs): + return self.layer._get_call_arg_value( # pylint: disable=protected-access + self._input_arg_name, args, kwargs, inputs_in_args=True) + + def _maybe_wrap_with_training_arg(self, call_fn, match_layer_training_arg): + """Wraps call function with added training argument if necessary.""" + if not self.layer._expects_training_arg and self._expects_training_arg: # pylint: disable=protected-access + # Add training arg to wrapper function. + arg_spec = tf_inspect.getfullargspec(call_fn) + args = arg_spec.args + ['training'] + defaults = list(arg_spec.defaults or []) + defaults.append(False) + new_arg_spec = tf_inspect.FullArgSpec( + args=args, + varargs=arg_spec.varargs, + varkw=arg_spec.varkw, + defaults=defaults, + kwonlyargs=arg_spec.kwonlyargs, + kwonlydefaults=arg_spec.kwonlydefaults, + annotations=arg_spec.annotations) + + # Set new training arg index + self._training_arg_index = len(args) - 1 + if tf_inspect.ismethod(call_fn): + self._training_arg_index -= 1 + + def wrap_with_training_arg(*args, **kwargs): + if match_layer_training_arg: + # Remove the training value, since the original call_fn does not + # expect a training arg. Instead, the training value will be + # propagated using the call context created in LayerCall. + args = list(args) + kwargs = kwargs.copy() + utils.remove_training_arg(self._training_arg_index, args, kwargs) + return call_fn(*args, **kwargs) + + return tf_decorator.make_decorator( + target=call_fn, + decorator_func=wrap_with_training_arg, + decorator_argspec=new_arg_spec) + + return call_fn + + def add_function(self, call_fn, name, match_layer_training_arg): + """Adds a layer call function to the collection. + + Args: + call_fn: a python function + name: Name of call function + match_layer_training_arg: If True, removes the `training` from the + function arguments when calling `call_fn`. + + Returns: + LayerCall (tf.function) + """ + fn = LayerCall( + self, + self._maybe_wrap_with_training_arg(call_fn, match_layer_training_arg), + name, + input_signature=self.fn_input_signature) + self._functions[name] = fn.wrapped_call + return fn + + def trace_with_input_signature(self): + """Trace with the layer/models inferred input signature if possible.""" + if (None not in nest.flatten(self._input_signature) and self._has_kwargs): + # Manually add traces for layers that have keyword arguments and have + # a fully defined input signature. + self.add_trace(*self._input_signature) + + +def _filtered_inputs(inputs): + return list(filter(tf_utils.is_tensor_or_variable, nest.flatten(inputs))) + + +def layer_call_wrapper(call_collection, method, name): + """Ensures layer losses are kept the same, and runs method in call context.""" + + # Create wrapper that deals with losses and call context. + def wrapper(*args, **kwargs): + """Calls method within call context.""" + layer = call_collection.layer + training = None + inputs = _filtered_inputs([args, kwargs]) + # pylint: disable=protected-access + if (args or kwargs) and call_collection.training_arg_was_passed( + args, kwargs): + training = call_collection.get_training_arg_value(args, kwargs) + # pylint: enable=protected-access + original_losses = _reset_layer_losses(layer) + with base_layer_utils.call_context().enter( + layer, inputs=inputs, build_graph=False, training=training, + saving=True): + with autocast_variable.enable_auto_cast_variables( + layer._compute_dtype_object): # pylint: disable=protected-access + ret = method(*args, **kwargs) + _restore_layer_losses(original_losses) + return ret + + # Rename to `name`, since tf.function doesn't have a name argument. Without + # this, all functions returned by this method will be named "call", which + # would be a nightmare to debug. + fn = tf_decorator.make_decorator(target=method, decorator_func=wrapper) + fn.__name__ = name + return fn + + +class LayerCall(object): + """Function that triggers traces of other functions in the same collection.""" + + def __init__(self, call_collection, call_fn, name, input_signature): + """Initializes a LayerCall object. + + Args: + call_collection: a LayerCallCollection, which contains the other layer + call functions (e.g. call_with_conditional_losses, call). These + functions should be traced with the same arguments. + call_fn: A call function. + name: Name of the call function. + input_signature: Input signature of call_fn (can be None). + """ + self.call_collection = call_collection + self.input_signature = input_signature + self.wrapped_call = def_function.function( + layer_call_wrapper(call_collection, call_fn, name), + input_signature=input_signature) + self.original_layer_call = call_collection.layer_call_method + + def _maybe_trace(self, args, kwargs): + # Trigger traces of other call functions + extra training-arg traces. + if tracing_enabled(): + self.call_collection.add_trace(*args, **kwargs) + + def __call__(self, *args, **kwargs): + self._maybe_trace(args, kwargs) + return self.wrapped_call(*args, **kwargs) + + def get_concrete_function(self, *args, **kwargs): + self._maybe_trace(args, kwargs) + return self.wrapped_call.get_concrete_function(*args, **kwargs) + + +def _wrap_call_and_conditional_losses(layer): + """Wraps call function that returns a tuple of (outputs, losses). + + The losses returned are conditional on the inputs passed to the call function. + Unconditional losses (e.g. weight regularizeration) are wrapped separately. + + Args: + layer: a Keras layer object + + Returns: + python call function that returns outputs and conditional losses -- excludes + activity regularizer + """ + # Create function that generates both outputs and losses + layer_call = _get_layer_call_method(layer) + def call_and_return_conditional_losses(*args, **kwargs): + """Returns layer (call_output, conditional losses) tuple.""" + call_output = layer_call(*args, **kwargs) + if version_utils.is_v1_layer_or_model(layer): + conditional_losses = layer.get_losses_for( + _filtered_inputs([args, kwargs])) + else: + conditional_losses = [ + l for l in layer.losses if not hasattr(l, '_unconditional_loss') + ] + return call_output, conditional_losses + + return _create_call_fn_decorator(layer, call_and_return_conditional_losses) + + +def _extract_outputs_from_fn(layer, call_and_return_conditional_losses): + """Returns a function that returns only call function outputs.""" + if isinstance(layer, keras_load.RevivedLayer): + return layer.keras_api.__call__ # pylint: disable=protected-access + def call(inputs, *args, **kwargs): + return call_and_return_conditional_losses(inputs, *args, **kwargs)[0] + return _create_call_fn_decorator(layer, call) + + +def _append_activity_regularizer_loss( + layer, call_fn_with_losses, activity_regularizer_fn): + """Appends activity regularizer loss to losses returned by the wrapped fn.""" + def fn(inputs, *args, **kwargs): + outputs, losses = call_fn_with_losses(inputs, *args, **kwargs) + losses.append(activity_regularizer_fn(outputs)) + return outputs, losses + return _create_call_fn_decorator(layer, fn) + + +def _create_call_fn_decorator(layer, wrapped_call): + call_fn = _get_layer_call_method(layer) + fn, arg_spec = utils.maybe_add_training_arg( + call_fn, wrapped_call, layer._expects_training_arg, # pylint: disable=protected-access + default_training_value=False) + return tf_decorator.make_decorator( + target=call_fn, + decorator_func=fn, + decorator_argspec=arg_spec) + + +def _wrap_unconditional_loss(loss_fn, index): + """Wraps callable/unconditional loss, returning a serializable function.""" + # Extract original loss function from partial function + fn = loss_fn.args[0] if isinstance(loss_fn, functools.partial) else loss_fn + if isinstance(fn, def_function.Function): + return fn + else: + return def_function.Function( + fn, 'loss_fn_{}'.format(index), input_signature=[]) + + +def _wrap_activity_regularizer(layer): + """Wraps the activity regularizer.""" + # pylint: disable=protected-access + if isinstance(layer._activity_regularizer, def_function.Function): + return layer._activity_regularizer + return def_function.Function( + layer._activity_regularizer, + '{}_activity_regularizer'.format(layer.name), + input_signature=[ + tensor_spec.TensorSpec(None, layer._compute_dtype or K.floatx()) + ]) + # pylint: enable=protected-access + + +def _get_layer_call_method(layer): + if isinstance(layer.call, (def_function.Function)): + return layer.call.python_function + return layer.call diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/serialized_attributes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/serialized_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..b12d2c3aad84af8338b915b1ff154df3daabd1d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/serialized_attributes.py @@ -0,0 +1,311 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper classes that list&validate all attributes to serialize to SavedModel. +""" + +from tensorflow.python.eager import def_function +from tensorflow.python.keras.saving.saved_model import constants +from tensorflow.python.keras.saving.saved_model import save_impl +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable.autotrackable import AutoTrackable + +# TODO(b/134426265): Switch back to single-quotes to match the rest of the file +# once the issue with copybara is fixed. +# pylint:disable=g-inconsistent-quotes +base_layer = LazyLoader( + "base_layer", globals(), + "tensorflow.python.keras.engine.base_layer") +training_lib = LazyLoader( + "training_lib", globals(), + "tensorflow.python.keras.engine.training") +metrics = LazyLoader("metrics", globals(), + "tensorflow.python.keras.metrics") +recurrent = LazyLoader( + "recurrent", globals(), + "tensorflow.python.keras.layers.recurrent") +# pylint:enable=g-inconsistent-quotes + + +class SerializedAttributes(object): + """Class that tracks and validates all serialization attributes. + + Keras models contain many Python-defined components. For example, the + trainable_variable property lists the model's trainable variables by + recursively retrieving the trainable variables from each of the child layers. + Another example is model.call, a python function that calls child layers and + adds ops to the backend graph. + + Only Tensorflow checkpointable objects and functions can be serialized to + SavedModel. Serializing a Keras model as-is results in a checkpointable object + that does not resemble a Keras model at all. Thus, extra checkpointable + objects and functions must be created during serialization. + + **Defining new serialized attributes** + Child classes should be defined using: + SerializedAttributes.with_attributes( + 'name', checkpointable_objects=[...], functions=[...], copy_from=[...]) + This class is used to cache generated checkpointable objects and functions, + ensuring that new objects and functions are generated a single time. + + **Usage during serialization** + Each Layer/Model object should have a corresponding instance of + SerializedAttributes. Create a new instance by calling + `SerializedAttributes.new(obj)`. Objects and functions may be saved using + `.set_and_validate_checkpointable_objects`/`.set_and_and_validate_functions`. + The properties `.checkpointable_objects` and `.functions` returns the cached + values. + + **Adding/changing attributes to save to SavedModel** + 1. Change the call to `SerializedAttributes.with_attributes` in the correct + class: + - CommonEndpoints: Base attributes to be added during serialization. If + these attributes are present in a Trackable object, it can be + deserialized to a Keras Model. + - LayerAttributes: Attributes to serialize for Layer objects. + - ModelAttributes: Attributes to serialize for Model objects. + 2. Update class docstring + 3. Update arguments to any calls to `set_and_validate_*`. For example, if + `call_raw_tensors` is added to the ModelAttributes function list, then + a `call_raw_tensors` function should be passed to + `set_and_validate_functions`. + + **Common endpoints vs other attributes** + Only common endpoints are attached directly to the root object. Keras-specific + attributes are saved to a separate trackable object with the name "keras_api". + The number of objects attached to the root is limited because any naming + conflicts will cause user code to break. + + Another reason is that this will only affect users who call + `tf.saved_model.load` instead of `tf.keras.models.load_model`. These are + advanced users who are likely to have defined their own tf.functions and + trackable objects. The added Keras-specific attributes are kept out of the way + in the "keras_api" namespace. + + Properties defined in this class may be used to filter out keras-specific + attributes: + - `functions_to_serialize`: Returns dict of functions to attach to the root + object. + - `checkpointable_objects_to_serialize`: Returns dict of objects to attach to + the root object (including separate trackable object containing + keras-specific attributes) + + All changes to the serialized attributes must be backwards-compatible, so + attributes should not be removed or modified without sufficient justification. + """ + + @staticmethod + def with_attributes( + name, checkpointable_objects=None, functions=None, copy_from=None): + """Creates a subclass with all attributes as specified in the arguments. + + Args: + name: Name of subclass + checkpointable_objects: List of checkpointable objects to be serialized + in the SavedModel. + functions: List of functions to be serialized in the SavedModel. + copy_from: List of other SerializedAttributes subclasses. The returned + class will copy checkpoint objects/functions from each subclass. + + Returns: + Child class with attributes as defined in the `checkpointable_objects` + and `functions` lists. + """ + checkpointable_objects = checkpointable_objects or [] + functions = functions or [] + + if copy_from is not None: + for cls in copy_from: + checkpointable_objects.extend(cls.all_checkpointable_objects) + functions.extend(cls.all_functions) + + classdict = { + 'all_checkpointable_objects': set(checkpointable_objects), + 'all_functions': set(functions)} + return type(name, (SerializedAttributes,), classdict) + + @staticmethod + def new(obj): + """Returns a new SerializedAttribute object.""" + if isinstance(obj, training_lib.Model): + return ModelAttributes() + elif isinstance(obj, metrics.Metric): + return MetricAttributes() + elif isinstance(obj, recurrent.RNN): + return RNNAttributes() + elif isinstance(obj, base_layer.Layer): + return LayerAttributes() + else: + raise TypeError('Internal error during serialization: Expected Keras ' + 'Layer object, got {} of type {}'.format(obj, type(obj))) + + def __init__(self): + self._object_dict = {} + self._function_dict = {} + self._keras_trackable = AutoTrackable() + + @property + def functions(self): + """Returns dictionary of all functions.""" + return {key: value for key, value in self._function_dict.items() + if value is not None} + + @property + def checkpointable_objects(self): + """Returns dictionary of all checkpointable objects.""" + return {key: value for key, value in self._object_dict.items() + if value is not None} + + @property + def functions_to_serialize(self): + """Returns functions to attach to the root object during serialization.""" + functions = {} + for key, v in self.functions.items(): + if key in CommonEndpoints.all_functions: + functions[key] = (v.wrapped_call if isinstance(v, save_impl.LayerCall) + else v) + return functions + + @property + def objects_to_serialize(self): + """Returns objects to attach to the root object during serialization.""" + objects = {key: value for key, value in self.checkpointable_objects.items() + if key in CommonEndpoints.all_checkpointable_objects} + objects[constants.KERAS_ATTR] = self._keras_trackable + return objects + + def set_and_validate_functions(self, function_dict): + """Saves function dictionary, and validates dictionary values.""" + for key in self.all_functions: + if key in function_dict: + if (function_dict[key] is not None and # Not all functions are required + not isinstance(function_dict[key], + (def_function.Function, save_impl.LayerCall))): + raise ValueError( + 'Function dictionary contained a non-function object: {} (for key' + ' {})'.format(function_dict[key], key)) + fn = function_dict[key] + self._function_dict[key] = fn + + # Extract TensorFlow `Function` from LayerCall. + tf_fn = fn.wrapped_call if isinstance(fn, save_impl.LayerCall) else fn + setattr(self._keras_trackable, key, tf_fn) + else: + raise ValueError('Function {} missing from serialized function dict.' + .format(key)) + return self.functions + + def set_and_validate_objects(self, object_dict): + """Saves objects to a dictionary, and validates the values.""" + for key in self.all_checkpointable_objects: + if key in object_dict: + if not isinstance(object_dict[key], trackable.Trackable): + raise ValueError( + 'Object dictionary contained a non-trackable object: {} (for key' + ' {})'.format(object_dict[key], key)) + self._object_dict[key] = object_dict[key] + setattr(self._keras_trackable, key, object_dict[key]) + else: + raise ValueError( + 'Object {} missing from serialized object dict.'.format(key)) + return self.checkpointable_objects + + +class CommonEndpoints(SerializedAttributes.with_attributes( + 'CommonEndpoints', + checkpointable_objects=['variables', 'trainable_variables', + 'regularization_losses'], + functions=['__call__', 'call_and_return_all_conditional_losses', + '_default_save_signature'])): + """Common endpoints shared by all models loadable by Keras. + + List of all attributes: + variables: List of all variables in the model and its sublayers. + trainable_variables: List of all trainable variables in the model and its + sublayers. + regularization_losses: List of all unconditional losses (losses not + dependent on the inputs) in the model and its sublayers. + __call__: Function that takes inputs and returns the outputs of the model + call function. + call_and_return_all_conditional_losses: Function that returns a tuple of + (call function outputs, list of all losses that depend on the inputs). + _default_save_signature: Traced model call function. This is only included + if the top level exported object is a Keras model. + """ + + +class LayerAttributes(SerializedAttributes.with_attributes( + 'LayerAttributes', + checkpointable_objects=['non_trainable_variables', 'layers', 'metrics', + 'layer_regularization_losses', 'layer_metrics'], + functions=['call_and_return_conditional_losses', 'activity_regularizer_fn'], + copy_from=[CommonEndpoints] + )): + """Layer checkpointable objects + functions that are saved to the SavedModel. + + List of all attributes: + All attributes from CommonEndpoints + non_trainable_variables: List of non-trainable variables in the layer and + its sublayers. + layers: List of all sublayers. + metrics: List of all metrics in the layer and its sublayers. + call_and_return_conditional_losses: Function that takes inputs and returns a + tuple of (outputs of the call function, list of input-dependent losses). + The list of losses excludes the activity regularizer function, which is + separate to allow the deserialized Layer object to define a different + activity regularizer. + activity_regularizer_fn: Callable that returns the activity regularizer loss + layer_regularization_losses: List of losses owned only by this layer. + layer_metrics: List of metrics owned by this layer. + """ + + +class ModelAttributes(SerializedAttributes.with_attributes( + 'ModelAttributes', + copy_from=[LayerAttributes])): + """Model checkpointable objects + functions that are saved to the SavedModel. + + List of all attributes: + All attributes from LayerAttributes (including CommonEndpoints) + """ + # TODO(kathywu): Add attributes `compile_losses` and `compile_metrics`, which + # list all losses and metrics defined by `model.compile`. + + +class MetricAttributes( + SerializedAttributes.with_attributes( + 'MetricAttributes', + checkpointable_objects=['variables'], + functions=[], + )): + """Attributes that are added to Metric objects when saved to SavedModel. + + List of all attributes: + variables: list of all variables + """ + pass + + +class RNNAttributes(SerializedAttributes.with_attributes( + 'RNNAttributes', + checkpointable_objects=['states'], + copy_from=[LayerAttributes])): + """RNN checkpointable objects + functions that are saved to the SavedModel. + + List of all attributes: + All attributes from LayerAttributes (including CommonEndpoints) + states: List of state variables + """ + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dac6364515c8e535414437621a0429826ecf2c21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model/utils.py @@ -0,0 +1,306 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility functions shared between SavedModel saving/loading implementations.""" + +import itertools +import threading +import types + +from tensorflow.python.eager import context +from tensorflow.python.keras import backend as K +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.util import tf_decorator + + +# pylint:disable=g-inconsistent-quotes +training_lib = LazyLoader( + "training_lib", globals(), + "tensorflow.python.keras.engine.training") +# pylint:enable=g-inconsistent-quotes + + +def use_wrapped_call(layer, call_fn, default_training_value=None, + return_method=False): + """Creates fn that adds the losses returned by call_fn & returns the outputs. + + Args: + layer: A Keras layer object + call_fn: tf.function that takes layer inputs (and possibly a training arg), + and returns a tuple of (outputs, list of losses). + default_training_value: Default value of the training kwarg. If `None`, the + default is `K.learning_phase()`. + return_method: Whether to return a method bound to the layer. + + Returns: + function that calls call_fn and returns the outputs. Losses returned by + call_fn are added to the layer losses. + """ + expects_training_arg = layer_uses_training_bool(layer) + if hasattr(call_fn, 'original_layer_call'): # call_fn is a LayerCall object + original_call = call_fn.original_layer_call + # In Python 3, callable objects are not compatible with inspect.getargspec + call_fn = call_fn.__call__ + else: + original_call = call_fn + fn, arg_spec = maybe_add_training_arg( + original_call, call_fn, expects_training_arg, default_training_value) + + def return_outputs_and_add_losses(*args, **kwargs): + """Returns the outputs from the layer call function, and adds the losses.""" + if return_method: + args = args[1:] + + outputs, losses = fn(*args, **kwargs) + layer.add_loss(losses, inputs=True) + + # TODO(kathywu): This is a temporary hack. When a network of layers is + # revived from SavedModel, only the top-level layer will have losses. This + # causes issues in eager mode because the child layers may have graph losses + # (thus model.losses returns a mix of Eager and graph tensors). To fix this, + # whenever eager losses are added to one layer, add eager losses to all + # child layers. This causes `.losses` to only return eager losses. + # pylint: disable=protected-access + if context.executing_eagerly(): + for i in layer._flatten_layers(): + if i is not layer: + i._eager_losses = [base_layer_utils.REVIVED_LOSS_PLACEHOLDER] + # pylint: enable=protected-access + return outputs + + decorated = tf_decorator.make_decorator( + target=call_fn, + decorator_func=return_outputs_and_add_losses, + decorator_argspec=arg_spec) + + if return_method: + return types.MethodType(decorated, layer) + else: + return decorated + + +def layer_uses_training_bool(layer): + """Returns whether this layer or any of its children uses the training arg.""" + if layer._expects_training_arg: # pylint: disable=protected-access + return True + visited = {layer} + to_visit = list_all_layers(layer) + while to_visit: + layer = to_visit.pop() + if layer in visited: + continue + if getattr(layer, '_expects_training_arg', True): + return True + visited.add(layer) + to_visit.extend(list_all_layers(layer)) + return False + + +def list_all_layers(obj): + if isinstance(obj, training_lib.Model): + # Handle special case of Sequential, which doesn't return + # the `Input` layer. + return obj.layers + else: + return list(obj._flatten_layers(include_self=False, recursive=False)) # pylint: disable=protected-access + + +def list_all_layers_and_sublayers(obj): + s = set([obj]) + s.update(itertools.chain.from_iterable( + list_all_layers_and_sublayers(layer) for layer in list_all_layers(obj))) + return s + + +def maybe_add_training_arg( + original_call, wrapped_call, expects_training_arg, default_training_value): + """Decorate call and optionally adds training argument. + + If a layer expects a training argument, this function ensures that 'training' + is present in the layer args or kwonly args, with the default training value. + + Args: + original_call: Original call function. + wrapped_call: Wrapped call function. + expects_training_arg: Whether to include 'training' argument. + default_training_value: Default value of the training kwarg to include in + the arg spec. If `None`, the default is `K.learning_phase()`. + + Returns: + Tuple of ( + function that calls `wrapped_call` and sets the training arg, + Argspec of returned function or `None` if the argspec is unchanged) + """ + if not expects_training_arg: + return wrapped_call, None + def wrap_with_training_arg(*args, **kwargs): + """Wrap the `wrapped_call` function, and set training argument.""" + training_arg_index = get_training_arg_index(original_call) + training = get_training_arg(training_arg_index, args, kwargs) + if training is None: + training = default_training_value or K.learning_phase() + + args = list(args) + kwargs = kwargs.copy() + + def replace_training_and_call(training): + set_training_arg(training, training_arg_index, args, kwargs) + return wrapped_call(*args, **kwargs) + + return control_flow_util.smart_cond( + training, lambda: replace_training_and_call(True), + lambda: replace_training_and_call(False)) + + # Create arg spec for decorated function. If 'training' is not defined in the + # args of the original arg spec, then add it to kwonlyargs. + arg_spec = tf_inspect.getfullargspec(original_call) + defaults = list(arg_spec.defaults) if arg_spec.defaults is not None else [] + + kwonlyargs = arg_spec.kwonlyargs + kwonlydefaults = arg_spec.kwonlydefaults or {} + # Add training arg if it does not exist, or set the default training value. + if 'training' not in arg_spec.args: + kwonlyargs.append('training') + kwonlydefaults['training'] = default_training_value + else: + index = arg_spec.args.index('training') + training_default_index = len(arg_spec.args) - index + if (arg_spec.defaults and + len(arg_spec.defaults) >= training_default_index and + defaults[-training_default_index] is None): + defaults[-training_default_index] = default_training_value + + decorator_argspec = tf_inspect.FullArgSpec( + args=arg_spec.args, + varargs=arg_spec.varargs, + varkw=arg_spec.varkw, + defaults=defaults, + kwonlyargs=kwonlyargs, + kwonlydefaults=kwonlydefaults, + annotations=arg_spec.annotations) + return wrap_with_training_arg, decorator_argspec + + +def get_training_arg_index(call_fn): + """Returns the index of 'training' in the layer call function arguments. + + Args: + call_fn: Call function. + + Returns: + - n: index of 'training' in the call function arguments. + - -1: if 'training' is not found in the arguments, but layer.call accepts + variable keyword arguments + - None: if layer doesn't expect a training argument. + """ + argspec = tf_inspect.getfullargspec(call_fn) + if argspec.varargs: + # When there are variable args, training must be a keyword arg. + if 'training' in argspec.kwonlyargs or argspec.varkw: + return -1 + return None + else: + # Try to find 'training' in the list of args or kwargs. + arg_list = argspec.args + if tf_inspect.ismethod(call_fn): + arg_list = arg_list[1:] + + if 'training' in arg_list: + return arg_list.index('training') + elif 'training' in argspec.kwonlyargs or argspec.varkw: + return -1 + return None + + +def set_training_arg(training, index, args, kwargs): + if index is None or index < 0 or len(args) <= index: # index is invalid + kwargs['training'] = training + else: + args[index] = training + return args, kwargs + + +def get_training_arg(index, args, kwargs): + if index is None or index < 0 or len(args) <= index: # index is invalid + return kwargs.get('training', None) + else: + return args[index] + + +def remove_training_arg(index, args, kwargs): + if index is None or index < 0 or len(args) <= index: # index is invalid + kwargs.pop('training', None) + else: + args.pop(index) + + +class SaveOptionsContext(threading.local): + + def __init__(self): + super(SaveOptionsContext, self).__init__() + self.save_traces = True + + +_save_options_context = SaveOptionsContext() + + +@tf_contextlib.contextmanager +def keras_option_scope(save_traces): + previous_value = _save_options_context.save_traces + try: + _save_options_context.save_traces = save_traces + yield + finally: + _save_options_context.save_traces = previous_value + + +def should_save_traces(): + """Whether to trace layer functions-can be disabled in the save_traces arg.""" + return _save_options_context.save_traces + + +@tf_contextlib.contextmanager +def no_automatic_dependency_tracking_scope(obj): + """A context that disables automatic dependency tracking when assigning attrs. + + Objects that inherit from Autotrackable automatically creates dependencies + to trackable objects through attribute assignments, and wraps data structures + (lists or dicts) with trackable classes. This scope may be used to temporarily + disable this behavior. This works similar to the decorator + `no_automatic_dependency_tracking`. + + Example usage: + ``` + model = tf.keras.Model() + model.arr1 = [] # Creates a ListWrapper object + with no_automatic_dependency_tracking_scope(model): + model.arr2 = [] # Creates a regular, untracked python list + ``` + + Args: + obj: A trackable object. + + Yields: + a scope in which the object doesn't track dependencies. + """ + previous_value = getattr(obj, '_setattr_tracking', True) + obj._setattr_tracking = False # pylint: disable=protected-access + try: + yield + finally: + obj._setattr_tracking = previous_value # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model_experimental.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model_experimental.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0067274f8fcd5e297b40b1edbdf80a2927a0db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saved_model_experimental.py @@ -0,0 +1,466 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Deprecated experimental Keras SavedModel implementation.""" + +import os +import warnings +from tensorflow.python.checkpoint import graph_view +from tensorflow.python.client import session +from tensorflow.python.framework import ops +from tensorflow.python.keras import backend +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras.optimizer_v2 import optimizer_v2 +from tensorflow.python.keras.saving import model_config +from tensorflow.python.keras.saving import saving_utils +from tensorflow.python.keras.saving import utils_v1 as model_utils +from tensorflow.python.keras.utils import mode_keys +from tensorflow.python.keras.utils.generic_utils import LazyLoader +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import builder as saved_model_builder +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import save as save_lib +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.util import compat +from tensorflow.python.util import nest + +# To avoid circular dependencies between keras/engine and keras/saving, +# code in keras/saving must delay imports. + +# TODO(b/134426265): Switch back to single-quotes to match the rest of the file +# once the issue with copybara is fixed. +# pylint:disable=g-inconsistent-quotes +metrics_lib = LazyLoader("metrics_lib", globals(), + "tensorflow.python.keras.metrics") +models_lib = LazyLoader("models_lib", globals(), + "tensorflow.python.keras.models") +sequential = LazyLoader( + "sequential", globals(), + "tensorflow.python.keras.engine.sequential") +# pylint:enable=g-inconsistent-quotes + + +# File name for json format of SavedModel. +SAVED_MODEL_FILENAME_JSON = 'saved_model.json' + + +def export_saved_model(model, + saved_model_path, + custom_objects=None, + as_text=False, + input_signature=None, + serving_only=False): + """Exports a `tf.keras.Model` as a Tensorflow SavedModel. + + Note that at this time, subclassed models can only be saved using + `serving_only=True`. + + The exported `SavedModel` is a standalone serialization of Tensorflow objects, + and is supported by TF language APIs and the Tensorflow Serving system. + To load the model, use the function + `tf.keras.experimental.load_from_saved_model`. + + The `SavedModel` contains: + + 1. a checkpoint containing the model weights. + 2. a `SavedModel` proto containing the Tensorflow backend graph. Separate + graphs are saved for prediction (serving), train, and evaluation. If + the model has not been compiled, then only the graph computing predictions + will be exported. + 3. the model's json config. If the model is subclassed, this will only be + included if the model's `get_config()` method is overwritten. + + Example: + + ```python + import tensorflow as tf + + # Create a tf.keras model. + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(1, input_shape=[10])) + model.summary() + + # Save the tf.keras model in the SavedModel format. + path = '/tmp/simple_keras_model' + tf.keras.experimental.export_saved_model(model, path) + + # Load the saved keras model back. + new_model = tf.keras.experimental.load_from_saved_model(path) + new_model.summary() + ``` + + Args: + model: A `tf.keras.Model` to be saved. If the model is subclassed, the flag + `serving_only` must be set to True. + saved_model_path: a string specifying the path to the SavedModel directory. + custom_objects: Optional dictionary mapping string names to custom classes + or functions (e.g. custom loss functions). + as_text: bool, `False` by default. Whether to write the `SavedModel` proto + in text format. Currently unavailable in serving-only mode. + input_signature: A possibly nested sequence of `tf.TensorSpec` objects, used + to specify the expected model inputs. See `tf.function` for more details. + serving_only: bool, `False` by default. When this is true, only the + prediction graph is saved. + + Raises: + NotImplementedError: If the model is a subclassed model, and serving_only is + False. + ValueError: If the input signature cannot be inferred from the model. + AssertionError: If the SavedModel directory already exists and isn't empty. + """ + warnings.warn('`tf.keras.experimental.export_saved_model` is deprecated' + 'and will be removed in a future version. ' + 'Please use `model.save(..., save_format="tf")` or ' + '`tf.keras.models.save_model(..., save_format="tf")`.') + if serving_only: + save_lib.save( + model, + saved_model_path, + signatures=saving_utils.trace_model_call(model, input_signature)) + else: + _save_v1_format(model, saved_model_path, custom_objects, as_text, + input_signature) + + try: + _export_model_json(model, saved_model_path) + except NotImplementedError: + logging.warning('Skipped saving model JSON, subclassed model does not have ' + 'get_config() defined.') + + +def _export_model_json(model, saved_model_path): + """Saves model configuration as a json string under assets folder.""" + model_json = model.to_json() + model_json_filepath = os.path.join( + _get_or_create_assets_dir(saved_model_path), + compat.as_text(SAVED_MODEL_FILENAME_JSON)) + with gfile.Open(model_json_filepath, 'w') as f: + f.write(model_json) + + +def _export_model_variables(model, saved_model_path): + """Saves model weights in checkpoint format under variables folder.""" + _get_or_create_variables_dir(saved_model_path) + checkpoint_prefix = _get_variables_path(saved_model_path) + model.save_weights(checkpoint_prefix, save_format='tf', overwrite=True) + return checkpoint_prefix + + +def _save_v1_format(model, path, custom_objects, as_text, input_signature): + """Exports model to v1 SavedModel format.""" + if not model._is_graph_network: # pylint: disable=protected-access + if isinstance(model, sequential.Sequential): + # If input shape is not directly set in the model, the exported model + # will infer the expected shapes of the input from the model. + if not model.built: + raise ValueError('Weights for sequential model have not yet been ' + 'created. Weights are created when the Model is first ' + 'called on inputs or `build()` is called with an ' + '`input_shape`, or the first layer in the model has ' + '`input_shape` during construction.') + # TODO(kathywu): Build the model with input_signature to create the + # weights before _export_model_variables(). + else: + raise NotImplementedError( + 'Subclassed models can only be exported for serving. Please set ' + 'argument serving_only=True.') + + builder = saved_model_builder._SavedModelBuilder(path) # pylint: disable=protected-access + + # Manually save variables to export them in an object-based checkpoint. This + # skips the `builder.add_meta_graph_and_variables()` step, which saves a + # named-based checkpoint. + # TODO(b/113134168): Add fn to Builder to save with object-based saver. + # TODO(b/113178242): This should only export the model json structure. Only + # one save is needed once the weights can be copied from the model to clone. + checkpoint_path = _export_model_variables(model, path) + + # Export each mode. Use ModeKeys enums defined for `Estimator` to ensure that + # Keras models and `Estimator`s are exported with the same format. + # Every time a mode is exported, the code checks to see if new variables have + # been created (e.g. optimizer slot variables). If that is the case, the + # checkpoint is re-saved to include the new variables. + export_args = {'builder': builder, + 'model': model, + 'custom_objects': custom_objects, + 'checkpoint_path': checkpoint_path, + 'input_signature': input_signature} + + has_saved_vars = False + if model.optimizer: + if isinstance(model.optimizer, (optimizer_v1.TFOptimizer, + optimizer_v2.OptimizerV2)): + _export_mode(mode_keys.ModeKeys.TRAIN, has_saved_vars, **export_args) + has_saved_vars = True + _export_mode(mode_keys.ModeKeys.TEST, has_saved_vars, **export_args) + else: + logging.warning( + 'Model was compiled with an optimizer, but the optimizer is not from ' + '`tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving ' + 'graph was exported. The train and evaluate graphs were not added to ' + 'the SavedModel.') + _export_mode(mode_keys.ModeKeys.PREDICT, has_saved_vars, **export_args) + + builder.save(as_text) + + +def _get_var_list(model): + """Returns list of all checkpointed saveable objects in the model.""" + var_list, _, _ = graph_view.ObjectGraphView(model).serialize_object_graph() + return var_list + + +def create_placeholder(spec): + return backend.placeholder(shape=spec.shape, dtype=spec.dtype, name=spec.name) + + +def _export_mode( + mode, has_saved_vars, builder, model, custom_objects, checkpoint_path, + input_signature): + """Exports a model, and optionally saves new vars from the clone model. + + Args: + mode: A `tf.estimator.ModeKeys` string. + has_saved_vars: A `boolean` indicating whether the SavedModel has already + exported variables. + builder: A `SavedModelBuilder` object. + model: A `tf.keras.Model` object. + custom_objects: A dictionary mapping string names to custom classes + or functions. + checkpoint_path: String path to checkpoint. + input_signature: Nested TensorSpec containing the expected inputs. Can be + `None`, in which case the signature will be inferred from the model. + + Raises: + ValueError: If the train/eval mode is being exported, but the model does + not have an optimizer. + """ + compile_clone = (mode != mode_keys.ModeKeys.PREDICT) + if compile_clone and not model.optimizer: + raise ValueError( + 'Model does not have an optimizer. Cannot export mode %s' % mode) + + model_graph = ops.get_default_graph() + with ops.Graph().as_default() as g, backend.learning_phase_scope( + mode == mode_keys.ModeKeys.TRAIN): + + if input_signature is None: + input_tensors = None + else: + input_tensors = nest.map_structure(create_placeholder, input_signature) + + # Clone the model into blank graph. This will create placeholders for inputs + # and targets. + clone = models_lib.clone_and_build_model( + model, input_tensors=input_tensors, custom_objects=custom_objects, + compile_clone=compile_clone) + + # Make sure that iterations variable is added to the global step collection, + # to ensure that, when the SavedModel graph is loaded, the iterations + # variable is returned by `tf.compat.v1.train.get_global_step()`. This is + # required for compatibility with the SavedModelEstimator. + if compile_clone: + g.add_to_collection(ops.GraphKeys.GLOBAL_STEP, clone.optimizer.iterations) + + # Extract update and train ops from train/test/predict functions. + train_op = None + if mode == mode_keys.ModeKeys.TRAIN: + clone._make_train_function() # pylint: disable=protected-access + train_op = clone.train_function.updates_op + elif mode == mode_keys.ModeKeys.TEST: + clone._make_test_function() # pylint: disable=protected-access + else: + clone._make_predict_function() # pylint: disable=protected-access + g.get_collection_ref(ops.GraphKeys.UPDATE_OPS).extend(clone.state_updates) + + with session.Session().as_default(): + clone_var_list = _get_var_list(clone) + if has_saved_vars: + # Confirm all variables in the clone have an entry in the checkpoint. + status = clone.load_weights(checkpoint_path) + status.assert_existing_objects_matched() + else: + # Confirm that variables between the clone and model match up exactly, + # not counting optimizer objects. Optimizer objects are ignored because + # if the model has not trained, the slot variables will not have been + # created yet. + # TODO(b/113179535): Replace with trackable equivalence. + _assert_same_non_optimizer_objects(model, model_graph, clone, g) + + # TODO(b/113178242): Use value transfer for trackable objects. + clone.load_weights(checkpoint_path) + + # Add graph and variables to SavedModel. + # TODO(b/113134168): Switch to add_meta_graph_and_variables. + clone.save_weights(checkpoint_path, save_format='tf', overwrite=True) + builder._has_saved_variables = True # pylint: disable=protected-access + + # Add graph to the SavedModel builder. + builder.add_meta_graph( + model_utils.EXPORT_TAG_MAP[mode], + signature_def_map=_create_signature_def_map(clone, mode), + saver=saver_lib.Saver( + clone_var_list, + # Allow saving Models with no variables. This is somewhat odd, but + # it's not necessarily a bug. + allow_empty=True), + init_op=variables.local_variables_initializer(), + train_op=train_op) + return None + + +def _create_signature_def_map(model, mode): + """Creates a SignatureDef map from a Keras model.""" + inputs_dict = {name: x for name, x in zip(model.input_names, model.inputs)} + if model.optimizer: + targets_dict = {x.name.split(':')[0]: x + for x in model._targets if x is not None} # pylint: disable=protected-access + inputs_dict.update(targets_dict) + outputs_dict = {name: x + for name, x in zip(model.output_names, model.outputs)} + metrics = saving_utils.extract_model_metrics(model) + + # Add metric variables to the `LOCAL_VARIABLES` collection. Metric variables + # are by default not added to any collections. We are doing this here, so + # that metric variables get initialized. + local_vars = set(ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES)) + vars_to_add = set() + if metrics is not None: + for key, value in metrics.items(): + if isinstance(value, metrics_lib.Metric): + vars_to_add.update(value.variables) + # Convert Metric instances to (value_tensor, update_op) tuple. + metrics[key] = (value.result(), value.updates[0]) + # Remove variables that are in the local variables collection already. + vars_to_add = vars_to_add.difference(local_vars) + for v in vars_to_add: + ops.add_to_collection(ops.GraphKeys.LOCAL_VARIABLES, v) + + export_outputs = model_utils.export_outputs_for_mode( + mode, + predictions=outputs_dict, + loss=model.total_loss if model.optimizer else None, + metrics=metrics) + return model_utils.build_all_signature_defs( + inputs_dict, + export_outputs=export_outputs, + serving_only=(mode == mode_keys.ModeKeys.PREDICT)) + + +def _assert_same_non_optimizer_objects(model, model_graph, clone, clone_graph): # pylint: disable=unused-argument + """Asserts model and clone contain the same trackable objects.""" + + # TODO(fchollet, kathywu): make sure this works in eager mode. + return True + + +def load_from_saved_model(saved_model_path, custom_objects=None): + """Loads a keras Model from a SavedModel created by `export_saved_model()`. + + This function reinstantiates model state by: + 1) loading model topology from json (this will eventually come + from metagraph). + 2) loading model weights from checkpoint. + + Example: + + ```python + import tensorflow as tf + + # Create a tf.keras model. + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(1, input_shape=[10])) + model.summary() + + # Save the tf.keras model in the SavedModel format. + path = '/tmp/simple_keras_model' + tf.keras.experimental.export_saved_model(model, path) + + # Load the saved keras model back. + new_model = tf.keras.experimental.load_from_saved_model(path) + new_model.summary() + ``` + + Args: + saved_model_path: a string specifying the path to an existing SavedModel. + custom_objects: Optional dictionary mapping names + (strings) to custom classes or functions to be + considered during deserialization. + + Returns: + a keras.Model instance. + """ + warnings.warn('`tf.keras.experimental.load_from_saved_model` is deprecated' + 'and will be removed in a future version. ' + 'Please switch to `tf.keras.models.load_model`.') + # restore model topology from json string + model_json_filepath = os.path.join( + compat.as_bytes(saved_model_path), + compat.as_bytes(constants.ASSETS_DIRECTORY), + compat.as_bytes(SAVED_MODEL_FILENAME_JSON)) + with gfile.Open(model_json_filepath, 'r') as f: + model_json = f.read() + model = model_config.model_from_json( + model_json, custom_objects=custom_objects) + + # restore model weights + checkpoint_prefix = os.path.join( + compat.as_text(saved_model_path), + compat.as_text(constants.VARIABLES_DIRECTORY), + compat.as_text(constants.VARIABLES_FILENAME)) + model.load_weights(checkpoint_prefix) + return model + + +#### Directory / path helpers + + +def _get_or_create_variables_dir(export_dir): + """Return variables sub-directory, or create one if it doesn't exist.""" + variables_dir = _get_variables_dir(export_dir) + file_io.recursive_create_dir(variables_dir) + return variables_dir + + +def _get_variables_dir(export_dir): + """Return variables sub-directory in the SavedModel.""" + return os.path.join( + compat.as_text(export_dir), + compat.as_text(constants.VARIABLES_DIRECTORY)) + + +def _get_variables_path(export_dir): + """Return the variables path, used as the prefix for checkpoint files.""" + return os.path.join( + compat.as_text(_get_variables_dir(export_dir)), + compat.as_text(constants.VARIABLES_FILENAME)) + + +def _get_or_create_assets_dir(export_dir): + """Return assets sub-directory, or create one if it doesn't exist.""" + assets_destination_dir = _get_assets_dir(export_dir) + + file_io.recursive_create_dir(assets_destination_dir) + + return assets_destination_dir + + +def _get_assets_dir(export_dir): + """Return path to asset directory in the SavedModel.""" + return os.path.join( + compat.as_text(export_dir), + compat.as_text(constants.ASSETS_DIRECTORY)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saving_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saving_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ef86aa26ae99dc9abacc85c2560ac9dcda9858eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/saving_utils.py @@ -0,0 +1,326 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils related to keras model saving.""" + +import collections +import copy +import os + +from tensorflow.python.eager import def_function +from tensorflow.python.keras import backend as K +from tensorflow.python.keras import losses +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras import optimizers +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.io_utils import ask_to_proceed_with_overwrite +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest + + +def extract_model_metrics(model): + """Convert metrics from a Keras model `compile` API to dictionary. + + This is used for converting Keras models to Estimators and SavedModels. + + Args: + model: A `tf.keras.Model` object. + + Returns: + Dictionary mapping metric names to metric instances. May return `None` if + the model does not contain any metrics. + """ + if getattr(model, '_compile_metrics', None): + # TODO(psv/kathywu): use this implementation in model to estimator flow. + # We are not using model.metrics here because we want to exclude the metrics + # added using `add_metric` API. + return {m.name: m for m in model._compile_metric_functions} # pylint: disable=protected-access + return None + + +def model_input_signature(model, keep_original_batch_size=False): + """Inspect model to get its input signature. + + The model's input signature is a list with a single (possibly-nested) object. + This is due to the Keras-enforced restriction that tensor inputs must be + passed in as the first argument. + + For example, a model with input {'feature1': , 'feature2': } + will have input signature: [{'feature1': TensorSpec, 'feature2': TensorSpec}] + + Args: + model: Keras Model object. + keep_original_batch_size: A boolean indicating whether we want to keep using + the original batch size or set it to None. Default is `False`, which means + that the batch dim of the returned input signature will always be set to + `None`. + + Returns: + A list containing either a single TensorSpec or an object with nested + TensorSpecs. This list does not contain the `training` argument. + """ + input_specs = model._get_save_spec(dynamic_batch=not keep_original_batch_size) # pylint: disable=protected-access + if input_specs is None: + return None + input_specs = _enforce_names_consistency(input_specs) + # Return a list with a single element as the model's input signature. + if isinstance(input_specs, + collections.abc.Sequence) and len(input_specs) == 1: + # Note that the isinstance check filters out single-element dictionaries, + # which should also be wrapped as a single-element list. + return input_specs + else: + return [input_specs] + + +def raise_model_input_error(model): + raise ValueError( + 'Model {} cannot be saved because the input shapes have not been ' + 'set. Usually, input shapes are automatically determined from calling' + ' `.fit()` or `.predict()`. To manually set the shapes, call ' + '`model.build(input_shape)`.'.format(model)) + + +def trace_model_call(model, input_signature=None): + """Trace the model call to create a tf.function for exporting a Keras model. + + Args: + model: A Keras model. + input_signature: optional, a list of tf.TensorSpec objects specifying the + inputs to the model. + + Returns: + A tf.function wrapping the model's call function with input signatures set. + + Raises: + ValueError: if input signature cannot be inferred from the model. + """ + if input_signature is None: + if isinstance(model.call, def_function.Function): + input_signature = model.call.input_signature + + if input_signature is None: + input_signature = model_input_signature(model) + + if input_signature is None: + raise_model_input_error(model) + + @def_function.function(input_signature=input_signature) + def _wrapped_model(*args): + """A concrete tf.function that wraps the model's call function.""" + # When given a single input, Keras models will call the model on the tensor + # rather than a list consisting of the single tensor. + inputs = args[0] if len(input_signature) == 1 else list(args) + + with base_layer_utils.call_context().enter( + model, inputs=inputs, build_graph=False, training=False, saving=True): + outputs = model(inputs, training=False) + + # Outputs always has to be a flat dict. + output_names = model.output_names # Functional Model. + if output_names is None: # Subclassed Model. + from tensorflow.python.keras.engine import compile_utils # pylint: disable=g-import-not-at-top + output_names = compile_utils.create_pseudo_output_names(outputs) + outputs = nest.flatten(outputs) + return {name: output for name, output in zip(output_names, outputs)} + + return _wrapped_model + + +def model_metadata(model, include_optimizer=True, require_config=True): + """Returns a dictionary containing the model metadata.""" + from tensorflow.python.keras import __version__ as keras_version # pylint: disable=g-import-not-at-top + from tensorflow.python.keras.optimizer_v2 import optimizer_v2 # pylint: disable=g-import-not-at-top + + model_config = {'class_name': model.__class__.__name__} + try: + model_config['config'] = model.get_config() + except NotImplementedError as e: + if require_config: + raise e + + metadata = dict( + keras_version=str(keras_version), + backend=K.backend(), + model_config=model_config) + if model.optimizer and include_optimizer: + if isinstance(model.optimizer, optimizer_v1.TFOptimizer): + logging.warning( + 'TensorFlow optimizers do not ' + 'make it possible to access ' + 'optimizer attributes or optimizer state ' + 'after instantiation. ' + 'As a result, we cannot save the optimizer ' + 'as part of the model save file. ' + 'You will have to compile your model again after loading it. ' + 'Prefer using a Keras optimizer instead ' + '(see keras.io/optimizers).') + elif model._compile_was_called: # pylint: disable=protected-access + training_config = model._get_compile_args(user_metrics=False) # pylint: disable=protected-access + training_config.pop('optimizer', None) # Handled separately. + metadata['training_config'] = _serialize_nested_config(training_config) + if isinstance(model.optimizer, optimizer_v2.RestoredOptimizer): + raise NotImplementedError( + 'As of now, Optimizers loaded from SavedModel cannot be saved. ' + 'If you\'re calling `model.save` or `tf.keras.models.save_model`,' + ' please set the `include_optimizer` option to `False`. For ' + '`tf.saved_model.save`, delete the optimizer from the model.') + else: + optimizer_config = { + 'class_name': + generic_utils.get_registered_name(model.optimizer.__class__), + 'config': + model.optimizer.get_config() + } + metadata['training_config']['optimizer_config'] = optimizer_config + return metadata + + +def should_overwrite(filepath, overwrite): + """Returns whether the filepath should be overwritten.""" + # If file exists and should not be overwritten. + if not overwrite and os.path.isfile(filepath): + return ask_to_proceed_with_overwrite(filepath) + return True + + +def compile_args_from_training_config(training_config, custom_objects=None): + """Return model.compile arguments from training config.""" + if custom_objects is None: + custom_objects = {} + + with generic_utils.CustomObjectScope(custom_objects): + optimizer_config = training_config['optimizer_config'] + optimizer = optimizers.deserialize(optimizer_config) + + # Recover losses. + loss = None + loss_config = training_config.get('loss', None) + if loss_config is not None: + loss = _deserialize_nested_config(losses.deserialize, loss_config) + + # Recover metrics. + metrics = None + metrics_config = training_config.get('metrics', None) + if metrics_config is not None: + metrics = _deserialize_nested_config(_deserialize_metric, metrics_config) + + # Recover weighted metrics. + weighted_metrics = None + weighted_metrics_config = training_config.get('weighted_metrics', None) + if weighted_metrics_config is not None: + weighted_metrics = _deserialize_nested_config(_deserialize_metric, + weighted_metrics_config) + + sample_weight_mode = training_config['sample_weight_mode'] if hasattr( + training_config, 'sample_weight_mode') else None + loss_weights = training_config['loss_weights'] + + return dict( + optimizer=optimizer, + loss=loss, + metrics=metrics, + weighted_metrics=weighted_metrics, + loss_weights=loss_weights, + sample_weight_mode=sample_weight_mode) + + +def _deserialize_nested_config(deserialize_fn, config): + """Deserializes arbitrary Keras `config` using `deserialize_fn`.""" + + def _is_single_object(obj): + if isinstance(obj, dict) and 'class_name' in obj: + return True # Serialized Keras object. + if isinstance(obj, str): + return True # Serialized function or string. + return False + + if config is None: + return None + if _is_single_object(config): + return deserialize_fn(config) + elif isinstance(config, dict): + return { + k: _deserialize_nested_config(deserialize_fn, v) + for k, v in config.items() + } + elif isinstance(config, (tuple, list)): + return [_deserialize_nested_config(deserialize_fn, obj) for obj in config] + + raise ValueError('Saved configuration not understood.') + + +def _serialize_nested_config(config): + """Serialized a nested structure of Keras objects.""" + + def _serialize_fn(obj): + if callable(obj): + return generic_utils.serialize_keras_object(obj) + return obj + + return nest.map_structure(_serialize_fn, config) + + +def _deserialize_metric(metric_config): + """Deserialize metrics, leaving special strings untouched.""" + from tensorflow.python.keras import metrics as metrics_module # pylint:disable=g-import-not-at-top + if metric_config in ['accuracy', 'acc', 'crossentropy', 'ce']: + # Do not deserialize accuracy and cross-entropy strings as we have special + # case handling for these in compile, based on model output shape. + return metric_config + return metrics_module.deserialize(metric_config) + + +def _enforce_names_consistency(specs): + """Enforces that either all specs have names or none do.""" + + def _has_name(spec): + return hasattr(spec, 'name') and spec.name is not None + + def _clear_name(spec): + spec = copy.deepcopy(spec) + if hasattr(spec, 'name'): + spec._name = None # pylint:disable=protected-access + return spec + + flat_specs = nest.flatten(specs) + name_inconsistency = ( + any(_has_name(s) for s in flat_specs) and + not all(_has_name(s) for s in flat_specs)) + + if name_inconsistency: + specs = nest.map_structure(_clear_name, specs) + return specs + + +def try_build_compiled_arguments(model): + if (not version_utils.is_v1_layer_or_model(model) and + model.outputs is not None): + try: + if not model.compiled_loss.built: + model.compiled_loss.build(model.outputs) + if not model.compiled_metrics.built: + model.compiled_metrics.build(model.outputs, model.outputs) + except: # pylint: disable=bare-except + logging.warning( + 'Compiled the loaded model, but the compiled metrics have yet to ' + 'be built. `model.compile_metrics` will be empty until you train ' + 'or evaluate the model.') + + +def is_hdf5_filepath(filepath): + return (filepath.endswith('.h5') or filepath.endswith('.keras') or + filepath.endswith('.hdf5')) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63128a7374a6cf17f862301960216029836c22bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Utils for saving a Keras Model or Estimator to the SavedModel format.""" +# pylint: disable=wildcard-import +from tensorflow.python.keras.saving.utils_v1.export_output import * +from tensorflow.python.keras.saving.utils_v1.export_utils import build_all_signature_defs +from tensorflow.python.keras.saving.utils_v1.export_utils import export_outputs_for_mode +from tensorflow.python.keras.saving.utils_v1.export_utils import EXPORT_TAG_MAP +from tensorflow.python.keras.saving.utils_v1.export_utils import get_export_outputs +from tensorflow.python.keras.saving.utils_v1.export_utils import get_temp_export_dir +from tensorflow.python.keras.saving.utils_v1.export_utils import get_timestamped_export_dir +from tensorflow.python.keras.saving.utils_v1.export_utils import SIGNATURE_KEY_MAP +# pylint: enable=wildcard-import +# LINT.ThenChange(//tensorflow/python/saved_model/model_utils/__init__.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_output.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_output.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad09a95a2cc9abfcf02a2466150227bd4380e55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_output.py @@ -0,0 +1,405 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Classes for different types of export output.""" + +import abc + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras.saving.utils_v1 import signature_def_utils as unexported_signature_utils +from tensorflow.python.saved_model import signature_def_utils + + +class ExportOutput(object): + """Represents an output of a model that can be served. + + These typically correspond to model heads. + """ + + __metaclass__ = abc.ABCMeta + + _SEPARATOR_CHAR = '/' + + @abc.abstractmethod + def as_signature_def(self, receiver_tensors): + """Generate a SignatureDef proto for inclusion in a MetaGraphDef. + + The SignatureDef will specify outputs as described in this ExportOutput, + and will use the provided receiver_tensors as inputs. + + Args: + receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying + input nodes that will be fed. + """ + pass + + def _check_output_key(self, key, error_label): + # For multi-head models, the key can be a tuple. + if isinstance(key, tuple): + key = self._SEPARATOR_CHAR.join(key) + + if not isinstance(key, str): + raise ValueError( + '{} output key must be a string; got {}.'.format(error_label, key)) + return key + + def _wrap_and_check_outputs( + self, outputs, single_output_default_name, error_label=None): + """Wraps raw tensors as dicts and checks type. + + Note that we create a new dict here so that we can overwrite the keys + if necessary. + + Args: + outputs: A `Tensor` or a dict of string to `Tensor`. + single_output_default_name: A string key for use in the output dict + if the provided `outputs` is a raw tensor. + error_label: descriptive string for use in error messages. If none, + single_output_default_name will be used. + + Returns: + A dict of tensors + + Raises: + ValueError: if the outputs dict keys are not strings or tuples of strings + or the values are not Tensors. + """ + if not isinstance(outputs, dict): + outputs = {single_output_default_name: outputs} + + output_dict = {} + for key, value in outputs.items(): + error_name = error_label or single_output_default_name + key = self._check_output_key(key, error_name) + if not isinstance(value, tensor.Tensor): + raise ValueError( + '{} output value must be a Tensor; got {}.'.format( + error_name, value)) + + output_dict[key] = value + return output_dict + + +class ClassificationOutput(ExportOutput): + """Represents the output of a classification head. + + Either classes or scores or both must be set. + + The classes `Tensor` must provide string labels, not integer class IDs. + + If only classes is set, it is interpreted as providing top-k results in + descending order. + + If only scores is set, it is interpreted as providing a score for every class + in order of class ID. + + If both classes and scores are set, they are interpreted as zipped, so each + score corresponds to the class at the same index. Clients should not depend + on the order of the entries. + """ + + def __init__(self, scores=None, classes=None): + """Constructor for `ClassificationOutput`. + + Args: + scores: A float `Tensor` giving scores (sometimes but not always + interpretable as probabilities) for each class. May be `None`, but + only if `classes` is set. Interpretation varies-- see class doc. + classes: A string `Tensor` giving predicted class labels. May be `None`, + but only if `scores` is set. Interpretation varies-- see class doc. + + Raises: + ValueError: if neither classes nor scores is set, or one of them is not a + `Tensor` with the correct dtype. + """ + if (scores is not None + and not (isinstance(scores, tensor.Tensor) + and scores.dtype.is_floating)): + raise ValueError('Classification scores must be a float32 Tensor; ' + 'got {}'.format(scores)) + if (classes is not None + and not (isinstance(classes, tensor.Tensor) + and dtypes.as_dtype(classes.dtype) == dtypes.string)): + raise ValueError('Classification classes must be a string Tensor; ' + 'got {}'.format(classes)) + if scores is None and classes is None: + raise ValueError('At least one of scores and classes must be set.') + + self._scores = scores + self._classes = classes + + @property + def scores(self): + return self._scores + + @property + def classes(self): + return self._classes + + def as_signature_def(self, receiver_tensors): + if len(receiver_tensors) != 1: + raise ValueError('Classification input must be a single string Tensor; ' + 'got {}'.format(receiver_tensors)) + (_, examples), = receiver_tensors.items() + if dtypes.as_dtype(examples.dtype) != dtypes.string: + raise ValueError('Classification input must be a single string Tensor; ' + 'got {}'.format(receiver_tensors)) + return signature_def_utils.classification_signature_def( + examples, self.classes, self.scores) + + +class RegressionOutput(ExportOutput): + """Represents the output of a regression head.""" + + def __init__(self, value): + """Constructor for `RegressionOutput`. + + Args: + value: a float `Tensor` giving the predicted values. Required. + + Raises: + ValueError: if the value is not a `Tensor` with dtype tf.float32. + """ + if not (isinstance(value, tensor.Tensor) and value.dtype.is_floating): + raise ValueError('Regression output value must be a float32 Tensor; ' + 'got {}'.format(value)) + self._value = value + + @property + def value(self): + return self._value + + def as_signature_def(self, receiver_tensors): + if len(receiver_tensors) != 1: + raise ValueError('Regression input must be a single string Tensor; ' + 'got {}'.format(receiver_tensors)) + (_, examples), = receiver_tensors.items() + if dtypes.as_dtype(examples.dtype) != dtypes.string: + raise ValueError('Regression input must be a single string Tensor; ' + 'got {}'.format(receiver_tensors)) + return signature_def_utils.regression_signature_def(examples, self.value) + + +class PredictOutput(ExportOutput): + """Represents the output of a generic prediction head. + + A generic prediction need not be either a classification or a regression. + + Named outputs must be provided as a dict from string to `Tensor`, + """ + _SINGLE_OUTPUT_DEFAULT_NAME = 'output' + + def __init__(self, outputs): + """Constructor for PredictOutput. + + Args: + outputs: A `Tensor` or a dict of string to `Tensor` representing the + predictions. + + Raises: + ValueError: if the outputs is not dict, or any of its keys are not + strings, or any of its values are not `Tensor`s. + """ + + self._outputs = self._wrap_and_check_outputs( + outputs, self._SINGLE_OUTPUT_DEFAULT_NAME, error_label='Prediction') + + @property + def outputs(self): + return self._outputs + + def as_signature_def(self, receiver_tensors): + return signature_def_utils.predict_signature_def(receiver_tensors, + self.outputs) + + +class _SupervisedOutput(ExportOutput): + """Represents the output of a supervised training or eval process.""" + __metaclass__ = abc.ABCMeta + + LOSS_NAME = 'loss' + PREDICTIONS_NAME = 'predictions' + METRICS_NAME = 'metrics' + + METRIC_VALUE_SUFFIX = 'value' + METRIC_UPDATE_SUFFIX = 'update_op' + + _loss = None + _predictions = None + _metrics = None + + def __init__(self, loss=None, predictions=None, metrics=None): + """Constructor for SupervisedOutput (ie, Train or Eval output). + + Args: + loss: dict of Tensors or single Tensor representing calculated loss. + predictions: dict of Tensors or single Tensor representing model + predictions. + metrics: Dict of metric results keyed by name. + The values of the dict can be one of the following: + (1) instance of `Metric` class. + (2) (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op. + + Raises: + ValueError: if any of the outputs' dict keys are not strings or tuples of + strings or the values are not Tensors (or Operations in the case of + update_op). + """ + + if loss is not None: + loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME) + self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME) + if predictions is not None: + pred_dict = self._wrap_and_check_outputs( + predictions, self.PREDICTIONS_NAME) + self._predictions = self._prefix_output_keys( + pred_dict, self.PREDICTIONS_NAME) + if metrics is not None: + self._metrics = self._wrap_and_check_metrics(metrics) + + def _prefix_output_keys(self, output_dict, output_name): + """Prepend output_name to the output_dict keys if it doesn't exist. + + This produces predictable prefixes for the pre-determined outputs + of SupervisedOutput. + + Args: + output_dict: dict of string to Tensor, assumed valid. + output_name: prefix string to prepend to existing keys. + + Returns: + dict with updated keys and existing values. + """ + + new_outputs = {} + for key, val in output_dict.items(): + key = self._prefix_key(key, output_name) + new_outputs[key] = val + return new_outputs + + def _prefix_key(self, key, output_name): + if key.find(output_name) != 0: + key = output_name + self._SEPARATOR_CHAR + key + return key + + def _wrap_and_check_metrics(self, metrics): + """Handle the saving of metrics. + + Metrics is either a tuple of (value, update_op), or a dict of such tuples. + Here, we separate out the tuples and create a dict with names to tensors. + + Args: + metrics: Dict of metric results keyed by name. + The values of the dict can be one of the following: + (1) instance of `Metric` class. + (2) (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op. + + Returns: + dict of output_names to tensors + + Raises: + ValueError: if the dict key is not a string, or the metric values or ops + are not tensors. + """ + if not isinstance(metrics, dict): + metrics = {self.METRICS_NAME: metrics} + + outputs = {} + for key, value in metrics.items(): + if isinstance(value, tuple): + metric_val, metric_op = value + else: # value is a keras.Metrics object + metric_val = value.result() + assert len(value.updates) == 1 # We expect only one update op. + metric_op = value.updates[0] + key = self._check_output_key(key, self.METRICS_NAME) + key = self._prefix_key(key, self.METRICS_NAME) + + val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX + op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX + if not isinstance(metric_val, tensor.Tensor): + raise ValueError( + '{} output value must be a Tensor; got {}.'.format( + key, metric_val)) + if not (tensor_util.is_tensor(metric_op) or + isinstance(metric_op, ops.Operation)): + raise ValueError( + '{} update_op must be a Tensor or Operation; got {}.'.format( + key, metric_op)) + + # We must wrap any ops (or variables) in a Tensor before export, as the + # SignatureDef proto expects tensors only. See b/109740581 + metric_op_tensor = metric_op + if not isinstance(metric_op, tensor.Tensor): + with ops.control_dependencies([metric_op]): + metric_op_tensor = constant_op.constant([], name='metric_op_wrapper') + + outputs[val_name] = metric_val + outputs[op_name] = metric_op_tensor + + return outputs + + @property + def loss(self): + return self._loss + + @property + def predictions(self): + return self._predictions + + @property + def metrics(self): + return self._metrics + + @abc.abstractmethod + def _get_signature_def_fn(self): + """Returns a function that produces a SignatureDef given desired outputs.""" + pass + + def as_signature_def(self, receiver_tensors): + signature_def_fn = self._get_signature_def_fn() + return signature_def_fn( + receiver_tensors, self.loss, self.predictions, self.metrics) + + +class TrainOutput(_SupervisedOutput): + """Represents the output of a supervised training process. + + This class generates the appropriate signature def for exporting + training output by type-checking and wrapping loss, predictions, and metrics + values. + """ + + def _get_signature_def_fn(self): + return unexported_signature_utils.supervised_train_signature_def + + +class EvalOutput(_SupervisedOutput): + """Represents the output of a supervised eval process. + + This class generates the appropriate signature def for exporting + eval output by type-checking and wrapping loss, predictions, and metrics + values. + """ + + def _get_signature_def_fn(self): + return unexported_signature_utils.supervised_eval_signature_def +# LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_output.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4688e88c22b8ad6107e1463f3929a3ce0b43bee4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/export_utils.py @@ -0,0 +1,358 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Utilities for creating SavedModels.""" + +import collections +import os +import time + +from tensorflow.python.keras.saving.utils_v1 import export_output as export_output_lib +from tensorflow.python.keras.saving.utils_v1 import mode_keys +from tensorflow.python.keras.saving.utils_v1 import unexported_constants +from tensorflow.python.keras.saving.utils_v1.mode_keys import KerasModeKeys as ModeKeys +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.util import compat + + +# Mapping of the modes to appropriate MetaGraph tags in the SavedModel. +EXPORT_TAG_MAP = mode_keys.ModeKeyMap(**{ + ModeKeys.PREDICT: [tag_constants.SERVING], + ModeKeys.TRAIN: [tag_constants.TRAINING], + ModeKeys.TEST: [unexported_constants.EVAL]}) + +# For every exported mode, a SignatureDef map should be created using the +# functions `export_outputs_for_mode` and `build_all_signature_defs`. By +# default, this map will contain a single Signature that defines the input +# tensors and output predictions, losses, and/or metrics (depending on the mode) +# The default keys used in the SignatureDef map are defined below. +SIGNATURE_KEY_MAP = mode_keys.ModeKeyMap(**{ + ModeKeys.PREDICT: signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, + ModeKeys.TRAIN: unexported_constants.DEFAULT_TRAIN_SIGNATURE_DEF_KEY, + ModeKeys.TEST: unexported_constants.DEFAULT_EVAL_SIGNATURE_DEF_KEY}) + +# Default names used in the SignatureDef input map, which maps strings to +# TensorInfo protos. +SINGLE_FEATURE_DEFAULT_NAME = 'feature' +SINGLE_RECEIVER_DEFAULT_NAME = 'input' +SINGLE_LABEL_DEFAULT_NAME = 'label' + +### Below utilities are specific to SavedModel exports. + + +def build_all_signature_defs(receiver_tensors, + export_outputs, + receiver_tensors_alternatives=None, + serving_only=True): + """Build `SignatureDef`s for all export outputs. + + Args: + receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying + input nodes where this receiver expects to be fed by default. Typically, + this is a single placeholder expecting serialized `tf.Example` protos. + export_outputs: a dict of ExportOutput instances, each of which has + an as_signature_def instance method that will be called to retrieve + the signature_def for all export output tensors. + receiver_tensors_alternatives: a dict of string to additional + groups of receiver tensors, each of which may be a `Tensor` or a dict of + string to `Tensor`. These named receiver tensor alternatives generate + additional serving signatures, which may be used to feed inputs at + different points within the input receiver subgraph. A typical usage is + to allow feeding raw feature `Tensor`s *downstream* of the + tf.io.parse_example() op. Defaults to None. + serving_only: boolean; if true, resulting signature defs will only include + valid serving signatures. If false, all requested signatures will be + returned. + + Returns: + signature_def representing all passed args. + + Raises: + ValueError: if export_outputs is not a dict + """ + if not isinstance(receiver_tensors, dict): + receiver_tensors = {SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors} + if export_outputs is None or not isinstance(export_outputs, dict): + raise ValueError('export_outputs must be a dict and not' + '{}'.format(type(export_outputs))) + + signature_def_map = {} + excluded_signatures = {} + for output_key, export_output in export_outputs.items(): + signature_name = '{}'.format(output_key or 'None') + try: + signature = export_output.as_signature_def(receiver_tensors) + signature_def_map[signature_name] = signature + except ValueError as e: + excluded_signatures[signature_name] = str(e) + + if receiver_tensors_alternatives: + for receiver_name, receiver_tensors_alt in ( + receiver_tensors_alternatives.items()): + if not isinstance(receiver_tensors_alt, dict): + receiver_tensors_alt = { + SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors_alt + } + for output_key, export_output in export_outputs.items(): + signature_name = '{}:{}'.format(receiver_name or 'None', output_key or + 'None') + try: + signature = export_output.as_signature_def(receiver_tensors_alt) + signature_def_map[signature_name] = signature + except ValueError as e: + excluded_signatures[signature_name] = str(e) + + _log_signature_report(signature_def_map, excluded_signatures) + + # The above calls to export_output_lib.as_signature_def should return only + # valid signatures; if there is a validity problem, they raise a ValueError, + # in which case we exclude that signature from signature_def_map above. + # The is_valid_signature check ensures that the signatures produced are + # valid for serving, and acts as an additional sanity check for export + # signatures produced for serving. We skip this check for training and eval + # signatures, which are not intended for serving. + if serving_only: + signature_def_map = { + k: v + for k, v in signature_def_map.items() + if signature_def_utils.is_valid_signature(v) + } + return signature_def_map + + +_FRIENDLY_METHOD_NAMES = { + signature_constants.CLASSIFY_METHOD_NAME: 'Classify', + signature_constants.REGRESS_METHOD_NAME: 'Regress', + signature_constants.PREDICT_METHOD_NAME: 'Predict', + unexported_constants.SUPERVISED_TRAIN_METHOD_NAME: 'Train', + unexported_constants.SUPERVISED_EVAL_METHOD_NAME: 'Eval', +} + + +def _log_signature_report(signature_def_map, excluded_signatures): + """Log a report of which signatures were produced.""" + sig_names_by_method_name = collections.defaultdict(list) + + # We'll collect whatever method_names are present, but also we want to make + # sure to output a line for each of the three standard methods even if they + # have no signatures. + for method_name in _FRIENDLY_METHOD_NAMES: + sig_names_by_method_name[method_name] = [] + + for signature_name, sig in signature_def_map.items(): + sig_names_by_method_name[sig.method_name].append(signature_name) + + # TODO(b/67733540): consider printing the full signatures, not just names + for method_name, sig_names in sig_names_by_method_name.items(): + if method_name in _FRIENDLY_METHOD_NAMES: + method_name = _FRIENDLY_METHOD_NAMES[method_name] + logging.info('Signatures INCLUDED in export for {}: {}'.format( + method_name, sig_names if sig_names else 'None')) + + if excluded_signatures: + logging.info('Signatures EXCLUDED from export because they cannot be ' + 'be served via TensorFlow Serving APIs:') + for signature_name, message in excluded_signatures.items(): + logging.info('\'{}\' : {}'.format(signature_name, message)) + + if not signature_def_map: + logging.warning('Export includes no signatures!') + elif (signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in + signature_def_map): + logging.warning('Export includes no default signature!') + + +# When we create a timestamped directory, there is a small chance that the +# directory already exists because another process is also creating these +# directories. In this case we just wait one second to get a new timestamp and +# try again. If this fails several times in a row, then something is seriously +# wrong. +MAX_DIRECTORY_CREATION_ATTEMPTS = 10 + + +def get_timestamped_export_dir(export_dir_base): + """Builds a path to a new subdirectory within the base directory. + + Each export is written into a new subdirectory named using the + current time. This guarantees monotonically increasing version + numbers even across multiple runs of the pipeline. + The timestamp used is the number of seconds since epoch UTC. + + Args: + export_dir_base: A string containing a directory to write the exported + graph and checkpoints. + Returns: + The full path of the new subdirectory (which is not actually created yet). + + Raises: + RuntimeError: if repeated attempts fail to obtain a unique timestamped + directory name. + """ + attempts = 0 + while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS: + timestamp = int(time.time()) + + result_dir = os.path.join( + compat.as_bytes(export_dir_base), compat.as_bytes(str(timestamp))) + if not gfile.Exists(result_dir): + # Collisions are still possible (though extremely unlikely): this + # directory is not actually created yet, but it will be almost + # instantly on return from this function. + return result_dir + time.sleep(1) + attempts += 1 + logging.warning( + 'Directory {} already exists; retrying (attempt {}/{})'.format( + compat.as_str(result_dir), attempts, + MAX_DIRECTORY_CREATION_ATTEMPTS)) + raise RuntimeError('Failed to obtain a unique export directory name after ' + '{} attempts.'.format(MAX_DIRECTORY_CREATION_ATTEMPTS)) + + +def get_temp_export_dir(timestamped_export_dir): + """Builds a directory name based on the argument but starting with 'temp-'. + + This relies on the fact that TensorFlow Serving ignores subdirectories of + the base directory that can't be parsed as integers. + + Args: + timestamped_export_dir: the name of the eventual export directory, e.g. + /foo/bar/ + + Returns: + A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-. + """ + (dirname, basename) = os.path.split(timestamped_export_dir) + if isinstance(basename, bytes): + str_name = basename.decode('utf-8') + else: + str_name = str(basename) + temp_export_dir = os.path.join( + compat.as_bytes(dirname), + compat.as_bytes('temp-{}'.format(str_name))) + return temp_export_dir + + +def export_outputs_for_mode( + mode, serving_export_outputs=None, predictions=None, loss=None, + metrics=None): + """Util function for constructing a `ExportOutput` dict given a mode. + + The returned dict can be directly passed to `build_all_signature_defs` helper + function as the `export_outputs` argument, used for generating a SignatureDef + map. + + Args: + mode: A `ModeKeys` specifying the mode. + serving_export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict or None. + predictions: A dict of Tensors or single Tensor representing model + predictions. This argument is only used if serving_export_outputs is not + set. + loss: A dict of Tensors or single Tensor representing calculated loss. + metrics: A dict of (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op + + Returns: + Dictionary mapping the a key to an `tf.estimator.export.ExportOutput` object + The key is the expected SignatureDef key for the mode. + + Raises: + ValueError: if an appropriate ExportOutput cannot be found for the mode. + """ + if mode not in SIGNATURE_KEY_MAP: + raise ValueError( + 'Export output type not found for mode: {}. Expected one of: {}.\n' + 'One likely error is that V1 Estimator Modekeys were somehow passed to ' + 'this function. Please ensure that you are using the new ModeKeys.' + .format(mode, SIGNATURE_KEY_MAP.keys())) + signature_key = SIGNATURE_KEY_MAP[mode] + if mode_keys.is_predict(mode): + return get_export_outputs(serving_export_outputs, predictions) + elif mode_keys.is_train(mode): + return {signature_key: export_output_lib.TrainOutput( + loss=loss, predictions=predictions, metrics=metrics)} + else: + return {signature_key: export_output_lib.EvalOutput( + loss=loss, predictions=predictions, metrics=metrics)} + + +def get_export_outputs(export_outputs, predictions): + """Validate export_outputs or create default export_outputs. + + Args: + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict or None. + predictions: Predictions `Tensor` or dict of `Tensor`. + + Returns: + Valid export_outputs dict + + Raises: + TypeError: if export_outputs is not a dict or its values are not + ExportOutput instances. + """ + if export_outputs is None: + default_output = export_output_lib.PredictOutput(predictions) + export_outputs = { + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: default_output} + + if not isinstance(export_outputs, dict): + raise TypeError('export_outputs must be dict, given: {}'.format( + export_outputs)) + for v in export_outputs.values(): + if not isinstance(v, export_output_lib.ExportOutput): + raise TypeError( + 'Values in export_outputs must be ExportOutput objects. ' + 'Given: {}'.format(export_outputs)) + + _maybe_add_default_serving_output(export_outputs) + + return export_outputs + + +def _maybe_add_default_serving_output(export_outputs): + """Add a default serving output to the export_outputs if not present. + + Args: + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict. + + Returns: + export_outputs dict with default serving signature added if necessary + + Raises: + ValueError: if multiple export_outputs were provided without a default + serving key. + """ + if len(export_outputs) == 1: + (key, value), = export_outputs.items() + if key != signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: + export_outputs[ + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = value + if len(export_outputs) > 1: + if (signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + not in export_outputs): + raise ValueError( + 'Multiple export_outputs were provided, but none of them is ' + 'specified as the default. Do this by naming one of them with ' + 'signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY.') + + return export_outputs +# LINT.ThenChange(//tensorflow/python/saved_model/model_utils/export_utils.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/mode_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/mode_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..d777cc56296215c90b08c65fecfae53da5d105a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/mode_keys.py @@ -0,0 +1,107 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Utils for managing different mode strings used by Keras and Estimator models. +""" + +import collections + + +class KerasModeKeys: + """Standard names for model modes. + + The following standard keys are defined: + + * `TRAIN`: training/fitting mode. + * `TEST`: testing/evaluation mode. + * `PREDICT`: prediction/inference mode. + """ + + TRAIN = 'train' + TEST = 'test' + PREDICT = 'predict' + + +# TODO(kathywu): Remove copy in Estimator after nightlies +class EstimatorModeKeys: + """Standard names for Estimator model modes. + + The following standard keys are defined: + + * `TRAIN`: training/fitting mode. + * `EVAL`: testing/evaluation mode. + * `PREDICT`: predication/inference mode. + """ + + TRAIN = 'train' + EVAL = 'eval' + PREDICT = 'infer' + + +def is_predict(mode): + return mode in [KerasModeKeys.PREDICT, EstimatorModeKeys.PREDICT] + + +def is_eval(mode): + return mode in [KerasModeKeys.TEST, EstimatorModeKeys.EVAL] + + +def is_train(mode): + return mode in [KerasModeKeys.TRAIN, EstimatorModeKeys.TRAIN] + + +class ModeKeyMap(collections.abc.Mapping): + """Map using ModeKeys as keys. + + This class creates an immutable mapping from modes to values. For example, + SavedModel export of Keras and Estimator models use this to map modes to their + corresponding MetaGraph tags/SignatureDef keys. + + Since this class uses modes, rather than strings, as keys, both "predict" + (Keras's PREDICT ModeKey) and "infer" (Estimator's PREDICT ModeKey) map to the + same value. + """ + + def __init__(self, **kwargs): + self._internal_dict = {} + self._keys = [] + for key in kwargs: + self._keys.append(key) + dict_key = self._get_internal_key(key) + if dict_key in self._internal_dict: + raise ValueError( + 'Error creating ModeKeyMap. Multiple keys/values found for {} mode.' + .format(dict_key)) + self._internal_dict[dict_key] = kwargs[key] + + def _get_internal_key(self, key): + """Return keys used for the internal dictionary.""" + if is_train(key): + return KerasModeKeys.TRAIN + if is_eval(key): + return KerasModeKeys.TEST + if is_predict(key): + return KerasModeKeys.PREDICT + raise ValueError('Invalid mode key: {}.'.format(key)) + + def __getitem__(self, key): + return self._internal_dict[self._get_internal_key(key)] + + def __iter__(self): + return iter(self._keys) + + def __len__(self): + return len(self._keys) +# LINT.ThenChange(//tensorflow/python/saved_model/model_utils/mode_keys.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/signature_def_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/signature_def_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0712f4a0eebe61ef8661c913e05bbacbc0f9bd56 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/signature_def_utils.py @@ -0,0 +1,77 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SignatureDef utility functions implementation.""" + +from tensorflow.python.keras.saving.utils_v1 import unexported_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import utils_impl as utils + + +# LINT.IfChange +def supervised_train_signature_def( + inputs, loss, predictions=None, metrics=None): + return _supervised_signature_def( + unexported_constants.SUPERVISED_TRAIN_METHOD_NAME, inputs, loss=loss, + predictions=predictions, metrics=metrics) + + +def supervised_eval_signature_def( + inputs, loss, predictions=None, metrics=None): + return _supervised_signature_def( + unexported_constants.SUPERVISED_EVAL_METHOD_NAME, inputs, loss=loss, + predictions=predictions, metrics=metrics) + + +def _supervised_signature_def( + method_name, inputs, loss=None, predictions=None, + metrics=None): + """Creates a signature for training and eval data. + + This function produces signatures that describe the inputs and outputs + of a supervised process, such as training or evaluation, that + results in loss, metrics, and the like. Note that this function only requires + inputs to be not None. + + Args: + method_name: Method name of the SignatureDef as a string. + inputs: dict of string to `Tensor`. + loss: dict of string to `Tensor` representing computed loss. + predictions: dict of string to `Tensor` representing the output predictions. + metrics: dict of string to `Tensor` representing metric ops. + + Returns: + A train- or eval-flavored signature_def. + + Raises: + ValueError: If inputs or outputs is `None`. + """ + if inputs is None or not inputs: + raise ValueError('{} inputs cannot be None or empty.'.format(method_name)) + + signature_inputs = {key: utils.build_tensor_info(tensor) + for key, tensor in inputs.items()} + + signature_outputs = {} + for output_set in (loss, predictions, metrics): + if output_set is not None: + sig_out = {key: utils.build_tensor_info(tensor) + for key, tensor in output_set.items()} + signature_outputs.update(sig_out) + + signature_def = signature_def_utils.build_signature_def( + signature_inputs, signature_outputs, method_name) + + return signature_def +# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/signature_def_utils.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/unexported_constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/unexported_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..9936f095df88a35c173fd5710632b17bb38b177c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/saving/utils_v1/unexported_constants.py @@ -0,0 +1,32 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Signature constants for SavedModel save and restore operations. + +These are the private constants that have not been exported. +""" + +# LINT.IfChange +DEFAULT_TRAIN_SIGNATURE_DEF_KEY = "train" + +DEFAULT_EVAL_SIGNATURE_DEF_KEY = "eval" + +SUPERVISED_TRAIN_METHOD_NAME = "tensorflow/supervised/training" + +SUPERVISED_EVAL_METHOD_NAME = "tensorflow/supervised/eval" +# LINT.ThenChange(//tensorflow/python/saved_model/signature_constants.py) + +# LINT.IfChange +EVAL = "eval" +# LINT.ThenChange(//tensorflow/python/saved_model/tag_constants.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/testing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/testing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e973da964c8215e5102e30d5e5e9ef635dc7edf2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/testing_utils.py @@ -0,0 +1,1089 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for unit-testing Keras.""" + +import collections +import contextlib +import functools +import itertools +import threading + +import numpy as np + +from tensorflow.python import tf2 +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import test_util +from tensorflow.python.keras import backend +from tensorflow.python.keras import layers +from tensorflow.python.keras import models +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.optimizer_v2 import adadelta as adadelta_v2 +from tensorflow.python.keras.optimizer_v2 import adagrad as adagrad_v2 +from tensorflow.python.keras.optimizer_v2 import adam as adam_v2 +from tensorflow.python.keras.optimizer_v2 import adamax as adamax_v2 +from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_v2 +from tensorflow.python.keras.optimizer_v2 import nadam as nadam_v2 +from tensorflow.python.keras.optimizer_v2 import rmsprop as rmsprop_v2 +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.util import tf_decorator + + +def string_test(actual, expected): + np.testing.assert_array_equal(actual, expected) + + +def numeric_test(actual, expected): + np.testing.assert_allclose(actual, expected, rtol=1e-3, atol=1e-6) + + +def get_test_data(train_samples, + test_samples, + input_shape, + num_classes, + random_seed=None): + """Generates test data to train a model on. + + Args: + train_samples: Integer, how many training samples to generate. + test_samples: Integer, how many test samples to generate. + input_shape: Tuple of integers, shape of the inputs. + num_classes: Integer, number of classes for the data and targets. + random_seed: Integer, random seed used by numpy to generate data. + + Returns: + A tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. + """ + if random_seed is not None: + np.random.seed(random_seed) + num_sample = train_samples + test_samples + templates = 2 * num_classes * np.random.random((num_classes,) + input_shape) + y = np.random.randint(0, num_classes, size=(num_sample,)) + x = np.zeros((num_sample,) + input_shape, dtype=np.float32) + for i in range(num_sample): + x[i] = templates[y[i]] + np.random.normal(loc=0, scale=1., size=input_shape) + return ((x[:train_samples], y[:train_samples]), + (x[train_samples:], y[train_samples:])) + + +@test_util.disable_cudnn_autotune +def layer_test(layer_cls, + kwargs=None, + input_shape=None, + input_dtype=None, + input_data=None, + expected_output=None, + expected_output_dtype=None, + expected_output_shape=None, + validate_training=True, + adapt_data=None, + custom_objects=None, + test_harness=None, + supports_masking=None): + """Test routine for a layer with a single input and single output. + + Args: + layer_cls: Layer class object. + kwargs: Optional dictionary of keyword arguments for instantiating the + layer. + input_shape: Input shape tuple. + input_dtype: Data type of the input data. + input_data: Numpy array of input data. + expected_output: Numpy array of the expected output. + expected_output_dtype: Data type expected for the output. + expected_output_shape: Shape tuple for the expected shape of the output. + validate_training: Whether to attempt to validate training on this layer. + This might be set to False for non-differentiable layers that output + string or integer values. + adapt_data: Optional data for an 'adapt' call. If None, adapt() will not + be tested for this layer. This is only relevant for PreprocessingLayers. + custom_objects: Optional dictionary mapping name strings to custom objects + in the layer class. This is helpful for testing custom layers. + test_harness: The Tensorflow test, if any, that this function is being + called in. + supports_masking: Optional boolean to check the `supports_masking` property + of the layer. If None, the check will not be performed. + + Returns: + The output data (Numpy array) returned by the layer, for additional + checks to be done by the calling code. + + Raises: + ValueError: if `input_shape is None`. + """ + if input_data is None: + if input_shape is None: + raise ValueError('input_shape is None') + if not input_dtype: + input_dtype = 'float32' + input_data_shape = list(input_shape) + for i, e in enumerate(input_data_shape): + if e is None: + input_data_shape[i] = np.random.randint(1, 4) + input_data = 10 * np.random.random(input_data_shape) + if input_dtype[:5] == 'float': + input_data -= 0.5 + input_data = input_data.astype(input_dtype) + elif input_shape is None: + input_shape = input_data.shape + if input_dtype is None: + input_dtype = input_data.dtype + if expected_output_dtype is None: + expected_output_dtype = input_dtype + + if dtypes.as_dtype(expected_output_dtype) == dtypes.string: + if test_harness: + assert_equal = test_harness.assertAllEqual + else: + assert_equal = string_test + else: + if test_harness: + assert_equal = test_harness.assertAllClose + else: + assert_equal = numeric_test + + # instantiation + kwargs = kwargs or {} + layer = layer_cls(**kwargs) + + if (supports_masking is not None + and layer.supports_masking != supports_masking): + raise AssertionError( + 'When testing layer %s, the `supports_masking` property is %r' + 'but expected to be %r.\nFull kwargs: %s' % + (layer_cls.__name__, layer.supports_masking, supports_masking, kwargs)) + + # Test adapt, if data was passed. + if adapt_data is not None: + layer.adapt(adapt_data) + + # test get_weights , set_weights at layer level + weights = layer.get_weights() + layer.set_weights(weights) + + # test and instantiation from weights + if 'weights' in tf_inspect.getargspec(layer_cls.__init__): + kwargs['weights'] = weights + layer = layer_cls(**kwargs) + + # test in functional API + x = layers.Input(shape=input_shape[1:], dtype=input_dtype) + y = layer(x) + if backend.dtype(y) != expected_output_dtype: + raise AssertionError('When testing layer %s, for input %s, found output ' + 'dtype=%s but expected to find %s.\nFull kwargs: %s' % + (layer_cls.__name__, x, backend.dtype(y), + expected_output_dtype, kwargs)) + + def assert_shapes_equal(expected, actual): + """Asserts that the output shape from the layer matches the actual shape.""" + if len(expected) != len(actual): + raise AssertionError( + 'When testing layer %s, for input %s, found output_shape=' + '%s but expected to find %s.\nFull kwargs: %s' % + (layer_cls.__name__, x, actual, expected, kwargs)) + + for expected_dim, actual_dim in zip(expected, actual): + if isinstance(expected_dim, tensor_shape.Dimension): + expected_dim = expected_dim.value + if isinstance(actual_dim, tensor_shape.Dimension): + actual_dim = actual_dim.value + if expected_dim is not None and expected_dim != actual_dim: + raise AssertionError( + 'When testing layer %s, for input %s, found output_shape=' + '%s but expected to find %s.\nFull kwargs: %s' % + (layer_cls.__name__, x, actual, expected, kwargs)) + + if expected_output_shape is not None: + assert_shapes_equal(tensor_shape.TensorShape(expected_output_shape), + y.shape) + + # check shape inference + model = models.Model(x, y) + computed_output_shape = tuple( + layer.compute_output_shape( + tensor_shape.TensorShape(input_shape)).as_list()) + computed_output_signature = layer.compute_output_signature( + tensor_spec.TensorSpec(shape=input_shape, dtype=input_dtype)) + actual_output = model.predict(input_data) + actual_output_shape = actual_output.shape + assert_shapes_equal(computed_output_shape, actual_output_shape) + assert_shapes_equal(computed_output_signature.shape, actual_output_shape) + if computed_output_signature.dtype != actual_output.dtype: + raise AssertionError( + 'When testing layer %s, for input %s, found output_dtype=' + '%s but expected to find %s.\nFull kwargs: %s' % + (layer_cls.__name__, x, actual_output.dtype, + computed_output_signature.dtype, kwargs)) + if expected_output is not None: + assert_equal(actual_output, expected_output) + + # test serialization, weight setting at model level + model_config = model.get_config() + recovered_model = models.Model.from_config(model_config, custom_objects) + if model.weights: + weights = model.get_weights() + recovered_model.set_weights(weights) + output = recovered_model.predict(input_data) + assert_equal(output, actual_output) + + # test training mode (e.g. useful for dropout tests) + # Rebuild the model to avoid the graph being reused between predict() and + # See b/120160788 for more details. This should be mitigated after 2.0. + layer_weights = layer.get_weights() # Get the layer weights BEFORE training. + if validate_training: + model = models.Model(x, layer(x)) + if _thread_local_data.run_eagerly is not None: + model.compile( + 'rmsprop', + 'mse', + weighted_metrics=['acc'], + run_eagerly=should_run_eagerly()) + else: + model.compile('rmsprop', 'mse', weighted_metrics=['acc']) + model.train_on_batch(input_data, actual_output) + + # test as first layer in Sequential API + layer_config = layer.get_config() + layer_config['batch_input_shape'] = input_shape + layer = layer.__class__.from_config(layer_config) + + # Test adapt, if data was passed. + if adapt_data is not None: + layer.adapt(adapt_data) + + model = models.Sequential() + model.add(layers.Input(shape=input_shape[1:], dtype=input_dtype)) + model.add(layer) + + layer.set_weights(layer_weights) + actual_output = model.predict(input_data) + actual_output_shape = actual_output.shape + for expected_dim, actual_dim in zip(computed_output_shape, + actual_output_shape): + if expected_dim is not None: + if expected_dim != actual_dim: + raise AssertionError( + 'When testing layer %s **after deserialization**, ' + 'for input %s, found output_shape=' + '%s but expected to find inferred shape %s.\nFull kwargs: %s' % + (layer_cls.__name__, + x, + actual_output_shape, + computed_output_shape, + kwargs)) + if expected_output is not None: + assert_equal(actual_output, expected_output) + + # test serialization, weight setting at model level + model_config = model.get_config() + recovered_model = models.Sequential.from_config(model_config, custom_objects) + if model.weights: + weights = model.get_weights() + recovered_model.set_weights(weights) + output = recovered_model.predict(input_data) + assert_equal(output, actual_output) + + # for further checks in the caller function + return actual_output + + +_thread_local_data = threading.local() +_thread_local_data.model_type = None +_thread_local_data.run_eagerly = None +_thread_local_data.saved_model_format = None +_thread_local_data.save_kwargs = None + + +@tf_contextlib.contextmanager +def model_type_scope(value): + """Provides a scope within which the model type to test is equal to `value`. + + The model type gets restored to its original value upon exiting the scope. + + Args: + value: model type value + + Yields: + The provided value. + """ + previous_value = _thread_local_data.model_type + try: + _thread_local_data.model_type = value + yield value + finally: + # Restore model type to initial value. + _thread_local_data.model_type = previous_value + + +@tf_contextlib.contextmanager +def run_eagerly_scope(value): + """Provides a scope within which we compile models to run eagerly or not. + + The boolean gets restored to its original value upon exiting the scope. + + Args: + value: Bool specifying if we should run models eagerly in the active test. + Should be True or False. + + Yields: + The provided value. + """ + previous_value = _thread_local_data.run_eagerly + try: + _thread_local_data.run_eagerly = value + yield value + finally: + # Restore model type to initial value. + _thread_local_data.run_eagerly = previous_value + + +def should_run_eagerly(): + """Returns whether the models we are testing should be run eagerly.""" + if _thread_local_data.run_eagerly is None: + raise ValueError('Cannot call `should_run_eagerly()` outside of a ' + '`run_eagerly_scope()` or `run_all_keras_modes` ' + 'decorator.') + + return _thread_local_data.run_eagerly and context.executing_eagerly() + + +@tf_contextlib.contextmanager +def saved_model_format_scope(value, **kwargs): + """Provides a scope within which the savde model format to test is `value`. + + The saved model format gets restored to its original value upon exiting the + scope. + + Args: + value: saved model format value + **kwargs: optional kwargs to pass to the save function. + + Yields: + The provided value. + """ + previous_format = _thread_local_data.saved_model_format + previous_kwargs = _thread_local_data.save_kwargs + try: + _thread_local_data.saved_model_format = value + _thread_local_data.save_kwargs = kwargs + yield + finally: + # Restore saved model format to initial value. + _thread_local_data.saved_model_format = previous_format + _thread_local_data.save_kwargs = previous_kwargs + + +def get_save_format(): + if _thread_local_data.saved_model_format is None: + raise ValueError( + 'Cannot call `get_save_format()` outside of a ' + '`saved_model_format_scope()` or `run_with_all_saved_model_formats` ' + 'decorator.') + return _thread_local_data.saved_model_format + + +def get_save_kwargs(): + if _thread_local_data.save_kwargs is None: + raise ValueError( + 'Cannot call `get_save_kwargs()` outside of a ' + '`saved_model_format_scope()` or `run_with_all_saved_model_formats` ' + 'decorator.') + return _thread_local_data.save_kwargs or {} + + +def get_model_type(): + """Gets the model type that should be tested.""" + if _thread_local_data.model_type is None: + raise ValueError('Cannot call `get_model_type()` outside of a ' + '`model_type_scope()` or `run_with_all_model_types` ' + 'decorator.') + + return _thread_local_data.model_type + + +def get_small_sequential_mlp(num_hidden, num_classes, input_dim=None): + model = models.Sequential() + if input_dim: + model.add(layers.Dense(num_hidden, activation='relu', input_dim=input_dim)) + else: + model.add(layers.Dense(num_hidden, activation='relu')) + activation = 'sigmoid' if num_classes == 1 else 'softmax' + model.add(layers.Dense(num_classes, activation=activation)) + return model + + +def get_small_functional_mlp(num_hidden, num_classes, input_dim): + inputs = layers.Input(shape=(input_dim,)) + outputs = layers.Dense(num_hidden, activation='relu')(inputs) + activation = 'sigmoid' if num_classes == 1 else 'softmax' + outputs = layers.Dense(num_classes, activation=activation)(outputs) + return models.Model(inputs, outputs) + + +class SmallSubclassMLP(models.Model): + """A subclass model based small MLP.""" + + def __init__(self, + num_hidden, + num_classes, + use_bn=False, + use_dp=False, + **kwargs): + super(SmallSubclassMLP, self).__init__(name='test_model', **kwargs) + self.use_bn = use_bn + self.use_dp = use_dp + + self.layer_a = layers.Dense(num_hidden, activation='relu') + activation = 'sigmoid' if num_classes == 1 else 'softmax' + self.layer_b = layers.Dense(num_classes, activation=activation) + if self.use_dp: + self.dp = layers.Dropout(0.5) + if self.use_bn: + self.bn = layers.BatchNormalization(axis=-1) + + def call(self, inputs, **kwargs): + x = self.layer_a(inputs) + if self.use_dp: + x = self.dp(x) + if self.use_bn: + x = self.bn(x) + return self.layer_b(x) + + +class _SmallSubclassMLPCustomBuild(models.Model): + """A subclass model small MLP that uses a custom build method.""" + + def __init__(self, num_hidden, num_classes): + super(_SmallSubclassMLPCustomBuild, self).__init__() + self.layer_a = None + self.layer_b = None + self.num_hidden = num_hidden + self.num_classes = num_classes + + def build(self, input_shape): + self.layer_a = layers.Dense(self.num_hidden, activation='relu') + activation = 'sigmoid' if self.num_classes == 1 else 'softmax' + self.layer_b = layers.Dense(self.num_classes, activation=activation) + + def call(self, inputs, **kwargs): + x = self.layer_a(inputs) + return self.layer_b(x) + + +def get_small_subclass_mlp(num_hidden, num_classes): + return SmallSubclassMLP(num_hidden, num_classes) + + +def get_small_subclass_mlp_with_custom_build(num_hidden, num_classes): + return _SmallSubclassMLPCustomBuild(num_hidden, num_classes) + + +def get_small_mlp(num_hidden, num_classes, input_dim): + """Get a small mlp of the model type specified by `get_model_type`.""" + model_type = get_model_type() + if model_type == 'subclass': + return get_small_subclass_mlp(num_hidden, num_classes) + if model_type == 'subclass_custom_build': + return get_small_subclass_mlp_with_custom_build(num_hidden, num_classes) + if model_type == 'sequential': + return get_small_sequential_mlp(num_hidden, num_classes, input_dim) + if model_type == 'functional': + return get_small_functional_mlp(num_hidden, num_classes, input_dim) + raise ValueError('Unknown model type {}'.format(model_type)) + + +class _SubclassModel(models.Model): + """A Keras subclass model.""" + + def __init__(self, model_layers, *args, **kwargs): + """Instantiate a model. + + Args: + model_layers: a list of layers to be added to the model. + *args: Model's args + **kwargs: Model's keyword args, at most one of input_tensor -> the input + tensor required for ragged/sparse input. + """ + + inputs = kwargs.pop('input_tensor', None) + super(_SubclassModel, self).__init__(*args, **kwargs) + # Note that clone and build doesn't support lists of layers in subclassed + # models. Adding each layer directly here. + for i, layer in enumerate(model_layers): + setattr(self, self._layer_name_for_i(i), layer) + + self.num_layers = len(model_layers) + + if inputs is not None: + self._set_inputs(inputs) + + def _layer_name_for_i(self, i): + return 'layer{}'.format(i) + + def call(self, inputs, **kwargs): + x = inputs + for i in range(self.num_layers): + layer = getattr(self, self._layer_name_for_i(i)) + x = layer(x) + return x + + +class _SubclassModelCustomBuild(models.Model): + """A Keras subclass model that uses a custom build method.""" + + def __init__(self, layer_generating_func, *args, **kwargs): + super(_SubclassModelCustomBuild, self).__init__(*args, **kwargs) + self.all_layers = None + self._layer_generating_func = layer_generating_func + + def build(self, input_shape): + model_layers = [] + for layer in self._layer_generating_func(): + model_layers.append(layer) + self.all_layers = model_layers + + def call(self, inputs, **kwargs): + x = inputs + for layer in self.all_layers: + x = layer(x) + return x + + +def get_model_from_layers(model_layers, + input_shape=None, + input_dtype=None, + name=None, + input_ragged=None, + input_sparse=None, + model_type=None): + """Builds a model from a sequence of layers. + + Args: + model_layers: The layers used to build the network. + input_shape: Shape tuple of the input or 'TensorShape' instance. + input_dtype: Datatype of the input. + name: Name for the model. + input_ragged: Boolean, whether the input data is a ragged tensor. + input_sparse: Boolean, whether the input data is a sparse tensor. + model_type: One of "subclass", "subclass_custom_build", "sequential", or + "functional". When None, defaults to `get_model_type`. + + Returns: + A Keras model. + """ + if model_type is None: + model_type = get_model_type() + if model_type == 'subclass': + inputs = None + if input_ragged or input_sparse: + inputs = layers.Input( + shape=input_shape, + dtype=input_dtype, + ragged=input_ragged, + sparse=input_sparse) + return _SubclassModel(model_layers, name=name, input_tensor=inputs) + + if model_type == 'subclass_custom_build': + layer_generating_func = lambda: model_layers + return _SubclassModelCustomBuild(layer_generating_func, name=name) + + if model_type == 'sequential': + model = models.Sequential(name=name) + if input_shape: + model.add( + layers.InputLayer( + input_shape=input_shape, + dtype=input_dtype, + ragged=input_ragged, + sparse=input_sparse)) + for layer in model_layers: + model.add(layer) + return model + + if model_type == 'functional': + if not input_shape: + raise ValueError('Cannot create a functional model from layers with no ' + 'input shape.') + inputs = layers.Input( + shape=input_shape, + dtype=input_dtype, + ragged=input_ragged, + sparse=input_sparse) + outputs = inputs + for layer in model_layers: + outputs = layer(outputs) + return models.Model(inputs, outputs, name=name) + + raise ValueError('Unknown model type {}'.format(model_type)) + + +class Bias(layers.Layer): + + def build(self, input_shape): + self.bias = self.add_variable('bias', (1,), initializer='zeros') + + def call(self, inputs): + return inputs + self.bias + + +class _MultiIOSubclassModel(models.Model): + """Multi IO Keras subclass model.""" + + def __init__(self, branch_a, branch_b, shared_input_branch=None, + shared_output_branch=None, name=None): + super(_MultiIOSubclassModel, self).__init__(name=name) + self._shared_input_branch = shared_input_branch + self._branch_a = branch_a + self._branch_b = branch_b + self._shared_output_branch = shared_output_branch + + def call(self, inputs, **kwargs): + if self._shared_input_branch: + for layer in self._shared_input_branch: + inputs = layer(inputs) + a = inputs + b = inputs + elif isinstance(inputs, dict): + a = inputs['input_1'] + b = inputs['input_2'] + else: + a, b = inputs + + for layer in self._branch_a: + a = layer(a) + for layer in self._branch_b: + b = layer(b) + outs = [a, b] + + if self._shared_output_branch: + for layer in self._shared_output_branch: + outs = layer(outs) + + return outs + + +class _MultiIOSubclassModelCustomBuild(models.Model): + """Multi IO Keras subclass model that uses a custom build method.""" + + def __init__(self, branch_a_func, branch_b_func, + shared_input_branch_func=None, + shared_output_branch_func=None): + super(_MultiIOSubclassModelCustomBuild, self).__init__() + self._shared_input_branch_func = shared_input_branch_func + self._branch_a_func = branch_a_func + self._branch_b_func = branch_b_func + self._shared_output_branch_func = shared_output_branch_func + + self._shared_input_branch = None + self._branch_a = None + self._branch_b = None + self._shared_output_branch = None + + def build(self, input_shape): + if self._shared_input_branch_func(): + self._shared_input_branch = self._shared_input_branch_func() + self._branch_a = self._branch_a_func() + self._branch_b = self._branch_b_func() + + if self._shared_output_branch_func(): + self._shared_output_branch = self._shared_output_branch_func() + + def call(self, inputs, **kwargs): + if self._shared_input_branch: + for layer in self._shared_input_branch: + inputs = layer(inputs) + a = inputs + b = inputs + else: + a, b = inputs + + for layer in self._branch_a: + a = layer(a) + for layer in self._branch_b: + b = layer(b) + outs = a, b + + if self._shared_output_branch: + for layer in self._shared_output_branch: + outs = layer(outs) + + return outs + + +def get_multi_io_model( + branch_a, + branch_b, + shared_input_branch=None, + shared_output_branch=None): + """Builds a multi-io model that contains two branches. + + The produced model will be of the type specified by `get_model_type`. + + To build a two-input, two-output model: + Specify a list of layers for branch a and branch b, but do not specify any + shared input branch or shared output branch. The resulting model will apply + each branch to a different input, to produce two outputs. + + The first value in branch_a must be the Keras 'Input' layer for branch a, + and the first value in branch_b must be the Keras 'Input' layer for + branch b. + + example usage: + ``` + branch_a = [Input(shape=(2,), name='a'), Dense(), Dense()] + branch_b = [Input(shape=(3,), name='b'), Dense(), Dense()] + + model = get_multi_io_model(branch_a, branch_b) + ``` + + To build a two-input, one-output model: + Specify a list of layers for branch a and branch b, and specify a + shared output branch. The resulting model will apply + each branch to a different input. It will then apply the shared output + branch to a tuple containing the intermediate outputs of each branch, + to produce a single output. The first layer in the shared_output_branch + must be able to merge a tuple of two tensors. + + The first value in branch_a must be the Keras 'Input' layer for branch a, + and the first value in branch_b must be the Keras 'Input' layer for + branch b. + + example usage: + ``` + input_branch_a = [Input(shape=(2,), name='a'), Dense(), Dense()] + input_branch_b = [Input(shape=(3,), name='b'), Dense(), Dense()] + shared_output_branch = [Concatenate(), Dense(), Dense()] + + model = get_multi_io_model(input_branch_a, input_branch_b, + shared_output_branch=shared_output_branch) + ``` + To build a one-input, two-output model: + Specify a list of layers for branch a and branch b, and specify a + shared input branch. The resulting model will take one input, and apply + the shared input branch to it. It will then respectively apply each branch + to that intermediate result in parallel, to produce two outputs. + + The first value in the shared_input_branch must be the Keras 'Input' layer + for the whole model. Branch a and branch b should not contain any Input + layers. + + example usage: + ``` + shared_input_branch = [Input(shape=(2,), name='in'), Dense(), Dense()] + output_branch_a = [Dense(), Dense()] + output_branch_b = [Dense(), Dense()] + + + model = get_multi_io_model(output__branch_a, output_branch_b, + shared_input_branch=shared_input_branch) + ``` + + Args: + branch_a: A sequence of layers for branch a of the model. + branch_b: A sequence of layers for branch b of the model. + shared_input_branch: An optional sequence of layers to apply to a single + input, before applying both branches to that intermediate result. If set, + the model will take only one input instead of two. Defaults to None. + shared_output_branch: An optional sequence of layers to merge the + intermediate results produced by branch a and branch b. If set, + the model will produce only one output instead of two. Defaults to None. + + Returns: + A multi-io model of the type specified by `get_model_type`, specified + by the different branches. + """ + # Extract the functional inputs from the layer lists + if shared_input_branch: + inputs = shared_input_branch[0] + shared_input_branch = shared_input_branch[1:] + else: + inputs = branch_a[0], branch_b[0] + branch_a = branch_a[1:] + branch_b = branch_b[1:] + + model_type = get_model_type() + if model_type == 'subclass': + return _MultiIOSubclassModel(branch_a, branch_b, shared_input_branch, + shared_output_branch) + + if model_type == 'subclass_custom_build': + return _MultiIOSubclassModelCustomBuild((lambda: branch_a), + (lambda: branch_b), + (lambda: shared_input_branch), + (lambda: shared_output_branch)) + + if model_type == 'sequential': + raise ValueError('Cannot use `get_multi_io_model` to construct ' + 'sequential models') + + if model_type == 'functional': + if shared_input_branch: + a_and_b = inputs + for layer in shared_input_branch: + a_and_b = layer(a_and_b) + a = a_and_b + b = a_and_b + else: + a, b = inputs + + for layer in branch_a: + a = layer(a) + for layer in branch_b: + b = layer(b) + outputs = a, b + + if shared_output_branch: + for layer in shared_output_branch: + outputs = layer(outputs) + + return models.Model(inputs, outputs) + + raise ValueError('Unknown model type {}'.format(model_type)) + + +_V2_OPTIMIZER_MAP = { + 'adadelta': adadelta_v2.Adadelta, + 'adagrad': adagrad_v2.Adagrad, + 'adam': adam_v2.Adam, + 'adamax': adamax_v2.Adamax, + 'nadam': nadam_v2.Nadam, + 'rmsprop': rmsprop_v2.RMSprop, + 'sgd': gradient_descent_v2.SGD +} + + +def get_v2_optimizer(name, **kwargs): + """Get the v2 optimizer requested. + + This is only necessary until v2 are the default, as we are testing in Eager, + and Eager + v1 optimizers fail tests. When we are in v2, the strings alone + should be sufficient, and this mapping can theoretically be removed. + + Args: + name: string name of Keras v2 optimizer. + **kwargs: any kwargs to pass to the optimizer constructor. + + Returns: + Initialized Keras v2 optimizer. + + Raises: + ValueError: if an unknown name was passed. + """ + try: + return _V2_OPTIMIZER_MAP[name](**kwargs) + except KeyError: + raise ValueError( + 'Could not find requested v2 optimizer: {}\nValid choices: {}'.format( + name, list(_V2_OPTIMIZER_MAP.keys()))) + + +def get_expected_metric_variable_names(var_names, name_suffix=''): + """Returns expected metric variable names given names and prefix/suffix.""" + if tf2.enabled() or context.executing_eagerly(): + # In V1 eager mode and V2 variable names are not made unique. + return [n + ':0' for n in var_names] + # In V1 graph mode variable names are made unique using a suffix. + return [n + name_suffix + ':0' for n in var_names] + + +def enable_v2_dtype_behavior(fn): + """Decorator for enabling the layer V2 dtype behavior on a test.""" + return _set_v2_dtype_behavior(fn, True) + + +def disable_v2_dtype_behavior(fn): + """Decorator for disabling the layer V2 dtype behavior on a test.""" + return _set_v2_dtype_behavior(fn, False) + + +def _set_v2_dtype_behavior(fn, enabled): + """Returns version of 'fn' that runs with v2 dtype behavior on or off.""" + @functools.wraps(fn) + def wrapper(*args, **kwargs): + v2_dtype_behavior = base_layer_utils.V2_DTYPE_BEHAVIOR + base_layer_utils.V2_DTYPE_BEHAVIOR = enabled + try: + return fn(*args, **kwargs) + finally: + base_layer_utils.V2_DTYPE_BEHAVIOR = v2_dtype_behavior + + return tf_decorator.make_decorator(fn, wrapper) + + +@contextlib.contextmanager +def device(should_use_gpu): + """Uses gpu when requested and available.""" + if should_use_gpu and test_util.is_gpu_available(): + dev = '/device:GPU:0' + else: + dev = '/device:CPU:0' + with ops.device(dev): + yield + + +@contextlib.contextmanager +def use_gpu(): + """Uses gpu when requested and available.""" + with device(should_use_gpu=True): + yield + + +def for_all_test_methods(decorator, *args, **kwargs): + """Generate class-level decorator from given method-level decorator. + + It is expected for the given decorator to take some arguments and return + a method that is then called on the test method to produce a decorated + method. + + Args: + decorator: The decorator to apply. + *args: Positional arguments + **kwargs: Keyword arguments + Returns: Function that will decorate a given classes test methods with the + decorator. + """ + + def all_test_methods_impl(cls): + """Apply decorator to all test methods in class.""" + for name in dir(cls): + value = getattr(cls, name) + if callable(value) and name.startswith('test') and (name != + 'test_session'): + setattr(cls, name, decorator(*args, **kwargs)(value)) + return cls + + return all_test_methods_impl + + +# The description is just for documentation purposes. +def run_without_tensor_float_32(description): # pylint: disable=unused-argument + """Execute test with TensorFloat-32 disabled. + + While almost every real-world deep learning model runs fine with + TensorFloat-32, many tests use assertAllClose or similar methods. + TensorFloat-32 matmuls typically will cause such methods to fail with the + default tolerances. + + Args: + description: A description used for documentation purposes, describing why + the test requires TensorFloat-32 to be disabled. + + Returns: + Decorator which runs a test with TensorFloat-32 disabled. + """ + + def decorator(f): + + @functools.wraps(f) + def decorated(self, *args, **kwargs): + allowed = config.tensor_float_32_execution_enabled() + try: + config.enable_tensor_float_32_execution(False) + f(self, *args, **kwargs) + finally: + config.enable_tensor_float_32_execution(allowed) + + return decorated + + return decorator + + +# The description is just for documentation purposes. +def run_all_without_tensor_float_32(description): # pylint: disable=unused-argument + """Execute all tests in a class with TensorFloat-32 disabled.""" + return for_all_test_methods(run_without_tensor_float_32, description) + + +def run_v2_only(func=None): + """Execute the decorated test only if running in v2 mode. + + This function is intended to be applied to tests that exercise v2 only + functionality. If the test is run in v1 mode it will simply be skipped. + + See go/tf-test-decorator-cheatsheet for the decorators to use in different + v1/v2/eager/graph combinations. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + + Returns: + Returns a decorator that will conditionally skip the decorated test method. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError('`run_v2_only` only supports test methods.') + + def decorated(self, *args, **kwargs): + if not tf2.enabled(): + self.skipTest('Test is only compatible with v2') + + return f(self, *args, **kwargs) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +def generate_combinations_with_testcase_name(**kwargs): + """Generate combinations based on its keyword arguments using combine(). + + This function calls combine() and appends a testcase name to the list of + dictionaries returned. The 'testcase_name' key is a required for named + parameterized tests. + + Args: + **kwargs: keyword arguments of form `option=[possibilities, ...]` or + `option=the_only_possibility`. + + Returns: + a list of dictionaries for each combination. Keys in the dictionaries are + the keyword argument names. Each key has one value - one of the + corresponding keyword argument values. + """ + sort_by_key = lambda k: k[0] + combinations = [] + for key, values in sorted(kwargs.items(), key=sort_by_key): + if not isinstance(values, list): + values = [values] + combinations.append([(key, value) for value in values]) + + combinations = [collections.OrderedDict(result) + for result in itertools.product(*combinations)] + named_combinations = [] + for combination in combinations: + assert isinstance(combination, collections.OrderedDict) + name = ''.join([ + '_{}_{}'.format(''.join(filter(str.isalnum, key)), + ''.join(filter(str.isalnum, str(value)))) + for key, value in combination.items() + ]) + named_combinations.append( + collections.OrderedDict( + list(combination.items()) + + [('testcase_name', '_test{}'.format(name))])) + + return named_combinations diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/all_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/all_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9cacf72c42039f45519665eb303c6273340fee50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/all_utils.py @@ -0,0 +1,37 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Public Keras utilities. + +This module is used as a shortcut to access all the symbols. Those symbols was +exposed under __init__, and was causing some hourglass import issue. +""" + +# pylint: disable=unused-import +from tensorflow.python.keras.utils.data_utils import GeneratorEnqueuer +from tensorflow.python.keras.utils.data_utils import get_file +from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer +from tensorflow.python.keras.utils.data_utils import Sequence +from tensorflow.python.keras.utils.data_utils import SequenceEnqueuer +from tensorflow.python.keras.utils.generic_utils import custom_object_scope +from tensorflow.python.keras.utils.generic_utils import CustomObjectScope +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import get_custom_objects +from tensorflow.python.keras.utils.generic_utils import Progbar +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.keras.utils.layer_utils import get_source_inputs +from tensorflow.python.keras.utils.np_utils import normalize +from tensorflow.python.keras.utils.np_utils import to_categorical +from tensorflow.python.keras.utils.vis_utils import model_to_dot +from tensorflow.python.keras.utils.vis_utils import plot_model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/control_flow_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/control_flow_util.py new file mode 100644 index 0000000000000000000000000000000000000000..067570eb6d64b01dc99ac29a5c87d4eca75a025b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/control_flow_util.py @@ -0,0 +1,136 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility functions for control flow. + +This file is copied from tensorflow/python/ops/control_flow_util.py. +""" + +from tensorflow.python.framework import smart_cond as smart_module +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import cond +from tensorflow.python.ops import variables + + +def InXlaContext(graph): + ctxt = graph._get_control_flow_context() # pylint: disable=protected-access + return GetContainingXLAContext(ctxt) is not None + + +def GraphOrParentsInXlaContext(graph): + while True: + if InXlaContext(graph): return True + try: + graph = graph.outer_graph + except AttributeError: + return False + + +def IsInWhileLoop(op): + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return GetContainingWhileContext(ctxt) is not None + + +def GetContainingWhileContext(ctxt, stop_ctxt=None): + """Returns the first ancestor WhileContext of `ctxt`. + + Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a + while loop. + + Args: + ctxt: ControlFlowContext + stop_ctxt: ControlFlowContext, optional. If provided, the search will end + if it sees stop_ctxt. + + Returns: + `ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing + `ctxt`, or None if `ctxt` is not in a while loop. If `stop_ctxt` is not + `None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal. + """ + while ctxt: + if ctxt.IsWhileContext() or ctxt == stop_ctxt: return ctxt + ctxt = ctxt.outer_context + return None + + +def GetContainingXLAContext(ctxt): + """Returns the first ancestor XLAContext of `ctxt`. + + Returns `ctxt` if `ctxt` is a XLAContext, or None if `ctxt` is not in a + while loop. + + Args: + ctxt: ControlFlowContext + + Returns: + `ctxt` if `ctxt` is a XLAContext, the most nested XLAContext containing + `ctxt`, or None if `ctxt` is not in a while loop. + """ + while ctxt: + if ctxt.IsXLAContext(): return ctxt + ctxt = ctxt.outer_context + return None + + +def smart_cond(pred, true_fn=None, false_fn=None, name=None): # pylint: disable=invalid-name + """Return either `true_fn()` if predicate `pred` is true else `false_fn()`. + + If `pred` is a bool or has a constant value, we return either `true_fn()` + or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both. + + Args: + pred: A scalar determining whether to return the result of `true_fn` or + `false_fn`. + true_fn: The callable to be performed if pred is true. + false_fn: The callable to be performed if pred is false. + name: Optional name prefix when using `tf.cond`. + + Returns: + Tensors returned by the call to either `true_fn` or `false_fn`. + + Raises: + TypeError: If `true_fn` or `false_fn` is not callable. + """ + if isinstance(pred, variables.Variable): + return cond.cond( + pred, true_fn=true_fn, false_fn=false_fn, name=name) + return smart_module.smart_cond( + pred, true_fn=true_fn, false_fn=false_fn, name=name) + + +def constant_value(pred): # pylint: disable=invalid-name + """Return the bool value for `pred`, or None if `pred` had a dynamic value. + + Args: + pred: A scalar, either a Python bool or a TensorFlow boolean variable + or tensor, or the Python integer 1 or 0. + + Returns: + True or False if `pred` has a constant boolean value, None otherwise. + + Raises: + TypeError: If `pred` is not a Variable, Tensor or bool, or Python + integer 1 or 0. + """ + if isinstance(pred, tensor.Tensor): + return tensor_util.constant_value(pred) + if pred in {0, 1}: # Accept 1/0 as valid boolean values + return bool(pred) + if isinstance(pred, bool): + return pred + if isinstance(pred, variables.Variable): + return None + raise TypeError("`pred` must be a Tensor, or a Python bool, or 1 or 0. " + "Found instead: %s" % type(pred)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/conv_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/conv_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b4556f2c724527c3c3a6c6963fcf5abf7dcbe655 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/conv_utils.py @@ -0,0 +1,515 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities used by convolution layers.""" + +import itertools + +import numpy as np + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.ops import array_ops + + +def convert_data_format(data_format, ndim): + if data_format == 'channels_last': + if ndim == 3: + return 'NWC' + elif ndim == 4: + return 'NHWC' + elif ndim == 5: + return 'NDHWC' + else: + raise ValueError('Input rank not supported:', ndim) + elif data_format == 'channels_first': + if ndim == 3: + return 'NCW' + elif ndim == 4: + return 'NCHW' + elif ndim == 5: + return 'NCDHW' + else: + raise ValueError('Input rank not supported:', ndim) + else: + raise ValueError('Invalid data_format:', data_format) + + +def normalize_tuple(value, n, name): + """Transforms a single integer or iterable of integers into an integer tuple. + + Args: + value: The value to validate and convert. Could an int, or any iterable of + ints. + n: The size of the tuple to be returned. + name: The name of the argument being validated, e.g. "strides" or + "kernel_size". This is only used to format error messages. + + Returns: + A tuple of n integers. + + Raises: + ValueError: If something else than an int/long or iterable thereof was + passed. + """ + if isinstance(value, int): + return (value,) * n + else: + try: + value_tuple = tuple(value) + except TypeError: + raise ValueError('The `' + name + '` argument must be a tuple of ' + + str(n) + ' integers. Received: ' + str(value)) + if len(value_tuple) != n: + raise ValueError('The `' + name + '` argument must be a tuple of ' + + str(n) + ' integers. Received: ' + str(value)) + for single_value in value_tuple: + try: + int(single_value) + except (ValueError, TypeError): + raise ValueError('The `' + name + '` argument must be a tuple of ' + + str(n) + ' integers. Received: ' + str(value) + ' ' + 'including element ' + str(single_value) + ' of type' + + ' ' + str(type(single_value))) + return value_tuple + + +def conv_output_length(input_length, filter_size, padding, stride, dilation=1): + """Determines output length of a convolution given input length. + + Args: + input_length: integer. + filter_size: integer. + padding: one of "same", "valid", "full", "causal" + stride: integer. + dilation: dilation rate, integer. + + Returns: + The output length (integer). + """ + if input_length is None: + return None + assert padding in {'same', 'valid', 'full', 'causal'} + dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) + if padding in ['same', 'causal']: + output_length = input_length + elif padding == 'valid': + output_length = input_length - dilated_filter_size + 1 + elif padding == 'full': + output_length = input_length + dilated_filter_size - 1 + return (output_length + stride - 1) // stride + + +def conv_input_length(output_length, filter_size, padding, stride): + """Determines input length of a convolution given output length. + + Args: + output_length: integer. + filter_size: integer. + padding: one of "same", "valid", "full". + stride: integer. + + Returns: + The input length (integer). + """ + if output_length is None: + return None + assert padding in {'same', 'valid', 'full'} + if padding == 'same': + pad = filter_size // 2 + elif padding == 'valid': + pad = 0 + elif padding == 'full': + pad = filter_size - 1 + return (output_length - 1) * stride - 2 * pad + filter_size + + +def deconv_output_length(input_length, + filter_size, + padding, + output_padding=None, + stride=0, + dilation=1): + """Determines output length of a transposed convolution given input length. + + Args: + input_length: Integer. + filter_size: Integer. + padding: one of `"same"`, `"valid"`, `"full"`. + output_padding: Integer, amount of padding along the output dimension. Can + be set to `None` in which case the output length is inferred. + stride: Integer. + dilation: Integer. + + Returns: + The output length (integer). + """ + assert padding in {'same', 'valid', 'full'} + if input_length is None: + return None + + # Get the dilated kernel size + filter_size = filter_size + (filter_size - 1) * (dilation - 1) + + # Infer length if output padding is None, else compute the exact length + if output_padding is None: + if padding == 'valid': + length = input_length * stride + max(filter_size - stride, 0) + elif padding == 'full': + length = input_length * stride - (stride + filter_size - 2) + elif padding == 'same': + length = input_length * stride + + else: + if padding == 'same': + pad = filter_size // 2 + elif padding == 'valid': + pad = 0 + elif padding == 'full': + pad = filter_size - 1 + + length = ((input_length - 1) * stride + filter_size - 2 * pad + + output_padding) + return length + + +def normalize_data_format(value): + if value is None: + value = backend.image_data_format() + data_format = value.lower() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('The `data_format` argument must be one of ' + '"channels_first", "channels_last". Received: ' + + str(value)) + return data_format + + +def normalize_padding(value): + if isinstance(value, (list, tuple)): + return value + padding = value.lower() + if padding not in {'valid', 'same', 'causal'}: + raise ValueError('The `padding` argument must be a list/tuple or one of ' + '"valid", "same" (or "causal", only for `Conv1D). ' + 'Received: ' + str(padding)) + return padding + + +def conv_kernel_mask(input_shape, kernel_shape, strides, padding): + """Compute a mask representing the connectivity of a convolution operation. + + Assume a convolution with given parameters is applied to an input having N + spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an + output with shape `(d_out1, ..., d_outN)`. This method returns a boolean array + of shape `(d_in1, ..., d_inN, d_out1, ..., d_outN)` with `True` entries + indicating pairs of input and output locations that are connected by a weight. + + Example: + + >>> input_shape = (4,) + >>> kernel_shape = (2,) + >>> strides = (1,) + >>> padding = "valid" + >>> conv_kernel_mask(input_shape, kernel_shape, strides, padding) + array([[ True, False, False], + [ True, True, False], + [False, True, True], + [False, False, True]]) + + where rows and columns correspond to inputs and outputs respectively. + + + Args: + input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the + input. + kernel_shape: tuple of size N, spatial shape of the convolutional kernel / + receptive field. + strides: tuple of size N, strides along each spatial dimension. + padding: type of padding, string `"same"` or `"valid"`. + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + + Returns: + A boolean 2N-D `np.ndarray` of shape + `(d_in1, ..., d_inN, d_out1, ..., d_outN)`, where `(d_out1, ..., d_outN)` + is the spatial shape of the output. `True` entries in the mask represent + pairs of input-output locations that are connected by a weight. + + Raises: + ValueError: if `input_shape`, `kernel_shape` and `strides` don't have the + same number of dimensions. + NotImplementedError: if `padding` is not in {`"same"`, `"valid"`}. + """ + if padding not in {'same', 'valid'}: + raise NotImplementedError('Padding type %s not supported. ' + 'Only "valid" and "same" ' + 'are implemented.' % padding) + + in_dims = len(input_shape) + if isinstance(kernel_shape, int): + kernel_shape = (kernel_shape,) * in_dims + if isinstance(strides, int): + strides = (strides,) * in_dims + + kernel_dims = len(kernel_shape) + stride_dims = len(strides) + if kernel_dims != in_dims or stride_dims != in_dims: + raise ValueError('Number of strides, input and kernel dimensions must all ' + 'match. Received: %d, %d, %d.' % + (stride_dims, in_dims, kernel_dims)) + + output_shape = conv_output_shape(input_shape, kernel_shape, strides, padding) + + mask_shape = input_shape + output_shape + mask = np.zeros(mask_shape, np.bool_) + + output_axes_ticks = [range(dim) for dim in output_shape] + for output_position in itertools.product(*output_axes_ticks): + input_axes_ticks = conv_connected_inputs(input_shape, kernel_shape, + output_position, strides, padding) + for input_position in itertools.product(*input_axes_ticks): + mask[input_position + output_position] = True + + return mask + + +def conv_kernel_idxs(input_shape, kernel_shape, strides, padding, filters_in, + filters_out, data_format): + """Yields output-input tuples of indices in a CNN layer. + + The generator iterates over all `(output_idx, input_idx)` tuples, where + `output_idx` is an integer index in a flattened tensor representing a single + output image of a convolutional layer that is connected (via the layer + weights) to the respective single input image at `input_idx` + + Example: + + >>> input_shape = (2, 2) + >>> kernel_shape = (2, 1) + >>> strides = (1, 1) + >>> padding = "valid" + >>> filters_in = 1 + >>> filters_out = 1 + >>> data_format = "channels_last" + >>> list(conv_kernel_idxs(input_shape, kernel_shape, strides, padding, + ... filters_in, filters_out, data_format)) + [(0, 0), (0, 2), (1, 1), (1, 3)] + + Args: + input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the + input. + kernel_shape: tuple of size N, spatial shape of the convolutional kernel / + receptive field. + strides: tuple of size N, strides along each spatial dimension. + padding: type of padding, string `"same"` or `"valid"`. + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + filters_in: `int`, number if filters in the input to the layer. + filters_out: `int', number if filters in the output of the layer. + data_format: string, "channels_first" or "channels_last". + + Yields: + The next tuple `(output_idx, input_idx)`, where + `output_idx` is an integer index in a flattened tensor representing a single + output image of a convolutional layer that is connected (via the layer + weights) to the respective single input image at `input_idx`. + + Raises: + ValueError: if `data_format` is neither + `"channels_last"` nor `"channels_first"`, or if number of strides, input, + and kernel number of dimensions do not match. + + NotImplementedError: if `padding` is neither `"same"` nor `"valid"`. + """ + if padding not in ('same', 'valid'): + raise NotImplementedError('Padding type %s not supported. ' + 'Only "valid" and "same" ' + 'are implemented.' % padding) + + in_dims = len(input_shape) + if isinstance(kernel_shape, int): + kernel_shape = (kernel_shape,) * in_dims + if isinstance(strides, int): + strides = (strides,) * in_dims + + kernel_dims = len(kernel_shape) + stride_dims = len(strides) + if kernel_dims != in_dims or stride_dims != in_dims: + raise ValueError('Number of strides, input and kernel dimensions must all ' + 'match. Received: %d, %d, %d.' % + (stride_dims, in_dims, kernel_dims)) + + output_shape = conv_output_shape(input_shape, kernel_shape, strides, padding) + output_axes_ticks = [range(dim) for dim in output_shape] + + if data_format == 'channels_first': + concat_idxs = lambda spatial_idx, filter_idx: (filter_idx,) + spatial_idx + elif data_format == 'channels_last': + concat_idxs = lambda spatial_idx, filter_idx: spatial_idx + (filter_idx,) + else: + raise ValueError('Data format %s not recognized.' + '`data_format` must be "channels_first" or ' + '"channels_last".' % data_format) + + for output_position in itertools.product(*output_axes_ticks): + input_axes_ticks = conv_connected_inputs(input_shape, kernel_shape, + output_position, strides, padding) + for input_position in itertools.product(*input_axes_ticks): + for f_in in range(filters_in): + for f_out in range(filters_out): + out_idx = np.ravel_multi_index( + multi_index=concat_idxs(output_position, f_out), + dims=concat_idxs(output_shape, filters_out)) + in_idx = np.ravel_multi_index( + multi_index=concat_idxs(input_position, f_in), + dims=concat_idxs(input_shape, filters_in)) + yield (out_idx, in_idx) + + +def conv_connected_inputs(input_shape, kernel_shape, output_position, strides, + padding): + """Return locations of the input connected to an output position. + + Assume a convolution with given parameters is applied to an input having N + spatial dimensions with `input_shape = (d_in1, ..., d_inN)`. This method + returns N ranges specifying the input region that was convolved with the + kernel to produce the output at position + `output_position = (p_out1, ..., p_outN)`. + + Example: + + >>> input_shape = (4, 4) + >>> kernel_shape = (2, 1) + >>> output_position = (1, 1) + >>> strides = (1, 1) + >>> padding = "valid" + >>> conv_connected_inputs(input_shape, kernel_shape, output_position, + ... strides, padding) + [range(1, 3), range(1, 2)] + + Args: + input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the + input. + kernel_shape: tuple of size N, spatial shape of the convolutional kernel / + receptive field. + output_position: tuple of size N: `(p_out1, ..., p_outN)`, a single position + in the output of the convolution. + strides: tuple of size N, strides along each spatial dimension. + padding: type of padding, string `"same"` or `"valid"`. + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + + Returns: + N ranges `[[p_in_left1, ..., p_in_right1], ..., + [p_in_leftN, ..., p_in_rightN]]` specifying the region in the + input connected to output_position. + """ + ranges = [] + + ndims = len(input_shape) + for d in range(ndims): + left_shift = int(kernel_shape[d] / 2) + right_shift = kernel_shape[d] - left_shift + + center = output_position[d] * strides[d] + + if padding == 'valid': + center += left_shift + + start = max(0, center - left_shift) + end = min(input_shape[d], center + right_shift) + + ranges.append(range(start, end)) + + return ranges + + +def conv_output_shape(input_shape, kernel_shape, strides, padding): + """Return the output shape of an N-D convolution. + + Forces dimensions where input is empty (size 0) to remain empty. + + Args: + input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the + input. + kernel_shape: tuple of size N, spatial shape of the convolutional kernel / + receptive field. + strides: tuple of size N, strides along each spatial dimension. + padding: type of padding, string `"same"` or `"valid"`. + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input. + + Returns: + tuple of size N: `(d_out1, ..., d_outN)`, spatial shape of the output. + """ + dims = range(len(kernel_shape)) + output_shape = [ + conv_output_length(input_shape[d], kernel_shape[d], padding, strides[d]) + for d in dims + ] + output_shape = tuple( + [0 if input_shape[d] == 0 else output_shape[d] for d in dims]) + return output_shape + + +def squeeze_batch_dims(inp, op, inner_rank): + """Returns `unsqueeze_batch(op(squeeze_batch(inp)))`. + + Where `squeeze_batch` reshapes `inp` to shape + `[prod(inp.shape[:-inner_rank])] + inp.shape[-inner_rank:]` + and `unsqueeze_batch` does the reverse reshape but on the output. + + Args: + inp: A tensor with dims `batch_shape + inner_shape` where `inner_shape` + is length `inner_rank`. + op: A callable that takes a single input tensor and returns a single. + output tensor. + inner_rank: A python integer. + + Returns: + `unsqueeze_batch_op(squeeze_batch(inp))`. + """ + with ops.name_scope_v2('squeeze_batch_dims'): + shape = inp.shape + + inner_shape = shape[-inner_rank:] + if not inner_shape.is_fully_defined(): + inner_shape = array_ops.shape(inp)[-inner_rank:] + + batch_shape = shape[:-inner_rank] + if not batch_shape.is_fully_defined(): + batch_shape = array_ops.shape(inp)[:-inner_rank] + + if isinstance(inner_shape, tensor_shape.TensorShape): + inp_reshaped = array_ops.reshape(inp, [-1] + inner_shape.as_list()) + else: + inp_reshaped = array_ops.reshape( + inp, array_ops.concat(([-1], inner_shape), axis=-1)) + + out_reshaped = op(inp_reshaped) + + out_inner_shape = out_reshaped.shape[-inner_rank:] + if not out_inner_shape.is_fully_defined(): + out_inner_shape = array_ops.shape(out_reshaped)[-inner_rank:] + + out = array_ops.reshape( + out_reshaped, array_ops.concat((batch_shape, out_inner_shape), axis=-1)) + + out.set_shape(inp.shape[:-inner_rank] + out.shape[-inner_rank:]) + return out diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/data_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa63910a3f06bf22786862fe87439891252213e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/data_utils.py @@ -0,0 +1,890 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-import-not-at-top +"""Utilities for file download and caching.""" + +from abc import abstractmethod +from contextlib import closing +import functools +import hashlib +import multiprocessing +import multiprocessing.dummy +import os +import queue +import random +import shutil +import sys # pylint: disable=unused-import +import tarfile +import threading +import time +import typing +import urllib +import weakref +import zipfile + +import numpy as np + +from tensorflow.python.framework import tensor +from six.moves.urllib.request import urlopen +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.keras.utils.generic_utils import Progbar +from tensorflow.python.keras.utils.io_utils import path_to_string + +# Required to support google internal urlretrieve +if sys.version_info[0] == 2: + + def urlretrieve(url, filename, reporthook=None, data=None): + """Replacement for `urlretrieve` for Python 2. + + Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy + `urllib` module, known to have issues with proxy management. + + Args: + url: url to retrieve. + filename: where to store the retrieved data locally. + reporthook: a hook function that will be called once on establishment of + the network connection and once after each block read thereafter. The + hook will be passed three arguments; a count of blocks transferred so + far, a block size in bytes, and the total size of the file. + data: `data` argument passed to `urlopen`. + """ + + def chunk_read(response, chunk_size=8192, reporthook=None): + content_type = response.info().get('Content-Length') + total_size = -1 + if content_type is not None: + total_size = int(content_type.strip()) + count = 0 + while True: + chunk = response.read(chunk_size) + count += 1 + if reporthook is not None: + reporthook(count, chunk_size, total_size) + if chunk: + yield chunk + else: + break + + response = urlopen(url, data) + with open(filename, 'wb') as fd: + for chunk in chunk_read(response, reporthook=reporthook): + fd.write(chunk) +else: + from urllib.request import urlretrieve # pylint: disable=g-importing-member + + +def is_generator_or_sequence(x): + """Check if `x` is a Keras generator type.""" + builtin_iterators = (str, list, tuple, dict, set, frozenset) + if isinstance(x, (tensor.Tensor, np.ndarray) + builtin_iterators): + return False + return (tf_inspect.isgenerator(x) or + isinstance(x, Sequence) or + isinstance(x, typing.Iterator)) + + +def _extract_archive(file_path, path='.', archive_format='auto'): + """Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats. + + Args: + file_path: path to the archive file + path: path to extract the archive file + archive_format: Archive format to try for extracting the file. + Options are 'auto', 'tar', 'zip', and None. + 'tar' includes tar, tar.gz, and tar.bz files. + The default 'auto' is ['tar', 'zip']. + None or an empty list will return no matches found. + + Returns: + True if a match was found and an archive extraction was completed, + False otherwise. + """ + if archive_format is None: + return False + if archive_format == 'auto': + archive_format = ['tar', 'zip'] + if isinstance(archive_format, str): + archive_format = [archive_format] + + file_path = path_to_string(file_path) + path = path_to_string(path) + + for archive_type in archive_format: + if archive_type == 'tar': + open_fn = tarfile.open + is_match_fn = tarfile.is_tarfile + if archive_type == 'zip': + open_fn = zipfile.ZipFile + is_match_fn = zipfile.is_zipfile + + if is_match_fn(file_path): + with open_fn(file_path) as archive: + try: + archive.extractall(path) + except (tarfile.TarError, RuntimeError, KeyboardInterrupt): + if os.path.exists(path): + if os.path.isfile(path): + os.remove(path) + else: + shutil.rmtree(path) + raise + return True + return False + + +def get_file(fname, + origin, + untar=False, + md5_hash=None, + file_hash=None, + cache_subdir='datasets', + hash_algorithm='auto', + extract=False, + archive_format='auto', + cache_dir=None): + """Downloads a file from a URL if it not already in the cache. + + By default the file at the url `origin` is downloaded to the + cache_dir `~/.keras`, placed in the cache_subdir `datasets`, + and given the filename `fname`. The final location of a file + `example.txt` would therefore be `~/.keras/datasets/example.txt`. + + Files in tar, tar.gz, tar.bz, and zip formats can also be extracted. + Passing a hash will verify the file after download. The command line + programs `shasum` and `sha256sum` can compute the hash. + + Example: + + ```python + path_to_downloaded_file = tf.keras.utils.get_file( + "flower_photos", + "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz", + untar=True) + ``` + + Args: + fname: Name of the file. If an absolute path `/path/to/file.txt` is + specified the file will be saved at that location. + origin: Original URL of the file. + untar: Deprecated in favor of `extract` argument. + boolean, whether the file should be decompressed + md5_hash: Deprecated in favor of `file_hash` argument. + md5 hash of the file for verification + file_hash: The expected hash string of the file after download. + The sha256 and md5 hash algorithms are both supported. + cache_subdir: Subdirectory under the Keras cache dir where the file is + saved. If an absolute path `/path/to/folder` is + specified the file will be saved at that location. + hash_algorithm: Select the hash algorithm to verify the file. + options are `'md5'`, `'sha256'`, and `'auto'`. + The default 'auto' detects the hash algorithm in use. + extract: True tries extracting the file as an Archive, like tar or zip. + archive_format: Archive format to try for extracting the file. + Options are `'auto'`, `'tar'`, `'zip'`, and `None`. + `'tar'` includes tar, tar.gz, and tar.bz files. + The default `'auto'` corresponds to `['tar', 'zip']`. + None or an empty list will return no matches found. + cache_dir: Location to store cached files, when None it + defaults to the default directory `~/.keras/`. + + Returns: + Path to the downloaded file + """ + if cache_dir is None: + cache_dir = os.path.join(os.path.expanduser('~'), '.keras') + if md5_hash is not None and file_hash is None: + file_hash = md5_hash + hash_algorithm = 'md5' + datadir_base = os.path.expanduser(cache_dir) + if not os.access(datadir_base, os.W_OK): + datadir_base = os.path.join('/tmp', '.keras') + datadir = os.path.join(datadir_base, cache_subdir) + _makedirs_exist_ok(datadir) + + fname = path_to_string(fname) + + if untar: + untar_fpath = os.path.join(datadir, fname) + fpath = untar_fpath + '.tar.gz' + else: + fpath = os.path.join(datadir, fname) + + download = False + if os.path.exists(fpath): + # File found; verify integrity if a hash was provided. + if file_hash is not None: + if not validate_file(fpath, file_hash, algorithm=hash_algorithm): + print('A local file was found, but it seems to be ' + 'incomplete or outdated because the ' + hash_algorithm + + ' file hash does not match the original value of ' + file_hash + + ' so we will re-download the data.') + download = True + else: + download = True + + if download: + print('Downloading data from', origin) + + class ProgressTracker(object): + # Maintain progbar for the lifetime of download. + # This design was chosen for Python 2.7 compatibility. + progbar = None + + def dl_progress(count, block_size, total_size): + if ProgressTracker.progbar is None: + if total_size == -1: + total_size = None + ProgressTracker.progbar = Progbar(total_size) + else: + ProgressTracker.progbar.update(count * block_size) + + error_msg = 'URL fetch failure on {}: {} -- {}' + try: + try: + urlretrieve(origin, fpath, dl_progress) + except urllib.error.HTTPError as e: + raise Exception(error_msg.format(origin, e.code, e.msg)) + except urllib.error.URLError as e: + raise Exception(error_msg.format(origin, e.errno, e.reason)) + except (Exception, KeyboardInterrupt) as e: + if os.path.exists(fpath): + os.remove(fpath) + raise + ProgressTracker.progbar = None + + if untar: + if not os.path.exists(untar_fpath): + _extract_archive(fpath, datadir, archive_format='tar') + return untar_fpath + + if extract: + _extract_archive(fpath, datadir, archive_format) + + return fpath + + +def _makedirs_exist_ok(datadir): + os.makedirs(datadir, exist_ok=True) # pylint: disable=unexpected-keyword-arg + + +def _resolve_hasher(algorithm, file_hash=None): + """Returns hash algorithm as hashlib function.""" + if algorithm == 'sha256': + return hashlib.sha256() + + if algorithm == 'auto' and file_hash is not None and len(file_hash) == 64: + return hashlib.sha256() + + # This is used only for legacy purposes. + return hashlib.md5() + + +def _hash_file(fpath, algorithm='sha256', chunk_size=65535): + """Calculates a file sha256 or md5 hash. + + Example: + + ```python + _hash_file('/path/to/file.zip') + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' + ``` + + Args: + fpath: path to the file being validated + algorithm: hash algorithm, one of `'auto'`, `'sha256'`, or `'md5'`. + The default `'auto'` detects the hash algorithm in use. + chunk_size: Bytes to read at a time, important for large files. + + Returns: + The file hash + """ + if isinstance(algorithm, str): + hasher = _resolve_hasher(algorithm) + else: + hasher = algorithm + + with open(fpath, 'rb') as fpath_file: + for chunk in iter(lambda: fpath_file.read(chunk_size), b''): + hasher.update(chunk) + + return hasher.hexdigest() + + +def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535): + """Validates a file against a sha256 or md5 hash. + + Args: + fpath: path to the file being validated + file_hash: The expected hash string of the file. + The sha256 and md5 hash algorithms are both supported. + algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'. + The default 'auto' detects the hash algorithm in use. + chunk_size: Bytes to read at a time, important for large files. + + Returns: + Whether the file is valid + """ + hasher = _resolve_hasher(algorithm, file_hash) + + if str(_hash_file(fpath, hasher, chunk_size)) == str(file_hash): + return True + else: + return False + + +class ThreadsafeIter(object): + """Wrap an iterator with a lock and propagate exceptions to all threads.""" + + def __init__(self, it): + self.it = it + self.lock = threading.Lock() + + # After a generator throws an exception all subsequent next() calls raise a + # StopIteration Exception. This, however, presents an issue when mixing + # generators and threading because it means the order of retrieval need not + # match the order in which the generator was called. This can make it appear + # that a generator exited normally when in fact the terminating exception is + # just in a different thread. In order to provide thread safety, once + # self.it has thrown an exception we continue to throw the same exception. + self._exception = None + + def __iter__(self): + return self + + def next(self): + return self.__next__() + + def __next__(self): + with self.lock: + if self._exception: + raise self._exception # pylint: disable=raising-bad-type + + try: + return next(self.it) + except Exception as e: + self._exception = e + raise + + +def threadsafe_generator(f): + + @functools.wraps(f) + def g(*a, **kw): + return ThreadsafeIter(f(*a, **kw)) + + return g + + +class Sequence(object): + """Base object for fitting to a sequence of data, such as a dataset. + + Every `Sequence` must implement the `__getitem__` and the `__len__` methods. + If you want to modify your dataset between epochs you may implement + `on_epoch_end`. + The method `__getitem__` should return a complete batch. + + Notes: + + `Sequence` are a safer way to do multiprocessing. This structure guarantees + that the network will only train once + on each sample per epoch which is not the case with generators. + + Examples: + + ```python + from skimage.io import imread + from skimage.transform import resize + import numpy as np + import math + + # Here, `x_set` is list of path to the images + # and `y_set` are the associated classes. + + class CIFAR10Sequence(Sequence): + + def __init__(self, x_set, y_set, batch_size): + self.x, self.y = x_set, y_set + self.batch_size = batch_size + + def __len__(self): + return math.ceil(len(self.x) / self.batch_size) + + def __getitem__(self, idx): + batch_x = self.x[idx * self.batch_size:(idx + 1) * + self.batch_size] + batch_y = self.y[idx * self.batch_size:(idx + 1) * + self.batch_size] + + return np.array([ + resize(imread(file_name), (200, 200)) + for file_name in batch_x]), np.array(batch_y) + ``` + """ + + @abstractmethod + def __getitem__(self, index): + """Gets batch at position `index`. + + Args: + index: position of the batch in the Sequence. + + Returns: + A batch + """ + raise NotImplementedError + + @abstractmethod + def __len__(self): + """Number of batch in the Sequence. + + Returns: + The number of batches in the Sequence. + """ + raise NotImplementedError + + def on_epoch_end(self): + """Method called at the end of every epoch. + """ + pass + + def __iter__(self): + """Create a generator that iterate over the Sequence.""" + for item in (self[i] for i in range(len(self))): + yield item + + +def iter_sequence_infinite(seq): + """Iterates indefinitely over a Sequence. + + Args: + seq: `Sequence` instance. + + Yields: + Batches of data from the `Sequence`. + """ + while True: + for item in seq: + yield item + + +# Global variables to be shared across processes +_SHARED_SEQUENCES = {} +# We use a Value to provide unique id to different processes. +_SEQUENCE_COUNTER = None + + +# Because multiprocessing pools are inherently unsafe, starting from a clean +# state can be essential to avoiding deadlocks. In order to accomplish this, we +# need to be able to check on the status of Pools that we create. +_DATA_POOLS = weakref.WeakSet() +_WORKER_ID_QUEUE = None # Only created if needed. +_WORKER_IDS = set() +_FORCE_THREADPOOL = False +_FORCE_THREADPOOL_LOCK = threading.RLock() + + +def dont_use_multiprocessing_pool(f): + @functools.wraps(f) + def wrapped(*args, **kwargs): + with _FORCE_THREADPOOL_LOCK: + global _FORCE_THREADPOOL + old_force_threadpool, _FORCE_THREADPOOL = _FORCE_THREADPOOL, True + out = f(*args, **kwargs) + _FORCE_THREADPOOL = old_force_threadpool + return out + return wrapped + + +def get_pool_class(use_multiprocessing): + global _FORCE_THREADPOOL + if not use_multiprocessing or _FORCE_THREADPOOL: + return multiprocessing.dummy.Pool # ThreadPool + return multiprocessing.Pool + + +def get_worker_id_queue(): + """Lazily create the queue to track worker ids.""" + global _WORKER_ID_QUEUE + if _WORKER_ID_QUEUE is None: + _WORKER_ID_QUEUE = multiprocessing.Queue() + return _WORKER_ID_QUEUE + + +def init_pool(seqs): + global _SHARED_SEQUENCES + _SHARED_SEQUENCES = seqs + + +def get_index(uid, i): + """Get the value from the Sequence `uid` at index `i`. + + To allow multiple Sequences to be used at the same time, we use `uid` to + get a specific one. A single Sequence would cause the validation to + overwrite the training Sequence. + + Args: + uid: int, Sequence identifier + i: index + + Returns: + The value at index `i`. + """ + return _SHARED_SEQUENCES[uid][i] + + +class SequenceEnqueuer(object): + """Base class to enqueue inputs. + + The task of an Enqueuer is to use parallelism to speed up preprocessing. + This is done with processes or threads. + + Example: + + ```python + enqueuer = SequenceEnqueuer(...) + enqueuer.start() + datas = enqueuer.get() + for data in datas: + # Use the inputs; training, evaluating, predicting. + # ... stop sometime. + enqueuer.stop() + ``` + + The `enqueuer.get()` should be an infinite stream of datas. + """ + + def __init__(self, sequence, + use_multiprocessing=False): + self.sequence = sequence + self.use_multiprocessing = use_multiprocessing + + global _SEQUENCE_COUNTER + if _SEQUENCE_COUNTER is None: + try: + _SEQUENCE_COUNTER = multiprocessing.Value('i', 0) + except OSError: + # In this case the OS does not allow us to use + # multiprocessing. We resort to an int + # for enqueuer indexing. + _SEQUENCE_COUNTER = 0 + + if isinstance(_SEQUENCE_COUNTER, int): + self.uid = _SEQUENCE_COUNTER + _SEQUENCE_COUNTER += 1 + else: + # Doing Multiprocessing.Value += x is not process-safe. + with _SEQUENCE_COUNTER.get_lock(): + self.uid = _SEQUENCE_COUNTER.value + _SEQUENCE_COUNTER.value += 1 + + self.workers = 0 + self.executor_fn = None + self.queue = None + self.run_thread = None + self.stop_signal = None + + def is_running(self): + return self.stop_signal is not None and not self.stop_signal.is_set() + + def start(self, workers=1, max_queue_size=10): + """Starts the handler's workers. + + Args: + workers: Number of workers. + max_queue_size: queue size + (when full, workers could block on `put()`) + """ + if self.use_multiprocessing: + self.executor_fn = self._get_executor_init(workers) + else: + # We do not need the init since it's threads. + self.executor_fn = lambda _: get_pool_class(False)(workers) + self.workers = workers + self.queue = queue.Queue(max_queue_size) + self.stop_signal = threading.Event() + self.run_thread = threading.Thread(target=self._run) + self.run_thread.daemon = True + self.run_thread.start() + + def _send_sequence(self): + """Sends current Iterable to all workers.""" + # For new processes that may spawn + _SHARED_SEQUENCES[self.uid] = self.sequence + + def stop(self, timeout=None): + """Stops running threads and wait for them to exit, if necessary. + + Should be called by the same thread which called `start()`. + + Args: + timeout: maximum time to wait on `thread.join()` + """ + self.stop_signal.set() + with self.queue.mutex: + self.queue.queue.clear() + self.queue.unfinished_tasks = 0 + self.queue.not_full.notify() + self.run_thread.join(timeout) + _SHARED_SEQUENCES[self.uid] = None + + def __del__(self): + if self.is_running(): + self.stop() + + @abstractmethod + def _run(self): + """Submits request to the executor and queue the `Future` objects.""" + raise NotImplementedError + + @abstractmethod + def _get_executor_init(self, workers): + """Gets the Pool initializer for multiprocessing. + + Args: + workers: Number of workers. + + Returns: + Function, a Function to initialize the pool + """ + raise NotImplementedError + + @abstractmethod + def get(self): + """Creates a generator to extract data from the queue. + + Skip the data if it is `None`. + # Returns + Generator yielding tuples `(inputs, targets)` + or `(inputs, targets, sample_weights)`. + """ + raise NotImplementedError + + +class OrderedEnqueuer(SequenceEnqueuer): + """Builds a Enqueuer from a Sequence. + + Args: + sequence: A `tf.keras.utils.data_utils.Sequence` object. + use_multiprocessing: use multiprocessing if True, otherwise threading + shuffle: whether to shuffle the data at the beginning of each epoch + """ + + def __init__(self, sequence, use_multiprocessing=False, shuffle=False): + super(OrderedEnqueuer, self).__init__(sequence, use_multiprocessing) + self.shuffle = shuffle + + def _get_executor_init(self, workers): + """Gets the Pool initializer for multiprocessing. + + Args: + workers: Number of workers. + + Returns: + Function, a Function to initialize the pool + """ + def pool_fn(seqs): + pool = get_pool_class(True)( + workers, initializer=init_pool_generator, + initargs=(seqs, None, get_worker_id_queue())) + _DATA_POOLS.add(pool) + return pool + + return pool_fn + + def _wait_queue(self): + """Wait for the queue to be empty.""" + while True: + time.sleep(0.1) + if self.queue.unfinished_tasks == 0 or self.stop_signal.is_set(): + return + + def _run(self): + """Submits request to the executor and queue the `Future` objects.""" + sequence = list(range(len(self.sequence))) + self._send_sequence() # Share the initial sequence + while True: + if self.shuffle: + random.shuffle(sequence) + + with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor: + for i in sequence: + if self.stop_signal.is_set(): + return + + self.queue.put( + executor.apply_async(get_index, (self.uid, i)), block=True) + + # Done with the current epoch, waiting for the final batches + self._wait_queue() + + if self.stop_signal.is_set(): + # We're done + return + + # Call the internal on epoch end. + self.sequence.on_epoch_end() + self._send_sequence() # Update the pool + + def get(self): + """Creates a generator to extract data from the queue. + + Skip the data if it is `None`. + + Yields: + The next element in the queue, i.e. a tuple + `(inputs, targets)` or + `(inputs, targets, sample_weights)`. + """ + while self.is_running(): + try: + inputs = self.queue.get(block=True, timeout=5).get() + if self.is_running(): + self.queue.task_done() + if inputs is not None: + yield inputs + except queue.Empty: + pass + except Exception as e: # pylint: disable=broad-except + self.stop() + raise e + + +def init_pool_generator(gens, random_seed=None, id_queue=None): + """Initializer function for pool workers. + + Args: + gens: State which should be made available to worker processes. + random_seed: An optional value with which to seed child processes. + id_queue: A multiprocessing Queue of worker ids. This is used to indicate + that a worker process was created by Keras and can be terminated using + the cleanup_all_keras_forkpools utility. + """ + global _SHARED_SEQUENCES + _SHARED_SEQUENCES = gens + + worker_proc = multiprocessing.current_process() + + # name isn't used for anything, but setting a more descriptive name is helpful + # when diagnosing orphaned processes. + worker_proc.name = 'Keras_worker_{}'.format(worker_proc.name) + + if random_seed is not None: + np.random.seed(random_seed + worker_proc.ident) + + if id_queue is not None: + # If a worker dies during init, the pool will just create a replacement. + id_queue.put(worker_proc.ident, block=True, timeout=0.1) + + +def next_sample(uid): + """Gets the next value from the generator `uid`. + + To allow multiple generators to be used at the same time, we use `uid` to + get a specific one. A single generator would cause the validation to + overwrite the training generator. + + Args: + uid: int, generator identifier + + Returns: + The next value of generator `uid`. + """ + return next(_SHARED_SEQUENCES[uid]) + + +class GeneratorEnqueuer(SequenceEnqueuer): + """Builds a queue out of a data generator. + + The provided generator can be finite in which case the class will throw + a `StopIteration` exception. + + Args: + generator: a generator function which yields data + use_multiprocessing: use multiprocessing if True, otherwise threading + random_seed: Initial seed for workers, + will be incremented by one for each worker. + """ + + def __init__(self, generator, + use_multiprocessing=False, + random_seed=None): + super(GeneratorEnqueuer, self).__init__(generator, use_multiprocessing) + self.random_seed = random_seed + + def _get_executor_init(self, workers): + """Gets the Pool initializer for multiprocessing. + + Args: + workers: Number of works. + + Returns: + A Function to initialize the pool + """ + def pool_fn(seqs): + pool = get_pool_class(True)( + workers, initializer=init_pool_generator, + initargs=(seqs, self.random_seed, get_worker_id_queue())) + _DATA_POOLS.add(pool) + return pool + return pool_fn + + def _run(self): + """Submits request to the executor and queue the `Future` objects.""" + self._send_sequence() # Share the initial generator + with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor: + while True: + if self.stop_signal.is_set(): + return + + self.queue.put( + executor.apply_async(next_sample, (self.uid,)), block=True) + + def get(self): + """Creates a generator to extract data from the queue. + + Skip the data if it is `None`. + + Yields: + The next element in the queue, i.e. a tuple + `(inputs, targets)` or + `(inputs, targets, sample_weights)`. + """ + try: + while self.is_running(): + inputs = self.queue.get(block=True).get() + self.queue.task_done() + if inputs is not None: + yield inputs + except StopIteration: + # Special case for finite generators + last_ones = [] + while self.queue.qsize() > 0: + last_ones.append(self.queue.get(block=True)) + # Wait for them to complete + for f in last_ones: + f.wait() + # Keep the good ones + last_ones = [future.get() for future in last_ones if future.successful()] + for inputs in last_ones: + if inputs is not None: + yield inputs + except Exception as e: # pylint: disable=broad-except + self.stop() + if 'generator already executing' in str(e): + raise RuntimeError( + 'Your generator is NOT thread-safe. ' + 'Keras requires a thread-safe generator when ' + '`use_multiprocessing=False, workers > 1`. ') + raise e diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/dataset_creator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/dataset_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..b318e2dd7fa4a525c4b732f1a87777fa8d17007a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/dataset_creator.py @@ -0,0 +1,99 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-classes-have-attributes +"""Input dataset creator for `model.fit`.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.types import data as data_types + + +class DatasetCreator(object): + """Object that returns a `tf.data.Dataset` upon invoking. + + `tf.keras.utils.experimental.DatasetCreator` is designated as a supported type + for `x`, or the input, in `tf.keras.Model.fit`. Pass an instance of this class + to `fit` when using a callable (with a `input_context` argument) that returns + a `tf.data.Dataset`. + + ```python + model = tf.keras.Sequential([tf.keras.layers.Dense(10)]) + model.compile(tf.keras.optimizers.SGD(), loss="mse") + + def dataset_fn(input_context): + global_batch_size = 64 + batch_size = input_context.get_per_replica_batch_size(global_batch_size) + dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat() + dataset = dataset.shard( + input_context.num_input_pipelines, input_context.input_pipeline_id) + dataset = dataset.batch(batch_size) + dataset = dataset.prefetch(2) + return dataset + + input_options = tf.distribute.InputOptions( + experimental_fetch_to_device=True, + experimental_per_replica_buffer_size=2) + model.fit(tf.keras.utils.experimental.DatasetCreator( + dataset_fn, input_options=input_options), epochs=10, steps_per_epoch=10) + ``` + + `Model.fit` usage with `DatasetCreator` is intended to work across all + `tf.distribute.Strategy`s, as long as `Strategy.scope` is used at model + creation: + + ```python + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver) + with strategy.scope(): + model = tf.keras.Sequential([tf.keras.layers.Dense(10)]) + model.compile(tf.keras.optimizers.SGD(), loss="mse") + ... + ``` + + Note: When using `DatasetCreator`, `steps_per_epoch` argument in `Model.fit` + must be provided as the cardinality of such input cannot be inferred. + + Args: + dataset_fn: A callable that takes a single argument of type + `tf.distribute.InputContext`, which is used for batch size calculation and + cross-worker input pipeline sharding (if neither is needed, the + `InputContext` parameter can be ignored in the `dataset_fn`), and returns + a `tf.data.Dataset`. + input_options: Optional `tf.distribute.InputOptions`, used for specific + options when used with distribution, for example, whether to prefetch + dataset elements to accelerator device memory or host device memory, and + prefetch buffer size in the replica device memory. No effect if not used + with distributed training. See `tf.distribute.InputOptions` for more + information. + """ + + def __init__(self, dataset_fn, input_options=None): + if not callable(dataset_fn): + raise TypeError('`dataset_fn` for `DatasetCreator` must be a `callable`.') + if input_options and (not isinstance(input_options, + distribute_lib.InputOptions)): + raise TypeError('`input_options` for `DatasetCreator` must be a ' + '`tf.distribute.InputOptions`.') + + self.dataset_fn = dataset_fn + self.input_options = input_options + + def __call__(self, *args, **kwargs): + # When a `DatasetCreator` is invoked, it forwards args/kwargs straight to + # the callable. + dataset = self.dataset_fn(*args, **kwargs) + if not isinstance(dataset, data_types.DatasetV2): + raise TypeError('The `callable` provided to `DatasetCreator` must return ' + 'a Dataset.') + return dataset diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/generic_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/generic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4a321f9bdd0215d17d633b929b843260095f6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/generic_utils.py @@ -0,0 +1,1186 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Python utilities required by Keras.""" + +import binascii +import codecs +import importlib +import marshal +import os +import re +import sys +import threading +import time +import types as python_types +import warnings +import weakref + +import numpy as np + +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator + +_GLOBAL_CUSTOM_OBJECTS = {} +_GLOBAL_CUSTOM_NAMES = {} + +# Flag that determines whether to skip the NotImplementedError when calling +# get_config in custom models and layers. This is only enabled when saving to +# SavedModel, when the config isn't required. +_SKIP_FAILED_SERIALIZATION = False +# If a layer does not have a defined config, then the returned config will be a +# dictionary with the below key. +_LAYER_UNDEFINED_CONFIG_KEY = 'layer was saved without config' + + +class CustomObjectScope(object): + """Exposes custom classes/functions to Keras deserialization internals. + + Under a scope `with custom_object_scope(objects_dict)`, Keras methods such + as `tf.keras.models.load_model` or `tf.keras.models.model_from_config` + will be able to deserialize any custom object referenced by a + saved config (e.g. a custom layer or metric). + + Example: + + Consider a custom regularizer `my_regularizer`: + + ```python + layer = Dense(3, kernel_regularizer=my_regularizer) + config = layer.get_config() # Config contains a reference to `my_regularizer` + ... + # Later: + with custom_object_scope({'my_regularizer': my_regularizer}): + layer = Dense.from_config(config) + ``` + + Args: + *args: Dictionary or dictionaries of `{name: object}` pairs. + """ + + def __init__(self, *args): + self.custom_objects = args + self.backup = None + + def __enter__(self): + self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() + for objects in self.custom_objects: + _GLOBAL_CUSTOM_OBJECTS.update(objects) + return self + + def __exit__(self, *args, **kwargs): + _GLOBAL_CUSTOM_OBJECTS.clear() + _GLOBAL_CUSTOM_OBJECTS.update(self.backup) + + +def get_custom_objects(): + """Retrieves a live reference to the global dictionary of custom objects. + + Updating and clearing custom objects using `custom_object_scope` + is preferred, but `get_custom_objects` can + be used to directly access the current collection of custom objects. + + Example: + + ```python + get_custom_objects().clear() + get_custom_objects()['MyObject'] = MyObject + ``` + + Returns: + Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). + """ + return _GLOBAL_CUSTOM_OBJECTS + + +# Store a unique, per-object ID for shared objects. +# +# We store a unique ID for each object so that we may, at loading time, +# re-create the network properly. Without this ID, we would have no way of +# determining whether a config is a description of a new object that +# should be created or is merely a reference to an already-created object. +SHARED_OBJECT_KEY = 'shared_object_id' + + +SHARED_OBJECT_DISABLED = threading.local() +SHARED_OBJECT_LOADING = threading.local() +SHARED_OBJECT_SAVING = threading.local() + + +# Attributes on the threadlocal variable must be set per-thread, thus we +# cannot initialize these globally. Instead, we have accessor functions with +# default values. +def _shared_object_disabled(): + """Get whether shared object handling is disabled in a threadsafe manner.""" + return getattr(SHARED_OBJECT_DISABLED, 'disabled', False) + + +def _shared_object_loading_scope(): + """Get the current shared object saving scope in a threadsafe manner.""" + return getattr(SHARED_OBJECT_LOADING, 'scope', NoopLoadingScope()) + + +def _shared_object_saving_scope(): + """Get the current shared object saving scope in a threadsafe manner.""" + return getattr(SHARED_OBJECT_SAVING, 'scope', None) + + +class DisableSharedObjectScope(object): + """A context manager for disabling handling of shared objects. + + Disables shared object handling for both saving and loading. + + Created primarily for use with `clone_model`, which does extra surgery that + is incompatible with shared objects. + """ + + def __enter__(self): + SHARED_OBJECT_DISABLED.disabled = True + self._orig_loading_scope = _shared_object_loading_scope() + self._orig_saving_scope = _shared_object_saving_scope() + + def __exit__(self, *args, **kwargs): + SHARED_OBJECT_DISABLED.disabled = False + SHARED_OBJECT_LOADING.scope = self._orig_loading_scope + SHARED_OBJECT_SAVING.scope = self._orig_saving_scope + + +class NoopLoadingScope(object): + """The default shared object loading scope. It does nothing. + + Created to simplify serialization code that doesn't care about shared objects + (e.g. when serializing a single object). + """ + + def get(self, unused_object_id): + return None + + def set(self, object_id, obj): + pass + + +class SharedObjectLoadingScope(object): + """A context manager for keeping track of loaded objects. + + During the deserialization process, we may come across objects that are + shared across multiple layers. In order to accurately restore the network + structure to its original state, `SharedObjectLoadingScope` allows us to + re-use shared objects rather than cloning them. + """ + + def __enter__(self): + if _shared_object_disabled(): + return NoopLoadingScope() + + global SHARED_OBJECT_LOADING + SHARED_OBJECT_LOADING.scope = self + self._obj_ids_to_obj = {} + return self + + def get(self, object_id): + """Given a shared object ID, returns a previously instantiated object. + + Args: + object_id: shared object ID to use when attempting to find already-loaded + object. + + Returns: + The object, if we've seen this ID before. Else, `None`. + """ + # Explicitly check for `None` internally to make external calling code a + # bit cleaner. + if object_id is None: + return + return self._obj_ids_to_obj.get(object_id) + + def set(self, object_id, obj): + """Stores an instantiated object for future lookup and sharing.""" + if object_id is None: + return + self._obj_ids_to_obj[object_id] = obj + + def __exit__(self, *args, **kwargs): + global SHARED_OBJECT_LOADING + SHARED_OBJECT_LOADING.scope = NoopLoadingScope() + + +class SharedObjectConfig(dict): + """A configuration container that keeps track of references. + + `SharedObjectConfig` will automatically attach a shared object ID to any + configs which are referenced more than once, allowing for proper shared + object reconstruction at load time. + + In most cases, it would be more proper to subclass something like + `collections.UserDict` or `collections.Mapping` rather than `dict` directly. + Unfortunately, python's json encoder does not support `Mapping`s. This is + important functionality to retain, since we are dealing with serialization. + + We should be safe to subclass `dict` here, since we aren't actually + overriding any core methods, only augmenting with a new one for reference + counting. + """ + + def __init__(self, base_config, object_id, **kwargs): + self.ref_count = 1 + self.object_id = object_id + super(SharedObjectConfig, self).__init__(base_config, **kwargs) + + def increment_ref_count(self): + # As soon as we've seen the object more than once, we want to attach the + # shared object ID. This allows us to only attach the shared object ID when + # it's strictly necessary, making backwards compatibility breakage less + # likely. + if self.ref_count == 1: + self[SHARED_OBJECT_KEY] = self.object_id + self.ref_count += 1 + + +class SharedObjectSavingScope(object): + """Keeps track of shared object configs when serializing.""" + + def __enter__(self): + if _shared_object_disabled(): + return None + + global SHARED_OBJECT_SAVING + + # Serialization can happen at a number of layers for a number of reasons. + # We may end up with a case where we're opening a saving scope within + # another saving scope. In that case, we'd like to use the outermost scope + # available and ignore inner scopes, since there is not (yet) a reasonable + # use case for having these nested and distinct. + if _shared_object_saving_scope() is not None: + self._passthrough = True + return _shared_object_saving_scope() + else: + self._passthrough = False + + SHARED_OBJECT_SAVING.scope = self + self._shared_objects_config = weakref.WeakKeyDictionary() + self._next_id = 0 + return self + + def get_config(self, obj): + """Gets a `SharedObjectConfig` if one has already been seen for `obj`. + + Args: + obj: The object for which to retrieve the `SharedObjectConfig`. + + Returns: + The SharedObjectConfig for a given object, if already seen. Else, + `None`. + """ + try: + shared_object_config = self._shared_objects_config[obj] + except (TypeError, KeyError): + # If the object is unhashable (e.g. a subclass of `AbstractBaseClass` + # that has not overridden `__hash__`), a `TypeError` will be thrown. + # We'll just continue on without shared object support. + return None + shared_object_config.increment_ref_count() + return shared_object_config + + def create_config(self, base_config, obj): + """Create a new SharedObjectConfig for a given object.""" + shared_object_config = SharedObjectConfig(base_config, self._next_id) + self._next_id += 1 + try: + self._shared_objects_config[obj] = shared_object_config + except TypeError: + # If the object is unhashable (e.g. a subclass of `AbstractBaseClass` + # that has not overridden `__hash__`), a `TypeError` will be thrown. + # We'll just continue on without shared object support. + pass + return shared_object_config + + def __exit__(self, *args, **kwargs): + if not getattr(self, '_passthrough', False): + global SHARED_OBJECT_SAVING + SHARED_OBJECT_SAVING.scope = None + + +def serialize_keras_class_and_config( + cls_name, cls_config, obj=None, shared_object_id=None): + """Returns the serialization of the class with the given config.""" + base_config = {'class_name': cls_name, 'config': cls_config} + + # We call `serialize_keras_class_and_config` for some branches of the load + # path. In that case, we may already have a shared object ID we'd like to + # retain. + if shared_object_id is not None: + base_config[SHARED_OBJECT_KEY] = shared_object_id + + # If we have an active `SharedObjectSavingScope`, check whether we've already + # serialized this config. If so, just use that config. This will store an + # extra ID field in the config, allowing us to re-create the shared object + # relationship at load time. + if _shared_object_saving_scope() is not None and obj is not None: + shared_object_config = _shared_object_saving_scope().get_config(obj) + if shared_object_config is None: + return _shared_object_saving_scope().create_config(base_config, obj) + return shared_object_config + + return base_config + + +def register_keras_serializable(package='Custom', name=None): + """Registers an object with the Keras serialization framework. + + This decorator injects the decorated class or function into the Keras custom + object dictionary, so that it can be serialized and deserialized without + needing an entry in the user-provided custom object dict. It also injects a + function that Keras will call to get the object's serializable string key. + + Note that to be serialized and deserialized, classes must implement the + `get_config()` method. Functions do not have this requirement. + + The object will be registered under the key 'package>name' where `name`, + defaults to the object name if not passed. + + Args: + package: The package that this class belongs to. + name: The name to serialize this class under in this package. If None, the + class' name will be used. + + Returns: + A decorator that registers the decorated class with the passed names. + """ + + def decorator(arg): + """Registers a class with the Keras serialization framework.""" + class_name = name if name is not None else arg.__name__ + registered_name = package + '>' + class_name + + if tf_inspect.isclass(arg) and not hasattr(arg, 'get_config'): + raise ValueError( + 'Cannot register a class that does not have a get_config() method.') + + if registered_name in _GLOBAL_CUSTOM_OBJECTS: + raise ValueError( + '%s has already been registered to %s' % + (registered_name, _GLOBAL_CUSTOM_OBJECTS[registered_name])) + + if arg in _GLOBAL_CUSTOM_NAMES: + raise ValueError('%s has already been registered to %s' % + (arg, _GLOBAL_CUSTOM_NAMES[arg])) + _GLOBAL_CUSTOM_OBJECTS[registered_name] = arg + _GLOBAL_CUSTOM_NAMES[arg] = registered_name + + return arg + + return decorator + + +def get_registered_name(obj): + """Returns the name registered to an object within the Keras framework. + + This function is part of the Keras serialization and deserialization + framework. It maps objects to the string names associated with those objects + for serialization/deserialization. + + Args: + obj: The object to look up. + + Returns: + The name associated with the object, or the default Python name if the + object is not registered. + """ + if obj in _GLOBAL_CUSTOM_NAMES: + return _GLOBAL_CUSTOM_NAMES[obj] + else: + return obj.__name__ + + +@tf_contextlib.contextmanager +def skip_failed_serialization(): + global _SKIP_FAILED_SERIALIZATION + prev = _SKIP_FAILED_SERIALIZATION + try: + _SKIP_FAILED_SERIALIZATION = True + yield + finally: + _SKIP_FAILED_SERIALIZATION = prev + + +def get_registered_object(name, custom_objects=None, module_objects=None): + """Returns the class associated with `name` if it is registered with Keras. + + This function is part of the Keras serialization and deserialization + framework. It maps strings to the objects associated with them for + serialization/deserialization. + + Example: + ``` + def from_config(cls, config, custom_objects=None): + if 'my_custom_object_name' in config: + config['hidden_cls'] = tf.keras.utils.get_registered_object( + config['my_custom_object_name'], custom_objects=custom_objects) + ``` + + Args: + name: The name to look up. + custom_objects: A dictionary of custom objects to look the name up in. + Generally, custom_objects is provided by the user. + module_objects: A dictionary of custom objects to look the name up in. + Generally, module_objects is provided by midlevel library implementers. + + Returns: + An instantiable class associated with 'name', or None if no such class + exists. + """ + if name in _GLOBAL_CUSTOM_OBJECTS: + return _GLOBAL_CUSTOM_OBJECTS[name] + elif custom_objects and name in custom_objects: + return custom_objects[name] + elif module_objects and name in module_objects: + return module_objects[name] + return None + + +# pylint: disable=g-bad-exception-name +class CustomMaskWarning(Warning): + pass +# pylint: enable=g-bad-exception-name + + +def serialize_keras_object(instance): + """Serialize a Keras object into a JSON-compatible representation. + + Calls to `serialize_keras_object` while underneath the + `SharedObjectSavingScope` context manager will cause any objects re-used + across multiple layers to be saved with a special shared object ID. This + allows the network to be re-created properly during deserialization. + + Args: + instance: The object to serialize. + + Returns: + A dict-like, JSON-compatible representation of the object's config. + """ + _, instance = tf_decorator.unwrap(instance) + if instance is None: + return None + + # pylint: disable=protected-access + # + # For v1 layers, checking supports_masking is not enough. We have to also + # check whether compute_mask has been overridden. + supports_masking = (getattr(instance, 'supports_masking', False) + or (hasattr(instance, 'compute_mask') + and not is_default(instance.compute_mask))) + if supports_masking and is_default(instance.get_config): + warnings.warn('Custom mask layers require a config and must override ' + 'get_config. When loading, the custom mask layer must be ' + 'passed to the custom_objects argument.', + category=CustomMaskWarning) + # pylint: enable=protected-access + + if hasattr(instance, 'get_config'): + name = get_registered_name(instance.__class__) + try: + config = instance.get_config() + except NotImplementedError as e: + if _SKIP_FAILED_SERIALIZATION: + return serialize_keras_class_and_config( + name, {_LAYER_UNDEFINED_CONFIG_KEY: True}) + raise e + serialization_config = {} + for key, item in config.items(): + if isinstance(item, str): + serialization_config[key] = item + continue + + # Any object of a different type needs to be converted to string or dict + # for serialization (e.g. custom functions, custom classes) + try: + serialized_item = serialize_keras_object(item) + if isinstance(serialized_item, dict) and not isinstance(item, dict): + serialized_item['__passive_serialization__'] = True + serialization_config[key] = serialized_item + except ValueError: + serialization_config[key] = item + + name = get_registered_name(instance.__class__) + return serialize_keras_class_and_config( + name, serialization_config, instance) + if hasattr(instance, '__name__'): + return get_registered_name(instance) + raise ValueError('Cannot serialize', instance) + + +def get_custom_objects_by_name(item, custom_objects=None): + """Returns the item if it is in either local or global custom objects.""" + if item in _GLOBAL_CUSTOM_OBJECTS: + return _GLOBAL_CUSTOM_OBJECTS[item] + elif custom_objects and item in custom_objects: + return custom_objects[item] + return None + + +def class_and_config_for_serialized_keras_object( + config, + module_objects=None, + custom_objects=None, + printable_module_name='object'): + """Returns the class name and config for a serialized keras object.""" + if (not isinstance(config, dict) + or 'class_name' not in config + or 'config' not in config): + raise ValueError('Improper config format: ' + str(config)) + + class_name = config['class_name'] + cls = get_registered_object(class_name, custom_objects, module_objects) + if cls is None: + raise ValueError( + 'Unknown {}: {}. Please ensure this object is ' + 'passed to the `custom_objects` argument. See ' + 'https://www.tensorflow.org/guide/keras/save_and_serialize' + '#registering_the_custom_object for details.' + .format(printable_module_name, class_name)) + + cls_config = config['config'] + # Check if `cls_config` is a list. If it is a list, return the class and the + # associated class configs for recursively deserialization. This case will + # happen on the old version of sequential model (e.g. `keras_version` == + # "2.0.6"), which is serialized in a different structure, for example + # "{'class_name': 'Sequential', + # 'config': [{'class_name': 'Embedding', 'config': ...}, {}, ...]}". + if isinstance(cls_config, list): + return (cls, cls_config) + + deserialized_objects = {} + for key, item in cls_config.items(): + if key == 'name': + # Assume that the value of 'name' is a string that should not be + # deserialized as a function. This avoids the corner case where + # cls_config['name'] has an identical name to a custom function and + # gets converted into that function. + deserialized_objects[key] = item + elif isinstance(item, dict) and '__passive_serialization__' in item: + deserialized_objects[key] = deserialize_keras_object( + item, + module_objects=module_objects, + custom_objects=custom_objects, + printable_module_name='config_item') + # TODO(momernick): Should this also have 'module_objects'? + elif (isinstance(item, str) and + tf_inspect.isfunction(get_registered_object(item, custom_objects))): + # Handle custom functions here. When saving functions, we only save the + # function's name as a string. If we find a matching string in the custom + # objects during deserialization, we convert the string back to the + # original function. + # Note that a potential issue is that a string field could have a naming + # conflict with a custom function name, but this should be a rare case. + # This issue does not occur if a string field has a naming conflict with + # a custom object, since the config of an object will always be a dict. + deserialized_objects[key] = get_registered_object(item, custom_objects) + for key, item in deserialized_objects.items(): + cls_config[key] = deserialized_objects[key] + + return (cls, cls_config) + + +def deserialize_keras_object(identifier, + module_objects=None, + custom_objects=None, + printable_module_name='object'): + """Turns the serialized form of a Keras object back into an actual object. + + This function is for mid-level library implementers rather than end users. + + Importantly, this utility requires you to provide the dict of `module_objects` + to use for looking up the object config; this is not populated by default. + If you need a deserialization utility that has preexisting knowledge of + built-in Keras objects, use e.g. `keras.layers.deserialize(config)`, + `keras.metrics.deserialize(config)`, etc. + + Calling `deserialize_keras_object` while underneath the + `SharedObjectLoadingScope` context manager will cause any already-seen shared + objects to be returned as-is rather than creating a new object. + + Args: + identifier: the serialized form of the object. + module_objects: A dictionary of built-in objects to look the name up in. + Generally, `module_objects` is provided by midlevel library implementers. + custom_objects: A dictionary of custom objects to look the name up in. + Generally, `custom_objects` is provided by the end user. + printable_module_name: A human-readable string representing the type of the + object. Printed in case of exception. + + Returns: + The deserialized object. + + Example: + + A mid-level library implementer might want to implement a utility for + retrieving an object from its config, as such: + + ```python + def deserialize(config, custom_objects=None): + return deserialize_keras_object( + identifier, + module_objects=globals(), + custom_objects=custom_objects, + name="MyObjectType", + ) + ``` + + This is how e.g. `keras.layers.deserialize()` is implemented. + """ + if identifier is None: + return None + + if isinstance(identifier, dict): + # In this case we are dealing with a Keras config dictionary. + config = identifier + (cls, cls_config) = class_and_config_for_serialized_keras_object( + config, module_objects, custom_objects, printable_module_name) + + # If this object has already been loaded (i.e. it's shared between multiple + # objects), return the already-loaded object. + shared_object_id = config.get(SHARED_OBJECT_KEY) + shared_object = _shared_object_loading_scope().get(shared_object_id) # pylint: disable=assignment-from-none + if shared_object is not None: + return shared_object + + if hasattr(cls, 'from_config'): + arg_spec = tf_inspect.getfullargspec(cls.from_config) + custom_objects = custom_objects or {} + + if 'custom_objects' in arg_spec.args: + deserialized_obj = cls.from_config( + cls_config, + custom_objects=dict( + list(_GLOBAL_CUSTOM_OBJECTS.items()) + + list(custom_objects.items()))) + else: + with CustomObjectScope(custom_objects): + deserialized_obj = cls.from_config(cls_config) + else: + # Then `cls` may be a function returning a class. + # in this case by convention `config` holds + # the kwargs of the function. + custom_objects = custom_objects or {} + with CustomObjectScope(custom_objects): + deserialized_obj = cls(**cls_config) + + # Add object to shared objects, in case we find it referenced again. + _shared_object_loading_scope().set(shared_object_id, deserialized_obj) + + return deserialized_obj + + elif isinstance(identifier, str): + object_name = identifier + if custom_objects and object_name in custom_objects: + obj = custom_objects.get(object_name) + elif object_name in _GLOBAL_CUSTOM_OBJECTS: + obj = _GLOBAL_CUSTOM_OBJECTS[object_name] + else: + obj = module_objects.get(object_name) + if obj is None: + raise ValueError( + 'Unknown {}: {}. Please ensure this object is ' + 'passed to the `custom_objects` argument. See ' + 'https://www.tensorflow.org/guide/keras/save_and_serialize' + '#registering_the_custom_object for details.' + .format(printable_module_name, object_name)) + + # Classes passed by name are instantiated with no args, functions are + # returned as-is. + if tf_inspect.isclass(obj): + return obj() + return obj + elif tf_inspect.isfunction(identifier): + # If a function has already been deserialized, return as is. + return identifier + else: + raise ValueError('Could not interpret serialized %s: %s' % + (printable_module_name, identifier)) + + +def func_dump(func): + """Serializes a user defined function. + + Args: + func: the function to serialize. + + Returns: + A tuple `(code, defaults, closure)`. + """ + if os.name == 'nt': + raw_code = marshal.dumps(func.__code__).replace(b'\\', b'/') + code = codecs.encode(raw_code, 'base64').decode('ascii') + else: + raw_code = marshal.dumps(func.__code__) + code = codecs.encode(raw_code, 'base64').decode('ascii') + defaults = func.__defaults__ + if func.__closure__: + closure = tuple(c.cell_contents for c in func.__closure__) + else: + closure = None + return code, defaults, closure + + +def func_load(code, defaults=None, closure=None, globs=None): + """Deserializes a user defined function. + + Args: + code: bytecode of the function. + defaults: defaults of the function. + closure: closure of the function. + globs: dictionary of global objects. + + Returns: + A function object. + """ + if isinstance(code, (tuple, list)): # unpack previous dump + code, defaults, closure = code + if isinstance(defaults, list): + defaults = tuple(defaults) + + def ensure_value_to_cell(value): + """Ensures that a value is converted to a python cell object. + + Args: + value: Any value that needs to be casted to the cell type + + Returns: + A value wrapped as a cell object (see function "func_load") + """ + + def dummy_fn(): + # pylint: disable=pointless-statement + value # just access it so it gets captured in .__closure__ + + cell_value = dummy_fn.__closure__[0] + if not isinstance(value, type(cell_value)): + return cell_value + return value + + if closure is not None: + closure = tuple(ensure_value_to_cell(_) for _ in closure) + try: + raw_code = codecs.decode(code.encode('ascii'), 'base64') + except (UnicodeEncodeError, binascii.Error): + raw_code = code.encode('raw_unicode_escape') + code = marshal.loads(raw_code) + if globs is None: + globs = globals() + return python_types.FunctionType( + code, globs, name=code.co_name, argdefs=defaults, closure=closure) + + +def has_arg(fn, name, accept_all=False): + """Checks if a callable accepts a given keyword argument. + + Args: + fn: Callable to inspect. + name: Check if `fn` can be called with `name` as a keyword argument. + accept_all: What to return if there is no parameter called `name` but the + function accepts a `**kwargs` argument. + + Returns: + bool, whether `fn` accepts a `name` keyword argument. + """ + arg_spec = tf_inspect.getfullargspec(fn) + if accept_all and arg_spec.varkw is not None: + return True + return name in arg_spec.args or name in arg_spec.kwonlyargs + + +class Progbar(object): + """Displays a progress bar. + + Args: + target: Total number of steps expected, None if unknown. + width: Progress bar width on screen. + verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose) + stateful_metrics: Iterable of string names of metrics that should *not* be + averaged over time. Metrics in this list will be displayed as-is. All + others will be averaged by the progbar before display. + interval: Minimum visual progress update interval (in seconds). + unit_name: Display name for step counts (usually "step" or "sample"). + """ + + def __init__(self, + target, + width=30, + verbose=1, + interval=0.05, + stateful_metrics=None, + unit_name='step'): + self.target = target + self.width = width + self.verbose = verbose + self.interval = interval + self.unit_name = unit_name + if stateful_metrics: + self.stateful_metrics = set(stateful_metrics) + else: + self.stateful_metrics = set() + + self._dynamic_display = ((hasattr(sys.stdout, 'isatty') and + sys.stdout.isatty()) or + 'ipykernel' in sys.modules or + 'posix' in sys.modules or + 'PYCHARM_HOSTED' in os.environ) + self._total_width = 0 + self._seen_so_far = 0 + # We use a dict + list to avoid garbage collection + # issues found in OrderedDict + self._values = {} + self._values_order = [] + self._start = time.time() + self._last_update = 0 + + self._time_after_first_step = None + + def update(self, current, values=None, finalize=None): + """Updates the progress bar. + + Args: + current: Index of current step. + values: List of tuples: `(name, value_for_last_step)`. If `name` is in + `stateful_metrics`, `value_for_last_step` will be displayed as-is. + Else, an average of the metric over time will be displayed. + finalize: Whether this is the last update for the progress bar. If + `None`, defaults to `current >= self.target`. + """ + if finalize is None: + if self.target is None: + finalize = False + else: + finalize = current >= self.target + + values = values or [] + for k, v in values: + if k not in self._values_order: + self._values_order.append(k) + if k not in self.stateful_metrics: + # In the case that progress bar doesn't have a target value in the first + # epoch, both on_batch_end and on_epoch_end will be called, which will + # cause 'current' and 'self._seen_so_far' to have the same value. Force + # the minimal value to 1 here, otherwise stateful_metric will be 0s. + value_base = max(current - self._seen_so_far, 1) + if k not in self._values: + self._values[k] = [v * value_base, value_base] + else: + self._values[k][0] += v * value_base + self._values[k][1] += value_base + else: + # Stateful metrics output a numeric value. This representation + # means "take an average from a single value" but keeps the + # numeric formatting. + self._values[k] = [v, 1] + self._seen_so_far = current + + now = time.time() + info = ' - %.0fs' % (now - self._start) + if self.verbose == 1: + if now - self._last_update < self.interval and not finalize: + return + + prev_total_width = self._total_width + if self._dynamic_display: + sys.stdout.write('\b' * prev_total_width) + sys.stdout.write('\r') + else: + sys.stdout.write('\n') + + if self.target is not None: + numdigits = int(np.log10(self.target)) + 1 + bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target) + prog = float(current) / self.target + prog_width = int(self.width * prog) + if prog_width > 0: + bar += ('=' * (prog_width - 1)) + if current < self.target: + bar += '>' + else: + bar += '=' + bar += ('.' * (self.width - prog_width)) + bar += ']' + else: + bar = '%7d/Unknown' % current + + self._total_width = len(bar) + sys.stdout.write(bar) + + time_per_unit = self._estimate_step_duration(current, now) + + if self.target is None or finalize: + if time_per_unit >= 1 or time_per_unit == 0: + info += ' %.0fs/%s' % (time_per_unit, self.unit_name) + elif time_per_unit >= 1e-3: + info += ' %.0fms/%s' % (time_per_unit * 1e3, self.unit_name) + else: + info += ' %.0fus/%s' % (time_per_unit * 1e6, self.unit_name) + else: + eta = time_per_unit * (self.target - current) + if eta > 3600: + eta_format = '%d:%02d:%02d' % (eta // 3600, + (eta % 3600) // 60, eta % 60) + elif eta > 60: + eta_format = '%d:%02d' % (eta // 60, eta % 60) + else: + eta_format = '%ds' % eta + + info = ' - ETA: %s' % eta_format + + for k in self._values_order: + info += ' - %s:' % k + if isinstance(self._values[k], list): + avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) + if abs(avg) > 1e-3: + info += ' %.4f' % avg + else: + info += ' %.4e' % avg + else: + info += ' %s' % self._values[k] + + self._total_width += len(info) + if prev_total_width > self._total_width: + info += (' ' * (prev_total_width - self._total_width)) + + if finalize: + info += '\n' + + sys.stdout.write(info) + sys.stdout.flush() + + elif self.verbose == 2: + if finalize: + numdigits = int(np.log10(self.target)) + 1 + count = ('%' + str(numdigits) + 'd/%d') % (current, self.target) + info = count + info + for k in self._values_order: + info += ' - %s:' % k + avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) + if avg > 1e-3: + info += ' %.4f' % avg + else: + info += ' %.4e' % avg + info += '\n' + + sys.stdout.write(info) + sys.stdout.flush() + + self._last_update = now + + def add(self, n, values=None): + self.update(self._seen_so_far + n, values) + + def _estimate_step_duration(self, current, now): + """Estimate the duration of a single step. + + Given the step number `current` and the corresponding time `now` + this function returns an estimate for how long a single step + takes. If this is called before one step has been completed + (i.e. `current == 0`) then zero is given as an estimate. The duration + estimate ignores the duration of the (assumed to be non-representative) + first step for estimates when more steps are available (i.e. `current>1`). + Args: + current: Index of current step. + now: The current time. + Returns: Estimate of the duration of a single step. + """ + if current: + # there are a few special scenarios here: + # 1) somebody is calling the progress bar without ever supplying step 1 + # 2) somebody is calling the progress bar and supplies step one mulitple + # times, e.g. as part of a finalizing call + # in these cases, we just fall back to the simple calculation + if self._time_after_first_step is not None and current > 1: + time_per_unit = (now - self._time_after_first_step) / (current - 1) + else: + time_per_unit = (now - self._start) / current + + if current == 1: + self._time_after_first_step = now + return time_per_unit + else: + return 0 + + def _update_stateful_metrics(self, stateful_metrics): + self.stateful_metrics = self.stateful_metrics.union(stateful_metrics) + + +def make_batches(size, batch_size): + """Returns a list of batch indices (tuples of indices). + + Args: + size: Integer, total size of the data to slice into batches. + batch_size: Integer, batch size. + + Returns: + A list of tuples of array indices. + """ + num_batches = int(np.ceil(size / float(batch_size))) + return [(i * batch_size, min(size, (i + 1) * batch_size)) + for i in range(0, num_batches)] + + +def slice_arrays(arrays, start=None, stop=None): + """Slice an array or list of arrays. + + This takes an array-like, or a list of + array-likes, and outputs: + - arrays[start:stop] if `arrays` is an array-like + - [x[start:stop] for x in arrays] if `arrays` is a list + + Can also work on list/array of indices: `slice_arrays(x, indices)` + + Args: + arrays: Single array or list of arrays. + start: can be an integer index (start index) or a list/array of indices + stop: integer (stop index); should be None if `start` was a list. + + Returns: + A slice of the array(s). + + Raises: + ValueError: If the value of start is a list and stop is not None. + """ + if arrays is None: + return [None] + if isinstance(start, list) and stop is not None: + raise ValueError('The stop argument has to be None if the value of start ' + 'is a list.') + elif isinstance(arrays, list): + if hasattr(start, '__len__'): + # hdf5 datasets only support list objects as indices + if hasattr(start, 'shape'): + start = start.tolist() + return [None if x is None else x[start] for x in arrays] + return [ + None if x is None else + None if not hasattr(x, '__getitem__') else x[start:stop] for x in arrays + ] + else: + if hasattr(start, '__len__'): + if hasattr(start, 'shape'): + start = start.tolist() + return arrays[start] + if hasattr(start, '__getitem__'): + return arrays[start:stop] + return [None] + + +def to_list(x): + """Normalizes a list/tensor into a list. + + If a tensor is passed, we return + a list of size 1 containing the tensor. + + Args: + x: target object to be normalized. + + Returns: + A list. + """ + if isinstance(x, list): + return x + return [x] + + +def to_snake_case(name): + intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) + insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() + # If the class is private the name starts with "_" which is not secure + # for creating scopes. We prefix the name with "private" in this case. + if insecure[0] != '_': + return insecure + return 'private' + insecure + + +def is_all_none(structure): + iterable = nest.flatten(structure) + # We cannot use Python's `any` because the iterable may return Tensors. + for element in iterable: + if element is not None: + return False + return True + + +def check_for_unexpected_keys(name, input_dict, expected_values): + unknown = set(input_dict.keys()).difference(expected_values) + if unknown: + raise ValueError('Unknown entries in {} dictionary: {}. Only expected ' + 'following keys: {}'.format(name, list(unknown), + expected_values)) + + +def validate_kwargs(kwargs, + allowed_kwargs, + error_message='Keyword argument not understood:'): + """Checks that all keyword arguments are in the set of allowed keys.""" + for kwarg in kwargs: + if kwarg not in allowed_kwargs: + raise TypeError(error_message, kwarg) + + +def validate_config(config): + """Determines whether config appears to be a valid layer config.""" + return isinstance(config, dict) and _LAYER_UNDEFINED_CONFIG_KEY not in config + + +def default(method): + """Decorates a method to detect overrides in subclasses.""" + method._is_default = True # pylint: disable=protected-access + return method + + +def is_default(method): + """Check if a method is decorated with the `default` wrapper.""" + return getattr(method, '_is_default', False) + + +def populate_dict_with_module_objects(target_dict, modules, obj_filter): + for module in modules: + for name in dir(module): + obj = getattr(module, name) + if obj_filter(obj): + target_dict[name] = obj + + +class LazyLoader(python_types.ModuleType): + """Lazily import a module, mainly to avoid pulling in large dependencies.""" + + def __init__(self, local_name, parent_module_globals, name): + self._local_name = local_name + self._parent_module_globals = parent_module_globals + super(LazyLoader, self).__init__(name) + + def _load(self): + """Load the module and insert it into the parent's globals.""" + # Import the target module and insert it into the parent's namespace + module = importlib.import_module(self.__name__) + self._parent_module_globals[self._local_name] = module + # Update this object's dict so that if someone keeps a reference to the + # LazyLoader, lookups are efficient (__getattr__ is only called on lookups + # that fail). + self.__dict__.update(module.__dict__) + return module + + def __getattr__(self, item): + module = self._load() + return getattr(module, item) + + +# Aliases + +custom_object_scope = CustomObjectScope # pylint: disable=invalid-name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/io_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/io_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eb05391bb30da7bc764c070e1b526882973aba1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/io_utils.py @@ -0,0 +1,59 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-import-not-at-top +"""Utilities related to disk I/O.""" + +import os + + +def path_to_string(path): + """Convert `PathLike` objects to their string representation. + + If given a non-string typed path object, converts it to its string + representation. + + If the object passed to `path` is not among the above, then it is + returned unchanged. This allows e.g. passthrough of file objects + through this function. + + Args: + path: `PathLike` object that represents a path + + Returns: + A string representation of the path argument, if Python support exists. + """ + if isinstance(path, os.PathLike): + return os.fspath(path) + return path + + +def ask_to_proceed_with_overwrite(filepath): + """Produces a prompt asking about overwriting a file. + + Args: + filepath: the path to the file to be overwritten. + + Returns: + True if we can proceed with overwrite, False otherwise. + """ + overwrite = input('[WARNING] %s already exists - overwrite? ' + '[y/n]' % (filepath)).strip().lower() + while overwrite not in ('y', 'n'): + overwrite = input('Enter "y" (overwrite) or "n" ' + '(cancel).').strip().lower() + if overwrite == 'n': + return False + print('[TIP] Next time specify overwrite=True!') + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/kernelized_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/kernelized_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20c3a9f4886c567809c9414ed98ece82c798ce69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/kernelized_utils.py @@ -0,0 +1,113 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility methods related to kernelized layers.""" + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops + + +def _to_matrix(u): + """If input tensor is a vector (i.e., has rank 1), converts it to matrix.""" + u_rank = len(u.shape) + if u_rank not in [1, 2]: + raise ValueError('The input tensor should have rank 1 or 2. Given rank: {}' + .format(u_rank)) + if u_rank == 1: + return array_ops.expand_dims(u, 0) + return u + + +def _align_matrices(x, y): + """Aligns x and y tensors to allow computations over pairs of their rows.""" + x_matrix = _to_matrix(x) + y_matrix = _to_matrix(y) + x_shape = x_matrix.shape + y_shape = y_matrix.shape + if y_shape[1] != x_shape[1]: # dimensions do not match. + raise ValueError( + 'The outermost dimensions of the input tensors should match. Given: {} ' + 'vs {}.'.format(y_shape[1], x_shape[1])) + + x_tile = array_ops.tile( + array_ops.expand_dims(x_matrix, 1), [1, y_shape[0], 1]) + y_tile = array_ops.tile( + array_ops.expand_dims(y_matrix, 0), [x_shape[0], 1, 1]) + return x_tile, y_tile + + +def inner_product(u, v): + u = _to_matrix(u) + v = _to_matrix(v) + return math_ops.matmul(u, v, transpose_b=True) + + +def exact_gaussian_kernel(x, y, stddev): + r"""Computes exact Gaussian kernel value(s) for tensors x and y and stddev. + + The Gaussian kernel for vectors u, v is defined as follows: + K(u, v) = exp(-||u-v||^2 / (2* stddev^2)) + where the norm is the l2-norm. x, y can be either vectors or matrices. If they + are vectors, they must have the same dimension. If they are matrices, they + must have the same number of columns. In the latter case, the method returns + (as a matrix) K(u, v) values for all pairs (u, v) where u is a row from x and + v is a row from y. + + Args: + x: a tensor of rank 1 or 2. It's shape should be either [dim] or [m, dim]. + y: a tensor of rank 1 or 2. It's shape should be either [dim] or [n, dim]. + stddev: The width of the Gaussian kernel. + + Returns: + A single value (scalar) with shape (1, 1) (if x, y are vectors) or a matrix + of shape (m, n) with entries K(u, v) (where K is the Gaussian kernel) for + all (u,v) pairs where u, v are rows from x and y respectively. + + Raises: + ValueError: if the shapes of x, y are not compatible. + """ + x_aligned, y_aligned = _align_matrices(x, y) + diff_squared_l2_norm = math_ops.reduce_sum( + math_ops.squared_difference(x_aligned, y_aligned), 2) + return math_ops.exp(-diff_squared_l2_norm / (2 * stddev * stddev)) + + +def exact_laplacian_kernel(x, y, stddev): + r"""Computes exact Laplacian kernel value(s) for tensors x and y using stddev. + + The Laplacian kernel for vectors u, v is defined as follows: + K(u, v) = exp(-||u-v|| / stddev) + where the norm is the l1-norm. x, y can be either vectors or matrices. If they + are vectors, they must have the same dimension. If they are matrices, they + must have the same number of columns. In the latter case, the method returns + (as a matrix) K(u, v) values for all pairs (u, v) where u is a row from x and + v is a row from y. + + Args: + x: a tensor of rank 1 or 2. It's shape should be either [dim] or [m, dim]. + y: a tensor of rank 1 or 2. It's shape should be either [dim] or [n, dim]. + stddev: The width of the Gaussian kernel. + + Returns: + A single value (scalar) with shape (1, 1) if x, y are vectors or a matrix + of shape (m, n) with entries K(u, v) (where K is the Laplacian kernel) for + all (u,v) pairs where u, v are rows from x and y respectively. + + Raises: + ValueError: if the shapes of x, y are not compatible. + """ + x_aligned, y_aligned = _align_matrices(x, y) + diff_l1_norm = math_ops.reduce_sum( + math_ops.abs(math_ops.subtract(x_aligned, y_aligned)), 2) + return math_ops.exp(-diff_l1_norm / stddev) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/layer_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/layer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..76b0b138596d66347ef8f716836f06ed5670f223 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/layer_utils.py @@ -0,0 +1,432 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Utilities related to layer/model functionality.""" + +import functools +import weakref + +import numpy as np + +from tensorflow.python.util import nest + + +def get_source_inputs(tensor, layer=None, node_index=None): + """Returns the list of input tensors necessary to compute `tensor`. + + Output will always be a list of tensors + (potentially with 1 element). + + Args: + tensor: The tensor to start from. + layer: Origin layer of the tensor. Will be + determined via tensor._keras_history if not provided. + node_index: Origin node index of the tensor. + + Returns: + List of input tensors. + """ + if not hasattr(tensor, '_keras_history'): + return tensor + + if layer is None or node_index: + layer, node_index, _ = tensor._keras_history + if not layer._inbound_nodes: + return [tensor] + else: + node = layer._inbound_nodes[node_index] + if node.is_input: + # Reached an Input layer, stop recursion. + return nest.flatten(node.input_tensors) + else: + source_tensors = [] + for layer, node_index, _, tensor in node.iterate_inbound(): + previous_sources = get_source_inputs(tensor, layer, node_index) + # Avoid input redundancy. + for x in previous_sources: + if all(x is not t for t in source_tensors): + source_tensors.append(x) + return source_tensors + + +def validate_string_arg(input_data, + allowable_strings, + layer_name, + arg_name, + allow_none=False, + allow_callables=False): + """Validates the correctness of a string-based arg.""" + if allow_none and input_data is None: + return + elif allow_callables and callable(input_data): + return + elif isinstance(input_data, str) and input_data in allowable_strings: + return + else: + allowed_args = '`None`, ' if allow_none else '' + allowed_args += 'a `Callable`, ' if allow_callables else '' + allowed_args += 'or one of the following values: %s' % (allowable_strings,) + raise ValueError(('The %s argument of layer %s received an invalid ' + 'value %s. Allowed values are: %s.') % + (arg_name, layer_name, input_data, allowed_args)) + + +def count_params(weights): + """Count the total number of scalars composing the weights. + + Args: + weights: An iterable containing the weights on which to compute params + + Returns: + The total number of scalars composing the weights + """ + unique_weights = {id(w): w for w in weights}.values() + weight_shapes = [w.shape.as_list() for w in unique_weights] + standardized_weight_shapes = [ + [0 if w_i is None else w_i for w_i in w] for w in weight_shapes + ] + return int(sum(np.prod(p) for p in standardized_weight_shapes)) + + +def print_summary(model, line_length=None, positions=None, print_fn=None): + """Prints a summary of a model. + + Args: + model: Keras model instance. + line_length: Total length of printed lines + (e.g. set this to adapt the display to different + terminal window sizes). + positions: Relative or absolute positions of log elements in each line. + If not provided, defaults to `[.33, .55, .67, 1.]`. + print_fn: Print function to use. + It will be called on each line of the summary. + You can set it to a custom function + in order to capture the string summary. + It defaults to `print` (prints to stdout). + """ + if print_fn is None: + print_fn = print + + if model.__class__.__name__ == 'Sequential': + sequential_like = True + elif not model._is_graph_network: + # We treat subclassed models as a simple sequence of layers, for logging + # purposes. + sequential_like = True + else: + sequential_like = True + nodes_by_depth = model._nodes_by_depth.values() + nodes = [] + for v in nodes_by_depth: + if (len(v) > 1) or (len(v) == 1 and + len(nest.flatten(v[0].keras_inputs)) > 1): + # if the model has multiple nodes + # or if the nodes have multiple inbound_layers + # the model is no longer sequential + sequential_like = False + break + nodes += v + if sequential_like: + # search for shared layers + for layer in model.layers: + flag = False + for node in layer._inbound_nodes: + if node in nodes: + if flag: + sequential_like = False + break + else: + flag = True + if not sequential_like: + break + + if sequential_like: + line_length = line_length or 65 + positions = positions or [.45, .85, 1.] + if positions[-1] <= 1: + positions = [int(line_length * p) for p in positions] + # header names for the different log elements + to_display = ['Layer (type)', 'Output Shape', 'Param #'] + else: + line_length = line_length or 98 + positions = positions or [.33, .55, .67, 1.] + if positions[-1] <= 1: + positions = [int(line_length * p) for p in positions] + # header names for the different log elements + to_display = ['Layer (type)', 'Output Shape', 'Param #', 'Connected to'] + relevant_nodes = [] + for v in model._nodes_by_depth.values(): + relevant_nodes += v + + def print_row(fields, positions): + line = '' + for i in range(len(fields)): + if i > 0: + line = line[:-1] + ' ' + line += str(fields[i]) + line = line[:positions[i]] + line += ' ' * (positions[i] - len(line)) + print_fn(line) + + print_fn('Model: "{}"'.format(model.name)) + print_fn('_' * line_length) + print_row(to_display, positions) + print_fn('=' * line_length) + + def print_layer_summary(layer): + """Prints a summary for a single layer. + + Args: + layer: target layer. + """ + try: + output_shape = layer.output_shape + except AttributeError: + output_shape = 'multiple' + except RuntimeError: # output_shape unknown in Eager mode. + output_shape = '?' + name = layer.name + cls_name = layer.__class__.__name__ + if not layer.built and not getattr(layer, '_is_graph_network', False): + # If a subclassed model has a layer that is not called in Model.call, the + # layer will not be built and we cannot call layer.count_params(). + params = '0 (unused)' + else: + params = layer.count_params() + fields = [name + ' (' + cls_name + ')', output_shape, params] + print_row(fields, positions) + + def print_layer_summary_with_connections(layer): + """Prints a summary for a single layer (including topological connections). + + Args: + layer: target layer. + """ + try: + output_shape = layer.output_shape + except AttributeError: + output_shape = 'multiple' + connections = [] + for node in layer._inbound_nodes: + if relevant_nodes and node not in relevant_nodes: + # node is not part of the current network + continue + + for inbound_layer, node_index, tensor_index, _ in node.iterate_inbound(): + connections.append('{}[{}][{}]'.format(inbound_layer.name, node_index, + tensor_index)) + + name = layer.name + cls_name = layer.__class__.__name__ + if not connections: + first_connection = '' + else: + first_connection = connections[0] + fields = [ + name + ' (' + cls_name + ')', output_shape, + layer.count_params(), first_connection + ] + print_row(fields, positions) + if len(connections) > 1: + for i in range(1, len(connections)): + fields = ['', '', '', connections[i]] + print_row(fields, positions) + + layers = model.layers + for i in range(len(layers)): + if sequential_like: + print_layer_summary(layers[i]) + else: + print_layer_summary_with_connections(layers[i]) + if i == len(layers) - 1: + print_fn('=' * line_length) + else: + print_fn('_' * line_length) + + if hasattr(model, '_collected_trainable_weights'): + trainable_count = count_params(model._collected_trainable_weights) + else: + trainable_count = count_params(model.trainable_weights) + + non_trainable_count = count_params(model.non_trainable_weights) + + print_fn('Total params: {:,}'.format(trainable_count + non_trainable_count)) + print_fn('Trainable params: {:,}'.format(trainable_count)) + print_fn('Non-trainable params: {:,}'.format(non_trainable_count)) + print_fn('_' * line_length) + + +def convert_dense_weights_data_format(dense, + previous_feature_map_shape, + target_data_format='channels_first'): + """Utility useful when changing a convnet's `data_format`. + + When porting the weights of a convnet from one data format to the other, + if the convnet includes a `Flatten` layer + (applied to the last convolutional feature map) + followed by a `Dense` layer, the weights of that `Dense` layer + should be updated to reflect the new dimension ordering. + + Args: + dense: The target `Dense` layer. + previous_feature_map_shape: A shape tuple of 3 integers, + e.g. `(512, 7, 7)`. The shape of the convolutional + feature map right before the `Flatten` layer that + came before the target `Dense` layer. + target_data_format: One of "channels_last", "channels_first". + Set it "channels_last" + if converting a "channels_first" model to "channels_last", + or reciprocally. + """ + assert target_data_format in {'channels_last', 'channels_first'} + kernel, bias = dense.get_weights() + for i in range(kernel.shape[1]): + if target_data_format == 'channels_first': + c, h, w = previous_feature_map_shape + original_fm_shape = (h, w, c) + ki = kernel[:, i].reshape(original_fm_shape) + ki = np.transpose(ki, (2, 0, 1)) # last -> first + else: + h, w, c = previous_feature_map_shape + original_fm_shape = (c, h, w) + ki = kernel[:, i].reshape(original_fm_shape) + ki = np.transpose(ki, (1, 2, 0)) # first -> last + kernel[:, i] = np.reshape(ki, (np.prod(previous_feature_map_shape),)) + dense.set_weights([kernel, bias]) + + +def is_builtin_layer(layer): + if not getattr(layer, '_keras_api_names', None): + return False + + # Subclasses of `Layer` that are not exported inherit the export name + # of the base layer class. + return (layer._keras_api_names != ('keras.layers.Layer',) and + layer._keras_api_names_v1 != ('keras.layers.Layer',)) + + +def cached_per_instance(f): + """Lightweight decorator for caching lazily constructed properties. + + When to use: + This decorator provides simple caching with minimal overhead. It is designed + for properties which are expensive to compute and static over the life of a + class instance, and provides no mechanism for cache invalidation. Thus it is + best suited for lazily exposing derived properties of other static data. + + For classes with custom getattr / setattr behavior (such as trackable + objects), storing cache results as object attributes is not performant. + Instead, a specialized cache can significantly reduce property lookup + overhead. (While still allowing the decorated property to be lazily computed.) + Consider the following class: + + ``` + class MyClass(object): + def __setattr__(self, key, value): + # Some expensive class specific code + # ... + # ... + + super(MyClass, self).__setattr__(key, value) + + @property + def thing(self): + # `thing` is expensive to compute (and may not even be requested), so we + # want to lazily compute it and then cache it. + output = getattr(self, '_thing', None) + if output is None: + self._thing = output = compute_thing(self) + return output + ``` + + It's also worth noting that ANY overriding of __setattr__, even something as + simple as: + ``` + def __setattr__(self, key, value): + super(MyClass, self).__setattr__(key, value) + ``` + + Slows down attribute assignment by nearly 10x. + + By contrast, replacing the definition of `thing` with the following sidesteps + the expensive __setattr__ altogether: + + ''' + @property + @tracking.cached_per_instance + def thing(self): + # `thing` is expensive to compute (and may not even be requested), so we + # want to lazily compute it and then cache it. + return compute_thing(self) + ''' + + Performance: + The overhead for this decorator is ~0.4 us / call. A much lower overhead + implementation (~0.085 us / call) can be achieved by using a custom dict type: + + ``` + def dict_based_cache(f): + class Cache(dict): + __slots__ = () + def __missing__(self, key): + self[key] = output = f(key) + return output + + return property(Cache().__getitem__) + ``` + + However, that implementation holds class instances as keys, and as a result + blocks garbage collection. (And modifying it to use weakref's as keys raises + the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary + implementation below turns out to be more prudent. + + Args: + f: The function to cache. + + Returns: + f decorated with simple caching behavior. + """ + + cache = weakref.WeakKeyDictionary() + + @functools.wraps(f) + def wrapped(item): + output = cache.get(item) + if output is None: + cache[item] = output = f(item) + return output + + wrapped.cache = cache + return wrapped + + +def filter_empty_layer_containers(layer_list): + """Filter out empty Layer-like containers and uniquify.""" + # TODO(b/130381733): Make this an attribute in base_layer.Layer. + existing = set() + to_visit = layer_list[::-1] + while to_visit: + obj = to_visit.pop() + if id(obj) in existing: + continue + existing.add(id(obj)) + if hasattr(obj, '_is_layer') and not isinstance(obj, type): + yield obj + else: + sub_layers = getattr(obj, 'layers', None) or [] + + # Trackable data structures will not show up in ".layers" lists, but + # the layers they contain will. + to_visit.extend(sub_layers[::-1]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/losses_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/losses_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6a37dfe958351ae6b48fc19333b62672d6660f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/losses_utils.py @@ -0,0 +1,370 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Utilities related to loss functions.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_tensor + + +class ReductionV2(object): + """Types of loss reduction. + + Contains the following values: + + * `AUTO`: Indicates that the reduction option will be determined by the usage + context. For almost all cases this defaults to `SUM_OVER_BATCH_SIZE`. When + used with `tf.distribute.Strategy`, outside of built-in training loops such + as `tf.keras` `compile` and `fit`, we expect reduction value to be + `SUM` or `NONE`. Using `AUTO` in that case will raise an error. + * `NONE`: No **additional** reduction is applied to the output of the wrapped + loss function. When non-scalar losses are returned to Keras functions like + `fit`/`evaluate`, the unreduced vector loss is passed to the optimizer + but the reported loss will be a scalar value. + + Caution: **Verify the shape of the outputs when using** `Reduction.NONE`. + The builtin loss functions wrapped by the loss classes reduce + one dimension (`axis=-1`, or `axis` if specified by loss function). + `Reduction.NONE` just means that no **additional** reduction is applied by + the class wrapper. For categorical losses with an example input shape of + `[batch, W, H, n_classes]` the `n_classes` dimension is reduced. For + pointwise losses your must include a dummy axis so that `[batch, W, H, 1]` + is reduced to `[batch, W, H]`. Without the dummy axis `[batch, W, H]` + will be incorrectly reduced to `[batch, W]`. + + * `SUM`: Scalar sum of weighted losses. + * `SUM_OVER_BATCH_SIZE`: Scalar `SUM` divided by number of elements in losses. + This reduction type is not supported when used with + `tf.distribute.Strategy` outside of built-in training loops like `tf.keras` + `compile`/`fit`. + + You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: + ``` + with strategy.scope(): + loss_obj = tf.keras.losses.CategoricalCrossentropy( + reduction=tf.keras.losses.Reduction.NONE) + .... + loss = tf.reduce_sum(loss_obj(labels, predictions)) * + (1. / global_batch_size) + ``` + + Please see the [custom training guide]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for more + details on this. + """ + + AUTO = 'auto' + NONE = 'none' + SUM = 'sum' + SUM_OVER_BATCH_SIZE = 'sum_over_batch_size' + + @classmethod + def all(cls): + return (cls.AUTO, cls.NONE, cls.SUM, cls.SUM_OVER_BATCH_SIZE) + + @classmethod + def validate(cls, key): + if key not in cls.all(): + raise ValueError('Invalid Reduction Key %s.' % key) + + +def remove_squeezable_dimensions( + labels, predictions, expected_rank_diff=0, name=None): + """Squeeze last dim if ranks differ from expected by exactly 1. + + In the common case where we expect shapes to match, `expected_rank_diff` + defaults to 0, and we squeeze the last dimension of the larger rank if they + differ by 1. + + But, for example, if `labels` contains class IDs and `predictions` contains 1 + probability per class, we expect `predictions` to have 1 more dimension than + `labels`, so `expected_rank_diff` would be 1. In this case, we'd squeeze + `labels` if `rank(predictions) - rank(labels) == 0`, and + `predictions` if `rank(predictions) - rank(labels) == 2`. + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + labels: Label values, a `Tensor` whose dimensions match `predictions`. + predictions: Predicted values, a `Tensor` of arbitrary dimensions. + expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. + name: Name of the op. + + Returns: + Tuple of `labels` and `predictions`, possibly with last dim squeezed. + """ + with backend.name_scope(name or 'remove_squeezable_dimensions'): + if not isinstance(predictions, ragged_tensor.RaggedTensor): + predictions = tensor_conversion.convert_to_tensor_v2_with_dispatch( + predictions + ) + if not isinstance(labels, ragged_tensor.RaggedTensor): + labels = tensor_conversion.convert_to_tensor_v2_with_dispatch(labels) + predictions_shape = predictions.shape + predictions_rank = predictions_shape.ndims + labels_shape = labels.shape + labels_rank = labels_shape.ndims + if (labels_rank is not None) and (predictions_rank is not None): + # Use static rank. + rank_diff = predictions_rank - labels_rank + if (rank_diff == expected_rank_diff + 1 and + predictions_shape.dims[-1].is_compatible_with(1)): + predictions = array_ops.squeeze(predictions, [-1]) + elif (rank_diff == expected_rank_diff - 1 and + labels_shape.dims[-1].is_compatible_with(1)): + labels = array_ops.squeeze(labels, [-1]) + return labels, predictions + + # Use dynamic rank. + rank_diff = array_ops.rank(predictions) - array_ops.rank(labels) + if (predictions_rank is None) or ( + predictions_shape.dims[-1].is_compatible_with(1)): + predictions = cond.cond( + math_ops.equal(expected_rank_diff + 1, rank_diff), + lambda: array_ops.squeeze(predictions, [-1]), + lambda: predictions) + if (labels_rank is None) or ( + labels_shape.dims[-1].is_compatible_with(1)): + labels = cond.cond( + math_ops.equal(expected_rank_diff - 1, rank_diff), + lambda: array_ops.squeeze(labels, [-1]), + lambda: labels) + return labels, predictions + + +def squeeze_or_expand_dimensions(y_pred, y_true=None, sample_weight=None): + """Squeeze or expand last dimension if needed. + + 1. Squeezes last dim of `y_pred` or `y_true` if their rank differs by 1 + (using `remove_squeezable_dimensions`). + 2. Squeezes or expands last dim of `sample_weight` if its rank differs by 1 + from the new rank of `y_pred`. + If `sample_weight` is scalar, it is kept scalar. + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + y_pred: Predicted values, a `Tensor` of arbitrary dimensions. + y_true: Optional label `Tensor` whose dimensions match `y_pred`. + sample_weight: Optional weight scalar or `Tensor` whose dimensions match + `y_pred`. + + Returns: + Tuple of `y_pred`, `y_true` and `sample_weight`. Each of them possibly has + the last dimension squeezed, + `sample_weight` could be extended by one dimension. + If `sample_weight` is None, (y_pred, y_true) is returned. + """ + y_pred_shape = y_pred.shape + y_pred_rank = y_pred_shape.ndims + if y_true is not None: + + # If sparse matrix is provided as `y_true`, the last dimension in `y_pred` + # may be > 1. Eg: y_true = [0, 1, 2] (shape=(3,)), + # y_pred = [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]] (shape=(3, 3)) + # In this case, we should not try to remove squeezable dimension. + y_true_shape = y_true.shape + y_true_rank = y_true_shape.ndims + if (y_true_rank is not None) and (y_pred_rank is not None): + # Use static rank for `y_true` and `y_pred`. + if (y_pred_rank - y_true_rank != 1) or y_pred_shape[-1] == 1: + y_true, y_pred = remove_squeezable_dimensions( + y_true, y_pred) + else: + # Use dynamic rank. + rank_diff = array_ops.rank(y_pred) - array_ops.rank(y_true) + squeeze_dims = lambda: remove_squeezable_dimensions( # pylint: disable=g-long-lambda + y_true, y_pred) + is_last_dim_1 = math_ops.equal(1, array_ops.shape(y_pred)[-1]) + maybe_squeeze_dims = lambda: cond.cond( # pylint: disable=g-long-lambda + is_last_dim_1, squeeze_dims, lambda: (y_true, y_pred)) + y_true, y_pred = cond.cond( + math_ops.equal(1, rank_diff), maybe_squeeze_dims, squeeze_dims) + + if sample_weight is None: + return y_pred, y_true + + weights_shape = sample_weight.shape + weights_rank = weights_shape.ndims + if weights_rank == 0: # If weights is scalar, do nothing. + return y_pred, y_true, sample_weight + + if (y_pred_rank is not None) and (weights_rank is not None): + # Use static rank. + if weights_rank - y_pred_rank == 1: + sample_weight = array_ops.squeeze(sample_weight, [-1]) + elif y_pred_rank - weights_rank == 1: + sample_weight = array_ops.expand_dims(sample_weight, [-1]) + return y_pred, y_true, sample_weight + + # Use dynamic rank. + weights_rank_tensor = array_ops.rank(sample_weight) + rank_diff = weights_rank_tensor - array_ops.rank(y_pred) + maybe_squeeze_weights = lambda: array_ops.squeeze(sample_weight, [-1]) + + def _maybe_expand_weights(): + expand_weights = lambda: array_ops.expand_dims(sample_weight, [-1]) + return cond.cond( + math_ops.equal(rank_diff, -1), expand_weights, lambda: sample_weight) + + def _maybe_adjust_weights(): + return cond.cond( + math_ops.equal(rank_diff, 1), maybe_squeeze_weights, + _maybe_expand_weights) + + # squeeze or expand last dim of `sample_weight` if its rank differs by 1 + # from the new rank of `y_pred`. + sample_weight = cond.cond( + math_ops.equal(weights_rank_tensor, 0), lambda: sample_weight, + _maybe_adjust_weights) + return y_pred, y_true, sample_weight + + +def _safe_mean(losses, num_present): + """Computes a safe mean of the losses. + + Args: + losses: `Tensor` whose elements contain individual loss measurements. + num_present: The number of measurable elements in `losses`. + + Returns: + A scalar representing the mean of `losses`. If `num_present` is zero, + then zero is returned. + """ + total_loss = math_ops.reduce_sum(losses) + return math_ops.div_no_nan(total_loss, num_present, name='value') + + +def _num_elements(losses): + """Computes the number of elements in `losses` tensor.""" + with backend.name_scope('num_elements') as scope: + return math_ops.cast(array_ops.size(losses, name=scope), dtype=losses.dtype) + + +def reduce_weighted_loss(weighted_losses, + reduction=ReductionV2.SUM_OVER_BATCH_SIZE): + """Reduces the individual weighted loss measurements.""" + if reduction == ReductionV2.NONE: + loss = weighted_losses + else: + loss = math_ops.reduce_sum(weighted_losses) + if reduction == ReductionV2.SUM_OVER_BATCH_SIZE: + loss = _safe_mean(loss, _num_elements(weighted_losses)) + return loss + + +def compute_weighted_loss(losses, + sample_weight=None, + reduction=ReductionV2.SUM_OVER_BATCH_SIZE, + name=None): + """Computes the weighted loss. + + Args: + losses: `Tensor` of shape `[batch_size, d1, ... dN]`. + sample_weight: Optional `Tensor` whose rank is either 0, or the same rank as + `losses`, or be broadcastable to `losses`. + reduction: (Optional) Type of `tf.keras.losses.Reduction` to apply to loss. + Default value is `SUM_OVER_BATCH_SIZE`. + name: Optional name for the op. + + Raises: + ValueError: If the shape of `sample_weight` is not compatible with `losses`. + + Returns: + Weighted loss `Tensor` of the same type as `losses`. If `reduction` is + `NONE`, this has the same shape as `losses`; otherwise, it is scalar. + """ + ReductionV2.validate(reduction) + + # If this function is called directly, then we just default 'AUTO' to + # 'SUM_OVER_BATCH_SIZE'. Eg. Canned estimator use cases. + if reduction == ReductionV2.AUTO: + reduction = ReductionV2.SUM_OVER_BATCH_SIZE + if sample_weight is None: + sample_weight = 1.0 + with backend.name_scope(name or 'weighted_loss'): + # Save the `reduction` argument for loss normalization when distributing + # to multiple replicas. Used only for estimator + v1 optimizer flow. + ops.get_default_graph()._last_loss_reduction = reduction # pylint: disable=protected-access + + if not isinstance(losses, + (keras_tensor.KerasTensor, ragged_tensor.RaggedTensor)): + losses = tensor_conversion.convert_to_tensor_v2_with_dispatch(losses) + input_dtype = losses.dtype + + if not isinstance(sample_weight, keras_tensor.KerasTensor): + sample_weight = tensor_conversion.convert_to_tensor_v2_with_dispatch( + sample_weight + ) + + # TODO(psv): Handle casting here in a better way, eg. if losses is float64 + # we do not want to lose precision. + losses = math_ops.cast(losses, 'float32') + sample_weight = math_ops.cast(sample_weight, 'float32') + # Update dimensions of `sample_weight` to match with `losses` if possible. + losses, _, sample_weight = squeeze_or_expand_dimensions( # pylint: disable=unbalanced-tuple-unpacking + losses, None, sample_weight) + weighted_losses = math_ops.multiply(losses, sample_weight) + + # Apply reduction function to the individual weighted losses. + loss = reduce_weighted_loss(weighted_losses, reduction) + # Convert the result back to the input type. + loss = math_ops.cast(loss, input_dtype) + return loss + + +def scale_loss_for_distribution(loss_value): + """Scales and returns the given loss value by the number of replicas.""" + num_replicas = ( + distribute_lib.get_strategy().num_replicas_in_sync) + if num_replicas > 1: + loss_value *= (1. / num_replicas) + return loss_value + + +def cast_losses_to_common_dtype(losses): + """Cast a list of losses to a common dtype. + + If any loss is floating-point, they will all be casted to the most-precise + floating-point loss. Otherwise the losses are not casted. We also skip casting + losses if there are any complex losses. + + Args: + losses: A list of losses. + + Returns: + `losses`, but they have been casted to a common dtype. + """ + highest_float = None + for loss in losses: + if loss.dtype.is_floating: + if highest_float is None or loss.dtype.size > highest_float.size: + highest_float = loss.dtype + elif {loss.dtype, highest_float} == {'bfloat16', 'float16'}: + highest_float = 'float32' + if loss.dtype.is_complex: + return losses # If we find any complex losses, do not cast any losses + if highest_float: + losses = [math_ops.cast(loss, highest_float) for loss in losses] + return losses diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/metrics_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/metrics_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fde05826279ecf81ea6cb2f4b7a884635e900405 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/metrics_utils.py @@ -0,0 +1,861 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Utils related to keras metrics.""" + +from enum import Enum +import functools +import weakref +import numpy as np + +from tensorflow.python.compat import compat +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.keras import backend +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils.generic_utils import to_list +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import variables as variables_module +from tensorflow.python.ops import weights_broadcast_ops +from tensorflow.python.ops.parallel_for import control_flow_ops as parallel_control_flow_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import tf_decorator + +NEG_INF = -1e10 + + +class Reduction(Enum): + """Types of metrics reduction. + + Contains the following values: + + * `SUM`: Scalar sum of weighted values. + * `SUM_OVER_BATCH_SIZE`: Scalar sum of weighted values divided by + number of elements. + * `WEIGHTED_MEAN`: Scalar sum of weighted values divided by sum of weights. + """ + SUM = 'sum' + SUM_OVER_BATCH_SIZE = 'sum_over_batch_size' + WEIGHTED_MEAN = 'weighted_mean' + + +def update_state_wrapper(update_state_fn): + """Decorator to wrap metric `update_state()` with `add_update()`. + + Args: + update_state_fn: function that accumulates metric statistics. + + Returns: + Decorated function that wraps `update_state_fn()` with `add_update()`. + """ + + def decorated(metric_obj, *args, **kwargs): + """Decorated function with `add_update()`.""" + strategy = distribute_lib.get_strategy() + + for weight in metric_obj.weights: + if (backend.is_tpu_strategy(strategy) and + not strategy.extended.variable_created_in_scope(weight) + and not distribute_lib.in_cross_replica_context()): + raise ValueError( + 'Trying to run metric.update_state in replica context when ' + 'the metric was not created in TPUStrategy scope. ' + 'Make sure the keras Metric is created in TPUstrategy scope. ') + + with tf_utils.graph_context_for_symbolic_tensors(*args, **kwargs): + update_op = update_state_fn(*args, **kwargs) + if update_op is not None: # update_op will be None in eager execution. + metric_obj.add_update(update_op) + return update_op + + return tf_decorator.make_decorator(update_state_fn, decorated) + + +def result_wrapper(result_fn): + """Decorator to wrap metric `result()` function in `merge_call()`. + + Result computation is an idempotent operation that simply calculates the + metric value using the state variables. + + If metric state variables are distributed across replicas/devices and + `result()` is requested from the context of one device - This function wraps + `result()` in a distribution strategy `merge_call()`. With this, + the metric state variables will be aggregated across devices. + + Args: + result_fn: function that computes the metric result. + + Returns: + Decorated function that wraps `result_fn()` in distribution strategy + `merge_call()`. + """ + + def decorated(metric_obj, *args): + """Decorated function with merge_call.""" + has_strategy = distribute_lib.has_strategy() + replica_context = distribute_lib.get_replica_context() + + # The purpose of using `merge_call` to call `result()` is to trigger cross + # replica aggregation of metric state variables (SyncOnReadVariable). After + # we introduced `variable_sync_on_read_context`, in principle there is no + # need to use `merge_call` here. However the branch still exists because: + # + # 1. Keras V1 training code sometimes assumes `result_t` is the same tensor + # across replicas (achieved by `merge_call`). With + # `variable_sync_on_read_context` each replica gets their own tensors + # residing on replica's device, thus breaking the assumption. + # 2. Keras c/fit creates a tf.function (a.k.a, train_function) that returns + # the metric values of the first replica. With + # `variable_sync_on_read_context` since each replica gets their own + # tensors, the metric result tensors on the non-first replicas are not in + # the return value of train_function, making TF graph optimizer prune the + # branch that computes and aggregates those metric results. As a result, + # if NCCL is used to do the aggregation, the program will hang because + # NCCL ops are only launched on the non-pruned first replica. + # + # We condition on strategy.extended._use_merge_call() since we know if it is + # false, the program uses `jit_compile` to compile replica fn, meaning it is + # not V1 training (hence #1 is okay), and no pruning will happen as + # compiled functions are not inlined (hence #2 is okay). + + if (not has_strategy or replica_context is None or + not distribute_lib.get_strategy( + ).extended._use_merge_call()): + with distribute_lib.variable_sync_on_read_context(): + raw_result = result_fn(*args) + # Results need to be wrapped in a `tf.identity` op to ensure + # correct execution order. + if isinstance(raw_result, + (tensor.Tensor, variables_module.Variable, float, int)): + result_t = array_ops.identity(raw_result) + elif isinstance(raw_result, dict): + result_t = { + key: array_ops.identity(value) + for key, value in raw_result.items() + } + else: + try: + result_t = array_ops.identity(raw_result) + except (ValueError, TypeError): + raise RuntimeError( + 'The output of `metric.result()` can only be a single ' + 'Tensor/Variable, or a dict of Tensors/Variables. ' + 'For metric %s, got result %s.' % (metric_obj.name, raw_result)) + else: + # TODO(psv): Test distribution of metrics using different distribution + # strategies. + + # Creating a wrapper for merge_fn. merge_call invokes the given merge_fn + # with distribution object as the first parameter. We create a wrapper + # here so that the result function need not have that parameter. + def merge_fn_wrapper(distribution, merge_fn, *args): + # We will get `PerReplica` merge function. Taking the first one as all + # are identical copies of the function that we had passed below. + result = distribution.experimental_local_results(merge_fn)[0](*args) + + # Wrapping result in identity so that control dependency between + # update_op from `update_state` and result works in case result returns + # a tensor. + return array_ops.identity(result) + + # Wrapping result in merge_call. merge_call is used when we want to leave + # replica mode and compute a value in cross replica mode. + result_t = replica_context.merge_call( + merge_fn_wrapper, args=(result_fn,) + args) + + # We are saving the result op here to be used in train/test execution + # functions. This basically gives the result op that was generated with a + # control dep to the updates for these workflows. + metric_obj._call_result = result_t + return result_t + + return tf_decorator.make_decorator(result_fn, decorated) + + +def weakmethod(method): + """Creates a weak reference to the bound method.""" + + cls = method.im_class + func = method.im_func + instance_ref = weakref.ref(method.im_self) + + @functools.wraps(method) + def inner(*args, **kwargs): + return func.__get__(instance_ref(), cls)(*args, **kwargs) + + del method + return inner + + +def assert_thresholds_range(thresholds): + if thresholds is not None: + invalid_thresholds = [t for t in thresholds if t is None or t < 0 or t > 1] + if invalid_thresholds: + raise ValueError( + 'Threshold values must be in [0, 1]. Invalid values: {}'.format( + invalid_thresholds)) + + +def parse_init_thresholds(thresholds, default_threshold=0.5): + if thresholds is not None: + assert_thresholds_range(to_list(thresholds)) + thresholds = to_list(default_threshold if thresholds is None else thresholds) + return thresholds + + +class ConfusionMatrix(Enum): + TRUE_POSITIVES = 'tp' + FALSE_POSITIVES = 'fp' + TRUE_NEGATIVES = 'tn' + FALSE_NEGATIVES = 'fn' + + +class AUCCurve(Enum): + """Type of AUC Curve (ROC or PR).""" + ROC = 'ROC' + PR = 'PR' + + @staticmethod + def from_str(key): + if key in ('pr', 'PR'): + return AUCCurve.PR + elif key in ('roc', 'ROC'): + return AUCCurve.ROC + else: + raise ValueError('Invalid AUC curve value "%s".' % key) + + +class AUCSummationMethod(Enum): + """Type of AUC summation method. + + https://en.wikipedia.org/wiki/Riemann_sum) + + Contains the following values: + * 'interpolation': Applies mid-point summation scheme for `ROC` curve. For + `PR` curve, interpolates (true/false) positives but not the ratio that is + precision (see Davis & Goadrich 2006 for details). + * 'minoring': Applies left summation for increasing intervals and right + summation for decreasing intervals. + * 'majoring': Applies right summation for increasing intervals and left + summation for decreasing intervals. + """ + INTERPOLATION = 'interpolation' + MAJORING = 'majoring' + MINORING = 'minoring' + + @staticmethod + def from_str(key): + if key in ('interpolation', 'Interpolation'): + return AUCSummationMethod.INTERPOLATION + elif key in ('majoring', 'Majoring'): + return AUCSummationMethod.MAJORING + elif key in ('minoring', 'Minoring'): + return AUCSummationMethod.MINORING + else: + raise ValueError('Invalid AUC summation method value "%s".' % key) + + +def _update_confusion_matrix_variables_optimized( + variables_to_update, + y_true, + y_pred, + thresholds, + multi_label=False, + sample_weights=None, + label_weights=None, + thresholds_with_epsilon=False): + """Update confusion matrix variables with memory efficient alternative. + + Note that the thresholds need to be evenly distributed within the list, eg, + the diff between consecutive elements are the same. + + To compute TP/FP/TN/FN, we are measuring a binary classifier + C(t) = (predictions >= t) + at each threshold 't'. So we have + TP(t) = sum( C(t) * true_labels ) + FP(t) = sum( C(t) * false_labels ) + + But, computing C(t) requires computation for each t. To make it fast, + observe that C(t) is a cumulative integral, and so if we have + thresholds = [t_0, ..., t_{n-1}]; t_0 < ... < t_{n-1} + where n = num_thresholds, and if we can compute the bucket function + B(i) = Sum( (predictions == t), t_i <= t < t{i+1} ) + then we get + C(t_i) = sum( B(j), j >= i ) + which is the reversed cumulative sum in tf.cumsum(). + + We can compute B(i) efficiently by taking advantage of the fact that + our thresholds are evenly distributed, in that + width = 1.0 / (num_thresholds - 1) + thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0] + Given a prediction value p, we can map it to its bucket by + bucket_index(p) = floor( p * (num_thresholds - 1) ) + so we can use tf.math.unsorted_segment_sum() to update the buckets in one + pass. + + Consider following example: + y_true = [0, 0, 1, 1] + y_pred = [0.1, 0.5, 0.3, 0.9] + thresholds = [0.0, 0.5, 1.0] + num_buckets = 2 # [0.0, 1.0], (1.0, 2.0] + bucket_index(y_pred) = tf.math.floor(y_pred * num_buckets) + = tf.math.floor([0.2, 1.0, 0.6, 1.8]) + = [0, 0, 0, 1] + # The meaning of this bucket is that if any of the label is true, + # then 1 will be added to the corresponding bucket with the index. + # Eg, if the label for 0.2 is true, then 1 will be added to bucket 0. If the + # label for 1.8 is true, then 1 will be added to bucket 1. + # + # Note the second item "1.0" is floored to 0, since the value need to be + # strictly larger than the bucket lower bound. + # In the implementation, we use tf.math.ceil() - 1 to achieve this. + tp_bucket_value = tf.math.unsorted_segment_sum(true_labels, bucket_indices, + num_segments=num_thresholds) + = [1, 1, 0] + # For [1, 1, 0] here, it means there is 1 true value contributed by bucket 0, + # and 1 value contributed by bucket 1. When we aggregate them to together, + # the result become [a + b + c, b + c, c], since large thresholds will always + # contribute to the value for smaller thresholds. + true_positive = tf.math.cumsum(tp_bucket_value, reverse=True) + = [2, 1, 0] + + This implementation exhibits a run time and space complexity of O(T + N), + where T is the number of thresholds and N is the size of predictions. + Metrics that rely on standard implementation instead exhibit a complexity of + O(T * N). + + Args: + variables_to_update: Dictionary with 'tp', 'fn', 'tn', 'fp' as valid keys + and corresponding variables to update as values. + y_true: A floating point `Tensor` whose shape matches `y_pred`. Will be cast + to `bool`. + y_pred: A floating point `Tensor` of arbitrary shape and whose values are in + the range `[0, 1]`. + thresholds: A sorted floating point `Tensor` with value in `[0, 1]`. + It need to be evenly distributed (the diff between each element need to be + the same). + multi_label: Optional boolean indicating whether multidimensional + prediction/labels should be treated as multilabel responses, or flattened + into a single label. When True, the valus of `variables_to_update` must + have a second dimension equal to the number of labels in y_true and + y_pred, and those tensors must not be RaggedTensors. + sample_weights: Optional `Tensor` whose rank is either 0, or the same rank + as `y_true`, and must be broadcastable to `y_true` (i.e., all dimensions + must be either `1`, or the same as the corresponding `y_true` dimension). + label_weights: Optional tensor of non-negative weights for multilabel + data. The weights are applied when calculating TP, FP, FN, and TN without + explicit multilabel handling (i.e. when the data is to be flattened). + thresholds_with_epsilon: Optional boolean indicating whether the leading and + tailing thresholds has any epsilon added for floating point imprecisions. + It will change how we handle the leading and tailing bucket. + + Returns: + Update op. + """ + num_thresholds = thresholds.shape.as_list()[0] + + if sample_weights is None: + sample_weights = 1.0 + else: + sample_weights = weights_broadcast_ops.broadcast_weights( + math_ops.cast(sample_weights, dtype=y_pred.dtype), y_pred) + if not multi_label: + sample_weights = array_ops.reshape(sample_weights, [-1]) + if label_weights is None: + label_weights = 1.0 + else: + label_weights = array_ops.expand_dims(label_weights, 0) + label_weights = weights_broadcast_ops.broadcast_weights(label_weights, + y_pred) + if not multi_label: + label_weights = array_ops.reshape(label_weights, [-1]) + weights = math_ops.multiply(sample_weights, label_weights) + + # We shouldn't need this, but in case there are predict value that is out of + # the range of [0.0, 1.0] + y_pred = clip_ops.clip_by_value(y_pred, + clip_value_min=0.0, clip_value_max=1.0) + + y_true = math_ops.cast(math_ops.cast(y_true, dtypes.bool), y_true.dtype) + if not multi_label: + y_true = array_ops.reshape(y_true, [-1]) + y_pred = array_ops.reshape(y_pred, [-1]) + + true_labels = math_ops.multiply(y_true, weights) + false_labels = math_ops.multiply((1.0 - y_true), weights) + + # Compute the bucket indices for each prediction value. + # Since the predict value has to be strictly greater than the thresholds, + # eg, buckets like [0, 0.5], (0.5, 1], and 0.5 belongs to first bucket. + # We have to use math.ceil(val) - 1 for the bucket. + bucket_indices = math_ops.ceil(y_pred * (num_thresholds - 1)) - 1 + + if thresholds_with_epsilon: + # In this case, the first bucket should actually take into account since + # the any prediction between [0.0, 1.0] should be larger than the first + # threshold. We change the bucket value from -1 to 0. + bucket_indices = nn_ops.relu(bucket_indices) + + bucket_indices = math_ops.cast(bucket_indices, dtypes.int32) + + if multi_label: + # We need to run bucket segment sum for each of the label class. In the + # multi_label case, the rank of the label is 2. We first transpose it so + # that the label dim becomes the first and we can parallel run though them. + true_labels = array_ops.transpose_v2(true_labels) + false_labels = array_ops.transpose_v2(false_labels) + bucket_indices = array_ops.transpose_v2(bucket_indices) + + def gather_bucket(label_and_bucket_index): + label, bucket_index = label_and_bucket_index[0], label_and_bucket_index[1] + return math_ops.unsorted_segment_sum( + data=label, segment_ids=bucket_index, num_segments=num_thresholds) + tp_bucket_v = parallel_control_flow_ops.vectorized_map( + gather_bucket, (true_labels, bucket_indices)) + fp_bucket_v = parallel_control_flow_ops.vectorized_map( + gather_bucket, (false_labels, bucket_indices)) + tp = array_ops.transpose_v2( + math_ops.cumsum(tp_bucket_v, reverse=True, axis=1)) + fp = array_ops.transpose_v2( + math_ops.cumsum(fp_bucket_v, reverse=True, axis=1)) + else: + tp_bucket_v = math_ops.unsorted_segment_sum( + data=true_labels, segment_ids=bucket_indices, + num_segments=num_thresholds) + fp_bucket_v = math_ops.unsorted_segment_sum( + data=false_labels, segment_ids=bucket_indices, + num_segments=num_thresholds) + tp = math_ops.cumsum(tp_bucket_v, reverse=True) + fp = math_ops.cumsum(fp_bucket_v, reverse=True) + + # fn = sum(true_labels) - tp + # tn = sum(false_labels) - fp + if (ConfusionMatrix.TRUE_NEGATIVES in variables_to_update or + ConfusionMatrix.FALSE_NEGATIVES in variables_to_update): + if multi_label: + total_true_labels = math_ops.reduce_sum(true_labels, axis=1) + total_false_labels = math_ops.reduce_sum(false_labels, axis=1) + else: + total_true_labels = math_ops.reduce_sum(true_labels) + total_false_labels = math_ops.reduce_sum(false_labels) + + update_ops = [] + if ConfusionMatrix.TRUE_POSITIVES in variables_to_update: + variable = variables_to_update[ConfusionMatrix.TRUE_POSITIVES] + update_ops.append(variable.assign_add(tp)) + if ConfusionMatrix.FALSE_POSITIVES in variables_to_update: + variable = variables_to_update[ConfusionMatrix.FALSE_POSITIVES] + update_ops.append(variable.assign_add(fp)) + if ConfusionMatrix.TRUE_NEGATIVES in variables_to_update: + variable = variables_to_update[ConfusionMatrix.TRUE_NEGATIVES] + tn = total_false_labels - fp + update_ops.append(variable.assign_add(tn)) + if ConfusionMatrix.FALSE_NEGATIVES in variables_to_update: + variable = variables_to_update[ConfusionMatrix.FALSE_NEGATIVES] + fn = total_true_labels - tp + update_ops.append(variable.assign_add(fn)) + return control_flow_ops.group(update_ops) + + +def is_evenly_distributed_thresholds(thresholds): + """Check if the thresholds list is evenly distributed. + + We could leverage evenly distributed thresholds to use less memory when + calculate metrcis like AUC where each individual threshold need to be + evaluted. + + Args: + thresholds: A python list or tuple, or 1D numpy array whose value is ranged + in [0, 1]. + + Returns: + boolean, whether the values in the inputs are evenly distributed. + """ + # Check the list value and see if it is evenly distributed. + num_thresholds = len(thresholds) + if num_thresholds < 3: + return False + even_thresholds = np.arange(num_thresholds, + dtype=np.float32) / (num_thresholds - 1) + return np.allclose(thresholds, even_thresholds, atol=backend.epsilon()) + + +def update_confusion_matrix_variables(variables_to_update, + y_true, + y_pred, + thresholds, + top_k=None, + class_id=None, + sample_weight=None, + multi_label=False, + label_weights=None, + thresholds_distributed_evenly=False): + """Returns op to update the given confusion matrix variables. + + For every pair of values in y_true and y_pred: + + true_positive: y_true == True and y_pred > thresholds + false_negatives: y_true == True and y_pred <= thresholds + true_negatives: y_true == False and y_pred <= thresholds + false_positive: y_true == False and y_pred > thresholds + + The results will be weighted and added together. When multiple thresholds are + provided, we will repeat the same for every threshold. + + For estimation of these metrics over a stream of data, the function creates an + `update_op` operation that updates the given variables. + + If `sample_weight` is `None`, weights default to 1. + Use weights of 0 to mask values. + + Args: + variables_to_update: Dictionary with 'tp', 'fn', 'tn', 'fp' as valid keys + and corresponding variables to update as values. + y_true: A `Tensor` whose shape matches `y_pred`. Will be cast to `bool`. + y_pred: A floating point `Tensor` of arbitrary shape and whose values are in + the range `[0, 1]`. + thresholds: A float value, float tensor, python list, or tuple of float + thresholds in `[0, 1]`, or NEG_INF (used when top_k is set). + top_k: Optional int, indicates that the positive labels should be limited to + the top k predictions. + class_id: Optional int, limits the prediction and labels to the class + specified by this argument. + sample_weight: Optional `Tensor` whose rank is either 0, or the same rank as + `y_true`, and must be broadcastable to `y_true` (i.e., all dimensions must + be either `1`, or the same as the corresponding `y_true` dimension). + multi_label: Optional boolean indicating whether multidimensional + prediction/labels should be treated as multilabel responses, or flattened + into a single label. When True, the valus of `variables_to_update` must + have a second dimension equal to the number of labels in y_true and + y_pred, and those tensors must not be RaggedTensors. + label_weights: (optional) tensor of non-negative weights for multilabel + data. The weights are applied when calculating TP, FP, FN, and TN without + explicit multilabel handling (i.e. when the data is to be flattened). + thresholds_distributed_evenly: Boolean, whether the thresholds are evenly + distributed within the list. An optimized method will be used if this is + the case. See _update_confusion_matrix_variables_optimized() for more + details. + + Returns: + Update op. + + Raises: + ValueError: If `y_pred` and `y_true` have mismatched shapes, or if + `sample_weight` is not `None` and its shape doesn't match `y_pred`, or if + `variables_to_update` contains invalid keys. + """ + if multi_label and label_weights is not None: + raise ValueError('`label_weights` for multilabel data should be handled ' + 'outside of `update_confusion_matrix_variables` when ' + '`multi_label` is True.') + if variables_to_update is None: + return + if not any( + key for key in variables_to_update if key in list(ConfusionMatrix)): + raise ValueError( + 'Please provide at least one valid confusion matrix ' + 'variable to update. Valid variable key options are: "{}". ' + 'Received: "{}"'.format( + list(ConfusionMatrix), variables_to_update.keys())) + + variable_dtype = list(variables_to_update.values())[0].dtype + + y_true = math_ops.cast(y_true, dtype=variable_dtype) + y_pred = math_ops.cast(y_pred, dtype=variable_dtype) + + if thresholds_distributed_evenly: + # Check whether the thresholds has any leading or tailing epsilon added + # for floating point imprecision. The leading and tailing threshold will be + # handled bit differently as the corner case. + # At this point, thresholds should be a list/array with more than 2 items, + # and ranged between [0, 1]. See is_evenly_distributed_thresholds() for more + # details. + thresholds_with_epsilon = thresholds[0] < 0.0 or thresholds[-1] > 1.0 + + thresholds = tensor_conversion.convert_to_tensor_v2_with_dispatch( + thresholds, dtype=variable_dtype + ) + num_thresholds = thresholds.shape.as_list()[0] + + if multi_label: + one_thresh = math_ops.equal( + math_ops.cast(1, dtype=dtypes.int32), + array_ops.rank(thresholds), + name='one_set_of_thresholds_cond') + else: + [y_pred, + y_true], _ = ragged_assert_compatible_and_get_flat_values([y_pred, y_true], + sample_weight) + one_thresh = math_ops.cast(True, dtype=dtypes.bool) + + invalid_keys = [ + key for key in variables_to_update if key not in list(ConfusionMatrix) + ] + if invalid_keys: + raise ValueError( + 'Invalid keys: {}. Valid variable key options are: "{}"'.format( + invalid_keys, list(ConfusionMatrix))) + + with ops.control_dependencies([ + check_ops.assert_greater_equal( + y_pred, + math_ops.cast(0.0, dtype=y_pred.dtype), + message='predictions must be >= 0'), + check_ops.assert_less_equal( + y_pred, + math_ops.cast(1.0, dtype=y_pred.dtype), + message='predictions must be <= 1') + ]): + if sample_weight is None: + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true) + else: + sample_weight = math_ops.cast(sample_weight, dtype=variable_dtype) + y_pred, y_true, sample_weight = ( + losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true, sample_weight=sample_weight)) + y_pred.shape.assert_is_compatible_with(y_true.shape) + + if top_k is not None: + y_pred = _filter_top_k(y_pred, top_k) + if class_id is not None: + y_true = y_true[..., class_id] + y_pred = y_pred[..., class_id] + + if thresholds_distributed_evenly and compat.forward_compatible(2021, 6, 8): + # The new approach will take effect after 2021/6/8, to give enough time + # for Brella release to pick up the new op tf.math.cumsum with float32. + return _update_confusion_matrix_variables_optimized( + variables_to_update, y_true, y_pred, thresholds, + multi_label=multi_label, sample_weights=sample_weight, + label_weights=label_weights, + thresholds_with_epsilon=thresholds_with_epsilon) + + pred_shape = array_ops.shape(y_pred) + num_predictions = pred_shape[0] + if y_pred.shape.ndims == 1: + num_labels = 1 + else: + num_labels = gen_math_ops.Prod(input=pred_shape[1:], axis=0) + thresh_label_tile = array_ops.where_v2(one_thresh, num_labels, + array_ops.ones([], dtype=dtypes.int32)) + + # Reshape predictions and labels, adding a dim for thresholding. + if multi_label: + predictions_extra_dim = array_ops.expand_dims(y_pred, 0) + labels_extra_dim = array_ops.expand_dims( + math_ops.cast(y_true, dtype=dtypes.bool), 0) + else: + # Flatten predictions and labels when not multilabel. + predictions_extra_dim = array_ops.reshape(y_pred, [1, -1]) + labels_extra_dim = array_ops.reshape( + math_ops.cast(y_true, dtype=dtypes.bool), [1, -1]) + + # Tile the thresholds for every prediction. + if multi_label: + thresh_pretile_shape = [num_thresholds, 1, -1] + thresh_tiles = [1, num_predictions, thresh_label_tile] + data_tiles = [num_thresholds, 1, 1] + else: + thresh_pretile_shape = [num_thresholds, -1] + thresh_tiles = [1, num_predictions * num_labels] + data_tiles = [num_thresholds, 1] + + thresh_tiled = array_ops.tile( + array_ops.reshape(thresholds, thresh_pretile_shape), + array_ops_stack.stack(thresh_tiles)) + + # Tile the predictions for every threshold. + preds_tiled = array_ops.tile(predictions_extra_dim, data_tiles) + + # Compare predictions and threshold. + pred_is_pos = math_ops.greater(preds_tiled, thresh_tiled) + + # Tile labels by number of thresholds + label_is_pos = array_ops.tile(labels_extra_dim, data_tiles) + + if sample_weight is not None: + sample_weight = weights_broadcast_ops.broadcast_weights( + math_ops.cast(sample_weight, dtype=variable_dtype), y_pred) + weights_tiled = array_ops.tile( + array_ops.reshape(sample_weight, thresh_tiles), data_tiles) + else: + weights_tiled = None + + if label_weights is not None and not multi_label: + label_weights = array_ops.expand_dims(label_weights, 0) + label_weights = weights_broadcast_ops.broadcast_weights(label_weights, + y_pred) + label_weights_tiled = array_ops.tile( + array_ops.reshape(label_weights, thresh_tiles), data_tiles) + if weights_tiled is None: + weights_tiled = label_weights_tiled + else: + weights_tiled = math_ops.multiply(weights_tiled, label_weights_tiled) + + update_ops = [] + + def weighted_assign_add(label, pred, weights, var): + label_and_pred = math_ops.cast( + math_ops.logical_and(label, pred), dtype=var.dtype) + if weights is not None: + label_and_pred *= math_ops.cast(weights, dtype=var.dtype) + return var.assign_add(math_ops.reduce_sum(label_and_pred, 1)) + + loop_vars = { + ConfusionMatrix.TRUE_POSITIVES: (label_is_pos, pred_is_pos), + } + update_tn = ConfusionMatrix.TRUE_NEGATIVES in variables_to_update + update_fp = ConfusionMatrix.FALSE_POSITIVES in variables_to_update + update_fn = ConfusionMatrix.FALSE_NEGATIVES in variables_to_update + + if update_fn or update_tn: + pred_is_neg = math_ops.logical_not(pred_is_pos) + loop_vars[ConfusionMatrix.FALSE_NEGATIVES] = (label_is_pos, pred_is_neg) + + if update_fp or update_tn: + label_is_neg = math_ops.logical_not(label_is_pos) + loop_vars[ConfusionMatrix.FALSE_POSITIVES] = (label_is_neg, pred_is_pos) + if update_tn: + loop_vars[ConfusionMatrix.TRUE_NEGATIVES] = (label_is_neg, pred_is_neg) + + for matrix_cond, (label, pred) in loop_vars.items(): + + if matrix_cond in variables_to_update: + update_ops.append( + weighted_assign_add(label, pred, weights_tiled, + variables_to_update[matrix_cond])) + + return control_flow_ops.group(update_ops) + + +def _filter_top_k(x, k): + """Filters top-k values in the last dim of x and set the rest to NEG_INF. + + Used for computing top-k prediction values in dense labels (which has the same + shape as predictions) for recall and precision top-k metrics. + + Args: + x: tensor with any dimensions. + k: the number of values to keep. + + Returns: + tensor with same shape and dtype as x. + """ + _, top_k_idx = nn_ops.top_k(x, k, sorted=False) + top_k_mask = math_ops.reduce_sum( + array_ops.one_hot(top_k_idx, array_ops.shape(x)[-1], axis=-1), axis=-2) + return x * top_k_mask + NEG_INF * (1 - top_k_mask) + + +def ragged_assert_compatible_and_get_flat_values(values, mask=None): + """If ragged, it checks the compatibility and then returns the flat_values. + + Note: If two tensors are dense, it does not check their compatibility. + Note: Although two ragged tensors with different ragged ranks could have + identical overall rank and dimension sizes and hence be compatible, + we do not support those cases. + Args: + values: A list of potentially ragged tensor of the same ragged_rank. + mask: A potentially ragged tensor of the same ragged_rank as elements in + Values. + + Returns: + A tuple in which the first element is the list of tensors and the second + is the mask tensor. ([Values], mask). Mask and the element in Values + are equal to the flat_values of the input arguments (if they were ragged). + """ + if isinstance(values, list): + is_all_ragged = \ + all(isinstance(rt, ragged_tensor.RaggedTensor) for rt in values) + is_any_ragged = \ + any(isinstance(rt, ragged_tensor.RaggedTensor) for rt in values) + else: + is_all_ragged = isinstance(values, ragged_tensor.RaggedTensor) + is_any_ragged = is_all_ragged + if (is_all_ragged and + ((mask is None) or isinstance(mask, ragged_tensor.RaggedTensor))): + to_be_stripped = False + if not isinstance(values, list): + values = [values] + to_be_stripped = True + + # NOTE: we leave the flat_values compatibility to + # tf.TensorShape `assert_is_compatible_with` + # check if both dynamic dimensions are equal and then use the flat_values. + nested_row_split_list = [rt.nested_row_splits for rt in values] + assertion_list = _assert_splits_match(nested_row_split_list) + + # if both are ragged sample_weights also should be ragged with same dims. + if isinstance(mask, ragged_tensor.RaggedTensor): + assertion_list_for_mask = _assert_splits_match( + [nested_row_split_list[0], mask.nested_row_splits]) + with ops.control_dependencies(assertion_list_for_mask): + mask = array_ops.expand_dims(mask.flat_values, -1) + + # values has at least 1 element. + flat_values = [] + for value in values: + with ops.control_dependencies(assertion_list): + flat_values.append(array_ops.expand_dims(value.flat_values, -1)) + + values = flat_values[0] if to_be_stripped else flat_values + + elif is_any_ragged: + raise TypeError('One of the inputs does not have acceptable types.') + # values are empty or value are not ragged and mask is ragged. + elif isinstance(mask, ragged_tensor.RaggedTensor): + raise TypeError('Ragged mask is not allowed with non-ragged inputs.') + + return values, mask + + +def _assert_splits_match(nested_splits_lists): + """Checks that the given splits lists are identical. + + Performs static tests to ensure that the given splits lists are identical, + and returns a list of control dependency op tensors that check that they are + fully identical. + + Args: + nested_splits_lists: A list of nested_splits_lists, where each split_list is + a list of `splits` tensors from a `RaggedTensor`, ordered from outermost + ragged dimension to innermost ragged dimension. + + Returns: + A list of control dependency op tensors. + Raises: + ValueError: If the splits are not identical. + """ + error_msg = 'Inputs must have identical ragged splits' + for splits_list in nested_splits_lists: + if len(splits_list) != len(nested_splits_lists[0]): + raise ValueError(error_msg) + return [ + check_ops.assert_equal(s1, s2, message=error_msg) # pylint: disable=g-complex-comprehension + for splits_list in nested_splits_lists[1:] + for (s1, s2) in zip(nested_splits_lists[0], splits_list) + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/mode_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/mode_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..38881970937bbdf133f3373e4ad7503c49d3153b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/mode_keys.py @@ -0,0 +1,19 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Keras model mode constants.""" + +# pylint: disable=unused-import +from tensorflow.python.saved_model.model_utils.mode_keys import KerasModeKeys as ModeKeys +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/np_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/np_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..591a8fe2fd3c198848c1a1d43f98dfdaa32eec67 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/np_utils.py @@ -0,0 +1,92 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Numpy-related utilities.""" + +import numpy as np + + +def to_categorical(y, num_classes=None, dtype='float32'): + """Converts a class vector (integers) to binary class matrix. + + E.g. for use with categorical_crossentropy. + + Args: + y: class vector to be converted into a matrix + (integers from 0 to num_classes). + num_classes: total number of classes. If `None`, this would be inferred + as the (largest number in `y`) + 1. + dtype: The data type expected by the input. Default: `'float32'`. + + Returns: + A binary matrix representation of the input. The classes axis is placed + last. + + Example: + + >>> a = tf.keras.utils.to_categorical([0, 1, 2, 3], num_classes=4) + >>> a = tf.constant(a, shape=[4, 4]) + >>> print(a) + tf.Tensor( + [[1. 0. 0. 0.] + [0. 1. 0. 0.] + [0. 0. 1. 0.] + [0. 0. 0. 1.]], shape=(4, 4), dtype=float32) + + >>> b = tf.constant([.9, .04, .03, .03, + ... .3, .45, .15, .13, + ... .04, .01, .94, .05, + ... .12, .21, .5, .17], + ... shape=[4, 4]) + >>> loss = tf.keras.backend.categorical_crossentropy(a, b) + >>> print(np.around(loss, 5)) + [0.10536 0.82807 0.1011 1.77196] + + >>> loss = tf.keras.backend.categorical_crossentropy(a, a) + >>> print(np.around(loss, 5)) + [0. 0. 0. 0.] + + Raises: + Value Error: If input contains string value + + """ + y = np.array(y, dtype='int') + input_shape = y.shape + if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: + input_shape = tuple(input_shape[:-1]) + y = y.ravel() + if not num_classes: + num_classes = np.max(y) + 1 + n = y.shape[0] + categorical = np.zeros((n, num_classes), dtype=dtype) + categorical[np.arange(n), y] = 1 + output_shape = input_shape + (num_classes,) + categorical = np.reshape(categorical, output_shape) + return categorical + + +def normalize(x, axis=-1, order=2): + """Normalizes a Numpy array. + + Args: + x: Numpy array to normalize. + axis: axis along which to normalize. + order: Normalization order (e.g. `order=2` for L2 norm). + + Returns: + A normalized copy of the array. + """ + l2 = np.atleast_1d(np.linalg.norm(x, order, axis)) + l2[l2 == 0] = 1 + return x / np.expand_dims(l2, axis) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/object_identity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/object_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..eabbe228385b7bd486b25b7c2a711450c9bc141b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/object_identity.py @@ -0,0 +1,265 @@ +"""Utilities for collecting objects based on "is" comparison.""" +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import collections +from typing import Any, Set +import weakref + + +# LINT.IfChange +class _ObjectIdentityWrapper(object): + """Wraps an object, mapping __eq__ on wrapper to "is" on wrapped. + + Since __eq__ is based on object identity, it's safe to also define __hash__ + based on object ids. This lets us add unhashable types like trackable + _ListWrapper objects to object-identity collections. + """ + + __slots__ = ["_wrapped", "__weakref__"] + + def __init__(self, wrapped): + self._wrapped = wrapped + + @property + def unwrapped(self): + return self._wrapped + + def _assert_type(self, other): + if not isinstance(other, _ObjectIdentityWrapper): + raise TypeError("Cannot compare wrapped object with unwrapped object") + + def __lt__(self, other): + self._assert_type(other) + return id(self._wrapped) < id(other._wrapped) # pylint: disable=protected-access + + def __gt__(self, other): + self._assert_type(other) + return id(self._wrapped) > id(other._wrapped) # pylint: disable=protected-access + + def __eq__(self, other): + if other is None: + return False + self._assert_type(other) + return self._wrapped is other._wrapped # pylint: disable=protected-access + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + # Wrapper id() is also fine for weakrefs. In fact, we rely on + # id(weakref.ref(a)) == id(weakref.ref(a)) and weakref.ref(a) is + # weakref.ref(a) in _WeakObjectIdentityWrapper. + return id(self._wrapped) + + def __repr__(self): + return "<{} wrapping {!r}>".format(type(self).__name__, self._wrapped) + + +class _WeakObjectIdentityWrapper(_ObjectIdentityWrapper): + + __slots__ = () + + def __init__(self, wrapped): + super(_WeakObjectIdentityWrapper, self).__init__(weakref.ref(wrapped)) + + @property + def unwrapped(self): + return self._wrapped() + + +class Reference(_ObjectIdentityWrapper): + """Reference that refers an object. + + ```python + x = [1] + y = [1] + + x_ref1 = Reference(x) + x_ref2 = Reference(x) + y_ref2 = Reference(y) + + print(x_ref1 == x_ref2) + ==> True + + print(x_ref1 == y) + ==> False + ``` + """ + + __slots__ = () + + # Disabling super class' unwrapped field. + unwrapped = property() + + def deref(self): + """Returns the referenced object. + + ```python + x_ref = Reference(x) + print(x is x_ref.deref()) + ==> True + ``` + """ + return self._wrapped + + +class ObjectIdentityDictionary(collections.abc.MutableMapping): + """A mutable mapping data structure which compares using "is". + + This is necessary because we have trackable objects (_ListWrapper) which + have behavior identical to built-in Python lists (including being unhashable + and comparing based on the equality of their contents by default). + """ + + __slots__ = ["_storage"] + + def __init__(self): + self._storage = {} + + def _wrap_key(self, key): + return _ObjectIdentityWrapper(key) + + def __getitem__(self, key): + return self._storage[self._wrap_key(key)] + + def __setitem__(self, key, value): + self._storage[self._wrap_key(key)] = value + + def __delitem__(self, key): + del self._storage[self._wrap_key(key)] + + def __len__(self): + return len(self._storage) + + def __iter__(self): + for key in self._storage: + yield key.unwrapped + + def __repr__(self): + return "ObjectIdentityDictionary(%s)" % repr(self._storage) + + +class ObjectIdentityWeakKeyDictionary(ObjectIdentityDictionary): + """Like weakref.WeakKeyDictionary, but compares objects with "is".""" + + __slots__ = ["__weakref__"] + + def _wrap_key(self, key): + return _WeakObjectIdentityWrapper(key) + + def __len__(self): + # Iterate, discarding old weak refs + return len(list(self._storage)) + + def __iter__(self): + keys = self._storage.keys() + for key in keys: + unwrapped = key.unwrapped + if unwrapped is None: + del self[key] + else: + yield unwrapped + + +class ObjectIdentitySet(collections.abc.MutableSet): + """Like the built-in set, but compares objects with "is".""" + + __slots__ = ["_storage", "__weakref__"] + + def __init__(self, *args): + self._storage = set(self._wrap_key(obj) for obj in list(*args)) + + def __le__(self, other: Set[Any]) -> bool: + if not isinstance(other, Set): + return NotImplemented + if len(self) > len(other): + return False + for item in self._storage: + if item not in other: + return False + return True + + def __ge__(self, other: Set[Any]) -> bool: + if not isinstance(other, Set): + return NotImplemented + if len(self) < len(other): + return False + for item in other: + if item not in self: + return False + return True + + @staticmethod + def _from_storage(storage): + result = ObjectIdentitySet() + result._storage = storage # pylint: disable=protected-access + return result + + def _wrap_key(self, key): + return _ObjectIdentityWrapper(key) + + def __contains__(self, key): + return self._wrap_key(key) in self._storage + + def discard(self, key): + self._storage.discard(self._wrap_key(key)) + + def add(self, key): + self._storage.add(self._wrap_key(key)) + + def update(self, items): + self._storage.update([self._wrap_key(item) for item in items]) + + def clear(self): + self._storage.clear() + + def intersection(self, items): + return self._storage.intersection([self._wrap_key(item) for item in items]) + + def difference(self, items): + return ObjectIdentitySet._from_storage( + self._storage.difference([self._wrap_key(item) for item in items])) + + def __len__(self): + return len(self._storage) + + def __iter__(self): + keys = list(self._storage) + for key in keys: + yield key.unwrapped + + +class ObjectIdentityWeakSet(ObjectIdentitySet): + """Like weakref.WeakSet, but compares objects with "is".""" + + __slots__ = () + + def _wrap_key(self, key): + return _WeakObjectIdentityWrapper(key) + + def __len__(self): + # Iterate, discarding old weak refs + return len([_ for _ in self]) + + def __iter__(self): + keys = list(self._storage) + for key in keys: + unwrapped = key.unwrapped + if unwrapped is None: + self.discard(key) + else: + yield unwrapped +# LINT.ThenChange(//tensorflow/python/util/object_identity.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_contextlib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_contextlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8ec40b353fbce45a2fd579baa533b53aea9291 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_contextlib.py @@ -0,0 +1,33 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TFDecorator-aware replacements for the contextlib module.""" + +import contextlib as _contextlib + +from tensorflow.python.util import tf_decorator + + +def contextmanager(target): + """A tf_decorator-aware wrapper for `contextlib.contextmanager`. + + Usage is identical to `contextlib.contextmanager`. + + Args: + target: A callable to be wrapped in a contextmanager. + Returns: + A callable that can be used inside of a `with` statement. + """ + context_manager = _contextlib.contextmanager(target) + return tf_decorator.make_decorator(target, context_manager, 'contextmanager') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_inspect.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..a1118644f38963a74a7b868637c29a9694ba997c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_inspect.py @@ -0,0 +1,415 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TFDecorator-aware replacements for the inspect module.""" + +import collections +import functools +import inspect as _inspect + +from tensorflow.python.util import tf_decorator + +try: + ArgSpec = _inspect.ArgSpec +except: + pass + + +if hasattr(_inspect, 'FullArgSpec'): + FullArgSpec = _inspect.FullArgSpec # pylint: disable=invalid-name +else: + FullArgSpec = collections.namedtuple('FullArgSpec', [ + 'args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults', + 'annotations' + ]) + + +def _convert_maybe_argspec_to_fullargspec(argspec): + if isinstance(argspec, FullArgSpec): + return argspec + return FullArgSpec( + args=argspec.args, + varargs=argspec.varargs, + varkw=argspec.keywords, + defaults=argspec.defaults, + kwonlyargs=[], + kwonlydefaults=None, + annotations={}) + +if hasattr(_inspect, 'getfullargspec'): + _getfullargspec = _inspect.getfullargspec # pylint: disable=invalid-name + + def _getargspec(target): + """A python3 version of getargspec. + + Calls `getfullargspec` and assigns args, varargs, + varkw, and defaults to a python 2/3 compatible `ArgSpec`. + + The parameter name 'varkw' is changed to 'keywords' to fit the + `ArgSpec` struct. + + Args: + target: the target object to inspect. + + Returns: + An ArgSpec with args, varargs, keywords, and defaults parameters + from FullArgSpec. + """ + fullargspecs = getfullargspec(target) + if hasattr(_inspect, 'ArgSpec'): + argspecs = ArgSpec( + args=fullargspecs.args, + varargs=fullargspecs.varargs, + keywords=fullargspecs.varkw, + defaults=fullargspecs.defaults) + else: + argspecs = FullArgSpec( + args=fullargspecs.args, + varargs=fullargspecs.varargs, + varkw=fullargspecs.varkw, + defaults=fullargspecs.defaults, + kwonlyargs=[], + kwonlydefaults=None, + annotations={}) + return argspecs +else: + _getargspec = _inspect.getargspec + + def _getfullargspec(target): + """A python2 version of getfullargspec. + + Args: + target: the target object to inspect. + + Returns: + A FullArgSpec with empty kwonlyargs, kwonlydefaults and annotations. + """ + return _convert_maybe_argspec_to_fullargspec(getargspec(target)) + + +def currentframe(): + """TFDecorator-aware replacement for inspect.currentframe.""" + return _inspect.stack()[1][0] + + +def getargspec(obj): + """TFDecorator-aware replacement for `inspect.getargspec`. + + Note: `getfullargspec` is recommended as the python 2/3 compatible + replacement for this function. + + Args: + obj: A function, partial function, or callable object, possibly decorated. + + Returns: + The `ArgSpec` that describes the signature of the outermost decorator that + changes the callable's signature, or the `ArgSpec` that describes + the object if not decorated. + + Raises: + ValueError: When callable's signature can not be expressed with + ArgSpec. + TypeError: For objects of unsupported types. + """ + if isinstance(obj, functools.partial): + return _get_argspec_for_partial(obj) + + decorators, target = tf_decorator.unwrap(obj) + + spec = next((d.decorator_argspec + for d in decorators + if d.decorator_argspec is not None), None) + if spec: + return spec + + try: + # Python3 will handle most callables here (not partial). + return _getargspec(target) + except TypeError: + pass + + if isinstance(target, type): + try: + return _getargspec(target.__init__) + except TypeError: + pass + + try: + return _getargspec(target.__new__) + except TypeError: + pass + + # The `type(target)` ensures that if a class is received we don't return + # the signature of its __call__ method. + return _getargspec(type(target).__call__) + + +def _get_argspec_for_partial(obj): + """Implements `getargspec` for `functools.partial` objects. + + Args: + obj: The `functools.partial` object + Returns: + An `inspect.ArgSpec` + Raises: + ValueError: When callable's signature can not be expressed with + ArgSpec. + """ + # When callable is a functools.partial object, we construct its ArgSpec with + # following strategy: + # - If callable partial contains default value for positional arguments (ie. + # object.args), then final ArgSpec doesn't contain those positional arguments. + # - If callable partial contains default value for keyword arguments (ie. + # object.keywords), then we merge them with wrapped target. Default values + # from callable partial takes precedence over those from wrapped target. + # + # However, there is a case where it is impossible to construct a valid + # ArgSpec. Python requires arguments that have no default values must be + # defined before those with default values. ArgSpec structure is only valid + # when this presumption holds true because default values are expressed as a + # tuple of values without keywords and they are always assumed to belong to + # last K arguments where K is number of default values present. + # + # Since functools.partial can give default value to any argument, this + # presumption may no longer hold in some cases. For example: + # + # def func(m, n): + # return 2 * m + n + # partialed = functools.partial(func, m=1) + # + # This example will result in m having a default value but n doesn't. This is + # usually not allowed in Python and can not be expressed in ArgSpec correctly. + # + # Thus, we must detect cases like this by finding first argument with default + # value and ensures all following arguments also have default values. When + # this is not true, a ValueError is raised. + + n_prune_args = len(obj.args) + partial_keywords = obj.keywords or {} + + args, varargs, keywords, defaults = getargspec(obj.func) + + # Pruning first n_prune_args arguments. + args = args[n_prune_args:] + + # Partial function may give default value to any argument, therefore length + # of default value list must be len(args) to allow each argument to + # potentially be given a default value. + no_default = object() + all_defaults = [no_default] * len(args) + + if defaults: + all_defaults[-len(defaults):] = defaults + + # Fill in default values provided by partial function in all_defaults. + for kw, default in partial_keywords.items(): + if kw in args: + idx = args.index(kw) + all_defaults[idx] = default + elif not keywords: + raise ValueError('Function does not have **kwargs parameter, but ' + 'contains an unknown partial keyword.') + + # Find first argument with default value set. + first_default = next( + (idx for idx, x in enumerate(all_defaults) if x is not no_default), None) + + # If no default values are found, return ArgSpec with defaults=None. + if first_default is None: + return ArgSpec(args, varargs, keywords, None) + + # Checks if all arguments have default value set after first one. + invalid_default_values = [ + args[i] for i, j in enumerate(all_defaults) + if j is no_default and i > first_default + ] + + if invalid_default_values: + raise ValueError('Some arguments %s do not have default value, but they ' + 'are positioned after those with default values. This can ' + 'not be expressed with ArgSpec.' % invalid_default_values) + + return ArgSpec(args, varargs, keywords, tuple(all_defaults[first_default:])) + + +def getfullargspec(obj): + """TFDecorator-aware replacement for `inspect.getfullargspec`. + + This wrapper emulates `inspect.getfullargspec` in[^)]* Python2. + + Args: + obj: A callable, possibly decorated. + + Returns: + The `FullArgSpec` that describes the signature of + the outermost decorator that changes the callable's signature. If the + callable is not decorated, `inspect.getfullargspec()` will be called + directly on the callable. + """ + decorators, target = tf_decorator.unwrap(obj) + + for d in decorators: + if d.decorator_argspec is not None: + return _convert_maybe_argspec_to_fullargspec(d.decorator_argspec) + return _getfullargspec(target) + + +def getcallargs(*func_and_positional, **named): + """TFDecorator-aware replacement for inspect.getcallargs. + + Args: + *func_and_positional: A callable, possibly decorated, followed by any + positional arguments that would be passed to `func`. + **named: The named argument dictionary that would be passed to `func`. + + Returns: + A dictionary mapping `func`'s named arguments to the values they would + receive if `func(*positional, **named)` were called. + + `getcallargs` will use the argspec from the outermost decorator that provides + it. If no attached decorators modify argspec, the final unwrapped target's + argspec will be used. + """ + func = func_and_positional[0] + positional = func_and_positional[1:] + argspec = getfullargspec(func) + call_args = named.copy() + this = getattr(func, 'im_self', None) or getattr(func, '__self__', None) + if ismethod(func) and this: + positional = (this,) + positional + remaining_positionals = [arg for arg in argspec.args if arg not in call_args] + call_args.update(dict(zip(remaining_positionals, positional))) + default_count = 0 if not argspec.defaults else len(argspec.defaults) + if default_count: + for arg, value in zip(argspec.args[-default_count:], argspec.defaults): + if arg not in call_args: + call_args[arg] = value + if argspec.kwonlydefaults is not None: + for k, v in argspec.kwonlydefaults.items(): + if k not in call_args: + call_args[k] = v + return call_args + + +def getframeinfo(*args, **kwargs): + return _inspect.getframeinfo(*args, **kwargs) + + +def getdoc(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getdoc. + + Args: + object: An object, possibly decorated. + + Returns: + The docstring associated with the object. + + The outermost-decorated object is intended to have the most complete + documentation, so the decorated parameter is not unwrapped. + """ + return _inspect.getdoc(object) + + +def getfile(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getfile.""" + unwrapped_object = tf_decorator.unwrap(object)[1] + + # Work around for the case when object is a stack frame + # and only .pyc files are used. In this case, getfile + # might return incorrect path. So, we get the path from f_globals + # instead. + if (hasattr(unwrapped_object, 'f_globals') and + '__file__' in unwrapped_object.f_globals): + return unwrapped_object.f_globals['__file__'] + return _inspect.getfile(unwrapped_object) + + +def getmembers(object, predicate=None): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getmembers.""" + return _inspect.getmembers(object, predicate) + + +def getmodule(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getmodule.""" + return _inspect.getmodule(object) + + +def getmro(cls): + """TFDecorator-aware replacement for inspect.getmro.""" + return _inspect.getmro(cls) + + +def getsource(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsource.""" + return _inspect.getsource(tf_decorator.unwrap(object)[1]) + + +def getsourcefile(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsourcefile.""" + return _inspect.getsourcefile(tf_decorator.unwrap(object)[1]) + + +def getsourcelines(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.getsourcelines.""" + return _inspect.getsourcelines(tf_decorator.unwrap(object)[1]) + + +def isbuiltin(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isbuiltin.""" + return _inspect.isbuiltin(tf_decorator.unwrap(object)[1]) + + +def isclass(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isclass.""" + return _inspect.isclass(tf_decorator.unwrap(object)[1]) + + +def isfunction(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isfunction.""" + return _inspect.isfunction(tf_decorator.unwrap(object)[1]) + + +def isframe(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismodule.""" + return _inspect.isframe(tf_decorator.unwrap(object)[1]) + + +def isgenerator(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isgenerator.""" + return _inspect.isgenerator(tf_decorator.unwrap(object)[1]) + + +def isgeneratorfunction(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isgeneratorfunction.""" + return _inspect.isgeneratorfunction(tf_decorator.unwrap(object)[1]) + + +def ismethod(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismethod.""" + return _inspect.ismethod(tf_decorator.unwrap(object)[1]) + + +def ismodule(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.ismodule.""" + return _inspect.ismodule(tf_decorator.unwrap(object)[1]) + + +def isroutine(object): # pylint: disable=redefined-builtin + """TFDecorator-aware replacement for inspect.isroutine.""" + return _inspect.isroutine(tf_decorator.unwrap(object)[1]) + + +def stack(context=1): + """TFDecorator-aware replacement for inspect.stack.""" + return _inspect.stack(context)[1:] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c419d73159f0c4f3cb2ecf33c6324d11ceb3ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/tf_utils.py @@ -0,0 +1,539 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorFlow-related utilities.""" + +import collections +import copy +import numpy as np + +from tensorflow.python.data.experimental.ops import cardinality +from tensorflow.python.distribute.coordinator import cluster_coordinator as coordinator_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.keras import backend as K +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.utils import object_identity +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.util import nest + + +def is_tensor_or_tensor_list(v): + v = nest.flatten(v) + if v and isinstance(v[0], tensor_lib.Tensor): + return True + else: + return False + + +def get_reachable_from_inputs(inputs, targets=None): + """Returns the set of tensors/ops reachable from `inputs`. + + Stops if all targets have been found (target is optional). + + Only valid in Symbolic mode, not Eager mode. + + Args: + inputs: List of tensors. + targets: List of tensors. + + Returns: + A set of tensors reachable from the inputs (includes the inputs themselves). + """ + inputs = nest.flatten(inputs, expand_composites=True) + reachable = object_identity.ObjectIdentitySet(inputs) + if targets: + remaining_targets = object_identity.ObjectIdentitySet(nest.flatten(targets)) + queue = collections.deque(inputs) + + while queue: + x = queue.pop() + if isinstance(x, tuple(_user_convertible_tensor_types)): + # Can't find consumers of user-specific types. + continue + + if isinstance(x, ops.Operation): + outputs = x.outputs[:] or [] + outputs += x._control_outputs # pylint: disable=protected-access + elif isinstance(x, variables.Variable): + try: + outputs = [x.op] + except AttributeError: + # Variables can be created in an Eager context. + outputs = [] + elif tensor_util.is_tf_type(x): + outputs = x.consumers() + else: + raise TypeError('Expected Operation, Variable, or Tensor, got ' + str(x)) + + for y in outputs: + if y not in reachable: + reachable.add(y) + if targets: + remaining_targets.discard(y) + queue.appendleft(y) + + if targets and not remaining_targets: + return reachable + + return reachable + + +# This function needs access to private functions of `nest`. +# pylint: disable=protected-access +def map_structure_with_atomic(is_atomic_fn, map_fn, nested): + """Maps the atomic elements of a nested structure. + + Args: + is_atomic_fn: A function that determines if an element of `nested` is + atomic. + map_fn: The function to apply to atomic elements of `nested`. + nested: A nested structure. + + Returns: + The nested structure, with atomic elements mapped according to `map_fn`. + + Raises: + ValueError: If an element that is neither atomic nor a sequence is + encountered. + """ + if is_atomic_fn(nested): + return map_fn(nested) + + # Recursively convert. + if not nest.is_nested(nested): + raise ValueError( + 'Received non-atomic and non-sequence element: {}'.format(nested)) + if nest.is_mapping(nested): + values = [nested[k] for k in sorted(nested.keys())] + elif nest.is_attrs(nested): + values = _astuple(nested) + else: + values = nested + mapped_values = [ + map_structure_with_atomic(is_atomic_fn, map_fn, ele) for ele in values + ] + return nest._sequence_like(nested, mapped_values) + + +def get_shapes(tensors): + """Gets shapes from tensors.""" + return nest.map_structure(lambda x: x.shape, tensors) + + +# pylint: enable=protected-access + + +def convert_shapes(input_shape, to_tuples=True): + """Converts nested shape representations to desired format. + + Performs: + + TensorShapes -> tuples if `to_tuples=True`. + tuples of int or None -> TensorShapes if `to_tuples=False`. + + Valid objects to be converted are: + - TensorShapes + - tuples with elements of type int or None. + - ints + - None + + Args: + input_shape: A nested structure of objects to be converted to TensorShapes. + to_tuples: If `True`, converts all TensorShape to tuples. Otherwise converts + all tuples representing shapes to TensorShapes. + + Returns: + Nested structure of shapes in desired format. + + Raises: + ValueError: when the input tensor shape can't be converted to tuples, eg + unknown tensor shape. + """ + + def _is_shape_component(value): + return value is None or isinstance(value, (int, tensor_shape.Dimension)) + + def _is_atomic_shape(input_shape): + # Ex: TensorShape or (None, 10, 32) or 5 or `None` + if _is_shape_component(input_shape): + return True + if isinstance(input_shape, tensor_shape.TensorShape): + return True + if (isinstance(input_shape, (tuple, list)) and + all(_is_shape_component(ele) for ele in input_shape)): + return True + return False + + def _convert_shape(input_shape): + input_shape = tensor_shape.TensorShape(input_shape) + if to_tuples: + input_shape = tuple(input_shape.as_list()) + return input_shape + + return map_structure_with_atomic(_is_atomic_shape, _convert_shape, + input_shape) + + +class ListWrapper(object): + """A wrapper for lists to be treated as elements for `nest`.""" + + def __init__(self, list_to_wrap): + self._list = list_to_wrap + + def as_list(self): + return self._list + + +def convert_inner_node_data(nested, wrap=False): + """Either wraps or unwraps innermost node data lists in `ListWrapper` objects. + + Args: + nested: A nested data structure. + wrap: If `True`, wrap innermost lists in `ListWrapper` objects. If `False`, + unwraps `ListWrapper` objects into lists. + + Returns: + Structure of same type as nested, with lists wrapped/unwrapped. + """ + + def _is_serialized_node_data(nested): + # Node data can be of form `[layer_name, node_id, tensor_id]` or + # `[layer_name, node_id, tensor_id, kwargs]`. + if (isinstance(nested, list) and (len(nested) in [3, 4]) and + isinstance(nested[0], str)): + return True + return False + + def _is_atomic_nested(nested): + """Returns `True` if `nested` is a list representing node data.""" + if isinstance(nested, ListWrapper): + return True + if _is_serialized_node_data(nested): + return True + return not nest.is_nested(nested) + + def _convert_object_or_list(nested): + """Convert b/t `ListWrapper` object and list representations.""" + if wrap: + if isinstance(nested, ListWrapper): + return nested + if _is_serialized_node_data(nested): + return ListWrapper(nested) + return nested + else: + if isinstance(nested, ListWrapper): + return nested.as_list() + return nested + + return map_structure_with_atomic(_is_atomic_nested, _convert_object_or_list, + nested) + + +def shape_type_conversion(fn): + """Decorator that handles tuple/TensorShape conversion. + + Used in `compute_output_shape` and `build`. + + Args: + fn: function to wrap. + + Returns: + Wrapped function. + """ + + def wrapper(instance, input_shape): + # Pass shapes as tuples to `fn` + # This preserves compatibility with external Keras. + if input_shape is not None: + input_shape = convert_shapes(input_shape, to_tuples=True) + output_shape = fn(instance, input_shape) + # Return shapes from `fn` as TensorShapes. + if output_shape is not None: + output_shape = convert_shapes(output_shape, to_tuples=False) + return output_shape + + return wrapper + + +def are_all_symbolic_tensors(tensors): + return all(map(is_symbolic_tensor, tensors)) + + +_user_convertible_tensor_types = set() + + +def is_extension_type(tensor): + """Returns whether a tensor is of an ExtensionType. + + github.com/tensorflow/community/pull/269 + Currently it works by checking if `tensor` is a `CompositeTensor` instance, + but this will be changed to use an appropriate extensiontype protocol + check once ExtensionType is made public. + + Args: + tensor: An object to test + + Returns: + True if the tensor is an extension type object, false if not. + """ + return isinstance(tensor, composite_tensor.CompositeTensor) + + +def is_symbolic_tensor(tensor): + """Returns whether a tensor is symbolic (from a TF graph) or an eager tensor. + + A Variable can be seen as either: it is considered symbolic + when we are in a graph scope, and eager when we are in an eager scope. + + Args: + tensor: A tensor instance to test. + + Returns: + True for symbolic tensors, False for eager tensors. + """ + if isinstance(tensor, tensor_lib.Tensor): + return hasattr(tensor, 'graph') + elif is_extension_type(tensor): + component_tensors = nest.flatten(tensor, expand_composites=True) + return any(hasattr(t, 'graph') for t in component_tensors) + elif isinstance(tensor, variables.Variable): + # Variables that are output of a Keras Layer in Functional API mode + # should be considered symbolic. + # TODO(omalleyt): We need a better way to check this in order to + # enable `run_eagerly=True` for Models containing Layers that + # return Variables as outputs. + return (getattr(tensor, '_keras_history', False) or + not context.executing_eagerly()) + elif isinstance(tensor, tuple(_user_convertible_tensor_types)): + tensor = ops.convert_to_tensor_or_composite(tensor) + return is_symbolic_tensor(tensor) + else: + return False + + +def register_symbolic_tensor_type(cls): + """Allows users to specify types regarded as symbolic `Tensor`s. + + Used in conjunction with `tf.register_tensor_conversion_function`, calling + `tf.keras.__internal__.utils.register_symbolic_tensor_type(cls)` + allows non-`Tensor` objects to be plumbed through Keras layers. + + Example: + + ```python + # One-time setup. + class Foo(object): + def __init__(self, input_): + self._input = input_ + def value(self): + return tf.constant(42.) + + tf.register_tensor_conversion_function( + Foo, lambda x, *args, **kwargs: x.value()) + + tf.keras.__internal__.utils.register_symbolic_tensor_type(Foo) + + # User-land. + layer = tf.keras.layers.Lambda(lambda input_: Foo(input_)) + ``` + + Args: + cls: A `class` type which shall be regarded as a symbolic `Tensor`. + """ + global _user_convertible_tensor_types + if cls not in _user_convertible_tensor_types: + keras_tensor.register_keras_tensor_specialization( + cls, keras_tensor.UserRegisteredTypeKerasTensor) + _user_convertible_tensor_types.add(cls) + + +def type_spec_from_value(value): + """Grab type_spec without converting array-likes to tensors.""" + if is_extension_type(value): + return value._type_spec # pylint: disable=protected-access + # Get a TensorSpec for array-like data without + # converting the data to a Tensor + if hasattr(value, 'shape') and hasattr(value, 'dtype'): + return tensor_lib.TensorSpec(value.shape, value.dtype) + else: + return type_spec.type_spec_from_value(value) + + +def is_ragged(tensor): + """Returns true if `tensor` is a ragged tensor or ragged tensor value.""" + return isinstance( + tensor, + (ragged_tensor.RaggedTensor, ragged_tensor_value.RaggedTensorValue)) + + +def is_sparse(tensor): + """Returns true if `tensor` is a sparse tensor or sparse tensor value.""" + return isinstance( + tensor, + (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)) + + +def is_tensor_or_variable(x): + return tensor_util.is_tf_type(x) or isinstance(x, variables.Variable) + + +def assert_no_legacy_layers(layers): + """Prevent tf.layers.Layers from being used with Keras. + + Certain legacy layers inherit from their keras analogs; however they are + not supported with keras and can lead to subtle and hard to diagnose bugs. + + Args: + layers: A list of layers to check + + Raises: + TypeError: If any elements of layers are tf.layers.Layers + """ + + # isinstance check for tf.layers.Layer introduces a circular dependency. + legacy_layers = [l for l in layers if getattr(l, '_is_legacy_layer', None)] + if legacy_layers: + layer_str = '\n'.join(' ' + str(l) for l in legacy_layers) + raise TypeError( + 'The following are legacy tf.layers.Layers:\n{}\nTo use keras as a ' + 'framework (for instance using the Network, Model, or Sequential ' + 'classes), please use the tf.keras.layers implementation instead. ' + '(Or, if writing custom layers, subclass from tf.keras.layers rather ' + 'than tf.layers)'.format(layer_str)) + + +@tf_contextlib.contextmanager +def maybe_init_scope(layer): + """Open an `init_scope` if in V2 mode and using the keras graph. + + Args: + layer: The Layer/Model that is currently active. + + Yields: + None + """ + # Don't open an init_scope in V1 mode or when using legacy tf.layers. + if (ops.executing_eagerly_outside_functions() and + getattr(layer, '_keras_style', True)): + with ops.init_scope(): + yield + else: + yield + + +@tf_contextlib.contextmanager +def graph_context_for_symbolic_tensors(*args, **kwargs): + """Returns graph context manager if any of the inputs is a symbolic tensor.""" + if any(is_symbolic_tensor(v) for v in list(args) + list(kwargs.values())): + with K.get_graph().as_default(): + yield + else: + yield + + +def dataset_is_infinite(dataset): + """True if the passed dataset is infinite.""" + if ops.executing_eagerly_outside_functions(): + return math_ops.equal( + cardinality.cardinality(dataset), cardinality.INFINITE) + else: + dataset_size = K.get_session().run(cardinality.cardinality(dataset)) + return dataset_size == cardinality.INFINITE + + +def get_tensor_spec(t, dynamic_batch=False, name=None): + """Returns a `TensorSpec` given a single `Tensor` or `TensorSpec`.""" + # pylint: disable=protected-access + if isinstance(t, type_spec.TypeSpec): + spec = t + elif is_extension_type(t): + # TODO(b/148821952): Should these specs have a name attr? + spec = t._type_spec + elif (hasattr(t, '_keras_history') and + hasattr(t._keras_history[0], '_type_spec')): + return t._keras_history[0]._type_spec + elif hasattr(t, 'shape') and hasattr(t, 'dtype'): + spec = tensor_lib.TensorSpec(shape=t.shape, dtype=t.dtype, name=name) + else: + return None # Allow non-Tensors to pass through. + + if not dynamic_batch: + return spec + + dynamic_batch_spec = copy.deepcopy(spec) + # RaggedTensorSpec only has a private _shape. + shape = dynamic_batch_spec._shape + if shape.rank is not None and shape.rank > 0: + shape_list = shape.as_list() + shape_list[0] = None + dynamic_batch_spec._shape = tensor_shape.TensorShape(shape_list) + return dynamic_batch_spec + # pylint: enable=protected-access + + +def sync_to_numpy_or_python_type(tensors): + """Syncs and converts a structure of `Tensor`s to `NumPy` arrays or Python scalar types. + + For each tensor, it calls `tensor.numpy()`. If the result is a scalar value, + it converts it to a Python type, such as a float or int, by calling + `result.item()`. + + Numpy scalars are converted, as Python types are often more convenient to deal + with. This is especially useful for bfloat16 Numpy scalars, which don't + support as many operations as other Numpy values. + + Async strategies (such as `TPUStrategy` and `ParameterServerStrategy`) are + forced to + sync during this process. + + Args: + tensors: A structure of tensors. + + Returns: + `tensors`, but scalar tensors are converted to Python types and non-scalar + tensors are converted to Numpy arrays. + """ + if isinstance(tensors, coordinator_lib.RemoteValue): + return tensors.fetch() + + def _to_single_numpy_or_python_type(t): + if isinstance(t, tensor_lib.Tensor): + x = t.numpy() + return x.item() if np.ndim(x) == 0 else x + return t # Don't turn ragged or sparse tensors to NumPy. + + return nest.map_structure(_to_single_numpy_or_python_type, tensors) + + +def _astuple(attrs): + """Converts the given attrs to tuple non-recursively.""" + cls = type(attrs) + fields = getattr(cls, '__attrs_attrs__', None) + if fields is None: + raise ValueError('%r is not an attrs-decorated class.' % cls) + values = [] + for field in fields: + values.append(getattr(attrs, field.name)) + return tuple(values) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/version_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/version_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a76ec7c55b34bbb3f7694d89e8fc08d5ebe54352 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/version_utils.py @@ -0,0 +1,134 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +"""Utilities for Keras classes with v1 and v2 versions.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.keras.utils.generic_utils import LazyLoader + +# TODO(b/134426265): Switch back to single-quotes once the issue +# with copybara is fixed. +# pylint: disable=g-inconsistent-quotes +training = LazyLoader( + "training", globals(), + "tensorflow.python.keras.engine.training") +training_v1 = LazyLoader( + "training_v1", globals(), + "tensorflow.python.keras.engine.training_v1") +base_layer = LazyLoader( + "base_layer", globals(), + "tensorflow.python.keras.engine.base_layer") +base_layer_v1 = LazyLoader( + "base_layer_v1", globals(), + "tensorflow.python.keras.engine.base_layer_v1") +callbacks = LazyLoader( + "callbacks", globals(), + "tensorflow.python.keras.callbacks") +callbacks_v1 = LazyLoader( + "callbacks_v1", globals(), + "tensorflow.python.keras.callbacks_v1") + + +# pylint: enable=g-inconsistent-quotes + + +class ModelVersionSelector(object): + """Chooses between Keras v1 and v2 Model class.""" + + def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument + use_v2 = should_use_v2() + cls = swap_class(cls, training.Model, training_v1.Model, use_v2) # pylint: disable=self-cls-assignment + return super(ModelVersionSelector, cls).__new__(cls) + + +class LayerVersionSelector(object): + """Chooses between Keras v1 and v2 Layer class.""" + + def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument + use_v2 = should_use_v2() + cls = swap_class(cls, base_layer.Layer, base_layer_v1.Layer, use_v2) # pylint: disable=self-cls-assignment + return super(LayerVersionSelector, cls).__new__(cls) + + +class TensorBoardVersionSelector(object): + """Chooses between Keras v1 and v2 TensorBoard callback class.""" + + def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument + use_v2 = should_use_v2() + start_cls = cls + cls = swap_class(start_cls, callbacks.TensorBoard, callbacks_v1.TensorBoard, + use_v2) + if start_cls == callbacks_v1.TensorBoard and cls == callbacks.TensorBoard: + # Since the v2 class is not a subclass of the v1 class, __init__ has to + # be called manually. + return cls(*args, **kwargs) + return super(TensorBoardVersionSelector, cls).__new__(cls) + + +def should_use_v2(): + """Determine if v1 or v2 version should be used.""" + if context.executing_eagerly(): + return True + elif ops.executing_eagerly_outside_functions(): + # Check for a v1 `wrap_function` FuncGraph. + # Code inside a `wrap_function` is treated like v1 code. + graph = ops.get_default_graph() + if (getattr(graph, "name", False) and + graph.name.startswith("wrapped_function")): + return False + return True + else: + return False + + +def swap_class(cls, v2_cls, v1_cls, use_v2): + """Swaps in v2_cls or v1_cls depending on graph mode.""" + if cls == object: + return cls + if cls in (v2_cls, v1_cls): + return v2_cls if use_v2 else v1_cls + + # Recursively search superclasses to swap in the right Keras class. + new_bases = [] + for base in cls.__bases__: + if ((use_v2 and issubclass(base, v1_cls) + # `v1_cls` often extends `v2_cls`, so it may still call `swap_class` + # even if it doesn't need to. That being said, it may be the safest + # not to over optimize this logic for the sake of correctness, + # especially if we swap v1 & v2 classes that don't extend each other, + # or when the inheritance order is different. + or (not use_v2 and issubclass(base, v2_cls)))): + new_base = swap_class(base, v2_cls, v1_cls, use_v2) + else: + new_base = base + new_bases.append(new_base) + cls.__bases__ = tuple(new_bases) + return cls + + +def disallow_legacy_graph(cls_name, method_name): + if not ops.executing_eagerly_outside_functions(): + error_msg = ( + "Calling `{cls_name}.{method_name}` in graph mode is not supported " + "when the `{cls_name}` instance was constructed with eager mode " + "enabled. Please construct your `{cls_name}` instance in graph mode or" + " call `{cls_name}.{method_name}` with eager mode enabled.") + error_msg = error_msg.format(cls_name=cls_name, method_name=method_name) + raise ValueError(error_msg) + + +def is_v1_layer_or_model(obj): + return isinstance(obj, (base_layer_v1.Layer, training_v1.Model)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/vis_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/vis_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6026caa355fca9e7a773746b05288e3fd2a9b0be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/utils/vis_utils.py @@ -0,0 +1,345 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=g-import-not-at-top +"""Utilities related to model visualization.""" + +import os +import sys +from tensorflow.python.keras.utils.io_utils import path_to_string +from tensorflow.python.util import nest + + +try: + # pydot-ng is a fork of pydot that is better maintained. + import pydot_ng as pydot +except ImportError: + # pydotplus is an improved version of pydot + try: + import pydotplus as pydot + except ImportError: + # Fall back on pydot if necessary. + try: + import pydot + except ImportError: + pydot = None + + +def check_pydot(): + """Returns True if PyDot and Graphviz are available.""" + if pydot is None: + return False + try: + # Attempt to create an image of a blank graph + # to check the pydot/graphviz installation. + pydot.Dot.create(pydot.Dot()) + return True + except (OSError, pydot.InvocationException): + return False + + +def is_wrapped_model(layer): + from tensorflow.python.keras.engine import functional + from tensorflow.python.keras.layers import wrappers + return (isinstance(layer, wrappers.Wrapper) and + isinstance(layer.layer, functional.Functional)) + + +def add_edge(dot, src, dst): + if not dot.get_edge(src, dst): + dot.add_edge(pydot.Edge(src, dst)) + + +def model_to_dot(model, + show_shapes=False, + show_dtype=False, + show_layer_names=True, + rankdir='TB', + expand_nested=False, + dpi=96, + subgraph=False): + """Convert a Keras model to dot format. + + Args: + model: A Keras model instance. + show_shapes: whether to display shape information. + show_dtype: whether to display layer dtypes. + show_layer_names: whether to display layer names. + rankdir: `rankdir` argument passed to PyDot, + a string specifying the format of the plot: + 'TB' creates a vertical plot; + 'LR' creates a horizontal plot. + expand_nested: whether to expand nested models into clusters. + dpi: Dots per inch. + subgraph: whether to return a `pydot.Cluster` instance. + + Returns: + A `pydot.Dot` instance representing the Keras model or + a `pydot.Cluster` instance representing nested model if + `subgraph=True`. + + Raises: + ImportError: if graphviz or pydot are not available. + """ + from tensorflow.python.keras.layers import wrappers + from tensorflow.python.keras.engine import sequential + from tensorflow.python.keras.engine import functional + + if not check_pydot(): + message = ( + 'You must install pydot (`pip install pydot`) ' + 'and install graphviz ' + '(see instructions at https://graphviz.gitlab.io/download/) ', + 'for plot_model/model_to_dot to work.') + if 'IPython.core.magics.namespace' in sys.modules: + # We don't raise an exception here in order to avoid crashing notebook + # tests where graphviz is not available. + print(message) + return + else: + raise ImportError(message) + + if subgraph: + dot = pydot.Cluster(style='dashed', graph_name=model.name) + dot.set('label', model.name) + dot.set('labeljust', 'l') + else: + dot = pydot.Dot() + dot.set('rankdir', rankdir) + dot.set('concentrate', True) + dot.set('dpi', dpi) + dot.set_node_defaults(shape='record') + + sub_n_first_node = {} + sub_n_last_node = {} + sub_w_first_node = {} + sub_w_last_node = {} + + layers = model.layers + if not model._is_graph_network: + node = pydot.Node(str(id(model)), label=model.name) + dot.add_node(node) + return dot + elif isinstance(model, sequential.Sequential): + if not model.built: + model.build() + layers = super(sequential.Sequential, model).layers + + # Create graph nodes. + for i, layer in enumerate(layers): + layer_id = str(id(layer)) + + # Append a wrapped layer's label to node's label, if it exists. + layer_name = layer.name + class_name = layer.__class__.__name__ + + if isinstance(layer, wrappers.Wrapper): + if expand_nested and isinstance(layer.layer, + functional.Functional): + submodel_wrapper = model_to_dot( + layer.layer, + show_shapes, + show_dtype, + show_layer_names, + rankdir, + expand_nested, + subgraph=True) + # sub_w : submodel_wrapper + sub_w_nodes = submodel_wrapper.get_nodes() + sub_w_first_node[layer.layer.name] = sub_w_nodes[0] + sub_w_last_node[layer.layer.name] = sub_w_nodes[-1] + dot.add_subgraph(submodel_wrapper) + else: + layer_name = '{}({})'.format(layer_name, layer.layer.name) + child_class_name = layer.layer.__class__.__name__ + class_name = '{}({})'.format(class_name, child_class_name) + + if expand_nested and isinstance(layer, functional.Functional): + submodel_not_wrapper = model_to_dot( + layer, + show_shapes, + show_dtype, + show_layer_names, + rankdir, + expand_nested, + subgraph=True) + # sub_n : submodel_not_wrapper + sub_n_nodes = submodel_not_wrapper.get_nodes() + sub_n_first_node[layer.name] = sub_n_nodes[0] + sub_n_last_node[layer.name] = sub_n_nodes[-1] + dot.add_subgraph(submodel_not_wrapper) + + # Create node's label. + if show_layer_names: + label = '{}: {}'.format(layer_name, class_name) + else: + label = class_name + + # Rebuild the label as a table including the layer's dtype. + if show_dtype: + + def format_dtype(dtype): + if dtype is None: + return '?' + else: + return str(dtype) + + label = '%s|%s' % (label, format_dtype(layer.dtype)) + + # Rebuild the label as a table including input/output shapes. + if show_shapes: + + def format_shape(shape): + return str(shape).replace(str(None), 'None') + + try: + outputlabels = format_shape(layer.output_shape) + except AttributeError: + outputlabels = '?' + if hasattr(layer, 'input_shape'): + inputlabels = format_shape(layer.input_shape) + elif hasattr(layer, 'input_shapes'): + inputlabels = ', '.join( + [format_shape(ishape) for ishape in layer.input_shapes]) + else: + inputlabels = '?' + label = '%s\n|{input:|output:}|{{%s}|{%s}}' % (label, + inputlabels, + outputlabels) + + if not expand_nested or not isinstance( + layer, functional.Functional): + node = pydot.Node(layer_id, label=label) + dot.add_node(node) + + # Connect nodes with edges. + for layer in layers: + layer_id = str(id(layer)) + for i, node in enumerate(layer._inbound_nodes): + node_key = layer.name + '_ib-' + str(i) + if node_key in model._network_nodes: + for inbound_layer in nest.flatten(node.inbound_layers): + inbound_layer_id = str(id(inbound_layer)) + if not expand_nested: + assert dot.get_node(inbound_layer_id) + assert dot.get_node(layer_id) + add_edge(dot, inbound_layer_id, layer_id) + else: + # if inbound_layer is not Model or wrapped Model + if (not isinstance(inbound_layer, + functional.Functional) and + not is_wrapped_model(inbound_layer)): + # if current layer is not Model or wrapped Model + if (not isinstance(layer, functional.Functional) and + not is_wrapped_model(layer)): + assert dot.get_node(inbound_layer_id) + assert dot.get_node(layer_id) + add_edge(dot, inbound_layer_id, layer_id) + # if current layer is Model + elif isinstance(layer, functional.Functional): + add_edge(dot, inbound_layer_id, + sub_n_first_node[layer.name].get_name()) + # if current layer is wrapped Model + elif is_wrapped_model(layer): + add_edge(dot, inbound_layer_id, layer_id) + name = sub_w_first_node[layer.layer.name].get_name() + add_edge(dot, layer_id, name) + # if inbound_layer is Model + elif isinstance(inbound_layer, functional.Functional): + name = sub_n_last_node[inbound_layer.name].get_name() + if isinstance(layer, functional.Functional): + output_name = sub_n_first_node[layer.name].get_name() + add_edge(dot, name, output_name) + else: + add_edge(dot, name, layer_id) + # if inbound_layer is wrapped Model + elif is_wrapped_model(inbound_layer): + inbound_layer_name = inbound_layer.layer.name + add_edge(dot, + sub_w_last_node[inbound_layer_name].get_name(), + layer_id) + return dot + + +def plot_model(model, + to_file='model.png', + show_shapes=False, + show_dtype=False, + show_layer_names=True, + rankdir='TB', + expand_nested=False, + dpi=96): + """Converts a Keras model to dot format and save to a file. + + Example: + + ```python + input = tf.keras.Input(shape=(100,), dtype='int32', name='input') + x = tf.keras.layers.Embedding( + output_dim=512, input_dim=10000, input_length=100)(input) + x = tf.keras.layers.LSTM(32)(x) + x = tf.keras.layers.Dense(64, activation='relu')(x) + x = tf.keras.layers.Dense(64, activation='relu')(x) + x = tf.keras.layers.Dense(64, activation='relu')(x) + output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(x) + model = tf.keras.Model(inputs=[input], outputs=[output]) + dot_img_file = '/tmp/model_1.png' + tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True) + ``` + + Args: + model: A Keras model instance + to_file: File name of the plot image. + show_shapes: whether to display shape information. + show_dtype: whether to display layer dtypes. + show_layer_names: whether to display layer names. + rankdir: `rankdir` argument passed to PyDot, + a string specifying the format of the plot: + 'TB' creates a vertical plot; + 'LR' creates a horizontal plot. + expand_nested: Whether to expand nested models into clusters. + dpi: Dots per inch. + + Returns: + A Jupyter notebook Image object if Jupyter is installed. + This enables in-line display of the model plots in notebooks. + """ + dot = model_to_dot( + model, + show_shapes=show_shapes, + show_dtype=show_dtype, + show_layer_names=show_layer_names, + rankdir=rankdir, + expand_nested=expand_nested, + dpi=dpi) + to_file = path_to_string(to_file) + if dot is None: + return + _, extension = os.path.splitext(to_file) + if not extension: + extension = 'png' + else: + extension = extension[1:] + # Save image to disk. + dot.write(to_file, format=extension) + # Return the image as a Jupyter Image object, to be displayed in-line. + # Note that we cannot easily detect whether the code is running in a + # notebook, and thus we always return the Image if Jupyter is available. + if extension != 'pdf': + try: + from IPython import display + return display.Image(filename=to_file) + except ImportError: + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b70cc349140f45cf28d0c7f7c07763be39e26097 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/bias_op_base.py @@ -0,0 +1,322 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Functional tests for BiasAdd.""" + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +@test_util.run_all_in_graph_and_eager_modes +class BiasAddTestBase(test.TestCase): + + def _npBias(self, inputs, bias): + assert len(bias.shape) == 1 + assert inputs.shape[-1] == bias.shape[0] + return inputs + bias.reshape(([1] * + (len(inputs.shape) - 1)) + [bias.shape[0]]) + + def testNpBias(self): + self.assertAllClose( + np.array([[11, 22, 33], [41, 52, 63]]), + self._npBias( + np.array([[10, 20, 30], [40, 50, 60]]), np.array([1, 2, 3]))) + + def _testBias(self, np_inputs, np_bias, use_gpu=False): + np_val = self._npBias(np_inputs, np_bias) + with self.cached_session(use_gpu=use_gpu): + tf_val = self.evaluate(nn_ops.bias_add(np_inputs, np_bias)) + self.assertAllCloseAccordingToType(np_val, tf_val) + + def _AtLeast3d(self, np_value): + # fill the input value to at least 3-dimension + if np_value.ndim < 3: + return np.reshape(np_value, (1,) * (3 - np_value.ndim) + np_value.shape) + return np_value + + def _NHWCToNCHW(self, np_value): + # fill the input value to at least 3-dimension + np_value = self._AtLeast3d(np_value) + # move the last dimension to second + np_dim = list(range(np_value.ndim)) + np_dim_new = list(np_dim[0:1]) + list(np_dim[-1:]) + list(np_dim[1:-1]) + return np.transpose(np_value, np_dim_new) + + def _NCHWToNHWC(self, np_value): + assert len(np_value.shape) >= 3 + np_dim = list(range(np_value.ndim)) + # move the second dimension to the last + np_dim_new = list(np_dim[0:1]) + list(np_dim[2:]) + list(np_dim[1:2]) + return np.transpose(np_value, np_dim_new) + + def _testBiasNCHW(self, np_inputs, np_bias, use_gpu): + np_val = self._npBias(np_inputs, np_bias) + np_inputs = self._NHWCToNCHW(np_inputs) + with self.cached_session(use_gpu=use_gpu): + tf_val = self.evaluate( + nn_ops.bias_add(np_inputs, np_bias, data_format="NCHW")) + tf_val = self._NCHWToNHWC(tf_val) + self.assertAllCloseAccordingToType(self._AtLeast3d(np_val), tf_val) + + def _testAll(self, np_inputs, np_bias): + self._testBias(np_inputs, np_bias, use_gpu=False) + self._testBiasNCHW(np_inputs, np_bias, use_gpu=False) + if np_inputs.dtype in [np.float16, np.float32, np.float64, np.int32]: + self._testBias(np_inputs, np_bias, use_gpu=True) + self._testBiasNCHW(np_inputs, np_bias, use_gpu=True) + + def _expectedException(self): + if context.executing_eagerly(): + return errors_impl.InvalidArgumentError + else: + return ValueError + + def testInputDims(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add([1, 2], [1]) + + def testBiasVec(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add( + array_ops.reshape([1, 2], shape=[1, 2]), + array_ops.reshape([1, 2], shape=[1, 2])) + + def testBiasInputsMatch(self): + with self.assertRaises(self._expectedException()): + nn_ops.bias_add( + array_ops.reshape([1, 2], shape=[1, 2]), + array_ops.reshape([1], shape=[1])) + + def testIntTypes(self): + for t in [np.int8, np.int16, np.int32, np.int64]: + self._testAll( + np.array([[10, 20, 30], [40, 50, 60]]).astype(t), + np.array([1, 2, 3]).astype(t)) + + def testFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 3).astype(t), + np.random.rand(3).astype(t)) + + def test4DFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 2, 3).astype(t), + np.random.rand(3).astype(t)) + self._testAll( + np.random.rand(2048, 4, 4, 4).astype(t), + np.random.rand(4).astype(t)) + self._testAll( + np.random.rand(4, 4, 4, 2048).astype(t), + np.random.rand(2048).astype(t)) + + def test5DFloatTypes(self): + for t in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + self._testAll( + np.random.rand(4, 3, 2, 3, 4).astype(t), + np.random.rand(4).astype(t)) + + def _random_tensor(self, shape, dtype): + return constant_op.constant(2 * np.random.rand(*shape) - 1, dtype=dtype) + + def _computeGradient(self, np_input, bias, dtype, data_format): + input_shape = output_shape = np_input.shape + bias_shape = bias.shape + input_tensor = constant_op.constant( + np_input, shape=input_shape, dtype=dtype) + bias_tensor = constant_op.constant(bias, shape=bias_shape, dtype=dtype) + + if context.executing_eagerly(): + + def bias_add(input_tensor, bias_tensor): + return nn_ops.bias_add( + input_tensor, bias_tensor, data_format=data_format) + + # The following is a work-around for TF issue 33660. Instead of + # calculating the analytical and numerical gradients for both + # inputs in a single call to compute_gradient, compute_gradient + # is called for each input separately. + def bias_add_1(input_tensor): + return bias_add(input_tensor, bias_tensor) + + def bias_add_2(bias_tensor): + return bias_add(input_tensor, bias_tensor) + + input_jacob_a, input_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_1, [input_tensor]) + bias_jacob_a, bias_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_2, [bias_tensor]) + + # Test gradient of BiasAddGrad + def bias_add_grad_function(upstream_gradients): + with backprop.GradientTape() as tape: + tape.watch(bias_tensor) + bias_add_output = bias_add(input_tensor, bias_tensor) + gradient_injector_output = bias_add_output * upstream_gradients + return tape.gradient(gradient_injector_output, bias_tensor) + + upstream_tensor = self._random_tensor(output_shape, dtype) + grad_jacob_a, grad_jacob_n = gradient_checker_v2.compute_gradient( + bias_add_grad_function, [upstream_tensor]) + else: + output_tensor = nn_ops.bias_add( + input_tensor, bias_tensor, data_format=data_format) + jacobians = gradient_checker.compute_gradient([input_tensor, bias_tensor], + [input_shape, bias_shape], + output_tensor, output_shape) + (input_jacob_a, input_jacob_n), (bias_jacob_a, bias_jacob_n) = jacobians + # Test gradient of BiasAddGrad + if dtype == dtypes.bfloat16: + # L2Loss is not supported for bfloat16 on CPU. + output_tensor = math_ops.cast(output_tensor, dtype=dtypes.float32) + bias_add_grad = gradients_impl.gradients( + nn_ops.l2_loss(output_tensor), bias_tensor)[0] + grad_jacob_a, grad_jacob_n = gradient_checker.compute_gradient( + output_tensor, output_shape, bias_add_grad, bias_shape) + + return ((input_jacob_a, bias_jacob_a, grad_jacob_a), + (input_jacob_n, bias_jacob_n, grad_jacob_n)) + + def _testGradient(self, np_input, bias, dtype, data_format, use_gpu): + with self.cached_session(use_gpu=use_gpu): + if data_format == "NCHW": + np_input = self._NHWCToNCHW(np_input) + jacob_a, jacob_n = self._computeGradient(np_input, bias, dtype, + data_format) + input_jacob_a, bias_jacob_a, grad_jacob_a = jacob_a + input_jacob_n, bias_jacob_n, grad_jacob_n = jacob_n + + if dtype in [np.float16, dtypes.bfloat16.as_numpy_dtype]: + # Compare fp16/bf16 analytical gradients to fp32 numerical gradients, + # since fp16/bf16 numerical gradients are too imprecise unless great + # care is taken with choosing the inputs and the delta. This is + # a weaker, but pragmatic, check (in particular, it does not test + # the op itself, only its gradient). + _, jacob_n = self._computeGradient(np_input, bias, np.float32, + data_format) + input_jacob_n, bias_jacob_n, grad_jacob_n = jacob_n + + if dtype == dtypes.float64: + threshold = 1e-10 + elif np_input.size >= 512: + # The 5e-3 threshold seems to have been marginal in these cases, and + # small changes in the test were pushing it over the limit. + threshold = 5e-2 + else: + threshold = 5e-3 + self.assertAllClose(input_jacob_a, input_jacob_n, threshold, threshold) + self.assertAllClose(bias_jacob_a, bias_jacob_n, threshold, threshold) + self.assertAllClose(grad_jacob_a, grad_jacob_n, threshold, threshold) + + def testGradientTensor2D(self): + for (data_format, use_gpu) in ("NHWC", False), ("NHWC", True): + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + dtype=dtype.as_numpy_dtype).reshape(3, 2) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def testGradientTensor3D(self): + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + # pylint: disable=too-many-function-args + np_input = np.array( + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + dtype=dtype.as_numpy_dtype).reshape(1, 3, 2) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def testGradientTensor4D(self): + for (data_format, use_gpu) in [("NHWC", False)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.arange( + 1.0, 49.0, + dtype=dtype.as_numpy_dtype).reshape([2, 3, 4, 2]).astype(np.float32) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + np_input = np.arange( + 1.0, 513.0, + dtype=dtype.as_numpy_dtype).reshape([64, 2, 2, + 2]).astype(np.float32) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + np_input = np.arange( + 1.0, 513.0, + dtype=dtype.as_numpy_dtype).reshape([2, 2, 2, + 64]).astype(np.float32) + self._testGradient(np_input, + np.random.rand(64).astype(dtype.as_numpy_dtype), + dtype, data_format, use_gpu) + + def testGradientTensor5D(self): + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for dtype in (dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.bfloat16): + np_input = np.arange( + 1.0, 49.0, + dtype=dtype.as_numpy_dtype).reshape([1, 2, 3, 4, + 2]).astype(np.float32) + bias = np.array([1.3, 2.4], dtype=dtype.as_numpy_dtype) + self._testGradient(np_input, bias, dtype, data_format, use_gpu) + + def test1x1Image(self): + for (data_format, use_gpu) in [("NHWC", False), ("NCHW", False)]: + np_input = np.arange(1.0, 129.0).reshape([4, 1, 1, 32]).astype(np.float32) + self._testGradient(np_input, + np.random.rand(32).astype(np.float32), dtypes.float32, + data_format, use_gpu) + + def testEmpty(self): + np.random.seed(7) + for shape in (0, 0), (2, 0), (0, 2), (4, 3, 0), (4, 0, 3), (0, 4, 3): + self._testAll(np.random.randn(*shape), np.random.randn(shape[-1])) + + def testEmptyGradient(self): + for (data_format, use_gpu) in ("NHWC", False), ("NHWC", True): + for shape in (0, 0), (2, 0), (0, 2): + self._testGradient( + np.random.randn(*shape), np.random.randn(shape[-1]), dtypes.float64, + data_format, use_gpu) + + for (data_format, use_gpu) in [("NHWC", False), ("NHWC", True), + ("NCHW", False), ("NCHW", True)]: + for shape in (4, 3, 0), (4, 0, 3), (0, 4, 3): + self._testGradient( + np.random.randn(*shape), np.random.randn(shape[-1]), dtypes.float64, + data_format, use_gpu) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0535a1e6af136d9efc1f8be05b93f834572326ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/cudnn_deterministic_base.py @@ -0,0 +1,292 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for deterministic cuDNN functionality.""" + +import collections + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import test + +# Notes: +# +# TensorFlow makes cuDNN run deterministically when op determinism is enabled +# via tf.config.experimental.enable_op_determinism(). Additionally, setting the +# environmental variable TF_CUDNN_DETERMINISTIC to 'true' or '1' makes cuDNN run +# deterministically, although this environemtnal variable is deprecated and will +# be removed in a future TensorFlow version. Unlike the enable_op_determinism() +# function, the environmental variable only makes ops using cuDNN deterministic, +# not all TensorFlow ops. +# +# Where both deterministic and non-deterministic cuDNN algorithms are available, +# selecting determinitic operation will lead to only the deterministic +# algorithms being chosen. Additionally, selecting deterministic operation will +# result in a deterministic, or reproducible, selection of algorithms (for any +# given layer configuration) for each of the forward and the two backward paths. +# +# These tests intend to confirm that deterministic algorithms are chosen (for +# the back-prop paths) when desterministic operation is selected. The tested +# configurations were first confirmed to produce non-deterministic results when +# the above-mentioned environment variables are not set. +# +# Even though selecting determinitic operation should ensure that the same +# algorithms, for a given layer configuration, are always used (i.e. that +# algorithm selection is deterministic / reproducible), this is not tested. + +# TODO(duncanriach): Add test for deterministic cuDNN max-pooling + +LayerShapeNHWC = collections.namedtuple('LayerShapeNHWC', + 'batch, height, width, channels') +FilterShape2D = collections.namedtuple( + 'FilterShape2D', 'height, width, in_channels, out_channels') +FilterShape2DTranspose = collections.namedtuple( + 'FilterShape2DTranspose', 'height, width, out_channels, in_channels') + +LayerShapeNCDHW = collections.namedtuple( + 'LayerShapeNCDHW', 'batch, channels, depth, height, width') +FilterShape3D = collections.namedtuple( + 'FilterShape3D', 'depth, height, width, in_channels, out_channels') + + +class ConvolutionTest(test.TestCase): + """Tests for deterministic cuDNN functionality.""" + + def _random_data_op(self, shape): + # np.random.random_sample can properly interpret either tf.TensorShape or + # namedtuple as a list. + return constant_op.constant( + 2 * np.random.random_sample(shape) - 1, dtype=dtypes.float32) + + def _random_out_op(self, in_shape, filter_shape, strides, padding, dilations): + # Choosing not to use array_op.zeros() to prevent possible removal by + # optimization + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + # Use the forward op's shape-inference + conv_op = nn_ops.conv2d( + in_op, filter_op, strides=strides, padding=padding, dilations=dilations) + out_shape = conv_op.get_shape() + out_op = self._random_data_op(out_shape) + return out_op + + def _assert_reproducible(self, operation): + with test_util.force_gpu(): + result_1 = operation() + result_2 = operation() + self.assertAllEqual(result_1, result_2) + + # The default forward algorithm choice, when using cuDNN 7, does not support + # the following layer configuration. This test case intends to confirm that + # an alternative algorithm is selected. Note that, in cuDNN 7, all forward + # algorithms are determnistic. + @test_util.run_cuda_only + def testConvForwardDefaultAlgorithmChoice(self): + in_shape = LayerShapeNCDHW(batch=2, channels=3, depth=5, height=7, width=6) + filter_shape = FilterShape3D( + depth=3, height=3, width=3, in_channels=3, out_channels=2) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + self._assert_reproducible(lambda: nn_ops.conv3d( + in_op, + filter_op, + strides=[1, 1, 1, 1, 1], + padding='VALID', + data_format='NCDHW', + dilations=[1, 1, 2, 2, 2])) + + # This test is primarily testing XLA since cuDNN forward convolutions are + # always deterministic, even when determinism is not enabled. The convolution + # configuration tested is nondeterministic with XLA when determinism is not + # enabled. + @test_util.run_cuda_only + def testConvForwardXLA(self): + in_shape = LayerShapeNCDHW( + batch=2, channels=8, depth=5, height=12, width=15) + filter_shape = FilterShape3D( + depth=3, height=3, width=3, in_channels=8, out_channels=1) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + self._assert_reproducible(lambda: nn_ops.conv3d( + in_op, + filter_op, + strides=[1, 1, 1, 1, 1], + padding='VALID', + data_format='NCDHW', + dilations=[1, 1, 2, 2, 2])) + + @test_util.run_cuda_only + def testConvBackwardFilterGradient(self, rate=1): + in_shape = LayerShapeNHWC(batch=8, height=64, width=64, channels=8) + filter_shape = FilterShape2D( + height=3, width=3, in_channels=8, out_channels=8) + in_op = self._random_data_op(in_shape) + strides = [1, 1, 1, 1] + padding = 'SAME' + dilations = [1, rate, rate, 1] + out_op = self._random_out_op(in_shape, filter_shape, strides, padding, + dilations) + self._assert_reproducible(lambda: nn_ops.conv2d_backprop_filter( + in_op, + filter_shape, + out_op, + strides=strides, + padding=padding, + dilations=dilations)) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvBackwardFilterGradientWithDilations(self): + self.testConvBackwardFilterGradient(rate=2) + + @test_util.run_cuda_only + def testConvBackwardInputGradient(self, rate=1): + in_shape = LayerShapeNHWC(batch=1, height=16, width=16, channels=1) + filter_shape = FilterShape2D( + height=7, width=7, in_channels=1, out_channels=3) + filter_op = self._random_data_op(filter_shape) + strides = [1, 1, 1, 1] + padding = 'SAME' + dilations = [1, rate, rate, 1] + out_op = self._random_out_op(in_shape, filter_shape, strides, padding, + dilations) + self._assert_reproducible(lambda: nn_ops.conv2d_backprop_input( + in_shape, + filter_op, + out_op, + strides=strides, + padding=padding, + dilations=dilations)) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvBackwardInputGradientWithDilations(self): + self.testConvBackwardInputGradient(rate=2) + + @test_util.run_cuda_only + def testConvTransposeForward(self, rate=1): + in_channels = 3 + out_channels = 1 + in_shape = LayerShapeNHWC( + batch=1, height=16, width=16, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=7, width=7, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + self._assert_reproducible(lambda: nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1])) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvTransposeForwardWithDilations(self): + self.testConvTransposeForward(rate=2) + + @test_util.run_cuda_only + def testConvTransposeBackwardFilterGradient(self, rate=1): + in_channels = 8 + out_channels = 8 + in_shape = LayerShapeNHWC( + batch=8, height=64, width=64, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=3, width=3, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + upstream_gradients = self._random_data_op(out_shape) + + def gradient(): + with backprop.GradientTape() as tape: + tape.watch(filter_op) + op_output = nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1]) + gradient_injector_output = op_output * upstream_gradients + return tape.gradient(gradient_injector_output, [filter_op])[0] + + self._assert_reproducible(gradient) + + # A configuration for this test could not be found that exercises + # nondeterminism when using XLA with determinism not enabled. + @test_util.run_cuda_only + def testConvTransposeBackwardFilterGradientWithDilations(self): + self.testConvTransposeBackwardFilterGradient(rate=2) + + # A configuration for this test could not be found that exercises + # nondeterminism when determinism is not enabled (for either XLA or non-XLA). + @test_util.run_cuda_only + def testConvTransposeBackwardInputGradient(self, rate=1): + in_channels = 1 + out_channels = 3 + in_shape = LayerShapeNHWC( + batch=1, height=16, width=16, channels=in_channels) + filter_shape = FilterShape2DTranspose( + height=7, width=7, out_channels=out_channels, in_channels=in_channels) + in_op = self._random_data_op(in_shape) + filter_op = self._random_data_op(filter_shape) + out_shape = LayerShapeNHWC( + batch=in_shape.batch, + height=in_shape.height, + width=in_shape.width, + channels=out_channels) + upstream_gradients = self._random_data_op(out_shape) + + def gradient(): + with backprop.GradientTape() as tape: + tape.watch(in_op) + op_output = nn_ops.conv2d_transpose_v2( + in_op, + filter_op, + out_shape, + strides=1, + padding='SAME', + data_format='NHWC', + dilations=[1, rate, rate, 1]) + gradient_injector_output = op_output * upstream_gradients + return tape.gradient(gradient_injector_output, [in_op])[0] + + self._assert_reproducible(gradient) + + # A configuration for this test could not be found that exercises + # nondeterminism when determinism is not enabled (for either XLA or non-XLA). + @test_util.run_cuda_only + def testConvTransposeBackwardInputGradientWithDilations(self): + self.testConvTransposeBackwardInputGradient(rate=2) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f63ad6ce9a94522dac5984f79999836ca478eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/depthwise_conv_op_base.py @@ -0,0 +1,1179 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Functional tests for depthwise convolutional operations.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging + + +def _DepthwiseConv2dNumpyBasic(x1, x2, strides): + """Compute depthwise_conv2d using Numpy. + + This allows use to test TensorFlow's depthwise_conv2d by comparing to the + Numpy version. + + Args: + x1: The input Numpy array, in NHWC format. + x2: The filter Numpy array. + strides: A Python list of 4 elements representing the strides. + + Returns: + The depthwise conv2d output as a Numpy array. + """ + n, h, w, c = x1.shape + fh, fw, c2, o = x2.shape + assert c == c2 + _, sh, sw, _ = strides + out_rows = (h - fh + sh) // sh + out_cols = (w - fw + sw) // sw + out = np.zeros([n, out_rows, out_cols, c * o]) + for i in range(out_rows): + for j in range(out_cols): + for k in range(c): + start_height = i * sh + end_height = start_height + fh + start_width = j * sw + end_width = start_width + fw + # multiplied_slice.shape: (b, fh, fw, o) + multiplied_slice = ( + x1[:, start_height:end_height, start_width:end_width, k, np.newaxis] + * x2[:, :, k, :]) + # Set a slice of b * o elements of 'out'. + out[:, i, j, k * o:(k + 1) * o] = np.sum(multiplied_slice, axis=(1, 2)) + return out + + +def _DepthwiseConv2dNumpy(x1, x2, strides, padding, data_format, dilations): + """Compute depthwise_conv2d using Numpy. + + This allows use to test TensorFlow's depthwise_conv2d by comparing to the + Numpy version. + + Unlike `_DepthwiseConv2dNumpyBasic`, this supports more advanced features + like padding. + + Args: + x1: The input Numpy array. + x2: The filter Numpy array. + strides: A Python list of 4 elements representing the strides. + padding: The padding. "SAME", "VALID", or a list of explicit paddings. + data_format: "NHWC" or "NCHW". + dilations: A list of 2 elements, representing the dilations. + + Returns: + The depthwise conv2d as a Numpy array. + """ + if data_format == "NCHW": + # Transpose arguments to NHWC format. + x1 = np.transpose(x1, (0, 3, 1, 2)) + strides = [strides[0], strides[3], strides[1], strides[2]] + if dilations: + dilations = [dilations[0], dilations[3], dilations[1], dilations[2]] + + if dilations: + # Dilate the filter so _DepthwiseConv2dNumpyBasic doesn't have to deal with + # dilations. + fh, fw, c, o = x2.shape + new_fh = (fh - 1) * dilations[0] + 1 + new_fw = (fw - 1) * dilations[1] + 1 + new_x2 = np.zeros((new_fh, new_fw, c, o)) + for i in range(fh): + for j in range(fw): + new_x2[i * dilations[0], j * dilations[1], ::] = x2[i, j, :, :] + x2 = new_x2 + + # Pad input so _DepthwiseConv2dNumpyBasic doesn't have to deal with padding. + if padding == "SAME": + + def PaddingsForDim(input_dim, filter_dim, stride): + """Computes paddings for a single dimension.""" + if input_dim % stride == 0: + total_padding = max(filter_dim - stride, 0) + else: + total_padding = max(filter_dim - (input_dim % stride), 0) + pad_before = total_padding // 2 + pad_after = total_padding - pad_before + return pad_before, pad_after + + padding = [(0, 0), + PaddingsForDim(x1.shape[1], x2.shape[0], strides[1]), + PaddingsForDim(x1.shape[2], x2.shape[1], strides[2]), (0, 0)] + elif padding == "VALID": + padding = [(0, 0)] * 4 + x1 = np.pad(x1, padding, "constant") + + y = _DepthwiseConv2dNumpyBasic(x1, x2, strides) + + if data_format == "NCHW": + # Transpose back to NCHW format. + y = np.transpose(y, (0, 2, 3, 1)) + + return y + + +def ConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding="SAME", + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([4, 5, 5, 48], [1, 1, 48, 2], [4, 5, 5, 96]), + Config([4, 8, 8, 84], [1, 3, 84, 1], [4, 8, 8, 84]), + Config([4, 17, 17, 48], [3, 1, 48, 4], [4, 17, 17, 192]), + Config([4, 9, 27, 8], [3, 3, 8, 1], [4, 9, 27, 8]), + Config([4, 31, 31, 7], [3, 3, 7, 1], [4, 31, 31, 7]), + Config([4, 35, 35, 2], [5, 5, 2, 1], [4, 35, 35, 2]), + Config([4, 147, 147, 2], [3, 3, 2, 8], [4, 49, 49, 16], + 3, + padding="VALID"), + Config([3, 299, 299, 3], [3, 2, 3, 8], [3, 150, 150, 24], 2), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 92, 92, 2], 2), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 183, 183, 2], dilations=[2, + 2]), + Config([5, 41, 35, 2], [4, 7, 2, 2], [5, 32, 23, 4], + padding="VALID", + dilations=[3, 2]), + ] + + +def ConfigsToTestExplicit(): + """Iterator for different convolution shapes, strides and explicit paddings. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding=None, + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([4, 5, 5, 48], [1, 1, 48, 2], [4, 8, 12, 96], + padding=[[1, 2], [3, 4]]), + Config([4, 1, 1, 3], [3, 3, 3, 2], [4, 29, 39, 6], + padding=[[10, 20], [15, 25]]), + Config([4, 9, 27, 8], [3, 3, 8, 1], [4, 14, 31, 8], + padding=[[3, 4], [4, 2]]), + Config([4, 31, 31, 7], [3, 3, 7, 1], [4, 29, 29, 7], + padding=[[0, 0], [0, 0]]), + Config([3, 299, 299, 3], [3, 2, 3, 8], [3, 150, 153, 24], + 2, + padding=[[1, 2], [3, 5]]), + Config([5, 183, 183, 1], [5, 5, 1, 2], [5, 62, 60, 2], + 3, + padding=[[3, 2], [1, 0]]), + Config([5, 29, 31, 1], [5, 4, 1, 2], [5, 26, 23, 2], + padding=[[3, 2], [1, 0]], + dilations=[2, 3]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([4, 5, 5, 48], [3, 3, 48, 1], [4, 5, 5, 48], + padding=[[0, 2], [0, 2]]), + Config([1, 8, 7, 2], [8, 7, 2, 1], [1, 8, 7, 2], padding=[[0, 7], [3, + 3]]), + Config([2, 4, 3, 2], [3, 2, 2, 1], [2, 4, 3, 2], padding=[[2, 0], [1, + 0]]), + ] + + +def CheckGradConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + compute_gradient_error() is very expensive. So the configs should be + relatively small. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding="SAME", + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([2, 5, 8, 1], [4, 4, 1, 2], [2, 5, 8, 2]), + Config([4, 5, 5, 1], [2, 2, 1, 2], [4, 2, 2, 2], 2, padding="VALID"), + Config([2, 4, 4, 2], [3, 1, 2, 2], [2, 4, 4, 4]), + Config([1, 15, 15, 2], [1, 3, 2, 1], [1, 15, 15, 2]), + Config([2, 15, 16, 1], [3, 3, 1, 2], [2, 5, 5, 2], 3, padding="VALID"), + Config([2, 5, 8, 1], [4, 3, 1, 2], [2, 5, 8, 2], dilations=[1, 2]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([1, 3, 1, 2], [2, 1, 2, 1], [1, 3, 1, 2]), + Config([2, 2, 3, 2], [2, 1, 2, 1], [2, 2, 3, 2]), + Config([2, 2, 3, 1], [2, 2, 1, 1], [2, 2, 3, 1]), + ] + + +def CheckGradConfigsToTestExplicit(): + """Iterator for different convolution shapes, strides and explicit paddings. + + compute_gradient_error() is very expensive. So the configs should be + relatively small. + + Returns: + List of tuples (input_size, filter_size, out_size, stride, padding, + dilations), the depthwise convolution parameters. + """ + + def Config(input_size, + filter_size, + out_size, + stride=1, + padding=None, + dilations=None): + return input_size, filter_size, out_size, stride, padding, dilations + + return [ + Config([2, 5, 8, 1], [4, 4, 1, 2], [2, 3, 10, 2], + padding=[[0, 1], [2, 3]]), + Config([4, 5, 5, 1], [2, 2, 1, 2], [4, 4, 5, 2], + 2, + padding=[[3, 1], [5, 0]]), + Config([2, 4, 4, 2], [3, 1, 2, 2], [2, 7, 11, 4], + padding=[[4, 1], [3, 4]]), + Config([1, 15, 15, 2], [1, 3, 2, 1], [1, 18, 23, 2], + padding=[[3, 0], [2, 8]]), + Config([2, 15, 16, 1], [3, 3, 1, 2], [2, 5, 8, 2], + 3, + padding=[[0, 0], [10, 0]]), + Config([2, 5, 8, 1], [3, 4, 1, 2], [2, 5, 10, 2], + padding=[[3, 1], [2, 3]], + dilations=[2, 1]), + # These cases test the kernels in depthwise_conv_op_gpu.h which are used + # if the input size is small. + Config([2, 4, 3, 2], [3, 2, 2, 1], [2, 4, 3, 2], padding=[[2, 0], [1, + 0]]), + ] + + +class DepthwiseConv2DBase(test.TestCase): + """Base test class for depthwise Conv2D tests.""" + + # This tests depthwise_conv2d and depthwise_conv2d_native + def _VerifyValues(self, + tensor_in_sizes, + filter_in_sizes, + stride, + padding, + data_type, + use_gpu, + grouped_conv=False, + data_format="NHWC", + dilations=None, + tolerance=None): + """Verifies the output values of the convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in [batch, input_rows, + input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, + input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + data_type: The data type to use. + use_gpu: Whether to use GPU. + grouped_conv: Whether to use cuDNN 7's grouped convolution. + data_format: The data_format of the input. "NHWC" or "NCHW". + dilations: A list of 2 elements, representing the dilations. + tolerance: The absolute and relative tolarance when verifying the output. + """ + input_size = 1 + filter_size = 1 + for s in tensor_in_sizes: + input_size *= s + for s in filter_in_sizes: + filter_size *= s + # Initializes the input and filter tensor with numbers incrementing to 1.0. + x1 = [f * 1.0 / input_size for f in range(1, input_size + 1)] + x1 = np.array(x1).reshape(tensor_in_sizes) + x2 = [f * 1.0 / filter_size for f in range(1, filter_size + 1)] + x2 = np.array(x2).reshape(filter_in_sizes) + # Compute reference result + strides = [1, stride, stride, 1] + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + np_result = _DepthwiseConv2dNumpy(x1, x2, strides, padding, "NHWC", + dilations) + + ops.reset_default_graph() + graph = ops.get_default_graph() + with self.session(graph=graph, use_gpu=use_gpu) as sess: + tolerance = tolerance or { + dtypes.float16: 4e-2, + dtypes.float32: 1e-5, + dtypes.float64: 1e-12, + dtypes.bfloat16: 1e-2, + }[data_type] + + t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=data_type) + t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=data_type) + + if data_format == "NCHW": + # Transpose from NHWC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + t1 = array_ops.transpose(t1, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + if isinstance(padding, list): + padding = [padding[0], padding[3], padding[1], padding[2]] + + # depthwise_conv2d_native does not support dilations except on TPUs. + if dilations is None: + with sess.graph._kernel_label_map( # pylint: disable=protected-access + {"DepthwiseConv2dNative": "cudnn_grouped_convolution"} + if grouped_conv else {}): + conv_native = nn_ops.depthwise_conv2d_native( + t1, t2, strides=strides, data_format=data_format, padding=padding) + + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1]) + + try: + # The Numpy array from calling depthwise_conv2d_native + native_result = self.evaluate(conv_native) + except errors.InvalidArgumentError as e: + # Grouped convolution kernel is only registered for cuDNN 7. Silently + # return when we are running on an earlier version or without GPU. + if ("No OpKernel was registered to support Op " + "'DepthwiseConv2dNative'") in e.message: + tf_logging.warn("Skipping grouped convolution test") + return + raise e + + conv_interface = nn_impl.depthwise_conv2d( + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations) + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_interface = array_ops.transpose(conv_interface, [0, 2, 3, 1]) + + # The Numpy array from calling depthwise_conv2d + interface_result = self.evaluate(conv_interface) + + if dilations is None: + self.assertAllClose( + native_result, np_result, atol=tolerance, rtol=tolerance) + self.assertAllClose( + interface_result, np_result, atol=tolerance, rtol=tolerance) + + @test_util.run_v1_only("b/120545219") + @test_util.run_cuda_only + def testDepthwiseConv2DCudnn(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + # The CuDNN depthwise conv is turned on only when input/output is NCHW and + # float16(half). See cudnn release note 7.6.3. + tf_logging.info( + "Testing DepthwiseConv2DCudnn, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2D(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2D, %dth config: %r * %r, stride: %d, padding: " + "%s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + tf_logging.info("Testing without grouped_conv") + tolerance = 1e-4 if data_type == dtypes.float32 else 1e-12 + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + dilations=dilations, + tolerance=tolerance) + tf_logging.info("Testing with grouped_conv") + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + grouped_conv=True, + dilations=dilations, + tolerance=tolerance) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DWithUnknownShape(self): + # GitHub issue 22110. + if not test.is_gpu_available(): + return + with self.session(): + x = array_ops.placeholder(dtypes.float32) + f = np.ones([1, 1, 1, 1], np.float32) + v = nn_impl.depthwise_conv2d( + x, f, [1, 1, 1, 1], "VALID", rate=[2, 1], data_format="NCHW") + self.assertAllEqual( + np.ones([1, 1, 1, 1], np.float32), + v.eval(feed_dict={x: np.ones([1, 1, 1, 1], np.float32)})) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFormat, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + tolerance = 1e-4 if data_type == dtypes.float32 else 1e-12 + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format="NCHW", + dilations=dilations, + tolerance=tolerance) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DExplicit(self): + for index, (input_size, filter_size, _, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2D, %dth config: %r * %r, stride: %d, padding: " + "%s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform and its support for bfloat16 is unknown. + data_types = [dtypes.float16, dtypes.float32] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64, dtypes.bfloat16]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + tolerance = 2e-2 if data_type == dtypes.bfloat16 else None + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + use_gpu=True, + data_format=data_format, + dilations=dilations, + tolerance=tolerance) + + +# This is testing against hand calculated results. + + def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, + expected, use_gpu): + """Verifies the output values of the depthwise convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in [batch, input_rows, + input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, + input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + expected: An array containing the expected operation outputs. + use_gpu: Whether to use GPU. + """ + total_size_1 = 1 + total_size_2 = 1 + for s in tensor_in_sizes: + total_size_1 *= s + for s in filter_in_sizes: + total_size_2 *= s + # Initializes the input tensor with array containing incrementing + # numbers from 1. + x1 = [f * 1.0 for f in range(1, total_size_1 + 1)] + x2 = [f * 1.0 for f in range(1, total_size_2 + 1)] + with self.cached_session(use_gpu=use_gpu) as sess: + t1 = constant_op.constant(x1, shape=tensor_in_sizes) + t1.set_shape(tensor_in_sizes) + t2 = constant_op.constant(x2, shape=filter_in_sizes) + conv = nn_ops.depthwise_conv2d_native( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + value = self.evaluate(conv) + tf_logging.info("value = %r", value) + self.assertArrayNear(expected, np.ravel(value), 1e-5) + self.assertShapeEqual(value, conv) + + def testConv2D2x2Filter(self): + # The inputs look like this (it's a 3 x 2 matrix, each of depth 2): + # + # [ (1.0, 2.0), (3.0, 4.0), ( 5.0, 6.0) ] + # [ (7.0, 8.0), (9.0, 10.0), (11.0, 12.0) ] + # We can view this as two inputs + # + # input depth 0: + # + # [ 1.0, 3.0, 5.0 ] + # [ 7.0, 9.0, 11.0 ] + # + # input depth 1: + # + # [ 2.0, 4.0, 6.0 ] + # [ 8.0, 10.0, 12.0 ] + # + # The filter looks like this (it has two 2 x 2 patches, each generating 2 + # depths): + # + # filter #0: + # + # [ (1.0, 3.0), ( 5.0, 7.0)] + # [ (9.0, 11.0), (13.0, 15.0)] + # + # filter #1: + # + # [ ( 2.0, 4.0), ( 6.0, 8.0)] + # [ (10.0, 12.0), (14.0, 16.0)] + # + # So the outputs are: + # + # (position 0, 0: in_depth 0, output_depth 0 -- using filter #0) + # 1.0 * 1.0 + 7.0 * 9.0 + 3.0 * 5.0 + 9.0 * 13.0 = 196 + # (position 0, 0: in_depth 0, output_depth 1 -- using filter #1) + # 1.0 * 2.0 + 7.0 * 10.0 + 3.0 * 6.0 + 9.0 * 14.0 = 216 + # (position 0, 0: in_depth 1, output_depth 2 -- using filter #0) + # 2.0 * 3.0 + 8.0 * 11.0 + 4.0 * 7.0 + 10.0 * 15.0 = 272 + # (position 0, 0: in_depth 1, output_depth 3 -- using filter #1) + # 2.0 * 4.0 + 8.0 * 12.0 + 4.0 * 8.0 + 10.0 * 16.0 = 296 + # + # (position 1, 0: in_depth 0, output_depth 0 -- using filter #0) + # 3.0 * 1.0 + 9.0 * 9.0 + 5.0 * 5.0 + 11.0 * 13.0 = 252 + # (position 1, 0: in_depth 0, output_depth 1 -- using filter #1) + # 3.0 * 2.0 + 9.0 * 10.0 + 5.0 * 6.0 + 11.0 * 14.0 = 280 + # (position 1, 0: in_depth 1, output_depth 2 -- using filter #0) + # 4.0 * 3.0 + 10.0 * 11.0 + 6.0 * 7.0 + 12.0 * 15.0 = 344 + # (position 1, 0: in_depth 1, output_depth 3 -- using filter #1) + # 4.0 * 4.0 + 10.0 * 12.0 + 6.0 * 8.0 + 12.0 * 16.0 = 376 + expected_output = [196, 216, 272, 296, 252, 280, 344, 376] + self._VerifyHandValues( + tensor_in_sizes=[1, 2, 3, 2], + filter_in_sizes=[2, 2, 2, 2], + stride=1, + padding="VALID", + expected=expected_output, + use_gpu=False) + + self._VerifyHandValues( + tensor_in_sizes=[1, 2, 3, 2], + filter_in_sizes=[2, 2, 2, 2], + stride=1, + padding="VALID", + expected=expected_output, + use_gpu=True) + + # Gradient checkers. This tests depthwise gradient computations for both + # BackpropFilter and BackpropInput by comparing gradients computed by the + # depthwise gradient ops with the gradients computed numerically (details can + # be found in the compute_gradient_error(). + # Note this check is very expensive so the input should not be too big. + def _ConstructAndTestGradient(self, + input_shape, + filter_shape, + output_shape, + stride, + padding, + data_type, + test_input, + use_gpu, + grouped_conv=False, + data_format="NHWC", + dilations=None): + input_size = 1 + for x in input_shape: + input_size *= x + filter_size = 1 + for x in filter_shape: + filter_size *= x + input_data = [x * 1.0 / input_size for x in range(0, input_size)] + input_np = np.array(input_data).reshape(input_shape) + filter_data = [x * 1.0 / filter_size for x in range(0, filter_size)] + filter_np = np.array(filter_data).reshape(filter_shape) + ops.reset_default_graph() + graph = ops.get_default_graph() + with self.session(graph=graph, use_gpu=use_gpu) as sess: + tolerance = { + dtypes.float16: 4e-0, + dtypes.float32: 8e-4, + dtypes.float64: 1e-12, + dtypes.bfloat16: 1e-0, + }[data_type] + + input_tensor = constant_op.constant( + input_np, shape=input_shape, dtype=data_type, name="input") + filter_tensor = constant_op.constant( + filter_np, shape=filter_shape, dtype=data_type, name="filter") + + native_input = input_tensor + strides = [1, stride, stride, 1] + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + if data_format == "NCHW": + # Transpose from NHWC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_input = array_ops.transpose(input_tensor, [0, 3, 1, 2]) + input_shape = [ + input_shape[0], input_shape[3], input_shape[1], input_shape[2] + ] + output_shape = [ + output_shape[0], output_shape[3], output_shape[1], output_shape[2] + ] + strides = [1, 1, stride, stride] + if isinstance(padding, list): + padding = [padding[0], padding[3], padding[1], padding[2]] + + with sess.graph._kernel_label_map({ # pylint: disable=protected-access,g-long-ternary + "DepthwiseConv2dNative": "cudnn_grouped_convolution", + "DepthwiseConv2dNativeBackpropInput": "cudnn_grouped_convolution", + "DepthwiseConv2dNativeBackpropFilter": "cudnn_grouped_convolution", + } if grouped_conv else {}): + depthwise_conv2d = nn_impl.depthwise_conv2d( + native_input, + filter_tensor, + strides, + padding, + data_format=data_format, + dilations=dilations, + name="depthwise_conv2d") + + self.assertEqual(output_shape, depthwise_conv2d.get_shape()) + + try: + if test_input: + err = gradient_checker.compute_gradient_error(native_input, + input_shape, + depthwise_conv2d, + output_shape) + else: + err = gradient_checker.compute_gradient_error(filter_tensor, + filter_shape, + depthwise_conv2d, + output_shape) + except errors.InvalidArgumentError as e: + # TODO(xjun): Tests depend on error messages could be brittle. + # Grouped convolution kernel is only registered for cuDNN 7. Silently + # return when we are running on an earlier version or without GPU. + if grouped_conv and ("No OpKernel was registered to support Op " + "'DepthwiseConv2dNative'") in e.message: + tf_logging.warn("Skipping grouped convolution test") + return + raise e + + tf_logging.info( + "data_type: %r, use_gpu: %r, grouped_conv: %r, error = %f", data_type, + use_gpu, grouped_conv, err) + self.assertLess(err, tolerance) + + @test_util.run_v1_only("b/120545219") + @test_util.run_cuda_only + def testDepthwiseConv2DInputGradCudnn(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + # The CuDNN depthwise conv (input gradient) is turned on only when + # stride = 1, input/output is NCHW and float16(half). See cudnn release + # note 7.6.3. + if stride != 1: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCudnn, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGrad(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DInputGrad, %dth config: %r * %r, stride: %d, " + "padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + dilations=dilations) + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + grouped_conv=True, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGradFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DInputGradFormat, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DInputGradExplicit(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2DInputGradExplicit, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform and its support for bfloat16 is unknown. + data_types = [dtypes.float16, dtypes.float32] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64, dtypes.bfloat16]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=True, + use_gpu=True, + data_format=data_format, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + @test_util.run_cuda_only + def testDepthwiseConv2DFilterGradCudnn(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + # The CuDNN depthwise conv (filter gradient) is turned on only when + # input/output is float16(half). See cudnn release note 7.6.3. + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCudnn, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + data_types = [dtypes.float16, dtypes.bfloat16] + for data_type in data_types: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NHWC", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGrad(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGrad, %dth config: %r * %r, stride: " + "%d, padding: %s", index, input_size, filter_size, stride, padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float16, dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGradFormat(self): + if not test.is_gpu_available(): + return + + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTest()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGradFormat, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform + optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] + for data_type in ([dtypes.float32] + optional_float64): + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format="NCHW", + dilations=dilations) + + @test_util.run_v1_only("b/120545219") + def testDepthwiseConv2DFilterGradExplicit(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(CheckGradConfigsToTestExplicit()): + tf_logging.info( + "Testing DepthwiseConv2DFilterGradExplicit, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # double datatype is currently not supported for convolution ops + # on the ROCm platform and its support for bfloat16 is unknown. + data_types = [dtypes.float16, dtypes.float32] + if not test.is_built_with_rocm(): + data_types.extend([dtypes.float64, dtypes.bfloat16]) + data_formats = ["NHWC", "NCHW"] if test.is_gpu_available() else ["NHWC"] + for data_type in data_types: + for data_format in data_formats: + self._ConstructAndTestGradient( + input_size, + filter_size, + output_size, + stride, + padding, + data_type, + test_input=False, + use_gpu=True, + data_format=data_format, + dilations=dilations) + + def _CompareBackpropInput(self, input_sizes, filter_sizes, output_sizes, + stride, padding, dtype): + x1 = np.random.rand(*filter_sizes) + x2 = np.random.rand(*output_sizes) + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + + def _GetVal(use_gpu, dtype): + with self.cached_session(use_gpu=use_gpu): + t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) + t1 = constant_op.constant(x1, shape=filter_sizes, dtype=dtype) + t2 = constant_op.constant(x2, shape=output_sizes, dtype=dtype) + backprop = nn_ops.depthwise_conv2d_native_backprop_input( + t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) + ret = self.evaluate(backprop) + self.assertShapeEqual(ret, backprop) + return ret + + rtol, atol = (1e-1, 1e-1) if dtype == "bfloat16" else (1e-4, 1e-4) + gpu_value = _GetVal(use_gpu=True, dtype=dtype) + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + self.assertAllClose(cpu_value, gpu_value, rtol=rtol, atol=atol) + + @test_util.run_gpu_only + def testDepthwiseConv2DInputGradCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float32") + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float64") + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + @test_util.run_gpu_only + def testDepthwiseConv2DInputGradExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DInputGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float32") + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "float64") + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + def _CompareBackpropFilter(self, input_sizes, filter_sizes, output_sizes, + stride, padding, dtype): + x0 = np.random.rand(*input_sizes) + x2 = np.random.rand(*output_sizes) + padding_nhwc = padding + padding_nchw = padding + if isinstance(padding, list): + padding_nhwc = [(0, 0)] + padding + [(0, 0)] + padding_nchw = [(0, 0)] + [(0, 0)] + padding + + def _GetVal(use_gpu, dtype, data_format="NHWC"): + with self.cached_session(use_gpu=use_gpu): + t0 = constant_op.constant(x0, shape=input_sizes, dtype=dtype) + t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) + t2 = constant_op.constant(x2, shape=output_sizes, dtype=dtype) + strides = [1, stride, stride, 1] + padding = padding_nhwc + if data_format == "NCHW": + t0 = array_ops.transpose(t0, [0, 3, 1, 2]) + t2 = array_ops.transpose(t2, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + padding = padding_nchw + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + t0, + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format) + ret = self.evaluate(backprop) + self.assertShapeEqual(ret, backprop) + return ret + + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + for data_format in ["NHWC", "NCHW"]: + gpu_value = _GetVal(use_gpu=True, dtype=dtype, data_format=data_format) + self.assertAllCloseAccordingToType( + cpu_value, gpu_value, rtol=1e-4, atol=1e-4, bfloat16_rtol=1e-0) + + @test_util.run_gpu_only + def testDepthwiseConv2DFilterGradCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float32") + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float64") + + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + @test_util.run_gpu_only + def testDepthwiseConv2DFilterGradExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DFilterGradCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float32") + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "float64") + + self._CompareBackpropFilter(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + def _CompareForward(self, input_sizes, filter_sizes, output_sizes, stride, + padding, dtype): + x1 = np.random.rand(*input_sizes) + x2 = np.random.rand(*filter_sizes) + if isinstance(padding, list): + padding = [(0, 0)] + padding + [(0, 0)] + + def _GetVal(use_gpu, dtype): + with self.cached_session(use_gpu=use_gpu): + t1 = constant_op.constant(x1, shape=input_sizes, dtype=dtype) + t2 = constant_op.constant(x2, shape=filter_sizes, dtype=dtype) + output = nn_ops.depthwise_conv2d_native( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + ret = self.evaluate(output) + self.assertShapeEqual(ret, output) + return ret + + gpu_value = _GetVal(use_gpu=True, dtype=dtype) + cpu_value = _GetVal(use_gpu=False, dtype=dtype) + self.assertAllCloseAccordingToType( + cpu_value, gpu_value, rtol=1e-4, atol=1e-4, bfloat16_rtol=1e-1) + + @test_util.run_gpu_only + def testDepthwiseConv2DForwardCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTest()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DForwardCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float32") + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float64") + + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "bfloat16") + + @test_util.run_gpu_only + def testDepthwiseConv2DForwardExplicitCompare(self): + for index, (input_size, filter_size, output_size, stride, padding, + dilations) in enumerate(ConfigsToTestExplicit()): + if dilations: + continue + tf_logging.info( + "Testing DepthwiseConv2DForwardCompare, %dth config: %r * %r, " + "stride: %d, padding: %s", index, input_size, filter_size, stride, + padding) + # Convolutions on the ROCm platform don't support double dtype. And its + # support for bf16 is unknown. So, we skip these tests. + if test.is_built_with_rocm(): + continue + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float64") + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "float32") + + self._CompareForward(input_size, filter_size, output_size, stride, + padding, "bfloat16") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..80948fa7328d9743d339be07c9f33bd7ddb6e8b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/nn_ops/xent_op_test_base.py @@ -0,0 +1,293 @@ +# Copyright 2015-2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for SoftmaxCrossEntropyWithLogits op.""" + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +# The following import is required to register the gradient function. +from tensorflow.python.ops.nn_grad import _SoftmaxCrossEntropyWithLogitsGrad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +class XentOpTestBase(test.TestCase): + + def _opFwdBwd(self, labels, logits, axis=-1): + """ Runs the op-under-test both forwards and backwards.""" + logits = ops.convert_to_tensor(logits) # needed for the gradient tape + with backprop.GradientTape() as tape: + tape.watch(logits) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, dim=axis) + return loss, tape.gradient(loss, logits) + + def _npXent(self, labels, logits, dim=-1): + if dim == -1: + dim = len(logits.shape) - 1 + one_only_on_dim = list(logits.shape) + one_only_on_dim[dim] = 1 + e = np.exp(logits - np.reshape(np.amax(logits, axis=dim), one_only_on_dim)) + probs = e / np.reshape(np.sum(e, axis=dim), one_only_on_dim) + bp = (probs - labels) + l = -np.sum(labels * np.log(probs + 1.0e-20), axis=dim) + return l, bp + + # TODO(b/123860949): The values are constant folded for XLA, so placeholders + # are needed. + def _testXent2D(self, + np_labels, + np_logits, + with_placeholders=False, + expected_gradient=None): + np_loss, np_gradient = self._npXent(labels=np_labels, logits=np_logits) + if expected_gradient is not None: + np_gradient = expected_gradient + with self.cached_session() as sess: + if with_placeholders: + logits_placeholder = array_ops.placeholder(np_logits.dtype) + labels_placeholder = array_ops.placeholder(np_labels.dtype) + loss, gradient = self._opFwdBwd(labels_placeholder, logits_placeholder) + tf_loss, tf_gradient = sess.run([loss, gradient], + feed_dict={ + labels_placeholder: np_labels, + logits_placeholder: np_logits + }) + else: + loss, gradient = self._opFwdBwd(np_labels, np_logits) + tf_loss, tf_gradient = self.evaluate([loss, gradient]) + self.assertAllCloseAccordingToType(np_loss, tf_loss, half_rtol=1e-2) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def _testXentND(self, np_labels, np_logits, dim=-1): + np_loss, _ = self._npXent(np_labels, np_logits, dim=dim) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=np_labels, logits=np_logits, dim=dim) + tf_loss = self.evaluate(loss) + self.assertAllCloseAccordingToType(np_loss, tf_loss) + + def _testSingleClass(self, expected_gradient=[[2.0], [1.0], [0.0], [0.0]]): + for dtype in np.float16, np.float32, dtypes.bfloat16.as_numpy_dtype: + loss, gradient = self._opFwdBwd( + labels=np.array([[-1.], [0.], [1.], [1.]]).astype(dtype), + logits=np.array([[1.], [-1.], [0.], [1.]]).astype(dtype)) + self.assertAllClose([0.0, 0.0, 0.0, 0.0], loss) + self.assertAllClose(expected_gradient, gradient) + + def testSingleClass(self): + """This method is structured to be easily overridden by a child class.""" + self._testSingleClass() + + def testNpXent(self): + # We create 2 batches of logits for testing. + # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3. + # batch 1 has a bit of difference: 1, 2, 3, 4, with soft targets (1, 2). + logits = [[1., 1., 1., 1.], [1., 2., 3., 4.]] + labels = [[0., 0., 0., 1.], [0., .5, .5, 0.]] + + # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25 + # With a hard target 3, the gradient is [0.25, 0.25, 0.25, -0.75] + # The loss for this batch is -log(0.25) = 1.386 + # + # For batch 1, we have: + # exp(0) = 1 + # exp(1) = 2.718 + # exp(2) = 7.389 + # exp(3) = 20.085 + # SUM = 31.192 + # So we have as probabilities: + # exp(0) / SUM = 0.032 + # exp(1) / SUM = 0.087 + # exp(2) / SUM = 0.237 + # exp(3) / SUM = 0.644 + # With a soft target (1, 2), the gradient is + # [0.032, 0.087 - 0.5 = -0.413, 0.237 - 0.5 = -0.263, 0.644] + # The loss for this batch is [0.5 * -log(0.087), 0.5 * -log(0.237)] + # = [1.3862, 1.9401] + np_loss, np_gradient = self._npXent(np.array(labels), np.array(logits)) + self.assertAllClose( + np.array([[0.25, 0.25, 0.25, -0.75], [0.0321, -0.4129, -0.2632, + 0.6439]]), + np_gradient, + rtol=1.e-3, + atol=1.e-3) + self.assertAllClose( + np.array([1.3862, 1.9401]), np_loss, rtol=1.e-3, atol=1.e-3) + + # TODO(b/123860949): The values are constant folded for XLA, so placeholders + # are needed. + @test_util.run_deprecated_v1 + def _testLabelsBroadcast(self, uniform_labels_gradient): + labels = np.array([[0., 0., 0., 1.]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D(labels, logits, with_placeholders=True) + labels = np.array([[1.]]).astype(np.float16) + logits = np.array([[1.], [2.]]).astype(np.float16) + self._testXent2D(labels, logits, with_placeholders=True) + labels = np.array([[0.], [2.], [0.25]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D( + labels, + logits, + with_placeholders=True, + expected_gradient=uniform_labels_gradient) + + def testLabelsBroadcast(self): + """This method is structured to be easily overridden by a child class.""" + self._testLabelsBroadcast(uniform_labels_gradient=[[ + 0.25, 0.25, 0.25, 0.25 + ], [-1.968, -1.913, -1.763, -1.355], [-0.218, -0.163, -0.013, 0.394]]) + + @test_util.run_deprecated_v1 + def testShapeMismatch(self): + with self.cached_session(): + with self.assertRaises(ValueError): + self._opFwdBwd( + labels=[[0., 1., 0.], [1., 0., 0.]], logits=[[0., 1.], [2., 3.]]) + + def testHalf(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float16) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16) + self._testXent2D(labels, logits) + + def testBfloat16(self): + labels = np.array([[0., 0., 0., 1.], + [0., .5, .5, 0.]]).astype(dtypes.bfloat16.as_numpy_dtype) + logits = np.array([[1., 1., 1., 1.], + [1., 2., 3., 4.]]).astype(dtypes.bfloat16.as_numpy_dtype) + self._testXent2D(labels, logits) + + def testFloat(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32) + self._testXent2D(labels, logits) + + def testDouble(self): + labels = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float64) + logits = np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64) + self._testXent2D(labels, logits) + + @test_util.run_deprecated_v1 + def testGradient(self): + with self.cached_session() as sess: + labels = constant_op.constant( + [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5], + shape=[3, 4], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, name="xent") + err = gradient_checker.compute_gradient_error(logits, [3, 4], x, [3]) + + # Check that no extra computation gets performed. When only the first + # derivative is requested, the second derivative must not be computed. + # So when there is no second derivative, there is no `BatchMatMul` op + # in the graph. + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertNotIn("BatchMatMul", op_names) + self.assertNotIn("BatchMatMulV2", op_names) + + self.assertLess(err, 5e-8) + + @test_util.run_deprecated_v1 + def testGradientLabelWithV2(self): + with self.cached_session(): + labels = constant_op.constant( + [0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5], + shape=[3, 4], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent") + err = gradient_checker.compute_gradient_error(labels, [3, 4], x, [3]) + + self.assertLess(err, 5e-8) + + @test_util.run_deprecated_v1 + def testSecondGradient(self): + with self.cached_session() as sess: + labels = constant_op.constant([ + 0.0, 0.0, 1.0 / 3, 0.0, 1.0 / 3, 0.0, 0.0, 0.0, 0.0, 0.5 / 3, 0.0, + 0.5 / 3 + ], + shape=[12], + dtype=dtypes.float64, + name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[12], + dtype=dtypes.float64, + name="logits") + x = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits, name="xent") + loss = math_ops.reduce_sum(x) + + gradients = gradients_impl.gradients(loss, [logits])[0] + + err = gradient_checker.compute_gradient_error(logits, [12], gradients, + [12]) + + if not config.is_op_determinism_enabled(): + # Check how second derivative is calculated. + # (it is equivalent to a `BatchMatMul` op being in the graph because of + # the implementation in SoftmaxCrossEntropyWithLogitsGrad) + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertIn("BatchMatMulV2", op_names) + + self.assertLess(err, 5e-8) + + def test3D(self): + labels = np.array([[[0., 0., 0., 1.], [0., 1., 0., 0.]], + [[0., 0.5, 0.5, 0.], [0.5, 0.5, 0., 0.]], + [[0., 1., 0., 0.], [0., 0., 1., 0.]]]).astype(np.float32) + logits = np.array([[[1., 1., 1., 1.], [1., 2., 3., 4.]], + [[2., 3., 4., 5.], [6., 7., 8., 9.]], + [[5., 4., 3., 2.], [1., 2., 3., 4.]]]).astype(np.float32) + self._testXentND(labels, logits, dim=0) + self._testXentND(labels, logits, dim=1) + self._testXentND(labels, logits, dim=-1) + + def testZeroDimension(self): + labels = np.zeros([0, 2, 4]).astype(np.float32) + logits = np.zeros([0, 2, 4]).astype(np.float32) + np_loss, _ = self._npXent(labels=labels, logits=logits) + loss = nn_ops.softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + tf_loss = self.evaluate(loss) + self.assertAllEqual(np_loss, tf_loss) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5a3db560832005ec67ff9942afa6d01ff1d95e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/random/util.py @@ -0,0 +1,164 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for testing random variables.""" + +import math + +import numpy as np + +from tensorflow.python.ops.distributions import special_math + + +def test_moment_matching( + samples, + number_moments, + dist, + stride=0): + """Return z-test scores for sample moments to match analytic moments. + + Given `samples`, check that the first sample `number_moments` match + the given `dist` moments by doing a z-test. + + Args: + samples: Samples from target distribution. + number_moments: Python `int` describing how many sample moments to check. + dist: SciPy distribution object that provides analytic moments. + stride: Distance between samples to check for statistical properties. + A stride of 0 means to use all samples, while other strides test for + spatial correlation. + Returns: + Array of z_test scores. + """ + + sample_moments = [] + expected_moments = [] + variance_sample_moments = [] + for i in range(1, number_moments + 1): + if len(samples.shape) == 2: + strided_range = samples.flat[::(i - 1) * stride + 1] + else: + strided_range = samples[::(i - 1) * stride + 1, ...] + sample_moments.append(np.mean(strided_range**i, axis=0)) + expected_moments.append(dist.moment(i)) + variance_sample_moments.append( + (dist.moment(2 * i) - dist.moment(i) ** 2) / len(strided_range)) + + z_test_scores = [] + for i in range(1, number_moments + 1): + # Assume every operation has a small numerical error. + # It takes i multiplications to calculate one i-th moment. + total_variance = ( + variance_sample_moments[i - 1] + + i * np.finfo(samples.dtype).eps) + tiny = np.finfo(samples.dtype).tiny + assert np.all(total_variance > 0) + total_variance = np.where(total_variance < tiny, tiny, total_variance) + # z_test is approximately a unit normal distribution. + z_test_scores.append(abs( + (sample_moments[i - 1] - expected_moments[i - 1]) / np.sqrt( + total_variance))) + return z_test_scores + + +def chi_squared(x, bins): + """Pearson's Chi-squared test.""" + x = np.ravel(x) + n = len(x) + histogram, _ = np.histogram(x, bins=bins, range=(0, 1)) + expected = n / float(bins) + return np.sum(np.square(histogram - expected) / expected) + + +def normal_cdf(x): + """Cumulative distribution function for a standard normal distribution.""" + return 0.5 + 0.5 * np.vectorize(math.erf)(x / math.sqrt(2)) + + +def anderson_darling(x): + """Anderson-Darling test for a standard normal distribution.""" + x = np.sort(np.ravel(x)) + n = len(x) + i = np.linspace(1, n, n) + z = np.sum((2 * i - 1) * np.log(normal_cdf(x)) + + (2 * (n - i) + 1) * np.log(1 - normal_cdf(x))) + return -n - z / n + + +def test_truncated_normal(assert_equal, + assert_all_close, + n, + y, + means=None, + stddevs=None, + minvals=None, + maxvals=None, + mean_atol=5e-4, + median_atol=8e-4, + variance_rtol=1e-3): + """Tests truncated normal distribution's statistics.""" + def _normal_cdf(x): + return .5 * math.erfc(-x / math.sqrt(2)) + + def normal_pdf(x): + return math.exp(-(x**2) / 2.) / math.sqrt(2 * math.pi) + + def probit(x): + return special_math.ndtri(x) + + a = -2. + b = 2. + mu = 0. + sigma = 1. + + if minvals is not None: + a = minvals + + if maxvals is not None: + b = maxvals + + if means is not None: + mu = means + + if stddevs is not None: + sigma = stddevs + + alpha = (a - mu) / sigma + beta = (b - mu) / sigma + z = _normal_cdf(beta) - _normal_cdf(alpha) + + assert_equal((y >= a).sum(), n) + assert_equal((y <= b).sum(), n) + + # For more information on these calculations, see: + # Burkardt, John. "The Truncated Normal Distribution". + # Department of Scientific Computing website. Florida State University. + expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma + y = y.astype(float) + actual_mean = np.mean(y) + assert_all_close(actual_mean, expected_mean, atol=mean_atol) + + expected_median = mu + probit( + (_normal_cdf(alpha) + _normal_cdf(beta)) / 2.) * sigma + actual_median = np.median(y) + assert_all_close(actual_median, expected_median, atol=median_atol) + + expected_variance = sigma**2 * (1 + ( + (alpha * normal_pdf(alpha) - beta * normal_pdf(beta)) / z) - ( + (normal_pdf(alpha) - normal_pdf(beta)) / z)**2) + actual_variance = np.var(y) + assert_all_close( + actual_variance, + expected_variance, + rtol=variance_rtol) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0d82ca8e6341227ff7df7cd223163db06985e798 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/signal/test_util.py @@ -0,0 +1,96 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Test utilities for tf.signal.""" + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.lite.python import interpreter +from tensorflow.lite.python import lite +from tensorflow.python.eager import def_function +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.training import saver + + +def grappler_optimize(graph, fetches=None, config_proto=None): + """Tries to optimize the provided graph using grappler. + + Args: + graph: A `tf.Graph` instance containing the graph to optimize. + fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away). + Grappler uses the 'train_op' collection to look for fetches, so if not + provided this collection should be non-empty. + config_proto: An optional `tf.compat.v1.ConfigProto` to use when rewriting + the graph. + + Returns: + A `tf.compat.v1.GraphDef` containing the rewritten graph. + """ + if config_proto is None: + config_proto = config_pb2.ConfigProto() + config_proto.graph_options.rewrite_options.min_graph_nodes = -1 + if fetches is not None: + for fetch in fetches: + graph.add_to_collection('train_op', fetch) + metagraph = saver.export_meta_graph(graph_def=graph.as_graph_def()) + return tf_optimizer.OptimizeGraph(config_proto, metagraph) + + +def tflite_convert(fn, input_templates): + """Converts the provided fn to tf.lite model. + + Args: + fn: A callable that expects a list of inputs like input_templates that + returns a tensor or structure of tensors. + input_templates: A list of Tensors, ndarrays or TensorSpecs describing the + inputs that fn expects. The actual values of the Tensors or ndarrays are + unused. + + Returns: + The serialized tf.lite model. + """ + fn = def_function.function(fn) + concrete_func = fn.get_concrete_function(*input_templates) + converter = lite.TFLiteConverterV2([concrete_func]) + return converter.convert() + + +def evaluate_tflite_model(tflite_model, input_ndarrays): + """Evaluates the provided tf.lite model with the given input ndarrays. + + Args: + tflite_model: bytes. The serialized tf.lite model. + input_ndarrays: A list of NumPy arrays to feed as input to the model. + + Returns: + A list of ndarrays produced by the model. + + Raises: + ValueError: If the number of input arrays does not match the number of + inputs the model expects. + """ + the_interpreter = interpreter.Interpreter(model_content=tflite_model) + the_interpreter.allocate_tensors() + + input_details = the_interpreter.get_input_details() + output_details = the_interpreter.get_output_details() + + if len(input_details) != len(input_ndarrays): + raise ValueError('Wrong number of inputs: provided=%s, ' + 'input_details=%s output_details=%s' % ( + input_ndarrays, input_details, output_details)) + for input_tensor, data in zip(input_details, input_ndarrays): + the_interpreter.set_tensor(input_tensor['index'], data) + the_interpreter.invoke() + return [the_interpreter.get_tensor(details['index']) + for details in output_details] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a30d82591da5c9eb2a6d64e62e2b5c7f9a979276 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py @@ -0,0 +1,318 @@ +# Copyright 2015-2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for SparseSoftmaxCrossEntropyWithLogits op.""" + +import numpy as np + +from tensorflow.python.eager import backprop as backprop_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import ops as ops_lib +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +class SparseXentOpTestBase(test.TestCase): + + def _opFwdBwd(self, labels, logits): + """Runs the op-under-test both forwards and backwards""" + logits = ops_lib.convert_to_tensor(logits) # needed for the gradient tape + with backprop_lib.GradientTape() as tape: + tape.watch(logits) + loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits) + return loss, tape.gradient(loss, logits) + + def _npXent(self, labels, logits): + logits = np.reshape(logits, [-1, logits.shape[-1]]) + labels = np.reshape(labels, [-1]) + batch_dim = 0 + class_dim = 1 + batch_size = logits.shape[batch_dim] + e = np.exp(logits - + np.reshape(np.amax(logits, axis=class_dim), [batch_size, 1])) + probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1]) + labels_mat = np.zeros_like(probs).astype(probs.dtype) + labels_mat[np.arange(batch_size), labels] = 1.0 + gradient = (probs - labels_mat) + loss = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1) + return loss, gradient + + def _testXent(self, np_labels, np_logits): + np_loss, np_gradient = self._npXent(labels=np_labels, logits=np_logits) + tf_loss, tf_gradient = self._opFwdBwd(labels=np_labels, logits=np_logits) + self.assertAllCloseAccordingToType(np_loss, tf_loss) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def testSingleClass(self): + for label_dtype in np.int32, np.int64: + tf_loss, tf_gradient = self._opFwdBwd( + labels=np.array([0, 0, 0]).astype(label_dtype), + logits=np.array([[1.], [-1.], [0.]]).astype(np.float32)) + self.assertAllClose([0.0, 0.0, 0.0], tf_loss) + self.assertAllClose([[0.0], [0.0], [0.0]], tf_gradient) + + @test_util.run_gpu_only() + def _testInvalidLabelGPU(self, invalid_label_gradient=np.nan): + labels = [4, 3, 0, -1] + logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]] + loss, gradient = self._opFwdBwd(labels=labels, logits=logits) + self.assertAllClose([np.nan, 1.3862, 3.4420, np.nan], + loss, + rtol=1e-3, + atol=1e-3) + self.assertAllClose( + [[invalid_label_gradient] * 4, [0.25, 0.25, 0.25, -0.75], + [-0.968, 0.087, 0.237, 0.6439], [invalid_label_gradient] * 4], + gradient, + rtol=1e-3, + atol=1e-3) + + def testInvalidLabelGPU(self): + """This method is structured to be easily overridden by a child class.""" + self._testInvalidLabelGPU() + + @test_util.run_in_graph_and_eager_modes(use_gpu=False) + @test_util.disable_xla("XLA cannot assert inside of a kernel.") + def _testInvalidLabelCPU(self, expected_regex="Received a label value of"): + labels = [4, 3, 0, -1] + logits = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.], + [1., 2., 3., 4.]] + with self.assertRaisesRegex( + (errors_impl.InvalidArgumentError, errors_impl.UnknownError), + expected_regex): + self.evaluate( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits)) + + def testInvalidLabelCPU(self): + """This method is structured to be easily overridden by a child class.""" + self._testInvalidLabelCPU() + + def testNpXent(self): + # We create 2 batches of logits for testing. + # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3. + # batch 1 has a bit of difference: 1, 2, 3, 4, with target 0. + labels = [3, 0] + logits = [[1., 1., 1., 1.], [1., 2., 3., 4.]] + + # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25 + # With a hard target 3, the gradient is [0.25, 0.25, 0.25, -0.75] + # The loss for this batch is -log(0.25) = 1.386 + # + # For batch 1, we have: + # exp(0) = 1 + # exp(1) = 2.718 + # exp(2) = 7.389 + # exp(3) = 20.085 + # SUM = 31.192 + # So we have as probabilities: + # exp(0) / SUM = 0.032 + # exp(1) / SUM = 0.087 + # exp(2) / SUM = 0.237 + # exp(3) / SUM = 0.644 + # With a hard 1, the gradient is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644] + # The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)] + # = [1.3862, 3.4420] + np_loss, np_gradient = self._npXent( + labels=np.array(labels), logits=np.array(logits)) + self.assertAllClose( + np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]), + np_gradient, + rtol=1.e-3, + atol=1.e-3) + self.assertAllClose( + np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3) + + def testShapeMismatch(self): + with self.assertRaisesRegex( + ValueError, "`labels.shape.rank` must equal `logits.shape.rank - 1`"): + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]]) + + def testScalar(self): + with self.assertRaisesRegex(ValueError, "`logits` cannot be a scalar"): + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=constant_op.constant(0), logits=constant_op.constant(1.0)) + + def _testLabelsPlaceholderScalar(self, expected_error_message): + with ops_lib.Graph().as_default(), self.session(): + labels = array_ops.placeholder(np.int32) + y = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=[[7.]]) + with self.assertRaisesOpError(expected_error_message): + y.eval(feed_dict={labels: 0}) + + def testLabelsPlaceholderScalar(self): + """This method is structured to be easily overridden by a child class.""" + self._testLabelsPlaceholderScalar( + expected_error_message="labels must be 1-D") + + def testVector(self): + loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=constant_op.constant(0), logits=constant_op.constant([1.0])) + self.assertAllClose(0.0, loss) + + def testFloat(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float32)) + + def testDouble(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([0, 3]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float64)) + + def testHalf(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], [1., 2., 3., + 4.]]).astype(np.float16)) + + def testBfloat16(self): + for label_dtype in np.int32, np.int64: + self._testXent( + np_labels=np.array([3, 0]).astype(label_dtype), + np_logits=np.array([[1., 1., 1., 1.], + [1., 2., 3., + 4.]]).astype(dtypes.bfloat16.as_numpy_dtype)) + + def testEmpty(self): + self._testXent( + np_labels=np.zeros((0,), dtype=np.int32), np_logits=np.zeros((0, 3))) + + @test_util.run_in_graph_and_eager_modes() + def testGradient(self): + with self.session() as sess: + labels = constant_op.constant([3, 0, 1], name="labels") + logits = constant_op.constant( + [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + + def xent(logits): + # gradient_checker_v2.computee_gradient doesn't take int32/int64. + # labels must be of type int32/int64, so passing them separately here. + return nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent") + + analytical, numerical = gradient_checker_v2.compute_gradient( + xent, [logits]) + + if not context.executing_eagerly(): + # Check that no extra computation performed. When only first derivative + # is requested, second derivative must not be computed. So when there is + # no second derivative, there is no `BatchMatMul` op in the graph. + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertNotIn("BatchMatMul", op_names) + self.assertNotIn("BatchMatMulV2", op_names) + + tol = 5e-8 + self.assertAllClose(analytical, numerical, atol=tol, rtol=tol) + + @test_util.run_in_graph_and_eager_modes() + def testSecondGradient(self): + with self.session() as sess: + labels = constant_op.constant([3, 0, 1], name="labels") + logits = constant_op.constant( + [0.3, 0.4, 0.1, 1.2, 0.1, 1.9, 0.1, 0.7, 0.8, 0.2, 1.3, 1.3], + shape=[3, 4], + dtype=dtypes.float64, + name="logits") + + def xent_grad(logits): + with backprop_lib.GradientTape() as tape: + tape.watch(logits) + return tape.gradient( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, name="xent"), [logits])[0] + + analytical, numerical = gradient_checker_v2.compute_gradient( + xent_grad, [logits]) + + if (not context.executing_eagerly() and + not config.is_op_determinism_enabled()): + # Check that second derivative is calculated. + # (it is equivalent to being `BatchMatMul` op in the graph because of + # implementation of xentropy grad) + op_names = [ + op.op_def.name for op in sess.graph.get_operations() if op.op_def + ] + self.assertIn("BatchMatMulV2", op_names) + + tol = 5e-8 + self.assertAllClose(analytical, numerical, atol=tol, rtol=tol) + + @test_util.run_in_graph_and_eager_modes() + def _testHighDim(self, labels, logits): + np_loss, np_gradient = self._npXent( + labels=np.array(labels), logits=np.array(logits)) + # manually reshape loss + np_loss = np.reshape(np_loss, np.array(labels).shape) + tf_loss = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits) + with backprop_lib.GradientTape() as tape: + logits = constant_op.constant(logits) + tape.watch(logits) + tf_gradient = tape.gradient( + nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits), [logits])[0] + tf_gradient = array_ops.reshape(tf_gradient, np_gradient.shape) + + self.assertAllCloseAccordingToType(np_loss, tf_loss) + self.assertAllCloseAccordingToType(np_gradient, tf_gradient) + + def testHighDim(self): + labels = [[3], [0]] + logits = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]] + self._testHighDim(labels, logits) + + def testHighDim2(self): + labels = [[3, 2], [0, 3]] + logits = [[[1., 1., 1., 1.], [2., 2., 2., 2.]], + [[1., 2., 3., 4.], [5., 6., 7., 8.]]] + self._testHighDim(labels, logits) + + def _testScalarHandling(self, expected_regex): + with ops_lib.Graph().as_default(), self.session(use_gpu=False) as sess: + with self.assertRaisesRegex(errors_impl.InvalidArgumentError, + expected_regex): + labels = array_ops.placeholder(dtypes.int32, shape=[None, 1]) + logits = array_ops.placeholder(dtypes.float32, shape=[None, 3]) + ce = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( + labels=array_ops.squeeze(labels), logits=logits) + labels_v2 = np.zeros((1, 1), dtype=np.int32) + logits_v2 = np.random.randn(1, 3) + sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2}) + + def testScalarHandling(self): + """This method is structured to be easily overridden by a child class.""" + self._testScalarHandling(expected_regex=".*labels must be 1-D.*") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..96078dda50d2f20fac1604aeefe39e4a8af037ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/base.py @@ -0,0 +1,22 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Contains the base Layer class, from which all layers inherit.""" +from tensorflow.python.keras.legacy_tf_layers import base + +InputSpec = base.InputSpec + +keras_style_scope = base.keras_style_scope +set_keras_style = base.set_keras_style +Layer = base.Layer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/convolutional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/convolutional.py new file mode 100644 index 0000000000000000000000000000000000000000..19d82d7d577d3c20873a1c8e3527cde3e2d01df2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/convolutional.py @@ -0,0 +1,48 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Contains the convolutional layer classes and their functional aliases. +""" +from tensorflow.python.keras.legacy_tf_layers import convolutional + +Conv1D = convolutional.Conv1D +conv1d = convolutional.conv1d +Conv2D = convolutional.Conv2D +conv2d = convolutional.conv2d +Conv3D = convolutional.Conv3D +conv3d = convolutional.conv3d +SeparableConv1D = convolutional.SeparableConv1D +SeparableConv2D = convolutional.SeparableConv2D +separable_conv1d = convolutional.separable_conv1d +separable_conv2d = convolutional.separable_conv2d +Conv2DTranspose = convolutional.Conv2DTranspose +conv2d_transpose = convolutional.conv2d_transpose +Conv3DTranspose = convolutional.Conv3DTranspose +conv3d_transpose = convolutional.conv3d_transpose + +# Aliases + +Convolution1D = Conv1D +Convolution2D = Conv2D +Convolution3D = Conv3D +SeparableConvolution2D = SeparableConv2D +Convolution2DTranspose = Deconvolution2D = Deconv2D = Conv2DTranspose +Convolution3DTranspose = Deconvolution3D = Deconv3D = Conv3DTranspose +convolution1d = conv1d +convolution2d = conv2d +convolution3d = conv3d +separable_convolution2d = separable_conv2d +convolution2d_transpose = deconvolution2d = deconv2d = conv2d_transpose +convolution3d_transpose = deconvolution3d = deconv3d = conv3d_transpose diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/core.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/core.py new file mode 100644 index 0000000000000000000000000000000000000000..360ac2774389f5b948db013eb0aaef573568ff15 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/core.py @@ -0,0 +1,33 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Contains the core layers: Dense, Dropout. + +Also contains their functional aliases. +""" +from tensorflow.python.keras.legacy_tf_layers import core + + +Dense = core.Dense +dense = core.dense +Dropout = core.Dropout +dropout = core.dropout +Flatten = core.Flatten +flatten = core.flatten + +# Aliases + +FullyConnected = Dense +fully_connected = dense diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/layers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..e75a55cd93612bc525fc724722c2c2b21df66d9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/layers.py @@ -0,0 +1,71 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=line-too-long +"""This library provides a set of high-level neural networks layers.""" + +# pylint: disable=g-bad-import-order,unused-import + +# Base objects. +from tensorflow.python.layers.base import Layer + +# Core layers. +from tensorflow.python.layers.core import Dense +from tensorflow.python.layers.core import Dropout +from tensorflow.python.layers.core import Flatten + +from tensorflow.python.layers.core import dense +from tensorflow.python.layers.core import dropout +from tensorflow.python.layers.core import flatten + +# Convolutional layers. +from tensorflow.python.layers.convolutional import SeparableConv1D +from tensorflow.python.layers.convolutional import SeparableConv2D +from tensorflow.python.layers.convolutional import SeparableConvolution2D +from tensorflow.python.layers.convolutional import Conv2DTranspose +from tensorflow.python.layers.convolutional import Convolution2DTranspose +from tensorflow.python.layers.convolutional import Conv3DTranspose +from tensorflow.python.layers.convolutional import Convolution3DTranspose +from tensorflow.python.layers.convolutional import Conv1D +from tensorflow.python.layers.convolutional import Convolution1D +from tensorflow.python.layers.convolutional import Conv2D +from tensorflow.python.layers.convolutional import Convolution2D +from tensorflow.python.layers.convolutional import Conv3D +from tensorflow.python.layers.convolutional import Convolution3D + +from tensorflow.python.layers.convolutional import separable_conv1d +from tensorflow.python.layers.convolutional import separable_conv2d +from tensorflow.python.layers.convolutional import conv2d_transpose +from tensorflow.python.layers.convolutional import conv3d_transpose +from tensorflow.python.layers.convolutional import conv1d +from tensorflow.python.layers.convolutional import conv2d +from tensorflow.python.layers.convolutional import conv3d + +# Pooling layers. +from tensorflow.python.layers.pooling import AveragePooling1D +from tensorflow.python.layers.pooling import MaxPooling1D +from tensorflow.python.layers.pooling import AveragePooling2D +from tensorflow.python.layers.pooling import MaxPooling2D +from tensorflow.python.layers.pooling import AveragePooling3D +from tensorflow.python.layers.pooling import MaxPooling3D + +from tensorflow.python.layers.pooling import average_pooling1d +from tensorflow.python.layers.pooling import max_pooling1d +from tensorflow.python.layers.pooling import average_pooling2d +from tensorflow.python.layers.pooling import max_pooling2d +from tensorflow.python.layers.pooling import average_pooling3d +from tensorflow.python.layers.pooling import max_pooling3d + +# pylint: enable=g-bad-import-order,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/normalization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f26c76b2dbb9f50ed38eee809f2c2cb4e74b1b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/normalization.py @@ -0,0 +1,34 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Contains the normalization layer classes and their functional aliases. +""" + +from tensorflow.python.util import lazy_loader + +normalization = lazy_loader.LazyLoader( + 'normalization', globals(), + 'tf_keras.legacy_tf_layers.normalization') + + +# pylint: disable=invalid-name +# lazy load all the attributes until they are accessed for the first time +def __getattr__(name): + if name in ['BatchNormalization', 'BatchNorm']: + return normalization.BatchNormalization + elif name in ['batch_normalization', 'batch_norm']: + return normalization.batch_normalization + else: + raise AttributeError(f'module {__name__} doesn\'t have attribute {name}') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/pooling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/pooling.py new file mode 100644 index 0000000000000000000000000000000000000000..216f657d633c9296181a50dbaafe8a5ce81e9166 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/pooling.py @@ -0,0 +1,39 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Contains the pooling layer classes and their functional aliases. +""" +from tensorflow.python.keras.legacy_tf_layers import pooling + + +AveragePooling1D = pooling.AveragePooling1D +average_pooling1d = pooling.average_pooling1d +MaxPooling1D = pooling.MaxPooling1D +max_pooling1d = pooling.max_pooling1d +AveragePooling2D = pooling.AveragePooling2D +average_pooling2d = pooling.average_pooling2d +MaxPooling2D = pooling.MaxPooling2D +max_pooling2d = pooling.max_pooling2d +AveragePooling3D = pooling.AveragePooling3D +average_pooling3d = pooling.average_pooling3d +MaxPooling3D = pooling.MaxPooling3D +max_pooling3d = pooling.max_pooling3d + +# Aliases + +AvgPool2D = AveragePooling2D +MaxPool2D = MaxPooling2D +max_pool2d = max_pooling2d +avg_pool2d = average_pooling2d diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec664156861b282363ac33a1d0c9a8ffa7a15dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/layers/utils.py @@ -0,0 +1,225 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Contains layer utilities for input validation and format conversion.""" +from tensorflow.python.framework import smart_cond as smart_module +from tensorflow.python.ops import cond +from tensorflow.python.ops import variables + + +def convert_data_format(data_format, ndim): + if data_format == 'channels_last': + if ndim == 3: + return 'NWC' + elif ndim == 4: + return 'NHWC' + elif ndim == 5: + return 'NDHWC' + else: + raise ValueError(f'Input rank: {ndim} not supported. We only support ' + 'input rank 3, 4 or 5.') + elif data_format == 'channels_first': + if ndim == 3: + return 'NCW' + elif ndim == 4: + return 'NCHW' + elif ndim == 5: + return 'NCDHW' + else: + raise ValueError(f'Input rank: {ndim} not supported. We only support ' + 'input rank 3, 4 or 5.') + else: + raise ValueError(f'Invalid data_format: {data_format}. We only support ' + '"channels_first" or "channels_last"') + + +def normalize_tuple(value, n, name): + """Transforms a single integer or iterable of integers into an integer tuple. + + Args: + value: The value to validate and convert. Could an int, or any iterable + of ints. + n: The size of the tuple to be returned. + name: The name of the argument being validated, e.g. "strides" or + "kernel_size". This is only used to format error messages. + + Returns: + A tuple of n integers. + + Raises: + ValueError: If something else than an int/long or iterable thereof was + passed. + """ + if isinstance(value, int): + return (value,) * n + else: + try: + value_tuple = tuple(value) + except TypeError: + raise ValueError(f'Argument `{name}` must be a tuple of {str(n)} ' + f'integers. Received: {str(value)}') + if len(value_tuple) != n: + raise ValueError(f'Argument `{name}` must be a tuple of {str(n)} ' + f'integers. Received: {str(value)}') + for single_value in value_tuple: + try: + int(single_value) + except (ValueError, TypeError): + raise ValueError(f'Argument `{name}` must be a tuple of {str(n)} ' + f'integers. Received: {str(value)} including element ' + f'{str(single_value)} of type ' + f'{str(type(single_value))}') + return value_tuple + + +def normalize_data_format(value): + data_format = value.lower() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('The `data_format` argument must be one of ' + '"channels_first", "channels_last". Received: ' + f'{str(value)}.') + return data_format + + +def normalize_padding(value): + padding = value.lower() + if padding not in {'valid', 'same'}: + raise ValueError('The `padding` argument must be one of "valid", "same". ' + f'Received: {str(padding)}.') + return padding + + +def conv_output_length(input_length, filter_size, padding, stride, dilation=1): + """Determines output length of a convolution given input length. + + Args: + input_length: integer. + filter_size: integer. + padding: one of "same", "valid", "full". + stride: integer. + dilation: dilation rate, integer. + + Returns: + The output length (integer). + """ + if input_length is None: + return None + assert padding in {'same', 'valid', 'full'} + dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) + if padding == 'same': + output_length = input_length + elif padding == 'valid': + output_length = input_length - dilated_filter_size + 1 + elif padding == 'full': + output_length = input_length + dilated_filter_size - 1 + return (output_length + stride - 1) // stride + + +def conv_input_length(output_length, filter_size, padding, stride): + """Determines input length of a convolution given output length. + + Args: + output_length: integer. + filter_size: integer. + padding: one of "same", "valid", "full". + stride: integer. + + Returns: + The input length (integer). + """ + if output_length is None: + return None + assert padding in {'same', 'valid', 'full'} + if padding == 'same': + pad = filter_size // 2 + elif padding == 'valid': + pad = 0 + elif padding == 'full': + pad = filter_size - 1 + return (output_length - 1) * stride - 2 * pad + filter_size + + +def deconv_output_length(input_length, filter_size, padding, stride): + """Determines output length of a transposed convolution given input length. + + Args: + input_length: integer. + filter_size: integer. + padding: one of "same", "valid", "full". + stride: integer. + + Returns: + The output length (integer). + """ + if input_length is None: + return None + input_length *= stride + if padding == 'valid': + input_length += max(filter_size - stride, 0) + elif padding == 'full': + input_length -= (stride + filter_size - 2) + return input_length + + +def smart_cond(pred, true_fn=None, false_fn=None, name=None): + """Return either `true_fn()` if predicate `pred` is true else `false_fn()`. + + If `pred` is a bool or has a constant value, we return either `true_fn()` + or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both. + + Args: + pred: A scalar determining whether to return the result of `true_fn` or + `false_fn`. + true_fn: The callable to be performed if pred is true. + false_fn: The callable to be performed if pred is false. + name: Optional name prefix when using `tf.cond`. + + Returns: + Tensors returned by the call to either `true_fn` or `false_fn`. + + Raises: + TypeError: If `true_fn` or `false_fn` is not callable. + """ + if isinstance(pred, variables.Variable): + return cond.cond( + pred, true_fn=true_fn, false_fn=false_fn, name=name) + return smart_module.smart_cond( + pred, true_fn=true_fn, false_fn=false_fn, name=name) + + +def constant_value(pred): + """Return the bool value for `pred`, or None if `pred` had a dynamic value. + + Args: + pred: A scalar, either a Python bool or a TensorFlow boolean variable + or tensor, or the Python integer 1 or 0. + + Returns: + True or False if `pred` has a constant boolean value, None otherwise. + + Raises: + TypeError: If `pred` is not a Variable, Tensor or bool, or Python + integer 1 or 0. + """ + # Allow integer booleans. + if isinstance(pred, int): + if pred == 1: + pred = True + elif pred == 0: + pred = False + + if isinstance(pred, variables.Variable): + return None + return smart_module.smart_constant_value(pred) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/core/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/core/_pywrap_py_func.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/core/_pywrap_py_func.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3401f23bfa3f191b2b1c1863afa3fa35fd47ed4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/core/_pywrap_py_func.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def initialize_py_trampoline(arg0: object) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_file_io.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_file_io.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d868905533b50a5b06480f0d5b2c013e308ae906 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_file_io.pyi @@ -0,0 +1,56 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 BufferedInputStream: + def __init__(self, filename: str, buffer_size: int, token: TransactionToken = ...) -> None: ... + def read(self, arg0: int) -> bytes: ... + def readline(self) -> bytes: ... + def seek(self, arg0: int) -> None: ... + def tell(self) -> int: ... + +class FileStatistics: + def __init__(self, *args, **kwargs) -> None: ... + @property + def is_directory(self) -> bool: ... + @property + def length(self) -> int: ... + @property + def mtime_nsec(self) -> int: ... + +class TransactionToken: + def __init__(self, *args, **kwargs) -> None: ... + +class WritableFile: + def __init__(self, filename: str, mode: str, token: TransactionToken = ...) -> None: ... + def append(self, arg0: str) -> None: ... + def close(self) -> None: ... + def flush(self) -> None: ... + def tell(self) -> int: ... + +def CopyFile(src: str, target: str, overwrite: bool, token: TransactionToken = ...) -> None: ... +def CreateDir(dirname: str, token: TransactionToken = ...) -> None: ... +def DeleteFile(filename: str, token: TransactionToken = ...) -> None: ... +def DeleteRecursively(dirname: str, token: TransactionToken = ...) -> None: ... +def FileExists(filename: str, token: TransactionToken = ...) -> None: ... +def GetChildren(dirname: str, token: TransactionToken = ...) -> list[str]: ... +def GetMatchingFiles(pattern: str, token: TransactionToken = ...) -> list[str]: ... +def GetRegisteredSchemes() -> list[str]: ... +def HasAtomicMove(arg0: str) -> bool: ... +def IsDirectory(dirname: str, token: TransactionToken = ...) -> bool: ... +def ReadFileToString(filename: str, token: TransactionToken = ...) -> bytes: ... +def RecursivelyCreateDir(dirname: str, token: TransactionToken = ...) -> None: ... +def RenameFile(src: str, target: str, overwrite: bool, token: TransactionToken = ...) -> None: ... +def Stat(filename: str, token: TransactionToken = ...) -> FileStatistics: ... +def WriteStringToFile(filename: str, data: str, token: TransactionToken = ...) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_record_io.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_record_io.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9939b15e7f01ed792f4def1fd85be83466113959 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/_pywrap_record_io.pyi @@ -0,0 +1,54 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import Any + +class RandomRecordReader: + def __init__(self, arg0: str) -> None: ... + def close(self) -> None: ... + def read(self, arg0: int) -> tuple: ... + +class RecordIterator: + def __init__(self, arg0: str, arg1: str) -> None: ... + def close(self) -> None: ... + def reopen(self) -> None: ... + def __iter__(self) -> object: ... + def __next__(self) -> bytes: ... + +class RecordWriter: + def __init__(self, arg0: str, arg1: RecordWriterOptions) -> None: ... + def close(self) -> None: ... + def flush(self) -> None: ... + def write(self, record: str) -> None: ... + def __enter__(self) -> object: ... + def __exit__(self, *args) -> None: ... + +class RecordWriterOptions: + def __init__(self, arg0: str) -> None: ... + @property + def compression_type(self) -> Any: ... + @property + def zlib_options(self) -> ZlibCompressionOptions: ... + +class ZlibCompressionOptions: + compression_level: int + compression_method: int + compression_strategy: int + flush_mode: int + input_buffer_size: int + mem_level: int + output_buffer_size: int + window_bits: int + def __init__(self, *args, **kwargs) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/file_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/file_io.py new file mode 100644 index 0000000000000000000000000000000000000000..5a460b2fb1dae50c4e2a686abf038e1e110eeeed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/file_io.py @@ -0,0 +1,1004 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""File IO methods that wrap the C++ FileSystem API.""" +import binascii +import os +from posixpath import join as urljoin +import uuid + +import six + +from tensorflow.python.framework import errors +from tensorflow.python.lib.io import _pywrap_file_io +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +# A good default block size depends on the system in question. +# A somewhat conservative default chosen here. +_DEFAULT_BLOCK_SIZE = 16 * 1024 * 1024 + + +class FileIO(object): + """FileIO class that exposes methods to read / write to / from files. + + The constructor takes the following arguments: + name: [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) + giving the pathname of the file to be opened. + mode: one of `r`, `w`, `a`, `r+`, `w+`, `a+`. Append `b` for bytes mode. + + Can be used as an iterator to iterate over lines in the file. + + The default buffer size used for the BufferedInputStream used for reading + the file line by line is 1024 * 512 bytes. + """ + + def __init__(self, name, mode, encoding="utf-8"): + self.__name = name + self.__mode = mode + self.__encoding = encoding + self._read_buf = None + self._writable_file = None + self._binary_mode = "b" in mode + mode = mode.replace("b", "") + if mode not in ("r", "w", "a", "r+", "w+", "a+"): + raise errors.InvalidArgumentError( + None, None, "mode is not 'r' or 'w' or 'a' or 'r+' or 'w+' or 'a+'") + self._read_check_passed = mode in ("r", "r+", "a+", "w+") + self._write_check_passed = mode in ("a", "w", "r+", "a+", "w+") + + @property + def name(self): + """Returns the file name.""" + return self.__name + + @property + def mode(self): + """Returns the mode in which the file was opened.""" + return self.__mode + + def _preread_check(self): + if not self._read_buf: + if not self._read_check_passed: + raise errors.PermissionDeniedError(None, None, + "File isn't open for reading") + self._read_buf = _pywrap_file_io.BufferedInputStream( + compat.path_to_str(self.__name), 1024 * 512) + + def _prewrite_check(self): + if not self._writable_file: + if not self._write_check_passed: + raise errors.PermissionDeniedError(None, None, + "File isn't open for writing") + self._writable_file = _pywrap_file_io.WritableFile( + compat.path_to_bytes(self.__name), compat.as_bytes(self.__mode)) + + def _prepare_value(self, val): + if self._binary_mode: + return compat.as_bytes(val, encoding=self.__encoding) + else: + return compat.as_str_any(val, encoding=self.__encoding) + + def size(self): + """Returns the size of the file.""" + return stat(self.__name).length + + def write(self, file_content): + """Writes file_content to the file. Appends to the end of the file.""" + self._prewrite_check() + self._writable_file.append( + compat.as_bytes(file_content, encoding=self.__encoding)) + + def read(self, n=-1): + """Returns the contents of a file as a string. + + Starts reading from current position in file. + + Args: + n: Read `n` bytes if `n != -1`. If `n = -1`, reads to end of file. + + Returns: + `n` bytes of the file (or whole file) in bytes mode or `n` bytes of the + string if in string (regular) mode. + """ + self._preread_check() + if n == -1: + length = self.size() - self.tell() + else: + length = n + return self._prepare_value(self._read_buf.read(length)) + + @deprecation.deprecated_args( + None, "position is deprecated in favor of the offset argument.", + "position") + def seek(self, offset=None, whence=0, position=None): + # TODO(jhseu): Delete later. Used to omit `position` from docs. + # pylint: disable=g-doc-args + """Seeks to the offset in the file. + + Args: + offset: The byte count relative to the whence argument. + whence: Valid values for whence are: + 0: start of the file (default) + 1: relative to the current position of the file + 2: relative to the end of file. `offset` is usually negative. + """ + # pylint: enable=g-doc-args + self._preread_check() + # We needed to make offset a keyword argument for backwards-compatibility. + # This check exists so that we can convert back to having offset be a + # positional argument. + # TODO(jhseu): Make `offset` a positional argument after `position` is + # deleted. + if offset is None and position is None: + raise TypeError("seek(): offset argument required") + if offset is not None and position is not None: + raise TypeError("seek(): offset and position may not be set " + "simultaneously.") + + if position is not None: + offset = position + + if whence == 0: + pass + elif whence == 1: + offset += self.tell() + elif whence == 2: + offset += self.size() + else: + raise errors.InvalidArgumentError( + None, None, + "Invalid whence argument: {}. Valid values are 0, 1, or 2.".format( + whence)) + self._read_buf.seek(offset) + + def readline(self): + r"""Reads the next line, keeping \n. At EOF, returns ''.""" + self._preread_check() + return self._prepare_value(self._read_buf.readline()) + + def readlines(self): + """Returns all lines from the file in a list.""" + self._preread_check() + lines = [] + while True: + s = self.readline() + if not s: + break + lines.append(s) + return lines + + def tell(self): + """Returns the current position in the file.""" + if self._read_check_passed: + self._preread_check() + return self._read_buf.tell() + else: + self._prewrite_check() + + return self._writable_file.tell() + + def __enter__(self): + """Make usable with "with" statement.""" + return self + + def __exit__(self, unused_type, unused_value, unused_traceback): + """Make usable with "with" statement.""" + self.close() + + def __iter__(self): + return self + + def __next__(self): + retval = self.readline() + if not retval: + raise StopIteration() + return retval + + def next(self): + return self.__next__() + + def flush(self): + """Flushes the Writable file. + + This only ensures that the data has made its way out of the process without + any guarantees on whether it's written to disk. This means that the + data would survive an application crash but not necessarily an OS crash. + """ + if self._writable_file: + self._writable_file.flush() + + def close(self): + r"""Closes the file. + + Should be called for the WritableFile to be flushed. + + In general, if you use the context manager pattern, you don't need to call + this directly. + + >>> with tf.io.gfile.GFile("/tmp/x", "w") as f: + ... f.write("asdf\n") + ... f.write("qwer\n") + >>> # implicit f.close() at the end of the block + + For cloud filesystems, forgetting to call `close()` might result in data + loss as last write might not have been replicated. + """ + self._read_buf = None + if self._writable_file: + self._writable_file.close() + self._writable_file = None + + def seekable(self): + """Returns True as FileIO supports random access ops of seek()/tell()""" + return True + + +@tf_export("io.gfile.exists") +def file_exists_v2(path): + """Determines whether a path exists or not. + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.exists("/tmp/x") + True + + You can also specify the URI scheme for selecting a different filesystem: + + >>> # for a GCS filesystem path: + >>> # tf.io.gfile.exists("gs://bucket/file") + >>> # for a local filesystem: + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.exists("file:///tmp/x") + True + + This currently returns `True` for existing directories but don't rely on this + behavior, especially if you are using cloud filesystems (e.g., GCS, S3, + Hadoop): + + >>> tf.io.gfile.exists("/tmp") + True + + Args: + path: string, a path + + Returns: + True if the path exists, whether it's a file or a directory. + False if the path does not exist and there are no filesystem errors. + + Raises: + errors.OpError: Propagates any errors reported by the FileSystem API. + """ + try: + _pywrap_file_io.FileExists(compat.path_to_bytes(path)) + except errors.NotFoundError: + return False + return True + + +@tf_export(v1=["gfile.Exists"]) +def file_exists(filename): + return file_exists_v2(filename) + + +file_exists.__doc__ = file_exists_v2.__doc__ + + +@tf_export(v1=["gfile.Remove"]) +def delete_file(filename): + """Deletes the file located at 'filename'. + + Args: + filename: string, a filename + + Raises: + errors.OpError: Propagates any errors reported by the FileSystem API. E.g., + `NotFoundError` if the file does not exist. + """ + delete_file_v2(filename) + + +@tf_export("io.gfile.remove") +def delete_file_v2(path): + """Deletes the path located at 'path'. + + Args: + path: string, a path + + Raises: + errors.OpError: Propagates any errors reported by the FileSystem API. E.g., + `NotFoundError` if the path does not exist. + """ + _pywrap_file_io.DeleteFile(compat.path_to_bytes(path)) + + +def read_file_to_string(filename, binary_mode=False): + """Reads the entire contents of a file to a string. + + Args: + filename: string, path to a file + binary_mode: whether to open the file in binary mode or not. This changes + the type of the object returned. + + Returns: + contents of the file as a string or bytes. + + Raises: + errors.OpError: Raises variety of errors that are subtypes e.g. + `NotFoundError` etc. + """ + if binary_mode: + f = FileIO(filename, mode="rb") + else: + f = FileIO(filename, mode="r") + return f.read() + + +def write_string_to_file(filename, file_content): + """Writes a string to a given file. + + Args: + filename: string, path to a file + file_content: string, contents that need to be written to the file + + Raises: + errors.OpError: If there are errors during the operation. + """ + with FileIO(filename, mode="w") as f: + f.write(file_content) + + +@tf_export(v1=["gfile.Glob"]) +def get_matching_files(filename): + """Returns a list of files that match the given pattern(s). + + Args: + filename: string or iterable of strings. The glob pattern(s). + + Returns: + A list of strings containing filenames that match the given pattern(s). + + Raises: + * errors.OpError: If there are filesystem / directory listing errors. + * errors.NotFoundError: If pattern to be matched is an invalid directory. + """ + return get_matching_files_v2(filename) + + +@tf_export("io.gfile.glob") +def get_matching_files_v2(pattern): + r"""Returns a list of files that match the given pattern(s). + + The patterns are defined as strings. Supported patterns are defined + here. Note that the pattern can be a Python iteratable of string patterns. + + The format definition of the pattern is: + + **pattern**: `{ term }` + + **term**: + * `'*'`: matches any sequence of non-'/' characters + * `'?'`: matches a single non-'/' character + * `'[' [ '^' ] { match-list } ']'`: matches any single + character (not) on the list + * `c`: matches character `c` where `c != '*', '?', '\\', '['` + * `'\\' c`: matches character `c` + + **character range**: + * `c`: matches character `c` while `c != '\\', '-', ']'` + * `'\\' c`: matches character `c` + * `lo '-' hi`: matches character `c` for `lo <= c <= hi` + + Examples: + + >>> tf.io.gfile.glob("*.py") + ... # For example, ['__init__.py'] + + >>> tf.io.gfile.glob("__init__.??") + ... # As above + + >>> files = {"*.py"} + >>> the_iterator = iter(files) + >>> tf.io.gfile.glob(the_iterator) + ... # As above + + See the C++ function `GetMatchingPaths` in + [`core/platform/file_system.h`] + (../../../core/platform/file_system.h) + for implementation details. + + Args: + pattern: string or iterable of strings. The glob pattern(s). + + Returns: + A list of strings containing filenames that match the given pattern(s). + + Raises: + errors.OpError: If there are filesystem / directory listing errors. + errors.NotFoundError: If pattern to be matched is an invalid directory. + """ + if isinstance(pattern, six.string_types): + return [ + # Convert the filenames to string from bytes. + compat.as_str_any(matching_filename) + for matching_filename in _pywrap_file_io.GetMatchingFiles( + compat.as_bytes(pattern)) + ] + else: + return [ + # Convert the filenames to string from bytes. + compat.as_str_any(matching_filename) # pylint: disable=g-complex-comprehension + for single_filename in pattern + for matching_filename in _pywrap_file_io.GetMatchingFiles( + compat.as_bytes(single_filename)) + ] + + +@tf_export(v1=["gfile.MkDir"]) +def create_dir(dirname): + """Creates a directory with the name `dirname`. + + Args: + dirname: string, name of the directory to be created + + Notes: The parent directories need to exist. Use `tf.io.gfile.makedirs` + instead if there is the possibility that the parent dirs don't exist. + + Raises: + errors.OpError: If the operation fails. + """ + create_dir_v2(dirname) + + +@tf_export("io.gfile.mkdir") +def create_dir_v2(path): + """Creates a directory with the name given by `path`. + + Args: + path: string, name of the directory to be created + + Notes: The parent directories need to exist. Use `tf.io.gfile.makedirs` + instead if there is the possibility that the parent dirs don't exist. + + Raises: + errors.OpError: If the operation fails. + """ + _pywrap_file_io.CreateDir(compat.path_to_bytes(path)) + + +@tf_export(v1=["gfile.MakeDirs"]) +def recursive_create_dir(dirname): + """Creates a directory and all parent/intermediate directories. + + It succeeds if dirname already exists and is writable. + + Args: + dirname: string, name of the directory to be created + + Raises: + errors.OpError: If the operation fails. + """ + recursive_create_dir_v2(dirname) + + +@tf_export("io.gfile.makedirs") +def recursive_create_dir_v2(path): + """Creates a directory and all parent/intermediate directories. + + It succeeds if path already exists and is writable. + + Args: + path: string, name of the directory to be created + + Raises: + errors.OpError: If the operation fails. + """ + _pywrap_file_io.RecursivelyCreateDir(compat.path_to_bytes(path)) + + +@tf_export("io.gfile.copy") +def copy_v2(src, dst, overwrite=False): + """Copies data from `src` to `dst`. + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.exists("/tmp/x") + True + >>> tf.io.gfile.copy("/tmp/x", "/tmp/y") + >>> tf.io.gfile.exists("/tmp/y") + True + >>> tf.io.gfile.remove("/tmp/y") + + You can also specify the URI scheme for selecting a different filesystem: + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y") + >>> tf.io.gfile.exists("/tmp/y") + True + >>> tf.io.gfile.remove("/tmp/y") + + Note that you need to always specify a file name, even if moving into a new + directory. This is because some cloud filesystems don't have the concept of a + directory. + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.mkdir("/tmp/new_dir") + >>> tf.io.gfile.copy("/tmp/x", "/tmp/new_dir/y") + >>> tf.io.gfile.exists("/tmp/new_dir/y") + True + >>> tf.io.gfile.rmtree("/tmp/new_dir") + + If you want to prevent errors if the path already exists, you can use + `overwrite` argument: + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y") + >>> tf.io.gfile.copy("/tmp/x", "file:///tmp/y", overwrite=True) + >>> tf.io.gfile.remove("/tmp/y") + + Note that the above will still result in an error if you try to overwrite a + directory with a file. + + Note that you cannot copy a directory, only file arguments are supported. + + Args: + src: string, name of the file whose contents need to be copied + dst: string, name of the file to which to copy to + overwrite: boolean, if false it's an error for `dst` to be occupied by an + existing file. + + Raises: + errors.OpError: If the operation fails. + """ + _pywrap_file_io.CopyFile( + compat.path_to_bytes(src), compat.path_to_bytes(dst), overwrite) + + +@tf_export(v1=["gfile.Copy"]) +def copy(oldpath, newpath, overwrite=False): + copy_v2(oldpath, newpath, overwrite) + + +copy.__doc__ = copy_v2.__doc__ + + +@tf_export(v1=["gfile.Rename"]) +def rename(oldname, newname, overwrite=False): + """Rename or move a file / directory. + + Args: + oldname: string, pathname for a file + newname: string, pathname to which the file needs to be moved + overwrite: boolean, if false it's an error for `newname` to be occupied by + an existing file. + + Raises: + errors.OpError: If the operation fails. + """ + rename_v2(oldname, newname, overwrite) + + +@tf_export("io.gfile.rename") +def rename_v2(src, dst, overwrite=False): + """Rename or move a file / directory. + + Args: + src: string, pathname for a file + dst: string, pathname to which the file needs to be moved + overwrite: boolean, if false it's an error for `dst` to be occupied by an + existing file. + + Raises: + errors.OpError: If the operation fails. + """ + _pywrap_file_io.RenameFile( + compat.path_to_bytes(src), compat.path_to_bytes(dst), overwrite) + + +def atomic_write_string_to_file(filename, contents, overwrite=True): + """Writes to `filename` atomically. + + This means that when `filename` appears in the filesystem, it will contain + all of `contents`. With write_string_to_file, it is possible for the file + to appear in the filesystem with `contents` only partially written. + + Accomplished by writing to a temp file and then renaming it. + + Args: + filename: string, pathname for a file + contents: string, contents that need to be written to the file + overwrite: boolean, if false it's an error for `filename` to be occupied by + an existing file. + """ + if not has_atomic_move(filename): + write_string_to_file(filename, contents) + else: + temp_pathname = filename + ".tmp" + uuid.uuid4().hex + write_string_to_file(temp_pathname, contents) + try: + rename(temp_pathname, filename, overwrite) + except errors.OpError: + delete_file(temp_pathname) + raise + + +@tf_export(v1=["gfile.DeleteRecursively"]) +def delete_recursively(dirname): + """Deletes everything under dirname recursively. + + Args: + dirname: string, a path to a directory + + Raises: + errors.OpError: If the operation fails. + """ + delete_recursively_v2(dirname) + + +@tf_export("io.gfile.rmtree") +def delete_recursively_v2(path): + """Deletes everything under path recursively. + + Args: + path: string, a path + + Raises: + errors.OpError: If the operation fails. + """ + _pywrap_file_io.DeleteRecursively(compat.path_to_bytes(path)) + + +@tf_export(v1=["gfile.IsDirectory"]) +def is_directory(dirname): + """Returns whether the path is a directory or not. + + Args: + dirname: string, path to a potential directory + + Returns: + True, if the path is a directory; False otherwise + """ + return is_directory_v2(dirname) + + +@tf_export("io.gfile.isdir") +def is_directory_v2(path): + """Returns whether the path is a directory or not. + + Args: + path: string, path to a potential directory + + Returns: + True, if the path is a directory; False otherwise + """ + try: + return _pywrap_file_io.IsDirectory(compat.path_to_bytes(path)) + except errors.OpError: + return False + + +def has_atomic_move(path): + """Checks whether the file system supports atomic moves. + + Returns whether or not the file system of the given path supports the atomic + move operation for a file or folder. If atomic move is supported, it is + recommended to use a temp location for writing and then move to the final + location. + + Args: + path: string, path to a file + + Returns: + True, if the path is on a file system that supports atomic move + False, if the file system does not support atomic move. In such cases + we need to be careful about using moves. In some cases it is safer + not to use temporary locations in this case. + """ + try: + return _pywrap_file_io.HasAtomicMove(compat.path_to_bytes(path)) + except errors.OpError: + # defaults to True + return True + + +@tf_export(v1=["gfile.ListDirectory"]) +def list_directory(dirname): + """Returns a list of entries contained within a directory. + + The list is in arbitrary order. It does not contain the special entries "." + and "..". + + Args: + dirname: string, path to a directory + + Returns: + [filename1, filename2, ... filenameN] as strings + + Raises: + errors.NotFoundError if directory doesn't exist + """ + return list_directory_v2(dirname) + + +@tf_export("io.gfile.listdir") +def list_directory_v2(path): + """Returns a list of entries contained within a directory. + + The list is in arbitrary order. It does not contain the special entries "." + and "..". + + Args: + path: string, path to a directory + + Returns: + [filename1, filename2, ... filenameN] as strings + + Raises: + errors.NotFoundError if directory doesn't exist + """ + if not is_directory(path): + raise errors.NotFoundError( + node_def=None, + op=None, + message="Could not find directory {}".format(path)) + + # Convert each element to string, since the return values of the + # vector of string should be interpreted as strings, not bytes. + return [ + compat.as_str_any(filename) + for filename in _pywrap_file_io.GetChildren(compat.path_to_bytes(path)) + ] + + +@tf_export("io.gfile.join") +def join(path, *paths): + r"""Join one or more path components intelligently. + + TensorFlow specific filesystems will be joined + like a url (using "/" as the path seperator) on all platforms: + + On Windows or Linux/Unix-like: + >>> tf.io.gfile.join("gcs://folder", "file.py") + 'gcs://folder/file.py' + + >>> tf.io.gfile.join("ram://folder", "file.py") + 'ram://folder/file.py' + + But the native filesystem is handled just like os.path.join: + + >>> path = tf.io.gfile.join("folder", "file.py") + >>> if os.name == "nt": + ... expected = "folder\\file.py" # Windows + ... else: + ... expected = "folder/file.py" # Linux/Unix-like + >>> path == expected + True + + Args: + path: string, path to a directory + paths: string, additional paths to concatenate + + Returns: + path: the joined path. + """ + # os.path.join won't take mixed bytes/str, so don't overwrite the incoming `path` var + path_ = compat.as_str_any(compat.path_to_str(path)) + if "://" in path_[1:]: + return urljoin(path, *paths) + return os.path.join(path, *paths) + + +@tf_export(v1=["gfile.Walk"]) +def walk(top, in_order=True): + """Recursive directory tree generator for directories. + + Args: + top: string, a Directory name + in_order: bool, Traverse in order if True, post order if False. Errors that + happen while listing directories are ignored. + + Yields: + Each yield is a 3-tuple: the pathname of a directory, followed by lists of + all its subdirectories and leaf files. That is, each yield looks like: + `(dirname, [subdirname, subdirname, ...], [filename, filename, ...])`. + Each item is a string. + """ + return walk_v2(top, in_order) + + +@tf_export("io.gfile.walk") +def walk_v2(top, topdown=True, onerror=None): + """Recursive directory tree generator for directories. + + Args: + top: string, a Directory name + topdown: bool, Traverse pre order if True, post order if False. + onerror: optional handler for errors. Should be a function, it will be + called with the error as argument. Rethrowing the error aborts the walk. + Errors that happen while listing directories are ignored. + + Yields: + Each yield is a 3-tuple: the pathname of a directory, followed by lists of + all its subdirectories and leaf files. That is, each yield looks like: + `(dirname, [subdirname, subdirname, ...], [filename, filename, ...])`. + Each item is a string. + """ + + def _make_full_path(parent, item): + # Since `join` discards paths before one that starts with the path + # separator (https://docs.python.org/3/library/os.path.html#join), + # we have to manually handle that case as `/` is a valid character on GCS. + if item[0] == os.sep: + return "".join([join(parent, ""), item]) + return join(parent, item) + + top = compat.as_str_any(compat.path_to_str(top)) + try: + listing = list_directory(top) + except errors.NotFoundError as err: + if onerror: + onerror(err) + else: + return + + files = [] + subdirs = [] + for item in listing: + full_path = _make_full_path(top, item) + if is_directory(full_path): + subdirs.append(item) + else: + files.append(item) + + here = (top, subdirs, files) + + if topdown: + yield here + + for subdir in subdirs: + for subitem in walk_v2( + _make_full_path(top, subdir), topdown, onerror=onerror): + yield subitem + + if not topdown: + yield here + + +@tf_export(v1=["gfile.Stat"]) +def stat(filename): + """Returns file statistics for a given path. + + Args: + filename: string, path to a file + + Returns: + FileStatistics struct that contains information about the path + + Raises: + errors.OpError: If the operation fails. + """ + return stat_v2(filename) + + +@tf_export("io.gfile.stat") +def stat_v2(path): + """Returns file statistics for a given path. + + Args: + path: string, path to a file + + Returns: + FileStatistics struct that contains information about the path + + Raises: + errors.OpError: If the operation fails. + """ + return _pywrap_file_io.Stat(compat.path_to_str(path)) + + +def filecmp(filename_a, filename_b): + """Compare two files, returning True if they are the same, False otherwise. + + We check size first and return False quickly if the files are different sizes. + If they are the same size, we continue to generating a crc for the whole file. + + You might wonder: why not use Python's `filecmp.cmp()` instead? The answer is + that the builtin library is not robust to the many different filesystems + TensorFlow runs on, and so we here perform a similar comparison with + the more robust FileIO. + + Args: + filename_a: string path to the first file. + filename_b: string path to the second file. + + Returns: + True if the files are the same, False otherwise. + """ + size_a = FileIO(filename_a, "rb").size() + size_b = FileIO(filename_b, "rb").size() + if size_a != size_b: + return False + + # Size is the same. Do a full check. + crc_a = file_crc32(filename_a) + crc_b = file_crc32(filename_b) + return crc_a == crc_b + + +def file_crc32(filename, block_size=_DEFAULT_BLOCK_SIZE): + """Get the crc32 of the passed file. + + The crc32 of a file can be used for error checking; two files with the same + crc32 are considered equivalent. Note that the entire file must be read + to produce the crc32. + + Args: + filename: string, path to a file + block_size: Integer, process the files by reading blocks of `block_size` + bytes. Use -1 to read the file as once. + + Returns: + hexadecimal as string, the crc32 of the passed file. + """ + crc = 0 + with FileIO(filename, mode="rb") as f: + chunk = f.read(n=block_size) + while chunk: + crc = binascii.crc32(chunk, crc) + chunk = f.read(n=block_size) + return hex(crc & 0xFFFFFFFF) + + +@tf_export("io.gfile.get_registered_schemes") +def get_registered_schemes(): + """Returns the currently registered filesystem schemes. + + The `tf.io.gfile` APIs, in addition to accepting traditional filesystem paths, + also accept file URIs that begin with a scheme. For example, the local + filesystem path `/tmp/tf` can also be addressed as `file:///tmp/tf`. In this + case, the scheme is `file`, followed by `://` and then the path, according to + [URI syntax](https://datatracker.ietf.org/doc/html/rfc3986#section-3). + + This function returns the currently registered schemes that will be recognized + by `tf.io.gfile` APIs. This includes both built-in schemes and those + registered by other TensorFlow filesystem implementations, for example those + provided by [TensorFlow I/O](https://github.com/tensorflow/io). + + The empty string is always included, and represents the "scheme" for regular + local filesystem paths. + + Returns: + List of string schemes, e.g. `['', 'file', 'ram']`, in arbitrary order. + + Raises: + errors.OpError: If the operation fails. + """ + return _pywrap_file_io.GetRegisteredSchemes() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/python_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/python_io.py new file mode 100644 index 0000000000000000000000000000000000000000..a7cd408463eb52f0860c8d853e2ec918fb67bbd1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/python_io.py @@ -0,0 +1,24 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Python functions for directly manipulating TFRecord-formatted files. + +API docstring: tensorflow.python_io +""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.lib.io.tf_record import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/tf_record.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/tf_record.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8d62ef2e5143bab380f66b30b83617e9b027af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/lib/io/tf_record.py @@ -0,0 +1,318 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""For reading and writing TFRecords files.""" + +from tensorflow.python.lib.io import _pywrap_record_io +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export( + v1=["io.TFRecordCompressionType", "python_io.TFRecordCompressionType"]) +@deprecation.deprecated_endpoints("io.TFRecordCompressionType", + "python_io.TFRecordCompressionType") +class TFRecordCompressionType(object): + """The type of compression for the record.""" + NONE = 0 + ZLIB = 1 + GZIP = 2 + + +@tf_export( + "io.TFRecordOptions", + v1=["io.TFRecordOptions", "python_io.TFRecordOptions"]) +@deprecation.deprecated_endpoints("python_io.TFRecordOptions") +class TFRecordOptions(object): + """Options used for manipulating TFRecord files.""" + compression_type_map = { + TFRecordCompressionType.ZLIB: "ZLIB", + TFRecordCompressionType.GZIP: "GZIP", + TFRecordCompressionType.NONE: "" + } + + def __init__(self, + compression_type=None, + flush_mode=None, + input_buffer_size=None, + output_buffer_size=None, + window_bits=None, + compression_level=None, + compression_method=None, + mem_level=None, + compression_strategy=None): + # pylint: disable=line-too-long + """Creates a `TFRecordOptions` instance. + + Options only effect TFRecordWriter when compression_type is not `None`. + Documentation, details, and defaults can be found in + [`zlib_compression_options.h`](https://www.tensorflow.org/code/tensorflow/core/lib/io/zlib_compression_options.h) + and in the [zlib manual](http://www.zlib.net/manual.html). + Leaving an option as `None` allows C++ to set a reasonable default. + + Args: + compression_type: `"GZIP"`, `"ZLIB"`, or `""` (no compression). + flush_mode: flush mode or `None`, Default: Z_NO_FLUSH. + input_buffer_size: int or `None`. + output_buffer_size: int or `None`. + window_bits: int or `None`. + compression_level: 0 to 9, or `None`. + compression_method: compression method or `None`. + mem_level: 1 to 9, or `None`. + compression_strategy: strategy or `None`. Default: Z_DEFAULT_STRATEGY. + + Returns: + A `TFRecordOptions` object. + + Raises: + ValueError: If compression_type is invalid. + """ + # pylint: enable=line-too-long + # Check compression_type is valid, but for backwards compatibility don't + # immediately convert to a string. + self.get_compression_type_string(compression_type) + self.compression_type = compression_type + self.flush_mode = flush_mode + self.input_buffer_size = input_buffer_size + self.output_buffer_size = output_buffer_size + self.window_bits = window_bits + self.compression_level = compression_level + self.compression_method = compression_method + self.mem_level = mem_level + self.compression_strategy = compression_strategy + + @classmethod + def get_compression_type_string(cls, options): + """Convert various option types to a unified string. + + Args: + options: `TFRecordOption`, `TFRecordCompressionType`, or string. + + Returns: + Compression type as string (e.g. `'ZLIB'`, `'GZIP'`, or `''`). + + Raises: + ValueError: If compression_type is invalid. + """ + if not options: + return "" + elif isinstance(options, TFRecordOptions): + return cls.get_compression_type_string(options.compression_type) + elif isinstance(options, TFRecordCompressionType): + return cls.compression_type_map[options] + elif options in TFRecordOptions.compression_type_map: + return cls.compression_type_map[options] + elif options in TFRecordOptions.compression_type_map.values(): + return options + else: + raise ValueError('Not a valid compression_type: "{}"'.format(options)) + + def _as_record_writer_options(self): + """Convert to RecordWriterOptions for use with PyRecordWriter.""" + options = _pywrap_record_io.RecordWriterOptions( + compat.as_bytes( + self.get_compression_type_string(self.compression_type))) + + if self.flush_mode is not None: + options.zlib_options.flush_mode = self.flush_mode + if self.input_buffer_size is not None: + options.zlib_options.input_buffer_size = self.input_buffer_size + if self.output_buffer_size is not None: + options.zlib_options.output_buffer_size = self.output_buffer_size + if self.window_bits is not None: + options.zlib_options.window_bits = self.window_bits + if self.compression_level is not None: + options.zlib_options.compression_level = self.compression_level + if self.compression_method is not None: + options.zlib_options.compression_method = self.compression_method + if self.mem_level is not None: + options.zlib_options.mem_level = self.mem_level + if self.compression_strategy is not None: + options.zlib_options.compression_strategy = self.compression_strategy + return options + + +@tf_export(v1=["io.tf_record_iterator", "python_io.tf_record_iterator"]) +@deprecation.deprecated( + date=None, + instructions=("Use eager execution and: \n" + "`tf.data.TFRecordDataset(path)`")) +def tf_record_iterator(path, options=None): + """An iterator that read the records from a TFRecords file. + + Args: + path: The path to the TFRecords file. + options: (optional) A TFRecordOptions object. + + Returns: + An iterator of serialized TFRecords. + + Raises: + IOError: If `path` cannot be opened for reading. + """ + compression_type = TFRecordOptions.get_compression_type_string(options) + return _pywrap_record_io.RecordIterator(path, compression_type) + + +def tf_record_random_reader(path): + """Creates a reader that allows random-access reads from a TFRecords file. + + The created reader object has the following method: + + - `read(offset)`, which returns a tuple of `(record, ending_offset)`, where + `record` is the TFRecord read at the offset, and + `ending_offset` is the ending offset of the read record. + + The method throws a `tf.errors.DataLossError` if data is corrupted at + the given offset. The method throws `IndexError` if the offset is out of + range for the TFRecords file. + + + Usage example: + ```py + reader = tf_record_random_reader(file_path) + + record_1, offset_1 = reader.read(0) # 0 is the initial offset. + # offset_1 is the ending offset of the 1st record and the starting offset of + # the next. + + record_2, offset_2 = reader.read(offset_1) + # offset_2 is the ending offset of the 2nd record and the starting offset of + # the next. + # We can jump back and read the first record again if so desired. + reader.read(0) + ``` + + Args: + path: The path to the TFRecords file. + + Returns: + An object that supports random-access reading of the serialized TFRecords. + + Raises: + IOError: If `path` cannot be opened for reading. + """ + return _pywrap_record_io.RandomRecordReader(path) + + +@tf_export( + "io.TFRecordWriter", v1=["io.TFRecordWriter", "python_io.TFRecordWriter"]) +@deprecation.deprecated_endpoints("python_io.TFRecordWriter") +class TFRecordWriter(_pywrap_record_io.RecordWriter): + """A class to write records to a TFRecords file. + + [TFRecords tutorial](https://www.tensorflow.org/tutorials/load_data/tfrecord) + + TFRecords is a binary format which is optimized for high throughput data + retrieval, generally in conjunction with `tf.data`. `TFRecordWriter` is used + to write serialized examples to a file for later consumption. The key steps + are: + + Ahead of time: + + - [Convert data into a serialized format]( + https://www.tensorflow.org/tutorials/load_data/tfrecord#tfexample) + - [Write the serialized data to one or more files]( + https://www.tensorflow.org/tutorials/load_data/tfrecord#tfrecord_files_in_python) + + During training or evaluation: + + - [Read serialized examples into memory]( + https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file) + - [Parse (deserialize) examples]( + https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file) + + A minimal example is given below: + + >>> import tempfile + >>> example_path = os.path.join(tempfile.gettempdir(), "example.tfrecords") + >>> np.random.seed(0) + + >>> # Write the records to a file. + ... with tf.io.TFRecordWriter(example_path) as file_writer: + ... for _ in range(4): + ... x, y = np.random.random(), np.random.random() + ... + ... record_bytes = tf.train.Example(features=tf.train.Features(feature={ + ... "x": tf.train.Feature(float_list=tf.train.FloatList(value=[x])), + ... "y": tf.train.Feature(float_list=tf.train.FloatList(value=[y])), + ... })).SerializeToString() + ... file_writer.write(record_bytes) + + >>> # Read the data back out. + >>> def decode_fn(record_bytes): + ... return tf.io.parse_single_example( + ... # Data + ... record_bytes, + ... + ... # Schema + ... {"x": tf.io.FixedLenFeature([], dtype=tf.float32), + ... "y": tf.io.FixedLenFeature([], dtype=tf.float32)} + ... ) + + >>> for batch in tf.data.TFRecordDataset([example_path]).map(decode_fn): + ... print("x = {x:.4f}, y = {y:.4f}".format(**batch)) + x = 0.5488, y = 0.7152 + x = 0.6028, y = 0.5449 + x = 0.4237, y = 0.6459 + x = 0.4376, y = 0.8918 + + This class implements `__enter__` and `__exit__`, and can be used + in `with` blocks like a normal file. (See the usage example above.) + """ + + # TODO(josh11b): Support appending? + def __init__(self, path, options=None): + """Opens file `path` and creates a `TFRecordWriter` writing to it. + + Args: + path: The path to the TFRecords file. + options: (optional) String specifying compression type, + `TFRecordCompressionType`, or `TFRecordOptions` object. + + Raises: + IOError: If `path` cannot be opened for writing. + ValueError: If valid compression_type can't be determined from `options`. + """ + if not isinstance(options, TFRecordOptions): + options = TFRecordOptions(compression_type=options) + + # pylint: disable=protected-access + super(TFRecordWriter, self).__init__( + compat.as_bytes(path), options._as_record_writer_options()) + # pylint: enable=protected-access + + # TODO(slebedev): The following wrapper methods are there to compensate + # for lack of signatures in pybind11-generated classes. Switch to + # __text_signature__ when TensorFlow drops Python 2.X support. + # See https://github.com/pybind/pybind11/issues/945 + # pylint: disable=useless-super-delegation + def write(self, record): + """Write a string record to the file. + + Args: + record: str + """ + super(TFRecordWriter, self).write(record) + + def flush(self): + """Flush the file.""" + super(TFRecordWriter, self).flush() + + def close(self): + """Close the file.""" + super(TFRecordWriter, self).close() + # pylint: enable=useless-super-delegation diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/module/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/module/module.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/module/module.py new file mode 100644 index 0000000000000000000000000000000000000000..19c9cc816ae4b738459991d6d2d6ee6ca81eadc4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/module/module.py @@ -0,0 +1,467 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Modules encapsulate building stateful components.""" + +import re + +from tensorflow.python import tf2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import ops +from tensorflow.python.ops import variables +from tensorflow.python.trackable import autotrackable +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("Module") +class Module(autotrackable.AutoTrackable): + """Base neural network module class. + + A module is a named container for `tf.Variable`s, other `tf.Module`s and + functions which apply to user input. For example a dense layer in a neural + network might be implemented as a `tf.Module`: + + >>> class Dense(tf.Module): + ... def __init__(self, input_dim, output_size, name=None): + ... super().__init__(name=name) + ... self.w = tf.Variable( + ... tf.random.normal([input_dim, output_size]), name='w') + ... self.b = tf.Variable(tf.zeros([output_size]), name='b') + ... def __call__(self, x): + ... y = tf.matmul(x, self.w) + self.b + ... return tf.nn.relu(y) + + You can use the Dense layer as you would expect: + + >>> d = Dense(input_dim=3, output_size=2) + >>> d(tf.ones([1, 3])) + + + + By subclassing `tf.Module` instead of `object` any `tf.Variable` or + `tf.Module` instances assigned to object properties can be collected using + the `variables`, `trainable_variables` or `submodules` property: + + >>> d.variables + (, + ) + + + Subclasses of `tf.Module` can also take advantage of the `_flatten` method + which can be used to implement tracking of any other types. + + All `tf.Module` classes have an associated `tf.name_scope` which can be used + to group operations in TensorBoard and create hierarchies for variable names + which can help with debugging. We suggest using the name scope when creating + nested submodules/parameters or for forward methods whose graph you might want + to inspect in TensorBoard. You can enter the name scope explicitly using + `with self.name_scope:` or you can annotate methods (apart from `__init__`) + with `@tf.Module.with_name_scope`. + + >>> class MLP(tf.Module): + ... def __init__(self, input_size, sizes, name=None): + ... super().__init__(name=name) + ... self.layers = [] + ... with self.name_scope: + ... for size in sizes: + ... self.layers.append(Dense(input_dim=input_size, output_size=size)) + ... input_size = size + ... @tf.Module.with_name_scope + ... def __call__(self, x): + ... for layer in self.layers: + ... x = layer(x) + ... return x + + >>> module = MLP(input_size=5, sizes=[5, 5]) + >>> module.variables + (, + , + , + ) + """ + + # AutoTrackable adds object attributes that users will not expect us to + # include when flattening (these reference dependencies reachable via other + # object attributes). + _TF_MODULE_IGNORED_PROPERTIES = frozenset(( + "_self_unconditional_checkpoint_dependencies", + "_self_unconditional_dependency_names" + )) + + def __init__(self, name=None): + if name is None: + name = camel_to_snake(type(self).__name__) + else: + if not valid_identifier(name): + raise ValueError( + "%r is not a valid module name. Module names must be valid Python " + "identifiers (e.g. a valid class name)." % name) + + self._name = name + if tf2.enabled(): + with ops.name_scope_v2(name) as scope_name: + self._name_scope = ops.name_scope_v2(scope_name) + else: + with ops.name_scope(name, skip_on_eager=False) as scope_name: + self._scope_name = scope_name + + @property + def name(self): + """Returns the name of this module as passed or determined in the ctor. + + NOTE: This is not the same as the `self.name_scope.name` which includes + parent module names. + """ + return self._name + + @property + def name_scope(self): + """Returns a `tf.name_scope` instance for this class.""" + if tf2.enabled(): + return self._name_scope + else: + # In TF1 name_scope is not re-entrant in eager so we cannot memoize it. + return ops.name_scope(self._scope_name, skip_on_eager=False) + + @property + def variables(self): + """Sequence of variables owned by this module and its submodules. + + Note: this method uses reflection to find variables on the current instance + and submodules. For performance reasons you may wish to cache the result + of calling this method if you don't expect the return value to change. + + Returns: + A sequence of variables for the current module (sorted by attribute + name) followed by variables from all submodules recursively (breadth + first). + """ + return tuple(self._flatten(predicate=_is_variable, expand_composites=True)) + + @property + def trainable_variables(self): + """Sequence of trainable variables owned by this module and its submodules. + + Note: this method uses reflection to find variables on the current instance + and submodules. For performance reasons you may wish to cache the result + of calling this method if you don't expect the return value to change. + + Returns: + A sequence of variables for the current module (sorted by attribute + name) followed by variables from all submodules recursively (breadth + first). + """ + return tuple( + self._flatten(predicate=_is_trainable_variable, expand_composites=True)) + + @property + def non_trainable_variables(self): + """Sequence of non-trainable variables owned by this module and its submodules. + + Note: this method uses reflection to find variables on the current instance + and submodules. For performance reasons you may wish to cache the result + of calling this method if you don't expect the return value to change. + + Returns: + A sequence of variables for the current module (sorted by attribute + name) followed by variables from all submodules recursively (breadth + first). + """ + return tuple(self._flatten( + predicate=_is_non_trainable_variable, expand_composites=True)) + + @property + def submodules(self): + """Sequence of all sub-modules. + + Submodules are modules which are properties of this module, or found as + properties of modules which are properties of this module (and so on). + + >>> a = tf.Module() + >>> b = tf.Module() + >>> c = tf.Module() + >>> a.b = b + >>> b.c = c + >>> list(a.submodules) == [b, c] + True + >>> list(b.submodules) == [c] + True + >>> list(c.submodules) == [] + True + + Returns: + A sequence of all submodules. + """ + return tuple(self._flatten(predicate=_is_module)) + + def _flatten(self, + recursive=True, + predicate=None, + attribute_traversal_key=None, + with_path=False, + expand_composites=False): + """Flattened attribute values in sorted order by attribute name. + + Modules are flattened by first walking their attributes in name order. + Each attribute value is then flattened to find leaf values. If flatten is + applied `recursive`ly and if the leaf is a `Module` it will also be + flattened to find leaves. Finally every leaf value is optionally tested + against the given `predicate` and finally yielded. + + ``` + class Foo(tf.Module): + def __init__(self): + super().__init__() + self.x = [tf.constant('a'), tf.constant('b')] + self.y = {'i': tf.constant('c'), 'j': tf.constant('d')} + self.z = tf.constant('e') + + @property + def tensors(self): + return tuple(self._flatten(predicate=is_tensor, with_path=True)) + + foo = Foo() + foo.tensors + # ==> ((('x', 0), ), + # (('x', 1), ), + # (('y', 'i'), ), + # (('y', 'j'), ), + # (('z',), )) + ``` + + `attribute_traversal_key` controls the order object properties are visited. + If not set objects are visited in ascending order by name. + + Args: + recursive: Whether to recurse into child modules or not. + predicate: (Optional) If set then only values matching predicate are + yielded. A value of `None` (the default) means no items will be + filtered. + attribute_traversal_key: (Optional) Method to rekey object attributes + before they are sorted. Contract is the same as `key` argument to + builtin `sorted` and only applies to object properties. + with_path: (Optional) Whether to include the path to the object as well + as the object itself. If `with_path` is `True` then leaves will not be + de-duplicated (e.g. if the same leaf instance is reachable via multiple + modules then it will be yielded multiple times with different paths). + expand_composites: If true, then composite tensors are expanded into their + component tensors. + + Returns: + Flat generator for leaves of the current module and optionally all + submodules. + """ + if predicate is None: + predicate = lambda _: True + + return _flatten_module( + self, + recursive=recursive, + predicate=predicate, + attributes_to_ignore=self._TF_MODULE_IGNORED_PROPERTIES, + attribute_traversal_key=attribute_traversal_key, + with_path=with_path, + expand_composites=expand_composites) + + @classmethod + def with_name_scope(cls, method): + """Decorator to automatically enter the module name scope. + + >>> class MyModule(tf.Module): + ... @tf.Module.with_name_scope + ... def __call__(self, x): + ... if not hasattr(self, 'w'): + ... self.w = tf.Variable(tf.random.normal([x.shape[1], 3])) + ... return tf.matmul(x, self.w) + + Using the above module would produce `tf.Variable`s and `tf.Tensor`s whose + names included the module name: + + >>> mod = MyModule() + >>> mod(tf.ones([1, 2])) + + >>> mod.w + + + Args: + method: The method to wrap. + + Returns: + The original method wrapped such that it enters the module's name scope. + """ + def method_with_name_scope(self, *args, **kwargs): + with self.name_scope: + return method(self, *args, **kwargs) + + return tf_decorator.make_decorator(method, method_with_name_scope) + + +def _is_variable(obj): + return isinstance(obj, variables.Variable) + + +def _is_trainable_variable(obj): + return _is_variable(obj) and getattr(obj, "trainable", False) + + +def _is_non_trainable_variable(obj): + return _is_variable(obj) and not getattr(obj, "trainable", False) + + +def _is_module(obj): + return isinstance(obj, Module) + +_CAMEL_TO_SNAKE_R = re.compile(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))") +_VALID_IDENTIFIER = re.compile(r"^[a-zA-Z_]([a-zA-Z0-9_])*$") + + +def valid_identifier(name): + return bool(_VALID_IDENTIFIER.match(name)) + + +def camel_to_snake(value): + return _CAMEL_TO_SNAKE_R.sub(r"_\1", value).lower() + + +def _flatten_non_variable_composites_with_tuple_path(structure, path_prefix=()): + """Flattens composite tensors with tuple path expect variables.""" + for path, child in nest.flatten_with_tuple_paths(structure): + if (isinstance(child, composite_tensor.CompositeTensor) and + not _is_variable(child)): + # pylint: disable=protected-access + spec = child._type_spec + yield from _flatten_non_variable_composites_with_tuple_path( + spec._to_components(child), + path_prefix + path + (spec.value_type.__name__,)) + # pylint: enable=protected-access + else: + yield path_prefix + path, child + + +def _flatten_module(module, + recursive, + predicate, + attribute_traversal_key, + attributes_to_ignore, + with_path, + expand_composites, + module_path=(), + seen=None, + recursion_stack=None): + """Implementation of `flatten`. + + Args: + module: Current module to process. + recursive: Whether to recurse into child modules or not. + predicate: (Optional) If set then only values matching predicate are + yielded. A value of `None` (the default) means no items will be + filtered. + attribute_traversal_key: (Optional) Method to rekey object attributes + before they are sorted. Contract is the same as `key` argument to + builtin `sorted` and only applies to object properties. + attributes_to_ignore: object attributes to ignored. + with_path: (Optional) Whether to include the path to the object as well + as the object itself. If `with_path` is `True` then leaves will not be + de-duplicated (e.g. if the same leaf instance is reachable via multiple + modules then it will be yielded multiple times with different paths). + expand_composites: If true, then composite tensors are expanded into their + component tensors. + module_path: The path to the current module as a tuple. + seen: A set containing all leaf IDs seen so far. + recursion_stack: A list containing all module IDs associated with the + current call stack. + + Yields: + Matched leaves with the optional corresponding paths of the current module + and optionally all its submodules. + """ + module_id = id(module) + if seen is None: + seen = set([module_id]) + + module_dict = vars(module) + submodules = [] + + if recursion_stack is None: + recursion_stack = [] + + # When calling `_flatten_module` with `with_path=False`, the global lookup + # table `seen` guarantees the uniqueness of the matched objects. + # In the case of `with_path=True`, there might be multiple paths associated + # with the same predicate, so we don't stop traversing according to `seen` + # to make sure all these paths are returned. + # When there are cycles connecting submodules, we break cycles by avoiding + # following back edges (links pointing to a node in `recursion_stack`). + if module_id in recursion_stack: + recursive = False + + for key in sorted(module_dict, key=attribute_traversal_key): + if key in attributes_to_ignore: + continue + + prop = module_dict[key] + try: + if expand_composites: + leaves = list(_flatten_non_variable_composites_with_tuple_path(prop)) + else: + leaves = nest.flatten_with_tuple_paths(prop) + except Exception as cause: # pylint: disable=broad-except + raise ValueError("Error processing property {!r} of {!r}".format( + key, prop)) from cause + + for leaf_path, leaf in leaves: + leaf_path = (key,) + leaf_path + + if not with_path: + leaf_id = id(leaf) + if leaf_id in seen: + continue + seen.add(leaf_id) + + if predicate(leaf): + if with_path: + yield module_path + leaf_path, leaf + else: + yield leaf + + if recursive and _is_module(leaf): + # Walk direct properties first then recurse. + submodules.append((module_path + leaf_path, leaf)) + + recursion_stack.append(module_id) + + for submodule_path, submodule in submodules: + subvalues = _flatten_module( + submodule, + recursive=recursive, + predicate=predicate, + attribute_traversal_key=attribute_traversal_key, + attributes_to_ignore=submodule._TF_MODULE_IGNORED_PROPERTIES, # pylint: disable=protected-access + with_path=with_path, + expand_composites=expand_composites, + module_path=submodule_path, + seen=seen, + recursion_stack=recursion_stack) + + for subvalue in subvalues: + # Predicate is already tested for these values. + yield subvalue + + recursion_stack.pop() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..c23c5356cc64b7c07bb761626160bfc3d95cf873 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_grad.py @@ -0,0 +1,1227 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in array_ops.py.""" + +from tensorflow.compiler.tf2xla.ops import gen_xla_ops +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices as indexed_slices_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops + + +@ops.RegisterGradient("Pack") +def _PackGrad(op: ops.Operation, grad): + """Gradient for pack op.""" + return array_ops_stack.unstack( + grad, num=op.get_attr("N"), axis=op.get_attr("axis")) + + +@ops.RegisterGradient("Unpack") +def _UnpackGrad(op: ops.Operation, *grads): + """Gradient for unpack op.""" + return array_ops_stack.stack(grads, axis=op.get_attr("axis")) + + +def _ConcatGradHelper( + op: ops.Operation, grad, start_value_index, end_value_index, dim_index +): + """Gradient for concat op. + + Args: + op: An operation. + grad: `Tensor` or `IndexedSlices` representing the gradients with respect to + each output of the op. + start_value_index: An integer index of the first value in the op.inputs. + end_value_index: An integer index of the last value in the op.inputs. + dim_index: An integer index of concat_dim or axis parameter in op.inputs. + + Returns: + Tensors representing the partial gradients with respect to each input + of the op. + + Raises: + ValueError: if concat_dim/axis is not statically known. + """ + + def _CreateDenseMaskAndBegin(sizes, concat_dim): + """Create variables for iteratively slicing a dense gradients tensor.""" + # Since shape is 1-D, shape_of_shape = [rank-of-inputs] + shape_of_shape = array_ops.shape(sizes[0]) + # Make a vector of length equal to the input's dimensions, + # with 0's everywhere and 1 in the concat dim position. + # Note: Can't use sparse_to_dense since it isn't GPU-capable (for now) + mask = array_ops.concat([ + array_ops.zeros( + array_ops.expand_dims(concat_dim, 0), dtype=dtypes.int32), [1], + array_ops.zeros(shape_of_shape - concat_dim - 1, dtype=dtypes.int32) + ], 0) + begin = array_ops.zeros(shape_of_shape, dtype=dtypes.int32) + return mask, begin + + def _ExtractInputShapes(inputs): + """Extract the shapes of a set of input tensors.""" + if context.executing_eagerly(): + return array_ops.shape_n(inputs) + sizes = [] + fully_known = True + for x in inputs: + input_shape = array_ops.shape(x) + if not isinstance(input_shape, + tensor.Tensor) or input_shape.op.type != "Const": + fully_known = False + break + sizes.append(input_shape) + + if fully_known: + return sizes + else: + return array_ops.shape_n(inputs) + + # Degenerate concatenation, just return grad. + if len(op.inputs) == 2: + return grad + [None] if end_value_index <= dim_index else [None] + grad + + concat_dim = op.inputs[dim_index] + input_values = op.inputs[start_value_index:end_value_index] + + out_grads = [] + if isinstance(grad, tensor.Tensor): + if context.executing_eagerly() or isinstance(concat_dim, ops.EagerTensor): + # Using mod here for convenience since concat_dim is already verified + # in concat implementation to be within the allowed [-rank, rank) range. + non_neg_concat_dim = ( + concat_dim._numpy().item(0) % input_values[0]._rank()) # pylint: disable=protected-access + # All inputs are guaranteed to be EagerTensors in eager mode + sizes = pywrap_tfe.TFE_Py_TensorShapeSlice(input_values, + non_neg_concat_dim) + out_grads = array_ops.split(grad, sizes, non_neg_concat_dim) + else: + if constant_op.is_constant(concat_dim): + # If concat_dim is a constant defined in a different context, + # then we duplicate it in the current context to avoid passing it + # through an Enter node. + # This is a small optimization in general, but it is required when + # compiling with XLA, as XLA needs the concat input to be folded into a + # constant. + grad_context = control_flow_util.GetOutputContext(grad.op) + dim_context = control_flow_util.GetOutputContext(concat_dim.op) + if dim_context != grad_context: + value = tensor_util.constant_value(concat_dim) + concat_dim = constant_op.constant(value=value, dtype=concat_dim.dtype) + + # Using mod here for convenience since concat_dim is already verified + # in concat implementation to be within the allowed [-rank, rank) range. + non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0]) + + # Get the inputs' tensor shapes + sizes = _ExtractInputShapes(input_values) + # The magic number of 16 was found through benchmarking a range of sizes + # on CPUs and a Maxwell TitanX. A speedup was seen in a large majority of + # cases when switching implementations at N=16, but it is possible that + # there will be a small number of performance regressions. + if len(sizes) > 16: + # extract the size of each input along the concat dimension + sizes = array_ops.squeeze( + array_ops.slice( + array_ops_stack.stack(sizes, axis=1), [non_neg_concat_dim, 0], + [1, -1])) + out_grads = array_ops.split(grad, sizes, non_neg_concat_dim) + else: + offset = gen_array_ops.concat_offset(non_neg_concat_dim, sizes) + for (begin, size) in zip(offset, sizes): + out_grads.append(array_ops.slice(grad, begin, size)) + elif isinstance(grad, indexed_slices_lib.IndexedSlices): + # Using mod here for convenience since concat_dim is already verified + # in concat implementation to be within the allowed [-rank, rank) range. + non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0]) + concat_dim_static = tensor_util.constant_value(concat_dim) + if concat_dim_static is None: + raise ValueError("Can only compute IndexedSlices gradient with " + "statically-known concat_dim") + if concat_dim_static < 0: + rank = tensor_util.constant_value(array_ops.rank(input_values[0])) + if rank is None: + raise ValueError("Can only compute IndexedSlices gradient with " + "negative concat_dim when first value rank is " + "statically-known.") + concat_dim_static %= rank + # Get the inputs' tensor shapes + sizes = [array_ops.shape(x) for x in input_values] + if concat_dim_static > 0: + # IndexedSlices, non_neg_concat_dim > 0. Each input gets IndexedSlices + # gradients with all the indices, but with grad.values sliced accordingly. + # This is like the Tensor case, except shape(grad.values)[0] is not equal + # to shape(sizes[i])[0], since only a subset of the dim-0 values are + # stored. + mask, begin = _CreateDenseMaskAndBegin(sizes, non_neg_concat_dim) + for size in sizes: + new_values = array_ops.slice( + grad.values, begin, + array_ops.concat([[-1], array_ops.slice(size, [1], [-1])], 0)) + out_grads.append( + indexed_slices_lib.IndexedSlices(new_values, grad.indices, size)) + # Lint complains begin = begin + ... + begin = math_ops.add(begin, size * mask) + else: + # IndexedSlices, concat_dim == 0. Each input gets IndexedSlices gradients + # only for the relevant indices. + start = constant_op.constant(0, dtype=grad.indices.dtype) + for size in sizes: + size_concat_dim = array_ops.gather(size, non_neg_concat_dim) + if size_concat_dim.dtype != grad.indices.dtype: + size_concat_dim = math_ops.cast( + size_concat_dim, dtype=grad.indices.dtype) + end = start + size_concat_dim + # Compute the 1-D Tensor of indices relevant for this input. + indices_to_select = array_ops.squeeze( + array_ops.where( + math_ops.logical_and(grad.indices >= start, + grad.indices < end)), + axis=[1]) + new_indices = array_ops.gather(grad.indices, indices_to_select) - start + new_values = array_ops.gather(grad.values, indices_to_select) + out_grads.append( + indexed_slices_lib.IndexedSlices(new_values, new_indices, size)) + start = end + else: + raise TypeError("Expected Tensor or IndexedSlices, got %s" % type(grad)) + + return (out_grads + [None] if end_value_index <= dim_index else [None] + + out_grads) + + +@ops.RegisterGradient("Concat") +def _ConcatGrad(op: ops.Operation, grad): + return _ConcatGradHelper( + op, + grad, + start_value_index=1, + end_value_index=len(op.inputs), + dim_index=0) + + +@ops.RegisterGradient("ConcatV2") +def _ConcatGradV2(op: ops.Operation, grad): + return _ConcatGradHelper( + op, grad, start_value_index=0, end_value_index=-1, dim_index=-1) + + +ops.NotDifferentiable("ConcatOffset") + + +@ops.RegisterGradient("Slice") +def _SliceGrad(op: ops.Operation, grad): + """Gradient for Slice op.""" + # Create an Nx2 padding where the first column represents how many + # zeros are to be prepended for each dimension, and the second + # column indicates how many zeros are appended. + # + # The number of zeros to append is the shape of the input + # elementwise-subtracted by both the begin vector and sizes vector. + # + # Some more reshaping is needed to assemble this tensor with the + # right dimensions. + input_vec = op.inputs[0] + begin_vec = op.inputs[1] + input_rank = array_ops.rank(input_vec) + index_dtype = begin_vec.dtype + slice_size = array_ops.shape(op.outputs[0], out_type=index_dtype) + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + return gen_xla_ops.xla_dynamic_update_slice(array_ops.zeros_like(input_vec), + grad, begin_vec), None, None + + shape = array_ops_stack.stack([input_rank, 1]) + before_pad = array_ops.reshape(begin_vec, shape) + after_pad = array_ops.reshape( + array_ops.shape(input_vec, out_type=index_dtype) - slice_size - begin_vec, + shape) + paddings = array_ops.concat([before_pad, after_pad], 1) + return array_ops.pad(grad, paddings), None, None + + +@ops.RegisterGradient("StridedSlice") +def _StridedSliceGrad(op: ops.Operation, grad): + """Gradient for StridedSlice op.""" + begin = op.inputs[1] + end = op.inputs[2] + strides = op.inputs[3] + # StridedSliceGrad requires `x`, `begin`, `end` and `strides` to be of the + # same dtype so we build a shape of the same type as other args. + # Note that the choice of `begin` for specifying `out_type` is arbitrary. + # We could choose any of {begin|end|strides}.dtype since they are required to + # be the same. + x = array_ops.shape(op.inputs[0], out_type=begin.dtype) + + x_static = tensor_util.constant_value(x) + x = x_static if x_static is not None else x + begin_static = tensor_util.constant_value(begin) + begin = begin_static if begin_static is not None else begin + end_static = tensor_util.constant_value(end) + end = end_static if end_static is not None else end + strides_static = tensor_util.constant_value(strides) + strides = strides_static if strides_static is not None else strides + + return array_ops.strided_slice_grad( + x, + begin, + end, + strides, + grad, + begin_mask=op.get_attr("begin_mask"), + end_mask=op.get_attr("end_mask"), + ellipsis_mask=op.get_attr("ellipsis_mask"), + new_axis_mask=op.get_attr("new_axis_mask"), + shrink_axis_mask=op.get_attr("shrink_axis_mask")), None, None, None + + +@ops.RegisterGradient("StridedSliceGrad") +def _StridedSliceGradGrad(op: ops.Operation, grad): + """Gradient for StridedSliceGrad op.""" + begin = op.inputs[1] + end = op.inputs[2] + strides = op.inputs[3] + + return None, None, None, None, array_ops.strided_slice( + grad, + begin, + end, + strides, + begin_mask=op.get_attr("begin_mask"), + end_mask=op.get_attr("end_mask"), + ellipsis_mask=op.get_attr("ellipsis_mask"), + new_axis_mask=op.get_attr("new_axis_mask"), + shrink_axis_mask=op.get_attr("shrink_axis_mask")) + + +@ops.RegisterGradient("TensorStridedSliceUpdate") +def _TensorStridedSliceUpdateGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring + begin = op.inputs[1] + end = op.inputs[2] + strides = op.inputs[3] + begin_mask = op.get_attr("begin_mask") + end_mask = op.get_attr("end_mask") + ellipsis_mask = op.get_attr("ellipsis_mask") + new_axis_mask = op.get_attr("new_axis_mask") + shrink_axis_mask = op.get_attr("shrink_axis_mask") + def Apply(f, *args): + return f(*args, + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask) + dy = Apply(array_ops.strided_slice, + grad, begin, end, strides) + dx = Apply(array_ops.tensor_strided_slice_update, + grad, begin, end, strides, array_ops.zeros_like(dy)) + + # The value is potentially broadcast to the shape of the strided slice, so we + # may need to adjust dy. + slice_shape = array_ops.shape(dy, out_type=begin.dtype) + value_shape = array_ops.shape(op.inputs[4], out_type=slice_shape.dtype) + + _, reduction_axes = gen_array_ops.broadcast_gradient_args( + slice_shape, value_shape) + dy_reshaped = math_ops.reduce_sum(dy, axis=reduction_axes, keepdims=True) + dy = array_ops.reshape(dy_reshaped, value_shape) + + return dx, None, None, None, dy + + +@ops.RegisterGradient("Split") +def _SplitGrad(op: ops.Operation, *grads): + return None, array_ops.concat(list(grads), op.inputs[0]) + + +@ops.RegisterGradient("SplitV") +def _SplitVGrad(op: ops.Operation, *grads): + returnval = array_ops.concat(list(grads), op.inputs[2]) + returnval = [returnval] + [ + None, + ] * ( + len(op.inputs) - 1) + return returnval + + +ops.NotDifferentiable("Const") + + +@ops.RegisterGradient("Diag") +def _DiagGrad(_, grad): + return array_ops.diag_part(grad) + + +@ops.RegisterGradient("DiagPart") +def _DiagPartGrad(_, grad): + return array_ops.diag(grad) + + +@ops.RegisterGradient("MatrixDiag") +def _MatrixDiagGrad(_, grad): + return array_ops.matrix_diag_part(grad) + + +@ops.RegisterGradient("MatrixDiagV2") +def _MatrixDiagV2Grad(op: ops.Operation, grad): + return array_ops.matrix_diag_part( + grad, k=op.inputs[1]), None, None, None, None + + +@ops.RegisterGradient("MatrixDiagV3") +def _MatrixDiagV3Grad(op: ops.Operation, grad): + return array_ops.matrix_diag_part( + grad, k=op.inputs[1], align=op.get_attr("align")), None, None, None, None + + +@ops.RegisterGradient("MatrixDiagPart") +def _MatrixDiagPartGrad(op: ops.Operation, grad): + matrix_shape = op.inputs[0].get_shape()[-2:] + if matrix_shape.is_fully_defined() and matrix_shape[0] == matrix_shape[1]: + return array_ops.matrix_diag(grad) + else: + return array_ops.matrix_set_diag(array_ops.zeros_like(op.inputs[0]), grad) + + +@ops.RegisterGradient("MatrixDiagPartV2") +def _MatrixDiagPartV2Grad(op: ops.Operation, grad): + """Gradient for MatrixDiagPartV2.""" + matrix_shape = op.inputs[0].get_shape()[-2:] + if matrix_shape.is_fully_defined(): + return array_ops.matrix_diag( + grad, + k=op.inputs[1], + num_rows=matrix_shape[0], + num_cols=matrix_shape[1]), None, None + else: + return array_ops.matrix_set_diag( + array_ops.zeros_like(op.inputs[0]), grad, k=op.inputs[1]), None, None + + +@ops.RegisterGradient("MatrixDiagPartV3") +def _MatrixDiagPartV3Grad(op: ops.Operation, grad): + """Gradient for MatrixDiagPartV3.""" + matrix_shape = op.inputs[0].get_shape()[-2:] + align = op.get_attr("align") + if matrix_shape.is_fully_defined(): + return array_ops.matrix_diag( + grad, + k=op.inputs[1], + num_rows=matrix_shape[0], + num_cols=matrix_shape[1], + align=align), None, None + else: + return array_ops.matrix_set_diag( + array_ops.zeros_like(op.inputs[0]), grad, k=op.inputs[1], + align=align), None, None + + +@ops.RegisterGradient("MatrixSetDiag") +def _MatrixSetDiagGrad(op: ops.Operation, grad): + """Gradient for MatrixSetDiag.""" + input_shape = op.inputs[0].get_shape().merge_with(grad.get_shape()) + diag_shape = op.inputs[1].get_shape() + batch_shape = input_shape[:-2].merge_with(diag_shape[:-1]) + matrix_shape = input_shape[-2:] + if batch_shape.is_fully_defined() and matrix_shape.is_fully_defined(): + diag_shape = batch_shape.as_list() + [min(matrix_shape.as_list())] + else: + with ops.colocate_with(grad): + grad_shape = array_ops.shape(grad) + grad_rank = array_ops.rank(grad) + batch_shape = array_ops.slice(grad_shape, [0], [grad_rank - 2]) + matrix_shape = array_ops.slice(grad_shape, [grad_rank - 2], [2]) + min_dim = math_ops.reduce_min(matrix_shape) + diag_shape = array_ops.concat([batch_shape, [min_dim]], 0) + grad_input = array_ops.matrix_set_diag( + grad, array_ops.zeros(diag_shape, dtype=grad.dtype)) + grad_diag = array_ops.matrix_diag_part(grad) + return (grad_input, grad_diag) + + +@ops.RegisterGradient("MatrixSetDiagV2") +def _MatrixSetDiagGradV2(op: ops.Operation, grad): + """Gradient for MatrixSetDiagV2.""" + diag_shape = op.inputs[1].get_shape() + if not diag_shape.is_fully_defined(): + # Need to know the values of `d_lower` and `d_upper` to infer diag_shape. + grad_shape = array_ops.shape(grad) + batch_shape = grad_shape[:-2] + matrix_shape = grad_shape[-2:] + diag_index = array_ops.reshape(op.inputs[2], [-1]) # Converts to vector. + d_lower = diag_index[0] + d_upper = diag_index[-1] # Works both when len(diag_index) is 1 and 2. + y_offset = cond.cond( + math_ops.less(d_upper, 0), lambda: d_upper, lambda: 0) + x_offset = cond.cond( + math_ops.greater(d_lower, 0), lambda: -d_lower, lambda: 0) + + max_diag_len = math_ops.minimum(matrix_shape[0] + y_offset, + matrix_shape[1] + x_offset) + # pylint: disable=g-long-lambda + # pyformat: disable + postfix = cond.cond( + math_ops.equal(d_lower, d_upper), + lambda: ops.convert_to_tensor([max_diag_len]), + lambda: ops.convert_to_tensor([d_upper - d_lower + 1, + max_diag_len])) + # pyformat: enable + # pylint: enable=g-long-lambda + diag_shape = array_ops.concat([batch_shape, postfix], 0) + + grad_input = array_ops.matrix_set_diag( + grad, array_ops.zeros(diag_shape, dtype=grad.dtype), k=op.inputs[2]) + grad_diag = array_ops.matrix_diag_part(grad, k=op.inputs[2]) + return (grad_input, grad_diag, None) + + +@ops.RegisterGradient("MatrixSetDiagV3") +def _MatrixSetDiagGradV3(op: ops.Operation, grad): + """Gradient for MatrixSetDiagV3.""" + diag_shape = op.inputs[1].get_shape() + align = op.get_attr("align") + if not diag_shape.is_fully_defined(): + # Need to know the values of `d_lower` and `d_upper` to infer diag_shape. + grad_shape = array_ops.shape(grad) + batch_shape = grad_shape[:-2] + matrix_shape = grad_shape[-2:] + diag_index = array_ops.reshape(op.inputs[2], [-1]) # Converts to vector. + d_lower = diag_index[0] + d_upper = diag_index[-1] # Works both when len(diag_index) is 1 and 2. + y_offset = cond.cond( + math_ops.less(d_upper, 0), lambda: d_upper, lambda: 0) + x_offset = cond.cond( + math_ops.greater(d_lower, 0), lambda: -d_lower, lambda: 0) + + max_diag_len = math_ops.minimum(matrix_shape[0] + y_offset, + matrix_shape[1] + x_offset) + # pylint: disable=g-long-lambda + # pyformat: disable + postfix = cond.cond( + math_ops.equal(d_lower, d_upper), + lambda: ops.convert_to_tensor([max_diag_len]), + lambda: ops.convert_to_tensor([d_upper - d_lower + 1, + max_diag_len])) + # pyformat: enable + # pylint: enable=g-long-lambda + diag_shape = array_ops.concat([batch_shape, postfix], 0) + + grad_input = array_ops.matrix_set_diag( + grad, + array_ops.zeros(diag_shape, dtype=grad.dtype), + k=op.inputs[2], + align=align) + grad_diag = array_ops.matrix_diag_part(grad, k=op.inputs[2], align=align) + return (grad_input, grad_diag, None) + + +@ops.RegisterGradient("MatrixBandPart") +def _MatrixBandPartGrad(op: ops.Operation, grad): + num_lower = op.inputs[1] + num_upper = op.inputs[2] + return (array_ops.matrix_band_part(grad, num_lower, num_upper), None, None) + + +# Edit Distance has no gradient (but can be used to eval seq2seq or CTC). +ops.NotDifferentiable("EditDistance") + + +@ops.RegisterGradient("Fill") +def _FillGrad(_, grad): + return None, math_ops.reduce_sum(grad) + + +ops.NotDifferentiable("ZerosLike") +ops.NotDifferentiable("OnesLike") + + +@ops.RegisterGradient("PreventGradient") +def _PreventGradientGrad(op: ops.Operation, _): + raise LookupError("Gradient explicitly disabled. Reason: %s" % + op.get_attr("message")) + + +def _IndexedSlicesToTensorNoWarning(indexed_slices): + """Converts an IndexedSlices to a Tensor without sparse->dense warnings.""" + if not isinstance(indexed_slices, indexed_slices_lib.IndexedSlices): + # If it is not IndexedSlices, it's better be a tensor. + return indexed_slices + if indexed_slices.dense_shape is None: + raise ValueError( + "Tensor conversion requested for IndexedSlices without dense_shape: %s" + % str(indexed_slices)) + return math_ops.unsorted_segment_sum(indexed_slices.values, + indexed_slices.indices, + indexed_slices.dense_shape[0]) + + +@ops.RegisterGradient("Gather") +def _GatherGrad(op: ops.Operation, grad): + """Gradient for Gather op.""" + # params can be large, so colocate the shape calculation with it. + params = op.inputs[0] + with ops.colocate_with(params): + params_shape = array_ops.shape(params) + + # Build appropriately shaped IndexedSlices + indices = op.inputs[1] + size = array_ops.expand_dims(array_ops.size(indices), 0) + values_shape = array_ops.concat([size, params_shape[1:]], 0) + values = array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), values_shape) + indices = array_ops.reshape(indices, size) + return [indexed_slices_lib.IndexedSlices(values, indices, params_shape), None] + + +def _GetBatchIndices(params_shape, indices, batch_dims): + """Addds the batch offsets to the given indices and returns the results.""" + batch_indices = indices + indices_dtype = indices.dtype.base_dtype + casted_params_shape = math_ops.cast(params_shape, indices_dtype) + accum_dim_value = array_ops.ones((), dtype=indices_dtype) + for dim in range(batch_dims, 0, -1): + dim_value = casted_params_shape[dim - 1] + accum_dim_value *= casted_params_shape[dim] + start = array_ops.zeros((), dtype=indices_dtype) + step = array_ops.ones((), dtype=indices_dtype) + dim_indices = math_ops.range(start, dim_value, step) + dim_indices *= accum_dim_value + dim_shape = array_ops.concat([ + array_ops.tile([1], [dim - 1]), [dim_value], + array_ops.tile([1], [array_ops.rank(indices) - dim]) + ], axis=0) + batch_indices += array_ops.reshape(dim_indices, dim_shape) + + return batch_indices + + +def _BatchGatherGrad(params_shape, values, indices, batch_dims, + gather_dim_size): + """Returns the gradient of GatherV2 with batch dimensions.""" + + # Axis is the first non-batch dimension. + indices_size = array_ops.expand_dims(array_ops.size(indices), 0) + if batch_dims: + values_shape = array_ops.shape(values) + # Add the batch offsets to indices and flatten the batch dimensions. + outer_shape = values_shape[:batch_dims] + inner_shape = values_shape[batch_dims:][1:] + batch_size = gen_math_ops.prod(outer_shape, [0], False) + flat_values_shape = array_ops.concat([[-1], inner_shape], 0) + gather_dim_size *= batch_size + + indices = _GetBatchIndices(params_shape, indices, batch_dims) + values = array_ops.reshape( + _IndexedSlicesToTensorNoWarning(values), flat_values_shape) + + indices = array_ops.reshape(indices, indices_size) + params_grad = math_ops.unsorted_segment_sum(values, indices, gather_dim_size) + + if batch_dims: + # Put back the batch dimensions. + params_grad = array_ops.reshape( + params_grad, array_ops.concat([outer_shape, flat_values_shape], 0)) + + return params_grad + + +@ops.RegisterGradient("GatherV2") +def _GatherV2Grad(op: ops.Operation, grad): + """Gradient for GatherV2 op.""" + # params can be large, so colocate the shape calculation with it. + # + # params can be very large for sparse model, array_ops.shape raises + # exception on the Windows platform when any dimension is larger than + # int32. params_shape is not used in optimizer apply_sparse gradients, + # so it's fine to convert it back to int32 regardless of truncation. + params = op.inputs[0] + with ops.colocate_with(params): + params_shape = array_ops.shape(params, out_type=ops.dtypes.int64) + params_shape = math_ops.cast(params_shape, dtypes.int32) + + indices = op.inputs[1] + indices_size = array_ops.expand_dims(array_ops.size(indices), 0) + axis = op.inputs[2] + axis_static = tensor_util.constant_value(axis) + batch_dims = int(op.get_attr("batch_dims")) + + if batch_dims < 0: + if indices.shape.ndims is None: + raise ValueError( + f"Currently, it is unsupported to take the gradient of tf.gather " + f"when batch_dims < 0 and the rank of the indices is unknown. Please " + f"pass a positive batch_dims or use tf.ensure_shape to update the " + f"shape of indices when calling tf.gather. Got " + f"batch_dims={batch_dims} and indices={indices}") + batch_dims += indices.shape.ndims + + # For axis 0 gathers, build an appropriately shaped IndexedSlices. + if axis_static == 0: + if context.executing_eagerly(): + with ops.device(indices_size.device): + params_tail_shape = array_ops.identity(params_shape)[1:] + else: + params_tail_shape = params_shape[1:] + values_shape = array_ops.concat([indices_size, params_tail_shape], 0) + values = array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), values_shape) + indices = array_ops.reshape(indices, indices_size) + params_grad = indexed_slices_lib.IndexedSlices(values, indices, + params_shape) + else: + # Handle axis by transposing the axis dimension to be the first non-batch + # dimension, compute the gradient and transpose the result back. + outer_shape = params_shape[:axis] + inner_shape = params_shape[axis:][1:] + values_shape = array_ops.concat([outer_shape, [-1], inner_shape], 0) + + values_dims = array_ops.size(values_shape) + axis_dims = array_ops.size(outer_shape) + + outer_batches_indices = math_ops.range(batch_dims) + batch_axis_indices = math_ops.range(batch_dims, axis_dims) + inner_axes_indices = math_ops.range(axis_dims + 1, values_dims) + + values = array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), values_shape) + + # Move values[axis] up to values[batch_dims] + transpose_dims = array_ops.concat([ + outer_batches_indices, [axis_dims], batch_axis_indices, + inner_axes_indices + ], 0) + values_transpose = array_ops.transpose(values, transpose_dims) + params_shape_transpose = array_ops.gather(params_shape, transpose_dims) + + params_grad = _BatchGatherGrad(params_shape_transpose, values_transpose, + indices, batch_dims, params_shape[axis]) + + # Inverts the above transpose by moving dimension batch_dims back to its + # original position. + invert_transpose_dims = array_ops.concat([ + outer_batches_indices, batch_axis_indices + 1, [batch_dims], + inner_axes_indices + ], 0) + params_grad = array_ops.transpose(params_grad, invert_transpose_dims) + + return [params_grad, None, None] + + +@ops.RegisterGradient("GatherNd") +def _GatherNdGrad(op: ops.Operation, grad): + ref = op.inputs[0] + indices = op.inputs[1] + ref_shape = array_ops.shape(ref, out_type=indices.dtype) + if indices.shape.ndims == 2 and indices.shape.dims[-1].value == 1: + ref_grad = indexed_slices_lib.IndexedSlices( + grad, array_ops.squeeze(indices, axis=-1), ref_shape) + else: + ref_grad = array_ops.scatter_nd(indices, grad, ref_shape) + return [ref_grad, None] + + +@ops.RegisterGradient("ResourceGatherNd") +def _ResourceGatherNdGrad(op: ops.Operation, grad): # pylint: disable=missing-docstring + ref = op.inputs[0] + indices = op.inputs[1] + ref_shape = gen_resource_variable_ops.variable_shape(ref, indices.dtype) + if indices.shape.ndims == 2 and indices.shape.dims[-1].value == 1: + ref_grad = indexed_slices_lib.IndexedSlices( + grad, array_ops.squeeze(indices, axis=-1), ref_shape) + else: + ref_grad = array_ops.scatter_nd(indices, grad, ref_shape) + return [ref_grad, None] + + +@ops.RegisterGradient("CheckNumerics") +def _CheckNumericsGrad(op: ops.Operation, grad): + """Gradient for check_numerics op.""" + return array_ops.check_numerics( + grad, + "Not a number (NaN) or infinity (Inf) values detected in gradient. %s" % + op.get_attr("message")) + + +@ops.RegisterGradient("CheckNumericsV2") +def _CheckNumericsV2Grad(op: ops.Operation, grad): + """Gradient for check_numerics op.""" + return array_ops.check_numerics_v2( + grad, + "Not a number (NaN) or infinity (Inf) values detected in gradient. %s" % + op.get_attr("message")) + + +@ops.RegisterGradient("PlaceholderWithDefault") +@ops.RegisterGradient("Identity") +def _IdGrad(_, grad): + return grad + + +@ops.RegisterGradient("_EagerConst") +def _EagerConstGrad(_, grad): + raise AssertionError( + "This op should never interact with gradient APIs. Please file a bug.") + + +@ops.RegisterGradient("RefIdentity") +def _RefIdGrad(_, grad): + return grad + + +@ops.RegisterGradient("IdentityN") +def _IdNGrad(_, *grad): + return grad + + +ops.NotDifferentiable("StopGradient") + + +@ops.RegisterGradient("Reshape") +def _ReshapeGrad(op: ops.Operation, grad): + return [ + array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), array_ops.shape(op.inputs[0])), + None + ] + + +ops.NotDifferentiable("InvertPermutation") + + +def _ReshapeToInput(op: ops.Operation, grad): + """Reshapes the gradient to the shape of the original input.""" + return array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), array_ops.shape(op.inputs[0])) + + +@ops.RegisterGradient("ExpandDims") +def _ExpandDimsGrad(op: ops.Operation, grad): + return [_ReshapeToInput(op, grad), None] + + +@ops.RegisterGradient("Squeeze") +def _SqueezeGrad(op: ops.Operation, grad): + return _ReshapeToInput(op, grad) + + +@ops.RegisterGradient("Transpose") +def _TransposeGrad(op: ops.Operation, grad): + """Returns unshuffle(grad).""" + p = op.inputs[1] + return [array_ops.transpose(grad, array_ops.invert_permutation(p)), None] + + +@ops.RegisterGradient("ConjugateTranspose") +def _ConjugateTransposeGrad(op: ops.Operation, grad): + """Returns conj(unshuffle(grad)).""" + p = op.inputs[1] + return [ + array_ops.transpose( + grad, array_ops.invert_permutation(p), conjugate=True), None + ] + + +ops.NotDifferentiable("Shape") + +ops.NotDifferentiable("ShapeN") + +ops.NotDifferentiable("Rank") + +ops.NotDifferentiable("Size") + + +@ops.RegisterGradient("Tile") +def _TileGrad(op: ops.Operation, grad): + """Sum reduces grad along the tiled dimensions.""" + input_shape = array_ops.shape(op.inputs[0], out_type=op.inputs[1].dtype) + # We interleave multiples and input_shape to get split_shape, + # reshape grad to split_shape, and reduce along all even + # dimensions (the tiled dimensions) to get the result + # with shape input_shape. For example + # input_shape = [20, 30, 40] + # multiples = [2, 3, 4] + # split_shape = [2, 20, 3, 30, 4, 40] + # axes = [0, 2, 4] + split_shape = array_ops.reshape( + array_ops.transpose(array_ops_stack.stack([op.inputs[1], input_shape])), + [-1]) + axes = math_ops.range(0, array_ops.size(split_shape), 2) + # Sum reduces grad along the first dimension for IndexedSlices + if isinstance(grad, indexed_slices_lib.IndexedSlices): + input_shape_0 = math_ops.cast(input_shape[0], grad.indices.dtype) + grad = math_ops.unsorted_segment_sum( + grad.values, math_ops.mod(grad.indices, input_shape_0), input_shape_0) + split_shape = array_ops.concat([[1], split_shape[1:]], axis=0) + input_grad = math_ops.reduce_sum(array_ops.reshape(grad, split_shape), axes) + # Fix shape inference + if not context.executing_eagerly(): + input_grad.set_shape(op.inputs[0].get_shape()) + return [input_grad, None] + + +ops.NotDifferentiable("BroadcastGradientArgs") + + +def _PadGrad(op: ops.Operation, grad): + """Gradient for Pad.""" + # Pad introduces values around the original tensor, so the gradient function + # slices the original shape out of the gradient.""" + x = op.inputs[0] + a = op.inputs[1] # [Rank(x), 2] + # Takes a slice of a. The 1st column. [Rank(x), 1]. + pad_before = array_ops.slice(a, [0, 0], + array_ops_stack.stack([array_ops.rank(x), 1])) + # Make it a 1-D tensor. + begin = array_ops.reshape(pad_before, [-1]) + sizes = array_ops.shape(x, out_type=begin.dtype) + x_grad = array_ops.slice(grad, begin, sizes) + if len(op.inputs) == 3: + return x_grad, None, None + else: + return x_grad, None + + +ops.RegisterGradient("Pad")(_PadGrad) +ops.RegisterGradient("PadV2")(_PadGrad) + + +# ReverseSequence is just a permutation. The gradient permutes back. +@ops.RegisterGradient("ReverseSequence") +def _ReverseSequenceGrad(op: ops.Operation, grad): + seq_lengths = op.inputs[1] + return [ + array_ops.reverse_sequence( + grad, + batch_axis=op.get_attr("batch_dim"), + seq_axis=op.get_attr("seq_dim"), + seq_lengths=seq_lengths), None + ] + + +@ops.RegisterGradient("Reverse") +def _ReverseGrad(op: ops.Operation, grad): + reverse_dims = op.inputs[1] + return gen_array_ops.reverse(grad, reverse_dims), None + + +@ops.RegisterGradient("ReverseV2") +def _ReverseV2Grad(op: ops.Operation, grad): + axis = op.inputs[1] + return array_ops.reverse_v2(grad, axis), None + + +@ops.RegisterGradient("SpaceToBatch") +def _SpaceToBatchGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: BatchToSpace. + block_size = op.get_attr("block_size") + return [ + array_ops.batch_to_space(grad, op.inputs[1], block_size=block_size), None + ] + + +@ops.RegisterGradient("SpaceToBatchND") +def _SpaceToBatchNDGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: BatchToSpaceND. + return [ + array_ops.batch_to_space_nd(grad, op.inputs[1], op.inputs[2]), None, None + ] + + +@ops.RegisterGradient("BatchToSpace") +def _BatchToSpaceGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: SpaceToBatch. + block_size = op.get_attr("block_size") + return [ + array_ops.space_to_batch(grad, op.inputs[1], block_size=block_size), None + ] + + +@ops.RegisterGradient("BatchToSpaceND") +def _BatchToSpaceNDGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: SpaceToBatchND. + return [ + array_ops.space_to_batch_nd(grad, op.inputs[1], op.inputs[2]), None, None + ] + + +@ops.RegisterGradient("SpaceToDepth") +def _SpaceToDepthGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: DepthToSpace. + block_size = op.get_attr("block_size") + data_format = op.get_attr("data_format") + if data_format == "NCHW_VECT_C": + raise ValueError("Cannot compute SpaceToDepth gradient with NCHW_VECT_C. " + "NCHW_VECT_C requires qint8 data type.") + return array_ops.depth_to_space(grad, block_size, data_format=data_format) + + +@ops.RegisterGradient("DepthToSpace") +def _DepthToSpaceGrad(op: ops.Operation, grad): + # Its gradient is the opposite op: SpaceToDepth. + block_size = op.get_attr("block_size") + data_format = op.get_attr("data_format") + if data_format == "NCHW_VECT_C": + raise ValueError("Cannot compute DepthToSpace gradient with NCHW_VECT_C. " + "NCHW_VECT_C requires qint8 data type.") + return array_ops.space_to_depth(grad, block_size, data_format=data_format) + + +ops.NotDifferentiable("OneHot") + + +@ops.RegisterGradient("MirrorPad") +def _MirrorPadGrad(op: ops.Operation, grad): + mode = op.get_attr("mode") + return [gen_array_ops.mirror_pad_grad(grad, op.inputs[1], mode=mode), None] + + +@ops.RegisterGradient("MirrorPadGrad") +def _MirrorPadGradGrad(op: ops.Operation, grad): + mode = op.get_attr("mode") + return [gen_array_ops.mirror_pad(grad, op.inputs[1], mode=mode), None] + + +@ops.RegisterGradient("QuantizeAndDequantize") +def _QuantizeAndDequantizeGrad(_, grad): + return grad + + +@ops.RegisterGradient("QuantizeAndDequantizeV2") +def _QuantizeAndDequantizeV2Grad(_, grad): + return [grad, None, None] + + +@ops.RegisterGradient("QuantizeAndDequantizeV3") +def _QuantizeAndDequantizeV3Grad(_, grad): + # Only propagate the gradient for the unquantized input. + return [grad, None, None, None] + + +@ops.RegisterGradient("ExtractImagePatches") +def _ExtractImagePatchesGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring + input_bhwc = array_ops.shape(op.inputs[0], out_type=dtypes.int64) + batch_size, rows_in, cols_in, channels = array_ops_stack.unstack(input_bhwc) + + output_bhwc = array_ops.shape(op.outputs[0], out_type=dtypes.int64) + rows_out, cols_out = array_ops_stack.unstack(output_bhwc[1:3]) + + _, ksize_r, ksize_c, _ = op.get_attr("ksizes") + + # Create indices matrix for input tensor. + # Note that 0 is preserved for padding location, + # so indices for input start from 1 to 1 + rows_in * cols_in. + input_indices_num = rows_in * cols_in + # XLA version of extract_image_patches does not support int64, + # using float32 instead. + input_idx = array_ops.reshape( + math_ops.range(1, input_indices_num + 1, dtype=ops.dtypes.float32), + (1, rows_in, cols_in, 1), + ) + input_idx_patched = gen_array_ops.extract_image_patches( + input_idx, op.get_attr("ksizes"), op.get_attr("strides"), + op.get_attr("rates"), op.get_attr("padding")) + input_idx_patched = math_ops.cast(input_idx_patched, dtypes.int64) + + grad_expanded = array_ops.transpose( + array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), + (batch_size, rows_out, cols_out, ksize_r, ksize_c, channels)), + (1, 2, 3, 4, 0, 5)) + grad_flat = array_ops.reshape(grad_expanded, (-1, batch_size * channels)) + + # Shift all input indices back. Padding locations will have "-1" value + # which is fortunately ignored by segmented sum. + segment_ids = array_ops.reshape(input_idx_patched, [-1]) - 1 + grad_out = math_ops.unsorted_segment_sum( + grad_flat, segment_ids, num_segments=input_indices_num + ) + + grad_out = array_ops.reshape( + grad_out, (rows_in, cols_in, batch_size, channels) + ) + grad_out = array_ops.transpose(grad_out, (2, 0, 1, 3)) + + return [grad_out] + + +@ops.RegisterGradient("ExtractVolumePatches") +def _ExtractVolumePatchesGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring + batch_size, planes_in, rows_in, cols_in, channels = [ + dim.value for dim in op.inputs[0].shape.dims + ] + input_bphwc = array_ops.shape(op.inputs[0]) + batch_size = input_bphwc[0] + channels = input_bphwc[4] + + # Create indices matrix for input tensor. + # Note that 0 is preserved for padding location, + # so indices for input start from 1 to 1 + rows_in * cols_in. + input_indices_num = 1 + planes_in * rows_in * cols_in + input_idx = array_ops.reshape( + math_ops.range(1, input_indices_num, dtype=ops.dtypes.int64), + (1, planes_in, rows_in, cols_in, 1)) + input_idx_patched = gen_array_ops.extract_volume_patches( + input_idx, op.get_attr("ksizes"), op.get_attr("strides"), + op.get_attr("padding")) + + # Create indices matrix for output tensor. + _, planes_out, rows_out, cols_out, _ = [ + dim.value for dim in op.outputs[0].shape.dims + ] + _, ksize_p, ksize_r, ksize_c, _ = op.get_attr("ksizes") + # Indices for output start from 0. + prc_indices_num = planes_out * rows_out * cols_out + output_indices_num = prc_indices_num * ksize_p * ksize_r * ksize_c + output_idx = array_ops.reshape( + math_ops.range(output_indices_num, dtype=ops.dtypes.int64), + (1, planes_out, rows_out, cols_out, ksize_p * ksize_r * ksize_c)) + + # Construct mapping table for indices: (input -> output). + idx_matrix = array_ops.concat([ + array_ops.expand_dims(input_idx_patched, axis=-1), + array_ops.expand_dims(output_idx, axis=-1) + ], + axis=-1) + idx_map = array_ops.reshape(idx_matrix, (-1, 2)) + + sp_shape = (input_indices_num, output_indices_num) + sp_mat_full = sparse_tensor.SparseTensor( + idx_map, array_ops.ones([output_indices_num], dtype=grad.dtype), sp_shape) + # Remove all padding locations [0, :]. + sp_mat = sparse_ops.sparse_slice(sp_mat_full, (1, 0), + (input_indices_num - 1, output_indices_num)) + + grad_expanded = array_ops.transpose( + array_ops.reshape( + _IndexedSlicesToTensorNoWarning(grad), + (batch_size, planes_out, rows_out, cols_out, ksize_p, ksize_r, + ksize_c, channels)), (1, 2, 3, 4, 5, 6, 0, 7)) + grad_flat = array_ops.reshape(grad_expanded, (-1, batch_size * channels)) + + jac = sparse_ops.sparse_tensor_dense_matmul(sp_mat, grad_flat) + + grad_out = array_ops.reshape( + jac, (planes_in, rows_in, cols_in, batch_size, channels)) + grad_out = array_ops.transpose(grad_out, (3, 0, 1, 2, 4)) + + return [grad_out] + + +@ops.RegisterGradient("ScatterNd") +def _ScatterNdGrad(op: ops.Operation, grad): + indices = op.inputs[0] + updates_grad = array_ops.gather_nd(grad, indices) + return [None, updates_grad, None] + + +@ops.RegisterGradient("TensorScatterUpdate") +def _TensorScatterUpdateGrad(op: ops.Operation, grad): + indices = op.inputs[1] + updates_grad = array_ops.gather_nd(grad, indices) + tensor_grad = array_ops.tensor_scatter_update( + array_ops.identity(grad), indices, + array_ops.zeros_like(op.inputs[2], dtype=grad.dtype)) + return [tensor_grad, None, updates_grad] + + +@ops.RegisterGradient("TensorScatterAdd") +def _TensorScatterAddGrad(op: ops.Operation, grad): + indices = op.inputs[1] + updates_grad = array_ops.gather_nd(grad, indices) + tensor_grad = array_ops.identity(grad) + return [tensor_grad, None, updates_grad] + + +def _TensorScatterMinOrMaxGrad(op: ops.Operation, grad): + """Gradient for TensorScatterMin and TensorScatterMax.""" + indices = op.inputs[1] + x = op.inputs[0] + y = op.inputs[2] + output = op.outputs[0] + x_indicators = math_ops.cast(math_ops.equal(x, output), grad.dtype) + y_output = array_ops.gather_nd(output, indices) + y_indicators = math_ops.cast(math_ops.equal(y, y_output), grad.dtype) + ys_indicators = array_ops.scatter_nd( + indices, y_indicators, array_ops.shape(x, out_type=indices.dtype)) + indicators = x_indicators + ys_indicators # All elements are >= 1. + # If there are multiple minimum or maximum elements then the gradient will be + # divided between them. + x_grad = grad * x_indicators / indicators + y_grad = array_ops.gather_nd(grad / indicators, indices) * y_indicators + return [x_grad, None, y_grad] + + +@ops.RegisterGradient("TensorScatterMax") +def _TensorScatterMaxGrad(op: ops.Operation, grad): + """Gradient for TensorScatterMax op.""" + return _TensorScatterMinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("TensorScatterMin") +def _TensorScatterMinGrad(op: ops.Operation, grad): + """Gradient for TensorScatterMin op.""" + return _TensorScatterMinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("TensorScatterSub") +def _TensorScatterSubGrad(op: ops.Operation, grad): + indices = op.inputs[1] + updates_grad = array_ops.gather_nd(grad, indices) + tensor_grad = array_ops.identity(grad) + return [tensor_grad, None, -updates_grad] + + +@ops.RegisterGradient("ScatterNdNonAliasingAdd") +def _ScatterNdNonAliasingAddGrad(op: ops.Operation, grad): + indices = op.inputs[1] + updates_grad = array_ops.gather_nd(grad, indices) + return [grad, None, updates_grad] + + +@ops.RegisterGradient("BroadcastTo") +def _BroadcastToGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring + input_value = op.inputs[0] + broadcast_shape = op.inputs[1] + shape_dtype = dtypes.int32 + if isinstance(broadcast_shape, tensor.Tensor): + shape_dtype = broadcast_shape.dtype + + input_value_shape = array_ops.shape(input_value, out_type=shape_dtype) + if not isinstance(broadcast_shape, ops.EagerTensor): + broadcast_shape_static = tensor_shape.TensorShape( + tensor_util.try_evaluate_constant(broadcast_shape)) + if broadcast_shape_static.is_fully_defined(): + broadcast_shape = constant_op.constant( + broadcast_shape_static.as_list(), dtype=shape_dtype) + _, reduction_axes = gen_array_ops.broadcast_gradient_args( + broadcast_shape, input_value_shape) + updates_grad_reshaped = math_ops.reduce_sum( + grad, axis=reduction_axes, keepdims=True) + updates_grad = array_ops.reshape(updates_grad_reshaped, input_value_shape) + return [updates_grad, None] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2eedaaadb58995744b260bb453d792ea3207db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops.py @@ -0,0 +1,6982 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# Tests for this file live in python/kernel_tests/array_ops_test.py +"""Support for manipulating tensors.""" + +import numbers +import numpy as np + +from tensorflow.core.config import flags +from tensorflow.dtensor.python import api as d_api +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +# 'Constant' gets imported in the module 'array_ops'. +from tensorflow.python.framework.constant_op import constant +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import shape_util +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_array_ops import * +from tensorflow.python.ops.gen_array_ops import reverse_v2 as reverse # pylint: disable=unused-import +from tensorflow.python.types import core +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import tf_export +# pylint: enable=wildcard-import + +# Used for slicing to specify a new 1 size dimension +newaxis = None +tf_export("newaxis").export_constant(__name__, "newaxis") + +# We override the 'slice' for the "slice" op, so we keep Python's +# existing 'slice' for later use in this module. +_BaseSlice = slice + + +@tf_export("reshape", v1=["reshape", "manip.reshape"]) +@dispatch.add_dispatch_support +def reshape(tensor, shape, name=None): # pylint: disable=redefined-outer-name + r"""Reshapes a tensor. + + Given `tensor`, this operation returns a new `tf.Tensor` that has the same + values as `tensor` in the same order, except with a new shape given by + `shape`. + + >>> t1 = [[1, 2, 3], + ... [4, 5, 6]] + >>> print(tf.shape(t1).numpy()) + [2 3] + >>> t2 = tf.reshape(t1, [6]) + >>> t2 + + >>> tf.reshape(t2, [3, 2]) + + + The `tf.reshape` does not change the order of or the total number of elements + in the tensor, and so it can reuse the underlying data buffer. This makes it + a fast operation independent of how big of a tensor it is operating on. + + >>> tf.reshape([1, 2, 3], [2, 2]) + Traceback (most recent call last): + ... + InvalidArgumentError: Input to reshape is a tensor with 3 values, but the + requested shape has 4 + + To instead reorder the data to rearrange the dimensions of a tensor, see + `tf.transpose`. + + >>> t = [[1, 2, 3], + ... [4, 5, 6]] + >>> tf.reshape(t, [3, 2]).numpy() + array([[1, 2], + [3, 4], + [5, 6]], dtype=int32) + >>> tf.transpose(t, perm=[1, 0]).numpy() + array([[1, 4], + [2, 5], + [3, 6]], dtype=int32) + + If one component of `shape` is the special value -1, the size of that + dimension is computed so that the total size remains constant. In particular, + a `shape` of `[-1]` flattens into 1-D. At most one component of `shape` can + be -1. + + >>> t = [[1, 2, 3], + ... [4, 5, 6]] + >>> tf.reshape(t, [-1]) + + >>> tf.reshape(t, [3, -1]) + + >>> tf.reshape(t, [-1, 2]) + + + `tf.reshape(t, [])` reshapes a tensor `t` with one element to a scalar. + + >>> tf.reshape([7], []).numpy() + 7 + + More examples: + + >>> t = [1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> print(tf.shape(t).numpy()) + [9] + >>> tf.reshape(t, [3, 3]) + + + >>> t = [[[1, 1], [2, 2]], + ... [[3, 3], [4, 4]]] + >>> print(tf.shape(t).numpy()) + [2 2 2] + >>> tf.reshape(t, [2, 4]) + + + >>> t = [[[1, 1, 1], + ... [2, 2, 2]], + ... [[3, 3, 3], + ... [4, 4, 4]], + ... [[5, 5, 5], + ... [6, 6, 6]]] + >>> print(tf.shape(t).numpy()) + [3 2 3] + >>> # Pass '[-1]' to flatten 't'. + >>> tf.reshape(t, [-1]) + + >>> # -- Using -1 to infer the shape -- + >>> # Here -1 is inferred to be 9: + >>> tf.reshape(t, [2, -1]) + + >>> # -1 is inferred to be 2: + >>> tf.reshape(t, [-1, 9]) + + >>> # -1 is inferred to be 3: + >>> tf.reshape(t, [ 2, -1, 3]) + + + Args: + tensor: A `Tensor`. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Defines the shape of the output tensor. + name: Optional string. A name for the operation. + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + result = gen_array_ops.reshape(tensor, shape, name) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("fill") +@dispatch.add_dispatch_support +def fill(dims, value, name=None, layout=None): + r"""Creates a tensor filled with a scalar value. + + See also `tf.ones`, `tf.zeros`, `tf.one_hot`, `tf.eye`. + + This operation creates a tensor of shape `dims` and fills it with `value`. + + For example: + + >>> tf.fill([2, 3], 9) + + + `tf.fill` evaluates at graph runtime and supports dynamic shapes based on + other runtime `tf.Tensors`, unlike `tf.constant(value, shape=dims)`, which + embeds the value as a `Const` node. + + Args: + dims: A 1-D sequence of non-negative numbers. Represents the shape of the + output `tf.Tensor`. Entries should be of type: `int32`, `int64`. + value: A value to fill the returned `tf.Tensor`. + name: Optional string. The name of the output `tf.Tensor`. + layout: Optional, `tf.experimental.dtensor.Layout`. If provided, the result + is a [DTensor](https://www.tensorflow.org/guide/dtensor_overview) with the + provided layout. + + Returns: + A `tf.Tensor` with shape `dims` and the same dtype as `value`. + + Raises: + InvalidArgumentError: `dims` contains negative entries. + NotFoundError: `dims` contains non-integer entries. + + @compatibility(numpy) + Similar to `np.full`. In `numpy`, more parameters are supported. Passing a + number argument as the shape (`np.full(5, value)`) is valid in `numpy` for + specifying a 1-D shaped result, while TensorFlow does not support this syntax. + @end_compatibility + """ + result = d_api.call_with_layout( + gen_array_ops.fill, layout=layout, dims=dims, value=value, name=name + ) + shape_util.maybe_set_static_shape(result, dims) + return result + + +@tf_export("identity") +@dispatch.add_dispatch_support +def identity(input, name=None): # pylint: disable=redefined-builtin + r"""Return a Tensor with the same shape and contents as input. + + The return value is not the same Tensor as the original, but contains the same + values. This operation is fast when used on the same device. + + For example: + + >>> a = tf.constant([0.78]) + >>> a_identity = tf.identity(a) + >>> a.numpy() + array([0.78], dtype=float32) + >>> a_identity.numpy() + array([0.78], dtype=float32) + + Calling `tf.identity` on a variable will make a Tensor that represents the + value of that variable at the time it is called. This is equivalent to calling + `.read_value()`. + + >>> a = tf.Variable(5) + >>> a_identity = tf.identity(a) + >>> a.assign_add(1) + + >>> a.numpy() + 6 + >>> a_identity.numpy() + 5 + + This function can also be used to explicitly transfer tensors between devices. + For example, to transfer a tensor in GPU memory back to host memory, one can + use: + + >>> with tf.device("/gpu:0"): + ... x_on_gpu = tf.constant(1) + >>> with tf.device("/cpu:0"): + ... x_on_cpu = tf.identity(x_on_gpu) + >>> x_on_cpu.device + '/job:localhost/replica:0/task:0/device:CPU:0' + + Args: + input: A `Tensor`, a `Variable`, a `CompositeTensor` or anything that can be + converted to a tensor using `tf.convert_to_tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or CompositeTensor. Has the same type and contents as `input`. + """ + # Don't expand ResourceVariables, so identity(variable) will return a Tensor. + if (isinstance(input, composite_tensor.CompositeTensor) and + not _pywrap_utils.IsResourceVariable(input)): + return nest.map_structure(identity, input, expand_composites=True) + if context.executing_eagerly() and not hasattr(input, "graph"): + # Make sure we get an input with handle data attached from resource + # variables. Variables have correct handle data when graph building. + input = ops.convert_to_tensor(input) + ret = gen_array_ops.identity(input, name=name) + # Propagate handle data for happier shape inference for resource variables. + if hasattr(input, "_handle_data"): + ret._handle_data = input._handle_data # pylint: disable=protected-access + return ret + + +# pylint: disable=redefined-builtin,protected-access +@tf_export(v1=["expand_dims"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "Use the `axis` argument instead", "dim") +def expand_dims(input, axis=None, name=None, dim=None): + """Returns a tensor with a length 1 axis inserted at index `axis`. + + Given a tensor `input`, this operation inserts a dimension of length 1 at the + dimension index `axis` of `input`'s shape. The dimension index follows Python + indexing rules: It's zero-based, a negative index it is counted backward + from the end. + + This operation is useful to: + + * Add an outer "batch" dimension to a single element. + * Align axes for broadcasting. + * To add an inner vector length axis to a tensor of scalars. + + For example: + + If you have a single image of shape `[height, width, channels]`: + + >>> image = tf.zeros([10,10,3]) + + You can add an outer `batch` axis by passing `axis=0`: + + >>> tf.expand_dims(image, axis=0).shape.as_list() + [1, 10, 10, 3] + + The new axis location matches Python `list.insert(axis, 1)`: + + >>> tf.expand_dims(image, axis=1).shape.as_list() + [10, 1, 10, 3] + + Following standard Python indexing rules, a negative `axis` counts from the + end so `axis=-1` adds an inner most dimension: + + >>> tf.expand_dims(image, -1).shape.as_list() + [10, 10, 3, 1] + + This operation requires that `axis` is a valid index for `input.shape`, + following Python indexing rules: + + ``` + -1-tf.rank(input) <= axis <= tf.rank(input) + ``` + + This operation is related to: + + * `tf.squeeze`, which removes dimensions of size 1. + * `tf.reshape`, which provides more flexible reshaping capability. + * `tf.sparse.expand_dims`, which provides this functionality for + `tf.SparseTensor` + + Args: + input: A `Tensor`. + axis: 0-D (scalar). Specifies the dimension index at which to expand the + shape of `input`. Must be in the range `[-rank(input) - 1, rank(input)]`. + name: The name of the output `Tensor` (optional). + dim: 0-D (scalar). Equivalent to `axis`, to be deprecated. + + Returns: + A `Tensor` with the same data as `input`, but its shape has an additional + dimension of size 1 added. + + Raises: + ValueError: if either both or neither of `dim` and `axis` are specified. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, "dim", dim) + if axis is None: + raise ValueError("Must specify an axis argument to tf.expand_dims()") + return expand_dims_v2(input, axis, name) + + +@tf_export("expand_dims", v1=[]) +@dispatch.add_dispatch_support +def expand_dims_v2(input, axis, name=None): + """Returns a tensor with a length 1 axis inserted at index `axis`. + + Given a tensor `input`, this operation inserts a dimension of length 1 at the + dimension index `axis` of `input`'s shape. The dimension index follows Python + indexing rules: It's zero-based, a negative index it is counted backward + from the end. + + This operation is useful to: + + * Add an outer "batch" dimension to a single element. + * Align axes for broadcasting. + * To add an inner vector length axis to a tensor of scalars. + + For example: + + If you have a single image of shape `[height, width, channels]`: + + >>> image = tf.zeros([10,10,3]) + + You can add an outer `batch` axis by passing `axis=0`: + + >>> tf.expand_dims(image, axis=0).shape.as_list() + [1, 10, 10, 3] + + The new axis location matches Python `list.insert(axis, 1)`: + + >>> tf.expand_dims(image, axis=1).shape.as_list() + [10, 1, 10, 3] + + Following standard Python indexing rules, a negative `axis` counts from the + end so `axis=-1` adds an inner most dimension: + + >>> tf.expand_dims(image, -1).shape.as_list() + [10, 10, 3, 1] + + This operation requires that `axis` is a valid index for `input.shape`, + following Python indexing rules: + + ``` + -1-tf.rank(input) <= axis <= tf.rank(input) + ``` + + This operation is related to: + + * `tf.squeeze`, which removes dimensions of size 1. + * `tf.reshape`, which provides more flexible reshaping capability. + * `tf.sparse.expand_dims`, which provides this functionality for + `tf.SparseTensor` + + Args: + input: A `Tensor`. + axis: Integer specifying the dimension index at which to expand the + shape of `input`. Given an input of D dimensions, `axis` must be in range + `[-(D+1), D]` (inclusive). + name: Optional string. The name of the output `Tensor`. + + Returns: + A tensor with the same data as `input`, with an additional dimension + inserted at the index specified by `axis`. + + Raises: + TypeError: If `axis` is not specified. + InvalidArgumentError: If `axis` is out of range `[-(D+1), D]`. + """ + return gen_array_ops.expand_dims(input, axis, name) + + +# pylint: enable=redefined-builtin,protected-access + + +# Aliases for some automatically-generated names. +# pylint: disable=protected-access +@deprecation.deprecated("2016-11-30", + "This op will be removed after the deprecation date. " + "Please switch to tf.setdiff1d().") +def listdiff(x, y, out_idx=None, name=None): + return gen_array_ops.list_diff(x, y, out_idx, name) + + +listdiff.__doc__ = gen_array_ops.list_diff.__doc__ + "\n" + listdiff.__doc__ + +# pylint: enable=protected-access + + +# pylint: disable=undefined-variable +@deprecation.deprecated("2018-11-30", + "This op will be removed after the deprecation date. " + "Please switch to tf.sets.difference().") +@tf_export(v1=["setdiff1d"]) +@dispatch.add_dispatch_support +def setdiff1d(x, y, index_dtype=dtypes.int32, name=None): + """Computes the difference between two lists of numbers or strings. + + Given a list x and a list y, this operation returns a list out that + represents all values that are in x but not in y. The returned list + out is sorted in the same order that the numbers appear in x + (duplicates are preserved). This operation also returns a list idx + that represents the position of each out element in x. + + In other words: + + ```python + out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1] + ``` + + Example usage: + + >>> x = [1, 2, 3, 4, 5, 6] + >>> y = [1, 3, 5] + >>> setdiff1d(x,y) + ListDiff(out=, idx=) + + Args: + x: A Tensor. 1-D. Values to keep. + y: A Tensor. Must have the same type as x. 1-D. Values to remove. + out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to + tf.int32. + name: A name for the operation (optional). + + Returns: + A tuple of Tensor objects (out, idx). + out: A Tensor. Has the same type as x. + idx: A Tensor of type out_idx. + """ + return gen_array_ops.list_diff(x, y, index_dtype, name) + + +setdiff1d.__doc__ = gen_array_ops.list_diff.__doc__ + + +@tf_export("broadcast_dynamic_shape") +@dispatch.add_dispatch_support +def broadcast_dynamic_shape(shape_x, shape_y): + """Computes the shape of a broadcast given symbolic shapes. + + When `shape_x` and `shape_y` are Tensors representing shapes (i.e. the result + of calling tf.shape on another Tensor) this computes a Tensor which is the + shape of the result of a broadcasting op applied in tensors of shapes + `shape_x` and `shape_y`. + + This is useful when validating the result of a broadcasting operation when the + tensors do not have statically known shapes. + + Example: + + >>> shape_x = (1, 2, 3) + >>> shape_y = (5, 1, 3) + >>> tf.broadcast_dynamic_shape(shape_x, shape_y) + + + Args: + shape_x: A rank 1 integer `Tensor`, representing the shape of x. + shape_y: A rank 1 integer `Tensor`, representing the shape of y. + + Returns: + A rank 1 integer `Tensor` representing the broadcasted shape. + + Raises: + InvalidArgumentError: If the two shapes are incompatible for + broadcasting. + """ + return gen_array_ops.broadcast_args(shape_x, shape_y) + + +@tf_export("broadcast_static_shape") +@dispatch.add_dispatch_support +def broadcast_static_shape(shape_x, shape_y): + """Computes the shape of a broadcast given known shapes. + + When `shape_x` and `shape_y` are fully known `TensorShape`s this computes a + `TensorShape` which is the shape of the result of a broadcasting op applied in + tensors of shapes `shape_x` and `shape_y`. + + For example, if shape_x is `TensorShape([1, 2, 3])` and shape_y is + `TensorShape([5, 1, 3])`, the result is a TensorShape whose value is + `TensorShape([5, 2, 3])`. + + This is useful when validating the result of a broadcasting operation when the + tensors have statically known shapes. + + Example: + + >>> shape_x = tf.TensorShape([1, 2, 3]) + >>> shape_y = tf.TensorShape([5, 1 ,3]) + >>> tf.broadcast_static_shape(shape_x, shape_y) + TensorShape([5, 2, 3]) + + Args: + shape_x: A `TensorShape` + shape_y: A `TensorShape` + + Returns: + A `TensorShape` representing the broadcasted shape. + + Raises: + ValueError: If the two shapes can not be broadcasted. + """ + return common_shapes.broadcast_shape(shape_x, shape_y) + + +@tf_export("shape", v1=[]) +@dispatch.add_dispatch_support +def shape_v2(input, out_type=None, name=None): + # pylint: disable=redefined-builtin + # TODO(b/274626120) Update `tf_shape_default_int64` comment when it is better + # supported. + """Returns a tensor containing the shape of the input tensor. + + See also `tf.size`, `tf.rank`. + + `tf.shape` returns a 1-D integer tensor representing the shape of `input`. + For a scalar input, the tensor returned has a shape of (0,) and its value is + the empty vector (i.e. []). + + For example: + + >>> tf.shape(1.) + + + >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) + >>> tf.shape(t) + + + Note: When using symbolic tensors, such as when using the Keras API, + tf.shape() will return the shape of the symbolic tensor. + + >>> a = tf.keras.layers.Input((None, 10)) + >>> tf.shape(a) + <... shape=(3,) dtype=int32...> + + In these cases, using `tf.Tensor.shape` will return more informative results. + + >>> a.shape + TensorShape([None, None, 10]) + + (The first `None` represents the as yet unknown batch size.) + + `tf.shape` and `Tensor.shape` should be identical in eager mode. Within + `tf.function` or within a `compat.v1` context, not all dimensions may be + known until execution time. Hence, when defining custom layers and models + for graph mode, prefer the dynamic `tf.shape(x)` over the static `x.shape`. + + Args: + input: A `Tensor` or `SparseTensor`. + out_type: (Optional) The specified output type of the operation (`int32` or + `int64`). Defaults to `tf.int32`. (Note: there is an experimental + flag, `tf_shape_default_int64` that changes the default to `tf.int64`. + This is an unsupported, experimental setting that causes known breakages.) + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + return shape(input, name, out_type) + + +@tf_export(v1=["shape"]) +@dispatch.add_dispatch_support +def shape(input, name=None, out_type=None): + # pylint: disable=redefined-builtin + """Returns the shape of a tensor. + + This operation returns a 1-D integer tensor representing the shape of `input`. + + For example: + + ```python + t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) + tf.shape(t) # [2, 2, 3] + ``` + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + out_type: (Optional) The specified output type of the operation (`int32` + or `int64`). Defaults to `tf.int32`. + + Returns: + A `Tensor` of type `out_type`. + """ + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + return shape_internal(input, name, optimize=True, out_type=out_type) + + +def shape_internal(input, name=None, optimize=True, out_type=None): + # pylint: disable=redefined-builtin + """Returns the shape of a tensor. + + If `out_type` is not specified and the shape is fully known, then we look at + the dimension values to determine whether to return an int32 or int64 tensor. + If the shape is not fully known, we default to int32. + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + optimize: if true, encode the shape as a constant when possible. + out_type: (Optional) The specified output type of the operation (`int32` or + `int64`). Defaults to tf.int32. + + Returns: + A `Tensor` of type `out_type`. + + """ + with ops.name_scope(name, "Shape", [input]) as name: + if isinstance( + input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + if not out_type: + out_type = dtypes.int32 + return gen_math_ops.cast(input.dense_shape, out_type) + else: + if not context.executing_eagerly(): + input = ops.convert_to_tensor(input) + input_shape = input.get_shape() + if optimize and input_shape.is_fully_defined(): + # For fully defined shapes, if the out_type is not specified, we pick + # int32 / int64 based on the actual values. + if not out_type: + return constant_op._tensor_shape_tensor_conversion_function( # pylint: disable=protected-access + input_shape) + return constant(input_shape.as_list(), out_type, name=name) + if not out_type: + out_type = dtypes.int32 + return gen_array_ops.shape(input, name=name, out_type=out_type) + + +@tf_export("shape_n") +@dispatch.add_dispatch_support +def shape_n(input, out_type=dtypes.int32, name=None): + # pylint: disable=redefined-builtin + """Returns shape of a list of tensors. + + Given a list of tensors, `tf.shape_n` is much faster than applying `tf.shape` + to each tensor individually. + >>> a = tf.ones([1, 2]) + >>> b = tf.ones([2, 3]) + >>> c = tf.ones([3, 4]) + >>> tf.shape_n([a, b, c]) + [, + , + ] + + Args: + input: A list of at least 1 `Tensor` object with the same dtype. + out_type: The specified output type of the operation (`int32` or `int64`). + Defaults to `tf.int32`(optional). + name: A name for the operation (optional). + + Returns: + A list of `Tensor` specifying the shape of each input tensor with type of + `out_type`. + """ + + return gen_array_ops.shape_n(input, out_type=out_type, name=name) + + +@tf_export("size", v1=[]) +@dispatch.add_dispatch_support +def size_v2(input, out_type=None, name=None): + # pylint: disable=redefined-builtin + """Returns the size of a tensor. + + See also `tf.shape`. + + Returns a 0-D `Tensor` representing the number of elements in `input` + of type `out_type`. Defaults to tf.int32. + + For example: + + >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) + >>> tf.size(t) + + + Args: + input: A `Tensor` or `SparseTensor`. + out_type: (Optional) The specified non-quantized numeric output type of the + operation. Defaults to `tf.int32`. (Note: there is an experimental + flag, `tf_shape_default_int64` that changes the default to `tf.int64`. + This is an unsupported, experimental setting that causes known breakages.) + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. Defaults to `tf.int32`. + + @compatibility(numpy) + Equivalent to np.size() + @end_compatibility + """ + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + return size(input, name, out_type) + + +@tf_export(v1=["size"]) +@dispatch.add_dispatch_support +def size(input, name=None, out_type=None): + # pylint: disable=redefined-builtin + """Returns the size of a tensor. + + Returns a 0-D `Tensor` representing the number of elements in `input` + of type `out_type`. Defaults to tf.int32. + + For example: + + ```python + t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) + tf.size(t) # 12 + ``` + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + out_type: (Optional) The specified non-quantized numeric output type of the + operation. Defaults to `tf.int32`. (Note: there is an experimental + flag, `tf_shape_default_int64` that changes the default to `tf.int64`. + This is an unsupported, experimental setting that causes known breakages.) + + Returns: + A `Tensor` of type `out_type`. Defaults to `tf.int32`. + + @compatibility(numpy) + Equivalent to np.size() + @end_compatibility + """ + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + return size_internal(input, name, optimize=True, out_type=out_type) + + +def size_internal(input, name=None, optimize=True, out_type=dtypes.int32): + # pylint: disable=redefined-builtin,protected-access + """Returns the size of a tensor. + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + optimize: if true, encode the size as a constant when possible. + out_type: (Optional) The specified non-quantized numeric output type of the + operation. Defaults to `tf.int32`. + + Returns: + A `Tensor` of type `out_type`. Defaults to `tf.int32`. + """ + if (context.executing_eagerly() and not hasattr(input, "graph") and + not isinstance( + input, + (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue))): + input = ops.convert_to_tensor(input) + np_out_type = out_type.as_numpy_dtype + num_elements = np.prod(input._shape_tuple(), dtype=np_out_type) # pylint: disable=protected-access + return ops.convert_to_tensor(num_elements, dtype=out_type) + with ops.name_scope(name, "Size", [input]) as name: + if isinstance( + input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + return gen_math_ops.prod( + gen_math_ops.cast(input.dense_shape, out_type), 0, name=name) + else: + input = ops.convert_to_tensor(input) + input_shape = input.get_shape() + if optimize: + if input_shape.is_fully_defined(): + return constant(input_shape.num_elements(), out_type, name=name) + if input_shape.dims and any(dim == 0 for dim in input_shape.dims): + return constant(0, out_type, name=name) + return gen_array_ops.size(input, name=name, out_type=out_type) + + +@tf_export("rank") +@dispatch.add_dispatch_support +def rank(input, name=None): + # pylint: disable=redefined-builtin + """Returns the rank of a tensor. + + See also `tf.shape`. + + Returns a 0-D `int32` `Tensor` representing the rank of `input`. + + For example: + + ```python + # shape of tensor 't' is [2, 2, 3] + t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) + tf.rank(t) # 3 + ``` + + **Note**: The rank of a tensor is not the same as the rank of a matrix. The + rank of a tensor is the number of indices required to uniquely select each + element of the tensor. Rank is also known as "order", "degree", or "ndims." + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + + @compatibility(numpy) + Equivalent to np.ndim + @end_compatibility + """ + return rank_internal(input, name, optimize=True) + + +def rank_internal(input, name=None, optimize=True): + # pylint: disable=redefined-builtin + """Returns the rank of a tensor. + + Args: + input: A `Tensor` or `SparseTensor`. + name: A name for the operation (optional). + optimize: if true, encode the rank as a constant when possible. + + Returns: + A `Tensor` of type `int32`. + """ + with ops.name_scope(name, "Rank", [input]) as name: + if isinstance( + input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + return gen_array_ops.size(input.dense_shape, name=name) + else: + input = ops.convert_to_tensor(input) + input_shape = input.get_shape() + if optimize and input_shape.ndims is not None: + return constant(input_shape.ndims, dtypes.int32, name=name) + return gen_array_ops.rank(input, name=name) + + +_SLICE_TYPE_ERROR = ( + "Only integers, slices (`:`), ellipsis (`...`), " + "tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid " + "indices") + +_SUPPORTED_SLICE_DTYPES = (dtypes.int16, dtypes.int32, dtypes.int32_ref, + dtypes.int64, dtypes.int64_ref) + + +def _check_index(idx): + """Check if a given value is a valid index into a tensor.""" + if isinstance(idx, (numbers.Integral, tensor_shape.Dimension)): + return + + # Optimistic check. Assumptions: + # * any object with a dtype is supported + # * any object with a dtype has a sizeable shape attribute. + dtype = getattr(idx, "dtype", None) + if (dtype is None or dtypes.as_dtype(dtype) not in _SUPPORTED_SLICE_DTYPES or + idx.shape and len(idx.shape) == 1): + # TODO(slebedev): IndexError seems more appropriate here, but it + # will break `_slice_helper` contract. + raise TypeError(_SLICE_TYPE_ERROR + ", got {!r}".format(idx)) + + +def _is_undefined_dimension(d): + return isinstance(d, tensor_shape.Dimension) and d.value is None + + +@tf_export("__operators__.getitem", v1=[]) +@dispatch.add_dispatch_support +def _slice_helper(tensor, slice_spec, var=None): + """Overload for Tensor.__getitem__. + + This operation extracts the specified region from the tensor. + The notation is similar to NumPy with the restriction that + currently only support basic indexing. That means that + using a non-scalar tensor as input is not currently allowed. + + Some useful examples: + + ```python + # Strip leading and trailing 2 elements + foo = tf.constant([1,2,3,4,5,6]) + print(foo[2:-2]) # => [3,4] + + # Skip every other row and reverse the order of the columns + foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) + print(foo[::2,::-1]) # => [[3,2,1], [9,8,7]] + + # Use scalar tensors as indices on both dimensions + print(foo[tf.constant(0), tf.constant(2)]) # => 3 + + # Insert another dimension + foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) + print(foo[tf.newaxis, :, :]) # => [[[1,2,3], [4,5,6], [7,8,9]]] + print(foo[:, tf.newaxis, :]) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]] + print(foo[:, :, tf.newaxis]) # => [[[1],[2],[3]], [[4],[5],[6]], + [[7],[8],[9]]] + + # Ellipses (3 equivalent operations) + foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) + print(foo[tf.newaxis, :, :]) # => [[[1,2,3], [4,5,6], [7,8,9]]] + print(foo[tf.newaxis, ...]) # => [[[1,2,3], [4,5,6], [7,8,9]]] + print(foo[tf.newaxis]) # => [[[1,2,3], [4,5,6], [7,8,9]]] + + # Masks + foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) + print(foo[foo > 2]) # => [3, 4, 5, 6, 7, 8, 9] + ``` + + Notes: + - `tf.newaxis` is `None` as in NumPy. + - An implicit ellipsis is placed at the end of the `slice_spec` + - NumPy advanced indexing is currently not supported. + + Purpose in the API: + + This method is exposed in TensorFlow's API so that library developers + can register dispatching for `Tensor.__getitem__` to allow it to handle + custom composite tensors & other custom objects. + + The API symbol is not intended to be called by users directly and does + appear in TensorFlow's generated documentation. + + Args: + tensor: An tensor.Tensor object. + slice_spec: The arguments to Tensor.__getitem__. + var: In the case of variable slice assignment, the Variable object to slice + (i.e. tensor is the read-only view of this variable). + + Returns: + The appropriate slice of "tensor", based on "slice_spec". + + Raises: + ValueError: If a slice range is negative size. + TypeError: If the slice indices aren't int, slice, ellipsis, + tf.newaxis or scalar int32/int64 tensors. + """ + tensor = ops.convert_to_tensor(tensor) + # TODO(wangpeng): Consider supporting var + if var is None and ops._numpy_style_slicing: # pylint: disable=protected-access + return tensor._numpy_style_getitem(slice_spec) # pylint: disable=protected-access + + if (isinstance(slice_spec, bool) + or (isinstance(slice_spec, tensor_lib.Tensor) + and slice_spec.dtype == dtypes.bool) + or (isinstance(slice_spec, np.ndarray) + and slice_spec.dtype == bool)): + return boolean_mask(tensor=tensor, mask=slice_spec) + + if not isinstance(slice_spec, (list, tuple)): + slice_spec = [slice_spec] + + begin, end, strides = [], [], [] + index = 0 + + new_axis_mask, shrink_axis_mask = 0, 0 + begin_mask, end_mask = 0, 0 + ellipsis_mask = 0 + for s in slice_spec: + if isinstance(s, _BaseSlice): + # Finds the best dtype for begin, end, and strides. + dtype = None + for t in [s.start, s.stop, s.step]: + if t is None or not isinstance(t, tensor_lib.Tensor): + continue + if t.dtype == dtypes.int64: + dtype = dtypes.int64 + elif t.dtype == dtypes.int32 and dtype != dtypes.int64: + dtype = dtypes.int32 + elif t.dtype == dtypes.int16 and dtype is None: + dtype = dtypes.int16 + + if s.start is not None and not _is_undefined_dimension(s.start): + _check_index(s.start) + begin.append(s.start) + else: + if dtype is not None: + begin.append(constant_op.constant(0, dtype=dtype)) + else: + begin.append(0) + begin_mask |= (1 << index) + if s.stop is not None and not _is_undefined_dimension(s.stop): + _check_index(s.stop) + end.append(s.stop) + else: + if dtype is not None: + end.append(constant_op.constant(0, dtype=dtype)) + else: + end.append(0) + end_mask |= (1 << index) + if s.step is not None and not _is_undefined_dimension(s.step): + _check_index(s.step) + strides.append(s.step) + else: + if dtype is not None: + strides.append(constant_op.constant(1, dtype=dtype)) + else: + strides.append(1) + elif s is Ellipsis: + begin.append(0) + end.append(0) + strides.append(1) + ellipsis_mask |= (1 << index) + elif s is newaxis: + begin.append(0) + end.append(0) + strides.append(1) + new_axis_mask |= (1 << index) + else: + _check_index(s) + begin.append(s) + end.append(s + 1) + # TODO(mdan): Investigate why we can't set int32 here. + if ( + isinstance(s, tensor_lib.Tensor) + and (s.dtype == dtypes.int16 or s.dtype == dtypes.int64)): + strides.append(constant_op.constant(1, dtype=s.dtype)) + else: + strides.append(1) + shrink_axis_mask |= (1 << index) + index += 1 + + # stack possibly involves no tensors, so we must use op_scope correct graph. + with ops.name_scope( + None, + "strided_slice", [tensor] + begin + end + strides, + skip_on_eager=False) as name: + if begin: + packed_begin, packed_end, packed_strides = ( + array_ops_stack.stack(begin), + array_ops_stack.stack(end), + array_ops_stack.stack(strides)) + # TODO(mdan): Instead of implicitly casting, it's better to enforce the + # same dtypes. + if (packed_begin.dtype == dtypes.int64 or + packed_end.dtype == dtypes.int64 or + packed_strides.dtype == dtypes.int64): + if packed_begin.dtype != dtypes.int64: + packed_begin = gen_math_ops.cast(packed_begin, dtypes.int64) + if packed_end.dtype != dtypes.int64: + packed_end = gen_math_ops.cast(packed_end, dtypes.int64) + if packed_strides.dtype != dtypes.int64: + packed_strides = gen_math_ops.cast(packed_strides, dtypes.int64) + elif (packed_begin.dtype == dtypes.int16 and + packed_end.dtype == dtypes.int16 and + packed_strides.dtype == dtypes.int16): + if packed_begin.dtype != dtypes.int16: + packed_begin = gen_math_ops.cast(packed_begin, dtypes.int16) + if packed_end.dtype != dtypes.int16: + packed_end = gen_math_ops.cast(packed_end, dtypes.int16) + if packed_strides.dtype != dtypes.int16: + packed_strides = gen_math_ops.cast(packed_strides, dtypes.int16) + else: + var_empty = constant([], dtype=dtypes.int32) + packed_begin = packed_end = packed_strides = var_empty + return strided_slice( + tensor, + packed_begin, + packed_end, + packed_strides, + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask, + var=var, + name=name) + + +# pylint: disable=undefined-variable,protected-access,redefined-outer-name +@tf_export("slice") +@dispatch.add_dispatch_support +def slice(input_, begin, size, name=None): + # pylint: disable=redefined-builtin + """Extracts a slice from a tensor. + + See also `tf.strided_slice`. + + This operation extracts a slice of size `size` from a tensor `input_` starting + at the location specified by `begin`. The slice `size` is represented as a + tensor shape, where `size[i]` is the number of elements of the 'i'th dimension + of `input_` that you want to slice. The starting location (`begin`) for the + slice is represented as an offset in each dimension of `input_`. In other + words, `begin[i]` is the offset into the i'th dimension of `input_` that you + want to slice from. + + Note that `tf.Tensor.__getitem__` is typically a more pythonic way to + perform slices, as it allows you to write `foo[3:7, :-2]` instead of + `tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2])`. + + `begin` is zero-based; `size` is one-based. If `size[i]` is -1, + all remaining elements in dimension i are included in the + slice. In other words, this is equivalent to setting: + + `size[i] = input_.dim_size(i) - begin[i]` + + This operation requires that: + + `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]` + + For example: + + ```python + t = tf.constant([[[1, 1, 1], [2, 2, 2]], + [[3, 3, 3], [4, 4, 4]], + [[5, 5, 5], [6, 6, 6]]]) + tf.slice(t, [1, 0, 0], [1, 1, 3]) # [[[3, 3, 3]]] + tf.slice(t, [1, 0, 0], [1, 2, 3]) # [[[3, 3, 3], + # [4, 4, 4]]] + tf.slice(t, [1, 0, 0], [2, 1, 3]) # [[[3, 3, 3]], + # [[5, 5, 5]]] + ``` + + Args: + input_: A `Tensor`. + begin: An `int32` or `int64` `Tensor`. + size: An `int32` or `int64` `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` the same type as `input_`. + """ + return gen_array_ops._slice(input_, begin, size, name=name) + + +# pylint: disable=invalid-name +@tf_export("strided_slice") +@dispatch.add_dispatch_support +def strided_slice(input_, + begin, + end, + strides=None, + begin_mask=0, + end_mask=0, + ellipsis_mask=0, + new_axis_mask=0, + shrink_axis_mask=0, + var=None, + name=None): + """Extracts a strided slice of a tensor (generalized Python array indexing). + + See also `tf.slice`. + + **Instead of calling this op directly most users will want to use the + NumPy-style slicing syntax (e.g. `tensor[..., 3:4:-1, tf.newaxis, 3]`), which + is supported via `tf.Tensor.__getitem__` and `tf.Variable.__getitem__`.** + The interface of this op is a low-level encoding of the slicing syntax. + + Roughly speaking, this op extracts a slice of size `(end-begin)/stride` + from the given `input_` tensor. Starting at the location specified by `begin` + the slice continues by adding `stride` to the index until all dimensions are + not less than `end`. + Note that a stride can be negative, which causes a reverse slice. + + Given a Python slice `input[spec0, spec1, ..., specn]`, + this function will be called as follows. + + `begin`, `end`, and `strides` will be vectors of length n. + n in general is not equal to the rank of the `input_` tensor. + + In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`, + `new_axis_mask`, `shrink_axis_mask`) the ith bit will correspond to + the ith spec. + + If the ith bit of `begin_mask` is set, `begin[i]` is ignored and + the fullest possible range in that dimension is used instead. + `end_mask` works analogously, except with the end range. + + `foo[5:,:,:3]` on a 7x8x9 tensor is equivalent to `foo[5:7,0:8,0:3]`. + `foo[::-1]` reverses a tensor with shape 8. + + If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions + as needed will be inserted between other dimensions. Only one + non-zero bit is allowed in `ellipsis_mask`. + + For example `foo[3:5,...,4:5]` on a shape 10x3x3x10 tensor is + equivalent to `foo[3:5,:,:,4:5]` and + `foo[3:5,...]` is equivalent to `foo[3:5,:,:,:]`. + + If the ith bit of `new_axis_mask` is set, then `begin`, + `end`, and `stride` are ignored and a new length 1 dimension is + added at this point in the output tensor. + + For example, + `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. + + If the ith bit of `shrink_axis_mask` is set, it implies that the ith + specification shrinks the dimensionality by 1, taking on the value at index + `begin[i]`. `end[i]` and `strides[i]` are ignored in this case. For example in + Python one might do `foo[:, 3, :]` which would result in `shrink_axis_mask` + equal to 2. + + + NOTE: `begin` and `end` are zero-indexed. + `strides` entries must be non-zero. + + + ```python + t = tf.constant([[[1, 1, 1], [2, 2, 2]], + [[3, 3, 3], [4, 4, 4]], + [[5, 5, 5], [6, 6, 6]]]) + tf.strided_slice(t, [1, 0, 0], [2, 1, 3], [1, 1, 1]) # [[[3, 3, 3]]] + tf.strided_slice(t, [1, 0, 0], [2, 2, 3], [1, 1, 1]) # [[[3, 3, 3], + # [4, 4, 4]]] + tf.strided_slice(t, [1, -1, 0], [2, -3, 3], [1, -1, 1]) # [[[4, 4, 4], + # [3, 3, 3]]] + ``` + + Args: + input_: A `Tensor`. + begin: An `int32` or `int64` `Tensor`. + end: An `int32` or `int64` `Tensor`. + strides: An `int32` or `int64` `Tensor`. + begin_mask: An `int32` mask. + end_mask: An `int32` mask. + ellipsis_mask: An `int32` mask. + new_axis_mask: An `int32` mask. + shrink_axis_mask: An `int32` mask. + var: The variable corresponding to `input_` or None + name: A name for the operation (optional). + + Returns: + A `Tensor` the same type as `input`. + """ + + if strides is None: + strides = ones_like(begin) + + op = gen_array_ops.strided_slice( + input=input_, + begin=begin, + end=end, + strides=strides, + name=name, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask) + + parent_name = name + + if var is not None: + def assign(val, name=None): + """Closure that holds all the arguments to create an assignment.""" + + if name is None: + name = parent_name + "_assign" + + return var._strided_slice_assign( + begin=begin, + end=end, + strides=strides, + value=val, + name=name, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask) + + op.assign = assign + + return op + + +def _SliceHelperVar(var, slice_spec): + """Creates a slice helper object given a variable. + + This allows creating a sub-tensor from part of the current contents + of a variable. See `tf.Tensor.__getitem__` for detailed examples + of slicing. + + This function in addition also allows assignment to a sliced range. + This is similar to `__setitem__` functionality in Python. However, + the syntax is different so that the user can capture the assignment + operation for grouping or passing to `sess.run()` in TF1. + For example, + + ```python + import tensorflow as tf + A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32) + print(A[:2, :2]) # => [[1,2], [4,5]] + + A[:2,:2].assign(22. * tf.ones((2, 2)))) + print(A) # => [[22, 22, 3], [22, 22, 6], [7,8,9]] + ``` + + Note that assignments currently do not support NumPy broadcasting + semantics. + + Args: + var: An `ops.Variable` object. + slice_spec: The arguments to `Tensor.__getitem__`. + + Returns: + The appropriate slice of "tensor", based on "slice_spec". + As an operator. The operator also has a `assign()` method + that can be used to generate an assignment operator. + + Raises: + ValueError: If a slice range is negative size. + TypeError: TypeError: If the slice indices aren't int, slice, + ellipsis, tf.newaxis or int32/int64 tensors. + + """ + + return _slice_helper(var.value(), slice_spec, var) + + +tensor_lib.Tensor._override_operator("__getitem__", _slice_helper) + + +@tf_export("parallel_stack") +@dispatch.add_dispatch_support +def parallel_stack(values, name="parallel_stack"): + """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel. + + Requires that the shape of inputs be known at graph construction time. + + Packs the list of tensors in `values` into a tensor with rank one higher than + each tensor in `values`, by packing them along the first dimension. + Given a list of length `N` of tensors of shape `(A, B, C)`; the `output` + tensor will have the shape `(N, A, B, C)`. + + For example: + + ```python + x = tf.constant([1, 4]) + y = tf.constant([2, 5]) + z = tf.constant([3, 6]) + tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]] + ``` + + The difference between `stack` and `parallel_stack` is that `stack` requires + all the inputs be computed before the operation will begin but doesn't require + that the input shapes be known during graph construction. + + `parallel_stack` will copy pieces of the input into the output as they become + available, in some situations this can provide a performance benefit. + + Unlike `stack`, `parallel_stack` does NOT support backpropagation. + + This is the opposite of unstack. The numpy equivalent is + + tf.parallel_stack([x, y, z]) = np.asarray([x, y, z]) + + @compatibility(eager) + parallel_stack is not compatible with eager execution. + @end_compatibility + + Args: + values: A list of `Tensor` objects with the same shape and type. + name: A name for this operation (optional). + + Returns: + output: A stacked `Tensor` with the same type as `values`. + + Raises: + RuntimeError: if executed in eager mode. + """ + if context.executing_eagerly(): + raise RuntimeError("tf.parallel_stack() is not compatible with " + "eager execution.") + with ops.name_scope(name): + value_t = ops.convert_to_tensor(values[0]) + value_shape = ops.convert_to_tensor(value_t).get_shape() + + output_shape = tensor_shape.TensorShape([len(values)]) + output_shape = output_shape.concatenate(value_shape) + # expand_dims converts concat to stack. + return gen_array_ops.parallel_concat( + [expand_dims(value, 0) for value in values], shape=output_shape) + + +# pylint: disable=invalid-name +def _autopacking_helper(list_or_tuple, dtype, name): + """Converts the given list or tuple to a tensor by packing. + + Args: + list_or_tuple: A (possibly nested) list or tuple containing a tensor. + dtype: The element type of the returned tensor. + name: A name for the returned tensor. + + Returns: + A `tf.Tensor` with value equivalent to `list_or_tuple`. + """ + if context.executing_eagerly(): + # NOTE: Fast path when all the items are tensors, this doesn't do any type + # checking. + if all(isinstance(elem, core.Tensor) for elem in list_or_tuple): + return gen_array_ops.pack(list_or_tuple, name=name) + must_pack = False + converted_elems = [] + with ops.name_scope(name) as scope: + for i, elem in enumerate(list_or_tuple): + if isinstance(elem, core.Tensor): + if dtype is not None and elem.dtype.base_dtype != dtype: + raise TypeError(f"Cannot convert a list containing a tensor of dtype " + f"{elem.dtype} to {dtype} (Tensor is: {elem!r})") + converted_elems.append(elem) + must_pack = True + elif isinstance(elem, (list, tuple)): + converted_elem = _autopacking_helper(elem, dtype, str(i)) + if isinstance(converted_elem, core.Tensor): + must_pack = True + converted_elems.append(converted_elem) + else: + converted_elems.append(elem) + if must_pack: + elems_as_tensors = [] + for i, elem in enumerate(converted_elems): + if isinstance(elem, core.Tensor): + elems_as_tensors.append(elem) + else: + # NOTE(mrry): This is inefficient, but it enables us to + # handle the case where the list arguments are other + # convertible-to-tensor types, such as numpy arrays. + elems_as_tensors.append( + constant_op.constant(elem, dtype=dtype, name=str(i))) + return gen_array_ops.pack(elems_as_tensors, name=scope) + else: + return converted_elems + + +def _get_dtype_from_nested_lists(list_or_tuple): + """Returns the dtype of any tensor-like object in `list_or_tuple`, if found. + + Args: + list_or_tuple: A list or tuple representing an object that can be converted + to a `tf.Tensor`. + + Returns: + The dtype of any tensor-like object in `list_or_tuple`, or `None` if no + such object exists. + """ + for elem in list_or_tuple: + if isinstance(elem, core.Tensor): + return elem.dtype.base_dtype + elif isinstance(elem, (list, tuple)): + maybe_dtype = _get_dtype_from_nested_lists(elem) + if maybe_dtype is not None: + return maybe_dtype + return None + + +def _cast_nested_seqs_to_dtype(dtype): + + def _maybe_cast(elem): + if isinstance(elem, core.Tensor): + if dtype != elem.dtype.base_dtype: + elem = gen_math_ops.cast(elem, dtype) + return elem + + return _maybe_cast + + +_NON_AUTOPACKABLE_TYPES = set(np.core.numerictypes.ScalarType) +_NON_AUTOPACKABLE_TYPES.add(np.ndarray) + + +def _should_not_autopack(v): + # The condition we really want is + # any(isinstance(elem, core.Tensor)) + # but it is >5x slower due to abc.ABCMeta.__instancecheck__. + # pylint: disable=unidiomatic-typecheck + # TODO(slebedev): add nest.all? + return all(type(elem) in _NON_AUTOPACKABLE_TYPES for elem in nest.flatten(v)) + # pylint: enable=unidiomatic-typecheck + + +def _autopacking_conversion_function(v, dtype=None, name=None, as_ref=False): + """Tensor conversion function that automatically packs arguments.""" + if as_ref or _should_not_autopack(v): + return NotImplemented + inferred_dtype = _get_dtype_from_nested_lists(v) + if inferred_dtype is None: + # We did not find any tensor-like objects in the nested lists, so defer to + # other conversion functions. + return NotImplemented + if dtype is None: + dtype = inferred_dtype + elif dtype != inferred_dtype: + v = nest.map_structure(_cast_nested_seqs_to_dtype(dtype), v) + return _autopacking_helper(v, dtype, name or "packed") + + +# pylint: enable=invalid-name + +# NOTE: Register this conversion function to run *before* one that +# assumes every element is a value. +tensor_conversion_registry.register_tensor_conversion_function( + (list, tuple), _autopacking_conversion_function, 99) + + +@tf_export("concat") +@dispatch.add_dispatch_support +def concat(values, axis, name="concat"): + """Concatenates tensors along one dimension. + + See also `tf.tile`, `tf.stack`, `tf.repeat`. + + Concatenates the list of tensors `values` along dimension `axis`. If + `values[i].shape = [D0, D1, ... Daxis(i), ...Dn]`, the concatenated + result has shape + + [D0, D1, ... Raxis, ...Dn] + + where + + Raxis = sum(Daxis(i)) + + That is, the data from the input tensors is joined along the `axis` + dimension. + + The number of dimensions of the input tensors must match, and all dimensions + except `axis` must be equal. + + For example: + + >>> t1 = [[1, 2, 3], [4, 5, 6]] + >>> t2 = [[7, 8, 9], [10, 11, 12]] + >>> tf.concat([t1, t2], 0) + + + >>> tf.concat([t1, t2], 1) + + + As in Python, the `axis` could also be negative numbers. Negative `axis` + are interpreted as counting from the end of the rank, i.e., + `axis + rank(values)`-th dimension. + + For example: + + >>> t1 = [[[1, 2], [2, 3]], [[4, 4], [5, 3]]] + >>> t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]] + >>> tf.concat([t1, t2], -1) + + + Note: If you are concatenating along a new axis consider using stack. + E.g. + + ```python + tf.concat([tf.expand_dims(t, axis) for t in tensors], axis) + ``` + + can be rewritten as + + ```python + tf.stack(tensors, axis=axis) + ``` + + Args: + values: A list of `Tensor` objects or a single `Tensor`. + axis: 0-D `int32` `Tensor`. Dimension along which to concatenate. Must be + in the range `[-rank(values), rank(values))`. As in Python, indexing for + axis is 0-based. Positive axis in the rage of `[0, rank(values))` refers + to `axis`-th dimension. And negative axis refers to `axis + + rank(values)`-th dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor` resulting from concatenation of the input tensors. + """ + if not isinstance(values, (list, tuple)): + values = [values] + # TODO(mrry): Change to return values? + if len(values) == 1: # Degenerate case of one tensor. + # Make a throwaway call to convert_to_tensor to make sure + # that axis is of the correct type, and make sure that + # the returned tensor is a scalar. + # TODO(keveman): Implement a standalone type and shape checker. + with ops.name_scope(name) as scope: + ops.convert_to_tensor( + axis, name="concat_dim", + dtype=dtypes.int32).get_shape().assert_has_rank(0) + return identity(values[0], name=name) + return gen_array_ops.concat_v2(values=values, axis=axis, name=name) + + +@tf_export(v1=["boolean_mask"]) +@dispatch.add_dispatch_support +def boolean_mask(tensor, mask, name="boolean_mask", axis=None): + """Apply boolean mask to tensor. + + Numpy equivalent is `tensor[mask]`. + + In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match + the first K dimensions of `tensor`'s shape. We then have: + `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]` + where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order). + The `axis` could be used with `mask` to indicate the axis to mask from. + In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match + the first `axis + dim(mask)` dimensions of `tensor`'s shape. + + See also: `tf.ragged.boolean_mask`, which can be applied to both dense and + ragged tensors, and can be used if you need to preserve the masked dimensions + of `tensor` (rather than flattening them, as `tf.boolean_mask` does). + + Examples: + + ```python + # 1-D example + tensor = [0, 1, 2, 3] + mask = np.array([True, False, True, False]) + tf.boolean_mask(tensor, mask) # [0, 2] + + # 2-D example + tensor = [[1, 2], [3, 4], [5, 6]] + mask = np.array([True, False, True]) + tf.boolean_mask(tensor, mask) # [[1, 2], [5, 6]] + ``` + + Args: + tensor: N-D Tensor. + mask: K-D boolean Tensor, K <= N and K must be known statically. + name: A name for this operation (optional). + axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By + default, axis is 0 which will mask from the first dimension. Otherwise K + + axis <= N. + + Returns: + (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding + to `True` values in `mask`. + + Raises: + ValueError: If shapes do not conform. + """ + + def _apply_mask_1d(reshaped_tensor, mask, axis=None): + """Mask tensor along dimension 0 with a 1-D mask.""" + indices = squeeze(where_v2(mask), axis=[1]) + return gather(reshaped_tensor, indices, axis=axis) + + with ops.name_scope(name, values=[tensor, mask]): + tensor = ops.convert_to_tensor(tensor, name="tensor") + mask = ops.convert_to_tensor(mask, name="mask") + + shape_mask = mask.get_shape() + ndims_mask = shape_mask.ndims + shape_tensor = tensor.get_shape() + if ndims_mask == 0: + raise ValueError("mask cannot be scalar.") + if ndims_mask is None: + raise ValueError( + "Number of mask dimensions must be specified, even if some dimensions" + " are None. E.g. shape=[None] is ok, but shape=None is not.") + axis = 0 if axis is None else axis + axis_value = tensor_util.constant_value(axis) + if axis_value is not None: + axis = axis_value + shape_tensor[axis:axis + ndims_mask].assert_is_compatible_with(shape_mask) + + leading_size = gen_math_ops.prod(shape(tensor)[axis:axis + ndims_mask], [0]) + tensor = reshape( + tensor, + concat([ + shape(tensor)[:axis], [leading_size], + shape(tensor)[axis + ndims_mask:] + ], 0)) + # TODO(yongtang): tf.reshape in C++ kernel might have set the shape + # correctly, so the following may not be needed? It still might be possible + # that there are some edge case where tensor_util.constant_value resolves + # more cases than ShapeInference of tf.reshape in C++ kernel. + if axis_value is not None: + first_dim = shape_tensor[axis:axis + ndims_mask].num_elements() + tensor.set_shape( + tensor_shape.as_shape(shape_tensor[:axis]).concatenate( + [first_dim]).concatenate(shape_tensor[axis + ndims_mask:])) + + mask = reshape(mask, [-1]) + return _apply_mask_1d(tensor, mask, axis) + + +@tf_export("boolean_mask", v1=[]) +@dispatch.add_dispatch_support +def boolean_mask_v2(tensor, mask, axis=None, name="boolean_mask"): + """Apply boolean mask to tensor. + + Numpy equivalent is `tensor[mask]`. + + In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match + the first K dimensions of `tensor`'s shape. We then have: + `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]` + where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order). + The `axis` could be used with `mask` to indicate the axis to mask from. + In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match + the first `axis + dim(mask)` dimensions of `tensor`'s shape. + + See also: `tf.ragged.boolean_mask`, which can be applied to both dense and + ragged tensors, and can be used if you need to preserve the masked dimensions + of `tensor` (rather than flattening them, as `tf.boolean_mask` does). + + Examples: + + >>> tensor = [0, 1, 2, 3] # 1-D example + >>> mask = np.array([True, False, True, False]) + >>> tf.boolean_mask(tensor, mask) + + + >>> tensor = [[1, 2], [3, 4], [5, 6]] # 2-D example + >>> mask = np.array([True, False, True]) + >>> tf.boolean_mask(tensor, mask) + + + Args: + tensor: N-D Tensor. + mask: K-D boolean Tensor, K <= N and K must be known statically. + axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By + default, axis is 0 which will mask from the first dimension. Otherwise K + + axis <= N. + name: A name for this operation (optional). + + Returns: + (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding + to `True` values in `mask`. + + Raises: + ValueError: If shapes do not conform. + + Examples: + + ```python + # 2-D example + tensor = [[1, 2], [3, 4], [5, 6]] + mask = np.array([True, False, True]) + boolean_mask(tensor, mask) # [[1, 2], [5, 6]] + ``` + """ + return boolean_mask(tensor, mask, name, axis) + + +@tf_export("sparse.mask", v1=["sparse.mask", "sparse_mask"]) +@deprecation.deprecated_endpoints("sparse_mask") +def sparse_mask(a, mask_indices, name=None): + """Masks elements of `IndexedSlices`. + + Given an `IndexedSlices` instance `a`, returns another `IndexedSlices` that + contains a subset of the slices of `a`. Only the slices at indices not + specified in `mask_indices` are returned. + + This is useful when you need to extract a subset of slices in an + `IndexedSlices` object. + + For example: + + ```python + # `a` contains slices at indices [12, 26, 37, 45] from a large tensor + # with shape [1000, 10] + a.indices # [12, 26, 37, 45] + tf.shape(a.values) # [4, 10] + + # `b` will be the subset of `a` slices at its second and third indices, so + # we want to mask its first and last indices (which are at absolute + # indices 12, 45) + b = tf.sparse.mask(a, [12, 45]) + + b.indices # [26, 37] + tf.shape(b.values) # [2, 10] + ``` + + Args: + a: An `IndexedSlices` instance. + mask_indices: Indices of elements to mask. + name: A name for the operation (optional). + + Returns: + The masked `IndexedSlices` instance. + """ + with ops.name_scope(name, "sparse_mask", [a, mask_indices]) as name: + indices = a.indices + out_indices, to_gather = gen_array_ops.list_diff(indices, mask_indices) + out_values = gather(a.values, to_gather, name=name) + return indexed_slices.IndexedSlices(out_values, out_indices, a.dense_shape) + + +@tf_export("unique") +@dispatch.add_dispatch_support +def unique(x, out_idx=dtypes.int32, name=None): + """Finds unique elements in a 1-D tensor. + + See also `tf.unique_with_counts`. + + This operation returns a tensor `y` containing all the unique elements + of `x` sorted in the same order that they occur in `x`. This operation + also returns a tensor `idx` the same size as `x` that contains the index + of each value of `x` in the unique output `y`. In other words: + + + y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1] + + Example usage: + + >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8]) + >>> y, idx = unique(x) + >>> y + + >>> idx + + + Args: + x: A Tensor. 1-D. + out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to + tf.int32. + name: A name for the operation (optional). + + Returns: + A tuple of Tensor objects (y, idx). + y: A Tensor. Has the same type as x. + idx: A Tensor of type out_idx. + + """ + # TODO(yongtang): switch to v2 once API deprecation + # period (3 weeks) pass. + # TODO(yongtang): The documentation should also + # be updated when switch to v2. + return gen_array_ops.unique(x, out_idx, name) + + +unique.__doc__ = gen_array_ops.unique.__doc__ + + +@tf_export("unique_with_counts") +@dispatch.add_dispatch_support +def unique_with_counts(x, out_idx=dtypes.int32, name=None): + """Finds unique elements in a 1-D tensor. + + See also `tf.unique`. + + This operation returns a tensor `y` containing all the unique elements + of `x` sorted in the same order that they occur in `x`. This operation + also returns a tensor `idx` the same size as `x` that contains the index + of each value of `x` in the unique output `y`. Finally, it returns a + third tensor `count` that contains the count of each element of `y` + in `x`. In other words: + + y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1] + + Example usage: + + >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8]) + >>> y, idx, count = unique_with_counts(x) + >>> y + + >>> idx + + >>> count + + + Args: + x: A Tensor. 1-D. + out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to + tf.int32. + name: A name for the operation (optional). + + Returns: + A tuple of Tensor objects (y, idx, count). + y: A Tensor. Has the same type as x. + idx: A Tensor of type out_idx. + count: A Tensor of type out_idx. + + """ + # TODO(yongtang): switch to v2 once API deprecation + # period (3 weeks) pass. + # TODO(yongtang): The documentation should also + # be updated when switch to v2. + return gen_array_ops.unique_with_counts(x, out_idx, name) + + +unique_with_counts.__doc__ = gen_array_ops.unique_with_counts.__doc__ + + +@tf_export("split") +@dispatch.add_dispatch_support +def split(value, num_or_size_splits, axis=0, num=None, name="split"): + """Splits a tensor `value` into a list of sub tensors. + + See also `tf.unstack`. + + If `num_or_size_splits` is an `int`, then it splits `value` along the + dimension `axis` into `num_or_size_splits` smaller tensors. This requires that + `value.shape[axis]` is divisible by `num_or_size_splits`. + + If `num_or_size_splits` is a 1-D Tensor (or list), then `value` is split into + `len(num_or_size_splits)` elements. The shape of the `i`-th + element has the same size as the `value` except along dimension `axis` where + the size is `num_or_size_splits[i]`. + + For example: + + >>> x = tf.Variable(tf.random.uniform([5, 30], -1, 1)) + >>> + >>> # Split `x` into 3 tensors along dimension 1 + >>> s0, s1, s2 = tf.split(x, num_or_size_splits=3, axis=1) + >>> tf.shape(s0).numpy() + array([ 5, 10], dtype=int32) + >>> + >>> # Split `x` into 3 tensors with sizes [4, 15, 11] along dimension 1 + >>> split0, split1, split2 = tf.split(x, [4, 15, 11], 1) + >>> tf.shape(split0).numpy() + array([5, 4], dtype=int32) + >>> tf.shape(split1).numpy() + array([ 5, 15], dtype=int32) + >>> tf.shape(split2).numpy() + array([ 5, 11], dtype=int32) + + Args: + value: The `Tensor` to split. + num_or_size_splits: Either an `int` indicating the number of splits + along `axis` or a 1-D integer `Tensor` or Python list containing the sizes + of each output tensor along `axis`. If an `int`, then it must evenly + divide `value.shape[axis]`; otherwise the sum of sizes along the split + axis must match that of the `value`. + axis: An `int` or scalar `int32` `Tensor`. The dimension along which + to split. Must be in the range `[-rank(value), rank(value))`. Defaults to + 0. + num: Optional, an `int`, used to specify the number of outputs when it + cannot be inferred from the shape of `size_splits`. + name: A name for the operation (optional). + + Returns: + if `num_or_size_splits` is an `int` returns a list of + `num_or_size_splits` `Tensor` objects; if `num_or_size_splits` is a 1-D + list or 1-D `Tensor` returns `num_or_size_splits.get_shape[0]` + `Tensor` objects resulting from splitting `value`. + + Raises: + ValueError: If `num` is unspecified and cannot be inferred. + ValueError: If `num_or_size_splits` is a scalar `Tensor`. + """ + if isinstance(num_or_size_splits, + (numbers.Integral, tensor_shape.Dimension)): + return gen_array_ops.split( + axis=axis, num_split=num_or_size_splits, value=value, name=name) + + size_splits = ops.convert_to_tensor(num_or_size_splits) + + if size_splits._rank() == 0: + raise ValueError( + "Rank-0 tensors are not supported as the num_or_size_splits argument " + "to split. Argument provided: %s" % (num_or_size_splits,)) + + if num is None: + size_splits_shape = size_splits._shape_tuple() + if size_splits_shape: + num = size_splits_shape[0] + if num is None: + raise ValueError( + f"Cannot infer argument `num` from shape {num_or_size_splits}") + + return gen_array_ops.split_v( + value=value, size_splits=size_splits, axis=axis, num_split=num, name=name) + + +@tf_export("transpose", v1=[]) +@dispatch.add_dispatch_support +def transpose_v2(a, perm=None, conjugate=False, name="transpose"): + """Transposes `a`, where `a` is a Tensor. + + Permutes the dimensions according to the value of `perm`. + + The returned tensor's dimension `i` will correspond to the input dimension + `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank + of the input tensor. Hence, by default, this operation performs a regular + matrix transpose on 2-D input Tensors. + + If conjugate is `True` and `a.dtype` is either `complex64` or `complex128` + then the values of `a` are conjugated and transposed. + + @compatibility(numpy) + In `numpy` transposes are memory-efficient constant time operations as they + simply return a new view of the same data with adjusted `strides`. + + TensorFlow does not support strides, so `transpose` returns a new tensor with + the items permuted. + @end_compatibility + + For example: + + >>> x = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> tf.transpose(x) + + + Equivalently, you could call `tf.transpose(x, perm=[1, 0])`. + + If `x` is complex, setting conjugate=True gives the conjugate transpose: + + >>> x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], + ... [4 + 4j, 5 + 5j, 6 + 6j]]) + >>> tf.transpose(x, conjugate=True) + + + 'perm' is more useful for n-dimensional tensors where n > 2: + + >>> x = tf.constant([[[ 1, 2, 3], + ... [ 4, 5, 6]], + ... [[ 7, 8, 9], + ... [10, 11, 12]]]) + + As above, simply calling `tf.transpose` will default to `perm=[2,1,0]`. + + To take the transpose of the matrices in dimension-0 (such as when you are + transposing matrices where 0 is the batch dimension), you would set + `perm=[0,2,1]`. + + >>> tf.transpose(x, perm=[0, 2, 1]) + + + Note: This has a shorthand `linalg.matrix_transpose`): + + Args: + a: A `Tensor`. + perm: A permutation of the dimensions of `a`. This should be a vector. + conjugate: Optional bool. Setting it to `True` is mathematically equivalent + to tf.math.conj(tf.transpose(input)). + name: A name for the operation (optional). + + Returns: + A transposed `Tensor`. + """ + return transpose(a=a, perm=perm, name=name, conjugate=conjugate) + + +@tf_export(v1=["transpose"]) +@dispatch.add_dispatch_support +def transpose(a, perm=None, name="transpose", conjugate=False): + """Transposes `a`. + + Permutes the dimensions according to `perm`. + + The returned tensor's dimension i will correspond to the input dimension + `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is + the rank of the input tensor. Hence, by default, this operation performs a + regular matrix transpose on 2-D input Tensors. If conjugate is True and + `a.dtype` is either `complex64` or `complex128` then the values of `a` + are conjugated and transposed. + + @compatibility(numpy) + In `numpy` transposes are memory-efficient constant time operations as they + simply return a new view of the same data with adjusted `strides`. + + TensorFlow does not support strides, so `transpose` returns a new tensor with + the items permuted. + @end_compatibility + + For example: + + ```python + x = tf.constant([[1, 2, 3], [4, 5, 6]]) + tf.transpose(x) # [[1, 4] + # [2, 5] + # [3, 6]] + + # Equivalently + tf.transpose(x, perm=[1, 0]) # [[1, 4] + # [2, 5] + # [3, 6]] + + # If x is complex, setting conjugate=True gives the conjugate transpose + x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], + [4 + 4j, 5 + 5j, 6 + 6j]]) + tf.transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j], + # [2 - 2j, 5 - 5j], + # [3 - 3j, 6 - 6j]] + + # 'perm' is more useful for n-dimensional tensors, for n > 2 + x = tf.constant([[[ 1, 2, 3], + [ 4, 5, 6]], + [[ 7, 8, 9], + [10, 11, 12]]]) + + # Take the transpose of the matrices in dimension-0 + # (this common operation has a shorthand `linalg.matrix_transpose`) + tf.transpose(x, perm=[0, 2, 1]) # [[[1, 4], + # [2, 5], + # [3, 6]], + # [[7, 10], + # [8, 11], + # [9, 12]]] + ``` + + Args: + a: A `Tensor`. + perm: A permutation of the dimensions of `a`. + name: A name for the operation (optional). + conjugate: Optional bool. Setting it to `True` is mathematically equivalent + to tf.math.conj(tf.transpose(input)). + + Returns: + A transposed `Tensor`. + """ + with ops.name_scope(name, "transpose", [a]) as name: + if not tensor_util.is_tf_type(a): + a = ops.convert_to_tensor(a, name="a") + + if conjugate and a.dtype.is_complex: + transpose_fn = gen_array_ops.conjugate_transpose + else: + transpose_fn = gen_array_ops.transpose + + if perm is not None: + return transpose_fn(a, perm, name=name) + + rank = a.shape.rank + if rank is None: + perm = gen_math_ops._range(gen_array_ops.rank(a) - 1, -1, -1) + else: + perm = np.arange(rank - 1, -1, -1, dtype=np.int32) + return transpose_fn(a, perm, name=name) + + +# pylint: disable=invalid-name +@tf_export( + "linalg.matrix_transpose", + v1=["linalg.transpose", "linalg.matrix_transpose", "matrix_transpose"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("matrix_transpose", "linalg.transpose") +def matrix_transpose(a, name="matrix_transpose", conjugate=False): + """Transposes last two dimensions of tensor `a`. + + For example: + + ```python + x = tf.constant([[1, 2, 3], [4, 5, 6]]) + tf.linalg.matrix_transpose(x) # [[1, 4], + # [2, 5], + # [3, 6]] + + x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], + [4 + 4j, 5 + 5j, 6 + 6j]]) + tf.linalg.matrix_transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j], + # [2 - 2j, 5 - 5j], + # [3 - 3j, 6 - 6j]] + + # Matrix with two batch dimensions. + # x.shape is [1, 2, 3, 4] + # tf.linalg.matrix_transpose(x) is shape [1, 2, 4, 3] + ``` + + Note that `tf.matmul` provides kwargs allowing for transpose of arguments. + This is done with minimal cost, and is preferable to using this function. E.g. + + ```python + # Good! Transpose is taken at minimal additional cost. + tf.matmul(matrix, b, transpose_b=True) + + # Inefficient! + tf.matmul(matrix, tf.linalg.matrix_transpose(b)) + ``` + + @compatibility(numpy) + In `numpy` transposes are memory-efficient constant time operations as they + simply return a new view of the same data with adjusted `strides`. + + TensorFlow does not support strides, `linalg.matrix_transpose` returns a new + tensor with the items permuted. + @end_compatibility + + Args: + a: A `Tensor` with `rank >= 2`. + name: A name for the operation (optional). + conjugate: Optional bool. Setting it to `True` is mathematically equivalent + to tf.math.conj(tf.linalg.matrix_transpose(input)). + + Returns: + A transposed batch matrix `Tensor`. + + Raises: + ValueError: If `a` is determined statically to have `rank < 2`. + """ + with ops.name_scope(name, values=[a]): + a = ops.convert_to_tensor(a, name="a") + + # If we know the number of dimensions (statically), we can do two things: + # 1. Check that `a` is a (batch) matrix. + # 2. Use a Python list for perm. This preserves static shape information + # and avoids extra computations. + a_shape = a.get_shape() + ndims = a_shape.ndims + if ndims is not None: + if ndims < 2: + raise ValueError("Argument `a` should be a (batch) matrix with rank " + f">= 2. Received `a` = {a} with shape: {a_shape}") + perm = list(range(ndims - 2)) + [ndims - 1] + [ndims - 2] + else: + a_rank = rank(a) + perm = concat( + (gen_math_ops._range(0, a_rank - 2, 1), [a_rank - 1, a_rank - 2]), 0) + + return transpose(a, perm=perm, conjugate=conjugate) + + +@tf_export("linalg.diag", v1=["linalg.diag", "matrix_diag"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("matrix_diag") +def matrix_diag(diagonal, + name="diag", + k=0, + num_rows=-1, + num_cols=-1, + padding_value=0, + align="RIGHT_LEFT"): + """Returns a batched diagonal tensor with given batched diagonal values. + + Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th + diagonals of a matrix, with everything else padded with `padding`. `num_rows` + and `num_cols` specify the dimension of the innermost matrix of the output. If + both are not specified, the op assumes the innermost matrix is square and + infers its size from `k` and the innermost dimension of `diagonal`. If only + one of them is specified, the op assumes the unspecified value is the smallest + possible based on other criteria. + + Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor + has rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only + one diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has + rank `r` with shape `[I, J, ..., L, num_rows, num_cols]`. + + The second innermost dimension of `diagonal` has double meaning. When `k` is + scalar or `k[0] == k[1]`, `M` is part of the batch size [I, J, ..., M], and + the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper + padding_value ; otherwise + ``` + + Otherwise, `M` is treated as the number of diagonals for the matrix in the + same batch (`M = k[1]-k[0]+1`), and the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + padding_value ; otherwise + ``` + where `d = n - m`, `diag_index = k[1] - d`, and + `index_in_diag = n - max(d, 0) + offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + For example: + + ``` + # The main diagonal. + diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4) + [5, 6, 7, 8]]) + tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4) + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]], + [[5, 0, 0, 0], + [0, 6, 0, 0], + [0, 0, 7, 0], + [0, 0, 0, 8]]] + + # A superdiagonal (per batch). + diagonal = np.array([[1, 2, 3], # Input shape: (2, 3) + [4, 5, 6]]) + tf.matrix_diag(diagonal, k = 1) + ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4) + [0, 0, 2, 0], + [0, 0, 0, 3], + [0, 0, 0, 0]], + [[0, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 0, 6], + [0, 0, 0, 0]]] + + # A tridiagonal band (per batch). + diagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3) + [1, 2, 3], + [0, 4, 5]], + [[2, 3, 0], + [6, 7, 9], + [0, 9, 1]]]) + tf.matrix_diag(diagonals, k = (-1, 1)) + ==> [[[1, 8, 0], # Output shape: (2, 3, 3) + [4, 2, 9], + [0, 5, 3]], + [[6, 2, 0], + [9, 7, 3], + [0, 1, 9]]] + + # RIGHT_LEFT alignment. + diagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3) + [1, 2, 3], + [4, 5, 0]], + [[0, 2, 3], + [6, 7, 9], + [9, 1, 0]]]) + tf.matrix_diag(diagonals, k = (-1, 1), align="RIGHT_LEFT") + ==> [[[1, 8, 0], # Output shape: (2, 3, 3) + [4, 2, 9], + [0, 5, 3]], + [[6, 2, 0], + [9, 7, 3], + [0, 1, 9]]] + + # Rectangular matrix. + diagonal = np.array([1, 2]) # Input shape: (2) + tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4) + ==> [[0, 0, 0, 0], # Output shape: (3, 4) + [1, 0, 0, 0], + [0, 2, 0, 0]] + + # Rectangular matrix with inferred num_cols and padding_value = 9. + tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9) + ==> [[9, 9], # Output shape: (3, 2) + [1, 9], + [9, 2]] + ``` + + Args: + diagonal: A `Tensor` with `rank k >= 1`. + name: A name for the operation (optional). + k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the + main diagonal, and negative value means subdiagonals. `k` can be a single + integer (for a single diagonal) or a pair of integers specifying the low + and high ends of a matrix band. `k[0]` must not be larger than `k[1]`. + num_rows: The number of rows of the output matrix. If it is not provided, + the op assumes the output matrix is a square matrix and infers the matrix + size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`. + num_cols: The number of columns of the output matrix. If it is not provided, + the op assumes the output matrix is a square matrix and infers the matrix + size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`. + padding_value: The value to fill the area outside the specified diagonal + band with. Default is 0. + align: Some diagonals are shorter than `max_diag_len` and need to be padded. + `align` is a string specifying how superdiagonals and subdiagonals should + be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" + (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" + aligns superdiagonals to the right (left-pads the row) and subdiagonals to + the left (right-pads the row). It is the packing format LAPACK uses. + cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment. + + Returns: + A Tensor. Has the same type as `diagonal`. + """ + # Special case to sidestep the tf.constant conversion error: + # TypeError: Expected bool, got 0 of type 'int' instead. + if hasattr(diagonal, "dtype") and diagonal.dtype == "bool": + padding_value = bool(padding_value) + + return gen_array_ops.matrix_diag_v3( + diagonal=diagonal, + k=k, + num_rows=num_rows, + num_cols=num_cols, + padding_value=padding_value, + align=align, + name=name) + + +@tf_export("linalg.diag_part", v1=["linalg.diag_part", "matrix_diag_part"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("matrix_diag_part") +def matrix_diag_part( + input, # pylint:disable=redefined-builtin + name="diag_part", + k=0, + padding_value=0, + align="RIGHT_LEFT"): + """Returns the batched diagonal part of a batched tensor. + + Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched + `input`. + + Assume `input` has `r` dimensions `[I, J, ..., L, M, N]`. + Let `max_diag_len` be the maximum length among all diagonals to be extracted, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + Let `num_diags` be the number of diagonals to extract, + `num_diags = k[1] - k[0] + 1`. + + If `num_diags == 1`, the output tensor is of rank `r - 1` with shape + `[I, J, ..., L, max_diag_len]` and values: + + ``` + diagonal[i, j, ..., l, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `y = max(-k[1], 0)`, `x = max(k[1], 0)`. + + Otherwise, the output tensor has rank `r` with dimensions + `[I, J, ..., L, num_diags, max_diag_len]` with values: + + ``` + diagonal[i, j, ..., l, m, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + The input must be at least a matrix. + + For example: + + ``` + input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4) + [5, 6, 7, 8], + [9, 8, 7, 6]], + [[5, 4, 3, 2], + [1, 2, 3, 4], + [5, 6, 7, 8]]]) + + # A main diagonal from each batch. + tf.linalg.diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3) + [5, 2, 7]] + + # A superdiagonal from each batch. + tf.linalg.diag_part(input, k = 1) + ==> [[2, 7, 6], # Output shape: (2, 3) + [4, 3, 8]] + + # A band from each batch. + tf.linalg.diag_part(input, k = (-1, 2)) + ==> [[[3, 8, 0], # Output shape: (2, 4, 3) + [2, 7, 6], + [1, 6, 7], + [0, 5, 8]], + [[3, 4, 0], + [4, 3, 8], + [5, 2, 7], + [0, 1, 6]]] + + # RIGHT_LEFT alignment. + tf.linalg.diag_part(input, k = (-1, 2), align="RIGHT_LEFT") + ==> [[[0, 3, 8], # Output shape: (2, 4, 3) + [2, 7, 6], + [1, 6, 7], + [5, 8, 0]], + [[0, 3, 4], + [4, 3, 8], + [5, 2, 7], + [1, 6, 0]]] + + # max_diag_len can be shorter than the main diagonal. + tf.linalg.diag_part(input, k = (-2, -1)) + ==> [[[5, 8], + [0, 9]], + [[1, 6], + [0, 5]]] + + # padding_value = 9 + tf.linalg.diag_part(input, k = (1, 3), padding_value = 9) + ==> [[[4, 9, 9], # Output shape: (2, 3, 3) + [3, 8, 9], + [2, 7, 6]], + [[2, 9, 9], + [3, 4, 9], + [4, 3, 8]]] + + ``` + + Args: + input: A `Tensor` with `rank k >= 2`. + name: A name for the operation (optional). + k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the + main diagonal, and negative value means subdiagonals. `k` can be a single + integer (for a single diagonal) or a pair of integers specifying the low + and high ends of a matrix band. `k[0]` must not be larger than `k[1]`. + padding_value: The value to fill the area outside the specified diagonal + band with. Default is 0. + align: Some diagonals are shorter than `max_diag_len` and need to be padded. + `align` is a string specifying how superdiagonals and subdiagonals should + be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" + (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" + aligns superdiagonals to the right (left-pads the row) and subdiagonals to + the left (right-pads the row). It is the packing format LAPACK uses. + cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment. + + Returns: + A Tensor containing diagonals of `input`. Has the same type as `input`. + + Raises: + InvalidArgumentError: When `k` is out of bound or when `k[0]>k[1:]`. + """ + # Special case to sidestep the tf.constant conversion error: + # TypeError: Expected bool, got 0 of type 'int' instead. + if hasattr(input, "dtype") and input.dtype == "bool": + padding_value = bool(padding_value) + + return gen_array_ops.matrix_diag_part_v3( + input=input, k=k, padding_value=padding_value, align=align, name=name) + + +@tf_export( + "linalg.tensor_diag_part", v1=["linalg.tensor_diag_part", "diag_part"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("diag_part") +def tensor_diag_part( + input, # pylint:disable=redefined-builtin + name=None): + """Returns the diagonal part of the tensor. + + This operation returns a tensor with the `diagonal` part + of the `input`. The `diagonal` part is computed as follows: + + Assume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a + tensor of rank `k` with dimensions `[D1,..., Dk]` where: + + `diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`. + + For a rank 2 tensor, `linalg.diag_part` and `linalg.tensor_diag_part` + produce the same result. For rank 3 and higher, linalg.diag_part extracts + the diagonal of each inner-most matrix in the tensor. An example where + they differ is given below. + + >>> x = [[[[1111,1112],[1121,1122]], + ... [[1211,1212],[1221,1222]]], + ... [[[2111, 2112], [2121, 2122]], + ... [[2211, 2212], [2221, 2222]]] + ... ] + >>> tf.linalg.tensor_diag_part(x) + + >>> tf.linalg.diag_part(x).shape + TensorShape([2, 2, 2]) + + Args: + input: A `Tensor` with rank `2k`. + name: A name for the operation (optional). + + Returns: + A Tensor containing diagonals of `input`. Has the same type as `input`, and + rank `k`. + """ + return gen_array_ops.diag_part(input=input, name=name) + + +@tf_export("linalg.set_diag", v1=["linalg.set_diag", "matrix_set_diag"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("matrix_set_diag") +def matrix_set_diag( + input, # pylint:disable=redefined-builtin + diagonal, + name="set_diag", + k=0, + align="RIGHT_LEFT"): + """Returns a batched matrix tensor with new batched diagonal values. + + Given `input` and `diagonal`, this operation returns a tensor with the + same shape and values as `input`, except for the specified diagonals of the + innermost matrices. These will be overwritten by the values in `diagonal`. + + `input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or + `k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`. + Otherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`. + `num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`. + `max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + + The output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`. + If `k` is scalar or `k[0] == k[1]`: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + + Otherwise, + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + where `d = n - m`, `diag_index = k[1] - d`, and + `index_in_diag = n - max(d, 0) + offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + For example: + + ``` + # The main diagonal. + input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4) + [7, 7, 7, 7], + [7, 7, 7, 7]], + [[7, 7, 7, 7], + [7, 7, 7, 7], + [7, 7, 7, 7]]]) + diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3) + [4, 5, 6]]) + tf.matrix_set_diag(input, diagonal) + ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4) + [7, 2, 7, 7], + [7, 7, 3, 7]], + [[4, 7, 7, 7], + [7, 5, 7, 7], + [7, 7, 6, 7]]] + + # A superdiagonal (per batch). + tf.matrix_set_diag(input, diagonal, k = 1) + ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4) + [7, 7, 2, 7], + [7, 7, 7, 3]], + [[7, 4, 7, 7], + [7, 7, 5, 7], + [7, 7, 7, 6]]] + + # A band of diagonals. + diagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3) + [6, 5, 8], + [1, 2, 3], + [0, 4, 5]], + [[1, 2, 0], + [5, 6, 4], + [6, 1, 2], + [0, 3, 4]]]) + tf.matrix_set_diag(input, diagonals, k = (-1, 2)) + ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4) + [4, 2, 5, 1], + [7, 5, 3, 8]], + [[6, 5, 1, 7], + [3, 1, 6, 2], + [7, 4, 2, 4]]] + + # RIGHT_LEFT alignment. + diagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3) + [6, 5, 8], + [1, 2, 3], + [4, 5, 0]], + [[0, 1, 2], + [5, 6, 4], + [6, 1, 2], + [3, 4, 0]]]) + tf.matrix_set_diag(input, diagonals, k = (-1, 2), align="RIGHT_LEFT") + ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4) + [4, 2, 5, 1], + [7, 5, 3, 8]], + [[6, 5, 1, 7], + [3, 1, 6, 2], + [7, 4, 2, 4]]] + + ``` + + Args: + input: A `Tensor` with rank `k + 1`, where `k >= 1`. + diagonal: A `Tensor` with rank `k`, when `d_lower == d_upper`, or `k + 1`, + otherwise. `k >= 1`. + name: A name for the operation (optional). + k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the + main diagonal, and negative value means subdiagonals. `k` can be a single + integer (for a single diagonal) or a pair of integers specifying the low + and high ends of a matrix band. `k[0]` must not be larger than `k[1]`. + align: Some diagonals are shorter than `max_diag_len` and need to be padded. + `align` is a string specifying how superdiagonals and subdiagonals should + be aligned, respectively. There are four possible alignments: "RIGHT_LEFT" + (default), "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" + aligns superdiagonals to the right (left-pads the row) and subdiagonals to + the left (right-pads the row). It is the packing format LAPACK uses. + cuSPARSE uses "LEFT_RIGHT", which is the opposite alignment. + """ + return gen_array_ops.matrix_set_diag_v3( + input=input, diagonal=diagonal, k=k, align=align, name=name) + + +# pylint: enable=invalid-name + + +def _constant_if_small(value, shape, dtype, name, layout=None): + try: + if np.prod(shape) < 1000: + return d_api.call_with_layout( + constant, layout, value, shape=shape, dtype=dtype, name=name + ) + except (NotImplementedError, TypeError): + # Happens when shape is a Tensor, list with Tensor elements, etc. + pass + return None + + +def _tag_zeros_tensor(fun): + """ Tags the result of function by setting _is_zeros_tensor attribute. + + This is useful to compute Hessians of fused ops such as cross_entropy. + """ + + def wrapped(*args, **kwargs): + tensor = fun(*args, **kwargs) + tensor._is_zeros_tensor = True + return tensor + + return tf_decorator.make_decorator(fun, wrapped) + + +@tf_export("zeros") +@dispatch.add_dispatch_support +@_tag_zeros_tensor +def zeros(shape, dtype=dtypes.float32, name=None, layout=None): + """Creates a tensor with all elements set to zero. + + See also `tf.zeros_like`, `tf.ones`, `tf.fill`, `tf.eye`. + + This operation returns a tensor of type `dtype` with shape `shape` and + all elements set to zero. + + >>> tf.zeros([3, 4], tf.int32) + + + Args: + shape: A `list` of integers, a `tuple` of integers, or a 1-D `Tensor` of + type `int32`. + dtype: The DType of an element in the resulting `Tensor`. + name: Optional string. A name for the operation. + layout: Optional, `tf.experimental.dtensor.Layout`. If provided, the result + is a [DTensor](https://www.tensorflow.org/guide/dtensor_overview) with the + provided layout. + + Returns: + A `Tensor` with all elements set to zero. + """ + dtype = dtypes.as_dtype(dtype).base_dtype + with ops.name_scope(name, "zeros", [shape]) as name: + if dtype == dtypes.bool: + zero = False + elif dtype == dtypes.string: + zero = "" + elif dtype.is_quantized: + zero = np.zeros([]).astype(dtype.as_numpy_dtype) + else: + zero = 0 + + if not isinstance(shape, tensor_lib.Tensor): + try: + if not context.executing_eagerly(): + # Create a constant if it won't be very big. Otherwise, create a fill + # op to prevent serialized GraphDefs from becoming too large. + output = _constant_if_small(zero, shape, dtype, name, layout=layout) + if output is not None: + return output + + # Go through tensor shapes to get int64-if-needed semantics + shape = constant_op._tensor_shape_tensor_conversion_function( + tensor_shape.TensorShape(shape)) + except (TypeError, ValueError, errors.UnimplementedError): + # Happens when shape is a list with tensor elements + shape = ops.convert_to_tensor(shape, dtype=dtypes.int32) + if not shape._shape_tuple(): + shape = reshape(shape, [-1]) # Ensure it's a vector + output = fill(shape, constant(zero, dtype=dtype), name=name, layout=layout) + assert output.dtype.base_dtype == dtype + return output + + +@tf_export(v1=["zeros_like"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def zeros_like(tensor, dtype=None, name=None, optimize=True): + """Creates a tensor with all elements set to zero. + + See also `tf.zeros`. + + Given a single tensor (`tensor`), this operation returns a tensor of the + same type and shape as `tensor` with all elements set to zero. Optionally, + you can use `dtype` to specify a new type for the returned tensor. + + Examples: + + >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> tf.zeros_like(tensor) + + + >>> tf.zeros_like(tensor, dtype=tf.float32) + + + Args: + tensor: A `Tensor`. + dtype: A type for the returned `Tensor`. Must be `float16`, `float32`, + `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, + `complex64`, `complex128`, `bool` or `string`. (optional) + name: A name for the operation (optional). + optimize: if `True`, attempt to statically determine the shape of `tensor` + and encode it as a constant. (optional, defaults to `True`) + + Returns: + A `Tensor` with all elements set to zero. + """ + return zeros_like_impl(tensor, dtype, name, optimize) + + +@tf_export("zeros_like", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def zeros_like_v2( + input, # pylint: disable=redefined-builtin + dtype=None, + name=None, + layout=None, +): + """Creates a tensor with all elements set to zero. + + See also `tf.zeros`. + + Given a single tensor or array-like object (`input`), this operation returns + a tensor of the same type and shape as `input` with all elements set to zero. + Optionally, you can use `dtype` to specify a new type for the returned tensor. + + Note that the layout of the input tensor is not preserved if the op + is used inside tf.function. To obtain a tensor with the same layout as the + input, chain the returned value to a `dtensor.relayout_like`. + + Examples: + + >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> tf.zeros_like(tensor) + + + >>> tf.zeros_like(tensor, dtype=tf.float32) + + + >>> tf.zeros_like([[1, 2, 3], [4, 5, 6]]) + + + Args: + input: A `Tensor` or array-like object. + dtype: A type for the returned `Tensor`. Must be `float16`, `float32`, + `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, + `complex64`, `complex128`, `bool` or `string` (optional). + name: A name for the operation (optional). + layout: Optional, `tf.experimental.dtensor.Layout`. If provided, the result + is a [DTensor](https://www.tensorflow.org/guide/dtensor_overview) with the + provided layout. + + Returns: + A `Tensor` with all elements set to zero. + """ + return zeros_like_impl(input, dtype, name, optimize=True, layout=layout) + + +def array_like_impl( + array_fn, array_like_fn, tensor, dtype, name, optimize=True, layout=None +): + """Internal implementation for ones_like and zeros_like API calls.""" + # Note: the output follows the layout argument, not the layout of the input. + if not tensor_util.is_tf_type(tensor): + tensor = ops.convert_to_tensor(tensor, name="tensor") + tensor_shape = tensor.shape + tensor_dtype = tensor.dtype + + if context.executing_eagerly(): + if dtype is not None and dtype != tensor_dtype: + return array_fn( + shape_internal(tensor, optimize=optimize), + dtype=dtype, + name=name, + layout=layout, + ) + return d_api.call_with_layout(array_like_fn, layout, tensor, name=name) + + # For now, variant types must be created via array_like_fn; as we need to + # pass the input variant object to the proper array_fn callback. + + if ( + optimize + and tensor_shape.is_fully_defined() + and tensor_dtype != dtypes.variant + ): + # We can produce a result tensor independent of the value of 'tensor', + # since the shape is known statically. + return array_fn( + tensor_shape, dtype=dtype or tensor_dtype, name=name, layout=layout + ) + + if dtype is not None and dtype != tensor_dtype and dtype != dtypes.variant: + return array_fn( + shape_internal(tensor, optimize=optimize), + dtype=dtype, + name=name, + layout=layout, + ) + return d_api.call_with_layout(array_like_fn, layout, tensor, name=name) + + +@_tag_zeros_tensor +def zeros_like_impl(tensor, dtype, name, optimize=True, layout=None): + """Internal implementation for the v1/v2 zeros_like API calls.""" + with ops.name_scope(name, "zeros_like", [tensor]) as name: + return array_like_impl( + zeros, + gen_array_ops.zeros_like, + tensor, + dtype, + name, + optimize=optimize, + layout=layout, + ) + + +@tf_export(v1=["ones_like"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def ones_like(tensor, dtype=None, name=None, optimize=True): + """Creates a tensor with all elements set to 1. + + See also `tf.ones`. + + Given a single tensor (`tensor`), this operation returns a tensor of the same + type and shape as `tensor` with all elements set to 1. Optionally, you can + specify a new type (`dtype`) for the returned tensor. + + For example: + + ```python + tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) + tf.ones_like(tensor) # [[1, 1, 1], [1, 1, 1]] + ``` + + Args: + tensor: A `Tensor`. + dtype: A type for the returned `Tensor`. Must be `float32`, `float64`, + `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`, + `complex128` or `bool`. + name: A name for the operation (optional). + optimize: if true, attempt to statically determine the shape of 'tensor' and + encode it as a constant. + + Returns: + A `Tensor` with all elements set to 1. + """ + return ones_like_impl(tensor, dtype, name, optimize) + + +@tf_export("ones_like", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def ones_like_v2( + input, # pylint: disable=redefined-builtin + dtype=None, + name=None, + layout=None, +): + """Creates a tensor of all ones that has the same shape as the input. + + See also `tf.ones`. + + Given a single tensor (`tensor`), this operation returns a tensor of the + same type and shape as `tensor` with all elements set to 1. Optionally, + you can use `dtype` to specify a new type for the returned tensor. + + For example: + + >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> tf.ones_like(tensor) + + + Note that the layout of the input tensor is not preserved if the op + is used inside tf.function. To obtain a tensor with the same layout as the + input, chain the returned value to a `dtensor.relayout_like`. + + Args: + input: A `Tensor`. + dtype: A type for the returned `Tensor`. Must be `float16`, `float32`, + `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, + `complex64`, `complex128`, `bool` or `string`. + name: A name for the operation (optional). + layout: Optional, `tf.experimental.dtensor.Layout`. If provided, the result + is a [DTensor](https://www.tensorflow.org/guide/dtensor_overview) with the + provided layout. + + Returns: + A `Tensor` with all elements set to one. + """ + with ops.name_scope(name, "ones_like", [input]) as name: + return array_like_impl( + ones, + gen_array_ops.ones_like, + input, + dtype, + name, + optimize=True, + layout=layout, + ) + + +def ones_like_impl(tensor, dtype, name, optimize=True, layout=None): + """Internal implementation for the v1/v2 ones_like API calls.""" + with ops.name_scope(name, "ones_like", [tensor]) as name: + + tensor = ops.convert_to_tensor(tensor, name="tensor") + ones_shape = shape_internal(tensor, optimize=optimize) + if dtype is None: + dtype = tensor.dtype + ret = ones(ones_shape, dtype=dtype, name=name, layout=layout) + if not context.executing_eagerly(): + ret.set_shape(tensor.get_shape()) + return ret + + +@tf_export("ones") +@dispatch.add_dispatch_support +def ones(shape, dtype=dtypes.float32, name=None, layout=None): + """Creates a tensor with all elements set to one (1). + + See also `tf.ones_like`, `tf.zeros`, `tf.fill`, `tf.eye`. + + This operation returns a tensor of type `dtype` with shape `shape` and + all elements set to one. + + >>> tf.ones([3, 4], tf.int32) + + + Args: + shape: A `list` of integers, a `tuple` of integers, or a 1-D `Tensor` of + type `int32`. + dtype: Optional DType of an element in the resulting `Tensor`. Default is + `tf.float32`. + name: Optional string. A name for the operation. + layout: Optional, `tf.experimental.dtensor.Layout`. If provided, the result + is a [DTensor](https://www.tensorflow.org/guide/dtensor_overview) with the + provided layout. + + Returns: + A `Tensor` with all elements set to one (1). + """ + dtype = dtypes.as_dtype(dtype).base_dtype + with ops.name_scope(name, "ones", [shape]) as name: + if dtype == dtypes.bool: + one = True + elif dtype.is_quantized: + one = np.ones([]).astype(dtype.as_numpy_dtype) + else: + one = 1 + if not isinstance(shape, tensor_lib.Tensor): + try: + if not context.executing_eagerly(): + # Create a constant if it won't be very big. Otherwise, create a fill + # op to prevent serialized GraphDefs from becoming too large. + output = _constant_if_small(one, shape, dtype, name, layout=layout) + if output is not None: + return output + + # Go through tensor shapes to get int64-if-needed semantics + shape = constant_op._tensor_shape_tensor_conversion_function( + tensor_shape.TensorShape(shape)) + except (TypeError, ValueError): + # Happens when shape is a list with tensor elements + shape = ops.convert_to_tensor(shape, dtype=dtypes.int32) + if not shape._shape_tuple(): + shape = reshape(shape, [-1]) # Ensure it's a vector + output = fill(shape, constant(one, dtype=dtype), name=name, layout=layout) + assert output.dtype.base_dtype == dtype + return output + + +@tf_export(v1=["placeholder"]) +def placeholder(dtype, shape=None, name=None): + """Inserts a placeholder for a tensor that will be always fed. + + **Important**: This tensor will produce an error if evaluated. Its value must + be fed using the `feed_dict` optional argument to `Session.run()`, + `Tensor.eval()`, or `Operation.run()`. + + For example: + + ```python + x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024)) + y = tf.matmul(x, x) + + with tf.compat.v1.Session() as sess: + print(sess.run(y)) # ERROR: will fail because x was not fed. + + rand_array = np.random.rand(1024, 1024) + print(sess.run(y, feed_dict={x: rand_array})) # Will succeed. + ``` + + Args: + dtype: The type of elements in the tensor to be fed. + shape: The shape of the tensor to be fed (optional). If the shape is not + specified, you can feed a tensor of any shape. + name: A name for the operation (optional). + + Returns: + A `Tensor` that may be used as a handle for feeding a value, but not + evaluated directly. + + Raises: + RuntimeError: if eager execution is enabled + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In TF2, you can just pass tensors directly + into ops and layers. If you want to explicitly set up your inputs, also see + [Keras functional API](https://www.tensorflow.org/guide/keras/functional) on + how to use `tf.keras.Input` to replace `tf.compat.v1.placeholder`. + `tf.function` arguments also do the job of `tf.compat.v1.placeholder`. + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError("tf.placeholder() is not compatible with " + "eager execution.") + + return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name) + + +@tf_export(v1=["placeholder_with_default"]) +def placeholder_with_default(input, shape, name=None): # pylint: disable=redefined-builtin + """A placeholder op that passes through `input` when its output is not fed. + + @compatibility(TF2) + This API is strongly discouraged for use with eager execution and + `tf.function`. The primary use of this API is for testing computation wrapped + within a `tf.function` where the input tensors might not have statically known + fully-defined shapes. The same can be achieved by creating a + [concrete function]( + https://www.tensorflow.org/guide/function#obtaining_concrete_functions) + from the `tf.function` with a `tf.TensorSpec` input which has partially + defined shapes. For example, the code + + >>> @tf.function + ... def f(): + ... x = tf.compat.v1.placeholder_with_default( + ... tf.constant([[1., 2., 3.], [4., 5., 6.]]), [None, 3]) + ... y = tf.constant([[1.],[2.], [3.]]) + ... z = tf.matmul(x, y) + ... assert z.shape[0] == None + ... assert z.shape[1] == 1 + + >>> f() + + can easily be replaced by + + >>> @tf.function + ... def f(x): + ... y = tf.constant([[1.],[2.], [3.]]) + ... z = tf.matmul(x, y) + ... assert z.shape[0] == None + ... assert z.shape[1] == 1 + + >>> g = f.get_concrete_function(tf.TensorSpec([None, 3])) + + You can learn more about `tf.function` at [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + + Args: + input: A `Tensor`. The default value to produce when output is not fed. + shape: A `tf.TensorShape` or list of `int`s. The (possibly partial) shape of + the tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + return gen_array_ops.placeholder_with_default(input, shape, name) + + +@tf_export(v1=["sparse.placeholder", "sparse_placeholder"]) +@deprecation.deprecated_endpoints("sparse_placeholder") +def sparse_placeholder(dtype, shape=None, name=None): + """Inserts a placeholder for a sparse tensor that will be always fed. + + **Important**: This sparse tensor will produce an error if evaluated. + Its value must be fed using the `feed_dict` optional argument to + `Session.run()`, `Tensor.eval()`, or `Operation.run()`. + + For example: + + ```python + x = tf.compat.v1.sparse.placeholder(tf.float32) + y = tf.sparse.reduce_sum(x) + + with tf.compat.v1.Session() as sess: + print(sess.run(y)) # ERROR: will fail because x was not fed. + + indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64) + values = np.array([1.0, 2.0], dtype=np.float32) + shape = np.array([7, 9, 2], dtype=np.int64) + print(sess.run(y, feed_dict={ + x: tf.compat.v1.SparseTensorValue(indices, values, shape)})) # Will + succeed. + print(sess.run(y, feed_dict={ + x: (indices, values, shape)})) # Will succeed. + + sp = tf.sparse.SparseTensor(indices=indices, values=values, + dense_shape=shape) + sp_value = sp.eval(session=sess) + print(sess.run(y, feed_dict={x: sp_value})) # Will succeed. + ``` + + + Args: + dtype: The type of `values` elements in the tensor to be fed. + shape: The shape of the tensor to be fed (optional). If the shape is not + specified, you can feed a sparse tensor of any shape. + name: A name for prefixing the operations (optional). + + Returns: + A `SparseTensor` that may be used as a handle for feeding a value, but not + evaluated directly. + + Raises: + RuntimeError: if eager execution is enabled + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In TF2, you can just pass tensors directly + into ops and layers. If you want to explicitly set up your inputs, also see + [Keras functional API](https://www.tensorflow.org/guide/keras/functional) on + how to use `tf.keras.Input` to replace `tf.compat.v1.sparse_placeholder`. + `tf.function` arguments also do the job of `tf.compat.v1.sparse_placeholder`. + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError("`sparse_placeholder` is not compatible with " + "eager execution.") + + shape_name = (name + "/shape") if name is not None else None + default_shape_name = (name + "/shape_default") if name is not None else None + if shape is None: + rank = None + dense_shape = placeholder(dtypes.int64, shape=[rank], name=shape_name) + dense_shape_default = tensor_util.constant_value_as_shape(dense_shape) + else: + if isinstance(shape, tensor_lib.Tensor): + rank = shape.get_shape()[0] + dense_shape_default = tensor_util.constant_value_as_shape(shape) + else: + rank = len(shape) + # determine the shape, to override the `.shape` property of the + # `SparseTensor` + dense_shape_default = tensor_shape.TensorShape( + tuple(None if dim == -1 else dim for dim in shape)) + shape = tuple(tensor_shape.dimension_value(dim) for dim in shape) + shape = tuple(-1 if dim is None else dim for dim in shape) + shape = ops.convert_to_tensor( + shape, dtype=dtypes.int64, name=default_shape_name) + + # `dense_shape` needs to be feedable (for users that treat this as an + # actual placeholder). `constant_value_as_shape` sets constants to + # not-feedable. placeholder_with_default works, but blocks `SparseTensor` + # from reading the default value back out. + dense_shape = placeholder_with_default( + shape, shape=shape.shape, name=shape_name) + + result = sparse_tensor.SparseTensor( + values=placeholder( + dtype, + shape=[None], + name=(name + "/values") if name is not None else None), + indices=placeholder( + dtypes.int64, + shape=[None, rank], + name=(name + "/indices") if name is not None else None), + dense_shape=dense_shape) + + # Now the SparseTensor.shape is a list of `None`s, since it couldn't read the + # default shape out of the placeholder. Override that + # shape to be the value determined here, so partial shapes can be + # propagated. + result.set_shape(dense_shape_default) + return result + +# pylint: enable=redefined-outer-name + + +@tf_export("pad", v1=[]) +@dispatch.add_dispatch_support +def pad_v2(tensor, paddings, mode="CONSTANT", constant_values=0, name=None): + """Pads a tensor. + + This operation pads a `tensor` according to the `paddings` you specify. + `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of + `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how + many values to add before the contents of `tensor` in that dimension, and + `paddings[D, 1]` indicates how many values to add after the contents of + `tensor` in that dimension. If `mode` is "REFLECT" then both `paddings[D, 0]` + and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If + `mode` is "SYMMETRIC" then both `paddings[D, 0]` and `paddings[D, 1]` must be + no greater than `tensor.dim_size(D)`. + + The padded size of each dimension D of the output is: + + `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]` + + For example: + + ```python + t = tf.constant([[1, 2, 3], [4, 5, 6]]) + paddings = tf.constant([[1, 1,], [2, 2]]) + # 'constant_values' is 0. + # rank of 't' is 2. + tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0], + # [0, 0, 1, 2, 3, 0, 0], + # [0, 0, 4, 5, 6, 0, 0], + # [0, 0, 0, 0, 0, 0, 0]] + + tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4], + # [3, 2, 1, 2, 3, 2, 1], + # [6, 5, 4, 5, 6, 5, 4], + # [3, 2, 1, 2, 3, 2, 1]] + + tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2], + # [2, 1, 1, 2, 3, 3, 2], + # [5, 4, 4, 5, 6, 6, 5], + # [5, 4, 4, 5, 6, 6, 5]] + ``` + + Args: + tensor: A `Tensor`. + paddings: A `Tensor` of type `int32`. + mode: One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive) + constant_values: In "CONSTANT" mode, the scalar pad value to use. Must be + same type as `tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + + Raises: + ValueError: When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC". + """ + return pad(tensor, paddings, mode, name, constant_values) + + +@tf_export(v1=["pad"]) +@dispatch.add_dispatch_support +def pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0): # pylint: disable=invalid-name + """Pads a tensor. + + This operation pads a `tensor` according to the `paddings` you specify. + `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of + `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how + many values to add before the contents of `tensor` in that dimension, and + `paddings[D, 1]` indicates how many values to add after the contents of + `tensor` in that dimension. If `mode` is "REFLECT" then both `paddings[D, 0]` + and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If + `mode` is "SYMMETRIC" then both `paddings[D, 0]` and `paddings[D, 1]` must be + no greater than `tensor.dim_size(D)`. + + The padded size of each dimension D of the output is: + + `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]` + + For example: + + ```python + t = tf.constant([[1, 2, 3], [4, 5, 6]]) + paddings = tf.constant([[1, 1,], [2, 2]]) + # 'constant_values' is 0. + # rank of 't' is 2. + tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0], + # [0, 0, 1, 2, 3, 0, 0], + # [0, 0, 4, 5, 6, 0, 0], + # [0, 0, 0, 0, 0, 0, 0]] + + tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4], + # [3, 2, 1, 2, 3, 2, 1], + # [6, 5, 4, 5, 6, 5, 4], + # [3, 2, 1, 2, 3, 2, 1]] + + tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2], + # [2, 1, 1, 2, 3, 3, 2], + # [5, 4, 4, 5, 6, 6, 5], + # [5, 4, 4, 5, 6, 6, 5]] + ``` + + Args: + tensor: A `Tensor`. + paddings: A `Tensor` of type `int32`. + mode: One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive) + name: A name for the operation (optional). + constant_values: In "CONSTANT" mode, the scalar pad value to use. Must be + same type as `tensor`. + + Returns: + A `Tensor`. Has the same type as `tensor`. + + Raises: + ValueError: When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC". + """ + + # Convert lower/mixed case to upper for NumPy compatibility + # NumPy uses all lower-case modes. + mode = mode.upper() + if mode == "CONSTANT": + # TODO(rjryan): Once the forward compatibility period (3 weeks) have passed + # remove the "Pad" fallback here. + if (not tensor_util.is_tf_type(constant_values) and + np.ndim(constant_values) == 0 and + constant_values == np.zeros_like(constant_values)): + result = gen_array_ops.pad(tensor, paddings, name=name) + else: + result = gen_array_ops.pad_v2( + tensor, paddings, constant_values, name=name) + elif mode == "REFLECT": + result = gen_array_ops.mirror_pad( + tensor, paddings, mode="REFLECT", name=name) + elif mode == "SYMMETRIC": + result = gen_array_ops.mirror_pad( + tensor, paddings, mode="SYMMETRIC", name=name) + else: + raise ValueError("Value of argument `mode` expected to be " + """one of "CONSTANT", "REFLECT", or "SYMMETRIC". """ + f"Received `mode` = {mode}") + + # Restore shape information where possible. + if not context.executing_eagerly(): + paddings_constant = _get_paddings_constant(paddings) + input_shape = ( + tensor_shape.TensorShape(tensor.shape) + if isinstance(tensor, tensor_lib.Tensor) else result.op.inputs[0].shape) + if (input_shape.ndims is not None and + not result.shape.is_fully_defined() and paddings_constant is not None): + new_shape = [] + for padding, dim in zip(paddings_constant, input_shape.as_list()): + if padding is None or dim is None or any((x is None for x in padding)): + new_shape.append(None) + else: + new_shape.append(sum(padding) + dim) + result.set_shape(new_shape) + + return result + + +def _get_paddings_constant(paddings): + """Helper to get the constant values of the paddings arg to pad(). + + Used under V1 graph mode to facilitate computation of the shape of the output + tensor of `pad()`. + + Args: + paddings: The same paddings arg as passed to pad(). Can be a Tensor, or + a nested list or tuple of Tensor and/or numbers. + + Returns: + A nested list or numbers or `None`, in which `None` indicates unknown + padding size. + """ + if isinstance(paddings, tensor_lib.Tensor): + return tensor_util.constant_value(paddings, partial=True) + elif isinstance(paddings, (list, tuple)): + return [_get_paddings_constant(x) for x in paddings] + else: + return paddings + + +@tf_export("meshgrid") +@dispatch.add_dispatch_support +def meshgrid(*args, **kwargs): + """Broadcasts parameters for evaluation on an N-D grid. + + Given N one-dimensional coordinate arrays `*args`, returns a list `outputs` + of N-D coordinate arrays for evaluating expressions on an N-D grid. + + Notes: + + `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions. + When the `indexing` argument is set to 'xy' (the default), the broadcasting + instructions for the first two dimensions are swapped. + + Examples: + + Calling `X, Y = meshgrid(x, y)` with the tensors + + ```python + x = [1, 2, 3] + y = [4, 5, 6] + X, Y = tf.meshgrid(x, y) + # X = [[1, 2, 3], + # [1, 2, 3], + # [1, 2, 3]] + # Y = [[4, 4, 4], + # [5, 5, 5], + # [6, 6, 6]] + ``` + + Args: + *args: `Tensor`s with rank 1. + **kwargs: + - indexing: Either 'xy' or 'ij' (optional, default: 'xy'). + - name: A name for the operation (optional). + + Returns: + outputs: A list of N `Tensor`s with rank N. + + Raises: + TypeError: When no keyword arguments (kwargs) are passed. + ValueError: When indexing keyword argument is not one of `xy` or `ij`. + """ + + indexing = kwargs.pop("indexing", "xy") + name = kwargs.pop("name", "meshgrid") + if kwargs: + key = list(kwargs.keys())[0] + raise TypeError("'{}' is an invalid keyword argument " + "for this function".format(key)) + + if indexing not in ("xy", "ij"): + raise ValueError("Argument `indexing` parameter must be either " + f"'xy' or 'ij', got '{indexing}'") + + with ops.name_scope(name, "meshgrid", args) as name: + ndim = len(args) + s0 = (1,) * ndim + + if not ndim: + return [] + + # Prepare reshape by inserting dimensions with size 1 where needed + output = [] + for i, x in enumerate(args): + output.append( + reshape(array_ops_stack.stack(x), (s0[:i] + (-1,) + s0[i + 1::]))) + # Create parameters for broadcasting each tensor to the full size + shapes = [size(x) for x in args] + + output_dtype = ops.convert_to_tensor(args[0]).dtype.base_dtype + + if indexing == "xy" and ndim > 1: + output[0] = reshape(output[0], (1, -1) + (1,) * (ndim - 2)) + output[1] = reshape(output[1], (-1, 1) + (1,) * (ndim - 2)) + shapes[0], shapes[1] = shapes[1], shapes[0] + + # TODO(nolivia): improve performance with a broadcast + mult_fact = ones(shapes, output_dtype) + return [x * mult_fact for x in output] + + +NEW_AXIS = -1 +SHRINK_AXIS = -2 + + +# PEP-8 naming +# pylint: disable=invalid-name,redefined-outer-name +def _compute_size_of_strided_dim(shrink, spec, size): + """Computes the size of a single strided slice dimension.""" + + unknown = None # Document what None means here. + use_full_range = None # Document other use of None. + # if this is a shrink axis (i.e. a non-range index) + # it either will produce an error or return 1 + if shrink: + return 1 + if size is unknown or size.value is unknown: + return unknown + size = size.value + stride = spec.step + if stride is not unknown: + if stride == 0: + return unknown + stride = spec.step + valid_range = [0, size] if stride > 0 else [-1, size - 1] + + # PEP-8 naming + # pylint: disable=invalid-name + def canonical(x, c): + if x is use_full_range: + return valid_range[c] if stride > 0 else valid_range[(c + 1) & 1] + else: + x_fwd = size + x if x < 0 else x # make negative indices positive + return max(valid_range[0], min(valid_range[1], x_fwd)) + + begin = canonical(spec.start, 0) + end = canonical(spec.stop, 1) + interval_length = end - begin + if interval_length == 0 or ((interval_length < 0) != (stride < 0)): + return 0 + else: + remainder = 1 if interval_length % stride != 0 else 0 + return interval_length // stride + remainder + else: + return unknown # unknown because stride is unknown + + +def _TileGradShape(op: ops.Operation): + """Shape function for the TileGrad op.""" + multiples_shape = op.inputs[1].get_shape().with_rank(1) + input_shape = op.inputs[0].get_shape().with_rank(multiples_shape[0]) + # NOTE(mrry): Represent `multiples` as a `TensorShape` because (i) + # it is a vector of non-negative integers, and (ii) doing so allows + # us to handle partially-known multiples. + multiples = tensor_util.constant_value_as_shape(op.inputs[1]).with_rank( + input_shape.ndims) + if multiples.ndims is None: + return [tensor_shape.unknown_shape()] + else: + output_dims = [] + for dim, multiple in zip(input_shape.dims, multiples.dims): + output_dims.append(dim // multiple) + return [tensor_shape.TensorShape(output_dims)] + + +@tf_export("edit_distance") +@dispatch.add_dispatch_support +def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"): + """Computes the Levenshtein distance between sequences. + + This operation takes variable-length sequences (`hypothesis` and `truth`), + each provided as a `SparseTensor`, and computes the Levenshtein distance. + You can normalize the edit distance by length of `truth` by setting + `normalize` to true. + + For example: + + Given the following input, + * `hypothesis` is a `tf.SparseTensor` of shape `[2, 1, 1]` + * `truth` is a `tf.SparseTensor` of shape `[2, 2, 2]` + + >>> hypothesis = tf.SparseTensor( + ... [[0, 0, 0], + ... [1, 0, 0]], + ... ["a", "b"], + ... (2, 1, 1)) + >>> truth = tf.SparseTensor( + ... [[0, 1, 0], + ... [1, 0, 0], + ... [1, 0, 1], + ... [1, 1, 0]], + ... ["a", "b", "c", "a"], + ... (2, 2, 2)) + >>> tf.edit_distance(hypothesis, truth, normalize=True) + + + The operation returns a dense Tensor of shape `[2, 2]` with + edit distances normalized by `truth` lengths. + + **Note**: It is possible to calculate edit distance between two + sparse tensors with variable-length values. However, attempting to create + them while eager execution is enabled will result in a `ValueError`. + + For the following inputs, + + ```python + # 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values: + # (0,0) = ["a"] + # (1,0) = ["b"] + hypothesis = tf.sparse.SparseTensor( + [[0, 0, 0], + [1, 0, 0]], + ["a", "b"], + (2, 1, 1)) + + # 'truth' is a tensor of shape `[2, 2]` with variable-length values: + # (0,0) = [] + # (0,1) = ["a"] + # (1,0) = ["b", "c"] + # (1,1) = ["a"] + truth = tf.sparse.SparseTensor( + [[0, 1, 0], + [1, 0, 0], + [1, 0, 1], + [1, 1, 0]], + ["a", "b", "c", "a"], + (2, 2, 2)) + + normalize = True + + # The output would be a dense Tensor of shape `(2,)`, with edit distances + normalized by 'truth' lengths. + # output => array([0., 0.5], dtype=float32) + ``` + + Args: + hypothesis: A `SparseTensor` containing hypothesis sequences. + truth: A `SparseTensor` containing truth sequences. + normalize: A `bool`. If `True`, normalizes the Levenshtein distance by + length of `truth.` + name: A name for the operation (optional). + + Returns: + A dense `Tensor` with rank `R - 1`, where R is the rank of the + `SparseTensor` inputs `hypothesis` and `truth`. + + Raises: + TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`. + """ + if not isinstance( + hypothesis, + (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + raise TypeError("Hypothesis must be a SparseTensor.") + if not isinstance( + truth, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): + raise TypeError("Truth must be a SparseTensor.") + + return gen_array_ops.edit_distance( + hypothesis.indices, + hypothesis.values, + hypothesis.dense_shape, + truth.indices, + truth.values, + truth.dense_shape, + normalize=normalize, + name=name) + + +@ops.RegisterGradient("FakeQuantWithMinMaxArgs") +def _FakeQuantWithMinMaxArgsGradient(op: ops.Operation, grad): + """Gradient for FakeQuantWithMinMaxArgs op.""" + return fake_quant_with_min_max_args_gradient( + grad, + op.inputs[0], + min=op.get_attr("min"), + max=op.get_attr("max"), + num_bits=op.get_attr("num_bits"), + narrow_range=op.get_attr("narrow_range")) + + +@ops.RegisterGradient("FakeQuantWithMinMaxVars") +def _FakeQuantWithMinMaxVarsGradient(op: ops.Operation, grad): + """Gradient for FakeQuantWithMinMaxVars op.""" + return fake_quant_with_min_max_vars_gradient( + grad, + op.inputs[0], + op.inputs[1], + op.inputs[2], + num_bits=op.get_attr("num_bits"), + narrow_range=op.get_attr("narrow_range")) + + +@ops.RegisterGradient("FakeQuantWithMinMaxVarsPerChannel") +def _FakeQuantWithMinMaxVarsPerChannelGradient(op: ops.Operation, grad): + """Gradient for FakeQuantWithMinMaxVarsPerChannel op.""" + return fake_quant_with_min_max_vars_per_channel_gradient( + grad, + op.inputs[0], + op.inputs[1], + op.inputs[2], + num_bits=op.get_attr("num_bits"), + narrow_range=op.get_attr("narrow_range")) + + +@ops.RegisterGradient("QuantizeAndDequantizeV4") +def _QuantizeAndDequantizeV4Grad(op: ops.Operation, grad): + """Gradient for QuantizeAndDequantizeV4 op.""" + return quantize_and_dequantize_v4_grad( + grad, + op.inputs[0], + op.inputs[1], + op.inputs[2], + axis=op.get_attr("axis")) + + +@ops.RegisterGradient("QuantizeAndDequantizeV4Grad") +def _QuantizeAndDequantizeV4GradGrad(op: ops.Operation, grad): + """Gradient for QuantizeAndDequantizeV4Grad op.""" + return _QuantizeAndDequantizeV4Grad(op, grad) + + +@tf_export("required_space_to_batch_paddings") +def required_space_to_batch_paddings(input_shape, + block_shape, + base_paddings=None, + name=None): + """Calculate padding required to make block_shape divide input_shape. + + This function can be used to calculate a suitable paddings argument for use + with space_to_batch_nd and batch_to_space_nd. + + Args: + input_shape: int32 Tensor of shape [N]. + block_shape: int32 Tensor of shape [N]. + base_paddings: Optional int32 Tensor of shape [N, 2]. Specifies the minimum + amount of padding to use. All elements must be >= 0. If not specified, + defaults to 0. + name: string. Optional name prefix. + + Returns: + (paddings, crops), where: + + `paddings` and `crops` are int32 Tensors of rank 2 and shape [N, 2] + satisfying: + + paddings[i, 0] = base_paddings[i, 0]. + 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shape[i] + (input_shape[i] + paddings[i, 0] + paddings[i, 1]) % block_shape[i] == 0 + + crops[i, 0] = 0 + crops[i, 1] = paddings[i, 1] - base_paddings[i, 1] + + Raises: ValueError if called with incompatible shapes. + """ + with ops.name_scope(name, "required_space_to_batch_paddings", + [input_shape, block_shape]): + input_shape = ops.convert_to_tensor( + input_shape, dtype=dtypes.int32, name="input_shape") + block_shape = ops.convert_to_tensor( + block_shape, dtype=dtypes.int32, name="block_shape") + + block_shape.get_shape().assert_is_fully_defined() + block_shape.get_shape().assert_has_rank(1) + num_block_dims = block_shape.get_shape().dims[0].value + if num_block_dims == 0: + return zeros([0, 2], dtypes.int32), zeros([0, 2], dtypes.int32) + + input_shape.get_shape().assert_is_compatible_with([num_block_dims]) + + if base_paddings is not None: + base_paddings = ops.convert_to_tensor( + base_paddings, dtype=dtypes.int32, name="base_paddings") + base_paddings.get_shape().assert_is_compatible_with([num_block_dims, 2]) + else: + base_paddings = zeros([num_block_dims, 2], dtypes.int32) + + const_block_shape = tensor_util.constant_value(block_shape) + const_input_shape = tensor_util.constant_value(input_shape) + const_base_paddings = tensor_util.constant_value(base_paddings) + if (const_block_shape is not None and const_input_shape is not None and + const_base_paddings is not None): + block_shape = const_block_shape + input_shape = const_input_shape + base_paddings = const_base_paddings + + # Use same expression for both constant and non-constant case. + pad_start = base_paddings[:, 0] + orig_pad_end = base_paddings[:, 1] + full_input_shape = input_shape + pad_start + orig_pad_end + pad_end_extra = (block_shape - full_input_shape % block_shape) % block_shape + pad_end = orig_pad_end + pad_end_extra + + result_paddings = array_ops_stack.stack( + [[pad_start[i], pad_end[i]] for i in range(num_block_dims)], + name="paddings") + result_crops = array_ops_stack.stack( + [[0, pad_end_extra[i]] for i in range(num_block_dims)], name="crops") + return result_paddings, result_crops + + +@tf_export(v1=["nn.space_to_batch", "space_to_batch"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("space_to_batch") +def space_to_batch( # pylint: disable=missing-docstring + input, # pylint: disable=redefined-builtin + paddings, + block_size=None, + name=None, + block_shape=None): # pylint: disable=redefined-builtin + block_size = deprecation.deprecated_argument_lookup("block_shape", + block_shape, "block_size", + block_size) + result = space_to_batch_nd( + input, + paddings=paddings, + block_shape=np.array([block_size, block_size], dtype=np.int64), + name=name) + result.set_shape(result.get_shape().with_rank(4)) + return result + + +space_to_batch.__doc__ = gen_array_ops.space_to_batch.__doc__ + + +@tf_export("space_to_batch", "nn.space_to_batch", v1=[]) +@dispatch.add_dispatch_support +def space_to_batch_v2(input, block_shape, paddings, name=None): # pylint: disable=redefined-builtin + return space_to_batch_nd(input, block_shape, paddings, name) + + +space_to_batch_v2.__doc__ = gen_array_ops.space_to_batch_nd.__doc__ + + +@tf_export(v1=["nn.space_to_depth", "space_to_depth"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("space_to_depth") +def space_to_depth(input, block_size, name=None, data_format="NHWC"): # pylint: disable=redefined-builtin + return gen_array_ops.space_to_depth(input, block_size, data_format, name=name) + + +space_to_depth.__doc__ = gen_array_ops.space_to_depth.__doc__ + + +@tf_export("nn.space_to_depth", v1=[]) +@dispatch.add_dispatch_support +def space_to_depth_v2(input, block_size, data_format="NHWC", name=None): # pylint: disable=redefined-builtin + return gen_array_ops.space_to_depth(input, block_size, data_format, name=name) + + +space_to_depth_v2.__doc__ = gen_array_ops.space_to_depth.__doc__ + + +@tf_export(v1=["nn.depth_to_space", "depth_to_space"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("depth_to_space") +def depth_to_space(input, block_size, name=None, data_format="NHWC"): # pylint: disable=redefined-builtin + return gen_array_ops.depth_to_space(input, block_size, data_format, name=name) + + +depth_to_space.__doc__ = gen_array_ops.depth_to_space.__doc__ + + +@tf_export("nn.depth_to_space", v1=[]) +@dispatch.add_dispatch_support +def depth_to_space_v2(input, block_size, data_format="NHWC", name=None): # pylint: disable=redefined-builtin + return gen_array_ops.depth_to_space(input, block_size, data_format, name=name) + + +depth_to_space_v2.__doc__ = gen_array_ops.depth_to_space.__doc__ + + +@tf_export(v1=["batch_to_space"]) +@dispatch.add_dispatch_support +def batch_to_space(input, crops, block_size, name=None, block_shape=None): # pylint: disable=redefined-builtin,missing-docstring + block_size = deprecation.deprecated_argument_lookup("block_shape", + block_shape, "block_size", + block_size) + result = batch_to_space_nd( + input, + crops=crops, + block_shape=np.array([block_size, block_size], dtype=np.int64), + name=name) + result.set_shape(result.get_shape().with_rank(4)) + return result + + +batch_to_space.__doc__ = gen_array_ops.batch_to_space.__doc__ + + +@tf_export("batch_to_space", v1=[]) +@dispatch.add_dispatch_support +def batch_to_space_v2(input, block_shape, crops, name=None): # pylint: disable=redefined-builtin + """BatchToSpace for N-D tensors of type T. + + This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of + shape `block_shape + [batch]`, interleaves these blocks back into the grid + defined by the spatial dimensions `[1, ..., M]`, to obtain a result with the + same rank as the input. The spatial dimensions of this intermediate result + are then optionally cropped according to `crops` to produce the output. This + is the reverse of SpaceToBatch (see `tf.space_to_batch`). + + Args: + input: A N-D `Tensor` with shape `input_shape = [batch] + spatial_shape + + remaining_shape`, where `spatial_shape` has M dimensions. + block_shape: A 1-D `Tensor` with shape [M]. Must be one of the following + types: `int32`, `int64`. All values must be >= 1. For backwards + compatibility with TF 1.0, this parameter may be an int, in which case it + is converted to + `numpy.array([block_shape, block_shape], + dtype=numpy.int64)`. + crops: A 2-D `Tensor` with shape `[M, 2]`. Must be one of the + following types: `int32`, `int64`. All values must be >= 0. + `crops[i] = [crop_start, crop_end]` specifies the amount to crop from + input dimension `i + 1`, which corresponds to spatial dimension `i`. + It is required that + `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. + This operation is equivalent to the following steps: + 1. Reshape `input` to `reshaped` of shape: [block_shape[0], ..., + block_shape[M-1], batch / prod(block_shape), input_shape[1], ..., + input_shape[N-1]] + 2. Permute dimensions of `reshaped` to produce `permuted` of shape + [batch / prod(block_shape), input_shape[1], block_shape[0], ..., + input_shape[M], block_shape[M-1], input_shape[M+1], + ..., input_shape[N-1]] + 3. Reshape `permuted` to produce `reshaped_permuted` of shape + [batch / prod(block_shape), input_shape[1] * block_shape[0], ..., + input_shape[M] * block_shape[M-1], input_shape[M+1], ..., + input_shape[N-1]] + 4. Crop the start and end of dimensions `[1, ..., M]` of + `reshaped_permuted` according to `crops` to produce the output + of shape: + [batch / prod(block_shape), input_shape[1] * + block_shape[0] - crops[0,0] - crops[0,1], ..., input_shape[M] * + block_shape[M-1] - crops[M-1,0] - crops[M-1,1], input_shape[M+1], + ..., input_shape[N-1]] + name: A name for the operation (optional). + + Examples: + + 1. For the following input of shape `[4, 1, 1, 1]`, + `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: + + ```python + [[[[1]]], + [[[2]]], + [[[3]]], + [[[4]]]] + ``` + + The output tensor has shape `[1, 2, 2, 1]` and value: + + ``` + x = [[[[1], [2]], + [[3], [4]]]] + ``` + + 2. For the following input of shape `[4, 1, 1, 3]`, + `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: + + ```python + [[[1, 2, 3]], + [[4, 5, 6]], + [[7, 8, 9]], + [[10, 11, 12]]] + ``` + + The output tensor has shape `[1, 2, 2, 3]` and value: + + ```python + x = [[[[1, 2, 3], [4, 5, 6 ]], + [[7, 8, 9], [10, 11, 12]]]] + ``` + + 3. For the following + input of shape `[4, 2, 2, 1]`, + `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: + + ```python + x = [[[[1], [3]], [[ 9], [11]]], + [[[2], [4]], [[10], [12]]], + [[[5], [7]], [[13], [15]]], + [[[6], [8]], [[14], [16]]]] + ``` + + The output tensor has shape `[1, 4, 4, 1]` and value: + + ```python + x = [[[1], [2], [ 3], [ 4]], + [[5], [6], [ 7], [ 8]], + [[9], [10], [11], [12]], + [[13], [14], [15], [16]]] + ``` + + 4. For the following input of shape + `[8, 1, 3, 1]`, + `block_shape = [2, 2]`, and `crops = [[0, 0], [2, 0]]`: + + ```python + x = [[[[0], [ 1], [ 3]]], + [[[0], [ 9], [11]]], + [[[0], [ 2], [ 4]]], + [[[0], [10], [12]]], + [[[0], [ 5], [ 7]]], + [[[0], [13], [15]]], + [[[0], [ 6], [ 8]]], + [[[0], [14], [16]]]] + ``` + + The output tensor has shape `[2, 2, 4, 1]` and value: + + ```python + x = [[[[ 1], [ 2], [ 3], [ 4]], + [[ 5], [ 6], [ 7], [ 8]]], + [[[ 9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + Returns: + A `Tensor`. Has the same type as `input`. + """ + if isinstance(block_shape, int): + block_shape = np.array([block_shape, block_shape], dtype=np.int64) + + return batch_to_space_nd( + input=input, block_shape=block_shape, crops=crops, name=name) + + +@tf_export("one_hot") +@dispatch.add_dispatch_support +def one_hot(indices, + depth, + on_value=None, + off_value=None, + axis=None, + dtype=None, + name=None): + """Returns a one-hot tensor. + + See also `tf.fill`, `tf.eye`. + + The locations represented by indices in `indices` take value `on_value`, + while all other locations take value `off_value`. + + `on_value` and `off_value` must have matching data types. If `dtype` is also + provided, they must be the same data type as specified by `dtype`. + + If `on_value` is not provided, it will default to the value `1` with type + `dtype` + + If `off_value` is not provided, it will default to the value `0` with type + `dtype` + + If the input `indices` is rank `N`, the output will have rank `N+1`. The + new axis is created at dimension `axis` (default: the new axis is appended + at the end). + + If `indices` is a scalar the output shape will be a vector of length `depth` + + If `indices` is a vector of length `features`, the output shape will be: + + ``` + features x depth if axis == -1 + depth x features if axis == 0 + ``` + + If `indices` is a matrix (batch) with shape `[batch, features]`, the output + shape will be: + + ``` + batch x features x depth if axis == -1 + batch x depth x features if axis == 1 + depth x batch x features if axis == 0 + ``` + + If `indices` is a RaggedTensor, the 'axis' argument must be positive and refer + to a non-ragged axis. The output will be equivalent to applying 'one_hot' on + the values of the RaggedTensor, and creating a new RaggedTensor from the + result. + + If `dtype` is not provided, it will attempt to assume the data type of + `on_value` or `off_value`, if one or both are passed in. If none of + `on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the + value `tf.float32`. + + Note: If a non-numeric data type output is desired (`tf.string`, `tf.bool`, + etc.), both `on_value` and `off_value` _must_ be provided to `one_hot`. + + For example: + + ```python + indices = [0, 1, 2] + depth = 3 + tf.one_hot(indices, depth) # output: [3 x 3] + # [[1., 0., 0.], + # [0., 1., 0.], + # [0., 0., 1.]] + + indices = [0, 2, -1, 1] + depth = 3 + tf.one_hot(indices, depth, + on_value=5.0, off_value=0.0, + axis=-1) # output: [4 x 3] + # [[5.0, 0.0, 0.0], # one_hot(0) + # [0.0, 0.0, 5.0], # one_hot(2) + # [0.0, 0.0, 0.0], # one_hot(-1) + # [0.0, 5.0, 0.0]] # one_hot(1) + + indices = [[0, 2], [1, -1]] + depth = 3 + tf.one_hot(indices, depth, + on_value=1.0, off_value=0.0, + axis=-1) # output: [2 x 2 x 3] + # [[[1.0, 0.0, 0.0], # one_hot(0) + # [0.0, 0.0, 1.0]], # one_hot(2) + # [[0.0, 1.0, 0.0], # one_hot(1) + # [0.0, 0.0, 0.0]]] # one_hot(-1) + + indices = tf.ragged.constant([[0, 1], [2]]) + depth = 3 + tf.one_hot(indices, depth) # output: [2 x None x 3] + # [[[1., 0., 0.], + # [0., 1., 0.]], + # [[0., 0., 1.]]] + ``` + + Args: + indices: A `Tensor` of indices. + depth: A scalar defining the depth of the one hot dimension. + on_value: A scalar defining the value to fill in output when `indices[j] + = i`. (default: 1) + off_value: A scalar defining the value to fill in output when `indices[j] + != i`. (default: 0) + axis: The axis to fill (default: -1, a new inner-most axis). + dtype: The data type of the output tensor. + name: A name for the operation (optional). + + Returns: + output: The one-hot tensor. + + Raises: + TypeError: If dtype of either `on_value` or `off_value` don't match `dtype` + TypeError: If dtype of `on_value` and `off_value` don't match one another + """ + with ops.name_scope( + name, "one_hot", + [indices, depth, on_value, off_value, axis, dtype]) as name: + on_exists = on_value is not None + off_exists = off_value is not None + + if on_exists: + on_value = ops.convert_to_tensor(on_value, dtype_hint=dtype) + if off_exists: + off_value = ops.convert_to_tensor(off_value, dtype_hint=dtype) + + on_dtype = on_value.dtype.base_dtype if on_exists else None + off_dtype = off_value.dtype.base_dtype if off_exists else None + + if on_exists or off_exists: + if dtype is not None: + # Ensure provided on_value and/or off_value match dtype + if on_exists and on_dtype != dtype: + raise TypeError("dtype {0} of on_value does not match " + "dtype parameter {1}".format(on_dtype, dtype)) + if off_exists and off_dtype != dtype: + raise TypeError("dtype {0} of off_value does not match " + "dtype parameter {1}".format(off_dtype, dtype)) + else: + # dtype not provided: automatically assign it + dtype = on_dtype if on_exists else off_dtype + elif dtype is None: + # None of on_value, off_value, or dtype provided. Default dtype to float32 + dtype = dtypes.float32 + + if not on_exists: + # on_value not provided: assign to value 1 of type dtype + on_value = ops.convert_to_tensor(1, dtype, name="on_value") + on_dtype = dtype + if not off_exists: + # off_value not provided: assign to value 0 of type dtype + off_value = ops.convert_to_tensor(0, dtype, name="off_value") + off_dtype = dtype + + if on_dtype != off_dtype: + raise TypeError("dtype {0} of on_value does not match " + "dtype {1} of off_value".format(on_dtype, off_dtype)) + + return gen_array_ops.one_hot(indices, depth, on_value, off_value, axis, + name) + + +def _all_dimensions(x): + """Returns a 1D-tensor listing all dimensions in x.""" + # Fast path: avoid creating Rank and Range ops if ndims is known. + if isinstance(x, tensor_lib.Tensor) and x.get_shape().ndims is not None: + return constant_op.constant( + np.arange(x.get_shape().ndims), dtype=dtypes.int32) + if (isinstance(x, sparse_tensor.SparseTensor) and + x.dense_shape.get_shape().is_fully_defined()): + r = x.dense_shape.get_shape().dims[0].value # sparse.dense_shape is 1-D. + return constant_op.constant(np.arange(r), dtype=dtypes.int32) + + # Otherwise, we rely on `range` and `rank` to do the right thing at runtime. + return gen_math_ops._range(0, rank(x), 1) + + +@tf_export("sequence_mask") +@dispatch.add_dispatch_support +def sequence_mask(lengths, maxlen=None, dtype=dtypes.bool, name=None): + """Returns a mask tensor representing the first N positions of each cell. + + If `lengths` has shape `[d_1, d_2, ..., d_n]` the resulting tensor `mask` has + dtype `dtype` and shape `[d_1, d_2, ..., d_n, maxlen]`, with + + ``` + mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n]) + ``` + + Examples: + + ```python + tf.sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False], + # [True, True, True, False, False], + # [True, True, False, False, False]] + + tf.sequence_mask([[1, 3],[2,0]]) # [[[True, False, False], + # [True, True, True]], + # [[True, True, False], + # [False, False, False]]] + ``` + + Args: + lengths: integer tensor, all its values <= maxlen. + maxlen: scalar integer tensor, size of last dimension of returned tensor. + Default is the maximum value in `lengths`. + dtype: output type of the resulting tensor. + name: name of the op. + + Returns: + A mask tensor of shape `lengths.shape + (maxlen,)`, cast to specified dtype. + Raises: + ValueError: if `maxlen` is not a scalar. + """ + with ops.name_scope(name, "SequenceMask", [lengths, maxlen]): + lengths = ops.convert_to_tensor(lengths) + + if maxlen is None: + maxlen = gen_math_ops._max(lengths, _all_dimensions(lengths)) + maxlen = gen_math_ops.maximum(constant(0, maxlen.dtype), maxlen) + else: + maxlen = ops.convert_to_tensor(maxlen) + if maxlen.get_shape().ndims is not None and maxlen.get_shape().ndims != 0: + raise ValueError("Argument `maxlen` must be scalar for sequence_mask, " + f"received `maxlen` = {maxlen} " + f"with shape '{maxlen.get_shape()}' instead") + + # The basic idea is to compare a range row vector of size maxlen: + # [0, 1, 2, 3, 4] + # to length as a matrix with 1 column: [[1], [3], [2]]. + # Because of broadcasting on both arguments this comparison results + # in a matrix of size (len(lengths), maxlen) + row_vector = gen_math_ops._range( + constant(0, maxlen.dtype), maxlen, constant(1, maxlen.dtype)) + # Since maxlen >= max(lengths), it is safe to use maxlen as a cast + # authoritative type. Whenever maxlen fits into tf.int32, so do the lengths. + matrix = gen_math_ops.cast(expand_dims(lengths, -1), maxlen.dtype) + result = row_vector < matrix + if dtype is None or result.dtype.is_compatible_with(dtype): + return result + else: + return gen_math_ops.cast(result, dtype) + + +@tf_export(v1=["squeeze"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "Use the `axis` argument instead", + "squeeze_dims") +def squeeze(input, axis=None, name=None, squeeze_dims=None): + # pylint: disable=redefined-builtin + """Removes dimensions of size 1 from the shape of a tensor. + + Given a tensor `input`, this operation returns a tensor of the same type with + all dimensions of size 1 removed. If you don't want to remove all size 1 + dimensions, you can remove specific size 1 dimensions by specifying + `axis`. + + For example: + + >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + >>> t = tf.ones([1, 2, 1, 3, 1, 1]) + >>> print(tf.shape(tf.squeeze(t)).numpy()) + [2 3] + + Or, to remove specific size 1 dimensions: + + >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + >>> t = tf.ones([1, 2, 1, 3, 1, 1]) + >>> print(tf.shape(tf.squeeze(t, [2, 4])).numpy()) + [1 2 3 1] + + Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)` + time, where `N` is the number of elements in the squeezed dimensions. + + Args: + input: A `Tensor`. The `input` to squeeze. + axis: An optional list of `ints`. Defaults to `[]`. If specified, only + squeezes the dimensions listed. The dimension index starts at 0. It is an + error to squeeze a dimension that is not 1. Must be in the range + `[-rank(input), rank(input))`. Must be specified if `input` is a + `RaggedTensor`. + name: A name for the operation (optional). + squeeze_dims: Deprecated keyword argument that is now axis. + + Returns: + A `Tensor`. Has the same type as `input`. + Contains the same data as `input`, but has one or more dimensions of + size 1 removed. + + Raises: + ValueError: When both `squeeze_dims` and `axis` are specified. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, "squeeze_dims", + squeeze_dims) + if np.isscalar(axis): + axis = [axis] + return gen_array_ops.squeeze(input, axis, name) + + +@tf_export("squeeze", v1=[]) +@dispatch.add_dispatch_support +def squeeze_v2(input, axis=None, name=None): + """Removes dimensions of size 1 from the shape of a tensor. + + Given a tensor `input`, this operation returns a tensor of the same type with + all dimensions of size 1 removed. If you don't want to remove all size 1 + dimensions, you can remove specific size 1 dimensions by specifying + `axis`. + + For example: + + ```python + # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + tf.shape(tf.squeeze(t)) # [2, 3] + ``` + + Or, to remove specific size 1 dimensions: + + ```python + # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1] + ``` + + Unlike the older op `tf.compat.v1.squeeze`, this op does not accept a + deprecated `squeeze_dims` argument. + + Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)` + time, where `N` is the number of elements in the squeezed dimensions. + + Note: If squeeze is performed on dimensions of unknown sizes, then the + returned Tensor will be of unknown shape. A common situation is when the + first (batch) dimension is of size `None`, `tf.squeeze` returns + `` shape which may be a surprise. Specify the `axis=` argument + to get the expected result, as illustrated in the following example: + + ```python + @tf.function + def func(x): + print('x.shape:', x.shape) + known_axes = [i for i, size in enumerate(x.shape) if size == 1] + y = tf.squeeze(x, axis=known_axes) + print('shape of tf.squeeze(x, axis=known_axes):', y.shape) + y = tf.squeeze(x) + print('shape of tf.squeeze(x):', y.shape) + return 0 + + _ = func.get_concrete_function(tf.TensorSpec([None, 1, 2], dtype=tf.int32)) + # Output is. + # x.shape: (None, 1, 2) + # shape of tf.squeeze(x, axis=known_axes): (None, 2) + # shape of tf.squeeze(x): + ``` + + Args: + input: A `Tensor`. The `input` to squeeze. + axis: An optional list of `ints`. Defaults to `[]`. If specified, only + squeezes the dimensions listed. The dimension index starts at 0. It is an + error to squeeze a dimension that is not 1. Must be in the range + `[-rank(input), rank(input))`. Must be specified if `input` is a + `RaggedTensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + Contains the same data as `input`, but has one or more dimensions of + size 1 removed. + + Raises: + ValueError: The input cannot be converted to a tensor, or the specified + axis cannot be squeezed. + """ + # pylint: disable=redefined-builtin + return squeeze(input, axis, name) + + +@tf_export(v1=["where"]) +@dispatch.add_dispatch_support +def where(condition, x=None, y=None, name=None): + """Return the elements, either from `x` or `y`, depending on the `condition`. + + If both `x` and `y` are None, then this operation returns the coordinates of + true elements of `condition`. The coordinates are returned in a 2-D tensor + where the first dimension (rows) represents the number of true elements, and + the second dimension (columns) represents the coordinates of the true + elements. Keep in mind, the shape of the output tensor can vary depending on + how many true values there are in input. Indices are output in row-major + order. + + If both non-None, `x` and `y` must have the same shape. + The `condition` tensor must be a scalar if `x` and `y` are scalar. + If `x` and `y` are tensors of higher rank, then `condition` must be either a + vector with size matching the first dimension of `x`, or must have the same + shape as `x`. + + The `condition` tensor acts as a mask that chooses, based on the value at each + element, whether the corresponding element / row in the output should be taken + from `x` (if true) or `y` (if false). + + If `condition` is a vector and `x` and `y` are higher rank matrices, then it + chooses which row (outer dimension) to copy from `x` and `y`. If `condition` + has the same shape as `x` and `y`, then it chooses which element to copy from + `x` and `y`. + + Args: + condition: A `Tensor` of type `bool` + x: A Tensor which may have the same shape as `condition`. If `condition` is + rank 1, `x` may have higher rank, but its first dimension must match the + size of `condition`. + y: A `tensor` with the same shape and type as `x`. + name: A name of the operation (optional) + + Returns: + A `Tensor` with the same type and shape as `x`, `y` if they are non-None. + Otherwise, a `Tensor` with shape `(num_true, rank(condition))`. + + Raises: + ValueError: When exactly one of `x` or `y` is non-None. + + @compatibility(TF2) + + This API is compatible with eager execution and `tf.function`. However, this + is still a legacy API endpoint originally designed for TF1. To migrate to + fully-native TF2, please replace its usage with `tf.where` instead, which is + directly backwards compatible with `tf.compat.v1.where`. + + However,`tf.compat.v1.where` is more restrictive than `tf.where`, requiring + `x` and `y` to have the same shape, and returning a `Tensor` with the same + type and shape as `x`, `y` (if they are both non-None). + + `tf.where` will accept `x`, `y` that are not the same shape as long as they + are broadcastable with one another and with `condition`, and will return a + `Tensor` with shape broadcast from `condition`, `x`, and `y`. + + For example, the following works with `tf.where` but not `tf.compat.v1.where`: + + >>> tf.where([True, False, False, True], [1,2,3,4], [100]) + + + >>> tf.where(True, [1,2,3,4], 100) + + + @end_compatibility + """ + if x is None and y is None: + with ops.name_scope(name, "Where", [condition]) as name: + condition = ops.convert_to_tensor( + condition, preferred_dtype=dtypes.bool, name="condition") + return gen_array_ops.where(condition=condition, name=name) + elif x is not None and y is not None: + return gen_math_ops.select(condition=condition, x=x, y=y, name=name) + else: + raise ValueError("x and y must both be non-None or both be None.") + + +@tf_export("where", v1=["where_v2"]) +@dispatch.add_dispatch_support +def where_v2(condition, x=None, y=None, name=None): + """Returns the indices of non-zero elements, or multiplexes `x` and `y`. + + This operation has two modes: + + 1. **Return the indices of non-zero elements** - When only + `condition` is provided the result is an `int64` tensor where each row is + the index of a non-zero element of `condition`. The result's shape + is `[tf.math.count_nonzero(condition), tf.rank(condition)]`. + 2. **Multiplex `x` and `y`** - When both `x` and `y` are provided the + result has the shape of `x`, `y`, and `condition` broadcast together. The + result is taken from `x` where `condition` is non-zero + or `y` where `condition` is zero. + + #### 1. Return the indices of non-zero elements + + Note: In this mode `condition` can have a dtype of `bool` or any numeric + dtype. + + If `x` and `y` are not provided (both are None): + + `tf.where` will return the indices of `condition` that are non-zero, + in the form of a 2-D tensor with shape `[n, d]`, where `n` is the number of + non-zero elements in `condition` (`tf.count_nonzero(condition)`), and `d` is + the number of axes of `condition` (`tf.rank(condition)`). + + Indices are output in row-major order. The `condition` can have a `dtype` of + `tf.bool`, or any numeric `dtype`. + + Here `condition` is a 1-axis `bool` tensor with 2 `True` values. The result + has a shape of `[2,1]` + + >>> tf.where([True, False, False, True]).numpy() + array([[0], + [3]]) + + Here `condition` is a 2-axis integer tensor, with 3 non-zero values. The + result has a shape of `[3, 2]`. + + >>> tf.where([[1, 0, 0], [1, 0, 1]]).numpy() + array([[0, 0], + [1, 0], + [1, 2]]) + + Here `condition` is a 3-axis float tensor, with 5 non-zero values. The output + shape is `[5, 3]`. + + >>> float_tensor = [[[0.1, 0], [0, 2.2], [3.5, 1e6]], + ... [[0, 0], [0, 0], [99, 0]]] + >>> tf.where(float_tensor).numpy() + array([[0, 0, 0], + [0, 1, 1], + [0, 2, 0], + [0, 2, 1], + [1, 2, 0]]) + + These indices are the same that `tf.sparse.SparseTensor` would use to + represent the condition tensor: + + >>> sparse = tf.sparse.from_dense(float_tensor) + >>> sparse.indices.numpy() + array([[0, 0, 0], + [0, 1, 1], + [0, 2, 0], + [0, 2, 1], + [1, 2, 0]]) + + A complex number is considered non-zero if either the real or imaginary + component is non-zero: + + >>> tf.where([complex(0.), complex(1.), 0+1j, 1+1j]).numpy() + array([[1], + [2], + [3]]) + + #### 2. Multiplex `x` and `y` + + Note: In this mode `condition` must have a dtype of `bool`. + + If `x` and `y` are also provided (both have non-None values) the `condition` + tensor acts as a mask that chooses whether the corresponding + element / row in the output should be taken from `x` (if the element in + `condition` is `True`) or `y` (if it is `False`). + + The shape of the result is formed by + [broadcasting](https://docs.scipy.org/doc/numpy/reference/ufuncs.html) + together the shapes of `condition`, `x`, and `y`. + + When all three inputs have the same size, each is handled element-wise. + + >>> tf.where([True, False, False, True], + ... [1, 2, 3, 4], + ... [100, 200, 300, 400]).numpy() + array([ 1, 200, 300, 4], dtype=int32) + + There are two main rules for broadcasting: + + 1. If a tensor has fewer axes than the others, length-1 axes are added to the + left of the shape. + 2. Axes with length-1 are streched to match the coresponding axes of the other + tensors. + + A length-1 vector is streched to match the other vectors: + + >>> tf.where([True, False, False, True], [1, 2, 3, 4], [100]).numpy() + array([ 1, 100, 100, 4], dtype=int32) + + A scalar is expanded to match the other arguments: + + >>> tf.where([[True, False], [False, True]], [[1, 2], [3, 4]], 100).numpy() + array([[ 1, 100], [100, 4]], dtype=int32) + >>> tf.where([[True, False], [False, True]], 1, 100).numpy() + array([[ 1, 100], [100, 1]], dtype=int32) + + A scalar `condition` returns the complete `x` or `y` tensor, with + broadcasting applied. + + >>> tf.where(True, [1, 2, 3, 4], 100).numpy() + array([1, 2, 3, 4], dtype=int32) + >>> tf.where(False, [1, 2, 3, 4], 100).numpy() + array([100, 100, 100, 100], dtype=int32) + + For a non-trivial example of broadcasting, here `condition` has a shape of + `[3]`, `x` has a shape of `[3,3]`, and `y` has a shape of `[3,1]`. + Broadcasting first expands the shape of `condition` to `[1,3]`. The final + broadcast shape is `[3,3]`. `condition` will select columns from `x` and `y`. + Since `y` only has one column, all columns from `y` will be identical. + + >>> tf.where([True, False, True], + ... x=[[1, 2, 3], + ... [4, 5, 6], + ... [7, 8, 9]], + ... y=[[100], + ... [200], + ... [300]] + ... ).numpy() + array([[ 1, 100, 3], + [ 4, 200, 6], + [ 7, 300, 9]], dtype=int32) + + Note that if the gradient of either branch of the `tf.where` generates + a `NaN`, then the gradient of the entire `tf.where` will be `NaN`. This is + because the gradient calculation for `tf.where` combines the two branches, for + performance reasons. + + A workaround is to use an inner `tf.where` to ensure the function has + no asymptote, and to avoid computing a value whose gradient is `NaN` by + replacing dangerous inputs with safe inputs. + + Instead of this, + + >>> x = tf.constant(0., dtype=tf.float32) + >>> with tf.GradientTape() as tape: + ... tape.watch(x) + ... y = tf.where(x < 1., 0., 1. / x) + >>> print(tape.gradient(y, x)) + tf.Tensor(nan, shape=(), dtype=float32) + + Although, the `1. / x` values are never used, its gradient is a `NaN` when + `x = 0`. Instead, we should guard that with another `tf.where` + + >>> x = tf.constant(0., dtype=tf.float32) + >>> with tf.GradientTape() as tape: + ... tape.watch(x) + ... safe_x = tf.where(tf.equal(x, 0.), 1., x) + ... y = tf.where(x < 1., 0., 1. / safe_x) + >>> print(tape.gradient(y, x)) + tf.Tensor(0.0, shape=(), dtype=float32) + + See also: + + * `tf.sparse` - The indices returned by the first form of `tf.where` can be + useful in `tf.sparse.SparseTensor` objects. + * `tf.gather_nd`, `tf.scatter_nd`, and related ops - Given the + list of indices returned from `tf.where` the `scatter` and `gather` family + of ops can be used fetch values or insert values at those indices. + * `tf.strings.length` - `tf.string` is not an allowed dtype for the + `condition`. Use the string length instead. + + Args: + condition: A `tf.Tensor` of dtype bool, or any numeric dtype. `condition` + must have dtype `bool` when `x` and `y` are provided. + x: If provided, a Tensor which is of the same type as `y`, and has a shape + broadcastable with `condition` and `y`. + y: If provided, a Tensor which is of the same type as `x`, and has a shape + broadcastable with `condition` and `x`. + name: A name of the operation (optional). + + Returns: + If `x` and `y` are provided: + A `Tensor` with the same type as `x` and `y`, and shape that + is broadcast from `condition`, `x`, and `y`. + Otherwise, a `Tensor` with shape `[tf.math.count_nonzero(condition), + tf.rank(condition)]`. + + Raises: + ValueError: When exactly one of `x` or `y` is non-None, or the shapes + are not all broadcastable. + """ + if x is None and y is None: + with ops.name_scope(name, "Where", [condition]) as name: + condition = ops.convert_to_tensor( + condition, preferred_dtype=dtypes.bool, name="condition") + return gen_array_ops.where(condition=condition, name=name) + elif x is not None and y is not None: + return gen_math_ops.select_v2(condition=condition, t=x, e=y, name=name) + else: + raise ValueError("x and y must both be non-None or both be None.") + + +# pylint: disable=redefined-builtin +@tf_export(v1=["reverse_sequence"]) +@deprecation.deprecated_args(None, + "seq_dim is deprecated, use seq_axis instead", + "seq_dim") +@deprecation.deprecated_args(None, + "batch_dim is deprecated, use batch_axis instead", + "batch_dim") +def reverse_sequence(input, + seq_lengths, + seq_axis=None, + batch_axis=None, + name=None, + seq_dim=None, + batch_dim=None): + """Reverses variable length slices. + + This op first slices `input` along the dimension `batch_axis`, and for + each slice `i`, reverses the first `seq_lengths[i]` elements along the + dimension `seq_axis`. + + The elements of `seq_lengths` must obey `seq_lengths[i] <= + input.dims[seq_axis]`, and `seq_lengths` must be a vector of length + `input.dims[batch_axis]`. + + The output slice `i` along dimension `batch_axis` is then given by + input slice `i`, with the first `seq_lengths[i]` slices along + dimension `seq_axis` reversed. + + Example usage: + + >>> seq_lengths = [7, 2, 3, 5] + >>> input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0], + ... [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]] + >>> output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0) + >>> output + + + Args: + input: A `Tensor`. The input to reverse. + seq_lengths: A `Tensor`. Must be one of the following types: `int32`, + `int64`. 1-D with length `input.dims(batch_axis)` and `max(seq_lengths) <= + input.dims(seq_axis)` + seq_axis: An `int`. The dimension which is partially reversed. + batch_axis: An optional `int`. Defaults to `0`. The dimension along which + reversal is performed. + name: A name for the operation (optional). + + Returns: + A Tensor. Has the same type as input. + """ + seq_axis = deprecation.deprecated_argument_lookup("seq_axis", seq_axis, + "seq_dim", seq_dim) + batch_axis = deprecation.deprecated_argument_lookup("batch_axis", batch_axis, + "batch_dim", batch_dim) + return gen_array_ops.reverse_sequence( + input=input, + seq_lengths=seq_lengths, + seq_dim=seq_axis, + batch_dim=batch_axis, + name=name) + + +@tf_export("reverse_sequence", v1=[]) +@dispatch.add_dispatch_support +def reverse_sequence_v2(input, + seq_lengths, + seq_axis=None, + batch_axis=None, + name=None): + """Reverses variable length slices. + + This op first slices `input` along the dimension `batch_axis`, and for + each slice `i`, reverses the first `seq_lengths[i]` elements along the + dimension `seq_axis`. + + The elements of `seq_lengths` must obey `seq_lengths[i] <= + input.dims[seq_axis]`, and `seq_lengths` must be a vector of length + `input.dims[batch_axis]`. + + The output slice `i` along dimension `batch_axis` is then given by + input slice `i`, with the first `seq_lengths[i]` slices along + dimension `seq_axis` reversed. + + Example usage: + + >>> seq_lengths = [7, 2, 3, 5] + >>> input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0], + ... [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]] + >>> output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0) + >>> output + + + Args: + input: A `Tensor`. The input to reverse. + seq_lengths: A `Tensor`. Must be one of the following types: `int32`, + `int64`. 1-D with length `input.dims(batch_axis)` and `max(seq_lengths) <= + input.dims(seq_axis)` + seq_axis: An `int`. The dimension which is partially reversed. + batch_axis: An optional `int`. Defaults to `0`. The dimension along which + reversal is performed. + name: A name for the operation (optional). + + Returns: + A Tensor. Has the same type as input. + """ + return gen_array_ops.reverse_sequence( + input=input, + seq_lengths=seq_lengths, + seq_dim=seq_axis, + batch_dim=batch_axis, + name=name) + +# pylint: enable=redefined-builtin + + +@tf_export(v1=["gather"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + ("The `validate_indices` argument has no effect. " + "Indices are always validated on CPU and never " + "validated on GPU."), + ("validate_indices", None)) +def gather(params, + indices, + validate_indices=None, + name=None, + axis=None, + batch_dims=0): # pylint: disable=g-doc-args + r"""Gather slices from params axis `axis` according to indices. + + Gather slices from `params` axis `axis` according to `indices`. `indices` + must be an integer tensor of any dimension (often 1-D). + + `Tensor.__getitem__` works for scalars, `tf.newaxis`, and + [python slices](https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing) + + `tf.gather` extends indexing to handle tensors of indices. + + In the simplest case it's identical to scalar indexing: + + >>> params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5']) + >>> params[3].numpy() + b'p3' + >>> tf.gather(params, 3).numpy() + b'p3' + + The most common case is to pass a single axis tensor of indices (this + can't be expressed as a python slice because the indices are not sequential): + + >>> indices = [2, 0, 2, 5] + >>> tf.gather(params, indices).numpy() + array([b'p2', b'p0', b'p2', b'p5'], dtype=object) + +
+ +
+ + The indices can have any shape. When the `params` has 1 axis, the + output shape is equal to the input shape: + + >>> tf.gather(params, [[2, 0], [2, 5]]).numpy() + array([[b'p2', b'p0'], + [b'p2', b'p5']], dtype=object) + + The `params` may also have any shape. `gather` can select slices + across any axis depending on the `axis` argument (which defaults to 0). + Below it is used to gather first rows, then columns from a matrix: + + >>> params = tf.constant([[0, 1.0, 2.0], + ... [10.0, 11.0, 12.0], + ... [20.0, 21.0, 22.0], + ... [30.0, 31.0, 32.0]]) + >>> tf.gather(params, indices=[3,1]).numpy() + array([[30., 31., 32.], + [10., 11., 12.]], dtype=float32) + >>> tf.gather(params, indices=[2,1], axis=1).numpy() + array([[ 2., 1.], + [12., 11.], + [22., 21.], + [32., 31.]], dtype=float32) + + More generally: The output shape has the same shape as the input, with the + indexed-axis replaced by the shape of the indices. + + >>> def result_shape(p_shape, i_shape, axis=0): + ... return p_shape[:axis] + i_shape + p_shape[axis+1:] + >>> + >>> result_shape([1, 2, 3], [], axis=1) + [1, 3] + >>> result_shape([1, 2, 3], [7], axis=1) + [1, 7, 3] + >>> result_shape([1, 2, 3], [7, 5], axis=1) + [1, 7, 5, 3] + + Here are some examples: + + >>> params.shape.as_list() + [4, 3] + >>> indices = tf.constant([[0, 2]]) + >>> tf.gather(params, indices=indices, axis=0).shape.as_list() + [1, 2, 3] + >>> tf.gather(params, indices=indices, axis=1).shape.as_list() + [4, 1, 2] + + >>> params = tf.random.normal(shape=(5, 6, 7, 8)) + >>> indices = tf.random.uniform(shape=(10, 11), maxval=7, dtype=tf.int32) + >>> result = tf.gather(params, indices, axis=2) + >>> result.shape.as_list() + [5, 6, 10, 11, 8] + + This is because each index takes a slice from `params`, and + places it at the corresponding location in the output. For the above example + + >>> # For any location in indices + >>> a, b = 0, 1 + >>> tf.reduce_all( + ... # the corresponding slice of the result + ... result[:, :, a, b, :] == + ... # is equal to the slice of `params` along `axis` at the index. + ... params[:, :, indices[a, b], :] + ... ).numpy() + True + + ### Batching: + + The `batch_dims` argument lets you gather different items from each element + of a batch. + + Using `batch_dims=1` is equivalent to having an outer loop over the first + axis of `params` and `indices`: + + >>> params = tf.constant([ + ... [0, 0, 1, 0, 2], + ... [3, 0, 0, 0, 4], + ... [0, 5, 0, 6, 0]]) + >>> indices = tf.constant([ + ... [2, 4], + ... [0, 4], + ... [1, 3]]) + + >>> tf.gather(params, indices, axis=1, batch_dims=1).numpy() + array([[1, 2], + [3, 4], + [5, 6]], dtype=int32) + + This is equivalent to: + + >>> def manually_batched_gather(params, indices, axis): + ... batch_dims=1 + ... result = [] + ... for p,i in zip(params, indices): + ... r = tf.gather(p, i, axis=axis-batch_dims) + ... result.append(r) + ... return tf.stack(result) + >>> manually_batched_gather(params, indices, axis=1).numpy() + array([[1, 2], + [3, 4], + [5, 6]], dtype=int32) + + Higher values of `batch_dims` are equivalent to multiple nested loops over + the outer axes of `params` and `indices`. So the overall shape function is + + >>> def batched_result_shape(p_shape, i_shape, axis=0, batch_dims=0): + ... return p_shape[:axis] + i_shape[batch_dims:] + p_shape[axis+1:] + >>> + >>> batched_result_shape( + ... p_shape=params.shape.as_list(), + ... i_shape=indices.shape.as_list(), + ... axis=1, + ... batch_dims=1) + [3, 2] + + >>> tf.gather(params, indices, axis=1, batch_dims=1).shape.as_list() + [3, 2] + + This comes up naturally if you need to use the indices of an operation like + `tf.argsort`, or `tf.math.top_k` where the last dimension of the indices + indexes into the last dimension of input, at the corresponding location. + In this case you can use `tf.gather(values, indices, batch_dims=-1)`. + + See also: + + * `tf.Tensor.__getitem__`: The direct tensor index operation (`t[]`), handles + scalars and python-slices `tensor[..., 7, 1:-1]` + * `tf.scatter`: A collection of operations similar to `__setitem__` + (`t[i] = x`) + * `tf.gather_nd`: An operation similar to `tf.gather` but gathers across + multiple axis at once (it can gather elements of a matrix instead of rows + or columns) + * `tf.boolean_mask`, `tf.where`: Binary indexing. + * `tf.slice` and `tf.strided_slice`: For lower level access to the + implementation of `__getitem__`'s python-slice handling (`t[1:-1:2]`) + + Args: + params: The `Tensor` from which to gather values. Must be at least rank + `axis + 1`. + indices: The index `Tensor`. Must be one of the following types: `int32`, + `int64`. The values must be in range `[0, params.shape[axis])`. + validate_indices: Deprecated, does nothing. Indices are always validated on + CPU, never validated on GPU. + + Caution: On CPU, if an out of bound index is found, an error is raised. + On GPU, if an out of bound index is found, a 0 is stored in the + corresponding output value. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The + `axis` in `params` to gather `indices` from. Must be greater than or equal + to `batch_dims`. Defaults to the first non-batch dimension. Supports + negative indexes. + batch_dims: An `integer`. The number of batch dimensions. Must be less + than or equal to `rank(indices)`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + del validate_indices + + if axis is None: + axis = batch_dims + if tensor_util.constant_value(axis) != 0: + return gen_array_ops.gather_v2( + params, indices, axis, batch_dims=batch_dims, name=name) + try: + # TODO(apassos) find a less bad way of detecting resource variables + # without introducing a circular dependency. + return params.sparse_read(indices, name=name) + except AttributeError: + return gen_array_ops.gather_v2(params, indices, axis, name=name) + + +@tf_export("gather", v1=[]) +@dispatch.add_dispatch_support +def gather_v2(params, + indices, + validate_indices=None, + axis=None, + batch_dims=0, + name=None): + return gather( + params, + indices, + validate_indices=validate_indices, + name=name, + axis=axis, + batch_dims=batch_dims) + + +gather_v2.__doc__ = gather.__doc__ + + +@tf_export(v1=["batch_gather"]) +@dispatch.add_dispatch_support +@deprecation.deprecated( + "2017-10-25", "`tf.batch_gather` is deprecated, please use `tf.gather` " + "with `batch_dims=tf.rank(indices) - 1` instead.") # pylint: disable=missing-docstring +def batch_gather(params, indices, name=None): + """Gather slices from params according to indices with leading batch dims.""" + with ops.name_scope(name, "BatchGather", [params, indices]): + indices = ops.convert_to_tensor(indices, name="indices") + params = ops.convert_to_tensor(params, name="params") + if indices.shape.ndims is None: + raise ValueError( + "batch_gather does not allow indices with unknown shape.") + return _batch_gather(params, indices, batch_dims=indices.shape.ndims - 1) + + +def _batch_gather(params, indices, batch_dims, axis=None): + r"""Gather slices from params according to indices with leading batch dims. + + This operation assumes that the leading `batch_dims` dimensions of `indices` + and `params` are batch dimensions; and performs a `tf.gather` operation within + each batch. (If `batch_dims` is not specified, then it defaults to + `rank(indices)-1`.) In the case in which `batch_dims==0`, this operation + is equivalent to `tf.gather`. + + Args: + params: A Tensor. The tensor from which to gather values. + indices: A Tensor. Must be one of the following types: int32, int64. Index + tensor. Must be in range `[0, params.shape[batch_dims]]`. + batch_dims: An integer or none. The number of batch dimensions. Must be + less than `rank(indices)`. Defaults to `rank(indices) - 1` if None. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The + `axis` in `params` to gather `indices` from. Must be greater than or equal + to `batch_dims`. Defaults to the first non-batch dimension. Supports + negative indexes. + + Returns: + A Tensor. Has the same type as `params`. + + Raises: + ValueError: if `indices` has an unknown shape. + """ + if batch_dims is not None and not isinstance(batch_dims, int): + raise TypeError("Argument `batch_dims` must be an int. " + f"Received `batch_dims` = {batch_dims} instead") + indices = ops.convert_to_tensor(indices, name="indices") + params = ops.convert_to_tensor(params, name="params") + + indices_ndims = indices.shape.ndims + if indices_ndims is None: + raise ValueError("tf.gather does not allow indices with unknown " + "rank when batch_dims is specified.") + if batch_dims is None: + batch_dims = indices_ndims - 1 + if batch_dims < 0: + batch_dims += indices_ndims + if batch_dims < 0 or batch_dims >= indices_ndims: + raise ValueError(f"Argument `batch_dims` = {batch_dims} must be less than " + f"rank(`indices`) = {indices_ndims}") + if params.shape.ndims is not None and batch_dims >= params.shape.ndims: + raise ValueError(f"Argument `batch_dims` = {batch_dims} must be less than " + f"rank(`params`) = {params.shape.ndims}") + + # Handle axis by transposing the axis dimension to be the first non-batch + # dimension, recursively calling batch_gather with axis=0, and then + # transposing the result to put the pre-axis dimensions before the indices + # dimensions. + if axis is not None and axis != batch_dims: + # Adjust axis to be positive. + if not isinstance(axis, int): + axis = tf.where(axis < 0, axis + array_ops.rank(params), axis) + elif axis < 0 and params.shape.ndims is None: + axis = axis + array_ops.rank(params) + else: + if (axis < -params.shape.ndims) or (axis >= params.shape.ndims): + raise ValueError(f"Argument `axis` = {axis} out of range " + f"[{-params.shape.ndims}, {params.shape.ndims})") + if axis < 0: + axis += params.shape.ndims + if axis < batch_dims: + raise ValueError(f"Argument `batch_dims` = {batch_dims} must be less " + f"than or equal to argument `axis` = {axis}") + + # Move params[axis] up to params[batch_dims]. + perm = [ + list(range(batch_dims)), [axis], + gen_math_ops._range(batch_dims, axis, 1), + gen_math_ops._range(axis + 1, rank(params), 1) + ] + params = transpose(params, concat(perm, axis=0)) + + result = _batch_gather(params, indices, batch_dims=batch_dims) + + # Move the result dimensions corresponding to params[batch_dims:axis] + # to just before the dimensions corresponding to indices[batch_dims:]. + params_start = indices_ndims + axis - batch_dims + perm = [ + list(range(batch_dims)), + gen_math_ops._range(indices_ndims, params_start, 1), + list(range(batch_dims, indices_ndims)), + gen_math_ops._range(params_start, rank(result), 1) + ] + return transpose(result, perm=concat(perm, axis=0)) + + indices_shape = shape(indices) + params_shape = shape(params) + batch_indices = indices + indices_dtype = indices.dtype.base_dtype + accum_dim_value = ones((), dtype=indices_dtype) + # Use correct type for offset index computation + casted_params_shape = gen_math_ops.cast(params_shape, indices_dtype) + for dim in range(batch_dims, 0, -1): + dim_value = casted_params_shape[dim - 1] + accum_dim_value *= casted_params_shape[dim] + start = zeros((), dtype=indices_dtype) + step = ones((), dtype=indices_dtype) + dim_indices = gen_math_ops._range(start, dim_value, step) + dim_indices *= accum_dim_value + dim_shape = array_ops_stack.stack( + [1] * (dim - 1) + [dim_value] + [1] * (indices_ndims - dim), axis=0) + batch_indices += reshape(dim_indices, dim_shape) + + flat_indices = reshape(batch_indices, [-1]) + outer_shape = params_shape[batch_dims + 1:] + flat_inner_shape = gen_math_ops.prod(params_shape[:batch_dims + 1], [0], + False) + + flat_params = reshape(params, concat([[flat_inner_shape], outer_shape], + axis=0)) + flat_result = gather(flat_params, flat_indices) + result = reshape(flat_result, concat([indices_shape, outer_shape], axis=0)) + final_shape = indices.get_shape()[:batch_dims].merge_with( + params.get_shape()[:batch_dims]) + final_shape = final_shape.concatenate(indices.get_shape().dims[batch_dims:]) + final_shape = final_shape.concatenate(params.get_shape()[batch_dims + 1:]) + result.set_shape(final_shape) + return result + + +@tf_export(v1=["gather_nd", "manip.gather_nd"]) +@dispatch.add_dispatch_support +@deprecated_endpoints("manip.gather_nd") +def gather_nd(params, indices, name=None, batch_dims=0): + r"""Gather slices from `params` into a Tensor with shape specified by `indices`. + + `indices` is a `Tensor` of indices into `params`. The index vectors are + arranged along the last axis of `indices`. + + This is similar to `tf.gather`, in which `indices` defines slices into the + first dimension of `params`. In `tf.gather_nd`, `indices` defines slices into + the first `N` dimensions of `params`, where `N = indices.shape[-1]`. + + Caution: On CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, a 0 is stored in the + corresponding output value. + + ## Gathering scalars + + In the simplest case the vectors in `indices` index the full rank of `params`: + + >>> tf.gather_nd( + ... indices=[[0, 0], + ... [1, 1]], + ... params = [['a', 'b'], + ... ['c', 'd']]).numpy() + array([b'a', b'd'], dtype=object) + + In this case the result has 1-axis fewer than `indices`, and each index vector + is replaced by the scalar indexed from `params`. + + In this case the shape relationship is: + + ``` + index_depth = indices.shape[-1] + assert index_depth == params.shape.rank + result_shape = indices.shape[:-1] + ``` + + If `indices` has a rank of `K`, it is helpful to think `indices` as a + (K-1)-dimensional tensor of indices into `params`. + + ## Gathering slices + + If the index vectors do not index the full rank of `params` then each location + in the result contains a slice of params. This example collects rows from a + matrix: + + >>> tf.gather_nd( + ... indices = [[1], + ... [0]], + ... params = [['a', 'b', 'c'], + ... ['d', 'e', 'f']]).numpy() + array([[b'd', b'e', b'f'], + [b'a', b'b', b'c']], dtype=object) + + Here `indices` contains `[2]` index vectors, each with a length of `1`. + The index vectors each refer to rows of the `params` matrix. Each + row has a shape of `[3]` so the output shape is `[2, 3]`. + + In this case, the relationship between the shapes is: + + ``` + index_depth = indices.shape[-1] + outer_shape = indices.shape[:-1] + assert index_depth <= params.shape.rank + inner_shape = params.shape[index_depth:] + output_shape = outer_shape + inner_shape + ``` + + It is helpful to think of the results in this case as tensors-of-tensors. + The shape of the outer tensor is set by the leading dimensions of `indices`. + While the shape of the inner tensors is the shape of a single slice. + + ## Batches + + Additionally, both `params` and `indices` can have `M` leading batch + dimensions that exactly match. In this case `batch_dims` must be set to `M`. + + For example, to collect one row from each of a batch of matrices you could + set the leading elements of the index vectors to be their location in the + batch: + + >>> tf.gather_nd( + ... indices = [[0, 1], + ... [1, 0], + ... [2, 4], + ... [3, 2], + ... [4, 1]], + ... params=tf.zeros([5, 7, 3])).shape.as_list() + [5, 3] + + The `batch_dims` argument lets you omit those leading location dimensions + from the index: + + >>> tf.gather_nd( + ... batch_dims=1, + ... indices = [[1], + ... [0], + ... [4], + ... [2], + ... [1]], + ... params=tf.zeros([5, 7, 3])).shape.as_list() + [5, 3] + + This is equivalent to caling a separate `gather_nd` for each location in the + batch dimensions. + + + >>> params=tf.zeros([5, 7, 3]) + >>> indices=tf.zeros([5, 1]) + >>> batch_dims = 1 + >>> + >>> index_depth = indices.shape[-1] + >>> batch_shape = indices.shape[:batch_dims] + >>> assert params.shape[:batch_dims] == batch_shape + >>> outer_shape = indices.shape[batch_dims:-1] + >>> assert index_depth <= params.shape.rank + >>> inner_shape = params.shape[batch_dims + index_depth:] + >>> output_shape = batch_shape + outer_shape + inner_shape + >>> output_shape.as_list() + [5, 3] + + ### More examples + + Indexing into a 3-tensor: + + >>> tf.gather_nd( + ... indices = [[1]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[[b'a1', b'b1'], + [b'c1', b'd1']]], dtype=object) + + + + >>> tf.gather_nd( + ... indices = [[0, 1], [1, 0]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[b'c0', b'd0'], + [b'a1', b'b1']], dtype=object) + + + >>> tf.gather_nd( + ... indices = [[0, 0, 1], [1, 0, 1]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([b'b0', b'b1'], dtype=object) + + The examples below are for the case when only indices have leading extra + dimensions. If both 'params' and 'indices' have leading batch dimensions, use + the 'batch_dims' parameter to run gather_nd in batch mode. + + Batched indexing into a matrix: + + >>> tf.gather_nd( + ... indices = [[[0, 0]], [[0, 1]]], + ... params = [['a', 'b'], ['c', 'd']]).numpy() + array([[b'a'], + [b'b']], dtype=object) + + + + Batched slice indexing into a matrix: + + >>> tf.gather_nd( + ... indices = [[[1]], [[0]]], + ... params = [['a', 'b'], ['c', 'd']]).numpy() + array([[[b'c', b'd']], + [[b'a', b'b']]], dtype=object) + + + Batched indexing into a 3-tensor: + + >>> tf.gather_nd( + ... indices = [[[1]], [[0]]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[[[b'a1', b'b1'], + [b'c1', b'd1']]], + [[[b'a0', b'b0'], + [b'c0', b'd0']]]], dtype=object) + + + >>> tf.gather_nd( + ... indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[[b'c0', b'd0'], + [b'a1', b'b1']], + [[b'a0', b'b0'], + [b'c1', b'd1']]], dtype=object) + + >>> tf.gather_nd( + ... indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[b'b0', b'b1'], + [b'd0', b'c1']], dtype=object) + + + Examples with batched 'params' and 'indices': + + >>> tf.gather_nd( + ... batch_dims = 1, + ... indices = [[1], + ... [0]], + ... params = [[['a0', 'b0'], + ... ['c0', 'd0']], + ... [['a1', 'b1'], + ... ['c1', 'd1']]]).numpy() + array([[b'c0', b'd0'], + [b'a1', b'b1']], dtype=object) + + + >>> tf.gather_nd( + ... batch_dims = 1, + ... indices = [[[1]], [[0]]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[[b'c0', b'd0']], + [[b'a1', b'b1']]], dtype=object) + + >>> tf.gather_nd( + ... batch_dims = 1, + ... indices = [[[1, 0]], [[0, 1]]], + ... params = [[['a0', 'b0'], ['c0', 'd0']], + ... [['a1', 'b1'], ['c1', 'd1']]]).numpy() + array([[b'c0'], + [b'b1']], dtype=object) + + + See also `tf.gather`. + + Args: + params: A `Tensor`. The tensor from which to gather values. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + name: A name for the operation (optional). + batch_dims: An integer or a scalar 'Tensor'. The number of batch dimensions. + + Returns: + A `Tensor`. Has the same type as `params`. + """ + batch_dims_ = tensor_util.constant_value(batch_dims) + if batch_dims_ is not None: + batch_dims = int(batch_dims_) + if batch_dims == 0: + try: + # TODO(apassos) find a less bad way of detecting resource variables + # without introducing a circular dependency. + return params.gather_nd(indices, name=name) + except AttributeError: + return gen_array_ops.gather_nd(params, indices, name=name) + else: + return batch_gather_nd(params, indices, batch_dims=batch_dims, name=name) + + +@tf_export("gather_nd", v1=[]) +@dispatch.add_dispatch_support +def gather_nd_v2(params, indices, batch_dims=0, name=None): + return gather_nd(params, indices, name=name, batch_dims=batch_dims) + + +gather_nd_v2.__doc__ = gather_nd.__doc__ + + +def batch_gather_nd(params, indices, batch_dims, name=None): + """gather_nd implementation with batch support.""" + with ops.name_scope(name, "BatchGatherND", [params, indices]): + indices = ops.convert_to_tensor(indices, name="indices") + params = ops.convert_to_tensor(params, name="params") + + if not isinstance(batch_dims, int): + raise TypeError(f"Argument `batch_dims` must be an int; got {batch_dims}") + if batch_dims < 0: + raise ValueError("tf.gather_nd does not allow negative batch_dims.") + params_ndims = params.shape.ndims + indices_ndims = indices.shape.ndims + if indices_ndims is not None and batch_dims >= indices_ndims: + raise ValueError(f"Argument `batch_dims` = {batch_dims} must be " + f"less than rank(`indices`) = {indices_ndims}") + if params_ndims is not None and batch_dims >= params_ndims: + raise ValueError(f"Argument `batch_dims` = {batch_dims} must be " + f"less than rank(`params`) = {params_ndims}") + + expand = batch_dims == 0 + if expand: + # Normally gather_nd will be called when batch_dims == 0. + # But if this function is called with batch_dims = 0, e.g. for testing + # purposes, this adds a dummy batch dimension to make batch_dims = 1. + params = expand_dims(params, axis=0) + indices = expand_dims(indices, axis=0) + batch_dims = 1 + + params_shape = shape(params) + indices_shape = shape(indices) + batch_shape = params_shape[:batch_dims] + batch_size = gen_math_ops.prod(batch_shape, [0]) + index_internal_ndims = rank(indices) - batch_dims - 1 + indices_internal_shape = indices_shape[batch_dims:-1] + + # Assuming a 'params' with shape [b1, ..., bM, g1, ..., gN] and an 'indices' + # with shape [b1, ..., bM, i1, ..., iK, C], where C <= N, we need to modify + # 'indices' s.t. it has shape [i1, ..., iK, D], where D <= M + N and slices + # to the entire 'params' tensor. + # Assuming we have a batch of shape [B1, B2], we use meshgrid to create a + # grid of size B1 x B2. + batch_dim_list = array_ops_stack.unstack(batch_shape, axis=0) + dim_ranges = [ + gen_math_ops.cast( + gen_math_ops._range(0, gen_math_ops.cast(x, dtypes.int32), 1), + indices.dtype, + ) + for x in batch_dim_list + ] + mesh_list = meshgrid(*dim_ranges, indexing="ij") if dim_ranges else [] + # Then we flatten and stack the tensors to form a (B1.B2) by 2 matrix. + flat_list = [reshape(x, shape=(-1,)) for x in mesh_list] + index_grid = transpose(array_ops_stack.stack(flat_list, axis=0)) + # We need to concatenate these batch coordinates with the internal indices. + # concat -> index_grid [B1.B2, 2] with indices [i1, ..., iK, C] + # So we reshape them both to [(B1.B2), i1, ..., iK, *] + index_grid_shape = shape(index_grid) + index_grid = reshape( + index_grid, + concat( + [ + index_grid_shape[:1], + ones(index_internal_ndims, dtype=index_grid_shape.dtype), + index_grid_shape[1:], + ], + axis=0, + ), + ) + tile_shape = concat(((1,), indices_internal_shape, (1,)), axis=0) + index_grid = tile(index_grid, multiples=tile_shape) + # index_grid now has shape [(B1.B2), i1, ..., iK, 2] + flat_shape = concat(([batch_size], indices_shape[batch_dims:]), axis=0) + flat_indices = reshape(indices, shape=flat_shape) + # flat_indices now has shape [(B1.B2), i1, ..., iK, C] + indices = concat((index_grid, flat_indices), axis=-1) + # indices has shape [(B1.B2), i1, ..., iK, 2+C] + out = gen_array_ops.gather_nd(params, indices) + # out has shape [(B1.B2), i1, ..., iK, N-C]. Now we reshape batch to + # its original form. + out_shape = shape(out) + out = reshape(out, shape=concat((batch_shape, out_shape[1:]), axis=0)) + if expand: + out = squeeze(out, axis=0) + return out + + +@deprecation.deprecated_endpoints("tensor_scatter_update") +@tf_export( + "tensor_scatter_nd_update", + v1=["tensor_scatter_nd_update", "tensor_scatter_update"]) +@dispatch.add_dispatch_support +def tensor_scatter_nd_update(tensor, indices, updates, name=None): + """Scatter `updates` into an existing tensor according to `indices`. + + This operation creates a new tensor by applying sparse `updates` to the + input `tensor`. This is similar to an index assignment. + + ``` + # Not implemented: tensors cannot be updated inplace. + tensor[indices] = updates + ``` + + If an out of bound index is found on CPU, an error is returned. + + > **WARNING**: There are some GPU specific semantics for this operation. + > + > - If an out of bound index is found, the index is ignored. + > - The order in which updates are applied is nondeterministic, so the output + > will be nondeterministic if `indices` contains duplicates. + + This operation is very similar to `tf.scatter_nd`, except that the updates are + scattered onto an existing tensor (as opposed to a zero-tensor). If the memory + for the existing tensor cannot be re-used, a copy is made and updated. + + In general: + + * `indices` is an integer tensor - the indices to update in `tensor`. + * `indices` has **at least two** axes, the last axis is the depth of the + index vectors. + * For each index vector in `indices` there is a corresponding entry in + `updates`. + * If the length of the index vectors matches the rank of the `tensor`, then + the index vectors each point to scalars in `tensor` and each update is a + scalar. + * If the length of the index vectors is less than the rank of `tensor`, then + the index vectors each point to the slices of `tensor` and shape of the updates + must match that slice. + + Overall this leads to the following shape constraints: + + ``` + assert tf.rank(indices) >= 2 + index_depth = indices.shape[-1] + batch_shape = indices.shape[:-1] + assert index_depth <= tf.rank(tensor) + outer_shape = tensor.shape[:index_depth] + inner_shape = tensor.shape[index_depth:] + assert updates.shape == batch_shape + inner_shape + ``` + + Typical usage is often much simpler than this general form, and it + can be better understood starting with simple examples: + + ### Scalar updates + + The simplest usage inserts scalar elements into a tensor by index. + In this case, the `index_depth` must equal the rank of the + input `tensor`, slice each column of `indices` is an index into an axis of the + input `tensor`. + + In this simplest case the shape constraints are: + + ``` + num_updates, index_depth = indices.shape.as_list() + assert updates.shape == [num_updates] + assert index_depth == tf.rank(tensor)` + ``` + + For example, to insert 4 scattered elements in a rank-1 tensor with + 8 elements. + +
+ +
+ + This scatter operation would look like this: + + >>> tensor = [0, 0, 0, 0, 0, 0, 0, 0] # tf.rank(tensor) == 1 + >>> indices = [[1], [3], [4], [7]] # num_updates == 4, index_depth == 1 + >>> updates = [9, 10, 11, 12] # num_updates == 4 + >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates)) + tf.Tensor([ 0 9 0 10 11 0 0 12], shape=(8,), dtype=int32) + + The length (first axis) of `updates` must equal the length of the `indices`: + `num_updates`. This is the number of updates being inserted. Each scalar + update is inserted into `tensor` at the indexed location. + + For a higher rank input `tensor` scalar updates can be inserted by using an + `index_depth` that matches `tf.rank(tensor)`: + + >>> tensor = [[1, 1], [1, 1], [1, 1]] # tf.rank(tensor) == 2 + >>> indices = [[0, 1], [2, 0]] # num_updates == 2, index_depth == 2 + >>> updates = [5, 10] # num_updates == 2 + >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates)) + tf.Tensor( + [[ 1 5] + [ 1 1] + [10 1]], shape=(3, 2), dtype=int32) + + ### Slice updates + + When the input `tensor` has more than one axis scatter can be used to update + entire slices. + + In this case it's helpful to think of the input `tensor` as being a two level + array-of-arrays. The shape of this two level array is split into the + `outer_shape` and the `inner_shape`. + + `indices` indexes into the outer level of the input tensor (`outer_shape`). + and replaces the sub-array at that location with the corresponding item from + the `updates` list. The shape of each update is `inner_shape`. + + When updating a list of slices the shape constraints are: + + ``` + num_updates, index_depth = indices.shape.as_list() + outer_shape = tensor.shape[:index_depth] + inner_shape = tensor.shape[index_depth:] + assert updates.shape == [num_updates, inner_shape] + ``` + + For example, to update rows of a `(6, 3)` `tensor`: + + >>> tensor = tf.zeros([6, 3], dtype=tf.int32) + + Use an index depth of one. + + >>> indices = tf.constant([[2], [4]]) # num_updates == 2, index_depth == 1 + >>> num_updates, index_depth = indices.shape.as_list() + + The `outer_shape` is `6`, the inner shape is `3`: + + >>> outer_shape = tensor.shape[:index_depth] + >>> inner_shape = tensor.shape[index_depth:] + + 2 rows are being indexed so 2 `updates` must be supplied. + Each update must be shaped to match the `inner_shape`. + + >>> # num_updates == 2, inner_shape==3 + >>> updates = tf.constant([[1, 2, 3], + ... [4, 5, 6]]) + + Altogether this gives: + + >>> tf.tensor_scatter_nd_update(tensor, indices, updates).numpy() + array([[0, 0, 0], + [0, 0, 0], + [1, 2, 3], + [0, 0, 0], + [4, 5, 6], + [0, 0, 0]], dtype=int32) + + #### More slice update examples + + A tensor representing a batch of uniformly sized video clips naturally has 5 + axes: `[batch_size, time, width, height, channels]`. + + For example: + + >>> batch_size, time, width, height, channels = 13,11,7,5,3 + >>> video_batch = tf.zeros([batch_size, time, width, height, channels]) + + To replace a selection of video clips: + * Use an `index_depth` of 1 (indexing the `outer_shape`: `[batch_size]`) + * Provide updates each with a shape matching the `inner_shape`: + `[time, width, height, channels]`. + + To replace the first two clips with ones: + + >>> indices = [[0],[1]] + >>> new_clips = tf.ones([2, time, width, height, channels]) + >>> tf.tensor_scatter_nd_update(video_batch, indices, new_clips) + + To replace a selection of frames in the videos: + + * `indices` must have an `index_depth` of 2 for the `outer_shape`: + `[batch_size, time]`. + * `updates` must be shaped like a list of images. Each update must have a + shape, matching the `inner_shape`: `[width, height, channels]`. + + To replace the first frame of the first three video clips: + + >>> indices = [[0, 0], [1, 0], [2, 0]] # num_updates=3, index_depth=2 + >>> new_images = tf.ones([ + ... # num_updates=3, inner_shape=(width, height, channels) + ... 3, width, height, channels]) + >>> tf.tensor_scatter_nd_update(video_batch, indices, new_images) + + ### Folded indices + + In simple cases it's convenient to think of `indices` and `updates` as + lists, but this is not a strict requirement. Instead of a flat `num_updates`, + the `indices` and `updates` can be folded into a `batch_shape`. This + `batch_shape` is all axes of the `indices`, except for the innermost + `index_depth` axis. + + ``` + index_depth = indices.shape[-1] + batch_shape = indices.shape[:-1] + ``` + + Note: The one exception is that the `batch_shape` cannot be `[]`. You can't + update a single index by passing indices with shape `[index_depth]`. + + `updates` must have a matching `batch_shape` (the axes before `inner_shape`). + + ``` + assert updates.shape == batch_shape + inner_shape + ``` + + Note: The result is equivalent to flattening the `batch_shape` axes of + `indices` and `updates`. This generalization just avoids the need + for reshapes when it is more natural to construct "folded" indices and + updates. + + With this generalization the full shape constraints are: + + ``` + assert tf.rank(indices) >= 2 + index_depth = indices.shape[-1] + batch_shape = indices.shape[:-1] + assert index_depth <= tf.rank(tensor) + outer_shape = tensor.shape[:index_depth] + inner_shape = tensor.shape[index_depth:] + assert updates.shape == batch_shape + inner_shape + ``` + + For example, to draw an `X` on a `(5,5)` matrix start with these indices: + + >>> tensor = tf.zeros([5,5]) + >>> indices = tf.constant([ + ... [[0,0], + ... [1,1], + ... [2,2], + ... [3,3], + ... [4,4]], + ... [[0,4], + ... [1,3], + ... [2,2], + ... [3,1], + ... [4,0]], + ... ]) + >>> indices.shape.as_list() # batch_shape == [2, 5], index_depth == 2 + [2, 5, 2] + + Here the `indices` do not have a shape of `[num_updates, index_depth]`, but a + shape of `batch_shape+[index_depth]`. + + Since the `index_depth` is equal to the rank of `tensor`: + + * `outer_shape` is `(5,5)` + * `inner_shape` is `()` - each update is scalar + * `updates.shape` is `batch_shape + inner_shape == (5,2) + ()` + + >>> updates = [ + ... [1,1,1,1,1], + ... [1,1,1,1,1], + ... ] + + Putting this together gives: + + >>> tf.tensor_scatter_nd_update(tensor, indices, updates).numpy() + array([[1., 0., 0., 0., 1.], + [0., 1., 0., 1., 0.], + [0., 0., 1., 0., 0.], + [0., 1., 0., 1., 0.], + [1., 0., 0., 0., 1.]], dtype=float32) + + Args: + tensor: Tensor to copy/update. + indices: Indices to update. + updates: Updates to apply at the indices. + name: Optional name for the operation. + + Returns: + A new tensor with the given shape and updates applied according to the + indices. + """ + return gen_array_ops.tensor_scatter_update( + tensor=tensor, indices=indices, updates=updates, name=name) + + +# Define quantize_v2 here in order to make name the second-to-last attribute, +# because round_mode was added later. +# (And also now because of 'axis' processing). +@tf_export(v1=["quantize_v2"]) +@dispatch.add_dispatch_support +@deprecation.deprecated( + "2017-10-25", + "`tf.quantize_v2` is deprecated, please use `tf.quantization.quantize` " + "instead.") # pylint: disable=missing-docstring +def quantize_v2( + input, # pylint: disable=redefined-builtin + min_range, + max_range, + T, + mode="MIN_COMBINED", + name=None, + round_mode="HALF_AWAY_FROM_ZERO", + narrow_range=False, + axis=None, + ensure_minimum_range=0.01): + if axis is None: + axis = -1 + elif axis < 0: + if input.shape.ndims is None: + raise ValueError("input should have known rank to use negative axis.") + axis %= input.shape.ndims + + if ensure_minimum_range != 0.01: + return gen_array_ops.quantize_v2( + input, + min_range, + max_range, + T=T, + mode=mode, + name=name, + round_mode=round_mode, + narrow_range=narrow_range, + axis=axis, + ensure_minimum_range=ensure_minimum_range) + return gen_array_ops.quantize_v2( + input, + min_range, + max_range, + T=T, + mode=mode, + name=name, + round_mode=round_mode, + narrow_range=narrow_range, + axis=axis) + + +quantize_v2.__doc__ = """Please use `tf.quantization.quantize` instead.""" + + +# We want to expose tf.quantization.quantize instead of +# tf.quantization.quantize; we can deprecate tf.quantization.quantize in next +# version of TensorFlow. +@tf_export("quantization.quantize", v1=["quantization.quantize", "quantize"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("quantize") +def quantize( + input, # pylint: disable=redefined-builtin + min_range, + max_range, + T, + mode="MIN_COMBINED", + round_mode="HALF_AWAY_FROM_ZERO", + name=None, + narrow_range=False, + axis=None, + ensure_minimum_range=0.01): + """Quantize the input tensor.""" + if ensure_minimum_range != 0.01: + return quantize_v2( + input, + min_range, + max_range, + T, + mode=mode, + round_mode=round_mode, + name=name, + narrow_range=narrow_range, + axis=axis, + ensure_minimum_range=ensure_minimum_range) + return quantize_v2( + input, + min_range, + max_range, + T, + mode=mode, + round_mode=round_mode, + name=name, + narrow_range=narrow_range, + axis=axis) + + +@tf_export("quantization.dequantize", v1=["quantization.dequantize", + "dequantize"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("dequantize") +def dequantize( # pylint: disable=missing-docstring + input, # pylint: disable=redefined-builtin + min_range, + max_range, + mode="MIN_COMBINED", + name=None, + axis=None, + narrow_range=False, + dtype=dtypes.float32): + if axis is None: + axis = -1 + elif axis < 0: + if input.shape.ndims is None: + raise ValueError("input should have known rank to use negative axis.") + axis %= input.shape.ndims + + if axis >= 0 or narrow_range: + return gen_array_ops.dequantize( + input, + min_range, + max_range, + mode=mode, + name=name, + narrow_range=narrow_range, + axis=axis, + dtype=dtype) + return gen_array_ops.dequantize( + input, min_range, max_range, mode=mode, name=name, dtype=dtype) + + +dequantize.__doc__ = gen_array_ops.dequantize.__doc__ + + +@tf_export("quantization.quantize_and_dequantize") +@dispatch.add_dispatch_support +@deprecation.deprecated(None, + "This Op has been deprecated, use" + + "`quantize_and_dequantize_v2` instead. To " + + "To simulate the V1 the behavior of " + + "tf.quantization.quantize_and_dequantize(...) use " + + "tf.grad_pass_through(" + + "tf.quantization.quantize_and_dequantize_v2)(...).") +def quantize_and_dequantize( + input, # pylint: disable=redefined-builtin + input_min, + input_max, + signed_input=True, + num_bits=8, + range_given=False, + round_mode="HALF_TO_EVEN", + name=None, + narrow_range=False, + axis=None): + """Quantizes then dequantizes a tensor. + + Args: + input: A `Tensor` to quantize and dequantize. + input_min: If range_given=True, the minimum input value, that needs to be + represented in the quantized representation. If axis is specified, this + should be a vector of minimum values for each slice along axis. + input_max: If range_given=True, the maximum input value that needs to be + represented in the quantized representation. If axis is specified, this + should be a vector of maximum values for each slice along axis. + signed_input: True if the quantization is signed or unsigned. + num_bits: The bitwidth of the quantization. + range_given: If true use `input_min` and `input_max` for the range of the + input, otherwise determine min and max from the input `Tensor`. + round_mode: Rounding mode when rounding from float values to quantized ones. + one of ['HALF_TO_EVEN', 'HALF_UP'] + name: Optional name for the operation. + narrow_range: If true, then the absolute value of the quantized minimum + value is the same as the quantized maximum value, instead of 1 greater. + i.e. for 8 bit quantization, the minimum value is -127 instead of -128. + axis: Integer. If specified, refers to a dimension of the input tensor, such + that quantization will be per slice along that dimension. + + Returns: + A `Tensor`. Each element is the result of quantizing and dequantizing the + corresponding element of `input`. + """ + if axis is None: + axis = -1 + elif axis < 0: + if input.shape.ndims is None: + raise ValueError("input should have known rank to use negative axis.") + axis %= input.shape.ndims + + return gen_array_ops.quantize_and_dequantize_v2( + input, + input_min=input_min, + input_max=input_max, + signed_input=signed_input, + num_bits=num_bits, + range_given=range_given, + round_mode=round_mode, + narrow_range=narrow_range, + axis=axis, + name=name) + + +@tf_export("quantization.quantize_and_dequantize_v2") +@dispatch.add_dispatch_support +def quantize_and_dequantize_v2( + input, # pylint: disable=redefined-builtin + input_min, + input_max, + signed_input=True, + num_bits=8, + range_given=False, + round_mode="HALF_TO_EVEN", + name=None, + narrow_range=False, + axis=None): + """Quantizes then dequantizes a tensor. + + Updates the gradient definition for quantization that is outside the range to + be 0.To simulate the V1 the behavior of + tf.quantization.quantize_and_dequantize(...) use + tf.grad_pass_through(tf.quantization.quantize_and_dequantize_v2)(...). + + Example usage: + + ```python + def getQuantizeOp(input): + input_tensor = tf.placeholder(tf.float32, shape=[4, 4]) + net = tf.quantization.quantize_and_dequantize(input, + input_min=min_threshold, + input_max=max_threshold, + range_given=True) + + To simulate v1 behavior: + + def testDecomposeQuantizeDequantize(self): + def f(input_tensor): + return tf.quantization.quantize_and_dequantize_v2(input_tensor, + input_min = 5.0, + input_max= -10.0, + range_given=True) + input_tensor = tf.placeholder(tf.float32, shape=[4, 4]) + net = tf.grad_pass_through(f)(input_tensor) + ``` + + Args: + input: A `Tensor` to quantize and dequantize. + input_min: If range_given=True, the minimum input value, that needs to be + represented in the quantized representation. If axis is specified, this + should be a vector of minimum values for each slice along axis. + input_max: If range_given=True, the maximum input value that needs to be + represented in the quantized representation. If axis is specified, this + should be a vector of maximum values for each slice along axis. + signed_input: True if the quantization is signed or unsigned. + num_bits: The bitwidth of the quantization. + range_given: If true use `input_min` and `input_max` for the range of the + input, otherwise determine min and max from the input `Tensor`. + round_mode: Rounding mode when rounding from float values to quantized ones. + one of ['HALF_TO_EVEN', 'HALF_UP'] + name: Optional name for the operation. + narrow_range: If true, then the absolute value of the quantized minimum + value is the same as the quantized maximum value, instead of 1 greater. + i.e. for 8 bit quantization, the minimum value is -127 instead of -128. + axis: Integer. If specified, refers to a dimension of the input tensor, such + that quantization will be per slice along that dimension. + + Returns: + A `Tensor`. Each element is the result of quantizing and dequantizing the + corresponding element of `input`. + """ + if axis is None: + axis = -1 + elif axis < 0: + if input.shape.ndims is None: + raise ValueError("input should have known rank to use negative axis.") + axis %= input.shape.ndims + + return gen_array_ops.quantize_and_dequantize_v4( + input, + input_min=input_min, + input_max=input_max, + signed_input=signed_input, + num_bits=num_bits, + range_given=range_given, + round_mode=round_mode, + narrow_range=narrow_range, + axis=axis, + name=name) + + +@tf_export("searchsorted") +@dispatch.add_dispatch_support +def searchsorted(sorted_sequence, + values, + side="left", + out_type=dtypes.int32, + name=None): + """Searches for where a value would go in a sorted sequence. + + This is not a method for checking containment (like python `in`). + + The typical use case for this operation is "binning", "bucketing", or + "discretizing". The `values` are assigned to bucket-indices based on the + **edges** listed in `sorted_sequence`. This operation + returns the bucket-index for each value. + + >>> edges = [-1, 3.3, 9.1, 10.0] + >>> values = [0.0, 4.1, 12.0] + >>> tf.searchsorted(edges, values).numpy() + array([1, 2, 4], dtype=int32) + + The `side` argument controls which index is returned if a value lands exactly + on an edge: + + >>> seq = [0, 3, 9, 10, 10] + >>> values = [0, 4, 10] + >>> tf.searchsorted(seq, values).numpy() + array([0, 2, 3], dtype=int32) + >>> tf.searchsorted(seq, values, side="right").numpy() + array([1, 2, 5], dtype=int32) + + The `axis` is not settable for this operation. It always operates on the + innermost dimension (`axis=-1`). The operation will accept any number of + outer dimensions. Here it is applied to the rows of a matrix: + + >>> sorted_sequence = [[0., 3., 8., 9., 10.], + ... [1., 2., 3., 4., 5.]] + >>> values = [[9.8, 2.1, 4.3], + ... [0.1, 6.6, 4.5, ]] + >>> tf.searchsorted(sorted_sequence, values).numpy() + array([[4, 1, 2], + [0, 5, 4]], dtype=int32) + + Note: This operation assumes that `sorted_sequence` **is sorted** along the + innermost axis, maybe using `tf.sort(..., axis=-1)`. **If the sequence is not + sorted, no error is raised** and the content of the returned tensor is not well + defined. + + Args: + sorted_sequence: N-D `Tensor` containing a sorted sequence. + values: N-D `Tensor` containing the search values. + side: 'left' or 'right'; 'left' corresponds to lower_bound and 'right' to + upper_bound. + out_type: The output type (`int32` or `int64`). Default is `tf.int32`. + name: Optional name for the operation. + + Returns: + An N-D `Tensor` the size of `values` containing the result of applying + either lower_bound or upper_bound (depending on side) to each value. The + result is not a global index to the entire `Tensor`, but the index in the + last dimension. + + Raises: + ValueError: If the last dimension of `sorted_sequence >= 2^31-1` elements. + If the total size of `values` exceeds `2^31 - 1` elements. + If the first `N-1` dimensions of the two tensors don't match. + """ + sequence_size = shape_internal(sorted_sequence)[-1] + values_size = shape_internal(values)[-1] + sorted_sequence_2d = reshape(sorted_sequence, [-1, sequence_size]) + values_2d = reshape(values, [-1, values_size]) + if side == "right": + output = gen_array_ops.upper_bound(sorted_sequence_2d, values_2d, out_type, + name) + elif side == "left": + output = gen_array_ops.lower_bound(sorted_sequence_2d, values_2d, out_type, + name) + else: + raise ValueError("Argument `side` must be either 'right' or 'left'. " + f"Received: `side` = '{side}'.") + return reshape(output, shape_internal(values)) + + +quantize.__doc__ = gen_array_ops.quantize_v2.__doc__ + + +@tf_export("image.extract_patches") +@dispatch.add_dispatch_support +def extract_image_patches_v2(images, sizes, strides, rates, padding, name=None): + r"""Extract `patches` from `images`. + + This op collects patches from the input image, as if applying a + convolution. All extracted patches are stacked in the depth (last) dimension + of the output. + + Specifically, the op extracts patches of shape `sizes` which are `strides` + apart in the input image. The output is subsampled using the `rates` argument, + in the same manner as "atrous" or "dilated" convolutions. + + The result is a 4D tensor which is indexed by batch, row, and column. + `output[i, x, y]` contains a flattened patch of size `sizes[1], sizes[2]` + which is taken from the input starting at + `images[i, x*strides[1], y*strides[2]]`. + + Each output patch can be reshaped to `sizes[1], sizes[2], depth`, where + `depth` is `images.shape[3]`. + + The output elements are taken from the input at intervals given by the `rate` + argument, as in dilated convolutions. + + The `padding` argument has no effect on the size of each patch, it determines + how many patches are extracted. If `VALID`, only patches which are fully + contained in the input image are included. If `SAME`, all patches whose + starting point is inside the input are included, and areas outside the input + default to zero. + + Example: + + ``` + n = 10 + # images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100 + images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]] + + # We generate two outputs as follows: + # 1. 3x3 patches with stride length 5 + # 2. Same as above, but the rate is increased to 2 + tf.image.extract_patches(images=images, + sizes=[1, 3, 3, 1], + strides=[1, 5, 5, 1], + rates=[1, 1, 1, 1], + padding='VALID') + + # Yields: + [[[[ 1 2 3 11 12 13 21 22 23] + [ 6 7 8 16 17 18 26 27 28]] + [[51 52 53 61 62 63 71 72 73] + [56 57 58 66 67 68 76 77 78]]]] + ``` + + If we mark the pixels in the input image which are taken for the output with + `*`, we see the pattern: + + ``` + * * * 4 5 * * * 9 10 + * * * 14 15 * * * 19 20 + * * * 24 25 * * * 29 30 + 31 32 33 34 35 36 37 38 39 40 + 41 42 43 44 45 46 47 48 49 50 + * * * 54 55 * * * 59 60 + * * * 64 65 * * * 69 70 + * * * 74 75 * * * 79 80 + 81 82 83 84 85 86 87 88 89 90 + 91 92 93 94 95 96 97 98 99 100 + ``` + + ``` + tf.image.extract_patches(images=images, + sizes=[1, 3, 3, 1], + strides=[1, 5, 5, 1], + rates=[1, 2, 2, 1], + padding='VALID') + + # Yields: + [[[[ 1 3 5 21 23 25 41 43 45] + [ 6 8 10 26 28 30 46 48 50]] + + [[ 51 53 55 71 73 75 91 93 95] + [ 56 58 60 76 78 80 96 98 100]]]] + ``` + + We can again draw the effect, this time using the symbols `*`, `x`, `+` and + `o` to distinguish the patches: + + ``` + * 2 * 4 * x 7 x 9 x + 11 12 13 14 15 16 17 18 19 20 + * 22 * 24 * x 27 x 29 x + 31 32 33 34 35 36 37 38 39 40 + * 42 * 44 * x 47 x 49 x + + 52 + 54 + o 57 o 59 o + 61 62 63 64 65 66 67 68 69 70 + + 72 + 74 + o 77 o 79 o + 81 82 83 84 85 86 87 88 89 90 + + 92 + 94 + o 97 o 99 o + ``` + + Args: + images: A 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. + sizes: The size of the extracted patches. Must be + `[1, size_rows, size_cols, 1]`. + strides: A 1-D Tensor of length 4. How far the centers of two consecutive + patches are in the images. Must be: `[1, stride_rows, stride_cols, 1]`. + rates: A 1-D Tensor of length 4. Must be: `[1, rate_rows, rate_cols, 1]`. + This is the input stride, specifying how far two consecutive patch samples + are in the input. Equivalent to extracting patches with `patch_sizes_eff = + patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling + them spatially by a factor of `rates`. This is equivalent to `rate` in + dilated (a.k.a. Atrous) convolutions. + padding: The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A 4-D Tensor of the same type as the input. + """ + return gen_array_ops.extract_image_patches(images, sizes, strides, rates, + padding, name) + + +@tf_export(v1=["image.extract_image_patches", "extract_image_patches"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "ksizes is deprecated, use sizes instead", + "ksizes") +def extract_image_patches( # pylint: disable=missing-docstring + images, + ksizes=None, + strides=None, + rates=None, + padding=None, + name=None, + sizes=None): + """Extract patches from images and put them in the "depth" output dimension. + + Args: + `images`: A `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, + `uint16`, `half`, `uint32`, `uint64`. 4-D Tensor with shape + `[batch, in_rows, in_cols, depth]`. `ksizes`: A list of `ints` that has + length `>= 4`. The size of the sliding window for each + dimension of `images`. `strides`: A list of `ints` that has length `>= 4`. + 1-D of length 4. How far the centers of two consecutive + patches are in the images. Must be: + `[1, stride_rows, stride_cols, 1]`. `rates`: A list of `ints` + that has length `>= 4`. 1-D of length 4. Must be: `[1, rate_rows, rate_cols, + 1]`. This is the input stride, specifying how far two consecutive patch + samples are in the input. Equivalent to extracting patches with + `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, + followed by subsampling them spatially by a factor of `rates`. This is + equivalent to `rate` in dilated (a.k.a. Atrous) convolutions. + `padding`: A `string` from: "SAME", "VALID". The type of padding algorithm + to use. + We specify the size-related attributes as: ``` ksizes = [1, ksize_rows, + ksize_cols, 1] strides = [1, strides_rows, strides_cols, 1] rates = [1, + rates_rows, rates_cols, 1] + name: A name for the operation (optional). ``` + + Returns: + A Tensor. Has the same type as images. + """ + ksizes = deprecation.deprecated_argument_lookup("sizes", sizes, "ksizes", + ksizes) + return gen_array_ops.extract_image_patches(images, ksizes, strides, rates, + padding, name) + + +extract_image_patches.__doc__ = gen_array_ops.extract_image_patches.__doc__ + + +@tf_export("fingerprint") +@dispatch.add_dispatch_support +def fingerprint(data, method="farmhash64", name=None): + r"""Generates fingerprint values. + + Generates fingerprint values of `data`. + + Fingerprint op considers the first dimension of `data` as the batch dimension, + and `output[i]` contains the fingerprint value generated from contents in + `data[i, ...]` for all `i`. + + Fingerprint op writes fingerprint values as byte arrays. For example, the + default method `farmhash64` generates a 64-bit fingerprint value at a time. + This 8-byte value is written out as an `tf.uint8` array of size 8, in + little-endian order. + + For example, suppose that `data` has data type `tf.int32` and shape (2, 3, 4), + and that the fingerprint method is `farmhash64`. In this case, the output + shape is (2, 8), where 2 is the batch dimension size of `data`, and 8 is the + size of each fingerprint value in bytes. `output[0, :]` is generated from + 12 integers in `data[0, :, :]` and similarly `output[1, :]` is generated from + other 12 integers in `data[1, :, :]`. + + Note that this op fingerprints the raw underlying buffer, and it does not + fingerprint Tensor's metadata such as data type and/or shape. For example, the + fingerprint values are invariant under reshapes and bitcasts as long as the + batch dimension remain the same: + + ```python + tf.fingerprint(data) == tf.fingerprint(tf.reshape(data, ...)) + tf.fingerprint(data) == tf.fingerprint(tf.bitcast(data, ...)) + ``` + + For string data, one should expect `tf.fingerprint(data) != + tf.fingerprint(tf.string.reduce_join(data))` in general. + + Args: + data: A `Tensor`. Must have rank 1 or higher. + method: A `Tensor` of type `tf.string`. Fingerprint method used by this op. + Currently, available method is `farmhash64`. + name: A name for the operation (optional). + + Returns: + A two-dimensional `Tensor` of type `tf.uint8`. The first dimension equals to + `data`'s first dimension, and the second dimension size depends on the + fingerprint algorithm. + """ + return gen_array_ops.fingerprint(data, method, name) + + +def convert_to_int_tensor(tensor, name, dtype=dtypes.int32): + """Converts the given value to an integer Tensor.""" + tensor = ops.convert_to_tensor( + tensor, name=name, preferred_dtype=dtype or dtypes.int32) + if tensor.dtype.is_integer: + if dtype is not None: + tensor = gen_math_ops.cast(tensor, dtype) + else: + raise TypeError(f"Argument `tensor` (name: {name}) must be of type integer." + f" Received `tensor` = {tensor} of dtype: {tensor.dtype}") + return tensor + + +def get_positive_axis(axis, ndims, axis_name="axis", ndims_name="ndims"): + """Validate an `axis` parameter, and normalize it to be positive. + + If `ndims` is known (i.e., not `None`), then check that `axis` is in the + range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or + `axis + ndims` (otherwise). + If `ndims` is not known, and `axis` is positive, then return it as-is. + If `ndims` is not known, and `axis` is negative, then report an error. + + Args: + axis: An integer constant + ndims: An integer constant, or `None` + axis_name: The name of `axis` (for error messages). + ndims_name: The name of `ndims` (for error messages). + + Returns: + The normalized `axis` value. + + Raises: + ValueError: If `axis` is out-of-bounds, or if `axis` is negative and + `ndims is None`. + """ + if not isinstance(axis, int): + raise TypeError(f"{axis_name} must be an int; got {type(axis).__name__}") + if ndims is not None: + if 0 <= axis < ndims: + return axis + elif -ndims <= axis < 0: + return axis + ndims + else: + raise ValueError(f"{axis_name}={axis} out of bounds: " + f"expected {-ndims}<={axis_name}<{ndims}") + elif axis < 0: + raise ValueError(f"{axis_name}={axis} may only be negative " + f"if {ndims_name} is statically known.") + return axis + + +# This op is intended to exactly match the semantics of numpy.repeat, with +# one exception: numpy.repeat has special (and somewhat non-intuitive) behavior +# when axis is not specified. Rather than implement that special behavior, we +# simply make `axis` be a required argument. +# +# External (OSS) `tf.repeat` feature request: +# https://github.com/tensorflow/tensorflow/issues/8246 +def repeat_with_axis(data, repeats, axis, name=None): + """Repeats elements of `data`. + + Args: + data: An `N`-dimensional tensor. + repeats: A 1-D integer tensor specifying how many times each element in + `axis` should be repeated. `len(repeats)` must equal `data.shape[axis]`. + Supports broadcasting from a scalar value. + axis: `int`. The axis along which to repeat values. Must be less than + `max(N, 1)`. + name: A name for the operation. + + Returns: + A tensor with `max(N, 1)` dimensions. Has the same shape as `data`, + except that dimension `axis` has size `sum(repeats)`. + + Example usage: + + >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0) + + >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0) + + >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1) + + + """ + # Whether the execution uses the optimized non-XLA implementation below. + # TODO(b/236387200): Separate the implementations at a lower level, so that + # non-XLA path gets the performance benefits and the XLA path is not broken + # after loading a saved model with the optimization. + use_optimized_non_xla_implementation = False + + if not isinstance(axis, int): + raise TypeError("Argument `axis` must be an int. " + f"Received `axis` = {axis} of type {type(axis).__name__}") + + with ops.name_scope(name, "Repeat", [data, repeats]): + data = ops.convert_to_tensor(data, name="data") + # Note: We want to pass dtype=None to convert_to_int_tensor so that the + # existing type is maintained instead of force-casting to int32. However, + # this is not compatible with the implementation used on the XLA path. + if not use_optimized_non_xla_implementation: + repeats = convert_to_int_tensor(repeats, name="repeats") + else: + repeats = convert_to_int_tensor(repeats, name="repeats", dtype=None) + + repeats.shape.with_rank_at_most(1) + + # If `data` is a scalar, then upgrade it to a vector. + data = _with_nonzero_rank(data) + data_shape = shape(data, out_type=repeats.dtype) + + # If `axis` is negative, then convert it to a positive value. + axis = get_positive_axis(axis, data.shape.rank, ndims_name="rank(data)") + + # If we know that `repeats` is a scalar, then we can just tile & reshape. + if repeats.shape.num_elements() == 1: + repeats = reshape(repeats, []) + expanded = expand_dims(data, axis + 1) + tiled = tile_one_dimension(expanded, axis + 1, repeats) + result_shape = concat([ + data_shape[:axis], [repeats * data_shape[axis]], data_shape[axis + 1:] + ], + axis=0) + return reshape(tiled, result_shape) + + # Check data Tensor shapes. + if repeats.shape.ndims == 1: + data.shape.dims[axis].assert_is_compatible_with(repeats.shape[0]) + + repeats = broadcast_to(repeats, [data_shape[axis]]) + + # The implementation on the else branch has better performance. However, it + # does not work on the XLA path since it relies on the range op with a + # shape that is not a compile-time constant. + if not use_optimized_non_xla_implementation: + repeats_original = repeats + + # Broadcast the `repeats` tensor so rank(repeats) == axis + 1. + if repeats.shape.ndims != axis + 1: + repeats_shape = shape(repeats) + repeats_ndims = rank(repeats) + broadcast_shape = concat( + [data_shape[:axis + 1 - repeats_ndims], repeats_shape], axis=0) + repeats = broadcast_to(repeats, broadcast_shape) + repeats.set_shape([None] * (axis + 1)) + + # Create a "sequence mask" based on `repeats`, where slices across `axis` + # contain one `True` value for each repetition. E.g., if + # `repeats = [3, 1, 2]`, then `mask = [[1, 1, 1], [1, 0, 0], [1, 1, 0]]`. + max_repeat = gen_math_ops._max(repeats, _all_dimensions(repeats)) + max_repeat = gen_math_ops.maximum( + ops.convert_to_tensor(0, name="zero", dtype=max_repeat.dtype), + max_repeat) + + mask = sequence_mask(repeats, max_repeat) + + # Add a new dimension around each value that needs to be repeated, and + # then tile that new dimension to match the maximum number of repetitions. + expanded = expand_dims(data, axis + 1) + tiled = tile_one_dimension(expanded, axis + 1, max_repeat) + + # Use `boolean_mask` to discard the extra repeated values. This also + # flattens all dimensions up through `axis`. + masked = boolean_mask(tiled, mask) + + # Reshape the output tensor to add the outer dimensions back. + if axis == 0: + result = masked + else: + repeated_dim_size = gen_math_ops._sum( + repeats_original, + axis=gen_math_ops._range(0, rank(repeats_original), 1)) + result_shape = concat( + [data_shape[:axis], [repeated_dim_size], data_shape[axis + 1:]], + axis=0) + result = reshape(masked, result_shape) + + # Preserve shape information. + if data.shape.ndims is not None: + new_axis_size = 0 if repeats.shape[0] == 0 else None + result.set_shape(data.shape[:axis].concatenate( + [new_axis_size]).concatenate(data.shape[axis + 1:])) + + return result + + else: + # Non-XLA path implementation + # E.g., repeats = [3, 4, 0, 2, 1]. + # E.g., repeats_scan = [3, 7, 7, 9, 10]. + repeats_scan = gen_math_ops.cumsum(repeats) + # This concat just prepends 0 to handle the case when repeats are empty. + # E.g., output_size = [0, 3, 7, 7, 9, 10][-1] = 10. + output_size = concat([zeros(1, dtype=repeats_scan.dtype), repeats_scan], + axis=0)[-1] + # E.g., output_indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. + output_indices = gen_math_ops.range(output_size, dtype=repeats.dtype) + # E.g., gather_indices = [0, 0, 0, 1, 1, 1, 1, 3, 3, 4]. + gather_indices = searchsorted( + repeats_scan, output_indices, side="right", out_type=repeats.dtype) + return gather(data, gather_indices, axis=axis) + + +def tile_one_dimension(data, axis, multiple): + """Tiles a single dimension of a tensor.""" + # Assumes axis is a nonnegative int. + if data.shape.ndims is not None: + multiples = [1] * data.shape.ndims + multiples[axis] = multiple + else: + ones_value = ones(rank(data), dtypes.int32) + multiples = concat([ones_value[:axis], [multiple], ones_value[axis + 1:]], + axis=0) + return tile(data, multiples) + + +def _with_nonzero_rank(data): + """If `data` is scalar, then add a dimension; otherwise return as-is.""" + if data.shape.ndims is not None: + if data.shape.ndims == 0: + return array_ops_stack.stack([data]) + else: + return data + else: + data_shape = shape(data) + data_ndims = rank(data) + return reshape(data, concat([[1], data_shape], axis=0)[-data_ndims:]) + + +@tf_export("repeat") +@dispatch.add_dispatch_support +def repeat(input, repeats, axis=None, name=None): # pylint: disable=redefined-builtin + """Repeat elements of `input`. + + See also `tf.concat`, `tf.stack`, `tf.tile`. + + Args: + input: An `N`-dimensional Tensor. + repeats: An 1-D `int` Tensor. The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. `len(repeats)` + must equal `input.shape[axis]` if axis is not None. + axis: An int. The axis along which to repeat values. By default, (axis=None), + use the flattened input array, and return a flat output array. + name: A name for the operation. + + Returns: + A Tensor which has the same shape as `input`, except along the given axis. + If axis is None then the output array is flattened to match the flattened + input array. + + Example usage: + + >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0) + + + >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0) + + + >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1) + + + >>> repeat(3, repeats=4) + + + >>> repeat([[1,2], [3,4]], repeats=2) + + + """ + if axis is None: + input = reshape(input, [-1]) + axis = 0 + return repeat_with_axis(input, repeats, axis, name) + + +@tf_export("guarantee_const") +@deprecation.deprecated(None, "Not for public use.") +def guarantee_const(input, name=None): # pylint: disable=redefined-builtin + """Promise to the TF runtime that the input tensor is a constant. + + The runtime is then free to make optimizations based on this. + + Returns the input tensor without modification. + + Args: + input: A `Tensor`. + name: A name for this operation. + + Returns: + A `Tensor`. Has the same dtype as `input`. + """ + return gen_array_ops.guarantee_const(input=input, name=name) + + +@tf_export("stop_gradient") +@dispatch.add_dispatch_support +def stop_gradient(input, name=None): # pylint: disable=redefined-builtin + """Stops gradient computation. + + NOTE: This docstring is patched out below. See + tensorflow/core/api_def/base_api/api_def_StopGradient.pbtxt for the full + docstring. That file determines the public documentation page. + + Args: + input: A `Tensor`. + name: A name for this operation. + + Returns: + A `Tensor`. Has the same dtype as `input`. + """ + # Don't expand ResourceVariables, so stop_gradient(variable) will return a + # Tensor. + if (isinstance(input, composite_tensor.CompositeTensor) and + not _pywrap_utils.IsResourceVariable(input)): + return nest.map_structure(stop_gradient, input, expand_composites=True) + # The StopGradient op has a gradient function registered which returns None + # (meaning statically known to be zero). For correctness, that's all we + # need. However, tf.GradientTape often makes decisions about what to keep in + # memory based on which forward-pass tensors are currently being watched, and + # returning None in a gradient is not sufficient to stop watching a tensor + # since the backward function doesn't run in the forward pass. Pausing the + # tape around this op instructs any tf.GradientTapes to ignore the + # forward-pass output of StopGradient, which may be much more efficient. + with record.stop_recording(): + return gen_array_ops.stop_gradient(input, name=name) + + +stop_gradient.__doc__ = gen_array_ops.stop_gradient.__doc__ + + +# Register elementwise ops that don't have Python wrappers. +dispatch.register_unary_elementwise_api(gen_array_ops.check_numerics) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops_stack.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..343313fe135a4330feb554bd117c1d3ad5db2e57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/array_ops_stack.py @@ -0,0 +1,214 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# Tests for this file live in python/kernel_tests/array_ops_test.py +"""Operations to stack and unstack tensors.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("stack") +@dispatch.add_dispatch_support +def stack(values, axis=0, name="stack"): + """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor. + + See also `tf.concat`, `tf.tile`, `tf.repeat`. + + Packs the list of tensors in `values` into a tensor with rank one higher than + each tensor in `values`, by packing them along the `axis` dimension. + Given a list of length `N` of tensors of shape `(A, B, C)`; + + if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. + if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. + Etc. + + For example: + + >>> x = tf.constant([1, 4]) + >>> y = tf.constant([2, 5]) + >>> z = tf.constant([3, 6]) + >>> tf.stack([x, y, z]) + + >>> tf.stack([x, y, z], axis=1) + + + This is the opposite of unstack. The numpy equivalent is `np.stack` + + >>> np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z])) + True + + Args: + values: A list of `Tensor` objects with the same shape and type. + axis: An `int`. The axis to stack along. Defaults to the first dimension. + Negative values wrap around, so the valid range is `[-(R+1), R+1)`. + name: A name for this operation (optional). + + Returns: + output: A stacked `Tensor` with the same type as `values`. + + Raises: + ValueError: If `axis` is out of the range [-(R+1), R+1). + """ + if axis == 0: + try: + # If the input is a constant list, it can be converted to a constant op + return ops.convert_to_tensor(values, name=name) + except (TypeError, ValueError, NotImplementedError): + pass # Input list contains non-constant tensors + + value_shape = ops.convert_to_tensor(values[0], name=name)._shape_tuple() # pylint: disable=protected-access + if value_shape is not None: + expanded_num_dims = len(value_shape) + 1 + if axis < -expanded_num_dims or axis >= expanded_num_dims: + raise ValueError(f"Argument `axis` = {axis} not in range " + f"[{-expanded_num_dims}, {expanded_num_dims})") + + return gen_array_ops.pack(values, axis=axis, name=name) + + +@tf_export("unstack") +@dispatch.add_dispatch_support +def unstack(value, num=None, axis=0, name="unstack"): + """Unpacks the given dimension of a rank-`R` tensor into rank-`(R-1)` tensors. + + Unpacks tensors from `value` by chipping it along the `axis` dimension. + + >>> x = tf.reshape(tf.range(12), (3,4)) + >>> + >>> p, q, r = tf.unstack(x) + >>> p.shape.as_list() + [4] + + >>> i, j, k, l = tf.unstack(x, axis=1) + >>> i.shape.as_list() + [3] + + This is the opposite of stack. + + >>> x = tf.stack([i, j, k, l], axis=1) + + More generally if you have a tensor of shape `(A, B, C, D)`: + + >>> A, B, C, D = [2, 3, 4, 5] + >>> t = tf.random.normal(shape=[A, B, C, D]) + + The number of tensor returned is equal to the length of the target `axis`: + + >>> axis = 2 + >>> items = tf.unstack(t, axis=axis) + >>> len(items) == t.shape[axis] + True + + The shape of each result tensor is equal to the shape of the input tensor, + with the target `axis` removed. + + >>> items[0].shape.as_list() # [A, B, D] + [2, 3, 5] + + The value of each tensor `items[i]` is equal to the slice of `input` across + `axis` at index `i`: + + >>> for i in range(len(items)): + ... slice = t[:,:,i,:] + ... assert tf.reduce_all(slice == items[i]) + + #### Python iterable unpacking + + With eager execution you _can_ unstack the 0th axis of a tensor using python's + iterable unpacking: + + >>> t = tf.constant([1,2,3]) + >>> a,b,c = t + + `unstack` is still necessary because Iterable unpacking doesn't work in + a `@tf.function`: Symbolic tensors are not iterable. + + You need to use `tf.unstack` here: + + >>> @tf.function + ... def bad(t): + ... a,b,c = t + ... return a + >>> + >>> bad(t) + Traceback (most recent call last): + ... + OperatorNotAllowedInGraphError: ... + + >>> @tf.function + ... def good(t): + ... a,b,c = tf.unstack(t) + ... return a + >>> + >>> good(t).numpy() + 1 + + #### Unknown shapes + + Eager tensors have concrete values, so their shape is always known. + Inside a `tf.function` the symbolic tensors may have unknown shapes. + If the length of `axis` is unknown `tf.unstack` will fail because it cannot + handle an unknown number of tensors: + + >>> @tf.function(input_signature=[tf.TensorSpec([None], tf.float32)]) + ... def bad(t): + ... tensors = tf.unstack(t) + ... return tensors[0] + >>> + >>> bad(tf.constant([1.0, 2.0, 3.0])) + Traceback (most recent call last): + ... + ValueError: Cannot infer argument `num` from shape (None,) + + If you know the `axis` length you can pass it as the `num` argument. But this + must be a constant value. + + If you actually need a variable number of tensors in a single `tf.function` + trace, you will need to use exlicit loops and a `tf.TensorArray` instead. + + Args: + value: A rank `R > 0` `Tensor` to be unstacked. + num: An `int`. The length of the dimension `axis`. Automatically inferred if + `None` (the default). + axis: An `int`. The axis to unstack along. Defaults to the first dimension. + Negative values wrap around, so the valid range is `[-R, R)`. + name: A name for the operation (optional). + + Returns: + The list of `Tensor` objects unstacked from `value`. + + Raises: + ValueError: If `axis` is out of the range `[-R, R)`. + ValueError: If `num` is unspecified and cannot be inferred. + InvalidArgumentError: If `num` does not match the shape of `value`. + """ + if num is None: + value = ops.convert_to_tensor(value) + value_shape = value.get_shape() + if value_shape.ndims is not None: + if axis < -value_shape.ndims or axis >= value_shape.ndims: + raise ValueError(f"Argument `axis` = {axis} not in range " + f"[{-value_shape.ndims}, {value_shape.ndims})") + num = value_shape.dims[axis].value + if num is None: + raise ValueError(f"Cannot infer argument `num` from shape {value_shape}") + return gen_array_ops.unpack(value, num=num, axis=axis, name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/autograph_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/autograph_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d99491abca37aa8755c9d762499b78384e40eb96 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/autograph_ops.py @@ -0,0 +1,146 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Autograph specific overrides for objects covered by tensor_util.is_tf_type.""" + +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import script_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops.parallel_for import control_flow_ops as parallel_ops + + +def wrap_py_func(f, args, kwargs=None): + """Helper that wraps a callable to py_func. + + The helper passes tensor arguments through the py_func interface. Non-tensor + arguments are allowed, and will be passed to f directly. Note that non-tensor + arguments are captured by f will not update every time the wrapper is + called (this is consistent with its argument list, which only includes + the tensor arguments). In general, it's safest not to reuse this wrapper. + + Args: + f: Callable + args: Positional arguments for f, as list or tuple. + kwargs: Keyword arguments for f, as dict with string keys. May be None. + + Returns: + The return values of f converted to tensor. + Raises: + ValueError: if any of the arguments are incorrect. + """ + tensor_args = [] + tensor_args_idx = {} + + # Of the positional arguments, only grab the tensor ones to be passed through + # the py_func. + n_args = len(args) + arg_is_tensor = tuple(map(tensor_util.is_tf_type, args)) + for i in range(n_args): + if arg_is_tensor[i]: + tensor_args_idx[i] = len(tensor_args) + tensor_args.append(args[i]) + + # We essentially take the tensor kwargs, if any, and add them to the list of + # positional arguments. The kwargs are then reconstructed inside the py_func. + # + # For example, if + # + # args = [Tensor(1), 'foo'] + # kwargs = {'a': Tensor(2), 'b': 'bar'} + # + # Then + # + # tensor_args = (Tensor(1), Tensor(2)) + # kwarg_keys = ('a', 'b') + if kwargs: + kwarg_keys = tuple(kwargs.keys()) + kwarg_is_tensor = {k: tensor_util.is_tf_type(kwargs[k]) for k in kwarg_keys} + for k in kwarg_keys: + if kwarg_is_tensor[k]: + tensor_args_idx[k] = len(tensor_args) + tensor_args.append(kwargs[k]) + else: + kwarg_keys = () + + def f_wrapper(*tensor_args): + f_args = tuple( + tensor_args[tensor_args_idx[i]] if arg_is_tensor[i] else a + for i, a in enumerate(args) + ) + f_kwargs = { + k: tensor_args[tensor_args_idx[k]] if kwarg_is_tensor[k] else kwargs[k] + for i, k in enumerate(kwarg_keys) + } + f(*f_args, **f_kwargs) + return 1 + + return script_ops.eager_py_func(f_wrapper, tensor_args, dtypes.int32) + + +def _tf_py_func_print(*objects, **kwargs): + """Overload of print_ as a py_func implementation.""" + override_kwargs = { + k: v for k, v in kwargs.items() if v is not py_builtins.UNSPECIFIED + } + if 'flush' not in override_kwargs: + # Defaulting to flushing the console in graph mode, which helps reduce + # garbled output in IPython. + override_kwargs['flush'] = True + + def print_wrapper(*vals, **kwargs): + vals = tuple(v.numpy() if tensor_util.is_tf_type(v) else v for v in vals) + # TensorFlow doesn't seem to generate Unicode when passing strings to + # py_func. This causes the print to add a "b'" wrapper to the output, + # which is probably never what you want. + vals = tuple(v.decode('utf-8') if isinstance(v, bytes) else v for v in vals) + print(*vals, **kwargs) + + return wrap_py_func(print_wrapper, objects, override_kwargs) + + +def _tf_sorted(iterable, key, reverse): + """Overload of sorted_ for Tensor iterable.""" + if reverse is py_builtins.UNSPECIFIED: + direction = 'ASCENDING' + else: + direction = 'DESCENDING' + if key is not py_builtins.UNSPECIFIED: + mapped = parallel_ops.vectorized_map(key, iterable) + if mapped.shape.rank is not None and mapped.shape.rank != 1: + raise ValueError('sort only supports only 1D tensors') + with ops.control_dependencies([ + check_ops.assert_rank_v2(mapped, 1, + 'sort only supports only 1D tensors') + ]): + order = sort_ops.argsort(mapped, direction=direction) + return array_ops.gather_v2(iterable, order) + if iterable.shape.rank is not None and iterable.shape.rank != 1: + raise ValueError('sort only supports only 1D tensors') + with ops.control_dependencies([ + check_ops.assert_rank_v2(iterable, 1, + 'sort only supports only 1D tensors') + ]): + return sort_ops.sort(iterable, direction=direction) + +py_builtins.print_registry.register( + tensor_util.tf_type_classes, _tf_py_func_print +) +py_builtins.sorted_registry.register( + tensor_util.tf_type_classes, _tf_sorted +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/batch_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/batch_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0361ea242946b32ecd38b8a61cad096dbadd813c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/batch_ops.py @@ -0,0 +1,123 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations for automatic batching and unbatching.""" +from tensorflow.python.eager import def_function +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import gen_batch_ops +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_batch_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("nondifferentiable_batch_function") +def batch_function(num_batch_threads, + max_batch_size, + batch_timeout_micros, + allowed_batch_sizes=None, + max_enqueued_batches=10, + autograph=True, + enable_large_batch_splitting=True): + """Batches the computation done by the decorated function. + + So, for example, in the following code + + ```python + @batch_function(1, 2, 3) + def layer(a): + return tf.matmul(a, a) + + b = layer(w) + ``` + + if more than one session.run call is simultaneously trying to compute `b` + the values of `w` will be gathered, non-deterministically concatenated + along the first axis, and only one thread will run the computation. See the + documentation of the `Batch` op for more details. + + Assumes that all arguments of the decorated function are Tensors which will + be batched along their first dimension. + + SparseTensor is not supported. The return value of the decorated function + must be a Tensor or a list/tuple of Tensors. + + Args: + num_batch_threads: Number of scheduling threads for processing batches + of work. Determines the number of batches processed in parallel. + max_batch_size: Batch sizes will never be bigger than this. + batch_timeout_micros: Maximum number of microseconds to wait before + outputting an incomplete batch. + allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, + does nothing. Otherwise, supplies a list of batch sizes, causing the op + to pad batches up to one of those sizes. The entries must increase + monotonically, and the final entry must equal max_batch_size. + max_enqueued_batches: The maximum depth of the batch queue. Defaults to 10. + autograph: Whether to use autograph to compile python and eager style code + for efficient graph-mode execution. + enable_large_batch_splitting: The value of this option doesn't affect + processing output given the same input; it affects implementation details + as stated below: 1. Improve batching efficiency by eliminating unnecessary + adding. 2.`max_batch_size` specifies the limit of input and + `allowed_batch_sizes` specifies the limit of a task to be processed. API + user can give an input of size 128 when 'max_execution_batch_size' + is 32 -> implementation can split input of 128 into 4 x 32, schedule + concurrent processing, and then return concatenated results corresponding + to 128. + + Returns: + The decorated function will return the unbatched computation output Tensors. + """ + + def decorator(fn): # pylint: disable=missing-docstring + + def decorated(*args): # pylint: disable=missing-docstring + + @def_function.function(autograph=autograph) + def computation(*computation_args): + return fn(*computation_args) + + computation = computation.get_concrete_function(*[ + tensor.TensorSpec( + dtype=x.dtype, shape=x.shape, name="batch_" + str(i)) + for i, x in enumerate(args) + ]) + + with ops.name_scope("batch") as name: + for a in args: + if not isinstance(a, tensor.Tensor): + raise ValueError("All arguments to functions decorated with " + "`batch_function` are supposed to be Tensors; " + f"found {a!r}.") + outputs = gen_batch_ops.batch_function( + num_batch_threads=num_batch_threads, + max_batch_size=max_batch_size, + batch_timeout_micros=batch_timeout_micros, + allowed_batch_sizes=allowed_batch_sizes, + max_enqueued_batches=max_enqueued_batches, + shared_name=name, + enable_large_batch_splitting=enable_large_batch_splitting, + f=computation, + in_tensors=list(args), + captured_tensors=computation.captured_inputs, + Tout=[o.dtype for o in computation.outputs]) + return nest.pack_sequence_as( + computation.structured_outputs, outputs, expand_composites=True) + + return decorated + + return decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bincount_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bincount_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f04866a223e907e38208b303d6e3fd9fcb0ed7ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bincount_ops.py @@ -0,0 +1,235 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# maxlengthations under the License. +# ============================================================================== +"""bincount ops.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("math.bincount", v1=[]) +@dispatch.add_dispatch_support +def bincount(arr, + weights=None, + minlength=None, + maxlength=None, + dtype=dtypes.int32, + name=None, + axis=None, + binary_output=False): + """Counts the number of occurrences of each value in an integer array. + + If `minlength` and `maxlength` are not given, returns a vector with length + `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. + + >>> values = tf.constant([1,1,2,3,2,4,4,5]) + >>> tf.math.bincount(values) + + + Vector length = Maximum element in vector `values` is 5. Adding 1, which is 6 + will be the vector length. + + Each bin value in the output indicates number of occurrences of the particular + index. Here, index 1 in output has a value 2. This indicates value 1 occurs + two times in `values`. + + **Bin-counting with weights** + + >>> values = tf.constant([1,1,2,3,2,4,4,5]) + >>> weights = tf.constant([1,5,0,1,0,5,4,5]) + >>> tf.math.bincount(values, weights=weights) + + + When `weights` is specified, bins will be incremented by the corresponding + weight instead of 1. Here, index 1 in output has a value 6. This is the + summation of `weights` corresponding to the value in `values` (i.e. for index + 1, the first two values are 1 so the first two weights, 1 and 5, are + summed). + + There is an equivilance between bin-counting with weights and + `unsorted_segement_sum` where `data` is the weights and `segment_ids` are the + values. + + >>> values = tf.constant([1,1,2,3,2,4,4,5]) + >>> weights = tf.constant([1,5,0,1,0,5,4,5]) + >>> tf.math.unsorted_segment_sum(weights, values, num_segments=6).numpy() + array([0, 6, 0, 1, 9, 5], dtype=int32) + + On GPU, `bincount` with weights is only supported when XLA is enabled + (typically when a function decorated with `@tf.function(jit_compile=True)`). + `unsorted_segment_sum` can be used as a workaround for the non-XLA case on + GPU. + + **Bin-counting matrix rows independently** + + This example uses `axis=-1` with a 2 dimensional input and returns a + `Tensor` with bincounting where axis 0 is **not** flattened, i.e. an + independent bincount for each matrix row. + + >>> data = np.array([[1, 2, 3, 0], [0, 0, 1, 2]], dtype=np.int32) + >>> tf.math.bincount(data, axis=-1) + + + **Bin-counting with binary_output** + + This example gives binary output instead of counting the occurrence. + + >>> data = np.array([[1, 2, 3, 0], [0, 0, 1, 2]], dtype=np.int32) + >>> tf.math.bincount(data, axis=-1, binary_output=True) + + + **Missing zeros in SparseTensor** + + Note that missing zeros (implict zeros) in SparseTensor are **NOT** counted. + This supports cases such as `0` in the values tensor indicates that index/id + `0`is present and a missing zero indicates that no index/id is present. + + If counting missing zeros is desired, there are workarounds. + For the `axis=0` case, the number of missing zeros can computed by subtracting + the number of elements in the SparseTensor's `values` tensor from the + number of elements in the dense shape, and this difference can be added to the + first element of the output of `bincount`. For all cases, the SparseTensor + can be converted to a dense Tensor with `tf.sparse.to_dense` before calling + `tf.math.bincount`. + + Args: + arr: A Tensor, RaggedTensor, or SparseTensor whose values should be counted. + These tensors must have a rank of 2 if `axis=-1`. + weights: If non-None, must be the same shape as arr. For each value in + `arr`, the bin will be incremented by the corresponding weight instead of + 1. If non-None, `binary_output` must be False. + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `arr` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + dtype: If `weights` is None, determines the type of the output bins. + name: A name scope for the associated operations (optional). + axis: The axis to slice over. Axes at and below `axis` will be flattened + before bin counting. Currently, only `0`, and `-1` are supported. If None, + all axes will be flattened (identical to passing `0`). + binary_output: If True, this op will output 1 instead of the number of times + a token appears (equivalent to one_hot + reduce_any instead of one_hot + + reduce_add). Defaults to False. + + Returns: + A vector with the same dtype as `weights` or the given `dtype` containing + the bincount values. + + Raises: + `InvalidArgumentError` if negative values are provided as an input. + + """ + name = "bincount" if name is None else name + with ops.name_scope(name): + arr = tensor_conversion.convert_to_tensor_v2_with_dispatch(arr, name="arr") + if weights is not None: + weights = tensor_conversion.convert_to_tensor_v2_with_dispatch( + weights, name="weights") + + if weights is not None and binary_output: + raise ValueError("Arguments `binary_output` and `weights` are mutually " + "exclusive. Please specify only one.") + + if not arr.dtype.is_integer: + arr = math_ops.cast(arr, dtypes.int32) + if axis is None: + axis = 0 + + if axis not in [0, -1]: + raise ValueError(f"Unsupported value for argument axis={axis}. Only 0 and" + " -1 are currently supported.") + + array_is_nonempty = array_ops.size(arr) > 0 + output_size = math_ops.cast(array_is_nonempty, arr.dtype) * ( + math_ops.reduce_max(arr) + 1) + if minlength is not None: + minlength = ops.convert_to_tensor( + minlength, name="minlength", dtype=arr.dtype) + output_size = gen_math_ops.maximum(minlength, output_size) + if maxlength is not None: + maxlength = ops.convert_to_tensor( + maxlength, name="maxlength", dtype=arr.dtype) + output_size = gen_math_ops.minimum(maxlength, output_size) + + if axis == 0: + if weights is not None: + weights = array_ops.reshape(weights, [-1]) + arr = array_ops.reshape(arr, [-1]) + + weights = validate_dense_weights(arr, weights, dtype) + return gen_math_ops.dense_bincount( + input=arr, + size=output_size, + weights=weights, + binary_output=binary_output) + + +@tf_export(v1=["math.bincount", "bincount"]) +@deprecation.deprecated_endpoints("bincount") +def bincount_v1(arr, + weights=None, + minlength=None, + maxlength=None, + dtype=dtypes.int32): + """Counts the number of occurrences of each value in an integer array. + + If `minlength` and `maxlength` are not given, returns a vector with length + `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. + If `weights` are non-None, then index `i` of the output stores the sum of the + value in `weights` at each index where the corresponding value in `arr` is + `i`. + + Args: + arr: An int32 tensor of non-negative values. + weights: If non-None, must be the same shape as arr. For each value in + `arr`, the bin will be incremented by the corresponding weight instead of + 1. + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `arr` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + dtype: If `weights` is None, determines the type of the output bins. + + Returns: + A vector with the same dtype as `weights` or the given `dtype`. The bin + values. + """ + return bincount(arr, weights, minlength, maxlength, dtype) + + +def validate_dense_weights(values, weights, dtype=None): + """Validates the passed weight tensor or creates an empty one.""" + if weights is None: + if dtype: + return array_ops.constant([], dtype=dtype) + return array_ops.constant([], dtype=values.dtype) + + if not isinstance(weights, tensor.Tensor): + raise ValueError( + "Argument `weights` must be a tf.Tensor if `values` is a tf.Tensor. " + f"Received weights={weights} of type: {type(weights).__name__}") + + return weights diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bitwise_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bitwise_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b2e31946a1b044645c7f4e45c7be5301de0dcdd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/bitwise_ops.py @@ -0,0 +1,33 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations for manipulating the binary representations of integers. + +API docstring: tensorflow.bitwise +""" + +from tensorflow.python.framework import ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_bitwise_ops import * +# pylint: enable=wildcard-import + +ops.NotDifferentiable("BitwiseAnd") +ops.NotDifferentiable("BitwiseOr") +ops.NotDifferentiable("BitwiseXor") +ops.NotDifferentiable("Invert") +ops.NotDifferentiable("PopulationCount") +ops.NotDifferentiable("LeftShift") +ops.NotDifferentiable("RightShift") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/boosted_trees_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/boosted_trees_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9204f9bf0d31fb9c89d524523cdee3a9a7ee8ade --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/boosted_trees_ops.py @@ -0,0 +1,311 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for boosted_trees.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_boosted_trees_ops +from tensorflow.python.ops import resources + +# Re-exporting ops used by other modules. +# pylint: disable=unused-import +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_aggregate_stats +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_bucketize +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_calculate_best_feature_split as calculate_best_feature_split +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_calculate_best_feature_split_v2 as calculate_best_feature_split_v2 +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_calculate_best_gains_per_feature as calculate_best_gains_per_feature +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_center_bias as center_bias +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_create_quantile_stream_resource as create_quantile_stream_resource +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_example_debug_outputs as example_debug_outputs +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_make_quantile_summaries as make_quantile_summaries +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_make_stats_summary as make_stats_summary +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_predict as predict +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_quantile_stream_resource_add_summaries as quantile_add_summaries +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_quantile_stream_resource_deserialize as quantile_resource_deserialize +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_quantile_stream_resource_flush as quantile_flush +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_quantile_stream_resource_get_bucket_boundaries as get_bucket_boundaries +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_quantile_stream_resource_handle_op as quantile_resource_handle_op +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_sparse_aggregate_stats +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_sparse_calculate_best_feature_split as sparse_calculate_best_feature_split +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_training_predict as training_predict +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_update_ensemble as update_ensemble +from tensorflow.python.ops.gen_boosted_trees_ops import boosted_trees_update_ensemble_v2 as update_ensemble_v2 +from tensorflow.python.ops.gen_boosted_trees_ops import is_boosted_trees_quantile_stream_resource_initialized as is_quantile_resource_initialized +# pylint: enable=unused-import + +from tensorflow.python.training import saver + + +class PruningMode: + """Class for working with Pruning modes.""" + NO_PRUNING, PRE_PRUNING, POST_PRUNING = range(0, 3) + + _map = {'none': NO_PRUNING, 'pre': PRE_PRUNING, 'post': POST_PRUNING} + + @classmethod + def from_str(cls, mode): + if mode in cls._map: + return cls._map[mode] + else: + raise ValueError( + 'pruning_mode mode must be one of: {}. Found: {}'.format(', '.join( + sorted(cls._map)), mode)) + + +class QuantileAccumulatorSaveable(saver.BaseSaverBuilder.SaveableObject): + """SaveableObject implementation for QuantileAccumulator.""" + + def __init__(self, resource_handle, create_op, num_streams, name): + self.resource_handle = resource_handle + self._num_streams = num_streams + self._create_op = create_op + bucket_boundaries = get_bucket_boundaries(self.resource_handle, + self._num_streams) + slice_spec = '' + specs = [] + + def make_save_spec(tensor, suffix): + return saver.BaseSaverBuilder.SaveSpec(tensor, slice_spec, name + suffix) + + for i in range(self._num_streams): + specs += [ + make_save_spec(bucket_boundaries[i], '_bucket_boundaries_' + str(i)) + ] + super(QuantileAccumulatorSaveable, self).__init__(self.resource_handle, + specs, name) + + def restore(self, restored_tensors, unused_tensor_shapes): + bucket_boundaries = restored_tensors + with ops.control_dependencies([self._create_op]): + return quantile_resource_deserialize( + self.resource_handle, bucket_boundaries=bucket_boundaries) + + +class QuantileAccumulator(): + """SaveableObject implementation for QuantileAccumulator. + + The bucket boundaries are serialized and deserialized from checkpointing. + """ + + def __init__(self, + epsilon, + num_streams, + num_quantiles, + name=None, + max_elements=None): + del max_elements # Unused. + + self._eps = epsilon + self._num_streams = num_streams + self._num_quantiles = num_quantiles + + with ops.name_scope(name, 'QuantileAccumulator') as name: + self._name = name + self.resource_handle = self._create_resource() + self._init_op = self._initialize() + is_initialized_op = self.is_initialized() + resources.register_resource(self.resource_handle, self._init_op, + is_initialized_op) + ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, + QuantileAccumulatorSaveable( + self.resource_handle, self._init_op, + self._num_streams, self.resource_handle.name)) + + def _create_resource(self): + return quantile_resource_handle_op( + container='', shared_name=self._name, name=self._name) + + def _initialize(self): + return create_quantile_stream_resource(self.resource_handle, self._eps, + self._num_streams) + + @property + def initializer(self): + if self._init_op is None: + self._init_op = self._initialize() + return self._init_op + + def is_initialized(self): + return is_quantile_resource_initialized(self.resource_handle) + + def _serialize_to_tensors(self): + raise NotImplementedError('When the need arises, TF2 compatibility can be ' + 'added by implementing this method, along with ' + '_restore_from_tensors below.') + + def _restore_from_tensors(self, restored_tensors): + raise NotImplementedError('When the need arises, TF2 compatibility can be ' + 'added by implementing this method, along with ' + '_serialize_to_tensors above.') + + def add_summaries(self, float_columns, example_weights): + summaries = make_quantile_summaries(float_columns, example_weights, + self._eps) + summary_op = quantile_add_summaries(self.resource_handle, summaries) + return summary_op + + def flush(self): + return quantile_flush(self.resource_handle, self._num_quantiles) + + def get_bucket_boundaries(self): + return get_bucket_boundaries(self.resource_handle, self._num_streams) + + +class _TreeEnsembleSavable(saver.BaseSaverBuilder.SaveableObject): + """SaveableObject implementation for TreeEnsemble.""" + + def __init__(self, resource_handle, create_op, name): + """Creates a _TreeEnsembleSavable object. + + Args: + resource_handle: handle to the decision tree ensemble variable. + create_op: the op to initialize the variable. + name: the name to save the tree ensemble variable under. + """ + stamp_token, serialized = ( + gen_boosted_trees_ops.boosted_trees_serialize_ensemble(resource_handle)) + # slice_spec is useful for saving a slice from a variable. + # It's not meaningful the tree ensemble variable. So we just pass an empty + # value. + slice_spec = '' + specs = [ + saver.BaseSaverBuilder.SaveSpec(stamp_token, slice_spec, + name + '_stamp'), + saver.BaseSaverBuilder.SaveSpec(serialized, slice_spec, + name + '_serialized'), + ] + super(_TreeEnsembleSavable, self).__init__(resource_handle, specs, name) + self.resource_handle = resource_handle + self._create_op = create_op + + def restore(self, restored_tensors, unused_restored_shapes): + """Restores the associated tree ensemble from 'restored_tensors'. + + Args: + restored_tensors: the tensors that were loaded from a checkpoint. + unused_restored_shapes: the shapes this object should conform to after + restore. Not meaningful for trees. + + Returns: + The operation that restores the state of the tree ensemble variable. + """ + with ops.control_dependencies([self._create_op]): + return gen_boosted_trees_ops.boosted_trees_deserialize_ensemble( + self.resource_handle, + stamp_token=restored_tensors[0], + tree_ensemble_serialized=restored_tensors[1]) + + +class TreeEnsemble(): + """Creates TreeEnsemble resource.""" + + def __init__(self, name, stamp_token=0, is_local=False, serialized_proto=''): + self._stamp_token = stamp_token + self._serialized_proto = serialized_proto + self._is_local = is_local + with ops.name_scope(name, 'TreeEnsemble') as name: + self._name = name + self.resource_handle = self._create_resource() + self._init_op = self._initialize() + is_initialized_op = self.is_initialized() + # Adds the variable to the savable list. + if not is_local: + ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, + _TreeEnsembleSavable( + self.resource_handle, self.initializer, + self.resource_handle.name)) + resources.register_resource( + self.resource_handle, + self.initializer, + is_initialized_op, + is_shared=not is_local) + + def _create_resource(self): + return gen_boosted_trees_ops.boosted_trees_ensemble_resource_handle_op( + container='', shared_name=self._name, name=self._name) + + def _initialize(self): + return gen_boosted_trees_ops.boosted_trees_create_ensemble( + self.resource_handle, + self._stamp_token, + tree_ensemble_serialized=self._serialized_proto) + + @property + def initializer(self): + if self._init_op is None: + self._init_op = self._initialize() + return self._init_op + + def is_initialized(self): + return gen_boosted_trees_ops.is_boosted_trees_ensemble_initialized( + self.resource_handle) + + def _serialize_to_tensors(self): + raise NotImplementedError('When the need arises, TF2 compatibility can be ' + 'added by implementing this method, along with ' + '_restore_from_tensors below.') + + def _restore_from_tensors(self, restored_tensors): + raise NotImplementedError('When the need arises, TF2 compatibility can be ' + 'added by implementing this method, along with ' + '_serialize_to_tensors above.') + + def get_stamp_token(self): + """Returns the current stamp token of the resource.""" + stamp_token, _, _, _, _ = ( + gen_boosted_trees_ops.boosted_trees_get_ensemble_states( + self.resource_handle)) + return stamp_token + + def get_states(self): + """Returns states of the tree ensemble. + + Returns: + stamp_token, num_trees, num_finalized_trees, num_attempted_layers and + range of the nodes in the latest layer. + """ + (stamp_token, num_trees, num_finalized_trees, num_attempted_layers, + nodes_range) = ( + gen_boosted_trees_ops.boosted_trees_get_ensemble_states( + self.resource_handle)) + # Use identity to give names. + return (array_ops.identity(stamp_token, name='stamp_token'), + array_ops.identity(num_trees, name='num_trees'), + array_ops.identity(num_finalized_trees, name='num_finalized_trees'), + array_ops.identity( + num_attempted_layers, name='num_attempted_layers'), + array_ops.identity(nodes_range, name='last_layer_nodes_range')) + + def serialize(self): + """Serializes the ensemble into proto and returns the serialized proto. + + Returns: + stamp_token: int64 scalar Tensor to denote the stamp of the resource. + serialized_proto: string scalar Tensor of the serialized proto. + """ + return gen_boosted_trees_ops.boosted_trees_serialize_ensemble( + self.resource_handle) + + def deserialize(self, stamp_token, serialized_proto): + """Deserialize the input proto and resets the ensemble from it. + + Args: + stamp_token: int64 scalar Tensor to denote the stamp of the resource. + serialized_proto: string scalar Tensor of the serialized proto. + + Returns: + Operation (for dependencies). + """ + return gen_boosted_trees_ops.boosted_trees_deserialize_ensemble( + self.resource_handle, stamp_token, serialized_proto) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/candidate_sampling_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/candidate_sampling_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d4291b0aa3fca61c3b11229eb7587d5f427cf434 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/candidate_sampling_ops.py @@ -0,0 +1,513 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Wrappers for candidate sampling operations.""" + +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import array_ops # pylint: disable=unused-import +from tensorflow.python.ops import gen_candidate_sampling_ops +from tensorflow.python.ops import math_ops # pylint: disable=unused-import +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export( + 'random.uniform_candidate_sampler', + v1=['random.uniform_candidate_sampler', 'nn.uniform_candidate_sampler']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('nn.uniform_candidate_sampler') +def uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, + range_max, seed=None, name=None): + """Samples a set of classes using a uniform base distribution. + + This operation randomly samples a tensor of sampled classes + (`sampled_candidates`) from the range of integers `[0, range_max)`. + + See the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf) + for a quick course on Candidate Sampling. + + The elements of `sampled_candidates` are drawn without replacement + (if `unique=True`) or with replacement (if `unique=False`) from + the base distribution. + + The base distribution for this operation is the uniform distribution + over the range of integers `[0, range_max)`. + + In addition, this operation returns tensors `true_expected_count` + and `sampled_expected_count` representing the number of times each + of the target classes (`true_classes`) and the sampled + classes (`sampled_candidates`) is expected to occur in an average + tensor of sampled classes. These values correspond to `Q(y|x)` + defined in the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). + If `unique=True`, then these are post-rejection probabilities and we + compute them approximately. + + Note that this function (and also other `*_candidate_sampler` + functions) only gives you the ingredients to implement the various + Candidate Sampling algorithms listed in the big table in the + [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). You + still need to implement the algorithms yourself. + + For example, according to that table, the phrase "negative samples" + may mean different things in different algorithms. For instance, in + NCE, "negative samples" means `S_i` (which is just the sampled + classes) which may overlap with true classes, while in Sampled + Logistic, "negative samples" means `S_i - T_i` which excludes the + true classes. The return value `sampled_candidates` corresponds to + `S_i`, not to any specific definition of "negative samples" in any + specific algorithm. It's your responsibility to pick an algorithm + and calculate the "negative samples" defined by that algorithm + (e.g. `S_i - T_i`). + + As another example, the `true_classes` argument is for calculating + the `true_expected_count` output (as a by-product of this function's + main calculation), which may be needed by some algorithms (according + to that table). It's not for excluding true classes in the return + value `sampled_candidates`. Again that step is algorithm-specific + and should be carried out by you. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + num_true: An `int`. The number of target classes per training example. + num_sampled: An `int`. The number of classes to randomly sample. The + `sampled_candidates` return value will have shape `[num_sampled]`. If + `unique=True`, `num_sampled` must be less than or equal to `range_max`. + unique: A `bool`. Determines whether all sampled classes in a batch are + unique. + range_max: An `int`. The number of possible classes. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + sampled_candidates: A tensor of type `int64` and shape + `[num_sampled]`. The sampled classes, either with possible + duplicates (`unique=False`) or all unique (`unique=True`). As + noted above, `sampled_candidates` may overlap with true classes. + true_expected_count: A tensor of type `float`. Same shape as + `true_classes`. The expected counts under the sampling distribution + of each of `true_classes`. + sampled_expected_count: A tensor of type `float`. Same shape as + `sampled_candidates`. The expected counts under the sampling distribution + of each of `sampled_candidates`. + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_candidate_sampling_ops.uniform_candidate_sampler( + true_classes, num_true, num_sampled, unique, range_max, seed=seed1, + seed2=seed2, name=name) + + +@tf_export( + 'random.log_uniform_candidate_sampler', + v1=[ + 'random.log_uniform_candidate_sampler', + 'nn.log_uniform_candidate_sampler' + ]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('nn.log_uniform_candidate_sampler') +def log_uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, + range_max, seed=None, name=None): + """Samples a set of classes using a log-uniform (Zipfian) base distribution. + + This operation randomly samples a tensor of sampled classes + (`sampled_candidates`) from the range of integers `[0, range_max)`. + + See the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf) + for a quick course on Candidate Sampling. + + The elements of `sampled_candidates` are drawn without replacement + (if `unique=True`) or with replacement (if `unique=False`) from + the base distribution. + + The base distribution for this operation is an approximately log-uniform + or Zipfian distribution: + + `P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)` + + This sampler is useful when the target classes approximately follow such + a distribution - for example, if the classes represent words in a lexicon + sorted in decreasing order of frequency. If your classes are not ordered by + decreasing frequency, do not use this op. + + In addition, this operation returns tensors `true_expected_count` + and `sampled_expected_count` representing the number of times each + of the target classes (`true_classes`) and the sampled + classes (`sampled_candidates`) is expected to occur in an average + tensor of sampled classes. These values correspond to `Q(y|x)` + defined in the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). + If `unique=True`, then these are post-rejection probabilities and we + compute them approximately. + + Note that this function (and also other `*_candidate_sampler` + functions) only gives you the ingredients to implement the various + Candidate Sampling algorithms listed in the big table in the + [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). You + still need to implement the algorithms yourself. + + For example, according to that table, the phrase "negative samples" + may mean different things in different algorithms. For instance, in + NCE, "negative samples" means `S_i` (which is just the sampled + classes) which may overlap with true classes, while in Sampled + Logistic, "negative samples" means `S_i - T_i` which excludes the + true classes. The return value `sampled_candidates` corresponds to + `S_i`, not to any specific definition of "negative samples" in any + specific algorithm. It's your responsibility to pick an algorithm + and calculate the "negative samples" defined by that algorithm + (e.g. `S_i - T_i`). + + As another example, the `true_classes` argument is for calculating + the `true_expected_count` output (as a by-product of this function's + main calculation), which may be needed by some algorithms (according + to that table). It's not for excluding true classes in the return + value `sampled_candidates`. Again that step is algorithm-specific + and should be carried out by you. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + num_true: An `int`. The number of target classes per training example. + num_sampled: An `int`. The number of classes to randomly sample. + unique: A `bool`. Determines whether all sampled classes in a batch are + unique. + range_max: An `int`. The number of possible classes. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + sampled_candidates: A tensor of type `int64` and shape + `[num_sampled]`. The sampled classes. As noted above, + `sampled_candidates` may overlap with true classes. + true_expected_count: A tensor of type `float`. Same shape as + `true_classes`. The expected counts under the sampling distribution + of each of `true_classes`. + sampled_expected_count: A tensor of type `float`. Same shape as + `sampled_candidates`. The expected counts under the sampling distribution + of each of `sampled_candidates`. + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_candidate_sampling_ops.log_uniform_candidate_sampler( + true_classes, num_true, num_sampled, unique, range_max, seed=seed1, + seed2=seed2, name=name) + + +@tf_export( + 'random.learned_unigram_candidate_sampler', + 'nn.learned_unigram_candidate_sampler') +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints(['nn.learned_unigram_candidate_sampler']) +def learned_unigram_candidate_sampler(true_classes, num_true, num_sampled, + unique, range_max, seed=None, name=None): + """Samples a set of classes from a distribution learned during training. + + This operation randomly samples a tensor of sampled classes + (`sampled_candidates`) from the range of integers `[0, range_max)`. + + See the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf) + for a quick course on Candidate Sampling. + + The elements of `sampled_candidates` are drawn without replacement + (if `unique=True`) or with replacement (if `unique=False`) from + the base distribution. + + The base distribution for this operation is constructed on the fly + during training. It is a unigram distribution over the target + classes seen so far during training. Every integer in `[0, range_max)` + begins with a weight of 1, and is incremented by 1 each time it is + seen as a target class. The base distribution is not saved to checkpoints, + so it is reset when the model is reloaded. + + In addition, this operation returns tensors `true_expected_count` + and `sampled_expected_count` representing the number of times each + of the target classes (`true_classes`) and the sampled + classes (`sampled_candidates`) is expected to occur in an average + tensor of sampled classes. These values correspond to `Q(y|x)` + defined in the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). + If `unique=True`, then these are post-rejection probabilities and we + compute them approximately. + + Note that this function (and also other `*_candidate_sampler` + functions) only gives you the ingredients to implement the various + Candidate Sampling algorithms listed in the big table in the + [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). You + still need to implement the algorithms yourself. + + For example, according to that table, the phrase "negative samples" + may mean different things in different algorithms. For instance, in + NCE, "negative samples" means `S_i` (which is just the sampled + classes) which may overlap with true classes, while in Sampled + Logistic, "negative samples" means `S_i - T_i` which excludes the + true classes. The return value `sampled_candidates` corresponds to + `S_i`, not to any specific definition of "negative samples" in any + specific algorithm. It's your responsibility to pick an algorithm + and calculate the "negative samples" defined by that algorithm + (e.g. `S_i - T_i`). + + As another example, the `true_classes` argument is for calculating + the `true_expected_count` output (as a by-product of this function's + main calculation), which may be needed by some algorithms (according + to that table). It's not for excluding true classes in the return + value `sampled_candidates`. Again that step is algorithm-specific + and should be carried out by you. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + num_true: An `int`. The number of target classes per training example. + num_sampled: An `int`. The number of classes to randomly sample. + unique: A `bool`. Determines whether all sampled classes in a batch are + unique. + range_max: An `int`. The number of possible classes. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + sampled_candidates: A tensor of type `int64` and shape + `[num_sampled]`. The sampled classes. As noted above, + `sampled_candidates` may overlap with true classes. + true_expected_count: A tensor of type `float`. Same shape as + `true_classes`. The expected counts under the sampling distribution + of each of `true_classes`. + sampled_expected_count: A tensor of type `float`. Same shape as + `sampled_candidates`. The expected counts under the sampling distribution + of each of `sampled_candidates`. + + """ + seed1, seed2 = random_seed.get_seed(seed) + # Limiting to Max int32 value + if range_max > 2147483647: + raise ValueError(f'Value of range_max:{range_max} is too large to handle') + return gen_candidate_sampling_ops.learned_unigram_candidate_sampler( + true_classes, num_true, num_sampled, unique, range_max, seed=seed1, + seed2=seed2, name=name) + + +@tf_export('random.fixed_unigram_candidate_sampler', + 'nn.fixed_unigram_candidate_sampler') +@dispatch.add_dispatch_support +def fixed_unigram_candidate_sampler(true_classes, + num_true, + num_sampled, + unique, + range_max, + vocab_file='', + distortion=1.0, + num_reserved_ids=0, + num_shards=1, + shard=0, + unigrams=(), + seed=None, + name=None): + """Samples a set of classes using the provided (fixed) base distribution. + + This operation randomly samples a tensor of sampled classes + (`sampled_candidates`) from the range of integers `[0, range_max)`. + + See the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf) + for a quick course on Candidate Sampling. + + The elements of `sampled_candidates` are drawn without replacement + (if `unique=True`) or with replacement (if `unique=False`) from + the base distribution. + + The base distribution is read from a file or passed in as an + in-memory array. There is also an option to skew the distribution by + applying a distortion power to the weights. + + In addition, this operation returns tensors `true_expected_count` + and `sampled_expected_count` representing the number of times each + of the target classes (`true_classes`) and the sampled + classes (`sampled_candidates`) is expected to occur in an average + tensor of sampled classes. These values correspond to `Q(y|x)` + defined in the [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). + If `unique=True`, then these are post-rejection probabilities and we + compute them approximately. + + Note that this function (and also other `*_candidate_sampler` + functions) only gives you the ingredients to implement the various + Candidate Sampling algorithms listed in the big table in the + [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). You + still need to implement the algorithms yourself. + + For example, according to that table, the phrase "negative samples" + may mean different things in different algorithms. For instance, in + NCE, "negative samples" means `S_i` (which is just the sampled + classes) which may overlap with true classes, while in Sampled + Logistic, "negative samples" means `S_i - T_i` which excludes the + true classes. The return value `sampled_candidates` corresponds to + `S_i`, not to any specific definition of "negative samples" in any + specific algorithm. It's your responsibility to pick an algorithm + and calculate the "negative samples" defined by that algorithm + (e.g. `S_i - T_i`). + + As another example, the `true_classes` argument is for calculating + the `true_expected_count` output (as a by-product of this function's + main calculation), which may be needed by some algorithms (according + to that table). It's not for excluding true classes in the return + value `sampled_candidates`. Again that step is algorithm-specific + and should be carried out by you. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + num_true: An `int`. The number of target classes per training example. + num_sampled: An `int`. The number of classes to randomly sample. + unique: A `bool`. Determines whether all sampled classes in a batch are + unique. + range_max: An `int`. The number of possible classes. + vocab_file: Each valid line in this file (which should have a CSV-like + format) corresponds to a valid word ID. IDs are in sequential order, + starting from num_reserved_ids. The last entry in each line is expected + to be a value corresponding to the count or relative probability. Exactly + one of `vocab_file` and `unigrams` needs to be passed to this operation. + distortion: The distortion is used to skew the unigram probability + distribution. Each weight is first raised to the distortion's power + before adding to the internal unigram distribution. As a result, + `distortion = 1.0` gives regular unigram sampling (as defined by the vocab + file), and `distortion = 0.0` gives a uniform distribution. + num_reserved_ids: Optionally some reserved IDs can be added in the range + `[0, num_reserved_ids)` by the users. One use case is that a special + unknown word token is used as ID 0. These IDs will have a sampling + probability of 0. + num_shards: A sampler can be used to sample from a subset of the original + range in order to speed up the whole computation through parallelism. This + parameter (together with `shard`) indicates the number of partitions that + are being used in the overall computation. + shard: A sampler can be used to sample from a subset of the original range + in order to speed up the whole computation through parallelism. This + parameter (together with `num_shards`) indicates the particular partition + number of the operation, when partitioning is being used. + unigrams: A list of unigram counts or probabilities, one per ID in + sequential order. Exactly one of `vocab_file` and `unigrams` should be + passed to this operation. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + sampled_candidates: A tensor of type `int64` and shape + `[num_sampled]`. The sampled classes. As noted above, + `sampled_candidates` may overlap with true classes. + true_expected_count: A tensor of type `float`. Same shape as + `true_classes`. The expected counts under the sampling distribution + of each of `true_classes`. + sampled_expected_count: A tensor of type `float`. Same shape as + `sampled_candidates`. The expected counts under the sampling distribution + of each of `sampled_candidates`. + + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_candidate_sampling_ops.fixed_unigram_candidate_sampler( + true_classes, num_true, num_sampled, unique, range_max, + vocab_file=vocab_file, distortion=distortion, + num_reserved_ids=num_reserved_ids, num_shards=num_shards, shard=shard, + unigrams=unigrams, seed=seed1, seed2=seed2, name=name) + + +@tf_export('random.all_candidate_sampler', 'nn.all_candidate_sampler') +def all_candidate_sampler(true_classes, num_true, num_sampled, unique, + seed=None, name=None): + """Generate the set of all classes. + + Deterministically generates and returns the set of all possible classes. + For testing purposes. There is no need to use this, since you might as + well use full softmax or full logistic regression. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + num_true: An `int`. The number of target classes per training example. + num_sampled: An `int`. The number of possible classes. + unique: A `bool`. Ignored. + unique. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`. + This operation deterministically returns the entire range + `[0, num_sampled]`. + true_expected_count: A tensor of type `float`. Same shape as + `true_classes`. The expected counts under the sampling distribution + of each of `true_classes`. All returned values are 1.0. + sampled_expected_count: A tensor of type `float`. Same shape as + `sampled_candidates`. The expected counts under the sampling distribution + of each of `sampled_candidates`. All returned values are 1.0. + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_candidate_sampling_ops.all_candidate_sampler( + true_classes, num_true, num_sampled, unique, seed=seed1, seed2=seed2, + name=name) + + +@tf_export('nn.compute_accidental_hits') +@dispatch.add_dispatch_support +def compute_accidental_hits(true_classes, sampled_candidates, num_true, + seed=None, name=None): + """Compute the position ids in `sampled_candidates` matching `true_classes`. + + In Candidate Sampling, this operation facilitates virtually removing + sampled classes which happen to match target classes. This is done + in Sampled Softmax and Sampled Logistic. + + See our [Candidate Sampling Algorithms + Reference](http://www.tensorflow.org/extras/candidate_sampling.pdf). + + We presuppose that the `sampled_candidates` are unique. + + We call it an 'accidental hit' when one of the target classes + matches one of the sampled classes. This operation reports + accidental hits as triples `(index, id, weight)`, where `index` + represents the row number in `true_classes`, `id` represents the + position in `sampled_candidates`, and weight is `-FLOAT_MAX`. + + The result of this op should be passed through a `sparse_to_dense` + operation, then added to the logits of the sampled classes. This + removes the contradictory effect of accidentally sampling the true + target classes as noise classes for the same example. + + Args: + true_classes: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + sampled_candidates: A tensor of type `int64` and shape `[num_sampled]`. + The sampled_candidates output of CandidateSampler. + num_true: An `int`. The number of target classes per training example. + seed: An `int`. An operation-specific seed. Default is 0. + name: A name for the operation (optional). + + Returns: + indices: A `Tensor` of type `int32` and shape `[num_accidental_hits]`. + Values indicate rows in `true_classes`. + ids: A `Tensor` of type `int64` and shape `[num_accidental_hits]`. + Values indicate positions in `sampled_candidates`. + weights: A `Tensor` of type `float` and shape `[num_accidental_hits]`. + Each value is `-FLOAT_MAX`. + + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_candidate_sampling_ops.compute_accidental_hits( + true_classes, sampled_candidates, num_true, seed=seed1, seed2=seed2, + name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/check_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/check_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bc3d6266ad342814e0548a78fdf7752091b0c20d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/check_ops.py @@ -0,0 +1,2365 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-short-docstring-punctuation +"""Asserts and Boolean Checks.""" + +import collections + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +NUMERIC_TYPES = frozenset([ + dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int8, dtypes.int16, + dtypes.int32, dtypes.int64, dtypes.uint8, dtypes.uint16, dtypes.uint32, + dtypes.uint64, dtypes.qint8, dtypes.qint16, dtypes.qint32, dtypes.quint8, + dtypes.quint16, dtypes.complex64, dtypes.complex128, dtypes.bfloat16 +]) + +__all__ = [ + 'assert_negative', + 'assert_positive', + 'assert_proper_iterable', + 'assert_non_negative', + 'assert_non_positive', + 'assert_equal', + 'assert_none_equal', + 'assert_near', + 'assert_integer', + 'assert_less', + 'assert_less_equal', + 'assert_greater', + 'assert_greater_equal', + 'assert_rank', + 'assert_rank_at_least', + 'assert_rank_in', + 'assert_same_float_dtype', + 'assert_scalar', + 'assert_type', + 'assert_shapes', + 'is_non_decreasing', + 'is_numeric_tensor', + 'is_strictly_increasing', +] + + +def _maybe_constant_value_string(t): + if not isinstance(t, tensor_lib.Tensor): + return str(t) + const_t = tensor_util.constant_value(t) + if const_t is not None: + return str(const_t) + return t + + +def _assert_static(condition, data): + """Raises a InvalidArgumentError with as much information as possible.""" + if not condition: + data_static = [_maybe_constant_value_string(x) for x in data] + raise errors.InvalidArgumentError(node_def=None, op=None, + message='\n'.join(data_static)) + + +def _shape_and_dtype_str(tensor): + """Returns a string containing tensor's shape and dtype.""" + return 'shape=%s dtype=%s' % (tensor.shape, tensor.dtype.name) + + +def _unary_assert_doc(sym, sym_name): + """Common docstring for assert_* ops that evaluate a unary predicate over every element of a tensor. + + Args: + sym: Mathematical symbol for the check performed on each element, i.e. "> 0" + sym_name: English-language name for the op described by sym + + Returns: + Decorator that adds the appropriate docstring to the function for symbol + `sym`. + """ + + def _decorator(func): + """Generated decorator that adds the appropriate docstring to the function for symbol `sym`. + + Args: + func: Function for a TensorFlow op + + Returns: + Version of `func` with documentation attached. + """ + opname = func.__name__ + cap_sym_name = sym_name.capitalize() + + func.__doc__ = """ + Assert the condition `x {sym}` holds element-wise. + + When running in graph mode, you should add a dependency on this operation + to ensure that it runs. Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.debugging.{opname}(x, y)]): + output = tf.reduce_sum(x) + ``` + + {sym_name} means, for every element `x[i]` of `x`, we have `x[i] {sym}`. + If `x` is empty this is trivially satisfied. + + Args: + x: Numeric `Tensor`. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "{opname}". + + Returns: + Op that raises `InvalidArgumentError` if `x {sym}` is False. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x {sym}` is False. The check can be performed immediately during + eager execution or if `x` is statically known. + """.format( + sym=sym, sym_name=cap_sym_name, opname=opname) + return func + + return _decorator + + +def _binary_assert_doc(sym, test_var): + """Common docstring for most of the v1 assert_* ops that compare two tensors element-wise. + + Args: + sym: Binary operation symbol, i.e. "==" + test_var: a string that represents the variable in the right-hand side of + binary operator of the test case + + Returns: + Decorator that adds the appropriate docstring to the function for + symbol `sym`. + """ + + def _decorator(func): + """Generated decorator that adds the appropriate docstring to the function for symbol `sym`. + + Args: + func: Function for a TensorFlow op + + Returns: + A version of `func` with documentation attached. + """ + opname = func.__name__ + + func.__doc__ = """ + Assert the condition `x {sym} y` holds element-wise. + + This condition holds if for every pair of (possibly broadcast) elements + `x[i]`, `y[i]`, we have `x[i] {sym} y[i]`. + If both `x` and `y` are empty, this is trivially satisfied. + + When running in graph mode, you should add a dependency on this operation + to ensure that it runs. Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.{opname}(x, y)]): + output = tf.reduce_sum(x) + ``` + + Args: + x: Numeric `Tensor`. + y: Numeric `Tensor`, same dtype as and broadcastable to `x`. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`, `y`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "{opname}". + + Returns: + Op that raises `InvalidArgumentError` if `x {sym} y` is False. + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x {sym} y` is False. The check can be performed immediately during + eager execution or if `x` and `y` are statically known. + + @compatibility(TF2) + `tf.compat.v1.{opname}` is compatible with eager execution and + `tf.function`. + Please use `tf.debugging.{opname}` instead when migrating to TF2. Apart + from `data`, all arguments are supported with the same argument name. + + If you want to ensure the assert statements run before the + potentially-invalid computation, please use `tf.control_dependencies`, + as tf.function auto-control dependencies are insufficient for assert + statements. + + #### Structural Mapping to Native TF2 + + Before: + + ```python + tf.compat.v1.{opname}( + x=x, y=y, data=data, summarize=summarize, + message=message, name=name) + ``` + + After: + + ```python + tf.debugging.{opname}( + x=x, y=y, message=message, + summarize=summarize, name=name) + ``` + + #### TF1 & TF2 Usage Example + + TF1: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... a = tf.compat.v1.placeholder(tf.float32, [2]) + ... b = tf.compat.v1.placeholder(tf.float32, [2]) + ... result = tf.compat.v1.{opname}(a, b, + ... message='"a {sym} b" does not hold for the given inputs') + ... with tf.compat.v1.control_dependencies([result]): + ... sum_node = a + b + >>> sess = tf.compat.v1.Session(graph=g) + >>> val = sess.run(sum_node, feed_dict={{a: [1, 2], b:{test_var}}}) + + + TF2: + + >>> a = tf.Variable([1, 2], dtype=tf.float32) + >>> b = tf.Variable({test_var}, dtype=tf.float32) + >>> assert_op = tf.debugging.{opname}(a, b, message= + ... '"a {sym} b" does not hold for the given inputs') + >>> # When working with tf.control_dependencies + >>> with tf.control_dependencies([assert_op]): + ... val = a + b + + @end_compatibility + """.format( + sym=sym, opname=opname, test_var=test_var) + return func + + return _decorator + + +def _binary_assert_doc_v2(sym, opname, test_var): + """Common docstring for v2 assert_* ops that compare two tensors element-wise. + + Args: + sym: Binary operation symbol, i.e. "==" + opname: Name for the symbol, i.e. "assert_equal" + test_var: A number used in the docstring example + + Returns: + Decorator that adds the appropriate docstring to the function for + symbol `sym`. + """ + + def _decorator(func): + """Decorator that adds docstring to the function for symbol `sym`. + + Args: + func: Function for a TensorFlow op + + Returns: + A version of `func` with documentation attached. + """ + + func.__doc__ = """ + Assert the condition `x {sym} y` holds element-wise. + + This Op checks that `x[i] {sym} y[i]` holds for every pair of (possibly + broadcast) elements of `x` and `y`. If both `x` and `y` are empty, this is + trivially satisfied. + + If `x` {sym} `y` does not hold, `message`, as well as the first `summarize` + entries of `x` and `y` are printed, and `InvalidArgumentError` is raised. + + When using inside `tf.function`, this API takes effects during execution. + It's recommended to use this API with `tf.control_dependencies` to + ensure the correct execution order. + + In the following example, without `tf.control_dependencies`, errors may + not be raised at all. + Check `tf.control_dependencies` for more details. + + >>> def check_size(x): + ... with tf.control_dependencies([ + ... tf.debugging.{opname}(tf.size(x), {test_var}, + ... message='Bad tensor size')]): + ... return x + + >>> check_size(tf.ones([2, 3], tf.float32)) + Traceback (most recent call last): + ... + InvalidArgumentError: ... + + Args: + x: Numeric `Tensor`. + y: Numeric `Tensor`, same dtype as and broadcastable to `x`. + message: A string to prefix to the default message. (optional) + summarize: Print this many entries of each tensor. (optional) + name: A name for this operation (optional). Defaults to "{opname}". + + Returns: + Op that raises `InvalidArgumentError` if `x {sym} y` is False. This can + be used with `tf.control_dependencies` inside of `tf.function`s to + block followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x == y` is False. The check can be performed immediately during eager + execution or if `x` and `y` are statically known. + """.format( + sym=sym, opname=opname, test_var=test_var) + return func + + return _decorator + + +def _make_assert_msg_data(sym, x, y, summarize, test_op): + """Subroutine of _binary_assert that generates the components of the default error message when running in eager mode. + + Args: + sym: Mathematical symbol for the test to apply to pairs of tensor elements, + i.e. "==" + x: First input to the assertion after applying `convert_to_tensor()` + y: Second input to the assertion + summarize: Value of the "summarize" parameter to the original assert_* call; + tells how many elements of each tensor to print. + test_op: TensorFlow op that returns a Boolean tensor with True in each + position where the assertion is satisfied. + + Returns: + List of tensors and scalars that, when stringified and concatenated, + will produce the error message string. + """ + # Prepare a message with first elements of x and y. + data = [] + + data.append('Condition x %s y did not hold.' % sym) + + if summarize > 0: + if x.shape == y.shape and x.shape.as_list(): + # If the shapes of x and y are the same (and not scalars), + # Get the values that actually differed and their indices. + # If shapes are different this information is more confusing + # than useful. + mask = math_ops.logical_not(test_op) + indices = array_ops.where(mask) + indices_np = indices.numpy() + x_vals = array_ops.boolean_mask(x, mask) + y_vals = array_ops.boolean_mask(y, mask) + num_vals = min(summarize, indices_np.shape[0]) + data.append('Indices of first %d different values:' % num_vals) + data.append(indices_np[:num_vals]) + data.append('Corresponding x values:') + data.append(x_vals.numpy().reshape((-1,))[:num_vals]) + data.append('Corresponding y values:') + data.append(y_vals.numpy().reshape((-1,))[:num_vals]) + + # reshape((-1,)) is the fastest way to get a flat array view. + x_np = x.numpy().reshape((-1,)) + y_np = y.numpy().reshape((-1,)) + x_sum = min(x_np.size, summarize) + y_sum = min(y_np.size, summarize) + data.append('First %d elements of x:' % x_sum) + data.append(x_np[:x_sum]) + data.append('First %d elements of y:' % y_sum) + data.append(y_np[:y_sum]) + + return data + + +def _pretty_print(data_item, summarize): + """Format a data item for use in an error message in eager mode. + + Args: + data_item: One of the items in the "data" argument to an assert_* function. + Can be a Tensor or a scalar value. + summarize: How many elements to retain of each tensor-valued entry in data. + + Returns: + An appropriate string representation of data_item + """ + if isinstance(data_item, tensor_lib.Tensor): + arr = data_item.numpy() + if np.isscalar(arr): + # Tensor.numpy() returns a scalar for zero-dimensional tensors + return str(arr) + else: + flat = arr.reshape((-1,)) + lst = [str(x) for x in flat[:summarize]] + if len(lst) < flat.size: + lst.append('...') + return str(lst) + else: + return str(data_item) + + +def _binary_assert(sym, opname, op_func, static_func, x, y, data, summarize, + message, name): + """Generic binary elementwise assertion. + + Implements the behavior described in _binary_assert_doc() above. + Args: + sym: Mathematical symbol for the test to apply to pairs of tensor elements, + i.e. "==" + opname: Name of the assert op in the public API, i.e. "assert_equal" + op_func: Function that, if passed the two Tensor inputs to the assertion (x + and y), will return the test to be passed to reduce_all() i.e. + static_func: Function that, if passed numpy ndarray versions of the two + inputs to the assertion, will return a Boolean ndarray with containing + True in all positions where the assertion PASSES. + i.e. np.equal for assert_equal() + x: Numeric `Tensor`. + y: Numeric `Tensor`, same dtype as and broadcastable to `x`. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`, `y`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to the value of + `opname`. + + Returns: + See docstring template in _binary_assert_doc(). + """ + with ops.name_scope(name, opname, [x, y, data]): + x = ops.convert_to_tensor(x, name='x') + y = ops.convert_to_tensor(y, name='y') + + if context.executing_eagerly(): + test_op = op_func(x, y) + condition = math_ops.reduce_all(test_op) + if condition: + return + + # If we get here, the assertion has failed. + # Default to printing 3 elements like control_flow_ops.Assert (used + # by graph mode) does. Also treat negative values as "print + # everything" for consistency with Tensor::SummarizeValue(). + if summarize is None: + summarize = 3 + elif summarize < 0: + summarize = 1e9 # Code below will find exact size of x and y. + + if data is None: + data = _make_assert_msg_data(sym, x, y, summarize, test_op) + + if message is not None: + data = [message] + list(data) + + raise errors.InvalidArgumentError( + node_def=None, + op=None, + message=('\n'.join(_pretty_print(d, summarize) for d in data))) + + else: # not context.executing_eagerly() + if data is None: + data = [ + 'Condition x %s y did not hold element-wise:' % sym, + 'x (%s) = ' % x.name, x, + 'y (%s) = ' % y.name, y + ] + if message is not None: + data = [message] + list(data) + condition = math_ops.reduce_all(op_func(x, y)) + x_static = tensor_util.constant_value(x) + y_static = tensor_util.constant_value(y) + if x_static is not None and y_static is not None: + condition_static = np.all(static_func(x_static, y_static)) + _assert_static(condition_static, data) + return control_flow_assert.Assert(condition, data, summarize=summarize) + + +@tf_export( + 'debugging.assert_proper_iterable', + v1=['debugging.assert_proper_iterable', 'assert_proper_iterable']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_proper_iterable') +def assert_proper_iterable(values): + """Static assert that values is a "proper" iterable. + + `Ops` that expect iterables of `Tensor` can call this to validate input. + Useful since `Tensor`, `ndarray`, byte/text type are all iterables themselves. + + Args: + values: Object to be checked. + + Raises: + TypeError: If `values` is not iterable or is one of + `Tensor`, `SparseTensor`, `np.array`, `tf.compat.bytes_or_text_types`. + """ + unintentional_iterables = ( + (tensor_lib.Tensor, sparse_tensor.SparseTensor, np.ndarray) + + compat.bytes_or_text_types + ) + if isinstance(values, unintentional_iterables): + raise TypeError( + 'Expected argument "values" to be a "proper" iterable. Found: %s' % + type(values)) + + if not hasattr(values, '__iter__'): + raise TypeError( + 'Expected argument "values" to be iterable. Found: %s' % type(values)) + + +@tf_export('debugging.assert_negative', v1=[]) +@dispatch.add_dispatch_support +def assert_negative_v2(x, message=None, summarize=None, name=None): + """Assert the condition `x < 0` holds element-wise. + + This Op checks that `x[i] < 0` holds for every element of `x`. If `x` is + empty, this is trivially satisfied. + + If `x` is not negative everywhere, `message`, as well as the first `summarize` + entries of `x` are printed, and `InvalidArgumentError` is raised. + + Args: + x: Numeric `Tensor`. + message: A string to prefix to the default message. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). Defaults to "assert_negative". + + Returns: + Op raising `InvalidArgumentError` unless `x` is all negative. This can be + used with `tf.control_dependencies` inside of `tf.function`s to block + followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x[i] < 0` is False. The check can be performed immediately during eager + execution or if `x` is statically known. + """ + return assert_negative(x=x, message=message, summarize=summarize, name=name) + + +@tf_export(v1=['debugging.assert_negative', 'assert_negative']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_negative') +@_unary_assert_doc('< 0', 'negative') +def assert_negative(x, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + message = _message_prefix(message) + with ops.name_scope(name, 'assert_negative', [x, data]): + x = ops.convert_to_tensor(x, name='x') + if data is None: + if context.executing_eagerly(): + name = _shape_and_dtype_str(x) + else: + name = x.name + data = [ + message, + 'Condition x < 0 did not hold element-wise:', + 'x (%s) = ' % name, x] + zero = ops.convert_to_tensor(0, dtype=x.dtype) + return assert_less(x, zero, data=data, summarize=summarize) + + +@tf_export('debugging.assert_positive', v1=[]) +@dispatch.add_dispatch_support +def assert_positive_v2(x, message=None, summarize=None, name=None): + """Assert the condition `x > 0` holds element-wise. + + This Op checks that `x[i] > 0` holds for every element of `x`. If `x` is + empty, this is trivially satisfied. + + If `x` is not positive everywhere, `message`, as well as the first `summarize` + entries of `x` are printed, and `InvalidArgumentError` is raised. + + Args: + x: Numeric `Tensor`. + message: A string to prefix to the default message. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). Defaults to "assert_positive". + + Returns: + Op raising `InvalidArgumentError` unless `x` is all positive. This can be + used with `tf.control_dependencies` inside of `tf.function`s to block + followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x[i] > 0` is False. The check can be performed immediately during eager + execution or if `x` is statically known. + """ + return assert_positive(x=x, summarize=summarize, message=message, name=name) + + +@tf_export(v1=['debugging.assert_positive', 'assert_positive']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_positive') +@_unary_assert_doc('> 0', 'positive') +def assert_positive(x, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + message = _message_prefix(message) + with ops.name_scope(name, 'assert_positive', [x, data]): + x = ops.convert_to_tensor(x, name='x') + if data is None: + if context.executing_eagerly(): + name = _shape_and_dtype_str(x) + else: + name = x.name + data = [ + message, 'Condition x > 0 did not hold element-wise:', + 'x (%s) = ' % name, x] + zero = ops.convert_to_tensor(0, dtype=x.dtype) + return assert_less(zero, x, data=data, summarize=summarize) + + +@tf_export('debugging.assert_non_negative', v1=[]) +@dispatch.add_dispatch_support +def assert_non_negative_v2(x, message=None, summarize=None, name=None): + """Assert the condition `x >= 0` holds element-wise. + + This Op checks that `x[i] >= 0` holds for every element of `x`. If `x` is + empty, this is trivially satisfied. + + If `x` is not >= 0 everywhere, `message`, as well as the first `summarize` + entries of `x` are printed, and `InvalidArgumentError` is raised. + + Args: + x: Numeric `Tensor`. + message: A string to prefix to the default message. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). Defaults to + "assert_non_negative". + + Returns: + Op raising `InvalidArgumentError` unless `x` is all non-negative. This can + be used with `tf.control_dependencies` inside of `tf.function`s to block + followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x[i] >= 0` is False. The check can be performed immediately during eager + execution or if `x` is statically known. + """ + return assert_non_negative(x=x, summarize=summarize, message=message, + name=name) + + +@tf_export(v1=['debugging.assert_non_negative', 'assert_non_negative']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_non_negative') +@_unary_assert_doc('>= 0', 'non-negative') +def assert_non_negative(x, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + message = _message_prefix(message) + with ops.name_scope(name, 'assert_non_negative', [x, data]): + x = ops.convert_to_tensor(x, name='x') + if data is None: + if context.executing_eagerly(): + name = _shape_and_dtype_str(x) + else: + name = x.name + data = [ + message, + 'Condition x >= 0 did not hold element-wise:', + 'x (%s) = ' % name, x] + zero = ops.convert_to_tensor(0, dtype=x.dtype) + return assert_less_equal(zero, x, data=data, summarize=summarize) + + +@tf_export('debugging.assert_non_positive', v1=[]) +@dispatch.add_dispatch_support +def assert_non_positive_v2(x, message=None, summarize=None, name=None): + """Assert the condition `x <= 0` holds element-wise. + + This Op checks that `x[i] <= 0` holds for every element of `x`. If `x` is + empty, this is trivially satisfied. + + If `x` is not <= 0 everywhere, `message`, as well as the first `summarize` + entries of `x` are printed, and `InvalidArgumentError` is raised. + + Args: + x: Numeric `Tensor`. + message: A string to prefix to the default message. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). Defaults to + "assert_non_positive". + + Returns: + Op raising `InvalidArgumentError` unless `x` is all non-positive. This can + be used with `tf.control_dependencies` inside of `tf.function`s to block + followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x[i] <= 0` is False. The check can be performed immediately during eager + execution or if `x` is statically known. + """ + return assert_non_positive(x=x, summarize=summarize, message=message, + name=name) + + +@tf_export(v1=['debugging.assert_non_positive', 'assert_non_positive']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_non_positive') +@_unary_assert_doc('<= 0', 'non-positive') +def assert_non_positive(x, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + message = _message_prefix(message) + with ops.name_scope(name, 'assert_non_positive', [x, data]): + x = ops.convert_to_tensor(x, name='x') + if data is None: + if context.executing_eagerly(): + name = _shape_and_dtype_str(x) + else: + name = x.name + data = [ + message, + 'Condition x <= 0 did not hold element-wise:' + 'x (%s) = ' % name, x] + zero = ops.convert_to_tensor(0, dtype=x.dtype) + return assert_less_equal(x, zero, data=data, summarize=summarize) + + +@tf_export('debugging.assert_equal', 'assert_equal', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('==', 'assert_equal', 3) +def assert_equal_v2(x, y, message=None, summarize=None, name=None): + return assert_equal(x=x, y=y, summarize=summarize, message=message, name=name) + + +@tf_export(v1=['debugging.assert_equal', 'assert_equal']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc('==', '[1, 2]') +def assert_equal(x, y, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + with ops.name_scope(name, 'assert_equal', [x, y, data]): + # Short-circuit if x and y are the same tensor. + if x is y: + return None if context.executing_eagerly() else control_flow_ops.no_op() + return _binary_assert('==', 'assert_equal', math_ops.equal, np.equal, x, y, + data, summarize, message, name) + + +@tf_export('debugging.assert_none_equal', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('!=', 'assert_none_equal', 6) +def assert_none_equal_v2(x, y, summarize=None, message=None, name=None): + return assert_none_equal(x=x, y=y, summarize=summarize, message=message, + name=name) + + +@tf_export(v1=['debugging.assert_none_equal', 'assert_none_equal']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_none_equal') +@_binary_assert_doc('!=', '[2, 1]') +def assert_none_equal( + x, y, data=None, summarize=None, message=None, name=None): + return _binary_assert('!=', 'assert_none_equal', math_ops.not_equal, + np.not_equal, x, y, data, summarize, message, name) + + +@tf_export('debugging.assert_near', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +def assert_near_v2(x, y, rtol=None, atol=None, message=None, summarize=None, + name=None): + """Assert the condition `x` and `y` are close element-wise. + + This Op checks that `x[i] - y[i] < atol + rtol * tf.abs(y[i])` holds for every + pair of (possibly broadcast) elements of `x` and `y`. If both `x` and `y` are + empty, this is trivially satisfied. + + If any elements of `x` and `y` are not close, `message`, as well as the first + `summarize` entries of `x` and `y` are printed, and `InvalidArgumentError` + is raised. + + The default `atol` and `rtol` is `10 * eps`, where `eps` is the smallest + representable positive number such that `1 + eps != 1`. This is about + `1.2e-6` in `32bit`, `2.22e-15` in `64bit`, and `0.00977` in `16bit`. + See `numpy.finfo`. + + Args: + x: Float or complex `Tensor`. + y: Float or complex `Tensor`, same dtype as and broadcastable to `x`. + rtol: `Tensor`. Same `dtype` as, and broadcastable to, `x`. + The relative tolerance. Default is `10 * eps`. + atol: `Tensor`. Same `dtype` as, and broadcastable to, `x`. + The absolute tolerance. Default is `10 * eps`. + message: A string to prefix to the default message. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). Defaults to "assert_near". + + Returns: + Op that raises `InvalidArgumentError` if `x` and `y` are not close enough. + This can be used with `tf.control_dependencies` inside of `tf.function`s + to block followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x != y` is False for any pair of elements in `x` and `y`. The check can + be performed immediately during eager execution or if `x` and `y` are + statically known. + + @compatibility(numpy) + Similar to `numpy.testing.assert_allclose`, except tolerance depends on data + type. This is due to the fact that `TensorFlow` is often used with `32bit`, + `64bit`, and even `16bit` data. + @end_compatibility + """ + return assert_near(x=x, y=y, rtol=rtol, atol=atol, summarize=summarize, + message=message, name=name) + + +@tf_export(v1=['debugging.assert_near', 'assert_near']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_near') +def assert_near( + x, y, rtol=None, atol=None, data=None, summarize=None, message=None, + name=None): + """Assert the condition `x` and `y` are close element-wise. + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.assert_near(x, y)]): + output = tf.reduce_sum(x) + ``` + + This condition holds if for every pair of (possibly broadcast) elements + `x[i]`, `y[i]`, we have + + ```tf.abs(x[i] - y[i]) <= atol + rtol * tf.abs(y[i])```. + + If both `x` and `y` are empty, this is trivially satisfied. + + The default `atol` and `rtol` is `10 * eps`, where `eps` is the smallest + representable positive number such that `1 + eps != 1`. This is about + `1.2e-6` in `32bit`, `2.22e-15` in `64bit`, and `0.00977` in `16bit`. + See `numpy.finfo`. + + Args: + x: Float or complex `Tensor`. + y: Float or complex `Tensor`, same `dtype` as, and broadcastable to, `x`. + rtol: `Tensor`. Same `dtype` as, and broadcastable to, `x`. + The relative tolerance. Default is `10 * eps`. + atol: `Tensor`. Same `dtype` as, and broadcastable to, `x`. + The absolute tolerance. Default is `10 * eps`. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`, `y`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_near". + + Returns: + Op that raises `InvalidArgumentError` if `x` and `y` are not close enough. + + @compatibility(numpy) + Similar to `numpy.testing.assert_allclose`, except tolerance depends on data + type. This is due to the fact that `TensorFlow` is often used with `32bit`, + `64bit`, and even `16bit` data. + @end_compatibility + """ + message = _message_prefix(message) + with ops.name_scope(name, 'assert_near', [x, y, rtol, atol, data]): + x = ops.convert_to_tensor(x, name='x') + y = ops.convert_to_tensor(y, name='y', dtype=x.dtype) + + dtype = x.dtype + if dtype.is_complex: + dtype = dtype.real_dtype + eps = np.finfo(dtype.as_numpy_dtype).eps + rtol = 10 * eps if rtol is None else rtol + atol = 10 * eps if atol is None else atol + + rtol = ops.convert_to_tensor(rtol, name='rtol', dtype=dtype) + atol = ops.convert_to_tensor(atol, name='atol', dtype=dtype) + + if context.executing_eagerly(): + x_name = _shape_and_dtype_str(x) + y_name = _shape_and_dtype_str(y) + else: + x_name = x.name + y_name = y.name + + if data is None: + data = [ + message, + 'x and y not equal to tolerance rtol = %s, atol = %s' % (rtol, atol), + 'x (%s) = ' % x_name, x, 'y (%s) = ' % y_name, y + ] + tol = atol + rtol * math_ops.abs(y) + diff = math_ops.abs(x - y) + condition = math_ops.reduce_all(math_ops.less(diff, tol)) + return control_flow_assert.Assert(condition, data, summarize=summarize) + + +@tf_export('debugging.assert_less', 'assert_less', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('<', 'assert_less', 3) +def assert_less_v2(x, y, message=None, summarize=None, name=None): + return assert_less(x=x, y=y, summarize=summarize, message=message, name=name) + + +@tf_export(v1=['debugging.assert_less', 'assert_less']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc('<', '[2, 3]') +def assert_less(x, y, data=None, summarize=None, message=None, name=None): + return _binary_assert('<', 'assert_less', math_ops.less, np.less, x, y, data, + summarize, message, name) + + +@tf_export('debugging.assert_less_equal', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('<=', 'assert_less_equal', 3) +def assert_less_equal_v2(x, y, message=None, summarize=None, name=None): + return assert_less_equal(x=x, y=y, + summarize=summarize, message=message, name=name) + + +@tf_export(v1=['debugging.assert_less_equal', 'assert_less_equal']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_less_equal') +@_binary_assert_doc('<=', '[1, 3]') +def assert_less_equal(x, y, data=None, summarize=None, message=None, name=None): + return _binary_assert('<=', 'assert_less_equal', math_ops.less_equal, + np.less_equal, x, y, data, summarize, message, name) + + +@tf_export('debugging.assert_greater', 'assert_greater', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('>', 'assert_greater', 9) +def assert_greater_v2(x, y, message=None, summarize=None, name=None): + return assert_greater(x=x, y=y, summarize=summarize, message=message, + name=name) + + +@tf_export(v1=['debugging.assert_greater', 'assert_greater']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc('>', '[0, 1]') +def assert_greater(x, y, data=None, summarize=None, message=None, name=None): # pylint: disable=missing-docstring + return _binary_assert('>', 'assert_greater', math_ops.greater, np.greater, x, + y, data, summarize, message, name) + + +@tf_export('debugging.assert_greater_equal', v1=[]) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@_binary_assert_doc_v2('>=', 'assert_greater_equal', 9) +def assert_greater_equal_v2(x, y, message=None, summarize=None, name=None): + return assert_greater_equal(x=x, y=y, summarize=summarize, message=message, + name=name) + + +@tf_export(v1=['debugging.assert_greater_equal', 'assert_greater_equal']) +@dispatch.register_binary_elementwise_assert_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_greater_equal') +@_binary_assert_doc('>=', '[1, 0]') +def assert_greater_equal(x, y, data=None, summarize=None, message=None, + name=None): + return _binary_assert('>=', 'assert_greater_equal', math_ops.greater_equal, + np.greater_equal, x, y, data, summarize, message, name) + + +def _assert_rank_condition( + x, rank, static_condition, dynamic_condition, data, summarize): + """Assert `x` has a rank that satisfies a given condition. + + Args: + x: Numeric `Tensor`. + rank: Scalar `Tensor`. + static_condition: A python function that takes `[actual_rank, given_rank]` + and returns `True` if the condition is satisfied, `False` otherwise. + dynamic_condition: An `op` that takes [actual_rank, given_rank] and return + `True` if the condition is satisfied, `False` otherwise. + data: The tensors to print out if the condition is false. Defaults to + error message and first few entries of `x`. + summarize: Print this many entries of each tensor. + + Returns: + Op raising `InvalidArgumentError` if `x` fails dynamic_condition. + + Raises: + ValueError: If static checks determine `x` fails static_condition. + """ + assert_type(rank, dtypes.int32) + + # Attempt to statically defined rank. + rank_static = tensor_util.constant_value(rank) + if rank_static is not None: + if rank_static.ndim != 0: + raise ValueError('Rank must be a scalar.') + + x_rank_static = x.get_shape().ndims + if x_rank_static is not None: + if not static_condition(x_rank_static, rank_static): + raise ValueError( + 'Static rank condition failed', x_rank_static, rank_static) + return control_flow_ops.no_op(name='static_checks_determined_all_ok') + + condition = dynamic_condition(array_ops.rank(x), rank) + + # Add the condition that `rank` must have rank zero. Prevents the bug where + # someone does assert_rank(x, [n]), rather than assert_rank(x, n). + if rank_static is None: + this_data = ['Rank must be a scalar. Received rank: ', rank] + rank_check = assert_rank(rank, 0, data=this_data) + condition = control_flow_ops.with_dependencies([rank_check], condition) + + return control_flow_assert.Assert(condition, data, summarize=summarize) + + +@tf_export('debugging.assert_rank', 'assert_rank', v1=[]) +@dispatch.add_dispatch_support +def assert_rank_v2(x, rank, message=None, name=None): + """Assert that `x` has rank equal to `rank`. + + This Op checks that the rank of `x` is equal to `rank`. + + If `x` has a different rank, `message`, as well as the shape of `x` are + printed, and `InvalidArgumentError` is raised. + + Args: + x: `Tensor`. + rank: Scalar integer `Tensor`. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to + "assert_rank". + + Returns: + Op raising `InvalidArgumentError` unless `x` has specified rank. + If static checks determine `x` has correct rank, a `no_op` is returned. + This can be used with `tf.control_dependencies` inside of `tf.function`s + to block followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: if the check can be performed immediately and + `x` does not have rank `rank`. The check can be performed immediately + during eager execution or if the shape of `x` is statically known. + """ + return assert_rank(x=x, rank=rank, message=message, name=name) + + +@tf_export(v1=['debugging.assert_rank', 'assert_rank']) +@dispatch.add_dispatch_support +def assert_rank(x, rank, data=None, summarize=None, message=None, name=None): + """Assert `x` has rank equal to `rank`. + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]): + output = tf.reduce_sum(x) + ``` + + Args: + x: Numeric `Tensor`. + rank: Scalar integer `Tensor`. + data: The tensors to print out if the condition is False. Defaults to + error message and the shape of `x`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_rank". + + Returns: + Op raising `InvalidArgumentError` unless `x` has specified rank. + If static checks determine `x` has correct rank, a `no_op` is returned. + + Raises: + ValueError: If static checks determine `x` has wrong rank. + """ + with ops.name_scope(name, 'assert_rank', (x, rank) + tuple(data or [])): + if not isinstance(x, sparse_tensor.SparseTensor): + x = ops.convert_to_tensor(x, name='x') + rank = ops.convert_to_tensor(rank, name='rank') + message = _message_prefix(message) + + static_condition = lambda actual_rank, given_rank: actual_rank == given_rank + dynamic_condition = math_ops.equal + + if context.executing_eagerly() or isinstance(x, sparse_tensor.SparseTensor): + name = '' + else: + name = x.name + + if data is None: + data = [ + message, + 'Tensor %s must have rank' % name, rank, 'Received shape: ', + array_ops.shape(x) + ] + + try: + assert_op = _assert_rank_condition(x, rank, static_condition, + dynamic_condition, data, summarize) + + except ValueError as e: + if e.args[0] == 'Static rank condition failed': + raise ValueError( + '%sTensor %s must have rank %d. Received rank %d, shape %s' % + (message, name, e.args[2], e.args[1], x.get_shape())) + else: + raise ValueError(e.args[0]) + + return assert_op + + +@tf_export('debugging.assert_rank_at_least', v1=[]) +@dispatch.add_dispatch_support +def assert_rank_at_least_v2(x, rank, message=None, name=None): + """Assert that `x` has rank of at least `rank`. + + This Op checks that the rank of `x` is greater or equal to `rank`. + + If `x` has a rank lower than `rank`, `message`, as well as the shape of `x` + are printed, and `InvalidArgumentError` is raised. + + Args: + x: `Tensor`. + rank: Scalar integer `Tensor`. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to + "assert_rank_at_least". + + Returns: + Op raising `InvalidArgumentError` unless `x` has specified rank or higher. + If static checks determine `x` has correct rank, a `no_op` is returned. + This can be used with `tf.control_dependencies` inside of `tf.function`s + to block followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: `x` does not have rank at least `rank`, but the rank + cannot be statically determined. + ValueError: If static checks determine `x` has mismatched rank. + """ + return assert_rank_at_least(x=x, rank=rank, message=message, name=name) + + +@tf_export(v1=['debugging.assert_rank_at_least', 'assert_rank_at_least']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_rank_at_least') +def assert_rank_at_least( + x, rank, data=None, summarize=None, message=None, name=None): + """Assert `x` has rank equal to `rank` or higher. + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.assert_rank_at_least(x, 2)]): + output = tf.reduce_sum(x) + ``` + + Args: + x: Numeric `Tensor`. + rank: Scalar `Tensor`. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). + Defaults to "assert_rank_at_least". + + Returns: + Op raising `InvalidArgumentError` unless `x` has specified rank or higher. + If static checks determine `x` has correct rank, a `no_op` is returned. + + Raises: + ValueError: If static checks determine `x` has wrong rank. + """ + with ops.name_scope( + name, 'assert_rank_at_least', (x, rank) + tuple(data or [])): + x = ops.convert_to_tensor(x, name='x') + rank = ops.convert_to_tensor(rank, name='rank') + message = _message_prefix(message) + + static_condition = lambda actual_rank, given_rank: actual_rank >= given_rank + dynamic_condition = math_ops.greater_equal + + if context.executing_eagerly(): + name = '' + else: + name = x.name + + if data is None: + data = [ + message, + 'Tensor %s must have rank at least' % name, rank, + 'Received shape: ', array_ops.shape(x) + ] + + try: + assert_op = _assert_rank_condition(x, rank, static_condition, + dynamic_condition, data, summarize) + + except ValueError as e: + if e.args[0] == 'Static rank condition failed': + raise ValueError( + '%sTensor %s must have rank at least %d. Received rank %d, ' + 'shape %s' % (message, name, e.args[2], e.args[1], x.get_shape())) + else: + raise + + return assert_op + + +def _static_rank_in(actual_rank, given_ranks): + return actual_rank in given_ranks + + +def _dynamic_rank_in(actual_rank, given_ranks): + if len(given_ranks) < 1: + return ops.convert_to_tensor(False) + result = math_ops.equal(given_ranks[0], actual_rank) + for given_rank in given_ranks[1:]: + result = math_ops.logical_or( + result, math_ops.equal(given_rank, actual_rank)) + return result + + +def _assert_ranks_condition( + x, ranks, static_condition, dynamic_condition, data, summarize): + """Assert `x` has a rank that satisfies a given condition. + + Args: + x: Numeric `Tensor`. + ranks: Scalar `Tensor`. + static_condition: A python function that takes + `[actual_rank, given_ranks]` and returns `True` if the condition is + satisfied, `False` otherwise. + dynamic_condition: An `op` that takes [actual_rank, given_ranks] + and return `True` if the condition is satisfied, `False` otherwise. + data: The tensors to print out if the condition is false. Defaults to + error message and first few entries of `x`. + summarize: Print this many entries of each tensor. + + Returns: + Op raising `InvalidArgumentError` if `x` fails dynamic_condition. + + Raises: + ValueError: If static checks determine `x` fails static_condition. + """ + for rank in ranks: + assert_type(rank, dtypes.int32) + + # Attempt to statically defined rank. + ranks_static = tuple([tensor_util.constant_value(rank) for rank in ranks]) + if not any(r is None for r in ranks_static): + for rank_static in ranks_static: + if rank_static.ndim != 0: + raise ValueError('Rank must be a scalar.') + + x_rank_static = x.get_shape().ndims + if x_rank_static is not None: + if not static_condition(x_rank_static, ranks_static): + raise ValueError( + 'Static rank condition failed', x_rank_static, ranks_static) + return control_flow_ops.no_op(name='static_checks_determined_all_ok') + + condition = dynamic_condition(array_ops.rank(x), ranks) + + # Add the condition that `rank` must have rank zero. Prevents the bug where + # someone does assert_rank(x, [n]), rather than assert_rank(x, n). + for rank, rank_static in zip(ranks, ranks_static): + if rank_static is None: + this_data = ['Rank must be a scalar. Received rank: ', rank] + rank_check = assert_rank(rank, 0, data=this_data) + condition = control_flow_ops.with_dependencies([rank_check], condition) + + return control_flow_assert.Assert(condition, data, summarize=summarize) + + +@tf_export('debugging.assert_rank_in', v1=[]) +@dispatch.add_dispatch_support +def assert_rank_in_v2(x, ranks, message=None, name=None): + """Assert that `x` has a rank in `ranks`. + + This Op checks that the rank of `x` is in `ranks`. + + If `x` has a different rank, `message`, as well as the shape of `x` are + printed, and `InvalidArgumentError` is raised. + + Args: + x: `Tensor`. + ranks: `Iterable` of scalar `Tensor` objects. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_rank_in". + + Returns: + Op raising `InvalidArgumentError` unless rank of `x` is in `ranks`. + If static checks determine `x` has matching rank, a `no_op` is returned. + This can be used with `tf.control_dependencies` inside of `tf.function`s + to block followup computation until the check has executed. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + InvalidArgumentError: `x` does not have rank in `ranks`, but the rank cannot + be statically determined. + ValueError: If static checks determine `x` has mismatched rank. + """ + return assert_rank_in(x=x, ranks=ranks, message=message, name=name) + + +@tf_export(v1=['debugging.assert_rank_in', 'assert_rank_in']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_rank_in') +def assert_rank_in( + x, ranks, data=None, summarize=None, message=None, name=None): + """Assert `x` has rank in `ranks`. + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.assert_rank_in(x, (2, 4))]): + output = tf.reduce_sum(x) + ``` + + Args: + x: Numeric `Tensor`. + ranks: Iterable of scalar `Tensor` objects. + data: The tensors to print out if the condition is False. Defaults to + error message and first few entries of `x`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). + Defaults to "assert_rank_in". + + Returns: + Op raising `InvalidArgumentError` unless rank of `x` is in `ranks`. + If static checks determine `x` has matching rank, a `no_op` is returned. + + Raises: + ValueError: If static checks determine `x` has mismatched rank. + """ + with ops.name_scope( + name, 'assert_rank_in', (x,) + tuple(ranks) + tuple(data or [])): + if not isinstance(x, sparse_tensor.SparseTensor): + x = ops.convert_to_tensor(x, name='x') + ranks = tuple([ops.convert_to_tensor(rank, name='rank') for rank in ranks]) + message = _message_prefix(message) + + if context.executing_eagerly() or isinstance(x, sparse_tensor.SparseTensor): + name = '' + else: + name = x.name + + if data is None: + data = [ + message, 'Tensor %s must have rank in' % name + ] + list(ranks) + [ + 'Received shape: ', array_ops.shape(x) + ] + + try: + assert_op = _assert_ranks_condition(x, ranks, _static_rank_in, + _dynamic_rank_in, data, summarize) + + except ValueError as e: + if e.args[0] == 'Static rank condition failed': + raise ValueError( + '%sTensor %s must have rank in %s. Received rank %d, ' + 'shape %s' % (message, name, e.args[2], e.args[1], x.get_shape())) + else: + raise + + return assert_op + + +@tf_export('debugging.assert_integer', v1=[]) +@dispatch.add_dispatch_support +def assert_integer_v2(x, message=None, name=None): + """Assert that `x` is of integer dtype. + + If `x` has a non-integer type, `message`, as well as the dtype of `x` are + printed, and `InvalidArgumentError` is raised. + + This can always be checked statically, so this method returns nothing. + + Args: + x: A `Tensor`. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_integer". + + Raises: + TypeError: If `x.dtype` is not a non-quantized integer type. + """ + assert_integer(x=x, message=message, name=name) + + +@tf_export(v1=['debugging.assert_integer', 'assert_integer']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_integer') +def assert_integer(x, message=None, name=None): + """Assert that `x` is of integer dtype. + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.compat.v1.assert_integer(x)]): + output = tf.reduce_sum(x) + ``` + + Args: + x: `Tensor` whose basetype is integer and is not quantized. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_integer". + + Raises: + TypeError: If `x.dtype` is anything other than non-quantized integer. + + Returns: + A `no_op` that does nothing. Type can be determined statically. + """ + with ops.name_scope(name, 'assert_integer', [x]): + x = ops.convert_to_tensor(x, name='x') + if not x.dtype.is_integer: + if context.executing_eagerly(): + name = 'tensor' + else: + name = x.name + err_msg = ( + '%sExpected "x" to be integer type. Found: %s of dtype %s' + % (_message_prefix(message), name, x.dtype)) + raise TypeError(err_msg) + + return control_flow_ops.no_op('statically_determined_was_integer') + + +@tf_export('debugging.assert_type', v1=[]) +@dispatch.add_dispatch_support +def assert_type_v2(tensor, tf_type, message=None, name=None): + """Asserts that the given `Tensor` is of the specified type. + + This can always be checked statically, so this method returns nothing. + + Example: + + >>> a = tf.Variable(1.0) + >>> tf.debugging.assert_type(a, tf_type= tf.float32) + + >>> b = tf.constant(21) + >>> tf.debugging.assert_type(b, tf_type=tf.bool) + Traceback (most recent call last): + ... + TypeError: ... + + >>> c = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], + ... dense_shape=[3, 4]) + >>> tf.debugging.assert_type(c, tf_type= tf.int32) + + Args: + tensor: A `Tensor`, `SparseTensor` or `tf.Variable` . + tf_type: A tensorflow type (`dtypes.float32`, `tf.int64`, `dtypes.bool`, + etc). + message: A string to prefix to the default message. + name: A name for this operation. Defaults to "assert_type" + + Raises: + TypeError: If the tensor's data type doesn't match `tf_type`. + """ + assert_type(tensor=tensor, tf_type=tf_type, message=message, name=name) + + +@tf_export(v1=['debugging.assert_type', 'assert_type']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_type') +def assert_type(tensor, tf_type, message=None, name=None): + """Statically asserts that the given `Tensor` is of the specified type. + + Args: + tensor: A `Tensor` or `SparseTensor`. + tf_type: A tensorflow type (`dtypes.float32`, `tf.int64`, `dtypes.bool`, + etc). + message: A string to prefix to the default message. + name: A name to give this `Op`. Defaults to "assert_type" + + Raises: + TypeError: If the tensors data type doesn't match `tf_type`. + + Returns: + A `no_op` that does nothing. Type can be determined statically. + """ + tf_type = dtypes.as_dtype(tf_type) + with ops.name_scope(name, 'assert_type', [tensor]): + if not isinstance(tensor, sparse_tensor.SparseTensor): + tensor = ops.convert_to_tensor(tensor, name='tensor') + if tensor.dtype != tf_type: + raise TypeError( + f'{_message_prefix(message)}{getattr(tensor, "name", "tensor")}' + f' must be of type {tf_type!r}; got {tensor.dtype!r}') + + return control_flow_ops.no_op('statically_determined_correct_type') + + +def _dimension_sizes(x): + """Gets the dimension sizes of a tensor `x`. + + If a size can be determined statically it is returned as an integer, + otherwise as a tensor. + + If `x` is a scalar it is treated as rank 1 size 1. + + Args: + x: A `Tensor`. + + Returns: + Dimension sizes. + """ + dynamic_shape = array_ops.shape(x) + rank = x.get_shape().rank + rank_is_known = rank is not None + if rank_is_known and rank == 0: + return (1,) + if rank_is_known and rank > 0: + static_shape = x.get_shape().as_list() + sizes = [ + int(size) if size is not None else dynamic_shape[i] + for i, size in enumerate(static_shape) + ] + return sizes + has_rank_zero = math_ops.equal(array_ops.rank(x), 0) + return cond.cond( + has_rank_zero, lambda: array_ops.constant([1]), lambda: dynamic_shape) + + +def _symbolic_dimension_sizes(symbolic_shape): + # If len(symbolic_shape) == 0 construct a tuple + if not symbolic_shape: + return tuple([1]) + + return symbolic_shape + + +def _has_known_value(dimension_size): + not_none = dimension_size is not None + try: + int(dimension_size) + can_be_parsed_as_int = True + except (ValueError, TypeError): + can_be_parsed_as_int = False + return not_none and can_be_parsed_as_int + + +def _is_symbol_for_any_size(symbol): + return symbol in [None, '.'] + + +_TensorDimSizes = collections.namedtuple( + '_TensorDimSizes', + ['x', 'unspecified_dim', 'actual_sizes', 'symbolic_sizes']) + + +@tf_export('debugging.assert_shapes', v1=[]) +@dispatch.add_dispatch_support +def assert_shapes_v2(shapes, data=None, summarize=None, message=None, + name=None): + """Assert tensor shapes and dimension size relationships between tensors. + + This Op checks that a collection of tensors shape relationships + satisfies given constraints. + + Example: + + >>> n = 10 + >>> q = 3 + >>> d = 7 + >>> x = tf.zeros([n,q]) + >>> y = tf.ones([n,d]) + >>> param = tf.Variable([1.0, 2.0, 3.0]) + >>> scalar = 1.0 + >>> tf.debugging.assert_shapes([ + ... (x, ('N', 'Q')), + ... (y, ('N', 'D')), + ... (param, ('Q',)), + ... (scalar, ()), + ... ]) + + >>> tf.debugging.assert_shapes([ + ... (x, ('N', 'D')), + ... (y, ('N', 'D')) + ... ]) + Traceback (most recent call last): + ... + ValueError: ... + + If `x`, `y`, `param` or `scalar` does not have a shape that satisfies + all specified constraints, `message`, as well as the first `summarize` entries + of the first encountered violating tensor are printed, and + `InvalidArgumentError` is raised. + + Size entries in the specified shapes are checked against other entries by + their __hash__, except: + - a size entry is interpreted as an explicit size if it can be parsed as an + integer primitive. + - a size entry is interpreted as *any* size if it is None or '.'. + + If the first entry of a shape is `...` (type `Ellipsis`) or '*' that indicates + a variable number of outer dimensions of unspecified size, i.e. the constraint + applies to the inner-most dimensions only. + + Scalar tensors and specified shapes of length zero (excluding the 'inner-most' + prefix) are both treated as having a single dimension of size one. + + Args: + shapes: dictionary with (`Tensor` to shape) items, or a list of + (`Tensor`, shape) tuples. A shape must be an iterable. + data: The tensors to print out if the condition is False. Defaults to error + message and first few entries of the violating tensor. + summarize: Print this many entries of the tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_shapes". + + Raises: + ValueError: If static checks determine any shape constraint is violated. + """ + assert_shapes( + shapes, data=data, summarize=summarize, message=message, name=name) + + +@tf_export(v1=['debugging.assert_shapes']) +@dispatch.add_dispatch_support +def assert_shapes(shapes, data=None, summarize=None, message=None, name=None): + """Assert tensor shapes and dimension size relationships between tensors. + + This Op checks that a collection of tensors shape relationships + satisfies given constraints. + + Example: + + >>> n = 10 + >>> q = 3 + >>> d = 7 + >>> x = tf.zeros([n,q]) + >>> y = tf.ones([n,d]) + >>> param = tf.Variable([1.0, 2.0, 3.0]) + >>> scalar = 1.0 + >>> tf.debugging.assert_shapes([ + ... (x, ('N', 'Q')), + ... (y, ('N', 'D')), + ... (param, ('Q',)), + ... (scalar, ()), + ... ]) + + >>> tf.debugging.assert_shapes([ + ... (x, ('N', 'D')), + ... (y, ('N', 'D')) + ... ]) + Traceback (most recent call last): + ... + ValueError: ... + + Example of adding a dependency to an operation: + + ```python + with tf.control_dependencies([tf.assert_shapes(shapes)]): + output = tf.matmul(x, y, transpose_a=True) + ``` + + If `x`, `y`, `param` or `scalar` does not have a shape that satisfies + all specified constraints, `message`, as well as the first `summarize` entries + of the first encountered violating tensor are printed, and + `InvalidArgumentError` is raised. + + Size entries in the specified shapes are checked against other entries by + their __hash__, except: + - a size entry is interpreted as an explicit size if it can be parsed as an + integer primitive. + - a size entry is interpreted as *any* size if it is None or '.'. + + If the first entry of a shape is `...` (type `Ellipsis`) or '*' that indicates + a variable number of outer dimensions of unspecified size, i.e. the constraint + applies to the inner-most dimensions only. + + Scalar tensors and specified shapes of length zero (excluding the 'inner-most' + prefix) are both treated as having a single dimension of size one. + + Args: + shapes: A list of (`Tensor`, `shape`) tuples, wherein `shape` is the + expected shape of `Tensor`. See the example code above. The `shape` must + be an iterable. Each element of the iterable can be either a concrete + integer value or a string that abstractly represents the dimension. + For example, + - `('N', 'Q')` specifies a 2D shape wherein the first and second + dimensions of shape may or may not be equal. + - `('N', 'N', 'Q')` specifies a 3D shape wherein the first and second + dimensions are equal. + - `(1, 'N')` specifies a 2D shape wherein the first dimension is + exactly 1 and the second dimension can be any value. + Note that the abstract dimension letters take effect across different + tuple elements of the list. For example, + `tf.debugging.assert_shapes([(x, ('N', 'A')), (y, ('N', 'B'))]` asserts + that both `x` and `y` are rank-2 tensors and their first dimensions are + equal (`N`). + `shape` can also be a `tf.TensorShape`. + data: The tensors to print out if the condition is False. Defaults to error + message and first few entries of the violating tensor. + summarize: Print this many entries of the tensor. + message: A string to prefix to the default message. + name: A name for this operation (optional). Defaults to "assert_shapes". + + Returns: + Op raising `InvalidArgumentError` unless all shape constraints are + satisfied. + If static checks determine all constraints are satisfied, a `no_op` is + returned. + + Raises: + ValueError: If static checks determine any shape constraint is violated. + """ + # If the user manages to assemble a dict containing tensors (possible in + # Graph mode only), make sure we still accept that. + if isinstance(shapes, dict): + shapes = shapes.items() + + message_prefix = _message_prefix(message) + with ops.name_scope(name, 'assert_shapes', [shapes, data]): + # Shape specified as None implies no constraint + shape_constraints = [(x if isinstance(x, sparse_tensor.SparseTensor) else + ops.convert_to_tensor(x), s) + for x, s in shapes if s is not None] + + executing_eagerly = context.executing_eagerly() + + def tensor_name(x): + if executing_eagerly or isinstance(x, sparse_tensor.SparseTensor): + return _shape_and_dtype_str(x) + return x.name + + tensor_dim_sizes = [] + for tensor, symbolic_shape in shape_constraints: + is_iterable = ( + hasattr(symbolic_shape, '__iter__') or + hasattr(symbolic_shape, '__getitem__') # For Python 2 compat. + ) + if not is_iterable: + raise ValueError( + '%s' + 'Tensor %s. Specified shape must be an iterable. ' + 'An iterable has the attribute `__iter__` or `__getitem__`. ' + 'Received specified shape: %s' % + (message_prefix, tensor_name(tensor), symbolic_shape)) + + # We convert this into a tuple to handle strings, lists and numpy arrays + symbolic_shape_tuple = tuple(symbolic_shape) + + tensors_specified_innermost = False + for i, symbol in enumerate(symbolic_shape_tuple): + if symbol not in [Ellipsis, '*']: + continue + + if i != 0: + raise ValueError( + '%s' + 'Tensor %s specified shape index %d. ' + 'Symbol `...` or `*` for a variable number of ' + 'unspecified dimensions is only allowed as the first entry' % + (message_prefix, tensor_name(tensor), i)) + + tensors_specified_innermost = True + + # Only include the size of the specified dimensions since the 0th symbol + # is either ellipsis or * + tensor_dim_sizes.append( + _TensorDimSizes( + tensor, tensors_specified_innermost, _dimension_sizes(tensor), + _symbolic_dimension_sizes( + symbolic_shape_tuple[1:] + if tensors_specified_innermost else symbolic_shape_tuple))) + + rank_assertions = [] + for sizes in tensor_dim_sizes: + rank = len(sizes.symbolic_sizes) + rank_zero_or_one = rank in [0, 1] + if sizes.unspecified_dim: + if rank_zero_or_one: + # No assertion of rank needed as `x` only need to have rank at least + # 0. See elif rank_zero_or_one case comment. + continue + assertion = assert_rank_at_least( + x=sizes.x, + rank=rank, + data=data, + summarize=summarize, + message=message, + name=name) + elif rank_zero_or_one: + # Rank 0 is treated as rank 1 size 1, i.e. there is + # no distinction between the two in terms of rank. + # See _dimension_sizes. + assertion = assert_rank_in( + x=sizes.x, + ranks=[0, 1], + data=data, + summarize=summarize, + message=message, + name=name) + else: + assertion = assert_rank( + x=sizes.x, + rank=rank, + data=data, + summarize=summarize, + message=message, + name=name) + rank_assertions.append(assertion) + + size_assertions = [] + size_specifications = {} + for sizes in tensor_dim_sizes: + for i, size_symbol in enumerate(sizes.symbolic_sizes): + + if _is_symbol_for_any_size(size_symbol): + # Size specified as any implies no constraint + continue + + if sizes.unspecified_dim: + tensor_dim = i - len(sizes.symbolic_sizes) + else: + tensor_dim = i + + if size_symbol in size_specifications or _has_known_value(size_symbol): + if _has_known_value(size_symbol): + specified_size = int(size_symbol) + size_check_message = 'Specified explicitly' + else: + specified_size, specified_by_y, specified_at_dim = ( + size_specifications[size_symbol]) + size_check_message = ( + 'Specified by tensor %s dimension %d' % + (tensor_name(specified_by_y), specified_at_dim)) + + # This is extremely subtle. If actual_sizes is dynamic, we must + # make sure a control dependency is inserted here so that this slice + # can not execute until the rank is asserted to be enough for the + # slice to not fail. + with ops.control_dependencies(rank_assertions): + actual_size = sizes.actual_sizes[tensor_dim] + if _has_known_value(actual_size) and _has_known_value(specified_size): + if int(actual_size) != int(specified_size): + raise ValueError( + '%s%s. Tensor %s dimension %s must have size %d. ' + 'Received size %d, shape %s' % + (message_prefix, size_check_message, tensor_name(sizes.x), + tensor_dim, specified_size, actual_size, + sizes.x.get_shape())) + # No dynamic assertion needed + continue + + condition = math_ops.equal( + ops.convert_to_tensor(actual_size), + ops.convert_to_tensor(specified_size)) + data_ = data + if data is None: + data_ = [ + message_prefix, size_check_message, + 'Tensor %s dimension' % tensor_name(sizes.x), tensor_dim, + 'must have size', specified_size, 'Received shape: ', + array_ops.shape(sizes.x) + ] + size_assertions.append( + control_flow_assert.Assert(condition, data_, summarize=summarize)) + else: + # Not sure if actual_sizes is a constant, but for safety, guard + # on rank. See explanation above about actual_sizes need for safety. + with ops.control_dependencies(rank_assertions): + size = sizes.actual_sizes[tensor_dim] + size_specifications[size_symbol] = (size, sizes.x, tensor_dim) + + # Ensure both assertions actually occur. + with ops.control_dependencies(rank_assertions): + shapes_assertion = control_flow_ops.group(size_assertions) + + return shapes_assertion + + +# pylint: disable=line-too-long +def _get_diff_for_monotonic_comparison(x): + """Gets the difference x[1:] - x[:-1].""" + x = array_ops.reshape(x, [-1]) + if not is_numeric_tensor(x): + raise TypeError('Expected x to be numeric, instead found: %s' % x) + + # If x has less than 2 elements, there is nothing to compare. So return []. + is_shorter_than_two = math_ops.less(array_ops.size(x), 2) + short_result = lambda: ops.convert_to_tensor([], dtype=x.dtype) + + # With 2 or more elements, return x[1:] - x[:-1] + s_len = array_ops.shape(x) - 1 + diff = lambda: array_ops.strided_slice(x, [1], [1] + s_len)- array_ops.strided_slice(x, [0], s_len) + return cond.cond(is_shorter_than_two, short_result, diff) + + +@tf_export( + 'debugging.is_numeric_tensor', + v1=['debugging.is_numeric_tensor', 'is_numeric_tensor']) +@deprecation.deprecated_endpoints('is_numeric_tensor') +def is_numeric_tensor(tensor): + """Returns `True` if the elements of `tensor` are numbers. + + Specifically, returns `True` if the dtype of `tensor` is one of the following: + + * `tf.float16` + * `tf.float32` + * `tf.float64` + * `tf.int8` + * `tf.int16` + * `tf.int32` + * `tf.int64` + * `tf.uint8` + * `tf.uint16` + * `tf.uint32` + * `tf.uint64` + * `tf.qint8` + * `tf.qint16` + * `tf.qint32` + * `tf.quint8` + * `tf.quint16` + * `tf.complex64` + * `tf.complex128` + * `tf.bfloat16` + + Returns `False` if `tensor` is of a non-numeric type or if `tensor` is not + a `tf.Tensor` object. + """ + return isinstance(tensor, tensor_lib.Tensor) and tensor.dtype in NUMERIC_TYPES + + +@tf_export( + 'math.is_non_decreasing', + v1=[ + 'math.is_non_decreasing', 'debugging.is_non_decreasing', + 'is_non_decreasing' + ]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('debugging.is_non_decreasing', + 'is_non_decreasing') +def is_non_decreasing(x, name=None): + """Returns `True` if `x` is non-decreasing. + + Elements of `x` are compared in row-major order. The tensor `[x[0],...]` + is non-decreasing if for every adjacent pair we have `x[i] <= x[i+1]`. + If `x` has less than two elements, it is trivially non-decreasing. + + See also: `is_strictly_increasing` + + >>> x1 = tf.constant([1.0, 1.0, 3.0]) + >>> tf.math.is_non_decreasing(x1) + + >>> x2 = tf.constant([3.0, 1.0, 2.0]) + >>> tf.math.is_non_decreasing(x2) + + + Args: + x: Numeric `Tensor`. + name: A name for this operation (optional). Defaults to "is_non_decreasing" + + Returns: + Boolean `Tensor`, equal to `True` iff `x` is non-decreasing. + + Raises: + TypeError: if `x` is not a numeric tensor. + """ + with ops.name_scope(name, 'is_non_decreasing', [x]): + diff = _get_diff_for_monotonic_comparison(x) + # When len(x) = 1, diff = [], less_equal = [], and reduce_all([]) = True. + zero = ops.convert_to_tensor(0, dtype=diff.dtype) + return math_ops.reduce_all(math_ops.less_equal(zero, diff)) + + +@tf_export( + 'math.is_strictly_increasing', + v1=[ + 'math.is_strictly_increasing', 'debugging.is_strictly_increasing', + 'is_strictly_increasing' + ]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('debugging.is_strictly_increasing', + 'is_strictly_increasing') +def is_strictly_increasing(x, name=None): + """Returns `True` if `x` is strictly increasing. + + Elements of `x` are compared in row-major order. The tensor `[x[0],...]` + is strictly increasing if for every adjacent pair we have `x[i] < x[i+1]`. + If `x` has less than two elements, it is trivially strictly increasing. + + See also: `is_non_decreasing` + + >>> x1 = tf.constant([1.0, 2.0, 3.0]) + >>> tf.math.is_strictly_increasing(x1) + + >>> x2 = tf.constant([3.0, 1.0, 2.0]) + >>> tf.math.is_strictly_increasing(x2) + + + Args: + x: Numeric `Tensor`. + name: A name for this operation (optional). + Defaults to "is_strictly_increasing" + + Returns: + Boolean `Tensor`, equal to `True` iff `x` is strictly increasing. + + Raises: + TypeError: if `x` is not a numeric tensor. + """ + with ops.name_scope(name, 'is_strictly_increasing', [x]): + diff = _get_diff_for_monotonic_comparison(x) + # When len(x) = 1, diff = [], less = [], and reduce_all([]) = True. + zero = ops.convert_to_tensor(0, dtype=diff.dtype) + return math_ops.reduce_all(math_ops.less(zero, diff)) + + +def _assert_same_base_type(items, expected_type=None): + r"""Asserts all items are of the same base type. + + Args: + items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`, + `Operation`, or `IndexedSlices`). Can include `None` elements, which + will be ignored. + expected_type: Expected type. If not specified, assert all items are + of the same base type. + + Returns: + Validated type, or none if neither expected_type nor items provided. + + Raises: + ValueError: If any types do not match. + """ + original_expected_type = expected_type + mismatch = False + for item in items: + if item is not None: + item_type = item.dtype.base_dtype + if not expected_type: + expected_type = item_type + elif expected_type != item_type: + mismatch = True + break + if mismatch: + # Loop back through and build up an informative error message (this is very + # slow, so we don't do it unless we found an error above). + expected_type = original_expected_type + original_item_str = None + for item in items: + if item is not None: + item_type = item.dtype.base_dtype + if not expected_type: + expected_type = item_type + original_item_str = item.name if hasattr(item, 'name') else str(item) + elif expected_type != item_type: + raise ValueError('%s, type=%s, must be of the same type (%s)%s.' % ( + item.name if hasattr(item, 'name') else str(item), + item_type, expected_type, + (' as %s' % original_item_str) if original_item_str else '')) + return expected_type # Should be unreachable + else: + return expected_type + + +@tf_export( + 'debugging.assert_same_float_dtype', + v1=['debugging.assert_same_float_dtype', 'assert_same_float_dtype']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_same_float_dtype') +def assert_same_float_dtype(tensors=None, dtype=None): + """Validate and return float type based on `tensors` and `dtype`. + + For ops such as matrix multiplication, inputs and weights must be of the + same float type. This function validates that all `tensors` are the same type, + validates that type is `dtype` (if supplied), and returns the type. Type must + be a floating point type. If neither `tensors` nor `dtype` is supplied, + the function will return `dtypes.float32`. + + Args: + tensors: Tensors of input values. Can include `None` elements, which will be + ignored. + dtype: Expected type. + + Returns: + Validated type. + + Raises: + ValueError: if neither `tensors` nor `dtype` is supplied, or result is not + float, or the common type of the inputs is not a floating point type. + """ + if tensors: + dtype = _assert_same_base_type(tensors, dtype) + if not dtype: + dtype = dtypes.float32 + elif not dtype.is_floating: + raise ValueError('Expected floating point type, got %s.' % dtype) + return dtype + + +@tf_export('debugging.assert_scalar', v1=[]) +@dispatch.add_dispatch_support +def assert_scalar_v2(tensor, message=None, name=None): + """Asserts that the given `tensor` is a scalar. + + This function raises `ValueError` unless it can be certain that the given + `tensor` is a scalar. `ValueError` is also raised if the shape of `tensor` is + unknown. + + This is always checked statically, so this method returns nothing. + + Args: + tensor: A `Tensor`. + message: A string to prefix to the default message. + name: A name for this operation. Defaults to "assert_scalar" + + Raises: + ValueError: If the tensor is not scalar (rank 0), or if its shape is + unknown. + """ + assert_scalar(tensor=tensor, message=message, name=name) + + +@tf_export(v1=['debugging.assert_scalar', 'assert_scalar']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('assert_scalar') +def assert_scalar(tensor, name=None, message=None): + """Asserts that the given `tensor` is a scalar (i.e. zero-dimensional). + + This function raises `ValueError` unless it can be certain that the given + `tensor` is a scalar. `ValueError` is also raised if the shape of `tensor` is + unknown. + + Args: + tensor: A `Tensor`. + name: A name for this operation. Defaults to "assert_scalar" + message: A string to prefix to the default message. + + Returns: + The input tensor (potentially converted to a `Tensor`). + + Raises: + ValueError: If the tensor is not scalar (rank 0), or if its shape is + unknown. + """ + with ops.name_scope(name, 'assert_scalar', [tensor]) as name_scope: + tensor = ops.convert_to_tensor(tensor, name=name_scope) + shape = tensor.get_shape() + message = _message_prefix(message) + if shape.ndims != 0: + if context.executing_eagerly(): + raise ValueError('%sExpected scalar shape, saw shape: %s.' + % (message, shape,)) + else: + raise ValueError('%sExpected scalar shape for %s, saw shape: %s.' + % (message, tensor.name, shape)) + return tensor + + +def _message_prefix(message): + if message: + return '%s. ' % message + return '' + + +@tf_export('ensure_shape') +@dispatch.add_dispatch_support +def ensure_shape(x, shape, name=None): + """Updates the shape of a tensor and checks at runtime that the shape holds. + + When executed, this operation asserts that the input tensor `x`'s shape + is compatible with the `shape` argument. + See `tf.TensorShape.is_compatible_with` for details. + + >>> x = tf.constant([[1, 2, 3], + ... [4, 5, 6]]) + >>> x = tf.ensure_shape(x, [2, 3]) + + Use `None` for unknown dimensions: + + >>> x = tf.ensure_shape(x, [None, 3]) + >>> x = tf.ensure_shape(x, [2, None]) + + If the tensor's shape is not compatible with the `shape` argument, an error + is raised: + + >>> x = tf.ensure_shape(x, [5]) + Traceback (most recent call last): + ... + tf.errors.InvalidArgumentError: Shape of tensor dummy_input [3] is not + compatible with expected shape [5]. [Op:EnsureShape] + + During graph construction (typically tracing a `tf.function`), + `tf.ensure_shape` updates the static-shape of the **result** tensor by + merging the two shapes. See `tf.TensorShape.merge_with` for details. + + This is most useful when **you** know a shape that can't be determined + statically by TensorFlow. + + The following trivial `tf.function` prints the input tensor's + static-shape before and after `ensure_shape` is applied. + + >>> @tf.function + ... def f(tensor): + ... print("Static-shape before:", tensor.shape) + ... tensor = tf.ensure_shape(tensor, [None, 3]) + ... print("Static-shape after:", tensor.shape) + ... return tensor + + This lets you see the effect of `tf.ensure_shape` when the function is traced: + >>> cf = f.get_concrete_function(tf.TensorSpec([None, None])) + Static-shape before: (None, None) + Static-shape after: (None, 3) + + >>> cf(tf.zeros([3, 3])) # Passes + >>> cf(tf.constant([1, 2, 3])) # fails + Traceback (most recent call last): + ... + InvalidArgumentError: Shape of tensor x [3] is not compatible with expected shape [3,3]. + + The above example raises `tf.errors.InvalidArgumentError`, because `x`'s + shape, `(3,)`, is not compatible with the `shape` argument, `(None, 3)` + + Inside a `tf.function` or `v1.Graph` context it checks both the buildtime and + runtime shapes. This is stricter than `tf.Tensor.set_shape` which only + checks the buildtime shape. + + Note: This differs from `tf.Tensor.set_shape` in that it sets the static shape + of the resulting tensor and enforces it at runtime, raising an error if the + tensor's runtime shape is incompatible with the specified shape. + `tf.Tensor.set_shape` sets the static shape of the tensor without enforcing it + at runtime, which may result in inconsistencies between the statically-known + shape of tensors and the runtime value of tensors. + + For example, of loading images of a known size: + + >>> @tf.function + ... def decode_image(png): + ... image = tf.image.decode_png(png, channels=3) + ... # the `print` executes during tracing. + ... print("Initial shape: ", image.shape) + ... image = tf.ensure_shape(image,[28, 28, 3]) + ... print("Final shape: ", image.shape) + ... return image + + When tracing a function, no ops are being executed, shapes may be unknown. + See the [Concrete Functions Guide](https://www.tensorflow.org/guide/concrete_function) + for details. + + >>> concrete_decode = decode_image.get_concrete_function( + ... tf.TensorSpec([], dtype=tf.string)) + Initial shape: (None, None, 3) + Final shape: (28, 28, 3) + + >>> image = tf.random.uniform(maxval=255, shape=[28, 28, 3], dtype=tf.int32) + >>> image = tf.cast(image,tf.uint8) + >>> png = tf.image.encode_png(image) + >>> image2 = concrete_decode(png) + >>> print(image2.shape) + (28, 28, 3) + + >>> image = tf.concat([image,image], axis=0) + >>> print(image.shape) + (56, 28, 3) + >>> png = tf.image.encode_png(image) + >>> image2 = concrete_decode(png) + Traceback (most recent call last): + ... + tf.errors.InvalidArgumentError: Shape of tensor DecodePng [56,28,3] is not + compatible with expected shape [28,28,3]. + + Caution: if you don't use the result of `tf.ensure_shape` the check may not + run. + + >>> @tf.function + ... def bad_decode_image(png): + ... image = tf.image.decode_png(png, channels=3) + ... # the `print` executes during tracing. + ... print("Initial shape: ", image.shape) + ... # BAD: forgot to use the returned tensor. + ... tf.ensure_shape(image,[28, 28, 3]) + ... print("Final shape: ", image.shape) + ... return image + + >>> image = bad_decode_image(png) + Initial shape: (None, None, 3) + Final shape: (None, None, 3) + >>> print(image.shape) + (56, 28, 3) + + Args: + x: A `Tensor`. + shape: A `TensorShape` representing the shape of this tensor, a + `TensorShapeProto`, a list, a tuple, or None. + name: A name for this operation (optional). Defaults to "EnsureShape". + + Returns: + A `Tensor`. Has the same type and contents as `x`. + + Raises: + tf.errors.InvalidArgumentError: If `shape` is incompatible with the shape + of `x`. + """ + if not isinstance(shape, tensor_shape.TensorShape): + shape = tensor_shape.TensorShape(shape) + + return array_ops.ensure_shape(x, shape, name=name) + + +@ops.RegisterGradient('EnsureShape') +def _ensure_shape_grad(op, grad): + del op # Unused. + return grad diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clip_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clip_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca98959cc4ef21a98c6a873e64b463d68fc6d2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clip_ops.py @@ -0,0 +1,430 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations for clipping (gradient, weight) tensors to min/max values.""" +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("clip_by_value") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def clip_by_value(t, clip_value_min, clip_value_max, + name=None): + """Clips tensor values to a specified min and max. + + Given a tensor `t`, this operation returns a tensor of the same type and + shape as `t` with its values clipped to `clip_value_min` and `clip_value_max`. + Any values less than `clip_value_min` are set to `clip_value_min`. Any values + greater than `clip_value_max` are set to `clip_value_max`. + + Note: `clip_value_min` needs to be smaller or equal to `clip_value_max` for + correct results. + + For example: + + Basic usage passes a scalar as the min and max value. + + >>> t = tf.constant([[-10., -1., 0.], [0., 2., 10.]]) + >>> t2 = tf.clip_by_value(t, clip_value_min=-1, clip_value_max=1) + >>> t2.numpy() + array([[-1., -1., 0.], + [ 0., 1., 1.]], dtype=float32) + + The min and max can be the same size as `t`, or broadcastable to that size. + + >>> t = tf.constant([[-1, 0., 10.], [-1, 0, 10]]) + >>> clip_min = [[2],[1]] + >>> t3 = tf.clip_by_value(t, clip_value_min=clip_min, clip_value_max=100) + >>> t3.numpy() + array([[ 2., 2., 10.], + [ 1., 1., 10.]], dtype=float32) + + Broadcasting fails, intentionally, if you would expand the dimensions of `t` + + >>> t = tf.constant([[-1, 0., 10.], [-1, 0, 10]]) + >>> clip_min = [[[2, 1]]] # Has a third axis + >>> t4 = tf.clip_by_value(t, clip_value_min=clip_min, clip_value_max=100) + Traceback (most recent call last): + ... + InvalidArgumentError: Incompatible shapes: [2,3] vs. [1,1,2] + + It throws a `TypeError` if you try to clip an `int` to a `float` value + (`tf.cast` the input to `float` first). + + >>> t = tf.constant([[1, 2], [3, 4]], dtype=tf.int32) + >>> t5 = tf.clip_by_value(t, clip_value_min=-3.1, clip_value_max=3.1) + Traceback (most recent call last): + ... + TypeError: Cannot convert ... + + + Args: + t: A `Tensor` or `IndexedSlices`. + clip_value_min: The minimum value to clip to. A scalar `Tensor` or one that + is broadcastable to the shape of `t`. + clip_value_max: The maximum value to clip to. A scalar `Tensor` or one that + is broadcastable to the shape of `t`. + name: A name for the operation (optional). + + Returns: + A clipped `Tensor` or `IndexedSlices`. + + Raises: + `tf.errors.InvalidArgumentError`: If the clip tensors would trigger array + broadcasting that would make the returned tensor larger than the input. + TypeError: If dtype of the input is `int32` and dtype of + the `clip_value_min` or `clip_value_max` is `float32` + """ + with ops.name_scope(name, "clip_by_value", + [t, clip_value_min, clip_value_max]) as name: + values = ops.convert_to_tensor( + t.values if isinstance(t, indexed_slices.IndexedSlices) else t, + name="t") + + # Go through list of tensors, for each value in each tensor clip + t_min = math_ops.minimum(values, clip_value_max) + # Assert that the shape is compatible with the initial shape, + # to prevent unintentional broadcasting. + values.shape.assert_is_compatible_with(t_min.shape) + + t_max = math_ops.maximum(t_min, clip_value_min, name=name) + values.shape.assert_is_compatible_with(t_max.shape) + + if isinstance(t, indexed_slices.IndexedSlices): + t_max = indexed_slices.IndexedSlices(t_max, t.indices, t.dense_shape) + + return t_max + # TODO(scottzhu): switch to use new implementation in 2 weeks. + # return gen_math_ops.clip_by_value( + # t, clip_value_min, clip_value_max, name=name) + + +@ops.RegisterGradient("ClipByValue") +def _clip_by_value_grad(op, grad): + """Returns grad of clip_by_value.""" + x = op.inputs[0] + y = op.inputs[1] + z = op.inputs[2] + gdtype = grad.dtype + sx = array_ops.shape(x) + sy = array_ops.shape(y) + sz = array_ops.shape(z) + gradshape = array_ops.shape(grad) + zeros = array_ops.zeros(gradshape, gdtype) + xymask = math_ops.less(x, y) + xzmask = math_ops.greater(x, z) + _, ry = gen_array_ops.broadcast_gradient_args(sx, sy) + _, rz = gen_array_ops.broadcast_gradient_args(sx, sz) + xgrad = array_ops.where(math_ops.logical_or(xymask, xzmask), zeros, grad) + ygrad = array_ops.where(xymask, grad, zeros) + zgrad = array_ops.where(xzmask, grad, zeros) + gy = array_ops.reshape(math_ops.reduce_sum(ygrad, ry), sy) + gz = array_ops.reshape(math_ops.reduce_sum(zgrad, rz), sz) + return xgrad, gy, gz + + +@tf_export("clip_by_norm") +@dispatch.add_dispatch_support +def clip_by_norm(t, clip_norm, axes=None, name=None): + """Clips tensor values to a maximum L2-norm. + + Given a tensor `t`, and a maximum clip value `clip_norm`, this operation + normalizes `t` so that its L2-norm is less than or equal to `clip_norm`, + along the dimensions given in `axes`. Specifically, in the default case + where all dimensions are used for calculation, if the L2-norm of `t` is + already less than or equal to `clip_norm`, then `t` is not modified. If + the L2-norm is greater than `clip_norm`, then this operation returns a + tensor of the same type and shape as `t` with its values set to: + + `t * clip_norm / l2norm(t)` + + In this case, the L2-norm of the output tensor is `clip_norm`. + + As another example, if `t` is a matrix and `axes == [1]`, then each row + of the output will have L2-norm less than or equal to `clip_norm`. If + `axes == [0]` instead, each column of the output will be clipped. + + Code example: + + >>> some_nums = tf.constant([[1, 2, 3, 4, 5]], dtype=tf.float32) + >>> tf.clip_by_norm(some_nums, 2.0).numpy() + array([[0.26967996, 0.5393599 , 0.80903983, 1.0787199 , 1.3483998 ]], + dtype=float32) + + This operation is typically used to clip gradients before applying them with + an optimizer. Most gradient data is a collection of different shaped tensors + for different parts of the model. Thus, this is a common usage: + + ``` + # Get your gradients after training + loss_value, grads = grad(model, features, labels) + + # Apply some clipping + grads = [tf.clip_by_norm(g, norm) + for g in grads] + + # Continue on with training + optimizer.apply_gradients(grads) + ``` + + Args: + t: A `Tensor` or `IndexedSlices`. This must be a floating point type. + clip_norm: A 0-D (scalar) `Tensor` > 0. A maximum clipping value, also + floating point + axes: A 1-D (vector) `Tensor` of type int32 containing the dimensions + to use for computing the L2-norm. If `None` (the default), uses all + dimensions. + name: A name for the operation (optional). + + Returns: + A clipped `Tensor` or `IndexedSlices`. + + Raises: + ValueError: If the clip_norm tensor is not a 0-D scalar tensor. + TypeError: If dtype of the input is not a floating point or + complex type. + """ + with ops.name_scope(name, "clip_by_norm", [t, clip_norm]) as name: + values = ops.convert_to_tensor( + t.values if isinstance(t, indexed_slices.IndexedSlices) else t, + name="t") + + # Calculate L2-norm, clip elements by ratio of clip_norm to L2-norm + l2sum = math_ops.reduce_sum(values * values, axes, keepdims=True) + pred = l2sum > 0 + # Two-tap tf.where trick to bypass NaN gradients + l2sum_safe = array_ops.where(pred, l2sum, array_ops.ones_like(l2sum)) + l2norm = array_ops.where(pred, math_ops.sqrt(l2sum_safe), l2sum) + intermediate = values * clip_norm + # Assert that the shape is compatible with the initial shape, + # to prevent unintentional broadcasting. + values.shape.assert_is_compatible_with(intermediate.shape) + values_clip = array_ops.identity( + intermediate / math_ops.maximum(l2norm, clip_norm), name=name) + + if isinstance(t, indexed_slices.IndexedSlices): + return indexed_slices.IndexedSlices(values_clip, t.indices, t.dense_shape) + + return values_clip + + +@tf_export("linalg.global_norm", v1=["linalg.global_norm", "global_norm"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("global_norm") +def global_norm(t_list, name=None): + """Computes the global norm of multiple tensors. + + Given a tuple or list of tensors `t_list`, this operation returns the + global norm of the elements in all tensors in `t_list`. The global norm is + computed as: + + `global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))` + + Any entries in `t_list` that are of type None are ignored. + + Args: + t_list: A tuple or list of mixed `Tensors`, `IndexedSlices`, or None. + name: A name for the operation (optional). + + Returns: + A 0-D (scalar) `Tensor` of type `float`. + + Raises: + TypeError: If `t_list` is not a sequence. + """ + if (not isinstance(t_list, collections_abc.Sequence) or + isinstance(t_list, str)): + raise TypeError("`t_list` should be a sequence of tensors. Received " + f"{type(t_list)}.") + t_list = list(t_list) + with ops.name_scope(name, "global_norm", t_list) as name: + values = [ + ops.convert_to_tensor( + t.values if isinstance(t, indexed_slices.IndexedSlices) else t, + name="t_%d" % i) if t is not None else t + for i, t in enumerate(t_list) + ] + half_squared_norms = [] + for v in values: + if v is not None: + with ops.colocate_with(v): + half_squared_norms.append(gen_nn_ops.l2_loss(v)) + + half_squared_norm = math_ops.reduce_sum( + array_ops_stack.stack(half_squared_norms)) + + norm = math_ops.sqrt( + half_squared_norm * + constant_op.constant(2.0, dtype=half_squared_norm.dtype), + name="global_norm") + + return norm + + +@tf_export("clip_by_global_norm") +@dispatch.add_dispatch_support +def clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None): + """Clips values of multiple tensors by the ratio of the sum of their norms. + + Given a tuple or list of tensors `t_list`, and a clipping ratio `clip_norm`, + this operation returns a list of clipped tensors `list_clipped` + and the global norm (`global_norm`) of all tensors in `t_list`. Optionally, + if you've already computed the global norm for `t_list`, you can specify + the global norm with `use_norm`. + + To perform the clipping, the values `t_list[i]` are set to: + + t_list[i] * clip_norm / max(global_norm, clip_norm) + + where: + + global_norm = sqrt(sum([l2norm(t)**2 for t in t_list])) + + If `clip_norm > global_norm` then the entries in `t_list` remain as they are, + otherwise they're all shrunk by the global ratio. + + If `global_norm == infinity` then the entries in `t_list` are all set to `NaN` + to signal that an error occurred. + + Any of the entries of `t_list` that are of type `None` are ignored. + + This is the correct way to perform gradient clipping (Pascanu et al., 2012). + + However, it is slower than `clip_by_norm()` because all the parameters must be + ready before the clipping operation can be performed. + + Args: + t_list: A tuple or list of mixed `Tensors`, `IndexedSlices`, or None. + clip_norm: A 0-D (scalar) `Tensor` > 0. The clipping ratio. + use_norm: A 0-D (scalar) `Tensor` of type `float` (optional). The global + norm to use. If not provided, `global_norm()` is used to compute the norm. + name: A name for the operation (optional). + + Returns: + list_clipped: A list of `Tensors` of the same type as `list_t`. + global_norm: A 0-D (scalar) `Tensor` representing the global norm. + + Raises: + TypeError: If `t_list` is not a sequence. + + References: + On the difficulty of training Recurrent Neural Networks: + [Pascanu et al., 2012](http://proceedings.mlr.press/v28/pascanu13.html) + ([pdf](http://proceedings.mlr.press/v28/pascanu13.pdf)) + """ + if (not isinstance(t_list, collections_abc.Sequence) or + isinstance(t_list, str)): + raise TypeError("`t_list` should be a sequence of tensors. Received " + f"{type(t_list)}.") + t_list = list(t_list) + if use_norm is None: + use_norm = global_norm(t_list, name) + + with ops.name_scope(name, "clip_by_global_norm", + t_list + [clip_norm]) as name: + # Calculate L2-norm, clip elements by ratio of clip_norm to L2-norm + scale_for_finite = clip_norm * math_ops.minimum( + 1.0 / use_norm, + constant_op.constant(1.0, dtype=use_norm.dtype) / clip_norm) + # If use_norm is any finite number, this is a no-op. For inf/-inf/NaN, + # this will make scale NaN. + scale = scale_for_finite + (use_norm - use_norm) + + values = [ + ops.convert_to_tensor( + t.values if isinstance(t, indexed_slices.IndexedSlices) else t, + name="t_%d" % i) if t is not None else t + for i, t in enumerate(t_list) + ] + + values_clipped = [] + for i, v in enumerate(values): + if v is None: + values_clipped.append(None) + else: + with ops.colocate_with(v): + values_clipped.append( + array_ops.identity( + v * math_ops.cast(scale, v.dtype), name="%s_%d" % (name, i) + ) + ) + + list_clipped = [ + indexed_slices.IndexedSlices(c_v, t.indices, t.dense_shape) + if isinstance(t, indexed_slices.IndexedSlices) else c_v + for (c_v, t) in zip(values_clipped, t_list) + ] + + return list_clipped, use_norm + + +@deprecation.deprecated( + date=None, + instructions="clip_by_average_norm is deprecated in TensorFlow 2.0. Please " + "use clip_by_norm(t, clip_norm * tf.cast(tf.size(t), tf.float32), name) " + "instead.") +@tf_export(v1=["clip_by_average_norm"]) +@dispatch.add_dispatch_support +def clip_by_average_norm(t, clip_norm, name=None): + """Clips tensor values to a maximum average L2-norm. + + Given a tensor `t`, and a maximum clip value `clip_norm`, this operation + normalizes `t` so that its average L2-norm is less than or equal to + `clip_norm`. Specifically, if the average L2-norm is already less than or + equal to `clip_norm`, then `t` is not modified. If the average L2-norm is + greater than `clip_norm`, then this operation returns a tensor of the same + type and shape as `t` with its values set to: + + `t * clip_norm / l2norm_avg(t)` + + In this case, the average L2-norm of the output tensor is `clip_norm`. + + This operation is typically used to clip gradients before applying them with + an optimizer. + + Args: + t: A `Tensor`. + clip_norm: A 0-D (scalar) `Tensor` > 0. A maximum clipping value. + name: A name for the operation (optional). + + Returns: + A clipped `Tensor`. + """ + with ops.name_scope(name, "clip_by_average_norm", [t, clip_norm]) as name: + t = ops.convert_to_tensor(t, name="t") + + # Calculate L2-norm per element, clip elements by ratio of clip_norm to + # L2-norm per element + n_element = math_ops.cast(array_ops.size(t), dtypes.float32) + l2norm_inv = math_ops.rsqrt( + math_ops.reduce_sum(t * t, math_ops.range(array_ops.rank(t)))) + tclip = array_ops.identity( + t * clip_norm * math_ops.minimum( + l2norm_inv * n_element, constant_op.constant(1.0) / clip_norm), + name=name) + + return tclip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clustering_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clustering_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..049ae582ec7b2b9d864ab37d0d7ad49117f51308 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/clustering_ops.py @@ -0,0 +1,775 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Clustering Operations.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed as random_seed_ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_clustering_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.embedding_ops import embedding_lookup +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_clustering_ops import * +# pylint: enable=wildcard-import + +# Euclidean distance between vectors U and V is defined as \\(||U - V||_F\\) +# which is the square root of the sum of the absolute squares of the elements +# difference. +SQUARED_EUCLIDEAN_DISTANCE = 'squared_euclidean' +# Cosine distance between vectors U and V is defined as +# \\(1 - (U \dot V) / (||U||_F ||V||_F)\\) +COSINE_DISTANCE = 'cosine' + +RANDOM_INIT = 'random' +KMEANS_PLUS_PLUS_INIT = 'kmeans_plus_plus' +KMC2_INIT = 'kmc2' + +# The name of the variable holding the cluster centers. Used by the Estimator. +CLUSTERS_VAR_NAME = 'clusters' + + +class KMeans: + """Creates the graph for k-means clustering.""" + + def __init__(self, + inputs, + num_clusters, + initial_clusters=RANDOM_INIT, + distance_metric=SQUARED_EUCLIDEAN_DISTANCE, + use_mini_batch=False, + mini_batch_steps_per_iteration=1, + random_seed=0, + kmeans_plus_plus_num_retries=2, + kmc2_chain_length=200): + """Creates an object for generating KMeans clustering graph. + + This class implements the following variants of K-means algorithm: + + If use_mini_batch is False, it runs standard full batch K-means. Each step + runs a single iteration of K-Means. This step can be run sharded across + multiple workers by passing a list of sharded inputs to this class. Note + however that a single step needs to process the full input at once. + + If use_mini_batch is True, it runs a generalization of the mini-batch + K-means algorithm. It runs multiple iterations, where each iteration is + composed of mini_batch_steps_per_iteration steps. Two copies of cluster + centers are maintained: one that is updated at the end of each iteration, + and one that is updated every step. The first copy is used to compute + cluster allocations for each step, and for inference, while the second copy + is the one updated each step using the mini-batch update rule. After each + iteration is complete, this second copy is copied back the first copy. + + Note that for use_mini_batch=True, when mini_batch_steps_per_iteration=1, + the algorithm reduces to the standard mini-batch algorithm. Also by setting + mini_batch_steps_per_iteration = num_inputs / batch_size, the algorithm + becomes an asynchronous version of the full-batch algorithm. Note however + that there is no guarantee by this implementation that each input is seen + exactly once per iteration. Also, different updates are applied + asynchronously without locking. So this asynchronous version may not behave + exactly like a full-batch version. + + Args: + inputs: An input tensor or list of input tensors. It is assumed that the + data points have been previously randomly permuted. + num_clusters: An integer tensor specifying the number of clusters. This + argument is ignored if initial_clusters is a tensor or numpy array. + initial_clusters: Specifies the clusters used during initialization. One + of the following: - a tensor or numpy array with the initial cluster + centers. - a function f(inputs, k) that returns up to k centers from + `inputs`. + - "random": Choose centers randomly from `inputs`. + - "kmeans_plus_plus": Use kmeans++ to choose centers from `inputs`. + - "kmc2": Use the fast k-MC2 algorithm to choose centers from `inputs`. + In the last three cases, one batch of `inputs` may not yield + `num_clusters` centers, in which case initialization will require + multiple batches until enough centers are chosen. In the case of + "random" or "kmeans_plus_plus", if the input size is <= `num_clusters` + then the entire batch is chosen to be cluster centers. + distance_metric: Distance metric used for clustering. Supported options: + "squared_euclidean", "cosine". + use_mini_batch: If true, use the mini-batch k-means algorithm. Else assume + full batch. + mini_batch_steps_per_iteration: Number of steps after which the updated + cluster centers are synced back to a master copy. + random_seed: Seed for PRNG used to initialize seeds. + kmeans_plus_plus_num_retries: For each point that is sampled during + kmeans++ initialization, this parameter specifies the number of + additional points to draw from the current distribution before selecting + the best. If a negative value is specified, a heuristic is used to + sample O(log(num_to_sample)) additional points. + kmc2_chain_length: Determines how many candidate points are used by the + k-MC2 algorithm to produce one new cluster centers. If a (mini-)batch + contains less points, one new cluster center is generated from the + (mini-)batch. + + Raises: + ValueError: An invalid argument was passed to initial_clusters or + distance_metric. + """ + initialization_algorithms = [RANDOM_INIT, KMEANS_PLUS_PLUS_INIT, KMC2_INIT] + if isinstance(initial_clusters, + str) and initial_clusters not in initialization_algorithms: + raise ValueError( + f'Unsupported initialization algorithm `{initial_clusters}`,' + f'must be one of `{initialization_algorithms}`.') + + distance_metrics = [SQUARED_EUCLIDEAN_DISTANCE, COSINE_DISTANCE] + if distance_metric not in distance_metrics: + raise ValueError(f'Unsupported distance metric `{distance_metric}`,' + f'must be one of `{distance_metrics}`.') + self._inputs = inputs if isinstance(inputs, list) else [inputs] + self._num_clusters = num_clusters + self._initial_clusters = initial_clusters + self._distance_metric = distance_metric + self._use_mini_batch = use_mini_batch + self._mini_batch_steps_per_iteration = int(mini_batch_steps_per_iteration) + self._seed = random_seed_ops.get_seed(random_seed)[0] + self._kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries + self._kmc2_chain_length = kmc2_chain_length + + @classmethod + def _distance_graph(cls, inputs, clusters, distance_metric): + """Computes distance between each input and each cluster center. + + Args: + inputs: list of input Tensors. + clusters: cluster Tensor. + distance_metric: distance metric used for clustering + + Returns: + list of Tensors, where each element corresponds to each element in inputs. + The value is the distance of each row to all the cluster centers. + Currently only Euclidean distance and cosine distance are supported. + """ + assert isinstance(inputs, list) + if distance_metric == SQUARED_EUCLIDEAN_DISTANCE: + return cls._compute_euclidean_distance(inputs, clusters) + elif distance_metric == COSINE_DISTANCE: + return cls._compute_cosine_distance( + inputs, clusters, inputs_normalized=True) + else: + assert False, str(distance_metric) + + @classmethod + def _compute_euclidean_distance(cls, inputs, clusters): + """Computes Euclidean distance between each input and each cluster center. + + Args: + inputs: list of input Tensors. + clusters: cluster Tensor. + + Returns: + list of Tensors, where each element corresponds to each element in inputs. + The value is the distance of each row to all the cluster centers. + """ + output = [] + for inp in inputs: + with ops.colocate_with(inp, ignore_existing=True): + # Computes Euclidean distance. Note the first and third terms are + # broadcast additions. + squared_distance = ( + math_ops.reduce_sum(math_ops.square(inp), 1, keepdims=True) - + 2 * math_ops.matmul(inp, clusters, transpose_b=True) + + array_ops.transpose( + math_ops.reduce_sum( + math_ops.square(clusters), 1, keepdims=True))) + output.append(squared_distance) + + return output + + @classmethod + def _compute_cosine_distance(cls, inputs, clusters, inputs_normalized=True): + """Computes cosine distance between each input and each cluster center. + + Args: + inputs: list of input Tensor. + clusters: cluster Tensor + inputs_normalized: if True, it assumes that inp and clusters are + normalized and computes the dot product which is equivalent to the + cosine distance. Else it L2 normalizes the inputs first. + + Returns: + list of Tensors, where each element corresponds to each element in inp. + The value is the distance of each row to all the cluster centers. + """ + output = [] + if not inputs_normalized: + with ops.colocate_with(clusters, ignore_existing=True): + clusters = nn_impl.l2_normalize(clusters, axis=1) + for inp in inputs: + with ops.colocate_with(inp, ignore_existing=True): + if not inputs_normalized: + inp = nn_impl.l2_normalize(inp, axis=1) + output.append(1 - math_ops.matmul(inp, clusters, transpose_b=True)) + return output + + def _infer_graph(self, inputs, clusters): + """Maps input to closest cluster and the score. + + Args: + inputs: list of input Tensors. + clusters: Tensor of cluster centers. + + Returns: + List of tuple, where each value in tuple corresponds to a value in inp. + The tuple has following three elements: + all_scores: distance of each input to each cluster center. + score: distance of each input to closest cluster center. + cluster_idx: index of cluster center closest to the corresponding input. + """ + assert isinstance(inputs, list) + # Pairwise distances are used only by transform(). In all other cases, this + # sub-graph is not evaluated. + scores = self._distance_graph(inputs, clusters, self._distance_metric) + output = [] + if (self._distance_metric == COSINE_DISTANCE and + not self._clusters_l2_normalized()): + # The cosine distance between normalized vectors x and y is the same as + # 2 * squared_euclidean_distance. We are using this fact and reusing the + # nearest_neighbors op. + # TODO(ands): Support COSINE distance in nearest_neighbors and remove + # this. + with ops.colocate_with(clusters, ignore_existing=True): + clusters = nn_impl.l2_normalize(clusters, axis=1) + for inp, score in zip(inputs, scores): + with ops.colocate_with(inp, ignore_existing=True): + (indices, + distances) = gen_clustering_ops.nearest_neighbors(inp, clusters, 1) + if self._distance_metric == COSINE_DISTANCE: + distances *= 0.5 + output.append( + (score, array_ops.squeeze(distances, + [-1]), array_ops.squeeze(indices, [-1]))) + return zip(*output) + + def _clusters_l2_normalized(self): + """Returns True if clusters centers are kept normalized.""" + return (self._distance_metric == COSINE_DISTANCE and + (not self._use_mini_batch or + self._mini_batch_steps_per_iteration > 1)) + + def _create_variables(self, num_clusters): + """Creates variables. + + Args: + num_clusters: an integer Tensor providing the number of clusters. + + Returns: + Tuple with following elements: + - cluster_centers: a Tensor for storing cluster centers + - cluster_centers_initialized: bool Variable indicating whether clusters + are initialized. + - cluster_counts: a Tensor for storing counts of points assigned to this + cluster. This is used by mini-batch training. + - cluster_centers_updated: Tensor representing copy of cluster centers + that are updated every step. + - update_in_steps: numbers of steps left before we sync + cluster_centers_updated back to cluster_centers. + """ + init_value = array_ops.placeholder_with_default([], shape=None) + cluster_centers = variable_v1.VariableV1( + init_value, name=CLUSTERS_VAR_NAME, validate_shape=False) + cluster_centers_initialized = variable_v1.VariableV1( + False, dtype=dtypes.bool, name='initialized') + + if self._use_mini_batch and self._mini_batch_steps_per_iteration > 1: + # Copy of cluster centers actively updated each step according to + # mini-batch update rule. + cluster_centers_updated = variable_v1.VariableV1( + init_value, name='clusters_updated', validate_shape=False) + # How many steps till we copy the updated clusters to cluster_centers. + update_in_steps = variable_v1.VariableV1( + self._mini_batch_steps_per_iteration, + dtype=dtypes.int64, + name='update_in_steps') + # Count of points assigned to cluster_centers_updated. + cluster_counts = variable_v1.VariableV1( + array_ops.zeros([num_clusters], dtype=dtypes.int64)) + else: + cluster_centers_updated = cluster_centers + update_in_steps = None + cluster_counts = ( + variable_v1.VariableV1( + array_ops.ones([num_clusters], dtype=dtypes.int64)) + if self._use_mini_batch else None) + return (cluster_centers, cluster_centers_initialized, cluster_counts, + cluster_centers_updated, update_in_steps) + + @classmethod + def _l2_normalize_data(cls, inputs): + """Normalized the input data.""" + output = [] + for inp in inputs: + with ops.colocate_with(inp, ignore_existing=True): + output.append(nn_impl.l2_normalize(inp, dim=1)) + return output + + def training_graph(self): + """Generate a training graph for kmeans algorithm. + + This returns, among other things, an op that chooses initial centers + (init_op), a boolean variable that is set to True when the initial centers + are chosen (cluster_centers_initialized), and an op to perform either an + entire Lloyd iteration or a mini-batch of a Lloyd iteration (training_op). + The caller should use these components as follows. A single worker should + execute init_op multiple times until cluster_centers_initialized becomes + True. Then multiple workers may execute training_op any number of times. + + Returns: + A tuple consisting of: + all_scores: A matrix (or list of matrices) of dimensions (num_input, + num_clusters) where the value is the distance of an input vector and a + cluster center. + cluster_idx: A vector (or list of vectors). Each element in the vector + corresponds to an input row in 'inp' and specifies the cluster id + corresponding to the input. + scores: Similar to cluster_idx but specifies the distance to the + assigned cluster instead. + cluster_centers_initialized: scalar indicating whether clusters have been + initialized. + init_op: an op to initialize the clusters. + training_op: an op that runs an iteration of training. + """ + # Implementation of kmeans. + if (isinstance(self._initial_clusters, str) or + callable(self._initial_clusters)): + initial_clusters = self._initial_clusters + num_clusters = ops.convert_to_tensor(self._num_clusters) + else: + initial_clusters = ops.convert_to_tensor(self._initial_clusters) + num_clusters = array_ops.shape(initial_clusters)[0] + + inputs = self._inputs + (cluster_centers_var, cluster_centers_initialized, total_counts, + cluster_centers_updated, + update_in_steps) = self._create_variables(num_clusters) + init_op = _InitializeClustersOpFactory( + self._inputs, num_clusters, initial_clusters, self._distance_metric, + self._seed, self._kmeans_plus_plus_num_retries, self._kmc2_chain_length, + cluster_centers_var, cluster_centers_updated, + cluster_centers_initialized).op() + cluster_centers = cluster_centers_var + + if self._distance_metric == COSINE_DISTANCE: + inputs = self._l2_normalize_data(inputs) + if not self._clusters_l2_normalized(): + cluster_centers = nn_impl.l2_normalize(cluster_centers, dim=1) + + all_scores, scores, cluster_idx = self._infer_graph(inputs, cluster_centers) + if self._use_mini_batch: + sync_updates_op = self._mini_batch_sync_updates_op( + update_in_steps, cluster_centers_var, cluster_centers_updated, + total_counts) + assert sync_updates_op is not None + with ops.control_dependencies([sync_updates_op]): + training_op = self._mini_batch_training_op(inputs, cluster_idx, + cluster_centers_updated, + total_counts) + else: + assert cluster_centers == cluster_centers_var + training_op = self._full_batch_training_op(inputs, num_clusters, + cluster_idx, + cluster_centers_var) + + return (all_scores, cluster_idx, scores, cluster_centers_initialized, + init_op, training_op) + + def _mini_batch_sync_updates_op(self, update_in_steps, cluster_centers_var, + cluster_centers_updated, total_counts): + if self._use_mini_batch and self._mini_batch_steps_per_iteration > 1: + assert update_in_steps is not None + with ops.colocate_with(update_in_steps, ignore_existing=True): + + def _f(): + # Note that there is a race condition here, so we do a best effort + # updates here. We reset update_in_steps first so that other workers + # don't duplicate the updates. Also we update cluster_center_vars + # before resetting total_counts to avoid large updates to + # cluster_centers_updated based on partially updated + # cluster_center_vars. + with ops.control_dependencies([ + state_ops.assign(update_in_steps, + self._mini_batch_steps_per_iteration - 1) + ]): + with ops.colocate_with( + cluster_centers_updated, ignore_existing=True): + if self._distance_metric == COSINE_DISTANCE: + cluster_centers = nn_impl.l2_normalize( + cluster_centers_updated, dim=1) + else: + cluster_centers = cluster_centers_updated + with ops.colocate_with(cluster_centers_var, ignore_existing=True): + with ops.control_dependencies( + [state_ops.assign(cluster_centers_var, cluster_centers)]): + with ops.colocate_with(None, ignore_existing=True): + with ops.control_dependencies([ + state_ops.assign(total_counts, + array_ops.zeros_like(total_counts)) + ]): + return array_ops.identity(update_in_steps) + + return cond.cond( + update_in_steps <= 0, _f, + lambda: state_ops.assign_sub(update_in_steps, 1)) + else: + return control_flow_ops.no_op() + + def _mini_batch_training_op(self, inputs, cluster_idx_list, cluster_centers, + total_counts): + """Creates an op for training for mini batch case. + + Args: + inputs: list of input Tensors. + cluster_idx_list: A vector (or list of vectors). Each element in the + vector corresponds to an input row in 'inp' and specifies the cluster id + corresponding to the input. + cluster_centers: Tensor Ref of cluster centers. + total_counts: Tensor Ref of cluster counts. + + Returns: + An op for doing an update of mini-batch k-means. + """ + update_ops = [] + for inp, cluster_idx in zip(inputs, cluster_idx_list): + with ops.colocate_with(inp, ignore_existing=True): + assert total_counts is not None + cluster_idx = array_ops.reshape(cluster_idx, [-1]) + # Dedupe the unique ids of cluster_centers being updated so that updates + # can be locally aggregated. + unique_ids, unique_idx = array_ops.unique(cluster_idx) + num_unique_cluster_idx = array_ops.size(unique_ids) + # Fetch the old values of counts and cluster_centers. + with ops.colocate_with(total_counts, ignore_existing=True): + old_counts = array_ops.gather(total_counts, unique_ids) + # TODO(agarwal): This colocation seems to run into problems. Fix it. + with ops.colocate_with(cluster_centers, ignore_existing=True): + old_cluster_centers = array_ops.gather(cluster_centers, unique_ids) + # Locally aggregate the increment to counts. + count_updates = math_ops.unsorted_segment_sum( + array_ops.ones_like(unique_idx, dtype=total_counts.dtype), + unique_idx, num_unique_cluster_idx) + # Locally compute the sum of inputs mapped to each id. + # For a cluster with old cluster value x, old count n, and with data + # d_1,...d_k newly assigned to it, we recompute the new value as + # \\(x += (sum_i(d_i) - k * x) / (n + k)\\). + # Compute \\(sum_i(d_i)\\), see comment above. + cluster_center_updates = math_ops.unsorted_segment_sum( + inp, unique_idx, num_unique_cluster_idx) + # Shape to enable broadcasting count_updates and learning_rate to inp. + # It extends the shape with 1's to match the rank of inp. + broadcast_shape = array_ops.concat([ + array_ops.reshape(num_unique_cluster_idx, [1]), + array_ops.ones( + array_ops.reshape(array_ops.rank(inp) - 1, [1]), + dtype=dtypes.int32) + ], 0) + # Subtract k * x, see comment above. + cluster_center_updates -= math_ops.cast( + array_ops.reshape(count_updates, broadcast_shape), + inp.dtype) * old_cluster_centers + learning_rate = math_ops.reciprocal( + math_ops.cast(old_counts + count_updates, inp.dtype)) + learning_rate = array_ops.reshape(learning_rate, broadcast_shape) + # scale by 1 / (n + k), see comment above. + cluster_center_updates *= learning_rate + # Apply the updates. + update_counts = state_ops.scatter_add(total_counts, unique_ids, + count_updates) + update_cluster_centers = state_ops.scatter_add(cluster_centers, + unique_ids, + cluster_center_updates) + update_ops.extend([update_counts, update_cluster_centers]) + return control_flow_ops.group(*update_ops) + + def _full_batch_training_op(self, inputs, num_clusters, cluster_idx_list, + cluster_centers): + """Creates an op for training for full batch case. + + Args: + inputs: list of input Tensors. + num_clusters: an integer Tensor providing the number of clusters. + cluster_idx_list: A vector (or list of vectors). Each element in the + vector corresponds to an input row in 'inp' and specifies the cluster id + corresponding to the input. + cluster_centers: Tensor Ref of cluster centers. + + Returns: + An op for doing an update of mini-batch k-means. + """ + cluster_sums = [] + cluster_counts = [] + epsilon = constant_op.constant(1e-6, dtype=inputs[0].dtype) + for inp, cluster_idx in zip(inputs, cluster_idx_list): + with ops.colocate_with(inp, ignore_existing=True): + cluster_sums.append( + math_ops.unsorted_segment_sum(inp, cluster_idx, num_clusters)) + cluster_counts.append( + math_ops.unsorted_segment_sum( + array_ops.reshape( + array_ops.ones( + array_ops.reshape(array_ops.shape(inp)[0], [-1])), + [-1, 1]), cluster_idx, num_clusters)) + with ops.colocate_with(cluster_centers, ignore_existing=True): + new_clusters_centers = math_ops.add_n(cluster_sums) / ( + math_ops.cast(math_ops.add_n(cluster_counts), cluster_sums[0].dtype) + + epsilon) + if self._clusters_l2_normalized(): + new_clusters_centers = nn_impl.l2_normalize(new_clusters_centers, dim=1) + return state_ops.assign(cluster_centers, new_clusters_centers) + + +class _InitializeClustersOpFactory: + """Internal class to create the op to initialize the clusters. + + The op performs this algorithm (see constructor args): + + num_remaining = num_clusters - length(cluster_centers) + if num_remaining == 0: + assert that cluster_centers_initialized is true + else: + assert that num_remaining > 0 + new_centers = choose up to num_remaining initial centers + l2-normalize new_centers if using cosine distance + all_centers = concat(cluster_centers, new_centers) + cluster_centers := all_centers + if there is a cluster_centers_updated variable: + cluster_centers_updated := cluster_centers + num_now_remaining = num_clusters - length(cluster_centers) + if num_now_remaining == 0: + cluster_centers_initialized := true + """ + + # TODO(ccolby): Refactor this class so that kmc2 isn't so much a special case. + + def __init__(self, inputs, num_clusters, initial_clusters, distance_metric, + random_seed, kmeans_plus_plus_num_retries, kmc2_chain_length, + cluster_centers, cluster_centers_updated, + cluster_centers_initialized): + """Creates an op factory. + + Args: + inputs: See KMeans constructor. + num_clusters: An integer Tensor providing the number of clusters. + initial_clusters: See KMeans constructor. + distance_metric: See KMeans constructor. + random_seed: See KMeans constructor. + kmeans_plus_plus_num_retries: See KMeans constructor. + kmc2_chain_length: See KMeans constructor. + cluster_centers: The TF variable holding the initial centers. It may + already contain some centers when the op is executed. + cluster_centers_updated: A second TF variable to hold a copy of the + initial centers, used for full-batch mode. In mini-batch mode, + cluster_centers_updated is the same variable as cluster_centers. + cluster_centers_initialized: A boolean TF variable that will be set to + true when all the initial centers have been chosen. + """ + # All of these instance variables are constants. + self._inputs = inputs + self._num_clusters = num_clusters + self._initial_clusters = initial_clusters + self._distance_metric = distance_metric + self._seed = random_seed + self._kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries + self._kmc2_chain_length = kmc2_chain_length + self._cluster_centers = cluster_centers + self._cluster_centers_updated = cluster_centers_updated + self._cluster_centers_initialized = cluster_centers_initialized + + self._num_selected = array_ops.shape(self._cluster_centers)[0] + self._num_remaining = self._num_clusters - self._num_selected + self._num_data = math_ops.add_n( + [array_ops.shape(i)[0] for i in self._inputs]) + + def _random(self): + indices = random_ops.random_uniform( + array_ops.reshape(self._num_remaining, [-1]), + minval=0, + maxval=math_ops.cast(self._num_data, dtypes.int64), + seed=self._seed, + dtype=dtypes.int64) + return embedding_lookup(self._inputs, indices, partition_strategy='div') + + def _kmeans_plus_plus(self): + # Points from only the first shard are used for initializing centers. + # TODO(ands): Use all points. + inp = self._inputs[0] + if self._distance_metric == COSINE_DISTANCE: + inp = nn_impl.l2_normalize(inp, dim=1) + return gen_clustering_ops.kmeans_plus_plus_initialization( + inp, math_ops.cast(self._num_remaining, dtypes.int64), self._seed, + self._kmeans_plus_plus_num_retries) + + def _kmc2_multiple_centers(self): + """Adds new initial cluster centers using the k-MC2 algorithm. + + In each call to the op, the provided batch is split into subsets based on + the specified `kmc2_chain_length`. On each subset, a single Markov chain of + the k-MC2 algorithm is used to add *one* new center cluster center. If there + are less than `kmc2_chain_length` points in the subset, a single center is + added using one Markov chain on the full input. It is assumed that the + provided batch has previously been randomly permuted. Otherwise, k-MC2 may + return suboptimal centers. + + Returns: + An op that adds new cluster centers. + """ + # The op only operates on the first shard of data. + first_shard = self._inputs[0] + # Number of points in the input that can be used. + batch_size = array_ops.shape(first_shard)[0] + # Maximum number of subsets such that the size of each subset is at least + # `kmc2_chain_length`. Final subsets may be larger. + max_to_sample = math_ops.cast( + batch_size / self._kmc2_chain_length, dtype=dtypes.int32) + # We sample at least one new center and at most all remaining centers. + num_to_sample = math_ops.maximum( + math_ops.minimum(self._num_remaining, max_to_sample), 1) + + def _cond(i, _): + """Stopping condition for the while loop.""" + return math_ops.less(i, num_to_sample) + + def _body(i, _): + """Body that adds a single new center based on a subset.""" + + def _sample_random(): + """Returns a random point as a cluster center.""" + # By assumption the batch is reshuffled and _sample_random is always + # called for i=0. Hence, we simply return the first point. + new_center = array_ops.reshape(first_shard[0], [1, -1]) + if self._distance_metric == COSINE_DISTANCE: + new_center = nn_impl.l2_normalize(new_center, dim=1) + return new_center + + def _sample_kmc2_chain(): + """Returns previous centers as well as a new center sampled using k-MC2.""" + # Extract the subset from the underlying batch. + start = i * self._kmc2_chain_length + end = start + self._kmc2_chain_length + subset = first_shard[start:end] + # Compute the distances from points in the subset to previous centers. + _, distances = gen_clustering_ops.nearest_neighbors( + subset, self._cluster_centers, 1) + # Sample index of new center using k-MC2 Markov chain. + new_center_index = gen_clustering_ops.kmc2_chain_initialization( + array_ops.squeeze(distances), self._seed) + # Extract actual new center. + newly_sampled_center = array_ops.reshape(subset[new_center_index], + [1, -1]) + # Return concatenation with previously sampled centers. + if self._distance_metric == COSINE_DISTANCE: + newly_sampled_center = nn_impl.l2_normalize( + newly_sampled_center, dim=1) + return array_ops.concat([self._cluster_centers, newly_sampled_center], + 0) + + # Obtain a random point if there are no previously sampled centers. + # Otherwise, construct a k-MC2 Markov chain. + new_centers = cond.cond( + math_ops.equal(self._num_selected, 0), _sample_random, + _sample_kmc2_chain) + # Assign new cluster centers to underlying variable. + assigned_centers = state_ops.assign( + self._cluster_centers, new_centers, validate_shape=False) + if self._cluster_centers_updated is not self._cluster_centers: + assigned_centers = state_ops.assign( + self._cluster_centers_updated, + assigned_centers, + validate_shape=False) + return i + 1, self._num_clusters - array_ops.shape(assigned_centers)[0] + + # Add num_to_sample new data points. + _, num_remaining = while_loop.while_loop(_cond, _body, [0, 0]) + return num_remaining + + def _greedy_batch_sampler(self, sampler): + # If the input dataset size is smaller than the number of centers + # remaining, choose the entire input dataset as centers. This can happen + # with mini-batch. Otherwise, sample the batch according to the provided + # sampler. + return cond.cond(self._num_data <= self._num_remaining, + lambda: array_ops.concat(self._inputs, 0), + sampler) + + def _single_batch_sampler(self, sampler): + # Enforce that there are at least as many data points as centers + # remaining. This gives the provided sampler the chance to select all + # remaining centers from a single batch. + with ops.control_dependencies( + [check_ops.assert_greater_equal(self._num_data, self._num_remaining)]): + return sampler() + + def _choose_initial_centers(self): + if isinstance(self._initial_clusters, str): + if self._initial_clusters == RANDOM_INIT: + return self._greedy_batch_sampler(self._random) + else: # self._initial_clusters == KMEANS_PLUS_PLUS_INIT + return self._single_batch_sampler(self._kmeans_plus_plus) + elif callable(self._initial_clusters): + return self._initial_clusters(self._inputs, self._num_remaining) + else: + with ops.control_dependencies([ + check_ops.assert_equal(self._num_remaining, + array_ops.shape(self._initial_clusters)[0]) + ]): + return self._initial_clusters + + def _add_new_centers(self): + """Adds some centers and returns the number of centers remaining.""" + new_centers = self._choose_initial_centers() + if self._distance_metric == COSINE_DISTANCE: + new_centers = nn_impl.l2_normalize(new_centers, dim=1) + # If cluster_centers is empty, it doesn't have the right shape for concat. + all_centers = cond.cond( + math_ops.equal(self._num_selected, 0), lambda: new_centers, + lambda: array_ops.concat([self._cluster_centers, new_centers], 0)) + # TODO(ccolby): De-dupe all_centers? + a = state_ops.assign( + self._cluster_centers, all_centers, validate_shape=False) + if self._cluster_centers_updated is not self._cluster_centers: + a = state_ops.assign( + self._cluster_centers_updated, a, validate_shape=False) + return self._num_clusters - array_ops.shape(a)[0] + + def _initialize(self): + with ops.control_dependencies([ + check_ops.assert_positive(self._num_remaining), + ]): + if self._initial_clusters == KMC2_INIT: + num_now_remaining = self._kmc2_multiple_centers() + else: + num_now_remaining = self._add_new_centers() + return cond.cond( + math_ops.equal(num_now_remaining, 0), + lambda: state_ops.assign(self._cluster_centers_initialized, True), + control_flow_ops.no_op) + + def op(self): + """Returns the cluster initializer op.""" + return cond.cond( + math_ops.equal(self._num_remaining, 0), + lambda: check_ops.assert_equal(self._cluster_centers_initialized, True), + self._initialize) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/collective_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/collective_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..eb822002b435ae7e44ed4b41182958a3a22b00cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/collective_ops.py @@ -0,0 +1,578 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorFlow collective Ops.""" +from tensorflow.python.ops import gen_collective_ops + + +def all_reduce(t, + group_size, + group_key, + instance_key, + merge_op='Add', + final_op='Id', + subdiv_offsets=(0,), + communication_hint='auto', + timeout=0): + """Reduces tensors collectively, across devices. + + Args: + t: the tensor to be reduced. + group_size: the total number of tensors to be collectively reduced. + Each must reside on a different device. Should be a positive integer. + group_key: an integer identifying the group of devices. + instance_key: an integer identifying the participating group of Ops. + merge_op: string naming the binary Op to be applied to compute each + partial reduction. + final_op: string naming the unary Op to be applied to each fully + reduced value. Can be 'Id' for no operation. + subdiv_offsets: a list of integer offsets into the tensor at which each + independent subdivision should begin. Use [0] if no subdivision should + be done. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: a float. If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the distributed reduction. + + Raises: + ValueError: if any of the input parameter constraints are not met. + """ + if group_size < 1: + raise ValueError('Parameter `group_size` to all_reduce must be at least 1. ' + f'Received: {group_size}.') + return gen_collective_ops.collective_reduce( + t, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + merge_op=merge_op, + final_op=final_op, + subdiv_offsets=subdiv_offsets, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def assign_group_v2(group_assignment, device_index, base_key): + """Assign group key based on group_assignment. + + Args: + group_assignment: a 2 dimensional integer Tensor that encodes which devices + belong to the same group. The values are indices of the devices within 0 + to number of devices. + device_index: integer for the index of the current device + base_key: integer to offset the resulted group_key. The base key shall be + unique for different values of group_assignment in the same tf.function. + Notes: The device_index argument must be consistent with the index of the + device of this Op in the device assignment list. The behavior of this Op is + undefined if they are inconsistent. + + Returns: + group_size, group_key: The group size and group key for the current device. + """ + group_size, group_key = gen_collective_ops.collective_assign_group_v2( + group_assignment=group_assignment, + device_index=device_index, + base_key=base_key) + return group_size, group_key + + +def all_reduce_v2(t, + group_size, + group_key, + instance_key, + merge_op='Add', + final_op='Id', + communication_hint='auto', + timeout=0, + ordering_token=None, + max_subdivs_per_device=-1, + name=None): + """Reduces tensors collectively, across devices. + + Args: + t: the tensor to be reduced. + group_size: an int32 tensor. The total number of tensors to be collectively + reduced. Each must reside on a different device. Should be a positive + integer. + group_key: an int32 tensor identifying the group of devices. + instance_key: an int32 tensor identifying the participating group of Ops. + merge_op: string naming the binary Op to be applied to compute each partial + reduction. + final_op: string naming the unary Op to be applied to each fully reduced + value. Can be 'Id' for no operation. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: a float. If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + ordering_token: a resource tensor on the same device as the op to order + the collectives in a per-device manner by auto control dependency. + This argument can be omited when there is one collective Op per + `tf.function`, or when explicit control dependency is used instead of + auto control dependency. + max_subdivs_per_device: int specifying the maximum number of subdivisions a + tensor on a device can be divided into. The runtime uses this contraint to + parallelize processing of each per-device tensor. Setting to -1 disables + subdivision and reverts to previous behavior of not sub-dividing tensor. + Setting to 0 uses sytem defaults. + name: name of the Op. + + Returns: + An Op implementing the distributed reduction. + """ + if ordering_token is not None: + ordering_token = [ordering_token] + else: + ordering_token = [] + + return gen_collective_ops.collective_reduce_v2( + t, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + merge_op=merge_op, + final_op=final_op, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout, + is_stateless=False, + ordering_token=ordering_token, + max_subdivs_per_device=max_subdivs_per_device, + name=name) + + +def all_gather(t, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0): + """Accumulates tensors collectively, across devices, along first dimension. + + Args: + t: the tensor to participate in the accumulation. + group_size: the total number of tensors to be collectively accumulated. + Each must reside on a different device. Should be a positive integer. + group_key: an integer identifying the group of devices. + instance_key: an integer identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: a float. If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the distributed operation. + + Raises: + ValueError: if any of the input parameter constraints are not met. + """ + if group_size < 1: + raise ValueError('Parameter `group_size` to all_gather must be at least 1.' + f' Received: {group_size}.') + return gen_collective_ops.collective_gather( + t, + shape=[0], + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def all_gather_v2(t, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0, + ordering_token=None, + name=None): + """Accumulates tensors collectively, across devices, along first dimension. + + Args: + t: the tensor to participate in the accumulation. + group_size: an int32 tensor, the total number of tensors to be collectively + accumulated. Each must reside on a different device. Should be a positive + integer. + group_key: an int32 tensor identifying the group of devices. + instance_key: an int32 tensor identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: a float. If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + ordering_token: a resource tensor on the same device as the op to order + the collectives in a per-device manner by auto control dependency. + This argument can be omited when there is one collective Op per + `tf.function`, or when explicit control dependency is used instead of + auto control dependency. + name: name of the Op. + + Returns: + An Op implementing the distributed operation. + """ + if ordering_token is not None: + ordering_token = [ordering_token] + else: + ordering_token = [] + + return gen_collective_ops.collective_gather_v2( + t, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout, + is_stateless=False, + ordering_token=ordering_token, + name=name) + + +def broadcast_send(t, + shape, + dtype, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0): + """Broadcasts one tensor to a group of others, across devices. + + Args: + t: the tensor to be sent. + shape: the shape of the tensor being sent, which must agree with t. + dtype: the type of the tensor being sent, which must agree with t. + group_size: one plus the number of receiving tensors, i.e. the total + number of devices participating. Each tensor must reside on a + different device. + group_key: an integer identifying the group of devices. + instance_key: an integer identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: If set to a non zero, set a completion timeout to detect staleness. + If the timer goes off, a DeadlineExceededError is raised. + The timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the distributed broadcast send. + + Raises: + ValueError: if any of the input parameter constraints are not met. + + Note that the shape and dtype arguments appear redundant since they + should be obtainable from t. The are two reasons for including + them. First, the shape and type of tensors passed via broadcast must + be known ahead of time in their most specific form so that the receive + side can allocate memory for the operation and shape/type inference can + carry forward from there. Including the same declarations on the + send side clarifies a commitment already made. Secondly, having nearly + identical use syntax for send and receive sides may simplify tool-driven + generation of broadcast. + """ + if group_size <= 1: + raise ValueError( + 'Parameter `group_size` to broadcast_send must be at least 2. ' + f'Received: {group_size}.') + if t.shape != shape: + raise ValueError( + 'Shape of broadcast_send tensor `t` not equal to declared shape. ' + f'Received {t.shape}, expected {shape}.') + if t.dtype != dtype: + raise ValueError( + 'Type of broadcast_send tensor `t` not equal to declared type. ' + f'Received {t.dtype}, expected {dtype}.') + return gen_collective_ops.collective_bcast_send( + t, + shape=shape, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def broadcast_send_v2(t, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0): + """Broadcasts one tensor to a group of others, across devices. + + Args: + t: the tensor to be sent. + group_size: an int32 tensor. One plus the number of receiving tensors, i.e. + the total number of devices participating. Each tensor must reside on a + different device. + group_key: an int32 tensor identifying the group of devices. + instance_key: an int32 tensor identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: If set to a non zero, set a completion timeout to detect staleness. + If the timer goes off, a DeadlineExceededError is raised. + The timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the distributed broadcast send. + """ + return gen_collective_ops.collective_bcast_send_v2( + t, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def broadcast_recv(shape, + dtype, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0): + """Receives a broadcasts tensor, across devices. + + Args: + shape: Shape of the tensor to be received. + dtype: Type of the tensor to be received. + group_size: one plus the number of receiving tensors, i.e. the total + number of devices participating. Each tensor must reside on a + different device. + group_key: an integer identifying the group of devices. + instance_key: an integer identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: If set to a non zero, set a completion timeout to detect staleness. + If the timer goes off, a DeadlineExceededError is raised. + The timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the broadcast receive. + + Raises: + ValueError: if any of the input parameter constraints are not met. + """ + if group_size <= 1: + raise ValueError( + 'Parameter `group_size` to broadcast_send must be at least 2. ' + f'Received: {group_size}.') + return gen_collective_ops.collective_bcast_recv( + shape=shape, + T=dtype, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def broadcast_recv_v2(shape, + dtype, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0): + """Receives a broadcasts tensor, across devices. + + Args: + shape: an int tensor. Shape of the tensor to be received. + dtype: Type of the tensor to be received. + group_size: an int32 tensor. One plus the number of receiving tensors, i.e. + the total number of devices participating. Each tensor must reside on a + different device. + group_key: an int32 tensor identifying the group of devices. + instance_key: an int32 tensor identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout: If set to a non zero, set a completion timeout to detect staleness. + If the timer goes off, a DeadlineExceededError is raised. + The timeout value in seconds. This feature is experimental. + + Returns: + An Op implementing the broadcast receive. + """ + return gen_collective_ops.collective_bcast_recv_v2( + T=dtype, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + shape=shape, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout) + + +def initialize_communicator(group_key, + rank, + group_size, + communication_hint='auto', + timeout_seconds=0): + """Initializes a collective communicator. + + This creates a collective communicator, which represents membership to a + collective group identified by the group_key. It should be called once per + member of the group, and each member needs to be on a different device. + It blocks until all members of the group run this op. + + Communicators of a group can only be initialized once. Trying to initialize + communicators for an existing group key will result in an error. + + Args: + group_key: an int32 `tf.Tensor` identifying the group. + rank: an `tf.Tensor` specifying the rank of this device in the group. If + specified, the rank is required to be unique in the group. + group_size: an int32 `tf.Tensor`. The size of the group. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto`, `ring`, and + `nccl`. + timeout_seconds: If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + + + Returns: + A resource `tf.Tensor`. + """ + return gen_collective_ops.collective_initialize_communicator( + group_key=group_key, + rank=rank, + group_size=group_size, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds) + + +def all_reduce_v3(communicator, + t, + reduction='Add', + group_assignment=None, + timeout_seconds=None): + """Reduces tensors mutually. + + Args: + communicator: the resource `tf.Tensor` returned from + `initialize_communicator`. + t: the `tf.Tensor` to be reduced. + reduction: a string. The name of the operation to reduce the values. + Accpeted values are `"min"`, `"max"`, `"mul"`, `"add"`. + group_assignment: Optional int32 `tf.Tensor` with shape [num_groups, + num_ranks_per_group]. `group_assignment[i]` represents the ranks in the + `ith` subgroup. + timeout_seconds: If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + + Returns: + The reduced `tf.Tensor`. + """ + if group_assignment is None: + group_assignment = [] + return gen_collective_ops.collective_reduce_v3( + communicator=communicator, + input=t, + group_assignment=group_assignment, + reduction=reduction, + timeout_seconds=timeout_seconds) + + +def all_to_all_v2( + t, + group_size, + group_key, + instance_key, + communication_hint='auto', + timeout=0, + ordering_token=None, + name=None, +): + """Exchanges tensors mutually. + + Args: + t: a `tf.Tensor`. The first dimension should have the length as the size of + the group. `t[i]` is sent to `rank i` within the group. + group_size: an int32 tensor, the total number of tensors to be mutually + exchanged. Each must reside on a different device. Should be a positive + integer. + group_key: an int32 tensor identifying the group of devices. + instance_key: an int32 tensor identifying the participating group of Ops. + communication_hint: preferred collective communication. The implementation + may fall back to another mechanism. Options include `auto` and `nccl`. + timeout: a float. If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + ordering_token: a resource tensor on the same device as the op to order the + collectives in a per-device manner by auto control dependency. This + argument can be omited when there is one collective Op per `tf.function`, + or when explicit control dependency is used instead of auto control + dependency. + name: name of the Op. + + Returns: + An Op implementing the distributed operation. + """ + if ordering_token is not None: + ordering_token = [ordering_token] + else: + ordering_token = [] + + return gen_collective_ops.collective_all_to_all_v2( + t, + group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint.lower(), + timeout_seconds=timeout, + is_stateless=False, + ordering_token=ordering_token, + name=name, + ) + + +def all_to_all_v3(communicator, t, group_assignment=None, timeout_seconds=None): + """Exchanges tensors mutually. + + Args: + communicator: the resource `tf.Tensor` returned from + `initialize_communicator`. + t: a `tf.Tensor`. The first dimension should have the length as the size of + the group. `t[i]` is sent to `rank i` within the group. + group_assignment: Optional int32 `tf.Tensor` with shape [num_groups, + num_ranks_per_group]. `group_assignment[i]` represents the ranks in the + `ith` subgroup. + timeout_seconds: If set to a non zero, set a completion timeout to detect + staleness. If the timer goes off, a DeadlineExceededError is raised. The + timeout value in seconds. This feature is experimental. + + Returns: + a `tf.Tensor`. `t[i]` is sent from `rank i` within the group. + """ + if group_assignment is None: + group_assignment = [] + return gen_collective_ops.collective_all_to_all_v3( + communicator=communicator, + input=t, + group_assignment=group_assignment, + timeout_seconds=timeout_seconds) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/composite_tensor_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/composite_tensor_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..51a44613f6ddb13f181a026668d3b818a1fedbd0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/composite_tensor_ops.py @@ -0,0 +1,118 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Operations for ExtensionTypes (aka Composite Tensors).""" + +from tensorflow.core.protobuf import composite_tensor_variant_pb2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import gen_composite_tensor_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import nest + + +def composite_tensor_to_variants(value, type_spec=None, name=None): + """Encodes `value` as a scalar variant tensor. + + Args: + value: The `ExtensionType` value to encode. + type_spec: Information about the value's type that should be included in the + encoding. + name: Optional name for the operation. + + Returns: + A Tensor with shape=`()` and dtype=`tf.variant`. + + Raises: + ValueError: If `type_spec` is not compatible with `value`. + """ + if not isinstance(value, composite_tensor.CompositeTensor): + raise TypeError("Expected `value` to be a CompositeTensor. " + f"Received {type(value)}.") + + if type_spec is None: + type_spec = value._type_spec # pylint: disable=protected-access + if not type_spec.is_compatible_with(value): + raise ValueError(f"`type_spec` {type_spec} is not compatible with `value` " + f"{value!r}.") + metadata = composite_tensor_variant_pb2.CompositeTensorVariantMetadata() + metadata.type_spec_proto.CopyFrom( + nested_structure_coder.encode_structure(type_spec).type_spec_value) + + return gen_composite_tensor_ops.CompositeTensorVariantFromComponents( + components=nest.flatten(value, expand_composites=True), + metadata=metadata.SerializeToString(), + name=name) + + +def composite_tensor_from_variant(encoded, type_spec, name=None): + """Returns the `ExtensionType` value encoded by a variant scalar tensor. + + Args: + encoded: A Tensor returned by `composite_tensor_to_variants`. + type_spec: The `TypeSpec` of the original value. This is used to determine + the number and types of the component tensors that comprise the decoded + value. Must be compatible with the `TypeSpec` serilized in `encoded`. + name: Optional name for the operation. + + Returns: + An `ExtensionType` value that is compatible with `TypeSpec`. + + Raises: + TypeError: If `encoded` is not a Tensor with dtype=variant. + InvalidArgumentError: If `encoded` is not compatible with `type_spec`. + """ + if not isinstance(encoded, tensor.Tensor): + raise TypeError(f"Expected `encoded` to be a Tensor, got {encoded!r}.") + if encoded.dtype != dtypes.variant: + raise TypeError("Expected `encoded` to have dtype=variant, got " + f"{encoded!r}.") + encoded.shape.assert_is_compatible_with(()) + + metadata = composite_tensor_variant_pb2.CompositeTensorVariantMetadata() + metadata.type_spec_proto.CopyFrom( + nested_structure_coder.encode_structure(type_spec).type_spec_value) + + component_dtypes = [ + t.dtype for t in nest.flatten(type_spec, expand_composites=True) + ] + + components = gen_composite_tensor_ops.CompositeTensorVariantToComponents( + encoded=encoded, + metadata=metadata.SerializeToString(), + Tcomponents=component_dtypes, + name=name) + return nest.pack_sequence_as(type_spec, components, expand_composites=True) + + +@ops.RegisterGradient("CompositeTensorVariantFromComponents") +def _composite_tensor_to_variants_grad(op, grad): + return gen_composite_tensor_ops.CompositeTensorVariantToComponents( + encoded=grad, + metadata=op.get_attr("metadata"), + Tcomponents=op.get_attr("Tcomponents")) + + +@ops.RegisterGradient("CompositeTensorVariantToComponents") +def _composite_tensor_from_variant_grad(op, *grad): + assert len(grad) == len(op.outputs) + # `components` is `op.outputs`, but with any tensors for which we're + # taking the gradient replaced by the corresponding value from `grad`. + components = [ + op.outputs[i] if grad[i] is None else grad[i] for i in range(len(grad)) + ] + return gen_composite_tensor_ops.CompositeTensorVariantFromComponents( + components=components, metadata=op.get_attr("metadata")) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond.py new file mode 100644 index 0000000000000000000000000000000000000000..23940e23847693a64e220c25419e0260f2979658 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond.py @@ -0,0 +1,409 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Cond function for Control Flow Operations.""" + +from tensorflow.python.eager import context +from tensorflow.python.eager.polymorphic_function import eager_function_run +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond_v2 +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util as util +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import core +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=redefined-outer-name +# pylint: disable=g-doc-args +@tf_export(v1=["cond"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args( + None, "fn1/fn2 are deprecated in favor of the true_fn/false_fn arguments.", + "fn1", "fn2") +def cond(pred, + true_fn=None, + false_fn=None, + strict=False, + name=None, + fn1=None, + fn2=None): + """Return `true_fn()` if the predicate `pred` is true else `false_fn()`. + + `true_fn` and `false_fn` both return lists of output tensors. `true_fn` and + `false_fn` must have the same non-zero number and type of outputs. + + **WARNING**: Any Tensors or Operations created outside of `true_fn` and + `false_fn` will be executed regardless of which branch is selected at runtime. + + Although this behavior is consistent with the dataflow model of TensorFlow, + it has frequently surprised users who expected a lazier semantics. + Consider the following simple program: + + ```python + z = tf.multiply(a, b) + result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y)) + ``` + + If `x < y`, the `tf.add` operation will be executed and `tf.square` + operation will not be executed. Since `z` is needed for at least one + branch of the `cond`, the `tf.multiply` operation is always executed, + unconditionally. + + Note that `cond` calls `true_fn` and `false_fn` *exactly once* (inside the + call to `cond`, and not at all during `Session.run()`). `cond` + stitches together the graph fragments created during the `true_fn` and + `false_fn` calls with some additional graph nodes to ensure that the right + branch gets executed depending on the value of `pred`. + + `tf.cond` supports nested structures as implemented in + `tensorflow.python.util.nest`. Both `true_fn` and `false_fn` must return the + same (possibly nested) value structure of lists, tuples, and/or named tuples. + Singleton lists and tuples form the only exceptions to this: when returned by + `true_fn` and/or `false_fn`, they are implicitly unpacked to single values. + This behavior is disabled by passing `strict=True`. + + Args: + pred: A scalar determining whether to return the result of `true_fn` or + `false_fn`. + true_fn: The callable to be performed if pred is true. + false_fn: The callable to be performed if pred is false. + strict: A boolean that enables/disables 'strict' mode; see above. + name: Optional name prefix for the returned tensors. + + Returns: + Tensors returned by the call to either `true_fn` or `false_fn`. If the + callables return a singleton list, the element is extracted from the list. + + Raises: + TypeError: if `true_fn` or `false_fn` is not callable. + ValueError: if `true_fn` and `false_fn` do not return the same number of + tensors, or return tensors of different types. + + Example: + + ```python + x = tf.constant(2) + y = tf.constant(5) + def f1(): return tf.multiply(x, 17) + def f2(): return tf.add(y, 23) + r = tf.cond(tf.less(x, y), f1, f2) + # r is set to f1(). + # Operations in f2 (e.g., tf.add) are not executed. + ``` + + """ + # We needed to make true_fn/false_fn keyword arguments for + # backwards-compatibility. This check exists so that we can convert back to + # having them be positional arguments. + # TODO(josh11b): Make `true_fn` and `false_fn` positional arguments after + # `fn1` and `fn2` are deleted. + if fn1 is not None: + if true_fn is not None: + raise TypeError( + "cond(): 'true_fn' and 'fn1' may not be set simultaneously.") + true_fn = fn1 + elif true_fn is None: + raise TypeError("cond(): 'true_fn' argument required") + if fn2 is not None: + if false_fn is not None: + raise TypeError( + "cond(): 'false_fn' and 'fn2' may not be set simultaneously.") + false_fn = fn2 + elif false_fn is None: + raise TypeError("cond(): 'false_fn' argument required") + + if not callable(true_fn): + raise TypeError("'true_fn' must be callable.") + if not callable(false_fn): + raise TypeError("'false_fn' must be callable.") + + if context.executing_eagerly(): + return _eager_cond_implementation(pred, true_fn, false_fn, strict, name) + + # Always enable control flow v2 if building a function, regardless of toggle. + if util.EnableControlFlowV2(ops.get_default_graph()): + return cond_v2.cond_v2(pred, true_fn, false_fn, name) + + with ops.name_scope(name, "cond", [pred]): + # Add the Switch to the graph. + if isinstance(pred, bool): + raise TypeError("'pred' must not be a Python bool.") + p_2, p_1 = control_flow_ops.switch(pred, pred) + pivot_1 = array_ops.identity(p_1, name="switch_t") + pivot_2 = array_ops.identity(p_2, name="switch_f") + pred = array_ops.identity(pred, name="pred_id") + # Disable the fetching of tensors that are only on one branch of cond. + for tensor in [p_1, p_2, pivot_1, pivot_2, pred]: + tensor.op.graph.prevent_fetching(tensor.op) + + # Build the graph for the true branch in a new context. + context_t = control_flow_ops.CondContext(pred, pivot_1, branch=1) + try: + context_t.Enter() + orig_res_t, res_t = context_t.BuildCondBranch(true_fn) + if orig_res_t is None: + raise ValueError("'true_fn' must have a return value.") + context_t.ExitResult(res_t) + finally: + context_t.Exit() + + # Build the graph for the false branch in a new context. + context_f = control_flow_ops.CondContext(pred, pivot_2, branch=0) + try: + context_f.Enter() + orig_res_f, res_f = context_f.BuildCondBranch(false_fn) + if orig_res_f is None: + raise ValueError("'false_fn' must have a return value.") + context_f.ExitResult(res_f) + finally: + context_f.Exit() + + if not strict: + orig_res_t = _UnpackIfSingleton(orig_res_t) + orig_res_f = _UnpackIfSingleton(orig_res_f) + + # Check that the return values of the two branches have the same structure. + try: + nest.assert_same_structure(orig_res_t, orig_res_f, expand_composites=True) + except (TypeError, ValueError): + nest.map_structure(_cast_indexed_slice_indices, orig_res_t, orig_res_f) + nest.map_structure(_cast_indexed_slice_indices, res_t, res_f) + try: + nest.assert_same_structure(orig_res_t, orig_res_f, + expand_composites=True) + except TypeError as e: + raise TypeError( + f"Incompatible return types of 'true_fn' and 'false_fn': {e}") + except ValueError as e: + raise ValueError( + f"Incompatible return values of 'true_fn' and 'false_fn': {e}") + + # Add the final merge to the graph. + if not res_t: + raise ValueError( + "'true_fn' and 'false_fn' must return at least one result.") + + res_t_flat = nest.flatten(res_t, expand_composites=True) + res_f_flat = nest.flatten(res_f, expand_composites=True) + + for (x, y) in zip(res_t_flat, res_f_flat): + assert ( + isinstance(x, tensor_lib.Tensor) + and isinstance(y, tensor_lib.Tensor)) + if x.dtype.base_dtype != y.dtype.base_dtype: + raise ValueError( + "Outputs of 'true_fn' and 'false_fn' must have the same type(s). " + f"Received {x.dtype.name} from 'true_fn' " + f"and {y.dtype.name} from 'false_fn'.") + + merges = [ + control_flow_ops.merge(pair)[0] for pair in zip(res_f_flat, res_t_flat)] + merges = nest.map_structure( + control_flow_ops._convert_flow_to_tensorarray, # pylint: disable=protected-access + nest.flatten(orig_res_t, expand_composites=True), + merges) + + # Only add non-nested conds to the collection. Any nested control flow will + # be encapsulated in the root context. + assert context_t.outer_context == context_f.outer_context + if context_t.outer_context is None: + ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_t) + ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_f) + + merges = nest.pack_sequence_as( + structure=orig_res_t, flat_sequence=merges, expand_composites=True) + + # Singleton lists and tuples are automatically unpacked if strict == False. + if not strict: + merges = _UnpackIfSingleton(merges) + return merges + + +@tf_export("cond", v1=[]) +@dispatch.add_dispatch_support +def cond_for_tf_v2(pred, true_fn=None, false_fn=None, name=None): + """Return `true_fn()` if the predicate `pred` is true else `false_fn()`. + + Note: This op is automatically used in a `tf.function` to convert Python + if-statements when the predicate is a `tf.Tensor`, unless `autograph=False` is + explicitly specified in `tf.function` args. For example, the following are + equivalent: + + >>> @tf.function + ... def fun1(x,y): + ... if x > 0: # AutoGraph converts if-statement to tf.cond(). + ... z = y+1 + ... else: + ... z = y-1 + ... return z + >>> fun1(tf.constant(7), tf.constant(3)).numpy() + 4 + + >>> @tf.function + ... def fun2(x,y): + ... pred = x > 0 + ... true_fn = lambda: y+1 + ... false_fn = lambda: y-1 + ... return tf.cond(pred, true_fn, false_fn) # Use tf.cond() explicitly. + >>> fun1(tf.constant(7), tf.constant(3)).numpy() + 4 + + For more information, see [tf.function and AutoGraph guide]( + https://www.tensorflow.org/guide/function#autograph_transformations). + + `true_fn` and `false_fn` both return lists of output tensors. `true_fn` and + `false_fn` must have the same non-zero number and type of outputs. + + **WARNING**: Any Tensors or Operations created outside of `true_fn` and + `false_fn` will be executed regardless of which branch is selected at runtime. + + Although this behavior is consistent with the dataflow model of TensorFlow, + it has frequently surprised users who expected a lazier semantics. + Consider the following simple program: + + >>> x, y = tf.constant(2, dtype=tf.int32), tf.constant(4, dtype=tf.int32) + >>> z = tf.multiply(x, y) + >>> r = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y)) + >>> r.numpy() + 10 + + If `x < y`, the `tf.add` operation will be executed and `tf.square` + operation will not be executed. Since `z` is needed for at least one + branch of the `cond`, the `tf.multiply` operation is always executed, + unconditionally. + + Note that `cond` calls `true_fn` and `false_fn` *exactly once* (inside the + call to `cond`, and not at all during `Session.run()`). `cond` + stitches together the graph fragments created during the `true_fn` and + `false_fn` calls with some additional graph nodes to ensure that the right + branch gets executed depending on the value of `pred`. + + `tf.cond` supports nested structures as implemented in + `tensorflow.python.util.nest`. Both `true_fn` and `false_fn` must return the + same (possibly nested) value structure of lists, tuples, and/or named tuples. + Singleton lists and tuples form the only exceptions to this: when returned by + `true_fn` and/or `false_fn`, they are implicitly unpacked to single values. + + Note: It is illegal to "directly" use tensors created inside a cond branch + outside it, e.g. by storing a reference to a branch tensor in the python + state. If you need to use a tensor created in a branch function you should + return it as an output of the branch function and use the output from + `tf.cond` instead. + + Args: + pred: A scalar determining whether to return the result of `true_fn` or + `false_fn`. + true_fn: The callable to be performed if pred is true. + false_fn: The callable to be performed if pred is false. + name: Optional name prefix for the returned tensors. + + Returns: + Tensors returned by the call to either `true_fn` or `false_fn`. If the + callables return a singleton list, the element is extracted from the list. + + Raises: + TypeError: if `true_fn` or `false_fn` is not callable. + ValueError: if `true_fn` and `false_fn` do not return the same number of + tensors, or return tensors of different types. + + Example: + + >>> x = tf.constant(2) + >>> y = tf.constant(5) + >>> def f1(): return tf.multiply(x, 7) + >>> def f2(): return tf.add(y, 3) + >>> r = tf.cond(tf.less(x, y), f1, f2) + >>> # r is set to f1(). + >>> # Operations in f2 (e.g., tf.add) are not executed. + >>> r.numpy() + 14 + + """ + return cond(pred, true_fn=true_fn, false_fn=false_fn, strict=True, name=name) + + +def _UnpackIfSingleton(res): + if isinstance(res, (list, tuple)) and len(res) == 1: + return res[0] + else: + return res + + +def _eager_cond_implementation(pred, true_fn, false_fn, strict, name): + """Special cases for `cond` when executing eagerly.""" + pred = ops.convert_to_tensor(pred) + pred_constant_value = tensor_util.constant_value(pred) + if pred_constant_value is None: + # Eager tensors from a parallel device may not have a constant + # value. Running the cond op itself would work, but we don't have logic to + # build cond ops without wrapping in a function first. + if (not isinstance(true_fn, core.PolymorphicFunction) + or not isinstance(false_fn, core.PolymorphicFunction)): + raise TypeError("When running tf.cond on a parallel device, 'true_fn' " + "and 'false_fn' must be decorated with `tf.function`.") + functions_run_eagerly = eager_function_run.functions_run_eagerly() + if functions_run_eagerly: + # We need to use tf.function to deal with variable creation inside the + # cond, and skipping it because of run_functions_eagerly would just + # crash immediately. + logging.warning( + "It looks like tf.function behavior was disabled, perhaps using " + "tf.config.run_functions_eagerly. Parallelized tf.cond requires " + "tf.function to work. This primitive will override the disable.") + eager_function_run.run_functions_eagerly(False) + try: + return cond_v2.cond_v2(pred, true_fn, false_fn, name) + finally: + if functions_run_eagerly is not None: + eager_function_run.run_functions_eagerly(functions_run_eagerly) + else: + # For conditions which are eager tensors with a constant value (most of + # them), we only call the relevant branch function and execute it eagerly. + with ops.name_scope(name, "cond", [pred]): + if pred_constant_value: + result = true_fn() + else: + result = false_fn() + if not strict: + result = _UnpackIfSingleton(result) + return result + + +def _cast_indexed_slice_indices(a, b): + """Cast IndexedSlice.indices from int32 to int64 where necessary. + + If `a` and `b` are both IndexedSlices, and their indices have different + dtypes, then cast both their dtypes to `int64` (modifies `a` and `b` + in-place). Otherwise, does nothing. + + Args: + a: A value, which may be an IndexedSlices. + b: A value, which may be an IndexedSlices. + """ + if (isinstance(a, indexed_slices.IndexedSlices) and + isinstance(b, indexed_slices.IndexedSlices) and + a.indices.dtype != b.indices.dtype): + # pylint: disable=protected-access + a._indices = math_ops.cast(a.indices, dtypes.int64) + b._indices = math_ops.cast(b.indices, dtypes.int64) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..27f57869511514a0ca1c3ea18c1887c14da3ceb1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cond_v2.py @@ -0,0 +1,1329 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""cond_v2 and gradient. + +This is a version of cond that emits a single If op, as well as the gradient +function for If ops produced by cond_v2. This will eventually replace the +current tf.cond implementation once it reaches feature and performance parity. +""" + +import collections + +from tensorflow.core.framework import types_pb2 +from tensorflow.python.eager import backprop_util +from tensorflow.python.framework import auto_control_deps +from tensorflow.python.framework import auto_control_deps_utils as acd +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import none_tensor # pylint: disable=unused-import +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import control_flow_util_v2 as util +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import gen_optional_ops +from tensorflow.python.ops import gradients_util +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest + + +# NOTE(skyewm): TensorFlow uses protected class methods and fields to signify +# that they aren't part of the official public API. These protected members +# often need to be used by implementation code however. Rather than litter the +# code with pylint comments, we ignore protected access violations for +# readability. +# pylint: disable=protected-access + +_COND = 1 +_CASE = 2 + + +def cond_v2(pred, true_fn, false_fn, name="cond"): + """Like tf.cond, except emits a single If op.""" + if isinstance(pred, bool): + raise TypeError("pred must not be a Python bool", pred) + + if not name: + name = "cond" + + with ops.name_scope(name) as scope: + true_name = util.unique_fn_name(scope, "true") + false_name = util.unique_fn_name(scope, "false") + + # Automatic control dependencies are added in defuns, but not in v1 + # graphs. Propagate that behavior here. + add_control_dependencies = ops.get_default_graph()._add_control_dependencies + pred = ops.convert_to_tensor(pred) + if (tensor_util.is_tf_type(pred) and + (pred.shape.dims is None or pred.shape.dims)): + pred = array_ops.squeeze_v2(pred) + + true_graph = func_graph_module.func_graph_from_py_func( + true_name, + true_fn, [], {}, + func_graph=util.CondBranchFuncGraph( + true_name, collections=ops.get_default_graph()._collections), # pylint: disable=protected-access + add_control_dependencies=add_control_dependencies, + op_return_value=pred) + false_graph = func_graph_module.func_graph_from_py_func( + false_name, + false_fn, [], {}, + func_graph=util.CondBranchFuncGraph( + false_name, collections=ops.get_default_graph()._collections), # pylint: disable=protected-access + add_control_dependencies=add_control_dependencies, + op_return_value=pred) + + verify_captures(_COND, [true_graph, false_graph]) + return _build_cond( + pred, + true_graph, + false_graph, + true_graph.external_captures, + false_graph.external_captures, + building_gradient=False, + name=scope) + + +@ops.RegisterGradient("StatelessIf") +@ops.RegisterGradient("If") +def _IfGrad(op, *grads): # pylint: disable=invalid-name + """The gradient of an If op produced by cond_v2.""" + # Get the if operator (this logic handles the case where op is a MockOp) + if_op = op.outputs[0].op + true_graph, false_graph = get_func_graphs(if_op) + # Note: op.graph != ops.get_default_graph() when we are computing the gradient + # of a nested cond. + assert true_graph.outer_graph == if_op.graph + assert false_graph.outer_graph == if_op.graph + + # Create grad functions that compute the gradient of the true/false forward + # graphs. These functions will capture tensors from the forward pass + # functions. + true_grad_graph = _create_grad_func( + true_graph, grads, util.unique_grad_fn_name(true_graph.name)) + false_grad_graph = _create_grad_func( + false_graph, grads, util.unique_grad_fn_name(false_graph.name)) + + # Replaces output None grads with zeros if at least one branch has non-None + # grad at that index. + _create_zeros_for_none_grads([true_graph, false_graph], + [true_grad_graph, false_grad_graph]) + + if (true_grad_graph.op_needs_rewrite or false_grad_graph.op_needs_rewrite): + # Modify 'op' to output the intermediates needed by the grad functions. Note + # that all needed intermediates are wrapped in optionals. Each optional + # intermediate output will have a value iff its corresponding branch is + # taken. + # NOTE(skyewm): if there are any active sessions, this modification to `op` + # may make them unrunnable! + + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + # XLA does not yet support optionals, so output intermediates directly and + # make them match via FakeParams, which can be converted to zeros in XLA. + # TODO(skyewm,jpienaar): can XLA support optionals? + true_intermediates = true_grad_graph.xla_intermediates + false_intermediates = false_grad_graph.xla_intermediates + extra_true_outputs, extra_false_outputs = _make_intermediates_match_xla( + [true_graph, false_graph], [true_intermediates, false_intermediates]) + else: + true_intermediates = true_grad_graph.wrapped_intermediates + false_intermediates = false_grad_graph.wrapped_intermediates + # Make outputs match by adding none optionals. + extra_true_outputs, extra_false_outputs = _make_intermediates_match( + [true_graph, false_graph], [true_intermediates, false_intermediates]) + + true_graph.outputs.extend(extra_true_outputs) + false_graph.outputs.extend(extra_false_outputs) + # TODO(skyewm): indicate it's an internal bug if this fails. + _check_same_outputs(_COND, [true_graph, false_graph]) + + true_graph.name += "_rewritten" + false_graph.name += "_rewritten" + + if_op._set_func_attr("then_branch", util.create_new_tf_function(true_graph)) + if_op._set_func_attr("else_branch", + util.create_new_tf_function(false_graph)) + if_op._set_type_list_attr("Tout", true_graph.output_types) + if_op._set_shape_list_attr("output_shapes", true_graph.output_shapes) + if_op._add_outputs( + [t.dtype for t in extra_true_outputs], + [t.shape for t in extra_true_outputs]) + + # Resolve references to forward graph tensors in grad graphs and ensure + # they are in-scope, i.e., belong to one of outer graphs of the grad graph. + true_grad_inputs = _resolve_grad_inputs(true_graph, true_grad_graph) + false_grad_inputs = _resolve_grad_inputs(false_graph, false_grad_graph) + + # This modifies true_grad_graph and false_grad_graph. + _make_output_composite_tensors_match(_COND, + [true_grad_graph, false_grad_graph]) + + outputs = _build_cond( + if_op.inputs[0], + true_grad_graph, + false_grad_graph, + true_grad_inputs, + false_grad_inputs, + building_gradient=True, + ) + + # The predicate has no gradient. + return [None] + outputs + + +def _is_op_stateful(op): + """Check whether an op is stateful. + + This helper function handles two special cases to make the stateful analysis + consistent with the mlir side effect analysis. + 1. GlobalIterIdOp should be stateless. + 2. CollectiveGatherV2 with attribute is_stateless to be True should be + stateless. + + Args: + op: Operation + + Returns: + Boolean indicates whether the operation is stateless or not. + """ + if op.type == "GlobalIterId": + return False + if op.type == "CollectiveGatherV2" and op.get_attr("is_stateless"): + return False + return op._is_stateful + + +def _build_cond(pred, + true_graph, + false_graph, + true_inputs, + false_inputs, + building_gradient, + name=None): + """Creates an If op from the specified predicate, branch functions and inputs. + + Note that this modifies true_graph and false_graph to make the inputs match, + and to output all intermediates values so they're available for the gradient + computation. + + true_graph and false_graph need not have the same input types, but they must + have the same output types. + + Args: + pred: boolean Tensor + true_graph: FuncGraph + false_graph: FuncGraph + true_inputs: a list of Tensors to be passed to true_graph as input. + false_inputs: a list of Tensors to be passed to false_graph as input. + building_gradient: Whether this is a gradient If op. + name: the name for the If op. + + Returns: + A list of Tensors which are the outputs of the If op. Does not include added + intermediate outputs. + """ + _make_indexed_slices_indices_types_match(_COND, [true_graph, false_graph]) + _check_same_outputs(_COND, [true_graph, false_graph]) + + # Add inputs to true_graph and false_graph to make them match. Note that + # this modifies true_graph and false_graph. + cond_inputs = _make_inputs_match([true_graph, false_graph], + [true_inputs, false_inputs]) + # We do not output intermediates of the gradient If op since this is just + # for backwards compatibility with existing code. + if not building_gradient and util.output_all_intermediates(): + # Add all intermediate tensors as function outputs so they're available for + # the gradient computation. Since the outputs of the two functions must + # match, we wrap all the intermediates in optionals. Each intermediate + # output will have a value iff its corresponding branch is taken. + + true_intermediates = _get_intermediates(true_graph) + false_intermediates = _get_intermediates(false_graph) + + # Wrap intermediates in optionals. + wrapped_true_intermediates = _wrap_intermediates(true_graph, + true_intermediates) + wrapped_false_intermediates = _wrap_intermediates(false_graph, + false_intermediates) + + # Make outputs match by adding none optionals. + extra_true_outputs, extra_false_outputs = _make_intermediates_match( # pylint: disable=unbalanced-tuple-unpacking + [true_graph, false_graph], + [wrapped_true_intermediates, wrapped_false_intermediates]) + + true_graph.outputs.extend(extra_true_outputs) + false_graph.outputs.extend(extra_false_outputs) + _check_same_outputs(_COND, [true_graph, false_graph]) + + # Create the If op. + with ops.control_dependencies( + list(true_graph.function_captures.control) + list( + false_graph.function_captures.control)): + true_stateful_ops = [ + op + for op in true_graph.get_operations() + if _is_op_stateful(op) + ] + false_stateful_ops = [ + op + for op in false_graph.get_operations() + if _is_op_stateful(op) + ] + if (true_stateful_ops or false_stateful_ops): + op_fn = gen_functional_ops._if + else: + op_fn = gen_functional_ops.stateless_if + + def _make_op(inputs): + if_op, tensors = util.get_op_and_outputs(op_fn( + pred, + inputs, [t.dtype for t in true_graph.outputs], + util.create_new_tf_function(true_graph), + util.create_new_tf_function(false_graph), + output_shapes=_get_output_shapes(true_graph.outputs, + false_graph.outputs), + name=name)) + _copy_handle_data(tensors, true_graph.outputs, false_graph.outputs) + # `if_op` is None if this is a `StatelessIf` op with no outputs. + if if_op is not None: + # The true and false graphs have already been created, and we need that + # to happen before we know which tensors will be captured and so whether + # to wrap the cond in a tf.function. Post-hoc mutation of the branch + # `outer_graph` properties seems like the only option if we want to + # conditionally wrap in a function. + true_graph.outer_graph = ops.get_default_graph() + false_graph.outer_graph = ops.get_default_graph() + if_op._true_graph = true_graph + if_op._false_graph = false_graph + util.maybe_set_lowering_attr(if_op) + util.maybe_propagate_compile_time_consts_in_xla(if_op) + _set_read_only_resource_inputs_attr(if_op, [true_graph, false_graph]) + # Prevent fetching since the variant outputs can't be fetched directly. + if_op.graph.prevent_fetching(if_op) + return tensors + tensors = util.run_as_function_for_tape_gradients(_make_op, cond_inputs) + + # Return identities for each output of the If op, rather than the output of + # the If op directly. This makes pruning work if the output of cond() is + # fetched: the lowering pass converts the If outputs into IdentityN outputs, + # which if fetched will cause all ops in the taken branch to be run (since + # it takes all merge ops as input). After lowering, each output identity op + # will end up with only the appropriate merge op as input. + # TODO(b/79984175): this doesn't have to be a tuple once we covert to the + # correct output structure + tensors = [array_ops.identity(t) for t in tensors] + + structured_output_specs = _get_compatible_structured_output_specs(true_graph, + false_graph) + return _pack_sequence_as(structured_output_specs, tensors) + + +def get_func_graphs(op): + """Returns `FuncGraph`s for the input op branches. + + Args: + op: The If or Case Operation. + + Returns: + A tuple of the `FuncGraph`s of the then_branch and else_branch (all branches + for Case). + """ + + def _get_func_graph_for_branch(name_attr_list, cached_attr_name=None): + """Generates and returns a FuncGraph for the given branch.""" + func_graph = None + if cached_attr_name is not None: + func_graph = getattr(op, cached_attr_name, None) + inputs = op.inputs[1:] # First input is pred. + if func_graph is None: + input_shapes = [t.shape for t in inputs] + func_graph = util.get_func_graph(op, input_shapes, name_attr_list.name) + for external_t, internal_t in zip(inputs, func_graph.inputs): + handle_data_util.copy_handle_data(external_t, internal_t) + func_graph.function_captures.reset_captures(inputs, func_graph.inputs) + # Link the op so that the gradient code can use it. + func_graph._forward_cond = op + return func_graph + + if op.type in ["If", "StatelessIf"]: + return (_get_func_graph_for_branch( + op.get_attr("then_branch"), "_true_graph"), + _get_func_graph_for_branch( + op.get_attr("else_branch"), "_false_graph")) + elif op.type in ["Case", "StatelessCase"]: + return [_get_func_graph_for_branch(branch_fn, "_branch_graph_{}".format(i)) + for i, branch_fn in enumerate(op.get_attr("branches"))] + else: + raise ValueError("Unsupported op type: {}".format(op.type)) + + +def _get_compatible_structured_output_specs(true_graph, false_graph): + """Returns the most specific compatible specs of graph structured outputs.""" + return nest.map_structure(_get_compatible_spec, + true_graph.structured_outputs, + false_graph.structured_outputs) + + +def _get_compatible_spec(value_or_spec1, value_or_spec2): + """Returns the most specific compatible spec. + + Args: + value_or_spec1: A TypeSpecs or a value that has a defined TypeSpec. + value_or_spec2: A TypeSpecs or a value that has a defined TypeSpec. + + Returns: + The most specific compatible TypeSpecs of the input. + + Raises: + ValueError: If value_or_spec1 is not compatible with value_or_spec2. + """ + spec1 = _get_spec_for(value_or_spec1) + spec2 = _get_spec_for(value_or_spec2) + + # pylint: disable=protected-access + common = spec1._without_tensor_names().most_specific_common_supertype( + [spec2._without_tensor_names()]) + if common is None: + raise TypeError(f"No common supertype of {spec1} and {spec2}.") + return common + + +def _get_spec_for(value_or_spec): + """Returns TypeSpec of a value or itself if it is a TypeSpec already.""" + if isinstance(value_or_spec, type_spec.TypeSpec): + return value_or_spec + return type_spec.type_spec_from_value(value_or_spec) + + +def _grad_fn(func_graph, grads): + """The gradient function for each conditional branch. + + This function builds the gradient graph of the corresponding forward-pass + conditional branch in `func_graph`. This is done by differentiating + func_graph's outputs w.r.t. its inputs. + + Args: + func_graph: FuncGraph. The corresponding forward-pass function. + grads: The list of input gradient Tensors. + + Returns: + The output gradient Tensors. + """ + # Filter out untrainable function outputs. + # NOTE(skyewm): If we don't do this, the untrainable tensors can sometimes + # cause _GradientsHelper to raise an exception (e.g. the implementation + # doesn't expect 'ys' to contain boolean tensors). + assert len(func_graph.outputs) == len(grads) + ys = [] + grad_ys = [] + for y, grad_y in zip(func_graph.outputs, grads): + if not backprop_util.IsTrainable(y): + continue + ys.append(y) + grad_ys.append(grad_y) + + # Build the gradient graph. Note that this builds the gradient computation of + # func_graph in the current graph, which requires capturing tensors from + # func_graph. The captured func_graph tensors are resolved to external tensors + # in _resolve_grad_inputs. + result = gradients_util._GradientsHelper( + ys, func_graph.inputs, grad_ys=grad_ys, + src_graph=func_graph) + + return result + + +def _create_grad_func(func_graph, grads, name): + """Returns the FuncGraph representation of _grad_fn.""" + return func_graph_module.func_graph_from_py_func( + name, + lambda: _grad_fn(func_graph, grads), [], {}, + func_graph=_CondGradFuncGraph(name, func_graph)) + + +def _resolve_grad_inputs(cond_graph, grad_graph): + """Returns the tensors to pass as inputs to `grad_graph`. + + The `grad_graph` may have external references to + 1. Its outer graph containing the input gradients. These references are kept + as is. + 2. Tensors in the forward pass graph. These tensors may not be "live" + when the gradient is being computed. We replace such references by their + corresponding tensor in `cond_graph.outer_graph`. In the case of nested + control flow or functions, the gradient logic handling + `grad_graph.outer_graph` will make sure the tensor from + `cond_graph.outer_graph` is also correctly captured. + + Args: + cond_graph: FuncGraph. The forward-pass function. + grad_graph: FuncGraph. The gradients function. + + Returns: + A list of inputs tensors to be passed to grad_graph. + """ + new_inputs = [] + + for t in grad_graph.external_captures: + # `t` must either be in `grad_graph.outer_graph` or in the forward + # `cond_graph`. + if t.graph != grad_graph.outer_graph: + assert t.graph == cond_graph + # `internal_captures` are not treated as intermediates and hence not added + # to If op outputs. So we get the outer tensor corresponding to those + # from the list of `external_captures`. + for i, output in enumerate(t.graph.outputs): + if output is t: + t = t.graph._forward_cond.outputs[i] + break + else: + for i, output in enumerate(t.graph.internal_captures): + if output is t: + t = t.graph.external_captures[i] + break + else: + raise ValueError("Could not find external tensor capture {tensor} in " + "captures or outputs".format(tensor=t)) + + # Note: We rely on the capturing logic of the gradient If op graph to + # correctly capture the tensors in `cond_graph.outer_graph`. Both cond_v2 + # and while_v2 handle this while building their gradient functions. + assert t.graph == cond_graph.outer_graph + new_inputs.append(t) + + return new_inputs + + +def _get_intermediates(func_graph): + """Returns intermediate tensors of `func_graph` for gradient computation.""" + intermediates = [] + for op in func_graph.get_operations(): + for t in op.outputs: + if t in func_graph.inputs: continue + if t in func_graph.outputs: continue + if t.dtype is dtypes.resource: + continue + # Accumulating mutexes can cause deadlock. + if op.type == "MutexLock": + continue + intermediates.append(t) + return intermediates + + +def _make_intermediates_match(branch_graphs, branch_optionals): + """Returns new optionals lists that have matching signatures. + + This is done by mirroring each list in the other using none optionals. + There is no merging of like optionals. + + Args: + branch_graphs: `list` of `FuncGraph`. + branch_optionals: `list` of `list`s of optional `Tensor`s from other + branch_graphs + + Returns: + A `list` of `list`s of `Tensor`s for each branch_graph. Each list has the + same number of `Tensor`s, all of which will be optionals of the same + shape/type. + """ + new_branch_optionals = [] + # Since the intermediates are optionals with dtype variant, we only need + # enough room for the longest list of intermediates. + intermediates_size = max(len(o) for o in branch_optionals) + for i, branch_graph in enumerate(branch_graphs): + other_optionals = _create_none_optionals( + branch_graph, intermediates_size - len(branch_optionals[i])) + new_branch_optionals.append(branch_optionals[i] + other_optionals) + return new_branch_optionals + + +def _make_intermediates_match_xla(branch_graphs, branch_intermediates): + """Like _make_intermediates_match but for the XLA case.""" + new_branch_intermediates = [] + for i, branch_graph in enumerate(branch_graphs): + other_fakeparams = _create_fakeparams( + branch_graph, + sum((bi for bi in branch_intermediates + if bi is not branch_intermediates[i]), [])) + num_preceding = sum(len(bi) for bi in branch_intermediates[:i]) + new_branch_intermediates.append(other_fakeparams[:num_preceding] + + branch_intermediates[i] + + other_fakeparams[num_preceding:]) + return new_branch_intermediates + + +def _make_inputs_match(branch_graphs, branch_inputs): + """Modifies branch_graphs so they have the same input signature. + + This method reorders and/or adds parameters to each graph in branch_graphs so + they have the same input signature, and updates the 'inputs' and 'captured' + fields of each graph accordingly. It uses the input tensors from the outer + graph to avoid duplicating shared arguments. + + Args: + branch_graphs: a `list` of `FuncGraph` + branch_inputs: a `list` of `list`s of `Tensor`s in the outer graph. The + inputs for the corresponding graph in `branch_graphs`. + + Returns: + A new list of Tensors from the outer graph that are the new inputs for each + branch_graph. This is a deduped version of `sum(branch_inputs)`. + """ + assert len(branch_graphs) == len(branch_inputs) + added_inputs = set() + new_inputs = [] + for branch_in in branch_inputs: + for tensor in branch_in: + tensor_id = ops.tensor_id(tensor) + if tensor_id not in added_inputs: + added_inputs.add(tensor_id) + new_inputs.append(tensor) + + for branch_graph, branch_in in zip(branch_graphs, branch_inputs): + input_ids = [ops.tensor_id(t) for t in branch_in] + branch_input_to_param = dict(zip(input_ids, branch_graph.inputs)) + input_list = [] + for in_t in new_inputs: + param = branch_input_to_param.get(ops.tensor_id(in_t)) + if param is None: + param = _create_dummy_input(branch_graph, in_t) + input_list.append(param) + + branch_graph.inputs = input_list + + # Rewrite the FuncGraphs' state to reflect the new inputs. + branch_graph.function_captures.reset_captures( + new_inputs, branch_graph.inputs) + + return new_inputs + + +def _create_zeros_for_none_grads(forward_graphs, grad_graphs): + """Creates zeros for None out grads if at least one branch has non-None grad. + + Args: + forward_graphs: List of forward FuncGraphs. + grad_graphs: List of grad FuncGraphs. + """ + assert len(forward_graphs) == len(grad_graphs) + branch_outputs = [g.structured_outputs for g in grad_graphs] + num_outputs_per_branch = [len(outs) for outs in branch_outputs] + assert len(set(num_outputs_per_branch)) == 1, num_outputs_per_branch + for output_idx, branch_outs in enumerate(zip(*branch_outputs)): + if (any(t is None for t in branch_outs) and + any(t is not None for t in branch_outs)): + for branch_index, t in enumerate(branch_outs): + if t is None: + with grad_graphs[branch_index].as_default(): + zeros = default_gradient.zeros_like( + forward_graphs[branch_index].inputs[output_idx]) + grad_graphs[branch_index].structured_outputs[output_idx] = zeros + + for grad_graph in grad_graphs: + grad_graph.outputs = [ + t for t in func_graph_module.flatten(grad_graph.structured_outputs) + if t is not None + ] + + +def _make_output_composite_tensors_match(op_type, branch_graphs): + """Modifies each branch_graph's outputs to have the same output signature. + + Currently the only transformation implemented is turning a Tensor into an + equivalent IndexedSlices if the other branch returns an IndexedSlices. + Updates branch_graph.{outputs,structured_outputs} for each branch_graph in + branch_graphs. + + Args: + op_type: _COND or _CASE + branch_graphs: `list` of `FuncGraph` + + Raises: + TypeError: if a set of outputs cannot be rewritten. + """ + # Note: since this is only used for gradient graphs, we do not expect the + # outputs to be structured (e.g. nested lists), and thus do not need to use + # nest.flatten, etc. + assert branch_graphs + branch_outputs = [g.structured_outputs for g in branch_graphs] + outputs_per_branch = list(len(outs) for outs in branch_outputs) + assert len(set(outputs_per_branch)) == 1, outputs_per_branch + + for output_idx, branch_outs in enumerate(zip(*branch_outputs)): + if len(set(type(out) for out in branch_outs)) == 1: + continue + if not any( + isinstance(out, indexed_slices.IndexedSlices) for out in branch_outs): + continue + for branch_idx, branch_out in enumerate(branch_outs): + if isinstance(branch_out, indexed_slices.IndexedSlices): + continue + elif isinstance(branch_out, tensor_lib.Tensor): + with branch_graphs[branch_idx].as_default(): + branch_outputs[branch_idx][output_idx] = math_ops._as_indexed_slices( + branch_out) + else: + raise TypeError( + "Cannot reconcile {op_name} {output_idx}-th outputs:\n" + " outputs from all branches: {outputs}".format( + op_name="tf.cond" if op_type == _COND else "tf.switch_case", + output_idx=output_idx, + outputs=branch_outs)) + + for branch_graph, branch_outs in zip(branch_graphs, branch_outputs): + branch_graph.structured_outputs = branch_outs + branch_graph.outputs = [ + t for t in func_graph_module.flatten(branch_outs) if t is not None + ] + + +def _make_indexed_slices_indices_types_match(op_type, branch_graphs): + """Match dtype of IndexedSlices.indices in outputs of branch_graphs.""" + assert branch_graphs + # Indices of `IndexedSlices.indices` tensors in `branch_graphs[i].outputs`. + indexed_slice_indices = [] + current_index = 0 + # Note that this still contains Nones. We leave those in so that error + # messages contain the correct indices. We handle the Nones later when + # updating `current_index`. + branch_outputs_flat_with_composites = [ + nest.flatten(branch_graph.structured_outputs, expand_composites=False) + for branch_graph in branch_graphs + ] + outs_per_branch = [len(outs) for outs in branch_outputs_flat_with_composites] + assert len(set(outs_per_branch)) == 1, outs_per_branch + # Store indices of IndexedSlices.indices in `indexed_slice_indices`. + for output_idx, branch_outs in enumerate( + zip(*branch_outputs_flat_with_composites)): + if len( + set( + isinstance(out, indexed_slices.IndexedSlices) + for out in branch_outs)) != 1: + raise TypeError("Cannot reconcile tf.{op_name} {output_idx}-th outputs:\n" + " branches returned: {outputs}".format( + op_name="cond" if op_type == _COND else "switch_case", + output_idx=output_idx, + outputs=branch_outs)) + if isinstance(branch_outs[0], indexed_slices.IndexedSlices): + # indices is the second component of the composite tensor. + indexed_slice_indices.append(current_index + 1) + if nest.is_nested_or_composite(branch_outs[0]): + current_index += len(nest.flatten(branch_outs[0], expand_composites=True)) + elif branch_outs[0] is not None: + # `FuncGraph.outputs` does not contain Nones so no need to update the + # counter in that case. + current_index += 1 + + if not indexed_slice_indices: + return + + # `FuncGraph.outputs` is the flattened `FuncGraph.structured_outputs` minus + # the Nones. + if current_index != len(branch_graphs[0].outputs): + raise ValueError("Insufficient elements in branch_graphs[0].outputs.\n" + "Expected: %i\n" + "Actual: %i" % + (current_index, len(branch_graphs[0].outputs))) + + # Cast indices with mismatching types to int64. + for index in indexed_slice_indices: + if any(bg.outputs[index].dtype not in (dtypes.int32, dtypes.int64) + for bg in branch_graphs): + raise TypeError("Type of IndexedSlices.indices must be int32 or int64. " + "Found: %s" % + str([bg.outputs[index].dtype for bg in branch_graphs])) + if len(set(bg.outputs[index].dtype for bg in branch_graphs)) != 1: + for branch_graph in branch_graphs: + if branch_graph.outputs[index].dtype == dtypes.int32: + with branch_graph.as_default(): + branch_graph.outputs[index] = math_ops.cast( + branch_graph.outputs[index], dtypes.int64) + + for branch_graph in branch_graphs: + branch_graph.structured_outputs = _pack_sequence_as( + branch_graph.structured_outputs, branch_graph.outputs) + + +def _pack_sequence_as(structured_outputs, op_outputs): + """Packs the outputs of the gradient If/Case op. + + The branch functions may contain None's in the list of `structured_outputs`. + `op_outputs` has those outputs missing. So we need to add those Nones to the + list of `op_outputs` and then pack it in the same structure as + `structured_outputs`. + + Args: + structured_outputs: structured_outputs from one of the branch functions. + op_outputs: List of output tensors of the op. + + Returns: + `op_outputs` packed like `structured_outputs`. + """ + outputs_with_nones = [] + counter = 0 + for output in nest.flatten(structured_outputs, expand_composites=True): + if output is None: + outputs_with_nones.append(None) + else: + outputs_with_nones.append(op_outputs[counter]) + counter += 1 + return func_graph_module.pack_sequence_as(structured_outputs, + outputs_with_nones) + + +def _wrap_intermediates(func_graph, intermediates): + with func_graph.as_default(): + return [gen_optional_ops.optional_from_value([t]) for t in intermediates] + + +def _create_dummy_input(func_graph, template_tensor): + """Creates tensors in func_graph to represent template_tensors. + + Args: + func_graph: FuncGraph. + template_tensor: a tensor in the outer graph. + + Returns: + A tensor in func_graph. + """ + with func_graph.as_default(): + return array_ops.placeholder( + template_tensor.dtype, shape=template_tensor.shape) + + +def _create_none_optionals(func_graph, n): + """Creates `n` `None` optionals in func_graph. + + Args: + func_graph: FuncGraph. + n: `int` the number of `None` optionals to make. + + Returns: + A list of tensors in func_graph. + """ + with func_graph.as_default(): + return [gen_optional_ops.optional_none() for _ in range(n)] + + +# TODO(b/265317139): remove this function and move this dynamic dimension +# handling logic to XLA once XLA shape is ready for dynamic dimensions. +def _convert_dynamic_dimension_to_zero(shape): + """Converts dynamic dimensions in `shape` to zero. + + The fake params created to match the intermediates captured in other branches + could have dynamic dimensions. But the XLA shape is not able to handle + dynamic dimensions in TF TensorShape. Setting the dynamic dimensions to + size zero will help avoid failing safety checks in bridge. When XLA + DynamicConditional op reconciles branch differences, XLA will replace the + dimension size 0 with a bounded dimension determined from the shape of + real argument in the other branch. + + Note: Rank unknown shapes are returned as they are. + + Args: + shape: The TensorShape of fake param. + + Returns: + The new TensorShape with dynamic dimensions set to zero. + """ + if shape.rank is None: + return shape + + return tensor_shape.TensorShape( + [0 if d is None else d for d in shape.as_list()] + ) + + +def _create_fakeparams(func_graph, template_tensors): + """Creates FakeParams for the XLA case.""" + with func_graph.as_default(): + return [ + gen_functional_ops.fake_param( + dtype=t.dtype, shape=_convert_dynamic_dimension_to_zero(t.shape)) + for t in template_tensors] + + +def _check_same_outputs(op_type, graphs): + """Raises an error if `graphs` have different outputs.""" + + def error(branch_idx, error_detail): + raise TypeError( + "{b0_name} and {bn_name} arguments to {op_name} must have the same " + "number, type, and overall structure of return values.\n" + "\n" + "{b0_name} output: {b0_out}\n" + "{bn_name} output: {bn_out}\n" + "\n" + "Error details:\n" + "{detail}".format( + b0_name="true_fn" if op_type == _COND else "branches[0]", + bn_name=("false_fn" if op_type == _COND else + "branches[{}]".format(branch_idx)), + op_name="tf.cond" if op_type == _COND else "tf.switch_case", + b0_out=graphs[0].structured_outputs, + bn_out=graphs[branch_idx].structured_outputs, + detail=error_detail)) + + for b in range(1, len(graphs)): + try: + nest.assert_same_structure( + graphs[0].structured_outputs, + graphs[b].structured_outputs, + expand_composites=True) + except (ValueError, TypeError) as e: + error(b, str(e)) + + op_type_str = "cond" if op_type == _COND else "case" + if len(graphs[0].outputs) != len(graphs[b].outputs): + raise ValueError("Lengths of branch outputs of {op_type} must match.\n" + "len(graphs[0].outputs): {len_0}\n" + "len(graphs[{b}].outputs): {len_b}\n".format( + op_type=op_type_str, + len_0=len(graphs[0].outputs), + b=b, + len_b=len(graphs[b].outputs))) + for b0_out, bn_out in zip(graphs[0].outputs, graphs[b].outputs): + if b0_out.dtype != bn_out.dtype: + error(b, "%s and %s have different types" % (b0_out, bn_out)) + + +def _get_output_shapes(*branch_graph_outputs): + output_shapes = [] + for out_by_branch in zip(*branch_graph_outputs): + shape = out_by_branch[0].shape + for other_out in out_by_branch[1:]: + shape = shape.most_specific_compatible_shape(other_out.shape) + output_shapes.append(shape) + return output_shapes + + +def _copy_handle_data(external_tensors, *branch_graph_outputs): + """Combines shapes in handle data and sets metadata on `external_tensors`.""" + for tensors in zip(external_tensors, *branch_graph_outputs): + external = tensors[0] + internal = tensors[1:] + internal_handle_data = [] + for tensor in internal: + handle_data = handle_data_util.get_resource_handle_data(tensor) + # NOTE: Assumes handle data has only one ShapeAndType entry. It's + # unclear how to combine different lengths across branches. + if not handle_data.is_set or len(handle_data.shape_and_type) != 1: + break + internal_handle_data.append(handle_data) + else: # There is handle data, so we need to combine it. + combined_shape = tensor_shape.TensorShape(None) + combined_dtype = None + for handle_data in internal_handle_data: + handle_shape = tensor_shape.TensorShape( + handle_data.shape_and_type[0].shape) + combined_shape = combined_shape.most_specific_compatible_shape( + handle_shape) + if combined_dtype is None: + combined_dtype = handle_data.shape_and_type[0].dtype + elif handle_data.shape_and_type[0].dtype != combined_dtype: + # Variants from different branches have different dtypes. The + # combined variant has no static dtype. + combined_dtype = types_pb2.DT_INVALID + combined_handle_data = internal_handle_data[0] + combined_handle_data.shape_and_type[0].shape.CopyFrom( + combined_shape.as_proto()) + combined_handle_data.shape_and_type[0].dtype = combined_dtype + handle_data_util.set_handle_data(external, combined_handle_data) + + +def verify_captures(op_type, branch_graphs): + """Verify that a branch's tensor is not accessed in another branch fn.""" + # Note: It is technically not possible for lower-branch_index branches to + # capture tensors from higher-branch_index branches, because of the order of + # branch graph construction, but we check all for completeness and to + # guard against potential future changes. + other_branch_graphs = {g: i for i, g in enumerate(branch_graphs)} + for i, branch_graph in enumerate(branch_graphs): + for t in branch_graph.external_captures: + if not isinstance(t, ops.EagerTensor) and t.graph in other_branch_graphs: + branch_names = ["true_fn", "false_fn"] if op_type == _COND else [ + "branch {}".format(bi) for bi in range(len(branch_graphs))] + raise ValueError( + "Tensor {tname} in {b0name} is accessed from {b1name}.".format( + tname=t.name, + b0name=branch_names[other_branch_graphs[t.graph]], + b1name=branch_names[i])) + + +class _CondGradFuncGraph(util.CondBranchFuncGraph): + """FuncGraph for the gradient function of the branch of an If op. + + Handles wrapping and unwrapping intermediate values that are captured by the + gradient computation in optionals. + + Attributes: + op_needs_rewrite: True if any intermediates were captured, meaning the + forward If op needs to be written to output the wrapped intermediates. + """ + + def __init__(self, name, forward_graph): + super(_CondGradFuncGraph, self).__init__( + name, collections=ops.get_default_graph()._collections) # pylint: disable=protected-access + self.op_needs_rewrite = False + self._forward_graph = forward_graph + # Maps from forward intermediate tensor -> the unwrapped captured + # intermediate. + self._indirect_captures = {} + # Maps unwrapped intermediate -> optional-wrapped intermediate in the + # forward graph. + self._wrapped_intermediates = collections.OrderedDict() + # Raw intermediates captured from the forward graph. Populated iff we're in + # an XLA context. + self._xla_intermediates = [] + # Maps forward intermediate constant valued tensor's id to the constant + # created in this graph for that tensor. + self._captured_constants = {} + + @property + def wrapped_intermediates(self): + """The optional-wrapped intermediates captured from the forward graph.""" + return list(self._wrapped_intermediates.values()) + + @property + def xla_intermediates(self): + """Raw intermediates captured from the forward graph if XLA is enabled.""" + return self._xla_intermediates + + def _capture_helper(self, tensor, name): + if (tensor.graph is not self._forward_graph or + any(tensor is t for t in self._forward_graph.inputs) or + any(tensor is t for t in self._forward_graph.outputs)): + return super(_CondGradFuncGraph, self)._capture_helper(tensor, name) + + tensor_id = ops.tensor_id(tensor) + + # If `tensor` is a graph-building time constant, we create a constant with + # the same value in the backward graph instead of capturing it. + if tensor_id in self._captured_constants: + return self._captured_constants[tensor_id] + elif constant_op.is_constant(tensor): + self._captured_constants[tensor_id] = constant_op.constant( + tensor_util.constant_value(tensor), dtype=tensor.dtype) + return self._captured_constants[tensor_id] + + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + # XLA does not yet support optionals, so capture intermediates directly. + # TODO(skyewm,jpienaar): can XLA support optionals? + if all(tensor is not capture for capture in self.external_captures): + self.xla_intermediates.append(tensor) + self.op_needs_rewrite = True + return super(_CondGradFuncGraph, self)._capture_helper(tensor, name) + + captured_tensor = self._indirect_captures.get(tensor_id) + if captured_tensor is not None: + return captured_tensor + + # 'tensor' is an uncaptured intermediate in the forward graph. + # If it is not a resource, we wrap it in an optional in the forward graph + # and capture the optional normally. We then unwrap the captured optional + # value in the gradient graph to get the raw intermediate value. + # If it is a resource, we trace the resource up to the input in the forward + # graph and capture that. + + if tensor.dtype == dtypes.resource: + # Index of the forward graph input corresponding to the resource tensor. + index = util.resource_input_index( + tensor.name, [t.name for t in self._forward_graph.inputs], + {op.name: op.node_def for op in self._forward_graph.get_operations()}, + self._forward_graph._functions) + # This gets mapped to the corresponding If op input in + # `_resolve_grad_inputs`. + captured_tensor = super(_CondGradFuncGraph, self)._capture_helper( + self._forward_graph.inputs[index], name) + else: + if tensor_id not in self._wrapped_intermediates: + # If the gradient has already been computed for this If op, 'tensor' may + # already be wrapped. + for consumer in tensor.consumers(): + if (consumer.type == "OptionalFromValue" and + any(consumer.outputs[0] is output + for output in self._forward_graph.outputs)): + optional = consumer.outputs[0] + break + else: + # 'tensor' hasn't been wrapped, do it now. + with self._forward_graph.as_default(): + optional = gen_optional_ops.optional_from_value([tensor]) + self.op_needs_rewrite = True + self._wrapped_intermediates[tensor_id] = optional + + optional = self._wrapped_intermediates[tensor_id] + captured_optional = super(_CondGradFuncGraph, + self)._capture_helper(optional, name) + captured_tensor = gen_optional_ops.optional_get_value( + captured_optional, [tensor.dtype], [tensor.shape] + )[0] + + self._indirect_captures[tensor_id] = captured_tensor + return captured_tensor + + +def indexed_case(branch_index, + branch_fns, + name="indexed_case", + lower_using_switch_merge=None): + """Like conv_v2, except emits a Case op instead of an If.""" + if isinstance(branch_index, int): + raise TypeError("branch_index must not be a Python int", branch_index) + + with ops.name_scope(name) as scope: + branch_names = [ + util.unique_fn_name(scope, "branch{}".format(b)) + for b in range(len(branch_fns)) + ] + + # Automatic control dependencies are added in defuns, but not in v1 + # graphs. Propagate that behavior here. + add_control_dependencies = ops.get_default_graph()._add_control_dependencies + branch_index = ops.convert_to_tensor(branch_index, name="branch_index") + + branch_graphs = [] + for branch_name, branch_fn in zip(branch_names, branch_fns): + branch_graphs.append( + func_graph_module.func_graph_from_py_func( + branch_name, + branch_fn, + [], + {}, + func_graph=util.CondBranchFuncGraph( + branch_name, + collections=ops.get_default_graph()._collections), # pylint: disable=protected-access + add_control_dependencies=add_control_dependencies, + op_return_value=branch_index)) + + verify_captures(_CASE, branch_graphs) + return _build_case( + branch_index, + branch_graphs, [g.external_captures for g in branch_graphs], + name=scope, + lower_using_switch_merge=lower_using_switch_merge) + + +@ops.RegisterGradient("Case") +@ops.RegisterGradient("StatelessCase") +def _CaseGrad(op, *grads): # pylint: disable=invalid-name + """The gradient of a Case op produced by tf.switch_case.""" + # Get the Case operator (this logic handles the case where op is a MockOp) + case_op = op.outputs[0].op + branch_graphs = get_func_graphs(case_op) + assert branch_graphs + # Note: op.graph != ops.get_default_graph() when we are computing the gradient + # of a nested cond. + for branch_graph in branch_graphs: + assert branch_graph.outer_graph == case_op.graph + + # Create grad functions that compute the gradient of the branch forward + # graphs. These functions will capture tensors from the forward pass + # functions. + branch_grad_graphs = [] + for branch_graph in branch_graphs: + branch_grad_graphs.append( + _create_grad_func(branch_graph, grads, + util.unique_grad_fn_name(branch_graph.name))) + # Replaces output None grads with zeros if at least one branch has non-None + # grad at that index. + _create_zeros_for_none_grads(branch_graphs, branch_grad_graphs) + + if any(g.op_needs_rewrite for g in branch_grad_graphs): + # Modify 'op' to output the intermediates needed by the grad functions. Note + # that all needed intermediates are wrapped in optionals. Each optional + # intermediate output will have a value iff its corresponding branch is + # taken. + # NOTE(bjp): if there are any active sessions, this modification to `op` + # may make them unrunnable! + + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + # XLA does not yet support optionals, so output intermediates directly and + # make them match via FakeParams, which can be converted to zeros in XLA. + # TODO(bjp,jpienaar): can XLA support optionals? + branches_intermediates = [ + branch_grad_graph.xla_intermediates + for branch_grad_graph in branch_grad_graphs + ] + extra_branch_outputs = _make_intermediates_match_xla( + branch_graphs, branches_intermediates) + else: + branch_intermediates = [ + g.wrapped_intermediates for g in branch_grad_graphs + ] + # Make outputs match by adding none optionals. + extra_branch_outputs = _make_intermediates_match(branch_graphs, + branch_intermediates) + + for branch_graph, extra_outputs in zip(branch_graphs, extra_branch_outputs): + branch_graph.outputs.extend(extra_outputs) + # TODO(bjp): indicate it's an internal bug if this fails. + _check_same_outputs(_CASE, branch_graphs) + + for branch_graph in branch_graphs: + branch_graph.name += "_rewritten" + + case_op._set_func_list_attr("branches", [ + util.create_new_tf_function(branch_graph) + for branch_graph in branch_graphs + ]) + case_op._set_type_list_attr("Tout", branch_graphs[0].output_types) + case_op._set_shape_list_attr("output_shapes", + branch_graphs[0].output_shapes) + case_op._add_outputs([t.dtype for t in extra_branch_outputs[0]], + [t.shape for t in extra_branch_outputs[0]]) + + # Resolve references to forward graph tensors in grad graphs and ensure + # they are in-scope, i.e., belong to one of outer graphs of the grad graph. + branches_grad_inputs = [ + _resolve_grad_inputs(branch_graph, branch_grad_graph) for branch_graph, + branch_grad_graph in zip(branch_graphs, branch_grad_graphs) + ] + + # This modifies the graphs in branch_grad_graphs. + _make_output_composite_tensors_match(_CASE, branch_grad_graphs) + + try: + lowering = case_op._get_attr_bool("_lower_using_switch_merge") + except errors_impl.NotFoundError: + lowering = None + + outputs = _build_case( + case_op.inputs[0], + branch_grad_graphs, + branches_grad_inputs, + name="gradient", + lower_using_switch_merge=lowering) + + # The predicate has no gradient. + return [None] + outputs + + +def _build_case(branch_index, + branch_graphs, + branch_inputs, + name=None, + lower_using_switch_merge=None): + """Creates an `Case` op from `branch_index`, branch graphs and inputs. + + Note that this modifies `branch_graphs` to make the inputs match, and to + output all intermediates values so they're available for the gradient + computation. + + `branch_graphs` need not have the same input types, but they must + have the same output types. + + Args: + branch_index: integer Tensor + branch_graphs: List of FuncGraph + branch_inputs: List of lists of Tensors to be passed to corresponding + branch_graph as input. + name: the name for the Case op. + lower_using_switch_merge: Lower this op using switch merge ops (optional). + + Returns: + A list of Tensors which are the outputs of the Case op. Does not include + added intermediate outputs. + """ + _make_indexed_slices_indices_types_match(_CASE, branch_graphs) + _check_same_outputs(_CASE, branch_graphs) + + # Add inputs to branch_graphs to make them match. Note that this modifies the + # graphs in `branch_graphs`. + case_inputs = _make_inputs_match(branch_graphs, branch_inputs) + + stateful_ops = [] + for bg in branch_graphs: + stateful_ops.extend([ + op for op in bg.get_operations() if auto_control_deps.op_is_stateful(op) + ]) + + if stateful_ops: + op_fn = gen_functional_ops.case + else: + op_fn = gen_functional_ops.stateless_case + + # Create the Case op. + with ops.control_dependencies( + sum((list(bg.function_captures.control) for bg in branch_graphs), [])): + + def _make_op(inputs): + case_op, tensors = util.get_op_and_outputs(op_fn( + branch_index, + inputs, [t.dtype for t in branch_graphs[0].outputs], + [util.create_new_tf_function(g) for g in branch_graphs], + output_shapes=_get_output_shapes(*[g.outputs for g in branch_graphs]), + name=name)) + _copy_handle_data(tensors, *[g.outputs for g in branch_graphs]) + if case_op is not None: + util.maybe_set_lowering_attr(case_op, lower_using_switch_merge) + util.maybe_propagate_compile_time_consts_in_xla(case_op) + _set_read_only_resource_inputs_attr(case_op, branch_graphs) + # Prevent fetching since the variant outputs can't be fetched directly. + case_op.graph.prevent_fetching(case_op) + + # Store the branch graphs so they can be reused during the gradient + # pass. + for i, bg in enumerate(branch_graphs): + bg.outer_graph = ops.get_default_graph() + setattr(case_op, "_branch_graph_{}".format(i), bg) + + return tensors + tensors = util.run_as_function_for_tape_gradients(_make_op, case_inputs) + + # Return identities for each output of the Case op, rather than the output of + # the Case op directly. This makes pruning work if the output of switch_case() + # is fetched: the lowering pass converts the Case outputs into IdentityN + # outputs, which if fetched will cause all ops in the taken branch to be run + # (since it takes all merge ops as input). After lowering, each output + # identity op will end up with only the appropriate merge op as input. + # TODO(b/79984175): this doesn't have to be a tuple once we covert to the + # correct output structure + tensors = [array_ops.identity(t) for t in tensors] + + return _pack_sequence_as(branch_graphs[0].structured_outputs, tensors) + + +def _set_read_only_resource_inputs_attr(op, branch_graphs): + """Sets the list of resource inputs which are read-only. + + This is used by AutomaticControlDependencies. + + Args: + op: If or Case Operation. + branch_graphs: List of branch FuncGraphs. + """ + # The first entry in `op.inputs` is the predicate which is not passed to + # branch graphs so len(branch_graph[i].inputs) == len(op.inputs) - 1. + read_only_indices = set(range(len(op.inputs) - 1)) + for branch_graph in branch_graphs: + assert len(branch_graph.inputs) == len(op.inputs) - 1, "should never happen" + if not read_only_indices: + break + branch_read_only_indices = acd.get_read_only_resource_input_indices_graph( + branch_graph) + read_only_indices = read_only_indices.intersection(branch_read_only_indices) + # Convert indices in `branch_graphs[i].inputs` to `op.inputs`. + read_only_indices = [i + 1 for i in read_only_indices] + ops.set_int_list_attr(op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR, + sorted(read_only_indices)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/confusion_matrix.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..614ad5dfe62fc5cb85a5dcb55528cda73be07fc2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/confusion_matrix.py @@ -0,0 +1,259 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Confusion matrix related utilities.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def remove_squeezable_dimensions( + labels, predictions, expected_rank_diff=0, name=None): + """Squeeze last dim if ranks differ from expected by exactly 1. + + In the common case where we expect shapes to match, `expected_rank_diff` + defaults to 0, and we squeeze the last dimension of the larger rank if they + differ by 1. + + But, for example, if `labels` contains class IDs and `predictions` contains 1 + probability per class, we expect `predictions` to have 1 more dimension than + `labels`, so `expected_rank_diff` would be 1. In this case, we'd squeeze + `labels` if `rank(predictions) - rank(labels) == 0`, and + `predictions` if `rank(predictions) - rank(labels) == 2`. + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + labels: Label values, a `Tensor` whose dimensions match `predictions`. + predictions: Predicted values, a `Tensor` of arbitrary dimensions. + expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. + name: Name of the op. + + Returns: + Tuple of `labels` and `predictions`, possibly with last dim squeezed. + """ + with ops.name_scope(name, 'remove_squeezable_dimensions', + [labels, predictions]): + predictions = ops.convert_to_tensor(predictions) + labels = ops.convert_to_tensor(labels) + predictions_shape = predictions.get_shape() + predictions_rank = predictions_shape.ndims + labels_shape = labels.get_shape() + labels_rank = labels_shape.ndims + if (labels_rank is not None) and (predictions_rank is not None): + # Use static rank. + rank_diff = predictions_rank - labels_rank + if (rank_diff == expected_rank_diff + 1 and + predictions_shape.dims[-1].is_compatible_with(1)): + predictions = array_ops.squeeze(predictions, [-1]) + elif (rank_diff == expected_rank_diff - 1 and + labels_shape.dims[-1].is_compatible_with(1)): + labels = array_ops.squeeze(labels, [-1]) + return labels, predictions + + # Use dynamic rank. + rank_diff = array_ops.rank(predictions) - array_ops.rank(labels) + if (predictions_rank is None) or ( + predictions_shape.dims[-1].is_compatible_with(1)): + predictions = cond.cond( + math_ops.equal(expected_rank_diff + 1, rank_diff), + lambda: array_ops.squeeze(predictions, [-1]), + lambda: predictions) + if (labels_rank is None) or ( + labels_shape.dims[-1].is_compatible_with(1)): + labels = cond.cond( + math_ops.equal(expected_rank_diff - 1, rank_diff), + lambda: array_ops.squeeze(labels, [-1]), + lambda: labels) + return labels, predictions + + +@tf_export('math.confusion_matrix', v1=[]) +@dispatch.add_dispatch_support +def confusion_matrix(labels, + predictions, + num_classes=None, + weights=None, + dtype=dtypes.int32, + name=None): + """Computes the confusion matrix from predictions and labels. + + The matrix columns represent the prediction labels and the rows represent the + real labels. The confusion matrix is always a 2-D array of shape `[n, n]`, + where `n` is the number of valid labels for a given classification task. Both + prediction and labels must be 1-D arrays of the same shape in order for this + function to work. + + If `num_classes` is `None`, then `num_classes` will be set to one plus the + maximum value in either predictions or labels. Class labels are expected to + start at 0. For example, if `num_classes` is 3, then the possible labels + would be `[0, 1, 2]`. + + If `weights` is not `None`, then each prediction contributes its + corresponding weight to the total value of the confusion matrix cell. + + For example: + + ```python + tf.math.confusion_matrix([1, 2, 4], [2, 2, 4]) ==> + [[0 0 0 0 0] + [0 0 1 0 0] + [0 0 1 0 0] + [0 0 0 0 0] + [0 0 0 0 1]] + ``` + + Note that the possible labels are assumed to be `[0, 1, 2, 3, 4]`, + resulting in a 5x5 confusion matrix. + + Args: + labels: 1-D `Tensor` of real labels for the classification task. + predictions: 1-D `Tensor` of predictions for a given classification. + num_classes: The possible number of labels the classification task can + have. If this value is not provided, it will be calculated + using both predictions and labels array. + weights: An optional `Tensor` whose shape matches `predictions`. + dtype: Data type of the confusion matrix. + name: Scope name. + + Returns: + A `Tensor` of type `dtype` with shape `[n, n]` representing the confusion + matrix, where `n` is the number of possible labels in the classification + task. + + Raises: + ValueError: If both predictions and labels are not 1-D vectors and have + mismatched shapes, or if `weights` is not `None` and its shape doesn't + match `predictions`. + """ + with ops.name_scope(name, 'confusion_matrix', + (predictions, labels, num_classes, weights)) as name: + labels, predictions = remove_squeezable_dimensions( + ops.convert_to_tensor(labels, name='labels'), + ops.convert_to_tensor( + predictions, name='predictions')) + predictions = math_ops.cast(predictions, dtypes.int64) + labels = math_ops.cast(labels, dtypes.int64) + + # Sanity checks - underflow or overflow can cause memory corruption. + labels = control_flow_ops.with_dependencies( + [check_ops.assert_non_negative( + labels, message='`labels` contains negative values')], + labels) + predictions = control_flow_ops.with_dependencies( + [check_ops.assert_non_negative( + predictions, message='`predictions` contains negative values')], + predictions) + + if num_classes is None: + num_classes = math_ops.maximum(math_ops.reduce_max(predictions), + math_ops.reduce_max(labels)) + 1 + else: + num_classes_int64 = math_ops.cast(num_classes, dtypes.int64) + labels = control_flow_ops.with_dependencies( + [check_ops.assert_less( + labels, num_classes_int64, message='`labels` out of bound')], + labels) + predictions = control_flow_ops.with_dependencies( + [check_ops.assert_less( + predictions, num_classes_int64, + message='`predictions` out of bound')], + predictions) + + if weights is not None: + weights = ops.convert_to_tensor(weights, name='weights') + predictions.get_shape().assert_is_compatible_with(weights.get_shape()) + weights = math_ops.cast(weights, dtype) + + shape = array_ops_stack.stack([num_classes, num_classes]) + indices = array_ops_stack.stack([labels, predictions], axis=1) + values = (array_ops.ones_like(predictions, dtype) + if weights is None else weights) + return array_ops.scatter_nd( + indices=indices, + updates=values, + shape=math_ops.cast(shape, dtypes.int64)) + + +@tf_export(v1=['math.confusion_matrix', 'confusion_matrix']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('confusion_matrix', 'train.confusion_matrix') +def confusion_matrix_v1(labels, + predictions, + num_classes=None, + dtype=dtypes.int32, + name=None, + weights=None): + """Computes the confusion matrix from predictions and labels. + + The matrix columns represent the prediction labels and the rows represent the + real labels. The confusion matrix is always a 2-D array of shape `[n, n]`, + where `n` is the number of valid labels for a given classification task. Both + prediction and labels must be 1-D arrays of the same shape in order for this + function to work. + + If `num_classes` is `None`, then `num_classes` will be set to one plus the + maximum value in either predictions or labels. Class labels are expected to + start at 0. For example, if `num_classes` is 3, then the possible labels + would be `[0, 1, 2]`. + + If `weights` is not `None`, then each prediction contributes its + corresponding weight to the total value of the confusion matrix cell. + + For example: + + ```python + tf.math.confusion_matrix([1, 2, 4], [2, 2, 4]) ==> + [[0 0 0 0 0] + [0 0 1 0 0] + [0 0 1 0 0] + [0 0 0 0 0] + [0 0 0 0 1]] + ``` + + Note that the possible labels are assumed to be `[0, 1, 2, 3, 4]`, + resulting in a 5x5 confusion matrix. + + Args: + labels: 1-D `Tensor` of real labels for the classification task. + predictions: 1-D `Tensor` of predictions for a given classification. + num_classes: The possible number of labels the classification task can have. + If this value is not provided, it will be calculated using both + predictions and labels array. + dtype: Data type of the confusion matrix. + name: Scope name. + weights: An optional `Tensor` whose shape matches `predictions`. + + Returns: + A `Tensor` of type `dtype` with shape `[n, n]` representing the confusion + matrix, where `n` is the number of possible labels in the classification + task. + + Raises: + ValueError: If both predictions and labels are not 1-D vectors and have + mismatched shapes, or if `weights` is not `None` and its shape doesn't + match `predictions`. + """ + return confusion_matrix(labels, predictions, num_classes, weights, dtype, + name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_assert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_assert.py new file mode 100644 index 0000000000000000000000000000000000000000..18928fa6f357544912c9c55845e622f415e43167 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_assert.py @@ -0,0 +1,130 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Assert functions for Control Flow Operations.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import gen_control_flow_ops +from tensorflow.python.ops import gen_logging_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util import tf_should_use +from tensorflow.python.util.tf_export import tf_export + + +def _summarize_eager(tensor, summarize=None): + """Returns a summarized string representation of eager `tensor`. + + Args: + tensor: EagerTensor to summarize + summarize: Include these many first elements of `array` + """ + # Emulate the behavior of Tensor::SummarizeValue() + if summarize is None: + summarize = 3 + elif summarize < 0: + summarize = array_ops.size(tensor) + + # reshape((-1,)) is the fastest way to get a flat array view + if tensor._rank(): # pylint: disable=protected-access + flat = tensor.numpy().reshape((-1,)) + lst = [str(x) for x in flat[:summarize]] + if len(lst) < flat.size: + lst.append("...") + else: + # tensor.numpy() returns a scalar for zero dimensional arrays + if gen_math_ops.not_equal(summarize, 0): + lst = [str(tensor.numpy())] + else: + lst = [] + + return ", ".join(lst) + + +# Assert and Print are special symbols in python, so we must +# use an upper-case version of them. +@tf_export("debugging.Assert", "Assert") +@dispatch.add_dispatch_support +@tf_should_use.should_use_result +def Assert(condition, data, summarize=None, name=None): + """Asserts that the given condition is true. + + If `condition` evaluates to false, print the list of tensors in `data`. + `summarize` determines how many entries of the tensors to print. + + Args: + condition: The condition to evaluate. + data: The tensors to print out when condition is false. + summarize: Print this many entries of each tensor. + name: A name for this operation (optional). + + Returns: + assert_op: An `Operation` that, when executed, raises a + `tf.errors.InvalidArgumentError` if `condition` is not true. + @compatibility(eager) + returns None + @end_compatibility + + Raises: + @compatibility(TF1) + When in TF V1 mode (that is, outside `tf.function`) Assert needs a control + dependency on the output to ensure the assertion executes: + + ```python + # Ensure maximum element of x is smaller or equal to 1 + assert_op = tf.Assert(tf.less_equal(tf.reduce_max(x), 1.), [x]) + with tf.control_dependencies([assert_op]): + ... code using x ... + ``` + + @end_compatibility + """ + if context.executing_eagerly(): + if not condition: + xs = ops.convert_n_to_tensor(data) + data_str = [_summarize_eager(x, summarize) for x in xs] + raise errors.InvalidArgumentError( + node_def=None, + op=None, + message="Expected '%s' to be true. Summarized data: %s" % + (condition, "\n".join(data_str))) + return + + with ops.name_scope(name, "Assert", [condition, data]) as name: + xs = ops.convert_n_to_tensor(data) + if all(x.dtype in {dtypes.string, dtypes.int32} for x in xs): + # As a simple heuristic, we assume that string and int32 are + # on host to avoid the need to use cond. If it is not case, + # we will pay the price copying the tensor to host memory. + return gen_logging_ops._assert(condition, data, summarize, name="Assert") # pylint: disable=protected-access + else: + condition = ops.convert_to_tensor(condition, name="Condition") + + def true_assert(): + return gen_logging_ops._assert( # pylint: disable=protected-access + condition, data, summarize, name="Assert") + + guarded_assert = cond.cond( + condition, + gen_control_flow_ops.no_op, + true_assert, + name="AssertGuard") + if context.executing_eagerly(): + return + return guarded_assert.op diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_case.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_case.py new file mode 100644 index 0000000000000000000000000000000000000000..be7beca29fe10a50e2cbc4e549cd27a80b64e0ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_case.py @@ -0,0 +1,417 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Case functions for Control Flow Operations.""" + +import collections +import functools +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("case", v1=[]) +@dispatch.add_dispatch_support +def case_v2(pred_fn_pairs, + default=None, + exclusive=False, + strict=False, + name="case"): + """Create a case operation. + + See also `tf.switch_case`. + + The `pred_fn_pairs` parameter is a list of pairs of size N. + Each pair contains a boolean scalar tensor and a python callable that + creates the tensors to be returned if the boolean evaluates to True. + `default` is a callable generating a list of tensors. All the callables + in `pred_fn_pairs` as well as `default` (if provided) should return the same + number and types of tensors. + + If `exclusive==True`, all predicates are evaluated, and an exception is + thrown if more than one of the predicates evaluates to `True`. + If `exclusive==False`, execution stops at the first predicate which + evaluates to True, and the tensors generated by the corresponding function + are returned immediately. If none of the predicates evaluate to True, this + operation returns the tensors generated by `default`. + + `tf.case` supports nested structures as implemented in + `tf.nest`. All of the callables must return the same (possibly nested) value + structure of lists, tuples, and/or named tuples. Singleton lists and tuples + form the only exceptions to this: when returned by a callable, they are + implicitly unpacked to single values. This behavior is disabled by passing + `strict=True`. + + @compatibility(v2) + `pred_fn_pairs` could be a dictionary in v1. However, tf.Tensor and + tf.Variable are no longer hashable in v2, so cannot be used as a key for a + dictionary. Please use a list or a tuple instead. + @end_compatibility + + + **Example 1:** + + Pseudocode: + + ``` + if (x < y) return 17; + else return 23; + ``` + + Expressions: + + ```python + f1 = lambda: tf.constant(17) + f2 = lambda: tf.constant(23) + r = tf.case([(tf.less(x, y), f1)], default=f2) + ``` + + **Example 2:** + + Pseudocode: + + ``` + if (x < y && x > z) raise OpError("Only one predicate may evaluate to True"); + if (x < y) return 17; + else if (x > z) return 23; + else return -1; + ``` + + Expressions: + + ```python + def f1(): return tf.constant(17) + def f2(): return tf.constant(23) + def f3(): return tf.constant(-1) + r = tf.case([(tf.less(x, y), f1), (tf.greater(x, z), f2)], + default=f3, exclusive=True) + ``` + + Args: + pred_fn_pairs: List of pairs of a boolean scalar tensor and a callable which + returns a list of tensors. + default: Optional callable that returns a list of tensors. + exclusive: True iff at most one predicate is allowed to evaluate to `True`. + strict: A boolean that enables/disables 'strict' mode; see above. + name: A name for this operation (optional). + + Returns: + The tensors returned by the first pair whose predicate evaluated to True, or + those returned by `default` if none does. + + Raises: + TypeError: If `pred_fn_pairs` is not a list/tuple. + TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + return _case_helper( + cond.cond, + pred_fn_pairs, + default, + exclusive, + name, + allow_python_preds=False, + strict=strict) + + +@tf_export(v1=["case"]) +@dispatch.add_dispatch_support +def case(pred_fn_pairs, + default=None, + exclusive=False, + strict=False, + name="case"): + """Create a case operation. + + See also `tf.switch_case`. + + The `pred_fn_pairs` parameter is a dict or list of pairs of size N. + Each pair contains a boolean scalar tensor and a python callable that + creates the tensors to be returned if the boolean evaluates to True. + `default` is a callable generating a list of tensors. All the callables + in `pred_fn_pairs` as well as `default` (if provided) should return the same + number and types of tensors. + + If `exclusive==True`, all predicates are evaluated, and an exception is + thrown if more than one of the predicates evaluates to `True`. + If `exclusive==False`, execution stops at the first predicate which + evaluates to True, and the tensors generated by the corresponding function + are returned immediately. If none of the predicates evaluate to True, this + operation returns the tensors generated by `default`. + + `tf.case` supports nested structures as implemented in + `tf.nest`. All of the callables must return the same (possibly nested) value + structure of lists, tuples, and/or named tuples. Singleton lists and tuples + form the only exceptions to this: when returned by a callable, they are + implicitly unpacked to single values. This behavior is disabled by passing + `strict=True`. + + If an unordered dictionary is used for `pred_fn_pairs`, the order of the + conditional tests is not guaranteed. However, the order is guaranteed to be + deterministic, so that variables created in conditional branches are created + in fixed order across runs. + + @compatibility(eager) + Unordered dictionaries are not supported in eager mode when `exclusive=False`. + Use a list of tuples instead. + @end_compatibility + + + **Example 1:** + + Pseudocode: + + ``` + if (x < y) return 17; + else return 23; + ``` + + Expressions: + + ```python + f1 = lambda: tf.constant(17) + f2 = lambda: tf.constant(23) + r = tf.case([(tf.less(x, y), f1)], default=f2) + ``` + + **Example 2:** + + Pseudocode: + + ``` + if (x < y && x > z) raise OpError("Only one predicate may evaluate to True"); + if (x < y) return 17; + else if (x > z) return 23; + else return -1; + ``` + + Expressions: + + ```python + def f1(): return tf.constant(17) + def f2(): return tf.constant(23) + def f3(): return tf.constant(-1) + r = tf.case({tf.less(x, y): f1, tf.greater(x, z): f2}, + default=f3, exclusive=True) + ``` + + Args: + pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor and a + callable which returns a list of tensors. + default: Optional callable that returns a list of tensors. + exclusive: True iff at most one predicate is allowed to evaluate to `True`. + strict: A boolean that enables/disables 'strict' mode; see above. + name: A name for this operation (optional). + + Returns: + The tensors returned by the first pair whose predicate evaluated to True, or + those returned by `default` if none does. + + Raises: + TypeError: If `pred_fn_pairs` is not a list/dictionary. + TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + return _case_helper( + cond.cond, + pred_fn_pairs, + default, + exclusive, + name, + allow_python_preds=False, + strict=strict) + + +def _assert_at_most_n_true(predicates, n, msg): + """Returns an Assert op that checks that at most n predicates are True. + + Args: + predicates: list of bool scalar tensors. + n: maximum number of true predicates allowed. + msg: Error message. + """ + preds_c = array_ops_stack.stack(predicates, name="preds_c") + num_true_conditions = math_ops.reduce_sum( + math_ops.cast(preds_c, dtypes.int32), name="num_true_conds") + condition = math_ops.less_equal(num_true_conditions, + constant_op.constant(n, name="n_true_conds")) + preds_names = ", ".join(getattr(p, "name", "?") for p in predicates) + error_msg = [ + "%s: more than %d conditions (%s) evaluated as True:" % + (msg, n, preds_names), preds_c + ] + return control_flow_assert.Assert( + condition, data=error_msg, summarize=len(predicates)) + + +def _case_create_default_action(predicates, actions): + """Creates default action for a list of actions and their predicates. + + It uses the input actions to select an arbitrary as default and makes sure + that corresponding predicates have valid values. + + Args: + predicates: a list of bool scalar tensors + actions: a list of callable objects which return tensors. + + Returns: + a callable + """ + k = len(predicates) - 1 # could pick any + predicate, action = predicates[k], actions[k] + other_predicates, other_actions = predicates[:k], actions[:k] + + def default_action(): + others_msg = ("Implementation error: " + "selected default action #%d was called, but some of other " + "predicates are True: " % k) + default_msg = ("Input error: " + "None of conditions evaluated as True:", + array_ops_stack.stack(predicates, name="preds_c")) + with ops.control_dependencies([ + _assert_at_most_n_true( # pylint: disable=protected-access + other_predicates, n=0, msg=others_msg), + control_flow_assert.Assert(predicate, data=default_msg) + ]): + return action() + + return default_action, other_predicates, other_actions + + +def _case_helper(cond_fn, + pred_fn_pairs, + default, + exclusive, + name, + allow_python_preds=False, + **cond_kwargs): + """Implementation of case that allows for different cond functions. + + Args: + cond_fn: method that has signature and semantics of `cond` above. + pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor, and a + callable which returns a list of tensors. + default: Optional callable that returns a list of tensors. + exclusive: True iff at most one predicate is allowed to evaluate to `True`. + name: A name for this operation (optional). + allow_python_preds: if true, pred_fn_pairs may contain Python bools in + addition to boolean Tensors + **cond_kwargs: keyword arguments that will be passed to `cond_fn`. + + Returns: + The tensors returned by the first pair whose predicate evaluated to True, or + those returned by `default` if none does. + + Raises: + TypeError: If `pred_fn_pairs` is not a list/dictionary. + TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + predicates, actions = _case_verify_and_canonicalize_args( + pred_fn_pairs, exclusive, name, allow_python_preds) + with ops.name_scope(name, "case", [predicates]): + if default is None: + default, predicates, actions = _case_create_default_action( + predicates, actions) + fn = default + # To eval conditions in direct order we create nested conditions in reverse: + # cond_fn(c[0], true_fn=.., false_fn=cond_fn(c[1], ...)) + for predicate, action in reversed(list(zip(predicates, actions))): + fn = functools.partial( + cond_fn, predicate, true_fn=action, false_fn=fn, **cond_kwargs) + if exclusive: + with ops.control_dependencies([ + _assert_at_most_n_true( # pylint: disable=protected-access + predicates, n=1, msg="Input error: exclusive=True") + ]): + return fn() + else: + return fn() + + +def _case_verify_and_canonicalize_args(pred_fn_pairs, exclusive, name, + allow_python_preds): + """Verifies input arguments for the case function. + + Args: + pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor, and a + callable which returns a list of tensors. + exclusive: True iff at most one predicate is allowed to evaluate to `True`. + name: A name for the case operation. + allow_python_preds: if true, pred_fn_pairs may contain Python bools in + addition to boolean Tensors + + Raises: + TypeError: If `pred_fn_pairs` is not a list/dictionary. + TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + + Returns: + a tuple . + """ + if not isinstance(pred_fn_pairs, (list, tuple, dict)): + raise TypeError("'pred_fn_pairs' must be a list, tuple, or dict. " + f"Received: {type(pred_fn_pairs)}") + + if isinstance(pred_fn_pairs, collections.OrderedDict): + pred_fn_pairs = pred_fn_pairs.items() + elif isinstance(pred_fn_pairs, dict): + if context.executing_eagerly(): + # No name to sort on in eager mode. Use dictionary traversal order, + # which is nondeterministic in versions of Python < 3.6 + if not exclusive: + raise ValueError("Unordered dictionaries are not supported for the " + "'pred_fn_pairs' argument when `exclusive=False` and " + "eager mode is enabled.") + pred_fn_pairs = list(pred_fn_pairs.items()) + else: + pred_fn_pairs = sorted( + pred_fn_pairs.items(), key=lambda item: item[0].name) + if not exclusive: + logging.warn( + "%s: An unordered dictionary of predicate/fn pairs was " + "provided, but exclusive=False. The order of conditional " + "tests is deterministic but not guaranteed.", name) + for pred_fn_pair in pred_fn_pairs: + if not isinstance(pred_fn_pair, tuple) or len(pred_fn_pair) != 2: + raise TypeError("Each entry in 'pred_fn_pairs' must be a 2-tuple. " + f"Received {pred_fn_pair}.") + pred, fn = pred_fn_pair + + if isinstance(pred, tensor.Tensor): + if pred.dtype != dtypes.bool: + raise TypeError("pred must be Tensor of type bool: %s" % pred.name) + elif not allow_python_preds: + raise TypeError("pred must be a Tensor, got: %s" % pred) + elif not isinstance(pred, bool): + raise TypeError("pred must be a Tensor or bool, got: %s" % pred) + + if not callable(fn): + raise TypeError("fn for pred %s must be callable." % pred.name) + + predicates, actions = zip(*pred_fn_pairs) + return predicates, actions diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe6d207f9805d347d078b57cd429f16dcc7015e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_grad.py @@ -0,0 +1,247 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Gradients for operators defined in control_flow_ops.py.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import math_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import,undefined-variable,redefined-builtin +from tensorflow.python.ops.control_flow_ops import * +# pylint: enable=wildcard-import + + +def _SwitchGrad(op, *grad): + """Gradients for a Switch op is calculated using a Merge op. + + If the switch is a loop switch, it will be visited twice. We create + the merge on the first visit, and update the other input of the merge + on the second visit. A next_iteration is also added on second visit. + """ + graph = ops.get_default_graph() + # pylint: disable=protected-access + op_ctxt = op._get_control_flow_context() + grad_ctxt = graph._get_control_flow_context() + # pylint: enable=protected-access + if isinstance(op_ctxt, WhileContext): + merge_grad = grad_ctxt.grad_state.switch_map.get(op) + if merge_grad is not None: + # This is the second time this Switch is visited. It comes from + # the non-exit branch of the Switch, so update the second input + # to the Merge. + # TODO(yuanbyu): Perform shape inference with this new input. + if grad[1] is not None: + # pylint: disable=protected-access + control_flow_ops._AddNextAndBackEdge(merge_grad, grad[1], + enforce_shape_invariant=False) + # pylint: enable=protected-access + return None, None + elif grad[0] is not None: + # This is the first time this Switch is visited. It comes from + # the Exit branch, which is grad[0]. grad[1] is empty at this point. + # Use grad[0] for both inputs to merge for now, but update the second + # input of merge when we see this Switch the second time. + merge_grad = merge([grad[0], grad[0]], name="b_switch")[0] + grad_ctxt.grad_state.switch_map[op] = merge_grad + return merge_grad, None + else: + # This is the first time this Switch is visited. It comes from the + # Identity branch. Such a Switch has `None` gradient for the Exit branch, + # meaning the output is not differentiable. + return None, None + elif isinstance(op_ctxt, CondContext): + zero_grad = grad[1 - op_ctxt.branch] + # At this point, we have created zero_grad guarded by the right switch. + # Unfortunately, we may still get None here for not trainable data types. + if zero_grad is None: + # For resource variables we get None always on the other branch, so bypass + # this. + if op.inputs[0].dtype == dtypes.resource: + return merge( + [grad[op_ctxt.branch]] * 2, name="cond_resource_grad")[0], None + return None, None + return merge(grad, name="cond_grad")[0], None + else: + false_grad = switch(grad[0], op.inputs[1])[0] + true_grad = switch(grad[1], op.inputs[1])[1] + return merge([false_grad, true_grad])[0], None + + +ops.RegisterGradient("Switch")(_SwitchGrad) +ops.RegisterGradient("RefSwitch")(_SwitchGrad) + + +@ops.RegisterGradient("Merge") +def _MergeGrad(op, grad, _): + """Gradients for a Merge op are calculated using a Switch op.""" + input_op = op.inputs[0].op + graph = ops.get_default_graph() + # pylint: disable=protected-access + op_ctxt = control_flow_util.GetOutputContext(input_op) + grad_ctxt = graph._get_control_flow_context() + # pylint: enable=protected-access + if isinstance(op_ctxt, WhileContext): + # pylint: disable=protected-access + return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot) + # pylint: enable=protected-access + elif isinstance(op_ctxt, CondContext): + pred = op_ctxt.pred + if grad_ctxt and grad_ctxt.grad_state: + # This Merge node is part of a cond within a loop. + # The backprop needs to have the value of this predicate for every + # iteration. So we must have its values accumulated in the forward, and + # use the accumulated values as the predicate for this backprop switch. + grad_state = grad_ctxt.grad_state + real_pred = grad_state.history_map.get(pred.name) + if real_pred is None: + # Remember the value of pred for every iteration. + grad_ctxt = grad_state.grad_context + grad_ctxt.Exit() + history_pred = grad_state.AddForwardAccumulator(pred) + grad_ctxt.Enter() + + # Add the stack pop op. If pred.op is in a (outer) CondContext, + # the stack pop will be guarded with a switch. + real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred) + grad_state.history_map[pred.name] = real_pred + pred = real_pred + # pylint: disable=protected-access + return control_flow_ops._SwitchRefOrTensor(grad, pred, name="cond_grad") + # pylint: enable=protected-access + else: + num_inputs = len(op.inputs) + cond = [math_ops.equal(op.outputs[1], i) for i in range(num_inputs)] + # pylint: disable=protected-access + return [ + control_flow_ops._SwitchRefOrTensor(grad, cond[i])[1] + for i in range(num_inputs) + ] + # pylint: enable=protected-access + + +@ops.RegisterGradient("RefMerge") +def _RefMergeGrad(op, grad, _): + return _MergeGrad(op, grad, _) + + +@ops.RegisterGradient("Exit") +def _ExitGrad(op, grad): + """Gradients for an exit op are calculated using an Enter op.""" + graph = ops.get_default_graph() + # pylint: disable=protected-access + op_ctxt = op._get_control_flow_context() + grad_ctxt = graph._get_control_flow_context() + # pylint: enable=protected-access + if not grad_ctxt.back_prop: + # The flag `back_prop` is set by users to suppress gradient + # computation for this loop. If the attribute `back_prop` is false, + # no gradient computation. + return None + + if op_ctxt.grad_state: + raise TypeError("Second-order gradient for while loops not supported.") + + if isinstance(grad, tensor.Tensor): + grad_ctxt.AddName(grad.name) + else: + if not isinstance( + grad, (indexed_slices.IndexedSlices, sparse_tensor.SparseTensor)): + raise TypeError(f"Type {type(grad)} not supported, must be either" + "`indexed_slices.IndexedSlices` or `SparseTensor`.") + grad_ctxt.AddName(grad.values.name) + grad_ctxt.AddName(grad.indices.name) + dense_shape = grad.dense_shape + if dense_shape is not None: + grad_ctxt.AddName(dense_shape.name) + grad_ctxt.Enter() + # pylint: disable=protected-access + result = control_flow_ops._Enter( + grad, grad_ctxt.name, is_constant=False, + parallel_iterations=grad_ctxt.parallel_iterations, + name="b_exit") + # pylint: enable=protected-access + grad_ctxt.loop_enters.append(result) + grad_ctxt.Exit() + return result + + +ops.RegisterGradient("RefExit")(_ExitGrad) + + +@ops.RegisterGradient("NextIteration") +def _NextIterationGrad(_, grad): + """A forward next_iteration is translated into a backprop identity. + + Note that the backprop next_iteration is added in switch grad. + """ + return grad + + +@ops.RegisterGradient("RefNextIteration") +def _RefNextIterationGrad(_, grad): + return _NextIterationGrad(_, grad) + + +@ops.RegisterGradient("Enter") +def _EnterGrad(op, grad): + """Gradients for an Enter are calculated using an Exit op. + + For loop variables, grad is the gradient so just add an exit. + For loop invariants, we need to add an accumulator loop. + """ + graph = ops.get_default_graph() + # pylint: disable=protected-access + grad_ctxt = graph._get_control_flow_context() + # pylint: enable=protected-access + if grad_ctxt is None: + return grad + if not grad_ctxt.back_prop: + # Skip gradient computation, if the attribute `back_prop` is false. + return grad + if grad_ctxt.grad_state is None: + # Pass the gradient through if we are not in a gradient while context. + return grad + if op.get_attr("is_constant"): + # Add a gradient accumulator for each loop invariant. + if isinstance(grad, tensor.Tensor): + result = grad_ctxt.AddBackpropAccumulator(op, grad) + elif isinstance(grad, indexed_slices.IndexedSlices): + result = grad_ctxt.AddBackpropIndexedSlicesAccumulator(op, grad) + else: + # TODO(yuanbyu, lukasr): Add support for SparseTensor. + raise TypeError(f"Type {type(grad)} not supported," + "must be Tensor or Indexed Slices") + else: + result = exit(grad) + grad_ctxt.loop_exits.append(result) + grad_ctxt.ExitResult([result]) + return result + + +@ops.RegisterGradient("RefEnter") +def _RefEnterGrad(op, grad): + return _EnterGrad(op, grad) + + +@ops.RegisterGradient("LoopCond") +def _LoopCondGrad(_): + """Stop backprop for the predicate of a while loop.""" + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..489ebe344bf4d42e3334d5182c1749296267d42e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_ops.py @@ -0,0 +1,2256 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Control Flow Operations. + +See the [autograph](https://www.tensorflow.org/guide/autograph) guide. +""" +# pylint: disable=g-bad-name +import abc + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.protobuf import control_flow_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_util as util +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import,undefined-variable +from tensorflow.python.ops.gen_control_flow_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.util import compat +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +# We override the 'tuple' for a control flow op, so we keep python's +# existing 'tuple' for later use in this module. +_basetuple = tuple + + +# pylint: disable=protected-access + + +def _Identity(tensor, name=None): + """Return a tensor with the same shape and contents as the input tensor. + + Args: + tensor: A Tensor. + name: A name for this operation (optional). + + Returns: + A Tensor with the same type and value as the input Tensor. + """ + tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True) + # TODO(b/246438937): Remove this when we expand ResourceVariables into + # dt_resource tensors. + tensor = variable_utils.convert_variables_to_tensors(tensor) + if isinstance(tensor, tensor_lib.Tensor): + if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access + return gen_array_ops.ref_identity(tensor, name=name) + else: + return array_ops.identity(tensor, name=name) + elif isinstance(tensor, composite_tensor.CompositeTensor): + return nest.map_structure(_Identity, tensor, expand_composites=True) + else: + raise TypeError("'tensor' must be a Tensor or CompositeTensor. " + f"Received: {type(tensor)}.") + + +def _NextIteration(tensor, name=None): + tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True) + if isinstance(tensor, tensor_lib.Tensor): + if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access + return ref_next_iteration(tensor, name=name) + else: + return next_iteration(tensor, name=name) + elif isinstance(tensor, composite_tensor.CompositeTensor): + return nest.map_structure(_NextIteration, tensor, expand_composites=True) + else: + raise TypeError("'tensor' must be a Tensor or CompositeTensor. " + f"Received: {type(tensor)}.") + + +def _Enter(tensor, + frame_name, + is_constant=False, + parallel_iterations=10, + use_ref=True, + use_input_shape=True, + name=None): + """Creates or finds a child frame, and makes `tensor` available to it. + + The unique `frame_name` is used by the `Executor` to identify frames. If + `is_constant` is true, `tensor` is a constant in the child frame; otherwise + it may be changed in the child frame. At most `parallel_iterations` + iterations are run in parallel in the child frame. + + Args: + tensor: The tensor to be made available to the child frame. + frame_name: The name of the child frame. + is_constant: If true, the output is constant within the child frame. + parallel_iterations: The number of iterations allowed to run in parallel. + use_ref: If true, use ref_enter if tensor is of ref type. + use_input_shape: If true, set the result's shape based on tensor's shape. + name: A name for this operation (optional). + + Returns: + The same tensor as `tensor`. + + Raises: + ValueError: If any tensor in `tensor` has a less specific shape + than its corresponding shape in `shape_invariant`. + """ + tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True) + if isinstance(tensor, tensor_lib.Tensor): + if tensor.dtype._is_ref_dtype and use_ref: # pylint: disable=protected-access + result = gen_control_flow_ops.ref_enter( + tensor, frame_name, is_constant, parallel_iterations, name=name) + else: + result = gen_control_flow_ops.enter( + tensor, frame_name, is_constant, parallel_iterations, name=name) + if use_input_shape: + result.set_shape(tensor.get_shape()) + return result + elif isinstance(tensor, composite_tensor.CompositeTensor): + + def enter_component(t): + return _Enter(t, frame_name, is_constant, parallel_iterations, use_ref, + use_input_shape) + + return nest.map_structure(enter_component, tensor, expand_composites=True) + else: + raise TypeError("'tensor' must be a Tensor or CompositeTensor. " + f"Received: {type(tensor)}.") + + +def exit(tensor, name=None): # pylint: disable=redefined-builtin + """Exits the current frame to its parent frame. + + Exit makes its input `tensor` available to the parent frame. + + Args: + tensor: The tensor to be made available to the parent frame. + name: A name for this operation (optional). + + Returns: + The same tensor as `tensor`. + """ + tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True) + if isinstance(tensor, tensor_lib.Tensor): + if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access + return gen_control_flow_ops.ref_exit(tensor, name) + else: + return gen_control_flow_ops._exit(tensor, name) + elif isinstance(tensor, composite_tensor.CompositeTensor): + return nest.map_structure(exit, tensor, expand_composites=True) + else: + raise TypeError("'tensor' must be a Tensor or CompositeTensor. " + f"Received: {type(tensor)}.") + + +def switch(data, pred, dtype=None, name=None): + """Forwards `data` to an output determined by `pred`. + + If `pred` is false, the `data` input is forwarded to the first output. + Otherwise, the data goes to the second output. + + This op handles `Tensor`s and `IndexedSlices`. + + Args: + data: The tensor to be forwarded to the appropriate output. + pred: A scalar that specifies which output port will receive data. + dtype: Optional element type for the returned tensor. If missing, the type + is inferred from the type of `value`. + name: A name for this operation (optional). + + Returns: + `(output_false, output_true)`: If `pred` is true, data will be forwarded + to `output_true`, otherwise it goes to `output_false`. + """ + with ops.name_scope(name, "Switch", [data, pred]) as name: + data = ops.internal_convert_to_tensor_or_composite( + data, dtype=dtype, name="data", as_ref=True) + pred = ops.convert_to_tensor(pred, name="pred") + if isinstance(data, tensor_lib.Tensor): + return gen_control_flow_ops.switch(data, pred, name=name) + else: + if not isinstance(data, composite_tensor.CompositeTensor): + raise TypeError( + "'data' must be a Tensor or CompositeTensor. " + f"Received: {type(data)}.") + tensors = nest.flatten(data, expand_composites=True) + mapped = [gen_control_flow_ops.switch(tensor, pred) for tensor in tensors] + mapped_f, mapped_t = zip(*mapped) + return (nest.pack_sequence_as(data, mapped_f, expand_composites=True), + nest.pack_sequence_as(data, mapped_t, expand_composites=True)) + + +def _SwitchRefOrTensor(data, pred, name="Switch"): + """Forwards `data` to an output determined by `pred`. + + If `pred` is false, the `data` input is forwarded to the first output. + Otherwise, the data goes to the second output. + + This op handles `Tensor`s and `IndexedSlices`. + + Args: + data: The tensor to be forwarded to the appropriate output. + pred: A scalar that specifies which output port will receive data. + name: A name for this operation (optional). + + Returns: + `(output_false, output_true)`: If `pred` is true, data will be forwarded to + `output_true`, otherwise it goes to `output_false`. + + Raises: + TypeError: if data is not a Tensor or IndexedSlices + """ + data = ops.convert_to_tensor_or_composite(data, name="data") + # NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below + # addresses the following scenario. + # + # Assume you execute Optimizer.apply_gradients() in a branch of a cond(). + # + # 1. The update op is created inside a `with ops.colocate(var):` block + # + # 2. Some tensor `data` is captured and a switch is created in a + # `with ops.colocate_with(data):` block. + # + # with ops.colocate_with(var): + # with ops.colocate_with(data): + # op = ... + # + # var and data may be pinned to different devices, so we want to ops + # created within ops.colocate_with(data) to ignore the existing stack. + with ops.colocate_with(data, ignore_existing=True): + if isinstance(data, tensor_lib.Tensor): + if data.dtype._is_ref_dtype: # pylint: disable=protected-access + return ref_switch(data, pred, name=name) + return switch(data, pred, name=name) + + +def merge(inputs, name=None): + """Returns the value of an available element of `inputs`. + + This op tests each of the tensors in `inputs` in turn to determine if any of + them is available. If it finds an available tensor, it returns it and its + index in `inputs`. + + It is an error if more than one tensor in `inputs` is available. If no tensor + in `inputs` is available, the returned tensor and index are not set. + + This op handles both `Tensor`s and `IndexedSlices`. If inputs has a mix of + `Tensor`s and `IndexedSlices`, all inputs are converted to IndexedSlices + before merging. + + Args: + inputs: The input tensors, at most one of which is available. + name: A name for this operation (optional). + + Returns: + A tuple containing the chosen input tensor and its index in `inputs`. + + Raises: + ValueError: If any of the inputs is None, or inputs are IndexedSlices and + some but not all have a dense_shape property. + """ + if any(inp is None for inp in inputs): + raise ValueError("At least one of the merge inputs is None: %s" % inputs) + with ops.name_scope(name, "Merge", inputs) as name: + inputs = [ + ops.internal_convert_to_tensor_or_composite(inp, as_ref=True) + for inp in inputs + ] + if all(isinstance(v, tensor_lib.Tensor) for v in inputs): + if all(v.dtype._is_ref_dtype for v in inputs): # pylint: disable=protected-access + return gen_control_flow_ops.ref_merge(inputs, name) + else: + return gen_control_flow_ops.merge(inputs, name) + else: + # If there is a mix of tensors and indexed slices, then convert the + # tensors to indexed slices. + if all( + isinstance(v, (indexed_slices.IndexedSlices, tensor_lib.Tensor)) + for v in inputs): + inputs = math_ops._as_indexed_slices_list(inputs, optimize=False) + + for v in inputs: + if not isinstance(v, composite_tensor.CompositeTensor): + raise TypeError("Type %s not supported" % type(v)) + + for v in inputs[1:]: + nest.assert_same_structure(inputs[0], v, expand_composites=True) + + flat_inputs = [nest.flatten(v, expand_composites=True) for v in inputs] + merged_results = [ + gen_control_flow_ops.merge(component) + for component in zip(*flat_inputs) + ] + flat_merged = [tensor for (tensor, _) in merged_results] + chosen_index = merged_results[0][1] + merged_inputs = nest.pack_sequence_as( + inputs[0], flat_merged, expand_composites=True) + return (merged_inputs, chosen_index) + + +def _convert_tensorarray_to_flow(tensor_or_tensor_array): + if isinstance(tensor_or_tensor_array, tensor_array_ops.TensorArray): + return tensor_or_tensor_array.flow + else: + return tensor_or_tensor_array + + +def _convert_flow_to_tensorarray(tensor_or_tensor_array, tensor_or_flow): + if isinstance(tensor_or_tensor_array, tensor_array_ops.TensorArray): + return tensor_array_ops.build_ta_with_new_flow(tensor_or_tensor_array, + tensor_or_flow) + else: + return tensor_or_flow + + +def _convert_to_tensor_or_composite_or_tensorarray(var): + if isinstance(var, tensor_array_ops.TensorArray): + return var + return ops.convert_to_tensor_or_composite(var) + + +# TODO(xjun): replace this with is_subtype_of after it is landed. +def _ShapeLessThanOrEqual(shape1, shape2): + if shape2.dims is None: + return True + if shape1.ndims != shape2.ndims: + return False + for dim1, dim2 in zip(shape1.dims, shape2.dims): + if dim2.value is not None and dim1.value != dim2.value: + return False + return True + + +def _shape_invariant_to_type_spec(var, shape=None): + """Converts a shape invariant to a TypeSpec. + + If `var` is a TensorArray, it will first be converted to its flow. + + Args: + var: The tensor, tensor array or composite tensor whose shape is described + by the shape invariant. + shape: A `TypeSpec` or `TensorShape`. If `shape` is already a `TypeSpec`, + then it is simply returned as-is. + + Returns: + A `TypeSpec` for `var`, consistent with the given shape. + + Raises: + TypeError: If `shape` is a TypeSpec and not compatible with `var`. + TypeError: If `shape` is not None, a TypeSpec, or a TensorShape. + TypeError: If `shape` is a TensorShape, `var` is a CompositeTensor, and + `var` doesn't implement the `_shape_invariant_to_type_spec` method. + """ + var = _convert_tensorarray_to_flow(var) + if shape is None: + return type_spec.type_spec_from_value(var) + elif isinstance(shape, type_spec.TypeSpec): + if not shape.is_compatible_with(var): + raise TypeError("TypeSpec %r is not compatible with %r" % (shape, var)) + return shape + elif not isinstance(shape, tensor_shape.TensorShape): + raise TypeError( + "'shape' must be one of TypeSpec, TensorShape or None. " + f"Received: {type(shape)}") + + if isinstance(var, tensor_lib.Tensor): + return tensor_lib.TensorSpec(shape, var.dtype) + else: + try: + return var._shape_invariant_to_type_spec(shape) # pylint: disable=protected-access + except NotImplementedError as e: + raise TypeError( + f"To describe or constrain a {type(var).__name__}, use a " + f"{type(var._type_spec).__name__} instead of a TensorShape.") from e # pylint: disable=protected-access + + +def _EnforceShapeInvariant(merge_var, next_var): + """Check if the shapes of the loops variables are invariants. + + Args: + merge_var: The tensor representing the initial values of the loop + variables. + next_var: The tensor representing the values of the loop variables + after one loop iteration. + + Raises: + ValueError: If any tensor in `merge_var` has a more specific shape than + its corresponding tensor in `next_var`. + """ + if isinstance(merge_var, tensor_lib.Tensor): + m_shape = merge_var.get_shape() + n_shape = next_var.get_shape() + if not _ShapeLessThanOrEqual(n_shape, m_shape): + enter = merge_var.op.inputs[0].op + assert util.IsLoopEnter(enter) + input_t = enter.inputs[0] + raise ValueError( + "Input tensor '%s' enters the loop with shape %s, but has shape %s " + "after one iteration. To allow the shape to vary across iterations, " + "use the `shape_invariants` argument of tf.while_loop to specify a " + "less-specific shape." % (input_t.name, input_t.shape, n_shape)) + else: + raise TypeError("'merge_var' must be a Tensor. " + f"Received: {type(merge_var)}.") + + +def _AddNextAndBackEdge(m, v, enforce_shape_invariant=True): + """Add NextIteration and back edge from v to m.""" + if isinstance(m, tensor_lib.Tensor): + v = ops.convert_to_tensor(v) + v = _NextIteration(v) + if enforce_shape_invariant: + # Make sure the shapes of loop outputs are correct. We do this before + # calling _update_input, which will raise a less-helpful error message if + # the types don't match. + # TODO(skyewm): call this for other cases below (needs testing) + _EnforceShapeInvariant(m, v) + m.op._update_input(1, v) # pylint: disable=protected-access + elif isinstance(m, composite_tensor.CompositeTensor): + # pylint: disable=protected-access + def update_component(m_component, v_component): + m_component.op._update_input(1, v_component) + + if isinstance(m, indexed_slices.IndexedSlices): + v = math_ops._as_indexed_slices(v, optimize=False) + # pylint: enable=protected-access + v = _NextIteration(v) + return nest.map_structure(update_component, m, v, expand_composites=True) + else: + raise TypeError("'m' must be a Tensor or CompositeTensor. " + f"Received: {type(m)}.") + return v + + +class ControlFlowContext(metaclass=abc.ABCMeta): + """The base class for control flow context. + + The usage pattern is a sequence of (Enter, Exit) followed by a final + ExitResult. + + We maintain the following state for control flow contexts during graph + construction: + 1. graph has _control_flow_context: the current context used to + construct new nodes. Changed by ctxt.Enter() and ctxt.Exit() + 2. op has _control_flow_context: the context to which the op belongs. + Set at the time the op is created. Immutable. + 3. A ControlFlowContext has _outer_context: the context in which this + context is created. Set at the time a context is created. Immutable. + 4. A ControlFlowContext has _context_stack. + Pushed and popped by ctxt.Enter() and ctxt.Exit() + """ + + def __init__(self, values_def=None, import_scope=None): + self._nested_contexts = [] + self._outer_context = ops.get_default_graph()._get_control_flow_context() + if self._outer_context: + self._outer_context._nested_contexts.append(self) # pylint: disable=protected-access + self._context_stack = [] + if values_def: + self._init_values_from_proto(values_def, import_scope=import_scope) + else: + # The names of tensors that have been already seen in this context. + self._values = set() + # The keys are the names of tensors referenced by but external to this + # context. Each value is the Tensor that should be used by this context to + # access the key value (e.g. a switch output guarding a cond input value). + self._external_values = {} + + def _init_values_from_proto(self, values_def, import_scope=None): + """Initializes values and external_values from `ValuesDef` protocol buffer. + + Args: + values_def: `ValuesDef` protocol buffer. + import_scope: Optional `string`. Name scope to add. + """ + assert isinstance(values_def, control_flow_pb2.ValuesDef) + self._values = set( + ops.prepend_name_scope(value, import_scope) + for value in values_def.values) + g = ops.get_default_graph() + self._external_values = {} + for k, v in values_def.external_values.items(): + k = ops.prepend_name_scope(k, import_scope) + self._external_values[k] = g.as_graph_element( + ops.prepend_name_scope(v, import_scope)) + op_names = set([ + op.split(":")[0] + for op in self._values - set(self._external_values.keys()) + ]) + for op in op_names: + # pylint: disable=protected-access + g.as_graph_element(op)._set_control_flow_context(self) + # pylint: enable=protected-access + + @property + def name(self): + return self._name + + @property + def outer_context(self): + """Return the context containing this context.""" + return self._outer_context + + @property + def grad_state(self): + raise NotImplementedError("Abstract method") + + @property + def back_prop(self): + raise NotImplementedError("Abstract method") + + @abc.abstractmethod + def to_control_flow_context_def(self, context_def, export_scope=None): + """Serializes this into `context_def`. + + Args: + context_def: a `ControlFlowContextDef` protocol buffer. + export_scope: Optional `string`. Name scope to remove. + """ + raise NotImplementedError("Abstract method") + + def _to_values_def(self, export_scope=None): + """Converts the values to a `ValuesDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `ValuesDef` protocol buffer. + """ + values_def = control_flow_pb2.ValuesDef() + values_def.values.extend( + [ops.strip_name_scope(v, export_scope) for v in sorted(self._values)]) + for k, v in self._external_values.items(): + k = ops.strip_name_scope(k, export_scope) + values_def.external_values[k] = ops.strip_name_scope(v.name, export_scope) + return values_def + + def AddName(self, name): + self._values.add(name) + + # pylint: disable=protected-access + def Enter(self): + """Enter this control flow context.""" + graph = ops.get_default_graph() + self._context_stack.append(graph._get_control_flow_context()) + graph._set_control_flow_context(self) + + def Exit(self): + """Exit this control flow context.""" + graph = ops.get_default_graph() + last_context = self._context_stack.pop() + graph._set_control_flow_context(last_context) + + def EnterGradientColocation(self, op: ops.Operation, gradient_uid): + """Start building a gradient colocated with an op.""" + if self._outer_context: + self._outer_context.EnterGradientColocation(op, gradient_uid) + + def ExitGradientColocation(self, op: ops.Operation, gradient_uid): + """Start building a gradient colocated with an op.""" + if self._outer_context: + self._outer_context.ExitGradientColocation(op, gradient_uid) + + def ExitResult(self, result): + """Make a list of tensors available in the outer context.""" + if self._outer_context: + def fn(x): + self._outer_context.AddName(x.name) + return x + nest.map_structure(fn, result, expand_composites=True) + + def GetWhileContext(self): + """Return the while context containing this context.""" + if self._outer_context: + return self._outer_context.GetWhileContext() + return None + + def _RemoveExternalControlEdges(self, op: ops.Operation): + """Remove any external control dependency on this op.""" + while_ctxt = self.GetWhileContext() + # A control input of `op` is internal if it is in the same while + # loop context as the enclosing while loop context of self. + if while_ctxt is None: + internal_control_inputs, external_control_inputs = op.control_inputs, [] + else: + internal_control_inputs, external_control_inputs = [], [] + for x in op.control_inputs: + ctxt = util.GetOutputContext(x) + if ctxt is not None and ctxt.GetWhileContext() == while_ctxt: + internal_control_inputs.append(x) + else: + external_control_inputs.append(x) + if len(internal_control_inputs) != len(op.control_inputs): + # TODO(mdan): perhaps there should be a replace_control_inputs() + op._remove_all_control_inputs() + op._add_control_inputs(internal_control_inputs) + return internal_control_inputs, external_control_inputs + + # pylint: enable=protected-access + + def AddInnerOp(self, op: ops.Operation): + """Notifies a scope about an operator added to an inner scope.""" + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def GetControlPivot(self): + """Returns the pivot node for this context, or None.""" + return None + + def IsWhileContext(self): + return False + + def IsCondContext(self): + return False + + def IsXLAContext(self): + return False + + def __str__(self): + return self.name + + +class CondContext(ControlFlowContext): + """The context for the conditional construct.""" + + def __init__(self, + pred=None, + pivot=None, + branch=None, + name="cond_text", + context_def=None, + import_scope=None): + """Creates a `CondContext`. + + Args: + pred: The `boolean` tensor for the conditional predicate. + pivot: The predicate tensor in this branch. + branch: 0 or 1 representing this branch. + name: Name of the `CondContext` python object. + context_def: Optional `ContextDef` protocol buffer to initialize the + `CondContext` object from. + import_scope: Optional `string`. Name scope to add. Only used when + initialing from protocol buffer. + """ + self._name = ops.get_default_graph().unique_name(name) + + if context_def: + self._init_from_proto(context_def, import_scope=import_scope) + else: + # Initializes the default fields. + ControlFlowContext.__init__(self) + self._pred = pred # The boolean tensor for the cond predicate + self._pivot = pivot # The predicate tensor in this branch + self._branch = branch # 0 or 1 representing this branch + + # Values considered to have been already seen in this context. pred is not + # included in this context. + self._values.add(pred.name) + self._external_values[pred.name] = pred + self._values.add(pivot.name) + pivot.op._set_control_flow_context(self) # pylint: disable=protected-access + + def _init_from_proto(self, context_def, import_scope=None): + """Creates a new `CondContext` from protocol buffer. + + Args: + context_def: `CondContextDef` protocol buffer. + import_scope: Optional `string`. Name scope to add. + """ + assert isinstance(context_def, control_flow_pb2.CondContextDef) + # Create from context_def. + g = ops.get_default_graph() + self._name = ops.prepend_name_scope(context_def.context_name, import_scope) + self._pred = g.as_graph_element( + ops.prepend_name_scope(context_def.pred_name, import_scope)) + self._pivot = g.as_graph_element( + ops.prepend_name_scope(context_def.pivot_name, import_scope)) + self._branch = context_def.branch + super(CondContext, self).__init__( + values_def=context_def.values_def, import_scope=import_scope) + + @property + def pred(self): + return self._pred + + @property + def pivot(self): + return self._pivot + + @property + def branch(self): + return self._branch + + @property + def grad_state(self): + if self.GetWhileContext(): + return self.GetWhileContext().grad_state + return None + + @property + def back_prop(self): + if self.GetWhileContext(): + return self.GetWhileContext().back_prop + return False + + def GetControlPivot(self): + return self._pivot + + def to_proto(self, export_scope=None): + """Converts a `CondContext` to a `CondContextDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `CondContextDef` protocol buffer. + """ + if (export_scope is None or self.name.startswith(export_scope)): + context_def = control_flow_pb2.CondContextDef() + context_def.context_name = ops.strip_name_scope(self.name, export_scope) + context_def.pred_name = ops.strip_name_scope(self._pred.name, + export_scope) + context_def.pivot_name = ops.strip_name_scope(self._pivot.name, + export_scope) + context_def.branch = self._branch + context_def.values_def.MergeFrom( + super(CondContext, self)._to_values_def(export_scope)) + for nested in self._nested_contexts: + nested_def = context_def.nested_contexts.add() + nested.to_control_flow_context_def(nested_def) + + return context_def + else: + return None + + @staticmethod + def from_proto(context_def, import_scope=None): + """Returns a `CondContext` object created from `context_def`.""" + ret = CondContext(context_def=context_def, import_scope=import_scope) + + ret.Enter() + for nested_def in context_def.nested_contexts: + from_control_flow_context_def(nested_def, import_scope=import_scope) + ret.Exit() + return ret + + def to_control_flow_context_def(self, context_def, export_scope=None): + context_def.cond_ctxt.CopyFrom(self.to_proto(export_scope=export_scope)) + + def AddValue(self, val): + """Add `val` to the current context and its outer context recursively.""" + if val.name in self._values: + # Use the real value if it comes from outer context. This is needed in + # particular for nested conds. + result = self._external_values.get(val.name) + result = val if result is None else result + else: + result = val + self._values.add(val.name) + if self._outer_context: + result = self._outer_context.AddValue(val) + self._values.add(result.name) + self._external_values[result.name] = result + with ops.control_dependencies(None): + result = _SwitchRefOrTensor(result, self._pred)[self._branch] + if self._outer_context: + self._outer_context.AddInnerOp(result.op) + + result.op.graph.prevent_fetching(result.op) + # pylint: disable=protected-access + result.op._set_control_flow_context(self) + # pylint: enable=protected-access + + # Mark Switch output as seen by this context and any outer contexts, + # just like what we do for normal op outputs in _AddOpInternal() below. + ctxt = self + while ctxt is not None: + # pylint: disable=protected-access + ctxt._values.add(result.name) + ctxt = ctxt._outer_context + # pylint: enable=protected-access + + self._external_values[val.name] = result + return result + + def AddOp(self, op: ops.Operation): + self._AddOpInternal(op) + + def _AddOpInternal(self, op: ops.Operation): + """Add `op` to the current context.""" + if not op.inputs: + # If we're in a while loop, remove any control inputs from outside the + # loop. + self._RemoveExternalControlEdges(op) + + if not any( + util.OpInContext(input_op, self) for input_op in op.control_inputs): + # pylint: disable=protected-access + op._add_control_input(self._pivot.op) + # pylint: enable=protected-access + else: + # Make each input to 'op' available in this CondContext. If an input is + # already part of this context there's nothing to do, but if it's + # external, AddValue() will handle adding the appropriate Switch node and + # other bookkeeping. + for index in range(len(op.inputs)): + x = op.inputs[index] + if op.type == "Merge" and x.op.type == "NextIteration": + # Edge case: if we're importing a while loop inside this CondContext, + # AddValue() will not correctly handle the NextIteration inputs to + # Merge node. The problem is that the NextIteration should also be + # part of this context, but if we're importing it won't have been + # processed and added to the context yet, so AddValue() will try to + # add a Switch which results in an invalid graph. Instead, we use the + # NextIteration input as-is here, and it will eventually be added to + # the context via AddOp(). + real_x = x + else: + real_x = self.AddValue(x) + if real_x != x: + # pylint: disable=protected-access + op._update_input(index, real_x) + # pylint: enable=protected-access + # Remove any external control dependency on this op. + self._RemoveExternalControlEdges(op) + # pylint: disable=protected-access + if op.graph._is_function(op.type) or op.type == "SymbolicGradient": + op._add_control_input(self._pivot.op) + # pylint: enable=protected-access + + # Mark op's outputs as seen by this context and any outer contexts. + output_names = [x.name for x in op.outputs] + ctxt = self + while ctxt is not None: + # pylint: disable=protected-access + ctxt._values.update(output_names) + ctxt = ctxt._outer_context + # pylint: enable=protected-access + + if self._outer_context or not util.IsLoopExit(op): + op.graph.prevent_fetching(op) + + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def _ProcessOutputTensor(self, val): + """Process an output tensor of a conditional branch.""" + real_val = val + if val.name not in self._values: + # Handle the special case of lambda: x + self._values.add(val.name) + if self._outer_context: + real_val = self._outer_context.AddValue(val) + self._values.add(real_val.name) + self._external_values[real_val.name] = real_val + real_val = _SwitchRefOrTensor(real_val, self._pred)[self._branch] + self._external_values[val.name] = real_val + else: + external_val = self._external_values.get(val.name) + if external_val is not None: + real_val = external_val + return real_val + + def _BuildCondTensor(self, v): + if isinstance(v, ops.Operation): + # Use pivot as the proxy for this op. + return with_dependencies([v], self._pivot) + else: + v = nest.map_structure( + _convert_tensorarray_to_flow, v, expand_composites=True) + return self._ProcessOutputTensor(ops.convert_to_tensor(v)) + + def BuildCondBranch(self, fn): + """Add the subgraph defined by fn() to the graph.""" + pre_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + original_result = fn() + post_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + if len(post_summaries) > len(pre_summaries): + new_summaries = post_summaries[len(pre_summaries):] + summary_ref = ops.get_collection_ref(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + summary_ref[:] = pre_summaries + with ops.control_dependencies(new_summaries): + if original_result is None: + return no_op(), None + elif not isinstance(original_result, ops.Operation): + original_result = variable_utils.convert_variables_to_tensors( + original_result) + original_result = nest.map_structure( + array_ops.identity, original_result, expand_composites=True) + if original_result is None: + return None, None + + original_result = variable_utils.convert_variables_to_tensors( + original_result) + result = nest.map_structure( + self._BuildCondTensor, original_result, expand_composites=True) + if not isinstance(result, (list, _basetuple)): + result = [result] + return original_result, result + + def IsCondContext(self): + return True + + +# pylint: enable=g-doc-args +# pylint: enable=redefined-outer-name + + +def _resource_safe_shape(t): + """Returns the shape of t or the variable it points to.""" + if t.dtype == dtypes.resource: + while t.op.inputs: + t = t.op.inputs[0] + return tensor_shape.TensorShape(t.op.get_attr("shape")) + return array_ops.shape_internal(t, optimize=False) + + +# TODO(yuanbyu): Consider having a unified notion of context for +# not only conditionals and loops but also control dependency and +# subgraphs. +class WhileContext(ControlFlowContext): + """The context for the loop construct.""" + + def __init__(self, + maximum_iterations=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name="while_context", + grad_state=None, + context_def=None, + import_scope=None): + """"Creates a `WhileContext`. + + Args: + maximum_iterations: Optional upper bound on number of loop iterations. + parallel_iterations: The number of iterations allowed to run in parallel. + back_prop: Whether backprop is enabled for this while loop. + swap_memory: Whether GPU-CPU memory swap is enabled for this loop. + name: Optional name prefix for the returned tensors. + grad_state: The gradient loop state. + context_def: Optional `WhileContextDef` protocol buffer to initialize the + `Whilecontext` python object from. + import_scope: Optional `string`. Name scope to add. Only used when + initialing from protocol buffer. + """ + if context_def: + self._init_from_proto(context_def, import_scope=import_scope) + else: + ControlFlowContext.__init__(self) + self._init_from_args(maximum_iterations, parallel_iterations, back_prop, + swap_memory, name) + # The gradient loop state. + self._grad_state = grad_state + + def _init_from_args(self, maximum_iterations, parallel_iterations, back_prop, + swap_memory, name): + """Creates a new `WhileContext` from arguments. + + Args: + maximum_iterations: Optional upper bound on number of loop iterations. + parallel_iterations: The number of iterations allowed to run in parallel. + back_prop: Whether backprop is enabled for this while loop. + swap_memory: Whether GPU-CPU memory swap is enabled for this loop. + name: Optional name prefix for the returned tensors. + + Raises: + ValueError: If `parallel_iterations` has invalid value. + """ + if not isinstance(parallel_iterations, int) or (parallel_iterations <= 0): + raise ValueError("'parallel_iterations' must be a positive integer: " + "%s" % parallel_iterations) + self._name = ops.get_default_graph().unique_name(name) + self._maximum_iterations = maximum_iterations + self._parallel_iterations = parallel_iterations + self._back_prop = back_prop + self._swap_memory = swap_memory + # We use this node to control constants created by the pred lambda. + self._pivot_for_pred = None + # We use this node to control constants created by the body lambda. + self._pivot_for_body = None + # The boolean tensor for loop termination condition. Used in code + # generation for gradient computation + self._pivot = None + # The list of exit tensors for loop variables. + self._loop_exits = [] + # The list of enter tensors for loop variables. + self._loop_enters = [] + self._graph = ops.get_default_graph() + + def _init_from_proto(self, context_def, import_scope=None): + """Creates a new `WhileContext` from protocol buffer. + + Args: + context_def: `WhileContextDef` protocol buffer. + import_scope: Optional `string`. Name scope to add. + """ + assert isinstance(context_def, control_flow_pb2.WhileContextDef) + # Create from context_def. + g = ops.get_default_graph() + self._name = ops.prepend_name_scope(context_def.context_name, import_scope) + if context_def.maximum_iterations_name: + self._maximum_iterations = g.as_graph_element( + ops.prepend_name_scope(context_def.maximum_iterations_name, + import_scope)) + else: + self._maximum_iterations = None + self._parallel_iterations = context_def.parallel_iterations + self._back_prop = context_def.back_prop + self._swap_memory = context_def.swap_memory + self._pivot_for_pred = g.as_graph_element( + ops.prepend_name_scope(context_def.pivot_for_pred_name, import_scope)) + # We use this node to control constants created by the body lambda. + self._pivot_for_body = g.as_graph_element( + ops.prepend_name_scope(context_def.pivot_for_body_name, import_scope)) + # The boolean tensor for loop termination condition. Used in code + # generation for gradient computation. + self._pivot = g.as_graph_element( + ops.prepend_name_scope(context_def.pivot_name, import_scope)) + # The list of exit tensors for loop variables. + self._loop_exits = [ + g.as_graph_element(ops.prepend_name_scope(exit_name, import_scope)) + for exit_name in context_def.loop_exit_names + ] + # The list of enter tensors for loop variables. + self._loop_enters = [ + g.as_graph_element(ops.prepend_name_scope(enter_name, import_scope)) + for enter_name in context_def.loop_enter_names + ] + super(WhileContext, self).__init__( + values_def=context_def.values_def, import_scope=import_scope) + + # import_scope causes self.name to be different from the original serialized + # context's name. Rewrite "frame_name" attrs with the new name. + if import_scope: + for tensor_name in self._values: + op = g.as_graph_element(tensor_name).op + if util.IsLoopEnter(op): + # pylint: disable=protected-access + op._set_attr("frame_name", + attr_value_pb2.AttrValue(s=compat.as_bytes(self.name))) + # pylint: enable=protected-access + self._graph = ops.get_default_graph() + + @property + def maximum_iterations(self): + """The maximum number of iterations that will be executed.""" + return self._maximum_iterations + + @property + def parallel_iterations(self): + """The number of iterations allowed to run in parallel.""" + return self._parallel_iterations + + @property + def back_prop(self): + """True iff backprop is enabled for this while loop.""" + return self._back_prop + + @property + def swap_memory(self): + """True iff GPU-CPU memory swap is enabled for this while loop.""" + return self._swap_memory + + @property + def pivot(self): + """The boolean tensor representing the loop termination condition.""" + return self._pivot + + @property + def loop_enters(self): + """The list of enter tensors for loop variables.""" + return self._loop_enters + + @property + def loop_exits(self): + """The list of exit tensors for loop variables.""" + return self._loop_exits + + @property + def grad_state(self): + """The gradient loop state.""" + return self._grad_state + + def to_proto(self, export_scope=None): + """Converts a `WhileContext` to a `WhileContextDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `WhileContextDef` protocol buffer. + """ + if (export_scope is None or self.name.startswith(export_scope)): + context_def = control_flow_pb2.WhileContextDef() + context_def.context_name = ops.strip_name_scope(self.name, export_scope) + context_def.parallel_iterations = self._parallel_iterations + if self._maximum_iterations is not None: + context_def.maximum_iterations_name = ops.strip_name_scope( + self._maximum_iterations.name, export_scope) + context_def.back_prop = self._back_prop + context_def.swap_memory = self._swap_memory + context_def.pivot_for_pred_name = ops.strip_name_scope( + self._pivot_for_pred.name, export_scope) + context_def.pivot_for_body_name = ops.strip_name_scope( + self._pivot_for_body.name, export_scope) + context_def.pivot_name = ops.strip_name_scope(self._pivot.name, + export_scope) + context_def.loop_exit_names.extend([ + ops.strip_name_scope(l.name, export_scope) for l in self._loop_exits + ]) + context_def.loop_enter_names.extend([ + ops.strip_name_scope(l.name, export_scope) for l in self._loop_enters + ]) + context_def.values_def.MergeFrom( + super(WhileContext, self)._to_values_def(export_scope=export_scope)) + for nested in self._nested_contexts: + nested_def = context_def.nested_contexts.add() + nested.to_control_flow_context_def(nested_def) + + return context_def + else: + return None + + def to_control_flow_context_def(self, context_def, export_scope=None): + context_def.while_ctxt.CopyFrom(self.to_proto(export_scope=export_scope)) + + @staticmethod + def from_proto(context_def, import_scope=None): + """Returns a `WhileContext` object created from `context_def`. + + Args: + context_def: A `WhileContextDef` protocol buffer. + import_scope: Optional `string`. Name scope to add. + + Returns: + A `WhileContext` Python object. + """ + ret = WhileContext(context_def=context_def, import_scope=import_scope) + ret.Enter() + for nested_def in context_def.nested_contexts: + from_control_flow_context_def(nested_def, import_scope=import_scope) + ret.Exit() + return ret + + def GetWhileContext(self): + return self + + def GetControlPivot(self): + if self._pivot_for_body is not None: + return self._pivot_for_body + return self._pivot_for_pred + + def AddValue(self, val): + """Add `val` to the current context and its outer context recursively.""" + result = val + new_value = val.name not in self._values + # Don't treat ops in this context as new values. Usually all known values + # are in self._values, except when we're importing a while loop inside this + # WhileContext. Since there's a cycle in this case, `val` may be part of the + # imported while loop but not yet processed by this context and added to + # self._values in _AddOpInternal. We only want to process external input + # tensors to the while loop here. + new_value &= val.op._control_flow_context is not self # pylint: disable=protected-access + if new_value: + self._values.add(val.name) + + # If we are in a grad context and val is from its forward context, + # use GetRealValue(), which adds the logic to save the history of + # val in forward. + grad_ctxt = ops.get_default_graph()._get_control_flow_context() + if grad_ctxt: + grad_ctxt = grad_ctxt.GetWhileContext() + if grad_ctxt.grad_state: + forward_ctxt = util.GetWhileContext(val.op) + if util.IsLoopExit(val.op): + forward_ctxt = forward_ctxt.outer_context + if forward_ctxt: + forward_ctxt = forward_ctxt.GetWhileContext() + if forward_ctxt == grad_ctxt.grad_state.forward_context: + real_val = grad_ctxt.grad_state.GetRealValue(val) + self._external_values[val.name] = real_val + return real_val + + if self._outer_context is not None: + result = self._outer_context.AddValue(val) + # Create an Enter to make `result` known to this loop context. + with ops.control_dependencies(None): + enter = _Enter( + result, + self._name, + is_constant=True, + parallel_iterations=self._parallel_iterations) + enter.graph.prevent_feeding(enter) + if self._outer_context: + self._outer_context.AddInnerOp(enter.op) + # Fix the control inputs and control flow context of these enter ops. + self._FixControlInputsAndContext([enter]) + + # Add `enter` in this context. + self._values.add(enter.name) + self._external_values[val.name] = enter + result = enter + else: + actual_val = self._external_values.get(val.name) + if actual_val is not None: + result = actual_val + return result + + def AddOp(self, op: ops.Operation): + """Add `op` to the current context.""" + # For a reduction op, if op is in a grad context and its input is from + # its forward context, moving op to the forward context means we would + # store the tensor after the reduction as opposed to the tensor before + # reduction, and therefore could significantly reduce memory consumption. + # For now, we do this only for a few ops. + # + # If in XLA context, do not move constant ops to forward pass as pushing to + # and popping from a stack removes the constant property of an op and breaks + # XLA compilation, which requires certain inputs to be constant for certain + # ops. + if not util.IsInXLAContext(op) and op.type in {"Shape", "Size", "Rank"}: + grad_ctxt = ops.get_default_graph()._get_control_flow_context() + if grad_ctxt: + grad_ctxt = grad_ctxt.GetWhileContext() + if grad_ctxt.grad_state: + op_input_forward_ctxt = util.GetWhileContext(op.inputs[0].op) + if op_input_forward_ctxt == grad_ctxt.grad_state.forward_context: + op_input_ctxt = op.inputs[0].op._get_control_flow_context() + op._set_control_flow_context(op_input_ctxt) + op_input_ctxt._AddOpInternal(op) + return + self._AddOpInternal(op) + + # pylint: disable=g-doc-args + def _AddOpInternal(self, op: ops.Operation): + """Add `op` to the current context. + + We move any external control dependencies of the op to the loop pivot, to + ensure they get executed. + """ + # This is needed to prevent frame mismatch errors where there are Const + # nodes inside tf.function in v1 while_loop and inlining is turned on. + if op.type in ["PartitionedCall", "StatefulPartitionedCall"]: + op._add_control_input(self.GetControlPivot().op) # pylint: disable=protected-access + if not op.inputs: + # Remove any external control dependency on this op + control_inputs, external_inputs = self._RemoveExternalControlEdges(op) + # Add a control edge from the control pivot to this op. + if not control_inputs: + # pylint: disable=protected-access + op._add_control_input(self.GetControlPivot().op) + # pylint: enable=protected-access + for x in op.outputs: + self._values.add(x.name) + else: + for index in range(len(op.inputs)): + x = op.inputs[index] + real_x = self.AddValue(x) + if real_x != x: + op._update_input(index, real_x) # pylint: disable=protected-access + # Remove any external control dependency on this op. + _, external_inputs = self._RemoveExternalControlEdges(op) + # Add a control dependency to prevent loop invariants from + # enabling ops that should not be executed. + self._MaybeAddControlDependency(op) + for x in op.outputs: + self._values.add(x.name) + if external_inputs: + # Use an identity to pull control inputs as data inputs. Note that we + # ignore ops which don't have outputs. TODO(apassos): fix that + with ops.control_dependencies(None): + self.Enter() + external_inputs = [ + array_ops.identity(x.outputs[0]).op + for x in external_inputs + if x.outputs + ] + self.Exit() + op._add_control_inputs(external_inputs) # pylint: disable=protected-access + if self._outer_context or not util.IsLoopExit(op): + op.graph.prevent_fetching(op) + for x in op.outputs: + op.graph.prevent_feeding(x) + + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def _MaybeAddControlDependency(self, op: ops.Operation): + """Add a control input to the op if it only depends on loop invariants.""" + + def _IsOpFree(op): + """Determines if `op` needs a control dependency.""" + if op.control_inputs: + return False + # pylint: disable=protected-access + if op.graph._is_function(op.type) or op.type == "SymbolicGradient": + return True + # pylint: enable=protected-access + for x in op.inputs: + if not util.IsLoopConstantEnter(x.op): + return False + return True + + if _IsOpFree(op): + # pylint: disable=protected-access + op._add_control_input(self.GetControlPivot().op) + # pylint: enable=protected-access + + def AddForwardLoopCounter(self, outer_grad_state): + """Adds a loop that counts the number of iterations. + + This is added to the forward loop at the time when we start to + create the loop for backprop gradient computation. Called in + the outer context of this forward context. + + The pseudocode is: + `n = 0; while (_pivot) { n++; }` + + Note that a control dependency is added to `n` to ensure the correct + execution order of stack push ops. + + Args: + outer_grad_state: The outer grad state. None if not nested. + + Returns: + The number of iterations taken by the forward loop and the loop index. + """ + n = constant_op.constant(0, name="f_count") + if outer_grad_state is not None: + # Force the stack pushes of i-th execution of an inner loop to be ordered + # before the pushes of (i+1)-th execution of the same inner loop. + outer_add_op = outer_grad_state.forward_index.op.inputs[0].op + n.op._add_control_input(outer_add_op) # pylint: disable=protected-access + + self.Enter() + self.AddName(n.name) + enter_n = _Enter( + n, + self._name, + is_constant=False, + parallel_iterations=self._parallel_iterations, + name="f_count") + self.loop_enters.append(enter_n) + + merge_n = merge([enter_n, enter_n])[0] + switch_n = switch(merge_n, self._pivot) + + index = math_ops.add(switch_n[1], 1) + next_n = _NextIteration(index) + merge_n.op._update_input(1, next_n) + + total_iterations = exit(switch_n[0], name="f_count") + self.loop_exits.append(total_iterations) + self.ExitResult([total_iterations]) + self.Exit() + return total_iterations, next_n + + def AddBackpropLoopCounter(self, count, outer_grad_state): + """Add the backprop loop that controls the iterations. + + This is added to the backprop loop. It is used to control the loop + termination of the backprop loop. Called in the outer context of + this grad context. + + The pseudocode is: + `n = count; while (n >= 1) { n--; }` + + Note that a control dependency is added to `final_zero` to ensure the + correct execution order of stack pop ops. + + Args: + count: The number of iterations for backprop. + outer_grad_state: The outer grad state. None if not nested. + + Returns: + The loop index. + """ + in_separate_functions = count.graph is not ops.get_default_graph() + if in_separate_functions: + # Brings the count into this graph + count = array_ops.identity(count) + else: + # TODO(apassos) XLA expects this constant to be created outside the loop, + # so doing that for now. + one = constant_op.constant(1, name="b_count") + + self.Enter() + self.AddName(count.name) + enter_count = _Enter( + count, + self._name, + is_constant=False, + parallel_iterations=self._parallel_iterations, + name="b_count") + self.loop_enters.append(enter_count) + + merge_count = merge([enter_count, enter_count])[0] + self._pivot_for_pred = merge_count + + if in_separate_functions: + one = constant_op.constant(1, name="b_count") + pred = math_ops.greater_equal(merge_count, one) + self._pivot = loop_cond(pred, name="b_count") + switch_count = switch(merge_count, self._pivot) + + index = math_ops.subtract(switch_count[1], one) + self._pivot_for_body = index + next_count = _NextIteration(index) + merge_count.op._update_input(1, next_count) + + final_zero = exit(switch_count[0], name="b_count") + self.loop_exits.append(final_zero) + if outer_grad_state is not None: + # Force the stack pops of i-th execution of an inner loop to be ordered + # before the pops of (i+1)-th execution of the same inner loop. + # pylint: disable=protected-access + outer_grad_state.grad_sync._add_control_input(final_zero.op) + # pylint: enable=protected-access + + self.ExitResult([final_zero]) + self.Exit() + return next_count + + def AddBackpropAccumulator(self, op: ops.Operation, grad): + """Add an accumulation loop for every loop invariant. + + This is added to the backprop loop. It is used to accumulate partial + gradients within each loop iteration. Called when in the gradient while + context. + + The pseudocode is: + ``` + acc = 0.0; + while (_pivot) { + acc += grad; + } + ``` + + Args: + op: The Enter op for a loop invariant. + grad: The partial gradient of an iteration for a loop invariant. + + Returns: + The gradient for a loop invariant. + """ + self.Exit() + # Create a zeros tensor with the right shape for acc. If we don't + # know the full shape statically, we will have to get the shape + # dynamically from the forward inference. Getting the shape right + # for the zeros is only needed for the base case when the loop exits + # without running any iterations. + shape = grad.get_shape() + if shape.is_fully_defined(): + if self.outer_context: + self.outer_context.Enter() + acc = constant_op.constant(0, grad.dtype, shape=shape, name="b_acc") + if self.outer_context: + self.outer_context.Exit() + else: + value = op.inputs[0] + if (isinstance(self.outer_context, WhileContext) and + self.outer_context.grad_state is not None): + # We are in a nested while loop. + forward_ctxt = self.grad_state.forward_context + forward_ctxt.outer_context.Enter() + zeros_shape = array_ops.shape_internal(value, optimize=False) + forward_ctxt.outer_context.Exit() + outer_grad_state = self.grad_state.outer_grad_state + history_zeros_shape = outer_grad_state.AddForwardAccumulator( + zeros_shape) + self.outer_context.Enter() + real_shape = outer_grad_state.AddBackpropAccumulatedValue( + history_zeros_shape, zeros_shape) + acc = array_ops.zeros(real_shape, grad.dtype) + self.outer_context.Exit() + else: + if self.outer_context: + self.outer_context.Enter() + zeros_shape = array_ops.shape_internal(value, optimize=False) + acc = array_ops.zeros(zeros_shape, grad.dtype) + if self.outer_context: + self.outer_context.Exit() + + self.Enter() + self.AddName(acc.name) + enter_acc = _Enter( + acc, + self._name, + is_constant=False, + parallel_iterations=self._parallel_iterations, + name="b_acc") + self.loop_enters.append(enter_acc) + + merge_acc = merge([enter_acc, enter_acc], name="b_acc")[0] + switch_acc_false, switch_acc_true = switch(merge_acc, self._pivot) + + add_acc = math_ops.add(switch_acc_true, grad) + next_acc = _NextIteration(add_acc) + merge_acc.op._update_input(1, next_acc) # pylint: disable=protected-access + + result_acc = exit(switch_acc_false, name="b_acc") + self.loop_exits.append(result_acc) + self.ExitResult([result_acc]) + return result_acc + + def AddBackpropIndexedSlicesAccumulator(self, op: ops.Operation, grad): + """This is used for accumulating gradients that are IndexedSlices. + + This is essentially the equivalent of AddBackpropAccumulator but optimized + for things like updating embeddings from within a while loop. + + Args: + op: The Enter op for a loop invariant. + grad: The partial gradients represented as an IndexedSlices. + + Returns: + The accumulated IndexedSlices gradient of the loop invariant. + """ + values = grad.values + indices = grad.indices + dense_shape = grad.dense_shape + + self.Exit() + if self.outer_context: + self.outer_context.Enter() + if values.get_shape().is_fully_defined(): + values_shape = tensor_shape.TensorShape([tensor_shape.Dimension(1)] + + values.get_shape().dims[1:]) + if self.outer_context: + self.outer_context.Enter() + values_acc = constant_op.constant( + 0, values.dtype, shape=values_shape, name="b_acc") + if self.outer_context: + self.outer_context.Exit() + else: + values_shape = _resource_safe_shape(op.inputs[0])[1:] + values_shape = array_ops.concat([[1], values_shape], 0) + values_acc = array_ops.zeros(values_shape, dtype=values.dtype) + indices_acc = constant_op.constant([0], indices.dtype) + shape_acc = None + if dense_shape is not None: + if dense_shape.get_shape().is_fully_defined(): + if self.outer_context: + self.outer_context.Enter() + shape_acc = constant_op.constant( + 0, dense_shape.dtype, shape=dense_shape.get_shape()) + if self.outer_context: + self.outer_context.Exit() + else: + shape_acc = array_ops.zeros_like( + array_ops.shape_internal( + op.inputs[0], optimize=False, out_type=dense_shape.dtype), + optimize=False) + + if self.outer_context: + self.outer_context.Exit() + + self.Enter() + self.AddName(values_acc.name) + self.AddName(indices_acc.name) + init_acc = [indices_acc, values_acc] + if shape_acc is not None: + self.AddName(shape_acc.name) + init_acc.append(shape_acc) + + # Set use_input_shape=False since the accumulator tensors will grow in + # size. If use_input_shape=True, the _update_input call below will result in + # incompatible shapes. + enter_acc = [ + _Enter( + x, + self._name, + is_constant=False, + parallel_iterations=self._parallel_iterations, + use_input_shape=False, + name="b_acc") for x in init_acc + ] + # Manually set appropriate partial shapes. + enter_acc[0].set_shape([None]) + if values_acc.shape.dims is not None: + enter_acc[1].set_shape([None] + values_acc.shape.as_list()[1:]) + self.loop_enters.extend(enter_acc) + + merge_acc = [merge([x, x], name="b_acc")[0] for x in enter_acc] + switch_acc = [switch(x, self._pivot) for x in merge_acc] + + # The actual accumulation. + acc_indexed_slices = [ + array_ops.concat([xa[1], xv], 0) + for xa, xv in zip(switch_acc[:2], [indices, values]) + ] + if shape_acc is not None: + # For the shape we just keep the maximum + acc_indexed_slices.append(math_ops.maximum(dense_shape, switch_acc[2][1])) + + next_acc = [_NextIteration(x) for x in acc_indexed_slices] + for xm, xn in zip(merge_acc, next_acc): + xm.op._update_input(1, xn) # pylint: disable=protected-access + + exit_acc = [exit(x[0], name="b_acc") for x in switch_acc] + self.loop_exits.extend(exit_acc) + + self.ExitResult(exit_acc) + return indexed_slices.IndexedSlices( + indices=exit_acc[0], + values=exit_acc[1], + dense_shape=exit_acc[2] if shape_acc is not None else None) + + def _InitializeValues(self, values): + """Makes the values known to this context.""" + self._values = set() + for x in values: + if isinstance(x, tensor_lib.Tensor): + self._values.add(x.name) + else: + raise TypeError("'values' must be a list of Tensors. " + f"Received: {type(x)}.") + + def _BuildLoop(self, pred, body, flat_orig_loop_vars, flat_loop_vars, + loop_vars_signature): + """Core: Add the loop termination condition and body to the graph.""" + flat_shape_invariants = nest.map_structure( + lambda spec: spec.shape, + nest.flatten(loop_vars_signature, expand_composites=True)) + + # Let the context know the loop variables so the loop variables + # would be added in the outer contexts properly. + self._InitializeValues(flat_loop_vars) + if self._outer_context: + real_vars = [self._outer_context.AddValue(x) for x in flat_loop_vars] + else: + real_vars = flat_loop_vars + + enter_vars = [] + with ops.control_dependencies(None): + for real_var, shape_invariant in zip(real_vars, flat_shape_invariants): + enter_var = _Enter( + real_var, + self._name, + is_constant=False, + parallel_iterations=self._parallel_iterations, + use_input_shape=False) + + if _ShapeLessThanOrEqual(real_var.get_shape(), shape_invariant): + enter_var.set_shape(shape_invariant) + else: + raise ValueError( + f"The shape invariant specified for {real_var.name} is not " + "compatible with the initial shape of the loop variable. It " + f"enters the loop with shape {real_var.get_shape()}, but the " + f"specified shape invariant is {shape_invariant}.") + + enter_var.graph.prevent_feeding(enter_var) + if self._outer_context: + self._outer_context.AddInnerOp(enter_var.op) + enter_vars.append(enter_var) + + # Finds the closest enclosing non-None control pivot. + outer_context = self._outer_context + control_pivot = None + while outer_context is not None and control_pivot is None: + control_pivot = outer_context.GetControlPivot() + # pylint: disable=protected-access + outer_context = outer_context._outer_context + # pylint: enable=protected-access + + if control_pivot is not None: + for var in enter_vars: + if util.IsLoopConstantEnter(var.op.inputs[0].op): + # pylint: disable=protected-access + var.op._add_control_input(control_pivot.op) + # pylint: enable=protected-access + + # Fix the control inputs and control flow context of these enter ops. + self._FixControlInputsAndContext(enter_vars) + self._InitializeValues(enter_vars) + self._loop_enters = enter_vars + + merge_vars = [merge([x, x])[0] for x in enter_vars] + self._pivot_for_pred = merge_vars[0] + + merge_vars_with_tensorarrays = nest.map_structure( + _convert_flow_to_tensorarray, flat_orig_loop_vars, merge_vars) + # Build the graph for pred. + packed_vars = nest.pack_sequence_as( + structure=loop_vars_signature, + flat_sequence=merge_vars_with_tensorarrays, + expand_composites=True) + c = ops.convert_to_tensor(pred(*packed_vars)) + self._pivot = loop_cond(c, name="LoopCond") + switch_vars = [_SwitchRefOrTensor(x, self._pivot) for x in merge_vars] + + # Build the graph for body. + vars_for_body = [_Identity(x[1]) for x in switch_vars] + self._pivot_for_body = vars_for_body[0] + # Convert TensorArray flow variables inside the context back into + # their associated TensorArrays for calling the body. + vars_for_body_with_tensorarrays = nest.map_structure( + _convert_flow_to_tensorarray, flat_orig_loop_vars, vars_for_body) + packed_vars_for_body = nest.pack_sequence_as( + structure=loop_vars_signature, + flat_sequence=vars_for_body_with_tensorarrays, + expand_composites=True) + pre_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + body_result = body(*packed_vars_for_body) + post_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + if not nest.is_nested(body_result): + body_result = [body_result] + if len(post_summaries) > len(pre_summaries): + new_summaries = post_summaries[len(pre_summaries):] + summary_ref = ops.get_collection_ref(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + summary_ref[:] = pre_summaries + with ops.control_dependencies(new_summaries): + + def map_fn(x): + # TODO(apassos) figure out how to trigger with tensor arrays as well + if isinstance(x, tensor_array_ops.TensorArray): + return x + return array_ops.identity(x) + + body_result = nest.map_structure( + map_fn, body_result, expand_composites=True) + + body_result = variable_utils.convert_variables_to_tensors(body_result) + # Compare the structure types of input and output of body. + # For backwards compatibility, the first layer is forced to a list + # during this comparison, because inputs are typically lists and + # outputs of the body are typically tuples. + nest.assert_same_structure( + list(packed_vars_for_body), list(body_result), expand_composites=True) + + # Store body_result to keep track of TensorArrays returned by body + original_body_result = body_result + # Convert TensorArrays returned by body into their flow variables + result = nest.map_structure( + _convert_tensorarray_to_flow, + nest.flatten(body_result, expand_composites=True), + expand_composites=True) + result = ops.convert_n_to_tensor_or_composite(result) + + # Add NextIteration and the back edges to complete the loop. + if len(merge_vars) != len(result): + raise ValueError("Number of inputs and outputs of 'body' must match " + f"'loop_vars'. Got {len(merge_vars)} for the number of " + f"inputs/outputs, and {len(result)} for 'loop_vars'.") + next_vars = [] + for m, v in zip(merge_vars, result): + next_vars.append(_AddNextAndBackEdge(m, v)) + + # Add the exit ops. + exit_vars = [exit(x[0]) for x in switch_vars] + self._loop_exits = exit_vars + + # Exit the loop. + self.ExitResult(exit_vars) + + return original_body_result, exit_vars + + def BuildLoop(self, pred, body, loop_vars, shape_invariants, + return_same_structure): + """Add the loop termination condition and body to the graph.""" + + # Keep flat_orig_loop_vars to identify which are TensorArrays + flat_orig_loop_vars = nest.flatten(loop_vars, expand_composites=True) + + loop_vars = nest.map_structure( + _convert_to_tensor_or_composite_or_tensorarray, loop_vars) + # Convert TensorArrays to their flow variables + flat_loop_vars = nest.map_structure( + _convert_tensorarray_to_flow, + nest.flatten(loop_vars, expand_composites=True)) + + if shape_invariants is not None: + loop_vars_signature = nest.map_structure( + _shape_invariant_to_type_spec, loop_vars, shape_invariants) + else: + loop_vars_signature = nest.map_structure( + _shape_invariant_to_type_spec, loop_vars) + + try: + self.Enter() + # _BuildLoop calls _update_input in several places. _mutation_lock() + # ensures a Session.run call cannot occur between creating and mutating + # new ops. + with ops.get_default_graph()._mutation_lock(): # pylint: disable=protected-access + original_body_result, exit_vars = self._BuildLoop( + pred, body, flat_orig_loop_vars, flat_loop_vars, + loop_vars_signature) + finally: + self.Exit() + + flat_result = nest.flatten(original_body_result, expand_composites=True) + # Convert TensorArray flow variables outside the context back into + # their associated TensorArrays for returning to caller. + exit_vars_with_tensorarrays = nest.map_structure( + _convert_flow_to_tensorarray, flat_result, exit_vars) + + packed_exit_vars = nest.pack_sequence_as( + structure=original_body_result, + flat_sequence=exit_vars_with_tensorarrays, + expand_composites=True) + + if return_same_structure: + return packed_exit_vars + else: + return packed_exit_vars[0] if len(exit_vars) == 1 else packed_exit_vars + + def _FixControlInputsAndContext(self, enters): + graph = ops.get_default_graph() + # pylint: disable=protected-access + for e in enters: + if isinstance(e, tensor_lib.Tensor): + xs = [e] + else: + raise TypeError("'enters' must be a list of Tensors. " + f"Received: {type(e)}.") + for x in xs: + inp_op = x.op.inputs[0].op + control_inputs = graph._control_dependencies_for_inputs([inp_op]) + outer_control_inputs = [] + for op in control_inputs: + # We need to keep control inputs that are in any ancestor + # ControlFlowContext, and within outer WhileContext. + keep_as_control_input = True + op_ctxt = util.GetOutputContext(op) + outer_ctxt = self.outer_context + outer_while_context = (None if outer_ctxt is None else + outer_ctxt.GetWhileContext()) + while outer_ctxt != op_ctxt: + if outer_ctxt is None or outer_ctxt == outer_while_context: + keep_as_control_input = False + break + outer_ctxt = outer_ctxt.outer_context + if keep_as_control_input: + outer_control_inputs.append(op) + x.op._set_control_flow_context(self) + x.op._add_control_inputs(outer_control_inputs) + graph._record_op_seen_by_control_dependencies(x.op) + # pylint: enable=protected-access + + def IsWhileContext(self): + return True + + +# pylint: enable=redefined-outer-name + + +def _AsTensorList(x, p): + """Return x as a list of Tensors or IndexedSlices. + + For entries of `x` that are Operations, this returns an Identity of `p` + with a dependency on the operation. + + Args: + x: A Tensor/IndexedSlices/Operation or a list or tuple of them. + p: A Tensor to return for entries in `x` that are Operations. + + Returns: + A list of Tensors or IndexedSlices. + """ + if not isinstance(x, (list, _basetuple)): + x = [x] + + l = [] + for v in x: + if isinstance(v, ops.Operation): + v = with_dependencies([v], p) + v = ops.convert_to_tensor_or_composite(v) + if isinstance(v, tensor_lib.Tensor): + l.append(array_ops.identity(v)) + else: + l.append( + indexed_slices.IndexedSlices( + array_ops.identity(v.values), array_ops.identity(v.indices))) + return l + + +def _CheckResults(a, b): + assert len(a) == len(b), ( + "Values returned by a() and b() must have the same length.") + for x, y in zip(a, b): + assert x.dtype == y.dtype, ( + "Values returned by a() [%s] and b() [%s] must have " + "the same type: %s, %s." % (x.name, y.name, x.dtype.name, y.dtype.name)) + + +def with_dependencies(dependencies, output_tensor, name=None): + """Produces the content of `output_tensor` only after `dependencies`. + + In some cases, a user may want the output of an operation to be + consumed externally only after some other dependencies have run + first. This function ensures returns `output_tensor`, but only after all + operations in `dependencies` have run. Note that this means that there is + no guarantee that `output_tensor` will be evaluated after any `dependencies` + have run. + + See also `tf.tuple` and `tf.group`. + + Args: + dependencies: Iterable of operations to run before this op finishes. + output_tensor: A `Tensor` or `IndexedSlices` that will be returned. + name: (Optional) A name for this operation. + + Returns: + Same as `output_tensor`. + + Raises: + TypeError: if `output_tensor` is not a `Tensor` or `IndexedSlices`. + """ + if context.executing_eagerly(): + return output_tensor + with ops.name_scope(name, "control_dependency", + list(dependencies) + [output_tensor]) as name: + with ops.colocate_with(output_tensor): + with ops.control_dependencies(dependencies): + output_tensor = ops.convert_to_tensor_or_composite(output_tensor) + if isinstance(output_tensor, indexed_slices.IndexedSlices): + return indexed_slices.IndexedSlices( + _Identity(output_tensor.values, name=name), output_tensor.indices, + output_tensor.dense_shape) + else: + return _Identity(output_tensor, name=name) + + +def _GroupControlDeps(dev, deps, name=None): + with ops.control_dependencies(deps): + if dev is None: + return no_op(name=name) + else: + with ops.device(dev): + return no_op(name=name) + + +# TODO(touts): Accept "inputs" as a list. +@tf_export("group") +def group(*inputs, **kwargs): + """Create an op that groups multiple operations. + + When this op finishes, all ops in `inputs` have finished. This op has no + output. + + Note: *In TensorFlow 2 with eager and/or Autograph, you should not require + this method, as ops execute in the expected order thanks to automatic control + dependencies.* Only use `tf.group` when working with v1 + `tf.Graph` code. + + When operating in a v1-style graph context, ops are not executed in the same + order as specified in the code; TensorFlow will attempt to execute ops in + parallel or in an order convenient to the result it is computing. `tf.group` + allows you to request that one or more results finish before execution + continues. + + `tf.group` creates a single op (of type `NoOp`), and then adds appropriate + control dependencies. Thus, `c = tf.group(a, b)` will compute the same graph + as this: + + with tf.control_dependencies([a, b]): + c = tf.no_op() + + See also `tf.tuple` and + `tf.control_dependencies`. + + Args: + *inputs: Zero or more tensors to group. + name: A name for this operation (optional). + + Returns: + An Operation that executes all its inputs. + + Raises: + ValueError: If an unknown keyword argument is provided. + """ + if context.executing_eagerly(): + return None + name = kwargs.pop("name", None) + if kwargs: + raise ValueError("Unknown keyword arguments: " + ", ".join(kwargs.keys())) + with ops.name_scope(name, "group_deps", inputs) as name: + # Grouping no inputs means do nothing + if not inputs: + return no_op(name=name) + + # Sorts *inputs according to their devices. + ops_on_device = {} # device -> operations specified on the device. + for inp in nest.flatten(inputs, expand_composites=True): + if not hasattr(inp, "device"): + raise TypeError("'inputs' should be zero or more (nested) Tensors. " + f"Received '{inp}' with type '{type(inp)}'.") + dev = inp.device + if dev in ops_on_device: + ops_on_device[dev].append(inp) + else: + ops_on_device[dev] = [inp] + if len(ops_on_device) == 1: + # 1-level tree. The root node is the returned NoOp node. + (dev, deps), = ops_on_device.items() + return _GroupControlDeps(dev, deps, name=name) + + # 2-level tree. The root node is the returned NoOp node. + # deps contains 1 NoOp node for each device. + deps = [] + + def device_key(dev): + """A sort key that allows None to be compared to strings.""" + return "" if dev is None else dev + + for dev in sorted(ops_on_device, key=device_key): + deps.append(_GroupControlDeps(dev, ops_on_device[dev])) + + with ops.control_dependencies(deps): + return no_op(name=name) + + +@tf_export("tuple", v1=[]) +@dispatch.add_dispatch_support +def tuple_v2(tensors, control_inputs=None, name=None): + """Groups tensors together. + + The returned tensors have the same value as the input tensors, but they + are computed only after all the input tensors have been computed. + + Note: *In TensorFlow 2 with eager and/or Autograph, you should not require + this method, as ops execute in the expected order thanks to automatic control + dependencies.* Only use `tf.tuple` when working with v1 `tf.Graph` code. + + See also `tf.group` and `tf.control_dependencies`. + + Example: + >>> with tf.Graph().as_default(): + ... with tf.compat.v1.Session() as sess: + ... v = tf.Variable(0.0) + ... a = tf.constant(1.0) + ... sess.run(tf.compat.v1.global_variables_initializer()) + ... for i in range(5): + ... update_op = v.assign_add(1.0) + ... b = a + v + ... res_b = sess.run(b) + ... res_v = sess.run(v) + ... print(res_v) + 0.0 + 0.0 + 0.0 + 0.0 + 0.0 + + >>> with tf.Graph().as_default(): + ... with tf.compat.v1.Session() as sess: + ... v = tf.Variable(0.0) + ... a = tf.constant(1.0) + ... sess.run(tf.compat.v1.global_variables_initializer()) + ... for i in range(5): + ... update_op = v.assign_add(1.0) + ... calc = [a + v] + ... # `tf.tuple` ensures `update_op` is run before `b` + ... b = tf.tuple(calc, [tf.group(update_op)]) + ... res_b = sess.run(b) + ... res_v = sess.run(v) + ... print(res_v) + 1.0 + 2.0 + 3.0 + 4.0 + 5.0 + + + Args: + tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`. + control_inputs: List of additional ops to finish before returning. + name: (optional) A name to use as a `name_scope` for the operation. + + Returns: + Same as `tensors`. + + Raises: + ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`. + TypeError: If `control_inputs` is not a list of `Operation` or `Tensor` + objects. + + """ + return tuple(tensors=tensors, name=name, control_inputs=control_inputs) # pylint: disable=redefined-builtin + + +@tf_export(v1=["tuple"]) +@dispatch.add_dispatch_support +def tuple(tensors, name=None, control_inputs=None): # pylint: disable=redefined-builtin + """Group tensors together. + + This creates a tuple of tensors with the same values as the `tensors` + argument, except that the value of each tensor is only returned after the + values of all tensors have been computed. + + `control_inputs` contains additional ops that have to finish before this op + finishes, but whose outputs are not returned. + + This can be used as a "join" mechanism for parallel computations: all the + argument tensors can be computed in parallel, but the values of any tensor + returned by `tuple` are only available after all the parallel computations + are done. + + See also `tf.group` and + `tf.control_dependencies`. + + Args: + tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`. + name: (optional) A name to use as a `name_scope` for the operation. + control_inputs: List of additional ops to finish before returning. + + Returns: + Same as `tensors`. + + Raises: + ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`. + TypeError: If `control_inputs` is not a list of `Operation` or `Tensor` + objects. + + """ + if context.executing_eagerly(): + return tensors + with ops.name_scope(name, "tuple", tensors) as name: + tensors = [ + t if (isinstance(t, ops.Operation) or tensor_util.is_tf_type(t) or + t is None) else ops.convert_to_tensor(t) for t in tensors + ] + gating_ops = [ + t if isinstance(t, ops.Operation) else t.op + for t in tensors + if t is not None + ] + if control_inputs: + for c in control_inputs: + if isinstance(c, tensor_lib.Tensor): + c = c.op + elif not isinstance(c, ops.Operation): + raise TypeError( + "'control_inputs' must only contain Operation or Tensor. " + f"Received: {type(c)}") + gating_ops.append(c) + # Note that in order to ensure ordering in the pbtxt, we must take care to + # ensure the order here. + gating_ops = sorted(set(gating_ops), key=lambda op: op._id) # Uniquify ops. + if not gating_ops: + raise ValueError("'tensors' must have at least one Tensor. " + f"Received: {tensors}.") + gate = group(*gating_ops) + tpl = [] + for t in tensors: + if tensor_util.is_tf_type(t): + tpl.append(with_dependencies([gate], t)) + elif isinstance(t, ops.Operation): + with ops.control_dependencies([gate]): + tpl.append(group(t)) + else: + tpl.append(None) + return tpl + + +class XLAControlFlowContext(ControlFlowContext): + """Base class for XLA and TPU control flow contexts.""" + + def __init__(self): + super(XLAControlFlowContext, self).__init__() + self._name = "XLAControlFlowContext" + + def to_control_flow_context_def(self, context_def, export_scope=None): + # pylint: disable=useless-super-delegation + # NOTE(slebedev): the method is required by `ControlFlowContext`. + super(XLAControlFlowContext, + self).to_control_flow_context_def(context_def, export_scope) + + def IsXLAContext(self): + return True + + def AddOp(self, _): + pass + + def AddValue(self, x): + return x + + def RequiresUniqueFunctionRetracing(self): + """Returns whether the tf.function should be retraced if the context changes. + """ + return False + + +@tf_export("__internal__.get_enclosing_xla_context", v1=[]) +def get_enclosing_xla_context(): + """Recursively find and return the XLAControlFlowContext.""" + graph = ops.get_default_graph() + while graph is not None: + # pylint: disable=protected-access + context_ = graph._get_control_flow_context() + # pylint: enable=protected-access + while context_ is not None: + if isinstance(context_, XLAControlFlowContext): + return context_ + context_ = context_.outer_context + # This may be a FuncGraph due to defuns or v2 control flow. We need to + # find the original graph with the XLAControlFlowContext. + graph = getattr(graph, "outer_graph", None) + return None + + +def from_control_flow_context_def(context_def, import_scope=None): + """Deserializes `context_def` into the appropriate ControlFlowContext. + + Args: + context_def: ControlFlowContextDef proto + import_scope: Optional `string`. Name scope to add. + + Returns: + A ControlFlowContext subclass + """ + if context_def.HasField("cond_ctxt"): + return CondContext.from_proto( + context_def.cond_ctxt, import_scope=import_scope) + if context_def.HasField("while_ctxt"): + return WhileContext.from_proto( + context_def.while_ctxt, import_scope=import_scope) + raise NotImplementedError("Unknown ControlFlowContextDef field: %s" % + context_def.WhichOneof("ctxt")) + + +ops.register_proto_function( + ops.GraphKeys.COND_CONTEXT, + proto_type=control_flow_pb2.CondContextDef, + to_proto=CondContext.to_proto, + from_proto=CondContext.from_proto) + +ops.register_proto_function( + ops.GraphKeys.WHILE_CONTEXT, + proto_type=control_flow_pb2.WhileContextDef, + to_proto=WhileContext.to_proto, + from_proto=WhileContext.from_proto) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_state.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_state.py new file mode 100644 index 0000000000000000000000000000000000000000..b604189e91aa2c5a26aa3dbb301b35220423394d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_state.py @@ -0,0 +1,835 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for managing state of v1 control flow for computing gradients.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util as util +from tensorflow.python.ops import control_flow_v2_func_graphs +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import resource_variable_ops + +# pylint: disable=protected-access + + +def _GetMaxSizeFromNestedMaximumIterations(value, while_ctxt): + """Calculate a max_size for use by stack ops inside an XLA while_loop. + + Args: + value: The value inside the while_loop forward context. Used for printing + error messages. + while_ctxt: The forward context inside which value resides. This does not + always match the value's immediate context, as `value` may be inside e.g. + a cond context inside the while_loop. + + Returns: + A tensor containing the `max_size` to feed to a Stack initializer. + + Raises: + ValueError: If `value` is nested inside a `while_loop` that either + lacks a `maximum_iterations` parameter, or the `maximum_iterations` + parameter: + + - is inside a `while_loop` that is a parent of the calling context, and + - cannot be evaluated at graph build time to a constant. + """ + value_name = value.name + # curr_ctxt is the context that tf.gradients was called in. + curr_ctxt = ops.get_default_graph()._get_control_flow_context() # pylint: disable=protected-access + + curr_ctxt_name = curr_ctxt.name if curr_ctxt is not None else "" + max_size = constant_op.constant(1) + + # Loop through all containing while contexts between value and the + # current context, multiplying together each context's + # max_iterations to get the maximum stack size. + while while_ctxt not in (None, curr_ctxt): + max_iter = while_ctxt.maximum_iterations + if max_iter is None: + raise ValueError( + "Cannot create a gradient accumulator for tensor '%s' inside " + "XLA while_loop because maximum_iterations was not passed to " + "the tf.while_loop call ('%s')." % (value_name, while_ctxt.name)) + + # pylint: disable=protected-access + max_iter_ctxt = max_iter.op._get_control_flow_context() + # pylint: enable=protected-access + + # If max_iter_ctxt (non-strictly) contains curr_ctxt, then it's OK to use. + if util.IsContainingContext(curr_ctxt, max_iter_ctxt): + max_size *= max_iter + else: + # We cannot use max_iter because it's defined in a nested while + # or cond context, so will fail if we try to use it as input to + # any ops in curr_ctxt (e.g. max_size or the final accumulator + # stack). Attempt to get a constant value out to use instead. + const_max_iter = tensor_util.constant_value(max_iter) + if const_max_iter is None: + raise ValueError( + "Cannot create a gradient accumulator for tensor '%s' inside XLA " + "while_loop. maximum_iterations tensor '%s' for while_loop context " + "'%s' must be statically known (e.g. a constant value or known " + "shape dimension), or be defined at or outside the while loop " + "context '%s' (currently defined in '%s')." % + (value_name, max_iter.name, while_ctxt.name, curr_ctxt_name, + max_iter_ctxt.name)) + max_size *= const_max_iter + + # Find the next outer WhileContext (or stop if we reach the + # tf.gradient's context). + while_ctxt = util.GetContainingWhileContext( + while_ctxt.outer_context, stop_ctxt=curr_ctxt) + + return max_size + + +class _GradLoopState: + """The state used for constructing the gradient graph for a while loop. + + We create a _GradLoopState for each while loop in forward and its + corresponding while loop in backprop. This gives us access to both + the forward and the backprop WhileContexts. + + During the construction of gradient graph, any time when we detect + a forward value that is needed for backprop, we create a history + accumulator and add it to `history_map`. Any time when we backprop + a loop switch op (in _SwitchGrad), we add the grad merge op in + `switch_map`. + """ + + def __init__(self, forward_ctxt, outer_grad_state): + # The grad loop state for the outer while loop. + self._outer_grad_state = None + + # The while loop context for forward. + self._forward_context = None + + # The loop counter added by AddForwardLoopCounter. It is the value + # of the loop counter for the next iteration. + self._forward_index = None + + # A sync op for forward. + self._forward_sync = None + + # The while loop context for backprop. + self._grad_context = None + + # The loop counter added by AddBackpropLoopCounter. It is the value + # of the loop counter for the current iteration. + self._grad_index = None + + # A sync op for backprop. + self._grad_sync = None + + # Information needed by backprop. + self._history_map = {} + self._switch_map = {} + self._unused_exits = [] + self._deferred_exits = [] + self._forward_loop_exits = list(forward_ctxt.loop_exits) + self._pending_exits_count = len(forward_ctxt.loop_exits) + + self._outer_grad_state = outer_grad_state + if outer_grad_state: + outer_forward_ctxt = outer_grad_state.forward_context + else: + if not hasattr(forward_ctxt, "outer_context"): + raise ValueError("Failed to call gradients on a while loop without" + "properly serializing graph via MetaGraphDef") + outer_forward_ctxt = forward_ctxt.outer_context + + # Add the forward loop counter. + with forward_ctxt._graph.as_default(): # pylint: disable=protected-access + if outer_forward_ctxt: + outer_forward_ctxt.Enter() + cnt, forward_index = forward_ctxt.AddForwardLoopCounter(outer_grad_state) + if outer_forward_ctxt: + outer_forward_ctxt.Exit() + self._forward_context = forward_ctxt + self._forward_index = forward_index + + # Add the backprop WhileContext, and the backprop loop counter. + if outer_grad_state: + # This is a nested loop. Remember the iteration counts for each + # execution of this inner loop. + outer_forward_ctxt.AddName(cnt.name) + history_cnt = outer_grad_state.AddForwardAccumulator(cnt) + + outer_grad_ctxt = outer_grad_state.grad_context + outer_grad_ctxt.Enter() + self._grad_context = control_flow_ops.WhileContext( + maximum_iterations=forward_ctxt.maximum_iterations, + parallel_iterations=forward_ctxt.parallel_iterations, + back_prop=forward_ctxt.back_prop, + swap_memory=forward_ctxt.swap_memory, + name=forward_ctxt.name, + grad_state=self) + real_cnt = outer_grad_state.AddBackpropAccumulatedValue(history_cnt, cnt) + self._grad_index = self._grad_context.AddBackpropLoopCounter( + real_cnt, outer_grad_state) + outer_grad_ctxt.Exit() + else: + if outer_forward_ctxt: + outer_forward_ctxt.Enter() + self._grad_context = control_flow_ops.WhileContext( + maximum_iterations=forward_ctxt.maximum_iterations, + parallel_iterations=forward_ctxt.parallel_iterations, + back_prop=forward_ctxt.back_prop, + swap_memory=forward_ctxt.swap_memory, + name=forward_ctxt.name, + grad_state=self) + self._grad_index = self._grad_context.AddBackpropLoopCounter( + cnt, outer_grad_state) + if outer_forward_ctxt: + outer_forward_ctxt.Exit() + + @property + def outer_grad_state(self): + """The grad loop state for outer loop.""" + return self._outer_grad_state + + @property + def forward_context(self): + """The while loop context for forward.""" + return self._forward_context + + @property + def forward_index(self): + """The loop index of forward loop.""" + return self._forward_index + + @property + def forward_sync(self): + """A control trigger node for synchronization in the forward loop. + + One main use is to keep the push ops of a stack executed in the + iteration order. + """ + if self._forward_sync is None: + with ops.control_dependencies(None): + self._forward_sync = control_flow_ops.control_trigger(name="f_sync") + self._forward_sync._set_control_flow_context(self._forward_context) + self._forward_index.op._add_control_input(self._forward_sync) + return self._forward_sync + + @property + def grad_context(self): + """The corresponding WhileContext for gradient.""" + return self._grad_context + + @property + def grad_index(self): + """The loop index of backprop loop.""" + return self._grad_index + + @property + def grad_sync(self): + """A control trigger node for synchronization in the grad loop. + + One main use is to keep the pop ops of a stack executed in the + iteration order. + """ + if self._grad_sync is None: + with ops.control_dependencies(None): + self._grad_sync = control_flow_ops.control_trigger(name="b_sync") + self._grad_sync._set_control_flow_context(self._grad_context) + self._grad_index.op._add_control_input(self._grad_sync) + if self._grad_context.outer_context: + self._grad_context.outer_context.AddInnerOp(self._grad_sync) + return self._grad_sync + + @property + def history_map(self): + """The map that records all the tensors needed for backprop.""" + return self._history_map + + @property + def switch_map(self): + """The map that records all the Switch ops for the while loop.""" + return self._switch_map + + @property + def unused_exits(self): + """The list of "unused" exits.""" + return self._unused_exits + + @property + def deferred_exits(self): + """The list of "deferred" exits.""" + return self._deferred_exits + + @property + def forward_loop_exits(self): + """The list of exits of the forward loop.""" + return self._forward_loop_exits + + @property + def pending_exits_count(self): + """The number of exits we expect to see but haven't.""" + return self._pending_exits_count + + @pending_exits_count.setter + def pending_exits_count(self, cnt): + """Set the pending count to cnt.""" + self._pending_exits_count = cnt + + def AddForwardAccumulator(self, value, dead_branch=False): + """Add an accumulator for each forward tensor that is needed in backprop. + + This is added to the forward loop at the first time when a tensor + in the forward loop is used by backprop gradient computation loop. + We create an accumulator that accumulates the value of tensor at each + iteration. Called in the control flow context where gradients() is called. + + The pseudocode is: + ``` + acc = stack(); + while (_pivot) { + acc = stack_push(acc, value); + } + ``` + + We make sure that the stack push op in one iteration is executed before + next iteration. This is achieved by adding a control edge from + `forward_index.op.inputs[0].op` to the push op, and another control + edge from the push op to either `forward_index.op` or `forward_sync`. + + Args: + value: The source tensor in forward that is to be accumulated. + dead_branch: True iff the tensor is on a dead branch of a cond. + + Returns: + The stack that contains the accumulated history of the tensor. + + Raises: + TypeError: For internal errors involving the value condition context. + ValueError: If `value` is inside a XLA scope and a valid max size + for the stack can't be found. + """ + # curr_ctxt is the context that tf.gradients was called in. + with self._forward_index.graph.as_default(): + curr_ctxt = ops.get_default_graph()._get_control_flow_context() # pylint: disable=protected-access + with ops.control_dependencies(None): + if curr_ctxt: + curr_ctxt.Enter() + with ops.colocate_with(value): + # We only need to pass maximum_iterations to the stack if + # we're inside an XLA context. + if not util.IsInXLAContext(value.op): + max_size = constant_op.constant(-1, dtypes.int32) + else: + max_size = _GetMaxSizeFromNestedMaximumIterations( + value, self.forward_context) + acc = gen_data_flow_ops.stack_v2( + max_size=max_size, elem_type=value.dtype.base_dtype, name="f_acc") + if curr_ctxt: + curr_ctxt.Exit() + + # Make acc available in the forward context. + enter_acc = self.forward_context.AddValue(acc) + + # Add the stack_push op in the context of value.op. + swap_enabled = self.forward_context.swap_memory + value_ctxt = util.GetOutputContext(value.op) + if value_ctxt == self.forward_context: + # value is not nested in the forward context. + self.forward_context.Enter() + push = gen_data_flow_ops.stack_push_v2( + enter_acc, value, swap_memory=swap_enabled) + self.forward_context.Exit() + # Protect stack push and order it before forward_index. + self.forward_index.op._add_control_input(push.op) + else: + # value is in a cond context within the forward context. + if not isinstance(value_ctxt, control_flow_ops.CondContext): + raise TypeError("value_ctxt is not a CondContext: %s" % value_ctxt) + if dead_branch: + # The special case for creating a zero tensor for a dead + # branch of a switch. See _ControlFlowState.ZerosLikeV1WhileLoop(). + value_ctxt.outer_context.Enter() + push = gen_data_flow_ops.stack_push_v2( + enter_acc, value, swap_memory=swap_enabled) + value_ctxt.outer_context.Exit() + push.op._set_control_flow_context(value_ctxt) + else: + value_ctxt.Enter() + push = gen_data_flow_ops.stack_push_v2( + enter_acc, value, swap_memory=swap_enabled) + value_ctxt.Exit() + # Protect stack push and order it before forward_sync. + self.forward_sync._add_control_input(push.op) + # Order stack push after the successor of forward_index + add_op = self.forward_index.op.inputs[0].op + push.op._add_control_input(add_op) + return acc + + def AddBackpropAccumulatedValue(self, history_value, value, + dead_branch=False): + """Add the getter for an accumulated value in the grad context. + + This is added to the backprop loop. Called in the grad context to + get the value of an accumulated value. The stack pop op must be guarded + by the pred of the controlling cond. + + Args: + history_value: The history (a stack) of a value. + value: The value that is pushed onto the stack. + dead_branch: True iff the tensor is on a dead branch of a cond. + + Returns: + The current value (the top of the stack). + """ + history_ctxt = history_value.op._get_control_flow_context() + # Find the cond context that controls history_value if any. + cond_ctxt = None + value_ctxt = value.op._get_control_flow_context() + while value_ctxt and value_ctxt != history_ctxt: + if isinstance(value_ctxt, control_flow_ops.CondContext): + cond_ctxt = value_ctxt + break + value_ctxt = value_ctxt.outer_context + with ops.control_dependencies(None): + self.grad_context.Enter() + if cond_ctxt: + # Guard stack pop with a switch if it is controlled by a cond. + grad_state = self + pred = None + while pred is None and grad_state: + pred = grad_state.history_map.get(cond_ctxt.pred.name) + grad_state = grad_state.outer_grad_state + if pred is None: + pred = cond_ctxt.pred + branch = (1 - cond_ctxt.branch) if dead_branch else cond_ctxt.branch + history_value = control_flow_ops._SwitchRefOrTensor( + history_value, pred)[branch] + pop = gen_data_flow_ops.stack_pop_v2(history_value, + value.dtype.base_dtype) + pop.set_shape(value.get_shape()) + self.grad_context.Exit() + parallel_iterations = self.grad_context.parallel_iterations + if parallel_iterations > 1: + # All pops are ordered after pivot_for_body and before grad_sync. + self.grad_sync._add_control_input(pop.op) + return pop + + def GetRealValue(self, value): + """Get the real value of `value`. + + If backprop "uses" a value produced by forward inference, an accumulator + is added in the forward loop to accumulate its values. We use the + accumulated value. This method must be called in the grad loop context. + `value` must be in forward and needed for backprop. + + Args: + value: A tensor to be captured. + + Returns: + The same tensor obtained from the saved history. + """ + assert value.op.type not in ["Variable", "VariableV2"] + real_value = self._history_map.get(value.name) + if real_value is None: + cur_value = value + cur_grad_state = self + while True: + enter_op = util.GetLoopConstantEnter(cur_value) + if enter_op: + # Special case: cur_value comes from a constant Enter node. + cur_value = enter_op.inputs[0] + cur_grad_state = cur_grad_state.outer_grad_state + if cur_grad_state is None: + # We are now outside all nested loops for this gradient(), + # so `value` is a loop invariant and there is no need to + # save the history of value. Just make cur_value to enter + # the right control flow context. + real_value = self._grad_context.AddValue(cur_value) + break + elif constant_op.is_constant(cur_value): + # If the value to be forwarded is a constant, clone the constant in + # the gradient loop rather than using a stack. + # TODO(phawkins): consider hoisting the constant out of the loop + # instead. + real_value = constant_op.constant( + tensor_util.constant_value(cur_value), dtype=cur_value.dtype) + break + else: + # Record the history of this value in forward_ctxt. + self._grad_context.Exit() + history_value = cur_grad_state.AddForwardAccumulator(cur_value) + self._grad_context.Enter() + break + + if real_value is None: + # Add the stack pop op in the grad context. + real_value = cur_grad_state.AddBackpropAccumulatedValue( + history_value, cur_value) + if cur_grad_state != self: + real_value = self._grad_context.AddValue(real_value) + self._history_map[value.name] = real_value + return real_value + + +class _ControlFlowState: + """Maintain the mapping from the loops to their grad states.""" + + def __init__(self): + self._map = {} # maps forward loop context to _GradLoopState + + def GetGradState(self, op: ops.Operation, before): + """Return the grad state for this op if it's in a forward loop context.""" + if before and util.IsLoopExit(op): + forward_ctxt = op._get_control_flow_context() # pylint: disable=protected-access + forward_ctxt = forward_ctxt.outer_context + if forward_ctxt: + forward_ctxt = forward_ctxt.GetWhileContext() + else: + forward_ctxt = util.GetWhileContext(op) + if forward_ctxt: + return self._map.get(forward_ctxt) + return None + + def ProcessUnusedLoopExits(self, pending_count, to_ops_set): + """Process all the "unused" loop exits. + + The "unused" exits of the loops are added to `unused_exits`. An exit is + unused if its pending_count is 0. If there is an exit with real gradient, + all these deferred exits will enter the backprop loop with zero gradient. + Otherwise, they will enter the backprop loop with None. As an example, + people often write: + + ```python + v1, _ = tf.while_loop(p, b, [x1, x2]) + result = gradients(v1, x1) + ``` + + The exit node for x2 is not included by the betweenness analysis. But we + need to backprop x2 if x2 is involved in computing v1. + + Args: + pending_count: The number of backprop inputs for every op. + to_ops_set: The set of ops for ys in gradients(ys, xs) + + Returns: + The set of unused loop exits that we know at this point we need + to backprop. + """ + loop_exits = [] + for grad_state in self._map.values(): + for y in grad_state.forward_loop_exits: + if pending_count[y.op] == 0: + grad_state.pending_exits_count -= 1 + if y.op not in to_ops_set: + grad_state.unused_exits.append(y) + if grad_state.pending_exits_count == 0: + loop_exits.extend(grad_state.unused_exits) + # Need to include Enters in backprop for higher-order gradients. + for y in grad_state.forward_context.loop_enters: + if pending_count[y.op] == 0: + pending_count[y.op] = 1 + return loop_exits + + def EnterGradWhileContext(self, op, before): + """Enter the WhileContext for gradient computation.""" + grad_state = self.GetGradState(op, before) + if grad_state: + grad_state.grad_context.Enter() + + def ExitGradWhileContext(self, op, before): + """Exit the WhileContext for gradient computation.""" + grad_state = self.GetGradState(op, before) + if grad_state: + grad_state.grad_context.Exit() + + def AddWhileContext(self, op, between_op_list, between_ops): + """Add the grad state for the while loop that op belongs to. + + Note that op is an Exit, and this method must be called in + the control flow context where gradients() is called. + + Note that this method modifies `between_op_list` and `between_ops`. + """ + forward_ctxt = util.GetWhileContext(op) + grad_state = self._map.get(forward_ctxt) + if grad_state is None: + # This is a new while loop so create a grad state for it. + outer_forward_ctxt = forward_ctxt.outer_context + if outer_forward_ctxt: + outer_forward_ctxt = outer_forward_ctxt.GetWhileContext() + outer_grad_state = None + if outer_forward_ctxt: + outer_grad_state = self._map.get(outer_forward_ctxt) + grad_state = _GradLoopState(forward_ctxt, outer_grad_state) + self._map[forward_ctxt] = grad_state + + # We need to include all exits of a loop for backprop. + for loop_exit in grad_state.forward_loop_exits: + if loop_exit.op not in between_ops: + between_ops.add(loop_exit.op) + between_op_list.append(loop_exit.op) + + def ZerosLikeForExit(self, val): + """Create zeros_like gradient for a loop exit. + + If the result of a loop variable is not used but is involved in + computing the result of some needed loop variable, we create a + zero-valued tensor that is fed as gradient for the Exit node of that + loop variable. Note that val.op is an Exit, and this method must be + called in the control flow context where gradients() is called. + + Args: + val: The output tensor of an Exit op. + + Returns: + A zero tensor of the same shape of val. + """ + val_shape = val.get_shape() + forward_ctxt = val.op._get_control_flow_context() + outer_forward_ctxt = forward_ctxt.outer_context + if outer_forward_ctxt: + outer_forward_ctxt = outer_forward_ctxt.GetWhileContext() + outer_grad_state = None + if outer_forward_ctxt: + outer_grad_state = self._map.get(outer_forward_ctxt) + if outer_grad_state: + # This is a nested loop. + if val_shape.is_fully_defined(): + # If the shape is known statically, just create a zero tensor + # with the right shape in the right context. + outer_grad_state.grad_context.Enter() + result = array_ops.zeros(val_shape.dims, val.dtype) + outer_grad_state.grad_context.Exit() + else: + # Only the shape of value is needed for backprop. + forward_ctxt.outer_context.Enter() + shape = array_ops.shape_internal(val, optimize=False) + forward_ctxt.outer_context.Exit() + # Save the shape to a stack. + history_shape = outer_grad_state.AddForwardAccumulator(shape) + # Get the shape back from the stack. + outer_grad_ctxt = outer_grad_state.grad_context + outer_grad_ctxt.Enter() + real_shape = outer_grad_state.AddBackpropAccumulatedValue( + history_shape, shape) + result = array_ops.zeros(real_shape, val.dtype) + outer_grad_ctxt.Exit() + else: + # This is not a nested loop. + if val_shape.is_fully_defined(): + # If the shape is known statically, just create a zero tensor + # with the right shape. + result = array_ops.zeros(val_shape.dims, val.dtype) + else: + result = array_ops.zeros_like(val, optimize=False) + return result + + def ZerosLikeV1WhileLoop(self, op, index): + """Create zeros_like for the specified output of an op. + + If op is in a while loop that is part of gradients(), this method + must be called in its grad loop context. + + Args: + op: A tensorflow operation. + index: the index for a specific output of the op. + + Returns: + A zero tensor of the same shape of op.outputs[index]. + """ + if util.IsLoopSwitch(op): + return None + if op.graph.building_function: + # The optimization here is tricky to apply to functions + return array_ops.zeros_like(op.outputs[index]) + dead_branch = util.IsSwitch(op) + forward_ctxt = util.GetWhileContext(op) + grad_state = self._map.get(forward_ctxt) + if grad_state is None: + # op is not in a while loop that is part of gradients(). + return ZerosLike(op, index) + op_ctxt = op._get_control_flow_context() + val = ops.convert_to_tensor(op.outputs[index], name="tensor") + shape = val.get_shape() + if shape.is_fully_defined(): + # If the shape is known statically, just create a zero tensor with + # the right shape in the grad loop context. + if val.dtype == dtypes.resource: + result = array_ops.zeros( + resource_variable_ops.variable_shape(val), + dtype=default_gradient.get_zeros_dtype(val)) + else: + result = constant_op.constant(0, shape=shape.dims, dtype=val.dtype) + if dead_branch: + # op is a cond switch. Guard the zero tensor with a switch. + pred = grad_state.history_map.get(op_ctxt.pred.name) + branch = op_ctxt.branch + result = control_flow_ops._SwitchRefOrTensor(result, pred)[1 - branch] + else: + # Unknown shape so keep a history of the shape at runtime. + if dead_branch: + # Need to add a special switch to guard the value. + pred = op_ctxt.pred + branch = op_ctxt.branch + op_ctxt.outer_context.Enter() + val = control_flow_ops._SwitchRefOrTensor(op.inputs[0], + pred)[1 - branch] + zeros_shape = array_ops.shape_internal(val, optimize=False) + op_ctxt.outer_context.Exit() + val.op._set_control_flow_context(op_ctxt) + zeros_shape.op._set_control_flow_context(op_ctxt) + else: + op_ctxt.Enter() + zeros_shape = array_ops.shape_internal(val, optimize=False) + op_ctxt.Exit() + + # Add forward accumulator for shape. + grad_state.grad_context.Exit() + history_zeros_shape = grad_state.AddForwardAccumulator( + zeros_shape, dead_branch=dead_branch) + grad_state.grad_context.Enter() + + # Create a zero tensor with the right shape. + shape = grad_state.AddBackpropAccumulatedValue(history_zeros_shape, + zeros_shape, dead_branch) + result = array_ops.zeros(shape, val.dtype) + return result + + def PostProcessing(self): + """Perform postprocessing at the end of gradients(). + + We have created the gradient graph at this point. So this function + can be used to perform any postprocessing on the gradient graph. + We currently perform the following postprocessing: + 1. Patch the gradient graph if the output of a loop variable + doesn't depend on its input. + """ + for _, grad_state in self._map.items(): + for _, b_merge in grad_state.switch_map.items(): + if b_merge.op.inputs[0] == b_merge.op.inputs[1]: + # The value of this loop variable at iteration i+1 doesn't + # depend on its value at iteration i. So use zeros as the + # gradients for all iterations > 0. + dtype = b_merge.op.inputs[0].dtype + shape = b_merge.op.inputs[0].get_shape() + # pylint: disable=protected-access + if shape.is_fully_defined(): + grad_state.grad_context.Enter() + # Create a zeros and use it for iterations > 0. + grad_val = constant_op.constant(0, dtype=dtype, shape=shape) + next_grad_val = control_flow_ops._NextIteration(grad_val) + grad_state.grad_context.Exit() + else: + # Create a zeros in the outer grad context. + outer_grad_ctxt = grad_state.grad_context.outer_context + if outer_grad_ctxt: + outer_grad_ctxt.Enter() + enter_grad_op = b_merge.op.inputs[0].op + enter_grad = enter_grad_op.inputs[0] + grad_shape = array_ops.shape_internal(enter_grad, optimize=False) + grad_val = array_ops.zeros(grad_shape) + if outer_grad_ctxt: + outer_grad_ctxt.Exit() + # Use the zeros for iterations > 0. + grad_state.grad_context.Enter() + next_grad_val = control_flow_ops._NextIteration(grad_val) + grad_state.grad_context.Exit() + b_merge.op._update_input(1, next_grad_val) + # pylint: enable=protected-access + + +def MaybeCreateControlFlowState(between_op_list, between_ops, + colocate_gradients_with_ops): + """Create the state for all the while loops involved in one gradients(). + + We create a _ControlFlowState when there are while loops involved in + gradients(). In gradients(), control flow logic is only invoked when + the _ControlFlowState is not None. + + Note that this method modifies `between_op_list` and `between_ops`. + """ + loop_state = None + for op in between_op_list: + if util.IsLoopExit(op): + if loop_state is None: + loop_state = _ControlFlowState() + if colocate_gradients_with_ops: + with ops.colocate_with(op): + loop_state.AddWhileContext(op, between_op_list, between_ops) + else: + loop_state.AddWhileContext(op, between_op_list, between_ops) + return loop_state + + +def _ZerosLikeV1(op, index): + """Branch of ZerosLike for TF1.""" + val = op.outputs[index] + op_ctxt = op._get_control_flow_context() # pylint: disable=protected-access + if op_ctxt: + # We are in a cond context. Use a switch to create zeros only when needed. + pred = op_ctxt.pred + branch = op_ctxt.branch + switch_val = control_flow_ops.switch(op.inputs[0], pred)[1 - branch] + # A op is created along the branch taken as control dependencies are on + # the whole op and not on the tensor output. + pivot = array_ops.identity(switch_val) + if val.dtype == dtypes.resource: + with ops.control_dependencies([pivot]): + return array_ops.zeros( + gen_resource_variable_ops.variable_shape(switch_val), + dtype=default_gradient.get_zeros_dtype(val)) + zeros_shape = array_ops.shape_internal(switch_val, optimize=False) + # Ensure ops created within array_ops.zeros are dominated by switch in + # cond context. + with ops.control_dependencies([pivot]): + return array_ops.zeros(zeros_shape, dtype=val.dtype) + else: + return array_ops.zeros_like(val, optimize=False) + + +def _ZerosLikeV2(op, index): + """Branch of ZerosLike for TF2.""" + val = op.outputs[index] + if val.dtype == dtypes.resource: + return array_ops.zeros( + gen_resource_variable_ops.variable_shape(val), + dtype=default_gradient.get_zeros_dtype(val)) + if (isinstance(val.op.graph, control_flow_v2_func_graphs.WhileBodyFuncGraph) + and val.dtype != dtypes.variant): + # In while_v2 we do not want to add a `ZerosLike` op because that will + # trigger accumulation of `val`. Normally `ZerosLike` is preferred because + # it helps avoid creating extra nodes(possibly Consts) for the shape. + # For variants, we must use ZerosLike. + if val.shape.is_fully_defined(): + return constant_op.constant(0, shape=val.shape.dims, dtype=val.dtype) + else: + # Note: Even though we add `Shape` in the default graph, while_v2 is smart + # enough to place it in the forward graph i.e. `val.graph`. + zeros_shape = array_ops.shape_internal(val, optimize=False) + return array_ops.zeros(zeros_shape, val.dtype) + else: + return array_ops.zeros_like(val, optimize=False) + + +def ZerosLike(op, index): + """Create zeros_like for the specified output of an op.""" + if not util.IsSwitch(op): + return _ZerosLikeV2(op, index) + else: + return _ZerosLikeV1(op, index) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_switch_case.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_switch_case.py new file mode 100644 index 0000000000000000000000000000000000000000..843a088017df367122a4567683ed36f59dfc3a5b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_switch_case.py @@ -0,0 +1,253 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Switch case for Control Flow Operations.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond_v2 +from tensorflow.python.ops import control_flow_util as util +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util.tf_export import tf_export + + +def _indexed_case_verify_and_canonicalize_args(branch_fns, default, + branch_index): + """Verifies input arguments for the case function. + + Args: + branch_fns: Dict or list of pairs of an `int` and a callable which returns a + list of tensors. + default: Optional callable that returns a list of tensors. + branch_index: Optional int `Tensor`, which selects for the corresponding + pred_fn_pair. + + Raises: + TypeError: If `branch_fns` is not a list/dictionary. + TypeError: If `branch_fns` is a list but does not contain 2-tuples or + callables. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + + Returns: + branch_fns: validated list of callables for each branch (default last). + """ + if not isinstance(branch_index, tensor.Tensor): + raise TypeError("'branch_index' must be a Tensor, got {}".format( + type(branch_index))) + if not branch_index.dtype.is_integer: + raise TypeError("'branch_index' must be an integer Tensor, got {}".format( + branch_index.dtype)) + + if not branch_fns: + raise ValueError("Must provide at least one item in 'branch_fns'") + if not isinstance(branch_fns, (list, tuple, dict)): + raise TypeError("'branch_fns' must be a list, tuple, or dict") + + if isinstance(branch_fns, dict): + branch_fns = branch_fns.items() + + if all(callable(fn) for fn in branch_fns): + branch_fns = list(enumerate(branch_fns)) + + for key_fn_pair in branch_fns: + if not isinstance(key_fn_pair, tuple) or len(key_fn_pair) != 2: + raise TypeError("Each entry in 'branch_fns' must be a 2-tuple. " + f"Received {key_fn_pair}.") + key, branch_fn = key_fn_pair + + if not isinstance(key, int): + raise TypeError("key must be a Python `int`, got {}".format(type(key))) + + if not callable(branch_fn): + raise TypeError("fn for key {} must be callable.".format(key)) + + keys = [p[0] for p in branch_fns] + if min(keys) < 0 or max(keys) >= len(keys) or len(set(keys)) != len(keys): + raise ValueError( + "branch indices (keys) must form contiguous range of [0 to {}) but " + "found {{{}}}".format(len(keys), ",".join(map(str, sorted(keys))))) + actions = [p[1] for p in sorted(branch_fns)] + if default is not None: + actions.append(default) + return actions + + +def _indexed_case_helper(branch_fns, + default, + branch_index, + name, + lower_using_switch_merge=None): + """Implementation of case that emits the n-way indexed Case op. + + Args: + branch_fns: Dict or list of pairs of a boolean scalar tensor, and a callable + which returns a list of tensors. + default: Optional callable that returns a list of tensors. + branch_index: Optional int `Tensor`, which selects for the corresponding + pred_fn_pair. + name: A name for this operation (optional). + lower_using_switch_merge: Lower this op using switch merge ops (optional). + + Returns: + The tensors returned by the pair whose key matched branch_index, or + those returned by `default` if none does. + + Raises: + TypeError: If `branch_fns` is not a list/dictionary. + TypeError: If `branch_fns` is a list but does not contain 2-tuples or + callables. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + branch_fns = _indexed_case_verify_and_canonicalize_args( + branch_fns, default, branch_index) + with ops.name_scope(name, "case", [branch_index]): + if context.executing_eagerly() and not hasattr(branch_index, "graph"): + branch_index = array_ops.where( + math_ops.less(branch_index, 0) + | math_ops.greater_equal(branch_index, len(branch_fns)), + len(branch_fns) - 1, branch_index) + return branch_fns[int(branch_index)]() + return cond_v2.indexed_case( + branch_index, + branch_fns, + lower_using_switch_merge=lower_using_switch_merge) + + +@tf_export("__internal__.execute_fn_for_device", v1=[]) +def execute_fn_for_device(device_branch_fns, default_fn, name="execute_fn"): + """Executes one of the provided callables based on the device placement. + + This API is used when the implementations for high level function depend on + the underlying device placement. It takes a dictionary of device type to + callables. The device type includes "CPU", "GPU", "TPU", etc. When the type of + the device where to run this op matches the key in 'device_branch_fns', + the corresponding callable is executed, falling back to 'default_fn' if none + matches. + + **Example:** + ```python + def f1(): return tf.constant(1) + def f2(): return tf.constant(2) + r = tf.execute_fn_for_device({"CPU": f1, "GPU": f2}, default_fn=f1) + ``` + 'r' is evaluated as 1 when it runs on CPU, 2 running on GPU, 1 running on + any other device types. + + + Args: + device_branch_fns: a dictionary of device types to the callables. Each + callable must return a matching structure of tensors. + default_fn: fallback callable when the underlying device does not match any + key in the 'device_branch_fns'. + name: A name for this operation (optional). + + Returns: + The tensors returned by the callable identified by device type during + execution, or those returned by 'default_fn' if no key matches. + """ + # Always execute the default fn for XLA to avoid complicated graph by case op. + # see more discussions in b/167276293. + is_in_xla = util.GraphOrParentsInXlaContext(ops.get_default_graph()) + if is_in_xla: + return default_fn() + device_branch_fns_upper = {k.upper(): v for k, v in device_branch_fns.items()} + branch_fns = list(device_branch_fns_upper.values()) + devices = list(device_branch_fns_upper.keys()) + device_index = gen_functional_ops.device_index(device_names=devices) + return _indexed_case_helper( + branch_fns, + default_fn, + device_index, + name, + lower_using_switch_merge=False) + + +@tf_export("switch_case") +def switch_case(branch_index, branch_fns, default=None, name="switch_case"): + """Create a switch/case operation, i.e. + + an integer-indexed conditional. + + See also `tf.case`. + + This op can be substantially more efficient than `tf.case` when exactly one + branch will be selected. `tf.switch_case` is more like a C++ switch/case + statement than `tf.case`, which is more like an if/elif/elif/else chain. + + The `branch_fns` parameter is either a dict from `int` to callables, or list + of (`int`, callable) pairs, or simply a list of callables (in which case the + index is implicitly the key). The `branch_index` `Tensor` is used to select an + element in `branch_fns` with matching `int` key, falling back to `default` + if none match, or `max(keys)` if no `default` is provided. The keys must form + a contiguous set from `0` to `len(branch_fns) - 1`. + + `tf.switch_case` supports nested structures as implemented in `tf.nest`. All + callables must return the same (possibly nested) value structure of lists, + tuples, and/or named tuples. + + **Example:** + + Pseudocode: + + ```c++ + switch (branch_index) { // c-style switch + case 0: return 17; + case 1: return 31; + default: return -1; + } + ``` + or + ```python + branches = {0: lambda: 17, 1: lambda: 31} + branches.get(branch_index, lambda: -1)() + ``` + + Expressions: + + ```python + def f1(): return tf.constant(17) + def f2(): return tf.constant(31) + def f3(): return tf.constant(-1) + r = tf.switch_case(branch_index, branch_fns={0: f1, 1: f2}, default=f3) + # Equivalent: tf.switch_case(branch_index, branch_fns={0: f1, 1: f2, 2: f3}) + ``` + + Args: + branch_index: An int Tensor specifying which of `branch_fns` should be + executed. + branch_fns: A `dict` mapping `int`s to callables, or a `list` of (`int`, + callable) pairs, or simply a list of callables (in which case the index + serves as the key). Each callable must return a matching structure of + tensors. + default: Optional callable that returns a structure of tensors. + name: A name for this operation (optional). + + Returns: + The tensors returned by the callable identified by `branch_index`, or those + returned by `default` if no key matches and `default` was provided, or those + returned by the max-keyed `branch_fn` if no `default` is provided. + + Raises: + TypeError: If `branch_fns` is not a list/dictionary. + TypeError: If `branch_fns` is a list but does not contain 2-tuples or + callables. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + return _indexed_case_helper(branch_fns, default, branch_index, name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1342fdd1c29c6eed917d897a052e7cea78b0bf28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util.py @@ -0,0 +1,367 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utility functions for control flow. + +This file is necessary to avoid cyclic dependencies between ops.py and +control_flow_ops.py. +""" + +import os +import traceback + +from tensorflow.python import tf2 +from tensorflow.python.platform import tf_logging as logging + +ENABLE_CONTROL_FLOW_V2 = ((tf2.enabled() and + os.getenv("TF_ENABLE_CONTROL_FLOW_V2") != "0") or + os.getenv("TF_ENABLE_CONTROL_FLOW_V2", "0") != "0" or + os.getenv("TF_ENABLE_COND_V2", "0") != "0" or + os.getenv("TF_ENABLE_WHILE_V2", "0") != "0" or + os.getenv("TF_ENABLE_TENSOR_ARRAY_V2", "0") != "0") + + +# TODO(b/137793122): Remove this. +def enable_control_flow_v2(): # pylint: disable=invalid-name + """Use control flow v2. + + Do not use this symbol. This will be removed. + """ + global ENABLE_CONTROL_FLOW_V2 + ENABLE_CONTROL_FLOW_V2 = True + + +def EnableControlFlowV2(graph): + """Returns whether control flow v2 should be used in `graph`.""" + # Enable new control flow in FuncGraphs (but not legacy _FuncGraphs). + # TODO(skyewm): do something better than hasattr without messing up imports. + return ENABLE_CONTROL_FLOW_V2 or ( + graph.building_function and not hasattr(graph, "_captured")) + + +def IsInXLAContext(op): + try: + xla_compile = op.get_attr("_XlaCompile") + if xla_compile: return True + except ValueError: + pass + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return GetContainingXLAContext(ctxt) is not None + + +def InXlaContext(graph): + ctxt = graph._get_control_flow_context() # pylint: disable=protected-access + return GetContainingXLAContext(ctxt) is not None + + +def GraphOrParentsInXlaContext(graph): + while True: + if InXlaContext(graph): return True + try: + graph = graph.outer_graph + except AttributeError: + return False + + +def IsInWhileLoop(op): + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return GetContainingWhileContext(ctxt) is not None + + +def IsInCond(op): + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return GetContainingCondContext(ctxt) is not None + + +def IsSwitch(op): + """Return true if `op` is a Switch.""" + return op.type == "Switch" or op.type == "RefSwitch" + + +def IsMerge(op): + """Return true if `op` is a Merge.""" + return op.type == "Merge" or op.type == "RefMerge" + + +def IsLoopEnter(op): + """Returns true if `op` is an Enter.""" + return op.type == "Enter" or op.type == "RefEnter" + + +def IsLoopExit(op): + """Return true if `op` is an Exit.""" + return op.type == "Exit" or op.type == "RefExit" + + +def IsCondSwitch(op): + """Return true if `op` is the Switch for a conditional.""" + if not IsSwitch(op): + return False + if not op.outputs: + return False + # Switch nodes are not part of the cond control flow context that they + # represent, so consider the consumers of its outputs to determine if it is + # cond switch or not. A switch is a cond switch iff all its consumers are in + # cond contexts. + is_cond_switch = True + for o in op.outputs: + for c in o.consumers(): + ctxt = c._get_control_flow_context() # pylint: disable=protected-access + if IsLoopEnter(c): + ctxt = ctxt.outer_context + is_cond_switch = is_cond_switch and (ctxt is not None and + ctxt.IsCondContext()) + return is_cond_switch + + +def IsCondMerge(op): + """Return true if `op` is the Merge for a conditional.""" + if not IsMerge(op): + return False + if not op.inputs: + return False + # Merge nodes are not part of the cond control flow context that they + # represent, so consider the inputs to the merge of to determine if it is + # cond merge or not: A merge is a cond merge iff all its inputs are in + # cond contexts. + is_cond_merge = True + for i in op.inputs: + ctxt = GetOutputContext(i.op) + is_cond_merge = is_cond_merge and ctxt is not None and ctxt.IsCondContext() + return is_cond_merge + + +def IsLoopSwitch(op): + """Return true if `op` is the Switch for a while loop.""" + if IsSwitch(op): + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return ctxt is not None and ctxt.IsWhileContext() and not IsCondSwitch(op) + return False + + +def IsLoopMerge(op): + """Return true if `op` is the Merge for a while loop.""" + if IsMerge(op): + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + return ctxt is not None and ctxt.IsWhileContext() and not IsCondMerge(op) + return False + + +def IsLoopConstantEnter(op): + """Return true iff op is a loop invariant.""" + return IsLoopEnter(op) and op.get_attr("is_constant") + + +def GetLoopConstantEnter(value): + """Return the enter op if we can infer `value` to be a loop invariant.""" + id_ops = {"Switch", "RefSwitch", "Identity", "RefIdentity"} + op = value.op + while op.type in id_ops: + op = op.inputs[0].op + return op if IsLoopConstantEnter(op) else None + + +def GetOutputContext(op): + """Return the control flow context for the output of an op.""" + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + # Exit nodes usually have a control flow context, except in the case where the + # exit node was imported via import_graph_def (in which case no nodes have + # control flow contexts). + if ctxt is not None and IsLoopExit(op): + ctxt = ctxt.outer_context + return ctxt + + +def GetContainingWhileContext(ctxt, stop_ctxt=None): + """Returns the first ancestor WhileContext of `ctxt`. + + Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a + while loop. + + Args: + ctxt: ControlFlowContext + stop_ctxt: ControlFlowContext, optional. If provided, the search will end + if it sees stop_ctxt. + + Returns: + `ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing + `ctxt`, or None if `ctxt` is not in a while loop. If `stop_ctxt` is not + `None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal. + """ + while ctxt: + if ctxt.IsWhileContext() or ctxt == stop_ctxt: return ctxt + ctxt = ctxt.outer_context + return None + + +def GetContainingXLAContext(ctxt): + """Returns the first ancestor XLAContext of `ctxt`. + + Returns `ctxt` if `ctxt` is a XLAContext, or None if `ctxt` is not in a + while loop. + + Args: + ctxt: ControlFlowContext + + Returns: + `ctxt` if `ctxt` is a XLAContext, the most nested XLAContext containing + `ctxt`, or None if `ctxt` is not in a while loop. + """ + while ctxt: + if ctxt.IsXLAContext(): return ctxt + ctxt = ctxt.outer_context + return None + + +def GetContainingCondContext(ctxt): + """Returns the first ancestor CondContext of `ctxt`. + + Returns `ctxt` if `ctxt` is a CondContext, or None if `ctxt` is not in a cond. + + Args: + ctxt: ControlFlowContext + + Returns: + `ctxt` if `ctxt` is a CondContext, the most nested CondContext containing + `ctxt`, or None if `ctxt` is not in a cond. + """ + while ctxt: + if ctxt.IsCondContext(): return ctxt + ctxt = ctxt.outer_context + return None + + +def IsContainingContext(ctxt, maybe_containing_ctxt): + """Returns true if `maybe_containing_ctxt` is or contains `ctxt`.""" + while ctxt is not maybe_containing_ctxt: + if ctxt is None: return False + ctxt = ctxt.outer_context + return True + + +def OpInContext(op, ctxt): + return IsContainingContext(op._get_control_flow_context(), ctxt) # pylint: disable=protected-access + + +def TensorInContext(tensor, ctxt): + return OpInContext(tensor.op, ctxt) + + +def CheckInputFromValidContext(op, input_op): + """Returns whether `input_op` can be used from `op`s context. + + Conceptually, only inputs from op's while context or any ancestor while + context (including outside of any context) are valid. In practice, there are + many other edge cases as well. + + Args: + op: Operation + input_op: Operation + + Raises: + ValueError: if input_op is from an invalid context. + """ + op_ctxt = op._get_control_flow_context() # pylint: disable=protected-access + input_ctxt = GetOutputContext(input_op) + valid = False + + if not input_ctxt: + # input_op isn't in a control flow context. + valid = True + elif op_ctxt is input_ctxt: + # input_op is in the same context as op. + valid = True + else: + while_ctxt = GetContainingWhileContext(op_ctxt) + input_while_ctxt = GetContainingWhileContext(input_ctxt) + + if while_ctxt is None: + if input_while_ctxt is None: + # Neither op nor input_op is in a while loop, but one or both are in + # conds. We allow this, although execution will fail if the branch + # corresponding to input_op's cond context isn't taken. + valid = True + # Invalid if op isn't in a while loop and input_op is. Unless... + if IsLoopEnter(op): + # WhileContext._BuildLoop clears context for Enter nodes. + valid = True + if IsSwitch(op): + # CondContext.AddValue clears context for Switch nodes. + valid = True + elif IsContainingContext(while_ctxt, input_while_ctxt): + # input_op is in a while loop which contains op's while loop (or not in a + # while loop at all). + valid = True + elif (while_ctxt.grad_state and + IsContainingContext(while_ctxt.grad_state.forward_context, + input_while_ctxt)): + # op is in a gradient context and input_op is in the associated forward + # pass context or an ancestor thereof. This case is need to build while + # loop gradients. + # NOTE(skyewm): we theoretically also need this case for custom gradient + # functions that close over tensors from ancestor contexts, but I haven't + # verified this. + valid = True + elif (while_ctxt.grad_state and + while_ctxt.grad_state.forward_context is + input_while_ctxt._outer_context): # pylint: disable=protected-access + # op is in a gradient context and input_op is in a child of the associated + # forward pass context. This case is needed for the gradients of while + # loops with conds. + valid = True + elif (input_while_ctxt.grad_state and + input_while_ctxt.grad_state.forward_context is while_ctxt): + # input_op is in the gradient context of op's context. This case is needed + # when the gradient of a while loop gradient is requested (this will + # eventually fail unless there is a stop_gradient() or similar). + valid = True + elif (input_while_ctxt.grad_state and + input_ctxt.grad_state.forward_context.grad_state and + input_ctxt.grad_state.forward_context.grad_state.forward_context is + while_ctxt): + # input_op is in the grad grad context of op's context. This case is + # needed when the gradient of a while loop gradient is requested (this + # will eventually fail unless there is a stop_gradient() or similar). + valid = True + + if not valid: + if while_ctxt: + error_msg = ( + f"Cannot use '{input_op.name}' as input to '{op.name}' because they " + "are in different while loops.") + else: + error_msg = ( + f"Cannot use '{input_op.name}' as input to '{op.name}' because " + f"'{input_op.name}' is in a while loop.") + + # Log the error message plus the relevant stack traces. The stacks may be + # useful for debugging this error, but we don't want to raise an + # unreadable exception. + log_msg = error_msg + log_msg += "\n\n%s while context: %s" % (op.name, while_ctxt) + log_msg += "\n%s while context: %s" % (input_op.name, input_while_ctxt) + log_msg += "\n\nTraceback for %s:\n%s\nTraceback for %s:\n%s\n" % ( + op.name, "".join(traceback.format_list(op.traceback)), + input_op.name, "".join(traceback.format_list(input_op.traceback))) + logging.info(log_msg) + raise ValueError(error_msg + " See info log for more details.") + + +def GetWhileContext(op): + """Get the WhileContext to which this op belongs.""" + ctxt = op._get_control_flow_context() # pylint: disable=protected-access + if ctxt: + ctxt = ctxt.GetWhileContext() + return ctxt diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..213698c06f7dfbec51cbe17807b445cd31b191f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_util_v2.py @@ -0,0 +1,400 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utilities for V2 control flow.""" + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager.polymorphic_function import atomic_function +from tensorflow.python.eager.polymorphic_function import concrete_function +from tensorflow.python.eager.polymorphic_function import tracing_compilation +from tensorflow.python.eager.polymorphic_function import transform +from tensorflow.python.framework import function_def_to_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework.func_graph import FuncGraph +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import control_flow_v2_func_graphs +from tensorflow.python.ops import gradients_util +from tensorflow.python.util import keras_deps +from tensorflow.python.util import tf_contextlib + +_EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = None +_DISABLE_LOWER_USING_SWITCH_MERGE = False + + +CondBranchFuncGraph = control_flow_v2_func_graphs.CondBranchFuncGraph +WhileCondFuncGraph = control_flow_v2_func_graphs.WhileCondFuncGraph +WhileBodyFuncGraph = control_flow_v2_func_graphs.WhileBodyFuncGraph + + +def in_defun(): + """Returns if the current graph is, or is nested in, a defun.""" + if context.executing_eagerly(): return False + + graph = ops.get_default_graph() + while (isinstance(graph, CondBranchFuncGraph) or + isinstance(graph, WhileBodyFuncGraph) or + isinstance(graph, WhileCondFuncGraph)): + graph = graph.outer_graph + return isinstance(graph, FuncGraph) + + +def in_while_loop_defun(graph): + """Returns if the graph is a while loop FuncGraph.""" + if context.executing_eagerly(): return False + return (isinstance(graph, WhileCondFuncGraph) or + isinstance(graph, WhileBodyFuncGraph)) + + +def create_new_tf_function(func_graph): + """Converts func_graph to a TF_Function and adds it to the current graph. + + Args: + func_graph: FuncGraph + + Returns: + The name of the new TF_Function. + """ + transform.apply_func_graph_transforms(func_graph) + func = atomic_function.from_func_graph(func_graph.name, func_graph, {}) + + func_graph.outer_graph._add_function_recursive(func) # pylint: disable=protected-access + return func_graph.name + + +def unique_fn_name(scope, name): + """Returns a unique name to use for a control flow function. + + Args: + scope: A name scope string. + name: An identifier for this function (e.g. "true", "body"). + + Returns: + A string, the name to use for the function. + """ + return ("%s%s_%s" % (scope, name, ops.uid())).replace("/", "_") + + +def unique_grad_fn_name(forward_name): + return "%s_grad_%s" % (forward_name, ops.uid()) + + +def maybe_set_lowering_attr(op, lower_using_switch_merge=None): + """Sets the flag to enable lowering on `op` if necessary. + + Lowering allows cond_v2 and while_v2 to avoid some of the limitations of + Functions, allowing users to specify devices & colocation inside of cond_v2 + and while_v2 input functions, and enabling non-strict evaluation & partial + pruning. This brings v2 control flow closer to feature parity with v1 control + flow. + + However, we do not lower in the following cases: + - When the `If` or `While` ops are in the XLA context. Because it is easier + for XLA to apply its own optimizations when dealing with un-lowered + control flow operators than with low-level control flow primitives. + - When the eager execution context specifies the executor of functions to + be the single threaded executor (see context.function_executor_type()). + Because the single threaded executor does not support v1 control flow ops. + - When 'lower_using_switch_merge' is explicitly set to False. + + Args: + op: An `If` or `While` Operation. + lower_using_switch_merge: Explicit value to lower or not (optional). + """ + if lower_using_switch_merge is not None: + # pylint: disable=protected-access + op._set_attr("_lower_using_switch_merge", + attr_value_pb2.AttrValue(b=lower_using_switch_merge)) + # pylint: enable=protected-access + elif (not _DISABLE_LOWER_USING_SWITCH_MERGE and + not control_flow_util.GraphOrParentsInXlaContext(op.graph) and + context.context().function_call_options.executor_type != + "SINGLE_THREADED_EXECUTOR"): + # pylint: disable=protected-access + op._set_attr("_lower_using_switch_merge", attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + + +def maybe_propagate_compile_time_consts_in_xla(op): + """Tells XLA whether to propagate compile-time consts in the loop body. + + This is needed to make compile time constants available to ops, for example + `max_num_elements` in `EmptyTensorList`, inside the loop body. Ideally this + would always be turned on, but that doesn't work with legacy functionalized + while_loops. + + Args: + op: A `While` Operation. + """ + if control_flow_util.GraphOrParentsInXlaContext(op.graph): + # pylint: disable=protected-access + op._set_attr("_xla_propagate_compile_time_consts", + attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + + +def resource_input_index(tensor_name, input_names, node_defs, functions): + """Returns the index of the input corresponding to `tensor_name`. + + This method is used to find the corresponding index of an arbitrary resource + tensor in a function (the function could be a loop body). We assume that + resource handles are never created in functions, so that every resource + tensor can be traced back to a function input. + + The awkward signature of this method is to make it work with both FuncGraphs + and FunctionDefs. This is so we can recurse on function call ops without + building the corresponding FuncGraph (note that even if a FuncGraph for a + FunctionDef already exists, the input/output/node names may have been + changed when the FuncGraph was serialized to the FunctionDef, which makes it + unusable with this algorithm). + + Args: + tensor_name: the name of the resource tensor to be resolved to an input. + input_names: a list of the names of all inputs to the function. + node_defs: a dict mapping op name -> NodeDef for every op in the function. + functions: a dict mapping function name -> AtomicFunction. + + Returns: + The index into input_names corresponding to `tensor_name`. + """ + while tensor_name not in input_names: + # FunctionDefs and graphs use different tensor naming conventions. + parts = tensor_name.split(":") + if len(parts) == 3: + op_name, _, output_idx = parts + elif len(parts) == 2: + op_name, output_idx = parts + else: + assert len(parts) == 1 + op_name = parts[0] + output_idx = 0 + tensor_name = "%s:%d" % (tensor_name, output_idx) + # Check again for cases where the tensor suffix (":0") is stripped out. + if tensor_name in input_names: + break + output_idx = int(output_idx) + node_def = node_defs[op_name] + + def _extract_input_index(function_attribute_name): + func_name = node_def.attr[function_attribute_name].func.name + fdef = functions[func_name].cached_definition + output_arg_name = fdef.signature.output_arg[output_idx].name + output_tensor_name = fdef.ret[output_arg_name] + return resource_input_index( + output_tensor_name, [arg.name for arg in fdef.signature.input_arg], + {ndef.name: ndef for ndef in fdef.node_def}, functions) + + if node_def.op in ("Identity", "While"): + # Captured resources occur at the same index in the lists of inputs and + # outputs of a while or identity op. So we lookup the input of `tensor.op` + # at the same index as the index of `tensor` in the `tensor.op.outputs`. + tensor_name = node_def.input[output_idx] + elif node_def.op in ("PartitionedCall", "StatefulPartitionedCall"): + # Functions output any captured resource tensors used by their + # gradients. `tensor_name` is one of these outputs from a nested + # function call, so recursively find the corresponding input in the + # nested FunctionDef. + tensor_name = node_def.input[_extract_input_index("f")] + elif node_def.op in ("If", "StatelessIf"): + input_index = _extract_input_index("then_branch") + if input_index != _extract_input_index("else_branch"): + raise AssertionError( + ("Expected cond branches ({} op) to each have the same " + "input->output mapping of resources.").format(node_def.op)) + tensor_name = node_def.input[ + # Ignore the `cond` input; the function inputs come after. + input_index + 1] + else: + # We assume there are no other ops types that will "forward" resource + # handles like this, so all other handles must have been created by the + # op. (Note that cond_v2 wraps resource handle outputs in optionals, + # which we'll end up accumulating). + raise ValueError("Taking gradient of a while loop which creates " + "a resource in its body is not supported: %s (%s)" + % (op_name, node_def.op)) + + return input_names.index(tensor_name) + + +@tf_contextlib.contextmanager +def clear_control_inputs(): + """Clears the control inputs but preserves the ControlFlowContext. + + This is needed to preserve the XLAControlFlowControl when clearing + control inputs for the gradient accumulators in while_v2. + `ops.control_dependencies` does not allow that. + + Yields: + A context manager in which the ops created will not have any control inputs + by default but the control flow context is the same. + """ + # pylint: disable=protected-access + control_flow_context = ops.get_default_graph()._get_control_flow_context() + with ops.control_dependencies(None): + ops.get_default_graph()._set_control_flow_context(control_flow_context) + yield + # pylint: enable=protected-access + + +def _is_tpu_strategy(strategy): + return (strategy is not None and + strategy.__class__.__name__.startswith("TPUStrategy")) + + +def _is_building_keras_layer(): + # TODO(srbs): Remove this function when we no long support session with Keras. + keras_call_context_function = keras_deps.get_call_context_function() + if keras_call_context_function: + return keras_call_context_function().layer is not None + else: + return False + + +def output_all_intermediates(): + """Whether to output all intermediates of a functional control flow op. + + The default behavior is to output intermediates only when building a Keras + Layer in graph mode and that too when certain other conditions are met: + 1. We do not output intermediates if the functional control flow op + is being built inside a FuncGraph which is not a If/While graph. This + guards against outputting intermediates in eager mode since keras adds + tensors to a FuncGraph named "keras_graph" in that case. Also because we + do not output intermediates of tf.function (since this feature is only for + backwards compatibility) outputting intermediates of functional control + flow ops built inside tf.function is of no value. + 2. We do not output intermediates when the compilation is using XLA or for a + TPU. + 3. We do not output intermediates when a single threaded executor is used + since that does not perform inlining and pruning. + + Returns: + A bool telling whether to output all intermediates. + """ + if _EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE is not None: + return _EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE + if in_defun(): + return False + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + return False + if (context.context().function_call_options.executor_type == + "SINGLE_THREADED_EXECUTOR"): + return False + return _is_building_keras_layer() + + +def get_func_graph(op, input_shapes, func_name): + """Generates and returns a FuncGraph for the given op and input_shapes.""" + fdef = None + graph = op.graph + # Recursively search the func in graphs. + while graph is not None: + func = graph._get_function(func_name) # pylint: disable=protected-access + if func is not None: + fdef = func.cached_definition + break + if hasattr(graph, "outer_graph"): + graph = graph.outer_graph + else: + break + + if fdef is None: + raise KeyError("%s cannot be found in the graph" % func_name) + + # `op.graph` may not be the same as `ops.get_default_graph()` e.g. + # in the case of nested if ops or when the gradient is being computed + # from inside a Defun. We build the `func_graph` with `op.graph` as its + # `outer_graph`. This resembles how the `FuncGraph` was built in the + # forward pass. We need this so that we can resolve references to tensors + # in `func_graph` from its gradient graph in `_resolve_grad_inputs`. + with op.graph.as_default(): + func_graph = function_def_to_graph.function_def_to_graph( + fdef, input_shapes=input_shapes) + + # TODO(xjun): Ideally we want to retrieve the gradient functions instead of + # re-create them. But the lifetime of gradient functions of PartitionedCall + # ops is attached to ParitionedCall ops in the original func_graph and + # when we are inside this function we don't have access to the original + # func_graph or PartitionedCall ops. See cl/499362867 and cl/273858076 for + # more context. + for operation in func_graph.get_operations(): + if operation.type in ["PartitionedCall", "StatefulPartitionedCall"]: + f = graph._get_function(operation.get_attr("f").name) # pylint: disable=protected-access + try: + cf = concrete_function.ConcreteFunction.from_func_graph( + f.graph, + f.function_type, + attrs=f.cached_definition.attr, + ) + except AttributeError: + # f is not found or f is a _DefinedFunction that doesn't have a graph. + continue + operation._gradient_function = cf._get_gradient_function() # pylint: disable=protected-access + + return func_graph + + +def get_op_and_outputs(op_or_outputs): + if isinstance(op_or_outputs, ops.Operation): + return op_or_outputs, [] + elif not op_or_outputs: # Empty list. + return None, [] + else: + return op_or_outputs[0].op, op_or_outputs + + +def graph_wrapped_for_higher_order_tape_gradients(graph): + """Check if `graph` is wrapped by `run_as_function_for_tape_gradients`.""" + while graph is not None: + if "cflow_gradient_wrapper" in getattr(graph, "name", ""): + return True + graph = getattr(graph, "outer_graph", None) + return False + + +def run_as_function_for_tape_gradients(make_op, inputs): + """Fix higher-order tape gradients by wrapping `make_op` in a function. + + Args: + make_op: A function that takes a list of inputs and returns a list of output + tensors. This function should set any handle data relevant to its outputs + before returning. + inputs: A list of tensors to check for tape gradients and pass to + `make_op`. These should include all tensors used in `make_op`. + + Returns: + Tensors corresponding to `make_op`'s output. + """ + # GradientTapes created inside a function currently don't work well with + # un-wrapped control flow ops in that same function. Wrapping in an extra + # layer of intermediate function means we run extra logic in the function + # gradient code to record the correct intermediates on the tape. + # + # The function attribute inputs to control flow ops are not hashable, so we + # pass everything as a capture to bypass defun's caching. + if (gradients_util.PossibleTapeGradientTypes(inputs) + == gradients_util.POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER + # We only need one function between the tape and the op; if we've already + # wrapped once, we stop wrapping to avoid infinite recursion. + and not (ops.get_default_graph().building_function + and "cflow_gradient_wrapper" in ops.get_default_graph().name)): + results = tracing_compilation.call_function( + (inputs,), + tracing_options=tracing_compilation.TracingOptions( + make_op, "cflow_gradient_wrapper", autograph=False + ), + ) + return results + else: + return make_op(inputs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_func_graphs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_func_graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..48bfac5239590789c2a5081cecf2fc6a003c5c97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_func_graphs.py @@ -0,0 +1,56 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""FuncGraphs for V2 control flow.""" + +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops + + +class ControlFlowFuncGraph(func_graph.FuncGraph): + """Contains control flow-specific FuncGraph logic.""" + + def __init__(self, *args, **kwargs): + super(ControlFlowFuncGraph, self).__init__(*args, **kwargs) + outer_graph = self.outer_graph + # Unlike tf.function, control flow FuncGraphs are generally created one per + # op. This means hard-coding any outer device scopes in the body (rather + # than inspecting the call-time placement of the control flow op) makes + # sense. + self._device_function_stack = outer_graph._device_function_stack.copy() # pylint: disable=protected-access + self.is_control_flow_graph = True + if ops.executing_eagerly_outside_functions(): + func_graph.override_func_graph_name_scope( + self, self.outer_graph.get_name_scope()) + + +class CondBranchFuncGraph(ControlFlowFuncGraph): + """FuncGraph for branches of tf.cond(). + + This is used to distinguish cond branches from other functions. + """ + + +class WhileCondFuncGraph(ControlFlowFuncGraph): + """FuncGraph for the condition of tf.while_loop(). + + This is used to distinguish while conditions from other functions. + """ + + +class WhileBodyFuncGraph(ControlFlowFuncGraph): + """FuncGraph for the body of tf.while_loop(). + + This is used to distinguish while bodies from other functions. + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_toggles.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_toggles.py new file mode 100644 index 0000000000000000000000000000000000000000..0985ce929112b98998ef9597b249282c887176c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/control_flow_v2_toggles.py @@ -0,0 +1,97 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""API for enabling v2 control flow.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import control_flow_util_v2 +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["enable_control_flow_v2"]) +def enable_control_flow_v2(): # pylint: disable=invalid-name + """Use control flow v2. + + control flow v2 (cfv2) is an improved version of control flow in TensorFlow + with support for higher order derivatives. Enabling cfv2 will change the + graph/function representation of control flow, e.g., `tf.while_loop` and + `tf.cond` will generate functional `While` and `If` ops instead of low-level + `Switch`, `Merge` etc. ops. Note: Importing and running graphs exported + with old control flow will still be supported. + + Calling tf.enable_control_flow_v2() lets you opt-in to this TensorFlow 2.0 + feature. + + Note: v2 control flow is always enabled inside of tf.function. Calling this + function is not required. + """ + # pylint: disable=protected-access + logging.vlog(1, "Enabling control flow v2") + ops._control_flow_api_gauge.get_cell().set(True) + control_flow_util.ENABLE_CONTROL_FLOW_V2 = True + + +@tf_export(v1=["disable_control_flow_v2"]) +def disable_control_flow_v2(): # pylint: disable=invalid-name + """Opts out of control flow v2. + + Note: v2 control flow is always enabled inside of tf.function. Calling this + function has no effect in that case. + + If your code needs tf.disable_control_flow_v2() to be called to work + properly please file a bug. + """ + # pylint: disable=protected-access + logging.vlog(1, "Disabling control flow v2") + ops._control_flow_api_gauge.get_cell().set(False) + control_flow_util.ENABLE_CONTROL_FLOW_V2 = False + + +@tf_export(v1=["control_flow_v2_enabled"]) +def control_flow_v2_enabled(): # pylint: disable=invalid-name + """Returns `True` if v2 control flow is enabled. + + Note: v2 control flow is always enabled inside of tf.function. + """ + return control_flow_util.EnableControlFlowV2(ops.get_default_graph()) + + +@tf_export(v1=["experimental.output_all_intermediates"]) +def output_all_intermediates(state): # pylint: disable=invalid-name + """Whether to output all intermediates from functional control flow ops. + + The "default" behavior to is to output all intermediates when using v2 control + flow inside Keras models in graph mode (possibly inside Estimators). This is + needed to support taking gradients of v2 control flow. In graph mode, Keras + can sometimes freeze the forward graph before the gradient computation which + does not work for v2 control flow since it requires updating the forward ops + to output the needed intermediates. We work around this by proactively + outputting the needed intermediates when building the forward pass itself. + Ideally any such extra tensors should be pruned out at runtime. However, if + for any reason this doesn't work for you or if you have an inference-only + model you can turn this behavior off using + `tf.compat.v1.experimental.output_all_intermediates(False)`. + + If with the default behavior you are still seeing errors of the form + "Connecting to invalid output X of source node Y which has Z outputs" try + setting `tf.compat.v1.experimental.output_all_intermediates(True)` and + please file an issue at https://github.com/tensorflow/tensorflow/issues. + + Args: + state: True, False or None. None restores the default behavior. + """ + control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = state # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/critical_section_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/critical_section_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8412d9932beb9c5655a580528b455b32d6d70259 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/critical_section_ops.py @@ -0,0 +1,419 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Critical Section object and execution logic.""" + +import collections +import contextlib +import threading + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +__all__ = ["CriticalSection"] + + +# Graph Keys +CRITICAL_SECTIONS = "critical_sections" +CRITICAL_SECTION_EXECUTIONS = "critical_section_executions" + + +class _ExecutionSignature( + collections.namedtuple("_ExecutionSignature", + ("op", "handle", + "resources", "exclusive_resource_access"))): + """A class storing an `ExecuteInCriticalResource` op and associated attrs.""" + pass + + +def _identity(x): + """Identity op that recognizes `TensorArray`, `Operation`, and `Tensor`.""" + if isinstance(x, tensor_array_ops.TensorArray): + return x.identity() + elif isinstance(x, ops.Operation): + return control_flow_ops.group(x) + elif context.executing_eagerly() and x is None: + return None + else: + return array_ops.identity(x) + + +def _get_device_or_colocation(op): + return op.device or _get_colocation(op) + + +def _get_colocation(op): + """Get colocation symbol from op, if any.""" + try: + return op.get_attr("_class") + except (ValueError, AttributeError): + return None + + +_CRITICAL_SECTION_STACK = threading.local() + + +def _get_critical_section_stack(): + try: + return _CRITICAL_SECTION_STACK.value + except AttributeError: + _CRITICAL_SECTION_STACK.value = [] + return _CRITICAL_SECTION_STACK.value + + +@contextlib.contextmanager +def _push_critical_section_stack(signature): + """Push a CriticalSection._signature to the thread-local stack. + + If the signature is already on the stack, raise an error because it means + we're trying to execute inside the same locked CriticalSection, which + will create a deadlock. + + Args: + signature: Tuple of the type `CriticalSection._signature`. Uniquely + identifies a CriticalSection by its `shared_name`, `container`, + and device. + + Yields: + An empty value. The context is guaranteed to run without deadlock. + + Raises: + ValueError: If the signature is already on the stack. + RuntimeError: If another thread or function modifies the current stack + entry during the yield. + """ + stack = _get_critical_section_stack() + if signature in stack: + raise ValueError( + f"Attempting to lock a CriticalSection (signature={signature}) in which" + " we are already running. This is illegal and may cause deadlocks.") + stack.append(signature) + try: + yield + finally: + received_signature = stack.pop() + if received_signature != signature: + raise RuntimeError( + "CriticalSection stack inconsistency: expected signature " + f"{signature} but received {received_signature}") + + +@tf_export("CriticalSection") +class CriticalSection: + """Critical section. + + A `CriticalSection` object is a resource in the graph which executes subgraphs + in **serial** order. A common example of a subgraph one may wish to run + exclusively is the one given by the following function: + + ```python + v = resource_variable_ops.ResourceVariable(0.0, name="v") + + def count(): + value = v.read_value() + with tf.control_dependencies([value]): + with tf.control_dependencies([v.assign_add(1)]): + return tf.identity(value) + ``` + + Here, a snapshot of `v` is captured in `value`; and then `v` is updated. + The snapshot value is returned. + + If multiple workers or threads all execute `count` in parallel, there is no + guarantee that access to the variable `v` is atomic at any point within + any thread's calculation of `count`. In fact, even implementing an atomic + counter that guarantees that the user will see each value `0, 1, ...,` is + currently impossible. + + The solution is to ensure any access to the underlying resource `v` is + only processed through a critical section: + + ```python + cs = CriticalSection() + f1 = cs.execute(count) + f2 = cs.execute(count) + output = f1 + f2 + session.run(output) + ``` + The functions `f1` and `f2` will be executed serially, and updates to `v` + will be atomic. + + **NOTES** + + All resource objects, including the critical section and any captured + variables of functions executed on that critical section, will be + colocated to the same device (host and cpu/gpu). + + When using multiple critical sections on the same resources, there is no + guarantee of exclusive access to those resources. This behavior is disallowed + by default (but see the kwarg `exclusive_resource_access`). + + For example, running the same function in two separate critical sections + will not ensure serial execution: + + ```python + v = tf.compat.v1.get_variable("v", initializer=0.0, use_resource=True) + def accumulate(up): + x = v.read_value() + with tf.control_dependencies([x]): + with tf.control_dependencies([v.assign_add(up)]): + return tf.identity(x) + ex1 = CriticalSection().execute( + accumulate, 1.0, exclusive_resource_access=False) + ex2 = CriticalSection().execute( + accumulate, 1.0, exclusive_resource_access=False) + bad_sum = ex1 + ex2 + sess.run(v.initializer) + sess.run(bad_sum) # May return 0.0 + ``` + """ + + def __init__(self, name=None, shared_name=None, + critical_section_def=None, import_scope=None): + """Creates a critical section.""" + context.ensure_initialized() + if critical_section_def and name is not None: + raise ValueError(f"Arguments critical_section_def={critical_section_def} " + f"and shared_name={shared_name} are mutually exclusive. " + "Please only specify one of them.") + if critical_section_def: + raise ValueError("Argument `critical_section_def` is not supported.") + else: + self._init_from_args(name, shared_name) + + def _init_from_args(self, name, shared_name): # pylint: disable=invalid-name + """Initialize the CriticalSection from constructor arguments.""" + with ops.name_scope(name, "CriticalSection", []) as name: + with ops.init_scope(): + # pylint: disable=protected-access + container = ops.get_default_graph()._container + # pylint: enable=protected-access + if shared_name is None: + shared_name = name + if container is None: + container = "" + self._handle = gen_resource_variable_ops.mutex_v2( + shared_name=shared_name, container=container, name=name) + # Get a uniquely identifying signature for the handle. + self._signature = ( + container, + # If shared_name is empty, a unique CriticalSection is created. + shared_name or id(self._handle), + _get_device_or_colocation(self._handle)) + + if not context.executing_eagerly(): + ops.add_to_collections(CRITICAL_SECTIONS, self) + + @property + def name(self): + return self._handle.op.name + + def execute(self, fn, exclusive_resource_access=True, name=None): + """Execute function `fn()` inside the critical section. + + `fn` should not accept any arguments. To add extra arguments to when + calling `fn` in the critical section, create a lambda: + + ```python + critical_section.execute(lambda: fn(*my_args, **my_kwargs)) + ``` + + Args: + fn: The function to execute. Must return at least one tensor. + exclusive_resource_access: Whether the resources required by + `fn` should be exclusive to this `CriticalSection`. Default: `True`. + You may want to set this to `False` if you will be accessing a + resource in read-only mode in two different CriticalSections. + name: The name to use when creating the execute operation. + + Returns: + The tensors returned from `fn()`. + + Raises: + ValueError: If `fn` attempts to lock this `CriticalSection` in any nested + or lazy way that may cause a deadlock. + ValueError: If `exclusive_resource_access == True` and + another `CriticalSection` has an execution requesting the same + resources as `fn``. Note, even if `exclusive_resource_access` is + `True`, if another execution in another `CriticalSection` was created + without `exclusive_resource_access=True`, a `ValueError` will be raised. + """ + with ops.name_scope(name, "critical_section_execute", []): + # Ensure that mutex locking only happens *after* all args and + # kwargs have been executed. This avoids certain types of deadlocks. + with _push_critical_section_stack(self._signature): + lock = gen_resource_variable_ops.mutex_lock(self._handle) + + if not context.executing_eagerly(): + # NOTE(ebrevdo): This is to ensure we don't pick up spurious + # Operations created by other threads. + with ops.get_default_graph()._lock: # pylint: disable=protected-access + existing_ops = ops.get_default_graph().get_operations() + with ops.control_dependencies([lock]): + r = fn() + # TODO(ebrevdo): If creating critical sections in a python loop, + # this makes graph creation time quadratic. Revisit if this + # becomes a problem. + created_ops = (set(ops.get_default_graph().get_operations()) + .difference(existing_ops)) + else: + with ops.control_dependencies([lock]): + r = fn() + + if not context.executing_eagerly(): + self._add_control_dependencies_to_lock(created_ops, lock.op) + + # captured_resources is a list of resources that are directly + # accessed only by ops created during fn(), not by any + # ancestors of those ops in the graph. + captured_resources = object_identity.ObjectIdentitySet([ + input_ for op in created_ops + for input_ in op.inputs + if input_.dtype == dtypes.resource + ]) + + # NOTE(ebrevdo): The only time self._is_self_handle() is True + # in this call is if one of the recently created ops, within + # the execute(), themselves attempt to access the + # CriticalSection. This will cause a deadlock. + if any(self._is_self_handle(x) for x in captured_resources): + raise ValueError( + "Attempting to lock a CriticalSection in which we are " + f"already running (signature={self._signature}). This is illegal " + "and may cause deadlocks.") + + self._check_multiple_access_to_resources( + captured_resources, exclusive_resource_access) + + r_flat = [_identity(x) for x in nest.flatten(r)] + + with ops.control_dependencies(r_flat): + # The identity must run on the same machine as self._handle + with ops.colocate_with(self._handle): + # Do not use array_ops.identity as there are special + # optimizations within TensorFlow which seem to elide it + # even when optimizations are disabled(!). + ensure_lock_exists = gen_resource_variable_ops.consume_mutex_lock( + lock) + + # Make sure that if any element of r is accessed, all of + # them are executed together. + r = nest.pack_sequence_as(r, control_flow_ops.tuple(nest.flatten(r))) + + with ops.control_dependencies([ensure_lock_exists]): + outputs = nest.map_structure(_identity, r) + + if not context.executing_eagerly(): + signature = _ExecutionSignature( + op=lock.op, + handle=self._handle, + resources=list(captured_resources), + exclusive_resource_access=exclusive_resource_access) + ops.add_to_collections( + CRITICAL_SECTION_EXECUTIONS, signature) + + return outputs + + def _add_control_dependencies_to_lock(self, created_ops, lock_op): + """To avoid deadlocks, all args must be executed before lock_op.""" + # Get all arguments (explicit and captured) of all ops created by fn(). + all_args = set([input_.op for op in created_ops for input_ in op.inputs]) + all_args.update( + input_op for op in created_ops for input_op in op.control_inputs) + # Unfortunately, we can't use sets throughout because TF seems to + # create new Operation objects for the same op sometimes; and we + # can't rely on id(op). + + # pylint: disable=protected-access + all_args_dict = dict((op._id, op) for op in all_args) + + # Remove ops created within fn, or that lock_op already has a + # control dependency on. Also remove a possible self-loop. + for op in created_ops: + all_args_dict.pop(op._id, None) + for op in lock_op.control_inputs: + all_args_dict.pop(op._id, None) + for input_ in lock_op.inputs: + all_args_dict.pop(input_.op._id, None) + all_args_dict.pop(lock_op._id, None) + + all_args = all_args_dict.values() + + if not all_args: + # No control dependencies to add; return early. + return + + # This group is important: it ensures that any ops in all_args + # outside the control context of the lock_op (and this fn, which + # runs in the same context) are added to this context before + # being added to the control dependencies of lock_op. + all_args = control_flow_ops.group(*all_args) + + lock_op._add_control_input(all_args) + # pylint: enable=protected-access + + def _is_self_handle(self, x): + """Check if the tensor `x` is the same Mutex as `self._handle`.""" + if isinstance(x, ops.EagerTensor): + return x is self._handle + return (x.op.type == "MutexV2" + # blank shared_name means the op will create a unique one. + and x.op.get_attr("shared_name") + and (x.op.get_attr("shared_name") == + self._handle.op.get_attr("shared_name")) + and (x.op.device == self._handle.op.device + or _get_colocation(x.op) == _get_colocation(self._handle.op))) + + def _check_multiple_access_to_resources( + self, captured_resources, exclusive_resource_access): + """Raise if captured_resources are accessed by another CriticalSection. + + Args: + captured_resources: Set of tensors of type resource. + exclusive_resource_access: Whether this execution requires exclusive + resource access. + + Raises: + ValueError: If any tensors in `captured_resources` are also accessed + by another `CriticalSection`, and at least one of them requires + exclusive resource access. + """ + # Collections and op introspection does not work in eager + # mode. This is generally ok; since eager mode (as of + # writing) executes sequentially anyway. + for sg in ops.get_collection(CRITICAL_SECTION_EXECUTIONS): + if self._is_self_handle(sg.handle): + # Other executions in the same critical section are allowed. + continue + if not (exclusive_resource_access or sg.exclusive_resource_access): + # Neither execution requested exclusive access. + continue + resource_intersection = captured_resources.intersection(sg.resources) + if resource_intersection: + raise ValueError( + "This execution would access resources: " + f"{list(resource_intersection)}. Either this lock " + f"(CriticalSection: {self._handle}) or lock '{sg}' " + f"(CriticalSection: {sg.handle}) requested exclusive resource " + "access of this resource. Did you mean to call execute with " + "keyword argument exclusive_resource_access=False?") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ctc_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ctc_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1bde62c0adbc2061bba84362ac3cf856de905a23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ctc_ops.py @@ -0,0 +1,1557 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""CTC (Connectionist Temporal Classification) Operations.""" + +import uuid + +# TODO(b/280454072) Remove compat and inplace_ops when foward compatibility +# window expires. +from tensorflow.python.compat import compat +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import custom_gradient +from tensorflow.python.ops import functional_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_ctc_ops +from tensorflow.python.ops import inplace_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops.nn_grad import _BroadcastMul +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +_DEFUN_API_NAME_ATTRIBUTE = "api_implements" +_DEFUN_DEVICE_ATTRIBUTE = "api_preferred_device" +_CPU_DEVICE_NAME = "CPU" +_GPU_DEVICE_NAME = "GPU" + + +def _get_context_device_type(): + """Parses the current context and returns the device type, eg CPU/GPU.""" + current_device = context.context().device_name + if current_device is None: + return None + return device.DeviceSpec.from_string(current_device).device_type + + +def _generate_defun_backend(unique_api_name, preferred_device, func): + function_attributes = { + _DEFUN_API_NAME_ATTRIBUTE: unique_api_name, + _DEFUN_DEVICE_ATTRIBUTE: preferred_device, + } + return def_function.function( + func=func, experimental_attributes=function_attributes, autograph=False) + +# pylint: disable=protected-access, invalid-name +@tf_export(v1=["nn.ctc_loss"]) +@dispatch.add_dispatch_support +def ctc_loss(labels, + inputs=None, + sequence_length=None, + preprocess_collapse_repeated=False, + ctc_merge_repeated=True, + ignore_longer_outputs_than_inputs=False, + time_major=True, + logits=None): + """Computes the CTC (Connectionist Temporal Classification) Loss. + + This op implements the CTC loss as presented in (Graves et al., 2006). + + Input requirements: + + ``` + sequence_length(b) <= time for all b + + max(labels.indices(labels.indices[:, 1] == b, 2)) + <= sequence_length(b) for all b. + ``` + + Notes: + + This class performs the softmax operation for you, so inputs should + be e.g. linear projections of outputs by an LSTM. + + The `inputs` Tensor's innermost dimension size, `num_classes`, represents + `num_labels + 1` classes, where num_labels is the number of true labels, and + the largest value `(num_classes - 1)` is reserved for the blank label. + + For example, for a vocabulary containing 3 labels `[a, b, c]`, + `num_classes = 4` and the labels indexing is `{a: 0, b: 1, c: 2, blank: 3}`. + + Regarding the arguments `preprocess_collapse_repeated` and + `ctc_merge_repeated`: + + If `preprocess_collapse_repeated` is True, then a preprocessing step runs + before loss calculation, wherein repeated labels passed to the loss + are merged into single labels. This is useful if the training labels come + from, e.g., forced alignments and therefore have unnecessary repetitions. + + If `ctc_merge_repeated` is set False, then deep within the CTC calculation, + repeated non-blank labels will not be merged and are interpreted + as individual labels. This is a simplified (non-standard) version of CTC. + + Here is a table of the (roughly) expected first order behavior: + + * `preprocess_collapse_repeated=False`, `ctc_merge_repeated=True` + + Classical CTC behavior: Outputs true repeated classes with blanks in + between, and can also output repeated classes with no blanks in + between that need to be collapsed by the decoder. + + * `preprocess_collapse_repeated=True`, `ctc_merge_repeated=False` + + Never learns to output repeated classes, as they are collapsed + in the input labels before training. + + * `preprocess_collapse_repeated=False`, `ctc_merge_repeated=False` + + Outputs repeated classes with blanks in between, but generally does not + require the decoder to collapse/merge repeated classes. + + * `preprocess_collapse_repeated=True`, `ctc_merge_repeated=True` + + Untested. Very likely will not learn to output repeated classes. + + The `ignore_longer_outputs_than_inputs` option allows to specify the behavior + of the CTCLoss when dealing with sequences that have longer outputs than + inputs. If true, the CTCLoss will simply return zero gradient for those + items, otherwise an InvalidArgument error is returned, stopping training. + + Args: + labels: An `int32` `SparseTensor`. + `labels.indices[i, :] == [b, t]` means `labels.values[i]` stores the id + for (batch b, time t). `labels.values[i]` must take on values in `[0, + num_labels)`. See `core/ops/ctc_ops.cc` for more details. + inputs: 3-D `float` `Tensor`. + If time_major == False, this will be a `Tensor` shaped: `[batch_size, + max_time, num_classes]`. + If time_major == True (default), this will be a `Tensor` shaped: + `[max_time, batch_size, num_classes]`. The logits. + sequence_length: 1-D `int32` vector, size `[batch_size]`. The sequence + lengths. + preprocess_collapse_repeated: Boolean. Default: False. If True, repeated + labels are collapsed prior to the CTC calculation. + ctc_merge_repeated: Boolean. Default: True. + ignore_longer_outputs_than_inputs: Boolean. Default: False. If True, + sequences with longer outputs than inputs will be ignored. + time_major: The shape format of the `inputs` Tensors. If True, these + `Tensors` must be shaped `[max_time, batch_size, num_classes]`. If False, + these `Tensors` must be shaped `[batch_size, max_time, num_classes]`. + Using `time_major = True` (default) is a bit more efficient because it + avoids transposes at the beginning of the ctc_loss calculation. However, + most TensorFlow data is batch-major, so by this function also accepts + inputs in batch-major form. + logits: Alias for inputs. + + Returns: + A 1-D `float` `Tensor`, size `[batch]`, containing the negative log + probabilities. + + Raises: + TypeError: if labels is not a `SparseTensor`. + + References: + Connectionist Temporal Classification - Labeling Unsegmented Sequence Data + with Recurrent Neural Networks: + [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) + ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf)) + """ + return _ctc_loss_impl( + labels, + inputs, + sequence_length, + preprocess_collapse_repeated, + ctc_merge_repeated, + ignore_longer_outputs_than_inputs, + time_major, + logits, + use_cudnn=False) + + +def _ctc_loss_impl(labels, + inputs=None, + sequence_length=None, + preprocess_collapse_repeated=False, + ctc_merge_repeated=True, + ignore_longer_outputs_than_inputs=False, + time_major=True, + logits=None, + use_cudnn=False): + # Helper function of ctc_loss with one additional param: + # use_cudnn: A bool to enable cuDNN CTC loss operation. If true, the blank + # index has to be 0. + + # The second, third, etc output tensors contain the gradients. We use it in + # _CTCLossGrad() below. + if not isinstance(labels, sparse_tensor.SparseTensor): + raise TypeError("Expected argument `labels` to be a SparseTensor. " + f"Received labels={labels} of type: " + f"{type(labels).__name__}") + + # For internal calculations, we transpose to [time, batch, num_classes] + inputs = deprecation.deprecated_argument_lookup("logits", logits, "inputs", + inputs) + + inputs = ops.convert_to_tensor(inputs, name="logits") + if not time_major: + inputs = array_ops.transpose(inputs, [1, 0, 2]) # (B,T,N) => (T,B,N) + + orig_dtype = inputs.dtype + if orig_dtype in (dtypes.float16, dtypes.bfloat16): + inputs = math_ops.cast(inputs, dtypes.float32) + + # gen_ctc_ops.ctc_loss_v2 differs from gen_ctc_ops.ctc_loss. v2 assumes the + # blank index to be 0, but v1 views it as the last index. + if use_cudnn: + ctc_loss_func = gen_ctc_ops.ctc_loss_v2 + else: + ctc_loss_func = gen_ctc_ops.ctc_loss + + loss, _ = ctc_loss_func( + inputs, + labels.indices, + labels.values, + sequence_length, + preprocess_collapse_repeated=preprocess_collapse_repeated, + ctc_merge_repeated=ctc_merge_repeated, + ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs) + + if orig_dtype in (dtypes.float16, dtypes.bfloat16): + loss = math_ops.cast(loss, orig_dtype) + + return loss + +# pylint: disable=unused-argument +def _CTCLossGradImpl(op, grad_loss, _): + # Outputs are: loss, grad + # + # Currently there is no way to take the second derivative of this op + # due to the fused implementation's interaction with tf.gradients(), + # so we make sure we prevent silently incorrect results by raising + # an error if the second derivative is requested via prevent_gradient. + grad_without_gradient = array_ops.prevent_gradient( + op.outputs[1], + message="Currently there is no way to take the second " + " derivative of ctc_loss due to the fused implementation's interaction " + " with tf.gradients()") + # Return gradient for inputs and None for + # labels_indices, labels_values and sequence_length + return [_BroadcastMul(grad_loss, grad_without_gradient), None, None, None] + + +# pylint: disable=unused-argument +@ops.RegisterGradient("CTCLoss") +def _CTCLossGrad(op, grad_loss, _): + """The derivative provided by CTC Loss. + + Args: + op: the CTCLoss op. + grad_loss: The backprop for cost. + + Returns: + The CTC Loss gradient. + """ + return _CTCLossGradImpl(op, grad_loss, _) + + +# pylint: disable=unused-argument +@ops.RegisterGradient("CTCLossV2") +def _CTCLossV2Grad(op, grad_loss, _): + """The derivative provided by CTC Loss V2. + + Args: + op: the CTCLossV2 op. + grad_loss: The backprop for cost. + + Returns: + The CTC Loss V2 gradient. + """ + return _CTCLossGradImpl(op, grad_loss, _) + + +@tf_export("nn.ctc_greedy_decoder") +@dispatch.add_dispatch_support +def ctc_greedy_decoder(inputs, + sequence_length, + merge_repeated=True, + blank_index=None): + """Performs greedy decoding on the logits given in input (best path). + + Given a tensor as `inputs`, the `blank_index` parameter defines the class + index of the blank symbol. + + For example: + + If `blank_index` is equal to 1: + + >>> inf = float("inf") + >>> logits = tf.constant([[[ 0., -inf, -inf], + ... [ -2.3, -inf, -0.1]], + ... [[ -inf, -0.5, -inf], + ... [ -inf, -inf, -0.1]], + ... [[ -inf, -inf, -inf], + ... [ -0.1, -inf, -2.3]]]) + >>> seq_lens = tf.constant([2, 3]) + >>> outputs = tf.nn.ctc_greedy_decoder( + ... logits, + ... seq_lens, + ... blank_index=1) + + Notes: + + - Unlike `ctc_beam_search_decoder`, `ctc_greedy_decoder` considers blanks + as regular elements when computing the probability of a sequence. + - Default `blank_index` is `(num_classes - 1)`, unless overriden. + + If `merge_repeated` is `True`, merge repeated classes in output. + This means that if consecutive logits' maximum indices are the same, + only the first of these is emitted. The sequence `A B B * B * B` (where '*' + is the blank label) becomes + + * `A B B B` if `merge_repeated=True`. + * `A B B B B` if `merge_repeated=False`. + + Args: + inputs: 3-D `float` `Tensor` sized `[max_time, batch_size, num_classes]`. + The logits. + sequence_length: 1-D `int32` vector containing sequence lengths, having size + `[batch_size]`. + merge_repeated: Boolean. Default: True. + blank_index: (Optional). Default: `num_classes - 1`. Define the class index + to use for the blank label. Negative values will start from num_classes, + ie, -1 will reproduce the ctc_greedy_decoder behavior of using + num_classes - 1 for the blank symbol, which corresponds to the default. + + Returns: + A tuple `(decoded, neg_sum_logits)` where + + decoded: A single-element list. `decoded[0]` + is an `SparseTensor` containing the decoded outputs s.t.: + + `decoded.indices`: Indices matrix `(total_decoded_outputs, 2)`. + The rows store: `[batch, time]`. + + `decoded.values`: Values vector, size `(total_decoded_outputs)`. + The vector stores the decoded classes. + + `decoded.dense_shape`: Shape vector, size `(2)`. + The shape values are: `[batch_size, max_decoded_length]` + + neg_sum_logits: A `float` matrix `(batch_size x 1)` containing, for the + sequence found, the negative of the sum of the greatest logit at each + timeframe. + """ + + outputs = gen_ctc_ops.ctc_greedy_decoder( + inputs, + sequence_length, + merge_repeated=merge_repeated, + blank_index=blank_index) + (decoded_ix, decoded_val, decoded_shape, log_probabilities) = outputs + return ([sparse_tensor.SparseTensor(decoded_ix, decoded_val, + decoded_shape)], log_probabilities) + + +@tf_export(v1=["nn.ctc_beam_search_decoder"]) +@dispatch.add_dispatch_support +def ctc_beam_search_decoder(inputs, + sequence_length, + beam_width=100, + top_paths=1, + merge_repeated=True): + """Performs beam search decoding on the logits given in input. + + **Note** Although in general greedy search is a special case of beam-search + with `top_paths=1` and `beam_width=1`, `ctc_beam_search_decoder` differs + from `ctc_greedy_decoder` in the treatment of blanks when computing the + probability of a sequence: + - `ctc_beam_search_decoder` treats blanks as sequence termination + - `ctc_greedy_decoder` treats blanks as regular elements + + If `merge_repeated` is `True`, merge repeated classes in the output beams. + This means that if consecutive entries in a beam are the same, + only the first of these is emitted. That is, when the sequence is + `A B B * B * B` (where '*' is the blank label), the return value is: + + * `A B` if `merge_repeated = True`. + * `A B B B` if `merge_repeated = False`. + + Args: + inputs: 3-D `float` `Tensor`, size `[max_time x batch_size x num_classes]`. + The logits. + sequence_length: 1-D `int32` vector containing sequence lengths, having size + `[batch_size]`. + beam_width: An int scalar >= 0 (beam search beam width). + top_paths: An int scalar >= 0, <= beam_width (controls output size). + merge_repeated: Boolean. Default: True. + + Returns: + A tuple `(decoded, log_probabilities)` where + + decoded: A list of length top_paths, where `decoded[j]` + is a `SparseTensor` containing the decoded outputs: + + `decoded[j].indices`: Indices matrix `(total_decoded_outputs[j] x 2)` + The rows store: [batch, time]. + + `decoded[j].values`: Values vector, size `(total_decoded_outputs[j])`. + The vector stores the decoded classes for beam j. + + `decoded[j].dense_shape`: Shape vector, size `(2)`. + The shape values are: `[batch_size, max_decoded_length[j]]`. + + log_probability: A `float` matrix `(batch_size x top_paths)` containing + sequence log-probabilities. + """ + + decoded_ixs, decoded_vals, decoded_shapes, log_probabilities = ( + gen_ctc_ops.ctc_beam_search_decoder( + inputs, + sequence_length, + beam_width=beam_width, + top_paths=top_paths, + merge_repeated=merge_repeated)) + + return ([ + sparse_tensor.SparseTensor(ix, val, shape) + for (ix, val, shape) in zip(decoded_ixs, decoded_vals, decoded_shapes) + ], log_probabilities) + + +@tf_export("nn.ctc_beam_search_decoder", v1=["nn.ctc_beam_search_decoder_v2"]) +@dispatch.add_dispatch_support +def ctc_beam_search_decoder_v2(inputs, + sequence_length, + beam_width=100, + top_paths=1): + """Performs beam search decoding on the logits given in input. + + **Note** Although in general greedy search is a special case of beam-search + with `top_paths=1` and `beam_width=1`, `ctc_beam_search_decoder` differs + from `ctc_greedy_decoder` in the treatment of blanks when computing the + probability of a sequence: + - `ctc_beam_search_decoder` treats blanks as sequence termination + - `ctc_greedy_decoder` treats blanks as regular elements + + Args: + inputs: 3-D `float` `Tensor`, size `[max_time, batch_size, num_classes]`. + The logits. + sequence_length: 1-D `int32` vector containing sequence lengths, having size + `[batch_size]`. + beam_width: An int scalar >= 0 (beam search beam width). + top_paths: An int scalar >= 0, <= beam_width (controls output size). + + Returns: + A tuple `(decoded, log_probabilities)` where + + decoded: A list of length top_paths, where `decoded[j]` + is a `SparseTensor` containing the decoded outputs: + + `decoded[j].indices`: Indices matrix `[total_decoded_outputs[j], 2]`; + The rows store: `[batch, time]`. + + `decoded[j].values`: Values vector, size `[total_decoded_outputs[j]]`. + The vector stores the decoded classes for beam `j`. + + `decoded[j].dense_shape`: Shape vector, size `(2)`. + The shape values are: `[batch_size, max_decoded_length[j]]`. + + log_probability: A `float` matrix `[batch_size, top_paths]` containing + sequence log-probabilities. + """ + + # Note, merge_repeated is an invalid optimization that is removed from the + # public API: it returns low probability paths. + return ctc_beam_search_decoder( + inputs, + sequence_length=sequence_length, + beam_width=beam_width, + top_paths=top_paths, + merge_repeated=False) + + +ops.NotDifferentiable("CTCGreedyDecoder") +ops.NotDifferentiable("CTCBeamSearchDecoder") + + +def _ctc_state_trans(label_seq): + """Computes CTC alignment model transition matrix. + + Args: + label_seq: tensor of shape [batch_size, max_seq_length] + + Returns: + tensor of shape [batch_size, states, states] with a state transition matrix + computed for each sequence of the batch. + """ + + with ops.name_scope("ctc_state_trans"): + label_seq = ops.convert_to_tensor(label_seq, name="label_seq") + batch_size = _get_dim(label_seq, 0) + num_labels = _get_dim(label_seq, 1) + + num_label_states = num_labels + 1 + num_states = 2 * num_label_states + + label_states = math_ops.range(num_label_states) + blank_states = label_states + num_label_states + + # Start state to first label. + start_to_label = [[1, 0]] + + # Blank to label transitions. + blank_to_label = array_ops_stack.stack( + [label_states[1:], blank_states[:-1]], 1) + + # Label to blank transitions. + label_to_blank = array_ops_stack.stack([blank_states, label_states], 1) + + # Scatter transitions that don't depend on sequence. + indices = array_ops.concat([start_to_label, blank_to_label, label_to_blank], + 0) + values = array_ops.ones([_get_dim(indices, 0)]) + trans = array_ops.scatter_nd( + indices, values, shape=[num_states, num_states]) + trans += linalg_ops.eye(num_states) # Self-loops. + + # Label to label transitions. Disallow transitions between repeated labels + # with no blank state in between. + batch_idx = array_ops.zeros_like(label_states[2:]) + indices = array_ops_stack.stack( + [batch_idx, label_states[2:], label_states[1:-1]], 1) + indices = array_ops.tile( + array_ops.expand_dims(indices, 0), [batch_size, 1, 1]) + batch_idx = array_ops.expand_dims(math_ops.range(batch_size), 1) * [1, 0, 0] + indices += array_ops.expand_dims(batch_idx, 1) + repeats = math_ops.equal(label_seq[:, :-1], label_seq[:, 1:]) + values = 1.0 - math_ops.cast(repeats, dtypes.float32) + batched_shape = [batch_size, num_states, num_states] + label_to_label = array_ops.scatter_nd(indices, values, batched_shape) + + return array_ops.expand_dims(trans, 0) + label_to_label + + +def ctc_state_log_probs(seq_lengths, max_seq_length): + """Computes CTC alignment initial and final state log probabilities. + + Create the initial/final state values directly as log values to avoid + having to take a float64 log on tpu (which does not exist). + + Args: + seq_lengths: int tensor of shape [batch_size], seq lengths in the batch. + max_seq_length: int, max sequence length possible. + + Returns: + initial_state_log_probs, final_state_log_probs + """ + + batch_size = _get_dim(seq_lengths, 0) + num_label_states = max_seq_length + 1 + num_duration_states = 2 + num_states = num_duration_states * num_label_states + log_0 = math_ops.cast( + math_ops.log(math_ops.cast(0, dtypes.float64) + 1e-307), dtypes.float32) + + initial_state_log_probs = array_ops.one_hot( + indices=array_ops.zeros([batch_size], dtype=dtypes.int32), + depth=num_states, + on_value=0.0, + off_value=log_0, + axis=1) + + label_final_state_mask = array_ops.one_hot( + seq_lengths, depth=num_label_states, axis=0) + duration_final_state_mask = array_ops.ones( + [num_duration_states, 1, batch_size]) + final_state_mask = duration_final_state_mask * label_final_state_mask + final_state_log_probs = (1.0 - final_state_mask) * log_0 + final_state_log_probs = array_ops.reshape(final_state_log_probs, + [num_states, batch_size]) + + return initial_state_log_probs, array_ops.transpose(final_state_log_probs) + + +def _ilabel_to_state(labels, num_labels, ilabel_log_probs): + """Project ilabel log probs to state log probs.""" + + num_label_states = _get_dim(labels, 1) + blank = ilabel_log_probs[:, :, :1] + blank = array_ops.tile(blank, [1, 1, num_label_states + 1]) + one_hot = array_ops.one_hot(labels, depth=num_labels) + one_hot = array_ops.expand_dims(one_hot, axis=0) + ilabel_log_probs = array_ops.expand_dims(ilabel_log_probs, axis=2) + state_log_probs = math_ops.reduce_sum(ilabel_log_probs * one_hot, axis=3) + state_log_probs = array_ops.concat([state_log_probs, blank], axis=2) + return array_ops.pad( + state_log_probs, [[0, 0], [0, 0], [1, 0]], + constant_values=math_ops.log(0.0)) + + +def _state_to_olabel(labels, num_labels, states): + """Sum state log probs to ilabel log probs.""" + + num_label_states = _get_dim(labels, 1) + 1 + label_states = states[:, :, 1:num_label_states] + blank_states = states[:, :, num_label_states:] + one_hot = array_ops.one_hot( + labels - 1, + depth=(num_labels - 1), + on_value=0.0, + off_value=math_ops.log(0.0)) + one_hot = array_ops.expand_dims(one_hot, axis=0) + label_states = array_ops.expand_dims(label_states, axis=3) + label_olabels = math_ops.reduce_logsumexp(label_states + one_hot, axis=2) + blank_olabels = math_ops.reduce_logsumexp(blank_states, axis=2, keepdims=True) + return array_ops.concat([blank_olabels, label_olabels], axis=-1) + + +# pylint: disable=redefined-outer-name +def _state_to_olabel_unique(labels, num_labels, states, unique): + """Sum state log probs to ilabel log probs using unique label indices.""" + + num_label_states = _get_dim(labels, 1) + 1 + label_states = states[:, :, 1:num_label_states] + blank_states = states[:, :, num_label_states:] + + unique_y, unique_idx = unique + mul_reduce = _sum_states(unique_idx, label_states) + + num_frames = _get_dim(states, 0) + batch_size = _get_dim(states, 1) + num_states = num_label_states - 1 + batch_state_major = array_ops.transpose(mul_reduce, perm=[1, 2, 0]) + batch_state_major = array_ops.reshape(batch_state_major, + [batch_size * num_states, num_frames]) + batch_offset = math_ops.range(batch_size, dtype=unique_y.dtype) * num_labels + indices = unique_y + array_ops.expand_dims(batch_offset, axis=-1) + indices = array_ops.reshape(indices, [-1, 1]) + scatter = array_ops.scatter_nd( + indices=indices, + updates=batch_state_major, + shape=[batch_size * num_labels, num_frames]) + scatter = array_ops.reshape(scatter, [batch_size, num_labels, num_frames]) + + mask = array_ops.ones_like(batch_state_major, dtype=dtypes.bool) + mask = array_ops.scatter_nd( + indices=indices, + updates=mask, + shape=[batch_size * num_labels, num_frames]) + mask = array_ops.reshape(mask, [batch_size, num_labels, num_frames]) + + scatter = array_ops.where( + mask, scatter, + array_ops.fill(array_ops.shape(scatter), math_ops.log(0.0))) + + label_olabels = array_ops.transpose(scatter, [2, 0, 1]) + label_olabels = label_olabels[:, :, 1:] + + blank_olabels = math_ops.reduce_logsumexp(blank_states, axis=2, keepdims=True) + + return array_ops.concat([blank_olabels, label_olabels], axis=-1) + + +def ctc_loss_and_grad(logits, labels, label_length, logit_length, unique=None): + """Computes the CTC loss and gradients. + + Most users will want fwd_bwd.ctc_loss + + This function returns the computed gradient, it does not have a gradient + of its own defined. + + Args: + logits: tensor of shape [frames, batch_size, num_labels] + labels: tensor of shape [batch_size, max_label_seq_length] + label_length: tensor of shape [batch_size] Length of reference label + sequence in labels. + logit_length: tensor of shape [batch_size] Length of input sequence in + logits. + unique: (optional) unique label indices as computed by unique(labels) If + supplied, enables an implementation that is faster and more memory + efficient on TPU. + + Returns: + loss: tensor of shape [batch_size] + gradient: tensor of shape [frames, batch_size, num_labels] + """ + + num_labels = _get_dim(logits, 2) + max_label_seq_length = _get_dim(labels, 1) + + ilabel_log_probs = nn_ops.log_softmax(logits) + state_log_probs = _ilabel_to_state(labels, num_labels, ilabel_log_probs) + state_trans_probs = _ctc_state_trans(labels) + initial_state_log_probs, final_state_log_probs = ctc_state_log_probs( + label_length, max_label_seq_length) + fwd_bwd_log_probs, log_likelihood = _forward_backward_log( + state_trans_log_probs=math_ops.log(state_trans_probs), + initial_state_log_probs=initial_state_log_probs, + final_state_log_probs=final_state_log_probs, + observed_log_probs=state_log_probs, + sequence_length=logit_length) + + if unique: + olabel_log_probs = _state_to_olabel_unique(labels, num_labels, + fwd_bwd_log_probs, unique) + else: + olabel_log_probs = _state_to_olabel(labels, num_labels, fwd_bwd_log_probs) + + grad = math_ops.exp(ilabel_log_probs) - math_ops.exp(olabel_log_probs) + + # Applies the sequence mask for the gradient. It is enough to appply the mask + # only for ilabel_log_probs because olabel_log_probs already consider the + # mask. However, it is just safe and clean to apply it for the gradient. + max_logit_length = _get_dim(logits, 0) + logit_mask = array_ops.sequence_mask(logit_length, max_logit_length, + dtypes.float32) + logit_mask = array_ops.transpose(logit_mask, perm=[1, 0]) + logit_mask = array_ops.expand_dims(logit_mask, axis=2) + grad *= logit_mask + + loss = -log_likelihood + return loss, grad + + +def _ctc_loss_grad(op, grad_loss, _): + grad = op.outputs[1] + grad = [array_ops.reshape(grad_loss, [1, -1, 1]) * grad] + grad += [None] * (len(op.inputs) - len(grad)) + return grad + + +def _ctc_loss_op_standard(labels, logits, logit_length, logits_time_major, + blank_index): + part_before = logits[:, :, :blank_index] + part_after = logits[:, :, blank_index + 1:] + part_blank = logits[:, :, blank_index:blank_index + 1] + logits = array_ops.concat([part_before, part_after, part_blank], axis=2) + labels = sparse_tensor.SparseTensor( + labels.indices, + array_ops.where(labels.values < blank_index, labels.values, + labels.values - 1), labels.dense_shape) + return _ctc_loss_impl( + labels=labels, + inputs=logits, + sequence_length=logit_length, + time_major=logits_time_major, + use_cudnn=False) + + +def _ctc_loss_op_cudnn(labels, logits, logit_length, logits_time_major, + blank_index): + part_before = logits[:, :, :blank_index] + part_after = logits[:, :, blank_index + 1:] + part_blank = logits[:, :, blank_index:blank_index + 1] + logits = array_ops.concat([part_blank, part_before, part_after], axis=2) + labels = sparse_tensor.SparseTensor( + labels.indices, + array_ops.where(labels.values < blank_index, labels.values + 1, + labels.values), labels.dense_shape) + return _ctc_loss_impl( + labels=labels, + inputs=logits, + sequence_length=logit_length, + time_major=logits_time_major, + use_cudnn=True) + + +def _ctc_loss_shape(op): + return [op.inputs[2].get_shape(), op.inputs[0].get_shape()] + + +# pylint: disable=protected-access, invalid-name +@tf_export(v1=["nn.ctc_loss_v2"]) +@dispatch.add_dispatch_support +def ctc_loss_v2(labels, + logits, + label_length, + logit_length, + logits_time_major=True, + unique=None, + blank_index=None, + name=None): + """Computes CTC (Connectionist Temporal Classification) loss. + + This op implements the CTC loss as presented in (Graves et al., 2006). + + Notes: + + - Same as the "Classic CTC" in TensorFlow 1.x's tf.compat.v1.nn.ctc_loss + setting of preprocess_collapse_repeated=False, ctc_merge_repeated=True + - Labels may be supplied as either a dense, zero-padded tensor with a + vector of label sequence lengths OR as a SparseTensor. + - On TPU and GPU: Only dense padded labels are supported. + - On CPU: Caller may use SparseTensor or dense padded labels but calling with + a SparseTensor will be significantly faster. + - Default blank label is 0 rather num_classes - 1, unless overridden by + blank_index. + + Args: + labels: tensor of shape [batch_size, max_label_seq_length] or SparseTensor + logits: tensor of shape [frames, batch_size, num_labels], if + logits_time_major == False, shape is [batch_size, frames, num_labels]. + label_length: tensor of shape [batch_size], None if labels is SparseTensor + Length of reference label sequence in labels. + logit_length: tensor of shape [batch_size] Length of input sequence in + logits. + logits_time_major: (optional) If True (default), logits is shaped [time, + batch, logits]. If False, shape is [batch, time, logits] + unique: (optional) Unique label indices as computed by + ctc_unique_labels(labels). If supplied, enable a faster, memory efficient + implementation on TPU. + blank_index: (optional) Set the class index to use for the blank label. + Negative values will start from num_classes, ie, -1 will reproduce the + ctc_loss behavior of using num_classes - 1 for the blank symbol. There is + some memory/performance overhead to switching from the default of 0 as an + additional shifted copy of the logits may be created. + name: A name for this `Op`. Defaults to "ctc_loss_dense". + + Returns: + loss: tensor of shape [batch_size], negative log probabilities. + + References: + Connectionist Temporal Classification - Labeling Unsegmented Sequence Data + with Recurrent Neural Networks: + [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) + ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf)) + """ + if isinstance(labels, sparse_tensor.SparseTensor): + if blank_index is None: + raise ValueError( + "Argument `blank_index` must be provided when labels is a " + "SparseTensor.") + + if blank_index < 0: + blank_index += _get_dim(logits, 2) + + if blank_index != _get_dim(logits, 2) - 1: + logits = array_ops.concat([ + logits[:, :, :blank_index], + logits[:, :, blank_index + 1:], + logits[:, :, blank_index:blank_index + 1], + ], + axis=2) + labels = sparse_tensor.SparseTensor( + labels.indices, + array_ops.where(labels.values < blank_index, labels.values, + labels.values - 1), labels.dense_shape) + + return ctc_loss( + labels=labels, + inputs=logits, + sequence_length=logit_length, + time_major=logits_time_major) + + if blank_index is None: + blank_index = 0 + + return ctc_loss_dense( + labels=labels, + logits=logits, + label_length=label_length, + logit_length=logit_length, + logits_time_major=logits_time_major, + unique=unique, + blank_index=blank_index, + name=name) + + +@tf_export("nn.ctc_loss", v1=[]) +@dispatch.add_dispatch_support +def ctc_loss_v3(labels, + logits, + label_length, + logit_length, + logits_time_major=True, + unique=None, + blank_index=None, + name=None): + """Computes CTC (Connectionist Temporal Classification) loss. + + This op implements the CTC loss as presented in + [Graves et al., 2006](https://www.cs.toronto.edu/~graves/icml_2006.pdf) + + Connectionist temporal classification (CTC) is a type of neural network output + and associated scoring function, for training recurrent neural networks (RNNs) + such as LSTM networks to tackle sequence problems where the timing is + variable. It can be used for tasks like on-line handwriting recognition or + recognizing phones in speech audio. CTC refers to the outputs and scoring, and + is independent of the underlying neural network structure. + + Notes: + + - This class performs the softmax operation for you, so `logits` should be + e.g. linear projections of outputs by an LSTM. + - Outputs true repeated classes with blanks in between, and can also output + repeated classes with no blanks in between that need to be collapsed by the + decoder. + - `labels` may be supplied as either a dense, zero-padded `Tensor` with a + vector of label sequence lengths OR as a `SparseTensor`. + - On TPU: Only dense padded `labels` are supported. + - On CPU and GPU: Caller may use `SparseTensor` or dense padded `labels` + but calling with a `SparseTensor` will be significantly faster. + - Default blank label is `0` instead of `num_labels - 1` (where `num_labels` + is the innermost dimension size of `logits`), unless overridden by + `blank_index`. + + >>> tf.random.set_seed(50) + >>> batch_size = 8 + >>> num_labels = 6 + >>> max_label_length = 5 + >>> num_frames = 12 + >>> labels = tf.random.uniform([batch_size, max_label_length], + ... minval=1, maxval=num_labels, dtype=tf.int64) + >>> logits = tf.random.uniform([num_frames, batch_size, num_labels]) + >>> label_length = tf.random.uniform([batch_size], minval=2, + ... maxval=max_label_length, dtype=tf.int64) + >>> label_mask = tf.sequence_mask(label_length, maxlen=max_label_length, + ... dtype=label_length.dtype) + >>> labels *= label_mask + >>> logit_length = [num_frames] * batch_size + >>> with tf.GradientTape() as t: + ... t.watch(logits) + ... ref_loss = tf.nn.ctc_loss( + ... labels=labels, + ... logits=logits, + ... label_length=label_length, + ... logit_length=logit_length, + ... blank_index=0) + >>> ref_grad = t.gradient(ref_loss, logits) + + Args: + labels: `Tensor` of shape `[batch_size, max_label_seq_length]` or + `SparseTensor`. + logits: `Tensor` of shape `[frames, batch_size, num_labels]`. If + `logits_time_major == False`, shape is `[batch_size, frames, num_labels]`. + label_length: `Tensor` of shape `[batch_size]`. None, if `labels` is a + `SparseTensor`. Length of reference label sequence in `labels`. + logit_length: `Tensor` of shape `[batch_size]`. Length of input sequence in + `logits`. + logits_time_major: (optional) If True (default), `logits` is shaped [frames, + batch_size, num_labels]. If False, shape is + `[batch_size, frames, num_labels]`. + unique: (optional) Unique label indices as computed by + `ctc_unique_labels(labels)`. If supplied, enable a faster, memory + efficient implementation on TPU. + blank_index: (optional) Set the class index to use for the blank label. + Negative values will start from `num_labels`, ie, `-1` will reproduce the + ctc_loss behavior of using `num_labels - 1` for the blank symbol. There is + some memory/performance overhead to switching from the default of 0 as an + additional shifted copy of `logits` may be created. + name: A name for this `Op`. Defaults to "ctc_loss_dense". + + Returns: + loss: A 1-D `float Tensor` of shape `[batch_size]`, containing negative log + probabilities. + + Raises: + ValueError: Argument `blank_index` must be provided when `labels` is a + `SparseTensor`. + + References: + Connectionist Temporal Classification - Labeling Unsegmented Sequence Data + with Recurrent Neural Networks: + [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) + ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf)) + + https://en.wikipedia.org/wiki/Connectionist_temporal_classification + """ + if isinstance(labels, sparse_tensor.SparseTensor): + if blank_index is None: + raise ValueError( + "Argument `blank_index` must be provided when `labels` is a " + "`SparseTensor`.") + + if blank_index < 0: + blank_index += _get_dim(logits, 2) + + logits = ops.convert_to_tensor(logits, name="logits") + + params = { + "labels": labels, + "logits": logits, + "logit_length": logit_length, + "logits_time_major": logits_time_major, + "blank_index": blank_index + } + + if context.executing_eagerly(): + device_type = _get_context_device_type() + can_use_gpu = ( + # Either user specified GPU or unspecified but GPU is available. + (device_type == _GPU_DEVICE_NAME or + (device_type is None and context.num_gpus() > 0))) + # Under eager context, check the device placement and prefer the + if can_use_gpu: + res = _ctc_loss_op_cudnn(**params) + else: + res = _ctc_loss_op_standard(**params) + else: + api_name = "ctc_loss_" + str(uuid.uuid4()) + ctc_loss_op_standard = _generate_defun_backend(api_name, _CPU_DEVICE_NAME, + _ctc_loss_op_standard) + ctc_loss_op_cudnn = _generate_defun_backend(api_name, _GPU_DEVICE_NAME, + _ctc_loss_op_cudnn) + res = ctc_loss_op_standard(**params) + concrete_func = ctc_loss_op_cudnn.get_concrete_function(**params) + concrete_func.add_to_graph() + concrete_func.add_gradient_functions_to_graph() + return res + + if blank_index is None: + blank_index = 0 + + return ctc_loss_dense( + labels=labels, + logits=logits, + label_length=label_length, + logit_length=logit_length, + logits_time_major=logits_time_major, + unique=unique, + blank_index=blank_index, + name=name) + + +def ctc_loss_dense(labels, + logits, + label_length, + logit_length, + logits_time_major=True, + unique=None, + blank_index=0, + name=None): + """Computes CTC (Connectionist Temporal Classification) loss. + + This op implements the CTC loss as presented in (Graves et al., 2006), + using the batched forward backward algorithm described in (Sim et al., 2017). + + Notes: + Significant differences from `tf.compat.v1.nn.ctc_loss`: + Supports GPU and TPU (`tf.compat.v1.nn.ctc_loss` supports CPU only): + For batched operations, GPU and TPU are significantly faster than using + `ctc_loss` on CPU. + This implementation runs on CPU, but significantly slower than ctc_loss. + Blank label is 0 rather num_classes - 1, unless overridden by blank_index. + Logits and labels are dense arrays with padding rather than SparseTensor. + The only mode supported is the same as: + preprocess_collapse_repeated=False, ctc_merge_repeated=True + To collapse labels, the caller can preprocess label sequence first. + + The dense implementation supports both CPU, GPU and TPU. A fast path is + provided that significantly improves memory use for large vocabulary if the + caller preprocesses label sequences to get unique label indices on the CPU + (eg. in the data input pipeline) using ctc_ops.unique and simplifies this in + the optional "unique" kwarg. This is especially useful for TPU and GPU but + also works with if used on CPU. + + Args: + labels: tensor of shape [batch_size, max_label_seq_length] + logits: tensor of shape [frames, batch_size, num_labels], if + logits_time_major == False, shape is [batch_size, frames, num_labels]. + label_length: tensor of shape [batch_size] Length of reference label + sequence in labels. + logit_length: tensor of shape [batch_size] Length of input sequence in + logits. + logits_time_major: (optional) If True (default), logits is shaped [time, + batch, logits]. If False, shape is [batch, time, logits] + unique: (optional) Unique label indices as computed by unique(labels). If + supplied, enable a faster, memory efficient implementation on TPU. + blank_index: (optional) Set the class index to use for the blank label. + Negative values will start from num_classes, ie, -1 will reproduce the + ctc_loss behavior of using num_classes - 1 for the blank symbol. There is + some memory/performance overhead to switching from the default of 0 as an + additional shifted copy of the logits may be created. + name: A name for this `Op`. Defaults to "ctc_loss_dense". + + Returns: + loss: tensor of shape [batch_size], negative log probabilities. + + References: + Connectionist Temporal Classification - Labeling Unsegmented Sequence Data + with Recurrent Neural Networks: + [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) + ([pdf](http://www.cs.toronto.edu/~graves/icml_2006.pdf)) + Improving the efficiency of forward-backward algorithm using batched + computation in TensorFlow: + [Sim et al., 2017](https://ieeexplore.ieee.org/document/8268944) + ([pdf](http://bacchiani.net/resume/papers/ASRU2017.pdf)) + """ + + with ops.name_scope(name, "ctc_loss_dense", + [logits, labels, label_length, logit_length]): + logits = ops.convert_to_tensor(logits, name="logits") + labels = ops.convert_to_tensor(labels, name="labels") + label_length = ops.convert_to_tensor(label_length, name="label_length") + logit_length = ops.convert_to_tensor(logit_length, name="logit_length") + + orig_dtype = logits.dtype + if orig_dtype in (dtypes.float16, dtypes.bfloat16): + logits = math_ops.cast(logits, dtypes.float32) + + if not logits_time_major: + logits = array_ops.transpose(logits, perm=[1, 0, 2]) + + if blank_index != 0: + if blank_index < 0: + blank_index += _get_dim(logits, 2) + logits = array_ops.concat([ + logits[:, :, blank_index:blank_index + 1], + logits[:, :, :blank_index], + logits[:, :, blank_index + 1:], + ], + axis=2) + labels = array_ops.where(labels < blank_index, labels + 1, labels) + + args = [logits, labels, label_length, logit_length] + + if unique: + unique_y, unique_idx = unique + if blank_index != 0: + unique_y = array_ops.where(unique_y < blank_index, unique_y + 1, + unique_y) + label_mask_len = math_ops.reduce_max(unique_idx, axis=1) + 1 + max_label_length = _get_dim(unique_y, 1) + label_mask = array_ops.sequence_mask(label_mask_len, max_label_length) + unique_y = array_ops.where(label_mask, unique_y, + array_ops.zeros_like(unique_y)) + args.extend([unique_y, unique_idx]) + + @custom_gradient.custom_gradient + def compute_ctc_loss(logits_t, labels_t, label_length_t, logit_length_t, + *unique_t): + """Compute CTC loss.""" + logits_t.set_shape(logits.shape) + labels_t.set_shape(labels.shape) + label_length_t.set_shape(label_length.shape) + logit_length_t.set_shape(logit_length.shape) + kwargs = dict( + logits=logits_t, + labels=labels_t, + label_length=label_length_t, + logit_length=logit_length_t) + if unique_t: + kwargs["unique"] = unique_t + result = ctc_loss_and_grad(**kwargs) + def grad(grad_loss): + grad = [array_ops.reshape(grad_loss, [1, -1, 1]) * result[1]] + grad += [None] * (len(args) - len(grad)) + return grad + + return result[0], grad + + loss = compute_ctc_loss(*args) + if orig_dtype in (dtypes.float16, dtypes.bfloat16): + loss = math_ops.cast(loss, orig_dtype) + return loss + + +@tf_export("nn.collapse_repeated") +@dispatch.add_dispatch_support +def collapse_repeated(labels, seq_length, name=None): + """Merge repeated labels into single labels. + + Args: + labels: Tensor of shape [batch, max value in seq_length] + seq_length: Tensor of shape [batch], sequence length of each batch element. + name: A name for this `Op`. Defaults to "collapse_repeated_labels". + + Returns: + A tuple `(collapsed_labels, new_seq_length)` where + + collapsed_labels: Tensor of shape [batch, max_seq_length] with repeated + labels collapsed and padded to max_seq_length, eg: + `[[A, A, B, B, A], [A, B, C, D, E]] => [[A, B, A, 0, 0], [A, B, C, D, E]]` + + new_seq_length: int tensor of shape [batch] with new sequence lengths. + """ + + with ops.name_scope(name, "collapse_repeated_labels", [labels, seq_length]): + labels = ops.convert_to_tensor(labels, name="labels") + seq_length = ops.convert_to_tensor(seq_length, name="seq_length") + + # Mask labels that don't equal previous label. + label_mask = array_ops.concat([ + array_ops.ones_like(labels[:, :1], dtypes.bool), + math_ops.not_equal(labels[:, 1:], labels[:, :-1]) + ], + axis=1) + + # Filter labels that aren't in the original sequence. + maxlen = _get_dim(labels, 1) + seq_mask = array_ops.sequence_mask(seq_length, maxlen=maxlen) + label_mask = math_ops.logical_and(label_mask, seq_mask) + + # Count masks for new sequence lengths. + new_seq_len = math_ops.reduce_sum( + math_ops.cast(label_mask, dtypes.int32), axis=1) + + # Mask indexes based on sequence length mask. + new_maxlen = math_ops.reduce_max(new_seq_len) + idx_mask = array_ops.sequence_mask(new_seq_len, maxlen=new_maxlen) + + # Flatten everything and mask out labels to keep and sparse indices. + flat_labels = array_ops.reshape(labels, [-1]) + flat_label_mask = array_ops.reshape(label_mask, [-1]) + flat_idx_mask = array_ops.reshape(idx_mask, [-1]) + idx = math_ops.range(_get_dim(flat_idx_mask, 0)) + + # Scatter to flat shape. + flat = array_ops.scatter_nd( + indices=array_ops.expand_dims( + array_ops.boolean_mask(idx, flat_idx_mask), axis=1), + updates=array_ops.boolean_mask(flat_labels, flat_label_mask), + shape=array_ops.shape(flat_idx_mask)) + + # Reshape back to square batch. + batch_size = _get_dim(labels, 0) + new_shape = [batch_size, new_maxlen] + return (array_ops.reshape(flat, new_shape), + math_ops.cast(new_seq_len, seq_length.dtype)) + + +def dense_labels_to_sparse(dense, length): + """Convert dense labels with sequence lengths to sparse tensor. + + Args: + dense: tensor of shape [batch, max_length] + length: int tensor of shape [batch] The length of each sequence in dense. + + Returns: + tf.sparse.SparseTensor with values only for the valid elements of sequences. + """ + + flat_values = array_ops.reshape(dense, [-1]) + flat_indices = math_ops.range( + array_ops.shape(flat_values, out_type=dtypes.int64)[0]) + mask = array_ops.sequence_mask(length, maxlen=array_ops.shape(dense)[1]) + flat_mask = array_ops.reshape(mask, [-1]) + indices = array_ops.expand_dims( + array_ops.boolean_mask(flat_indices, flat_mask), 1) + values = array_ops.boolean_mask(flat_values, flat_mask) + sparse = sparse_tensor.SparseTensor( + indices=indices, + values=math_ops.cast(values, dtypes.int32), + dense_shape=array_ops.shape(flat_values, out_type=dtypes.int64)) + reshaped = sparse_ops.sparse_reshape(sparse, array_ops.shape(dense)) + max_length = math_ops.reduce_max(length) + return sparse_tensor.SparseTensor( + indices=reshaped.indices, + values=reshaped.values, + dense_shape=[ + math_ops.cast(reshaped.dense_shape[0], dtypes.int64), + math_ops.cast(max_length, dtypes.int64) + ]) + + +@tf_export("nn.ctc_unique_labels") +@dispatch.add_dispatch_support +def ctc_unique_labels(labels, name=None): + """Get unique labels and indices for batched labels for `tf.nn.ctc_loss`. + + For use with `tf.nn.ctc_loss` optional argument `unique`: This op can be + used to preprocess labels in input pipeline to for better speed/memory use + computing the ctc loss on TPU. + + Example: + ctc_unique_labels([[3, 4, 4, 3]]) -> + unique labels padded with 0: [[3, 4, 0, 0]] + indices of original labels in unique: [0, 1, 1, 0] + + Args: + labels: tensor of shape [batch_size, max_label_length] padded with 0. + name: A name for this `Op`. Defaults to "ctc_unique_labels". + + Returns: + tuple of + - unique labels, tensor of shape `[batch_size, max_label_length]` + - indices into unique labels, shape `[batch_size, max_label_length]` + """ + + with ops.name_scope(name, "ctc_unique_labels", [labels]): + labels = ops.convert_to_tensor(labels, name="labels") + + def _unique(x): + u = array_ops.unique(x) + y = array_ops.pad(u.y, [[0, _get_dim(u.idx, 0) - _get_dim(u.y, 0)]]) + y = math_ops.cast(y, dtypes.int64) + return [y, u.idx] + + return map_fn.map_fn(_unique, labels, dtype=[dtypes.int64, dtypes.int32]) + + +def _sum_states(idx, states): + """Take logsumexp for each unique state out of all label states. + + Args: + idx: tensor of shape [batch, label_length] For each sequence, indices into a + set of unique labels as computed by calling unique. + states: tensor of shape [frames, batch, label_length] Log probabilities for + each label state. + + Returns: + tensor of shape [frames, batch_size, label_length], log probabilities summed + for each unique label of the sequence. + """ + + with ops.name_scope("sum_states"): + idx = ops.convert_to_tensor(idx, name="idx") + num_states = _get_dim(states, 2) + states = array_ops.expand_dims(states, axis=2) + one_hot = array_ops.one_hot( + idx, + depth=num_states, + on_value=0.0, + off_value=math_ops.log(0.0), + axis=1) + return math_ops.reduce_logsumexp(states + one_hot, axis=-1) + + +def _forward_backward_log(state_trans_log_probs, initial_state_log_probs, + final_state_log_probs, observed_log_probs, + sequence_length): + """Forward-backward algorithm computed in log domain. + + Args: + state_trans_log_probs: tensor of shape [states, states] or if different + transition matrix per batch [batch_size, states, states] + initial_state_log_probs: tensor of shape [batch_size, states] + final_state_log_probs: tensor of shape [batch_size, states] + observed_log_probs: tensor of shape [frames, batch_size, states] + sequence_length: tensor of shape [batch_size] + + Returns: + forward backward log probabilities: tensor of shape [frames, batch, states] + log_likelihood: tensor of shape [batch_size] + + Raises: + ValueError: If state_trans_log_probs has unknown or incorrect rank. + """ + + if state_trans_log_probs.shape.ndims == 2: + perm = [1, 0] + elif state_trans_log_probs.shape.ndims == 3: + perm = [0, 2, 1] + else: + raise ValueError( + "Rank of argument `state_trans_log_probs` must be known and equal to " + f"2 or 3. Received state_trans_log_probs={state_trans_log_probs} of " + f"rank {state_trans_log_probs.shape.ndims}") + + bwd_state_trans_log_probs = array_ops.transpose(state_trans_log_probs, perm) + batch_size = _get_dim(observed_log_probs, 1) + + def _forward(state_log_prob, obs_log_prob): + state_log_prob = array_ops.expand_dims(state_log_prob, axis=1) # Broadcast. + state_log_prob += state_trans_log_probs + state_log_prob = math_ops.reduce_logsumexp(state_log_prob, axis=-1) + state_log_prob += obs_log_prob + log_prob_sum = math_ops.reduce_logsumexp( + state_log_prob, axis=-1, keepdims=True) + state_log_prob -= log_prob_sum + return state_log_prob + + fwd = _scan( + _forward, observed_log_probs, initial_state_log_probs, inclusive=True) + + def _backward(accs, elems): + """Calculate log probs and cumulative sum masked for sequence length.""" + state_log_prob, cum_log_sum = accs + obs_log_prob, mask = elems + state_log_prob += obs_log_prob + state_log_prob = array_ops.expand_dims(state_log_prob, axis=1) # Broadcast. + state_log_prob += bwd_state_trans_log_probs + state_log_prob = math_ops.reduce_logsumexp(state_log_prob, axis=-1) + + log_prob_sum = math_ops.reduce_logsumexp( + state_log_prob, axis=-1, keepdims=True) + state_log_prob -= log_prob_sum + + cum_log_sum += array_ops.squeeze(log_prob_sum, axis=[-1]) * mask + batched_mask = array_ops.expand_dims(mask, axis=1) + out = state_log_prob * batched_mask + out += final_state_log_probs * (1.0 - batched_mask) + return out, cum_log_sum + + zero_log_sum = array_ops.zeros([batch_size]) + maxlen = _get_dim(observed_log_probs, 0) + mask = array_ops.sequence_mask(sequence_length, maxlen, dtypes.float32) + mask = array_ops.transpose(mask, perm=[1, 0]) + + bwd, cum_log_sum = _scan( + _backward, (observed_log_probs, mask), + (final_state_log_probs, zero_log_sum), + reverse=True, + inclusive=True) + + fwd_bwd_log_probs = fwd[1:] + bwd[1:] + fwd_bwd_log_probs_sum = math_ops.reduce_logsumexp( + fwd_bwd_log_probs, axis=2, keepdims=True) + fwd_bwd_log_probs -= fwd_bwd_log_probs_sum + fwd_bwd_log_probs += math_ops.log(array_ops.expand_dims(mask, axis=2)) + + log_likelihood = bwd[0, :, 0] + cum_log_sum[0] + + return fwd_bwd_log_probs, log_likelihood + + +# TODO(tombagby): This is currently faster for the ctc implementation than using +# functional_ops.scan, but could be replaced by that or something similar if +# things change. +def _scan(fn, elems, initial, reverse=False, inclusive=False, final_only=False): + """Repeatedly applies callable `fn` to a sequence of elements. + + Implemented by functional_ops.While, tpu friendly, no gradient. + + This is similar to functional_ops.scan but significantly faster on tpu/gpu + for the forward backward use case. + + Examples: + scan(lambda a, e: a + e, [1.0, 2.0, 3.0], 1.0) => [2.0, 4.0, 7.0] + + Multiple accumulators: + scan(lambda a, e: (a[0] + e, a[1] * e), [1.0, 2.0, 3.0], (0.0, 1.0)) + + Multiple inputs: + scan(lambda a, e: a + (e[0] * e[1]), (elems1, elems2), 0.0) + + Args: + fn: callable, fn(accumulators, element) return new accumulator values. The + (possibly nested) sequence of accumulators is the same as `initial` and + the return value must have the same structure. + elems: A (possibly nested) tensor which will be unpacked along the first + dimension. The resulting slices will be the second argument to fn. The + first dimension of all nested input tensors must be the same. + initial: A tensor or (possibly nested) sequence of tensors with initial + values for the accumulators. + reverse: (optional) True enables scan and output elems in reverse order. + inclusive: (optional) True includes the initial accumulator values in the + output. Length of output will be len(elem sequence) + 1. Not meaningful if + final_only is True. + final_only: (optional) When True, return only the final accumulated values, + not the concatenation of accumulated values for each input. + + Returns: + A (possibly nested) sequence of tensors with the results of applying fn + to tensors unpacked from elems and previous accumulator values. + """ + + flat_elems = [ops.convert_to_tensor(x) for x in nest.flatten(elems)] + num_elems = array_ops.shape(flat_elems[0])[0] + pack_elems = lambda x: nest.pack_sequence_as(structure=elems, flat_sequence=x) + flat_initial = [ops.convert_to_tensor(x) for x in nest.flatten(initial)] + pack = lambda x: nest.pack_sequence_as(structure=initial, flat_sequence=x) + accum_dtypes = [x.dtype for x in flat_initial] + num_accums = len(flat_initial) + + # Types for counter, [outputs], [accumulators] loop arguments. + if final_only: + loop_dtypes = [dtypes.int32, dtypes.int32] + accum_dtypes + else: + loop_dtypes = [dtypes.int32, dtypes.int32] + accum_dtypes + accum_dtypes + + # TODO(tombagby): Update to tfe.defun + def cond(i, num_elems, *args): + del args + return i >= 0 if reverse else i < num_elems + + # The loop *args are [output tensors] + [accumulator tensors] which must + # be paired. Each output corresponds to one accumulator. + def body(i, num_elems, *args): + """Loop body.""" + i.set_shape([]) + if final_only: + accum = args + else: + out, accum = args[:num_accums], args[num_accums:] + slices = [array_ops.gather(e, i) for e in flat_elems] + accum = fn(pack(accum), pack_elems(slices)) + flat_accum = nest.flatten(accum) + if final_only: + new_out = [] + else: + update_i = i + 1 if inclusive and not reverse else i + # TODO(b/280454072) Cleanup when foward compatibility window expires. + if compat.forward_compatible(2023, 10, 26): + new_out = [ + gen_array_ops.tensor_scatter_update(x, [[update_i]], [y]) + for x, y in zip(out, flat_accum) + ] + else: + new_out = [ + inplace_ops.alias_inplace_update(x, update_i, y) + for x, y in zip(out, flat_accum) + ] + i = i - 1 if reverse else i + 1 + return [i, num_elems] + new_out + flat_accum + + init_i = ( + array_ops.shape(flat_elems[0])[0] - + 1 if reverse else constant_op.constant(0, dtype=dtypes.int32)) + outputs = [] + if not final_only: + num_outputs = array_ops.shape(flat_elems[0])[0] + (1 if inclusive else 0) + for initial_accum in flat_initial: + out_shape = array_ops.concat( + [[num_outputs], array_ops.shape(initial_accum)], 0) + out = inplace_ops.empty(out_shape, dtype=initial_accum.dtype, init=True) + if inclusive: + # TODO(b/280454072) Cleanup when foward compatibility window expires. + if compat.forward_compatible(2023, 10, 26): + out = gen_array_ops.tensor_scatter_add( + out, [[init_i + (1 if reverse else 0)]], [initial_accum] + ) + else: + out = inplace_ops.alias_inplace_add( + out, init_i + (1 if reverse else 0), initial_accum + ) + outputs.append(out) + loop_in = [init_i, num_elems] + outputs + flat_initial + hostmem = [ + i for i, x in enumerate(loop_in) + if x.dtype.base_dtype in (dtypes.int32, dtypes.int64) + ] + + if context.executing_eagerly(): + loop_results = loop_in + while cond(*loop_results): + loop_results = body(*loop_results) + else: + # TODO(tombagby): Update to while_v2. + cond = function.Defun(*loop_dtypes)(cond) + body = function.Defun(*loop_dtypes)(body) + loop_results = functional_ops.While(loop_in, cond, body, hostmem=hostmem) + out = loop_results[2:num_accums + 2] + return pack(out) + + +def _get_dim(tensor, i): + """Get value of tensor shape[i] preferring static value if available.""" + return tensor_shape.dimension_value( + tensor.shape[i]) or array_ops.shape(tensor)[i] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cudnn_rnn_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cudnn_rnn_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..44e9b29a3a35ae489412dd960a8a0569d25cb0ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/cudnn_rnn_grad.py @@ -0,0 +1,99 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for CuudnnRNN operators.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_cudnn_rnn_ops + + +@ops.RegisterGradient("CudnnRNN") +def _cudnn_rnn_backward(op: ops.Operation, *grads): + """Gradients for the CudnnRNN op.""" + if not op.get_attr("is_training"): + raise ValueError( + "To use CudnnRNN in gradients, is_training must be set to True.") + return gen_cudnn_rnn_ops.cudnn_rnn_backprop( + input=op.inputs[0], + input_h=op.inputs[1], + input_c=op.inputs[2], + params=op.inputs[3], + output=op.outputs[0], + output_h=op.outputs[1], + output_c=op.outputs[2], + output_backprop=grads[0], + output_h_backprop=grads[1], + output_c_backprop=grads[2], + reserve_space=op.outputs[3], + dropout=op.get_attr("dropout"), + seed=op.get_attr("seed"), + seed2=op.get_attr("seed2"), + rnn_mode=op.get_attr("rnn_mode"), + input_mode=op.get_attr("input_mode"), + direction=op.get_attr("direction")) + + +@ops.RegisterGradient("CudnnRNNV2") +def _cudnn_rnn_backward_v2(op: ops.Operation, *grad): + if not op.get_attr("is_training"): + raise ValueError( + "To use CudnnRNNV2 in gradients, is_training must be set to True.") + return gen_cudnn_rnn_ops.cudnn_rnn_backprop_v2( + input=op.inputs[0], + input_h=op.inputs[1], + input_c=op.inputs[2], + params=op.inputs[3], + output=op.outputs[0], + output_h=op.outputs[1], + output_c=op.outputs[2], + output_backprop=grad[0], + output_h_backprop=grad[1], + output_c_backprop=grad[2], + reserve_space=op.outputs[3], + host_reserved=op.outputs[4], + dropout=op.get_attr("dropout"), + seed=op.get_attr("seed"), + seed2=op.get_attr("seed2"), + rnn_mode=op.get_attr("rnn_mode"), + input_mode=op.get_attr("input_mode"), + direction=op.get_attr("direction")) + + +@ops.RegisterGradient("CudnnRNNV3") +def _cudnn_rnn_backwardv3(op: ops.Operation, *grads): + """Gradients for the CudnnRNNV3 op.""" + if not op.get_attr("is_training"): + raise ValueError( + "To use CudnnRNNV3 in gradients, is_training must be set to True.") + return gen_cudnn_rnn_ops.cudnn_rnn_backprop_v3( + input=op.inputs[0], + input_h=op.inputs[1], + input_c=op.inputs[2], + params=op.inputs[3], + sequence_lengths=op.inputs[4], + output=op.outputs[0], + output_h=op.outputs[1], + output_c=op.outputs[2], + output_backprop=grads[0], + output_h_backprop=grads[1], + output_c_backprop=grads[2], + reserve_space=op.outputs[3], + host_reserved=op.outputs[4], + dropout=op.get_attr("dropout"), + seed=op.get_attr("seed"), + seed2=op.get_attr("seed2"), + time_major=op.get_attr("time_major"), + num_proj=op.get_attr("num_proj"), + rnn_mode=op.get_attr("rnn_mode"), + input_mode=op.get_attr("input_mode"), + direction=op.get_attr("direction")) + (None,) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/custom_gradient.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/custom_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..2b943a6a8b03b84cb053d860b35866a38f56431f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/custom_gradient.py @@ -0,0 +1,827 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Decorator to overrides the gradient for a function.""" + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import op_selector +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +VAR_OP_TYPES = [ + "VariableV2", + "VarHandleOp", +] + + +@tf_export("custom_gradient") +def custom_gradient(f=None): + """Decorator to define a function with a custom gradient. + + This decorator allows fine grained control over the gradients of a sequence + for operations. This may be useful for multiple reasons, including providing + a more efficient or numerically stable gradient for a sequence of operations. + + For example, consider the following function that commonly occurs in the + computation of cross entropy and log likelihoods: + + ```python + def log1pexp(x): + return tf.math.log(1 + tf.exp(x)) + ``` + + Due to numerical instability, the gradient of this function evaluated at x=100 + is NaN. For example: + + ```python + with tf.GradientTape() as tape: + tape.watch(x) + y=log1pexp(x) + dy_dx = tape.gradient(y, x) # Will be NaN when evaluated. + ``` + + The gradient expression can be analytically simplified to provide numerical + stability: + + ```python + @tf.custom_gradient + def log1pexp(x): + e = tf.exp(x) + def grad(upstream): + return upstream * (1 - 1 / (1 + e)) + return tf.math.log(1 + e), grad + ``` + + With this definition, the gradient `dy_dx` at `x = 100` will be correctly + evaluated as 1.0. + + The variable `upstream` is defined as the upstream gradient. i.e. the gradient + from all the layers or functions originating from this layer. The above + example has no upstream functions, therefore `upstream = dy/dy = 1.0`. + + Assume that `x_i` is `log1pexp` in the forward pass `x_1 = x_1(x_0)`, + `x_2 = x_2(x_1)`, ..., `x_i = x_i(x_i-1)`, ..., `x_n = x_n(x_n-1)`. By + chain rule we know that `dx_n/dx_0 = dx_n/dx_n-1 * dx_n-1/dx_n-2 * ... * + dx_i/dx_i-1 * ... * dx_1/dx_0`. + + In this case the gradient of our current function defined as + `dx_i/dx_i-1 = (1 - 1 / (1 + e))`. The upstream gradient `upstream` would be + `dx_n/dx_n-1 * dx_n-1/dx_n-2 * ... * dx_i+1/dx_i`. The upstream gradient + multiplied by the current gradient is then passed downstream. + + In case the function takes multiple variables as input, the `grad` + function must also return the same number of variables. + We take the function `z = x * y` as an example. + + >>> @tf.custom_gradient + ... def bar(x, y): + ... def grad(upstream): + ... dz_dx = y + ... dz_dy = x + ... return upstream * dz_dx, upstream * dz_dy + ... z = x * y + ... return z, grad + >>> x = tf.constant(2.0, dtype=tf.float32) + >>> y = tf.constant(3.0, dtype=tf.float32) + >>> with tf.GradientTape(persistent=True) as tape: + ... tape.watch(x) + ... tape.watch(y) + ... z = bar(x, y) + >>> z + + >>> tape.gradient(z, x) + + >>> tape.gradient(z, y) + + + Nesting custom gradients can lead to unintuitive results. The default + behavior does not correspond to n-th order derivatives. For example + + ```python + @tf.custom_gradient + def op(x): + y = op1(x) + @tf.custom_gradient + def grad_fn(dy): + gdy = op2(x, y, dy) + def grad_grad_fn(ddy): # Not the 2nd order gradient of op w.r.t. x. + return op3(x, y, dy, ddy) + return gdy, grad_grad_fn + return y, grad_fn + ``` + + The function `grad_grad_fn` will be calculating the first order gradient + of `grad_fn` with respect to `dy`, which is used to generate forward-mode + gradient graphs from backward-mode gradient graphs, but is not the same as + the second order gradient of `op` with respect to `x`. + + Instead, wrap nested `@tf.custom_gradients` in another function: + + ```python + @tf.custom_gradient + def op_with_fused_backprop(x): + y, x_grad = fused_op(x) + def first_order_gradient(dy): + @tf.custom_gradient + def first_order_custom(unused_x): + def second_order_and_transpose(ddy): + return second_order_for_x(...), gradient_wrt_dy(...) + return x_grad, second_order_and_transpose + return dy * first_order_custom(x) + return y, first_order_gradient + ``` + + Additional arguments to the inner `@tf.custom_gradient`-decorated function + control the expected return values of the innermost function. + + The examples above illustrate how to specify custom gradients for functions + which do not read from variables. The following example uses variables, which + require special handling because they are effectively inputs of the forward + function. + + >>> weights = tf.Variable(tf.ones([2])) # Trainable variable weights + >>> @tf.custom_gradient + ... def linear_poly(x): + ... # Creating polynomial + ... poly = weights[1] * x + weights[0] + ... + ... def grad_fn(dpoly, variables): + ... # dy/dx = weights[1] and we need to left multiply dpoly + ... grad_xs = dpoly * weights[1] # Scalar gradient + ... + ... grad_vars = [] # To store gradients of passed variables + ... assert variables is not None + ... assert len(variables) == 1 + ... assert variables[0] is weights + ... # Manually computing dy/dweights + ... dy_dw = dpoly * tf.stack([x ** 1, x ** 0]) + ... grad_vars.append( + ... tf.reduce_sum(tf.reshape(dy_dw, [2, -1]), axis=1) + ... ) + ... return grad_xs, grad_vars + ... return poly, grad_fn + >>> x = tf.constant([1., 2., 3.]) + >>> with tf.GradientTape(persistent=True) as tape: + ... tape.watch(x) + ... poly = linear_poly(x) + >>> poly # poly = x + 1 + + >>> tape.gradient(poly, x) # conventional scalar gradient dy/dx + + >>> tape.gradient(poly, weights) + + + Above example illustrates usage of trainable variable `weights`. + In the example, the inner `grad_fn` accepts an extra `variables` input + parameter and also returns an extra `grad_vars` output. That extra argument + is passed if the forward function reads any variables. You need to + compute the gradient w.r.t. each of those `variables` and output it as a list + of `grad_vars`. Note here that default value of `variables` is set to `None` + when no variables are used in the forward function. + + It should be noted `tf.GradientTape` is still watching the forward pass of a + `tf.custom_gradient`, and will use the ops it watches. As a consequence, + calling `tf.function` while the tape is still watching leads + to a gradient graph being built. If an op is used in `tf.function` without + registered gradient, a `LookupError` will be raised. + + Users can insert `tf.stop_gradient` to customize this behavior. This + is demonstrated in the example below. `tf.random.shuffle` does not have a + registered gradient. As a result `tf.stop_gradient` is used to avoid the + `LookupError`. + + ```python + x = tf.constant([0.3, 0.5], dtype=tf.float32) + + @tf.custom_gradient + def test_func_with_stop_grad(x): + @tf.function + def _inner_func(): + # Avoid exception during the forward pass + return tf.stop_gradient(tf.random.shuffle(x)) + # return tf.random.shuffle(x) # This will raise + + res = _inner_func() + def grad(upstream): + return upstream # Arbitrarily defined custom gradient + return res, grad + + with tf.GradientTape() as g: + g.watch(x) + res = test_func_with_stop_grad(x) + + g.gradient(res, x) + ``` + + See also `tf.RegisterGradient` which registers a gradient function for a + primitive TensorFlow operation. `tf.custom_gradient` on the other hand allows + for fine grained control over the gradient computation of a sequence of + operations. + + Note that if the decorated function uses `Variable`s, the enclosing variable + scope must be using + [ResourceVariables](https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables). + + Args: + f: function `f(*x)` that returns a tuple `(y, grad_fn)` where: + - `x` is a sequence of (nested structures of) `Tensor` inputs to the + function. + - `y` is a (nested structure of) `Tensor` outputs of applying TensorFlow + operations in `f` to `x`. + - `grad_fn` is a function with the signature `g(*grad_ys)` which returns + a list of `Tensor`s the same size as (flattened) `x` - the derivatives + of `Tensor`s in `y` with respect to the `Tensor`s in `x`. `grad_ys` is + a sequence of `Tensor`s the same size as (flattened) `y` holding the + initial value gradients for each `Tensor` in `y`. + + In a pure mathematical sense, a vector-argument vector-valued function + `f`'s derivatives should be its Jacobian matrix `J`. Here we are + expressing the Jacobian `J` as a function `grad_fn` which defines how + `J` will transform a vector `grad_ys` when left-multiplied with it + (`grad_ys * J`, the vector-Jacobian product, or VJP). This functional + representation of a matrix is convenient to use for chain-rule + calculation (in e.g. the back-propagation algorithm). + + If `f` uses `Variable`s (that are not part of the + inputs), i.e. through `get_variable`, then `grad_fn` should have + signature `g(*grad_ys, variables=None)`, where `variables` is a list of + the `Variable`s, and return a 2-tuple `(grad_xs, grad_vars)`, where + `grad_xs` is the same as above, and `grad_vars` is a `list` + with the derivatives of `Tensor`s in `y` with respect to the variables + (that is, grad_vars has one Tensor per variable in variables). + + Returns: + A function `h(x)` which returns the same value as `f(x)[0]` and whose + gradient (as calculated by `tf.gradients`) is determined by `f(x)[1]`. + """ + + if f is None: + return lambda f: custom_gradient(f=f) + + @Bind.decorator + def decorated(wrapped, args, kwargs): + """Decorated function with custom gradient.""" + if context.executing_eagerly(): + return _eager_mode_decorator(wrapped, args, kwargs) + else: + return _graph_mode_decorator(wrapped, args, kwargs) + + return tf_decorator.make_decorator(f, decorated(f)) # pylint: disable=no-value-for-parameter + + +class Bind: + """When called evaluates `d(f, args, kwargs)` but supports binding `f`. + + >>> @Bind.decorator + ... def my_decorator(f, args, kwargs): + ... print("my_decorator called with", args, kwargs) + ... return f(*args, **kwargs) + + >>> class Foo: + ... @my_decorator + ... def bar(self, a, b, c): + ... return a * b * c + + >>> Foo.bar(None, 1, 2, c=3) + my_decorator called with (None, 1, 2) {'c': 3} + 6 + + >>> foo = Foo() + >>> foo.bar(1, 2, c=3) + my_decorator called with (1, 2) {'c': 3} + 6 + """ + + @classmethod + def decorator(cls, d): + return lambda f: Bind(f, d) + + def __init__(self, f, d): + self._f = f + self._d = d + + def __get__(self, instance, owner): + if instance is not None: + f = self._f.__get__(instance, owner) + return tf_decorator.make_decorator(f, Bind(f, self._d)) + else: + return self + + def __call__(self, *a, **k): + return self._d(self._f, a, k) + + +def get_variable_by_name(var_name): + """Given a variable name, retrieves a handle on the tensorflow Variable.""" + global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) + + def _filter_fn(item): + try: + return var_name == item.op.name + except AttributeError: + # Collection items without operation are ignored. + return False + + candidate_vars = list(filter(_filter_fn, global_vars)) + + if len(candidate_vars) >= 1: + # Filter out non-trainable variables. + candidate_vars = [v for v in candidate_vars if v.trainable] + else: + raise ValueError("Unsuccessful at finding variable {}.".format(var_name)) + + if len(candidate_vars) == 1: + return candidate_vars[0] + elif len(candidate_vars) > 1: + raise ValueError( + "Unsuccessful at finding trainable variable {}. " + "Number of candidates: {}. " + "Candidates: {}".format(var_name, len(candidate_vars), candidate_vars)) + else: + # The variable is not trainable. + return None + + +def _get_dependent_variables(input_ops, output_ops): + """Finds variables involved in the subgraph between input_ops and output_ops. + + Args: + input_ops: Flattened list of input ops + output_ops: Flattened list of output ops + + Returns: + A list of variables + """ + + # avoids the edge-case when input_ops == output_ops. + output_ops = nest.map_structure(gen_array_ops.identity, output_ops) + inbetween_ops = op_selector.get_backward_walk_ops( + seed_ops=output_ops, + stop_at_ts=input_ops, + inclusive=False, + only_differentiable=True) + var_ops = (op for op in inbetween_ops if op.type in VAR_OP_TYPES) + var_names = (op.name for op in var_ops) + tf_vars = (get_variable_by_name(var_name) for var_name in var_names) + tf_vars = [v for v in tf_vars if v is not None] + return tf_vars + + +def generate_name(): + return "CustomGradient-%s" % ops.uid() + + +def _graph_mode_decorator(f, args, kwargs): + """Implement custom gradient decorator for graph mode.""" + # TODO(rsepassi): Add support for kwargs + if kwargs: + raise ValueError( + "The custom_gradient decorator currently supports keywords " + "arguments only when eager execution is enabled.") + name = generate_name() + args = variable_utils.convert_variables_to_tensors(args) + args = nest.map_structure(ops.convert_to_tensor, args, expand_composites=True) + + # Checking global and local variables attempts to ensure that no non-resource + # Variables are added to the graph. + current_var_scope = variable_scope.get_variable_scope() + before_vars = set([ + v.ref() for v in current_var_scope.global_variables() + + current_var_scope.local_variables() + ]) + with record.VariableWatcher() as variable_watcher: + result, grad_fn = f(*args) + + flat_args = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(args)) + flat_result = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(result)) + flat_result_len = len(flat_result) + + after_vars = set([ + v.ref() for v in current_var_scope.global_variables() + + current_var_scope.local_variables() + ]) + new_vars = after_vars - before_vars + new_vars_list = [v.deref() for v in new_vars] + for v in new_vars_list: + if not resource_variable_ops.is_resource_variable(v): + raise TypeError( + "All variables used by a function wrapped with @custom_gradient must " + "be `ResourceVariable`s. Ensure that no `variable_scope` is created " + "with `use_resource=False`.") + + # The variables that grad_fn needs to return gradients for are the set of + # variables used that are *not* part of the inputs. + variables_in_tape = frozenset([ + v.ref() for v in variable_watcher.watched_variables() + ]) + + graphs = {getattr(o, "graph", None) for o in flat_result} + # Not all results may be tensors. However, we want to ensure all tensor + # outputs are from the same graph and get a list of captured inputs for + # variable search + graphs.discard(None) # Discard non-graph outputs + if graphs: + if len(graphs) > 1: + raise ValueError( + "All custom_gradient outputs should be from the same graph") + output_graph = graphs.pop() + filtered_input_tensors = [] + for i in flat_args: + if i.graph == output_graph: + filtered_input_tensors.append(i) + else: + filtered_input_tensors = flat_args + + variables_in_subgraph = frozenset([ + v.ref() for v in _get_dependent_variables( + input_ops=filtered_input_tensors, output_ops=flat_result) + ]) + variables = sorted( + [v.deref() for v in variables_in_subgraph.union(variables_in_tape)], + key=lambda v: v.name) + + grad_argspec = tf_inspect.getfullargspec(grad_fn) + variables_in_signature = ("variables" in grad_argspec.args or + "variables" in grad_argspec.kwonlyargs or + grad_argspec.varkw) + if variables and not variables_in_signature: + raise TypeError( + "@tf.custom_gradient grad_fn must accept keyword argument 'variables', " + "since function uses variables: {}".format(variables)) + if variables_in_signature and not variables: + # User seems to intend to use variables but none were captured. + logging.vlog( + 1, "@custom_gradient grad_fn has 'variables' in signature, " + "but no ResourceVariables were used on the forward pass.") + + all_tensors = flat_result + flat_args + variables + + def tape_grad_fn(*result_grad_components): + """Custom grad fn wrapper.""" + result_grads = composite_tensor_gradient.replace_flat_tensors_for_gradients( + nest.flatten(result), result_grad_components[:flat_result_len]) + if not isinstance(result_grads, (list, tuple)): + result_grads = [result_grads] + + if variables: + input_grads, variable_grads = grad_fn(*result_grads, variables=variables) + if len(variable_grads) != len(variables): + raise ValueError("Must return gradient for each variable from " + "@custom_gradient grad_fn.") + else: + input_grads = grad_fn(*result_grads) + variable_grads = [] + + # Need to return one value per input to the IdentityN, so pad the + # gradients of the inputs of the custom_gradient function with the + # gradients of the outputs as well. + input_grads = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(input_grads)) + return ([None] * flat_result_len) + input_grads + variable_grads + + @ops.RegisterGradient(name) + def internal_grad_fn(unused_op, *result_grads): # pylint: disable=unused-variable + """Custom grad fn wrapper.""" + return tape_grad_fn(*result_grads) + + original_tensors = all_tensors + with ops.get_default_graph().gradient_override_map({"IdentityN": name}): + all_tensors = array_ops.identity_n(all_tensors) + + original_tensors = [ops.convert_to_tensor(x) for x in original_tensors] + + # Propagate handle data for happier shape inference for resource variables. + for i, t in enumerate(original_tensors): + if t.dtype == dtypes.resource and hasattr(t, "_handle_data"): + all_tensors[i]._handle_data = t._handle_data # pylint: disable=protected-access + record.record_operation( + f.__name__, all_tensors, original_tensors, tape_grad_fn) + for ot, t in zip(original_tensors, all_tensors): + handle_data_util.copy_handle_data(ot, t) + flat_result = composite_tensor_gradient.replace_flat_tensors_for_gradients( + nest.flatten(result), all_tensors[:flat_result_len]) + return nest.pack_sequence_as(result, flat_result) + + +def _eager_mode_decorator(f, args, kwargs): + """Implement custom gradient decorator for eager mode.""" + with record.VariableWatcher() as variable_watcher: + result, grad_fn = f(*args, **kwargs) + flat_args = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(args)) + flat_kwargs = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(kwargs)) + all_inputs = flat_args + flat_kwargs + # The variables that grad_fn needs to return gradients for are the set of + # variables used that are *not* part of the inputs. + variables = [ + v.deref() # pylint: disable=g-complex-comprehension + for v in set(v.ref() for v in variable_watcher.watched_variables()) + if all(v.deref() is not i for i in all_inputs) + ] + grad_argspec = tf_inspect.getfullargspec(grad_fn) + if (variables and ("variables" not in grad_argspec.args) and + ("variables" not in grad_argspec.kwonlyargs) and + not grad_argspec.varkw): + raise TypeError( + "@tf.custom_gradient grad_fn must accept keyword argument 'variables', " + "since function uses variables: {}".format(variables)) + flat_result = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(result)) + # TODO(apassos) consider removing the identity below. + flat_result = [gen_array_ops.identity(x) for x in flat_result] + + input_tensors = [ + ops.convert_to_tensor(x) for x in flat_args + list(variables)] + + recorded_inputs = input_tensors + arg_count = len(flat_args) + + def actual_grad_fn(*result_grad_components): + """Custom grad fn wrapper.""" + result_grads = composite_tensor_gradient.replace_flat_tensors_for_gradients( + nest.flatten(result), result_grad_components) + if not isinstance(result_grads, (list, tuple)): + result_grads = [result_grads] + + if variables: + input_grads, variable_grads = grad_fn(*result_grads, variables=variables) + if len(variable_grads) != len(variables): + raise ValueError("Must return gradient for each variable from " + "@custom_gradient grad_fn.") + else: + input_grads = grad_fn(*result_grads) + variable_grads = [] + flat_grads = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(input_grads)) + if len(flat_grads) != arg_count: + raise ValueError( + f"custom_gradient function expected to return {arg_count} " + f"gradients, but returned {len(flat_grads)} instead.") + return flat_grads + variable_grads + + record.record_operation(f.__name__, flat_result, recorded_inputs, + actual_grad_fn) + flat_result = composite_tensor_gradient.replace_flat_tensors_for_gradients( + nest.flatten(result), flat_result) + return nest.pack_sequence_as(result, flat_result) + + +@tf_export("recompute_grad") +def recompute_grad(f): + """Defines a function as a recompute-checkpoint for the tape auto-diff. + + Tape checkpointing is a technique to reduce the memory consumption of the + auto-diff tape: + + - Without tape checkpointing operations and intermediate values are + recorded to the tape for use in the backward pass. + + - With tape checkpointing, only the function call and its inputs are + recorded. During back-propagation the `recompute_grad` custom gradient + (`tf.custom_gradient`) recomputes the function under a localized Tape object. + This recomputation of the function during backpropagation performs redundant + calculation, but reduces the overall memory usage of the Tape. + + >>> y = tf.Variable(1.0) + + >>> def my_function(x): + ... tf.print('running') + ... z = x*y + ... return z + + >>> my_function_recompute = tf.recompute_grad(my_function) + + >>> with tf.GradientTape() as tape: + ... r = tf.constant(1.0) + ... for i in range(4): + ... r = my_function_recompute(r) + running + running + running + running + + >>> grad = tape.gradient(r, [y]) + running + running + running + running + + Without `recompute_grad`, the tape contains all intermitate steps, and no + recomputation is performed. + + >>> with tf.GradientTape() as tape: + ... r = tf.constant(1.0) + ... for i in range(4): + ... r = my_function(r) + running + running + running + running + + >>> grad = tape.gradient(r, [y]) + + + If `f` was a `tf.keras` `Model` or `Layer` object, methods and attributes + such as `f.variables` are not available on the returned function `g`. + Either keep a reference of `f` , or use `g.__wrapped__` for accessing + these variables and methods. + + + >>> def print_running_and_return(x): + ... tf.print("running") + ... return x + + >>> model = tf.keras.Sequential([ + ... tf.keras.layers.Lambda(print_running_and_return), + ... tf.keras.layers.Dense(2) + ... ]) + + >>> model_recompute = tf.recompute_grad(model) + + >>> with tf.GradientTape(persistent=True) as tape: + ... r = tf.constant([[1,2]]) + ... for i in range(4): + ... r = model_recompute(r) + running + running + running + running + + >>> grad = tape.gradient(r, model.variables) + running + running + running + running + + Alternatively, use the `__wrapped__` attribute to access the original + model object. + + >>> grad = tape.gradient(r, model_recompute.__wrapped__.variables) + running + running + running + running + + + Args: + f: function `f(*x)` that returns a `Tensor` or sequence of `Tensor` outputs. + + Returns: + A function `g` wrapping `f` that defines a custom gradient, which recomputes + `f` on the backwards pass of a gradient call. + """ + # TODO(cdfreeman) Add is_recomputing functionality from graph mode version + + @custom_gradient + def inner(*args, **kwargs): + """Inner function closure for calculating gradients.""" + current_var_scope = variable_scope.get_variable_scope() + with record.stop_recording(): + result = f(*args, **kwargs) + + def grad_wrapper(*wrapper_args, variables=None): + """Wrapper function to accomodate lack of kwargs in graph mode custom_gradient.""" + + @custom_gradient + def inner_recompute_grad(*dresult): + """Nested custom gradient function for computing grads in reverse and forward mode autodiff.""" + # Gradient calculation for reverse mode autodiff. + with backprop.GradientTape() as t: + id_args = nest.map_structure(gen_array_ops.identity, args) + # Tuple `dresult` should contain at least one tensor. + assert len(dresult) >= 1 + + if not context.executing_eagerly(): + # XLA doesn't respect `tf.control_dependencies`. The code block + # below manually adds a data dependency to `dresult` to ensure + # recomputation of `f(*args, **kwargs)` happens after `dresult`. + + # This works even if `dresult[0]` is a size 0 tensor as reduce_max + # of a size 0 tensor returns -inf. Use reshape here to avoid reading + # the entire `dresult[0]`. + elem = math_ops.reduce_max(array_ops.reshape(dresult[0], [-1])[:1]) + # Cast elem to bool in case elem is NaN. + elem_bool = math_ops.cast(elem, dtypes.bool) + dresult_dep = array_ops.where_v2( + elem_bool == elem_bool, 0., float("nan")) # pylint: disable=comparison-with-itself + id_args = nest.map_structure( + lambda x: x + math_ops.cast(dresult_dep, x.dtype), id_args) + + t.watch(id_args) + if variables is not None: + t.watch(variables) + with variable_scope.variable_scope(current_var_scope): + recomputed_result = f(*id_args, **kwargs) + kw_vars = [] + if variables is not None: + kw_vars = list(variables) + grads = t.gradient( + recomputed_result, + list(id_args) + kw_vars, + output_gradients=dresult, + unconnected_gradients=UnconnectedGradients.ZERO) + + def transpose(*t_args, **t_kwargs): + """Gradient function calculation for forward mode autodiff.""" + # Just throw an error since gradients / activations are not stored on + # tape for recompute. + raise NotImplementedError( + "recompute_grad tried to transpose grad of {}. " + "Consider not using recompute_grad in forward mode" + "autodiff".format(f.__name__)) + + return (grads[:len(id_args)], grads[len(id_args):]), transpose + + return inner_recompute_grad(*wrapper_args) + + return result, grad_wrapper + + return tf_decorator.make_decorator(f, inner) + + +@tf_export("grad_pass_through") +def grad_pass_through(f): + """Creates a grad-pass-through op with the forward behavior provided in f. + + Use this function to wrap any op, maintaining its behavior in the forward + pass, but replacing the original op in the backward graph with an identity. + For example: + + ```python + x = tf.Variable(1.0, name="x") + z = tf.Variable(3.0, name="z") + + with tf.GradientTape() as tape: + # y will evaluate to 9.0 + y = tf.grad_pass_through(x.assign)(z**2) + # grads will evaluate to 6.0 + grads = tape.gradient(y, z) + ``` + + Another example is a 'differentiable' moving average approximation, where + gradients are allowed to flow into the last value fed to the moving average, + but the moving average is still used for the forward pass: + + ```python + x = ... # Some scalar value + # A moving average object, we don't need to know how this is implemented + moving_average = MovingAverage() + with backprop.GradientTape() as tape: + # mavg_x will evaluate to the current running average value + mavg_x = tf.grad_pass_through(moving_average)(x) + grads = tape.gradient(mavg_x, x) # grads will evaluate to 1.0 + ``` + + Args: + f: function `f(*x)` that returns a `Tensor` or nested structure of `Tensor` + outputs. + + Returns: + A function `h(x)` which returns the same values as `f(x)` and whose + gradients are the same as those of an identity function. + """ + @custom_gradient + def _grad_pass_through_op(*args, **kwargs): + def grad(*args, **kwargs): + variables = kwargs.get("variables") + if variables is not None: + # Variables involved in the wrapped op will not receive gradients. + return args, [None] * len(variables) + return args + return f(*args, **kwargs), grad + return tf_decorator.make_decorator(f, _grad_pass_through_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..30c0dc706355605452ff3e653a64c71c5c18afa1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_grad.py @@ -0,0 +1,82 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Gradients for operators defined in data_flow_ops.py.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import math_ops + + +@ops.RegisterGradient("DynamicPartition") +def _DynamicPartitionGrads(op, *grads): + """Gradients for DynamicPartition.""" + data = op.inputs[0] + indices = op.inputs[1] + num_partitions = op.get_attr("num_partitions") + + prefix_shape = array_ops.shape(indices) + original_indices = array_ops.reshape( + math_ops.range(math_ops.reduce_prod(prefix_shape)), prefix_shape) + partitioned_indices = data_flow_ops.dynamic_partition( + original_indices, indices, num_partitions) + reconstructed = data_flow_ops.parallel_dynamic_stitch(partitioned_indices, + grads) + reconstructed = array_ops.reshape(reconstructed, array_ops.shape(data)) + return [reconstructed, None] + + +@ops.RegisterGradient("DynamicStitch") +@ops.RegisterGradient("ParallelDynamicStitch") +def _DynamicStitchGrads(op, grad): + """Gradients for DynamicStitch and ParallelDynamicStitch.""" + + num_values = len(op.inputs) // 2 + indices_grad = [None] * num_values + + def AsInt32(x): + return (x if op.inputs[0].dtype == dtypes.int32 else + math_ops.cast(x, dtypes.int32)) + + inputs = [AsInt32(op.inputs[i]) for i in range(num_values)] + if isinstance(grad, indexed_slices.IndexedSlices): + output_shape = array_ops.shape(op.outputs[0]) + output_rows = output_shape[0] + grad = math_ops.unsorted_segment_sum(grad.values, grad.indices, output_rows) + values_grad = [array_ops.gather(grad, inp) for inp in inputs] + return indices_grad + values_grad + + +ops.NotDifferentiable("Queue") +ops.NotDifferentiable("QueueEnqueue") +ops.NotDifferentiable("QueueEnqueueMany") +ops.NotDifferentiable("QueueDequeue") +ops.NotDifferentiable("QueueDequeueMany") +ops.NotDifferentiable("QueueDequeueUpTo") +ops.NotDifferentiable("QueueClose") +ops.NotDifferentiable("QueueSize") + +ops.NotDifferentiable("Stack") +ops.NotDifferentiable("StackPush") +ops.NotDifferentiable("StackPop") +ops.NotDifferentiable("StackClose") + +ops.NotDifferentiable("GetSessionHandle") +ops.NotDifferentiable("GetSessionHandleV2") +ops.NotDifferentiable("GetSessionTensor") +ops.NotDifferentiable("DeleteSessionTensor") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..cef44f03933c013719a154e7572d85c0984432e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/data_flow_ops.py @@ -0,0 +1,2518 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#============================================================================== +"""Data Flow Operations.""" +# pylint: disable=g-bad-name +import functools +import hashlib +import threading + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.lib.io import python_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_data_flow_ops import * +from tensorflow.python.util import deprecation +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + +# pylint: enable=wildcard-import + + +def _as_type_list(dtypes): + """Convert dtypes to a list of types.""" + assert dtypes is not None + if not (isinstance(dtypes, list) or isinstance(dtypes, tuple)): + # We have a single type. + return [dtypes] + else: + # We have a list or tuple of types. + return list(dtypes) + + +def _as_shape_list(shapes, + dtypes, + unknown_dim_allowed=False, + unknown_rank_allowed=False): + """Convert shapes to a list of tuples of int (or None).""" + del dtypes + if unknown_dim_allowed: + if (not isinstance(shapes, collections_abc.Sequence) or not shapes or + any(shape is None or isinstance(shape, int) for shape in shapes)): + raise ValueError( + "When providing partial shapes, a list of shapes must be provided.") + if shapes is None: + return None + if isinstance(shapes, tensor_shape.TensorShape): + shapes = [shapes] + if not isinstance(shapes, (tuple, list)): + raise TypeError( + "Shapes must be a TensorShape or a list or tuple of TensorShapes, " + f"got {type(shapes)} instead.") + if all(shape is None or isinstance(shape, int) for shape in shapes): + # We have a single shape. + shapes = [shapes] + shapes = [tensor_shape.as_shape(shape) for shape in shapes] + if not unknown_dim_allowed: + if any(not shape.is_fully_defined() for shape in shapes): + raise ValueError(f"All shapes must be fully defined: {shapes}") + if not unknown_rank_allowed: + if any(shape.dims is None for shape in shapes): + raise ValueError(f"All shapes must have a defined rank: {shapes}") + + return shapes + + +def _as_name_list(names, dtypes): + if names is None: + return None + if not isinstance(names, (list, tuple)): + names = [names] + if len(names) != len(dtypes): + raise ValueError("List of names must have the same length as the list " + f"of dtypes, received len(names)={len(names)}," + f"len(dtypes)={len(dtypes)}") + return list(names) + + +def _shape_common(s1, s2): + """The greatest lower bound (ordered by specificity) TensorShape.""" + s1 = tensor_shape.TensorShape(s1) + s2 = tensor_shape.TensorShape(s2) + if s1.ndims is None or s2.ndims is None or s1.ndims != s2.ndims: + return tensor_shape.unknown_shape() + d = [ + d1 if d1 is not None and d1 == d2 else None + for (d1, d2) in zip(s1.as_list(), s2.as_list()) + ] + return tensor_shape.TensorShape(d) + + +# pylint: disable=protected-access +@tf_export("queue.QueueBase", + v1=["queue.QueueBase", "io.QueueBase", "QueueBase"]) +@deprecation.deprecated_endpoints(["io.QueueBase", "QueueBase"]) +class QueueBase: + """Base class for queue implementations. + + A queue is a TensorFlow data structure that stores tensors across + multiple steps, and exposes operations that enqueue and dequeue + tensors. + + Each queue element is a tuple of one or more tensors, where each + tuple component has a static dtype, and may have a static shape. The + queue implementations support versions of enqueue and dequeue that + handle single elements, versions that support enqueuing and + dequeuing a batch of elements at once. + + See `tf.queue.FIFOQueue` and + `tf.queue.RandomShuffleQueue` for concrete + implementations of this class, and instructions on how to create + them. + """ + + def __init__(self, dtypes, shapes, names, queue_ref): + """Constructs a queue object from a queue reference. + + The two optional lists, `shapes` and `names`, must be of the same length + as `dtypes` if provided. The values at a given index `i` indicate the + shape and name to use for the corresponding queue component in `dtypes`. + + Args: + dtypes: A list of types. The length of dtypes must equal the number + of tensors in each element. + shapes: Constraints on the shapes of tensors in an element: + A list of shape tuples or None. This list is the same length + as dtypes. If the shape of any tensors in the element are constrained, + all must be; shapes can be None if the shapes should not be constrained. + names: Optional list of names. If provided, the `enqueue()` and + `dequeue()` methods will use dictionaries with these names as keys. + Must be None or a list or tuple of the same length as `dtypes`. + queue_ref: The queue reference, i.e. the output of the queue op. + + Raises: + ValueError: If one of the arguments is invalid. + """ + self._dtypes = dtypes + if shapes is not None: + if len(shapes) != len(dtypes): + raise ValueError("Queue shapes must have the same length as dtypes, " + f"received len(shapes)={len(shapes)}, " + f"len(dtypes)={len(dtypes)}") + self._shapes = [tensor_shape.TensorShape(s) for s in shapes] + else: + self._shapes = [tensor_shape.unknown_shape() for _ in self._dtypes] + if names is not None: + if len(names) != len(dtypes): + raise ValueError("Queue names must have the same length as dtypes," + f"received len(names)={len(names)}," + f"len {len(dtypes)}") + self._names = names + else: + self._names = None + self._queue_ref = queue_ref + if isinstance(queue_ref, ops.EagerTensor): + if context.context().scope_name: + self._name = context.context().scope_name + else: + self._name = "Empty" + self._resource_deleter = resource_variable_ops.EagerResourceDeleter( + queue_ref, None) + else: + self._name = self._queue_ref.op.name.split("/")[-1] + + @staticmethod + def from_list(index, queues): + """Create a queue using the queue reference from `queues[index]`. + + Args: + index: An integer scalar tensor that determines the input that gets + selected. + queues: A list of `QueueBase` objects. + + Returns: + A `QueueBase` object. + + Raises: + TypeError: When `queues` is not a list of `QueueBase` objects, + or when the data types of `queues` are not all the same. + """ + if ((not queues) or (not isinstance(queues, list)) or + (not all(isinstance(x, QueueBase) for x in queues))): + raise TypeError("A list of queues expected") + + dtypes = queues[0].dtypes + if not all(dtypes == q.dtypes for q in queues[1:]): + raise TypeError("Queues do not have matching component dtypes.") + + names = queues[0].names + if not all(names == q.names for q in queues[1:]): + raise TypeError("Queues do not have matching component names.") + + queue_shapes = [q.shapes for q in queues] + reduced_shapes = [ + functools.reduce(_shape_common, s) for s in zip(*queue_shapes) + ] + + queue_refs = array_ops_stack.stack([x.queue_ref for x in queues]) + selected_queue = array_ops.gather(queue_refs, index) + return QueueBase( + dtypes=dtypes, + shapes=reduced_shapes, + names=names, + queue_ref=selected_queue) + + @property + def queue_ref(self): + """The underlying queue reference.""" + return self._queue_ref + + @property + def name(self): + """The name of the underlying queue.""" + if context.executing_eagerly(): + return self._name + return self._queue_ref.op.name + + @property + def dtypes(self): + """The list of dtypes for each component of a queue element.""" + return self._dtypes + + @property + def shapes(self): + """The list of shapes for each component of a queue element.""" + return self._shapes + + @property + def names(self): + """The list of names for each component of a queue element.""" + return self._names + + def _check_enqueue_dtypes(self, vals): + """Validate and convert `vals` to a list of `Tensor`s. + + The `vals` argument can be a Tensor, a list or tuple of tensors, or a + dictionary with tensor values. + + If it is a dictionary, the queue must have been constructed with a + `names` attribute and the dictionary keys must match the queue names. + If the queue was constructed with a `names` attribute, `vals` must + be a dictionary. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary.. + + Returns: + A list of `Tensor` objects. + + Raises: + ValueError: If `vals` is invalid. + """ + if isinstance(vals, dict): + if not self._names: + raise ValueError("Queue must have names to enqueue a dictionary") + if sorted(self._names, key=str) != sorted(vals.keys(), key=str): + raise ValueError("Keys in dictionary to enqueue do not match " + f"names of Queue. Dictionary: {sorted(vals.keys())}," + f"Queue: {sorted(self._names)}") + # The order of values in `self._names` indicates the order in which the + # tensors in the dictionary `vals` must be listed. + vals = [vals[k] for k in self._names] + else: + if self._names: + raise ValueError("You must enqueue a dictionary in a Queue with names") + if not isinstance(vals, (list, tuple)): + vals = [vals] + + tensors = [] + for i, (val, dtype) in enumerate(zip(vals, self._dtypes)): + tensors.append( + ops.convert_to_tensor(val, dtype=dtype, name="component_%d" % i)) + + return tensors + + def _scope_vals(self, vals): + """Return a list of values to pass to `name_scope()`. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary. + + Returns: + The values in vals as a list. + """ + if isinstance(vals, (list, tuple)): + return vals + elif isinstance(vals, dict): + return vals.values() + else: + return [vals] + + def enqueue(self, vals, name=None): + """Enqueues one element to this queue. + + If the queue is full when this operation executes, it will block + until the element has been enqueued. + + At runtime, this operation may raise an error if the queue is + `tf.QueueBase.close` before or during its execution. If the + queue is closed before this operation runs, + `tf.errors.CancelledError` will be raised. If this operation is + blocked, and either (i) the queue is closed by a close operation + with `cancel_pending_enqueues=True`, or (ii) the session is + `tf.Session.close`, + `tf.errors.CancelledError` will be raised. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary containing + the values to enqueue. + name: A name for the operation (optional). + + Returns: + The operation that enqueues a new tuple of tensors to the queue. + """ + with ops.name_scope(name, "%s_enqueue" % self._name, + self._scope_vals(vals)) as scope: + vals = self._check_enqueue_dtypes(vals) + + # NOTE(mrry): Not using a shape function because we need access to + # the `QueueBase` object. + for val, shape in zip(vals, self._shapes): + val.get_shape().assert_is_compatible_with(shape) + + if self._queue_ref.dtype == _dtypes.resource: + return gen_data_flow_ops.queue_enqueue_v2( + self._queue_ref, vals, name=scope) + else: + return gen_data_flow_ops.queue_enqueue( + self._queue_ref, vals, name=scope) + + def enqueue_many(self, vals, name=None): + """Enqueues zero or more elements to this queue. + + This operation slices each component tensor along the 0th dimension to + make multiple queue elements. All of the tensors in `vals` must have the + same size in the 0th dimension. + + If the queue is full when this operation executes, it will block + until all of the elements have been enqueued. + + At runtime, this operation may raise an error if the queue is + `tf.QueueBase.close` before or during its execution. If the + queue is closed before this operation runs, + `tf.errors.CancelledError` will be raised. If this operation is + blocked, and either (i) the queue is closed by a close operation + with `cancel_pending_enqueues=True`, or (ii) the session is + `tf.Session.close`, + `tf.errors.CancelledError` will be raised. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary + from which the queue elements are taken. + name: A name for the operation (optional). + + Returns: + The operation that enqueues a batch of tuples of tensors to the queue. + """ + with ops.name_scope(name, "%s_EnqueueMany" % self._name, + self._scope_vals(vals)) as scope: + vals = self._check_enqueue_dtypes(vals) + + # NOTE(mrry): Not using a shape function because we need access to + # the `QueueBase` object. + # NOTE(fchollet): the code that follow is verbose because it needs to be + # compatible with both TF v1 TensorShape behavior and TF v2 behavior. + batch_dim = tensor_shape.dimension_value( + vals[0].get_shape().with_rank_at_least(1)[0]) + batch_dim = tensor_shape.Dimension(batch_dim) + for val, shape in zip(vals, self._shapes): + val_batch_dim = tensor_shape.dimension_value( + val.get_shape().with_rank_at_least(1)[0]) + val_batch_dim = tensor_shape.Dimension(val_batch_dim) + batch_dim = batch_dim.merge_with(val_batch_dim) + val.get_shape()[1:].assert_is_compatible_with(shape) + + return gen_data_flow_ops.queue_enqueue_many_v2( + self._queue_ref, vals, name=scope) + + def _dequeue_return_value(self, tensors): + """Return the value to return from a dequeue op. + + If the queue has names, return a dictionary with the + names as keys. Otherwise return either a single tensor + or a list of tensors depending on the length of `tensors`. + + Args: + tensors: List of tensors from the dequeue op. + + Returns: + A single tensor, a list of tensors, or a dictionary + of tensors. + """ + if self._names: + # The returned values in `tensors` are in the same order as + # the names in `self._names`. + return {n: tensors[i] for i, n in enumerate(self._names)} + elif len(tensors) == 1: + return tensors[0] + else: + return tensors + + def dequeue(self, name=None): + """Dequeues one element from this queue. + + If the queue is empty when this operation executes, it will block + until there is an element to dequeue. + + At runtime, this operation may raise an error if the queue is + `tf.QueueBase.close` before or during its execution. If the + queue is closed, the queue is empty, and there are no pending + enqueue operations that can fulfill this request, + `tf.errors.OutOfRangeError` will be raised. If the session is + `tf.Session.close`, + `tf.errors.CancelledError` will be raised. + + Args: + name: A name for the operation (optional). + + Returns: + The tuple of tensors that was dequeued. + """ + if name is None: + name = "%s_Dequeue" % self._name + if self._queue_ref.dtype == _dtypes.resource: + ret = gen_data_flow_ops.queue_dequeue_v2( + self._queue_ref, self._dtypes, name=name) + else: + ret = gen_data_flow_ops.queue_dequeue( + self._queue_ref, self._dtypes, name=name) + + # NOTE(mrry): Not using a shape function because we need access to + # the `QueueBase` object. + if not context.executing_eagerly(): + op = ret[0].op + for output, shape in zip(op.values(), self._shapes): + output.set_shape(shape) + + return self._dequeue_return_value(ret) + + def dequeue_many(self, n, name=None): + """Dequeues and concatenates `n` elements from this queue. + + This operation concatenates queue-element component tensors along + the 0th dimension to make a single component tensor. All of the + components in the dequeued tuple will have size `n` in the 0th dimension. + + If the queue is closed and there are less than `n` elements left, then an + `OutOfRange` exception is raised. + + At runtime, this operation may raise an error if the queue is + `tf.QueueBase.close` before or during its execution. If the + queue is closed, the queue contains fewer than `n` elements, and + there are no pending enqueue operations that can fulfill this + request, `tf.errors.OutOfRangeError` will be raised. If the + session is `tf.Session.close`, + `tf.errors.CancelledError` will be raised. + + Args: + n: A scalar `Tensor` containing the number of elements to dequeue. + name: A name for the operation (optional). + + Returns: + The list of concatenated tensors that was dequeued. + """ + if name is None: + name = "%s_DequeueMany" % self._name + + ret = gen_data_flow_ops.queue_dequeue_many_v2( + self._queue_ref, n=n, component_types=self._dtypes, name=name) + + # NOTE(mrry): Not using a shape function because we need access to + # the Queue object. + if not context.executing_eagerly(): + op = ret[0].op + batch_dim = tensor_shape.Dimension( + tensor_util.constant_value(op.inputs[1])) + for output, shape in zip(op.values(), self._shapes): + output.set_shape( + tensor_shape.TensorShape([batch_dim]).concatenate(shape)) + + return self._dequeue_return_value(ret) + + def dequeue_up_to(self, n, name=None): + """Dequeues and concatenates `n` elements from this queue. + + **Note** This operation is not supported by all queues. If a queue does not + support DequeueUpTo, then a `tf.errors.UnimplementedError` is raised. + + This operation concatenates queue-element component tensors along + the 0th dimension to make a single component tensor. If the queue + has not been closed, all of the components in the dequeued tuple + will have size `n` in the 0th dimension. + + If the queue is closed and there are more than `0` but fewer than + `n` elements remaining, then instead of raising a + `tf.errors.OutOfRangeError` like `tf.QueueBase.dequeue_many`, + less than `n` elements are returned immediately. If the queue is + closed and there are `0` elements left in the queue, then a + `tf.errors.OutOfRangeError` is raised just like in `dequeue_many`. + Otherwise the behavior is identical to `dequeue_many`. + + Args: + n: A scalar `Tensor` containing the number of elements to dequeue. + name: A name for the operation (optional). + + Returns: + The tuple of concatenated tensors that was dequeued. + """ + if name is None: + name = "%s_DequeueUpTo" % self._name + + ret = gen_data_flow_ops.queue_dequeue_up_to_v2( + self._queue_ref, n=n, component_types=self._dtypes, name=name) + + # NOTE(mrry): Not using a shape function because we need access to + # the Queue object. + if not context.executing_eagerly(): + op = ret[0].op + for output, shape in zip(op.values(), self._shapes): + output.set_shape(tensor_shape.TensorShape([None]).concatenate(shape)) + + return self._dequeue_return_value(ret) + + def close(self, cancel_pending_enqueues=False, name=None): + """Closes this queue. + + This operation signals that no more elements will be enqueued in + the given queue. Subsequent `enqueue` and `enqueue_many` + operations will fail. Subsequent `dequeue` and `dequeue_many` + operations will continue to succeed if sufficient elements remain + in the queue. Subsequently dequeue and dequeue_many operations + that would otherwise block waiting for more elements (if close + hadn't been called) will now fail immediately. + + If `cancel_pending_enqueues` is `True`, all pending requests will also + be canceled. + + Args: + cancel_pending_enqueues: (Optional.) A boolean, defaulting to + `False` (described above). + name: A name for the operation (optional). + + Returns: + The operation that closes the queue. + """ + if name is None: + name = "%s_Close" % self._name + if self._queue_ref.dtype == _dtypes.resource: + return gen_data_flow_ops.queue_close_v2( + self._queue_ref, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + else: + return gen_data_flow_ops.queue_close( + self._queue_ref, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + + def is_closed(self, name=None): + """Returns true if queue is closed. + + This operation returns true if the queue is closed and false if the queue + is open. + + Args: + name: A name for the operation (optional). + + Returns: + True if the queue is closed and false if the queue is open. + """ + if name is None: + name = "%s_Is_Closed" % self._name + if self._queue_ref.dtype == _dtypes.resource: + return gen_data_flow_ops.queue_is_closed_v2(self._queue_ref, name=name) + else: + return gen_data_flow_ops.queue_is_closed_(self._queue_ref, name=name) + + def size(self, name=None): + """Compute the number of elements in this queue. + + Args: + name: A name for the operation (optional). + + Returns: + A scalar tensor containing the number of elements in this queue. + """ + if name is None: + name = "%s_Size" % self._name + if self._queue_ref.dtype == _dtypes.resource: + return gen_data_flow_ops.queue_size_v2(self._queue_ref, name=name) + else: + return gen_data_flow_ops.queue_size(self._queue_ref, name=name) + +def _shared_name(shared_name): + if context.executing_eagerly(): + return str(ops.uid()) + return shared_name + + +@tf_export( + "queue.RandomShuffleQueue", + v1=["queue.RandomShuffleQueue", + "io.RandomShuffleQueue", "RandomShuffleQueue"]) +@deprecation.deprecated_endpoints( + ["io.RandomShuffleQueue", "RandomShuffleQueue"]) +class RandomShuffleQueue(QueueBase): + """A queue implementation that dequeues elements in a random order. + + See `tf.queue.QueueBase` for a description of the methods on + this class. + """ + + def __init__(self, + capacity, + min_after_dequeue, + dtypes, + shapes=None, + names=None, + seed=None, + shared_name=None, + name="random_shuffle_queue"): + """Create a queue that dequeues elements in a random order. + + A `RandomShuffleQueue` has bounded capacity; supports multiple + concurrent producers and consumers; and provides exactly-once + delivery. + + A `RandomShuffleQueue` holds a list of up to `capacity` + elements. Each element is a fixed-length tuple of tensors whose + dtypes are described by `dtypes`, and whose shapes are optionally + described by the `shapes` argument. + + If the `shapes` argument is specified, each component of a queue + element must have the respective fixed shape. If it is + unspecified, different queue elements may have different shapes, + but the use of `dequeue_many` is disallowed. + + The `min_after_dequeue` argument allows the caller to specify a + minimum number of elements that will remain in the queue after a + `dequeue` or `dequeue_many` operation completes, to ensure a + minimum level of mixing of elements. This invariant is maintained + by blocking those operations until sufficient elements have been + enqueued. The `min_after_dequeue` argument is ignored after the + queue has been closed. + + Args: + capacity: An integer. The upper bound on the number of elements + that may be stored in this queue. + min_after_dequeue: An integer (described above). + dtypes: A list of `DType` objects. The length of `dtypes` must equal + the number of tensors in each queue element. + shapes: (Optional.) A list of fully-defined `TensorShape` objects + with the same length as `dtypes`, or `None`. + names: (Optional.) A list of string naming the components in the queue + with the same length as `dtypes`, or `None`. If specified the dequeue + methods return a dictionary with the names as keys. + seed: A Python integer. Used to create a random seed. See + `tf.compat.v1.set_random_seed` + for behavior. + shared_name: (Optional.) If non-empty, this queue will be shared under + the given name across multiple sessions. + name: Optional name for the queue operation. + """ + dtypes = _as_type_list(dtypes) + shapes = _as_shape_list(shapes, dtypes) + names = _as_name_list(names, dtypes) + seed1, seed2 = random_seed.get_seed(seed) + if seed1 is None and seed2 is None: + seed1, seed2 = 0, 0 + elif seed is None and shared_name is not None: + # This means that graph seed is provided but op seed is not provided. + # If shared_name is also provided, make seed2 depend only on the graph + # seed and shared_name. (seed2 from get_seed() is generally dependent on + # the id of the last op created.) + string = (str(seed1) + shared_name).encode("utf-8") + seed2 = int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF + queue_ref = gen_data_flow_ops.random_shuffle_queue_v2( + component_types=dtypes, + shapes=shapes, + capacity=capacity, + min_after_dequeue=min_after_dequeue, + seed=seed1, + seed2=seed2, + shared_name=_shared_name(shared_name), + name=name) + + super(RandomShuffleQueue, self).__init__(dtypes, shapes, names, queue_ref) + + +@tf_export("queue.FIFOQueue", v1=["queue.FIFOQueue", "FIFOQueue"]) +@deprecation.deprecated_endpoints("FIFOQueue") +class FIFOQueue(QueueBase): + """A queue implementation that dequeues elements in first-in first-out order. + + See `tf.queue.QueueBase` for a description of the methods on + this class. + """ + + def __init__(self, + capacity, + dtypes, + shapes=None, + names=None, + shared_name=None, + name="fifo_queue"): + """Creates a queue that dequeues elements in a first-in first-out order. + + A `FIFOQueue` has bounded capacity; supports multiple concurrent + producers and consumers; and provides exactly-once delivery. + + A `FIFOQueue` holds a list of up to `capacity` elements. Each + element is a fixed-length tuple of tensors whose dtypes are + described by `dtypes`, and whose shapes are optionally described + by the `shapes` argument. + + If the `shapes` argument is specified, each component of a queue + element must have the respective fixed shape. If it is + unspecified, different queue elements may have different shapes, + but the use of `dequeue_many` is disallowed. + + Args: + capacity: An integer. The upper bound on the number of elements + that may be stored in this queue. + dtypes: A list of `DType` objects. The length of `dtypes` must equal + the number of tensors in each queue element. + shapes: (Optional.) A list of fully-defined `TensorShape` objects + with the same length as `dtypes`, or `None`. + names: (Optional.) A list of string naming the components in the queue + with the same length as `dtypes`, or `None`. If specified the dequeue + methods return a dictionary with the names as keys. + shared_name: (Optional.) If non-empty, this queue will be shared under + the given name across multiple sessions. + name: Optional name for the queue operation. + """ + dtypes = _as_type_list(dtypes) + shapes = _as_shape_list(shapes, dtypes) + names = _as_name_list(names, dtypes) + with ops.init_scope(), ops.device("CPU"): + queue_ref = gen_data_flow_ops.fifo_queue_v2( + component_types=dtypes, + shapes=shapes, + capacity=capacity, + shared_name=_shared_name(shared_name), + name=name) + + super(FIFOQueue, self).__init__(dtypes, shapes, names, queue_ref) + + +# TODO(allenl): If GPU-compatible queues turn out to be useful, we should +# implement GPU kernels for EnqueueMany and DequeueMany so we can make the +# public FIFOQueue GPU-compatible and remove this internal version. +class GPUCompatibleFIFOQueue(QueueBase): + """A queue implementation that dequeues elements in first-in first-out order. + + GPUCompatibleFIFOQueue is like FIFOQueue, but the queue resource may be placed + either on a CPU or on a GPU. It is not cross-device: enqueues and dequeues + will be colocated with the queue resource. GPUCompatibleFIFOQueue only + supports enqueue and dequeue at the moment, not enqueue_many or dequeue_many. + + See `tf.queue.QueueBase` for a description of the methods on this class. + """ + + def __init__(self, + capacity, + dtypes, + shapes=None, + names=None, + shared_name=None, + name="fifo_queue"): + """Creates a queue that dequeues elements in a first-in first-out order. + + A `FIFOQueue` has bounded capacity; supports multiple concurrent + producers and consumers; and provides exactly-once delivery. + + A `FIFOQueue` holds a list of up to `capacity` elements. Each + element is a fixed-length tuple of tensors whose dtypes are + described by `dtypes`, and whose shapes are optionally described + by the `shapes` argument. + + If the `shapes` argument is specified, each component of a queue + element must have the respective fixed shape. If it is + unspecified, different queue elements may have different shapes, + but the use of `dequeue_many` is disallowed. + + Args: + capacity: An integer. The upper bound on the number of elements + that may be stored in this queue. + dtypes: A list of `DType` objects. The length of `dtypes` must equal + the number of tensors in each queue element. + shapes: (Optional.) A list of fully-defined `TensorShape` objects + with the same length as `dtypes`, or `None`. + names: (Optional.) A list of string naming the components in the queue + with the same length as `dtypes`, or `None`. If specified the dequeue + methods return a dictionary with the names as keys. + shared_name: (Optional.) If non-empty, this queue will be shared under + the given name across multiple sessions. + name: Optional name for the queue operation. + """ + dtypes = _as_type_list(dtypes) + shapes = _as_shape_list(shapes, dtypes) + names = _as_name_list(names, dtypes) + with ops.init_scope(): + queue_ref = gen_data_flow_ops.fifo_queue_v2( + component_types=dtypes, + shapes=shapes, + capacity=capacity, + shared_name=_shared_name(shared_name), + name=name) + + super(GPUCompatibleFIFOQueue, self).__init__( + dtypes, shapes, names, queue_ref) + + def enqueue_many(self, vals, name=None): + """enqueue_many is not supported on GPUCompatibleFIFOQueue.""" + raise NotImplementedError( + "GPUCompatibleFIFOQueue does not support enqueue_many or dequeue_many, " + "only enqueue and dequeue.") + + def dequeue_many(self, n, name=None): + """dequeue_many is not supported on GPUCompatibleFIFOQueue.""" + raise NotImplementedError( + "GPUCompatibleFIFOQueue does not support enqueue_many or dequeue_many, " + "only enqueue and dequeue.") + + +@tf_export( + "queue.PaddingFIFOQueue", + v1=["queue.PaddingFIFOQueue", "io.PaddingFIFOQueue", "PaddingFIFOQueue"]) +@deprecation.deprecated_endpoints(["io.PaddingFIFOQueue", "PaddingFIFOQueue"]) +class PaddingFIFOQueue(QueueBase): + """A FIFOQueue that supports batching variable-sized tensors by padding. + + A `PaddingFIFOQueue` may contain components with dynamic shape, while also + supporting `dequeue_many`. See the constructor for more details. + + See `tf.queue.QueueBase` for a description of the methods on + this class. + """ + + def __init__(self, + capacity, + dtypes, + shapes, + names=None, + shared_name=None, + name="padding_fifo_queue"): + """Creates a queue that dequeues elements in a first-in first-out order. + + A `PaddingFIFOQueue` has bounded capacity; supports multiple concurrent + producers and consumers; and provides exactly-once delivery. + + A `PaddingFIFOQueue` holds a list of up to `capacity` elements. Each + element is a fixed-length tuple of tensors whose dtypes are + described by `dtypes`, and whose shapes are described by the `shapes` + argument. + + The `shapes` argument must be specified; each component of a queue + element must have the respective shape. Shapes of fixed + rank but variable size are allowed by setting any shape dimension to None. + In this case, the inputs' shape may vary along the given dimension, and + `dequeue_many` will pad the given dimension with zeros up to the maximum + shape of all elements in the given batch. + + Args: + capacity: An integer. The upper bound on the number of elements + that may be stored in this queue. + dtypes: A list of `DType` objects. The length of `dtypes` must equal + the number of tensors in each queue element. + shapes: A list of `TensorShape` objects, with the same length as + `dtypes`. Any dimension in the `TensorShape` containing value + `None` is dynamic and allows values to be enqueued with + variable size in that dimension. + names: (Optional.) A list of string naming the components in the queue + with the same length as `dtypes`, or `None`. If specified the dequeue + methods return a dictionary with the names as keys. + shared_name: (Optional.) If non-empty, this queue will be shared under + the given name across multiple sessions. + name: Optional name for the queue operation. + + Raises: + ValueError: If shapes is not a list of shapes, or the lengths of dtypes + and shapes do not match, or if names is specified and the lengths of + dtypes and names do not match. + """ + dtypes = _as_type_list(dtypes) + shapes = _as_shape_list(shapes, dtypes, unknown_dim_allowed=True) + names = _as_name_list(names, dtypes) + if len(dtypes) != len(shapes): + raise ValueError("Shapes must be provided for all components, " + f"but received {len(dtypes)} dtypes and " + f"{len(shapes)} shapes.") + queue_ref = gen_data_flow_ops.padding_fifo_queue_v2( + component_types=dtypes, + shapes=shapes, + capacity=capacity, + shared_name=_shared_name(shared_name), + name=name) + + super(PaddingFIFOQueue, self).__init__(dtypes, shapes, names, queue_ref) + + +@tf_export("queue.PriorityQueue", + v1=["queue.PriorityQueue", "io.PriorityQueue", "PriorityQueue"]) +@deprecation.deprecated_endpoints(["io.PriorityQueue", "PriorityQueue"]) +class PriorityQueue(QueueBase): + """A queue implementation that dequeues elements in prioritized order. + + See `tf.queue.QueueBase` for a description of the methods on + this class. + """ + + def __init__(self, + capacity, + types, + shapes=None, + names=None, + shared_name=None, + name="priority_queue"): + """Creates a queue that dequeues elements in a first-in first-out order. + + A `PriorityQueue` has bounded capacity; supports multiple concurrent + producers and consumers; and provides exactly-once delivery. + + A `PriorityQueue` holds a list of up to `capacity` elements. Each + element is a fixed-length tuple of tensors whose dtypes are + described by `types`, and whose shapes are optionally described + by the `shapes` argument. + + If the `shapes` argument is specified, each component of a queue + element must have the respective fixed shape. If it is + unspecified, different queue elements may have different shapes, + but the use of `dequeue_many` is disallowed. + + Enqueues and Dequeues to the `PriorityQueue` must include an additional + tuple entry at the beginning: the `priority`. The priority must be + an int64 scalar (for `enqueue`) or an int64 vector (for `enqueue_many`). + + Args: + capacity: An integer. The upper bound on the number of elements + that may be stored in this queue. + types: A list of `DType` objects. The length of `types` must equal + the number of tensors in each queue element, except the first priority + element. The first tensor in each element is the priority, + which must be type int64. + shapes: (Optional.) A list of fully-defined `TensorShape` objects, + with the same length as `types`, or `None`. + names: (Optional.) A list of strings naming the components in the queue + with the same length as `dtypes`, or `None`. If specified, the dequeue + methods return a dictionary with the names as keys. + shared_name: (Optional.) If non-empty, this queue will be shared under + the given name across multiple sessions. + name: Optional name for the queue operation. + """ + types = _as_type_list(types) + shapes = _as_shape_list(shapes, types) + + queue_ref = gen_data_flow_ops.priority_queue_v2( + component_types=types, + shapes=shapes, + capacity=capacity, + shared_name=_shared_name(shared_name), + name=name) + + priority_dtypes = [_dtypes.int64] + types + priority_shapes = [()] + shapes if shapes else shapes + + super(PriorityQueue, self).__init__(priority_dtypes, priority_shapes, names, + queue_ref) + + +# TODO(josh11b): class BatchQueue(QueueBase): + + +class Barrier: + """Represents a key-value map that persists across graph executions.""" + + def __init__(self, types, shapes=None, shared_name=None, name="barrier"): + """Creates a barrier that persists across different graph executions. + + A barrier represents a key-value map, where each key is a string, and + each value is a tuple of tensors. + + At runtime, the barrier contains 'complete' and 'incomplete' + elements. A complete element has defined tensors for all + components of its value tuple, and may be accessed using + take_many. An incomplete element has some undefined components in + its value tuple, and may be updated using insert_many. + + The barrier call `take_many` outputs values in a particular order. + First, it only outputs completed values. Second, the order in which + completed values are returned matches the order in which their very + first component was inserted into the barrier. So, for example, for this + sequence of insertions and removals: + + barrier = Barrier((tf.string, tf.int32), shapes=((), ())) + barrier.insert_many(0, keys=["k1", "k2"], values=["a", "b"]).run() + barrier.insert_many(1, keys=["k1"], values=[1]).run() + barrier.insert_many(0, keys=["k3"], values=["c"]).run() + barrier.insert_many(1, keys=["k3"], values=[3]).run() + barrier.insert_many(1, keys=["k2"], values=[2]).run() + + (indices, keys, values) = barrier.take_many(2) + (indices_val, keys_val, values0_val, values1_val) = + session.run([indices, keys, values[0], values[1]]) + + The output will be (up to permutation of "k1" and "k2"): + + indices_val == (-2**63, -2**63) + keys_val == ("k1", "k2") + values0_val == ("a", "b") + values1_val == (1, 2) + + Note the key "k2" was inserted into the barrier before "k3". Even though + "k3" was completed first, both are complete by the time + take_many is called. As a result, "k2" is prioritized and "k1" and "k2" + are returned first. "k3" remains in the barrier until the next execution + of `take_many`. Since "k1" and "k2" had their first insertions into + the barrier together, their indices are the same (-2**63). The index + of "k3" will be -2**63 + 1, because it was the next new inserted key. + + Args: + types: A single dtype or a tuple of dtypes, corresponding to the + dtypes of the tensor elements that comprise a value in this barrier. + shapes: Optional. Constraints on the shapes of tensors in the values: + a single tensor shape tuple; a tuple of tensor shape tuples + for each barrier-element tuple component; or None if the shape should + not be constrained. + shared_name: Optional. If non-empty, this barrier will be shared under + the given name across multiple sessions. + name: Optional name for the barrier op. + + Raises: + ValueError: If one of the `shapes` indicate no elements. + """ + self._types = _as_type_list(types) + + if shapes is not None: + shapes = _as_shape_list(shapes, self._types) + self._shapes = [tensor_shape.TensorShape(s) for s in shapes] + for i, shape in enumerate(self._shapes): + if shape.num_elements() == 0: + raise ValueError("Empty tensors are not supported, but received " + f"shape '{shape}' at index {i}") + else: + self._shapes = [tensor_shape.unknown_shape() for _ in self._types] + + self._barrier_ref = gen_data_flow_ops.barrier( + component_types=self._types, + shapes=self._shapes, + shared_name=shared_name, + name=name) + if context.executing_eagerly(): + self._name = context.context().scope_name + else: + self._name = self._barrier_ref.op.name.split("/")[-1] + + @property + def barrier_ref(self): + """Get the underlying barrier reference.""" + return self._barrier_ref + + @property + def name(self): + """The name of the underlying barrier.""" + if context.executing_eagerly(): + return self._name + return self._barrier_ref.op.name + + def insert_many(self, component_index, keys, values, name=None): + """For each key, assigns the respective value to the specified component. + + This operation updates each element at component_index. + + Args: + component_index: The component of the value that is being assigned. + keys: A vector of keys, with length n. + values: An any-dimensional tensor of values, which are associated with the + respective keys. The first dimension must have length n. + name: Optional name for the op. + + Returns: + The operation that performs the insertion. + Raises: + InvalidArgumentsError: If inserting keys and values without elements. + """ + if name is None: + name = "%s_BarrierInsertMany" % self._name + return gen_data_flow_ops.barrier_insert_many( + self._barrier_ref, keys, values, component_index, name=name) + + def take_many(self, + num_elements, + allow_small_batch=False, + timeout=None, + name=None): + """Takes the given number of completed elements from this barrier. + + This operation concatenates completed-element component tensors along + the 0th dimension to make a single component tensor. + + If barrier has no completed elements, this operation will block + until there are 'num_elements' elements to take. + + TODO(b/25743580): the semantics of `allow_small_batch` are experimental + and may be extended to other cases in the future. + + TODO(ebrevdo): If a take_many(allow_small_batch=True) is blocking + already when the barrier is closed, it will block for ever. Fix this + by using asynchronous operations. + + Args: + num_elements: The number of elements to take. + allow_small_batch: If the barrier is closed, don't block if there are less + completed elements than requested, but instead return all available + completed elements. + timeout: This specifies the number of milliseconds to block + before returning with DEADLINE_EXCEEDED. (This option is not + supported yet.) + name: A name for the operation (optional). + + Returns: + A tuple of (index, key, value_list). + "index" is a int64 tensor of length num_elements containing the + index of the insert_many call for which the very first component of + the given element was inserted into the Barrier, starting with + the value -2**63. Note, this value is different from the + index of the insert_many call for which the element was completed. + "key" is a string tensor of length num_elements containing the keys. + "value_list" is a tuple of tensors, each one with size num_elements + in the 0th dimension for each component in the barrier's values. + + """ + if name is None: + name = "%s_BarrierTakeMany" % self._name + ret = gen_data_flow_ops.barrier_take_many( + self._barrier_ref, + num_elements, + self._types, + allow_small_batch, + timeout, + name=name) + + # NOTE(mrry): Not using a shape function because we need access to + # the Barrier object. + if not context.executing_eagerly(): + op = ret[0].op + if allow_small_batch: + batch_dim = None + else: + batch_dim = tensor_shape.Dimension( + tensor_util.constant_value(op.inputs[1])) + op.outputs[0].set_shape(tensor_shape.TensorShape([batch_dim])) # indices + op.outputs[1].set_shape(tensor_shape.TensorShape([batch_dim])) # keys + for output, shape in zip(op.outputs[2:], self._shapes): # value_list + output.set_shape( + tensor_shape.TensorShape([batch_dim]).concatenate(shape)) + + return ret + + def close(self, cancel_pending_enqueues=False, name=None): + """Closes this barrier. + + This operation signals that no more new key values will be inserted in the + given barrier. Subsequent InsertMany operations with new keys will fail. + InsertMany operations that just complement already existing keys with other + components, will continue to succeed. Subsequent TakeMany operations will + continue to succeed if sufficient elements remain in the barrier. Subsequent + TakeMany operations that would block will fail immediately. + + If `cancel_pending_enqueues` is `True`, all pending requests to the + underlying queue will also be canceled, and completing of already + started values is also not acceptable anymore. + + Args: + cancel_pending_enqueues: (Optional.) A boolean, defaulting to + `False` (described above). + name: Optional name for the op. + + Returns: + The operation that closes the barrier. + """ + if name is None: + name = "%s_BarrierClose" % self._name + return gen_data_flow_ops.barrier_close( + self._barrier_ref, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + + def ready_size(self, name=None): + """Compute the number of complete elements in the given barrier. + + Args: + name: A name for the operation (optional). + + Returns: + A single-element tensor containing the number of complete elements in the + given barrier. + """ + if name is None: + name = "%s_BarrierReadySize" % self._name + return gen_data_flow_ops.barrier_ready_size(self._barrier_ref, name=name) + + def incomplete_size(self, name=None): + """Compute the number of incomplete elements in the given barrier. + + Args: + name: A name for the operation (optional). + + Returns: + A single-element tensor containing the number of incomplete elements in + the given barrier. + """ + if name is None: + name = "%s_BarrierIncompleteSize" % self._name + return gen_data_flow_ops.barrier_incomplete_size( + self._barrier_ref, name=name) + + +@tf_export(v1=["ConditionalAccumulatorBase"]) +class ConditionalAccumulatorBase: + """A conditional accumulator for aggregating gradients. + + Up-to-date gradients (i.e., time step at which gradient was computed is + equal to the accumulator's time step) are added to the accumulator. + + Extraction of the average gradient is blocked until the required number of + gradients has been accumulated. + """ + + def __init__(self, dtype, shape, accumulator_ref): + """Creates a new ConditionalAccumulator. + + Args: + dtype: Datatype of the accumulated gradients. + shape: Shape of the accumulated gradients. + accumulator_ref: A handle to the conditional accumulator, created by sub- + classes + """ + self._dtype = dtype + if shape is not None: + self._shape = tensor_shape.TensorShape(shape) + else: + self._shape = tensor_shape.unknown_shape() + self._accumulator_ref = accumulator_ref + if context.executing_eagerly(): + self._name = context.context().scope_name + else: + self._name = self._accumulator_ref.op.name.split("/")[-1] + + @property + def accumulator_ref(self): + """The underlying accumulator reference.""" + return self._accumulator_ref + + @property + def name(self): + """The name of the underlying accumulator.""" + return self._name + + @property + def dtype(self): + """The datatype of the gradients accumulated by this accumulator.""" + return self._dtype + + def num_accumulated(self, name=None): + """Number of gradients that have currently been aggregated in accumulator. + + Args: + name: Optional name for the operation. + + Returns: + Number of accumulated gradients currently in accumulator. + """ + if name is None: + name = "%s_NumAccumulated" % self._name + + return gen_data_flow_ops.resource_accumulator_num_accumulated( + self._accumulator_ref, name=name) + + def set_global_step(self, new_global_step, name=None): + """Sets the global time step of the accumulator. + + The operation logs a warning if we attempt to set to a time step that is + lower than the accumulator's own time step. + + Args: + new_global_step: Value of new time step. Can be a variable or a constant + name: Optional name for the operation. + + Returns: + Operation that sets the accumulator's time step. + """ + return gen_data_flow_ops.resource_accumulator_set_global_step( + self._accumulator_ref, + math_ops.cast(ops.convert_to_tensor(new_global_step), _dtypes.int64), + name=name) + + +@tf_export(v1=["ConditionalAccumulator"]) +class ConditionalAccumulator(ConditionalAccumulatorBase): + """A conditional accumulator for aggregating gradients. + + Up-to-date gradients (i.e., time step at which gradient was computed is + equal to the accumulator's time step) are added to the accumulator. + + Extraction of the average gradient is blocked until the required number of + gradients has been accumulated. + """ + + def __init__(self, + dtype, + shape=None, + shared_name=None, + name="conditional_accumulator", + reduction_type="MEAN"): + """Creates a new ConditionalAccumulator. + + Args: + dtype: Datatype of the accumulated gradients. + shape: Shape of the accumulated gradients. + shared_name: Optional. If non-empty, this accumulator will be shared under + the given name across multiple sessions. + name: Optional name for the accumulator. + reduction_type: Reduction type to use when taking the gradient. + """ + accumulator_ref = gen_data_flow_ops.resource_conditional_accumulator( + dtype=dtype, + shape=shape, + shared_name=shared_name, + name=name, + reduction_type=reduction_type) + if context.executing_eagerly(): + self._resource_deleter = resource_variable_ops.EagerResourceDeleter( + handle=accumulator_ref, handle_device=context.context().device_name) + + super(ConditionalAccumulator, self).__init__(dtype, shape, accumulator_ref) + + def apply_grad(self, grad, local_step=0, name=None): + """Attempts to apply a gradient to the accumulator. + + The attempt is silently dropped if the gradient is stale, i.e., local_step + is less than the accumulator's global time step. + + Args: + grad: The gradient tensor to be applied. + local_step: Time step at which the gradient was computed. + name: Optional name for the operation. + + Returns: + The operation that (conditionally) applies a gradient to the accumulator. + + Raises: + ValueError: If grad is of the wrong shape + """ + grad = ops.convert_to_tensor(grad, self._dtype) + grad.get_shape().assert_is_compatible_with(self._shape) + local_step = math_ops.cast(ops.convert_to_tensor(local_step), _dtypes.int64) + + return gen_data_flow_ops.resource_accumulator_apply_gradient( + self._accumulator_ref, local_step=local_step, gradient=grad, name=name) + + def take_grad(self, num_required, name=None): + """Attempts to extract the average gradient from the accumulator. + + The operation blocks until sufficient number of gradients have been + successfully applied to the accumulator. + + Once successful, the following actions are also triggered: + + - Counter of accumulated gradients is reset to 0. + - Aggregated gradient is reset to 0 tensor. + - Accumulator's internal time step is incremented by 1. + + Args: + num_required: Number of gradients that needs to have been aggregated + name: Optional name for the operation + + Returns: + A tensor holding the value of the average gradient. + + Raises: + InvalidArgumentError: If num_required < 1 + """ + out = gen_data_flow_ops.resource_accumulator_take_gradient( + self._accumulator_ref, num_required, dtype=self._dtype, name=name) + out.set_shape(self._shape) + return out + + +@tf_export( + v1=["sparse.SparseConditionalAccumulator", "SparseConditionalAccumulator"]) +class SparseConditionalAccumulator(ConditionalAccumulatorBase): + """A conditional accumulator for aggregating sparse gradients. + + Sparse gradients are represented by `IndexedSlices`. + + Up-to-date gradients (i.e., time step at which gradient was computed is + equal to the accumulator's time step) are added to the accumulator. + + Extraction of the average gradient is blocked until the required number of + gradients has been accumulated. + + Args: + dtype: Datatype of the accumulated gradients. + shape: Shape of the accumulated gradients. + shared_name: Optional. If non-empty, this accumulator will be shared under + the given name across multiple sessions. + name: Optional name for the accumulator. + reduction_type: Reduction type to use when taking the gradient. + """ + + def __init__(self, + dtype, + shape=None, + shared_name=None, + name="sparse_conditional_accumulator", + reduction_type="MEAN"): + accumulator_ref = gen_data_flow_ops.sparse_conditional_accumulator( + dtype=dtype, + shape=shape, + shared_name=shared_name, + name=name, + reduction_type=reduction_type) + super(SparseConditionalAccumulator, self).__init__(dtype, shape, + accumulator_ref) + + def apply_indexed_slices_grad(self, grad, local_step=0, name=None): + """Attempts to apply a gradient to the accumulator. + + The attempt is silently dropped if the gradient is stale, i.e., `local_step` + is less than the accumulator's global time step. + + Args: + grad: The gradient `IndexedSlices` to be applied. + local_step: Time step at which the gradient was computed. + name: Optional name for the operation. + + Returns: + The operation that (conditionally) applies a gradient to the accumulator. + + Raises: + InvalidArgumentError: If grad is of the wrong shape + """ + return self.apply_grad( + grad_indices=grad.indices, + grad_values=grad.values, + grad_shape=grad.dense_shape, + local_step=local_step, + name=name) + + def apply_grad(self, + grad_indices, + grad_values, + grad_shape=None, + local_step=0, + name=None): + """Attempts to apply a sparse gradient to the accumulator. + + The attempt is silently dropped if the gradient is stale, i.e., `local_step` + is less than the accumulator's global time step. + + A sparse gradient is represented by its indices, values and possibly empty + or None shape. Indices must be a vector representing the locations of + non-zero entries in the tensor. Values are the non-zero slices of the + gradient, and must have the same first dimension as indices, i.e., the nnz + represented by indices and values must be consistent. Shape, if not empty or + None, must be consistent with the accumulator's shape (if also provided). + + Example: + A tensor [[0, 0], [0, 1], [2, 3]] can be represented + indices: [1,2] + values: [[0,1],[2,3]] + shape: [3, 2] + + Args: + grad_indices: Indices of the sparse gradient to be applied. + grad_values: Values of the sparse gradient to be applied. + grad_shape: Shape of the sparse gradient to be applied. + local_step: Time step at which the gradient was computed. + name: Optional name for the operation. + + Returns: + The operation that (conditionally) applies a gradient to the accumulator. + + Raises: + InvalidArgumentError: If grad is of the wrong shape + """ + local_step = math_ops.cast(ops.convert_to_tensor(local_step), _dtypes.int64) + return gen_data_flow_ops.sparse_accumulator_apply_gradient( + self._accumulator_ref, + local_step=local_step, + gradient_indices=math_ops.cast(grad_indices, _dtypes.int64), + gradient_values=grad_values, + gradient_shape=math_ops.cast( + [] if grad_shape is None else grad_shape, _dtypes.int64), + has_known_shape=(grad_shape is not None), + name=name) + + def take_grad(self, num_required, name=None): + """Attempts to extract the average gradient from the accumulator. + + The operation blocks until sufficient number of gradients have been + successfully applied to the accumulator. + + Once successful, the following actions are also triggered: + - Counter of accumulated gradients is reset to 0. + - Aggregated gradient is reset to 0 tensor. + - Accumulator's internal time step is incremented by 1. + + Args: + num_required: Number of gradients that needs to have been aggregated + name: Optional name for the operation + + Returns: + A tuple of indices, values, and shape representing the average gradient. + + Raises: + InvalidArgumentError: If `num_required` < 1 + """ + return gen_data_flow_ops.sparse_accumulator_take_gradient( + self._accumulator_ref, num_required, dtype=self._dtype, name=name) + + def take_indexed_slices_grad(self, num_required, name=None): + """Attempts to extract the average gradient from the accumulator. + + The operation blocks until sufficient number of gradients have been + successfully applied to the accumulator. + + Once successful, the following actions are also triggered: + - Counter of accumulated gradients is reset to 0. + - Aggregated gradient is reset to 0 tensor. + - Accumulator's internal time step is incremented by 1. + + Args: + num_required: Number of gradients that needs to have been aggregated + name: Optional name for the operation + + Returns: + An `IndexedSlices` holding the value of the average gradient. + + Raises: + InvalidArgumentError: If `num_required` < 1 + """ + return_val = gen_data_flow_ops.sparse_accumulator_take_gradient( + self._accumulator_ref, num_required, dtype=self._dtype, name=name) + return indexed_slices.IndexedSlices( + indices=return_val.indices, + values=return_val.values, + dense_shape=return_val.shape) + + # SparseConditionalAccumulator is not switched to resource. Use old kernels. + def num_accumulated(self, name=None): + """Number of gradients that have currently been aggregated in accumulator. + + Args: + name: Optional name for the operation. + + Returns: + Number of accumulated gradients currently in accumulator. + """ + if name is None: + name = "%s_NumAccumulated" % self._name + + return gen_data_flow_ops.accumulator_num_accumulated( + self._accumulator_ref, name=name) + + def set_global_step(self, new_global_step, name=None): + """Sets the global time step of the accumulator. + + The operation logs a warning if we attempt to set to a time step that is + lower than the accumulator's own time step. + + Args: + new_global_step: Value of new time step. Can be a variable or a constant + name: Optional name for the operation. + + Returns: + Operation that sets the accumulator's time step. + """ + return gen_data_flow_ops.accumulator_set_global_step( + self._accumulator_ref, + math_ops.cast(ops.convert_to_tensor(new_global_step), _dtypes.int64), + name=name) + + +class BaseStagingArea: + """Base class for Staging Areas.""" + _identifier = 0 + _lock = threading.Lock() + + def __init__(self, + dtypes, + shapes=None, + names=None, + shared_name=None, + capacity=0, + memory_limit=0): + if shared_name is None: + self._name = ( + ops.get_default_graph().unique_name(self.__class__.__name__)) + elif isinstance(shared_name, str): + self._name = shared_name + else: + raise ValueError(f"shared_name must be a string, got {shared_name}") + + self._dtypes = dtypes + + if shapes is not None: + if len(shapes) != len(dtypes): + raise ValueError("StagingArea shapes must be the same length as dtypes") + self._shapes = [tensor_shape.TensorShape(s) for s in shapes] + else: + self._shapes = [tensor_shape.unknown_shape() for _ in self._dtypes] + + if names is not None: + if len(names) != len(dtypes): + raise ValueError("StagingArea names must be the same length as dtypes") + self._names = names + else: + self._names = None + + self._capacity = capacity + self._memory_limit = memory_limit + + # all get and put ops must colocate with this op + with ops.name_scope("%s_root" % self._name): + self._coloc_op = control_flow_ops.no_op() + + @property + def name(self): + """The name of the staging area.""" + return self._name + + @property + def dtypes(self): + """The list of dtypes for each component of a staging area element.""" + return self._dtypes + + @property + def shapes(self): + """The list of shapes for each component of a staging area element.""" + return self._shapes + + @property + def names(self): + """The list of names for each component of a staging area element.""" + return self._names + + @property + def capacity(self): + """The maximum number of elements of this staging area.""" + return self._capacity + + @property + def memory_limit(self): + """The maximum number of bytes of this staging area.""" + return self._memory_limit + + def _check_put_dtypes(self, vals, indices=None): + """Validate and convert `vals` to a list of `Tensor`s. + + The `vals` argument can be a Tensor, a list or tuple of tensors, or a + dictionary with tensor values. + + If `vals` is a list, then the appropriate indices associated with the + values must be provided. + + If it is a dictionary, the staging area must have been constructed with a + `names` attribute and the dictionary keys must match the staging area names. + `indices` will be inferred from the dictionary keys. + If the staging area was constructed with a `names` attribute, `vals` must + be a dictionary. + + Checks that the dtype and shape of each value matches that + of the staging area. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary. + + Returns: + A (tensors, indices) tuple where `tensors` is a list of `Tensor` objects + and `indices` is a list of indices associated with the tensors. + + Raises: + ValueError: If `vals` or `indices` is invalid. + """ + if isinstance(vals, dict): + if not self._names: + raise ValueError( + "Staging areas must have names to enqueue a dictionary") + if not set(vals.keys()).issubset(self._names): + raise ValueError("Keys in dictionary to put do not match names " + f"of staging area. Dictionary: {sorted(vals.keys())}" + f"Queue: {sorted(self._names)}") + # The order of values in `self._names` indicates the order in which the + # tensors in the dictionary `vals` must be listed. + vals, indices, _ = zip(*[(vals[k], i, k) + for i, k in enumerate(self._names) + if k in vals]) + else: + if self._names: + raise ValueError("You must enqueue a dictionary in a staging area " + "with names") + + if indices is None: + raise ValueError("Indices must be supplied when inserting a list " + "of tensors") + + if len(indices) != len(vals): + raise ValueError(f"Number of indices {len(indices)} doesn't match " + f"number of values {len(vals)}") + + if not isinstance(vals, (list, tuple)): + vals = [vals] + indices = [0] + + # Sanity check number of values + if not len(vals) <= len(self._dtypes): + raise ValueError(f"Unexpected number of inputs {len(vals)} vs " + f"{len(self._dtypes)}") + + tensors = [] + + for val, i in zip(vals, indices): + dtype, shape = self._dtypes[i], self._shapes[i] + # Check dtype + if val.dtype != dtype: + raise ValueError(f"Datatypes do not match. " + f"Received val.dtype {str(val.dtype)} and " + f"dtype {str(dtype)}") + # Check shape + val.get_shape().assert_is_compatible_with(shape) + + tensors.append( + ops.convert_to_tensor(val, dtype=dtype, name="component_%d" % i)) + + return tensors, indices + + def _create_device_transfers(self, tensors): + """Encode inter-device transfers if the current device + is not the same as the Staging Area's device. + """ + + if not isinstance(tensors, (tuple, list)): + tensors = [tensors] + + curr_device_scope = control_flow_ops.no_op().device + + if curr_device_scope != self._coloc_op.device: + tensors = [array_ops.identity(t) for t in tensors] + + return tensors + + def _get_return_value(self, tensors, indices): + """Return the value to return from a get op. + + If the staging area has names, return a dictionary with the + names as keys. Otherwise return either a single tensor + or a list of tensors depending on the length of `tensors`. + + Args: + tensors: List of tensors from the get op. + indices: Indices of associated names and shapes + + Returns: + A single tensor, a list of tensors, or a dictionary + of tensors. + """ + + tensors = self._create_device_transfers(tensors) + + # Sets shape + for output, i in zip(tensors, indices): + output.set_shape(self._shapes[i]) + + if self._names: + # The returned values in `tensors` are in the same order as + # the names in `self._names`. + return {self._names[i]: t for t, i in zip(tensors, indices)} + return tensors + + def _scope_vals(self, vals): + """Return a list of values to pass to `name_scope()`. + + Args: + vals: A tensor, a list or tuple of tensors, or a dictionary. + + Returns: + The values in vals as a list. + """ + if isinstance(vals, (list, tuple)): + return vals + elif isinstance(vals, dict): + return vals.values() + else: + return [vals] + + +class StagingArea(BaseStagingArea): + """Class for staging inputs. No ordering guarantees. + + A `StagingArea` is a TensorFlow data structure that stores tensors across + multiple steps, and exposes operations that can put and get tensors. + + Each `StagingArea` element is a tuple of one or more tensors, where each + tuple component has a static dtype, and may have a static shape. + + The capacity of a `StagingArea` may be bounded or unbounded. + It supports multiple concurrent producers and consumers; and + provides exactly-once delivery. + + Each element of a `StagingArea` is a fixed-length tuple of tensors whose + dtypes are described by `dtypes`, and whose shapes are optionally described + by the `shapes` argument. + + If the `shapes` argument is specified, each component of a staging area + element must have the respective fixed shape. If it is + unspecified, different elements may have different shapes, + + It can be configured with a capacity in which case + put(values) will block until space becomes available. + + Similarly, it can be configured with a memory limit which + will block put(values) until space is available. + This is mostly useful for limiting the number of tensors on + devices such as GPUs. + + All get() and peek() commands block if the requested data + is not present in the Staging Area. + + """ + + def __init__(self, + dtypes, + shapes=None, + names=None, + shared_name=None, + capacity=0, + memory_limit=0): + """Constructs a staging area object. + + The two optional lists, `shapes` and `names`, must be of the same length + as `dtypes` if provided. The values at a given index `i` indicate the + shape and name to use for the corresponding queue component in `dtypes`. + + The device scope at the time of object creation determines where the + storage for the `StagingArea` will reside. Calls to `put` will incur a copy + to this memory space, if necessary. Tensors returned by `get` will be + placed according to the device scope when `get` is called. + + Args: + dtypes: A list of types. The length of dtypes must equal the number + of tensors in each element. + shapes: (Optional.) Constraints on the shapes of tensors in an element. + A list of shape tuples or None. This list is the same length + as dtypes. If the shape of any tensors in the element are constrained, + all must be; shapes can be None if the shapes should not be constrained. + names: (Optional.) If provided, the `get()` and + `put()` methods will use dictionaries with these names as keys. + Must be None or a list or tuple of the same length as `dtypes`. + shared_name: (Optional.) A name to be used for the shared object. By + passing the same name to two different python objects they will share + the underlying staging area. Must be a string. + capacity: (Optional.) Maximum number of elements. + An integer. If zero, the Staging Area is unbounded + memory_limit: (Optional.) Maximum number of bytes of all tensors + in the Staging Area. + An integer. If zero, the Staging Area is unbounded + + Raises: + ValueError: If one of the arguments is invalid. + """ + + super(StagingArea, self).__init__(dtypes, shapes, names, shared_name, + capacity, memory_limit) + + def put(self, values, name=None): + """Create an op that places a value into the staging area. + + This operation will block if the `StagingArea` has reached + its capacity. + + Args: + values: A single tensor, a list or tuple of tensors, or a dictionary with + tensor values. The number of elements must match the length of the + list provided to the dtypes argument when creating the StagingArea. + name: A name for the operation (optional). + + Returns: + The created op. + + Raises: + ValueError: If the number or type of inputs don't match the staging area. + """ + with ops.name_scope(name, "%s_put" % self._name, + self._scope_vals(values)) as scope: + + if not isinstance(values, (list, tuple, dict)): + values = [values] + + # Hard-code indices for this staging area + indices = list(range(len(values))) + vals, _ = self._check_put_dtypes(values, indices) + + with ops.colocate_with(self._coloc_op): + op = gen_data_flow_ops.stage( + values=vals, + shared_name=self._name, + name=scope, + capacity=self._capacity, + memory_limit=self._memory_limit) + + return op + + def __internal_get(self, get_fn, name): + with ops.colocate_with(self._coloc_op): + ret = get_fn() + + indices = list(range(len(self._dtypes))) # Hard coded + return self._get_return_value(ret, indices) + + def get(self, name=None): + """Gets one element from this staging area. + + If the staging area is empty when this operation executes, it will block + until there is an element to dequeue. + + Note that unlike others ops that can block, like the queue Dequeue + operations, this can stop other work from happening. To avoid this, the + intended use is for this to be called only when there will be an element + already available. One method for doing this in a training loop would be to + run a `put()` call during a warmup session.run call, and then call both + `get()` and `put()` in each subsequent step. + + The placement of the returned tensor will be determined by the current + device scope when this function is called. + + Args: + name: A name for the operation (optional). + + Returns: + The tuple of tensors that was gotten. + """ + if name is None: + name = "%s_get" % self._name + + # pylint: disable=bad-continuation + fn = lambda: gen_data_flow_ops.unstage(dtypes=self._dtypes, + shared_name=self._name, name=name, + capacity=self._capacity, + memory_limit=self._memory_limit) + # pylint: enable=bad-continuation + + return self.__internal_get(fn, name) + + def peek(self, index, name=None): + """Peeks at an element in the staging area. + + If the staging area is too small to contain the element at + the specified index, it will block until enough elements + are inserted to complete the operation. + + The placement of the returned tensor will be determined by + the current device scope when this function is called. + + Args: + index: The index of the tensor within the staging area + to look up. + name: A name for the operation (optional). + + Returns: + The tuple of tensors that was gotten. + """ + if name is None: + name = "%s_peek" % self._name + + # pylint: disable=bad-continuation + fn = lambda: gen_data_flow_ops.stage_peek(index, + dtypes=self._dtypes, shared_name=self._name, + name=name, capacity=self._capacity, + memory_limit=self._memory_limit) + # pylint: enable=bad-continuation + + return self.__internal_get(fn, name) + + def size(self, name=None): + """Returns the number of elements in the staging area. + + Args: + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_size" % self._name + + return gen_data_flow_ops.stage_size( + name=name, + shared_name=self._name, + dtypes=self._dtypes, + capacity=self._capacity, + memory_limit=self._memory_limit) + + def clear(self, name=None): + """Clears the staging area. + + Args: + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_clear" % self._name + + return gen_data_flow_ops.stage_clear( + name=name, + shared_name=self._name, + dtypes=self._dtypes, + capacity=self._capacity, + memory_limit=self._memory_limit) + + +class MapStagingArea(BaseStagingArea): + """A `MapStagingArea` is a TensorFlow data structure that stores tensors + across multiple steps, and exposes operations that can put and get tensors. + + Each `MapStagingArea` element is a (key, value) pair. + Only int64 keys are supported, other types should be + hashed to produce a key. + Values are a tuple of one or more tensors. + Each tuple component has a static dtype, + and may have a static shape. + + The capacity of a `MapStagingArea` may be bounded or unbounded. + It supports multiple concurrent producers and consumers; and + provides exactly-once delivery. + + Each value tuple of a `MapStagingArea` is a fixed-length tuple of tensors + whose + dtypes are described by `dtypes`, and whose shapes are optionally described + by the `shapes` argument. + + If the `shapes` argument is specified, each component of a staging area + element must have the respective fixed shape. If it is + unspecified, different elements may have different shapes, + + It behaves like an associative container with support for: + + - put(key, values) + - peek(key) like dict.get(key) + - get(key) like dict.pop(key) + - get(key=None) like dict.popitem() + - size() + - clear() + + If ordered a tree structure ordered by key will be used and + get(key=None) will remove (key, value) pairs in increasing key order. + Otherwise a hashtable + + It can be configured with a capacity in which case + put(key, values) will block until space becomes available. + + Similarly, it can be configured with a memory limit which + will block put(key, values) until space is available. + This is mostly useful for limiting the number of tensors on + devices such as GPUs. + + All get() and peek() commands block if the requested + (key, value) pair is not present in the staging area. + + Partial puts are supported and will be placed in an incomplete + map until such time as all values associated with the key have + been inserted. Once completed, this (key, value) pair will be + inserted into the map. Data in the incomplete map + counts towards the memory limit, but not towards capacity limit. + + Partial gets from the map are also supported. + This removes the partially requested tensors from the entry, + but the entry is only removed from the map once all tensors + associated with it are removed. + """ + + def __init__(self, + dtypes, + shapes=None, + names=None, + shared_name=None, + ordered=False, + capacity=0, + memory_limit=0): + """Args: + + dtypes: A list of types. The length of dtypes must equal the number + of tensors in each element. + capacity: (Optional.) Maximum number of elements. + An integer. If zero, the Staging Area is unbounded + memory_limit: (Optional.) Maximum number of bytes of all tensors + in the Staging Area (excluding keys). + An integer. If zero, the Staging Area is unbounded + ordered: (Optional.) If True the underlying data structure + is a tree ordered on key. Otherwise assume a hashtable. + shapes: (Optional.) Constraints on the shapes of tensors in an element. + A list of shape tuples or None. This list is the same length + as dtypes. If the shape of any tensors in the element are constrained, + all must be; shapes can be None if the shapes should not be constrained. + names: (Optional.) If provided, the `get()` and + `put()` methods will use dictionaries with these names as keys. + Must be None or a list or tuple of the same length as `dtypes`. + shared_name: (Optional.) A name to be used for the shared object. By + passing the same name to two different python objects they will share + the underlying staging area. Must be a string. + + Raises: + ValueError: If one of the arguments is invalid. + + """ + + super(MapStagingArea, self).__init__(dtypes, shapes, names, shared_name, + capacity, memory_limit) + + # Defer to different methods depending if the map is ordered + self._ordered = ordered + + if ordered: + self._put_fn = gen_data_flow_ops.ordered_map_stage + self._pop_fn = gen_data_flow_ops.ordered_map_unstage + self._popitem_fn = gen_data_flow_ops.ordered_map_unstage_no_key + self._peek_fn = gen_data_flow_ops.ordered_map_peek + self._size_fn = gen_data_flow_ops.ordered_map_size + self._incomplete_size_fn = gen_data_flow_ops.ordered_map_incomplete_size + self._clear_fn = gen_data_flow_ops.ordered_map_clear + else: + self._put_fn = gen_data_flow_ops.map_stage + self._pop_fn = gen_data_flow_ops.map_unstage + self._popitem_fn = gen_data_flow_ops.map_unstage_no_key + self._peek_fn = gen_data_flow_ops.map_peek + self._size_fn = gen_data_flow_ops.map_size + self._incomplete_size_fn = gen_data_flow_ops.map_incomplete_size + self._clear_fn = gen_data_flow_ops.map_clear + + def put(self, key, vals, indices=None, name=None): + """Create an op that stores the (key, vals) pair in the staging area. + + Incomplete puts are possible, preferably using a dictionary for vals + as the appropriate dtypes and shapes can be inferred from the value names + dictionary key values. If vals is a list or tuple, indices must + also be specified so that the op knows at which element position + to perform the insert. + + This operation will block if the capacity or memory limit of this + container is reached. + + Args: + key: Key associated with the data + vals: Tensor (or a dict/tuple of Tensors) to place + into the staging area. + indices: (Optional) if vals is a tuple/list, this is required. + name: A name for the operation (optional) + + Returns: + The created op + + Raises: + ValueError: If the number or type of inputs don't match the staging + area. + """ + + with ops.name_scope(name, "%s_put" % self._name, + self._scope_vals(vals)) as scope: + + vals, indices = self._check_put_dtypes(vals, indices) + + with ops.colocate_with(self._coloc_op): + op = self._put_fn( + key, + indices, + vals, + dtypes=self._dtypes, + shared_name=self._name, + name=scope, + capacity=self._capacity, + memory_limit=self._memory_limit) + return op + + def _get_indices_and_dtypes(self, indices=None): + if indices is None: + indices = list(range(len(self._dtypes))) + + if not isinstance(indices, (tuple, list)): + raise TypeError(f"Invalid indices type {type(indices)}") + + if len(indices) == 0: + raise ValueError("Empty indices") + + if all(isinstance(i, str) for i in indices): + if self._names is None: + raise ValueError(f"String indices provided {indices}, but " + "this Staging Area was not created with names.") + + try: + indices = [self._names.index(n) for n in indices] + except ValueError: + raise ValueError(f"Named index not in " + f"Staging Area names {self._names}") + elif all(isinstance(i, int) for i in indices): + pass + else: + raise TypeError(f"Mixed types in indices {indices}. " + "May only be str or int") + + dtypes = [self._dtypes[i] for i in indices] + + return indices, dtypes + + def peek(self, key, indices=None, name=None): + """Peeks at staging area data associated with the key. + + If the key is not in the staging area, it will block + until the associated (key, value) is inserted. + + Args: + key: Key associated with the required data + indices: Partial list of tensors to retrieve (optional). + A list of integer or string indices. + String indices are only valid if the Staging Area + has names associated with it. + name: A name for the operation (optional) + + Returns: + The created op + """ + + if name is None: + name = "%s_pop" % self._name + + indices, dtypes = self._get_indices_and_dtypes(indices) + + with ops.colocate_with(self._coloc_op): + result = self._peek_fn( + key, + shared_name=self._name, + indices=indices, + dtypes=dtypes, + name=name, + capacity=self._capacity, + memory_limit=self._memory_limit) + + return self._get_return_value(result, indices) + + def get(self, key=None, indices=None, name=None): + """If the key is provided, the associated (key, value) is returned from the staging area. + + If the key is not in the staging area, this method will block until + the associated (key, value) is inserted. + If no key is provided and the staging area is ordered, + the (key, value) with the smallest key will be returned. + Otherwise, a random (key, value) will be returned. + + If the staging area is empty when this operation executes, + it will block until there is an element to dequeue. + + Args: + key: Key associated with the required data (Optional) + indices: Partial list of tensors to retrieve (optional). + A list of integer or string indices. + String indices are only valid if the Staging Area + has names associated with it. + name: A name for the operation (optional) + + Returns: + The created op + """ + if key is None: + return self._popitem(indices=indices, name=name) + else: + return self._pop(key, indices=indices, name=name) + + def _pop(self, key, indices=None, name=None): + """Remove and return the associated (key, value) is returned from the staging area. + + If the key is not in the staging area, this method will block until + the associated (key, value) is inserted. + Args: + key: Key associated with the required data + indices: Partial list of tensors to retrieve (optional). + A list of integer or string indices. + String indices are only valid if the Staging Area + has names associated with it. + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_get" % self._name + + indices, dtypes = self._get_indices_and_dtypes(indices) + + with ops.colocate_with(self._coloc_op): + result = self._pop_fn( + key, + shared_name=self._name, + indices=indices, + dtypes=dtypes, + name=name, + capacity=self._capacity, + memory_limit=self._memory_limit) + + return key, self._get_return_value(result, indices) + + def _popitem(self, indices=None, name=None): + """If the staging area is ordered, the (key, value) with the smallest key will be returned. + + Otherwise, a random (key, value) will be returned. + If the staging area is empty when this operation executes, + it will block until there is an element to dequeue. + + Args: + key: Key associated with the required data + indices: Partial list of tensors to retrieve (optional). + A list of integer or string indices. + String indices are only valid if the Staging Area + has names associated with it. + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_get_nokey" % self._name + + indices, dtypes = self._get_indices_and_dtypes(indices) + + with ops.colocate_with(self._coloc_op): + key, result = self._popitem_fn( + shared_name=self._name, + indices=indices, + dtypes=dtypes, + name=name, + capacity=self._capacity, + memory_limit=self._memory_limit) + + # Separate keys and results out from + # underlying namedtuple + key = self._create_device_transfers(key)[0] + result = self._get_return_value(result, indices) + + return key, result + + def size(self, name=None): + """Returns the number of elements in the staging area. + + Args: + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_size" % self._name + + return self._size_fn( + shared_name=self._name, + name=name, + dtypes=self._dtypes, + capacity=self._capacity, + memory_limit=self._memory_limit) + + def incomplete_size(self, name=None): + """Returns the number of incomplete elements in the staging area. + + Args: + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_incomplete_size" % self._name + + return self._incomplete_size_fn( + shared_name=self._name, + name=name, + dtypes=self._dtypes, + capacity=self._capacity, + memory_limit=self._memory_limit) + + def clear(self, name=None): + """Clears the staging area. + + Args: + name: A name for the operation (optional) + + Returns: + The created op + """ + if name is None: + name = "%s_clear" % self._name + + return self._clear_fn( + shared_name=self._name, + name=name, + dtypes=self._dtypes, + capacity=self._capacity, + memory_limit=self._memory_limit) + + +class RecordInput: + """RecordInput asynchronously reads and randomly yields TFRecords. + + A RecordInput Op will continuously read a batch of records asynchronously + into a buffer of some fixed capacity. It can also asynchronously yield + random records from this buffer. + + It will not start yielding until at least `buffer_size / 2` elements have been + placed into the buffer so that sufficient randomization can take place. + + The order the files are read will be shifted each epoch by `shift_amount` so + that the data is presented in a different order every epoch. + """ + + def __init__(self, + file_pattern, + batch_size=1, + buffer_size=1, + parallelism=1, + shift_ratio=0, + seed=0, + name=None, + batches=None, + compression_type=None): + """Constructs a RecordInput Op. + + Args: + file_pattern: File path to the dataset, possibly containing wildcards. + All matching files will be iterated over each epoch. + batch_size: How many records to return at a time. + buffer_size: The maximum number of records the buffer will contain. + parallelism: How many reader threads to use for reading from files. + shift_ratio: What percentage of the total number files to move the start + file forward by each epoch. + seed: Specify the random number seed used by generator that randomizes + records. + name: Optional name for the operation. + batches: None by default, creating a single batch op. Otherwise specifies + how many batches to create, which are returned as a list when + `get_yield_op()` is called. An example use case is to split processing + between devices on one computer. + compression_type: The type of compression for the file. Currently ZLIB and + GZIP are supported. Defaults to none. + + Raises: + ValueError: If one of the arguments is invalid. + """ + self._batch_size = batch_size + if batches is not None: + self._batch_size *= batches + self._batches = batches + self._file_pattern = file_pattern + self._buffer_size = buffer_size + self._parallelism = parallelism + self._shift_ratio = shift_ratio + self._seed = seed + self._name = name + self._compression_type = python_io.TFRecordCompressionType.NONE + if compression_type is not None: + self._compression_type = compression_type + + def get_yield_op(self): + """Adds a node that yields a group of records every time it is executed. + If RecordInput `batches` parameter is not None, it yields a list of + record batches with the specified `batch_size`. + """ + compression_type = python_io.TFRecordOptions.get_compression_type_string( + python_io.TFRecordOptions(self._compression_type)) + records = gen_data_flow_ops.record_input( + file_pattern=self._file_pattern, + file_buffer_size=self._buffer_size, + file_parallelism=self._parallelism, + file_shuffle_shift_ratio=self._shift_ratio, + batch_size=self._batch_size, + file_random_seed=self._seed, + compression_type=compression_type, + name=self._name) + if self._batches is None: + return records + else: + with ops.name_scope(self._name): + batch_list = [[] for _ in range(self._batches)] + records = array_ops.split(records, self._batch_size, 0) + for index, protobuf in enumerate(records): + batch_index = index % self._batches + batch_list[batch_index].append(array_ops.reshape(protobuf, [])) + return batch_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/default_gradient.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/default_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae3219578feb69242896ec52938a9315a8beaa7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/default_gradient.py @@ -0,0 +1,80 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for computing default gradients.""" +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops + + +def get_zeros_dtype(t): + """Return the dtype for the default gradient for a Tensor.""" + if t.dtype == dtypes.resource: + handle_data = resource_variable_ops.get_eager_safe_handle_data(t) + if (handle_data is None or not handle_data.is_set or + len(handle_data.shape_and_type) != 1): + raise ValueError("Internal error: Tried to take gradients (or similar) " + "of a variable without handle data:\n%s" % str(t)) + return handle_data.shape_and_type[0].dtype + return t.dtype + + +def shape_and_dtype(t): + """Return the shape and dtype for the default gradient for a Tensor.""" + if t.dtype == dtypes.resource: + handle_data = resource_variable_ops.get_eager_safe_handle_data(t) + if (handle_data is None or not handle_data.is_set or + len(handle_data.shape_and_type) != 1): + raise ValueError("Internal error: Tried to take gradients (or similar) " + "of a variable without handle data:\n%s" % str(t)) + shape_and_type = handle_data.shape_and_type[0] + return (tensor_shape.TensorShape(shape_and_type.shape), + dtypes.as_dtype(shape_and_type.dtype)) + return t.shape, t.dtype + + +def zeros_like(t): + """Like array_ops.zeros_like, but respects resource handles.""" + if t.dtype == dtypes.resource: + return array_ops.zeros(*shape_and_dtype(t)) + else: + return array_ops.zeros_like(t) + + +def ones_like(t): + """Like array_ops.ones_like, but respects resource handles.""" + if t.dtype == dtypes.resource: + return array_ops.ones(*shape_and_dtype(t)) + else: + return array_ops.ones_like(t) + + +def supports_default_grad(t): + """Whether tensor `t` supports creating a default gradient. + + This function assumes that `t` is of a trainable type. + + Args: + t: Tensor + + Returns: + Bool + """ + if t.dtype == dtypes.resource: + handle_data = resource_variable_ops.get_eager_safe_handle_data(t) + if (handle_data is None or not handle_data.is_set or + len(handle_data.shape_and_type) != 1): + return False + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8365f2485eeb95eec0512770d1c747fcf367582d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Core module for TensorFlow distribution objects and helpers.""" +from tensorflow.python.ops.distributions import distributions diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bernoulli.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bernoulli.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5d875c8cf285f25071edf175b4ecfe1d8f5baa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bernoulli.py @@ -0,0 +1,183 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Bernoulli distribution class.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["distributions.Bernoulli"]) +class Bernoulli(distribution.Distribution): + """Bernoulli distribution. + + The Bernoulli distribution with `probs` parameter, i.e., the probability of a + `1` outcome (vs a `0` outcome). + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + logits=None, + probs=None, + dtype=dtypes.int32, + validate_args=False, + allow_nan_stats=True, + name="Bernoulli"): + """Construct Bernoulli distributions. + + Args: + logits: An N-D `Tensor` representing the log-odds of a `1` event. Each + entry in the `Tensor` parametrizes an independent Bernoulli distribution + where the probability of an event is sigmoid(logits). Only one of + `logits` or `probs` should be passed in. + probs: An N-D `Tensor` representing the probability of a `1` + event. Each entry in the `Tensor` parameterizes an independent + Bernoulli distribution. Only one of `logits` or `probs` should be passed + in. + dtype: The type of the event samples. Default: `int32`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + ValueError: If p and logits are passed, or if neither are passed. + """ + parameters = dict(locals()) + with ops.name_scope(name) as name: + self._logits, self._probs = distribution_util.get_logits_and_probs( + logits=logits, + probs=probs, + validate_args=validate_args, + name=name) + super(Bernoulli, self).__init__( + dtype=dtype, + reparameterization_type=distribution.NOT_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._logits, self._probs], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return {"logits": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} + + @property + def logits(self): + """Log-odds of a `1` outcome (vs `0`).""" + return self._logits + + @property + def probs(self): + """Probability of a `1` outcome (vs `0`).""" + return self._probs + + def _batch_shape_tensor(self): + return array_ops.shape(self._logits) + + def _batch_shape(self): + return self._logits.get_shape() + + def _event_shape_tensor(self): + return array_ops.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + new_shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + uniform = random_ops.random_uniform( + new_shape, seed=seed, dtype=self.probs.dtype) + sample = math_ops.less(uniform, self.probs) + return math_ops.cast(sample, self.dtype) + + def _log_prob(self, event): + if self.validate_args: + event = distribution_util.embed_check_integer_casting_closed( + event, target_dtype=dtypes.bool) + + # TODO(jaana): The current sigmoid_cross_entropy_with_logits has + # inconsistent behavior for logits = inf/-inf. + event = math_ops.cast(event, self.logits.dtype) + logits = self.logits + # sigmoid_cross_entropy_with_logits doesn't broadcast shape, + # so we do this here. + + def _broadcast(logits, event): + return (array_ops.ones_like(event) * logits, + array_ops.ones_like(logits) * event) + + if not (event.get_shape().is_fully_defined() and + logits.get_shape().is_fully_defined() and + event.get_shape() == logits.get_shape()): + logits, event = _broadcast(logits, event) + return -nn.sigmoid_cross_entropy_with_logits(labels=event, logits=logits) + + def _entropy(self): + return (-self.logits * (math_ops.sigmoid(self.logits) - 1) + # pylint: disable=invalid-unary-operand-type + nn.softplus(-self.logits)) # pylint: disable=invalid-unary-operand-type + + def _mean(self): + return array_ops.identity(self.probs) + + def _variance(self): + return self._mean() * (1. - self.probs) + + def _mode(self): + """Returns `1` if `prob > 0.5` and `0` otherwise.""" + return math_ops.cast(self.probs > 0.5, self.dtype) + + +@kullback_leibler.RegisterKL(Bernoulli, Bernoulli) +def _kl_bernoulli_bernoulli(a, b, name=None): + """Calculate the batched KL divergence KL(a || b) with a and b Bernoulli. + + Args: + a: instance of a Bernoulli distribution object. + b: instance of a Bernoulli distribution object. + name: (optional) Name to use for created operations. + default is "kl_bernoulli_bernoulli". + + Returns: + Batchwise KL(a || b) + """ + with ops.name_scope(name, "kl_bernoulli_bernoulli", + values=[a.logits, b.logits]): + delta_probs0 = nn.softplus(-b.logits) - nn.softplus(-a.logits) + delta_probs1 = nn.softplus(b.logits) - nn.softplus(a.logits) + return (math_ops.sigmoid(a.logits) * delta_probs0 + + math_ops.sigmoid(-a.logits) * delta_probs1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/beta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/beta.py new file mode 100644 index 0000000000000000000000000000000000000000..ce89d662cb7792a6a81712f62e687e0a7fcba093 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/beta.py @@ -0,0 +1,407 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Beta distribution class.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Beta", + "BetaWithSoftplusConcentration", +] + + +_beta_sample_note = """Note: `x` must have dtype `self.dtype` and be in +`[0, 1].` It must have a shape compatible with `self.batch_shape()`.""" + + +@tf_export(v1=["distributions.Beta"]) +class Beta(distribution.Distribution): + """Beta distribution. + + The Beta distribution is defined over the `(0, 1)` interval using parameters + `concentration1` (aka "alpha") and `concentration0` (aka "beta"). + + #### Mathematical Details + + The probability density function (pdf) is, + + ```none + pdf(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z + Z = Gamma(alpha) Gamma(beta) / Gamma(alpha + beta) + ``` + + where: + + * `concentration1 = alpha`, + * `concentration0 = beta`, + * `Z` is the normalization constant, and, + * `Gamma` is the [gamma function]( + https://en.wikipedia.org/wiki/Gamma_function). + + The concentration parameters represent mean total counts of a `1` or a `0`, + i.e., + + ```none + concentration1 = alpha = mean * total_concentration + concentration0 = beta = (1. - mean) * total_concentration + ``` + + where `mean` in `(0, 1)` and `total_concentration` is a positive real number + representing a mean `total_count = concentration1 + concentration0`. + + Distribution parameters are automatically broadcast in all functions; see + examples for details. + + Warning: The samples can be zero due to finite precision. + This happens more often when some of the concentrations are very small. + Make sure to round the samples to `np.finfo(dtype).tiny` before computing the + density. + + Samples of this distribution are reparameterized (pathwise differentiable). + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + #### Examples + + ```python + import tensorflow_probability as tfp + tfd = tfp.distributions + + # Create a batch of three Beta distributions. + alpha = [1, 2, 3] + beta = [1, 2, 3] + dist = tfd.Beta(alpha, beta) + + dist.sample([4, 5]) # Shape [4, 5, 3] + + # `x` has three batch entries, each with two samples. + x = [[.1, .4, .5], + [.2, .3, .5]] + # Calculate the probability of each pair of samples under the corresponding + # distribution in `dist`. + dist.prob(x) # Shape [2, 3] + ``` + + ```python + # Create batch_shape=[2, 3] via parameter broadcast: + alpha = [[1.], [2]] # Shape [2, 1] + beta = [3., 4, 5] # Shape [3] + dist = tfd.Beta(alpha, beta) + + # alpha broadcast as: [[1., 1, 1,], + # [2, 2, 2]] + # beta broadcast as: [[3., 4, 5], + # [3, 4, 5]] + # batch_Shape [2, 3] + dist.sample([4, 5]) # Shape [4, 5, 2, 3] + + x = [.2, .3, .5] + # x will be broadcast as [[.2, .3, .5], + # [.2, .3, .5]], + # thus matching batch_shape [2, 3]. + dist.prob(x) # Shape [2, 3] + ``` + + Compute the gradients of samples w.r.t. the parameters: + + ```python + alpha = tf.constant(1.0) + beta = tf.constant(2.0) + dist = tfd.Beta(alpha, beta) + samples = dist.sample(5) # Shape [5] + loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function + # Unbiased stochastic gradients of the loss function + grads = tf.gradients(loss, [alpha, beta]) + ``` + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + concentration1=None, + concentration0=None, + validate_args=False, + allow_nan_stats=True, + name="Beta"): + """Initialize a batch of Beta distributions. + + Args: + concentration1: Positive floating-point `Tensor` indicating mean + number of successes; aka "alpha". Implies `self.dtype` and + `self.batch_shape`, i.e., + `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. + concentration0: Positive floating-point `Tensor` indicating mean + number of failures; aka "beta". Otherwise has same semantics as + `concentration1`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[concentration1, concentration0]) as name: + self._concentration1 = self._maybe_assert_valid_concentration( + ops.convert_to_tensor(concentration1, name="concentration1"), + validate_args) + self._concentration0 = self._maybe_assert_valid_concentration( + ops.convert_to_tensor(concentration0, name="concentration0"), + validate_args) + check_ops.assert_same_float_dtype([ + self._concentration1, self._concentration0]) + self._total_concentration = self._concentration1 + self._concentration0 + super(Beta, self).__init__( + dtype=self._total_concentration.dtype, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + parameters=parameters, + graph_parents=[self._concentration1, + self._concentration0, + self._total_concentration], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict(zip( + ["concentration1", "concentration0"], + [ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)] * 2)) + + @property + def concentration1(self): + """Concentration parameter associated with a `1` outcome.""" + return self._concentration1 + + @property + def concentration0(self): + """Concentration parameter associated with a `0` outcome.""" + return self._concentration0 + + @property + def total_concentration(self): + """Sum of concentration parameters.""" + return self._total_concentration + + def _batch_shape_tensor(self): + return array_ops.shape(self.total_concentration) + + def _batch_shape(self): + return self.total_concentration.get_shape() + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + expanded_concentration1 = array_ops.ones_like( + self.total_concentration, dtype=self.dtype) * self.concentration1 + expanded_concentration0 = array_ops.ones_like( + self.total_concentration, dtype=self.dtype) * self.concentration0 + gamma1_sample = random_ops.random_gamma( + shape=[n], + alpha=expanded_concentration1, + dtype=self.dtype, + seed=seed) + gamma2_sample = random_ops.random_gamma( + shape=[n], + alpha=expanded_concentration0, + dtype=self.dtype, + seed=distribution_util.gen_new_seed(seed, "beta")) + beta_sample = gamma1_sample / (gamma1_sample + gamma2_sample) + return beta_sample + + @distribution_util.AppendDocstring(_beta_sample_note) + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + @distribution_util.AppendDocstring(_beta_sample_note) + def _prob(self, x): + return math_ops.exp(self._log_prob(x)) + + @distribution_util.AppendDocstring(_beta_sample_note) + def _log_cdf(self, x): + return math_ops.log(self._cdf(x)) + + @distribution_util.AppendDocstring(_beta_sample_note) + def _cdf(self, x): + return math_ops.betainc(self.concentration1, self.concentration0, x) + + def _log_unnormalized_prob(self, x): + x = self._maybe_assert_valid_sample(x) + return (math_ops.xlogy(self.concentration1 - 1., x) + + (self.concentration0 - 1.) * math_ops.log1p(-x)) # pylint: disable=invalid-unary-operand-type + + def _log_normalization(self): + return (math_ops.lgamma(self.concentration1) + + math_ops.lgamma(self.concentration0) + - math_ops.lgamma(self.total_concentration)) + + def _entropy(self): + return ( + self._log_normalization() + - (self.concentration1 - 1.) * math_ops.digamma(self.concentration1) + - (self.concentration0 - 1.) * math_ops.digamma(self.concentration0) + + ((self.total_concentration - 2.) * + math_ops.digamma(self.total_concentration))) + + def _mean(self): + return self._concentration1 / self._total_concentration + + def _variance(self): + return self._mean() * (1. - self._mean()) / (1. + self.total_concentration) + + @distribution_util.AppendDocstring( + """Note: The mode is undefined when `concentration1 <= 1` or + `concentration0 <= 1`. If `self.allow_nan_stats` is `True`, `NaN` + is used for undefined modes. If `self.allow_nan_stats` is `False` an + exception is raised when one or more modes are undefined.""") + def _mode(self): + mode = (self.concentration1 - 1.) / (self.total_concentration - 2.) + if self.allow_nan_stats: + nan = array_ops.fill( + self.batch_shape_tensor(), + np.array(np.nan, dtype=self.dtype.as_numpy_dtype()), + name="nan") + is_defined = math_ops.logical_and(self.concentration1 > 1., + self.concentration0 > 1.) + return array_ops.where_v2(is_defined, mode, nan) + return control_flow_ops.with_dependencies([ + check_ops.assert_less( + array_ops.ones([], dtype=self.dtype), + self.concentration1, + message="Mode undefined for concentration1 <= 1."), + check_ops.assert_less( + array_ops.ones([], dtype=self.dtype), + self.concentration0, + message="Mode undefined for concentration0 <= 1.") + ], mode) + + def _maybe_assert_valid_concentration(self, concentration, validate_args): + """Checks the validity of a concentration parameter.""" + if not validate_args: + return concentration + return control_flow_ops.with_dependencies([ + check_ops.assert_positive( + concentration, + message="Concentration parameter must be positive."), + ], concentration) + + def _maybe_assert_valid_sample(self, x): + """Checks the validity of a sample.""" + if not self.validate_args: + return x + return control_flow_ops.with_dependencies([ + check_ops.assert_positive(x, message="sample must be positive"), + check_ops.assert_less( + x, + array_ops.ones([], self.dtype), + message="sample must be less than `1`."), + ], x) + + +class BetaWithSoftplusConcentration(Beta): + """Beta with softplus transform of `concentration1` and `concentration0`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.Beta(tf.nn.softplus(concentration1), " + "tf.nn.softplus(concentration2))` instead.", + warn_once=True) + def __init__(self, + concentration1, + concentration0, + validate_args=False, + allow_nan_stats=True, + name="BetaWithSoftplusConcentration"): + parameters = dict(locals()) + with ops.name_scope(name, values=[concentration1, + concentration0]) as name: + super(BetaWithSoftplusConcentration, self).__init__( + concentration1=nn.softplus(concentration1, + name="softplus_concentration1"), + concentration0=nn.softplus(concentration0, + name="softplus_concentration0"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters + + +@kullback_leibler.RegisterKL(Beta, Beta) +def _kl_beta_beta(d1, d2, name=None): + """Calculate the batchwise KL divergence KL(d1 || d2) with d1 and d2 Beta. + + Args: + d1: instance of a Beta distribution object. + d2: instance of a Beta distribution object. + name: (optional) Name to use for created operations. + default is "kl_beta_beta". + + Returns: + Batchwise KL(d1 || d2) + """ + def delta(fn, is_property=True): + fn1 = getattr(d1, fn) + fn2 = getattr(d2, fn) + return (fn2 - fn1) if is_property else (fn2() - fn1()) + with ops.name_scope(name, "kl_beta_beta", values=[ + d1.concentration1, + d1.concentration0, + d1.total_concentration, + d2.concentration1, + d2.concentration0, + d2.total_concentration, + ]): + return (delta("_log_normalization", is_property=False) + - math_ops.digamma(d1.concentration1) * delta("concentration1") + - math_ops.digamma(d1.concentration0) * delta("concentration0") + + (math_ops.digamma(d1.total_concentration) + * delta("total_concentration"))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf3dde499db2678923bd9b0e85ed7299de295f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector.py @@ -0,0 +1,21 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Bijector base.""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import,unused-import +from tensorflow.python.ops.distributions.bijector_impl import Bijector + +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..99d7a5ab106578b3ea653fbbeec23c10e40ad292 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_impl.py @@ -0,0 +1,1113 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Bijector base.""" + +import abc +import collections +import contextlib +import re + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import object_identity + + +__all__ = [ + "Bijector", +] + + +class _Mapping(collections.namedtuple( + "_Mapping", ["x", "y", "ildj_map", "kwargs"])): + """Helper class to make it easier to manage caching in `Bijector`.""" + + def __new__(cls, x=None, y=None, ildj_map=None, kwargs=None): + """Custom __new__ so namedtuple items have defaults. + + Args: + x: `Tensor`. Forward. + y: `Tensor`. Inverse. + ildj_map: `Dictionary`. This is a mapping from event_ndims to a `Tensor` + representing the inverse log det jacobian. + kwargs: Python dictionary. Extra args supplied to + forward/inverse/etc functions. + + Returns: + mapping: New instance of _Mapping. + """ + return super(_Mapping, cls).__new__(cls, x, y, ildj_map, kwargs) + + @property + def x_key(self): + """Returns key used for caching Y=g(X).""" + return ((object_identity.Reference(self.x),) + + self._deep_tuple(tuple(sorted(self.kwargs.items())))) + + @property + def y_key(self): + """Returns key used for caching X=g^{-1}(Y).""" + return ((object_identity.Reference(self.y),) + + self._deep_tuple(tuple(sorted(self.kwargs.items())))) + + def merge(self, x=None, y=None, ildj_map=None, kwargs=None, mapping=None): + """Returns new _Mapping with args merged with self. + + Args: + x: `Tensor`. Forward. + y: `Tensor`. Inverse. + ildj_map: `Dictionary`. This is a mapping from event_ndims to a `Tensor` + representing the inverse log det jacobian. + kwargs: Python dictionary. Extra args supplied to + forward/inverse/etc functions. + mapping: Instance of _Mapping to merge. Can only be specified if no other + arg is specified. + + Returns: + mapping: New instance of `_Mapping` which has inputs merged with self. + + Raises: + ValueError: if mapping and any other arg is not `None`. + """ + if mapping is None: + mapping = _Mapping(x=x, y=y, ildj_map=ildj_map, kwargs=kwargs) + elif any(arg is not None for arg in [x, y, ildj_map, kwargs]): + raise ValueError("Cannot simultaneously specify mapping and individual " + "arguments.") + + return _Mapping( + x=self._merge(self.x, mapping.x), + y=self._merge(self.y, mapping.y), + ildj_map=self._merge_dicts(self.ildj_map, mapping.ildj_map), + kwargs=self._merge(self.kwargs, mapping.kwargs)) + + def _merge_dicts(self, old=None, new=None): + """Helper to merge two dictionaries.""" + old = {} if old is None else old + new = {} if new is None else new + for k, v in new.items(): + val = old.get(k, None) + if val is not None and val is not v: + raise ValueError("Found different value for existing key " + "(key:{} old_value:{} new_value:{}".format( + k, old[k], v)) + old[k] = v + return old + + def _merge(self, old, new): + """Helper to merge which handles merging one value.""" + if old is None: + return new + elif new is not None and old is not new: + raise ValueError("Incompatible values: %s != %s" % (old, new)) + return old + + def _deep_tuple(self, x): + """Converts lists of lists to tuples of tuples.""" + return (tuple(map(self._deep_tuple, x)) + if isinstance(x, (list, tuple)) else x) + + +class Bijector(metaclass=abc.ABCMeta): + r"""Interface for transformations of a `Distribution` sample. + + Bijectors can be used to represent any differentiable and injective + (one to one) function defined on an open subset of `R^n`. Some non-injective + transformations are also supported (see "Non Injective Transforms" below). + + #### Mathematical Details + + A `Bijector` implements a [smooth covering map]( + https://en.wikipedia.org/wiki/Local_diffeomorphism), i.e., a local + diffeomorphism such that every point in the target has a neighborhood evenly + covered by a map ([see also]( + https://en.wikipedia.org/wiki/Covering_space#Covering_of_a_manifold)). + A `Bijector` is used by `TransformedDistribution` but can be generally used + for transforming a `Distribution` generated `Tensor`. A `Bijector` is + characterized by three operations: + + 1. Forward + + Useful for turning one random outcome into another random outcome from a + different distribution. + + 2. Inverse + + Useful for "reversing" a transformation to compute one probability in + terms of another. + + 3. `log_det_jacobian(x)` + + "The log of the absolute value of the determinant of the matrix of all + first-order partial derivatives of the inverse function." + + Useful for inverting a transformation to compute one probability in terms + of another. Geometrically, the Jacobian determinant is the volume of the + transformation and is used to scale the probability. + + We take the absolute value of the determinant before log to avoid NaN + values. Geometrically, a negative determinant corresponds to an + orientation-reversing transformation. It is ok for us to discard the sign + of the determinant because we only integrate everywhere-nonnegative + functions (probability densities) and the correct orientation is always the + one that produces a nonnegative integrand. + + By convention, transformations of random variables are named in terms of the + forward transformation. The forward transformation creates samples, the + inverse is useful for computing probabilities. + + #### Example Uses + + - Basic properties: + + ```python + x = ... # A tensor. + # Evaluate forward transformation. + fwd_x = my_bijector.forward(x) + x == my_bijector.inverse(fwd_x) + x != my_bijector.forward(fwd_x) # Not equal because x != g(g(x)). + ``` + + - Computing a log-likelihood: + + ```python + def transformed_log_prob(bijector, log_prob, x): + return (bijector.inverse_log_det_jacobian(x, event_ndims=0) + + log_prob(bijector.inverse(x))) + ``` + + - Transforming a random outcome: + + ```python + def transformed_sample(bijector, x): + return bijector.forward(x) + ``` + + #### Example Bijectors + + - "Exponential" + + ```none + Y = g(X) = exp(X) + X ~ Normal(0, 1) # Univariate. + ``` + + Implies: + + ```none + g^{-1}(Y) = log(Y) + |Jacobian(g^{-1})(y)| = 1 / y + Y ~ LogNormal(0, 1), i.e., + prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y)) + = (1 / y) Normal(log(y); 0, 1) + ``` + + Here is an example of how one might implement the `Exp` bijector: + + ```python + class Exp(Bijector): + + def __init__(self, validate_args=False, name="exp"): + super(Exp, self).__init__( + validate_args=validate_args, + forward_min_event_ndims=0, + name=name) + + def _forward(self, x): + return math_ops.exp(x) + + def _inverse(self, y): + return math_ops.log(y) + + def _inverse_log_det_jacobian(self, y): + return -self._forward_log_det_jacobian(self._inverse(y)) + + def _forward_log_det_jacobian(self, x): + # Notice that we needn't do any reducing, even when`event_ndims > 0`. + # The base Bijector class will handle reducing for us; it knows how + # to do so because we called `super` `__init__` with + # `forward_min_event_ndims = 0`. + return x + ``` + + - "Affine" + + ```none + Y = g(X) = sqrtSigma * X + mu + X ~ MultivariateNormal(0, I_d) + ``` + + Implies: + + ```none + g^{-1}(Y) = inv(sqrtSigma) * (Y - mu) + |Jacobian(g^{-1})(y)| = det(inv(sqrtSigma)) + Y ~ MultivariateNormal(mu, sqrtSigma) , i.e., + prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y)) + = det(sqrtSigma)^(-d) * + MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d) + ``` + + #### Min_event_ndims and Naming + + Bijectors are named for the dimensionality of data they act on (i.e. without + broadcasting). We can think of bijectors having an intrinsic `min_event_ndims` + , which is the minimum number of dimensions for the bijector act on. For + instance, a Cholesky decomposition requires a matrix, and hence + `min_event_ndims=2`. + + Some examples: + + `AffineScalar: min_event_ndims=0` + `Affine: min_event_ndims=1` + `Cholesky: min_event_ndims=2` + `Exp: min_event_ndims=0` + `Sigmoid: min_event_ndims=0` + `SoftmaxCentered: min_event_ndims=1` + + Note the difference between `Affine` and `AffineScalar`. `AffineScalar` + operates on scalar events, whereas `Affine` operates on vector-valued events. + + More generally, there is a `forward_min_event_ndims` and an + `inverse_min_event_ndims`. In most cases, these will be the same. + However, for some shape changing bijectors, these will be different + (e.g. a bijector which pads an extra dimension at the end, might have + `forward_min_event_ndims=0` and `inverse_min_event_ndims=1`. + + + #### Jacobian Determinant + + The Jacobian determinant is a reduction over `event_ndims - min_event_ndims` + (`forward_min_event_ndims` for `forward_log_det_jacobian` and + `inverse_min_event_ndims` for `inverse_log_det_jacobian`). + To see this, consider the `Exp` `Bijector` applied to a `Tensor` which has + sample, batch, and event (S, B, E) shape semantics. Suppose the `Tensor`'s + partitioned-shape is `(S=[4], B=[2], E=[3, 3])`. The shape of the `Tensor` + returned by `forward` and `inverse` is unchanged, i.e., `[4, 2, 3, 3]`. + However the shape returned by `inverse_log_det_jacobian` is `[4, 2]` because + the Jacobian determinant is a reduction over the event dimensions. + + Another example is the `Affine` `Bijector`. Because `min_event_ndims = 1`, the + Jacobian determinant reduction is over `event_ndims - 1`. + + It is sometimes useful to implement the inverse Jacobian determinant as the + negative forward Jacobian determinant. For example, + + ```python + def _inverse_log_det_jacobian(self, y): + return -self._forward_log_det_jac(self._inverse(y)) # Note negation. + ``` + + The correctness of this approach can be seen from the following claim. + + - Claim: + + Assume `Y = g(X)` is a bijection whose derivative exists and is nonzero + for its domain, i.e., `dY/dX = d/dX g(X) != 0`. Then: + + ```none + (log o det o jacobian o g^{-1})(Y) = -(log o det o jacobian o g)(X) + ``` + + - Proof: + + From the bijective, nonzero differentiability of `g`, the + [inverse function theorem]( + https://en.wikipedia.org/wiki/Inverse_function_theorem) + implies `g^{-1}` is differentiable in the image of `g`. + Applying the chain rule to `y = g(x) = g(g^{-1}(y))` yields + `I = g'(g^{-1}(y))*g^{-1}'(y)`. + The same theorem also implies `g^{-1}'` is non-singular therefore: + `inv[ g'(g^{-1}(y)) ] = g^{-1}'(y)`. + The claim follows from [properties of determinant]( + https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups). + + Generally its preferable to directly implement the inverse Jacobian + determinant. This should have superior numerical stability and will often + share subgraphs with the `_inverse` implementation. + + #### Is_constant_jacobian + + Certain bijectors will have constant jacobian matrices. For instance, the + `Affine` bijector encodes multiplication by a matrix plus a shift, with + jacobian matrix, the same aforementioned matrix. + + `is_constant_jacobian` encodes the fact that the jacobian matrix is constant. + The semantics of this argument are the following: + + * Repeated calls to "log_det_jacobian" functions with the same + `event_ndims` (but not necessarily same input), will return the first + computed jacobian (because the matrix is constant, and hence is input + independent). + * `log_det_jacobian` implementations are merely broadcastable to the true + `log_det_jacobian` (because, again, the jacobian matrix is input + independent). Specifically, `log_det_jacobian` is implemented as the + log jacobian determinant for a single input. + + ```python + class Identity(Bijector): + + def __init__(self, validate_args=False, name="identity"): + super(Identity, self).__init__( + is_constant_jacobian=True, + validate_args=validate_args, + forward_min_event_ndims=0, + name=name) + + def _forward(self, x): + return x + + def _inverse(self, y): + return y + + def _inverse_log_det_jacobian(self, y): + return -self._forward_log_det_jacobian(self._inverse(y)) + + def _forward_log_det_jacobian(self, x): + # The full log jacobian determinant would be array_ops.zero_like(x). + # However, we circumvent materializing that, since the jacobian + # calculation is input independent, and we specify it for one input. + return constant_op.constant(0., x.dtype.base_dtype) + + ``` + + #### Subclass Requirements + + - Subclasses typically implement: + + - `_forward`, + - `_inverse`, + - `_inverse_log_det_jacobian`, + - `_forward_log_det_jacobian` (optional). + + The `_forward_log_det_jacobian` is called when the bijector is inverted via + the `Invert` bijector. If undefined, a slightly less efficiently + calculation, `-1 * _inverse_log_det_jacobian`, is used. + + If the bijector changes the shape of the input, you must also implement: + + - _forward_event_shape_tensor, + - _forward_event_shape (optional), + - _inverse_event_shape_tensor, + - _inverse_event_shape (optional). + + By default the event-shape is assumed unchanged from input. + + - If the `Bijector`'s use is limited to `TransformedDistribution` (or friends + like `QuantizedDistribution`) then depending on your use, you may not need + to implement all of `_forward` and `_inverse` functions. + + Examples: + + 1. Sampling (e.g., `sample`) only requires `_forward`. + 2. Probability functions (e.g., `prob`, `cdf`, `survival`) only require + `_inverse` (and related). + 3. Only calling probability functions on the output of `sample` means + `_inverse` can be implemented as a cache lookup. + + See "Example Uses" [above] which shows how these functions are used to + transform a distribution. (Note: `_forward` could theoretically be + implemented as a cache lookup but this would require controlling the + underlying sample generation mechanism.) + + #### Non Injective Transforms + + **WARNING** Handing of non-injective transforms is subject to change. + + Non injective maps `g` are supported, provided their domain `D` can be + partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that, + ignoring sets of measure zero, the restriction of `g` to each subset is a + differentiable bijection onto `g(D)`. In particular, this implies that for + `y in g(D)`, the set inverse, i.e. `g^{-1}(y) = {x in D : g(x) = y}`, always + contains exactly `k` distinct points. + + The property, `_is_injective` is set to `False` to indicate that the bijector + is not injective, yet satisfies the above condition. + + The usual bijector API is modified in the case `_is_injective is False` (see + method docstrings for specifics). Here we show by example the `AbsoluteValue` + bijector. In this case, the domain `D = (-inf, inf)`, can be partitioned + into `D1 = (-inf, 0)`, `D2 = {0}`, and `D3 = (0, inf)`. Let `gi` be the + restriction of `g` to `Di`, then both `g1` and `g3` are bijections onto + `(0, inf)`, with `g1^{-1}(y) = -y`, and `g3^{-1}(y) = y`. We will use + `g1` and `g3` to define bijector methods over `D1` and `D3`. `D2 = {0}` is + an oddball in that `g2` is one to one, and the derivative is not well defined. + Fortunately, when considering transformations of probability densities + (e.g. in `TransformedDistribution`), sets of measure zero have no effect in + theory, and only a small effect in 32 or 64 bit precision. For that reason, + we define `inverse(0)` and `inverse_log_det_jacobian(0)` both as `[0, 0]`, + which is convenient and results in a left-semicontinuous pdf. + + + ```python + abs = tfp.distributions.bijectors.AbsoluteValue() + + abs.forward(-1.) + ==> 1. + + abs.forward(1.) + ==> 1. + + abs.inverse(1.) + ==> (-1., 1.) + + # The |dX/dY| is constant, == 1. So Log|dX/dY| == 0. + abs.inverse_log_det_jacobian(1., event_ndims=0) + ==> (0., 0.) + + # Special case handling of 0. + abs.inverse(0.) + ==> (0., 0.) + + abs.inverse_log_det_jacobian(0., event_ndims=0) + ==> (0., 0.) + ``` + + """ + + @abc.abstractmethod + def __init__(self, + graph_parents=None, + is_constant_jacobian=False, + validate_args=False, + dtype=None, + forward_min_event_ndims=None, + inverse_min_event_ndims=None, + name=None): + """Constructs Bijector. + + A `Bijector` transforms random variables into new random variables. + + Examples: + + ```python + # Create the Y = g(X) = X transform. + identity = Identity() + + # Create the Y = g(X) = exp(X) transform. + exp = Exp() + ``` + + See `Bijector` subclass docstring for more details and specific examples. + + Args: + graph_parents: Python list of graph prerequisites of this `Bijector`. + is_constant_jacobian: Python `bool` indicating that the Jacobian matrix is + not a function of the input. + validate_args: Python `bool`, default `False`. Whether to validate input + with asserts. If `validate_args` is `False`, and the inputs are invalid, + correct behavior is not guaranteed. + dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not + enforced. + forward_min_event_ndims: Python `integer` indicating the minimum number of + dimensions `forward` operates on. + inverse_min_event_ndims: Python `integer` indicating the minimum number of + dimensions `inverse` operates on. Will be set to + `forward_min_event_ndims` by default, if no value is provided. + name: The name to give Ops created by the initializer. + + Raises: + ValueError: If neither `forward_min_event_ndims` and + `inverse_min_event_ndims` are specified, or if either of them is + negative. + ValueError: If a member of `graph_parents` is not a `Tensor`. + """ + self._graph_parents = graph_parents or [] + + if forward_min_event_ndims is None and inverse_min_event_ndims is None: + raise ValueError("Must specify at least one of `forward_min_event_ndims` " + "and `inverse_min_event_ndims`.") + elif inverse_min_event_ndims is None: + inverse_min_event_ndims = forward_min_event_ndims + elif forward_min_event_ndims is None: + forward_min_event_ndims = inverse_min_event_ndims + + if not isinstance(forward_min_event_ndims, int): + raise TypeError("Expected forward_min_event_ndims to be of " + "type int, got {}".format( + type(forward_min_event_ndims).__name__)) + + if not isinstance(inverse_min_event_ndims, int): + raise TypeError("Expected inverse_min_event_ndims to be of " + "type int, got {}".format( + type(inverse_min_event_ndims).__name__)) + + if forward_min_event_ndims < 0: + raise ValueError("forward_min_event_ndims must be a non-negative " + "integer.") + if inverse_min_event_ndims < 0: + raise ValueError("inverse_min_event_ndims must be a non-negative " + "integer.") + + self._forward_min_event_ndims = forward_min_event_ndims + self._inverse_min_event_ndims = inverse_min_event_ndims + self._is_constant_jacobian = is_constant_jacobian + self._constant_ildj_map = {} + self._validate_args = validate_args + self._dtype = dtype + # These dicts can only be accessed using _Mapping.x_key or _Mapping.y_key + self._from_y = {} + self._from_x = {} + if name: + self._name = name + else: + # We want the default convention to be snake_case rather than CamelCase + # since `Chain` uses bijector.name as the kwargs dictionary key. + def camel_to_snake(name): + s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) + return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() + self._name = camel_to_snake(type(self).__name__.lstrip("_")) + + for i, t in enumerate(self._graph_parents): + if t is None or not tensor_util.is_tf_type(t): + raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t)) + + @property + def graph_parents(self): + """Returns this `Bijector`'s graph_parents as a Python list.""" + return self._graph_parents + + @property + def forward_min_event_ndims(self): + """Returns the minimal number of dimensions bijector.forward operates on.""" + return self._forward_min_event_ndims + + @property + def inverse_min_event_ndims(self): + """Returns the minimal number of dimensions bijector.inverse operates on.""" + return self._inverse_min_event_ndims + + @property + def is_constant_jacobian(self): + """Returns true iff the Jacobian matrix is not a function of x. + + Note: Jacobian matrix is either constant for both forward and inverse or + neither. + + Returns: + is_constant_jacobian: Python `bool`. + """ + return self._is_constant_jacobian + + @property + def _is_injective(self): + """Returns true iff the forward map `g` is injective (one-to-one function). + + **WARNING** This hidden property and its behavior are subject to change. + + Note: Non-injective maps `g` are supported, provided their domain `D` can + be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that, + ignoring sets of measure zero, the restriction of `g` to each subset is a + differentiable bijection onto `g(D)`. + + Returns: + is_injective: Python `bool`. + """ + return True + + @property + def validate_args(self): + """Returns True if Tensor arguments will be validated.""" + return self._validate_args + + @property + def dtype(self): + """dtype of `Tensor`s transformable by this distribution.""" + return self._dtype + + @property + def name(self): + """Returns the string name of this `Bijector`.""" + return self._name + + def _forward_event_shape_tensor(self, input_shape): + """Subclass implementation for `forward_event_shape_tensor` function.""" + # By default, we assume event_shape is unchanged. + return input_shape + + def forward_event_shape_tensor(self, + input_shape, + name="forward_event_shape_tensor"): + """Shape of a single sample from a single batch as an `int32` 1D `Tensor`. + + Args: + input_shape: `Tensor`, `int32` vector indicating event-portion shape + passed into `forward` function. + name: name to give to the op + + Returns: + forward_event_shape_tensor: `Tensor`, `int32` vector indicating + event-portion shape after applying `forward`. + """ + with self._name_scope(name, [input_shape]): + input_shape = ops.convert_to_tensor(input_shape, dtype=dtypes.int32, + name="input_shape") + return self._forward_event_shape_tensor(input_shape) + + def _forward_event_shape(self, input_shape): + """Subclass implementation for `forward_event_shape` public function.""" + # By default, we assume event_shape is unchanged. + return input_shape + + def forward_event_shape(self, input_shape): + """Shape of a single sample from a single batch as a `TensorShape`. + + Same meaning as `forward_event_shape_tensor`. May be only partially defined. + + Args: + input_shape: `TensorShape` indicating event-portion shape passed into + `forward` function. + + Returns: + forward_event_shape_tensor: `TensorShape` indicating event-portion shape + after applying `forward`. Possibly unknown. + """ + return self._forward_event_shape(tensor_shape.TensorShape(input_shape)) + + def _inverse_event_shape_tensor(self, output_shape): + """Subclass implementation for `inverse_event_shape_tensor` function.""" + # By default, we assume event_shape is unchanged. + return output_shape + + def inverse_event_shape_tensor(self, + output_shape, + name="inverse_event_shape_tensor"): + """Shape of a single sample from a single batch as an `int32` 1D `Tensor`. + + Args: + output_shape: `Tensor`, `int32` vector indicating event-portion shape + passed into `inverse` function. + name: name to give to the op + + Returns: + inverse_event_shape_tensor: `Tensor`, `int32` vector indicating + event-portion shape after applying `inverse`. + """ + with self._name_scope(name, [output_shape]): + output_shape = ops.convert_to_tensor(output_shape, dtype=dtypes.int32, + name="output_shape") + return self._inverse_event_shape_tensor(output_shape) + + def _inverse_event_shape(self, output_shape): + """Subclass implementation for `inverse_event_shape` public function.""" + # By default, we assume event_shape is unchanged. + return tensor_shape.TensorShape(output_shape) + + def inverse_event_shape(self, output_shape): + """Shape of a single sample from a single batch as a `TensorShape`. + + Same meaning as `inverse_event_shape_tensor`. May be only partially defined. + + Args: + output_shape: `TensorShape` indicating event-portion shape passed into + `inverse` function. + + Returns: + inverse_event_shape_tensor: `TensorShape` indicating event-portion shape + after applying `inverse`. Possibly unknown. + """ + return self._inverse_event_shape(output_shape) + + def _forward(self, x): + """Subclass implementation for `forward` public function.""" + raise NotImplementedError("forward not implemented.") + + def _call_forward(self, x, name, **kwargs): + with self._name_scope(name, [x]): + x = ops.convert_to_tensor(x, name="x") + self._maybe_assert_dtype(x) + if not self._is_injective: # No caching for non-injective + return self._forward(x, **kwargs) + mapping = self._lookup(x=x, kwargs=kwargs) + if mapping.y is not None: + return mapping.y + mapping = mapping.merge(y=self._forward(x, **kwargs)) + self._cache(mapping) + return mapping.y + + def forward(self, x, name="forward"): + """Returns the forward `Bijector` evaluation, i.e., X = g(Y). + + Args: + x: `Tensor`. The input to the "forward" evaluation. + name: The name to give this op. + + Returns: + `Tensor`. + + Raises: + TypeError: if `self.dtype` is specified and `x.dtype` is not + `self.dtype`. + NotImplementedError: if `_forward` is not implemented. + """ + return self._call_forward(x, name) + + def _inverse(self, y): + """Subclass implementation for `inverse` public function.""" + raise NotImplementedError("inverse not implemented") + + def _call_inverse(self, y, name, **kwargs): + with self._name_scope(name, [y]): + y = ops.convert_to_tensor(y, name="y") + self._maybe_assert_dtype(y) + if not self._is_injective: # No caching for non-injective + return self._inverse(y, **kwargs) + mapping = self._lookup(y=y, kwargs=kwargs) + if mapping.x is not None: + return mapping.x + mapping = mapping.merge(x=self._inverse(y, **kwargs)) + self._cache(mapping) + return mapping.x + + def inverse(self, y, name="inverse"): + """Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y). + + Args: + y: `Tensor`. The input to the "inverse" evaluation. + name: The name to give this op. + + Returns: + `Tensor`, if this bijector is injective. + If not injective, returns the k-tuple containing the unique + `k` points `(x1, ..., xk)` such that `g(xi) = y`. + + Raises: + TypeError: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. + NotImplementedError: if `_inverse` is not implemented. + """ + return self._call_inverse(y, name) + + def _inverse_log_det_jacobian(self, y): + """Subclass implementation of `inverse_log_det_jacobian` public function. + + In particular, this method differs from the public function, in that it + does not take `event_ndims`. Thus, this implements the minimal Jacobian + determinant calculation (i.e. over `inverse_min_event_ndims`). + + Args: + y: `Tensor`. The input to the "inverse_log_det_jacobian" evaluation. + Returns: + inverse_log_det_jacobian: `Tensor`, if this bijector is injective. + If not injective, returns the k-tuple containing jacobians for the + unique `k` points `(x1, ..., xk)` such that `g(xi) = y`. + """ + raise NotImplementedError("inverse_log_det_jacobian not implemented.") + + def _call_inverse_log_det_jacobian(self, y, event_ndims, name, **kwargs): + with self._name_scope(name, [y]): + if event_ndims in self._constant_ildj_map: + return self._constant_ildj_map[event_ndims] + y = ops.convert_to_tensor(y, name="y") + self._maybe_assert_dtype(y) + with ops.control_dependencies(self._check_valid_event_ndims( + min_event_ndims=self.inverse_min_event_ndims, + event_ndims=event_ndims)): + if not self._is_injective: # No caching for non-injective + try: + ildjs = self._inverse_log_det_jacobian(y, **kwargs) + return tuple(self._reduce_jacobian_det_over_event( + y, ildj, self.inverse_min_event_ndims, event_ndims) + for ildj in ildjs) + except NotImplementedError as original_exception: + try: + x = self._inverse(y, **kwargs) + fldjs = self._forward_log_det_jacobian(x, **kwargs) + return tuple(self._reduce_jacobian_det_over_event( + x, -fldj, self.forward_min_event_ndims, event_ndims) + for fldj in fldjs) + except NotImplementedError: + raise original_exception + + mapping = self._lookup(y=y, kwargs=kwargs) + if mapping.ildj_map is not None and event_ndims in mapping.ildj_map: + return mapping.ildj_map[event_ndims] + try: + x = None # Not needed; leave cache as is. + ildj = self._inverse_log_det_jacobian(y, **kwargs) + ildj = self._reduce_jacobian_det_over_event( + y, ildj, self.inverse_min_event_ndims, event_ndims) + except NotImplementedError as original_exception: + try: + x = (mapping.x if mapping.x is not None + else self._inverse(y, **kwargs)) + ildj = -self._forward_log_det_jacobian(x, **kwargs) + ildj = self._reduce_jacobian_det_over_event( + x, ildj, self.forward_min_event_ndims, event_ndims) + except NotImplementedError: + raise original_exception + + mapping = mapping.merge(x=x, ildj_map={event_ndims: ildj}) + self._cache(mapping) + if self.is_constant_jacobian: + self._constant_ildj_map[event_ndims] = ildj + return ildj + + def inverse_log_det_jacobian( + self, y, event_ndims, name="inverse_log_det_jacobian"): + """Returns the (log o det o Jacobian o inverse)(y). + + Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.) + + Note that `forward_log_det_jacobian` is the negative of this function, + evaluated at `g^{-1}(y)`. + + Args: + y: `Tensor`. The input to the "inverse" Jacobian determinant evaluation. + event_ndims: Number of dimensions in the probabilistic events being + transformed. Must be greater than or equal to + `self.inverse_min_event_ndims`. The result is summed over the final + dimensions to produce a scalar Jacobian determinant for each event, + i.e. it has shape `y.shape.ndims - event_ndims` dimensions. + name: The name to give this op. + + Returns: + `Tensor`, if this bijector is injective. + If not injective, returns the tuple of local log det + Jacobians, `log(det(Dg_i^{-1}(y)))`, where `g_i` is the restriction + of `g` to the `ith` partition `Di`. + + Raises: + TypeError: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. + NotImplementedError: if `_inverse_log_det_jacobian` is not implemented. + """ + return self._call_inverse_log_det_jacobian(y, event_ndims, name) + + def _forward_log_det_jacobian(self, x): + """Subclass implementation of `forward_log_det_jacobian` public function. + + In particular, this method differs from the public function, in that it + does not take `event_ndims`. Thus, this implements the minimal Jacobian + determinant calculation (i.e. over `forward_min_event_ndims`). + + Args: + x: `Tensor`. The input to the "forward_log_det_jacobian" evaluation. + + Returns: + forward_log_det_jacobian: `Tensor`, if this bijector is injective. + If not injective, returns the k-tuple containing jacobians for the + unique `k` points `(x1, ..., xk)` such that `g(xi) = y`. + """ + + raise NotImplementedError( + "forward_log_det_jacobian not implemented.") + + def _call_forward_log_det_jacobian(self, x, event_ndims, name, **kwargs): + if not self._is_injective: + raise NotImplementedError( + "forward_log_det_jacobian cannot be implemented for non-injective " + "transforms.") + with self._name_scope(name, [x]): + with ops.control_dependencies(self._check_valid_event_ndims( + min_event_ndims=self.forward_min_event_ndims, + event_ndims=event_ndims)): + if event_ndims in self._constant_ildj_map: + # Need "-1. *" to avoid invalid-unary-operand-type linter warning. + return -1. * self._constant_ildj_map[event_ndims] + x = ops.convert_to_tensor(x, name="x") + self._maybe_assert_dtype(x) + if not self._is_injective: # No caching for non-injective + try: + fldjs = self._forward_log_det_jacobian(x, **kwargs) # No caching. + return tuple(self._reduce_jacobian_det_over_event( + x, fldj, self.forward_min_event_ndims, event_ndims) + for fldj in fldjs) + except NotImplementedError as original_exception: + try: + y = self._forward(x, **kwargs) + ildjs = self._inverse_log_det_jacobian(y, **kwargs) + return tuple(self._reduce_jacobian_det_over_event( + y, -ildj, self.inverse_min_event_ndims, event_ndims) + for ildj in ildjs) + except NotImplementedError: + raise original_exception + mapping = self._lookup(x=x, kwargs=kwargs) + if mapping.ildj_map is not None and event_ndims in mapping.ildj_map: + return -mapping.ildj_map[event_ndims] + try: + y = None # Not needed; leave cache as is. + ildj = -self._forward_log_det_jacobian(x, **kwargs) + ildj = self._reduce_jacobian_det_over_event( + x, ildj, self.forward_min_event_ndims, event_ndims) + except NotImplementedError as original_exception: + try: + y = (mapping.y if mapping.y is not None + else self._forward(x, **kwargs)) + ildj = self._inverse_log_det_jacobian(y, **kwargs) + ildj = self._reduce_jacobian_det_over_event( + y, ildj, self.inverse_min_event_ndims, event_ndims) + except NotImplementedError: + raise original_exception + mapping = mapping.merge(y=y, ildj_map={event_ndims: ildj}) + self._cache(mapping) + if self.is_constant_jacobian: + self._constant_ildj_map[event_ndims] = ildj + return -ildj + + def forward_log_det_jacobian( + self, x, event_ndims, name="forward_log_det_jacobian"): + """Returns both the forward_log_det_jacobian. + + Args: + x: `Tensor`. The input to the "forward" Jacobian determinant evaluation. + event_ndims: Number of dimensions in the probabilistic events being + transformed. Must be greater than or equal to + `self.forward_min_event_ndims`. The result is summed over the final + dimensions to produce a scalar Jacobian determinant for each event, + i.e. it has shape `x.shape.ndims - event_ndims` dimensions. + name: The name to give this op. + + Returns: + `Tensor`, if this bijector is injective. + If not injective this is not implemented. + + Raises: + TypeError: if `self.dtype` is specified and `y.dtype` is not + `self.dtype`. + NotImplementedError: if neither `_forward_log_det_jacobian` + nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or + this is a non-injective bijector. + """ + return self._call_forward_log_det_jacobian(x, event_ndims, name) + + @contextlib.contextmanager + def _name_scope(self, name=None, values=None): + """Helper function to standardize op scope.""" + with ops.name_scope(self.name): + with ops.name_scope( + name, values=(values or []) + self.graph_parents) as scope: + yield scope + + def _maybe_assert_dtype(self, x): + """Helper to check dtype when self.dtype is known.""" + if self.dtype is not None and self.dtype.base_dtype != x.dtype.base_dtype: + raise TypeError("Input had dtype %s but expected %s." % + (self.dtype, x.dtype)) + + def _cache(self, mapping): + """Helper which stores mapping info in forward/inverse dicts.""" + # Merging from lookup is an added check that we're not overwriting anything + # which is not None. + mapping = mapping.merge(mapping=self._lookup( + mapping.x, mapping.y, mapping.kwargs)) + if mapping.x is None and mapping.y is None: + raise ValueError("Caching expects at least one of (x,y) to be known, " + "i.e., not None.") + self._from_x[mapping.x_key] = mapping + self._from_y[mapping.y_key] = mapping + + def _lookup(self, x=None, y=None, kwargs=None): + """Helper which retrieves mapping info from forward/inverse dicts.""" + mapping = _Mapping(x=x, y=y, kwargs=kwargs) + # Since _cache requires both x,y to be set, we only need to do one cache + # lookup since the mapping is always in both or neither. + if mapping.x is not None: + return self._from_x.get(mapping.x_key, mapping) + if mapping.y is not None: + return self._from_y.get(mapping.y_key, mapping) + return mapping + + def _reduce_jacobian_det_over_event( + self, y, ildj, min_event_ndims, event_ndims): + """Reduce jacobian over event_ndims - min_event_ndims.""" + # In this case, we need to tile the Jacobian over the event and reduce. + y_rank = array_ops.rank(y) + y_shape = array_ops.shape(y)[ + y_rank - event_ndims : y_rank - min_event_ndims] + + ones = array_ops.ones(y_shape, ildj.dtype) + reduced_ildj = math_ops.reduce_sum( + ones * ildj, + axis=self._get_event_reduce_dims(min_event_ndims, event_ndims)) + # The multiplication by ones can change the inferred static shape so we try + # to recover as much as possible. + event_ndims_ = self._maybe_get_static_event_ndims(event_ndims) + if (event_ndims_ is not None and + y.shape.ndims is not None and + ildj.shape.ndims is not None): + y_shape = y.shape[y.shape.ndims - event_ndims_ : + y.shape.ndims - min_event_ndims] + broadcast_shape = array_ops.broadcast_static_shape(ildj.shape, y_shape) + reduced_ildj.set_shape( + broadcast_shape[: broadcast_shape.ndims - ( + event_ndims_ - min_event_ndims)]) + + return reduced_ildj + + def _get_event_reduce_dims(self, min_event_ndims, event_ndims): + """Compute the reduction dimensions given event_ndims.""" + event_ndims_ = self._maybe_get_static_event_ndims(event_ndims) + + if event_ndims_ is not None: + return [-index for index in range(1, event_ndims_ - min_event_ndims + 1)] + else: + reduce_ndims = event_ndims - min_event_ndims + return math_ops.range(-reduce_ndims, 0) + + def _check_valid_event_ndims(self, min_event_ndims, event_ndims): + """Check whether event_ndims is at least min_event_ndims.""" + event_ndims = ops.convert_to_tensor(event_ndims, name="event_ndims") + event_ndims_ = tensor_util.constant_value(event_ndims) + assertions = [] + + if not event_ndims.dtype.is_integer: + raise ValueError("Expected integer dtype, got dtype {}".format( + event_ndims.dtype)) + + if event_ndims_ is not None: + if event_ndims.shape.ndims != 0: + raise ValueError("Expected scalar event_ndims, got shape {}".format( + event_ndims.shape)) + if min_event_ndims > event_ndims_: + raise ValueError("event_ndims ({}) must be larger than " + "min_event_ndims ({})".format( + event_ndims_, min_event_ndims)) + elif self.validate_args: + assertions += [ + check_ops.assert_greater_equal(event_ndims, min_event_ndims)] + + if event_ndims.shape.is_fully_defined(): + if event_ndims.shape.ndims != 0: + raise ValueError("Expected scalar shape, got ndims {}".format( + event_ndims.shape.ndims)) + + elif self.validate_args: + assertions += [ + check_ops.assert_rank(event_ndims, 0, message="Expected scalar.")] + return assertions + + def _maybe_get_static_event_ndims(self, event_ndims): + """Helper which returns tries to return an integer static value.""" + event_ndims_ = distribution_util.maybe_get_static_value(event_ndims) + + if isinstance(event_ndims_, (np.generic, np.ndarray)): + if event_ndims_.dtype not in (np.int32, np.int64): + raise ValueError("Expected integer dtype, got dtype {}".format( + event_ndims_.dtype)) + + if isinstance(event_ndims_, np.ndarray) and len(event_ndims_.shape): + raise ValueError("Expected a scalar integer, got {}".format( + event_ndims_)) + event_ndims_ = int(event_ndims_) + + return event_ndims_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..48433c568e60205ab4bb4625986baa14ee98af1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/bijector_test_util.py @@ -0,0 +1,221 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Bijector unit-test utilities.""" + +import numpy as np + +from tensorflow.python.framework import ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.distributions import uniform as uniform_lib + + +def assert_finite(array): + if not np.isfinite(array).all(): + raise AssertionError("array was not all finite. %s" % array[:15]) + + +def assert_strictly_increasing(array): + np.testing.assert_array_less(0., np.diff(array)) + + +def assert_strictly_decreasing(array): + np.testing.assert_array_less(np.diff(array), 0.) + + +def assert_strictly_monotonic(array): + if array[0] < array[-1]: + assert_strictly_increasing(array) + else: + assert_strictly_decreasing(array) + + +def assert_scalar_congruency(bijector, + lower_x, + upper_x, + n=int(10e3), + rtol=0.01, + sess=None): + """Assert `bijector`'s forward/inverse/inverse_log_det_jacobian are congruent. + + We draw samples `X ~ U(lower_x, upper_x)`, then feed these through the + `bijector` in order to check that: + + 1. the forward is strictly monotonic. + 2. the forward/inverse methods are inverses of each other. + 3. the jacobian is the correct change of measure. + + This can only be used for a Bijector mapping open subsets of the real line + to themselves. This is due to the fact that this test compares the `prob` + before/after transformation with the Lebesgue measure on the line. + + Args: + bijector: Instance of Bijector + lower_x: Python scalar. + upper_x: Python scalar. Must have `lower_x < upper_x`, and both must be in + the domain of the `bijector`. The `bijector` should probably not produce + huge variation in values in the interval `(lower_x, upper_x)`, or else + the variance based check of the Jacobian will require small `rtol` or + huge `n`. + n: Number of samples to draw for the checks. + rtol: Positive number. Used for the Jacobian check. + sess: `tf.compat.v1.Session`. Defaults to the default session. + + Raises: + AssertionError: If tests fail. + """ + # Checks and defaults. + if sess is None: + sess = ops.get_default_session() + + # Should be monotonic over this interval + ten_x_pts = np.linspace(lower_x, upper_x, num=10).astype(np.float32) + if bijector.dtype is not None: + ten_x_pts = ten_x_pts.astype(bijector.dtype.as_numpy_dtype) + forward_on_10_pts = bijector.forward(ten_x_pts) + + # Set the lower/upper limits in the range of the bijector. + lower_y, upper_y = sess.run( + [bijector.forward(lower_x), bijector.forward(upper_x)]) + if upper_y < lower_y: # If bijector.forward is a decreasing function. + lower_y, upper_y = upper_y, lower_y + + # Uniform samples from the domain, range. + uniform_x_samps = uniform_lib.Uniform( + low=lower_x, high=upper_x).sample(n, seed=0) + uniform_y_samps = uniform_lib.Uniform( + low=lower_y, high=upper_y).sample(n, seed=1) + + # These compositions should be the identity. + inverse_forward_x = bijector.inverse(bijector.forward(uniform_x_samps)) + forward_inverse_y = bijector.forward(bijector.inverse(uniform_y_samps)) + + # For a < b, and transformation y = y(x), + # (b - a) = \int_a^b dx = \int_{y(a)}^{y(b)} |dx/dy| dy + # "change_measure_dy_dx" below is a Monte Carlo approximation to the right + # hand side, which should then be close to the left, which is (b - a). + # We assume event_ndims=0 because we assume scalar -> scalar. The log_det + # methods will handle whether they expect event_ndims > 0. + dy_dx = math_ops.exp(bijector.inverse_log_det_jacobian( + uniform_y_samps, event_ndims=0)) + # E[|dx/dy|] under Uniform[lower_y, upper_y] + # = \int_{y(a)}^{y(b)} |dx/dy| dP(u), where dP(u) is the uniform measure + expectation_of_dy_dx_under_uniform = math_ops.reduce_mean(dy_dx) + # dy = dP(u) * (upper_y - lower_y) + change_measure_dy_dx = ( + (upper_y - lower_y) * expectation_of_dy_dx_under_uniform) + + # We'll also check that dy_dx = 1 / dx_dy. + dx_dy = math_ops.exp( + bijector.forward_log_det_jacobian( + bijector.inverse(uniform_y_samps), event_ndims=0)) + + [ + forward_on_10_pts_v, + dy_dx_v, + dx_dy_v, + change_measure_dy_dx_v, + uniform_x_samps_v, + uniform_y_samps_v, + inverse_forward_x_v, + forward_inverse_y_v, + ] = sess.run([ + forward_on_10_pts, + dy_dx, + dx_dy, + change_measure_dy_dx, + uniform_x_samps, + uniform_y_samps, + inverse_forward_x, + forward_inverse_y, + ]) + + assert_strictly_monotonic(forward_on_10_pts_v) + # Composition of forward/inverse should be the identity. + np.testing.assert_allclose( + inverse_forward_x_v, uniform_x_samps_v, atol=1e-5, rtol=1e-3) + np.testing.assert_allclose( + forward_inverse_y_v, uniform_y_samps_v, atol=1e-5, rtol=1e-3) + # Change of measure should be correct. + np.testing.assert_allclose( + upper_x - lower_x, change_measure_dy_dx_v, atol=0, rtol=rtol) + # Inverse Jacobian should be equivalent to the reciprocal of the forward + # Jacobian. + np.testing.assert_allclose( + dy_dx_v, np.divide(1., dx_dy_v), atol=1e-5, rtol=1e-3) + + +def assert_bijective_and_finite( + bijector, x, y, event_ndims, atol=0, rtol=1e-5, sess=None): + """Assert that forward/inverse (along with jacobians) are inverses and finite. + + It is recommended to use x and y values that are very very close to the edge + of the Bijector's domain. + + Args: + bijector: A Bijector instance. + x: np.array of values in the domain of bijector.forward. + y: np.array of values in the domain of bijector.inverse. + event_ndims: Integer describing the number of event dimensions this bijector + operates on. + atol: Absolute tolerance. + rtol: Relative tolerance. + sess: TensorFlow session. Defaults to the default session. + + Raises: + AssertionError: If tests fail. + """ + sess = sess or ops.get_default_session() + + # These are the incoming points, but people often create a crazy range of + # values for which these end up being bad, especially in 16bit. + assert_finite(x) + assert_finite(y) + + f_x = bijector.forward(x) + g_y = bijector.inverse(y) + + [ + x_from_x, + y_from_y, + ildj_f_x, + fldj_x, + ildj_y, + fldj_g_y, + f_x_v, + g_y_v, + ] = sess.run([ + bijector.inverse(f_x), + bijector.forward(g_y), + bijector.inverse_log_det_jacobian(f_x, event_ndims=event_ndims), + bijector.forward_log_det_jacobian(x, event_ndims=event_ndims), + bijector.inverse_log_det_jacobian(y, event_ndims=event_ndims), + bijector.forward_log_det_jacobian(g_y, event_ndims=event_ndims), + f_x, + g_y, + ]) + + assert_finite(x_from_x) + assert_finite(y_from_y) + assert_finite(ildj_f_x) + assert_finite(fldj_x) + assert_finite(ildj_y) + assert_finite(fldj_g_y) + assert_finite(f_x_v) + assert_finite(g_y_v) + + np.testing.assert_allclose(x_from_x, x, atol=atol, rtol=rtol) + np.testing.assert_allclose(y_from_y, y, atol=atol, rtol=rtol) + np.testing.assert_allclose(-ildj_f_x, fldj_x, atol=atol, rtol=rtol) + np.testing.assert_allclose(-ildj_y, fldj_g_y, atol=atol, rtol=rtol) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/categorical.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..2054271c71ce81200674a005841d0fb5bc7dd789 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/categorical.py @@ -0,0 +1,345 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Categorical distribution class.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +def _broadcast_cat_event_and_params(event, params, base_dtype): + """Broadcasts the event or distribution parameters.""" + if event.dtype.is_integer: + pass + elif event.dtype.is_floating: + # When `validate_args=True` we've already ensured int/float casting + # is closed. + event = math_ops.cast(event, dtype=dtypes.int32) + else: + raise TypeError("`value` should have integer `dtype` or " + "`self.dtype` ({})".format(base_dtype)) + shape_known_statically = ( + params.shape.ndims is not None and + params.shape[:-1].is_fully_defined() and + event.shape.is_fully_defined()) + if not shape_known_statically or params.shape[:-1] != event.shape: + params *= array_ops.ones_like(event[..., array_ops.newaxis], + dtype=params.dtype) + params_shape = array_ops.shape(params)[:-1] + event *= array_ops.ones(params_shape, dtype=event.dtype) + if params.shape.ndims is not None: + event.set_shape(tensor_shape.TensorShape(params.shape[:-1])) + + return event, params + + +@tf_export(v1=["distributions.Categorical"]) +class Categorical(distribution.Distribution): + """Categorical distribution. + + The Categorical distribution is parameterized by either probabilities or + log-probabilities of a set of `K` classes. It is defined over the integers + `{0, 1, ..., K}`. + + The Categorical distribution is closely related to the `OneHotCategorical` and + `Multinomial` distributions. The Categorical distribution can be intuited as + generating samples according to `argmax{ OneHotCategorical(probs) }` itself + being identical to `argmax{ Multinomial(probs, total_count=1) }`. + + #### Mathematical Details + + The probability mass function (pmf) is, + + ```none + pmf(k; pi) = prod_j pi_j**[k == j] + ``` + + #### Pitfalls + + The number of classes, `K`, must not exceed: + - the largest integer representable by `self.dtype`, i.e., + `2**(mantissa_bits+1)` (IEEE 754), + - the maximum `Tensor` index, i.e., `2**31-1`. + + In other words, + + ```python + K <= min(2**31-1, { + tf.float16: 2**11, + tf.float32: 2**24, + tf.float64: 2**53 }[param.dtype]) + ``` + + Note: This condition is validated only when `self.validate_args = True`. + + #### Examples + + Creates a 3-class distribution with the 2nd class being most likely. + + ```python + dist = Categorical(probs=[0.1, 0.5, 0.4]) + n = 1e4 + empirical_prob = tf.cast( + tf.histogram_fixed_width( + dist.sample(int(n)), + [0., 2], + nbins=3), + dtype=tf.float32) / n + # ==> array([ 0.1005, 0.5037, 0.3958], dtype=float32) + ``` + + Creates a 3-class distribution with the 2nd class being most likely. + Parameterized by [logits](https://en.wikipedia.org/wiki/Logit) rather than + probabilities. + + ```python + dist = Categorical(logits=np.log([0.1, 0.5, 0.4]) + n = 1e4 + empirical_prob = tf.cast( + tf.histogram_fixed_width( + dist.sample(int(n)), + [0., 2], + nbins=3), + dtype=tf.float32) / n + # ==> array([0.1045, 0.5047, 0.3908], dtype=float32) + ``` + + Creates a 3-class distribution with the 3rd class being most likely. + The distribution functions can be evaluated on counts. + + ```python + # counts is a scalar. + p = [0.1, 0.4, 0.5] + dist = Categorical(probs=p) + dist.prob(0) # Shape [] + + # p will be broadcast to [[0.1, 0.4, 0.5], [0.1, 0.4, 0.5]] to match counts. + counts = [1, 0] + dist.prob(counts) # Shape [2] + + # p will be broadcast to shape [3, 5, 7, 3] to match counts. + counts = [[...]] # Shape [5, 7, 3] + dist.prob(counts) # Shape [5, 7, 3] + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__( + self, + logits=None, + probs=None, + dtype=dtypes.int32, + validate_args=False, + allow_nan_stats=True, + name="Categorical"): + """Initialize Categorical distributions using class log-probabilities. + + Args: + logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities + of a set of Categorical distributions. The first `N - 1` dimensions + index into a batch of independent distributions and the last dimension + represents a vector of logits for each class. Only one of `logits` or + `probs` should be passed in. + probs: An N-D `Tensor`, `N >= 1`, representing the probabilities + of a set of Categorical distributions. The first `N - 1` dimensions + index into a batch of independent distributions and the last dimension + represents a vector of probabilities for each class. Only one of + `logits` or `probs` should be passed in. + dtype: The type of the event samples (default: int32). + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[logits, probs]) as name: + self._logits, self._probs = distribution_util.get_logits_and_probs( + logits=logits, + probs=probs, + validate_args=validate_args, + multidimensional=True, + name=name) + + if validate_args: + self._logits = distribution_util.embed_check_categorical_event_shape( + self._logits) + + logits_shape_static = self._logits.get_shape().with_rank_at_least(1) + if logits_shape_static.ndims is not None: + self._batch_rank = ops.convert_to_tensor( + logits_shape_static.ndims - 1, + dtype=dtypes.int32, + name="batch_rank") + else: + with ops.name_scope(name="batch_rank"): + self._batch_rank = array_ops.rank(self._logits) - 1 + + logits_shape = array_ops.shape(self._logits, name="logits_shape") + if tensor_shape.dimension_value(logits_shape_static[-1]) is not None: + self._event_size = ops.convert_to_tensor( + logits_shape_static.dims[-1].value, + dtype=dtypes.int32, + name="event_size") + else: + with ops.name_scope(name="event_size"): + self._event_size = logits_shape[self._batch_rank] + + if logits_shape_static[:-1].is_fully_defined(): + self._batch_shape_val = constant_op.constant( + logits_shape_static[:-1].as_list(), + dtype=dtypes.int32, + name="batch_shape") + else: + with ops.name_scope(name="batch_shape"): + self._batch_shape_val = logits_shape[:-1] + super(Categorical, self).__init__( + dtype=dtype, + reparameterization_type=distribution.NOT_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._logits, + self._probs], + name=name) + + @property + def event_size(self): + """Scalar `int32` tensor: the number of classes.""" + return self._event_size + + @property + def logits(self): + """Vector of coordinatewise logits.""" + return self._logits + + @property + def probs(self): + """Vector of coordinatewise probabilities.""" + return self._probs + + def _batch_shape_tensor(self): + return array_ops.identity(self._batch_shape_val) + + def _batch_shape(self): + return self.logits.get_shape()[:-1] + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + if self.logits.get_shape().ndims == 2: + logits_2d = self.logits + else: + logits_2d = array_ops.reshape(self.logits, [-1, self.event_size]) + sample_dtype = dtypes.int64 if self.dtype.size > 4 else dtypes.int32 + draws = random_ops.multinomial( + logits_2d, n, seed=seed, output_dtype=sample_dtype) + draws = array_ops.reshape( + array_ops.transpose(draws), + array_ops.concat([[n], self.batch_shape_tensor()], 0)) + return math_ops.cast(draws, self.dtype) + + def _cdf(self, k): + k = ops.convert_to_tensor(k, name="k") + if self.validate_args: + k = distribution_util.embed_check_integer_casting_closed( + k, target_dtype=dtypes.int32) + + k, probs = _broadcast_cat_event_and_params( + k, self.probs, base_dtype=self.dtype.base_dtype) + + # batch-flatten everything in order to use `sequence_mask()`. + batch_flattened_probs = array_ops.reshape(probs, + (-1, self._event_size)) + batch_flattened_k = array_ops.reshape(k, [-1]) + + to_sum_over = array_ops.where( + array_ops.sequence_mask(batch_flattened_k, self._event_size), + batch_flattened_probs, + array_ops.zeros_like(batch_flattened_probs)) + batch_flattened_cdf = math_ops.reduce_sum(to_sum_over, axis=-1) + # Reshape back to the shape of the argument. + return array_ops.reshape(batch_flattened_cdf, array_ops.shape(k)) + + def _log_prob(self, k): + k = ops.convert_to_tensor(k, name="k") + if self.validate_args: + k = distribution_util.embed_check_integer_casting_closed( + k, target_dtype=dtypes.int32) + k, logits = _broadcast_cat_event_and_params( + k, self.logits, base_dtype=self.dtype.base_dtype) + + # pylint: disable=invalid-unary-operand-type + return -nn_ops.sparse_softmax_cross_entropy_with_logits( + labels=k, + logits=logits) + + def _entropy(self): + return -math_ops.reduce_sum( + nn_ops.log_softmax(self.logits) * self.probs, axis=-1) + + def _mode(self): + ret = math_ops.argmax(self.logits, axis=self._batch_rank) + ret = math_ops.cast(ret, self.dtype) + ret.set_shape(self.batch_shape) + return ret + + +@kullback_leibler.RegisterKL(Categorical, Categorical) +def _kl_categorical_categorical(a, b, name=None): + """Calculate the batched KL divergence KL(a || b) with a and b Categorical. + + Args: + a: instance of a Categorical distribution object. + b: instance of a Categorical distribution object. + name: (optional) Name to use for created operations. + default is "kl_categorical_categorical". + + Returns: + Batchwise KL(a || b) + """ + with ops.name_scope(name, "kl_categorical_categorical", + values=[a.logits, b.logits]): + # sum(probs log(probs / (1 - probs))) + delta_log_probs1 = (nn_ops.log_softmax(a.logits) - + nn_ops.log_softmax(b.logits)) + return math_ops.reduce_sum(nn_ops.softmax(a.logits) * delta_log_probs1, + axis=-1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet.py new file mode 100644 index 0000000000000000000000000000000000000000..cac99f8e0c071fd539fca7d22bd118c83a9ad5d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet.py @@ -0,0 +1,410 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Dirichlet distribution class.""" + +import numpy as np + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Dirichlet", +] + + +_dirichlet_sample_note = """Note: `value` must be a non-negative tensor with +dtype `self.dtype` and be in the `(self.event_shape() - 1)`-simplex, i.e., +`tf.reduce_sum(value, -1) = 1`. It must have a shape compatible with +`self.batch_shape() + self.event_shape()`.""" + + +@tf_export(v1=["distributions.Dirichlet"]) +class Dirichlet(distribution.Distribution): + """Dirichlet distribution. + + The Dirichlet distribution is defined over the + [`(k-1)`-simplex](https://en.wikipedia.org/wiki/Simplex) using a positive, + length-`k` vector `concentration` (`k > 1`). The Dirichlet is identically the + Beta distribution when `k = 2`. + + #### Mathematical Details + + The Dirichlet is a distribution over the open `(k-1)`-simplex, i.e., + + ```none + S^{k-1} = { (x_0, ..., x_{k-1}) in R^k : sum_j x_j = 1 and all_j x_j > 0 }. + ``` + + The probability density function (pdf) is, + + ```none + pdf(x; alpha) = prod_j x_j**(alpha_j - 1) / Z + Z = prod_j Gamma(alpha_j) / Gamma(sum_j alpha_j) + ``` + + where: + + * `x in S^{k-1}`, i.e., the `(k-1)`-simplex, + * `concentration = alpha = [alpha_0, ..., alpha_{k-1}]`, `alpha_j > 0`, + * `Z` is the normalization constant aka the [multivariate beta function]( + https://en.wikipedia.org/wiki/Beta_function#Multivariate_beta_function), + and, + * `Gamma` is the [gamma function]( + https://en.wikipedia.org/wiki/Gamma_function). + + The `concentration` represents mean total counts of class occurrence, i.e., + + ```none + concentration = alpha = mean * total_concentration + ``` + + where `mean` in `S^{k-1}` and `total_concentration` is a positive real number + representing a mean total count. + + Distribution parameters are automatically broadcast in all functions; see + examples for details. + + Warning: Some components of the samples can be zero due to finite precision. + This happens more often when some of the concentrations are very small. + Make sure to round the samples to `np.finfo(dtype).tiny` before computing the + density. + + Samples of this distribution are reparameterized (pathwise differentiable). + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + #### Examples + + ```python + import tensorflow_probability as tfp + tfd = tfp.distributions + + # Create a single trivariate Dirichlet, with the 3rd class being three times + # more frequent than the first. I.e., batch_shape=[], event_shape=[3]. + alpha = [1., 2, 3] + dist = tfd.Dirichlet(alpha) + + dist.sample([4, 5]) # shape: [4, 5, 3] + + # x has one sample, one batch, three classes: + x = [.2, .3, .5] # shape: [3] + dist.prob(x) # shape: [] + + # x has two samples from one batch: + x = [[.1, .4, .5], + [.2, .3, .5]] + dist.prob(x) # shape: [2] + + # alpha will be broadcast to shape [5, 7, 3] to match x. + x = [[...]] # shape: [5, 7, 3] + dist.prob(x) # shape: [5, 7] + ``` + + ```python + # Create batch_shape=[2], event_shape=[3]: + alpha = [[1., 2, 3], + [4, 5, 6]] # shape: [2, 3] + dist = tfd.Dirichlet(alpha) + + dist.sample([4, 5]) # shape: [4, 5, 2, 3] + + x = [.2, .3, .5] + # x will be broadcast as [[.2, .3, .5], + # [.2, .3, .5]], + # thus matching batch_shape [2, 3]. + dist.prob(x) # shape: [2] + ``` + + Compute the gradients of samples w.r.t. the parameters: + + ```python + alpha = tf.constant([1.0, 2.0, 3.0]) + dist = tfd.Dirichlet(alpha) + samples = dist.sample(5) # Shape [5, 3] + loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function + # Unbiased stochastic gradients of the loss function + grads = tf.gradients(loss, alpha) + ``` + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + concentration, + validate_args=False, + allow_nan_stats=True, + name="Dirichlet"): + """Initialize a batch of Dirichlet distributions. + + Args: + concentration: Positive floating-point `Tensor` indicating mean number + of class occurrences; aka "alpha". Implies `self.dtype`, and + `self.batch_shape`, `self.event_shape`, i.e., if + `concentration.shape = [N1, N2, ..., Nm, k]` then + `batch_shape = [N1, N2, ..., Nm]` and + `event_shape = [k]`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[concentration]) as name: + self._concentration = self._maybe_assert_valid_concentration( + ops.convert_to_tensor(concentration, name="concentration"), + validate_args) + self._total_concentration = math_ops.reduce_sum(self._concentration, -1) + super(Dirichlet, self).__init__( + dtype=self._concentration.dtype, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + parameters=parameters, + graph_parents=[self._concentration, + self._total_concentration], + name=name) + + @property + def concentration(self): + """Concentration parameter; expected counts for that coordinate.""" + return self._concentration + + @property + def total_concentration(self): + """Sum of last dim of concentration parameter.""" + return self._total_concentration + + def _batch_shape_tensor(self): + return array_ops.shape(self.total_concentration) + + def _batch_shape(self): + return self.total_concentration.get_shape() + + def _event_shape_tensor(self): + return array_ops.shape(self.concentration)[-1:] + + def _event_shape(self): + return self.concentration.get_shape().with_rank_at_least(1)[-1:] + + def _sample_n(self, n, seed=None): + gamma_sample = random_ops.random_gamma( + shape=[n], + alpha=self.concentration, + dtype=self.dtype, + seed=seed) + return gamma_sample / math_ops.reduce_sum(gamma_sample, -1, keepdims=True) + + @distribution_util.AppendDocstring(_dirichlet_sample_note) + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + @distribution_util.AppendDocstring(_dirichlet_sample_note) + def _prob(self, x): + return math_ops.exp(self._log_prob(x)) + + def _log_unnormalized_prob(self, x): + x = self._maybe_assert_valid_sample(x) + return math_ops.reduce_sum(math_ops.xlogy(self.concentration - 1., x), -1) + + def _log_normalization(self): + return special_math_ops.lbeta(self.concentration) + + def _entropy(self): + k = math_ops.cast(self.event_shape_tensor()[0], self.dtype) + return ( + self._log_normalization() + + ((self.total_concentration - k) + * math_ops.digamma(self.total_concentration)) + - math_ops.reduce_sum( + (self.concentration - 1.) * math_ops.digamma(self.concentration), + axis=-1)) + + def _mean(self): + return self.concentration / self.total_concentration[..., array_ops.newaxis] + + def _covariance(self): + x = self._variance_scale_term() * self._mean() + # pylint: disable=invalid-unary-operand-type + return array_ops.matrix_set_diag( + -math_ops.matmul( + x[..., array_ops.newaxis], + x[..., array_ops.newaxis, :]), # outer prod + self._variance()) + + def _variance(self): + scale = self._variance_scale_term() + x = scale * self._mean() + return x * (scale - x) + + def _variance_scale_term(self): + """Helper to `_covariance` and `_variance` which computes a shared scale.""" + return math_ops.rsqrt(1. + self.total_concentration[..., array_ops.newaxis]) + + @distribution_util.AppendDocstring( + """Note: The mode is undefined when any `concentration <= 1`. If + `self.allow_nan_stats` is `True`, `NaN` is used for undefined modes. If + `self.allow_nan_stats` is `False` an exception is raised when one or more + modes are undefined.""") + def _mode(self): + k = math_ops.cast(self.event_shape_tensor()[0], self.dtype) + mode = (self.concentration - 1.) / ( + self.total_concentration[..., array_ops.newaxis] - k) + if self.allow_nan_stats: + nan = array_ops.fill( + array_ops.shape(mode), + np.array(np.nan, dtype=self.dtype.as_numpy_dtype()), + name="nan") + return array_ops.where_v2( + math_ops.reduce_all(self.concentration > 1., axis=-1), mode, nan) + return control_flow_ops.with_dependencies([ + check_ops.assert_less( + array_ops.ones([], self.dtype), + self.concentration, + message="Mode undefined when any concentration <= 1"), + ], mode) + + def _maybe_assert_valid_concentration(self, concentration, validate_args): + """Checks the validity of the concentration parameter.""" + if not validate_args: + return concentration + return control_flow_ops.with_dependencies([ + check_ops.assert_positive( + concentration, + message="Concentration parameter must be positive."), + check_ops.assert_rank_at_least( + concentration, 1, + message="Concentration parameter must have >=1 dimensions."), + check_ops.assert_less( + 1, array_ops.shape(concentration)[-1], + message="Concentration parameter must have event_size >= 2."), + ], concentration) + + def _maybe_assert_valid_sample(self, x): + """Checks the validity of a sample.""" + if not self.validate_args: + return x + return control_flow_ops.with_dependencies([ + check_ops.assert_positive(x, message="samples must be positive"), + check_ops.assert_near( + array_ops.ones([], dtype=self.dtype), + math_ops.reduce_sum(x, -1), + message="sample last-dimension must sum to `1`"), + ], x) + + +@kullback_leibler.RegisterKL(Dirichlet, Dirichlet) +def _kl_dirichlet_dirichlet(d1, d2, name=None): + """Batchwise KL divergence KL(d1 || d2) with d1 and d2 Dirichlet. + + Args: + d1: instance of a Dirichlet distribution object. + d2: instance of a Dirichlet distribution object. + name: (optional) Name to use for created operations. + default is "kl_dirichlet_dirichlet". + + Returns: + Batchwise KL(d1 || d2) + """ + with ops.name_scope(name, "kl_dirichlet_dirichlet", values=[ + d1.concentration, d2.concentration]): + # The KL between Dirichlet distributions can be derived as follows. We have + # + # Dir(x; a) = 1 / B(a) * prod_i[x[i]^(a[i] - 1)] + # + # where B(a) is the multivariate Beta function: + # + # B(a) = Gamma(a[1]) * ... * Gamma(a[n]) / Gamma(a[1] + ... + a[n]) + # + # The KL is + # + # KL(Dir(x; a), Dir(x; b)) = E_Dir(x; a){log(Dir(x; a) / Dir(x; b))} + # + # so we'll need to know the log density of the Dirichlet. This is + # + # log(Dir(x; a)) = sum_i[(a[i] - 1) log(x[i])] - log B(a) + # + # The only term that matters for the expectations is the log(x[i]). To + # compute the expectation of this term over the Dirichlet density, we can + # use the following facts about the Dirichlet in exponential family form: + # 1. log(x[i]) is a sufficient statistic + # 2. expected sufficient statistics (of any exp family distribution) are + # equal to derivatives of the log normalizer with respect to + # corresponding natural parameters: E{T[i](x)} = dA/d(eta[i]) + # + # To proceed, we can rewrite the Dirichlet density in exponential family + # form as follows: + # + # Dir(x; a) = exp{eta(a) . T(x) - A(a)} + # + # where '.' is the dot product of vectors eta and T, and A is a scalar: + # + # eta[i](a) = a[i] - 1 + # T[i](x) = log(x[i]) + # A(a) = log B(a) + # + # Now, we can use fact (2) above to write + # + # E_Dir(x; a)[log(x[i])] + # = dA(a) / da[i] + # = d/da[i] log B(a) + # = d/da[i] (sum_j lgamma(a[j])) - lgamma(sum_j a[j]) + # = digamma(a[i])) - digamma(sum_j a[j]) + # + # Putting it all together, we have + # + # KL[Dir(x; a) || Dir(x; b)] + # = E_Dir(x; a){log(Dir(x; a) / Dir(x; b)} + # = E_Dir(x; a){sum_i[(a[i] - b[i]) log(x[i])} - (lbeta(a) - lbeta(b)) + # = sum_i[(a[i] - b[i]) * E_Dir(x; a){log(x[i])}] - lbeta(a) + lbeta(b) + # = sum_i[(a[i] - b[i]) * (digamma(a[i]) - digamma(sum_j a[j]))] + # - lbeta(a) + lbeta(b)) + + digamma_sum_d1 = math_ops.digamma( + math_ops.reduce_sum(d1.concentration, axis=-1, keepdims=True)) + digamma_diff = math_ops.digamma(d1.concentration) - digamma_sum_d1 + concentration_diff = d1.concentration - d2.concentration + + return (math_ops.reduce_sum(concentration_diff * digamma_diff, axis=-1) - + special_math_ops.lbeta(d1.concentration) + + special_math_ops.lbeta(d2.concentration)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet_multinomial.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet_multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..947801cf1bf66dc0b24adbfa706fc3b7d3db0e17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/dirichlet_multinomial.py @@ -0,0 +1,353 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The DirichletMultinomial distribution class.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "DirichletMultinomial", +] + + +_dirichlet_multinomial_sample_note = """For each batch of counts, +`value = [n_0, ..., n_{K-1}]`, `P[value]` is the probability that after +sampling `self.total_count` draws from this Dirichlet-Multinomial distribution, +the number of draws falling in class `j` is `n_j`. Since this definition is +[exchangeable](https://en.wikipedia.org/wiki/Exchangeable_random_variables); +different sequences have the same counts so the probability includes a +combinatorial coefficient. + +Note: `value` must be a non-negative tensor with dtype `self.dtype`, have no +fractional components, and such that +`tf.reduce_sum(value, -1) = self.total_count`. Its shape must be broadcastable +with `self.concentration` and `self.total_count`.""" + + +@tf_export(v1=["distributions.DirichletMultinomial"]) +class DirichletMultinomial(distribution.Distribution): + """Dirichlet-Multinomial compound distribution. + + The Dirichlet-Multinomial distribution is parameterized by a (batch of) + length-`K` `concentration` vectors (`K > 1`) and a `total_count` number of + trials, i.e., the number of trials per draw from the DirichletMultinomial. It + is defined over a (batch of) length-`K` vector `counts` such that + `tf.reduce_sum(counts, -1) = total_count`. The Dirichlet-Multinomial is + identically the Beta-Binomial distribution when `K = 2`. + + #### Mathematical Details + + The Dirichlet-Multinomial is a distribution over `K`-class counts, i.e., a + length-`K` vector of non-negative integer `counts = n = [n_0, ..., n_{K-1}]`. + + The probability mass function (pmf) is, + + ```none + pmf(n; alpha, N) = Beta(alpha + n) / (prod_j n_j!) / Z + Z = Beta(alpha) / N! + ``` + + where: + + * `concentration = alpha = [alpha_0, ..., alpha_{K-1}]`, `alpha_j > 0`, + * `total_count = N`, `N` a positive integer, + * `N!` is `N` factorial, and, + * `Beta(x) = prod_j Gamma(x_j) / Gamma(sum_j x_j)` is the + [multivariate beta function]( + https://en.wikipedia.org/wiki/Beta_function#Multivariate_beta_function), + and, + * `Gamma` is the [gamma function]( + https://en.wikipedia.org/wiki/Gamma_function). + + Dirichlet-Multinomial is a [compound distribution]( + https://en.wikipedia.org/wiki/Compound_probability_distribution), i.e., its + samples are generated as follows. + + 1. Choose class probabilities: + `probs = [p_0,...,p_{K-1}] ~ Dir(concentration)` + 2. Draw integers: + `counts = [n_0,...,n_{K-1}] ~ Multinomial(total_count, probs)` + + The last `concentration` dimension parametrizes a single Dirichlet-Multinomial + distribution. When calling distribution functions (e.g., `dist.prob(counts)`), + `concentration`, `total_count` and `counts` are broadcast to the same shape. + The last dimension of `counts` corresponds single Dirichlet-Multinomial + distributions. + + Distribution parameters are automatically broadcast in all functions; see + examples for details. + + #### Pitfalls + + The number of classes, `K`, must not exceed: + - the largest integer representable by `self.dtype`, i.e., + `2**(mantissa_bits+1)` (IEE754), + - the maximum `Tensor` index, i.e., `2**31-1`. + + In other words, + + ```python + K <= min(2**31-1, { + tf.float16: 2**11, + tf.float32: 2**24, + tf.float64: 2**53 }[param.dtype]) + ``` + + Note: This condition is validated only when `self.validate_args = True`. + + #### Examples + + ```python + alpha = [1., 2., 3.] + n = 2. + dist = DirichletMultinomial(n, alpha) + ``` + + Creates a 3-class distribution, with the 3rd class is most likely to be + drawn. + The distribution functions can be evaluated on counts. + + ```python + # counts same shape as alpha. + counts = [0., 0., 2.] + dist.prob(counts) # Shape [] + + # alpha will be broadcast to [[1., 2., 3.], [1., 2., 3.]] to match counts. + counts = [[1., 1., 0.], [1., 0., 1.]] + dist.prob(counts) # Shape [2] + + # alpha will be broadcast to shape [5, 7, 3] to match counts. + counts = [[...]] # Shape [5, 7, 3] + dist.prob(counts) # Shape [5, 7] + ``` + + Creates a 2-batch of 3-class distributions. + + ```python + alpha = [[1., 2., 3.], [4., 5., 6.]] # Shape [2, 3] + n = [3., 3.] + dist = DirichletMultinomial(n, alpha) + + # counts will be broadcast to [[2., 1., 0.], [2., 1., 0.]] to match alpha. + counts = [2., 1., 0.] + dist.prob(counts) # Shape [2] + ``` + + """ + + # TODO(b/27419586) Change docstring for dtype of concentration once int + # allowed. + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + total_count, + concentration, + validate_args=False, + allow_nan_stats=True, + name="DirichletMultinomial"): + """Initialize a batch of DirichletMultinomial distributions. + + Args: + total_count: Non-negative floating point tensor, whose dtype is the same + as `concentration`. The shape is broadcastable to `[N1,..., Nm]` with + `m >= 0`. Defines this as a batch of `N1 x ... x Nm` different + Dirichlet multinomial distributions. Its components should be equal to + integer values. + concentration: Positive floating point tensor, whose dtype is the + same as `n` with shape broadcastable to `[N1,..., Nm, K]` `m >= 0`. + Defines this as a batch of `N1 x ... x Nm` different `K` class Dirichlet + multinomial distributions. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[total_count, concentration]) as name: + # Broadcasting works because: + # * The broadcasting convention is to prepend dimensions of size [1], and + # we use the last dimension for the distribution, whereas + # the batch dimensions are the leading dimensions, which forces the + # distribution dimension to be defined explicitly (i.e. it cannot be + # created automatically by prepending). This forces enough explicitness. + # * All calls involving `counts` eventually require a broadcast between + # `counts` and concentration. + self._total_count = ops.convert_to_tensor(total_count, name="total_count") + if validate_args: + self._total_count = ( + distribution_util.embed_check_nonnegative_integer_form( + self._total_count)) + self._concentration = self._maybe_assert_valid_concentration( + ops.convert_to_tensor(concentration, + name="concentration"), + validate_args) + self._total_concentration = math_ops.reduce_sum(self._concentration, -1) + super(DirichletMultinomial, self).__init__( + dtype=self._concentration.dtype, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + reparameterization_type=distribution.NOT_REPARAMETERIZED, + parameters=parameters, + graph_parents=[self._total_count, + self._concentration], + name=name) + + @property + def total_count(self): + """Number of trials used to construct a sample.""" + return self._total_count + + @property + def concentration(self): + """Concentration parameter; expected prior counts for that coordinate.""" + return self._concentration + + @property + def total_concentration(self): + """Sum of last dim of concentration parameter.""" + return self._total_concentration + + def _batch_shape_tensor(self): + return array_ops.shape(self.total_concentration) + + def _batch_shape(self): + return self.total_concentration.get_shape() + + def _event_shape_tensor(self): + return array_ops.shape(self.concentration)[-1:] + + def _event_shape(self): + # Event shape depends only on total_concentration, not "n". + return self.concentration.get_shape().with_rank_at_least(1)[-1:] + + def _sample_n(self, n, seed=None): + n_draws = math_ops.cast(self.total_count, dtype=dtypes.int32) + k = self.event_shape_tensor()[0] + unnormalized_logits = array_ops.reshape( + math_ops.log(random_ops.random_gamma( + shape=[n], + alpha=self.concentration, + dtype=self.dtype, + seed=seed)), + shape=[-1, k]) + draws = random_ops.multinomial( + logits=unnormalized_logits, + num_samples=n_draws, + seed=distribution_util.gen_new_seed(seed, salt="dirichlet_multinomial")) + x = math_ops.reduce_sum(array_ops.one_hot(draws, depth=k), -2) + final_shape = array_ops.concat([[n], self.batch_shape_tensor(), [k]], 0) + x = array_ops.reshape(x, final_shape) + return math_ops.cast(x, self.dtype) + + @distribution_util.AppendDocstring(_dirichlet_multinomial_sample_note) + def _log_prob(self, counts): + counts = self._maybe_assert_valid_sample(counts) + ordered_prob = ( + special_math_ops.lbeta(self.concentration + counts) + - special_math_ops.lbeta(self.concentration)) + return ordered_prob + distribution_util.log_combinations( + self.total_count, counts) + + @distribution_util.AppendDocstring(_dirichlet_multinomial_sample_note) + def _prob(self, counts): + return math_ops.exp(self._log_prob(counts)) + + def _mean(self): + return self.total_count * (self.concentration / + self.total_concentration[..., array_ops.newaxis]) + + @distribution_util.AppendDocstring( + """The covariance for each batch member is defined as the following: + + ```none + Var(X_j) = n * alpha_j / alpha_0 * (1 - alpha_j / alpha_0) * + (n + alpha_0) / (1 + alpha_0) + ``` + + where `concentration = alpha` and + `total_concentration = alpha_0 = sum_j alpha_j`. + + The covariance between elements in a batch is defined as: + + ```none + Cov(X_i, X_j) = -n * alpha_i * alpha_j / alpha_0 ** 2 * + (n + alpha_0) / (1 + alpha_0) + ``` + """) + def _covariance(self): + x = self._variance_scale_term() * self._mean() + # pylint: disable=invalid-unary-operand-type + return array_ops.matrix_set_diag( + -math_ops.matmul( + x[..., array_ops.newaxis], + x[..., array_ops.newaxis, :]), # outer prod + self._variance()) + + def _variance(self): + scale = self._variance_scale_term() + x = scale * self._mean() + return x * (self.total_count * scale - x) + + def _variance_scale_term(self): + """Helper to `_covariance` and `_variance` which computes a shared scale.""" + # We must take care to expand back the last dim whenever we use the + # total_concentration. + c0 = self.total_concentration[..., array_ops.newaxis] + return math_ops.sqrt((1. + c0 / self.total_count) / (1. + c0)) + + def _maybe_assert_valid_concentration(self, concentration, validate_args): + """Checks the validity of the concentration parameter.""" + if not validate_args: + return concentration + concentration = distribution_util.embed_check_categorical_event_shape( + concentration) + return control_flow_ops.with_dependencies([ + check_ops.assert_positive( + concentration, + message="Concentration parameter must be positive."), + ], concentration) + + def _maybe_assert_valid_sample(self, counts): + """Check counts for proper shape, values, then return tensor version.""" + if not self.validate_args: + return counts + counts = distribution_util.embed_check_nonnegative_integer_form(counts) + return control_flow_ops.with_dependencies([ + check_ops.assert_equal( + self.total_count, math_ops.reduce_sum(counts, -1), + message="counts last-dimension must sum to `self.total_count`"), + ], counts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distribution.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..09d9e2a507d7ded2170735b72088c59ae15ab8fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distribution.py @@ -0,0 +1,1316 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base classes for probability distributions.""" + +import abc +import contextlib +import types + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util +from tensorflow.python.util import deprecation +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "ReparameterizationType", + "FULLY_REPARAMETERIZED", + "NOT_REPARAMETERIZED", + "Distribution", +] + +_DISTRIBUTION_PUBLIC_METHOD_WRAPPERS = [ + "batch_shape", + "batch_shape_tensor", + "cdf", + "covariance", + "cross_entropy", + "entropy", + "event_shape", + "event_shape_tensor", + "kl_divergence", + "log_cdf", + "log_prob", + "log_survival_function", + "mean", + "mode", + "prob", + "sample", + "stddev", + "survival_function", + "variance", +] + + +class _BaseDistribution(metaclass=abc.ABCMeta): + """Abstract base class needed for resolving subclass hierarchy.""" + pass + + +def _copy_fn(fn): + """Create a deep copy of fn. + + Args: + fn: a callable + + Returns: + A `FunctionType`: a deep copy of fn. + + Raises: + TypeError: if `fn` is not a callable. + """ + if not callable(fn): + raise TypeError("fn is not callable: %s" % fn) + # The blessed way to copy a function. copy.deepcopy fails to create a + # non-reference copy. Since: + # types.FunctionType == type(lambda: None), + # and the docstring for the function type states: + # + # function(code, globals[, name[, argdefs[, closure]]]) + # + # Create a function object from a code object and a dictionary. + # ... + # + # Here we can use this to create a new function with the old function's + # code, globals, closure, etc. + return types.FunctionType( + code=fn.__code__, globals=fn.__globals__, + name=fn.__name__, argdefs=fn.__defaults__, + closure=fn.__closure__) + + +def _update_docstring(old_str, append_str): + """Update old_str by inserting append_str just before the "Args:" section.""" + old_str = old_str or "" + old_str_lines = old_str.split("\n") + + # Step 0: Prepend spaces to all lines of append_str. This is + # necessary for correct markdown generation. + append_str = "\n".join(" %s" % line for line in append_str.split("\n")) + + # Step 1: Find mention of "Args": + has_args_ix = [ + ix for ix, line in enumerate(old_str_lines) + if line.strip().lower() == "args:"] + if has_args_ix: + final_args_ix = has_args_ix[-1] + return ("\n".join(old_str_lines[:final_args_ix]) + + "\n\n" + append_str + "\n\n" + + "\n".join(old_str_lines[final_args_ix:])) + else: + return old_str + "\n\n" + append_str + + +def _convert_to_tensor(value, name=None, preferred_dtype=None): + """Converts to tensor avoiding an eager bug that loses float precision.""" + # TODO(b/116672045): Remove this function. + if (context.executing_eagerly() and preferred_dtype is not None and + (preferred_dtype.is_integer or preferred_dtype.is_bool)): + v = ops.convert_to_tensor(value, name=name) + if v.dtype.is_floating: + return v + return ops.convert_to_tensor( + value, name=name, preferred_dtype=preferred_dtype) + + +class _DistributionMeta(abc.ABCMeta): + + def __new__(mcs, classname, baseclasses, attrs): + """Control the creation of subclasses of the Distribution class. + + The main purpose of this method is to properly propagate docstrings + from private Distribution methods, like `_log_prob`, into their + public wrappers as inherited by the Distribution base class + (e.g. `log_prob`). + + Args: + classname: The name of the subclass being created. + baseclasses: A tuple of parent classes. + attrs: A dict mapping new attributes to their values. + + Returns: + The class object. + + Raises: + TypeError: If `Distribution` is not a subclass of `BaseDistribution`, or + the new class is derived via multiple inheritance and the first + parent class is not a subclass of `BaseDistribution`. + AttributeError: If `Distribution` does not implement e.g. `log_prob`. + ValueError: If a `Distribution` public method lacks a docstring. + """ + if not baseclasses: # Nothing to be done for Distribution + raise TypeError("Expected non-empty baseclass. Does Distribution " + "not subclass _BaseDistribution?") + which_base = [ + base for base in baseclasses + if base == _BaseDistribution or issubclass(base, Distribution)] + base = which_base[0] + if base == _BaseDistribution: # Nothing to be done for Distribution + return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs) + if not issubclass(base, Distribution): + raise TypeError("First parent class declared for %s must be " + "Distribution, but saw '%s'" % (classname, base.__name__)) + for attr in _DISTRIBUTION_PUBLIC_METHOD_WRAPPERS: + special_attr = "_%s" % attr + class_attr_value = attrs.get(attr, None) + if attr in attrs: + # The method is being overridden, do not update its docstring + continue + base_attr_value = getattr(base, attr, None) + if not base_attr_value: + raise AttributeError( + "Internal error: expected base class '%s' to implement method '%s'" + % (base.__name__, attr)) + class_special_attr_value = attrs.get(special_attr, None) + if class_special_attr_value is None: + # No _special method available, no need to update the docstring. + continue + class_special_attr_docstring = tf_inspect.getdoc(class_special_attr_value) + if not class_special_attr_docstring: + # No docstring to append. + continue + class_attr_value = _copy_fn(base_attr_value) + class_attr_docstring = tf_inspect.getdoc(base_attr_value) + if class_attr_docstring is None: + raise ValueError( + "Expected base class fn to contain a docstring: %s.%s" + % (base.__name__, attr)) + class_attr_value.__doc__ = _update_docstring( + class_attr_value.__doc__, + ("Additional documentation from `%s`:\n\n%s" + % (classname, class_special_attr_docstring))) + attrs[attr] = class_attr_value + + return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs) + + +@tf_export(v1=["distributions.ReparameterizationType"]) +class ReparameterizationType: + """Instances of this class represent how sampling is reparameterized. + + Two static instances exist in the distributions library, signifying + one of two possible properties for samples from a distribution: + + `FULLY_REPARAMETERIZED`: Samples from the distribution are fully + reparameterized, and straight-through gradients are supported. + + `NOT_REPARAMETERIZED`: Samples from the distribution are not fully + reparameterized, and straight-through gradients are either partially + unsupported or are not supported at all. In this case, for purposes of + e.g. RL or variational inference, it is generally safest to wrap the + sample results in a `stop_gradients` call and use policy + gradients / surrogate loss instead. + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, rep_type): + self._rep_type = rep_type + + def __repr__(self): + return "" % self._rep_type + + def __eq__(self, other): + """Determine if this `ReparameterizationType` is equal to another. + + Since ReparameterizationType instances are constant static global + instances, equality checks if two instances' id() values are equal. + + Args: + other: Object to compare against. + + Returns: + `self is other`. + """ + return self is other + + +# Fully reparameterized distribution: samples from a fully +# reparameterized distribution support straight-through gradients with +# respect to all parameters. +FULLY_REPARAMETERIZED = ReparameterizationType("FULLY_REPARAMETERIZED") +tf_export(v1=["distributions.FULLY_REPARAMETERIZED"]).export_constant( + __name__, "FULLY_REPARAMETERIZED") + + +# Not reparameterized distribution: samples from a non- +# reparameterized distribution do not support straight-through gradients for +# at least some of the parameters. +NOT_REPARAMETERIZED = ReparameterizationType("NOT_REPARAMETERIZED") +tf_export(v1=["distributions.NOT_REPARAMETERIZED"]).export_constant( + __name__, "NOT_REPARAMETERIZED") + + +@tf_export(v1=["distributions.Distribution"]) +class Distribution(_BaseDistribution, metaclass=_DistributionMeta): + """A generic probability distribution base class. + + `Distribution` is a base class for constructing and organizing properties + (e.g., mean, variance) of random variables (e.g, Bernoulli, Gaussian). + + #### Subclassing + + Subclasses are expected to implement a leading-underscore version of the + same-named function. The argument signature should be identical except for + the omission of `name="..."`. For example, to enable `log_prob(value, + name="log_prob")` a subclass should implement `_log_prob(value)`. + + Subclasses can append to public-level docstrings by providing + docstrings for their method specializations. For example: + + ```python + @util.AppendDocstring("Some other details.") + def _log_prob(self, value): + ... + ``` + + would add the string "Some other details." to the `log_prob` function + docstring. This is implemented as a simple decorator to avoid python + linter complaining about missing Args/Returns/Raises sections in the + partial docstrings. + + #### Broadcasting, batching, and shapes + + All distributions support batches of independent distributions of that type. + The batch shape is determined by broadcasting together the parameters. + + The shape of arguments to `__init__`, `cdf`, `log_cdf`, `prob`, and + `log_prob` reflect this broadcasting, as does the return value of `sample` and + `sample_n`. + + `sample_n_shape = [n] + batch_shape + event_shape`, where `sample_n_shape` is + the shape of the `Tensor` returned from `sample_n`, `n` is the number of + samples, `batch_shape` defines how many independent distributions there are, + and `event_shape` defines the shape of samples from each of those independent + distributions. Samples are independent along the `batch_shape` dimensions, but + not necessarily so along the `event_shape` dimensions (depending on the + particulars of the underlying distribution). + + Using the `Uniform` distribution as an example: + + ```python + minval = 3.0 + maxval = [[4.0, 6.0], + [10.0, 12.0]] + + # Broadcasting: + # This instance represents 4 Uniform distributions. Each has a lower bound at + # 3.0 as the `minval` parameter was broadcasted to match `maxval`'s shape. + u = Uniform(minval, maxval) + + # `event_shape` is `TensorShape([])`. + event_shape = u.event_shape + # `event_shape_t` is a `Tensor` which will evaluate to []. + event_shape_t = u.event_shape_tensor() + + # Sampling returns a sample per distribution. `samples` has shape + # [5, 2, 2], which is [n] + batch_shape + event_shape, where n=5, + # batch_shape=[2, 2], and event_shape=[]. + samples = u.sample_n(5) + + # The broadcasting holds across methods. Here we use `cdf` as an example. The + # same holds for `log_cdf` and the likelihood functions. + + # `cum_prob` has shape [2, 2] as the `value` argument was broadcasted to the + # shape of the `Uniform` instance. + cum_prob_broadcast = u.cdf(4.0) + + # `cum_prob`'s shape is [2, 2], one per distribution. No broadcasting + # occurred. + cum_prob_per_dist = u.cdf([[4.0, 5.0], + [6.0, 7.0]]) + + # INVALID as the `value` argument is not broadcastable to the distribution's + # shape. + cum_prob_invalid = u.cdf([4.0, 5.0, 6.0]) + ``` + + #### Shapes + + There are three important concepts associated with TensorFlow Distributions + shapes: + - Event shape describes the shape of a single draw from the distribution; + it may be dependent across dimensions. For scalar distributions, the event + shape is `[]`. For a 5-dimensional MultivariateNormal, the event shape is + `[5]`. + - Batch shape describes independent, not identically distributed draws, aka a + "collection" or "bunch" of distributions. + - Sample shape describes independent, identically distributed draws of batches + from the distribution family. + + The event shape and the batch shape are properties of a Distribution object, + whereas the sample shape is associated with a specific call to `sample` or + `log_prob`. + + For detailed usage examples of TensorFlow Distributions shapes, see + [this tutorial]( + https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/jupyter_notebooks/Understanding_TensorFlow_Distributions_Shapes.ipynb) + + #### Parameter values leading to undefined statistics or distributions. + + Some distributions do not have well-defined statistics for all initialization + parameter values. For example, the beta distribution is parameterized by + positive real numbers `concentration1` and `concentration0`, and does not have + well-defined mode if `concentration1 < 1` or `concentration0 < 1`. + + The user is given the option of raising an exception or returning `NaN`. + + ```python + a = tf.exp(tf.matmul(logits, weights_a)) + b = tf.exp(tf.matmul(logits, weights_b)) + + # Will raise exception if ANY batch member has a < 1 or b < 1. + dist = distributions.beta(a, b, allow_nan_stats=False) + mode = dist.mode().eval() + + # Will return NaN for batch members with either a < 1 or b < 1. + dist = distributions.beta(a, b, allow_nan_stats=True) # Default behavior + mode = dist.mode().eval() + ``` + + In all cases, an exception is raised if *invalid* parameters are passed, e.g. + + ```python + # Will raise an exception if any Op is run. + negative_a = -1.0 * a # beta distribution by definition has a > 0. + dist = distributions.beta(negative_a, b, allow_nan_stats=True) + dist.mean().eval() + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + dtype, + reparameterization_type, + validate_args, + allow_nan_stats, + parameters=None, + graph_parents=None, + name=None): + """Constructs the `Distribution`. + + **This is a private method for subclass use.** + + Args: + dtype: The type of the event samples. `None` implies no type-enforcement. + reparameterization_type: Instance of `ReparameterizationType`. + If `distributions.FULLY_REPARAMETERIZED`, this + `Distribution` can be reparameterized in terms of some standard + distribution with a function whose Jacobian is constant for the support + of the standard distribution. If `distributions.NOT_REPARAMETERIZED`, + then no such reparameterization is available. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + parameters: Python `dict` of parameters used to instantiate this + `Distribution`. + graph_parents: Python `list` of graph prerequisites of this + `Distribution`. + name: Python `str` name prefixed to Ops created by this class. Default: + subclass name. + + Raises: + ValueError: if any member of graph_parents is `None` or not a `Tensor`. + """ + graph_parents = [] if graph_parents is None else graph_parents + for i, t in enumerate(graph_parents): + if t is None or not tensor_util.is_tf_type(t): + raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t)) + if not name or name[-1] != "/": # `name` is not a name scope + non_unique_name = name or type(self).__name__ + with ops.name_scope(non_unique_name) as name: + pass + self._dtype = dtype + self._reparameterization_type = reparameterization_type + self._allow_nan_stats = allow_nan_stats + self._validate_args = validate_args + self._parameters = parameters or {} + self._graph_parents = graph_parents + self._name = name + + @property + def _parameters(self): + return self._parameter_dict + + @_parameters.setter + def _parameters(self, value): + """Intercept assignments to self._parameters to avoid reference cycles. + + Parameters are often created using locals(), so we need to clean out any + references to `self` before assigning it to an attribute. + + Args: + value: A dictionary of parameters to assign to the `_parameters` property. + """ + if "self" in value: + del value["self"] + self._parameter_dict = value + + @classmethod + def param_shapes(cls, sample_shape, name="DistributionParamShapes"): + """Shapes of parameters given the desired shape of a call to `sample()`. + + This is a class method that describes what key/value arguments are required + to instantiate the given `Distribution` so that a particular shape is + returned for that instance's call to `sample()`. + + Subclasses should override class method `_param_shapes`. + + Args: + sample_shape: `Tensor` or python list/tuple. Desired shape of a call to + `sample()`. + name: name to prepend ops with. + + Returns: + `dict` of parameter name to `Tensor` shapes. + """ + with ops.name_scope(name, values=[sample_shape]): + return cls._param_shapes(sample_shape) + + @classmethod + def param_static_shapes(cls, sample_shape): + """param_shapes with static (i.e. `TensorShape`) shapes. + + This is a class method that describes what key/value arguments are required + to instantiate the given `Distribution` so that a particular shape is + returned for that instance's call to `sample()`. Assumes that the sample's + shape is known statically. + + Subclasses should override class method `_param_shapes` to return + constant-valued tensors when constant values are fed. + + Args: + sample_shape: `TensorShape` or python list/tuple. Desired shape of a call + to `sample()`. + + Returns: + `dict` of parameter name to `TensorShape`. + + Raises: + ValueError: if `sample_shape` is a `TensorShape` and is not fully defined. + """ + if isinstance(sample_shape, tensor_shape.TensorShape): + if not sample_shape.is_fully_defined(): + raise ValueError("TensorShape sample_shape must be fully defined") + sample_shape = sample_shape.as_list() + + params = cls.param_shapes(sample_shape) + + static_params = {} + for name, shape in params.items(): + static_shape = tensor_util.constant_value(shape) + if static_shape is None: + raise ValueError( + "sample_shape must be a fully-defined TensorShape or list/tuple") + static_params[name] = tensor_shape.TensorShape(static_shape) + + return static_params + + @staticmethod + def _param_shapes(sample_shape): + raise NotImplementedError("_param_shapes not implemented") + + @property + def name(self): + """Name prepended to all ops created by this `Distribution`.""" + return self._name + + @property + def dtype(self): + """The `DType` of `Tensor`s handled by this `Distribution`.""" + return self._dtype + + @property + def parameters(self): + """Dictionary of parameters used to instantiate this `Distribution`.""" + # Remove "self", "__class__", or other special variables. These can appear + # if the subclass used: + # `parameters = dict(locals())`. + return {k: v for k, v in self._parameters.items() + if not k.startswith("__") and k != "self"} + + @property + def reparameterization_type(self): + """Describes how samples from the distribution are reparameterized. + + Currently this is one of the static instances + `distributions.FULLY_REPARAMETERIZED` + or `distributions.NOT_REPARAMETERIZED`. + + Returns: + An instance of `ReparameterizationType`. + """ + return self._reparameterization_type + + @property + def allow_nan_stats(self): + """Python `bool` describing behavior when a stat is undefined. + + Stats return +/- infinity when it makes sense. E.g., the variance of a + Cauchy distribution is infinity. However, sometimes the statistic is + undefined, e.g., if a distribution's pdf does not achieve a maximum within + the support of the distribution, the mode is undefined. If the mean is + undefined, then by definition the variance is undefined. E.g. the mean for + Student's T for df = 1 is undefined (no clear way to say it is either + or - + infinity), so the variance = E[(X - mean)**2] is also undefined. + + Returns: + allow_nan_stats: Python `bool`. + """ + return self._allow_nan_stats + + @property + def validate_args(self): + """Python `bool` indicating possibly expensive checks are enabled.""" + return self._validate_args + + def copy(self, **override_parameters_kwargs): + """Creates a deep copy of the distribution. + + Note: the copy distribution may continue to depend on the original + initialization arguments. + + Args: + **override_parameters_kwargs: String/value dictionary of initialization + arguments to override with new values. + + Returns: + distribution: A new instance of `type(self)` initialized from the union + of self.parameters and override_parameters_kwargs, i.e., + `dict(self.parameters, **override_parameters_kwargs)`. + """ + parameters = dict(self.parameters, **override_parameters_kwargs) + return type(self)(**parameters) + + def _batch_shape_tensor(self): + raise NotImplementedError( + "batch_shape_tensor is not implemented: {}".format(type(self).__name__)) + + def batch_shape_tensor(self, name="batch_shape_tensor"): + """Shape of a single sample from a single event index as a 1-D `Tensor`. + + The batch dimensions are indexes into independent, non-identical + parameterizations of this distribution. + + Args: + name: name to give to the op + + Returns: + batch_shape: `Tensor`. + """ + with self._name_scope(name): + if self.batch_shape.is_fully_defined(): + return ops.convert_to_tensor(self.batch_shape.as_list(), + dtype=dtypes.int32, + name="batch_shape") + return self._batch_shape_tensor() + + def _batch_shape(self): + return tensor_shape.TensorShape(None) + + @property + def batch_shape(self): + """Shape of a single sample from a single event index as a `TensorShape`. + + May be partially defined or unknown. + + The batch dimensions are indexes into independent, non-identical + parameterizations of this distribution. + + Returns: + batch_shape: `TensorShape`, possibly unknown. + """ + return tensor_shape.as_shape(self._batch_shape()) + + def _event_shape_tensor(self): + raise NotImplementedError( + "event_shape_tensor is not implemented: {}".format(type(self).__name__)) + + def event_shape_tensor(self, name="event_shape_tensor"): + """Shape of a single sample from a single batch as a 1-D int32 `Tensor`. + + Args: + name: name to give to the op + + Returns: + event_shape: `Tensor`. + """ + with self._name_scope(name): + if self.event_shape.is_fully_defined(): + return ops.convert_to_tensor(self.event_shape.as_list(), + dtype=dtypes.int32, + name="event_shape") + return self._event_shape_tensor() + + def _event_shape(self): + return tensor_shape.TensorShape(None) + + @property + def event_shape(self): + """Shape of a single sample from a single batch as a `TensorShape`. + + May be partially defined or unknown. + + Returns: + event_shape: `TensorShape`, possibly unknown. + """ + return tensor_shape.as_shape(self._event_shape()) + + def is_scalar_event(self, name="is_scalar_event"): + """Indicates that `event_shape == []`. + + Args: + name: Python `str` prepended to names of ops created by this function. + + Returns: + is_scalar_event: `bool` scalar `Tensor`. + """ + with self._name_scope(name): + return ops.convert_to_tensor( + self._is_scalar_helper(self.event_shape, self.event_shape_tensor), + name="is_scalar_event") + + def is_scalar_batch(self, name="is_scalar_batch"): + """Indicates that `batch_shape == []`. + + Args: + name: Python `str` prepended to names of ops created by this function. + + Returns: + is_scalar_batch: `bool` scalar `Tensor`. + """ + with self._name_scope(name): + return ops.convert_to_tensor( + self._is_scalar_helper(self.batch_shape, self.batch_shape_tensor), + name="is_scalar_batch") + + def _sample_n(self, n, seed=None): + raise NotImplementedError("sample_n is not implemented: {}".format( + type(self).__name__)) + + def _call_sample_n(self, sample_shape, seed, name, **kwargs): + with self._name_scope(name, values=[sample_shape]): + sample_shape = ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32, name="sample_shape") + sample_shape, n = self._expand_sample_shape_to_vector( + sample_shape, "sample_shape") + samples = self._sample_n(n, seed, **kwargs) + batch_event_shape = array_ops.shape(samples)[1:] + final_shape = array_ops.concat([sample_shape, batch_event_shape], 0) + samples = array_ops.reshape(samples, final_shape) + samples = self._set_sample_static_shape(samples, sample_shape) + return samples + + def sample(self, sample_shape=(), seed=None, name="sample"): + """Generate samples of the specified shape. + + Note that a call to `sample()` without arguments will generate a single + sample. + + Args: + sample_shape: 0D or 1D `int32` `Tensor`. Shape of the generated samples. + seed: Python integer seed for RNG + name: name to give to the op. + + Returns: + samples: a `Tensor` with prepended dimensions `sample_shape`. + """ + return self._call_sample_n(sample_shape, seed, name) + + def _log_prob(self, value): + raise NotImplementedError("log_prob is not implemented: {}".format( + type(self).__name__)) + + def _call_log_prob(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._log_prob(value, **kwargs) + except NotImplementedError as original_exception: + try: + return math_ops.log(self._prob(value, **kwargs)) + except NotImplementedError: + raise original_exception + + def log_prob(self, value, name="log_prob"): + """Log probability density/mass function. + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + log_prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + """ + return self._call_log_prob(value, name) + + def _prob(self, value): + raise NotImplementedError("prob is not implemented: {}".format( + type(self).__name__)) + + def _call_prob(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._prob(value, **kwargs) + except NotImplementedError as original_exception: + try: + return math_ops.exp(self._log_prob(value, **kwargs)) + except NotImplementedError: + raise original_exception + + def prob(self, value, name="prob"): + """Probability density/mass function. + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + prob: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + """ + return self._call_prob(value, name) + + def _log_cdf(self, value): + raise NotImplementedError("log_cdf is not implemented: {}".format( + type(self).__name__)) + + def _call_log_cdf(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._log_cdf(value, **kwargs) + except NotImplementedError as original_exception: + try: + return math_ops.log(self._cdf(value, **kwargs)) + except NotImplementedError: + raise original_exception + + def log_cdf(self, value, name="log_cdf"): + """Log cumulative distribution function. + + Given random variable `X`, the cumulative distribution function `cdf` is: + + ```none + log_cdf(x) := Log[ P[X <= x] ] + ``` + + Often, a numerical approximation can be used for `log_cdf(x)` that yields + a more accurate answer than simply taking the logarithm of the `cdf` when + `x << -1`. + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + logcdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + """ + return self._call_log_cdf(value, name) + + def _cdf(self, value): + raise NotImplementedError("cdf is not implemented: {}".format( + type(self).__name__)) + + def _call_cdf(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._cdf(value, **kwargs) + except NotImplementedError as original_exception: + try: + return math_ops.exp(self._log_cdf(value, **kwargs)) + except NotImplementedError: + raise original_exception + + def cdf(self, value, name="cdf"): + """Cumulative distribution function. + + Given random variable `X`, the cumulative distribution function `cdf` is: + + ```none + cdf(x) := P[X <= x] + ``` + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + cdf: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + """ + return self._call_cdf(value, name) + + def _log_survival_function(self, value): + raise NotImplementedError( + "log_survival_function is not implemented: {}".format( + type(self).__name__)) + + def _call_log_survival_function(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._log_survival_function(value, **kwargs) + except NotImplementedError as original_exception: + try: + return math_ops.log1p(-self.cdf(value, **kwargs)) + except NotImplementedError: + raise original_exception + + def log_survival_function(self, value, name="log_survival_function"): + """Log survival function. + + Given random variable `X`, the survival function is defined: + + ```none + log_survival_function(x) = Log[ P[X > x] ] + = Log[ 1 - P[X <= x] ] + = Log[ 1 - cdf(x) ] + ``` + + Typically, different numerical approximations can be used for the log + survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`. + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + """ + return self._call_log_survival_function(value, name) + + def _survival_function(self, value): + raise NotImplementedError("survival_function is not implemented: {}".format( + type(self).__name__)) + + def _call_survival_function(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + try: + return self._survival_function(value, **kwargs) + except NotImplementedError as original_exception: + try: + return 1. - self.cdf(value, **kwargs) + except NotImplementedError: + raise original_exception + + def survival_function(self, value, name="survival_function"): + """Survival function. + + Given random variable `X`, the survival function is defined: + + ```none + survival_function(x) = P[X > x] + = 1 - P[X <= x] + = 1 - cdf(x). + ``` + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type + `self.dtype`. + """ + return self._call_survival_function(value, name) + + def _entropy(self): + raise NotImplementedError("entropy is not implemented: {}".format( + type(self).__name__)) + + def entropy(self, name="entropy"): + """Shannon entropy in nats.""" + with self._name_scope(name): + return self._entropy() + + def _mean(self): + raise NotImplementedError("mean is not implemented: {}".format( + type(self).__name__)) + + def mean(self, name="mean"): + """Mean.""" + with self._name_scope(name): + return self._mean() + + def _quantile(self, value): + raise NotImplementedError("quantile is not implemented: {}".format( + type(self).__name__)) + + def _call_quantile(self, value, name, **kwargs): + with self._name_scope(name, values=[value]): + value = _convert_to_tensor( + value, name="value", preferred_dtype=self.dtype) + return self._quantile(value, **kwargs) + + def quantile(self, value, name="quantile"): + """Quantile function. Aka "inverse cdf" or "percent point function". + + Given random variable `X` and `p in [0, 1]`, the `quantile` is: + + ```none + quantile(p) := x such that P[X <= x] == p + ``` + + Args: + value: `float` or `double` `Tensor`. + name: Python `str` prepended to names of ops created by this function. + + Returns: + quantile: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with + values of type `self.dtype`. + """ + return self._call_quantile(value, name) + + def _variance(self): + raise NotImplementedError("variance is not implemented: {}".format( + type(self).__name__)) + + def variance(self, name="variance"): + """Variance. + + Variance is defined as, + + ```none + Var = E[(X - E[X])**2] + ``` + + where `X` is the random variable associated with this distribution, `E` + denotes expectation, and `Var.shape = batch_shape + event_shape`. + + Args: + name: Python `str` prepended to names of ops created by this function. + + Returns: + variance: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + """ + with self._name_scope(name): + try: + return self._variance() + except NotImplementedError as original_exception: + try: + return math_ops.square(self._stddev()) + except NotImplementedError: + raise original_exception + + def _stddev(self): + raise NotImplementedError("stddev is not implemented: {}".format( + type(self).__name__)) + + def stddev(self, name="stddev"): + """Standard deviation. + + Standard deviation is defined as, + + ```none + stddev = E[(X - E[X])**2]**0.5 + ``` + + where `X` is the random variable associated with this distribution, `E` + denotes expectation, and `stddev.shape = batch_shape + event_shape`. + + Args: + name: Python `str` prepended to names of ops created by this function. + + Returns: + stddev: Floating-point `Tensor` with shape identical to + `batch_shape + event_shape`, i.e., the same shape as `self.mean()`. + """ + + with self._name_scope(name): + try: + return self._stddev() + except NotImplementedError as original_exception: + try: + return math_ops.sqrt(self._variance()) + except NotImplementedError: + raise original_exception + + def _covariance(self): + raise NotImplementedError("covariance is not implemented: {}".format( + type(self).__name__)) + + def covariance(self, name="covariance"): + """Covariance. + + Covariance is (possibly) defined only for non-scalar-event distributions. + + For example, for a length-`k`, vector-valued distribution, it is calculated + as, + + ```none + Cov[i, j] = Covariance(X_i, X_j) = E[(X_i - E[X_i]) (X_j - E[X_j])] + ``` + + where `Cov` is a (batch of) `k x k` matrix, `0 <= (i, j) < k`, and `E` + denotes expectation. + + Alternatively, for non-vector, multivariate distributions (e.g., + matrix-valued, Wishart), `Covariance` shall return a (batch of) matrices + under some vectorization of the events, i.e., + + ```none + Cov[i, j] = Covariance(Vec(X)_i, Vec(X)_j) = [as above] + ``` + + where `Cov` is a (batch of) `k' x k'` matrices, + `0 <= (i, j) < k' = reduce_prod(event_shape)`, and `Vec` is some function + mapping indices of this distribution's event dimensions to indices of a + length-`k'` vector. + + Args: + name: Python `str` prepended to names of ops created by this function. + + Returns: + covariance: Floating-point `Tensor` with shape `[B1, ..., Bn, k', k']` + where the first `n` dimensions are batch coordinates and + `k' = reduce_prod(self.event_shape)`. + """ + with self._name_scope(name): + return self._covariance() + + def _mode(self): + raise NotImplementedError("mode is not implemented: {}".format( + type(self).__name__)) + + def mode(self, name="mode"): + """Mode.""" + with self._name_scope(name): + return self._mode() + + def _cross_entropy(self, other): + return kullback_leibler.cross_entropy( + self, other, allow_nan_stats=self.allow_nan_stats) + + def cross_entropy(self, other, name="cross_entropy"): + """Computes the (Shannon) cross entropy. + + Denote this distribution (`self`) by `P` and the `other` distribution by + `Q`. Assuming `P, Q` are absolutely continuous with respect to + one another and permit densities `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) + cross entropy is defined as: + + ```none + H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) + ``` + + where `F` denotes the support of the random variable `X ~ P`. + + Args: + other: `tfp.distributions.Distribution` instance. + name: Python `str` prepended to names of ops created by this function. + + Returns: + cross_entropy: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + """ + with self._name_scope(name): + return self._cross_entropy(other) + + def _kl_divergence(self, other): + return kullback_leibler.kl_divergence( + self, other, allow_nan_stats=self.allow_nan_stats) + + def kl_divergence(self, other, name="kl_divergence"): + """Computes the Kullback--Leibler divergence. + + Denote this distribution (`self`) by `p` and the `other` distribution by + `q`. Assuming `p, q` are absolutely continuous with respect to reference + measure `r`, the KL divergence is defined as: + + ```none + KL[p, q] = E_p[log(p(X)/q(X))] + = -int_F p(x) log q(x) dr(x) + int_F p(x) log p(x) dr(x) + = H[p, q] - H[p] + ``` + + where `F` denotes the support of the random variable `X ~ p`, `H[., .]` + denotes (Shanon) cross entropy, and `H[.]` denotes (Shanon) entropy. + + Args: + other: `tfp.distributions.Distribution` instance. + name: Python `str` prepended to names of ops created by this function. + + Returns: + kl_divergence: `self.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of the Kullback-Leibler + divergence. + """ + with self._name_scope(name): + return self._kl_divergence(other) + + def __str__(self): + return ("tfp.distributions.{type_name}(" + "\"{self_name}\"" + "{maybe_batch_shape}" + "{maybe_event_shape}" + ", dtype={dtype})".format( + type_name=type(self).__name__, + self_name=self.name, + maybe_batch_shape=(", batch_shape={}".format(self.batch_shape) + if self.batch_shape.ndims is not None + else ""), + maybe_event_shape=(", event_shape={}".format(self.event_shape) + if self.event_shape.ndims is not None + else ""), + dtype=self.dtype.name)) + + def __repr__(self): + return ("".format( + type_name=type(self).__name__, + self_name=self.name, + batch_shape=self.batch_shape, + event_shape=self.event_shape, + dtype=self.dtype.name)) + + @contextlib.contextmanager + def _name_scope(self, name=None, values=None): + """Helper function to standardize op scope.""" + with ops.name_scope(self.name): + with ops.name_scope(name, values=( + ([] if values is None else values) + self._graph_parents)) as scope: + yield scope + + def _expand_sample_shape_to_vector(self, x, name): + """Helper to `sample` which ensures input is 1D.""" + x_static_val = tensor_util.constant_value(x) + if x_static_val is None: + prod = math_ops.reduce_prod(x) + else: + prod = np.prod(x_static_val, dtype=x.dtype.as_numpy_dtype()) + + ndims = x.get_shape().ndims # != sample_ndims + if ndims is None: + # Maybe expand_dims. + ndims = array_ops.rank(x) + expanded_shape = util.pick_vector( + math_ops.equal(ndims, 0), + np.array([1], dtype=np.int32), array_ops.shape(x)) + x = array_ops.reshape(x, expanded_shape) + elif ndims == 0: + # Definitely expand_dims. + if x_static_val is not None: + x = ops.convert_to_tensor( + np.array([x_static_val], dtype=x.dtype.as_numpy_dtype()), + name=name) + else: + x = array_ops.reshape(x, [1]) + elif ndims != 1: + raise ValueError("Input is neither scalar nor vector.") + + return x, prod + + def _set_sample_static_shape(self, x, sample_shape): + """Helper to `sample`; sets static shape info.""" + # Set shape hints. + sample_shape = tensor_shape.TensorShape( + tensor_util.constant_value(sample_shape)) + + ndims = x.get_shape().ndims + sample_ndims = sample_shape.ndims + batch_ndims = self.batch_shape.ndims + event_ndims = self.event_shape.ndims + + # Infer rank(x). + if (ndims is None and + sample_ndims is not None and + batch_ndims is not None and + event_ndims is not None): + ndims = sample_ndims + batch_ndims + event_ndims + x.set_shape([None] * ndims) + + # Infer sample shape. + if ndims is not None and sample_ndims is not None: + shape = sample_shape.concatenate([None]*(ndims - sample_ndims)) + x.set_shape(x.get_shape().merge_with(shape)) + + # Infer event shape. + if ndims is not None and event_ndims is not None: + shape = tensor_shape.TensorShape( + [None]*(ndims - event_ndims)).concatenate(self.event_shape) + x.set_shape(x.get_shape().merge_with(shape)) + + # Infer batch shape. + if batch_ndims is not None: + if ndims is not None: + if sample_ndims is None and event_ndims is not None: + sample_ndims = ndims - batch_ndims - event_ndims + elif event_ndims is None and sample_ndims is not None: + event_ndims = ndims - batch_ndims - sample_ndims + if sample_ndims is not None and event_ndims is not None: + shape = tensor_shape.TensorShape([None]*sample_ndims).concatenate( + self.batch_shape).concatenate([None]*event_ndims) + x.set_shape(x.get_shape().merge_with(shape)) + + return x + + def _is_scalar_helper(self, static_shape, dynamic_shape_fn): + """Implementation for `is_scalar_batch` and `is_scalar_event`.""" + if static_shape.ndims is not None: + return static_shape.ndims == 0 + shape = dynamic_shape_fn() + if (shape.get_shape().ndims is not None and + shape.get_shape().dims[0].value is not None): + # If the static_shape is correctly written then we should never execute + # this branch. We keep it just in case there's some unimagined corner + # case. + return shape.get_shape().as_list() == [0] + return math_ops.equal(array_ops.shape(shape)[0], 0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distributions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc015295f5872f14d1373ca1db10892789924e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/distributions.py @@ -0,0 +1,36 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Core module for TensorFlow distribution objects and helpers.""" +from tensorflow.python.util import deprecation + + +# pylint: disable=wildcard-import,unused-import,g-import-not-at-top +with deprecation.silence(): + from tensorflow.python.ops.distributions.bernoulli import Bernoulli + from tensorflow.python.ops.distributions.beta import Beta + from tensorflow.python.ops.distributions.categorical import Categorical + from tensorflow.python.ops.distributions.dirichlet import Dirichlet + from tensorflow.python.ops.distributions.dirichlet_multinomial import DirichletMultinomial + from tensorflow.python.ops.distributions.distribution import * + from tensorflow.python.ops.distributions.exponential import Exponential + from tensorflow.python.ops.distributions.gamma import Gamma + from tensorflow.python.ops.distributions.kullback_leibler import * + from tensorflow.python.ops.distributions.laplace import Laplace + from tensorflow.python.ops.distributions.multinomial import Multinomial + from tensorflow.python.ops.distributions.normal import Normal + from tensorflow.python.ops.distributions.student_t import StudentT + from tensorflow.python.ops.distributions.uniform import Uniform +# pylint: enable=wildcard-import,unused-import +del deprecation diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/exponential.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/exponential.py new file mode 100644 index 0000000000000000000000000000000000000000..729ae866dbc7aea8c654a41ea00db4043afe70b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/exponential.py @@ -0,0 +1,162 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Exponential distribution class.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import gamma +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Exponential", + "ExponentialWithSoftplusRate", +] + + +@tf_export(v1=["distributions.Exponential"]) +class Exponential(gamma.Gamma): + """Exponential distribution. + + The Exponential distribution is parameterized by an event `rate` parameter. + + #### Mathematical Details + + The probability density function (pdf) is, + + ```none + pdf(x; lambda, x > 0) = exp(-lambda x) / Z + Z = 1 / lambda + ``` + + where `rate = lambda` and `Z` is the normalizaing constant. + + The Exponential distribution is a special case of the Gamma distribution, + i.e., + + ```python + Exponential(rate) = Gamma(concentration=1., rate) + ``` + + The Exponential distribution uses a `rate` parameter, or "inverse scale", + which can be intuited as, + + ```none + X ~ Exponential(rate=1) + Y = X / rate + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + rate, + validate_args=False, + allow_nan_stats=True, + name="Exponential"): + """Construct Exponential distribution with parameter `rate`. + + Args: + rate: Floating point tensor, equivalent to `1 / mean`. Must contain only + positive values. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + # Even though all statistics of are defined for valid inputs, this is not + # true in the parent class "Gamma." Therefore, passing + # allow_nan_stats=True + # through to the parent class results in unnecessary asserts. + with ops.name_scope(name, values=[rate]) as name: + self._rate = ops.convert_to_tensor(rate, name="rate") + super(Exponential, self).__init__( + concentration=array_ops.ones([], dtype=self._rate.dtype), + rate=self._rate, + allow_nan_stats=allow_nan_stats, + validate_args=validate_args, + name=name) + self._parameters = parameters + self._graph_parents += [self._rate] + + @staticmethod + def _param_shapes(sample_shape): + return {"rate": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} + + @property + def rate(self): + return self._rate + + def _log_survival_function(self, value): + return self._log_prob(value) - math_ops.log(self._rate) + + def _sample_n(self, n, seed=None): + shape = array_ops.concat([[n], array_ops.shape(self._rate)], 0) + # Uniform variates must be sampled from the open-interval `(0, 1)` rather + # than `[0, 1)`. To do so, we use `np.finfo(self.dtype.as_numpy_dtype).tiny` + # because it is the smallest, positive, "normal" number. A "normal" number + # is such that the mantissa has an implicit leading 1. Normal, positive + # numbers x, y have the reasonable property that, `x + y >= max(x, y)`. In + # this case, a subnormal number (i.e., np.nextafter) can cause us to sample + # 0. + sampled = random_ops.random_uniform( + shape, + minval=np.finfo(self.dtype.as_numpy_dtype).tiny, + maxval=1., + seed=seed, + dtype=self.dtype) + return -math_ops.log(sampled) / self._rate + + +class ExponentialWithSoftplusRate(Exponential): + """Exponential with softplus transform on `rate`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.Exponential(tf.nn.softplus(rate)).", + warn_once=True) + def __init__(self, + rate, + validate_args=False, + allow_nan_stats=True, + name="ExponentialWithSoftplusRate"): + parameters = dict(locals()) + with ops.name_scope(name, values=[rate]) as name: + super(ExponentialWithSoftplusRate, self).__init__( + rate=nn.softplus(rate, name="softplus_rate"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/gamma.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..c84caebf92f90fe1f47d63f282658cd95cdd9345 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/gamma.py @@ -0,0 +1,338 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Gamma distribution class.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Gamma", + "GammaWithSoftplusConcentrationRate", +] + + +@tf_export(v1=["distributions.Gamma"]) +class Gamma(distribution.Distribution): + """Gamma distribution. + + The Gamma distribution is defined over positive real numbers using + parameters `concentration` (aka "alpha") and `rate` (aka "beta"). + + #### Mathematical Details + + The probability density function (pdf) is, + + ```none + pdf(x; alpha, beta, x > 0) = x**(alpha - 1) exp(-x beta) / Z + Z = Gamma(alpha) beta**(-alpha) + ``` + + where: + + * `concentration = alpha`, `alpha > 0`, + * `rate = beta`, `beta > 0`, + * `Z` is the normalizing constant, and, + * `Gamma` is the [gamma function]( + https://en.wikipedia.org/wiki/Gamma_function). + + The cumulative density function (cdf) is, + + ```none + cdf(x; alpha, beta, x > 0) = GammaInc(alpha, beta x) / Gamma(alpha) + ``` + + where `GammaInc` is the [lower incomplete Gamma function]( + https://en.wikipedia.org/wiki/Incomplete_gamma_function). + + The parameters can be intuited via their relationship to mean and stddev, + + ```none + concentration = alpha = (mean / stddev)**2 + rate = beta = mean / stddev**2 = concentration / mean + ``` + + Distribution parameters are automatically broadcast in all functions; see + examples for details. + + Warning: The samples of this distribution are always non-negative. However, + the samples that are smaller than `np.finfo(dtype).tiny` are rounded + to this value, so it appears more often than it should. + This should only be noticeable when the `concentration` is very small, or the + `rate` is very large. See note in `tf.random.gamma` docstring. + + Samples of this distribution are reparameterized (pathwise differentiable). + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + #### Examples + + ```python + import tensorflow_probability as tfp + tfd = tfp.distributions + + dist = tfd.Gamma(concentration=3.0, rate=2.0) + dist2 = tfd.Gamma(concentration=[3.0, 4.0], rate=[2.0, 3.0]) + ``` + + Compute the gradients of samples w.r.t. the parameters: + + ```python + concentration = tf.constant(3.0) + rate = tf.constant(2.0) + dist = tfd.Gamma(concentration, rate) + samples = dist.sample(5) # Shape [5] + loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function + # Unbiased stochastic gradients of the loss function + grads = tf.gradients(loss, [concentration, rate]) + ``` + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf](http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name="Gamma"): + """Construct Gamma with `concentration` and `rate` parameters. + + The parameters `concentration` and `rate` must be shaped in a way that + supports broadcasting (e.g. `concentration + rate` is a valid operation). + + Args: + concentration: Floating point tensor, the concentration params of the + distribution(s). Must contain only positive values. + rate: Floating point tensor, the inverse scale params of the + distribution(s). Must contain only positive values. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + TypeError: if `concentration` and `rate` are different dtypes. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[concentration, rate]) as name: + with ops.control_dependencies([ + check_ops.assert_positive(concentration), + check_ops.assert_positive(rate), + ] if validate_args else []): + self._concentration = array_ops.identity( + concentration, name="concentration") + self._rate = array_ops.identity(rate, name="rate") + check_ops.assert_same_float_dtype( + [self._concentration, self._rate]) + super(Gamma, self).__init__( + dtype=self._concentration.dtype, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + parameters=parameters, + graph_parents=[self._concentration, + self._rate], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("concentration", "rate"), ([ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def concentration(self): + """Concentration parameter.""" + return self._concentration + + @property + def rate(self): + """Rate parameter.""" + return self._rate + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.concentration), + array_ops.shape(self.rate)) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + self.concentration.get_shape(), + self.rate.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + @distribution_util.AppendDocstring( + """Note: See `tf.random.gamma` docstring for sampling details and + caveats.""") + def _sample_n(self, n, seed=None): + return random_ops.random_gamma( + shape=[n], + alpha=self.concentration, + beta=self.rate, + dtype=self.dtype, + seed=seed) + + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + def _cdf(self, x): + x = self._maybe_assert_valid_sample(x) + # Note that igamma returns the regularized incomplete gamma function, + # which is what we want for the CDF. + return math_ops.igamma(self.concentration, self.rate * x) + + def _log_unnormalized_prob(self, x): + x = self._maybe_assert_valid_sample(x) + return math_ops.xlogy(self.concentration - 1., x) - self.rate * x + + def _log_normalization(self): + return (math_ops.lgamma(self.concentration) + - self.concentration * math_ops.log(self.rate)) + + def _entropy(self): + return (self.concentration + - math_ops.log(self.rate) + + math_ops.lgamma(self.concentration) + + ((1. - self.concentration) * + math_ops.digamma(self.concentration))) + + def _mean(self): + return self.concentration / self.rate + + def _variance(self): + return self.concentration / math_ops.square(self.rate) + + def _stddev(self): + return math_ops.sqrt(self.concentration) / self.rate + + @distribution_util.AppendDocstring( + """The mode of a gamma distribution is `(shape - 1) / rate` when + `shape > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is `False`, + an exception will be raised rather than returning `NaN`.""") + def _mode(self): + mode = (self.concentration - 1.) / self.rate + if self.allow_nan_stats: + nan = array_ops.fill( + self.batch_shape_tensor(), + np.array(np.nan, dtype=self.dtype.as_numpy_dtype()), + name="nan") + return array_ops.where_v2(self.concentration > 1., mode, nan) + else: + return control_flow_ops.with_dependencies([ + check_ops.assert_less( + array_ops.ones([], self.dtype), + self.concentration, + message="mode not defined when any concentration <= 1"), + ], mode) + + def _maybe_assert_valid_sample(self, x): + check_ops.assert_same_float_dtype(tensors=[x], dtype=self.dtype) + if not self.validate_args: + return x + return control_flow_ops.with_dependencies([ + check_ops.assert_positive(x), + ], x) + + +class GammaWithSoftplusConcentrationRate(Gamma): + """`Gamma` with softplus of `concentration` and `rate`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.Gamma(tf.nn.softplus(concentration), " + "tf.nn.softplus(rate))` instead.", + warn_once=True) + def __init__(self, + concentration, + rate, + validate_args=False, + allow_nan_stats=True, + name="GammaWithSoftplusConcentrationRate"): + parameters = dict(locals()) + with ops.name_scope(name, values=[concentration, rate]) as name: + super(GammaWithSoftplusConcentrationRate, self).__init__( + concentration=nn.softplus(concentration, + name="softplus_concentration"), + rate=nn.softplus(rate, name="softplus_rate"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters + + +@kullback_leibler.RegisterKL(Gamma, Gamma) +def _kl_gamma_gamma(g0, g1, name=None): + """Calculate the batched KL divergence KL(g0 || g1) with g0 and g1 Gamma. + + Args: + g0: instance of a Gamma distribution object. + g1: instance of a Gamma distribution object. + name: (optional) Name to use for created operations. + Default is "kl_gamma_gamma". + + Returns: + kl_gamma_gamma: `Tensor`. The batchwise KL(g0 || g1). + """ + with ops.name_scope(name, "kl_gamma_gamma", values=[ + g0.concentration, g0.rate, g1.concentration, g1.rate]): + # Result from: + # http://www.fil.ion.ucl.ac.uk/~wpenny/publications/densities.ps + # For derivation see: + # http://stats.stackexchange.com/questions/11646/kullback-leibler-divergence-between-two-gamma-distributions pylint: disable=line-too-long + return (((g0.concentration - g1.concentration) + * math_ops.digamma(g0.concentration)) + + math_ops.lgamma(g1.concentration) + - math_ops.lgamma(g0.concentration) + + g1.concentration * math_ops.log(g0.rate) + - g1.concentration * math_ops.log(g1.rate) + + g0.concentration * (g1.rate / g0.rate - 1.)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/identity_bijector.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/identity_bijector.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6ae896567a3b4a6a11d16fd1a521b765e229d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/identity_bijector.py @@ -0,0 +1,68 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Identity bijector.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.ops.distributions import bijector +from tensorflow.python.util import deprecation + + +__all__ = [ + "Identity", +] + + +class Identity(bijector.Bijector): + """Compute Y = g(X) = X. + + Example Use: + + ```python + # Create the Y=g(X)=X transform which is intended for Tensors with 1 batch + # ndim and 1 event ndim (i.e., vector of vectors). + identity = Identity() + x = [[1., 2], + [3, 4]] + x == identity.forward(x) == identity.inverse(x) + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, validate_args=False, name="identity"): + super(Identity, self).__init__( + forward_min_event_ndims=0, + is_constant_jacobian=True, + validate_args=validate_args, + name=name) + + def _forward(self, x): + return x + + def _inverse(self, y): + return y + + def _inverse_log_det_jacobian(self, y): + return constant_op.constant(0., dtype=y.dtype) + + def _forward_log_det_jacobian(self, x): + return constant_op.constant(0., dtype=x.dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/kullback_leibler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/kullback_leibler.py new file mode 100644 index 0000000000000000000000000000000000000000..c8dfb2157e9ff252cce3294c70b6059380d28a60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/kullback_leibler.py @@ -0,0 +1,210 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Registration and usage mechanisms for KL-divergences.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import math_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +_DIVERGENCES = {} + + +__all__ = [ + "RegisterKL", + "kl_divergence", +] + + +def _registered_kl(type_a, type_b): + """Get the KL function registered for classes a and b.""" + hierarchy_a = tf_inspect.getmro(type_a) + hierarchy_b = tf_inspect.getmro(type_b) + dist_to_children = None + kl_fn = None + for mro_to_a, parent_a in enumerate(hierarchy_a): + for mro_to_b, parent_b in enumerate(hierarchy_b): + candidate_dist = mro_to_a + mro_to_b + candidate_kl_fn = _DIVERGENCES.get((parent_a, parent_b), None) + if not kl_fn or (candidate_kl_fn and candidate_dist < dist_to_children): + dist_to_children = candidate_dist + kl_fn = candidate_kl_fn + return kl_fn + + +@deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) +@tf_export(v1=["distributions.kl_divergence"]) +def kl_divergence(distribution_a, distribution_b, + allow_nan_stats=True, name=None): + """Get the KL-divergence KL(distribution_a || distribution_b). + + If there is no KL method registered specifically for `type(distribution_a)` + and `type(distribution_b)`, then the class hierarchies of these types are + searched. + + If one KL method is registered between any pairs of classes in these two + parent hierarchies, it is used. + + If more than one such registered method exists, the method whose registered + classes have the shortest sum MRO paths to the input types is used. + + If more than one such shortest path exists, the first method + identified in the search is used (favoring a shorter MRO distance to + `type(distribution_a)`). + + Args: + distribution_a: The first distribution. + distribution_b: The second distribution. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Returns: + A Tensor with the batchwise KL-divergence between `distribution_a` + and `distribution_b`. + + Raises: + NotImplementedError: If no KL method is defined for distribution types + of `distribution_a` and `distribution_b`. + """ + kl_fn = _registered_kl(type(distribution_a), type(distribution_b)) + if kl_fn is None: + raise NotImplementedError( + "No KL(distribution_a || distribution_b) registered for distribution_a " + "type %s and distribution_b type %s" + % (type(distribution_a).__name__, type(distribution_b).__name__)) + + with ops.name_scope("KullbackLeibler"): + kl_t = kl_fn(distribution_a, distribution_b, name=name) + if allow_nan_stats: + return kl_t + + # Check KL for NaNs + kl_t = array_ops.identity(kl_t, name="kl") + + with ops.control_dependencies([ + control_flow_assert.Assert( + math_ops.logical_not(math_ops.reduce_any(math_ops.is_nan(kl_t))), [ + "KL calculation between %s and %s returned NaN values " + "(and was called with allow_nan_stats=False). Values:" % + (distribution_a.name, distribution_b.name), kl_t + ]) + ]): + return array_ops.identity(kl_t, name="checked_kl") + + +@deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) +def cross_entropy(ref, other, + allow_nan_stats=True, name=None): + """Computes the (Shannon) cross entropy. + + Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q` + are absolutely continuous with respect to one another and permit densities + `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) cross entropy is defined as: + + ```none + H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x) + ``` + + where `F` denotes the support of the random variable `X ~ P`. + + Args: + ref: `tfd.Distribution` instance. + other: `tfd.Distribution` instance. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` prepended to names of ops created by this function. + + Returns: + cross_entropy: `ref.dtype` `Tensor` with shape `[B1, ..., Bn]` + representing `n` different calculations of (Shanon) cross entropy. + """ + with ops.name_scope(name, "cross_entropy"): + return ref.entropy() + kl_divergence( + ref, other, allow_nan_stats=allow_nan_stats) + + +@tf_export(v1=["distributions.RegisterKL"]) +class RegisterKL: + """Decorator to register a KL divergence implementation function. + + Usage: + + @distributions.RegisterKL(distributions.Normal, distributions.Normal) + def _kl_normal_mvn(norm_a, norm_b): + # Return KL(norm_a || norm_b) + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, dist_cls_a, dist_cls_b): + """Initialize the KL registrar. + + Args: + dist_cls_a: the class of the first argument of the KL divergence. + dist_cls_b: the class of the second argument of the KL divergence. + """ + self._key = (dist_cls_a, dist_cls_b) + + def __call__(self, kl_fn): + """Perform the KL registration. + + Args: + kl_fn: The function to use for the KL divergence. + + Returns: + kl_fn + + Raises: + TypeError: if kl_fn is not a callable. + ValueError: if a KL divergence function has already been registered for + the given argument classes. + """ + if not callable(kl_fn): + raise TypeError("kl_fn must be callable, received: %s" % kl_fn) + if self._key in _DIVERGENCES: + raise ValueError("KL(%s || %s) has already been registered to: %s" + % (self._key[0].__name__, self._key[1].__name__, + _DIVERGENCES[self._key])) + _DIVERGENCES[self._key] = kl_fn + return kl_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/laplace.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/laplace.py new file mode 100644 index 0000000000000000000000000000000000000000..9cebbac5daab17b18450a05c5bfa977b4f019bbb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/laplace.py @@ -0,0 +1,238 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Laplace distribution class.""" + +import math + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import special_math +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Laplace", + "LaplaceWithSoftplusScale", +] + + +@tf_export(v1=["distributions.Laplace"]) +class Laplace(distribution.Distribution): + """The Laplace distribution with location `loc` and `scale` parameters. + + #### Mathematical details + + The probability density function (pdf) of this distribution is, + + ```none + pdf(x; mu, sigma) = exp(-|x - mu| / sigma) / Z + Z = 2 sigma + ``` + + where `loc = mu`, `scale = sigma`, and `Z` is the normalization constant. + + Note that the Laplace distribution can be thought of two exponential + distributions spliced together "back-to-back." + + The Lpalce distribution is a member of the [location-scale family]( + https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be + constructed as, + + ```none + X ~ Laplace(loc=0, scale=1) + Y = loc + scale * X + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="Laplace"): + """Construct Laplace distribution with parameters `loc` and `scale`. + + The parameters `loc` and `scale` must be shaped in a way that supports + broadcasting (e.g., `loc / scale` is a valid operation). + + Args: + loc: Floating point tensor which characterizes the location (center) + of the distribution. + scale: Positive floating point tensor which characterizes the spread of + the distribution. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + TypeError: if `loc` and `scale` are of different dtype. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[loc, scale]) as name: + with ops.control_dependencies([check_ops.assert_positive(scale)] if + validate_args else []): + self._loc = array_ops.identity(loc, name="loc") + self._scale = array_ops.identity(scale, name="scale") + check_ops.assert_same_float_dtype([self._loc, self._scale]) + super(Laplace, self).__init__( + dtype=self._loc.dtype, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._loc, self._scale], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("loc", "scale"), ([ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def loc(self): + """Distribution parameter for the location.""" + return self._loc + + @property + def scale(self): + """Distribution parameter for scale.""" + return self._scale + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.loc), array_ops.shape(self.scale)) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + self.loc.get_shape(), self.scale.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + # Uniform variates must be sampled from the open-interval `(-1, 1)` rather + # than `[-1, 1)`. In the case of `(0, 1)` we'd use + # `np.finfo(self.dtype.as_numpy_dtype).tiny` because it is the smallest, + # positive, "normal" number. However, the concept of subnormality exists + # only at zero; here we need the smallest usable number larger than -1, + # i.e., `-1 + eps/2`. + uniform_samples = random_ops.random_uniform( + shape=shape, + minval=np.nextafter(self.dtype.as_numpy_dtype(-1.), + self.dtype.as_numpy_dtype(0.)), + maxval=1., + dtype=self.dtype, + seed=seed) + return (self.loc - self.scale * math_ops.sign(uniform_samples) * + math_ops.log1p(-math_ops.abs(uniform_samples))) + + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + def _prob(self, x): + return math_ops.exp(self._log_prob(x)) + + def _log_cdf(self, x): + return special_math.log_cdf_laplace(self._z(x)) + + def _log_survival_function(self, x): + return special_math.log_cdf_laplace(-self._z(x)) + + def _cdf(self, x): + z = self._z(x) + return (0.5 + 0.5 * math_ops.sign(z) * + (1. - math_ops.exp(-math_ops.abs(z)))) + + def _log_unnormalized_prob(self, x): + return -math_ops.abs(self._z(x)) + + def _log_normalization(self): + return math.log(2.) + math_ops.log(self.scale) + + def _entropy(self): + # Use broadcasting rules to calculate the full broadcast scale. + scale = self.scale + array_ops.zeros_like(self.loc) + return math.log(2.) + 1. + math_ops.log(scale) + + def _mean(self): + return self.loc + array_ops.zeros_like(self.scale) + + def _stddev(self): + return math.sqrt(2.) * self.scale + array_ops.zeros_like(self.loc) + + def _median(self): + return self._mean() + + def _mode(self): + return self._mean() + + def _z(self, x): + return (x - self.loc) / self.scale + + +class LaplaceWithSoftplusScale(Laplace): + """Laplace with softplus applied to `scale`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.Laplace(loc, tf.nn.softplus(scale)) " + "instead.", + warn_once=True) + def __init__(self, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="LaplaceWithSoftplusScale"): + parameters = dict(locals()) + with ops.name_scope(name, values=[loc, scale]) as name: + super(LaplaceWithSoftplusScale, self).__init__( + loc=loc, + scale=nn.softplus(scale, name="softplus_scale"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/multinomial.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/multinomial.py new file mode 100644 index 0000000000000000000000000000000000000000..4b889bcb288f3b23684631bff8278e1604b45643 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/multinomial.py @@ -0,0 +1,314 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Multinomial distribution class.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Multinomial", +] + + +_multinomial_sample_note = """For each batch of counts, `value = [n_0, ... +,n_{k-1}]`, `P[value]` is the probability that after sampling `self.total_count` +draws from this Multinomial distribution, the number of draws falling in class +`j` is `n_j`. Since this definition is [exchangeable]( +https://en.wikipedia.org/wiki/Exchangeable_random_variables); different +sequences have the same counts so the probability includes a combinatorial +coefficient. + +Note: `value` must be a non-negative tensor with dtype `self.dtype`, have no +fractional components, and such that +`tf.reduce_sum(value, -1) = self.total_count`. Its shape must be broadcastable +with `self.probs` and `self.total_count`.""" + + +@tf_export(v1=["distributions.Multinomial"]) +class Multinomial(distribution.Distribution): + """Multinomial distribution. + + This Multinomial distribution is parameterized by `probs`, a (batch of) + length-`K` `prob` (probability) vectors (`K > 1`) such that + `tf.reduce_sum(probs, -1) = 1`, and a `total_count` number of trials, i.e., + the number of trials per draw from the Multinomial. It is defined over a + (batch of) length-`K` vector `counts` such that + `tf.reduce_sum(counts, -1) = total_count`. The Multinomial is identically the + Binomial distribution when `K = 2`. + + #### Mathematical Details + + The Multinomial is a distribution over `K`-class counts, i.e., a length-`K` + vector of non-negative integer `counts = n = [n_0, ..., n_{K-1}]`. + + The probability mass function (pmf) is, + + ```none + pmf(n; pi, N) = prod_j (pi_j)**n_j / Z + Z = (prod_j n_j!) / N! + ``` + + where: + * `probs = pi = [pi_0, ..., pi_{K-1}]`, `pi_j > 0`, `sum_j pi_j = 1`, + * `total_count = N`, `N` a positive integer, + * `Z` is the normalization constant, and, + * `N!` denotes `N` factorial. + + Distribution parameters are automatically broadcast in all functions; see + examples for details. + + #### Pitfalls + + The number of classes, `K`, must not exceed: + - the largest integer representable by `self.dtype`, i.e., + `2**(mantissa_bits+1)` (IEE754), + - the maximum `Tensor` index, i.e., `2**31-1`. + + In other words, + + ```python + K <= min(2**31-1, { + tf.float16: 2**11, + tf.float32: 2**24, + tf.float64: 2**53 }[param.dtype]) + ``` + + Note: This condition is validated only when `self.validate_args = True`. + + #### Examples + + Create a 3-class distribution, with the 3rd class is most likely to be drawn, + using logits. + + ```python + logits = [-50., -43, 0] + dist = Multinomial(total_count=4., logits=logits) + ``` + + Create a 3-class distribution, with the 3rd class is most likely to be drawn. + + ```python + p = [.2, .3, .5] + dist = Multinomial(total_count=4., probs=p) + ``` + + The distribution functions can be evaluated on counts. + + ```python + # counts same shape as p. + counts = [1., 0, 3] + dist.prob(counts) # Shape [] + + # p will be broadcast to [[.2, .3, .5], [.2, .3, .5]] to match counts. + counts = [[1., 2, 1], [2, 2, 0]] + dist.prob(counts) # Shape [2] + + # p will be broadcast to shape [5, 7, 3] to match counts. + counts = [[...]] # Shape [5, 7, 3] + dist.prob(counts) # Shape [5, 7] + ``` + + Create a 2-batch of 3-class distributions. + + ```python + p = [[.1, .2, .7], [.3, .3, .4]] # Shape [2, 3] + dist = Multinomial(total_count=[4., 5], probs=p) + + counts = [[2., 1, 1], [3, 1, 1]] + dist.prob(counts) # Shape [2] + + dist.sample(5) # Shape [5, 2, 3] + ``` + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + total_count, + logits=None, + probs=None, + validate_args=False, + allow_nan_stats=True, + name="Multinomial"): + """Initialize a batch of Multinomial distributions. + + Args: + total_count: Non-negative floating point tensor with shape broadcastable + to `[N1,..., Nm]` with `m >= 0`. Defines this as a batch of + `N1 x ... x Nm` different Multinomial distributions. Its components + should be equal to integer values. + logits: Floating point tensor representing unnormalized log-probabilities + of a positive event with shape broadcastable to + `[N1,..., Nm, K]` `m >= 0`, and the same dtype as `total_count`. Defines + this as a batch of `N1 x ... x Nm` different `K` class Multinomial + distributions. Only one of `logits` or `probs` should be passed in. + probs: Positive floating point tensor with shape broadcastable to + `[N1,..., Nm, K]` `m >= 0` and same dtype as `total_count`. Defines + this as a batch of `N1 x ... x Nm` different `K` class Multinomial + distributions. `probs`'s components in the last portion of its shape + should sum to `1`. Only one of `logits` or `probs` should be passed in. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[total_count, logits, probs]) as name: + self._total_count = ops.convert_to_tensor(total_count, name="total_count") + if validate_args: + self._total_count = ( + distribution_util.embed_check_nonnegative_integer_form( + self._total_count)) + self._logits, self._probs = distribution_util.get_logits_and_probs( + logits=logits, + probs=probs, + multidimensional=True, + validate_args=validate_args, + name=name) + self._mean_val = self._total_count[..., array_ops.newaxis] * self._probs + super(Multinomial, self).__init__( + dtype=self._probs.dtype, + reparameterization_type=distribution.NOT_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._total_count, + self._logits, + self._probs], + name=name) + + @property + def total_count(self): + """Number of trials used to construct a sample.""" + return self._total_count + + @property + def logits(self): + """Vector of coordinatewise logits.""" + return self._logits + + @property + def probs(self): + """Probability of drawing a `1` in that coordinate.""" + return self._probs + + def _batch_shape_tensor(self): + return array_ops.shape(self._mean_val)[:-1] + + def _batch_shape(self): + return self._mean_val.get_shape().with_rank_at_least(1)[:-1] + + def _event_shape_tensor(self): + return array_ops.shape(self._mean_val)[-1:] + + def _event_shape(self): + return self._mean_val.get_shape().with_rank_at_least(1)[-1:] + + def _sample_n(self, n, seed=None): + n_draws = math_ops.cast(self.total_count, dtype=dtypes.int32) + k = self.event_shape_tensor()[0] + + # broadcast the total_count and logits to same shape + n_draws = array_ops.ones_like( + self.logits[..., 0], dtype=n_draws.dtype) * n_draws + logits = array_ops.ones_like( + n_draws[..., array_ops.newaxis], dtype=self.logits.dtype) * self.logits + + # flatten the total_count and logits + flat_logits = array_ops.reshape(logits, [-1, k]) # [B1B2...Bm, k] + flat_ndraws = n * array_ops.reshape(n_draws, [-1]) # [B1B2...Bm] + + # computes each total_count and logits situation by map_fn + def _sample_single(args): + logits, n_draw = args[0], args[1] # [K], [] + x = random_ops.multinomial(logits[array_ops.newaxis, ...], n_draw, + seed) # [1, n*n_draw] + x = array_ops.reshape(x, shape=[n, -1]) # [n, n_draw] + x = math_ops.reduce_sum(array_ops.one_hot(x, depth=k), axis=-2) # [n, k] + return x + + x = map_fn.map_fn( + _sample_single, [flat_logits, flat_ndraws], + dtype=self.dtype) # [B1B2...Bm, n, k] + + # reshape the results to proper shape + x = array_ops.transpose(x, perm=[1, 0, 2]) + final_shape = array_ops.concat([[n], self.batch_shape_tensor(), [k]], 0) + x = array_ops.reshape(x, final_shape) # [n, B1, B2,..., Bm, k] + return x + + @distribution_util.AppendDocstring(_multinomial_sample_note) + def _log_prob(self, counts): + return self._log_unnormalized_prob(counts) - self._log_normalization(counts) + + def _log_unnormalized_prob(self, counts): + counts = self._maybe_assert_valid_sample(counts) + return math_ops.reduce_sum(counts * nn_ops.log_softmax(self.logits), -1) + + def _log_normalization(self, counts): + counts = self._maybe_assert_valid_sample(counts) + return -distribution_util.log_combinations(self.total_count, counts) + + def _mean(self): + return array_ops.identity(self._mean_val) + + def _covariance(self): + p = self.probs * array_ops.ones_like( + self.total_count)[..., array_ops.newaxis] + # pylint: disable=invalid-unary-operand-type + return array_ops.matrix_set_diag( + -math_ops.matmul( + self._mean_val[..., array_ops.newaxis], + p[..., array_ops.newaxis, :]), # outer product + self._variance()) + + def _variance(self): + p = self.probs * array_ops.ones_like( + self.total_count)[..., array_ops.newaxis] + return self._mean_val - self._mean_val * p + + def _maybe_assert_valid_sample(self, counts): + """Check counts for proper shape, values, then return tensor version.""" + if not self.validate_args: + return counts + counts = distribution_util.embed_check_nonnegative_integer_form(counts) + return control_flow_ops.with_dependencies([ + check_ops.assert_equal( + self.total_count, math_ops.reduce_sum(counts, -1), + message="counts must sum to `self.total_count`"), + ], counts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/normal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/normal.py new file mode 100644 index 0000000000000000000000000000000000000000..4bd9f36873d455f9df6329c1693f2e9f4df5d4b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/normal.py @@ -0,0 +1,291 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Normal (Gaussian) distribution class.""" + +import math + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import kullback_leibler +from tensorflow.python.ops.distributions import special_math +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "Normal", + "NormalWithSoftplusScale", +] + + +@tf_export(v1=["distributions.Normal"]) +class Normal(distribution.Distribution): + """The Normal distribution with location `loc` and `scale` parameters. + + #### Mathematical details + + The probability density function (pdf) is, + + ```none + pdf(x; mu, sigma) = exp(-0.5 (x - mu)**2 / sigma**2) / Z + Z = (2 pi sigma**2)**0.5 + ``` + + where `loc = mu` is the mean, `scale = sigma` is the std. deviation, and, `Z` + is the normalization constant. + + The Normal distribution is a member of the [location-scale family]( + https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be + constructed as, + + ```none + X ~ Normal(loc=0, scale=1) + Y = loc + scale * X + ``` + + #### Examples + + Examples of initialization of one or a batch of distributions. + + ```python + import tensorflow_probability as tfp + tfd = tfp.distributions + + # Define a single scalar Normal distribution. + dist = tfd.Normal(loc=0., scale=3.) + + # Evaluate the cdf at 1, returning a scalar. + dist.cdf(1.) + + # Define a batch of two scalar valued Normals. + # The first has mean 1 and standard deviation 11, the second 2 and 22. + dist = tfd.Normal(loc=[1, 2.], scale=[11, 22.]) + + # Evaluate the pdf of the first distribution on 0, and the second on 1.5, + # returning a length two tensor. + dist.prob([0, 1.5]) + + # Get 3 samples, returning a 3 x 2 tensor. + dist.sample([3]) + ``` + + Arguments are broadcast when possible. + + ```python + # Define a batch of two scalar valued Normals. + # Both have mean 1, but different standard deviations. + dist = tfd.Normal(loc=1., scale=[11, 22.]) + + # Evaluate the pdf of both distributions on the same point, 3.0, + # returning a length 2 tensor. + dist.prob(3.0) + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="Normal"): + """Construct Normal distributions with mean and stddev `loc` and `scale`. + + The parameters `loc` and `scale` must be shaped in a way that supports + broadcasting (e.g. `loc + scale` is a valid operation). + + Args: + loc: Floating point tensor; the means of the distribution(s). + scale: Floating point tensor; the stddevs of the distribution(s). + Must contain only positive values. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + TypeError: if `loc` and `scale` have different `dtype`. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[loc, scale]) as name: + with ops.control_dependencies([check_ops.assert_positive(scale)] if + validate_args else []): + self._loc = array_ops.identity(loc, name="loc") + self._scale = array_ops.identity(scale, name="scale") + check_ops.assert_same_float_dtype([self._loc, self._scale]) + super(Normal, self).__init__( + dtype=self._scale.dtype, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._loc, self._scale], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("loc", "scale"), ([ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def loc(self): + """Distribution parameter for the mean.""" + return self._loc + + @property + def scale(self): + """Distribution parameter for standard deviation.""" + return self._scale + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.loc), + array_ops.shape(self.scale)) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + self.loc.get_shape(), + self.scale.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + sampled = random_ops.random_normal( + shape=shape, mean=0., stddev=1., dtype=self.loc.dtype, seed=seed) + return sampled * self.scale + self.loc + + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + def _log_cdf(self, x): + return special_math.log_ndtr(self._z(x)) + + def _cdf(self, x): + return special_math.ndtr(self._z(x)) + + def _log_survival_function(self, x): + return special_math.log_ndtr(-self._z(x)) + + def _survival_function(self, x): + return special_math.ndtr(-self._z(x)) + + def _log_unnormalized_prob(self, x): + return -0.5 * math_ops.square(self._z(x)) + + def _log_normalization(self): + return 0.5 * math.log(2. * math.pi) + math_ops.log(self.scale) + + def _entropy(self): + # Use broadcasting rules to calculate the full broadcast scale. + scale = self.scale * array_ops.ones_like(self.loc) + return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(scale) + + def _mean(self): + return self.loc * array_ops.ones_like(self.scale) + + def _quantile(self, p): + return self._inv_z(special_math.ndtri(p)) + + def _stddev(self): + return self.scale * array_ops.ones_like(self.loc) + + def _mode(self): + return self._mean() + + def _z(self, x): + """Standardize input `x` to a unit normal.""" + with ops.name_scope("standardize", values=[x]): + return (x - self.loc) / self.scale + + def _inv_z(self, z): + """Reconstruct input `x` from a its normalized version.""" + with ops.name_scope("reconstruct", values=[z]): + return z * self.scale + self.loc + + +class NormalWithSoftplusScale(Normal): + """Normal with softplus applied to `scale`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.Normal(loc, tf.nn.softplus(scale)) " + "instead.", + warn_once=True) + def __init__(self, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="NormalWithSoftplusScale"): + parameters = dict(locals()) + with ops.name_scope(name, values=[scale]) as name: + super(NormalWithSoftplusScale, self).__init__( + loc=loc, + scale=nn.softplus(scale, name="softplus_scale"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters + + +@kullback_leibler.RegisterKL(Normal, Normal) +def _kl_normal_normal(n_a, n_b, name=None): + """Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal. + + Args: + n_a: instance of a Normal distribution object. + n_b: instance of a Normal distribution object. + name: (optional) Name to use for created operations. + default is "kl_normal_normal". + + Returns: + Batchwise KL(n_a || n_b) + """ + with ops.name_scope(name, "kl_normal_normal", [n_a.loc, n_b.loc]): + one = constant_op.constant(1, dtype=n_a.dtype) + two = constant_op.constant(2, dtype=n_a.dtype) + half = constant_op.constant(0.5, dtype=n_a.dtype) + s_a_squared = math_ops.square(n_a.scale) + s_b_squared = math_ops.square(n_b.scale) + ratio = s_a_squared / s_b_squared + return (math_ops.squared_difference(n_a.loc, n_b.loc) / (two * s_b_squared) + + half * (ratio - one - math_ops.log(ratio))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/special_math.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/special_math.py new file mode 100644 index 0000000000000000000000000000000000000000..797270f3e143e407afdc4d23837574a137bbc0db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/special_math.py @@ -0,0 +1,470 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# Functions "ndtr" and "ndtri" are derived from calculations made in: +# https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html +# In the following email exchange, the author gives his consent to redistribute +# derived works under an Apache 2.0 license. +# +# From: Stephen Moshier +# Date: Sat, Jun 9, 2018 at 2:36 PM +# Subject: Re: Licensing cephes under Apache (BSD-like) license. +# To: rif +# +# +# +# Hello Rif, +# +# Yes, Google may distribute Cephes files under the Apache 2 license. +# +# If clarification is needed, I do not favor BSD over other free licenses. +# I would agree that Apache 2 seems to cover the concern you mentioned +# about sublicensees. +# +# Best wishes for good luck with your projects! +# Steve Moshier +# +# +# +# On Thu, 31 May 2018, rif wrote: +# +# > Hello Steve. +# > My name is Rif. I work on machine learning software at Google. +# > +# > Your cephes software continues to be incredibly useful and widely used. I +# > was wondering whether it would be permissible for us to use the Cephes code +# > under the Apache 2.0 license, which is extremely similar in permissions to +# > the BSD license (Wikipedia comparisons). This would be quite helpful to us +# > in terms of avoiding multiple licenses on software. +# > +# > I'm sorry to bother you with this (I can imagine you're sick of hearing +# > about this by now), but I want to be absolutely clear we're on the level and +# > not misusing your important software. In former conversation with Eugene +# > Brevdo (ebrevdo@google.com), you wrote "If your licensing is similar to BSD, +# > the formal way that has been handled is simply to add a statement to the +# > effect that you are incorporating the Cephes software by permission of the +# > author." I wanted to confirm that (a) we could use the Apache license, (b) +# > that we don't need to (and probably you don't want to) keep getting +# > contacted about individual uses, because your intent is generally to allow +# > this software to be reused under "BSD-like" license, and (c) you're OK +# > letting incorporators decide whether a license is sufficiently BSD-like? +# > +# > Best, +# > +# > rif +# > +# > +# > + +"""Special Math Ops.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops + +__all__ = [ + "erfinv", + "ndtr", + "ndtri", + "log_ndtr", + "log_cdf_laplace", +] + + +# log_ndtr uses different functions over the ranges +# (-infty, lower](lower, upper](upper, infty) +# Lower bound values were chosen by examining where the support of ndtr +# appears to be zero, relative to scipy's (which is always 64bit). They were +# then made more conservative just to be safe. (Conservative means use the +# expansion more than we probably need to.) See `NdtrTest` in +# special_math_test.py. +LOGNDTR_FLOAT64_LOWER = np.array(-20, np.float64) +LOGNDTR_FLOAT32_LOWER = np.array(-10, np.float32) + +# Upper bound values were chosen by examining for which values of 'x' +# Log[cdf(x)] is 0, after which point we need to use the approximation +# Log[cdf(x)] = Log[1 - cdf(-x)] approx -cdf(-x). We chose a value slightly +# conservative, meaning we use the approximation earlier than needed. +LOGNDTR_FLOAT64_UPPER = np.array(8, np.float64) +LOGNDTR_FLOAT32_UPPER = np.array(5, np.float32) + + +def ndtr(x, name="ndtr"): + """Normal distribution function. + + Returns the area under the Gaussian probability density function, integrated + from minus infinity to x: + + ``` + 1 / x + ndtr(x) = ---------- | exp(-0.5 t**2) dt + sqrt(2 pi) /-inf + + = 0.5 (1 + erf(x / sqrt(2))) + = 0.5 erfc(x / sqrt(2)) + ``` + + Args: + x: `Tensor` of type `float32`, `float64`. + name: Python string. A name for the operation (default="ndtr"). + + Returns: + ndtr: `Tensor` with `dtype=x.dtype`. + + Raises: + TypeError: if `x` is not floating-type. + """ + + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + if x.dtype.as_numpy_dtype not in [np.float32, np.float64]: + raise TypeError( + "x.dtype=%s is not handled, see docstring for supported types." + % x.dtype) + return _ndtr(x) + + +def _ndtr(x): + """Implements ndtr core logic.""" + half_sqrt_2 = constant_op.constant( + 0.5 * np.sqrt(2.), dtype=x.dtype, name="half_sqrt_2") + w = x * half_sqrt_2 + z = math_ops.abs(w) + y = array_ops.where_v2( + math_ops.less(z, half_sqrt_2), 1. + math_ops.erf(w), + array_ops.where_v2( + math_ops.greater(w, 0.), 2. - math_ops.erfc(z), math_ops.erfc(z))) + return 0.5 * y + + +def ndtri(p, name="ndtri"): + """The inverse of the CDF of the Normal distribution function. + + Returns x such that the area under the pdf from minus infinity to x is equal + to p. + + A piece-wise rational approximation is done for the function. + This is a port of the implementation in netlib. + + Args: + p: `Tensor` of type `float32`, `float64`. + name: Python string. A name for the operation (default="ndtri"). + + Returns: + x: `Tensor` with `dtype=p.dtype`. + + Raises: + TypeError: if `p` is not floating-type. + """ + + with ops.name_scope(name, values=[p]): + p = ops.convert_to_tensor(p, name="p") + if p.dtype.as_numpy_dtype not in [np.float32, np.float64]: + raise TypeError( + "p.dtype=%s is not handled, see docstring for supported types." + % p.dtype) + return _ndtri(p) + + +def _ndtri(p): + """Implements ndtri core logic.""" + + # Constants used in piece-wise rational approximations. Taken from the cephes + # library: + # https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html + + p0 = [ + -1.23916583867381258016E0, 1.39312609387279679503E1, + -5.66762857469070293439E1, 9.80010754185999661536E1, + -5.99633501014107895267E1 + ] + q0 = [ + -1.18331621121330003142E0, 1.59056225126211695515E1, + -8.20372256168333339912E1, 2.00260212380060660359E2, + -2.25462687854119370527E2, 8.63602421390890590575E1, + 4.67627912898881538453E0, 1.95448858338141759834E0, 1.0 + ] + p1 = [ + -8.57456785154685413611E-4, -3.50424626827848203418E-2, + -1.40256079171354495875E-1, 2.18663306850790267539E0, + 1.46849561928858024014E1, 4.40805073893200834700E1, + 5.71628192246421288162E1, 3.15251094599893866154E1, + 4.05544892305962419923E0 + ] + q1 = [ + -9.33259480895457427372E-4, -3.80806407691578277194E-2, + -1.42182922854787788574E-1, 2.50464946208309415979E0, + 1.50425385692907503408E1, 4.13172038254672030440E1, + 4.53907635128879210584E1, 1.57799883256466749731E1, 1.0 + ] + p2 = [ + 6.23974539184983293730E-9, 2.65806974686737550832E-6, + 3.01581553508235416007E-4, 1.23716634817820021358E-2, + 2.01485389549179081538E-1, 1.33303460815807542389E0, + 3.93881025292474443415E0, 6.91522889068984211695E0, + 3.23774891776946035970E0 + ] + q2 = [ + 6.79019408009981274425E-9, 2.89247864745380683936E-6, + 3.28014464682127739104E-4, 1.34204006088543189037E-2, + 2.16236993594496635890E-1, 1.37702099489081330271E0, + 3.67983563856160859403E0, 6.02427039364742014255E0, 1.0 + ] + + def _create_polynomial(var, coeffs): + """Compute n_th order polynomial via Horner's method.""" + coeffs = np.array(coeffs, var.dtype.as_numpy_dtype) + if not coeffs.size: + return array_ops.zeros_like(var) + return coeffs[0] + _create_polynomial(var, coeffs[1:]) * var + + maybe_complement_p = array_ops.where_v2(p > -np.expm1(-2.), 1. - p, p) + # Write in an arbitrary value in place of 0 for p since 0 will cause NaNs + # later on. The result from the computation when p == 0 is not used so any + # number that doesn't result in NaNs is fine. + sanitized_mcp = array_ops.where_v2( + maybe_complement_p <= 0., + array_ops.fill(array_ops.shape(p), np.array(0.5, p.dtype.as_numpy_dtype)), + maybe_complement_p) + + # Compute x for p > exp(-2): x/sqrt(2pi) = w + w**3 P0(w**2)/Q0(w**2). + w = sanitized_mcp - 0.5 + ww = w ** 2 + x_for_big_p = w + w * ww * (_create_polynomial(ww, p0) + / _create_polynomial(ww, q0)) + x_for_big_p *= -np.sqrt(2. * np.pi) + + # Compute x for p <= exp(-2): x = z - log(z)/z - (1/z) P(1/z) / Q(1/z), + # where z = sqrt(-2. * log(p)), and P/Q are chosen between two different + # arrays based on whether p < exp(-32). + z = math_ops.sqrt(-2. * math_ops.log(sanitized_mcp)) + first_term = z - math_ops.log(z) / z + second_term_small_p = ( + _create_polynomial(1. / z, p2) / + _create_polynomial(1. / z, q2) / z) + second_term_otherwise = ( + _create_polynomial(1. / z, p1) / + _create_polynomial(1. / z, q1) / z) + x_for_small_p = first_term - second_term_small_p + x_otherwise = first_term - second_term_otherwise + + x = array_ops.where_v2( + sanitized_mcp > np.exp(-2.), x_for_big_p, + array_ops.where_v2(z >= 8.0, x_for_small_p, x_otherwise)) + + x = array_ops.where_v2(p > 1. - np.exp(-2.), x, -x) + infinity_scalar = constant_op.constant(np.inf, dtype=p.dtype) + infinity = array_ops.fill(array_ops.shape(p), infinity_scalar) + x_nan_replaced = array_ops.where_v2(p <= 0.0, -infinity, + array_ops.where_v2(p >= 1.0, infinity, x)) + return x_nan_replaced + + +def log_ndtr(x, series_order=3, name="log_ndtr"): + """Log Normal distribution function. + + For details of the Normal distribution function see `ndtr`. + + This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or + using an asymptotic series. Specifically: + - For `x > upper_segment`, use the approximation `-ndtr(-x)` based on + `log(1-x) ~= -x, x << 1`. + - For `lower_segment < x <= upper_segment`, use the existing `ndtr` technique + and take a log. + - For `x <= lower_segment`, we use the series approximation of erf to compute + the log CDF directly. + + The `lower_segment` is set based on the precision of the input: + + ``` + lower_segment = { -20, x.dtype=float64 + { -10, x.dtype=float32 + upper_segment = { 8, x.dtype=float64 + { 5, x.dtype=float32 + ``` + + When `x < lower_segment`, the `ndtr` asymptotic series approximation is: + + ``` + ndtr(x) = scale * (1 + sum) + R_N + scale = exp(-0.5 x**2) / (-x sqrt(2 pi)) + sum = Sum{(-1)^n (2n-1)!! / (x**2)^n, n=1:N} + R_N = O(exp(-0.5 x**2) (2N+1)!! / |x|^{2N+3}) + ``` + + where `(2n-1)!! = (2n-1) (2n-3) (2n-5) ... (3) (1)` is a + [double-factorial](https://en.wikipedia.org/wiki/Double_factorial). + + + Args: + x: `Tensor` of type `float32`, `float64`. + series_order: Positive Python `integer`. Maximum depth to + evaluate the asymptotic expansion. This is the `N` above. + name: Python string. A name for the operation (default="log_ndtr"). + + Returns: + log_ndtr: `Tensor` with `dtype=x.dtype`. + + Raises: + TypeError: if `x.dtype` is not handled. + TypeError: if `series_order` is a not Python `integer.` + ValueError: if `series_order` is not in `[0, 30]`. + """ + if not isinstance(series_order, int): + raise TypeError("series_order must be a Python integer.") + if series_order < 0: + raise ValueError("series_order must be non-negative.") + if series_order > 30: + raise ValueError("series_order must be <= 30.") + + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + + if x.dtype.as_numpy_dtype == np.float64: + lower_segment = LOGNDTR_FLOAT64_LOWER + upper_segment = LOGNDTR_FLOAT64_UPPER + elif x.dtype.as_numpy_dtype == np.float32: + lower_segment = LOGNDTR_FLOAT32_LOWER + upper_segment = LOGNDTR_FLOAT32_UPPER + else: + raise TypeError("x.dtype=%s is not supported." % x.dtype) + + # The basic idea here was ported from: + # https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html + # We copy the main idea, with a few changes + # * For x >> 1, and X ~ Normal(0, 1), + # Log[P[X < x]] = Log[1 - P[X < -x]] approx -P[X < -x], + # which extends the range of validity of this function. + # * We use one fixed series_order for all of 'x', rather than adaptive. + # * Our docstring properly reflects that this is an asymptotic series, not a + # Taylor series. We also provided a correct bound on the remainder. + # * We need to use the max/min in the _log_ndtr_lower arg to avoid nan when + # x=0. This happens even though the branch is unchosen because when x=0 + # the gradient of a select involves the calculation 1*dy+0*(-inf)=nan + # regardless of whether dy is finite. Note that the minimum is a NOP if + # the branch is chosen. + return array_ops.where_v2( + math_ops.greater(x, upper_segment), + -_ndtr(-x), # log(1-x) ~= -x, x << 1 # pylint: disable=invalid-unary-operand-type + array_ops.where_v2( + math_ops.greater(x, lower_segment), + math_ops.log(_ndtr(math_ops.maximum(x, lower_segment))), + _log_ndtr_lower(math_ops.minimum(x, lower_segment), series_order))) + + +def _log_ndtr_lower(x, series_order): + """Asymptotic expansion version of `Log[cdf(x)]`, appropriate for `x<<-1`.""" + x_2 = math_ops.square(x) + # Log of the term multiplying (1 + sum) + log_scale = -0.5 * x_2 - math_ops.log(-x) - 0.5 * np.log(2. * np.pi) + return log_scale + math_ops.log(_log_ndtr_asymptotic_series(x, series_order)) + + +def _log_ndtr_asymptotic_series(x, series_order): + """Calculates the asymptotic series used in log_ndtr.""" + dtype = x.dtype.as_numpy_dtype + if series_order <= 0: + return np.array(1, dtype) + x_2 = math_ops.square(x) + even_sum = array_ops.zeros_like(x) + odd_sum = array_ops.zeros_like(x) + x_2n = x_2 # Start with x^{2*1} = x^{2*n} with n = 1. + for n in range(1, series_order + 1): + y = np.array(_double_factorial(2 * n - 1), dtype) / x_2n + if n % 2: + odd_sum += y + else: + even_sum += y + x_2n *= x_2 + return 1. + even_sum - odd_sum + + +def erfinv(x, name="erfinv"): + """The inverse function for erf, the error function. + + Args: + x: `Tensor` of type `float32`, `float64`. + name: Python string. A name for the operation (default="erfinv"). + + Returns: + x: `Tensor` with `dtype=x.dtype`. + + Raises: + TypeError: if `x` is not floating-type. + """ + + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + if x.dtype.as_numpy_dtype not in [np.float32, np.float64]: + raise TypeError( + "x.dtype=%s is not handled, see docstring for supported types." + % x.dtype) + return ndtri((x + 1.0) / 2.0) / np.sqrt(2) + + +def _double_factorial(n): + """The double factorial function for small Python integer `n`.""" + return np.prod(np.arange(n, 1, -2)) + + +def log_cdf_laplace(x, name="log_cdf_laplace"): + """Log Laplace distribution function. + + This function calculates `Log[L(x)]`, where `L(x)` is the cumulative + distribution function of the Laplace distribution, i.e. + + ```L(x) := 0.5 * int_{-infty}^x e^{-|t|} dt``` + + For numerical accuracy, `L(x)` is computed in different ways depending on `x`, + + ``` + x <= 0: + Log[L(x)] = Log[0.5] + x, which is exact + + 0 < x: + Log[L(x)] = Log[1 - 0.5 * e^{-x}], which is exact + ``` + + Args: + x: `Tensor` of type `float32`, `float64`. + name: Python string. A name for the operation (default="log_ndtr"). + + Returns: + `Tensor` with `dtype=x.dtype`. + + Raises: + TypeError: if `x.dtype` is not handled. + """ + + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + + # For x < 0, L(x) = 0.5 * exp{x} exactly, so Log[L(x)] = log(0.5) + x. + lower_solution = -np.log(2.) + x + + # safe_exp_neg_x = exp{-x} for x > 0, but is + # bounded above by 1, which avoids + # log[1 - 1] = -inf for x = log(1/2), AND + # exp{-x} --> inf, for x << -1 + safe_exp_neg_x = math_ops.exp(-math_ops.abs(x)) + + # log1p(z) = log(1 + z) approx z for |z| << 1. This approximation is used + # internally by log1p, rather than being done explicitly here. + upper_solution = math_ops.log1p(-0.5 * safe_exp_neg_x) + + return array_ops.where_v2(x < 0., lower_solution, upper_solution) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/student_t.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/student_t.py new file mode 100644 index 0000000000000000000000000000000000000000..63e4f73c2b0000825f58cb4ff0c5264a59b8946d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/student_t.py @@ -0,0 +1,391 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Student's t distribution class.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "StudentT", + "StudentTWithAbsDfSoftplusScale", +] + + +@tf_export(v1=["distributions.StudentT"]) +class StudentT(distribution.Distribution): + """Student's t-distribution. + + This distribution has parameters: degree of freedom `df`, location `loc`, + and `scale`. + + #### Mathematical details + + The probability density function (pdf) is, + + ```none + pdf(x; df, mu, sigma) = (1 + y**2 / df)**(-0.5 (df + 1)) / Z + where, + y = (x - mu) / sigma + Z = abs(sigma) sqrt(df pi) Gamma(0.5 df) / Gamma(0.5 (df + 1)) + ``` + + where: + * `loc = mu`, + * `scale = sigma`, and, + * `Z` is the normalization constant, and, + * `Gamma` is the [gamma function]( + https://en.wikipedia.org/wiki/Gamma_function). + + The StudentT distribution is a member of the [location-scale family]( + https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be + constructed as, + + ```none + X ~ StudentT(df, loc=0, scale=1) + Y = loc + scale * X + ``` + + Notice that `scale` has semantics more similar to standard deviation than + variance. However it is not actually the std. deviation; the Student's + t-distribution std. dev. is `scale sqrt(df / (df - 2))` when `df > 2`. + + Samples of this distribution are reparameterized (pathwise differentiable). + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + #### Examples + + Examples of initialization of one or a batch of distributions. + + ```python + import tensorflow_probability as tfp + tfd = tfp.distributions + + # Define a single scalar Student t distribution. + single_dist = tfd.StudentT(df=3) + + # Evaluate the pdf at 1, returning a scalar Tensor. + single_dist.prob(1.) + + # Define a batch of two scalar valued Student t's. + # The first has degrees of freedom 2, mean 1, and scale 11. + # The second 3, 2 and 22. + multi_dist = tfd.StudentT(df=[2, 3], loc=[1, 2.], scale=[11, 22.]) + + # Evaluate the pdf of the first distribution on 0, and the second on 1.5, + # returning a length two tensor. + multi_dist.prob([0, 1.5]) + + # Get 3 samples, returning a 3 x 2 tensor. + multi_dist.sample(3) + ``` + + Arguments are broadcast when possible. + + ```python + # Define a batch of two Student's t distributions. + # Both have df 2 and mean 1, but different scales. + dist = tfd.StudentT(df=2, loc=1, scale=[11, 22.]) + + # Evaluate the pdf of both distributions on the same point, 3.0, + # returning a length 2 tensor. + dist.prob(3.0) + ``` + + Compute the gradients of samples w.r.t. the parameters: + + ```python + df = tf.constant(2.0) + loc = tf.constant(2.0) + scale = tf.constant(11.0) + dist = tfd.StudentT(df=df, loc=loc, scale=scale) + samples = dist.sample(5) # Shape [5] + loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function + # Unbiased stochastic gradients of the loss function + grads = tf.gradients(loss, [df, loc, scale]) + ``` + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf](http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + df, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="StudentT"): + """Construct Student's t distributions. + + The distributions have degree of freedom `df`, mean `loc`, and scale + `scale`. + + The parameters `df`, `loc`, and `scale` must be shaped in a way that + supports broadcasting (e.g. `df + loc + scale` is a valid operation). + + Args: + df: Floating-point `Tensor`. The degrees of freedom of the + distribution(s). `df` must contain only positive values. + loc: Floating-point `Tensor`. The mean(s) of the distribution(s). + scale: Floating-point `Tensor`. The scaling factor(s) for the + distribution(s). Note that `scale` is not technically the standard + deviation of this distribution but has semantics more similar to + standard deviation than variance. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, + statistics (e.g., mean, mode, variance) use the value "`NaN`" to + indicate the result is undefined. When `False`, an exception is raised + if one or more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + TypeError: if loc and scale are different dtypes. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[df, loc, scale]) as name: + with ops.control_dependencies([check_ops.assert_positive(df)] + if validate_args else []): + self._df = array_ops.identity(df, name="df") + self._loc = array_ops.identity(loc, name="loc") + self._scale = array_ops.identity(scale, name="scale") + check_ops.assert_same_float_dtype( + (self._df, self._loc, self._scale)) + super(StudentT, self).__init__( + dtype=self._scale.dtype, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._df, self._loc, self._scale], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("df", "loc", "scale"), ( + [ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32)] * 3))) + + @property + def df(self): + """Degrees of freedom in these Student's t distribution(s).""" + return self._df + + @property + def loc(self): + """Locations of these Student's t distribution(s).""" + return self._loc + + @property + def scale(self): + """Scaling factors of these Student's t distribution(s).""" + return self._scale + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.df), + array_ops.broadcast_dynamic_shape( + array_ops.shape(self.loc), array_ops.shape(self.scale))) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + array_ops.broadcast_static_shape(self.df.get_shape(), + self.loc.get_shape()), + self.scale.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=math_ops.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + # The sampling method comes from the fact that if: + # X ~ Normal(0, 1) + # Z ~ Chi2(df) + # Y = X / sqrt(Z / df) + # then: + # Y ~ StudentT(df). + shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + normal_sample = random_ops.random_normal(shape, dtype=self.dtype, seed=seed) + df = self.df * array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype) + gamma_sample = random_ops.random_gamma( + [n], + 0.5 * df, + beta=0.5, + dtype=self.dtype, + seed=distribution_util.gen_new_seed(seed, salt="student_t")) + samples = normal_sample * math_ops.rsqrt(gamma_sample / df) + return samples * self.scale + self.loc # Abs(scale) not wanted. + + def _log_prob(self, x): + return self._log_unnormalized_prob(x) - self._log_normalization() + + def _log_unnormalized_prob(self, x): + y = (x - self.loc) / self.scale # Abs(scale) superfluous. + return -0.5 * (self.df + 1.) * math_ops.log1p(y**2. / self.df) + + def _log_normalization(self): + return (math_ops.log(math_ops.abs(self.scale)) + + 0.5 * math_ops.log(self.df) + + 0.5 * np.log(np.pi) + + math_ops.lgamma(0.5 * self.df) - + math_ops.lgamma(0.5 * (self.df + 1.))) + + def _cdf(self, x): + # Take Abs(scale) to make subsequent where work correctly. + y = (x - self.loc) / math_ops.abs(self.scale) + x_t = self.df / (y**2. + self.df) + neg_cdf = 0.5 * math_ops.betainc(0.5 * self.df, 0.5, x_t) + return array_ops.where_v2(math_ops.less(y, 0.), neg_cdf, 1. - neg_cdf) + + def _entropy(self): + v = array_ops.ones(self.batch_shape_tensor(), + dtype=self.dtype)[..., array_ops.newaxis] + u = v * self.df[..., array_ops.newaxis] + beta_arg = array_ops.concat([u, v], -1) / 2. + return (math_ops.log(math_ops.abs(self.scale)) + + 0.5 * math_ops.log(self.df) + + special_math_ops.lbeta(beta_arg) + + 0.5 * (self.df + 1.) * + (math_ops.digamma(0.5 * (self.df + 1.)) - + math_ops.digamma(0.5 * self.df))) + + @distribution_util.AppendDocstring( + """The mean of Student's T equals `loc` if `df > 1`, otherwise it is + `NaN`. If `self.allow_nan_stats=True`, then an exception will be raised + rather than returning `NaN`.""") + def _mean(self): + mean = self.loc * array_ops.ones(self.batch_shape_tensor(), + dtype=self.dtype) + if self.allow_nan_stats: + nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype()) + return array_ops.where_v2( + math_ops.greater( + self.df, + array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype)), + mean, array_ops.fill(self.batch_shape_tensor(), nan, name="nan")) + else: + return control_flow_ops.with_dependencies( + [ + check_ops.assert_less( + array_ops.ones([], dtype=self.dtype), + self.df, + message="mean not defined for components of df <= 1"), + ], + mean) + + @distribution_util.AppendDocstring(""" + The variance for Student's T equals + + ``` + df / (df - 2), when df > 2 + infinity, when 1 < df <= 2 + NaN, when df <= 1 + ``` + """) + def _variance(self): + # We need to put the tf.where inside the outer tf.where to ensure we never + # hit a NaN in the gradient. + denom = array_ops.where_v2( + math_ops.greater(self.df, 2.), self.df - 2., + array_ops.ones_like(self.df)) + # Abs(scale) superfluous. + var = (array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype) * + math_ops.square(self.scale) * self.df / denom) + # When 1 < df <= 2, variance is infinite. + inf = np.array(np.inf, dtype=self.dtype.as_numpy_dtype()) + result_where_defined = array_ops.where_v2( + self.df > array_ops.fill(self.batch_shape_tensor(), 2.), var, + array_ops.fill(self.batch_shape_tensor(), inf, name="inf")) + + if self.allow_nan_stats: + nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype()) + return array_ops.where_v2( + math_ops.greater( + self.df, + array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype)), + result_where_defined, + array_ops.fill(self.batch_shape_tensor(), nan, name="nan")) + else: + return control_flow_ops.with_dependencies( + [ + check_ops.assert_less( + array_ops.ones([], dtype=self.dtype), + self.df, + message="variance not defined for components of df <= 1"), + ], + result_where_defined) + + def _mode(self): + return array_ops.identity(self.loc) + + +class StudentTWithAbsDfSoftplusScale(StudentT): + """StudentT with `df = floor(abs(df))` and `scale = softplus(scale)`.""" + + @deprecation.deprecated( + "2019-01-01", + "Use `tfd.StudentT(tf.floor(tf.abs(df)), loc, " + "tf.nn.softplus(scale)) instead.", + warn_once=True) + def __init__(self, + df, + loc, + scale, + validate_args=False, + allow_nan_stats=True, + name="StudentTWithAbsDfSoftplusScale"): + parameters = dict(locals()) + with ops.name_scope(name, values=[df, scale]) as name: + super(StudentTWithAbsDfSoftplusScale, self).__init__( + df=math_ops.floor(math_ops.abs(df)), + loc=loc, + scale=nn.softplus(scale, name="softplus_scale"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=name) + self._parameters = parameters diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/uniform.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/uniform.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6a8874ed1f94019b96640c0d046820ee0fdb40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/uniform.py @@ -0,0 +1,204 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The Uniform distribution class.""" + +import math + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import distribution +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["distributions.Uniform"]) +class Uniform(distribution.Distribution): + """Uniform distribution with `low` and `high` parameters. + + #### Mathematical Details + + The probability density function (pdf) is, + + ```none + pdf(x; a, b) = I[a <= x < b] / Z + Z = b - a + ``` + + where + + - `low = a`, + - `high = b`, + - `Z` is the normalizing constant, and + - `I[predicate]` is the [indicator function]( + https://en.wikipedia.org/wiki/Indicator_function) for `predicate`. + + The parameters `low` and `high` must be shaped in a way that supports + broadcasting (e.g., `high - low` is a valid operation). + + #### Examples + + ```python + # Without broadcasting: + u1 = Uniform(low=3.0, high=4.0) # a single uniform distribution [3, 4] + u2 = Uniform(low=[1.0, 2.0], + high=[3.0, 4.0]) # 2 distributions [1, 3], [2, 4] + u3 = Uniform(low=[[1.0, 2.0], + [3.0, 4.0]], + high=[[1.5, 2.5], + [3.5, 4.5]]) # 4 distributions + ``` + + ```python + # With broadcasting: + u1 = Uniform(low=3.0, high=[5.0, 6.0, 7.0]) # 3 distributions + ``` + + """ + + @deprecation.deprecated( + "2019-01-01", + "The TensorFlow Distributions library has moved to " + "TensorFlow Probability " + "(https://github.com/tensorflow/probability). You " + "should update all references to use `tfp.distributions` " + "instead of `tf.distributions`.", + warn_once=True) + def __init__(self, + low=0., + high=1., + validate_args=False, + allow_nan_stats=True, + name="Uniform"): + """Initialize a batch of Uniform distributions. + + Args: + low: Floating point tensor, lower boundary of the output interval. Must + have `low < high`. + high: Floating point tensor, upper boundary of the output interval. Must + have `low < high`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + InvalidArgumentError: if `low >= high` and `validate_args=False`. + """ + parameters = dict(locals()) + with ops.name_scope(name, values=[low, high]) as name: + with ops.control_dependencies([ + check_ops.assert_less( + low, high, message="uniform not defined when low >= high.") + ] if validate_args else []): + self._low = array_ops.identity(low, name="low") + self._high = array_ops.identity(high, name="high") + check_ops.assert_same_float_dtype([self._low, self._high]) + super(Uniform, self).__init__( + dtype=self._low.dtype, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._low, + self._high], + name=name) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("low", "high"), + ([ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def low(self): + """Lower boundary of the output interval.""" + return self._low + + @property + def high(self): + """Upper boundary of the output interval.""" + return self._high + + def range(self, name="range"): + """`high - low`.""" + with self._name_scope(name): + return self.high - self.low + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.low), + array_ops.shape(self.high)) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + self.low.get_shape(), + self.high.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.TensorShape([]) + + def _sample_n(self, n, seed=None): + shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + samples = random_ops.random_uniform(shape=shape, + dtype=self.dtype, + seed=seed) + return self.low + self.range() * samples + + def _prob(self, x): + broadcasted_x = x * array_ops.ones( + self.batch_shape_tensor(), dtype=x.dtype) + return array_ops.where_v2( + math_ops.is_nan(broadcasted_x), broadcasted_x, + array_ops.where_v2( + math_ops.logical_or(broadcasted_x < self.low, + broadcasted_x >= self.high), + array_ops.zeros_like(broadcasted_x), + array_ops.ones_like(broadcasted_x) / self.range())) + + def _cdf(self, x): + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(x), self.batch_shape_tensor()) + zeros = array_ops.zeros(broadcast_shape, dtype=self.dtype) + ones = array_ops.ones(broadcast_shape, dtype=self.dtype) + broadcasted_x = x * ones + result_if_not_big = array_ops.where_v2( + x < self.low, zeros, (broadcasted_x - self.low) / self.range()) + return array_ops.where_v2(x >= self.high, ones, result_if_not_big) + + def _entropy(self): + return math_ops.log(self.range()) + + def _mean(self): + return (self.low + self.high) / 2. + + def _variance(self): + return math_ops.square(self.range()) / 12. + + def _stddev(self): + return self.range() / math.sqrt(12.) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/util.py new file mode 100644 index 0000000000000000000000000000000000000000..62f91b7003a8a092c38e19f7b7cfbe0139337fa0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/distributions/util.py @@ -0,0 +1,1448 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for probability distributions.""" + +import functools +import hashlib + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.util import tf_inspect + + +def assert_integer_form(x, + data=None, + summarize=None, + message=None, + int_dtype=None, + name="assert_integer_form"): + """Assert that x has integer components (or floats equal to integers). + + Args: + x: Floating-point `Tensor` + data: The tensors to print out if the condition is `False`. Defaults to + error message and first few entries of `x` and `y`. + summarize: Print this many entries of each tensor. + message: A string to prefix to the default message. + int_dtype: A `tf.dtype` used to cast the float to. The default (`None`) + implies the smallest possible signed int will be used for casting. + name: A name for this operation (optional). + + Returns: + Op raising `InvalidArgumentError` if `cast(x, int_dtype) != x`. + """ + with ops.name_scope(name, values=[x, data]): + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_integer: + return control_flow_ops.no_op() + message = message or "{} has non-integer components".format(x) + if int_dtype is None: + try: + int_dtype = { + dtypes.float16: dtypes.int16, + dtypes.float32: dtypes.int32, + dtypes.float64: dtypes.int64, + }[x.dtype.base_dtype] + except KeyError: + raise TypeError("Unrecognized type {}".format(x.dtype.name)) + return check_ops.assert_equal( + x, + math_ops.cast(math_ops.cast(x, int_dtype), x.dtype), + data=data, + summarize=summarize, + message=message, + name=name) + + +def assert_symmetric(matrix): + matrix_t = array_ops.matrix_transpose(matrix) + return control_flow_ops.with_dependencies( + [check_ops.assert_equal(matrix, matrix_t)], matrix) + + +def embed_check_nonnegative_integer_form( + x, name="embed_check_nonnegative_integer_form"): + """Assert x is a non-negative tensor, and optionally of integers.""" + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + assertions = [ + check_ops.assert_non_negative( + x, message="'{}' must be non-negative.".format(x)), + ] + if not x.dtype.is_integer: + assertions += [ + assert_integer_form( + x, + message="'{}' cannot contain fractional components.".format(x)), + ] + return control_flow_ops.with_dependencies(assertions, x) + + +def same_dynamic_shape(a, b): + """Returns whether a and b have the same dynamic shape. + + Args: + a: `Tensor` + b: `Tensor` + + Returns: + `bool` `Tensor` representing if both tensors have the same shape. + """ + a = ops.convert_to_tensor(a, name="a") + b = ops.convert_to_tensor(b, name="b") + + # Here we can't just do math_ops.equal(a.shape, b.shape), since + # static shape inference may break the equality comparison between + # shape(a) and shape(b) in math_ops.equal. + def all_shapes_equal(): + return math_ops.reduce_all( + math_ops.equal( + array_ops.concat( + [array_ops.shape(a), array_ops.shape(b)], 0), + array_ops.concat( + [array_ops.shape(b), array_ops.shape(a)], 0))) + + # One of the shapes isn't fully defined, so we need to use the dynamic + # shape. + return tf_cond.cond( + math_ops.equal(array_ops.rank(a), array_ops.rank(b)), + all_shapes_equal, lambda: constant_op.constant(False)) + + +def maybe_get_static_value(x, dtype=None): + """Helper which tries to return a static value. + + Given `x`, extract it's value statically, optionally casting to a specific + dtype. If this is not possible, None is returned. + + Args: + x: `Tensor` for which to extract a value statically. + dtype: Optional dtype to cast to. + + Returns: + Statically inferred value if possible, otherwise None. + """ + if x is None: + return x + try: + # This returns an np.ndarray. + x_ = tensor_util.constant_value(x) + except TypeError: + x_ = x + if x_ is None or dtype is None: + return x_ + return np.array(x_, dtype) + + +def get_logits_and_probs(logits=None, + probs=None, + multidimensional=False, + validate_args=False, + name="get_logits_and_probs", + dtype=None): + """Converts logit to probabilities (or vice-versa), and returns both. + + Args: + logits: Floating-point `Tensor` representing log-odds. + probs: Floating-point `Tensor` representing probabilities. + multidimensional: Python `bool`, default `False`. If `True`, represents + whether the last dimension of `logits` or `probs`, a `[N1, N2, ... k]` + dimensional tensor, representing the logit or probability of `shape[-1]` + classes. + validate_args: Python `bool`, default `False`. When `True`, either assert `0 + <= probs <= 1` (if not `multidimensional`) or that the last dimension of + `probs` sums to one. + name: A name for this operation (optional). + dtype: `tf.DType` to prefer when converting args to `Tensor`s. + + Returns: + logits, probs: Tuple of `Tensor`s. If `probs` has an entry that is `0` or + `1`, then the corresponding entry in the returned logit will be `-Inf` and + `Inf` respectively. + + Raises: + ValueError: if neither `probs` nor `logits` were passed in, or both were. + """ + with ops.name_scope(name, values=[probs, logits]): + if (probs is None) == (logits is None): + raise ValueError("Must pass probs or logits, but not both.") + + if probs is None: + logits = ops.convert_to_tensor(logits, name="logits", dtype=dtype) + if not logits.dtype.is_floating: + raise TypeError("logits must having floating type.") + # We can early return since we constructed probs and therefore know + # they're valid. + if multidimensional: + if validate_args: + logits = embed_check_categorical_event_shape(logits) + return logits, nn.softmax(logits, name="probs") + return logits, math_ops.sigmoid(logits, name="probs") + + probs = ops.convert_to_tensor(probs, name="probs", dtype=dtype) + if not probs.dtype.is_floating: + raise TypeError("probs must having floating type.") + + if validate_args: + with ops.name_scope("validate_probs"): + one = constant_op.constant(1., probs.dtype) + dependencies = [check_ops.assert_non_negative(probs)] + if multidimensional: + probs = embed_check_categorical_event_shape(probs) + dependencies += [ + check_ops.assert_near( + math_ops.reduce_sum(probs, -1), + one, + message="probs does not sum to 1.") + ] + else: + dependencies += [ + check_ops.assert_less_equal( + probs, one, message="probs has components greater than 1.") + ] + probs = control_flow_ops.with_dependencies(dependencies, probs) + + with ops.name_scope("logits"): + if multidimensional: + # Here we don't compute the multidimensional case, in a manner + # consistent with respect to the unidimensional case. We do so + # following the TF convention. Typically, you might expect to see + # logits = log(probs) - log(probs[pivot]). A side-effect of + # being consistent with the TF approach is that the unidimensional case + # implicitly handles the second dimension but the multidimensional case + # explicitly keeps the pivot dimension. + return math_ops.log(probs), probs + return math_ops.log(probs) - math_ops.log1p(-1. * probs), probs + + +def _is_known_unsigned_by_dtype(dt): + """Helper returning True if dtype is known to be unsigned.""" + return { + dtypes.bool: True, + dtypes.uint8: True, + dtypes.uint16: True, + }.get(dt.base_dtype, False) + + +def _is_known_signed_by_dtype(dt): + """Helper returning True if dtype is known to be signed.""" + return { + dtypes.float16: True, + dtypes.float32: True, + dtypes.float64: True, + dtypes.int8: True, + dtypes.int16: True, + dtypes.int32: True, + dtypes.int64: True, + }.get(dt.base_dtype, False) + + +def _is_known_dtype(dt): + """Helper returning True if dtype is known.""" + return _is_known_unsigned_by_dtype(dt) or _is_known_signed_by_dtype(dt) + + +def _largest_integer_by_dtype(dt): + """Helper returning the largest integer exactly representable by dtype.""" + if not _is_known_dtype(dt): + raise TypeError("Unrecognized dtype: {}".format(dt.name)) + if dt.is_floating: + return int(2**(np.finfo(dt.as_numpy_dtype).nmant + 1)) + if dt.is_integer: + return np.iinfo(dt.as_numpy_dtype).max + if dt.base_dtype == dtypes.bool: + return int(1) + # We actually can't land here but keep the case for completeness. + raise TypeError("Unrecognized dtype: {}".format(dt.name)) + + +def _smallest_integer_by_dtype(dt): + """Helper returning the smallest integer exactly representable by dtype.""" + if not _is_known_dtype(dt): + raise TypeError("Unrecognized dtype: {}".format(dt.name)) + if _is_known_unsigned_by_dtype(dt): + return 0 + return -1 * _largest_integer_by_dtype(dt) + + +def _is_integer_like_by_dtype(dt): + """Helper returning True if dtype.is_integer or is `bool`.""" + if not _is_known_dtype(dt): + raise TypeError("Unrecognized dtype: {}".format(dt.name)) + return dt.is_integer or dt.base_dtype == dtypes.bool + + +def embed_check_categorical_event_shape( + categorical_param, name="embed_check_categorical_event_shape"): + """Embeds checks that categorical distributions don't have too many classes. + + A categorical-type distribution is one which, e.g., returns the class label + rather than a one-hot encoding. E.g., `Categorical(probs)`. + + Since distributions output samples in the same dtype as the parameters, we + must ensure that casting doesn't lose precision. That is, the + `parameter.dtype` implies a maximum number of classes. However, since shape is + `int32` and categorical variables are presumed to be indexes into a `Tensor`, + we must also ensure that the number of classes is no larger than the largest + possible `int32` index, i.e., `2**31-1`. + + In other words the number of classes, `K`, must satisfy the following + condition: + + ```python + K <= min( + int(2**31 - 1), # Largest float as an index. + { + dtypes.float16: int(2**11), # Largest int as a float16. + dtypes.float32: int(2**24), + dtypes.float64: int(2**53), + }.get(categorical_param.dtype.base_dtype, 0)) + ``` + + Args: + categorical_param: Floating-point `Tensor` representing parameters of + distribution over categories. The rightmost shape is presumed to be the + number of categories. + name: A name for this operation (optional). + + Returns: + categorical_param: Input `Tensor` with appropriate assertions embedded. + + Raises: + TypeError: if `categorical_param` has an unknown `dtype`. + ValueError: if we can statically identify `categorical_param` as being too + large (for being closed under int32/float casting). + """ + with ops.name_scope(name, values=[categorical_param]): + x = ops.convert_to_tensor(categorical_param, name="categorical_param") + # The size must not exceed both of: + # - The largest possible int32 (since categorical values are presumed to be + # indexes into a Tensor). + # - The largest possible integer exactly representable under the given + # floating-point dtype (since we need to cast to/from). + # + # The chosen floating-point thresholds are 2**(1 + mantissa_bits). + # For more details, see: + # https://en.wikipedia.org/wiki/Floating-point_arithmetic#Internal_representation + x_dtype = x.dtype.base_dtype + max_event_size = ( + _largest_integer_by_dtype(x_dtype) if x_dtype.is_floating else 0) + if max_event_size == 0: + raise TypeError("Unable to validate size of unrecognized dtype " + "({}).".format(x_dtype.name)) + try: + x_shape_static = x.get_shape().with_rank_at_least(1) + except ValueError: + raise ValueError("A categorical-distribution parameter must have " + "at least 1 dimension.") + if tensor_shape.dimension_value(x_shape_static[-1]) is not None: + event_size = x_shape_static.dims[-1].value + if event_size < 2: + raise ValueError("A categorical-distribution parameter must have at " + "least 2 events.") + if event_size > max_event_size: + raise ValueError("Number of classes exceeds `dtype` precision, i.e., " + "{} implies shape ({}) cannot exceed {}.".format( + x_dtype.name, event_size, max_event_size)) + return x + else: + event_size = array_ops.shape(x, name="x_shape")[-1] + return control_flow_ops.with_dependencies([ + check_ops.assert_rank_at_least( + x, + 1, + message=("A categorical-distribution parameter must have " + "at least 1 dimension.")), + check_ops.assert_greater_equal( + array_ops.shape(x)[-1], + 2, + message=("A categorical-distribution parameter must have at " + "least 2 events.")), + check_ops.assert_less_equal( + event_size, + max_event_size, + message="Number of classes exceeds `dtype` precision, " + "i.e., {} dtype cannot exceed {} shape.".format( + x_dtype.name, max_event_size)), + ], x) + + +def embed_check_integer_casting_closed(x, + target_dtype, + assert_nonnegative=True, + name="embed_check_casting_closed"): + """Ensures integers remain unaffected despite casting to/from int/float types. + + Example integer-types: `uint8`, `int32`, `bool`. + Example floating-types: `float32`, `float64`. + + The largest possible integer representable by an IEEE754 floating-point is + `2**(1 + mantissa_bits)` yet the largest possible integer as an int-type is + `2**(bits - 1) - 1`. This function ensures that a `Tensor` purporting to have + integer-form values can be cast to some other type without loss of precision. + + The smallest representable integer is the negative of the largest + representable integer, except for types: `uint8`, `uint16`, `bool`. For these + types, the smallest representable integer is `0`. + + Args: + x: `Tensor` representing integer-form values. + target_dtype: TF `dtype` under which `x` should have identical values. + assert_nonnegative: `bool` indicating `x` should contain nonnegative values. + name: A name for this operation (optional). + + Returns: + x: Input `Tensor` with appropriate assertions embedded. + + Raises: + TypeError: if `x` is neither integer- nor floating-type. + TypeError: if `target_dtype` is neither integer- nor floating-type. + TypeError: if neither `x` nor `target_dtype` are integer-type. + """ + + with ops.name_scope(name, values=[x]): + x = ops.convert_to_tensor(x, name="x") + if (not _is_integer_like_by_dtype(x.dtype) and not x.dtype.is_floating): + raise TypeError("{}.dtype must be floating- or " + "integer-type.".format(x.dtype.name)) + if (not _is_integer_like_by_dtype(target_dtype) and + not target_dtype.is_floating): + raise TypeError("target_dtype ({}) must be floating- or " + "integer-type.".format(target_dtype.name)) + if (not _is_integer_like_by_dtype(x.dtype) and + not _is_integer_like_by_dtype(target_dtype)): + raise TypeError("At least one of {}.dtype ({}) and target_dtype ({}) " + "must be integer-type.".format(x, x.dtype.name, + target_dtype.name)) + + assertions = [] + if assert_nonnegative: + assertions += [ + check_ops.assert_non_negative( + x, message="Elements must be non-negative."), + ] + + if x.dtype.is_floating: + # Being here means _is_integer_like_by_dtype(target_dtype) = True. + # Since this check implies the magnitude check below, we need only it. + assertions += [ + assert_integer_form( + x, + int_dtype=target_dtype, + message="Elements must be {}-equivalent.".format( + target_dtype.name)), + ] + else: + if (_largest_integer_by_dtype(x.dtype) > + _largest_integer_by_dtype(target_dtype)): + # Cast may lose integer precision. + assertions += [ + check_ops.assert_less_equal( + x, + _largest_integer_by_dtype(target_dtype), + message=("Elements cannot exceed {}.".format( + _largest_integer_by_dtype(target_dtype)))), + ] + if (not assert_nonnegative and (_smallest_integer_by_dtype( + x.dtype) < _smallest_integer_by_dtype(target_dtype))): + assertions += [ + check_ops.assert_greater_equal( + x, + _smallest_integer_by_dtype(target_dtype), + message=("Elements cannot be smaller than {}.".format( + _smallest_integer_by_dtype(target_dtype)))), + ] + + if not assertions: + return x + return control_flow_ops.with_dependencies(assertions, x) + + +def log_combinations(n, counts, name="log_combinations"): + """Multinomial coefficient. + + Given `n` and `counts`, where `counts` has last dimension `k`, we compute + the multinomial coefficient as: + + ```n! / sum_i n_i!``` + + where `i` runs over all `k` classes. + + Args: + n: Floating-point `Tensor` broadcastable with `counts`. This represents `n` + outcomes. + counts: Floating-point `Tensor` broadcastable with `n`. This represents + counts in `k` classes, where `k` is the last dimension of the tensor. + name: A name for this operation (optional). + + Returns: + `Tensor` representing the multinomial coefficient between `n` and `counts`. + """ + # First a bit about the number of ways counts could have come in: + # E.g. if counts = [1, 2], then this is 3 choose 2. + # In general, this is (sum counts)! / sum(counts!) + # The sum should be along the last dimension of counts. This is the + # "distribution" dimension. Here n a priori represents the sum of counts. + with ops.name_scope(name, values=[n, counts]): + n = ops.convert_to_tensor(n, name="n") + counts = ops.convert_to_tensor(counts, name="counts") + total_permutations = math_ops.lgamma(n + 1) + counts_factorial = math_ops.lgamma(counts + 1) + redundant_permutations = math_ops.reduce_sum(counts_factorial, axis=[-1]) + return total_permutations - redundant_permutations + + +def matrix_diag_transform(matrix, transform=None, name=None): + """Transform diagonal of [batch-]matrix, leave rest of matrix unchanged. + + Create a trainable covariance defined by a Cholesky factor: + + ```python + # Transform network layer into 2 x 2 array. + matrix_values = tf.contrib.layers.fully_connected(activations, 4) + matrix = tf.reshape(matrix_values, (batch_size, 2, 2)) + + # Make the diagonal positive. If the upper triangle was zero, this would be a + # valid Cholesky factor. + chol = matrix_diag_transform(matrix, transform=tf.nn.softplus) + + # LinearOperatorLowerTriangular ignores the upper triangle. + operator = LinearOperatorLowerTriangular(chol) + ``` + + Example of heteroskedastic 2-D linear regression. + + ```python + tfd = tfp.distributions + + # Get a trainable Cholesky factor. + matrix_values = tf.contrib.layers.fully_connected(activations, 4) + matrix = tf.reshape(matrix_values, (batch_size, 2, 2)) + chol = matrix_diag_transform(matrix, transform=tf.nn.softplus) + + # Get a trainable mean. + mu = tf.contrib.layers.fully_connected(activations, 2) + + # This is a fully trainable multivariate normal! + dist = tfd.MultivariateNormalTriL(mu, chol) + + # Standard log loss. Minimizing this will "train" mu and chol, and then dist + # will be a distribution predicting labels as multivariate Gaussians. + loss = -1 * tf.reduce_mean(dist.log_prob(labels)) + ``` + + Args: + matrix: Rank `R` `Tensor`, `R >= 2`, where the last two dimensions are + equal. + transform: Element-wise function mapping `Tensors` to `Tensors`. To be + applied to the diagonal of `matrix`. If `None`, `matrix` is returned + unchanged. Defaults to `None`. + name: A name to give created ops. Defaults to "matrix_diag_transform". + + Returns: + A `Tensor` with same shape and `dtype` as `matrix`. + """ + with ops.name_scope(name, "matrix_diag_transform", [matrix]): + matrix = ops.convert_to_tensor(matrix, name="matrix") + if transform is None: + return matrix + # Replace the diag with transformed diag. + diag = array_ops.matrix_diag_part(matrix) + transformed_diag = transform(diag) + transformed_mat = array_ops.matrix_set_diag(matrix, transformed_diag) + + return transformed_mat + + +def rotate_transpose(x, shift, name="rotate_transpose"): + """Circularly moves dims left or right. + + Effectively identical to: + + ```python + numpy.transpose(x, numpy.roll(numpy.arange(len(x.shape)), shift)) + ``` + + When `validate_args=False` additional graph-runtime checks are + performed. These checks entail moving data from to GPU to CPU. + + Example: + + ```python + x = tf.random.normal([1, 2, 3, 4]) # Tensor of shape [1, 2, 3, 4]. + rotate_transpose(x, -1).shape == [2, 3, 4, 1] + rotate_transpose(x, -2).shape == [3, 4, 1, 2] + rotate_transpose(x, 1).shape == [4, 1, 2, 3] + rotate_transpose(x, 2).shape == [3, 4, 1, 2] + rotate_transpose(x, 7).shape == rotate_transpose(x, 3).shape # [2, 3, 4, 1] + rotate_transpose(x, -7).shape == rotate_transpose(x, -3).shape # [4, 1, 2, 3] + ``` + + Args: + x: `Tensor`. + shift: `Tensor`. Number of dimensions to transpose left (shift<0) or + transpose right (shift>0). + name: Python `str`. The name to give this op. + + Returns: + rotated_x: Input `Tensor` with dimensions circularly rotated by shift. + + Raises: + TypeError: if shift is not integer type. + """ + with ops.name_scope(name, values=[x, shift]): + x = ops.convert_to_tensor(x, name="x") + shift = ops.convert_to_tensor(shift, name="shift") + # We do not assign back to preserve constant-ness. + check_ops.assert_integer(shift) + shift_value_static = tensor_util.constant_value(shift) + ndims = x.get_shape().ndims + if ndims is not None and shift_value_static is not None: + if ndims < 2: + return x + shift_value_static = np.sign(shift_value_static) * ( + abs(shift_value_static) % ndims) + if shift_value_static == 0: + return x + perm = np.roll(np.arange(ndims), shift_value_static) + return array_ops.transpose(x, perm=perm) + else: + # Consider if we always had a positive shift, and some specified + # direction. + # When shifting left we want the new array: + # last(x, n-shift) + first(x, shift) + # and if shifting right then we want: + # last(x, shift) + first(x, n-shift) + # Observe that last(a) == slice(a, n) and first(a) == slice(0, a). + # Also, we can encode direction and shift as one: direction * shift. + # Combining these facts, we have: + # a = cond(shift<0, -shift, n-shift) + # last(x, n-a) + first(x, a) == x[a:n] + x[0:a] + # Finally, we transform shift by modulo length so it can be specified + # independently from the array upon which it operates (like python). + ndims = array_ops.rank(x) + shift = array_ops.where_v2( + math_ops.less(shift, 0), + math_ops.mod(-shift, ndims), # pylint: disable=invalid-unary-operand-type + ndims - math_ops.mod(shift, ndims)) + first = math_ops.range(0, shift) + last = math_ops.range(shift, ndims) + perm = array_ops.concat([last, first], 0) + return array_ops.transpose(x, perm=perm) + + +def pick_vector(cond, true_vector, false_vector, name="pick_vector"): + """Picks possibly different length row `Tensor`s based on condition. + + Value `Tensor`s should have exactly one dimension. + + If `cond` is a python Boolean or `tf.constant` then either `true_vector` or + `false_vector` is immediately returned. I.e., no graph nodes are created and + no validation happens. + + Args: + cond: `Tensor`. Must have `dtype=tf.bool` and be scalar. + true_vector: `Tensor` of one dimension. Returned when cond is `True`. + false_vector: `Tensor` of one dimension. Returned when cond is `False`. + name: Python `str`. The name to give this op. + Example: ```python pick_vector(tf.less(0, 5), tf.range(10, 12), tf.range(15, + 18)) # [10, 11] pick_vector(tf.less(5, 0), tf.range(10, 12), tf.range(15, + 18)) # [15, 16, 17] ``` + + Returns: + true_or_false_vector: `Tensor`. + + Raises: + TypeError: if `cond.dtype != tf.bool` + TypeError: if `cond` is not a constant and + `true_vector.dtype != false_vector.dtype` + """ + with ops.name_scope(name, values=(cond, true_vector, false_vector)): + cond = ops.convert_to_tensor(cond, name="cond") + if cond.dtype != dtypes.bool: + raise TypeError("%s.dtype=%s which is not %s" % + (cond, cond.dtype, dtypes.bool)) + cond_value_static = tensor_util.constant_value(cond) + if cond_value_static is not None: + return true_vector if cond_value_static else false_vector + true_vector = ops.convert_to_tensor(true_vector, name="true_vector") + false_vector = ops.convert_to_tensor(false_vector, name="false_vector") + if true_vector.dtype != false_vector.dtype: + raise TypeError( + "%s.dtype=%s does not match %s.dtype=%s" % + (true_vector, true_vector.dtype, false_vector, false_vector.dtype)) + n = array_ops.shape(true_vector)[0] + return array_ops.slice( + array_ops.concat([true_vector, false_vector], 0), + [array_ops.where_v2(cond, 0, n)], [array_ops.where(cond, n, -1)]) + + +def prefer_static_broadcast_shape(shape1, + shape2, + name="prefer_static_broadcast_shape"): + """Convenience function which statically broadcasts shape when possible. + + Args: + shape1: `1-D` integer `Tensor`. Already converted to tensor! + shape2: `1-D` integer `Tensor`. Already converted to tensor! + name: A string name to prepend to created ops. + + Returns: + The broadcast shape, either as `TensorShape` (if broadcast can be done + statically), or as a `Tensor`. + """ + with ops.name_scope(name, values=[shape1, shape2]): + + def make_shape_tensor(x): + return ops.convert_to_tensor(x, name="shape", dtype=dtypes.int32) + + def get_tensor_shape(s): + if isinstance(s, tensor_shape.TensorShape): + return s + s_ = tensor_util.constant_value(make_shape_tensor(s)) + if s_ is not None: + return tensor_shape.TensorShape(s_) + return None + + def get_shape_tensor(s): + if not isinstance(s, tensor_shape.TensorShape): + return make_shape_tensor(s) + if s.is_fully_defined(): + return make_shape_tensor(s.as_list()) + raise ValueError("Cannot broadcast from partially " + "defined `TensorShape`.") + + shape1_ = get_tensor_shape(shape1) + shape2_ = get_tensor_shape(shape2) + if shape1_ is not None and shape2_ is not None: + return array_ops.broadcast_static_shape(shape1_, shape2_) + + shape1_ = get_shape_tensor(shape1) + shape2_ = get_shape_tensor(shape2) + return array_ops.broadcast_dynamic_shape(shape1_, shape2_) + + +def prefer_static_rank(x): + """Return static rank of tensor `x` if available, else `tf.rank(x)`. + + Args: + x: `Tensor` (already converted). + + Returns: + Numpy array (if static rank is obtainable), else `Tensor`. + """ + return prefer_static_value(array_ops.rank(x)) + + +def prefer_static_shape(x): + """Return static shape of tensor `x` if available, else `tf.shape(x)`. + + Args: + x: `Tensor` (already converted). + + Returns: + Numpy array (if static shape is obtainable), else `Tensor`. + """ + return prefer_static_value(array_ops.shape(x)) + + +def prefer_static_value(x): + """Return static value of tensor `x` if available, else `x`. + + Args: + x: `Tensor` (already converted). + + Returns: + Numpy array (if static value is obtainable), else `Tensor`. + """ + static_x = tensor_util.constant_value(x) + if static_x is not None: + return static_x + return x + + +def gen_new_seed(seed, salt): + """Generate a new seed, from the given seed and salt.""" + if seed is None: + return None + string = (str(seed) + salt).encode("utf-8") + return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF + + +def fill_triangular(x, upper=False, name=None): + """Creates a (batch of) triangular matrix from a vector of inputs. + + Created matrix can be lower- or upper-triangular. (It is more efficient to + create the matrix as upper or lower, rather than transpose.) + + Triangular matrix elements are filled in a clockwise spiral. See example, + below. + + If `x.get_shape()` is `[b1, b2, ..., bB, d]` then the output shape is + `[b1, b2, ..., bB, n, n]` where `n` is such that `d = n(n+1)/2`, i.e., + `n = int(np.sqrt(0.25 + 2. * m) - 0.5)`. + + Example: + + ```python + fill_triangular([1, 2, 3, 4, 5, 6]) + # ==> [[4, 0, 0], + # [6, 5, 0], + # [3, 2, 1]] + + fill_triangular([1, 2, 3, 4, 5, 6], upper=True) + # ==> [[1, 2, 3], + # [0, 5, 6], + # [0, 0, 4]] + ``` + + For comparison, a pure numpy version of this function can be found in + `util_test.py`, function `_fill_triangular`. + + Args: + x: `Tensor` representing lower (or upper) triangular elements. + upper: Python `bool` representing whether output matrix should be upper + triangular (`True`) or lower triangular (`False`, default). + name: Python `str`. The name to give this op. + + Returns: + tril: `Tensor` with lower (or upper) triangular elements filled from `x`. + + Raises: + ValueError: if `x` cannot be mapped to a triangular matrix. + """ + + with ops.name_scope(name, "fill_triangular", values=[x]): + x = ops.convert_to_tensor(x, name="x") + if tensor_shape.dimension_value( + x.shape.with_rank_at_least(1)[-1]) is not None: + # Formula derived by solving for n: m = n(n+1)/2. + m = np.int32(x.shape.dims[-1].value) + n = np.sqrt(0.25 + 2. * m) - 0.5 + if n != np.floor(n): + raise ValueError("Input right-most shape ({}) does not " + "correspond to a triangular matrix.".format(m)) + n = np.int32(n) + static_final_shape = x.shape[:-1].concatenate([n, n]) + else: + m = array_ops.shape(x)[-1] + # For derivation, see above. Casting automatically lops off the 0.5, so we + # omit it. We don't validate n is an integer because this has + # graph-execution cost; an error will be thrown from the reshape, below. + n = math_ops.cast( + math_ops.sqrt(0.25 + math_ops.cast(2 * m, dtype=dtypes.float32)), + dtype=dtypes.int32) + static_final_shape = x.shape.with_rank_at_least(1)[:-1].concatenate( + [None, None]) + # We now concatenate the "tail" of `x` to `x` (and reverse one of them). + # + # We do this based on the insight that the input `x` provides `ceil(n/2)` + # rows of an `n x n` matrix, some of which will get zeroed out being on the + # wrong side of the diagonal. The first row will not get zeroed out at all, + # and we need `floor(n/2)` more rows, so the first is what we omit from + # `x_tail`. If we then stack those `ceil(n/2)` rows with the `floor(n/2)` + # rows provided by a reversed tail, it is exactly the other set of elements + # of the reversed tail which will be zeroed out for being on the wrong side + # of the diagonal further up/down the matrix. And, in doing-so, we've filled + # the triangular matrix in a clock-wise spiral pattern. Neat! + # + # Try it out in numpy: + # n = 3 + # x = np.arange(n * (n + 1) / 2) + # m = x.shape[0] + # n = np.int32(np.sqrt(.25 + 2 * m) - .5) + # x_tail = x[(m - (n**2 - m)):] + # np.concatenate([x_tail, x[::-1]], 0).reshape(n, n) # lower + # # ==> array([[3, 4, 5], + # [5, 4, 3], + # [2, 1, 0]]) + # np.concatenate([x, x_tail[::-1]], 0).reshape(n, n) # upper + # # ==> array([[0, 1, 2], + # [3, 4, 5], + # [5, 4, 3]]) + # + # Note that we can't simply do `x[..., -(n**2 - m):]` because this doesn't + # correctly handle `m == n == 1`. Hence, we do nonnegative indexing. + # Furthermore observe that: + # m - (n**2 - m) + # = n**2 / 2 + n / 2 - (n**2 - n**2 / 2 + n / 2) + # = 2 (n**2 / 2 + n / 2) - n**2 + # = n**2 + n - n**2 + # = n + ndims = prefer_static_rank(x) + if upper: + x_list = [x, array_ops.reverse(x[..., n:], axis=[ndims - 1])] + else: + x_list = [x[..., n:], array_ops.reverse(x, axis=[ndims - 1])] + new_shape = ( + static_final_shape.as_list() if static_final_shape.is_fully_defined() + else array_ops.concat([array_ops.shape(x)[:-1], [n, n]], axis=0)) + x = array_ops.reshape(array_ops.concat(x_list, axis=-1), new_shape) + x = array_ops.matrix_band_part( + x, num_lower=(0 if upper else -1), num_upper=(-1 if upper else 0)) + x.set_shape(static_final_shape) + return x + + +def fill_triangular_inverse(x, upper=False, name=None): + """Creates a vector from a (batch of) triangular matrix. + + The vector is created from the lower-triangular or upper-triangular portion + depending on the value of the parameter `upper`. + + If `x.shape` is `[b1, b2, ..., bB, n, n]` then the output shape is + `[b1, b2, ..., bB, d]` where `d = n (n + 1) / 2`. + + Example: + + ```python + fill_triangular_inverse( + [[4, 0, 0], + [6, 5, 0], + [3, 2, 1]]) + + # ==> [1, 2, 3, 4, 5, 6] + + fill_triangular_inverse( + [[1, 2, 3], + [0, 5, 6], + [0, 0, 4]], upper=True) + + # ==> [1, 2, 3, 4, 5, 6] + ``` + + Args: + x: `Tensor` representing lower (or upper) triangular elements. + upper: Python `bool` representing whether output matrix should be upper + triangular (`True`) or lower triangular (`False`, default). + name: Python `str`. The name to give this op. + + Returns: + flat_tril: (Batch of) vector-shaped `Tensor` representing vectorized lower + (or upper) triangular elements from `x`. + """ + + with ops.name_scope(name, "fill_triangular_inverse", values=[x]): + x = ops.convert_to_tensor(x, name="x") + if tensor_shape.dimension_value( + x.shape.with_rank_at_least(2)[-1]) is not None: + n = np.int32(x.shape.dims[-1].value) + m = np.int32((n * (n + 1)) // 2) + static_final_shape = x.shape[:-2].concatenate([m]) + else: + n = array_ops.shape(x)[-1] + m = (n * (n + 1)) // 2 + static_final_shape = x.shape.with_rank_at_least(2)[:-2].concatenate( + [None]) + ndims = prefer_static_rank(x) + if upper: + initial_elements = x[..., 0, :] + triangular_portion = x[..., 1:, :] + else: + initial_elements = array_ops.reverse(x[..., -1, :], axis=[ndims - 2]) + triangular_portion = x[..., :-1, :] + rotated_triangular_portion = array_ops.reverse( + array_ops.reverse(triangular_portion, axis=[ndims - 1]), + axis=[ndims - 2]) + consolidated_matrix = triangular_portion + rotated_triangular_portion + end_sequence = array_ops.reshape( + consolidated_matrix, + array_ops.concat([array_ops.shape(x)[:-2], [n * (n - 1)]], axis=0)) + y = array_ops.concat([initial_elements, end_sequence[..., :m - n]], axis=-1) + y.set_shape(static_final_shape) + return y + + +def tridiag(below=None, diag=None, above=None, name=None): + """Creates a matrix with values set above, below, and on the diagonal. + + Example: + + ```python + tridiag(below=[1., 2., 3.], + diag=[4., 5., 6., 7.], + above=[8., 9., 10.]) + # ==> array([[ 4., 8., 0., 0.], + # [ 1., 5., 9., 0.], + # [ 0., 2., 6., 10.], + # [ 0., 0., 3., 7.]], dtype=float32) + ``` + + Warning: This Op is intended for convenience, not efficiency. + + Args: + below: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the below + diagonal part. `None` is logically equivalent to `below = 0`. + diag: `Tensor` of shape `[B1, ..., Bb, d]` corresponding to the diagonal + part. `None` is logically equivalent to `diag = 0`. + above: `Tensor` of shape `[B1, ..., Bb, d-1]` corresponding to the above + diagonal part. `None` is logically equivalent to `above = 0`. + name: Python `str`. The name to give this op. + + Returns: + tridiag: `Tensor` with values set above, below and on the diagonal. + + Raises: + ValueError: if all inputs are `None`. + """ + + def _pad(x): + """Prepends and appends a zero to every vector in a batch of vectors.""" + shape = array_ops.concat([array_ops.shape(x)[:-1], [1]], axis=0) + z = array_ops.zeros(shape, dtype=x.dtype) + return array_ops.concat([z, x, z], axis=-1) + + def _add(*x): + """Adds list of Tensors, ignoring `None`.""" + s = None + for y in x: + if y is None: + continue + elif s is None: + s = y + else: + s += y + if s is None: + raise ValueError("Must specify at least one of `below`, `diag`, `above`.") + return s + + with ops.name_scope(name, "tridiag", [below, diag, above]): + if below is not None: + below = ops.convert_to_tensor(below, name="below") + below = array_ops.matrix_diag(_pad(below))[..., :-1, 1:] + if diag is not None: + diag = ops.convert_to_tensor(diag, name="diag") + diag = array_ops.matrix_diag(diag) + if above is not None: + above = ops.convert_to_tensor(above, name="above") + above = array_ops.matrix_diag(_pad(above))[..., 1:, :-1] + # TODO(jvdillon): Consider using scatter_nd instead of creating three full + # matrices. + return _add(below, diag, above) + + +def reduce_weighted_logsumexp(logx, + w=None, + axis=None, + keep_dims=False, + return_sign=False, + name=None): + """Computes `log(abs(sum(weight * exp(elements across tensor dimensions))))`. + + If all weights `w` are known to be positive, it is more efficient to directly + use `reduce_logsumexp`, i.e., `tf.reduce_logsumexp(logx + tf.math.log(w))` is + more + efficient than `du.reduce_weighted_logsumexp(logx, w)`. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each + entry in `axis`. If `keep_dims` is true, the reduced dimensions + are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a + tensor with a single element is returned. + + This function is more numerically stable than log(sum(w * exp(input))). It + avoids overflows caused by taking the exp of large inputs and underflows + caused by taking the log of small inputs. + + For example: + + ```python + x = tf.constant([[0., 0, 0], + [0, 0, 0]]) + + w = tf.constant([[-1., 1, 1], + [1, 1, 1]]) + + du.reduce_weighted_logsumexp(x, w) + # ==> log(-1*1 + 1*1 + 1*1 + 1*1 + 1*1 + 1*1) = log(4) + + du.reduce_weighted_logsumexp(x, w, axis=0) + # ==> [log(-1+1), log(1+1), log(1+1)] + + du.reduce_weighted_logsumexp(x, w, axis=1) + # ==> [log(-1+1+1), log(1+1+1)] + + du.reduce_weighted_logsumexp(x, w, axis=1, keep_dims=True) + # ==> [[log(-1+1+1)], [log(1+1+1)]] + + du.reduce_weighted_logsumexp(x, w, axis=[0, 1]) + # ==> log(-1+5) + ``` + + Args: + logx: The tensor to reduce. Should have numeric type. + w: The weight tensor. Should have numeric type identical to `logx`. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keep_dims: If true, retains reduced dimensions with length 1. + return_sign: If `True`, returns the sign of the result. + name: A name for the operation (optional). + + Returns: + lswe: The `log(abs(sum(weight * exp(x))))` reduced tensor. + sign: (Optional) The sign of `sum(weight * exp(x))`. + """ + with ops.name_scope(name, "reduce_weighted_logsumexp", [logx, w]): + logx = ops.convert_to_tensor(logx, name="logx") + if w is None: + lswe = math_ops.reduce_logsumexp(logx, axis=axis, keepdims=keep_dims) + if return_sign: + sgn = array_ops.ones_like(lswe) + return lswe, sgn + return lswe + w = ops.convert_to_tensor(w, dtype=logx.dtype, name="w") + log_absw_x = logx + math_ops.log(math_ops.abs(w)) + max_log_absw_x = math_ops.reduce_max(log_absw_x, axis=axis, keepdims=True) + # If the largest element is `-inf` or `inf` then we don't bother subtracting + # off the max. We do this because otherwise we'd get `inf - inf = NaN`. That + # this is ok follows from the fact that we're actually free to subtract any + # value we like, so long as we add it back after taking the `log(sum(...))`. + max_log_absw_x = array_ops.where_v2( + math_ops.is_inf(max_log_absw_x), array_ops.zeros_like(max_log_absw_x), + max_log_absw_x) + wx_over_max_absw_x = ( + math_ops.sign(w) * math_ops.exp(log_absw_x - max_log_absw_x)) + sum_wx_over_max_absw_x = math_ops.reduce_sum( + wx_over_max_absw_x, axis=axis, keepdims=keep_dims) + if not keep_dims: + max_log_absw_x = array_ops.squeeze(max_log_absw_x, axis) + sgn = math_ops.sign(sum_wx_over_max_absw_x) + lswe = max_log_absw_x + math_ops.log(sgn * sum_wx_over_max_absw_x) + if return_sign: + return lswe, sgn + return lswe + + +# TODO(jvdillon): Merge this test back into: +# tensorflow/python/ops/softplus_op_test.py +# once TF core is accepting new ops. +def softplus_inverse(x, name=None): + """Computes the inverse softplus, i.e., x = softplus_inverse(softplus(x)). + + Mathematically this op is equivalent to: + + ```none + softplus_inverse = log(exp(x) - 1.) + ``` + + Args: + x: `Tensor`. Non-negative (not enforced), floating-point. + name: A name for the operation (optional). + + Returns: + `Tensor`. Has the same type/shape as input `x`. + """ + with ops.name_scope(name, "softplus_inverse", values=[x]): + x = ops.convert_to_tensor(x, name="x") + # We begin by deriving a more numerically stable softplus_inverse: + # x = softplus(y) = Log[1 + exp{y}], (which means x > 0). + # ==> exp{x} = 1 + exp{y} (1) + # ==> y = Log[exp{x} - 1] (2) + # = Log[(exp{x} - 1) / exp{x}] + Log[exp{x}] + # = Log[(1 - exp{-x}) / 1] + Log[exp{x}] + # = Log[1 - exp{-x}] + x (3) + # (2) is the "obvious" inverse, but (3) is more stable than (2) for large x. + # For small x (e.g. x = 1e-10), (3) will become -inf since 1 - exp{-x} will + # be zero. To fix this, we use 1 - exp{-x} approx x for small x > 0. + # + # In addition to the numerically stable derivation above, we clamp + # small/large values to be congruent with the logic in: + # tensorflow/core/kernels/softplus_op.h + # + # Finally, we set the input to one whenever the input is too large or too + # small. This ensures that no unchosen codepath is +/- inf. This is + # necessary to ensure the gradient doesn't get NaNs. Recall that the + # gradient of `where` behaves like `pred*pred_true + (1-pred)*pred_false` + # thus an `inf` in an unselected path results in `0*inf=nan`. We are careful + # to overwrite `x` with ones only when we will never actually use this + # value. Note that we use ones and not zeros since `log(expm1(0.)) = -inf`. + threshold = np.log(np.finfo(x.dtype.as_numpy_dtype).eps) + 2. + is_too_small = math_ops.less(x, np.exp(threshold)) + is_too_large = math_ops.greater(x, -threshold) + too_small_value = math_ops.log(x) + too_large_value = x + # This `where` will ultimately be a NOP because we won't select this + # codepath whenever we used the surrogate `ones_like`. + x = array_ops.where_v2( + math_ops.logical_or(is_too_small, is_too_large), array_ops.ones_like(x), + x) + y = x + math_ops.log(-math_ops.expm1(-x)) # == log(expm1(x)) + return array_ops.where_v2( + is_too_small, too_small_value, + array_ops.where_v2(is_too_large, too_large_value, y)) + + +# TODO(b/35290280): Add unit-tests. +def dimension_size(x, axis): + """Returns the size of a specific dimension.""" + # Since tf.gather isn't "constant-in, constant-out", we must first check the + # static shape or fallback to dynamic shape. + s = tensor_shape.dimension_value( + x.shape.with_rank_at_least(np.abs(axis))[axis]) + if s is not None: + return s + return array_ops.shape(x)[axis] + + +def process_quadrature_grid_and_probs(quadrature_grid_and_probs, + dtype, + validate_args, + name=None): + """Validates quadrature grid, probs or computes them as necessary. + + Args: + quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s + representing the sample points and the corresponding (possibly + normalized) weight. When `None`, defaults to: + `np.polynomial.hermite.hermgauss(deg=8)`. + dtype: The expected `dtype` of `grid` and `probs`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + name: Python `str` name prefixed to Ops created by this class. + + Returns: + quadrature_grid_and_probs: Python pair of `float`-like `Tensor`s + representing the sample points and the corresponding (possibly + normalized) weight. + + Raises: + ValueError: if `quadrature_grid_and_probs is not None` and + `len(quadrature_grid_and_probs[0]) != len(quadrature_grid_and_probs[1])` + """ + with ops.name_scope(name, "process_quadrature_grid_and_probs", + [quadrature_grid_and_probs]): + if quadrature_grid_and_probs is None: + grid, probs = np.polynomial.hermite.hermgauss(deg=8) + grid = grid.astype(dtype.as_numpy_dtype) + probs = probs.astype(dtype.as_numpy_dtype) + probs /= np.linalg.norm(probs, ord=1, keepdims=True) + grid = ops.convert_to_tensor(grid, name="grid", dtype=dtype) + probs = ops.convert_to_tensor(probs, name="probs", dtype=dtype) + return grid, probs + + grid, probs = tuple(quadrature_grid_and_probs) + grid = ops.convert_to_tensor(grid, name="grid", dtype=dtype) + probs = ops.convert_to_tensor(probs, name="unnormalized_probs", dtype=dtype) + probs /= linalg_ops.norm(probs, ord=1, axis=-1, keepdims=True, name="probs") + + def _static_event_size(x): + """Returns the static size of a specific dimension or `None`.""" + return tensor_shape.dimension_value(x.shape.with_rank_at_least(1)[-1]) + + m, n = _static_event_size(probs), _static_event_size(grid) + if m is not None and n is not None: + if m != n: + raise ValueError("`quadrature_grid_and_probs` must be a `tuple` of " + "same-length zero-th-dimension `Tensor`s " + "(saw lengths {}, {})".format(m, n)) + elif validate_args: + assertions = [ + check_ops.assert_equal( + dimension_size(probs, axis=-1), + dimension_size(grid, axis=-1), + message=("`quadrature_grid_and_probs` must be a `tuple` of " + "same-length zero-th-dimension `Tensor`s")), + ] + with ops.control_dependencies(assertions): + grid = array_ops.identity(grid) + probs = array_ops.identity(probs) + return grid, probs + + +def pad(x, axis, front=False, back=False, value=0, count=1, name=None): + """Pads `value` to the front and/or back of a `Tensor` dim, `count` times. + + Args: + x: `Tensor` input. + axis: Scalar `int`-like `Tensor` representing the single dimension to pad. + (Negative indexing is supported.) + front: Python `bool`; if `True` the beginning of the `axis` dimension is + padded with `value`, `count` times. If `False` no front padding is made. + back: Python `bool`; if `True` the end of the `axis` dimension is padded + with `value`, `count` times. If `False` no end padding is made. + value: Scalar `int`-like `Tensor` representing the actual value added to the + front and/or back of the `axis` dimension of `x`. + count: Scalar `int`-like `Tensor` representing number of elements added to + the front and/or back of the `axis` dimension of `x`. E.g., if `front = + back = True` then `2 * count` elements are added. + name: Python `str` name prefixed to Ops created by this function. + + Returns: + pad: The padded version of input `x`. + + Raises: + ValueError: if both `front` and `back` are `False`. + TypeError: if `count` is not `int`-like. + """ + with ops.name_scope(name, "pad", [x, value, count]): + x = ops.convert_to_tensor(x, name="x") + value = ops.convert_to_tensor(value, dtype=x.dtype, name="value") + count = ops.convert_to_tensor(count, name="count") + if not count.dtype.is_integer: + raise TypeError("`count.dtype` (`{}`) must be `int`-like.".format( + count.dtype.name)) + if not front and not back: + raise ValueError("At least one of `front`, `back` must be `True`.") + ndims = ( + x.shape.ndims if x.shape.ndims is not None else array_ops.rank( + x, name="ndims")) + axis = ops.convert_to_tensor(axis, name="axis") + axis_ = tensor_util.constant_value(axis) + if axis_ is not None: + axis = axis_ + if axis < 0: + axis = ndims + axis + count_ = tensor_util.constant_value(count) + if axis_ >= 0 or x.shape.ndims is not None: + head = x.shape[:axis] + middle = tensor_shape.TensorShape(None if count_ is None else ( + tensor_shape.dimension_at_index(x.shape, axis) + count_ * + (front + back))) + tail = x.shape[axis + 1:] + final_shape = head.concatenate(middle.concatenate(tail)) + else: + final_shape = None + else: + axis = array_ops.where_v2(axis < 0, ndims + axis, axis) + final_shape = None + x = array_ops.pad( + x, + paddings=array_ops.one_hot( + indices=array_ops_stack.stack( + [axis if front else -1, axis if back else -1]), + depth=ndims, + axis=0, + on_value=count, + dtype=dtypes.int32), + constant_values=value) + if final_shape is not None: + x.set_shape(final_shape) + return x + + +def parent_frame_arguments(): + """Returns parent frame arguments. + + When called inside a function, returns a dictionary with the caller's function + arguments. These are positional arguments and keyword arguments (**kwargs), + while variable arguments (*varargs) are excluded. + + When called at global scope, this will return an empty dictionary, since there + are no arguments. + + WARNING: If caller function argument names are overloaded before invoking + this method, then values will reflect the overloaded value. For this reason, + we recommend calling `parent_frame_arguments` at the beginning of the + function. + """ + # All arguments and the names used for *varargs, and **kwargs + arg_names, variable_arg_name, keyword_arg_name, local_vars = ( + tf_inspect._inspect.getargvalues( # pylint: disable=protected-access + # Get the first frame of the caller of this method. + tf_inspect._inspect.stack()[1][0])) # pylint: disable=protected-access + + # Remove the *varargs, and flatten the **kwargs. Both are + # nested lists. + local_vars.pop(variable_arg_name, {}) + keyword_args = local_vars.pop(keyword_arg_name, {}) + + final_args = {} + # Copy over arguments and their values. In general, local_vars + # may contain more than just the arguments, since this method + # can be called anywhere in a function. + for arg_name in arg_names: + final_args[arg_name] = local_vars.pop(arg_name) + final_args.update(keyword_args) + + return final_args + + +class AppendDocstring: + """Helper class to promote private subclass docstring to public counterpart. + + Example: + + ```python + class TransformedDistribution(Distribution): + @distribution_util.AppendDocstring( + additional_note="A special note!", + kwargs_dict={"foo": "An extra arg."}) + def _prob(self, y, foo=None): + pass + ``` + + In this case, the `AppendDocstring` decorator appends the `additional_note` to + the docstring of `prob` (not `_prob`) and adds a new `kwargs` + section with each dictionary item as a bullet-point. + + For a more detailed example, see `TransformedDistribution`. + """ + + def __init__(self, additional_note="", kwargs_dict=None): + """Initializes the AppendDocstring object. + + Args: + additional_note: Python string added as additional docstring to public + version of function. + kwargs_dict: Python string/string dictionary representing specific kwargs + expanded from the **kwargs input. + + Raises: + ValueError: if kwargs_dict.key contains whitespace. + ValueError: if kwargs_dict.value contains newlines. + """ + self._additional_note = additional_note + if kwargs_dict: + bullets = [] + for key in sorted(kwargs_dict.keys()): + value = kwargs_dict[key] + if any(x.isspace() for x in key): + raise ValueError("Parameter name \"%s\" contains whitespace." % key) + value = value.lstrip() + if "\n" in value: + raise ValueError( + "Parameter description for \"%s\" contains newlines." % key) + bullets.append("* `%s`: %s" % (key, value)) + self._additional_note += ("\n\n##### `kwargs`:\n\n" + "\n".join(bullets)) + + def __call__(self, fn): + + @functools.wraps(fn) + def _fn(*args, **kwargs): + return fn(*args, **kwargs) + + if _fn.__doc__ is None: + _fn.__doc__ = self._additional_note + else: + _fn.__doc__ += "\n%s" % self._additional_note + return _fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/embedding_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/embedding_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2e03549967204167a5d732d4c27c87b5ec923c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/embedding_ops.py @@ -0,0 +1,1182 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for embeddings.""" + +from tensorflow.python.compat import compat +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import clip_ops +# Imports gradient definitions. +from tensorflow.python.ops import data_flow_grad # pylint: disable=unused-import +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variables +from tensorflow.python.types import core +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def _clip(params, ids, max_norm): + """Helper function for _embedding_lookup_and_transform. + + This function optionally clips embeddings to an l2-norm of max_norm. + + Args: + params: A `Tensor` of embeddings retrieved by `gather`. + ids: The `ids` argument that was passed to `gather`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value. + + Returns: + A `Tensor` with the same type as `params`. + """ + + def _rank(x): + """Helper function to retrieve the rank of a tensor. + + Args: + x: Something convertible to `Tensor`. + + Returns: + Either a pair `(rank, True)` where `rank` is an integer or a pair + `(rank, False)` where `rank` is an integer `Tensor`. In either case, + `rank` is the rank of `x`. + """ + rank = ops.convert_to_tensor(x).get_shape().ndims + if rank: + return rank, True + else: + return array_ops.rank(x), False + + if max_norm is None: + return params + ids_rank, ids_static = _rank(ids) + params_rank, params_static = _rank(params) + return clip_ops.clip_by_norm( + params, + max_norm, + axes=(list(range(ids_rank, params_rank)) if ids_static and params_static + else math_ops.range(ids_rank, params_rank))) + + +def _colocate_with(param): + if ops.inside_function() and hasattr(param, "handle"): + # The `ops.colocate_with` will hard-code a device string if `param.device` + # is known, which will then break serving. We capture it here so that it + # produces a tensor without a device. + return ops.colocate_with(ops.get_default_graph().capture(param.handle)) + else: + return ops.colocate_with(param) + + +def _embedding_lookup_and_transform(params, + ids, + partition_strategy="mod", + name=None, + max_norm=None, + transform_fn=None): + """Helper function for embedding_lookup and _compute_sampled_logits. + + This function is a generalization of embedding_lookup that optionally + applies a caller-specified transformation to each embedding. This is + done through the `transform_fn` argument. If provided, the function is + applied to each partitioned tensor of retrieved embeddings, colocated + with the embeddings. This function will be called with a single `Tensor` + argument of the same type as the `params` tensor and should return a + `Tensor`. The shape of the argument will be the same as `params` except + for the size of the first dimension. The first dimension of the result's + shape must be the same size as the argument's. + + Args: + params: See embedding_lookup. + ids: See embedding_lookup. + partition_strategy: See embedding_lookup. + name: See embedding_lookup. + max_norm: See embedding_lookup. + transform_fn: An optional function to apply to each retrieved embedding. If + max_norm is provided, transform_fn is applied to the norm-limited + embeddings. + + Returns: + See embedding_lookup for details. + Raises: + ValueError: If `params` is empty. + """ + if params is None: + raise ValueError("params must be specified") + if isinstance(params, (list, tuple)) and not params: + raise ValueError("Length of params is currently 0. " + "Need at least one param.") + if isinstance(params, variables.PartitionedVariable): + params = list(params) # Iterate to get the underlying Variables. + if not isinstance(params, list): + params = [params] + + with ops.name_scope(name, "embedding_lookup", params + [ids]) as name: + np = len(params) # Number of partitions + # Preserve the resource variable status to avoid accidental dense reads. + if not any( + isinstance(p, resource_variable_ops.BaseResourceVariable) + for p in params): + params = indexed_slices.convert_n_to_tensor_or_indexed_slices( + params, name="params") + ids = ops.convert_to_tensor(ids, name="ids") + if np == 1 and (not transform_fn or ids.get_shape().ndims == 1): + with _colocate_with(params[0]): + result = _clip( + array_ops.gather(params[0], ids, name=name), ids, max_norm) + if transform_fn: + result = transform_fn(result) + # Make sure the final result does not have colocation constraints on the + # params. Similar to the case np > 1 where parallel_dynamic_stitch is + # outside the scope of all with _colocate_with(params[p]). + return array_ops.identity(result) + else: + # Flatten the ids. There are two cases where we need to do this. + # - There is more than one params tensor. + # - There is a transform_fn and ids is not statically known to be 1-D. + # We must flatten in this case because transform_fn expects a flat + # tensor of embeddings. + flat_ids = array_ops.reshape(ids, [-1]) + original_indices = math_ops.range(array_ops.size(flat_ids)) + + # Create p_assignments and set new_ids depending on the strategy. + if partition_strategy == "mod": + p_assignments = flat_ids % np + new_ids = flat_ids // np + elif partition_strategy == "div": + # Compute num_total_ids as the sum of dim-0 of params, then assign to + # partitions based on a constant number of ids per partition. Optimize + # if we already know the full shape statically. + dim_0_size = tensor_shape.Dimension( + tensor_shape.dimension_value(params[0].get_shape()[0])) + for p in range(1, np): + dim_0_size += tensor_shape.Dimension( + tensor_shape.dimension_value(params[p].get_shape()[0])) + if dim_0_size.value: + num_total_ids = constant_op.constant(dim_0_size.value, flat_ids.dtype) + else: + dim_0_sizes = [] + for p in range(np): + param_p_dim = tensor_shape.dimension_value(params[p].get_shape()[0]) + if param_p_dim is not None: + dim_0_sizes.append(param_p_dim) + else: + with _colocate_with(params[p]): + dim_0_sizes.append(array_ops.shape(params[p])[0]) + num_total_ids = math_ops.reduce_sum( + math_ops.cast(array_ops_stack.stack(dim_0_sizes), flat_ids.dtype)) + ids_per_partition = num_total_ids // np + extras = num_total_ids % np + + p_assignments = math_ops.maximum(flat_ids // (ids_per_partition + 1), + (flat_ids - extras) // + ids_per_partition) + + # Emulate a conditional using a boolean indicator tensor + new_ids = array_ops.where(p_assignments < extras, + flat_ids % (ids_per_partition + 1), + (flat_ids - extras) % ids_per_partition) + else: + raise ValueError( + f"Unrecognized partition strategy: {partition_strategy}." + "Must be one of either `mod` or `div`.") + + # Cast partition assignments to int32 for use in dynamic_partition. + # There really should not be more than 2^32 partitions. + p_assignments = math_ops.cast(p_assignments, dtypes.int32) + # Partition list of ids based on assignments into np separate lists + gather_ids = data_flow_ops.dynamic_partition(new_ids, p_assignments, np) + # Similarly, partition the original indices. + pindices = data_flow_ops.dynamic_partition(original_indices, + p_assignments, np) + # Do np separate lookups, finding embeddings for plist[p] in params[p] + partitioned_result = [] + for p in range(np): + pids = gather_ids[p] + with ops.device_v2(None): + with _colocate_with(params[p]): + result = array_ops.gather(params[p], pids) + if transform_fn: + # If transform_fn is provided, the clip_by_norm precedes + # the transform and hence must be co-located. See below + # for the counterpart if transform_fn is not provided. + result = transform_fn(_clip(result, pids, max_norm)) + partitioned_result.append(result) + # Stitch these back together + ret = data_flow_ops.parallel_dynamic_stitch( + pindices, partitioned_result, name=name) + + # Determine the static element shape. + if transform_fn is None: + element_shape_s = params[0].get_shape()[1:] + for p in params[1:]: + element_shape_s = element_shape_s.merge_with(p.get_shape()[1:]) + else: + element_shape_s = ret.get_shape()[1:] + + # Compute the dynamic element shape. + if element_shape_s.is_fully_defined(): + element_shape_d = element_shape_s + elif transform_fn is None: + # It's important that we compute params[0].shape on the right device + # to avoid data motion. + with _colocate_with(params[0]): + params_shape = array_ops.shape(params[0]) + element_shape_d = params_shape[1:] + else: + element_shape_d = array_ops.shape(ret)[1:] + + # Reshape to reverse the flattening of ids. + ret = array_ops.reshape( + ret, array_ops.concat([array_ops.shape(ids), element_shape_d], 0)) + + # Normally the reshape is sufficient, but setting shape explicitly + # teaches shape inference that params[1:].get_shape() matters + # (in the case that transform_fn is None). + ret.set_shape(ids.get_shape().concatenate(element_shape_s)) + if not transform_fn: + # If transform_fn was provided, the clip_by_norm was done above. + ret = _clip(ret, ids, max_norm) + return ret + + +@tf_export(v1=["nn.embedding_lookup"]) +@dispatch.add_dispatch_support +def embedding_lookup( + params, + ids, + partition_strategy="mod", + name=None, + validate_indices=True, # pylint: disable=unused-argument + max_norm=None): + """Looks up embeddings for the given `ids` from a list of tensors. + + This function is used to perform parallel lookups on the list of tensors in + `params`. It is a generalization of `tf.gather`, where `params` is + interpreted as a partitioning of a large embedding tensor. `params` may be + a `PartitionedVariable` as returned by using `tf.compat.v1.get_variable()` + with a partitioner. + + If `len(params) > 1`, each element `id` of `ids` is partitioned between + the elements of `params` according to the `partition_strategy`. + In all strategies, if the id space does not evenly divide the number of + partitions, each of the first `(max_id + 1) % len(params)` partitions will + be assigned one more id. + + If `partition_strategy` is `"mod"`, we assign each id to partition + `p = id % len(params)`. For instance, + 13 ids are split across 5 partitions as: + `[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8], [4, 9]]` + + If `partition_strategy` is `"div"`, we assign ids to partitions in a + contiguous manner. In this case, 13 ids are split across 5 partitions as: + `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]` + + If the input ids are ragged tensors, partition variables are not supported and + the partition strategy and the max_norm are ignored. + The results of the lookup are concatenated into a dense + tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`. + + Args: + params: A single tensor representing the complete embedding tensor, or a + list of P tensors all of same shape except for the first dimension, + representing sharded embedding tensors. Alternatively, a + `PartitionedVariable`, created by partitioning along dimension 0. Each + element must be appropriately sized for the given `partition_strategy`. + ids: A `Tensor` or a 'RaggedTensor' with type `int32` or `int64` containing + the ids to be looked up in `params`. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default + is `"mod"`. + name: A name for the operation (optional). + validate_indices: DEPRECATED. If this operation is assigned to CPU, values + in `indices` are always validated to be within range. If assigned to GPU, + out-of-bound indices result in safe but unspecified behavior, which may + include raising an error. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value. + + Returns: + A `Tensor` or a 'RaggedTensor', depending on the input, with the same type + as the tensors in `params`. + + Raises: + ValueError: If `params` is empty. + """ + + """ + **Behavior Difference between CPU and GPU** + + Please note that when using `tf.nn.embedding_lookup` on a GPU, if an out-of-bound + index is encountered, a value of 0 will be stored in the corresponding output value. + On the other hand, when using `tf.nn.embedding_lookup` on a CPU, an error will be + returned if an out-of-bound index is found. + + This behavior difference can impact the results of your computation, especially when + dealing with indices that may go beyond the bounds of the tensor. + Make sure to be mindful of this distinction when using the `tf.nn.embedding_lookup` + function in your computations. + + **Usage Example** + + Here's an example demonstrating how to use `tf.nn.embedding_lookup`: + + ```python + import tensorflow as tf + + # Example embedding matrix and indices + embedding_matrix = tf.constant([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) + indices = tf.constant([1, 0, 2]) + + # Perform embedding lookup + embeddings = tf.nn.embedding_lookup(embedding_matrix, indices) + + # Print the result + print("Embeddings:") + print(embeddings.numpy()) + ``` + """ + + return _embedding_lookup_and_transform( + params=params, + ids=ids, + partition_strategy=partition_strategy, + name=name, + max_norm=max_norm, + transform_fn=None) + + +@tf_export("nn.embedding_lookup", v1=[]) +@dispatch.add_dispatch_support +def embedding_lookup_v2(params, ids, max_norm=None, name=None): + """Looks up embeddings for the given `ids` from a list of tensors. + + This function is used to perform parallel lookups on the list of tensors in + `params`. It is a generalization of `tf.gather`, where `params` is + interpreted as a partitioning of a large embedding tensor. + + If `len(params) > 1`, each element `id` of `ids` is partitioned between the + elements of `params` according to the "div" partition strategy, which means we + assign ids to partitions in a contiguous manner. For instance, 13 ids are + split across 5 partitions as: + `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`. + + If the id space does not evenly divide the number of partitions, each of the + first `(max_id + 1) % len(params)` partitions will be assigned one more id. + + The results of the lookup are concatenated into a dense + tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`. + + Args: + params: A single tensor representing the complete embedding tensor, or a + list of tensors all of same shape except for the first dimension, + representing sharded embedding tensors following "div" partition strategy. + ids: A `Tensor` with type `int32` or `int64` containing the ids to be looked + up in `params`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as the tensors in `params`. + + For instance, if `params` is a 5x2 matrix: + + ```python + [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + ``` + + or a list of matrices: + + ```python + params[0]: [[1, 2], [3, 4]] + params[1]: [[5, 6], [7, 8]] + params[2]: [[9, 10]] + ``` + + and `ids` is: + + ```python + [0, 3, 4] + ``` + + The output will be a 3x2 matrix: + + ```python + [[1, 2], [7, 8], [9, 10]] + ``` + + Raises: + ValueError: If `params` is empty. + """ + return embedding_lookup(params, ids, "div", name, max_norm=max_norm) + + +@tf_export(v1=["nn.embedding_lookup_sparse"]) +@dispatch.add_dispatch_support +def embedding_lookup_sparse( + params, + sp_ids, + sp_weights, + partition_strategy="mod", + name=None, + combiner=None, + max_norm=None, + allow_fast_lookup=False, +): + """Looks up embeddings for the given ids and weights from a list of tensors. + + This op assumes that there is at least one id for each row in the dense tensor + represented by sp_ids (i.e. there are no rows with empty features), and that + all the indices of sp_ids are in canonical row-major order. + + `sp_ids` and `sp_weights` (if not None) are `SparseTensor`s or `RaggedTensor`s + with rank of 2. For `SpareTensor`s with left-aligned non-zero entries which + can be described as `RaggedTensor`s, use of `RaggedTensor`s can yield higher + performance. + + It also assumes that all id values lie in the range [0, p0), where p0 + is the sum of the size of params along dimension 0. + + Args: + params: A single tensor representing the complete embedding tensor, or a + list tensors all of same shape except for the first dimension, + representing sharded embedding tensors. Alternatively, a + `PartitionedVariable`, created by partitioning along dimension 0. Each + element must be appropriately sized for the given `partition_strategy`. + sp_ids: N x M `SparseTensor` of int64 ids where N is typically batch size + and M is arbitrary or a `RaggedTensor` with rank 2. + sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as + `sparse_ids`, containing float / double weights corresponding to + `sparse_ids`, or `None` if all weights are assumed to be 1.0. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default + is `"mod"`. See `tf.nn.embedding_lookup` for more details. + name: Optional name for the op. + combiner: A string specifying the reduction op. Currently "mean", "sqrtn" + and "sum" are supported. "sum" computes the weighted sum of the embedding + results for each row. "mean" is the weighted sum divided by the total + weight. "sqrtn" is the weighted sum divided by the square root of the sum + of the squares of the weights. Defaults to `mean`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value, before combining. + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sp_ids`, the op + looks up the embeddings for all ids in that row, multiplies them by the + corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined params) = [p0, p1, ..., pm]` + + and + + `shape(sp_ids) = shape(sp_weights) = [d0, d1]` + + then + + `shape(output) = [d0, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id 0, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + TypeError: If `sp_ids` is not a `SparseTensor` or `RaggedTensor`, or if + `sp_weights` is neither `None` nor of the same type as `sp_ids`. + ValueError: If `combiner` is not one of {"mean", "sqrtn", "sum"}. + """ + if combiner is None: + combiner = "mean" + if combiner not in ("mean", "sqrtn", "sum"): + raise ValueError( + f"combiner must be one of 'mean', 'sqrtn' or 'sum', got {combiner}") + if isinstance(params, variables.PartitionedVariable): + params = list(params) # Iterate to get the underlying Variables. + if not isinstance(params, list): + params = [params] + if not isinstance(sp_ids, sparse_tensor.SparseTensor): + raise TypeError(f"sp_ids must be SparseTensor, got {type(sp_ids)}") + ignore_weights = sp_weights is None + if not ignore_weights: + if not isinstance(sp_weights, sparse_tensor.SparseTensor): + raise TypeError(f"sp_weights must be either None or SparseTensor," + f"got {type(sp_weights)}") + sp_ids.values.get_shape().assert_is_compatible_with( + sp_weights.values.get_shape()) + sp_ids.indices.get_shape().assert_is_compatible_with( + sp_weights.indices.get_shape()) + sp_ids.dense_shape.get_shape().assert_is_compatible_with( + sp_weights.dense_shape.get_shape()) + # TODO(yleon): Add enhanced node assertions to verify that sp_ids and + # sp_weights have equal indices and shapes. + + with ops.name_scope(name, "embedding_lookup_sparse", + params + [sp_ids]) as name: + + segment_ids = sp_ids.indices[:, 0] + ids = sp_ids.values + + return embedding_lookup_sparse_impl( + params, + segment_ids, + sp_weights, + ids, + combiner, + ignore_weights, + max_norm, + allow_fast_lookup, + partition_strategy, + name, + ) + + +@tf_export("nn.embedding_lookup_sparse", v1=[]) +@dispatch.add_dispatch_support +def embedding_lookup_sparse_v2( + params, + sp_ids, + sp_weights, + combiner=None, + max_norm=None, + name=None, + allow_fast_lookup=False, +): + """Looks up embeddings for the given ids and weights from a list of tensors. + + `params` is a dense tensor or a list of dense tensors, and `sp_ids` is a 2D + `tf.SparseTensor` or `tf.RaggedTensor` indicating the indices of `params` to + gather. + + This op is best described with an example. Suppose `params` is an embedding + table of size `(4, 2)` and `sp_ids` has 3 rows. Since `sp_ids` is sparse or + ragged, not every row has the same number of elements. The output has shape + (3, 2). Each row of `sp_ids` is a list of indices, where each index selects a + row of `params`. For a given row of `sp_ids`, the rows of `params` are + gathered based on the indices in `sp_ids`, then combined by taking their sum + or mean. + + >>> params = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.float32) + >>> sp_ids = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]], + ... values=[0, 1, 3, 2], dense_shape=(3, 2)) + >>> tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights=None, + ... combiner='sum').numpy() + array([[4., 6.], [7., 8.], [5., 6.]], dtype=float32) + + In this example, `sp_ids` has 3 rows, so the output has 3 rows. Row 0 of + `sp_ids` has values 0 and 1, so it selects rows 0 and 1 from `params`, which + are `[1, 2]` and `[3, 4]`. The rows are summed since `combiner='sum'`, + resulting in the output row of `[4, 6]`. + + Since row 1 and 2 of `sp_ids` only have one value each, they simply select the + corresponding row from `params` as the output row. Row 1 has value `3` so + it selects the `params` elements `[7, 8]` and row 2 has the value 2 so it + selects the `params` elements `[5, 6]`. + + If `sparse_weights` is specified, it must have the same shape as `sp_ids`. + `sparse_weights` is used to assign a weight to each slice of `params`. For + example: + + >>> params = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.float32) + >>> sp_ids = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]], + ... values=[0, 1, 3, 2], dense_shape=(3, 2)) + >>> sparse_weights = tf.SparseTensor(indices=[[0, 0], [0, 1], [1, 0], [2, 0]], + ... values=[0.1, 1.0, 0.5, 2.0], + ... dense_shape=(3, 2)) + >>> tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights=sparse_weights, + ... combiner='sum').numpy() + array([[3.1, 4.2], [3.5, 4.], [10., 12.]], dtype=float32) + + In general, `params` can have shape `(p0, ..., pn)` and `sp_ids` can have `M` + rows, where each row can have any number of elements. The output has shape + `(M, p1, ..., pn)`. Each slice of the output `output[i, ...]` is obtained as + follows: The `combiner` argument is used to combine the values + `params[sp_ids[i, j], ...] * sparse_weights[i, j]` for each `j` in `range(0, + len(sp_ids[i]))`, e.g. by taking the sum or mean of the values. + + This op assumes that there is at least one id for each row in the dense tensor + represented by sp_ids (i.e. there are no rows with empty features), and that + all the indices of sp_ids are in canonical row-major order. + + `sp_ids` and `sp_weights` (if not None) are `SparseTensor`s or `RaggedTensor`s + with rank of 2. For `SpareTensor`s with left-aligned non-zero entries which + can be described as `RaggedTensor`s, use of `RaggedTensor`s can yield higher + performance. + + This op assumes that all id values lie in the range [0, p0), where p0 + is `params.shape[0]`. If you want a version of this op that prunes id values + less than 0, see `tf.nn.safe_embedding_lookup_sparse` + + If `len(params) > 1`, each element of `sp_ids` is partitioned between the + elements of `params` according to the "div" partition strategy, which means we + assign ids to partitions in a contiguous manner. For instance, 13 ids are + split across 5 partitions as: + `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`. + + If the id space does not evenly divide the number of partitions, each of the + first `(max_id + 1) % len(params)` partitions will be assigned one more id. + + Args: + params: A single tensor representing the complete embedding tensor, or a + list of tensors all of same shape except for the first dimension, + representing sharded embedding tensors following "div" partition strategy. + sp_ids: N x M `SparseTensor` of int64 ids where N is typically batch size + and M is arbitrary or a `RaggedTensor` with rank 2. + sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as + `sparse_ids`, containing float / double weights corresponding to + `sparse_ids`, or `None` if all weights are assumed to be 1.0. + combiner: A string specifying the reduction op. Currently "mean", "sqrtn" + and "sum" are supported. "sum" computes the weighted sum of the embedding + results for each row. "mean" is the weighted sum divided by the total + weight. "sqrtn" is the weighted sum divided by the square root of the sum + of the squares of the weights. Defaults to `mean`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value, before combining. + name: Optional name for the op. + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sp_ids`, the op + looks up the embeddings for all ids in that row, multiplies them by the + corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined params) = [p0, p1, ..., pm]` + + and + + `shape(sp_ids) = shape(sp_weights) = [d0, d1]` + + then + + `shape(output) = [d0, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id 0, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + TypeError: If `sp_ids` is not a `SparseTensor`, or if `sp_weights` is + neither `None` nor `SparseTensor`. + ValueError: If `combiner` is not one of {"mean", "sqrtn", "sum"}. + """ + return embedding_lookup_sparse( + params, + sp_ids, + sp_weights, + "div", + name, + combiner, + max_norm, + allow_fast_lookup, + ) + + +@tf_export("nn.safe_embedding_lookup_sparse", v1=[]) +@dispatch.add_dispatch_support +def safe_embedding_lookup_sparse_v2( + embedding_weights, + sparse_ids, + sparse_weights=None, + combiner="mean", + default_id=None, + max_norm=None, + name=None, + allow_fast_lookup=False, +): + """Lookup embedding results, accounting for invalid IDs and empty features. + + The partitioned embedding in `embedding_weights` must all be the same shape + except for the first dimension. The first dimension is allowed to vary as the + vocabulary size is not necessarily a multiple of num of shards. + + This is similar to `tf.nn.embedding_lookup_sparse`, except invalid IDs (< 0) + are pruned from input IDs and weights, as well as any IDs with non-positive + weight. For an entry with no features, the embedding vector for `default_id` + is returned, or the 0-vector if `default_id` is not supplied. See + `tf.nn.embedding_lookup_sparse` for more information on how sparse embedding + lookups work in general. + + The ids and weights may be multi-dimensional `SparseTensor`s or + `RaggedTensor`s with rank of 2. For `SpareTensor`s with left-aligned non-zero + entries which can be described as `RaggedTensor`s, use of `RaggedTensor`s can + yield higher performance. + + If `len(embedding_weights) > 1`, each element `id` of `ids` is partitioned + between the elements of `embedding_weights` according to the "div" partition + strategy, which means we assign ids to partitions in a contiguous manner. For + instance, 13 ids are split across 5 partitions as: + `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`. + + If the id space does not evenly divide the number of partitions, each of the + first `(max_id + 1) % len(embedding_weights)` partitions will be assigned one + more id. + + Args: + embedding_weights: A single tensor representing the complete embedding + tensor, or a list of tensors all of same shape except for the first + dimension, representing sharded embedding tensors following "div" + partition strategy. + sparse_ids: `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the + ids, where `d_0` is typically batch size, or a `RaggedTensor` with rank 2. + sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as + `sparse_ids`, containing float weights corresponding to `sparse_ids`, or + `None` if all weights are assumed to be 1.0. + combiner: A string specifying how to combine embedding results for each + entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the + default. + default_id: The id to use for an entry with no features. Defaults to + 0-vector. + max_norm: If not `None`, all embeddings are l2-normalized to max_norm before + combining. + name: A name for this operation (optional). + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sparse_ids`, + the op looks up the embeddings for all ids in that row, multiplies them by + the corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined embedding_weights) = [p0, p1, ..., pm]` + + and + + `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]` + + then + + `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id -1, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + `default_id` is 0. + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + ValueError: if `embedding_weights` is empty. + """ + return safe_embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights=sparse_weights, + combiner=combiner, + default_id=default_id, + name=name, + partition_strategy="div", + max_norm=max_norm, + allow_fast_lookup=allow_fast_lookup, + ) + + +@tf_export(v1=["nn.safe_embedding_lookup_sparse"]) +@dispatch.add_dispatch_support +def safe_embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights=None, + combiner="mean", + default_id=None, + name=None, + partition_strategy="div", + max_norm=None, + allow_fast_lookup=False, +): + """Lookup embedding results, accounting for invalid IDs and empty features. + + The partitioned embedding in `embedding_weights` must all be the same shape + except for the first dimension. The first dimension is allowed to vary as the + vocabulary size is not necessarily a multiple of `P`. `embedding_weights` + may be a `PartitionedVariable` as returned by using + `tf.compat.v1.get_variable()` with a + partitioner. + + Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs + with non-positive weight. For an entry with no features, the embedding vector + for `default_id` is returned, or the 0-vector if `default_id` is not supplied. + + The ids and weights may be multi-dimensional `SparseTensor`s or + `RaggedTensor`s with rank of 2. For `SpareTensor`s with left-aligned non-zero + entries which can be described as `RaggedTensor`s, use of `RaggedTensor`s can + yield higher performance. Embeddings are always aggregated along the last + dimension. + + Args: + embedding_weights: A single tensor representing the complete embedding + tensor, or a list tensors all of same shape except for the first + dimension, representing sharded embedding tensors. Alternatively, a + `PartitionedVariable`, created by partitioning along dimension 0. Each + element must be appropriately sized for the given `partition_strategy`. + sparse_ids: `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the + ids, where `d_0` is typically batch size, or a `RaggedTensor` with rank 2. + sparse_weights: `SparseTensor` or `RaggedTensor` of same type and shape as + `sparse_ids`, containing float weights corresponding to `sparse_ids`, or + `None` if all weights are assumed to be 1.0. + combiner: A string specifying how to combine embedding results for each + entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the + default. + default_id: The id to use for an entry with no features. + name: A name for this operation (optional). + partition_strategy: A string specifying the partitioning strategy. Currently + `"div"` and `"mod"` are supported. Default is `"div"`. + max_norm: If not `None`, all embeddings are l2-normalized to max_norm before + combining. + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sp_ids`, the op + looks up the embeddings for all ids in that row, multiplies them by the + corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined embedding_weights) = [p0, p1, ..., pm]` + + and + + `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]` + + then + + `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id -1, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + `default_id` is 0. + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + ValueError: if `embedding_weights` is empty. + """ + if embedding_weights is None: + raise ValueError(f"Missing embedding_weights {embedding_weights}.") + if isinstance(embedding_weights, variables.PartitionedVariable): + embedding_weights = list(embedding_weights) # get underlying Variables. + if not isinstance(embedding_weights, list): + embedding_weights = [embedding_weights] + if len(embedding_weights) < 1: + raise ValueError(f"Missing embedding_weights {embedding_weights}.") + + dtype = sparse_weights.dtype if sparse_weights is not None else None + embedding_weights = [ + w if (resource_variable_ops.is_resource_variable(w) + and dtype in (None, w.dtype)) + else ops.convert_to_tensor(w, dtype=dtype) + for w in embedding_weights + ] + + with ops.name_scope(name, "embedding_lookup", embedding_weights + + [sparse_ids, sparse_weights]) as scope: + # Reshape higher-rank sparse ids and weights to linear segment ids. + original_shape = sparse_ids.dense_shape + original_rank_dim = tensor_shape.dimension_value( + sparse_ids.dense_shape.get_shape()[0]) + original_rank = ( + array_ops.size(original_shape) + if original_rank_dim is None else original_rank_dim) + sparse_ids = sparse_ops.sparse_reshape(sparse_ids, [ + math_ops.reduce_prod( + array_ops.slice(original_shape, [0], [original_rank - 1])), + array_ops.gather(original_shape, original_rank - 1) + ]) + if sparse_weights is not None: + sparse_weights = sparse_tensor.SparseTensor(sparse_ids.indices, + sparse_weights.values, + sparse_ids.dense_shape) + + # Prune invalid ids and weights. + sparse_ids, sparse_weights = _prune_invalid_ids(sparse_ids, sparse_weights) + if combiner != "sum": + sparse_ids, sparse_weights = _prune_invalid_weights( + sparse_ids, sparse_weights) + + # Fill in dummy values for empty features, if necessary. + sparse_ids, is_row_empty = sparse_ops.sparse_fill_empty_rows( + sparse_ids, default_id or 0) + if sparse_weights is not None: + sparse_weights, _ = sparse_ops.sparse_fill_empty_rows(sparse_weights, 1.0) + + result = embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights, + combiner=combiner, + partition_strategy=partition_strategy, + name=None if default_id is None else scope, + max_norm=max_norm, + allow_fast_lookup=allow_fast_lookup, + ) + + if default_id is None: + # Broadcast is_row_empty to the same shape as embedding_lookup_result, + # for use in Select. + is_row_empty = array_ops.tile( + array_ops.reshape(is_row_empty, [-1, 1]), + array_ops_stack.stack([1, array_ops.shape(result)[1]])) + + result = array_ops.where( + is_row_empty, array_ops.zeros_like(result), result, name=scope) + + # Reshape back from linear ids back into higher-dimensional dense result. + final_result = array_ops.reshape( + result, + array_ops.concat([ + array_ops.slice( + math_ops.cast(original_shape, dtypes.int32), [0], + [original_rank - 1]), + array_ops.slice(array_ops.shape(result), [1], [-1]) + ], 0)) + final_result.set_shape( + tensor_shape.unknown_shape( + (tensor_shape.Dimension(original_rank_dim) - 1).value + ).concatenate(result.get_shape()[1:]) + ) + return final_result + + +def embedding_lookup_sparse_impl( + params, + segment_ids, + sp_weights, + ids, + combiner, + ignore_weights, + max_norm, + allow_fast_lookup, + partition_strategy, + name, +): + """Implementation of sparse embedding aggregation.""" + need_sparse_segment_gradient = False + # Ensure we can query the devices below. + segment_ids = ops.convert_to_tensor(segment_ids, name="segment_ids") + if len(params) == 1 and not isinstance( + params[0], (core.Tensor, composite_tensor.CompositeTensor) + ): + params = [ops.convert_to_tensor(params[0], name="params")] + # Note that if the params are on a different device (e.g., CPU), we must use + # embedding_lookup() so that the gather operation is colocated with them. + if ( + len(params) == 1 + and not isinstance(params[0], composite_tensor.CompositeTensor) + and params[0].device == segment_ids.device + and max_norm is None + and ( + allow_fast_lookup + or (ignore_weights and compat.forward_compatible(2023, 9, 26)) + ) + ): + idx = ids + embeddings = params[0] + if isinstance(embeddings, resource_variable_ops.BaseResourceVariable): + # Avoid a redundant copy due to copy-on-read semantics for + # sparsely-updated variables. + embeddings = embeddings.read_value_no_copy() + if not allow_fast_lookup: + need_sparse_segment_gradient = True + else: + ids, idx = array_ops.unique(ids) + embeddings = embedding_lookup( + params, ids, partition_strategy=partition_strategy, max_norm=max_norm + ) + + if not ignore_weights: + if segment_ids.dtype != dtypes.int32: + segment_ids = math_ops.cast(segment_ids, dtypes.int32) + + weights = sp_weights.values + embeddings = array_ops.gather(embeddings, idx) + + original_dtype = embeddings.dtype + if embeddings.dtype in (dtypes.float16, dtypes.bfloat16): + # Cast low-precision embeddings to float32 during the computation to + # avoid numerical issues. + embeddings = math_ops.cast(embeddings, dtypes.float32) + if weights.dtype != embeddings.dtype: + weights = math_ops.cast(weights, embeddings.dtype) + + # Reshape weights to allow broadcast + ones_shape = array_ops.expand_dims(array_ops.rank(embeddings) - 1, 0) + ones = array_ops.ones(ones_shape, dtype=dtypes.int32) + bcast_weights_shape = array_ops.concat([array_ops.shape(weights), ones], 0) + + orig_weights_shape = weights.get_shape() + weights = array_ops.reshape(weights, bcast_weights_shape) + + # Set the weight shape, since after reshaping to bcast_weights_shape, + # the shape becomes None. + if embeddings.get_shape().ndims is not None: + weights.set_shape( + orig_weights_shape.concatenate( + [1 for _ in range(embeddings.get_shape().ndims - 1)] + ) + ) + + embeddings *= weights + + if combiner == "sum": + embeddings = math_ops.segment_sum(embeddings, segment_ids, name=name) + elif combiner == "mean": + embeddings = math_ops.segment_sum(embeddings, segment_ids) + weight_sum = math_ops.segment_sum(weights, segment_ids) + embeddings = math_ops.div_no_nan(embeddings, weight_sum, name=name) + elif combiner == "sqrtn": + embeddings = math_ops.segment_sum(embeddings, segment_ids) + weights_squared = math_ops.pow(weights, 2) + weight_sum = math_ops.segment_sum(weights_squared, segment_ids) + weight_sum_sqrt = math_ops.sqrt(weight_sum) + embeddings = math_ops.div_no_nan(embeddings, weight_sum_sqrt, name=name) + else: + assert False, "Unrecognized combiner" + if embeddings.dtype != original_dtype: + embeddings = math_ops.cast(embeddings, original_dtype) + else: + if segment_ids.dtype not in (dtypes.int32, dtypes.int64): + segment_ids = math_ops.cast(segment_ids, dtypes.int32) + assert idx is not None + if combiner == "sum": + embeddings = math_ops.sparse_segment_sum( + embeddings, + idx, + segment_ids, + name=name, + sparse_gradient=need_sparse_segment_gradient, + ) + elif combiner == "mean": + embeddings = math_ops.sparse_segment_mean( + embeddings, + idx, + segment_ids, + name=name, + sparse_gradient=need_sparse_segment_gradient, + ) + elif combiner == "sqrtn": + embeddings = math_ops.sparse_segment_sqrt_n( + embeddings, + idx, + segment_ids, + name=name, + sparse_gradient=need_sparse_segment_gradient, + ) + else: + assert False, "Unrecognized combiner" + + return embeddings + + +def _prune_invalid_ids(sparse_ids, sparse_weights): + """Prune invalid IDs (< 0) from the input ids and weights.""" + is_id_valid = math_ops.greater_equal(sparse_ids.values, 0) + if sparse_weights is not None: + is_id_valid = math_ops.logical_and( + is_id_valid, + array_ops.ones_like(sparse_weights.values, dtype=dtypes.bool)) + sparse_ids = sparse_ops.sparse_retain(sparse_ids, is_id_valid) + if sparse_weights is not None: + sparse_weights = sparse_ops.sparse_retain(sparse_weights, is_id_valid) + return sparse_ids, sparse_weights + + +def _prune_invalid_weights(sparse_ids, sparse_weights): + """Prune invalid weights (< 0) from the input ids and weights.""" + if sparse_weights is not None: + is_weights_valid = math_ops.greater(sparse_weights.values, 0) + sparse_ids = sparse_ops.sparse_retain(sparse_ids, is_weights_valid) + sparse_weights = sparse_ops.sparse_retain(sparse_weights, is_weights_valid) + return sparse_ids, sparse_weights diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/filesystem_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/filesystem_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d30c24d1df9f01e83a8e351e2649c20d143606cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/filesystem_ops.py @@ -0,0 +1,38 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Filesystem related operations.""" + +from tensorflow.python.ops import gen_filesystem_ops as _gen_filesystem_ops + + +# pylint: disable=protected-access +def filesystem_set_configuration(scheme, key, value, name=None): + """Set configuration of the file system. + + Args: + scheme: File system scheme. + key: The name of the configuration option. + value: The value of the configuration option. + name: A name for the operation (optional). + + Returns: + None. + """ + + return _gen_filesystem_ops.file_system_set_configuration( + scheme, key=key, value=value, name=name) + + +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/functional_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/functional_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a50b445aea6394a0071f34e79ea3f10603d98bd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/functional_ops.py @@ -0,0 +1,1119 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Functional operations.""" + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import while_loop +# pylint: disable=unused-import +from tensorflow.python.ops.gen_functional_ops import remote_call +# pylint: enable=unused-import +from tensorflow.python.ops.gen_functional_ops import symbolic_gradient +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# TODO(yuanbyu, mrry): Handle stride to support sliding windows. +@tf_export(v1=["foldl"]) +@dispatch.add_dispatch_support +def foldl(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name=None): + """foldl on the list of tensors unpacked from `elems` on dimension 0. + + This foldl operator repeatedly applies the callable `fn` to a sequence + of elements from first to last. The elements are made of the tensors + unpacked from `elems` on dimension 0. The callable fn takes two tensors as + arguments. The first argument is the accumulated value computed from the + preceding invocation of fn, and the second is the value at the current + position of `elems`. If `initializer` is None, `elems` must contain at least + one element, and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is fn(initializer, values[0]).shape`. + + This method also allows multi-arity `elems` and output of `fn`. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The signature of `fn` may + match the structure of `elems`. That is, if `elems` is + `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: + `fn = lambda (t1, [t2, t3, [t4, t5]]):`. + + Args: + fn: The callable to be performed. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + as the initial value for the accumulator. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) True enables support for back propagation. + swap_memory: (optional) True enables GPU-CPU memory swapping. + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors, resulting from applying + `fn` consecutively to the list of tensors unpacked from `elems`, from first + to last. + + Raises: + TypeError: if `fn` is not callable. + + Example: + ```python + elems = tf.constant([1, 2, 3, 4, 5, 6]) + sum = foldl(lambda a, x: a + x, elems) + # sum == 21 + ``` + """ + if not callable(fn): + raise TypeError( + f"{fn.__name__} is not callable. Please provide a callable function.") + + def create_ta(elem): + return tensor_array_ops.TensorArray( + dtype=elem.dtype, size=n, dynamic_size=False, + infer_shape=True).unstack(elem) + + in_graph_mode = not context.executing_eagerly() + with ops.name_scope(name, "foldl", [elems]): + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode: + # Any get_variable calls in fn will cache the first call locally + # and not issue repeated network I/O requests for each iteration. + varscope = vs.get_variable_scope() + varscope_caching_device_was_none = False + if varscope.caching_device is None: + # TODO(ebrevdo): Change to using colocate_with here and in other + # methods. + varscope.set_caching_device(lambda op: op.device) + varscope_caching_device_was_none = True + + # Convert elems to tensor array. n may be known statically. + elems_flat = [ + ops.convert_to_tensor(elem, name="elem") for elem in nest.flatten(elems) + ] + n = ( + tensor_shape.dimension_value(elems_flat[0].shape[0]) or + array_ops.shape(elems_flat[0])[0]) + + elems_ta = nest.map_structure(create_ta, elems) + + if initializer is None: + a = nest.map_structure(lambda elem: elem.read(0), elems_ta) + i = constant_op.constant(1) + else: + a = initializer + i = constant_op.constant(0) + + def compute(i, a): + elem_i = nest.map_structure(lambda elem: elem.read(i), elems_ta) + a = fn(a, elem_i) + return [i + 1, a] + + _, r_a = while_loop.while_loop( + lambda i, a: i < n, + compute, [i, a], + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + maximum_iterations=n) + + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode and varscope_caching_device_was_none: + varscope.set_caching_device(None) + + return r_a + + +@tf_export("foldl", v1=[]) +@dispatch.add_dispatch_support +@deprecation.deprecated_arg_values( + None, + """back_prop=False is deprecated. Consider using tf.stop_gradient instead. +Instead of: +results = tf.foldl(fn, elems, back_prop=False) +Use: +results = tf.nest.map_structure(tf.stop_gradient, tf.foldl(fn, elems))""", + warn_once=True, + back_prop=False) +def foldl_v2(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name=None): + """foldl on the list of tensors unpacked from `elems` on dimension 0. + + This foldl operator repeatedly applies the callable `fn` to a sequence + of elements from first to last. The elements are made of the tensors + unpacked from `elems` on dimension 0. The callable fn takes two tensors as + arguments. The first argument is the accumulated value computed from the + preceding invocation of fn, and the second is the value at the current + position of `elems`. If `initializer` is None, `elems` must contain at least + one element, and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is fn(initializer, values[0]).shape`. + + This method also allows multi-arity `elems` and output of `fn`. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The signature of `fn` may + match the structure of `elems`. That is, if `elems` is + `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: + `fn = lambda (t1, [t2, t3, [t4, t5]]):`. + + Args: + fn: The callable to be performed. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + as the initial value for the accumulator. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) Deprecated. False disables support for back + propagation. Prefer using `tf.stop_gradient` instead. + swap_memory: (optional) True enables GPU-CPU memory swapping. + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors, resulting from applying + `fn` consecutively to the list of tensors unpacked from `elems`, from first + to last. + + Raises: + TypeError: if `fn` is not callable. + + Example: + ```python + elems = tf.constant([1, 2, 3, 4, 5, 6]) + sum = tf.foldl(lambda a, x: a + x, elems) + # sum == 21 + ``` + """ + return foldl( + fn=fn, + elems=elems, + initializer=initializer, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + name=name) + + +@tf_export(v1=["foldr"]) +@dispatch.add_dispatch_support +def foldr(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name=None): + """foldr on the list of tensors unpacked from `elems` on dimension 0. + + This foldr operator repeatedly applies the callable `fn` to a sequence + of elements from last to first. The elements are made of the tensors + unpacked from `elems`. The callable fn takes two tensors as arguments. + The first argument is the accumulated value computed from the preceding + invocation of fn, and the second is the value at the current position of + `elems`. If `initializer` is None, `elems` must contain at least one element, + and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is `fn(initializer, values[0]).shape`. + + This method also allows multi-arity `elems` and output of `fn`. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The signature of `fn` may + match the structure of `elems`. That is, if `elems` is + `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: + `fn = lambda (t1, [t2, t3, [t4, t5]]):`. + + Args: + fn: The callable to be performed. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + as the initial value for the accumulator. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) True enables support for back propagation. + swap_memory: (optional) True enables GPU-CPU memory swapping. + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors, resulting from applying + `fn` consecutively to the list of tensors unpacked from `elems`, from last + to first. + + Raises: + TypeError: if `fn` is not callable. + + Example: + ```python + elems = [1, 2, 3, 4, 5, 6] + sum = foldr(lambda a, x: a + x, elems) + # sum == 21 + ``` + """ + if not callable(fn): + raise TypeError( + f"{fn.__name__} is not callable. Please provide a callable function.") + + def create_ta(elem): + return tensor_array_ops.TensorArray( + dtype=elem.dtype, size=n, dynamic_size=False, + infer_shape=True).unstack(elem) + + in_graph_mode = not context.executing_eagerly() + with ops.name_scope(name, "foldr", [elems]): + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode: + # Any get_variable calls in fn will cache the first call locally and not + # issue repeated network I/O requests for each iteration. + varscope = vs.get_variable_scope() + varscope_caching_device_was_none = False + if varscope.caching_device is None: + # TODO(ebrevdo): Change to using colocate_with here and in other + # methods. + varscope.set_caching_device(lambda op: op.device) + varscope_caching_device_was_none = True + + # Convert elems to tensor array. n may be known statically. + elems_flat = [ + ops.convert_to_tensor(elem, name="elem") for elem in nest.flatten(elems) + ] + n = ( + tensor_shape.dimension_value(elems_flat[0].shape[0]) or + array_ops.shape(elems_flat[0])[0]) + + elems_ta = nest.map_structure(create_ta, elems) + + if initializer is None: + i = n - 1 + a = nest.map_structure(lambda elem: elem.read(i), elems_ta) + else: + i = n + a = initializer + + def compute(i, a): + i -= 1 + elem = nest.map_structure(lambda elem: elem.read(i), elems_ta) + a_out = fn(a, elem) + return [i, a_out] + + _, r_a = while_loop.while_loop( + lambda i, a: i > 0, + compute, [i, a], + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + maximum_iterations=n) + + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode and varscope_caching_device_was_none: + varscope.set_caching_device(None) + + return r_a + + +@tf_export("foldr", v1=[]) +@dispatch.add_dispatch_support +@deprecation.deprecated_arg_values( + None, + """back_prop=False is deprecated. Consider using tf.stop_gradient instead. +Instead of: +results = tf.foldr(fn, elems, back_prop=False) +Use: +results = tf.nest.map_structure(tf.stop_gradient, tf.foldr(fn, elems))""", + warn_once=True, + back_prop=False) +def foldr_v2(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name=None): + """foldr on the list of tensors unpacked from `elems` on dimension 0. + + This foldr operator repeatedly applies the callable `fn` to a sequence + of elements from last to first. The elements are made of the tensors + unpacked from `elems`. The callable fn takes two tensors as arguments. + The first argument is the accumulated value computed from the preceding + invocation of fn, and the second is the value at the current position of + `elems`. If `initializer` is None, `elems` must contain at least one element, + and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is `fn(initializer, values[0]).shape`. + + This method also allows multi-arity `elems` and output of `fn`. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The signature of `fn` may + match the structure of `elems`. That is, if `elems` is + `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: + `fn = lambda (t1, [t2, t3, [t4, t5]]):`. + + Args: + fn: The callable to be performed. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + as the initial value for the accumulator. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) Deprecated. False disables support for back + propagation. Prefer using `tf.stop_gradient` instead. + swap_memory: (optional) True enables GPU-CPU memory swapping. + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors, resulting from applying + `fn` consecutively to the list of tensors unpacked from `elems`, from last + to first. + + Raises: + TypeError: if `fn` is not callable. + + Example: + ```python + elems = [1, 2, 3, 4, 5, 6] + sum = tf.foldr(lambda a, x: a + x, elems) + # sum == 21 + ``` + """ + return foldr( + fn=fn, + elems=elems, + initializer=initializer, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + name=name) + + +@tf_export(v1=["scan"]) +@dispatch.add_dispatch_support +def scan(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + infer_shape=True, + reverse=False, + name=None): + """scan on the list of tensors unpacked from `elems` on dimension 0. + + See also `tf.map_fn`. + + The simplest version of `scan` repeatedly applies the callable `fn` to a + sequence of elements from first to last. The elements are made of the tensors + unpacked from `elems` on dimension 0. The callable fn takes two tensors as + arguments. The first argument is the accumulated value computed from the + preceding invocation of fn, and the second is the value at the current + position of `elems`. If `initializer` is None, `elems` must contain at least + one element, and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`. + If reverse=True, it's fn(initializer, values[-1]).shape. + + This method also allows multi-arity `elems` and accumulator. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The second argument of + `fn` must match the structure of `elems`. + + If no `initializer` is provided, the output structure and dtypes of `fn` + are assumed to be the same as its input; and in this case, the first + argument of `fn` must match the structure of `elems`. + + If an `initializer` is provided, then the output of `fn` must have the same + structure as `initializer`; and the first argument of `fn` must match + this structure. + + For example, if `elems` is `(t1, [t2, t3])` and `initializer` is + `[i1, i2]` then an appropriate signature for `fn` in `python2` is: + `fn = lambda (acc_p1, acc_p2), (t1, [t2, t3]):` and `fn` must return a list, + `[acc_n1, acc_n2]`. An alternative correct signature for `fn`, and the + one that works in `python3`, is: + `fn = lambda a, t:`, where `a` and `t` correspond to the input tuples. + + Args: + fn: The callable to be performed. It accepts two arguments. The first will + have the same structure as `initializer` if one is provided, otherwise it + will have the same structure as `elems`. The second will have the same + (possibly nested) structure as `elems`. Its output must have the same + structure as `initializer` if one is provided, otherwise it must have the + same structure as `elems`. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + initial value for the accumulator, and the expected output type of `fn`. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) True enables support for back propagation. + swap_memory: (optional) True enables GPU-CPU memory swapping. + infer_shape: (optional) False disables tests for consistent output shapes. + reverse: (optional) True scans the tensor last to first (instead of first to + last). + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors. Each tensor packs the + results of applying `fn` to tensors unpacked from `elems` along the first + dimension, and the previous accumulator value(s), from first to last (or + last to first, if `reverse=True`). + + Raises: + TypeError: if `fn` is not callable or the structure of the output of + `fn` and `initializer` do not match. + ValueError: if the lengths of the output of `fn` and `initializer` + do not match. + + Examples: + ```python + elems = np.array([1, 2, 3, 4, 5, 6]) + sum = scan(lambda a, x: a + x, elems) + # sum == [1, 3, 6, 10, 15, 21] + sum = scan(lambda a, x: a + x, elems, reverse=True) + # sum == [21, 20, 18, 15, 11, 6] + ``` + + ```python + elems = np.array([1, 2, 3, 4, 5, 6]) + initializer = np.array(0) + sum_one = scan( + lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer) + # sum_one == [1, 2, 3, 4, 5, 6] + ``` + + ```python + elems = np.array([1, 0, 0, 0, 0, 0]) + initializer = (np.array(0), np.array(1)) + fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer) + # fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13]) + ``` + """ + if not callable(fn): + raise TypeError( + f"{fn.__name__} is not callable. Please provide a callable function.") + + input_is_sequence = nest.is_nested(elems) + input_flatten = lambda x: nest.flatten(x) if input_is_sequence else [x] + + def input_pack(x): + return nest.pack_sequence_as(elems, x) if input_is_sequence else x[0] + + if initializer is None: + output_is_sequence = input_is_sequence + output_flatten = input_flatten + output_pack = input_pack + else: + output_is_sequence = nest.is_nested(initializer) + output_flatten = lambda x: nest.flatten(x) if output_is_sequence else [x] + + def output_pack(x): + return (nest.pack_sequence_as(initializer, x) + if output_is_sequence else x[0]) + + elems_flat = input_flatten(elems) + + in_graph_mode = not context.executing_eagerly() + with ops.name_scope(name, "scan", elems_flat): + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode: + # Any get_variable calls in fn will cache the first call locally + # and not issue repeated network I/O requests for each iteration. + varscope = vs.get_variable_scope() + varscope_caching_device_was_none = False + if varscope.caching_device is None: + # TODO(ebrevdo): Change to using colocate_with here and in other + # methods. + varscope.set_caching_device(lambda op: op.device) + varscope_caching_device_was_none = True + + # Convert elems to tensor array. + elems_flat = [ + ops.convert_to_tensor(elem, name="elem") for elem in elems_flat + ] + + # Convert elems to tensor array. n may be known statically. + n = tensor_shape.dimension_value(elems_flat[0].shape[0]) + if n is None: + n = array_ops.shape(elems_flat[0])[0] + + # TensorArrays are always flat + elems_ta = [ + tensor_array_ops.TensorArray( + dtype=elem.dtype, + size=n, + dynamic_size=False, + element_shape=elem.shape[1:], + infer_shape=True) for elem in elems_flat + ] + # Unpack elements + elems_ta = [ + elem_ta.unstack(elem) for elem_ta, elem in zip(elems_ta, elems_flat) + ] + + if initializer is None: + a_flat = [elem.read(n - 1 if reverse else 0) for elem in elems_ta] + i = 1 + else: + initializer_flat = output_flatten(initializer) + a_flat = [ops.convert_to_tensor(init) for init in initializer_flat] + i = 0 + + # Create a tensor array to store the intermediate values. + accs_ta = [ + tensor_array_ops.TensorArray( + dtype=init.dtype, + size=n, + element_shape=init.shape if infer_shape else None, + dynamic_size=False, + infer_shape=infer_shape) for init in a_flat + ] + + if initializer is None: + accs_ta = [ + acc_ta.write(n - 1 if reverse else 0, a) + for (acc_ta, a) in zip(accs_ta, a_flat) + ] + + def compute(i, a_flat, tas): + """The loop body of scan. + + Args: + i: the loop counter. + a_flat: the accumulator value(s), flattened. + tas: the output accumulator TensorArray(s), flattened. + + Returns: + [i + 1, a_flat, tas]: the updated counter + new accumulator values + + updated TensorArrays + + Raises: + TypeError: if initializer and fn() output structure do not match + ValueType: if initializer and fn() output lengths do not match + """ + packed_elems = input_pack([elem_ta.read(i) for elem_ta in elems_ta]) + packed_a = output_pack(a_flat) + a_out = fn(packed_a, packed_elems) + nest.assert_same_structure(elems if initializer is None else initializer, + a_out) + flat_a_out = output_flatten(a_out) + tas = [ta.write(i, value) for (ta, value) in zip(tas, flat_a_out)] + if reverse: + next_i = i - 1 + else: + next_i = i + 1 + return (next_i, flat_a_out, tas) + + if reverse: + initial_i = n - 1 - i + condition = lambda i, _1, _2: i >= 0 + else: + initial_i = i + condition = lambda i, _1, _2: i < n + _, _, r_a = while_loop.while_loop( + condition, + compute, (initial_i, a_flat, accs_ta), + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + maximum_iterations=n) + + results_flat = [r.stack() for r in r_a] + + n_static = tensor_shape.Dimension( + tensor_shape.dimension_value( + elems_flat[0].get_shape().with_rank_at_least(1)[0])) + for elem in elems_flat[1:]: + n_static.assert_is_compatible_with( + tensor_shape.Dimension( + tensor_shape.dimension_value( + elem.get_shape().with_rank_at_least(1)[0]))) + for r in results_flat: + r.set_shape( + tensor_shape.TensorShape(n_static).concatenate(r.get_shape()[1:])) + + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode and varscope_caching_device_was_none: + varscope.set_caching_device(None) + + return output_pack(results_flat) + + +@tf_export("scan", v1=[]) +@dispatch.add_dispatch_support +@deprecation.deprecated_arg_values( + None, + """back_prop=False is deprecated. Consider using tf.stop_gradient instead. +Instead of: +results = tf.scan(fn, elems, back_prop=False) +Use: +results = tf.nest.map_structure(tf.stop_gradient, tf.scan(fn, elems))""", + warn_once=True, + back_prop=False) +def scan_v2(fn, + elems, + initializer=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + infer_shape=True, + reverse=False, + name=None): + """scan on the list of tensors unpacked from `elems` on dimension 0. + + The simplest version of `scan` repeatedly applies the callable `fn` to a + sequence of elements from first to last. The elements are made of the tensors + unpacked from `elems` on dimension 0. The callable fn takes two tensors as + arguments. The first argument is the accumulated value computed from the + preceding invocation of fn, and the second is the value at the current + position of `elems`. If `initializer` is None, `elems` must contain at least + one element, and its first element is used as the initializer. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`. + If reverse=True, it's fn(initializer, values[-1]).shape. + + This method also allows multi-arity `elems` and accumulator. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The second argument of + `fn` must match the structure of `elems`. + + If no `initializer` is provided, the output structure and dtypes of `fn` + are assumed to be the same as its input; and in this case, the first + argument of `fn` must match the structure of `elems`. + + If an `initializer` is provided, then the output of `fn` must have the same + structure as `initializer`; and the first argument of `fn` must match + this structure. + + For example, if `elems` is `(t1, [t2, t3])` and `initializer` is + `[i1, i2]` then an appropriate signature for `fn` in `python2` is: + `fn = lambda (acc_p1, acc_p2), (t1, [t2, t3]):` and `fn` must return a list, + `[acc_n1, acc_n2]`. An alternative correct signature for `fn`, and the + one that works in `python3`, is: + `fn = lambda a, t:`, where `a` and `t` correspond to the input tuples. + + Args: + fn: The callable to be performed. It accepts two arguments. The first will + have the same structure as `initializer` if one is provided, otherwise it + will have the same structure as `elems`. The second will have the same + (possibly nested) structure as `elems`. Its output must have the same + structure as `initializer` if one is provided, otherwise it must have the + same structure as `elems`. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be the first argument to `fn`. + initializer: (optional) A tensor or (possibly nested) sequence of tensors, + initial value for the accumulator, and the expected output type of `fn`. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. + back_prop: (optional) Deprecated. False disables support for back + propagation. Prefer using `tf.stop_gradient` instead. + swap_memory: (optional) True enables GPU-CPU memory swapping. + infer_shape: (optional) False disables tests for consistent output shapes. + reverse: (optional) True scans the tensor last to first (instead of first to + last). + name: (optional) Name prefix for the returned tensors. + + Returns: + A tensor or (possibly nested) sequence of tensors. Each tensor packs the + results of applying `fn` to tensors unpacked from `elems` along the first + dimension, and the previous accumulator value(s), from first to last (or + last to first, if `reverse=True`). + + Raises: + TypeError: if `fn` is not callable or the structure of the output of + `fn` and `initializer` do not match. + ValueError: if the lengths of the output of `fn` and `initializer` + do not match. + + Examples: + ```python + elems = np.array([1, 2, 3, 4, 5, 6]) + sum = scan(lambda a, x: a + x, elems) + # sum == [1, 3, 6, 10, 15, 21] + sum = scan(lambda a, x: a + x, elems, reverse=True) + # sum == [21, 20, 18, 15, 11, 6] + ``` + + ```python + elems = np.array([1, 2, 3, 4, 5, 6]) + initializer = np.array(0) + sum_one = scan( + lambda a, x: x[0] - x[1] + a, (elems + 1, elems), initializer) + # sum_one == [1, 2, 3, 4, 5, 6] + ``` + + ```python + elems = np.array([1, 0, 0, 0, 0, 0]) + initializer = (np.array(0), np.array(1)) + fibonaccis = scan(lambda a, _: (a[1], a[0] + a[1]), elems, initializer) + # fibonaccis == ([1, 1, 2, 3, 5, 8], [1, 2, 3, 5, 8, 13]) + ``` + """ + return scan( + fn=fn, + elems=elems, + initializer=initializer, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + infer_shape=infer_shape, + reverse=reverse, + name=name) + + +# pylint: disable=invalid-name +def If(cond, inputs, then_branch, else_branch, name=None): + r"""output = Cond(inputs) ? + + then_branch(inputs) : else_branch(inputs). + + Args: + cond: A `Tensor`. A scalar. If the scalar is not a boolean, the scalar is + converted to a boolean according to the following rule: if the scalar is a + numerical value, non-zero means True and zero means False; if the scalar + is a string, non-empty means True and empty means False. + inputs: A list of input tensors. + then_branch: A function takes 'inputs' and returns a list of tensors, whose + types are the same as what else_branch returns. + else_branch: A function takes 'inputs' and returns a list of tensors. whose + types are the same as what then_branch returns. + name: A name for the operation (optional). + + Returns: + A list of tensors returned by either then_branch(inputs) + or else_branch(inputs). + """ + # pylint: disable=protected-access + # Handle the Defun case until users have transitioned to tf.function. Note + # that composites may need to be re-packed by the caller. + if isinstance(then_branch, function._DefinedFunction): + tlist = [_.type for _ in then_branch.definition.signature.output_arg] + return gen_functional_ops._if( + cond, inputs, tlist, then_branch, else_branch, name=name) + + # We assume that `then_branch` is a ConcreteFunction here. + then_out = then_branch.structured_outputs + else_out = else_branch.structured_outputs + + # Ensure then/else are the same type of composites to avoid an invalid call + # to pack_sequence_as later on. + nest.assert_same_structure(then_out, else_out, expand_composites=True) + + tlist = nest.flatten(then_branch.output_dtypes) + ret = gen_functional_ops._if( + cond, inputs, tlist, then_branch, else_branch, name=name) + + # Re-pack the outputs to restore any CompositeTensors + return nest.pack_sequence_as(then_out, ret, expand_composites=True) + + +def Gradient(inputs, f, name=None): + r"""Computes the gradient function for function f via backpropagation. + + Args: + inputs: A list of tensors of size N + M. + f: The function we want to compute the gradient for. The function 'f' must + be a numerical function which takes N inputs and produces M outputs. Its + gradient function 'g', which is a function taking N + M inputs and + produces N outputs. I.e. if we have (y1, y2, ..., yM) = f(x1, x2, ..., + xN), then, g is (dL/dx1, dL/dx2, ..., dL/dxN) = g(x1, x2, ..., xN, dL/dy1, + dL/dy2, ..., dL/dyM), where L is a scalar-value function of (x1, x2, ..., + xN) (e.g., the loss function). dL/dxi is the partial derivative of L with + respect to xi. + name: A name for the operation (optional). + + Returns: + A list of tensors of size N. + """ + # TODO(zhifengc): Pretty-print the above spec in latex. + # TODO(zhfiengc): Needs some math expert to say the comment above better. + tlist = [_.type for _ in f.definition.signature.input_arg] + return symbolic_gradient(input=inputs, Tout=tlist, f=f, name=name) + + +def _GetInputDtypes(func): + """Returns the input dtypes of func, excluding dtypes for captured inputs.""" + if isinstance(func, function._DefinedFunction): # pylint: disable=protected-access + return func.declared_input_types + + # We assume that `func` is a ConcreteFunction here, but we are not able to + # verify since importing eager function library will cause cyclic dependence. + # + # ConcreteFunction.inputs includes captured inputs. + num_non_captured_inputs = len(func.inputs) - len(func.captured_inputs) + inputs_without_captured = func.inputs[:num_non_captured_inputs] + return [t.dtype for t in inputs_without_captured] + + +def _LoopBodyCaptureWrapper(func): + """Returns a wrapper for `func` that handles loop-carried captured inputs.""" + + @function.Defun(*_GetInputDtypes(func), func_name="%s_Wrapper" % func.name) + def Wrapper(*args): + """A wrapper that handles loop-carried captured inputs.""" + result = func(*args) + extra_args = tuple(function.get_extra_args()) + # Nullary functions return an Operation. Normal functions can't do this + # because their return values are converted to Tensors. + if isinstance(result, ops.Operation): + return extra_args + # Unary functions return a single Tensor value. + elif not isinstance(result, (list, tuple)): + return (result,) + extra_args + # N-ary functions return a tuple of Tensors. + else: + return result + type(result)(extra_args) + + return Wrapper + + +# pylint: disable=invalid-name,protected-access +def While(input_, cond, body, name=None, hostmem=None): + r"""output = input; While (Cond(output)) { output = Body(output) }. + + Args: + input_: A list of `Tensor` objects. A list of input tensors whose types are + T. + cond: . A function takes 'input' and returns a tensor. If the tensor is a + scalar of non-boolean, the scalar is converted to a boolean + according to the following rule: if the scalar is a numerical value, + non-zero means True and zero means False; if the scalar is a string, + non-empty means True and empty means False. If the tensor is not a + scalar, non-emptiness means True and False otherwise. + body: . A function takes a list of tensors and returns another list tensors. + Both lists have the same types as specified by T. + name: A name for the operation (optional). + hostmem: A list of integer. If i is in the list, input[i] is a host memory + tensor. + + Raises: + ValueError: if `cond` has implicitly captured inputs or if `cond` and `body` + have different signatures. + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + A list of output tensors whose types are T. + """ + if cond.captured_inputs: + raise ValueError( + "The 'cond' argument can not have implicitly captured inputs. Received " + f"captured_inputs: {cond.captured_inputs}") + + cond_input_types = _GetInputDtypes(cond) + body_input_types = _GetInputDtypes(body) + + if cond_input_types != body_input_types: + raise ValueError( + "The 'cond' and 'body' signatures do not match. Received: " + f"cond_input_types={cond_input_types}, body_input_types=" + f"{body_input_types}") + + if body.captured_inputs: + cond_dtypes = list(body_input_types) + [ + t.dtype for t in body.captured_inputs + ] + + @function.Defun(*cond_dtypes, func_name="%s_Wrapper" % cond.name) + def CondWrapper(*args): + """A wrapper that handles loop-carried captured inputs.""" + return cond(*args[:len(body_input_types)]) + + ret = gen_functional_ops._while( + input_ + body.captured_inputs, + CondWrapper, + _LoopBodyCaptureWrapper(body), + name=name) + # Slice off the loop-carried captured inputs. + ret = ret[:-len(body.captured_inputs)] + else: + ret = gen_functional_ops._while(input_, cond, body, name=name) + if hostmem: + input_attr = attr_value_pb2.AttrValue() + input_attr.list.i.extend(hostmem) + ret[0].op._set_attr("_input_hostmem", input_attr) # pylint: disable=protected-access + + output_attr = attr_value_pb2.AttrValue() + output_attr.list.i.extend(hostmem) + ret[0].op._set_attr("_output_hostmem", output_attr) # pylint: disable=protected-access + return ret + + +# b/36459430 +# +# Ideally, we do not need this rewrite For loop into a While loop. +# However, today, if a While runs on GPU and the condition returns a +# boolean, the While kernel crashes. Even if we fix the crash, the +# bool needs to be copied between GPU and CPU. So, a for loop is much +# preferred when running on GPU. +# +# On the other hand, For op has no directly XLA kernel. So, when we run +# a for loop, we need to rewrite it using a While op. +# +# It should be possible and probably better to write a XLA C++ kernel +# implementing the logic in _ForUsingWhile. +def _ForUsingWhile(start, + limit, + delta, + inputs, + forbody, + name=None, + hostmem=None): + """Helper to implement a For loop using a While.""" + # To support negative delta (e.g., range(100, 0, -3)), we iterate + # over the range(n) and use iter * delta + start as the real + # iteration index. (e.g., for i in range(34): iter = i * (-3) + + # 100). + d = math_ops.abs(delta) + # XLA on TPUs doesn't support integer division + n = math_ops.cast( + math_ops.cast((math_ops.abs(limit - start) + d - 1), dtypes.float32) / + math_ops.cast(d, dtypes.float32), dtypes.int32) + + # Carried loop variables ("extra_args") are implicitly added to the input list + # of the WhileBody function. WhileCond does not call forbody, and so does not + # depend on any of forbody's extra_args. Since WhileCond and WhileBody + # must have identical inputs, we have to augment the cond signature to take + # the same types as the carried loop variables. + body_sig = [dtypes.int32] * 4 + list(forbody.declared_input_types)[1:] + + cond_name = "%s_Cond" % forbody.name + + @function.Defun(*body_sig, func_name=cond_name) + def WhileCond(i, n, *args): + del args + return i < n + + body_name = "%s_Body" % forbody.name + + @function.Defun(*body_sig, func_name=body_name) + def WhileBody(i, n, start, delta, *args): + """A While wrapper for forbody that handles loop-carried captured inputs.""" + for_result = forbody(start + i * delta, *args) + # Nullary functions return an Operation. Normal functions can't do this + # because their return values are converted to Tensors. + if isinstance(for_result, ops.Operation): + for_result = () + # Unary functions return a single Tensor value. + elif isinstance(for_result, tensor.Tensor): + for_result = (for_result,) + return (i + 1, n, start, delta) + tuple(for_result) + + if hostmem is not None: + hostmem = [0, 1, 2, 3] + [(4 + _) for _ in hostmem] + else: + hostmem = [0, 1, 2, 3] + + results = While( + input_=[0, n, start, delta] + inputs, + cond=WhileCond, + body=WhileBody, + name=name, + hostmem=hostmem) + # Slice off the loop-carried captured inputs. + return list(results[4:len(results)]) + + +def For(start, + limit, + delta, + inputs, + body, + name=None, + hostmem=None, + rewrite_with_while=None): + r"""out = input; for i in range(start, limit, delta) out = body(i, out). + + Args: + start: A `Tensor` of type `int32`. + limit: A `Tensor` of type `int32`. + delta: A `Tensor` of type `int32`. + inputs: A list of `Tensor` objects. A list of input tensors whose types are + T. + body: A function takes a list of tensors and returns another list of + tensors. Both lists have the same types as (int32, T...). + name: A name for the operation (optional). + hostmem: A list of integer. If i is in the list, inputs[i] is a host memory + tensor. In other words, (i+1)-th argument of the body function is + expecting a host memory. + rewrite_with_while: If True, using While op to implement the For. + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + A list of output tensors whose types are T. + """ + if rewrite_with_while: + return _ForUsingWhile(start, limit, delta, inputs, body, name, hostmem) + if body.captured_inputs: + ret = gen_functional_ops._for( + start, + limit, + delta, + inputs + body.captured_inputs, + _LoopBodyCaptureWrapper(body), + name=name) + # Slice off the loop-carried captured inputs. + ret = ret[:-len(body.captured_inputs)] + else: + ret = gen_functional_ops._for(start, limit, delta, inputs, body, name=name) + if hostmem: + num_for_params = 3 # start/limit/delta + + input_attr = attr_value_pb2.AttrValue() + input_attr.list.i.extend([num_for_params + i for i in hostmem]) + ret[0].op._set_attr("_input_hostmem", input_attr) # pylint: disable=protected-access + + output_attr = attr_value_pb2.AttrValue() + output_attr.list.i.extend(hostmem) + ret[0].op._set_attr("_output_hostmem", output_attr) # pylint: disable=protected-access + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc8d0c43276d6dc1a804a80eac3c552fddb8924 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_array_ops.py @@ -0,0 +1,13096 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_BatchMatrixBandPart_T = TypeVar("TV_BatchMatrixBandPart_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def batch_matrix_band_part(input: Annotated[Any, TV_BatchMatrixBandPart_T], num_lower: Annotated[Any, _atypes.Int64], num_upper: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, TV_BatchMatrixBandPart_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. + num_lower: A `Tensor` of type `int64`. + num_upper: A `Tensor` of type `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixBandPart", name, input, num_lower, num_upper) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_band_part_eager_fallback( + input, num_lower, num_upper, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixBandPart", input=input, num_lower=num_lower, + num_upper=num_upper, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixBandPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixBandPart = tf_export("raw_ops.BatchMatrixBandPart")(_ops.to_raw_op(batch_matrix_band_part)) + + +def batch_matrix_band_part_eager_fallback(input: Annotated[Any, TV_BatchMatrixBandPart_T], num_lower: Annotated[Any, _atypes.Int64], num_upper: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, TV_BatchMatrixBandPart_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + num_lower = _ops.convert_to_tensor(num_lower, _dtypes.int64) + num_upper = _ops.convert_to_tensor(num_upper, _dtypes.int64) + _inputs_flat = [input, num_lower, num_upper] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchMatrixBandPart", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixBandPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixDiag_T = TypeVar("TV_BatchMatrixDiag_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def batch_matrix_diag(diagonal: Annotated[Any, TV_BatchMatrixDiag_T], name=None) -> Annotated[Any, TV_BatchMatrixDiag_T]: + r"""TODO: add doc. + + Args: + diagonal: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixDiag", name, diagonal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_diag_eager_fallback( + diagonal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixDiag", diagonal=diagonal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixDiag = tf_export("raw_ops.BatchMatrixDiag")(_ops.to_raw_op(batch_matrix_diag)) + + +def batch_matrix_diag_eager_fallback(diagonal: Annotated[Any, TV_BatchMatrixDiag_T], name, ctx) -> Annotated[Any, TV_BatchMatrixDiag_T]: + _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], ctx, []) + _inputs_flat = [diagonal] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchMatrixDiag", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixDiagPart_T = TypeVar("TV_BatchMatrixDiagPart_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def batch_matrix_diag_part(input: Annotated[Any, TV_BatchMatrixDiagPart_T], name=None) -> Annotated[Any, TV_BatchMatrixDiagPart_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixDiagPart", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_diag_part_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixDiagPart", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixDiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixDiagPart = tf_export("raw_ops.BatchMatrixDiagPart")(_ops.to_raw_op(batch_matrix_diag_part)) + + +def batch_matrix_diag_part_eager_fallback(input: Annotated[Any, TV_BatchMatrixDiagPart_T], name, ctx) -> Annotated[Any, TV_BatchMatrixDiagPart_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchMatrixDiagPart", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixDiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixSetDiag_T = TypeVar("TV_BatchMatrixSetDiag_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def batch_matrix_set_diag(input: Annotated[Any, TV_BatchMatrixSetDiag_T], diagonal: Annotated[Any, TV_BatchMatrixSetDiag_T], name=None) -> Annotated[Any, TV_BatchMatrixSetDiag_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. + diagonal: A `Tensor`. Must have the same type as `input`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixSetDiag", name, input, diagonal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_set_diag_eager_fallback( + input, diagonal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixSetDiag", input=input, diagonal=diagonal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixSetDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixSetDiag = tf_export("raw_ops.BatchMatrixSetDiag")(_ops.to_raw_op(batch_matrix_set_diag)) + + +def batch_matrix_set_diag_eager_fallback(input: Annotated[Any, TV_BatchMatrixSetDiag_T], diagonal: Annotated[Any, TV_BatchMatrixSetDiag_T], name, ctx) -> Annotated[Any, TV_BatchMatrixSetDiag_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], ctx, []) + (input, diagonal) = _inputs_T + _inputs_flat = [input, diagonal] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchMatrixSetDiag", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixSetDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchToSpace_T = TypeVar("TV_BatchToSpace_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_BatchToSpace_Tidx = TypeVar("TV_BatchToSpace_Tidx", _atypes.Int32, _atypes.Int64) + +def batch_to_space(input: Annotated[Any, TV_BatchToSpace_T], crops: Annotated[Any, TV_BatchToSpace_Tidx], block_size: int, name=None) -> Annotated[Any, TV_BatchToSpace_T]: + r"""BatchToSpace for 4-D tensors of type T. + + This is a legacy version of the more general BatchToSpaceND. + + Rearranges (permutes) data from batch into blocks of spatial data, followed by + cropping. This is the reverse transformation of SpaceToBatch. More specifically, + this op outputs a copy of the input tensor where values from the `batch` + dimension are moved in spatial blocks to the `height` and `width` dimensions, + followed by cropping along the `height` and `width` dimensions. + + Args: + input: A `Tensor`. 4-D tensor with shape + `[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, + depth]`. Note that the batch size of the input tensor must be divisible by + `block_size * block_size`. + crops: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies + how many elements to crop from the intermediate result across the spatial + dimensions as follows: + + crops = [[crop_top, crop_bottom], [crop_left, crop_right]] + block_size: An `int` that is `>= 2`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchToSpace", name, input, crops, "block_size", block_size) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_to_space_eager_fallback( + input, crops, block_size=block_size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + block_size = _execute.make_int(block_size, "block_size") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchToSpace", input=input, crops=crops, block_size=block_size, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "block_size", + _op._get_attr_int("block_size"), "Tidx", + _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchToSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchToSpace = tf_export("raw_ops.BatchToSpace")(_ops.to_raw_op(batch_to_space)) + + +def batch_to_space_eager_fallback(input: Annotated[Any, TV_BatchToSpace_T], crops: Annotated[Any, TV_BatchToSpace_Tidx], block_size: int, name, ctx) -> Annotated[Any, TV_BatchToSpace_T]: + block_size = _execute.make_int(block_size, "block_size") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tidx, (crops,) = _execute.args_to_matching_eager([crops], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, crops] + _attrs = ("T", _attr_T, "block_size", block_size, "Tidx", _attr_Tidx) + _result = _execute.execute(b"BatchToSpace", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchToSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchToSpaceND_T = TypeVar("TV_BatchToSpaceND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_BatchToSpaceND_Tblock_shape = TypeVar("TV_BatchToSpaceND_Tblock_shape", _atypes.Int32, _atypes.Int64) +TV_BatchToSpaceND_Tcrops = TypeVar("TV_BatchToSpaceND_Tcrops", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['batch_to_space_nd', 'manip.batch_to_space_nd']) +@deprecated_endpoints('batch_to_space_nd', 'manip.batch_to_space_nd') +def batch_to_space_nd(input: Annotated[Any, TV_BatchToSpaceND_T], block_shape: Annotated[Any, TV_BatchToSpaceND_Tblock_shape], crops: Annotated[Any, TV_BatchToSpaceND_Tcrops], name=None) -> Annotated[Any, TV_BatchToSpaceND_T]: + r"""BatchToSpace for N-D tensors of type T. + + This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of shape + `block_shape + [batch]`, interleaves these blocks back into the grid defined by + the spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as + the input. The spatial dimensions of this intermediate result are then + optionally cropped according to `crops` to produce the output. This is the + reverse of SpaceToBatch. See below for a precise description. + + Args: + input: A `Tensor`. + N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, + where spatial_shape has M dimensions. + block_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D with shape `[M]`, all values must be >= 1. + crops: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D with shape `[M, 2]`, all values must be >= 0. + `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input + dimension `i + 1`, which corresponds to spatial dimension `i`. It is + required that + `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. + + This operation is equivalent to the following steps: + + 1. Reshape `input` to `reshaped` of shape: + [block_shape[0], ..., block_shape[M-1], + batch / prod(block_shape), + input_shape[1], ..., input_shape[N-1]] + + 2. Permute dimensions of `reshaped` to produce `permuted` of shape + [batch / prod(block_shape), + + input_shape[1], block_shape[0], + ..., + input_shape[M], block_shape[M-1], + + input_shape[M+1], ..., input_shape[N-1]] + + 3. Reshape `permuted` to produce `reshaped_permuted` of shape + [batch / prod(block_shape), + + input_shape[1] * block_shape[0], + ..., + input_shape[M] * block_shape[M-1], + + input_shape[M+1], + ..., + input_shape[N-1]] + + 4. Crop the start and end of dimensions `[1, ..., M]` of + `reshaped_permuted` according to `crops` to produce the output of shape: + [batch / prod(block_shape), + + input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], + ..., + input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], + + input_shape[M+1], ..., input_shape[N-1]] + + Some examples: + + (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and + `crops = [[0, 0], [0, 0]]`: + + ``` + [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] + ``` + + The output tensor has shape `[1, 2, 2, 1]` and value: + + ``` + x = [[[[1], [2]], [[3], [4]]]] + ``` + + (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and + `crops = [[0, 0], [0, 0]]`: + + ``` + [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] + ``` + + The output tensor has shape `[1, 2, 2, 3]` and value: + + ``` + x = [[[[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]]]] + ``` + + (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and + `crops = [[0, 0], [0, 0]]`: + + ``` + x = [[[[1], [3]], [[9], [11]]], + [[[2], [4]], [[10], [12]]], + [[[5], [7]], [[13], [15]]], + [[[6], [8]], [[14], [16]]]] + ``` + + The output tensor has shape `[1, 4, 4, 1]` and value: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]], + [[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and + `crops = [[0, 0], [2, 0]]`: + + ``` + x = [[[[0], [1], [3]]], [[[0], [9], [11]]], + [[[0], [2], [4]]], [[[0], [10], [12]]], + [[[0], [5], [7]]], [[[0], [13], [15]]], + [[[0], [6], [8]]], [[[0], [14], [16]]]] + ``` + + The output tensor has shape `[2, 2, 4, 1]` and value: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]]], + [[[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchToSpaceND", name, input, block_shape, crops) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_batch_to_space_nd( + (input, block_shape, crops, name,), None) + if _result is not NotImplemented: + return _result + return batch_to_space_nd_eager_fallback( + input, block_shape, crops, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + batch_to_space_nd, (), dict(input=input, block_shape=block_shape, + crops=crops, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_batch_to_space_nd( + (input, block_shape, crops, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchToSpaceND", input=input, block_shape=block_shape, crops=crops, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + batch_to_space_nd, (), dict(input=input, block_shape=block_shape, + crops=crops, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tblock_shape", + _op._get_attr_type("Tblock_shape"), "Tcrops", + _op._get_attr_type("Tcrops")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchToSpaceND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchToSpaceND = tf_export("raw_ops.BatchToSpaceND")(_ops.to_raw_op(batch_to_space_nd)) +_dispatcher_for_batch_to_space_nd = batch_to_space_nd._tf_type_based_dispatcher.Dispatch + + +def batch_to_space_nd_eager_fallback(input: Annotated[Any, TV_BatchToSpaceND_T], block_shape: Annotated[Any, TV_BatchToSpaceND_Tblock_shape], crops: Annotated[Any, TV_BatchToSpaceND_Tcrops], name, ctx) -> Annotated[Any, TV_BatchToSpaceND_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tblock_shape, (block_shape,) = _execute.args_to_matching_eager([block_shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tcrops, (crops,) = _execute.args_to_matching_eager([crops], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, block_shape, crops] + _attrs = ("T", _attr_T, "Tblock_shape", _attr_Tblock_shape, "Tcrops", + _attr_Tcrops) + _result = _execute.execute(b"BatchToSpaceND", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchToSpaceND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Bitcast_T = TypeVar("TV_Bitcast_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Bitcast_type = TypeVar("TV_Bitcast_type", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitcast') +def bitcast(input: Annotated[Any, TV_Bitcast_T], type: TV_Bitcast_type, name=None) -> Annotated[Any, TV_Bitcast_type]: + r"""Bitcasts a tensor from one type to another without copying data. + + Given a tensor `input`, this operation returns a tensor that has the same buffer + data as `input` with datatype `type`. + + If the input datatype `T` is larger than the output datatype `type` then the + shape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)]. + + If `T` is smaller than `type`, the operator requires that the rightmost + dimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from + [..., sizeof(`type`)/sizeof(`T`)] to [...]. + + tf.bitcast() and tf.cast() work differently when real dtype is casted as a complex dtype + (e.g. tf.complex64 or tf.complex128) as tf.cast() make imaginary part 0 while tf.bitcast() + gives module error. + For example, + + Example 1: + + >>> a = [1., 2., 3.] + >>> equality_bitcast = tf.bitcast(a, tf.complex128) + Traceback (most recent call last): + ... + InvalidArgumentError: Cannot bitcast from 1 to 18 [Op:Bitcast] + >>> equality_cast = tf.cast(a, tf.complex128) + >>> print(equality_cast) + tf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128) + + Example 2: + + >>> tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8) + + + Example 3: + + >>> x = [1., 2., 3.] + >>> y = [0., 2., 3.] + >>> equality= tf.equal(x,y) + >>> equality_cast = tf.cast(equality,tf.float32) + >>> equality_bitcast = tf.bitcast(equality_cast,tf.uint8) + >>> print(equality) + tf.Tensor([False True True], shape=(3,), dtype=bool) + >>> print(equality_cast) + tf.Tensor([0. 1. 1.], shape=(3,), dtype=float32) + >>> print(equality_bitcast) + tf.Tensor( + [[ 0 0 0 0] + [ 0 0 128 63] + [ 0 0 128 63]], shape=(3, 4), dtype=uint8) + + *NOTE*: Bitcast is implemented as a low-level cast, so machines with different + endian orderings will give different results. A copy from input buffer to output + buffer is made on BE machines when types are of different sizes in order to get + the same casting results as on LE machines. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`. + type: A `tf.DType` from: `tf.bfloat16, tf.half, tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.uint32, tf.uint64, tf.int8, tf.int16, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint16, tf.quint16, tf.qint32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Bitcast", name, input, "type", type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_bitcast( + (input, type, name,), None) + if _result is not NotImplemented: + return _result + return bitcast_eager_fallback( + input, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitcast, (), dict(input=input, type=type, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_bitcast( + (input, type, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Bitcast", input=input, type=type, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitcast, (), dict(input=input, type=type, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "type", + _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Bitcast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Bitcast = tf_export("raw_ops.Bitcast")(_ops.to_raw_op(bitcast)) +_dispatcher_for_bitcast = bitcast._tf_type_based_dispatcher.Dispatch + + +def bitcast_eager_fallback(input: Annotated[Any, TV_Bitcast_T], type: TV_Bitcast_type, name, ctx) -> Annotated[Any, TV_Bitcast_type]: + type = _execute.make_type(type, "type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int64, _dtypes.int32, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.int8, _dtypes.int16, _dtypes.complex64, _dtypes.complex128, _dtypes.qint8, _dtypes.quint8, _dtypes.qint16, _dtypes.quint16, _dtypes.qint32, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "type", type) + _result = _execute.execute(b"Bitcast", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Bitcast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BroadcastArgs_T = TypeVar("TV_BroadcastArgs_T", _atypes.Int32, _atypes.Int64) + +def broadcast_args(s0: Annotated[Any, TV_BroadcastArgs_T], s1: Annotated[Any, TV_BroadcastArgs_T], name=None) -> Annotated[Any, TV_BroadcastArgs_T]: + r"""Return the shape of s0 op s1 with broadcast. + + Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the + broadcasted shape. `s0`, `s1` and `r0` are all integer vectors. + + Args: + s0: A `Tensor`. Must be one of the following types: `int32`, `int64`. + s1: A `Tensor`. Must have the same type as `s0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `s0`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BroadcastArgs", name, s0, s1) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return broadcast_args_eager_fallback( + s0, s1, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BroadcastArgs", s0=s0, s1=s1, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BroadcastArgs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BroadcastArgs = tf_export("raw_ops.BroadcastArgs")(_ops.to_raw_op(broadcast_args)) + + +def broadcast_args_eager_fallback(s0: Annotated[Any, TV_BroadcastArgs_T], s1: Annotated[Any, TV_BroadcastArgs_T], name, ctx) -> Annotated[Any, TV_BroadcastArgs_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([s0, s1], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + (s0, s1) = _inputs_T + _inputs_flat = [s0, s1] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BroadcastArgs", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BroadcastArgs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_BroadcastGradientArgsOutput = collections.namedtuple( + "BroadcastGradientArgs", + ["r0", "r1"]) + + +TV_BroadcastGradientArgs_T = TypeVar("TV_BroadcastGradientArgs_T", _atypes.Int32, _atypes.Int64) + +def broadcast_gradient_args(s0: Annotated[Any, TV_BroadcastGradientArgs_T], s1: Annotated[Any, TV_BroadcastGradientArgs_T], name=None): + r"""Return the reduction indices for computing gradients of s0 op s1 with broadcast. + + This is typically used by gradient computations for a broadcasting operation. + + Args: + s0: A `Tensor`. Must be one of the following types: `int32`, `int64`. + s1: A `Tensor`. Must have the same type as `s0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (r0, r1). + + r0: A `Tensor`. Has the same type as `s0`. + r1: A `Tensor`. Has the same type as `s0`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BroadcastGradientArgs", name, s0, s1) + _result = _BroadcastGradientArgsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return broadcast_gradient_args_eager_fallback( + s0, s1, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BroadcastGradientArgs", s0=s0, s1=s1, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BroadcastGradientArgs", _inputs_flat, _attrs, _result) + _result = _BroadcastGradientArgsOutput._make(_result) + return _result + +BroadcastGradientArgs = tf_export("raw_ops.BroadcastGradientArgs")(_ops.to_raw_op(broadcast_gradient_args)) + + +def broadcast_gradient_args_eager_fallback(s0: Annotated[Any, TV_BroadcastGradientArgs_T], s1: Annotated[Any, TV_BroadcastGradientArgs_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([s0, s1], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + (s0, s1) = _inputs_T + _inputs_flat = [s0, s1] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BroadcastGradientArgs", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BroadcastGradientArgs", _inputs_flat, _attrs, _result) + _result = _BroadcastGradientArgsOutput._make(_result) + return _result + + +TV_BroadcastTo_T = TypeVar("TV_BroadcastTo_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_BroadcastTo_Tidx = TypeVar("TV_BroadcastTo_Tidx", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('broadcast_to') +def broadcast_to(input: Annotated[Any, TV_BroadcastTo_T], shape: Annotated[Any, TV_BroadcastTo_Tidx], name=None) -> Annotated[Any, TV_BroadcastTo_T]: + r"""Broadcast an array for a compatible shape. + + Broadcasting is the process of making arrays to have compatible shapes + for arithmetic operations. Two shapes are compatible if for each + dimension pair they are either equal or one of them is one. + + For example: + + >>> x = tf.constant([[1, 2, 3]]) # Shape (1, 3,) + >>> y = tf.broadcast_to(x, [2, 3]) + >>> print(y) + tf.Tensor( + [[1 2 3] + [1 2 3]], shape=(2, 3), dtype=int32) + + In the above example, the input Tensor with the shape of `[1, 3]` + is broadcasted to output Tensor with shape of `[2, 3]`. + + When broadcasting, if a tensor has fewer axes than necessary its shape is + padded on the left with ones. So this gives the same result as the previous + example: + + >>> x = tf.constant([1, 2, 3]) # Shape (3,) + >>> y = tf.broadcast_to(x, [2, 3]) + + + When doing broadcasted operations such as multiplying a tensor + by a scalar, broadcasting (usually) confers some time or space + benefit, as the broadcasted tensor is never materialized. + + However, `broadcast_to` does not carry with it any such benefits. + The newly-created tensor takes the full memory of the broadcasted + shape. (In a graph context, `broadcast_to` might be fused to + subsequent operation and then be optimized away, however.) + + Args: + input: A `Tensor`. A Tensor to broadcast. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + An 1-D `int` Tensor. The shape of the desired output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BroadcastTo", name, input, shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_broadcast_to( + (input, shape, name,), None) + if _result is not NotImplemented: + return _result + return broadcast_to_eager_fallback( + input, shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + broadcast_to, (), dict(input=input, shape=shape, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_broadcast_to( + (input, shape, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BroadcastTo", input=input, shape=shape, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + broadcast_to, (), dict(input=input, shape=shape, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BroadcastTo", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BroadcastTo = tf_export("raw_ops.BroadcastTo")(_ops.to_raw_op(broadcast_to)) +_dispatcher_for_broadcast_to = broadcast_to._tf_type_based_dispatcher.Dispatch + + +def broadcast_to_eager_fallback(input: Annotated[Any, TV_BroadcastTo_T], shape: Annotated[Any, TV_BroadcastTo_Tidx], name, ctx) -> Annotated[Any, TV_BroadcastTo_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tidx, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, shape] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"BroadcastTo", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BroadcastTo", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CheckNumerics_T = TypeVar("TV_CheckNumerics_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('debugging.check_numerics', v1=['debugging.check_numerics', 'check_numerics']) +@deprecated_endpoints('check_numerics') +def check_numerics(tensor: Annotated[Any, TV_CheckNumerics_T], message: str, name=None) -> Annotated[Any, TV_CheckNumerics_T]: + r"""Checks a tensor for NaN and Inf values. + + When run, reports an `InvalidArgument` error if `tensor` has any values + that are not a number (NaN) or infinity (Inf). Otherwise, returns the input + tensor. + + Example usage: + + ``` python + a = tf.Variable(1.0) + tf.debugging.check_numerics(a, message='') + + b = tf.Variable(np.nan) + try: + tf.debugging.check_numerics(b, message='Checking b') + except Exception as e: + assert "Checking b : Tensor had NaN values" in e.message + + c = tf.Variable(np.inf) + try: + tf.debugging.check_numerics(c, message='Checking c') + except Exception as e: + assert "Checking c : Tensor had Inf values" in e.message + ``` + + Args: + tensor: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + message: A `string`. Prefix of the error message. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CheckNumerics", name, tensor, "message", message) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_check_numerics( + (tensor, message, name,), None) + if _result is not NotImplemented: + return _result + return check_numerics_eager_fallback( + tensor, message=message, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + check_numerics, (), dict(tensor=tensor, message=message, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_check_numerics( + (tensor, message, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + message = _execute.make_str(message, "message") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CheckNumerics", tensor=tensor, message=message, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + check_numerics, (), dict(tensor=tensor, message=message, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "message", + _op.get_attr("message")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CheckNumerics", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CheckNumerics = tf_export("raw_ops.CheckNumerics")(_ops.to_raw_op(check_numerics)) +_dispatcher_for_check_numerics = check_numerics._tf_type_based_dispatcher.Dispatch + + +def check_numerics_eager_fallback(tensor: Annotated[Any, TV_CheckNumerics_T], message: str, name, ctx) -> Annotated[Any, TV_CheckNumerics_T]: + message = _execute.make_str(message, "message") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [tensor] + _attrs = ("T", _attr_T, "message", message) + _result = _execute.execute(b"CheckNumerics", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CheckNumerics", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CheckNumericsV2_T = TypeVar("TV_CheckNumericsV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def check_numerics_v2(tensor: Annotated[Any, TV_CheckNumericsV2_T], message: str, name=None) -> Annotated[Any, TV_CheckNumericsV2_T]: + r"""Checks a tensor for NaN, -Inf and +Inf values. + + When run, reports an `InvalidArgument` error if `tensor` has any values + that are not a number (NaN) or infinity (Inf). Otherwise, returns the input + tensor. Unlike CheckNumerics (V1), CheckNumericsV2 distinguishes -Inf and +Inf + in the errors it throws. + + Args: + tensor: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + message: A `string`. Prefix of the error message. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CheckNumericsV2", name, tensor, "message", message) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return check_numerics_v2_eager_fallback( + tensor, message=message, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + message = _execute.make_str(message, "message") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CheckNumericsV2", tensor=tensor, message=message, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "message", + _op.get_attr("message")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CheckNumericsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CheckNumericsV2 = tf_export("raw_ops.CheckNumericsV2")(_ops.to_raw_op(check_numerics_v2)) + + +def check_numerics_v2_eager_fallback(tensor: Annotated[Any, TV_CheckNumericsV2_T], message: str, name, ctx) -> Annotated[Any, TV_CheckNumericsV2_T]: + message = _execute.make_str(message, "message") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [tensor] + _attrs = ("T", _attr_T, "message", message) + _result = _execute.execute(b"CheckNumericsV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CheckNumericsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Concat_T = TypeVar("TV_Concat_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def concat(concat_dim: Annotated[Any, _atypes.Int32], values: Annotated[List[Any], TV_Concat_T], name=None) -> Annotated[Any, TV_Concat_T]: + r"""Concatenates tensors along one dimension. + + Args: + concat_dim: A `Tensor` of type `int32`. + 0-D. The dimension along which to concatenate. Must be in the + range [0, rank(values)). + values: A list of at least 2 `Tensor` objects with the same type. + The `N` Tensors to concatenate. Their ranks and types must match, + and their sizes must match in all dimensions except `concat_dim`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Concat", name, concat_dim, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return concat_eager_fallback( + concat_dim, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'concat' Op, not %r." % values) + _attr_N = len(values) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Concat", concat_dim=concat_dim, values=values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Concat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Concat = tf_export("raw_ops.Concat")(_ops.to_raw_op(concat)) + + +def concat_eager_fallback(concat_dim: Annotated[Any, _atypes.Int32], values: Annotated[List[Any], TV_Concat_T], name, ctx) -> Annotated[Any, TV_Concat_T]: + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'concat' Op, not %r." % values) + _attr_N = len(values) + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) + _inputs_flat = [concat_dim] + list(values) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"Concat", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Concat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ConcatOffset_shape_type = TypeVar("TV_ConcatOffset_shape_type", _atypes.Int32, _atypes.Int64) + +def concat_offset(concat_dim: Annotated[Any, _atypes.Int32], shape: Annotated[List[Any], TV_ConcatOffset_shape_type], name=None): + r"""Computes offsets of concat inputs within its output. + + For example: + + >>> x = [2, 2, 7] + >>> y = [2, 3, 7] + >>> z = [2, 9, 7] + >>> offsets = concat_offset(1, [x, y, z]) + >>> [list(off.numpy()) for off in offsets] + [[0, 0, 0], [0, 2, 0], [0, 5, 0]] + + This is typically used by gradient computations for a concat operation. + + Args: + concat_dim: A `Tensor` of type `int32`. + The dimension along which to concatenate. + shape: A list of at least 2 `Tensor` objects with the same type in: `int32`, `int64`. + The `N` int32 or int64 vectors representing shape of tensors being concatenated. + name: A name for the operation (optional). + + Returns: + A list with the same length as `shape` of `Tensor` objects with the same type as `shape`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConcatOffset", name, concat_dim, shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return concat_offset_eager_fallback( + concat_dim, shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(shape, (list, tuple)): + raise TypeError( + "Expected list for 'shape' argument to " + "'concat_offset' Op, not %r." % shape) + _attr_N = len(shape) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConcatOffset", concat_dim=concat_dim, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "shape_type", + _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConcatOffset", _inputs_flat, _attrs, _result) + return _result + +ConcatOffset = tf_export("raw_ops.ConcatOffset")(_ops.to_raw_op(concat_offset)) + + +def concat_offset_eager_fallback(concat_dim: Annotated[Any, _atypes.Int32], shape: Annotated[List[Any], TV_ConcatOffset_shape_type], name, ctx): + if not isinstance(shape, (list, tuple)): + raise TypeError( + "Expected list for 'shape' argument to " + "'concat_offset' Op, not %r." % shape) + _attr_N = len(shape) + _attr_shape_type, shape = _execute.args_to_matching_eager(list(shape), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) + _inputs_flat = [concat_dim] + list(shape) + _attrs = ("N", _attr_N, "shape_type", _attr_shape_type) + _result = _execute.execute(b"ConcatOffset", _attr_N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ConcatOffset", _inputs_flat, _attrs, _result) + return _result + + +TV_ConcatV2_T = TypeVar("TV_ConcatV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ConcatV2_Tidx = TypeVar("TV_ConcatV2_Tidx", _atypes.Int32, _atypes.Int64) + +def concat_v2(values: Annotated[List[Any], TV_ConcatV2_T], axis: Annotated[Any, TV_ConcatV2_Tidx], name=None) -> Annotated[Any, TV_ConcatV2_T]: + r"""Concatenates tensors along one dimension. + + Args: + values: A list of at least 2 `Tensor` objects with the same type. + List of `N` Tensors to concatenate. Their ranks and types must match, + and their sizes must match in all dimensions except `concat_dim`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D. The dimension along which to concatenate. Must be in the + range [-rank(values), rank(values)). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConcatV2", name, values, axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return concat_v2_eager_fallback( + values, axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'concat_v2' Op, not %r." % values) + _attr_N = len(values) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConcatV2", values=values, axis=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConcatV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ConcatV2 = tf_export("raw_ops.ConcatV2")(_ops.to_raw_op(concat_v2)) + + +def concat_v2_eager_fallback(values: Annotated[List[Any], TV_ConcatV2_T], axis: Annotated[Any, TV_ConcatV2_Tidx], name, ctx) -> Annotated[Any, TV_ConcatV2_T]: + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'concat_v2' Op, not %r." % values) + _attr_N = len(values) + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = list(values) + [axis] + _attrs = ("N", _attr_N, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"ConcatV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ConcatV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ConjugateTranspose_T = TypeVar("TV_ConjugateTranspose_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ConjugateTranspose_Tperm = TypeVar("TV_ConjugateTranspose_Tperm", _atypes.Int32, _atypes.Int64) + +def conjugate_transpose(x: Annotated[Any, TV_ConjugateTranspose_T], perm: Annotated[Any, TV_ConjugateTranspose_Tperm], name=None) -> Annotated[Any, TV_ConjugateTranspose_T]: + r"""Shuffle dimensions of x according to a permutation and conjugate the result. + + The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: + `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` + `y[i,j,k,...,s,t,u] == conj(x[perm[i], perm[j], perm[k],...,perm[s], perm[t], perm[u]])` + + Args: + x: A `Tensor`. + perm: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConjugateTranspose", name, x, perm) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conjugate_transpose_eager_fallback( + x, perm, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConjugateTranspose", x=x, perm=perm, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tperm", + _op._get_attr_type("Tperm")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConjugateTranspose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ConjugateTranspose = tf_export("raw_ops.ConjugateTranspose")(_ops.to_raw_op(conjugate_transpose)) + + +def conjugate_transpose_eager_fallback(x: Annotated[Any, TV_ConjugateTranspose_T], perm: Annotated[Any, TV_ConjugateTranspose_Tperm], name, ctx) -> Annotated[Any, TV_ConjugateTranspose_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _attr_Tperm, (perm,) = _execute.args_to_matching_eager([perm], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x, perm] + _attrs = ("T", _attr_T, "Tperm", _attr_Tperm) + _result = _execute.execute(b"ConjugateTranspose", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ConjugateTranspose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Const_dtype = TypeVar("TV_Const_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def const(value, dtype: TV_Const_dtype, name=None) -> Annotated[Any, TV_Const_dtype]: + r"""Returns a constant tensor. + + Args: + value: A `tf.TensorProto`. Attr `value` is the tensor to return. + dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Const", name, "value", value, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return const_eager_fallback( + value=value, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + value = _execute.make_tensor(value, "value") + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Const", value=value, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("value", _op.get_attr("value"), "dtype", + _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Const", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Const = tf_export("raw_ops.Const")(_ops.to_raw_op(const)) + + +def const_eager_fallback(value, dtype: TV_Const_dtype, name, ctx) -> Annotated[Any, TV_Const_dtype]: + value = _execute.make_tensor(value, "value") + dtype = _execute.make_type(dtype, "dtype") + _inputs_flat = [] + _attrs = ("value", value, "dtype", dtype) + _result = _execute.execute(b"Const", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Const", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugGradientIdentity_T = TypeVar("TV_DebugGradientIdentity_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_gradient_identity(input: Annotated[Any, TV_DebugGradientIdentity_T], name=None) -> Annotated[Any, TV_DebugGradientIdentity_T]: + r"""Identity op for gradient debugging. + + This op is hidden from public in Python. It is used by TensorFlow Debugger to + register gradient tensors for gradient debugging. + This op operates on non-reference-type tensors. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugGradientIdentity", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_gradient_identity_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugGradientIdentity", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugGradientIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugGradientIdentity = tf_export("raw_ops.DebugGradientIdentity")(_ops.to_raw_op(debug_gradient_identity)) + + +def debug_gradient_identity_eager_fallback(input: Annotated[Any, TV_DebugGradientIdentity_T], name, ctx) -> Annotated[Any, TV_DebugGradientIdentity_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DebugGradientIdentity", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugGradientIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugGradientRefIdentity_T = TypeVar("TV_DebugGradientRefIdentity_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_gradient_ref_identity(input: Annotated[Any, TV_DebugGradientRefIdentity_T], name=None) -> Annotated[Any, TV_DebugGradientRefIdentity_T]: + r"""Identity op for gradient debugging. + + This op is hidden from public in Python. It is used by TensorFlow Debugger to + register gradient tensors for gradient debugging. + This op operates on reference-type tensors. + + Args: + input: A mutable `Tensor`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("debug_gradient_ref_identity op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugGradientRefIdentity", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugGradientRefIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugGradientRefIdentity = tf_export("raw_ops.DebugGradientRefIdentity")(_ops.to_raw_op(debug_gradient_ref_identity)) + + +def debug_gradient_ref_identity_eager_fallback(input: Annotated[Any, TV_DebugGradientRefIdentity_T], name, ctx) -> Annotated[Any, TV_DebugGradientRefIdentity_T]: + raise RuntimeError("debug_gradient_ref_identity op does not support eager execution. Arg 'output' is a ref.") + +TV_DeepCopy_T = TypeVar("TV_DeepCopy_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def deep_copy(x: Annotated[Any, TV_DeepCopy_T], name=None) -> Annotated[Any, TV_DeepCopy_T]: + r"""Makes a copy of `x`. + + Args: + x: A `Tensor`. The source tensor of type `T`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeepCopy", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return deep_copy_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeepCopy", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DeepCopy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DeepCopy = tf_export("raw_ops.DeepCopy")(_ops.to_raw_op(deep_copy)) + + +def deep_copy_eager_fallback(x: Annotated[Any, TV_DeepCopy_T], name, ctx) -> Annotated[Any, TV_DeepCopy_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DeepCopy", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DeepCopy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DepthToSpace_T = TypeVar("TV_DepthToSpace_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def depth_to_space(input: Annotated[Any, TV_DepthToSpace_T], block_size: int, data_format:str="NHWC", name=None) -> Annotated[Any, TV_DepthToSpace_T]: + r"""DepthToSpace for tensors of type T. + + Rearranges data from depth into blocks of spatial data. + This is the reverse transformation of SpaceToDepth. More specifically, + this op outputs a copy of the input tensor where values from the `depth` + dimension are moved in spatial blocks to the `height` and `width` dimensions. + The attr `block_size` indicates the input block size and how the data is moved. + + * Chunks of data of size `block_size * block_size` from depth are rearranged + into non-overlapping blocks of size `block_size x block_size` + * The width of the output tensor is `input_depth * block_size`, whereas the + height is `input_height * block_size`. + * The Y, X coordinates within each block of the output image are determined + by the high order component of the input channel index. + * The depth of the input tensor must be divisible by + `block_size * block_size`. + + The `data_format` attr specifies the layout of the input and output tensors + with the following options: + "NHWC": `[ batch, height, width, channels ]` + "NCHW": `[ batch, channels, height, width ]` + "NCHW_VECT_C": + `qint8 [ batch, channels / 4, height, width, 4 ]` + + It is useful to consider the operation as transforming a 6-D Tensor. + e.g. for data_format = NHWC, + Each element in the input tensor can be specified via 6 coordinates, + ordered by decreasing memory layout significance as: + n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates + within the input image, bX, bY means coordinates + within the output block, oC means output channels). + The output would be the input transposed to the following layout: + n,iY,bY,iX,bX,oC + + This operation is useful for resizing the activations between convolutions + (but keeping all data), e.g. instead of pooling. It is also useful for training + purely convolutional models. + + For example, given an input of shape `[1, 1, 1, 4]`, data_format = "NHWC" and + block_size = 2: + + ``` + x = [[[[1, 2, 3, 4]]]] + + ``` + + This operation will output a tensor of shape `[1, 2, 2, 1]`: + + ``` + [[[[1], [2]], + [[3], [4]]]] + ``` + + Here, the input has a batch of 1 and each batch element has shape `[1, 1, 4]`, + the corresponding output will have 2x2 elements and will have a depth of + 1 channel (1 = `4 / (block_size * block_size)`). + The output element shape is `[2, 2, 1]`. + + For an input tensor with larger depth, here of shape `[1, 1, 1, 12]`, e.g. + + ``` + x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] + ``` + + This operation, for block size of 2, will return the following tensor of shape + `[1, 2, 2, 3]` + + ``` + [[[[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]]]] + + ``` + + Similarly, for the following input of shape `[1 2 2 4]`, and a block size of 2: + + ``` + x = [[[[1, 2, 3, 4], + [5, 6, 7, 8]], + [[9, 10, 11, 12], + [13, 14, 15, 16]]]] + ``` + + the operator will return the following tensor of shape `[1 4 4 1]`: + + ``` + x = [[[ [1], [2], [5], [6]], + [ [3], [4], [7], [8]], + [ [9], [10], [13], [14]], + [ [11], [12], [15], [16]]]] + + ``` + + Args: + input: A `Tensor`. + block_size: An `int` that is `>= 2`. + The size of the spatial block, same as in Space2Depth. + data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DepthToSpace", name, input, "block_size", block_size, + "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return depth_to_space_eager_fallback( + input, block_size=block_size, data_format=data_format, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + block_size = _execute.make_int(block_size, "block_size") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DepthToSpace", input=input, block_size=block_size, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "block_size", + _op._get_attr_int("block_size"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DepthToSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DepthToSpace = tf_export("raw_ops.DepthToSpace")(_ops.to_raw_op(depth_to_space)) + + +def depth_to_space_eager_fallback(input: Annotated[Any, TV_DepthToSpace_T], block_size: int, data_format: str, name, ctx) -> Annotated[Any, TV_DepthToSpace_T]: + block_size = _execute.make_int(block_size, "block_size") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "block_size", block_size, "data_format", + data_format) + _result = _execute.execute(b"DepthToSpace", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DepthToSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Dequantize_T = TypeVar("TV_Dequantize_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_Dequantize_dtype = TypeVar("TV_Dequantize_dtype", _atypes.BFloat16, _atypes.Float32) + +def dequantize(input: Annotated[Any, TV_Dequantize_T], min_range: Annotated[Any, _atypes.Float32], max_range: Annotated[Any, _atypes.Float32], mode:str="MIN_COMBINED", narrow_range:bool=False, axis:int=-1, dtype:TV_Dequantize_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_Dequantize_dtype]: + r"""Dequantize the 'input' tensor into a float or bfloat16 Tensor. + + [min_range, max_range] are scalar floats that specify the range for + the output. The 'mode' attribute controls exactly which calculations are + used to convert the float values to their quantized equivalents. + + In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: + + ``` + if T == qint8: in[i] += (range(T) + 1)/ 2.0 + out[i] = min_range + (in[i]* (max_range - min_range) / range(T)) + ``` + here `range(T) = numeric_limits::max() - numeric_limits::min()` + + *MIN_COMBINED Mode Example* + + If the input comes from a QuantizedRelu6, the output type is + quint8 (range of 0-255) but the possible range of QuantizedRelu6 is + 0-6. The min_range and max_range values are therefore 0.0 and 6.0. + Dequantize on quint8 will take each value, cast to float, and multiply + by 6 / 255. + Note that if quantizedtype is qint8, the operation will additionally add + each value by 128 prior to casting. + + If the mode is 'MIN_FIRST', then this approach is used: + + ```c++ + num_discrete_values = 1 << (# of bits in T) + range_adjust = num_discrete_values / (num_discrete_values - 1) + range = (range_max - range_min) * range_adjust + range_scale = range / num_discrete_values + const double offset_input = static_cast(input) - lowest_quantized; + result = range_min + ((input - numeric_limits::min()) * range_scale) + ``` + + If the mode is `SCALED`, dequantization is performed by multiplying each + input value by a scaling_factor. (Thus an input of 0 always maps to 0.0). + + The scaling_factor is determined from `min_range`, `max_range`, and + `narrow_range` in a way that is compatible with `QuantizeAndDequantize{V2|V3}` + and `QuantizeV2`, using the following algorithm: + + ```c++ + + const int min_expected_T = std::numeric_limits::min() + + (narrow_range ? 1 : 0); + const int max_expected_T = std::numeric_limits::max(); + const float max_expected_T = std::numeric_limits::max(); + + const float scale_factor = + (std::numeric_limits::min() == 0) ? (max_range / max_expected_T) + : std::max(min_range / min_expected_T, + max_range / max_expected_T); + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_range: A `Tensor` of type `float32`. + The minimum scalar value possibly produced for the input. + max_range: A `Tensor` of type `float32`. + The maximum scalar value possibly produced for the input. + mode: An optional `string` from: `"MIN_COMBINED", "MIN_FIRST", "SCALED"`. Defaults to `"MIN_COMBINED"`. + narrow_range: An optional `bool`. Defaults to `False`. + axis: An optional `int`. Defaults to `-1`. + dtype: An optional `tf.DType` from: `tf.bfloat16, tf.float32`. Defaults to `tf.float32`. + Type of the output tensor. Currently Dequantize supports float and bfloat16. + If 'dtype' is 'bfloat16', it only supports 'MIN_COMBINED' mode. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Dequantize", name, input, min_range, max_range, "mode", mode, + "narrow_range", narrow_range, "axis", axis, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dequantize_eager_fallback( + input, min_range, max_range, mode=mode, narrow_range=narrow_range, + axis=axis, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if mode is None: + mode = "MIN_COMBINED" + mode = _execute.make_str(mode, "mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Dequantize", input=input, min_range=min_range, max_range=max_range, + mode=mode, narrow_range=narrow_range, axis=axis, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "mode", _op.get_attr("mode"), + "narrow_range", _op._get_attr_bool("narrow_range"), "axis", + _op._get_attr_int("axis"), "dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Dequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Dequantize = tf_export("raw_ops.Dequantize")(_ops.to_raw_op(dequantize)) + + +def dequantize_eager_fallback(input: Annotated[Any, TV_Dequantize_T], min_range: Annotated[Any, _atypes.Float32], max_range: Annotated[Any, _atypes.Float32], mode: str, narrow_range: bool, axis: int, dtype: TV_Dequantize_dtype, name, ctx) -> Annotated[Any, TV_Dequantize_dtype]: + if mode is None: + mode = "MIN_COMBINED" + mode = _execute.make_str(mode, "mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_range = _ops.convert_to_tensor(min_range, _dtypes.float32) + max_range = _ops.convert_to_tensor(max_range, _dtypes.float32) + _inputs_flat = [input, min_range, max_range] + _attrs = ("T", _attr_T, "mode", mode, "narrow_range", narrow_range, "axis", + axis, "dtype", dtype) + _result = _execute.execute(b"Dequantize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Dequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Diag_T = TypeVar("TV_Diag_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.tensor_diag', v1=['linalg.tensor_diag', 'diag']) +@deprecated_endpoints('diag') +def diag(diagonal: Annotated[Any, TV_Diag_T], name=None) -> Annotated[Any, TV_Diag_T]: + r"""Returns a diagonal tensor with a given diagonal values. + + Given a `diagonal`, this operation returns a tensor with the `diagonal` and + everything else padded with zeros. The diagonal is computed as follows: + + Assume `diagonal` has dimensions [D1,..., Dk], then the output is a tensor of + rank 2k with dimensions [D1,..., Dk, D1,..., Dk] where: + + `output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]` and 0 everywhere else. + + For example: + + ``` + # 'diagonal' is [1, 2, 3, 4] + tf.diag(diagonal) ==> [[1, 0, 0, 0] + [0, 2, 0, 0] + [0, 0, 3, 0] + [0, 0, 0, 4]] + ``` + + Args: + diagonal: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. + Rank k tensor where k is at most 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Diag", name, diagonal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_diag( + (diagonal, name,), None) + if _result is not NotImplemented: + return _result + return diag_eager_fallback( + diagonal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + diag, (), dict(diagonal=diagonal, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_diag( + (diagonal, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Diag", diagonal=diagonal, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + diag, (), dict(diagonal=diagonal, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Diag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Diag = tf_export("raw_ops.Diag")(_ops.to_raw_op(diag)) +_dispatcher_for_diag = diag._tf_type_based_dispatcher.Dispatch + + +def diag_eager_fallback(diagonal: Annotated[Any, TV_Diag_T], name, ctx) -> Annotated[Any, TV_Diag_T]: + _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [diagonal] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Diag", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Diag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DiagPart_T = TypeVar("TV_DiagPart_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def diag_part(input: Annotated[Any, TV_DiagPart_T], name=None) -> Annotated[Any, TV_DiagPart_T]: + r"""Returns the diagonal part of the tensor. + + This operation returns a tensor with the `diagonal` part + of the `input`. The `diagonal` part is computed as follows: + + Assume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a + tensor of rank `k` with dimensions `[D1,..., Dk]` where: + + `diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`. + + For example: + + ``` + # 'input' is [[1, 0, 0, 0] + [0, 2, 0, 0] + [0, 0, 3, 0] + [0, 0, 0, 4]] + + tf.diag_part(input) ==> [1, 2, 3, 4] + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. + Rank k tensor where k is even and not zero. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DiagPart", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return diag_part_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DiagPart", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DiagPart = tf_export("raw_ops.DiagPart")(_ops.to_raw_op(diag_part)) + + +def diag_part_eager_fallback(input: Annotated[Any, TV_DiagPart_T], name, ctx) -> Annotated[Any, TV_DiagPart_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DiagPart", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_EditDistance_T = TypeVar("TV_EditDistance_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def edit_distance(hypothesis_indices: Annotated[Any, _atypes.Int64], hypothesis_values: Annotated[Any, TV_EditDistance_T], hypothesis_shape: Annotated[Any, _atypes.Int64], truth_indices: Annotated[Any, _atypes.Int64], truth_values: Annotated[Any, TV_EditDistance_T], truth_shape: Annotated[Any, _atypes.Int64], normalize:bool=True, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Computes the (possibly normalized) Levenshtein Edit Distance. + + The inputs are variable-length sequences provided by SparseTensors + (hypothesis_indices, hypothesis_values, hypothesis_shape) + and + (truth_indices, truth_values, truth_shape). + + The inputs are: + + Args: + hypothesis_indices: A `Tensor` of type `int64`. + The indices of the hypothesis list SparseTensor. + This is an N x R int64 matrix. + hypothesis_values: A `Tensor`. + The values of the hypothesis list SparseTensor. + This is an N-length vector. + hypothesis_shape: A `Tensor` of type `int64`. + The shape of the hypothesis list SparseTensor. + This is an R-length vector. + truth_indices: A `Tensor` of type `int64`. + The indices of the truth list SparseTensor. + This is an M x R int64 matrix. + truth_values: A `Tensor`. Must have the same type as `hypothesis_values`. + The values of the truth list SparseTensor. + This is an M-length vector. + truth_shape: A `Tensor` of type `int64`. truth indices, vector. + normalize: An optional `bool`. Defaults to `True`. + boolean (if true, edit distances are normalized by length of truth). + + The output is: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EditDistance", name, hypothesis_indices, hypothesis_values, + hypothesis_shape, truth_indices, truth_values, truth_shape, + "normalize", normalize) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return edit_distance_eager_fallback( + hypothesis_indices, hypothesis_values, hypothesis_shape, + truth_indices, truth_values, truth_shape, normalize=normalize, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if normalize is None: + normalize = True + normalize = _execute.make_bool(normalize, "normalize") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EditDistance", hypothesis_indices=hypothesis_indices, + hypothesis_values=hypothesis_values, + hypothesis_shape=hypothesis_shape, + truth_indices=truth_indices, + truth_values=truth_values, truth_shape=truth_shape, + normalize=normalize, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("normalize", _op._get_attr_bool("normalize"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EditDistance", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EditDistance = tf_export("raw_ops.EditDistance")(_ops.to_raw_op(edit_distance)) + + +def edit_distance_eager_fallback(hypothesis_indices: Annotated[Any, _atypes.Int64], hypothesis_values: Annotated[Any, TV_EditDistance_T], hypothesis_shape: Annotated[Any, _atypes.Int64], truth_indices: Annotated[Any, _atypes.Int64], truth_values: Annotated[Any, TV_EditDistance_T], truth_shape: Annotated[Any, _atypes.Int64], normalize: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if normalize is None: + normalize = True + normalize = _execute.make_bool(normalize, "normalize") + _attr_T, _inputs_T = _execute.args_to_matching_eager([hypothesis_values, truth_values], ctx, []) + (hypothesis_values, truth_values) = _inputs_T + hypothesis_indices = _ops.convert_to_tensor(hypothesis_indices, _dtypes.int64) + hypothesis_shape = _ops.convert_to_tensor(hypothesis_shape, _dtypes.int64) + truth_indices = _ops.convert_to_tensor(truth_indices, _dtypes.int64) + truth_shape = _ops.convert_to_tensor(truth_shape, _dtypes.int64) + _inputs_flat = [hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape] + _attrs = ("normalize", normalize, "T", _attr_T) + _result = _execute.execute(b"EditDistance", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EditDistance", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Empty_dtype = TypeVar("TV_Empty_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def empty(shape: Annotated[Any, _atypes.Int32], dtype: TV_Empty_dtype, init:bool=False, name=None) -> Annotated[Any, TV_Empty_dtype]: + r"""Creates a tensor with the given shape. + +This operation creates a tensor of `shape` and `dtype`. + + Args: + shape: A `Tensor` of type `int32`. + 1-D. Represents the shape of the output tensor. + dtype: A `tf.DType`. + init: An optional `bool`. Defaults to `False`. + If True, initialize the returned tensor with the default value of dtype. Otherwise, the implementation is free not to initializethe tensor's content. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Empty", name, shape, "dtype", dtype, "init", init) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return empty_eager_fallback( + shape, dtype=dtype, init=init, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if init is None: + init = False + init = _execute.make_bool(init, "init") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Empty", shape=shape, dtype=dtype, init=init, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "init", + _op._get_attr_bool("init")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Empty", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Empty = tf_export("raw_ops.Empty")(_ops.to_raw_op(empty)) + + +def empty_eager_fallback(shape: Annotated[Any, _atypes.Int32], dtype: TV_Empty_dtype, init: bool, name, ctx) -> Annotated[Any, TV_Empty_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if init is None: + init = False + init = _execute.make_bool(init, "init") + shape = _ops.convert_to_tensor(shape, _dtypes.int32) + _inputs_flat = [shape] + _attrs = ("dtype", dtype, "init", init) + _result = _execute.execute(b"Empty", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Empty", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_EnsureShape_T = TypeVar("TV_EnsureShape_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ensure_shape(input: Annotated[Any, TV_EnsureShape_T], shape, name=None) -> Annotated[Any, TV_EnsureShape_T]: + r"""Ensures that the tensor's shape matches the expected shape. + + Raises an error if the input tensor's shape does not match the specified shape. + Returns the input tensor otherwise. + + Args: + input: A `Tensor`. A tensor, whose shape is to be validated. + shape: A `tf.TensorShape` or list of `ints`. + The expected (possibly partially specified) shape of the input tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnsureShape", name, input, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ensure_shape_eager_fallback( + input, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnsureShape", input=input, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shape", _op.get_attr("shape"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EnsureShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EnsureShape = tf_export("raw_ops.EnsureShape")(_ops.to_raw_op(ensure_shape)) + + +def ensure_shape_eager_fallback(input: Annotated[Any, TV_EnsureShape_T], shape, name, ctx) -> Annotated[Any, TV_EnsureShape_T]: + shape = _execute.make_shape(shape, "shape") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("shape", shape, "T", _attr_T) + _result = _execute.execute(b"EnsureShape", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EnsureShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ExpandDims_T = TypeVar("TV_ExpandDims_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ExpandDims_Tdim = TypeVar("TV_ExpandDims_Tdim", _atypes.Int32, _atypes.Int64) + +def expand_dims(input: Annotated[Any, TV_ExpandDims_T], axis: Annotated[Any, TV_ExpandDims_Tdim], name=None) -> Annotated[Any, TV_ExpandDims_T]: + r"""Inserts a dimension of 1 into a tensor's shape. + + Given a tensor `input`, this operation inserts a dimension of 1 at the + dimension index `axis` of `input`'s shape. The dimension index `axis` starts at + zero; if you specify a negative number for `axis` it is counted backward from + the end. + + This operation is useful if you want to add a batch dimension to a single + element. For example, if you have a single image of shape `[height, width, + channels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`, + which will make the shape `[1, height, width, channels]`. + + Other examples: + + ``` + # 't' is a tensor of shape [2] + shape(expand_dims(t, 0)) ==> [1, 2] + shape(expand_dims(t, 1)) ==> [2, 1] + shape(expand_dims(t, -1)) ==> [2, 1] + + # 't2' is a tensor of shape [2, 3, 5] + shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5] + shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5] + shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1] + ``` + + This operation requires that: + + `-1-input.dims() <= dim <= input.dims()` + + This operation is related to `squeeze()`, which removes dimensions of + size 1. + + Args: + input: A `Tensor`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D (scalar). Specifies the dimension index at which to + expand the shape of `input`. Must be in the range + `[-rank(input) - 1, rank(input)]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExpandDims", name, input, axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return expand_dims_eager_fallback( + input, axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExpandDims", input=input, dim=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tdim", + _op._get_attr_type("Tdim")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExpandDims", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExpandDims = tf_export("raw_ops.ExpandDims")(_ops.to_raw_op(expand_dims)) + + +def expand_dims_eager_fallback(input: Annotated[Any, TV_ExpandDims_T], axis: Annotated[Any, TV_ExpandDims_Tdim], name, ctx) -> Annotated[Any, TV_ExpandDims_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tdim, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("T", _attr_T, "Tdim", _attr_Tdim) + _result = _execute.execute(b"ExpandDims", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExpandDims", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ExtractImagePatches_T = TypeVar("TV_ExtractImagePatches_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def extract_image_patches(images: Annotated[Any, TV_ExtractImagePatches_T], ksizes, strides, rates, padding: str, name=None) -> Annotated[Any, TV_ExtractImagePatches_T]: + r"""Extract `patches` from `images` and put them in the "depth" output dimension. + + Args: + images: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`, `bool`. + 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. + ksizes: A list of `ints` that has length `>= 4`. + The size of the sliding window for each dimension of `images`. + strides: A list of `ints` that has length `>= 4`. + How far the centers of two consecutive patches are in + the images. Must be: `[1, stride_rows, stride_cols, 1]`. + rates: A list of `ints` that has length `>= 4`. + Must be: `[1, rate_rows, rate_cols, 1]`. This is the + input stride, specifying how far two consecutive patch samples are in the + input. Equivalent to extracting patches with + `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by + subsampling them spatially by a factor of `rates`. This is equivalent to + `rate` in dilated (a.k.a. Atrous) convolutions. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExtractImagePatches", name, images, "ksizes", ksizes, + "strides", strides, "rates", rates, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return extract_image_patches_eager_fallback( + images, ksizes=ksizes, strides=strides, rates=rates, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksizes, (list, tuple)): + raise TypeError( + "Expected list for 'ksizes' argument to " + "'extract_image_patches' Op, not %r." % ksizes) + ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'extract_image_patches' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'extract_image_patches' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExtractImagePatches", images=images, ksizes=ksizes, strides=strides, + rates=rates, padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksizes", _op.get_attr("ksizes"), "strides", + _op.get_attr("strides"), "rates", _op.get_attr("rates"), "T", + _op._get_attr_type("T"), "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExtractImagePatches", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExtractImagePatches = tf_export("raw_ops.ExtractImagePatches")(_ops.to_raw_op(extract_image_patches)) + + +def extract_image_patches_eager_fallback(images: Annotated[Any, TV_ExtractImagePatches_T], ksizes, strides, rates, padding: str, name, ctx) -> Annotated[Any, TV_ExtractImagePatches_T]: + if not isinstance(ksizes, (list, tuple)): + raise TypeError( + "Expected list for 'ksizes' argument to " + "'extract_image_patches' Op, not %r." % ksizes) + ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'extract_image_patches' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'extract_image_patches' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, _dtypes.bool, ]) + _inputs_flat = [images] + _attrs = ("ksizes", ksizes, "strides", strides, "rates", rates, "T", + _attr_T, "padding", padding) + _result = _execute.execute(b"ExtractImagePatches", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExtractImagePatches", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ExtractVolumePatches_T = TypeVar("TV_ExtractVolumePatches_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('extract_volume_patches') +def extract_volume_patches(input: Annotated[Any, TV_ExtractVolumePatches_T], ksizes, strides, padding: str, name=None) -> Annotated[Any, TV_ExtractVolumePatches_T]: + r"""Extract `patches` from `input` and put them in the `"depth"` output dimension. 3D extension of `extract_image_patches`. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`. + ksizes: A list of `ints` that has length `>= 5`. + The size of the sliding window for each dimension of `input`. + strides: A list of `ints` that has length `>= 5`. + 1-D of length 5. How far the centers of two consecutive patches are in + `input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + + The size-related attributes are specified as follows: + + ```python + ksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1] + strides = [1, stride_planes, strides_rows, strides_cols, 1] + ``` + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExtractVolumePatches", name, input, "ksizes", ksizes, + "strides", strides, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_extract_volume_patches( + (input, ksizes, strides, padding, name,), None) + if _result is not NotImplemented: + return _result + return extract_volume_patches_eager_fallback( + input, ksizes=ksizes, strides=strides, padding=padding, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + extract_volume_patches, (), dict(input=input, ksizes=ksizes, + strides=strides, padding=padding, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_extract_volume_patches( + (input, ksizes, strides, padding, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(ksizes, (list, tuple)): + raise TypeError( + "Expected list for 'ksizes' argument to " + "'extract_volume_patches' Op, not %r." % ksizes) + ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'extract_volume_patches' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExtractVolumePatches", input=input, ksizes=ksizes, strides=strides, + padding=padding, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + extract_volume_patches, (), dict(input=input, ksizes=ksizes, + strides=strides, padding=padding, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksizes", _op.get_attr("ksizes"), "strides", + _op.get_attr("strides"), "T", _op._get_attr_type("T"), + "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExtractVolumePatches", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExtractVolumePatches = tf_export("raw_ops.ExtractVolumePatches")(_ops.to_raw_op(extract_volume_patches)) +_dispatcher_for_extract_volume_patches = extract_volume_patches._tf_type_based_dispatcher.Dispatch + + +def extract_volume_patches_eager_fallback(input: Annotated[Any, TV_ExtractVolumePatches_T], ksizes, strides, padding: str, name, ctx) -> Annotated[Any, TV_ExtractVolumePatches_T]: + if not isinstance(ksizes, (list, tuple)): + raise TypeError( + "Expected list for 'ksizes' argument to " + "'extract_volume_patches' Op, not %r." % ksizes) + ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'extract_volume_patches' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [input] + _attrs = ("ksizes", ksizes, "strides", strides, "T", _attr_T, "padding", + padding) + _result = _execute.execute(b"ExtractVolumePatches", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExtractVolumePatches", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_args', v1=['quantization.fake_quant_with_min_max_args', 'fake_quant_with_min_max_args']) +@deprecated_endpoints('fake_quant_with_min_max_args') +def fake_quant_with_min_max_args(inputs: Annotated[Any, _atypes.Float32], min:float=-6, max:float=6, num_bits:int=8, narrow_range:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same shape and type. + + + Quantization is called fake since the output is still in floating point. + The API converts inputs into values within the range [min and max] and returns + as output. + + Attributes + + * `[min; max]` define the clamping range for the `inputs` data. + * `inputs` values are quantized into the quantization range ( + `[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` + when it is true) and then de-quantized and output as floats in `[min; max]` + interval. + * `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. + + Before quantization, `min` and `max` values are adjusted with the following + logic. + It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, + the behavior can be unexpected: + + * If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. + * If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. + * If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, + `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. + + + Examples + + ```python + + inp = tf.constant ([10.03, -10.23, 3]) + out = tf.quantization.fake_quant_with_min_max_args(inp, min=-5, max=5, + num_bits=16) + print(out) + + # Output: + # tf.Tensor([ 4.9999237 -5.0000763 3.0000763], shape=(3,), dtype=float32) + ``` + + Raises: + * InvalidArgumentError: + - If num_bits are outside of range [2, 16]. + - If min >= max. + * ValueError: If `inputs` are of any other type than float32. + + Args: + inputs: A `Tensor` of type `float32`. + min: An optional `float`. Defaults to `-6`. + max: An optional `float`. Defaults to `6`. + num_bits: An optional `int`. Defaults to `8`. + narrow_range: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxArgs", name, inputs, "min", min, "max", max, + "num_bits", num_bits, "narrow_range", narrow_range) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_args( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_args_eager_fallback( + inputs, min=min, max=max, num_bits=num_bits, + narrow_range=narrow_range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_args, (), dict(inputs=inputs, min=min, + max=max, num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_args( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if min is None: + min = -6 + min = _execute.make_float(min, "min") + if max is None: + max = 6 + max = _execute.make_float(max, "max") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxArgs", inputs=inputs, min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_args, (), dict(inputs=inputs, min=min, + max=max, num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("min", _op.get_attr("min"), "max", _op.get_attr("max"), + "num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxArgs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeQuantWithMinMaxArgs = tf_export("raw_ops.FakeQuantWithMinMaxArgs")(_ops.to_raw_op(fake_quant_with_min_max_args)) +_dispatcher_for_fake_quant_with_min_max_args = fake_quant_with_min_max_args._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_args_eager_fallback(inputs: Annotated[Any, _atypes.Float32], min: float, max: float, num_bits: int, narrow_range: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if min is None: + min = -6 + min = _execute.make_float(min, "min") + if max is None: + max = 6 + max = _execute.make_float(max, "max") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + _inputs_flat = [inputs] + _attrs = ("min", min, "max", max, "num_bits", num_bits, "narrow_range", + narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxArgs", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxArgs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_args_gradient', v1=['quantization.fake_quant_with_min_max_args_gradient', 'fake_quant_with_min_max_args_gradient']) +@deprecated_endpoints('fake_quant_with_min_max_args_gradient') +def fake_quant_with_min_max_args_gradient(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min:float=-6, max:float=6, num_bits:int=8, narrow_range:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Compute gradients for a FakeQuantWithMinMaxArgs operation. + + Args: + gradients: A `Tensor` of type `float32`. + Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. + inputs: A `Tensor` of type `float32`. + Values passed as inputs to the FakeQuantWithMinMaxArgs operation. + min: An optional `float`. Defaults to `-6`. + max: An optional `float`. Defaults to `6`. + num_bits: An optional `int`. Defaults to `8`. + narrow_range: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxArgsGradient", name, gradients, inputs, + "min", min, "max", max, "num_bits", num_bits, "narrow_range", + narrow_range) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_args_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_args_gradient_eager_fallback( + gradients, inputs, min=min, max=max, num_bits=num_bits, + narrow_range=narrow_range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_args_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_args_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if min is None: + min = -6 + min = _execute.make_float(min, "min") + if max is None: + max = 6 + max = _execute.make_float(max, "max") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxArgsGradient", gradients=gradients, inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_args_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("min", _op.get_attr("min"), "max", _op.get_attr("max"), + "num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxArgsGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeQuantWithMinMaxArgsGradient = tf_export("raw_ops.FakeQuantWithMinMaxArgsGradient")(_ops.to_raw_op(fake_quant_with_min_max_args_gradient)) +_dispatcher_for_fake_quant_with_min_max_args_gradient = fake_quant_with_min_max_args_gradient._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_args_gradient_eager_fallback(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min: float, max: float, num_bits: int, narrow_range: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if min is None: + min = -6 + min = _execute.make_float(min, "min") + if max is None: + max = 6 + max = _execute.make_float(max, "max") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + _inputs_flat = [gradients, inputs] + _attrs = ("min", min, "max", max, "num_bits", num_bits, "narrow_range", + narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxArgsGradient", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxArgsGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_vars', v1=['quantization.fake_quant_with_min_max_vars', 'fake_quant_with_min_max_vars']) +@deprecated_endpoints('fake_quant_with_min_max_vars') +def fake_quant_with_min_max_vars(inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits:int=8, narrow_range:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Fake-quantize the 'inputs' tensor of type float via global float scalars + + Fake-quantize the `inputs` tensor of type float via global float scalars + `min` and `max` to `outputs` tensor of same shape as `inputs`. + + Attributes + + * `[min; max]` define the clamping range for the `inputs` data. + * `inputs` values are quantized into the quantization range ( + `[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` + when it is true) and then de-quantized and output as floats in `[min; max]` + interval. + * `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. + + Before quantization, `min` and `max` values are adjusted with the following + logic. + It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, + the behavior can be unexpected: + + * If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. + * If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. + * If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, + `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. + + This operation has a gradient and thus allows for training `min` and `max` + values. + + Args: + inputs: A `Tensor` of type `float32`. + min: A `Tensor` of type `float32`. + max: A `Tensor` of type `float32`. + num_bits: An optional `int`. Defaults to `8`. + narrow_range: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxVars", name, inputs, min, max, "num_bits", + num_bits, "narrow_range", narrow_range) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_vars( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_vars_eager_fallback( + inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars, (), dict(inputs=inputs, min=min, + max=max, num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_vars( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxVars", inputs=inputs, min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars, (), dict(inputs=inputs, min=min, + max=max, num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxVars", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeQuantWithMinMaxVars = tf_export("raw_ops.FakeQuantWithMinMaxVars")(_ops.to_raw_op(fake_quant_with_min_max_vars)) +_dispatcher_for_fake_quant_with_min_max_vars = fake_quant_with_min_max_vars._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_vars_eager_fallback(inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits: int, narrow_range: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + min = _ops.convert_to_tensor(min, _dtypes.float32) + max = _ops.convert_to_tensor(max, _dtypes.float32) + _inputs_flat = [inputs, min, max] + _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxVars", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxVars", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FakeQuantWithMinMaxVarsGradientOutput = collections.namedtuple( + "FakeQuantWithMinMaxVarsGradient", + ["backprops_wrt_input", "backprop_wrt_min", "backprop_wrt_max"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_vars_gradient', v1=['quantization.fake_quant_with_min_max_vars_gradient', 'fake_quant_with_min_max_vars_gradient']) +@deprecated_endpoints('fake_quant_with_min_max_vars_gradient') +def fake_quant_with_min_max_vars_gradient(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits:int=8, narrow_range:bool=False, name=None): + r"""Compute gradients for a FakeQuantWithMinMaxVars operation. + + Args: + gradients: A `Tensor` of type `float32`. + Backpropagated gradients above the FakeQuantWithMinMaxVars operation. + inputs: A `Tensor` of type `float32`. + Values passed as inputs to the FakeQuantWithMinMaxVars operation. + min, max: Quantization interval, scalar floats. + min: A `Tensor` of type `float32`. + max: A `Tensor` of type `float32`. + num_bits: An optional `int`. Defaults to `8`. + The bitwidth of the quantization; between 2 and 8, inclusive. + narrow_range: An optional `bool`. Defaults to `False`. + Whether to quantize into 2^num_bits - 1 distinct values. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). + + backprops_wrt_input: A `Tensor` of type `float32`. + backprop_wrt_min: A `Tensor` of type `float32`. + backprop_wrt_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxVarsGradient", name, gradients, inputs, min, + max, "num_bits", num_bits, "narrow_range", narrow_range) + _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_vars_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_vars_gradient_eager_fallback( + gradients, inputs, min, max, num_bits=num_bits, + narrow_range=narrow_range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_vars_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxVarsGradient", gradients=gradients, inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxVarsGradient", _inputs_flat, _attrs, _result) + _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) + return _result + +FakeQuantWithMinMaxVarsGradient = tf_export("raw_ops.FakeQuantWithMinMaxVarsGradient")(_ops.to_raw_op(fake_quant_with_min_max_vars_gradient)) +_dispatcher_for_fake_quant_with_min_max_vars_gradient = fake_quant_with_min_max_vars_gradient._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_vars_gradient_eager_fallback(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits: int, narrow_range: bool, name, ctx): + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + min = _ops.convert_to_tensor(min, _dtypes.float32) + max = _ops.convert_to_tensor(max, _dtypes.float32) + _inputs_flat = [gradients, inputs, min, max] + _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxVarsGradient", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxVarsGradient", _inputs_flat, _attrs, _result) + _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_vars_per_channel', v1=['quantization.fake_quant_with_min_max_vars_per_channel', 'fake_quant_with_min_max_vars_per_channel']) +@deprecated_endpoints('fake_quant_with_min_max_vars_per_channel') +def fake_quant_with_min_max_vars_per_channel(inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits:int=8, narrow_range:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Fake-quantize the 'inputs' tensor of type float via per-channel floats + + Fake-quantize the `inputs` tensor of type float per-channel and one of the + shapes: `[d]`, `[b, d]` `[b, h, w, d]` via per-channel floats `min` and `max` + of shape `[d]` to `outputs` tensor of same shape as `inputs`. + + Attributes + + * `[min; max]` define the clamping range for the `inputs` data. + * `inputs` values are quantized into the quantization range ( + `[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` + when it is true) and then de-quantized and output as floats in `[min; max]` + interval. + * `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. + + Before quantization, `min` and `max` values are adjusted with the following + logic. + It is suggested to have `min <= 0 <= max`. If `0` is not in the range of values, + the behavior can be unexpected: + + * If `0 < min < max`: `min_adj = 0` and `max_adj = max - min`. + * If `min < max < 0`: `min_adj = min - max` and `max_adj = 0`. + * If `min <= 0 <= max`: `scale = (max - min) / (2^num_bits - 1) `, + `min_adj = scale * round(min / scale)` and `max_adj = max + min_adj - min`. + + This operation has a gradient and thus allows for training `min` and `max` + values. + + Args: + inputs: A `Tensor` of type `float32`. + min: A `Tensor` of type `float32`. + max: A `Tensor` of type `float32`. + num_bits: An optional `int`. Defaults to `8`. + narrow_range: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxVarsPerChannel", name, inputs, min, max, + "num_bits", num_bits, "narrow_range", narrow_range) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_vars_per_channel( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_vars_per_channel_eager_fallback( + inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_per_channel, (), dict(inputs=inputs, + min=min, + max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_vars_per_channel( + (inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxVarsPerChannel", inputs=inputs, min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_per_channel, (), dict(inputs=inputs, + min=min, max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxVarsPerChannel", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeQuantWithMinMaxVarsPerChannel = tf_export("raw_ops.FakeQuantWithMinMaxVarsPerChannel")(_ops.to_raw_op(fake_quant_with_min_max_vars_per_channel)) +_dispatcher_for_fake_quant_with_min_max_vars_per_channel = fake_quant_with_min_max_vars_per_channel._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_vars_per_channel_eager_fallback(inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits: int, narrow_range: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + min = _ops.convert_to_tensor(min, _dtypes.float32) + max = _ops.convert_to_tensor(max, _dtypes.float32) + _inputs_flat = [inputs, min, max] + _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxVarsPerChannel", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxVarsPerChannel", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FakeQuantWithMinMaxVarsPerChannelGradientOutput = collections.namedtuple( + "FakeQuantWithMinMaxVarsPerChannelGradient", + ["backprops_wrt_input", "backprop_wrt_min", "backprop_wrt_max"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.fake_quant_with_min_max_vars_per_channel_gradient', v1=['quantization.fake_quant_with_min_max_vars_per_channel_gradient', 'fake_quant_with_min_max_vars_per_channel_gradient']) +@deprecated_endpoints('fake_quant_with_min_max_vars_per_channel_gradient') +def fake_quant_with_min_max_vars_per_channel_gradient(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits:int=8, narrow_range:bool=False, name=None): + r"""Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. + + Args: + gradients: A `Tensor` of type `float32`. + Backpropagated gradients above the FakeQuantWithMinMaxVars operation, + shape one of: `[d]`, `[b, d]`, `[b, h, w, d]`. + inputs: A `Tensor` of type `float32`. + Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape + same as `gradients`. + min, max: Quantization interval, floats of shape `[d]`. + min: A `Tensor` of type `float32`. + max: A `Tensor` of type `float32`. + num_bits: An optional `int`. Defaults to `8`. + The bitwidth of the quantization; between 2 and 16, inclusive. + narrow_range: An optional `bool`. Defaults to `False`. + Whether to quantize into 2^num_bits - 1 distinct values. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). + + backprops_wrt_input: A `Tensor` of type `float32`. + backprop_wrt_min: A `Tensor` of type `float32`. + backprop_wrt_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeQuantWithMinMaxVarsPerChannelGradient", name, gradients, + inputs, min, max, "num_bits", num_bits, "narrow_range", narrow_range) + _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fake_quant_with_min_max_vars_per_channel_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + return fake_quant_with_min_max_vars_per_channel_gradient_eager_fallback( + gradients, inputs, min, max, num_bits=num_bits, + narrow_range=narrow_range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_per_channel_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, + max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fake_quant_with_min_max_vars_per_channel_gradient( + (gradients, inputs, min, max, num_bits, narrow_range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQuantWithMinMaxVarsPerChannelGradient", gradients=gradients, + inputs=inputs, min=min, + max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fake_quant_with_min_max_vars_per_channel_gradient, (), dict(gradients=gradients, + inputs=inputs, + min=min, + max=max, + num_bits=num_bits, + narrow_range=narrow_range, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bits", _op._get_attr_int("num_bits"), "narrow_range", + _op._get_attr_bool("narrow_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQuantWithMinMaxVarsPerChannelGradient", _inputs_flat, _attrs, _result) + _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) + return _result + +FakeQuantWithMinMaxVarsPerChannelGradient = tf_export("raw_ops.FakeQuantWithMinMaxVarsPerChannelGradient")(_ops.to_raw_op(fake_quant_with_min_max_vars_per_channel_gradient)) +_dispatcher_for_fake_quant_with_min_max_vars_per_channel_gradient = fake_quant_with_min_max_vars_per_channel_gradient._tf_type_based_dispatcher.Dispatch + + +def fake_quant_with_min_max_vars_per_channel_gradient_eager_fallback(gradients: Annotated[Any, _atypes.Float32], inputs: Annotated[Any, _atypes.Float32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], num_bits: int, narrow_range: bool, name, ctx): + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + min = _ops.convert_to_tensor(min, _dtypes.float32) + max = _ops.convert_to_tensor(max, _dtypes.float32) + _inputs_flat = [gradients, inputs, min, max] + _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) + _result = _execute.execute(b"FakeQuantWithMinMaxVarsPerChannelGradient", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeQuantWithMinMaxVarsPerChannelGradient", _inputs_flat, _attrs, _result) + _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) + return _result + + +TV_Fill_T = TypeVar("TV_Fill_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Fill_index_type = TypeVar("TV_Fill_index_type", _atypes.Int32, _atypes.Int64) + +def fill(dims: Annotated[Any, TV_Fill_index_type], value: Annotated[Any, TV_Fill_T], name=None) -> Annotated[Any, TV_Fill_T]: + r"""Creates a tensor filled with a scalar value. + + This operation creates a tensor of shape `dims` and fills it with `value`. + + For example: + + ``` + # Output tensor has shape [2, 3]. + fill([2, 3], 9) ==> [[9, 9, 9] + [9, 9, 9]] + ``` + + `tf.fill` differs from `tf.constant` in a few ways: + + * `tf.fill` only supports scalar contents, whereas `tf.constant` supports + Tensor values. + * `tf.fill` creates an Op in the computation graph that constructs the actual + Tensor value at runtime. This is in contrast to `tf.constant` which embeds + the entire Tensor into the graph with a `Const` node. + * Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes + based on other runtime Tensors, unlike `tf.constant`. + + Args: + dims: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D. Represents the shape of the output tensor. + value: A `Tensor`. 0-D (scalar). Value to fill the returned tensor. + + @compatibility(numpy) + Equivalent to np.full + @end_compatibility + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Fill", name, dims, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fill_eager_fallback( + dims, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Fill", dims=dims, value=value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "index_type", + _op._get_attr_type("index_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Fill", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Fill = tf_export("raw_ops.Fill")(_ops.to_raw_op(fill)) + + +def fill_eager_fallback(dims: Annotated[Any, TV_Fill_index_type], value: Annotated[Any, TV_Fill_T], name, ctx) -> Annotated[Any, TV_Fill_T]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _attr_index_type, (dims,) = _execute.args_to_matching_eager([dims], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [dims, value] + _attrs = ("T", _attr_T, "index_type", _attr_index_type) + _result = _execute.execute(b"Fill", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Fill", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Fingerprint_T = TypeVar("TV_Fingerprint_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def fingerprint(data: Annotated[Any, TV_Fingerprint_T], method: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Generates fingerprint values. + + Generates fingerprint values of `data`. + + Fingerprint op considers the first dimension of `data` as the batch dimension, + and `output[i]` contains the fingerprint value generated from contents in + `data[i, ...]` for all `i`. + + Fingerprint op writes fingerprint values as byte arrays. For example, the + default method `farmhash64` generates a 64-bit fingerprint value at a time. + This 8-byte value is written out as an `uint8` array of size 8, in little-endian + order. + + For example, suppose that `data` has data type `DT_INT32` and shape (2, 3, 4), + and that the fingerprint method is `farmhash64`. In this case, the output shape + is (2, 8), where 2 is the batch dimension size of `data`, and 8 is the size of + each fingerprint value in bytes. `output[0, :]` is generated from 12 integers in + `data[0, :, :]` and similarly `output[1, :]` is generated from other 12 integers + in `data[1, :, :]`. + + Note that this op fingerprints the raw underlying buffer, and it does not + fingerprint Tensor's metadata such as data type and/or shape. For example, the + fingerprint values are invariant under reshapes and bitcasts as long as the + batch dimension remain the same: + + ``` + Fingerprint(data) == Fingerprint(Reshape(data, ...)) + Fingerprint(data) == Fingerprint(Bitcast(data, ...)) + ``` + + For string data, one should expect `Fingerprint(data) != + Fingerprint(ReduceJoin(data))` in general. + + Args: + data: A `Tensor`. Must have rank 1 or higher. + method: A `Tensor` of type `string`. + Fingerprint method used by this op. Currently available method is + `farmhash::fingerprint64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Fingerprint", name, data, method) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fingerprint_eager_fallback( + data, method, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Fingerprint", data=data, method=method, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Fingerprint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Fingerprint = tf_export("raw_ops.Fingerprint")(_ops.to_raw_op(fingerprint)) + + +def fingerprint_eager_fallback(data: Annotated[Any, TV_Fingerprint_T], method: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.UInt8]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + method = _ops.convert_to_tensor(method, _dtypes.string) + _inputs_flat = [data, method] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Fingerprint", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Fingerprint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Gather_Tparams = TypeVar("TV_Gather_Tparams", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Gather_Tindices = TypeVar("TV_Gather_Tindices", _atypes.Int32, _atypes.Int64) + +def gather(params: Annotated[Any, TV_Gather_Tparams], indices: Annotated[Any, TV_Gather_Tindices], validate_indices:bool=True, name=None) -> Annotated[Any, TV_Gather_Tparams]: + r"""Gather slices from `params` according to `indices`. + + `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). + Produces an output tensor with shape `indices.shape + params.shape[1:]` where: + + ```python + # Scalar indices + output[:, ..., :] = params[indices, :, ... :] + + # Vector indices + output[i, :, ..., :] = params[indices[i], :, ... :] + + # Higher rank indices + output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :] + ``` + + If `indices` is a permutation and `len(indices) == params.shape[0]` then + this operation will permute `params` accordingly. + + `validate_indices`: DEPRECATED. If this operation is assigned to CPU, values in + `indices` are always validated to be within range. If assigned to GPU, + out-of-bound indices result in safe but unspecified behavior, which may include + raising an error. + +
+ +
+ + Args: + params: A `Tensor`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Gather", name, params, indices, "validate_indices", + validate_indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return gather_eager_fallback( + params, indices, validate_indices=validate_indices, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Gather", params=params, indices=indices, + validate_indices=validate_indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("validate_indices", _op._get_attr_bool("validate_indices"), + "Tparams", _op._get_attr_type("Tparams"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Gather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Gather = tf_export("raw_ops.Gather")(_ops.to_raw_op(gather)) + + +def gather_eager_fallback(params: Annotated[Any, TV_Gather_Tparams], indices: Annotated[Any, TV_Gather_Tindices], validate_indices: bool, name, ctx) -> Annotated[Any, TV_Gather_Tparams]: + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [params, indices] + _attrs = ("validate_indices", validate_indices, "Tparams", _attr_Tparams, + "Tindices", _attr_Tindices) + _result = _execute.execute(b"Gather", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Gather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GatherNd_Tparams = TypeVar("TV_GatherNd_Tparams", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_GatherNd_Tindices = TypeVar("TV_GatherNd_Tindices", _atypes.Int16, _atypes.Int32, _atypes.Int64) + +def gather_nd(params: Annotated[Any, TV_GatherNd_Tparams], indices: Annotated[Any, TV_GatherNd_Tindices], name=None) -> Annotated[Any, TV_GatherNd_Tparams]: + r"""Gather slices from `params` into a Tensor with shape specified by `indices`. + + `indices` is a K-dimensional integer tensor, best thought of as a + (K-1)-dimensional tensor of indices into `params`, where each element defines a + slice of `params`: + + output[\\(i_0, ..., i_{K-2}\\)] = params[indices[\\(i_0, ..., i_{K-2}\\)]] + + Whereas in `tf.gather` `indices` defines slices into the `axis` + dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the + first `N` dimensions of `params`, where `N = indices.shape[-1]`. + + The last dimension of `indices` can be at most the rank of + `params`: + + indices.shape[-1] <= params.rank + + The last dimension of `indices` corresponds to elements + (if `indices.shape[-1] == params.rank`) or slices + (if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]` + of `params`. The output tensor has shape + + indices.shape[:-1] + params.shape[indices.shape[-1]:] + + Note that on CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, a 0 is stored in the + corresponding output value. + + Some examples below. + + Simple indexing into a matrix: + + ```python + indices = [[0, 0], [1, 1]] + params = [['a', 'b'], ['c', 'd']] + output = ['a', 'd'] + ``` + + Slice indexing into a matrix: + + ```python + indices = [[1], [0]] + params = [['a', 'b'], ['c', 'd']] + output = [['c', 'd'], ['a', 'b']] + ``` + + Indexing into a 3-tensor: + + ```python + indices = [[1]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = [[['a1', 'b1'], ['c1', 'd1']]] + + + indices = [[0, 1], [1, 0]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = [['c0', 'd0'], ['a1', 'b1']] + + + indices = [[0, 0, 1], [1, 0, 1]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = ['b0', 'b1'] + ``` + + Batched indexing into a matrix: + + ```python + indices = [[[0, 0]], [[0, 1]]] + params = [['a', 'b'], ['c', 'd']] + output = [['a'], ['b']] + ``` + + Batched slice indexing into a matrix: + + ```python + indices = [[[1]], [[0]]] + params = [['a', 'b'], ['c', 'd']] + output = [[['c', 'd']], [['a', 'b']]] + ``` + + Batched indexing into a 3-tensor: + + ```python + indices = [[[1]], [[0]]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = [[[['a1', 'b1'], ['c1', 'd1']]], + [[['a0', 'b0'], ['c0', 'd0']]]] + + indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = [[['c0', 'd0'], ['a1', 'b1']], + [['a0', 'b0'], ['c1', 'd1']]] + + + indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]] + params = [[['a0', 'b0'], ['c0', 'd0']], + [['a1', 'b1'], ['c1', 'd1']]] + output = [['b0', 'b1'], ['d0', 'c1']] + ``` + + See also `tf.gather` and `tf.batch_gather`. + + Args: + params: A `Tensor`. The tensor from which to gather values. + indices: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + Index tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GatherNd", name, params, indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return gather_nd_eager_fallback( + params, indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GatherNd", params=params, indices=indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tparams", _op._get_attr_type("Tparams"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GatherNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GatherNd = tf_export("raw_ops.GatherNd")(_ops.to_raw_op(gather_nd)) + + +def gather_nd_eager_fallback(params: Annotated[Any, TV_GatherNd_Tparams], indices: Annotated[Any, TV_GatherNd_Tindices], name, ctx) -> Annotated[Any, TV_GatherNd_Tparams]: + _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [params, indices] + _attrs = ("Tparams", _attr_Tparams, "Tindices", _attr_Tindices) + _result = _execute.execute(b"GatherNd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GatherNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GatherV2_Tparams = TypeVar("TV_GatherV2_Tparams", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_GatherV2_Tindices = TypeVar("TV_GatherV2_Tindices", _atypes.Int16, _atypes.Int32, _atypes.Int64) +TV_GatherV2_Taxis = TypeVar("TV_GatherV2_Taxis", _atypes.Int32, _atypes.Int64) + +def gather_v2(params: Annotated[Any, TV_GatherV2_Tparams], indices: Annotated[Any, TV_GatherV2_Tindices], axis: Annotated[Any, TV_GatherV2_Taxis], batch_dims:int=0, name=None) -> Annotated[Any, TV_GatherV2_Tparams]: + r"""Gather slices from `params` axis `axis` according to `indices`. + + `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). + Produces an output tensor with shape `params.shape[:axis] + + indices.shape[batch_dims:] + params.shape[axis + 1:]` where: + + ```python + # Scalar indices (output is rank(params) - 1). + output[a_0, ..., a_n, b_0, ..., b_n] = + params[a_0, ..., a_n, indices, b_0, ..., b_n] + + # Vector indices (output is rank(params)). + output[a_0, ..., a_n, i, b_0, ..., b_n] = + params[a_0, ..., a_n, indices[i], b_0, ..., b_n] + + # Higher rank indices (output is rank(params) + rank(indices) - 1). + output[a_0, ..., a_n, i, ..., j, b_0, ... b_n] = + params[a_0, ..., a_n, indices[i, ..., j], b_0, ..., b_n] + ``` + +
+ +
+ + Note that on CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, a 0 is stored in the + corresponding output value. + + See also `tf.batch_gather` and `tf.gather_nd`. + + Args: + params: A `Tensor`. + The tensor from which to gather values. Must be at least rank + `axis + 1`. + indices: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + Index tensor. Must be in range `[0, params.shape[axis])`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The axis in `params` to gather `indices` from. Defaults to the first + dimension. Supports negative indexes. + batch_dims: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GatherV2", name, params, indices, axis, "batch_dims", + batch_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return gather_v2_eager_fallback( + params, indices, axis, batch_dims=batch_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if batch_dims is None: + batch_dims = 0 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GatherV2", params=params, indices=indices, axis=axis, + batch_dims=batch_dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("batch_dims", _op._get_attr_int("batch_dims"), "Tparams", + _op._get_attr_type("Tparams"), "Tindices", + _op._get_attr_type("Tindices"), "Taxis", + _op._get_attr_type("Taxis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GatherV2 = tf_export("raw_ops.GatherV2")(_ops.to_raw_op(gather_v2)) + + +def gather_v2_eager_fallback(params: Annotated[Any, TV_GatherV2_Tparams], indices: Annotated[Any, TV_GatherV2_Tindices], axis: Annotated[Any, TV_GatherV2_Taxis], batch_dims: int, name, ctx) -> Annotated[Any, TV_GatherV2_Tparams]: + if batch_dims is None: + batch_dims = 0 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [params, indices, axis] + _attrs = ("batch_dims", batch_dims, "Tparams", _attr_Tparams, "Tindices", + _attr_Tindices, "Taxis", _attr_Taxis) + _result = _execute.execute(b"GatherV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GuaranteeConst_T = TypeVar("TV_GuaranteeConst_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def guarantee_const(input: Annotated[Any, TV_GuaranteeConst_T], name=None) -> Annotated[Any, TV_GuaranteeConst_T]: + r"""Gives a guarantee to the TF runtime that the input tensor is a constant. + + The runtime is then free to make optimizations based on this. + + Only accepts value typed tensors as inputs and rejects resource variable handles + as input. + + Returns the input tensor without modification. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GuaranteeConst", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return guarantee_const_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GuaranteeConst", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GuaranteeConst", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GuaranteeConst = tf_export("raw_ops.GuaranteeConst")(_ops.to_raw_op(guarantee_const)) + + +def guarantee_const_eager_fallback(input: Annotated[Any, TV_GuaranteeConst_T], name, ctx) -> Annotated[Any, TV_GuaranteeConst_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GuaranteeConst", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GuaranteeConst", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Identity_T = TypeVar("TV_Identity_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def identity(input: Annotated[Any, TV_Identity_T], name=None) -> Annotated[Any, TV_Identity_T]: + r"""Return a tensor with the same shape and contents as the input tensor or value. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Identity", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return identity_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Identity", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Identity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Identity = tf_export("raw_ops.Identity")(_ops.to_raw_op(identity)) + + +def identity_eager_fallback(input: Annotated[Any, TV_Identity_T], name, ctx) -> Annotated[Any, TV_Identity_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Identity", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Identity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('identity_n') +def identity_n(input, name=None): + r"""Returns a list of tensors with the same shapes and contents as the input + + tensors. + + This op can be used to override the gradient for complicated functions. For + example, suppose y = f(x) and we wish to apply a custom function g for backprop + such that dx = g(dy). In Python, + + ```python + with tf.get_default_graph().gradient_override_map( + {'IdentityN': 'OverrideGradientWithG'}): + y, _ = identity_n([f(x), x]) + + @tf.RegisterGradient('OverrideGradientWithG') + def ApplyG(op, dy, _): + return [None, g(dy)] # Do not backprop to f(x). + ``` + + Args: + input: A list of `Tensor` objects. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IdentityN", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_identity_n( + (input, name,), None) + if _result is not NotImplemented: + return _result + return identity_n_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + identity_n, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_identity_n( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IdentityN", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + identity_n, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IdentityN", _inputs_flat, _attrs, _result) + return _result + +IdentityN = tf_export("raw_ops.IdentityN")(_ops.to_raw_op(identity_n)) +_dispatcher_for_identity_n = identity_n._tf_type_based_dispatcher.Dispatch + + +def identity_n_eager_fallback(input, name, ctx): + _attr_T, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"IdentityN", len(input), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IdentityN", _inputs_flat, _attrs, _result) + return _result + + +TV_ImmutableConst_dtype = TypeVar("TV_ImmutableConst_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def immutable_const(dtype: TV_ImmutableConst_dtype, shape, memory_region_name: str, name=None) -> Annotated[Any, TV_ImmutableConst_dtype]: + r"""Returns immutable tensor from memory region. + + The current implementation memmaps the tensor from a file. + + Args: + dtype: A `tf.DType`. Type of the returned tensor. + shape: A `tf.TensorShape` or list of `ints`. Shape of the returned tensor. + memory_region_name: A `string`. + Name of readonly memory region used by the tensor, see + NewReadOnlyMemoryRegionFromFile in tensorflow::Env. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ImmutableConst", name, "dtype", dtype, "shape", shape, + "memory_region_name", memory_region_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return immutable_const_eager_fallback( + dtype=dtype, shape=shape, memory_region_name=memory_region_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + memory_region_name = _execute.make_str(memory_region_name, "memory_region_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ImmutableConst", dtype=dtype, shape=shape, + memory_region_name=memory_region_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "memory_region_name", + _op.get_attr("memory_region_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ImmutableConst", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ImmutableConst = tf_export("raw_ops.ImmutableConst")(_ops.to_raw_op(immutable_const)) + + +def immutable_const_eager_fallback(dtype: TV_ImmutableConst_dtype, shape, memory_region_name: str, name, ctx) -> Annotated[Any, TV_ImmutableConst_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + memory_region_name = _execute.make_str(memory_region_name, "memory_region_name") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape, "memory_region_name", + memory_region_name) + _result = _execute.execute(b"ImmutableConst", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ImmutableConst", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InplaceAdd_T = TypeVar("TV_InplaceAdd_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def inplace_add(x: Annotated[Any, TV_InplaceAdd_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceAdd_T], name=None) -> Annotated[Any, TV_InplaceAdd_T]: + r"""Adds v into specified rows of x. + + Computes y = x; y[i, :] += v; return y. + + Args: + x: A `Tensor`. A `Tensor` of type T. + i: A `Tensor` of type `int32`. + A vector. Indices into the left-most dimension of `x`. + v: A `Tensor`. Must have the same type as `x`. + A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InplaceAdd", name, x, i, v) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return inplace_add_eager_fallback( + x, i, v, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InplaceAdd", x=x, i=i, v=v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InplaceAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InplaceAdd = tf_export("raw_ops.InplaceAdd")(_ops.to_raw_op(inplace_add)) + + +def inplace_add_eager_fallback(x: Annotated[Any, TV_InplaceAdd_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceAdd_T], name, ctx) -> Annotated[Any, TV_InplaceAdd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], ctx, []) + (x, v) = _inputs_T + i = _ops.convert_to_tensor(i, _dtypes.int32) + _inputs_flat = [x, i, v] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InplaceAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InplaceAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InplaceSub_T = TypeVar("TV_InplaceSub_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def inplace_sub(x: Annotated[Any, TV_InplaceSub_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceSub_T], name=None) -> Annotated[Any, TV_InplaceSub_T]: + r""" Subtracts `v` into specified rows of `x`. + + Computes y = x; y[i, :] -= v; return y. + + Args: + x: A `Tensor`. A `Tensor` of type T. + i: A `Tensor` of type `int32`. + A vector. Indices into the left-most dimension of `x`. + v: A `Tensor`. Must have the same type as `x`. + A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InplaceSub", name, x, i, v) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return inplace_sub_eager_fallback( + x, i, v, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InplaceSub", x=x, i=i, v=v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InplaceSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InplaceSub = tf_export("raw_ops.InplaceSub")(_ops.to_raw_op(inplace_sub)) + + +def inplace_sub_eager_fallback(x: Annotated[Any, TV_InplaceSub_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceSub_T], name, ctx) -> Annotated[Any, TV_InplaceSub_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], ctx, []) + (x, v) = _inputs_T + i = _ops.convert_to_tensor(i, _dtypes.int32) + _inputs_flat = [x, i, v] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InplaceSub", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InplaceSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InplaceUpdate_T = TypeVar("TV_InplaceUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def inplace_update(x: Annotated[Any, TV_InplaceUpdate_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceUpdate_T], name=None) -> Annotated[Any, TV_InplaceUpdate_T]: + r"""Updates specified rows 'i' with values 'v'. + + Computes `x[i, :] = v; return x`. + + Originally this function is mutative however for compilation we make this + operation create / operate on a copy of `x`. + + Args: + x: A `Tensor`. A tensor of type `T`. + i: A `Tensor` of type `int32`. + A vector. Indices into the left-most dimension of `x`. + v: A `Tensor`. Must have the same type as `x`. + A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InplaceUpdate", name, x, i, v) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return inplace_update_eager_fallback( + x, i, v, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InplaceUpdate", x=x, i=i, v=v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InplaceUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InplaceUpdate = tf_export("raw_ops.InplaceUpdate")(_ops.to_raw_op(inplace_update)) + + +def inplace_update_eager_fallback(x: Annotated[Any, TV_InplaceUpdate_T], i: Annotated[Any, _atypes.Int32], v: Annotated[Any, TV_InplaceUpdate_T], name, ctx) -> Annotated[Any, TV_InplaceUpdate_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], ctx, []) + (x, v) = _inputs_T + i = _ops.convert_to_tensor(i, _dtypes.int32) + _inputs_flat = [x, i, v] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InplaceUpdate", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InplaceUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InvertPermutation_T = TypeVar("TV_InvertPermutation_T", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.invert_permutation', v1=['math.invert_permutation', 'invert_permutation']) +@deprecated_endpoints('invert_permutation') +def invert_permutation(x: Annotated[Any, TV_InvertPermutation_T], name=None) -> Annotated[Any, TV_InvertPermutation_T]: + r"""Computes the inverse permutation of a tensor. + + This operation computes the inverse of an index permutation. It takes a 1-D + integer tensor `x`, which represents the indices of a zero-based array, and + swaps each value with its index position. In other words, for an output tensor + `y` and an input tensor `x`, this operation computes the following: + + `y[x[i]] = i for i in [0, 1, ..., len(x) - 1]` + + The values must include 0. There can be no duplicate values or negative values. + + For example: + + ``` + # tensor `x` is [3, 4, 0, 2, 1] + invert_permutation(x) ==> [2, 4, 3, 0, 1] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InvertPermutation", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_invert_permutation( + (x, name,), None) + if _result is not NotImplemented: + return _result + return invert_permutation_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + invert_permutation, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_invert_permutation( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InvertPermutation", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + invert_permutation, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InvertPermutation", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InvertPermutation = tf_export("raw_ops.InvertPermutation")(_ops.to_raw_op(invert_permutation)) +_dispatcher_for_invert_permutation = invert_permutation._tf_type_based_dispatcher.Dispatch + + +def invert_permutation_eager_fallback(x: Annotated[Any, TV_InvertPermutation_T], name, ctx) -> Annotated[Any, TV_InvertPermutation_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InvertPermutation", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InvertPermutation", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_ListDiffOutput = collections.namedtuple( + "ListDiff", + ["out", "idx"]) + + +TV_ListDiff_T = TypeVar("TV_ListDiff_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ListDiff_out_idx = TypeVar("TV_ListDiff_out_idx", _atypes.Int32, _atypes.Int64) + +def list_diff(x: Annotated[Any, TV_ListDiff_T], y: Annotated[Any, TV_ListDiff_T], out_idx:TV_ListDiff_out_idx=_dtypes.int32, name=None): + r"""Computes the difference between two lists of numbers or strings. + + Given a list `x` and a list `y`, this operation returns a list `out` that + represents all values that are in `x` but not in `y`. The returned list `out` + is sorted in the same order that the numbers appear in `x` (duplicates are + preserved). This operation also returns a list `idx` that represents the + position of each `out` element in `x`. In other words: + + `out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]` + + For example, given this input: + + ``` + x = [1, 2, 3, 4, 5, 6] + y = [1, 3, 5] + ``` + + This operation would return: + + ``` + out ==> [2, 4, 6] + idx ==> [1, 3, 5] + ``` + + Args: + x: A `Tensor`. 1-D. Values to keep. + y: A `Tensor`. Must have the same type as `x`. 1-D. Values to remove. + out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, idx). + + out: A `Tensor`. Has the same type as `x`. + idx: A `Tensor` of type `out_idx`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ListDiff", name, x, y, "out_idx", out_idx) + _result = _ListDiffOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return list_diff_eager_fallback( + x, y, out_idx=out_idx, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ListDiff", x=x, y=y, out_idx=out_idx, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_idx", + _op._get_attr_type("out_idx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ListDiff", _inputs_flat, _attrs, _result) + _result = _ListDiffOutput._make(_result) + return _result + +ListDiff = tf_export("raw_ops.ListDiff")(_ops.to_raw_op(list_diff)) + + +def list_diff_eager_fallback(x: Annotated[Any, TV_ListDiff_T], y: Annotated[Any, TV_ListDiff_T], out_idx: TV_ListDiff_out_idx, name, ctx): + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, []) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "out_idx", out_idx) + _result = _execute.execute(b"ListDiff", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ListDiff", _inputs_flat, _attrs, _result) + _result = _ListDiffOutput._make(_result) + return _result + + +TV_LowerBound_T = TypeVar("TV_LowerBound_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LowerBound_out_type = TypeVar("TV_LowerBound_out_type", _atypes.Int32, _atypes.Int64) + +def lower_bound(sorted_inputs: Annotated[Any, TV_LowerBound_T], values: Annotated[Any, TV_LowerBound_T], out_type:TV_LowerBound_out_type=_dtypes.int32, name=None) -> Annotated[Any, TV_LowerBound_out_type]: + r"""Applies lower_bound(sorted_search_values, values) along each row. + + Each set of rows with the same index in (sorted_inputs, values) is treated + independently. The resulting row is the equivalent of calling + `np.searchsorted(sorted_inputs, values, side='left')`. + + The result is not a global index to the entire + `Tensor`, but rather just the index in the last dimension. + + A 2-D example: + sorted_sequence = [[0, 3, 9, 9, 10], + [1, 2, 3, 4, 5]] + values = [[2, 4, 9], + [0, 2, 6]] + + result = LowerBound(sorted_sequence, values) + + result == [[1, 2, 2], + [0, 1, 5]] + + Args: + sorted_inputs: A `Tensor`. 2-D Tensor where each row is ordered. + values: A `Tensor`. Must have the same type as `sorted_inputs`. + 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains + the values that will be searched for in `sorted_search_values`. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LowerBound", name, sorted_inputs, values, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lower_bound_eager_fallback( + sorted_inputs, values, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LowerBound", sorted_inputs=sorted_inputs, values=values, + out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LowerBound", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LowerBound = tf_export("raw_ops.LowerBound")(_ops.to_raw_op(lower_bound)) + + +def lower_bound_eager_fallback(sorted_inputs: Annotated[Any, TV_LowerBound_T], values: Annotated[Any, TV_LowerBound_T], out_type: TV_LowerBound_out_type, name, ctx) -> Annotated[Any, TV_LowerBound_out_type]: + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, _inputs_T = _execute.args_to_matching_eager([sorted_inputs, values], ctx, []) + (sorted_inputs, values) = _inputs_T + _inputs_flat = [sorted_inputs, values] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"LowerBound", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LowerBound", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixBandPart_T = TypeVar("TV_MatrixBandPart_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MatrixBandPart_Tindex = TypeVar("TV_MatrixBandPart_Tindex", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.band_part', v1=['linalg.band_part', 'matrix_band_part']) +@deprecated_endpoints('matrix_band_part') +def matrix_band_part(input: Annotated[Any, TV_MatrixBandPart_T], num_lower: Annotated[Any, TV_MatrixBandPart_Tindex], num_upper: Annotated[Any, TV_MatrixBandPart_Tindex], name=None) -> Annotated[Any, TV_MatrixBandPart_T]: + r"""Copy a tensor setting everything outside a central band in each innermost matrix to zero. + + The `band` part is computed as follows: + Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a + tensor with the same shape where + + `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`. + + The indicator function + + `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && + (num_upper < 0 || (n-m) <= num_upper)`. + + For example: + + ``` + # if 'input' is [[ 0, 1, 2, 3] + # [-1, 0, 1, 2] + # [-2, -1, 0, 1] + # [-3, -2, -1, 0]], + + tf.linalg.band_part(input, 1, -1) ==> [[ 0, 1, 2, 3] + [-1, 0, 1, 2] + [ 0, -1, 0, 1] + [ 0, 0, -1, 0]], + + tf.linalg.band_part(input, 2, 1) ==> [[ 0, 1, 0, 0] + [-1, 0, 1, 0] + [-2, -1, 0, 1] + [ 0, -2, -1, 0]] + ``` + + Useful special cases: + + ``` + tf.linalg.band_part(input, 0, -1) ==> Upper triangular part. + tf.linalg.band_part(input, -1, 0) ==> Lower triangular part. + tf.linalg.band_part(input, 0, 0) ==> Diagonal. + ``` + + Args: + input: A `Tensor`. Rank `k` tensor. + num_lower: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D tensor. Number of subdiagonals to keep. If negative, keep entire + lower triangle. + num_upper: A `Tensor`. Must have the same type as `num_lower`. + 0-D tensor. Number of superdiagonals to keep. If negative, keep + entire upper triangle. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixBandPart", name, input, num_lower, num_upper) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matrix_band_part( + (input, num_lower, num_upper, name,), None) + if _result is not NotImplemented: + return _result + return matrix_band_part_eager_fallback( + input, num_lower, num_upper, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_band_part, (), dict(input=input, num_lower=num_lower, + num_upper=num_upper, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matrix_band_part( + (input, num_lower, num_upper, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixBandPart", input=input, num_lower=num_lower, + num_upper=num_upper, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_band_part, (), dict(input=input, num_lower=num_lower, + num_upper=num_upper, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindex", + _op._get_attr_type("Tindex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixBandPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixBandPart = tf_export("raw_ops.MatrixBandPart")(_ops.to_raw_op(matrix_band_part)) +_dispatcher_for_matrix_band_part = matrix_band_part._tf_type_based_dispatcher.Dispatch + + +def matrix_band_part_eager_fallback(input: Annotated[Any, TV_MatrixBandPart_T], num_lower: Annotated[Any, TV_MatrixBandPart_Tindex], num_upper: Annotated[Any, TV_MatrixBandPart_Tindex], name, ctx) -> Annotated[Any, TV_MatrixBandPart_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tindex, _inputs_Tindex = _execute.args_to_matching_eager([num_lower, num_upper], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + (num_lower, num_upper) = _inputs_Tindex + _inputs_flat = [input, num_lower, num_upper] + _attrs = ("T", _attr_T, "Tindex", _attr_Tindex) + _result = _execute.execute(b"MatrixBandPart", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixBandPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiag_T = TypeVar("TV_MatrixDiag_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag(diagonal: Annotated[Any, TV_MatrixDiag_T], name=None) -> Annotated[Any, TV_MatrixDiag_T]: + r"""Returns a batched diagonal tensor with a given batched diagonal values. + + Given a `diagonal`, this operation returns a tensor with the `diagonal` and + everything else padded with zeros. The diagonal is computed as follows: + + Assume `diagonal` has `k` dimensions `[I, J, K, ..., N]`, then the output is a + tensor of rank `k+1` with dimensions [I, J, K, ..., N, N]` where: + + `output[i, j, k, ..., m, n] = 1{m=n} * diagonal[i, j, k, ..., n]`. + + For example: + + ``` + # 'diagonal' is [[1, 2, 3, 4], [5, 6, 7, 8]] + + and diagonal.shape = (2, 4) + + tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0] + [0, 2, 0, 0] + [0, 0, 3, 0] + [0, 0, 0, 4]], + [[5, 0, 0, 0] + [0, 6, 0, 0] + [0, 0, 7, 0] + [0, 0, 0, 8]]] + + which has shape (2, 4, 4) + ``` + + Args: + diagonal: A `Tensor`. Rank `k`, where `k >= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiag", name, diagonal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_eager_fallback( + diagonal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiag", diagonal=diagonal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiag = tf_export("raw_ops.MatrixDiag")(_ops.to_raw_op(matrix_diag)) + + +def matrix_diag_eager_fallback(diagonal: Annotated[Any, TV_MatrixDiag_T], name, ctx) -> Annotated[Any, TV_MatrixDiag_T]: + _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], ctx, []) + _inputs_flat = [diagonal] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixDiag", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiagPart_T = TypeVar("TV_MatrixDiagPart_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag_part(input: Annotated[Any, TV_MatrixDiagPart_T], name=None) -> Annotated[Any, TV_MatrixDiagPart_T]: + r"""Returns the batched diagonal part of a batched tensor. + + This operation returns a tensor with the `diagonal` part + of the batched `input`. The `diagonal` part is computed as follows: + + Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a + tensor of rank `k - 1` with dimensions `[I, J, K, ..., min(M, N)]` where: + + `diagonal[i, j, k, ..., n] = input[i, j, k, ..., n, n]`. + + The input must be at least a matrix. + + For example: + + ``` + # 'input' is [[[1, 0, 0, 0] + [0, 2, 0, 0] + [0, 0, 3, 0] + [0, 0, 0, 4]], + [[5, 0, 0, 0] + [0, 6, 0, 0] + [0, 0, 7, 0] + [0, 0, 0, 8]]] + + and input.shape = (2, 4, 4) + + tf.matrix_diag_part(input) ==> [[1, 2, 3, 4], [5, 6, 7, 8]] + + which has shape (2, 4) + ``` + + Args: + input: A `Tensor`. Rank `k` tensor where `k >= 2`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiagPart", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_part_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiagPart", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiagPart = tf_export("raw_ops.MatrixDiagPart")(_ops.to_raw_op(matrix_diag_part)) + + +def matrix_diag_part_eager_fallback(input: Annotated[Any, TV_MatrixDiagPart_T], name, ctx) -> Annotated[Any, TV_MatrixDiagPart_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixDiagPart", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiagPart", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiagPartV2_T = TypeVar("TV_MatrixDiagPartV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag_part_v2(input: Annotated[Any, TV_MatrixDiagPartV2_T], k: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagPartV2_T], name=None) -> Annotated[Any, TV_MatrixDiagPartV2_T]: + r"""Returns the batched diagonal part of a batched tensor. + + Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched + `input`. + + Assume `input` has `r` dimensions `[I, J, ..., L, M, N]`. + Let `max_diag_len` be the maximum length among all diagonals to be extracted, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + Let `num_diags` be the number of diagonals to extract, + `num_diags = k[1] - k[0] + 1`. + + If `num_diags == 1`, the output tensor is of rank `r - 1` with shape + `[I, J, ..., L, max_diag_len]` and values: + + ``` + diagonal[i, j, ..., l, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `y = max(-k[1], 0)`, `x = max(k[1], 0)`. + + Otherwise, the output tensor has rank `r` with dimensions + `[I, J, ..., L, num_diags, max_diag_len]` with values: + + ``` + diagonal[i, j, ..., l, m, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `d = k[1] - m`, `y = max(-d, 0)`, and `x = max(d, 0)`. + + The input must be at least a matrix. + + For example: + + ``` + input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4) + [5, 6, 7, 8], + [9, 8, 7, 6]], + [[5, 4, 3, 2], + [1, 2, 3, 4], + [5, 6, 7, 8]]]) + + # A main diagonal from each batch. + tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3) + [5, 2, 7]] + + # A superdiagonal from each batch. + tf.matrix_diag_part(input, k = 1) + ==> [[2, 7, 6], # Output shape: (2, 3) + [4, 3, 8]] + + # A tridiagonal band from each batch. + tf.matrix_diag_part(input, k = (-1, 1)) + ==> [[[2, 7, 6], # Output shape: (2, 3, 3) + [1, 6, 7], + [5, 8, 0]], + [[4, 3, 8], + [5, 2, 7], + [1, 6, 0]]] + + # Padding value = 9 + tf.matrix_diag_part(input, k = (1, 3), padding_value = 9) + ==> [[[4, 9, 9], # Output shape: (2, 3, 3) + [3, 8, 9], + [2, 7, 6]], + [[2, 9, 9], + [3, 4, 9], + [4, 3, 8]]] + ``` + + Args: + input: A `Tensor`. Rank `r` tensor where `r >= 2`. + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + padding_value: A `Tensor`. Must have the same type as `input`. + The value to fill the area outside the specified diagonal band with. + Default is 0. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiagPartV2", name, input, k, padding_value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_part_v2_eager_fallback( + input, k, padding_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiagPartV2", input=input, k=k, padding_value=padding_value, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiagPartV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiagPartV2 = tf_export("raw_ops.MatrixDiagPartV2")(_ops.to_raw_op(matrix_diag_part_v2)) + + +def matrix_diag_part_v2_eager_fallback(input: Annotated[Any, TV_MatrixDiagPartV2_T], k: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagPartV2_T], name, ctx) -> Annotated[Any, TV_MatrixDiagPartV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, padding_value], ctx, []) + (input, padding_value) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + _inputs_flat = [input, k, padding_value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixDiagPartV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiagPartV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiagPartV3_T = TypeVar("TV_MatrixDiagPartV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag_part_v3(input: Annotated[Any, TV_MatrixDiagPartV3_T], k: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagPartV3_T], align:str="RIGHT_LEFT", name=None) -> Annotated[Any, TV_MatrixDiagPartV3_T]: + r"""Returns the batched diagonal part of a batched tensor. + + Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched + `input`. + + Assume `input` has `r` dimensions `[I, J, ..., L, M, N]`. + Let `max_diag_len` be the maximum length among all diagonals to be extracted, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + Let `num_diags` be the number of diagonals to extract, + `num_diags = k[1] - k[0] + 1`. + + If `num_diags == 1`, the output tensor is of rank `r - 1` with shape + `[I, J, ..., L, max_diag_len]` and values: + + ``` + diagonal[i, j, ..., l, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `y = max(-k[1], 0)`, `x = max(k[1], 0)`. + + Otherwise, the output tensor has rank `r` with dimensions + `[I, J, ..., L, num_diags, max_diag_len]` with values: + + ``` + diagonal[i, j, ..., l, m, n] + = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N, + padding_value ; otherwise. + ``` + where `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + The input must be at least a matrix. + + For example: + + ``` + input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4) + [5, 6, 7, 8], + [9, 8, 7, 6]], + [[5, 4, 3, 2], + [1, 2, 3, 4], + [5, 6, 7, 8]]]) + + # A main diagonal from each batch. + tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3) + [5, 2, 7]] + + # A superdiagonal from each batch. + tf.matrix_diag_part(input, k = 1) + ==> [[2, 7, 6], # Output shape: (2, 3) + [4, 3, 8]] + + # A band from each batch. + tf.matrix_diag_part(input, k = (-1, 2)) + ==> [[[0, 3, 8], # Output shape: (2, 4, 3) + [2, 7, 6], + [1, 6, 7], + [5, 8, 0]], + [[0, 3, 4], + [4, 3, 8], + [5, 2, 7], + [1, 6, 0]]] + + # LEFT_RIGHT alignment. + tf.matrix_diag_part(input, k = (-1, 2), align="LEFT_RIGHT") + ==> [[[3, 8, 0], # Output shape: (2, 4, 3) + [2, 7, 6], + [1, 6, 7], + [0, 5, 8]], + [[3, 4, 0], + [4, 3, 8], + [5, 2, 7], + [0, 1, 6]]] + + # max_diag_len can be shorter than the main diagonal. + tf.matrix_diag_part(input, k = (-2, -1)) + ==> [[[5, 8], + [9, 0]], + [[1, 6], + [5, 0]]] + + # padding_value = 9 + tf.matrix_diag_part(input, k = (1, 3), padding_value = 9) + ==> [[[9, 9, 4], # Output shape: (2, 3, 3) + [9, 3, 8], + [2, 7, 6]], + [[9, 9, 2], + [9, 3, 4], + [4, 3, 8]]] + + ``` + + Args: + input: A `Tensor`. Rank `r` tensor where `r >= 2`. + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + padding_value: A `Tensor`. Must have the same type as `input`. + The value to fill the area outside the specified diagonal band with. + Default is 0. + align: An optional `string` from: `"LEFT_RIGHT", "RIGHT_LEFT", "LEFT_LEFT", "RIGHT_RIGHT"`. Defaults to `"RIGHT_LEFT"`. + Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is + a string specifying how superdiagonals and subdiagonals should be aligned, + respectively. There are four possible alignments: "RIGHT_LEFT" (default), + "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals + to the right (left-pads the row) and subdiagonals to the left (right-pads the + row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is + the opposite alignment. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiagPartV3", name, input, k, padding_value, "align", + align) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_part_v3_eager_fallback( + input, k, padding_value, align=align, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiagPartV3", input=input, k=k, padding_value=padding_value, + align=align, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align", _op.get_attr("align")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiagPartV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiagPartV3 = tf_export("raw_ops.MatrixDiagPartV3")(_ops.to_raw_op(matrix_diag_part_v3)) + + +def matrix_diag_part_v3_eager_fallback(input: Annotated[Any, TV_MatrixDiagPartV3_T], k: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagPartV3_T], align: str, name, ctx) -> Annotated[Any, TV_MatrixDiagPartV3_T]: + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, padding_value], ctx, []) + (input, padding_value) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + _inputs_flat = [input, k, padding_value] + _attrs = ("T", _attr_T, "align", align) + _result = _execute.execute(b"MatrixDiagPartV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiagPartV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiagV2_T = TypeVar("TV_MatrixDiagV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag_v2(diagonal: Annotated[Any, TV_MatrixDiagV2_T], k: Annotated[Any, _atypes.Int32], num_rows: Annotated[Any, _atypes.Int32], num_cols: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagV2_T], name=None) -> Annotated[Any, TV_MatrixDiagV2_T]: + r"""Returns a batched diagonal tensor with given batched diagonal values. + + Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th + diagonals of a matrix, with everything else padded with `padding`. `num_rows` + and `num_cols` specify the dimension of the innermost matrix of the output. If + both are not specified, the op assumes the innermost matrix is square and infers + its size from `k` and the innermost dimension of `diagonal`. If only one of them + is specified, the op assumes the unspecified value is the smallest possible + based on other criteria. + + Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has + rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one + diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank + `r` with shape `[I, J, ..., L, num_rows, num_cols]`. + + The second innermost dimension of `diagonal` has double meaning. + When `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size + [I, J, ..., M], and the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper + padding_value ; otherwise + ``` + + Otherwise, `M` is treated as the number of diagonals for the matrix in the + same batch (`M = k[1]-k[0]+1`), and the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + padding_value ; otherwise + ``` + where `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`. + + For example: + + ``` + # The main diagonal. + diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4) + [5, 6, 7, 8]]) + tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4) + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]], + [[5, 0, 0, 0], + [0, 6, 0, 0], + [0, 0, 7, 0], + [0, 0, 0, 8]]] + + # A superdiagonal (per batch). + diagonal = np.array([[1, 2, 3], # Input shape: (2, 3) + [4, 5, 6]]) + tf.matrix_diag(diagonal, k = 1) + ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4) + [0, 0, 2, 0], + [0, 0, 0, 3], + [0, 0, 0, 0]], + [[0, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 0, 6], + [0, 0, 0, 0]]] + + # A band of diagonals. + diagonals = np.array([[[1, 2, 3], # Input shape: (2, 2, 3) + [4, 5, 0]], + [[6, 7, 9], + [9, 1, 0]]]) + tf.matrix_diag(diagonals, k = (-1, 0)) + ==> [[[1, 0, 0], # Output shape: (2, 3, 3) + [4, 2, 0], + [0, 5, 3]], + [[6, 0, 0], + [9, 7, 0], + [0, 1, 9]]] + + # Rectangular matrix. + diagonal = np.array([1, 2]) # Input shape: (2) + tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4) + ==> [[0, 0, 0, 0], # Output shape: (3, 4) + [1, 0, 0, 0], + [0, 2, 0, 0]] + + # Rectangular matrix with inferred num_cols and padding_value = 9. + tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9) + ==> [[9, 9], # Output shape: (3, 2) + [1, 9], + [9, 2]] + ``` + + Args: + diagonal: A `Tensor`. Rank `r`, where `r >= 1` + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + num_rows: A `Tensor` of type `int32`. + The number of rows of the output matrix. If it is not provided, the op assumes + the output matrix is a square matrix and infers the matrix size from k and the + innermost dimension of `diagonal`. + num_cols: A `Tensor` of type `int32`. + The number of columns of the output matrix. If it is not provided, the op + assumes the output matrix is a square matrix and infers the matrix size from + k and the innermost dimension of `diagonal`. + padding_value: A `Tensor`. Must have the same type as `diagonal`. + The number to fill the area outside the specified diagonal band with. + Default is 0. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiagV2", name, diagonal, k, num_rows, num_cols, + padding_value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_v2_eager_fallback( + diagonal, k, num_rows, num_cols, padding_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiagV2", diagonal=diagonal, k=k, num_rows=num_rows, + num_cols=num_cols, padding_value=padding_value, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiagV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiagV2 = tf_export("raw_ops.MatrixDiagV2")(_ops.to_raw_op(matrix_diag_v2)) + + +def matrix_diag_v2_eager_fallback(diagonal: Annotated[Any, TV_MatrixDiagV2_T], k: Annotated[Any, _atypes.Int32], num_rows: Annotated[Any, _atypes.Int32], num_cols: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagV2_T], name, ctx) -> Annotated[Any, TV_MatrixDiagV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([diagonal, padding_value], ctx, []) + (diagonal, padding_value) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + num_rows = _ops.convert_to_tensor(num_rows, _dtypes.int32) + num_cols = _ops.convert_to_tensor(num_cols, _dtypes.int32) + _inputs_flat = [diagonal, k, num_rows, num_cols, padding_value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixDiagV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiagV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixDiagV3_T = TypeVar("TV_MatrixDiagV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_diag_v3(diagonal: Annotated[Any, TV_MatrixDiagV3_T], k: Annotated[Any, _atypes.Int32], num_rows: Annotated[Any, _atypes.Int32], num_cols: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagV3_T], align:str="RIGHT_LEFT", name=None) -> Annotated[Any, TV_MatrixDiagV3_T]: + r"""Returns a batched diagonal tensor with given batched diagonal values. + + Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th + diagonals of a matrix, with everything else padded with `padding`. `num_rows` + and `num_cols` specify the dimension of the innermost matrix of the output. If + both are not specified, the op assumes the innermost matrix is square and infers + its size from `k` and the innermost dimension of `diagonal`. If only one of them + is specified, the op assumes the unspecified value is the smallest possible + based on other criteria. + + Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor has + rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only one + diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has rank + `r` with shape `[I, J, ..., L, num_rows, num_cols]`. + + The second innermost dimension of `diagonal` has double meaning. + When `k` is scalar or `k[0] == k[1]`, `M` is part of the batch size + [I, J, ..., M], and the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper + padding_value ; otherwise + ``` + + Otherwise, `M` is treated as the number of diagonals for the matrix in the + same batch (`M = k[1]-k[0]+1`), and the output tensor is: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + padding_value ; otherwise + ``` + where `d = n - m`, `diag_index = [k] - d`, and + `index_in_diag = n - max(d, 0) + offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + For example: + + ``` + # The main diagonal. + diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4) + [5, 6, 7, 8]]) + tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4) + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]], + [[5, 0, 0, 0], + [0, 6, 0, 0], + [0, 0, 7, 0], + [0, 0, 0, 8]]] + + # A superdiagonal (per batch). + diagonal = np.array([[1, 2, 3], # Input shape: (2, 3) + [4, 5, 6]]) + tf.matrix_diag(diagonal, k = 1) + ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4) + [0, 0, 2, 0], + [0, 0, 0, 3], + [0, 0, 0, 0]], + [[0, 4, 0, 0], + [0, 0, 5, 0], + [0, 0, 0, 6], + [0, 0, 0, 0]]] + + # A tridiagonal band (per batch). + diagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3) + [1, 2, 3], + [4, 5, 0]], + [[0, 2, 3], + [6, 7, 9], + [9, 1, 0]]]) + tf.matrix_diag(diagonals, k = (-1, 1)) + ==> [[[1, 8, 0], # Output shape: (2, 3, 3) + [4, 2, 9], + [0, 5, 3]], + [[6, 2, 0], + [9, 7, 3], + [0, 1, 9]]] + + # LEFT_RIGHT alignment. + diagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3) + [1, 2, 3], + [0, 4, 5]], + [[2, 3, 0], + [6, 7, 9], + [0, 9, 1]]]) + tf.matrix_diag(diagonals, k = (-1, 1), align="LEFT_RIGHT") + ==> [[[1, 8, 0], # Output shape: (2, 3, 3) + [4, 2, 9], + [0, 5, 3]], + [[6, 2, 0], + [9, 7, 3], + [0, 1, 9]]] + + # Rectangular matrix. + diagonal = np.array([1, 2]) # Input shape: (2) + tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4) + ==> [[0, 0, 0, 0], # Output shape: (3, 4) + [1, 0, 0, 0], + [0, 2, 0, 0]] + + # Rectangular matrix with inferred num_cols and padding_value = 9. + tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9) + ==> [[9, 9], # Output shape: (3, 2) + [1, 9], + [9, 2]] + + ``` + + Args: + diagonal: A `Tensor`. Rank `r`, where `r >= 1` + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + num_rows: A `Tensor` of type `int32`. + The number of rows of the output matrix. If it is not provided, the op assumes + the output matrix is a square matrix and infers the matrix size from k and the + innermost dimension of `diagonal`. + num_cols: A `Tensor` of type `int32`. + The number of columns of the output matrix. If it is not provided, the op + assumes the output matrix is a square matrix and infers the matrix size from + k and the innermost dimension of `diagonal`. + padding_value: A `Tensor`. Must have the same type as `diagonal`. + The number to fill the area outside the specified diagonal band with. + Default is 0. + align: An optional `string` from: `"LEFT_RIGHT", "RIGHT_LEFT", "LEFT_LEFT", "RIGHT_RIGHT"`. Defaults to `"RIGHT_LEFT"`. + Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is + a string specifying how superdiagonals and subdiagonals should be aligned, + respectively. There are four possible alignments: "RIGHT_LEFT" (default), + "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals + to the right (left-pads the row) and subdiagonals to the left (right-pads the + row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is + the opposite alignment. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDiagV3", name, diagonal, k, num_rows, num_cols, + padding_value, "align", align) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_diag_v3_eager_fallback( + diagonal, k, num_rows, num_cols, padding_value, align=align, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDiagV3", diagonal=diagonal, k=k, num_rows=num_rows, + num_cols=num_cols, padding_value=padding_value, + align=align, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align", _op.get_attr("align")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDiagV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDiagV3 = tf_export("raw_ops.MatrixDiagV3")(_ops.to_raw_op(matrix_diag_v3)) + + +def matrix_diag_v3_eager_fallback(diagonal: Annotated[Any, TV_MatrixDiagV3_T], k: Annotated[Any, _atypes.Int32], num_rows: Annotated[Any, _atypes.Int32], num_cols: Annotated[Any, _atypes.Int32], padding_value: Annotated[Any, TV_MatrixDiagV3_T], align: str, name, ctx) -> Annotated[Any, TV_MatrixDiagV3_T]: + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _attr_T, _inputs_T = _execute.args_to_matching_eager([diagonal, padding_value], ctx, []) + (diagonal, padding_value) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + num_rows = _ops.convert_to_tensor(num_rows, _dtypes.int32) + num_cols = _ops.convert_to_tensor(num_cols, _dtypes.int32) + _inputs_flat = [diagonal, k, num_rows, num_cols, padding_value] + _attrs = ("T", _attr_T, "align", align) + _result = _execute.execute(b"MatrixDiagV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDiagV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSetDiag_T = TypeVar("TV_MatrixSetDiag_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_set_diag(input: Annotated[Any, TV_MatrixSetDiag_T], diagonal: Annotated[Any, TV_MatrixSetDiag_T], name=None) -> Annotated[Any, TV_MatrixSetDiag_T]: + r"""Returns a batched matrix tensor with new batched diagonal values. + + Given `input` and `diagonal`, this operation returns a tensor with the + same shape and values as `input`, except for the main diagonal of the + innermost matrices. These will be overwritten by the values in `diagonal`. + + The output is computed as follows: + + Assume `input` has `k+1` dimensions `[I, J, K, ..., M, N]` and `diagonal` has + `k` dimensions `[I, J, K, ..., min(M, N)]`. Then the output is a + tensor of rank `k+1` with dimensions `[I, J, K, ..., M, N]` where: + + * `output[i, j, k, ..., m, n] = diagonal[i, j, k, ..., n]` for `m == n`. + * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`. + + Args: + input: A `Tensor`. Rank `k+1`, where `k >= 1`. + diagonal: A `Tensor`. Must have the same type as `input`. + Rank `k`, where `k >= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSetDiag", name, input, diagonal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_set_diag_eager_fallback( + input, diagonal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSetDiag", input=input, diagonal=diagonal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSetDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSetDiag = tf_export("raw_ops.MatrixSetDiag")(_ops.to_raw_op(matrix_set_diag)) + + +def matrix_set_diag_eager_fallback(input: Annotated[Any, TV_MatrixSetDiag_T], diagonal: Annotated[Any, TV_MatrixSetDiag_T], name, ctx) -> Annotated[Any, TV_MatrixSetDiag_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], ctx, []) + (input, diagonal) = _inputs_T + _inputs_flat = [input, diagonal] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixSetDiag", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSetDiag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSetDiagV2_T = TypeVar("TV_MatrixSetDiagV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_set_diag_v2(input: Annotated[Any, TV_MatrixSetDiagV2_T], diagonal: Annotated[Any, TV_MatrixSetDiagV2_T], k: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_MatrixSetDiagV2_T]: + r"""Returns a batched matrix tensor with new batched diagonal values. + + Given `input` and `diagonal`, this operation returns a tensor with the + same shape and values as `input`, except for the specified diagonals of the + innermost matrices. These will be overwritten by the values in `diagonal`. + + `input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or + `k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`. + Otherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`. + `num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`. + `max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + + The output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`. + If `k` is scalar or `k[0] == k[1]`: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + + Otherwise, + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + where `d = n - m`, `diag_index = k[1] - d`, and `index_in_diag = n - max(d, 0)`. + + For example: + + ``` + # The main diagonal. + input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4) + [7, 7, 7, 7], + [7, 7, 7, 7]], + [[7, 7, 7, 7], + [7, 7, 7, 7], + [7, 7, 7, 7]]]) + diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3) + [4, 5, 6]]) + tf.matrix_set_diag(diagonal) ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4) + [7, 2, 7, 7], + [7, 7, 3, 7]], + [[4, 7, 7, 7], + [7, 5, 7, 7], + [7, 7, 6, 7]]] + + # A superdiagonal (per batch). + tf.matrix_set_diag(diagonal, k = 1) + ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4) + [7, 7, 2, 7], + [7, 7, 7, 3]], + [[7, 4, 7, 7], + [7, 7, 5, 7], + [7, 7, 7, 6]]] + + # A band of diagonals. + diagonals = np.array([[[1, 2, 3], # Diagonal shape: (2, 2, 3) + [4, 5, 0]], + [[6, 1, 2], + [3, 4, 0]]]) + tf.matrix_set_diag(diagonals, k = (-1, 0)) + ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4) + [4, 2, 7, 7], + [0, 5, 3, 7]], + [[6, 7, 7, 7], + [3, 1, 7, 7], + [7, 4, 2, 7]]] + + ``` + + Args: + input: A `Tensor`. Rank `r+1`, where `r >= 1`. + diagonal: A `Tensor`. Must have the same type as `input`. + Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`. + `k >= 1`. + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSetDiagV2", name, input, diagonal, k) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_set_diag_v2_eager_fallback( + input, diagonal, k, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSetDiagV2", input=input, diagonal=diagonal, k=k, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSetDiagV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSetDiagV2 = tf_export("raw_ops.MatrixSetDiagV2")(_ops.to_raw_op(matrix_set_diag_v2)) + + +def matrix_set_diag_v2_eager_fallback(input: Annotated[Any, TV_MatrixSetDiagV2_T], diagonal: Annotated[Any, TV_MatrixSetDiagV2_T], k: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_MatrixSetDiagV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], ctx, []) + (input, diagonal) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + _inputs_flat = [input, diagonal, k] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixSetDiagV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSetDiagV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSetDiagV3_T = TypeVar("TV_MatrixSetDiagV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def matrix_set_diag_v3(input: Annotated[Any, TV_MatrixSetDiagV3_T], diagonal: Annotated[Any, TV_MatrixSetDiagV3_T], k: Annotated[Any, _atypes.Int32], align:str="RIGHT_LEFT", name=None) -> Annotated[Any, TV_MatrixSetDiagV3_T]: + r"""Returns a batched matrix tensor with new batched diagonal values. + + Given `input` and `diagonal`, this operation returns a tensor with the + same shape and values as `input`, except for the specified diagonals of the + innermost matrices. These will be overwritten by the values in `diagonal`. + + `input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or + `k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`. + Otherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`. + `num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`. + `max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`, + `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))` + + The output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`. + If `k` is scalar or `k[0] == k[1]`: + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + + Otherwise, + + ``` + output[i, j, ..., l, m, n] + = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1] + input[i, j, ..., l, m, n] ; otherwise + ``` + where `d = n - m`, `diag_index = k[1] - d`, and + `index_in_diag = n - max(d, 0) + offset`. + + `offset` is zero except when the alignment of the diagonal is to the right. + ``` + offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT} + and `d >= 0`) or + (`align` in {LEFT_RIGHT, RIGHT_RIGHT} + and `d <= 0`) + 0 ; otherwise + ``` + where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`. + + For example: + + ``` + # The main diagonal. + input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4) + [7, 7, 7, 7], + [7, 7, 7, 7]], + [[7, 7, 7, 7], + [7, 7, 7, 7], + [7, 7, 7, 7]]]) + diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3) + [4, 5, 6]]) + tf.matrix_set_diag(input, diagonal) + ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4) + [7, 2, 7, 7], + [7, 7, 3, 7]], + [[4, 7, 7, 7], + [7, 5, 7, 7], + [7, 7, 6, 7]]] + + # A superdiagonal (per batch). + tf.matrix_set_diag(input, diagonal, k = 1) + ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4) + [7, 7, 2, 7], + [7, 7, 7, 3]], + [[7, 4, 7, 7], + [7, 7, 5, 7], + [7, 7, 7, 6]]] + + # A band of diagonals. + diagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3) + [6, 5, 8], + [1, 2, 3], + [4, 5, 0]], + [[0, 1, 2], + [5, 6, 4], + [6, 1, 2], + [3, 4, 0]]]) + tf.matrix_set_diag(input, diagonals, k = (-1, 2)) + ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4) + [4, 2, 5, 1], + [7, 5, 3, 8]], + [[6, 5, 1, 7], + [3, 1, 6, 2], + [7, 4, 2, 4]]] + + # LEFT_RIGHT alignment. + diagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3) + [6, 5, 8], + [1, 2, 3], + [0, 4, 5]], + [[1, 2, 0], + [5, 6, 4], + [6, 1, 2], + [0, 3, 4]]]) + tf.matrix_set_diag(input, diagonals, k = (-1, 2), align="LEFT_RIGHT") + ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4) + [4, 2, 5, 1], + [7, 5, 3, 8]], + [[6, 5, 1, 7], + [3, 1, 6, 2], + [7, 4, 2, 4]]] + + ``` + + Args: + input: A `Tensor`. Rank `r+1`, where `r >= 1`. + diagonal: A `Tensor`. Must have the same type as `input`. + Rank `r` when `k` is an integer or `k[0] == k[1]`. Otherwise, it has rank `r+1`. + `k >= 1`. + k: A `Tensor` of type `int32`. + Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main + diagonal, and negative value means subdiagonals. `k` can be a single integer + (for a single diagonal) or a pair of integers specifying the low and high ends + of a matrix band. `k[0]` must not be larger than `k[1]`. + align: An optional `string` from: `"LEFT_RIGHT", "RIGHT_LEFT", "LEFT_LEFT", "RIGHT_RIGHT"`. Defaults to `"RIGHT_LEFT"`. + Some diagonals are shorter than `max_diag_len` and need to be padded. `align` is + a string specifying how superdiagonals and subdiagonals should be aligned, + respectively. There are four possible alignments: "RIGHT_LEFT" (default), + "LEFT_RIGHT", "LEFT_LEFT", and "RIGHT_RIGHT". "RIGHT_LEFT" aligns superdiagonals + to the right (left-pads the row) and subdiagonals to the left (right-pads the + row). It is the packing format LAPACK uses. cuSPARSE uses "LEFT_RIGHT", which is + the opposite alignment. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSetDiagV3", name, input, diagonal, k, "align", align) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_set_diag_v3_eager_fallback( + input, diagonal, k, align=align, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSetDiagV3", input=input, diagonal=diagonal, k=k, align=align, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align", _op.get_attr("align")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSetDiagV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSetDiagV3 = tf_export("raw_ops.MatrixSetDiagV3")(_ops.to_raw_op(matrix_set_diag_v3)) + + +def matrix_set_diag_v3_eager_fallback(input: Annotated[Any, TV_MatrixSetDiagV3_T], diagonal: Annotated[Any, TV_MatrixSetDiagV3_T], k: Annotated[Any, _atypes.Int32], align: str, name, ctx) -> Annotated[Any, TV_MatrixSetDiagV3_T]: + if align is None: + align = "RIGHT_LEFT" + align = _execute.make_str(align, "align") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], ctx, []) + (input, diagonal) = _inputs_T + k = _ops.convert_to_tensor(k, _dtypes.int32) + _inputs_flat = [input, diagonal, k] + _attrs = ("T", _attr_T, "align", align) + _result = _execute.execute(b"MatrixSetDiagV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSetDiagV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MirrorPad_T = TypeVar("TV_MirrorPad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MirrorPad_Tpaddings = TypeVar("TV_MirrorPad_Tpaddings", _atypes.Int32, _atypes.Int64) + +def mirror_pad(input: Annotated[Any, TV_MirrorPad_T], paddings: Annotated[Any, TV_MirrorPad_Tpaddings], mode: str, name=None) -> Annotated[Any, TV_MirrorPad_T]: + r"""Pads a tensor with mirrored values. + + This operation pads a `input` with mirrored values according to the `paddings` + you specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is + the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates + how many values to add before the contents of `input` in that dimension, and + `paddings[D, 1]` indicates how many values to add after the contents of `input` + in that dimension. Both `paddings[D, 0]` and `paddings[D, 1]` must be no greater + than `input.dim_size(D)` (or `input.dim_size(D) - 1`) if `copy_border` is true + (if false, respectively). + + The padded size of each dimension D of the output is: + + `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` + + For example: + + ``` + # 't' is [[1, 2, 3], [4, 5, 6]]. + # 'paddings' is [[1, 1]], [2, 2]]. + # 'mode' is SYMMETRIC. + # rank of 't' is 2. + pad(t, paddings) ==> [[2, 1, 1, 2, 3, 3, 2] + [2, 1, 1, 2, 3, 3, 2] + [5, 4, 4, 5, 6, 6, 5] + [5, 4, 4, 5, 6, 6, 5]] + ``` + + Args: + input: A `Tensor`. The input tensor to be padded. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A two-column matrix specifying the padding sizes. The number of + rows must be the same as the rank of `input`. + mode: A `string` from: `"REFLECT", "SYMMETRIC"`. + Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions + do not include the borders, while in symmetric mode the padded regions + do include the borders. For example, if `input` is `[1, 2, 3]` and `paddings` + is `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and + it is `[1, 2, 3, 3, 2]` in symmetric mode. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MirrorPad", name, input, paddings, "mode", mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mirror_pad_eager_fallback( + input, paddings, mode=mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + mode = _execute.make_str(mode, "mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MirrorPad", input=input, paddings=paddings, mode=mode, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tpaddings", + _op._get_attr_type("Tpaddings"), "mode", _op.get_attr("mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MirrorPad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MirrorPad = tf_export("raw_ops.MirrorPad")(_ops.to_raw_op(mirror_pad)) + + +def mirror_pad_eager_fallback(input: Annotated[Any, TV_MirrorPad_T], paddings: Annotated[Any, TV_MirrorPad_Tpaddings], mode: str, name, ctx) -> Annotated[Any, TV_MirrorPad_T]: + mode = _execute.make_str(mode, "mode") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, paddings] + _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "mode", mode) + _result = _execute.execute(b"MirrorPad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MirrorPad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MirrorPadGrad_T = TypeVar("TV_MirrorPadGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MirrorPadGrad_Tpaddings = TypeVar("TV_MirrorPadGrad_Tpaddings", _atypes.Int32, _atypes.Int64) + +def mirror_pad_grad(input: Annotated[Any, TV_MirrorPadGrad_T], paddings: Annotated[Any, TV_MirrorPadGrad_Tpaddings], mode: str, name=None) -> Annotated[Any, TV_MirrorPadGrad_T]: + r"""Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor. + + This operation folds the padded areas of `input` by `MirrorPad` according to the + `paddings` you specify. `paddings` must be the same as `paddings` argument + given to the corresponding `MirrorPad` op. + + The folded size of each dimension D of the output is: + + `input.dim_size(D) - paddings(D, 0) - paddings(D, 1)` + + For example: + + ``` + # 't' is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. + # 'paddings' is [[0, 1]], [0, 1]]. + # 'mode' is SYMMETRIC. + # rank of 't' is 2. + pad(t, paddings) ==> [[ 1, 5] + [11, 28]] + ``` + + Args: + input: A `Tensor`. The input tensor to be folded. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A two-column matrix specifying the padding sizes. The number of + rows must be the same as the rank of `input`. + mode: A `string` from: `"REFLECT", "SYMMETRIC"`. + The mode used in the `MirrorPad` op. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MirrorPadGrad", name, input, paddings, "mode", mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mirror_pad_grad_eager_fallback( + input, paddings, mode=mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + mode = _execute.make_str(mode, "mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MirrorPadGrad", input=input, paddings=paddings, mode=mode, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tpaddings", + _op._get_attr_type("Tpaddings"), "mode", _op.get_attr("mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MirrorPadGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MirrorPadGrad = tf_export("raw_ops.MirrorPadGrad")(_ops.to_raw_op(mirror_pad_grad)) + + +def mirror_pad_grad_eager_fallback(input: Annotated[Any, TV_MirrorPadGrad_T], paddings: Annotated[Any, TV_MirrorPadGrad_Tpaddings], mode: str, name, ctx) -> Annotated[Any, TV_MirrorPadGrad_T]: + mode = _execute.make_str(mode, "mode") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, paddings] + _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "mode", mode) + _result = _execute.execute(b"MirrorPadGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MirrorPadGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_OneHot_T = TypeVar("TV_OneHot_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_OneHot_TI = TypeVar("TV_OneHot_TI", _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) + +def one_hot(indices: Annotated[Any, TV_OneHot_TI], depth: Annotated[Any, _atypes.Int32], on_value: Annotated[Any, TV_OneHot_T], off_value: Annotated[Any, TV_OneHot_T], axis:int=-1, name=None) -> Annotated[Any, TV_OneHot_T]: + r"""Returns a one-hot tensor. + + The locations represented by indices in `indices` take value `on_value`, + while all other locations take value `off_value`. + + If the input `indices` is rank `N`, the output will have rank `N+1`, + The new axis is created at dimension `axis` (default: the new axis is + appended at the end). + + If `indices` is a scalar the output shape will be a vector of length `depth`. + + If `indices` is a vector of length `features`, the output shape will be: + ``` + features x depth if axis == -1 + depth x features if axis == 0 + ``` + + If `indices` is a matrix (batch) with shape `[batch, features]`, + the output shape will be: + ``` + batch x features x depth if axis == -1 + batch x depth x features if axis == 1 + depth x batch x features if axis == 0 + ``` + + + Examples + ========= + + Suppose that + ``` + indices = [0, 2, -1, 1] + depth = 3 + on_value = 5.0 + off_value = 0.0 + axis = -1 + ``` + + Then output is `[4 x 3]`: + ``` + output = + [5.0 0.0 0.0] // one_hot(0) + [0.0 0.0 5.0] // one_hot(2) + [0.0 0.0 0.0] // one_hot(-1) + [0.0 5.0 0.0] // one_hot(1) + ``` + + Suppose that + ``` + indices = [0, 2, -1, 1] + depth = 3 + on_value = 0.0 + off_value = 3.0 + axis = 0 + ``` + + Then output is `[3 x 4]`: + ``` + output = + [0.0 3.0 3.0 3.0] + [3.0 3.0 3.0 0.0] + [3.0 3.0 3.0 3.0] + [3.0 0.0 3.0 3.0] + // ^ one_hot(0) + // ^ one_hot(2) + // ^ one_hot(-1) + // ^ one_hot(1) + ``` + + Suppose that + ``` + indices = [[0, 2], [1, -1]] + depth = 3 + on_value = 1.0 + off_value = 0.0 + axis = -1 + ``` + + Then output is `[2 x 2 x 3]`: + ``` + output = + [ + [1.0, 0.0, 0.0] // one_hot(0) + [0.0, 0.0, 1.0] // one_hot(2) + ][ + [0.0, 1.0, 0.0] // one_hot(1) + [0.0, 0.0, 0.0] // one_hot(-1) + ] + ``` + + Args: + indices: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int32`, `int64`. + A tensor of indices. + depth: A `Tensor` of type `int32`. + A scalar defining the depth of the one hot dimension. + on_value: A `Tensor`. + A scalar defining the value to fill in output when `indices[j] = i`. + off_value: A `Tensor`. Must have the same type as `on_value`. + A scalar defining the value to fill in output when `indices[j] != i`. + axis: An optional `int`. Defaults to `-1`. + The axis to fill (default: -1, a new inner-most axis). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `on_value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OneHot", name, indices, depth, on_value, off_value, "axis", + axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return one_hot_eager_fallback( + indices, depth, on_value, off_value, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OneHot", indices=indices, depth=depth, on_value=on_value, + off_value=off_value, axis=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("axis", _op._get_attr_int("axis"), "T", _op._get_attr_type("T"), + "TI", _op._get_attr_type("TI")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OneHot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OneHot = tf_export("raw_ops.OneHot")(_ops.to_raw_op(one_hot)) + + +def one_hot_eager_fallback(indices: Annotated[Any, TV_OneHot_TI], depth: Annotated[Any, _atypes.Int32], on_value: Annotated[Any, TV_OneHot_T], off_value: Annotated[Any, TV_OneHot_T], axis: int, name, ctx) -> Annotated[Any, TV_OneHot_T]: + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([on_value, off_value], ctx, []) + (on_value, off_value) = _inputs_T + _attr_TI, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int32, _dtypes.int64, ], _dtypes.int64) + depth = _ops.convert_to_tensor(depth, _dtypes.int32) + _inputs_flat = [indices, depth, on_value, off_value] + _attrs = ("axis", axis, "T", _attr_T, "TI", _attr_TI) + _result = _execute.execute(b"OneHot", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OneHot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_OnesLike_T = TypeVar("TV_OnesLike_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def ones_like(x: Annotated[Any, TV_OnesLike_T], name=None) -> Annotated[Any, TV_OnesLike_T]: + r"""Returns a tensor of ones with the same shape and type as x. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`, `complex64`, `complex128`, `bool`. + a tensor of type T. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OnesLike", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ones_like_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OnesLike", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OnesLike", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OnesLike = tf_export("raw_ops.OnesLike")(_ops.to_raw_op(ones_like)) + + +def ones_like_eager_fallback(x: Annotated[Any, TV_OnesLike_T], name, ctx) -> Annotated[Any, TV_OnesLike_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, _dtypes.bool, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"OnesLike", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OnesLike", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Pack_T = TypeVar("TV_Pack_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def pack(values: Annotated[List[Any], TV_Pack_T], axis:int=0, name=None) -> Annotated[Any, TV_Pack_T]: + r"""Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor. + + Packs the `N` tensors in `values` into a tensor with rank one higher than each + tensor in `values`, by packing them along the `axis` dimension. + Given a list of tensors of shape `(A, B, C)`; + + if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. + if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. + Etc. + + For example: + + ``` + # 'x' is [1, 4] + # 'y' is [2, 5] + # 'z' is [3, 6] + pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. + pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]] + ``` + + This is the opposite of `unpack`. + + Args: + values: A list of at least 1 `Tensor` objects with the same type. + Must be of same shape and type. + axis: An optional `int`. Defaults to `0`. + Dimension along which to pack. Negative values wrap around, so the + valid range is `[-(R+1), R+1)`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Pack", name, values, "axis", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return pack_eager_fallback( + values, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'pack' Op, not %r." % values) + _attr_N = len(values) + if axis is None: + axis = 0 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Pack", values=values, axis=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "axis", _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Pack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Pack = tf_export("raw_ops.Pack")(_ops.to_raw_op(pack)) + + +def pack_eager_fallback(values: Annotated[List[Any], TV_Pack_T], axis: int, name, ctx) -> Annotated[Any, TV_Pack_T]: + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'pack' Op, not %r." % values) + _attr_N = len(values) + if axis is None: + axis = 0 + axis = _execute.make_int(axis, "axis") + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + _inputs_flat = list(values) + _attrs = ("N", _attr_N, "T", _attr_T, "axis", axis) + _result = _execute.execute(b"Pack", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Pack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Pad_T = TypeVar("TV_Pad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Pad_Tpaddings = TypeVar("TV_Pad_Tpaddings", _atypes.Int32, _atypes.Int64) + +def pad(input: Annotated[Any, TV_Pad_T], paddings: Annotated[Any, TV_Pad_Tpaddings], name=None) -> Annotated[Any, TV_Pad_T]: + r"""Pads a tensor with zeros. + + This operation pads a `input` with zeros according to the `paddings` you + specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the + rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates + how many zeros to add before the contents of `input` in that dimension, and + `paddings[D, 1]` indicates how many zeros to add after the contents of `input` + in that dimension. + + The padded size of each dimension D of the output is: + + `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` + + For example: + + ``` + # 't' is [[1, 1], [2, 2]] + # 'paddings' is [[1, 1], [2, 2]] + # rank of 't' is 2 + pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] + [0, 0, 1, 1, 0, 0] + [0, 0, 2, 2, 0, 0] + [0, 0, 0, 0, 0, 0]] + ``` + + Args: + input: A `Tensor`. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Pad", name, input, paddings) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return pad_eager_fallback( + input, paddings, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Pad", input=input, paddings=paddings, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tpaddings", + _op._get_attr_type("Tpaddings")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Pad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Pad = tf_export("raw_ops.Pad")(_ops.to_raw_op(pad)) + + +def pad_eager_fallback(input: Annotated[Any, TV_Pad_T], paddings: Annotated[Any, TV_Pad_Tpaddings], name, ctx) -> Annotated[Any, TV_Pad_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, paddings] + _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings) + _result = _execute.execute(b"Pad", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Pad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PadV2_T = TypeVar("TV_PadV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_PadV2_Tpaddings = TypeVar("TV_PadV2_Tpaddings", _atypes.Int32, _atypes.Int64) + +def pad_v2(input: Annotated[Any, TV_PadV2_T], paddings: Annotated[Any, TV_PadV2_Tpaddings], constant_values: Annotated[Any, TV_PadV2_T], name=None) -> Annotated[Any, TV_PadV2_T]: + r"""Pads a tensor. + + This operation pads `input` according to the `paddings` and `constant_values` + you specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is + the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates + how many padding values to add before the contents of `input` in that dimension, + and `paddings[D, 1]` indicates how many padding values to add after the contents + of `input` in that dimension. `constant_values` is a scalar tensor of the same + type as `input` that indicates the value to use for padding `input`. + + The padded size of each dimension D of the output is: + + `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` + + For example: + + ``` + # 't' is [[1, 1], [2, 2]] + # 'paddings' is [[1, 1], [2, 2]] + # 'constant_values' is 0 + # rank of 't' is 2 + pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] + [0, 0, 1, 1, 0, 0] + [0, 0, 2, 2, 0, 0] + [0, 0, 0, 0, 0, 0]] + ``` + + Args: + input: A `Tensor`. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + constant_values: A `Tensor`. Must have the same type as `input`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PadV2", name, input, paddings, constant_values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return pad_v2_eager_fallback( + input, paddings, constant_values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PadV2", input=input, paddings=paddings, + constant_values=constant_values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tpaddings", + _op._get_attr_type("Tpaddings")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PadV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PadV2 = tf_export("raw_ops.PadV2")(_ops.to_raw_op(pad_v2)) + + +def pad_v2_eager_fallback(input: Annotated[Any, TV_PadV2_T], paddings: Annotated[Any, TV_PadV2_Tpaddings], constant_values: Annotated[Any, TV_PadV2_T], name, ctx) -> Annotated[Any, TV_PadV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, constant_values], ctx, []) + (input, constant_values) = _inputs_T + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, paddings, constant_values] + _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings) + _result = _execute.execute(b"PadV2", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PadV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ParallelConcat_T = TypeVar("TV_ParallelConcat_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def parallel_concat(values: Annotated[List[Any], TV_ParallelConcat_T], shape, name=None) -> Annotated[Any, TV_ParallelConcat_T]: + r"""Concatenates a list of `N` tensors along the first dimension. + + The input tensors are all required to have size 1 in the first dimension. + + For example: + + ``` + # 'x' is [[1, 4]] + # 'y' is [[2, 5]] + # 'z' is [[3, 6]] + parallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. + ``` + + The difference between concat and parallel_concat is that concat requires all + of the inputs be computed before the operation will begin but doesn't require + that the input shapes be known during graph construction. Parallel concat + will copy pieces of the input into the output as they become available, in + some situations this can provide a performance benefit. + + Args: + values: A list of at least 1 `Tensor` objects with the same type. + Tensors to be concatenated. All must have size 1 in the first dimension + and same shape. + shape: A `tf.TensorShape` or list of `ints`. + the final shape of the result; should be equal to the shapes of any input + but with the number of input values in the first dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelConcat", name, values, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_concat_eager_fallback( + values, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'parallel_concat' Op, not %r." % values) + _attr_N = len(values) + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelConcat", values=values, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "shape", _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelConcat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelConcat = tf_export("raw_ops.ParallelConcat")(_ops.to_raw_op(parallel_concat)) + + +def parallel_concat_eager_fallback(values: Annotated[List[Any], TV_ParallelConcat_T], shape, name, ctx) -> Annotated[Any, TV_ParallelConcat_T]: + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'parallel_concat' Op, not %r." % values) + _attr_N = len(values) + shape = _execute.make_shape(shape, "shape") + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + _inputs_flat = list(values) + _attrs = ("N", _attr_N, "T", _attr_T, "shape", shape) + _result = _execute.execute(b"ParallelConcat", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelConcat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Placeholder_dtype = TypeVar("TV_Placeholder_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def placeholder(dtype: TV_Placeholder_dtype, shape=None, name=None) -> Annotated[Any, TV_Placeholder_dtype]: + r"""A placeholder op for a value that will be fed into the computation. + + N.B. This operation will fail with an error if it is executed. It is + intended as a way to represent a value that will always be fed, and to + provide attrs that enable the fed value to be checked at runtime. + + Args: + dtype: A `tf.DType`. The type of elements in the tensor. + shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + (Optional) The shape of the tensor. If the shape has 0 dimensions, the + shape is unconstrained. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Placeholder", name, "dtype", dtype, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return placeholder_eager_fallback( + dtype=dtype, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if shape is None: + shape = None + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Placeholder", dtype=dtype, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Placeholder", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Placeholder = tf_export("raw_ops.Placeholder")(_ops.to_raw_op(placeholder)) + + +def placeholder_eager_fallback(dtype: TV_Placeholder_dtype, shape, name, ctx) -> Annotated[Any, TV_Placeholder_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if shape is None: + shape = None + shape = _execute.make_shape(shape, "shape") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape) + _result = _execute.execute(b"Placeholder", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Placeholder", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PlaceholderV2_dtype = TypeVar("TV_PlaceholderV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def placeholder_v2(dtype: TV_PlaceholderV2_dtype, shape, name=None) -> Annotated[Any, TV_PlaceholderV2_dtype]: + r"""A placeholder op for a value that will be fed into the computation. + + N.B. This operation will fail with an error if it is executed. It is + intended as a way to represent a value that will always be fed, and to + provide attrs that enable the fed value to be checked at runtime. + + Args: + dtype: A `tf.DType`. The type of elements in the tensor. + shape: A `tf.TensorShape` or list of `ints`. + The shape of the tensor. The shape can be any partially-specified + shape. To be unconstrained, pass in a shape with unknown rank. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PlaceholderV2", name, "dtype", dtype, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return placeholder_v2_eager_fallback( + dtype=dtype, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PlaceholderV2", dtype=dtype, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PlaceholderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PlaceholderV2 = tf_export("raw_ops.PlaceholderV2")(_ops.to_raw_op(placeholder_v2)) + + +def placeholder_v2_eager_fallback(dtype: TV_PlaceholderV2_dtype, shape, name, ctx) -> Annotated[Any, TV_PlaceholderV2_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape) + _result = _execute.execute(b"PlaceholderV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PlaceholderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PlaceholderWithDefault_dtype = TypeVar("TV_PlaceholderWithDefault_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def placeholder_with_default(input: Annotated[Any, TV_PlaceholderWithDefault_dtype], shape, name=None) -> Annotated[Any, TV_PlaceholderWithDefault_dtype]: + r"""A placeholder op that passes through `input` when its output is not fed. + + Args: + input: A `Tensor`. The default value to produce when `output` is not fed. + shape: A `tf.TensorShape` or list of `ints`. + The (possibly partial) shape of the tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PlaceholderWithDefault", name, input, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return placeholder_with_default_eager_fallback( + input, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PlaceholderWithDefault", input=input, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PlaceholderWithDefault", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PlaceholderWithDefault = tf_export("raw_ops.PlaceholderWithDefault")(_ops.to_raw_op(placeholder_with_default)) + + +def placeholder_with_default_eager_fallback(input: Annotated[Any, TV_PlaceholderWithDefault_dtype], shape, name, ctx) -> Annotated[Any, TV_PlaceholderWithDefault_dtype]: + shape = _execute.make_shape(shape, "shape") + _attr_dtype, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("dtype", _attr_dtype, "shape", shape) + _result = _execute.execute(b"PlaceholderWithDefault", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PlaceholderWithDefault", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PreventGradient_T = TypeVar("TV_PreventGradient_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def prevent_gradient(input: Annotated[Any, TV_PreventGradient_T], message:str="", name=None) -> Annotated[Any, TV_PreventGradient_T]: + r"""An identity op that triggers an error if a gradient is requested. + + When executed in a graph, this op outputs its input tensor as-is. + + When building ops to compute gradients, the TensorFlow gradient system + will return an error when trying to lookup the gradient of this op, + because no gradient must ever be registered for this function. This + op exists to prevent subtle bugs from silently returning unimplemented + gradients in some corner cases. + + Args: + input: A `Tensor`. any tensor. + message: An optional `string`. Defaults to `""`. + Will be printed in the error when anyone tries to differentiate + this operation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PreventGradient", name, input, "message", message) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return prevent_gradient_eager_fallback( + input, message=message, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if message is None: + message = "" + message = _execute.make_str(message, "message") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PreventGradient", input=input, message=message, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "message", + _op.get_attr("message")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PreventGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PreventGradient = tf_export("raw_ops.PreventGradient")(_ops.to_raw_op(prevent_gradient)) + + +def prevent_gradient_eager_fallback(input: Annotated[Any, TV_PreventGradient_T], message: str, name, ctx) -> Annotated[Any, TV_PreventGradient_T]: + if message is None: + message = "" + message = _execute.make_str(message, "message") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "message", message) + _result = _execute.execute(b"PreventGradient", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PreventGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_QuantizeAndDequantize_T = TypeVar("TV_QuantizeAndDequantize_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def quantize_and_dequantize(input: Annotated[Any, TV_QuantizeAndDequantize_T], signed_input:bool=True, num_bits:int=8, range_given:bool=False, input_min:float=0, input_max:float=0, name=None) -> Annotated[Any, TV_QuantizeAndDequantize_T]: + r"""Use QuantizeAndDequantizeV2 instead. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + signed_input: An optional `bool`. Defaults to `True`. + num_bits: An optional `int`. Defaults to `8`. + range_given: An optional `bool`. Defaults to `False`. + input_min: An optional `float`. Defaults to `0`. + input_max: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeAndDequantize", name, input, "signed_input", + signed_input, "num_bits", num_bits, "range_given", range_given, + "input_min", input_min, "input_max", input_max) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_and_dequantize_eager_fallback( + input, signed_input=signed_input, num_bits=num_bits, + range_given=range_given, input_min=input_min, input_max=input_max, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if input_min is None: + input_min = 0 + input_min = _execute.make_float(input_min, "input_min") + if input_max is None: + input_max = 0 + input_max = _execute.make_float(input_max, "input_max") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeAndDequantize", input=input, signed_input=signed_input, + num_bits=num_bits, range_given=range_given, + input_min=input_min, input_max=input_max, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("signed_input", _op._get_attr_bool("signed_input"), "num_bits", + _op._get_attr_int("num_bits"), "range_given", + _op._get_attr_bool("range_given"), "input_min", + _op.get_attr("input_min"), "input_max", + _op.get_attr("input_max"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeAndDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QuantizeAndDequantize = tf_export("raw_ops.QuantizeAndDequantize")(_ops.to_raw_op(quantize_and_dequantize)) + + +def quantize_and_dequantize_eager_fallback(input: Annotated[Any, TV_QuantizeAndDequantize_T], signed_input: bool, num_bits: int, range_given: bool, input_min: float, input_max: float, name, ctx) -> Annotated[Any, TV_QuantizeAndDequantize_T]: + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if input_min is None: + input_min = 0 + input_min = _execute.make_float(input_min, "input_min") + if input_max is None: + input_max = 0 + input_max = _execute.make_float(input_max, "input_max") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [input] + _attrs = ("signed_input", signed_input, "num_bits", num_bits, "range_given", + range_given, "input_min", input_min, "input_max", input_max, "T", _attr_T) + _result = _execute.execute(b"QuantizeAndDequantize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeAndDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_QuantizeAndDequantizeV2_T = TypeVar("TV_QuantizeAndDequantizeV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def quantize_and_dequantize_v2(input: Annotated[Any, TV_QuantizeAndDequantizeV2_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV2_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV2_T], signed_input:bool=True, num_bits:int=8, range_given:bool=False, round_mode:str="HALF_TO_EVEN", narrow_range:bool=False, axis:int=-1, name=None) -> Annotated[Any, TV_QuantizeAndDequantizeV2_T]: + r"""Quantizes then dequantizes a tensor. + + This op simulates the precision loss from the quantized forward pass by: + + 1. Quantizing the tensor to fixed point numbers, which should match the target + quantization method when it is used in inference. + 2. Dequantizing it back to floating point numbers for the following ops, most + likely matmul. + + There are different ways to quantize. This version uses only scaling, so 0.0 + maps to 0. + + From the specified 'num_bits' in the quantized output type, it determines + minimum and maximum representable quantized values. + + e.g. + + * [-128, 127] for signed, num_bits = 8, or + * [0, 255] for unsigned, num_bits = 8. + + If range_given == False, the initial input_min, input_max will be determined + automatically as the minimum and maximum values in the input tensor, otherwise + the specified values of input_min, input_max are used. + + Note: If the input_min, input_max are specified, they do not need to equal the + actual minimum and maximum values in the tensor. e.g. in some cases it may be + beneficial to specify these values such that the low probability extremes of the + input distribution are clipped. + + This op determines the maximum scale_factor that would map the initial + [input_min, input_max] range to a range that lies within the representable + quantized range. + + It determines the scale from one of input_min and input_max, then updates the + other one to maximize the representable range. + + e.g. + + * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, + 5.0]: it would use a scale_factor of -128 / -10.0 = 12.8 In this case, it + would update input_max to be 127 / 12.8 = 9.921875 + * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, + 10.0]: it would use a scale_factor of 127 / 10.0 = 12.7 In this case, it + would update input_min to be 128.0 / 12.7 = -10.07874 + * if the output is unsigned, input_min is forced to be 0, and only the + specified input_max is used. + + After determining the scale_factor and updating the input range, it applies the + following to each value in the 'input' tensor. + + output = round(clamp(value, input_min, input_max) * scale_factor) / scale_factor. + + The above round function rounds the value based on the given round_mode. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + Tensor to quantize and then dequantize. + input_min: A `Tensor`. Must have the same type as `input`. + If `range_given == True`, this specifies the minimum input value that needs to + be represented, otherwise it is determined from the min value of the `input` + tensor. + input_max: A `Tensor`. Must have the same type as `input`. + If `range_given == True`, this specifies the maximum input value that needs to + be represented, otherwise it is determined from the max value of the `input` + tensor. + signed_input: An optional `bool`. Defaults to `True`. + Whether the quantization is signed or unsigned. (actually this parameter should + have been called `signed_output`) + num_bits: An optional `int`. Defaults to `8`. + The bitwidth of the quantization. + range_given: An optional `bool`. Defaults to `False`. + Whether the range is given or should be determined from the `input` tensor. + round_mode: An optional `string` from: `"HALF_TO_EVEN", "HALF_UP"`. Defaults to `"HALF_TO_EVEN"`. + The 'round_mode' attribute controls which rounding tie-breaking algorithm is + used when rounding float values to their quantized equivalents. The following + rounding modes are currently supported: + + * HALF_TO_EVEN: this is the default round_mode. + * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 + rounds up to -7. + narrow_range: An optional `bool`. Defaults to `False`. + If True, then the absolute value of the quantized minimum value is the same as + the quantized maximum value, instead of 1 greater. + i.e. for 8 bit quantization, the minimum value is -127 instead of -128. + axis: An optional `int`. Defaults to `-1`. + If specified, this axis is treated as a channel or slice axis, and a separate + quantization range is used for each channel or slice along this axis. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeAndDequantizeV2", name, input, input_min, input_max, + "signed_input", signed_input, "num_bits", num_bits, "range_given", + range_given, "round_mode", round_mode, "narrow_range", narrow_range, + "axis", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_and_dequantize_v2_eager_fallback( + input, input_min, input_max, signed_input=signed_input, + num_bits=num_bits, range_given=range_given, round_mode=round_mode, + narrow_range=narrow_range, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if round_mode is None: + round_mode = "HALF_TO_EVEN" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeAndDequantizeV2", input=input, input_min=input_min, + input_max=input_max, + signed_input=signed_input, + num_bits=num_bits, range_given=range_given, + round_mode=round_mode, + narrow_range=narrow_range, axis=axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("signed_input", _op._get_attr_bool("signed_input"), "num_bits", + _op._get_attr_int("num_bits"), "range_given", + _op._get_attr_bool("range_given"), "T", _op._get_attr_type("T"), + "round_mode", _op.get_attr("round_mode"), "narrow_range", + _op._get_attr_bool("narrow_range"), "axis", + _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeAndDequantizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QuantizeAndDequantizeV2 = tf_export("raw_ops.QuantizeAndDequantizeV2")(_ops.to_raw_op(quantize_and_dequantize_v2)) + + +def quantize_and_dequantize_v2_eager_fallback(input: Annotated[Any, TV_QuantizeAndDequantizeV2_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV2_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV2_T], signed_input: bool, num_bits: int, range_given: bool, round_mode: str, narrow_range: bool, axis: int, name, ctx) -> Annotated[Any, TV_QuantizeAndDequantizeV2_T]: + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if round_mode is None: + round_mode = "HALF_TO_EVEN" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_min, input_max], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_min, input_max) = _inputs_T + _inputs_flat = [input, input_min, input_max] + _attrs = ("signed_input", signed_input, "num_bits", num_bits, "range_given", + range_given, "T", _attr_T, "round_mode", round_mode, "narrow_range", + narrow_range, "axis", axis) + _result = _execute.execute(b"QuantizeAndDequantizeV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeAndDequantizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_QuantizeAndDequantizeV3_T = TypeVar("TV_QuantizeAndDequantizeV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def quantize_and_dequantize_v3(input: Annotated[Any, TV_QuantizeAndDequantizeV3_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV3_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV3_T], num_bits: Annotated[Any, _atypes.Int32], signed_input:bool=True, range_given:bool=True, narrow_range:bool=False, axis:int=-1, name=None) -> Annotated[Any, TV_QuantizeAndDequantizeV3_T]: + r"""Quantizes then dequantizes a tensor. + + This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a + tensor, so its value can change during training. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_min: A `Tensor`. Must have the same type as `input`. + input_max: A `Tensor`. Must have the same type as `input`. + num_bits: A `Tensor` of type `int32`. + signed_input: An optional `bool`. Defaults to `True`. + range_given: An optional `bool`. Defaults to `True`. + narrow_range: An optional `bool`. Defaults to `False`. + axis: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeAndDequantizeV3", name, input, input_min, input_max, + num_bits, "signed_input", signed_input, "range_given", range_given, + "narrow_range", narrow_range, "axis", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_and_dequantize_v3_eager_fallback( + input, input_min, input_max, num_bits, signed_input=signed_input, + range_given=range_given, narrow_range=narrow_range, axis=axis, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if range_given is None: + range_given = True + range_given = _execute.make_bool(range_given, "range_given") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeAndDequantizeV3", input=input, input_min=input_min, + input_max=input_max, num_bits=num_bits, + signed_input=signed_input, + range_given=range_given, + narrow_range=narrow_range, axis=axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("signed_input", _op._get_attr_bool("signed_input"), + "range_given", _op._get_attr_bool("range_given"), "T", + _op._get_attr_type("T"), "narrow_range", + _op._get_attr_bool("narrow_range"), "axis", + _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeAndDequantizeV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QuantizeAndDequantizeV3 = tf_export("raw_ops.QuantizeAndDequantizeV3")(_ops.to_raw_op(quantize_and_dequantize_v3)) + + +def quantize_and_dequantize_v3_eager_fallback(input: Annotated[Any, TV_QuantizeAndDequantizeV3_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV3_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV3_T], num_bits: Annotated[Any, _atypes.Int32], signed_input: bool, range_given: bool, narrow_range: bool, axis: int, name, ctx) -> Annotated[Any, TV_QuantizeAndDequantizeV3_T]: + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if range_given is None: + range_given = True + range_given = _execute.make_bool(range_given, "range_given") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_min, input_max], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_min, input_max) = _inputs_T + num_bits = _ops.convert_to_tensor(num_bits, _dtypes.int32) + _inputs_flat = [input, input_min, input_max, num_bits] + _attrs = ("signed_input", signed_input, "range_given", range_given, "T", + _attr_T, "narrow_range", narrow_range, "axis", axis) + _result = _execute.execute(b"QuantizeAndDequantizeV3", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeAndDequantizeV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_QuantizeAndDequantizeV4_T = TypeVar("TV_QuantizeAndDequantizeV4_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def quantize_and_dequantize_v4(input: Annotated[Any, TV_QuantizeAndDequantizeV4_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV4_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV4_T], signed_input:bool=True, num_bits:int=8, range_given:bool=False, round_mode:str="HALF_TO_EVEN", narrow_range:bool=False, axis:int=-1, name=None) -> Annotated[Any, TV_QuantizeAndDequantizeV4_T]: + r"""Quantizes then dequantizes a tensor. + + This is almost identical to QuantizeAndDequantizeV2, except that it returns a + gradient of 1 for inputs that are within the quantization range, or 0 otherwise. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + Tensor to quantize and then dequantize. + input_min: A `Tensor`. Must have the same type as `input`. + If `range_given == True`, this specifies the minimum input value that needs to + be represented, otherwise it is determined from the min value of the `input` + tensor. + input_max: A `Tensor`. Must have the same type as `input`. + If `range_given == True`, this specifies the maximum input value that needs to + be represented, otherwise it is determined from the max value of the `input` + tensor. + signed_input: An optional `bool`. Defaults to `True`. + Whether the quantization is signed or unsigned. (actually this parameter should + have been called `signed_output`) + num_bits: An optional `int`. Defaults to `8`. + The bitwidth of the quantization. + range_given: An optional `bool`. Defaults to `False`. + Whether the range is given or should be determined from the `input` tensor. + round_mode: An optional `string` from: `"HALF_TO_EVEN", "HALF_UP"`. Defaults to `"HALF_TO_EVEN"`. + The 'round_mode' attribute controls which rounding tie-breaking algorithm is + used when rounding float values to their quantized equivalents. The following + rounding modes are currently supported: + + * HALF_TO_EVEN: this is the default round_mode. + * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 + rounds up to -7. + narrow_range: An optional `bool`. Defaults to `False`. + If True, then the absolute value of the quantized minimum value is the same as + the quantized maximum value, instead of 1 greater. + i.e. for 8 bit quantization, the minimum value is -127 instead of -128. + axis: An optional `int`. Defaults to `-1`. + If specified, this axis is treated as a channel or slice axis, and a separate + quantization range is used for each channel or slice along this axis. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeAndDequantizeV4", name, input, input_min, input_max, + "signed_input", signed_input, "num_bits", num_bits, "range_given", + range_given, "round_mode", round_mode, "narrow_range", narrow_range, + "axis", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_and_dequantize_v4_eager_fallback( + input, input_min, input_max, signed_input=signed_input, + num_bits=num_bits, range_given=range_given, round_mode=round_mode, + narrow_range=narrow_range, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if round_mode is None: + round_mode = "HALF_TO_EVEN" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeAndDequantizeV4", input=input, input_min=input_min, + input_max=input_max, + signed_input=signed_input, + num_bits=num_bits, range_given=range_given, + round_mode=round_mode, + narrow_range=narrow_range, axis=axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("signed_input", _op._get_attr_bool("signed_input"), "num_bits", + _op._get_attr_int("num_bits"), "range_given", + _op._get_attr_bool("range_given"), "T", _op._get_attr_type("T"), + "round_mode", _op.get_attr("round_mode"), "narrow_range", + _op._get_attr_bool("narrow_range"), "axis", + _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeAndDequantizeV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QuantizeAndDequantizeV4 = tf_export("raw_ops.QuantizeAndDequantizeV4")(_ops.to_raw_op(quantize_and_dequantize_v4)) + + +def quantize_and_dequantize_v4_eager_fallback(input: Annotated[Any, TV_QuantizeAndDequantizeV4_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV4_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV4_T], signed_input: bool, num_bits: int, range_given: bool, round_mode: str, narrow_range: bool, axis: int, name, ctx) -> Annotated[Any, TV_QuantizeAndDequantizeV4_T]: + if signed_input is None: + signed_input = True + signed_input = _execute.make_bool(signed_input, "signed_input") + if num_bits is None: + num_bits = 8 + num_bits = _execute.make_int(num_bits, "num_bits") + if range_given is None: + range_given = False + range_given = _execute.make_bool(range_given, "range_given") + if round_mode is None: + round_mode = "HALF_TO_EVEN" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_min, input_max], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_min, input_max) = _inputs_T + _inputs_flat = [input, input_min, input_max] + _attrs = ("signed_input", signed_input, "num_bits", num_bits, "range_given", + range_given, "T", _attr_T, "round_mode", round_mode, "narrow_range", + narrow_range, "axis", axis) + _result = _execute.execute(b"QuantizeAndDequantizeV4", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeAndDequantizeV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QuantizeAndDequantizeV4GradOutput = collections.namedtuple( + "QuantizeAndDequantizeV4Grad", + ["input_backprop", "input_min_backprop", "input_max_backprop"]) + + +TV_QuantizeAndDequantizeV4Grad_T = TypeVar("TV_QuantizeAndDequantizeV4Grad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def quantize_and_dequantize_v4_grad(gradients: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], axis:int=-1, name=None): + r"""Returns the gradient of `QuantizeAndDequantizeV4`. + + Returns a gradient of 1 for inputs that are within the quantization range, + or 0 otherwise. + + Args: + gradients: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input: A `Tensor`. Must have the same type as `gradients`. + input_min: A `Tensor`. Must have the same type as `gradients`. + input_max: A `Tensor`. Must have the same type as `gradients`. + axis: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (input_backprop, input_min_backprop, input_max_backprop). + + input_backprop: A `Tensor`. Has the same type as `gradients`. + input_min_backprop: A `Tensor`. Has the same type as `gradients`. + input_max_backprop: A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeAndDequantizeV4Grad", name, gradients, input, + input_min, input_max, "axis", axis) + _result = _QuantizeAndDequantizeV4GradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_and_dequantize_v4_grad_eager_fallback( + gradients, input, input_min, input_max, axis=axis, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeAndDequantizeV4Grad", gradients=gradients, input=input, + input_min=input_min, + input_max=input_max, axis=axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "axis", _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeAndDequantizeV4Grad", _inputs_flat, _attrs, _result) + _result = _QuantizeAndDequantizeV4GradOutput._make(_result) + return _result + +QuantizeAndDequantizeV4Grad = tf_export("raw_ops.QuantizeAndDequantizeV4Grad")(_ops.to_raw_op(quantize_and_dequantize_v4_grad)) + + +def quantize_and_dequantize_v4_grad_eager_fallback(gradients: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input_min: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], input_max: Annotated[Any, TV_QuantizeAndDequantizeV4Grad_T], axis: int, name, ctx): + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, input, input_min, input_max], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (gradients, input, input_min, input_max) = _inputs_T + _inputs_flat = [gradients, input, input_min, input_max] + _attrs = ("T", _attr_T, "axis", axis) + _result = _execute.execute(b"QuantizeAndDequantizeV4Grad", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeAndDequantizeV4Grad", _inputs_flat, _attrs, _result) + _result = _QuantizeAndDequantizeV4GradOutput._make(_result) + return _result + +_QuantizeV2Output = collections.namedtuple( + "QuantizeV2", + ["output", "output_min", "output_max"]) + + +TV_QuantizeV2_T = TypeVar("TV_QuantizeV2_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantize_v2(input: Annotated[Any, _atypes.Float32], min_range: Annotated[Any, _atypes.Float32], max_range: Annotated[Any, _atypes.Float32], T: TV_QuantizeV2_T, mode:str="MIN_COMBINED", round_mode:str="HALF_AWAY_FROM_ZERO", narrow_range:bool=False, axis:int=-1, ensure_minimum_range:float=0.01, name=None): + r"""Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. + + [min_range, max_range] are scalar floats that specify the range for + the 'input' data. The 'mode' attribute controls exactly which calculations are + used to convert the float values to their quantized equivalents. The + 'round_mode' attribute controls which rounding tie-breaking algorithm is used + when rounding float values to their quantized equivalents. + + In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: + + ``` + out[i] = (in[i] - min_range) * range(T) / (max_range - min_range) + if T == qint8: out[i] -= (range(T) + 1) / 2.0 + ``` + + here `range(T) = numeric_limits::max() - numeric_limits::min()` + + *MIN_COMBINED Mode Example* + + Assume the input is type float and has a possible range of [0.0, 6.0] and the + output type is quint8 ([0, 255]). The min_range and max_range values should be + specified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each + value of the input by 255/6 and cast to quint8. + + If the output type was qint8 ([-128, 127]), the operation will additionally + subtract each value by 128 prior to casting, so that the range of values aligns + with the range of qint8. + + If the mode is 'MIN_FIRST', then this approach is used: + + ``` + num_discrete_values = 1 << (# of bits in T) + range_adjust = num_discrete_values / (num_discrete_values - 1) + range = (range_max - range_min) * range_adjust + range_scale = num_discrete_values / range + quantized = round(input * range_scale) - round(range_min * range_scale) + + numeric_limits::min() + quantized = max(quantized, numeric_limits::min()) + quantized = min(quantized, numeric_limits::max()) + ``` + + The biggest difference between this and MIN_COMBINED is that the minimum range + is rounded first, before it's subtracted from the rounded value. With + MIN_COMBINED, a small bias is introduced where repeated iterations of quantizing + and dequantizing will introduce a larger and larger error. + + *SCALED mode Example* + + `SCALED` mode matches the quantization approach used in + `QuantizeAndDequantize{V2|V3}`. + + If the mode is `SCALED`, the quantization is performed by multiplying each + input value by a scaling_factor. + The scaling_factor is determined from `min_range` and `max_range` to be as large + as possible such that the range from `min_range` to `max_range` is representable + within values of type T. + + ```c++ + + const int min_T = std::numeric_limits::min(); + const int max_T = std::numeric_limits::max(); + const float max_float = std::numeric_limits::max(); + + const float scale_factor_from_min_side = + (min_T * min_range > 0) ? min_T / min_range : max_float; + const float scale_factor_from_max_side = + (max_T * max_range > 0) ? max_T / max_range : max_float; + + const float scale_factor = std::min(scale_factor_from_min_side, + scale_factor_from_max_side); + ``` + + We next use the scale_factor to adjust min_range and max_range as follows: + + ```c++ + min_range = min_T / scale_factor; + max_range = max_T / scale_factor; + ``` + + + e.g. if T = qint8, and initially min_range = -10, and max_range = 9, we would + compare -128/-10.0 = 12.8 to 127/9.0 = 14.11, and set scaling_factor = 12.8 + In this case, min_range would remain -10, but max_range would be adjusted to + 127 / 12.8 = 9.921875 + + So we will quantize input values in the range (-10, 9.921875) to (-128, 127). + + The input tensor can now be quantized by clipping values to the range + `min_range` to `max_range`, then multiplying by scale_factor as follows: + + ```c++ + result = round(min(max_range, max(min_range, input)) * scale_factor) + ``` + + The adjusted `min_range` and `max_range` are returned as outputs 2 and 3 of + this operation. These outputs should be used as the range for any further + calculations. + + + *narrow_range (bool) attribute* + + If true, we do not use the minimum quantized value. + i.e. for int8 the quantized output, it would be restricted to the range + -127..127 instead of the full -128..127 range. + This is provided for compatibility with certain inference backends. + (Only applies to SCALED mode) + + + *axis (int) attribute* + + An optional `axis` attribute can specify a dimension index of the input tensor, + such that quantization ranges will be calculated and applied separately for each + slice of the tensor along that dimension. This is useful for per-channel + quantization. + + If axis is specified, min_range and max_range + + if `axis`=None, per-tensor quantization is performed as normal. + + + *ensure_minimum_range (float) attribute* + + Ensures the minimum quantization range is at least this value. + The legacy default value for this is 0.01, but it is strongly suggested to + set it to 0 for new uses. + + Args: + input: A `Tensor` of type `float32`. + min_range: A `Tensor` of type `float32`. + The minimum value of the quantization range. This value may be adjusted by the + op depending on other parameters. The adjusted value is written to `output_min`. + If the `axis` attribute is specified, this must be a 1-D tensor whose size + matches the `axis` dimension of the input and output tensors. + max_range: A `Tensor` of type `float32`. + The maximum value of the quantization range. This value may be adjusted by the + op depending on other parameters. The adjusted value is written to `output_max`. + If the `axis` attribute is specified, this must be a 1-D tensor whose size + matches the `axis` dimension of the input and output tensors. + T: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. + mode: An optional `string` from: `"MIN_COMBINED", "MIN_FIRST", "SCALED"`. Defaults to `"MIN_COMBINED"`. + round_mode: An optional `string` from: `"HALF_AWAY_FROM_ZERO", "HALF_TO_EVEN"`. Defaults to `"HALF_AWAY_FROM_ZERO"`. + narrow_range: An optional `bool`. Defaults to `False`. + axis: An optional `int`. Defaults to `-1`. + ensure_minimum_range: An optional `float`. Defaults to `0.01`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor` of type `T`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeV2", name, input, min_range, max_range, "T", T, "mode", + mode, "round_mode", round_mode, "narrow_range", narrow_range, "axis", + axis, "ensure_minimum_range", ensure_minimum_range) + _result = _QuantizeV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_v2_eager_fallback( + input, min_range, max_range, T=T, mode=mode, round_mode=round_mode, + narrow_range=narrow_range, axis=axis, + ensure_minimum_range=ensure_minimum_range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + if mode is None: + mode = "MIN_COMBINED" + mode = _execute.make_str(mode, "mode") + if round_mode is None: + round_mode = "HALF_AWAY_FROM_ZERO" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + if ensure_minimum_range is None: + ensure_minimum_range = 0.01 + ensure_minimum_range = _execute.make_float(ensure_minimum_range, "ensure_minimum_range") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeV2", input=input, min_range=min_range, max_range=max_range, + T=T, mode=mode, round_mode=round_mode, + narrow_range=narrow_range, axis=axis, + ensure_minimum_range=ensure_minimum_range, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "mode", _op.get_attr("mode"), + "round_mode", _op.get_attr("round_mode"), "narrow_range", + _op._get_attr_bool("narrow_range"), "axis", + _op._get_attr_int("axis"), "ensure_minimum_range", + _op.get_attr("ensure_minimum_range")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeV2", _inputs_flat, _attrs, _result) + _result = _QuantizeV2Output._make(_result) + return _result + +QuantizeV2 = tf_export("raw_ops.QuantizeV2")(_ops.to_raw_op(quantize_v2)) + + +def quantize_v2_eager_fallback(input: Annotated[Any, _atypes.Float32], min_range: Annotated[Any, _atypes.Float32], max_range: Annotated[Any, _atypes.Float32], T: TV_QuantizeV2_T, mode: str, round_mode: str, narrow_range: bool, axis: int, ensure_minimum_range: float, name, ctx): + T = _execute.make_type(T, "T") + if mode is None: + mode = "MIN_COMBINED" + mode = _execute.make_str(mode, "mode") + if round_mode is None: + round_mode = "HALF_AWAY_FROM_ZERO" + round_mode = _execute.make_str(round_mode, "round_mode") + if narrow_range is None: + narrow_range = False + narrow_range = _execute.make_bool(narrow_range, "narrow_range") + if axis is None: + axis = -1 + axis = _execute.make_int(axis, "axis") + if ensure_minimum_range is None: + ensure_minimum_range = 0.01 + ensure_minimum_range = _execute.make_float(ensure_minimum_range, "ensure_minimum_range") + input = _ops.convert_to_tensor(input, _dtypes.float32) + min_range = _ops.convert_to_tensor(min_range, _dtypes.float32) + max_range = _ops.convert_to_tensor(max_range, _dtypes.float32) + _inputs_flat = [input, min_range, max_range] + _attrs = ("T", T, "mode", mode, "round_mode", round_mode, "narrow_range", + narrow_range, "axis", axis, "ensure_minimum_range", ensure_minimum_range) + _result = _execute.execute(b"QuantizeV2", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeV2", _inputs_flat, _attrs, _result) + _result = _QuantizeV2Output._make(_result) + return _result + +_QuantizedConcatOutput = collections.namedtuple( + "QuantizedConcat", + ["output", "output_min", "output_max"]) + + +TV_QuantizedConcat_T = TypeVar("TV_QuantizedConcat_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('quantization.quantized_concat', v1=['quantization.quantized_concat', 'quantized_concat']) +@deprecated_endpoints('quantized_concat') +def quantized_concat(concat_dim: Annotated[Any, _atypes.Int32], values: Annotated[List[Any], TV_QuantizedConcat_T], input_mins: Annotated[List[Any], _atypes.Float32], input_maxes: Annotated[List[Any], _atypes.Float32], name=None): + r"""Concatenates quantized tensors along one dimension. + + Args: + concat_dim: A `Tensor` of type `int32`. + 0-D. The dimension along which to concatenate. Must be in the + range [0, rank(values)). + values: A list of at least 2 `Tensor` objects with the same type. + The `N` Tensors to concatenate. Their ranks and types must match, + and their sizes must match in all dimensions except `concat_dim`. + input_mins: A list with the same length as `values` of `Tensor` objects with type `float32`. + The minimum scalar values for each of the input tensors. + input_maxes: A list with the same length as `values` of `Tensor` objects with type `float32`. + The maximum scalar values for each of the input tensors. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor`. Has the same type as `values`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConcat", name, concat_dim, values, input_mins, + input_maxes) + _result = _QuantizedConcatOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_quantized_concat( + (concat_dim, values, input_mins, input_maxes, name,), None) + if _result is not NotImplemented: + return _result + return quantized_concat_eager_fallback( + concat_dim, values, input_mins, input_maxes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + quantized_concat, (), dict(concat_dim=concat_dim, values=values, + input_mins=input_mins, + input_maxes=input_maxes, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_quantized_concat( + (concat_dim, values, input_mins, input_maxes, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'quantized_concat' Op, not %r." % values) + _attr_N = len(values) + if not isinstance(input_mins, (list, tuple)): + raise TypeError( + "Expected list for 'input_mins' argument to " + "'quantized_concat' Op, not %r." % input_mins) + if len(input_mins) != _attr_N: + raise ValueError( + "List argument 'input_mins' to 'quantized_concat' Op with length %d " + "must match length %d of argument 'values'." % + (len(input_mins), _attr_N)) + if not isinstance(input_maxes, (list, tuple)): + raise TypeError( + "Expected list for 'input_maxes' argument to " + "'quantized_concat' Op, not %r." % input_maxes) + if len(input_maxes) != _attr_N: + raise ValueError( + "List argument 'input_maxes' to 'quantized_concat' Op with length %d " + "must match length %d of argument 'values'." % + (len(input_maxes), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConcat", concat_dim=concat_dim, values=values, + input_mins=input_mins, input_maxes=input_maxes, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + quantized_concat, (), dict(concat_dim=concat_dim, values=values, + input_mins=input_mins, + input_maxes=input_maxes, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConcat", _inputs_flat, _attrs, _result) + _result = _QuantizedConcatOutput._make(_result) + return _result + +QuantizedConcat = tf_export("raw_ops.QuantizedConcat")(_ops.to_raw_op(quantized_concat)) +_dispatcher_for_quantized_concat = quantized_concat._tf_type_based_dispatcher.Dispatch + + +def quantized_concat_eager_fallback(concat_dim: Annotated[Any, _atypes.Int32], values: Annotated[List[Any], TV_QuantizedConcat_T], input_mins: Annotated[List[Any], _atypes.Float32], input_maxes: Annotated[List[Any], _atypes.Float32], name, ctx): + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'quantized_concat' Op, not %r." % values) + _attr_N = len(values) + if not isinstance(input_mins, (list, tuple)): + raise TypeError( + "Expected list for 'input_mins' argument to " + "'quantized_concat' Op, not %r." % input_mins) + if len(input_mins) != _attr_N: + raise ValueError( + "List argument 'input_mins' to 'quantized_concat' Op with length %d " + "must match length %d of argument 'values'." % + (len(input_mins), _attr_N)) + if not isinstance(input_maxes, (list, tuple)): + raise TypeError( + "Expected list for 'input_maxes' argument to " + "'quantized_concat' Op, not %r." % input_maxes) + if len(input_maxes) != _attr_N: + raise ValueError( + "List argument 'input_maxes' to 'quantized_concat' Op with length %d " + "must match length %d of argument 'values'." % + (len(input_maxes), _attr_N)) + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) + input_mins = _ops.convert_n_to_tensor(input_mins, _dtypes.float32) + input_maxes = _ops.convert_n_to_tensor(input_maxes, _dtypes.float32) + _inputs_flat = [concat_dim] + list(values) + list(input_mins) + list(input_maxes) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"QuantizedConcat", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConcat", _inputs_flat, _attrs, _result) + _result = _QuantizedConcatOutput._make(_result) + return _result + +_QuantizedInstanceNormOutput = collections.namedtuple( + "QuantizedInstanceNorm", + ["y", "y_min", "y_max"]) + + +TV_QuantizedInstanceNorm_T = TypeVar("TV_QuantizedInstanceNorm_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_instance_norm(x: Annotated[Any, TV_QuantizedInstanceNorm_T], x_min: Annotated[Any, _atypes.Float32], x_max: Annotated[Any, _atypes.Float32], output_range_given:bool=False, given_y_min:float=0, given_y_max:float=0, variance_epsilon:float=1e-05, min_separation:float=0.001, name=None): + r"""Quantized Instance normalization. + + Args: + x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A 4D input Tensor. + x_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized input. + x_max: A `Tensor` of type `float32`. + The value represented by the highest quantized input. + output_range_given: An optional `bool`. Defaults to `False`. + If True, `given_y_min` and `given_y_min` + and `given_y_max` are used as the output range. Otherwise, + the implementation computes the output range. + given_y_min: An optional `float`. Defaults to `0`. + Output in `y_min` if `output_range_given` is True. + given_y_max: An optional `float`. Defaults to `0`. + Output in `y_max` if `output_range_given` is True. + variance_epsilon: An optional `float`. Defaults to `1e-05`. + A small float number to avoid dividing by 0. + min_separation: An optional `float`. Defaults to `0.001`. + Minimum value of `y_max - y_min` + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, y_min, y_max). + + y: A `Tensor`. Has the same type as `x`. + y_min: A `Tensor` of type `float32`. + y_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedInstanceNorm", name, x, x_min, x_max, + "output_range_given", output_range_given, "given_y_min", given_y_min, + "given_y_max", given_y_max, "variance_epsilon", variance_epsilon, + "min_separation", min_separation) + _result = _QuantizedInstanceNormOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_instance_norm_eager_fallback( + x, x_min, x_max, output_range_given=output_range_given, + given_y_min=given_y_min, given_y_max=given_y_max, + variance_epsilon=variance_epsilon, min_separation=min_separation, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_range_given is None: + output_range_given = False + output_range_given = _execute.make_bool(output_range_given, "output_range_given") + if given_y_min is None: + given_y_min = 0 + given_y_min = _execute.make_float(given_y_min, "given_y_min") + if given_y_max is None: + given_y_max = 0 + given_y_max = _execute.make_float(given_y_max, "given_y_max") + if variance_epsilon is None: + variance_epsilon = 1e-05 + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + if min_separation is None: + min_separation = 0.001 + min_separation = _execute.make_float(min_separation, "min_separation") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedInstanceNorm", x=x, x_min=x_min, x_max=x_max, + output_range_given=output_range_given, + given_y_min=given_y_min, + given_y_max=given_y_max, + variance_epsilon=variance_epsilon, + min_separation=min_separation, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "output_range_given", + _op._get_attr_bool("output_range_given"), "given_y_min", + _op.get_attr("given_y_min"), "given_y_max", + _op.get_attr("given_y_max"), "variance_epsilon", + _op.get_attr("variance_epsilon"), "min_separation", + _op.get_attr("min_separation")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedInstanceNorm", _inputs_flat, _attrs, _result) + _result = _QuantizedInstanceNormOutput._make(_result) + return _result + +QuantizedInstanceNorm = tf_export("raw_ops.QuantizedInstanceNorm")(_ops.to_raw_op(quantized_instance_norm)) + + +def quantized_instance_norm_eager_fallback(x: Annotated[Any, TV_QuantizedInstanceNorm_T], x_min: Annotated[Any, _atypes.Float32], x_max: Annotated[Any, _atypes.Float32], output_range_given: bool, given_y_min: float, given_y_max: float, variance_epsilon: float, min_separation: float, name, ctx): + if output_range_given is None: + output_range_given = False + output_range_given = _execute.make_bool(output_range_given, "output_range_given") + if given_y_min is None: + given_y_min = 0 + given_y_min = _execute.make_float(given_y_min, "given_y_min") + if given_y_max is None: + given_y_max = 0 + given_y_max = _execute.make_float(given_y_max, "given_y_max") + if variance_epsilon is None: + variance_epsilon = 1e-05 + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + if min_separation is None: + min_separation = 0.001 + min_separation = _execute.make_float(min_separation, "min_separation") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + x_min = _ops.convert_to_tensor(x_min, _dtypes.float32) + x_max = _ops.convert_to_tensor(x_max, _dtypes.float32) + _inputs_flat = [x, x_min, x_max] + _attrs = ("T", _attr_T, "output_range_given", output_range_given, + "given_y_min", given_y_min, "given_y_max", given_y_max, "variance_epsilon", + variance_epsilon, "min_separation", min_separation) + _result = _execute.execute(b"QuantizedInstanceNorm", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedInstanceNorm", _inputs_flat, _attrs, _result) + _result = _QuantizedInstanceNormOutput._make(_result) + return _result + +_QuantizedReshapeOutput = collections.namedtuple( + "QuantizedReshape", + ["output", "output_min", "output_max"]) + + +TV_QuantizedReshape_T = TypeVar("TV_QuantizedReshape_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_QuantizedReshape_Tshape = TypeVar("TV_QuantizedReshape_Tshape", _atypes.Int32, _atypes.Int64) + +def quantized_reshape(tensor: Annotated[Any, TV_QuantizedReshape_T], shape: Annotated[Any, TV_QuantizedReshape_Tshape], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], name=None): + r"""Reshapes a quantized tensor as per the Reshape op. + + ``` + + Args: + tensor: A `Tensor`. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Defines the shape of the output tensor. + input_min: A `Tensor` of type `float32`. The minimum value of the input. + input_max: A `Tensor` of type `float32`. The maximum value of the input. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor`. Has the same type as `tensor`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedReshape", name, tensor, shape, input_min, input_max) + _result = _QuantizedReshapeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_reshape_eager_fallback( + tensor, shape, input_min, input_max, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedReshape", tensor=tensor, shape=shape, input_min=input_min, + input_max=input_max, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedReshape", _inputs_flat, _attrs, _result) + _result = _QuantizedReshapeOutput._make(_result) + return _result + +QuantizedReshape = tf_export("raw_ops.QuantizedReshape")(_ops.to_raw_op(quantized_reshape)) + + +def quantized_reshape_eager_fallback(tensor: Annotated[Any, TV_QuantizedReshape_T], shape: Annotated[Any, TV_QuantizedReshape_Tshape], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], name, ctx): + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + _inputs_flat = [tensor, shape, input_min, input_max] + _attrs = ("T", _attr_T, "Tshape", _attr_Tshape) + _result = _execute.execute(b"QuantizedReshape", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedReshape", _inputs_flat, _attrs, _result) + _result = _QuantizedReshapeOutput._make(_result) + return _result + + +TV_Rank_T = TypeVar("TV_Rank_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def rank(input: Annotated[Any, TV_Rank_T], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the rank of a tensor. + + This operation returns an integer representing the rank of `input`. + + For example: + + ``` + # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] + # shape of tensor 't' is [2, 2, 3] + rank(t) ==> 3 + ``` + + **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank + of a tensor is the number of indices required to uniquely select each element + of the tensor. Rank is also known as "order", "degree", or "ndims." + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Rank", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rank_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Rank", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Rank", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Rank = tf_export("raw_ops.Rank")(_ops.to_raw_op(rank)) + + +def rank_eager_fallback(input: Annotated[Any, TV_Rank_T], name, ctx) -> Annotated[Any, _atypes.Int32]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Rank", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Rank", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RefIdentity_T = TypeVar("TV_RefIdentity_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_identity(input: Annotated[Any, TV_RefIdentity_T], name=None) -> Annotated[Any, TV_RefIdentity_T]: + r"""Return the same ref tensor as the input ref tensor. + + Args: + input: A mutable `Tensor`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_identity op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefIdentity", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefIdentity = tf_export("raw_ops.RefIdentity")(_ops.to_raw_op(ref_identity)) + + +def ref_identity_eager_fallback(input: Annotated[Any, TV_RefIdentity_T], name, ctx) -> Annotated[Any, TV_RefIdentity_T]: + raise RuntimeError("ref_identity op does not support eager execution. Arg 'output' is a ref.") + +TV_Reshape_T = TypeVar("TV_Reshape_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Reshape_Tshape = TypeVar("TV_Reshape_Tshape", _atypes.Int32, _atypes.Int64) + +def reshape(tensor: Annotated[Any, TV_Reshape_T], shape: Annotated[Any, TV_Reshape_Tshape], name=None) -> Annotated[Any, TV_Reshape_T]: + r"""Reshapes a tensor. + + Given `tensor`, this operation returns a tensor that has the same values + as `tensor` with shape `shape`. + + If one component of 1-D tensor `shape` is the special value -1, the size of that + dimension is computed so that the total size remains constant. In particular, a + `shape` of `[-1]` flattens into 1-D. At most one component of `shape` may be + unknown. + + The `shape` must be 1-D and the operation returns a tensor with shape + `shape` filled with the values of `tensor`. In this case, the number of elements + implied by `shape` must be the same as the number of elements in `tensor`. + + It is an error if `shape` is not 1-D. + + For example: + + ``` + # tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9] + # tensor 't' has shape [9] + reshape(t, [3, 3]) ==> [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + + # tensor 't' is [[[1, 1], [2, 2]], + # [[3, 3], [4, 4]]] + # tensor 't' has shape [2, 2, 2] + reshape(t, [2, 4]) ==> [[1, 1, 2, 2], + [3, 3, 4, 4]] + + # tensor 't' is [[[1, 1, 1], + # [2, 2, 2]], + # [[3, 3, 3], + # [4, 4, 4]], + # [[5, 5, 5], + # [6, 6, 6]]] + # tensor 't' has shape [3, 2, 3] + # pass '[-1]' to flatten 't' + reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6] + + # -1 can also be used to infer the shape + + # -1 is inferred to be 9: + reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], + [4, 4, 4, 5, 5, 5, 6, 6, 6]] + # -1 is inferred to be 2: + reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], + [4, 4, 4, 5, 5, 5, 6, 6, 6]] + # -1 is inferred to be 3: + reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1], + [2, 2, 2], + [3, 3, 3]], + [[4, 4, 4], + [5, 5, 5], + [6, 6, 6]]] + + # tensor 't' is [7] + # shape `[]` reshapes to a scalar + reshape(t, []) ==> 7 + ``` + + Args: + tensor: A `Tensor`. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Defines the shape of the output tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Reshape", name, tensor, shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reshape_eager_fallback( + tensor, shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Reshape", tensor=tensor, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Reshape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Reshape = tf_export("raw_ops.Reshape")(_ops.to_raw_op(reshape)) + + +def reshape_eager_fallback(tensor: Annotated[Any, TV_Reshape_T], shape: Annotated[Any, TV_Reshape_Tshape], name, ctx) -> Annotated[Any, TV_Reshape_T]: + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [tensor, shape] + _attrs = ("T", _attr_T, "Tshape", _attr_Tshape) + _result = _execute.execute(b"Reshape", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Reshape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceStridedSliceAssign_T = TypeVar("TV_ResourceStridedSliceAssign_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceStridedSliceAssign_Index = TypeVar("TV_ResourceStridedSliceAssign_Index", _atypes.Int32, _atypes.Int64) + +def resource_strided_slice_assign(ref: Annotated[Any, _atypes.Resource], begin: Annotated[Any, TV_ResourceStridedSliceAssign_Index], end: Annotated[Any, TV_ResourceStridedSliceAssign_Index], strides: Annotated[Any, TV_ResourceStridedSliceAssign_Index], value: Annotated[Any, TV_ResourceStridedSliceAssign_T], begin_mask:int=0, end_mask:int=0, ellipsis_mask:int=0, new_axis_mask:int=0, shrink_axis_mask:int=0, name=None): + r"""Assign `value` to the sliced l-value reference of `ref`. + + The values of `value` are assigned to the positions in the variable + `ref` that are selected by the slice parameters. The slice parameters + `begin, `end`, `strides`, etc. work exactly as in `StridedSlice`. + + NOTE this op currently does not support broadcasting and so `value`'s + shape must be exactly the shape produced by the slice of `ref`. + + Args: + ref: A `Tensor` of type `resource`. + begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. + end: A `Tensor`. Must have the same type as `begin`. + strides: A `Tensor`. Must have the same type as `begin`. + value: A `Tensor`. + begin_mask: An optional `int`. Defaults to `0`. + end_mask: An optional `int`. Defaults to `0`. + ellipsis_mask: An optional `int`. Defaults to `0`. + new_axis_mask: An optional `int`. Defaults to `0`. + shrink_axis_mask: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceStridedSliceAssign", name, ref, begin, end, strides, + value, "begin_mask", begin_mask, "end_mask", end_mask, + "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, + "shrink_axis_mask", shrink_axis_mask) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_strided_slice_assign_eager_fallback( + ref, begin, end, strides, value, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceStridedSliceAssign", ref=ref, begin=begin, end=end, + strides=strides, value=value, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask, + name=name) + return _op +ResourceStridedSliceAssign = tf_export("raw_ops.ResourceStridedSliceAssign")(_ops.to_raw_op(resource_strided_slice_assign)) + + +def resource_strided_slice_assign_eager_fallback(ref: Annotated[Any, _atypes.Resource], begin: Annotated[Any, TV_ResourceStridedSliceAssign_Index], end: Annotated[Any, TV_ResourceStridedSliceAssign_Index], strides: Annotated[Any, TV_ResourceStridedSliceAssign_Index], value: Annotated[Any, TV_ResourceStridedSliceAssign_T], begin_mask: int, end_mask: int, ellipsis_mask: int, new_axis_mask: int, shrink_axis_mask: int, name, ctx): + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, end, strides], ctx, [_dtypes.int32, _dtypes.int64, ]) + (begin, end, strides) = _inputs_Index + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, begin, end, strides, value] + _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, + "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", + new_axis_mask, "shrink_axis_mask", shrink_axis_mask) + _result = _execute.execute(b"ResourceStridedSliceAssign", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_Reverse_T = TypeVar("TV_Reverse_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def reverse(tensor: Annotated[Any, TV_Reverse_T], dims: Annotated[Any, _atypes.Bool], name=None) -> Annotated[Any, TV_Reverse_T]: + r"""Reverses specific dimensions of a tensor. + + Given a `tensor`, and a `bool` tensor `dims` representing the dimensions + of `tensor`, this operation reverses each dimension i of `tensor` where + `dims[i]` is `True`. + + `tensor` can have up to 8 dimensions. The number of dimensions + of `tensor` must equal the number of elements in `dims`. In other words: + + `rank(tensor) = size(dims)` + + For example: + + ``` + # tensor 't' is [[[[ 0, 1, 2, 3], + # [ 4, 5, 6, 7], + # [ 8, 9, 10, 11]], + # [[12, 13, 14, 15], + # [16, 17, 18, 19], + # [20, 21, 22, 23]]]] + # tensor 't' shape is [1, 2, 3, 4] + + # 'dims' is [False, False, False, True] + reverse(t, dims) ==> [[[[ 3, 2, 1, 0], + [ 7, 6, 5, 4], + [ 11, 10, 9, 8]], + [[15, 14, 13, 12], + [19, 18, 17, 16], + [23, 22, 21, 20]]]] + + # 'dims' is [False, True, False, False] + reverse(t, dims) ==> [[[[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23] + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]]] + + # 'dims' is [False, False, True, False] + reverse(t, dims) ==> [[[[8, 9, 10, 11], + [4, 5, 6, 7], + [0, 1, 2, 3]] + [[20, 21, 22, 23], + [16, 17, 18, 19], + [12, 13, 14, 15]]]] + ``` + + Args: + tensor: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `uint16`, `int16`, `uint32`, `int32`, `uint64`, `int64`, `bool`, `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`, `string`. + Up to 8-D. + dims: A `Tensor` of type `bool`. 1-D. The dimensions to reverse. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Reverse", name, tensor, dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reverse_eager_fallback( + tensor, dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Reverse", tensor=tensor, dims=dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Reverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Reverse = tf_export("raw_ops.Reverse")(_ops.to_raw_op(reverse)) + + +def reverse_eager_fallback(tensor: Annotated[Any, TV_Reverse_T], dims: Annotated[Any, _atypes.Bool], name, ctx) -> Annotated[Any, TV_Reverse_T]: + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.uint32, _dtypes.int32, _dtypes.uint64, _dtypes.int64, _dtypes.bool, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, _dtypes.string, ]) + dims = _ops.convert_to_tensor(dims, _dtypes.bool) + _inputs_flat = [tensor, dims] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Reverse", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Reverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReverseSequence_T = TypeVar("TV_ReverseSequence_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ReverseSequence_Tlen = TypeVar("TV_ReverseSequence_Tlen", _atypes.Int32, _atypes.Int64) + +def reverse_sequence(input: Annotated[Any, TV_ReverseSequence_T], seq_lengths: Annotated[Any, TV_ReverseSequence_Tlen], seq_dim: int, batch_dim:int=0, name=None) -> Annotated[Any, TV_ReverseSequence_T]: + r"""Reverses variable length slices. + + This op first slices `input` along the dimension `batch_dim`, and for each + slice `i`, reverses the first `seq_lengths[i]` elements along + the dimension `seq_dim`. + + The elements of `seq_lengths` must obey `seq_lengths[i] <= input.dims[seq_dim]`, + and `seq_lengths` must be a vector of length `input.dims[batch_dim]`. + + The output slice `i` along dimension `batch_dim` is then given by input + slice `i`, with the first `seq_lengths[i]` slices along dimension + `seq_dim` reversed. + + For example: + + ``` + # Given this: + batch_dim = 0 + seq_dim = 1 + input.dims = (4, 8, ...) + seq_lengths = [7, 2, 3, 5] + + # then slices of input are reversed on seq_dim, but only up to seq_lengths: + output[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...] + output[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...] + output[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...] + output[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...] + + # while entries past seq_lens are copied through: + output[0, 7:, :, ...] = input[0, 7:, :, ...] + output[1, 2:, :, ...] = input[1, 2:, :, ...] + output[2, 3:, :, ...] = input[2, 3:, :, ...] + output[3, 2:, :, ...] = input[3, 2:, :, ...] + ``` + + In contrast, if: + + ``` + # Given this: + batch_dim = 2 + seq_dim = 0 + input.dims = (8, ?, 4, ...) + seq_lengths = [7, 2, 3, 5] + + # then slices of input are reversed on seq_dim, but only up to seq_lengths: + output[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...] + output[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...] + output[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...] + output[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...] + + # while entries past seq_lens are copied through: + output[7:, :, 0, :, ...] = input[7:, :, 0, :, ...] + output[2:, :, 1, :, ...] = input[2:, :, 1, :, ...] + output[3:, :, 2, :, ...] = input[3:, :, 2, :, ...] + output[2:, :, 3, :, ...] = input[2:, :, 3, :, ...] + ``` + + Args: + input: A `Tensor`. The input to reverse. + seq_lengths: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D with length `input.dims(batch_dim)` and + `max(seq_lengths) <= input.dims(seq_dim)` + seq_dim: An `int`. The dimension which is partially reversed. + batch_dim: An optional `int`. Defaults to `0`. + The dimension along which reversal is performed. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReverseSequence", name, input, seq_lengths, "seq_dim", seq_dim, + "batch_dim", batch_dim) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reverse_sequence_eager_fallback( + input, seq_lengths, seq_dim=seq_dim, batch_dim=batch_dim, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + seq_dim = _execute.make_int(seq_dim, "seq_dim") + if batch_dim is None: + batch_dim = 0 + batch_dim = _execute.make_int(batch_dim, "batch_dim") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReverseSequence", input=input, seq_lengths=seq_lengths, + seq_dim=seq_dim, batch_dim=batch_dim, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seq_dim", _op._get_attr_int("seq_dim"), "batch_dim", + _op._get_attr_int("batch_dim"), "T", _op._get_attr_type("T"), + "Tlen", _op._get_attr_type("Tlen")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReverseSequence", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReverseSequence = tf_export("raw_ops.ReverseSequence")(_ops.to_raw_op(reverse_sequence)) + + +def reverse_sequence_eager_fallback(input: Annotated[Any, TV_ReverseSequence_T], seq_lengths: Annotated[Any, TV_ReverseSequence_Tlen], seq_dim: int, batch_dim: int, name, ctx) -> Annotated[Any, TV_ReverseSequence_T]: + seq_dim = _execute.make_int(seq_dim, "seq_dim") + if batch_dim is None: + batch_dim = 0 + batch_dim = _execute.make_int(batch_dim, "batch_dim") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tlen, (seq_lengths,) = _execute.args_to_matching_eager([seq_lengths], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [input, seq_lengths] + _attrs = ("seq_dim", seq_dim, "batch_dim", batch_dim, "T", _attr_T, "Tlen", + _attr_Tlen) + _result = _execute.execute(b"ReverseSequence", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReverseSequence", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReverseV2_Tidx = TypeVar("TV_ReverseV2_Tidx", _atypes.Int32, _atypes.Int64) +TV_ReverseV2_T = TypeVar("TV_ReverseV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('reverse', v1=['reverse', 'manip.reverse', 'reverse_v2']) +@deprecated_endpoints('manip.reverse', 'reverse_v2') +def reverse_v2(tensor: Annotated[Any, TV_ReverseV2_T], axis: Annotated[Any, TV_ReverseV2_Tidx], name=None) -> Annotated[Any, TV_ReverseV2_T]: + r"""Reverses specific dimensions of a tensor. + + Given a `tensor`, and a `int32` tensor `axis` representing the set of + dimensions of `tensor` to reverse. This operation reverses each dimension + `i` for which there exists `j` s.t. `axis[j] == i`. + + `tensor` can have up to 8 dimensions. The number of dimensions specified + in `axis` may be 0 or more entries. If an index is specified more than + once, a InvalidArgument error is raised. + + For example: + + ``` + # tensor 't' is [[[[ 0, 1, 2, 3], + # [ 4, 5, 6, 7], + # [ 8, 9, 10, 11]], + # [[12, 13, 14, 15], + # [16, 17, 18, 19], + # [20, 21, 22, 23]]]] + # tensor 't' shape is [1, 2, 3, 4] + + # 'dims' is [3] or 'dims' is [-1] + reverse(t, dims) ==> [[[[ 3, 2, 1, 0], + [ 7, 6, 5, 4], + [ 11, 10, 9, 8]], + [[15, 14, 13, 12], + [19, 18, 17, 16], + [23, 22, 21, 20]]]] + + # 'dims' is '[1]' (or 'dims' is '[-3]') + reverse(t, dims) ==> [[[[12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23] + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]]] + + # 'dims' is '[2]' (or 'dims' is '[-2]') + reverse(t, dims) ==> [[[[8, 9, 10, 11], + [4, 5, 6, 7], + [0, 1, 2, 3]] + [[20, 21, 22, 23], + [16, 17, 18, 19], + [12, 13, 14, 15]]]] + ``` + + Args: + tensor: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `int64`, `uint64`, `bool`, `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`, `string`. + Up to 8-D. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D. The indices of the dimensions to reverse. Must be in the range + `[-rank(tensor), rank(tensor))`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReverseV2", name, tensor, axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_reverse_v2( + (tensor, axis, name,), None) + if _result is not NotImplemented: + return _result + return reverse_v2_eager_fallback( + tensor, axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reverse_v2, (), dict(tensor=tensor, axis=axis, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_reverse_v2( + (tensor, axis, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReverseV2", tensor=tensor, axis=axis, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reverse_v2, (), dict(tensor=tensor, axis=axis, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReverseV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReverseV2 = tf_export("raw_ops.ReverseV2")(_ops.to_raw_op(reverse_v2)) +_dispatcher_for_reverse_v2 = reverse_v2._tf_type_based_dispatcher.Dispatch + + +def reverse_v2_eager_fallback(tensor: Annotated[Any, TV_ReverseV2_T], axis: Annotated[Any, TV_ReverseV2_Tidx], name, ctx) -> Annotated[Any, TV_ReverseV2_T]: + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, _dtypes.bool, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, _dtypes.string, ]) + _inputs_flat = [tensor, axis] + _attrs = ("Tidx", _attr_Tidx, "T", _attr_T) + _result = _execute.execute(b"ReverseV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReverseV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ScatterNd_T = TypeVar("TV_ScatterNd_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ScatterNd_Tindices = TypeVar("TV_ScatterNd_Tindices", _atypes.Int16, _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('scatter_nd', v1=['scatter_nd', 'manip.scatter_nd']) +@deprecated_endpoints('manip.scatter_nd') +def scatter_nd(indices: Annotated[Any, TV_ScatterNd_Tindices], updates: Annotated[Any, TV_ScatterNd_T], shape: Annotated[Any, TV_ScatterNd_Tindices], name=None) -> Annotated[Any, TV_ScatterNd_T]: + r"""Scatters `updates` into a tensor of shape `shape` according to `indices`. + + Scatter sparse `updates` according to individual values at the specified + `indices`. This op returns an output tensor with the `shape` you specify. This + op is the inverse of the `tf.gather_nd` operator which extracts values or slices + from a given tensor. + + This operation is similar to `tf.tensor_scatter_nd_add`, except that the tensor + is zero-initialized. Calling `tf.scatter_nd(indices, updates, shape)` + is identical to calling + `tf.tensor_scatter_nd_add(tf.zeros(shape, updates.dtype), indices, updates)` + + If `indices` contains duplicates, the associated `updates` are accumulated + (summed) into the output tensor. + + **WARNING**: For floating-point data types, the output may be nondeterministic. + This is because the order in which the updates are applied is nondeterministic + and when floating-point numbers are added in different orders the resulting + numerical approximation error can be slightly different. However, the output + will be deterministic if op determinism is enabled via + `tf.config.experimental.enable_op_determinism`. + + `indices` is an integer tensor containing indices into the output tensor. The + last dimension of `indices` can be at most the rank of `shape`: + + indices.shape[-1] <= shape.rank + + The last dimension of `indices` corresponds to indices of elements + (if `indices.shape[-1] = shape.rank`) or slices + (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of + `shape`. + + `updates` is a tensor with shape: + + indices.shape[:-1] + shape[indices.shape[-1]:] + + The simplest form of the scatter op is to insert individual elements in + a tensor by index. Consider an example where you want to insert 4 scattered + elements in a rank-1 tensor with 8 elements. + +
+ +
+ + In Python, this scatter operation would look like this: + + ```python + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + shape = tf.constant([8]) + scatter = tf.scatter_nd(indices, updates, shape) + print(scatter) + ``` + + The resulting tensor would look like this: + + [0, 11, 0, 10, 9, 0, 0, 12] + + You can also insert entire slices of a higher rank tensor all at once. For + example, you can insert two slices in the first dimension of a rank-3 tensor + with two matrices of new values. + +
+ +
+ + In Python, this scatter operation would look like this: + + ```python + indices = tf.constant([[1], [3]]) + updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], + [7, 7, 7, 7], [8, 8, 8, 8]], + [[5, 5, 5, 5], [6, 6, 6, 6], + [7, 7, 7, 7], [8, 8, 8, 8]]]) + shape = tf.constant([4, 4, 4]) + scatter = tf.scatter_nd(indices, updates, shape) + print(scatter) + ``` + + The resulting tensor would look like this: + + [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]] + + Note that on CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, the index is ignored. + + Args: + indices: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + Tensor of indices. + updates: A `Tensor`. Values to scatter into the output tensor. + shape: A `Tensor`. Must have the same type as `indices`. + 1-D. The shape of the output tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `updates`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScatterNd", name, indices, updates, shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_scatter_nd( + (indices, updates, shape, name,), None) + if _result is not NotImplemented: + return _result + return scatter_nd_eager_fallback( + indices, updates, shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + scatter_nd, (), dict(indices=indices, updates=updates, + shape=shape, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_scatter_nd( + (indices, updates, shape, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNd", indices=indices, updates=updates, shape=shape, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + scatter_nd, (), dict(indices=indices, updates=updates, shape=shape, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNd = tf_export("raw_ops.ScatterNd")(_ops.to_raw_op(scatter_nd)) +_dispatcher_for_scatter_nd = scatter_nd._tf_type_based_dispatcher.Dispatch + + +def scatter_nd_eager_fallback(indices: Annotated[Any, TV_ScatterNd_Tindices], updates: Annotated[Any, TV_ScatterNd_T], shape: Annotated[Any, TV_ScatterNd_Tindices], name, ctx) -> Annotated[Any, TV_ScatterNd_T]: + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, _inputs_Tindices = _execute.args_to_matching_eager([indices, shape], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + (indices, shape) = _inputs_Tindices + _inputs_flat = [indices, updates, shape] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ScatterNd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScatterNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ScatterNdNonAliasingAdd_T = TypeVar("TV_ScatterNdNonAliasingAdd_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterNdNonAliasingAdd_Tindices = TypeVar("TV_ScatterNdNonAliasingAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_non_aliasing_add(input: Annotated[Any, TV_ScatterNdNonAliasingAdd_T], indices: Annotated[Any, TV_ScatterNdNonAliasingAdd_Tindices], updates: Annotated[Any, TV_ScatterNdNonAliasingAdd_T], name=None) -> Annotated[Any, TV_ScatterNdNonAliasingAdd_T]: + r"""Applies sparse addition to `input` using individual values or slices + + from `updates` according to indices `indices`. The updates are non-aliasing: + `input` is only modified in-place if no other operations will use it. + Otherwise, a copy of `input` is made. This operation has a gradient with + respect to both `input` and `updates`. + + `input` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `input`. + It must be shape \\([d_0, ..., d_{Q-2}, K]\\) where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or `(P-K)`-dimensional slices + (if `K < P`) along the `K`th dimension of `input`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + $$[d_0, ..., d_{Q-2}, input.shape[K], ..., input.shape[P-1]].$$ + + For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 + elements. In Python, that addition would look like this: + + input = tf.constant([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + output = tf.scatter_nd_non_aliasing_add(input, indices, updates) + with tf.Session() as sess: + print(sess.run(output)) + + The resulting value `output` would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to slices. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. + A Tensor. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: `int32`, `int64`. + A tensor of indices into `input`. + updates: A `Tensor`. Must have the same type as `input`. + A Tensor. Must have the same type as ref. A tensor of updated values + to add to `input`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScatterNdNonAliasingAdd", name, input, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return scatter_nd_non_aliasing_add_eager_fallback( + input, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdNonAliasingAdd", input=input, indices=indices, + updates=updates, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdNonAliasingAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdNonAliasingAdd = tf_export("raw_ops.ScatterNdNonAliasingAdd")(_ops.to_raw_op(scatter_nd_non_aliasing_add)) + + +def scatter_nd_non_aliasing_add_eager_fallback(input: Annotated[Any, TV_ScatterNdNonAliasingAdd_T], indices: Annotated[Any, TV_ScatterNdNonAliasingAdd_Tindices], updates: Annotated[Any, TV_ScatterNdNonAliasingAdd_T], name, ctx) -> Annotated[Any, TV_ScatterNdNonAliasingAdd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.bool, ]) + (input, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ScatterNdNonAliasingAdd", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScatterNdNonAliasingAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Shape_T = TypeVar("TV_Shape_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Shape_out_type = TypeVar("TV_Shape_out_type", _atypes.Int32, _atypes.Int64) + +def shape(input: Annotated[Any, TV_Shape_T], out_type:TV_Shape_out_type=_dtypes.int32, name=None) -> Annotated[Any, TV_Shape_out_type]: + r"""Returns the shape of a tensor. + + This operation returns a 1-D integer tensor representing the shape of `input`. + + For example: + + ``` + # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] + shape(t) ==> [2, 2, 3] + ``` + + Args: + input: A `Tensor`. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Shape", name, input, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shape_eager_fallback( + input, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Shape", input=input, out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Shape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Shape = tf_export("raw_ops.Shape")(_ops.to_raw_op(shape)) + + +def shape_eager_fallback(input: Annotated[Any, TV_Shape_T], out_type: TV_Shape_out_type, name, ctx) -> Annotated[Any, TV_Shape_out_type]: + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"Shape", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Shape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ShapeN_T = TypeVar("TV_ShapeN_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ShapeN_out_type = TypeVar("TV_ShapeN_out_type", _atypes.Int32, _atypes.Int64) + +def shape_n(input: Annotated[List[Any], TV_ShapeN_T], out_type:TV_ShapeN_out_type=_dtypes.int32, name=None): + r"""Returns shape of tensors. + + This operation returns N 1-D integer tensors representing shape of `input[i]s`. + + Args: + input: A list of at least 1 `Tensor` objects with the same type. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A list with the same length as `input` of `Tensor` objects with type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShapeN", name, input, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shape_n_eager_fallback( + input, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(input, (list, tuple)): + raise TypeError( + "Expected list for 'input' argument to " + "'shape_n' Op, not %r." % input) + _attr_N = len(input) + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShapeN", input=input, out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "out_type", _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShapeN", _inputs_flat, _attrs, _result) + return _result + +ShapeN = tf_export("raw_ops.ShapeN")(_ops.to_raw_op(shape_n)) + + +def shape_n_eager_fallback(input: Annotated[List[Any], TV_ShapeN_T], out_type: TV_ShapeN_out_type, name, ctx): + if not isinstance(input, (list, tuple)): + raise TypeError( + "Expected list for 'input' argument to " + "'shape_n' Op, not %r." % input) + _attr_N = len(input) + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, input = _execute.args_to_matching_eager(list(input), ctx, []) + _inputs_flat = list(input) + _attrs = ("N", _attr_N, "T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"ShapeN", _attr_N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShapeN", _inputs_flat, _attrs, _result) + return _result + + +TV_Size_T = TypeVar("TV_Size_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Size_out_type = TypeVar("TV_Size_out_type", _atypes.Int32, _atypes.Int64) + +def size(input: Annotated[Any, TV_Size_T], out_type:TV_Size_out_type=_dtypes.int32, name=None) -> Annotated[Any, TV_Size_out_type]: + r"""Returns the size of a tensor. + + This operation returns an integer representing the number of elements in + `input`. + + For example: + + ``` + # 't' is [[[1, 1,, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]] + size(t) ==> 12 + ``` + + Args: + input: A `Tensor`. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Size", name, input, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return size_eager_fallback( + input, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Size", input=input, out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Size", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Size = tf_export("raw_ops.Size")(_ops.to_raw_op(size)) + + +def size_eager_fallback(input: Annotated[Any, TV_Size_T], out_type: TV_Size_out_type, name, ctx) -> Annotated[Any, TV_Size_out_type]: + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"Size", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Size", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Slice_T = TypeVar("TV_Slice_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Slice_Index = TypeVar("TV_Slice_Index", _atypes.Int32, _atypes.Int64) + +def _slice(input: Annotated[Any, TV_Slice_T], begin: Annotated[Any, TV_Slice_Index], size: Annotated[Any, TV_Slice_Index], name=None) -> Annotated[Any, TV_Slice_T]: + r"""Return a slice from 'input'. + + The output tensor is a tensor with dimensions described by 'size' + whose values are extracted from 'input' starting at the offsets in + 'begin'. + + *Requirements*: + 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n) + + Args: + input: A `Tensor`. + begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. + begin[i] specifies the offset into the 'i'th dimension of + 'input' to slice from. + size: A `Tensor`. Must have the same type as `begin`. + size[i] specifies the number of elements of the 'i'th dimension + of 'input' to slice. If size[i] is -1, all remaining elements in dimension + i are included in the slice (i.e. this is equivalent to setting + size[i] = input.dim_size(i) - begin[i]). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Slice", name, input, begin, size) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _slice_eager_fallback( + input, begin, size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Slice", input=input, begin=begin, size=size, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Index", + _op._get_attr_type("Index")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Slice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Slice = tf_export("raw_ops.Slice")(_ops.to_raw_op(_slice)) + + +def _slice_eager_fallback(input: Annotated[Any, TV_Slice_T], begin: Annotated[Any, TV_Slice_Index], size: Annotated[Any, TV_Slice_Index], name, ctx) -> Annotated[Any, TV_Slice_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, size], ctx, [_dtypes.int32, _dtypes.int64, ]) + (begin, size) = _inputs_Index + _inputs_flat = [input, begin, size] + _attrs = ("T", _attr_T, "Index", _attr_Index) + _result = _execute.execute(b"Slice", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Slice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Snapshot_T = TypeVar("TV_Snapshot_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def snapshot(input: Annotated[Any, TV_Snapshot_T], name=None) -> Annotated[Any, TV_Snapshot_T]: + r"""Returns a copy of the input tensor. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Snapshot", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Snapshot", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Snapshot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Snapshot = tf_export("raw_ops.Snapshot")(_ops.to_raw_op(snapshot)) + + +def snapshot_eager_fallback(input: Annotated[Any, TV_Snapshot_T], name, ctx) -> Annotated[Any, TV_Snapshot_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Snapshot", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Snapshot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SpaceToBatch_T = TypeVar("TV_SpaceToBatch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SpaceToBatch_Tpaddings = TypeVar("TV_SpaceToBatch_Tpaddings", _atypes.Int32, _atypes.Int64) + +def space_to_batch(input: Annotated[Any, TV_SpaceToBatch_T], paddings: Annotated[Any, TV_SpaceToBatch_Tpaddings], block_size: int, name=None) -> Annotated[Any, TV_SpaceToBatch_T]: + r"""SpaceToBatch for 4-D tensors of type T. + + This is a legacy version of the more general SpaceToBatchND. + + Zero-pads and then rearranges (permutes) blocks of spatial data into batch. + More specifically, this op outputs a copy of the input tensor where values from + the `height` and `width` dimensions are moved to the `batch` dimension. After + the zero-padding, both `height` and `width` of the input must be divisible by the + block size. + + The attr `block_size` must be greater than one. It indicates the block size. + + * Non-overlapping blocks of size `block_size x block size` in the height and + width dimensions are rearranged into the batch dimension at each location. + * The batch of the output tensor is `batch * block_size * block_size`. + * Both height_pad and width_pad must be divisible by block_size. + + The shape of the output will be: + + [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, + depth] + + Some examples: + + (1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2: + + ``` + x = [[[[1], [2]], [[3], [4]]]] + ``` + + The output tensor has shape `[4, 1, 1, 1]` and value: + + ``` + [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] + ``` + + (2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2: + + ``` + x = [[[[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]]]] + ``` + + The output tensor has shape `[4, 1, 1, 3]` and value: + + ``` + [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] + ``` + + (3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]], + [[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + The output tensor has shape `[4, 2, 2, 1]` and value: + + ``` + x = [[[[1], [3]], [[9], [11]]], + [[[2], [4]], [[10], [12]]], + [[[5], [7]], [[13], [15]]], + [[[6], [8]], [[14], [16]]]] + ``` + + (4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]]], + [[[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + The output tensor has shape `[8, 1, 2, 1]` and value: + + ``` + x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], + [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] + ``` + + Among others, this operation is useful for reducing atrous convolution into + regular convolution. + + Args: + input: A `Tensor`. 4-D with shape `[batch, height, width, depth]`. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies + the padding of the input with zeros across the spatial dimensions as follows: + + paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] + + The effective spatial dimensions of the zero-padded input tensor will be: + + height_pad = pad_top + height + pad_bottom + width_pad = pad_left + width + pad_right + block_size: An `int` that is `>= 2`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SpaceToBatch", name, input, paddings, "block_size", block_size) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return space_to_batch_eager_fallback( + input, paddings, block_size=block_size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + block_size = _execute.make_int(block_size, "block_size") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SpaceToBatch", input=input, paddings=paddings, block_size=block_size, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tpaddings", + _op._get_attr_type("Tpaddings"), "block_size", + _op._get_attr_int("block_size")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SpaceToBatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SpaceToBatch = tf_export("raw_ops.SpaceToBatch")(_ops.to_raw_op(space_to_batch)) + + +def space_to_batch_eager_fallback(input: Annotated[Any, TV_SpaceToBatch_T], paddings: Annotated[Any, TV_SpaceToBatch_Tpaddings], block_size: int, name, ctx) -> Annotated[Any, TV_SpaceToBatch_T]: + block_size = _execute.make_int(block_size, "block_size") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, paddings] + _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "block_size", + block_size) + _result = _execute.execute(b"SpaceToBatch", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SpaceToBatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SpaceToBatchND_T = TypeVar("TV_SpaceToBatchND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SpaceToBatchND_Tblock_shape = TypeVar("TV_SpaceToBatchND_Tblock_shape", _atypes.Int32, _atypes.Int64) +TV_SpaceToBatchND_Tpaddings = TypeVar("TV_SpaceToBatchND_Tpaddings", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('space_to_batch_nd', v1=['space_to_batch_nd', 'manip.space_to_batch_nd']) +@deprecated_endpoints('manip.space_to_batch_nd') +def space_to_batch_nd(input: Annotated[Any, TV_SpaceToBatchND_T], block_shape: Annotated[Any, TV_SpaceToBatchND_Tblock_shape], paddings: Annotated[Any, TV_SpaceToBatchND_Tpaddings], name=None) -> Annotated[Any, TV_SpaceToBatchND_T]: + r"""SpaceToBatch for N-D tensors of type T. + + This operation divides "spatial" dimensions `[1, ..., M]` of the input into a + grid of blocks of shape `block_shape`, and interleaves these blocks with the + "batch" dimension (0) such that in the output, the spatial dimensions + `[1, ..., M]` correspond to the position within the grid, and the batch + dimension combines both the position within a spatial block and the original + batch position. Prior to division into blocks, the spatial dimensions of the + input are optionally zero padded according to `paddings`. See below for a + precise description. + + This operation is equivalent to the following steps: + + 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the + input according to `paddings` to produce `padded` of shape `padded_shape`. + + 2. Reshape `padded` to `reshaped_padded` of shape: + + [batch] + + [padded_shape[1] / block_shape[0], + block_shape[0], + ..., + padded_shape[M] / block_shape[M-1], + block_shape[M-1]] + + remaining_shape + + 3. Permute dimensions of `reshaped_padded` to produce + `permuted_reshaped_padded` of shape: + + block_shape + + [batch] + + [padded_shape[1] / block_shape[0], + ..., + padded_shape[M] / block_shape[M-1]] + + remaining_shape + + 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch + dimension, producing an output tensor of shape: + + [batch * prod(block_shape)] + + [padded_shape[1] / block_shape[0], + ..., + padded_shape[M] / block_shape[M-1]] + + remaining_shape + + Some examples: + + (1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and + `paddings = [[0, 0], [0, 0]]`: + + ``` + x = [[[[1], [2]], [[3], [4]]]] + ``` + + The output tensor has shape `[4, 1, 1, 1]` and value: + + ``` + [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] + ``` + + (2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and + `paddings = [[0, 0], [0, 0]]`: + + ``` + x = [[[[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]]]] + ``` + + The output tensor has shape `[4, 1, 1, 3]` and value: + + ``` + [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] + ``` + + (3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and + `paddings = [[0, 0], [0, 0]]`: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]], + [[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + The output tensor has shape `[4, 2, 2, 1]` and value: + + ``` + x = [[[[1], [3]], [[9], [11]]], + [[[2], [4]], [[10], [12]]], + [[[5], [7]], [[13], [15]]], + [[[6], [8]], [[14], [16]]]] + ``` + + (4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and + paddings = `[[0, 0], [2, 0]]`: + + ``` + x = [[[[1], [2], [3], [4]], + [[5], [6], [7], [8]]], + [[[9], [10], [11], [12]], + [[13], [14], [15], [16]]]] + ``` + + The output tensor has shape `[8, 1, 3, 1]` and value: + + ``` + x = [[[[0], [1], [3]]], [[[0], [9], [11]]], + [[[0], [2], [4]]], [[[0], [10], [12]]], + [[[0], [5], [7]]], [[[0], [13], [15]]], + [[[0], [6], [8]]], [[[0], [14], [16]]]] + ``` + + Among others, this operation is useful for reducing atrous convolution into + regular convolution. + + Args: + input: A `Tensor`. + N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, + where spatial_shape has `M` dimensions. + block_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D with shape `[M]`, all values must be >= 1. + paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D with shape `[M, 2]`, all values must be >= 0. + `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension + `i + 1`, which corresponds to spatial dimension `i`. It is required that + `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SpaceToBatchND", name, input, block_shape, paddings) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_space_to_batch_nd( + (input, block_shape, paddings, name,), None) + if _result is not NotImplemented: + return _result + return space_to_batch_nd_eager_fallback( + input, block_shape, paddings, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + space_to_batch_nd, (), dict(input=input, block_shape=block_shape, + paddings=paddings, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_space_to_batch_nd( + (input, block_shape, paddings, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SpaceToBatchND", input=input, block_shape=block_shape, + paddings=paddings, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + space_to_batch_nd, (), dict(input=input, block_shape=block_shape, + paddings=paddings, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tblock_shape", + _op._get_attr_type("Tblock_shape"), "Tpaddings", + _op._get_attr_type("Tpaddings")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SpaceToBatchND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SpaceToBatchND = tf_export("raw_ops.SpaceToBatchND")(_ops.to_raw_op(space_to_batch_nd)) +_dispatcher_for_space_to_batch_nd = space_to_batch_nd._tf_type_based_dispatcher.Dispatch + + +def space_to_batch_nd_eager_fallback(input: Annotated[Any, TV_SpaceToBatchND_T], block_shape: Annotated[Any, TV_SpaceToBatchND_Tblock_shape], paddings: Annotated[Any, TV_SpaceToBatchND_Tpaddings], name, ctx) -> Annotated[Any, TV_SpaceToBatchND_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tblock_shape, (block_shape,) = _execute.args_to_matching_eager([block_shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, block_shape, paddings] + _attrs = ("T", _attr_T, "Tblock_shape", _attr_Tblock_shape, "Tpaddings", + _attr_Tpaddings) + _result = _execute.execute(b"SpaceToBatchND", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SpaceToBatchND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SpaceToDepth_T = TypeVar("TV_SpaceToDepth_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def space_to_depth(input: Annotated[Any, TV_SpaceToDepth_T], block_size: int, data_format:str="NHWC", name=None) -> Annotated[Any, TV_SpaceToDepth_T]: + r"""SpaceToDepth for tensors of type T. + + Rearranges blocks of spatial data, into depth. More specifically, + this op outputs a copy of the input tensor where values from the `height` + and `width` dimensions are moved to the `depth` dimension. + The attr `block_size` indicates the input block size. + + * Non-overlapping blocks of size `block_size x block size` are rearranged + into depth at each location. + * The depth of the output tensor is `block_size * block_size * input_depth`. + * The Y, X coordinates within each block of the input become the high order + component of the output channel index. + * The input tensor's height and width must be divisible by block_size. + + The `data_format` attr specifies the layout of the input and output tensors + with the following options: + "NHWC": `[ batch, height, width, channels ]` + "NCHW": `[ batch, channels, height, width ]` + "NCHW_VECT_C": + `qint8 [ batch, channels / 4, height, width, 4 ]` + + It is useful to consider the operation as transforming a 6-D Tensor. + e.g. for data_format = NHWC, + Each element in the input tensor can be specified via 6 coordinates, + ordered by decreasing memory layout significance as: + n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates + within the output image, bX, bY means coordinates + within the input block, iC means input channels). + The output would be a transpose to the following layout: + n,oY,oX,bY,bX,iC + + This operation is useful for resizing the activations between convolutions + (but keeping all data), e.g. instead of pooling. It is also useful for training + purely convolutional models. + + For example, given an input of shape `[1, 2, 2, 1]`, data_format = "NHWC" and + block_size = 2: + + ``` + x = [[[[1], [2]], + [[3], [4]]]] + ``` + + This operation will output a tensor of shape `[1, 1, 1, 4]`: + + ``` + [[[[1, 2, 3, 4]]]] + ``` + + Here, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`, + the corresponding output will have a single element (i.e. width and height are + both 1) and will have a depth of 4 channels (1 * block_size * block_size). + The output element shape is `[1, 1, 4]`. + + For an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g. + + ``` + x = [[[[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]]]] + ``` + + This operation, for block_size of 2, will return the following tensor of shape + `[1, 1, 1, 12]` + + ``` + [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] + ``` + + Similarly, for the following input of shape `[1 4 4 1]`, and a block size of 2: + + ``` + x = [[[[1], [2], [5], [6]], + [[3], [4], [7], [8]], + [[9], [10], [13], [14]], + [[11], [12], [15], [16]]]] + ``` + + the operator will return the following tensor of shape `[1 2 2 4]`: + + ``` + x = [[[[1, 2, 3, 4], + [5, 6, 7, 8]], + [[9, 10, 11, 12], + [13, 14, 15, 16]]]] + ``` + + Args: + input: A `Tensor`. + block_size: An `int` that is `>= 2`. The size of the spatial block. + data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SpaceToDepth", name, input, "block_size", block_size, + "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return space_to_depth_eager_fallback( + input, block_size=block_size, data_format=data_format, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + block_size = _execute.make_int(block_size, "block_size") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SpaceToDepth", input=input, block_size=block_size, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "block_size", + _op._get_attr_int("block_size"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SpaceToDepth", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SpaceToDepth = tf_export("raw_ops.SpaceToDepth")(_ops.to_raw_op(space_to_depth)) + + +def space_to_depth_eager_fallback(input: Annotated[Any, TV_SpaceToDepth_T], block_size: int, data_format: str, name, ctx) -> Annotated[Any, TV_SpaceToDepth_T]: + block_size = _execute.make_int(block_size, "block_size") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "block_size", block_size, "data_format", + data_format) + _result = _execute.execute(b"SpaceToDepth", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SpaceToDepth", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Split_T = TypeVar("TV_Split_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def split(axis: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_Split_T], num_split: int, name=None): + r"""Splits a tensor into `num_split` tensors along one dimension. + + Args: + axis: A `Tensor` of type `int32`. + 0-D. The dimension along which to split. Must be in the range + `[-rank(value), rank(value))`. + value: A `Tensor`. The tensor to split. + num_split: An `int` that is `>= 1`. + The number of ways to split. Must evenly divide + `value.shape[split_dim]`. + name: A name for the operation (optional). + + Returns: + A list of `num_split` `Tensor` objects with the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Split", name, axis, value, "num_split", num_split) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return split_eager_fallback( + axis, value, num_split=num_split, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_split = _execute.make_int(num_split, "num_split") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Split", split_dim=axis, value=value, num_split=num_split, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_split", _op._get_attr_int("num_split"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Split", _inputs_flat, _attrs, _result) + return _result + +Split = tf_export("raw_ops.Split")(_ops.to_raw_op(split)) + + +def split_eager_fallback(axis: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_Split_T], num_split: int, name, ctx): + num_split = _execute.make_int(num_split, "num_split") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + axis = _ops.convert_to_tensor(axis, _dtypes.int32) + _inputs_flat = [axis, value] + _attrs = ("num_split", num_split, "T", _attr_T) + _result = _execute.execute(b"Split", num_split, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Split", _inputs_flat, _attrs, _result) + return _result + + +TV_SplitV_T = TypeVar("TV_SplitV_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SplitV_Tlen = TypeVar("TV_SplitV_Tlen", _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def split_v(value: Annotated[Any, TV_SplitV_T], size_splits: Annotated[Any, TV_SplitV_Tlen], axis: Annotated[Any, _atypes.Int32], num_split: int, name=None): + r"""Splits a tensor into `num_split` tensors along one dimension. + + Args: + value: A `Tensor`. The tensor to split. + size_splits: A `Tensor`. Must be one of the following types: `int8`, `int32`, `int64`. + list containing the sizes of each output tensor along the split + dimension. Must sum to the dimension of value along split_dim. + Can contain one -1 indicating that dimension is to be inferred. + axis: A `Tensor` of type `int32`. + 0-D. The dimension along which to split. Must be in the range + `[-rank(value), rank(value))`. + num_split: An `int` that is `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `num_split` `Tensor` objects with the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SplitV", name, value, size_splits, axis, "num_split", + num_split) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return split_v_eager_fallback( + value, size_splits, axis, num_split=num_split, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_split = _execute.make_int(num_split, "num_split") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SplitV", value=value, size_splits=size_splits, split_dim=axis, + num_split=num_split, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_split", _op._get_attr_int("num_split"), "T", + _op._get_attr_type("T"), "Tlen", _op._get_attr_type("Tlen")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SplitV", _inputs_flat, _attrs, _result) + return _result + +SplitV = tf_export("raw_ops.SplitV")(_ops.to_raw_op(split_v)) + + +def split_v_eager_fallback(value: Annotated[Any, TV_SplitV_T], size_splits: Annotated[Any, TV_SplitV_Tlen], axis: Annotated[Any, _atypes.Int32], num_split: int, name, ctx): + num_split = _execute.make_int(num_split, "num_split") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _attr_Tlen, (size_splits,) = _execute.args_to_matching_eager([size_splits], ctx, [_dtypes.int8, _dtypes.int32, _dtypes.int64, ], _dtypes.int64) + axis = _ops.convert_to_tensor(axis, _dtypes.int32) + _inputs_flat = [value, size_splits, axis] + _attrs = ("num_split", num_split, "T", _attr_T, "Tlen", _attr_Tlen) + _result = _execute.execute(b"SplitV", num_split, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SplitV", _inputs_flat, _attrs, _result) + return _result + + +TV_Squeeze_T = TypeVar("TV_Squeeze_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def squeeze(input: Annotated[Any, TV_Squeeze_T], axis=[], name=None) -> Annotated[Any, TV_Squeeze_T]: + r"""Removes dimensions of size 1 from the shape of a tensor. + + Given a tensor `input`, this operation returns a tensor of the same type with + all dimensions of size 1 removed. If you don't want to remove all size 1 + dimensions, you can remove specific size 1 dimensions by specifying + `axis`. + + For example: + + ``` + # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + shape(squeeze(t)) ==> [2, 3] + ``` + + Or, to remove specific size 1 dimensions: + + ``` + # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] + shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1] + ``` + + Args: + input: A `Tensor`. The `input` to squeeze. + axis: An optional list of `ints`. Defaults to `[]`. + If specified, only squeezes the dimensions listed. The dimension + index starts at 0. It is an error to squeeze a dimension that is not 1. Must + be in the range `[-rank(input), rank(input))`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Squeeze", name, input, "squeeze_dims", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return squeeze_eager_fallback( + input, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if axis is None: + axis = [] + if not isinstance(axis, (list, tuple)): + raise TypeError( + "Expected list for 'axis' argument to " + "'squeeze' Op, not %r." % axis) + axis = [_execute.make_int(_i, "axis") for _i in axis] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Squeeze", input=input, squeeze_dims=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "squeeze_dims", + _op.get_attr("squeeze_dims")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Squeeze", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Squeeze = tf_export("raw_ops.Squeeze")(_ops.to_raw_op(squeeze)) + + +def squeeze_eager_fallback(input: Annotated[Any, TV_Squeeze_T], axis, name, ctx) -> Annotated[Any, TV_Squeeze_T]: + if axis is None: + axis = [] + if not isinstance(axis, (list, tuple)): + raise TypeError( + "Expected list for 'axis' argument to " + "'squeeze' Op, not %r." % axis) + axis = [_execute.make_int(_i, "axis") for _i in axis] + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "squeeze_dims", axis) + _result = _execute.execute(b"Squeeze", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Squeeze", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StopGradient_T = TypeVar("TV_StopGradient_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stop_gradient(input: Annotated[Any, TV_StopGradient_T], name=None) -> Annotated[Any, TV_StopGradient_T]: + r"""Stops gradient computation. + + When executed in a graph, this op outputs its input tensor as-is. + + When building ops to compute gradients, this op prevents the contribution of + its inputs to be taken into account. Normally, the gradient generator adds ops + to a graph to compute the derivatives of a specified 'loss' by recursively + finding out inputs that contributed to its computation. If you insert this op + in the graph it inputs are masked from the gradient generator. They are not + taken into account for computing gradients. + + This is useful any time you want to compute a value with TensorFlow but need + to pretend that the value was a constant. For example, the softmax function + for a vector x can be written as + + ```python + + def softmax(x): + numerator = tf.exp(x) + denominator = tf.reduce_sum(numerator) + return numerator / denominator + ``` + + This however is susceptible to overflow if the values in x are large. An + alternative more stable way is to subtract the maximum of x from each of the + values. + + ```python + + def stable_softmax(x): + z = x - tf.reduce_max(x) + numerator = tf.exp(z) + denominator = tf.reduce_sum(numerator) + return numerator / denominator + ``` + + However, when we backprop through the softmax to x, we dont want to backprop + through the `tf.reduce_max(x)` (if the max values are not unique then the + gradient could flow to the wrong input) calculation and treat that as a + constant. Therefore, we should write this out as + + ```python + + def stable_softmax(x): + z = x - tf.stop_gradient(tf.reduce_max(x)) + numerator = tf.exp(z) + denominator = tf.reduce_sum(numerator) + return numerator / denominator + ``` + + Some other examples include: + + * The *EM* algorithm where the *M-step* should not involve backpropagation + through the output of the *E-step*. + * Contrastive divergence training of Boltzmann machines where, when + differentiating the energy function, the training must not backpropagate + through the graph that generated the samples from the model. + * Adversarial training, where no backprop should happen through the adversarial + example generation process. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StopGradient", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stop_gradient_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StopGradient", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StopGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StopGradient = tf_export("raw_ops.StopGradient")(_ops.to_raw_op(stop_gradient)) + + +def stop_gradient_eager_fallback(input: Annotated[Any, TV_StopGradient_T], name, ctx) -> Annotated[Any, TV_StopGradient_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"StopGradient", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StopGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StridedSlice_T = TypeVar("TV_StridedSlice_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StridedSlice_Index = TypeVar("TV_StridedSlice_Index", _atypes.Int16, _atypes.Int32, _atypes.Int64) + +def strided_slice(input: Annotated[Any, TV_StridedSlice_T], begin: Annotated[Any, TV_StridedSlice_Index], end: Annotated[Any, TV_StridedSlice_Index], strides: Annotated[Any, TV_StridedSlice_Index], begin_mask:int=0, end_mask:int=0, ellipsis_mask:int=0, new_axis_mask:int=0, shrink_axis_mask:int=0, name=None) -> Annotated[Any, TV_StridedSlice_T]: + r"""Return a strided slice from `input`. + + Note, most python users will want to use the Python `Tensor.__getitem__` + or `Variable.__getitem__` rather than this op directly. + + The goal of this op is to produce a new tensor with a subset of + the elements from the `n` dimensional `input` tensor. The subset is chosen using + a sequence of `m` sparse range specifications encoded into the arguments + of this function. Note, in some cases + `m` could be equal to `n`, but this need not be the case. Each + range specification entry can be one of the following: + + - An ellipsis (...). Ellipses are used to imply zero or more + dimensions of full-dimension selection and are produced using + `ellipsis_mask`. For example, `foo[...]` is the identity slice. + + - A new axis. This is used to insert a new shape=1 dimension and is + produced using `new_axis_mask`. For example, `foo[:, ...]` where + `foo` is shape `(3, 4)` produces a `(1, 3, 4)` tensor. + + + - A range `begin:end:stride`. This is used to specify how much to choose from + a given dimension. `stride` can be any integer but 0. `begin` is an integer + which represents the index of the first value to select while `end` represents + the index of the last value to select. The number of values selected in each + dimension is `end - begin` if `stride > 0` and `begin - end` if `stride < 0`. + `begin` and `end` can be negative where `-1` is the last element, `-2` is + the second to last. `begin_mask` controls whether to replace the explicitly + given `begin` with an implicit effective value of `0` if `stride > 0` and + `-1` if `stride < 0`. `end_mask` is analogous but produces the number + required to create the largest open interval. For example, given a shape + `(3,)` tensor `foo[:]`, the effective `begin` and `end` are `0` and `3`. Do + not assume this is equivalent to `foo[0:-1]` which has an effective `begin` + and `end` of `0` and `2`. Another example is `foo[-2::-1]` which reverses the + first dimension of a tensor while dropping the last two (in the original + order elements). For example `foo = [1,2,3,4]; foo[-2::-1]` is `[4,3]`. + + - A single index. This is used to keep only elements that have a given + index. For example (`foo[2, :]` on a shape `(5,6)` tensor produces a + shape `(6,)` tensor. This is encoded in `begin` and `end` and + `shrink_axis_mask`. + + Each conceptual range specification is encoded in the op's argument. This + encoding is best understand by considering a non-trivial example. In + particular, + `foo[1, 2:4, None, ..., :-3:-1, :]` will be encoded as + + ``` + begin = [1, 2, x, x, 0, x] # x denotes don't care (usually 0) + end = [2, 4, x, x, -3, x] + strides = [1, 1, x, x, -1, 1] + begin_mask = 1<<4 | 1<<5 = 48 + end_mask = 1<<5 = 32 + ellipsis_mask = 1<<3 = 8 + new_axis_mask = 1<<2 = 4 + shrink_axis_mask = 1<<0 = 1 + ``` + + In this case if `foo.shape` is (5, 5, 5, 5, 5, 5) the final shape of + the slice becomes (2, 1, 5, 5, 2, 5). + Let us walk step by step through each argument specification. + + 1. The first argument in the example slice is turned into `begin = 1` and + `end = begin + 1 = 2`. To disambiguate from the original spec `2:4` we + also set the appropriate bit in `shrink_axis_mask`. + + 2. `2:4` is contributes 2, 4, 1 to begin, end, and stride. All masks have + zero bits contributed. + + 3. None is a synonym for `tf.newaxis`. This means insert a dimension of size 1 + dimension in the final shape. Dummy values are contributed to begin, + end and stride, while the new_axis_mask bit is set. + + 4. `...` grab the full ranges from as many dimensions as needed to + fully specify a slice for every dimension of the input shape. + + 5. `:-3:-1` shows the use of negative indices. A negative index `i` associated + with a dimension that has shape `s` is converted to a positive index + `s + i`. So `-1` becomes `s-1` (i.e. the last element). This conversion + is done internally so begin, end and strides receive x, -3, and -1. + The appropriate begin_mask bit is set to indicate the start range is the + full range (ignoring the x). + + 6. `:` indicates that the entire contents of the corresponding dimension + is selected. This is equivalent to `::` or `0::1`. begin, end, and strides + receive 0, 0, and 1, respectively. The appropriate bits in `begin_mask` and + `end_mask` are also set. + + *Requirements*: + `0 != strides[i] for i in [0, m)` + `ellipsis_mask must be a power of two (only one ellipsis)` + + Args: + input: A `Tensor`. + begin: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + `begin[k]` specifies the offset into the `k`th range specification. + The exact dimension this corresponds to will be determined by context. + Out-of-bounds values will be silently clamped. If the `k`th bit of + `begin_mask` then `begin[k]` is ignored and the full range of the + appropriate dimension is used instead. Negative values causes indexing + to start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`. + end: A `Tensor`. Must have the same type as `begin`. + `end[i]` is like `begin` with the exception that `end_mask` is + used to determine full ranges. + strides: A `Tensor`. Must have the same type as `begin`. + `strides[i]` specifies the increment in the `i`th specification + after extracting a given element. Negative indices will reverse + the original order. Out or range values are + clamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0` + begin_mask: An optional `int`. Defaults to `0`. + a bitmask where a bit i being 1 means to ignore the begin + value and instead use the largest interval possible. At runtime + begin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or + `[-1, n-1]` if `stride[i] < 0` + end_mask: An optional `int`. Defaults to `0`. analogous to `begin_mask` + ellipsis_mask: An optional `int`. Defaults to `0`. + a bitmask where bit `i` being 1 means the `i`th + position is actually an ellipsis. One bit at most can be 1. + If `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)` + is provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis + implicitly creates as many range specifications as necessary to fully + specify the sliced range for every dimension. For example for a 4-dimensional + tensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`. + new_axis_mask: An optional `int`. Defaults to `0`. + a bitmask where bit `i` being 1 means the `i`th + specification creates a new shape 1 dimension. For example + `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. + shrink_axis_mask: An optional `int`. Defaults to `0`. + a bitmask where bit `i` implies that the `i`th + specification should shrink the dimensionality. begin and end + must imply a slice of size 1 in the dimension. For example in + python one might do `foo[:, 3, :]` which would result in + `shrink_axis_mask` being 2. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StridedSlice", name, input, begin, end, strides, "begin_mask", + begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, + "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return strided_slice_eager_fallback( + input, begin, end, strides, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StridedSlice", input=input, begin=begin, end=end, strides=strides, + begin_mask=begin_mask, end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Index", + _op._get_attr_type("Index"), "begin_mask", + _op._get_attr_int("begin_mask"), "end_mask", + _op._get_attr_int("end_mask"), "ellipsis_mask", + _op._get_attr_int("ellipsis_mask"), "new_axis_mask", + _op._get_attr_int("new_axis_mask"), "shrink_axis_mask", + _op._get_attr_int("shrink_axis_mask")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StridedSlice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StridedSlice = tf_export("raw_ops.StridedSlice")(_ops.to_raw_op(strided_slice)) + + +def strided_slice_eager_fallback(input: Annotated[Any, TV_StridedSlice_T], begin: Annotated[Any, TV_StridedSlice_Index], end: Annotated[Any, TV_StridedSlice_Index], strides: Annotated[Any, TV_StridedSlice_Index], begin_mask: int, end_mask: int, ellipsis_mask: int, new_axis_mask: int, shrink_axis_mask: int, name, ctx) -> Annotated[Any, TV_StridedSlice_T]: + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, end, strides], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + (begin, end, strides) = _inputs_Index + _inputs_flat = [input, begin, end, strides] + _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, + "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", + new_axis_mask, "shrink_axis_mask", shrink_axis_mask) + _result = _execute.execute(b"StridedSlice", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StridedSlice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StridedSliceAssign_T = TypeVar("TV_StridedSliceAssign_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StridedSliceAssign_Index = TypeVar("TV_StridedSliceAssign_Index", _atypes.Int32, _atypes.Int64) + +def strided_slice_assign(ref: Annotated[Any, TV_StridedSliceAssign_T], begin: Annotated[Any, TV_StridedSliceAssign_Index], end: Annotated[Any, TV_StridedSliceAssign_Index], strides: Annotated[Any, TV_StridedSliceAssign_Index], value: Annotated[Any, TV_StridedSliceAssign_T], begin_mask:int=0, end_mask:int=0, ellipsis_mask:int=0, new_axis_mask:int=0, shrink_axis_mask:int=0, name=None) -> Annotated[Any, TV_StridedSliceAssign_T]: + r"""Assign `value` to the sliced l-value reference of `ref`. + + The values of `value` are assigned to the positions in the variable + `ref` that are selected by the slice parameters. The slice parameters + `begin`, `end`, `strides`, etc. work exactly as in `StridedSlice`. + + NOTE this op currently does not support broadcasting and so `value`'s + shape must be exactly the shape produced by the slice of `ref`. + + Args: + ref: A mutable `Tensor`. + begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. + end: A `Tensor`. Must have the same type as `begin`. + strides: A `Tensor`. Must have the same type as `begin`. + value: A `Tensor`. Must have the same type as `ref`. + begin_mask: An optional `int`. Defaults to `0`. + end_mask: An optional `int`. Defaults to `0`. + ellipsis_mask: An optional `int`. Defaults to `0`. + new_axis_mask: An optional `int`. Defaults to `0`. + shrink_axis_mask: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("strided_slice_assign op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StridedSliceAssign", ref=ref, begin=begin, end=end, strides=strides, + value=value, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Index", + _op._get_attr_type("Index"), "begin_mask", + _op._get_attr_int("begin_mask"), "end_mask", + _op._get_attr_int("end_mask"), "ellipsis_mask", + _op._get_attr_int("ellipsis_mask"), "new_axis_mask", + _op._get_attr_int("new_axis_mask"), "shrink_axis_mask", + _op._get_attr_int("shrink_axis_mask")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StridedSliceAssign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StridedSliceAssign = tf_export("raw_ops.StridedSliceAssign")(_ops.to_raw_op(strided_slice_assign)) + + +def strided_slice_assign_eager_fallback(ref: Annotated[Any, TV_StridedSliceAssign_T], begin: Annotated[Any, TV_StridedSliceAssign_Index], end: Annotated[Any, TV_StridedSliceAssign_Index], strides: Annotated[Any, TV_StridedSliceAssign_Index], value: Annotated[Any, TV_StridedSliceAssign_T], begin_mask: int, end_mask: int, ellipsis_mask: int, new_axis_mask: int, shrink_axis_mask: int, name, ctx) -> Annotated[Any, TV_StridedSliceAssign_T]: + raise RuntimeError("strided_slice_assign op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_StridedSliceGrad_T = TypeVar("TV_StridedSliceGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StridedSliceGrad_Index = TypeVar("TV_StridedSliceGrad_Index", _atypes.Int32, _atypes.Int64) + +def strided_slice_grad(shape: Annotated[Any, TV_StridedSliceGrad_Index], begin: Annotated[Any, TV_StridedSliceGrad_Index], end: Annotated[Any, TV_StridedSliceGrad_Index], strides: Annotated[Any, TV_StridedSliceGrad_Index], dy: Annotated[Any, TV_StridedSliceGrad_T], begin_mask:int=0, end_mask:int=0, ellipsis_mask:int=0, new_axis_mask:int=0, shrink_axis_mask:int=0, name=None) -> Annotated[Any, TV_StridedSliceGrad_T]: + r"""Returns the gradient of `StridedSlice`. + + Since `StridedSlice` cuts out pieces of its `input` which is size + `shape`, its gradient will have the same shape (which is passed here + as `shape`). The gradient will be zero in any element that the slice + does not select. + + Arguments are the same as StridedSliceGrad with the exception that + `dy` is the input gradient to be propagated and `shape` is the + shape of `StridedSlice`'s `input`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + begin: A `Tensor`. Must have the same type as `shape`. + end: A `Tensor`. Must have the same type as `shape`. + strides: A `Tensor`. Must have the same type as `shape`. + dy: A `Tensor`. + begin_mask: An optional `int`. Defaults to `0`. + end_mask: An optional `int`. Defaults to `0`. + ellipsis_mask: An optional `int`. Defaults to `0`. + new_axis_mask: An optional `int`. Defaults to `0`. + shrink_axis_mask: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `dy`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StridedSliceGrad", name, shape, begin, end, strides, dy, + "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", + ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", + shrink_axis_mask) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return strided_slice_grad_eager_fallback( + shape, begin, end, strides, dy, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StridedSliceGrad", shape=shape, begin=begin, end=end, + strides=strides, dy=dy, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Index", + _op._get_attr_type("Index"), "begin_mask", + _op._get_attr_int("begin_mask"), "end_mask", + _op._get_attr_int("end_mask"), "ellipsis_mask", + _op._get_attr_int("ellipsis_mask"), "new_axis_mask", + _op._get_attr_int("new_axis_mask"), "shrink_axis_mask", + _op._get_attr_int("shrink_axis_mask")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StridedSliceGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StridedSliceGrad = tf_export("raw_ops.StridedSliceGrad")(_ops.to_raw_op(strided_slice_grad)) + + +def strided_slice_grad_eager_fallback(shape: Annotated[Any, TV_StridedSliceGrad_Index], begin: Annotated[Any, TV_StridedSliceGrad_Index], end: Annotated[Any, TV_StridedSliceGrad_Index], strides: Annotated[Any, TV_StridedSliceGrad_Index], dy: Annotated[Any, TV_StridedSliceGrad_T], begin_mask: int, end_mask: int, ellipsis_mask: int, new_axis_mask: int, shrink_axis_mask: int, name, ctx) -> Annotated[Any, TV_StridedSliceGrad_T]: + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _attr_T, (dy,) = _execute.args_to_matching_eager([dy], ctx, []) + _attr_Index, _inputs_Index = _execute.args_to_matching_eager([shape, begin, end, strides], ctx, [_dtypes.int32, _dtypes.int64, ]) + (shape, begin, end, strides) = _inputs_Index + _inputs_flat = [shape, begin, end, strides, dy] + _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, + "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", + new_axis_mask, "shrink_axis_mask", shrink_axis_mask) + _result = _execute.execute(b"StridedSliceGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StridedSliceGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorScatterAdd_T = TypeVar("TV_TensorScatterAdd_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorScatterAdd_Tindices = TypeVar("TV_TensorScatterAdd_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('tensor_scatter_nd_add', v1=['tensor_scatter_nd_add', 'tensor_scatter_add']) +@deprecated_endpoints('tensor_scatter_add') +def tensor_scatter_add(tensor: Annotated[Any, TV_TensorScatterAdd_T], indices: Annotated[Any, TV_TensorScatterAdd_Tindices], updates: Annotated[Any, TV_TensorScatterAdd_T], name=None) -> Annotated[Any, TV_TensorScatterAdd_T]: + r"""Adds sparse `updates` to an existing tensor according to `indices`. + + This operation creates a new tensor by adding sparse `updates` to the passed + in `tensor`. + This operation is very similar to `tf.compat.v1.scatter_nd_add`, except that the + updates are added onto an existing tensor (as opposed to a variable). If the + memory for the existing tensor cannot be re-used, a copy is made and updated. + + `indices` is an integer tensor containing indices into a new tensor of shape + `tensor.shape`. The last dimension of `indices` can be at most the rank of + `tensor.shape`: + + ``` + indices.shape[-1] <= tensor.shape.rank + ``` + + The last dimension of `indices` corresponds to indices into elements + (if `indices.shape[-1] = tensor.shape.rank`) or slices + (if `indices.shape[-1] < tensor.shape.rank`) along dimension + `indices.shape[-1]` of `tensor.shape`. `updates` is a tensor with shape + + ``` + indices.shape[:-1] + tensor.shape[indices.shape[-1]:] + ``` + + The simplest form of `tensor_scatter_nd_add` is to add individual elements to a + tensor by index. For example, say we want to add 4 elements in a rank-1 + tensor with 8 elements. + + In Python, this scatter add operation would look like this: + + >>> indices = tf.constant([[4], [3], [1], [7]]) + >>> updates = tf.constant([9, 10, 11, 12]) + >>> tensor = tf.ones([8], dtype=tf.int32) + >>> updated = tf.tensor_scatter_nd_add(tensor, indices, updates) + >>> updated + + + We can also, insert entire slices of a higher rank tensor all at once. For + example, if we wanted to insert two slices in the first dimension of a + rank-3 tensor with two matrices of new values. + + In Python, this scatter add operation would look like this: + + >>> indices = tf.constant([[0], [2]]) + >>> updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], + ... [7, 7, 7, 7], [8, 8, 8, 8]], + ... [[5, 5, 5, 5], [6, 6, 6, 6], + ... [7, 7, 7, 7], [8, 8, 8, 8]]]) + >>> tensor = tf.ones([4, 4, 4],dtype=tf.int32) + >>> updated = tf.tensor_scatter_nd_add(tensor, indices, updates) + >>> updated + + + Note: on CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, the index is ignored. + + Args: + tensor: A `Tensor`. Tensor to copy/update. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + updates: A `Tensor`. Must have the same type as `tensor`. + Updates to scatter into output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorScatterAdd", name, tensor, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tensor_scatter_add( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + return tensor_scatter_add_eager_fallback( + tensor, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_add, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tensor_scatter_add( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorScatterAdd", tensor=tensor, indices=indices, updates=updates, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_add, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorScatterAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorScatterAdd = tf_export("raw_ops.TensorScatterAdd")(_ops.to_raw_op(tensor_scatter_add)) +_dispatcher_for_tensor_scatter_add = tensor_scatter_add._tf_type_based_dispatcher.Dispatch + + +def tensor_scatter_add_eager_fallback(tensor: Annotated[Any, TV_TensorScatterAdd_T], indices: Annotated[Any, TV_TensorScatterAdd_Tindices], updates: Annotated[Any, TV_TensorScatterAdd_T], name, ctx) -> Annotated[Any, TV_TensorScatterAdd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], ctx, []) + (tensor, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [tensor, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"TensorScatterAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorScatterAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorScatterMax_T = TypeVar("TV_TensorScatterMax_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorScatterMax_Tindices = TypeVar("TV_TensorScatterMax_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('tensor_scatter_nd_max') +def tensor_scatter_max(tensor: Annotated[Any, TV_TensorScatterMax_T], indices: Annotated[Any, TV_TensorScatterMax_Tindices], updates: Annotated[Any, TV_TensorScatterMax_T], name=None) -> Annotated[Any, TV_TensorScatterMax_T]: + r"""Apply a sparse update to a tensor taking the element-wise maximum. + + Returns a new tensor copied from `tensor` whose values are element-wise maximum between + tensor and updates according to the indices. + + >>> tensor = [0, 0, 0, 0, 0, 0, 0, 0] + >>> indices = [[1], [4], [5]] + >>> updates = [1, -1, 1] + >>> tf.tensor_scatter_nd_max(tensor, indices, updates).numpy() + array([0, 1, 0, 0, 0, 1, 0, 0], dtype=int32) + + Refer to `tf.tensor_scatter_nd_update` for more details. + + Args: + tensor: A `Tensor`. Tensor to update. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + updates: A `Tensor`. Must have the same type as `tensor`. + Updates to scatter into output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorScatterMax", name, tensor, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tensor_scatter_max( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + return tensor_scatter_max_eager_fallback( + tensor, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_max, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tensor_scatter_max( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorScatterMax", tensor=tensor, indices=indices, updates=updates, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_max, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorScatterMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorScatterMax = tf_export("raw_ops.TensorScatterMax")(_ops.to_raw_op(tensor_scatter_max)) +_dispatcher_for_tensor_scatter_max = tensor_scatter_max._tf_type_based_dispatcher.Dispatch + + +def tensor_scatter_max_eager_fallback(tensor: Annotated[Any, TV_TensorScatterMax_T], indices: Annotated[Any, TV_TensorScatterMax_Tindices], updates: Annotated[Any, TV_TensorScatterMax_T], name, ctx) -> Annotated[Any, TV_TensorScatterMax_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], ctx, []) + (tensor, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [tensor, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"TensorScatterMax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorScatterMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorScatterMin_T = TypeVar("TV_TensorScatterMin_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorScatterMin_Tindices = TypeVar("TV_TensorScatterMin_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('tensor_scatter_nd_min') +def tensor_scatter_min(tensor: Annotated[Any, TV_TensorScatterMin_T], indices: Annotated[Any, TV_TensorScatterMin_Tindices], updates: Annotated[Any, TV_TensorScatterMin_T], name=None) -> Annotated[Any, TV_TensorScatterMin_T]: + r"""TODO: add doc. + + Args: + tensor: A `Tensor`. Tensor to update. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + updates: A `Tensor`. Must have the same type as `tensor`. + Updates to scatter into output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorScatterMin", name, tensor, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tensor_scatter_min( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + return tensor_scatter_min_eager_fallback( + tensor, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_min, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tensor_scatter_min( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorScatterMin", tensor=tensor, indices=indices, updates=updates, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_min, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorScatterMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorScatterMin = tf_export("raw_ops.TensorScatterMin")(_ops.to_raw_op(tensor_scatter_min)) +_dispatcher_for_tensor_scatter_min = tensor_scatter_min._tf_type_based_dispatcher.Dispatch + + +def tensor_scatter_min_eager_fallback(tensor: Annotated[Any, TV_TensorScatterMin_T], indices: Annotated[Any, TV_TensorScatterMin_Tindices], updates: Annotated[Any, TV_TensorScatterMin_T], name, ctx) -> Annotated[Any, TV_TensorScatterMin_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], ctx, []) + (tensor, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [tensor, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"TensorScatterMin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorScatterMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorScatterSub_T = TypeVar("TV_TensorScatterSub_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorScatterSub_Tindices = TypeVar("TV_TensorScatterSub_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('tensor_scatter_nd_sub', v1=['tensor_scatter_nd_sub', 'tensor_scatter_sub']) +@deprecated_endpoints('tensor_scatter_sub') +def tensor_scatter_sub(tensor: Annotated[Any, TV_TensorScatterSub_T], indices: Annotated[Any, TV_TensorScatterSub_Tindices], updates: Annotated[Any, TV_TensorScatterSub_T], name=None) -> Annotated[Any, TV_TensorScatterSub_T]: + r"""Subtracts sparse `updates` from an existing tensor according to `indices`. + + This operation creates a new tensor by subtracting sparse `updates` from the + passed in `tensor`. + This operation is very similar to `tf.scatter_nd_sub`, except that the updates + are subtracted from an existing tensor (as opposed to a variable). If the memory + for the existing tensor cannot be re-used, a copy is made and updated. + + `indices` is an integer tensor containing indices into a new tensor of shape + `shape`. The last dimension of `indices` can be at most the rank of `shape`: + + indices.shape[-1] <= shape.rank + + The last dimension of `indices` corresponds to indices into elements + (if `indices.shape[-1] = shape.rank`) or slices + (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of + `shape`. `updates` is a tensor with shape + + indices.shape[:-1] + shape[indices.shape[-1]:] + + The simplest form of tensor_scatter_sub is to subtract individual elements + from a tensor by index. For example, say we want to insert 4 scattered elements + in a rank-1 tensor with 8 elements. + + In Python, this scatter subtract operation would look like this: + + ```python + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + tensor = tf.ones([8], dtype=tf.int32) + updated = tf.tensor_scatter_nd_sub(tensor, indices, updates) + print(updated) + ``` + + The resulting tensor would look like this: + + [1, -10, 1, -9, -8, 1, 1, -11] + + We can also, insert entire slices of a higher rank tensor all at once. For + example, if we wanted to insert two slices in the first dimension of a + rank-3 tensor with two matrices of new values. + + In Python, this scatter add operation would look like this: + + ```python + indices = tf.constant([[0], [2]]) + updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], + [7, 7, 7, 7], [8, 8, 8, 8]], + [[5, 5, 5, 5], [6, 6, 6, 6], + [7, 7, 7, 7], [8, 8, 8, 8]]]) + tensor = tf.ones([4, 4, 4],dtype=tf.int32) + updated = tf.tensor_scatter_nd_sub(tensor, indices, updates) + print(updated) + ``` + + The resulting tensor would look like this: + + [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], + [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], + [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], + [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] + + Note that on CPU, if an out of bound index is found, an error is returned. + On GPU, if an out of bound index is found, the index is ignored. + + Args: + tensor: A `Tensor`. Tensor to copy/update. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + updates: A `Tensor`. Must have the same type as `tensor`. + Updates to scatter into output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorScatterSub", name, tensor, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tensor_scatter_sub( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + return tensor_scatter_sub_eager_fallback( + tensor, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_sub, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tensor_scatter_sub( + (tensor, indices, updates, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorScatterSub", tensor=tensor, indices=indices, updates=updates, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tensor_scatter_sub, (), dict(tensor=tensor, indices=indices, + updates=updates, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorScatterSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorScatterSub = tf_export("raw_ops.TensorScatterSub")(_ops.to_raw_op(tensor_scatter_sub)) +_dispatcher_for_tensor_scatter_sub = tensor_scatter_sub._tf_type_based_dispatcher.Dispatch + + +def tensor_scatter_sub_eager_fallback(tensor: Annotated[Any, TV_TensorScatterSub_T], indices: Annotated[Any, TV_TensorScatterSub_Tindices], updates: Annotated[Any, TV_TensorScatterSub_T], name, ctx) -> Annotated[Any, TV_TensorScatterSub_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], ctx, []) + (tensor, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [tensor, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"TensorScatterSub", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorScatterSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorScatterUpdate_T = TypeVar("TV_TensorScatterUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorScatterUpdate_Tindices = TypeVar("TV_TensorScatterUpdate_Tindices", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.UInt16) + +def tensor_scatter_update(tensor: Annotated[Any, TV_TensorScatterUpdate_T], indices: Annotated[Any, TV_TensorScatterUpdate_Tindices], updates: Annotated[Any, TV_TensorScatterUpdate_T], name=None) -> Annotated[Any, TV_TensorScatterUpdate_T]: + r"""Scatter `updates` into an existing tensor according to `indices`. + + This operation creates a new tensor by applying sparse `updates` to the passed + in `tensor`. + This operation is very similar to `tf.scatter_nd`, except that the updates are + scattered onto an existing tensor (as opposed to a zero-tensor). If the memory + for the existing tensor cannot be re-used, a copy is made and updated. + + If `indices` contains duplicates, then we pick the last update for the index. + + If an out of bound index is found on CPU, an error is returned. + + **WARNING**: There are some GPU specific semantics for this operation. + - If an out of bound index is found, the index is ignored. + - The order in which updates are applied is nondeterministic, so the output + will be nondeterministic if `indices` contains duplicates. + + `indices` is an integer tensor containing indices into a new tensor of shape + `shape`. + + * `indices` must have at least 2 axes: `(num_updates, index_depth)`. + * The last axis of `indices` is how deep to index into `tensor` so this index + depth must be less than the rank of `tensor`: `indices.shape[-1] <= tensor.ndim` + + if `indices.shape[-1] = tensor.rank` this Op indexes and updates scalar elements. + if `indices.shape[-1] < tensor.rank` it indexes and updates slices of the input + `tensor`. + + Each `update` has a rank of `tensor.rank - indices.shape[-1]`. + The overall shape of `updates` is: + + ``` + indices.shape[:-1] + tensor.shape[indices.shape[-1]:] + ``` + + For usage examples see the python [tf.tensor_scatter_nd_update]( + https://www.tensorflow.org/api_docs/python/tf/tensor_scatter_nd_update) function + + Args: + tensor: A `Tensor`. Tensor to copy/update. + indices: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`, `uint16`. + Index tensor. + updates: A `Tensor`. Must have the same type as `tensor`. + Updates to scatter into output. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorScatterUpdate", name, tensor, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_scatter_update_eager_fallback( + tensor, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorScatterUpdate", tensor=tensor, indices=indices, + updates=updates, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorScatterUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorScatterUpdate = tf_export("raw_ops.TensorScatterUpdate")(_ops.to_raw_op(tensor_scatter_update)) + + +def tensor_scatter_update_eager_fallback(tensor: Annotated[Any, TV_TensorScatterUpdate_T], indices: Annotated[Any, TV_TensorScatterUpdate_Tindices], updates: Annotated[Any, TV_TensorScatterUpdate_T], name, ctx) -> Annotated[Any, TV_TensorScatterUpdate_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], ctx, []) + (tensor, updates) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint16, ]) + _inputs_flat = [tensor, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"TensorScatterUpdate", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorScatterUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorStridedSliceUpdate_T = TypeVar("TV_TensorStridedSliceUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorStridedSliceUpdate_Index = TypeVar("TV_TensorStridedSliceUpdate_Index", _atypes.Int32, _atypes.Int64) + +def tensor_strided_slice_update(input: Annotated[Any, TV_TensorStridedSliceUpdate_T], begin: Annotated[Any, TV_TensorStridedSliceUpdate_Index], end: Annotated[Any, TV_TensorStridedSliceUpdate_Index], strides: Annotated[Any, TV_TensorStridedSliceUpdate_Index], value: Annotated[Any, TV_TensorStridedSliceUpdate_T], begin_mask:int=0, end_mask:int=0, ellipsis_mask:int=0, new_axis_mask:int=0, shrink_axis_mask:int=0, name=None) -> Annotated[Any, TV_TensorStridedSliceUpdate_T]: + r"""Assign `value` to the sliced l-value reference of `input`. + + The values of `value` are assigned to the positions in the tensor `input` that + are selected by the slice parameters. The slice parameters `begin` `end` + `strides` etc. work exactly as in `StridedSlice`. + + NOTE this op currently does not support broadcasting and so `value`'s shape + must be exactly the shape produced by the slice of `input`. + + Args: + input: A `Tensor`. + begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. + end: A `Tensor`. Must have the same type as `begin`. + strides: A `Tensor`. Must have the same type as `begin`. + value: A `Tensor`. Must have the same type as `input`. + begin_mask: An optional `int`. Defaults to `0`. + end_mask: An optional `int`. Defaults to `0`. + ellipsis_mask: An optional `int`. Defaults to `0`. + new_axis_mask: An optional `int`. Defaults to `0`. + shrink_axis_mask: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorStridedSliceUpdate", name, input, begin, end, strides, + value, "begin_mask", begin_mask, "end_mask", end_mask, + "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, + "shrink_axis_mask", shrink_axis_mask) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_strided_slice_update_eager_fallback( + input, begin, end, strides, value, begin_mask=begin_mask, + end_mask=end_mask, ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorStridedSliceUpdate", input=input, begin=begin, end=end, + strides=strides, value=value, + begin_mask=begin_mask, end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Index", + _op._get_attr_type("Index"), "begin_mask", + _op._get_attr_int("begin_mask"), "end_mask", + _op._get_attr_int("end_mask"), "ellipsis_mask", + _op._get_attr_int("ellipsis_mask"), "new_axis_mask", + _op._get_attr_int("new_axis_mask"), "shrink_axis_mask", + _op._get_attr_int("shrink_axis_mask")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorStridedSliceUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorStridedSliceUpdate = tf_export("raw_ops.TensorStridedSliceUpdate")(_ops.to_raw_op(tensor_strided_slice_update)) + + +def tensor_strided_slice_update_eager_fallback(input: Annotated[Any, TV_TensorStridedSliceUpdate_T], begin: Annotated[Any, TV_TensorStridedSliceUpdate_Index], end: Annotated[Any, TV_TensorStridedSliceUpdate_Index], strides: Annotated[Any, TV_TensorStridedSliceUpdate_Index], value: Annotated[Any, TV_TensorStridedSliceUpdate_T], begin_mask: int, end_mask: int, ellipsis_mask: int, new_axis_mask: int, shrink_axis_mask: int, name, ctx) -> Annotated[Any, TV_TensorStridedSliceUpdate_T]: + if begin_mask is None: + begin_mask = 0 + begin_mask = _execute.make_int(begin_mask, "begin_mask") + if end_mask is None: + end_mask = 0 + end_mask = _execute.make_int(end_mask, "end_mask") + if ellipsis_mask is None: + ellipsis_mask = 0 + ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") + if new_axis_mask is None: + new_axis_mask = 0 + new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") + if shrink_axis_mask is None: + shrink_axis_mask = 0 + shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, value], ctx, []) + (input, value) = _inputs_T + _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, end, strides], ctx, [_dtypes.int32, _dtypes.int64, ]) + (begin, end, strides) = _inputs_Index + _inputs_flat = [input, begin, end, strides, value] + _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, + "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", + new_axis_mask, "shrink_axis_mask", shrink_axis_mask) + _result = _execute.execute(b"TensorStridedSliceUpdate", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorStridedSliceUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Tile_T = TypeVar("TV_Tile_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Tile_Tmultiples = TypeVar("TV_Tile_Tmultiples", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('tile', v1=['tile', 'manip.tile']) +@deprecated_endpoints('manip.tile') +def tile(input: Annotated[Any, TV_Tile_T], multiples: Annotated[Any, TV_Tile_Tmultiples], name=None) -> Annotated[Any, TV_Tile_T]: + r"""Constructs a tensor by tiling a given tensor. + + This operation creates a new tensor by replicating `input` `multiples` times. + The output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements, + and the values of `input` are replicated `multiples[i]` times along the 'i'th + dimension. For example, tiling `[a b c d]` by `[2]` produces + `[a b c d a b c d]`. + + >>> a = tf.constant([[1,2,3],[4,5,6]], tf.int32) + >>> b = tf.constant([1,2], tf.int32) + >>> tf.tile(a, b) + + >>> c = tf.constant([2,1], tf.int32) + >>> tf.tile(a, c) + + >>> d = tf.constant([2,2], tf.int32) + >>> tf.tile(a, d) + + + Args: + input: A `Tensor`. 1-D or higher. + multiples: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D. Length must be the same as the number of dimensions in `input` + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Tile", name, input, multiples) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tile( + (input, multiples, name,), None) + if _result is not NotImplemented: + return _result + return tile_eager_fallback( + input, multiples, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tile, (), dict(input=input, multiples=multiples, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tile( + (input, multiples, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Tile", input=input, multiples=multiples, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tile, (), dict(input=input, multiples=multiples, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tmultiples", + _op._get_attr_type("Tmultiples")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Tile", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Tile = tf_export("raw_ops.Tile")(_ops.to_raw_op(tile)) +_dispatcher_for_tile = tile._tf_type_based_dispatcher.Dispatch + + +def tile_eager_fallback(input: Annotated[Any, TV_Tile_T], multiples: Annotated[Any, TV_Tile_Tmultiples], name, ctx) -> Annotated[Any, TV_Tile_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tmultiples, (multiples,) = _execute.args_to_matching_eager([multiples], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, multiples] + _attrs = ("T", _attr_T, "Tmultiples", _attr_Tmultiples) + _result = _execute.execute(b"Tile", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Tile", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TileGrad_T = TypeVar("TV_TileGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tile_grad(input: Annotated[Any, TV_TileGrad_T], multiples: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_TileGrad_T]: + r"""Returns the gradient of `Tile`. + + Since `Tile` takes an input and repeats the input `multiples` times + along each dimension, `TileGrad` takes in `multiples` and aggregates + each repeated tile of `input` into `output`. + + Args: + input: A `Tensor`. + multiples: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TileGrad", name, input, multiples) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tile_grad_eager_fallback( + input, multiples, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TileGrad", input=input, multiples=multiples, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TileGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TileGrad = tf_export("raw_ops.TileGrad")(_ops.to_raw_op(tile_grad)) + + +def tile_grad_eager_fallback(input: Annotated[Any, TV_TileGrad_T], multiples: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_TileGrad_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + multiples = _ops.convert_to_tensor(multiples, _dtypes.int32) + _inputs_flat = [input, multiples] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TileGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TileGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Transpose_T = TypeVar("TV_Transpose_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Transpose_Tperm = TypeVar("TV_Transpose_Tperm", _atypes.Int32, _atypes.Int64) + +def transpose(x: Annotated[Any, TV_Transpose_T], perm: Annotated[Any, TV_Transpose_Tperm], name=None) -> Annotated[Any, TV_Transpose_T]: + r"""Shuffle dimensions of x according to a permutation. + + The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: + `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` + + Args: + x: A `Tensor`. + perm: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Transpose", name, x, perm) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return transpose_eager_fallback( + x, perm, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Transpose", x=x, perm=perm, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tperm", + _op._get_attr_type("Tperm")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Transpose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Transpose = tf_export("raw_ops.Transpose")(_ops.to_raw_op(transpose)) + + +def transpose_eager_fallback(x: Annotated[Any, TV_Transpose_T], perm: Annotated[Any, TV_Transpose_Tperm], name, ctx) -> Annotated[Any, TV_Transpose_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _attr_Tperm, (perm,) = _execute.args_to_matching_eager([perm], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x, perm] + _attrs = ("T", _attr_T, "Tperm", _attr_Tperm) + _result = _execute.execute(b"Transpose", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Transpose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_UniqueOutput = collections.namedtuple( + "Unique", + ["y", "idx"]) + + +TV_Unique_T = TypeVar("TV_Unique_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Unique_out_idx = TypeVar("TV_Unique_out_idx", _atypes.Int32, _atypes.Int64) + +def unique(x: Annotated[Any, TV_Unique_T], out_idx:TV_Unique_out_idx=_dtypes.int32, name=None): + r"""Finds unique elements in a 1-D tensor. + + This operation returns a tensor `y` containing all of the unique elements of `x` + sorted in the same order that they occur in `x`; `x` does not need to be sorted. + This operation also returns a tensor `idx` the same size as `x` that contains + the index of each value of `x` in the unique output `y`. In other words: + + `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` + + Examples: + + ``` + # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] + y, idx = unique(x) + y ==> [1, 2, 4, 7, 8] + idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] + ``` + + ``` + # tensor 'x' is [4, 5, 1, 2, 3, 3, 4, 5] + y, idx = unique(x) + y ==> [4, 5, 1, 2, 3] + idx ==> [0, 1, 2, 3, 4, 4, 0, 1] + ``` + + Args: + x: A `Tensor`. 1-D. + out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, idx). + + y: A `Tensor`. Has the same type as `x`. + idx: A `Tensor` of type `out_idx`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Unique", name, x, "out_idx", out_idx) + _result = _UniqueOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unique_eager_fallback( + x, out_idx=out_idx, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Unique", x=x, out_idx=out_idx, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_idx", + _op._get_attr_type("out_idx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Unique", _inputs_flat, _attrs, _result) + _result = _UniqueOutput._make(_result) + return _result + +Unique = tf_export("raw_ops.Unique")(_ops.to_raw_op(unique)) + + +def unique_eager_fallback(x: Annotated[Any, TV_Unique_T], out_idx: TV_Unique_out_idx, name, ctx): + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _inputs_flat = [x] + _attrs = ("T", _attr_T, "out_idx", out_idx) + _result = _execute.execute(b"Unique", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Unique", _inputs_flat, _attrs, _result) + _result = _UniqueOutput._make(_result) + return _result + +_UniqueV2Output = collections.namedtuple( + "UniqueV2", + ["y", "idx"]) + + +TV_UniqueV2_T = TypeVar("TV_UniqueV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_UniqueV2_Taxis = TypeVar("TV_UniqueV2_Taxis", _atypes.Int32, _atypes.Int64) +TV_UniqueV2_out_idx = TypeVar("TV_UniqueV2_out_idx", _atypes.Int32, _atypes.Int64) + +def unique_v2(x: Annotated[Any, TV_UniqueV2_T], axis: Annotated[Any, TV_UniqueV2_Taxis], out_idx:TV_UniqueV2_out_idx=_dtypes.int32, name=None): + r"""Finds unique elements along an axis of a tensor. + + This operation either returns a tensor `y` containing unique elements + along the `axis` of a tensor. The returned unique elements is sorted + in the same order as they occur along `axis` in `x`. + This operation also returns a tensor `idx` that is the same size as + the number of the elements in `x` along the `axis` dimension. It + contains the index in the unique output `y`. + In other words, for an `1-D` tensor `x` with `axis = None: + + `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` + + For example: + + ``` + # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] + y, idx = unique(x) + y ==> [1, 2, 4, 7, 8] + idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] + ``` + + For an `2-D` tensor `x` with `axis = 0`: + + ``` + # tensor 'x' is [[1, 0, 0], + # [1, 0, 0], + # [2, 0, 0]] + y, idx = unique(x, axis=0) + y ==> [[1, 0, 0], + [2, 0, 0]] + idx ==> [0, 0, 1] + ``` + + For an `2-D` tensor `x` with `axis = 1`: + + ``` + # tensor 'x' is [[1, 0, 0], + # [1, 0, 0], + # [2, 0, 0]] + y, idx = unique(x, axis=1) + y ==> [[1, 0], + [1, 0], + [2, 0]] + idx ==> [0, 1, 1] + ``` + + Args: + x: A `Tensor`. A `Tensor`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `Tensor` of type `int32` (default: None). The axis of the Tensor to + find the unique elements. + out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, idx). + + y: A `Tensor`. Has the same type as `x`. + idx: A `Tensor` of type `out_idx`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniqueV2", name, x, axis, "out_idx", out_idx) + _result = _UniqueV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unique_v2_eager_fallback( + x, axis, out_idx=out_idx, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniqueV2", x=x, axis=axis, out_idx=out_idx, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Taxis", + _op._get_attr_type("Taxis"), "out_idx", + _op._get_attr_type("out_idx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniqueV2", _inputs_flat, _attrs, _result) + _result = _UniqueV2Output._make(_result) + return _result + +UniqueV2 = tf_export("raw_ops.UniqueV2")(_ops.to_raw_op(unique_v2)) + + +def unique_v2_eager_fallback(x: Annotated[Any, TV_UniqueV2_T], axis: Annotated[Any, TV_UniqueV2_Taxis], out_idx: TV_UniqueV2_out_idx, name, ctx): + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [x, axis] + _attrs = ("T", _attr_T, "Taxis", _attr_Taxis, "out_idx", out_idx) + _result = _execute.execute(b"UniqueV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniqueV2", _inputs_flat, _attrs, _result) + _result = _UniqueV2Output._make(_result) + return _result + +_UniqueWithCountsOutput = collections.namedtuple( + "UniqueWithCounts", + ["y", "idx", "count"]) + + +TV_UniqueWithCounts_T = TypeVar("TV_UniqueWithCounts_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_UniqueWithCounts_out_idx = TypeVar("TV_UniqueWithCounts_out_idx", _atypes.Int32, _atypes.Int64) + +def unique_with_counts(x: Annotated[Any, TV_UniqueWithCounts_T], out_idx:TV_UniqueWithCounts_out_idx=_dtypes.int32, name=None): + r"""Finds unique elements in a 1-D tensor. + + This operation returns a tensor `y` containing all of the unique elements of `x` + sorted in the same order that they occur in `x`. This operation also returns a + tensor `idx` the same size as `x` that contains the index of each value of `x` + in the unique output `y`. Finally, it returns a third tensor `count` that + contains the count of each element of `y` in `x`. In other words: + + `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` + + For example: + + ``` + # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] + y, idx, count = unique_with_counts(x) + y ==> [1, 2, 4, 7, 8] + idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] + count ==> [2, 1, 3, 1, 2] + ``` + + Args: + x: A `Tensor`. 1-D. + out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, idx, count). + + y: A `Tensor`. Has the same type as `x`. + idx: A `Tensor` of type `out_idx`. + count: A `Tensor` of type `out_idx`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniqueWithCounts", name, x, "out_idx", out_idx) + _result = _UniqueWithCountsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unique_with_counts_eager_fallback( + x, out_idx=out_idx, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniqueWithCounts", x=x, out_idx=out_idx, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_idx", + _op._get_attr_type("out_idx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniqueWithCounts", _inputs_flat, _attrs, _result) + _result = _UniqueWithCountsOutput._make(_result) + return _result + +UniqueWithCounts = tf_export("raw_ops.UniqueWithCounts")(_ops.to_raw_op(unique_with_counts)) + + +def unique_with_counts_eager_fallback(x: Annotated[Any, TV_UniqueWithCounts_T], out_idx: TV_UniqueWithCounts_out_idx, name, ctx): + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _inputs_flat = [x] + _attrs = ("T", _attr_T, "out_idx", out_idx) + _result = _execute.execute(b"UniqueWithCounts", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniqueWithCounts", _inputs_flat, _attrs, _result) + _result = _UniqueWithCountsOutput._make(_result) + return _result + +_UniqueWithCountsV2Output = collections.namedtuple( + "UniqueWithCountsV2", + ["y", "idx", "count"]) + + +TV_UniqueWithCountsV2_T = TypeVar("TV_UniqueWithCountsV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_UniqueWithCountsV2_Taxis = TypeVar("TV_UniqueWithCountsV2_Taxis", _atypes.Int32, _atypes.Int64) +TV_UniqueWithCountsV2_out_idx = TypeVar("TV_UniqueWithCountsV2_out_idx", _atypes.Int32, _atypes.Int64) + +def unique_with_counts_v2(x: Annotated[Any, TV_UniqueWithCountsV2_T], axis: Annotated[Any, TV_UniqueWithCountsV2_Taxis], out_idx:TV_UniqueWithCountsV2_out_idx=_dtypes.int32, name=None): + r"""Finds unique elements along an axis of a tensor. + + This operation either returns a tensor `y` containing unique elements + along the `axis` of a tensor. The returned unique elements is sorted + in the same order as they occur along `axis` in `x`. + This operation also returns a tensor `idx` and a tensor `count` + that are the same size as the number of the elements in `x` along the + `axis` dimension. The `idx` contains the index in the unique output `y` + and the `count` contains the count in the unique output `y`. + In other words, for an `1-D` tensor `x` with `axis = None: + + `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` + + For example: + + ``` + x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8]) + y, idx, count = tf.raw_ops.UniqueWithCountsV2(x=x, axis = [0]) + y ==> [1, 2, 4, 7, 8] + idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] + count ==> [2, 1, 3, 1, 2] + ``` + + For a `2-D` tensor `x` with `axis = 0`: + + ``` + x = tf.constant([[1, 0, 0], + [1, 0, 0], + [2, 0, 0]]) + y, idx, count = tf.raw_ops.UniqueWithCountsV2(x=x, axis=[0]) + y ==> [[1, 0, 0], + [2, 0, 0]] + idx ==> [0, 0, 1] + count ==> [2, 1] + ``` + + For a `2-D` tensor `x` with `axis = 1`: + + ``` + x = tf.constant([[1, 0, 0], + [1, 0, 0], + [2, 0, 0]]) + y, idx, count = tf.raw_ops.UniqueWithCountsV2(x=x, axis=[1]) + y ==> [[1, 0], + [1, 0], + [2, 0]] + idx ==> [0, 1, 1] + count ==> [1, 2] + ``` + + Args: + x: A `Tensor`. A `Tensor`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `Tensor` of type `int32` (default: None). The axis of the Tensor to + find the unique elements. + out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, idx, count). + + y: A `Tensor`. Has the same type as `x`. + idx: A `Tensor` of type `out_idx`. + count: A `Tensor` of type `out_idx`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniqueWithCountsV2", name, x, axis, "out_idx", out_idx) + _result = _UniqueWithCountsV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unique_with_counts_v2_eager_fallback( + x, axis, out_idx=out_idx, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniqueWithCountsV2", x=x, axis=axis, out_idx=out_idx, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Taxis", + _op._get_attr_type("Taxis"), "out_idx", + _op._get_attr_type("out_idx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniqueWithCountsV2", _inputs_flat, _attrs, _result) + _result = _UniqueWithCountsV2Output._make(_result) + return _result + +UniqueWithCountsV2 = tf_export("raw_ops.UniqueWithCountsV2")(_ops.to_raw_op(unique_with_counts_v2)) + + +def unique_with_counts_v2_eager_fallback(x: Annotated[Any, TV_UniqueWithCountsV2_T], axis: Annotated[Any, TV_UniqueWithCountsV2_Taxis], out_idx: TV_UniqueWithCountsV2_out_idx, name, ctx): + if out_idx is None: + out_idx = _dtypes.int32 + out_idx = _execute.make_type(out_idx, "out_idx") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [x, axis] + _attrs = ("T", _attr_T, "Taxis", _attr_Taxis, "out_idx", out_idx) + _result = _execute.execute(b"UniqueWithCountsV2", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniqueWithCountsV2", _inputs_flat, _attrs, _result) + _result = _UniqueWithCountsV2Output._make(_result) + return _result + + +TV_Unpack_T = TypeVar("TV_Unpack_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def unpack(value: Annotated[Any, TV_Unpack_T], num: int, axis:int=0, name=None): + r"""Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors. + + Unpacks `num` tensors from `value` by chipping it along the `axis` dimension. + For example, given a tensor of shape `(A, B, C, D)`; + + If `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]` + and each tensor in `output` will have shape `(B, C, D)`. (Note that the + dimension unpacked along is gone, unlike `split`). + + If `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]` + and each tensor in `output` will have shape `(A, C, D)`. + Etc. + + This is the opposite of `pack`. + + Args: + value: A `Tensor`. + 1-D or higher, with `axis` dimension size equal to `num`. + num: An `int` that is `>= 0`. + axis: An optional `int`. Defaults to `0`. + Dimension along which to unpack. Negative values wrap around, so the + valid range is `[-R, R)`. + name: A name for the operation (optional). + + Returns: + A list of `num` `Tensor` objects with the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Unpack", name, value, "num", num, "axis", axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unpack_eager_fallback( + value, num=num, axis=axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num = _execute.make_int(num, "num") + if axis is None: + axis = 0 + axis = _execute.make_int(axis, "axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Unpack", value=value, num=num, axis=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num", _op._get_attr_int("num"), "T", _op._get_attr_type("T"), + "axis", _op._get_attr_int("axis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Unpack", _inputs_flat, _attrs, _result) + return _result + +Unpack = tf_export("raw_ops.Unpack")(_ops.to_raw_op(unpack)) + + +def unpack_eager_fallback(value: Annotated[Any, TV_Unpack_T], num: int, axis: int, name, ctx): + num = _execute.make_int(num, "num") + if axis is None: + axis = 0 + axis = _execute.make_int(axis, "axis") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _inputs_flat = [value] + _attrs = ("num", num, "T", _attr_T, "axis", axis) + _result = _execute.execute(b"Unpack", num, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Unpack", _inputs_flat, _attrs, _result) + return _result + + +TV_UnravelIndex_Tidx = TypeVar("TV_UnravelIndex_Tidx", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('unravel_index') +def unravel_index(indices: Annotated[Any, TV_UnravelIndex_Tidx], dims: Annotated[Any, TV_UnravelIndex_Tidx], name=None) -> Annotated[Any, TV_UnravelIndex_Tidx]: + r"""Converts an array of flat indices into a tuple of coordinate arrays. + + + Example: + + ``` + y = tf.unravel_index(indices=[2, 5, 7], dims=[3, 3]) + # 'dims' represent a hypothetical (3, 3) tensor of indices: + # [[0, 1, *2*], + # [3, 4, *5*], + # [6, *7*, 8]] + # For each entry from 'indices', this operation returns + # its coordinates (marked with '*'), such as + # 2 ==> (0, 2) + # 5 ==> (1, 2) + # 7 ==> (2, 1) + y ==> [[0, 1, 2], [2, 2, 1]] + ``` + + @compatibility(numpy) + Equivalent to np.unravel_index + @end_compatibility + + Args: + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + An 0-D or 1-D `int` Tensor whose elements are indices into the + flattened version of an array of dimensions dims. + dims: A `Tensor`. Must have the same type as `indices`. + An 1-D `int` Tensor. The shape of the array to use for unraveling + indices. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `indices`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnravelIndex", name, indices, dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unravel_index( + (indices, dims, name,), None) + if _result is not NotImplemented: + return _result + return unravel_index_eager_fallback( + indices, dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unravel_index, (), dict(indices=indices, dims=dims, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unravel_index( + (indices, dims, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnravelIndex", indices=indices, dims=dims, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unravel_index, (), dict(indices=indices, dims=dims, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnravelIndex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnravelIndex = tf_export("raw_ops.UnravelIndex")(_ops.to_raw_op(unravel_index)) +_dispatcher_for_unravel_index = unravel_index._tf_type_based_dispatcher.Dispatch + + +def unravel_index_eager_fallback(indices: Annotated[Any, TV_UnravelIndex_Tidx], dims: Annotated[Any, TV_UnravelIndex_Tidx], name, ctx) -> Annotated[Any, TV_UnravelIndex_Tidx]: + _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([indices, dims], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + (indices, dims) = _inputs_Tidx + _inputs_flat = [indices, dims] + _attrs = ("Tidx", _attr_Tidx) + _result = _execute.execute(b"UnravelIndex", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnravelIndex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UpperBound_T = TypeVar("TV_UpperBound_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_UpperBound_out_type = TypeVar("TV_UpperBound_out_type", _atypes.Int32, _atypes.Int64) + +def upper_bound(sorted_inputs: Annotated[Any, TV_UpperBound_T], values: Annotated[Any, TV_UpperBound_T], out_type:TV_UpperBound_out_type=_dtypes.int32, name=None) -> Annotated[Any, TV_UpperBound_out_type]: + r"""Applies upper_bound(sorted_search_values, values) along each row. + + Each set of rows with the same index in (sorted_inputs, values) is treated + independently. The resulting row is the equivalent of calling + `np.searchsorted(sorted_inputs, values, side='right')`. + + The result is not a global index to the entire + `Tensor`, but rather just the index in the last dimension. + + A 2-D example: + sorted_sequence = [[0, 3, 9, 9, 10], + [1, 2, 3, 4, 5]] + values = [[2, 4, 9], + [0, 2, 6]] + + result = UpperBound(sorted_sequence, values) + + result == [[1, 2, 4], + [0, 2, 5]] + + Args: + sorted_inputs: A `Tensor`. 2-D Tensor where each row is ordered. + values: A `Tensor`. Must have the same type as `sorted_inputs`. + 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains + the values that will be searched for in `sorted_search_values`. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UpperBound", name, sorted_inputs, values, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return upper_bound_eager_fallback( + sorted_inputs, values, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UpperBound", sorted_inputs=sorted_inputs, values=values, + out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UpperBound", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UpperBound = tf_export("raw_ops.UpperBound")(_ops.to_raw_op(upper_bound)) + + +def upper_bound_eager_fallback(sorted_inputs: Annotated[Any, TV_UpperBound_T], values: Annotated[Any, TV_UpperBound_T], out_type: TV_UpperBound_out_type, name, ctx) -> Annotated[Any, TV_UpperBound_out_type]: + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, _inputs_T = _execute.args_to_matching_eager([sorted_inputs, values], ctx, []) + (sorted_inputs, values) = _inputs_T + _inputs_flat = [sorted_inputs, values] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"UpperBound", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UpperBound", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Where_T = TypeVar("TV_Where_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def where(condition: Annotated[Any, TV_Where_T], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns locations of nonzero / true values in a tensor. + + This operation returns the coordinates of true elements in `condition`. The + coordinates are returned in a 2-D tensor where the first dimension (rows) + represents the number of true elements, and the second dimension (columns) + represents the coordinates of the true elements. Keep in mind, the shape of + the output tensor can vary depending on how many true values there are in + `condition`. Indices are output in row-major order. + + For example: + + ``` + # 'input' tensor is [[True, False] + # [True, False]] + # 'input' has two true values, so output has two coordinates. + # 'input' has rank of 2, so coordinates have two indices. + where(input) ==> [[0, 0], + [1, 0]] + + # `condition` tensor is [[[True, False] + # [True, False]] + # [[False, True] + # [False, True]] + # [[False, False] + # [False, True]]] + # 'input' has 5 true values, so output has 5 coordinates. + # 'input' has rank of 3, so coordinates have three indices. + where(input) ==> [[0, 0, 0], + [0, 1, 0], + [1, 0, 1], + [1, 1, 1], + [2, 1, 1]] + + # `condition` tensor is [[[1.5, 0.0] + # [-0.5, 0.0]] + # [[0.0, 0.25] + # [0.0, 0.75]] + # [[0.0, 0.0] + # [0.0, 0.01]]] + # 'input' has 5 nonzero values, so output has 5 coordinates. + # 'input' has rank of 3, so coordinates have three indices. + where(input) ==> [[0, 0, 0], + [0, 1, 0], + [1, 0, 1], + [1, 1, 1], + [2, 1, 1]] + + # `condition` tensor is [[[1.5 + 0.0j, 0.0 + 0.0j] + # [0.0 + 0.5j, 0.0 + 0.0j]] + # [[0.0 + 0.0j, 0.25 + 1.5j] + # [0.0 + 0.0j, 0.75 + 0.0j]] + # [[0.0 + 0.0j, 0.0 + 0.0j] + # [0.0 + 0.0j, 0.01 + 0.0j]]] + # 'input' has 5 nonzero magnitude values, so output has 5 coordinates. + # 'input' has rank of 3, so coordinates have three indices. + where(input) ==> [[0, 0, 0], + [0, 1, 0], + [1, 0, 1], + [1, 1, 1], + [2, 1, 1]] + ``` + + Args: + condition: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Where", name, condition) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return where_eager_fallback( + condition, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Where", input=condition, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Where", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Where = tf_export("raw_ops.Where")(_ops.to_raw_op(where)) + + +def where_eager_fallback(condition: Annotated[Any, TV_Where_T], name, ctx) -> Annotated[Any, _atypes.Int64]: + _attr_T, (condition,) = _execute.args_to_matching_eager([condition], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.bool, ], _dtypes.bool) + _inputs_flat = [condition] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Where", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Where", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ZerosLike_T = TypeVar("TV_ZerosLike_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def zeros_like(x: Annotated[Any, TV_ZerosLike_T], name=None) -> Annotated[Any, TV_ZerosLike_T]: + r"""Returns a tensor of zeros with the same shape and type as x. + + Args: + x: A `Tensor`. a tensor of type T. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ZerosLike", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return zeros_like_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ZerosLike", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ZerosLike", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ZerosLike = tf_export("raw_ops.ZerosLike")(_ops.to_raw_op(zeros_like)) + + +def zeros_like_eager_fallback(x: Annotated[Any, TV_ZerosLike_T], name, ctx) -> Annotated[Any, TV_ZerosLike_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ZerosLike", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ZerosLike", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_audio_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_audio_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5a29489dc41e616010846d36a9772f7b6f4d73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_audio_ops.py @@ -0,0 +1,472 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def audio_spectrogram(input: Annotated[Any, _atypes.Float32], window_size: int, stride: int, magnitude_squared:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Produces a visualization of audio data over time. + + Spectrograms are a standard way of representing audio information as a series of + slices of frequency information, one slice for each window of time. By joining + these together into a sequence, they form a distinctive fingerprint of the sound + over time. + + This op expects to receive audio data as an input, stored as floats in the range + -1 to 1, together with a window width in samples, and a stride specifying how + far to move the window between slices. From this it generates a three + dimensional output. The first dimension is for the channels in the input, so a + stereo audio input would have two here for example. The second dimension is time, + with successive frequency slices. The third dimension has an amplitude value for + each frequency during that time slice. + + This means the layout when converted and saved as an image is rotated 90 degrees + clockwise from a typical spectrogram. Time is descending down the Y axis, and + the frequency decreases from left to right. + + Each value in the result represents the square root of the sum of the real and + imaginary parts of an FFT on the current window of samples. In this way, the + lowest dimension represents the power of each frequency in the current window, + and adjacent windows are concatenated in the next dimension. + + To get a more intuitive and visual look at what this operation does, you can run + tensorflow/examples/wav_to_spectrogram to read in an audio file and save out the + resulting spectrogram as a PNG image. + + Args: + input: A `Tensor` of type `float32`. Float representation of audio data. + window_size: An `int`. + How wide the input window is in samples. For the highest efficiency + this should be a power of two, but other values are accepted. + stride: An `int`. + How widely apart the center of adjacent sample windows should be. + magnitude_squared: An optional `bool`. Defaults to `False`. + Whether to return the squared magnitude or just the + magnitude. Using squared magnitude can avoid extra calculations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AudioSpectrogram", name, input, "window_size", window_size, + "stride", stride, "magnitude_squared", magnitude_squared) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return audio_spectrogram_eager_fallback( + input, window_size=window_size, stride=stride, + magnitude_squared=magnitude_squared, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + window_size = _execute.make_int(window_size, "window_size") + stride = _execute.make_int(stride, "stride") + if magnitude_squared is None: + magnitude_squared = False + magnitude_squared = _execute.make_bool(magnitude_squared, "magnitude_squared") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AudioSpectrogram", input=input, window_size=window_size, + stride=stride, + magnitude_squared=magnitude_squared, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("window_size", _op._get_attr_int("window_size"), "stride", + _op._get_attr_int("stride"), "magnitude_squared", + _op._get_attr_bool("magnitude_squared")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AudioSpectrogram", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AudioSpectrogram = tf_export("raw_ops.AudioSpectrogram")(_ops.to_raw_op(audio_spectrogram)) + + +def audio_spectrogram_eager_fallback(input: Annotated[Any, _atypes.Float32], window_size: int, stride: int, magnitude_squared: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + window_size = _execute.make_int(window_size, "window_size") + stride = _execute.make_int(stride, "stride") + if magnitude_squared is None: + magnitude_squared = False + magnitude_squared = _execute.make_bool(magnitude_squared, "magnitude_squared") + input = _ops.convert_to_tensor(input, _dtypes.float32) + _inputs_flat = [input] + _attrs = ("window_size", window_size, "stride", stride, "magnitude_squared", + magnitude_squared) + _result = _execute.execute(b"AudioSpectrogram", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AudioSpectrogram", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_DecodeWavOutput = collections.namedtuple( + "DecodeWav", + ["audio", "sample_rate"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('audio.decode_wav') +def decode_wav(contents: Annotated[Any, _atypes.String], desired_channels:int=-1, desired_samples:int=-1, name=None): + r"""Decode a 16-bit PCM WAV file to a float tensor. + + The -32768 to 32767 signed 16-bit values will be scaled to -1.0 to 1.0 in float. + + When desired_channels is set, if the input contains fewer channels than this + then the last channel will be duplicated to give the requested number, else if + the input has more channels than requested then the additional channels will be + ignored. + + If desired_samples is set, then the audio will be cropped or padded with zeroes + to the requested length. + + The first output contains a Tensor with the content of the audio samples. The + lowest dimension will be the number of channels, and the second will be the + number of samples. For example, a ten-sample-long stereo WAV file should give an + output shape of [10, 2]. + + Args: + contents: A `Tensor` of type `string`. + The WAV-encoded audio, usually from a file. + desired_channels: An optional `int`. Defaults to `-1`. + Number of sample channels wanted. + desired_samples: An optional `int`. Defaults to `-1`. + Length of audio requested. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (audio, sample_rate). + + audio: A `Tensor` of type `float32`. + sample_rate: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeWav", name, contents, "desired_channels", + desired_channels, "desired_samples", desired_samples) + _result = _DecodeWavOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_decode_wav( + (contents, desired_channels, desired_samples, name,), None) + if _result is not NotImplemented: + return _result + return decode_wav_eager_fallback( + contents, desired_channels=desired_channels, + desired_samples=desired_samples, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_wav, (), dict(contents=contents, + desired_channels=desired_channels, + desired_samples=desired_samples, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_decode_wav( + (contents, desired_channels, desired_samples, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if desired_channels is None: + desired_channels = -1 + desired_channels = _execute.make_int(desired_channels, "desired_channels") + if desired_samples is None: + desired_samples = -1 + desired_samples = _execute.make_int(desired_samples, "desired_samples") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeWav", contents=contents, desired_channels=desired_channels, + desired_samples=desired_samples, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_wav, (), dict(contents=contents, + desired_channels=desired_channels, + desired_samples=desired_samples, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("desired_channels", _op._get_attr_int("desired_channels"), + "desired_samples", _op._get_attr_int("desired_samples")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeWav", _inputs_flat, _attrs, _result) + _result = _DecodeWavOutput._make(_result) + return _result + +DecodeWav = tf_export("raw_ops.DecodeWav")(_ops.to_raw_op(decode_wav)) +_dispatcher_for_decode_wav = decode_wav._tf_type_based_dispatcher.Dispatch + + +def decode_wav_eager_fallback(contents: Annotated[Any, _atypes.String], desired_channels: int, desired_samples: int, name, ctx): + if desired_channels is None: + desired_channels = -1 + desired_channels = _execute.make_int(desired_channels, "desired_channels") + if desired_samples is None: + desired_samples = -1 + desired_samples = _execute.make_int(desired_samples, "desired_samples") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("desired_channels", desired_channels, "desired_samples", + desired_samples) + _result = _execute.execute(b"DecodeWav", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeWav", _inputs_flat, _attrs, _result) + _result = _DecodeWavOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('audio.encode_wav') +def encode_wav(audio: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.String]: + r"""Encode audio data using the WAV file format. + + This operation will generate a string suitable to be saved out to create a .wav + audio file. It will be encoded in the 16-bit PCM format. It takes in float + values in the range -1.0f to 1.0f, and any outside that value will be clamped to + that range. + + `audio` is a 2-D float Tensor of shape `[length, channels]`. + `sample_rate` is a scalar Tensor holding the rate to use (e.g. 44100). + + Args: + audio: A `Tensor` of type `float32`. 2-D with shape `[length, channels]`. + sample_rate: A `Tensor` of type `int32`. + Scalar containing the sample frequency. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodeWav", name, audio, sample_rate) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_encode_wav( + (audio, sample_rate, name,), None) + if _result is not NotImplemented: + return _result + return encode_wav_eager_fallback( + audio, sample_rate, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_wav, (), dict(audio=audio, sample_rate=sample_rate, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_encode_wav( + (audio, sample_rate, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodeWav", audio=audio, sample_rate=sample_rate, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_wav, (), dict(audio=audio, sample_rate=sample_rate, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodeWav", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodeWav = tf_export("raw_ops.EncodeWav")(_ops.to_raw_op(encode_wav)) +_dispatcher_for_encode_wav = encode_wav._tf_type_based_dispatcher.Dispatch + + +def encode_wav_eager_fallback(audio: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.String]: + audio = _ops.convert_to_tensor(audio, _dtypes.float32) + sample_rate = _ops.convert_to_tensor(sample_rate, _dtypes.int32) + _inputs_flat = [audio, sample_rate] + _attrs = None + _result = _execute.execute(b"EncodeWav", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodeWav", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def mfcc(spectrogram: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Int32], upper_frequency_limit:float=4000, lower_frequency_limit:float=20, filterbank_channel_count:int=40, dct_coefficient_count:int=13, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Transforms a spectrogram into a form that's useful for speech recognition. + + Mel Frequency Cepstral Coefficients are a way of representing audio data that's + been effective as an input feature for machine learning. They are created by + taking the spectrum of a spectrogram (a 'cepstrum'), and discarding some of the + higher frequencies that are less significant to the human ear. They have a long + history in the speech recognition world, and https://en.wikipedia.org/wiki/Mel-frequency_cepstrum + is a good resource to learn more. + + Args: + spectrogram: A `Tensor` of type `float32`. + Typically produced by the Spectrogram op, with magnitude_squared + set to true. + sample_rate: A `Tensor` of type `int32`. + How many samples per second the source audio used. + upper_frequency_limit: An optional `float`. Defaults to `4000`. + The highest frequency to use when calculating the + ceptstrum. + lower_frequency_limit: An optional `float`. Defaults to `20`. + The lowest frequency to use when calculating the + ceptstrum. + filterbank_channel_count: An optional `int`. Defaults to `40`. + Resolution of the Mel bank used internally. + dct_coefficient_count: An optional `int`. Defaults to `13`. + How many output channels to produce per time slice. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Mfcc", name, spectrogram, sample_rate, "upper_frequency_limit", + upper_frequency_limit, "lower_frequency_limit", lower_frequency_limit, + "filterbank_channel_count", filterbank_channel_count, + "dct_coefficient_count", dct_coefficient_count) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mfcc_eager_fallback( + spectrogram, sample_rate, + upper_frequency_limit=upper_frequency_limit, + lower_frequency_limit=lower_frequency_limit, + filterbank_channel_count=filterbank_channel_count, + dct_coefficient_count=dct_coefficient_count, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if upper_frequency_limit is None: + upper_frequency_limit = 4000 + upper_frequency_limit = _execute.make_float(upper_frequency_limit, "upper_frequency_limit") + if lower_frequency_limit is None: + lower_frequency_limit = 20 + lower_frequency_limit = _execute.make_float(lower_frequency_limit, "lower_frequency_limit") + if filterbank_channel_count is None: + filterbank_channel_count = 40 + filterbank_channel_count = _execute.make_int(filterbank_channel_count, "filterbank_channel_count") + if dct_coefficient_count is None: + dct_coefficient_count = 13 + dct_coefficient_count = _execute.make_int(dct_coefficient_count, "dct_coefficient_count") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Mfcc", spectrogram=spectrogram, sample_rate=sample_rate, + upper_frequency_limit=upper_frequency_limit, + lower_frequency_limit=lower_frequency_limit, + filterbank_channel_count=filterbank_channel_count, + dct_coefficient_count=dct_coefficient_count, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("upper_frequency_limit", _op.get_attr("upper_frequency_limit"), + "lower_frequency_limit", _op.get_attr("lower_frequency_limit"), + "filterbank_channel_count", + _op._get_attr_int("filterbank_channel_count"), + "dct_coefficient_count", + _op._get_attr_int("dct_coefficient_count")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Mfcc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Mfcc = tf_export("raw_ops.Mfcc")(_ops.to_raw_op(mfcc)) + + +def mfcc_eager_fallback(spectrogram: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Int32], upper_frequency_limit: float, lower_frequency_limit: float, filterbank_channel_count: int, dct_coefficient_count: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + if upper_frequency_limit is None: + upper_frequency_limit = 4000 + upper_frequency_limit = _execute.make_float(upper_frequency_limit, "upper_frequency_limit") + if lower_frequency_limit is None: + lower_frequency_limit = 20 + lower_frequency_limit = _execute.make_float(lower_frequency_limit, "lower_frequency_limit") + if filterbank_channel_count is None: + filterbank_channel_count = 40 + filterbank_channel_count = _execute.make_int(filterbank_channel_count, "filterbank_channel_count") + if dct_coefficient_count is None: + dct_coefficient_count = 13 + dct_coefficient_count = _execute.make_int(dct_coefficient_count, "dct_coefficient_count") + spectrogram = _ops.convert_to_tensor(spectrogram, _dtypes.float32) + sample_rate = _ops.convert_to_tensor(sample_rate, _dtypes.int32) + _inputs_flat = [spectrogram, sample_rate] + _attrs = ("upper_frequency_limit", upper_frequency_limit, + "lower_frequency_limit", lower_frequency_limit, "filterbank_channel_count", + filterbank_channel_count, "dct_coefficient_count", dct_coefficient_count) + _result = _execute.execute(b"Mfcc", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Mfcc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_batch_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_batch_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..846f568a686781a3bfa1884e356a0de48879f288 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_batch_ops.py @@ -0,0 +1,699 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_BatchOutput = collections.namedtuple( + "Batch", + ["batched_tensors", "batch_index", "id"]) + + +def batch(in_tensors, num_batch_threads: int, max_batch_size: int, batch_timeout_micros: int, grad_timeout_micros: int, max_enqueued_batches:int=10, allowed_batch_sizes=[], container:str="", shared_name:str="", batching_queue:str="", name=None): + r"""Batches all input tensors nondeterministically. + + When many instances of this Op are being run concurrently with the same + container/shared_name in the same device, some will output zero-shaped Tensors + and others will output Tensors of size up to max_batch_size. + + All Tensors in in_tensors are batched together (so, for example, labels and + features should be batched with a single instance of this operation. + + Each invocation of batch emits an `id` scalar which will be used to identify + this particular invocation when doing unbatch or its gradient. + + Each op which emits a non-empty batch will also emit a non-empty batch_index + Tensor, which, is a [K, 3] matrix where each row contains the invocation's id, + start, and length of elements of each set of Tensors present in batched_tensors. + + Batched tensors are concatenated along the first dimension, and all tensors in + in_tensors must have the first dimension of the same size. + + in_tensors: The tensors to be batched. + num_batch_threads: Number of scheduling threads for processing batches of work. + Determines the number of batches processed in parallel. + max_batch_size: Batch sizes will never be bigger than this. + batch_timeout_micros: Maximum number of microseconds to wait before outputting + an incomplete batch. + allowed_batch_sizes: Optional list of allowed batch sizes. If left empty, does + nothing. Otherwise, supplies a list of batch sizes, causing the op to pad + batches up to one of those sizes. The entries must increase monotonically, and + the final entry must equal max_batch_size. + grad_timeout_micros: The timeout to use for the gradient. See Unbatch. + batched_tensors: Either empty tensors or a batch of concatenated Tensors. + batch_index: If out_tensors is non-empty, has information to invert it. + container: Controls the scope of sharing of this batch. + id: always contains a scalar with a unique ID for this invocation of Batch. + shared_name: Concurrently running instances of batch in the same device with the + same container and shared_name will batch their elements together. If left + empty, the op name will be used as the shared name. + T: the types of tensors to be batched. + + Args: + in_tensors: A list of `Tensor` objects. + num_batch_threads: An `int`. + max_batch_size: An `int`. + batch_timeout_micros: An `int`. + grad_timeout_micros: An `int`. + max_enqueued_batches: An optional `int`. Defaults to `10`. + allowed_batch_sizes: An optional list of `ints`. Defaults to `[]`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + batching_queue: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (batched_tensors, batch_index, id). + + batched_tensors: A list of `Tensor` objects. Has the same type as `in_tensors`. + batch_index: A `Tensor` of type `int64`. + id: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Batch", name, in_tensors, "num_batch_threads", + num_batch_threads, "max_batch_size", max_batch_size, + "max_enqueued_batches", max_enqueued_batches, "batch_timeout_micros", + batch_timeout_micros, "allowed_batch_sizes", allowed_batch_sizes, + "grad_timeout_micros", grad_timeout_micros, "container", container, + "shared_name", shared_name, "batching_queue", batching_queue) + _result = _BatchOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_eager_fallback( + in_tensors, num_batch_threads=num_batch_threads, + max_batch_size=max_batch_size, + max_enqueued_batches=max_enqueued_batches, + batch_timeout_micros=batch_timeout_micros, + allowed_batch_sizes=allowed_batch_sizes, + grad_timeout_micros=grad_timeout_micros, container=container, + shared_name=shared_name, batching_queue=batching_queue, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_batch_threads = _execute.make_int(num_batch_threads, "num_batch_threads") + max_batch_size = _execute.make_int(max_batch_size, "max_batch_size") + batch_timeout_micros = _execute.make_int(batch_timeout_micros, "batch_timeout_micros") + grad_timeout_micros = _execute.make_int(grad_timeout_micros, "grad_timeout_micros") + if max_enqueued_batches is None: + max_enqueued_batches = 10 + max_enqueued_batches = _execute.make_int(max_enqueued_batches, "max_enqueued_batches") + if allowed_batch_sizes is None: + allowed_batch_sizes = [] + if not isinstance(allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_batch_sizes' argument to " + "'batch' Op, not %r." % allowed_batch_sizes) + allowed_batch_sizes = [_execute.make_int(_i, "allowed_batch_sizes") for _i in allowed_batch_sizes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if batching_queue is None: + batching_queue = "" + batching_queue = _execute.make_str(batching_queue, "batching_queue") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Batch", in_tensors=in_tensors, num_batch_threads=num_batch_threads, + max_batch_size=max_batch_size, + batch_timeout_micros=batch_timeout_micros, + grad_timeout_micros=grad_timeout_micros, + max_enqueued_batches=max_enqueued_batches, + allowed_batch_sizes=allowed_batch_sizes, container=container, + shared_name=shared_name, batching_queue=batching_queue, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_batch_threads", _op._get_attr_int("num_batch_threads"), + "max_batch_size", _op._get_attr_int("max_batch_size"), + "max_enqueued_batches", + _op._get_attr_int("max_enqueued_batches"), + "batch_timeout_micros", + _op._get_attr_int("batch_timeout_micros"), + "allowed_batch_sizes", _op.get_attr("allowed_batch_sizes"), + "grad_timeout_micros", _op._get_attr_int("grad_timeout_micros"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "batching_queue", + _op.get_attr("batching_queue"), "T", _op.get_attr("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Batch", _inputs_flat, _attrs, _result) + _result = [_result[:len(in_tensors)]] + _result[len(in_tensors):] + _result = _BatchOutput._make(_result) + return _result + +Batch = tf_export("raw_ops.Batch")(_ops.to_raw_op(batch)) + + +def batch_eager_fallback(in_tensors, num_batch_threads: int, max_batch_size: int, batch_timeout_micros: int, grad_timeout_micros: int, max_enqueued_batches: int, allowed_batch_sizes, container: str, shared_name: str, batching_queue: str, name, ctx): + num_batch_threads = _execute.make_int(num_batch_threads, "num_batch_threads") + max_batch_size = _execute.make_int(max_batch_size, "max_batch_size") + batch_timeout_micros = _execute.make_int(batch_timeout_micros, "batch_timeout_micros") + grad_timeout_micros = _execute.make_int(grad_timeout_micros, "grad_timeout_micros") + if max_enqueued_batches is None: + max_enqueued_batches = 10 + max_enqueued_batches = _execute.make_int(max_enqueued_batches, "max_enqueued_batches") + if allowed_batch_sizes is None: + allowed_batch_sizes = [] + if not isinstance(allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_batch_sizes' argument to " + "'batch' Op, not %r." % allowed_batch_sizes) + allowed_batch_sizes = [_execute.make_int(_i, "allowed_batch_sizes") for _i in allowed_batch_sizes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if batching_queue is None: + batching_queue = "" + batching_queue = _execute.make_str(batching_queue, "batching_queue") + _attr_T, in_tensors = _execute.convert_to_mixed_eager_tensors(in_tensors, ctx) + _inputs_flat = list(in_tensors) + _attrs = ("num_batch_threads", num_batch_threads, "max_batch_size", + max_batch_size, "max_enqueued_batches", max_enqueued_batches, + "batch_timeout_micros", batch_timeout_micros, "allowed_batch_sizes", + allowed_batch_sizes, "grad_timeout_micros", grad_timeout_micros, + "container", container, "shared_name", shared_name, "batching_queue", + batching_queue, "T", _attr_T) + _result = _execute.execute(b"Batch", len(in_tensors) + 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Batch", _inputs_flat, _attrs, _result) + _result = [_result[:len(in_tensors)]] + _result[len(in_tensors):] + _result = _BatchOutput._make(_result) + return _result + + +def batch_function(in_tensors, captured_tensors, f, num_batch_threads: int, max_batch_size: int, batch_timeout_micros: int, Tout, max_enqueued_batches:int=10, allowed_batch_sizes=[], container:str="", shared_name:str="", batching_queue:str="", low_priority_max_batch_size:int=0, low_priority_batch_timeout_micros:int=0, low_priority_allowed_batch_sizes=[], low_priority_max_enqueued_batches:int=0, enable_large_batch_splitting:bool=False, name=None): + r"""Batches all the inputs tensors to the computation done by the function. + + So, for example, in the following code + + ```python + + # This input will be captured. + y = tf.placeholder_with_default(1.0, shape=[]) + + @tf.Defun(tf.float32) + def computation(a): + return tf.matmul(a, a) + y + + b = gen_batch_ops.batch_function( + f=computation + in_tensors=[a], + captured_tensors=computation.captured_inputs, + Tout=[o.type for o in computation.definition.signature.output_arg], + num_batch_threads=1, + max_batch_size=10, + batch_timeout_micros=100000, # 100ms + allowed_batch_sizes=[3, 10], + batching_queue="") + ``` + + If more than one session.run call is simultaneously trying to compute `b` + the values of `a` will be gathered, non-deterministically concatenated + along the first axis, and only one thread will run the computation. + + Assumes that all arguments of the function are Tensors which will be batched + along their first dimension. + + Arguments that are captured, are not batched. The session.run call which does + the concatenation, will use the values of the captured tensors available to it. + Therefore, typical uses of captured tensors should involve values which remain + unchanged across session.run calls. Inference is a good example of this. + + SparseTensor is not supported. The return value of the decorated function + must be a Tensor or a list/tuple of Tensors. + + Args: + in_tensors: A list of `Tensor` objects. The tensors to be batched. + captured_tensors: A list of `Tensor` objects. + The tensors which are captured in the function, and don't need + to be batched. + f: A function decorated with @Defun. + num_batch_threads: An `int`. + Number of scheduling threads for processing batches of work. + Determines the number of batches processed in parallel. + max_batch_size: An `int`. Batch sizes will never be bigger than this. + batch_timeout_micros: An `int`. + Maximum number of microseconds to wait before outputting + an incomplete batch. + Tout: A list of `tf.DTypes` that has length `>= 1`. + the types of the output tensors. + max_enqueued_batches: An optional `int`. Defaults to `10`. + Maximum number of batches enqueued. Default: 10. + allowed_batch_sizes: An optional list of `ints`. Defaults to `[]`. + Optional list of allowed batch sizes. If left empty, does + nothing. Otherwise, supplies a list of batch sizes, causing the op to pad + batches up to one of those sizes. The entries must increase monotonically. + If enable_large_batch_splitting is false (i.e., large-input-split is not + enabled) the final entry must equal max_batch_size. + container: An optional `string`. Defaults to `""`. + Controls the scope of sharing of this batch. + shared_name: An optional `string`. Defaults to `""`. + Concurrently running instances of batch in the same device with the + same container and shared_name will batch their elements together. If left + empty, the op name will be used as the shared name. + batching_queue: An optional `string`. Defaults to `""`. + low_priority_max_batch_size: An optional `int`. Defaults to `0`. + low_priority_batch_timeout_micros: An optional `int`. Defaults to `0`. + low_priority_allowed_batch_sizes: An optional list of `ints`. Defaults to `[]`. + low_priority_max_enqueued_batches: An optional `int`. Defaults to `0`. + enable_large_batch_splitting: An optional `bool`. Defaults to `False`. + input with a large size (i.e., larger than the largest value of + `allowed_batch_sizes`) will be splitted into multiple batches with batch size. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchFunction", name, in_tensors, captured_tensors, "f", f, + "num_batch_threads", num_batch_threads, "max_batch_size", + max_batch_size, "batch_timeout_micros", batch_timeout_micros, + "max_enqueued_batches", max_enqueued_batches, "allowed_batch_sizes", + allowed_batch_sizes, "container", container, "shared_name", + shared_name, "batching_queue", batching_queue, + "low_priority_max_batch_size", low_priority_max_batch_size, + "low_priority_batch_timeout_micros", + low_priority_batch_timeout_micros, "low_priority_allowed_batch_sizes", + low_priority_allowed_batch_sizes, "low_priority_max_enqueued_batches", + low_priority_max_enqueued_batches, "Tout", Tout, + "enable_large_batch_splitting", enable_large_batch_splitting) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_function_eager_fallback( + in_tensors, captured_tensors, f=f, + num_batch_threads=num_batch_threads, max_batch_size=max_batch_size, + batch_timeout_micros=batch_timeout_micros, + max_enqueued_batches=max_enqueued_batches, + allowed_batch_sizes=allowed_batch_sizes, container=container, + shared_name=shared_name, batching_queue=batching_queue, + low_priority_max_batch_size=low_priority_max_batch_size, + low_priority_batch_timeout_micros=low_priority_batch_timeout_micros, + low_priority_allowed_batch_sizes=low_priority_allowed_batch_sizes, + low_priority_max_enqueued_batches=low_priority_max_enqueued_batches, + Tout=Tout, + enable_large_batch_splitting=enable_large_batch_splitting, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_batch_threads = _execute.make_int(num_batch_threads, "num_batch_threads") + max_batch_size = _execute.make_int(max_batch_size, "max_batch_size") + batch_timeout_micros = _execute.make_int(batch_timeout_micros, "batch_timeout_micros") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'batch_function' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if max_enqueued_batches is None: + max_enqueued_batches = 10 + max_enqueued_batches = _execute.make_int(max_enqueued_batches, "max_enqueued_batches") + if allowed_batch_sizes is None: + allowed_batch_sizes = [] + if not isinstance(allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_batch_sizes' argument to " + "'batch_function' Op, not %r." % allowed_batch_sizes) + allowed_batch_sizes = [_execute.make_int(_i, "allowed_batch_sizes") for _i in allowed_batch_sizes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if batching_queue is None: + batching_queue = "" + batching_queue = _execute.make_str(batching_queue, "batching_queue") + if low_priority_max_batch_size is None: + low_priority_max_batch_size = 0 + low_priority_max_batch_size = _execute.make_int(low_priority_max_batch_size, "low_priority_max_batch_size") + if low_priority_batch_timeout_micros is None: + low_priority_batch_timeout_micros = 0 + low_priority_batch_timeout_micros = _execute.make_int(low_priority_batch_timeout_micros, "low_priority_batch_timeout_micros") + if low_priority_allowed_batch_sizes is None: + low_priority_allowed_batch_sizes = [] + if not isinstance(low_priority_allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'low_priority_allowed_batch_sizes' argument to " + "'batch_function' Op, not %r." % low_priority_allowed_batch_sizes) + low_priority_allowed_batch_sizes = [_execute.make_int(_i, "low_priority_allowed_batch_sizes") for _i in low_priority_allowed_batch_sizes] + if low_priority_max_enqueued_batches is None: + low_priority_max_enqueued_batches = 0 + low_priority_max_enqueued_batches = _execute.make_int(low_priority_max_enqueued_batches, "low_priority_max_enqueued_batches") + if enable_large_batch_splitting is None: + enable_large_batch_splitting = False + enable_large_batch_splitting = _execute.make_bool(enable_large_batch_splitting, "enable_large_batch_splitting") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchFunction", in_tensors=in_tensors, + captured_tensors=captured_tensors, f=f, + num_batch_threads=num_batch_threads, + max_batch_size=max_batch_size, + batch_timeout_micros=batch_timeout_micros, Tout=Tout, + max_enqueued_batches=max_enqueued_batches, + allowed_batch_sizes=allowed_batch_sizes, + container=container, shared_name=shared_name, + batching_queue=batching_queue, + low_priority_max_batch_size=low_priority_max_batch_size, + low_priority_batch_timeout_micros=low_priority_batch_timeout_micros, + low_priority_allowed_batch_sizes=low_priority_allowed_batch_sizes, + low_priority_max_enqueued_batches=low_priority_max_enqueued_batches, + enable_large_batch_splitting=enable_large_batch_splitting, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "num_batch_threads", + _op._get_attr_int("num_batch_threads"), "max_batch_size", + _op._get_attr_int("max_batch_size"), "batch_timeout_micros", + _op._get_attr_int("batch_timeout_micros"), + "max_enqueued_batches", + _op._get_attr_int("max_enqueued_batches"), + "allowed_batch_sizes", _op.get_attr("allowed_batch_sizes"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "batching_queue", + _op.get_attr("batching_queue"), "low_priority_max_batch_size", + _op._get_attr_int("low_priority_max_batch_size"), + "low_priority_batch_timeout_micros", + _op._get_attr_int("low_priority_batch_timeout_micros"), + "low_priority_allowed_batch_sizes", + _op.get_attr("low_priority_allowed_batch_sizes"), + "low_priority_max_enqueued_batches", + _op._get_attr_int("low_priority_max_enqueued_batches"), "Tin", + _op.get_attr("Tin"), "Tcaptured", _op.get_attr("Tcaptured"), + "Tout", _op.get_attr("Tout"), "enable_large_batch_splitting", + _op._get_attr_bool("enable_large_batch_splitting")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchFunction", _inputs_flat, _attrs, _result) + return _result + +BatchFunction = tf_export("raw_ops.BatchFunction")(_ops.to_raw_op(batch_function)) + + +def batch_function_eager_fallback(in_tensors, captured_tensors, f, num_batch_threads: int, max_batch_size: int, batch_timeout_micros: int, Tout, max_enqueued_batches: int, allowed_batch_sizes, container: str, shared_name: str, batching_queue: str, low_priority_max_batch_size: int, low_priority_batch_timeout_micros: int, low_priority_allowed_batch_sizes, low_priority_max_enqueued_batches: int, enable_large_batch_splitting: bool, name, ctx): + num_batch_threads = _execute.make_int(num_batch_threads, "num_batch_threads") + max_batch_size = _execute.make_int(max_batch_size, "max_batch_size") + batch_timeout_micros = _execute.make_int(batch_timeout_micros, "batch_timeout_micros") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'batch_function' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if max_enqueued_batches is None: + max_enqueued_batches = 10 + max_enqueued_batches = _execute.make_int(max_enqueued_batches, "max_enqueued_batches") + if allowed_batch_sizes is None: + allowed_batch_sizes = [] + if not isinstance(allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_batch_sizes' argument to " + "'batch_function' Op, not %r." % allowed_batch_sizes) + allowed_batch_sizes = [_execute.make_int(_i, "allowed_batch_sizes") for _i in allowed_batch_sizes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if batching_queue is None: + batching_queue = "" + batching_queue = _execute.make_str(batching_queue, "batching_queue") + if low_priority_max_batch_size is None: + low_priority_max_batch_size = 0 + low_priority_max_batch_size = _execute.make_int(low_priority_max_batch_size, "low_priority_max_batch_size") + if low_priority_batch_timeout_micros is None: + low_priority_batch_timeout_micros = 0 + low_priority_batch_timeout_micros = _execute.make_int(low_priority_batch_timeout_micros, "low_priority_batch_timeout_micros") + if low_priority_allowed_batch_sizes is None: + low_priority_allowed_batch_sizes = [] + if not isinstance(low_priority_allowed_batch_sizes, (list, tuple)): + raise TypeError( + "Expected list for 'low_priority_allowed_batch_sizes' argument to " + "'batch_function' Op, not %r." % low_priority_allowed_batch_sizes) + low_priority_allowed_batch_sizes = [_execute.make_int(_i, "low_priority_allowed_batch_sizes") for _i in low_priority_allowed_batch_sizes] + if low_priority_max_enqueued_batches is None: + low_priority_max_enqueued_batches = 0 + low_priority_max_enqueued_batches = _execute.make_int(low_priority_max_enqueued_batches, "low_priority_max_enqueued_batches") + if enable_large_batch_splitting is None: + enable_large_batch_splitting = False + enable_large_batch_splitting = _execute.make_bool(enable_large_batch_splitting, "enable_large_batch_splitting") + _attr_Tin, in_tensors = _execute.convert_to_mixed_eager_tensors(in_tensors, ctx) + _attr_Tcaptured, captured_tensors = _execute.convert_to_mixed_eager_tensors(captured_tensors, ctx) + _inputs_flat = list(in_tensors) + list(captured_tensors) + _attrs = ("f", f, "num_batch_threads", num_batch_threads, "max_batch_size", + max_batch_size, "batch_timeout_micros", batch_timeout_micros, + "max_enqueued_batches", max_enqueued_batches, "allowed_batch_sizes", + allowed_batch_sizes, "container", container, "shared_name", shared_name, + "batching_queue", batching_queue, "low_priority_max_batch_size", + low_priority_max_batch_size, "low_priority_batch_timeout_micros", + low_priority_batch_timeout_micros, "low_priority_allowed_batch_sizes", + low_priority_allowed_batch_sizes, "low_priority_max_enqueued_batches", + low_priority_max_enqueued_batches, "Tin", _attr_Tin, "Tcaptured", + _attr_Tcaptured, "Tout", Tout, "enable_large_batch_splitting", + enable_large_batch_splitting) + _result = _execute.execute(b"BatchFunction", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchFunction", _inputs_flat, _attrs, _result) + return _result + + +TV_Unbatch_T = TypeVar("TV_Unbatch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def unbatch(batched_tensor: Annotated[Any, TV_Unbatch_T], batch_index: Annotated[Any, _atypes.Int64], id: Annotated[Any, _atypes.Int64], timeout_micros: int, container:str="", shared_name:str="", name=None) -> Annotated[Any, TV_Unbatch_T]: + r"""Reverses the operation of Batch for a single output Tensor. + + An instance of Unbatch either receives an empty batched_tensor, in which case it + asynchronously waits until the values become available from a concurrently + running instance of Unbatch with the same container and shared_name, or receives + a non-empty batched_tensor in which case it finalizes all other concurrently + running instances and outputs its own element from the batch. + + batched_tensor: The possibly transformed output of Batch. The size of the first + dimension should remain unchanged by the transformations for the operation to + work. + batch_index: The matching batch_index obtained from Batch. + id: The id scalar emitted by Batch. + unbatched_tensor: The Tensor corresponding to this execution. + timeout_micros: Maximum amount of time (in microseconds) to wait to receive the + batched input tensor associated with a given invocation of the op. + container: Container to control resource sharing. + shared_name: Instances of Unbatch with the same container and shared_name are + assumed to possibly belong to the same batch. If left empty, the op name will + be used as the shared name. + + Args: + batched_tensor: A `Tensor`. + batch_index: A `Tensor` of type `int64`. + id: A `Tensor` of type `int64`. + timeout_micros: An `int`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `batched_tensor`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Unbatch", name, batched_tensor, batch_index, id, + "timeout_micros", timeout_micros, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unbatch_eager_fallback( + batched_tensor, batch_index, id, timeout_micros=timeout_micros, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + timeout_micros = _execute.make_int(timeout_micros, "timeout_micros") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Unbatch", batched_tensor=batched_tensor, batch_index=batch_index, + id=id, timeout_micros=timeout_micros, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("timeout_micros", _op._get_attr_int("timeout_micros"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Unbatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Unbatch = tf_export("raw_ops.Unbatch")(_ops.to_raw_op(unbatch)) + + +def unbatch_eager_fallback(batched_tensor: Annotated[Any, TV_Unbatch_T], batch_index: Annotated[Any, _atypes.Int64], id: Annotated[Any, _atypes.Int64], timeout_micros: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, TV_Unbatch_T]: + timeout_micros = _execute.make_int(timeout_micros, "timeout_micros") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_T, (batched_tensor,) = _execute.args_to_matching_eager([batched_tensor], ctx, []) + batch_index = _ops.convert_to_tensor(batch_index, _dtypes.int64) + id = _ops.convert_to_tensor(id, _dtypes.int64) + _inputs_flat = [batched_tensor, batch_index, id] + _attrs = ("timeout_micros", timeout_micros, "container", container, + "shared_name", shared_name, "T", _attr_T) + _result = _execute.execute(b"Unbatch", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Unbatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnbatchGrad_T = TypeVar("TV_UnbatchGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def unbatch_grad(original_input: Annotated[Any, TV_UnbatchGrad_T], batch_index: Annotated[Any, _atypes.Int64], grad: Annotated[Any, TV_UnbatchGrad_T], id: Annotated[Any, _atypes.Int64], container:str="", shared_name:str="", name=None) -> Annotated[Any, TV_UnbatchGrad_T]: + r"""Gradient of Unbatch. + + Acts like Batch but using the given batch_index index of batching things as they + become available. This ensures that the gradients are propagated back in the + same session which did the forward pass. + + original_input: The input to the Unbatch operation this is the gradient of. + batch_index: The batch_index given to the Unbatch operation this is the gradient + of. + grad: The downstream gradient. + id: The id scalar emitted by Batch. + batched_grad: The return value, either an empty tensor or the batched gradient. + container: Container to control resource sharing. + shared_name: Instances of UnbatchGrad with the same container and shared_name + are assumed to possibly belong to the same batch. If left empty, the op name + will be used as the shared name. + + Args: + original_input: A `Tensor`. + batch_index: A `Tensor` of type `int64`. + grad: A `Tensor`. Must have the same type as `original_input`. + id: A `Tensor` of type `int64`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `original_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnbatchGrad", name, original_input, batch_index, grad, id, + "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unbatch_grad_eager_fallback( + original_input, batch_index, grad, id, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnbatchGrad", original_input=original_input, batch_index=batch_index, + grad=grad, id=id, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnbatchGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnbatchGrad = tf_export("raw_ops.UnbatchGrad")(_ops.to_raw_op(unbatch_grad)) + + +def unbatch_grad_eager_fallback(original_input: Annotated[Any, TV_UnbatchGrad_T], batch_index: Annotated[Any, _atypes.Int64], grad: Annotated[Any, TV_UnbatchGrad_T], id: Annotated[Any, _atypes.Int64], container: str, shared_name: str, name, ctx) -> Annotated[Any, TV_UnbatchGrad_T]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_T, _inputs_T = _execute.args_to_matching_eager([original_input, grad], ctx, []) + (original_input, grad) = _inputs_T + batch_index = _ops.convert_to_tensor(batch_index, _dtypes.int64) + id = _ops.convert_to_tensor(id, _dtypes.int64) + _inputs_flat = [original_input, batch_index, grad, id] + _attrs = ("container", container, "shared_name", shared_name, "T", _attr_T) + _result = _execute.execute(b"UnbatchGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnbatchGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_bitwise_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_bitwise_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7d68681f43d638850d1fc7c4a5a6e4e3d8fb796e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_bitwise_ops.py @@ -0,0 +1,765 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_BitwiseAnd_T = TypeVar("TV_BitwiseAnd_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.bitwise_and') +def bitwise_and(x: Annotated[Any, TV_BitwiseAnd_T], y: Annotated[Any, TV_BitwiseAnd_T], name=None) -> Annotated[Any, TV_BitwiseAnd_T]: + r"""Elementwise computes the bitwise AND of `x` and `y`. + + The result will have those bits set, that are set in both `x` and `y`. The + computation is performed on the underlying representations of `x` and `y`. + + For example: + + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + dtype_list = [tf.int8, tf.int16, tf.int32, tf.int64, + tf.uint8, tf.uint16, tf.uint32, tf.uint64] + + for dtype in dtype_list: + lhs = tf.constant([0, 5, 3, 14], dtype=dtype) + rhs = tf.constant([5, 0, 7, 11], dtype=dtype) + exp = tf.constant([0, 0, 3, 10], dtype=tf.float32) + + res = bitwise_ops.bitwise_and(lhs, rhs) + tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BitwiseAnd", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_bitwise_and( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return bitwise_and_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_and, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_bitwise_and( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BitwiseAnd", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_and, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BitwiseAnd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BitwiseAnd = tf_export("raw_ops.BitwiseAnd")(_ops.to_raw_op(bitwise_and)) +_dispatcher_for_bitwise_and = bitwise_and._tf_type_based_dispatcher.Dispatch + + +def bitwise_and_eager_fallback(x: Annotated[Any, TV_BitwiseAnd_T], y: Annotated[Any, TV_BitwiseAnd_T], name, ctx) -> Annotated[Any, TV_BitwiseAnd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BitwiseAnd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BitwiseAnd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BitwiseOr_T = TypeVar("TV_BitwiseOr_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.bitwise_or') +def bitwise_or(x: Annotated[Any, TV_BitwiseOr_T], y: Annotated[Any, TV_BitwiseOr_T], name=None) -> Annotated[Any, TV_BitwiseOr_T]: + r"""Elementwise computes the bitwise OR of `x` and `y`. + + The result will have those bits set, that are set in `x`, `y` or both. The + computation is performed on the underlying representations of `x` and `y`. + + For example: + + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + dtype_list = [tf.int8, tf.int16, tf.int32, tf.int64, + tf.uint8, tf.uint16, tf.uint32, tf.uint64] + + for dtype in dtype_list: + lhs = tf.constant([0, 5, 3, 14], dtype=dtype) + rhs = tf.constant([5, 0, 7, 11], dtype=dtype) + exp = tf.constant([5, 5, 7, 15], dtype=tf.float32) + + res = bitwise_ops.bitwise_or(lhs, rhs) + tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BitwiseOr", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_bitwise_or( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return bitwise_or_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_or, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_bitwise_or( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BitwiseOr", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_or, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BitwiseOr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BitwiseOr = tf_export("raw_ops.BitwiseOr")(_ops.to_raw_op(bitwise_or)) +_dispatcher_for_bitwise_or = bitwise_or._tf_type_based_dispatcher.Dispatch + + +def bitwise_or_eager_fallback(x: Annotated[Any, TV_BitwiseOr_T], y: Annotated[Any, TV_BitwiseOr_T], name, ctx) -> Annotated[Any, TV_BitwiseOr_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BitwiseOr", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BitwiseOr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BitwiseXor_T = TypeVar("TV_BitwiseXor_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.bitwise_xor') +def bitwise_xor(x: Annotated[Any, TV_BitwiseXor_T], y: Annotated[Any, TV_BitwiseXor_T], name=None) -> Annotated[Any, TV_BitwiseXor_T]: + r"""Elementwise computes the bitwise XOR of `x` and `y`. + + The result will have those bits set, that are different in `x` and `y`. The + computation is performed on the underlying representations of `x` and `y`. + + For example: + + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + dtype_list = [tf.int8, tf.int16, tf.int32, tf.int64, + tf.uint8, tf.uint16, tf.uint32, tf.uint64] + + for dtype in dtype_list: + lhs = tf.constant([0, 5, 3, 14], dtype=dtype) + rhs = tf.constant([5, 0, 7, 11], dtype=dtype) + exp = tf.constant([5, 5, 4, 5], dtype=tf.float32) + + res = bitwise_ops.bitwise_xor(lhs, rhs) + tf.assert_equal(tf.cast(res, tf.float32), exp) # TRUE + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BitwiseXor", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_bitwise_xor( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return bitwise_xor_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_xor, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_bitwise_xor( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BitwiseXor", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + bitwise_xor, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BitwiseXor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BitwiseXor = tf_export("raw_ops.BitwiseXor")(_ops.to_raw_op(bitwise_xor)) +_dispatcher_for_bitwise_xor = bitwise_xor._tf_type_based_dispatcher.Dispatch + + +def bitwise_xor_eager_fallback(x: Annotated[Any, TV_BitwiseXor_T], y: Annotated[Any, TV_BitwiseXor_T], name, ctx) -> Annotated[Any, TV_BitwiseXor_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BitwiseXor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BitwiseXor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Invert_T = TypeVar("TV_Invert_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.invert') +def invert(x: Annotated[Any, TV_Invert_T], name=None) -> Annotated[Any, TV_Invert_T]: + r"""Invert (flip) each bit of supported types; for example, type `uint8` value 01010101 becomes 10101010. + + Flip each bit of supported types. For example, type `int8` (decimal 2) binary 00000010 becomes (decimal -3) binary 11111101. + This operation is performed on each element of the tensor argument `x`. + + Example: + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + + # flip 2 (00000010) to -3 (11111101) + tf.assert_equal(-3, bitwise_ops.invert(2)) + + dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, + dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64] + + inputs = [0, 5, 3, 14] + for dtype in dtype_list: + # Because of issues with negative numbers, let's test this indirectly. + # 1. invert(a) and a = 0 + # 2. invert(a) or a = invert(0) + input_tensor = tf.constant([0, 5, 3, 14], dtype=dtype) + not_a_and_a, not_a_or_a, not_0 = [bitwise_ops.bitwise_and( + input_tensor, bitwise_ops.invert(input_tensor)), + bitwise_ops.bitwise_or( + input_tensor, bitwise_ops.invert(input_tensor)), + bitwise_ops.invert( + tf.constant(0, dtype=dtype))] + + expected = tf.constant([0, 0, 0, 0], dtype=tf.float32) + tf.assert_equal(tf.cast(not_a_and_a, tf.float32), expected) + + expected = tf.cast([not_0] * 4, tf.float32) + tf.assert_equal(tf.cast(not_a_or_a, tf.float32), expected) + + # For unsigned dtypes let's also check the result directly. + if dtype.is_unsigned: + inverted = bitwise_ops.invert(input_tensor) + expected = tf.constant([dtype.max - x for x in inputs], dtype=tf.float32) + tf.assert_equal(tf.cast(inverted, tf.float32), tf.cast(expected, tf.float32)) + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Invert", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_invert( + (x, name,), None) + if _result is not NotImplemented: + return _result + return invert_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + invert, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_invert( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Invert", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + invert, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Invert", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Invert = tf_export("raw_ops.Invert")(_ops.to_raw_op(invert)) +_dispatcher_for_invert = invert._tf_type_based_dispatcher.Dispatch + + +def invert_eager_fallback(x: Annotated[Any, TV_Invert_T], name, ctx) -> Annotated[Any, TV_Invert_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Invert", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Invert", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LeftShift_T = TypeVar("TV_LeftShift_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.left_shift') +def left_shift(x: Annotated[Any, TV_LeftShift_T], y: Annotated[Any, TV_LeftShift_T], name=None) -> Annotated[Any, TV_LeftShift_T]: + r"""Elementwise computes the bitwise left-shift of `x` and `y`. + + If `y` is negative, or greater than or equal to the width of `x` in bits the + result is implementation defined. + + Example: + + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + import numpy as np + dtype_list = [tf.int8, tf.int16, tf.int32, tf.int64] + + for dtype in dtype_list: + lhs = tf.constant([-1, -5, -3, -14], dtype=dtype) + rhs = tf.constant([5, 0, 7, 11], dtype=dtype) + + left_shift_result = bitwise_ops.left_shift(lhs, rhs) + + print(left_shift_result) + + # This will print: + # tf.Tensor([ -32 -5 -128 0], shape=(4,), dtype=int8) + # tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int16) + # tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int32) + # tf.Tensor([ -32 -5 -384 -28672], shape=(4,), dtype=int64) + + lhs = np.array([-2, 64, 101, 32], dtype=np.int8) + rhs = np.array([-1, -5, -3, -14], dtype=np.int8) + bitwise_ops.left_shift(lhs, rhs) + # + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LeftShift", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_left_shift( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return left_shift_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + left_shift, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_left_shift( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LeftShift", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + left_shift, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LeftShift", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LeftShift = tf_export("raw_ops.LeftShift")(_ops.to_raw_op(left_shift)) +_dispatcher_for_left_shift = left_shift._tf_type_based_dispatcher.Dispatch + + +def left_shift_eager_fallback(x: Annotated[Any, TV_LeftShift_T], y: Annotated[Any, TV_LeftShift_T], name, ctx) -> Annotated[Any, TV_LeftShift_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"LeftShift", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LeftShift", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PopulationCount_T = TypeVar("TV_PopulationCount_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def population_count(x: Annotated[Any, TV_PopulationCount_T], name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Computes element-wise population count (a.k.a. popcount, bitsum, bitcount). + + For each entry in `x`, calculates the number of `1` (on) bits in the binary + representation of that entry. + + **NOTE**: It is more efficient to first `tf.bitcast` your tensors into + `int32` or `int64` and perform the bitcount on the result, than to feed in + 8- or 16-bit inputs and then aggregate the resulting counts. + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PopulationCount", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return population_count_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PopulationCount", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PopulationCount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PopulationCount = tf_export("raw_ops.PopulationCount")(_ops.to_raw_op(population_count)) + + +def population_count_eager_fallback(x: Annotated[Any, TV_PopulationCount_T], name, ctx) -> Annotated[Any, _atypes.UInt8]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"PopulationCount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PopulationCount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RightShift_T = TypeVar("TV_RightShift_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('bitwise.right_shift') +def right_shift(x: Annotated[Any, TV_RightShift_T], y: Annotated[Any, TV_RightShift_T], name=None) -> Annotated[Any, TV_RightShift_T]: + r"""Elementwise computes the bitwise right-shift of `x` and `y`. + + Performs a logical shift for unsigned integer types, and an arithmetic shift + for signed integer types. + + If `y` is negative, or greater than or equal to than the width of `x` in bits + the result is implementation defined. + + Example: + + ```python + import tensorflow as tf + from tensorflow.python.ops import bitwise_ops + import numpy as np + dtype_list = [tf.int8, tf.int16, tf.int32, tf.int64] + + for dtype in dtype_list: + lhs = tf.constant([-1, -5, -3, -14], dtype=dtype) + rhs = tf.constant([5, 0, 7, 11], dtype=dtype) + + right_shift_result = bitwise_ops.right_shift(lhs, rhs) + + print(right_shift_result) + + # This will print: + # tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int8) + # tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int16) + # tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int32) + # tf.Tensor([-1 -5 -1 -1], shape=(4,), dtype=int64) + + lhs = np.array([-2, 64, 101, 32], dtype=np.int8) + rhs = np.array([-1, -5, -3, -14], dtype=np.int8) + bitwise_ops.right_shift(lhs, rhs) + # + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RightShift", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_right_shift( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return right_shift_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + right_shift, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_right_shift( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RightShift", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + right_shift, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RightShift", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RightShift = tf_export("raw_ops.RightShift")(_ops.to_raw_op(right_shift)) +_dispatcher_for_right_shift = right_shift._tf_type_based_dispatcher.Dispatch + + +def right_shift_eager_fallback(x: Annotated[Any, TV_RightShift_T], y: Annotated[Any, TV_RightShift_T], name, ctx) -> Annotated[Any, TV_RightShift_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RightShift", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RightShift", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_boosted_trees_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_boosted_trees_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..024b9616204af56de5baf22810b2a193583dc4fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_boosted_trees_ops.py @@ -0,0 +1,2649 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def boosted_trees_aggregate_stats(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], feature: Annotated[Any, _atypes.Int32], max_splits: int, num_buckets: int, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Aggregates the summary of accumulated stats for the batch. + + The summary stats contains gradients and hessians accumulated for each node, feature dimension id and bucket. + + Args: + node_ids: A `Tensor` of type `int32`. + int32; Rank 1 Tensor containing node ids for each example, shape [batch_size]. + gradients: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example. + hessians: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example. + feature: A `Tensor` of type `int32`. + int32; Rank 2 feature Tensors (shape=[batch_size, feature_dimension]). + max_splits: An `int` that is `>= 1`. + int; the maximum number of splits possible in the whole tree. + num_buckets: An `int` that is `>= 1`. + int; equals to the maximum possible value of bucketized feature. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesAggregateStats", name, node_ids, gradients, + hessians, feature, "max_splits", max_splits, "num_buckets", + num_buckets) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_aggregate_stats_eager_fallback( + node_ids, gradients, hessians, feature, max_splits=max_splits, + num_buckets=num_buckets, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesAggregateStats", node_ids=node_ids, gradients=gradients, + hessians=hessians, feature=feature, + max_splits=max_splits, + num_buckets=num_buckets, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_splits", _op._get_attr_int("max_splits"), "num_buckets", + _op._get_attr_int("num_buckets")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesAggregateStats", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesAggregateStats = tf_export("raw_ops.BoostedTreesAggregateStats")(_ops.to_raw_op(boosted_trees_aggregate_stats)) + + +def boosted_trees_aggregate_stats_eager_fallback(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], feature: Annotated[Any, _atypes.Int32], max_splits: int, num_buckets: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + node_ids = _ops.convert_to_tensor(node_ids, _dtypes.int32) + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + hessians = _ops.convert_to_tensor(hessians, _dtypes.float32) + feature = _ops.convert_to_tensor(feature, _dtypes.int32) + _inputs_flat = [node_ids, gradients, hessians, feature] + _attrs = ("max_splits", max_splits, "num_buckets", num_buckets) + _result = _execute.execute(b"BoostedTreesAggregateStats", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesAggregateStats", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_bucketize(float_values: Annotated[List[Any], _atypes.Float32], bucket_boundaries: Annotated[List[Any], _atypes.Float32], name=None): + r"""Bucketize each feature based on bucket boundaries. + + An op that returns a list of float tensors, where each tensor represents the + bucketized values for a single feature. + + Args: + float_values: A list of `Tensor` objects with type `float32`. + float; List of Rank 1 Tensor each containing float values for a single feature. + bucket_boundaries: A list with the same length as `float_values` of `Tensor` objects with type `float32`. + float; List of Rank 1 Tensors each containing the bucket boundaries for a single + feature. + name: A name for the operation (optional). + + Returns: + A list with the same length as `float_values` of `Tensor` objects with type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesBucketize", name, float_values, bucket_boundaries) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_bucketize_eager_fallback( + float_values, bucket_boundaries, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(float_values, (list, tuple)): + raise TypeError( + "Expected list for 'float_values' argument to " + "'boosted_trees_bucketize' Op, not %r." % float_values) + _attr_num_features = len(float_values) + if not isinstance(bucket_boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'bucket_boundaries' argument to " + "'boosted_trees_bucketize' Op, not %r." % bucket_boundaries) + if len(bucket_boundaries) != _attr_num_features: + raise ValueError( + "List argument 'bucket_boundaries' to 'boosted_trees_bucketize' Op with length %d " + "must match length %d of argument 'float_values'." % + (len(bucket_boundaries), _attr_num_features)) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesBucketize", float_values=float_values, + bucket_boundaries=bucket_boundaries, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_features", _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesBucketize", _inputs_flat, _attrs, _result) + return _result + +BoostedTreesBucketize = tf_export("raw_ops.BoostedTreesBucketize")(_ops.to_raw_op(boosted_trees_bucketize)) + + +def boosted_trees_bucketize_eager_fallback(float_values: Annotated[List[Any], _atypes.Float32], bucket_boundaries: Annotated[List[Any], _atypes.Float32], name, ctx): + if not isinstance(float_values, (list, tuple)): + raise TypeError( + "Expected list for 'float_values' argument to " + "'boosted_trees_bucketize' Op, not %r." % float_values) + _attr_num_features = len(float_values) + if not isinstance(bucket_boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'bucket_boundaries' argument to " + "'boosted_trees_bucketize' Op, not %r." % bucket_boundaries) + if len(bucket_boundaries) != _attr_num_features: + raise ValueError( + "List argument 'bucket_boundaries' to 'boosted_trees_bucketize' Op with length %d " + "must match length %d of argument 'float_values'." % + (len(bucket_boundaries), _attr_num_features)) + float_values = _ops.convert_n_to_tensor(float_values, _dtypes.float32) + bucket_boundaries = _ops.convert_n_to_tensor(bucket_boundaries, _dtypes.float32) + _inputs_flat = list(float_values) + list(bucket_boundaries) + _attrs = ("num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesBucketize", _attr_num_features, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesBucketize", _inputs_flat, _attrs, _result) + return _result + +_BoostedTreesCalculateBestFeatureSplitOutput = collections.namedtuple( + "BoostedTreesCalculateBestFeatureSplit", + ["node_ids", "gains", "feature_dimensions", "thresholds", "left_node_contribs", "right_node_contribs", "split_with_default_directions"]) + + +def boosted_trees_calculate_best_feature_split(node_id_range: Annotated[Any, _atypes.Int32], stats_summary: Annotated[Any, _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, split_type:str="inequality", name=None): + r"""Calculates gains for each feature and returns the best possible split information for the feature. + + The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. + + It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. + + In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). + + The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. + + Args: + node_id_range: A `Tensor` of type `int32`. + A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). + stats_summary: A `Tensor` of type `float32`. + A Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. + The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. + l1: A `Tensor` of type `float32`. + l1 regularization factor on leaf weights, per instance based. + l2: A `Tensor` of type `float32`. + l2 regularization factor on leaf weights, per instance based. + tree_complexity: A `Tensor` of type `float32`. + adjustment to the gain, per leaf based. + min_node_weight: A `Tensor` of type `float32`. + minimum avg of hessians in a node before required for the node to be considered for splitting. + logits_dimension: An `int` that is `>= 1`. + The dimension of logit, i.e., number of classes. + split_type: An optional `string` from: `"inequality", "equality"`. Defaults to `"inequality"`. + A string indicating if this Op should perform inequality split or equality split. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (node_ids, gains, feature_dimensions, thresholds, left_node_contribs, right_node_contribs, split_with_default_directions). + + node_ids: A `Tensor` of type `int32`. + gains: A `Tensor` of type `float32`. + feature_dimensions: A `Tensor` of type `int32`. + thresholds: A `Tensor` of type `int32`. + left_node_contribs: A `Tensor` of type `float32`. + right_node_contribs: A `Tensor` of type `float32`. + split_with_default_directions: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCalculateBestFeatureSplit", name, node_id_range, + stats_summary, l1, l2, tree_complexity, min_node_weight, + "logits_dimension", logits_dimension, "split_type", split_type) + _result = _BoostedTreesCalculateBestFeatureSplitOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_calculate_best_feature_split_eager_fallback( + node_id_range, stats_summary, l1, l2, tree_complexity, + min_node_weight, logits_dimension=logits_dimension, + split_type=split_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + if split_type is None: + split_type = "inequality" + split_type = _execute.make_str(split_type, "split_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCalculateBestFeatureSplit", node_id_range=node_id_range, + stats_summary=stats_summary, + l1=l1, l2=l2, + tree_complexity=tree_complexity, + min_node_weight=min_node_weight, + logits_dimension=logits_dimension, + split_type=split_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("logits_dimension", _op._get_attr_int("logits_dimension"), + "split_type", _op.get_attr("split_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesCalculateBestFeatureSplit", _inputs_flat, _attrs, _result) + _result = _BoostedTreesCalculateBestFeatureSplitOutput._make(_result) + return _result + +BoostedTreesCalculateBestFeatureSplit = tf_export("raw_ops.BoostedTreesCalculateBestFeatureSplit")(_ops.to_raw_op(boosted_trees_calculate_best_feature_split)) + + +def boosted_trees_calculate_best_feature_split_eager_fallback(node_id_range: Annotated[Any, _atypes.Int32], stats_summary: Annotated[Any, _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, split_type: str, name, ctx): + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + if split_type is None: + split_type = "inequality" + split_type = _execute.make_str(split_type, "split_type") + node_id_range = _ops.convert_to_tensor(node_id_range, _dtypes.int32) + stats_summary = _ops.convert_to_tensor(stats_summary, _dtypes.float32) + l1 = _ops.convert_to_tensor(l1, _dtypes.float32) + l2 = _ops.convert_to_tensor(l2, _dtypes.float32) + tree_complexity = _ops.convert_to_tensor(tree_complexity, _dtypes.float32) + min_node_weight = _ops.convert_to_tensor(min_node_weight, _dtypes.float32) + _inputs_flat = [node_id_range, stats_summary, l1, l2, tree_complexity, min_node_weight] + _attrs = ("logits_dimension", logits_dimension, "split_type", split_type) + _result = _execute.execute(b"BoostedTreesCalculateBestFeatureSplit", 7, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesCalculateBestFeatureSplit", _inputs_flat, _attrs, _result) + _result = _BoostedTreesCalculateBestFeatureSplitOutput._make(_result) + return _result + +_BoostedTreesCalculateBestFeatureSplitV2Output = collections.namedtuple( + "BoostedTreesCalculateBestFeatureSplitV2", + ["node_ids", "gains", "feature_ids", "feature_dimensions", "thresholds", "left_node_contribs", "right_node_contribs", "split_with_default_directions"]) + + +def boosted_trees_calculate_best_feature_split_v2(node_id_range: Annotated[Any, _atypes.Int32], stats_summaries_list: Annotated[List[Any], _atypes.Float32], split_types: Annotated[Any, _atypes.String], candidate_feature_ids: Annotated[Any, _atypes.Int32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, name=None): + r"""Calculates gains for each feature and returns the best possible split information for each node. However, if no split is found, then no split information is returned for that node. + + The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. + + It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. + + In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). + + The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. + + Args: + node_id_range: A `Tensor` of type `int32`. + A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). + stats_summaries_list: A list of at least 1 `Tensor` objects with type `float32`. + A list of Rank 4 tensor (#shape=[max_splits, feature_dims, bucket, stats_dims]) for accumulated stats summary (gradient/hessian) per node, per dimension, per buckets for each feature. + The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. + split_types: A `Tensor` of type `string`. + A Rank 1 tensor indicating if this Op should perform inequality split or equality split per feature. + candidate_feature_ids: A `Tensor` of type `int32`. + Rank 1 tensor with ids for each feature. This is the real id of the feature. + l1: A `Tensor` of type `float32`. + l1 regularization factor on leaf weights, per instance based. + l2: A `Tensor` of type `float32`. + l2 regularization factor on leaf weights, per instance based. + tree_complexity: A `Tensor` of type `float32`. + adjustment to the gain, per leaf based. + min_node_weight: A `Tensor` of type `float32`. + minimum avg of hessians in a node before required for the node to be considered for splitting. + logits_dimension: An `int` that is `>= 1`. + The dimension of logit, i.e., number of classes. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (node_ids, gains, feature_ids, feature_dimensions, thresholds, left_node_contribs, right_node_contribs, split_with_default_directions). + + node_ids: A `Tensor` of type `int32`. + gains: A `Tensor` of type `float32`. + feature_ids: A `Tensor` of type `int32`. + feature_dimensions: A `Tensor` of type `int32`. + thresholds: A `Tensor` of type `int32`. + left_node_contribs: A `Tensor` of type `float32`. + right_node_contribs: A `Tensor` of type `float32`. + split_with_default_directions: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCalculateBestFeatureSplitV2", name, node_id_range, + stats_summaries_list, split_types, candidate_feature_ids, l1, l2, + tree_complexity, min_node_weight, "logits_dimension", + logits_dimension) + _result = _BoostedTreesCalculateBestFeatureSplitV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_calculate_best_feature_split_v2_eager_fallback( + node_id_range, stats_summaries_list, split_types, + candidate_feature_ids, l1, l2, tree_complexity, min_node_weight, + logits_dimension=logits_dimension, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(stats_summaries_list, (list, tuple)): + raise TypeError( + "Expected list for 'stats_summaries_list' argument to " + "'boosted_trees_calculate_best_feature_split_v2' Op, not %r." % stats_summaries_list) + _attr_num_features = len(stats_summaries_list) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCalculateBestFeatureSplitV2", node_id_range=node_id_range, + stats_summaries_list=stats_summaries_list, + split_types=split_types, + candidate_feature_ids=candidate_feature_ids, + l1=l1, l2=l2, + tree_complexity=tree_complexity, + min_node_weight=min_node_weight, + logits_dimension=logits_dimension, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_features", _op._get_attr_int("num_features"), + "logits_dimension", _op._get_attr_int("logits_dimension")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesCalculateBestFeatureSplitV2", _inputs_flat, _attrs, _result) + _result = _BoostedTreesCalculateBestFeatureSplitV2Output._make(_result) + return _result + +BoostedTreesCalculateBestFeatureSplitV2 = tf_export("raw_ops.BoostedTreesCalculateBestFeatureSplitV2")(_ops.to_raw_op(boosted_trees_calculate_best_feature_split_v2)) + + +def boosted_trees_calculate_best_feature_split_v2_eager_fallback(node_id_range: Annotated[Any, _atypes.Int32], stats_summaries_list: Annotated[List[Any], _atypes.Float32], split_types: Annotated[Any, _atypes.String], candidate_feature_ids: Annotated[Any, _atypes.Int32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, name, ctx): + if not isinstance(stats_summaries_list, (list, tuple)): + raise TypeError( + "Expected list for 'stats_summaries_list' argument to " + "'boosted_trees_calculate_best_feature_split_v2' Op, not %r." % stats_summaries_list) + _attr_num_features = len(stats_summaries_list) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + node_id_range = _ops.convert_to_tensor(node_id_range, _dtypes.int32) + stats_summaries_list = _ops.convert_n_to_tensor(stats_summaries_list, _dtypes.float32) + split_types = _ops.convert_to_tensor(split_types, _dtypes.string) + candidate_feature_ids = _ops.convert_to_tensor(candidate_feature_ids, _dtypes.int32) + l1 = _ops.convert_to_tensor(l1, _dtypes.float32) + l2 = _ops.convert_to_tensor(l2, _dtypes.float32) + tree_complexity = _ops.convert_to_tensor(tree_complexity, _dtypes.float32) + min_node_weight = _ops.convert_to_tensor(min_node_weight, _dtypes.float32) + _inputs_flat = [node_id_range] + list(stats_summaries_list) + [split_types, candidate_feature_ids, l1, l2, tree_complexity, min_node_weight] + _attrs = ("num_features", _attr_num_features, "logits_dimension", + logits_dimension) + _result = _execute.execute(b"BoostedTreesCalculateBestFeatureSplitV2", 8, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesCalculateBestFeatureSplitV2", _inputs_flat, _attrs, _result) + _result = _BoostedTreesCalculateBestFeatureSplitV2Output._make(_result) + return _result + +_BoostedTreesCalculateBestGainsPerFeatureOutput = collections.namedtuple( + "BoostedTreesCalculateBestGainsPerFeature", + ["node_ids_list", "gains_list", "thresholds_list", "left_node_contribs_list", "right_node_contribs_list"]) + + +def boosted_trees_calculate_best_gains_per_feature(node_id_range: Annotated[Any, _atypes.Int32], stats_summary_list: Annotated[List[Any], _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], max_splits: int, name=None): + r"""Calculates gains for each feature and returns the best possible split information for the feature. + + The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. + + It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. + + In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). + + The length of output lists are all of the same length, `num_features`. + The output shapes are compatible in a way that the first dimension of all tensors of all lists are the same and equal to the number of possible split nodes for each feature. + + Args: + node_id_range: A `Tensor` of type `int32`. + A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). + stats_summary_list: A list of at least 1 `Tensor` objects with type `float32`. + A list of Rank 3 tensor (#shape=[max_splits, bucket, 2]) for accumulated stats summary (gradient/hessian) per node per buckets for each feature. The first dimension of the tensor is the maximum number of splits, and thus not all elements of it will be used, but only the indexes specified by node_ids will be used. + l1: A `Tensor` of type `float32`. + l1 regularization factor on leaf weights, per instance based. + l2: A `Tensor` of type `float32`. + l2 regularization factor on leaf weights, per instance based. + tree_complexity: A `Tensor` of type `float32`. + adjustment to the gain, per leaf based. + min_node_weight: A `Tensor` of type `float32`. + minimum avg of hessians in a node before required for the node to be considered for splitting. + max_splits: An `int` that is `>= 1`. + the number of nodes that can be split in the whole tree. Used as a dimension of output tensors. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (node_ids_list, gains_list, thresholds_list, left_node_contribs_list, right_node_contribs_list). + + node_ids_list: A list with the same length as `stats_summary_list` of `Tensor` objects with type `int32`. + gains_list: A list with the same length as `stats_summary_list` of `Tensor` objects with type `float32`. + thresholds_list: A list with the same length as `stats_summary_list` of `Tensor` objects with type `int32`. + left_node_contribs_list: A list with the same length as `stats_summary_list` of `Tensor` objects with type `float32`. + right_node_contribs_list: A list with the same length as `stats_summary_list` of `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCalculateBestGainsPerFeature", name, node_id_range, + stats_summary_list, l1, l2, tree_complexity, min_node_weight, + "max_splits", max_splits) + _result = _BoostedTreesCalculateBestGainsPerFeatureOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_calculate_best_gains_per_feature_eager_fallback( + node_id_range, stats_summary_list, l1, l2, tree_complexity, + min_node_weight, max_splits=max_splits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(stats_summary_list, (list, tuple)): + raise TypeError( + "Expected list for 'stats_summary_list' argument to " + "'boosted_trees_calculate_best_gains_per_feature' Op, not %r." % stats_summary_list) + _attr_num_features = len(stats_summary_list) + max_splits = _execute.make_int(max_splits, "max_splits") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCalculateBestGainsPerFeature", node_id_range=node_id_range, + stats_summary_list=stats_summary_list, + l1=l1, l2=l2, + tree_complexity=tree_complexity, + min_node_weight=min_node_weight, + max_splits=max_splits, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_splits", _op._get_attr_int("max_splits"), "num_features", + _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesCalculateBestGainsPerFeature", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_num_features]] + _result[_attr_num_features:] + _result = _result[:1] + [_result[1:1 + _attr_num_features]] + _result[1 + _attr_num_features:] + _result = _result[:2] + [_result[2:2 + _attr_num_features]] + _result[2 + _attr_num_features:] + _result = _result[:3] + [_result[3:3 + _attr_num_features]] + _result[3 + _attr_num_features:] + _result = _result[:4] + [_result[4:]] + _result = _BoostedTreesCalculateBestGainsPerFeatureOutput._make(_result) + return _result + +BoostedTreesCalculateBestGainsPerFeature = tf_export("raw_ops.BoostedTreesCalculateBestGainsPerFeature")(_ops.to_raw_op(boosted_trees_calculate_best_gains_per_feature)) + + +def boosted_trees_calculate_best_gains_per_feature_eager_fallback(node_id_range: Annotated[Any, _atypes.Int32], stats_summary_list: Annotated[List[Any], _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], max_splits: int, name, ctx): + if not isinstance(stats_summary_list, (list, tuple)): + raise TypeError( + "Expected list for 'stats_summary_list' argument to " + "'boosted_trees_calculate_best_gains_per_feature' Op, not %r." % stats_summary_list) + _attr_num_features = len(stats_summary_list) + max_splits = _execute.make_int(max_splits, "max_splits") + node_id_range = _ops.convert_to_tensor(node_id_range, _dtypes.int32) + stats_summary_list = _ops.convert_n_to_tensor(stats_summary_list, _dtypes.float32) + l1 = _ops.convert_to_tensor(l1, _dtypes.float32) + l2 = _ops.convert_to_tensor(l2, _dtypes.float32) + tree_complexity = _ops.convert_to_tensor(tree_complexity, _dtypes.float32) + min_node_weight = _ops.convert_to_tensor(min_node_weight, _dtypes.float32) + _inputs_flat = [node_id_range] + list(stats_summary_list) + [l1, l2, tree_complexity, min_node_weight] + _attrs = ("max_splits", max_splits, "num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesCalculateBestGainsPerFeature", + _attr_num_features + _attr_num_features + + _attr_num_features + _attr_num_features + + _attr_num_features, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesCalculateBestGainsPerFeature", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_num_features]] + _result[_attr_num_features:] + _result = _result[:1] + [_result[1:1 + _attr_num_features]] + _result[1 + _attr_num_features:] + _result = _result[:2] + [_result[2:2 + _attr_num_features]] + _result[2 + _attr_num_features:] + _result = _result[:3] + [_result[3:3 + _attr_num_features]] + _result[3 + _attr_num_features:] + _result = _result[:4] + [_result[4:]] + _result = _BoostedTreesCalculateBestGainsPerFeatureOutput._make(_result) + return _result + + +def boosted_trees_center_bias(tree_ensemble_handle: Annotated[Any, _atypes.Resource], mean_gradients: Annotated[Any, _atypes.Float32], mean_hessians: Annotated[Any, _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble. + mean_gradients: A `Tensor` of type `float32`. + A tensor with shape=[logits_dimension] with mean of gradients for a first node. + mean_hessians: A `Tensor` of type `float32`. + A tensor with shape=[logits_dimension] mean of hessians for a first node. + l1: A `Tensor` of type `float32`. + l1 regularization factor on leaf weights, per instance based. + l2: A `Tensor` of type `float32`. + l2 regularization factor on leaf weights, per instance based. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCenterBias", name, tree_ensemble_handle, + mean_gradients, mean_hessians, l1, l2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_center_bias_eager_fallback( + tree_ensemble_handle, mean_gradients, mean_hessians, l1, l2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCenterBias", tree_ensemble_handle=tree_ensemble_handle, + mean_gradients=mean_gradients, + mean_hessians=mean_hessians, l1=l1, l2=l2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesCenterBias", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesCenterBias = tf_export("raw_ops.BoostedTreesCenterBias")(_ops.to_raw_op(boosted_trees_center_bias)) + + +def boosted_trees_center_bias_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], mean_gradients: Annotated[Any, _atypes.Float32], mean_hessians: Annotated[Any, _atypes.Float32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Bool]: + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + mean_gradients = _ops.convert_to_tensor(mean_gradients, _dtypes.float32) + mean_hessians = _ops.convert_to_tensor(mean_hessians, _dtypes.float32) + l1 = _ops.convert_to_tensor(l1, _dtypes.float32) + l2 = _ops.convert_to_tensor(l2, _dtypes.float32) + _inputs_flat = [tree_ensemble_handle, mean_gradients, mean_hessians, l1, l2] + _attrs = None + _result = _execute.execute(b"BoostedTreesCenterBias", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesCenterBias", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_create_ensemble(tree_ensemble_handle: Annotated[Any, _atypes.Resource], stamp_token: Annotated[Any, _atypes.Int64], tree_ensemble_serialized: Annotated[Any, _atypes.String], name=None): + r"""Creates a tree ensemble model and returns a handle to it. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble resource to be created. + stamp_token: A `Tensor` of type `int64`. + Token to use as the initial value of the resource stamp. + tree_ensemble_serialized: A `Tensor` of type `string`. + Serialized proto of the tree ensemble. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCreateEnsemble", name, tree_ensemble_handle, + stamp_token, tree_ensemble_serialized) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_create_ensemble_eager_fallback( + tree_ensemble_handle, stamp_token, tree_ensemble_serialized, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCreateEnsemble", tree_ensemble_handle=tree_ensemble_handle, + stamp_token=stamp_token, + tree_ensemble_serialized=tree_ensemble_serialized, + name=name) + return _op +BoostedTreesCreateEnsemble = tf_export("raw_ops.BoostedTreesCreateEnsemble")(_ops.to_raw_op(boosted_trees_create_ensemble)) + + +def boosted_trees_create_ensemble_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], stamp_token: Annotated[Any, _atypes.Int64], tree_ensemble_serialized: Annotated[Any, _atypes.String], name, ctx): + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + stamp_token = _ops.convert_to_tensor(stamp_token, _dtypes.int64) + tree_ensemble_serialized = _ops.convert_to_tensor(tree_ensemble_serialized, _dtypes.string) + _inputs_flat = [tree_ensemble_handle, stamp_token, tree_ensemble_serialized] + _attrs = None + _result = _execute.execute(b"BoostedTreesCreateEnsemble", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_create_quantile_stream_resource(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], epsilon: Annotated[Any, _atypes.Float32], num_streams: Annotated[Any, _atypes.Int64], max_elements:int=1099511627776, name=None): + r"""Create the Resource for Quantile Streams. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource; Handle to quantile stream resource. + epsilon: A `Tensor` of type `float32`. + float; The required approximation error of the stream resource. + num_streams: A `Tensor` of type `int64`. + int; The number of streams managed by the resource that shares the same epsilon. + max_elements: An optional `int`. Defaults to `1099511627776`. + int; The maximum number of data points that can be fed to the stream. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesCreateQuantileStreamResource", name, + quantile_stream_resource_handle, epsilon, num_streams, "max_elements", + max_elements) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_create_quantile_stream_resource_eager_fallback( + quantile_stream_resource_handle, epsilon, num_streams, + max_elements=max_elements, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if max_elements is None: + max_elements = 1099511627776 + max_elements = _execute.make_int(max_elements, "max_elements") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesCreateQuantileStreamResource", quantile_stream_resource_handle=quantile_stream_resource_handle, + epsilon=epsilon, + num_streams=num_streams, + max_elements=max_elements, + name=name) + return _op +BoostedTreesCreateQuantileStreamResource = tf_export("raw_ops.BoostedTreesCreateQuantileStreamResource")(_ops.to_raw_op(boosted_trees_create_quantile_stream_resource)) + + +def boosted_trees_create_quantile_stream_resource_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], epsilon: Annotated[Any, _atypes.Float32], num_streams: Annotated[Any, _atypes.Int64], max_elements: int, name, ctx): + if max_elements is None: + max_elements = 1099511627776 + max_elements = _execute.make_int(max_elements, "max_elements") + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + epsilon = _ops.convert_to_tensor(epsilon, _dtypes.float32) + num_streams = _ops.convert_to_tensor(num_streams, _dtypes.int64) + _inputs_flat = [quantile_stream_resource_handle, epsilon, num_streams] + _attrs = ("max_elements", max_elements) + _result = _execute.execute(b"BoostedTreesCreateQuantileStreamResource", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_deserialize_ensemble(tree_ensemble_handle: Annotated[Any, _atypes.Resource], stamp_token: Annotated[Any, _atypes.Int64], tree_ensemble_serialized: Annotated[Any, _atypes.String], name=None): + r"""Deserializes a serialized tree ensemble config and replaces current tree + + ensemble. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble. + stamp_token: A `Tensor` of type `int64`. + Token to use as the new value of the resource stamp. + tree_ensemble_serialized: A `Tensor` of type `string`. + Serialized proto of the ensemble. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesDeserializeEnsemble", name, tree_ensemble_handle, + stamp_token, tree_ensemble_serialized) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_deserialize_ensemble_eager_fallback( + tree_ensemble_handle, stamp_token, tree_ensemble_serialized, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesDeserializeEnsemble", tree_ensemble_handle=tree_ensemble_handle, + stamp_token=stamp_token, + tree_ensemble_serialized=tree_ensemble_serialized, + name=name) + return _op +BoostedTreesDeserializeEnsemble = tf_export("raw_ops.BoostedTreesDeserializeEnsemble")(_ops.to_raw_op(boosted_trees_deserialize_ensemble)) + + +def boosted_trees_deserialize_ensemble_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], stamp_token: Annotated[Any, _atypes.Int64], tree_ensemble_serialized: Annotated[Any, _atypes.String], name, ctx): + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + stamp_token = _ops.convert_to_tensor(stamp_token, _dtypes.int64) + tree_ensemble_serialized = _ops.convert_to_tensor(tree_ensemble_serialized, _dtypes.string) + _inputs_flat = [tree_ensemble_handle, stamp_token, tree_ensemble_serialized] + _attrs = None + _result = _execute.execute(b"BoostedTreesDeserializeEnsemble", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_ensemble_resource_handle_op(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a handle to a BoostedTreesEnsembleResource + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesEnsembleResourceHandleOp", name, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_ensemble_resource_handle_op_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesEnsembleResourceHandleOp", container=container, + shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesEnsembleResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesEnsembleResourceHandleOp = tf_export("raw_ops.BoostedTreesEnsembleResourceHandleOp")(_ops.to_raw_op(boosted_trees_ensemble_resource_handle_op)) + + +def boosted_trees_ensemble_resource_handle_op_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"BoostedTreesEnsembleResourceHandleOp", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesEnsembleResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_example_debug_outputs(tree_ensemble_handle: Annotated[Any, _atypes.Resource], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name=None) -> Annotated[Any, _atypes.String]: + r"""Debugging/model interpretability outputs for each example. + + It traverses all the trees and computes debug metrics for individual examples, + such as getting split feature ids and logits after each split along the decision + path used to compute directional feature contributions. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + bucketized_features: A list of at least 1 `Tensor` objects with type `int32`. + A list of rank 1 Tensors containing bucket id for each + feature. + logits_dimension: An `int`. + scalar, dimension of the logits, to be used for constructing the protos in + examples_debug_outputs_serialized. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesExampleDebugOutputs", name, tree_ensemble_handle, + bucketized_features, "logits_dimension", logits_dimension) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_example_debug_outputs_eager_fallback( + tree_ensemble_handle, bucketized_features, + logits_dimension=logits_dimension, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_example_debug_outputs' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesExampleDebugOutputs", tree_ensemble_handle=tree_ensemble_handle, + bucketized_features=bucketized_features, + logits_dimension=logits_dimension, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bucketized_features", + _op._get_attr_int("num_bucketized_features"), + "logits_dimension", _op._get_attr_int("logits_dimension")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesExampleDebugOutputs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesExampleDebugOutputs = tf_export("raw_ops.BoostedTreesExampleDebugOutputs")(_ops.to_raw_op(boosted_trees_example_debug_outputs)) + + +def boosted_trees_example_debug_outputs_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name, ctx) -> Annotated[Any, _atypes.String]: + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_example_debug_outputs' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + bucketized_features = _ops.convert_n_to_tensor(bucketized_features, _dtypes.int32) + _inputs_flat = [tree_ensemble_handle] + list(bucketized_features) + _attrs = ("num_bucketized_features", _attr_num_bucketized_features, + "logits_dimension", logits_dimension) + _result = _execute.execute(b"BoostedTreesExampleDebugOutputs", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesExampleDebugOutputs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_flush_quantile_summaries(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_features: int, name=None): + r"""Flush the quantile summaries from each quantile stream resource. + + An op that outputs a list of quantile summaries of a quantile stream resource. + Each summary Tensor is rank 2, containing summaries (value, weight, min_rank, + max_rank) for a single feature. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource handle referring to a QuantileStreamResource. + num_features: An `int` that is `>= 0`. + name: A name for the operation (optional). + + Returns: + A list of `num_features` `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesFlushQuantileSummaries", name, + quantile_stream_resource_handle, "num_features", num_features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_flush_quantile_summaries_eager_fallback( + quantile_stream_resource_handle, num_features=num_features, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_features = _execute.make_int(num_features, "num_features") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesFlushQuantileSummaries", quantile_stream_resource_handle=quantile_stream_resource_handle, + num_features=num_features, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("num_features", _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesFlushQuantileSummaries", _inputs_flat, _attrs, _result) + return _result + +BoostedTreesFlushQuantileSummaries = tf_export("raw_ops.BoostedTreesFlushQuantileSummaries")(_ops.to_raw_op(boosted_trees_flush_quantile_summaries)) + + +def boosted_trees_flush_quantile_summaries_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_features: int, name, ctx): + num_features = _execute.make_int(num_features, "num_features") + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + _inputs_flat = [quantile_stream_resource_handle] + _attrs = ("num_features", num_features) + _result = _execute.execute(b"BoostedTreesFlushQuantileSummaries", + num_features, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesFlushQuantileSummaries", _inputs_flat, _attrs, _result) + return _result + +_BoostedTreesGetEnsembleStatesOutput = collections.namedtuple( + "BoostedTreesGetEnsembleStates", + ["stamp_token", "num_trees", "num_finalized_trees", "num_attempted_layers", "last_layer_nodes_range"]) + + +def boosted_trees_get_ensemble_states(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name=None): + r"""Retrieves the tree ensemble resource stamp token, number of trees and growing statistics. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (stamp_token, num_trees, num_finalized_trees, num_attempted_layers, last_layer_nodes_range). + + stamp_token: A `Tensor` of type `int64`. + num_trees: A `Tensor` of type `int32`. + num_finalized_trees: A `Tensor` of type `int32`. + num_attempted_layers: A `Tensor` of type `int32`. + last_layer_nodes_range: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesGetEnsembleStates", name, tree_ensemble_handle) + _result = _BoostedTreesGetEnsembleStatesOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_get_ensemble_states_eager_fallback( + tree_ensemble_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesGetEnsembleStates", tree_ensemble_handle=tree_ensemble_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesGetEnsembleStates", _inputs_flat, _attrs, _result) + _result = _BoostedTreesGetEnsembleStatesOutput._make(_result) + return _result + +BoostedTreesGetEnsembleStates = tf_export("raw_ops.BoostedTreesGetEnsembleStates")(_ops.to_raw_op(boosted_trees_get_ensemble_states)) + + +def boosted_trees_get_ensemble_states_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name, ctx): + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + _inputs_flat = [tree_ensemble_handle] + _attrs = None + _result = _execute.execute(b"BoostedTreesGetEnsembleStates", 5, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesGetEnsembleStates", _inputs_flat, _attrs, _result) + _result = _BoostedTreesGetEnsembleStatesOutput._make(_result) + return _result + + +def boosted_trees_make_quantile_summaries(float_values: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], epsilon: Annotated[Any, _atypes.Float32], name=None): + r"""Makes the summary of quantiles for the batch. + + An op that takes a list of tensors (one tensor per feature) and outputs the + quantile summaries for each tensor. + + Args: + float_values: A list of `Tensor` objects with type `float32`. + float; List of Rank 1 Tensors each containing values for a single feature. + example_weights: A `Tensor` of type `float32`. + float; Rank 1 Tensor with weights per instance. + epsilon: A `Tensor` of type `float32`. + float; The required maximum approximation error. + name: A name for the operation (optional). + + Returns: + A list with the same length as `float_values` of `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesMakeQuantileSummaries", name, float_values, + example_weights, epsilon) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_make_quantile_summaries_eager_fallback( + float_values, example_weights, epsilon, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(float_values, (list, tuple)): + raise TypeError( + "Expected list for 'float_values' argument to " + "'boosted_trees_make_quantile_summaries' Op, not %r." % float_values) + _attr_num_features = len(float_values) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesMakeQuantileSummaries", float_values=float_values, + example_weights=example_weights, + epsilon=epsilon, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_features", _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesMakeQuantileSummaries", _inputs_flat, _attrs, _result) + return _result + +BoostedTreesMakeQuantileSummaries = tf_export("raw_ops.BoostedTreesMakeQuantileSummaries")(_ops.to_raw_op(boosted_trees_make_quantile_summaries)) + + +def boosted_trees_make_quantile_summaries_eager_fallback(float_values: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], epsilon: Annotated[Any, _atypes.Float32], name, ctx): + if not isinstance(float_values, (list, tuple)): + raise TypeError( + "Expected list for 'float_values' argument to " + "'boosted_trees_make_quantile_summaries' Op, not %r." % float_values) + _attr_num_features = len(float_values) + float_values = _ops.convert_n_to_tensor(float_values, _dtypes.float32) + example_weights = _ops.convert_to_tensor(example_weights, _dtypes.float32) + epsilon = _ops.convert_to_tensor(epsilon, _dtypes.float32) + _inputs_flat = list(float_values) + [example_weights, epsilon] + _attrs = ("num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesMakeQuantileSummaries", + _attr_num_features, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesMakeQuantileSummaries", _inputs_flat, _attrs, _result) + return _result + + +def boosted_trees_make_stats_summary(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], bucketized_features_list: Annotated[List[Any], _atypes.Int32], max_splits: int, num_buckets: int, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Makes the summary of accumulated stats for the batch. + + The summary stats contains gradients and hessians accumulated into the corresponding node and bucket for each example. + + Args: + node_ids: A `Tensor` of type `int32`. + int32 Rank 1 Tensor containing node ids, which each example falls into for the requested layer. + gradients: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[#examples, 1]) for gradients. + hessians: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[#examples, 1]) for hessians. + bucketized_features_list: A list of at least 1 `Tensor` objects with type `int32`. + int32 list of Rank 1 Tensors, each containing the bucketized feature (for each feature column). + max_splits: An `int` that is `>= 1`. + int; the maximum number of splits possible in the whole tree. + num_buckets: An `int` that is `>= 1`. + int; equals to the maximum possible value of bucketized feature. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesMakeStatsSummary", name, node_ids, gradients, + hessians, bucketized_features_list, "max_splits", max_splits, + "num_buckets", num_buckets) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_make_stats_summary_eager_fallback( + node_ids, gradients, hessians, bucketized_features_list, + max_splits=max_splits, num_buckets=num_buckets, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(bucketized_features_list, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features_list' argument to " + "'boosted_trees_make_stats_summary' Op, not %r." % bucketized_features_list) + _attr_num_features = len(bucketized_features_list) + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesMakeStatsSummary", node_ids=node_ids, + gradients=gradients, + hessians=hessians, + bucketized_features_list=bucketized_features_list, + max_splits=max_splits, + num_buckets=num_buckets, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_splits", _op._get_attr_int("max_splits"), "num_buckets", + _op._get_attr_int("num_buckets"), "num_features", + _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesMakeStatsSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesMakeStatsSummary = tf_export("raw_ops.BoostedTreesMakeStatsSummary")(_ops.to_raw_op(boosted_trees_make_stats_summary)) + + +def boosted_trees_make_stats_summary_eager_fallback(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], bucketized_features_list: Annotated[List[Any], _atypes.Int32], max_splits: int, num_buckets: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + if not isinstance(bucketized_features_list, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features_list' argument to " + "'boosted_trees_make_stats_summary' Op, not %r." % bucketized_features_list) + _attr_num_features = len(bucketized_features_list) + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + node_ids = _ops.convert_to_tensor(node_ids, _dtypes.int32) + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + hessians = _ops.convert_to_tensor(hessians, _dtypes.float32) + bucketized_features_list = _ops.convert_n_to_tensor(bucketized_features_list, _dtypes.int32) + _inputs_flat = [node_ids, gradients, hessians] + list(bucketized_features_list) + _attrs = ("max_splits", max_splits, "num_buckets", num_buckets, + "num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesMakeStatsSummary", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesMakeStatsSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_predict(tree_ensemble_handle: Annotated[Any, _atypes.Resource], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Runs multiple additive regression ensemble predictors on input instances and + + computes the logits. It is designed to be used during prediction. + It traverses all the trees and calculates the final score for each instance. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + bucketized_features: A list of at least 1 `Tensor` objects with type `int32`. + A list of rank 1 Tensors containing bucket id for each + feature. + logits_dimension: An `int`. + scalar, dimension of the logits, to be used for partial logits + shape. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesPredict", name, tree_ensemble_handle, + bucketized_features, "logits_dimension", logits_dimension) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_predict_eager_fallback( + tree_ensemble_handle, bucketized_features, + logits_dimension=logits_dimension, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_predict' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesPredict", tree_ensemble_handle=tree_ensemble_handle, + bucketized_features=bucketized_features, + logits_dimension=logits_dimension, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bucketized_features", + _op._get_attr_int("num_bucketized_features"), + "logits_dimension", _op._get_attr_int("logits_dimension")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesPredict", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesPredict = tf_export("raw_ops.BoostedTreesPredict")(_ops.to_raw_op(boosted_trees_predict)) + + +def boosted_trees_predict_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_predict' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + bucketized_features = _ops.convert_n_to_tensor(bucketized_features, _dtypes.int32) + _inputs_flat = [tree_ensemble_handle] + list(bucketized_features) + _attrs = ("num_bucketized_features", _attr_num_bucketized_features, + "logits_dimension", logits_dimension) + _result = _execute.execute(b"BoostedTreesPredict", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesPredict", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def boosted_trees_quantile_stream_resource_add_summaries(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], summaries: Annotated[List[Any], _atypes.Float32], name=None): + r"""Add the quantile summaries to each quantile stream resource. + + An op that adds a list of quantile summaries to a quantile stream resource. Each + summary Tensor is rank 2, containing summaries (value, weight, min_rank, max_rank) + for a single feature. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource handle referring to a QuantileStreamResource. + summaries: A list of `Tensor` objects with type `float32`. + string; List of Rank 2 Tensor each containing the summaries for a single feature. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesQuantileStreamResourceAddSummaries", name, + quantile_stream_resource_handle, summaries) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_quantile_stream_resource_add_summaries_eager_fallback( + quantile_stream_resource_handle, summaries, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(summaries, (list, tuple)): + raise TypeError( + "Expected list for 'summaries' argument to " + "'boosted_trees_quantile_stream_resource_add_summaries' Op, not %r." % summaries) + _attr_num_features = len(summaries) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesQuantileStreamResourceAddSummaries", quantile_stream_resource_handle=quantile_stream_resource_handle, + summaries=summaries, + name=name) + return _op +BoostedTreesQuantileStreamResourceAddSummaries = tf_export("raw_ops.BoostedTreesQuantileStreamResourceAddSummaries")(_ops.to_raw_op(boosted_trees_quantile_stream_resource_add_summaries)) + + +def boosted_trees_quantile_stream_resource_add_summaries_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], summaries: Annotated[List[Any], _atypes.Float32], name, ctx): + if not isinstance(summaries, (list, tuple)): + raise TypeError( + "Expected list for 'summaries' argument to " + "'boosted_trees_quantile_stream_resource_add_summaries' Op, not %r." % summaries) + _attr_num_features = len(summaries) + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + summaries = _ops.convert_n_to_tensor(summaries, _dtypes.float32) + _inputs_flat = [quantile_stream_resource_handle] + list(summaries) + _attrs = ("num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesQuantileStreamResourceAddSummaries", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_quantile_stream_resource_deserialize(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], bucket_boundaries: Annotated[List[Any], _atypes.Float32], name=None): + r"""Deserialize bucket boundaries and ready flag into current QuantileAccumulator. + + An op that deserializes bucket boundaries and are boundaries ready flag into current QuantileAccumulator. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource handle referring to a QuantileStreamResource. + bucket_boundaries: A list of at least 1 `Tensor` objects with type `float32`. + float; List of Rank 1 Tensors each containing the bucket boundaries for a feature. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesQuantileStreamResourceDeserialize", name, + quantile_stream_resource_handle, bucket_boundaries) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_quantile_stream_resource_deserialize_eager_fallback( + quantile_stream_resource_handle, bucket_boundaries, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(bucket_boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'bucket_boundaries' argument to " + "'boosted_trees_quantile_stream_resource_deserialize' Op, not %r." % bucket_boundaries) + _attr_num_streams = len(bucket_boundaries) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesQuantileStreamResourceDeserialize", quantile_stream_resource_handle=quantile_stream_resource_handle, + bucket_boundaries=bucket_boundaries, + name=name) + return _op +BoostedTreesQuantileStreamResourceDeserialize = tf_export("raw_ops.BoostedTreesQuantileStreamResourceDeserialize")(_ops.to_raw_op(boosted_trees_quantile_stream_resource_deserialize)) + + +def boosted_trees_quantile_stream_resource_deserialize_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], bucket_boundaries: Annotated[List[Any], _atypes.Float32], name, ctx): + if not isinstance(bucket_boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'bucket_boundaries' argument to " + "'boosted_trees_quantile_stream_resource_deserialize' Op, not %r." % bucket_boundaries) + _attr_num_streams = len(bucket_boundaries) + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + bucket_boundaries = _ops.convert_n_to_tensor(bucket_boundaries, _dtypes.float32) + _inputs_flat = [quantile_stream_resource_handle] + list(bucket_boundaries) + _attrs = ("num_streams", _attr_num_streams) + _result = _execute.execute(b"BoostedTreesQuantileStreamResourceDeserialize", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_quantile_stream_resource_flush(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_buckets: Annotated[Any, _atypes.Int64], generate_quantiles:bool=False, name=None): + r"""Flush the summaries for a quantile stream resource. + + An op that flushes the summaries for a quantile stream resource. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource handle referring to a QuantileStreamResource. + num_buckets: A `Tensor` of type `int64`. + int; approximate number of buckets unless using generate_quantiles. + generate_quantiles: An optional `bool`. Defaults to `False`. + bool; If True, the output will be the num_quantiles for each stream where the ith + entry is the ith quantile of the input with an approximation error of epsilon. + Duplicate values may be present. + If False, the output will be the points in the histogram that we got which roughly + translates to 1/epsilon boundaries and without any duplicates. + Default to False. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesQuantileStreamResourceFlush", name, + quantile_stream_resource_handle, num_buckets, "generate_quantiles", + generate_quantiles) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_quantile_stream_resource_flush_eager_fallback( + quantile_stream_resource_handle, num_buckets, + generate_quantiles=generate_quantiles, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if generate_quantiles is None: + generate_quantiles = False + generate_quantiles = _execute.make_bool(generate_quantiles, "generate_quantiles") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesQuantileStreamResourceFlush", quantile_stream_resource_handle=quantile_stream_resource_handle, + num_buckets=num_buckets, + generate_quantiles=generate_quantiles, + name=name) + return _op +BoostedTreesQuantileStreamResourceFlush = tf_export("raw_ops.BoostedTreesQuantileStreamResourceFlush")(_ops.to_raw_op(boosted_trees_quantile_stream_resource_flush)) + + +def boosted_trees_quantile_stream_resource_flush_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_buckets: Annotated[Any, _atypes.Int64], generate_quantiles: bool, name, ctx): + if generate_quantiles is None: + generate_quantiles = False + generate_quantiles = _execute.make_bool(generate_quantiles, "generate_quantiles") + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + num_buckets = _ops.convert_to_tensor(num_buckets, _dtypes.int64) + _inputs_flat = [quantile_stream_resource_handle, num_buckets] + _attrs = ("generate_quantiles", generate_quantiles) + _result = _execute.execute(b"BoostedTreesQuantileStreamResourceFlush", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_quantile_stream_resource_get_bucket_boundaries(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_features: int, name=None): + r"""Generate the bucket boundaries for each feature based on accumulated summaries. + + An op that returns a list of float tensors for a quantile stream resource. Each + tensor is Rank 1 containing bucket boundaries for a single feature. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource handle referring to a QuantileStreamResource. + num_features: An `int` that is `>= 0`. + inferred int; number of features to get bucket boundaries for. + name: A name for the operation (optional). + + Returns: + A list of `num_features` `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesQuantileStreamResourceGetBucketBoundaries", name, + quantile_stream_resource_handle, "num_features", num_features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_quantile_stream_resource_get_bucket_boundaries_eager_fallback( + quantile_stream_resource_handle, num_features=num_features, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_features = _execute.make_int(num_features, "num_features") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesQuantileStreamResourceGetBucketBoundaries", quantile_stream_resource_handle=quantile_stream_resource_handle, + num_features=num_features, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("num_features", _op._get_attr_int("num_features")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesQuantileStreamResourceGetBucketBoundaries", _inputs_flat, _attrs, _result) + return _result + +BoostedTreesQuantileStreamResourceGetBucketBoundaries = tf_export("raw_ops.BoostedTreesQuantileStreamResourceGetBucketBoundaries")(_ops.to_raw_op(boosted_trees_quantile_stream_resource_get_bucket_boundaries)) + + +def boosted_trees_quantile_stream_resource_get_bucket_boundaries_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], num_features: int, name, ctx): + num_features = _execute.make_int(num_features, "num_features") + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + _inputs_flat = [quantile_stream_resource_handle] + _attrs = ("num_features", num_features) + _result = _execute.execute(b"BoostedTreesQuantileStreamResourceGetBucketBoundaries", + num_features, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesQuantileStreamResourceGetBucketBoundaries", _inputs_flat, _attrs, _result) + return _result + + +def boosted_trees_quantile_stream_resource_handle_op(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a handle to a BoostedTreesQuantileStreamResource. + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesQuantileStreamResourceHandleOp", name, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_quantile_stream_resource_handle_op_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesQuantileStreamResourceHandleOp", container=container, + shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesQuantileStreamResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BoostedTreesQuantileStreamResourceHandleOp = tf_export("raw_ops.BoostedTreesQuantileStreamResourceHandleOp")(_ops.to_raw_op(boosted_trees_quantile_stream_resource_handle_op)) + + +def boosted_trees_quantile_stream_resource_handle_op_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"BoostedTreesQuantileStreamResourceHandleOp", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesQuantileStreamResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_BoostedTreesSerializeEnsembleOutput = collections.namedtuple( + "BoostedTreesSerializeEnsemble", + ["stamp_token", "tree_ensemble_serialized"]) + + +def boosted_trees_serialize_ensemble(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name=None): + r"""Serializes the tree ensemble to a proto. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (stamp_token, tree_ensemble_serialized). + + stamp_token: A `Tensor` of type `int64`. + tree_ensemble_serialized: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesSerializeEnsemble", name, tree_ensemble_handle) + _result = _BoostedTreesSerializeEnsembleOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_serialize_ensemble_eager_fallback( + tree_ensemble_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesSerializeEnsemble", tree_ensemble_handle=tree_ensemble_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesSerializeEnsemble", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSerializeEnsembleOutput._make(_result) + return _result + +BoostedTreesSerializeEnsemble = tf_export("raw_ops.BoostedTreesSerializeEnsemble")(_ops.to_raw_op(boosted_trees_serialize_ensemble)) + + +def boosted_trees_serialize_ensemble_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name, ctx): + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + _inputs_flat = [tree_ensemble_handle] + _attrs = None + _result = _execute.execute(b"BoostedTreesSerializeEnsemble", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesSerializeEnsemble", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSerializeEnsembleOutput._make(_result) + return _result + +_BoostedTreesSparseAggregateStatsOutput = collections.namedtuple( + "BoostedTreesSparseAggregateStats", + ["stats_summary_indices", "stats_summary_values", "stats_summary_shape"]) + + +def boosted_trees_sparse_aggregate_stats(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], feature_indices: Annotated[Any, _atypes.Int32], feature_values: Annotated[Any, _atypes.Int32], feature_shape: Annotated[Any, _atypes.Int32], max_splits: int, num_buckets: int, name=None): + r"""Aggregates the summary of accumulated stats for the batch. + + The summary stats contains gradients and hessians accumulated for each node, bucket and dimension id. + + Args: + node_ids: A `Tensor` of type `int32`. + int32; Rank 1 Tensor containing node ids for each example, shape [batch_size]. + gradients: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[batch_size, logits_dimension]) with gradients for each example. + hessians: A `Tensor` of type `float32`. + float32; Rank 2 Tensor (shape=[batch_size, hessian_dimension]) with hessians for each example. + feature_indices: A `Tensor` of type `int32`. + int32; Rank 2 indices of feature sparse Tensors (shape=[number of sparse entries, 2]). + Number of sparse entries across all instances from the batch. The first value is + the index of the instance, the second is dimension of the feature. The second axis + can only have 2 values, i.e., the input dense version of Tensor can only be matrix. + feature_values: A `Tensor` of type `int32`. + int32; Rank 1 values of feature sparse Tensors (shape=[number of sparse entries]). + Number of sparse entries across all instances from the batch. The first value is + the index of the instance, the second is dimension of the feature. + feature_shape: A `Tensor` of type `int32`. + int32; Rank 1 dense shape of feature sparse Tensors (shape=[2]). + The first axis can only have 2 values, [batch_size, feature_dimension]. + max_splits: An `int` that is `>= 1`. + int; the maximum number of splits possible in the whole tree. + num_buckets: An `int` that is `>= 1`. + int; equals to the maximum possible value of bucketized feature + 1. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (stats_summary_indices, stats_summary_values, stats_summary_shape). + + stats_summary_indices: A `Tensor` of type `int32`. + stats_summary_values: A `Tensor` of type `float32`. + stats_summary_shape: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesSparseAggregateStats", name, node_ids, gradients, + hessians, feature_indices, feature_values, feature_shape, + "max_splits", max_splits, "num_buckets", num_buckets) + _result = _BoostedTreesSparseAggregateStatsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_sparse_aggregate_stats_eager_fallback( + node_ids, gradients, hessians, feature_indices, feature_values, + feature_shape, max_splits=max_splits, num_buckets=num_buckets, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesSparseAggregateStats", node_ids=node_ids, + gradients=gradients, + hessians=hessians, + feature_indices=feature_indices, + feature_values=feature_values, + feature_shape=feature_shape, + max_splits=max_splits, + num_buckets=num_buckets, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_splits", _op._get_attr_int("max_splits"), "num_buckets", + _op._get_attr_int("num_buckets")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesSparseAggregateStats", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSparseAggregateStatsOutput._make(_result) + return _result + +BoostedTreesSparseAggregateStats = tf_export("raw_ops.BoostedTreesSparseAggregateStats")(_ops.to_raw_op(boosted_trees_sparse_aggregate_stats)) + + +def boosted_trees_sparse_aggregate_stats_eager_fallback(node_ids: Annotated[Any, _atypes.Int32], gradients: Annotated[Any, _atypes.Float32], hessians: Annotated[Any, _atypes.Float32], feature_indices: Annotated[Any, _atypes.Int32], feature_values: Annotated[Any, _atypes.Int32], feature_shape: Annotated[Any, _atypes.Int32], max_splits: int, num_buckets: int, name, ctx): + max_splits = _execute.make_int(max_splits, "max_splits") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + node_ids = _ops.convert_to_tensor(node_ids, _dtypes.int32) + gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) + hessians = _ops.convert_to_tensor(hessians, _dtypes.float32) + feature_indices = _ops.convert_to_tensor(feature_indices, _dtypes.int32) + feature_values = _ops.convert_to_tensor(feature_values, _dtypes.int32) + feature_shape = _ops.convert_to_tensor(feature_shape, _dtypes.int32) + _inputs_flat = [node_ids, gradients, hessians, feature_indices, feature_values, feature_shape] + _attrs = ("max_splits", max_splits, "num_buckets", num_buckets) + _result = _execute.execute(b"BoostedTreesSparseAggregateStats", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesSparseAggregateStats", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSparseAggregateStatsOutput._make(_result) + return _result + +_BoostedTreesSparseCalculateBestFeatureSplitOutput = collections.namedtuple( + "BoostedTreesSparseCalculateBestFeatureSplit", + ["node_ids", "gains", "feature_dimensions", "thresholds", "left_node_contribs", "right_node_contribs", "split_with_default_directions"]) + + +def boosted_trees_sparse_calculate_best_feature_split(node_id_range: Annotated[Any, _atypes.Int32], stats_summary_indices: Annotated[Any, _atypes.Int32], stats_summary_values: Annotated[Any, _atypes.Float32], stats_summary_shape: Annotated[Any, _atypes.Int32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, split_type:str="inequality", name=None): + r"""Calculates gains for each feature and returns the best possible split information for the feature. + + The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature. + + It is possible that not all nodes can be split on each feature. Hence, the list of possible nodes can differ between the features. Therefore, we return `node_ids_list` for each feature, containing the list of nodes that this feature can be used to split. + + In this manner, the output is the best split per features and per node, so that it needs to be combined later to produce the best split for each node (among all possible features). + + The output shapes are compatible in a way that the first dimension of all tensors are the same and equal to the number of possible split nodes for each feature. + + Args: + node_id_range: A `Tensor` of type `int32`. + A Rank 1 tensor (shape=[2]) to specify the range [first, last) of node ids to process within `stats_summary_list`. The nodes are iterated between the two nodes specified by the tensor, as like `for node_id in range(node_id_range[0], node_id_range[1])` (Note that the last index node_id_range[1] is exclusive). + stats_summary_indices: A `Tensor` of type `int32`. + A Rank 2 int64 tensor of dense shape [N, 4] (N specifies the number of non-zero values) for accumulated stats summary (gradient/hessian) per node per bucket for each feature. The second dimension contains node id, feature dimension, bucket id, and stats dim. + stats dim is the sum of logits dimension and hessian dimension, hessian dimension can either be logits dimension if diagonal hessian is used, or logits dimension^2 if full hessian is used. + stats_summary_values: A `Tensor` of type `float32`. + A Rank 1 float tensor of dense shape [N] (N specifies the number of non-zero values), which supplies the values for each element in summary_indices. + stats_summary_shape: A `Tensor` of type `int32`. + A Rank 1 float tensor of dense shape [4], which specifies the dense shape of the sparse tensor, which is [num tree nodes, feature dimensions, num buckets, stats dim]. + l1: A `Tensor` of type `float32`. + l1 regularization factor on leaf weights, per instance based. + l2: A `Tensor` of type `float32`. + l2 regularization factor on leaf weights, per instance based. + tree_complexity: A `Tensor` of type `float32`. + adjustment to the gain, per leaf based. + min_node_weight: A `Tensor` of type `float32`. + minimum avg of hessians in a node before required for the node to be considered for splitting. + logits_dimension: An `int` that is `>= 1`. + The dimension of logit, i.e., number of classes. + split_type: An optional `string` from: `"inequality"`. Defaults to `"inequality"`. + A string indicating if this Op should perform inequality split or equality split. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (node_ids, gains, feature_dimensions, thresholds, left_node_contribs, right_node_contribs, split_with_default_directions). + + node_ids: A `Tensor` of type `int32`. + gains: A `Tensor` of type `float32`. + feature_dimensions: A `Tensor` of type `int32`. + thresholds: A `Tensor` of type `int32`. + left_node_contribs: A `Tensor` of type `float32`. + right_node_contribs: A `Tensor` of type `float32`. + split_with_default_directions: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesSparseCalculateBestFeatureSplit", name, + node_id_range, stats_summary_indices, stats_summary_values, + stats_summary_shape, l1, l2, tree_complexity, min_node_weight, + "logits_dimension", logits_dimension, "split_type", split_type) + _result = _BoostedTreesSparseCalculateBestFeatureSplitOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_sparse_calculate_best_feature_split_eager_fallback( + node_id_range, stats_summary_indices, stats_summary_values, + stats_summary_shape, l1, l2, tree_complexity, min_node_weight, + logits_dimension=logits_dimension, split_type=split_type, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + if split_type is None: + split_type = "inequality" + split_type = _execute.make_str(split_type, "split_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesSparseCalculateBestFeatureSplit", node_id_range=node_id_range, + stats_summary_indices=stats_summary_indices, + stats_summary_values=stats_summary_values, + stats_summary_shape=stats_summary_shape, + l1=l1, l2=l2, + tree_complexity=tree_complexity, + min_node_weight=min_node_weight, + logits_dimension=logits_dimension, + split_type=split_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("logits_dimension", _op._get_attr_int("logits_dimension"), + "split_type", _op.get_attr("split_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesSparseCalculateBestFeatureSplit", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSparseCalculateBestFeatureSplitOutput._make(_result) + return _result + +BoostedTreesSparseCalculateBestFeatureSplit = tf_export("raw_ops.BoostedTreesSparseCalculateBestFeatureSplit")(_ops.to_raw_op(boosted_trees_sparse_calculate_best_feature_split)) + + +def boosted_trees_sparse_calculate_best_feature_split_eager_fallback(node_id_range: Annotated[Any, _atypes.Int32], stats_summary_indices: Annotated[Any, _atypes.Int32], stats_summary_values: Annotated[Any, _atypes.Float32], stats_summary_shape: Annotated[Any, _atypes.Int32], l1: Annotated[Any, _atypes.Float32], l2: Annotated[Any, _atypes.Float32], tree_complexity: Annotated[Any, _atypes.Float32], min_node_weight: Annotated[Any, _atypes.Float32], logits_dimension: int, split_type: str, name, ctx): + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + if split_type is None: + split_type = "inequality" + split_type = _execute.make_str(split_type, "split_type") + node_id_range = _ops.convert_to_tensor(node_id_range, _dtypes.int32) + stats_summary_indices = _ops.convert_to_tensor(stats_summary_indices, _dtypes.int32) + stats_summary_values = _ops.convert_to_tensor(stats_summary_values, _dtypes.float32) + stats_summary_shape = _ops.convert_to_tensor(stats_summary_shape, _dtypes.int32) + l1 = _ops.convert_to_tensor(l1, _dtypes.float32) + l2 = _ops.convert_to_tensor(l2, _dtypes.float32) + tree_complexity = _ops.convert_to_tensor(tree_complexity, _dtypes.float32) + min_node_weight = _ops.convert_to_tensor(min_node_weight, _dtypes.float32) + _inputs_flat = [node_id_range, stats_summary_indices, stats_summary_values, stats_summary_shape, l1, l2, tree_complexity, min_node_weight] + _attrs = ("logits_dimension", logits_dimension, "split_type", split_type) + _result = _execute.execute(b"BoostedTreesSparseCalculateBestFeatureSplit", + 7, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesSparseCalculateBestFeatureSplit", _inputs_flat, _attrs, _result) + _result = _BoostedTreesSparseCalculateBestFeatureSplitOutput._make(_result) + return _result + +_BoostedTreesTrainingPredictOutput = collections.namedtuple( + "BoostedTreesTrainingPredict", + ["partial_logits", "tree_ids", "node_ids"]) + + +def boosted_trees_training_predict(tree_ensemble_handle: Annotated[Any, _atypes.Resource], cached_tree_ids: Annotated[Any, _atypes.Int32], cached_node_ids: Annotated[Any, _atypes.Int32], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name=None): + r"""Runs multiple additive regression ensemble predictors on input instances and + + computes the update to cached logits. It is designed to be used during training. + It traverses the trees starting from cached tree id and cached node id and + calculates the updates to be pushed to the cache. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + cached_tree_ids: A `Tensor` of type `int32`. + Rank 1 Tensor containing cached tree ids which is the starting + tree of prediction. + cached_node_ids: A `Tensor` of type `int32`. + Rank 1 Tensor containing cached node id which is the starting + node of prediction. + bucketized_features: A list of at least 1 `Tensor` objects with type `int32`. + A list of rank 1 Tensors containing bucket id for each + feature. + logits_dimension: An `int`. + scalar, dimension of the logits, to be used for partial logits + shape. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (partial_logits, tree_ids, node_ids). + + partial_logits: A `Tensor` of type `float32`. + tree_ids: A `Tensor` of type `int32`. + node_ids: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesTrainingPredict", name, tree_ensemble_handle, + cached_tree_ids, cached_node_ids, bucketized_features, + "logits_dimension", logits_dimension) + _result = _BoostedTreesTrainingPredictOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_training_predict_eager_fallback( + tree_ensemble_handle, cached_tree_ids, cached_node_ids, + bucketized_features, logits_dimension=logits_dimension, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_training_predict' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesTrainingPredict", tree_ensemble_handle=tree_ensemble_handle, + cached_tree_ids=cached_tree_ids, + cached_node_ids=cached_node_ids, + bucketized_features=bucketized_features, + logits_dimension=logits_dimension, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_bucketized_features", + _op._get_attr_int("num_bucketized_features"), + "logits_dimension", _op._get_attr_int("logits_dimension")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BoostedTreesTrainingPredict", _inputs_flat, _attrs, _result) + _result = _BoostedTreesTrainingPredictOutput._make(_result) + return _result + +BoostedTreesTrainingPredict = tf_export("raw_ops.BoostedTreesTrainingPredict")(_ops.to_raw_op(boosted_trees_training_predict)) + + +def boosted_trees_training_predict_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], cached_tree_ids: Annotated[Any, _atypes.Int32], cached_node_ids: Annotated[Any, _atypes.Int32], bucketized_features: Annotated[List[Any], _atypes.Int32], logits_dimension: int, name, ctx): + if not isinstance(bucketized_features, (list, tuple)): + raise TypeError( + "Expected list for 'bucketized_features' argument to " + "'boosted_trees_training_predict' Op, not %r." % bucketized_features) + _attr_num_bucketized_features = len(bucketized_features) + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + cached_tree_ids = _ops.convert_to_tensor(cached_tree_ids, _dtypes.int32) + cached_node_ids = _ops.convert_to_tensor(cached_node_ids, _dtypes.int32) + bucketized_features = _ops.convert_n_to_tensor(bucketized_features, _dtypes.int32) + _inputs_flat = [tree_ensemble_handle, cached_tree_ids, cached_node_ids] + list(bucketized_features) + _attrs = ("num_bucketized_features", _attr_num_bucketized_features, + "logits_dimension", logits_dimension) + _result = _execute.execute(b"BoostedTreesTrainingPredict", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BoostedTreesTrainingPredict", _inputs_flat, _attrs, _result) + _result = _BoostedTreesTrainingPredictOutput._make(_result) + return _result + + +def boosted_trees_update_ensemble(tree_ensemble_handle: Annotated[Any, _atypes.Resource], feature_ids: Annotated[Any, _atypes.Int32], node_ids: Annotated[List[Any], _atypes.Int32], gains: Annotated[List[Any], _atypes.Float32], thresholds: Annotated[List[Any], _atypes.Int32], left_node_contribs: Annotated[List[Any], _atypes.Float32], right_node_contribs: Annotated[List[Any], _atypes.Float32], max_depth: Annotated[Any, _atypes.Int32], learning_rate: Annotated[Any, _atypes.Float32], pruning_mode: int, name=None): + r"""Updates the tree ensemble by either adding a layer to the last tree being grown + + or by starting a new tree. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the ensemble variable. + feature_ids: A `Tensor` of type `int32`. + Rank 1 tensor with ids for each feature. This is the real id of + the feature that will be used in the split. + node_ids: A list of `Tensor` objects with type `int32`. + List of rank 1 tensors representing the nodes for which this feature + has a split. + gains: A list with the same length as `node_ids` of `Tensor` objects with type `float32`. + List of rank 1 tensors representing the gains for each of the feature's + split. + thresholds: A list with the same length as `node_ids` of `Tensor` objects with type `int32`. + List of rank 1 tensors representing the thesholds for each of the + feature's split. + left_node_contribs: A list with the same length as `node_ids` of `Tensor` objects with type `float32`. + List of rank 2 tensors with left leaf contribs for each of + the feature's splits. Will be added to the previous node values to constitute + the values of the left nodes. + right_node_contribs: A list with the same length as `node_ids` of `Tensor` objects with type `float32`. + List of rank 2 tensors with right leaf contribs for each + of the feature's splits. Will be added to the previous node values to constitute + the values of the right nodes. + max_depth: A `Tensor` of type `int32`. Max depth of the tree to build. + learning_rate: A `Tensor` of type `float32`. + shrinkage const for each new tree. + pruning_mode: An `int` that is `>= 0`. + 0-No pruning, 1-Pre-pruning, 2-Post-pruning. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesUpdateEnsemble", name, tree_ensemble_handle, + feature_ids, node_ids, gains, thresholds, left_node_contribs, + right_node_contribs, max_depth, learning_rate, "pruning_mode", + pruning_mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_update_ensemble_eager_fallback( + tree_ensemble_handle, feature_ids, node_ids, gains, thresholds, + left_node_contribs, right_node_contribs, max_depth, learning_rate, + pruning_mode=pruning_mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(node_ids, (list, tuple)): + raise TypeError( + "Expected list for 'node_ids' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % node_ids) + _attr_num_features = len(node_ids) + if not isinstance(gains, (list, tuple)): + raise TypeError( + "Expected list for 'gains' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % gains) + if len(gains) != _attr_num_features: + raise ValueError( + "List argument 'gains' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(gains), _attr_num_features)) + if not isinstance(thresholds, (list, tuple)): + raise TypeError( + "Expected list for 'thresholds' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % thresholds) + if len(thresholds) != _attr_num_features: + raise ValueError( + "List argument 'thresholds' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(thresholds), _attr_num_features)) + if not isinstance(left_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'left_node_contribs' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % left_node_contribs) + if len(left_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'left_node_contribs' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(left_node_contribs), _attr_num_features)) + if not isinstance(right_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'right_node_contribs' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % right_node_contribs) + if len(right_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'right_node_contribs' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(right_node_contribs), _attr_num_features)) + pruning_mode = _execute.make_int(pruning_mode, "pruning_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesUpdateEnsemble", tree_ensemble_handle=tree_ensemble_handle, + feature_ids=feature_ids, + node_ids=node_ids, gains=gains, + thresholds=thresholds, + left_node_contribs=left_node_contribs, + right_node_contribs=right_node_contribs, + max_depth=max_depth, + learning_rate=learning_rate, + pruning_mode=pruning_mode, name=name) + return _op +BoostedTreesUpdateEnsemble = tf_export("raw_ops.BoostedTreesUpdateEnsemble")(_ops.to_raw_op(boosted_trees_update_ensemble)) + + +def boosted_trees_update_ensemble_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], feature_ids: Annotated[Any, _atypes.Int32], node_ids: Annotated[List[Any], _atypes.Int32], gains: Annotated[List[Any], _atypes.Float32], thresholds: Annotated[List[Any], _atypes.Int32], left_node_contribs: Annotated[List[Any], _atypes.Float32], right_node_contribs: Annotated[List[Any], _atypes.Float32], max_depth: Annotated[Any, _atypes.Int32], learning_rate: Annotated[Any, _atypes.Float32], pruning_mode: int, name, ctx): + if not isinstance(node_ids, (list, tuple)): + raise TypeError( + "Expected list for 'node_ids' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % node_ids) + _attr_num_features = len(node_ids) + if not isinstance(gains, (list, tuple)): + raise TypeError( + "Expected list for 'gains' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % gains) + if len(gains) != _attr_num_features: + raise ValueError( + "List argument 'gains' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(gains), _attr_num_features)) + if not isinstance(thresholds, (list, tuple)): + raise TypeError( + "Expected list for 'thresholds' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % thresholds) + if len(thresholds) != _attr_num_features: + raise ValueError( + "List argument 'thresholds' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(thresholds), _attr_num_features)) + if not isinstance(left_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'left_node_contribs' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % left_node_contribs) + if len(left_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'left_node_contribs' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(left_node_contribs), _attr_num_features)) + if not isinstance(right_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'right_node_contribs' argument to " + "'boosted_trees_update_ensemble' Op, not %r." % right_node_contribs) + if len(right_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'right_node_contribs' to 'boosted_trees_update_ensemble' Op with length %d " + "must match length %d of argument 'node_ids'." % + (len(right_node_contribs), _attr_num_features)) + pruning_mode = _execute.make_int(pruning_mode, "pruning_mode") + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + feature_ids = _ops.convert_to_tensor(feature_ids, _dtypes.int32) + node_ids = _ops.convert_n_to_tensor(node_ids, _dtypes.int32) + gains = _ops.convert_n_to_tensor(gains, _dtypes.float32) + thresholds = _ops.convert_n_to_tensor(thresholds, _dtypes.int32) + left_node_contribs = _ops.convert_n_to_tensor(left_node_contribs, _dtypes.float32) + right_node_contribs = _ops.convert_n_to_tensor(right_node_contribs, _dtypes.float32) + max_depth = _ops.convert_to_tensor(max_depth, _dtypes.int32) + learning_rate = _ops.convert_to_tensor(learning_rate, _dtypes.float32) + _inputs_flat = [tree_ensemble_handle, feature_ids] + list(node_ids) + list(gains) + list(thresholds) + list(left_node_contribs) + list(right_node_contribs) + [max_depth, learning_rate] + _attrs = ("pruning_mode", pruning_mode, "num_features", _attr_num_features) + _result = _execute.execute(b"BoostedTreesUpdateEnsemble", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def boosted_trees_update_ensemble_v2(tree_ensemble_handle: Annotated[Any, _atypes.Resource], feature_ids: Annotated[List[Any], _atypes.Int32], dimension_ids: Annotated[List[Any], _atypes.Int32], node_ids: Annotated[List[Any], _atypes.Int32], gains: Annotated[List[Any], _atypes.Float32], thresholds: Annotated[List[Any], _atypes.Int32], left_node_contribs: Annotated[List[Any], _atypes.Float32], right_node_contribs: Annotated[List[Any], _atypes.Float32], split_types: Annotated[List[Any], _atypes.String], max_depth: Annotated[Any, _atypes.Int32], learning_rate: Annotated[Any, _atypes.Float32], pruning_mode: Annotated[Any, _atypes.Int32], logits_dimension:int=1, name=None): + r"""Updates the tree ensemble by adding a layer to the last tree being grown + + or by starting a new tree. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the ensemble variable. + feature_ids: A list of at least 1 `Tensor` objects with type `int32`. + Rank 1 tensor with ids for each feature. This is the real id of + the feature that will be used in the split. + dimension_ids: A list of `Tensor` objects with type `int32`. + List of rank 1 tensors representing the dimension in each feature. + node_ids: A list with the same length as `dimension_ids` of `Tensor` objects with type `int32`. + List of rank 1 tensors representing the nodes for which this feature + has a split. + gains: A list with the same length as `dimension_ids` of `Tensor` objects with type `float32`. + List of rank 1 tensors representing the gains for each of the feature's + split. + thresholds: A list with the same length as `dimension_ids` of `Tensor` objects with type `int32`. + List of rank 1 tensors representing the thesholds for each of the + feature's split. + left_node_contribs: A list with the same length as `dimension_ids` of `Tensor` objects with type `float32`. + List of rank 2 tensors with left leaf contribs for each of + the feature's splits. Will be added to the previous node values to constitute + the values of the left nodes. + right_node_contribs: A list with the same length as `dimension_ids` of `Tensor` objects with type `float32`. + List of rank 2 tensors with right leaf contribs for each + of the feature's splits. Will be added to the previous node values to constitute + the values of the right nodes. + split_types: A list with the same length as `dimension_ids` of `Tensor` objects with type `string`. + List of rank 1 tensors representing the split type for each feature. + max_depth: A `Tensor` of type `int32`. Max depth of the tree to build. + learning_rate: A `Tensor` of type `float32`. + shrinkage const for each new tree. + pruning_mode: A `Tensor` of type `int32`. + 0-No pruning, 1-Pre-pruning, 2-Post-pruning. + logits_dimension: An optional `int`. Defaults to `1`. + scalar, dimension of the logits + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BoostedTreesUpdateEnsembleV2", name, tree_ensemble_handle, + feature_ids, dimension_ids, node_ids, gains, thresholds, + left_node_contribs, right_node_contribs, split_types, max_depth, + learning_rate, pruning_mode, "logits_dimension", logits_dimension) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return boosted_trees_update_ensemble_v2_eager_fallback( + tree_ensemble_handle, feature_ids, dimension_ids, node_ids, gains, + thresholds, left_node_contribs, right_node_contribs, split_types, + max_depth, learning_rate, pruning_mode, + logits_dimension=logits_dimension, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dimension_ids, (list, tuple)): + raise TypeError( + "Expected list for 'dimension_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % dimension_ids) + _attr_num_features = len(dimension_ids) + if not isinstance(node_ids, (list, tuple)): + raise TypeError( + "Expected list for 'node_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % node_ids) + if len(node_ids) != _attr_num_features: + raise ValueError( + "List argument 'node_ids' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(node_ids), _attr_num_features)) + if not isinstance(gains, (list, tuple)): + raise TypeError( + "Expected list for 'gains' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % gains) + if len(gains) != _attr_num_features: + raise ValueError( + "List argument 'gains' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(gains), _attr_num_features)) + if not isinstance(thresholds, (list, tuple)): + raise TypeError( + "Expected list for 'thresholds' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % thresholds) + if len(thresholds) != _attr_num_features: + raise ValueError( + "List argument 'thresholds' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(thresholds), _attr_num_features)) + if not isinstance(left_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'left_node_contribs' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % left_node_contribs) + if len(left_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'left_node_contribs' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(left_node_contribs), _attr_num_features)) + if not isinstance(right_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'right_node_contribs' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % right_node_contribs) + if len(right_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'right_node_contribs' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(right_node_contribs), _attr_num_features)) + if not isinstance(split_types, (list, tuple)): + raise TypeError( + "Expected list for 'split_types' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % split_types) + if len(split_types) != _attr_num_features: + raise ValueError( + "List argument 'split_types' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(split_types), _attr_num_features)) + if not isinstance(feature_ids, (list, tuple)): + raise TypeError( + "Expected list for 'feature_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % feature_ids) + _attr_num_groups = len(feature_ids) + if logits_dimension is None: + logits_dimension = 1 + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BoostedTreesUpdateEnsembleV2", tree_ensemble_handle=tree_ensemble_handle, + feature_ids=feature_ids, + dimension_ids=dimension_ids, + node_ids=node_ids, gains=gains, + thresholds=thresholds, + left_node_contribs=left_node_contribs, + right_node_contribs=right_node_contribs, + split_types=split_types, + max_depth=max_depth, + learning_rate=learning_rate, + pruning_mode=pruning_mode, + logits_dimension=logits_dimension, + name=name) + return _op +BoostedTreesUpdateEnsembleV2 = tf_export("raw_ops.BoostedTreesUpdateEnsembleV2")(_ops.to_raw_op(boosted_trees_update_ensemble_v2)) + + +def boosted_trees_update_ensemble_v2_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], feature_ids: Annotated[List[Any], _atypes.Int32], dimension_ids: Annotated[List[Any], _atypes.Int32], node_ids: Annotated[List[Any], _atypes.Int32], gains: Annotated[List[Any], _atypes.Float32], thresholds: Annotated[List[Any], _atypes.Int32], left_node_contribs: Annotated[List[Any], _atypes.Float32], right_node_contribs: Annotated[List[Any], _atypes.Float32], split_types: Annotated[List[Any], _atypes.String], max_depth: Annotated[Any, _atypes.Int32], learning_rate: Annotated[Any, _atypes.Float32], pruning_mode: Annotated[Any, _atypes.Int32], logits_dimension: int, name, ctx): + if not isinstance(dimension_ids, (list, tuple)): + raise TypeError( + "Expected list for 'dimension_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % dimension_ids) + _attr_num_features = len(dimension_ids) + if not isinstance(node_ids, (list, tuple)): + raise TypeError( + "Expected list for 'node_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % node_ids) + if len(node_ids) != _attr_num_features: + raise ValueError( + "List argument 'node_ids' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(node_ids), _attr_num_features)) + if not isinstance(gains, (list, tuple)): + raise TypeError( + "Expected list for 'gains' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % gains) + if len(gains) != _attr_num_features: + raise ValueError( + "List argument 'gains' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(gains), _attr_num_features)) + if not isinstance(thresholds, (list, tuple)): + raise TypeError( + "Expected list for 'thresholds' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % thresholds) + if len(thresholds) != _attr_num_features: + raise ValueError( + "List argument 'thresholds' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(thresholds), _attr_num_features)) + if not isinstance(left_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'left_node_contribs' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % left_node_contribs) + if len(left_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'left_node_contribs' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(left_node_contribs), _attr_num_features)) + if not isinstance(right_node_contribs, (list, tuple)): + raise TypeError( + "Expected list for 'right_node_contribs' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % right_node_contribs) + if len(right_node_contribs) != _attr_num_features: + raise ValueError( + "List argument 'right_node_contribs' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(right_node_contribs), _attr_num_features)) + if not isinstance(split_types, (list, tuple)): + raise TypeError( + "Expected list for 'split_types' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % split_types) + if len(split_types) != _attr_num_features: + raise ValueError( + "List argument 'split_types' to 'boosted_trees_update_ensemble_v2' Op with length %d " + "must match length %d of argument 'dimension_ids'." % + (len(split_types), _attr_num_features)) + if not isinstance(feature_ids, (list, tuple)): + raise TypeError( + "Expected list for 'feature_ids' argument to " + "'boosted_trees_update_ensemble_v2' Op, not %r." % feature_ids) + _attr_num_groups = len(feature_ids) + if logits_dimension is None: + logits_dimension = 1 + logits_dimension = _execute.make_int(logits_dimension, "logits_dimension") + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + feature_ids = _ops.convert_n_to_tensor(feature_ids, _dtypes.int32) + dimension_ids = _ops.convert_n_to_tensor(dimension_ids, _dtypes.int32) + node_ids = _ops.convert_n_to_tensor(node_ids, _dtypes.int32) + gains = _ops.convert_n_to_tensor(gains, _dtypes.float32) + thresholds = _ops.convert_n_to_tensor(thresholds, _dtypes.int32) + left_node_contribs = _ops.convert_n_to_tensor(left_node_contribs, _dtypes.float32) + right_node_contribs = _ops.convert_n_to_tensor(right_node_contribs, _dtypes.float32) + split_types = _ops.convert_n_to_tensor(split_types, _dtypes.string) + max_depth = _ops.convert_to_tensor(max_depth, _dtypes.int32) + learning_rate = _ops.convert_to_tensor(learning_rate, _dtypes.float32) + pruning_mode = _ops.convert_to_tensor(pruning_mode, _dtypes.int32) + _inputs_flat = [tree_ensemble_handle] + list(feature_ids) + list(dimension_ids) + list(node_ids) + list(gains) + list(thresholds) + list(left_node_contribs) + list(right_node_contribs) + list(split_types) + [max_depth, learning_rate, pruning_mode] + _attrs = ("num_features", _attr_num_features, "logits_dimension", + logits_dimension, "num_groups", _attr_num_groups) + _result = _execute.execute(b"BoostedTreesUpdateEnsembleV2", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def is_boosted_trees_ensemble_initialized(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Checks whether a tree ensemble has been initialized. + + Args: + tree_ensemble_handle: A `Tensor` of type `resource`. + Handle to the tree ensemble resource. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsBoostedTreesEnsembleInitialized", name, tree_ensemble_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return is_boosted_trees_ensemble_initialized_eager_fallback( + tree_ensemble_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsBoostedTreesEnsembleInitialized", tree_ensemble_handle=tree_ensemble_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsBoostedTreesEnsembleInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsBoostedTreesEnsembleInitialized = tf_export("raw_ops.IsBoostedTreesEnsembleInitialized")(_ops.to_raw_op(is_boosted_trees_ensemble_initialized)) + + +def is_boosted_trees_ensemble_initialized_eager_fallback(tree_ensemble_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + tree_ensemble_handle = _ops.convert_to_tensor(tree_ensemble_handle, _dtypes.resource) + _inputs_flat = [tree_ensemble_handle] + _attrs = None + _result = _execute.execute(b"IsBoostedTreesEnsembleInitialized", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsBoostedTreesEnsembleInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def is_boosted_trees_quantile_stream_resource_initialized(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Checks whether a quantile stream has been initialized. + + An Op that checks if quantile stream resource is initialized. + + Args: + quantile_stream_resource_handle: A `Tensor` of type `resource`. + resource; The reference to quantile stream resource handle. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsBoostedTreesQuantileStreamResourceInitialized", name, + quantile_stream_resource_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return is_boosted_trees_quantile_stream_resource_initialized_eager_fallback( + quantile_stream_resource_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsBoostedTreesQuantileStreamResourceInitialized", quantile_stream_resource_handle=quantile_stream_resource_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsBoostedTreesQuantileStreamResourceInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsBoostedTreesQuantileStreamResourceInitialized = tf_export("raw_ops.IsBoostedTreesQuantileStreamResourceInitialized")(_ops.to_raw_op(is_boosted_trees_quantile_stream_resource_initialized)) + + +def is_boosted_trees_quantile_stream_resource_initialized_eager_fallback(quantile_stream_resource_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + quantile_stream_resource_handle = _ops.convert_to_tensor(quantile_stream_resource_handle, _dtypes.resource) + _inputs_flat = [quantile_stream_resource_handle] + _attrs = None + _result = _execute.execute(b"IsBoostedTreesQuantileStreamResourceInitialized", + 1, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsBoostedTreesQuantileStreamResourceInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_candidate_sampling_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_candidate_sampling_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c8bf6bfb1ddf06114965d7887747855e30a34b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_candidate_sampling_ops.py @@ -0,0 +1,951 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_AllCandidateSamplerOutput = collections.namedtuple( + "AllCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def all_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a learned unigram distribution. + + See explanations of candidate sampling and the data formats at + go/candidate-sampling. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. Number of candidates to produce. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AllCandidateSampler", name, true_classes, "num_true", num_true, + "num_sampled", num_sampled, "unique", unique, "seed", seed, "seed2", + seed2) + _result = _AllCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return all_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AllCandidateSampler", true_classes=true_classes, num_true=num_true, + num_sampled=num_sampled, unique=unique, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "seed", _op._get_attr_int("seed"), + "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AllCandidateSampler", _inputs_flat, _attrs, _result) + _result = _AllCandidateSamplerOutput._make(_result) + return _result + +AllCandidateSampler = tf_export("raw_ops.AllCandidateSampler")(_ops.to_raw_op(all_candidate_sampler)) + + +def all_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"AllCandidateSampler", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AllCandidateSampler", _inputs_flat, _attrs, _result) + _result = _AllCandidateSamplerOutput._make(_result) + return _result + +_ComputeAccidentalHitsOutput = collections.namedtuple( + "ComputeAccidentalHits", + ["indices", "ids", "weights"]) + + +def compute_accidental_hits(true_classes: Annotated[Any, _atypes.Int64], sampled_candidates: Annotated[Any, _atypes.Int64], num_true: int, seed:int=0, seed2:int=0, name=None): + r"""Computes the ids of the positions in sampled_candidates that match true_labels. + + When doing log-odds NCE, the result of this op should be passed through a + SparseToDense op, then added to the logits of the sampled candidates. This has + the effect of 'removing' the sampled labels that match the true labels by + making the classifier sure that they are sampled labels. + + Args: + true_classes: A `Tensor` of type `int64`. + The true_classes output of UnpackSparseLabels. + sampled_candidates: A `Tensor` of type `int64`. + The sampled_candidates output of CandidateSampler. + num_true: An `int`. Number of true labels per context. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, ids, weights). + + indices: A `Tensor` of type `int32`. + ids: A `Tensor` of type `int64`. + weights: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ComputeAccidentalHits", name, true_classes, sampled_candidates, + "num_true", num_true, "seed", seed, "seed2", seed2) + _result = _ComputeAccidentalHitsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return compute_accidental_hits_eager_fallback( + true_classes, sampled_candidates, num_true=num_true, seed=seed, + seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ComputeAccidentalHits", true_classes=true_classes, + sampled_candidates=sampled_candidates, + num_true=num_true, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ComputeAccidentalHits", _inputs_flat, _attrs, _result) + _result = _ComputeAccidentalHitsOutput._make(_result) + return _result + +ComputeAccidentalHits = tf_export("raw_ops.ComputeAccidentalHits")(_ops.to_raw_op(compute_accidental_hits)) + + +def compute_accidental_hits_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], sampled_candidates: Annotated[Any, _atypes.Int64], num_true: int, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + sampled_candidates = _ops.convert_to_tensor(sampled_candidates, _dtypes.int64) + _inputs_flat = [true_classes, sampled_candidates] + _attrs = ("num_true", num_true, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"ComputeAccidentalHits", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ComputeAccidentalHits", _inputs_flat, _attrs, _result) + _result = _ComputeAccidentalHitsOutput._make(_result) + return _result + +_FixedUnigramCandidateSamplerOutput = collections.namedtuple( + "FixedUnigramCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def fixed_unigram_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, vocab_file:str="", distortion:float=1, num_reserved_ids:int=0, num_shards:int=1, shard:int=0, unigrams=[], seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a learned unigram distribution. + + A unigram sampler could use a fixed unigram distribution read from a + file or passed in as an in-memory array instead of building up the distribution + from data on the fly. There is also an option to skew the distribution by + applying a distortion power to the weights. + + The vocabulary file should be in CSV-like format, with the last field + being the weight associated with the word. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. + Number of candidates to randomly sample. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + range_max: An `int` that is `>= 1`. + The sampler will sample integers from the interval [0, range_max). + vocab_file: An optional `string`. Defaults to `""`. + Each valid line in this file (which should have a CSV-like format) + corresponds to a valid word ID. IDs are in sequential order, starting from + num_reserved_ids. The last entry in each line is expected to be a value + corresponding to the count or relative probability. Exactly one of vocab_file + and unigrams needs to be passed to this op. + distortion: An optional `float`. Defaults to `1`. + The distortion is used to skew the unigram probability distribution. + Each weight is first raised to the distortion's power before adding to the + internal unigram distribution. As a result, distortion = 1.0 gives regular + unigram sampling (as defined by the vocab file), and distortion = 0.0 gives + a uniform distribution. + num_reserved_ids: An optional `int`. Defaults to `0`. + Optionally some reserved IDs can be added in the range [0, + ..., num_reserved_ids) by the users. One use case is that a special unknown + word token is used as ID 0. These IDs will have a sampling probability of 0. + num_shards: An optional `int` that is `>= 1`. Defaults to `1`. + A sampler can be used to sample from a subset of the original range + in order to speed up the whole computation through parallelism. This parameter + (together with 'shard') indicates the number of partitions that are being + used in the overall computation. + shard: An optional `int` that is `>= 0`. Defaults to `0`. + A sampler can be used to sample from a subset of the original range + in order to speed up the whole computation through parallelism. This parameter + (together with 'num_shards') indicates the particular partition number of a + sampler op, when partitioning is being used. + unigrams: An optional list of `floats`. Defaults to `[]`. + A list of unigram counts or probabilities, one per ID in sequential + order. Exactly one of vocab_file and unigrams should be passed to this op. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FixedUnigramCandidateSampler", name, true_classes, "num_true", + num_true, "num_sampled", num_sampled, "unique", unique, "range_max", + range_max, "vocab_file", vocab_file, "distortion", distortion, + "num_reserved_ids", num_reserved_ids, "num_shards", num_shards, + "shard", shard, "unigrams", unigrams, "seed", seed, "seed2", seed2) + _result = _FixedUnigramCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fixed_unigram_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, vocab_file=vocab_file, + distortion=distortion, num_reserved_ids=num_reserved_ids, + num_shards=num_shards, shard=shard, unigrams=unigrams, seed=seed, + seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if vocab_file is None: + vocab_file = "" + vocab_file = _execute.make_str(vocab_file, "vocab_file") + if distortion is None: + distortion = 1 + distortion = _execute.make_float(distortion, "distortion") + if num_reserved_ids is None: + num_reserved_ids = 0 + num_reserved_ids = _execute.make_int(num_reserved_ids, "num_reserved_ids") + if num_shards is None: + num_shards = 1 + num_shards = _execute.make_int(num_shards, "num_shards") + if shard is None: + shard = 0 + shard = _execute.make_int(shard, "shard") + if unigrams is None: + unigrams = [] + if not isinstance(unigrams, (list, tuple)): + raise TypeError( + "Expected list for 'unigrams' argument to " + "'fixed_unigram_candidate_sampler' Op, not %r." % unigrams) + unigrams = [_execute.make_float(_f, "unigrams") for _f in unigrams] + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FixedUnigramCandidateSampler", true_classes=true_classes, + num_true=num_true, + num_sampled=num_sampled, + unique=unique, range_max=range_max, + vocab_file=vocab_file, + distortion=distortion, + num_reserved_ids=num_reserved_ids, + num_shards=num_shards, shard=shard, + unigrams=unigrams, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "range_max", + _op._get_attr_int("range_max"), "vocab_file", + _op.get_attr("vocab_file"), "distortion", + _op.get_attr("distortion"), "num_reserved_ids", + _op._get_attr_int("num_reserved_ids"), "num_shards", + _op._get_attr_int("num_shards"), "shard", + _op._get_attr_int("shard"), "unigrams", + _op.get_attr("unigrams"), "seed", _op._get_attr_int("seed"), + "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FixedUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _FixedUnigramCandidateSamplerOutput._make(_result) + return _result + +FixedUnigramCandidateSampler = tf_export("raw_ops.FixedUnigramCandidateSampler")(_ops.to_raw_op(fixed_unigram_candidate_sampler)) + + +def fixed_unigram_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, vocab_file: str, distortion: float, num_reserved_ids: int, num_shards: int, shard: int, unigrams, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if vocab_file is None: + vocab_file = "" + vocab_file = _execute.make_str(vocab_file, "vocab_file") + if distortion is None: + distortion = 1 + distortion = _execute.make_float(distortion, "distortion") + if num_reserved_ids is None: + num_reserved_ids = 0 + num_reserved_ids = _execute.make_int(num_reserved_ids, "num_reserved_ids") + if num_shards is None: + num_shards = 1 + num_shards = _execute.make_int(num_shards, "num_shards") + if shard is None: + shard = 0 + shard = _execute.make_int(shard, "shard") + if unigrams is None: + unigrams = [] + if not isinstance(unigrams, (list, tuple)): + raise TypeError( + "Expected list for 'unigrams' argument to " + "'fixed_unigram_candidate_sampler' Op, not %r." % unigrams) + unigrams = [_execute.make_float(_f, "unigrams") for _f in unigrams] + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "range_max", range_max, "vocab_file", vocab_file, "distortion", + distortion, "num_reserved_ids", num_reserved_ids, "num_shards", num_shards, + "shard", shard, "unigrams", unigrams, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"FixedUnigramCandidateSampler", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FixedUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _FixedUnigramCandidateSamplerOutput._make(_result) + return _result + +_LearnedUnigramCandidateSamplerOutput = collections.namedtuple( + "LearnedUnigramCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def learned_unigram_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a learned unigram distribution. + + See explanations of candidate sampling and the data formats at + go/candidate-sampling. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. + Number of candidates to randomly sample. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + range_max: An `int` that is `>= 1`. + The sampler will sample integers from the interval [0, range_max). + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LearnedUnigramCandidateSampler", name, true_classes, + "num_true", num_true, "num_sampled", num_sampled, "unique", unique, + "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _LearnedUnigramCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return learned_unigram_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LearnedUnigramCandidateSampler", true_classes=true_classes, + num_true=num_true, + num_sampled=num_sampled, + unique=unique, range_max=range_max, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "range_max", + _op._get_attr_int("range_max"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LearnedUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _LearnedUnigramCandidateSamplerOutput._make(_result) + return _result + +LearnedUnigramCandidateSampler = tf_export("raw_ops.LearnedUnigramCandidateSampler")(_ops.to_raw_op(learned_unigram_candidate_sampler)) + + +def learned_unigram_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"LearnedUnigramCandidateSampler", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LearnedUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _LearnedUnigramCandidateSamplerOutput._make(_result) + return _result + +_LogUniformCandidateSamplerOutput = collections.namedtuple( + "LogUniformCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def log_uniform_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a log-uniform distribution. + + See explanations of candidate sampling and the data formats at + go/candidate-sampling. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. + Number of candidates to randomly sample. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + range_max: An `int` that is `>= 1`. + The sampler will sample integers from the interval [0, range_max). + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogUniformCandidateSampler", name, true_classes, "num_true", + num_true, "num_sampled", num_sampled, "unique", unique, "range_max", + range_max, "seed", seed, "seed2", seed2) + _result = _LogUniformCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return log_uniform_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogUniformCandidateSampler", true_classes=true_classes, + num_true=num_true, + num_sampled=num_sampled, unique=unique, + range_max=range_max, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "range_max", + _op._get_attr_int("range_max"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogUniformCandidateSampler", _inputs_flat, _attrs, _result) + _result = _LogUniformCandidateSamplerOutput._make(_result) + return _result + +LogUniformCandidateSampler = tf_export("raw_ops.LogUniformCandidateSampler")(_ops.to_raw_op(log_uniform_candidate_sampler)) + + +def log_uniform_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"LogUniformCandidateSampler", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogUniformCandidateSampler", _inputs_flat, _attrs, _result) + _result = _LogUniformCandidateSamplerOutput._make(_result) + return _result + +_ThreadUnsafeUnigramCandidateSamplerOutput = collections.namedtuple( + "ThreadUnsafeUnigramCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def thread_unsafe_unigram_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a learned unigram distribution. + + See explanations of candidate sampling and the data formats at + go/candidate-sampling. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. + Number of candidates to randomly sample. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + range_max: An `int` that is `>= 1`. + The sampler will sample integers from the interval [0, range_max). + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ThreadUnsafeUnigramCandidateSampler", name, true_classes, + "num_true", num_true, "num_sampled", num_sampled, "unique", unique, + "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _ThreadUnsafeUnigramCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return thread_unsafe_unigram_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ThreadUnsafeUnigramCandidateSampler", true_classes=true_classes, + num_true=num_true, + num_sampled=num_sampled, + unique=unique, + range_max=range_max, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "range_max", + _op._get_attr_int("range_max"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ThreadUnsafeUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _ThreadUnsafeUnigramCandidateSamplerOutput._make(_result) + return _result + +ThreadUnsafeUnigramCandidateSampler = tf_export("raw_ops.ThreadUnsafeUnigramCandidateSampler")(_ops.to_raw_op(thread_unsafe_unigram_candidate_sampler)) + + +def thread_unsafe_unigram_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"ThreadUnsafeUnigramCandidateSampler", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ThreadUnsafeUnigramCandidateSampler", _inputs_flat, _attrs, _result) + _result = _ThreadUnsafeUnigramCandidateSamplerOutput._make(_result) + return _result + +_UniformCandidateSamplerOutput = collections.namedtuple( + "UniformCandidateSampler", + ["sampled_candidates", "true_expected_count", "sampled_expected_count"]) + + +def uniform_candidate_sampler(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed:int=0, seed2:int=0, name=None): + r"""Generates labels for candidate sampling with a uniform distribution. + + See explanations of candidate sampling and the data formats at + go/candidate-sampling. + + For each batch, this op picks a single set of sampled candidate labels. + + The advantages of sampling candidates per-batch are simplicity and the + possibility of efficient dense matrix multiplication. The disadvantage is that + the sampled candidates must be chosen independently of the context and of the + true labels. + + Args: + true_classes: A `Tensor` of type `int64`. + A batch_size * num_true matrix, in which each row contains the + IDs of the num_true target_classes in the corresponding original label. + num_true: An `int` that is `>= 1`. Number of true labels per context. + num_sampled: An `int` that is `>= 1`. + Number of candidates to randomly sample. + unique: A `bool`. + If unique is true, we sample with rejection, so that all sampled + candidates in a batch are unique. This requires some approximation to + estimate the post-rejection sampling probabilities. + range_max: An `int` that is `>= 1`. + The sampler will sample integers from the interval [0, range_max). + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sampled_candidates, true_expected_count, sampled_expected_count). + + sampled_candidates: A `Tensor` of type `int64`. + true_expected_count: A `Tensor` of type `float32`. + sampled_expected_count: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformCandidateSampler", name, true_classes, "num_true", + num_true, "num_sampled", num_sampled, "unique", unique, "range_max", + range_max, "seed", seed, "seed2", seed2) + _result = _UniformCandidateSamplerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_candidate_sampler_eager_fallback( + true_classes, num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformCandidateSampler", true_classes=true_classes, + num_true=num_true, num_sampled=num_sampled, + unique=unique, range_max=range_max, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_true", _op._get_attr_int("num_true"), "num_sampled", + _op._get_attr_int("num_sampled"), "unique", + _op._get_attr_bool("unique"), "range_max", + _op._get_attr_int("range_max"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformCandidateSampler", _inputs_flat, _attrs, _result) + _result = _UniformCandidateSamplerOutput._make(_result) + return _result + +UniformCandidateSampler = tf_export("raw_ops.UniformCandidateSampler")(_ops.to_raw_op(uniform_candidate_sampler)) + + +def uniform_candidate_sampler_eager_fallback(true_classes: Annotated[Any, _atypes.Int64], num_true: int, num_sampled: int, unique: bool, range_max: int, seed: int, seed2: int, name, ctx): + num_true = _execute.make_int(num_true, "num_true") + num_sampled = _execute.make_int(num_sampled, "num_sampled") + unique = _execute.make_bool(unique, "unique") + range_max = _execute.make_int(range_max, "range_max") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + true_classes = _ops.convert_to_tensor(true_classes, _dtypes.int64) + _inputs_flat = [true_classes] + _attrs = ("num_true", num_true, "num_sampled", num_sampled, "unique", + unique, "range_max", range_max, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"UniformCandidateSampler", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformCandidateSampler", _inputs_flat, _attrs, _result) + _result = _UniformCandidateSamplerOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_checkpoint_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_checkpoint_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..080e69342d31cfcc040a046b19957141047fe53a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_checkpoint_ops.py @@ -0,0 +1,288 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_GenerateVocabRemappingOutput = collections.namedtuple( + "GenerateVocabRemapping", + ["remapping", "num_present"]) + + +def generate_vocab_remapping(new_vocab_file: Annotated[Any, _atypes.String], old_vocab_file: Annotated[Any, _atypes.String], new_vocab_offset: int, num_new_vocab: int, old_vocab_size:int=-1, name=None): + r"""Given a path to new and old vocabulary files, returns a remapping Tensor of + + length `num_new_vocab`, where `remapping[i]` contains the row number in the old + vocabulary that corresponds to row `i` in the new vocabulary (starting at line + `new_vocab_offset` and up to `num_new_vocab` entities), or `-1` if entry `i` + in the new vocabulary is not in the old vocabulary. The old vocabulary is + constrained to the first `old_vocab_size` entries if `old_vocab_size` is not the + default value of -1. + + `num_vocab_offset` enables + use in the partitioned variable case, and should generally be set through + examining partitioning info. The format of the files should be a text file, + with each line containing a single entity within the vocabulary. + + For example, with `new_vocab_file` a text file containing each of the following + elements on a single line: `[f0, f1, f2, f3]`, old_vocab_file = [f1, f0, f3], + `num_new_vocab = 3, new_vocab_offset = 1`, the returned remapping would be + `[0, -1, 2]`. + + The op also returns a count of how many entries in the new vocabulary + were present in the old vocabulary, which is used to calculate the number of + values to initialize in a weight matrix remapping + + This functionality can be used to remap both row vocabularies (typically, + features) and column vocabularies (typically, classes) from TensorFlow + checkpoints. Note that the partitioning logic relies on contiguous vocabularies + corresponding to div-partitioned variables. Moreover, the underlying remapping + uses an IndexTable (as opposed to an inexact CuckooTable), so client code should + use the corresponding index_table_from_file() as the FeatureColumn framework + does (as opposed to tf.feature_to_id(), which uses a CuckooTable). + + Args: + new_vocab_file: A `Tensor` of type `string`. Path to the new vocab file. + old_vocab_file: A `Tensor` of type `string`. Path to the old vocab file. + new_vocab_offset: An `int` that is `>= 0`. + How many entries into the new vocab file to start reading. + num_new_vocab: An `int` that is `>= 0`. + Number of entries in the new vocab file to remap. + old_vocab_size: An optional `int` that is `>= -1`. Defaults to `-1`. + Number of entries in the old vocab file to consider. If -1, + use the entire old vocabulary. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (remapping, num_present). + + remapping: A `Tensor` of type `int64`. + num_present: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GenerateVocabRemapping", name, new_vocab_file, old_vocab_file, + "new_vocab_offset", new_vocab_offset, "num_new_vocab", num_new_vocab, + "old_vocab_size", old_vocab_size) + _result = _GenerateVocabRemappingOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return generate_vocab_remapping_eager_fallback( + new_vocab_file, old_vocab_file, new_vocab_offset=new_vocab_offset, + num_new_vocab=num_new_vocab, old_vocab_size=old_vocab_size, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + new_vocab_offset = _execute.make_int(new_vocab_offset, "new_vocab_offset") + num_new_vocab = _execute.make_int(num_new_vocab, "num_new_vocab") + if old_vocab_size is None: + old_vocab_size = -1 + old_vocab_size = _execute.make_int(old_vocab_size, "old_vocab_size") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GenerateVocabRemapping", new_vocab_file=new_vocab_file, + old_vocab_file=old_vocab_file, + new_vocab_offset=new_vocab_offset, + num_new_vocab=num_new_vocab, + old_vocab_size=old_vocab_size, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("new_vocab_offset", _op._get_attr_int("new_vocab_offset"), + "num_new_vocab", _op._get_attr_int("num_new_vocab"), + "old_vocab_size", _op._get_attr_int("old_vocab_size")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GenerateVocabRemapping", _inputs_flat, _attrs, _result) + _result = _GenerateVocabRemappingOutput._make(_result) + return _result + +GenerateVocabRemapping = tf_export("raw_ops.GenerateVocabRemapping")(_ops.to_raw_op(generate_vocab_remapping)) + + +def generate_vocab_remapping_eager_fallback(new_vocab_file: Annotated[Any, _atypes.String], old_vocab_file: Annotated[Any, _atypes.String], new_vocab_offset: int, num_new_vocab: int, old_vocab_size: int, name, ctx): + new_vocab_offset = _execute.make_int(new_vocab_offset, "new_vocab_offset") + num_new_vocab = _execute.make_int(num_new_vocab, "num_new_vocab") + if old_vocab_size is None: + old_vocab_size = -1 + old_vocab_size = _execute.make_int(old_vocab_size, "old_vocab_size") + new_vocab_file = _ops.convert_to_tensor(new_vocab_file, _dtypes.string) + old_vocab_file = _ops.convert_to_tensor(old_vocab_file, _dtypes.string) + _inputs_flat = [new_vocab_file, old_vocab_file] + _attrs = ("new_vocab_offset", new_vocab_offset, "num_new_vocab", + num_new_vocab, "old_vocab_size", old_vocab_size) + _result = _execute.execute(b"GenerateVocabRemapping", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GenerateVocabRemapping", _inputs_flat, _attrs, _result) + _result = _GenerateVocabRemappingOutput._make(_result) + return _result + + +def load_and_remap_matrix(ckpt_path: Annotated[Any, _atypes.String], old_tensor_name: Annotated[Any, _atypes.String], row_remapping: Annotated[Any, _atypes.Int64], col_remapping: Annotated[Any, _atypes.Int64], initializing_values: Annotated[Any, _atypes.Float32], num_rows: int, num_cols: int, max_rows_in_memory:int=-1, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint + + at `ckpt_path` and potentially reorders its rows and columns using the + specified remappings. + + Most users should use one of the wrapper initializers (such as + `tf.contrib.framework.load_and_remap_matrix_initializer`) instead of this + function directly. + + The remappings are 1-D tensors with the following properties: + + * `row_remapping` must have exactly `num_rows` entries. Row `i` of the output + matrix will be initialized from the row corresponding to index + `row_remapping[i]` in the old `Tensor` from the checkpoint. + * `col_remapping` must have either 0 entries (indicating that no column + reordering is needed) or `num_cols` entries. If specified, column `j` of the + output matrix will be initialized from the column corresponding to index + `col_remapping[j]` in the old `Tensor` from the checkpoint. + * A value of -1 in either of the remappings signifies a "missing" entry. In that + case, values from the `initializing_values` tensor will be used to fill that + missing row or column. If `row_remapping` has `r` missing entries and + `col_remapping` has `c` missing entries, then the following condition must be + true: + + `(r * num_cols) + (c * num_rows) - (r * c) == len(initializing_values)` + + The remapping tensors can be generated using the GenerateVocabRemapping op. + + As an example, with row_remapping = [1, 0, -1], col_remapping = [0, 2, -1], + initializing_values = [0.5, -0.5, 0.25, -0.25, 42], and w(i, j) representing + the value from row i, column j of the old tensor in the checkpoint, the output + matrix will look like the following: + + [[w(1, 0), w(1, 2), 0.5], + [w(0, 0), w(0, 2), -0.5], + [0.25, -0.25, 42]] + + Args: + ckpt_path: A `Tensor` of type `string`. + Path to the TensorFlow checkpoint (version 2, `TensorBundle`) from + which the old matrix `Tensor` will be loaded. + old_tensor_name: A `Tensor` of type `string`. + Name of the 2-D `Tensor` to load from checkpoint. + row_remapping: A `Tensor` of type `int64`. + An int `Tensor` of row remappings (generally created by + `generate_vocab_remapping`). Even if no row remapping is needed, this must + still be an index-valued Tensor (e.g. [0, 1, 2, ...]), or a shifted + index-valued `Tensor` (e.g. [8, 9, 10, ...], for partitioned `Variables`). + col_remapping: A `Tensor` of type `int64`. + An int `Tensor` of column remappings (generally created by + `generate_vocab_remapping`). May be a size-0 `Tensor` if only row remapping + is to be done (e.g. column ordering is the same). + initializing_values: A `Tensor` of type `float32`. + A float `Tensor` containing values to fill in for cells + in the output matrix that are not loaded from the checkpoint. Length must be + exactly the same as the number of missing / new cells. + num_rows: An `int` that is `>= 0`. + Number of rows (length of the 1st dimension) in the output matrix. + num_cols: An `int` that is `>= 1`. + Number of columns (length of the 2nd dimension) in the output matrix. + max_rows_in_memory: An optional `int`. Defaults to `-1`. + The maximum number of rows to load from the checkpoint at + once. If less than or equal to 0, the entire matrix will be loaded into + memory. Setting this arg trades increased disk reads for lower memory usage. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadAndRemapMatrix", name, ckpt_path, old_tensor_name, + row_remapping, col_remapping, initializing_values, "num_rows", + num_rows, "num_cols", num_cols, "max_rows_in_memory", + max_rows_in_memory) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_and_remap_matrix_eager_fallback( + ckpt_path, old_tensor_name, row_remapping, col_remapping, + initializing_values, num_rows=num_rows, num_cols=num_cols, + max_rows_in_memory=max_rows_in_memory, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_rows = _execute.make_int(num_rows, "num_rows") + num_cols = _execute.make_int(num_cols, "num_cols") + if max_rows_in_memory is None: + max_rows_in_memory = -1 + max_rows_in_memory = _execute.make_int(max_rows_in_memory, "max_rows_in_memory") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadAndRemapMatrix", ckpt_path=ckpt_path, + old_tensor_name=old_tensor_name, + row_remapping=row_remapping, + col_remapping=col_remapping, + initializing_values=initializing_values, + num_rows=num_rows, num_cols=num_cols, + max_rows_in_memory=max_rows_in_memory, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_rows", _op._get_attr_int("num_rows"), "num_cols", + _op._get_attr_int("num_cols"), "max_rows_in_memory", + _op._get_attr_int("max_rows_in_memory")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LoadAndRemapMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LoadAndRemapMatrix = tf_export("raw_ops.LoadAndRemapMatrix")(_ops.to_raw_op(load_and_remap_matrix)) + + +def load_and_remap_matrix_eager_fallback(ckpt_path: Annotated[Any, _atypes.String], old_tensor_name: Annotated[Any, _atypes.String], row_remapping: Annotated[Any, _atypes.Int64], col_remapping: Annotated[Any, _atypes.Int64], initializing_values: Annotated[Any, _atypes.Float32], num_rows: int, num_cols: int, max_rows_in_memory: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + num_rows = _execute.make_int(num_rows, "num_rows") + num_cols = _execute.make_int(num_cols, "num_cols") + if max_rows_in_memory is None: + max_rows_in_memory = -1 + max_rows_in_memory = _execute.make_int(max_rows_in_memory, "max_rows_in_memory") + ckpt_path = _ops.convert_to_tensor(ckpt_path, _dtypes.string) + old_tensor_name = _ops.convert_to_tensor(old_tensor_name, _dtypes.string) + row_remapping = _ops.convert_to_tensor(row_remapping, _dtypes.int64) + col_remapping = _ops.convert_to_tensor(col_remapping, _dtypes.int64) + initializing_values = _ops.convert_to_tensor(initializing_values, _dtypes.float32) + _inputs_flat = [ckpt_path, old_tensor_name, row_remapping, col_remapping, initializing_values] + _attrs = ("num_rows", num_rows, "num_cols", num_cols, "max_rows_in_memory", + max_rows_in_memory) + _result = _execute.execute(b"LoadAndRemapMatrix", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LoadAndRemapMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_clustering_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_clustering_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..36f16d43bb07ec4e40295fd532921678d633fd17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_clustering_ops.py @@ -0,0 +1,241 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def kmc2_chain_initialization(distances: Annotated[Any, _atypes.Float32], seed: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the index of a data point that should be added to the seed set. + + Entries in distances are assumed to be squared distances of candidate points to + the already sampled centers in the seed set. The op constructs one Markov chain + of the k-MC^2 algorithm and returns the index of one candidate point to be added + as an additional cluster center. + + Args: + distances: A `Tensor` of type `float32`. + Vector with squared distances to the closest previously sampled cluster center + for each candidate point. + seed: A `Tensor` of type `int64`. + Scalar. Seed for initializing the random number generator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "KMC2ChainInitialization", name, distances, seed) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return kmc2_chain_initialization_eager_fallback( + distances, seed, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "KMC2ChainInitialization", distances=distances, seed=seed, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "KMC2ChainInitialization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +KMC2ChainInitialization = tf_export("raw_ops.KMC2ChainInitialization")(_ops.to_raw_op(kmc2_chain_initialization)) + + +def kmc2_chain_initialization_eager_fallback(distances: Annotated[Any, _atypes.Float32], seed: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Int64]: + distances = _ops.convert_to_tensor(distances, _dtypes.float32) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + _inputs_flat = [distances, seed] + _attrs = None + _result = _execute.execute(b"KMC2ChainInitialization", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "KMC2ChainInitialization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def kmeans_plus_plus_initialization(points: Annotated[Any, _atypes.Float32], num_to_sample: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], num_retries_per_sample: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Selects num_to_sample rows of input using the KMeans++ criterion. + + Rows of points are assumed to be input points. One row is selected at random. + Subsequent rows are sampled with probability proportional to the squared L2 + distance from the nearest row selected thus far till num_to_sample rows have + been sampled. + + Args: + points: A `Tensor` of type `float32`. + Matrix of shape (n, d). Rows are assumed to be input points. + num_to_sample: A `Tensor` of type `int64`. + Scalar. The number of rows to sample. This value must not be larger than n. + seed: A `Tensor` of type `int64`. + Scalar. Seed for initializing the random number generator. + num_retries_per_sample: A `Tensor` of type `int64`. + Scalar. For each row that is sampled, this parameter + specifies the number of additional points to draw from the current + distribution before selecting the best. If a negative value is specified, a + heuristic is used to sample O(log(num_to_sample)) additional points. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "KmeansPlusPlusInitialization", name, points, num_to_sample, + seed, num_retries_per_sample) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return kmeans_plus_plus_initialization_eager_fallback( + points, num_to_sample, seed, num_retries_per_sample, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "KmeansPlusPlusInitialization", points=points, + num_to_sample=num_to_sample, + seed=seed, + num_retries_per_sample=num_retries_per_sample, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "KmeansPlusPlusInitialization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +KmeansPlusPlusInitialization = tf_export("raw_ops.KmeansPlusPlusInitialization")(_ops.to_raw_op(kmeans_plus_plus_initialization)) + + +def kmeans_plus_plus_initialization_eager_fallback(points: Annotated[Any, _atypes.Float32], num_to_sample: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], num_retries_per_sample: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Float32]: + points = _ops.convert_to_tensor(points, _dtypes.float32) + num_to_sample = _ops.convert_to_tensor(num_to_sample, _dtypes.int64) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + num_retries_per_sample = _ops.convert_to_tensor(num_retries_per_sample, _dtypes.int64) + _inputs_flat = [points, num_to_sample, seed, num_retries_per_sample] + _attrs = None + _result = _execute.execute(b"KmeansPlusPlusInitialization", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "KmeansPlusPlusInitialization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_NearestNeighborsOutput = collections.namedtuple( + "NearestNeighbors", + ["nearest_center_indices", "nearest_center_distances"]) + + +def nearest_neighbors(points: Annotated[Any, _atypes.Float32], centers: Annotated[Any, _atypes.Float32], k: Annotated[Any, _atypes.Int64], name=None): + r"""Selects the k nearest centers for each point. + + Rows of points are assumed to be input points. Rows of centers are assumed to be + the list of candidate centers. For each point, the k centers that have least L2 + distance to it are computed. + + Args: + points: A `Tensor` of type `float32`. + Matrix of shape (n, d). Rows are assumed to be input points. + centers: A `Tensor` of type `float32`. + Matrix of shape (m, d). Rows are assumed to be centers. + k: A `Tensor` of type `int64`. + Number of nearest centers to return for each point. If k is larger than m, then + only m centers are returned. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (nearest_center_indices, nearest_center_distances). + + nearest_center_indices: A `Tensor` of type `int64`. + nearest_center_distances: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NearestNeighbors", name, points, centers, k) + _result = _NearestNeighborsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return nearest_neighbors_eager_fallback( + points, centers, k, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NearestNeighbors", points=points, centers=centers, k=k, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "NearestNeighbors", _inputs_flat, _attrs, _result) + _result = _NearestNeighborsOutput._make(_result) + return _result + +NearestNeighbors = tf_export("raw_ops.NearestNeighbors")(_ops.to_raw_op(nearest_neighbors)) + + +def nearest_neighbors_eager_fallback(points: Annotated[Any, _atypes.Float32], centers: Annotated[Any, _atypes.Float32], k: Annotated[Any, _atypes.Int64], name, ctx): + points = _ops.convert_to_tensor(points, _dtypes.float32) + centers = _ops.convert_to_tensor(centers, _dtypes.float32) + k = _ops.convert_to_tensor(k, _dtypes.int64) + _inputs_flat = [points, centers, k] + _attrs = None + _result = _execute.execute(b"NearestNeighbors", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NearestNeighbors", _inputs_flat, _attrs, _result) + _result = _NearestNeighborsOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_collective_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_collective_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..47dab58eb6178b1a5823723883a7fc4335d4958c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_collective_ops.py @@ -0,0 +1,1452 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_CollectiveAllToAllV2_T = TypeVar("TV_CollectiveAllToAllV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_all_to_all_v2(input: Annotated[Any, TV_CollectiveAllToAllV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], communication_hint:str="auto", timeout_seconds:float=0, is_stateless:bool=False, name=None) -> Annotated[Any, TV_CollectiveAllToAllV2_T]: + r"""Mutually exchanges multiple tensors of identical type and shape. + + `is_stateless` means each op does not need control dependencies to other + collective ops. In this case, keys that are unique at runtime + (e.g. `instance_key`) should be used to distinguish collective groups. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + ordering_token: A list of `Tensor` objects with type `resource`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + is_stateless: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveAllToAllV2", name, input, group_size, group_key, + instance_key, ordering_token, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds, + "is_stateless", is_stateless) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_all_to_all_v2_eager_fallback( + input, group_size, group_key, instance_key, ordering_token, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, is_stateless=is_stateless, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_all_to_all_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveAllToAllV2", input=input, group_size=group_size, + group_key=group_key, + instance_key=instance_key, + ordering_token=ordering_token, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, + is_stateless=is_stateless, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds"), "is_stateless", + _op._get_attr_bool("is_stateless"), "Nordering_token", + _op._get_attr_int("Nordering_token")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveAllToAllV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveAllToAllV2 = tf_export("raw_ops.CollectiveAllToAllV2")(_ops.to_raw_op(collective_all_to_all_v2)) + + +def collective_all_to_all_v2_eager_fallback(input: Annotated[Any, TV_CollectiveAllToAllV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], communication_hint: str, timeout_seconds: float, is_stateless: bool, name, ctx) -> Annotated[Any, TV_CollectiveAllToAllV2_T]: + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_all_to_all_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + ordering_token = _ops.convert_n_to_tensor(ordering_token, _dtypes.resource) + _inputs_flat = [input, group_size, group_key, instance_key] + list(ordering_token) + _attrs = ("T", _attr_T, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds, "is_stateless", is_stateless, + "Nordering_token", _attr_Nordering_token) + _result = _execute.execute(b"CollectiveAllToAllV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveAllToAllV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveAllToAllV3_T = TypeVar("TV_CollectiveAllToAllV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_all_to_all_v3(input: Annotated[Any, TV_CollectiveAllToAllV3_T], communicator: Annotated[Any, _atypes.Resource], group_assignment: Annotated[Any, _atypes.Int32], timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveAllToAllV3_T]: + r"""Mutually exchanges multiple tensors of identical type and shape. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + communicator: A `Tensor` of type `resource`. + group_assignment: A `Tensor` of type `int32`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveAllToAllV3", name, input, communicator, + group_assignment, "timeout_seconds", timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_all_to_all_v3_eager_fallback( + input, communicator, group_assignment, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveAllToAllV3", input=input, communicator=communicator, + group_assignment=group_assignment, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveAllToAllV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveAllToAllV3 = tf_export("raw_ops.CollectiveAllToAllV3")(_ops.to_raw_op(collective_all_to_all_v3)) + + +def collective_all_to_all_v3_eager_fallback(input: Annotated[Any, TV_CollectiveAllToAllV3_T], communicator: Annotated[Any, _atypes.Resource], group_assignment: Annotated[Any, _atypes.Int32], timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveAllToAllV3_T]: + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + communicator = _ops.convert_to_tensor(communicator, _dtypes.resource) + group_assignment = _ops.convert_to_tensor(group_assignment, _dtypes.int32) + _inputs_flat = [input, communicator, group_assignment] + _attrs = ("T", _attr_T, "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveAllToAllV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveAllToAllV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_CollectiveAssignGroupV2Output = collections.namedtuple( + "CollectiveAssignGroupV2", + ["group_size", "group_key"]) + + +def collective_assign_group_v2(group_assignment: Annotated[Any, _atypes.Int32], device_index: Annotated[Any, _atypes.Int32], base_key: Annotated[Any, _atypes.Int32], name=None): + r"""Assign group keys based on group assignment. + + Args: + group_assignment: A `Tensor` of type `int32`. + device_index: A `Tensor` of type `int32`. + base_key: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (group_size, group_key). + + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveAssignGroupV2", name, group_assignment, device_index, + base_key) + _result = _CollectiveAssignGroupV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_assign_group_v2_eager_fallback( + group_assignment, device_index, base_key, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveAssignGroupV2", group_assignment=group_assignment, + device_index=device_index, + base_key=base_key, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveAssignGroupV2", _inputs_flat, _attrs, _result) + _result = _CollectiveAssignGroupV2Output._make(_result) + return _result + +CollectiveAssignGroupV2 = tf_export("raw_ops.CollectiveAssignGroupV2")(_ops.to_raw_op(collective_assign_group_v2)) + + +def collective_assign_group_v2_eager_fallback(group_assignment: Annotated[Any, _atypes.Int32], device_index: Annotated[Any, _atypes.Int32], base_key: Annotated[Any, _atypes.Int32], name, ctx): + group_assignment = _ops.convert_to_tensor(group_assignment, _dtypes.int32) + device_index = _ops.convert_to_tensor(device_index, _dtypes.int32) + base_key = _ops.convert_to_tensor(base_key, _dtypes.int32) + _inputs_flat = [group_assignment, device_index, base_key] + _attrs = None + _result = _execute.execute(b"CollectiveAssignGroupV2", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveAssignGroupV2", _inputs_flat, _attrs, _result) + _result = _CollectiveAssignGroupV2Output._make(_result) + return _result + + +TV_CollectiveBcastRecv_T = TypeVar("TV_CollectiveBcastRecv_T", _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_bcast_recv(T: TV_CollectiveBcastRecv_T, group_size: int, group_key: int, instance_key: int, shape, communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveBcastRecv_T]: + r"""Receives a tensor value broadcast from another device. + + Args: + T: A `tf.DType` from: `tf.bool, tf.float32, tf.half, tf.float64, tf.int32, tf.int64`. + group_size: An `int`. + group_key: An `int`. + instance_key: An `int`. + shape: A `tf.TensorShape` or list of `ints`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveBcastRecv", name, "T", T, "group_size", group_size, + "group_key", group_key, "instance_key", instance_key, "shape", shape, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_bcast_recv_eager_fallback( + T=T, group_size=group_size, group_key=group_key, + instance_key=instance_key, shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveBcastRecv", T=T, group_size=group_size, + group_key=group_key, instance_key=instance_key, + shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "group_size", + _op._get_attr_int("group_size"), "group_key", + _op._get_attr_int("group_key"), "instance_key", + _op._get_attr_int("instance_key"), "shape", + _op.get_attr("shape"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveBcastRecv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveBcastRecv = tf_export("raw_ops.CollectiveBcastRecv")(_ops.to_raw_op(collective_bcast_recv)) + + +def collective_bcast_recv_eager_fallback(T: TV_CollectiveBcastRecv_T, group_size: int, group_key: int, instance_key: int, shape, communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveBcastRecv_T]: + T = _execute.make_type(T, "T") + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _inputs_flat = [] + _attrs = ("T", T, "group_size", group_size, "group_key", group_key, + "instance_key", instance_key, "shape", shape, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveBcastRecv", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveBcastRecv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveBcastRecvV2_T = TypeVar("TV_CollectiveBcastRecvV2_T", _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_CollectiveBcastRecvV2_Tshape = TypeVar("TV_CollectiveBcastRecvV2_Tshape", _atypes.Int32, _atypes.Int64) + +def collective_bcast_recv_v2(group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], shape: Annotated[Any, TV_CollectiveBcastRecvV2_Tshape], T: TV_CollectiveBcastRecvV2_T, communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveBcastRecvV2_T]: + r"""Receives a tensor value broadcast from another device. + + Args: + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + T: A `tf.DType` from: `tf.bool, tf.float32, tf.half, tf.float64, tf.int32, tf.int64`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveBcastRecvV2", name, group_size, group_key, + instance_key, shape, "T", T, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_bcast_recv_v2_eager_fallback( + group_size, group_key, instance_key, shape, T=T, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveBcastRecvV2", group_size=group_size, group_key=group_key, + instance_key=instance_key, shape=shape, T=T, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tshape", + _op._get_attr_type("Tshape"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveBcastRecvV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveBcastRecvV2 = tf_export("raw_ops.CollectiveBcastRecvV2")(_ops.to_raw_op(collective_bcast_recv_v2)) + + +def collective_bcast_recv_v2_eager_fallback(group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], shape: Annotated[Any, TV_CollectiveBcastRecvV2_Tshape], T: TV_CollectiveBcastRecvV2_T, communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveBcastRecvV2_T]: + T = _execute.make_type(T, "T") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + _inputs_flat = [group_size, group_key, instance_key, shape] + _attrs = ("T", T, "Tshape", _attr_Tshape, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveBcastRecvV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveBcastRecvV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveBcastSend_T = TypeVar("TV_CollectiveBcastSend_T", _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_bcast_send(input: Annotated[Any, TV_CollectiveBcastSend_T], group_size: int, group_key: int, instance_key: int, shape, communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveBcastSend_T]: + r"""Broadcasts a tensor value to one or more other devices. + + Args: + input: A `Tensor`. Must be one of the following types: `bool`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: An `int`. + group_key: An `int`. + instance_key: An `int`. + shape: A `tf.TensorShape` or list of `ints`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveBcastSend", name, input, "group_size", group_size, + "group_key", group_key, "instance_key", instance_key, "shape", shape, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_bcast_send_eager_fallback( + input, group_size=group_size, group_key=group_key, + instance_key=instance_key, shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveBcastSend", input=input, group_size=group_size, + group_key=group_key, instance_key=instance_key, + shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "group_size", + _op._get_attr_int("group_size"), "group_key", + _op._get_attr_int("group_key"), "instance_key", + _op._get_attr_int("instance_key"), "shape", + _op.get_attr("shape"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveBcastSend", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveBcastSend = tf_export("raw_ops.CollectiveBcastSend")(_ops.to_raw_op(collective_bcast_send)) + + +def collective_bcast_send_eager_fallback(input: Annotated[Any, TV_CollectiveBcastSend_T], group_size: int, group_key: int, instance_key: int, shape, communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveBcastSend_T]: + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bool, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "group_size", group_size, "group_key", group_key, + "instance_key", instance_key, "shape", shape, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveBcastSend", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveBcastSend", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveBcastSendV2_T = TypeVar("TV_CollectiveBcastSendV2_T", _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_bcast_send_v2(input: Annotated[Any, TV_CollectiveBcastSendV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveBcastSendV2_T]: + r"""Broadcasts a tensor value to one or more other devices. + + Args: + input: A `Tensor`. Must be one of the following types: `bool`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveBcastSendV2", name, input, group_size, group_key, + instance_key, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_bcast_send_v2_eager_fallback( + input, group_size, group_key, instance_key, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveBcastSendV2", input=input, group_size=group_size, + group_key=group_key, + instance_key=instance_key, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveBcastSendV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveBcastSendV2 = tf_export("raw_ops.CollectiveBcastSendV2")(_ops.to_raw_op(collective_bcast_send_v2)) + + +def collective_bcast_send_v2_eager_fallback(input: Annotated[Any, TV_CollectiveBcastSendV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveBcastSendV2_T]: + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bool, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + _inputs_flat = [input, group_size, group_key, instance_key] + _attrs = ("T", _attr_T, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveBcastSendV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveBcastSendV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveGather_T = TypeVar("TV_CollectiveGather_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_gather(input: Annotated[Any, TV_CollectiveGather_T], group_size: int, group_key: int, instance_key: int, shape, communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveGather_T]: + r"""Mutually accumulates multiple tensors of identical type and shape. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `half`, `float64`, `int32`, `int64`. + group_size: An `int`. + group_key: An `int`. + instance_key: An `int`. + shape: A `tf.TensorShape` or list of `ints`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveGather", name, input, "group_size", group_size, + "group_key", group_key, "instance_key", instance_key, "shape", shape, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_gather_eager_fallback( + input, group_size=group_size, group_key=group_key, + instance_key=instance_key, shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveGather", input=input, group_size=group_size, + group_key=group_key, instance_key=instance_key, + shape=shape, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "group_size", + _op._get_attr_int("group_size"), "group_key", + _op._get_attr_int("group_key"), "instance_key", + _op._get_attr_int("instance_key"), "shape", + _op.get_attr("shape"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveGather = tf_export("raw_ops.CollectiveGather")(_ops.to_raw_op(collective_gather)) + + +def collective_gather_eager_fallback(input: Annotated[Any, TV_CollectiveGather_T], group_size: int, group_key: int, instance_key: int, shape, communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveGather_T]: + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + shape = _execute.make_shape(shape, "shape") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "group_size", group_size, "group_key", group_key, + "instance_key", instance_key, "shape", shape, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds) + _result = _execute.execute(b"CollectiveGather", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveGatherV2_T = TypeVar("TV_CollectiveGatherV2_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_gather_v2(input: Annotated[Any, TV_CollectiveGatherV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], communication_hint:str="auto", timeout_seconds:float=0, is_stateless:bool=False, name=None) -> Annotated[Any, TV_CollectiveGatherV2_T]: + r"""Mutually accumulates multiple tensors of identical type and shape. + + `is_stateless` means each op does not need control dependencies to other + collective ops. In this case, keys that are unique at runtime + (e.g. `instance_key`) should be used to distinguish collective groups. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `half`, `float64`, `int32`, `int64`. + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + ordering_token: A list of `Tensor` objects with type `resource`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + is_stateless: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveGatherV2", name, input, group_size, group_key, + instance_key, ordering_token, "communication_hint", + communication_hint, "timeout_seconds", timeout_seconds, + "is_stateless", is_stateless) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_gather_v2_eager_fallback( + input, group_size, group_key, instance_key, ordering_token, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, is_stateless=is_stateless, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_gather_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveGatherV2", input=input, group_size=group_size, + group_key=group_key, instance_key=instance_key, + ordering_token=ordering_token, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, + is_stateless=is_stateless, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds"), "is_stateless", + _op._get_attr_bool("is_stateless"), "Nordering_token", + _op._get_attr_int("Nordering_token")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveGatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveGatherV2 = tf_export("raw_ops.CollectiveGatherV2")(_ops.to_raw_op(collective_gather_v2)) + + +def collective_gather_v2_eager_fallback(input: Annotated[Any, TV_CollectiveGatherV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], communication_hint: str, timeout_seconds: float, is_stateless: bool, name, ctx) -> Annotated[Any, TV_CollectiveGatherV2_T]: + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_gather_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + ordering_token = _ops.convert_n_to_tensor(ordering_token, _dtypes.resource) + _inputs_flat = [input, group_size, group_key, instance_key] + list(ordering_token) + _attrs = ("T", _attr_T, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds, "is_stateless", is_stateless, + "Nordering_token", _attr_Nordering_token) + _result = _execute.execute(b"CollectiveGatherV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveGatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def collective_initialize_communicator(group_key: Annotated[Any, _atypes.Int32], rank: Annotated[Any, _atypes.Int32], group_size: Annotated[Any, _atypes.Int32], communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Initializes a group for collective operations. + + Args: + group_key: A `Tensor` of type `int32`. + rank: A `Tensor` of type `int32`. + group_size: A `Tensor` of type `int32`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveInitializeCommunicator", name, group_key, rank, + group_size, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_initialize_communicator_eager_fallback( + group_key, rank, group_size, communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveInitializeCommunicator", group_key=group_key, rank=rank, + group_size=group_size, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("communication_hint", _op.get_attr("communication_hint"), + "timeout_seconds", _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveInitializeCommunicator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveInitializeCommunicator = tf_export("raw_ops.CollectiveInitializeCommunicator")(_ops.to_raw_op(collective_initialize_communicator)) + + +def collective_initialize_communicator_eager_fallback(group_key: Annotated[Any, _atypes.Int32], rank: Annotated[Any, _atypes.Int32], group_size: Annotated[Any, _atypes.Int32], communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, _atypes.Resource]: + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + rank = _ops.convert_to_tensor(rank, _dtypes.int32) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + _inputs_flat = [group_key, rank, group_size] + _attrs = ("communication_hint", communication_hint, "timeout_seconds", + timeout_seconds) + _result = _execute.execute(b"CollectiveInitializeCommunicator", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveInitializeCommunicator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveReduce_T = TypeVar("TV_CollectiveReduce_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_reduce(input: Annotated[Any, TV_CollectiveReduce_T], group_size: int, group_key: int, instance_key: int, merge_op: str, final_op: str, subdiv_offsets, wait_for=[], communication_hint:str="auto", timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveReduce_T]: + r"""Mutually reduces multiple tensors of identical type and shape. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: An `int`. + group_key: An `int`. + instance_key: An `int`. + merge_op: A `string` from: `"Min", "Max", "Mul", "Add"`. + final_op: A `string` from: `"Id", "Div"`. + subdiv_offsets: A list of `ints`. + wait_for: An optional list of `ints`. Defaults to `[]`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveReduce", name, input, "group_size", group_size, + "group_key", group_key, "instance_key", instance_key, "merge_op", + merge_op, "final_op", final_op, "subdiv_offsets", subdiv_offsets, + "wait_for", wait_for, "communication_hint", communication_hint, + "timeout_seconds", timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_reduce_eager_fallback( + input, group_size=group_size, group_key=group_key, + instance_key=instance_key, merge_op=merge_op, final_op=final_op, + subdiv_offsets=subdiv_offsets, wait_for=wait_for, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if not isinstance(subdiv_offsets, (list, tuple)): + raise TypeError( + "Expected list for 'subdiv_offsets' argument to " + "'collective_reduce' Op, not %r." % subdiv_offsets) + subdiv_offsets = [_execute.make_int(_i, "subdiv_offsets") for _i in subdiv_offsets] + if wait_for is None: + wait_for = [] + if not isinstance(wait_for, (list, tuple)): + raise TypeError( + "Expected list for 'wait_for' argument to " + "'collective_reduce' Op, not %r." % wait_for) + wait_for = [_execute.make_int(_i, "wait_for") for _i in wait_for] + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveReduce", input=input, group_size=group_size, + group_key=group_key, instance_key=instance_key, + merge_op=merge_op, final_op=final_op, + subdiv_offsets=subdiv_offsets, wait_for=wait_for, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "group_size", + _op._get_attr_int("group_size"), "group_key", + _op._get_attr_int("group_key"), "instance_key", + _op._get_attr_int("instance_key"), "merge_op", + _op.get_attr("merge_op"), "final_op", _op.get_attr("final_op"), + "subdiv_offsets", _op.get_attr("subdiv_offsets"), "wait_for", + _op.get_attr("wait_for"), "communication_hint", + _op.get_attr("communication_hint"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveReduce = tf_export("raw_ops.CollectiveReduce")(_ops.to_raw_op(collective_reduce)) + + +def collective_reduce_eager_fallback(input: Annotated[Any, TV_CollectiveReduce_T], group_size: int, group_key: int, instance_key: int, merge_op: str, final_op: str, subdiv_offsets, wait_for, communication_hint: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveReduce_T]: + group_size = _execute.make_int(group_size, "group_size") + group_key = _execute.make_int(group_key, "group_key") + instance_key = _execute.make_int(instance_key, "instance_key") + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if not isinstance(subdiv_offsets, (list, tuple)): + raise TypeError( + "Expected list for 'subdiv_offsets' argument to " + "'collective_reduce' Op, not %r." % subdiv_offsets) + subdiv_offsets = [_execute.make_int(_i, "subdiv_offsets") for _i in subdiv_offsets] + if wait_for is None: + wait_for = [] + if not isinstance(wait_for, (list, tuple)): + raise TypeError( + "Expected list for 'wait_for' argument to " + "'collective_reduce' Op, not %r." % wait_for) + wait_for = [_execute.make_int(_i, "wait_for") for _i in wait_for] + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "group_size", group_size, "group_key", group_key, + "instance_key", instance_key, "merge_op", merge_op, "final_op", final_op, + "subdiv_offsets", subdiv_offsets, "wait_for", wait_for, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds) + _result = _execute.execute(b"CollectiveReduce", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveReduceScatterV2_T = TypeVar("TV_CollectiveReduceScatterV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_reduce_scatter_v2(input: Annotated[Any, TV_CollectiveReduceScatterV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], merge_op: str, final_op: str, communication_hint:str="auto", timeout_seconds:float=0, is_stateless:bool=False, max_subdivs_per_device:int=-1, name=None) -> Annotated[Any, TV_CollectiveReduceScatterV2_T]: + r"""Mutually reduces multiple tensors of identical type and shape and scatters the result. + + `is_stateless` means each op does not need control dependencies to other + collective ops. In this case, keys that are unique at runtime + (e.g. `instance_key`) should be used to distinguish collective groups. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + ordering_token: A list of `Tensor` objects with type `resource`. + merge_op: A `string` from: `"Min", "Max", "Mul", "Add"`. + final_op: A `string` from: `"Id", "Div"`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + is_stateless: An optional `bool`. Defaults to `False`. + max_subdivs_per_device: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveReduceScatterV2", name, input, group_size, group_key, + instance_key, ordering_token, "merge_op", merge_op, "final_op", + final_op, "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds, "is_stateless", is_stateless, + "max_subdivs_per_device", max_subdivs_per_device) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_reduce_scatter_v2_eager_fallback( + input, group_size, group_key, instance_key, ordering_token, + merge_op=merge_op, final_op=final_op, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, is_stateless=is_stateless, + max_subdivs_per_device=max_subdivs_per_device, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_reduce_scatter_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + if max_subdivs_per_device is None: + max_subdivs_per_device = -1 + max_subdivs_per_device = _execute.make_int(max_subdivs_per_device, "max_subdivs_per_device") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveReduceScatterV2", input=input, group_size=group_size, + group_key=group_key, + instance_key=instance_key, + ordering_token=ordering_token, + merge_op=merge_op, final_op=final_op, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, + is_stateless=is_stateless, + max_subdivs_per_device=max_subdivs_per_device, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "merge_op", + _op.get_attr("merge_op"), "final_op", _op.get_attr("final_op"), + "communication_hint", _op.get_attr("communication_hint"), + "timeout_seconds", _op.get_attr("timeout_seconds"), + "is_stateless", _op._get_attr_bool("is_stateless"), + "Nordering_token", _op._get_attr_int("Nordering_token"), + "max_subdivs_per_device", + _op._get_attr_int("max_subdivs_per_device")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveReduceScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveReduceScatterV2 = tf_export("raw_ops.CollectiveReduceScatterV2")(_ops.to_raw_op(collective_reduce_scatter_v2)) + + +def collective_reduce_scatter_v2_eager_fallback(input: Annotated[Any, TV_CollectiveReduceScatterV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], merge_op: str, final_op: str, communication_hint: str, timeout_seconds: float, is_stateless: bool, max_subdivs_per_device: int, name, ctx) -> Annotated[Any, TV_CollectiveReduceScatterV2_T]: + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_reduce_scatter_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + if max_subdivs_per_device is None: + max_subdivs_per_device = -1 + max_subdivs_per_device = _execute.make_int(max_subdivs_per_device, "max_subdivs_per_device") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + ordering_token = _ops.convert_n_to_tensor(ordering_token, _dtypes.resource) + _inputs_flat = [input, group_size, group_key, instance_key] + list(ordering_token) + _attrs = ("T", _attr_T, "merge_op", merge_op, "final_op", final_op, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds, "is_stateless", is_stateless, "Nordering_token", + _attr_Nordering_token, "max_subdivs_per_device", max_subdivs_per_device) + _result = _execute.execute(b"CollectiveReduceScatterV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveReduceScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveReduceV2_T = TypeVar("TV_CollectiveReduceV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_reduce_v2(input: Annotated[Any, TV_CollectiveReduceV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], merge_op: str, final_op: str, communication_hint:str="auto", timeout_seconds:float=0, is_stateless:bool=False, max_subdivs_per_device:int=-1, name=None) -> Annotated[Any, TV_CollectiveReduceV2_T]: + r"""Mutually reduces multiple tensors of identical type and shape. + + `is_stateless` means each op does not need control dependencies to other + collective ops. In this case, keys that are unique at runtime + (e.g. `instance_key`) should be used to distinguish collective groups. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + group_size: A `Tensor` of type `int32`. + group_key: A `Tensor` of type `int32`. + instance_key: A `Tensor` of type `int32`. + ordering_token: A list of `Tensor` objects with type `resource`. + merge_op: A `string` from: `"Min", "Max", "Mul", "Add"`. + final_op: A `string` from: `"Id", "Div"`. + communication_hint: An optional `string`. Defaults to `"auto"`. + timeout_seconds: An optional `float`. Defaults to `0`. + is_stateless: An optional `bool`. Defaults to `False`. + max_subdivs_per_device: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveReduceV2", name, input, group_size, group_key, + instance_key, ordering_token, "merge_op", merge_op, "final_op", + final_op, "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds, "is_stateless", is_stateless, + "max_subdivs_per_device", max_subdivs_per_device) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_reduce_v2_eager_fallback( + input, group_size, group_key, instance_key, ordering_token, + merge_op=merge_op, final_op=final_op, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, is_stateless=is_stateless, + max_subdivs_per_device=max_subdivs_per_device, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_reduce_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + if max_subdivs_per_device is None: + max_subdivs_per_device = -1 + max_subdivs_per_device = _execute.make_int(max_subdivs_per_device, "max_subdivs_per_device") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveReduceV2", input=input, group_size=group_size, + group_key=group_key, instance_key=instance_key, + ordering_token=ordering_token, + merge_op=merge_op, final_op=final_op, + communication_hint=communication_hint, + timeout_seconds=timeout_seconds, + is_stateless=is_stateless, + max_subdivs_per_device=max_subdivs_per_device, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "merge_op", + _op.get_attr("merge_op"), "final_op", _op.get_attr("final_op"), + "communication_hint", _op.get_attr("communication_hint"), + "timeout_seconds", _op.get_attr("timeout_seconds"), + "is_stateless", _op._get_attr_bool("is_stateless"), + "Nordering_token", _op._get_attr_int("Nordering_token"), + "max_subdivs_per_device", + _op._get_attr_int("max_subdivs_per_device")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveReduceV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveReduceV2 = tf_export("raw_ops.CollectiveReduceV2")(_ops.to_raw_op(collective_reduce_v2)) + + +def collective_reduce_v2_eager_fallback(input: Annotated[Any, TV_CollectiveReduceV2_T], group_size: Annotated[Any, _atypes.Int32], group_key: Annotated[Any, _atypes.Int32], instance_key: Annotated[Any, _atypes.Int32], ordering_token: Annotated[List[Any], _atypes.Resource], merge_op: str, final_op: str, communication_hint: str, timeout_seconds: float, is_stateless: bool, max_subdivs_per_device: int, name, ctx) -> Annotated[Any, TV_CollectiveReduceV2_T]: + if not isinstance(ordering_token, (list, tuple)): + raise TypeError( + "Expected list for 'ordering_token' argument to " + "'collective_reduce_v2' Op, not %r." % ordering_token) + _attr_Nordering_token = len(ordering_token) + merge_op = _execute.make_str(merge_op, "merge_op") + final_op = _execute.make_str(final_op, "final_op") + if communication_hint is None: + communication_hint = "auto" + communication_hint = _execute.make_str(communication_hint, "communication_hint") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + if is_stateless is None: + is_stateless = False + is_stateless = _execute.make_bool(is_stateless, "is_stateless") + if max_subdivs_per_device is None: + max_subdivs_per_device = -1 + max_subdivs_per_device = _execute.make_int(max_subdivs_per_device, "max_subdivs_per_device") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + group_size = _ops.convert_to_tensor(group_size, _dtypes.int32) + group_key = _ops.convert_to_tensor(group_key, _dtypes.int32) + instance_key = _ops.convert_to_tensor(instance_key, _dtypes.int32) + ordering_token = _ops.convert_n_to_tensor(ordering_token, _dtypes.resource) + _inputs_flat = [input, group_size, group_key, instance_key] + list(ordering_token) + _attrs = ("T", _attr_T, "merge_op", merge_op, "final_op", final_op, + "communication_hint", communication_hint, "timeout_seconds", + timeout_seconds, "is_stateless", is_stateless, "Nordering_token", + _attr_Nordering_token, "max_subdivs_per_device", max_subdivs_per_device) + _result = _execute.execute(b"CollectiveReduceV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveReduceV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CollectiveReduceV3_T = TypeVar("TV_CollectiveReduceV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def collective_reduce_v3(input: Annotated[Any, TV_CollectiveReduceV3_T], communicator: Annotated[Any, _atypes.Resource], group_assignment: Annotated[Any, _atypes.Int32], reduction: str, timeout_seconds:float=0, name=None) -> Annotated[Any, TV_CollectiveReduceV3_T]: + r"""Mutually reduces multiple tensors of identical type and shape. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int32`, `int64`. + communicator: A `Tensor` of type `resource`. + group_assignment: A `Tensor` of type `int32`. + reduction: A `string` from: `"Min", "Max", "Mul", "Add"`. + timeout_seconds: An optional `float`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectiveReduceV3", name, input, communicator, + group_assignment, "reduction", reduction, "timeout_seconds", + timeout_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_reduce_v3_eager_fallback( + input, communicator, group_assignment, reduction=reduction, + timeout_seconds=timeout_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + reduction = _execute.make_str(reduction, "reduction") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectiveReduceV3", input=input, communicator=communicator, + group_assignment=group_assignment, + reduction=reduction, + timeout_seconds=timeout_seconds, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "reduction", + _op.get_attr("reduction"), "timeout_seconds", + _op.get_attr("timeout_seconds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectiveReduceV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectiveReduceV3 = tf_export("raw_ops.CollectiveReduceV3")(_ops.to_raw_op(collective_reduce_v3)) + + +def collective_reduce_v3_eager_fallback(input: Annotated[Any, TV_CollectiveReduceV3_T], communicator: Annotated[Any, _atypes.Resource], group_assignment: Annotated[Any, _atypes.Int32], reduction: str, timeout_seconds: float, name, ctx) -> Annotated[Any, TV_CollectiveReduceV3_T]: + reduction = _execute.make_str(reduction, "reduction") + if timeout_seconds is None: + timeout_seconds = 0 + timeout_seconds = _execute.make_float(timeout_seconds, "timeout_seconds") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + communicator = _ops.convert_to_tensor(communicator, _dtypes.resource) + group_assignment = _ops.convert_to_tensor(group_assignment, _dtypes.int32) + _inputs_flat = [input, communicator, group_assignment] + _attrs = ("T", _attr_T, "reduction", reduction, "timeout_seconds", + timeout_seconds) + _result = _execute.execute(b"CollectiveReduceV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectiveReduceV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_composite_tensor_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_composite_tensor_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..189c7e6f4ea0cfc2da4d592f67cf1c18291d09e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_composite_tensor_ops.py @@ -0,0 +1,172 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def composite_tensor_variant_from_components(components, metadata: str, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Encodes an `ExtensionType` value into a `variant` scalar Tensor. + + Returns a scalar variant tensor containing a single `CompositeTensorVariant` + with the specified Tensor components and TypeSpec. + + Args: + components: A list of `Tensor` objects. + The component tensors for the extension type value. + metadata: A `string`. + String serialization for the TypeSpec. (Note: the encoding for the TypeSpec + may change in future versions of TensorFlow.) + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CompositeTensorVariantFromComponents", name, components, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return composite_tensor_variant_from_components_eager_fallback( + components, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CompositeTensorVariantFromComponents", components=components, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata"), "Tcomponents", + _op.get_attr("Tcomponents")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CompositeTensorVariantFromComponents", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CompositeTensorVariantFromComponents = tf_export("raw_ops.CompositeTensorVariantFromComponents")(_ops.to_raw_op(composite_tensor_variant_from_components)) + + +def composite_tensor_variant_from_components_eager_fallback(components, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + metadata = _execute.make_str(metadata, "metadata") + _attr_Tcomponents, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + _inputs_flat = list(components) + _attrs = ("metadata", metadata, "Tcomponents", _attr_Tcomponents) + _result = _execute.execute(b"CompositeTensorVariantFromComponents", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CompositeTensorVariantFromComponents", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def composite_tensor_variant_to_components(encoded: Annotated[Any, _atypes.Variant], metadata: str, Tcomponents, name=None): + r"""Decodes a `variant` scalar Tensor into an `ExtensionType` value. + + Returns the Tensor components encoded in a `CompositeTensorVariant`. + + Raises an error if `type_spec_proto` doesn't match the TypeSpec + in `encoded`. + + Args: + encoded: A `Tensor` of type `variant`. + A scalar `variant` Tensor containing an encoded ExtensionType value. + metadata: A `string`. + String serialization for the TypeSpec. Must be compatible with the + `TypeSpec` contained in `encoded`. (Note: the encoding for the TypeSpec + may change in future versions of TensorFlow.) + Tcomponents: A list of `tf.DTypes`. Expected dtypes for components. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tcomponents`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CompositeTensorVariantToComponents", name, encoded, "metadata", + metadata, "Tcomponents", Tcomponents) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return composite_tensor_variant_to_components_eager_fallback( + encoded, metadata=metadata, Tcomponents=Tcomponents, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + metadata = _execute.make_str(metadata, "metadata") + if not isinstance(Tcomponents, (list, tuple)): + raise TypeError( + "Expected list for 'Tcomponents' argument to " + "'composite_tensor_variant_to_components' Op, not %r." % Tcomponents) + Tcomponents = [_execute.make_type(_t, "Tcomponents") for _t in Tcomponents] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CompositeTensorVariantToComponents", encoded=encoded, + metadata=metadata, + Tcomponents=Tcomponents, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata"), "Tcomponents", + _op.get_attr("Tcomponents")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CompositeTensorVariantToComponents", _inputs_flat, _attrs, _result) + return _result + +CompositeTensorVariantToComponents = tf_export("raw_ops.CompositeTensorVariantToComponents")(_ops.to_raw_op(composite_tensor_variant_to_components)) + + +def composite_tensor_variant_to_components_eager_fallback(encoded: Annotated[Any, _atypes.Variant], metadata: str, Tcomponents, name, ctx): + metadata = _execute.make_str(metadata, "metadata") + if not isinstance(Tcomponents, (list, tuple)): + raise TypeError( + "Expected list for 'Tcomponents' argument to " + "'composite_tensor_variant_to_components' Op, not %r." % Tcomponents) + Tcomponents = [_execute.make_type(_t, "Tcomponents") for _t in Tcomponents] + encoded = _ops.convert_to_tensor(encoded, _dtypes.variant) + _inputs_flat = [encoded] + _attrs = ("metadata", metadata, "Tcomponents", Tcomponents) + _result = _execute.execute(b"CompositeTensorVariantToComponents", + len(Tcomponents), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CompositeTensorVariantToComponents", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_control_flow_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_control_flow_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d18779e11e66d375950c965ac427984610c7c532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_control_flow_ops.py @@ -0,0 +1,884 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def abort(error_msg:str="", exit_without_error:bool=False, name=None): + r"""Raise a exception to abort the process when called. + + If exit_without_error is true, the process will exit normally, + otherwise it will exit with a SIGABORT signal. + + Returns nothing but an exception. + + Args: + error_msg: An optional `string`. Defaults to `""`. + A string which is the message associated with the exception. + exit_without_error: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Abort", name, "error_msg", error_msg, "exit_without_error", + exit_without_error) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return abort_eager_fallback( + error_msg=error_msg, exit_without_error=exit_without_error, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if error_msg is None: + error_msg = "" + error_msg = _execute.make_str(error_msg, "error_msg") + if exit_without_error is None: + exit_without_error = False + exit_without_error = _execute.make_bool(exit_without_error, "exit_without_error") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Abort", error_msg=error_msg, exit_without_error=exit_without_error, + name=name) + return _op +Abort = tf_export("raw_ops.Abort")(_ops.to_raw_op(abort)) + + +def abort_eager_fallback(error_msg: str, exit_without_error: bool, name, ctx): + if error_msg is None: + error_msg = "" + error_msg = _execute.make_str(error_msg, "error_msg") + if exit_without_error is None: + exit_without_error = False + exit_without_error = _execute.make_bool(exit_without_error, "exit_without_error") + _inputs_flat = [] + _attrs = ("error_msg", error_msg, "exit_without_error", exit_without_error) + _result = _execute.execute(b"Abort", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +def control_trigger(name=None): + r"""Does nothing. Serves as a control trigger for scheduling. + + Only useful as a placeholder for control edges. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ControlTrigger", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return control_trigger_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ControlTrigger", name=name) + return _op +ControlTrigger = tf_export("raw_ops.ControlTrigger")(_ops.to_raw_op(control_trigger)) + + +def control_trigger_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"ControlTrigger", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_Enter_T = TypeVar("TV_Enter_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def enter(data: Annotated[Any, TV_Enter_T], frame_name: str, is_constant:bool=False, parallel_iterations:int=10, name=None) -> Annotated[Any, TV_Enter_T]: + r"""Creates or finds a child frame, and makes `data` available to the child frame. + + This op is used together with `Exit` to create loops in the graph. + The unique `frame_name` is used by the `Executor` to identify frames. If + `is_constant` is true, `output` is a constant in the child frame; otherwise + it may be changed in the child frame. At most `parallel_iterations` iterations + are run in parallel in the child frame. + + Args: + data: A `Tensor`. The tensor to be made available to the child frame. + frame_name: A `string`. The name of the child frame. + is_constant: An optional `bool`. Defaults to `False`. + If true, the output is constant within the child frame. + parallel_iterations: An optional `int`. Defaults to `10`. + The number of iterations allowed to run in parallel. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Enter", name, data, "frame_name", frame_name, "is_constant", + is_constant, "parallel_iterations", parallel_iterations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enter_eager_fallback( + data, frame_name=frame_name, is_constant=is_constant, + parallel_iterations=parallel_iterations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + frame_name = _execute.make_str(frame_name, "frame_name") + if is_constant is None: + is_constant = False + is_constant = _execute.make_bool(is_constant, "is_constant") + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Enter", data=data, frame_name=frame_name, is_constant=is_constant, + parallel_iterations=parallel_iterations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "frame_name", + _op.get_attr("frame_name"), "is_constant", + _op._get_attr_bool("is_constant"), "parallel_iterations", + _op._get_attr_int("parallel_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Enter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Enter = tf_export("raw_ops.Enter")(_ops.to_raw_op(enter)) + + +def enter_eager_fallback(data: Annotated[Any, TV_Enter_T], frame_name: str, is_constant: bool, parallel_iterations: int, name, ctx) -> Annotated[Any, TV_Enter_T]: + frame_name = _execute.make_str(frame_name, "frame_name") + if is_constant is None: + is_constant = False + is_constant = _execute.make_bool(is_constant, "is_constant") + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + _inputs_flat = [data] + _attrs = ("T", _attr_T, "frame_name", frame_name, "is_constant", + is_constant, "parallel_iterations", parallel_iterations) + _result = _execute.execute(b"Enter", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Enter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Exit_T = TypeVar("TV_Exit_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def _exit(data: Annotated[Any, TV_Exit_T], name=None) -> Annotated[Any, TV_Exit_T]: + r"""Exits the current frame to its parent frame. + + Exit makes its input `data` available to the parent frame. + + Args: + data: A `Tensor`. The tensor to be made available to the parent frame. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Exit", name, data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _exit_eager_fallback( + data, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Exit", data=data, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Exit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Exit = tf_export("raw_ops.Exit")(_ops.to_raw_op(_exit)) + + +def _exit_eager_fallback(data: Annotated[Any, TV_Exit_T], name, ctx) -> Annotated[Any, TV_Exit_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + _inputs_flat = [data] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Exit", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Exit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def loop_cond(input: Annotated[Any, _atypes.Bool], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Forwards the input to the output. + + This operator represents the loop termination condition used by the + "pivot" switches of a loop. + + Args: + input: A `Tensor` of type `bool`. + A boolean scalar, representing the branch predicate of the Switch op. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoopCond", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return loop_cond_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoopCond", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LoopCond", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LoopCond = tf_export("raw_ops.LoopCond")(_ops.to_raw_op(loop_cond)) + + +def loop_cond_eager_fallback(input: Annotated[Any, _atypes.Bool], name, ctx) -> Annotated[Any, _atypes.Bool]: + input = _ops.convert_to_tensor(input, _dtypes.bool) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"LoopCond", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LoopCond", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_MergeOutput = collections.namedtuple( + "Merge", + ["output", "value_index"]) + + +TV_Merge_T = TypeVar("TV_Merge_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def merge(inputs: Annotated[List[Any], TV_Merge_T], name=None): + r"""Forwards the value of an available tensor from `inputs` to `output`. + + `Merge` waits for at least one of the tensors in `inputs` to become available. + It is usually combined with `Switch` to implement branching. + + `Merge` forwards the first tensor to become available to `output`, and sets + `value_index` to its index in `inputs`. + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + The input tensors, exactly one of which will become available. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, value_index). + + output: A `Tensor`. Has the same type as `inputs`. + value_index: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Merge", name, inputs) + _result = _MergeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return merge_eager_fallback( + inputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'merge' Op, not %r." % inputs) + _attr_N = len(inputs) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Merge", inputs=inputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Merge", _inputs_flat, _attrs, _result) + _result = _MergeOutput._make(_result) + return _result + +Merge = tf_export("raw_ops.Merge")(_ops.to_raw_op(merge)) + + +def merge_eager_fallback(inputs: Annotated[List[Any], TV_Merge_T], name, ctx): + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'merge' Op, not %r." % inputs) + _attr_N = len(inputs) + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"Merge", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Merge", _inputs_flat, _attrs, _result) + _result = _MergeOutput._make(_result) + return _result + + +TV_NextIteration_T = TypeVar("TV_NextIteration_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def next_iteration(data: Annotated[Any, TV_NextIteration_T], name=None) -> Annotated[Any, TV_NextIteration_T]: + r"""Makes its input available to the next iteration. + + Args: + data: A `Tensor`. The tensor to be made available to the next iteration. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NextIteration", name, data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return next_iteration_eager_fallback( + data, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NextIteration", data=data, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NextIteration", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NextIteration = tf_export("raw_ops.NextIteration")(_ops.to_raw_op(next_iteration)) + + +def next_iteration_eager_fallback(data: Annotated[Any, TV_NextIteration_T], name, ctx) -> Annotated[Any, TV_NextIteration_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + _inputs_flat = [data] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"NextIteration", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NextIteration", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('no_op') +def no_op(name=None): + r"""Does nothing. Only useful as a placeholder for control edges. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NoOp", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_no_op( + (name,), None) + if _result is not NotImplemented: + return _result + return no_op_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + no_op, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_no_op( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NoOp", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + no_op, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NoOp = tf_export("raw_ops.NoOp")(_ops.to_raw_op(no_op)) +_dispatcher_for_no_op = no_op._tf_type_based_dispatcher.Dispatch + + +def no_op_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"NoOp", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +TV_RefEnter_T = TypeVar("TV_RefEnter_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_enter(data: Annotated[Any, TV_RefEnter_T], frame_name: str, is_constant:bool=False, parallel_iterations:int=10, name=None) -> Annotated[Any, TV_RefEnter_T]: + r"""Creates or finds a child frame, and makes `data` available to the child frame. + + The unique `frame_name` is used by the `Executor` to identify frames. If + `is_constant` is true, `output` is a constant in the child frame; otherwise + it may be changed in the child frame. At most `parallel_iterations` iterations + are run in parallel in the child frame. + + Args: + data: A mutable `Tensor`. + The tensor to be made available to the child frame. + frame_name: A `string`. The name of the child frame. + is_constant: An optional `bool`. Defaults to `False`. + If true, the output is constant within the child frame. + parallel_iterations: An optional `int`. Defaults to `10`. + The number of iterations allowed to run in parallel. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_enter op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + frame_name = _execute.make_str(frame_name, "frame_name") + if is_constant is None: + is_constant = False + is_constant = _execute.make_bool(is_constant, "is_constant") + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefEnter", data=data, frame_name=frame_name, is_constant=is_constant, + parallel_iterations=parallel_iterations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "frame_name", + _op.get_attr("frame_name"), "is_constant", + _op._get_attr_bool("is_constant"), "parallel_iterations", + _op._get_attr_int("parallel_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefEnter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefEnter = tf_export("raw_ops.RefEnter")(_ops.to_raw_op(ref_enter)) + + +def ref_enter_eager_fallback(data: Annotated[Any, TV_RefEnter_T], frame_name: str, is_constant: bool, parallel_iterations: int, name, ctx) -> Annotated[Any, TV_RefEnter_T]: + raise RuntimeError("ref_enter op does not support eager execution. Arg 'output' is a ref.") + +TV_RefExit_T = TypeVar("TV_RefExit_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_exit(data: Annotated[Any, TV_RefExit_T], name=None) -> Annotated[Any, TV_RefExit_T]: + r"""Exits the current frame to its parent frame. + + Exit makes its input `data` available to the parent frame. + + Args: + data: A mutable `Tensor`. + The tensor to be made available to the parent frame. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_exit op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefExit", data=data, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefExit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefExit = tf_export("raw_ops.RefExit")(_ops.to_raw_op(ref_exit)) + + +def ref_exit_eager_fallback(data: Annotated[Any, TV_RefExit_T], name, ctx) -> Annotated[Any, TV_RefExit_T]: + raise RuntimeError("ref_exit op does not support eager execution. Arg 'output' is a ref.") +_RefMergeOutput = collections.namedtuple( + "RefMerge", + ["output", "value_index"]) + + +TV_RefMerge_T = TypeVar("TV_RefMerge_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_merge(inputs: Annotated[List[Any], TV_RefMerge_T], name=None): + r"""Forwards the value of an available tensor from `inputs` to `output`. + + `Merge` waits for at least one of the tensors in `inputs` to become available. + It is usually combined with `Switch` to implement branching. + + `Merge` forwards the first tensor for become available to `output`, and sets + `value_index` to its index in `inputs`. + + Args: + inputs: A list of at least 1 mutable `Tensor` objects with the same type. + The input tensors, exactly one of which will become available. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, value_index). + + output: A mutable `Tensor`. Has the same type as `inputs`. + value_index: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_merge op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'ref_merge' Op, not %r." % inputs) + _attr_N = len(inputs) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefMerge", inputs=inputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefMerge", _inputs_flat, _attrs, _result) + _result = _RefMergeOutput._make(_result) + return _result + +RefMerge = tf_export("raw_ops.RefMerge")(_ops.to_raw_op(ref_merge)) + + +def ref_merge_eager_fallback(inputs: Annotated[List[Any], TV_RefMerge_T], name, ctx): + raise RuntimeError("ref_merge op does not support eager execution. Arg 'output' is a ref.") + +TV_RefNextIteration_T = TypeVar("TV_RefNextIteration_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_next_iteration(data: Annotated[Any, TV_RefNextIteration_T], name=None) -> Annotated[Any, TV_RefNextIteration_T]: + r"""Makes its input available to the next iteration. + + Args: + data: A mutable `Tensor`. + The tensor to be made available to the next iteration. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_next_iteration op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefNextIteration", data=data, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefNextIteration", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefNextIteration = tf_export("raw_ops.RefNextIteration")(_ops.to_raw_op(ref_next_iteration)) + + +def ref_next_iteration_eager_fallback(data: Annotated[Any, TV_RefNextIteration_T], name, ctx) -> Annotated[Any, TV_RefNextIteration_T]: + raise RuntimeError("ref_next_iteration op does not support eager execution. Arg 'output' is a ref.") + +TV_RefSelect_T = TypeVar("TV_RefSelect_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_select(index: Annotated[Any, _atypes.Int32], inputs: Annotated[List[Any], TV_RefSelect_T], name=None) -> Annotated[Any, TV_RefSelect_T]: + r"""Forwards the `index`th element of `inputs` to `output`. + + Args: + index: A `Tensor` of type `int32`. + A scalar that determines the input that gets selected. + inputs: A list of at least 1 mutable `Tensor` objects with the same type. + A list of ref tensors, one of which will be forwarded to `output`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_select op does not support eager execution. Arg 'output' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'ref_select' Op, not %r." % inputs) + _attr_N = len(inputs) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefSelect", index=index, inputs=inputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefSelect", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefSelect = tf_export("raw_ops.RefSelect")(_ops.to_raw_op(ref_select)) + + +def ref_select_eager_fallback(index: Annotated[Any, _atypes.Int32], inputs: Annotated[List[Any], TV_RefSelect_T], name, ctx) -> Annotated[Any, TV_RefSelect_T]: + raise RuntimeError("ref_select op does not support eager execution. Arg 'output' is a ref.") +_RefSwitchOutput = collections.namedtuple( + "RefSwitch", + ["output_false", "output_true"]) + + +TV_RefSwitch_T = TypeVar("TV_RefSwitch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def ref_switch(data: Annotated[Any, TV_RefSwitch_T], pred: Annotated[Any, _atypes.Bool], name=None): + r"""Forwards the ref tensor `data` to the output port determined by `pred`. + + If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise, + the data goes to `output_false`. + + See also `Switch` and `Merge`. + + Args: + data: A mutable `Tensor`. + The ref tensor to be forwarded to the appropriate output. + pred: A `Tensor` of type `bool`. + A scalar that specifies which output port will receive data. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_false, output_true). + + output_false: A mutable `Tensor`. Has the same type as `data`. + output_true: A mutable `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_switch op does not support eager execution. Arg 'output_true' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefSwitch", data=data, pred=pred, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefSwitch", _inputs_flat, _attrs, _result) + _result = _RefSwitchOutput._make(_result) + return _result + +RefSwitch = tf_export("raw_ops.RefSwitch")(_ops.to_raw_op(ref_switch)) + + +def ref_switch_eager_fallback(data: Annotated[Any, TV_RefSwitch_T], pred: Annotated[Any, _atypes.Bool], name, ctx): + raise RuntimeError("ref_switch op does not support eager execution. Arg 'output_true' is a ref.") +_SwitchOutput = collections.namedtuple( + "Switch", + ["output_false", "output_true"]) + + +TV_Switch_T = TypeVar("TV_Switch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def switch(data: Annotated[Any, TV_Switch_T], pred: Annotated[Any, _atypes.Bool], name=None): + r"""Forwards `data` to the output port determined by `pred`. + + If `pred` is true, the `data` input is forwarded to `output_true`. Otherwise, + the data goes to `output_false`. + + See also `RefSwitch` and `Merge`. + + Args: + data: A `Tensor`. The tensor to be forwarded to the appropriate output. + pred: A `Tensor` of type `bool`. + A scalar that specifies which output port will receive data. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_false, output_true). + + output_false: A `Tensor`. Has the same type as `data`. + output_true: A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Switch", name, data, pred) + _result = _SwitchOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return switch_eager_fallback( + data, pred, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Switch", data=data, pred=pred, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Switch", _inputs_flat, _attrs, _result) + _result = _SwitchOutput._make(_result) + return _result + +Switch = tf_export("raw_ops.Switch")(_ops.to_raw_op(switch)) + + +def switch_eager_fallback(data: Annotated[Any, TV_Switch_T], pred: Annotated[Any, _atypes.Bool], name, ctx): + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + pred = _ops.convert_to_tensor(pred, _dtypes.bool) + _inputs_flat = [data, pred] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Switch", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Switch", _inputs_flat, _attrs, _result) + _result = _SwitchOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_count_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_count_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..87072be3076ed03ac328da1c101c49fa1677bb47 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_count_ops.py @@ -0,0 +1,349 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_DenseCountSparseOutputOutput = collections.namedtuple( + "DenseCountSparseOutput", + ["output_indices", "output_values", "output_dense_shape"]) + + +TV_DenseCountSparseOutput_T = TypeVar("TV_DenseCountSparseOutput_T", _atypes.Int32, _atypes.Int64) +TV_DenseCountSparseOutput_output_type = TypeVar("TV_DenseCountSparseOutput_output_type", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def dense_count_sparse_output(values: Annotated[Any, TV_DenseCountSparseOutput_T], weights: Annotated[Any, TV_DenseCountSparseOutput_output_type], binary_output: bool, minlength:int=-1, maxlength:int=-1, name=None): + r"""Performs sparse-output bin counting for a tf.tensor input. + + Counts the number of times each value occurs in the input. + + Args: + values: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Tensor containing data to count. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + A Tensor of the same shape as indices containing per-index weight values. May + also be the empty tensor if no weights are used. + binary_output: A `bool`. + Whether to output the number of occurrences of each value or 1. + minlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Minimum value to count. Can be set to -1 for no minimum. + maxlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Maximum value to count. Can be set to -1 for no maximum. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `weights`. + output_dense_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseCountSparseOutput", name, values, weights, "minlength", + minlength, "maxlength", maxlength, "binary_output", binary_output) + _result = _DenseCountSparseOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_count_sparse_output_eager_fallback( + values, weights, minlength=minlength, maxlength=maxlength, + binary_output=binary_output, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseCountSparseOutput", values=values, weights=weights, + binary_output=binary_output, + minlength=minlength, maxlength=maxlength, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "minlength", + _op._get_attr_int("minlength"), "maxlength", + _op._get_attr_int("maxlength"), "binary_output", + _op._get_attr_bool("binary_output"), "output_type", + _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _DenseCountSparseOutputOutput._make(_result) + return _result + +DenseCountSparseOutput = tf_export("raw_ops.DenseCountSparseOutput")(_ops.to_raw_op(dense_count_sparse_output)) + + +def dense_count_sparse_output_eager_fallback(values: Annotated[Any, TV_DenseCountSparseOutput_T], weights: Annotated[Any, TV_DenseCountSparseOutput_output_type], binary_output: bool, minlength: int, maxlength: int, name, ctx): + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [values, weights] + _attrs = ("T", _attr_T, "minlength", minlength, "maxlength", maxlength, + "binary_output", binary_output, "output_type", _attr_output_type) + _result = _execute.execute(b"DenseCountSparseOutput", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _DenseCountSparseOutputOutput._make(_result) + return _result + +_RaggedCountSparseOutputOutput = collections.namedtuple( + "RaggedCountSparseOutput", + ["output_indices", "output_values", "output_dense_shape"]) + + +TV_RaggedCountSparseOutput_T = TypeVar("TV_RaggedCountSparseOutput_T", _atypes.Int32, _atypes.Int64) +TV_RaggedCountSparseOutput_output_type = TypeVar("TV_RaggedCountSparseOutput_output_type", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def ragged_count_sparse_output(splits: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedCountSparseOutput_T], weights: Annotated[Any, TV_RaggedCountSparseOutput_output_type], binary_output: bool, minlength:int=-1, maxlength:int=-1, name=None): + r"""Performs sparse-output bin counting for a ragged tensor input. + + Counts the number of times each value occurs in the input. + + Args: + splits: A `Tensor` of type `int64`. + Tensor containing the row splits of the ragged tensor to count. + values: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Tensor containing values of the sparse tensor to count. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + A Tensor of the same shape as indices containing per-index weight values. + May also be the empty tensor if no weights are used. + binary_output: A `bool`. + Whether to output the number of occurrences of each value or 1. + minlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Minimum value to count. Can be set to -1 for no minimum. + maxlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Maximum value to count. Can be set to -1 for no maximum. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `weights`. + output_dense_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedCountSparseOutput", name, splits, values, weights, + "minlength", minlength, "maxlength", maxlength, "binary_output", + binary_output) + _result = _RaggedCountSparseOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_count_sparse_output_eager_fallback( + splits, values, weights, minlength=minlength, maxlength=maxlength, + binary_output=binary_output, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedCountSparseOutput", splits=splits, values=values, + weights=weights, + binary_output=binary_output, + minlength=minlength, maxlength=maxlength, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "minlength", + _op._get_attr_int("minlength"), "maxlength", + _op._get_attr_int("maxlength"), "binary_output", + _op._get_attr_bool("binary_output"), "output_type", + _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _RaggedCountSparseOutputOutput._make(_result) + return _result + +RaggedCountSparseOutput = tf_export("raw_ops.RaggedCountSparseOutput")(_ops.to_raw_op(ragged_count_sparse_output)) + + +def ragged_count_sparse_output_eager_fallback(splits: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedCountSparseOutput_T], weights: Annotated[Any, TV_RaggedCountSparseOutput_output_type], binary_output: bool, minlength: int, maxlength: int, name, ctx): + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + splits = _ops.convert_to_tensor(splits, _dtypes.int64) + _inputs_flat = [splits, values, weights] + _attrs = ("T", _attr_T, "minlength", minlength, "maxlength", maxlength, + "binary_output", binary_output, "output_type", _attr_output_type) + _result = _execute.execute(b"RaggedCountSparseOutput", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _RaggedCountSparseOutputOutput._make(_result) + return _result + +_SparseCountSparseOutputOutput = collections.namedtuple( + "SparseCountSparseOutput", + ["output_indices", "output_values", "output_dense_shape"]) + + +TV_SparseCountSparseOutput_T = TypeVar("TV_SparseCountSparseOutput_T", _atypes.Int32, _atypes.Int64) +TV_SparseCountSparseOutput_output_type = TypeVar("TV_SparseCountSparseOutput_output_type", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def sparse_count_sparse_output(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseCountSparseOutput_T], dense_shape: Annotated[Any, _atypes.Int64], weights: Annotated[Any, TV_SparseCountSparseOutput_output_type], binary_output: bool, minlength:int=-1, maxlength:int=-1, name=None): + r"""Performs sparse-output bin counting for a sparse tensor input. + + Counts the number of times each value occurs in the input. + + Args: + indices: A `Tensor` of type `int64`. + Tensor containing the indices of the sparse tensor to count. + values: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Tensor containing values of the sparse tensor to count. + dense_shape: A `Tensor` of type `int64`. + Tensor containing the dense shape of the sparse tensor to count. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + A Tensor of the same shape as indices containing per-index weight values. + May also be the empty tensor if no weights are used. + binary_output: A `bool`. + Whether to output the number of occurrences of each value or 1. + minlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Minimum value to count. Can be set to -1 for no minimum. + maxlength: An optional `int` that is `>= -1`. Defaults to `-1`. + Maximum value to count. Can be set to -1 for no maximum. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_dense_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `weights`. + output_dense_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseCountSparseOutput", name, indices, values, dense_shape, + weights, "minlength", minlength, "maxlength", maxlength, + "binary_output", binary_output) + _result = _SparseCountSparseOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_count_sparse_output_eager_fallback( + indices, values, dense_shape, weights, minlength=minlength, + maxlength=maxlength, binary_output=binary_output, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseCountSparseOutput", indices=indices, values=values, + dense_shape=dense_shape, weights=weights, + binary_output=binary_output, + minlength=minlength, maxlength=maxlength, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "minlength", + _op._get_attr_int("minlength"), "maxlength", + _op._get_attr_int("maxlength"), "binary_output", + _op._get_attr_bool("binary_output"), "output_type", + _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _SparseCountSparseOutputOutput._make(_result) + return _result + +SparseCountSparseOutput = tf_export("raw_ops.SparseCountSparseOutput")(_ops.to_raw_op(sparse_count_sparse_output)) + + +def sparse_count_sparse_output_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseCountSparseOutput_T], dense_shape: Annotated[Any, _atypes.Int64], weights: Annotated[Any, TV_SparseCountSparseOutput_output_type], binary_output: bool, minlength: int, maxlength: int, name, ctx): + binary_output = _execute.make_bool(binary_output, "binary_output") + if minlength is None: + minlength = -1 + minlength = _execute.make_int(minlength, "minlength") + if maxlength is None: + maxlength = -1 + maxlength = _execute.make_int(maxlength, "maxlength") + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_output_type, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [indices, values, dense_shape, weights] + _attrs = ("T", _attr_T, "minlength", minlength, "maxlength", maxlength, + "binary_output", binary_output, "output_type", _attr_output_type) + _result = _execute.execute(b"SparseCountSparseOutput", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseCountSparseOutput", _inputs_flat, _attrs, _result) + _result = _SparseCountSparseOutputOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ctc_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ctc_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..03c7cb298e45a797b1d99e5b8ee4257e81a28740 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ctc_ops.py @@ -0,0 +1,491 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_CTCBeamSearchDecoderOutput = collections.namedtuple( + "CTCBeamSearchDecoder", + ["decoded_indices", "decoded_values", "decoded_shape", "log_probability"]) + + +TV_CTCBeamSearchDecoder_T = TypeVar("TV_CTCBeamSearchDecoder_T", _atypes.Float32, _atypes.Float64) + +def ctc_beam_search_decoder(inputs: Annotated[Any, TV_CTCBeamSearchDecoder_T], sequence_length: Annotated[Any, _atypes.Int32], beam_width: int, top_paths: int, merge_repeated:bool=True, name=None): + r"""Performs beam search decoding on the logits given in input. + + A note about the attribute merge_repeated: For the beam search decoder, + this means that if consecutive entries in a beam are the same, only + the first of these is emitted. That is, when the top path is "A B B B B", + "A B" is returned if merge_repeated = True but "A B B B B" is + returned if merge_repeated = False. + + Args: + inputs: A `Tensor`. Must be one of the following types: `float32`, `float64`. + 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. + sequence_length: A `Tensor` of type `int32`. + A vector containing sequence lengths, size `(batch)`. + beam_width: An `int` that is `>= 1`. + A scalar >= 0 (beam search beam width). + top_paths: An `int` that is `>= 1`. + A scalar >= 0, <= beam_width (controls output size). + merge_repeated: An optional `bool`. Defaults to `True`. + If true, merge repeated classes in output. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (decoded_indices, decoded_values, decoded_shape, log_probability). + + decoded_indices: A list of `top_paths` `Tensor` objects with type `int64`. + decoded_values: A list of `top_paths` `Tensor` objects with type `int64`. + decoded_shape: A list of `top_paths` `Tensor` objects with type `int64`. + log_probability: A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CTCBeamSearchDecoder", name, inputs, sequence_length, + "beam_width", beam_width, "top_paths", top_paths, "merge_repeated", + merge_repeated) + _result = _CTCBeamSearchDecoderOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ctc_beam_search_decoder_eager_fallback( + inputs, sequence_length, beam_width=beam_width, top_paths=top_paths, + merge_repeated=merge_repeated, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + beam_width = _execute.make_int(beam_width, "beam_width") + top_paths = _execute.make_int(top_paths, "top_paths") + if merge_repeated is None: + merge_repeated = True + merge_repeated = _execute.make_bool(merge_repeated, "merge_repeated") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CTCBeamSearchDecoder", inputs=inputs, + sequence_length=sequence_length, + beam_width=beam_width, top_paths=top_paths, + merge_repeated=merge_repeated, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("beam_width", _op._get_attr_int("beam_width"), "top_paths", + _op._get_attr_int("top_paths"), "merge_repeated", + _op._get_attr_bool("merge_repeated"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CTCBeamSearchDecoder", _inputs_flat, _attrs, _result) + _result = [_result[:top_paths]] + _result[top_paths:] + _result = _result[:1] + [_result[1:1 + top_paths]] + _result[1 + top_paths:] + _result = _result[:2] + [_result[2:2 + top_paths]] + _result[2 + top_paths:] + _result = _CTCBeamSearchDecoderOutput._make(_result) + return _result + +CTCBeamSearchDecoder = tf_export("raw_ops.CTCBeamSearchDecoder")(_ops.to_raw_op(ctc_beam_search_decoder)) + + +def ctc_beam_search_decoder_eager_fallback(inputs: Annotated[Any, TV_CTCBeamSearchDecoder_T], sequence_length: Annotated[Any, _atypes.Int32], beam_width: int, top_paths: int, merge_repeated: bool, name, ctx): + beam_width = _execute.make_int(beam_width, "beam_width") + top_paths = _execute.make_int(top_paths, "top_paths") + if merge_repeated is None: + merge_repeated = True + merge_repeated = _execute.make_bool(merge_repeated, "merge_repeated") + _attr_T, (inputs,) = _execute.args_to_matching_eager([inputs], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + sequence_length = _ops.convert_to_tensor(sequence_length, _dtypes.int32) + _inputs_flat = [inputs, sequence_length] + _attrs = ("beam_width", beam_width, "top_paths", top_paths, + "merge_repeated", merge_repeated, "T", _attr_T) + _result = _execute.execute(b"CTCBeamSearchDecoder", top_paths + top_paths + + top_paths + 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CTCBeamSearchDecoder", _inputs_flat, _attrs, _result) + _result = [_result[:top_paths]] + _result[top_paths:] + _result = _result[:1] + [_result[1:1 + top_paths]] + _result[1 + top_paths:] + _result = _result[:2] + [_result[2:2 + top_paths]] + _result[2 + top_paths:] + _result = _CTCBeamSearchDecoderOutput._make(_result) + return _result + +_CTCGreedyDecoderOutput = collections.namedtuple( + "CTCGreedyDecoder", + ["decoded_indices", "decoded_values", "decoded_shape", "log_probability"]) + + +TV_CTCGreedyDecoder_T = TypeVar("TV_CTCGreedyDecoder_T", _atypes.Float32, _atypes.Float64) + +def ctc_greedy_decoder(inputs: Annotated[Any, TV_CTCGreedyDecoder_T], sequence_length: Annotated[Any, _atypes.Int32], merge_repeated:bool=False, blank_index:int=-1, name=None): + r"""Performs greedy decoding on the logits given in inputs. + + A note about the attribute merge_repeated: if enabled, when + consecutive logits' maximum indices are the same, only the first of + these is emitted. Labeling the blank '*', the sequence "A B B * B B" + becomes "A B B" if merge_repeated = True and "A B B B B" if + merge_repeated = False. + + Regardless of the value of merge_repeated, if the maximum index of a given + time and batch corresponds to the blank, index `(num_classes - 1)`, no new + element is emitted. + + Args: + inputs: A `Tensor`. Must be one of the following types: `float32`, `float64`. + 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. + sequence_length: A `Tensor` of type `int32`. + A vector containing sequence lengths, size `(batch_size)`. + merge_repeated: An optional `bool`. Defaults to `False`. + If True, merge repeated classes in output. + blank_index: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (decoded_indices, decoded_values, decoded_shape, log_probability). + + decoded_indices: A `Tensor` of type `int64`. + decoded_values: A `Tensor` of type `int64`. + decoded_shape: A `Tensor` of type `int64`. + log_probability: A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CTCGreedyDecoder", name, inputs, sequence_length, + "merge_repeated", merge_repeated, "blank_index", blank_index) + _result = _CTCGreedyDecoderOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ctc_greedy_decoder_eager_fallback( + inputs, sequence_length, merge_repeated=merge_repeated, + blank_index=blank_index, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if merge_repeated is None: + merge_repeated = False + merge_repeated = _execute.make_bool(merge_repeated, "merge_repeated") + if blank_index is None: + blank_index = -1 + blank_index = _execute.make_int(blank_index, "blank_index") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CTCGreedyDecoder", inputs=inputs, sequence_length=sequence_length, + merge_repeated=merge_repeated, + blank_index=blank_index, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("merge_repeated", _op._get_attr_bool("merge_repeated"), + "blank_index", _op._get_attr_int("blank_index"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CTCGreedyDecoder", _inputs_flat, _attrs, _result) + _result = _CTCGreedyDecoderOutput._make(_result) + return _result + +CTCGreedyDecoder = tf_export("raw_ops.CTCGreedyDecoder")(_ops.to_raw_op(ctc_greedy_decoder)) + + +def ctc_greedy_decoder_eager_fallback(inputs: Annotated[Any, TV_CTCGreedyDecoder_T], sequence_length: Annotated[Any, _atypes.Int32], merge_repeated: bool, blank_index: int, name, ctx): + if merge_repeated is None: + merge_repeated = False + merge_repeated = _execute.make_bool(merge_repeated, "merge_repeated") + if blank_index is None: + blank_index = -1 + blank_index = _execute.make_int(blank_index, "blank_index") + _attr_T, (inputs,) = _execute.args_to_matching_eager([inputs], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + sequence_length = _ops.convert_to_tensor(sequence_length, _dtypes.int32) + _inputs_flat = [inputs, sequence_length] + _attrs = ("merge_repeated", merge_repeated, "blank_index", blank_index, "T", + _attr_T) + _result = _execute.execute(b"CTCGreedyDecoder", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CTCGreedyDecoder", _inputs_flat, _attrs, _result) + _result = _CTCGreedyDecoderOutput._make(_result) + return _result + +_CTCLossOutput = collections.namedtuple( + "CTCLoss", + ["loss", "gradient"]) + + +TV_CTCLoss_T = TypeVar("TV_CTCLoss_T", _atypes.Float32, _atypes.Float64) + +def ctc_loss(inputs: Annotated[Any, TV_CTCLoss_T], labels_indices: Annotated[Any, _atypes.Int64], labels_values: Annotated[Any, _atypes.Int32], sequence_length: Annotated[Any, _atypes.Int32], preprocess_collapse_repeated:bool=False, ctc_merge_repeated:bool=True, ignore_longer_outputs_than_inputs:bool=False, name=None): + r"""Calculates the CTC Loss (log probability) for each batch entry. Also calculates + + the gradient. This class performs the softmax operation for you, so inputs + should be e.g. linear projections of outputs by an LSTM. + + Args: + inputs: A `Tensor`. Must be one of the following types: `float32`, `float64`. + 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. + labels_indices: A `Tensor` of type `int64`. + The indices of a `SparseTensor`. + `labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for + `(batch b, time t)`. + labels_values: A `Tensor` of type `int32`. + The values (labels) associated with the given batch and time. + sequence_length: A `Tensor` of type `int32`. + A vector containing sequence lengths (batch). + preprocess_collapse_repeated: An optional `bool`. Defaults to `False`. + Scalar, if true then repeated labels are + collapsed prior to the CTC calculation. + ctc_merge_repeated: An optional `bool`. Defaults to `True`. + Scalar. If set to false, *during* CTC calculation + repeated non-blank labels will not be merged and are interpreted as + individual labels. This is a simplified version of CTC. + ignore_longer_outputs_than_inputs: An optional `bool`. Defaults to `False`. + Scalar. If set to true, during CTC + calculation, items that have longer output sequences than input sequences + are skipped: they don't contribute to the loss term and have zero-gradient. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (loss, gradient). + + loss: A `Tensor`. Has the same type as `inputs`. + gradient: A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CTCLoss", name, inputs, labels_indices, labels_values, + sequence_length, "preprocess_collapse_repeated", + preprocess_collapse_repeated, "ctc_merge_repeated", + ctc_merge_repeated, "ignore_longer_outputs_than_inputs", + ignore_longer_outputs_than_inputs) + _result = _CTCLossOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ctc_loss_eager_fallback( + inputs, labels_indices, labels_values, sequence_length, + preprocess_collapse_repeated=preprocess_collapse_repeated, + ctc_merge_repeated=ctc_merge_repeated, + ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if preprocess_collapse_repeated is None: + preprocess_collapse_repeated = False + preprocess_collapse_repeated = _execute.make_bool(preprocess_collapse_repeated, "preprocess_collapse_repeated") + if ctc_merge_repeated is None: + ctc_merge_repeated = True + ctc_merge_repeated = _execute.make_bool(ctc_merge_repeated, "ctc_merge_repeated") + if ignore_longer_outputs_than_inputs is None: + ignore_longer_outputs_than_inputs = False + ignore_longer_outputs_than_inputs = _execute.make_bool(ignore_longer_outputs_than_inputs, "ignore_longer_outputs_than_inputs") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CTCLoss", inputs=inputs, labels_indices=labels_indices, + labels_values=labels_values, + sequence_length=sequence_length, + preprocess_collapse_repeated=preprocess_collapse_repeated, + ctc_merge_repeated=ctc_merge_repeated, + ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("preprocess_collapse_repeated", + _op._get_attr_bool("preprocess_collapse_repeated"), + "ctc_merge_repeated", _op._get_attr_bool("ctc_merge_repeated"), + "ignore_longer_outputs_than_inputs", + _op._get_attr_bool("ignore_longer_outputs_than_inputs"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CTCLoss", _inputs_flat, _attrs, _result) + _result = _CTCLossOutput._make(_result) + return _result + +CTCLoss = tf_export("raw_ops.CTCLoss")(_ops.to_raw_op(ctc_loss)) + + +def ctc_loss_eager_fallback(inputs: Annotated[Any, TV_CTCLoss_T], labels_indices: Annotated[Any, _atypes.Int64], labels_values: Annotated[Any, _atypes.Int32], sequence_length: Annotated[Any, _atypes.Int32], preprocess_collapse_repeated: bool, ctc_merge_repeated: bool, ignore_longer_outputs_than_inputs: bool, name, ctx): + if preprocess_collapse_repeated is None: + preprocess_collapse_repeated = False + preprocess_collapse_repeated = _execute.make_bool(preprocess_collapse_repeated, "preprocess_collapse_repeated") + if ctc_merge_repeated is None: + ctc_merge_repeated = True + ctc_merge_repeated = _execute.make_bool(ctc_merge_repeated, "ctc_merge_repeated") + if ignore_longer_outputs_than_inputs is None: + ignore_longer_outputs_than_inputs = False + ignore_longer_outputs_than_inputs = _execute.make_bool(ignore_longer_outputs_than_inputs, "ignore_longer_outputs_than_inputs") + _attr_T, (inputs,) = _execute.args_to_matching_eager([inputs], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + labels_indices = _ops.convert_to_tensor(labels_indices, _dtypes.int64) + labels_values = _ops.convert_to_tensor(labels_values, _dtypes.int32) + sequence_length = _ops.convert_to_tensor(sequence_length, _dtypes.int32) + _inputs_flat = [inputs, labels_indices, labels_values, sequence_length] + _attrs = ("preprocess_collapse_repeated", preprocess_collapse_repeated, + "ctc_merge_repeated", ctc_merge_repeated, + "ignore_longer_outputs_than_inputs", ignore_longer_outputs_than_inputs, "T", + _attr_T) + _result = _execute.execute(b"CTCLoss", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CTCLoss", _inputs_flat, _attrs, _result) + _result = _CTCLossOutput._make(_result) + return _result + +_CTCLossV2Output = collections.namedtuple( + "CTCLossV2", + ["loss", "gradient"]) + + +def ctc_loss_v2(inputs: Annotated[Any, _atypes.Float32], labels_indices: Annotated[Any, _atypes.Int64], labels_values: Annotated[Any, _atypes.Int32], sequence_length: Annotated[Any, _atypes.Int32], preprocess_collapse_repeated:bool=False, ctc_merge_repeated:bool=True, ignore_longer_outputs_than_inputs:bool=False, name=None): + r"""Calculates the CTC Loss (log probability) for each batch entry. Also calculates + + the gradient. This class performs the softmax operation for you, so inputs + should be e.g. linear projections of outputs by an LSTM. + + Args: + inputs: A `Tensor` of type `float32`. + 3-D, shape: `(max_time x batch_size x num_classes)`, the logits. Default blank + label is 0 rather num_classes - 1. + labels_indices: A `Tensor` of type `int64`. + The indices of a `SparseTensor`. + `labels_indices(i, :) == [b, t]` means `labels_values(i)` stores the id for + `(batch b, time t)`. + labels_values: A `Tensor` of type `int32`. + The values (labels) associated with the given batch and time. + sequence_length: A `Tensor` of type `int32`. + A vector containing sequence lengths (batch). + preprocess_collapse_repeated: An optional `bool`. Defaults to `False`. + Scalar, if true then repeated labels are + collapsed prior to the CTC calculation. + ctc_merge_repeated: An optional `bool`. Defaults to `True`. + Scalar. If set to false, *during* CTC calculation + repeated non-blank labels will not be merged and are interpreted as + individual labels. This is a simplified version of CTC. + ignore_longer_outputs_than_inputs: An optional `bool`. Defaults to `False`. + Scalar. If set to true, during CTC + calculation, items that have longer output sequences than input sequences + are skipped: they don't contribute to the loss term and have zero-gradient. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (loss, gradient). + + loss: A `Tensor` of type `float32`. + gradient: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CTCLossV2", name, inputs, labels_indices, labels_values, + sequence_length, "preprocess_collapse_repeated", + preprocess_collapse_repeated, "ctc_merge_repeated", + ctc_merge_repeated, "ignore_longer_outputs_than_inputs", + ignore_longer_outputs_than_inputs) + _result = _CTCLossV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ctc_loss_v2_eager_fallback( + inputs, labels_indices, labels_values, sequence_length, + preprocess_collapse_repeated=preprocess_collapse_repeated, + ctc_merge_repeated=ctc_merge_repeated, + ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if preprocess_collapse_repeated is None: + preprocess_collapse_repeated = False + preprocess_collapse_repeated = _execute.make_bool(preprocess_collapse_repeated, "preprocess_collapse_repeated") + if ctc_merge_repeated is None: + ctc_merge_repeated = True + ctc_merge_repeated = _execute.make_bool(ctc_merge_repeated, "ctc_merge_repeated") + if ignore_longer_outputs_than_inputs is None: + ignore_longer_outputs_than_inputs = False + ignore_longer_outputs_than_inputs = _execute.make_bool(ignore_longer_outputs_than_inputs, "ignore_longer_outputs_than_inputs") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CTCLossV2", inputs=inputs, labels_indices=labels_indices, + labels_values=labels_values, + sequence_length=sequence_length, + preprocess_collapse_repeated=preprocess_collapse_repeated, + ctc_merge_repeated=ctc_merge_repeated, + ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("preprocess_collapse_repeated", + _op._get_attr_bool("preprocess_collapse_repeated"), + "ctc_merge_repeated", _op._get_attr_bool("ctc_merge_repeated"), + "ignore_longer_outputs_than_inputs", + _op._get_attr_bool("ignore_longer_outputs_than_inputs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CTCLossV2", _inputs_flat, _attrs, _result) + _result = _CTCLossV2Output._make(_result) + return _result + +CTCLossV2 = tf_export("raw_ops.CTCLossV2")(_ops.to_raw_op(ctc_loss_v2)) + + +def ctc_loss_v2_eager_fallback(inputs: Annotated[Any, _atypes.Float32], labels_indices: Annotated[Any, _atypes.Int64], labels_values: Annotated[Any, _atypes.Int32], sequence_length: Annotated[Any, _atypes.Int32], preprocess_collapse_repeated: bool, ctc_merge_repeated: bool, ignore_longer_outputs_than_inputs: bool, name, ctx): + if preprocess_collapse_repeated is None: + preprocess_collapse_repeated = False + preprocess_collapse_repeated = _execute.make_bool(preprocess_collapse_repeated, "preprocess_collapse_repeated") + if ctc_merge_repeated is None: + ctc_merge_repeated = True + ctc_merge_repeated = _execute.make_bool(ctc_merge_repeated, "ctc_merge_repeated") + if ignore_longer_outputs_than_inputs is None: + ignore_longer_outputs_than_inputs = False + ignore_longer_outputs_than_inputs = _execute.make_bool(ignore_longer_outputs_than_inputs, "ignore_longer_outputs_than_inputs") + inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) + labels_indices = _ops.convert_to_tensor(labels_indices, _dtypes.int64) + labels_values = _ops.convert_to_tensor(labels_values, _dtypes.int32) + sequence_length = _ops.convert_to_tensor(sequence_length, _dtypes.int32) + _inputs_flat = [inputs, labels_indices, labels_values, sequence_length] + _attrs = ("preprocess_collapse_repeated", preprocess_collapse_repeated, + "ctc_merge_repeated", ctc_merge_repeated, + "ignore_longer_outputs_than_inputs", ignore_longer_outputs_than_inputs) + _result = _execute.execute(b"CTCLossV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CTCLossV2", _inputs_flat, _attrs, _result) + _result = _CTCLossV2Output._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_cudnn_rnn_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_cudnn_rnn_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a24c7357e630f0590bfa3c33dd79a3db3b8d14d8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_cudnn_rnn_ops.py @@ -0,0 +1,2033 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_CudnnRNNOutput = collections.namedtuple( + "CudnnRNN", + ["output", "output_h", "output_c", "reserve_space"]) + + +TV_CudnnRNN_T = TypeVar("TV_CudnnRNN_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn(input: Annotated[Any, TV_CudnnRNN_T], input_h: Annotated[Any, TV_CudnnRNN_T], input_c: Annotated[Any, TV_CudnnRNN_T], params: Annotated[Any, TV_CudnnRNN_T], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, is_training:bool=True, name=None): + r"""A RNN backed by cuDNN. + + Computes the RNN from the input and initial states, with respect to the params + buffer. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. + input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, + num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + output: A 3-D tensor with the shape of [seq_length, batch_size, + dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + is_training: Indicates whether this operation is used for inference or + training. + reserve_space: An opaque tensor that can be used in backprop calculation. It + is only produced if is_training is false. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + is_training: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_h, output_c, reserve_space). + + output: A `Tensor`. Has the same type as `input`. + output_h: A `Tensor`. Has the same type as `input`. + output_c: A `Tensor`. Has the same type as `input`. + reserve_space: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNN", name, input, input_h, input_c, params, "rnn_mode", + rnn_mode, "input_mode", input_mode, "direction", direction, "dropout", + dropout, "seed", seed, "seed2", seed2, "is_training", is_training) + _result = _CudnnRNNOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_eager_fallback( + input, input_h, input_c, params, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, is_training=is_training, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNN", input=input, input_h=input_h, input_c=input_c, + params=params, rnn_mode=rnn_mode, input_mode=input_mode, + direction=direction, dropout=dropout, seed=seed, + seed2=seed2, is_training=is_training, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNN", _inputs_flat, _attrs, _result) + _result = _CudnnRNNOutput._make(_result) + return _result + +CudnnRNN = tf_export("raw_ops.CudnnRNN")(_ops.to_raw_op(cudnn_rnn)) + + +def cudnn_rnn_eager_fallback(input: Annotated[Any, TV_CudnnRNN_T], input_h: Annotated[Any, TV_CudnnRNN_T], input_c: Annotated[Any, TV_CudnnRNN_T], params: Annotated[Any, TV_CudnnRNN_T], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, is_training: bool, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params) = _inputs_T + _inputs_flat = [input, input_h, input_c, params] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "is_training", is_training) + _result = _execute.execute(b"CudnnRNN", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNN", _inputs_flat, _attrs, _result) + _result = _CudnnRNNOutput._make(_result) + return _result + +_CudnnRNNBackpropOutput = collections.namedtuple( + "CudnnRNNBackprop", + ["input_backprop", "input_h_backprop", "input_c_backprop", "params_backprop"]) + + +TV_CudnnRNNBackprop_T = TypeVar("TV_CudnnRNNBackprop_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_backprop(input: Annotated[Any, TV_CudnnRNNBackprop_T], input_h: Annotated[Any, TV_CudnnRNNBackprop_T], input_c: Annotated[Any, TV_CudnnRNNBackprop_T], params: Annotated[Any, TV_CudnnRNNBackprop_T], output: Annotated[Any, TV_CudnnRNNBackprop_T], output_h: Annotated[Any, TV_CudnnRNNBackprop_T], output_c: Annotated[Any, TV_CudnnRNNBackprop_T], output_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], reserve_space: Annotated[Any, TV_CudnnRNNBackprop_T], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, name=None): + r"""Backprop step of CudnnRNN. + + Compute the backprop of both data and weights in a RNN. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. + input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, + num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + output: A 3-D tensor with the shape of [seq_length, batch_size, + dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + output_backprop: A 3-D tensor with the same shape as output in the forward pass. + output_h_backprop: A 3-D tensor with the same shape as output_h in the forward + pass. + output_c_backprop: A 3-D tensor with the same shape as output_c in the forward + pass. + reserve_space: The same reserve_space produced in for forward operation. + input_backprop: The backprop to input in the forward pass. Has the same shape + as input. + input_h_backprop: The backprop to input_h in the forward pass. Has the same + shape as input_h. + input_c_backprop: The backprop to input_c in the forward pass. Has the same + shape as input_c. + params_backprop: The backprop to the params buffer in the forward pass. Has the + same shape as params. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + output: A `Tensor`. Must have the same type as `input`. + output_h: A `Tensor`. Must have the same type as `input`. + output_c: A `Tensor`. Must have the same type as `input`. + output_backprop: A `Tensor`. Must have the same type as `input`. + output_h_backprop: A `Tensor`. Must have the same type as `input`. + output_c_backprop: A `Tensor`. Must have the same type as `input`. + reserve_space: A `Tensor`. Must have the same type as `input`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (input_backprop, input_h_backprop, input_c_backprop, params_backprop). + + input_backprop: A `Tensor`. Has the same type as `input`. + input_h_backprop: A `Tensor`. Has the same type as `input`. + input_c_backprop: A `Tensor`. Has the same type as `input`. + params_backprop: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNBackprop", name, input, input_h, input_c, params, + output, output_h, output_c, output_backprop, output_h_backprop, + output_c_backprop, reserve_space, "rnn_mode", rnn_mode, "input_mode", + input_mode, "direction", direction, "dropout", dropout, "seed", seed, + "seed2", seed2) + _result = _CudnnRNNBackpropOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_backprop_eager_fallback( + input, input_h, input_c, params, output, output_h, output_c, + output_backprop, output_h_backprop, output_c_backprop, + reserve_space, rnn_mode=rnn_mode, input_mode=input_mode, + direction=direction, dropout=dropout, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNBackprop", input=input, input_h=input_h, input_c=input_c, + params=params, output=output, output_h=output_h, + output_c=output_c, + output_backprop=output_backprop, + output_h_backprop=output_h_backprop, + output_c_backprop=output_c_backprop, + reserve_space=reserve_space, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNBackprop", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropOutput._make(_result) + return _result + +CudnnRNNBackprop = tf_export("raw_ops.CudnnRNNBackprop")(_ops.to_raw_op(cudnn_rnn_backprop)) + + +def cudnn_rnn_backprop_eager_fallback(input: Annotated[Any, TV_CudnnRNNBackprop_T], input_h: Annotated[Any, TV_CudnnRNNBackprop_T], input_c: Annotated[Any, TV_CudnnRNNBackprop_T], params: Annotated[Any, TV_CudnnRNNBackprop_T], output: Annotated[Any, TV_CudnnRNNBackprop_T], output_h: Annotated[Any, TV_CudnnRNNBackprop_T], output_c: Annotated[Any, TV_CudnnRNNBackprop_T], output_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackprop_T], reserve_space: Annotated[Any, TV_CudnnRNNBackprop_T], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space) = _inputs_T + _inputs_flat = [input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"CudnnRNNBackprop", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNBackprop", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropOutput._make(_result) + return _result + +_CudnnRNNBackpropV2Output = collections.namedtuple( + "CudnnRNNBackpropV2", + ["input_backprop", "input_h_backprop", "input_c_backprop", "params_backprop"]) + + +TV_CudnnRNNBackpropV2_T = TypeVar("TV_CudnnRNNBackpropV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_backprop_v2(input: Annotated[Any, TV_CudnnRNNBackpropV2_T], input_h: Annotated[Any, TV_CudnnRNNBackpropV2_T], input_c: Annotated[Any, TV_CudnnRNNBackpropV2_T], params: Annotated[Any, TV_CudnnRNNBackpropV2_T], output: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_h: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_c: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], reserve_space: Annotated[Any, TV_CudnnRNNBackpropV2_T], host_reserved: Annotated[Any, _atypes.Int8], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, name=None): + r"""Backprop step of CudnnRNN. + + Compute the backprop of both data and weights in a RNN. Takes an extra + "host_reserved" inupt than CudnnRNNBackprop, which is used to determine RNN + cudnnRNNAlgo_t and cudnnMathType_t. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicates whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. + input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, + num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + output: A 3-D tensor with the shape of [seq_length, batch_size, + dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + output_backprop: A 3-D tensor with the same shape as output in the forward pass. + output_h_backprop: A 3-D tensor with the same shape as output_h in the forward + pass. + output_c_backprop: A 3-D tensor with the same shape as output_c in the forward + pass. + reserve_space: The same reserve_space produced in the forward operation. + host_reserved: The same host_reserved produced in the forward operation. + input_backprop: The backprop to input in the forward pass. Has the same shape + as input. + input_h_backprop: The backprop to input_h in the forward pass. Has the same + shape as input_h. + input_c_backprop: The backprop to input_c in the forward pass. Has the same + shape as input_c. + params_backprop: The backprop to the params buffer in the forward pass. Has the + same shape as params. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + output: A `Tensor`. Must have the same type as `input`. + output_h: A `Tensor`. Must have the same type as `input`. + output_c: A `Tensor`. Must have the same type as `input`. + output_backprop: A `Tensor`. Must have the same type as `input`. + output_h_backprop: A `Tensor`. Must have the same type as `input`. + output_c_backprop: A `Tensor`. Must have the same type as `input`. + reserve_space: A `Tensor`. Must have the same type as `input`. + host_reserved: A `Tensor` of type `int8`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (input_backprop, input_h_backprop, input_c_backprop, params_backprop). + + input_backprop: A `Tensor`. Has the same type as `input`. + input_h_backprop: A `Tensor`. Has the same type as `input`. + input_c_backprop: A `Tensor`. Has the same type as `input`. + params_backprop: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNBackpropV2", name, input, input_h, input_c, params, + output, output_h, output_c, output_backprop, output_h_backprop, + output_c_backprop, reserve_space, host_reserved, "rnn_mode", rnn_mode, + "input_mode", input_mode, "direction", direction, "dropout", dropout, + "seed", seed, "seed2", seed2) + _result = _CudnnRNNBackpropV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_backprop_v2_eager_fallback( + input, input_h, input_c, params, output, output_h, output_c, + output_backprop, output_h_backprop, output_c_backprop, + reserve_space, host_reserved, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNBackpropV2", input=input, input_h=input_h, input_c=input_c, + params=params, output=output, output_h=output_h, + output_c=output_c, + output_backprop=output_backprop, + output_h_backprop=output_h_backprop, + output_c_backprop=output_c_backprop, + reserve_space=reserve_space, + host_reserved=host_reserved, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNBackpropV2", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropV2Output._make(_result) + return _result + +CudnnRNNBackpropV2 = tf_export("raw_ops.CudnnRNNBackpropV2")(_ops.to_raw_op(cudnn_rnn_backprop_v2)) + + +def cudnn_rnn_backprop_v2_eager_fallback(input: Annotated[Any, TV_CudnnRNNBackpropV2_T], input_h: Annotated[Any, TV_CudnnRNNBackpropV2_T], input_c: Annotated[Any, TV_CudnnRNNBackpropV2_T], params: Annotated[Any, TV_CudnnRNNBackpropV2_T], output: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_h: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_c: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackpropV2_T], reserve_space: Annotated[Any, TV_CudnnRNNBackpropV2_T], host_reserved: Annotated[Any, _atypes.Int8], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space) = _inputs_T + host_reserved = _ops.convert_to_tensor(host_reserved, _dtypes.int8) + _inputs_flat = [input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space, host_reserved] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"CudnnRNNBackpropV2", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNBackpropV2", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropV2Output._make(_result) + return _result + +_CudnnRNNBackpropV3Output = collections.namedtuple( + "CudnnRNNBackpropV3", + ["input_backprop", "input_h_backprop", "input_c_backprop", "params_backprop"]) + + +TV_CudnnRNNBackpropV3_T = TypeVar("TV_CudnnRNNBackpropV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_backprop_v3(input: Annotated[Any, TV_CudnnRNNBackpropV3_T], input_h: Annotated[Any, TV_CudnnRNNBackpropV3_T], input_c: Annotated[Any, TV_CudnnRNNBackpropV3_T], params: Annotated[Any, TV_CudnnRNNBackpropV3_T], sequence_lengths: Annotated[Any, _atypes.Int32], output: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_h: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_c: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], reserve_space: Annotated[Any, TV_CudnnRNNBackpropV3_T], host_reserved: Annotated[Any, _atypes.Int8], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, num_proj:int=0, time_major:bool=True, name=None): + r"""Backprop step of CudnnRNNV3. + + Compute the backprop of both data and weights in a RNN. Takes an extra + "sequence_lengths" input than CudnnRNNBackprop. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicates whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: If time_major is true, this is a 3-D tensor with the shape of + [seq_length, batch_size, input_size]. If time_major is false, the shape is + [batch_size, seq_length, input_size]. + input_h: If time_major is true, this is a 3-D tensor with the shape of + [num_layer * dir, batch_size, num_units]. If time_major is false, the shape + is [batch_size, num_layer * dir, num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + sequence_lengths: a vector of lengths of each input sequence. + output: If time_major is true, this is a 3-D tensor with the shape of + [seq_length, batch_size, dir * num_units]. If time_major is false, the + shape is [batch_size, seq_length, dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + output_backprop: A 3-D tensor with the same shape as output in the forward pass. + output_h_backprop: A 3-D tensor with the same shape as output_h in the forward + pass. + output_c_backprop: A 3-D tensor with the same shape as output_c in the forward + pass. + time_major: Indicates whether the input/output format is time major or batch + major. + reserve_space: The same reserve_space produced in the forward operation. + input_backprop: The backprop to input in the forward pass. Has the same shape + as input. + input_h_backprop: The backprop to input_h in the forward pass. Has the same + shape as input_h. + input_c_backprop: The backprop to input_c in the forward pass. Has the same + shape as input_c. + params_backprop: The backprop to the params buffer in the forward pass. Has the + same shape as params. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + sequence_lengths: A `Tensor` of type `int32`. + output: A `Tensor`. Must have the same type as `input`. + output_h: A `Tensor`. Must have the same type as `input`. + output_c: A `Tensor`. Must have the same type as `input`. + output_backprop: A `Tensor`. Must have the same type as `input`. + output_h_backprop: A `Tensor`. Must have the same type as `input`. + output_c_backprop: A `Tensor`. Must have the same type as `input`. + reserve_space: A `Tensor`. Must have the same type as `input`. + host_reserved: A `Tensor` of type `int8`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + num_proj: An optional `int`. Defaults to `0`. + time_major: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (input_backprop, input_h_backprop, input_c_backprop, params_backprop). + + input_backprop: A `Tensor`. Has the same type as `input`. + input_h_backprop: A `Tensor`. Has the same type as `input`. + input_c_backprop: A `Tensor`. Has the same type as `input`. + params_backprop: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNBackpropV3", name, input, input_h, input_c, params, + sequence_lengths, output, output_h, output_c, output_backprop, + output_h_backprop, output_c_backprop, reserve_space, host_reserved, + "rnn_mode", rnn_mode, "input_mode", input_mode, "direction", + direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "num_proj", num_proj, "time_major", time_major) + _result = _CudnnRNNBackpropV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_backprop_v3_eager_fallback( + input, input_h, input_c, params, sequence_lengths, output, output_h, + output_c, output_backprop, output_h_backprop, output_c_backprop, + reserve_space, host_reserved, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, num_proj=num_proj, time_major=time_major, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + if time_major is None: + time_major = True + time_major = _execute.make_bool(time_major, "time_major") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNBackpropV3", input=input, input_h=input_h, input_c=input_c, + params=params, + sequence_lengths=sequence_lengths, + output=output, output_h=output_h, + output_c=output_c, + output_backprop=output_backprop, + output_h_backprop=output_h_backprop, + output_c_backprop=output_c_backprop, + reserve_space=reserve_space, + host_reserved=host_reserved, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, + num_proj=num_proj, time_major=time_major, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "num_proj", + _op._get_attr_int("num_proj"), "time_major", + _op._get_attr_bool("time_major")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNBackpropV3", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropV3Output._make(_result) + return _result + +CudnnRNNBackpropV3 = tf_export("raw_ops.CudnnRNNBackpropV3")(_ops.to_raw_op(cudnn_rnn_backprop_v3)) + + +def cudnn_rnn_backprop_v3_eager_fallback(input: Annotated[Any, TV_CudnnRNNBackpropV3_T], input_h: Annotated[Any, TV_CudnnRNNBackpropV3_T], input_c: Annotated[Any, TV_CudnnRNNBackpropV3_T], params: Annotated[Any, TV_CudnnRNNBackpropV3_T], sequence_lengths: Annotated[Any, _atypes.Int32], output: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_h: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_c: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_h_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], output_c_backprop: Annotated[Any, TV_CudnnRNNBackpropV3_T], reserve_space: Annotated[Any, TV_CudnnRNNBackpropV3_T], host_reserved: Annotated[Any, _atypes.Int8], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, num_proj: int, time_major: bool, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + if time_major is None: + time_major = True + time_major = _execute.make_bool(time_major, "time_major") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space) = _inputs_T + sequence_lengths = _ops.convert_to_tensor(sequence_lengths, _dtypes.int32) + host_reserved = _ops.convert_to_tensor(host_reserved, _dtypes.int8) + _inputs_flat = [input, input_h, input_c, params, sequence_lengths, output, output_h, output_c, output_backprop, output_h_backprop, output_c_backprop, reserve_space, host_reserved] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "num_proj", num_proj, "time_major", time_major) + _result = _execute.execute(b"CudnnRNNBackpropV3", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNBackpropV3", _inputs_flat, _attrs, _result) + _result = _CudnnRNNBackpropV3Output._make(_result) + return _result + + +TV_CudnnRNNCanonicalToParams_T = TypeVar("TV_CudnnRNNCanonicalToParams_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_canonical_to_params(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], weights: Annotated[List[Any], TV_CudnnRNNCanonicalToParams_T], biases: Annotated[List[Any], TV_CudnnRNNCanonicalToParams_T], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_CudnnRNNCanonicalToParams_T]: + r"""Converts CudnnRNN params from canonical form to usable form. + + Writes a set of weights into the opaque params buffer so they can be used in + upcoming training or inferences. + + Note that the params buffer may not be compatible across different GPUs. So any + save and restoration should be converted to and from the canonical weights and + biases. + + num_layers: Specifies the number of layers in the RNN model. + num_units: Specifies the size of the hidden state. + input_size: Specifies the size of the input state. + weights: the canonical form of weights that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + biases: the canonical form of biases that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + num_params: number of parameter sets for all layers. + Each layer may contain multiple parameter sets, with each set consisting of + a weight matrix and a bias vector. + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + The actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. + dir = (direction == bidirectional) ? 2 : 1 + dropout: dropout probability. When set to 0., dropout is disabled. + seed: the 1st part of a seed to initialize dropout. + seed2: the 2nd part of a seed to initialize dropout. + + Args: + num_layers: A `Tensor` of type `int32`. + num_units: A `Tensor` of type `int32`. + input_size: A `Tensor` of type `int32`. + weights: A list of at least 1 `Tensor` objects with the same type in: `bfloat16`, `half`, `float32`, `float64`. + biases: A list with the same length as `weights` of `Tensor` objects with the same type as `weights`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNCanonicalToParams", name, num_layers, num_units, + input_size, weights, biases, "rnn_mode", rnn_mode, "input_mode", + input_mode, "direction", direction, "dropout", dropout, "seed", seed, + "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_canonical_to_params_eager_fallback( + num_layers, num_units, input_size, weights, biases, + rnn_mode=rnn_mode, input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(weights, (list, tuple)): + raise TypeError( + "Expected list for 'weights' argument to " + "'cudnn_rnn_canonical_to_params' Op, not %r." % weights) + _attr_num_params = len(weights) + if not isinstance(biases, (list, tuple)): + raise TypeError( + "Expected list for 'biases' argument to " + "'cudnn_rnn_canonical_to_params' Op, not %r." % biases) + if len(biases) != _attr_num_params: + raise ValueError( + "List argument 'biases' to 'cudnn_rnn_canonical_to_params' Op with length %d " + "must match length %d of argument 'weights'." % + (len(biases), _attr_num_params)) + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNCanonicalToParams", num_layers=num_layers, + num_units=num_units, + input_size=input_size, weights=weights, + biases=biases, rnn_mode=rnn_mode, + input_mode=input_mode, + direction=direction, dropout=dropout, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_params", + _op._get_attr_int("num_params"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNCanonicalToParams", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CudnnRNNCanonicalToParams = tf_export("raw_ops.CudnnRNNCanonicalToParams")(_ops.to_raw_op(cudnn_rnn_canonical_to_params)) + + +def cudnn_rnn_canonical_to_params_eager_fallback(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], weights: Annotated[List[Any], TV_CudnnRNNCanonicalToParams_T], biases: Annotated[List[Any], TV_CudnnRNNCanonicalToParams_T], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_CudnnRNNCanonicalToParams_T]: + if not isinstance(weights, (list, tuple)): + raise TypeError( + "Expected list for 'weights' argument to " + "'cudnn_rnn_canonical_to_params' Op, not %r." % weights) + _attr_num_params = len(weights) + if not isinstance(biases, (list, tuple)): + raise TypeError( + "Expected list for 'biases' argument to " + "'cudnn_rnn_canonical_to_params' Op, not %r." % biases) + if len(biases) != _attr_num_params: + raise ValueError( + "List argument 'biases' to 'cudnn_rnn_canonical_to_params' Op with length %d " + "must match length %d of argument 'weights'." % + (len(biases), _attr_num_params)) + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, _inputs_T = _execute.args_to_matching_eager(list(weights) + list(biases), ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_T = [_inputs_T[:_attr_num_params]] + _inputs_T[_attr_num_params:] + _inputs_T = _inputs_T[:1] + [_inputs_T[1:]] + (weights, biases) = _inputs_T + num_layers = _ops.convert_to_tensor(num_layers, _dtypes.int32) + num_units = _ops.convert_to_tensor(num_units, _dtypes.int32) + input_size = _ops.convert_to_tensor(input_size, _dtypes.int32) + _inputs_flat = [num_layers, num_units, input_size] + list(weights) + list(biases) + _attrs = ("T", _attr_T, "num_params", _attr_num_params, "rnn_mode", + rnn_mode, "input_mode", input_mode, "direction", direction, "dropout", + dropout, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"CudnnRNNCanonicalToParams", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNCanonicalToParams", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CudnnRNNCanonicalToParamsV2_T = TypeVar("TV_CudnnRNNCanonicalToParamsV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_canonical_to_params_v2(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], weights: Annotated[List[Any], TV_CudnnRNNCanonicalToParamsV2_T], biases: Annotated[List[Any], TV_CudnnRNNCanonicalToParamsV2_T], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, num_proj:int=0, name=None) -> Annotated[Any, TV_CudnnRNNCanonicalToParamsV2_T]: + r"""Converts CudnnRNN params from canonical form to usable form. It supports the projection in LSTM. + + Writes a set of weights into the opaque params buffer so they can be used in + upcoming training or inferences. + + Note that the params buffer may not be compatible across different GPUs. So any + save and restoration should be converted to and from the canonical weights and + biases. + + num_layers: Specifies the number of layers in the RNN model. + num_units: Specifies the size of the hidden state. + input_size: Specifies the size of the input state. + weights: the canonical form of weights that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + biases: the canonical form of biases that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + num_params_weights: number of weight parameter matrix for all layers. + num_params_biases: number of bias parameter vector for all layers. + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + The actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. + dir = (direction == bidirectional) ? 2 : 1 + dropout: dropout probability. When set to 0., dropout is disabled. + seed: the 1st part of a seed to initialize dropout. + seed2: the 2nd part of a seed to initialize dropout. + num_proj: The output dimensionality for the projection matrices. If None or 0, + no projection is performed. + + Args: + num_layers: A `Tensor` of type `int32`. + num_units: A `Tensor` of type `int32`. + input_size: A `Tensor` of type `int32`. + weights: A list of at least 1 `Tensor` objects with the same type in: `bfloat16`, `half`, `float32`, `float64`. + biases: A list of at least 1 `Tensor` objects with the same type as `weights`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + num_proj: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNCanonicalToParamsV2", name, num_layers, num_units, + input_size, weights, biases, "rnn_mode", rnn_mode, "input_mode", + input_mode, "direction", direction, "dropout", dropout, "seed", seed, + "seed2", seed2, "num_proj", num_proj) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_canonical_to_params_v2_eager_fallback( + num_layers, num_units, input_size, weights, biases, + rnn_mode=rnn_mode, input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, num_proj=num_proj, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(weights, (list, tuple)): + raise TypeError( + "Expected list for 'weights' argument to " + "'cudnn_rnn_canonical_to_params_v2' Op, not %r." % weights) + _attr_num_params_weights = len(weights) + if not isinstance(biases, (list, tuple)): + raise TypeError( + "Expected list for 'biases' argument to " + "'cudnn_rnn_canonical_to_params_v2' Op, not %r." % biases) + _attr_num_params_biases = len(biases) + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNCanonicalToParamsV2", num_layers=num_layers, + num_units=num_units, + input_size=input_size, weights=weights, + biases=biases, rnn_mode=rnn_mode, + input_mode=input_mode, + direction=direction, dropout=dropout, + seed=seed, seed2=seed2, + num_proj=num_proj, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_params_weights", + _op._get_attr_int("num_params_weights"), "num_params_biases", + _op._get_attr_int("num_params_biases"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "num_proj", + _op._get_attr_int("num_proj")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNCanonicalToParamsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CudnnRNNCanonicalToParamsV2 = tf_export("raw_ops.CudnnRNNCanonicalToParamsV2")(_ops.to_raw_op(cudnn_rnn_canonical_to_params_v2)) + + +def cudnn_rnn_canonical_to_params_v2_eager_fallback(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], weights: Annotated[List[Any], TV_CudnnRNNCanonicalToParamsV2_T], biases: Annotated[List[Any], TV_CudnnRNNCanonicalToParamsV2_T], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, num_proj: int, name, ctx) -> Annotated[Any, TV_CudnnRNNCanonicalToParamsV2_T]: + if not isinstance(weights, (list, tuple)): + raise TypeError( + "Expected list for 'weights' argument to " + "'cudnn_rnn_canonical_to_params_v2' Op, not %r." % weights) + _attr_num_params_weights = len(weights) + if not isinstance(biases, (list, tuple)): + raise TypeError( + "Expected list for 'biases' argument to " + "'cudnn_rnn_canonical_to_params_v2' Op, not %r." % biases) + _attr_num_params_biases = len(biases) + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + _attr_T, _inputs_T = _execute.args_to_matching_eager(list(weights) + list(biases), ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_T = [_inputs_T[:_attr_num_params_weights]] + _inputs_T[_attr_num_params_weights:] + _inputs_T = _inputs_T[:1] + [_inputs_T[1:]] + (weights, biases) = _inputs_T + num_layers = _ops.convert_to_tensor(num_layers, _dtypes.int32) + num_units = _ops.convert_to_tensor(num_units, _dtypes.int32) + input_size = _ops.convert_to_tensor(input_size, _dtypes.int32) + _inputs_flat = [num_layers, num_units, input_size] + list(weights) + list(biases) + _attrs = ("T", _attr_T, "num_params_weights", _attr_num_params_weights, + "num_params_biases", _attr_num_params_biases, "rnn_mode", rnn_mode, + "input_mode", input_mode, "direction", direction, "dropout", dropout, + "seed", seed, "seed2", seed2, "num_proj", num_proj) + _result = _execute.execute(b"CudnnRNNCanonicalToParamsV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNCanonicalToParamsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CudnnRNNParamsSize_T = TypeVar("TV_CudnnRNNParamsSize_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_CudnnRNNParamsSize_S = TypeVar("TV_CudnnRNNParamsSize_S", _atypes.Int32, _atypes.Int64) + +def cudnn_rnn_params_size(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], T: TV_CudnnRNNParamsSize_T, S: TV_CudnnRNNParamsSize_S, rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, num_proj:int=0, name=None) -> Annotated[Any, TV_CudnnRNNParamsSize_S]: + r"""Computes size of weights that can be used by a Cudnn RNN model. + + Return the params size that can be used by the Cudnn RNN model. Subsequent + weight allocation and initialization should use this size. + + num_layers: Specifies the number of layers in the RNN model. + num_units: Specifies the size of the hidden state. + input_size: Specifies the size of the input state. + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + The actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. + dir = (direction == bidirectional) ? 2 : 1 + dropout: dropout probability. When set to 0., dropout is disabled. + seed: the 1st part of a seed to initialize dropout. + seed2: the 2nd part of a seed to initialize dropout. + params_size: The size of the params buffer that should be allocated and + initialized for this RNN model. Note that this params buffer may not be + compatible across GPUs. Please use CudnnRNNParamsWeights and + CudnnRNNParamsBiases to save and restore them in a way that is compatible + across different runs. + + Args: + num_layers: A `Tensor` of type `int32`. + num_units: A `Tensor` of type `int32`. + input_size: A `Tensor` of type `int32`. + T: A `tf.DType` from: `tf.bfloat16, tf.half, tf.float32, tf.float64`. + S: A `tf.DType` from: `tf.int32, tf.int64`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + num_proj: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `S`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNParamsSize", name, num_layers, num_units, input_size, + "T", T, "S", S, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", + seed2, "num_proj", num_proj) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_params_size_eager_fallback( + num_layers, num_units, input_size, T=T, S=S, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, num_proj=num_proj, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + S = _execute.make_type(S, "S") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNParamsSize", num_layers=num_layers, num_units=num_units, + input_size=input_size, T=T, S=S, + rnn_mode=rnn_mode, input_mode=input_mode, + direction=direction, dropout=dropout, seed=seed, + seed2=seed2, num_proj=num_proj, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "S", _op._get_attr_type("S"), + "rnn_mode", _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "num_proj", + _op._get_attr_int("num_proj")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNParamsSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CudnnRNNParamsSize = tf_export("raw_ops.CudnnRNNParamsSize")(_ops.to_raw_op(cudnn_rnn_params_size)) + + +def cudnn_rnn_params_size_eager_fallback(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], T: TV_CudnnRNNParamsSize_T, S: TV_CudnnRNNParamsSize_S, rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, num_proj: int, name, ctx) -> Annotated[Any, TV_CudnnRNNParamsSize_S]: + T = _execute.make_type(T, "T") + S = _execute.make_type(S, "S") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + num_layers = _ops.convert_to_tensor(num_layers, _dtypes.int32) + num_units = _ops.convert_to_tensor(num_units, _dtypes.int32) + input_size = _ops.convert_to_tensor(input_size, _dtypes.int32) + _inputs_flat = [num_layers, num_units, input_size] + _attrs = ("T", T, "S", S, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "num_proj", num_proj) + _result = _execute.execute(b"CudnnRNNParamsSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNParamsSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_CudnnRNNParamsToCanonicalOutput = collections.namedtuple( + "CudnnRNNParamsToCanonical", + ["weights", "biases"]) + + +TV_CudnnRNNParamsToCanonical_T = TypeVar("TV_CudnnRNNParamsToCanonical_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_params_to_canonical(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], params: Annotated[Any, TV_CudnnRNNParamsToCanonical_T], num_params: int, rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, name=None): + r"""Retrieves CudnnRNN params in canonical form. + + Retrieves a set of weights from the opaque params buffer that can be saved and + restored in a way compatible with future runs. + + Note that the params buffer may not be compatible across different GPUs. So any + save and restoration should be converted to and from the canonical weights and + biases. + + num_layers: Specifies the number of layers in the RNN model. + num_units: Specifies the size of the hidden state. + input_size: Specifies the size of the input state. + num_params: number of parameter sets for all layers. + Each layer may contain multiple parameter sets, with each set consisting of + a weight matrix and a bias vector. + weights: the canonical form of weights that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + biases: the canonical form of biases that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + The actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. + dir = (direction == bidirectional) ? 2 : 1 + dropout: dropout probability. When set to 0., dropout is disabled. + seed: the 1st part of a seed to initialize dropout. + seed2: the 2nd part of a seed to initialize dropout. + + Args: + num_layers: A `Tensor` of type `int32`. + num_units: A `Tensor` of type `int32`. + input_size: A `Tensor` of type `int32`. + params: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + num_params: An `int` that is `>= 1`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (weights, biases). + + weights: A list of `num_params` `Tensor` objects with the same type as `params`. + biases: A list of `num_params` `Tensor` objects with the same type as `params`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNParamsToCanonical", name, num_layers, num_units, + input_size, params, "num_params", num_params, "rnn_mode", rnn_mode, + "input_mode", input_mode, "direction", direction, "dropout", dropout, + "seed", seed, "seed2", seed2) + _result = _CudnnRNNParamsToCanonicalOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_params_to_canonical_eager_fallback( + num_layers, num_units, input_size, params, num_params=num_params, + rnn_mode=rnn_mode, input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_params = _execute.make_int(num_params, "num_params") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNParamsToCanonical", num_layers=num_layers, + num_units=num_units, + input_size=input_size, params=params, + num_params=num_params, rnn_mode=rnn_mode, + input_mode=input_mode, + direction=direction, dropout=dropout, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_params", + _op._get_attr_int("num_params"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNParamsToCanonical", _inputs_flat, _attrs, _result) + _result = [_result[:num_params]] + _result[num_params:] + _result = _result[:1] + [_result[1:]] + _result = _CudnnRNNParamsToCanonicalOutput._make(_result) + return _result + +CudnnRNNParamsToCanonical = tf_export("raw_ops.CudnnRNNParamsToCanonical")(_ops.to_raw_op(cudnn_rnn_params_to_canonical)) + + +def cudnn_rnn_params_to_canonical_eager_fallback(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], params: Annotated[Any, TV_CudnnRNNParamsToCanonical_T], num_params: int, rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, name, ctx): + num_params = _execute.make_int(num_params, "num_params") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (params,) = _execute.args_to_matching_eager([params], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + num_layers = _ops.convert_to_tensor(num_layers, _dtypes.int32) + num_units = _ops.convert_to_tensor(num_units, _dtypes.int32) + input_size = _ops.convert_to_tensor(input_size, _dtypes.int32) + _inputs_flat = [num_layers, num_units, input_size, params] + _attrs = ("T", _attr_T, "num_params", num_params, "rnn_mode", rnn_mode, + "input_mode", input_mode, "direction", direction, "dropout", dropout, + "seed", seed, "seed2", seed2) + _result = _execute.execute(b"CudnnRNNParamsToCanonical", num_params + + num_params, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNParamsToCanonical", _inputs_flat, _attrs, _result) + _result = [_result[:num_params]] + _result[num_params:] + _result = _result[:1] + [_result[1:]] + _result = _CudnnRNNParamsToCanonicalOutput._make(_result) + return _result + +_CudnnRNNParamsToCanonicalV2Output = collections.namedtuple( + "CudnnRNNParamsToCanonicalV2", + ["weights", "biases"]) + + +TV_CudnnRNNParamsToCanonicalV2_T = TypeVar("TV_CudnnRNNParamsToCanonicalV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnn_params_to_canonical_v2(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], params: Annotated[Any, TV_CudnnRNNParamsToCanonicalV2_T], num_params_weights: int, num_params_biases: int, rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, num_proj:int=0, name=None): + r"""Retrieves CudnnRNN params in canonical form. It supports the projection in LSTM. + + Retrieves a set of weights from the opaque params buffer that can be saved and + restored in a way compatible with future runs. + + Note that the params buffer may not be compatible across different GPUs. So any + save and restoration should be converted to and from the canonical weights and + biases. + + num_layers: Specifies the number of layers in the RNN model. + num_units: Specifies the size of the hidden state. + input_size: Specifies the size of the input state. + num_params_weights: number of weight parameter matrix for all layers. + num_params_biases: number of bias parameter vector for all layers. + weights: the canonical form of weights that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + biases: the canonical form of biases that can be used for saving + and restoration. They are more likely to be compatible across different + generations. + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicate whether there is a linear projection between the input and + The actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. + dir = (direction == bidirectional) ? 2 : 1 + dropout: dropout probability. When set to 0., dropout is disabled. + seed: the 1st part of a seed to initialize dropout. + seed2: the 2nd part of a seed to initialize dropout. + num_proj: The output dimensionality for the projection matrices. If None or 0, + no projection is performed. + + Args: + num_layers: A `Tensor` of type `int32`. + num_units: A `Tensor` of type `int32`. + input_size: A `Tensor` of type `int32`. + params: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + num_params_weights: An `int` that is `>= 1`. + num_params_biases: An `int` that is `>= 1`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + num_proj: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (weights, biases). + + weights: A list of `num_params_weights` `Tensor` objects with the same type as `params`. + biases: A list of `num_params_biases` `Tensor` objects with the same type as `params`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNParamsToCanonicalV2", name, num_layers, num_units, + input_size, params, "num_params_weights", num_params_weights, + "num_params_biases", num_params_biases, "rnn_mode", rnn_mode, + "input_mode", input_mode, "direction", direction, "dropout", dropout, + "seed", seed, "seed2", seed2, "num_proj", num_proj) + _result = _CudnnRNNParamsToCanonicalV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnn_params_to_canonical_v2_eager_fallback( + num_layers, num_units, input_size, params, + num_params_weights=num_params_weights, + num_params_biases=num_params_biases, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, num_proj=num_proj, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_params_weights = _execute.make_int(num_params_weights, "num_params_weights") + num_params_biases = _execute.make_int(num_params_biases, "num_params_biases") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNParamsToCanonicalV2", num_layers=num_layers, + num_units=num_units, + input_size=input_size, params=params, + num_params_weights=num_params_weights, + num_params_biases=num_params_biases, + rnn_mode=rnn_mode, + input_mode=input_mode, + direction=direction, dropout=dropout, + seed=seed, seed2=seed2, + num_proj=num_proj, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_params_weights", + _op._get_attr_int("num_params_weights"), "num_params_biases", + _op._get_attr_int("num_params_biases"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "num_proj", + _op._get_attr_int("num_proj")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNParamsToCanonicalV2", _inputs_flat, _attrs, _result) + _result = [_result[:num_params_weights]] + _result[num_params_weights:] + _result = _result[:1] + [_result[1:]] + _result = _CudnnRNNParamsToCanonicalV2Output._make(_result) + return _result + +CudnnRNNParamsToCanonicalV2 = tf_export("raw_ops.CudnnRNNParamsToCanonicalV2")(_ops.to_raw_op(cudnn_rnn_params_to_canonical_v2)) + + +def cudnn_rnn_params_to_canonical_v2_eager_fallback(num_layers: Annotated[Any, _atypes.Int32], num_units: Annotated[Any, _atypes.Int32], input_size: Annotated[Any, _atypes.Int32], params: Annotated[Any, TV_CudnnRNNParamsToCanonicalV2_T], num_params_weights: int, num_params_biases: int, rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, num_proj: int, name, ctx): + num_params_weights = _execute.make_int(num_params_weights, "num_params_weights") + num_params_biases = _execute.make_int(num_params_biases, "num_params_biases") + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + _attr_T, (params,) = _execute.args_to_matching_eager([params], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + num_layers = _ops.convert_to_tensor(num_layers, _dtypes.int32) + num_units = _ops.convert_to_tensor(num_units, _dtypes.int32) + input_size = _ops.convert_to_tensor(input_size, _dtypes.int32) + _inputs_flat = [num_layers, num_units, input_size, params] + _attrs = ("T", _attr_T, "num_params_weights", num_params_weights, + "num_params_biases", num_params_biases, "rnn_mode", rnn_mode, "input_mode", + input_mode, "direction", direction, "dropout", dropout, "seed", seed, + "seed2", seed2, "num_proj", num_proj) + _result = _execute.execute(b"CudnnRNNParamsToCanonicalV2", + num_params_weights + num_params_biases, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNParamsToCanonicalV2", _inputs_flat, _attrs, _result) + _result = [_result[:num_params_weights]] + _result[num_params_weights:] + _result = _result[:1] + [_result[1:]] + _result = _CudnnRNNParamsToCanonicalV2Output._make(_result) + return _result + +_CudnnRNNV2Output = collections.namedtuple( + "CudnnRNNV2", + ["output", "output_h", "output_c", "reserve_space", "host_reserved"]) + + +TV_CudnnRNNV2_T = TypeVar("TV_CudnnRNNV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnnv2(input: Annotated[Any, TV_CudnnRNNV2_T], input_h: Annotated[Any, TV_CudnnRNNV2_T], input_c: Annotated[Any, TV_CudnnRNNV2_T], params: Annotated[Any, TV_CudnnRNNV2_T], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, is_training:bool=True, name=None): + r"""A RNN backed by cuDNN. + + Computes the RNN from the input and initial states, with respect to the params + buffer. Produces one extra output "host_reserved" than CudnnRNN. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicates whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: A 3-D tensor with the shape of [seq_length, batch_size, input_size]. + input_h: A 3-D tensor with the shape of [num_layer * dir, batch_size, + num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + output: A 3-D tensor with the shape of [seq_length, batch_size, + dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + is_training: Indicates whether this operation is used for inference or + training. + reserve_space: An opaque tensor that can be used in backprop calculation. It + is only produced if is_training is true. + host_reserved: An opaque tensor that can be used in backprop calculation. It is + only produced if is_training is true. It is output on host memory rather than + device memory. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + is_training: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_h, output_c, reserve_space, host_reserved). + + output: A `Tensor`. Has the same type as `input`. + output_h: A `Tensor`. Has the same type as `input`. + output_c: A `Tensor`. Has the same type as `input`. + reserve_space: A `Tensor`. Has the same type as `input`. + host_reserved: A `Tensor` of type `int8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNV2", name, input, input_h, input_c, params, "rnn_mode", + rnn_mode, "input_mode", input_mode, "direction", direction, "dropout", + dropout, "seed", seed, "seed2", seed2, "is_training", is_training) + _result = _CudnnRNNV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnnv2_eager_fallback( + input, input_h, input_c, params, rnn_mode=rnn_mode, + input_mode=input_mode, direction=direction, dropout=dropout, + seed=seed, seed2=seed2, is_training=is_training, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNV2", input=input, input_h=input_h, input_c=input_c, + params=params, rnn_mode=rnn_mode, input_mode=input_mode, + direction=direction, dropout=dropout, seed=seed, + seed2=seed2, is_training=is_training, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNV2", _inputs_flat, _attrs, _result) + _result = _CudnnRNNV2Output._make(_result) + return _result + +CudnnRNNV2 = tf_export("raw_ops.CudnnRNNV2")(_ops.to_raw_op(cudnn_rnnv2)) + + +def cudnn_rnnv2_eager_fallback(input: Annotated[Any, TV_CudnnRNNV2_T], input_h: Annotated[Any, TV_CudnnRNNV2_T], input_c: Annotated[Any, TV_CudnnRNNV2_T], params: Annotated[Any, TV_CudnnRNNV2_T], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, is_training: bool, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params) = _inputs_T + _inputs_flat = [input, input_h, input_c, params] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "is_training", is_training) + _result = _execute.execute(b"CudnnRNNV2", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNV2", _inputs_flat, _attrs, _result) + _result = _CudnnRNNV2Output._make(_result) + return _result + +_CudnnRNNV3Output = collections.namedtuple( + "CudnnRNNV3", + ["output", "output_h", "output_c", "reserve_space", "host_reserved"]) + + +TV_CudnnRNNV3_T = TypeVar("TV_CudnnRNNV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cudnn_rnnv3(input: Annotated[Any, TV_CudnnRNNV3_T], input_h: Annotated[Any, TV_CudnnRNNV3_T], input_c: Annotated[Any, TV_CudnnRNNV3_T], params: Annotated[Any, TV_CudnnRNNV3_T], sequence_lengths: Annotated[Any, _atypes.Int32], rnn_mode:str="lstm", input_mode:str="linear_input", direction:str="unidirectional", dropout:float=0, seed:int=0, seed2:int=0, num_proj:int=0, is_training:bool=True, time_major:bool=True, name=None): + r"""A RNN backed by cuDNN. + + Computes the RNN from the input and initial states, with respect to the params + buffer. Accepts one extra input "sequence_lengths" than CudnnRNN. + + rnn_mode: Indicates the type of the RNN model. + input_mode: Indicates whether there is a linear projection between the input and + the actual computation before the first layer. 'skip_input' is only allowed + when input_size == num_units; 'auto_select' implies 'skip_input' when + input_size == num_units; otherwise, it implies 'linear_input'. + direction: Indicates whether a bidirectional model will be used. Should be + "unidirectional" or "bidirectional". + dropout: Dropout probability. When set to 0., dropout is disabled. + seed: The 1st part of a seed to initialize dropout. + seed2: The 2nd part of a seed to initialize dropout. + input: If time_major is true, this is a 3-D tensor with the shape of + [seq_length, batch_size, input_size]. If time_major is false, the shape is + [batch_size, seq_length, input_size]. + input_h: If time_major is true, this is a 3-D tensor with the shape of + [num_layer * dir, batch_size, num_units]. If time_major is false, the shape + is [batch_size, num_layer * dir, num_units]. + input_c: For LSTM, a 3-D tensor with the shape of + [num_layer * dir, batch, num_units]. For other models, it is ignored. + params: A 1-D tensor that contains the weights and biases in an opaque layout. + The size must be created through CudnnRNNParamsSize, and initialized + separately. Note that they might not be compatible across different + generations. So it is a good idea to save and restore + sequence_lengths: a vector of lengths of each input sequence. + output: If time_major is true, this is a 3-D tensor with the shape of + [seq_length, batch_size, dir * num_units]. If time_major is false, the + shape is [batch_size, seq_length, dir * num_units]. + output_h: The same shape has input_h. + output_c: The same shape as input_c for LSTM. An empty tensor for other models. + is_training: Indicates whether this operation is used for inference or + training. + time_major: Indicates whether the input/output format is time major or batch + major. + reserve_space: An opaque tensor that can be used in backprop calculation. It + is only produced if is_training is true. + + Args: + input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + input_h: A `Tensor`. Must have the same type as `input`. + input_c: A `Tensor`. Must have the same type as `input`. + params: A `Tensor`. Must have the same type as `input`. + sequence_lengths: A `Tensor` of type `int32`. + rnn_mode: An optional `string` from: `"rnn_relu", "rnn_tanh", "lstm", "gru"`. Defaults to `"lstm"`. + input_mode: An optional `string` from: `"linear_input", "skip_input", "auto_select"`. Defaults to `"linear_input"`. + direction: An optional `string` from: `"unidirectional", "bidirectional"`. Defaults to `"unidirectional"`. + dropout: An optional `float`. Defaults to `0`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + num_proj: An optional `int`. Defaults to `0`. + is_training: An optional `bool`. Defaults to `True`. + time_major: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_h, output_c, reserve_space, host_reserved). + + output: A `Tensor`. Has the same type as `input`. + output_h: A `Tensor`. Has the same type as `input`. + output_c: A `Tensor`. Has the same type as `input`. + reserve_space: A `Tensor`. Has the same type as `input`. + host_reserved: A `Tensor` of type `int8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CudnnRNNV3", name, input, input_h, input_c, params, + sequence_lengths, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", + seed2, "num_proj", num_proj, "is_training", is_training, "time_major", + time_major) + _result = _CudnnRNNV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cudnn_rnnv3_eager_fallback( + input, input_h, input_c, params, sequence_lengths, + rnn_mode=rnn_mode, input_mode=input_mode, direction=direction, + dropout=dropout, seed=seed, seed2=seed2, num_proj=num_proj, + is_training=is_training, time_major=time_major, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + if time_major is None: + time_major = True + time_major = _execute.make_bool(time_major, "time_major") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CudnnRNNV3", input=input, input_h=input_h, input_c=input_c, + params=params, sequence_lengths=sequence_lengths, + rnn_mode=rnn_mode, input_mode=input_mode, + direction=direction, dropout=dropout, seed=seed, + seed2=seed2, num_proj=num_proj, is_training=is_training, + time_major=time_major, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "rnn_mode", + _op.get_attr("rnn_mode"), "input_mode", + _op.get_attr("input_mode"), "direction", + _op.get_attr("direction"), "dropout", _op.get_attr("dropout"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "num_proj", + _op._get_attr_int("num_proj"), "is_training", + _op._get_attr_bool("is_training"), "time_major", + _op._get_attr_bool("time_major")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CudnnRNNV3", _inputs_flat, _attrs, _result) + _result = _CudnnRNNV3Output._make(_result) + return _result + +CudnnRNNV3 = tf_export("raw_ops.CudnnRNNV3")(_ops.to_raw_op(cudnn_rnnv3)) + + +def cudnn_rnnv3_eager_fallback(input: Annotated[Any, TV_CudnnRNNV3_T], input_h: Annotated[Any, TV_CudnnRNNV3_T], input_c: Annotated[Any, TV_CudnnRNNV3_T], params: Annotated[Any, TV_CudnnRNNV3_T], sequence_lengths: Annotated[Any, _atypes.Int32], rnn_mode: str, input_mode: str, direction: str, dropout: float, seed: int, seed2: int, num_proj: int, is_training: bool, time_major: bool, name, ctx): + if rnn_mode is None: + rnn_mode = "lstm" + rnn_mode = _execute.make_str(rnn_mode, "rnn_mode") + if input_mode is None: + input_mode = "linear_input" + input_mode = _execute.make_str(input_mode, "input_mode") + if direction is None: + direction = "unidirectional" + direction = _execute.make_str(direction, "direction") + if dropout is None: + dropout = 0 + dropout = _execute.make_float(dropout, "dropout") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if num_proj is None: + num_proj = 0 + num_proj = _execute.make_int(num_proj, "num_proj") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + if time_major is None: + time_major = True + time_major = _execute.make_bool(time_major, "time_major") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_h, input_c, params], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, input_h, input_c, params) = _inputs_T + sequence_lengths = _ops.convert_to_tensor(sequence_lengths, _dtypes.int32) + _inputs_flat = [input, input_h, input_c, params, sequence_lengths] + _attrs = ("T", _attr_T, "rnn_mode", rnn_mode, "input_mode", input_mode, + "direction", direction, "dropout", dropout, "seed", seed, "seed2", seed2, + "num_proj", num_proj, "is_training", is_training, "time_major", time_major) + _result = _execute.execute(b"CudnnRNNV3", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CudnnRNNV3", _inputs_flat, _attrs, _result) + _result = _CudnnRNNV3Output._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_data_flow_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_data_flow_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2e32a871b3d2f282def9106344a23fa8536748b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_data_flow_ops.py @@ -0,0 +1,8117 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AccumulatorApplyGradient_dtype = TypeVar("TV_AccumulatorApplyGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def accumulator_apply_gradient(handle: Annotated[Any, _atypes.String], local_step: Annotated[Any, _atypes.Int64], gradient: Annotated[Any, TV_AccumulatorApplyGradient_dtype], name=None): + r"""Applies a gradient to a given accumulator. + + Does not add if local_step is lesser than the accumulator's global_step. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a accumulator. + local_step: A `Tensor` of type `int64`. + The local_step value at which the gradient was computed. + gradient: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of the gradient to be accumulated. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("accumulator_apply_gradient op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AccumulatorApplyGradient", handle=handle, local_step=local_step, + gradient=gradient, name=name) + return _op +AccumulatorApplyGradient = tf_export("raw_ops.AccumulatorApplyGradient")(_ops.to_raw_op(accumulator_apply_gradient)) + + +def accumulator_apply_gradient_eager_fallback(handle: Annotated[Any, _atypes.String], local_step: Annotated[Any, _atypes.Int64], gradient: Annotated[Any, TV_AccumulatorApplyGradient_dtype], name, ctx): + raise RuntimeError("accumulator_apply_gradient op does not support eager execution. Arg 'handle' is a ref.") + +def accumulator_num_accumulated(handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the number of gradients aggregated in the given accumulators. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to an accumulator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("accumulator_num_accumulated op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AccumulatorNumAccumulated", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "AccumulatorNumAccumulated", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AccumulatorNumAccumulated = tf_export("raw_ops.AccumulatorNumAccumulated")(_ops.to_raw_op(accumulator_num_accumulated)) + + +def accumulator_num_accumulated_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("accumulator_num_accumulated op does not support eager execution. Arg 'handle' is a ref.") + +def accumulator_set_global_step(handle: Annotated[Any, _atypes.String], new_global_step: Annotated[Any, _atypes.Int64], name=None): + r"""Updates the accumulator with a new value for global_step. + + Logs warning if the accumulator's value is already higher than + new_global_step. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to an accumulator. + new_global_step: A `Tensor` of type `int64`. + The new global_step value to set. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("accumulator_set_global_step op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AccumulatorSetGlobalStep", handle=handle, + new_global_step=new_global_step, + name=name) + return _op +AccumulatorSetGlobalStep = tf_export("raw_ops.AccumulatorSetGlobalStep")(_ops.to_raw_op(accumulator_set_global_step)) + + +def accumulator_set_global_step_eager_fallback(handle: Annotated[Any, _atypes.String], new_global_step: Annotated[Any, _atypes.Int64], name, ctx): + raise RuntimeError("accumulator_set_global_step op does not support eager execution. Arg 'handle' is a ref.") + +TV_AccumulatorTakeGradient_dtype = TypeVar("TV_AccumulatorTakeGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def accumulator_take_gradient(handle: Annotated[Any, _atypes.String], num_required: Annotated[Any, _atypes.Int32], dtype: TV_AccumulatorTakeGradient_dtype, name=None) -> Annotated[Any, TV_AccumulatorTakeGradient_dtype]: + r"""Extracts the average gradient in the given ConditionalAccumulator. + + The op blocks until sufficient (i.e., more than num_required) + gradients have been accumulated. If the accumulator has already + aggregated more than num_required gradients, it returns the average of + the accumulated gradients. Also automatically increments the recorded + global_step in the accumulator by 1, and resets the aggregate to 0. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to an accumulator. + num_required: A `Tensor` of type `int32`. + Number of gradients required before we return an aggregate. + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The data type of accumulated gradients. Needs to correspond to the type + of the accumulator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("accumulator_take_gradient op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AccumulatorTakeGradient", handle=handle, num_required=num_required, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AccumulatorTakeGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AccumulatorTakeGradient = tf_export("raw_ops.AccumulatorTakeGradient")(_ops.to_raw_op(accumulator_take_gradient)) + + +def accumulator_take_gradient_eager_fallback(handle: Annotated[Any, _atypes.String], num_required: Annotated[Any, _atypes.Int32], dtype: TV_AccumulatorTakeGradient_dtype, name, ctx) -> Annotated[Any, TV_AccumulatorTakeGradient_dtype]: + raise RuntimeError("accumulator_take_gradient op does not support eager execution. Arg 'handle' is a ref.") + +def barrier(component_types, shapes=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Defines a barrier that persists across different graph executions. + + A barrier represents a key-value map, where each key is a string, and + each value is a tuple of tensors. + + At runtime, the barrier contains 'complete' and 'incomplete' + elements. A complete element has defined tensors for all components of + its value tuple, and may be accessed using BarrierTakeMany. An + incomplete element has some undefined components in its value tuple, + and may be updated using BarrierInsertMany. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. Each shape must be 1 in the + first dimension. The length of this attr must be the same as the length of + component_types. + capacity: An optional `int`. Defaults to `-1`. + The capacity of the barrier. The default capacity is MAX_INT32, + which is the largest capacity of the underlying queue. + container: An optional `string`. Defaults to `""`. + If non-empty, this barrier is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this barrier will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'barrier' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'barrier' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Barrier", component_types=component_types, shapes=shapes, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Barrier", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Barrier = tf_export("raw_ops.Barrier")(_ops.to_raw_op(barrier)) + + +def barrier_eager_fallback(component_types, shapes, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("barrier op does not support eager execution. Arg 'handle' is a ref.") + +def barrier_close(handle: Annotated[Any, _atypes.String], cancel_pending_enqueues:bool=False, name=None): + r"""Closes the given barrier. + + This operation signals that no more new elements will be inserted in the + given barrier. Subsequent InsertMany that try to introduce a new key will fail. + Subsequent InsertMany operations that just add missing components to already + existing elements will continue to succeed. Subsequent TakeMany operations will + continue to succeed if sufficient completed elements remain in the barrier. + Subsequent TakeMany operations that would block will fail immediately. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a barrier. + cancel_pending_enqueues: An optional `bool`. Defaults to `False`. + If true, all pending enqueue requests that are + blocked on the barrier's queue will be canceled. InsertMany will fail, even + if no new key is introduced. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier_close op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if cancel_pending_enqueues is None: + cancel_pending_enqueues = False + cancel_pending_enqueues = _execute.make_bool(cancel_pending_enqueues, "cancel_pending_enqueues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BarrierClose", handle=handle, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + return _op +BarrierClose = tf_export("raw_ops.BarrierClose")(_ops.to_raw_op(barrier_close)) + + +def barrier_close_eager_fallback(handle: Annotated[Any, _atypes.String], cancel_pending_enqueues: bool, name, ctx): + raise RuntimeError("barrier_close op does not support eager execution. Arg 'handle' is a ref.") + +def barrier_incomplete_size(handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Computes the number of incomplete elements in the given barrier. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a barrier. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier_incomplete_size op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BarrierIncompleteSize", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BarrierIncompleteSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BarrierIncompleteSize = tf_export("raw_ops.BarrierIncompleteSize")(_ops.to_raw_op(barrier_incomplete_size)) + + +def barrier_incomplete_size_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("barrier_incomplete_size op does not support eager execution. Arg 'handle' is a ref.") + +TV_BarrierInsertMany_T = TypeVar("TV_BarrierInsertMany_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def barrier_insert_many(handle: Annotated[Any, _atypes.String], keys: Annotated[Any, _atypes.String], values: Annotated[Any, TV_BarrierInsertMany_T], component_index: int, name=None): + r"""For each key, assigns the respective value to the specified component. + + If a key is not found in the barrier, this operation will create a new + incomplete element. If a key is found in the barrier, and the element + already has a value at component_index, this operation will fail with + INVALID_ARGUMENT, and leave the barrier in an undefined state. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a barrier. + keys: A `Tensor` of type `string`. + A one-dimensional tensor of keys, with length n. + values: A `Tensor`. + An any-dimensional tensor of values, which are associated with the + respective keys. The 0th dimension must have length n. + component_index: An `int`. + The component of the barrier elements that is being assigned. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier_insert_many op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + component_index = _execute.make_int(component_index, "component_index") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BarrierInsertMany", handle=handle, keys=keys, values=values, + component_index=component_index, name=name) + return _op +BarrierInsertMany = tf_export("raw_ops.BarrierInsertMany")(_ops.to_raw_op(barrier_insert_many)) + + +def barrier_insert_many_eager_fallback(handle: Annotated[Any, _atypes.String], keys: Annotated[Any, _atypes.String], values: Annotated[Any, TV_BarrierInsertMany_T], component_index: int, name, ctx): + raise RuntimeError("barrier_insert_many op does not support eager execution. Arg 'handle' is a ref.") + +def barrier_ready_size(handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Computes the number of complete elements in the given barrier. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a barrier. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier_ready_size op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BarrierReadySize", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BarrierReadySize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BarrierReadySize = tf_export("raw_ops.BarrierReadySize")(_ops.to_raw_op(barrier_ready_size)) + + +def barrier_ready_size_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("barrier_ready_size op does not support eager execution. Arg 'handle' is a ref.") +_BarrierTakeManyOutput = collections.namedtuple( + "BarrierTakeMany", + ["indices", "keys", "values"]) + + +def barrier_take_many(handle: Annotated[Any, _atypes.String], num_elements: Annotated[Any, _atypes.Int32], component_types, allow_small_batch:bool=False, wait_for_incomplete:bool=False, timeout_ms:int=-1, name=None): + r"""Takes the given number of completed elements from a barrier. + + This operation concatenates completed-element component tensors along + the 0th dimension to make a single component tensor. + + Elements come out of the barrier when they are complete, and in the order + in which they were placed into the barrier. The indices output provides + information about the batch in which each element was originally inserted + into the barrier. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a barrier. + num_elements: A `Tensor` of type `int32`. + A single-element tensor containing the number of elements to + take. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + allow_small_batch: An optional `bool`. Defaults to `False`. + Allow to return less than num_elements items if barrier is + already closed. + wait_for_incomplete: An optional `bool`. Defaults to `False`. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is empty, this operation will block for up to + timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, keys, values). + + indices: A `Tensor` of type `int64`. + keys: A `Tensor` of type `string`. + values: A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("barrier_take_many op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'barrier_take_many' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if allow_small_batch is None: + allow_small_batch = False + allow_small_batch = _execute.make_bool(allow_small_batch, "allow_small_batch") + if wait_for_incomplete is None: + wait_for_incomplete = False + wait_for_incomplete = _execute.make_bool(wait_for_incomplete, "wait_for_incomplete") + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BarrierTakeMany", handle=handle, num_elements=num_elements, + component_types=component_types, + allow_small_batch=allow_small_batch, + wait_for_incomplete=wait_for_incomplete, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "allow_small_batch", _op._get_attr_bool("allow_small_batch"), + "wait_for_incomplete", + _op._get_attr_bool("wait_for_incomplete"), "timeout_ms", + _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BarrierTakeMany", _inputs_flat, _attrs, _result) + _result = _result[:2] + [_result[2:]] + _result = _BarrierTakeManyOutput._make(_result) + return _result + +BarrierTakeMany = tf_export("raw_ops.BarrierTakeMany")(_ops.to_raw_op(barrier_take_many)) + + +def barrier_take_many_eager_fallback(handle: Annotated[Any, _atypes.String], num_elements: Annotated[Any, _atypes.Int32], component_types, allow_small_batch: bool, wait_for_incomplete: bool, timeout_ms: int, name, ctx): + raise RuntimeError("barrier_take_many op does not support eager execution. Arg 'handle' is a ref.") + +TV_ConditionalAccumulator_dtype = TypeVar("TV_ConditionalAccumulator_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def conditional_accumulator(dtype: TV_ConditionalAccumulator_dtype, shape, container:str="", shared_name:str="", reduction_type:str="MEAN", name=None) -> Annotated[Any, _atypes.String]: + r"""A conditional accumulator for aggregating gradients. + + The accumulator accepts gradients marked with local_step greater or + equal to the most recent global_step known to the accumulator. The + average can be extracted from the accumulator, provided sufficient + gradients have been accumulated. Extracting the average automatically + resets the aggregate to 0, and increments the global_step recorded by + the accumulator. + + Args: + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The type of the value being accumulated. + shape: A `tf.TensorShape` or list of `ints`. + The shape of the values, can be [], in which case shape is unknown. + container: An optional `string`. Defaults to `""`. + If non-empty, this accumulator is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this accumulator will be shared under the + given name across multiple sessions. + reduction_type: An optional `string` from: `"MEAN", "SUM"`. Defaults to `"MEAN"`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("conditional_accumulator op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if reduction_type is None: + reduction_type = "MEAN" + reduction_type = _execute.make_str(reduction_type, "reduction_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConditionalAccumulator", dtype=dtype, shape=shape, + container=container, + shared_name=shared_name, + reduction_type=reduction_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name"), "reduction_type", + _op.get_attr("reduction_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConditionalAccumulator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ConditionalAccumulator = tf_export("raw_ops.ConditionalAccumulator")(_ops.to_raw_op(conditional_accumulator)) + + +def conditional_accumulator_eager_fallback(dtype: TV_ConditionalAccumulator_dtype, shape, container: str, shared_name: str, reduction_type: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("conditional_accumulator op does not support eager execution. Arg 'handle' is a ref.") + +def delete_session_tensor(handle: Annotated[Any, _atypes.String], name=None): + r"""Delete the tensor specified by its handle in the session. + + Args: + handle: A `Tensor` of type `string`. + The handle for a tensor stored in the session state. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteSessionTensor", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_session_tensor_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteSessionTensor", handle=handle, name=name) + return _op +DeleteSessionTensor = tf_export("raw_ops.DeleteSessionTensor")(_ops.to_raw_op(delete_session_tensor)) + + +def delete_session_tensor_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.string) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"DeleteSessionTensor", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_DynamicPartition_T = TypeVar("TV_DynamicPartition_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('dynamic_partition') +def dynamic_partition(data: Annotated[Any, TV_DynamicPartition_T], partitions: Annotated[Any, _atypes.Int32], num_partitions: int, name=None): + r"""Partitions `data` into `num_partitions` tensors using indices from `partitions`. + + For each index tuple `js` of size `partitions.ndim`, the slice `data[js, ...]` + becomes part of `outputs[partitions[js]]`. The slices with `partitions[js] = i` + are placed in `outputs[i]` in lexicographic order of `js`, and the first + dimension of `outputs[i]` is the number of entries in `partitions` equal to `i`. + In detail, + + ```python + outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:] + + outputs[i] = pack([data[js, ...] for js if partitions[js] == i]) + ``` + + `data.shape` must start with `partitions.shape`. + + For example: + + ```python + # Scalar partitions. + partitions = 1 + num_partitions = 2 + data = [10, 20] + outputs[0] = [] # Empty with shape [0, 2] + outputs[1] = [[10, 20]] + + # Vector partitions. + partitions = [0, 0, 1, 1, 0] + num_partitions = 2 + data = [10, 20, 30, 40, 50] + outputs[0] = [10, 20, 50] + outputs[1] = [30, 40] + ``` + + See `dynamic_stitch` for an example on how to merge partitions back. + +
+ +
+ + + Raises: + * `InvalidArgumentError` in following cases: + - If partitions is not in range `[0, num_partiions)` + - If `partitions.shape` does not match prefix of `data.shape` argument. + + Args: + data: A `Tensor`. + partitions: A `Tensor` of type `int32`. + Any shape. Indices in the range `[0, num_partitions)`. + num_partitions: An `int` that is `>= 1`. + The number of partitions to output. + name: A name for the operation (optional). + + Returns: + A list of `num_partitions` `Tensor` objects with the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DynamicPartition", name, data, partitions, "num_partitions", + num_partitions) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_dynamic_partition( + (data, partitions, num_partitions, name,), None) + if _result is not NotImplemented: + return _result + return dynamic_partition_eager_fallback( + data, partitions, num_partitions=num_partitions, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dynamic_partition, (), dict(data=data, partitions=partitions, + num_partitions=num_partitions, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_dynamic_partition( + (data, partitions, num_partitions, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + num_partitions = _execute.make_int(num_partitions, "num_partitions") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DynamicPartition", data=data, partitions=partitions, + num_partitions=num_partitions, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dynamic_partition, (), dict(data=data, partitions=partitions, + num_partitions=num_partitions, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_partitions", _op._get_attr_int("num_partitions"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DynamicPartition", _inputs_flat, _attrs, _result) + return _result + +DynamicPartition = tf_export("raw_ops.DynamicPartition")(_ops.to_raw_op(dynamic_partition)) +_dispatcher_for_dynamic_partition = dynamic_partition._tf_type_based_dispatcher.Dispatch + + +def dynamic_partition_eager_fallback(data: Annotated[Any, TV_DynamicPartition_T], partitions: Annotated[Any, _atypes.Int32], num_partitions: int, name, ctx): + num_partitions = _execute.make_int(num_partitions, "num_partitions") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, []) + partitions = _ops.convert_to_tensor(partitions, _dtypes.int32) + _inputs_flat = [data, partitions] + _attrs = ("num_partitions", num_partitions, "T", _attr_T) + _result = _execute.execute(b"DynamicPartition", num_partitions, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DynamicPartition", _inputs_flat, _attrs, _result) + return _result + + +TV_DynamicStitch_T = TypeVar("TV_DynamicStitch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('dynamic_stitch') +def dynamic_stitch(indices: Annotated[List[Any], _atypes.Int32], data: Annotated[List[Any], TV_DynamicStitch_T], name=None) -> Annotated[Any, TV_DynamicStitch_T]: + r"""Interleave the values from the `data` tensors into a single tensor. + + Builds a merged tensor such that + + ```python + merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...] + ``` + + For example, if each `indices[m]` is scalar or vector, we have + + ```python + # Scalar indices: + merged[indices[m], ...] = data[m][...] + + # Vector indices: + merged[indices[m][i], ...] = data[m][i, ...] + ``` + + Each `data[i].shape` must start with the corresponding `indices[i].shape`, + and the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we + must have `data[i].shape = indices[i].shape + constant`. In terms of this + `constant`, the output shape is + + merged.shape = [max(indices)] + constant + + Values are merged in order, so if an index appears in both `indices[m][i]` and + `indices[n][j]` for `(m,i) < (n,j)` the slice `data[n][j]` will appear in the + merged result. If you do not need this guarantee, ParallelDynamicStitch might + perform better on some devices. + + For example: + + ```python + indices[0] = 6 + indices[1] = [4, 1] + indices[2] = [[5, 2], [0, 3]] + data[0] = [61, 62] + data[1] = [[41, 42], [11, 12]] + data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]] + merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42], + [51, 52], [61, 62]] + ``` + + This method can be used to merge partitions created by `dynamic_partition` + as illustrated on the following example: + + ```python + # Apply function (increments x_i) on elements for which a certain condition + # apply (x_i != -1 in this example). + x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4]) + condition_mask=tf.not_equal(x,tf.constant(-1.)) + partitioned_data = tf.dynamic_partition( + x, tf.cast(condition_mask, tf.int32) , 2) + partitioned_data[1] = partitioned_data[1] + 1.0 + condition_indices = tf.dynamic_partition( + tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2) + x = tf.dynamic_stitch(condition_indices, partitioned_data) + # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain + # unchanged. + ``` + +
+ +
+ + Args: + indices: A list of at least 1 `Tensor` objects with type `int32`. + data: A list with the same length as `indices` of `Tensor` objects with the same type. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DynamicStitch", name, indices, data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_dynamic_stitch( + (indices, data, name,), None) + if _result is not NotImplemented: + return _result + return dynamic_stitch_eager_fallback( + indices, data, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dynamic_stitch, (), dict(indices=indices, data=data, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_dynamic_stitch( + (indices, data, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'dynamic_stitch' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(data, (list, tuple)): + raise TypeError( + "Expected list for 'data' argument to " + "'dynamic_stitch' Op, not %r." % data) + if len(data) != _attr_N: + raise ValueError( + "List argument 'data' to 'dynamic_stitch' Op with length %d " + "must match length %d of argument 'indices'." % + (len(data), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DynamicStitch", indices=indices, data=data, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dynamic_stitch, (), dict(indices=indices, data=data, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DynamicStitch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DynamicStitch = tf_export("raw_ops.DynamicStitch")(_ops.to_raw_op(dynamic_stitch)) +_dispatcher_for_dynamic_stitch = dynamic_stitch._tf_type_based_dispatcher.Dispatch + + +def dynamic_stitch_eager_fallback(indices: Annotated[List[Any], _atypes.Int32], data: Annotated[List[Any], TV_DynamicStitch_T], name, ctx) -> Annotated[Any, TV_DynamicStitch_T]: + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'dynamic_stitch' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(data, (list, tuple)): + raise TypeError( + "Expected list for 'data' argument to " + "'dynamic_stitch' Op, not %r." % data) + if len(data) != _attr_N: + raise ValueError( + "List argument 'data' to 'dynamic_stitch' Op with length %d " + "must match length %d of argument 'indices'." % + (len(data), _attr_N)) + _attr_T, data = _execute.args_to_matching_eager(list(data), ctx, []) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int32) + _inputs_flat = list(indices) + list(data) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"DynamicStitch", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DynamicStitch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def fifo_queue(component_types, shapes=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A queue that produces elements in first-in first-out order. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("fifo_queue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'fifo_queue' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'fifo_queue' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FIFOQueue", component_types=component_types, shapes=shapes, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FIFOQueue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FIFOQueue = tf_export("raw_ops.FIFOQueue")(_ops.to_raw_op(fifo_queue)) + + +def fifo_queue_eager_fallback(component_types, shapes, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("fifo_queue op does not support eager execution. Arg 'handle' is a ref.") + +def fifo_queue_v2(component_types, shapes=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A queue that produces elements in first-in first-out order. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FIFOQueueV2", name, "component_types", component_types, + "shapes", shapes, "capacity", capacity, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fifo_queue_v2_eager_fallback( + component_types=component_types, shapes=shapes, capacity=capacity, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'fifo_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'fifo_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FIFOQueueV2", component_types=component_types, shapes=shapes, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FIFOQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FIFOQueueV2 = tf_export("raw_ops.FIFOQueueV2")(_ops.to_raw_op(fifo_queue_v2)) + + +def fifo_queue_v2_eager_fallback(component_types, shapes, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'fifo_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'fifo_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("component_types", component_types, "shapes", shapes, "capacity", + capacity, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"FIFOQueueV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FIFOQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def fake_queue(resource: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Deprecated. Do not use. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("fake_queue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeQueue", resource=resource, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeQueue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeQueue = tf_export("raw_ops.FakeQueue")(_ops.to_raw_op(fake_queue)) + + +def fake_queue_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("fake_queue op does not support eager execution. Arg 'handle' is a ref.") + +TV_GetSessionHandle_T = TypeVar("TV_GetSessionHandle_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def get_session_handle(value: Annotated[Any, TV_GetSessionHandle_T], name=None) -> Annotated[Any, _atypes.String]: + r"""Store the input tensor in the state of the current session. + + Args: + value: A `Tensor`. The tensor to be stored. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetSessionHandle", name, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return get_session_handle_eager_fallback( + value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetSessionHandle", value=value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetSessionHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GetSessionHandle = tf_export("raw_ops.GetSessionHandle")(_ops.to_raw_op(get_session_handle)) + + +def get_session_handle_eager_fallback(value: Annotated[Any, TV_GetSessionHandle_T], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _inputs_flat = [value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GetSessionHandle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetSessionHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GetSessionHandleV2_T = TypeVar("TV_GetSessionHandleV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def get_session_handle_v2(value: Annotated[Any, TV_GetSessionHandleV2_T], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Store the input tensor in the state of the current session. + + Args: + value: A `Tensor`. The tensor to be stored. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetSessionHandleV2", name, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return get_session_handle_v2_eager_fallback( + value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetSessionHandleV2", value=value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetSessionHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GetSessionHandleV2 = tf_export("raw_ops.GetSessionHandleV2")(_ops.to_raw_op(get_session_handle_v2)) + + +def get_session_handle_v2_eager_fallback(value: Annotated[Any, TV_GetSessionHandleV2_T], name, ctx) -> Annotated[Any, _atypes.Resource]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _inputs_flat = [value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GetSessionHandleV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetSessionHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GetSessionTensor_dtype = TypeVar("TV_GetSessionTensor_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def get_session_tensor(handle: Annotated[Any, _atypes.String], dtype: TV_GetSessionTensor_dtype, name=None) -> Annotated[Any, TV_GetSessionTensor_dtype]: + r"""Get the value of the tensor specified by its handle. + + Args: + handle: A `Tensor` of type `string`. + The handle for a tensor stored in the session state. + dtype: A `tf.DType`. The type of the output value. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetSessionTensor", name, handle, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return get_session_tensor_eager_fallback( + handle, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetSessionTensor", handle=handle, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetSessionTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GetSessionTensor = tf_export("raw_ops.GetSessionTensor")(_ops.to_raw_op(get_session_tensor)) + + +def get_session_tensor_eager_fallback(handle: Annotated[Any, _atypes.String], dtype: TV_GetSessionTensor_dtype, name, ctx) -> Annotated[Any, TV_GetSessionTensor_dtype]: + dtype = _execute.make_type(dtype, "dtype") + handle = _ops.convert_to_tensor(handle, _dtypes.string) + _inputs_flat = [handle] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"GetSessionTensor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetSessionTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def map_clear(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes all elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapClear", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_clear_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapClear", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + return _op +MapClear = tf_export("raw_ops.MapClear")(_ops.to_raw_op(map_clear)) + + +def map_clear_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapClear", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def map_incomplete_size(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int32]: + r"""Op returns the number of incomplete elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapIncompleteSize", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_incomplete_size_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_incomplete_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapIncompleteSize", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapIncompleteSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MapIncompleteSize = tf_export("raw_ops.MapIncompleteSize")(_ops.to_raw_op(map_incomplete_size)) + + +def map_incomplete_size_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_incomplete_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapIncompleteSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapIncompleteSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def map_peek(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op peeks at the values at the specified key. If the + + underlying container does not contain this key + this op will block until it does. + + Args: + key: A `Tensor` of type `int64`. + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapPeek", name, key, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_peek_eager_fallback( + key, indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapPeek", key=key, indices=indices, dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapPeek", _inputs_flat, _attrs, _result) + return _result + +MapPeek = tf_export("raw_ops.MapPeek")(_ops.to_raw_op(map_peek)) + + +def map_peek_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapPeek", len(dtypes), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapPeek", _inputs_flat, _attrs, _result) + return _result + + +def map_size(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int32]: + r"""Op returns the number of elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapSize", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_size_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapSize", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MapSize = tf_export("raw_ops.MapSize")(_ops.to_raw_op(map_size)) + + +def map_size_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapSize", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def map_stage(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], values, dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Stage (key, values) in the underlying container which behaves like a hashtable. + + Args: + key: A `Tensor` of type `int64`. int64 + indices: A `Tensor` of type `int32`. + values: A list of `Tensor` objects. a list of tensors + dtypes A list of data types that inserted values should adhere to. + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + Maximum number of elements in the Staging Area. If > 0, inserts + on the container will block when the capacity is reached. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. Otherwise, + a default container is used. + shared_name: An optional `string`. Defaults to `""`. + It is necessary to match this name to the matching Unstage Op. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapStage", name, key, indices, values, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_stage_eager_fallback( + key, indices, values, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_stage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapStage", key=key, indices=indices, values=values, dtypes=dtypes, + capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, name=name) + return _op +MapStage = tf_export("raw_ops.MapStage")(_ops.to_raw_op(map_stage)) + + +def map_stage_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], values, dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_stage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_fake_dtypes, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + list(values) + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "fake_dtypes", _attr_fake_dtypes, "container", container, + "shared_name", shared_name) + _result = _execute.execute(b"MapStage", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def map_unstage(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes and returns the values associated with the key + + from the underlying container. If the underlying container + does not contain this key, the op will block until it does. + + Args: + key: A `Tensor` of type `int64`. + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapUnstage", name, key, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_unstage_eager_fallback( + key, indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapUnstage", key=key, indices=indices, dtypes=dtypes, + capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapUnstage", _inputs_flat, _attrs, _result) + return _result + +MapUnstage = tf_export("raw_ops.MapUnstage")(_ops.to_raw_op(map_unstage)) + + +def map_unstage_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapUnstage", len(dtypes), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapUnstage", _inputs_flat, _attrs, _result) + return _result + +_MapUnstageNoKeyOutput = collections.namedtuple( + "MapUnstageNoKey", + ["key", "values"]) + + +def map_unstage_no_key(indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes and returns a random (key, value) + + from the underlying container. If the underlying container + does not contain elements, the op will block until it does. + + Args: + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, values). + + key: A `Tensor` of type `int64`. + values: A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapUnstageNoKey", name, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + _result = _MapUnstageNoKeyOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_unstage_no_key_eager_fallback( + indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_unstage_no_key' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapUnstageNoKey", indices=indices, dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapUnstageNoKey", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _MapUnstageNoKeyOutput._make(_result) + return _result + +MapUnstageNoKey = tf_export("raw_ops.MapUnstageNoKey")(_ops.to_raw_op(map_unstage_no_key)) + + +def map_unstage_no_key_eager_fallback(indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'map_unstage_no_key' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"MapUnstageNoKey", len(dtypes) + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapUnstageNoKey", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _MapUnstageNoKeyOutput._make(_result) + return _result + + +def ordered_map_clear(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes all elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapClear", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_clear_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapClear", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + return _op +OrderedMapClear = tf_export("raw_ops.OrderedMapClear")(_ops.to_raw_op(ordered_map_clear)) + + +def ordered_map_clear_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapClear", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def ordered_map_incomplete_size(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int32]: + r"""Op returns the number of incomplete elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapIncompleteSize", name, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_incomplete_size_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_incomplete_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapIncompleteSize", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, + container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OrderedMapIncompleteSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OrderedMapIncompleteSize = tf_export("raw_ops.OrderedMapIncompleteSize")(_ops.to_raw_op(ordered_map_incomplete_size)) + + +def ordered_map_incomplete_size_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_incomplete_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapIncompleteSize", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OrderedMapIncompleteSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def ordered_map_peek(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op peeks at the values at the specified key. If the + + underlying container does not contain this key + this op will block until it does. This Op is optimized for + performance. + + Args: + key: A `Tensor` of type `int64`. + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapPeek", name, key, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_peek_eager_fallback( + key, indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapPeek", key=key, indices=indices, dtypes=dtypes, + capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OrderedMapPeek", _inputs_flat, _attrs, _result) + return _result + +OrderedMapPeek = tf_export("raw_ops.OrderedMapPeek")(_ops.to_raw_op(ordered_map_peek)) + + +def ordered_map_peek_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapPeek", len(dtypes), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OrderedMapPeek", _inputs_flat, _attrs, _result) + return _result + + +def ordered_map_size(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int32]: + r"""Op returns the number of elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapSize", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_size_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapSize", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OrderedMapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OrderedMapSize = tf_export("raw_ops.OrderedMapSize")(_ops.to_raw_op(ordered_map_size)) + + +def ordered_map_size_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OrderedMapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def ordered_map_stage(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], values, dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Stage (key, values) in the underlying container which behaves like a ordered + + associative container. Elements are ordered by key. + + Args: + key: A `Tensor` of type `int64`. int64 + indices: A `Tensor` of type `int32`. + values: A list of `Tensor` objects. a list of tensors + dtypes A list of data types that inserted values should adhere to. + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + Maximum number of elements in the Staging Area. If > 0, inserts + on the container will block when the capacity is reached. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. Otherwise, + a default container is used. + shared_name: An optional `string`. Defaults to `""`. + It is necessary to match this name to the matching Unstage Op. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapStage", name, key, indices, values, "capacity", + capacity, "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_stage_eager_fallback( + key, indices, values, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_stage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapStage", key=key, indices=indices, values=values, + dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + return _op +OrderedMapStage = tf_export("raw_ops.OrderedMapStage")(_ops.to_raw_op(ordered_map_stage)) + + +def ordered_map_stage_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], values, dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_stage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_fake_dtypes, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + list(values) + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "fake_dtypes", _attr_fake_dtypes, "container", container, + "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapStage", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def ordered_map_unstage(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes and returns the values associated with the key + + from the underlying container. If the underlying container + does not contain this key, the op will block until it does. + + Args: + key: A `Tensor` of type `int64`. + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapUnstage", name, key, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_unstage_eager_fallback( + key, indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapUnstage", key=key, indices=indices, dtypes=dtypes, + capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OrderedMapUnstage", _inputs_flat, _attrs, _result) + return _result + +OrderedMapUnstage = tf_export("raw_ops.OrderedMapUnstage")(_ops.to_raw_op(ordered_map_unstage)) + + +def ordered_map_unstage_eager_fallback(key: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + key = _ops.convert_to_tensor(key, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [key, indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapUnstage", len(dtypes), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OrderedMapUnstage", _inputs_flat, _attrs, _result) + return _result + +_OrderedMapUnstageNoKeyOutput = collections.namedtuple( + "OrderedMapUnstageNoKey", + ["key", "values"]) + + +def ordered_map_unstage_no_key(indices: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes and returns the (key, value) element with the smallest + + key from the underlying container. If the underlying container + does not contain elements, the op will block until it does. + + Args: + indices: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, values). + + key: A `Tensor` of type `int64`. + values: A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OrderedMapUnstageNoKey", name, indices, "capacity", capacity, + "memory_limit", memory_limit, "dtypes", dtypes, "container", + container, "shared_name", shared_name) + _result = _OrderedMapUnstageNoKeyOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ordered_map_unstage_no_key_eager_fallback( + indices, capacity=capacity, memory_limit=memory_limit, + dtypes=dtypes, container=container, shared_name=shared_name, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_unstage_no_key' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OrderedMapUnstageNoKey", indices=indices, dtypes=dtypes, + capacity=capacity, + memory_limit=memory_limit, + container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OrderedMapUnstageNoKey", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _OrderedMapUnstageNoKeyOutput._make(_result) + return _result + +OrderedMapUnstageNoKey = tf_export("raw_ops.OrderedMapUnstageNoKey")(_ops.to_raw_op(ordered_map_unstage_no_key)) + + +def ordered_map_unstage_no_key_eager_fallback(indices: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'ordered_map_unstage_no_key' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [indices] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"OrderedMapUnstageNoKey", len(dtypes) + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OrderedMapUnstageNoKey", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _OrderedMapUnstageNoKeyOutput._make(_result) + return _result + + +def padding_fifo_queue(component_types, shapes=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A queue that produces elements in first-in first-out order. + + Variable-size shapes are allowed by setting the corresponding shape dimensions + to 0 in the shape attr. In this case DequeueMany will pad up to the maximum + size of any given element in the minibatch. See below for details. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. + Shapes of fixed rank but variable size are allowed by setting + any shape dimension to -1. In this case, the inputs' shape may vary along + the given dimension, and DequeueMany will pad the given dimension with + zeros up to the maximum shape of all elements in the given batch. + If the length of this attr is 0, different queue elements may have + different ranks and shapes, but only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("padding_fifo_queue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'padding_fifo_queue' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'padding_fifo_queue' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PaddingFIFOQueue", component_types=component_types, shapes=shapes, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PaddingFIFOQueue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PaddingFIFOQueue = tf_export("raw_ops.PaddingFIFOQueue")(_ops.to_raw_op(padding_fifo_queue)) + + +def padding_fifo_queue_eager_fallback(component_types, shapes, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("padding_fifo_queue op does not support eager execution. Arg 'handle' is a ref.") + +def padding_fifo_queue_v2(component_types, shapes=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A queue that produces elements in first-in first-out order. + + Variable-size shapes are allowed by setting the corresponding shape dimensions + to 0 in the shape attr. In this case DequeueMany will pad up to the maximum + size of any given element in the minibatch. See below for details. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. + Shapes of fixed rank but variable size are allowed by setting + any shape dimension to -1. In this case, the inputs' shape may vary along + the given dimension, and DequeueMany will pad the given dimension with + zeros up to the maximum shape of all elements in the given batch. + If the length of this attr is 0, different queue elements may have + different ranks and shapes, but only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PaddingFIFOQueueV2", name, "component_types", component_types, + "shapes", shapes, "capacity", capacity, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return padding_fifo_queue_v2_eager_fallback( + component_types=component_types, shapes=shapes, capacity=capacity, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'padding_fifo_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'padding_fifo_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PaddingFIFOQueueV2", component_types=component_types, shapes=shapes, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PaddingFIFOQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PaddingFIFOQueueV2 = tf_export("raw_ops.PaddingFIFOQueueV2")(_ops.to_raw_op(padding_fifo_queue_v2)) + + +def padding_fifo_queue_v2_eager_fallback(component_types, shapes, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'padding_fifo_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'padding_fifo_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("component_types", component_types, "shapes", shapes, "capacity", + capacity, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"PaddingFIFOQueueV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PaddingFIFOQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ParallelDynamicStitch_T = TypeVar("TV_ParallelDynamicStitch_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def parallel_dynamic_stitch(indices: Annotated[List[Any], _atypes.Int32], data: Annotated[List[Any], TV_ParallelDynamicStitch_T], name=None) -> Annotated[Any, TV_ParallelDynamicStitch_T]: + r"""Interleave the values from the `data` tensors into a single tensor. + + Builds a merged tensor such that + + ```python + merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...] + ``` + + For example, if each `indices[m]` is scalar or vector, we have + + ```python + # Scalar indices: + merged[indices[m], ...] = data[m][...] + + # Vector indices: + merged[indices[m][i], ...] = data[m][i, ...] + ``` + + Each `data[i].shape` must start with the corresponding `indices[i].shape`, + and the rest of `data[i].shape` must be constant w.r.t. `i`. That is, we + must have `data[i].shape = indices[i].shape + constant`. In terms of this + `constant`, the output shape is + + merged.shape = [max(indices)] + constant + + Values may be merged in parallel, so if an index appears in both `indices[m][i]` + and `indices[n][j]`, the result may be invalid. This differs from the normal + DynamicStitch operator that defines the behavior in that case. + + For example: + + ```python + indices[0] = 6 + indices[1] = [4, 1] + indices[2] = [[5, 2], [0, 3]] + data[0] = [61, 62] + data[1] = [[41, 42], [11, 12]] + data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]] + merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42], + [51, 52], [61, 62]] + ``` + + This method can be used to merge partitions created by `dynamic_partition` + as illustrated on the following example: + + ```python + # Apply function (increments x_i) on elements for which a certain condition + # apply (x_i != -1 in this example). + x=tf.constant([0.1, -1., 5.2, 4.3, -1., 7.4]) + condition_mask=tf.not_equal(x,tf.constant(-1.)) + partitioned_data = tf.dynamic_partition( + x, tf.cast(condition_mask, tf.int32) , 2) + partitioned_data[1] = partitioned_data[1] + 1.0 + condition_indices = tf.dynamic_partition( + tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2) + x = tf.dynamic_stitch(condition_indices, partitioned_data) + # Here x=[1.1, -1., 6.2, 5.3, -1, 8.4], the -1. values remain + # unchanged. + ``` + +
+ +
+ + Args: + indices: A list of at least 1 `Tensor` objects with type `int32`. + data: A list with the same length as `indices` of `Tensor` objects with the same type. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelDynamicStitch", name, indices, data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_dynamic_stitch_eager_fallback( + indices, data, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'parallel_dynamic_stitch' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(data, (list, tuple)): + raise TypeError( + "Expected list for 'data' argument to " + "'parallel_dynamic_stitch' Op, not %r." % data) + if len(data) != _attr_N: + raise ValueError( + "List argument 'data' to 'parallel_dynamic_stitch' Op with length %d " + "must match length %d of argument 'indices'." % + (len(data), _attr_N)) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelDynamicStitch", indices=indices, data=data, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelDynamicStitch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelDynamicStitch = tf_export("raw_ops.ParallelDynamicStitch")(_ops.to_raw_op(parallel_dynamic_stitch)) + + +def parallel_dynamic_stitch_eager_fallback(indices: Annotated[List[Any], _atypes.Int32], data: Annotated[List[Any], TV_ParallelDynamicStitch_T], name, ctx) -> Annotated[Any, TV_ParallelDynamicStitch_T]: + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'parallel_dynamic_stitch' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(data, (list, tuple)): + raise TypeError( + "Expected list for 'data' argument to " + "'parallel_dynamic_stitch' Op, not %r." % data) + if len(data) != _attr_N: + raise ValueError( + "List argument 'data' to 'parallel_dynamic_stitch' Op with length %d " + "must match length %d of argument 'indices'." % + (len(data), _attr_N)) + _attr_T, data = _execute.args_to_matching_eager(list(data), ctx, []) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int32) + _inputs_flat = list(indices) + list(data) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"ParallelDynamicStitch", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelDynamicStitch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def priority_queue(shapes, component_types=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A queue that produces elements sorted by the first component value. + + Note that the PriorityQueue requires the first component of any element + to be a scalar int64, in addition to the other elements declared by + component_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue + and DequeueMany) on a PriorityQueue will all require (resp. output) one extra + entry in their input (resp. output) lists. + + Args: + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + component_types: An optional list of `tf.DTypes`. Defaults to `[]`. + The type of each component in a value. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("priority_queue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'priority_queue' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if component_types is None: + component_types = [] + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'priority_queue' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PriorityQueue", shapes=shapes, component_types=component_types, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PriorityQueue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PriorityQueue = tf_export("raw_ops.PriorityQueue")(_ops.to_raw_op(priority_queue)) + + +def priority_queue_eager_fallback(shapes, component_types, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("priority_queue op does not support eager execution. Arg 'handle' is a ref.") + +def priority_queue_v2(shapes, component_types=[], capacity:int=-1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A queue that produces elements sorted by the first component value. + + Note that the PriorityQueue requires the first component of any element + to be a scalar int64, in addition to the other elements declared by + component_types. Therefore calls to Enqueue and EnqueueMany (resp. Dequeue + and DequeueMany) on a PriorityQueue will all require (resp. output) one extra + entry in their input (resp. output) lists. + + Args: + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + component_types: An optional list of `tf.DTypes`. Defaults to `[]`. + The type of each component in a value. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PriorityQueueV2", name, "component_types", component_types, + "shapes", shapes, "capacity", capacity, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return priority_queue_v2_eager_fallback( + component_types=component_types, shapes=shapes, capacity=capacity, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'priority_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if component_types is None: + component_types = [] + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'priority_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PriorityQueueV2", shapes=shapes, component_types=component_types, + capacity=capacity, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PriorityQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PriorityQueueV2 = tf_export("raw_ops.PriorityQueueV2")(_ops.to_raw_op(priority_queue_v2)) + + +def priority_queue_v2_eager_fallback(shapes, component_types, capacity: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'priority_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if component_types is None: + component_types = [] + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'priority_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("component_types", component_types, "shapes", shapes, "capacity", + capacity, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"PriorityQueueV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PriorityQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def queue_close(handle: Annotated[Any, _atypes.String], cancel_pending_enqueues:bool=False, name=None): + r"""Closes the given queue. + + This operation signals that no more elements will be enqueued in the + given queue. Subsequent Enqueue(Many) operations will fail. + Subsequent Dequeue(Many) operations will continue to succeed if + sufficient elements remain in the queue. Subsequent Dequeue(Many) + operations that would block will fail immediately. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + cancel_pending_enqueues: An optional `bool`. Defaults to `False`. + If true, all pending enqueue requests that are + blocked on the given queue will be canceled. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_close op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if cancel_pending_enqueues is None: + cancel_pending_enqueues = False + cancel_pending_enqueues = _execute.make_bool(cancel_pending_enqueues, "cancel_pending_enqueues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueClose", handle=handle, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + return _op +QueueClose = tf_export("raw_ops.QueueClose")(_ops.to_raw_op(queue_close)) + + +def queue_close_eager_fallback(handle: Annotated[Any, _atypes.String], cancel_pending_enqueues: bool, name, ctx): + raise RuntimeError("queue_close op does not support eager execution. Arg 'handle' is a ref.") + +def queue_close_v2(handle: Annotated[Any, _atypes.Resource], cancel_pending_enqueues:bool=False, name=None): + r"""Closes the given queue. + + This operation signals that no more elements will be enqueued in the + given queue. Subsequent Enqueue(Many) operations will fail. + Subsequent Dequeue(Many) operations will continue to succeed if + sufficient elements remain in the queue. Subsequent Dequeue(Many) + operations that would block will fail immediately. + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + cancel_pending_enqueues: An optional `bool`. Defaults to `False`. + If true, all pending enqueue requests that are + blocked on the given queue will be canceled. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueCloseV2", name, handle, "cancel_pending_enqueues", + cancel_pending_enqueues) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_close_v2_eager_fallback( + handle, cancel_pending_enqueues=cancel_pending_enqueues, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if cancel_pending_enqueues is None: + cancel_pending_enqueues = False + cancel_pending_enqueues = _execute.make_bool(cancel_pending_enqueues, "cancel_pending_enqueues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueCloseV2", handle=handle, + cancel_pending_enqueues=cancel_pending_enqueues, + name=name) + return _op +QueueCloseV2 = tf_export("raw_ops.QueueCloseV2")(_ops.to_raw_op(queue_close_v2)) + + +def queue_close_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], cancel_pending_enqueues: bool, name, ctx): + if cancel_pending_enqueues is None: + cancel_pending_enqueues = False + cancel_pending_enqueues = _execute.make_bool(cancel_pending_enqueues, "cancel_pending_enqueues") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = ("cancel_pending_enqueues", cancel_pending_enqueues) + _result = _execute.execute(b"QueueCloseV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def queue_dequeue(handle: Annotated[Any, _atypes.String], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues a tuple of one or more tensors from the given queue. + + This operation has k outputs, where k is the number of components + in the tuples stored in the given queue, and output i is the ith + component of the dequeued tuple. + + N.B. If the queue is empty, this operation will block until an element + has been dequeued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is empty, this operation will block for up to + timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_dequeue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeue", handle=handle, component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeue", _inputs_flat, _attrs, _result) + return _result + +QueueDequeue = tf_export("raw_ops.QueueDequeue")(_ops.to_raw_op(queue_dequeue)) + + +def queue_dequeue_eager_fallback(handle: Annotated[Any, _atypes.String], component_types, timeout_ms: int, name, ctx): + raise RuntimeError("queue_dequeue op does not support eager execution. Arg 'handle' is a ref.") + +def queue_dequeue_many(handle: Annotated[Any, _atypes.String], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues `n` tuples of one or more tensors from the given queue. + + If the queue is closed and there are fewer than `n` elements, then an + OutOfRange error is returned. + + This operation concatenates queue-element component tensors along the + 0th dimension to make a single component tensor. All of the components + in the dequeued tuple will have size `n` in the 0th dimension. + + This operation has `k` outputs, where `k` is the number of components in + the tuples stored in the given queue, and output `i` is the ith + component of the dequeued tuple. + + N.B. If the queue is empty, this operation will block until `n` elements + have been dequeued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + n: A `Tensor` of type `int32`. The number of tuples to dequeue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue has fewer than n elements, this operation + will block for up to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_dequeue_many op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_many' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeueMany", handle=handle, n=n, + component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeueMany", _inputs_flat, _attrs, _result) + return _result + +QueueDequeueMany = tf_export("raw_ops.QueueDequeueMany")(_ops.to_raw_op(queue_dequeue_many)) + + +def queue_dequeue_many_eager_fallback(handle: Annotated[Any, _atypes.String], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms: int, name, ctx): + raise RuntimeError("queue_dequeue_many op does not support eager execution. Arg 'handle' is a ref.") + +def queue_dequeue_many_v2(handle: Annotated[Any, _atypes.Resource], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues `n` tuples of one or more tensors from the given queue. + + If the queue is closed and there are fewer than `n` elements, then an + OutOfRange error is returned. + + This operation concatenates queue-element component tensors along the + 0th dimension to make a single component tensor. All of the components + in the dequeued tuple will have size `n` in the 0th dimension. + + This operation has `k` outputs, where `k` is the number of components in + the tuples stored in the given queue, and output `i` is the ith + component of the dequeued tuple. + + N.B. If the queue is empty, this operation will block until `n` elements + have been dequeued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + n: A `Tensor` of type `int32`. The number of tuples to dequeue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue has fewer than n elements, this operation + will block for up to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueDequeueManyV2", name, handle, n, "component_types", + component_types, "timeout_ms", timeout_ms) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_dequeue_many_v2_eager_fallback( + handle, n, component_types=component_types, timeout_ms=timeout_ms, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_many_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeueManyV2", handle=handle, n=n, + component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeueManyV2", _inputs_flat, _attrs, _result) + return _result + +QueueDequeueManyV2 = tf_export("raw_ops.QueueDequeueManyV2")(_ops.to_raw_op(queue_dequeue_many_v2)) + + +def queue_dequeue_many_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms: int, name, ctx): + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_many_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + n = _ops.convert_to_tensor(n, _dtypes.int32) + _inputs_flat = [handle, n] + _attrs = ("component_types", component_types, "timeout_ms", timeout_ms) + _result = _execute.execute(b"QueueDequeueManyV2", len(component_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QueueDequeueManyV2", _inputs_flat, _attrs, _result) + return _result + + +def queue_dequeue_up_to(handle: Annotated[Any, _atypes.String], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues `n` tuples of one or more tensors from the given queue. + + This operation is not supported by all queues. If a queue does not support + DequeueUpTo, then an Unimplemented error is returned. + + If the queue is closed and there are more than 0 but less than `n` + elements remaining, then instead of returning an OutOfRange error like + QueueDequeueMany, less than `n` elements are returned immediately. If + the queue is closed and there are 0 elements left in the queue, then + an OutOfRange error is returned just like in QueueDequeueMany. + Otherwise the behavior is identical to QueueDequeueMany: + + This operation concatenates queue-element component tensors along the + 0th dimension to make a single component tensor. All of the components + in the dequeued tuple will have size `n` in the 0th dimension. + + This operation has k outputs, where `k` is the number of components in + the tuples stored in the given queue, and output `i` is the ith + component of the dequeued tuple. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + n: A `Tensor` of type `int32`. The number of tuples to dequeue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue has fewer than n elements, this operation + will block for up to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_dequeue_up_to op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_up_to' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeueUpTo", handle=handle, n=n, + component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeueUpTo", _inputs_flat, _attrs, _result) + return _result + +QueueDequeueUpTo = tf_export("raw_ops.QueueDequeueUpTo")(_ops.to_raw_op(queue_dequeue_up_to)) + + +def queue_dequeue_up_to_eager_fallback(handle: Annotated[Any, _atypes.String], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms: int, name, ctx): + raise RuntimeError("queue_dequeue_up_to op does not support eager execution. Arg 'handle' is a ref.") + +def queue_dequeue_up_to_v2(handle: Annotated[Any, _atypes.Resource], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues `n` tuples of one or more tensors from the given queue. + + This operation is not supported by all queues. If a queue does not support + DequeueUpTo, then an Unimplemented error is returned. + + If the queue is closed and there are more than 0 but less than `n` + elements remaining, then instead of returning an OutOfRange error like + QueueDequeueMany, less than `n` elements are returned immediately. If + the queue is closed and there are 0 elements left in the queue, then + an OutOfRange error is returned just like in QueueDequeueMany. + Otherwise the behavior is identical to QueueDequeueMany: + + This operation concatenates queue-element component tensors along the + 0th dimension to make a single component tensor. All of the components + in the dequeued tuple will have size n in the 0th dimension. + + This operation has `k` outputs, where `k` is the number of components in + the tuples stored in the given queue, and output `i` is the ith + component of the dequeued tuple. + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + n: A `Tensor` of type `int32`. The number of tuples to dequeue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue has fewer than n elements, this operation + will block for up to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueDequeueUpToV2", name, handle, n, "component_types", + component_types, "timeout_ms", timeout_ms) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_dequeue_up_to_v2_eager_fallback( + handle, n, component_types=component_types, timeout_ms=timeout_ms, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_up_to_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeueUpToV2", handle=handle, n=n, + component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeueUpToV2", _inputs_flat, _attrs, _result) + return _result + +QueueDequeueUpToV2 = tf_export("raw_ops.QueueDequeueUpToV2")(_ops.to_raw_op(queue_dequeue_up_to_v2)) + + +def queue_dequeue_up_to_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], n: Annotated[Any, _atypes.Int32], component_types, timeout_ms: int, name, ctx): + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_up_to_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + n = _ops.convert_to_tensor(n, _dtypes.int32) + _inputs_flat = [handle, n] + _attrs = ("component_types", component_types, "timeout_ms", timeout_ms) + _result = _execute.execute(b"QueueDequeueUpToV2", len(component_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QueueDequeueUpToV2", _inputs_flat, _attrs, _result) + return _result + + +def queue_dequeue_v2(handle: Annotated[Any, _atypes.Resource], component_types, timeout_ms:int=-1, name=None): + r"""Dequeues a tuple of one or more tensors from the given queue. + + This operation has k outputs, where k is the number of components + in the tuples stored in the given queue, and output i is the ith + component of the dequeued tuple. + + N.B. If the queue is empty, this operation will block until an element + has been dequeued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a tuple. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is empty, this operation will block for up to + timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `component_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueDequeueV2", name, handle, "component_types", + component_types, "timeout_ms", timeout_ms) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_dequeue_v2_eager_fallback( + handle, component_types=component_types, timeout_ms=timeout_ms, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueDequeueV2", handle=handle, component_types=component_types, + timeout_ms=timeout_ms, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), + "timeout_ms", _op._get_attr_int("timeout_ms")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueDequeueV2", _inputs_flat, _attrs, _result) + return _result + +QueueDequeueV2 = tf_export("raw_ops.QueueDequeueV2")(_ops.to_raw_op(queue_dequeue_v2)) + + +def queue_dequeue_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], component_types, timeout_ms: int, name, ctx): + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'queue_dequeue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = ("component_types", component_types, "timeout_ms", timeout_ms) + _result = _execute.execute(b"QueueDequeueV2", len(component_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QueueDequeueV2", _inputs_flat, _attrs, _result) + return _result + + +def queue_enqueue(handle: Annotated[Any, _atypes.String], components, timeout_ms:int=-1, name=None): + r"""Enqueues a tuple of one or more tensors in the given queue. + + The components input has k elements, which correspond to the components of + tuples stored in the given queue. + + N.B. If the queue is full, this operation will block until the given + element has been enqueued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + components: A list of `Tensor` objects. + One or more tensors from which the enqueued tensors should be taken. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is full, this operation will block for up to + timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_enqueue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueEnqueue", handle=handle, components=components, + timeout_ms=timeout_ms, name=name) + return _op +QueueEnqueue = tf_export("raw_ops.QueueEnqueue")(_ops.to_raw_op(queue_enqueue)) + + +def queue_enqueue_eager_fallback(handle: Annotated[Any, _atypes.String], components, timeout_ms: int, name, ctx): + raise RuntimeError("queue_enqueue op does not support eager execution. Arg 'handle' is a ref.") + +def queue_enqueue_many(handle: Annotated[Any, _atypes.String], components, timeout_ms:int=-1, name=None): + r"""Enqueues zero or more tuples of one or more tensors in the given queue. + + This operation slices each component tensor along the 0th dimension to + make multiple queue elements. All of the tuple components must have the + same size in the 0th dimension. + + The components input has k elements, which correspond to the components of + tuples stored in the given queue. + + N.B. If the queue is full, this operation will block until the given + elements have been enqueued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + components: A list of `Tensor` objects. + One or more tensors from which the enqueued tensors should + be taken. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is too full, this operation will block for up + to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_enqueue_many op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueEnqueueMany", handle=handle, components=components, + timeout_ms=timeout_ms, name=name) + return _op +QueueEnqueueMany = tf_export("raw_ops.QueueEnqueueMany")(_ops.to_raw_op(queue_enqueue_many)) + + +def queue_enqueue_many_eager_fallback(handle: Annotated[Any, _atypes.String], components, timeout_ms: int, name, ctx): + raise RuntimeError("queue_enqueue_many op does not support eager execution. Arg 'handle' is a ref.") + +def queue_enqueue_many_v2(handle: Annotated[Any, _atypes.Resource], components, timeout_ms:int=-1, name=None): + r"""Enqueues zero or more tuples of one or more tensors in the given queue. + + This operation slices each component tensor along the 0th dimension to + make multiple queue elements. All of the tuple components must have the + same size in the 0th dimension. + + The components input has k elements, which correspond to the components of + tuples stored in the given queue. + + N.B. If the queue is full, this operation will block until the given + elements have been enqueued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + components: A list of `Tensor` objects. + One or more tensors from which the enqueued tensors should + be taken. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is too full, this operation will block for up + to timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueEnqueueManyV2", name, handle, components, "timeout_ms", + timeout_ms) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_enqueue_many_v2_eager_fallback( + handle, components, timeout_ms=timeout_ms, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueEnqueueManyV2", handle=handle, components=components, + timeout_ms=timeout_ms, name=name) + return _op +QueueEnqueueManyV2 = tf_export("raw_ops.QueueEnqueueManyV2")(_ops.to_raw_op(queue_enqueue_many_v2)) + + +def queue_enqueue_many_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], components, timeout_ms: int, name, ctx): + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _attr_Tcomponents, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + list(components) + _attrs = ("Tcomponents", _attr_Tcomponents, "timeout_ms", timeout_ms) + _result = _execute.execute(b"QueueEnqueueManyV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def queue_enqueue_v2(handle: Annotated[Any, _atypes.Resource], components, timeout_ms:int=-1, name=None): + r"""Enqueues a tuple of one or more tensors in the given queue. + + The components input has k elements, which correspond to the components of + tuples stored in the given queue. + + N.B. If the queue is full, this operation will block until the given + element has been enqueued (or 'timeout_ms' elapses, if specified). + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + components: A list of `Tensor` objects. + One or more tensors from which the enqueued tensors should be taken. + timeout_ms: An optional `int`. Defaults to `-1`. + If the queue is full, this operation will block for up to + timeout_ms milliseconds. + Note: This option is not supported yet. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueEnqueueV2", name, handle, components, "timeout_ms", + timeout_ms) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_enqueue_v2_eager_fallback( + handle, components, timeout_ms=timeout_ms, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueEnqueueV2", handle=handle, components=components, + timeout_ms=timeout_ms, name=name) + return _op +QueueEnqueueV2 = tf_export("raw_ops.QueueEnqueueV2")(_ops.to_raw_op(queue_enqueue_v2)) + + +def queue_enqueue_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], components, timeout_ms: int, name, ctx): + if timeout_ms is None: + timeout_ms = -1 + timeout_ms = _execute.make_int(timeout_ms, "timeout_ms") + _attr_Tcomponents, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + list(components) + _attrs = ("Tcomponents", _attr_Tcomponents, "timeout_ms", timeout_ms) + _result = _execute.execute(b"QueueEnqueueV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def queue_is_closed(handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns true if queue is closed. + + This operation returns true if the queue is closed and false if the queue + is open. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_is_closed op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueIsClosed", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueIsClosed", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QueueIsClosed = tf_export("raw_ops.QueueIsClosed")(_ops.to_raw_op(queue_is_closed)) + + +def queue_is_closed_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Bool]: + raise RuntimeError("queue_is_closed op does not support eager execution. Arg 'handle' is a ref.") + +def queue_is_closed_v2(handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns true if queue is closed. + + This operation returns true if the queue is closed and false if the queue + is open. + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueIsClosedV2", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_is_closed_v2_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueIsClosedV2", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueIsClosedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QueueIsClosedV2 = tf_export("raw_ops.QueueIsClosedV2")(_ops.to_raw_op(queue_is_closed_v2)) + + +def queue_is_closed_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"QueueIsClosedV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QueueIsClosedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def queue_size(handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Computes the number of elements in the given queue. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a queue. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("queue_size op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueSize", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QueueSize = tf_export("raw_ops.QueueSize")(_ops.to_raw_op(queue_size)) + + +def queue_size_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("queue_size op does not support eager execution. Arg 'handle' is a ref.") + +def queue_size_v2(handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Computes the number of elements in the given queue. + + Args: + handle: A `Tensor` of type `resource`. The handle to a queue. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QueueSizeV2", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return queue_size_v2_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QueueSizeV2", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "QueueSizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QueueSizeV2 = tf_export("raw_ops.QueueSizeV2")(_ops.to_raw_op(queue_size_v2)) + + +def queue_size_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Int32]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"QueueSizeV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QueueSizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def random_shuffle_queue(component_types, shapes=[], capacity:int=-1, min_after_dequeue:int=0, seed:int=0, seed2:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A queue that randomizes the order of elements. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + min_after_dequeue: An optional `int`. Defaults to `0`. + Dequeue will block unless there would be this + many elements after the dequeue or the queue is closed. This + ensures a minimum level of mixing of elements. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 is set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, a random seed is used. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("random_shuffle_queue op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'random_shuffle_queue' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'random_shuffle_queue' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if min_after_dequeue is None: + min_after_dequeue = 0 + min_after_dequeue = _execute.make_int(min_after_dequeue, "min_after_dequeue") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomShuffleQueue", component_types=component_types, shapes=shapes, + capacity=capacity, + min_after_dequeue=min_after_dequeue, seed=seed, + seed2=seed2, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "min_after_dequeue", + _op._get_attr_int("min_after_dequeue"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomShuffleQueue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomShuffleQueue = tf_export("raw_ops.RandomShuffleQueue")(_ops.to_raw_op(random_shuffle_queue)) + + +def random_shuffle_queue_eager_fallback(component_types, shapes, capacity: int, min_after_dequeue: int, seed: int, seed2: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("random_shuffle_queue op does not support eager execution. Arg 'handle' is a ref.") + +def random_shuffle_queue_v2(component_types, shapes=[], capacity:int=-1, min_after_dequeue:int=0, seed:int=0, seed2:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A queue that randomizes the order of elements. + + Args: + component_types: A list of `tf.DTypes` that has length `>= 1`. + The type of each component in a value. + shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The shape of each component in a value. The length of this attr must + be either 0 or the same as the length of component_types. If the length of + this attr is 0, the shapes of queue elements are not constrained, and + only one element may be dequeued at a time. + capacity: An optional `int`. Defaults to `-1`. + The upper bound on the number of elements in this queue. + Negative numbers mean no limit. + min_after_dequeue: An optional `int`. Defaults to `0`. + Dequeue will block unless there would be this + many elements after the dequeue or the queue is closed. This + ensures a minimum level of mixing of elements. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 is set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, a random seed is used. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this queue will be shared under the given name + across multiple sessions. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomShuffleQueueV2", name, "component_types", + component_types, "shapes", shapes, "capacity", capacity, + "min_after_dequeue", min_after_dequeue, "seed", seed, "seed2", seed2, + "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_shuffle_queue_v2_eager_fallback( + component_types=component_types, shapes=shapes, capacity=capacity, + min_after_dequeue=min_after_dequeue, seed=seed, seed2=seed2, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'random_shuffle_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'random_shuffle_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if min_after_dequeue is None: + min_after_dequeue = 0 + min_after_dequeue = _execute.make_int(min_after_dequeue, "min_after_dequeue") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomShuffleQueueV2", component_types=component_types, + shapes=shapes, capacity=capacity, + min_after_dequeue=min_after_dequeue, + seed=seed, seed2=seed2, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("component_types", _op.get_attr("component_types"), "shapes", + _op.get_attr("shapes"), "capacity", + _op._get_attr_int("capacity"), "min_after_dequeue", + _op._get_attr_int("min_after_dequeue"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomShuffleQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomShuffleQueueV2 = tf_export("raw_ops.RandomShuffleQueueV2")(_ops.to_raw_op(random_shuffle_queue_v2)) + + +def random_shuffle_queue_v2_eager_fallback(component_types, shapes, capacity: int, min_after_dequeue: int, seed: int, seed2: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(component_types, (list, tuple)): + raise TypeError( + "Expected list for 'component_types' argument to " + "'random_shuffle_queue_v2' Op, not %r." % component_types) + component_types = [_execute.make_type(_t, "component_types") for _t in component_types] + if shapes is None: + shapes = [] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'random_shuffle_queue_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if capacity is None: + capacity = -1 + capacity = _execute.make_int(capacity, "capacity") + if min_after_dequeue is None: + min_after_dequeue = 0 + min_after_dequeue = _execute.make_int(min_after_dequeue, "min_after_dequeue") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("component_types", component_types, "shapes", shapes, "capacity", + capacity, "min_after_dequeue", min_after_dequeue, "seed", seed, "seed2", + seed2, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"RandomShuffleQueueV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomShuffleQueueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def record_input(file_pattern: str, file_random_seed:int=301, file_shuffle_shift_ratio:float=0, file_buffer_size:int=10000, file_parallelism:int=16, batch_size:int=32, compression_type:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Emits randomized records. + + Args: + file_pattern: A `string`. Glob pattern for the data files. + file_random_seed: An optional `int`. Defaults to `301`. + Random seeds used to produce randomized records. + file_shuffle_shift_ratio: An optional `float`. Defaults to `0`. + Shifts the list of files after the list is randomly + shuffled. + file_buffer_size: An optional `int`. Defaults to `10000`. + The randomization shuffling buffer. + file_parallelism: An optional `int`. Defaults to `16`. + How many sstables are opened and concurrently iterated over. + batch_size: An optional `int`. Defaults to `32`. The batch size. + compression_type: An optional `string`. Defaults to `""`. + The type of compression for the file. Currently ZLIB and + GZIP are supported. Defaults to none. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RecordInput", name, "file_pattern", file_pattern, + "file_random_seed", file_random_seed, "file_shuffle_shift_ratio", + file_shuffle_shift_ratio, "file_buffer_size", file_buffer_size, + "file_parallelism", file_parallelism, "batch_size", batch_size, + "compression_type", compression_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return record_input_eager_fallback( + file_pattern=file_pattern, file_random_seed=file_random_seed, + file_shuffle_shift_ratio=file_shuffle_shift_ratio, + file_buffer_size=file_buffer_size, + file_parallelism=file_parallelism, batch_size=batch_size, + compression_type=compression_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + file_pattern = _execute.make_str(file_pattern, "file_pattern") + if file_random_seed is None: + file_random_seed = 301 + file_random_seed = _execute.make_int(file_random_seed, "file_random_seed") + if file_shuffle_shift_ratio is None: + file_shuffle_shift_ratio = 0 + file_shuffle_shift_ratio = _execute.make_float(file_shuffle_shift_ratio, "file_shuffle_shift_ratio") + if file_buffer_size is None: + file_buffer_size = 10000 + file_buffer_size = _execute.make_int(file_buffer_size, "file_buffer_size") + if file_parallelism is None: + file_parallelism = 16 + file_parallelism = _execute.make_int(file_parallelism, "file_parallelism") + if batch_size is None: + batch_size = 32 + batch_size = _execute.make_int(batch_size, "batch_size") + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RecordInput", file_pattern=file_pattern, + file_random_seed=file_random_seed, + file_shuffle_shift_ratio=file_shuffle_shift_ratio, + file_buffer_size=file_buffer_size, + file_parallelism=file_parallelism, + batch_size=batch_size, + compression_type=compression_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("file_pattern", _op.get_attr("file_pattern"), + "file_random_seed", _op._get_attr_int("file_random_seed"), + "file_shuffle_shift_ratio", + _op.get_attr("file_shuffle_shift_ratio"), "file_buffer_size", + _op._get_attr_int("file_buffer_size"), "file_parallelism", + _op._get_attr_int("file_parallelism"), "batch_size", + _op._get_attr_int("batch_size"), "compression_type", + _op.get_attr("compression_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RecordInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RecordInput = tf_export("raw_ops.RecordInput")(_ops.to_raw_op(record_input)) + + +def record_input_eager_fallback(file_pattern: str, file_random_seed: int, file_shuffle_shift_ratio: float, file_buffer_size: int, file_parallelism: int, batch_size: int, compression_type: str, name, ctx) -> Annotated[Any, _atypes.String]: + file_pattern = _execute.make_str(file_pattern, "file_pattern") + if file_random_seed is None: + file_random_seed = 301 + file_random_seed = _execute.make_int(file_random_seed, "file_random_seed") + if file_shuffle_shift_ratio is None: + file_shuffle_shift_ratio = 0 + file_shuffle_shift_ratio = _execute.make_float(file_shuffle_shift_ratio, "file_shuffle_shift_ratio") + if file_buffer_size is None: + file_buffer_size = 10000 + file_buffer_size = _execute.make_int(file_buffer_size, "file_buffer_size") + if file_parallelism is None: + file_parallelism = 16 + file_parallelism = _execute.make_int(file_parallelism, "file_parallelism") + if batch_size is None: + batch_size = 32 + batch_size = _execute.make_int(batch_size, "batch_size") + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + _inputs_flat = [] + _attrs = ("file_pattern", file_pattern, "file_random_seed", + file_random_seed, "file_shuffle_shift_ratio", file_shuffle_shift_ratio, + "file_buffer_size", file_buffer_size, "file_parallelism", file_parallelism, + "batch_size", batch_size, "compression_type", compression_type) + _result = _execute.execute(b"RecordInput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RecordInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceAccumulatorApplyGradient_dtype = TypeVar("TV_ResourceAccumulatorApplyGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_accumulator_apply_gradient(handle: Annotated[Any, _atypes.Resource], local_step: Annotated[Any, _atypes.Int64], gradient: Annotated[Any, TV_ResourceAccumulatorApplyGradient_dtype], name=None): + r"""Applies a gradient to a given accumulator. + + Does not add if local_step is lesser than the accumulator's global_step. + + Args: + handle: A `Tensor` of type `resource`. The handle to a accumulator. + local_step: A `Tensor` of type `int64`. + The local_step value at which the gradient was computed. + gradient: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of the gradient to be accumulated. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceAccumulatorApplyGradient", name, handle, local_step, + gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_accumulator_apply_gradient_eager_fallback( + handle, local_step, gradient, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceAccumulatorApplyGradient", handle=handle, + local_step=local_step, + gradient=gradient, name=name) + return _op +ResourceAccumulatorApplyGradient = tf_export("raw_ops.ResourceAccumulatorApplyGradient")(_ops.to_raw_op(resource_accumulator_apply_gradient)) + + +def resource_accumulator_apply_gradient_eager_fallback(handle: Annotated[Any, _atypes.Resource], local_step: Annotated[Any, _atypes.Int64], gradient: Annotated[Any, TV_ResourceAccumulatorApplyGradient_dtype], name, ctx): + _attr_dtype, (gradient,) = _execute.args_to_matching_eager([gradient], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + local_step = _ops.convert_to_tensor(local_step, _dtypes.int64) + _inputs_flat = [handle, local_step, gradient] + _attrs = ("dtype", _attr_dtype) + _result = _execute.execute(b"ResourceAccumulatorApplyGradient", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def resource_accumulator_num_accumulated(handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the number of gradients aggregated in the given accumulators. + + Args: + handle: A `Tensor` of type `resource`. The handle to an accumulator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceAccumulatorNumAccumulated", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_accumulator_num_accumulated_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceAccumulatorNumAccumulated", handle=handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceAccumulatorNumAccumulated", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceAccumulatorNumAccumulated = tf_export("raw_ops.ResourceAccumulatorNumAccumulated")(_ops.to_raw_op(resource_accumulator_num_accumulated)) + + +def resource_accumulator_num_accumulated_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Int32]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"ResourceAccumulatorNumAccumulated", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceAccumulatorNumAccumulated", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def resource_accumulator_set_global_step(handle: Annotated[Any, _atypes.Resource], new_global_step: Annotated[Any, _atypes.Int64], name=None): + r"""Updates the accumulator with a new value for global_step. + + Logs warning if the accumulator's value is already higher than + new_global_step. + + Args: + handle: A `Tensor` of type `resource`. The handle to an accumulator. + new_global_step: A `Tensor` of type `int64`. + The new global_step value to set. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceAccumulatorSetGlobalStep", name, handle, + new_global_step) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_accumulator_set_global_step_eager_fallback( + handle, new_global_step, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceAccumulatorSetGlobalStep", handle=handle, + new_global_step=new_global_step, + name=name) + return _op +ResourceAccumulatorSetGlobalStep = tf_export("raw_ops.ResourceAccumulatorSetGlobalStep")(_ops.to_raw_op(resource_accumulator_set_global_step)) + + +def resource_accumulator_set_global_step_eager_fallback(handle: Annotated[Any, _atypes.Resource], new_global_step: Annotated[Any, _atypes.Int64], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + new_global_step = _ops.convert_to_tensor(new_global_step, _dtypes.int64) + _inputs_flat = [handle, new_global_step] + _attrs = None + _result = _execute.execute(b"ResourceAccumulatorSetGlobalStep", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceAccumulatorTakeGradient_dtype = TypeVar("TV_ResourceAccumulatorTakeGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_accumulator_take_gradient(handle: Annotated[Any, _atypes.Resource], num_required: Annotated[Any, _atypes.Int32], dtype: TV_ResourceAccumulatorTakeGradient_dtype, name=None) -> Annotated[Any, TV_ResourceAccumulatorTakeGradient_dtype]: + r"""Extracts the average gradient in the given ConditionalAccumulator. + + The op blocks until sufficient (i.e., more than num_required) + gradients have been accumulated. If the accumulator has already + aggregated more than num_required gradients, it returns the average of + the accumulated gradients. Also automatically increments the recorded + global_step in the accumulator by 1, and resets the aggregate to 0. + + Args: + handle: A `Tensor` of type `resource`. The handle to an accumulator. + num_required: A `Tensor` of type `int32`. + Number of gradients required before we return an aggregate. + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The data type of accumulated gradients. Needs to correspond to the type + of the accumulator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceAccumulatorTakeGradient", name, handle, num_required, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_accumulator_take_gradient_eager_fallback( + handle, num_required, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceAccumulatorTakeGradient", handle=handle, + num_required=num_required, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceAccumulatorTakeGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceAccumulatorTakeGradient = tf_export("raw_ops.ResourceAccumulatorTakeGradient")(_ops.to_raw_op(resource_accumulator_take_gradient)) + + +def resource_accumulator_take_gradient_eager_fallback(handle: Annotated[Any, _atypes.Resource], num_required: Annotated[Any, _atypes.Int32], dtype: TV_ResourceAccumulatorTakeGradient_dtype, name, ctx) -> Annotated[Any, TV_ResourceAccumulatorTakeGradient_dtype]: + dtype = _execute.make_type(dtype, "dtype") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + num_required = _ops.convert_to_tensor(num_required, _dtypes.int32) + _inputs_flat = [handle, num_required] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"ResourceAccumulatorTakeGradient", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceAccumulatorTakeGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceConditionalAccumulator_dtype = TypeVar("TV_ResourceConditionalAccumulator_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_conditional_accumulator(dtype: TV_ResourceConditionalAccumulator_dtype, shape, container:str="", shared_name:str="", reduction_type:str="MEAN", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A conditional accumulator for aggregating gradients. + + The accumulator accepts gradients marked with local_step greater or + equal to the most recent global_step known to the accumulator. The + average can be extracted from the accumulator, provided sufficient + gradients have been accumulated. Extracting the average automatically + resets the aggregate to 0, and increments the global_step recorded by + the accumulator. + This is a resource version of ConditionalAccumulator that will work in TF2.0 + with tf.cond version 2. + + Args: + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The type of the value being accumulated. + shape: A `tf.TensorShape` or list of `ints`. + The shape of the values, can be [], in which case shape is unknown. + container: An optional `string`. Defaults to `""`. + If non-empty, this accumulator is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this accumulator will be shared under the + given name across multiple sessions. + reduction_type: An optional `string` from: `"MEAN", "SUM"`. Defaults to `"MEAN"`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceConditionalAccumulator", name, "dtype", dtype, "shape", + shape, "container", container, "shared_name", shared_name, + "reduction_type", reduction_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_conditional_accumulator_eager_fallback( + dtype=dtype, shape=shape, container=container, + shared_name=shared_name, reduction_type=reduction_type, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if reduction_type is None: + reduction_type = "MEAN" + reduction_type = _execute.make_str(reduction_type, "reduction_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceConditionalAccumulator", dtype=dtype, shape=shape, + container=container, + shared_name=shared_name, + reduction_type=reduction_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name"), "reduction_type", + _op.get_attr("reduction_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceConditionalAccumulator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceConditionalAccumulator = tf_export("raw_ops.ResourceConditionalAccumulator")(_ops.to_raw_op(resource_conditional_accumulator)) + + +def resource_conditional_accumulator_eager_fallback(dtype: TV_ResourceConditionalAccumulator_dtype, shape, container: str, shared_name: str, reduction_type: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if reduction_type is None: + reduction_type = "MEAN" + reduction_type = _execute.make_str(reduction_type, "reduction_type") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape, "container", container, + "shared_name", shared_name, "reduction_type", reduction_type) + _result = _execute.execute(b"ResourceConditionalAccumulator", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceConditionalAccumulator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseAccumulatorApplyGradient_dtype = TypeVar("TV_SparseAccumulatorApplyGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_accumulator_apply_gradient(handle: Annotated[Any, _atypes.String], local_step: Annotated[Any, _atypes.Int64], gradient_indices: Annotated[Any, _atypes.Int64], gradient_values: Annotated[Any, TV_SparseAccumulatorApplyGradient_dtype], gradient_shape: Annotated[Any, _atypes.Int64], has_known_shape: bool, name=None): + r"""Applies a sparse gradient to a given accumulator. + + Does not add if local_step is smaller than the accumulator's + global_step. + + Args: + handle: A `Tensor` of type mutable `string`. The handle to a accumulator. + local_step: A `Tensor` of type `int64`. + The local_step value at which the sparse gradient was computed. + gradient_indices: A `Tensor` of type `int64`. + Indices of the sparse gradient to be accumulated. Must be a + vector. + gradient_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Values are the non-zero slices of the gradient, and must have + the same first dimension as indices, i.e., the nnz represented by indices and + values must be consistent. + gradient_shape: A `Tensor` of type `int64`. + Shape of the sparse gradient to be accumulated. + has_known_shape: A `bool`. + Boolean indicating whether gradient_shape is unknown, in which + case the input is ignored during validation. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_accumulator_apply_gradient op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + has_known_shape = _execute.make_bool(has_known_shape, "has_known_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseAccumulatorApplyGradient", handle=handle, + local_step=local_step, + gradient_indices=gradient_indices, + gradient_values=gradient_values, + gradient_shape=gradient_shape, + has_known_shape=has_known_shape, + name=name) + return _op +SparseAccumulatorApplyGradient = tf_export("raw_ops.SparseAccumulatorApplyGradient")(_ops.to_raw_op(sparse_accumulator_apply_gradient)) + + +def sparse_accumulator_apply_gradient_eager_fallback(handle: Annotated[Any, _atypes.String], local_step: Annotated[Any, _atypes.Int64], gradient_indices: Annotated[Any, _atypes.Int64], gradient_values: Annotated[Any, TV_SparseAccumulatorApplyGradient_dtype], gradient_shape: Annotated[Any, _atypes.Int64], has_known_shape: bool, name, ctx): + raise RuntimeError("sparse_accumulator_apply_gradient op does not support eager execution. Arg 'handle' is a ref.") +_SparseAccumulatorTakeGradientOutput = collections.namedtuple( + "SparseAccumulatorTakeGradient", + ["indices", "values", "shape"]) + + +TV_SparseAccumulatorTakeGradient_dtype = TypeVar("TV_SparseAccumulatorTakeGradient_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_accumulator_take_gradient(handle: Annotated[Any, _atypes.String], num_required: Annotated[Any, _atypes.Int32], dtype: TV_SparseAccumulatorTakeGradient_dtype, name=None): + r"""Extracts the average sparse gradient in a SparseConditionalAccumulator. + + The op will blocks until sufficient (i.e., more than num_required) + gradients have been accumulated. If the accumulator has already + aggregated more than num_required gradients, it will return its + average of the accumulated gradients. Also automatically increments + the recorded global_step in the accumulator by 1, and resets the + aggregate to 0. + + Args: + handle: A `Tensor` of type mutable `string`. + The handle to a SparseConditionalAccumulator. + num_required: A `Tensor` of type `int32`. + Number of gradients required before we return an aggregate. + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The data type of accumulated gradients. Needs to correspond to the type + of the accumulator. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, values, shape). + + indices: A `Tensor` of type `int64`. + values: A `Tensor` of type `dtype`. + shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_accumulator_take_gradient op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseAccumulatorTakeGradient", handle=handle, + num_required=num_required, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseAccumulatorTakeGradient", _inputs_flat, _attrs, _result) + _result = _SparseAccumulatorTakeGradientOutput._make(_result) + return _result + +SparseAccumulatorTakeGradient = tf_export("raw_ops.SparseAccumulatorTakeGradient")(_ops.to_raw_op(sparse_accumulator_take_gradient)) + + +def sparse_accumulator_take_gradient_eager_fallback(handle: Annotated[Any, _atypes.String], num_required: Annotated[Any, _atypes.Int32], dtype: TV_SparseAccumulatorTakeGradient_dtype, name, ctx): + raise RuntimeError("sparse_accumulator_take_gradient op does not support eager execution. Arg 'handle' is a ref.") + +TV_SparseConditionalAccumulator_dtype = TypeVar("TV_SparseConditionalAccumulator_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_conditional_accumulator(dtype: TV_SparseConditionalAccumulator_dtype, shape, container:str="", shared_name:str="", reduction_type:str="MEAN", name=None) -> Annotated[Any, _atypes.String]: + r"""A conditional accumulator for aggregating sparse gradients. + + The accumulator accepts gradients marked with local_step greater or + equal to the most recent global_step known to the accumulator. The + average can be extracted from the accumulator, provided sufficient + gradients have been accumulated. Extracting the average automatically + resets the aggregate to 0, and increments the global_step recorded by + the accumulator. + + Args: + dtype: A `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.uint8, tf.int16, tf.int8, tf.complex64, tf.int64, tf.qint8, tf.quint8, tf.qint32, tf.bfloat16, tf.qint16, tf.quint16, tf.uint16, tf.complex128, tf.half, tf.uint32, tf.uint64`. + The type of the value being accumulated. + shape: A `tf.TensorShape` or list of `ints`. The shape of the values. + container: An optional `string`. Defaults to `""`. + If non-empty, this accumulator is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this accumulator will be shared under the given name + across multiple sessions. + reduction_type: An optional `string` from: `"MEAN", "SUM"`. Defaults to `"MEAN"`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_conditional_accumulator op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if reduction_type is None: + reduction_type = "MEAN" + reduction_type = _execute.make_str(reduction_type, "reduction_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseConditionalAccumulator", dtype=dtype, shape=shape, + container=container, + shared_name=shared_name, + reduction_type=reduction_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name"), "reduction_type", + _op.get_attr("reduction_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseConditionalAccumulator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseConditionalAccumulator = tf_export("raw_ops.SparseConditionalAccumulator")(_ops.to_raw_op(sparse_conditional_accumulator)) + + +def sparse_conditional_accumulator_eager_fallback(dtype: TV_SparseConditionalAccumulator_dtype, shape, container: str, shared_name: str, reduction_type: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("sparse_conditional_accumulator op does not support eager execution. Arg 'handle' is a ref.") + +TV_Stack_elem_type = TypeVar("TV_Stack_elem_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def _stack(elem_type: TV_Stack_elem_type, stack_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Deprecated, use StackV2. + + Args: + elem_type: A `tf.DType`. + stack_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("stack op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + elem_type = _execute.make_type(elem_type, "elem_type") + if stack_name is None: + stack_name = "" + stack_name = _execute.make_str(stack_name, "stack_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Stack", elem_type=elem_type, stack_name=stack_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("elem_type", _op._get_attr_type("elem_type"), "stack_name", + _op.get_attr("stack_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Stack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Stack = tf_export("raw_ops.Stack")(_ops.to_raw_op(_stack)) + + +def _stack_eager_fallback(elem_type: TV_Stack_elem_type, stack_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("stack op does not support eager execution. Arg 'handle' is a ref.") + +def stack_close(handle: Annotated[Any, _atypes.String], name=None): + r"""Deprecated, use StackCloseV2. + + Args: + handle: A `Tensor` of type mutable `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("stack_close op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackClose", handle=handle, name=name) + return _op +StackClose = tf_export("raw_ops.StackClose")(_ops.to_raw_op(stack_close)) + + +def stack_close_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx): + raise RuntimeError("stack_close op does not support eager execution. Arg 'handle' is a ref.") + +def stack_close_v2(handle: Annotated[Any, _atypes.Resource], name=None): + r"""Delete the stack from its resource container. + + Args: + handle: A `Tensor` of type `resource`. The handle to a stack. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StackCloseV2", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stack_close_v2_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackCloseV2", handle=handle, name=name) + return _op +StackCloseV2 = tf_export("raw_ops.StackCloseV2")(_ops.to_raw_op(stack_close_v2)) + + +def stack_close_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"StackCloseV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_StackPop_elem_type = TypeVar("TV_StackPop_elem_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stack_pop(handle: Annotated[Any, _atypes.String], elem_type: TV_StackPop_elem_type, name=None) -> Annotated[Any, TV_StackPop_elem_type]: + r"""Deprecated, use StackPopV2. + + Args: + handle: A `Tensor` of type mutable `string`. + elem_type: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `elem_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("stack_pop op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + elem_type = _execute.make_type(elem_type, "elem_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackPop", handle=handle, elem_type=elem_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("elem_type", _op._get_attr_type("elem_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StackPop", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StackPop = tf_export("raw_ops.StackPop")(_ops.to_raw_op(stack_pop)) + + +def stack_pop_eager_fallback(handle: Annotated[Any, _atypes.String], elem_type: TV_StackPop_elem_type, name, ctx) -> Annotated[Any, TV_StackPop_elem_type]: + raise RuntimeError("stack_pop op does not support eager execution. Arg 'handle' is a ref.") + +TV_StackPopV2_elem_type = TypeVar("TV_StackPopV2_elem_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stack_pop_v2(handle: Annotated[Any, _atypes.Resource], elem_type: TV_StackPopV2_elem_type, name=None) -> Annotated[Any, TV_StackPopV2_elem_type]: + r"""Pop the element at the top of the stack. + + Args: + handle: A `Tensor` of type `resource`. The handle to a stack. + elem_type: A `tf.DType`. The type of the elem that is popped. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `elem_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StackPopV2", name, handle, "elem_type", elem_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stack_pop_v2_eager_fallback( + handle, elem_type=elem_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + elem_type = _execute.make_type(elem_type, "elem_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackPopV2", handle=handle, elem_type=elem_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("elem_type", _op._get_attr_type("elem_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StackPopV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StackPopV2 = tf_export("raw_ops.StackPopV2")(_ops.to_raw_op(stack_pop_v2)) + + +def stack_pop_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], elem_type: TV_StackPopV2_elem_type, name, ctx) -> Annotated[Any, TV_StackPopV2_elem_type]: + elem_type = _execute.make_type(elem_type, "elem_type") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = ("elem_type", elem_type) + _result = _execute.execute(b"StackPopV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StackPopV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StackPush_T = TypeVar("TV_StackPush_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stack_push(handle: Annotated[Any, _atypes.String], elem: Annotated[Any, TV_StackPush_T], swap_memory:bool=False, name=None) -> Annotated[Any, TV_StackPush_T]: + r"""Deprecated, use StackPushV2. + + Args: + handle: A `Tensor` of type mutable `string`. + elem: A `Tensor`. + swap_memory: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `elem`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("stack_push op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + if swap_memory is None: + swap_memory = False + swap_memory = _execute.make_bool(swap_memory, "swap_memory") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackPush", handle=handle, elem=elem, swap_memory=swap_memory, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "swap_memory", + _op._get_attr_bool("swap_memory")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StackPush", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StackPush = tf_export("raw_ops.StackPush")(_ops.to_raw_op(stack_push)) + + +def stack_push_eager_fallback(handle: Annotated[Any, _atypes.String], elem: Annotated[Any, TV_StackPush_T], swap_memory: bool, name, ctx) -> Annotated[Any, TV_StackPush_T]: + raise RuntimeError("stack_push op does not support eager execution. Arg 'handle' is a ref.") + +TV_StackPushV2_T = TypeVar("TV_StackPushV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stack_push_v2(handle: Annotated[Any, _atypes.Resource], elem: Annotated[Any, TV_StackPushV2_T], swap_memory:bool=False, name=None) -> Annotated[Any, TV_StackPushV2_T]: + r"""Push an element onto the stack. + + Args: + handle: A `Tensor` of type `resource`. The handle to a stack. + elem: A `Tensor`. The tensor to be pushed onto the stack. + swap_memory: An optional `bool`. Defaults to `False`. + Swap `elem` to CPU. Default to false. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `elem`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StackPushV2", name, handle, elem, "swap_memory", swap_memory) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stack_push_v2_eager_fallback( + handle, elem, swap_memory=swap_memory, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if swap_memory is None: + swap_memory = False + swap_memory = _execute.make_bool(swap_memory, "swap_memory") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackPushV2", handle=handle, elem=elem, swap_memory=swap_memory, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "swap_memory", + _op._get_attr_bool("swap_memory")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StackPushV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StackPushV2 = tf_export("raw_ops.StackPushV2")(_ops.to_raw_op(stack_push_v2)) + + +def stack_push_v2_eager_fallback(handle: Annotated[Any, _atypes.Resource], elem: Annotated[Any, TV_StackPushV2_T], swap_memory: bool, name, ctx) -> Annotated[Any, TV_StackPushV2_T]: + if swap_memory is None: + swap_memory = False + swap_memory = _execute.make_bool(swap_memory, "swap_memory") + _attr_T, (elem,) = _execute.args_to_matching_eager([elem], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle, elem] + _attrs = ("T", _attr_T, "swap_memory", swap_memory) + _result = _execute.execute(b"StackPushV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StackPushV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StackV2_elem_type = TypeVar("TV_StackV2_elem_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stack_v2(max_size: Annotated[Any, _atypes.Int32], elem_type: TV_StackV2_elem_type, stack_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A stack that produces elements in first-in last-out order. + + Args: + max_size: A `Tensor` of type `int32`. + The maximum size of the stack if non-negative. If negative, the stack + size is unlimited. + elem_type: A `tf.DType`. The type of the elements on the stack. + stack_name: An optional `string`. Defaults to `""`. + Overrides the name used for the temporary stack resource. Default + value is the name of the 'Stack' op (which is guaranteed unique). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StackV2", name, max_size, "elem_type", elem_type, "stack_name", + stack_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stack_v2_eager_fallback( + max_size, elem_type=elem_type, stack_name=stack_name, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + elem_type = _execute.make_type(elem_type, "elem_type") + if stack_name is None: + stack_name = "" + stack_name = _execute.make_str(stack_name, "stack_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StackV2", max_size=max_size, elem_type=elem_type, + stack_name=stack_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("elem_type", _op._get_attr_type("elem_type"), "stack_name", + _op.get_attr("stack_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StackV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StackV2 = tf_export("raw_ops.StackV2")(_ops.to_raw_op(stack_v2)) + + +def stack_v2_eager_fallback(max_size: Annotated[Any, _atypes.Int32], elem_type: TV_StackV2_elem_type, stack_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + elem_type = _execute.make_type(elem_type, "elem_type") + if stack_name is None: + stack_name = "" + stack_name = _execute.make_str(stack_name, "stack_name") + max_size = _ops.convert_to_tensor(max_size, _dtypes.int32) + _inputs_flat = [max_size] + _attrs = ("elem_type", elem_type, "stack_name", stack_name) + _result = _execute.execute(b"StackV2", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StackV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def stage(values, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Stage values similar to a lightweight Enqueue. + + The basic functionality of this Op is similar to a queue with many + fewer capabilities and options. This Op is optimized for performance. + + Args: + values: A list of `Tensor` objects. a list of tensors + dtypes A list of data types that inserted values should adhere to. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + Maximum number of elements in the Staging Area. If > 0, inserts + on the container will block when the capacity is reached. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + The maximum number of bytes allowed for Tensors in the Staging Area. + If > 0, inserts will block until sufficient space is available. + container: An optional `string`. Defaults to `""`. + If non-empty, this queue is placed in the given container. Otherwise, + a default container is used. + shared_name: An optional `string`. Defaults to `""`. + It is necessary to match this name to the matching Unstage Op. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Stage", name, values, "capacity", capacity, "memory_limit", + memory_limit, "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stage_eager_fallback( + values, capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Stage", values=values, capacity=capacity, memory_limit=memory_limit, + container=container, shared_name=shared_name, name=name) + return _op +Stage = tf_export("raw_ops.Stage")(_ops.to_raw_op(stage)) + + +def stage_eager_fallback(values, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_dtypes, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + _inputs_flat = list(values) + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + _attr_dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"Stage", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +def stage_clear(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op removes all elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StageClear", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stage_clear_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StageClear", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + return _op +StageClear = tf_export("raw_ops.StageClear")(_ops.to_raw_op(stage_clear)) + + +def stage_clear_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_clear' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"StageClear", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def stage_peek(index: Annotated[Any, _atypes.Int32], dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op peeks at the values at the specified index. If the + + underlying container does not contain sufficient elements + this op will block until it does. This Op is optimized for + performance. + + Args: + index: A `Tensor` of type `int32`. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StagePeek", name, index, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stage_peek_eager_fallback( + index, capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StagePeek", index=index, dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StagePeek", _inputs_flat, _attrs, _result) + return _result + +StagePeek = tf_export("raw_ops.StagePeek")(_ops.to_raw_op(stage_peek)) + + +def stage_peek_eager_fallback(index: Annotated[Any, _atypes.Int32], dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_peek' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + index = _ops.convert_to_tensor(index, _dtypes.int32) + _inputs_flat = [index] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"StagePeek", len(dtypes), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StagePeek", _inputs_flat, _attrs, _result) + return _result + + +def stage_size(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int32]: + r"""Op returns the number of elements in the underlying container. + + Args: + dtypes: A list of `tf.DTypes`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StageSize", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stage_size_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StageSize", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StageSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StageSize = tf_export("raw_ops.StageSize")(_ops.to_raw_op(stage_size)) + + +def stage_size_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'stage_size' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"StageSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StageSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArray_dtype = TypeVar("TV_TensorArray_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArray_dtype, dynamic_size:bool=False, clear_after_read:bool=True, tensor_array_name:str="", element_shape=None, name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + size: A `Tensor` of type `int32`. + dtype: A `tf.DType`. + dynamic_size: An optional `bool`. Defaults to `False`. + clear_after_read: An optional `bool`. Defaults to `True`. + tensor_array_name: An optional `string`. Defaults to `""`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if dynamic_size is None: + dynamic_size = False + dynamic_size = _execute.make_bool(dynamic_size, "dynamic_size") + if clear_after_read is None: + clear_after_read = True + clear_after_read = _execute.make_bool(clear_after_read, "clear_after_read") + if tensor_array_name is None: + tensor_array_name = "" + tensor_array_name = _execute.make_str(tensor_array_name, "tensor_array_name") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArray", size=size, dtype=dtype, dynamic_size=dynamic_size, + clear_after_read=clear_after_read, + tensor_array_name=tensor_array_name, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "dynamic_size", + _op._get_attr_bool("dynamic_size"), "clear_after_read", + _op._get_attr_bool("clear_after_read"), "tensor_array_name", + _op.get_attr("tensor_array_name"), "element_shape", + _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArray", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArray = tf_export("raw_ops.TensorArray")(_ops.to_raw_op(tensor_array)) + + +def tensor_array_eager_fallback(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArray_dtype, dynamic_size: bool, clear_after_read: bool, tensor_array_name: str, element_shape, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("tensor_array op does not support eager execution. Arg 'handle' is a ref.") + +def tensor_array_close(handle: Annotated[Any, _atypes.String], name=None): + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_close op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayClose", handle=handle, name=name) + return _op +TensorArrayClose = tf_export("raw_ops.TensorArrayClose")(_ops.to_raw_op(tensor_array_close)) + + +def tensor_array_close_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx): + raise RuntimeError("tensor_array_close op does not support eager execution. Arg 'handle' is a ref.") + +def tensor_array_close_v2(handle: Annotated[Any, _atypes.String], name=None): + r"""Deprecated. Use TensorArrayCloseV3 + + Args: + handle: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayCloseV2", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_close_v2_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayCloseV2", handle=handle, name=name) + return _op +TensorArrayCloseV2 = tf_export("raw_ops.TensorArrayCloseV2")(_ops.to_raw_op(tensor_array_close_v2)) + + +def tensor_array_close_v2_eager_fallback(handle: Annotated[Any, _atypes.String], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.string) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"TensorArrayCloseV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def tensor_array_close_v3(handle: Annotated[Any, _atypes.Resource], name=None): + r"""Delete the TensorArray from its resource container. + + This enables the user to close and release the resource in the middle + of a step/run. + + Args: + handle: A `Tensor` of type `resource`. + The handle to a TensorArray (output of TensorArray or TensorArrayGrad). + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayCloseV3", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_close_v3_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayCloseV3", handle=handle, name=name) + return _op +TensorArrayCloseV3 = tf_export("raw_ops.TensorArrayCloseV3")(_ops.to_raw_op(tensor_array_close_v3)) + + +def tensor_array_close_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"TensorArrayCloseV3", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + +_TensorArrayConcatOutput = collections.namedtuple( + "TensorArrayConcat", + ["value", "lengths"]) + + +TV_TensorArrayConcat_dtype = TypeVar("TV_TensorArrayConcat_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_concat(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcat_dtype, element_shape_except0=None, name=None): + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + element_shape_except0: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (value, lengths). + + value: A `Tensor` of type `dtype`. + lengths: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_concat op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape_except0 is None: + element_shape_except0 = None + element_shape_except0 = _execute.make_shape(element_shape_except0, "element_shape_except0") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayConcat", handle=handle, flow_in=flow_in, dtype=dtype, + element_shape_except0=element_shape_except0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape_except0", + _op.get_attr("element_shape_except0")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayConcat", _inputs_flat, _attrs, _result) + _result = _TensorArrayConcatOutput._make(_result) + return _result + +TensorArrayConcat = tf_export("raw_ops.TensorArrayConcat")(_ops.to_raw_op(tensor_array_concat)) + + +def tensor_array_concat_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcat_dtype, element_shape_except0, name, ctx): + raise RuntimeError("tensor_array_concat op does not support eager execution. Arg 'handle' is a ref.") +_TensorArrayConcatV2Output = collections.namedtuple( + "TensorArrayConcatV2", + ["value", "lengths"]) + + +TV_TensorArrayConcatV2_dtype = TypeVar("TV_TensorArrayConcatV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_concat_v2(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcatV2_dtype, element_shape_except0=None, name=None): + r"""Deprecated. Use TensorArrayConcatV3 + + Args: + handle: A `Tensor` of type `string`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + element_shape_except0: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (value, lengths). + + value: A `Tensor` of type `dtype`. + lengths: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayConcatV2", name, handle, flow_in, "dtype", dtype, + "element_shape_except0", element_shape_except0) + _result = _TensorArrayConcatV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_concat_v2_eager_fallback( + handle, flow_in, dtype=dtype, + element_shape_except0=element_shape_except0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape_except0 is None: + element_shape_except0 = None + element_shape_except0 = _execute.make_shape(element_shape_except0, "element_shape_except0") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayConcatV2", handle=handle, flow_in=flow_in, dtype=dtype, + element_shape_except0=element_shape_except0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape_except0", + _op.get_attr("element_shape_except0")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayConcatV2", _inputs_flat, _attrs, _result) + _result = _TensorArrayConcatV2Output._make(_result) + return _result + +TensorArrayConcatV2 = tf_export("raw_ops.TensorArrayConcatV2")(_ops.to_raw_op(tensor_array_concat_v2)) + + +def tensor_array_concat_v2_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcatV2_dtype, element_shape_except0, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + if element_shape_except0 is None: + element_shape_except0 = None + element_shape_except0 = _execute.make_shape(element_shape_except0, "element_shape_except0") + handle = _ops.convert_to_tensor(handle, _dtypes.string) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = ("dtype", dtype, "element_shape_except0", element_shape_except0) + _result = _execute.execute(b"TensorArrayConcatV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayConcatV2", _inputs_flat, _attrs, _result) + _result = _TensorArrayConcatV2Output._make(_result) + return _result + +_TensorArrayConcatV3Output = collections.namedtuple( + "TensorArrayConcatV3", + ["value", "lengths"]) + + +TV_TensorArrayConcatV3_dtype = TypeVar("TV_TensorArrayConcatV3_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_concat_v3(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcatV3_dtype, element_shape_except0=None, name=None): + r"""Concat the elements from the TensorArray into value `value`. + + Takes `T` elements of shapes + + ``` + (n0 x d0 x d1 x ...), (n1 x d0 x d1 x ...), ..., (n(T-1) x d0 x d1 x ...) + ``` + + and concatenates them into a Tensor of shape: + + ``` + (n0 + n1 + ... + n(T-1) x d0 x d1 x ...) + ``` + + All elements must have the same shape (excepting the first dimension). + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + dtype: A `tf.DType`. The type of the elem that is returned. + element_shape_except0: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + The expected shape of an element, if known, + excluding the first dimension. Used to validate the shapes of + TensorArray elements. If this shape is not fully specified, concatenating + zero-size TensorArrays is an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (value, lengths). + + value: A `Tensor` of type `dtype`. + lengths: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayConcatV3", name, handle, flow_in, "dtype", dtype, + "element_shape_except0", element_shape_except0) + _result = _TensorArrayConcatV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_concat_v3_eager_fallback( + handle, flow_in, dtype=dtype, + element_shape_except0=element_shape_except0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape_except0 is None: + element_shape_except0 = None + element_shape_except0 = _execute.make_shape(element_shape_except0, "element_shape_except0") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayConcatV3", handle=handle, flow_in=flow_in, dtype=dtype, + element_shape_except0=element_shape_except0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape_except0", + _op.get_attr("element_shape_except0")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayConcatV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayConcatV3Output._make(_result) + return _result + +TensorArrayConcatV3 = tf_export("raw_ops.TensorArrayConcatV3")(_ops.to_raw_op(tensor_array_concat_v3)) + + +def tensor_array_concat_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayConcatV3_dtype, element_shape_except0, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + if element_shape_except0 is None: + element_shape_except0 = None + element_shape_except0 = _execute.make_shape(element_shape_except0, "element_shape_except0") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = ("dtype", dtype, "element_shape_except0", element_shape_except0) + _result = _execute.execute(b"TensorArrayConcatV3", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayConcatV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayConcatV3Output._make(_result) + return _result + + +TV_TensorArrayGather_dtype = TypeVar("TV_TensorArrayGather_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_gather(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGather_dtype, element_shape=None, name=None) -> Annotated[Any, TV_TensorArrayGather_dtype]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + indices: A `Tensor` of type `int32`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_gather op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGather", handle=handle, indices=indices, flow_in=flow_in, + dtype=dtype, element_shape=element_shape, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayGather = tf_export("raw_ops.TensorArrayGather")(_ops.to_raw_op(tensor_array_gather)) + + +def tensor_array_gather_eager_fallback(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGather_dtype, element_shape, name, ctx) -> Annotated[Any, TV_TensorArrayGather_dtype]: + raise RuntimeError("tensor_array_gather op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayGatherV2_dtype = TypeVar("TV_TensorArrayGatherV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_gather_v2(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGatherV2_dtype, element_shape=None, name=None) -> Annotated[Any, TV_TensorArrayGatherV2_dtype]: + r"""Deprecated. Use TensorArrayGatherV3 + + Args: + handle: A `Tensor` of type `string`. + indices: A `Tensor` of type `int32`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayGatherV2", name, handle, indices, flow_in, "dtype", + dtype, "element_shape", element_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_gather_v2_eager_fallback( + handle, indices, flow_in, dtype=dtype, element_shape=element_shape, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGatherV2", handle=handle, indices=indices, + flow_in=flow_in, dtype=dtype, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayGatherV2 = tf_export("raw_ops.TensorArrayGatherV2")(_ops.to_raw_op(tensor_array_gather_v2)) + + +def tensor_array_gather_v2_eager_fallback(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGatherV2_dtype, element_shape, name, ctx) -> Annotated[Any, TV_TensorArrayGatherV2_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + handle = _ops.convert_to_tensor(handle, _dtypes.string) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, indices, flow_in] + _attrs = ("dtype", dtype, "element_shape", element_shape) + _result = _execute.execute(b"TensorArrayGatherV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayGatherV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayGatherV3_dtype = TypeVar("TV_TensorArrayGatherV3_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_gather_v3(handle: Annotated[Any, _atypes.Resource], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGatherV3_dtype, element_shape=None, name=None) -> Annotated[Any, TV_TensorArrayGatherV3_dtype]: + r"""Gather specific elements from the TensorArray into output `value`. + + All elements selected by `indices` must have the same shape. + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + indices: A `Tensor` of type `int32`. + The locations in the TensorArray from which to read tensor elements. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + dtype: A `tf.DType`. The type of the elem that is returned. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + The expected shape of an element, if known. Used to + validate the shapes of TensorArray elements. If this shape is not + fully specified, gathering zero-size TensorArrays is an error. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayGatherV3", name, handle, indices, flow_in, "dtype", + dtype, "element_shape", element_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_gather_v3_eager_fallback( + handle, indices, flow_in, dtype=dtype, element_shape=element_shape, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGatherV3", handle=handle, indices=indices, + flow_in=flow_in, dtype=dtype, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGatherV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayGatherV3 = tf_export("raw_ops.TensorArrayGatherV3")(_ops.to_raw_op(tensor_array_gather_v3)) + + +def tensor_array_gather_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], indices: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayGatherV3_dtype, element_shape, name, ctx) -> Annotated[Any, TV_TensorArrayGatherV3_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, indices, flow_in] + _attrs = ("dtype", dtype, "element_shape", element_shape) + _result = _execute.execute(b"TensorArrayGatherV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayGatherV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_array_grad(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], source: str, name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `string`. + flow_in: A `Tensor` of type `float32`. + source: A `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_grad op does not support eager execution. Arg 'grad_handle' is a ref.") + # Add nodes to the TensorFlow graph. + source = _execute.make_str(source, "source") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGrad", handle=handle, flow_in=flow_in, source=source, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("source", _op.get_attr("source")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayGrad = tf_export("raw_ops.TensorArrayGrad")(_ops.to_raw_op(tensor_array_grad)) + + +def tensor_array_grad_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], source: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("tensor_array_grad op does not support eager execution. Arg 'grad_handle' is a ref.") + +def tensor_array_grad_v2(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], source: str, name=None) -> Annotated[Any, _atypes.String]: + r"""Deprecated. Use TensorArrayGradV3 + + Args: + handle: A `Tensor` of type `string`. + flow_in: A `Tensor` of type `float32`. + source: A `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayGradV2", name, handle, flow_in, "source", source) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_grad_v2_eager_fallback( + handle, flow_in, source=source, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + source = _execute.make_str(source, "source") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGradV2", handle=handle, flow_in=flow_in, source=source, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("source", _op.get_attr("source")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayGradV2 = tf_export("raw_ops.TensorArrayGradV2")(_ops.to_raw_op(tensor_array_grad_v2)) + + +def tensor_array_grad_v2_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], source: str, name, ctx) -> Annotated[Any, _atypes.String]: + source = _execute.make_str(source, "source") + handle = _ops.convert_to_tensor(handle, _dtypes.string) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = ("source", source) + _result = _execute.execute(b"TensorArrayGradV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TensorArrayGradV3Output = collections.namedtuple( + "TensorArrayGradV3", + ["grad_handle", "flow_out"]) + + +def tensor_array_grad_v3(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], source: str, name=None): + r"""Creates a TensorArray for storing the gradients of values in the given handle. + + If the given TensorArray gradient already exists, returns a reference to it. + + Locks the size of the original TensorArray by disabling its dynamic size flag. + + **A note about the input flow_in:** + + The handle flow_in forces the execution of the gradient lookup to occur + only after certain other operations have occurred. For example, when + the forward TensorArray is dynamically sized, writes to this TensorArray + may resize the object. The gradient TensorArray is statically sized based + on the size of the forward TensorArray when this operation executes. + Furthermore, the size of the forward TensorArray is frozen by this call. + As a result, the flow is used to ensure that the call to generate the gradient + TensorArray only happens after all writes are executed. + + In the case of dynamically sized TensorArrays, gradient computation should + only be performed on read operations that have themselves been chained via + flow to occur only after all writes have executed. That way the final size + of the forward TensorArray is known when this operation is called. + + **A note about the source attribute:** + + TensorArray gradient calls use an accumulator TensorArray object. If + multiple gradients are calculated and run in the same session, the multiple + gradient nodes may accidentally flow through the same accumulator TensorArray. + This double counts and generally breaks the TensorArray gradient flow. + + The solution is to identify which gradient call this particular + TensorArray gradient is being called in. This is performed by identifying + a unique string (e.g. "gradients", "gradients_1", ...) from the input + gradient Tensor's name. This string is used as a suffix when creating + the TensorArray gradient object here (the attribute `source`). + + The attribute `source` is added as a suffix to the forward TensorArray's + name when performing the creation / lookup, so that each separate gradient + calculation gets its own TensorArray accumulator. + + Args: + handle: A `Tensor` of type `resource`. + The handle to the forward TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + source: A `string`. + The gradient source string, used to decide which gradient TensorArray + to return. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (grad_handle, flow_out). + + grad_handle: A `Tensor` of type `resource`. + flow_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayGradV3", name, handle, flow_in, "source", source) + _result = _TensorArrayGradV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_grad_v3_eager_fallback( + handle, flow_in, source=source, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + source = _execute.make_str(source, "source") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGradV3", handle=handle, flow_in=flow_in, source=source, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("source", _op.get_attr("source")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGradV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayGradV3Output._make(_result) + return _result + +TensorArrayGradV3 = tf_export("raw_ops.TensorArrayGradV3")(_ops.to_raw_op(tensor_array_grad_v3)) + + +def tensor_array_grad_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], source: str, name, ctx): + source = _execute.make_str(source, "source") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = ("source", source) + _result = _execute.execute(b"TensorArrayGradV3", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayGradV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayGradV3Output._make(_result) + return _result + +_TensorArrayGradWithShapeOutput = collections.namedtuple( + "TensorArrayGradWithShape", + ["grad_handle", "flow_out"]) + + +def tensor_array_grad_with_shape(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], shape_to_prepend: Annotated[Any, _atypes.Int32], source: str, name=None): + r"""Creates a TensorArray for storing multiple gradients of values in the given handle. + + Similar to TensorArrayGradV3. However it creates an accumulator with an + expanded shape compared to the input TensorArray whose gradient is being + computed. This enables multiple gradients for the same TensorArray to be + calculated using the same accumulator. + + Args: + handle: A `Tensor` of type `resource`. + The handle to the forward TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + shape_to_prepend: A `Tensor` of type `int32`. + An int32 vector representing a shape. Elements in the gradient accumulator will + have shape which is this shape_to_prepend value concatenated with shape of the + elements in the TensorArray corresponding to the input handle. + source: A `string`. + The gradient source string, used to decide which gradient TensorArray + to return. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (grad_handle, flow_out). + + grad_handle: A `Tensor` of type `resource`. + flow_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayGradWithShape", name, handle, flow_in, + shape_to_prepend, "source", source) + _result = _TensorArrayGradWithShapeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_grad_with_shape_eager_fallback( + handle, flow_in, shape_to_prepend, source=source, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + source = _execute.make_str(source, "source") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayGradWithShape", handle=handle, flow_in=flow_in, + shape_to_prepend=shape_to_prepend, + source=source, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("source", _op.get_attr("source")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayGradWithShape", _inputs_flat, _attrs, _result) + _result = _TensorArrayGradWithShapeOutput._make(_result) + return _result + +TensorArrayGradWithShape = tf_export("raw_ops.TensorArrayGradWithShape")(_ops.to_raw_op(tensor_array_grad_with_shape)) + + +def tensor_array_grad_with_shape_eager_fallback(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], shape_to_prepend: Annotated[Any, _atypes.Int32], source: str, name, ctx): + source = _execute.make_str(source, "source") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + shape_to_prepend = _ops.convert_to_tensor(shape_to_prepend, _dtypes.int32) + _inputs_flat = [handle, flow_in, shape_to_prepend] + _attrs = ("source", source) + _result = _execute.execute(b"TensorArrayGradWithShape", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayGradWithShape", _inputs_flat, _attrs, _result) + _result = _TensorArrayGradWithShapeOutput._make(_result) + return _result + + +TV_TensorArrayPack_dtype = TypeVar("TV_TensorArrayPack_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_pack(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayPack_dtype, element_shape=None, name=None) -> Annotated[Any, TV_TensorArrayPack_dtype]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_pack op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayPack", handle=handle, flow_in=flow_in, dtype=dtype, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayPack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayPack = tf_export("raw_ops.TensorArrayPack")(_ops.to_raw_op(tensor_array_pack)) + + +def tensor_array_pack_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayPack_dtype, element_shape, name, ctx) -> Annotated[Any, TV_TensorArrayPack_dtype]: + raise RuntimeError("tensor_array_pack op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayRead_dtype = TypeVar("TV_TensorArrayRead_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_read(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayRead_dtype, name=None) -> Annotated[Any, TV_TensorArrayRead_dtype]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + index: A `Tensor` of type `int32`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_read op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayRead", handle=handle, index=index, flow_in=flow_in, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayRead", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayRead = tf_export("raw_ops.TensorArrayRead")(_ops.to_raw_op(tensor_array_read)) + + +def tensor_array_read_eager_fallback(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayRead_dtype, name, ctx) -> Annotated[Any, TV_TensorArrayRead_dtype]: + raise RuntimeError("tensor_array_read op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayReadV2_dtype = TypeVar("TV_TensorArrayReadV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_read_v2(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayReadV2_dtype, name=None) -> Annotated[Any, TV_TensorArrayReadV2_dtype]: + r"""Deprecated. Use TensorArrayReadV3 + + Args: + handle: A `Tensor` of type `string`. + index: A `Tensor` of type `int32`. + flow_in: A `Tensor` of type `float32`. + dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayReadV2", name, handle, index, flow_in, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_read_v2_eager_fallback( + handle, index, flow_in, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayReadV2", handle=handle, index=index, flow_in=flow_in, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayReadV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayReadV2 = tf_export("raw_ops.TensorArrayReadV2")(_ops.to_raw_op(tensor_array_read_v2)) + + +def tensor_array_read_v2_eager_fallback(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayReadV2_dtype, name, ctx) -> Annotated[Any, TV_TensorArrayReadV2_dtype]: + dtype = _execute.make_type(dtype, "dtype") + handle = _ops.convert_to_tensor(handle, _dtypes.string) + index = _ops.convert_to_tensor(index, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, index, flow_in] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"TensorArrayReadV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayReadV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayReadV3_dtype = TypeVar("TV_TensorArrayReadV3_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_read_v3(handle: Annotated[Any, _atypes.Resource], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayReadV3_dtype, name=None) -> Annotated[Any, TV_TensorArrayReadV3_dtype]: + r"""Read an element from the TensorArray into output `value`. + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + index: A `Tensor` of type `int32`. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + dtype: A `tf.DType`. The type of the elem that is returned. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayReadV3", name, handle, index, flow_in, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_read_v3_eager_fallback( + handle, index, flow_in, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayReadV3", handle=handle, index=index, flow_in=flow_in, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayReadV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayReadV3 = tf_export("raw_ops.TensorArrayReadV3")(_ops.to_raw_op(tensor_array_read_v3)) + + +def tensor_array_read_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], index: Annotated[Any, _atypes.Int32], flow_in: Annotated[Any, _atypes.Float32], dtype: TV_TensorArrayReadV3_dtype, name, ctx) -> Annotated[Any, TV_TensorArrayReadV3_dtype]: + dtype = _execute.make_type(dtype, "dtype") + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + index = _ops.convert_to_tensor(index, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, index, flow_in] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"TensorArrayReadV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayReadV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayScatter_T = TypeVar("TV_TensorArrayScatter_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_scatter(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatter_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + indices: A `Tensor` of type `int32`. + value: A `Tensor`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_scatter op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayScatter", handle=handle, indices=indices, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayScatter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayScatter = tf_export("raw_ops.TensorArrayScatter")(_ops.to_raw_op(tensor_array_scatter)) + + +def tensor_array_scatter_eager_fallback(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatter_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + raise RuntimeError("tensor_array_scatter op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayScatterV2_T = TypeVar("TV_TensorArrayScatterV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_scatter_v2(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatterV2_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Deprecated. Use TensorArrayScatterV3 + + Args: + handle: A `Tensor` of type `string`. + indices: A `Tensor` of type `int32`. + value: A `Tensor`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayScatterV2", name, handle, indices, value, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_scatter_v2_eager_fallback( + handle, indices, value, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayScatterV2", handle=handle, indices=indices, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayScatterV2 = tf_export("raw_ops.TensorArrayScatterV2")(_ops.to_raw_op(tensor_array_scatter_v2)) + + +def tensor_array_scatter_v2_eager_fallback(handle: Annotated[Any, _atypes.String], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatterV2_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.string) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, indices, value, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArrayScatterV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayScatterV3_T = TypeVar("TV_TensorArrayScatterV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_scatter_v3(handle: Annotated[Any, _atypes.Resource], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatterV3_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Scatter the data from the input value into specific TensorArray elements. + + `indices` must be a vector, its length must match the first dim of `value`. + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + indices: A `Tensor` of type `int32`. + The locations at which to write the tensor elements. + value: A `Tensor`. The concatenated tensor to write to the TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayScatterV3", name, handle, indices, value, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_scatter_v3_eager_fallback( + handle, indices, value, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayScatterV3", handle=handle, indices=indices, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayScatterV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayScatterV3 = tf_export("raw_ops.TensorArrayScatterV3")(_ops.to_raw_op(tensor_array_scatter_v3)) + + +def tensor_array_scatter_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], indices: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayScatterV3_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, indices, value, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArrayScatterV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayScatterV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_array_size(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_size op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySize", handle=handle, flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySize = tf_export("raw_ops.TensorArraySize")(_ops.to_raw_op(tensor_array_size)) + + +def tensor_array_size_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("tensor_array_size op does not support eager execution. Arg 'handle' is a ref.") + +def tensor_array_size_v2(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Deprecated. Use TensorArraySizeV3 + + Args: + handle: A `Tensor` of type `string`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArraySizeV2", name, handle, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_size_v2_eager_fallback( + handle, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySizeV2", handle=handle, flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySizeV2 = tf_export("raw_ops.TensorArraySizeV2")(_ops.to_raw_op(tensor_array_size_v2)) + + +def tensor_array_size_v2_eager_fallback(handle: Annotated[Any, _atypes.String], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + handle = _ops.convert_to_tensor(handle, _dtypes.string) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = None + _result = _execute.execute(b"TensorArraySizeV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArraySizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_array_size_v3(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Get the current size of the TensorArray. + + Args: + handle: A `Tensor` of type `resource`. + The handle to a TensorArray (output of TensorArray or TensorArrayGrad). + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArraySizeV3", name, handle, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_size_v3_eager_fallback( + handle, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySizeV3", handle=handle, flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySizeV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySizeV3 = tf_export("raw_ops.TensorArraySizeV3")(_ops.to_raw_op(tensor_array_size_v3)) + + +def tensor_array_size_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, flow_in] + _attrs = None + _result = _execute.execute(b"TensorArraySizeV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArraySizeV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArraySplit_T = TypeVar("TV_TensorArraySplit_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_split(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArraySplit_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + value: A `Tensor`. + lengths: A `Tensor` of type `int64`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_split op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySplit", handle=handle, value=value, lengths=lengths, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySplit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySplit = tf_export("raw_ops.TensorArraySplit")(_ops.to_raw_op(tensor_array_split)) + + +def tensor_array_split_eager_fallback(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArraySplit_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + raise RuntimeError("tensor_array_split op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArraySplitV2_T = TypeVar("TV_TensorArraySplitV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_split_v2(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArraySplitV2_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Deprecated. Use TensorArraySplitV3 + + Args: + handle: A `Tensor` of type `string`. + value: A `Tensor`. + lengths: A `Tensor` of type `int64`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArraySplitV2", name, handle, value, lengths, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_split_v2_eager_fallback( + handle, value, lengths, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySplitV2", handle=handle, value=value, lengths=lengths, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySplitV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySplitV2 = tf_export("raw_ops.TensorArraySplitV2")(_ops.to_raw_op(tensor_array_split_v2)) + + +def tensor_array_split_v2_eager_fallback(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArraySplitV2_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.string) + lengths = _ops.convert_to_tensor(lengths, _dtypes.int64) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, value, lengths, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArraySplitV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArraySplitV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArraySplitV3_T = TypeVar("TV_TensorArraySplitV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_split_v3(handle: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_TensorArraySplitV3_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Split the data from the input value into TensorArray elements. + + Assuming that `lengths` takes on values + + ``` + (n0, n1, ..., n(T-1)) + ``` + + and that `value` has shape + + ``` + (n0 + n1 + ... + n(T-1) x d0 x d1 x ...), + ``` + + this splits values into a TensorArray with T tensors. + + TensorArray index t will be the subtensor of values with starting position + + ``` + (n0 + n1 + ... + n(t-1), 0, 0, ...) + ``` + + and having size + + ``` + nt x d0 x d1 x ... + ``` + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + value: A `Tensor`. The concatenated tensor to write to the TensorArray. + lengths: A `Tensor` of type `int64`. + The vector of lengths, how to split the rows of value into the + TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArraySplitV3", name, handle, value, lengths, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_split_v3_eager_fallback( + handle, value, lengths, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArraySplitV3", handle=handle, value=value, lengths=lengths, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArraySplitV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArraySplitV3 = tf_export("raw_ops.TensorArraySplitV3")(_ops.to_raw_op(tensor_array_split_v3)) + + +def tensor_array_split_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_TensorArraySplitV3_T], lengths: Annotated[Any, _atypes.Int64], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + lengths = _ops.convert_to_tensor(lengths, _dtypes.int64) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, value, lengths, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArraySplitV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArraySplitV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayUnpack_T = TypeVar("TV_TensorArrayUnpack_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_unpack(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArrayUnpack_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + value: A `Tensor`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_unpack op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayUnpack", handle=handle, value=value, flow_in=flow_in, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayUnpack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayUnpack = tf_export("raw_ops.TensorArrayUnpack")(_ops.to_raw_op(tensor_array_unpack)) + + +def tensor_array_unpack_eager_fallback(handle: Annotated[Any, _atypes.String], value: Annotated[Any, TV_TensorArrayUnpack_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + raise RuntimeError("tensor_array_unpack op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayV2_dtype = TypeVar("TV_TensorArrayV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_v2(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArrayV2_dtype, element_shape=None, dynamic_size:bool=False, clear_after_read:bool=True, tensor_array_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Deprecated. Use TensorArrayV3 + + Args: + size: A `Tensor` of type `int32`. + dtype: A `tf.DType`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + dynamic_size: An optional `bool`. Defaults to `False`. + clear_after_read: An optional `bool`. Defaults to `True`. + tensor_array_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayV2", name, size, "dtype", dtype, "element_shape", + element_shape, "dynamic_size", dynamic_size, "clear_after_read", + clear_after_read, "tensor_array_name", tensor_array_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_v2_eager_fallback( + size, dtype=dtype, element_shape=element_shape, + dynamic_size=dynamic_size, clear_after_read=clear_after_read, + tensor_array_name=tensor_array_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + if dynamic_size is None: + dynamic_size = False + dynamic_size = _execute.make_bool(dynamic_size, "dynamic_size") + if clear_after_read is None: + clear_after_read = True + clear_after_read = _execute.make_bool(clear_after_read, "clear_after_read") + if tensor_array_name is None: + tensor_array_name = "" + tensor_array_name = _execute.make_str(tensor_array_name, "tensor_array_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayV2", size=size, dtype=dtype, element_shape=element_shape, + dynamic_size=dynamic_size, + clear_after_read=clear_after_read, + tensor_array_name=tensor_array_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape"), "dynamic_size", + _op._get_attr_bool("dynamic_size"), "clear_after_read", + _op._get_attr_bool("clear_after_read"), "tensor_array_name", + _op.get_attr("tensor_array_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayV2 = tf_export("raw_ops.TensorArrayV2")(_ops.to_raw_op(tensor_array_v2)) + + +def tensor_array_v2_eager_fallback(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArrayV2_dtype, element_shape, dynamic_size: bool, clear_after_read: bool, tensor_array_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + if dynamic_size is None: + dynamic_size = False + dynamic_size = _execute.make_bool(dynamic_size, "dynamic_size") + if clear_after_read is None: + clear_after_read = True + clear_after_read = _execute.make_bool(clear_after_read, "clear_after_read") + if tensor_array_name is None: + tensor_array_name = "" + tensor_array_name = _execute.make_str(tensor_array_name, "tensor_array_name") + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [size] + _attrs = ("dtype", dtype, "element_shape", element_shape, "dynamic_size", + dynamic_size, "clear_after_read", clear_after_read, "tensor_array_name", + tensor_array_name) + _result = _execute.execute(b"TensorArrayV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TensorArrayV3Output = collections.namedtuple( + "TensorArrayV3", + ["handle", "flow"]) + + +TV_TensorArrayV3_dtype = TypeVar("TV_TensorArrayV3_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_v3(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArrayV3_dtype, element_shape=None, dynamic_size:bool=False, clear_after_read:bool=True, identical_element_shapes:bool=False, tensor_array_name:str="", name=None): + r"""An array of Tensors of given size. + + Write data via Write and read via Read or Pack. + + Args: + size: A `Tensor` of type `int32`. The size of the array. + dtype: A `tf.DType`. The type of the elements on the tensor_array. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + The expected shape of an element, if known. Used to + validate the shapes of TensorArray elements. If this shape is not + fully specified, gathering zero-size TensorArrays is an error. + dynamic_size: An optional `bool`. Defaults to `False`. + A boolean that determines whether writes to the TensorArray + are allowed to grow the size. By default, this is not allowed. + clear_after_read: An optional `bool`. Defaults to `True`. + If true (default), Tensors in the TensorArray are cleared + after being read. This disables multiple read semantics but allows early + release of memory. + identical_element_shapes: An optional `bool`. Defaults to `False`. + If true (default is false), then all + elements in the TensorArray will be expected to have identical shapes. + This allows certain behaviors, like dynamically checking for + consistent shapes on write, and being able to fill in properly + shaped zero tensors on stack -- even if the element_shape attribute + is not fully defined. + tensor_array_name: An optional `string`. Defaults to `""`. + Overrides the name used for the temporary tensor_array + resource. Default value is the name of the 'TensorArray' op (which + is guaranteed unique). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, flow). + + handle: A `Tensor` of type `resource`. + flow: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayV3", name, size, "dtype", dtype, "element_shape", + element_shape, "dynamic_size", dynamic_size, "clear_after_read", + clear_after_read, "identical_element_shapes", + identical_element_shapes, "tensor_array_name", tensor_array_name) + _result = _TensorArrayV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_v3_eager_fallback( + size, dtype=dtype, element_shape=element_shape, + dynamic_size=dynamic_size, clear_after_read=clear_after_read, + identical_element_shapes=identical_element_shapes, + tensor_array_name=tensor_array_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + if dynamic_size is None: + dynamic_size = False + dynamic_size = _execute.make_bool(dynamic_size, "dynamic_size") + if clear_after_read is None: + clear_after_read = True + clear_after_read = _execute.make_bool(clear_after_read, "clear_after_read") + if identical_element_shapes is None: + identical_element_shapes = False + identical_element_shapes = _execute.make_bool(identical_element_shapes, "identical_element_shapes") + if tensor_array_name is None: + tensor_array_name = "" + tensor_array_name = _execute.make_str(tensor_array_name, "tensor_array_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayV3", size=size, dtype=dtype, element_shape=element_shape, + dynamic_size=dynamic_size, + clear_after_read=clear_after_read, + identical_element_shapes=identical_element_shapes, + tensor_array_name=tensor_array_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "element_shape", + _op.get_attr("element_shape"), "dynamic_size", + _op._get_attr_bool("dynamic_size"), "clear_after_read", + _op._get_attr_bool("clear_after_read"), + "identical_element_shapes", + _op._get_attr_bool("identical_element_shapes"), + "tensor_array_name", _op.get_attr("tensor_array_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayV3Output._make(_result) + return _result + +TensorArrayV3 = tf_export("raw_ops.TensorArrayV3")(_ops.to_raw_op(tensor_array_v3)) + + +def tensor_array_v3_eager_fallback(size: Annotated[Any, _atypes.Int32], dtype: TV_TensorArrayV3_dtype, element_shape, dynamic_size: bool, clear_after_read: bool, identical_element_shapes: bool, tensor_array_name: str, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + if dynamic_size is None: + dynamic_size = False + dynamic_size = _execute.make_bool(dynamic_size, "dynamic_size") + if clear_after_read is None: + clear_after_read = True + clear_after_read = _execute.make_bool(clear_after_read, "clear_after_read") + if identical_element_shapes is None: + identical_element_shapes = False + identical_element_shapes = _execute.make_bool(identical_element_shapes, "identical_element_shapes") + if tensor_array_name is None: + tensor_array_name = "" + tensor_array_name = _execute.make_str(tensor_array_name, "tensor_array_name") + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [size] + _attrs = ("dtype", dtype, "element_shape", element_shape, "dynamic_size", + dynamic_size, "clear_after_read", clear_after_read, + "identical_element_shapes", identical_element_shapes, "tensor_array_name", + tensor_array_name) + _result = _execute.execute(b"TensorArrayV3", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayV3", _inputs_flat, _attrs, _result) + _result = _TensorArrayV3Output._make(_result) + return _result + + +TV_TensorArrayWrite_T = TypeVar("TV_TensorArrayWrite_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_write(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWrite_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type mutable `string`. + index: A `Tensor` of type `int32`. + value: A `Tensor`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tensor_array_write op does not support eager execution. Arg 'handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayWrite", handle=handle, index=index, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayWrite", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayWrite = tf_export("raw_ops.TensorArrayWrite")(_ops.to_raw_op(tensor_array_write)) + + +def tensor_array_write_eager_fallback(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWrite_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + raise RuntimeError("tensor_array_write op does not support eager execution. Arg 'handle' is a ref.") + +TV_TensorArrayWriteV2_T = TypeVar("TV_TensorArrayWriteV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_write_v2(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWriteV2_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Deprecated. Use TensorArrayGradV3 + + Args: + handle: A `Tensor` of type `string`. + index: A `Tensor` of type `int32`. + value: A `Tensor`. + flow_in: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayWriteV2", name, handle, index, value, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_write_v2_eager_fallback( + handle, index, value, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayWriteV2", handle=handle, index=index, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayWriteV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayWriteV2 = tf_export("raw_ops.TensorArrayWriteV2")(_ops.to_raw_op(tensor_array_write_v2)) + + +def tensor_array_write_v2_eager_fallback(handle: Annotated[Any, _atypes.String], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWriteV2_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.string) + index = _ops.convert_to_tensor(index, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, index, value, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArrayWriteV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayWriteV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorArrayWriteV3_T = TypeVar("TV_TensorArrayWriteV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_array_write_v3(handle: Annotated[Any, _atypes.Resource], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWriteV3_T], flow_in: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Push an element onto the tensor_array. + + Args: + handle: A `Tensor` of type `resource`. The handle to a TensorArray. + index: A `Tensor` of type `int32`. + The position to write to inside the TensorArray. + value: A `Tensor`. The tensor to write to the TensorArray. + flow_in: A `Tensor` of type `float32`. + A float scalar that enforces proper chaining of operations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorArrayWriteV3", name, handle, index, value, flow_in) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_array_write_v3_eager_fallback( + handle, index, value, flow_in, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorArrayWriteV3", handle=handle, index=index, value=value, + flow_in=flow_in, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorArrayWriteV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorArrayWriteV3 = tf_export("raw_ops.TensorArrayWriteV3")(_ops.to_raw_op(tensor_array_write_v3)) + + +def tensor_array_write_v3_eager_fallback(handle: Annotated[Any, _atypes.Resource], index: Annotated[Any, _atypes.Int32], value: Annotated[Any, TV_TensorArrayWriteV3_T], flow_in: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + index = _ops.convert_to_tensor(index, _dtypes.int32) + flow_in = _ops.convert_to_tensor(flow_in, _dtypes.float32) + _inputs_flat = [handle, index, value, flow_in] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorArrayWriteV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorArrayWriteV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def unstage(dtypes, capacity:int=0, memory_limit:int=0, container:str="", shared_name:str="", name=None): + r"""Op is similar to a lightweight Dequeue. + + The basic functionality is similar to dequeue with many fewer + capabilities and options. This Op is optimized for performance. + + Args: + dtypes: A list of `tf.DTypes` that has length `>= 1`. + capacity: An optional `int` that is `>= 0`. Defaults to `0`. + memory_limit: An optional `int` that is `>= 0`. Defaults to `0`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Unstage", name, "capacity", capacity, "memory_limit", + memory_limit, "dtypes", dtypes, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unstage_eager_fallback( + capacity=capacity, memory_limit=memory_limit, dtypes=dtypes, + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Unstage", dtypes=dtypes, capacity=capacity, + memory_limit=memory_limit, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("capacity", _op._get_attr_int("capacity"), "memory_limit", + _op._get_attr_int("memory_limit"), "dtypes", + _op.get_attr("dtypes"), "container", _op.get_attr("container"), + "shared_name", _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Unstage", _inputs_flat, _attrs, _result) + return _result + +Unstage = tf_export("raw_ops.Unstage")(_ops.to_raw_op(unstage)) + + +def unstage_eager_fallback(dtypes, capacity: int, memory_limit: int, container: str, shared_name: str, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'unstage' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if capacity is None: + capacity = 0 + capacity = _execute.make_int(capacity, "capacity") + if memory_limit is None: + memory_limit = 0 + memory_limit = _execute.make_int(memory_limit, "memory_limit") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("capacity", capacity, "memory_limit", memory_limit, "dtypes", + dtypes, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"Unstage", len(dtypes), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Unstage", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_dataset_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_dataset_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9089ec4d27a83cb1b538e23be5c6b91d977f9c5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_dataset_ops.py @@ -0,0 +1,8315 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def anonymous_iterator(output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""A container for an iterator resource. + + Args: + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousIterator", name, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_iterator_eager_fallback( + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousIterator", output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousIterator = tf_export("raw_ops.AnonymousIterator")(_ops.to_raw_op(anonymous_iterator)) + + +def anonymous_iterator_eager_fallback(output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AnonymousIterator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_AnonymousIteratorV2Output = collections.namedtuple( + "AnonymousIteratorV2", + ["handle", "deleter"]) + + +def anonymous_iterator_v2(output_types, output_shapes, name=None): + r"""A container for an iterator resource. + + Args: + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, deleter). + + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousIteratorV2", name, "output_types", output_types, + "output_shapes", output_shapes) + _result = _AnonymousIteratorV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_iterator_v2_eager_fallback( + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousIteratorV2", output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousIteratorV2", _inputs_flat, _attrs, _result) + _result = _AnonymousIteratorV2Output._make(_result) + return _result + +AnonymousIteratorV2 = tf_export("raw_ops.AnonymousIteratorV2")(_ops.to_raw_op(anonymous_iterator_v2)) + + +def anonymous_iterator_v2_eager_fallback(output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AnonymousIteratorV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousIteratorV2", _inputs_flat, _attrs, _result) + _result = _AnonymousIteratorV2Output._make(_result) + return _result + + +def anonymous_iterator_v3(output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""A container for an iterator resource. + + Args: + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousIteratorV3", name, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_iterator_v3_eager_fallback( + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousIteratorV3", output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousIteratorV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousIteratorV3 = tf_export("raw_ops.AnonymousIteratorV3")(_ops.to_raw_op(anonymous_iterator_v3)) + + +def anonymous_iterator_v3_eager_fallback(output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_iterator_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_iterator_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AnonymousIteratorV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousIteratorV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_AnonymousMemoryCacheOutput = collections.namedtuple( + "AnonymousMemoryCache", + ["handle", "deleter"]) + + +def anonymous_memory_cache(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, deleter). + + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMemoryCache", name) + _result = _AnonymousMemoryCacheOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_memory_cache_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMemoryCache", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMemoryCache", _inputs_flat, _attrs, _result) + _result = _AnonymousMemoryCacheOutput._make(_result) + return _result + +AnonymousMemoryCache = tf_export("raw_ops.AnonymousMemoryCache")(_ops.to_raw_op(anonymous_memory_cache)) + + +def anonymous_memory_cache_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"AnonymousMemoryCache", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMemoryCache", _inputs_flat, _attrs, _result) + _result = _AnonymousMemoryCacheOutput._make(_result) + return _result + +_AnonymousMultiDeviceIteratorOutput = collections.namedtuple( + "AnonymousMultiDeviceIterator", + ["handle", "deleter"]) + + +def anonymous_multi_device_iterator(devices, output_types, output_shapes, name=None): + r"""A container for a multi device iterator resource. + + Args: + devices: A list of `strings` that has length `>= 1`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, deleter). + + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMultiDeviceIterator", name, "devices", devices, + "output_types", output_types, "output_shapes", output_shapes) + _result = _AnonymousMultiDeviceIteratorOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_multi_device_iterator_eager_fallback( + devices=devices, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMultiDeviceIterator", devices=devices, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("devices", _op.get_attr("devices"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMultiDeviceIterator", _inputs_flat, _attrs, _result) + _result = _AnonymousMultiDeviceIteratorOutput._make(_result) + return _result + +AnonymousMultiDeviceIterator = tf_export("raw_ops.AnonymousMultiDeviceIterator")(_ops.to_raw_op(anonymous_multi_device_iterator)) + + +def anonymous_multi_device_iterator_eager_fallback(devices, output_types, output_shapes, name, ctx): + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_multi_device_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("devices", devices, "output_types", output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"AnonymousMultiDeviceIterator", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMultiDeviceIterator", _inputs_flat, _attrs, _result) + _result = _AnonymousMultiDeviceIteratorOutput._make(_result) + return _result + + +def anonymous_multi_device_iterator_v3(devices, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""A container for a multi device iterator resource. + + Args: + devices: A list of `strings` that has length `>= 1`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMultiDeviceIteratorV3", name, "devices", devices, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_multi_device_iterator_v3_eager_fallback( + devices=devices, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMultiDeviceIteratorV3", devices=devices, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("devices", _op.get_attr("devices"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMultiDeviceIteratorV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousMultiDeviceIteratorV3 = tf_export("raw_ops.AnonymousMultiDeviceIteratorV3")(_ops.to_raw_op(anonymous_multi_device_iterator_v3)) + + +def anonymous_multi_device_iterator_v3_eager_fallback(devices, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'anonymous_multi_device_iterator_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("devices", devices, "output_types", output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"AnonymousMultiDeviceIteratorV3", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMultiDeviceIteratorV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_AnonymousRandomSeedGeneratorOutput = collections.namedtuple( + "AnonymousRandomSeedGenerator", + ["handle", "deleter"]) + + +def anonymous_random_seed_generator(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], name=None): + r"""TODO: add doc. + + Args: + seed: A `Tensor` of type `int64`. + seed2: A `Tensor` of type `int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, deleter). + + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousRandomSeedGenerator", name, seed, seed2) + _result = _AnonymousRandomSeedGeneratorOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_random_seed_generator_eager_fallback( + seed, seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousRandomSeedGenerator", seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousRandomSeedGenerator", _inputs_flat, _attrs, _result) + _result = _AnonymousRandomSeedGeneratorOutput._make(_result) + return _result + +AnonymousRandomSeedGenerator = tf_export("raw_ops.AnonymousRandomSeedGenerator")(_ops.to_raw_op(anonymous_random_seed_generator)) + + +def anonymous_random_seed_generator_eager_fallback(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], name, ctx): + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + _inputs_flat = [seed, seed2] + _attrs = None + _result = _execute.execute(b"AnonymousRandomSeedGenerator", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousRandomSeedGenerator", _inputs_flat, _attrs, _result) + _result = _AnonymousRandomSeedGeneratorOutput._make(_result) + return _result + +_AnonymousSeedGeneratorOutput = collections.namedtuple( + "AnonymousSeedGenerator", + ["handle", "deleter"]) + + +def anonymous_seed_generator(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], reshuffle: Annotated[Any, _atypes.Bool], name=None): + r"""TODO: add doc. + + Args: + seed: A `Tensor` of type `int64`. + seed2: A `Tensor` of type `int64`. + reshuffle: A `Tensor` of type `bool`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (handle, deleter). + + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousSeedGenerator", name, seed, seed2, reshuffle) + _result = _AnonymousSeedGeneratorOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_seed_generator_eager_fallback( + seed, seed2, reshuffle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousSeedGenerator", seed=seed, seed2=seed2, reshuffle=reshuffle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousSeedGenerator", _inputs_flat, _attrs, _result) + _result = _AnonymousSeedGeneratorOutput._make(_result) + return _result + +AnonymousSeedGenerator = tf_export("raw_ops.AnonymousSeedGenerator")(_ops.to_raw_op(anonymous_seed_generator)) + + +def anonymous_seed_generator_eager_fallback(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], reshuffle: Annotated[Any, _atypes.Bool], name, ctx): + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + reshuffle = _ops.convert_to_tensor(reshuffle, _dtypes.bool) + _inputs_flat = [seed, seed2, reshuffle] + _attrs = None + _result = _execute.execute(b"AnonymousSeedGenerator", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousSeedGenerator", _inputs_flat, _attrs, _result) + _result = _AnonymousSeedGeneratorOutput._make(_result) + return _result + + +def batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches `batch_size` elements from `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchDataset", name, input_dataset, batch_size, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_dataset_eager_fallback( + input_dataset, batch_size, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchDataset", input_dataset=input_dataset, batch_size=batch_size, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchDataset = tf_export("raw_ops.BatchDataset")(_ops.to_raw_op(batch_dataset)) + + +def batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + _inputs_flat = [input_dataset, batch_size] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"BatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, parallel_copy:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches `batch_size` elements from `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a batch. + drop_remainder: A `Tensor` of type `bool`. + A scalar representing whether the last batch should be dropped in case its size + is smaller than desired. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + parallel_copy: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchDatasetV2", name, input_dataset, batch_size, + drop_remainder, "parallel_copy", parallel_copy, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_dataset_v2_eager_fallback( + input_dataset, batch_size, drop_remainder, + parallel_copy=parallel_copy, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'batch_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'batch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchDatasetV2", input_dataset=input_dataset, batch_size=batch_size, + drop_remainder=drop_remainder, + output_types=output_types, + output_shapes=output_shapes, + parallel_copy=parallel_copy, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("parallel_copy", _op._get_attr_bool("parallel_copy"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchDatasetV2 = tf_export("raw_ops.BatchDatasetV2")(_ops.to_raw_op(batch_dataset_v2)) + + +def batch_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, parallel_copy: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'batch_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'batch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset, batch_size, drop_remainder] + _attrs = ("parallel_copy", parallel_copy, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"BatchDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def cache_dataset(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that caches elements from `input_dataset`. + + A CacheDataset will iterate over the input_dataset, and store tensors. If the + cache already exists, the cache will be used. If the cache is inappropriate + (e.g. cannot be opened, contains tensors of the wrong shape / size), an error + will the returned when used. + + Args: + input_dataset: A `Tensor` of type `variant`. + filename: A `Tensor` of type `string`. + A path on the filesystem where we should cache the dataset. Note: this + will be a directory. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CacheDataset", name, input_dataset, filename, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cache_dataset_eager_fallback( + input_dataset, filename, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'cache_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'cache_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CacheDataset", input_dataset=input_dataset, filename=filename, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CacheDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CacheDataset = tf_export("raw_ops.CacheDataset")(_ops.to_raw_op(cache_dataset)) + + +def cache_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'cache_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'cache_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + _inputs_flat = [input_dataset, filename] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"CacheDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CacheDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def cache_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], cache: Annotated[Any, _atypes.Resource], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + filename: A `Tensor` of type `string`. + cache: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CacheDatasetV2", name, input_dataset, filename, cache, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cache_dataset_v2_eager_fallback( + input_dataset, filename, cache, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'cache_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'cache_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CacheDatasetV2", input_dataset=input_dataset, filename=filename, + cache=cache, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CacheDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CacheDatasetV2 = tf_export("raw_ops.CacheDatasetV2")(_ops.to_raw_op(cache_dataset_v2)) + + +def cache_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], cache: Annotated[Any, _atypes.Resource], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'cache_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'cache_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + cache = _ops.convert_to_tensor(cache, _dtypes.resource) + _inputs_flat = [input_dataset, filename, cache] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"CacheDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CacheDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def concatenate_dataset(input_dataset: Annotated[Any, _atypes.Variant], another_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that concatenates `input_dataset` with `another_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + another_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConcatenateDataset", name, input_dataset, another_dataset, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return concatenate_dataset_eager_fallback( + input_dataset, another_dataset, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'concatenate_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'concatenate_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConcatenateDataset", input_dataset=input_dataset, + another_dataset=another_dataset, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConcatenateDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ConcatenateDataset = tf_export("raw_ops.ConcatenateDataset")(_ops.to_raw_op(concatenate_dataset)) + + +def concatenate_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], another_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'concatenate_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'concatenate_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + another_dataset = _ops.convert_to_tensor(another_dataset, _dtypes.variant) + _inputs_flat = [input_dataset, another_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"ConcatenateDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ConcatenateDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_cardinality(input_dataset: Annotated[Any, _atypes.Variant], cardinality_options:str="", name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the cardinality of `input_dataset`. + + Returns the cardinality of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to return cardinality for. + cardinality_options: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetCardinality", name, input_dataset, + "cardinality_options", cardinality_options) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_cardinality_eager_fallback( + input_dataset, cardinality_options=cardinality_options, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if cardinality_options is None: + cardinality_options = "" + cardinality_options = _execute.make_str(cardinality_options, "cardinality_options") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetCardinality", input_dataset=input_dataset, + cardinality_options=cardinality_options, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("cardinality_options", _op.get_attr("cardinality_options")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DatasetCardinality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DatasetCardinality = tf_export("raw_ops.DatasetCardinality")(_ops.to_raw_op(dataset_cardinality)) + + +def dataset_cardinality_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], cardinality_options: str, name, ctx) -> Annotated[Any, _atypes.Int64]: + if cardinality_options is None: + cardinality_options = "" + cardinality_options = _execute.make_str(cardinality_options, "cardinality_options") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("cardinality_options", cardinality_options) + _result = _execute.execute(b"DatasetCardinality", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DatasetCardinality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_to_graph(input_dataset: Annotated[Any, _atypes.Variant], stateful_whitelist=[], allow_stateful:bool=False, strip_device_assignment:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Returns a serialized GraphDef representing `input_dataset`. + + Returns a graph representation for `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to return the graph representation for. + stateful_whitelist: An optional list of `strings`. Defaults to `[]`. + allow_stateful: An optional `bool`. Defaults to `False`. + strip_device_assignment: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetToGraph", name, input_dataset, "stateful_whitelist", + stateful_whitelist, "allow_stateful", allow_stateful, + "strip_device_assignment", strip_device_assignment) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_to_graph_eager_fallback( + input_dataset, stateful_whitelist=stateful_whitelist, + allow_stateful=allow_stateful, + strip_device_assignment=strip_device_assignment, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if stateful_whitelist is None: + stateful_whitelist = [] + if not isinstance(stateful_whitelist, (list, tuple)): + raise TypeError( + "Expected list for 'stateful_whitelist' argument to " + "'dataset_to_graph' Op, not %r." % stateful_whitelist) + stateful_whitelist = [_execute.make_str(_s, "stateful_whitelist") for _s in stateful_whitelist] + if allow_stateful is None: + allow_stateful = False + allow_stateful = _execute.make_bool(allow_stateful, "allow_stateful") + if strip_device_assignment is None: + strip_device_assignment = False + strip_device_assignment = _execute.make_bool(strip_device_assignment, "strip_device_assignment") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetToGraph", input_dataset=input_dataset, + stateful_whitelist=stateful_whitelist, + allow_stateful=allow_stateful, + strip_device_assignment=strip_device_assignment, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("stateful_whitelist", _op.get_attr("stateful_whitelist"), + "allow_stateful", _op._get_attr_bool("allow_stateful"), + "strip_device_assignment", + _op._get_attr_bool("strip_device_assignment")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DatasetToGraph", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DatasetToGraph = tf_export("raw_ops.DatasetToGraph")(_ops.to_raw_op(dataset_to_graph)) + + +def dataset_to_graph_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], stateful_whitelist, allow_stateful: bool, strip_device_assignment: bool, name, ctx) -> Annotated[Any, _atypes.String]: + if stateful_whitelist is None: + stateful_whitelist = [] + if not isinstance(stateful_whitelist, (list, tuple)): + raise TypeError( + "Expected list for 'stateful_whitelist' argument to " + "'dataset_to_graph' Op, not %r." % stateful_whitelist) + stateful_whitelist = [_execute.make_str(_s, "stateful_whitelist") for _s in stateful_whitelist] + if allow_stateful is None: + allow_stateful = False + allow_stateful = _execute.make_bool(allow_stateful, "allow_stateful") + if strip_device_assignment is None: + strip_device_assignment = False + strip_device_assignment = _execute.make_bool(strip_device_assignment, "strip_device_assignment") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("stateful_whitelist", stateful_whitelist, "allow_stateful", + allow_stateful, "strip_device_assignment", strip_device_assignment) + _result = _execute.execute(b"DatasetToGraph", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DatasetToGraph", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_to_graph_v2(input_dataset: Annotated[Any, _atypes.Variant], external_state_policy:int=0, strip_device_assignment:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Returns a serialized GraphDef representing `input_dataset`. + + Returns a graph representation for `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to return the graph representation for. + external_state_policy: An optional `int`. Defaults to `0`. + strip_device_assignment: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetToGraphV2", name, input_dataset, + "external_state_policy", external_state_policy, + "strip_device_assignment", strip_device_assignment) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_to_graph_v2_eager_fallback( + input_dataset, external_state_policy=external_state_policy, + strip_device_assignment=strip_device_assignment, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if external_state_policy is None: + external_state_policy = 0 + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if strip_device_assignment is None: + strip_device_assignment = False + strip_device_assignment = _execute.make_bool(strip_device_assignment, "strip_device_assignment") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetToGraphV2", input_dataset=input_dataset, + external_state_policy=external_state_policy, + strip_device_assignment=strip_device_assignment, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("external_state_policy", + _op._get_attr_int("external_state_policy"), + "strip_device_assignment", + _op._get_attr_bool("strip_device_assignment")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DatasetToGraphV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DatasetToGraphV2 = tf_export("raw_ops.DatasetToGraphV2")(_ops.to_raw_op(dataset_to_graph_v2)) + + +def dataset_to_graph_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], external_state_policy: int, strip_device_assignment: bool, name, ctx) -> Annotated[Any, _atypes.String]: + if external_state_policy is None: + external_state_policy = 0 + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if strip_device_assignment is None: + strip_device_assignment = False + strip_device_assignment = _execute.make_bool(strip_device_assignment, "strip_device_assignment") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("external_state_policy", external_state_policy, + "strip_device_assignment", strip_device_assignment) + _result = _execute.execute(b"DatasetToGraphV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DatasetToGraphV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_to_single_element(dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata:str="", name=None): + r"""Outputs the single element from the given dataset. + + Args: + dataset: A `Tensor` of type `variant`. + A handle to a dataset that contains a single element. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetToSingleElement", name, dataset, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_to_single_element_eager_fallback( + dataset, output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'dataset_to_single_element' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'dataset_to_single_element' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetToSingleElement", dataset=dataset, output_types=output_types, + output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DatasetToSingleElement", _inputs_flat, _attrs, _result) + return _result + +DatasetToSingleElement = tf_export("raw_ops.DatasetToSingleElement")(_ops.to_raw_op(dataset_to_single_element)) + + +def dataset_to_single_element_eager_fallback(dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata: str, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'dataset_to_single_element' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'dataset_to_single_element' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + _inputs_flat = [dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"DatasetToSingleElement", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DatasetToSingleElement", _inputs_flat, _attrs, _result) + return _result + + +def delete_iterator(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name=None): + r"""A container for an iterator resource. + + Args: + handle: A `Tensor` of type `resource`. A handle to the iterator to delete. + deleter: A `Tensor` of type `variant`. A variant deleter. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteIterator", name, handle, deleter) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_iterator_eager_fallback( + handle, deleter, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteIterator", handle=handle, deleter=deleter, name=name) + return _op +DeleteIterator = tf_export("raw_ops.DeleteIterator")(_ops.to_raw_op(delete_iterator)) + + +def delete_iterator_eager_fallback(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + deleter = _ops.convert_to_tensor(deleter, _dtypes.variant) + _inputs_flat = [handle, deleter] + _attrs = None + _result = _execute.execute(b"DeleteIterator", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def delete_memory_cache(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name=None): + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteMemoryCache", name, handle, deleter) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_memory_cache_eager_fallback( + handle, deleter, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteMemoryCache", handle=handle, deleter=deleter, name=name) + return _op +DeleteMemoryCache = tf_export("raw_ops.DeleteMemoryCache")(_ops.to_raw_op(delete_memory_cache)) + + +def delete_memory_cache_eager_fallback(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + deleter = _ops.convert_to_tensor(deleter, _dtypes.variant) + _inputs_flat = [handle, deleter] + _attrs = None + _result = _execute.execute(b"DeleteMemoryCache", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def delete_multi_device_iterator(multi_device_iterator: Annotated[Any, _atypes.Resource], iterators: Annotated[List[Any], _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name=None): + r"""A container for an iterator resource. + + Args: + multi_device_iterator: A `Tensor` of type `resource`. + A handle to the multi device iterator to delete. + iterators: A list of `Tensor` objects with type `resource`. + A list of iterator handles (unused). This is added so that automatic control dependencies get added during function tracing that ensure this op runs after all the dependent iterators are deleted. + deleter: A `Tensor` of type `variant`. A variant deleter. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteMultiDeviceIterator", name, multi_device_iterator, + iterators, deleter) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_multi_device_iterator_eager_fallback( + multi_device_iterator, iterators, deleter, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(iterators, (list, tuple)): + raise TypeError( + "Expected list for 'iterators' argument to " + "'delete_multi_device_iterator' Op, not %r." % iterators) + _attr_N = len(iterators) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteMultiDeviceIterator", multi_device_iterator=multi_device_iterator, + iterators=iterators, deleter=deleter, + name=name) + return _op +DeleteMultiDeviceIterator = tf_export("raw_ops.DeleteMultiDeviceIterator")(_ops.to_raw_op(delete_multi_device_iterator)) + + +def delete_multi_device_iterator_eager_fallback(multi_device_iterator: Annotated[Any, _atypes.Resource], iterators: Annotated[List[Any], _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name, ctx): + if not isinstance(iterators, (list, tuple)): + raise TypeError( + "Expected list for 'iterators' argument to " + "'delete_multi_device_iterator' Op, not %r." % iterators) + _attr_N = len(iterators) + multi_device_iterator = _ops.convert_to_tensor(multi_device_iterator, _dtypes.resource) + iterators = _ops.convert_n_to_tensor(iterators, _dtypes.resource) + deleter = _ops.convert_to_tensor(deleter, _dtypes.variant) + _inputs_flat = [multi_device_iterator] + list(iterators) + [deleter] + _attrs = ("N", _attr_N) + _result = _execute.execute(b"DeleteMultiDeviceIterator", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def delete_random_seed_generator(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name=None): + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteRandomSeedGenerator", name, handle, deleter) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_random_seed_generator_eager_fallback( + handle, deleter, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteRandomSeedGenerator", handle=handle, deleter=deleter, + name=name) + return _op +DeleteRandomSeedGenerator = tf_export("raw_ops.DeleteRandomSeedGenerator")(_ops.to_raw_op(delete_random_seed_generator)) + + +def delete_random_seed_generator_eager_fallback(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + deleter = _ops.convert_to_tensor(deleter, _dtypes.variant) + _inputs_flat = [handle, deleter] + _attrs = None + _result = _execute.execute(b"DeleteRandomSeedGenerator", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def delete_seed_generator(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name=None): + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `resource`. + deleter: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeleteSeedGenerator", name, handle, deleter) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return delete_seed_generator_eager_fallback( + handle, deleter, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeleteSeedGenerator", handle=handle, deleter=deleter, name=name) + return _op +DeleteSeedGenerator = tf_export("raw_ops.DeleteSeedGenerator")(_ops.to_raw_op(delete_seed_generator)) + + +def delete_seed_generator_eager_fallback(handle: Annotated[Any, _atypes.Resource], deleter: Annotated[Any, _atypes.Variant], name, ctx): + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + deleter = _ops.convert_to_tensor(deleter, _dtypes.variant) + _inputs_flat = [handle, deleter] + _attrs = None + _result = _execute.execute(b"DeleteSeedGenerator", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def deserialize_iterator(resource_handle: Annotated[Any, _atypes.Resource], serialized: Annotated[Any, _atypes.Variant], name=None): + r"""Converts the given variant tensor to an iterator and stores it in the given resource. + + Args: + resource_handle: A `Tensor` of type `resource`. + A handle to an iterator resource. + serialized: A `Tensor` of type `variant`. + A variant tensor storing the state of the iterator contained in the + resource. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeserializeIterator", name, resource_handle, serialized) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return deserialize_iterator_eager_fallback( + resource_handle, serialized, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeserializeIterator", resource_handle=resource_handle, + serialized=serialized, name=name) + return _op +DeserializeIterator = tf_export("raw_ops.DeserializeIterator")(_ops.to_raw_op(deserialize_iterator)) + + +def deserialize_iterator_eager_fallback(resource_handle: Annotated[Any, _atypes.Resource], serialized: Annotated[Any, _atypes.Variant], name, ctx): + resource_handle = _ops.convert_to_tensor(resource_handle, _dtypes.resource) + serialized = _ops.convert_to_tensor(serialized, _dtypes.variant) + _inputs_flat = [resource_handle, serialized] + _attrs = None + _result = _execute.execute(b"DeserializeIterator", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def dummy_memory_cache(name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DummyMemoryCache", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dummy_memory_cache_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DummyMemoryCache", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DummyMemoryCache", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DummyMemoryCache = tf_export("raw_ops.DummyMemoryCache")(_ops.to_raw_op(dummy_memory_cache)) + + +def dummy_memory_cache_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Resource]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"DummyMemoryCache", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DummyMemoryCache", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dummy_seed_generator(name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DummySeedGenerator", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dummy_seed_generator_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DummySeedGenerator", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DummySeedGenerator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DummySeedGenerator = tf_export("raw_ops.DummySeedGenerator")(_ops.to_raw_op(dummy_seed_generator)) + + +def dummy_seed_generator_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Resource]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"DummySeedGenerator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DummySeedGenerator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def filter_by_last_component_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset containing elements of first component of `input_dataset` having true in the last component. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FilterByLastComponentDataset", name, input_dataset, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return filter_by_last_component_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'filter_by_last_component_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'filter_by_last_component_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FilterByLastComponentDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FilterByLastComponentDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FilterByLastComponentDataset = tf_export("raw_ops.FilterByLastComponentDataset")(_ops.to_raw_op(filter_by_last_component_dataset)) + + +def filter_by_last_component_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'filter_by_last_component_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'filter_by_last_component_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"FilterByLastComponentDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FilterByLastComponentDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def filter_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset containing elements of `input_dataset` matching `predicate`. + + The `predicate` function must return a scalar boolean and accept the + following arguments: + + * One tensor for each component of an element of `input_dataset`. + * One tensor for each value in `other_arguments`. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `predicate`. + predicate: A function decorated with @Defun. + A function returning a scalar boolean. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FilterDataset", name, input_dataset, other_arguments, + "predicate", predicate, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return filter_dataset_eager_fallback( + input_dataset, other_arguments, predicate=predicate, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'filter_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'filter_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FilterDataset", input_dataset=input_dataset, + other_arguments=other_arguments, predicate=predicate, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("predicate", _op.get_attr("predicate"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FilterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FilterDataset = tf_export("raw_ops.FilterDataset")(_ops.to_raw_op(filter_dataset)) + + +def filter_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'filter_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'filter_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("predicate", predicate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"FilterDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FilterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def finalize_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, has_captured_ref:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset by applying `tf.data.Options` to `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + has_captured_ref: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FinalizeDataset", name, input_dataset, "has_captured_ref", + has_captured_ref, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return finalize_dataset_eager_fallback( + input_dataset, has_captured_ref=has_captured_ref, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'finalize_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'finalize_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if has_captured_ref is None: + has_captured_ref = False + has_captured_ref = _execute.make_bool(has_captured_ref, "has_captured_ref") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FinalizeDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, + has_captured_ref=has_captured_ref, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("has_captured_ref", _op._get_attr_bool("has_captured_ref"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FinalizeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FinalizeDataset = tf_export("raw_ops.FinalizeDataset")(_ops.to_raw_op(finalize_dataset)) + + +def finalize_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, has_captured_ref: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'finalize_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'finalize_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if has_captured_ref is None: + has_captured_ref = False + has_captured_ref = _execute.make_bool(has_captured_ref, "has_captured_ref") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("has_captured_ref", has_captured_ref, "output_types", + output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"FinalizeDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FinalizeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def fixed_length_record_dataset(filenames: Annotated[Any, _atypes.String], header_bytes: Annotated[Any, _atypes.Int64], record_bytes: Annotated[Any, _atypes.Int64], footer_bytes: Annotated[Any, _atypes.Int64], buffer_size: Annotated[Any, _atypes.Int64], metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the records from one or more binary files. + + Args: + filenames: A `Tensor` of type `string`. + A scalar or a vector containing the name(s) of the file(s) to be + read. + header_bytes: A `Tensor` of type `int64`. + A scalar representing the number of bytes to skip at the + beginning of a file. + record_bytes: A `Tensor` of type `int64`. + A scalar representing the number of bytes in each record. + footer_bytes: A `Tensor` of type `int64`. + A scalar representing the number of bytes to skip at the end + of a file. + buffer_size: A `Tensor` of type `int64`. + A scalar representing the number of bytes to buffer. Must be > 0. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FixedLengthRecordDataset", name, filenames, header_bytes, + record_bytes, footer_bytes, buffer_size, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fixed_length_record_dataset_eager_fallback( + filenames, header_bytes, record_bytes, footer_bytes, buffer_size, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FixedLengthRecordDataset", filenames=filenames, + header_bytes=header_bytes, + record_bytes=record_bytes, + footer_bytes=footer_bytes, + buffer_size=buffer_size, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FixedLengthRecordDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FixedLengthRecordDataset = tf_export("raw_ops.FixedLengthRecordDataset")(_ops.to_raw_op(fixed_length_record_dataset)) + + +def fixed_length_record_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], header_bytes: Annotated[Any, _atypes.Int64], record_bytes: Annotated[Any, _atypes.Int64], footer_bytes: Annotated[Any, _atypes.Int64], buffer_size: Annotated[Any, _atypes.Int64], metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + header_bytes = _ops.convert_to_tensor(header_bytes, _dtypes.int64) + record_bytes = _ops.convert_to_tensor(record_bytes, _dtypes.int64) + footer_bytes = _ops.convert_to_tensor(footer_bytes, _dtypes.int64) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + _inputs_flat = [filenames, header_bytes, record_bytes, footer_bytes, buffer_size] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"FixedLengthRecordDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FixedLengthRecordDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def fixed_length_record_dataset_v2(filenames: Annotated[Any, _atypes.String], header_bytes: Annotated[Any, _atypes.Int64], record_bytes: Annotated[Any, _atypes.Int64], footer_bytes: Annotated[Any, _atypes.Int64], buffer_size: Annotated[Any, _atypes.Int64], compression_type: Annotated[Any, _atypes.String], metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + filenames: A `Tensor` of type `string`. + header_bytes: A `Tensor` of type `int64`. + record_bytes: A `Tensor` of type `int64`. + footer_bytes: A `Tensor` of type `int64`. + buffer_size: A `Tensor` of type `int64`. + compression_type: A `Tensor` of type `string`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FixedLengthRecordDatasetV2", name, filenames, header_bytes, + record_bytes, footer_bytes, buffer_size, compression_type, "metadata", + metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fixed_length_record_dataset_v2_eager_fallback( + filenames, header_bytes, record_bytes, footer_bytes, buffer_size, + compression_type, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FixedLengthRecordDatasetV2", filenames=filenames, + header_bytes=header_bytes, + record_bytes=record_bytes, + footer_bytes=footer_bytes, + buffer_size=buffer_size, + compression_type=compression_type, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FixedLengthRecordDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FixedLengthRecordDatasetV2 = tf_export("raw_ops.FixedLengthRecordDatasetV2")(_ops.to_raw_op(fixed_length_record_dataset_v2)) + + +def fixed_length_record_dataset_v2_eager_fallback(filenames: Annotated[Any, _atypes.String], header_bytes: Annotated[Any, _atypes.Int64], record_bytes: Annotated[Any, _atypes.Int64], footer_bytes: Annotated[Any, _atypes.Int64], buffer_size: Annotated[Any, _atypes.Int64], compression_type: Annotated[Any, _atypes.String], metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + header_bytes = _ops.convert_to_tensor(header_bytes, _dtypes.int64) + record_bytes = _ops.convert_to_tensor(record_bytes, _dtypes.int64) + footer_bytes = _ops.convert_to_tensor(footer_bytes, _dtypes.int64) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + _inputs_flat = [filenames, header_bytes, record_bytes, footer_bytes, buffer_size, compression_type] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"FixedLengthRecordDatasetV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FixedLengthRecordDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def flat_map_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Unlike MapDataset, the `f` in FlatMapDataset is expected to return a + Dataset variant, and FlatMapDataset will flatten successive results + into a single Dataset. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FlatMapDataset", name, input_dataset, other_arguments, "f", f, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return flat_map_dataset_eager_fallback( + input_dataset, other_arguments, f=f, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'flat_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'flat_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FlatMapDataset", input_dataset=input_dataset, + other_arguments=other_arguments, f=f, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FlatMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FlatMapDataset = tf_export("raw_ops.FlatMapDataset")(_ops.to_raw_op(flat_map_dataset)) + + +def flat_map_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'flat_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'flat_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"FlatMapDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FlatMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def generator_dataset(init_func_other_args, next_func_other_args, finalize_func_other_args, init_func, next_func, finalize_func, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that invokes a function to generate elements. + + Args: + init_func_other_args: A list of `Tensor` objects. + next_func_other_args: A list of `Tensor` objects. + finalize_func_other_args: A list of `Tensor` objects. + init_func: A function decorated with @Defun. + next_func: A function decorated with @Defun. + finalize_func: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GeneratorDataset", name, init_func_other_args, + next_func_other_args, finalize_func_other_args, "init_func", + init_func, "next_func", next_func, "finalize_func", finalize_func, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return generator_dataset_eager_fallback( + init_func_other_args, next_func_other_args, + finalize_func_other_args, init_func=init_func, next_func=next_func, + finalize_func=finalize_func, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'generator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'generator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GeneratorDataset", init_func_other_args=init_func_other_args, + next_func_other_args=next_func_other_args, + finalize_func_other_args=finalize_func_other_args, + init_func=init_func, next_func=next_func, + finalize_func=finalize_func, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("init_func", _op.get_attr("init_func"), "next_func", + _op.get_attr("next_func"), "finalize_func", + _op.get_attr("finalize_func"), "Tinit_func_args", + _op.get_attr("Tinit_func_args"), "Tnext_func_args", + _op.get_attr("Tnext_func_args"), "Tfinalize_func_args", + _op.get_attr("Tfinalize_func_args"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GeneratorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GeneratorDataset = tf_export("raw_ops.GeneratorDataset")(_ops.to_raw_op(generator_dataset)) + + +def generator_dataset_eager_fallback(init_func_other_args, next_func_other_args, finalize_func_other_args, init_func, next_func, finalize_func, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'generator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'generator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Tinit_func_args, init_func_other_args = _execute.convert_to_mixed_eager_tensors(init_func_other_args, ctx) + _attr_Tnext_func_args, next_func_other_args = _execute.convert_to_mixed_eager_tensors(next_func_other_args, ctx) + _attr_Tfinalize_func_args, finalize_func_other_args = _execute.convert_to_mixed_eager_tensors(finalize_func_other_args, ctx) + _inputs_flat = list(init_func_other_args) + list(next_func_other_args) + list(finalize_func_other_args) + _attrs = ("init_func", init_func, "next_func", next_func, "finalize_func", + finalize_func, "Tinit_func_args", _attr_Tinit_func_args, "Tnext_func_args", + _attr_Tnext_func_args, "Tfinalize_func_args", _attr_Tfinalize_func_args, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"GeneratorDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GeneratorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def get_options(input_dataset: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.String]: + r"""Returns the `tf.data.Options` attached to `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetOptions", name, input_dataset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return get_options_eager_fallback( + input_dataset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetOptions", input_dataset=input_dataset, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetOptions", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GetOptions = tf_export("raw_ops.GetOptions")(_ops.to_raw_op(get_options)) + + +def get_options_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.String]: + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = None + _result = _execute.execute(b"GetOptions", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetOptions", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def interleave_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Unlike MapDataset, the `f` in InterleaveDataset is expected to return + a Dataset variant, and InterleaveDataset will flatten successive + results into a single Dataset. Unlike FlatMapDataset, + InterleaveDataset will interleave sequences of up to `block_length` + consecutive elements from `cycle_length` input elements. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + cycle_length: A `Tensor` of type `int64`. + block_length: A `Tensor` of type `int64`. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InterleaveDataset", name, input_dataset, other_arguments, + cycle_length, block_length, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return interleave_dataset_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, f=f, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InterleaveDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, f=f, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InterleaveDataset = tf_export("raw_ops.InterleaveDataset")(_ops.to_raw_op(interleave_dataset)) + + +def interleave_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"InterleaveDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator(shared_name: str, container: str, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""A container for an iterator resource. + + Args: + shared_name: A `string`. + container: A `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Iterator", name, "shared_name", shared_name, "container", + container, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_eager_fallback( + shared_name=shared_name, container=container, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Iterator", shared_name=shared_name, container=container, + output_types=output_types, output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shared_name", _op.get_attr("shared_name"), "container", + _op.get_attr("container"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Iterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Iterator = tf_export("raw_ops.Iterator")(_ops.to_raw_op(iterator)) + + +def iterator_eager_fallback(shared_name: str, container: str, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("shared_name", shared_name, "container", container, + "output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"Iterator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Iterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator_from_string_handle(string_handle: Annotated[Any, _atypes.String], output_types=[], output_shapes=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Converts the given string representing a handle to an iterator to a resource. + + Args: + string_handle: A `Tensor` of type `string`. + A string representation of the given handle. + output_types: An optional list of `tf.DTypes`. Defaults to `[]`. + If specified, defines the type of each tuple component in an + element produced by the resulting iterator. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + If specified, defines the shape of each tuple component in an + element produced by the resulting iterator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorFromStringHandle", name, string_handle, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_from_string_handle_eager_fallback( + string_handle, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_from_string_handle' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_from_string_handle' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorFromStringHandle", string_handle=string_handle, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorFromStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorFromStringHandle = tf_export("raw_ops.IteratorFromStringHandle")(_ops.to_raw_op(iterator_from_string_handle)) + + +def iterator_from_string_handle_eager_fallback(string_handle: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_from_string_handle' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_from_string_handle' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + string_handle = _ops.convert_to_tensor(string_handle, _dtypes.string) + _inputs_flat = [string_handle] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorFromStringHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorFromStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator_from_string_handle_v2(string_handle: Annotated[Any, _atypes.String], output_types=[], output_shapes=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + string_handle: A `Tensor` of type `string`. + output_types: An optional list of `tf.DTypes`. Defaults to `[]`. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorFromStringHandleV2", name, string_handle, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_from_string_handle_v2_eager_fallback( + string_handle, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_from_string_handle_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_from_string_handle_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorFromStringHandleV2", string_handle=string_handle, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorFromStringHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorFromStringHandleV2 = tf_export("raw_ops.IteratorFromStringHandleV2")(_ops.to_raw_op(iterator_from_string_handle_v2)) + + +def iterator_from_string_handle_v2_eager_fallback(string_handle: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_from_string_handle_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_from_string_handle_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + string_handle = _ops.convert_to_tensor(string_handle, _dtypes.string) + _inputs_flat = [string_handle] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorFromStringHandleV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorFromStringHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator_get_next(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name=None): + r"""Gets the next output from the given iterator . + + Args: + iterator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorGetNext", name, iterator, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_get_next_eager_fallback( + iterator, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorGetNext", iterator=iterator, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorGetNext", _inputs_flat, _attrs, _result) + return _result + +IteratorGetNext = tf_export("raw_ops.IteratorGetNext")(_ops.to_raw_op(iterator_get_next)) + + +def iterator_get_next_eager_fallback(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [iterator] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorGetNext", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorGetNext", _inputs_flat, _attrs, _result) + return _result + + +def iterator_get_next_as_optional(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Gets the next output from the given iterator as an Optional variant. + + Args: + iterator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorGetNextAsOptional", name, iterator, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_get_next_as_optional_eager_fallback( + iterator, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next_as_optional' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next_as_optional' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorGetNextAsOptional", iterator=iterator, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorGetNextAsOptional", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorGetNextAsOptional = tf_export("raw_ops.IteratorGetNextAsOptional")(_ops.to_raw_op(iterator_get_next_as_optional)) + + +def iterator_get_next_as_optional_eager_fallback(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next_as_optional' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next_as_optional' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [iterator] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorGetNextAsOptional", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorGetNextAsOptional", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator_get_next_sync(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name=None): + r"""Gets the next output from the given iterator. + + This operation is a synchronous version IteratorGetNext. It should only be used + in situations where the iterator does not block the calling thread, or where + the calling thread is not a member of the thread pool used to execute parallel + operations (e.g. in eager mode). + + Args: + iterator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorGetNextSync", name, iterator, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_get_next_sync_eager_fallback( + iterator, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next_sync' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next_sync' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorGetNextSync", iterator=iterator, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorGetNextSync", _inputs_flat, _attrs, _result) + return _result + +IteratorGetNextSync = tf_export("raw_ops.IteratorGetNextSync")(_ops.to_raw_op(iterator_get_next_sync)) + + +def iterator_get_next_sync_eager_fallback(iterator: Annotated[Any, _atypes.Resource], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_get_next_sync' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_get_next_sync' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [iterator] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorGetNextSync", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorGetNextSync", _inputs_flat, _attrs, _result) + return _result + + +def iterator_to_string_handle(resource_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Converts the given `resource_handle` representing an iterator to a string. + + Args: + resource_handle: A `Tensor` of type `resource`. + A handle to an iterator resource. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorToStringHandle", name, resource_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_to_string_handle_eager_fallback( + resource_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorToStringHandle", resource_handle=resource_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorToStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorToStringHandle = tf_export("raw_ops.IteratorToStringHandle")(_ops.to_raw_op(iterator_to_string_handle)) + + +def iterator_to_string_handle_eager_fallback(resource_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + resource_handle = _ops.convert_to_tensor(resource_handle, _dtypes.resource) + _inputs_flat = [resource_handle] + _attrs = None + _result = _execute.execute(b"IteratorToStringHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorToStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def iterator_v2(shared_name: str, container: str, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + shared_name: A `string`. + container: A `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorV2", name, "shared_name", shared_name, "container", + container, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_v2_eager_fallback( + shared_name=shared_name, container=container, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorV2", shared_name=shared_name, container=container, + output_types=output_types, output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shared_name", _op.get_attr("shared_name"), "container", + _op.get_attr("container"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorV2 = tf_export("raw_ops.IteratorV2")(_ops.to_raw_op(iterator_v2)) + + +def iterator_v2_eager_fallback(shared_name: str, container: str, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'iterator_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'iterator_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("shared_name", shared_name, "container", container, + "output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"IteratorV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def make_iterator(dataset: Annotated[Any, _atypes.Variant], iterator: Annotated[Any, _atypes.Resource], name=None): + r"""Makes a new iterator from the given `dataset` and stores it in `iterator`. + + This operation may be executed multiple times. Each execution will reset the + iterator in `iterator` to the first element of `dataset`. + + Args: + dataset: A `Tensor` of type `variant`. + iterator: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MakeIterator", name, dataset, iterator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return make_iterator_eager_fallback( + dataset, iterator, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MakeIterator", dataset=dataset, iterator=iterator, name=name) + return _op +MakeIterator = tf_export("raw_ops.MakeIterator")(_ops.to_raw_op(make_iterator)) + + +def make_iterator_eager_fallback(dataset: Annotated[Any, _atypes.Variant], iterator: Annotated[Any, _atypes.Resource], name, ctx): + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [dataset, iterator] + _attrs = None + _result = _execute.execute(b"MakeIterator", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def map_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, use_inter_op_parallelism:bool=True, preserve_cardinality:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_inter_op_parallelism: An optional `bool`. Defaults to `True`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapDataset", name, input_dataset, other_arguments, "f", f, + "output_types", output_types, "output_shapes", output_shapes, + "use_inter_op_parallelism", use_inter_op_parallelism, + "preserve_cardinality", preserve_cardinality, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_dataset_eager_fallback( + input_dataset, other_arguments, f=f, output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + preserve_cardinality=preserve_cardinality, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapDataset", input_dataset=input_dataset, + other_arguments=other_arguments, f=f, + output_types=output_types, output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + preserve_cardinality=preserve_cardinality, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_inter_op_parallelism", + _op._get_attr_bool("use_inter_op_parallelism"), + "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MapDataset = tf_export("raw_ops.MapDataset")(_ops.to_raw_op(map_dataset)) + + +def map_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, use_inter_op_parallelism: bool, preserve_cardinality: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "preserve_cardinality", preserve_cardinality, + "metadata", metadata) + _result = _execute.execute(b"MapDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def map_defun(arguments, captured_inputs, output_types, output_shapes, f, max_intra_op_parallelism:int=1, name=None): + r""" Maps a function on the list of tensors unpacked from arguments on dimension 0. + The function given by `f` is assumed to be stateless, and is executed + concurrently on all the slices; up to batch_size (i.e. the size of the 0th + dimension of each argument) functions will be scheduled at once. + + The `max_intra_op_parallelism` attr, which defaults to 1, can be used to + limit the intra op parallelism. To limit inter-op parallelism, a user can + set a private threadpool on the dataset using `tf.data.Options`'s + `ThreadingOptions`. + + Note that this op is not exposed to users directly, but is invoked in tf.data + rewrites. + + Args: + arguments: A list of `Tensor` objects. + A list of tensors whose types are `Targuments`, corresponding to the inputs + the function should be mapped over. + captured_inputs: A list of `Tensor` objects. + A list of tensors whose types are `Tcaptured`, corresponding to the captured + inputs of the defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + A list of types. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + A list of shapes. + f: A function decorated with @Defun. + max_intra_op_parallelism: An optional `int`. Defaults to `1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapDefun", name, arguments, captured_inputs, "output_types", + output_types, "output_shapes", output_shapes, "f", f, + "max_intra_op_parallelism", max_intra_op_parallelism) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_defun_eager_fallback( + arguments, captured_inputs, output_types=output_types, + output_shapes=output_shapes, f=f, + max_intra_op_parallelism=max_intra_op_parallelism, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_defun' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_defun' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapDefun", arguments=arguments, captured_inputs=captured_inputs, + output_types=output_types, output_shapes=output_shapes, + f=f, max_intra_op_parallelism=max_intra_op_parallelism, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Targuments", _op.get_attr("Targuments"), "Tcaptured", + _op.get_attr("Tcaptured"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "f", _op.get_attr("f"), + "max_intra_op_parallelism", + _op._get_attr_int("max_intra_op_parallelism")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapDefun", _inputs_flat, _attrs, _result) + return _result + +MapDefun = tf_export("raw_ops.MapDefun")(_ops.to_raw_op(map_defun)) + + +def map_defun_eager_fallback(arguments, captured_inputs, output_types, output_shapes, f, max_intra_op_parallelism: int, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_defun' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_defun' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + _attr_Targuments, arguments = _execute.convert_to_mixed_eager_tensors(arguments, ctx) + _attr_Tcaptured, captured_inputs = _execute.convert_to_mixed_eager_tensors(captured_inputs, ctx) + _inputs_flat = list(arguments) + list(captured_inputs) + _attrs = ("Targuments", _attr_Targuments, "Tcaptured", _attr_Tcaptured, + "output_types", output_types, "output_shapes", output_shapes, "f", f, + "max_intra_op_parallelism", max_intra_op_parallelism) + _result = _execute.execute(b"MapDefun", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapDefun", _inputs_flat, _attrs, _result) + return _result + + +def model_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, algorithm:int=0, cpu_budget:int=0, ram_budget:int=0, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Identity transformation that models performance. + + Identity transformation that models performance. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + algorithm: An optional `int`. Defaults to `0`. + cpu_budget: An optional `int`. Defaults to `0`. + ram_budget: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ModelDataset", name, input_dataset, "algorithm", algorithm, + "cpu_budget", cpu_budget, "ram_budget", ram_budget, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return model_dataset_eager_fallback( + input_dataset, algorithm=algorithm, cpu_budget=cpu_budget, + ram_budget=ram_budget, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'model_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'model_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if algorithm is None: + algorithm = 0 + algorithm = _execute.make_int(algorithm, "algorithm") + if cpu_budget is None: + cpu_budget = 0 + cpu_budget = _execute.make_int(cpu_budget, "cpu_budget") + if ram_budget is None: + ram_budget = 0 + ram_budget = _execute.make_int(ram_budget, "ram_budget") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ModelDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, algorithm=algorithm, + cpu_budget=cpu_budget, ram_budget=ram_budget, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("algorithm", _op._get_attr_int("algorithm"), "cpu_budget", + _op._get_attr_int("cpu_budget"), "ram_budget", + _op._get_attr_int("ram_budget"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ModelDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ModelDataset = tf_export("raw_ops.ModelDataset")(_ops.to_raw_op(model_dataset)) + + +def model_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, algorithm: int, cpu_budget: int, ram_budget: int, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'model_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'model_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if algorithm is None: + algorithm = 0 + algorithm = _execute.make_int(algorithm, "algorithm") + if cpu_budget is None: + cpu_budget = 0 + cpu_budget = _execute.make_int(cpu_budget, "cpu_budget") + if ram_budget is None: + ram_budget = 0 + ram_budget = _execute.make_int(ram_budget, "ram_budget") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("algorithm", algorithm, "cpu_budget", cpu_budget, "ram_budget", + ram_budget, "output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ModelDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ModelDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def multi_device_iterator(devices, shared_name: str, container: str, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a MultiDeviceIterator resource. + + Args: + devices: A list of `strings` that has length `>= 1`. + A list of devices the iterator works across. + shared_name: A `string`. + If non-empty, this resource will be shared under the given name + across multiple sessions. + container: A `string`. + If non-empty, this resource is placed in the given container. + Otherwise, a default container is used. + output_types: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + The list of shapes being produced. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MultiDeviceIterator", name, "devices", devices, "shared_name", + shared_name, "container", container, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multi_device_iterator_eager_fallback( + devices=devices, shared_name=shared_name, container=container, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'multi_device_iterator' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MultiDeviceIterator", devices=devices, shared_name=shared_name, + container=container, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("devices", _op.get_attr("devices"), "shared_name", + _op.get_attr("shared_name"), "container", + _op.get_attr("container"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MultiDeviceIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MultiDeviceIterator = tf_export("raw_ops.MultiDeviceIterator")(_ops.to_raw_op(multi_device_iterator)) + + +def multi_device_iterator_eager_fallback(devices, shared_name: str, container: str, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(devices, (list, tuple)): + raise TypeError( + "Expected list for 'devices' argument to " + "'multi_device_iterator' Op, not %r." % devices) + devices = [_execute.make_str(_s, "devices") for _s in devices] + shared_name = _execute.make_str(shared_name, "shared_name") + container = _execute.make_str(container, "container") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _inputs_flat = [] + _attrs = ("devices", devices, "shared_name", shared_name, "container", + container, "output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"MultiDeviceIterator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MultiDeviceIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def multi_device_iterator_from_string_handle(string_handle: Annotated[Any, _atypes.String], output_types=[], output_shapes=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Generates a MultiDeviceIterator resource from its provided string handle. + + Args: + string_handle: A `Tensor` of type `string`. + String representing the resource. + output_types: An optional list of `tf.DTypes`. Defaults to `[]`. + The type list for the return values. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + The list of shapes being produced. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MultiDeviceIteratorFromStringHandle", name, string_handle, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multi_device_iterator_from_string_handle_eager_fallback( + string_handle, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator_from_string_handle' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator_from_string_handle' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MultiDeviceIteratorFromStringHandle", string_handle=string_handle, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MultiDeviceIteratorFromStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MultiDeviceIteratorFromStringHandle = tf_export("raw_ops.MultiDeviceIteratorFromStringHandle")(_ops.to_raw_op(multi_device_iterator_from_string_handle)) + + +def multi_device_iterator_from_string_handle_eager_fallback(string_handle: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Resource]: + if output_types is None: + output_types = [] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator_from_string_handle' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator_from_string_handle' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + string_handle = _ops.convert_to_tensor(string_handle, _dtypes.string) + _inputs_flat = [string_handle] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"MultiDeviceIteratorFromStringHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MultiDeviceIteratorFromStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def multi_device_iterator_get_next_from_shard(multi_device_iterator: Annotated[Any, _atypes.Resource], shard_num: Annotated[Any, _atypes.Int32], incarnation_id: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None): + r"""Gets next element for the provided shard number. + + Args: + multi_device_iterator: A `Tensor` of type `resource`. + A MultiDeviceIterator resource. + shard_num: A `Tensor` of type `int32`. + Integer representing which shard to fetch data for. + incarnation_id: A `Tensor` of type `int64`. + Which incarnation of the MultiDeviceIterator is running. + output_types: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + The list of shapes being produced. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MultiDeviceIteratorGetNextFromShard", name, + multi_device_iterator, shard_num, incarnation_id, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multi_device_iterator_get_next_from_shard_eager_fallback( + multi_device_iterator, shard_num, incarnation_id, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator_get_next_from_shard' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator_get_next_from_shard' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MultiDeviceIteratorGetNextFromShard", multi_device_iterator=multi_device_iterator, + shard_num=shard_num, + incarnation_id=incarnation_id, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MultiDeviceIteratorGetNextFromShard", _inputs_flat, _attrs, _result) + return _result + +MultiDeviceIteratorGetNextFromShard = tf_export("raw_ops.MultiDeviceIteratorGetNextFromShard")(_ops.to_raw_op(multi_device_iterator_get_next_from_shard)) + + +def multi_device_iterator_get_next_from_shard_eager_fallback(multi_device_iterator: Annotated[Any, _atypes.Resource], shard_num: Annotated[Any, _atypes.Int32], incarnation_id: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'multi_device_iterator_get_next_from_shard' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'multi_device_iterator_get_next_from_shard' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + multi_device_iterator = _ops.convert_to_tensor(multi_device_iterator, _dtypes.resource) + shard_num = _ops.convert_to_tensor(shard_num, _dtypes.int32) + incarnation_id = _ops.convert_to_tensor(incarnation_id, _dtypes.int64) + _inputs_flat = [multi_device_iterator, shard_num, incarnation_id] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"MultiDeviceIteratorGetNextFromShard", + len(output_types), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MultiDeviceIteratorGetNextFromShard", _inputs_flat, _attrs, _result) + return _result + + +def multi_device_iterator_init(dataset: Annotated[Any, _atypes.Variant], multi_device_iterator: Annotated[Any, _atypes.Resource], max_buffer_size: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Initializes the multi device iterator with the given dataset. + + Args: + dataset: A `Tensor` of type `variant`. Dataset to be iterated upon. + multi_device_iterator: A `Tensor` of type `resource`. + A MultiDeviceIteratorResource. + max_buffer_size: A `Tensor` of type `int64`. + The maximum size of the host side per device buffer to keep. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MultiDeviceIteratorInit", name, dataset, multi_device_iterator, + max_buffer_size) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multi_device_iterator_init_eager_fallback( + dataset, multi_device_iterator, max_buffer_size, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MultiDeviceIteratorInit", dataset=dataset, + multi_device_iterator=multi_device_iterator, + max_buffer_size=max_buffer_size, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MultiDeviceIteratorInit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MultiDeviceIteratorInit = tf_export("raw_ops.MultiDeviceIteratorInit")(_ops.to_raw_op(multi_device_iterator_init)) + + +def multi_device_iterator_init_eager_fallback(dataset: Annotated[Any, _atypes.Variant], multi_device_iterator: Annotated[Any, _atypes.Resource], max_buffer_size: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Int64]: + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + multi_device_iterator = _ops.convert_to_tensor(multi_device_iterator, _dtypes.resource) + max_buffer_size = _ops.convert_to_tensor(max_buffer_size, _dtypes.int64) + _inputs_flat = [dataset, multi_device_iterator, max_buffer_size] + _attrs = None + _result = _execute.execute(b"MultiDeviceIteratorInit", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MultiDeviceIteratorInit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def multi_device_iterator_to_string_handle(multi_device_iterator: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Produces a string handle for the given MultiDeviceIterator. + + Args: + multi_device_iterator: A `Tensor` of type `resource`. + A MultiDeviceIterator resource. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MultiDeviceIteratorToStringHandle", name, + multi_device_iterator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multi_device_iterator_to_string_handle_eager_fallback( + multi_device_iterator, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MultiDeviceIteratorToStringHandle", multi_device_iterator=multi_device_iterator, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MultiDeviceIteratorToStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MultiDeviceIteratorToStringHandle = tf_export("raw_ops.MultiDeviceIteratorToStringHandle")(_ops.to_raw_op(multi_device_iterator_to_string_handle)) + + +def multi_device_iterator_to_string_handle_eager_fallback(multi_device_iterator: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + multi_device_iterator = _ops.convert_to_tensor(multi_device_iterator, _dtypes.resource) + _inputs_flat = [multi_device_iterator] + _attrs = None + _result = _execute.execute(b"MultiDeviceIteratorToStringHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MultiDeviceIteratorToStringHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def one_shot_iterator(dataset_factory, output_types, output_shapes, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Makes a "one-shot" iterator that can be iterated only once. + + A one-shot iterator bundles the logic for defining the dataset and + the state of the iterator in a single op, which allows simple input + pipelines to be defined without an additional initialization + ("MakeIterator") step. + + One-shot iterators have the following limitations: + + * They do not support parameterization: all logic for creating the underlying + dataset must be bundled in the `dataset_factory` function. + * They are not resettable. Once a one-shot iterator reaches the end of its + underlying dataset, subsequent "IteratorGetNext" operations on that + iterator will always produce an `OutOfRange` error. + + For greater flexibility, use "Iterator" and "MakeIterator" to define + an iterator using an arbitrary subgraph, which may capture tensors + (including fed values) as parameters, and which may be reset multiple + times by rerunning "MakeIterator". + + Args: + dataset_factory: A function decorated with @Defun. + A function of type `() -> DT_VARIANT`, where the returned + DT_VARIANT is a dataset. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OneShotIterator", name, "dataset_factory", dataset_factory, + "output_types", output_types, "output_shapes", output_shapes, + "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return one_shot_iterator_eager_fallback( + dataset_factory=dataset_factory, output_types=output_types, + output_shapes=output_shapes, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'one_shot_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'one_shot_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OneShotIterator", dataset_factory=dataset_factory, + output_types=output_types, + output_shapes=output_shapes, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dataset_factory", _op.get_attr("dataset_factory"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OneShotIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OneShotIterator = tf_export("raw_ops.OneShotIterator")(_ops.to_raw_op(one_shot_iterator)) + + +def one_shot_iterator_eager_fallback(dataset_factory, output_types, output_shapes, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'one_shot_iterator' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'one_shot_iterator' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("dataset_factory", dataset_factory, "output_types", output_types, + "output_shapes", output_shapes, "container", container, "shared_name", + shared_name) + _result = _execute.execute(b"OneShotIterator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OneShotIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def optimize_dataset(input_dataset: Annotated[Any, _atypes.Variant], optimizations: Annotated[Any, _atypes.String], output_types, output_shapes, optimization_configs=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset by applying optimizations to `input_dataset`. + + Creates a dataset by applying optimizations to `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + optimizations: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying optimizations to use. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + optimization_configs: An optional list of `strings`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptimizeDataset", name, input_dataset, optimizations, + "output_types", output_types, "output_shapes", output_shapes, + "optimization_configs", optimization_configs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optimize_dataset_eager_fallback( + input_dataset, optimizations, output_types=output_types, + output_shapes=output_shapes, + optimization_configs=optimization_configs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optimize_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optimize_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if optimization_configs is None: + optimization_configs = [] + if not isinstance(optimization_configs, (list, tuple)): + raise TypeError( + "Expected list for 'optimization_configs' argument to " + "'optimize_dataset' Op, not %r." % optimization_configs) + optimization_configs = [_execute.make_str(_s, "optimization_configs") for _s in optimization_configs] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptimizeDataset", input_dataset=input_dataset, + optimizations=optimizations, + output_types=output_types, + output_shapes=output_shapes, + optimization_configs=optimization_configs, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "optimization_configs", + _op.get_attr("optimization_configs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptimizeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptimizeDataset = tf_export("raw_ops.OptimizeDataset")(_ops.to_raw_op(optimize_dataset)) + + +def optimize_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], optimizations: Annotated[Any, _atypes.String], output_types, output_shapes, optimization_configs, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optimize_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optimize_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if optimization_configs is None: + optimization_configs = [] + if not isinstance(optimization_configs, (list, tuple)): + raise TypeError( + "Expected list for 'optimization_configs' argument to " + "'optimize_dataset' Op, not %r." % optimization_configs) + optimization_configs = [_execute.make_str(_s, "optimization_configs") for _s in optimization_configs] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + optimizations = _ops.convert_to_tensor(optimizations, _dtypes.string) + _inputs_flat = [input_dataset, optimizations] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "optimization_configs", optimization_configs) + _result = _execute.execute(b"OptimizeDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptimizeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def optimize_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], optimizations_enabled: Annotated[Any, _atypes.String], optimizations_disabled: Annotated[Any, _atypes.String], optimizations_default: Annotated[Any, _atypes.String], output_types, output_shapes, optimization_configs=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset by applying related optimizations to `input_dataset`. + + Creates a dataset by applying related optimizations to `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + optimizations_enabled: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying user enabled optimizations. + optimizations_disabled: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying user disabled optimizations. + optimizations_default: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying optimizations by default. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + optimization_configs: An optional list of `strings`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptimizeDatasetV2", name, input_dataset, optimizations_enabled, + optimizations_disabled, optimizations_default, "output_types", + output_types, "output_shapes", output_shapes, "optimization_configs", + optimization_configs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optimize_dataset_v2_eager_fallback( + input_dataset, optimizations_enabled, optimizations_disabled, + optimizations_default, output_types=output_types, + output_shapes=output_shapes, + optimization_configs=optimization_configs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optimize_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optimize_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if optimization_configs is None: + optimization_configs = [] + if not isinstance(optimization_configs, (list, tuple)): + raise TypeError( + "Expected list for 'optimization_configs' argument to " + "'optimize_dataset_v2' Op, not %r." % optimization_configs) + optimization_configs = [_execute.make_str(_s, "optimization_configs") for _s in optimization_configs] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptimizeDatasetV2", input_dataset=input_dataset, + optimizations_enabled=optimizations_enabled, + optimizations_disabled=optimizations_disabled, + optimizations_default=optimizations_default, + output_types=output_types, + output_shapes=output_shapes, + optimization_configs=optimization_configs, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "optimization_configs", + _op.get_attr("optimization_configs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptimizeDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptimizeDatasetV2 = tf_export("raw_ops.OptimizeDatasetV2")(_ops.to_raw_op(optimize_dataset_v2)) + + +def optimize_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], optimizations_enabled: Annotated[Any, _atypes.String], optimizations_disabled: Annotated[Any, _atypes.String], optimizations_default: Annotated[Any, _atypes.String], output_types, output_shapes, optimization_configs, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optimize_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optimize_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if optimization_configs is None: + optimization_configs = [] + if not isinstance(optimization_configs, (list, tuple)): + raise TypeError( + "Expected list for 'optimization_configs' argument to " + "'optimize_dataset_v2' Op, not %r." % optimization_configs) + optimization_configs = [_execute.make_str(_s, "optimization_configs") for _s in optimization_configs] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + optimizations_enabled = _ops.convert_to_tensor(optimizations_enabled, _dtypes.string) + optimizations_disabled = _ops.convert_to_tensor(optimizations_disabled, _dtypes.string) + optimizations_default = _ops.convert_to_tensor(optimizations_default, _dtypes.string) + _inputs_flat = [input_dataset, optimizations_enabled, optimizations_disabled, optimizations_default] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "optimization_configs", optimization_configs) + _result = _execute.execute(b"OptimizeDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptimizeDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def options_dataset(input_dataset: Annotated[Any, _atypes.Variant], serialized_options: str, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset by attaching tf.data.Options to `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + serialized_options: A `string`. + A `tf.string` scalar `tf.Tensor` of serialized `tf.data.Options` protocol buffer. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptionsDataset", name, input_dataset, "serialized_options", + serialized_options, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return options_dataset_eager_fallback( + input_dataset, serialized_options=serialized_options, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + serialized_options = _execute.make_str(serialized_options, "serialized_options") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'options_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'options_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptionsDataset", input_dataset=input_dataset, + serialized_options=serialized_options, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("serialized_options", _op.get_attr("serialized_options"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptionsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptionsDataset = tf_export("raw_ops.OptionsDataset")(_ops.to_raw_op(options_dataset)) + + +def options_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], serialized_options: str, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + serialized_options = _execute.make_str(serialized_options, "serialized_options") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'options_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'options_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("serialized_options", serialized_options, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"OptionsDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptionsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def padded_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], padded_shapes: Annotated[List[Any], _atypes.Int64], padding_values, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches and pads `batch_size` elements from the input. + + Args: + input_dataset: A `Tensor` of type `variant`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. + padded_shapes: A list of at least 1 `Tensor` objects with type `int64`. + A list of int64 tensors representing the desired padded shapes + of the corresponding output components. These shapes may be partially + specified, using `-1` to indicate that a particular dimension should be + padded to the maximum size of all batch elements. + padding_values: A list of `Tensor` objects. + A list of scalars containing the padding value to use for + each of the outputs. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PaddedBatchDataset", name, input_dataset, batch_size, + padded_shapes, padding_values, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return padded_batch_dataset_eager_fallback( + input_dataset, batch_size, padded_shapes, padding_values, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(padded_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'padded_shapes' argument to " + "'padded_batch_dataset' Op, not %r." % padded_shapes) + _attr_N = len(padded_shapes) + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'padded_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PaddedBatchDataset", input_dataset=input_dataset, + batch_size=batch_size, + padded_shapes=padded_shapes, + padding_values=padding_values, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Toutput_types", _op.get_attr("Toutput_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N"), + "metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PaddedBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PaddedBatchDataset = tf_export("raw_ops.PaddedBatchDataset")(_ops.to_raw_op(padded_batch_dataset)) + + +def padded_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], padded_shapes: Annotated[List[Any], _atypes.Int64], padding_values, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(padded_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'padded_shapes' argument to " + "'padded_batch_dataset' Op, not %r." % padded_shapes) + _attr_N = len(padded_shapes) + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'padded_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Toutput_types, padding_values = _execute.convert_to_mixed_eager_tensors(padding_values, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + padded_shapes = _ops.convert_n_to_tensor(padded_shapes, _dtypes.int64) + _inputs_flat = [input_dataset, batch_size] + list(padded_shapes) + list(padding_values) + _attrs = ("Toutput_types", _attr_Toutput_types, "output_shapes", + output_shapes, "N", _attr_N, "metadata", metadata) + _result = _execute.execute(b"PaddedBatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PaddedBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def padded_batch_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], padded_shapes: Annotated[List[Any], _atypes.Int64], padding_values, drop_remainder: Annotated[Any, _atypes.Bool], output_shapes, parallel_copy:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches and pads `batch_size` elements from the input. + + Args: + input_dataset: A `Tensor` of type `variant`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. + padded_shapes: A list of at least 1 `Tensor` objects with type `int64`. + A list of int64 tensors representing the desired padded shapes + of the corresponding output components. These shapes may be partially + specified, using `-1` to indicate that a particular dimension should be + padded to the maximum size of all batch elements. + padding_values: A list of `Tensor` objects. + A list of scalars containing the padding value to use for + each of the outputs. + drop_remainder: A `Tensor` of type `bool`. + A scalar representing whether the last batch should be dropped in case its size + is smaller than desired. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + parallel_copy: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PaddedBatchDatasetV2", name, input_dataset, batch_size, + padded_shapes, padding_values, drop_remainder, "parallel_copy", + parallel_copy, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return padded_batch_dataset_v2_eager_fallback( + input_dataset, batch_size, padded_shapes, padding_values, + drop_remainder, parallel_copy=parallel_copy, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(padded_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'padded_shapes' argument to " + "'padded_batch_dataset_v2' Op, not %r." % padded_shapes) + _attr_N = len(padded_shapes) + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'padded_batch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PaddedBatchDatasetV2", input_dataset=input_dataset, + batch_size=batch_size, + padded_shapes=padded_shapes, + padding_values=padding_values, + drop_remainder=drop_remainder, + output_shapes=output_shapes, + parallel_copy=parallel_copy, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("parallel_copy", _op._get_attr_bool("parallel_copy"), + "Toutput_types", _op.get_attr("Toutput_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N"), + "metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PaddedBatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PaddedBatchDatasetV2 = tf_export("raw_ops.PaddedBatchDatasetV2")(_ops.to_raw_op(padded_batch_dataset_v2)) + + +def padded_batch_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], padded_shapes: Annotated[List[Any], _atypes.Int64], padding_values, drop_remainder: Annotated[Any, _atypes.Bool], output_shapes, parallel_copy: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(padded_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'padded_shapes' argument to " + "'padded_batch_dataset_v2' Op, not %r." % padded_shapes) + _attr_N = len(padded_shapes) + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'padded_batch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Toutput_types, padding_values = _execute.convert_to_mixed_eager_tensors(padding_values, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + padded_shapes = _ops.convert_n_to_tensor(padded_shapes, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset, batch_size] + list(padded_shapes) + list(padding_values) + [drop_remainder] + _attrs = ("parallel_copy", parallel_copy, "Toutput_types", + _attr_Toutput_types, "output_shapes", output_shapes, "N", _attr_N, + "metadata", metadata) + _result = _execute.execute(b"PaddedBatchDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PaddedBatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, parallel_copy:bool=False, deterministic:str="default", metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + batch_size: A `Tensor` of type `int64`. + num_parallel_calls: A `Tensor` of type `int64`. + drop_remainder: A `Tensor` of type `bool`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + parallel_copy: An optional `bool`. Defaults to `False`. + deterministic: An optional `string`. Defaults to `"default"`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelBatchDataset", name, input_dataset, batch_size, + num_parallel_calls, drop_remainder, "parallel_copy", parallel_copy, + "output_types", output_types, "output_shapes", output_shapes, + "deterministic", deterministic, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_batch_dataset_eager_fallback( + input_dataset, batch_size, num_parallel_calls, drop_remainder, + parallel_copy=parallel_copy, output_types=output_types, + output_shapes=output_shapes, deterministic=deterministic, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelBatchDataset", input_dataset=input_dataset, + batch_size=batch_size, + num_parallel_calls=num_parallel_calls, + drop_remainder=drop_remainder, + output_types=output_types, + output_shapes=output_shapes, + parallel_copy=parallel_copy, + deterministic=deterministic, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("parallel_copy", _op._get_attr_bool("parallel_copy"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "deterministic", + _op.get_attr("deterministic"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelBatchDataset = tf_export("raw_ops.ParallelBatchDataset")(_ops.to_raw_op(parallel_batch_dataset)) + + +def parallel_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, parallel_copy: bool, deterministic: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_copy is None: + parallel_copy = False + parallel_copy = _execute.make_bool(parallel_copy, "parallel_copy") + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset, batch_size, num_parallel_calls, drop_remainder] + _attrs = ("parallel_copy", parallel_copy, "output_types", output_types, + "output_shapes", output_shapes, "deterministic", deterministic, "metadata", + metadata) + _result = _execute.execute(b"ParallelBatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_filter_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int64], predicate, output_types, output_shapes, deterministic:str="default", metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset containing elements of `input_dataset` matching `predicate`. + + The `predicate` function must return a scalar boolean and accept the + following arguments: + + * One tensor for each component of an element of `input_dataset`. + * One tensor for each value in `other_arguments`. + + Unlike a "FilterDataset", which applies `predicate` sequentially, this dataset + invokes up to `num_parallel_calls` copies of `predicate` in parallel. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `predicate`. + num_parallel_calls: A `Tensor` of type `int64`. + The number of concurrent invocations of `predicate` that process + elements from `input_dataset` in parallel. + predicate: A function decorated with @Defun. + A function returning a scalar boolean. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + deterministic: An optional `string`. Defaults to `"default"`. + A string indicating the op-level determinism to use. Deterministic controls + whether the interleave is allowed to return elements out of order if the next + element to be returned isn't available, but a later element is. Options are + "true", "false", and "default". "default" indicates that determinism should be + decided by the `experimental_deterministic` parameter of `tf.data.Options`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelFilterDataset", name, input_dataset, other_arguments, + num_parallel_calls, "predicate", predicate, "deterministic", + deterministic, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_filter_dataset_eager_fallback( + input_dataset, other_arguments, num_parallel_calls, + predicate=predicate, deterministic=deterministic, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_filter_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_filter_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelFilterDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + num_parallel_calls=num_parallel_calls, + predicate=predicate, + output_types=output_types, + output_shapes=output_shapes, + deterministic=deterministic, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("predicate", _op.get_attr("predicate"), "deterministic", + _op.get_attr("deterministic"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelFilterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelFilterDataset = tf_export("raw_ops.ParallelFilterDataset")(_ops.to_raw_op(parallel_filter_dataset)) + + +def parallel_filter_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int64], predicate, output_types, output_shapes, deterministic: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_filter_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_filter_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [num_parallel_calls] + _attrs = ("predicate", predicate, "deterministic", deterministic, + "Targuments", _attr_Targuments, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"ParallelFilterDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelFilterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_interleave_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, sloppy:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, except that the + dataset will fetch records from the interleaved datasets in parallel. + + The `tf.data` Python API creates instances of this op from + `Dataset.interleave()` when the `num_parallel_calls` parameter of that method + is set to any value other than `None`. + + By default, the output of this dataset will be deterministic, which may result + in the dataset blocking if the next data item to be returned isn't available. + In order to avoid head-of-line blocking, one can set the + `experimental_deterministic` parameter of `tf.data.Options` to `False`, + which can improve performance at the expense of non-determinism. + + Args: + input_dataset: A `Tensor` of type `variant`. + Dataset that produces a stream of arguments for the function `f`. + other_arguments: A list of `Tensor` objects. + Additional arguments to pass to `f` beyond those produced by `input_dataset`. + Evaluated once when the dataset is instantiated. + cycle_length: A `Tensor` of type `int64`. + Number of datasets (each created by applying `f` to the elements of + `input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a + round-robin fashion. + block_length: A `Tensor` of type `int64`. + Number of elements at a time to produce from each interleaved invocation of a + dataset returned by `f`. + num_parallel_calls: A `Tensor` of type `int64`. + Determines the number of threads that should be used for fetching data from + input datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE` + constant can be used to indicate that the level of parallelism should be autotuned. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + sloppy: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelInterleaveDatasetV2", name, input_dataset, + other_arguments, cycle_length, block_length, num_parallel_calls, "f", + f, "output_types", output_types, "output_shapes", output_shapes, + "sloppy", sloppy, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_interleave_dataset_v2_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, + num_parallel_calls, f=f, output_types=output_types, + output_shapes=output_shapes, sloppy=sloppy, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelInterleaveDatasetV2", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, + num_parallel_calls=num_parallel_calls, + f=f, output_types=output_types, + output_shapes=output_shapes, + sloppy=sloppy, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "sloppy", + _op._get_attr_bool("sloppy"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelInterleaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelInterleaveDatasetV2 = tf_export("raw_ops.ParallelInterleaveDatasetV2")(_ops.to_raw_op(parallel_interleave_dataset_v2)) + + +def parallel_interleave_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, sloppy: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, num_parallel_calls] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "sloppy", sloppy, "metadata", + metadata) + _result = _execute.execute(b"ParallelInterleaveDatasetV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelInterleaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_interleave_dataset_v3(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic:str="default", metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, except that the + dataset will fetch records from the interleaved datasets in parallel. + + The `tf.data` Python API creates instances of this op from + `Dataset.interleave()` when the `num_parallel_calls` parameter of that method + is set to any value other than `None`. + + By default, the output of this dataset will be deterministic, which may result + in the dataset blocking if the next data item to be returned isn't available. + In order to avoid head-of-line blocking, one can either set the `deterministic` + attribute to "false", or leave it as "default" and set the + `experimental_deterministic` parameter of `tf.data.Options` to `False`. + This can improve performance at the expense of non-determinism. + + Args: + input_dataset: A `Tensor` of type `variant`. + Dataset that produces a stream of arguments for the function `f`. + other_arguments: A list of `Tensor` objects. + Additional arguments to pass to `f` beyond those produced by `input_dataset`. + Evaluated once when the dataset is instantiated. + cycle_length: A `Tensor` of type `int64`. + Number of datasets (each created by applying `f` to the elements of + `input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a + round-robin fashion. + block_length: A `Tensor` of type `int64`. + Number of elements at a time to produce from each interleaved invocation of a + dataset returned by `f`. + num_parallel_calls: A `Tensor` of type `int64`. + Determines the number of threads that should be used for fetching data from + input datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE` + constant can be used to indicate that the level of parallelism should be autotuned. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + deterministic: An optional `string`. Defaults to `"default"`. + A string indicating the op-level determinism to use. Deterministic controls + whether the interleave is allowed to return elements out of order if the next + element to be returned isn't available, but a later element is. Options are + "true", "false", and "default". "default" indicates that determinism should be + decided by the `experimental_deterministic` parameter of `tf.data.Options`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelInterleaveDatasetV3", name, input_dataset, + other_arguments, cycle_length, block_length, num_parallel_calls, "f", + f, "deterministic", deterministic, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_interleave_dataset_v3_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, + num_parallel_calls, f=f, deterministic=deterministic, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelInterleaveDatasetV3", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, + num_parallel_calls=num_parallel_calls, + f=f, output_types=output_types, + output_shapes=output_shapes, + deterministic=deterministic, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "deterministic", + _op.get_attr("deterministic"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelInterleaveDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelInterleaveDatasetV3 = tf_export("raw_ops.ParallelInterleaveDatasetV3")(_ops.to_raw_op(parallel_interleave_dataset_v3)) + + +def parallel_interleave_dataset_v3_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, num_parallel_calls] + _attrs = ("f", f, "deterministic", deterministic, "Targuments", + _attr_Targuments, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + _result = _execute.execute(b"ParallelInterleaveDatasetV3", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelInterleaveDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_interleave_dataset_v4(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic:str="default", metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, except that the + dataset will fetch records from the interleaved datasets in parallel. + + The `tf.data` Python API creates instances of this op from + `Dataset.interleave()` when the `num_parallel_calls` parameter of that method + is set to any value other than `None`. + + By default, the output of this dataset will be deterministic, which may result + in the dataset blocking if the next data item to be returned isn't available. + In order to avoid head-of-line blocking, one can either set the `deterministic` + attribute to "false", or leave it as "default" and set the + `experimental_deterministic` parameter of `tf.data.Options` to `False`. + This can improve performance at the expense of non-determinism. + + Args: + input_dataset: A `Tensor` of type `variant`. + Dataset that produces a stream of arguments for the function `f`. + other_arguments: A list of `Tensor` objects. + Additional arguments to pass to `f` beyond those produced by `input_dataset`. + Evaluated once when the dataset is instantiated. + cycle_length: A `Tensor` of type `int64`. + Number of datasets (each created by applying `f` to the elements of + `input_dataset`) among which the `ParallelInterleaveDatasetV2` will cycle in a + round-robin fashion. + block_length: A `Tensor` of type `int64`. + Number of elements at a time to produce from each interleaved invocation of a + dataset returned by `f`. + buffer_output_elements: A `Tensor` of type `int64`. + The number of elements each iterator being interleaved should buffer (similar + to the `.prefetch()` transformation for each interleaved iterator). + prefetch_input_elements: A `Tensor` of type `int64`. + Determines the number of iterators to prefetch, allowing buffers to warm up and + data to be pre-fetched without blocking the main thread. + num_parallel_calls: A `Tensor` of type `int64`. + Determines the number of threads that should be used for fetching data from + input datasets in parallel. The Python API `tf.data.experimental.AUTOTUNE` + constant can be used to indicate that the level of parallelism should be autotuned. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + deterministic: An optional `string`. Defaults to `"default"`. + A string indicating the op-level determinism to use. Deterministic controls + whether the interleave is allowed to return elements out of order if the next + element to be returned isn't available, but a later element is. Options are + "true", "false", and "default". "default" indicates that determinism should be + decided by the `experimental_deterministic` parameter of `tf.data.Options`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelInterleaveDatasetV4", name, input_dataset, + other_arguments, cycle_length, block_length, buffer_output_elements, + prefetch_input_elements, num_parallel_calls, "f", f, "deterministic", + deterministic, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_interleave_dataset_v4_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, + buffer_output_elements, prefetch_input_elements, num_parallel_calls, + f=f, deterministic=deterministic, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v4' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v4' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelInterleaveDatasetV4", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, + buffer_output_elements=buffer_output_elements, + prefetch_input_elements=prefetch_input_elements, + num_parallel_calls=num_parallel_calls, + f=f, output_types=output_types, + output_shapes=output_shapes, + deterministic=deterministic, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "deterministic", + _op.get_attr("deterministic"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelInterleaveDatasetV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelInterleaveDatasetV4 = tf_export("raw_ops.ParallelInterleaveDatasetV4")(_ops.to_raw_op(parallel_interleave_dataset_v4)) + + +def parallel_interleave_dataset_v4_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset_v4' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset_v4' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + buffer_output_elements = _ops.convert_to_tensor(buffer_output_elements, _dtypes.int64) + prefetch_input_elements = _ops.convert_to_tensor(prefetch_input_elements, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, buffer_output_elements, prefetch_input_elements, num_parallel_calls] + _attrs = ("f", f, "deterministic", deterministic, "Targuments", + _attr_Targuments, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + _result = _execute.execute(b"ParallelInterleaveDatasetV4", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelInterleaveDatasetV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_map_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int32], f, output_types, output_shapes, use_inter_op_parallelism:bool=True, sloppy:bool=False, preserve_cardinality:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up + to `num_parallel_calls` copies of `f` in parallel. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + num_parallel_calls: A `Tensor` of type `int32`. + The number of concurrent invocations of `f` that process + elements from `input_dataset` in parallel. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_inter_op_parallelism: An optional `bool`. Defaults to `True`. + sloppy: An optional `bool`. Defaults to `False`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelMapDataset", name, input_dataset, other_arguments, + num_parallel_calls, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "sloppy", sloppy, "preserve_cardinality", + preserve_cardinality, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_map_dataset_eager_fallback( + input_dataset, other_arguments, num_parallel_calls, f=f, + output_types=output_types, output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, sloppy=sloppy, + preserve_cardinality=preserve_cardinality, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelMapDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + num_parallel_calls=num_parallel_calls, f=f, + output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + sloppy=sloppy, + preserve_cardinality=preserve_cardinality, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_inter_op_parallelism", + _op._get_attr_bool("use_inter_op_parallelism"), "sloppy", + _op._get_attr_bool("sloppy"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelMapDataset = tf_export("raw_ops.ParallelMapDataset")(_ops.to_raw_op(parallel_map_dataset)) + + +def parallel_map_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int32], f, output_types, output_shapes, use_inter_op_parallelism: bool, sloppy: bool, preserve_cardinality: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int32) + _inputs_flat = [input_dataset] + list(other_arguments) + [num_parallel_calls] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "sloppy", sloppy, "preserve_cardinality", + preserve_cardinality, "metadata", metadata) + _result = _execute.execute(b"ParallelMapDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_map_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, use_inter_op_parallelism:bool=True, deterministic:str="default", preserve_cardinality:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up + to `num_parallel_calls` copies of `f` in parallel. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + num_parallel_calls: A `Tensor` of type `int64`. + The number of concurrent invocations of `f` that process + elements from `input_dataset` in parallel. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_inter_op_parallelism: An optional `bool`. Defaults to `True`. + deterministic: An optional `string`. Defaults to `"default"`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelMapDatasetV2", name, input_dataset, other_arguments, + num_parallel_calls, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "deterministic", deterministic, + "preserve_cardinality", preserve_cardinality, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_map_dataset_v2_eager_fallback( + input_dataset, other_arguments, num_parallel_calls, f=f, + output_types=output_types, output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + deterministic=deterministic, + preserve_cardinality=preserve_cardinality, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_map_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_map_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelMapDatasetV2", input_dataset=input_dataset, + other_arguments=other_arguments, + num_parallel_calls=num_parallel_calls, f=f, + output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + deterministic=deterministic, + preserve_cardinality=preserve_cardinality, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_inter_op_parallelism", + _op._get_attr_bool("use_inter_op_parallelism"), "deterministic", + _op.get_attr("deterministic"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelMapDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelMapDatasetV2 = tf_export("raw_ops.ParallelMapDatasetV2")(_ops.to_raw_op(parallel_map_dataset_v2)) + + +def parallel_map_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, num_parallel_calls: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, use_inter_op_parallelism: bool, deterministic: str, preserve_cardinality: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_map_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_map_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [num_parallel_calls] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "deterministic", deterministic, + "preserve_cardinality", preserve_cardinality, "metadata", metadata) + _result = _execute.execute(b"ParallelMapDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelMapDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def prefetch_dataset(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], output_types, output_shapes, slack_period:int=0, legacy_autotune:bool=True, buffer_size_min:int=0, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that asynchronously prefetches elements from `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + The maximum number of elements to buffer in an iterator over + this dataset. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + slack_period: An optional `int`. Defaults to `0`. + legacy_autotune: An optional `bool`. Defaults to `True`. + buffer_size_min: An optional `int`. Defaults to `0`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PrefetchDataset", name, input_dataset, buffer_size, + "output_types", output_types, "output_shapes", output_shapes, + "slack_period", slack_period, "legacy_autotune", legacy_autotune, + "buffer_size_min", buffer_size_min, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return prefetch_dataset_eager_fallback( + input_dataset, buffer_size, output_types=output_types, + output_shapes=output_shapes, slack_period=slack_period, + legacy_autotune=legacy_autotune, buffer_size_min=buffer_size_min, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'prefetch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'prefetch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if slack_period is None: + slack_period = 0 + slack_period = _execute.make_int(slack_period, "slack_period") + if legacy_autotune is None: + legacy_autotune = True + legacy_autotune = _execute.make_bool(legacy_autotune, "legacy_autotune") + if buffer_size_min is None: + buffer_size_min = 0 + buffer_size_min = _execute.make_int(buffer_size_min, "buffer_size_min") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PrefetchDataset", input_dataset=input_dataset, + buffer_size=buffer_size, output_types=output_types, + output_shapes=output_shapes, + slack_period=slack_period, + legacy_autotune=legacy_autotune, + buffer_size_min=buffer_size_min, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "slack_period", + _op._get_attr_int("slack_period"), "legacy_autotune", + _op._get_attr_bool("legacy_autotune"), "buffer_size_min", + _op._get_attr_int("buffer_size_min"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PrefetchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PrefetchDataset = tf_export("raw_ops.PrefetchDataset")(_ops.to_raw_op(prefetch_dataset)) + + +def prefetch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], output_types, output_shapes, slack_period: int, legacy_autotune: bool, buffer_size_min: int, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'prefetch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'prefetch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if slack_period is None: + slack_period = 0 + slack_period = _execute.make_int(slack_period, "slack_period") + if legacy_autotune is None: + legacy_autotune = True + legacy_autotune = _execute.make_bool(legacy_autotune, "legacy_autotune") + if buffer_size_min is None: + buffer_size_min = 0 + buffer_size_min = _execute.make_int(buffer_size_min, "buffer_size_min") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + _inputs_flat = [input_dataset, buffer_size] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "slack_period", slack_period, "legacy_autotune", legacy_autotune, + "buffer_size_min", buffer_size_min, "metadata", metadata) + _result = _execute.execute(b"PrefetchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PrefetchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def range_dataset(start: Annotated[Any, _atypes.Int64], stop: Annotated[Any, _atypes.Int64], step: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", replicate_on_split:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset with a range of values. Corresponds to python's xrange. + + Args: + start: A `Tensor` of type `int64`. + corresponds to start in python's xrange(). + stop: A `Tensor` of type `int64`. + corresponds to stop in python's xrange(). + step: A `Tensor` of type `int64`. + corresponds to step in python's xrange(). + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + replicate_on_split: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RangeDataset", name, start, stop, step, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata, + "replicate_on_split", replicate_on_split) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return range_dataset_eager_fallback( + start, stop, step, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + replicate_on_split=replicate_on_split, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'range_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'range_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + if replicate_on_split is None: + replicate_on_split = False + replicate_on_split = _execute.make_bool(replicate_on_split, "replicate_on_split") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RangeDataset", start=start, stop=stop, step=step, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + replicate_on_split=replicate_on_split, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata"), "replicate_on_split", + _op._get_attr_bool("replicate_on_split")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RangeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RangeDataset = tf_export("raw_ops.RangeDataset")(_ops.to_raw_op(range_dataset)) + + +def range_dataset_eager_fallback(start: Annotated[Any, _atypes.Int64], stop: Annotated[Any, _atypes.Int64], step: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, replicate_on_split: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'range_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'range_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + if replicate_on_split is None: + replicate_on_split = False + replicate_on_split = _execute.make_bool(replicate_on_split, "replicate_on_split") + start = _ops.convert_to_tensor(start, _dtypes.int64) + stop = _ops.convert_to_tensor(stop, _dtypes.int64) + step = _ops.convert_to_tensor(step, _dtypes.int64) + _inputs_flat = [start, stop, step] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata, "replicate_on_split", replicate_on_split) + _result = _execute.execute(b"RangeDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RangeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def reduce_dataset(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, use_inter_op_parallelism:bool=True, metadata:str="", name=None): + r"""Reduces the input dataset to a singleton using a reduce function. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + initial_state: A list of `Tensor` objects. + A nested structure of tensors, representing the initial state of the + transformation. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + A function that maps `(old_state, input_element)` to `new_state`. It must take + two arguments and return a nested structures of tensors. The structure of + `new_state` must match the structure of `initial_state`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_inter_op_parallelism: An optional `bool`. Defaults to `True`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReduceDataset", name, input_dataset, initial_state, + other_arguments, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reduce_dataset_eager_fallback( + input_dataset, initial_state, other_arguments, f=f, + output_types=output_types, output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'reduce_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'reduce_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReduceDataset", input_dataset=input_dataset, + initial_state=initial_state, + other_arguments=other_arguments, f=f, + output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + metadata=metadata, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Tstate", _op.get_attr("Tstate"), + "Targuments", _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_inter_op_parallelism", + _op._get_attr_bool("use_inter_op_parallelism"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReduceDataset", _inputs_flat, _attrs, _result) + return _result + +ReduceDataset = tf_export("raw_ops.ReduceDataset")(_ops.to_raw_op(reduce_dataset)) + + +def reduce_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, use_inter_op_parallelism: bool, metadata: str, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'reduce_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'reduce_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Tstate, initial_state = _execute.convert_to_mixed_eager_tensors(initial_state, ctx) + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(initial_state) + list(other_arguments) + _attrs = ("f", f, "Tstate", _attr_Tstate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes, + "use_inter_op_parallelism", use_inter_op_parallelism, "metadata", metadata) + _result = _execute.execute(b"ReduceDataset", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReduceDataset", _inputs_flat, _attrs, _result) + return _result + + +def repeat_dataset(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the outputs of `input_dataset` `count` times. + + Args: + input_dataset: A `Tensor` of type `variant`. + count: A `Tensor` of type `int64`. + A scalar representing the number of times that `input_dataset` should + be repeated. A value of `-1` indicates that it should be repeated infinitely. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RepeatDataset", name, input_dataset, count, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return repeat_dataset_eager_fallback( + input_dataset, count, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'repeat_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'repeat_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RepeatDataset", input_dataset=input_dataset, count=count, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RepeatDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RepeatDataset = tf_export("raw_ops.RepeatDataset")(_ops.to_raw_op(repeat_dataset)) + + +def repeat_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'repeat_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'repeat_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + count = _ops.convert_to_tensor(count, _dtypes.int64) + _inputs_flat = [input_dataset, count] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"RepeatDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RepeatDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def rewrite_dataset(input_dataset: Annotated[Any, _atypes.Variant], rewrite_name: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + rewrite_name: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RewriteDataset", name, input_dataset, rewrite_name, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rewrite_dataset_eager_fallback( + input_dataset, rewrite_name, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rewrite_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rewrite_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RewriteDataset", input_dataset=input_dataset, + rewrite_name=rewrite_name, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RewriteDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RewriteDataset = tf_export("raw_ops.RewriteDataset")(_ops.to_raw_op(rewrite_dataset)) + + +def rewrite_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], rewrite_name: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rewrite_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rewrite_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + rewrite_name = _ops.convert_to_tensor(rewrite_name, _dtypes.string) + _inputs_flat = [input_dataset, rewrite_name] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"RewriteDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RewriteDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def serialize_iterator(resource_handle: Annotated[Any, _atypes.Resource], external_state_policy:int=0, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Converts the given `resource_handle` representing an iterator to a variant tensor. + + Args: + resource_handle: A `Tensor` of type `resource`. + A handle to an iterator resource. + external_state_policy: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SerializeIterator", name, resource_handle, + "external_state_policy", external_state_policy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return serialize_iterator_eager_fallback( + resource_handle, external_state_policy=external_state_policy, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if external_state_policy is None: + external_state_policy = 0 + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SerializeIterator", resource_handle=resource_handle, + external_state_policy=external_state_policy, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("external_state_policy", + _op._get_attr_int("external_state_policy")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SerializeIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SerializeIterator = tf_export("raw_ops.SerializeIterator")(_ops.to_raw_op(serialize_iterator)) + + +def serialize_iterator_eager_fallback(resource_handle: Annotated[Any, _atypes.Resource], external_state_policy: int, name, ctx) -> Annotated[Any, _atypes.Variant]: + if external_state_policy is None: + external_state_policy = 0 + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + resource_handle = _ops.convert_to_tensor(resource_handle, _dtypes.resource) + _inputs_flat = [resource_handle] + _attrs = ("external_state_policy", external_state_policy) + _result = _execute.execute(b"SerializeIterator", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SerializeIterator", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shard_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_shards: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, require_non_empty:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a `Dataset` that includes only 1/`num_shards` of this dataset. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_shards: A `Tensor` of type `int64`. + An integer representing the number of shards operating in parallel. + index: A `Tensor` of type `int64`. + An integer representing the current worker index. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + require_non_empty: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShardDataset", name, input_dataset, num_shards, index, + "require_non_empty", require_non_empty, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shard_dataset_eager_fallback( + input_dataset, num_shards, index, + require_non_empty=require_non_empty, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if require_non_empty is None: + require_non_empty = False + require_non_empty = _execute.make_bool(require_non_empty, "require_non_empty") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShardDataset", input_dataset=input_dataset, num_shards=num_shards, + index=index, output_types=output_types, + output_shapes=output_shapes, + require_non_empty=require_non_empty, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("require_non_empty", _op._get_attr_bool("require_non_empty"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShardDataset = tf_export("raw_ops.ShardDataset")(_ops.to_raw_op(shard_dataset)) + + +def shard_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_shards: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, require_non_empty: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if require_non_empty is None: + require_non_empty = False + require_non_empty = _execute.make_bool(require_non_empty, "require_non_empty") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_shards = _ops.convert_to_tensor(num_shards, _dtypes.int64) + index = _ops.convert_to_tensor(index, _dtypes.int64) + _inputs_flat = [input_dataset, num_shards, index] + _attrs = ("require_non_empty", require_non_empty, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"ShardDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shuffle_and_repeat_dataset(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, reshuffle_each_iteration:bool=True, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that shuffles and repeats elements from `input_dataset` + + pseudorandomly. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + The number of output elements to buffer in an iterator over + this dataset. Compare with the `min_after_dequeue` attr when creating a + `RandomShuffleQueue`. + seed: A `Tensor` of type `int64`. + A scalar seed for the random number generator. If either `seed` or + `seed2` is set to be non-zero, the random number generator is seeded + by the given seed. Otherwise, a random seed is used. + seed2: A `Tensor` of type `int64`. + A second scalar seed to avoid seed collision. + count: A `Tensor` of type `int64`. + A scalar representing the number of times the underlying dataset + should be repeated. The default is `-1`, which results in infinite repetition. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reshuffle_each_iteration: An optional `bool`. Defaults to `True`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShuffleAndRepeatDataset", name, input_dataset, buffer_size, + seed, seed2, count, "output_types", output_types, "output_shapes", + output_shapes, "reshuffle_each_iteration", reshuffle_each_iteration, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shuffle_and_repeat_dataset_eager_fallback( + input_dataset, buffer_size, seed, seed2, count, + output_types=output_types, output_shapes=output_shapes, + reshuffle_each_iteration=reshuffle_each_iteration, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_and_repeat_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_and_repeat_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShuffleAndRepeatDataset", input_dataset=input_dataset, + buffer_size=buffer_size, seed=seed, + seed2=seed2, count=count, + output_types=output_types, + output_shapes=output_shapes, + reshuffle_each_iteration=reshuffle_each_iteration, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "reshuffle_each_iteration", + _op._get_attr_bool("reshuffle_each_iteration"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShuffleAndRepeatDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShuffleAndRepeatDataset = tf_export("raw_ops.ShuffleAndRepeatDataset")(_ops.to_raw_op(shuffle_and_repeat_dataset)) + + +def shuffle_and_repeat_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, reshuffle_each_iteration: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_and_repeat_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_and_repeat_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + count = _ops.convert_to_tensor(count, _dtypes.int64) + _inputs_flat = [input_dataset, buffer_size, seed, seed2, count] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "reshuffle_each_iteration", reshuffle_each_iteration, "metadata", metadata) + _result = _execute.execute(b"ShuffleAndRepeatDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShuffleAndRepeatDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shuffle_and_repeat_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], count: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, reshuffle_each_iteration:bool=True, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + seed: A `Tensor` of type `int64`. + seed2: A `Tensor` of type `int64`. + count: A `Tensor` of type `int64`. + seed_generator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reshuffle_each_iteration: An optional `bool`. Defaults to `True`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShuffleAndRepeatDatasetV2", name, input_dataset, buffer_size, + seed, seed2, count, seed_generator, "reshuffle_each_iteration", + reshuffle_each_iteration, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shuffle_and_repeat_dataset_v2_eager_fallback( + input_dataset, buffer_size, seed, seed2, count, seed_generator, + reshuffle_each_iteration=reshuffle_each_iteration, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_and_repeat_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_and_repeat_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShuffleAndRepeatDatasetV2", input_dataset=input_dataset, + buffer_size=buffer_size, seed=seed, + seed2=seed2, count=count, + seed_generator=seed_generator, + output_types=output_types, + output_shapes=output_shapes, + reshuffle_each_iteration=reshuffle_each_iteration, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reshuffle_each_iteration", + _op._get_attr_bool("reshuffle_each_iteration"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShuffleAndRepeatDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShuffleAndRepeatDatasetV2 = tf_export("raw_ops.ShuffleAndRepeatDatasetV2")(_ops.to_raw_op(shuffle_and_repeat_dataset_v2)) + + +def shuffle_and_repeat_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], count: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, reshuffle_each_iteration: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_and_repeat_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_and_repeat_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + count = _ops.convert_to_tensor(count, _dtypes.int64) + seed_generator = _ops.convert_to_tensor(seed_generator, _dtypes.resource) + _inputs_flat = [input_dataset, buffer_size, seed, seed2, count, seed_generator] + _attrs = ("reshuffle_each_iteration", reshuffle_each_iteration, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"ShuffleAndRepeatDatasetV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShuffleAndRepeatDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shuffle_dataset(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, reshuffle_each_iteration:bool=True, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that shuffles elements from `input_dataset` pseudorandomly. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + The number of output elements to buffer in an iterator over + this dataset. Compare with the `min_after_dequeue` attr when creating a + `RandomShuffleQueue`. + seed: A `Tensor` of type `int64`. + A scalar seed for the random number generator. If either `seed` or + `seed2` is set to be non-zero, the random number generator is seeded + by the given seed. Otherwise, a random seed is used. + seed2: A `Tensor` of type `int64`. + A second scalar seed to avoid seed collision. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reshuffle_each_iteration: An optional `bool`. Defaults to `True`. + If true, each iterator over this dataset will be given + a different pseudorandomly generated seed, based on a sequence seeded by the + `seed` and `seed2` inputs. If false, each iterator will be given the same + seed, and repeated iteration over this dataset will yield the exact same + sequence of results. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShuffleDataset", name, input_dataset, buffer_size, seed, seed2, + "reshuffle_each_iteration", reshuffle_each_iteration, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shuffle_dataset_eager_fallback( + input_dataset, buffer_size, seed, seed2, + reshuffle_each_iteration=reshuffle_each_iteration, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShuffleDataset", input_dataset=input_dataset, + buffer_size=buffer_size, seed=seed, seed2=seed2, + output_types=output_types, + output_shapes=output_shapes, + reshuffle_each_iteration=reshuffle_each_iteration, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reshuffle_each_iteration", + _op._get_attr_bool("reshuffle_each_iteration"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShuffleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShuffleDataset = tf_export("raw_ops.ShuffleDataset")(_ops.to_raw_op(shuffle_dataset)) + + +def shuffle_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, reshuffle_each_iteration: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + _inputs_flat = [input_dataset, buffer_size, seed, seed2] + _attrs = ("reshuffle_each_iteration", reshuffle_each_iteration, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"ShuffleDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShuffleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shuffle_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + seed_generator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShuffleDatasetV2", name, input_dataset, buffer_size, + seed_generator, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shuffle_dataset_v2_eager_fallback( + input_dataset, buffer_size, seed_generator, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShuffleDatasetV2", input_dataset=input_dataset, + buffer_size=buffer_size, + seed_generator=seed_generator, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShuffleDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShuffleDatasetV2 = tf_export("raw_ops.ShuffleDatasetV2")(_ops.to_raw_op(shuffle_dataset_v2)) + + +def shuffle_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + seed_generator = _ops.convert_to_tensor(seed_generator, _dtypes.resource) + _inputs_flat = [input_dataset, buffer_size, seed_generator] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"ShuffleDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShuffleDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def shuffle_dataset_v3(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, reshuffle_each_iteration:bool=True, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + buffer_size: A `Tensor` of type `int64`. + seed: A `Tensor` of type `int64`. + seed2: A `Tensor` of type `int64`. + seed_generator: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reshuffle_each_iteration: An optional `bool`. Defaults to `True`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShuffleDatasetV3", name, input_dataset, buffer_size, seed, + seed2, seed_generator, "reshuffle_each_iteration", + reshuffle_each_iteration, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shuffle_dataset_v3_eager_fallback( + input_dataset, buffer_size, seed, seed2, seed_generator, + reshuffle_each_iteration=reshuffle_each_iteration, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShuffleDatasetV3", input_dataset=input_dataset, + buffer_size=buffer_size, seed=seed, seed2=seed2, + seed_generator=seed_generator, + output_types=output_types, + output_shapes=output_shapes, + reshuffle_each_iteration=reshuffle_each_iteration, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reshuffle_each_iteration", + _op._get_attr_bool("reshuffle_each_iteration"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShuffleDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShuffleDatasetV3 = tf_export("raw_ops.ShuffleDatasetV3")(_ops.to_raw_op(shuffle_dataset_v3)) + + +def shuffle_dataset_v3_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], buffer_size: Annotated[Any, _atypes.Int64], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, reshuffle_each_iteration: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'shuffle_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'shuffle_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + reshuffle_each_iteration = _execute.make_bool(reshuffle_each_iteration, "reshuffle_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + seed_generator = _ops.convert_to_tensor(seed_generator, _dtypes.resource) + _inputs_flat = [input_dataset, buffer_size, seed, seed2, seed_generator] + _attrs = ("reshuffle_each_iteration", reshuffle_each_iteration, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"ShuffleDatasetV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShuffleDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def skip_dataset(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that skips `count` elements from the `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + count: A `Tensor` of type `int64`. + A scalar representing the number of elements from the `input_dataset` + that should be skipped. If count is -1, skips everything. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SkipDataset", name, input_dataset, count, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return skip_dataset_eager_fallback( + input_dataset, count, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'skip_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'skip_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SkipDataset", input_dataset=input_dataset, count=count, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SkipDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SkipDataset = tf_export("raw_ops.SkipDataset")(_ops.to_raw_op(skip_dataset)) + + +def skip_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'skip_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'skip_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + count = _ops.convert_to_tensor(count, _dtypes.int64) + _inputs_flat = [input_dataset, count] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"SkipDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SkipDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseTensorSliceDataset_Tvalues = TypeVar("TV_SparseTensorSliceDataset_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_tensor_slice_dataset(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseTensorSliceDataset_Tvalues], dense_shape: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that splits a SparseTensor into elements row-wise. + + Args: + indices: A `Tensor` of type `int64`. + values: A `Tensor`. + dense_shape: A `Tensor` of type `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseTensorSliceDataset", name, indices, values, dense_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_tensor_slice_dataset_eager_fallback( + indices, values, dense_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseTensorSliceDataset", indices=indices, values=values, + dense_shape=dense_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tvalues", _op._get_attr_type("Tvalues")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseTensorSliceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseTensorSliceDataset = tf_export("raw_ops.SparseTensorSliceDataset")(_ops.to_raw_op(sparse_tensor_slice_dataset)) + + +def sparse_tensor_slice_dataset_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseTensorSliceDataset_Tvalues], dense_shape: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_Tvalues, (values,) = _execute.args_to_matching_eager([values], ctx, []) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [indices, values, dense_shape] + _attrs = ("Tvalues", _attr_Tvalues) + _result = _execute.execute(b"SparseTensorSliceDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseTensorSliceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tf_record_dataset(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the records from one or more TFRecord files. + + Args: + filenames: A `Tensor` of type `string`. + A scalar or vector containing the name(s) of the file(s) to be + read. + compression_type: A `Tensor` of type `string`. + A scalar containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + buffer_size: A `Tensor` of type `int64`. + A scalar representing the number of bytes to buffer. A value of + 0 means no buffering will be performed. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TFRecordDataset", name, filenames, compression_type, + buffer_size, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tf_record_dataset_eager_fallback( + filenames, compression_type, buffer_size, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TFRecordDataset", filenames=filenames, + compression_type=compression_type, + buffer_size=buffer_size, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TFRecordDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TFRecordDataset = tf_export("raw_ops.TFRecordDataset")(_ops.to_raw_op(tf_record_dataset)) + + +def tf_record_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"TFRecordDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TFRecordDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tf_record_dataset_v2(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], byte_offsets: Annotated[Any, _atypes.Int64], metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the records from one or more TFRecord files. + + Args: + filenames: A `Tensor` of type `string`. + A scalar or vector containing the name(s) of the file(s) to be + read. + compression_type: A `Tensor` of type `string`. + A scalar containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + buffer_size: A `Tensor` of type `int64`. + A scalar representing the number of bytes to buffer. A value of + 0 means no buffering will be performed. + byte_offsets: A `Tensor` of type `int64`. + A scalar or vector containing the number of bytes for each file + that will be skipped prior to reading. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TFRecordDatasetV2", name, filenames, compression_type, + buffer_size, byte_offsets, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tf_record_dataset_v2_eager_fallback( + filenames, compression_type, buffer_size, byte_offsets, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TFRecordDatasetV2", filenames=filenames, + compression_type=compression_type, + buffer_size=buffer_size, + byte_offsets=byte_offsets, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TFRecordDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TFRecordDatasetV2 = tf_export("raw_ops.TFRecordDatasetV2")(_ops.to_raw_op(tf_record_dataset_v2)) + + +def tf_record_dataset_v2_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], byte_offsets: Annotated[Any, _atypes.Int64], metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + byte_offsets = _ops.convert_to_tensor(byte_offsets, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size, byte_offsets] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"TFRecordDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TFRecordDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def take_dataset(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that contains `count` elements from the `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + count: A `Tensor` of type `int64`. + A scalar representing the number of elements from the `input_dataset` + that should be taken. A value of `-1` indicates that all of `input_dataset` + is taken. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TakeDataset", name, input_dataset, count, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return take_dataset_eager_fallback( + input_dataset, count, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'take_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'take_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TakeDataset", input_dataset=input_dataset, count=count, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TakeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TakeDataset = tf_export("raw_ops.TakeDataset")(_ops.to_raw_op(take_dataset)) + + +def take_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], count: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'take_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'take_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + count = _ops.convert_to_tensor(count, _dtypes.int64) + _inputs_flat = [input_dataset, count] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"TakeDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TakeDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_dataset(components, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits `components` as a tuple of tensors once. + + Args: + components: A list of `Tensor` objects. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorDataset", name, components, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_dataset_eager_fallback( + components, output_shapes=output_shapes, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'tensor_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorDataset", components=components, output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Toutput_types", _op.get_attr("Toutput_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorDataset = tf_export("raw_ops.TensorDataset")(_ops.to_raw_op(tensor_dataset)) + + +def tensor_dataset_eager_fallback(components, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'tensor_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Toutput_types, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + _inputs_flat = list(components) + _attrs = ("Toutput_types", _attr_Toutput_types, "output_shapes", + output_shapes, "metadata", metadata) + _result = _execute.execute(b"TensorDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_slice_dataset(components, output_shapes, is_files:bool=False, metadata:str="", replicate_on_split:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits each dim-0 slice of `components` once. + + Args: + components: A list of `Tensor` objects. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + is_files: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + replicate_on_split: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorSliceDataset", name, components, "output_shapes", + output_shapes, "is_files", is_files, "metadata", metadata, + "replicate_on_split", replicate_on_split) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_slice_dataset_eager_fallback( + components, output_shapes=output_shapes, is_files=is_files, + metadata=metadata, replicate_on_split=replicate_on_split, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'tensor_slice_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if is_files is None: + is_files = False + is_files = _execute.make_bool(is_files, "is_files") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + if replicate_on_split is None: + replicate_on_split = False + replicate_on_split = _execute.make_bool(replicate_on_split, "replicate_on_split") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorSliceDataset", components=components, + output_shapes=output_shapes, is_files=is_files, + metadata=metadata, + replicate_on_split=replicate_on_split, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Toutput_types", _op.get_attr("Toutput_types"), "output_shapes", + _op.get_attr("output_shapes"), "is_files", + _op._get_attr_bool("is_files"), "metadata", + _op.get_attr("metadata"), "replicate_on_split", + _op._get_attr_bool("replicate_on_split")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorSliceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorSliceDataset = tf_export("raw_ops.TensorSliceDataset")(_ops.to_raw_op(tensor_slice_dataset)) + + +def tensor_slice_dataset_eager_fallback(components, output_shapes, is_files: bool, metadata: str, replicate_on_split: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'tensor_slice_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if is_files is None: + is_files = False + is_files = _execute.make_bool(is_files, "is_files") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + if replicate_on_split is None: + replicate_on_split = False + replicate_on_split = _execute.make_bool(replicate_on_split, "replicate_on_split") + _attr_Toutput_types, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + _inputs_flat = list(components) + _attrs = ("Toutput_types", _attr_Toutput_types, "output_shapes", + output_shapes, "is_files", is_files, "metadata", metadata, + "replicate_on_split", replicate_on_split) + _result = _execute.execute(b"TensorSliceDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorSliceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def text_line_dataset(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the lines of one or more text files. + + Args: + filenames: A `Tensor` of type `string`. + A scalar or a vector containing the name(s) of the file(s) to be + read. + compression_type: A `Tensor` of type `string`. + A scalar containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + buffer_size: A `Tensor` of type `int64`. + A scalar containing the number of bytes to buffer. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TextLineDataset", name, filenames, compression_type, + buffer_size, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return text_line_dataset_eager_fallback( + filenames, compression_type, buffer_size, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TextLineDataset", filenames=filenames, + compression_type=compression_type, + buffer_size=buffer_size, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TextLineDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TextLineDataset = tf_export("raw_ops.TextLineDataset")(_ops.to_raw_op(text_line_dataset)) + + +def text_line_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"TextLineDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TextLineDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def unwrap_dataset_variant(input_handle: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_handle: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnwrapDatasetVariant", name, input_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unwrap_dataset_variant_eager_fallback( + input_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnwrapDatasetVariant", input_handle=input_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnwrapDatasetVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnwrapDatasetVariant = tf_export("raw_ops.UnwrapDatasetVariant")(_ops.to_raw_op(unwrap_dataset_variant)) + + +def unwrap_dataset_variant_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Variant]: + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = None + _result = _execute.execute(b"UnwrapDatasetVariant", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnwrapDatasetVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def window_dataset(input_dataset: Annotated[Any, _atypes.Variant], size: Annotated[Any, _atypes.Int64], shift: Annotated[Any, _atypes.Int64], stride: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r""" Combines (nests of) input elements into a dataset of (nests of) windows. + + A "window" is a finite dataset of flat elements of size `size` (or possibly + fewer if there are not enough input elements to fill the window and + `drop_remainder` evaluates to false). + + The `shift` argument determines the number of input elements by which + the window moves on each iteration. The first element in the `k`th window + will be element + + ``` + 1 + (k-1) * shift + ``` + + of the input dataset. In particular, the first element of the first window + will always be the first element of the input dataset. + + If the `stride` parameter is greater than 1, then each window will skip + `(stride - 1)` input elements between each element that appears in the + window. Output windows will still contain `size` elements regardless of + the value of `stride`. + + The `stride` argument determines the stride of the input elements, and the + `shift` argument determines the shift of the window. + + For example, letting `{...}` to represent a Dataset: + + - `tf.data.Dataset.range(7).window(2)` produces + `{{0, 1}, {2, 3}, {4, 5}, {6}}` + - `tf.data.Dataset.range(7).window(3, 2, 1, True)` produces + `{{0, 1, 2}, {2, 3, 4}, {4, 5, 6}}` + - `tf.data.Dataset.range(7).window(3, 1, 2, True)` produces + `{{0, 2, 4}, {1, 3, 5}, {2, 4, 6}}` + + Note that when the `window` transformation is applied to a dataset of + nested elements, it produces a dataset of nested windows. + + For example: + + - `tf.data.Dataset.from_tensor_slices((range(4), range(4))).window(2)` + produces `{({0, 1}, {0, 1}), ({2, 3}, {2, 3})}` + - `tf.data.Dataset.from_tensor_slices({"a": range(4)}).window(2)` + produces `{{"a": {0, 1}}, {"a": {2, 3}}}` + + Args: + input_dataset: A `Tensor` of type `variant`. + size: A `Tensor` of type `int64`. + An integer scalar, representing the number of elements + of the input dataset to combine into a window. Must be positive. + shift: A `Tensor` of type `int64`. + An integer scalar, representing the number of input elements + by which the window moves in each iteration. Defaults to `size`. + Must be positive. + stride: A `Tensor` of type `int64`. + An integer scalar, representing the stride of the input elements + in the sliding window. Must be positive. The default value of 1 means + "retain every input element". + drop_remainder: A `Tensor` of type `bool`. + A Boolean scalar, representing whether the last window should be + dropped if its size is smaller than `window_size`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WindowDataset", name, input_dataset, size, shift, stride, + drop_remainder, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return window_dataset_eager_fallback( + input_dataset, size, shift, stride, drop_remainder, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WindowDataset", input_dataset=input_dataset, size=size, shift=shift, + stride=stride, drop_remainder=drop_remainder, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "WindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WindowDataset = tf_export("raw_ops.WindowDataset")(_ops.to_raw_op(window_dataset)) + + +def window_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], size: Annotated[Any, _atypes.Int64], shift: Annotated[Any, _atypes.Int64], stride: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + size = _ops.convert_to_tensor(size, _dtypes.int64) + shift = _ops.convert_to_tensor(shift, _dtypes.int64) + stride = _ops.convert_to_tensor(stride, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset, size, shift, stride, drop_remainder] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"WindowDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "WindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def window_op(inputs, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + inputs: A list of `Tensor` objects. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WindowOp", name, inputs, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return window_op_eager_fallback( + inputs, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'window_op' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'window_op' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WindowOp", inputs=inputs, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "Tinputs", + _op.get_attr("Tinputs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "WindowOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WindowOp = tf_export("raw_ops.WindowOp")(_ops.to_raw_op(window_op)) + + +def window_op_eager_fallback(inputs, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'window_op' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'window_op' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tinputs, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx) + _inputs_flat = list(inputs) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "Tinputs", _attr_Tinputs) + _result = _execute.execute(b"WindowOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "WindowOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def wrap_dataset_variant(input_handle: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_handle: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WrapDatasetVariant", name, input_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return wrap_dataset_variant_eager_fallback( + input_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WrapDatasetVariant", input_handle=input_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "WrapDatasetVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WrapDatasetVariant = tf_export("raw_ops.WrapDatasetVariant")(_ops.to_raw_op(wrap_dataset_variant)) + + +def wrap_dataset_variant_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Variant]: + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = None + _result = _execute.execute(b"WrapDatasetVariant", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "WrapDatasetVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def zip_dataset(input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that zips together `input_datasets`. + + The elements of the resulting dataset are created by zipping corresponding + elements from each of the input datasets. + + The size of the resulting dataset will match the size of the smallest input + dataset, and no error will be raised if input datasets have different sizes. + + Args: + input_datasets: A list of at least 1 `Tensor` objects with type `variant`. + List of `N` variant Tensors representing datasets to be zipped together. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ZipDataset", name, input_datasets, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return zip_dataset_eager_fallback( + input_datasets, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'zip_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'zip_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'zip_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ZipDataset", input_datasets=input_datasets, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N"), + "metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ZipDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ZipDataset = tf_export("raw_ops.ZipDataset")(_ops.to_raw_op(zip_dataset)) + + +def zip_dataset_eager_fallback(input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'zip_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'zip_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'zip_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_datasets = _ops.convert_n_to_tensor(input_datasets, _dtypes.variant) + _inputs_flat = list(input_datasets) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, "N", + _attr_N, "metadata", metadata) + _result = _execute.execute(b"ZipDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ZipDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_debug_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_debug_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..89eb9b63db128e267316ac66105aa85748781d4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_debug_ops.py @@ -0,0 +1,1073 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Copy_T = TypeVar("TV_Copy_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def copy(input: Annotated[Any, TV_Copy_T], tensor_name:str="", debug_ops_spec=[], name=None) -> Annotated[Any, TV_Copy_T]: + r"""Copy a tensor from CPU-to-CPU or GPU-to-GPU. + + Performs CPU-to-CPU or GPU-to-GPU deep-copying of tensor, depending on the + device on which the tensor is allocated. + N.B.: If the all downstream attached debug ops are disabled given the current + gRPC gating status, the output will simply forward the input tensor without + deep-copying. See the documentation of Debug* ops for more details. + + Unlike the CopyHost Op, this op does not have HostMemory constraint on its + input or output. + + Args: + input: A `Tensor`. Input tensor. + tensor_name: An optional `string`. Defaults to `""`. + The name of the input tensor. + debug_ops_spec: An optional list of `strings`. Defaults to `[]`. + A list of debug op spec (op, url, gated_grpc) for attached debug + ops. Each element of the list has the format + ;;, wherein gated_grpc is boolean represented + as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", + "DebugIdentity;file:///tmp/tfdbg_1;0". + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Copy", name, input, "tensor_name", tensor_name, + "debug_ops_spec", debug_ops_spec) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return copy_eager_fallback( + input, tensor_name=tensor_name, debug_ops_spec=debug_ops_spec, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_ops_spec is None: + debug_ops_spec = [] + if not isinstance(debug_ops_spec, (list, tuple)): + raise TypeError( + "Expected list for 'debug_ops_spec' argument to " + "'copy' Op, not %r." % debug_ops_spec) + debug_ops_spec = [_execute.make_str(_s, "debug_ops_spec") for _s in debug_ops_spec] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Copy", input=input, tensor_name=tensor_name, + debug_ops_spec=debug_ops_spec, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "tensor_name", + _op.get_attr("tensor_name"), "debug_ops_spec", + _op.get_attr("debug_ops_spec")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Copy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Copy = tf_export("raw_ops.Copy")(_ops.to_raw_op(copy)) + + +def copy_eager_fallback(input: Annotated[Any, TV_Copy_T], tensor_name: str, debug_ops_spec, name, ctx) -> Annotated[Any, TV_Copy_T]: + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_ops_spec is None: + debug_ops_spec = [] + if not isinstance(debug_ops_spec, (list, tuple)): + raise TypeError( + "Expected list for 'debug_ops_spec' argument to " + "'copy' Op, not %r." % debug_ops_spec) + debug_ops_spec = [_execute.make_str(_s, "debug_ops_spec") for _s in debug_ops_spec] + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "tensor_name", tensor_name, "debug_ops_spec", + debug_ops_spec) + _result = _execute.execute(b"Copy", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Copy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CopyHost_T = TypeVar("TV_CopyHost_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def copy_host(input: Annotated[Any, TV_CopyHost_T], tensor_name:str="", debug_ops_spec=[], name=None) -> Annotated[Any, TV_CopyHost_T]: + r"""Copy a tensor to host. + + Performs CPU-to-CPU deep-copying of tensor. + N.B.: If the all downstream attached debug ops are disabled given the current + gRPC gating status, the output will simply forward the input tensor without + deep-copying. See the documentation of Debug* ops for more details. + + Unlike the Copy Op, this op has HostMemory constraint on its input or output. + + Args: + input: A `Tensor`. Input tensor. + tensor_name: An optional `string`. Defaults to `""`. + The name of the input tensor. + debug_ops_spec: An optional list of `strings`. Defaults to `[]`. + A list of debug op spec (op, url, gated_grpc) for attached debug + ops. Each element of the list has the format + ;;, wherein gated_grpc is boolean represented + as 0/1. E.g., "DebugIdentity;grpc://foo:3333;1", + "DebugIdentity;file:///tmp/tfdbg_1;0". + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CopyHost", name, input, "tensor_name", tensor_name, + "debug_ops_spec", debug_ops_spec) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return copy_host_eager_fallback( + input, tensor_name=tensor_name, debug_ops_spec=debug_ops_spec, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_ops_spec is None: + debug_ops_spec = [] + if not isinstance(debug_ops_spec, (list, tuple)): + raise TypeError( + "Expected list for 'debug_ops_spec' argument to " + "'copy_host' Op, not %r." % debug_ops_spec) + debug_ops_spec = [_execute.make_str(_s, "debug_ops_spec") for _s in debug_ops_spec] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CopyHost", input=input, tensor_name=tensor_name, + debug_ops_spec=debug_ops_spec, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "tensor_name", + _op.get_attr("tensor_name"), "debug_ops_spec", + _op.get_attr("debug_ops_spec")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CopyHost", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CopyHost = tf_export("raw_ops.CopyHost")(_ops.to_raw_op(copy_host)) + + +def copy_host_eager_fallback(input: Annotated[Any, TV_CopyHost_T], tensor_name: str, debug_ops_spec, name, ctx) -> Annotated[Any, TV_CopyHost_T]: + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_ops_spec is None: + debug_ops_spec = [] + if not isinstance(debug_ops_spec, (list, tuple)): + raise TypeError( + "Expected list for 'debug_ops_spec' argument to " + "'copy_host' Op, not %r." % debug_ops_spec) + debug_ops_spec = [_execute.make_str(_s, "debug_ops_spec") for _s in debug_ops_spec] + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "tensor_name", tensor_name, "debug_ops_spec", + debug_ops_spec) + _result = _execute.execute(b"CopyHost", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CopyHost", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugIdentity_T = TypeVar("TV_DebugIdentity_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_identity(input: Annotated[Any, TV_DebugIdentity_T], device_name:str="", tensor_name:str="", debug_urls=[], gated_grpc:bool=False, name=None) -> Annotated[Any, TV_DebugIdentity_T]: + r"""Provides an identity mapping of the non-Ref type input tensor for debugging. + + Provides an identity mapping of the non-Ref type input tensor for debugging. + + Args: + input: A `Tensor`. Input tensor, non-Reference type + device_name: An optional `string`. Defaults to `""`. + Name of the device on which the tensor resides. + tensor_name: An optional `string`. Defaults to `""`. + Name of the input tensor. + debug_urls: An optional list of `strings`. Defaults to `[]`. + List of URLs to debug targets, e.g., + file:///foo/tfdbg_dump, grpc:://localhost:11011 + gated_grpc: An optional `bool`. Defaults to `False`. + Whether this op will be gated. If any of the debug_urls of this + debug node is of the grpc:// scheme, when the value of this attribute is set + to True, the data will not actually be sent via the grpc stream unless this + debug op has been enabled at the debug_url. If all of the debug_urls of this + debug node are of the grpc:// scheme and the debug op is enabled at none of + them, the output will be an empty Tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugIdentity", name, input, "device_name", device_name, + "tensor_name", tensor_name, "debug_urls", debug_urls, "gated_grpc", + gated_grpc) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_identity_eager_fallback( + input, device_name=device_name, tensor_name=tensor_name, + debug_urls=debug_urls, gated_grpc=gated_grpc, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugIdentity", input=input, device_name=device_name, + tensor_name=tensor_name, debug_urls=debug_urls, + gated_grpc=gated_grpc, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "device_name", + _op.get_attr("device_name"), "tensor_name", + _op.get_attr("tensor_name"), "debug_urls", + _op.get_attr("debug_urls"), "gated_grpc", + _op._get_attr_bool("gated_grpc")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugIdentity = tf_export("raw_ops.DebugIdentity")(_ops.to_raw_op(debug_identity)) + + +def debug_identity_eager_fallback(input: Annotated[Any, TV_DebugIdentity_T], device_name: str, tensor_name: str, debug_urls, gated_grpc: bool, name, ctx) -> Annotated[Any, TV_DebugIdentity_T]: + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "device_name", device_name, "tensor_name", + tensor_name, "debug_urls", debug_urls, "gated_grpc", gated_grpc) + _result = _execute.execute(b"DebugIdentity", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugIdentity", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugIdentityV2_T = TypeVar("TV_DebugIdentityV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_identity_v2(input: Annotated[Any, TV_DebugIdentityV2_T], tfdbg_context_id:str="", op_name:str="", output_slot:int=-1, tensor_debug_mode:int=-1, debug_urls=[], circular_buffer_size:int=1000, tfdbg_run_id:str="", name=None) -> Annotated[Any, TV_DebugIdentityV2_T]: + r"""Debug Identity V2 Op. + + Provides an identity mapping from input to output, while writing the content of + the input tensor by calling DebugEventsWriter. + + The semantics of the input tensor depends on tensor_debug_mode. In typical + usage, the input tensor comes directly from the user computation only when + graph_debug_mode is FULL_TENSOR (see protobuf/debug_event.proto for a + list of all the possible values of graph_debug_mode). For the other debug modes, + the input tensor should be produced by an additional op or subgraph that + computes summary information about one or more tensors. + + Args: + input: A `Tensor`. Input tensor, non-Reference type + tfdbg_context_id: An optional `string`. Defaults to `""`. + A tfdbg-generated ID for the context that the op belongs to, + e.g., a concrete compiled tf.function. + op_name: An optional `string`. Defaults to `""`. + Optional. Name of the op that the debug op is concerned with. + Used only for single-tensor trace. + output_slot: An optional `int`. Defaults to `-1`. + Optional. Output slot index of the tensor that the debug op + is concerned with. Used only for single-tensor trace. + tensor_debug_mode: An optional `int`. Defaults to `-1`. + TensorDebugMode enum value. See debug_event.proto for details. + debug_urls: An optional list of `strings`. Defaults to `[]`. + List of URLs to debug targets, e.g., file:///foo/tfdbg_dump. + circular_buffer_size: An optional `int`. Defaults to `1000`. + tfdbg_run_id: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugIdentityV2", name, input, "tfdbg_context_id", + tfdbg_context_id, "op_name", op_name, "output_slot", output_slot, + "tensor_debug_mode", tensor_debug_mode, "debug_urls", debug_urls, + "circular_buffer_size", circular_buffer_size, "tfdbg_run_id", + tfdbg_run_id) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_identity_v2_eager_fallback( + input, tfdbg_context_id=tfdbg_context_id, op_name=op_name, + output_slot=output_slot, tensor_debug_mode=tensor_debug_mode, + debug_urls=debug_urls, circular_buffer_size=circular_buffer_size, + tfdbg_run_id=tfdbg_run_id, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if tfdbg_context_id is None: + tfdbg_context_id = "" + tfdbg_context_id = _execute.make_str(tfdbg_context_id, "tfdbg_context_id") + if op_name is None: + op_name = "" + op_name = _execute.make_str(op_name, "op_name") + if output_slot is None: + output_slot = -1 + output_slot = _execute.make_int(output_slot, "output_slot") + if tensor_debug_mode is None: + tensor_debug_mode = -1 + tensor_debug_mode = _execute.make_int(tensor_debug_mode, "tensor_debug_mode") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity_v2' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if circular_buffer_size is None: + circular_buffer_size = 1000 + circular_buffer_size = _execute.make_int(circular_buffer_size, "circular_buffer_size") + if tfdbg_run_id is None: + tfdbg_run_id = "" + tfdbg_run_id = _execute.make_str(tfdbg_run_id, "tfdbg_run_id") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugIdentityV2", input=input, tfdbg_context_id=tfdbg_context_id, + op_name=op_name, output_slot=output_slot, + tensor_debug_mode=tensor_debug_mode, + debug_urls=debug_urls, + circular_buffer_size=circular_buffer_size, + tfdbg_run_id=tfdbg_run_id, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "tfdbg_context_id", + _op.get_attr("tfdbg_context_id"), "op_name", + _op.get_attr("op_name"), "output_slot", + _op._get_attr_int("output_slot"), "tensor_debug_mode", + _op._get_attr_int("tensor_debug_mode"), "debug_urls", + _op.get_attr("debug_urls"), "circular_buffer_size", + _op._get_attr_int("circular_buffer_size"), "tfdbg_run_id", + _op.get_attr("tfdbg_run_id")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugIdentityV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugIdentityV2 = tf_export("raw_ops.DebugIdentityV2")(_ops.to_raw_op(debug_identity_v2)) + + +def debug_identity_v2_eager_fallback(input: Annotated[Any, TV_DebugIdentityV2_T], tfdbg_context_id: str, op_name: str, output_slot: int, tensor_debug_mode: int, debug_urls, circular_buffer_size: int, tfdbg_run_id: str, name, ctx) -> Annotated[Any, TV_DebugIdentityV2_T]: + if tfdbg_context_id is None: + tfdbg_context_id = "" + tfdbg_context_id = _execute.make_str(tfdbg_context_id, "tfdbg_context_id") + if op_name is None: + op_name = "" + op_name = _execute.make_str(op_name, "op_name") + if output_slot is None: + output_slot = -1 + output_slot = _execute.make_int(output_slot, "output_slot") + if tensor_debug_mode is None: + tensor_debug_mode = -1 + tensor_debug_mode = _execute.make_int(tensor_debug_mode, "tensor_debug_mode") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity_v2' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if circular_buffer_size is None: + circular_buffer_size = 1000 + circular_buffer_size = _execute.make_int(circular_buffer_size, "circular_buffer_size") + if tfdbg_run_id is None: + tfdbg_run_id = "" + tfdbg_run_id = _execute.make_str(tfdbg_run_id, "tfdbg_run_id") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "tfdbg_context_id", tfdbg_context_id, "op_name", + op_name, "output_slot", output_slot, "tensor_debug_mode", tensor_debug_mode, + "debug_urls", debug_urls, "circular_buffer_size", circular_buffer_size, + "tfdbg_run_id", tfdbg_run_id) + _result = _execute.execute(b"DebugIdentityV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugIdentityV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugIdentityV3_T = TypeVar("TV_DebugIdentityV3_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_identity_v3(input: Annotated[Any, TV_DebugIdentityV3_T], device_name:str="", tensor_name:str="", io_of_node:str="", is_input:bool=False, io_index:int=-1, debug_urls=[], gated_grpc:bool=False, name=None) -> Annotated[Any, TV_DebugIdentityV3_T]: + r"""Provides an identity mapping of the non-Ref type input tensor for debugging. + + Provides an identity mapping of the non-Ref type input tensor for debugging. + + Args: + input: A `Tensor`. Input tensor, non-Reference type + device_name: An optional `string`. Defaults to `""`. + Name of the device on which the tensor resides. + tensor_name: An optional `string`. Defaults to `""`. + Name of the input tensor. + io_of_node: An optional `string`. Defaults to `""`. + Name of the node of which the tensor is an input or output. + is_input: An optional `bool`. Defaults to `False`. + If true, the tensor is an input of the node; otherwise the output. + io_index: An optional `int`. Defaults to `-1`. + The index of which the tensor is an input or output of the node. + debug_urls: An optional list of `strings`. Defaults to `[]`. + List of URLs to debug targets, e.g., + file:///foo/tfdbg_dump, grpc:://localhost:11011 + gated_grpc: An optional `bool`. Defaults to `False`. + Whether this op will be gated. If any of the debug_urls of this + debug node is of the grpc:// scheme, when the value of this attribute is set + to True, the data will not actually be sent via the grpc stream unless this + debug op has been enabled at the debug_url. If all of the debug_urls of this + debug node are of the grpc:// scheme and the debug op is enabled at none of + them, the output will be an empty Tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugIdentityV3", name, input, "device_name", device_name, + "tensor_name", tensor_name, "io_of_node", io_of_node, "is_input", + is_input, "io_index", io_index, "debug_urls", debug_urls, + "gated_grpc", gated_grpc) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_identity_v3_eager_fallback( + input, device_name=device_name, tensor_name=tensor_name, + io_of_node=io_of_node, is_input=is_input, io_index=io_index, + debug_urls=debug_urls, gated_grpc=gated_grpc, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if io_of_node is None: + io_of_node = "" + io_of_node = _execute.make_str(io_of_node, "io_of_node") + if is_input is None: + is_input = False + is_input = _execute.make_bool(is_input, "is_input") + if io_index is None: + io_index = -1 + io_index = _execute.make_int(io_index, "io_index") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity_v3' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugIdentityV3", input=input, device_name=device_name, + tensor_name=tensor_name, io_of_node=io_of_node, + is_input=is_input, io_index=io_index, + debug_urls=debug_urls, gated_grpc=gated_grpc, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "device_name", + _op.get_attr("device_name"), "tensor_name", + _op.get_attr("tensor_name"), "io_of_node", + _op.get_attr("io_of_node"), "is_input", + _op._get_attr_bool("is_input"), "io_index", + _op._get_attr_int("io_index"), "debug_urls", + _op.get_attr("debug_urls"), "gated_grpc", + _op._get_attr_bool("gated_grpc")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugIdentityV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugIdentityV3 = tf_export("raw_ops.DebugIdentityV3")(_ops.to_raw_op(debug_identity_v3)) + + +def debug_identity_v3_eager_fallback(input: Annotated[Any, TV_DebugIdentityV3_T], device_name: str, tensor_name: str, io_of_node: str, is_input: bool, io_index: int, debug_urls, gated_grpc: bool, name, ctx) -> Annotated[Any, TV_DebugIdentityV3_T]: + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if io_of_node is None: + io_of_node = "" + io_of_node = _execute.make_str(io_of_node, "io_of_node") + if is_input is None: + is_input = False + is_input = _execute.make_bool(is_input, "is_input") + if io_index is None: + io_index = -1 + io_index = _execute.make_int(io_index, "io_index") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_identity_v3' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "device_name", device_name, "tensor_name", + tensor_name, "io_of_node", io_of_node, "is_input", is_input, "io_index", + io_index, "debug_urls", debug_urls, "gated_grpc", gated_grpc) + _result = _execute.execute(b"DebugIdentityV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugIdentityV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugNanCount_T = TypeVar("TV_DebugNanCount_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_nan_count(input: Annotated[Any, TV_DebugNanCount_T], device_name:str="", tensor_name:str="", debug_urls=[], gated_grpc:bool=False, name=None) -> Annotated[Any, _atypes.Int64]: + r"""Debug NaN Value Counter Op. + + Counts number of NaNs in the input tensor, for debugging. + + Args: + input: A `Tensor`. Input tensor, non-Reference type. + device_name: An optional `string`. Defaults to `""`. + tensor_name: An optional `string`. Defaults to `""`. + Name of the input tensor. + debug_urls: An optional list of `strings`. Defaults to `[]`. + List of URLs to debug targets, e.g., + file:///foo/tfdbg_dump, grpc:://localhost:11011. + gated_grpc: An optional `bool`. Defaults to `False`. + Whether this op will be gated. If any of the debug_urls of this + debug node is of the grpc:// scheme, when the value of this attribute is set + to True, the data will not actually be sent via the grpc stream unless this + debug op has been enabled at the debug_url. If all of the debug_urls of this + debug node are of the grpc:// scheme and the debug op is enabled at none of + them, the output will be an empty Tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugNanCount", name, input, "device_name", device_name, + "tensor_name", tensor_name, "debug_urls", debug_urls, "gated_grpc", + gated_grpc) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_nan_count_eager_fallback( + input, device_name=device_name, tensor_name=tensor_name, + debug_urls=debug_urls, gated_grpc=gated_grpc, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_nan_count' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugNanCount", input=input, device_name=device_name, + tensor_name=tensor_name, debug_urls=debug_urls, + gated_grpc=gated_grpc, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "device_name", + _op.get_attr("device_name"), "tensor_name", + _op.get_attr("tensor_name"), "debug_urls", + _op.get_attr("debug_urls"), "gated_grpc", + _op._get_attr_bool("gated_grpc")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugNanCount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugNanCount = tf_export("raw_ops.DebugNanCount")(_ops.to_raw_op(debug_nan_count)) + + +def debug_nan_count_eager_fallback(input: Annotated[Any, TV_DebugNanCount_T], device_name: str, tensor_name: str, debug_urls, gated_grpc: bool, name, ctx) -> Annotated[Any, _atypes.Int64]: + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_nan_count' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "device_name", device_name, "tensor_name", + tensor_name, "debug_urls", debug_urls, "gated_grpc", gated_grpc) + _result = _execute.execute(b"DebugNanCount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugNanCount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugNumericSummary_T = TypeVar("TV_DebugNumericSummary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_numeric_summary(input: Annotated[Any, TV_DebugNumericSummary_T], device_name:str="", tensor_name:str="", debug_urls=[], lower_bound:float=float('-inf'), upper_bound:float=float('inf'), mute_if_healthy:bool=False, gated_grpc:bool=False, name=None) -> Annotated[Any, _atypes.Float64]: + r"""Debug Numeric Summary Op. + + Provide a basic summary of numeric value types, range and distribution. + + output: A double tensor of shape [14 + nDimensions], where nDimensions is the + number of dimensions of the tensor's shape. The elements of output are: + [0]: is initialized (1.0) or not (0.0). + [1]: total number of elements + [2]: NaN element count + [3]: generalized -inf count: elements <= lower_bound. lower_bound is -inf by + default. + [4]: negative element count (excluding -inf), if lower_bound is the default + -inf. Otherwise, this is the count of elements > lower_bound and < 0. + [5]: zero element count + [6]: positive element count (excluding +inf), if upper_bound is the default + +inf. Otherwise, this is the count of elements < upper_bound and > 0. + [7]: generalized +inf count, elements >= upper_bound. upper_bound is +inf by + default. + Output elements [1:8] are all zero, if the tensor is uninitialized. + [8]: minimum of all non-inf and non-NaN elements. + If uninitialized or no such element exists: +inf. + [9]: maximum of all non-inf and non-NaN elements. + If uninitialized or no such element exists: -inf. + [10]: mean of all non-inf and non-NaN elements. + If uninitialized or no such element exists: NaN. + [11]: variance of all non-inf and non-NaN elements. + If uninitialized or no such element exists: NaN. + [12]: Data type of the tensor encoded as an enum integer. See the DataType + proto for more details. + [13]: Number of dimensions of the tensor (ndims). + [14+]: Sizes of the dimensions. + + Args: + input: A `Tensor`. Input tensor, non-Reference type. + device_name: An optional `string`. Defaults to `""`. + tensor_name: An optional `string`. Defaults to `""`. + Name of the input tensor. + debug_urls: An optional list of `strings`. Defaults to `[]`. + List of URLs to debug targets, e.g., + file:///foo/tfdbg_dump, grpc:://localhost:11011. + lower_bound: An optional `float`. Defaults to `float('-inf')`. + (float) The lower bound <= which values will be included in the + generalized -inf count. Default: -inf. + upper_bound: An optional `float`. Defaults to `float('inf')`. + (float) The upper bound >= which values will be included in the + generalized +inf count. Default: +inf. + mute_if_healthy: An optional `bool`. Defaults to `False`. + (bool) Do not send data to the debug URLs unless at least one + of elements [2], [3] and [7] (i.e., the nan count and the generalized -inf and + inf counts) is non-zero. + gated_grpc: An optional `bool`. Defaults to `False`. + Whether this op will be gated. If any of the debug_urls of this + debug node is of the grpc:// scheme, when the value of this attribute is set + to True, the data will not actually be sent via the grpc stream unless this + debug op has been enabled at the debug_url. If all of the debug_urls of this + debug node are of the grpc:// scheme and the debug op is enabled at none of + them, the output will be an empty Tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugNumericSummary", name, input, "device_name", device_name, + "tensor_name", tensor_name, "debug_urls", debug_urls, "lower_bound", + lower_bound, "upper_bound", upper_bound, "mute_if_healthy", + mute_if_healthy, "gated_grpc", gated_grpc) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_numeric_summary_eager_fallback( + input, device_name=device_name, tensor_name=tensor_name, + debug_urls=debug_urls, lower_bound=lower_bound, + upper_bound=upper_bound, mute_if_healthy=mute_if_healthy, + gated_grpc=gated_grpc, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_numeric_summary' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if lower_bound is None: + lower_bound = float('-inf') + lower_bound = _execute.make_float(lower_bound, "lower_bound") + if upper_bound is None: + upper_bound = float('inf') + upper_bound = _execute.make_float(upper_bound, "upper_bound") + if mute_if_healthy is None: + mute_if_healthy = False + mute_if_healthy = _execute.make_bool(mute_if_healthy, "mute_if_healthy") + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugNumericSummary", input=input, device_name=device_name, + tensor_name=tensor_name, debug_urls=debug_urls, + lower_bound=lower_bound, + upper_bound=upper_bound, + mute_if_healthy=mute_if_healthy, + gated_grpc=gated_grpc, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "device_name", + _op.get_attr("device_name"), "tensor_name", + _op.get_attr("tensor_name"), "debug_urls", + _op.get_attr("debug_urls"), "lower_bound", + _op.get_attr("lower_bound"), "upper_bound", + _op.get_attr("upper_bound"), "mute_if_healthy", + _op._get_attr_bool("mute_if_healthy"), "gated_grpc", + _op._get_attr_bool("gated_grpc")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugNumericSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugNumericSummary = tf_export("raw_ops.DebugNumericSummary")(_ops.to_raw_op(debug_numeric_summary)) + + +def debug_numeric_summary_eager_fallback(input: Annotated[Any, TV_DebugNumericSummary_T], device_name: str, tensor_name: str, debug_urls, lower_bound: float, upper_bound: float, mute_if_healthy: bool, gated_grpc: bool, name, ctx) -> Annotated[Any, _atypes.Float64]: + if device_name is None: + device_name = "" + device_name = _execute.make_str(device_name, "device_name") + if tensor_name is None: + tensor_name = "" + tensor_name = _execute.make_str(tensor_name, "tensor_name") + if debug_urls is None: + debug_urls = [] + if not isinstance(debug_urls, (list, tuple)): + raise TypeError( + "Expected list for 'debug_urls' argument to " + "'debug_numeric_summary' Op, not %r." % debug_urls) + debug_urls = [_execute.make_str(_s, "debug_urls") for _s in debug_urls] + if lower_bound is None: + lower_bound = float('-inf') + lower_bound = _execute.make_float(lower_bound, "lower_bound") + if upper_bound is None: + upper_bound = float('inf') + upper_bound = _execute.make_float(upper_bound, "upper_bound") + if mute_if_healthy is None: + mute_if_healthy = False + mute_if_healthy = _execute.make_bool(mute_if_healthy, "mute_if_healthy") + if gated_grpc is None: + gated_grpc = False + gated_grpc = _execute.make_bool(gated_grpc, "gated_grpc") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "device_name", device_name, "tensor_name", + tensor_name, "debug_urls", debug_urls, "lower_bound", lower_bound, + "upper_bound", upper_bound, "mute_if_healthy", mute_if_healthy, + "gated_grpc", gated_grpc) + _result = _execute.execute(b"DebugNumericSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugNumericSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DebugNumericSummaryV2_output_dtype = TypeVar("TV_DebugNumericSummaryV2_output_dtype", _atypes.Float32, _atypes.Float64) +TV_DebugNumericSummaryV2_T = TypeVar("TV_DebugNumericSummaryV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def debug_numeric_summary_v2(input: Annotated[Any, TV_DebugNumericSummaryV2_T], output_dtype:TV_DebugNumericSummaryV2_output_dtype=_dtypes.float32, tensor_debug_mode:int=-1, tensor_id:int=-1, name=None) -> Annotated[Any, TV_DebugNumericSummaryV2_output_dtype]: + r"""Debug Numeric Summary V2 Op. + + Computes a numeric summary of the input tensor. The shape of the output + depends on the tensor_debug_mode attribute. + This op is used internally by TensorFlow Debugger (tfdbg) v2. + + Args: + input: A `Tensor`. Input tensor, to be summarized by the op. + output_dtype: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + Optional. The type of the output. Can be float32 or float64 (default: float32). + tensor_debug_mode: An optional `int`. Defaults to `-1`. + Tensor debug mode: the mode in which the input tensor is summarized + by the op. See the TensorDebugMode enum in + tensorflow/core/protobuf/debug_event.proto for details. + + Supported values: + 2 (CURT_HEALTH): Output a float32/64 tensor of shape [2]. The 1st + element is the tensor_id, if provided, and -1 otherwise. The 2nd + element is a bit which is set to 1 if the input tensor has an + infinity or nan value, or zero otherwise. + + 3 (CONCISE_HEALTH): Output a float32/64 tensor of shape [5]. The 1st + element is the tensor_id, if provided, and -1 otherwise. The + remaining four slots are the total number of elements, -infs, + +infs, and nans in the input tensor respectively. + + 4 (FULL_HEALTH): Output a float32/64 tensor of shape [11]. The 1st + element is the tensor_id, if provided, and -1 otherwise. The 2nd + element is the device_id, if provided, and -1 otherwise. The 3rd + element holds the datatype value of the input tensor as according + to the enumerated type in tensorflow/core/framework/types.proto. + The remaining elements hold the total number of elements, -infs, + +infs, nans, negative finite numbers, zeros, and positive finite + numbers in the input tensor respectively. + + 5 (SHAPE): Output a float32/64 tensor of shape [10]. The 1st + element is the tensor_id, if provided, and -1 otherwise. The 2nd + element holds the datatype value of the input tensor as according + to the enumerated type in tensorflow/core/framework/types.proto. + The 3rd element holds the rank of the tensor. The 4th element holds + the number of elements within the tensor. Finally the remaining 6 + elements hold the shape of the tensor. If the rank of the tensor + is lower than 6, the shape is right padded with zeros. If the rank + is greater than 6, the head of the shape is truncated. + + 6 (FULL_NUMERICS): Output a float32/64 tensor of shape [22]. The 1st + element is the tensor_id, if provided, and -1 otherwise. The 2nd + element is the device_id, if provided, and -1 otherwise. The 3rd + element holds the datatype value of the input tensor as according + to the enumerated type in tensorflow/core/framework/types.proto. + The 4th element holds the rank of the tensor. The 5th to 11th + elements hold the shape of the tensor. If the rank of the tensor + is lower than 6, the shape is right padded with zeros. If the rank + is greater than 6, the head of the shape is truncated. The 12th to + 18th elements hold the number of elements, -infs, +infs, nans, + denormal floats, negative finite numbers, zeros, and positive + finite numbers in the input tensor respectively. The final four + elements hold the min value, max value, mean, and variance of the + input tensor. + + 8 (REDUCE_INF_NAN_THREE_SLOTS): Output a float32/64 tensor of shape + [3]. The 1st element is -inf if any elements of the input tensor + is -inf, or zero otherwise. The 2nd element is +inf if any elements + of the input tensor is +inf, or zero otherwise. The 3rd element is + nan if any element of the input tensor is nan, or zero otherwise. + tensor_id: An optional `int`. Defaults to `-1`. + Optional. An integer identifier for the tensor being summarized by this op. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DebugNumericSummaryV2", name, input, "output_dtype", + output_dtype, "tensor_debug_mode", tensor_debug_mode, "tensor_id", + tensor_id) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return debug_numeric_summary_v2_eager_fallback( + input, output_dtype=output_dtype, + tensor_debug_mode=tensor_debug_mode, tensor_id=tensor_id, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_dtype is None: + output_dtype = _dtypes.float32 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + if tensor_debug_mode is None: + tensor_debug_mode = -1 + tensor_debug_mode = _execute.make_int(tensor_debug_mode, "tensor_debug_mode") + if tensor_id is None: + tensor_id = -1 + tensor_id = _execute.make_int(tensor_id, "tensor_id") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DebugNumericSummaryV2", input=input, output_dtype=output_dtype, + tensor_debug_mode=tensor_debug_mode, + tensor_id=tensor_id, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_dtype", _op._get_attr_type("output_dtype"), "T", + _op._get_attr_type("T"), "tensor_debug_mode", + _op._get_attr_int("tensor_debug_mode"), "tensor_id", + _op._get_attr_int("tensor_id")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DebugNumericSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DebugNumericSummaryV2 = tf_export("raw_ops.DebugNumericSummaryV2")(_ops.to_raw_op(debug_numeric_summary_v2)) + + +def debug_numeric_summary_v2_eager_fallback(input: Annotated[Any, TV_DebugNumericSummaryV2_T], output_dtype: TV_DebugNumericSummaryV2_output_dtype, tensor_debug_mode: int, tensor_id: int, name, ctx) -> Annotated[Any, TV_DebugNumericSummaryV2_output_dtype]: + if output_dtype is None: + output_dtype = _dtypes.float32 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + if tensor_debug_mode is None: + tensor_debug_mode = -1 + tensor_debug_mode = _execute.make_int(tensor_debug_mode, "tensor_debug_mode") + if tensor_id is None: + tensor_id = -1 + tensor_id = _execute.make_int(tensor_id, "tensor_id") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("output_dtype", output_dtype, "T", _attr_T, "tensor_debug_mode", + tensor_debug_mode, "tensor_id", tensor_id) + _result = _execute.execute(b"DebugNumericSummaryV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DebugNumericSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_decode_proto_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_decode_proto_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2b54f765f78083220fcb027d4395bf87e80c006e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_decode_proto_ops.py @@ -0,0 +1,319 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_DecodeProtoV2Output = collections.namedtuple( + "DecodeProtoV2", + ["sizes", "values"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.decode_proto') +def decode_proto_v2(bytes: Annotated[Any, _atypes.String], message_type: str, field_names, output_types, descriptor_source:str="local://", message_format:str="binary", sanitize:bool=False, name=None): + r"""The op extracts fields from a serialized protocol buffers message into tensors. + + Note: This API is designed for orthogonality rather than human-friendliness. It + can be used to parse input protos by hand, but it is intended for use in + generated code. + + The `decode_proto` op extracts fields from a serialized protocol buffers + message into tensors. The fields in `field_names` are decoded and converted + to the corresponding `output_types` if possible. + + A `message_type` name must be provided to give context for the field names. + The actual message descriptor can be looked up either in the linked-in + descriptor pool or a filename provided by the caller using the + `descriptor_source` attribute. + + Each output tensor is a dense tensor. This means that it is padded to hold + the largest number of repeated elements seen in the input minibatch. (The + shape is also padded by one to prevent zero-sized dimensions). The actual + repeat counts for each example in the minibatch can be found in the `sizes` + output. In many cases the output of `decode_proto` is fed immediately into + tf.squeeze if missing values are not a concern. When using tf.squeeze, always + pass the squeeze dimension explicitly to avoid surprises. + + For the most part, the mapping between Proto field types and TensorFlow dtypes + is straightforward. However, there are a few special cases: + + - A proto field that contains a submessage or group can only be converted + to `DT_STRING` (the serialized submessage). This is to reduce the complexity + of the API. The resulting string can be used as input to another instance of + the decode_proto op. + + - TensorFlow lacks support for unsigned integers. The ops represent uint64 + types as a `DT_INT64` with the same twos-complement bit pattern (the obvious + way). Unsigned int32 values can be represented exactly by specifying type + `DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in + the `output_types` attribute. + + - `map` fields are not directly decoded. They are treated as `repeated` fields, + of the appropriate entry type. The proto-compiler defines entry types for each + map field. The type-name is the field name, converted to "CamelCase" with + "Entry" appended. The `tf.train.Features.FeatureEntry` message is an example of + one of these implicit `Entry` types. + + - `enum` fields should be read as int32. + + Both binary and text proto serializations are supported, and can be + chosen using the `format` attribute. + + The `descriptor_source` attribute selects the source of protocol + descriptors to consult when looking up `message_type`. This may be: + + - An empty string or "local://", in which case protocol descriptors are + created for C++ (not Python) proto definitions linked to the binary. + + - A file, in which case protocol descriptors are created from the file, + which is expected to contain a `FileDescriptorSet` serialized as a string. + NOTE: You can build a `descriptor_source` file using the `--descriptor_set_out` + and `--include_imports` options to the protocol compiler `protoc`. + + - A "bytes://", in which protocol descriptors are created from ``, + which is expected to be a `FileDescriptorSet` serialized as a string. + + Here is an example: + + The, internal, `Summary.Value` proto contains a + `oneof {float simple_value; Image image; ...}` + + >>> from google.protobuf import text_format + >>> + >>> # A Summary.Value contains: oneof {float simple_value; Image image} + >>> values = [ + ... "simple_value: 2.2", + ... "simple_value: 1.2", + ... "image { height: 128 width: 512 }", + ... "image { height: 256 width: 256 }",] + >>> values = [ + ... text_format.Parse(v, tf.compat.v1.Summary.Value()).SerializeToString() + ... for v in values] + + The following can decode both fields from the serialized strings: + + >>> sizes, [simple_value, image] = tf.io.decode_proto( + ... values, + ... tf.compat.v1.Summary.Value.DESCRIPTOR.full_name, + ... field_names=['simple_value', 'image'], + ... output_types=[tf.float32, tf.string]) + + The `sizes` has the same shape as the input, with an additional axis across the + fields that were decoded. Here the first column of `sizes` is the size of the + decoded `simple_value` field: + + >>> print(sizes) + tf.Tensor( + [[1 0] + [1 0] + [0 1] + [0 1]], shape=(4, 2), dtype=int32) + + The result tensors each have one more index than the input byte-strings. + The valid elements of each result tensor are indicated by + the appropriate column of `sizes`. The invalid elements are padded with a + default value: + + >>> print(simple_value) + tf.Tensor( + [[2.2] + [1.2] + [0. ] + [0. ]], shape=(4, 1), dtype=float32) + + Nested protos are extracted as string tensors: + + >>> print(image.dtype) + + >>> print(image.shape.as_list()) + [4, 1] + + To convert to a `tf.RaggedTensor` representation use: + + >>> tf.RaggedTensor.from_tensor(simple_value, lengths=sizes[:, 0]).to_list() + [[2.2], [1.2], [], []] + + Args: + bytes: A `Tensor` of type `string`. + Tensor of serialized protos with shape `batch_shape`. + message_type: A `string`. Name of the proto message type to decode. + field_names: A list of `strings`. + List of strings containing proto field names. An extension field can be decoded + by using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME. + output_types: A list of `tf.DTypes`. + List of TF types to use for the respective field in field_names. + descriptor_source: An optional `string`. Defaults to `"local://"`. + Either the special value `local://` or a path to a file containing + a serialized `FileDescriptorSet`. + message_format: An optional `string`. Defaults to `"binary"`. + Either `binary` or `text`. + sanitize: An optional `bool`. Defaults to `False`. + Whether to sanitize the result or not. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sizes, values). + + sizes: A `Tensor` of type `int32`. + values: A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeProtoV2", name, bytes, "message_type", message_type, + "field_names", field_names, "output_types", output_types, + "descriptor_source", descriptor_source, "message_format", + message_format, "sanitize", sanitize) + _result = _DecodeProtoV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_decode_proto_v2( + (bytes, message_type, field_names, output_types, descriptor_source, + message_format, sanitize, name,), None) + if _result is not NotImplemented: + return _result + return decode_proto_v2_eager_fallback( + bytes, message_type=message_type, field_names=field_names, + output_types=output_types, descriptor_source=descriptor_source, + message_format=message_format, sanitize=sanitize, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_proto_v2, (), dict(bytes=bytes, message_type=message_type, + field_names=field_names, + output_types=output_types, + descriptor_source=descriptor_source, + message_format=message_format, + sanitize=sanitize, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_decode_proto_v2( + (bytes, message_type, field_names, output_types, descriptor_source, + message_format, sanitize, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + message_type = _execute.make_str(message_type, "message_type") + if not isinstance(field_names, (list, tuple)): + raise TypeError( + "Expected list for 'field_names' argument to " + "'decode_proto_v2' Op, not %r." % field_names) + field_names = [_execute.make_str(_s, "field_names") for _s in field_names] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'decode_proto_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if descriptor_source is None: + descriptor_source = "local://" + descriptor_source = _execute.make_str(descriptor_source, "descriptor_source") + if message_format is None: + message_format = "binary" + message_format = _execute.make_str(message_format, "message_format") + if sanitize is None: + sanitize = False + sanitize = _execute.make_bool(sanitize, "sanitize") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeProtoV2", bytes=bytes, message_type=message_type, + field_names=field_names, output_types=output_types, + descriptor_source=descriptor_source, + message_format=message_format, sanitize=sanitize, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_proto_v2, (), dict(bytes=bytes, message_type=message_type, + field_names=field_names, + output_types=output_types, + descriptor_source=descriptor_source, + message_format=message_format, + sanitize=sanitize, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("message_type", _op.get_attr("message_type"), "field_names", + _op.get_attr("field_names"), "output_types", + _op.get_attr("output_types"), "descriptor_source", + _op.get_attr("descriptor_source"), "message_format", + _op.get_attr("message_format"), "sanitize", + _op._get_attr_bool("sanitize")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeProtoV2", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _DecodeProtoV2Output._make(_result) + return _result + +DecodeProtoV2 = tf_export("raw_ops.DecodeProtoV2")(_ops.to_raw_op(decode_proto_v2)) +_dispatcher_for_decode_proto_v2 = decode_proto_v2._tf_type_based_dispatcher.Dispatch + + +def decode_proto_v2_eager_fallback(bytes: Annotated[Any, _atypes.String], message_type: str, field_names, output_types, descriptor_source: str, message_format: str, sanitize: bool, name, ctx): + message_type = _execute.make_str(message_type, "message_type") + if not isinstance(field_names, (list, tuple)): + raise TypeError( + "Expected list for 'field_names' argument to " + "'decode_proto_v2' Op, not %r." % field_names) + field_names = [_execute.make_str(_s, "field_names") for _s in field_names] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'decode_proto_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if descriptor_source is None: + descriptor_source = "local://" + descriptor_source = _execute.make_str(descriptor_source, "descriptor_source") + if message_format is None: + message_format = "binary" + message_format = _execute.make_str(message_format, "message_format") + if sanitize is None: + sanitize = False + sanitize = _execute.make_bool(sanitize, "sanitize") + bytes = _ops.convert_to_tensor(bytes, _dtypes.string) + _inputs_flat = [bytes] + _attrs = ("message_type", message_type, "field_names", field_names, + "output_types", output_types, "descriptor_source", descriptor_source, + "message_format", message_format, "sanitize", sanitize) + _result = _execute.execute(b"DecodeProtoV2", len(output_types) + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeProtoV2", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:]] + _result = _DecodeProtoV2Output._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_encode_proto_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_encode_proto_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1c8ddd410b03865f255c53c9fc269c448bdff03a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_encode_proto_ops.py @@ -0,0 +1,190 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.encode_proto') +def encode_proto(sizes: Annotated[Any, _atypes.Int32], values, field_names, message_type: str, descriptor_source:str="local://", name=None) -> Annotated[Any, _atypes.String]: + r"""The op serializes protobuf messages provided in the input tensors. + + The types of the tensors in `values` must match the schema for the fields + specified in `field_names`. All the tensors in `values` must have a common + shape prefix, *batch_shape*. + + The `sizes` tensor specifies repeat counts for each field. The repeat count + (last dimension) of a each tensor in `values` must be greater than or equal + to corresponding repeat count in `sizes`. + + A `message_type` name must be provided to give context for the field names. + The actual message descriptor can be looked up either in the linked-in + descriptor pool or a filename provided by the caller using the + `descriptor_source` attribute. + + For the most part, the mapping between Proto field types and TensorFlow dtypes + is straightforward. However, there are a few special cases: + + - A proto field that contains a submessage or group can only be converted + to `DT_STRING` (the serialized submessage). This is to reduce the complexity + of the API. The resulting string can be used as input to another instance of + the decode_proto op. + + - TensorFlow lacks support for unsigned integers. The ops represent uint64 + types as a `DT_INT64` with the same twos-complement bit pattern (the obvious + way). Unsigned int32 values can be represented exactly by specifying type + `DT_INT64`, or using twos-complement if the caller specifies `DT_INT32` in + the `output_types` attribute. + + The `descriptor_source` attribute selects the source of protocol + descriptors to consult when looking up `message_type`. This may be: + + - An empty string or "local://", in which case protocol descriptors are + created for C++ (not Python) proto definitions linked to the binary. + + - A file, in which case protocol descriptors are created from the file, + which is expected to contain a `FileDescriptorSet` serialized as a string. + NOTE: You can build a `descriptor_source` file using the `--descriptor_set_out` + and `--include_imports` options to the protocol compiler `protoc`. + + - A "bytes://", in which protocol descriptors are created from ``, + which is expected to be a `FileDescriptorSet` serialized as a string. + + Args: + sizes: A `Tensor` of type `int32`. + Tensor of int32 with shape `[batch_shape, len(field_names)]`. + values: A list of `Tensor` objects. + List of tensors containing values for the corresponding field. + field_names: A list of `strings`. + List of strings containing proto field names. + message_type: A `string`. Name of the proto message type to decode. + descriptor_source: An optional `string`. Defaults to `"local://"`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodeProto", name, sizes, values, "field_names", field_names, + "message_type", message_type, "descriptor_source", descriptor_source) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_encode_proto( + (sizes, values, field_names, message_type, descriptor_source, + name,), None) + if _result is not NotImplemented: + return _result + return encode_proto_eager_fallback( + sizes, values, field_names=field_names, message_type=message_type, + descriptor_source=descriptor_source, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_proto, (), dict(sizes=sizes, values=values, + field_names=field_names, + message_type=message_type, + descriptor_source=descriptor_source, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_encode_proto( + (sizes, values, field_names, message_type, descriptor_source, name,), + None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(field_names, (list, tuple)): + raise TypeError( + "Expected list for 'field_names' argument to " + "'encode_proto' Op, not %r." % field_names) + field_names = [_execute.make_str(_s, "field_names") for _s in field_names] + message_type = _execute.make_str(message_type, "message_type") + if descriptor_source is None: + descriptor_source = "local://" + descriptor_source = _execute.make_str(descriptor_source, "descriptor_source") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodeProto", sizes=sizes, values=values, field_names=field_names, + message_type=message_type, + descriptor_source=descriptor_source, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_proto, (), dict(sizes=sizes, values=values, + field_names=field_names, + message_type=message_type, + descriptor_source=descriptor_source, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("field_names", _op.get_attr("field_names"), "message_type", + _op.get_attr("message_type"), "descriptor_source", + _op.get_attr("descriptor_source"), "Tinput_types", + _op.get_attr("Tinput_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodeProto", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodeProto = tf_export("raw_ops.EncodeProto")(_ops.to_raw_op(encode_proto)) +_dispatcher_for_encode_proto = encode_proto._tf_type_based_dispatcher.Dispatch + + +def encode_proto_eager_fallback(sizes: Annotated[Any, _atypes.Int32], values, field_names, message_type: str, descriptor_source: str, name, ctx) -> Annotated[Any, _atypes.String]: + if not isinstance(field_names, (list, tuple)): + raise TypeError( + "Expected list for 'field_names' argument to " + "'encode_proto' Op, not %r." % field_names) + field_names = [_execute.make_str(_s, "field_names") for _s in field_names] + message_type = _execute.make_str(message_type, "message_type") + if descriptor_source is None: + descriptor_source = "local://" + descriptor_source = _execute.make_str(descriptor_source, "descriptor_source") + _attr_Tinput_types, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + sizes = _ops.convert_to_tensor(sizes, _dtypes.int32) + _inputs_flat = [sizes] + list(values) + _attrs = ("field_names", field_names, "message_type", message_type, + "descriptor_source", descriptor_source, "Tinput_types", _attr_Tinput_types) + _result = _execute.execute(b"EncodeProto", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodeProto", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_experimental_dataset_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_experimental_dataset_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf089dd7f78ef0402ecd7c85d25066412a40511 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_experimental_dataset_ops.py @@ -0,0 +1,10610 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def assert_cardinality_dataset(input_dataset: Annotated[Any, _atypes.Variant], cardinality: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + cardinality: A `Tensor` of type `int64`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssertCardinalityDataset", name, input_dataset, cardinality, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assert_cardinality_dataset_eager_fallback( + input_dataset, cardinality, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_cardinality_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_cardinality_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssertCardinalityDataset", input_dataset=input_dataset, + cardinality=cardinality, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AssertCardinalityDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AssertCardinalityDataset = tf_export("raw_ops.AssertCardinalityDataset")(_ops.to_raw_op(assert_cardinality_dataset)) + + +def assert_cardinality_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], cardinality: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_cardinality_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_cardinality_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cardinality = _ops.convert_to_tensor(cardinality, _dtypes.int64) + _inputs_flat = [input_dataset, cardinality] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AssertCardinalityDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AssertCardinalityDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def assert_next_dataset(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""A transformation that asserts which transformations happen next. + + This transformation checks whether the camel-case names (i.e. "FlatMap", not + "flat_map") of the transformations following this transformation match the list + of names in the `transformations` argument. If there is a mismatch, the + transformation raises an exception. + + The check occurs when iterating over the contents of the dataset, which + means that the check happens *after* any static optimizations are applied + to the dataset graph. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + `AssertNextDataset` passes through the outputs of its input dataset. + transformations: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying the transformations that are + expected to happen next. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssertNextDataset", name, input_dataset, transformations, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assert_next_dataset_eager_fallback( + input_dataset, transformations, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_next_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_next_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssertNextDataset", input_dataset=input_dataset, + transformations=transformations, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AssertNextDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AssertNextDataset = tf_export("raw_ops.AssertNextDataset")(_ops.to_raw_op(assert_next_dataset)) + + +def assert_next_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_next_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_next_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + transformations = _ops.convert_to_tensor(transformations, _dtypes.string) + _inputs_flat = [input_dataset, transformations] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AssertNextDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AssertNextDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def assert_prev_dataset(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""A transformation that asserts which transformations happened previously. + + This transformation checks the names and, optionally, the attribute name-value + pairs in the `transformations` argument against those of the transformations + that preceded this transformation. If there is a mismatch, the transformation + raises an exception. + + The check occurs when iterating over the contents of the dataset, which + means that the check happens *after* any static optimizations are applied + to the dataset graph. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + `AssertPrevDataset` passes through the outputs of its input dataset. + transformations: A `Tensor` of type `string`. + A `tf.string` vector `tf.Tensor` identifying the transformations, with optional + attribute name-value pairs, that are expected to have happened previously. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssertPrevDataset", name, input_dataset, transformations, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assert_prev_dataset_eager_fallback( + input_dataset, transformations, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_prev_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_prev_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssertPrevDataset", input_dataset=input_dataset, + transformations=transformations, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AssertPrevDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AssertPrevDataset = tf_export("raw_ops.AssertPrevDataset")(_ops.to_raw_op(assert_prev_dataset)) + + +def assert_prev_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'assert_prev_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'assert_prev_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + transformations = _ops.convert_to_tensor(transformations, _dtypes.string) + _inputs_flat = [input_dataset, transformations] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"AssertPrevDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AssertPrevDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def auto_shard_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_workers: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, auto_shard_policy:int=0, num_replicas:int=0, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that shards the input dataset. + + Creates a dataset that shards the input dataset by num_workers, returning a + sharded dataset for the index-th worker. This attempts to automatically shard + a dataset by examining the Dataset graph and inserting a shard op before the + inputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset). + + This dataset will throw a NotFound error if we cannot shard the dataset + automatically. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + num_workers: A `Tensor` of type `int64`. + A scalar representing the number of workers to distribute this dataset across. + index: A `Tensor` of type `int64`. + A scalar representing the index of the current worker out of num_workers. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + auto_shard_policy: An optional `int`. Defaults to `0`. + num_replicas: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AutoShardDataset", name, input_dataset, num_workers, index, + "auto_shard_policy", auto_shard_policy, "output_types", output_types, + "output_shapes", output_shapes, "num_replicas", num_replicas) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return auto_shard_dataset_eager_fallback( + input_dataset, num_workers, index, + auto_shard_policy=auto_shard_policy, output_types=output_types, + output_shapes=output_shapes, num_replicas=num_replicas, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'auto_shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'auto_shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if auto_shard_policy is None: + auto_shard_policy = 0 + auto_shard_policy = _execute.make_int(auto_shard_policy, "auto_shard_policy") + if num_replicas is None: + num_replicas = 0 + num_replicas = _execute.make_int(num_replicas, "num_replicas") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AutoShardDataset", input_dataset=input_dataset, + num_workers=num_workers, index=index, + output_types=output_types, + output_shapes=output_shapes, + auto_shard_policy=auto_shard_policy, + num_replicas=num_replicas, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("auto_shard_policy", _op._get_attr_int("auto_shard_policy"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "num_replicas", + _op._get_attr_int("num_replicas")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AutoShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AutoShardDataset = tf_export("raw_ops.AutoShardDataset")(_ops.to_raw_op(auto_shard_dataset)) + + +def auto_shard_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_workers: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, auto_shard_policy: int, num_replicas: int, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'auto_shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'auto_shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if auto_shard_policy is None: + auto_shard_policy = 0 + auto_shard_policy = _execute.make_int(auto_shard_policy, "auto_shard_policy") + if num_replicas is None: + num_replicas = 0 + num_replicas = _execute.make_int(num_replicas, "num_replicas") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_workers = _ops.convert_to_tensor(num_workers, _dtypes.int64) + index = _ops.convert_to_tensor(index, _dtypes.int64) + _inputs_flat = [input_dataset, num_workers, index] + _attrs = ("auto_shard_policy", auto_shard_policy, "output_types", + output_types, "output_shapes", output_shapes, "num_replicas", num_replicas) + _result = _execute.execute(b"AutoShardDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AutoShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def bytes_produced_stats_dataset(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Records the bytes size of each element of `input_dataset` in a StatsAggregator. + + Args: + input_dataset: A `Tensor` of type `variant`. + tag: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BytesProducedStatsDataset", name, input_dataset, tag, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bytes_produced_stats_dataset_eager_fallback( + input_dataset, tag, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'bytes_produced_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'bytes_produced_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BytesProducedStatsDataset", input_dataset=input_dataset, tag=tag, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BytesProducedStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BytesProducedStatsDataset = tf_export("raw_ops.BytesProducedStatsDataset")(_ops.to_raw_op(bytes_produced_stats_dataset)) + + +def bytes_produced_stats_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'bytes_produced_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'bytes_produced_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [input_dataset, tag] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"BytesProducedStatsDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BytesProducedStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def csv_dataset(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + filenames: A `Tensor` of type `string`. + compression_type: A `Tensor` of type `string`. + buffer_size: A `Tensor` of type `int64`. + header: A `Tensor` of type `bool`. + field_delim: A `Tensor` of type `string`. + use_quote_delim: A `Tensor` of type `bool`. + na_value: A `Tensor` of type `string`. + select_cols: A `Tensor` of type `int64`. + record_defaults: A list of `Tensor` objects with types from: `float32`, `float64`, `int32`, `int64`, `string`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CSVDataset", name, filenames, compression_type, buffer_size, + header, field_delim, use_quote_delim, na_value, select_cols, + record_defaults, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return csv_dataset_eager_fallback( + filenames, compression_type, buffer_size, header, field_delim, + use_quote_delim, na_value, select_cols, record_defaults, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'csv_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CSVDataset", filenames=filenames, compression_type=compression_type, + buffer_size=buffer_size, header=header, + field_delim=field_delim, + use_quote_delim=use_quote_delim, na_value=na_value, + select_cols=select_cols, + record_defaults=record_defaults, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CSVDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CSVDataset = tf_export("raw_ops.CSVDataset")(_ops.to_raw_op(csv_dataset)) + + +def csv_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'csv_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_output_types, record_defaults = _execute.convert_to_mixed_eager_tensors(record_defaults, ctx) + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + header = _ops.convert_to_tensor(header, _dtypes.bool) + field_delim = _ops.convert_to_tensor(field_delim, _dtypes.string) + use_quote_delim = _ops.convert_to_tensor(use_quote_delim, _dtypes.bool) + na_value = _ops.convert_to_tensor(na_value, _dtypes.string) + select_cols = _ops.convert_to_tensor(select_cols, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size, header, field_delim, use_quote_delim, na_value, select_cols] + list(record_defaults) + _attrs = ("output_types", _attr_output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"CSVDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CSVDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def csv_dataset_v2(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, exclude_cols: Annotated[Any, _atypes.Int64], output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + filenames: A `Tensor` of type `string`. + compression_type: A `Tensor` of type `string`. + buffer_size: A `Tensor` of type `int64`. + header: A `Tensor` of type `bool`. + field_delim: A `Tensor` of type `string`. + use_quote_delim: A `Tensor` of type `bool`. + na_value: A `Tensor` of type `string`. + select_cols: A `Tensor` of type `int64`. + record_defaults: A list of `Tensor` objects with types from: `float32`, `float64`, `int32`, `int64`, `string`. + exclude_cols: A `Tensor` of type `int64`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CSVDatasetV2", name, filenames, compression_type, buffer_size, + header, field_delim, use_quote_delim, na_value, select_cols, + record_defaults, exclude_cols, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return csv_dataset_v2_eager_fallback( + filenames, compression_type, buffer_size, header, field_delim, + use_quote_delim, na_value, select_cols, record_defaults, + exclude_cols, output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'csv_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CSVDatasetV2", filenames=filenames, + compression_type=compression_type, + buffer_size=buffer_size, header=header, + field_delim=field_delim, + use_quote_delim=use_quote_delim, na_value=na_value, + select_cols=select_cols, + record_defaults=record_defaults, + exclude_cols=exclude_cols, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CSVDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CSVDatasetV2 = tf_export("raw_ops.CSVDatasetV2")(_ops.to_raw_op(csv_dataset_v2)) + + +def csv_dataset_v2_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, exclude_cols: Annotated[Any, _atypes.Int64], output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'csv_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_output_types, record_defaults = _execute.convert_to_mixed_eager_tensors(record_defaults, ctx) + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + header = _ops.convert_to_tensor(header, _dtypes.bool) + field_delim = _ops.convert_to_tensor(field_delim, _dtypes.string) + use_quote_delim = _ops.convert_to_tensor(use_quote_delim, _dtypes.bool) + na_value = _ops.convert_to_tensor(na_value, _dtypes.string) + select_cols = _ops.convert_to_tensor(select_cols, _dtypes.int64) + exclude_cols = _ops.convert_to_tensor(exclude_cols, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size, header, field_delim, use_quote_delim, na_value, select_cols] + list(record_defaults) + [exclude_cols] + _attrs = ("output_types", _attr_output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"CSVDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CSVDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def choose_fastest_branch_dataset(input_dataset: Annotated[Any, _atypes.Variant], ratio_numerator: Annotated[Any, _atypes.Int64], ratio_denominator: Annotated[Any, _atypes.Int64], other_arguments, num_elements_per_branch: int, branches, other_arguments_lengths, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + ratio_numerator: A `Tensor` of type `int64`. + ratio_denominator: A `Tensor` of type `int64`. + other_arguments: A list of `Tensor` objects. + num_elements_per_branch: An `int` that is `>= 1`. + branches: A list of functions decorated with @Defun that has length `>= 1`. + other_arguments_lengths: A list of `ints` that has length `>= 1`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ChooseFastestBranchDataset", name, input_dataset, + ratio_numerator, ratio_denominator, other_arguments, + "num_elements_per_branch", num_elements_per_branch, "branches", + branches, "other_arguments_lengths", other_arguments_lengths, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return choose_fastest_branch_dataset_eager_fallback( + input_dataset, ratio_numerator, ratio_denominator, other_arguments, + num_elements_per_branch=num_elements_per_branch, branches=branches, + other_arguments_lengths=other_arguments_lengths, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_elements_per_branch = _execute.make_int(num_elements_per_branch, "num_elements_per_branch") + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % branches) + if not isinstance(other_arguments_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'other_arguments_lengths' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % other_arguments_lengths) + other_arguments_lengths = [_execute.make_int(_i, "other_arguments_lengths") for _i in other_arguments_lengths] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ChooseFastestBranchDataset", input_dataset=input_dataset, + ratio_numerator=ratio_numerator, + ratio_denominator=ratio_denominator, + other_arguments=other_arguments, + num_elements_per_branch=num_elements_per_branch, + branches=branches, + other_arguments_lengths=other_arguments_lengths, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Targuments", _op.get_attr("Targuments"), + "num_elements_per_branch", + _op._get_attr_int("num_elements_per_branch"), "branches", + _op.get_attr("branches"), "other_arguments_lengths", + _op.get_attr("other_arguments_lengths"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ChooseFastestBranchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ChooseFastestBranchDataset = tf_export("raw_ops.ChooseFastestBranchDataset")(_ops.to_raw_op(choose_fastest_branch_dataset)) + + +def choose_fastest_branch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], ratio_numerator: Annotated[Any, _atypes.Int64], ratio_denominator: Annotated[Any, _atypes.Int64], other_arguments, num_elements_per_branch: int, branches, other_arguments_lengths, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + num_elements_per_branch = _execute.make_int(num_elements_per_branch, "num_elements_per_branch") + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % branches) + if not isinstance(other_arguments_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'other_arguments_lengths' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % other_arguments_lengths) + other_arguments_lengths = [_execute.make_int(_i, "other_arguments_lengths") for _i in other_arguments_lengths] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'choose_fastest_branch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + ratio_numerator = _ops.convert_to_tensor(ratio_numerator, _dtypes.int64) + ratio_denominator = _ops.convert_to_tensor(ratio_denominator, _dtypes.int64) + _inputs_flat = [input_dataset, ratio_numerator, ratio_denominator] + list(other_arguments) + _attrs = ("Targuments", _attr_Targuments, "num_elements_per_branch", + num_elements_per_branch, "branches", branches, "other_arguments_lengths", + other_arguments_lengths, "output_types", output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"ChooseFastestBranchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ChooseFastestBranchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def choose_fastest_dataset(input_datasets: Annotated[List[Any], _atypes.Variant], num_experiments: int, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_datasets: A list of at least 2 `Tensor` objects with type `variant`. + num_experiments: An `int`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ChooseFastestDataset", name, input_datasets, "num_experiments", + num_experiments, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return choose_fastest_dataset_eager_fallback( + input_datasets, num_experiments=num_experiments, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'choose_fastest_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + num_experiments = _execute.make_int(num_experiments, "num_experiments") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'choose_fastest_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'choose_fastest_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ChooseFastestDataset", input_datasets=input_datasets, + num_experiments=num_experiments, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "num_experiments", + _op._get_attr_int("num_experiments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ChooseFastestDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ChooseFastestDataset = tf_export("raw_ops.ChooseFastestDataset")(_ops.to_raw_op(choose_fastest_dataset)) + + +def choose_fastest_dataset_eager_fallback(input_datasets: Annotated[List[Any], _atypes.Variant], num_experiments: int, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'choose_fastest_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + num_experiments = _execute.make_int(num_experiments, "num_experiments") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'choose_fastest_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'choose_fastest_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_datasets = _ops.convert_n_to_tensor(input_datasets, _dtypes.variant) + _inputs_flat = list(input_datasets) + _attrs = ("N", _attr_N, "num_experiments", num_experiments, "output_types", + output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ChooseFastestDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ChooseFastestDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def compress_element(components, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Compresses a dataset element. + + Args: + components: A list of `Tensor` objects. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CompressElement", name, components) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return compress_element_eager_fallback( + components, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CompressElement", components=components, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("input_types", _op.get_attr("input_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CompressElement", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CompressElement = tf_export("raw_ops.CompressElement")(_ops.to_raw_op(compress_element)) + + +def compress_element_eager_fallback(components, name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_input_types, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + _inputs_flat = list(components) + _attrs = ("input_types", _attr_input_types) + _result = _execute.execute(b"CompressElement", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CompressElement", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def compute_batch_size(input_dataset: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Computes the static batch size of a dataset sans partial batches. + + Args: + input_dataset: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ComputeBatchSize", name, input_dataset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return compute_batch_size_eager_fallback( + input_dataset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ComputeBatchSize", input_dataset=input_dataset, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ComputeBatchSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ComputeBatchSize = tf_export("raw_ops.ComputeBatchSize")(_ops.to_raw_op(compute_batch_size)) + + +def compute_batch_size_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int64]: + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = None + _result = _execute.execute(b"ComputeBatchSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ComputeBatchSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def data_service_dataset(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, task_refresh_interval_hint_ms:int=-1, data_transfer_protocol:str="", target_workers:str="AUTO", cross_trainer_cache_options:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that reads data from the tf.data service. + + Args: + dataset_id: A `Tensor` of type `int64`. + processing_mode: A `Tensor` of type `string`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + job_name: A `Tensor` of type `string`. + max_outstanding_requests: A `Tensor` of type `int64`. + iteration_counter: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + task_refresh_interval_hint_ms: An optional `int`. Defaults to `-1`. + data_transfer_protocol: An optional `string`. Defaults to `""`. + target_workers: An optional `string`. Defaults to `"AUTO"`. + cross_trainer_cache_options: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataServiceDataset", name, dataset_id, processing_mode, + address, protocol, job_name, max_outstanding_requests, + iteration_counter, "task_refresh_interval_hint_ms", + task_refresh_interval_hint_ms, "output_types", output_types, + "output_shapes", output_shapes, "data_transfer_protocol", + data_transfer_protocol, "target_workers", target_workers, + "cross_trainer_cache_options", cross_trainer_cache_options) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_service_dataset_eager_fallback( + dataset_id, processing_mode, address, protocol, job_name, + max_outstanding_requests, iteration_counter, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + output_types=output_types, output_shapes=output_shapes, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + cross_trainer_cache_options=cross_trainer_cache_options, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataServiceDataset", dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, protocol=protocol, + job_name=job_name, + max_outstanding_requests=max_outstanding_requests, + iteration_counter=iteration_counter, + output_types=output_types, + output_shapes=output_shapes, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + cross_trainer_cache_options=cross_trainer_cache_options, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("task_refresh_interval_hint_ms", + _op._get_attr_int("task_refresh_interval_hint_ms"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "data_transfer_protocol", + _op.get_attr("data_transfer_protocol"), "target_workers", + _op.get_attr("target_workers"), "cross_trainer_cache_options", + _op.get_attr("cross_trainer_cache_options")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataServiceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataServiceDataset = tf_export("raw_ops.DataServiceDataset")(_ops.to_raw_op(data_service_dataset)) + + +def data_service_dataset_eager_fallback(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, task_refresh_interval_hint_ms: int, data_transfer_protocol: str, target_workers: str, cross_trainer_cache_options: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + dataset_id = _ops.convert_to_tensor(dataset_id, _dtypes.int64) + processing_mode = _ops.convert_to_tensor(processing_mode, _dtypes.string) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + job_name = _ops.convert_to_tensor(job_name, _dtypes.string) + max_outstanding_requests = _ops.convert_to_tensor(max_outstanding_requests, _dtypes.int64) + iteration_counter = _ops.convert_to_tensor(iteration_counter, _dtypes.resource) + _inputs_flat = [dataset_id, processing_mode, address, protocol, job_name, max_outstanding_requests, iteration_counter] + _attrs = ("task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "cross_trainer_cache_options", cross_trainer_cache_options) + _result = _execute.execute(b"DataServiceDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataServiceDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def data_service_dataset_v2(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, task_refresh_interval_hint_ms:int=-1, data_transfer_protocol:str="", target_workers:str="AUTO", cross_trainer_cache_options:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that reads data from the tf.data service. + + Args: + dataset_id: A `Tensor` of type `int64`. + processing_mode: A `Tensor` of type `string`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + job_name: A `Tensor` of type `string`. + consumer_index: A `Tensor` of type `int64`. + num_consumers: A `Tensor` of type `int64`. + max_outstanding_requests: A `Tensor` of type `int64`. + iteration_counter: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + task_refresh_interval_hint_ms: An optional `int`. Defaults to `-1`. + data_transfer_protocol: An optional `string`. Defaults to `""`. + target_workers: An optional `string`. Defaults to `"AUTO"`. + cross_trainer_cache_options: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataServiceDatasetV2", name, dataset_id, processing_mode, + address, protocol, job_name, consumer_index, num_consumers, + max_outstanding_requests, iteration_counter, + "task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "cross_trainer_cache_options", + cross_trainer_cache_options) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_service_dataset_v2_eager_fallback( + dataset_id, processing_mode, address, protocol, job_name, + consumer_index, num_consumers, max_outstanding_requests, + iteration_counter, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + output_types=output_types, output_shapes=output_shapes, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + cross_trainer_cache_options=cross_trainer_cache_options, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataServiceDatasetV2", dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, protocol=protocol, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + iteration_counter=iteration_counter, + output_types=output_types, + output_shapes=output_shapes, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + cross_trainer_cache_options=cross_trainer_cache_options, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("task_refresh_interval_hint_ms", + _op._get_attr_int("task_refresh_interval_hint_ms"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "data_transfer_protocol", + _op.get_attr("data_transfer_protocol"), "target_workers", + _op.get_attr("target_workers"), "cross_trainer_cache_options", + _op.get_attr("cross_trainer_cache_options")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataServiceDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataServiceDatasetV2 = tf_export("raw_ops.DataServiceDatasetV2")(_ops.to_raw_op(data_service_dataset_v2)) + + +def data_service_dataset_v2_eager_fallback(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, task_refresh_interval_hint_ms: int, data_transfer_protocol: str, target_workers: str, cross_trainer_cache_options: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + dataset_id = _ops.convert_to_tensor(dataset_id, _dtypes.int64) + processing_mode = _ops.convert_to_tensor(processing_mode, _dtypes.string) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + job_name = _ops.convert_to_tensor(job_name, _dtypes.string) + consumer_index = _ops.convert_to_tensor(consumer_index, _dtypes.int64) + num_consumers = _ops.convert_to_tensor(num_consumers, _dtypes.int64) + max_outstanding_requests = _ops.convert_to_tensor(max_outstanding_requests, _dtypes.int64) + iteration_counter = _ops.convert_to_tensor(iteration_counter, _dtypes.resource) + _inputs_flat = [dataset_id, processing_mode, address, protocol, job_name, consumer_index, num_consumers, max_outstanding_requests, iteration_counter] + _attrs = ("task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "cross_trainer_cache_options", cross_trainer_cache_options) + _result = _execute.execute(b"DataServiceDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataServiceDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def data_service_dataset_v3(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, uncompress_fn, task_refresh_interval_hint_ms:int=-1, data_transfer_protocol:str="", target_workers:str="AUTO", uncompress:bool=False, cross_trainer_cache_options:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that reads data from the tf.data service. + + Args: + dataset_id: A `Tensor` of type `int64`. + processing_mode: A `Tensor` of type `string`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + job_name: A `Tensor` of type `string`. + consumer_index: A `Tensor` of type `int64`. + num_consumers: A `Tensor` of type `int64`. + max_outstanding_requests: A `Tensor` of type `int64`. + iteration_counter: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + uncompress_fn: A function decorated with @Defun. + task_refresh_interval_hint_ms: An optional `int`. Defaults to `-1`. + data_transfer_protocol: An optional `string`. Defaults to `""`. + target_workers: An optional `string`. Defaults to `"AUTO"`. + uncompress: An optional `bool`. Defaults to `False`. + cross_trainer_cache_options: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataServiceDatasetV3", name, dataset_id, processing_mode, + address, protocol, job_name, consumer_index, num_consumers, + max_outstanding_requests, iteration_counter, + "task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "uncompress", uncompress, "uncompress_fn", + uncompress_fn, "cross_trainer_cache_options", + cross_trainer_cache_options) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_service_dataset_v3_eager_fallback( + dataset_id, processing_mode, address, protocol, job_name, + consumer_index, num_consumers, max_outstanding_requests, + iteration_counter, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + output_types=output_types, output_shapes=output_shapes, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, uncompress=uncompress, + uncompress_fn=uncompress_fn, + cross_trainer_cache_options=cross_trainer_cache_options, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if uncompress is None: + uncompress = False + uncompress = _execute.make_bool(uncompress, "uncompress") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataServiceDatasetV3", dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, protocol=protocol, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + iteration_counter=iteration_counter, + output_types=output_types, + output_shapes=output_shapes, + uncompress_fn=uncompress_fn, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + uncompress=uncompress, + cross_trainer_cache_options=cross_trainer_cache_options, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("task_refresh_interval_hint_ms", + _op._get_attr_int("task_refresh_interval_hint_ms"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "data_transfer_protocol", + _op.get_attr("data_transfer_protocol"), "target_workers", + _op.get_attr("target_workers"), "uncompress", + _op._get_attr_bool("uncompress"), "uncompress_fn", + _op.get_attr("uncompress_fn"), "cross_trainer_cache_options", + _op.get_attr("cross_trainer_cache_options")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataServiceDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataServiceDatasetV3 = tf_export("raw_ops.DataServiceDatasetV3")(_ops.to_raw_op(data_service_dataset_v3)) + + +def data_service_dataset_v3_eager_fallback(dataset_id: Annotated[Any, _atypes.Int64], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, uncompress_fn, task_refresh_interval_hint_ms: int, data_transfer_protocol: str, target_workers: str, uncompress: bool, cross_trainer_cache_options: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v3' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v3' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if uncompress is None: + uncompress = False + uncompress = _execute.make_bool(uncompress, "uncompress") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + dataset_id = _ops.convert_to_tensor(dataset_id, _dtypes.int64) + processing_mode = _ops.convert_to_tensor(processing_mode, _dtypes.string) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + job_name = _ops.convert_to_tensor(job_name, _dtypes.string) + consumer_index = _ops.convert_to_tensor(consumer_index, _dtypes.int64) + num_consumers = _ops.convert_to_tensor(num_consumers, _dtypes.int64) + max_outstanding_requests = _ops.convert_to_tensor(max_outstanding_requests, _dtypes.int64) + iteration_counter = _ops.convert_to_tensor(iteration_counter, _dtypes.resource) + _inputs_flat = [dataset_id, processing_mode, address, protocol, job_name, consumer_index, num_consumers, max_outstanding_requests, iteration_counter] + _attrs = ("task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "uncompress", uncompress, "uncompress_fn", uncompress_fn, + "cross_trainer_cache_options", cross_trainer_cache_options) + _result = _execute.execute(b"DataServiceDatasetV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataServiceDatasetV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def data_service_dataset_v4(dataset_id: Annotated[Any, _atypes.String], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, uncompress_fn, task_refresh_interval_hint_ms:int=-1, data_transfer_protocol:str="", target_workers:str="AUTO", uncompress:bool=False, cross_trainer_cache_options:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that reads data from the tf.data service. + + Args: + dataset_id: A `Tensor` of type `string`. + processing_mode: A `Tensor` of type `string`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + job_name: A `Tensor` of type `string`. + consumer_index: A `Tensor` of type `int64`. + num_consumers: A `Tensor` of type `int64`. + max_outstanding_requests: A `Tensor` of type `int64`. + iteration_counter: A `Tensor` of type `resource`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + uncompress_fn: A function decorated with @Defun. + task_refresh_interval_hint_ms: An optional `int`. Defaults to `-1`. + data_transfer_protocol: An optional `string`. Defaults to `""`. + target_workers: An optional `string`. Defaults to `"AUTO"`. + uncompress: An optional `bool`. Defaults to `False`. + cross_trainer_cache_options: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataServiceDatasetV4", name, dataset_id, processing_mode, + address, protocol, job_name, consumer_index, num_consumers, + max_outstanding_requests, iteration_counter, + "task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "uncompress", uncompress, "uncompress_fn", + uncompress_fn, "cross_trainer_cache_options", + cross_trainer_cache_options) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_service_dataset_v4_eager_fallback( + dataset_id, processing_mode, address, protocol, job_name, + consumer_index, num_consumers, max_outstanding_requests, + iteration_counter, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + output_types=output_types, output_shapes=output_shapes, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, uncompress=uncompress, + uncompress_fn=uncompress_fn, + cross_trainer_cache_options=cross_trainer_cache_options, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v4' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v4' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if uncompress is None: + uncompress = False + uncompress = _execute.make_bool(uncompress, "uncompress") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataServiceDatasetV4", dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, protocol=protocol, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + iteration_counter=iteration_counter, + output_types=output_types, + output_shapes=output_shapes, + uncompress_fn=uncompress_fn, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + data_transfer_protocol=data_transfer_protocol, + target_workers=target_workers, + uncompress=uncompress, + cross_trainer_cache_options=cross_trainer_cache_options, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("task_refresh_interval_hint_ms", + _op._get_attr_int("task_refresh_interval_hint_ms"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "data_transfer_protocol", + _op.get_attr("data_transfer_protocol"), "target_workers", + _op.get_attr("target_workers"), "uncompress", + _op._get_attr_bool("uncompress"), "uncompress_fn", + _op.get_attr("uncompress_fn"), "cross_trainer_cache_options", + _op.get_attr("cross_trainer_cache_options")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataServiceDatasetV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataServiceDatasetV4 = tf_export("raw_ops.DataServiceDatasetV4")(_ops.to_raw_op(data_service_dataset_v4)) + + +def data_service_dataset_v4_eager_fallback(dataset_id: Annotated[Any, _atypes.String], processing_mode: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], job_name: Annotated[Any, _atypes.String], consumer_index: Annotated[Any, _atypes.Int64], num_consumers: Annotated[Any, _atypes.Int64], max_outstanding_requests: Annotated[Any, _atypes.Int64], iteration_counter: Annotated[Any, _atypes.Resource], output_types, output_shapes, uncompress_fn, task_refresh_interval_hint_ms: int, data_transfer_protocol: str, target_workers: str, uncompress: bool, cross_trainer_cache_options: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'data_service_dataset_v4' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'data_service_dataset_v4' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = -1 + task_refresh_interval_hint_ms = _execute.make_int(task_refresh_interval_hint_ms, "task_refresh_interval_hint_ms") + if data_transfer_protocol is None: + data_transfer_protocol = "" + data_transfer_protocol = _execute.make_str(data_transfer_protocol, "data_transfer_protocol") + if target_workers is None: + target_workers = "AUTO" + target_workers = _execute.make_str(target_workers, "target_workers") + if uncompress is None: + uncompress = False + uncompress = _execute.make_bool(uncompress, "uncompress") + if cross_trainer_cache_options is None: + cross_trainer_cache_options = "" + cross_trainer_cache_options = _execute.make_str(cross_trainer_cache_options, "cross_trainer_cache_options") + dataset_id = _ops.convert_to_tensor(dataset_id, _dtypes.string) + processing_mode = _ops.convert_to_tensor(processing_mode, _dtypes.string) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + job_name = _ops.convert_to_tensor(job_name, _dtypes.string) + consumer_index = _ops.convert_to_tensor(consumer_index, _dtypes.int64) + num_consumers = _ops.convert_to_tensor(num_consumers, _dtypes.int64) + max_outstanding_requests = _ops.convert_to_tensor(max_outstanding_requests, _dtypes.int64) + iteration_counter = _ops.convert_to_tensor(iteration_counter, _dtypes.resource) + _inputs_flat = [dataset_id, processing_mode, address, protocol, job_name, consumer_index, num_consumers, max_outstanding_requests, iteration_counter] + _attrs = ("task_refresh_interval_hint_ms", task_refresh_interval_hint_ms, + "output_types", output_types, "output_shapes", output_shapes, + "data_transfer_protocol", data_transfer_protocol, "target_workers", + target_workers, "uncompress", uncompress, "uncompress_fn", uncompress_fn, + "cross_trainer_cache_options", cross_trainer_cache_options) + _result = _execute.execute(b"DataServiceDatasetV4", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataServiceDatasetV4", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_from_graph(graph_def: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset from the given `graph_def`. + + Creates a dataset from the provided `graph_def`. + + Args: + graph_def: A `Tensor` of type `string`. + The graph representation of the dataset (as serialized GraphDef). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetFromGraph", name, graph_def) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_from_graph_eager_fallback( + graph_def, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetFromGraph", graph_def=graph_def, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DatasetFromGraph", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DatasetFromGraph = tf_export("raw_ops.DatasetFromGraph")(_ops.to_raw_op(dataset_from_graph)) + + +def dataset_from_graph_eager_fallback(graph_def: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Variant]: + graph_def = _ops.convert_to_tensor(graph_def, _dtypes.string) + _inputs_flat = [graph_def] + _attrs = None + _result = _execute.execute(b"DatasetFromGraph", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DatasetFromGraph", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def dataset_to_tf_record(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], name=None): + r"""Writes the given dataset to the given file using the TFRecord format. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to write. + filename: A `Tensor` of type `string`. + A scalar string tensor representing the filename to use. + compression_type: A `Tensor` of type `string`. + A scalar string tensor containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DatasetToTFRecord", name, input_dataset, filename, + compression_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dataset_to_tf_record_eager_fallback( + input_dataset, filename, compression_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DatasetToTFRecord", input_dataset=input_dataset, filename=filename, + compression_type=compression_type, name=name) + return _op +DatasetToTFRecord = tf_export("raw_ops.DatasetToTFRecord")(_ops.to_raw_op(dataset_to_tf_record)) + + +def dataset_to_tf_record_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], name, ctx): + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + _inputs_flat = [input_dataset, filename, compression_type] + _attrs = None + _result = _execute.execute(b"DatasetToTFRecord", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def dense_to_sparse_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], row_shape: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches input elements into a SparseTensor. + + Args: + input_dataset: A `Tensor` of type `variant`. + A handle to an input dataset. Must have a single component. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. + row_shape: A `Tensor` of type `int64`. + A vector representing the dense shape of each row in the produced + SparseTensor. The shape may be partially specified, using `-1` to indicate + that a particular dimension should use the maximum size of all batch elements. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseToSparseBatchDataset", name, input_dataset, batch_size, + row_shape, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_to_sparse_batch_dataset_eager_fallback( + input_dataset, batch_size, row_shape, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'dense_to_sparse_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'dense_to_sparse_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseToSparseBatchDataset", input_dataset=input_dataset, + batch_size=batch_size, + row_shape=row_shape, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseToSparseBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DenseToSparseBatchDataset = tf_export("raw_ops.DenseToSparseBatchDataset")(_ops.to_raw_op(dense_to_sparse_batch_dataset)) + + +def dense_to_sparse_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], row_shape: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'dense_to_sparse_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'dense_to_sparse_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + row_shape = _ops.convert_to_tensor(row_shape, _dtypes.int64) + _inputs_flat = [input_dataset, batch_size, row_shape] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"DenseToSparseBatchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseToSparseBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def directed_interleave_dataset(selector_input_dataset: Annotated[Any, _atypes.Variant], data_input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, stop_on_empty_dataset:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""A substitute for `InterleaveDataset` on a fixed list of `N` datasets. + + Args: + selector_input_dataset: A `Tensor` of type `variant`. + A dataset of scalar `DT_INT64` elements that determines which of the + `N` data inputs should produce the next output element. + data_input_datasets: A list of at least 1 `Tensor` objects with type `variant`. + `N` datasets with the same type that will be interleaved according to + the values of `selector_input_dataset`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + stop_on_empty_dataset: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DirectedInterleaveDataset", name, selector_input_dataset, + data_input_datasets, "output_types", output_types, "output_shapes", + output_shapes, "stop_on_empty_dataset", stop_on_empty_dataset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return directed_interleave_dataset_eager_fallback( + selector_input_dataset, data_input_datasets, + output_types=output_types, output_shapes=output_shapes, + stop_on_empty_dataset=stop_on_empty_dataset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(data_input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'data_input_datasets' argument to " + "'directed_interleave_dataset' Op, not %r." % data_input_datasets) + _attr_N = len(data_input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'directed_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'directed_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if stop_on_empty_dataset is None: + stop_on_empty_dataset = False + stop_on_empty_dataset = _execute.make_bool(stop_on_empty_dataset, "stop_on_empty_dataset") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DirectedInterleaveDataset", selector_input_dataset=selector_input_dataset, + data_input_datasets=data_input_datasets, + output_types=output_types, + output_shapes=output_shapes, + stop_on_empty_dataset=stop_on_empty_dataset, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N"), + "stop_on_empty_dataset", + _op._get_attr_bool("stop_on_empty_dataset")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DirectedInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DirectedInterleaveDataset = tf_export("raw_ops.DirectedInterleaveDataset")(_ops.to_raw_op(directed_interleave_dataset)) + + +def directed_interleave_dataset_eager_fallback(selector_input_dataset: Annotated[Any, _atypes.Variant], data_input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, stop_on_empty_dataset: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(data_input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'data_input_datasets' argument to " + "'directed_interleave_dataset' Op, not %r." % data_input_datasets) + _attr_N = len(data_input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'directed_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'directed_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if stop_on_empty_dataset is None: + stop_on_empty_dataset = False + stop_on_empty_dataset = _execute.make_bool(stop_on_empty_dataset, "stop_on_empty_dataset") + selector_input_dataset = _ops.convert_to_tensor(selector_input_dataset, _dtypes.variant) + data_input_datasets = _ops.convert_n_to_tensor(data_input_datasets, _dtypes.variant) + _inputs_flat = [selector_input_dataset] + list(data_input_datasets) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, "N", + _attr_N, "stop_on_empty_dataset", stop_on_empty_dataset) + _result = _execute.execute(b"DirectedInterleaveDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DirectedInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def distributed_save(dataset: Annotated[Any, _atypes.Variant], directory: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], metadata:str="", name=None): + r"""TODO: add doc. + + Args: + dataset: A `Tensor` of type `variant`. + directory: A `Tensor` of type `string`. + address: A `Tensor` of type `string`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DistributedSave", name, dataset, directory, address, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return distributed_save_eager_fallback( + dataset, directory, address, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DistributedSave", dataset=dataset, directory=directory, + address=address, metadata=metadata, name=name) + return _op +DistributedSave = tf_export("raw_ops.DistributedSave")(_ops.to_raw_op(distributed_save)) + + +def distributed_save_eager_fallback(dataset: Annotated[Any, _atypes.Variant], directory: Annotated[Any, _atypes.String], address: Annotated[Any, _atypes.String], metadata: str, name, ctx): + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + directory = _ops.convert_to_tensor(directory, _dtypes.string) + address = _ops.convert_to_tensor(address, _dtypes.string) + _inputs_flat = [dataset, directory, address] + _attrs = ("metadata", metadata) + _result = _execute.execute(b"DistributedSave", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def dummy_iteration_counter(name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DummyIterationCounter", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dummy_iteration_counter_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DummyIterationCounter", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DummyIterationCounter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DummyIterationCounter = tf_export("raw_ops.DummyIterationCounter")(_ops.to_raw_op(dummy_iteration_counter)) + + +def dummy_iteration_counter_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Resource]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"DummyIterationCounter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DummyIterationCounter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_assert_next_dataset(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + transformations: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalAssertNextDataset", name, input_dataset, + transformations, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_assert_next_dataset_eager_fallback( + input_dataset, transformations, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_assert_next_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_assert_next_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalAssertNextDataset", input_dataset=input_dataset, + transformations=transformations, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalAssertNextDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalAssertNextDataset = tf_export("raw_ops.ExperimentalAssertNextDataset")(_ops.to_raw_op(experimental_assert_next_dataset)) + + +def experimental_assert_next_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], transformations: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_assert_next_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_assert_next_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + transformations = _ops.convert_to_tensor(transformations, _dtypes.string) + _inputs_flat = [input_dataset, transformations] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalAssertNextDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalAssertNextDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_auto_shard_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_workers: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, auto_shard_policy:int=0, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that shards the input dataset. + + Creates a dataset that shards the input dataset by num_workers, returning a + sharded dataset for the index-th worker. This attempts to automatically shard + a dataset by examining the Dataset graph and inserting a shard op before the + inputs to a reader Dataset (e.g. CSVDataset, TFRecordDataset). + + This dataset will throw a NotFound error if we cannot shard the dataset + automatically. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + num_workers: A `Tensor` of type `int64`. + A scalar representing the number of workers to distribute this dataset across. + index: A `Tensor` of type `int64`. + A scalar representing the index of the current worker out of num_workers. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + auto_shard_policy: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalAutoShardDataset", name, input_dataset, + num_workers, index, "auto_shard_policy", auto_shard_policy, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_auto_shard_dataset_eager_fallback( + input_dataset, num_workers, index, + auto_shard_policy=auto_shard_policy, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_auto_shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_auto_shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if auto_shard_policy is None: + auto_shard_policy = 0 + auto_shard_policy = _execute.make_int(auto_shard_policy, "auto_shard_policy") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalAutoShardDataset", input_dataset=input_dataset, + num_workers=num_workers, index=index, + output_types=output_types, + output_shapes=output_shapes, + auto_shard_policy=auto_shard_policy, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("auto_shard_policy", _op._get_attr_int("auto_shard_policy"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalAutoShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalAutoShardDataset = tf_export("raw_ops.ExperimentalAutoShardDataset")(_ops.to_raw_op(experimental_auto_shard_dataset)) + + +def experimental_auto_shard_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_workers: Annotated[Any, _atypes.Int64], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, auto_shard_policy: int, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_auto_shard_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_auto_shard_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if auto_shard_policy is None: + auto_shard_policy = 0 + auto_shard_policy = _execute.make_int(auto_shard_policy, "auto_shard_policy") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_workers = _ops.convert_to_tensor(num_workers, _dtypes.int64) + index = _ops.convert_to_tensor(index, _dtypes.int64) + _inputs_flat = [input_dataset, num_workers, index] + _attrs = ("auto_shard_policy", auto_shard_policy, "output_types", + output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalAutoShardDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalAutoShardDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_bytes_produced_stats_dataset(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Records the bytes size of each element of `input_dataset` in a StatsAggregator. + + Args: + input_dataset: A `Tensor` of type `variant`. + tag: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalBytesProducedStatsDataset", name, input_dataset, + tag, "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_bytes_produced_stats_dataset_eager_fallback( + input_dataset, tag, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_bytes_produced_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_bytes_produced_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalBytesProducedStatsDataset", input_dataset=input_dataset, + tag=tag, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalBytesProducedStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalBytesProducedStatsDataset = tf_export("raw_ops.ExperimentalBytesProducedStatsDataset")(_ops.to_raw_op(experimental_bytes_produced_stats_dataset)) + + +def experimental_bytes_produced_stats_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_bytes_produced_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_bytes_produced_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [input_dataset, tag] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalBytesProducedStatsDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalBytesProducedStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_csv_dataset(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + filenames: A `Tensor` of type `string`. + compression_type: A `Tensor` of type `string`. + buffer_size: A `Tensor` of type `int64`. + header: A `Tensor` of type `bool`. + field_delim: A `Tensor` of type `string`. + use_quote_delim: A `Tensor` of type `bool`. + na_value: A `Tensor` of type `string`. + select_cols: A `Tensor` of type `int64`. + record_defaults: A list of `Tensor` objects with types from: `float32`, `float64`, `int32`, `int64`, `string`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalCSVDataset", name, filenames, compression_type, + buffer_size, header, field_delim, use_quote_delim, na_value, + select_cols, record_defaults, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_csv_dataset_eager_fallback( + filenames, compression_type, buffer_size, header, field_delim, + use_quote_delim, na_value, select_cols, record_defaults, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_csv_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalCSVDataset", filenames=filenames, + compression_type=compression_type, + buffer_size=buffer_size, header=header, + field_delim=field_delim, + use_quote_delim=use_quote_delim, + na_value=na_value, select_cols=select_cols, + record_defaults=record_defaults, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalCSVDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalCSVDataset = tf_export("raw_ops.ExperimentalCSVDataset")(_ops.to_raw_op(experimental_csv_dataset)) + + +def experimental_csv_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], buffer_size: Annotated[Any, _atypes.Int64], header: Annotated[Any, _atypes.Bool], field_delim: Annotated[Any, _atypes.String], use_quote_delim: Annotated[Any, _atypes.Bool], na_value: Annotated[Any, _atypes.String], select_cols: Annotated[Any, _atypes.Int64], record_defaults, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_csv_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_output_types, record_defaults = _execute.convert_to_mixed_eager_tensors(record_defaults, ctx) + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + buffer_size = _ops.convert_to_tensor(buffer_size, _dtypes.int64) + header = _ops.convert_to_tensor(header, _dtypes.bool) + field_delim = _ops.convert_to_tensor(field_delim, _dtypes.string) + use_quote_delim = _ops.convert_to_tensor(use_quote_delim, _dtypes.bool) + na_value = _ops.convert_to_tensor(na_value, _dtypes.string) + select_cols = _ops.convert_to_tensor(select_cols, _dtypes.int64) + _inputs_flat = [filenames, compression_type, buffer_size, header, field_delim, use_quote_delim, na_value, select_cols] + list(record_defaults) + _attrs = ("output_types", _attr_output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"ExperimentalCSVDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalCSVDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_choose_fastest_dataset(input_datasets: Annotated[List[Any], _atypes.Variant], num_experiments: int, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_datasets: A list of at least 2 `Tensor` objects with type `variant`. + num_experiments: An `int`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalChooseFastestDataset", name, input_datasets, + "num_experiments", num_experiments, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_choose_fastest_dataset_eager_fallback( + input_datasets, num_experiments=num_experiments, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + num_experiments = _execute.make_int(num_experiments, "num_experiments") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalChooseFastestDataset", input_datasets=input_datasets, + num_experiments=num_experiments, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "num_experiments", + _op._get_attr_int("num_experiments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalChooseFastestDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalChooseFastestDataset = tf_export("raw_ops.ExperimentalChooseFastestDataset")(_ops.to_raw_op(experimental_choose_fastest_dataset)) + + +def experimental_choose_fastest_dataset_eager_fallback(input_datasets: Annotated[List[Any], _atypes.Variant], num_experiments: int, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'input_datasets' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % input_datasets) + _attr_N = len(input_datasets) + num_experiments = _execute.make_int(num_experiments, "num_experiments") + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_choose_fastest_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_datasets = _ops.convert_n_to_tensor(input_datasets, _dtypes.variant) + _inputs_flat = list(input_datasets) + _attrs = ("N", _attr_N, "num_experiments", num_experiments, "output_types", + output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalChooseFastestDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalChooseFastestDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_dataset_cardinality(input_dataset: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the cardinality of `input_dataset`. + + Returns the cardinality of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to return cardinality for. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalDatasetCardinality", name, input_dataset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_dataset_cardinality_eager_fallback( + input_dataset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalDatasetCardinality", input_dataset=input_dataset, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalDatasetCardinality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalDatasetCardinality = tf_export("raw_ops.ExperimentalDatasetCardinality")(_ops.to_raw_op(experimental_dataset_cardinality)) + + +def experimental_dataset_cardinality_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int64]: + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = None + _result = _execute.execute(b"ExperimentalDatasetCardinality", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalDatasetCardinality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_dataset_to_tf_record(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], name=None): + r"""Writes the given dataset to the given file using the TFRecord format. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the dataset to write. + filename: A `Tensor` of type `string`. + A scalar string tensor representing the filename to use. + compression_type: A `Tensor` of type `string`. + A scalar string tensor containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalDatasetToTFRecord", name, input_dataset, filename, + compression_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_dataset_to_tf_record_eager_fallback( + input_dataset, filename, compression_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalDatasetToTFRecord", input_dataset=input_dataset, + filename=filename, + compression_type=compression_type, + name=name) + return _op +ExperimentalDatasetToTFRecord = tf_export("raw_ops.ExperimentalDatasetToTFRecord")(_ops.to_raw_op(experimental_dataset_to_tf_record)) + + +def experimental_dataset_to_tf_record_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], filename: Annotated[Any, _atypes.String], compression_type: Annotated[Any, _atypes.String], name, ctx): + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + compression_type = _ops.convert_to_tensor(compression_type, _dtypes.string) + _inputs_flat = [input_dataset, filename, compression_type] + _attrs = None + _result = _execute.execute(b"ExperimentalDatasetToTFRecord", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def experimental_dense_to_sparse_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], row_shape: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that batches input elements into a SparseTensor. + + Args: + input_dataset: A `Tensor` of type `variant`. + A handle to an input dataset. Must have a single component. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. + row_shape: A `Tensor` of type `int64`. + A vector representing the dense shape of each row in the produced + SparseTensor. The shape may be partially specified, using `-1` to indicate + that a particular dimension should use the maximum size of all batch elements. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalDenseToSparseBatchDataset", name, input_dataset, + batch_size, row_shape, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_dense_to_sparse_batch_dataset_eager_fallback( + input_dataset, batch_size, row_shape, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_dense_to_sparse_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_dense_to_sparse_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalDenseToSparseBatchDataset", input_dataset=input_dataset, + batch_size=batch_size, + row_shape=row_shape, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalDenseToSparseBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalDenseToSparseBatchDataset = tf_export("raw_ops.ExperimentalDenseToSparseBatchDataset")(_ops.to_raw_op(experimental_dense_to_sparse_batch_dataset)) + + +def experimental_dense_to_sparse_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_size: Annotated[Any, _atypes.Int64], row_shape: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_dense_to_sparse_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_dense_to_sparse_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + row_shape = _ops.convert_to_tensor(row_shape, _dtypes.int64) + _inputs_flat = [input_dataset, batch_size, row_shape] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalDenseToSparseBatchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalDenseToSparseBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_directed_interleave_dataset(selector_input_dataset: Annotated[Any, _atypes.Variant], data_input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""A substitute for `InterleaveDataset` on a fixed list of `N` datasets. + + Args: + selector_input_dataset: A `Tensor` of type `variant`. + A dataset of scalar `DT_INT64` elements that determines which of the + `N` data inputs should produce the next output element. + data_input_datasets: A list of at least 1 `Tensor` objects with type `variant`. + `N` datasets with the same type that will be interleaved according to + the values of `selector_input_dataset`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalDirectedInterleaveDataset", name, + selector_input_dataset, data_input_datasets, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_directed_interleave_dataset_eager_fallback( + selector_input_dataset, data_input_datasets, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(data_input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'data_input_datasets' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % data_input_datasets) + _attr_N = len(data_input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalDirectedInterleaveDataset", selector_input_dataset=selector_input_dataset, + data_input_datasets=data_input_datasets, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalDirectedInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalDirectedInterleaveDataset = tf_export("raw_ops.ExperimentalDirectedInterleaveDataset")(_ops.to_raw_op(experimental_directed_interleave_dataset)) + + +def experimental_directed_interleave_dataset_eager_fallback(selector_input_dataset: Annotated[Any, _atypes.Variant], data_input_datasets: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(data_input_datasets, (list, tuple)): + raise TypeError( + "Expected list for 'data_input_datasets' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % data_input_datasets) + _attr_N = len(data_input_datasets) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_directed_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + selector_input_dataset = _ops.convert_to_tensor(selector_input_dataset, _dtypes.variant) + data_input_datasets = _ops.convert_n_to_tensor(data_input_datasets, _dtypes.variant) + _inputs_flat = [selector_input_dataset] + list(data_input_datasets) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, "N", + _attr_N) + _result = _execute.execute(b"ExperimentalDirectedInterleaveDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalDirectedInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_group_by_reducer_dataset(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, init_func_other_arguments, reduce_func_other_arguments, finalize_func_other_arguments, key_func, init_func, reduce_func, finalize_func, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that computes a group-by on `input_dataset`. + + Creates a dataset that computes a group-by on `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + key_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `key_func`. + init_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `init_func`. + reduce_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `reduce_func`. + finalize_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `finalize_func`. + key_func: A function decorated with @Defun. + A function mapping an element of `input_dataset`, concatenated + with `key_func_other_arguments` to a scalar value of type DT_INT64. + init_func: A function decorated with @Defun. + A function mapping a key of type DT_INT64, concatenated with + `init_func_other_arguments` to the initial reducer state. + reduce_func: A function decorated with @Defun. + A function mapping the current reducer state and an element of `input_dataset`, + concatenated with `reduce_func_other_arguments` to a new reducer state. + finalize_func: A function decorated with @Defun. + A function mapping the final reducer state to an output element. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalGroupByReducerDataset", name, input_dataset, + key_func_other_arguments, init_func_other_arguments, + reduce_func_other_arguments, finalize_func_other_arguments, + "key_func", key_func, "init_func", init_func, "reduce_func", + reduce_func, "finalize_func", finalize_func, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_group_by_reducer_dataset_eager_fallback( + input_dataset, key_func_other_arguments, init_func_other_arguments, + reduce_func_other_arguments, finalize_func_other_arguments, + key_func=key_func, init_func=init_func, reduce_func=reduce_func, + finalize_func=finalize_func, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_group_by_reducer_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_group_by_reducer_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalGroupByReducerDataset", input_dataset=input_dataset, + key_func_other_arguments=key_func_other_arguments, + init_func_other_arguments=init_func_other_arguments, + reduce_func_other_arguments=reduce_func_other_arguments, + finalize_func_other_arguments=finalize_func_other_arguments, + key_func=key_func, + init_func=init_func, + reduce_func=reduce_func, + finalize_func=finalize_func, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_func", _op.get_attr("key_func"), "init_func", + _op.get_attr("init_func"), "reduce_func", + _op.get_attr("reduce_func"), "finalize_func", + _op.get_attr("finalize_func"), "Tkey_func_other_arguments", + _op.get_attr("Tkey_func_other_arguments"), + "Tinit_func_other_arguments", + _op.get_attr("Tinit_func_other_arguments"), + "Treduce_func_other_arguments", + _op.get_attr("Treduce_func_other_arguments"), + "Tfinalize_func_other_arguments", + _op.get_attr("Tfinalize_func_other_arguments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalGroupByReducerDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalGroupByReducerDataset = tf_export("raw_ops.ExperimentalGroupByReducerDataset")(_ops.to_raw_op(experimental_group_by_reducer_dataset)) + + +def experimental_group_by_reducer_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, init_func_other_arguments, reduce_func_other_arguments, finalize_func_other_arguments, key_func, init_func, reduce_func, finalize_func, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_group_by_reducer_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_group_by_reducer_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tkey_func_other_arguments, key_func_other_arguments = _execute.convert_to_mixed_eager_tensors(key_func_other_arguments, ctx) + _attr_Tinit_func_other_arguments, init_func_other_arguments = _execute.convert_to_mixed_eager_tensors(init_func_other_arguments, ctx) + _attr_Treduce_func_other_arguments, reduce_func_other_arguments = _execute.convert_to_mixed_eager_tensors(reduce_func_other_arguments, ctx) + _attr_Tfinalize_func_other_arguments, finalize_func_other_arguments = _execute.convert_to_mixed_eager_tensors(finalize_func_other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(key_func_other_arguments) + list(init_func_other_arguments) + list(reduce_func_other_arguments) + list(finalize_func_other_arguments) + _attrs = ("key_func", key_func, "init_func", init_func, "reduce_func", + reduce_func, "finalize_func", finalize_func, "Tkey_func_other_arguments", + _attr_Tkey_func_other_arguments, "Tinit_func_other_arguments", + _attr_Tinit_func_other_arguments, "Treduce_func_other_arguments", + _attr_Treduce_func_other_arguments, "Tfinalize_func_other_arguments", + _attr_Tfinalize_func_other_arguments, "output_types", output_types, + "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalGroupByReducerDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalGroupByReducerDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_group_by_window_dataset(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, reduce_func_other_arguments, window_size_func_other_arguments, key_func, reduce_func, window_size_func, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that computes a windowed group-by on `input_dataset`. + + // TODO(mrry): Support non-int64 keys. + + Args: + input_dataset: A `Tensor` of type `variant`. + key_func_other_arguments: A list of `Tensor` objects. + reduce_func_other_arguments: A list of `Tensor` objects. + window_size_func_other_arguments: A list of `Tensor` objects. + key_func: A function decorated with @Defun. + A function mapping an element of `input_dataset`, concatenated + with `key_func_other_arguments` to a scalar value of type DT_INT64. + reduce_func: A function decorated with @Defun. + window_size_func: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalGroupByWindowDataset", name, input_dataset, + key_func_other_arguments, reduce_func_other_arguments, + window_size_func_other_arguments, "key_func", key_func, "reduce_func", + reduce_func, "window_size_func", window_size_func, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_group_by_window_dataset_eager_fallback( + input_dataset, key_func_other_arguments, + reduce_func_other_arguments, window_size_func_other_arguments, + key_func=key_func, reduce_func=reduce_func, + window_size_func=window_size_func, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_group_by_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_group_by_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalGroupByWindowDataset", input_dataset=input_dataset, + key_func_other_arguments=key_func_other_arguments, + reduce_func_other_arguments=reduce_func_other_arguments, + window_size_func_other_arguments=window_size_func_other_arguments, + key_func=key_func, + reduce_func=reduce_func, + window_size_func=window_size_func, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_func", _op.get_attr("key_func"), "reduce_func", + _op.get_attr("reduce_func"), "window_size_func", + _op.get_attr("window_size_func"), "Tkey_func_other_arguments", + _op.get_attr("Tkey_func_other_arguments"), + "Treduce_func_other_arguments", + _op.get_attr("Treduce_func_other_arguments"), + "Twindow_size_func_other_arguments", + _op.get_attr("Twindow_size_func_other_arguments"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalGroupByWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalGroupByWindowDataset = tf_export("raw_ops.ExperimentalGroupByWindowDataset")(_ops.to_raw_op(experimental_group_by_window_dataset)) + + +def experimental_group_by_window_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, reduce_func_other_arguments, window_size_func_other_arguments, key_func, reduce_func, window_size_func, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_group_by_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_group_by_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tkey_func_other_arguments, key_func_other_arguments = _execute.convert_to_mixed_eager_tensors(key_func_other_arguments, ctx) + _attr_Treduce_func_other_arguments, reduce_func_other_arguments = _execute.convert_to_mixed_eager_tensors(reduce_func_other_arguments, ctx) + _attr_Twindow_size_func_other_arguments, window_size_func_other_arguments = _execute.convert_to_mixed_eager_tensors(window_size_func_other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(key_func_other_arguments) + list(reduce_func_other_arguments) + list(window_size_func_other_arguments) + _attrs = ("key_func", key_func, "reduce_func", reduce_func, + "window_size_func", window_size_func, "Tkey_func_other_arguments", + _attr_Tkey_func_other_arguments, "Treduce_func_other_arguments", + _attr_Treduce_func_other_arguments, "Twindow_size_func_other_arguments", + _attr_Twindow_size_func_other_arguments, "output_types", output_types, + "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalGroupByWindowDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalGroupByWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_ignore_errors_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, log_warning:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that contains the elements of `input_dataset` ignoring errors. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + log_warning: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalIgnoreErrorsDataset", name, input_dataset, + "output_types", output_types, "output_shapes", output_shapes, + "log_warning", log_warning) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_ignore_errors_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, log_warning=log_warning, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_ignore_errors_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_ignore_errors_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if log_warning is None: + log_warning = False + log_warning = _execute.make_bool(log_warning, "log_warning") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalIgnoreErrorsDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, + log_warning=log_warning, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "log_warning", + _op._get_attr_bool("log_warning")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalIgnoreErrorsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalIgnoreErrorsDataset = tf_export("raw_ops.ExperimentalIgnoreErrorsDataset")(_ops.to_raw_op(experimental_ignore_errors_dataset)) + + +def experimental_ignore_errors_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, log_warning: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_ignore_errors_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_ignore_errors_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if log_warning is None: + log_warning = False + log_warning = _execute.make_bool(log_warning, "log_warning") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "log_warning", log_warning) + _result = _execute.execute(b"ExperimentalIgnoreErrorsDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalIgnoreErrorsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_iterator_get_device(resource: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Returns the name of the device on which `resource` has been placed. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalIteratorGetDevice", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_iterator_get_device_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalIteratorGetDevice", resource=resource, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalIteratorGetDevice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalIteratorGetDevice = tf_export("raw_ops.ExperimentalIteratorGetDevice")(_ops.to_raw_op(experimental_iterator_get_device)) + + +def experimental_iterator_get_device_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"ExperimentalIteratorGetDevice", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalIteratorGetDevice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_lmdb_dataset(filenames: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + filenames: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalLMDBDataset", name, filenames, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_lmdb_dataset_eager_fallback( + filenames, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_lmdb_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_lmdb_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalLMDBDataset", filenames=filenames, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalLMDBDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalLMDBDataset = tf_export("raw_ops.ExperimentalLMDBDataset")(_ops.to_raw_op(experimental_lmdb_dataset)) + + +def experimental_lmdb_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_lmdb_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_lmdb_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + _inputs_flat = [filenames] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalLMDBDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalLMDBDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_latency_stats_dataset(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Records the latency of producing `input_dataset` elements in a StatsAggregator. + + Args: + input_dataset: A `Tensor` of type `variant`. + tag: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalLatencyStatsDataset", name, input_dataset, tag, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_latency_stats_dataset_eager_fallback( + input_dataset, tag, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_latency_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_latency_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalLatencyStatsDataset", input_dataset=input_dataset, + tag=tag, output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalLatencyStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalLatencyStatsDataset = tf_export("raw_ops.ExperimentalLatencyStatsDataset")(_ops.to_raw_op(experimental_latency_stats_dataset)) + + +def experimental_latency_stats_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_latency_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_latency_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [input_dataset, tag] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalLatencyStatsDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalLatencyStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_map_and_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], f, output_types, output_shapes, preserve_cardinality:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that fuses mapping with batching. + + Creates a dataset that applies `f` to the outputs of `input_dataset` and then + batches `batch_size` of them. + + Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up + to `batch_size * num_parallel_batches` copies of `f` in parallel. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when building a closure + for `f`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. It determines the number of concurrent invocations of `f` that process + elements from `input_dataset` in parallel. + num_parallel_calls: A `Tensor` of type `int64`. + A scalar representing the maximum number of parallel invocations of the `map_fn` + function. Applying the `map_fn` on consecutive input elements in parallel has + the potential to improve input pipeline throughput. + drop_remainder: A `Tensor` of type `bool`. + A scalar representing whether the last batch should be dropped in case its size + is smaller than desired. + f: A function decorated with @Defun. + A function to apply to the outputs of `input_dataset`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalMapAndBatchDataset", name, input_dataset, + other_arguments, batch_size, num_parallel_calls, drop_remainder, "f", + f, "output_types", output_types, "output_shapes", output_shapes, + "preserve_cardinality", preserve_cardinality) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_map_and_batch_dataset_eager_fallback( + input_dataset, other_arguments, batch_size, num_parallel_calls, + drop_remainder, f=f, output_types=output_types, + output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_map_and_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_map_and_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalMapAndBatchDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + batch_size=batch_size, + num_parallel_calls=num_parallel_calls, + drop_remainder=drop_remainder, f=f, + output_types=output_types, + output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalMapAndBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalMapAndBatchDataset = tf_export("raw_ops.ExperimentalMapAndBatchDataset")(_ops.to_raw_op(experimental_map_and_batch_dataset)) + + +def experimental_map_and_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], f, output_types, output_shapes, preserve_cardinality: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_map_and_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_map_and_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset] + list(other_arguments) + [batch_size, num_parallel_calls, drop_remainder] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "preserve_cardinality", + preserve_cardinality) + _result = _execute.execute(b"ExperimentalMapAndBatchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalMapAndBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_map_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, use_inter_op_parallelism:bool=True, preserve_cardinality:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_inter_op_parallelism: An optional `bool`. Defaults to `True`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalMapDataset", name, input_dataset, other_arguments, + "f", f, "output_types", output_types, "output_shapes", output_shapes, + "use_inter_op_parallelism", use_inter_op_parallelism, + "preserve_cardinality", preserve_cardinality) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_map_dataset_eager_fallback( + input_dataset, other_arguments, f=f, output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + preserve_cardinality=preserve_cardinality, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalMapDataset", input_dataset=input_dataset, + other_arguments=other_arguments, f=f, + output_types=output_types, + output_shapes=output_shapes, + use_inter_op_parallelism=use_inter_op_parallelism, + preserve_cardinality=preserve_cardinality, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_inter_op_parallelism", + _op._get_attr_bool("use_inter_op_parallelism"), + "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalMapDataset = tf_export("raw_ops.ExperimentalMapDataset")(_ops.to_raw_op(experimental_map_dataset)) + + +def experimental_map_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, f, output_types, output_shapes, use_inter_op_parallelism: bool, preserve_cardinality: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_map_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_map_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_inter_op_parallelism is None: + use_inter_op_parallelism = True + use_inter_op_parallelism = _execute.make_bool(use_inter_op_parallelism, "use_inter_op_parallelism") + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "use_inter_op_parallelism", + use_inter_op_parallelism, "preserve_cardinality", preserve_cardinality) + _result = _execute.execute(b"ExperimentalMapDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalMapDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_matching_files_dataset(patterns: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + patterns: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalMatchingFilesDataset", name, patterns) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_matching_files_dataset_eager_fallback( + patterns, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalMatchingFilesDataset", patterns=patterns, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalMatchingFilesDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalMatchingFilesDataset = tf_export("raw_ops.ExperimentalMatchingFilesDataset")(_ops.to_raw_op(experimental_matching_files_dataset)) + + +def experimental_matching_files_dataset_eager_fallback(patterns: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Variant]: + patterns = _ops.convert_to_tensor(patterns, _dtypes.string) + _inputs_flat = [patterns] + _attrs = None + _result = _execute.execute(b"ExperimentalMatchingFilesDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalMatchingFilesDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_max_intra_op_parallelism_dataset(input_dataset: Annotated[Any, _atypes.Variant], max_intra_op_parallelism: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that overrides the maximum intra-op parallelism. + + Args: + input_dataset: A `Tensor` of type `variant`. + max_intra_op_parallelism: A `Tensor` of type `int64`. + Identifies the maximum intra-op parallelism to use. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalMaxIntraOpParallelismDataset", name, input_dataset, + max_intra_op_parallelism, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_max_intra_op_parallelism_dataset_eager_fallback( + input_dataset, max_intra_op_parallelism, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_max_intra_op_parallelism_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_max_intra_op_parallelism_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalMaxIntraOpParallelismDataset", input_dataset=input_dataset, + max_intra_op_parallelism=max_intra_op_parallelism, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalMaxIntraOpParallelismDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalMaxIntraOpParallelismDataset = tf_export("raw_ops.ExperimentalMaxIntraOpParallelismDataset")(_ops.to_raw_op(experimental_max_intra_op_parallelism_dataset)) + + +def experimental_max_intra_op_parallelism_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], max_intra_op_parallelism: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_max_intra_op_parallelism_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_max_intra_op_parallelism_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + max_intra_op_parallelism = _ops.convert_to_tensor(max_intra_op_parallelism, _dtypes.int64) + _inputs_flat = [input_dataset, max_intra_op_parallelism] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalMaxIntraOpParallelismDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalMaxIntraOpParallelismDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_non_serializable_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalNonSerializableDataset", name, input_dataset, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_non_serializable_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_non_serializable_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_non_serializable_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalNonSerializableDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalNonSerializableDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalNonSerializableDataset = tf_export("raw_ops.ExperimentalNonSerializableDataset")(_ops.to_raw_op(experimental_non_serializable_dataset)) + + +def experimental_non_serializable_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_non_serializable_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_non_serializable_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalNonSerializableDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalNonSerializableDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_parallel_interleave_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], sloppy: Annotated[Any, _atypes.Bool], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, with the exception + that if retrieving the next value from a dataset would cause the requester to + block, it will skip that input dataset. This dataset is especially useful + when loading data from a variable-latency datastores (e.g. HDFS, GCS), as it + allows the training step to proceed so long as some data is available. + + !! WARNING !! This dataset is not deterministic! + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + cycle_length: A `Tensor` of type `int64`. + block_length: A `Tensor` of type `int64`. + sloppy: A `Tensor` of type `bool`. + buffer_output_elements: A `Tensor` of type `int64`. + prefetch_input_elements: A `Tensor` of type `int64`. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalParallelInterleaveDataset", name, input_dataset, + other_arguments, cycle_length, block_length, sloppy, + buffer_output_elements, prefetch_input_elements, "f", f, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_parallel_interleave_dataset_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, sloppy, + buffer_output_elements, prefetch_input_elements, f=f, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_parallel_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_parallel_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalParallelInterleaveDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, + sloppy=sloppy, + buffer_output_elements=buffer_output_elements, + prefetch_input_elements=prefetch_input_elements, + f=f, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalParallelInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalParallelInterleaveDataset = tf_export("raw_ops.ExperimentalParallelInterleaveDataset")(_ops.to_raw_op(experimental_parallel_interleave_dataset)) + + +def experimental_parallel_interleave_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], sloppy: Annotated[Any, _atypes.Bool], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_parallel_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_parallel_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + sloppy = _ops.convert_to_tensor(sloppy, _dtypes.bool) + buffer_output_elements = _ops.convert_to_tensor(buffer_output_elements, _dtypes.int64) + prefetch_input_elements = _ops.convert_to_tensor(prefetch_input_elements, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, sloppy, buffer_output_elements, prefetch_input_elements] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalParallelInterleaveDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalParallelInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_parse_example_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, sloppy:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_parallel_calls: A `Tensor` of type `int64`. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A dict mapping string keys to `Tensor`s. + The keys of the dict must match the dense_keys of the feature. + sparse_keys: A list of `strings`. + A list of string keys in the examples features. + The results for these keys will be returned as `SparseTensor` objects. + dense_keys: A list of `strings`. + A list of Ndense string Tensors (scalars). + The keys expected in the Examples features associated with dense values. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `DTypes` of the same length as `sparse_keys`. + Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), + and `tf.string` (`BytesList`) are supported. + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + List of tuples with the same length as `dense_keys`. + The shape of the data for each dense feature referenced by `dense_keys`. + Required for any input tensors identified by `dense_keys`. Must be + either fully defined, or may contain an unknown first dimension. + An unknown first dimension means the feature is treated as having + a variable number of blocks, and the output shape along this dimension + is considered unknown at graph build time. Padding is applied for + minibatch elements smaller than the maximum number of blocks for the + given feature along this dimension. + output_types: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + The list of shapes being produced. + sloppy: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalParseExampleDataset", name, input_dataset, + num_parallel_calls, dense_defaults, "sparse_keys", sparse_keys, + "dense_keys", dense_keys, "sparse_types", sparse_types, + "dense_shapes", dense_shapes, "output_types", output_types, + "output_shapes", output_shapes, "sloppy", sloppy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_parse_example_dataset_eager_fallback( + input_dataset, num_parallel_calls, dense_defaults, + sparse_keys=sparse_keys, dense_keys=dense_keys, + sparse_types=sparse_types, dense_shapes=dense_shapes, + output_types=output_types, output_shapes=output_shapes, + sloppy=sloppy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'experimental_parse_example_dataset' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'experimental_parse_example_dataset' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'experimental_parse_example_dataset' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'experimental_parse_example_dataset' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_parse_example_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_parse_example_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalParseExampleDataset", input_dataset=input_dataset, + num_parallel_calls=num_parallel_calls, + dense_defaults=dense_defaults, + sparse_keys=sparse_keys, + dense_keys=dense_keys, + sparse_types=sparse_types, + dense_shapes=dense_shapes, + output_types=output_types, + output_shapes=output_shapes, + sloppy=sloppy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sparse_keys", _op.get_attr("sparse_keys"), "dense_keys", + _op.get_attr("dense_keys"), "sparse_types", + _op.get_attr("sparse_types"), "Tdense", _op.get_attr("Tdense"), + "dense_shapes", _op.get_attr("dense_shapes"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "sloppy", + _op._get_attr_bool("sloppy")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalParseExampleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalParseExampleDataset = tf_export("raw_ops.ExperimentalParseExampleDataset")(_ops.to_raw_op(experimental_parse_example_dataset)) + + +def experimental_parse_example_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, sloppy: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'experimental_parse_example_dataset' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'experimental_parse_example_dataset' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'experimental_parse_example_dataset' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'experimental_parse_example_dataset' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_parse_example_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_parse_example_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset, num_parallel_calls] + list(dense_defaults) + _attrs = ("sparse_keys", sparse_keys, "dense_keys", dense_keys, + "sparse_types", sparse_types, "Tdense", _attr_Tdense, "dense_shapes", + dense_shapes, "output_types", output_types, "output_shapes", output_shapes, + "sloppy", sloppy) + _result = _execute.execute(b"ExperimentalParseExampleDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalParseExampleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_private_thread_pool_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_threads: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_threads: A `Tensor` of type `int64`. + Identifies the number of threads to use for the private threadpool. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalPrivateThreadPoolDataset", name, input_dataset, + num_threads, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_private_thread_pool_dataset_eager_fallback( + input_dataset, num_threads, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_private_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_private_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalPrivateThreadPoolDataset", input_dataset=input_dataset, + num_threads=num_threads, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalPrivateThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalPrivateThreadPoolDataset = tf_export("raw_ops.ExperimentalPrivateThreadPoolDataset")(_ops.to_raw_op(experimental_private_thread_pool_dataset)) + + +def experimental_private_thread_pool_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_threads: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_private_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_private_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_threads = _ops.convert_to_tensor(num_threads, _dtypes.int64) + _inputs_flat = [input_dataset, num_threads] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalPrivateThreadPoolDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalPrivateThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_random_dataset(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a Dataset that returns pseudorandom numbers. + + Args: + seed: A `Tensor` of type `int64`. + A scalar seed for the random number generator. If either seed or + seed2 is set to be non-zero, the random number generator is seeded + by the given seed. Otherwise, a random seed is used. + seed2: A `Tensor` of type `int64`. + A second scalar seed to avoid seed collision. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalRandomDataset", name, seed, seed2, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_random_dataset_eager_fallback( + seed, seed2, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_random_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_random_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalRandomDataset", seed=seed, seed2=seed2, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalRandomDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalRandomDataset = tf_export("raw_ops.ExperimentalRandomDataset")(_ops.to_raw_op(experimental_random_dataset)) + + +def experimental_random_dataset_eager_fallback(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_random_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_random_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + _inputs_flat = [seed, seed2] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalRandomDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalRandomDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_rebatch_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_replicas: Annotated[Any, _atypes.Int64], output_types, output_shapes, use_fallback:bool=True, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that changes the batch size. + + Creates a dataset that changes the batch size of the dataset to current batch + size // num_replicas. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + num_replicas: A `Tensor` of type `int64`. + A scalar representing the number of replicas to distribute this batch across. As + a result of this transformation the current batch size would end up being + divided by this parameter. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_fallback: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalRebatchDataset", name, input_dataset, num_replicas, + "output_types", output_types, "output_shapes", output_shapes, + "use_fallback", use_fallback) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_rebatch_dataset_eager_fallback( + input_dataset, num_replicas, output_types=output_types, + output_shapes=output_shapes, use_fallback=use_fallback, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_rebatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_rebatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_fallback is None: + use_fallback = True + use_fallback = _execute.make_bool(use_fallback, "use_fallback") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalRebatchDataset", input_dataset=input_dataset, + num_replicas=num_replicas, + output_types=output_types, + output_shapes=output_shapes, + use_fallback=use_fallback, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_fallback", + _op._get_attr_bool("use_fallback")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalRebatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalRebatchDataset = tf_export("raw_ops.ExperimentalRebatchDataset")(_ops.to_raw_op(experimental_rebatch_dataset)) + + +def experimental_rebatch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_replicas: Annotated[Any, _atypes.Int64], output_types, output_shapes, use_fallback: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_rebatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_rebatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_fallback is None: + use_fallback = True + use_fallback = _execute.make_bool(use_fallback, "use_fallback") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_replicas = _ops.convert_to_tensor(num_replicas, _dtypes.int64) + _inputs_flat = [input_dataset, num_replicas] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "use_fallback", use_fallback) + _result = _execute.execute(b"ExperimentalRebatchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalRebatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_scan_dataset(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, preserve_cardinality:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset successively reduces `f` over the elements of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + initial_state: A list of `Tensor` objects. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalScanDataset", name, input_dataset, initial_state, + other_arguments, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "preserve_cardinality", + preserve_cardinality) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_scan_dataset_eager_fallback( + input_dataset, initial_state, other_arguments, f=f, + output_types=output_types, output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_scan_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_scan_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalScanDataset", input_dataset=input_dataset, + initial_state=initial_state, + other_arguments=other_arguments, f=f, + output_types=output_types, + output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Tstate", _op.get_attr("Tstate"), + "Targuments", _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalScanDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalScanDataset = tf_export("raw_ops.ExperimentalScanDataset")(_ops.to_raw_op(experimental_scan_dataset)) + + +def experimental_scan_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, preserve_cardinality: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_scan_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_scan_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + _attr_Tstate, initial_state = _execute.convert_to_mixed_eager_tensors(initial_state, ctx) + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(initial_state) + list(other_arguments) + _attrs = ("f", f, "Tstate", _attr_Tstate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes, + "preserve_cardinality", preserve_cardinality) + _result = _execute.execute(b"ExperimentalScanDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalScanDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_set_stats_aggregator_dataset(input_dataset: Annotated[Any, _atypes.Variant], stats_aggregator: Annotated[Any, _atypes.Resource], tag: Annotated[Any, _atypes.String], counter_prefix: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + stats_aggregator: A `Tensor` of type `resource`. + tag: A `Tensor` of type `string`. + counter_prefix: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalSetStatsAggregatorDataset", name, input_dataset, + stats_aggregator, tag, counter_prefix, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_set_stats_aggregator_dataset_eager_fallback( + input_dataset, stats_aggregator, tag, counter_prefix, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_set_stats_aggregator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_set_stats_aggregator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalSetStatsAggregatorDataset", input_dataset=input_dataset, + stats_aggregator=stats_aggregator, + tag=tag, + counter_prefix=counter_prefix, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalSetStatsAggregatorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalSetStatsAggregatorDataset = tf_export("raw_ops.ExperimentalSetStatsAggregatorDataset")(_ops.to_raw_op(experimental_set_stats_aggregator_dataset)) + + +def experimental_set_stats_aggregator_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], stats_aggregator: Annotated[Any, _atypes.Resource], tag: Annotated[Any, _atypes.String], counter_prefix: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_set_stats_aggregator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_set_stats_aggregator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + stats_aggregator = _ops.convert_to_tensor(stats_aggregator, _dtypes.resource) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + counter_prefix = _ops.convert_to_tensor(counter_prefix, _dtypes.string) + _inputs_flat = [input_dataset, stats_aggregator, tag, counter_prefix] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalSetStatsAggregatorDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalSetStatsAggregatorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_sleep_dataset(input_dataset: Annotated[Any, _atypes.Variant], sleep_microseconds: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + sleep_microseconds: A `Tensor` of type `int64`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalSleepDataset", name, input_dataset, + sleep_microseconds, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_sleep_dataset_eager_fallback( + input_dataset, sleep_microseconds, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sleep_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sleep_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalSleepDataset", input_dataset=input_dataset, + sleep_microseconds=sleep_microseconds, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalSleepDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalSleepDataset = tf_export("raw_ops.ExperimentalSleepDataset")(_ops.to_raw_op(experimental_sleep_dataset)) + + +def experimental_sleep_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], sleep_microseconds: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sleep_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sleep_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + sleep_microseconds = _ops.convert_to_tensor(sleep_microseconds, _dtypes.int64) + _inputs_flat = [input_dataset, sleep_microseconds] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalSleepDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalSleepDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_sliding_window_dataset(input_dataset: Annotated[Any, _atypes.Variant], window_size: Annotated[Any, _atypes.Int64], window_shift: Annotated[Any, _atypes.Int64], window_stride: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that passes a sliding window over `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + window_size: A `Tensor` of type `int64`. + A scalar representing the number of elements in the + sliding window. + window_shift: A `Tensor` of type `int64`. + A scalar representing the steps moving the sliding window + forward in one iteration. It must be positive. + window_stride: A `Tensor` of type `int64`. + A scalar representing the stride of the input elements of the sliding window. + It must be positive. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalSlidingWindowDataset", name, input_dataset, + window_size, window_shift, window_stride, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_sliding_window_dataset_eager_fallback( + input_dataset, window_size, window_shift, window_stride, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sliding_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sliding_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalSlidingWindowDataset", input_dataset=input_dataset, + window_size=window_size, + window_shift=window_shift, + window_stride=window_stride, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalSlidingWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalSlidingWindowDataset = tf_export("raw_ops.ExperimentalSlidingWindowDataset")(_ops.to_raw_op(experimental_sliding_window_dataset)) + + +def experimental_sliding_window_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], window_size: Annotated[Any, _atypes.Int64], window_shift: Annotated[Any, _atypes.Int64], window_stride: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sliding_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sliding_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + window_size = _ops.convert_to_tensor(window_size, _dtypes.int64) + window_shift = _ops.convert_to_tensor(window_shift, _dtypes.int64) + window_stride = _ops.convert_to_tensor(window_stride, _dtypes.int64) + _inputs_flat = [input_dataset, window_size, window_shift, window_stride] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalSlidingWindowDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalSlidingWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_sql_dataset(driver_name: Annotated[Any, _atypes.String], data_source_name: Annotated[Any, _atypes.String], query: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that executes a SQL query and emits rows of the result set. + + Args: + driver_name: A `Tensor` of type `string`. + The database type. Currently, the only supported type is 'sqlite'. + data_source_name: A `Tensor` of type `string`. + A connection string to connect to the database. + query: A `Tensor` of type `string`. A SQL query to execute. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalSqlDataset", name, driver_name, data_source_name, + query, "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_sql_dataset_eager_fallback( + driver_name, data_source_name, query, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sql_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sql_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalSqlDataset", driver_name=driver_name, + data_source_name=data_source_name, + query=query, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalSqlDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalSqlDataset = tf_export("raw_ops.ExperimentalSqlDataset")(_ops.to_raw_op(experimental_sql_dataset)) + + +def experimental_sql_dataset_eager_fallback(driver_name: Annotated[Any, _atypes.String], data_source_name: Annotated[Any, _atypes.String], query: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_sql_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_sql_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + driver_name = _ops.convert_to_tensor(driver_name, _dtypes.string) + data_source_name = _ops.convert_to_tensor(data_source_name, _dtypes.string) + query = _ops.convert_to_tensor(query, _dtypes.string) + _inputs_flat = [driver_name, data_source_name, query] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalSqlDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalSqlDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_stats_aggregator_handle(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a statistics manager resource. + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalStatsAggregatorHandle", name, "container", + container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_stats_aggregator_handle_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalStatsAggregatorHandle", container=container, + shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalStatsAggregatorHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalStatsAggregatorHandle = tf_export("raw_ops.ExperimentalStatsAggregatorHandle")(_ops.to_raw_op(experimental_stats_aggregator_handle)) + + +def experimental_stats_aggregator_handle_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"ExperimentalStatsAggregatorHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalStatsAggregatorHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_stats_aggregator_summary(iterator: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Produces a summary of any statistics recorded by the given statistics manager. + + Args: + iterator: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalStatsAggregatorSummary", name, iterator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_stats_aggregator_summary_eager_fallback( + iterator, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalStatsAggregatorSummary", iterator=iterator, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalStatsAggregatorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalStatsAggregatorSummary = tf_export("raw_ops.ExperimentalStatsAggregatorSummary")(_ops.to_raw_op(experimental_stats_aggregator_summary)) + + +def experimental_stats_aggregator_summary_eager_fallback(iterator: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [iterator] + _attrs = None + _result = _execute.execute(b"ExperimentalStatsAggregatorSummary", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalStatsAggregatorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_take_while_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that stops iteration when predicate` is false. + + The `predicate` function must return a scalar boolean and accept the + following arguments: + + * One tensor for each component of an element of `input_dataset`. + * One tensor for each value in `other_arguments`. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `predicate`. + predicate: A function decorated with @Defun. + A function returning a scalar boolean. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalTakeWhileDataset", name, input_dataset, + other_arguments, "predicate", predicate, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_take_while_dataset_eager_fallback( + input_dataset, other_arguments, predicate=predicate, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_take_while_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_take_while_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalTakeWhileDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + predicate=predicate, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("predicate", _op.get_attr("predicate"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalTakeWhileDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalTakeWhileDataset = tf_export("raw_ops.ExperimentalTakeWhileDataset")(_ops.to_raw_op(experimental_take_while_dataset)) + + +def experimental_take_while_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_take_while_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_take_while_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("predicate", predicate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalTakeWhileDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalTakeWhileDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_thread_pool_dataset(input_dataset: Annotated[Any, _atypes.Variant], thread_pool: Annotated[Any, _atypes.Resource], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + thread_pool: A `Tensor` of type `resource`. + A resource produced by the ThreadPoolHandle op. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalThreadPoolDataset", name, input_dataset, + thread_pool, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_thread_pool_dataset_eager_fallback( + input_dataset, thread_pool, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalThreadPoolDataset", input_dataset=input_dataset, + thread_pool=thread_pool, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalThreadPoolDataset = tf_export("raw_ops.ExperimentalThreadPoolDataset")(_ops.to_raw_op(experimental_thread_pool_dataset)) + + +def experimental_thread_pool_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], thread_pool: Annotated[Any, _atypes.Resource], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + thread_pool = _ops.convert_to_tensor(thread_pool, _dtypes.resource) + _inputs_flat = [input_dataset, thread_pool] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalThreadPoolDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_thread_pool_handle(num_threads: int, display_name: str, max_intra_op_parallelism:int=1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + num_threads: An `int`. The number of threads in the thread pool. + display_name: A `string`. + A human-readable name for the threads that may be visible in some + visualizations. + threadpool. + max_intra_op_parallelism: An optional `int`. Defaults to `1`. + The maximum degree of parallelism to use within operations that execute on this + threadpool. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalThreadPoolHandle", name, "num_threads", + num_threads, "max_intra_op_parallelism", max_intra_op_parallelism, + "display_name", display_name, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_thread_pool_handle_eager_fallback( + num_threads=num_threads, + max_intra_op_parallelism=max_intra_op_parallelism, + display_name=display_name, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_threads = _execute.make_int(num_threads, "num_threads") + display_name = _execute.make_str(display_name, "display_name") + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalThreadPoolHandle", num_threads=num_threads, + display_name=display_name, + max_intra_op_parallelism=max_intra_op_parallelism, + container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_threads", _op._get_attr_int("num_threads"), + "max_intra_op_parallelism", + _op._get_attr_int("max_intra_op_parallelism"), "display_name", + _op.get_attr("display_name"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalThreadPoolHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalThreadPoolHandle = tf_export("raw_ops.ExperimentalThreadPoolHandle")(_ops.to_raw_op(experimental_thread_pool_handle)) + + +def experimental_thread_pool_handle_eager_fallback(num_threads: int, display_name: str, max_intra_op_parallelism: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + num_threads = _execute.make_int(num_threads, "num_threads") + display_name = _execute.make_str(display_name, "display_name") + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("num_threads", num_threads, "max_intra_op_parallelism", + max_intra_op_parallelism, "display_name", display_name, "container", + container, "shared_name", shared_name) + _result = _execute.execute(b"ExperimentalThreadPoolHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalThreadPoolHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_unbatch_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""A dataset that splits the elements of its input into multiple elements. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalUnbatchDataset", name, input_dataset, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_unbatch_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_unbatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_unbatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalUnbatchDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalUnbatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalUnbatchDataset = tf_export("raw_ops.ExperimentalUnbatchDataset")(_ops.to_raw_op(experimental_unbatch_dataset)) + + +def experimental_unbatch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_unbatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_unbatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalUnbatchDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalUnbatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def experimental_unique_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that contains the unique elements of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExperimentalUniqueDataset", name, input_dataset, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return experimental_unique_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_unique_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_unique_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExperimentalUniqueDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExperimentalUniqueDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExperimentalUniqueDataset = tf_export("raw_ops.ExperimentalUniqueDataset")(_ops.to_raw_op(experimental_unique_dataset)) + + +def experimental_unique_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'experimental_unique_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'experimental_unique_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ExperimentalUniqueDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExperimentalUniqueDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def get_element_at_index(dataset: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None): + r"""Gets the element at the specified index in a dataset. + + Args: + dataset: A `Tensor` of type `variant`. + index: A `Tensor` of type `int64`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetElementAtIndex", name, dataset, index, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return get_element_at_index_eager_fallback( + dataset, index, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'get_element_at_index' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'get_element_at_index' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetElementAtIndex", dataset=dataset, index=index, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetElementAtIndex", _inputs_flat, _attrs, _result) + return _result + +GetElementAtIndex = tf_export("raw_ops.GetElementAtIndex")(_ops.to_raw_op(get_element_at_index)) + + +def get_element_at_index_eager_fallback(dataset: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'get_element_at_index' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'get_element_at_index' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + index = _ops.convert_to_tensor(index, _dtypes.int64) + _inputs_flat = [dataset, index] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"GetElementAtIndex", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetElementAtIndex", _inputs_flat, _attrs, _result) + return _result + + +def group_by_reducer_dataset(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, init_func_other_arguments, reduce_func_other_arguments, finalize_func_other_arguments, key_func, init_func, reduce_func, finalize_func, output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that computes a group-by on `input_dataset`. + + Creates a dataset that computes a group-by on `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + key_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `key_func`. + init_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `init_func`. + reduce_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `reduce_func`. + finalize_func_other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `finalize_func`. + key_func: A function decorated with @Defun. + A function mapping an element of `input_dataset`, concatenated + with `key_func_other_arguments` to a scalar value of type DT_INT64. + init_func: A function decorated with @Defun. + A function mapping a key of type DT_INT64, concatenated with + `init_func_other_arguments` to the initial reducer state. + reduce_func: A function decorated with @Defun. + A function mapping the current reducer state and an element of `input_dataset`, + concatenated with `reduce_func_other_arguments` to a new reducer state. + finalize_func: A function decorated with @Defun. + A function mapping the final reducer state to an output element. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GroupByReducerDataset", name, input_dataset, + key_func_other_arguments, init_func_other_arguments, + reduce_func_other_arguments, finalize_func_other_arguments, + "key_func", key_func, "init_func", init_func, "reduce_func", + reduce_func, "finalize_func", finalize_func, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return group_by_reducer_dataset_eager_fallback( + input_dataset, key_func_other_arguments, init_func_other_arguments, + reduce_func_other_arguments, finalize_func_other_arguments, + key_func=key_func, init_func=init_func, reduce_func=reduce_func, + finalize_func=finalize_func, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'group_by_reducer_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'group_by_reducer_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GroupByReducerDataset", input_dataset=input_dataset, + key_func_other_arguments=key_func_other_arguments, + init_func_other_arguments=init_func_other_arguments, + reduce_func_other_arguments=reduce_func_other_arguments, + finalize_func_other_arguments=finalize_func_other_arguments, + key_func=key_func, init_func=init_func, + reduce_func=reduce_func, + finalize_func=finalize_func, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_func", _op.get_attr("key_func"), "init_func", + _op.get_attr("init_func"), "reduce_func", + _op.get_attr("reduce_func"), "finalize_func", + _op.get_attr("finalize_func"), "Tkey_func_other_arguments", + _op.get_attr("Tkey_func_other_arguments"), + "Tinit_func_other_arguments", + _op.get_attr("Tinit_func_other_arguments"), + "Treduce_func_other_arguments", + _op.get_attr("Treduce_func_other_arguments"), + "Tfinalize_func_other_arguments", + _op.get_attr("Tfinalize_func_other_arguments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GroupByReducerDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GroupByReducerDataset = tf_export("raw_ops.GroupByReducerDataset")(_ops.to_raw_op(group_by_reducer_dataset)) + + +def group_by_reducer_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, init_func_other_arguments, reduce_func_other_arguments, finalize_func_other_arguments, key_func, init_func, reduce_func, finalize_func, output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'group_by_reducer_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'group_by_reducer_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tkey_func_other_arguments, key_func_other_arguments = _execute.convert_to_mixed_eager_tensors(key_func_other_arguments, ctx) + _attr_Tinit_func_other_arguments, init_func_other_arguments = _execute.convert_to_mixed_eager_tensors(init_func_other_arguments, ctx) + _attr_Treduce_func_other_arguments, reduce_func_other_arguments = _execute.convert_to_mixed_eager_tensors(reduce_func_other_arguments, ctx) + _attr_Tfinalize_func_other_arguments, finalize_func_other_arguments = _execute.convert_to_mixed_eager_tensors(finalize_func_other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(key_func_other_arguments) + list(init_func_other_arguments) + list(reduce_func_other_arguments) + list(finalize_func_other_arguments) + _attrs = ("key_func", key_func, "init_func", init_func, "reduce_func", + reduce_func, "finalize_func", finalize_func, "Tkey_func_other_arguments", + _attr_Tkey_func_other_arguments, "Tinit_func_other_arguments", + _attr_Tinit_func_other_arguments, "Treduce_func_other_arguments", + _attr_Treduce_func_other_arguments, "Tfinalize_func_other_arguments", + _attr_Tfinalize_func_other_arguments, "output_types", output_types, + "output_shapes", output_shapes) + _result = _execute.execute(b"GroupByReducerDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GroupByReducerDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def group_by_window_dataset(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, reduce_func_other_arguments, window_size_func_other_arguments, key_func, reduce_func, window_size_func, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that computes a windowed group-by on `input_dataset`. + + // TODO(mrry): Support non-int64 keys. + + Args: + input_dataset: A `Tensor` of type `variant`. + key_func_other_arguments: A list of `Tensor` objects. + reduce_func_other_arguments: A list of `Tensor` objects. + window_size_func_other_arguments: A list of `Tensor` objects. + key_func: A function decorated with @Defun. + A function mapping an element of `input_dataset`, concatenated + with `key_func_other_arguments` to a scalar value of type DT_INT64. + reduce_func: A function decorated with @Defun. + window_size_func: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GroupByWindowDataset", name, input_dataset, + key_func_other_arguments, reduce_func_other_arguments, + window_size_func_other_arguments, "key_func", key_func, "reduce_func", + reduce_func, "window_size_func", window_size_func, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return group_by_window_dataset_eager_fallback( + input_dataset, key_func_other_arguments, + reduce_func_other_arguments, window_size_func_other_arguments, + key_func=key_func, reduce_func=reduce_func, + window_size_func=window_size_func, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'group_by_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'group_by_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GroupByWindowDataset", input_dataset=input_dataset, + key_func_other_arguments=key_func_other_arguments, + reduce_func_other_arguments=reduce_func_other_arguments, + window_size_func_other_arguments=window_size_func_other_arguments, + key_func=key_func, reduce_func=reduce_func, + window_size_func=window_size_func, + output_types=output_types, + output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_func", _op.get_attr("key_func"), "reduce_func", + _op.get_attr("reduce_func"), "window_size_func", + _op.get_attr("window_size_func"), "Tkey_func_other_arguments", + _op.get_attr("Tkey_func_other_arguments"), + "Treduce_func_other_arguments", + _op.get_attr("Treduce_func_other_arguments"), + "Twindow_size_func_other_arguments", + _op.get_attr("Twindow_size_func_other_arguments"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GroupByWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GroupByWindowDataset = tf_export("raw_ops.GroupByWindowDataset")(_ops.to_raw_op(group_by_window_dataset)) + + +def group_by_window_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], key_func_other_arguments, reduce_func_other_arguments, window_size_func_other_arguments, key_func, reduce_func, window_size_func, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'group_by_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'group_by_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Tkey_func_other_arguments, key_func_other_arguments = _execute.convert_to_mixed_eager_tensors(key_func_other_arguments, ctx) + _attr_Treduce_func_other_arguments, reduce_func_other_arguments = _execute.convert_to_mixed_eager_tensors(reduce_func_other_arguments, ctx) + _attr_Twindow_size_func_other_arguments, window_size_func_other_arguments = _execute.convert_to_mixed_eager_tensors(window_size_func_other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(key_func_other_arguments) + list(reduce_func_other_arguments) + list(window_size_func_other_arguments) + _attrs = ("key_func", key_func, "reduce_func", reduce_func, + "window_size_func", window_size_func, "Tkey_func_other_arguments", + _attr_Tkey_func_other_arguments, "Treduce_func_other_arguments", + _attr_Treduce_func_other_arguments, "Twindow_size_func_other_arguments", + _attr_Twindow_size_func_other_arguments, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"GroupByWindowDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GroupByWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def ignore_errors_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, log_warning:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that contains the elements of `input_dataset` ignoring errors. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + log_warning: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IgnoreErrorsDataset", name, input_dataset, "output_types", + output_types, "output_shapes", output_shapes, "log_warning", + log_warning) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ignore_errors_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, log_warning=log_warning, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'ignore_errors_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'ignore_errors_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if log_warning is None: + log_warning = False + log_warning = _execute.make_bool(log_warning, "log_warning") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IgnoreErrorsDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, + log_warning=log_warning, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "log_warning", + _op._get_attr_bool("log_warning")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IgnoreErrorsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IgnoreErrorsDataset = tf_export("raw_ops.IgnoreErrorsDataset")(_ops.to_raw_op(ignore_errors_dataset)) + + +def ignore_errors_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, log_warning: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'ignore_errors_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'ignore_errors_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if log_warning is None: + log_warning = False + log_warning = _execute.make_bool(log_warning, "log_warning") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "log_warning", log_warning) + _result = _execute.execute(b"IgnoreErrorsDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IgnoreErrorsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def initialize_table_from_dataset(table_handle: Annotated[Any, _atypes.Resource], dataset: Annotated[Any, _atypes.Variant], name=None): + r"""TODO: add doc. + + Args: + table_handle: A `Tensor` of type `resource`. + dataset: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InitializeTableFromDataset", name, table_handle, dataset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return initialize_table_from_dataset_eager_fallback( + table_handle, dataset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InitializeTableFromDataset", table_handle=table_handle, + dataset=dataset, name=name) + return _op +InitializeTableFromDataset = tf_export("raw_ops.InitializeTableFromDataset")(_ops.to_raw_op(initialize_table_from_dataset)) + + +def initialize_table_from_dataset_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], dataset: Annotated[Any, _atypes.Variant], name, ctx): + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + _inputs_flat = [table_handle, dataset] + _attrs = None + _result = _execute.execute(b"InitializeTableFromDataset", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def iterator_get_device(resource: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Returns the name of the device on which `resource` has been placed. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IteratorGetDevice", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return iterator_get_device_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IteratorGetDevice", resource=resource, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IteratorGetDevice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IteratorGetDevice = tf_export("raw_ops.IteratorGetDevice")(_ops.to_raw_op(iterator_get_device)) + + +def iterator_get_device_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"IteratorGetDevice", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IteratorGetDevice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def lmdb_dataset(filenames: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits the key-value pairs in one or more LMDB files. + + The Lightning Memory-Mapped Database Manager, or LMDB, is an embedded binary + key-value database. This dataset can read the contents of LMDB database files, + the names of which generally have the `.mdb` suffix. + + Each output element consists of a key-value pair represented as a pair of + scalar string `Tensor`s, where the first `Tensor` contains the key and the + second `Tensor` contains the value. + + LMDB uses different file formats on big- and little-endian machines. + `LMDBDataset` can only read files in the format of the host machine. + + Args: + filenames: A `Tensor` of type `string`. + A scalar or a vector containing the name(s) of the binary file(s) to be + read. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LMDBDataset", name, filenames, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lmdb_dataset_eager_fallback( + filenames, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'lmdb_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'lmdb_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LMDBDataset", filenames=filenames, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LMDBDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LMDBDataset = tf_export("raw_ops.LMDBDataset")(_ops.to_raw_op(lmdb_dataset)) + + +def lmdb_dataset_eager_fallback(filenames: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'lmdb_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'lmdb_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + filenames = _ops.convert_to_tensor(filenames, _dtypes.string) + _inputs_flat = [filenames] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"LMDBDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LMDBDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def latency_stats_dataset(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Records the latency of producing `input_dataset` elements in a StatsAggregator. + + Args: + input_dataset: A `Tensor` of type `variant`. + tag: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LatencyStatsDataset", name, input_dataset, tag, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return latency_stats_dataset_eager_fallback( + input_dataset, tag, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'latency_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'latency_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LatencyStatsDataset", input_dataset=input_dataset, tag=tag, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LatencyStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LatencyStatsDataset = tf_export("raw_ops.LatencyStatsDataset")(_ops.to_raw_op(latency_stats_dataset)) + + +def latency_stats_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], tag: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'latency_stats_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'latency_stats_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [input_dataset, tag] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"LatencyStatsDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LatencyStatsDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def legacy_parallel_interleave_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic:str="default", metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, with the exception + that if retrieving the next value from a dataset would cause the requester to + block, it will skip that input dataset. This dataset is especially useful + when loading data from a variable-latency datastores (e.g. HDFS, GCS), as it + allows the training step to proceed so long as some data is available. + + !! WARNING !! This dataset is not deterministic! + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + cycle_length: A `Tensor` of type `int64`. + block_length: A `Tensor` of type `int64`. + buffer_output_elements: A `Tensor` of type `int64`. + prefetch_input_elements: A `Tensor` of type `int64`. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + deterministic: An optional `string`. Defaults to `"default"`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LegacyParallelInterleaveDatasetV2", name, input_dataset, + other_arguments, cycle_length, block_length, buffer_output_elements, + prefetch_input_elements, "f", f, "deterministic", deterministic, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return legacy_parallel_interleave_dataset_v2_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, + buffer_output_elements, prefetch_input_elements, f=f, + deterministic=deterministic, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'legacy_parallel_interleave_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'legacy_parallel_interleave_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LegacyParallelInterleaveDatasetV2", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, + buffer_output_elements=buffer_output_elements, + prefetch_input_elements=prefetch_input_elements, + f=f, output_types=output_types, + output_shapes=output_shapes, + deterministic=deterministic, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "deterministic", + _op.get_attr("deterministic"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LegacyParallelInterleaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LegacyParallelInterleaveDatasetV2 = tf_export("raw_ops.LegacyParallelInterleaveDatasetV2")(_ops.to_raw_op(legacy_parallel_interleave_dataset_v2)) + + +def legacy_parallel_interleave_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, deterministic: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'legacy_parallel_interleave_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'legacy_parallel_interleave_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + buffer_output_elements = _ops.convert_to_tensor(buffer_output_elements, _dtypes.int64) + prefetch_input_elements = _ops.convert_to_tensor(prefetch_input_elements, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, buffer_output_elements, prefetch_input_elements] + _attrs = ("f", f, "deterministic", deterministic, "Targuments", + _attr_Targuments, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + _result = _execute.execute(b"LegacyParallelInterleaveDatasetV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LegacyParallelInterleaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def list_dataset(tensors, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that emits each of `tensors` once. + + Args: + tensors: A list of `Tensor` objects. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ListDataset", name, tensors, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return list_dataset_eager_fallback( + tensors, output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'list_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'list_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ListDataset", tensors=tensors, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput_types", _op.get_attr("Tinput_types"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ListDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ListDataset = tf_export("raw_ops.ListDataset")(_ops.to_raw_op(list_dataset)) + + +def list_dataset_eager_fallback(tensors, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'list_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'list_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Tinput_types, tensors = _execute.convert_to_mixed_eager_tensors(tensors, ctx) + _inputs_flat = list(tensors) + _attrs = ("Tinput_types", _attr_Tinput_types, "output_types", output_types, + "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"ListDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ListDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def load_dataset(path: Annotated[Any, _atypes.String], reader_func_other_args, output_types, output_shapes, reader_func, compression:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + path: A `Tensor` of type `string`. + reader_func_other_args: A list of `Tensor` objects. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reader_func: A function decorated with @Defun. + compression: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadDataset", name, path, reader_func_other_args, + "output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "reader_func", reader_func) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_dataset_eager_fallback( + path, reader_func_other_args, output_types=output_types, + output_shapes=output_shapes, compression=compression, + reader_func=reader_func, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'load_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'load_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadDataset", path=path, + reader_func_other_args=reader_func_other_args, + output_types=output_types, output_shapes=output_shapes, + reader_func=reader_func, compression=compression, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "compression", + _op.get_attr("compression"), "reader_func", + _op.get_attr("reader_func"), "Treader_func_args", + _op.get_attr("Treader_func_args")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LoadDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LoadDataset = tf_export("raw_ops.LoadDataset")(_ops.to_raw_op(load_dataset)) + + +def load_dataset_eager_fallback(path: Annotated[Any, _atypes.String], reader_func_other_args, output_types, output_shapes, reader_func, compression: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'load_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'load_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + _attr_Treader_func_args, reader_func_other_args = _execute.convert_to_mixed_eager_tensors(reader_func_other_args, ctx) + path = _ops.convert_to_tensor(path, _dtypes.string) + _inputs_flat = [path] + list(reader_func_other_args) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "reader_func", reader_func, "Treader_func_args", + _attr_Treader_func_args) + _result = _execute.execute(b"LoadDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LoadDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def map_and_batch_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], f, output_types, output_shapes, preserve_cardinality:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that fuses mapping with batching. + + Creates a dataset that applies `f` to the outputs of `input_dataset` and then + batches `batch_size` of them. + + Unlike a "MapDataset", which applies `f` sequentially, this dataset invokes up + to `batch_size * num_parallel_batches` copies of `f` in parallel. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when building a closure + for `f`. + batch_size: A `Tensor` of type `int64`. + A scalar representing the number of elements to accumulate in a + batch. It determines the number of concurrent invocations of `f` that process + elements from `input_dataset` in parallel. + num_parallel_calls: A `Tensor` of type `int64`. + A scalar representing the maximum number of parallel invocations of the `map_fn` + function. Applying the `map_fn` on consecutive input elements in parallel has + the potential to improve input pipeline throughput. + drop_remainder: A `Tensor` of type `bool`. + A scalar representing whether the last batch should be dropped in case its size + is smaller than desired. + f: A function decorated with @Defun. + A function to apply to the outputs of `input_dataset`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MapAndBatchDataset", name, input_dataset, other_arguments, + batch_size, num_parallel_calls, drop_remainder, "f", f, + "output_types", output_types, "output_shapes", output_shapes, + "preserve_cardinality", preserve_cardinality, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return map_and_batch_dataset_eager_fallback( + input_dataset, other_arguments, batch_size, num_parallel_calls, + drop_remainder, f=f, output_types=output_types, + output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_and_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_and_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MapAndBatchDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + batch_size=batch_size, + num_parallel_calls=num_parallel_calls, + drop_remainder=drop_remainder, f=f, + output_types=output_types, + output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MapAndBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MapAndBatchDataset = tf_export("raw_ops.MapAndBatchDataset")(_ops.to_raw_op(map_and_batch_dataset)) + + +def map_and_batch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, batch_size: Annotated[Any, _atypes.Int64], num_parallel_calls: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], f, output_types, output_shapes, preserve_cardinality: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'map_and_batch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'map_and_batch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_size = _ops.convert_to_tensor(batch_size, _dtypes.int64) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset] + list(other_arguments) + [batch_size, num_parallel_calls, drop_remainder] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "preserve_cardinality", + preserve_cardinality, "metadata", metadata) + _result = _execute.execute(b"MapAndBatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MapAndBatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def matching_files_dataset(patterns: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + patterns: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatchingFilesDataset", name, patterns) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matching_files_dataset_eager_fallback( + patterns, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatchingFilesDataset", patterns=patterns, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatchingFilesDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatchingFilesDataset = tf_export("raw_ops.MatchingFilesDataset")(_ops.to_raw_op(matching_files_dataset)) + + +def matching_files_dataset_eager_fallback(patterns: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Variant]: + patterns = _ops.convert_to_tensor(patterns, _dtypes.string) + _inputs_flat = [patterns] + _attrs = None + _result = _execute.execute(b"MatchingFilesDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatchingFilesDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def max_intra_op_parallelism_dataset(input_dataset: Annotated[Any, _atypes.Variant], max_intra_op_parallelism: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that overrides the maximum intra-op parallelism. + + Args: + input_dataset: A `Tensor` of type `variant`. + max_intra_op_parallelism: A `Tensor` of type `int64`. + Identifies the maximum intra-op parallelism to use. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxIntraOpParallelismDataset", name, input_dataset, + max_intra_op_parallelism, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_intra_op_parallelism_dataset_eager_fallback( + input_dataset, max_intra_op_parallelism, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'max_intra_op_parallelism_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'max_intra_op_parallelism_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxIntraOpParallelismDataset", input_dataset=input_dataset, + max_intra_op_parallelism=max_intra_op_parallelism, + output_types=output_types, + output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxIntraOpParallelismDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxIntraOpParallelismDataset = tf_export("raw_ops.MaxIntraOpParallelismDataset")(_ops.to_raw_op(max_intra_op_parallelism_dataset)) + + +def max_intra_op_parallelism_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], max_intra_op_parallelism: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'max_intra_op_parallelism_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'max_intra_op_parallelism_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + max_intra_op_parallelism = _ops.convert_to_tensor(max_intra_op_parallelism, _dtypes.int64) + _inputs_flat = [input_dataset, max_intra_op_parallelism] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"MaxIntraOpParallelismDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxIntraOpParallelismDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def non_serializable_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonSerializableDataset", name, input_dataset, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_serializable_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'non_serializable_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'non_serializable_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonSerializableDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonSerializableDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonSerializableDataset = tf_export("raw_ops.NonSerializableDataset")(_ops.to_raw_op(non_serializable_dataset)) + + +def non_serializable_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'non_serializable_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'non_serializable_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"NonSerializableDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonSerializableDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parallel_interleave_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], sloppy: Annotated[Any, _atypes.Bool], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that applies `f` to the outputs of `input_dataset`. + + The resulting dataset is similar to the `InterleaveDataset`, with the exception + that if retrieving the next value from a dataset would cause the requester to + block, it will skip that input dataset. This dataset is especially useful + when loading data from a variable-latency datastores (e.g. HDFS, GCS), as it + allows the training step to proceed so long as some data is available. + + !! WARNING !! If the `sloppy` parameter is set to `True`, the operation of this + dataset will not be deterministic! + + This dataset has been superseded by `ParallelInterleaveDatasetV2`. New code + should use `ParallelInterleaveDatasetV2`. + + The Python API `tf.data.experimental.parallel_interleave` creates instances of + this op. `tf.data.experimental.parallel_interleave` is a deprecated API. + + Args: + input_dataset: A `Tensor` of type `variant`. + Dataset that produces a stream of arguments for the function `f`. + other_arguments: A list of `Tensor` objects. + Additional arguments to pass to `f` beyond those produced by `input_dataset`. + Evaluated once when the dataset is instantiated. + cycle_length: A `Tensor` of type `int64`. + Number of datasets (each created by applying `f` to the elements of + `input_dataset`) among which the `ParallelInterleaveDataset` will cycle in a + round-robin fashion. + block_length: A `Tensor` of type `int64`. + Number of elements at a time to produce from each interleaved invocation of a + dataset returned by `f`. + sloppy: A `Tensor` of type `bool`. + If `True`, return elements as they become available, even if that means returning + these elements in a non-deterministic order. Sloppy operation may result in better + performance in the presence of stragglers, but the dataset will still block if + all of its open streams are blocked. + If `False`, always return elements in a deterministic order. + buffer_output_elements: A `Tensor` of type `int64`. + The number of elements each iterator being interleaved should buffer (similar + to the `.prefetch()` transformation for each interleaved iterator). + prefetch_input_elements: A `Tensor` of type `int64`. + Determines the number of iterators to prefetch, allowing buffers to warm up and + data to be pre-fetched without blocking the main thread. + f: A function decorated with @Defun. + A function mapping elements of `input_dataset`, concatenated with + `other_arguments`, to a Dataset variant that contains elements matching + `output_types` and `output_shapes`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParallelInterleaveDataset", name, input_dataset, + other_arguments, cycle_length, block_length, sloppy, + buffer_output_elements, prefetch_input_elements, "f", f, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parallel_interleave_dataset_eager_fallback( + input_dataset, other_arguments, cycle_length, block_length, sloppy, + buffer_output_elements, prefetch_input_elements, f=f, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParallelInterleaveDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + cycle_length=cycle_length, + block_length=block_length, sloppy=sloppy, + buffer_output_elements=buffer_output_elements, + prefetch_input_elements=prefetch_input_elements, + f=f, output_types=output_types, + output_shapes=output_shapes, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParallelInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParallelInterleaveDataset = tf_export("raw_ops.ParallelInterleaveDataset")(_ops.to_raw_op(parallel_interleave_dataset)) + + +def parallel_interleave_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, cycle_length: Annotated[Any, _atypes.Int64], block_length: Annotated[Any, _atypes.Int64], sloppy: Annotated[Any, _atypes.Bool], buffer_output_elements: Annotated[Any, _atypes.Int64], prefetch_input_elements: Annotated[Any, _atypes.Int64], f, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parallel_interleave_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parallel_interleave_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + cycle_length = _ops.convert_to_tensor(cycle_length, _dtypes.int64) + block_length = _ops.convert_to_tensor(block_length, _dtypes.int64) + sloppy = _ops.convert_to_tensor(sloppy, _dtypes.bool) + buffer_output_elements = _ops.convert_to_tensor(buffer_output_elements, _dtypes.int64) + prefetch_input_elements = _ops.convert_to_tensor(prefetch_input_elements, _dtypes.int64) + _inputs_flat = [input_dataset] + list(other_arguments) + [cycle_length, block_length, sloppy, buffer_output_elements, prefetch_input_elements] + _attrs = ("f", f, "Targuments", _attr_Targuments, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + _result = _execute.execute(b"ParallelInterleaveDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParallelInterleaveDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parse_example_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, sloppy:bool=False, ragged_keys=[], ragged_value_types=[], ragged_split_types=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_parallel_calls: A `Tensor` of type `int64`. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A dict mapping string keys to `Tensor`s. + The keys of the dict must match the dense_keys of the feature. + sparse_keys: A list of `strings`. + A list of string keys in the examples features. + The results for these keys will be returned as `SparseTensor` objects. + dense_keys: A list of `strings`. + A list of Ndense string Tensors (scalars). + The keys expected in the Examples features associated with dense values. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `DTypes` of the same length as `sparse_keys`. + Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), + and `tf.string` (`BytesList`) are supported. + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + List of tuples with the same length as `dense_keys`. + The shape of the data for each dense feature referenced by `dense_keys`. + Required for any input tensors identified by `dense_keys`. Must be + either fully defined, or may contain an unknown first dimension. + An unknown first dimension means the feature is treated as having + a variable number of blocks, and the output shape along this dimension + is considered unknown at graph build time. Padding is applied for + minibatch elements smaller than the maximum number of blocks for the + given feature along this dimension. + output_types: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + The list of shapes being produced. + sloppy: An optional `bool`. Defaults to `False`. + ragged_keys: An optional list of `strings`. Defaults to `[]`. + ragged_value_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + ragged_split_types: An optional list of `tf.DTypes` from: `tf.int32, tf.int64`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseExampleDataset", name, input_dataset, num_parallel_calls, + dense_defaults, "sparse_keys", sparse_keys, "dense_keys", dense_keys, + "sparse_types", sparse_types, "dense_shapes", dense_shapes, + "output_types", output_types, "output_shapes", output_shapes, + "sloppy", sloppy, "ragged_keys", ragged_keys, "ragged_value_types", + ragged_value_types, "ragged_split_types", ragged_split_types) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_example_dataset_eager_fallback( + input_dataset, num_parallel_calls, dense_defaults, + sparse_keys=sparse_keys, dense_keys=dense_keys, + sparse_types=sparse_types, dense_shapes=dense_shapes, + output_types=output_types, output_shapes=output_shapes, + sloppy=sloppy, ragged_keys=ragged_keys, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example_dataset' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example_dataset' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_dataset' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_dataset' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parse_example_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parse_example_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if ragged_keys is None: + ragged_keys = [] + if not isinstance(ragged_keys, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_keys' argument to " + "'parse_example_dataset' Op, not %r." % ragged_keys) + ragged_keys = [_execute.make_str(_s, "ragged_keys") for _s in ragged_keys] + if ragged_value_types is None: + ragged_value_types = [] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_dataset' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if ragged_split_types is None: + ragged_split_types = [] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_dataset' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseExampleDataset", input_dataset=input_dataset, + num_parallel_calls=num_parallel_calls, + dense_defaults=dense_defaults, + sparse_keys=sparse_keys, dense_keys=dense_keys, + sparse_types=sparse_types, + dense_shapes=dense_shapes, + output_types=output_types, + output_shapes=output_shapes, sloppy=sloppy, + ragged_keys=ragged_keys, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sparse_keys", _op.get_attr("sparse_keys"), "dense_keys", + _op.get_attr("dense_keys"), "sparse_types", + _op.get_attr("sparse_types"), "Tdense", _op.get_attr("Tdense"), + "dense_shapes", _op.get_attr("dense_shapes"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "sloppy", + _op._get_attr_bool("sloppy"), "ragged_keys", + _op.get_attr("ragged_keys"), "ragged_value_types", + _op.get_attr("ragged_value_types"), "ragged_split_types", + _op.get_attr("ragged_split_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseExampleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParseExampleDataset = tf_export("raw_ops.ParseExampleDataset")(_ops.to_raw_op(parse_example_dataset)) + + +def parse_example_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, sloppy: bool, ragged_keys, ragged_value_types, ragged_split_types, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example_dataset' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example_dataset' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_dataset' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_dataset' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parse_example_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parse_example_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if sloppy is None: + sloppy = False + sloppy = _execute.make_bool(sloppy, "sloppy") + if ragged_keys is None: + ragged_keys = [] + if not isinstance(ragged_keys, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_keys' argument to " + "'parse_example_dataset' Op, not %r." % ragged_keys) + ragged_keys = [_execute.make_str(_s, "ragged_keys") for _s in ragged_keys] + if ragged_value_types is None: + ragged_value_types = [] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_dataset' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if ragged_split_types is None: + ragged_split_types = [] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_dataset' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset, num_parallel_calls] + list(dense_defaults) + _attrs = ("sparse_keys", sparse_keys, "dense_keys", dense_keys, + "sparse_types", sparse_types, "Tdense", _attr_Tdense, "dense_shapes", + dense_shapes, "output_types", output_types, "output_shapes", output_shapes, + "sloppy", sloppy, "ragged_keys", ragged_keys, "ragged_value_types", + ragged_value_types, "ragged_split_types", ragged_split_types) + _result = _execute.execute(b"ParseExampleDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseExampleDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def parse_example_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, deterministic:str="default", ragged_keys=[], ragged_value_types=[], ragged_split_types=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Transforms `input_dataset` containing `Example` protos as vectors of DT_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_parallel_calls: A `Tensor` of type `int64`. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A dict mapping string keys to `Tensor`s. + The keys of the dict must match the dense_keys of the feature. + sparse_keys: A list of `strings`. + A list of string keys in the examples features. + The results for these keys will be returned as `SparseTensor` objects. + dense_keys: A list of `strings`. + A list of Ndense string Tensors (scalars). + The keys expected in the Examples features associated with dense values. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `DTypes` of the same length as `sparse_keys`. + Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), + and `tf.string` (`BytesList`) are supported. + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + List of tuples with the same length as `dense_keys`. + The shape of the data for each dense feature referenced by `dense_keys`. + Required for any input tensors identified by `dense_keys`. Must be + either fully defined, or may contain an unknown first dimension. + An unknown first dimension means the feature is treated as having + a variable number of blocks, and the output shape along this dimension + is considered unknown at graph build time. Padding is applied for + minibatch elements smaller than the maximum number of blocks for the + given feature along this dimension. + output_types: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + The list of shapes being produced. + deterministic: An optional `string`. Defaults to `"default"`. + A string indicating the op-level determinism to use. Deterministic controls + whether the dataset is allowed to return elements out of order if the next + element to be returned isn't available, but a later element is. Options are + "true", "false", and "default". "default" indicates that determinism should be + decided by the `experimental_deterministic` parameter of `tf.data.Options`. + ragged_keys: An optional list of `strings`. Defaults to `[]`. + ragged_value_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + ragged_split_types: An optional list of `tf.DTypes` from: `tf.int32, tf.int64`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseExampleDatasetV2", name, input_dataset, + num_parallel_calls, dense_defaults, "sparse_keys", sparse_keys, + "dense_keys", dense_keys, "sparse_types", sparse_types, + "dense_shapes", dense_shapes, "output_types", output_types, + "output_shapes", output_shapes, "deterministic", deterministic, + "ragged_keys", ragged_keys, "ragged_value_types", ragged_value_types, + "ragged_split_types", ragged_split_types) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_example_dataset_v2_eager_fallback( + input_dataset, num_parallel_calls, dense_defaults, + sparse_keys=sparse_keys, dense_keys=dense_keys, + sparse_types=sparse_types, dense_shapes=dense_shapes, + output_types=output_types, output_shapes=output_shapes, + deterministic=deterministic, ragged_keys=ragged_keys, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_dataset_v2' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parse_example_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if ragged_keys is None: + ragged_keys = [] + if not isinstance(ragged_keys, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_keys) + ragged_keys = [_execute.make_str(_s, "ragged_keys") for _s in ragged_keys] + if ragged_value_types is None: + ragged_value_types = [] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if ragged_split_types is None: + ragged_split_types = [] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseExampleDatasetV2", input_dataset=input_dataset, + num_parallel_calls=num_parallel_calls, + dense_defaults=dense_defaults, + sparse_keys=sparse_keys, + dense_keys=dense_keys, + sparse_types=sparse_types, + dense_shapes=dense_shapes, + output_types=output_types, + output_shapes=output_shapes, + deterministic=deterministic, + ragged_keys=ragged_keys, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sparse_keys", _op.get_attr("sparse_keys"), "dense_keys", + _op.get_attr("dense_keys"), "sparse_types", + _op.get_attr("sparse_types"), "Tdense", _op.get_attr("Tdense"), + "dense_shapes", _op.get_attr("dense_shapes"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "deterministic", + _op.get_attr("deterministic"), "ragged_keys", + _op.get_attr("ragged_keys"), "ragged_value_types", + _op.get_attr("ragged_value_types"), "ragged_split_types", + _op.get_attr("ragged_split_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseExampleDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParseExampleDatasetV2 = tf_export("raw_ops.ParseExampleDatasetV2")(_ops.to_raw_op(parse_example_dataset_v2)) + + +def parse_example_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_parallel_calls: Annotated[Any, _atypes.Int64], dense_defaults, sparse_keys, dense_keys, sparse_types, dense_shapes, output_types, output_shapes, deterministic: str, ragged_keys, ragged_value_types, ragged_split_types, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_dataset_v2' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'parse_example_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if deterministic is None: + deterministic = "default" + deterministic = _execute.make_str(deterministic, "deterministic") + if ragged_keys is None: + ragged_keys = [] + if not isinstance(ragged_keys, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_keys' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_keys) + ragged_keys = [_execute.make_str(_s, "ragged_keys") for _s in ragged_keys] + if ragged_value_types is None: + ragged_value_types = [] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if ragged_split_types is None: + ragged_split_types = [] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_dataset_v2' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_parallel_calls = _ops.convert_to_tensor(num_parallel_calls, _dtypes.int64) + _inputs_flat = [input_dataset, num_parallel_calls] + list(dense_defaults) + _attrs = ("sparse_keys", sparse_keys, "dense_keys", dense_keys, + "sparse_types", sparse_types, "Tdense", _attr_Tdense, "dense_shapes", + dense_shapes, "output_types", output_types, "output_shapes", output_shapes, + "deterministic", deterministic, "ragged_keys", ragged_keys, + "ragged_value_types", ragged_value_types, "ragged_split_types", + ragged_split_types) + _result = _execute.execute(b"ParseExampleDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseExampleDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def private_thread_pool_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_threads: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + num_threads: A `Tensor` of type `int64`. + Identifies the number of threads to use for the private threadpool. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PrivateThreadPoolDataset", name, input_dataset, num_threads, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return private_thread_pool_dataset_eager_fallback( + input_dataset, num_threads, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'private_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'private_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PrivateThreadPoolDataset", input_dataset=input_dataset, + num_threads=num_threads, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PrivateThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PrivateThreadPoolDataset = tf_export("raw_ops.PrivateThreadPoolDataset")(_ops.to_raw_op(private_thread_pool_dataset)) + + +def private_thread_pool_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_threads: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'private_thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'private_thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_threads = _ops.convert_to_tensor(num_threads, _dtypes.int64) + _inputs_flat = [input_dataset, num_threads] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"PrivateThreadPoolDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PrivateThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def random_dataset(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a Dataset that returns pseudorandom numbers. + + Creates a Dataset that returns a stream of uniformly distributed + pseudorandom 64-bit signed integers. + + In the TensorFlow Python API, you can instantiate this dataset via the + class `tf.data.experimental.RandomDataset`. + + Instances of this dataset are also created as a result of the + `hoist_random_uniform` static optimization. Whether this optimization is + performed is determined by the `experimental_optimization.hoist_random_uniform` + option of `tf.data.Options`. + + Args: + seed: A `Tensor` of type `int64`. + A scalar seed for the random number generator. If either seed or + seed2 is set to be non-zero, the random number generator is seeded + by the given seed. Otherwise, a random seed is used. + seed2: A `Tensor` of type `int64`. + A second scalar seed to avoid seed collision. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomDataset", name, seed, seed2, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_dataset_eager_fallback( + seed, seed2, output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'random_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'random_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomDataset", seed=seed, seed2=seed2, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomDataset = tf_export("raw_ops.RandomDataset")(_ops.to_raw_op(random_dataset)) + + +def random_dataset_eager_fallback(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'random_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'random_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + _inputs_flat = [seed, seed2] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"RandomDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def random_dataset_v2(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, rerandomize_each_iteration:bool=False, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a Dataset that returns pseudorandom numbers. + + Creates a Dataset that returns a stream of uniformly distributed + pseudorandom 64-bit signed integers. It accepts a boolean attribute that + determines if the random number generators are re-applied at each epoch. The + default value is True which means that the seeds are applied and the same + sequence of random numbers are generated at each epoch. If set to False, the + seeds are not re-applied and a different sequence of random numbers are + generated at each epoch. + + In the TensorFlow Python API, you can instantiate this dataset via the + class `tf.data.experimental.RandomDatasetV2`. + + Args: + seed: A `Tensor` of type `int64`. + A scalar seed for the random number generator. If either seed or + seed2 is set to be non-zero, the random number generator is seeded + by the given seed. Otherwise, a random seed is used. + seed2: A `Tensor` of type `int64`. + A second scalar seed to avoid seed collision. + seed_generator: A `Tensor` of type `resource`. + A resource for the random number seed generator. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + rerandomize_each_iteration: An optional `bool`. Defaults to `False`. + A boolean attribute to rerandomize the sequence of random numbers generated + at each epoch. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomDatasetV2", name, seed, seed2, seed_generator, + "rerandomize_each_iteration", rerandomize_each_iteration, + "output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_dataset_v2_eager_fallback( + seed, seed2, seed_generator, + rerandomize_each_iteration=rerandomize_each_iteration, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'random_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'random_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if rerandomize_each_iteration is None: + rerandomize_each_iteration = False + rerandomize_each_iteration = _execute.make_bool(rerandomize_each_iteration, "rerandomize_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomDatasetV2", seed=seed, seed2=seed2, + seed_generator=seed_generator, + output_types=output_types, + output_shapes=output_shapes, + rerandomize_each_iteration=rerandomize_each_iteration, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("rerandomize_each_iteration", + _op._get_attr_bool("rerandomize_each_iteration"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomDatasetV2 = tf_export("raw_ops.RandomDatasetV2")(_ops.to_raw_op(random_dataset_v2)) + + +def random_dataset_v2_eager_fallback(seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], seed_generator: Annotated[Any, _atypes.Resource], output_types, output_shapes, rerandomize_each_iteration: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'random_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'random_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if rerandomize_each_iteration is None: + rerandomize_each_iteration = False + rerandomize_each_iteration = _execute.make_bool(rerandomize_each_iteration, "rerandomize_each_iteration") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + seed_generator = _ops.convert_to_tensor(seed_generator, _dtypes.resource) + _inputs_flat = [seed, seed2, seed_generator] + _attrs = ("rerandomize_each_iteration", rerandomize_each_iteration, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"RandomDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def rebatch_dataset(input_dataset: Annotated[Any, _atypes.Variant], num_replicas: Annotated[Any, _atypes.Int64], output_types, output_shapes, use_fallback:bool=True, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that changes the batch size. + + Creates a dataset that changes the batch size of the dataset to current batch + size // num_workers. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + num_replicas: A `Tensor` of type `int64`. + A scalar representing the number of replicas to distribute this batch across. As + a result of this transformation the current batch size would end up being + divided by this parameter. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + use_fallback: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RebatchDataset", name, input_dataset, num_replicas, + "output_types", output_types, "output_shapes", output_shapes, + "use_fallback", use_fallback) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rebatch_dataset_eager_fallback( + input_dataset, num_replicas, output_types=output_types, + output_shapes=output_shapes, use_fallback=use_fallback, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rebatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rebatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_fallback is None: + use_fallback = True + use_fallback = _execute.make_bool(use_fallback, "use_fallback") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RebatchDataset", input_dataset=input_dataset, + num_replicas=num_replicas, + output_types=output_types, + output_shapes=output_shapes, + use_fallback=use_fallback, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "use_fallback", + _op._get_attr_bool("use_fallback")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RebatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RebatchDataset = tf_export("raw_ops.RebatchDataset")(_ops.to_raw_op(rebatch_dataset)) + + +def rebatch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], num_replicas: Annotated[Any, _atypes.Int64], output_types, output_shapes, use_fallback: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rebatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rebatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if use_fallback is None: + use_fallback = True + use_fallback = _execute.make_bool(use_fallback, "use_fallback") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + num_replicas = _ops.convert_to_tensor(num_replicas, _dtypes.int64) + _inputs_flat = [input_dataset, num_replicas] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "use_fallback", use_fallback) + _result = _execute.execute(b"RebatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RebatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def rebatch_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], batch_sizes: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that changes the batch size. + + Creates a dataset that rebatches elements from `input_dataset` into new batch + sizes. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + batch_sizes: A `Tensor` of type `int64`. + A vector of integers representing the size of batches to produce. These values + are cycled through in order. + drop_remainder: A `Tensor` of type `bool`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RebatchDatasetV2", name, input_dataset, batch_sizes, + drop_remainder, "output_types", output_types, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rebatch_dataset_v2_eager_fallback( + input_dataset, batch_sizes, drop_remainder, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rebatch_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rebatch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RebatchDatasetV2", input_dataset=input_dataset, + batch_sizes=batch_sizes, + drop_remainder=drop_remainder, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RebatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RebatchDatasetV2 = tf_export("raw_ops.RebatchDatasetV2")(_ops.to_raw_op(rebatch_dataset_v2)) + + +def rebatch_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], batch_sizes: Annotated[Any, _atypes.Int64], drop_remainder: Annotated[Any, _atypes.Bool], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'rebatch_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'rebatch_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + batch_sizes = _ops.convert_to_tensor(batch_sizes, _dtypes.int64) + drop_remainder = _ops.convert_to_tensor(drop_remainder, _dtypes.bool) + _inputs_flat = [input_dataset, batch_sizes, drop_remainder] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"RebatchDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RebatchDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def register_dataset(dataset: Annotated[Any, _atypes.Variant], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], external_state_policy: int, element_spec:str="", metadata:str="", name=None) -> Annotated[Any, _atypes.Int64]: + r"""Registers a dataset with the tf.data service. + + Args: + dataset: A `Tensor` of type `variant`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + external_state_policy: An `int`. + element_spec: An optional `string`. Defaults to `""`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RegisterDataset", name, dataset, address, protocol, + "external_state_policy", external_state_policy, "element_spec", + element_spec, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return register_dataset_eager_fallback( + dataset, address, protocol, + external_state_policy=external_state_policy, + element_spec=element_spec, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if element_spec is None: + element_spec = "" + element_spec = _execute.make_str(element_spec, "element_spec") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RegisterDataset", dataset=dataset, address=address, + protocol=protocol, + external_state_policy=external_state_policy, + element_spec=element_spec, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("external_state_policy", + _op._get_attr_int("external_state_policy"), "element_spec", + _op.get_attr("element_spec"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RegisterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RegisterDataset = tf_export("raw_ops.RegisterDataset")(_ops.to_raw_op(register_dataset)) + + +def register_dataset_eager_fallback(dataset: Annotated[Any, _atypes.Variant], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], external_state_policy: int, element_spec: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.Int64]: + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if element_spec is None: + element_spec = "" + element_spec = _execute.make_str(element_spec, "element_spec") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + _inputs_flat = [dataset, address, protocol] + _attrs = ("external_state_policy", external_state_policy, "element_spec", + element_spec, "metadata", metadata) + _result = _execute.execute(b"RegisterDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RegisterDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def register_dataset_v2(dataset: Annotated[Any, _atypes.Variant], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], external_state_policy: int, element_spec:str="", requested_dataset_id:str="", metadata:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Registers a dataset with the tf.data service. + + Args: + dataset: A `Tensor` of type `variant`. + address: A `Tensor` of type `string`. + protocol: A `Tensor` of type `string`. + external_state_policy: An `int`. + element_spec: An optional `string`. Defaults to `""`. + requested_dataset_id: An optional `string`. Defaults to `""`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RegisterDatasetV2", name, dataset, address, protocol, + "external_state_policy", external_state_policy, "element_spec", + element_spec, "requested_dataset_id", requested_dataset_id, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return register_dataset_v2_eager_fallback( + dataset, address, protocol, + external_state_policy=external_state_policy, + element_spec=element_spec, + requested_dataset_id=requested_dataset_id, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if element_spec is None: + element_spec = "" + element_spec = _execute.make_str(element_spec, "element_spec") + if requested_dataset_id is None: + requested_dataset_id = "" + requested_dataset_id = _execute.make_str(requested_dataset_id, "requested_dataset_id") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RegisterDatasetV2", dataset=dataset, address=address, + protocol=protocol, + external_state_policy=external_state_policy, + element_spec=element_spec, + requested_dataset_id=requested_dataset_id, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("external_state_policy", + _op._get_attr_int("external_state_policy"), "element_spec", + _op.get_attr("element_spec"), "requested_dataset_id", + _op.get_attr("requested_dataset_id"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RegisterDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RegisterDatasetV2 = tf_export("raw_ops.RegisterDatasetV2")(_ops.to_raw_op(register_dataset_v2)) + + +def register_dataset_v2_eager_fallback(dataset: Annotated[Any, _atypes.Variant], address: Annotated[Any, _atypes.String], protocol: Annotated[Any, _atypes.String], external_state_policy: int, element_spec: str, requested_dataset_id: str, metadata: str, name, ctx) -> Annotated[Any, _atypes.String]: + external_state_policy = _execute.make_int(external_state_policy, "external_state_policy") + if element_spec is None: + element_spec = "" + element_spec = _execute.make_str(element_spec, "element_spec") + if requested_dataset_id is None: + requested_dataset_id = "" + requested_dataset_id = _execute.make_str(requested_dataset_id, "requested_dataset_id") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + dataset = _ops.convert_to_tensor(dataset, _dtypes.variant) + address = _ops.convert_to_tensor(address, _dtypes.string) + protocol = _ops.convert_to_tensor(protocol, _dtypes.string) + _inputs_flat = [dataset, address, protocol] + _attrs = ("external_state_policy", external_state_policy, "element_spec", + element_spec, "requested_dataset_id", requested_dataset_id, "metadata", + metadata) + _result = _execute.execute(b"RegisterDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RegisterDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sampling_dataset(input_dataset: Annotated[Any, _atypes.Variant], rate: Annotated[Any, _atypes.Float32], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that takes a Bernoulli sample of the contents of another dataset. + + There is no transformation in the `tf.data` Python API for creating this dataset. + Instead, it is created as a result of the `filter_with_random_uniform_fusion` + static optimization. Whether this optimization is performed is determined by the + `experimental_optimization.filter_with_random_uniform_fusion` option of + `tf.data.Options`. + + Args: + input_dataset: A `Tensor` of type `variant`. + rate: A `Tensor` of type `float32`. + A scalar representing the sample rate. Each element of `input_dataset` is + retained with this probability, independent of all other elements. + seed: A `Tensor` of type `int64`. + A scalar representing seed of random number generator. + seed2: A `Tensor` of type `int64`. + A scalar representing seed2 of random number generator. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SamplingDataset", name, input_dataset, rate, seed, seed2, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sampling_dataset_eager_fallback( + input_dataset, rate, seed, seed2, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sampling_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sampling_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SamplingDataset", input_dataset=input_dataset, rate=rate, seed=seed, + seed2=seed2, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SamplingDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SamplingDataset = tf_export("raw_ops.SamplingDataset")(_ops.to_raw_op(sampling_dataset)) + + +def sampling_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], rate: Annotated[Any, _atypes.Float32], seed: Annotated[Any, _atypes.Int64], seed2: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sampling_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sampling_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + rate = _ops.convert_to_tensor(rate, _dtypes.float32) + seed = _ops.convert_to_tensor(seed, _dtypes.int64) + seed2 = _ops.convert_to_tensor(seed2, _dtypes.int64) + _inputs_flat = [input_dataset, rate, seed, seed2] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"SamplingDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SamplingDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def save_dataset(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], shard_func_other_args, shard_func, compression:str="", use_shard_func:bool=True, name=None): + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + path: A `Tensor` of type `string`. + shard_func_other_args: A list of `Tensor` objects. + shard_func: A function decorated with @Defun. + compression: An optional `string`. Defaults to `""`. + use_shard_func: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SaveDataset", name, input_dataset, path, shard_func_other_args, + "compression", compression, "shard_func", shard_func, + "use_shard_func", use_shard_func) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return save_dataset_eager_fallback( + input_dataset, path, shard_func_other_args, compression=compression, + shard_func=shard_func, use_shard_func=use_shard_func, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if use_shard_func is None: + use_shard_func = True + use_shard_func = _execute.make_bool(use_shard_func, "use_shard_func") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SaveDataset", input_dataset=input_dataset, path=path, + shard_func_other_args=shard_func_other_args, + shard_func=shard_func, compression=compression, + use_shard_func=use_shard_func, name=name) + return _op +SaveDataset = tf_export("raw_ops.SaveDataset")(_ops.to_raw_op(save_dataset)) + + +def save_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], shard_func_other_args, shard_func, compression: str, use_shard_func: bool, name, ctx): + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if use_shard_func is None: + use_shard_func = True + use_shard_func = _execute.make_bool(use_shard_func, "use_shard_func") + _attr_Tshard_func_args, shard_func_other_args = _execute.convert_to_mixed_eager_tensors(shard_func_other_args, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + path = _ops.convert_to_tensor(path, _dtypes.string) + _inputs_flat = [input_dataset, path] + list(shard_func_other_args) + _attrs = ("compression", compression, "shard_func", shard_func, + "use_shard_func", use_shard_func, "Tshard_func_args", + _attr_Tshard_func_args) + _result = _execute.execute(b"SaveDataset", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def save_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], shard_func_other_args, shard_func, output_types, output_shapes, compression:str="", use_shard_func:bool=True, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + path: A `Tensor` of type `string`. + shard_func_other_args: A list of `Tensor` objects. + shard_func: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + compression: An optional `string`. Defaults to `""`. + use_shard_func: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SaveDatasetV2", name, input_dataset, path, + shard_func_other_args, "compression", compression, "shard_func", + shard_func, "use_shard_func", use_shard_func, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return save_dataset_v2_eager_fallback( + input_dataset, path, shard_func_other_args, compression=compression, + shard_func=shard_func, use_shard_func=use_shard_func, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'save_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'save_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if use_shard_func is None: + use_shard_func = True + use_shard_func = _execute.make_bool(use_shard_func, "use_shard_func") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SaveDatasetV2", input_dataset=input_dataset, path=path, + shard_func_other_args=shard_func_other_args, + shard_func=shard_func, output_types=output_types, + output_shapes=output_shapes, compression=compression, + use_shard_func=use_shard_func, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compression", _op.get_attr("compression"), "shard_func", + _op.get_attr("shard_func"), "use_shard_func", + _op._get_attr_bool("use_shard_func"), "Tshard_func_args", + _op.get_attr("Tshard_func_args"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SaveDatasetV2 = tf_export("raw_ops.SaveDatasetV2")(_ops.to_raw_op(save_dataset_v2)) + + +def save_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], shard_func_other_args, shard_func, output_types, output_shapes, compression: str, use_shard_func: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'save_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'save_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if use_shard_func is None: + use_shard_func = True + use_shard_func = _execute.make_bool(use_shard_func, "use_shard_func") + _attr_Tshard_func_args, shard_func_other_args = _execute.convert_to_mixed_eager_tensors(shard_func_other_args, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + path = _ops.convert_to_tensor(path, _dtypes.string) + _inputs_flat = [input_dataset, path] + list(shard_func_other_args) + _attrs = ("compression", compression, "shard_func", shard_func, + "use_shard_func", use_shard_func, "Tshard_func_args", + _attr_Tshard_func_args, "output_types", output_types, "output_shapes", + output_shapes) + _result = _execute.execute(b"SaveDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SaveDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def scan_dataset(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, preserve_cardinality:bool=False, use_default_device:bool=True, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset successively reduces `f` over the elements of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + initial_state: A list of `Tensor` objects. + other_arguments: A list of `Tensor` objects. + f: A function decorated with @Defun. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + preserve_cardinality: An optional `bool`. Defaults to `False`. + use_default_device: An optional `bool`. Defaults to `True`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScanDataset", name, input_dataset, initial_state, + other_arguments, "f", f, "output_types", output_types, + "output_shapes", output_shapes, "preserve_cardinality", + preserve_cardinality, "use_default_device", use_default_device, + "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return scan_dataset_eager_fallback( + input_dataset, initial_state, other_arguments, f=f, + output_types=output_types, output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, + use_default_device=use_default_device, metadata=metadata, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'scan_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'scan_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if use_default_device is None: + use_default_device = True + use_default_device = _execute.make_bool(use_default_device, "use_default_device") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScanDataset", input_dataset=input_dataset, + initial_state=initial_state, + other_arguments=other_arguments, f=f, + output_types=output_types, output_shapes=output_shapes, + preserve_cardinality=preserve_cardinality, + use_default_device=use_default_device, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("f", _op.get_attr("f"), "Tstate", _op.get_attr("Tstate"), + "Targuments", _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "preserve_cardinality", + _op._get_attr_bool("preserve_cardinality"), + "use_default_device", _op._get_attr_bool("use_default_device"), + "metadata", _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScanDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScanDataset = tf_export("raw_ops.ScanDataset")(_ops.to_raw_op(scan_dataset)) + + +def scan_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], initial_state, other_arguments, f, output_types, output_shapes, preserve_cardinality: bool, use_default_device: bool, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'scan_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'scan_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if preserve_cardinality is None: + preserve_cardinality = False + preserve_cardinality = _execute.make_bool(preserve_cardinality, "preserve_cardinality") + if use_default_device is None: + use_default_device = True + use_default_device = _execute.make_bool(use_default_device, "use_default_device") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Tstate, initial_state = _execute.convert_to_mixed_eager_tensors(initial_state, ctx) + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(initial_state) + list(other_arguments) + _attrs = ("f", f, "Tstate", _attr_Tstate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes, + "preserve_cardinality", preserve_cardinality, "use_default_device", + use_default_device, "metadata", metadata) + _result = _execute.execute(b"ScanDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScanDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def set_stats_aggregator_dataset(input_dataset: Annotated[Any, _atypes.Variant], stats_aggregator: Annotated[Any, _atypes.Resource], tag: Annotated[Any, _atypes.String], counter_prefix: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + stats_aggregator: A `Tensor` of type `resource`. + tag: A `Tensor` of type `string`. + counter_prefix: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SetStatsAggregatorDataset", name, input_dataset, + stats_aggregator, tag, counter_prefix, "output_types", output_types, + "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return set_stats_aggregator_dataset_eager_fallback( + input_dataset, stats_aggregator, tag, counter_prefix, + output_types=output_types, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'set_stats_aggregator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'set_stats_aggregator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SetStatsAggregatorDataset", input_dataset=input_dataset, + stats_aggregator=stats_aggregator, + tag=tag, counter_prefix=counter_prefix, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SetStatsAggregatorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SetStatsAggregatorDataset = tf_export("raw_ops.SetStatsAggregatorDataset")(_ops.to_raw_op(set_stats_aggregator_dataset)) + + +def set_stats_aggregator_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], stats_aggregator: Annotated[Any, _atypes.Resource], tag: Annotated[Any, _atypes.String], counter_prefix: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'set_stats_aggregator_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'set_stats_aggregator_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + stats_aggregator = _ops.convert_to_tensor(stats_aggregator, _dtypes.resource) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + counter_prefix = _ops.convert_to_tensor(counter_prefix, _dtypes.string) + _inputs_flat = [input_dataset, stats_aggregator, tag, counter_prefix] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"SetStatsAggregatorDataset", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SetStatsAggregatorDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sleep_dataset(input_dataset: Annotated[Any, _atypes.Variant], sleep_microseconds: Annotated[Any, _atypes.Int64], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_dataset: A `Tensor` of type `variant`. + sleep_microseconds: A `Tensor` of type `int64`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SleepDataset", name, input_dataset, sleep_microseconds, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sleep_dataset_eager_fallback( + input_dataset, sleep_microseconds, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sleep_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sleep_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SleepDataset", input_dataset=input_dataset, + sleep_microseconds=sleep_microseconds, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SleepDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SleepDataset = tf_export("raw_ops.SleepDataset")(_ops.to_raw_op(sleep_dataset)) + + +def sleep_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], sleep_microseconds: Annotated[Any, _atypes.Int64], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sleep_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sleep_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + sleep_microseconds = _ops.convert_to_tensor(sleep_microseconds, _dtypes.int64) + _inputs_flat = [input_dataset, sleep_microseconds] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"SleepDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SleepDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sliding_window_dataset(input_dataset: Annotated[Any, _atypes.Variant], window_size: Annotated[Any, _atypes.Int64], window_shift: Annotated[Any, _atypes.Int64], window_stride: Annotated[Any, _atypes.Int64], output_types, output_shapes, drop_remainder:bool=True, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that passes a sliding window over `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + window_size: A `Tensor` of type `int64`. + A scalar representing the number of elements in the + sliding window. + window_shift: A `Tensor` of type `int64`. + A scalar representing the steps moving the sliding window + forward in one iteration. It must be positive. + window_stride: A `Tensor` of type `int64`. + A scalar representing the stride of the input elements of the sliding window. + It must be positive. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + drop_remainder: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SlidingWindowDataset", name, input_dataset, window_size, + window_shift, window_stride, "drop_remainder", drop_remainder, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sliding_window_dataset_eager_fallback( + input_dataset, window_size, window_shift, window_stride, + drop_remainder=drop_remainder, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sliding_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sliding_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if drop_remainder is None: + drop_remainder = True + drop_remainder = _execute.make_bool(drop_remainder, "drop_remainder") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SlidingWindowDataset", input_dataset=input_dataset, + window_size=window_size, + window_shift=window_shift, + window_stride=window_stride, + output_types=output_types, + output_shapes=output_shapes, + drop_remainder=drop_remainder, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("drop_remainder", _op._get_attr_bool("drop_remainder"), + "output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SlidingWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SlidingWindowDataset = tf_export("raw_ops.SlidingWindowDataset")(_ops.to_raw_op(sliding_window_dataset)) + + +def sliding_window_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], window_size: Annotated[Any, _atypes.Int64], window_shift: Annotated[Any, _atypes.Int64], window_stride: Annotated[Any, _atypes.Int64], output_types, output_shapes, drop_remainder: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sliding_window_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sliding_window_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if drop_remainder is None: + drop_remainder = True + drop_remainder = _execute.make_bool(drop_remainder, "drop_remainder") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + window_size = _ops.convert_to_tensor(window_size, _dtypes.int64) + window_shift = _ops.convert_to_tensor(window_shift, _dtypes.int64) + window_stride = _ops.convert_to_tensor(window_stride, _dtypes.int64) + _inputs_flat = [input_dataset, window_size, window_shift, window_stride] + _attrs = ("drop_remainder", drop_remainder, "output_types", output_types, + "output_shapes", output_shapes) + _result = _execute.execute(b"SlidingWindowDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SlidingWindowDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def snapshot_chunk_dataset(chunk_file: Annotated[Any, _atypes.String], output_types, output_shapes, compression:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + chunk_file: A `Tensor` of type `string`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + compression: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SnapshotChunkDataset", name, chunk_file, "output_types", + output_types, "output_shapes", output_shapes, "compression", + compression) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_chunk_dataset_eager_fallback( + chunk_file, output_types=output_types, output_shapes=output_shapes, + compression=compression, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_chunk_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_chunk_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SnapshotChunkDataset", chunk_file=chunk_file, + output_types=output_types, + output_shapes=output_shapes, + compression=compression, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "compression", + _op.get_attr("compression")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SnapshotChunkDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SnapshotChunkDataset = tf_export("raw_ops.SnapshotChunkDataset")(_ops.to_raw_op(snapshot_chunk_dataset)) + + +def snapshot_chunk_dataset_eager_fallback(chunk_file: Annotated[Any, _atypes.String], output_types, output_shapes, compression: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_chunk_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_chunk_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + chunk_file = _ops.convert_to_tensor(chunk_file, _dtypes.string) + _inputs_flat = [chunk_file] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "compression", compression) + _result = _execute.execute(b"SnapshotChunkDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SnapshotChunkDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def snapshot_dataset(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], output_types, output_shapes, compression:str="", reader_path_prefix:str="", writer_path_prefix:str="", shard_size_bytes:int=10737418240, pending_snapshot_expiry_seconds:int=86400, num_reader_threads:int=1, reader_buffer_size:int=1, num_writer_threads:int=1, writer_buffer_size:int=1, shuffle_on_read:bool=False, seed:int=0, seed2:int=0, mode:str="auto", snapshot_name:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that will write to / read from a snapshot. + + This dataset attempts to determine whether a valid snapshot exists at the + `snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`. + If not, it will run the preprocessing pipeline as usual, and write out a + snapshot of the data processed for future use. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + path: A `Tensor` of type `string`. + The path we should write snapshots to / read snapshots from. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + compression: An optional `string`. Defaults to `""`. + reader_path_prefix: An optional `string`. Defaults to `""`. + writer_path_prefix: An optional `string`. Defaults to `""`. + shard_size_bytes: An optional `int`. Defaults to `10737418240`. + pending_snapshot_expiry_seconds: An optional `int`. Defaults to `86400`. + num_reader_threads: An optional `int`. Defaults to `1`. + reader_buffer_size: An optional `int`. Defaults to `1`. + num_writer_threads: An optional `int`. Defaults to `1`. + writer_buffer_size: An optional `int`. Defaults to `1`. + shuffle_on_read: An optional `bool`. Defaults to `False`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + mode: An optional `string`. Defaults to `"auto"`. + snapshot_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SnapshotDataset", name, input_dataset, path, "output_types", + output_types, "output_shapes", output_shapes, "compression", + compression, "reader_path_prefix", reader_path_prefix, + "writer_path_prefix", writer_path_prefix, "shard_size_bytes", + shard_size_bytes, "pending_snapshot_expiry_seconds", + pending_snapshot_expiry_seconds, "num_reader_threads", + num_reader_threads, "reader_buffer_size", reader_buffer_size, + "num_writer_threads", num_writer_threads, "writer_buffer_size", + writer_buffer_size, "shuffle_on_read", shuffle_on_read, "seed", seed, + "seed2", seed2, "mode", mode, "snapshot_name", snapshot_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_dataset_eager_fallback( + input_dataset, path, output_types=output_types, + output_shapes=output_shapes, compression=compression, + reader_path_prefix=reader_path_prefix, + writer_path_prefix=writer_path_prefix, + shard_size_bytes=shard_size_bytes, + pending_snapshot_expiry_seconds=pending_snapshot_expiry_seconds, + num_reader_threads=num_reader_threads, + reader_buffer_size=reader_buffer_size, + num_writer_threads=num_writer_threads, + writer_buffer_size=writer_buffer_size, + shuffle_on_read=shuffle_on_read, seed=seed, seed2=seed2, mode=mode, + snapshot_name=snapshot_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if reader_path_prefix is None: + reader_path_prefix = "" + reader_path_prefix = _execute.make_str(reader_path_prefix, "reader_path_prefix") + if writer_path_prefix is None: + writer_path_prefix = "" + writer_path_prefix = _execute.make_str(writer_path_prefix, "writer_path_prefix") + if shard_size_bytes is None: + shard_size_bytes = 10737418240 + shard_size_bytes = _execute.make_int(shard_size_bytes, "shard_size_bytes") + if pending_snapshot_expiry_seconds is None: + pending_snapshot_expiry_seconds = 86400 + pending_snapshot_expiry_seconds = _execute.make_int(pending_snapshot_expiry_seconds, "pending_snapshot_expiry_seconds") + if num_reader_threads is None: + num_reader_threads = 1 + num_reader_threads = _execute.make_int(num_reader_threads, "num_reader_threads") + if reader_buffer_size is None: + reader_buffer_size = 1 + reader_buffer_size = _execute.make_int(reader_buffer_size, "reader_buffer_size") + if num_writer_threads is None: + num_writer_threads = 1 + num_writer_threads = _execute.make_int(num_writer_threads, "num_writer_threads") + if writer_buffer_size is None: + writer_buffer_size = 1 + writer_buffer_size = _execute.make_int(writer_buffer_size, "writer_buffer_size") + if shuffle_on_read is None: + shuffle_on_read = False + shuffle_on_read = _execute.make_bool(shuffle_on_read, "shuffle_on_read") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if mode is None: + mode = "auto" + mode = _execute.make_str(mode, "mode") + if snapshot_name is None: + snapshot_name = "" + snapshot_name = _execute.make_str(snapshot_name, "snapshot_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SnapshotDataset", input_dataset=input_dataset, path=path, + output_types=output_types, + output_shapes=output_shapes, + compression=compression, + reader_path_prefix=reader_path_prefix, + writer_path_prefix=writer_path_prefix, + shard_size_bytes=shard_size_bytes, + pending_snapshot_expiry_seconds=pending_snapshot_expiry_seconds, + num_reader_threads=num_reader_threads, + reader_buffer_size=reader_buffer_size, + num_writer_threads=num_writer_threads, + writer_buffer_size=writer_buffer_size, + shuffle_on_read=shuffle_on_read, seed=seed, + seed2=seed2, mode=mode, + snapshot_name=snapshot_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "compression", + _op.get_attr("compression"), "reader_path_prefix", + _op.get_attr("reader_path_prefix"), "writer_path_prefix", + _op.get_attr("writer_path_prefix"), "shard_size_bytes", + _op._get_attr_int("shard_size_bytes"), + "pending_snapshot_expiry_seconds", + _op._get_attr_int("pending_snapshot_expiry_seconds"), + "num_reader_threads", _op._get_attr_int("num_reader_threads"), + "reader_buffer_size", _op._get_attr_int("reader_buffer_size"), + "num_writer_threads", _op._get_attr_int("num_writer_threads"), + "writer_buffer_size", _op._get_attr_int("writer_buffer_size"), + "shuffle_on_read", _op._get_attr_bool("shuffle_on_read"), + "seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "mode", _op.get_attr("mode"), + "snapshot_name", _op.get_attr("snapshot_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SnapshotDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SnapshotDataset = tf_export("raw_ops.SnapshotDataset")(_ops.to_raw_op(snapshot_dataset)) + + +def snapshot_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], output_types, output_shapes, compression: str, reader_path_prefix: str, writer_path_prefix: str, shard_size_bytes: int, pending_snapshot_expiry_seconds: int, num_reader_threads: int, reader_buffer_size: int, num_writer_threads: int, writer_buffer_size: int, shuffle_on_read: bool, seed: int, seed2: int, mode: str, snapshot_name: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if reader_path_prefix is None: + reader_path_prefix = "" + reader_path_prefix = _execute.make_str(reader_path_prefix, "reader_path_prefix") + if writer_path_prefix is None: + writer_path_prefix = "" + writer_path_prefix = _execute.make_str(writer_path_prefix, "writer_path_prefix") + if shard_size_bytes is None: + shard_size_bytes = 10737418240 + shard_size_bytes = _execute.make_int(shard_size_bytes, "shard_size_bytes") + if pending_snapshot_expiry_seconds is None: + pending_snapshot_expiry_seconds = 86400 + pending_snapshot_expiry_seconds = _execute.make_int(pending_snapshot_expiry_seconds, "pending_snapshot_expiry_seconds") + if num_reader_threads is None: + num_reader_threads = 1 + num_reader_threads = _execute.make_int(num_reader_threads, "num_reader_threads") + if reader_buffer_size is None: + reader_buffer_size = 1 + reader_buffer_size = _execute.make_int(reader_buffer_size, "reader_buffer_size") + if num_writer_threads is None: + num_writer_threads = 1 + num_writer_threads = _execute.make_int(num_writer_threads, "num_writer_threads") + if writer_buffer_size is None: + writer_buffer_size = 1 + writer_buffer_size = _execute.make_int(writer_buffer_size, "writer_buffer_size") + if shuffle_on_read is None: + shuffle_on_read = False + shuffle_on_read = _execute.make_bool(shuffle_on_read, "shuffle_on_read") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if mode is None: + mode = "auto" + mode = _execute.make_str(mode, "mode") + if snapshot_name is None: + snapshot_name = "" + snapshot_name = _execute.make_str(snapshot_name, "snapshot_name") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + path = _ops.convert_to_tensor(path, _dtypes.string) + _inputs_flat = [input_dataset, path] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "reader_path_prefix", reader_path_prefix, + "writer_path_prefix", writer_path_prefix, "shard_size_bytes", + shard_size_bytes, "pending_snapshot_expiry_seconds", + pending_snapshot_expiry_seconds, "num_reader_threads", num_reader_threads, + "reader_buffer_size", reader_buffer_size, "num_writer_threads", + num_writer_threads, "writer_buffer_size", writer_buffer_size, + "shuffle_on_read", shuffle_on_read, "seed", seed, "seed2", seed2, "mode", + mode, "snapshot_name", snapshot_name) + _result = _execute.execute(b"SnapshotDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SnapshotDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def snapshot_dataset_reader(shard_dir: Annotated[Any, _atypes.String], start_index: Annotated[Any, _atypes.Int64], output_types, output_shapes, version: int, compression:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + shard_dir: A `Tensor` of type `string`. + start_index: A `Tensor` of type `int64`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + version: An `int`. + compression: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SnapshotDatasetReader", name, shard_dir, start_index, + "output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "version", version) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_dataset_reader_eager_fallback( + shard_dir, start_index, output_types=output_types, + output_shapes=output_shapes, compression=compression, + version=version, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset_reader' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset_reader' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + version = _execute.make_int(version, "version") + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SnapshotDatasetReader", shard_dir=shard_dir, start_index=start_index, + output_types=output_types, + output_shapes=output_shapes, version=version, + compression=compression, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "compression", + _op.get_attr("compression"), "version", + _op._get_attr_int("version")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SnapshotDatasetReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SnapshotDatasetReader = tf_export("raw_ops.SnapshotDatasetReader")(_ops.to_raw_op(snapshot_dataset_reader)) + + +def snapshot_dataset_reader_eager_fallback(shard_dir: Annotated[Any, _atypes.String], start_index: Annotated[Any, _atypes.Int64], output_types, output_shapes, version: int, compression: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset_reader' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset_reader' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + version = _execute.make_int(version, "version") + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + shard_dir = _ops.convert_to_tensor(shard_dir, _dtypes.string) + start_index = _ops.convert_to_tensor(start_index, _dtypes.int64) + _inputs_flat = [shard_dir, start_index] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "version", version) + _result = _execute.execute(b"SnapshotDatasetReader", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SnapshotDatasetReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def snapshot_dataset_v2(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], reader_func_other_args, shard_func_other_args, output_types, output_shapes, reader_func, shard_func, compression:str="", reader_prefix:str="", writer_prefix:str="", hash_valid:bool=False, hash:int=0, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that will write to / read from a snapshot. + + This dataset attempts to determine whether a valid snapshot exists at the + `snapshot_path`, and reads from the snapshot in lieu of using `input_dataset`. + If not, it will run the preprocessing pipeline as usual, and write out a + snapshot of the data processed for future use. + + Args: + input_dataset: A `Tensor` of type `variant`. + A variant tensor representing the input dataset. + path: A `Tensor` of type `string`. + The path we should write snapshots to / read snapshots from. + reader_func_other_args: A list of `Tensor` objects. + shard_func_other_args: A list of `Tensor` objects. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + reader_func: A function decorated with @Defun. + Optional. A function to control how to read data from snapshot shards. + shard_func: A function decorated with @Defun. + Optional. A function to control how to shard data when writing a snapshot. + compression: An optional `string`. Defaults to `""`. + The type of compression to be applied to the saved snapshot files. + reader_prefix: An optional `string`. Defaults to `""`. + writer_prefix: An optional `string`. Defaults to `""`. + hash_valid: An optional `bool`. Defaults to `False`. + hash: An optional `int`. Defaults to `0`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SnapshotDatasetV2", name, input_dataset, path, + reader_func_other_args, shard_func_other_args, "output_types", + output_types, "output_shapes", output_shapes, "compression", + compression, "reader_prefix", reader_prefix, "writer_prefix", + writer_prefix, "hash_valid", hash_valid, "hash", hash, "reader_func", + reader_func, "shard_func", shard_func, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_dataset_v2_eager_fallback( + input_dataset, path, reader_func_other_args, shard_func_other_args, + output_types=output_types, output_shapes=output_shapes, + compression=compression, reader_prefix=reader_prefix, + writer_prefix=writer_prefix, hash_valid=hash_valid, hash=hash, + reader_func=reader_func, shard_func=shard_func, metadata=metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if reader_prefix is None: + reader_prefix = "" + reader_prefix = _execute.make_str(reader_prefix, "reader_prefix") + if writer_prefix is None: + writer_prefix = "" + writer_prefix = _execute.make_str(writer_prefix, "writer_prefix") + if hash_valid is None: + hash_valid = False + hash_valid = _execute.make_bool(hash_valid, "hash_valid") + if hash is None: + hash = 0 + hash = _execute.make_int(hash, "hash") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SnapshotDatasetV2", input_dataset=input_dataset, path=path, + reader_func_other_args=reader_func_other_args, + shard_func_other_args=shard_func_other_args, + output_types=output_types, + output_shapes=output_shapes, + reader_func=reader_func, shard_func=shard_func, + compression=compression, + reader_prefix=reader_prefix, + writer_prefix=writer_prefix, + hash_valid=hash_valid, hash=hash, + metadata=metadata, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "compression", + _op.get_attr("compression"), "reader_prefix", + _op.get_attr("reader_prefix"), "writer_prefix", + _op.get_attr("writer_prefix"), "hash_valid", + _op._get_attr_bool("hash_valid"), "hash", + _op._get_attr_int("hash"), "reader_func", + _op.get_attr("reader_func"), "shard_func", + _op.get_attr("shard_func"), "Treader_func_args", + _op.get_attr("Treader_func_args"), "Tshard_func_args", + _op.get_attr("Tshard_func_args"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SnapshotDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SnapshotDatasetV2 = tf_export("raw_ops.SnapshotDatasetV2")(_ops.to_raw_op(snapshot_dataset_v2)) + + +def snapshot_dataset_v2_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], path: Annotated[Any, _atypes.String], reader_func_other_args, shard_func_other_args, output_types, output_shapes, reader_func, shard_func, compression: str, reader_prefix: str, writer_prefix: str, hash_valid: bool, hash: int, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_dataset_v2' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_dataset_v2' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if compression is None: + compression = "" + compression = _execute.make_str(compression, "compression") + if reader_prefix is None: + reader_prefix = "" + reader_prefix = _execute.make_str(reader_prefix, "reader_prefix") + if writer_prefix is None: + writer_prefix = "" + writer_prefix = _execute.make_str(writer_prefix, "writer_prefix") + if hash_valid is None: + hash_valid = False + hash_valid = _execute.make_bool(hash_valid, "hash_valid") + if hash is None: + hash = 0 + hash = _execute.make_int(hash, "hash") + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Treader_func_args, reader_func_other_args = _execute.convert_to_mixed_eager_tensors(reader_func_other_args, ctx) + _attr_Tshard_func_args, shard_func_other_args = _execute.convert_to_mixed_eager_tensors(shard_func_other_args, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + path = _ops.convert_to_tensor(path, _dtypes.string) + _inputs_flat = [input_dataset, path] + list(reader_func_other_args) + list(shard_func_other_args) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "compression", compression, "reader_prefix", reader_prefix, "writer_prefix", + writer_prefix, "hash_valid", hash_valid, "hash", hash, "reader_func", + reader_func, "shard_func", shard_func, "Treader_func_args", + _attr_Treader_func_args, "Tshard_func_args", _attr_Tshard_func_args, + "metadata", metadata) + _result = _execute.execute(b"SnapshotDatasetV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SnapshotDatasetV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def snapshot_nested_dataset_reader(inputs: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + inputs: A list of at least 1 `Tensor` objects with type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SnapshotNestedDatasetReader", name, inputs, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return snapshot_nested_dataset_reader_eager_fallback( + inputs, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SnapshotNestedDatasetReader", inputs=inputs, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SnapshotNestedDatasetReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SnapshotNestedDatasetReader = tf_export("raw_ops.SnapshotNestedDatasetReader")(_ops.to_raw_op(snapshot_nested_dataset_reader)) + + +def snapshot_nested_dataset_reader_eager_fallback(inputs: Annotated[List[Any], _atypes.Variant], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'snapshot_nested_dataset_reader' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + inputs = _ops.convert_n_to_tensor(inputs, _dtypes.variant) + _inputs_flat = list(inputs) + _attrs = ("output_types", output_types, "output_shapes", output_shapes, "N", + _attr_N) + _result = _execute.execute(b"SnapshotNestedDatasetReader", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SnapshotNestedDatasetReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sql_dataset(driver_name: Annotated[Any, _atypes.String], data_source_name: Annotated[Any, _atypes.String], query: Annotated[Any, _atypes.String], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that executes a SQL query and emits rows of the result set. + + Args: + driver_name: A `Tensor` of type `string`. + The database type. Currently, the only supported type is 'sqlite'. + data_source_name: A `Tensor` of type `string`. + A connection string to connect to the database. + query: A `Tensor` of type `string`. A SQL query to execute. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SqlDataset", name, driver_name, data_source_name, query, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sql_dataset_eager_fallback( + driver_name, data_source_name, query, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sql_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sql_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SqlDataset", driver_name=driver_name, + data_source_name=data_source_name, query=query, + output_types=output_types, output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SqlDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SqlDataset = tf_export("raw_ops.SqlDataset")(_ops.to_raw_op(sql_dataset)) + + +def sql_dataset_eager_fallback(driver_name: Annotated[Any, _atypes.String], data_source_name: Annotated[Any, _atypes.String], query: Annotated[Any, _atypes.String], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'sql_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'sql_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + driver_name = _ops.convert_to_tensor(driver_name, _dtypes.string) + data_source_name = _ops.convert_to_tensor(data_source_name, _dtypes.string) + query = _ops.convert_to_tensor(query, _dtypes.string) + _inputs_flat = [driver_name, data_source_name, query] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"SqlDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SqlDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def stats_aggregator_handle(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a statistics manager resource. + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatsAggregatorHandle", name, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stats_aggregator_handle_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatsAggregatorHandle", container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatsAggregatorHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatsAggregatorHandle = tf_export("raw_ops.StatsAggregatorHandle")(_ops.to_raw_op(stats_aggregator_handle)) + + +def stats_aggregator_handle_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"StatsAggregatorHandle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatsAggregatorHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def stats_aggregator_handle_v2(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatsAggregatorHandleV2", name, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stats_aggregator_handle_v2_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatsAggregatorHandleV2", container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatsAggregatorHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatsAggregatorHandleV2 = tf_export("raw_ops.StatsAggregatorHandleV2")(_ops.to_raw_op(stats_aggregator_handle_v2)) + + +def stats_aggregator_handle_v2_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"StatsAggregatorHandleV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatsAggregatorHandleV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def stats_aggregator_set_summary_writer(stats_aggregator: Annotated[Any, _atypes.Resource], summary: Annotated[Any, _atypes.Resource], name=None): + r"""Set a summary_writer_interface to record statistics using given stats_aggregator. + + Args: + stats_aggregator: A `Tensor` of type `resource`. + summary: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatsAggregatorSetSummaryWriter", name, stats_aggregator, + summary) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stats_aggregator_set_summary_writer_eager_fallback( + stats_aggregator, summary, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatsAggregatorSetSummaryWriter", stats_aggregator=stats_aggregator, + summary=summary, name=name) + return _op +StatsAggregatorSetSummaryWriter = tf_export("raw_ops.StatsAggregatorSetSummaryWriter")(_ops.to_raw_op(stats_aggregator_set_summary_writer)) + + +def stats_aggregator_set_summary_writer_eager_fallback(stats_aggregator: Annotated[Any, _atypes.Resource], summary: Annotated[Any, _atypes.Resource], name, ctx): + stats_aggregator = _ops.convert_to_tensor(stats_aggregator, _dtypes.resource) + summary = _ops.convert_to_tensor(summary, _dtypes.resource) + _inputs_flat = [stats_aggregator, summary] + _attrs = None + _result = _execute.execute(b"StatsAggregatorSetSummaryWriter", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def stats_aggregator_summary(iterator: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Produces a summary of any statistics recorded by the given statistics manager. + + Args: + iterator: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatsAggregatorSummary", name, iterator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stats_aggregator_summary_eager_fallback( + iterator, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatsAggregatorSummary", iterator=iterator, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatsAggregatorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatsAggregatorSummary = tf_export("raw_ops.StatsAggregatorSummary")(_ops.to_raw_op(stats_aggregator_summary)) + + +def stats_aggregator_summary_eager_fallback(iterator: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + iterator = _ops.convert_to_tensor(iterator, _dtypes.resource) + _inputs_flat = [iterator] + _attrs = None + _result = _execute.execute(b"StatsAggregatorSummary", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatsAggregatorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def take_while_dataset(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that stops iteration when predicate` is false. + + The `predicate` function must return a scalar boolean and accept the + following arguments: + + * One tensor for each component of an element of `input_dataset`. + * One tensor for each value in `other_arguments`. + + Args: + input_dataset: A `Tensor` of type `variant`. + other_arguments: A list of `Tensor` objects. + A list of tensors, typically values that were captured when + building a closure for `predicate`. + predicate: A function decorated with @Defun. + A function returning a scalar boolean. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TakeWhileDataset", name, input_dataset, other_arguments, + "predicate", predicate, "output_types", output_types, "output_shapes", + output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return take_while_dataset_eager_fallback( + input_dataset, other_arguments, predicate=predicate, + output_types=output_types, output_shapes=output_shapes, + metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'take_while_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'take_while_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TakeWhileDataset", input_dataset=input_dataset, + other_arguments=other_arguments, + predicate=predicate, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("predicate", _op.get_attr("predicate"), "Targuments", + _op.get_attr("Targuments"), "output_types", + _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TakeWhileDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TakeWhileDataset = tf_export("raw_ops.TakeWhileDataset")(_ops.to_raw_op(take_while_dataset)) + + +def take_while_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], other_arguments, predicate, output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'take_while_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'take_while_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _attr_Targuments, other_arguments = _execute.convert_to_mixed_eager_tensors(other_arguments, ctx) + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + list(other_arguments) + _attrs = ("predicate", predicate, "Targuments", _attr_Targuments, + "output_types", output_types, "output_shapes", output_shapes, "metadata", + metadata) + _result = _execute.execute(b"TakeWhileDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TakeWhileDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def thread_pool_dataset(input_dataset: Annotated[Any, _atypes.Variant], thread_pool: Annotated[Any, _atypes.Resource], output_types, output_shapes, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + thread_pool: A `Tensor` of type `resource`. + A resource produced by the ThreadPoolHandle op. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ThreadPoolDataset", name, input_dataset, thread_pool, + "output_types", output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return thread_pool_dataset_eager_fallback( + input_dataset, thread_pool, output_types=output_types, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ThreadPoolDataset", input_dataset=input_dataset, + thread_pool=thread_pool, + output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ThreadPoolDataset = tf_export("raw_ops.ThreadPoolDataset")(_ops.to_raw_op(thread_pool_dataset)) + + +def thread_pool_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], thread_pool: Annotated[Any, _atypes.Resource], output_types, output_shapes, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'thread_pool_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'thread_pool_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + thread_pool = _ops.convert_to_tensor(thread_pool, _dtypes.resource) + _inputs_flat = [input_dataset, thread_pool] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"ThreadPoolDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ThreadPoolDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def thread_pool_handle(num_threads: int, display_name: str, max_intra_op_parallelism:int=1, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a dataset that uses a custom thread pool to compute `input_dataset`. + + Args: + num_threads: An `int`. The number of threads in the thread pool. + display_name: A `string`. + A human-readable name for the threads that may be visible in some + visualizations. + threadpool. + max_intra_op_parallelism: An optional `int`. Defaults to `1`. + The maximum degree of parallelism to use within operations that execute on this + threadpool. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ThreadPoolHandle", name, "num_threads", num_threads, + "max_intra_op_parallelism", max_intra_op_parallelism, "display_name", + display_name, "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return thread_pool_handle_eager_fallback( + num_threads=num_threads, + max_intra_op_parallelism=max_intra_op_parallelism, + display_name=display_name, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_threads = _execute.make_int(num_threads, "num_threads") + display_name = _execute.make_str(display_name, "display_name") + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ThreadPoolHandle", num_threads=num_threads, + display_name=display_name, + max_intra_op_parallelism=max_intra_op_parallelism, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_threads", _op._get_attr_int("num_threads"), + "max_intra_op_parallelism", + _op._get_attr_int("max_intra_op_parallelism"), "display_name", + _op.get_attr("display_name"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ThreadPoolHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ThreadPoolHandle = tf_export("raw_ops.ThreadPoolHandle")(_ops.to_raw_op(thread_pool_handle)) + + +def thread_pool_handle_eager_fallback(num_threads: int, display_name: str, max_intra_op_parallelism: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + num_threads = _execute.make_int(num_threads, "num_threads") + display_name = _execute.make_str(display_name, "display_name") + if max_intra_op_parallelism is None: + max_intra_op_parallelism = 1 + max_intra_op_parallelism = _execute.make_int(max_intra_op_parallelism, "max_intra_op_parallelism") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("num_threads", num_threads, "max_intra_op_parallelism", + max_intra_op_parallelism, "display_name", display_name, "container", + container, "shared_name", shared_name) + _result = _execute.execute(b"ThreadPoolHandle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ThreadPoolHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def unbatch_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""A dataset that splits the elements of its input into multiple elements. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnbatchDataset", name, input_dataset, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unbatch_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'unbatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'unbatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnbatchDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnbatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnbatchDataset = tf_export("raw_ops.UnbatchDataset")(_ops.to_raw_op(unbatch_dataset)) + + +def unbatch_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'unbatch_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'unbatch_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"UnbatchDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnbatchDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def uncompress_element(compressed: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None): + r"""Uncompresses a compressed dataset element. + + Args: + compressed: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UncompressElement", name, compressed, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uncompress_element_eager_fallback( + compressed, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'uncompress_element' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'uncompress_element' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UncompressElement", compressed=compressed, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UncompressElement", _inputs_flat, _attrs, _result) + return _result + +UncompressElement = tf_export("raw_ops.UncompressElement")(_ops.to_raw_op(uncompress_element)) + + +def uncompress_element_eager_fallback(compressed: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'uncompress_element' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'uncompress_element' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + compressed = _ops.convert_to_tensor(compressed, _dtypes.variant) + _inputs_flat = [compressed] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"UncompressElement", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UncompressElement", _inputs_flat, _attrs, _result) + return _result + + +def unique_dataset(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata:str="", name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a dataset that contains the unique elements of `input_dataset`. + + Args: + input_dataset: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + metadata: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniqueDataset", name, input_dataset, "output_types", + output_types, "output_shapes", output_shapes, "metadata", metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unique_dataset_eager_fallback( + input_dataset, output_types=output_types, + output_shapes=output_shapes, metadata=metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'unique_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'unique_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniqueDataset", input_dataset=input_dataset, + output_types=output_types, + output_shapes=output_shapes, metadata=metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes"), "metadata", + _op.get_attr("metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniqueDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniqueDataset = tf_export("raw_ops.UniqueDataset")(_ops.to_raw_op(unique_dataset)) + + +def unique_dataset_eager_fallback(input_dataset: Annotated[Any, _atypes.Variant], output_types, output_shapes, metadata: str, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'unique_dataset' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'unique_dataset' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if metadata is None: + metadata = "" + metadata = _execute.make_str(metadata, "metadata") + input_dataset = _ops.convert_to_tensor(input_dataset, _dtypes.variant) + _inputs_flat = [input_dataset] + _attrs = ("output_types", output_types, "output_shapes", output_shapes, + "metadata", metadata) + _result = _execute.execute(b"UniqueDataset", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniqueDataset", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_filesystem_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_filesystem_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c8db7ca04c4878178a1586110c35cc020af96dd6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_filesystem_ops.py @@ -0,0 +1,72 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def file_system_set_configuration(scheme: Annotated[Any, _atypes.String], key: Annotated[Any, _atypes.String], value: Annotated[Any, _atypes.String], name=None): + r"""Set configuration of the file system. + + Args: + scheme: A `Tensor` of type `string`. File system scheme. + key: A `Tensor` of type `string`. The name of the configuration option. + value: A `Tensor` of type `string`. The value of the configuration option. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FileSystemSetConfiguration", name, scheme, key, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return file_system_set_configuration_eager_fallback( + scheme, key, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FileSystemSetConfiguration", scheme=scheme, key=key, value=value, + name=name) + return _op +FileSystemSetConfiguration = tf_export("raw_ops.FileSystemSetConfiguration")(_ops.to_raw_op(file_system_set_configuration)) + + +def file_system_set_configuration_eager_fallback(scheme: Annotated[Any, _atypes.String], key: Annotated[Any, _atypes.String], value: Annotated[Any, _atypes.String], name, ctx): + scheme = _ops.convert_to_tensor(scheme, _dtypes.string) + key = _ops.convert_to_tensor(key, _dtypes.string) + value = _ops.convert_to_tensor(value, _dtypes.string) + _inputs_flat = [scheme, key, value] + _attrs = None + _result = _execute.execute(b"FileSystemSetConfiguration", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_functional_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_functional_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ec20eb347e3b2d84d72a77c93f731325be8e0899 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_functional_ops.py @@ -0,0 +1,1306 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def case(branch_index: Annotated[Any, _atypes.Int32], input, Tout, branches, output_shapes=[], name=None): + r"""An n-way switch statement which calls a single branch function. + + An n-way switch statement, implementing the following: + ``` + switch (branch_index) { + case 0: + output = branches[0](input); + break; + case 1: + output = branches[1](input); + break; + ... + case [[nbranches-1]]: + default: + output = branches[nbranches-1](input); + break; + } + ``` + + Args: + branch_index: A `Tensor` of type `int32`. + The branch selector, an int32 Tensor. + input: A list of `Tensor` objects. + A list of input tensors passed to the branch function. + Tout: A list of `tf.DTypes`. A list of output types. + branches: A list of functions decorated with @Defun that has length `>= 1`. + A list of functions each of which takes 'inputs' and returns a list of + tensors, whose types are the same as what every other branch returns. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Case", name, branch_index, input, "Tout", Tout, "branches", + branches, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return case_eager_fallback( + branch_index, input, Tout=Tout, branches=branches, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'case' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'case' Op, not %r." % branches) + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'case' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Case", branch_index=branch_index, input=input, Tout=Tout, + branches=branches, output_shapes=output_shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), + "branches", _op.get_attr("branches"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Case", _inputs_flat, _attrs, _result) + return _result + +Case = tf_export("raw_ops.Case")(_ops.to_raw_op(case)) + + +def case_eager_fallback(branch_index: Annotated[Any, _atypes.Int32], input, Tout, branches, output_shapes, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'case' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'case' Op, not %r." % branches) + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'case' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + branch_index = _ops.convert_to_tensor(branch_index, _dtypes.int32) + _inputs_flat = [branch_index] + list(input) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "branches", branches, + "output_shapes", output_shapes) + _result = _execute.execute(b"Case", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Case", _inputs_flat, _attrs, _result) + return _result + + +def device_index(device_names, name=None) -> Annotated[Any, _atypes.Int32]: + r"""Return the index of device the op runs. + + Given a list of device names, this operation returns the index of the device + this op runs. The length of the list is returned in two cases: + (1) Device does not exist in the given device list. + (2) It is in XLA compilation. + + Args: + device_names: A list of `strings`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeviceIndex", name, "device_names", device_names) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return device_index_eager_fallback( + device_names=device_names, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(device_names, (list, tuple)): + raise TypeError( + "Expected list for 'device_names' argument to " + "'device_index' Op, not %r." % device_names) + device_names = [_execute.make_str(_s, "device_names") for _s in device_names] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeviceIndex", device_names=device_names, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("device_names", _op.get_attr("device_names")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DeviceIndex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DeviceIndex = tf_export("raw_ops.DeviceIndex")(_ops.to_raw_op(device_index)) + + +def device_index_eager_fallback(device_names, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(device_names, (list, tuple)): + raise TypeError( + "Expected list for 'device_names' argument to " + "'device_index' Op, not %r." % device_names) + device_names = [_execute.make_str(_s, "device_names") for _s in device_names] + _inputs_flat = [] + _attrs = ("device_names", device_names) + _result = _execute.execute(b"DeviceIndex", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DeviceIndex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FakeParam_dtype = TypeVar("TV_FakeParam_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def fake_param(dtype: TV_FakeParam_dtype, shape, name=None) -> Annotated[Any, TV_FakeParam_dtype]: + r""" This op is used as a placeholder in If branch functions. It doesn't provide a + valid output when run, so must either be removed (e.g. replaced with a + function input) or guaranteed not to be used (e.g. if mirroring an + intermediate output needed for the gradient computation of the other branch). + + Args: + dtype: A `tf.DType`. The type of the output. + shape: A `tf.TensorShape` or list of `ints`. + The purported shape of the output. This is only used for shape inference; + the output will not necessarily have this shape. Can be a partial shape. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FakeParam", name, "dtype", dtype, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fake_param_eager_fallback( + dtype=dtype, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FakeParam", dtype=dtype, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FakeParam", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FakeParam = tf_export("raw_ops.FakeParam")(_ops.to_raw_op(fake_param)) + + +def fake_param_eager_fallback(dtype: TV_FakeParam_dtype, shape, name, ctx) -> Annotated[Any, TV_FakeParam_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape) + _result = _execute.execute(b"FakeParam", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FakeParam", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def _for(start: Annotated[Any, _atypes.Int32], limit: Annotated[Any, _atypes.Int32], delta: Annotated[Any, _atypes.Int32], input, body, name=None): + r"""Applies a for loop. + + ```python + output = input; + for i in range(start, limit, delta) + output = body(i, output); + ``` + + Args: + start: A `Tensor` of type `int32`. The lower bound. An int32 + limit: A `Tensor` of type `int32`. The upper bound. An int32 + delta: A `Tensor` of type `int32`. The increment. An int32 + input: A list of `Tensor` objects. + A list of input tensors whose types are T. + body: A function decorated with @Defun. + A function that takes a list of tensors (int32, T) and returns another + list of tensors (T). + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "For", name, start, limit, delta, input, "body", body) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _for_eager_fallback( + start, limit, delta, input, body=body, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "For", start=start, limit=limit, delta=delta, input=input, body=body, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T"), "body", _op.get_attr("body")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "For", _inputs_flat, _attrs, _result) + return _result + +For = tf_export("raw_ops.For")(_ops.to_raw_op(_for)) + + +def _for_eager_fallback(start: Annotated[Any, _atypes.Int32], limit: Annotated[Any, _atypes.Int32], delta: Annotated[Any, _atypes.Int32], input, body, name, ctx): + _attr_T, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + start = _ops.convert_to_tensor(start, _dtypes.int32) + limit = _ops.convert_to_tensor(limit, _dtypes.int32) + delta = _ops.convert_to_tensor(delta, _dtypes.int32) + _inputs_flat = [start, limit, delta] + list(input) + _attrs = ("T", _attr_T, "body", body) + _result = _execute.execute(b"For", len(input), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "For", _inputs_flat, _attrs, _result) + return _result + + +TV_If_Tcond = TypeVar("TV_If_Tcond", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def _if(cond: Annotated[Any, TV_If_Tcond], input, Tout, then_branch, else_branch, output_shapes=[], name=None): + r"""output = cond ? then_branch(input) : else_branch(input) + + Args: + cond: A `Tensor`. + A Tensor. If the tensor is a scalar of non-boolean type, the + scalar is converted to a boolean according to the + following rule: if the scalar is a numerical value, non-zero means + `True` and zero means False; if the scalar is a string, non-empty + means `True` and empty means `False`. If the tensor is not a scalar, + being empty means False and being non-empty means True. + input: A list of `Tensor` objects. A list of input tensors. + Tout: A list of `tf.DTypes`. A list of output types. + then_branch: A function decorated with @Defun. + A function that takes 'inputs' and returns a list of tensors, whose + types are the same as what else_branch returns. + else_branch: A function decorated with @Defun. + A function that takes 'inputs' and returns a list of tensors, whose + types are the same as what then_branch returns. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "If", name, cond, input, "Tout", Tout, "then_branch", + then_branch, "else_branch", else_branch, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _if_eager_fallback( + cond, input, Tout=Tout, then_branch=then_branch, + else_branch=else_branch, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'if' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'if' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "If", cond=cond, input=input, Tout=Tout, then_branch=then_branch, + else_branch=else_branch, output_shapes=output_shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("Tcond", _op._get_attr_type("Tcond"), "Tin", + _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), + "then_branch", _op.get_attr("then_branch"), "else_branch", + _op.get_attr("else_branch"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "If", _inputs_flat, _attrs, _result) + return _result + +If = tf_export("raw_ops.If")(_ops.to_raw_op(_if)) + + +def _if_eager_fallback(cond: Annotated[Any, TV_If_Tcond], input, Tout, then_branch, else_branch, output_shapes, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'if' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'if' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tcond, (cond,) = _execute.args_to_matching_eager([cond], ctx, []) + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = [cond] + list(input) + _attrs = ("Tcond", _attr_Tcond, "Tin", _attr_Tin, "Tout", Tout, + "then_branch", then_branch, "else_branch", else_branch, "output_shapes", + output_shapes) + _result = _execute.execute(b"If", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "If", _inputs_flat, _attrs, _result) + return _result + + +def partitioned_call(args, Tout, f, config:str="", config_proto:str="", executor_type:str="", name=None): + r"""returns `f(inputs)`, where `f`'s body is placed and partitioned. + + Asynchronously executes a function, potentially across multiple devices but + within a single process. The kernel places and partitions a given function's + underlying graph, and executes each of the partitioned subgraphs as a function. + + Args: + args: A list of `Tensor` objects. A list of input tensors. + Tout: A list of `tf.DTypes`. A list of output types. + f: A function decorated with @Defun. + A function that takes 'args', a list of tensors, and returns 'output', + another list of tensors. Input and output types are specified by 'Tin' + and 'Tout'. The function body of f will be placed and partitioned across + devices, setting this op apart from the regular Call op. + config: An optional `string`. Defaults to `""`. + config_proto: An optional `string`. Defaults to `""`. + executor_type: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PartitionedCall", name, args, "Tout", Tout, "f", f, "config", + config, "config_proto", config_proto, "executor_type", executor_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return partitioned_call_eager_fallback( + args, Tout=Tout, f=f, config=config, config_proto=config_proto, + executor_type=executor_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if config is None: + config = "" + config = _execute.make_str(config, "config") + if config_proto is None: + config_proto = "" + config_proto = _execute.make_str(config_proto, "config_proto") + if executor_type is None: + executor_type = "" + executor_type = _execute.make_str(executor_type, "executor_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PartitionedCall", args=args, Tout=Tout, f=f, config=config, + config_proto=config_proto, + executor_type=executor_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), "f", + _op.get_attr("f"), "config", _op.get_attr("config"), + "config_proto", _op.get_attr("config_proto"), "executor_type", + _op.get_attr("executor_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PartitionedCall", _inputs_flat, _attrs, _result) + return _result + +PartitionedCall = tf_export("raw_ops.PartitionedCall")(_ops.to_raw_op(partitioned_call)) + + +def partitioned_call_eager_fallback(args, Tout, f, config: str, config_proto: str, executor_type: str, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if config is None: + config = "" + config = _execute.make_str(config, "config") + if config_proto is None: + config_proto = "" + config_proto = _execute.make_str(config_proto, "config_proto") + if executor_type is None: + executor_type = "" + executor_type = _execute.make_str(executor_type, "executor_type") + _attr_Tin, args = _execute.convert_to_mixed_eager_tensors(args, ctx) + _inputs_flat = list(args) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "f", f, "config", config, + "config_proto", config_proto, "executor_type", executor_type) + _result = _execute.execute(b"PartitionedCall", len(Tout), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PartitionedCall", _inputs_flat, _attrs, _result) + return _result + + +def remote_call(target: Annotated[Any, _atypes.String], args, Tout, f, name=None): + r"""Runs function `f` on a remote device indicated by `target`. + + Args: + target: A `Tensor` of type `string`. + A fully specified device name where we want to run the function. + args: A list of `Tensor` objects. A list of arguments for the function. + Tout: A list of `tf.DTypes` that has length `>= 1`. + The type list for the return values. + f: A function decorated with @Defun. The function to run remotely. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RemoteCall", name, target, args, "Tout", Tout, "f", f) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return remote_call_eager_fallback( + target, args, Tout=Tout, f=f, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'remote_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RemoteCall", target=target, args=args, Tout=Tout, f=f, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), "f", + _op.get_attr("f")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RemoteCall", _inputs_flat, _attrs, _result) + return _result + +RemoteCall = tf_export("raw_ops.RemoteCall")(_ops.to_raw_op(remote_call)) + + +def remote_call_eager_fallback(target: Annotated[Any, _atypes.String], args, Tout, f, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'remote_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _attr_Tin, args = _execute.convert_to_mixed_eager_tensors(args, ctx) + target = _ops.convert_to_tensor(target, _dtypes.string) + _inputs_flat = [target] + list(args) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "f", f) + _result = _execute.execute(b"RemoteCall", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RemoteCall", _inputs_flat, _attrs, _result) + return _result + + +def stateful_partitioned_call(args, Tout, f, config:str="", config_proto:str="", executor_type:str="", name=None): + r"""returns `f(inputs)`, where `f`'s body is placed and partitioned. + + Args: + args: A list of `Tensor` objects. A list of input tensors. + Tout: A list of `tf.DTypes`. A list of output types. + f: A function decorated with @Defun. + A function that takes 'args', a list of tensors, and returns 'output', + another list of tensors. Input and output types are specified by 'Tin' + and 'Tout'. The function body of f will be placed and partitioned across + devices, setting this op apart from the regular Call op. This op is + stateful. + config: An optional `string`. Defaults to `""`. + config_proto: An optional `string`. Defaults to `""`. + executor_type: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulPartitionedCall", name, args, "Tout", Tout, "f", f, + "config", config, "config_proto", config_proto, "executor_type", + executor_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_partitioned_call_eager_fallback( + args, Tout=Tout, f=f, config=config, config_proto=config_proto, + executor_type=executor_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateful_partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if config is None: + config = "" + config = _execute.make_str(config, "config") + if config_proto is None: + config_proto = "" + config_proto = _execute.make_str(config_proto, "config_proto") + if executor_type is None: + executor_type = "" + executor_type = _execute.make_str(executor_type, "executor_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulPartitionedCall", args=args, Tout=Tout, f=f, config=config, + config_proto=config_proto, + executor_type=executor_type, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), "f", + _op.get_attr("f"), "config", _op.get_attr("config"), + "config_proto", _op.get_attr("config_proto"), "executor_type", + _op.get_attr("executor_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulPartitionedCall", _inputs_flat, _attrs, _result) + return _result + +StatefulPartitionedCall = tf_export("raw_ops.StatefulPartitionedCall")(_ops.to_raw_op(stateful_partitioned_call)) + + +def stateful_partitioned_call_eager_fallback(args, Tout, f, config: str, config_proto: str, executor_type: str, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateful_partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if config is None: + config = "" + config = _execute.make_str(config, "config") + if config_proto is None: + config_proto = "" + config_proto = _execute.make_str(config_proto, "config_proto") + if executor_type is None: + executor_type = "" + executor_type = _execute.make_str(executor_type, "executor_type") + _attr_Tin, args = _execute.convert_to_mixed_eager_tensors(args, ctx) + _inputs_flat = list(args) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "f", f, "config", config, + "config_proto", config_proto, "executor_type", executor_type) + _result = _execute.execute(b"StatefulPartitionedCall", len(Tout), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulPartitionedCall", _inputs_flat, _attrs, _result) + return _result + + +def stateless_case(branch_index: Annotated[Any, _atypes.Int32], input, Tout, branches, output_shapes=[], name=None): + r"""An n-way switch statement which calls a single branch function. + + An n-way switch statement, implementing the following: + ``` + switch (branch_index) { + case 0: + output = branches[0](input); + break; + case 1: + output = branches[1](input); + break; + ... + case [[nbranches-1]]: + default: + output = branches[nbranches-1](input); + break; + } + ``` + + This should only be used when the none of branches has stateful ops. + + Args: + branch_index: A `Tensor` of type `int32`. + The branch selector, an int32 Tensor. + input: A list of `Tensor` objects. + A list of input tensors passed to the branch function. + Tout: A list of `tf.DTypes`. A list of output types. + branches: A list of functions decorated with @Defun that has length `>= 1`. + A list of functions each of which takes 'inputs' and returns a list of + tensors, whose types are the same as what every other branch returns. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessCase", name, branch_index, input, "Tout", Tout, + "branches", branches, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_case_eager_fallback( + branch_index, input, Tout=Tout, branches=branches, + output_shapes=output_shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateless_case' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'stateless_case' Op, not %r." % branches) + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_case' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessCase", branch_index=branch_index, input=input, Tout=Tout, + branches=branches, output_shapes=output_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), + "branches", _op.get_attr("branches"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessCase", _inputs_flat, _attrs, _result) + return _result + +StatelessCase = tf_export("raw_ops.StatelessCase")(_ops.to_raw_op(stateless_case)) + + +def stateless_case_eager_fallback(branch_index: Annotated[Any, _atypes.Int32], input, Tout, branches, output_shapes, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateless_case' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if not isinstance(branches, (list, tuple)): + raise TypeError( + "Expected list for 'branches' argument to " + "'stateless_case' Op, not %r." % branches) + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_case' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + branch_index = _ops.convert_to_tensor(branch_index, _dtypes.int32) + _inputs_flat = [branch_index] + list(input) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "branches", branches, + "output_shapes", output_shapes) + _result = _execute.execute(b"StatelessCase", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessCase", _inputs_flat, _attrs, _result) + return _result + + +TV_StatelessIf_Tcond = TypeVar("TV_StatelessIf_Tcond", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateless_if(cond: Annotated[Any, TV_StatelessIf_Tcond], input, Tout, then_branch, else_branch, output_shapes=[], name=None): + r"""output = cond ? then_branch(input) : else_branch(input) + + Args: + cond: A `Tensor`. + A Tensor. If the tensor is a scalar of non-boolean type, the + scalar is converted to a boolean according to the + following rule: if the scalar is a numerical value, non-zero means + `True` and zero means False; if the scalar is a string, non-empty + means `True` and empty means `False`. If the tensor is not a scalar, + being empty means False and being non-empty means True. + + This should only be used when the if then/else body functions do not + have stateful ops. + input: A list of `Tensor` objects. A list of input tensors. + Tout: A list of `tf.DTypes`. A list of output types. + then_branch: A function decorated with @Defun. + A function that takes 'inputs' and returns a list of tensors, whose + types are the same as what else_branch returns. + else_branch: A function decorated with @Defun. + A function that takes 'inputs' and returns a list of tensors, whose + types are the same as what then_branch returns. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessIf", name, cond, input, "Tout", Tout, "then_branch", + then_branch, "else_branch", else_branch, "output_shapes", + output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_if_eager_fallback( + cond, input, Tout=Tout, then_branch=then_branch, + else_branch=else_branch, output_shapes=output_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateless_if' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_if' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessIf", cond=cond, input=input, Tout=Tout, + then_branch=then_branch, else_branch=else_branch, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcond", _op._get_attr_type("Tcond"), "Tin", + _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), + "then_branch", _op.get_attr("then_branch"), "else_branch", + _op.get_attr("else_branch"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessIf", _inputs_flat, _attrs, _result) + return _result + +StatelessIf = tf_export("raw_ops.StatelessIf")(_ops.to_raw_op(stateless_if)) + + +def stateless_if_eager_fallback(cond: Annotated[Any, TV_StatelessIf_Tcond], input, Tout, then_branch, else_branch, output_shapes, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'stateless_if' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_if' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _attr_Tcond, (cond,) = _execute.args_to_matching_eager([cond], ctx, []) + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = [cond] + list(input) + _attrs = ("Tcond", _attr_Tcond, "Tin", _attr_Tin, "Tout", Tout, + "then_branch", then_branch, "else_branch", else_branch, "output_shapes", + output_shapes) + _result = _execute.execute(b"StatelessIf", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessIf", _inputs_flat, _attrs, _result) + return _result + + +def stateless_while(input, cond, body, output_shapes=[], parallel_iterations:int=10, name=None): + r"""output = input; While (Cond(output)) { output = Body(output) } + + Args: + input: A list of `Tensor` objects. + A list of input tensors whose types are T. + cond: A function decorated with @Defun. + A function takes 'input' and returns a tensor. If the tensor is + a scalar of non-boolean, the scalar is converted to a boolean + according to the following rule: if the scalar is a numerical + value, non-zero means True and zero means False; if the scalar is + a string, non-empty means True and empty means False. If the + tensor is not a scalar, non-emptiness means True and False + otherwise. + + This should only be used when the while condition and body functions + do not have stateful ops. + body: A function decorated with @Defun. + A function that takes a list of tensors and returns another + list of tensors. Both lists have the same types as specified + by T. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + parallel_iterations: An optional `int`. Defaults to `10`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessWhile", name, input, "cond", cond, "body", body, + "output_shapes", output_shapes, "parallel_iterations", + parallel_iterations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_while_eager_fallback( + input, cond=cond, body=body, output_shapes=output_shapes, + parallel_iterations=parallel_iterations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_while' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessWhile", input=input, cond=cond, body=body, + output_shapes=output_shapes, + parallel_iterations=parallel_iterations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T"), "cond", _op.get_attr("cond"), "body", + _op.get_attr("body"), "output_shapes", + _op.get_attr("output_shapes"), "parallel_iterations", + _op._get_attr_int("parallel_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessWhile", _inputs_flat, _attrs, _result) + return _result + +StatelessWhile = tf_export("raw_ops.StatelessWhile")(_ops.to_raw_op(stateless_while)) + + +def stateless_while_eager_fallback(input, cond, body, output_shapes, parallel_iterations: int, name, ctx): + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'stateless_while' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _attr_T, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("T", _attr_T, "cond", cond, "body", body, "output_shapes", + output_shapes, "parallel_iterations", parallel_iterations) + _result = _execute.execute(b"StatelessWhile", len(input), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessWhile", _inputs_flat, _attrs, _result) + return _result + + +def symbolic_gradient(input, Tout, f, name=None): + r"""Computes the gradient function for function f via backpropagation. + + Args: + input: A list of `Tensor` objects. a list of input tensors of size N + M; + Tout: A list of `tf.DTypes` that has length `>= 1`. + the type list for the input list. + f: A function decorated with @Defun. + The function we want to compute the gradient for. + + The function 'f' must be a numerical function which takes N inputs and + produces M outputs. Its gradient function 'g', which is computed by + this SymbolicGradient op is a function taking N + M inputs and + produces N outputs. + + I.e. if we have + (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), + then, g is + (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, + dL/dy1, dL/dy2, ..., dL/dy_M), + + where L is a scalar-value function of (x1, x2, ..., xN) (e.g., the + loss function). dL/dx_i is the partial derivative of L with respect + to x_i. + + (Needs some math expert to say the comment above better.) + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SymbolicGradient", name, input, "Tout", Tout, "f", f) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return symbolic_gradient_eager_fallback( + input, Tout=Tout, f=f, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'symbolic_gradient' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SymbolicGradient", input=input, Tout=Tout, f=f, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), "f", + _op.get_attr("f")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SymbolicGradient", _inputs_flat, _attrs, _result) + return _result + +SymbolicGradient = tf_export("raw_ops.SymbolicGradient")(_ops.to_raw_op(symbolic_gradient)) + + +def symbolic_gradient_eager_fallback(input, Tout, f, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'symbolic_gradient' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "f", f) + _result = _execute.execute(b"SymbolicGradient", len(Tout), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SymbolicGradient", _inputs_flat, _attrs, _result) + return _result + + +TV_ToBool_T = TypeVar("TV_ToBool_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def to_bool(input: Annotated[Any, TV_ToBool_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Converts a tensor to a scalar predicate. + + Converts a tensor to a scalar predicate with the following rules: + + - For 0D tensors, truthiness is determined by comparing against a "zero" + value. For numerical types it is the obvious zero. For strings it is the + empty string. + + - For >0D tensors, truthiness is determined by looking at the number of + elements. If has zero elements, then the result is false. Otherwise the + result is true. + + This matches the behavior of If and While for determining if a tensor counts + as true/false for a branch condition. + + Args: + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ToBool", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return to_bool_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ToBool", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ToBool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ToBool = tf_export("raw_ops.ToBool")(_ops.to_raw_op(to_bool)) + + +def to_bool_eager_fallback(input: Annotated[Any, TV_ToBool_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ToBool", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ToBool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def _while(input, cond, body, output_shapes=[], parallel_iterations:int=10, name=None): + r"""output = input; While (Cond(output)) { output = Body(output) } + + Args: + input: A list of `Tensor` objects. + A list of input tensors whose types are T. + cond: A function decorated with @Defun. + A function takes 'input' and returns a tensor. If the tensor is + a scalar of non-boolean, the scalar is converted to a boolean + according to the following rule: if the scalar is a numerical + value, non-zero means True and zero means False; if the scalar is + a string, non-empty means True and empty means False. If the + tensor is not a scalar, non-emptiness means True and False + otherwise. + body: A function decorated with @Defun. + A function that takes a list of tensors and returns another + list of tensors. Both lists have the same types as specified + by T. + output_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + parallel_iterations: An optional `int`. Defaults to `10`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "While", name, input, "cond", cond, "body", body, + "output_shapes", output_shapes, "parallel_iterations", + parallel_iterations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _while_eager_fallback( + input, cond=cond, body=body, output_shapes=output_shapes, + parallel_iterations=parallel_iterations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'while' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "While", input=input, cond=cond, body=body, + output_shapes=output_shapes, + parallel_iterations=parallel_iterations, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T"), "cond", _op.get_attr("cond"), "body", + _op.get_attr("body"), "output_shapes", + _op.get_attr("output_shapes"), "parallel_iterations", + _op._get_attr_int("parallel_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "While", _inputs_flat, _attrs, _result) + return _result + +While = tf_export("raw_ops.While")(_ops.to_raw_op(_while)) + + +def _while_eager_fallback(input, cond, body, output_shapes, parallel_iterations: int, name, ctx): + if output_shapes is None: + output_shapes = [] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'while' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + if parallel_iterations is None: + parallel_iterations = 10 + parallel_iterations = _execute.make_int(parallel_iterations, "parallel_iterations") + _attr_T, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("T", _attr_T, "cond", cond, "body", body, "output_shapes", + output_shapes, "parallel_iterations", parallel_iterations) + _result = _execute.execute(b"While", len(input), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "While", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_image_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_image_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb64bf090c5ffa1e176f1f00bce1b4901df9964 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_image_ops.py @@ -0,0 +1,4871 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AdjustContrast_T = TypeVar("TV_AdjustContrast_T", _atypes.Float32, _atypes.Float64, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) + +def adjust_contrast(images: Annotated[Any, TV_AdjustContrast_T], contrast_factor: Annotated[Any, _atypes.Float32], min_value: Annotated[Any, _atypes.Float32], max_value: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""Deprecated. Disallowed in GraphDef version >= 2. + + Args: + images: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`. + contrast_factor: A `Tensor` of type `float32`. + min_value: A `Tensor` of type `float32`. + max_value: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AdjustContrast", name, images, contrast_factor, min_value, + max_value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return adjust_contrast_eager_fallback( + images, contrast_factor, min_value, max_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AdjustContrast", images=images, contrast_factor=contrast_factor, + min_value=min_value, max_value=max_value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AdjustContrast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AdjustContrast = tf_export("raw_ops.AdjustContrast")(_ops.to_raw_op(adjust_contrast)) + + +def adjust_contrast_eager_fallback(images: Annotated[Any, TV_AdjustContrast_T], contrast_factor: Annotated[Any, _atypes.Float32], min_value: Annotated[Any, _atypes.Float32], max_value: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + contrast_factor = _ops.convert_to_tensor(contrast_factor, _dtypes.float32) + min_value = _ops.convert_to_tensor(min_value, _dtypes.float32) + max_value = _ops.convert_to_tensor(max_value, _dtypes.float32) + _inputs_flat = [images, contrast_factor, min_value, max_value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AdjustContrast", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AdjustContrast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AdjustContrastv2_T = TypeVar("TV_AdjustContrastv2_T", _atypes.Float32, _atypes.Half) + +def adjust_contrastv2(images: Annotated[Any, TV_AdjustContrastv2_T], contrast_factor: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, TV_AdjustContrastv2_T]: + r"""Adjust the contrast of one or more images. + + `images` is a tensor of at least 3 dimensions. The last 3 dimensions are + interpreted as `[height, width, channels]`. The other dimensions only + represent a collection of images, such as `[batch, height, width, channels].` + + Contrast is adjusted independently for each channel of each image. + + For each channel, the Op first computes the mean of the image pixels in the + channel and then adjusts each component of each pixel to + `(x - mean) * contrast_factor + mean`. + + Args: + images: A `Tensor`. Must be one of the following types: `half`, `float32`. + Images to adjust. At least 3-D. + contrast_factor: A `Tensor` of type `float32`. + A float multiplier for adjusting contrast. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AdjustContrastv2", name, images, contrast_factor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return adjust_contrastv2_eager_fallback( + images, contrast_factor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AdjustContrastv2", images=images, contrast_factor=contrast_factor, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AdjustContrastv2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AdjustContrastv2 = tf_export("raw_ops.AdjustContrastv2")(_ops.to_raw_op(adjust_contrastv2)) + + +def adjust_contrastv2_eager_fallback(images: Annotated[Any, TV_AdjustContrastv2_T], contrast_factor: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, TV_AdjustContrastv2_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + contrast_factor = _ops.convert_to_tensor(contrast_factor, _dtypes.float32) + _inputs_flat = [images, contrast_factor] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AdjustContrastv2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AdjustContrastv2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AdjustHue_T = TypeVar("TV_AdjustHue_T", _atypes.Float32, _atypes.Half) + +def adjust_hue(images: Annotated[Any, TV_AdjustHue_T], delta: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, TV_AdjustHue_T]: + r"""Adjust the hue of one or more images. + + `images` is a tensor of at least 3 dimensions. The last dimension is + interpreted as channels, and must be three. + + The input image is considered in the RGB colorspace. Conceptually, the RGB + colors are first mapped into HSV. A delta is then applied all the hue values, + and then remapped back to RGB colorspace. + + Args: + images: A `Tensor`. Must be one of the following types: `half`, `float32`. + Images to adjust. At least 3-D. + delta: A `Tensor` of type `float32`. A float delta to add to the hue. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AdjustHue", name, images, delta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return adjust_hue_eager_fallback( + images, delta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AdjustHue", images=images, delta=delta, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AdjustHue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AdjustHue = tf_export("raw_ops.AdjustHue")(_ops.to_raw_op(adjust_hue)) + + +def adjust_hue_eager_fallback(images: Annotated[Any, TV_AdjustHue_T], delta: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, TV_AdjustHue_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + delta = _ops.convert_to_tensor(delta, _dtypes.float32) + _inputs_flat = [images, delta] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AdjustHue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AdjustHue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AdjustSaturation_T = TypeVar("TV_AdjustSaturation_T", _atypes.Float32, _atypes.Half) + +def adjust_saturation(images: Annotated[Any, TV_AdjustSaturation_T], scale: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, TV_AdjustSaturation_T]: + r"""Adjust the saturation of one or more images. + + `images` is a tensor of at least 3 dimensions. The last dimension is + interpreted as channels, and must be three. + + The input image is considered in the RGB colorspace. Conceptually, the RGB + colors are first mapped into HSV. A scale is then applied all the saturation + values, and then remapped back to RGB colorspace. + + Args: + images: A `Tensor`. Must be one of the following types: `half`, `float32`. + Images to adjust. At least 3-D. + scale: A `Tensor` of type `float32`. + A float scale to add to the saturation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AdjustSaturation", name, images, scale) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return adjust_saturation_eager_fallback( + images, scale, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AdjustSaturation", images=images, scale=scale, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AdjustSaturation", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AdjustSaturation = tf_export("raw_ops.AdjustSaturation")(_ops.to_raw_op(adjust_saturation)) + + +def adjust_saturation_eager_fallback(images: Annotated[Any, TV_AdjustSaturation_T], scale: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, TV_AdjustSaturation_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + scale = _ops.convert_to_tensor(scale, _dtypes.float32) + _inputs_flat = [images, scale] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AdjustSaturation", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AdjustSaturation", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_CombinedNonMaxSuppressionOutput = collections.namedtuple( + "CombinedNonMaxSuppression", + ["nmsed_boxes", "nmsed_scores", "nmsed_classes", "valid_detections"]) + + +def combined_non_max_suppression(boxes: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size_per_class: Annotated[Any, _atypes.Int32], max_total_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, _atypes.Float32], score_threshold: Annotated[Any, _atypes.Float32], pad_per_class:bool=False, clip_boxes:bool=True, name=None): + r"""Greedily selects a subset of bounding boxes in descending order of score, + + This operation performs non_max_suppression on the inputs per batch, across + all classes. + Prunes away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Also note that + this algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is the final boxes, scores and classes tensor + returned after performing non_max_suppression. + + Args: + boxes: A `Tensor` of type `float32`. + A 4-D float tensor of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then + same boxes are used for all classes otherwise, if `q` is equal to number of + classes, class-specific boxes are used. + scores: A `Tensor` of type `float32`. + A 3-D float tensor of shape `[batch_size, num_boxes, num_classes]` + representing a single score corresponding to each box (each row of boxes). + max_output_size_per_class: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression per class + max_total_size: A `Tensor` of type `int32`. + An int32 scalar representing the maximum number of boxes retained over all + classes. Note that setting this value to a large number may result in OOM error + depending on the system workload. + iou_threshold: A `Tensor` of type `float32`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too much with respect to IOU. + score_threshold: A `Tensor` of type `float32`. + A 0-D float tensor representing the threshold for deciding when to remove + boxes based on score. + pad_per_class: An optional `bool`. Defaults to `False`. + If false, the output nmsed boxes, scores and classes + are padded/clipped to `max_total_size`. If true, the + output nmsed boxes, scores and classes are padded to be of length + `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in + which case it is clipped to `max_total_size`. Defaults to false. + clip_boxes: An optional `bool`. Defaults to `True`. + If true, assume the box coordinates are between [0, 1] and clip the output boxes + if they fall beyond [0, 1]. If false, do not do clipping and output the box + coordinates as it is. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections). + + nmsed_boxes: A `Tensor` of type `float32`. + nmsed_scores: A `Tensor` of type `float32`. + nmsed_classes: A `Tensor` of type `float32`. + valid_detections: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CombinedNonMaxSuppression", name, boxes, scores, + max_output_size_per_class, max_total_size, iou_threshold, + score_threshold, "pad_per_class", pad_per_class, "clip_boxes", + clip_boxes) + _result = _CombinedNonMaxSuppressionOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return combined_non_max_suppression_eager_fallback( + boxes, scores, max_output_size_per_class, max_total_size, + iou_threshold, score_threshold, pad_per_class=pad_per_class, + clip_boxes=clip_boxes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if pad_per_class is None: + pad_per_class = False + pad_per_class = _execute.make_bool(pad_per_class, "pad_per_class") + if clip_boxes is None: + clip_boxes = True + clip_boxes = _execute.make_bool(clip_boxes, "clip_boxes") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CombinedNonMaxSuppression", boxes=boxes, scores=scores, + max_output_size_per_class=max_output_size_per_class, + max_total_size=max_total_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_per_class=pad_per_class, + clip_boxes=clip_boxes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pad_per_class", _op._get_attr_bool("pad_per_class"), + "clip_boxes", _op._get_attr_bool("clip_boxes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CombinedNonMaxSuppression", _inputs_flat, _attrs, _result) + _result = _CombinedNonMaxSuppressionOutput._make(_result) + return _result + +CombinedNonMaxSuppression = tf_export("raw_ops.CombinedNonMaxSuppression")(_ops.to_raw_op(combined_non_max_suppression)) + + +def combined_non_max_suppression_eager_fallback(boxes: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size_per_class: Annotated[Any, _atypes.Int32], max_total_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, _atypes.Float32], score_threshold: Annotated[Any, _atypes.Float32], pad_per_class: bool, clip_boxes: bool, name, ctx): + if pad_per_class is None: + pad_per_class = False + pad_per_class = _execute.make_bool(pad_per_class, "pad_per_class") + if clip_boxes is None: + clip_boxes = True + clip_boxes = _execute.make_bool(clip_boxes, "clip_boxes") + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + scores = _ops.convert_to_tensor(scores, _dtypes.float32) + max_output_size_per_class = _ops.convert_to_tensor(max_output_size_per_class, _dtypes.int32) + max_total_size = _ops.convert_to_tensor(max_total_size, _dtypes.int32) + iou_threshold = _ops.convert_to_tensor(iou_threshold, _dtypes.float32) + score_threshold = _ops.convert_to_tensor(score_threshold, _dtypes.float32) + _inputs_flat = [boxes, scores, max_output_size_per_class, max_total_size, iou_threshold, score_threshold] + _attrs = ("pad_per_class", pad_per_class, "clip_boxes", clip_boxes) + _result = _execute.execute(b"CombinedNonMaxSuppression", 4, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CombinedNonMaxSuppression", _inputs_flat, _attrs, _result) + _result = _CombinedNonMaxSuppressionOutput._make(_result) + return _result + + +TV_CropAndResize_T = TypeVar("TV_CropAndResize_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def crop_and_resize(image: Annotated[Any, TV_CropAndResize_T], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], crop_size: Annotated[Any, _atypes.Int32], method:str="bilinear", extrapolation_value:float=0, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Extracts crops from the input image tensor and resizes them. + + Extracts crops from the input image tensor and resizes them using bilinear + sampling or nearest neighbor sampling (possibly with aspect ratio change) to a + common output size specified by `crop_size`. This is more general than the + `crop_to_bounding_box` op which extracts a fixed size slice from the input image + and does not allow resizing or aspect ratio change. + + Returns a tensor with `crops` from the input `image` at positions defined at the + bounding box locations in `boxes`. The cropped boxes are all resized (with + bilinear or nearest neighbor interpolation) to a fixed + `size = [crop_height, crop_width]`. The result is a 4-D tensor + `[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned. + In particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical + results to using `tf.image.resize_bilinear()` or + `tf.image.resize_nearest_neighbor()`(depends on the `method` argument) with + `align_corners=True`. + + Args: + image: A `Tensor`. Must be one of the following types: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `half`, `float32`, `float64`. + A 4-D tensor of shape `[batch, image_height, image_width, depth]`. + Both `image_height` and `image_width` need to be positive. + boxes: A `Tensor` of type `float32`. + A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor + specifies the coordinates of a box in the `box_ind[i]` image and is specified + in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of + `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the + `[0, 1]` interval of normalized image height is mapped to + `[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in + which case the sampled crop is an up-down flipped version of the original + image. The width dimension is treated similarly. Normalized coordinates + outside the `[0, 1]` range are allowed, in which case we use + `extrapolation_value` to extrapolate the input image values. + box_ind: A `Tensor` of type `int32`. + A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. + The value of `box_ind[i]` specifies the image that the `i`-th box refers to. + crop_size: A `Tensor` of type `int32`. + A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All + cropped image patches are resized to this size. The aspect ratio of the image + content is not preserved. Both `crop_height` and `crop_width` need to be + positive. + method: An optional `string` from: `"bilinear", "nearest"`. Defaults to `"bilinear"`. + A string specifying the sampling method for resizing. It can be either + `"bilinear"` or `"nearest"` and default to `"bilinear"`. Currently two sampling + methods are supported: Bilinear and Nearest Neighbor. + extrapolation_value: An optional `float`. Defaults to `0`. + Value used for extrapolation, when applicable. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CropAndResize", name, image, boxes, box_ind, crop_size, + "method", method, "extrapolation_value", extrapolation_value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return crop_and_resize_eager_fallback( + image, boxes, box_ind, crop_size, method=method, + extrapolation_value=extrapolation_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + if extrapolation_value is None: + extrapolation_value = 0 + extrapolation_value = _execute.make_float(extrapolation_value, "extrapolation_value") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CropAndResize", image=image, boxes=boxes, box_ind=box_ind, + crop_size=crop_size, method=method, + extrapolation_value=extrapolation_value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "method", _op.get_attr("method"), + "extrapolation_value", _op.get_attr("extrapolation_value")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CropAndResize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CropAndResize = tf_export("raw_ops.CropAndResize")(_ops.to_raw_op(crop_and_resize)) + + +def crop_and_resize_eager_fallback(image: Annotated[Any, TV_CropAndResize_T], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], crop_size: Annotated[Any, _atypes.Int32], method: str, extrapolation_value: float, name, ctx) -> Annotated[Any, _atypes.Float32]: + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + if extrapolation_value is None: + extrapolation_value = 0 + extrapolation_value = _execute.make_float(extrapolation_value, "extrapolation_value") + _attr_T, (image,) = _execute.args_to_matching_eager([image], ctx, [_dtypes.uint8, _dtypes.uint16, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + box_ind = _ops.convert_to_tensor(box_ind, _dtypes.int32) + crop_size = _ops.convert_to_tensor(crop_size, _dtypes.int32) + _inputs_flat = [image, boxes, box_ind, crop_size] + _attrs = ("T", _attr_T, "method", method, "extrapolation_value", + extrapolation_value) + _result = _execute.execute(b"CropAndResize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CropAndResize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CropAndResizeGradBoxes_T = TypeVar("TV_CropAndResizeGradBoxes_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def crop_and_resize_grad_boxes(grads: Annotated[Any, _atypes.Float32], image: Annotated[Any, TV_CropAndResizeGradBoxes_T], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], method:str="bilinear", name=None) -> Annotated[Any, _atypes.Float32]: + r"""Computes the gradient of the crop_and_resize op wrt the input boxes tensor. + + Args: + grads: A `Tensor` of type `float32`. + A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. + image: A `Tensor`. Must be one of the following types: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `half`, `float32`, `float64`. + A 4-D tensor of shape `[batch, image_height, image_width, depth]`. + Both `image_height` and `image_width` need to be positive. + boxes: A `Tensor` of type `float32`. + A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor + specifies the coordinates of a box in the `box_ind[i]` image and is specified + in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of + `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the + `[0, 1]` interval of normalized image height is mapped to + `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in + which case the sampled crop is an up-down flipped version of the original + image. The width dimension is treated similarly. Normalized coordinates + outside the `[0, 1]` range are allowed, in which case we use + `extrapolation_value` to extrapolate the input image values. + box_ind: A `Tensor` of type `int32`. + A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. + The value of `box_ind[i]` specifies the image that the `i`-th box refers to. + method: An optional `string` from: `"bilinear"`. Defaults to `"bilinear"`. + A string specifying the interpolation method. Only 'bilinear' is + supported for now. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CropAndResizeGradBoxes", name, grads, image, boxes, box_ind, + "method", method) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return crop_and_resize_grad_boxes_eager_fallback( + grads, image, boxes, box_ind, method=method, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CropAndResizeGradBoxes", grads=grads, image=image, boxes=boxes, + box_ind=box_ind, method=method, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "method", _op.get_attr("method")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CropAndResizeGradBoxes", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CropAndResizeGradBoxes = tf_export("raw_ops.CropAndResizeGradBoxes")(_ops.to_raw_op(crop_and_resize_grad_boxes)) + + +def crop_and_resize_grad_boxes_eager_fallback(grads: Annotated[Any, _atypes.Float32], image: Annotated[Any, TV_CropAndResizeGradBoxes_T], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], method: str, name, ctx) -> Annotated[Any, _atypes.Float32]: + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + _attr_T, (image,) = _execute.args_to_matching_eager([image], ctx, [_dtypes.uint8, _dtypes.uint16, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + grads = _ops.convert_to_tensor(grads, _dtypes.float32) + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + box_ind = _ops.convert_to_tensor(box_ind, _dtypes.int32) + _inputs_flat = [grads, image, boxes, box_ind] + _attrs = ("T", _attr_T, "method", method) + _result = _execute.execute(b"CropAndResizeGradBoxes", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CropAndResizeGradBoxes", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CropAndResizeGradImage_T = TypeVar("TV_CropAndResizeGradImage_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def crop_and_resize_grad_image(grads: Annotated[Any, _atypes.Float32], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], image_size: Annotated[Any, _atypes.Int32], T: TV_CropAndResizeGradImage_T, method:str="bilinear", name=None) -> Annotated[Any, TV_CropAndResizeGradImage_T]: + r"""Computes the gradient of the crop_and_resize op wrt the input image tensor. + + Args: + grads: A `Tensor` of type `float32`. + A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. + boxes: A `Tensor` of type `float32`. + A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor + specifies the coordinates of a box in the `box_ind[i]` image and is specified + in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of + `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the + `[0, 1]` interval of normalized image height is mapped to + `[0, image_height - 1] in image height coordinates. We do allow y1 > y2, in + which case the sampled crop is an up-down flipped version of the original + image. The width dimension is treated similarly. Normalized coordinates + outside the `[0, 1]` range are allowed, in which case we use + `extrapolation_value` to extrapolate the input image values. + box_ind: A `Tensor` of type `int32`. + A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. + The value of `box_ind[i]` specifies the image that the `i`-th box refers to. + image_size: A `Tensor` of type `int32`. + A 1-D tensor with value `[batch, image_height, image_width, depth]` + containing the original image size. Both `image_height` and `image_width` need + to be positive. + T: A `tf.DType` from: `tf.float32, tf.half, tf.float64`. + method: An optional `string` from: `"bilinear", "nearest"`. Defaults to `"bilinear"`. + A string specifying the interpolation method. Only 'bilinear' is + supported for now. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CropAndResizeGradImage", name, grads, boxes, box_ind, + image_size, "T", T, "method", method) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return crop_and_resize_grad_image_eager_fallback( + grads, boxes, box_ind, image_size, T=T, method=method, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CropAndResizeGradImage", grads=grads, boxes=boxes, box_ind=box_ind, + image_size=image_size, T=T, method=method, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "method", _op.get_attr("method")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CropAndResizeGradImage", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CropAndResizeGradImage = tf_export("raw_ops.CropAndResizeGradImage")(_ops.to_raw_op(crop_and_resize_grad_image)) + + +def crop_and_resize_grad_image_eager_fallback(grads: Annotated[Any, _atypes.Float32], boxes: Annotated[Any, _atypes.Float32], box_ind: Annotated[Any, _atypes.Int32], image_size: Annotated[Any, _atypes.Int32], T: TV_CropAndResizeGradImage_T, method: str, name, ctx) -> Annotated[Any, TV_CropAndResizeGradImage_T]: + T = _execute.make_type(T, "T") + if method is None: + method = "bilinear" + method = _execute.make_str(method, "method") + grads = _ops.convert_to_tensor(grads, _dtypes.float32) + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + box_ind = _ops.convert_to_tensor(box_ind, _dtypes.int32) + image_size = _ops.convert_to_tensor(image_size, _dtypes.int32) + _inputs_flat = [grads, boxes, box_ind, image_size] + _attrs = ("T", T, "method", method) + _result = _execute.execute(b"CropAndResizeGradImage", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CropAndResizeGradImage", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def decode_and_crop_jpeg(contents: Annotated[Any, _atypes.String], crop_window: Annotated[Any, _atypes.Int32], channels:int=0, ratio:int=1, fancy_upscaling:bool=True, try_recover_truncated:bool=False, acceptable_fraction:float=1, dct_method:str="", name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Decode and Crop a JPEG-encoded image to a uint8 tensor. + + The attr `channels` indicates the desired number of color channels for the + decoded image. + + Accepted values are: + + * 0: Use the number of channels in the JPEG-encoded image. + * 1: output a grayscale image. + * 3: output an RGB image. + + If needed, the JPEG-encoded image is transformed to match the requested number + of color channels. + + The attr `ratio` allows downscaling the image by an integer factor during + decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than + downscaling the image later. + + + It is equivalent to a combination of decode and crop, but much faster by only + decoding partial jpeg image. + + Args: + contents: A `Tensor` of type `string`. 0-D. The JPEG-encoded image. + crop_window: A `Tensor` of type `int32`. + 1-D. The crop window: [crop_y, crop_x, crop_height, crop_width]. + channels: An optional `int`. Defaults to `0`. + Number of color channels for the decoded image. + ratio: An optional `int`. Defaults to `1`. Downscaling ratio. + fancy_upscaling: An optional `bool`. Defaults to `True`. + If true use a slower but nicer upscaling of the + chroma planes (yuv420/422 only). + try_recover_truncated: An optional `bool`. Defaults to `False`. + If true try to recover an image from truncated input. + acceptable_fraction: An optional `float`. Defaults to `1`. + The minimum required fraction of lines before a truncated + input is accepted. + dct_method: An optional `string`. Defaults to `""`. + string specifying a hint about the algorithm used for + decompression. Defaults to "" which maps to a system-specific + default. Currently valid values are ["INTEGER_FAST", + "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal + jpeg library changes to a version that does not have that specific + option.) + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeAndCropJpeg", name, contents, crop_window, "channels", + channels, "ratio", ratio, "fancy_upscaling", fancy_upscaling, + "try_recover_truncated", try_recover_truncated, "acceptable_fraction", + acceptable_fraction, "dct_method", dct_method) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_and_crop_jpeg_eager_fallback( + contents, crop_window, channels=channels, ratio=ratio, + fancy_upscaling=fancy_upscaling, + try_recover_truncated=try_recover_truncated, + acceptable_fraction=acceptable_fraction, dct_method=dct_method, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if ratio is None: + ratio = 1 + ratio = _execute.make_int(ratio, "ratio") + if fancy_upscaling is None: + fancy_upscaling = True + fancy_upscaling = _execute.make_bool(fancy_upscaling, "fancy_upscaling") + if try_recover_truncated is None: + try_recover_truncated = False + try_recover_truncated = _execute.make_bool(try_recover_truncated, "try_recover_truncated") + if acceptable_fraction is None: + acceptable_fraction = 1 + acceptable_fraction = _execute.make_float(acceptable_fraction, "acceptable_fraction") + if dct_method is None: + dct_method = "" + dct_method = _execute.make_str(dct_method, "dct_method") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeAndCropJpeg", contents=contents, crop_window=crop_window, + channels=channels, ratio=ratio, + fancy_upscaling=fancy_upscaling, + try_recover_truncated=try_recover_truncated, + acceptable_fraction=acceptable_fraction, + dct_method=dct_method, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("channels", _op._get_attr_int("channels"), "ratio", + _op._get_attr_int("ratio"), "fancy_upscaling", + _op._get_attr_bool("fancy_upscaling"), "try_recover_truncated", + _op._get_attr_bool("try_recover_truncated"), + "acceptable_fraction", _op.get_attr("acceptable_fraction"), + "dct_method", _op.get_attr("dct_method")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeAndCropJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeAndCropJpeg = tf_export("raw_ops.DecodeAndCropJpeg")(_ops.to_raw_op(decode_and_crop_jpeg)) + + +def decode_and_crop_jpeg_eager_fallback(contents: Annotated[Any, _atypes.String], crop_window: Annotated[Any, _atypes.Int32], channels: int, ratio: int, fancy_upscaling: bool, try_recover_truncated: bool, acceptable_fraction: float, dct_method: str, name, ctx) -> Annotated[Any, _atypes.UInt8]: + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if ratio is None: + ratio = 1 + ratio = _execute.make_int(ratio, "ratio") + if fancy_upscaling is None: + fancy_upscaling = True + fancy_upscaling = _execute.make_bool(fancy_upscaling, "fancy_upscaling") + if try_recover_truncated is None: + try_recover_truncated = False + try_recover_truncated = _execute.make_bool(try_recover_truncated, "try_recover_truncated") + if acceptable_fraction is None: + acceptable_fraction = 1 + acceptable_fraction = _execute.make_float(acceptable_fraction, "acceptable_fraction") + if dct_method is None: + dct_method = "" + dct_method = _execute.make_str(dct_method, "dct_method") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + crop_window = _ops.convert_to_tensor(crop_window, _dtypes.int32) + _inputs_flat = [contents, crop_window] + _attrs = ("channels", channels, "ratio", ratio, "fancy_upscaling", + fancy_upscaling, "try_recover_truncated", try_recover_truncated, + "acceptable_fraction", acceptable_fraction, "dct_method", dct_method) + _result = _execute.execute(b"DecodeAndCropJpeg", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeAndCropJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def decode_bmp(contents: Annotated[Any, _atypes.String], channels:int=0, name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Decode the first frame of a BMP-encoded image to a uint8 tensor. + + The attr `channels` indicates the desired number of color channels for the + decoded image. + + Accepted values are: + + * 0: Use the number of channels in the BMP-encoded image. + * 3: output an RGB image. + * 4: output an RGBA image. + + Args: + contents: A `Tensor` of type `string`. 0-D. The BMP-encoded image. + channels: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeBmp", name, contents, "channels", channels) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_bmp_eager_fallback( + contents, channels=channels, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeBmp", contents=contents, channels=channels, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("channels", _op._get_attr_int("channels")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeBmp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeBmp = tf_export("raw_ops.DecodeBmp")(_ops.to_raw_op(decode_bmp)) + + +def decode_bmp_eager_fallback(contents: Annotated[Any, _atypes.String], channels: int, name, ctx) -> Annotated[Any, _atypes.UInt8]: + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("channels", channels) + _result = _execute.execute(b"DecodeBmp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeBmp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def decode_gif(contents: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Decode the frame(s) of a GIF-encoded image to a uint8 tensor. + + GIF images with frame or transparency compression are not supported. + On Linux and MacOS systems, convert animated GIFs from compressed to + uncompressed by running: + + convert $src.gif -coalesce $dst.gif + + This op also supports decoding JPEGs and PNGs, though it is cleaner to use + `tf.io.decode_image`. + + Args: + contents: A `Tensor` of type `string`. 0-D. The GIF-encoded image. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeGif", name, contents) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_gif_eager_fallback( + contents, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeGif", contents=contents, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeGif", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeGif = tf_export("raw_ops.DecodeGif")(_ops.to_raw_op(decode_gif)) + + +def decode_gif_eager_fallback(contents: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.UInt8]: + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = None + _result = _execute.execute(b"DecodeGif", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeGif", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DecodeImage_dtype = TypeVar("TV_DecodeImage_dtype", _atypes.Float32, _atypes.UInt16, _atypes.UInt8) + +def decode_image(contents: Annotated[Any, _atypes.String], channels:int=0, dtype:TV_DecodeImage_dtype=_dtypes.uint8, expand_animations:bool=True, name=None) -> Annotated[Any, TV_DecodeImage_dtype]: + r"""Function for decode_bmp, decode_gif, decode_jpeg, and decode_png. + + Detects whether an image is a BMP, GIF, JPEG, or PNG, and performs the + appropriate operation to convert the input bytes string into a Tensor of type + dtype. + + *NOTE*: decode_gif returns a 4-D array [num_frames, height, width, 3], as + opposed to decode_bmp, decode_jpeg and decode_png, which return 3-D arrays + [height, width, num_channels]. Make sure to take this into account when + constructing your graph if you are intermixing GIF files with BMP, JPEG, and/or + PNG files. Alternately, set the expand_animations argument of this function to + False, in which case the op will return 3-dimensional tensors and will truncate + animated GIF files to the first frame. + + *NOTE*: If the first frame of an animated GIF does not occupy the entire + canvas (maximum frame width x maximum frame height), then it fills the + unoccupied areas (in the first frame) with zeros (black). For frames after the + first frame that does not occupy the entire canvas, it uses the previous + frame to fill the unoccupied areas. + + Args: + contents: A `Tensor` of type `string`. 0-D. The encoded image bytes. + channels: An optional `int`. Defaults to `0`. + Number of color channels for the decoded image. + dtype: An optional `tf.DType` from: `tf.uint8, tf.uint16, tf.float32`. Defaults to `tf.uint8`. + The desired DType of the returned Tensor. + expand_animations: An optional `bool`. Defaults to `True`. + Controls the output shape of the returned op. If True, the returned op will + produce a 3-D tensor for PNG, JPEG, and BMP files; and a 4-D tensor for all + GIFs, whether animated or not. If, False, the returned op will produce a 3-D + tensor for all file types and will truncate animated GIFs to the first frame. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeImage", name, contents, "channels", channels, "dtype", + dtype, "expand_animations", expand_animations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_image_eager_fallback( + contents, channels=channels, dtype=dtype, + expand_animations=expand_animations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if dtype is None: + dtype = _dtypes.uint8 + dtype = _execute.make_type(dtype, "dtype") + if expand_animations is None: + expand_animations = True + expand_animations = _execute.make_bool(expand_animations, "expand_animations") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeImage", contents=contents, channels=channels, dtype=dtype, + expand_animations=expand_animations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("channels", _op._get_attr_int("channels"), "dtype", + _op._get_attr_type("dtype"), "expand_animations", + _op._get_attr_bool("expand_animations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeImage", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeImage = tf_export("raw_ops.DecodeImage")(_ops.to_raw_op(decode_image)) + + +def decode_image_eager_fallback(contents: Annotated[Any, _atypes.String], channels: int, dtype: TV_DecodeImage_dtype, expand_animations: bool, name, ctx) -> Annotated[Any, TV_DecodeImage_dtype]: + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if dtype is None: + dtype = _dtypes.uint8 + dtype = _execute.make_type(dtype, "dtype") + if expand_animations is None: + expand_animations = True + expand_animations = _execute.make_bool(expand_animations, "expand_animations") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("channels", channels, "dtype", dtype, "expand_animations", + expand_animations) + _result = _execute.execute(b"DecodeImage", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeImage", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def decode_jpeg(contents: Annotated[Any, _atypes.String], channels:int=0, ratio:int=1, fancy_upscaling:bool=True, try_recover_truncated:bool=False, acceptable_fraction:float=1, dct_method:str="", name=None) -> Annotated[Any, _atypes.UInt8]: + r"""Decode a JPEG-encoded image to a uint8 tensor. + + The attr `channels` indicates the desired number of color channels for the + decoded image. + + Accepted values are: + + * 0: Use the number of channels in the JPEG-encoded image. + * 1: output a grayscale image. + * 3: output an RGB image. + + If needed, the JPEG-encoded image is transformed to match the requested number + of color channels. + + The attr `ratio` allows downscaling the image by an integer factor during + decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than + downscaling the image later. + + + This op also supports decoding PNGs and non-animated GIFs since the interface is + the same, though it is cleaner to use `tf.io.decode_image`. + + Args: + contents: A `Tensor` of type `string`. 0-D. The JPEG-encoded image. + channels: An optional `int`. Defaults to `0`. + Number of color channels for the decoded image. + ratio: An optional `int`. Defaults to `1`. Downscaling ratio. + fancy_upscaling: An optional `bool`. Defaults to `True`. + If true use a slower but nicer upscaling of the + chroma planes (yuv420/422 only). + try_recover_truncated: An optional `bool`. Defaults to `False`. + If true try to recover an image from truncated input. + acceptable_fraction: An optional `float`. Defaults to `1`. + The minimum required fraction of lines before a truncated + input is accepted. + dct_method: An optional `string`. Defaults to `""`. + string specifying a hint about the algorithm used for + decompression. Defaults to "" which maps to a system-specific + default. Currently valid values are ["INTEGER_FAST", + "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal + jpeg library changes to a version that does not have that specific + option.) + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `uint8`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeJpeg", name, contents, "channels", channels, "ratio", + ratio, "fancy_upscaling", fancy_upscaling, "try_recover_truncated", + try_recover_truncated, "acceptable_fraction", acceptable_fraction, + "dct_method", dct_method) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_jpeg_eager_fallback( + contents, channels=channels, ratio=ratio, + fancy_upscaling=fancy_upscaling, + try_recover_truncated=try_recover_truncated, + acceptable_fraction=acceptable_fraction, dct_method=dct_method, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if ratio is None: + ratio = 1 + ratio = _execute.make_int(ratio, "ratio") + if fancy_upscaling is None: + fancy_upscaling = True + fancy_upscaling = _execute.make_bool(fancy_upscaling, "fancy_upscaling") + if try_recover_truncated is None: + try_recover_truncated = False + try_recover_truncated = _execute.make_bool(try_recover_truncated, "try_recover_truncated") + if acceptable_fraction is None: + acceptable_fraction = 1 + acceptable_fraction = _execute.make_float(acceptable_fraction, "acceptable_fraction") + if dct_method is None: + dct_method = "" + dct_method = _execute.make_str(dct_method, "dct_method") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeJpeg", contents=contents, channels=channels, ratio=ratio, + fancy_upscaling=fancy_upscaling, + try_recover_truncated=try_recover_truncated, + acceptable_fraction=acceptable_fraction, + dct_method=dct_method, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("channels", _op._get_attr_int("channels"), "ratio", + _op._get_attr_int("ratio"), "fancy_upscaling", + _op._get_attr_bool("fancy_upscaling"), "try_recover_truncated", + _op._get_attr_bool("try_recover_truncated"), + "acceptable_fraction", _op.get_attr("acceptable_fraction"), + "dct_method", _op.get_attr("dct_method")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeJpeg = tf_export("raw_ops.DecodeJpeg")(_ops.to_raw_op(decode_jpeg)) + + +def decode_jpeg_eager_fallback(contents: Annotated[Any, _atypes.String], channels: int, ratio: int, fancy_upscaling: bool, try_recover_truncated: bool, acceptable_fraction: float, dct_method: str, name, ctx) -> Annotated[Any, _atypes.UInt8]: + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if ratio is None: + ratio = 1 + ratio = _execute.make_int(ratio, "ratio") + if fancy_upscaling is None: + fancy_upscaling = True + fancy_upscaling = _execute.make_bool(fancy_upscaling, "fancy_upscaling") + if try_recover_truncated is None: + try_recover_truncated = False + try_recover_truncated = _execute.make_bool(try_recover_truncated, "try_recover_truncated") + if acceptable_fraction is None: + acceptable_fraction = 1 + acceptable_fraction = _execute.make_float(acceptable_fraction, "acceptable_fraction") + if dct_method is None: + dct_method = "" + dct_method = _execute.make_str(dct_method, "dct_method") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("channels", channels, "ratio", ratio, "fancy_upscaling", + fancy_upscaling, "try_recover_truncated", try_recover_truncated, + "acceptable_fraction", acceptable_fraction, "dct_method", dct_method) + _result = _execute.execute(b"DecodeJpeg", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DecodePng_dtype = TypeVar("TV_DecodePng_dtype", _atypes.UInt16, _atypes.UInt8) + +def decode_png(contents: Annotated[Any, _atypes.String], channels:int=0, dtype:TV_DecodePng_dtype=_dtypes.uint8, name=None) -> Annotated[Any, TV_DecodePng_dtype]: + r"""Decode a PNG-encoded image to a uint8 or uint16 tensor. + + The attr `channels` indicates the desired number of color channels for the + decoded image. + + Accepted values are: + + * 0: Use the number of channels in the PNG-encoded image. + * 1: output a grayscale image. + * 3: output an RGB image. + * 4: output an RGBA image. + + If needed, the PNG-encoded image is transformed to match the requested number + of color channels. + + This op also supports decoding JPEGs and non-animated GIFs since the interface + is the same, though it is cleaner to use `tf.io.decode_image`. + + Args: + contents: A `Tensor` of type `string`. 0-D. The PNG-encoded image. + channels: An optional `int`. Defaults to `0`. + Number of color channels for the decoded image. + dtype: An optional `tf.DType` from: `tf.uint8, tf.uint16`. Defaults to `tf.uint8`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodePng", name, contents, "channels", channels, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_png_eager_fallback( + contents, channels=channels, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if dtype is None: + dtype = _dtypes.uint8 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodePng", contents=contents, channels=channels, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("channels", _op._get_attr_int("channels"), "dtype", + _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodePng", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodePng = tf_export("raw_ops.DecodePng")(_ops.to_raw_op(decode_png)) + + +def decode_png_eager_fallback(contents: Annotated[Any, _atypes.String], channels: int, dtype: TV_DecodePng_dtype, name, ctx) -> Annotated[Any, TV_DecodePng_dtype]: + if channels is None: + channels = 0 + channels = _execute.make_int(channels, "channels") + if dtype is None: + dtype = _dtypes.uint8 + dtype = _execute.make_type(dtype, "dtype") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("channels", channels, "dtype", dtype) + _result = _execute.execute(b"DecodePng", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodePng", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DrawBoundingBoxes_T = TypeVar("TV_DrawBoundingBoxes_T", _atypes.Float32, _atypes.Half) + +def draw_bounding_boxes(images: Annotated[Any, TV_DrawBoundingBoxes_T], boxes: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, TV_DrawBoundingBoxes_T]: + r"""Draw bounding boxes on a batch of images. + + Outputs a copy of `images` but draws on top of the pixels zero or more bounding + boxes specified by the locations in `boxes`. The coordinates of the each + bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + height of the underlying image. + + For example, if an image is 100 x 200 pixels (height x width) and the bounding + box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of + the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates). + + Parts of the bounding box may fall outside the image. + + Args: + images: A `Tensor`. Must be one of the following types: `float32`, `half`. + 4-D with shape `[batch, height, width, depth]`. A batch of images. + boxes: A `Tensor` of type `float32`. + 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding + boxes. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DrawBoundingBoxes", name, images, boxes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return draw_bounding_boxes_eager_fallback( + images, boxes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DrawBoundingBoxes", images=images, boxes=boxes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DrawBoundingBoxes", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DrawBoundingBoxes = tf_export("raw_ops.DrawBoundingBoxes")(_ops.to_raw_op(draw_bounding_boxes)) + + +def draw_bounding_boxes_eager_fallback(images: Annotated[Any, TV_DrawBoundingBoxes_T], boxes: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, TV_DrawBoundingBoxes_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.float32, _dtypes.half, ], _dtypes.float32) + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + _inputs_flat = [images, boxes] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DrawBoundingBoxes", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DrawBoundingBoxes", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DrawBoundingBoxesV2_T = TypeVar("TV_DrawBoundingBoxesV2_T", _atypes.Float32, _atypes.Half) + +def draw_bounding_boxes_v2(images: Annotated[Any, TV_DrawBoundingBoxesV2_T], boxes: Annotated[Any, _atypes.Float32], colors: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, TV_DrawBoundingBoxesV2_T]: + r"""Draw bounding boxes on a batch of images. + + Outputs a copy of `images` but draws on top of the pixels zero or more bounding + boxes specified by the locations in `boxes`. The coordinates of the each + bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + height of the underlying image. + + For example, if an image is 100 x 200 pixels (height x width) and the bounding + box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of + the bounding box will be `(40, 10)` to `(100, 50)` (in (x,y) coordinates). + + Parts of the bounding box may fall outside the image. + + Args: + images: A `Tensor`. Must be one of the following types: `float32`, `half`. + 4-D with shape `[batch, height, width, depth]`. A batch of images. + boxes: A `Tensor` of type `float32`. + 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding + boxes. + colors: A `Tensor` of type `float32`. + 2-D. A list of RGBA colors to cycle through for the boxes. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DrawBoundingBoxesV2", name, images, boxes, colors) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return draw_bounding_boxes_v2_eager_fallback( + images, boxes, colors, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DrawBoundingBoxesV2", images=images, boxes=boxes, colors=colors, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DrawBoundingBoxesV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DrawBoundingBoxesV2 = tf_export("raw_ops.DrawBoundingBoxesV2")(_ops.to_raw_op(draw_bounding_boxes_v2)) + + +def draw_bounding_boxes_v2_eager_fallback(images: Annotated[Any, TV_DrawBoundingBoxesV2_T], boxes: Annotated[Any, _atypes.Float32], colors: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, TV_DrawBoundingBoxesV2_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.float32, _dtypes.half, ], _dtypes.float32) + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + colors = _ops.convert_to_tensor(colors, _dtypes.float32) + _inputs_flat = [images, boxes, colors] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DrawBoundingBoxesV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DrawBoundingBoxesV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def encode_jpeg(image: Annotated[Any, _atypes.UInt8], format:str="", quality:int=95, progressive:bool=False, optimize_size:bool=False, chroma_downsampling:bool=True, density_unit:str="in", x_density:int=300, y_density:int=300, xmp_metadata:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""JPEG-encode an image. + + `image` is a 3-D uint8 Tensor of shape `[height, width, channels]`. + + The attr `format` can be used to override the color format of the encoded + output. Values can be: + + * `''`: Use a default format based on the number of channels in the image. + * `grayscale`: Output a grayscale JPEG image. The `channels` dimension + of `image` must be 1. + * `rgb`: Output an RGB JPEG image. The `channels` dimension + of `image` must be 3. + + If `format` is not specified or is the empty string, a default format is picked + in function of the number of channels in `image`: + + * 1: Output a grayscale image. + * 3: Output an RGB image. + + Args: + image: A `Tensor` of type `uint8`. + 3-D with shape `[height, width, channels]`. + format: An optional `string` from: `"", "grayscale", "rgb"`. Defaults to `""`. + Per pixel image format. + quality: An optional `int`. Defaults to `95`. + Quality of the compression from 0 to 100 (higher is better and slower). + progressive: An optional `bool`. Defaults to `False`. + If True, create a JPEG that loads progressively (coarse to fine). + optimize_size: An optional `bool`. Defaults to `False`. + If True, spend CPU/RAM to reduce size with no quality change. + chroma_downsampling: An optional `bool`. Defaults to `True`. + See http://en.wikipedia.org/wiki/Chroma_subsampling. + density_unit: An optional `string` from: `"in", "cm"`. Defaults to `"in"`. + Unit used to specify `x_density` and `y_density`: + pixels per inch (`'in'`) or centimeter (`'cm'`). + x_density: An optional `int`. Defaults to `300`. + Horizontal pixels per density unit. + y_density: An optional `int`. Defaults to `300`. + Vertical pixels per density unit. + xmp_metadata: An optional `string`. Defaults to `""`. + If not empty, embed this XMP metadata in the image header. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodeJpeg", name, image, "format", format, "quality", quality, + "progressive", progressive, "optimize_size", optimize_size, + "chroma_downsampling", chroma_downsampling, "density_unit", + density_unit, "x_density", x_density, "y_density", y_density, + "xmp_metadata", xmp_metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return encode_jpeg_eager_fallback( + image, format=format, quality=quality, progressive=progressive, + optimize_size=optimize_size, + chroma_downsampling=chroma_downsampling, density_unit=density_unit, + x_density=x_density, y_density=y_density, xmp_metadata=xmp_metadata, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if format is None: + format = "" + format = _execute.make_str(format, "format") + if quality is None: + quality = 95 + quality = _execute.make_int(quality, "quality") + if progressive is None: + progressive = False + progressive = _execute.make_bool(progressive, "progressive") + if optimize_size is None: + optimize_size = False + optimize_size = _execute.make_bool(optimize_size, "optimize_size") + if chroma_downsampling is None: + chroma_downsampling = True + chroma_downsampling = _execute.make_bool(chroma_downsampling, "chroma_downsampling") + if density_unit is None: + density_unit = "in" + density_unit = _execute.make_str(density_unit, "density_unit") + if x_density is None: + x_density = 300 + x_density = _execute.make_int(x_density, "x_density") + if y_density is None: + y_density = 300 + y_density = _execute.make_int(y_density, "y_density") + if xmp_metadata is None: + xmp_metadata = "" + xmp_metadata = _execute.make_str(xmp_metadata, "xmp_metadata") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodeJpeg", image=image, format=format, quality=quality, + progressive=progressive, optimize_size=optimize_size, + chroma_downsampling=chroma_downsampling, + density_unit=density_unit, x_density=x_density, + y_density=y_density, xmp_metadata=xmp_metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("format", _op.get_attr("format"), "quality", + _op._get_attr_int("quality"), "progressive", + _op._get_attr_bool("progressive"), "optimize_size", + _op._get_attr_bool("optimize_size"), "chroma_downsampling", + _op._get_attr_bool("chroma_downsampling"), "density_unit", + _op.get_attr("density_unit"), "x_density", + _op._get_attr_int("x_density"), "y_density", + _op._get_attr_int("y_density"), "xmp_metadata", + _op.get_attr("xmp_metadata")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodeJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodeJpeg = tf_export("raw_ops.EncodeJpeg")(_ops.to_raw_op(encode_jpeg)) + + +def encode_jpeg_eager_fallback(image: Annotated[Any, _atypes.UInt8], format: str, quality: int, progressive: bool, optimize_size: bool, chroma_downsampling: bool, density_unit: str, x_density: int, y_density: int, xmp_metadata: str, name, ctx) -> Annotated[Any, _atypes.String]: + if format is None: + format = "" + format = _execute.make_str(format, "format") + if quality is None: + quality = 95 + quality = _execute.make_int(quality, "quality") + if progressive is None: + progressive = False + progressive = _execute.make_bool(progressive, "progressive") + if optimize_size is None: + optimize_size = False + optimize_size = _execute.make_bool(optimize_size, "optimize_size") + if chroma_downsampling is None: + chroma_downsampling = True + chroma_downsampling = _execute.make_bool(chroma_downsampling, "chroma_downsampling") + if density_unit is None: + density_unit = "in" + density_unit = _execute.make_str(density_unit, "density_unit") + if x_density is None: + x_density = 300 + x_density = _execute.make_int(x_density, "x_density") + if y_density is None: + y_density = 300 + y_density = _execute.make_int(y_density, "y_density") + if xmp_metadata is None: + xmp_metadata = "" + xmp_metadata = _execute.make_str(xmp_metadata, "xmp_metadata") + image = _ops.convert_to_tensor(image, _dtypes.uint8) + _inputs_flat = [image] + _attrs = ("format", format, "quality", quality, "progressive", progressive, + "optimize_size", optimize_size, "chroma_downsampling", chroma_downsampling, + "density_unit", density_unit, "x_density", x_density, "y_density", + y_density, "xmp_metadata", xmp_metadata) + _result = _execute.execute(b"EncodeJpeg", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodeJpeg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def encode_jpeg_variable_quality(images: Annotated[Any, _atypes.UInt8], quality: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.String]: + r"""JPEG encode input image with provided compression quality. + + `image` is a 3-D uint8 Tensor of shape `[height, width, channels]`. + `quality` is an int32 jpeg compression quality value between 0 and 100. + + Args: + images: A `Tensor` of type `uint8`. Images to adjust. At least 3-D. + quality: A `Tensor` of type `int32`. An int quality to encode to. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodeJpegVariableQuality", name, images, quality) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return encode_jpeg_variable_quality_eager_fallback( + images, quality, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodeJpegVariableQuality", images=images, quality=quality, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodeJpegVariableQuality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodeJpegVariableQuality = tf_export("raw_ops.EncodeJpegVariableQuality")(_ops.to_raw_op(encode_jpeg_variable_quality)) + + +def encode_jpeg_variable_quality_eager_fallback(images: Annotated[Any, _atypes.UInt8], quality: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.String]: + images = _ops.convert_to_tensor(images, _dtypes.uint8) + quality = _ops.convert_to_tensor(quality, _dtypes.int32) + _inputs_flat = [images, quality] + _attrs = None + _result = _execute.execute(b"EncodeJpegVariableQuality", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodeJpegVariableQuality", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_EncodePng_T = TypeVar("TV_EncodePng_T", _atypes.UInt16, _atypes.UInt8) + +def encode_png(image: Annotated[Any, TV_EncodePng_T], compression:int=-1, name=None) -> Annotated[Any, _atypes.String]: + r"""PNG-encode an image. + + `image` is a 3-D uint8 or uint16 Tensor of shape `[height, width, channels]` + where `channels` is: + + * 1: for grayscale. + * 2: for grayscale + alpha. + * 3: for RGB. + * 4: for RGBA. + + The ZLIB compression level, `compression`, can be -1 for the PNG-encoder + default or a value from 0 to 9. 9 is the highest compression level, generating + the smallest output, but is slower. + + Args: + image: A `Tensor`. Must be one of the following types: `uint8`, `uint16`. + 3-D with shape `[height, width, channels]`. + compression: An optional `int`. Defaults to `-1`. Compression level. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodePng", name, image, "compression", compression) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return encode_png_eager_fallback( + image, compression=compression, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compression is None: + compression = -1 + compression = _execute.make_int(compression, "compression") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodePng", image=image, compression=compression, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compression", _op._get_attr_int("compression"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodePng", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodePng = tf_export("raw_ops.EncodePng")(_ops.to_raw_op(encode_png)) + + +def encode_png_eager_fallback(image: Annotated[Any, TV_EncodePng_T], compression: int, name, ctx) -> Annotated[Any, _atypes.String]: + if compression is None: + compression = -1 + compression = _execute.make_int(compression, "compression") + _attr_T, (image,) = _execute.args_to_matching_eager([image], ctx, [_dtypes.uint8, _dtypes.uint16, ], _dtypes.uint8) + _inputs_flat = [image] + _attrs = ("compression", compression, "T", _attr_T) + _result = _execute.execute(b"EncodePng", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodePng", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def extract_glimpse(input: Annotated[Any, _atypes.Float32], size: Annotated[Any, _atypes.Int32], offsets: Annotated[Any, _atypes.Float32], centered:bool=True, normalized:bool=True, uniform_noise:bool=True, noise:str="uniform", name=None) -> Annotated[Any, _atypes.Float32]: + r"""Extracts a glimpse from the input tensor. + + Returns a set of windows called glimpses extracted at location + `offsets` from the input tensor. If the windows only partially + overlaps the inputs, the non overlapping areas will be filled with + random noise. + + The result is a 4-D tensor of shape `[batch_size, glimpse_height, + glimpse_width, channels]`. The channels and batch dimensions are the + same as that of the input tensor. The height and width of the output + windows are specified in the `size` parameter. + + The argument `normalized` and `centered` controls how the windows are built: + + * If the coordinates are normalized but not centered, 0.0 and 1.0 + correspond to the minimum and maximum of each height and width + dimension. + * If the coordinates are both normalized and centered, they range from + -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper + left corner, the lower right corner is located at (1.0, 1.0) and the + center is at (0, 0). + * If the coordinates are not normalized they are interpreted as + numbers of pixels. + + Args: + input: A `Tensor` of type `float32`. + A 4-D float tensor of shape `[batch_size, height, width, channels]`. + size: A `Tensor` of type `int32`. + A 1-D tensor of 2 elements containing the size of the glimpses + to extract. The glimpse height must be specified first, following + by the glimpse width. + offsets: A `Tensor` of type `float32`. + A 2-D integer tensor of shape `[batch_size, 2]` containing + the y, x locations of the center of each window. + centered: An optional `bool`. Defaults to `True`. + indicates if the offset coordinates are centered relative to + the image, in which case the (0, 0) offset is relative to the center + of the input images. If false, the (0,0) offset corresponds to the + upper left corner of the input images. + normalized: An optional `bool`. Defaults to `True`. + indicates if the offset coordinates are normalized. + uniform_noise: An optional `bool`. Defaults to `True`. + indicates if the noise should be generated using a + uniform distribution or a Gaussian distribution. + noise: An optional `string`. Defaults to `"uniform"`. + indicates if the noise should `uniform`, `gaussian`, or + `zero`. The default is `uniform` which means the noise type + will be decided by `uniform_noise`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExtractGlimpse", name, input, size, offsets, "centered", + centered, "normalized", normalized, "uniform_noise", uniform_noise, + "noise", noise) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return extract_glimpse_eager_fallback( + input, size, offsets, centered=centered, normalized=normalized, + uniform_noise=uniform_noise, noise=noise, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if centered is None: + centered = True + centered = _execute.make_bool(centered, "centered") + if normalized is None: + normalized = True + normalized = _execute.make_bool(normalized, "normalized") + if uniform_noise is None: + uniform_noise = True + uniform_noise = _execute.make_bool(uniform_noise, "uniform_noise") + if noise is None: + noise = "uniform" + noise = _execute.make_str(noise, "noise") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExtractGlimpse", input=input, size=size, offsets=offsets, + centered=centered, normalized=normalized, + uniform_noise=uniform_noise, noise=noise, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("centered", _op._get_attr_bool("centered"), "normalized", + _op._get_attr_bool("normalized"), "uniform_noise", + _op._get_attr_bool("uniform_noise"), "noise", + _op.get_attr("noise")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExtractGlimpse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExtractGlimpse = tf_export("raw_ops.ExtractGlimpse")(_ops.to_raw_op(extract_glimpse)) + + +def extract_glimpse_eager_fallback(input: Annotated[Any, _atypes.Float32], size: Annotated[Any, _atypes.Int32], offsets: Annotated[Any, _atypes.Float32], centered: bool, normalized: bool, uniform_noise: bool, noise: str, name, ctx) -> Annotated[Any, _atypes.Float32]: + if centered is None: + centered = True + centered = _execute.make_bool(centered, "centered") + if normalized is None: + normalized = True + normalized = _execute.make_bool(normalized, "normalized") + if uniform_noise is None: + uniform_noise = True + uniform_noise = _execute.make_bool(uniform_noise, "uniform_noise") + if noise is None: + noise = "uniform" + noise = _execute.make_str(noise, "noise") + input = _ops.convert_to_tensor(input, _dtypes.float32) + size = _ops.convert_to_tensor(size, _dtypes.int32) + offsets = _ops.convert_to_tensor(offsets, _dtypes.float32) + _inputs_flat = [input, size, offsets] + _attrs = ("centered", centered, "normalized", normalized, "uniform_noise", + uniform_noise, "noise", noise) + _result = _execute.execute(b"ExtractGlimpse", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExtractGlimpse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def extract_glimpse_v2(input: Annotated[Any, _atypes.Float32], size: Annotated[Any, _atypes.Int32], offsets: Annotated[Any, _atypes.Float32], centered:bool=True, normalized:bool=True, uniform_noise:bool=True, noise:str="uniform", name=None) -> Annotated[Any, _atypes.Float32]: + r"""Extracts a glimpse from the input tensor. + + Returns a set of windows called glimpses extracted at location + `offsets` from the input tensor. If the windows only partially + overlaps the inputs, the non overlapping areas will be filled with + random noise. + + The result is a 4-D tensor of shape `[batch_size, glimpse_height, + glimpse_width, channels]`. The channels and batch dimensions are the + same as that of the input tensor. The height and width of the output + windows are specified in the `size` parameter. + + The argument `normalized` and `centered` controls how the windows are built: + + * If the coordinates are normalized but not centered, 0.0 and 1.0 + correspond to the minimum and maximum of each height and width + dimension. + * If the coordinates are both normalized and centered, they range from + -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper + left corner, the lower right corner is located at (1.0, 1.0) and the + center is at (0, 0). + * If the coordinates are not normalized they are interpreted as + numbers of pixels. + + Args: + input: A `Tensor` of type `float32`. + A 4-D float tensor of shape `[batch_size, height, width, channels]`. + size: A `Tensor` of type `int32`. + A 1-D tensor of 2 elements containing the size of the glimpses + to extract. The glimpse height must be specified first, following + by the glimpse width. + offsets: A `Tensor` of type `float32`. + A 2-D integer tensor of shape `[batch_size, 2]` containing + the y, x locations of the center of each window. + centered: An optional `bool`. Defaults to `True`. + indicates if the offset coordinates are centered relative to + the image, in which case the (0, 0) offset is relative to the center + of the input images. If false, the (0,0) offset corresponds to the + upper left corner of the input images. + normalized: An optional `bool`. Defaults to `True`. + indicates if the offset coordinates are normalized. + uniform_noise: An optional `bool`. Defaults to `True`. + indicates if the noise should be generated using a + uniform distribution or a Gaussian distribution. + noise: An optional `string`. Defaults to `"uniform"`. + indicates if the noise should `uniform`, `gaussian`, or + `zero`. The default is `uniform` which means the noise type + will be decided by `uniform_noise`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExtractGlimpseV2", name, input, size, offsets, "centered", + centered, "normalized", normalized, "uniform_noise", uniform_noise, + "noise", noise) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return extract_glimpse_v2_eager_fallback( + input, size, offsets, centered=centered, normalized=normalized, + uniform_noise=uniform_noise, noise=noise, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if centered is None: + centered = True + centered = _execute.make_bool(centered, "centered") + if normalized is None: + normalized = True + normalized = _execute.make_bool(normalized, "normalized") + if uniform_noise is None: + uniform_noise = True + uniform_noise = _execute.make_bool(uniform_noise, "uniform_noise") + if noise is None: + noise = "uniform" + noise = _execute.make_str(noise, "noise") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExtractGlimpseV2", input=input, size=size, offsets=offsets, + centered=centered, normalized=normalized, + uniform_noise=uniform_noise, noise=noise, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("centered", _op._get_attr_bool("centered"), "normalized", + _op._get_attr_bool("normalized"), "uniform_noise", + _op._get_attr_bool("uniform_noise"), "noise", + _op.get_attr("noise")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExtractGlimpseV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExtractGlimpseV2 = tf_export("raw_ops.ExtractGlimpseV2")(_ops.to_raw_op(extract_glimpse_v2)) + + +def extract_glimpse_v2_eager_fallback(input: Annotated[Any, _atypes.Float32], size: Annotated[Any, _atypes.Int32], offsets: Annotated[Any, _atypes.Float32], centered: bool, normalized: bool, uniform_noise: bool, noise: str, name, ctx) -> Annotated[Any, _atypes.Float32]: + if centered is None: + centered = True + centered = _execute.make_bool(centered, "centered") + if normalized is None: + normalized = True + normalized = _execute.make_bool(normalized, "normalized") + if uniform_noise is None: + uniform_noise = True + uniform_noise = _execute.make_bool(uniform_noise, "uniform_noise") + if noise is None: + noise = "uniform" + noise = _execute.make_str(noise, "noise") + input = _ops.convert_to_tensor(input, _dtypes.float32) + size = _ops.convert_to_tensor(size, _dtypes.int32) + offsets = _ops.convert_to_tensor(offsets, _dtypes.float32) + _inputs_flat = [input, size, offsets] + _attrs = ("centered", centered, "normalized", normalized, "uniform_noise", + uniform_noise, "noise", noise) + _result = _execute.execute(b"ExtractGlimpseV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExtractGlimpseV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ExtractJpegShape_output_type = TypeVar("TV_ExtractJpegShape_output_type", _atypes.Int32, _atypes.Int64) + +def extract_jpeg_shape(contents: Annotated[Any, _atypes.String], output_type:TV_ExtractJpegShape_output_type=_dtypes.int32, name=None) -> Annotated[Any, TV_ExtractJpegShape_output_type]: + r"""Extract the shape information of a JPEG-encoded image. + + This op only parses the image header, so it is much faster than DecodeJpeg. + + Args: + contents: A `Tensor` of type `string`. 0-D. The JPEG-encoded image. + output_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + (Optional) The output type of the operation (int32 or int64). + Defaults to int32. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ExtractJpegShape", name, contents, "output_type", output_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return extract_jpeg_shape_eager_fallback( + contents, output_type=output_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_type is None: + output_type = _dtypes.int32 + output_type = _execute.make_type(output_type, "output_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ExtractJpegShape", contents=contents, output_type=output_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_type", _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ExtractJpegShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ExtractJpegShape = tf_export("raw_ops.ExtractJpegShape")(_ops.to_raw_op(extract_jpeg_shape)) + + +def extract_jpeg_shape_eager_fallback(contents: Annotated[Any, _atypes.String], output_type: TV_ExtractJpegShape_output_type, name, ctx) -> Annotated[Any, TV_ExtractJpegShape_output_type]: + if output_type is None: + output_type = _dtypes.int32 + output_type = _execute.make_type(output_type, "output_type") + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [contents] + _attrs = ("output_type", output_type) + _result = _execute.execute(b"ExtractJpegShape", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ExtractJpegShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_GenerateBoundingBoxProposalsOutput = collections.namedtuple( + "GenerateBoundingBoxProposals", + ["rois", "roi_probabilities"]) + + +def generate_bounding_box_proposals(scores: Annotated[Any, _atypes.Float32], bbox_deltas: Annotated[Any, _atypes.Float32], image_info: Annotated[Any, _atypes.Float32], anchors: Annotated[Any, _atypes.Float32], nms_threshold: Annotated[Any, _atypes.Float32], pre_nms_topn: Annotated[Any, _atypes.Int32], min_size: Annotated[Any, _atypes.Float32], post_nms_topn:int=300, name=None): + r"""This op produces Region of Interests from given bounding boxes(bbox_deltas) encoded wrt anchors according to eq.2 in arXiv:1506.01497 + + The op selects top `pre_nms_topn` scoring boxes, decodes them with respect to anchors, + applies non-maximal suppression on overlapping boxes with higher than + `nms_threshold` intersection-over-union (iou) value, discarding boxes where shorter + side is less than `min_size`. + Inputs: + `scores`: A 4D tensor of shape [Batch, Height, Width, Num Anchors] containing the scores per anchor at given position + `bbox_deltas`: is a tensor of shape [Batch, Height, Width, 4 x Num Anchors] boxes encoded to each anchor + `anchors`: A 1D tensor of shape [4 x Num Anchors], representing the anchors. + Outputs: + `rois`: output RoIs, a 3D tensor of shape [Batch, post_nms_topn, 4], padded by 0 if less than post_nms_topn candidates found. + `roi_probabilities`: probability scores of each roi in 'rois', a 2D tensor of shape [Batch,post_nms_topn], padded with 0 if needed, sorted by scores. + + Args: + scores: A `Tensor` of type `float32`. + A 4-D float tensor of shape `[num_images, height, width, num_achors]` containing scores of the boxes for given anchors, can be unsorted. + bbox_deltas: A `Tensor` of type `float32`. + A 4-D float tensor of shape `[num_images, height, width, 4 x num_anchors]`. encoding boxes with respec to each anchor. + Coordinates are given in the form [dy, dx, dh, dw]. + image_info: A `Tensor` of type `float32`. + A 2-D float tensor of shape `[num_images, 5]` containing image information Height, Width, Scale. + anchors: A `Tensor` of type `float32`. + A 2-D float tensor of shape `[num_anchors, 4]` describing the anchor boxes. Boxes are formatted in the form [y1, x1, y2, x2]. + nms_threshold: A `Tensor` of type `float32`. + A scalar float tensor for non-maximal-suppression threshold. + pre_nms_topn: A `Tensor` of type `int32`. + A scalar int tensor for the number of top scoring boxes to be used as input. + min_size: A `Tensor` of type `float32`. + A scalar float tensor. Any box that has a smaller size than min_size will be discarded. + post_nms_topn: An optional `int`. Defaults to `300`. + An integer. Maximum number of rois in the output. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (rois, roi_probabilities). + + rois: A `Tensor` of type `float32`. + roi_probabilities: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GenerateBoundingBoxProposals", name, scores, bbox_deltas, + image_info, anchors, nms_threshold, pre_nms_topn, min_size, + "post_nms_topn", post_nms_topn) + _result = _GenerateBoundingBoxProposalsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return generate_bounding_box_proposals_eager_fallback( + scores, bbox_deltas, image_info, anchors, nms_threshold, + pre_nms_topn, min_size, post_nms_topn=post_nms_topn, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if post_nms_topn is None: + post_nms_topn = 300 + post_nms_topn = _execute.make_int(post_nms_topn, "post_nms_topn") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GenerateBoundingBoxProposals", scores=scores, + bbox_deltas=bbox_deltas, + image_info=image_info, + anchors=anchors, + nms_threshold=nms_threshold, + pre_nms_topn=pre_nms_topn, + min_size=min_size, + post_nms_topn=post_nms_topn, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("post_nms_topn", _op._get_attr_int("post_nms_topn")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GenerateBoundingBoxProposals", _inputs_flat, _attrs, _result) + _result = _GenerateBoundingBoxProposalsOutput._make(_result) + return _result + +GenerateBoundingBoxProposals = tf_export("raw_ops.GenerateBoundingBoxProposals")(_ops.to_raw_op(generate_bounding_box_proposals)) + + +def generate_bounding_box_proposals_eager_fallback(scores: Annotated[Any, _atypes.Float32], bbox_deltas: Annotated[Any, _atypes.Float32], image_info: Annotated[Any, _atypes.Float32], anchors: Annotated[Any, _atypes.Float32], nms_threshold: Annotated[Any, _atypes.Float32], pre_nms_topn: Annotated[Any, _atypes.Int32], min_size: Annotated[Any, _atypes.Float32], post_nms_topn: int, name, ctx): + if post_nms_topn is None: + post_nms_topn = 300 + post_nms_topn = _execute.make_int(post_nms_topn, "post_nms_topn") + scores = _ops.convert_to_tensor(scores, _dtypes.float32) + bbox_deltas = _ops.convert_to_tensor(bbox_deltas, _dtypes.float32) + image_info = _ops.convert_to_tensor(image_info, _dtypes.float32) + anchors = _ops.convert_to_tensor(anchors, _dtypes.float32) + nms_threshold = _ops.convert_to_tensor(nms_threshold, _dtypes.float32) + pre_nms_topn = _ops.convert_to_tensor(pre_nms_topn, _dtypes.int32) + min_size = _ops.convert_to_tensor(min_size, _dtypes.float32) + _inputs_flat = [scores, bbox_deltas, image_info, anchors, nms_threshold, pre_nms_topn, min_size] + _attrs = ("post_nms_topn", post_nms_topn) + _result = _execute.execute(b"GenerateBoundingBoxProposals", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GenerateBoundingBoxProposals", _inputs_flat, _attrs, _result) + _result = _GenerateBoundingBoxProposalsOutput._make(_result) + return _result + + +TV_HSVToRGB_T = TypeVar("TV_HSVToRGB_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('image.hsv_to_rgb') +def hsv_to_rgb(images: Annotated[Any, TV_HSVToRGB_T], name=None) -> Annotated[Any, TV_HSVToRGB_T]: + r"""Convert one or more images from HSV to RGB. + + Outputs a tensor of the same shape as the `images` tensor, containing the RGB + value of the pixels. The output is only well defined if the value in `images` + are in `[0,1]`. + + See `rgb_to_hsv` for a description of the HSV encoding. + + Args: + images: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 1-D or higher rank. HSV data to convert. Last dimension must be size 3. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "HSVToRGB", name, images) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_hsv_to_rgb( + (images, name,), None) + if _result is not NotImplemented: + return _result + return hsv_to_rgb_eager_fallback( + images, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + hsv_to_rgb, (), dict(images=images, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_hsv_to_rgb( + (images, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "HSVToRGB", images=images, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + hsv_to_rgb, (), dict(images=images, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "HSVToRGB", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +HSVToRGB = tf_export("raw_ops.HSVToRGB")(_ops.to_raw_op(hsv_to_rgb)) +_dispatcher_for_hsv_to_rgb = hsv_to_rgb._tf_type_based_dispatcher.Dispatch + + +def hsv_to_rgb_eager_fallback(images: Annotated[Any, TV_HSVToRGB_T], name, ctx) -> Annotated[Any, TV_HSVToRGB_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ], _dtypes.float32) + _inputs_flat = [images] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"HSVToRGB", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "HSVToRGB", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ImageProjectiveTransformV2_dtype = TypeVar("TV_ImageProjectiveTransformV2_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64, _atypes.UInt8) + +def image_projective_transform_v2(images: Annotated[Any, TV_ImageProjectiveTransformV2_dtype], transforms: Annotated[Any, _atypes.Float32], output_shape: Annotated[Any, _atypes.Int32], interpolation: str, fill_mode:str="CONSTANT", name=None) -> Annotated[Any, TV_ImageProjectiveTransformV2_dtype]: + r"""Applies the given transform to each of the images. + + If one row of `transforms` is `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps + the *output* point `(x, y)` to a transformed *input* point + `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where + `k = c0 x + c1 y + 1`. If the transformed point lays outside of the input + image, the output pixel is set to 0. + + Args: + images: A `Tensor`. Must be one of the following types: `uint8`, `int32`, `int64`, `half`, `float32`, `float64`. + 4-D with shape `[batch, height, width, channels]`. + transforms: A `Tensor` of type `float32`. + 2-D Tensor, `[batch, 8]` or `[1, 8]` matrix, where each row corresponds to a 3 x 3 + projective transformation matrix, with the last entry assumed to be 1. If there + is one row, the same transformation will be applied to all images. + output_shape: A `Tensor` of type `int32`. + 1-D Tensor [new_height, new_width]. + interpolation: A `string`. Interpolation method, "NEAREST" or "BILINEAR". + fill_mode: An optional `string`. Defaults to `"CONSTANT"`. + Fill mode, "REFLECT", "WRAP", or "CONSTANT". + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ImageProjectiveTransformV2", name, images, transforms, + output_shape, "interpolation", interpolation, "fill_mode", fill_mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return image_projective_transform_v2_eager_fallback( + images, transforms, output_shape, interpolation=interpolation, + fill_mode=fill_mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + interpolation = _execute.make_str(interpolation, "interpolation") + if fill_mode is None: + fill_mode = "CONSTANT" + fill_mode = _execute.make_str(fill_mode, "fill_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ImageProjectiveTransformV2", images=images, transforms=transforms, + output_shape=output_shape, + interpolation=interpolation, + fill_mode=fill_mode, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "interpolation", + _op.get_attr("interpolation"), "fill_mode", + _op.get_attr("fill_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ImageProjectiveTransformV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ImageProjectiveTransformV2 = tf_export("raw_ops.ImageProjectiveTransformV2")(_ops.to_raw_op(image_projective_transform_v2)) + + +def image_projective_transform_v2_eager_fallback(images: Annotated[Any, TV_ImageProjectiveTransformV2_dtype], transforms: Annotated[Any, _atypes.Float32], output_shape: Annotated[Any, _atypes.Int32], interpolation: str, fill_mode: str, name, ctx) -> Annotated[Any, TV_ImageProjectiveTransformV2_dtype]: + interpolation = _execute.make_str(interpolation, "interpolation") + if fill_mode is None: + fill_mode = "CONSTANT" + fill_mode = _execute.make_str(fill_mode, "fill_mode") + _attr_dtype, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.uint8, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + transforms = _ops.convert_to_tensor(transforms, _dtypes.float32) + output_shape = _ops.convert_to_tensor(output_shape, _dtypes.int32) + _inputs_flat = [images, transforms, output_shape] + _attrs = ("dtype", _attr_dtype, "interpolation", interpolation, "fill_mode", + fill_mode) + _result = _execute.execute(b"ImageProjectiveTransformV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ImageProjectiveTransformV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ImageProjectiveTransformV3_dtype = TypeVar("TV_ImageProjectiveTransformV3_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64, _atypes.UInt8) + +def image_projective_transform_v3(images: Annotated[Any, TV_ImageProjectiveTransformV3_dtype], transforms: Annotated[Any, _atypes.Float32], output_shape: Annotated[Any, _atypes.Int32], fill_value: Annotated[Any, _atypes.Float32], interpolation: str, fill_mode:str="CONSTANT", name=None) -> Annotated[Any, TV_ImageProjectiveTransformV3_dtype]: + r"""Applies the given transform to each of the images. + + If one row of `transforms` is `[a0, a1, a2, b0, b1, b2, c0, c1]`, then it maps + the *output* point `(x, y)` to a transformed *input* point + `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where + `k = c0 x + c1 y + 1`. If the transformed point lays outside of the input + image, the output pixel is set to fill_value. + + Args: + images: A `Tensor`. Must be one of the following types: `uint8`, `int32`, `int64`, `half`, `float32`, `float64`. + 4-D with shape `[batch, height, width, channels]`. + transforms: A `Tensor` of type `float32`. + 2-D Tensor, `[batch, 8]` or `[1, 8]` matrix, where each row corresponds to a 3 x 3 + projective transformation matrix, with the last entry assumed to be 1. If there + is one row, the same transformation will be applied to all images. + output_shape: A `Tensor` of type `int32`. + 1-D Tensor [new_height, new_width]. + fill_value: A `Tensor` of type `float32`. + float, the value to be filled when fill_mode is constant". + interpolation: A `string`. Interpolation method, "NEAREST" or "BILINEAR". + fill_mode: An optional `string`. Defaults to `"CONSTANT"`. + Fill mode, "REFLECT", "WRAP", "CONSTANT", or "NEAREST". + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ImageProjectiveTransformV3", name, images, transforms, + output_shape, fill_value, "interpolation", interpolation, "fill_mode", + fill_mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return image_projective_transform_v3_eager_fallback( + images, transforms, output_shape, fill_value, + interpolation=interpolation, fill_mode=fill_mode, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + interpolation = _execute.make_str(interpolation, "interpolation") + if fill_mode is None: + fill_mode = "CONSTANT" + fill_mode = _execute.make_str(fill_mode, "fill_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ImageProjectiveTransformV3", images=images, transforms=transforms, + output_shape=output_shape, + fill_value=fill_value, + interpolation=interpolation, + fill_mode=fill_mode, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "interpolation", + _op.get_attr("interpolation"), "fill_mode", + _op.get_attr("fill_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ImageProjectiveTransformV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ImageProjectiveTransformV3 = tf_export("raw_ops.ImageProjectiveTransformV3")(_ops.to_raw_op(image_projective_transform_v3)) + + +def image_projective_transform_v3_eager_fallback(images: Annotated[Any, TV_ImageProjectiveTransformV3_dtype], transforms: Annotated[Any, _atypes.Float32], output_shape: Annotated[Any, _atypes.Int32], fill_value: Annotated[Any, _atypes.Float32], interpolation: str, fill_mode: str, name, ctx) -> Annotated[Any, TV_ImageProjectiveTransformV3_dtype]: + interpolation = _execute.make_str(interpolation, "interpolation") + if fill_mode is None: + fill_mode = "CONSTANT" + fill_mode = _execute.make_str(fill_mode, "fill_mode") + _attr_dtype, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.uint8, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + transforms = _ops.convert_to_tensor(transforms, _dtypes.float32) + output_shape = _ops.convert_to_tensor(output_shape, _dtypes.int32) + fill_value = _ops.convert_to_tensor(fill_value, _dtypes.float32) + _inputs_flat = [images, transforms, output_shape, fill_value] + _attrs = ("dtype", _attr_dtype, "interpolation", interpolation, "fill_mode", + fill_mode) + _result = _execute.execute(b"ImageProjectiveTransformV3", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ImageProjectiveTransformV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def non_max_suppression(boxes: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold:float=0.5, name=None) -> Annotated[Any, _atypes.Int32]: + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Note that this + algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + selected_indices = tf.image.non_max_suppression( + boxes, scores, max_output_size, iou_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + + Args: + boxes: A `Tensor` of type `float32`. + A 2-D float tensor of shape `[num_boxes, 4]`. + scores: A `Tensor` of type `float32`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + iou_threshold: An optional `float`. Defaults to `0.5`. + A float representing the threshold for deciding whether boxes + overlap too much with respect to IOU. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppression", name, boxes, scores, max_output_size, + "iou_threshold", iou_threshold) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_eager_fallback( + boxes, scores, max_output_size, iou_threshold=iou_threshold, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if iou_threshold is None: + iou_threshold = 0.5 + iou_threshold = _execute.make_float(iou_threshold, "iou_threshold") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppression", boxes=boxes, scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("iou_threshold", _op.get_attr("iou_threshold")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppression", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonMaxSuppression = tf_export("raw_ops.NonMaxSuppression")(_ops.to_raw_op(non_max_suppression)) + + +def non_max_suppression_eager_fallback(boxes: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: float, name, ctx) -> Annotated[Any, _atypes.Int32]: + if iou_threshold is None: + iou_threshold = 0.5 + iou_threshold = _execute.make_float(iou_threshold, "iou_threshold") + boxes = _ops.convert_to_tensor(boxes, _dtypes.float32) + scores = _ops.convert_to_tensor(scores, _dtypes.float32) + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + _inputs_flat = [boxes, scores, max_output_size] + _attrs = ("iou_threshold", iou_threshold) + _result = _execute.execute(b"NonMaxSuppression", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppression", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NonMaxSuppressionV2_T = TypeVar("TV_NonMaxSuppressionV2_T", _atypes.Float32, _atypes.Half) +TV_NonMaxSuppressionV2_T_threshold = TypeVar("TV_NonMaxSuppressionV2_T_threshold", _atypes.Float32, _atypes.Half) + +def non_max_suppression_v2(boxes: Annotated[Any, TV_NonMaxSuppressionV2_T], scores: Annotated[Any, TV_NonMaxSuppressionV2_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV2_T_threshold], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Note that this + algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + + selected_indices = tf.image.non_max_suppression_v2( + boxes, scores, max_output_size, iou_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + + Args: + boxes: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 2-D float tensor of shape `[num_boxes, 4]`. + scores: A `Tensor`. Must have the same type as `boxes`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + iou_threshold: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too much with respect to IOU. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppressionV2", name, boxes, scores, max_output_size, + iou_threshold) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_v2_eager_fallback( + boxes, scores, max_output_size, iou_threshold, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppressionV2", boxes=boxes, scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "T_threshold", + _op._get_attr_type("T_threshold")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppressionV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonMaxSuppressionV2 = tf_export("raw_ops.NonMaxSuppressionV2")(_ops.to_raw_op(non_max_suppression_v2)) + + +def non_max_suppression_v2_eager_fallback(boxes: Annotated[Any, TV_NonMaxSuppressionV2_T], scores: Annotated[Any, TV_NonMaxSuppressionV2_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV2_T_threshold], name, ctx) -> Annotated[Any, _atypes.Int32]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([boxes, scores], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (boxes, scores) = _inputs_T + _attr_T_threshold, (iou_threshold,) = _execute.args_to_matching_eager([iou_threshold], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + _inputs_flat = [boxes, scores, max_output_size, iou_threshold] + _attrs = ("T", _attr_T, "T_threshold", _attr_T_threshold) + _result = _execute.execute(b"NonMaxSuppressionV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppressionV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NonMaxSuppressionV3_T = TypeVar("TV_NonMaxSuppressionV3_T", _atypes.Float32, _atypes.Half) +TV_NonMaxSuppressionV3_T_threshold = TypeVar("TV_NonMaxSuppressionV3_T_threshold", _atypes.Float32, _atypes.Half) + +def non_max_suppression_v3(boxes: Annotated[Any, TV_NonMaxSuppressionV3_T], scores: Annotated[Any, TV_NonMaxSuppressionV3_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV3_T_threshold], score_threshold: Annotated[Any, TV_NonMaxSuppressionV3_T_threshold], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes with score less than + `score_threshold` are removed. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system and more + generally is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + selected_indices = tf.image.non_max_suppression_v2( + boxes, scores, max_output_size, iou_threshold, score_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + + Args: + boxes: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 2-D float tensor of shape `[num_boxes, 4]`. + scores: A `Tensor`. Must have the same type as `boxes`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + iou_threshold: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too much with respect to IOU. + score_threshold: A `Tensor`. Must have the same type as `iou_threshold`. + A 0-D float tensor representing the threshold for deciding when to remove + boxes based on score. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppressionV3", name, boxes, scores, max_output_size, + iou_threshold, score_threshold) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_v3_eager_fallback( + boxes, scores, max_output_size, iou_threshold, score_threshold, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppressionV3", boxes=boxes, scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "T_threshold", + _op._get_attr_type("T_threshold")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppressionV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonMaxSuppressionV3 = tf_export("raw_ops.NonMaxSuppressionV3")(_ops.to_raw_op(non_max_suppression_v3)) + + +def non_max_suppression_v3_eager_fallback(boxes: Annotated[Any, TV_NonMaxSuppressionV3_T], scores: Annotated[Any, TV_NonMaxSuppressionV3_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV3_T_threshold], score_threshold: Annotated[Any, TV_NonMaxSuppressionV3_T_threshold], name, ctx) -> Annotated[Any, _atypes.Int32]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([boxes, scores], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (boxes, scores) = _inputs_T + _attr_T_threshold, _inputs_T_threshold = _execute.args_to_matching_eager([iou_threshold, score_threshold], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (iou_threshold, score_threshold) = _inputs_T_threshold + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + _inputs_flat = [boxes, scores, max_output_size, iou_threshold, score_threshold] + _attrs = ("T", _attr_T, "T_threshold", _attr_T_threshold) + _result = _execute.execute(b"NonMaxSuppressionV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppressionV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_NonMaxSuppressionV4Output = collections.namedtuple( + "NonMaxSuppressionV4", + ["selected_indices", "valid_outputs"]) + + +TV_NonMaxSuppressionV4_T = TypeVar("TV_NonMaxSuppressionV4_T", _atypes.Float32, _atypes.Half) +TV_NonMaxSuppressionV4_T_threshold = TypeVar("TV_NonMaxSuppressionV4_T_threshold", _atypes.Float32, _atypes.Half) + +def non_max_suppression_v4(boxes: Annotated[Any, TV_NonMaxSuppressionV4_T], scores: Annotated[Any, TV_NonMaxSuppressionV4_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV4_T_threshold], score_threshold: Annotated[Any, TV_NonMaxSuppressionV4_T_threshold], pad_to_max_output_size:bool=False, name=None): + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes with score less than + `score_threshold` are removed. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system and more + generally is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + selected_indices = tf.image.non_max_suppression_v2( + boxes, scores, max_output_size, iou_threshold, score_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + + Args: + boxes: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 2-D float tensor of shape `[num_boxes, 4]`. + scores: A `Tensor`. Must have the same type as `boxes`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + iou_threshold: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too much with respect to IOU. + score_threshold: A `Tensor`. Must have the same type as `iou_threshold`. + A 0-D float tensor representing the threshold for deciding when to remove + boxes based on score. + pad_to_max_output_size: An optional `bool`. Defaults to `False`. + If true, the output `selected_indices` is padded to be of length + `max_output_size`. Defaults to false. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (selected_indices, valid_outputs). + + selected_indices: A `Tensor` of type `int32`. + valid_outputs: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppressionV4", name, boxes, scores, max_output_size, + iou_threshold, score_threshold, "pad_to_max_output_size", + pad_to_max_output_size) + _result = _NonMaxSuppressionV4Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_v4_eager_fallback( + boxes, scores, max_output_size, iou_threshold, score_threshold, + pad_to_max_output_size=pad_to_max_output_size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if pad_to_max_output_size is None: + pad_to_max_output_size = False + pad_to_max_output_size = _execute.make_bool(pad_to_max_output_size, "pad_to_max_output_size") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppressionV4", boxes=boxes, scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=pad_to_max_output_size, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "T_threshold", + _op._get_attr_type("T_threshold"), "pad_to_max_output_size", + _op._get_attr_bool("pad_to_max_output_size")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppressionV4", _inputs_flat, _attrs, _result) + _result = _NonMaxSuppressionV4Output._make(_result) + return _result + +NonMaxSuppressionV4 = tf_export("raw_ops.NonMaxSuppressionV4")(_ops.to_raw_op(non_max_suppression_v4)) + + +def non_max_suppression_v4_eager_fallback(boxes: Annotated[Any, TV_NonMaxSuppressionV4_T], scores: Annotated[Any, TV_NonMaxSuppressionV4_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV4_T_threshold], score_threshold: Annotated[Any, TV_NonMaxSuppressionV4_T_threshold], pad_to_max_output_size: bool, name, ctx): + if pad_to_max_output_size is None: + pad_to_max_output_size = False + pad_to_max_output_size = _execute.make_bool(pad_to_max_output_size, "pad_to_max_output_size") + _attr_T, _inputs_T = _execute.args_to_matching_eager([boxes, scores], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (boxes, scores) = _inputs_T + _attr_T_threshold, _inputs_T_threshold = _execute.args_to_matching_eager([iou_threshold, score_threshold], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (iou_threshold, score_threshold) = _inputs_T_threshold + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + _inputs_flat = [boxes, scores, max_output_size, iou_threshold, score_threshold] + _attrs = ("T", _attr_T, "T_threshold", _attr_T_threshold, + "pad_to_max_output_size", pad_to_max_output_size) + _result = _execute.execute(b"NonMaxSuppressionV4", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppressionV4", _inputs_flat, _attrs, _result) + _result = _NonMaxSuppressionV4Output._make(_result) + return _result + +_NonMaxSuppressionV5Output = collections.namedtuple( + "NonMaxSuppressionV5", + ["selected_indices", "selected_scores", "valid_outputs"]) + + +TV_NonMaxSuppressionV5_T = TypeVar("TV_NonMaxSuppressionV5_T", _atypes.Float32, _atypes.Half) + +def non_max_suppression_v5(boxes: Annotated[Any, TV_NonMaxSuppressionV5_T], scores: Annotated[Any, TV_NonMaxSuppressionV5_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV5_T], score_threshold: Annotated[Any, TV_NonMaxSuppressionV5_T], soft_nms_sigma: Annotated[Any, TV_NonMaxSuppressionV5_T], pad_to_max_output_size:bool=False, name=None): + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes with score less than + `score_threshold` are removed. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system and more + generally is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + selected_indices = tf.image.non_max_suppression_v2( + boxes, scores, max_output_size, iou_threshold, score_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + This op also supports a Soft-NMS (with Gaussian weighting) mode (c.f. + Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score + of other overlapping boxes instead of directly causing them to be pruned. + To enable this Soft-NMS mode, set the `soft_nms_sigma` parameter to be + larger than 0. + + Args: + boxes: A `Tensor`. Must be one of the following types: `half`, `float32`. + A 2-D float tensor of shape `[num_boxes, 4]`. + scores: A `Tensor`. Must have the same type as `boxes`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + iou_threshold: A `Tensor`. Must have the same type as `boxes`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too much with respect to IOU. + score_threshold: A `Tensor`. Must have the same type as `boxes`. + A 0-D float tensor representing the threshold for deciding when to remove + boxes based on score. + soft_nms_sigma: A `Tensor`. Must have the same type as `boxes`. + A 0-D float tensor representing the sigma parameter for Soft NMS; see Bodla et + al (c.f. https://arxiv.org/abs/1704.04503). When `soft_nms_sigma=0.0` (which + is default), we fall back to standard (hard) NMS. + pad_to_max_output_size: An optional `bool`. Defaults to `False`. + If true, the output `selected_indices` is padded to be of length + `max_output_size`. Defaults to false. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (selected_indices, selected_scores, valid_outputs). + + selected_indices: A `Tensor` of type `int32`. + selected_scores: A `Tensor`. Has the same type as `boxes`. + valid_outputs: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppressionV5", name, boxes, scores, max_output_size, + iou_threshold, score_threshold, soft_nms_sigma, + "pad_to_max_output_size", pad_to_max_output_size) + _result = _NonMaxSuppressionV5Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_v5_eager_fallback( + boxes, scores, max_output_size, iou_threshold, score_threshold, + soft_nms_sigma, pad_to_max_output_size=pad_to_max_output_size, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if pad_to_max_output_size is None: + pad_to_max_output_size = False + pad_to_max_output_size = _execute.make_bool(pad_to_max_output_size, "pad_to_max_output_size") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppressionV5", boxes=boxes, scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + soft_nms_sigma=soft_nms_sigma, + pad_to_max_output_size=pad_to_max_output_size, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "pad_to_max_output_size", + _op._get_attr_bool("pad_to_max_output_size")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppressionV5", _inputs_flat, _attrs, _result) + _result = _NonMaxSuppressionV5Output._make(_result) + return _result + +NonMaxSuppressionV5 = tf_export("raw_ops.NonMaxSuppressionV5")(_ops.to_raw_op(non_max_suppression_v5)) + + +def non_max_suppression_v5_eager_fallback(boxes: Annotated[Any, TV_NonMaxSuppressionV5_T], scores: Annotated[Any, TV_NonMaxSuppressionV5_T], max_output_size: Annotated[Any, _atypes.Int32], iou_threshold: Annotated[Any, TV_NonMaxSuppressionV5_T], score_threshold: Annotated[Any, TV_NonMaxSuppressionV5_T], soft_nms_sigma: Annotated[Any, TV_NonMaxSuppressionV5_T], pad_to_max_output_size: bool, name, ctx): + if pad_to_max_output_size is None: + pad_to_max_output_size = False + pad_to_max_output_size = _execute.make_bool(pad_to_max_output_size, "pad_to_max_output_size") + _attr_T, _inputs_T = _execute.args_to_matching_eager([boxes, scores, iou_threshold, score_threshold, soft_nms_sigma], ctx, [_dtypes.half, _dtypes.float32, ], _dtypes.float32) + (boxes, scores, iou_threshold, score_threshold, soft_nms_sigma) = _inputs_T + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + _inputs_flat = [boxes, scores, max_output_size, iou_threshold, score_threshold, soft_nms_sigma] + _attrs = ("T", _attr_T, "pad_to_max_output_size", pad_to_max_output_size) + _result = _execute.execute(b"NonMaxSuppressionV5", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppressionV5", _inputs_flat, _attrs, _result) + _result = _NonMaxSuppressionV5Output._make(_result) + return _result + + +def non_max_suppression_with_overlaps(overlaps: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size: Annotated[Any, _atypes.Int32], overlap_threshold: Annotated[Any, _atypes.Float32], score_threshold: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Greedily selects a subset of bounding boxes in descending order of score, + + pruning away boxes that have high overlaps + with previously selected boxes. Bounding boxes with score less than + `score_threshold` are removed. N-by-n overlap values are supplied as square matrix, + which allows for defining a custom overlap criterium (eg. intersection over union, + intersection over area, etc.). + + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather operation`. For example: + + selected_indices = tf.image.non_max_suppression_with_overlaps( + overlaps, scores, max_output_size, overlap_threshold, score_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + + Args: + overlaps: A `Tensor` of type `float32`. + A 2-D float tensor of shape `[num_boxes, num_boxes]` representing + the n-by-n box overlap values. + scores: A `Tensor` of type `float32`. + A 1-D float tensor of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A `Tensor` of type `int32`. + A scalar integer tensor representing the maximum number of + boxes to be selected by non max suppression. + overlap_threshold: A `Tensor` of type `float32`. + A 0-D float tensor representing the threshold for deciding whether + boxes overlap too. + score_threshold: A `Tensor` of type `float32`. + A 0-D float tensor representing the threshold for deciding when to remove + boxes based on score. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonMaxSuppressionWithOverlaps", name, overlaps, scores, + max_output_size, overlap_threshold, score_threshold) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_max_suppression_with_overlaps_eager_fallback( + overlaps, scores, max_output_size, overlap_threshold, + score_threshold, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonMaxSuppressionWithOverlaps", overlaps=overlaps, scores=scores, + max_output_size=max_output_size, + overlap_threshold=overlap_threshold, + score_threshold=score_threshold, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonMaxSuppressionWithOverlaps", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonMaxSuppressionWithOverlaps = tf_export("raw_ops.NonMaxSuppressionWithOverlaps")(_ops.to_raw_op(non_max_suppression_with_overlaps)) + + +def non_max_suppression_with_overlaps_eager_fallback(overlaps: Annotated[Any, _atypes.Float32], scores: Annotated[Any, _atypes.Float32], max_output_size: Annotated[Any, _atypes.Int32], overlap_threshold: Annotated[Any, _atypes.Float32], score_threshold: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + overlaps = _ops.convert_to_tensor(overlaps, _dtypes.float32) + scores = _ops.convert_to_tensor(scores, _dtypes.float32) + max_output_size = _ops.convert_to_tensor(max_output_size, _dtypes.int32) + overlap_threshold = _ops.convert_to_tensor(overlap_threshold, _dtypes.float32) + score_threshold = _ops.convert_to_tensor(score_threshold, _dtypes.float32) + _inputs_flat = [overlaps, scores, max_output_size, overlap_threshold, score_threshold] + _attrs = None + _result = _execute.execute(b"NonMaxSuppressionWithOverlaps", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonMaxSuppressionWithOverlaps", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QuantizedResizeBilinearOutput = collections.namedtuple( + "QuantizedResizeBilinear", + ["resized_images", "out_min", "out_max"]) + + +TV_QuantizedResizeBilinear_T = TypeVar("TV_QuantizedResizeBilinear_T", _atypes.Float32, _atypes.QInt32, _atypes.QUInt8) + +def quantized_resize_bilinear(images: Annotated[Any, TV_QuantizedResizeBilinear_T], size: Annotated[Any, _atypes.Int32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], align_corners:bool=False, half_pixel_centers:bool=False, name=None): + r"""Resize quantized `images` to `size` using quantized bilinear interpolation. + + Input images and output images must be quantized types. + + Args: + images: A `Tensor`. Must be one of the following types: `quint8`, `qint32`, `float32`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + min: A `Tensor` of type `float32`. + max: A `Tensor` of type `float32`. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (resized_images, out_min, out_max). + + resized_images: A `Tensor`. Has the same type as `images`. + out_min: A `Tensor` of type `float32`. + out_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedResizeBilinear", name, images, size, min, max, + "align_corners", align_corners, "half_pixel_centers", + half_pixel_centers) + _result = _QuantizedResizeBilinearOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_resize_bilinear_eager_fallback( + images, size, min, max, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedResizeBilinear", images=images, size=size, min=min, max=max, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedResizeBilinear", _inputs_flat, _attrs, _result) + _result = _QuantizedResizeBilinearOutput._make(_result) + return _result + +QuantizedResizeBilinear = tf_export("raw_ops.QuantizedResizeBilinear")(_ops.to_raw_op(quantized_resize_bilinear)) + + +def quantized_resize_bilinear_eager_fallback(images: Annotated[Any, TV_QuantizedResizeBilinear_T], size: Annotated[Any, _atypes.Int32], min: Annotated[Any, _atypes.Float32], max: Annotated[Any, _atypes.Float32], align_corners: bool, half_pixel_centers: bool, name, ctx): + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.quint8, _dtypes.qint32, _dtypes.float32, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + min = _ops.convert_to_tensor(min, _dtypes.float32) + max = _ops.convert_to_tensor(max, _dtypes.float32) + _inputs_flat = [images, size, min, max] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"QuantizedResizeBilinear", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedResizeBilinear", _inputs_flat, _attrs, _result) + _result = _QuantizedResizeBilinearOutput._make(_result) + return _result + + +TV_RGBToHSV_T = TypeVar("TV_RGBToHSV_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('image.rgb_to_hsv') +def rgb_to_hsv(images: Annotated[Any, TV_RGBToHSV_T], name=None) -> Annotated[Any, TV_RGBToHSV_T]: + r"""Converts one or more images from RGB to HSV. + + Outputs a tensor of the same shape as the `images` tensor, containing the HSV + value of the pixels. The output is only well defined if the value in `images` + are in `[0,1]`. + + `output[..., 0]` contains hue, `output[..., 1]` contains saturation, and + `output[..., 2]` contains value. All HSV values are in `[0,1]`. A hue of 0 + corresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue. + + Usage Example: + + >>> blue_image = tf.stack([ + ... tf.zeros([5,5]), + ... tf.zeros([5,5]), + ... tf.ones([5,5])], + ... axis=-1) + >>> blue_hsv_image = tf.image.rgb_to_hsv(blue_image) + >>> blue_hsv_image[0,0].numpy() + array([0.6666667, 1. , 1. ], dtype=float32) + + Args: + images: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 1-D or higher rank. RGB data to convert. Last dimension must be size 3. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RGBToHSV", name, images) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_rgb_to_hsv( + (images, name,), None) + if _result is not NotImplemented: + return _result + return rgb_to_hsv_eager_fallback( + images, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rgb_to_hsv, (), dict(images=images, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_rgb_to_hsv( + (images, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RGBToHSV", images=images, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rgb_to_hsv, (), dict(images=images, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RGBToHSV", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RGBToHSV = tf_export("raw_ops.RGBToHSV")(_ops.to_raw_op(rgb_to_hsv)) +_dispatcher_for_rgb_to_hsv = rgb_to_hsv._tf_type_based_dispatcher.Dispatch + + +def rgb_to_hsv_eager_fallback(images: Annotated[Any, TV_RGBToHSV_T], name, ctx) -> Annotated[Any, TV_RGBToHSV_T]: + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ], _dtypes.float32) + _inputs_flat = [images] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RGBToHSV", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RGBToHSV", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomCrop_T = TypeVar("TV_RandomCrop_T", _atypes.Float32, _atypes.Float64, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) + +def random_crop(image: Annotated[Any, TV_RandomCrop_T], size: Annotated[Any, _atypes.Int64], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomCrop_T]: + r"""Randomly crop `image`. + + `size` is a 1-D int64 tensor with 2 elements representing the crop height and + width. The values must be non negative. + + This Op picks a random location in `image` and crops a `height` by `width` + rectangle from that location. The random location is picked so the cropped + area will fit inside the original image. + + Args: + image: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`, `float32`, `float64`. + 3-D of shape `[height, width, channels]`. + size: A `Tensor` of type `int64`. + 1-D of length 2 containing: `crop_height`, `crop_width`.. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `image`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomCrop", name, image, size, "seed", seed, "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_crop_eager_fallback( + image, size, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomCrop", image=image, size=size, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "seed", _op._get_attr_int("seed"), + "seed2", _op._get_attr_int("seed2")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomCrop", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomCrop = tf_export("raw_ops.RandomCrop")(_ops.to_raw_op(random_crop)) + + +def random_crop_eager_fallback(image: Annotated[Any, TV_RandomCrop_T], size: Annotated[Any, _atypes.Int64], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomCrop_T]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (image,) = _execute.args_to_matching_eager([image], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + size = _ops.convert_to_tensor(size, _dtypes.int64) + _inputs_flat = [image, size] + _attrs = ("T", _attr_T, "seed", seed, "seed2", seed2) + _result = _execute.execute(b"RandomCrop", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomCrop", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeArea_T = TypeVar("TV_ResizeArea_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def resize_area(images: Annotated[Any, TV_ResizeArea_T], size: Annotated[Any, _atypes.Int32], align_corners:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Resize `images` to `size` using area interpolation. + + Input images can be of different types but output images are always float. + + The range of pixel values for the output image might be slightly different + from the range for the input image because of limited numerical precision. + To guarantee an output range, for example `[0.0, 1.0]`, apply + `tf.clip_by_value` to the output. + + Each output pixel is computed by first transforming the pixel's footprint into + the input tensor and then averaging the pixels that intersect the footprint. An + input pixel's contribution to the average is weighted by the fraction of its + area that intersects the footprint. This is the same as OpenCV's INTER_AREA. + + Args: + images: A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `half`, `float32`, `float64`, `bfloat16`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeArea", name, images, size, "align_corners", + align_corners) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_area_eager_fallback( + images, size, align_corners=align_corners, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeArea", images=images, size=size, align_corners=align_corners, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeArea", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeArea = tf_export("raw_ops.ResizeArea")(_ops.to_raw_op(resize_area)) + + +def resize_area_eager_fallback(images: Annotated[Any, TV_ResizeArea_T], size: Annotated[Any, _atypes.Int32], align_corners: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.bfloat16, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [images, size] + _attrs = ("T", _attr_T, "align_corners", align_corners) + _result = _execute.execute(b"ResizeArea", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeArea", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeBicubic_T = TypeVar("TV_ResizeBicubic_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def resize_bicubic(images: Annotated[Any, TV_ResizeBicubic_T], size: Annotated[Any, _atypes.Int32], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Resize `images` to `size` using bicubic interpolation. + + Input images can be of different types but output images are always float. + + Args: + images: A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `half`, `float32`, `float64`, `bfloat16`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeBicubic", name, images, size, "align_corners", + align_corners, "half_pixel_centers", half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_bicubic_eager_fallback( + images, size, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeBicubic", images=images, size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeBicubic", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeBicubic = tf_export("raw_ops.ResizeBicubic")(_ops.to_raw_op(resize_bicubic)) + + +def resize_bicubic_eager_fallback(images: Annotated[Any, TV_ResizeBicubic_T], size: Annotated[Any, _atypes.Int32], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.bfloat16, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [images, size] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeBicubic", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeBicubic", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeBicubicGrad_T = TypeVar("TV_ResizeBicubicGrad_T", _atypes.Float32, _atypes.Float64) + +def resize_bicubic_grad(grads: Annotated[Any, _atypes.Float32], original_image: Annotated[Any, TV_ResizeBicubicGrad_T], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, TV_ResizeBicubicGrad_T]: + r"""Computes the gradient of bicubic interpolation. + + Args: + grads: A `Tensor` of type `float32`. + 4-D with shape `[batch, height, width, channels]`. + original_image: A `Tensor`. Must be one of the following types: `float32`, `float64`. + 4-D with shape `[batch, orig_height, orig_width, channels]`, + The image tensor that was resized. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and grad tensors are + aligned. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `original_image`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeBicubicGrad", name, grads, original_image, + "align_corners", align_corners, "half_pixel_centers", + half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_bicubic_grad_eager_fallback( + grads, original_image, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeBicubicGrad", grads=grads, original_image=original_image, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeBicubicGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeBicubicGrad = tf_export("raw_ops.ResizeBicubicGrad")(_ops.to_raw_op(resize_bicubic_grad)) + + +def resize_bicubic_grad_eager_fallback(grads: Annotated[Any, _atypes.Float32], original_image: Annotated[Any, TV_ResizeBicubicGrad_T], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, TV_ResizeBicubicGrad_T]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (original_image,) = _execute.args_to_matching_eager([original_image], ctx, [_dtypes.float32, _dtypes.float64, ]) + grads = _ops.convert_to_tensor(grads, _dtypes.float32) + _inputs_flat = [grads, original_image] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeBicubicGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeBicubicGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeBilinear_T = TypeVar("TV_ResizeBilinear_T", _atypes.BFloat16, _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def resize_bilinear(images: Annotated[Any, TV_ResizeBilinear_T], size: Annotated[Any, _atypes.Int32], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Resize `images` to `size` using bilinear interpolation. + + Input images can be of different types but output images are always float. + + Args: + images: A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `half`, `float32`, `float64`, `bfloat16`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeBilinear", name, images, size, "align_corners", + align_corners, "half_pixel_centers", half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_bilinear_eager_fallback( + images, size, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeBilinear", images=images, size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeBilinear", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeBilinear = tf_export("raw_ops.ResizeBilinear")(_ops.to_raw_op(resize_bilinear)) + + +def resize_bilinear_eager_fallback(images: Annotated[Any, TV_ResizeBilinear_T], size: Annotated[Any, _atypes.Int32], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.int64, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.bfloat16, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [images, size] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeBilinear", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeBilinear", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeBilinearGrad_T = TypeVar("TV_ResizeBilinearGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def resize_bilinear_grad(grads: Annotated[Any, _atypes.Float32], original_image: Annotated[Any, TV_ResizeBilinearGrad_T], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, TV_ResizeBilinearGrad_T]: + r"""Computes the gradient of bilinear interpolation. + + Args: + grads: A `Tensor` of type `float32`. + 4-D with shape `[batch, height, width, channels]`. + original_image: A `Tensor`. Must be one of the following types: `float32`, `bfloat16`, `half`, `float64`. + 4-D with shape `[batch, orig_height, orig_width, channels]`, + The image tensor that was resized. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and grad tensors are + aligned. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `original_image`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeBilinearGrad", name, grads, original_image, + "align_corners", align_corners, "half_pixel_centers", + half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_bilinear_grad_eager_fallback( + grads, original_image, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeBilinearGrad", grads=grads, original_image=original_image, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeBilinearGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeBilinearGrad = tf_export("raw_ops.ResizeBilinearGrad")(_ops.to_raw_op(resize_bilinear_grad)) + + +def resize_bilinear_grad_eager_fallback(grads: Annotated[Any, _atypes.Float32], original_image: Annotated[Any, TV_ResizeBilinearGrad_T], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, TV_ResizeBilinearGrad_T]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (original_image,) = _execute.args_to_matching_eager([original_image], ctx, [_dtypes.float32, _dtypes.bfloat16, _dtypes.half, _dtypes.float64, ]) + grads = _ops.convert_to_tensor(grads, _dtypes.float32) + _inputs_flat = [grads, original_image] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeBilinearGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeBilinearGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeNearestNeighbor_T = TypeVar("TV_ResizeNearestNeighbor_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def resize_nearest_neighbor(images: Annotated[Any, TV_ResizeNearestNeighbor_T], size: Annotated[Any, _atypes.Int32], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, TV_ResizeNearestNeighbor_T]: + r"""Resize `images` to `size` using nearest neighbor interpolation. + + Args: + images: A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `half`, `float32`, `float64`, `bfloat16`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeNearestNeighbor", name, images, size, "align_corners", + align_corners, "half_pixel_centers", half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_nearest_neighbor_eager_fallback( + images, size, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeNearestNeighbor", images=images, size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeNearestNeighbor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeNearestNeighbor = tf_export("raw_ops.ResizeNearestNeighbor")(_ops.to_raw_op(resize_nearest_neighbor)) + + +def resize_nearest_neighbor_eager_fallback(images: Annotated[Any, TV_ResizeNearestNeighbor_T], size: Annotated[Any, _atypes.Int32], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, TV_ResizeNearestNeighbor_T]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.bfloat16, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [images, size] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeNearestNeighbor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeNearestNeighbor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResizeNearestNeighborGrad_T = TypeVar("TV_ResizeNearestNeighborGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int8, _atypes.UInt8) + +def resize_nearest_neighbor_grad(grads: Annotated[Any, TV_ResizeNearestNeighborGrad_T], size: Annotated[Any, _atypes.Int32], align_corners:bool=False, half_pixel_centers:bool=False, name=None) -> Annotated[Any, TV_ResizeNearestNeighborGrad_T]: + r"""Computes the gradient of nearest neighbor interpolation. + + Args: + grads: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int32`, `half`, `float32`, `float64`, `bfloat16`. + 4-D with shape `[batch, height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `orig_height, orig_width`. The + original input size. + align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and grad tensors are + aligned. Defaults to false. + half_pixel_centers: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grads`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResizeNearestNeighborGrad", name, grads, size, "align_corners", + align_corners, "half_pixel_centers", half_pixel_centers) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resize_nearest_neighbor_grad_eager_fallback( + grads, size, align_corners=align_corners, + half_pixel_centers=half_pixel_centers, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResizeNearestNeighborGrad", grads=grads, size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "align_corners", + _op._get_attr_bool("align_corners"), "half_pixel_centers", + _op._get_attr_bool("half_pixel_centers")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResizeNearestNeighborGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResizeNearestNeighborGrad = tf_export("raw_ops.ResizeNearestNeighborGrad")(_ops.to_raw_op(resize_nearest_neighbor_grad)) + + +def resize_nearest_neighbor_grad_eager_fallback(grads: Annotated[Any, TV_ResizeNearestNeighborGrad_T], size: Annotated[Any, _atypes.Int32], align_corners: bool, half_pixel_centers: bool, name, ctx) -> Annotated[Any, TV_ResizeNearestNeighborGrad_T]: + if align_corners is None: + align_corners = False + align_corners = _execute.make_bool(align_corners, "align_corners") + if half_pixel_centers is None: + half_pixel_centers = False + half_pixel_centers = _execute.make_bool(half_pixel_centers, "half_pixel_centers") + _attr_T, (grads,) = _execute.args_to_matching_eager([grads], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int32, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.bfloat16, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [grads, size] + _attrs = ("T", _attr_T, "align_corners", align_corners, + "half_pixel_centers", half_pixel_centers) + _result = _execute.execute(b"ResizeNearestNeighborGrad", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResizeNearestNeighborGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SampleDistortedBoundingBoxOutput = collections.namedtuple( + "SampleDistortedBoundingBox", + ["begin", "size", "bboxes"]) + + +TV_SampleDistortedBoundingBox_T = TypeVar("TV_SampleDistortedBoundingBox_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) + +def sample_distorted_bounding_box(image_size: Annotated[Any, TV_SampleDistortedBoundingBox_T], bounding_boxes: Annotated[Any, _atypes.Float32], seed:int=0, seed2:int=0, min_object_covered:float=0.1, aspect_ratio_range=[0.75, 1.33], area_range=[0.05, 1], max_attempts:int=100, use_image_if_no_bounding_boxes:bool=False, name=None): + r"""Generate a single randomly distorted bounding box for an image. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving + its content, i.e. *data augmentation*. This Op outputs a randomly distorted + localization of an object, i.e. bounding box, given an `image_size`, + `bounding_boxes` and a series of constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize + what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + height of the underlying image. + + For example, + + ```python + # Generate a single distorted bounding box. + begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( + tf.shape(image), + bounding_boxes=bounding_boxes) + + # Draw the bounding box in an image summary. + image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), + bbox_for_draw) + tf.summary.image('images_with_box', image_with_box) + + # Employ the bounding box to distort the image. + distorted_image = tf.slice(image, begin, size) + ``` + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = true` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`. + 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. + 3-D with shape `[batch, N, 4]` describing the N bounding boxes + associated with the image. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to non-zero, the random number + generator is seeded by the given `seed`. Otherwise, it is seeded by a random + seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + min_object_covered: An optional `float`. Defaults to `0.1`. + The cropped area of the image must contain at least this + fraction of any bounding box supplied. The value of this parameter should be + non-negative. In the case of 0, the cropped area does not need to overlap + any of the bounding boxes supplied. + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, 1.33]`. + The cropped area of the image must have an aspect ratio = + width / height within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. + The cropped area of the image must contain a fraction of the + supplied image within this range. + max_attempts: An optional `int`. Defaults to `100`. + Number of attempts at generating a cropped region of the image + of the specified constraints. After `max_attempts` failures, return the entire + image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. + If true, assume an implicit bounding box covering the whole input. If false, + raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. + size: A `Tensor`. Has the same type as `image_size`. + bboxes: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SampleDistortedBoundingBox", name, image_size, bounding_boxes, + "seed", seed, "seed2", seed2, "min_object_covered", + min_object_covered, "aspect_ratio_range", aspect_ratio_range, + "area_range", area_range, "max_attempts", max_attempts, + "use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) + _result = _SampleDistortedBoundingBoxOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sample_distorted_bounding_box_eager_fallback( + image_size, bounding_boxes, seed=seed, seed2=seed2, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if min_object_covered is None: + min_object_covered = 0.1 + min_object_covered = _execute.make_float(min_object_covered, "min_object_covered") + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'sample_distorted_bounding_box' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'sample_distorted_bounding_box' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SampleDistortedBoundingBox", image_size=image_size, + bounding_boxes=bounding_boxes, + seed=seed, seed2=seed2, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "seed", _op._get_attr_int("seed"), + "seed2", _op._get_attr_int("seed2"), "min_object_covered", + _op.get_attr("min_object_covered"), "aspect_ratio_range", + _op.get_attr("aspect_ratio_range"), "area_range", + _op.get_attr("area_range"), "max_attempts", + _op._get_attr_int("max_attempts"), + "use_image_if_no_bounding_boxes", + _op._get_attr_bool("use_image_if_no_bounding_boxes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SampleDistortedBoundingBox", _inputs_flat, _attrs, _result) + _result = _SampleDistortedBoundingBoxOutput._make(_result) + return _result + +SampleDistortedBoundingBox = tf_export("raw_ops.SampleDistortedBoundingBox")(_ops.to_raw_op(sample_distorted_bounding_box)) + + +def sample_distorted_bounding_box_eager_fallback(image_size: Annotated[Any, TV_SampleDistortedBoundingBox_T], bounding_boxes: Annotated[Any, _atypes.Float32], seed: int, seed2: int, min_object_covered: float, aspect_ratio_range, area_range, max_attempts: int, use_image_if_no_bounding_boxes: bool, name, ctx): + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if min_object_covered is None: + min_object_covered = 0.1 + min_object_covered = _execute.make_float(min_object_covered, "min_object_covered") + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'sample_distorted_bounding_box' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'sample_distorted_bounding_box' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _attr_T, (image_size,) = _execute.args_to_matching_eager([image_size], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + bounding_boxes = _ops.convert_to_tensor(bounding_boxes, _dtypes.float32) + _inputs_flat = [image_size, bounding_boxes] + _attrs = ("T", _attr_T, "seed", seed, "seed2", seed2, "min_object_covered", + min_object_covered, "aspect_ratio_range", aspect_ratio_range, "area_range", + area_range, "max_attempts", max_attempts, "use_image_if_no_bounding_boxes", + use_image_if_no_bounding_boxes) + _result = _execute.execute(b"SampleDistortedBoundingBox", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SampleDistortedBoundingBox", _inputs_flat, _attrs, _result) + _result = _SampleDistortedBoundingBoxOutput._make(_result) + return _result + +_SampleDistortedBoundingBoxV2Output = collections.namedtuple( + "SampleDistortedBoundingBoxV2", + ["begin", "size", "bboxes"]) + + +TV_SampleDistortedBoundingBoxV2_T = TypeVar("TV_SampleDistortedBoundingBoxV2_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) + +def sample_distorted_bounding_box_v2(image_size: Annotated[Any, TV_SampleDistortedBoundingBoxV2_T], bounding_boxes: Annotated[Any, _atypes.Float32], min_object_covered: Annotated[Any, _atypes.Float32], seed:int=0, seed2:int=0, aspect_ratio_range=[0.75, 1.33], area_range=[0.05, 1], max_attempts:int=100, use_image_if_no_bounding_boxes:bool=False, name=None): + r"""Generate a single randomly distorted bounding box for an image. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving + its content, i.e. *data augmentation*. This Op outputs a randomly distorted + localization of an object, i.e. bounding box, given an `image_size`, + `bounding_boxes` and a series of constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize + what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + height of the underlying image. + + For example, + + ```python + # Generate a single distorted bounding box. + begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( + tf.shape(image), + bounding_boxes=bounding_boxes) + + # Draw the bounding box in an image summary. + image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), + bbox_for_draw) + tf.summary.image('images_with_box', image_with_box) + + # Employ the bounding box to distort the image. + distorted_image = tf.slice(image, begin, size) + ``` + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = true` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`. + 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. + 3-D with shape `[batch, N, 4]` describing the N bounding boxes + associated with the image. + min_object_covered: A `Tensor` of type `float32`. + The cropped area of the image must contain at least this + fraction of any bounding box supplied. The value of this parameter should be + non-negative. In the case of 0, the cropped area does not need to overlap + any of the bounding boxes supplied. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to non-zero, the random number + generator is seeded by the given `seed`. Otherwise, it is seeded by a random + seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, 1.33]`. + The cropped area of the image must have an aspect ratio = + width / height within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. + The cropped area of the image must contain a fraction of the + supplied image within this range. + max_attempts: An optional `int`. Defaults to `100`. + Number of attempts at generating a cropped region of the image + of the specified constraints. After `max_attempts` failures, return the entire + image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. + If true, assume an implicit bounding box covering the whole input. If false, + raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. + size: A `Tensor`. Has the same type as `image_size`. + bboxes: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SampleDistortedBoundingBoxV2", name, image_size, + bounding_boxes, min_object_covered, "seed", seed, "seed2", seed2, + "aspect_ratio_range", aspect_ratio_range, "area_range", area_range, + "max_attempts", max_attempts, "use_image_if_no_bounding_boxes", + use_image_if_no_bounding_boxes) + _result = _SampleDistortedBoundingBoxV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sample_distorted_bounding_box_v2_eager_fallback( + image_size, bounding_boxes, min_object_covered, seed=seed, + seed2=seed2, aspect_ratio_range=aspect_ratio_range, + area_range=area_range, max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'sample_distorted_bounding_box_v2' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'sample_distorted_bounding_box_v2' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SampleDistortedBoundingBoxV2", image_size=image_size, + bounding_boxes=bounding_boxes, + min_object_covered=min_object_covered, + seed=seed, seed2=seed2, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "seed", _op._get_attr_int("seed"), + "seed2", _op._get_attr_int("seed2"), "aspect_ratio_range", + _op.get_attr("aspect_ratio_range"), "area_range", + _op.get_attr("area_range"), "max_attempts", + _op._get_attr_int("max_attempts"), + "use_image_if_no_bounding_boxes", + _op._get_attr_bool("use_image_if_no_bounding_boxes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SampleDistortedBoundingBoxV2", _inputs_flat, _attrs, _result) + _result = _SampleDistortedBoundingBoxV2Output._make(_result) + return _result + +SampleDistortedBoundingBoxV2 = tf_export("raw_ops.SampleDistortedBoundingBoxV2")(_ops.to_raw_op(sample_distorted_bounding_box_v2)) + + +def sample_distorted_bounding_box_v2_eager_fallback(image_size: Annotated[Any, TV_SampleDistortedBoundingBoxV2_T], bounding_boxes: Annotated[Any, _atypes.Float32], min_object_covered: Annotated[Any, _atypes.Float32], seed: int, seed2: int, aspect_ratio_range, area_range, max_attempts: int, use_image_if_no_bounding_boxes: bool, name, ctx): + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'sample_distorted_bounding_box_v2' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'sample_distorted_bounding_box_v2' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _attr_T, (image_size,) = _execute.args_to_matching_eager([image_size], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + bounding_boxes = _ops.convert_to_tensor(bounding_boxes, _dtypes.float32) + min_object_covered = _ops.convert_to_tensor(min_object_covered, _dtypes.float32) + _inputs_flat = [image_size, bounding_boxes, min_object_covered] + _attrs = ("T", _attr_T, "seed", seed, "seed2", seed2, "aspect_ratio_range", + aspect_ratio_range, "area_range", area_range, "max_attempts", max_attempts, + "use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) + _result = _execute.execute(b"SampleDistortedBoundingBoxV2", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SampleDistortedBoundingBoxV2", _inputs_flat, _attrs, _result) + _result = _SampleDistortedBoundingBoxV2Output._make(_result) + return _result + + +TV_ScaleAndTranslate_T = TypeVar("TV_ScaleAndTranslate_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def scale_and_translate(images: Annotated[Any, TV_ScaleAndTranslate_T], size: Annotated[Any, _atypes.Int32], scale: Annotated[Any, _atypes.Float32], translation: Annotated[Any, _atypes.Float32], kernel_type:str="lanczos3", antialias:bool=True, name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + images: A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `bfloat16`, `half`, `float32`, `float64`. + size: A `Tensor` of type `int32`. + scale: A `Tensor` of type `float32`. + translation: A `Tensor` of type `float32`. + kernel_type: An optional `string`. Defaults to `"lanczos3"`. + antialias: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScaleAndTranslate", name, images, size, scale, translation, + "kernel_type", kernel_type, "antialias", antialias) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return scale_and_translate_eager_fallback( + images, size, scale, translation, kernel_type=kernel_type, + antialias=antialias, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if kernel_type is None: + kernel_type = "lanczos3" + kernel_type = _execute.make_str(kernel_type, "kernel_type") + if antialias is None: + antialias = True + antialias = _execute.make_bool(antialias, "antialias") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScaleAndTranslate", images=images, size=size, scale=scale, + translation=translation, kernel_type=kernel_type, + antialias=antialias, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "kernel_type", + _op.get_attr("kernel_type"), "antialias", + _op._get_attr_bool("antialias")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScaleAndTranslate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScaleAndTranslate = tf_export("raw_ops.ScaleAndTranslate")(_ops.to_raw_op(scale_and_translate)) + + +def scale_and_translate_eager_fallback(images: Annotated[Any, TV_ScaleAndTranslate_T], size: Annotated[Any, _atypes.Int32], scale: Annotated[Any, _atypes.Float32], translation: Annotated[Any, _atypes.Float32], kernel_type: str, antialias: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if kernel_type is None: + kernel_type = "lanczos3" + kernel_type = _execute.make_str(kernel_type, "kernel_type") + if antialias is None: + antialias = True + antialias = _execute.make_bool(antialias, "antialias") + _attr_T, (images,) = _execute.args_to_matching_eager([images], ctx, [_dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.int64, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + size = _ops.convert_to_tensor(size, _dtypes.int32) + scale = _ops.convert_to_tensor(scale, _dtypes.float32) + translation = _ops.convert_to_tensor(translation, _dtypes.float32) + _inputs_flat = [images, size, scale, translation] + _attrs = ("T", _attr_T, "kernel_type", kernel_type, "antialias", antialias) + _result = _execute.execute(b"ScaleAndTranslate", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScaleAndTranslate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ScaleAndTranslateGrad_T = TypeVar("TV_ScaleAndTranslateGrad_T", bound=_atypes.Float32) + +def scale_and_translate_grad(grads: Annotated[Any, TV_ScaleAndTranslateGrad_T], original_image: Annotated[Any, TV_ScaleAndTranslateGrad_T], scale: Annotated[Any, _atypes.Float32], translation: Annotated[Any, _atypes.Float32], kernel_type:str="lanczos3", antialias:bool=True, name=None) -> Annotated[Any, TV_ScaleAndTranslateGrad_T]: + r"""TODO: add doc. + + Args: + grads: A `Tensor`. Must be one of the following types: `float32`. + original_image: A `Tensor`. Must have the same type as `grads`. + scale: A `Tensor` of type `float32`. + translation: A `Tensor` of type `float32`. + kernel_type: An optional `string`. Defaults to `"lanczos3"`. + antialias: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grads`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScaleAndTranslateGrad", name, grads, original_image, scale, + translation, "kernel_type", kernel_type, "antialias", antialias) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return scale_and_translate_grad_eager_fallback( + grads, original_image, scale, translation, kernel_type=kernel_type, + antialias=antialias, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if kernel_type is None: + kernel_type = "lanczos3" + kernel_type = _execute.make_str(kernel_type, "kernel_type") + if antialias is None: + antialias = True + antialias = _execute.make_bool(antialias, "antialias") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScaleAndTranslateGrad", grads=grads, original_image=original_image, + scale=scale, translation=translation, + kernel_type=kernel_type, antialias=antialias, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "kernel_type", + _op.get_attr("kernel_type"), "antialias", + _op._get_attr_bool("antialias")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScaleAndTranslateGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScaleAndTranslateGrad = tf_export("raw_ops.ScaleAndTranslateGrad")(_ops.to_raw_op(scale_and_translate_grad)) + + +def scale_and_translate_grad_eager_fallback(grads: Annotated[Any, TV_ScaleAndTranslateGrad_T], original_image: Annotated[Any, TV_ScaleAndTranslateGrad_T], scale: Annotated[Any, _atypes.Float32], translation: Annotated[Any, _atypes.Float32], kernel_type: str, antialias: bool, name, ctx) -> Annotated[Any, TV_ScaleAndTranslateGrad_T]: + if kernel_type is None: + kernel_type = "lanczos3" + kernel_type = _execute.make_str(kernel_type, "kernel_type") + if antialias is None: + antialias = True + antialias = _execute.make_bool(antialias, "antialias") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grads, original_image], ctx, [_dtypes.float32, ]) + (grads, original_image) = _inputs_T + scale = _ops.convert_to_tensor(scale, _dtypes.float32) + translation = _ops.convert_to_tensor(translation, _dtypes.float32) + _inputs_flat = [grads, original_image, scale, translation] + _attrs = ("T", _attr_T, "kernel_type", kernel_type, "antialias", antialias) + _result = _execute.execute(b"ScaleAndTranslateGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScaleAndTranslateGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_StatelessSampleDistortedBoundingBoxOutput = collections.namedtuple( + "StatelessSampleDistortedBoundingBox", + ["begin", "size", "bboxes"]) + + +TV_StatelessSampleDistortedBoundingBox_T = TypeVar("TV_StatelessSampleDistortedBoundingBox_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) +TV_StatelessSampleDistortedBoundingBox_Tseed = TypeVar("TV_StatelessSampleDistortedBoundingBox_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_sample_distorted_bounding_box(image_size: Annotated[Any, TV_StatelessSampleDistortedBoundingBox_T], bounding_boxes: Annotated[Any, _atypes.Float32], min_object_covered: Annotated[Any, _atypes.Float32], seed: Annotated[Any, TV_StatelessSampleDistortedBoundingBox_Tseed], aspect_ratio_range=[0.75, 1.33], area_range=[0.05, 1], max_attempts:int=100, use_image_if_no_bounding_boxes:bool=False, name=None): + r"""Generate a randomly distorted bounding box for an image deterministically. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving its + content, i.e. *data augmentation*. This Op, given the same `seed`, + deterministically outputs a randomly distorted localization of an object, i.e. + bounding box, given an `image_size`, `bounding_boxes` and a series of + constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to visualize + what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + the height of the underlying image. + + The output of this Op is guaranteed to be the same given the same `seed` and is + independent of how many times the function is called, and independent of global + seed settings (e.g. `tf.random.set_seed`). + + Example usage: + + >>> image = np.array([[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]]) + >>> bbox = tf.constant( + ... [0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) + >>> seed = (1, 2) + >>> # Generate a single distorted bounding box. + >>> bbox_begin, bbox_size, bbox_draw = ( + ... tf.image.stateless_sample_distorted_bounding_box( + ... tf.shape(image), bounding_boxes=bbox, seed=seed)) + >>> # Employ the bounding box to distort the image. + >>> tf.slice(image, bbox_begin, bbox_size) + + >>> # Draw the bounding box in an image summary. + >>> colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + >>> tf.image.draw_bounding_boxes( + ... tf.expand_dims(tf.cast(image, tf.float32),0), bbox_draw, colors) + + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = true` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`. + 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. + 3-D with shape `[batch, N, 4]` describing the N bounding boxes + associated with the image. + min_object_covered: A `Tensor` of type `float32`. + The cropped area of the image must contain at least this + fraction of any bounding box supplied. The value of this parameter should be + non-negative. In the case of 0, the cropped area does not need to overlap + any of the bounding boxes supplied. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D with shape `[2]`. The seed to the random number generator. Must have dtype + `int32` or `int64`. (When using XLA, only `int32` is allowed.) + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, 1.33]`. + The cropped area of the image must have an aspect ratio = + width / height within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. + The cropped area of the image must contain a fraction of the + supplied image within this range. + max_attempts: An optional `int`. Defaults to `100`. + Number of attempts at generating a cropped region of the image + of the specified constraints. After `max_attempts` failures, return the entire + image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. + If true, assume an implicit bounding box covering the whole input. If false, + raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. + size: A `Tensor`. Has the same type as `image_size`. + bboxes: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessSampleDistortedBoundingBox", name, image_size, + bounding_boxes, min_object_covered, seed, "aspect_ratio_range", + aspect_ratio_range, "area_range", area_range, "max_attempts", + max_attempts, "use_image_if_no_bounding_boxes", + use_image_if_no_bounding_boxes) + _result = _StatelessSampleDistortedBoundingBoxOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_sample_distorted_bounding_box_eager_fallback( + image_size, bounding_boxes, min_object_covered, seed, + aspect_ratio_range=aspect_ratio_range, area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'stateless_sample_distorted_bounding_box' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'stateless_sample_distorted_bounding_box' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessSampleDistortedBoundingBox", image_size=image_size, + bounding_boxes=bounding_boxes, + min_object_covered=min_object_covered, + seed=seed, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tseed", + _op._get_attr_type("Tseed"), "aspect_ratio_range", + _op.get_attr("aspect_ratio_range"), "area_range", + _op.get_attr("area_range"), "max_attempts", + _op._get_attr_int("max_attempts"), + "use_image_if_no_bounding_boxes", + _op._get_attr_bool("use_image_if_no_bounding_boxes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessSampleDistortedBoundingBox", _inputs_flat, _attrs, _result) + _result = _StatelessSampleDistortedBoundingBoxOutput._make(_result) + return _result + +StatelessSampleDistortedBoundingBox = tf_export("raw_ops.StatelessSampleDistortedBoundingBox")(_ops.to_raw_op(stateless_sample_distorted_bounding_box)) + + +def stateless_sample_distorted_bounding_box_eager_fallback(image_size: Annotated[Any, TV_StatelessSampleDistortedBoundingBox_T], bounding_boxes: Annotated[Any, _atypes.Float32], min_object_covered: Annotated[Any, _atypes.Float32], seed: Annotated[Any, TV_StatelessSampleDistortedBoundingBox_Tseed], aspect_ratio_range, area_range, max_attempts: int, use_image_if_no_bounding_boxes: bool, name, ctx): + if aspect_ratio_range is None: + aspect_ratio_range = [0.75, 1.33] + if not isinstance(aspect_ratio_range, (list, tuple)): + raise TypeError( + "Expected list for 'aspect_ratio_range' argument to " + "'stateless_sample_distorted_bounding_box' Op, not %r." % aspect_ratio_range) + aspect_ratio_range = [_execute.make_float(_f, "aspect_ratio_range") for _f in aspect_ratio_range] + if area_range is None: + area_range = [0.05, 1] + if not isinstance(area_range, (list, tuple)): + raise TypeError( + "Expected list for 'area_range' argument to " + "'stateless_sample_distorted_bounding_box' Op, not %r." % area_range) + area_range = [_execute.make_float(_f, "area_range") for _f in area_range] + if max_attempts is None: + max_attempts = 100 + max_attempts = _execute.make_int(max_attempts, "max_attempts") + if use_image_if_no_bounding_boxes is None: + use_image_if_no_bounding_boxes = False + use_image_if_no_bounding_boxes = _execute.make_bool(use_image_if_no_bounding_boxes, "use_image_if_no_bounding_boxes") + _attr_T, (image_size,) = _execute.args_to_matching_eager([image_size], ctx, [_dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ]) + bounding_boxes = _ops.convert_to_tensor(bounding_boxes, _dtypes.float32) + min_object_covered = _ops.convert_to_tensor(min_object_covered, _dtypes.float32) + _inputs_flat = [image_size, bounding_boxes, min_object_covered, seed] + _attrs = ("T", _attr_T, "Tseed", _attr_Tseed, "aspect_ratio_range", + aspect_ratio_range, "area_range", area_range, "max_attempts", max_attempts, + "use_image_if_no_bounding_boxes", use_image_if_no_bounding_boxes) + _result = _execute.execute(b"StatelessSampleDistortedBoundingBox", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessSampleDistortedBoundingBox", _inputs_flat, _attrs, _result) + _result = _StatelessSampleDistortedBoundingBoxOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_io_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_io_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6a5c36a5ab6277b8c3ec54bbbfefdecb2e683f9b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_io_ops.py @@ -0,0 +1,2345 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def fixed_length_record_reader(record_bytes: int, header_bytes:int=0, footer_bytes:int=0, hop_bytes:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs fixed-length records from a file. + + Args: + record_bytes: An `int`. Number of bytes in the record. + header_bytes: An optional `int`. Defaults to `0`. + Number of bytes in the header, defaults to 0. + footer_bytes: An optional `int`. Defaults to `0`. + Number of bytes in the footer, defaults to 0. + hop_bytes: An optional `int`. Defaults to `0`. + Number of bytes to hop before each read. Default of 0 means using + record_bytes. + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("fixed_length_record_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + record_bytes = _execute.make_int(record_bytes, "record_bytes") + if header_bytes is None: + header_bytes = 0 + header_bytes = _execute.make_int(header_bytes, "header_bytes") + if footer_bytes is None: + footer_bytes = 0 + footer_bytes = _execute.make_int(footer_bytes, "footer_bytes") + if hop_bytes is None: + hop_bytes = 0 + hop_bytes = _execute.make_int(hop_bytes, "hop_bytes") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FixedLengthRecordReader", record_bytes=record_bytes, + header_bytes=header_bytes, + footer_bytes=footer_bytes, + hop_bytes=hop_bytes, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("header_bytes", _op._get_attr_int("header_bytes"), + "record_bytes", _op._get_attr_int("record_bytes"), + "footer_bytes", _op._get_attr_int("footer_bytes"), "hop_bytes", + _op._get_attr_int("hop_bytes"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FixedLengthRecordReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FixedLengthRecordReader = tf_export("raw_ops.FixedLengthRecordReader")(_ops.to_raw_op(fixed_length_record_reader)) + + +def fixed_length_record_reader_eager_fallback(record_bytes: int, header_bytes: int, footer_bytes: int, hop_bytes: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("fixed_length_record_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +def fixed_length_record_reader_v2(record_bytes: int, header_bytes:int=0, footer_bytes:int=0, hop_bytes:int=0, container:str="", shared_name:str="", encoding:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A Reader that outputs fixed-length records from a file. + + Args: + record_bytes: An `int`. Number of bytes in the record. + header_bytes: An optional `int`. Defaults to `0`. + Number of bytes in the header, defaults to 0. + footer_bytes: An optional `int`. Defaults to `0`. + Number of bytes in the footer, defaults to 0. + hop_bytes: An optional `int`. Defaults to `0`. + Number of bytes to hop before each read. Default of 0 means using + record_bytes. + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + encoding: An optional `string`. Defaults to `""`. + The type of encoding for the file. Currently ZLIB and GZIP + are supported. Defaults to none. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FixedLengthRecordReaderV2", name, "header_bytes", header_bytes, + "record_bytes", record_bytes, "footer_bytes", footer_bytes, + "hop_bytes", hop_bytes, "container", container, "shared_name", + shared_name, "encoding", encoding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fixed_length_record_reader_v2_eager_fallback( + header_bytes=header_bytes, record_bytes=record_bytes, + footer_bytes=footer_bytes, hop_bytes=hop_bytes, container=container, + shared_name=shared_name, encoding=encoding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + record_bytes = _execute.make_int(record_bytes, "record_bytes") + if header_bytes is None: + header_bytes = 0 + header_bytes = _execute.make_int(header_bytes, "header_bytes") + if footer_bytes is None: + footer_bytes = 0 + footer_bytes = _execute.make_int(footer_bytes, "footer_bytes") + if hop_bytes is None: + hop_bytes = 0 + hop_bytes = _execute.make_int(hop_bytes, "hop_bytes") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FixedLengthRecordReaderV2", record_bytes=record_bytes, + header_bytes=header_bytes, + footer_bytes=footer_bytes, + hop_bytes=hop_bytes, container=container, + shared_name=shared_name, + encoding=encoding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("header_bytes", _op._get_attr_int("header_bytes"), + "record_bytes", _op._get_attr_int("record_bytes"), + "footer_bytes", _op._get_attr_int("footer_bytes"), "hop_bytes", + _op._get_attr_int("hop_bytes"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "encoding", + _op.get_attr("encoding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FixedLengthRecordReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FixedLengthRecordReaderV2 = tf_export("raw_ops.FixedLengthRecordReaderV2")(_ops.to_raw_op(fixed_length_record_reader_v2)) + + +def fixed_length_record_reader_v2_eager_fallback(record_bytes: int, header_bytes: int, footer_bytes: int, hop_bytes: int, container: str, shared_name: str, encoding: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + record_bytes = _execute.make_int(record_bytes, "record_bytes") + if header_bytes is None: + header_bytes = 0 + header_bytes = _execute.make_int(header_bytes, "header_bytes") + if footer_bytes is None: + footer_bytes = 0 + footer_bytes = _execute.make_int(footer_bytes, "footer_bytes") + if hop_bytes is None: + hop_bytes = 0 + hop_bytes = _execute.make_int(hop_bytes, "hop_bytes") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + _inputs_flat = [] + _attrs = ("header_bytes", header_bytes, "record_bytes", record_bytes, + "footer_bytes", footer_bytes, "hop_bytes", hop_bytes, "container", + container, "shared_name", shared_name, "encoding", encoding) + _result = _execute.execute(b"FixedLengthRecordReaderV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FixedLengthRecordReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def identity_reader(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs the queued work as both the key and value. + + To use, enqueue strings in a Queue. ReaderRead will take the front + work string and output (work, work). + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("identity_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IdentityReader", container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IdentityReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IdentityReader = tf_export("raw_ops.IdentityReader")(_ops.to_raw_op(identity_reader)) + + +def identity_reader_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("identity_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +def identity_reader_v2(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A Reader that outputs the queued work as both the key and value. + + To use, enqueue strings in a Queue. ReaderRead will take the front + work string and output (work, work). + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IdentityReaderV2", name, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return identity_reader_v2_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IdentityReaderV2", container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IdentityReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IdentityReaderV2 = tf_export("raw_ops.IdentityReaderV2")(_ops.to_raw_op(identity_reader_v2)) + + +def identity_reader_v2_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"IdentityReaderV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IdentityReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def lmdb_reader(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs the records from a LMDB file. + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lmdb_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LMDBReader", container=container, shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LMDBReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LMDBReader = tf_export("raw_ops.LMDBReader")(_ops.to_raw_op(lmdb_reader)) + + +def lmdb_reader_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("lmdb_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.matching_files', v1=['io.matching_files', 'matching_files']) +@deprecated_endpoints('matching_files') +def matching_files(pattern: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Returns the set of files matching one or more glob patterns. + + Note that this routine only supports wildcard characters in the + basename portion of the pattern, not in the directory portion. + Note also that the order of filenames returned is deterministic. + + Args: + pattern: A `Tensor` of type `string`. + Shell wildcard pattern(s). Scalar or vector of type string. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatchingFiles", name, pattern) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matching_files( + (pattern, name,), None) + if _result is not NotImplemented: + return _result + return matching_files_eager_fallback( + pattern, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matching_files, (), dict(pattern=pattern, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matching_files( + (pattern, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatchingFiles", pattern=pattern, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matching_files, (), dict(pattern=pattern, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatchingFiles", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatchingFiles = tf_export("raw_ops.MatchingFiles")(_ops.to_raw_op(matching_files)) +_dispatcher_for_matching_files = matching_files._tf_type_based_dispatcher.Dispatch + + +def matching_files_eager_fallback(pattern: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + pattern = _ops.convert_to_tensor(pattern, _dtypes.string) + _inputs_flat = [pattern] + _attrs = None + _result = _execute.execute(b"MatchingFiles", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatchingFiles", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def merge_v2_checkpoints(checkpoint_prefixes: Annotated[Any, _atypes.String], destination_prefix: Annotated[Any, _atypes.String], delete_old_dirs:bool=True, allow_missing_files:bool=False, name=None): + r"""V2 format specific: merges the metadata files of sharded checkpoints. The + + result is one logical checkpoint, with one physical metadata file and renamed + data files. + + Intended for "grouping" multiple checkpoints in a sharded checkpoint setup. + + If delete_old_dirs is true, attempts to delete recursively the dirname of each + path in the input checkpoint_prefixes. This is useful when those paths are non + user-facing temporary locations. + + If allow_missing_files is true, merges the checkpoint prefixes as long as + at least one file exists. Otherwise, if no files exist, an error will be thrown. + The default value for allow_missing_files is false. + + Args: + checkpoint_prefixes: A `Tensor` of type `string`. + prefixes of V2 checkpoints to merge. + destination_prefix: A `Tensor` of type `string`. + scalar. The desired final prefix. Allowed to be the same + as one of the checkpoint_prefixes. + delete_old_dirs: An optional `bool`. Defaults to `True`. see above. + allow_missing_files: An optional `bool`. Defaults to `False`. see above. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MergeV2Checkpoints", name, checkpoint_prefixes, + destination_prefix, "delete_old_dirs", delete_old_dirs, + "allow_missing_files", allow_missing_files) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return merge_v2_checkpoints_eager_fallback( + checkpoint_prefixes, destination_prefix, + delete_old_dirs=delete_old_dirs, + allow_missing_files=allow_missing_files, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if delete_old_dirs is None: + delete_old_dirs = True + delete_old_dirs = _execute.make_bool(delete_old_dirs, "delete_old_dirs") + if allow_missing_files is None: + allow_missing_files = False + allow_missing_files = _execute.make_bool(allow_missing_files, "allow_missing_files") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MergeV2Checkpoints", checkpoint_prefixes=checkpoint_prefixes, + destination_prefix=destination_prefix, + delete_old_dirs=delete_old_dirs, + allow_missing_files=allow_missing_files, + name=name) + return _op +MergeV2Checkpoints = tf_export("raw_ops.MergeV2Checkpoints")(_ops.to_raw_op(merge_v2_checkpoints)) + + +def merge_v2_checkpoints_eager_fallback(checkpoint_prefixes: Annotated[Any, _atypes.String], destination_prefix: Annotated[Any, _atypes.String], delete_old_dirs: bool, allow_missing_files: bool, name, ctx): + if delete_old_dirs is None: + delete_old_dirs = True + delete_old_dirs = _execute.make_bool(delete_old_dirs, "delete_old_dirs") + if allow_missing_files is None: + allow_missing_files = False + allow_missing_files = _execute.make_bool(allow_missing_files, "allow_missing_files") + checkpoint_prefixes = _ops.convert_to_tensor(checkpoint_prefixes, _dtypes.string) + destination_prefix = _ops.convert_to_tensor(destination_prefix, _dtypes.string) + _inputs_flat = [checkpoint_prefixes, destination_prefix] + _attrs = ("delete_old_dirs", delete_old_dirs, "allow_missing_files", + allow_missing_files) + _result = _execute.execute(b"MergeV2Checkpoints", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def read_file(filename: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Reads and outputs the entire contents of the input filename. + + Args: + filename: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReadFile", name, filename) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return read_file_eager_fallback( + filename, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReadFile", filename=filename, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReadFile", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReadFile = tf_export("raw_ops.ReadFile")(_ops.to_raw_op(read_file)) + + +def read_file_eager_fallback(filename: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + filename = _ops.convert_to_tensor(filename, _dtypes.string) + _inputs_flat = [filename] + _attrs = None + _result = _execute.execute(b"ReadFile", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReadFile", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def reader_num_records_produced(reader_handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the number of records this Reader has produced. + + This is the same as the number of ReaderRead executions that have + succeeded. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_num_records_produced op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderNumRecordsProduced", reader_handle=reader_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderNumRecordsProduced", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderNumRecordsProduced = tf_export("raw_ops.ReaderNumRecordsProduced")(_ops.to_raw_op(reader_num_records_produced)) + + +def reader_num_records_produced_eager_fallback(reader_handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int64]: + raise RuntimeError("reader_num_records_produced op does not support eager execution. Arg 'reader_handle' is a ref.") + +def reader_num_records_produced_v2(reader_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the number of records this Reader has produced. + + This is the same as the number of ReaderRead executions that have + succeeded. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderNumRecordsProducedV2", name, reader_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_num_records_produced_v2_eager_fallback( + reader_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderNumRecordsProducedV2", reader_handle=reader_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderNumRecordsProducedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderNumRecordsProducedV2 = tf_export("raw_ops.ReaderNumRecordsProducedV2")(_ops.to_raw_op(reader_num_records_produced_v2)) + + +def reader_num_records_produced_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Int64]: + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + _inputs_flat = [reader_handle] + _attrs = None + _result = _execute.execute(b"ReaderNumRecordsProducedV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReaderNumRecordsProducedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def reader_num_work_units_completed(reader_handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the number of work units this Reader has finished processing. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_num_work_units_completed op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderNumWorkUnitsCompleted", reader_handle=reader_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderNumWorkUnitsCompleted", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderNumWorkUnitsCompleted = tf_export("raw_ops.ReaderNumWorkUnitsCompleted")(_ops.to_raw_op(reader_num_work_units_completed)) + + +def reader_num_work_units_completed_eager_fallback(reader_handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int64]: + raise RuntimeError("reader_num_work_units_completed op does not support eager execution. Arg 'reader_handle' is a ref.") + +def reader_num_work_units_completed_v2(reader_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Returns the number of work units this Reader has finished processing. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderNumWorkUnitsCompletedV2", name, reader_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_num_work_units_completed_v2_eager_fallback( + reader_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderNumWorkUnitsCompletedV2", reader_handle=reader_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderNumWorkUnitsCompletedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderNumWorkUnitsCompletedV2 = tf_export("raw_ops.ReaderNumWorkUnitsCompletedV2")(_ops.to_raw_op(reader_num_work_units_completed_v2)) + + +def reader_num_work_units_completed_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Int64]: + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + _inputs_flat = [reader_handle] + _attrs = None + _result = _execute.execute(b"ReaderNumWorkUnitsCompletedV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReaderNumWorkUnitsCompletedV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_ReaderReadOutput = collections.namedtuple( + "ReaderRead", + ["key", "value"]) + + +def reader_read(reader_handle: Annotated[Any, _atypes.String], queue_handle: Annotated[Any, _atypes.String], name=None): + r"""Returns the next record (key, value pair) produced by a Reader. + + Will dequeue from the input queue if necessary (e.g. when the + Reader needs to start reading from a new file since it has finished + with the previous file). + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + queue_handle: A `Tensor` of type mutable `string`. + Handle to a Queue, with string work items. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, value). + + key: A `Tensor` of type `string`. + value: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_read op does not support eager execution. Arg 'queue_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderRead", reader_handle=reader_handle, queue_handle=queue_handle, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderRead", _inputs_flat, _attrs, _result) + _result = _ReaderReadOutput._make(_result) + return _result + +ReaderRead = tf_export("raw_ops.ReaderRead")(_ops.to_raw_op(reader_read)) + + +def reader_read_eager_fallback(reader_handle: Annotated[Any, _atypes.String], queue_handle: Annotated[Any, _atypes.String], name, ctx): + raise RuntimeError("reader_read op does not support eager execution. Arg 'queue_handle' is a ref.") +_ReaderReadUpToOutput = collections.namedtuple( + "ReaderReadUpTo", + ["keys", "values"]) + + +def reader_read_up_to(reader_handle: Annotated[Any, _atypes.String], queue_handle: Annotated[Any, _atypes.String], num_records: Annotated[Any, _atypes.Int64], name=None): + r"""Returns up to `num_records` (key, value) pairs produced by a Reader. + + Will dequeue from the input queue if necessary (e.g. when the + Reader needs to start reading from a new file since it has finished + with the previous file). + It may return less than `num_records` even before the last batch. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a `Reader`. + queue_handle: A `Tensor` of type mutable `string`. + Handle to a `Queue`, with string work items. + num_records: A `Tensor` of type `int64`. + number of records to read from `Reader`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (keys, values). + + keys: A `Tensor` of type `string`. + values: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_read_up_to op does not support eager execution. Arg 'queue_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderReadUpTo", reader_handle=reader_handle, + queue_handle=queue_handle, num_records=num_records, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderReadUpTo", _inputs_flat, _attrs, _result) + _result = _ReaderReadUpToOutput._make(_result) + return _result + +ReaderReadUpTo = tf_export("raw_ops.ReaderReadUpTo")(_ops.to_raw_op(reader_read_up_to)) + + +def reader_read_up_to_eager_fallback(reader_handle: Annotated[Any, _atypes.String], queue_handle: Annotated[Any, _atypes.String], num_records: Annotated[Any, _atypes.Int64], name, ctx): + raise RuntimeError("reader_read_up_to op does not support eager execution. Arg 'queue_handle' is a ref.") +_ReaderReadUpToV2Output = collections.namedtuple( + "ReaderReadUpToV2", + ["keys", "values"]) + + +def reader_read_up_to_v2(reader_handle: Annotated[Any, _atypes.Resource], queue_handle: Annotated[Any, _atypes.Resource], num_records: Annotated[Any, _atypes.Int64], name=None): + r"""Returns up to `num_records` (key, value) pairs produced by a Reader. + + Will dequeue from the input queue if necessary (e.g. when the + Reader needs to start reading from a new file since it has finished + with the previous file). + It may return less than `num_records` even before the last batch. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a `Reader`. + queue_handle: A `Tensor` of type `resource`. + Handle to a `Queue`, with string work items. + num_records: A `Tensor` of type `int64`. + number of records to read from `Reader`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (keys, values). + + keys: A `Tensor` of type `string`. + values: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderReadUpToV2", name, reader_handle, queue_handle, + num_records) + _result = _ReaderReadUpToV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_read_up_to_v2_eager_fallback( + reader_handle, queue_handle, num_records, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderReadUpToV2", reader_handle=reader_handle, + queue_handle=queue_handle, + num_records=num_records, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderReadUpToV2", _inputs_flat, _attrs, _result) + _result = _ReaderReadUpToV2Output._make(_result) + return _result + +ReaderReadUpToV2 = tf_export("raw_ops.ReaderReadUpToV2")(_ops.to_raw_op(reader_read_up_to_v2)) + + +def reader_read_up_to_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], queue_handle: Annotated[Any, _atypes.Resource], num_records: Annotated[Any, _atypes.Int64], name, ctx): + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + queue_handle = _ops.convert_to_tensor(queue_handle, _dtypes.resource) + num_records = _ops.convert_to_tensor(num_records, _dtypes.int64) + _inputs_flat = [reader_handle, queue_handle, num_records] + _attrs = None + _result = _execute.execute(b"ReaderReadUpToV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReaderReadUpToV2", _inputs_flat, _attrs, _result) + _result = _ReaderReadUpToV2Output._make(_result) + return _result + +_ReaderReadV2Output = collections.namedtuple( + "ReaderReadV2", + ["key", "value"]) + + +def reader_read_v2(reader_handle: Annotated[Any, _atypes.Resource], queue_handle: Annotated[Any, _atypes.Resource], name=None): + r"""Returns the next record (key, value pair) produced by a Reader. + + Will dequeue from the input queue if necessary (e.g. when the + Reader needs to start reading from a new file since it has finished + with the previous file). + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + queue_handle: A `Tensor` of type `resource`. + Handle to a Queue, with string work items. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, value). + + key: A `Tensor` of type `string`. + value: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderReadV2", name, reader_handle, queue_handle) + _result = _ReaderReadV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_read_v2_eager_fallback( + reader_handle, queue_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderReadV2", reader_handle=reader_handle, + queue_handle=queue_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderReadV2", _inputs_flat, _attrs, _result) + _result = _ReaderReadV2Output._make(_result) + return _result + +ReaderReadV2 = tf_export("raw_ops.ReaderReadV2")(_ops.to_raw_op(reader_read_v2)) + + +def reader_read_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], queue_handle: Annotated[Any, _atypes.Resource], name, ctx): + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + queue_handle = _ops.convert_to_tensor(queue_handle, _dtypes.resource) + _inputs_flat = [reader_handle, queue_handle] + _attrs = None + _result = _execute.execute(b"ReaderReadV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReaderReadV2", _inputs_flat, _attrs, _result) + _result = _ReaderReadV2Output._make(_result) + return _result + + +def reader_reset(reader_handle: Annotated[Any, _atypes.String], name=None): + r"""Restore a Reader to its initial clean state. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_reset op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderReset", reader_handle=reader_handle, name=name) + return _op +ReaderReset = tf_export("raw_ops.ReaderReset")(_ops.to_raw_op(reader_reset)) + + +def reader_reset_eager_fallback(reader_handle: Annotated[Any, _atypes.String], name, ctx): + raise RuntimeError("reader_reset op does not support eager execution. Arg 'reader_handle' is a ref.") + +def reader_reset_v2(reader_handle: Annotated[Any, _atypes.Resource], name=None): + r"""Restore a Reader to its initial clean state. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderResetV2", name, reader_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_reset_v2_eager_fallback( + reader_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderResetV2", reader_handle=reader_handle, name=name) + return _op +ReaderResetV2 = tf_export("raw_ops.ReaderResetV2")(_ops.to_raw_op(reader_reset_v2)) + + +def reader_reset_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], name, ctx): + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + _inputs_flat = [reader_handle] + _attrs = None + _result = _execute.execute(b"ReaderResetV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def reader_restore_state(reader_handle: Annotated[Any, _atypes.String], state: Annotated[Any, _atypes.String], name=None): + r"""Restore a reader to a previously saved state. + + Not all Readers support being restored, so this can produce an + Unimplemented error. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + state: A `Tensor` of type `string`. + Result of a ReaderSerializeState of a Reader with type + matching reader_handle. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_restore_state op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderRestoreState", reader_handle=reader_handle, state=state, + name=name) + return _op +ReaderRestoreState = tf_export("raw_ops.ReaderRestoreState")(_ops.to_raw_op(reader_restore_state)) + + +def reader_restore_state_eager_fallback(reader_handle: Annotated[Any, _atypes.String], state: Annotated[Any, _atypes.String], name, ctx): + raise RuntimeError("reader_restore_state op does not support eager execution. Arg 'reader_handle' is a ref.") + +def reader_restore_state_v2(reader_handle: Annotated[Any, _atypes.Resource], state: Annotated[Any, _atypes.String], name=None): + r"""Restore a reader to a previously saved state. + + Not all Readers support being restored, so this can produce an + Unimplemented error. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + state: A `Tensor` of type `string`. + Result of a ReaderSerializeState of a Reader with type + matching reader_handle. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderRestoreStateV2", name, reader_handle, state) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_restore_state_v2_eager_fallback( + reader_handle, state, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderRestoreStateV2", reader_handle=reader_handle, state=state, + name=name) + return _op +ReaderRestoreStateV2 = tf_export("raw_ops.ReaderRestoreStateV2")(_ops.to_raw_op(reader_restore_state_v2)) + + +def reader_restore_state_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], state: Annotated[Any, _atypes.String], name, ctx): + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + state = _ops.convert_to_tensor(state, _dtypes.string) + _inputs_flat = [reader_handle, state] + _attrs = None + _result = _execute.execute(b"ReaderRestoreStateV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def reader_serialize_state(reader_handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Produce a string tensor that encodes the state of a Reader. + + Not all Readers support being serialized, so this can produce an + Unimplemented error. + + Args: + reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("reader_serialize_state op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderSerializeState", reader_handle=reader_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderSerializeState", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderSerializeState = tf_export("raw_ops.ReaderSerializeState")(_ops.to_raw_op(reader_serialize_state)) + + +def reader_serialize_state_eager_fallback(reader_handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("reader_serialize_state op does not support eager execution. Arg 'reader_handle' is a ref.") + +def reader_serialize_state_v2(reader_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.String]: + r"""Produce a string tensor that encodes the state of a Reader. + + Not all Readers support being serialized, so this can produce an + Unimplemented error. + + Args: + reader_handle: A `Tensor` of type `resource`. Handle to a Reader. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReaderSerializeStateV2", name, reader_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reader_serialize_state_v2_eager_fallback( + reader_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReaderSerializeStateV2", reader_handle=reader_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReaderSerializeStateV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReaderSerializeStateV2 = tf_export("raw_ops.ReaderSerializeStateV2")(_ops.to_raw_op(reader_serialize_state_v2)) + + +def reader_serialize_state_v2_eager_fallback(reader_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.String]: + reader_handle = _ops.convert_to_tensor(reader_handle, _dtypes.resource) + _inputs_flat = [reader_handle] + _attrs = None + _result = _execute.execute(b"ReaderSerializeStateV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReaderSerializeStateV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Restore_dt = TypeVar("TV_Restore_dt", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def restore(file_pattern: Annotated[Any, _atypes.String], tensor_name: Annotated[Any, _atypes.String], dt: TV_Restore_dt, preferred_shard:int=-1, name=None) -> Annotated[Any, TV_Restore_dt]: + r"""Restores a tensor from checkpoint files. + + Reads a tensor stored in one or several files. If there are several files (for + instance because a tensor was saved as slices), `file_pattern` may contain + wildcard symbols (`*` and `?`) in the filename portion only, not in the + directory portion. + + If a `file_pattern` matches several files, `preferred_shard` can be used to hint + in which file the requested tensor is likely to be found. This op will first + open the file at index `preferred_shard` in the list of matching files and try + to restore tensors from that file. Only if some tensors or tensor slices are + not found in that first file, then the Op opens all the files. Setting + `preferred_shard` to match the value passed as the `shard` input + of a matching `Save` Op may speed up Restore. This attribute only affects + performance, not correctness. The default value -1 means files are processed in + order. + + See also `RestoreSlice`. + + Args: + file_pattern: A `Tensor` of type `string`. + Must have a single element. The pattern of the files from + which we read the tensor. + tensor_name: A `Tensor` of type `string`. + Must have a single element. The name of the tensor to be + restored. + dt: A `tf.DType`. The type of the tensor to be restored. + preferred_shard: An optional `int`. Defaults to `-1`. + Index of file to open first if multiple files match + `file_pattern`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dt`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Restore", name, file_pattern, tensor_name, "dt", dt, + "preferred_shard", preferred_shard) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return restore_eager_fallback( + file_pattern, tensor_name, dt=dt, preferred_shard=preferred_shard, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dt = _execute.make_type(dt, "dt") + if preferred_shard is None: + preferred_shard = -1 + preferred_shard = _execute.make_int(preferred_shard, "preferred_shard") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Restore", file_pattern=file_pattern, tensor_name=tensor_name, dt=dt, + preferred_shard=preferred_shard, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dt", _op._get_attr_type("dt"), "preferred_shard", + _op._get_attr_int("preferred_shard")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Restore", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Restore = tf_export("raw_ops.Restore")(_ops.to_raw_op(restore)) + + +def restore_eager_fallback(file_pattern: Annotated[Any, _atypes.String], tensor_name: Annotated[Any, _atypes.String], dt: TV_Restore_dt, preferred_shard: int, name, ctx) -> Annotated[Any, TV_Restore_dt]: + dt = _execute.make_type(dt, "dt") + if preferred_shard is None: + preferred_shard = -1 + preferred_shard = _execute.make_int(preferred_shard, "preferred_shard") + file_pattern = _ops.convert_to_tensor(file_pattern, _dtypes.string) + tensor_name = _ops.convert_to_tensor(tensor_name, _dtypes.string) + _inputs_flat = [file_pattern, tensor_name] + _attrs = ("dt", dt, "preferred_shard", preferred_shard) + _result = _execute.execute(b"Restore", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Restore", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RestoreSlice_dt = TypeVar("TV_RestoreSlice_dt", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def restore_slice(file_pattern: Annotated[Any, _atypes.String], tensor_name: Annotated[Any, _atypes.String], shape_and_slice: Annotated[Any, _atypes.String], dt: TV_RestoreSlice_dt, preferred_shard:int=-1, name=None) -> Annotated[Any, TV_RestoreSlice_dt]: + r"""Restores a tensor from checkpoint files. + + This is like `Restore` except that restored tensor can be listed as filling + only a slice of a larger tensor. `shape_and_slice` specifies the shape of the + larger tensor and the slice that the restored tensor covers. + + The `shape_and_slice` input has the same format as the + elements of the `shapes_and_slices` input of the `SaveSlices` op. + + Args: + file_pattern: A `Tensor` of type `string`. + Must have a single element. The pattern of the files from + which we read the tensor. + tensor_name: A `Tensor` of type `string`. + Must have a single element. The name of the tensor to be + restored. + shape_and_slice: A `Tensor` of type `string`. + Scalar. The shapes and slice specifications to use when + restoring a tensors. + dt: A `tf.DType`. The type of the tensor to be restored. + preferred_shard: An optional `int`. Defaults to `-1`. + Index of file to open first if multiple files match + `file_pattern`. See the documentation for `Restore`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dt`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RestoreSlice", name, file_pattern, tensor_name, + shape_and_slice, "dt", dt, "preferred_shard", preferred_shard) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return restore_slice_eager_fallback( + file_pattern, tensor_name, shape_and_slice, dt=dt, + preferred_shard=preferred_shard, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dt = _execute.make_type(dt, "dt") + if preferred_shard is None: + preferred_shard = -1 + preferred_shard = _execute.make_int(preferred_shard, "preferred_shard") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RestoreSlice", file_pattern=file_pattern, tensor_name=tensor_name, + shape_and_slice=shape_and_slice, dt=dt, + preferred_shard=preferred_shard, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dt", _op._get_attr_type("dt"), "preferred_shard", + _op._get_attr_int("preferred_shard")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RestoreSlice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RestoreSlice = tf_export("raw_ops.RestoreSlice")(_ops.to_raw_op(restore_slice)) + + +def restore_slice_eager_fallback(file_pattern: Annotated[Any, _atypes.String], tensor_name: Annotated[Any, _atypes.String], shape_and_slice: Annotated[Any, _atypes.String], dt: TV_RestoreSlice_dt, preferred_shard: int, name, ctx) -> Annotated[Any, TV_RestoreSlice_dt]: + dt = _execute.make_type(dt, "dt") + if preferred_shard is None: + preferred_shard = -1 + preferred_shard = _execute.make_int(preferred_shard, "preferred_shard") + file_pattern = _ops.convert_to_tensor(file_pattern, _dtypes.string) + tensor_name = _ops.convert_to_tensor(tensor_name, _dtypes.string) + shape_and_slice = _ops.convert_to_tensor(shape_and_slice, _dtypes.string) + _inputs_flat = [file_pattern, tensor_name, shape_and_slice] + _attrs = ("dt", dt, "preferred_shard", preferred_shard) + _result = _execute.execute(b"RestoreSlice", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RestoreSlice", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def restore_v2(prefix: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shape_and_slices: Annotated[Any, _atypes.String], dtypes, name=None): + r"""Restores tensors from a V2 checkpoint. + + For backward compatibility with the V1 format, this Op currently allows + restoring from a V1 checkpoint as well: + - This Op first attempts to find the V2 index file pointed to by "prefix", and + if found proceed to read it as a V2 checkpoint; + - Otherwise the V1 read path is invoked. + Relying on this behavior is not recommended, as the ability to fall back to read + V1 might be deprecated and eventually removed. + + By default, restores the named tensors in full. If the caller wishes to restore + specific slices of stored tensors, "shape_and_slices" should be non-empty + strings and correspondingly well-formed. + + Callers must ensure all the named tensors are indeed stored in the checkpoint. + + Args: + prefix: A `Tensor` of type `string`. + Must have a single element. The prefix of a V2 checkpoint. + tensor_names: A `Tensor` of type `string`. + shape {N}. The names of the tensors to be restored. + shape_and_slices: A `Tensor` of type `string`. + shape {N}. The slice specs of the tensors to be restored. + Empty strings indicate that they are non-partitioned tensors. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + shape {N}. The list of expected dtype for the tensors. Must match + those stored in the checkpoint. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RestoreV2", name, prefix, tensor_names, shape_and_slices, + "dtypes", dtypes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return restore_v2_eager_fallback( + prefix, tensor_names, shape_and_slices, dtypes=dtypes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'restore_v2' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RestoreV2", prefix=prefix, tensor_names=tensor_names, + shape_and_slices=shape_and_slices, dtypes=dtypes, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("dtypes", _op.get_attr("dtypes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RestoreV2", _inputs_flat, _attrs, _result) + return _result + +RestoreV2 = tf_export("raw_ops.RestoreV2")(_ops.to_raw_op(restore_v2)) + + +def restore_v2_eager_fallback(prefix: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shape_and_slices: Annotated[Any, _atypes.String], dtypes, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'restore_v2' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + prefix = _ops.convert_to_tensor(prefix, _dtypes.string) + tensor_names = _ops.convert_to_tensor(tensor_names, _dtypes.string) + shape_and_slices = _ops.convert_to_tensor(shape_and_slices, _dtypes.string) + _inputs_flat = [prefix, tensor_names, shape_and_slices] + _attrs = ("dtypes", dtypes) + _result = _execute.execute(b"RestoreV2", len(dtypes), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RestoreV2", _inputs_flat, _attrs, _result) + return _result + + +def save(filename: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], data, name=None): + r"""Saves the input tensors to disk. + + The size of `tensor_names` must match the number of tensors in `data`. `data[i]` + is written to `filename` with name `tensor_names[i]`. + + See also `SaveSlices`. + + Args: + filename: A `Tensor` of type `string`. + Must have a single element. The name of the file to which we write + the tensor. + tensor_names: A `Tensor` of type `string`. + Shape `[N]`. The names of the tensors to be saved. + data: A list of `Tensor` objects. `N` tensors to save. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Save", name, filename, tensor_names, data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return save_eager_fallback( + filename, tensor_names, data, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Save", filename=filename, tensor_names=tensor_names, data=data, + name=name) + return _op +Save = tf_export("raw_ops.Save")(_ops.to_raw_op(save)) + + +def save_eager_fallback(filename: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], data, name, ctx): + _attr_T, data = _execute.convert_to_mixed_eager_tensors(data, ctx) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + tensor_names = _ops.convert_to_tensor(tensor_names, _dtypes.string) + _inputs_flat = [filename, tensor_names] + list(data) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Save", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +def save_slices(filename: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shapes_and_slices: Annotated[Any, _atypes.String], data, name=None): + r"""Saves input tensors slices to disk. + + This is like `Save` except that tensors can be listed in the saved file as being + a slice of a larger tensor. `shapes_and_slices` specifies the shape of the + larger tensor and the slice that this tensor covers. `shapes_and_slices` must + have as many elements as `tensor_names`. + + Elements of the `shapes_and_slices` input must either be: + + * The empty string, in which case the corresponding tensor is + saved normally. + * A string of the form `dim0 dim1 ... dimN-1 slice-spec` where the + `dimI` are the dimensions of the larger tensor and `slice-spec` + specifies what part is covered by the tensor to save. + + `slice-spec` itself is a `:`-separated list: `slice0:slice1:...:sliceN-1` + where each `sliceI` is either: + + * The string `-` meaning that the slice covers all indices of this dimension + * `start,length` where `start` and `length` are integers. In that + case the slice covers `length` indices starting at `start`. + + See also `Save`. + + Args: + filename: A `Tensor` of type `string`. + Must have a single element. The name of the file to which we write the + tensor. + tensor_names: A `Tensor` of type `string`. + Shape `[N]`. The names of the tensors to be saved. + shapes_and_slices: A `Tensor` of type `string`. + Shape `[N]`. The shapes and slice specifications to use when + saving the tensors. + data: A list of `Tensor` objects. `N` tensors to save. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SaveSlices", name, filename, tensor_names, shapes_and_slices, + data) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return save_slices_eager_fallback( + filename, tensor_names, shapes_and_slices, data, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SaveSlices", filename=filename, tensor_names=tensor_names, + shapes_and_slices=shapes_and_slices, data=data, + name=name) + return _op +SaveSlices = tf_export("raw_ops.SaveSlices")(_ops.to_raw_op(save_slices)) + + +def save_slices_eager_fallback(filename: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shapes_and_slices: Annotated[Any, _atypes.String], data, name, ctx): + _attr_T, data = _execute.convert_to_mixed_eager_tensors(data, ctx) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + tensor_names = _ops.convert_to_tensor(tensor_names, _dtypes.string) + shapes_and_slices = _ops.convert_to_tensor(shapes_and_slices, _dtypes.string) + _inputs_flat = [filename, tensor_names, shapes_and_slices] + list(data) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SaveSlices", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def save_v2(prefix: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shape_and_slices: Annotated[Any, _atypes.String], tensors, name=None): + r"""Saves tensors in V2 checkpoint format. + + By default, saves the named tensors in full. If the caller wishes to save + specific slices of full tensors, "shape_and_slices" should be non-empty strings + and correspondingly well-formed. + + Args: + prefix: A `Tensor` of type `string`. + Must have a single element. The prefix of the V2 checkpoint to which we + write the tensors. + tensor_names: A `Tensor` of type `string`. + shape {N}. The names of the tensors to be saved. + shape_and_slices: A `Tensor` of type `string`. + shape {N}. The slice specs of the tensors to be saved. + Empty strings indicate that they are non-partitioned tensors. + tensors: A list of `Tensor` objects. `N` tensors to save. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SaveV2", name, prefix, tensor_names, shape_and_slices, tensors) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return save_v2_eager_fallback( + prefix, tensor_names, shape_and_slices, tensors, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SaveV2", prefix=prefix, tensor_names=tensor_names, + shape_and_slices=shape_and_slices, tensors=tensors, + name=name) + return _op +SaveV2 = tf_export("raw_ops.SaveV2")(_ops.to_raw_op(save_v2)) + + +def save_v2_eager_fallback(prefix: Annotated[Any, _atypes.String], tensor_names: Annotated[Any, _atypes.String], shape_and_slices: Annotated[Any, _atypes.String], tensors, name, ctx): + _attr_dtypes, tensors = _execute.convert_to_mixed_eager_tensors(tensors, ctx) + prefix = _ops.convert_to_tensor(prefix, _dtypes.string) + tensor_names = _ops.convert_to_tensor(tensor_names, _dtypes.string) + shape_and_slices = _ops.convert_to_tensor(shape_and_slices, _dtypes.string) + _inputs_flat = [prefix, tensor_names, shape_and_slices] + list(tensors) + _attrs = ("dtypes", _attr_dtypes) + _result = _execute.execute(b"SaveV2", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +def sharded_filename(basename: Annotated[Any, _atypes.String], shard: Annotated[Any, _atypes.Int32], num_shards: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.String]: + r"""Generate a sharded filename. The filename is printf formatted as + + %s-%05d-of-%05d, basename, shard, num_shards. + + Args: + basename: A `Tensor` of type `string`. + shard: A `Tensor` of type `int32`. + num_shards: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShardedFilename", name, basename, shard, num_shards) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sharded_filename_eager_fallback( + basename, shard, num_shards, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShardedFilename", basename=basename, shard=shard, + num_shards=num_shards, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShardedFilename", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShardedFilename = tf_export("raw_ops.ShardedFilename")(_ops.to_raw_op(sharded_filename)) + + +def sharded_filename_eager_fallback(basename: Annotated[Any, _atypes.String], shard: Annotated[Any, _atypes.Int32], num_shards: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.String]: + basename = _ops.convert_to_tensor(basename, _dtypes.string) + shard = _ops.convert_to_tensor(shard, _dtypes.int32) + num_shards = _ops.convert_to_tensor(num_shards, _dtypes.int32) + _inputs_flat = [basename, shard, num_shards] + _attrs = None + _result = _execute.execute(b"ShardedFilename", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShardedFilename", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sharded_filespec(basename: Annotated[Any, _atypes.String], num_shards: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.String]: + r"""Generate a glob pattern matching all sharded file names. + + Args: + basename: A `Tensor` of type `string`. + num_shards: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShardedFilespec", name, basename, num_shards) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sharded_filespec_eager_fallback( + basename, num_shards, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShardedFilespec", basename=basename, num_shards=num_shards, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ShardedFilespec", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ShardedFilespec = tf_export("raw_ops.ShardedFilespec")(_ops.to_raw_op(sharded_filespec)) + + +def sharded_filespec_eager_fallback(basename: Annotated[Any, _atypes.String], num_shards: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.String]: + basename = _ops.convert_to_tensor(basename, _dtypes.string) + num_shards = _ops.convert_to_tensor(num_shards, _dtypes.int32) + _inputs_flat = [basename, num_shards] + _attrs = None + _result = _execute.execute(b"ShardedFilespec", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ShardedFilespec", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tf_record_reader(container:str="", shared_name:str="", compression_type:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs the records from a TensorFlow Records file. + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + compression_type: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("tf_record_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TFRecordReader", container=container, shared_name=shared_name, + compression_type=compression_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "compression_type", + _op.get_attr("compression_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TFRecordReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TFRecordReader = tf_export("raw_ops.TFRecordReader")(_ops.to_raw_op(tf_record_reader)) + + +def tf_record_reader_eager_fallback(container: str, shared_name: str, compression_type: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("tf_record_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +def tf_record_reader_v2(container:str="", shared_name:str="", compression_type:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A Reader that outputs the records from a TensorFlow Records file. + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + compression_type: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TFRecordReaderV2", name, "container", container, "shared_name", + shared_name, "compression_type", compression_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tf_record_reader_v2_eager_fallback( + container=container, shared_name=shared_name, + compression_type=compression_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TFRecordReaderV2", container=container, shared_name=shared_name, + compression_type=compression_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "compression_type", + _op.get_attr("compression_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TFRecordReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TFRecordReaderV2 = tf_export("raw_ops.TFRecordReaderV2")(_ops.to_raw_op(tf_record_reader_v2)) + + +def tf_record_reader_v2_eager_fallback(container: str, shared_name: str, compression_type: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name, + "compression_type", compression_type) + _result = _execute.execute(b"TFRecordReaderV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TFRecordReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def text_line_reader(skip_header_lines:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs the lines of a file delimited by '\n'. + + Args: + skip_header_lines: An optional `int`. Defaults to `0`. + Number of lines to skip from the beginning of every file. + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("text_line_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + if skip_header_lines is None: + skip_header_lines = 0 + skip_header_lines = _execute.make_int(skip_header_lines, "skip_header_lines") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TextLineReader", skip_header_lines=skip_header_lines, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("skip_header_lines", _op._get_attr_int("skip_header_lines"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TextLineReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TextLineReader = tf_export("raw_ops.TextLineReader")(_ops.to_raw_op(text_line_reader)) + + +def text_line_reader_eager_fallback(skip_header_lines: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("text_line_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +def text_line_reader_v2(skip_header_lines:int=0, container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A Reader that outputs the lines of a file delimited by '\n'. + + Args: + skip_header_lines: An optional `int`. Defaults to `0`. + Number of lines to skip from the beginning of every file. + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TextLineReaderV2", name, "skip_header_lines", + skip_header_lines, "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return text_line_reader_v2_eager_fallback( + skip_header_lines=skip_header_lines, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if skip_header_lines is None: + skip_header_lines = 0 + skip_header_lines = _execute.make_int(skip_header_lines, "skip_header_lines") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TextLineReaderV2", skip_header_lines=skip_header_lines, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("skip_header_lines", _op._get_attr_int("skip_header_lines"), + "container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TextLineReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TextLineReaderV2 = tf_export("raw_ops.TextLineReaderV2")(_ops.to_raw_op(text_line_reader_v2)) + + +def text_line_reader_v2_eager_fallback(skip_header_lines: int, container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if skip_header_lines is None: + skip_header_lines = 0 + skip_header_lines = _execute.make_int(skip_header_lines, "skip_header_lines") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("skip_header_lines", skip_header_lines, "container", container, + "shared_name", shared_name) + _result = _execute.execute(b"TextLineReaderV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TextLineReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def whole_file_reader(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""A Reader that outputs the entire contents of a file as a value. + + To use, enqueue filenames in a Queue. The output of ReaderRead will + be a filename (key) and the contents of that file (value). + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("whole_file_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WholeFileReader", container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "WholeFileReader", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WholeFileReader = tf_export("raw_ops.WholeFileReader")(_ops.to_raw_op(whole_file_reader)) + + +def whole_file_reader_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("whole_file_reader op does not support eager execution. Arg 'reader_handle' is a ref.") + +def whole_file_reader_v2(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""A Reader that outputs the entire contents of a file as a value. + + To use, enqueue filenames in a Queue. The output of ReaderRead will + be a filename (key) and the contents of that file (value). + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this reader is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this reader is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WholeFileReaderV2", name, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return whole_file_reader_v2_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WholeFileReaderV2", container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "WholeFileReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WholeFileReaderV2 = tf_export("raw_ops.WholeFileReaderV2")(_ops.to_raw_op(whole_file_reader_v2)) + + +def whole_file_reader_v2_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"WholeFileReaderV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "WholeFileReaderV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.write_file', v1=['io.write_file', 'write_file']) +@deprecated_endpoints('write_file') +def write_file(filename: Annotated[Any, _atypes.String], contents: Annotated[Any, _atypes.String], name=None): + r"""Writes `contents` to the file at input `filename`. + + Creates the file and recursively creates directory if it does not exist. + + Args: + filename: A `Tensor` of type `string`. + scalar. The name of the file to which we write the contents. + contents: A `Tensor` of type `string`. + scalar. The content to be written to the output file. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteFile", name, filename, contents) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_write_file( + (filename, contents, name,), None) + if _result is not NotImplemented: + return _result + return write_file_eager_fallback( + filename, contents, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + write_file, (), dict(filename=filename, contents=contents, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_write_file( + (filename, contents, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteFile", filename=filename, contents=contents, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + write_file, (), dict(filename=filename, contents=contents, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +WriteFile = tf_export("raw_ops.WriteFile")(_ops.to_raw_op(write_file)) +_dispatcher_for_write_file = write_file._tf_type_based_dispatcher.Dispatch + + +def write_file_eager_fallback(filename: Annotated[Any, _atypes.String], contents: Annotated[Any, _atypes.String], name, ctx): + filename = _ops.convert_to_tensor(filename, _dtypes.string) + contents = _ops.convert_to_tensor(contents, _dtypes.string) + _inputs_flat = [filename, contents] + _attrs = None + _result = _execute.execute(b"WriteFile", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_linalg_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_linalg_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bd63ad437da91a9d1c6846e92ac9f5a8a86f88f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_linalg_ops.py @@ -0,0 +1,2683 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_BandedTriangularSolve_T = TypeVar("TV_BandedTriangularSolve_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def banded_triangular_solve(matrix: Annotated[Any, TV_BandedTriangularSolve_T], rhs: Annotated[Any, TV_BandedTriangularSolve_T], lower:bool=True, adjoint:bool=False, name=None) -> Annotated[Any, TV_BandedTriangularSolve_T]: + r"""TODO: add doc. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + rhs: A `Tensor`. Must have the same type as `matrix`. + lower: An optional `bool`. Defaults to `True`. + adjoint: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BandedTriangularSolve", name, matrix, rhs, "lower", lower, + "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return banded_triangular_solve_eager_fallback( + matrix, rhs, lower=lower, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BandedTriangularSolve", matrix=matrix, rhs=rhs, lower=lower, + adjoint=adjoint, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("lower", _op._get_attr_bool("lower"), "adjoint", + _op._get_attr_bool("adjoint"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BandedTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BandedTriangularSolve = tf_export("raw_ops.BandedTriangularSolve")(_ops.to_raw_op(banded_triangular_solve)) + + +def banded_triangular_solve_eager_fallback(matrix: Annotated[Any, TV_BandedTriangularSolve_T], rhs: Annotated[Any, TV_BandedTriangularSolve_T], lower: bool, adjoint: bool, name, ctx) -> Annotated[Any, TV_BandedTriangularSolve_T]: + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + (matrix, rhs) = _inputs_T + _inputs_flat = [matrix, rhs] + _attrs = ("lower", lower, "adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"BandedTriangularSolve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BandedTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchCholesky_T = TypeVar("TV_BatchCholesky_T", _atypes.Float32, _atypes.Float64) + +def batch_cholesky(input: Annotated[Any, TV_BatchCholesky_T], name=None) -> Annotated[Any, TV_BatchCholesky_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchCholesky", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_cholesky_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchCholesky", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchCholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchCholesky = tf_export("raw_ops.BatchCholesky")(_ops.to_raw_op(batch_cholesky)) + + +def batch_cholesky_eager_fallback(input: Annotated[Any, TV_BatchCholesky_T], name, ctx) -> Annotated[Any, TV_BatchCholesky_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchCholesky", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchCholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchCholeskyGrad_T = TypeVar("TV_BatchCholeskyGrad_T", _atypes.Float32, _atypes.Float64) + +def batch_cholesky_grad(l: Annotated[Any, TV_BatchCholeskyGrad_T], grad: Annotated[Any, TV_BatchCholeskyGrad_T], name=None) -> Annotated[Any, TV_BatchCholeskyGrad_T]: + r"""TODO: add doc. + + Args: + l: A `Tensor`. Must be one of the following types: `float32`, `float64`. + grad: A `Tensor`. Must have the same type as `l`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `l`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchCholeskyGrad", name, l, grad) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_cholesky_grad_eager_fallback( + l, grad, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchCholeskyGrad", l=l, grad=grad, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchCholeskyGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchCholeskyGrad = tf_export("raw_ops.BatchCholeskyGrad")(_ops.to_raw_op(batch_cholesky_grad)) + + +def batch_cholesky_grad_eager_fallback(l: Annotated[Any, TV_BatchCholeskyGrad_T], grad: Annotated[Any, TV_BatchCholeskyGrad_T], name, ctx) -> Annotated[Any, TV_BatchCholeskyGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([l, grad], ctx, [_dtypes.float32, _dtypes.float64, ]) + (l, grad) = _inputs_T + _inputs_flat = [l, grad] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchCholeskyGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchCholeskyGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixDeterminant_T = TypeVar("TV_BatchMatrixDeterminant_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def batch_matrix_determinant(input: Annotated[Any, TV_BatchMatrixDeterminant_T], name=None) -> Annotated[Any, TV_BatchMatrixDeterminant_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixDeterminant", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_determinant_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixDeterminant", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixDeterminant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixDeterminant = tf_export("raw_ops.BatchMatrixDeterminant")(_ops.to_raw_op(batch_matrix_determinant)) + + +def batch_matrix_determinant_eager_fallback(input: Annotated[Any, TV_BatchMatrixDeterminant_T], name, ctx) -> Annotated[Any, TV_BatchMatrixDeterminant_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchMatrixDeterminant", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixDeterminant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixInverse_T = TypeVar("TV_BatchMatrixInverse_T", _atypes.Float32, _atypes.Float64) + +def batch_matrix_inverse(input: Annotated[Any, TV_BatchMatrixInverse_T], adjoint:bool=False, name=None) -> Annotated[Any, TV_BatchMatrixInverse_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`. + adjoint: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixInverse", name, input, "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_inverse_eager_fallback( + input, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixInverse", input=input, adjoint=adjoint, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("adjoint", _op._get_attr_bool("adjoint"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixInverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixInverse = tf_export("raw_ops.BatchMatrixInverse")(_ops.to_raw_op(batch_matrix_inverse)) + + +def batch_matrix_inverse_eager_fallback(input: Annotated[Any, TV_BatchMatrixInverse_T], adjoint: bool, name, ctx) -> Annotated[Any, TV_BatchMatrixInverse_T]: + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"BatchMatrixInverse", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixInverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixSolve_T = TypeVar("TV_BatchMatrixSolve_T", _atypes.Float32, _atypes.Float64) + +def batch_matrix_solve(matrix: Annotated[Any, TV_BatchMatrixSolve_T], rhs: Annotated[Any, TV_BatchMatrixSolve_T], adjoint:bool=False, name=None) -> Annotated[Any, TV_BatchMatrixSolve_T]: + r"""TODO: add doc. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`. + rhs: A `Tensor`. Must have the same type as `matrix`. + adjoint: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixSolve", name, matrix, rhs, "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_solve_eager_fallback( + matrix, rhs, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixSolve", matrix=matrix, rhs=rhs, adjoint=adjoint, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("adjoint", _op._get_attr_bool("adjoint"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixSolve = tf_export("raw_ops.BatchMatrixSolve")(_ops.to_raw_op(batch_matrix_solve)) + + +def batch_matrix_solve_eager_fallback(matrix: Annotated[Any, TV_BatchMatrixSolve_T], rhs: Annotated[Any, TV_BatchMatrixSolve_T], adjoint: bool, name, ctx) -> Annotated[Any, TV_BatchMatrixSolve_T]: + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, ]) + (matrix, rhs) = _inputs_T + _inputs_flat = [matrix, rhs] + _attrs = ("adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"BatchMatrixSolve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixSolveLs_T = TypeVar("TV_BatchMatrixSolveLs_T", _atypes.Float32, _atypes.Float64) + +def batch_matrix_solve_ls(matrix: Annotated[Any, TV_BatchMatrixSolveLs_T], rhs: Annotated[Any, TV_BatchMatrixSolveLs_T], l2_regularizer: Annotated[Any, _atypes.Float64], fast:bool=True, name=None) -> Annotated[Any, TV_BatchMatrixSolveLs_T]: + r"""TODO: add doc. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`. + rhs: A `Tensor`. Must have the same type as `matrix`. + l2_regularizer: A `Tensor` of type `float64`. + fast: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixSolveLs", name, matrix, rhs, l2_regularizer, "fast", + fast) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_solve_ls_eager_fallback( + matrix, rhs, l2_regularizer, fast=fast, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if fast is None: + fast = True + fast = _execute.make_bool(fast, "fast") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixSolveLs", matrix=matrix, rhs=rhs, + l2_regularizer=l2_regularizer, fast=fast, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "fast", + _op._get_attr_bool("fast")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixSolveLs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixSolveLs = tf_export("raw_ops.BatchMatrixSolveLs")(_ops.to_raw_op(batch_matrix_solve_ls)) + + +def batch_matrix_solve_ls_eager_fallback(matrix: Annotated[Any, TV_BatchMatrixSolveLs_T], rhs: Annotated[Any, TV_BatchMatrixSolveLs_T], l2_regularizer: Annotated[Any, _atypes.Float64], fast: bool, name, ctx) -> Annotated[Any, TV_BatchMatrixSolveLs_T]: + if fast is None: + fast = True + fast = _execute.make_bool(fast, "fast") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, ]) + (matrix, rhs) = _inputs_T + l2_regularizer = _ops.convert_to_tensor(l2_regularizer, _dtypes.float64) + _inputs_flat = [matrix, rhs, l2_regularizer] + _attrs = ("T", _attr_T, "fast", fast) + _result = _execute.execute(b"BatchMatrixSolveLs", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixSolveLs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatrixTriangularSolve_T = TypeVar("TV_BatchMatrixTriangularSolve_T", _atypes.Float32, _atypes.Float64) + +def batch_matrix_triangular_solve(matrix: Annotated[Any, TV_BatchMatrixTriangularSolve_T], rhs: Annotated[Any, TV_BatchMatrixTriangularSolve_T], lower:bool=True, adjoint:bool=False, name=None) -> Annotated[Any, TV_BatchMatrixTriangularSolve_T]: + r"""TODO: add doc. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`. + rhs: A `Tensor`. Must have the same type as `matrix`. + lower: An optional `bool`. Defaults to `True`. + adjoint: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatrixTriangularSolve", name, matrix, rhs, "lower", lower, + "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_matrix_triangular_solve_eager_fallback( + matrix, rhs, lower=lower, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatrixTriangularSolve", matrix=matrix, rhs=rhs, lower=lower, + adjoint=adjoint, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("lower", _op._get_attr_bool("lower"), "adjoint", + _op._get_attr_bool("adjoint"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatrixTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatrixTriangularSolve = tf_export("raw_ops.BatchMatrixTriangularSolve")(_ops.to_raw_op(batch_matrix_triangular_solve)) + + +def batch_matrix_triangular_solve_eager_fallback(matrix: Annotated[Any, TV_BatchMatrixTriangularSolve_T], rhs: Annotated[Any, TV_BatchMatrixTriangularSolve_T], lower: bool, adjoint: bool, name, ctx) -> Annotated[Any, TV_BatchMatrixTriangularSolve_T]: + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, ]) + (matrix, rhs) = _inputs_T + _inputs_flat = [matrix, rhs] + _attrs = ("lower", lower, "adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"BatchMatrixTriangularSolve", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatrixTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchSelfAdjointEig_T = TypeVar("TV_BatchSelfAdjointEig_T", _atypes.Float32, _atypes.Float64) + +def batch_self_adjoint_eig(input: Annotated[Any, TV_BatchSelfAdjointEig_T], name=None) -> Annotated[Any, TV_BatchSelfAdjointEig_T]: + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchSelfAdjointEig", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_self_adjoint_eig_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchSelfAdjointEig", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchSelfAdjointEig", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchSelfAdjointEig = tf_export("raw_ops.BatchSelfAdjointEig")(_ops.to_raw_op(batch_self_adjoint_eig)) + + +def batch_self_adjoint_eig_eager_fallback(input: Annotated[Any, TV_BatchSelfAdjointEig_T], name, ctx) -> Annotated[Any, TV_BatchSelfAdjointEig_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BatchSelfAdjointEig", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchSelfAdjointEig", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_BatchSelfAdjointEigV2Output = collections.namedtuple( + "BatchSelfAdjointEigV2", + ["e", "v"]) + + +TV_BatchSelfAdjointEigV2_T = TypeVar("TV_BatchSelfAdjointEigV2_T", _atypes.Float32, _atypes.Float64) + +def batch_self_adjoint_eig_v2(input: Annotated[Any, TV_BatchSelfAdjointEigV2_T], compute_v:bool=True, name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`. + compute_v: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (e, v). + + e: A `Tensor`. Has the same type as `input`. + v: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchSelfAdjointEigV2", name, input, "compute_v", compute_v) + _result = _BatchSelfAdjointEigV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_self_adjoint_eig_v2_eager_fallback( + input, compute_v=compute_v, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchSelfAdjointEigV2", input=input, compute_v=compute_v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compute_v", _op._get_attr_bool("compute_v"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchSelfAdjointEigV2", _inputs_flat, _attrs, _result) + _result = _BatchSelfAdjointEigV2Output._make(_result) + return _result + +BatchSelfAdjointEigV2 = tf_export("raw_ops.BatchSelfAdjointEigV2")(_ops.to_raw_op(batch_self_adjoint_eig_v2)) + + +def batch_self_adjoint_eig_v2_eager_fallback(input: Annotated[Any, TV_BatchSelfAdjointEigV2_T], compute_v: bool, name, ctx): + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("compute_v", compute_v, "T", _attr_T) + _result = _execute.execute(b"BatchSelfAdjointEigV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchSelfAdjointEigV2", _inputs_flat, _attrs, _result) + _result = _BatchSelfAdjointEigV2Output._make(_result) + return _result + +_BatchSvdOutput = collections.namedtuple( + "BatchSvd", + ["s", "u", "v"]) + + +TV_BatchSvd_T = TypeVar("TV_BatchSvd_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def batch_svd(input: Annotated[Any, TV_BatchSvd_T], compute_uv:bool=True, full_matrices:bool=False, name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `complex64`, `complex128`. + compute_uv: An optional `bool`. Defaults to `True`. + full_matrices: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (s, u, v). + + s: A `Tensor`. Has the same type as `input`. + u: A `Tensor`. Has the same type as `input`. + v: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchSvd", name, input, "compute_uv", compute_uv, + "full_matrices", full_matrices) + _result = _BatchSvdOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_svd_eager_fallback( + input, compute_uv=compute_uv, full_matrices=full_matrices, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compute_uv is None: + compute_uv = True + compute_uv = _execute.make_bool(compute_uv, "compute_uv") + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchSvd", input=input, compute_uv=compute_uv, + full_matrices=full_matrices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compute_uv", _op._get_attr_bool("compute_uv"), "full_matrices", + _op._get_attr_bool("full_matrices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchSvd", _inputs_flat, _attrs, _result) + _result = _BatchSvdOutput._make(_result) + return _result + +BatchSvd = tf_export("raw_ops.BatchSvd")(_ops.to_raw_op(batch_svd)) + + +def batch_svd_eager_fallback(input: Annotated[Any, TV_BatchSvd_T], compute_uv: bool, full_matrices: bool, name, ctx): + if compute_uv is None: + compute_uv = True + compute_uv = _execute.make_bool(compute_uv, "compute_uv") + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("compute_uv", compute_uv, "full_matrices", full_matrices, "T", + _attr_T) + _result = _execute.execute(b"BatchSvd", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchSvd", _inputs_flat, _attrs, _result) + _result = _BatchSvdOutput._make(_result) + return _result + + +TV_Cholesky_T = TypeVar("TV_Cholesky_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.cholesky', v1=['linalg.cholesky', 'cholesky']) +@deprecated_endpoints('cholesky') +def cholesky(input: Annotated[Any, TV_Cholesky_T], name=None) -> Annotated[Any, TV_Cholesky_T]: + r"""Computes the Cholesky decomposition of one or more square matrices. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. + + The input has to be symmetric and positive definite. Only the lower-triangular + part of the input will be used for this operation. The upper-triangular part + will not be read. + + The output is a tensor of the same shape as the input + containing the Cholesky decompositions for all input submatrices `[..., :, :]`. + + **Note**: The gradient computation on GPU is faster for large matrices but + not for large batch dimensions when the submatrices are small. In this + case it might be faster to use the CPU. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cholesky", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_cholesky( + (input, name,), None) + if _result is not NotImplemented: + return _result + return cholesky_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cholesky, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_cholesky( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cholesky", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cholesky, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cholesky = tf_export("raw_ops.Cholesky")(_ops.to_raw_op(cholesky)) +_dispatcher_for_cholesky = cholesky._tf_type_based_dispatcher.Dispatch + + +def cholesky_eager_fallback(input: Annotated[Any, TV_Cholesky_T], name, ctx) -> Annotated[Any, TV_Cholesky_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Cholesky", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CholeskyGrad_T = TypeVar("TV_CholeskyGrad_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def cholesky_grad(l: Annotated[Any, TV_CholeskyGrad_T], grad: Annotated[Any, TV_CholeskyGrad_T], name=None) -> Annotated[Any, TV_CholeskyGrad_T]: + r"""Computes the reverse mode backpropagated gradient of the Cholesky algorithm. + + For an explanation see "Differentiation of the Cholesky algorithm" by + Iain Murray http://arxiv.org/abs/1602.07527. + + Args: + l: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + Output of batch Cholesky algorithm l = cholesky(A). Shape is `[..., M, M]`. + Algorithm depends only on lower triangular part of the innermost matrices of + this tensor. + grad: A `Tensor`. Must have the same type as `l`. + df/dl where f is some scalar function. Shape is `[..., M, M]`. + Algorithm depends only on lower triangular part of the innermost matrices of + this tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `l`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CholeskyGrad", name, l, grad) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cholesky_grad_eager_fallback( + l, grad, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CholeskyGrad", l=l, grad=grad, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CholeskyGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CholeskyGrad = tf_export("raw_ops.CholeskyGrad")(_ops.to_raw_op(cholesky_grad)) + + +def cholesky_grad_eager_fallback(l: Annotated[Any, TV_CholeskyGrad_T], grad: Annotated[Any, TV_CholeskyGrad_T], name, ctx) -> Annotated[Any, TV_CholeskyGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([l, grad], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (l, grad) = _inputs_T + _inputs_flat = [l, grad] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"CholeskyGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CholeskyGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_EigOutput = collections.namedtuple( + "Eig", + ["e", "v"]) + + +TV_Eig_T = TypeVar("TV_Eig_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) +TV_Eig_Tout = TypeVar("TV_Eig_Tout", _atypes.Complex128, _atypes.Complex64) + +def eig(input: Annotated[Any, TV_Eig_T], Tout: TV_Eig_Tout, compute_v:bool=True, name=None): + r"""Computes the eigen decomposition of one or more square matrices. + + Computes the eigenvalues and (optionally) right eigenvectors of each inner matrix in + `input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues + are sorted in non-decreasing order. + + ```python + # a is a tensor. + # e is a tensor of eigenvalues. + # v is a tensor of eigenvectors. + e, v = eig(a) + e = eig(a, compute_v=False) + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `complex64`, `complex128`. + `Tensor` input of shape `[N, N]`. + Tout: A `tf.DType` from: `tf.complex64, tf.complex128`. + compute_v: An optional `bool`. Defaults to `True`. + If `True` then eigenvectors will be computed and returned in `v`. + Otherwise, only the eigenvalues will be computed. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (e, v). + + e: A `Tensor` of type `Tout`. + v: A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Eig", name, input, "compute_v", compute_v, "Tout", Tout) + _result = _EigOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return eig_eager_fallback( + input, compute_v=compute_v, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Eig", input=input, Tout=Tout, compute_v=compute_v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compute_v", _op._get_attr_bool("compute_v"), "T", + _op._get_attr_type("T"), "Tout", _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Eig", _inputs_flat, _attrs, _result) + _result = _EigOutput._make(_result) + return _result + +Eig = tf_export("raw_ops.Eig")(_ops.to_raw_op(eig)) + + +def eig_eager_fallback(input: Annotated[Any, TV_Eig_T], Tout: TV_Eig_Tout, compute_v: bool, name, ctx): + Tout = _execute.make_type(Tout, "Tout") + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("compute_v", compute_v, "T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"Eig", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Eig", _inputs_flat, _attrs, _result) + _result = _EigOutput._make(_result) + return _result + + +TV_Einsum_T = TypeVar("TV_Einsum_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def einsum(inputs: Annotated[List[Any], TV_Einsum_T], equation: str, name=None) -> Annotated[Any, TV_Einsum_T]: + r"""Tensor contraction according to Einstein summation convention. + + Implements generalized Tensor contraction and reduction. Each input Tensor must + have a corresponding input subscript appearing in the comma-separated left-hand + side of the equation. The right-hand side of the equation consists of the + output subscript. The input subscripts and the output subscript should consist + of zero or more named axis labels and at most one ellipsis (`...`). + + The named axis labels may be any single character other than those having + special meaning, namely `,.->`. The behavior of this Op is undefined if it + receives an ill-formatted equation; since the validation is done at + graph-building time, we omit format validation checks at runtime. + + Note: This Op is *not* intended to be called by the user; instead users should + call `tf.einsum` directly. It is a hidden Op used by `tf.einsum`. + + Operations are applied to the input(s) according to the following rules: + + (a) Generalized Diagonals: For input dimensions corresponding to axis labels + appearing more than once in the same input subscript, we take the + generalized (`k`-dimensional) diagonal. + For example, in the equation `iii->i` with input shape `[3, 3, 3]`, the + generalized diagonal would consist of `3` elements at indices `(0, 0, 0)`, + `(1, 1, 1)` and `(2, 2, 2)` to create a Tensor of shape `[3]`. + + (b) Reduction: Axes corresponding to labels appearing only in one input + subscript but not in the output subscript are summed over prior to Tensor + contraction. + For example, in the equation `ab,bc->b`, the axis labels `a` and `c` are + the reduction axis labels. + + (c) Batch Dimensions: Axes corresponding to labels appearing in each of the + input subscripts and also in the output subscript make up the batch + dimensions in Tensor contraction. Unnamed axis labels corresponding to + ellipsis (`...`) also correspond to batch dimensions. + For example, for the equation denoting batch matrix multiplication, + `bij,bjk->bik`, the axis label `b` corresponds to a batch dimension. + + (d) Contraction: In case of binary einsum, axes corresponding to labels + appearing in two different inputs (and not in the output) are contracted + against each other. + Considering the batch matrix multiplication equation again + (`bij,bjk->bik`), the contracted axis label is `j`. + + (e) Expand Diagonal: If the output subscripts contain repeated (explicit) axis + labels, the opposite operation of (a) is applied. For example, in the + equation `i->iii`, and input shape `[3]`, the output of shape `[3, 3, 3]` + are all zeros, except for the (generalized) diagonal which is populated + with values from the input. + Note: This operation is not supported by `np.einsum` or `tf.einsum`; it is + provided to enable computing the symbolic gradient of `tf.einsum`. + + The output subscripts must contain only labels appearing in at least one of the + input subscripts. Furthermore, all dimensions mapping to the same axis label + must be equal. + + Any of the input and output subscripts may contain at most a single ellipsis + (`...`). These ellipsis are mapped against dimensions not corresponding to any + named axis label. If two inputs contain ellipsis, then they are broadcasted + according to standard NumPy broadcasting + [rules](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). + + The broadcasted dimensions are placed in the corresponding location of the + ellipsis in the output subscript. If the broadcasted dimensions are non-empty + and the output subscripts do not contain ellipsis, then an InvalidArgument error + is raised. + + @compatibility(numpy) + Similar to [`numpy.einsum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html). + + Comparison with `numpy.einsum`: + + * This Op only supports unary and binary forms of `numpy.einsum`. + * This Op does not support implicit form. (i.e. equations without `->`). + * This Op also supports repeated indices in the output subscript, which is not + supported by `numpy.einsum`. + @end_compatibility + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + List of 1 or 2 Tensors. + equation: A `string`. + String describing the Einstein Summation operation; in the format of np.einsum. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Einsum", name, inputs, "equation", equation) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return einsum_eager_fallback( + inputs, equation=equation, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'einsum' Op, not %r." % inputs) + _attr_N = len(inputs) + equation = _execute.make_str(equation, "equation") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Einsum", inputs=inputs, equation=equation, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("equation", _op.get_attr("equation"), "N", + _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Einsum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Einsum = tf_export("raw_ops.Einsum")(_ops.to_raw_op(einsum)) + + +def einsum_eager_fallback(inputs: Annotated[List[Any], TV_Einsum_T], equation: str, name, ctx) -> Annotated[Any, TV_Einsum_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'einsum' Op, not %r." % inputs) + _attr_N = len(inputs) + equation = _execute.make_str(equation, "equation") + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("equation", equation, "N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"Einsum", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Einsum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_LogMatrixDeterminantOutput = collections.namedtuple( + "LogMatrixDeterminant", + ["sign", "log_abs_determinant"]) + + +TV_LogMatrixDeterminant_T = TypeVar("TV_LogMatrixDeterminant_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def log_matrix_determinant(input: Annotated[Any, TV_LogMatrixDeterminant_T], name=None): + r"""Computes the sign and the log of the absolute value of the determinant of + + one or more square matrices. + + The input is a tensor of shape `[N, M, M]` whose inner-most 2 dimensions + form square matrices. The outputs are two tensors containing the signs and + absolute values of the log determinants for all N input submatrices + `[..., :, :]` such that `determinant = sign*exp(log_abs_determinant)`. + The `log_abs_determinant` is computed as `det(P)*sum(log(diag(LU)))` where `LU` + is the `LU` decomposition of the input and `P` is the corresponding + permutation matrix. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `complex64`, `complex128`. + Shape is `[N, M, M]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sign, log_abs_determinant). + + sign: A `Tensor`. Has the same type as `input`. + log_abs_determinant: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogMatrixDeterminant", name, input) + _result = _LogMatrixDeterminantOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return log_matrix_determinant_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogMatrixDeterminant", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogMatrixDeterminant", _inputs_flat, _attrs, _result) + _result = _LogMatrixDeterminantOutput._make(_result) + return _result + +LogMatrixDeterminant = tf_export("raw_ops.LogMatrixDeterminant")(_ops.to_raw_op(log_matrix_determinant)) + + +def log_matrix_determinant_eager_fallback(input: Annotated[Any, TV_LogMatrixDeterminant_T], name, ctx): + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"LogMatrixDeterminant", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogMatrixDeterminant", _inputs_flat, _attrs, _result) + _result = _LogMatrixDeterminantOutput._make(_result) + return _result + +_LuOutput = collections.namedtuple( + "Lu", + ["lu", "p"]) + + +TV_Lu_T = TypeVar("TV_Lu_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_Lu_output_idx_type = TypeVar("TV_Lu_output_idx_type", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.lu') +def lu(input: Annotated[Any, TV_Lu_T], output_idx_type:TV_Lu_output_idx_type=_dtypes.int32, name=None): + r"""Computes the LU decomposition of one or more square matrices. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. + + The input has to be invertible. + + The output consists of two tensors LU and P containing the LU decomposition + of all input submatrices `[..., :, :]`. LU encodes the lower triangular and + upper triangular factors. + + For each input submatrix of shape `[M, M]`, L is a lower triangular matrix of + shape `[M, M]` with unit diagonal whose entries correspond to the strictly lower + triangular part of LU. U is a upper triangular matrix of shape `[M, M]` whose + entries correspond to the upper triangular part, including the diagonal, of LU. + + P represents a permutation matrix encoded as a list of indices each between `0` + and `M-1`, inclusive. If P_mat denotes the permutation matrix corresponding to + P, then the L, U and P satisfies P_mat * input = L * U. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + A tensor of shape `[..., M, M]` whose inner-most 2 dimensions form matrices of + size `[M, M]`. + output_idx_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (lu, p). + + lu: A `Tensor`. Has the same type as `input`. + p: A `Tensor` of type `output_idx_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Lu", name, input, "output_idx_type", output_idx_type) + _result = _LuOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_lu( + (input, output_idx_type, name,), None) + if _result is not NotImplemented: + return _result + return lu_eager_fallback( + input, output_idx_type=output_idx_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lu, (), dict(input=input, output_idx_type=output_idx_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_lu( + (input, output_idx_type, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if output_idx_type is None: + output_idx_type = _dtypes.int32 + output_idx_type = _execute.make_type(output_idx_type, "output_idx_type") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Lu", input=input, output_idx_type=output_idx_type, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lu, (), dict(input=input, output_idx_type=output_idx_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "output_idx_type", + _op._get_attr_type("output_idx_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Lu", _inputs_flat, _attrs, _result) + _result = _LuOutput._make(_result) + return _result + +Lu = tf_export("raw_ops.Lu")(_ops.to_raw_op(lu)) +_dispatcher_for_lu = lu._tf_type_based_dispatcher.Dispatch + + +def lu_eager_fallback(input: Annotated[Any, TV_Lu_T], output_idx_type: TV_Lu_output_idx_type, name, ctx): + if output_idx_type is None: + output_idx_type = _dtypes.int32 + output_idx_type = _execute.make_type(output_idx_type, "output_idx_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "output_idx_type", output_idx_type) + _result = _execute.execute(b"Lu", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Lu", _inputs_flat, _attrs, _result) + _result = _LuOutput._make(_result) + return _result + + +TV_MatrixDeterminant_T = TypeVar("TV_MatrixDeterminant_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.det', v1=['linalg.det', 'matrix_determinant']) +@deprecated_endpoints('matrix_determinant') +def matrix_determinant(input: Annotated[Any, TV_MatrixDeterminant_T], name=None) -> Annotated[Any, TV_MatrixDeterminant_T]: + r"""Computes the determinant of one or more square matrices. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. The output is a tensor containing the determinants + for all input submatrices `[..., :, :]`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixDeterminant", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matrix_determinant( + (input, name,), None) + if _result is not NotImplemented: + return _result + return matrix_determinant_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_determinant, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matrix_determinant( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixDeterminant", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_determinant, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixDeterminant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixDeterminant = tf_export("raw_ops.MatrixDeterminant")(_ops.to_raw_op(matrix_determinant)) +_dispatcher_for_matrix_determinant = matrix_determinant._tf_type_based_dispatcher.Dispatch + + +def matrix_determinant_eager_fallback(input: Annotated[Any, TV_MatrixDeterminant_T], name, ctx) -> Annotated[Any, TV_MatrixDeterminant_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixDeterminant", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixDeterminant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixExponential_T = TypeVar("TV_MatrixExponential_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def matrix_exponential(input: Annotated[Any, TV_MatrixExponential_T], name=None) -> Annotated[Any, TV_MatrixExponential_T]: + r"""Deprecated, use python implementation tf.linalg.matrix_exponential. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixExponential", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_exponential_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixExponential", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixExponential", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixExponential = tf_export("raw_ops.MatrixExponential")(_ops.to_raw_op(matrix_exponential)) + + +def matrix_exponential_eager_fallback(input: Annotated[Any, TV_MatrixExponential_T], name, ctx) -> Annotated[Any, TV_MatrixExponential_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixExponential", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixExponential", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixInverse_T = TypeVar("TV_MatrixInverse_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.inv', v1=['linalg.inv', 'matrix_inverse']) +@deprecated_endpoints('matrix_inverse') +def matrix_inverse(input: Annotated[Any, TV_MatrixInverse_T], adjoint:bool=False, name=None) -> Annotated[Any, TV_MatrixInverse_T]: + r"""Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes). + + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. The output is a tensor of the same shape as the input + containing the inverse for all input submatrices `[..., :, :]`. + + The op uses LU decomposition with partial pivoting to compute the inverses. + + If a matrix is not invertible there is no guarantee what the op does. It + may detect the condition and raise an exception or it may simply return a + garbage result. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + adjoint: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixInverse", name, input, "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matrix_inverse( + (input, adjoint, name,), None) + if _result is not NotImplemented: + return _result + return matrix_inverse_eager_fallback( + input, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_inverse, (), dict(input=input, adjoint=adjoint, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matrix_inverse( + (input, adjoint, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixInverse", input=input, adjoint=adjoint, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_inverse, (), dict(input=input, adjoint=adjoint, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("adjoint", _op._get_attr_bool("adjoint"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixInverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixInverse = tf_export("raw_ops.MatrixInverse")(_ops.to_raw_op(matrix_inverse)) +_dispatcher_for_matrix_inverse = matrix_inverse._tf_type_based_dispatcher.Dispatch + + +def matrix_inverse_eager_fallback(input: Annotated[Any, TV_MatrixInverse_T], adjoint: bool, name, ctx) -> Annotated[Any, TV_MatrixInverse_T]: + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"MatrixInverse", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixInverse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixLogarithm_T = TypeVar("TV_MatrixLogarithm_T", _atypes.Complex128, _atypes.Complex64) + +def matrix_logarithm(input: Annotated[Any, TV_MatrixLogarithm_T], name=None) -> Annotated[Any, TV_MatrixLogarithm_T]: + r"""Computes the matrix logarithm of one or more square matrices: + + + \\(log(exp(A)) = A\\) + + This op is only defined for complex matrices. If A is positive-definite and + real, then casting to a complex matrix, taking the logarithm and casting back + to a real matrix will give the correct result. + + This function computes the matrix logarithm using the Schur-Parlett algorithm. + Details of the algorithm can be found in Section 11.6.2 of: + Nicholas J. Higham, Functions of Matrices: Theory and Computation, SIAM 2008. + ISBN 978-0-898716-46-7. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. The output is a tensor of the same shape as the input + containing the exponential for all input submatrices `[..., :, :]`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + Shape is `[..., M, M]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixLogarithm", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_logarithm_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixLogarithm", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixLogarithm", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixLogarithm = tf_export("raw_ops.MatrixLogarithm")(_ops.to_raw_op(matrix_logarithm)) + + +def matrix_logarithm_eager_fallback(input: Annotated[Any, TV_MatrixLogarithm_T], name, ctx) -> Annotated[Any, TV_MatrixLogarithm_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixLogarithm", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixLogarithm", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSolve_T = TypeVar("TV_MatrixSolve_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.solve', v1=['linalg.solve', 'matrix_solve']) +@deprecated_endpoints('matrix_solve') +def matrix_solve(matrix: Annotated[Any, TV_MatrixSolve_T], rhs: Annotated[Any, TV_MatrixSolve_T], adjoint:bool=False, name=None) -> Annotated[Any, TV_MatrixSolve_T]: + r"""Solves systems of linear equations. + + `Matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. `Rhs` is a tensor of shape `[..., M, K]`. The `output` is + a tensor shape `[..., M, K]`. If `adjoint` is `False` then each output matrix + satisfies `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`. + If `adjoint` is `True` then each output matrix satisfies + `adjoint(matrix[..., :, :]) * output[..., :, :] = rhs[..., :, :]`. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + rhs: A `Tensor`. Must have the same type as `matrix`. + Shape is `[..., M, K]`. + adjoint: An optional `bool`. Defaults to `False`. + Boolean indicating whether to solve with `matrix` or its (block-wise) + adjoint. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSolve", name, matrix, rhs, "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matrix_solve( + (matrix, rhs, adjoint, name,), None) + if _result is not NotImplemented: + return _result + return matrix_solve_eager_fallback( + matrix, rhs, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_solve, (), dict(matrix=matrix, rhs=rhs, adjoint=adjoint, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matrix_solve( + (matrix, rhs, adjoint, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSolve", matrix=matrix, rhs=rhs, adjoint=adjoint, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_solve, (), dict(matrix=matrix, rhs=rhs, adjoint=adjoint, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("adjoint", _op._get_attr_bool("adjoint"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSolve = tf_export("raw_ops.MatrixSolve")(_ops.to_raw_op(matrix_solve)) +_dispatcher_for_matrix_solve = matrix_solve._tf_type_based_dispatcher.Dispatch + + +def matrix_solve_eager_fallback(matrix: Annotated[Any, TV_MatrixSolve_T], rhs: Annotated[Any, TV_MatrixSolve_T], adjoint: bool, name, ctx) -> Annotated[Any, TV_MatrixSolve_T]: + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + (matrix, rhs) = _inputs_T + _inputs_flat = [matrix, rhs] + _attrs = ("adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"MatrixSolve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSolveLs_T = TypeVar("TV_MatrixSolveLs_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def matrix_solve_ls(matrix: Annotated[Any, TV_MatrixSolveLs_T], rhs: Annotated[Any, TV_MatrixSolveLs_T], l2_regularizer: Annotated[Any, _atypes.Float64], fast:bool=True, name=None) -> Annotated[Any, TV_MatrixSolveLs_T]: + r"""Solves one or more linear least-squares problems. + + `matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions + form real or complex matrices of size `[M, N]`. `Rhs` is a tensor of the same + type as `matrix` and shape `[..., M, K]`. + The output is a tensor shape `[..., N, K]` where each output matrix solves + each of the equations + `matrix[..., :, :]` * `output[..., :, :]` = `rhs[..., :, :]` + in the least squares sense. + + We use the following notation for (complex) matrix and right-hand sides + in the batch: + + `matrix`=\\(A \in \mathbb{C}^{m \times n}\\), + `rhs`=\\(B \in \mathbb{C}^{m \times k}\\), + `output`=\\(X \in \mathbb{C}^{n \times k}\\), + `l2_regularizer`=\\(\lambda \in \mathbb{R}\\). + + If `fast` is `True`, then the solution is computed by solving the normal + equations using Cholesky decomposition. Specifically, if \\(m \ge n\\) then + \\(X = (A^H A + \lambda I)^{-1} A^H B\\), which solves the least-squares + problem \\(X = \mathrm{argmin}_{Z \in \Re^{n \times k} } ||A Z - B||_F^2 + \lambda ||Z||_F^2\\). + If \\(m \lt n\\) then `output` is computed as + \\(X = A^H (A A^H + \lambda I)^{-1} B\\), which (for \\(\lambda = 0\\)) is the + minimum-norm solution to the under-determined linear system, i.e. + \\(X = \mathrm{argmin}_{Z \in \mathbb{C}^{n \times k} } ||Z||_F^2 \\), + subject to \\(A Z = B\\). Notice that the fast path is only numerically stable + when \\(A\\) is numerically full rank and has a condition number + \\(\mathrm{cond}(A) \lt \frac{1}{\sqrt{\epsilon_{mach} } }\\) or \\(\lambda\\) is + sufficiently large. + + If `fast` is `False` an algorithm based on the numerically robust complete + orthogonal decomposition is used. This computes the minimum-norm + least-squares solution, even when \\(A\\) is rank deficient. This path is + typically 6-7 times slower than the fast path. If `fast` is `False` then + `l2_regularizer` is ignored. + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, N]`. + rhs: A `Tensor`. Must have the same type as `matrix`. + Shape is `[..., M, K]`. + l2_regularizer: A `Tensor` of type `float64`. Scalar tensor. + + @compatibility(numpy) + Equivalent to np.linalg.lstsq + @end_compatibility + fast: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSolveLs", name, matrix, rhs, l2_regularizer, "fast", + fast) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_solve_ls_eager_fallback( + matrix, rhs, l2_regularizer, fast=fast, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if fast is None: + fast = True + fast = _execute.make_bool(fast, "fast") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSolveLs", matrix=matrix, rhs=rhs, + l2_regularizer=l2_regularizer, fast=fast, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "fast", + _op._get_attr_bool("fast")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSolveLs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSolveLs = tf_export("raw_ops.MatrixSolveLs")(_ops.to_raw_op(matrix_solve_ls)) + + +def matrix_solve_ls_eager_fallback(matrix: Annotated[Any, TV_MatrixSolveLs_T], rhs: Annotated[Any, TV_MatrixSolveLs_T], l2_regularizer: Annotated[Any, _atypes.Float64], fast: bool, name, ctx) -> Annotated[Any, TV_MatrixSolveLs_T]: + if fast is None: + fast = True + fast = _execute.make_bool(fast, "fast") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + (matrix, rhs) = _inputs_T + l2_regularizer = _ops.convert_to_tensor(l2_regularizer, _dtypes.float64) + _inputs_flat = [matrix, rhs, l2_regularizer] + _attrs = ("T", _attr_T, "fast", fast) + _result = _execute.execute(b"MatrixSolveLs", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSolveLs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixSquareRoot_T = TypeVar("TV_MatrixSquareRoot_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.sqrtm', 'matrix_square_root') +def matrix_square_root(input: Annotated[Any, TV_MatrixSquareRoot_T], name=None) -> Annotated[Any, TV_MatrixSquareRoot_T]: + r"""Computes the matrix square root of one or more square matrices: + + matmul(sqrtm(A), sqrtm(A)) = A + + The input matrix should be invertible. If the input matrix is real, it should + have no eigenvalues which are real and negative (pairs of complex conjugate + eigenvalues are allowed). + + The matrix square root is computed by first reducing the matrix to + quasi-triangular form with the real Schur decomposition. The square root + of the quasi-triangular matrix is then computed directly. Details of + the algorithm can be found in: Nicholas J. Higham, "Computing real + square roots of a real matrix", Linear Algebra Appl., 1987. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. The output is a tensor of the same shape as the input + containing the matrix square root for all input submatrices `[..., :, :]`. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixSquareRoot", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_matrix_square_root( + (input, name,), None) + if _result is not NotImplemented: + return _result + return matrix_square_root_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_square_root, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_matrix_square_root( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixSquareRoot", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + matrix_square_root, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixSquareRoot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixSquareRoot = tf_export("raw_ops.MatrixSquareRoot")(_ops.to_raw_op(matrix_square_root)) +_dispatcher_for_matrix_square_root = matrix_square_root._tf_type_based_dispatcher.Dispatch + + +def matrix_square_root_eager_fallback(input: Annotated[Any, TV_MatrixSquareRoot_T], name, ctx) -> Annotated[Any, TV_MatrixSquareRoot_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MatrixSquareRoot", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixSquareRoot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatrixTriangularSolve_T = TypeVar("TV_MatrixTriangularSolve_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def matrix_triangular_solve(matrix: Annotated[Any, TV_MatrixTriangularSolve_T], rhs: Annotated[Any, TV_MatrixTriangularSolve_T], lower:bool=True, adjoint:bool=False, name=None) -> Annotated[Any, TV_MatrixTriangularSolve_T]: + r"""Solves systems of linear equations with upper or lower triangular matrices by backsubstitution. + + + `matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form + square matrices. If `lower` is `True` then the strictly upper triangular part + of each inner-most matrix is assumed to be zero and not accessed. + If `lower` is False then the strictly lower triangular part of each inner-most + matrix is assumed to be zero and not accessed. + `rhs` is a tensor of shape `[..., M, N]`. + + The output is a tensor of shape `[..., M, N]`. If `adjoint` is + `True` then the innermost matrices in `output` satisfy matrix equations + `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]`. + If `adjoint` is `False` then the strictly then the innermost matrices in + `output` satisfy matrix equations + `adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`. + + Note, the batch shapes for the inputs only need to broadcast. + + Example: + ```python + + a = tf.constant([[3, 0, 0, 0], + [2, 1, 0, 0], + [1, 0, 1, 0], + [1, 1, 1, 1]], dtype=tf.float32) + + b = tf.constant([[4], + [2], + [4], + [2]], dtype=tf.float32) + + x = tf.linalg.triangular_solve(a, b, lower=True) + x + # + + # in python3 one can use `a@x` + tf.matmul(a, x) + # + ``` + + Args: + matrix: A `Tensor`. Must be one of the following types: `bfloat16`, `float64`, `float32`, `half`, `complex64`, `complex128`. + Shape is `[..., M, M]`. + rhs: A `Tensor`. Must have the same type as `matrix`. + Shape is `[..., M, K]`. + lower: An optional `bool`. Defaults to `True`. + Boolean indicating whether the innermost matrices in `matrix` are + lower or upper triangular. + adjoint: An optional `bool`. Defaults to `False`. + Boolean indicating whether to solve with `matrix` or its (block-wise) + adjoint. + + @compatibility(numpy) + Equivalent to scipy.linalg.solve_triangular + @end_compatibility + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `matrix`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatrixTriangularSolve", name, matrix, rhs, "lower", lower, + "adjoint", adjoint) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return matrix_triangular_solve_eager_fallback( + matrix, rhs, lower=lower, adjoint=adjoint, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatrixTriangularSolve", matrix=matrix, rhs=rhs, lower=lower, + adjoint=adjoint, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("lower", _op._get_attr_bool("lower"), "adjoint", + _op._get_attr_bool("adjoint"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatrixTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatrixTriangularSolve = tf_export("raw_ops.MatrixTriangularSolve")(_ops.to_raw_op(matrix_triangular_solve)) + + +def matrix_triangular_solve_eager_fallback(matrix: Annotated[Any, TV_MatrixTriangularSolve_T], rhs: Annotated[Any, TV_MatrixTriangularSolve_T], lower: bool, adjoint: bool, name, ctx) -> Annotated[Any, TV_MatrixTriangularSolve_T]: + if lower is None: + lower = True + lower = _execute.make_bool(lower, "lower") + if adjoint is None: + adjoint = False + adjoint = _execute.make_bool(adjoint, "adjoint") + _attr_T, _inputs_T = _execute.args_to_matching_eager([matrix, rhs], ctx, [_dtypes.bfloat16, _dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + (matrix, rhs) = _inputs_T + _inputs_flat = [matrix, rhs] + _attrs = ("lower", lower, "adjoint", adjoint, "T", _attr_T) + _result = _execute.execute(b"MatrixTriangularSolve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatrixTriangularSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QrOutput = collections.namedtuple( + "Qr", + ["q", "r"]) + + +TV_Qr_T = TypeVar("TV_Qr_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.qr', v1=['linalg.qr', 'qr']) +@deprecated_endpoints('qr') +def qr(input: Annotated[Any, TV_Qr_T], full_matrices:bool=False, name=None): + r"""Computes the QR decompositions of one or more matrices. + + Computes the QR decomposition of each inner matrix in `tensor` such that + `tensor[..., :, :] = q[..., :, :] * r[..., :,:])` + + Currently, the gradient for the QR decomposition is well-defined only when + the first `P` columns of the inner matrix are linearly independent, where + `P` is the minimum of `M` and `N`, the 2 inner-most dimmensions of `tensor`. + + ```python + # a is a tensor. + # q is a tensor of orthonormal matrices. + # r is a tensor of upper triangular matrices. + q, r = qr(a) + q_full, r_full = qr(a, full_matrices=True) + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + A tensor of shape `[..., M, N]` whose inner-most 2 dimensions + form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. + full_matrices: An optional `bool`. Defaults to `False`. + If true, compute full-sized `q` and `r`. If false + (the default), compute only the leading `P` columns of `q`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (q, r). + + q: A `Tensor`. Has the same type as `input`. + r: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Qr", name, input, "full_matrices", full_matrices) + _result = _QrOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_qr( + (input, full_matrices, name,), None) + if _result is not NotImplemented: + return _result + return qr_eager_fallback( + input, full_matrices=full_matrices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + qr, (), dict(input=input, full_matrices=full_matrices, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_qr( + (input, full_matrices, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Qr", input=input, full_matrices=full_matrices, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + qr, (), dict(input=input, full_matrices=full_matrices, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("full_matrices", _op._get_attr_bool("full_matrices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Qr", _inputs_flat, _attrs, _result) + _result = _QrOutput._make(_result) + return _result + +Qr = tf_export("raw_ops.Qr")(_ops.to_raw_op(qr)) +_dispatcher_for_qr = qr._tf_type_based_dispatcher.Dispatch + + +def qr_eager_fallback(input: Annotated[Any, TV_Qr_T], full_matrices: bool, name, ctx): + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("full_matrices", full_matrices, "T", _attr_T) + _result = _execute.execute(b"Qr", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Qr", _inputs_flat, _attrs, _result) + _result = _QrOutput._make(_result) + return _result + + +TV_SelfAdjointEig_T = TypeVar("TV_SelfAdjointEig_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def self_adjoint_eig(input: Annotated[Any, TV_SelfAdjointEig_T], name=None) -> Annotated[Any, TV_SelfAdjointEig_T]: + r"""Computes the Eigen Decomposition of a batch of square self-adjoint matrices. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices, with the same constraints as the single matrix + SelfAdjointEig. + + The result is a [..., M+1, M] matrix with [..., 0,:] containing the + eigenvalues, and subsequent [...,1:, :] containing the eigenvectors. The eigenvalues + are sorted in non-decreasing order. + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`. + Shape is `[..., M, M]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SelfAdjointEig", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return self_adjoint_eig_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SelfAdjointEig", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SelfAdjointEig", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SelfAdjointEig = tf_export("raw_ops.SelfAdjointEig")(_ops.to_raw_op(self_adjoint_eig)) + + +def self_adjoint_eig_eager_fallback(input: Annotated[Any, TV_SelfAdjointEig_T], name, ctx) -> Annotated[Any, TV_SelfAdjointEig_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SelfAdjointEig", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SelfAdjointEig", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SelfAdjointEigV2Output = collections.namedtuple( + "SelfAdjointEigV2", + ["e", "v"]) + + +TV_SelfAdjointEigV2_T = TypeVar("TV_SelfAdjointEigV2_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def self_adjoint_eig_v2(input: Annotated[Any, TV_SelfAdjointEigV2_T], compute_v:bool=True, name=None): + r"""Computes the eigen decomposition of one or more square self-adjoint matrices. + + Computes the eigenvalues and (optionally) eigenvectors of each inner matrix in + `input` such that `input[..., :, :] = v[..., :, :] * diag(e[..., :])`. The eigenvalues + are sorted in non-decreasing order. + + ```python + # a is a tensor. + # e is a tensor of eigenvalues. + # v is a tensor of eigenvectors. + e, v = self_adjoint_eig(a) + e = self_adjoint_eig(a, compute_v=False) + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + `Tensor` input of shape `[N, N]`. + compute_v: An optional `bool`. Defaults to `True`. + If `True` then eigenvectors will be computed and returned in `v`. + Otherwise, only the eigenvalues will be computed. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (e, v). + + e: A `Tensor`. Has the same type as `input`. + v: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SelfAdjointEigV2", name, input, "compute_v", compute_v) + _result = _SelfAdjointEigV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return self_adjoint_eig_v2_eager_fallback( + input, compute_v=compute_v, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SelfAdjointEigV2", input=input, compute_v=compute_v, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compute_v", _op._get_attr_bool("compute_v"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SelfAdjointEigV2", _inputs_flat, _attrs, _result) + _result = _SelfAdjointEigV2Output._make(_result) + return _result + +SelfAdjointEigV2 = tf_export("raw_ops.SelfAdjointEigV2")(_ops.to_raw_op(self_adjoint_eig_v2)) + + +def self_adjoint_eig_v2_eager_fallback(input: Annotated[Any, TV_SelfAdjointEigV2_T], compute_v: bool, name, ctx): + if compute_v is None: + compute_v = True + compute_v = _execute.make_bool(compute_v, "compute_v") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("compute_v", compute_v, "T", _attr_T) + _result = _execute.execute(b"SelfAdjointEigV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SelfAdjointEigV2", _inputs_flat, _attrs, _result) + _result = _SelfAdjointEigV2Output._make(_result) + return _result + +_SvdOutput = collections.namedtuple( + "Svd", + ["s", "u", "v"]) + + +TV_Svd_T = TypeVar("TV_Svd_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def svd(input: Annotated[Any, TV_Svd_T], compute_uv:bool=True, full_matrices:bool=False, name=None): + r"""Computes the singular value decompositions of one or more matrices. + + Computes the SVD of each inner matrix in `input` such that + `input[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])` + + ```python + # a is a tensor containing a batch of matrices. + # s is a tensor of singular values for each matrix. + # u is the tensor containing the left singular vectors for each matrix. + # v is the tensor containing the right singular vectors for each matrix. + s, u, v = svd(a) + s, _, _ = svd(a, compute_uv=False) + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `half`, `complex64`, `complex128`. + A tensor of shape `[..., M, N]` whose inner-most 2 dimensions + form matrices of size `[M, N]`. Let `P` be the minimum of `M` and `N`. + compute_uv: An optional `bool`. Defaults to `True`. + If true, left and right singular vectors will be + computed and returned in `u` and `v`, respectively. + If false, `u` and `v` are not set and should never referenced. + full_matrices: An optional `bool`. Defaults to `False`. + If true, compute full-sized `u` and `v`. If false + (the default), compute only the leading `P` singular vectors. + Ignored if `compute_uv` is `False`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (s, u, v). + + s: A `Tensor`. Has the same type as `input`. + u: A `Tensor`. Has the same type as `input`. + v: A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Svd", name, input, "compute_uv", compute_uv, "full_matrices", + full_matrices) + _result = _SvdOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return svd_eager_fallback( + input, compute_uv=compute_uv, full_matrices=full_matrices, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if compute_uv is None: + compute_uv = True + compute_uv = _execute.make_bool(compute_uv, "compute_uv") + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Svd", input=input, compute_uv=compute_uv, + full_matrices=full_matrices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compute_uv", _op._get_attr_bool("compute_uv"), "full_matrices", + _op._get_attr_bool("full_matrices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Svd", _inputs_flat, _attrs, _result) + _result = _SvdOutput._make(_result) + return _result + +Svd = tf_export("raw_ops.Svd")(_ops.to_raw_op(svd)) + + +def svd_eager_fallback(input: Annotated[Any, TV_Svd_T], compute_uv: bool, full_matrices: bool, name, ctx): + if compute_uv is None: + compute_uv = True + compute_uv = _execute.make_bool(compute_uv, "compute_uv") + if full_matrices is None: + full_matrices = False + full_matrices = _execute.make_bool(full_matrices, "full_matrices") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.half, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [input] + _attrs = ("compute_uv", compute_uv, "full_matrices", full_matrices, "T", + _attr_T) + _result = _execute.execute(b"Svd", 3, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Svd", _inputs_flat, _attrs, _result) + _result = _SvdOutput._make(_result) + return _result + + +TV_TridiagonalMatMul_T = TypeVar("TV_TridiagonalMatMul_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def tridiagonal_mat_mul(superdiag: Annotated[Any, TV_TridiagonalMatMul_T], maindiag: Annotated[Any, TV_TridiagonalMatMul_T], subdiag: Annotated[Any, TV_TridiagonalMatMul_T], rhs: Annotated[Any, TV_TridiagonalMatMul_T], name=None) -> Annotated[Any, TV_TridiagonalMatMul_T]: + r"""Calculate product with tridiagonal matrix. + + Calculates product of two matrices, where left matrix is a tridiagonal matrix. + + Args: + superdiag: A `Tensor`. Must be one of the following types: `float64`, `float32`, `complex64`, `complex128`. + Tensor of shape `[..., 1, M]`, representing superdiagonals of + tri-diagonal matrices to the left of multiplication. Last element is ignored. + maindiag: A `Tensor`. Must have the same type as `superdiag`. + Tensor of shape `[..., 1, M]`, representing main diagonals of tri-diagonal + matrices to the left of multiplication. + subdiag: A `Tensor`. Must have the same type as `superdiag`. + Tensor of shape `[..., 1, M]`, representing subdiagonals of tri-diagonal + matrices to the left of multiplication. First element is ignored. + rhs: A `Tensor`. Must have the same type as `superdiag`. + Tensor of shape `[..., M, N]`, representing MxN matrices to the right of + multiplication. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `superdiag`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TridiagonalMatMul", name, superdiag, maindiag, subdiag, rhs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tridiagonal_mat_mul_eager_fallback( + superdiag, maindiag, subdiag, rhs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TridiagonalMatMul", superdiag=superdiag, maindiag=maindiag, + subdiag=subdiag, rhs=rhs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TridiagonalMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TridiagonalMatMul = tf_export("raw_ops.TridiagonalMatMul")(_ops.to_raw_op(tridiagonal_mat_mul)) + + +def tridiagonal_mat_mul_eager_fallback(superdiag: Annotated[Any, TV_TridiagonalMatMul_T], maindiag: Annotated[Any, TV_TridiagonalMatMul_T], subdiag: Annotated[Any, TV_TridiagonalMatMul_T], rhs: Annotated[Any, TV_TridiagonalMatMul_T], name, ctx) -> Annotated[Any, TV_TridiagonalMatMul_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([superdiag, maindiag, subdiag, rhs], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.complex64, _dtypes.complex128, ]) + (superdiag, maindiag, subdiag, rhs) = _inputs_T + _inputs_flat = [superdiag, maindiag, subdiag, rhs] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TridiagonalMatMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TridiagonalMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TridiagonalSolve_T = TypeVar("TV_TridiagonalSolve_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def tridiagonal_solve(diagonals: Annotated[Any, TV_TridiagonalSolve_T], rhs: Annotated[Any, TV_TridiagonalSolve_T], partial_pivoting:bool=True, perturb_singular:bool=False, name=None) -> Annotated[Any, TV_TridiagonalSolve_T]: + r"""Solves tridiagonal systems of equations. + + Solves tridiagonal systems of equations. + Supports batch dimensions and multiple right-hand sides per each left-hand + side. + On CPU, solution is computed via Gaussian elimination with or without partial + pivoting, depending on `partial_pivoting` attribute. On GPU, Nvidia's cuSPARSE + library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv + Partial pivoting is not yet supported by XLA backends. + + Args: + diagonals: A `Tensor`. Must be one of the following types: `float64`, `float32`, `complex64`, `complex128`. + Tensor of shape `[..., 3, M]` whose innermost 2 dimensions represent the + tridiagonal matrices with three rows being the superdiagonal, diagonals, and + subdiagonals, in order. The last element of the superdiagonal and the first + element of the subdiagonal is ignored. + rhs: A `Tensor`. Must have the same type as `diagonals`. + Tensor of shape `[..., M, K]`, representing K right-hand sides per each + left-hand side. + partial_pivoting: An optional `bool`. Defaults to `True`. + Whether to apply partial pivoting. Partial pivoting makes the procedure more + stable, but slower. + perturb_singular: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `diagonals`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TridiagonalSolve", name, diagonals, rhs, "partial_pivoting", + partial_pivoting, "perturb_singular", perturb_singular) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tridiagonal_solve_eager_fallback( + diagonals, rhs, partial_pivoting=partial_pivoting, + perturb_singular=perturb_singular, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if partial_pivoting is None: + partial_pivoting = True + partial_pivoting = _execute.make_bool(partial_pivoting, "partial_pivoting") + if perturb_singular is None: + perturb_singular = False + perturb_singular = _execute.make_bool(perturb_singular, "perturb_singular") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TridiagonalSolve", diagonals=diagonals, rhs=rhs, + partial_pivoting=partial_pivoting, + perturb_singular=perturb_singular, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("partial_pivoting", _op._get_attr_bool("partial_pivoting"), + "perturb_singular", _op._get_attr_bool("perturb_singular"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TridiagonalSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TridiagonalSolve = tf_export("raw_ops.TridiagonalSolve")(_ops.to_raw_op(tridiagonal_solve)) + + +def tridiagonal_solve_eager_fallback(diagonals: Annotated[Any, TV_TridiagonalSolve_T], rhs: Annotated[Any, TV_TridiagonalSolve_T], partial_pivoting: bool, perturb_singular: bool, name, ctx) -> Annotated[Any, TV_TridiagonalSolve_T]: + if partial_pivoting is None: + partial_pivoting = True + partial_pivoting = _execute.make_bool(partial_pivoting, "partial_pivoting") + if perturb_singular is None: + perturb_singular = False + perturb_singular = _execute.make_bool(perturb_singular, "perturb_singular") + _attr_T, _inputs_T = _execute.args_to_matching_eager([diagonals, rhs], ctx, [_dtypes.float64, _dtypes.float32, _dtypes.complex64, _dtypes.complex128, ]) + (diagonals, rhs) = _inputs_T + _inputs_flat = [diagonals, rhs] + _attrs = ("partial_pivoting", partial_pivoting, "perturb_singular", + perturb_singular, "T", _attr_T) + _result = _execute.execute(b"TridiagonalSolve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TridiagonalSolve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_list_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_list_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..032f2bbe22dbc6b69b996ae57011d3886a02a5aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_list_ops.py @@ -0,0 +1,1464 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_EmptyTensorList_element_dtype = TypeVar("TV_EmptyTensorList_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_EmptyTensorList_shape_type = TypeVar("TV_EmptyTensorList_shape_type", _atypes.Int32, _atypes.Int64) + +def empty_tensor_list(element_shape: Annotated[Any, TV_EmptyTensorList_shape_type], max_num_elements: Annotated[Any, _atypes.Int32], element_dtype: TV_EmptyTensorList_element_dtype, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates and returns an empty tensor list. + + All list elements must be tensors of dtype element_dtype and shape compatible + with element_shape. + + handle: an empty tensor list. + element_dtype: the type of elements in the list. + element_shape: a shape compatible with that of elements in the list. + + Args: + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + max_num_elements: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EmptyTensorList", name, element_shape, max_num_elements, + "element_dtype", element_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return empty_tensor_list_eager_fallback( + element_shape, max_num_elements, element_dtype=element_dtype, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EmptyTensorList", element_shape=element_shape, + max_num_elements=max_num_elements, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EmptyTensorList", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EmptyTensorList = tf_export("raw_ops.EmptyTensorList")(_ops.to_raw_op(empty_tensor_list)) + + +def empty_tensor_list_eager_fallback(element_shape: Annotated[Any, TV_EmptyTensorList_shape_type], max_num_elements: Annotated[Any, _atypes.Int32], element_dtype: TV_EmptyTensorList_element_dtype, name, ctx) -> Annotated[Any, _atypes.Variant]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + max_num_elements = _ops.convert_to_tensor(max_num_elements, _dtypes.int32) + _inputs_flat = [element_shape, max_num_elements] + _attrs = ("element_dtype", element_dtype, "shape_type", _attr_shape_type) + _result = _execute.execute(b"EmptyTensorList", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EmptyTensorList", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TensorListConcatOutput = collections.namedtuple( + "TensorListConcat", + ["tensor", "lengths"]) + + +TV_TensorListConcat_element_dtype = TypeVar("TV_TensorListConcat_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_concat(input_handle: Annotated[Any, _atypes.Variant], element_dtype: TV_TensorListConcat_element_dtype, element_shape=None, name=None): + r"""Concats all tensors in the list along the 0th dimension. + + Requires that all tensors have the same shape except the first dimension. + + input_handle: The input list. + tensor: The concated result. + lengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient. + + Args: + input_handle: A `Tensor` of type `variant`. + element_dtype: A `tf.DType`. + element_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (tensor, lengths). + + tensor: A `Tensor` of type `element_dtype`. + lengths: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListConcat", name, input_handle, "element_dtype", + element_dtype, "element_shape", element_shape) + _result = _TensorListConcatOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_concat_eager_fallback( + input_handle, element_dtype=element_dtype, + element_shape=element_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListConcat", input_handle=input_handle, + element_dtype=element_dtype, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "element_shape", _op.get_attr("element_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListConcat", _inputs_flat, _attrs, _result) + _result = _TensorListConcatOutput._make(_result) + return _result + +TensorListConcat = tf_export("raw_ops.TensorListConcat")(_ops.to_raw_op(tensor_list_concat)) + + +def tensor_list_concat_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], element_dtype: TV_TensorListConcat_element_dtype, element_shape, name, ctx): + element_dtype = _execute.make_type(element_dtype, "element_dtype") + if element_shape is None: + element_shape = None + element_shape = _execute.make_shape(element_shape, "element_shape") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = ("element_dtype", element_dtype, "element_shape", element_shape) + _result = _execute.execute(b"TensorListConcat", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListConcat", _inputs_flat, _attrs, _result) + _result = _TensorListConcatOutput._make(_result) + return _result + + +TV_TensorListConcatLists_element_dtype = TypeVar("TV_TensorListConcatLists_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_concat_lists(input_a: Annotated[Any, _atypes.Variant], input_b: Annotated[Any, _atypes.Variant], element_dtype: TV_TensorListConcatLists_element_dtype, name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_a: A `Tensor` of type `variant`. + input_b: A `Tensor` of type `variant`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListConcatLists", name, input_a, input_b, + "element_dtype", element_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_concat_lists_eager_fallback( + input_a, input_b, element_dtype=element_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListConcatLists", input_a=input_a, input_b=input_b, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListConcatLists", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListConcatLists = tf_export("raw_ops.TensorListConcatLists")(_ops.to_raw_op(tensor_list_concat_lists)) + + +def tensor_list_concat_lists_eager_fallback(input_a: Annotated[Any, _atypes.Variant], input_b: Annotated[Any, _atypes.Variant], element_dtype: TV_TensorListConcatLists_element_dtype, name, ctx) -> Annotated[Any, _atypes.Variant]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + input_a = _ops.convert_to_tensor(input_a, _dtypes.variant) + input_b = _ops.convert_to_tensor(input_b, _dtypes.variant) + _inputs_flat = [input_a, input_b] + _attrs = ("element_dtype", element_dtype) + _result = _execute.execute(b"TensorListConcatLists", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListConcatLists", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TensorListConcatV2Output = collections.namedtuple( + "TensorListConcatV2", + ["tensor", "lengths"]) + + +TV_TensorListConcatV2_element_dtype = TypeVar("TV_TensorListConcatV2_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListConcatV2_shape_type = TypeVar("TV_TensorListConcatV2_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_concat_v2(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, TV_TensorListConcatV2_shape_type], leading_dims: Annotated[Any, _atypes.Int64], element_dtype: TV_TensorListConcatV2_element_dtype, name=None): + r"""Concats all tensors in the list along the 0th dimension. + + Requires that all tensors have the same shape except the first dimension. + + input_handle: The input list. + element_shape: The shape of the uninitialized elements in the list. If the first + dimension is not -1, it is assumed that all list elements have the same + leading dim. + leading_dims: The list of leading dims of uninitialized list elements. Used if + the leading dim of input_handle.element_shape or the element_shape input arg + is not already set. + tensor: The concated result. + lengths: Output tensor containing sizes of the 0th dimension of tensors in the list, used for computing the gradient. + + Args: + input_handle: A `Tensor` of type `variant`. + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + leading_dims: A `Tensor` of type `int64`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (tensor, lengths). + + tensor: A `Tensor` of type `element_dtype`. + lengths: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListConcatV2", name, input_handle, element_shape, + leading_dims, "element_dtype", element_dtype) + _result = _TensorListConcatV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_concat_v2_eager_fallback( + input_handle, element_shape, leading_dims, + element_dtype=element_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListConcatV2", input_handle=input_handle, + element_shape=element_shape, + leading_dims=leading_dims, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListConcatV2", _inputs_flat, _attrs, _result) + _result = _TensorListConcatV2Output._make(_result) + return _result + +TensorListConcatV2 = tf_export("raw_ops.TensorListConcatV2")(_ops.to_raw_op(tensor_list_concat_v2)) + + +def tensor_list_concat_v2_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, TV_TensorListConcatV2_shape_type], leading_dims: Annotated[Any, _atypes.Int64], element_dtype: TV_TensorListConcatV2_element_dtype, name, ctx): + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + leading_dims = _ops.convert_to_tensor(leading_dims, _dtypes.int64) + _inputs_flat = [input_handle, element_shape, leading_dims] + _attrs = ("element_dtype", element_dtype, "shape_type", _attr_shape_type) + _result = _execute.execute(b"TensorListConcatV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListConcatV2", _inputs_flat, _attrs, _result) + _result = _TensorListConcatV2Output._make(_result) + return _result + + +TV_TensorListElementShape_shape_type = TypeVar("TV_TensorListElementShape_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_element_shape(input_handle: Annotated[Any, _atypes.Variant], shape_type: TV_TensorListElementShape_shape_type, name=None) -> Annotated[Any, TV_TensorListElementShape_shape_type]: + r"""The shape of the elements of the given list, as a tensor. + + input_handle: the list + element_shape: the shape of elements of the list + + Args: + input_handle: A `Tensor` of type `variant`. + shape_type: A `tf.DType` from: `tf.int32, tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `shape_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListElementShape", name, input_handle, "shape_type", + shape_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_element_shape_eager_fallback( + input_handle, shape_type=shape_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shape_type = _execute.make_type(shape_type, "shape_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListElementShape", input_handle=input_handle, + shape_type=shape_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListElementShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListElementShape = tf_export("raw_ops.TensorListElementShape")(_ops.to_raw_op(tensor_list_element_shape)) + + +def tensor_list_element_shape_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], shape_type: TV_TensorListElementShape_shape_type, name, ctx) -> Annotated[Any, TV_TensorListElementShape_shape_type]: + shape_type = _execute.make_type(shape_type, "shape_type") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = ("shape_type", shape_type) + _result = _execute.execute(b"TensorListElementShape", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListElementShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListFromTensor_element_dtype = TypeVar("TV_TensorListFromTensor_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListFromTensor_shape_type = TypeVar("TV_TensorListFromTensor_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_from_tensor(tensor: Annotated[Any, TV_TensorListFromTensor_element_dtype], element_shape: Annotated[Any, TV_TensorListFromTensor_shape_type], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a TensorList which, when stacked, has the value of `tensor`. + + Each tensor in the result list corresponds to one row of the input tensor. + + tensor: The input tensor. + output_handle: The list. + + Args: + tensor: A `Tensor`. + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListFromTensor", name, tensor, element_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_from_tensor_eager_fallback( + tensor, element_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListFromTensor", tensor=tensor, element_shape=element_shape, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListFromTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListFromTensor = tf_export("raw_ops.TensorListFromTensor")(_ops.to_raw_op(tensor_list_from_tensor)) + + +def tensor_list_from_tensor_eager_fallback(tensor: Annotated[Any, TV_TensorListFromTensor_element_dtype], element_shape: Annotated[Any, TV_TensorListFromTensor_shape_type], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [tensor, element_shape] + _attrs = ("element_dtype", _attr_element_dtype, "shape_type", + _attr_shape_type) + _result = _execute.execute(b"TensorListFromTensor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListFromTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListGather_element_dtype = TypeVar("TV_TensorListGather_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_gather(input_handle: Annotated[Any, _atypes.Variant], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListGather_element_dtype, name=None) -> Annotated[Any, TV_TensorListGather_element_dtype]: + r"""Creates a Tensor by indexing into the TensorList. + + Each row in the produced Tensor corresponds to the element in the TensorList + specified by the given index (see `tf.gather`). + + input_handle: The input tensor list. + indices: The indices used to index into the list. + values: The tensor. + + Args: + input_handle: A `Tensor` of type `variant`. + indices: A `Tensor` of type `int32`. + element_shape: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `element_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListGather", name, input_handle, indices, element_shape, + "element_dtype", element_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_gather_eager_fallback( + input_handle, indices, element_shape, element_dtype=element_dtype, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListGather", input_handle=input_handle, indices=indices, + element_shape=element_shape, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListGather = tf_export("raw_ops.TensorListGather")(_ops.to_raw_op(tensor_list_gather)) + + +def tensor_list_gather_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListGather_element_dtype, name, ctx) -> Annotated[Any, TV_TensorListGather_element_dtype]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + element_shape = _ops.convert_to_tensor(element_shape, _dtypes.int32) + _inputs_flat = [input_handle, indices, element_shape] + _attrs = ("element_dtype", element_dtype) + _result = _execute.execute(b"TensorListGather", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListGetItem_element_dtype = TypeVar("TV_TensorListGetItem_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_get_item(input_handle: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListGetItem_element_dtype, name=None) -> Annotated[Any, TV_TensorListGetItem_element_dtype]: + r"""Returns the item in the list with the given index. + + input_handle: the list + index: the position in the list from which an element will be retrieved + item: the element at that position + + Args: + input_handle: A `Tensor` of type `variant`. + index: A `Tensor` of type `int32`. + element_shape: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `element_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListGetItem", name, input_handle, index, element_shape, + "element_dtype", element_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_get_item_eager_fallback( + input_handle, index, element_shape, element_dtype=element_dtype, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListGetItem", input_handle=input_handle, index=index, + element_shape=element_shape, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListGetItem", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListGetItem = tf_export("raw_ops.TensorListGetItem")(_ops.to_raw_op(tensor_list_get_item)) + + +def tensor_list_get_item_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListGetItem_element_dtype, name, ctx) -> Annotated[Any, TV_TensorListGetItem_element_dtype]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + index = _ops.convert_to_tensor(index, _dtypes.int32) + element_shape = _ops.convert_to_tensor(element_shape, _dtypes.int32) + _inputs_flat = [input_handle, index, element_shape] + _attrs = ("element_dtype", element_dtype) + _result = _execute.execute(b"TensorListGetItem", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListGetItem", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_list_length(input_handle: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the number of tensors in the input tensor list. + + input_handle: the input list + length: the number of tensors in the list + + Args: + input_handle: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListLength", name, input_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_length_eager_fallback( + input_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListLength", input_handle=input_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListLength", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListLength = tf_export("raw_ops.TensorListLength")(_ops.to_raw_op(tensor_list_length)) + + +def tensor_list_length_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int32]: + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = None + _result = _execute.execute(b"TensorListLength", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListLength", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TensorListPopBackOutput = collections.namedtuple( + "TensorListPopBack", + ["output_handle", "tensor"]) + + +TV_TensorListPopBack_element_dtype = TypeVar("TV_TensorListPopBack_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_pop_back(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListPopBack_element_dtype, name=None): + r"""Returns the last element of the input list as well as a list with all but that element. + + Fails if the list is empty. + + input_handle: the input list + tensor: the withdrawn last element of the list + element_dtype: the type of elements in the list + element_shape: the shape of the output tensor + + Args: + input_handle: A `Tensor` of type `variant`. + element_shape: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_handle, tensor). + + output_handle: A `Tensor` of type `variant`. + tensor: A `Tensor` of type `element_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListPopBack", name, input_handle, element_shape, + "element_dtype", element_dtype) + _result = _TensorListPopBackOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_pop_back_eager_fallback( + input_handle, element_shape, element_dtype=element_dtype, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListPopBack", input_handle=input_handle, + element_shape=element_shape, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListPopBack", _inputs_flat, _attrs, _result) + _result = _TensorListPopBackOutput._make(_result) + return _result + +TensorListPopBack = tf_export("raw_ops.TensorListPopBack")(_ops.to_raw_op(tensor_list_pop_back)) + + +def tensor_list_pop_back_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListPopBack_element_dtype, name, ctx): + element_dtype = _execute.make_type(element_dtype, "element_dtype") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + element_shape = _ops.convert_to_tensor(element_shape, _dtypes.int32) + _inputs_flat = [input_handle, element_shape] + _attrs = ("element_dtype", element_dtype) + _result = _execute.execute(b"TensorListPopBack", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListPopBack", _inputs_flat, _attrs, _result) + _result = _TensorListPopBackOutput._make(_result) + return _result + + +TV_TensorListPushBack_element_dtype = TypeVar("TV_TensorListPushBack_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_push_back(input_handle: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListPushBack_element_dtype], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Returns a list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`. + + tensor: The tensor to put on the list. + input_handle: The old list. + output_handle: A list with the elements of the old list followed by tensor. + element_dtype: the type of elements in the list. + element_shape: a shape compatible with that of elements in the list. + + Args: + input_handle: A `Tensor` of type `variant`. + tensor: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListPushBack", name, input_handle, tensor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_push_back_eager_fallback( + input_handle, tensor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListPushBack", input_handle=input_handle, tensor=tensor, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListPushBack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListPushBack = tf_export("raw_ops.TensorListPushBack")(_ops.to_raw_op(tensor_list_push_back)) + + +def tensor_list_push_back_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListPushBack_element_dtype], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle, tensor] + _attrs = ("element_dtype", _attr_element_dtype) + _result = _execute.execute(b"TensorListPushBack", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListPushBack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListPushBackBatch_element_dtype = TypeVar("TV_TensorListPushBackBatch_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_push_back_batch(input_handles: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListPushBackBatch_element_dtype], name=None) -> Annotated[Any, _atypes.Variant]: + r"""TODO: add doc. + + Args: + input_handles: A `Tensor` of type `variant`. + tensor: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListPushBackBatch", name, input_handles, tensor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_push_back_batch_eager_fallback( + input_handles, tensor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListPushBackBatch", input_handles=input_handles, tensor=tensor, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListPushBackBatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListPushBackBatch = tf_export("raw_ops.TensorListPushBackBatch")(_ops.to_raw_op(tensor_list_push_back_batch)) + + +def tensor_list_push_back_batch_eager_fallback(input_handles: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListPushBackBatch_element_dtype], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + input_handles = _ops.convert_to_tensor(input_handles, _dtypes.variant) + _inputs_flat = [input_handles, tensor] + _attrs = ("element_dtype", _attr_element_dtype) + _result = _execute.execute(b"TensorListPushBackBatch", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListPushBackBatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListReserve_element_dtype = TypeVar("TV_TensorListReserve_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListReserve_shape_type = TypeVar("TV_TensorListReserve_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_reserve(element_shape: Annotated[Any, TV_TensorListReserve_shape_type], num_elements: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListReserve_element_dtype, name=None) -> Annotated[Any, _atypes.Variant]: + r"""List of the given size with empty elements. + + element_shape: the shape of the future elements of the list + num_elements: the number of elements to reserve + handle: the output list + element_dtype: the desired type of elements in the list. + + Args: + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + num_elements: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListReserve", name, element_shape, num_elements, + "element_dtype", element_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_reserve_eager_fallback( + element_shape, num_elements, element_dtype=element_dtype, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListReserve", element_shape=element_shape, + num_elements=num_elements, + element_dtype=element_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListReserve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListReserve = tf_export("raw_ops.TensorListReserve")(_ops.to_raw_op(tensor_list_reserve)) + + +def tensor_list_reserve_eager_fallback(element_shape: Annotated[Any, TV_TensorListReserve_shape_type], num_elements: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListReserve_element_dtype, name, ctx) -> Annotated[Any, _atypes.Variant]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + num_elements = _ops.convert_to_tensor(num_elements, _dtypes.int32) + _inputs_flat = [element_shape, num_elements] + _attrs = ("element_dtype", element_dtype, "shape_type", _attr_shape_type) + _result = _execute.execute(b"TensorListReserve", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListReserve", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_list_resize(input_handle: Annotated[Any, _atypes.Variant], size: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Resizes the list. + + + input_handle: the input list + size: size of the output list + + Args: + input_handle: A `Tensor` of type `variant`. + size: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListResize", name, input_handle, size) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_resize_eager_fallback( + input_handle, size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListResize", input_handle=input_handle, size=size, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListResize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListResize = tf_export("raw_ops.TensorListResize")(_ops.to_raw_op(tensor_list_resize)) + + +def tensor_list_resize_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], size: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Variant]: + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [input_handle, size] + _attrs = None + _result = _execute.execute(b"TensorListResize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListResize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListScatter_element_dtype = TypeVar("TV_TensorListScatter_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListScatter_shape_type = TypeVar("TV_TensorListScatter_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_scatter(tensor: Annotated[Any, TV_TensorListScatter_element_dtype], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, TV_TensorListScatter_shape_type], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a TensorList by indexing into a Tensor. + + Each member of the TensorList corresponds to one row of the input tensor, + specified by the given index (see `tf.gather`). + + tensor: The input tensor. + indices: The indices used to index into the list. + element_shape: The shape of the elements in the list (can be less specified than + the shape of the tensor). + output_handle: The TensorList. + + Args: + tensor: A `Tensor`. + indices: A `Tensor` of type `int32`. + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListScatter", name, tensor, indices, element_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_scatter_eager_fallback( + tensor, indices, element_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListScatter", tensor=tensor, indices=indices, + element_shape=element_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListScatter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListScatter = tf_export("raw_ops.TensorListScatter")(_ops.to_raw_op(tensor_list_scatter)) + + +def tensor_list_scatter_eager_fallback(tensor: Annotated[Any, TV_TensorListScatter_element_dtype], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, TV_TensorListScatter_shape_type], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [tensor, indices, element_shape] + _attrs = ("element_dtype", _attr_element_dtype, "shape_type", + _attr_shape_type) + _result = _execute.execute(b"TensorListScatter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListScatter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListScatterIntoExistingList_element_dtype = TypeVar("TV_TensorListScatterIntoExistingList_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_scatter_into_existing_list(input_handle: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListScatterIntoExistingList_element_dtype], indices: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Scatters tensor at indices in an input list. + + Each member of the TensorList corresponds to one row of the input tensor, + specified by the given index (see `tf.gather`). + + input_handle: The list to scatter into. + tensor: The input tensor. + indices: The indices used to index into the list. + output_handle: The TensorList. + + Args: + input_handle: A `Tensor` of type `variant`. + tensor: A `Tensor`. + indices: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListScatterIntoExistingList", name, input_handle, tensor, + indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_scatter_into_existing_list_eager_fallback( + input_handle, tensor, indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListScatterIntoExistingList", input_handle=input_handle, + tensor=tensor, indices=indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListScatterIntoExistingList", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListScatterIntoExistingList = tf_export("raw_ops.TensorListScatterIntoExistingList")(_ops.to_raw_op(tensor_list_scatter_into_existing_list)) + + +def tensor_list_scatter_into_existing_list_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], tensor: Annotated[Any, TV_TensorListScatterIntoExistingList_element_dtype], indices: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + _inputs_flat = [input_handle, tensor, indices] + _attrs = ("element_dtype", _attr_element_dtype) + _result = _execute.execute(b"TensorListScatterIntoExistingList", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListScatterIntoExistingList", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListScatterV2_element_dtype = TypeVar("TV_TensorListScatterV2_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListScatterV2_shape_type = TypeVar("TV_TensorListScatterV2_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_scatter_v2(tensor: Annotated[Any, TV_TensorListScatterV2_element_dtype], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, TV_TensorListScatterV2_shape_type], num_elements: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates a TensorList by indexing into a Tensor. + + Each member of the TensorList corresponds to one row of the input tensor, + specified by the given index (see `tf.gather`). + + tensor: The input tensor. + indices: The indices used to index into the list. + element_shape: The shape of the elements in the list (can be less specified than + the shape of the tensor). + num_elements: The size of the output list. Must be large enough to accommodate + the largest index in indices. If -1, the list is just large enough to include + the largest index in indices. + output_handle: The TensorList. + + Args: + tensor: A `Tensor`. + indices: A `Tensor` of type `int32`. + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + num_elements: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListScatterV2", name, tensor, indices, element_shape, + num_elements) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_scatter_v2_eager_fallback( + tensor, indices, element_shape, num_elements, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListScatterV2", tensor=tensor, indices=indices, + element_shape=element_shape, + num_elements=num_elements, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListScatterV2 = tf_export("raw_ops.TensorListScatterV2")(_ops.to_raw_op(tensor_list_scatter_v2)) + + +def tensor_list_scatter_v2_eager_fallback(tensor: Annotated[Any, TV_TensorListScatterV2_element_dtype], indices: Annotated[Any, _atypes.Int32], element_shape: Annotated[Any, TV_TensorListScatterV2_shape_type], num_elements: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int32) + num_elements = _ops.convert_to_tensor(num_elements, _dtypes.int32) + _inputs_flat = [tensor, indices, element_shape, num_elements] + _attrs = ("element_dtype", _attr_element_dtype, "shape_type", + _attr_shape_type) + _result = _execute.execute(b"TensorListScatterV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListScatterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListSetItem_element_dtype = TypeVar("TV_TensorListSetItem_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_set_item(input_handle: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], item: Annotated[Any, TV_TensorListSetItem_element_dtype], resize_if_index_out_of_bounds:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Sets the index-th position of the list to contain the given tensor. + + input_handle: the list + index: the position in the list to which the tensor will be assigned + item: the element to be assigned to that position + output_handle: the new list, with the element in the proper position + + Args: + input_handle: A `Tensor` of type `variant`. + index: A `Tensor` of type `int32`. + item: A `Tensor`. + resize_if_index_out_of_bounds: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListSetItem", name, input_handle, index, item, + "resize_if_index_out_of_bounds", resize_if_index_out_of_bounds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_set_item_eager_fallback( + input_handle, index, item, + resize_if_index_out_of_bounds=resize_if_index_out_of_bounds, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if resize_if_index_out_of_bounds is None: + resize_if_index_out_of_bounds = False + resize_if_index_out_of_bounds = _execute.make_bool(resize_if_index_out_of_bounds, "resize_if_index_out_of_bounds") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListSetItem", input_handle=input_handle, index=index, + item=item, + resize_if_index_out_of_bounds=resize_if_index_out_of_bounds, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "resize_if_index_out_of_bounds", + _op._get_attr_bool("resize_if_index_out_of_bounds")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListSetItem", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListSetItem = tf_export("raw_ops.TensorListSetItem")(_ops.to_raw_op(tensor_list_set_item)) + + +def tensor_list_set_item_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], item: Annotated[Any, TV_TensorListSetItem_element_dtype], resize_if_index_out_of_bounds: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if resize_if_index_out_of_bounds is None: + resize_if_index_out_of_bounds = False + resize_if_index_out_of_bounds = _execute.make_bool(resize_if_index_out_of_bounds, "resize_if_index_out_of_bounds") + _attr_element_dtype, (item,) = _execute.args_to_matching_eager([item], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + index = _ops.convert_to_tensor(index, _dtypes.int32) + _inputs_flat = [input_handle, index, item] + _attrs = ("element_dtype", _attr_element_dtype, + "resize_if_index_out_of_bounds", resize_if_index_out_of_bounds) + _result = _execute.execute(b"TensorListSetItem", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListSetItem", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListSplit_element_dtype = TypeVar("TV_TensorListSplit_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorListSplit_shape_type = TypeVar("TV_TensorListSplit_shape_type", _atypes.Int32, _atypes.Int64) + +def tensor_list_split(tensor: Annotated[Any, TV_TensorListSplit_element_dtype], element_shape: Annotated[Any, TV_TensorListSplit_shape_type], lengths: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Splits a tensor into a list. + + list[i] corresponds to lengths[i] tensors from the input tensor. + The tensor must have rank at least 1 and contain exactly sum(lengths) elements. + + tensor: The input tensor. + element_shape: A shape compatible with that of elements in the tensor. + lengths: Vector of sizes of the 0th dimension of tensors in the list. + output_handle: The list. + + Args: + tensor: A `Tensor`. + element_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + lengths: A `Tensor` of type `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListSplit", name, tensor, element_shape, lengths) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_split_eager_fallback( + tensor, element_shape, lengths, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListSplit", tensor=tensor, element_shape=element_shape, + lengths=lengths, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "shape_type", _op._get_attr_type("shape_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListSplit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListSplit = tf_export("raw_ops.TensorListSplit")(_ops.to_raw_op(tensor_list_split)) + + +def tensor_list_split_eager_fallback(tensor: Annotated[Any, TV_TensorListSplit_element_dtype], element_shape: Annotated[Any, TV_TensorListSplit_shape_type], lengths: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_element_dtype, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _attr_shape_type, (element_shape,) = _execute.args_to_matching_eager([element_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + lengths = _ops.convert_to_tensor(lengths, _dtypes.int64) + _inputs_flat = [tensor, element_shape, lengths] + _attrs = ("element_dtype", _attr_element_dtype, "shape_type", + _attr_shape_type) + _result = _execute.execute(b"TensorListSplit", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListSplit", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorListStack_element_dtype = TypeVar("TV_TensorListStack_element_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_list_stack(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListStack_element_dtype, num_elements:int=-1, name=None) -> Annotated[Any, TV_TensorListStack_element_dtype]: + r"""Stacks all tensors in the list. + + Requires that all tensors have the same shape. + + input_handle: the input list + tensor: the gathered result + num_elements: optional. If not -1, the number of elements in the list. + + Args: + input_handle: A `Tensor` of type `variant`. + element_shape: A `Tensor` of type `int32`. + element_dtype: A `tf.DType`. + num_elements: An optional `int`. Defaults to `-1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `element_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorListStack", name, input_handle, element_shape, + "element_dtype", element_dtype, "num_elements", num_elements) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_list_stack_eager_fallback( + input_handle, element_shape, element_dtype=element_dtype, + num_elements=num_elements, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + element_dtype = _execute.make_type(element_dtype, "element_dtype") + if num_elements is None: + num_elements = -1 + num_elements = _execute.make_int(num_elements, "num_elements") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorListStack", input_handle=input_handle, + element_shape=element_shape, + element_dtype=element_dtype, + num_elements=num_elements, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("element_dtype", _op._get_attr_type("element_dtype"), + "num_elements", _op._get_attr_int("num_elements")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorListStack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorListStack = tf_export("raw_ops.TensorListStack")(_ops.to_raw_op(tensor_list_stack)) + + +def tensor_list_stack_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], element_shape: Annotated[Any, _atypes.Int32], element_dtype: TV_TensorListStack_element_dtype, num_elements: int, name, ctx) -> Annotated[Any, TV_TensorListStack_element_dtype]: + element_dtype = _execute.make_type(element_dtype, "element_dtype") + if num_elements is None: + num_elements = -1 + num_elements = _execute.make_int(num_elements, "num_elements") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + element_shape = _ops.convert_to_tensor(element_shape, _dtypes.int32) + _inputs_flat = [input_handle, element_shape] + _attrs = ("element_dtype", element_dtype, "num_elements", num_elements) + _result = _execute.execute(b"TensorListStack", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorListStack", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_logging_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_logging_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..faf48784b86dada639fd386327af6eb72a727d74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_logging_ops.py @@ -0,0 +1,974 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def _assert(condition: Annotated[Any, _atypes.Bool], data, summarize:int=3, name=None): + r"""Asserts that the given condition is true. + + If `condition` evaluates to false, print the list of tensors in `data`. + `summarize` determines how many entries of the tensors to print. + + Args: + condition: A `Tensor` of type `bool`. The condition to evaluate. + data: A list of `Tensor` objects. + The tensors to print out when condition is false. + summarize: An optional `int`. Defaults to `3`. + Print this many entries of each tensor. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Assert", name, condition, data, "summarize", summarize) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _assert_eager_fallback( + condition, data, summarize=summarize, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Assert", condition=condition, data=data, summarize=summarize, + name=name) + return _op +Assert = tf_export("raw_ops.Assert")(_ops.to_raw_op(_assert)) + + +def _assert_eager_fallback(condition: Annotated[Any, _atypes.Bool], data, summarize: int, name, ctx): + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _attr_T, data = _execute.convert_to_mixed_eager_tensors(data, ctx) + condition = _ops.convert_to_tensor(condition, _dtypes.bool) + _inputs_flat = [condition] + list(data) + _attrs = ("T", _attr_T, "summarize", summarize) + _result = _execute.execute(b"Assert", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +def audio_summary(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: float, max_outputs:int=3, name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with audio. + + The summary has up to `max_outputs` summary values containing audio. The + audio is built from `tensor` which must be 3-D with shape `[batch_size, + frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are + assumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`. + + The `tag` argument is a scalar `Tensor` of type `string`. It is used to + build the `tag` of the summary values: + + * If `max_outputs` is 1, the summary value tag is '*tag*/audio'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. + + Args: + tag: A `Tensor` of type `string`. + Scalar. Used to build the `tag` attribute of the summary values. + tensor: A `Tensor` of type `float32`. 2-D of shape `[batch_size, frames]`. + sample_rate: A `float`. The sample rate of the signal in hertz. + max_outputs: An optional `int` that is `>= 1`. Defaults to `3`. + Max number of batch elements to generate audio for. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AudioSummary", name, tag, tensor, "sample_rate", sample_rate, + "max_outputs", max_outputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return audio_summary_eager_fallback( + tag, tensor, sample_rate=sample_rate, max_outputs=max_outputs, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + sample_rate = _execute.make_float(sample_rate, "sample_rate") + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AudioSummary", tag=tag, tensor=tensor, sample_rate=sample_rate, + max_outputs=max_outputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sample_rate", _op.get_attr("sample_rate"), "max_outputs", + _op._get_attr_int("max_outputs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AudioSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AudioSummary = tf_export("raw_ops.AudioSummary")(_ops.to_raw_op(audio_summary)) + + +def audio_summary_eager_fallback(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: float, max_outputs: int, name, ctx) -> Annotated[Any, _atypes.String]: + sample_rate = _execute.make_float(sample_rate, "sample_rate") + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + tag = _ops.convert_to_tensor(tag, _dtypes.string) + tensor = _ops.convert_to_tensor(tensor, _dtypes.float32) + _inputs_flat = [tag, tensor] + _attrs = ("sample_rate", sample_rate, "max_outputs", max_outputs) + _result = _execute.execute(b"AudioSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AudioSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def audio_summary_v2(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Float32], max_outputs:int=3, name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with audio. + + The summary has up to `max_outputs` summary values containing audio. The + audio is built from `tensor` which must be 3-D with shape `[batch_size, + frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are + assumed to be in the range of `[-1.0, 1.0]` with a sample rate of `sample_rate`. + + The `tag` argument is a scalar `Tensor` of type `string`. It is used to + build the `tag` of the summary values: + + * If `max_outputs` is 1, the summary value tag is '*tag*/audio'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. + + Args: + tag: A `Tensor` of type `string`. + Scalar. Used to build the `tag` attribute of the summary values. + tensor: A `Tensor` of type `float32`. 2-D of shape `[batch_size, frames]`. + sample_rate: A `Tensor` of type `float32`. + The sample rate of the signal in hertz. + max_outputs: An optional `int` that is `>= 1`. Defaults to `3`. + Max number of batch elements to generate audio for. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AudioSummaryV2", name, tag, tensor, sample_rate, "max_outputs", + max_outputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return audio_summary_v2_eager_fallback( + tag, tensor, sample_rate, max_outputs=max_outputs, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AudioSummaryV2", tag=tag, tensor=tensor, sample_rate=sample_rate, + max_outputs=max_outputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_outputs", _op._get_attr_int("max_outputs")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AudioSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AudioSummaryV2 = tf_export("raw_ops.AudioSummaryV2")(_ops.to_raw_op(audio_summary_v2)) + + +def audio_summary_v2_eager_fallback(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Float32], max_outputs: int, name, ctx) -> Annotated[Any, _atypes.String]: + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + tag = _ops.convert_to_tensor(tag, _dtypes.string) + tensor = _ops.convert_to_tensor(tensor, _dtypes.float32) + sample_rate = _ops.convert_to_tensor(sample_rate, _dtypes.float32) + _inputs_flat = [tag, tensor, sample_rate] + _attrs = ("max_outputs", max_outputs) + _result = _execute.execute(b"AudioSummaryV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AudioSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_HistogramSummary_T = TypeVar("TV_HistogramSummary_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def histogram_summary(tag: Annotated[Any, _atypes.String], values: Annotated[Any, TV_HistogramSummary_T], name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with a histogram. + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + + This op reports an `InvalidArgument` error if any value is not finite. + + Args: + tag: A `Tensor` of type `string`. + Scalar. Tag to use for the `Summary.Value`. + values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + Any shape. Values to use to build the histogram. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "HistogramSummary", name, tag, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return histogram_summary_eager_fallback( + tag, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "HistogramSummary", tag=tag, values=values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "HistogramSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +HistogramSummary = tf_export("raw_ops.HistogramSummary")(_ops.to_raw_op(histogram_summary)) + + +def histogram_summary_eager_fallback(tag: Annotated[Any, _atypes.String], values: Annotated[Any, TV_HistogramSummary_T], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ], _dtypes.float32) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [tag, values] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"HistogramSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "HistogramSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ImageSummary_T = TypeVar("TV_ImageSummary_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.UInt8) + +def image_summary(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_ImageSummary_T], max_images:int=3, bad_color=_execute.make_tensor("""dtype: DT_UINT8 tensor_shape { dim { size: 4 } } int_val: 255 int_val: 0 int_val: 0 int_val: 255 """, "bad_color"), name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with images. + + The summary has up to `max_images` summary values containing images. The + images are built from `tensor` which must be 4-D with shape `[batch_size, + height, width, channels]` and where `channels` can be: + + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + + The images have the same number of channels as the input tensor. For float + input, the values are normalized one image at a time to fit in the range + `[0, 255]`. `uint8` values are unchanged. The op uses two different + normalization algorithms: + + * If the input values are all positive, they are rescaled so the largest one + is 255. + + * If any input value is negative, the values are shifted so input value 0.0 + is at 127. They are then rescaled so that either the smallest value is 0, + or the largest one is 255. + + The `tag` argument is a scalar `Tensor` of type `string`. It is used to + build the `tag` of the summary values: + + * If `max_images` is 1, the summary value tag is '*tag*/image'. + * If `max_images` is greater than 1, the summary value tags are + generated sequentially as '*tag*/image/0', '*tag*/image/1', etc. + + The `bad_color` argument is the color to use in the generated images for + non-finite input values. It is a `uint8` 1-D tensor of length `channels`. + Each element must be in the range `[0, 255]` (It represents the value of a + pixel in the output image). Non-finite values in the input tensor are + replaced by this tensor in the output image. The default value is the color + red. + + Args: + tag: A `Tensor` of type `string`. + Scalar. Used to build the `tag` attribute of the summary values. + tensor: A `Tensor`. Must be one of the following types: `uint8`, `float32`, `half`, `float64`. + 4-D of shape `[batch_size, height, width, channels]` where + `channels` is 1, 3, or 4. + max_images: An optional `int` that is `>= 1`. Defaults to `3`. + Max number of batch elements to generate images for. + bad_color: An optional `tf.TensorProto`. Defaults to `dtype: DT_UINT8 tensor_shape { dim { size: 4 } } int_val: 255 int_val: 0 int_val: 0 int_val: 255`. + Color to use for pixels with non-finite values. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ImageSummary", name, tag, tensor, "max_images", max_images, + "bad_color", bad_color) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return image_summary_eager_fallback( + tag, tensor, max_images=max_images, bad_color=bad_color, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if max_images is None: + max_images = 3 + max_images = _execute.make_int(max_images, "max_images") + if bad_color is None: + bad_color = _execute.make_tensor("""dtype: DT_UINT8 tensor_shape { dim { size: 4 } } int_val: 255 int_val: 0 int_val: 0 int_val: 255 """, "bad_color") + bad_color = _execute.make_tensor(bad_color, "bad_color") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ImageSummary", tag=tag, tensor=tensor, max_images=max_images, + bad_color=bad_color, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("max_images", _op._get_attr_int("max_images"), "T", + _op._get_attr_type("T"), "bad_color", _op.get_attr("bad_color")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ImageSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ImageSummary = tf_export("raw_ops.ImageSummary")(_ops.to_raw_op(image_summary)) + + +def image_summary_eager_fallback(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_ImageSummary_T], max_images: int, bad_color, name, ctx) -> Annotated[Any, _atypes.String]: + if max_images is None: + max_images = 3 + max_images = _execute.make_int(max_images, "max_images") + if bad_color is None: + bad_color = _execute.make_tensor("""dtype: DT_UINT8 tensor_shape { dim { size: 4 } } int_val: 255 int_val: 0 int_val: 0 int_val: 255 """, "bad_color") + bad_color = _execute.make_tensor(bad_color, "bad_color") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.uint8, _dtypes.float32, _dtypes.half, _dtypes.float64, ], _dtypes.float32) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [tag, tensor] + _attrs = ("max_images", max_images, "T", _attr_T, "bad_color", bad_color) + _result = _execute.execute(b"ImageSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ImageSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def merge_summary(inputs: Annotated[List[Any], _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Merges summaries. + + This op creates a + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + protocol buffer that contains the union of all the values in the input + summaries. + + When the Op is run, it reports an `InvalidArgument` error if multiple values + in the summaries to merge use the same tag. + + Args: + inputs: A list of at least 1 `Tensor` objects with type `string`. + Can be of any shape. Each must contain serialized `Summary` protocol + buffers. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MergeSummary", name, inputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return merge_summary_eager_fallback( + inputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'merge_summary' Op, not %r." % inputs) + _attr_N = len(inputs) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MergeSummary", inputs=inputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MergeSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MergeSummary = tf_export("raw_ops.MergeSummary")(_ops.to_raw_op(merge_summary)) + + +def merge_summary_eager_fallback(inputs: Annotated[List[Any], _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'merge_summary' Op, not %r." % inputs) + _attr_N = len(inputs) + inputs = _ops.convert_n_to_tensor(inputs, _dtypes.string) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N) + _result = _execute.execute(b"MergeSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MergeSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Print_T = TypeVar("TV_Print_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def _print(input: Annotated[Any, TV_Print_T], data, message:str="", first_n:int=-1, summarize:int=3, name=None) -> Annotated[Any, TV_Print_T]: + r"""Prints a list of tensors. + + Passes `input` through to `output` and prints `data` when evaluating. + + Args: + input: A `Tensor`. The tensor passed to `output` + data: A list of `Tensor` objects. + A list of tensors to print out when op is evaluated. + message: An optional `string`. Defaults to `""`. + A string, prefix of the error message. + first_n: An optional `int`. Defaults to `-1`. + Only log `first_n` number of times. -1 disables logging. + summarize: An optional `int`. Defaults to `3`. + Only print this many entries of each tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Print", name, input, data, "message", message, "first_n", + first_n, "summarize", summarize) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _print_eager_fallback( + input, data, message=message, first_n=first_n, summarize=summarize, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if message is None: + message = "" + message = _execute.make_str(message, "message") + if first_n is None: + first_n = -1 + first_n = _execute.make_int(first_n, "first_n") + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Print", input=input, data=data, message=message, first_n=first_n, + summarize=summarize, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "U", _op.get_attr("U"), "message", + _op.get_attr("message"), "first_n", + _op._get_attr_int("first_n"), "summarize", + _op._get_attr_int("summarize")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Print", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Print = tf_export("raw_ops.Print")(_ops.to_raw_op(_print)) + + +def _print_eager_fallback(input: Annotated[Any, TV_Print_T], data, message: str, first_n: int, summarize: int, name, ctx) -> Annotated[Any, TV_Print_T]: + if message is None: + message = "" + message = _execute.make_str(message, "message") + if first_n is None: + first_n = -1 + first_n = _execute.make_int(first_n, "first_n") + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_U, data = _execute.convert_to_mixed_eager_tensors(data, ctx) + _inputs_flat = [input] + list(data) + _attrs = ("T", _attr_T, "U", _attr_U, "message", message, "first_n", + first_n, "summarize", summarize) + _result = _execute.execute(b"Print", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Print", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def print_v2(input: Annotated[Any, _atypes.String], output_stream:str="stderr", end:str="\n", name=None): + r"""Prints a string scalar. + + Prints a string scalar to the desired output_stream. + + Args: + input: A `Tensor` of type `string`. The string scalar to print. + output_stream: An optional `string`. Defaults to `"stderr"`. + A string specifying the output stream or logging level to print to. + end: An optional `string`. Defaults to `"\n"`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PrintV2", name, input, "output_stream", output_stream, "end", + end) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return print_v2_eager_fallback( + input, output_stream=output_stream, end=end, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_stream is None: + output_stream = "stderr" + output_stream = _execute.make_str(output_stream, "output_stream") + if end is None: + end = "\n" + end = _execute.make_str(end, "end") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PrintV2", input=input, output_stream=output_stream, end=end, + name=name) + return _op +PrintV2 = tf_export("raw_ops.PrintV2")(_ops.to_raw_op(print_v2)) + + +def print_v2_eager_fallback(input: Annotated[Any, _atypes.String], output_stream: str, end: str, name, ctx): + if output_stream is None: + output_stream = "stderr" + output_stream = _execute.make_str(output_stream, "output_stream") + if end is None: + end = "\n" + end = _execute.make_str(end, "end") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("output_stream", output_stream, "end", end) + _result = _execute.execute(b"PrintV2", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +TV_ScalarSummary_T = TypeVar("TV_ScalarSummary_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def scalar_summary(tags: Annotated[Any, _atypes.String], values: Annotated[Any, TV_ScalarSummary_T], name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with scalar values. + + The input `tags` and `values` must have the same shape. The generated summary + has a summary value for each tag-value pair in `tags` and `values`. + + Args: + tags: A `Tensor` of type `string`. Tags for the summary. + values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + Same shape as `tags. Values for the summary. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ScalarSummary", name, tags, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return scalar_summary_eager_fallback( + tags, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScalarSummary", tags=tags, values=values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScalarSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScalarSummary = tf_export("raw_ops.ScalarSummary")(_ops.to_raw_op(scalar_summary)) + + +def scalar_summary_eager_fallback(tags: Annotated[Any, _atypes.String], values: Annotated[Any, TV_ScalarSummary_T], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + tags = _ops.convert_to_tensor(tags, _dtypes.string) + _inputs_flat = [tags, values] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ScalarSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ScalarSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorSummary_T = TypeVar("TV_TensorSummary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_summary(tensor: Annotated[Any, TV_TensorSummary_T], description:str="", labels=[], display_name:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with a tensor. + + This op is being phased out in favor of TensorSummaryV2, which lets callers pass + a tag as well as a serialized SummaryMetadata proto string that contains + plugin-specific data. We will keep this op to maintain backwards compatibility. + + Args: + tensor: A `Tensor`. A tensor to serialize. + description: An optional `string`. Defaults to `""`. + A json-encoded SummaryDescription proto. + labels: An optional list of `strings`. Defaults to `[]`. + An unused list of strings. + display_name: An optional `string`. Defaults to `""`. An unused string. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorSummary", name, tensor, "description", description, + "labels", labels, "display_name", display_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_summary_eager_fallback( + tensor, description=description, labels=labels, + display_name=display_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if description is None: + description = "" + description = _execute.make_str(description, "description") + if labels is None: + labels = [] + if not isinstance(labels, (list, tuple)): + raise TypeError( + "Expected list for 'labels' argument to " + "'tensor_summary' Op, not %r." % labels) + labels = [_execute.make_str(_s, "labels") for _s in labels] + if display_name is None: + display_name = "" + display_name = _execute.make_str(display_name, "display_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorSummary", tensor=tensor, description=description, + labels=labels, display_name=display_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "description", + _op.get_attr("description"), "labels", _op.get_attr("labels"), + "display_name", _op.get_attr("display_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorSummary = tf_export("raw_ops.TensorSummary")(_ops.to_raw_op(tensor_summary)) + + +def tensor_summary_eager_fallback(tensor: Annotated[Any, TV_TensorSummary_T], description: str, labels, display_name: str, name, ctx) -> Annotated[Any, _atypes.String]: + if description is None: + description = "" + description = _execute.make_str(description, "description") + if labels is None: + labels = [] + if not isinstance(labels, (list, tuple)): + raise TypeError( + "Expected list for 'labels' argument to " + "'tensor_summary' Op, not %r." % labels) + labels = [_execute.make_str(_s, "labels") for _s in labels] + if display_name is None: + display_name = "" + display_name = _execute.make_str(display_name, "display_name") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _inputs_flat = [tensor] + _attrs = ("T", _attr_T, "description", description, "labels", labels, + "display_name", display_name) + _result = _execute.execute(b"TensorSummary", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorSummary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorSummaryV2_T = TypeVar("TV_TensorSummaryV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_summary_v2(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_TensorSummaryV2_T], serialized_summary_metadata: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Outputs a `Summary` protocol buffer with a tensor and per-plugin data. + + Args: + tag: A `Tensor` of type `string`. + A string attached to this summary. Used for organization in TensorBoard. + tensor: A `Tensor`. A tensor to serialize. + serialized_summary_metadata: A `Tensor` of type `string`. + A serialized SummaryMetadata proto. Contains plugin + data. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorSummaryV2", name, tag, tensor, + serialized_summary_metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_summary_v2_eager_fallback( + tag, tensor, serialized_summary_metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorSummaryV2", tag=tag, tensor=tensor, + serialized_summary_metadata=serialized_summary_metadata, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorSummaryV2 = tf_export("raw_ops.TensorSummaryV2")(_ops.to_raw_op(tensor_summary_v2)) + + +def tensor_summary_v2_eager_fallback(tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_TensorSummaryV2_T], serialized_summary_metadata: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + serialized_summary_metadata = _ops.convert_to_tensor(serialized_summary_metadata, _dtypes.string) + _inputs_flat = [tag, tensor, serialized_summary_metadata] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TensorSummaryV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorSummaryV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('timestamp') +def timestamp(name=None) -> Annotated[Any, _atypes.Float64]: + r"""Provides the time since epoch in seconds. + + Returns the timestamp as a `float64` for seconds since the Unix epoch. + + Common usages include: + * Logging + * Providing a random number seed + * Debugging graph execution + * Generating timing information, mainly through comparison of timestamps + + Note: In graph mode, the timestamp is computed when the op is executed, + not when it is added to the graph. In eager mode, the timestamp is computed + when the op is eagerly executed. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Timestamp", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_timestamp( + (name,), None) + if _result is not NotImplemented: + return _result + return timestamp_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + timestamp, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_timestamp( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Timestamp", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + timestamp, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Timestamp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Timestamp = tf_export("raw_ops.Timestamp")(_ops.to_raw_op(timestamp)) +_dispatcher_for_timestamp = timestamp._tf_type_based_dispatcher.Dispatch + + +def timestamp_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Float64]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"Timestamp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Timestamp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_lookup_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_lookup_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..28ed1ec13ab38f818703f6a725d5f6ca674e333e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_lookup_ops.py @@ -0,0 +1,1947 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AnonymousHashTable_key_dtype = TypeVar("TV_AnonymousHashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_AnonymousHashTable_value_dtype = TypeVar("TV_AnonymousHashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def anonymous_hash_table(key_dtype: TV_AnonymousHashTable_key_dtype, value_dtype: TV_AnonymousHashTable_value_dtype, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a uninitialized anonymous hash table. + + This op creates a new anonymous hash table (as a resource) everytime + it is executed, with the specified dtype of its keys and values, + returning the resource handle. Before using the table you will have + to initialize it. After initialization the table will be + immutable. The table is anonymous in the sense that it can only be + accessed by the returned resource handle (e.g. it cannot be looked up + by a name in a resource manager). The table will be automatically + deleted when all resource handles pointing to it are gone. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousHashTable", name, "key_dtype", key_dtype, + "value_dtype", value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_hash_table_eager_fallback( + key_dtype=key_dtype, value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousHashTable", key_dtype=key_dtype, value_dtype=value_dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousHashTable = tf_export("raw_ops.AnonymousHashTable")(_ops.to_raw_op(anonymous_hash_table)) + + +def anonymous_hash_table_eager_fallback(key_dtype: TV_AnonymousHashTable_key_dtype, value_dtype: TV_AnonymousHashTable_value_dtype, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _inputs_flat = [] + _attrs = ("key_dtype", key_dtype, "value_dtype", value_dtype) + _result = _execute.execute(b"AnonymousHashTable", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AnonymousMutableDenseHashTable_key_dtype = TypeVar("TV_AnonymousMutableDenseHashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_AnonymousMutableDenseHashTable_value_dtype = TypeVar("TV_AnonymousMutableDenseHashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def anonymous_mutable_dense_hash_table(empty_key: Annotated[Any, TV_AnonymousMutableDenseHashTable_key_dtype], deleted_key: Annotated[Any, TV_AnonymousMutableDenseHashTable_key_dtype], value_dtype: TV_AnonymousMutableDenseHashTable_value_dtype, value_shape=[], initial_num_buckets:int=131072, max_load_factor:float=0.8, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty anonymous mutable hash table that uses tensors as the backing store. + + This op creates a new anonymous mutable hash table (as a resource) everytime + it is executed, with the specified dtype of its keys and values, + returning the resource handle. Each value must be a scalar. + Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + It uses "open addressing" with quadratic reprobing to resolve + collisions. + + The table is anonymous in the sense that it can only be + accessed by the returned resource handle (e.g. it cannot be looked up + by a name in a resource manager). The table will be automatically + deleted when all resource handles pointing to it are gone. + + Args: + empty_key: A `Tensor`. + The key used to represent empty key buckets internally. Must not + be used in insert or lookup operations. + deleted_key: A `Tensor`. Must have the same type as `empty_key`. + value_dtype: A `tf.DType`. Type of the table values. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + The shape of each value. + initial_num_buckets: An optional `int`. Defaults to `131072`. + The initial number of hash table buckets. Must be a power + to 2. + max_load_factor: An optional `float`. Defaults to `0.8`. + The maximum ratio between number of entries and number of + buckets before growing the table. Must be between 0 and 1. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMutableDenseHashTable", name, empty_key, deleted_key, + "value_dtype", value_dtype, "value_shape", value_shape, + "initial_num_buckets", initial_num_buckets, "max_load_factor", + max_load_factor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_mutable_dense_hash_table_eager_fallback( + empty_key, deleted_key, value_dtype=value_dtype, + value_shape=value_shape, initial_num_buckets=initial_num_buckets, + max_load_factor=max_load_factor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + if initial_num_buckets is None: + initial_num_buckets = 131072 + initial_num_buckets = _execute.make_int(initial_num_buckets, "initial_num_buckets") + if max_load_factor is None: + max_load_factor = 0.8 + max_load_factor = _execute.make_float(max_load_factor, "max_load_factor") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMutableDenseHashTable", empty_key=empty_key, + deleted_key=deleted_key, + value_dtype=value_dtype, + value_shape=value_shape, + initial_num_buckets=initial_num_buckets, + max_load_factor=max_load_factor, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape"), "initial_num_buckets", + _op._get_attr_int("initial_num_buckets"), "max_load_factor", + _op.get_attr("max_load_factor")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMutableDenseHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousMutableDenseHashTable = tf_export("raw_ops.AnonymousMutableDenseHashTable")(_ops.to_raw_op(anonymous_mutable_dense_hash_table)) + + +def anonymous_mutable_dense_hash_table_eager_fallback(empty_key: Annotated[Any, TV_AnonymousMutableDenseHashTable_key_dtype], deleted_key: Annotated[Any, TV_AnonymousMutableDenseHashTable_key_dtype], value_dtype: TV_AnonymousMutableDenseHashTable_value_dtype, value_shape, initial_num_buckets: int, max_load_factor: float, name, ctx) -> Annotated[Any, _atypes.Resource]: + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + if initial_num_buckets is None: + initial_num_buckets = 131072 + initial_num_buckets = _execute.make_int(initial_num_buckets, "initial_num_buckets") + if max_load_factor is None: + max_load_factor = 0.8 + max_load_factor = _execute.make_float(max_load_factor, "max_load_factor") + _attr_key_dtype, _inputs_key_dtype = _execute.args_to_matching_eager([empty_key, deleted_key], ctx, []) + (empty_key, deleted_key) = _inputs_key_dtype + _inputs_flat = [empty_key, deleted_key] + _attrs = ("key_dtype", _attr_key_dtype, "value_dtype", value_dtype, + "value_shape", value_shape, "initial_num_buckets", initial_num_buckets, + "max_load_factor", max_load_factor) + _result = _execute.execute(b"AnonymousMutableDenseHashTable", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMutableDenseHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AnonymousMutableHashTable_key_dtype = TypeVar("TV_AnonymousMutableHashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_AnonymousMutableHashTable_value_dtype = TypeVar("TV_AnonymousMutableHashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def anonymous_mutable_hash_table(key_dtype: TV_AnonymousMutableHashTable_key_dtype, value_dtype: TV_AnonymousMutableHashTable_value_dtype, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty anonymous mutable hash table. + + This op creates a new anonymous mutable hash table (as a resource) everytime + it is executed, with the specified dtype of its keys and values, + returning the resource handle. Each value must be a scalar. + Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + The table is anonymous in the sense that it can only be + accessed by the returned resource handle (e.g. it cannot be looked up + by a name in a resource manager). The table will be automatically + deleted when all resource handles pointing to it are gone. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMutableHashTable", name, "key_dtype", key_dtype, + "value_dtype", value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_mutable_hash_table_eager_fallback( + key_dtype=key_dtype, value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMutableHashTable", key_dtype=key_dtype, + value_dtype=value_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMutableHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousMutableHashTable = tf_export("raw_ops.AnonymousMutableHashTable")(_ops.to_raw_op(anonymous_mutable_hash_table)) + + +def anonymous_mutable_hash_table_eager_fallback(key_dtype: TV_AnonymousMutableHashTable_key_dtype, value_dtype: TV_AnonymousMutableHashTable_value_dtype, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _inputs_flat = [] + _attrs = ("key_dtype", key_dtype, "value_dtype", value_dtype) + _result = _execute.execute(b"AnonymousMutableHashTable", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMutableHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AnonymousMutableHashTableOfTensors_key_dtype = TypeVar("TV_AnonymousMutableHashTableOfTensors_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_AnonymousMutableHashTableOfTensors_value_dtype = TypeVar("TV_AnonymousMutableHashTableOfTensors_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def anonymous_mutable_hash_table_of_tensors(key_dtype: TV_AnonymousMutableHashTableOfTensors_key_dtype, value_dtype: TV_AnonymousMutableHashTableOfTensors_value_dtype, value_shape=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty anonymous mutable hash table of vector values. + + This op creates a new anonymous mutable hash table (as a resource) everytime + it is executed, with the specified dtype of its keys and values, + returning the resource handle. Each value must be a vector. + Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + The table is anonymous in the sense that it can only be + accessed by the returned resource handle (e.g. it cannot be looked up + by a name in a resource manager). The table will be automatically + deleted when all resource handles pointing to it are gone. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AnonymousMutableHashTableOfTensors", name, "key_dtype", + key_dtype, "value_dtype", value_dtype, "value_shape", value_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return anonymous_mutable_hash_table_of_tensors_eager_fallback( + key_dtype=key_dtype, value_dtype=value_dtype, + value_shape=value_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AnonymousMutableHashTableOfTensors", key_dtype=key_dtype, + value_dtype=value_dtype, + value_shape=value_shape, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AnonymousMutableHashTableOfTensors", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AnonymousMutableHashTableOfTensors = tf_export("raw_ops.AnonymousMutableHashTableOfTensors")(_ops.to_raw_op(anonymous_mutable_hash_table_of_tensors)) + + +def anonymous_mutable_hash_table_of_tensors_eager_fallback(key_dtype: TV_AnonymousMutableHashTableOfTensors_key_dtype, value_dtype: TV_AnonymousMutableHashTableOfTensors_value_dtype, value_shape, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + _inputs_flat = [] + _attrs = ("key_dtype", key_dtype, "value_dtype", value_dtype, "value_shape", + value_shape) + _result = _execute.execute(b"AnonymousMutableHashTableOfTensors", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AnonymousMutableHashTableOfTensors", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_HashTable_key_dtype = TypeVar("TV_HashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_HashTable_value_dtype = TypeVar("TV_HashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def hash_table(key_dtype: TV_HashTable_key_dtype, value_dtype: TV_HashTable_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Creates a non-initialized hash table. + + This op creates a hash table, specifying the type of its keys and values. + Before using the table you will have to initialize it. After initialization the + table will be immutable. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + If true and shared_name is empty, the table is shared + using the node name. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "HashTable", key_dtype=key_dtype, value_dtype=value_dtype, + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "HashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +HashTable = tf_export("raw_ops.HashTable")(_ops.to_raw_op(hash_table)) + + +def hash_table_eager_fallback(key_dtype: TV_HashTable_key_dtype, value_dtype: TV_HashTable_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_HashTableV2_key_dtype = TypeVar("TV_HashTableV2_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_HashTableV2_value_dtype = TypeVar("TV_HashTableV2_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def hash_table_v2(key_dtype: TV_HashTableV2_key_dtype, value_dtype: TV_HashTableV2_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a non-initialized hash table. + + This op creates a hash table, specifying the type of its keys and values. + Before using the table you will have to initialize it. After initialization the + table will be immutable. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + If true and shared_name is empty, the table is shared + using the node name. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "HashTableV2", name, "container", container, "shared_name", + shared_name, "use_node_name_sharing", use_node_name_sharing, + "key_dtype", key_dtype, "value_dtype", value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return hash_table_v2_eager_fallback( + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, key_dtype=key_dtype, + value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "HashTableV2", key_dtype=key_dtype, value_dtype=value_dtype, + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "HashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +HashTableV2 = tf_export("raw_ops.HashTableV2")(_ops.to_raw_op(hash_table_v2)) + + +def hash_table_v2_eager_fallback(key_dtype: TV_HashTableV2_key_dtype, value_dtype: TV_HashTableV2_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name, + "use_node_name_sharing", use_node_name_sharing, "key_dtype", key_dtype, + "value_dtype", value_dtype) + _result = _execute.execute(b"HashTableV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "HashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InitializeTable_Tkey = TypeVar("TV_InitializeTable_Tkey", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_InitializeTable_Tval = TypeVar("TV_InitializeTable_Tval", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def initialize_table(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_InitializeTable_Tkey], values: Annotated[Any, TV_InitializeTable_Tval], name=None): + r"""Table initializer that takes two tensors for keys and values respectively. + + Args: + table_handle: A `Tensor` of type mutable `string`. + Handle to a table which will be initialized. + keys: A `Tensor`. Keys of type Tkey. + values: A `Tensor`. Values of type Tval. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("initialize_table op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InitializeTable", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +InitializeTable = tf_export("raw_ops.InitializeTable")(_ops.to_raw_op(initialize_table)) + + +def initialize_table_eager_fallback(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_InitializeTable_Tkey], values: Annotated[Any, TV_InitializeTable_Tval], name, ctx): + raise RuntimeError("initialize_table op does not support eager execution. Arg 'table_handle' is a ref.") + +def initialize_table_from_text_file(table_handle: Annotated[Any, _atypes.String], filename: Annotated[Any, _atypes.String], key_index: int, value_index: int, vocab_size:int=-1, delimiter:str="\t", offset:int=0, name=None): + r"""Initializes a table from a text file. + + It inserts one key-value pair into the table for each line of the file. + The key and value is extracted from the whole line content, elements from the + split line based on `delimiter` or the line number (starting from zero). + Where to extract the key and value from a line is specified by `key_index` and + `value_index`. + + - A value of -1 means use the line number(starting from zero), expects `int64`. + - A value of -2 means use the whole line content, expects `string`. + - A value >= 0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Args: + table_handle: A `Tensor` of type mutable `string`. + Handle to a table which will be initialized. + filename: A `Tensor` of type `string`. Filename of a vocabulary text file. + key_index: An `int` that is `>= -2`. + Column index in a line to get the table `key` values from. + value_index: An `int` that is `>= -2`. + Column index that represents information of a line to get the table + `value` values from. + vocab_size: An optional `int` that is `>= -1`. Defaults to `-1`. + Number of elements of the file, use -1 if unknown. + delimiter: An optional `string`. Defaults to `"\t"`. + Delimiter to separate fields in a line. + offset: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("initialize_table_from_text_file op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + key_index = _execute.make_int(key_index, "key_index") + value_index = _execute.make_int(value_index, "value_index") + if vocab_size is None: + vocab_size = -1 + vocab_size = _execute.make_int(vocab_size, "vocab_size") + if delimiter is None: + delimiter = "\t" + delimiter = _execute.make_str(delimiter, "delimiter") + if offset is None: + offset = 0 + offset = _execute.make_int(offset, "offset") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InitializeTableFromTextFile", table_handle=table_handle, + filename=filename, key_index=key_index, + value_index=value_index, + vocab_size=vocab_size, + delimiter=delimiter, offset=offset, + name=name) + return _op +InitializeTableFromTextFile = tf_export("raw_ops.InitializeTableFromTextFile")(_ops.to_raw_op(initialize_table_from_text_file)) + + +def initialize_table_from_text_file_eager_fallback(table_handle: Annotated[Any, _atypes.String], filename: Annotated[Any, _atypes.String], key_index: int, value_index: int, vocab_size: int, delimiter: str, offset: int, name, ctx): + raise RuntimeError("initialize_table_from_text_file op does not support eager execution. Arg 'table_handle' is a ref.") + +def initialize_table_from_text_file_v2(table_handle: Annotated[Any, _atypes.Resource], filename: Annotated[Any, _atypes.String], key_index: int, value_index: int, vocab_size:int=-1, delimiter:str="\t", offset:int=0, name=None): + r"""Initializes a table from a text file. + + It inserts one key-value pair into the table for each line of the file. + The key and value is extracted from the whole line content, elements from the + split line based on `delimiter` or the line number (starting from zero). + Where to extract the key and value from a line is specified by `key_index` and + `value_index`. + + - A value of -1 means use the line number(starting from zero), expects `int64`. + - A value of -2 means use the whole line content, expects `string`. + - A value >= 0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Args: + table_handle: A `Tensor` of type `resource`. + Handle to a table which will be initialized. + filename: A `Tensor` of type `string`. Filename of a vocabulary text file. + key_index: An `int` that is `>= -2`. + Column index in a line to get the table `key` values from. + value_index: An `int` that is `>= -2`. + Column index that represents information of a line to get the table + `value` values from. + vocab_size: An optional `int` that is `>= -1`. Defaults to `-1`. + Number of elements of the file, use -1 if unknown. + delimiter: An optional `string`. Defaults to `"\t"`. + Delimiter to separate fields in a line. + offset: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InitializeTableFromTextFileV2", name, table_handle, filename, + "key_index", key_index, "value_index", value_index, "vocab_size", + vocab_size, "delimiter", delimiter, "offset", offset) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return initialize_table_from_text_file_v2_eager_fallback( + table_handle, filename, key_index=key_index, + value_index=value_index, vocab_size=vocab_size, delimiter=delimiter, + offset=offset, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_index = _execute.make_int(key_index, "key_index") + value_index = _execute.make_int(value_index, "value_index") + if vocab_size is None: + vocab_size = -1 + vocab_size = _execute.make_int(vocab_size, "vocab_size") + if delimiter is None: + delimiter = "\t" + delimiter = _execute.make_str(delimiter, "delimiter") + if offset is None: + offset = 0 + offset = _execute.make_int(offset, "offset") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InitializeTableFromTextFileV2", table_handle=table_handle, + filename=filename, + key_index=key_index, + value_index=value_index, + vocab_size=vocab_size, + delimiter=delimiter, offset=offset, + name=name) + return _op +InitializeTableFromTextFileV2 = tf_export("raw_ops.InitializeTableFromTextFileV2")(_ops.to_raw_op(initialize_table_from_text_file_v2)) + + +def initialize_table_from_text_file_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], filename: Annotated[Any, _atypes.String], key_index: int, value_index: int, vocab_size: int, delimiter: str, offset: int, name, ctx): + key_index = _execute.make_int(key_index, "key_index") + value_index = _execute.make_int(value_index, "value_index") + if vocab_size is None: + vocab_size = -1 + vocab_size = _execute.make_int(vocab_size, "vocab_size") + if delimiter is None: + delimiter = "\t" + delimiter = _execute.make_str(delimiter, "delimiter") + if offset is None: + offset = 0 + offset = _execute.make_int(offset, "offset") + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + filename = _ops.convert_to_tensor(filename, _dtypes.string) + _inputs_flat = [table_handle, filename] + _attrs = ("key_index", key_index, "value_index", value_index, "vocab_size", + vocab_size, "delimiter", delimiter, "offset", offset) + _result = _execute.execute(b"InitializeTableFromTextFileV2", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_InitializeTableV2_Tkey = TypeVar("TV_InitializeTableV2_Tkey", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_InitializeTableV2_Tval = TypeVar("TV_InitializeTableV2_Tval", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def initialize_table_v2(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_InitializeTableV2_Tkey], values: Annotated[Any, TV_InitializeTableV2_Tval], name=None): + r"""Table initializer that takes two tensors for keys and values respectively. + + Args: + table_handle: A `Tensor` of type `resource`. + Handle to a table which will be initialized. + keys: A `Tensor`. Keys of type Tkey. + values: A `Tensor`. Values of type Tval. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InitializeTableV2", name, table_handle, keys, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return initialize_table_v2_eager_fallback( + table_handle, keys, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InitializeTableV2", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +InitializeTableV2 = tf_export("raw_ops.InitializeTableV2")(_ops.to_raw_op(initialize_table_v2)) + + +def initialize_table_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_InitializeTableV2_Tkey], values: Annotated[Any, TV_InitializeTableV2_Tval], name, ctx): + _attr_Tkey, (keys,) = _execute.args_to_matching_eager([keys], ctx, []) + _attr_Tval, (values,) = _execute.args_to_matching_eager([values], ctx, []) + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle, keys, values] + _attrs = ("Tkey", _attr_Tkey, "Tval", _attr_Tval) + _result = _execute.execute(b"InitializeTableV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + +_LookupTableExportOutput = collections.namedtuple( + "LookupTableExport", + ["keys", "values"]) + + +TV_LookupTableExport_Tkeys = TypeVar("TV_LookupTableExport_Tkeys", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableExport_Tvalues = TypeVar("TV_LookupTableExport_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_export(table_handle: Annotated[Any, _atypes.String], Tkeys: TV_LookupTableExport_Tkeys, Tvalues: TV_LookupTableExport_Tvalues, name=None): + r"""Outputs all keys and values in the table. + + Args: + table_handle: A `Tensor` of type mutable `string`. Handle to the table. + Tkeys: A `tf.DType`. + Tvalues: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (keys, values). + + keys: A `Tensor` of type `Tkeys`. + values: A `Tensor` of type `Tvalues`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lookup_table_export op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + Tkeys = _execute.make_type(Tkeys, "Tkeys") + Tvalues = _execute.make_type(Tvalues, "Tvalues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableExport", table_handle=table_handle, Tkeys=Tkeys, + Tvalues=Tvalues, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tkeys", _op._get_attr_type("Tkeys"), "Tvalues", + _op._get_attr_type("Tvalues")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableExport", _inputs_flat, _attrs, _result) + _result = _LookupTableExportOutput._make(_result) + return _result + +LookupTableExport = tf_export("raw_ops.LookupTableExport")(_ops.to_raw_op(lookup_table_export)) + + +def lookup_table_export_eager_fallback(table_handle: Annotated[Any, _atypes.String], Tkeys: TV_LookupTableExport_Tkeys, Tvalues: TV_LookupTableExport_Tvalues, name, ctx): + raise RuntimeError("lookup_table_export op does not support eager execution. Arg 'table_handle' is a ref.") +_LookupTableExportV2Output = collections.namedtuple( + "LookupTableExportV2", + ["keys", "values"]) + + +TV_LookupTableExportV2_Tkeys = TypeVar("TV_LookupTableExportV2_Tkeys", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableExportV2_Tvalues = TypeVar("TV_LookupTableExportV2_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_export_v2(table_handle: Annotated[Any, _atypes.Resource], Tkeys: TV_LookupTableExportV2_Tkeys, Tvalues: TV_LookupTableExportV2_Tvalues, name=None): + r"""Outputs all keys and values in the table. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + Tkeys: A `tf.DType`. + Tvalues: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (keys, values). + + keys: A `Tensor` of type `Tkeys`. + values: A `Tensor` of type `Tvalues`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableExportV2", name, table_handle, "Tkeys", Tkeys, + "Tvalues", Tvalues) + _result = _LookupTableExportV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_export_v2_eager_fallback( + table_handle, Tkeys=Tkeys, Tvalues=Tvalues, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tkeys = _execute.make_type(Tkeys, "Tkeys") + Tvalues = _execute.make_type(Tvalues, "Tvalues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableExportV2", table_handle=table_handle, Tkeys=Tkeys, + Tvalues=Tvalues, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tkeys", _op._get_attr_type("Tkeys"), "Tvalues", + _op._get_attr_type("Tvalues")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableExportV2", _inputs_flat, _attrs, _result) + _result = _LookupTableExportV2Output._make(_result) + return _result + +LookupTableExportV2 = tf_export("raw_ops.LookupTableExportV2")(_ops.to_raw_op(lookup_table_export_v2)) + + +def lookup_table_export_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], Tkeys: TV_LookupTableExportV2_Tkeys, Tvalues: TV_LookupTableExportV2_Tvalues, name, ctx): + Tkeys = _execute.make_type(Tkeys, "Tkeys") + Tvalues = _execute.make_type(Tvalues, "Tvalues") + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle] + _attrs = ("Tkeys", Tkeys, "Tvalues", Tvalues) + _result = _execute.execute(b"LookupTableExportV2", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LookupTableExportV2", _inputs_flat, _attrs, _result) + _result = _LookupTableExportV2Output._make(_result) + return _result + + +TV_LookupTableFind_Tin = TypeVar("TV_LookupTableFind_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableFind_Tout = TypeVar("TV_LookupTableFind_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_find(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableFind_Tin], default_value: Annotated[Any, TV_LookupTableFind_Tout], name=None) -> Annotated[Any, TV_LookupTableFind_Tout]: + r"""Looks up keys in a table, outputs the corresponding values. + + The tensor `keys` must of the same type as the keys of the table. + The output `values` is of the type of the table values. + + The scalar `default_value` is the value output for keys not present in the + table. It must also be of the same type as the table values. + + Args: + table_handle: A `Tensor` of type mutable `string`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + default_value: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `default_value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lookup_table_find op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableFind", table_handle=table_handle, keys=keys, + default_value=default_value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableFind", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LookupTableFind = tf_export("raw_ops.LookupTableFind")(_ops.to_raw_op(lookup_table_find)) + + +def lookup_table_find_eager_fallback(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableFind_Tin], default_value: Annotated[Any, TV_LookupTableFind_Tout], name, ctx) -> Annotated[Any, TV_LookupTableFind_Tout]: + raise RuntimeError("lookup_table_find op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_LookupTableFindV2_Tin = TypeVar("TV_LookupTableFindV2_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableFindV2_Tout = TypeVar("TV_LookupTableFindV2_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_find_v2(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableFindV2_Tin], default_value: Annotated[Any, TV_LookupTableFindV2_Tout], name=None) -> Annotated[Any, TV_LookupTableFindV2_Tout]: + r"""Looks up keys in a table, outputs the corresponding values. + + The tensor `keys` must of the same type as the keys of the table. + The output `values` is of the type of the table values. + + The scalar `default_value` is the value output for keys not present in the + table. It must also be of the same type as the table values. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + default_value: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `default_value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableFindV2", name, table_handle, keys, default_value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_find_v2_eager_fallback( + table_handle, keys, default_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableFindV2", table_handle=table_handle, keys=keys, + default_value=default_value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableFindV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LookupTableFindV2 = tf_export("raw_ops.LookupTableFindV2")(_ops.to_raw_op(lookup_table_find_v2)) + + +def lookup_table_find_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableFindV2_Tin], default_value: Annotated[Any, TV_LookupTableFindV2_Tout], name, ctx) -> Annotated[Any, TV_LookupTableFindV2_Tout]: + _attr_Tin, (keys,) = _execute.args_to_matching_eager([keys], ctx, []) + _attr_Tout, (default_value,) = _execute.args_to_matching_eager([default_value], ctx, []) + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle, keys, default_value] + _attrs = ("Tin", _attr_Tin, "Tout", _attr_Tout) + _result = _execute.execute(b"LookupTableFindV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LookupTableFindV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LookupTableImport_Tin = TypeVar("TV_LookupTableImport_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableImport_Tout = TypeVar("TV_LookupTableImport_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_import(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableImport_Tin], values: Annotated[Any, TV_LookupTableImport_Tout], name=None): + r"""Replaces the contents of the table with the specified keys and values. + + The tensor `keys` must be of the same type as the keys of the table. + The tensor `values` must be of the type of the table values. + + Args: + table_handle: A `Tensor` of type mutable `string`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + values: A `Tensor`. Values to associate with keys. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lookup_table_import op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableImport", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +LookupTableImport = tf_export("raw_ops.LookupTableImport")(_ops.to_raw_op(lookup_table_import)) + + +def lookup_table_import_eager_fallback(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableImport_Tin], values: Annotated[Any, TV_LookupTableImport_Tout], name, ctx): + raise RuntimeError("lookup_table_import op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_LookupTableImportV2_Tin = TypeVar("TV_LookupTableImportV2_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableImportV2_Tout = TypeVar("TV_LookupTableImportV2_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_import_v2(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableImportV2_Tin], values: Annotated[Any, TV_LookupTableImportV2_Tout], name=None): + r"""Replaces the contents of the table with the specified keys and values. + + The tensor `keys` must be of the same type as the keys of the table. + The tensor `values` must be of the type of the table values. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + values: A `Tensor`. Values to associate with keys. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableImportV2", name, table_handle, keys, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_import_v2_eager_fallback( + table_handle, keys, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableImportV2", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +LookupTableImportV2 = tf_export("raw_ops.LookupTableImportV2")(_ops.to_raw_op(lookup_table_import_v2)) + + +def lookup_table_import_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableImportV2_Tin], values: Annotated[Any, TV_LookupTableImportV2_Tout], name, ctx): + _attr_Tin, (keys,) = _execute.args_to_matching_eager([keys], ctx, []) + _attr_Tout, (values,) = _execute.args_to_matching_eager([values], ctx, []) + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle, keys, values] + _attrs = ("Tin", _attr_Tin, "Tout", _attr_Tout) + _result = _execute.execute(b"LookupTableImportV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_LookupTableInsert_Tin = TypeVar("TV_LookupTableInsert_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableInsert_Tout = TypeVar("TV_LookupTableInsert_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_insert(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableInsert_Tin], values: Annotated[Any, TV_LookupTableInsert_Tout], name=None): + r"""Updates the table to associates keys with values. + + The tensor `keys` must be of the same type as the keys of the table. + The tensor `values` must be of the type of the table values. + + Args: + table_handle: A `Tensor` of type mutable `string`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + values: A `Tensor`. Values to associate with keys. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lookup_table_insert op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableInsert", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +LookupTableInsert = tf_export("raw_ops.LookupTableInsert")(_ops.to_raw_op(lookup_table_insert)) + + +def lookup_table_insert_eager_fallback(table_handle: Annotated[Any, _atypes.String], keys: Annotated[Any, TV_LookupTableInsert_Tin], values: Annotated[Any, TV_LookupTableInsert_Tout], name, ctx): + raise RuntimeError("lookup_table_insert op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_LookupTableInsertV2_Tin = TypeVar("TV_LookupTableInsertV2_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_LookupTableInsertV2_Tout = TypeVar("TV_LookupTableInsertV2_Tout", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_insert_v2(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableInsertV2_Tin], values: Annotated[Any, TV_LookupTableInsertV2_Tout], name=None): + r"""Updates the table to associates keys with values. + + The tensor `keys` must be of the same type as the keys of the table. + The tensor `values` must be of the type of the table values. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + keys: A `Tensor`. Any shape. Keys to look up. + values: A `Tensor`. Values to associate with keys. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableInsertV2", name, table_handle, keys, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_insert_v2_eager_fallback( + table_handle, keys, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableInsertV2", table_handle=table_handle, keys=keys, + values=values, name=name) + return _op +LookupTableInsertV2 = tf_export("raw_ops.LookupTableInsertV2")(_ops.to_raw_op(lookup_table_insert_v2)) + + +def lookup_table_insert_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableInsertV2_Tin], values: Annotated[Any, TV_LookupTableInsertV2_Tout], name, ctx): + _attr_Tin, (keys,) = _execute.args_to_matching_eager([keys], ctx, []) + _attr_Tout, (values,) = _execute.args_to_matching_eager([values], ctx, []) + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle, keys, values] + _attrs = ("Tin", _attr_Tin, "Tout", _attr_Tout) + _result = _execute.execute(b"LookupTableInsertV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_LookupTableRemoveV2_Tin = TypeVar("TV_LookupTableRemoveV2_Tin", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def lookup_table_remove_v2(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableRemoveV2_Tin], name=None): + r"""Removes keys and its associated values from a table. + + The tensor `keys` must of the same type as the keys of the table. Keys not + already in the table are silently ignored. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + keys: A `Tensor`. Any shape. Keys of the elements to remove. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableRemoveV2", name, table_handle, keys) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_remove_v2_eager_fallback( + table_handle, keys, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableRemoveV2", table_handle=table_handle, keys=keys, + name=name) + return _op +LookupTableRemoveV2 = tf_export("raw_ops.LookupTableRemoveV2")(_ops.to_raw_op(lookup_table_remove_v2)) + + +def lookup_table_remove_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], keys: Annotated[Any, TV_LookupTableRemoveV2_Tin], name, ctx): + _attr_Tin, (keys,) = _execute.args_to_matching_eager([keys], ctx, []) + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle, keys] + _attrs = ("Tin", _attr_Tin) + _result = _execute.execute(b"LookupTableRemoveV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def lookup_table_size(table_handle: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Computes the number of elements in the given table. + + Args: + table_handle: A `Tensor` of type mutable `string`. Handle to the table. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("lookup_table_size op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableSize", table_handle=table_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LookupTableSize = tf_export("raw_ops.LookupTableSize")(_ops.to_raw_op(lookup_table_size)) + + +def lookup_table_size_eager_fallback(table_handle: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int64]: + raise RuntimeError("lookup_table_size op does not support eager execution. Arg 'table_handle' is a ref.") + +def lookup_table_size_v2(table_handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Computes the number of elements in the given table. + + Args: + table_handle: A `Tensor` of type `resource`. Handle to the table. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LookupTableSizeV2", name, table_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lookup_table_size_v2_eager_fallback( + table_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LookupTableSizeV2", table_handle=table_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LookupTableSizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LookupTableSizeV2 = tf_export("raw_ops.LookupTableSizeV2")(_ops.to_raw_op(lookup_table_size_v2)) + + +def lookup_table_size_v2_eager_fallback(table_handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Int64]: + table_handle = _ops.convert_to_tensor(table_handle, _dtypes.resource) + _inputs_flat = [table_handle] + _attrs = None + _result = _execute.execute(b"LookupTableSizeV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LookupTableSizeV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MutableDenseHashTable_key_dtype = TypeVar("TV_MutableDenseHashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableDenseHashTable_value_dtype = TypeVar("TV_MutableDenseHashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_dense_hash_table(empty_key: Annotated[Any, TV_MutableDenseHashTable_key_dtype], value_dtype: TV_MutableDenseHashTable_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, value_shape=[], initial_num_buckets:int=131072, max_load_factor:float=0.8, name=None) -> Annotated[Any, _atypes.String]: + r"""Creates an empty hash table that uses tensors as the backing store. + + It uses "open addressing" with quadratic reprobing to resolve + collisions. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a scalar. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + empty_key: A `Tensor`. + The key used to represent empty key buckets internally. Must not + be used in insert or lookup operations. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + The shape of each value. + initial_num_buckets: An optional `int`. Defaults to `131072`. + The initial number of hash table buckets. Must be a power + to 2. + max_load_factor: An optional `float`. Defaults to `0.8`. + The maximum ratio between number of entries and number of + buckets before growing the table. Must be between 0 and 1. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("mutable_dense_hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + if initial_num_buckets is None: + initial_num_buckets = 131072 + initial_num_buckets = _execute.make_int(initial_num_buckets, "initial_num_buckets") + if max_load_factor is None: + max_load_factor = 0.8 + max_load_factor = _execute.make_float(max_load_factor, "max_load_factor") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableDenseHashTable", empty_key=empty_key, value_dtype=value_dtype, + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + value_shape=value_shape, + initial_num_buckets=initial_num_buckets, + max_load_factor=max_load_factor, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape"), "initial_num_buckets", + _op._get_attr_int("initial_num_buckets"), "max_load_factor", + _op.get_attr("max_load_factor")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableDenseHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableDenseHashTable = tf_export("raw_ops.MutableDenseHashTable")(_ops.to_raw_op(mutable_dense_hash_table)) + + +def mutable_dense_hash_table_eager_fallback(empty_key: Annotated[Any, TV_MutableDenseHashTable_key_dtype], value_dtype: TV_MutableDenseHashTable_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, value_shape, initial_num_buckets: int, max_load_factor: float, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("mutable_dense_hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_MutableDenseHashTableV2_key_dtype = TypeVar("TV_MutableDenseHashTableV2_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableDenseHashTableV2_value_dtype = TypeVar("TV_MutableDenseHashTableV2_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_dense_hash_table_v2(empty_key: Annotated[Any, TV_MutableDenseHashTableV2_key_dtype], deleted_key: Annotated[Any, TV_MutableDenseHashTableV2_key_dtype], value_dtype: TV_MutableDenseHashTableV2_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, value_shape=[], initial_num_buckets:int=131072, max_load_factor:float=0.8, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty hash table that uses tensors as the backing store. + + It uses "open addressing" with quadratic reprobing to resolve + collisions. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a scalar. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + empty_key: A `Tensor`. + The key used to represent empty key buckets internally. Must not + be used in insert or lookup operations. + deleted_key: A `Tensor`. Must have the same type as `empty_key`. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + The shape of each value. + initial_num_buckets: An optional `int`. Defaults to `131072`. + The initial number of hash table buckets. Must be a power + to 2. + max_load_factor: An optional `float`. Defaults to `0.8`. + The maximum ratio between number of entries and number of + buckets before growing the table. Must be between 0 and 1. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MutableDenseHashTableV2", name, empty_key, deleted_key, + "container", container, "shared_name", shared_name, + "use_node_name_sharing", use_node_name_sharing, "value_dtype", + value_dtype, "value_shape", value_shape, "initial_num_buckets", + initial_num_buckets, "max_load_factor", max_load_factor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mutable_dense_hash_table_v2_eager_fallback( + empty_key, deleted_key, container=container, + shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + value_dtype=value_dtype, value_shape=value_shape, + initial_num_buckets=initial_num_buckets, + max_load_factor=max_load_factor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + if initial_num_buckets is None: + initial_num_buckets = 131072 + initial_num_buckets = _execute.make_int(initial_num_buckets, "initial_num_buckets") + if max_load_factor is None: + max_load_factor = 0.8 + max_load_factor = _execute.make_float(max_load_factor, "max_load_factor") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableDenseHashTableV2", empty_key=empty_key, + deleted_key=deleted_key, + value_dtype=value_dtype, + container=container, + shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + value_shape=value_shape, + initial_num_buckets=initial_num_buckets, + max_load_factor=max_load_factor, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape"), "initial_num_buckets", + _op._get_attr_int("initial_num_buckets"), "max_load_factor", + _op.get_attr("max_load_factor")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableDenseHashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableDenseHashTableV2 = tf_export("raw_ops.MutableDenseHashTableV2")(_ops.to_raw_op(mutable_dense_hash_table_v2)) + + +def mutable_dense_hash_table_v2_eager_fallback(empty_key: Annotated[Any, TV_MutableDenseHashTableV2_key_dtype], deleted_key: Annotated[Any, TV_MutableDenseHashTableV2_key_dtype], value_dtype: TV_MutableDenseHashTableV2_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, value_shape, initial_num_buckets: int, max_load_factor: float, name, ctx) -> Annotated[Any, _atypes.Resource]: + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + if initial_num_buckets is None: + initial_num_buckets = 131072 + initial_num_buckets = _execute.make_int(initial_num_buckets, "initial_num_buckets") + if max_load_factor is None: + max_load_factor = 0.8 + max_load_factor = _execute.make_float(max_load_factor, "max_load_factor") + _attr_key_dtype, _inputs_key_dtype = _execute.args_to_matching_eager([empty_key, deleted_key], ctx, []) + (empty_key, deleted_key) = _inputs_key_dtype + _inputs_flat = [empty_key, deleted_key] + _attrs = ("container", container, "shared_name", shared_name, + "use_node_name_sharing", use_node_name_sharing, "key_dtype", + _attr_key_dtype, "value_dtype", value_dtype, "value_shape", value_shape, + "initial_num_buckets", initial_num_buckets, "max_load_factor", + max_load_factor) + _result = _execute.execute(b"MutableDenseHashTableV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MutableDenseHashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MutableHashTable_key_dtype = TypeVar("TV_MutableHashTable_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableHashTable_value_dtype = TypeVar("TV_MutableHashTable_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_hash_table(key_dtype: TV_MutableHashTable_key_dtype, value_dtype: TV_MutableHashTable_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Creates an empty hash table. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a scalar. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + If true and shared_name is empty, the table is shared + using the node name. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("mutable_hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableHashTable", key_dtype=key_dtype, value_dtype=value_dtype, + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableHashTable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableHashTable = tf_export("raw_ops.MutableHashTable")(_ops.to_raw_op(mutable_hash_table)) + + +def mutable_hash_table_eager_fallback(key_dtype: TV_MutableHashTable_key_dtype, value_dtype: TV_MutableHashTable_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("mutable_hash_table op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_MutableHashTableOfTensors_key_dtype = TypeVar("TV_MutableHashTableOfTensors_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableHashTableOfTensors_value_dtype = TypeVar("TV_MutableHashTableOfTensors_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_hash_table_of_tensors(key_dtype: TV_MutableHashTableOfTensors_key_dtype, value_dtype: TV_MutableHashTableOfTensors_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, value_shape=[], name=None) -> Annotated[Any, _atypes.String]: + r"""Creates an empty hash table. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a vector. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("mutable_hash_table_of_tensors op does not support eager execution. Arg 'table_handle' is a ref.") + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableHashTableOfTensors", key_dtype=key_dtype, + value_dtype=value_dtype, + container=container, + shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + value_shape=value_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableHashTableOfTensors", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableHashTableOfTensors = tf_export("raw_ops.MutableHashTableOfTensors")(_ops.to_raw_op(mutable_hash_table_of_tensors)) + + +def mutable_hash_table_of_tensors_eager_fallback(key_dtype: TV_MutableHashTableOfTensors_key_dtype, value_dtype: TV_MutableHashTableOfTensors_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, value_shape, name, ctx) -> Annotated[Any, _atypes.String]: + raise RuntimeError("mutable_hash_table_of_tensors op does not support eager execution. Arg 'table_handle' is a ref.") + +TV_MutableHashTableOfTensorsV2_key_dtype = TypeVar("TV_MutableHashTableOfTensorsV2_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableHashTableOfTensorsV2_value_dtype = TypeVar("TV_MutableHashTableOfTensorsV2_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_hash_table_of_tensors_v2(key_dtype: TV_MutableHashTableOfTensorsV2_key_dtype, value_dtype: TV_MutableHashTableOfTensorsV2_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, value_shape=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty hash table. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a vector. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + value_shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MutableHashTableOfTensorsV2", name, "container", container, + "shared_name", shared_name, "use_node_name_sharing", + use_node_name_sharing, "key_dtype", key_dtype, "value_dtype", + value_dtype, "value_shape", value_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mutable_hash_table_of_tensors_v2_eager_fallback( + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, key_dtype=key_dtype, + value_dtype=value_dtype, value_shape=value_shape, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableHashTableOfTensorsV2", key_dtype=key_dtype, + value_dtype=value_dtype, + container=container, + shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + value_shape=value_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype"), "value_shape", + _op.get_attr("value_shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableHashTableOfTensorsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableHashTableOfTensorsV2 = tf_export("raw_ops.MutableHashTableOfTensorsV2")(_ops.to_raw_op(mutable_hash_table_of_tensors_v2)) + + +def mutable_hash_table_of_tensors_v2_eager_fallback(key_dtype: TV_MutableHashTableOfTensorsV2_key_dtype, value_dtype: TV_MutableHashTableOfTensorsV2_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, value_shape, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + if value_shape is None: + value_shape = [] + value_shape = _execute.make_shape(value_shape, "value_shape") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name, + "use_node_name_sharing", use_node_name_sharing, "key_dtype", key_dtype, + "value_dtype", value_dtype, "value_shape", value_shape) + _result = _execute.execute(b"MutableHashTableOfTensorsV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MutableHashTableOfTensorsV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MutableHashTableV2_key_dtype = TypeVar("TV_MutableHashTableV2_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_MutableHashTableV2_value_dtype = TypeVar("TV_MutableHashTableV2_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def mutable_hash_table_v2(key_dtype: TV_MutableHashTableV2_key_dtype, value_dtype: TV_MutableHashTableV2_value_dtype, container:str="", shared_name:str="", use_node_name_sharing:bool=False, name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates an empty hash table. + + This op creates a mutable hash table, specifying the type of its keys and + values. Each value must be a scalar. Data can be inserted into the table using + the insert operations. It does not support the initialization operation. + + Args: + key_dtype: A `tf.DType`. Type of the table keys. + value_dtype: A `tf.DType`. Type of the table values. + container: An optional `string`. Defaults to `""`. + If non-empty, this table is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this table is shared under the given name across + multiple sessions. + use_node_name_sharing: An optional `bool`. Defaults to `False`. + If true and shared_name is empty, the table is shared + using the node name. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MutableHashTableV2", name, "container", container, + "shared_name", shared_name, "use_node_name_sharing", + use_node_name_sharing, "key_dtype", key_dtype, "value_dtype", + value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mutable_hash_table_v2_eager_fallback( + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, key_dtype=key_dtype, + value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutableHashTableV2", key_dtype=key_dtype, value_dtype=value_dtype, + container=container, shared_name=shared_name, + use_node_name_sharing=use_node_name_sharing, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "use_node_name_sharing", + _op._get_attr_bool("use_node_name_sharing"), "key_dtype", + _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutableHashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutableHashTableV2 = tf_export("raw_ops.MutableHashTableV2")(_ops.to_raw_op(mutable_hash_table_v2)) + + +def mutable_hash_table_v2_eager_fallback(key_dtype: TV_MutableHashTableV2_key_dtype, value_dtype: TV_MutableHashTableV2_value_dtype, container: str, shared_name: str, use_node_name_sharing: bool, name, ctx) -> Annotated[Any, _atypes.Resource]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + value_dtype = _execute.make_type(value_dtype, "value_dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if use_node_name_sharing is None: + use_node_name_sharing = False + use_node_name_sharing = _execute.make_bool(use_node_name_sharing, "use_node_name_sharing") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name, + "use_node_name_sharing", use_node_name_sharing, "key_dtype", key_dtype, + "value_dtype", value_dtype) + _result = _execute.execute(b"MutableHashTableV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MutableHashTableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_manip_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_manip_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3b10462fc3f22c0a593e1fb1efb7d4a068f2cafc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_manip_ops.py @@ -0,0 +1,116 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Roll_T = TypeVar("TV_Roll_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Roll_Tshift = TypeVar("TV_Roll_Tshift", _atypes.Int32, _atypes.Int64) +TV_Roll_Taxis = TypeVar("TV_Roll_Taxis", _atypes.Int32, _atypes.Int64) + +def roll(input: Annotated[Any, TV_Roll_T], shift: Annotated[Any, TV_Roll_Tshift], axis: Annotated[Any, TV_Roll_Taxis], name=None) -> Annotated[Any, TV_Roll_T]: + r"""Rolls the elements of a tensor along an axis. + + The elements are shifted positively (towards larger indices) by the offset of + `shift` along the dimension of `axis`. Negative `shift` values will shift + elements in the opposite direction. Elements that roll passed the last position + will wrap around to the first and vice versa. Multiple shifts along multiple + axes may be specified. + + For example: + + ``` + # 't' is [0, 1, 2, 3, 4] + roll(t, shift=2, axis=0) ==> [3, 4, 0, 1, 2] + + # shifting along multiple dimensions + # 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] + roll(t, shift=[1, -2], axis=[0, 1]) ==> [[7, 8, 9, 5, 6], [2, 3, 4, 0, 1]] + + # shifting along the same axis multiple times + # 't' is [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] + roll(t, shift=[2, -3], axis=[1, 1]) ==> [[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]] + ``` + + Args: + input: A `Tensor`. + shift: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Dimension must be 0-D or 1-D. `shift[i]` specifies the number of places by which + elements are shifted positively (towards larger indices) along the dimension + specified by `axis[i]`. Negative shifts will roll the elements in the opposite + direction. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Dimension must be 0-D or 1-D. `axis[i]` specifies the dimension that the shift + `shift[i]` should occur. If the same axis is referenced more than once, the + total shift for that axis will be the sum of all the shifts that belong to that + axis. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Roll", name, input, shift, axis) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return roll_eager_fallback( + input, shift, axis, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Roll", input=input, shift=shift, axis=axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tshift", + _op._get_attr_type("Tshift"), "Taxis", + _op._get_attr_type("Taxis")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Roll", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Roll = tf_export("raw_ops.Roll")(_ops.to_raw_op(roll)) + + +def roll_eager_fallback(input: Annotated[Any, TV_Roll_T], shift: Annotated[Any, TV_Roll_Tshift], axis: Annotated[Any, TV_Roll_Taxis], name, ctx) -> Annotated[Any, TV_Roll_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _attr_Tshift, (shift,) = _execute.args_to_matching_eager([shift], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input, shift, axis] + _attrs = ("T", _attr_T, "Tshift", _attr_Tshift, "Taxis", _attr_Taxis) + _result = _execute.execute(b"Roll", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Roll", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_map_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_map_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a982e832ed251fa5603ece2c9103382ec1e048dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_map_ops.py @@ -0,0 +1,466 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def empty_tensor_map(name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates and returns an empty tensor map. + + handle: an empty tensor map + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EmptyTensorMap", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return empty_tensor_map_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EmptyTensorMap", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "EmptyTensorMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EmptyTensorMap = tf_export("raw_ops.EmptyTensorMap")(_ops.to_raw_op(empty_tensor_map)) + + +def empty_tensor_map_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Variant]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"EmptyTensorMap", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EmptyTensorMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorMapErase_key_dtype = TypeVar("TV_TensorMapErase_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorMapErase_value_dtype = TypeVar("TV_TensorMapErase_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_map_erase(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapErase_key_dtype], value_dtype: TV_TensorMapErase_value_dtype, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Returns a tensor map with item from given key erased. + + input_handle: the original map + output_handle: the map with value from given key removed + key: the key of the value to be erased + + Args: + input_handle: A `Tensor` of type `variant`. + key: A `Tensor`. + value_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapErase", name, input_handle, key, "value_dtype", + value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_erase_eager_fallback( + input_handle, key, value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapErase", input_handle=input_handle, key=key, + value_dtype=value_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapErase", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapErase = tf_export("raw_ops.TensorMapErase")(_ops.to_raw_op(tensor_map_erase)) + + +def tensor_map_erase_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapErase_key_dtype], value_dtype: TV_TensorMapErase_value_dtype, name, ctx) -> Annotated[Any, _atypes.Variant]: + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _attr_key_dtype, (key,) = _execute.args_to_matching_eager([key], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle, key] + _attrs = ("key_dtype", _attr_key_dtype, "value_dtype", value_dtype) + _result = _execute.execute(b"TensorMapErase", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapErase", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorMapHasKey_key_dtype = TypeVar("TV_TensorMapHasKey_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_map_has_key(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapHasKey_key_dtype], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns whether the given key exists in the map. + + input_handle: the input map + key: the key to check + has_key: whether the key is already in the map or not + + Args: + input_handle: A `Tensor` of type `variant`. + key: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapHasKey", name, input_handle, key) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_has_key_eager_fallback( + input_handle, key, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapHasKey", input_handle=input_handle, key=key, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapHasKey", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapHasKey = tf_export("raw_ops.TensorMapHasKey")(_ops.to_raw_op(tensor_map_has_key)) + + +def tensor_map_has_key_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapHasKey_key_dtype], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_key_dtype, (key,) = _execute.args_to_matching_eager([key], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle, key] + _attrs = ("key_dtype", _attr_key_dtype) + _result = _execute.execute(b"TensorMapHasKey", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapHasKey", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorMapInsert_key_dtype = TypeVar("TV_TensorMapInsert_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorMapInsert_value_dtype = TypeVar("TV_TensorMapInsert_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_map_insert(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapInsert_key_dtype], value: Annotated[Any, TV_TensorMapInsert_value_dtype], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Returns a map that is the 'input_handle' with the given key-value pair inserted. + + input_handle: the original map + output_handle: the map with key and value inserted + key: the key to be inserted + value: the value to be inserted + + Args: + input_handle: A `Tensor` of type `variant`. + key: A `Tensor`. + value: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapInsert", name, input_handle, key, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_insert_eager_fallback( + input_handle, key, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapInsert", input_handle=input_handle, key=key, value=value, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapInsert", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapInsert = tf_export("raw_ops.TensorMapInsert")(_ops.to_raw_op(tensor_map_insert)) + + +def tensor_map_insert_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapInsert_key_dtype], value: Annotated[Any, TV_TensorMapInsert_value_dtype], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_key_dtype, (key,) = _execute.args_to_matching_eager([key], ctx, []) + _attr_value_dtype, (value,) = _execute.args_to_matching_eager([value], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle, key, value] + _attrs = ("key_dtype", _attr_key_dtype, "value_dtype", _attr_value_dtype) + _result = _execute.execute(b"TensorMapInsert", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapInsert", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorMapLookup_key_dtype = TypeVar("TV_TensorMapLookup_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_TensorMapLookup_value_dtype = TypeVar("TV_TensorMapLookup_value_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_map_lookup(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapLookup_key_dtype], value_dtype: TV_TensorMapLookup_value_dtype, name=None) -> Annotated[Any, TV_TensorMapLookup_value_dtype]: + r"""Returns the value from a given key in a tensor map. + + input_handle: the input map + key: the key to be looked up + value: the value found from the given key + + Args: + input_handle: A `Tensor` of type `variant`. + key: A `Tensor`. + value_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `value_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapLookup", name, input_handle, key, "value_dtype", + value_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_lookup_eager_fallback( + input_handle, key, value_dtype=value_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapLookup", input_handle=input_handle, key=key, + value_dtype=value_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype"), "value_dtype", + _op._get_attr_type("value_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapLookup", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapLookup = tf_export("raw_ops.TensorMapLookup")(_ops.to_raw_op(tensor_map_lookup)) + + +def tensor_map_lookup_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], key: Annotated[Any, TV_TensorMapLookup_key_dtype], value_dtype: TV_TensorMapLookup_value_dtype, name, ctx) -> Annotated[Any, TV_TensorMapLookup_value_dtype]: + value_dtype = _execute.make_type(value_dtype, "value_dtype") + _attr_key_dtype, (key,) = _execute.args_to_matching_eager([key], ctx, []) + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle, key] + _attrs = ("key_dtype", _attr_key_dtype, "value_dtype", value_dtype) + _result = _execute.execute(b"TensorMapLookup", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapLookup", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tensor_map_size(input_handle: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the number of tensors in the input tensor map. + + input_handle: the input map + size: the number of tensors in the map + + Args: + input_handle: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapSize", name, input_handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_size_eager_fallback( + input_handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapSize", input_handle=input_handle, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapSize = tf_export("raw_ops.TensorMapSize")(_ops.to_raw_op(tensor_map_size)) + + +def tensor_map_size_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int32]: + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = None + _result = _execute.execute(b"TensorMapSize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TensorMapStackKeys_key_dtype = TypeVar("TV_TensorMapStackKeys_key_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tensor_map_stack_keys(input_handle: Annotated[Any, _atypes.Variant], key_dtype: TV_TensorMapStackKeys_key_dtype, name=None) -> Annotated[Any, TV_TensorMapStackKeys_key_dtype]: + r"""Returns a Tensor stack of all keys in a tensor map. + + input_handle: the input map + keys: the returned Tensor of all keys in the map + + Args: + input_handle: A `Tensor` of type `variant`. + key_dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `key_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TensorMapStackKeys", name, input_handle, "key_dtype", + key_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tensor_map_stack_keys_eager_fallback( + input_handle, key_dtype=key_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + key_dtype = _execute.make_type(key_dtype, "key_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TensorMapStackKeys", input_handle=input_handle, key_dtype=key_dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("key_dtype", _op._get_attr_type("key_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TensorMapStackKeys", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TensorMapStackKeys = tf_export("raw_ops.TensorMapStackKeys")(_ops.to_raw_op(tensor_map_stack_keys)) + + +def tensor_map_stack_keys_eager_fallback(input_handle: Annotated[Any, _atypes.Variant], key_dtype: TV_TensorMapStackKeys_key_dtype, name, ctx) -> Annotated[Any, TV_TensorMapStackKeys_key_dtype]: + key_dtype = _execute.make_type(key_dtype, "key_dtype") + input_handle = _ops.convert_to_tensor(input_handle, _dtypes.variant) + _inputs_flat = [input_handle] + _attrs = ("key_dtype", key_dtype) + _result = _execute.execute(b"TensorMapStackKeys", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TensorMapStackKeys", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2df6f68ebdff506afd7c4b3647612eeea7b2ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_math_ops.py @@ -0,0 +1,13616 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Abs_T = TypeVar("TV_Abs_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def _abs(x: Annotated[Any, TV_Abs_T], name=None) -> Annotated[Any, TV_Abs_T]: + r"""Computes the absolute value of a tensor. + + Given a tensor `x`, this operation returns a tensor containing the absolute + value of each element in `x`. For example, if x is an input element and y is + an output element, this operation computes \\(y = |x|\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Abs", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _abs_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Abs", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Abs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Abs = tf_export("raw_ops.Abs")(_ops.to_raw_op(_abs)) + + +def _abs_eager_fallback(x: Annotated[Any, TV_Abs_T], name, ctx) -> Annotated[Any, TV_Abs_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Abs", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Abs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AccumulateNV2_T = TypeVar("TV_AccumulateNV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def accumulate_nv2(inputs: Annotated[List[Any], TV_AccumulateNV2_T], shape, name=None) -> Annotated[Any, TV_AccumulateNV2_T]: + r"""Returns the element-wise sum of a list of tensors. + + `tf.accumulate_n_v2` performs the same operation as `tf.add_n`, but does not + wait for all of its inputs to be ready before beginning to sum. This can + save memory if inputs are ready at different times, since minimum temporary + storage is proportional to the output size rather than the inputs size. + + Unlike the original `accumulate_n`, `accumulate_n_v2` is differentiable. + + Returns a `Tensor` of same shape and type as the elements of `inputs`. + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type in: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A list of `Tensor` objects, each with same shape and type. + shape: A `tf.TensorShape` or list of `ints`. + Shape of elements of `inputs`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AccumulateNV2", name, inputs, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return accumulate_nv2_eager_fallback( + inputs, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'accumulate_nv2' Op, not %r." % inputs) + _attr_N = len(inputs) + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AccumulateNV2", inputs=inputs, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "shape", _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AccumulateNV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AccumulateNV2 = tf_export("raw_ops.AccumulateNV2")(_ops.to_raw_op(accumulate_nv2)) + + +def accumulate_nv2_eager_fallback(inputs: Annotated[List[Any], TV_AccumulateNV2_T], shape, name, ctx) -> Annotated[Any, TV_AccumulateNV2_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'accumulate_nv2' Op, not %r." % inputs) + _attr_N = len(inputs) + shape = _execute.make_shape(shape, "shape") + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "T", _attr_T, "shape", shape) + _result = _execute.execute(b"AccumulateNV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AccumulateNV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Acos_T = TypeVar("TV_Acos_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def acos(x: Annotated[Any, TV_Acos_T], name=None) -> Annotated[Any, TV_Acos_T]: + r"""Computes acos of x element-wise. + + + Provided an input tensor, the `tf.math.acos` operation returns the inverse cosine of each element of the tensor. If `y = tf.math.cos(x)` then, `x = tf.math.acos(y)`. + + Input range is `[-1, 1]` and the output has a range of `[0, pi]`. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Acos", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return acos_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Acos", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Acos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Acos = tf_export("raw_ops.Acos")(_ops.to_raw_op(acos)) + + +def acos_eager_fallback(x: Annotated[Any, TV_Acos_T], name, ctx) -> Annotated[Any, TV_Acos_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Acos", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Acos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Acosh_T = TypeVar("TV_Acosh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.acosh', 'acosh') +def acosh(x: Annotated[Any, TV_Acosh_T], name=None) -> Annotated[Any, TV_Acosh_T]: + r"""Computes inverse hyperbolic cosine of x element-wise. + + Given an input tensor, the function computes inverse hyperbolic cosine of every element. + Input range is `[1, inf]`. It returns `nan` if the input lies outside the range. + + ```python + x = tf.constant([-2, -0.5, 1, 1.2, 200, 10000, float("inf")]) + tf.math.acosh(x) ==> [nan nan 0. 0.62236255 5.9914584 9.903487 inf] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Acosh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_acosh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return acosh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + acosh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_acosh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Acosh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + acosh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Acosh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Acosh = tf_export("raw_ops.Acosh")(_ops.to_raw_op(acosh)) +_dispatcher_for_acosh = acosh._tf_type_based_dispatcher.Dispatch + + +def acosh_eager_fallback(x: Annotated[Any, TV_Acosh_T], name, ctx) -> Annotated[Any, TV_Acosh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Acosh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Acosh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Add_T = TypeVar("TV_Add_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt8) + +def add(x: Annotated[Any, TV_Add_T], y: Annotated[Any, TV_Add_T], name=None) -> Annotated[Any, TV_Add_T]: + r"""Returns x + y element-wise. + + *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Given two input tensors, the `tf.add` operation computes the sum for every element in the tensor. + + Both input and output have a range `(-inf, inf)`. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `string`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Add", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return add_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Add", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Add", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Add = tf_export("raw_ops.Add")(_ops.to_raw_op(add)) + + +def add_eager_fallback(x: Annotated[Any, TV_Add_T], y: Annotated[Any, TV_Add_T], name, ctx) -> Annotated[Any, TV_Add_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, _dtypes.string, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Add", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Add", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AddN_T = TypeVar("TV_AddN_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def add_n(inputs: Annotated[List[Any], TV_AddN_T], name=None) -> Annotated[Any, TV_AddN_T]: + r"""Add all input tensors element wise. + + Inputs must be of same size and shape. + + ```python + x = [9, 7, 10] + tf.math.add_n(x) ==> 26 + ``` + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type in: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AddN", name, inputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return add_n_eager_fallback( + inputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'add_n' Op, not %r." % inputs) + _attr_N = len(inputs) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AddN", inputs=inputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AddN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AddN = tf_export("raw_ops.AddN")(_ops.to_raw_op(add_n)) + + +def add_n_eager_fallback(inputs: Annotated[List[Any], TV_AddN_T], name, ctx) -> Annotated[Any, TV_AddN_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'add_n' Op, not %r." % inputs) + _attr_N = len(inputs) + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.variant, ]) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"AddN", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AddN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AddV2_T = TypeVar("TV_AddV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def add_v2(x: Annotated[Any, TV_AddV2_T], y: Annotated[Any, TV_AddV2_T], name=None) -> Annotated[Any, TV_AddV2_T]: + r"""Returns x + y element-wise. + + *NOTE*: `Add` supports broadcasting. `AddN` does not. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AddV2", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return add_v2_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AddV2", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AddV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AddV2 = tf_export("raw_ops.AddV2")(_ops.to_raw_op(add_v2)) + + +def add_v2_eager_fallback(x: Annotated[Any, TV_AddV2_T], y: Annotated[Any, TV_AddV2_T], name, ctx) -> Annotated[Any, TV_AddV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AddV2", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AddV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_All_Tidx = TypeVar("TV_All_Tidx", _atypes.Int32, _atypes.Int64) + +def _all(input: Annotated[Any, _atypes.Bool], axis: Annotated[Any, TV_All_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Computes the "logical and" of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor` of type `bool`. The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "All", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _all_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "All", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "Tidx", + _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "All", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +All = tf_export("raw_ops.All")(_ops.to_raw_op(_all)) + + +def _all_eager_fallback(input: Annotated[Any, _atypes.Bool], axis: Annotated[Any, TV_All_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, _atypes.Bool]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + input = _ops.convert_to_tensor(input, _dtypes.bool) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "Tidx", _attr_Tidx) + _result = _execute.execute(b"All", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "All", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Angle_T = TypeVar("TV_Angle_T", _atypes.Complex128, _atypes.Complex64) +TV_Angle_Tout = TypeVar("TV_Angle_Tout", _atypes.Float32, _atypes.Float64) + +def angle(input: Annotated[Any, TV_Angle_T], Tout:TV_Angle_Tout=_dtypes.float32, name=None) -> Annotated[Any, TV_Angle_Tout]: + r"""Returns the argument of a complex number. + + Given a tensor `input` of complex numbers, this operation returns a tensor of + type `float` that is the argument of each element in `input`. All elements in + `input` must be complex numbers of the form \\(a + bj\\), where *a* + is the real part and *b* is the imaginary part. + + The argument returned by this operation is of the form \\(atan2(b, a)\\). + + For example: + + ``` + # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] + tf.math.angle(input) ==> [2.0132, 1.056] + ``` + + @compatibility(numpy) + Equivalent to np.angle. + @end_compatibility + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Angle", name, input, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return angle_eager_fallback( + input, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Angle", input=input, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Angle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Angle = tf_export("raw_ops.Angle")(_ops.to_raw_op(angle)) + + +def angle_eager_fallback(input: Annotated[Any, TV_Angle_T], Tout: TV_Angle_Tout, name, ctx) -> Annotated[Any, TV_Angle_Tout]: + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"Angle", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Angle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Any_Tidx = TypeVar("TV_Any_Tidx", _atypes.Int32, _atypes.Int64) + +def _any(input: Annotated[Any, _atypes.Bool], axis: Annotated[Any, TV_Any_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Computes the "logical or" of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor` of type `bool`. The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Any", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _any_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Any", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "Tidx", + _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Any", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Any = tf_export("raw_ops.Any")(_ops.to_raw_op(_any)) + + +def _any_eager_fallback(input: Annotated[Any, _atypes.Bool], axis: Annotated[Any, TV_Any_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, _atypes.Bool]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + input = _ops.convert_to_tensor(input, _dtypes.bool) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Any", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Any", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ApproximateEqual_T = TypeVar("TV_ApproximateEqual_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def approximate_equal(x: Annotated[Any, TV_ApproximateEqual_T], y: Annotated[Any, TV_ApproximateEqual_T], tolerance:float=1e-05, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of abs(x-y) < tolerance element-wise. + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + tolerance: An optional `float`. Defaults to `1e-05`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ApproximateEqual", name, x, y, "tolerance", tolerance) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return approximate_equal_eager_fallback( + x, y, tolerance=tolerance, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if tolerance is None: + tolerance = 1e-05 + tolerance = _execute.make_float(tolerance, "tolerance") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApproximateEqual", x=x, y=y, tolerance=tolerance, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "tolerance", + _op.get_attr("tolerance")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApproximateEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApproximateEqual = tf_export("raw_ops.ApproximateEqual")(_ops.to_raw_op(approximate_equal)) + + +def approximate_equal_eager_fallback(x: Annotated[Any, TV_ApproximateEqual_T], y: Annotated[Any, TV_ApproximateEqual_T], tolerance: float, name, ctx) -> Annotated[Any, _atypes.Bool]: + if tolerance is None: + tolerance = 1e-05 + tolerance = _execute.make_float(tolerance, "tolerance") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "tolerance", tolerance) + _result = _execute.execute(b"ApproximateEqual", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ApproximateEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ArgMax_T = TypeVar("TV_ArgMax_T", _atypes.BFloat16, _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ArgMax_Tidx = TypeVar("TV_ArgMax_Tidx", _atypes.Int16, _atypes.Int32, _atypes.Int64) +TV_ArgMax_output_type = TypeVar("TV_ArgMax_output_type", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.UInt16) + +def arg_max(input: Annotated[Any, TV_ArgMax_T], dimension: Annotated[Any, TV_ArgMax_Tidx], output_type:TV_ArgMax_output_type=_dtypes.int64, name=None) -> Annotated[Any, TV_ArgMax_output_type]: + r"""Returns the index with the largest value across dimensions of a tensor. + + Note that in case of ties the identity of the return value is not guaranteed. + + Usage: + ```python + import tensorflow as tf + a = [1, 10, 26.9, 2.8, 166.32, 62.3] + b = tf.math.argmax(input = a) + c = tf.keras.backend.eval(b) + # c = 4 + # here a[4] = 166.32 which is the largest element of a across axis 0 + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`, `quint8`, `qint32`, `qint16`, `quint16`, `bool`. + dimension: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + int16, int32 or int64, must be in the range `[-rank(input), rank(input))`. + Describes which dimension of the input Tensor to reduce across. For vectors, + use dimension = 0. + output_type: An optional `tf.DType` from: `tf.int16, tf.uint16, tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ArgMax", name, input, dimension, "output_type", output_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return arg_max_eager_fallback( + input, dimension, output_type=output_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_type is None: + output_type = _dtypes.int64 + output_type = _execute.make_type(output_type, "output_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ArgMax", input=input, dimension=dimension, output_type=output_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "output_type", + _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ArgMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ArgMax = tf_export("raw_ops.ArgMax")(_ops.to_raw_op(arg_max)) + + +def arg_max_eager_fallback(input: Annotated[Any, TV_ArgMax_T], dimension: Annotated[Any, TV_ArgMax_Tidx], output_type: TV_ArgMax_output_type, name, ctx) -> Annotated[Any, TV_ArgMax_output_type]: + if output_type is None: + output_type = _dtypes.int64 + output_type = _execute.make_type(output_type, "output_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, _dtypes.bool, ]) + _attr_Tidx, (dimension,) = _execute.args_to_matching_eager([dimension], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, dimension] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "output_type", output_type) + _result = _execute.execute(b"ArgMax", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ArgMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ArgMin_T = TypeVar("TV_ArgMin_T", _atypes.BFloat16, _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ArgMin_Tidx = TypeVar("TV_ArgMin_Tidx", _atypes.Int32, _atypes.Int64) +TV_ArgMin_output_type = TypeVar("TV_ArgMin_output_type", _atypes.Int32, _atypes.Int64) + +def arg_min(input: Annotated[Any, TV_ArgMin_T], dimension: Annotated[Any, TV_ArgMin_Tidx], output_type:TV_ArgMin_output_type=_dtypes.int64, name=None) -> Annotated[Any, TV_ArgMin_output_type]: + r"""Returns the index with the smallest value across dimensions of a tensor. + + Note that in case of ties the identity of the return value is not guaranteed. + + Usage: + ```python + import tensorflow as tf + a = [1, 10, 26.9, 2.8, 166.32, 62.3] + b = tf.math.argmin(input = a) + c = tf.keras.backend.eval(b) + # c = 0 + # here a[0] = 1 which is the smallest element of a across axis 0 + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`, `quint8`, `qint32`, `qint16`, `quint16`, `bool`. + dimension: A `Tensor`. Must be one of the following types: `int32`, `int64`. + int32 or int64, must be in the range `[-rank(input), rank(input))`. + Describes which dimension of the input Tensor to reduce across. For vectors, + use dimension = 0. + output_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ArgMin", name, input, dimension, "output_type", output_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return arg_min_eager_fallback( + input, dimension, output_type=output_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_type is None: + output_type = _dtypes.int64 + output_type = _execute.make_type(output_type, "output_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ArgMin", input=input, dimension=dimension, output_type=output_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "output_type", + _op._get_attr_type("output_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ArgMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ArgMin = tf_export("raw_ops.ArgMin")(_ops.to_raw_op(arg_min)) + + +def arg_min_eager_fallback(input: Annotated[Any, TV_ArgMin_T], dimension: Annotated[Any, TV_ArgMin_Tidx], output_type: TV_ArgMin_output_type, name, ctx) -> Annotated[Any, TV_ArgMin_output_type]: + if output_type is None: + output_type = _dtypes.int64 + output_type = _execute.make_type(output_type, "output_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, _dtypes.bool, ]) + _attr_Tidx, (dimension,) = _execute.args_to_matching_eager([dimension], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, dimension] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "output_type", output_type) + _result = _execute.execute(b"ArgMin", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ArgMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Asin_T = TypeVar("TV_Asin_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.asin', 'asin') +def asin(x: Annotated[Any, TV_Asin_T], name=None) -> Annotated[Any, TV_Asin_T]: + r"""Computes the trignometric inverse sine of x element-wise. + + The `tf.math.asin` operation returns the inverse of `tf.math.sin`, such that + if `y = tf.math.sin(x)` then, `x = tf.math.asin(y)`. + + **Note**: The output of `tf.math.asin` will lie within the invertible range + of sine, i.e [-pi/2, pi/2]. + + For example: + + ```python + # Note: [1.047, 0.785] ~= [(pi/3), (pi/4)] + x = tf.constant([1.047, 0.785]) + y = tf.math.sin(x) # [0.8659266, 0.7068252] + + tf.math.asin(y) # [1.047, 0.785] = x + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Asin", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_asin( + (x, name,), None) + if _result is not NotImplemented: + return _result + return asin_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + asin, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_asin( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Asin", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + asin, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Asin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Asin = tf_export("raw_ops.Asin")(_ops.to_raw_op(asin)) +_dispatcher_for_asin = asin._tf_type_based_dispatcher.Dispatch + + +def asin_eager_fallback(x: Annotated[Any, TV_Asin_T], name, ctx) -> Annotated[Any, TV_Asin_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Asin", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Asin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Asinh_T = TypeVar("TV_Asinh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.asinh', 'asinh') +def asinh(x: Annotated[Any, TV_Asinh_T], name=None) -> Annotated[Any, TV_Asinh_T]: + r"""Computes inverse hyperbolic sine of x element-wise. + + Given an input tensor, this function computes inverse hyperbolic sine + for every element in the tensor. Both input and output has a range of + `[-inf, inf]`. + + ```python + x = tf.constant([-float("inf"), -2, -0.5, 1, 1.2, 200, 10000, float("inf")]) + tf.math.asinh(x) ==> [-inf -1.4436355 -0.4812118 0.8813736 1.0159732 5.991471 9.903487 inf] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Asinh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_asinh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return asinh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + asinh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_asinh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Asinh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + asinh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Asinh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Asinh = tf_export("raw_ops.Asinh")(_ops.to_raw_op(asinh)) +_dispatcher_for_asinh = asinh._tf_type_based_dispatcher.Dispatch + + +def asinh_eager_fallback(x: Annotated[Any, TV_Asinh_T], name, ctx) -> Annotated[Any, TV_Asinh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Asinh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Asinh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Atan_T = TypeVar("TV_Atan_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.atan', 'atan') +def atan(x: Annotated[Any, TV_Atan_T], name=None) -> Annotated[Any, TV_Atan_T]: + r"""Computes the trignometric inverse tangent of x element-wise. + + The `tf.math.atan` operation returns the inverse of `tf.math.tan`, such that + if `y = tf.math.tan(x)` then, `x = tf.math.atan(y)`. + + **Note**: The output of `tf.math.atan` will lie within the invertible range + of tan, i.e (-pi/2, pi/2). + + For example: + + ```python + # Note: [1.047, 0.785] ~= [(pi/3), (pi/4)] + x = tf.constant([1.047, 0.785]) + y = tf.math.tan(x) # [1.731261, 0.99920404] + + tf.math.atan(y) # [1.047, 0.785] = x + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Atan", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_atan( + (x, name,), None) + if _result is not NotImplemented: + return _result + return atan_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_atan( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Atan", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Atan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Atan = tf_export("raw_ops.Atan")(_ops.to_raw_op(atan)) +_dispatcher_for_atan = atan._tf_type_based_dispatcher.Dispatch + + +def atan_eager_fallback(x: Annotated[Any, TV_Atan_T], name, ctx) -> Annotated[Any, TV_Atan_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Atan", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Atan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Atan2_T = TypeVar("TV_Atan2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.atan2', 'atan2') +def atan2(y: Annotated[Any, TV_Atan2_T], x: Annotated[Any, TV_Atan2_T], name=None) -> Annotated[Any, TV_Atan2_T]: + r"""Computes arctangent of `y/x` element-wise, respecting signs of the arguments. + + This is the angle \\( \theta \in [-\pi, \pi] \\) such that + \\[ x = r \cos(\theta) \\] + and + \\[ y = r \sin(\theta) \\] + where \\(r = \sqrt{x^2 + y^2} \\). + + For example: + + >>> x = [1., 1.] + >>> y = [1., -1.] + >>> print((tf.math.atan2(y,x) * (180 / np.pi)).numpy()) + [ 45. -45.] + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + x: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Atan2", name, y, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_atan2( + (y, x, name,), None) + if _result is not NotImplemented: + return _result + return atan2_eager_fallback( + y, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atan2, (), dict(y=y, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_atan2( + (y, x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Atan2", y=y, x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atan2, (), dict(y=y, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Atan2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Atan2 = tf_export("raw_ops.Atan2")(_ops.to_raw_op(atan2)) +_dispatcher_for_atan2 = atan2._tf_type_based_dispatcher.Dispatch + + +def atan2_eager_fallback(y: Annotated[Any, TV_Atan2_T], x: Annotated[Any, TV_Atan2_T], name, ctx) -> Annotated[Any, TV_Atan2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (y, x) = _inputs_T + _inputs_flat = [y, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Atan2", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Atan2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Atanh_T = TypeVar("TV_Atanh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.atanh', 'atanh') +def atanh(x: Annotated[Any, TV_Atanh_T], name=None) -> Annotated[Any, TV_Atanh_T]: + r"""Computes inverse hyperbolic tangent of x element-wise. + + Given an input tensor, this function computes inverse hyperbolic tangent + for every element in the tensor. Input range is `[-1,1]` and output range is + `[-inf, inf]`. If input is `-1`, output will be `-inf` and if the + input is `1`, output will be `inf`. Values outside the range will have + `nan` as output. + + ```python + x = tf.constant([-float("inf"), -1, -0.5, 1, 0, 0.5, 10, float("inf")]) + tf.math.atanh(x) ==> [nan -inf -0.54930615 inf 0. 0.54930615 nan nan] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Atanh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_atanh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return atanh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atanh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_atanh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Atanh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + atanh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Atanh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Atanh = tf_export("raw_ops.Atanh")(_ops.to_raw_op(atanh)) +_dispatcher_for_atanh = atanh._tf_type_based_dispatcher.Dispatch + + +def atanh_eager_fallback(x: Annotated[Any, TV_Atanh_T], name, ctx) -> Annotated[Any, TV_Atanh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Atanh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Atanh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatMul_T = TypeVar("TV_BatchMatMul_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def batch_mat_mul(x: Annotated[Any, TV_BatchMatMul_T], y: Annotated[Any, TV_BatchMatMul_T], adj_x:bool=False, adj_y:bool=False, name=None) -> Annotated[Any, TV_BatchMatMul_T]: + r"""Multiplies slices of two tensors in batches. + + Multiplies all slices of `Tensor` `x` and `y` (each slice can be + viewed as an element of a batch), and arranges the individual results + in a single output tensor of the same batch size. Each of the + individual slices can optionally be adjointed (to adjoint a matrix + means to transpose and conjugate it) before multiplication by setting + the `adj_x` or `adj_y` flag to `True`, which are by default `False`. + + The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` + and `[..., r_y, c_y]`. + + The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: + + r_o = c_x if adj_x else r_x + c_o = r_y if adj_y else c_y + + It is computed as: + + output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. + 2-D or higher with shape `[..., r_x, c_x]`. + y: A `Tensor`. Must have the same type as `x`. + 2-D or higher with shape `[..., r_y, c_y]`. + adj_x: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `x`. Defaults to `False`. + adj_y: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `y`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatMul", name, x, y, "adj_x", adj_x, "adj_y", adj_y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_mat_mul_eager_fallback( + x, y, adj_x=adj_x, adj_y=adj_y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatMul", x=x, y=y, adj_x=adj_x, adj_y=adj_y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "adj_x", + _op._get_attr_bool("adj_x"), "adj_y", + _op._get_attr_bool("adj_y")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatMul = tf_export("raw_ops.BatchMatMul")(_ops.to_raw_op(batch_mat_mul)) + + +def batch_mat_mul_eager_fallback(x: Annotated[Any, TV_BatchMatMul_T], y: Annotated[Any, TV_BatchMatMul_T], adj_x: bool, adj_y: bool, name, ctx) -> Annotated[Any, TV_BatchMatMul_T]: + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "adj_x", adj_x, "adj_y", adj_y) + _result = _execute.execute(b"BatchMatMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatMulV2_T = TypeVar("TV_BatchMatMulV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def batch_mat_mul_v2(x: Annotated[Any, TV_BatchMatMulV2_T], y: Annotated[Any, TV_BatchMatMulV2_T], adj_x:bool=False, adj_y:bool=False, name=None) -> Annotated[Any, TV_BatchMatMulV2_T]: + r"""Multiplies slices of two tensors in batches. + + Multiplies all slices of `Tensor` `x` and `y` (each slice can be + viewed as an element of a batch), and arranges the individual results + in a single output tensor of the same batch size. Each of the + individual slices can optionally be adjointed (to adjoint a matrix + means to transpose and conjugate it) before multiplication by setting + the `adj_x` or `adj_y` flag to `True`, which are by default `False`. + + The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` + and `[..., r_y, c_y]`. + + The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: + + r_o = c_x if adj_x else r_x + c_o = r_y if adj_y else c_y + + It is computed as: + + output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) + + *NOTE*: `BatchMatMulV2` supports broadcasting in the batch dimensions. More + about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`. + 2-D or higher with shape `[..., r_x, c_x]`. + y: A `Tensor`. Must have the same type as `x`. + 2-D or higher with shape `[..., r_y, c_y]`. + adj_x: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `x`. Defaults to `False`. + adj_y: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `y`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatMulV2", name, x, y, "adj_x", adj_x, "adj_y", adj_y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_mat_mul_v2_eager_fallback( + x, y, adj_x=adj_x, adj_y=adj_y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatMulV2", x=x, y=y, adj_x=adj_x, adj_y=adj_y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "adj_x", + _op._get_attr_bool("adj_x"), "adj_y", + _op._get_attr_bool("adj_y")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatMulV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatMulV2 = tf_export("raw_ops.BatchMatMulV2")(_ops.to_raw_op(batch_mat_mul_v2)) + + +def batch_mat_mul_v2_eager_fallback(x: Annotated[Any, TV_BatchMatMulV2_T], y: Annotated[Any, TV_BatchMatMulV2_T], adj_x: bool, adj_y: bool, name, ctx) -> Annotated[Any, TV_BatchMatMulV2_T]: + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "adj_x", adj_x, "adj_y", adj_y) + _result = _execute.execute(b"BatchMatMulV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatMulV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchMatMulV3_Ta = TypeVar("TV_BatchMatMulV3_Ta", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) +TV_BatchMatMulV3_Tb = TypeVar("TV_BatchMatMulV3_Tb", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt8) +TV_BatchMatMulV3_Tout = TypeVar("TV_BatchMatMulV3_Tout", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64) + +def batch_mat_mul_v3(x: Annotated[Any, TV_BatchMatMulV3_Ta], y: Annotated[Any, TV_BatchMatMulV3_Tb], Tout: TV_BatchMatMulV3_Tout, adj_x:bool=False, adj_y:bool=False, name=None) -> Annotated[Any, TV_BatchMatMulV3_Tout]: + r"""Multiplies slices of two tensors in batches. + + Multiplies all slices of `Tensor` `x` and `y` (each slice can be + viewed as an element of a batch), and arranges the individual results + in a single output tensor of the same batch size. Each of the + individual slices can optionally be adjointed (to adjoint a matrix + means to transpose and conjugate it) before multiplication by setting + the `adj_x` or `adj_y` flag to `True`, which are by default `False`. + + The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` + and `[..., r_y, c_y]`. + + The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: + + r_o = c_x if adj_x else r_x + c_o = r_y if adj_y else c_y + + It is computed as: + + output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) + + *NOTE*: `BatchMatMulV3` supports broadcasting in the batch dimensions. More + about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + 2-D or higher with shape `[..., r_x, c_x]`. + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + 2-D or higher with shape `[..., r_y, c_y]`. + Tout: A `tf.DType` from: `tf.bfloat16, tf.half, tf.float32, tf.float64, tf.int16, tf.int32, tf.int64, tf.complex64, tf.complex128`. + If not spcified, Tout is the same type to input type. + adj_x: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `x`. Defaults to `False`. + adj_y: An optional `bool`. Defaults to `False`. + If `True`, adjoint the slices of `y`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchMatMulV3", name, x, y, "Tout", Tout, "adj_x", adj_x, + "adj_y", adj_y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_mat_mul_v3_eager_fallback( + x, y, Tout=Tout, adj_x=adj_x, adj_y=adj_y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchMatMulV3", x=x, y=y, Tout=Tout, adj_x=adj_x, adj_y=adj_y, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Ta", _op._get_attr_type("Ta"), "Tb", _op._get_attr_type("Tb"), + "Tout", _op._get_attr_type("Tout"), "adj_x", + _op._get_attr_bool("adj_x"), "adj_y", + _op._get_attr_bool("adj_y")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchMatMulV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchMatMulV3 = tf_export("raw_ops.BatchMatMulV3")(_ops.to_raw_op(batch_mat_mul_v3)) + + +def batch_mat_mul_v3_eager_fallback(x: Annotated[Any, TV_BatchMatMulV3_Ta], y: Annotated[Any, TV_BatchMatMulV3_Tb], Tout: TV_BatchMatMulV3_Tout, adj_x: bool, adj_y: bool, name, ctx) -> Annotated[Any, TV_BatchMatMulV3_Tout]: + Tout = _execute.make_type(Tout, "Tout") + if adj_x is None: + adj_x = False + adj_x = _execute.make_bool(adj_x, "adj_x") + if adj_y is None: + adj_y = False + adj_y = _execute.make_bool(adj_y, "adj_y") + _attr_Ta, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _attr_Tb, (y,) = _execute.args_to_matching_eager([y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x, y] + _attrs = ("Ta", _attr_Ta, "Tb", _attr_Tb, "Tout", Tout, "adj_x", adj_x, + "adj_y", adj_y) + _result = _execute.execute(b"BatchMatMulV3", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchMatMulV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Betainc_T = TypeVar("TV_Betainc_T", _atypes.Float32, _atypes.Float64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.betainc', v1=['math.betainc', 'betainc']) +@deprecated_endpoints('betainc') +def betainc(a: Annotated[Any, TV_Betainc_T], b: Annotated[Any, TV_Betainc_T], x: Annotated[Any, TV_Betainc_T], name=None) -> Annotated[Any, TV_Betainc_T]: + r"""Compute the regularized incomplete beta integral \\(I_x(a, b)\\). + + The regularized incomplete beta integral is defined as: + + + \\(I_x(a, b) = \frac{B(x; a, b)}{B(a, b)}\\) + + where + + + \\(B(x; a, b) = \int_0^x t^{a-1} (1 - t)^{b-1} dt\\) + + + is the incomplete beta function and \\(B(a, b)\\) is the *complete* + beta function. + + Args: + a: A `Tensor`. Must be one of the following types: `float32`, `float64`. + b: A `Tensor`. Must have the same type as `a`. + x: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Betainc", name, a, b, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_betainc( + (a, b, x, name,), None) + if _result is not NotImplemented: + return _result + return betainc_eager_fallback( + a, b, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + betainc, (), dict(a=a, b=b, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_betainc( + (a, b, x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Betainc", a=a, b=b, x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + betainc, (), dict(a=a, b=b, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Betainc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Betainc = tf_export("raw_ops.Betainc")(_ops.to_raw_op(betainc)) +_dispatcher_for_betainc = betainc._tf_type_based_dispatcher.Dispatch + + +def betainc_eager_fallback(a: Annotated[Any, TV_Betainc_T], b: Annotated[Any, TV_Betainc_T], x: Annotated[Any, TV_Betainc_T], name, ctx) -> Annotated[Any, TV_Betainc_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b, x], ctx, [_dtypes.float32, _dtypes.float64, ]) + (a, b, x) = _inputs_T + _inputs_flat = [a, b, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Betainc", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Betainc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Bincount_T = TypeVar("TV_Bincount_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def bincount(arr: Annotated[Any, _atypes.Int32], size: Annotated[Any, _atypes.Int32], weights: Annotated[Any, TV_Bincount_T], name=None) -> Annotated[Any, TV_Bincount_T]: + r"""Counts the number of occurrences of each value in an integer array. + + Outputs a vector with length `size` and the same dtype as `weights`. If + `weights` are empty, then index `i` stores the number of times the value `i` is + counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of + the value in `weights` at each index where the corresponding value in `arr` is + `i`. + + Values in `arr` outside of the range [0, size) are ignored. + + Args: + arr: A `Tensor` of type `int32`. int32 `Tensor`. + size: A `Tensor` of type `int32`. non-negative int32 scalar `Tensor`. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + is an int32, int64, float32, or float64 `Tensor` with the same + shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights + equal to 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Bincount", name, arr, size, weights) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bincount_eager_fallback( + arr, size, weights, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Bincount", arr=arr, size=size, weights=weights, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Bincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Bincount = tf_export("raw_ops.Bincount")(_ops.to_raw_op(bincount)) + + +def bincount_eager_fallback(arr: Annotated[Any, _atypes.Int32], size: Annotated[Any, _atypes.Int32], weights: Annotated[Any, TV_Bincount_T], name, ctx) -> Annotated[Any, TV_Bincount_T]: + _attr_T, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + arr = _ops.convert_to_tensor(arr, _dtypes.int32) + size = _ops.convert_to_tensor(size, _dtypes.int32) + _inputs_flat = [arr, size, weights] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Bincount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Bincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Bucketize_T = TypeVar("TV_Bucketize_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def bucketize(input: Annotated[Any, TV_Bucketize_T], boundaries, name=None) -> Annotated[Any, _atypes.Int32]: + r"""Bucketizes 'input' based on 'boundaries'. + + For example, if the inputs are + boundaries = [0, 10, 100] + input = [[-5, 10000] + [150, 10] + [5, 100]] + + then the output will be + output = [[0, 3] + [3, 2] + [1, 3]] + + Args: + input: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + Any shape of Tensor contains with int or float type. + boundaries: A list of `floats`. + A sorted list of floats gives the boundary of the buckets. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Bucketize", name, input, "boundaries", boundaries) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bucketize_eager_fallback( + input, boundaries=boundaries, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'boundaries' argument to " + "'bucketize' Op, not %r." % boundaries) + boundaries = [_execute.make_float(_f, "boundaries") for _f in boundaries] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Bucketize", input=input, boundaries=boundaries, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "boundaries", + _op.get_attr("boundaries")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Bucketize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Bucketize = tf_export("raw_ops.Bucketize")(_ops.to_raw_op(bucketize)) + + +def bucketize_eager_fallback(input: Annotated[Any, TV_Bucketize_T], boundaries, name, ctx) -> Annotated[Any, _atypes.Int32]: + if not isinstance(boundaries, (list, tuple)): + raise TypeError( + "Expected list for 'boundaries' argument to " + "'bucketize' Op, not %r." % boundaries) + boundaries = [_execute.make_float(_f, "boundaries") for _f in boundaries] + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "boundaries", boundaries) + _result = _execute.execute(b"Bucketize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Bucketize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cast_SrcT = TypeVar("TV_Cast_SrcT", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_Cast_DstT = TypeVar("TV_Cast_DstT", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def cast(x: Annotated[Any, TV_Cast_SrcT], DstT: TV_Cast_DstT, Truncate:bool=False, name=None) -> Annotated[Any, TV_Cast_DstT]: + r"""Cast x of type SrcT to y of DstT. + + Args: + x: A `Tensor`. + DstT: A `tf.DType`. + Truncate: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `DstT`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cast", name, x, "DstT", DstT, "Truncate", Truncate) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cast_eager_fallback( + x, DstT=DstT, Truncate=Truncate, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + DstT = _execute.make_type(DstT, "DstT") + if Truncate is None: + Truncate = False + Truncate = _execute.make_bool(Truncate, "Truncate") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cast", x=x, DstT=DstT, Truncate=Truncate, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("SrcT", _op._get_attr_type("SrcT"), "DstT", + _op._get_attr_type("DstT"), "Truncate", + _op._get_attr_bool("Truncate")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cast = tf_export("raw_ops.Cast")(_ops.to_raw_op(cast)) + + +def cast_eager_fallback(x: Annotated[Any, TV_Cast_SrcT], DstT: TV_Cast_DstT, Truncate: bool, name, ctx) -> Annotated[Any, TV_Cast_DstT]: + DstT = _execute.make_type(DstT, "DstT") + if Truncate is None: + Truncate = False + Truncate = _execute.make_bool(Truncate, "Truncate") + _attr_SrcT, (x,) = _execute.args_to_matching_eager([x], ctx, []) + _inputs_flat = [x] + _attrs = ("SrcT", _attr_SrcT, "DstT", DstT, "Truncate", Truncate) + _result = _execute.execute(b"Cast", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Ceil_T = TypeVar("TV_Ceil_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def ceil(x: Annotated[Any, TV_Ceil_T], name=None) -> Annotated[Any, TV_Ceil_T]: + r"""Returns element-wise smallest integer not less than x. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Ceil", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ceil_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Ceil", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Ceil", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Ceil = tf_export("raw_ops.Ceil")(_ops.to_raw_op(ceil)) + + +def ceil_eager_fallback(x: Annotated[Any, TV_Ceil_T], name, ctx) -> Annotated[Any, TV_Ceil_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Ceil", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Ceil", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ClipByValue_T = TypeVar("TV_ClipByValue_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def _clip_by_value(t: Annotated[Any, TV_ClipByValue_T], clip_value_min: Annotated[Any, TV_ClipByValue_T], clip_value_max: Annotated[Any, TV_ClipByValue_T], name=None) -> Annotated[Any, TV_ClipByValue_T]: + r"""Clips tensor values to a specified min and max. + + Given a tensor `t`, this operation returns a tensor of the same type and + shape as `t` with its values clipped to `clip_value_min` and `clip_value_max`. + Any values less than `clip_value_min` are set to `clip_value_min`. Any values + greater than `clip_value_max` are set to `clip_value_max`. + + Args: + t: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A `Tensor`. + clip_value_min: A `Tensor`. Must have the same type as `t`. + A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape + as `t`. The minimum value to clip by. + clip_value_max: A `Tensor`. Must have the same type as `t`. + A 0-D (scalar) `Tensor`, or a `Tensor` with the same shape + as `t`. The maximum value to clip by. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ClipByValue", name, t, clip_value_min, clip_value_max) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _clip_by_value_eager_fallback( + t, clip_value_min, clip_value_max, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ClipByValue", t=t, clip_value_min=clip_value_min, + clip_value_max=clip_value_max, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ClipByValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ClipByValue = tf_export("raw_ops.ClipByValue")(_ops.to_raw_op(_clip_by_value)) + + +def _clip_by_value_eager_fallback(t: Annotated[Any, TV_ClipByValue_T], clip_value_min: Annotated[Any, TV_ClipByValue_T], clip_value_max: Annotated[Any, TV_ClipByValue_T], name, ctx) -> Annotated[Any, TV_ClipByValue_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([t, clip_value_min, clip_value_max], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (t, clip_value_min, clip_value_max) = _inputs_T + _inputs_flat = [t, clip_value_min, clip_value_max] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ClipByValue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ClipByValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Complex_T = TypeVar("TV_Complex_T", _atypes.Float32, _atypes.Float64) +TV_Complex_Tout = TypeVar("TV_Complex_Tout", _atypes.Complex128, _atypes.Complex64) + +def _complex(real: Annotated[Any, TV_Complex_T], imag: Annotated[Any, TV_Complex_T], Tout:TV_Complex_Tout=_dtypes.complex64, name=None) -> Annotated[Any, TV_Complex_Tout]: + r"""Converts two real numbers to a complex number. + + Given a tensor `real` representing the real part of a complex number, and a + tensor `imag` representing the imaginary part of a complex number, this + operation returns complex numbers elementwise of the form \\(a + bj\\), where + *a* represents the `real` part and *b* represents the `imag` part. + + The input tensors `real` and `imag` must have the same shape. + + For example: + + ``` + # tensor 'real' is [2.25, 3.25] + # tensor `imag` is [4.75, 5.75] + tf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]] + ``` + + Args: + real: A `Tensor`. Must be one of the following types: `float32`, `float64`. + imag: A `Tensor`. Must have the same type as `real`. + Tout: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Complex", name, real, imag, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _complex_eager_fallback( + real, imag, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tout is None: + Tout = _dtypes.complex64 + Tout = _execute.make_type(Tout, "Tout") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Complex", real=real, imag=imag, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Complex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Complex = tf_export("raw_ops.Complex")(_ops.to_raw_op(_complex)) + + +def _complex_eager_fallback(real: Annotated[Any, TV_Complex_T], imag: Annotated[Any, TV_Complex_T], Tout: TV_Complex_Tout, name, ctx) -> Annotated[Any, TV_Complex_Tout]: + if Tout is None: + Tout = _dtypes.complex64 + Tout = _execute.make_type(Tout, "Tout") + _attr_T, _inputs_T = _execute.args_to_matching_eager([real, imag], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + (real, imag) = _inputs_T + _inputs_flat = [real, imag] + _attrs = ("T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"Complex", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Complex", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ComplexAbs_T = TypeVar("TV_ComplexAbs_T", _atypes.Complex128, _atypes.Complex64) +TV_ComplexAbs_Tout = TypeVar("TV_ComplexAbs_Tout", _atypes.Float32, _atypes.Float64) + +def complex_abs(x: Annotated[Any, TV_ComplexAbs_T], Tout:TV_ComplexAbs_Tout=_dtypes.float32, name=None) -> Annotated[Any, TV_ComplexAbs_Tout]: + r"""Computes the complex absolute value of a tensor. + + Given a tensor `x` of complex numbers, this operation returns a tensor of type + `float` or `double` that is the absolute value of each element in `x`. All + elements in `x` must be complex numbers of the form \\(a + bj\\). The absolute + value is computed as \\( \sqrt{a^2 + b^2}\\). + + For example: + + >>> x = tf.complex(3.0, 4.0) + >>> print((tf.raw_ops.ComplexAbs(x=x, Tout=tf.dtypes.float32, name=None)).numpy()) + 5.0 + + Args: + x: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ComplexAbs", name, x, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return complex_abs_eager_fallback( + x, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ComplexAbs", x=x, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ComplexAbs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ComplexAbs = tf_export("raw_ops.ComplexAbs")(_ops.to_raw_op(complex_abs)) + + +def complex_abs_eager_fallback(x: Annotated[Any, TV_ComplexAbs_T], Tout: TV_ComplexAbs_Tout, name, ctx) -> Annotated[Any, TV_ComplexAbs_Tout]: + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [x] + _attrs = ("T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"ComplexAbs", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ComplexAbs", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conj_T = TypeVar("TV_Conj_T", _atypes.Complex128, _atypes.Complex64, _atypes.Variant) + +def conj(input: Annotated[Any, TV_Conj_T], name=None) -> Annotated[Any, TV_Conj_T]: + r"""Returns the complex conjugate of a complex number. + + Given a tensor `input` of complex numbers, this operation returns a tensor of + complex numbers that are the complex conjugate of each element in `input`. The + complex numbers in `input` must be of the form \\(a + bj\\), where *a* is the + real part and *b* is the imaginary part. + + The complex conjugate returned by this operation is of the form \\(a - bj\\). + + For example: + + ``` + # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] + tf.conj(input) ==> [-2.25 - 4.75j, 3.25 - 5.75j] + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`, `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conj", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conj_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conj", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conj", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conj = tf_export("raw_ops.Conj")(_ops.to_raw_op(conj)) + + +def conj_eager_fallback(input: Annotated[Any, TV_Conj_T], name, ctx) -> Annotated[Any, TV_Conj_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, _dtypes.variant, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Conj", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conj", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cos_T = TypeVar("TV_Cos_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.cos', 'cos') +def cos(x: Annotated[Any, TV_Cos_T], name=None) -> Annotated[Any, TV_Cos_T]: + r"""Computes cos of x element-wise. + + Given an input tensor, this function computes cosine of every + element in the tensor. Input range is `(-inf, inf)` and + output range is `[-1,1]`. If input lies outside the boundary, `nan` + is returned. + + ```python + x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 200, 10000, float("inf")]) + tf.math.cos(x) ==> [nan -0.91113025 0.87758255 0.5403023 0.36235774 0.48718765 -0.95215535 nan] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cos", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_cos( + (x, name,), None) + if _result is not NotImplemented: + return _result + return cos_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cos, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_cos( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cos", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cos, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cos = tf_export("raw_ops.Cos")(_ops.to_raw_op(cos)) +_dispatcher_for_cos = cos._tf_type_based_dispatcher.Dispatch + + +def cos_eager_fallback(x: Annotated[Any, TV_Cos_T], name, ctx) -> Annotated[Any, TV_Cos_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Cos", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cosh_T = TypeVar("TV_Cosh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.cosh', 'cosh') +def cosh(x: Annotated[Any, TV_Cosh_T], name=None) -> Annotated[Any, TV_Cosh_T]: + r"""Computes hyperbolic cosine of x element-wise. + + Given an input tensor, this function computes hyperbolic cosine of every + element in the tensor. Input range is `[-inf, inf]` and output range + is `[1, inf]`. + + ```python + x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 2, 10, float("inf")]) + tf.math.cosh(x) ==> [inf 4.0515420e+03 1.1276259e+00 1.5430807e+00 1.8106556e+00 3.7621956e+00 1.1013233e+04 inf] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cosh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_cosh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return cosh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cosh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_cosh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cosh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cosh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cosh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cosh = tf_export("raw_ops.Cosh")(_ops.to_raw_op(cosh)) +_dispatcher_for_cosh = cosh._tf_type_based_dispatcher.Dispatch + + +def cosh_eager_fallback(x: Annotated[Any, TV_Cosh_T], name, ctx) -> Annotated[Any, TV_Cosh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Cosh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cosh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cross_T = TypeVar("TV_Cross_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('linalg.cross', v1=['linalg.cross', 'cross']) +@deprecated_endpoints('cross') +def cross(a: Annotated[Any, TV_Cross_T], b: Annotated[Any, TV_Cross_T], name=None) -> Annotated[Any, TV_Cross_T]: + r"""Compute the pairwise cross product. + + `a` and `b` must be the same shape; they can either be simple 3-element vectors, + or any shape where the innermost dimension is 3. In the latter case, each pair + of corresponding 3-element vectors is cross-multiplied independently. + + Args: + a: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + A tensor containing 3-element vectors. + b: A `Tensor`. Must have the same type as `a`. + Another tensor, of same type and shape as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cross", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_cross( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return cross_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cross, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_cross( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cross", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + cross, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cross", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cross = tf_export("raw_ops.Cross")(_ops.to_raw_op(cross)) +_dispatcher_for_cross = cross._tf_type_based_dispatcher.Dispatch + + +def cross_eager_fallback(a: Annotated[Any, TV_Cross_T], b: Annotated[Any, TV_Cross_T], name, ctx) -> Annotated[Any, TV_Cross_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (a, b) = _inputs_T + _inputs_flat = [a, b] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Cross", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cross", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cumprod_T = TypeVar("TV_Cumprod_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Cumprod_Tidx = TypeVar("TV_Cumprod_Tidx", _atypes.Int32, _atypes.Int64) + +def cumprod(x: Annotated[Any, TV_Cumprod_T], axis: Annotated[Any, TV_Cumprod_Tidx], exclusive:bool=False, reverse:bool=False, name=None) -> Annotated[Any, TV_Cumprod_T]: + r"""Compute the cumulative product of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumprod, which means that the first + element of the input is identical to the first element of the output: + + ```python + tf.cumprod([a, b, c]) # => [a, a * b, a * b * c] + ``` + + By setting the `exclusive` kwarg to `True`, an exclusive cumprod is + performed instead: + + ```python + tf.cumprod([a, b, c], exclusive=True) # => [1, a, a * b] + ``` + + By setting the `reverse` kwarg to `True`, the cumprod is performed in the + opposite direction: + + ```python + tf.cumprod([a, b, c], reverse=True) # => [a * b * c, b * c, c] + ``` + + This is more efficient than using separate `tf.reverse` ops. + + The `reverse` and `exclusive` kwargs can also be combined: + + ```python + tf.cumprod([a, b, c], exclusive=True, reverse=True) # => [b * c, c, 1] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, + `complex128`, `qint8`, `quint8`, `qint32`, `half`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `Tensor` of type `int32` (default: 0). Must be in the range + `[-rank(x), rank(x))`. + exclusive: An optional `bool`. Defaults to `False`. + If `True`, perform exclusive cumprod. + reverse: An optional `bool`. Defaults to `False`. + A `bool` (default: False). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cumprod", name, x, axis, "exclusive", exclusive, "reverse", + reverse) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cumprod_eager_fallback( + x, axis, exclusive=exclusive, reverse=reverse, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cumprod", x=x, axis=axis, exclusive=exclusive, reverse=reverse, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("exclusive", _op._get_attr_bool("exclusive"), "reverse", + _op._get_attr_bool("reverse"), "T", _op._get_attr_type("T"), + "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cumprod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cumprod = tf_export("raw_ops.Cumprod")(_ops.to_raw_op(cumprod)) + + +def cumprod_eager_fallback(x: Annotated[Any, TV_Cumprod_T], axis: Annotated[Any, TV_Cumprod_Tidx], exclusive: bool, reverse: bool, name, ctx) -> Annotated[Any, TV_Cumprod_T]: + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x, axis] + _attrs = ("exclusive", exclusive, "reverse", reverse, "T", _attr_T, "Tidx", + _attr_Tidx) + _result = _execute.execute(b"Cumprod", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cumprod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Cumsum_T = TypeVar("TV_Cumsum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Cumsum_Tidx = TypeVar("TV_Cumsum_Tidx", _atypes.Int32, _atypes.Int64) + +def cumsum(x: Annotated[Any, TV_Cumsum_T], axis: Annotated[Any, TV_Cumsum_Tidx], exclusive:bool=False, reverse:bool=False, name=None) -> Annotated[Any, TV_Cumsum_T]: + r"""Compute the cumulative sum of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumsum, which means that the first + element of the input is identical to the first element of the output: + + ```python + tf.cumsum([a, b, c]) # => [a, a + b, a + b + c] + ``` + + By setting the `exclusive` kwarg to `True`, an exclusive cumsum is + performed instead: + + ```python + tf.cumsum([a, b, c], exclusive=True) # => [0, a, a + b] + ``` + + By setting the `reverse` kwarg to `True`, the cumsum is performed in the + opposite direction: + + ```python + tf.cumsum([a, b, c], reverse=True) # => [a + b + c, b + c, c] + ``` + + This is more efficient than using separate `tf.reverse` ops. + + The `reverse` and `exclusive` kwargs can also be combined: + + ```python + tf.cumsum([a, b, c], exclusive=True, reverse=True) # => [b + c, c, 0] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, + `complex128`, `qint8`, `quint8`, `qint32`, `half`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `Tensor` of type `int32` (default: 0). Must be in the range + `[-rank(x), rank(x))`. + exclusive: An optional `bool`. Defaults to `False`. + If `True`, perform exclusive cumsum. + reverse: An optional `bool`. Defaults to `False`. + A `bool` (default: False). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Cumsum", name, x, axis, "exclusive", exclusive, "reverse", + reverse) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cumsum_eager_fallback( + x, axis, exclusive=exclusive, reverse=reverse, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Cumsum", x=x, axis=axis, exclusive=exclusive, reverse=reverse, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("exclusive", _op._get_attr_bool("exclusive"), "reverse", + _op._get_attr_bool("reverse"), "T", _op._get_attr_type("T"), + "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Cumsum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Cumsum = tf_export("raw_ops.Cumsum")(_ops.to_raw_op(cumsum)) + + +def cumsum_eager_fallback(x: Annotated[Any, TV_Cumsum_T], axis: Annotated[Any, TV_Cumsum_Tidx], exclusive: bool, reverse: bool, name, ctx) -> Annotated[Any, TV_Cumsum_T]: + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x, axis] + _attrs = ("exclusive", exclusive, "reverse", reverse, "T", _attr_T, "Tidx", + _attr_Tidx) + _result = _execute.execute(b"Cumsum", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Cumsum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_CumulativeLogsumexp_T = TypeVar("TV_CumulativeLogsumexp_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_CumulativeLogsumexp_Tidx = TypeVar("TV_CumulativeLogsumexp_Tidx", _atypes.Int32, _atypes.Int64) + +def cumulative_logsumexp(x: Annotated[Any, TV_CumulativeLogsumexp_T], axis: Annotated[Any, TV_CumulativeLogsumexp_Tidx], exclusive:bool=False, reverse:bool=False, name=None) -> Annotated[Any, TV_CumulativeLogsumexp_T]: + r"""Compute the cumulative product of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumulative log-sum-exp, + which means that the first + element of the input is identical to the first element of the output: + ```python + tf.math.cumulative_logsumexp([a, b, c]) # => [a, log(exp(a) + exp(b)), log(exp(a) + exp(b) + exp(c))] + ``` + + By setting the `exclusive` kwarg to `True`, an exclusive cumulative log-sum-exp is + performed instead: + ```python + tf.cumulative_logsumexp([a, b, c], exclusive=True) # => [-inf, a, log(exp(a) * exp(b))] + ``` + Note that the neutral element of the log-sum-exp operation is `-inf`, + however, for performance reasons, the minimal value representable by the + floating point type is used instead. + + By setting the `reverse` kwarg to `True`, the cumulative log-sum-exp is performed in the + opposite direction. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + A `Tensor`. Must be one of the following types: `float16`, `float32`, `float64`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `Tensor` of type `int32` (default: 0). Must be in the range + `[-rank(x), rank(x))`. + exclusive: An optional `bool`. Defaults to `False`. + If `True`, perform exclusive cumulative log-sum-exp. + reverse: An optional `bool`. Defaults to `False`. + A `bool` (default: False). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CumulativeLogsumexp", name, x, axis, "exclusive", exclusive, + "reverse", reverse) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cumulative_logsumexp_eager_fallback( + x, axis, exclusive=exclusive, reverse=reverse, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CumulativeLogsumexp", x=x, axis=axis, exclusive=exclusive, + reverse=reverse, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("exclusive", _op._get_attr_bool("exclusive"), "reverse", + _op._get_attr_bool("reverse"), "T", _op._get_attr_type("T"), + "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CumulativeLogsumexp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CumulativeLogsumexp = tf_export("raw_ops.CumulativeLogsumexp")(_ops.to_raw_op(cumulative_logsumexp)) + + +def cumulative_logsumexp_eager_fallback(x: Annotated[Any, TV_CumulativeLogsumexp_T], axis: Annotated[Any, TV_CumulativeLogsumexp_Tidx], exclusive: bool, reverse: bool, name, ctx) -> Annotated[Any, TV_CumulativeLogsumexp_T]: + if exclusive is None: + exclusive = False + exclusive = _execute.make_bool(exclusive, "exclusive") + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x, axis] + _attrs = ("exclusive", exclusive, "reverse", reverse, "T", _attr_T, "Tidx", + _attr_Tidx) + _result = _execute.execute(b"CumulativeLogsumexp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CumulativeLogsumexp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DenseBincount_Tidx = TypeVar("TV_DenseBincount_Tidx", _atypes.Int32, _atypes.Int64) +TV_DenseBincount_T = TypeVar("TV_DenseBincount_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def dense_bincount(input: Annotated[Any, TV_DenseBincount_Tidx], size: Annotated[Any, TV_DenseBincount_Tidx], weights: Annotated[Any, TV_DenseBincount_T], binary_output:bool=False, name=None) -> Annotated[Any, TV_DenseBincount_T]: + r"""Counts the number of occurrences of each value in an integer array. + + Outputs a vector with length `size` and the same dtype as `weights`. If + `weights` are empty, then index `i` stores the number of times the value `i` is + counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of + the value in `weights` at each index where the corresponding value in `arr` is + `i`. + + Values in `arr` outside of the range [0, size) are ignored. + + Args: + input: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1D or 2D int `Tensor`. + size: A `Tensor`. Must have the same type as `input`. + non-negative int scalar `Tensor`. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + is an int32, int64, float32, or float64 `Tensor` with the same + shape as `arr`, or a length-0 `Tensor`, in which case it acts as all weights + equal to 1. + binary_output: An optional `bool`. Defaults to `False`. + bool; Whether the kernel should count the appearance or number of occurrences. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseBincount", name, input, size, weights, "binary_output", + binary_output) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_bincount_eager_fallback( + input, size, weights, binary_output=binary_output, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseBincount", input=input, size=size, weights=weights, + binary_output=binary_output, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx"), "T", + _op._get_attr_type("T"), "binary_output", + _op._get_attr_bool("binary_output")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DenseBincount = tf_export("raw_ops.DenseBincount")(_ops.to_raw_op(dense_bincount)) + + +def dense_bincount_eager_fallback(input: Annotated[Any, TV_DenseBincount_Tidx], size: Annotated[Any, TV_DenseBincount_Tidx], weights: Annotated[Any, TV_DenseBincount_T], binary_output: bool, name, ctx) -> Annotated[Any, TV_DenseBincount_T]: + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([input, size], ctx, [_dtypes.int32, _dtypes.int64, ]) + (input, size) = _inputs_Tidx + _attr_T, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [input, size, weights] + _attrs = ("Tidx", _attr_Tidx, "T", _attr_T, "binary_output", binary_output) + _result = _execute.execute(b"DenseBincount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Digamma_T = TypeVar("TV_Digamma_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.digamma', v1=['math.digamma', 'digamma']) +@deprecated_endpoints('digamma') +def digamma(x: Annotated[Any, TV_Digamma_T], name=None) -> Annotated[Any, TV_Digamma_T]: + r"""Computes Psi, the derivative of Lgamma (the log of the absolute value of + + `Gamma(x)`), element-wise. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Digamma", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_digamma( + (x, name,), None) + if _result is not NotImplemented: + return _result + return digamma_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + digamma, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_digamma( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Digamma", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + digamma, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Digamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Digamma = tf_export("raw_ops.Digamma")(_ops.to_raw_op(digamma)) +_dispatcher_for_digamma = digamma._tf_type_based_dispatcher.Dispatch + + +def digamma_eager_fallback(x: Annotated[Any, TV_Digamma_T], name, ctx) -> Annotated[Any, TV_Digamma_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Digamma", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Digamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Div_T = TypeVar("TV_Div_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def div(x: Annotated[Any, TV_Div_T], y: Annotated[Any, TV_Div_T], name=None) -> Annotated[Any, TV_Div_T]: + r"""Returns x / y element-wise. + + *NOTE*: `Div` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `uint64`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Div", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return div_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Div", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Div", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Div = tf_export("raw_ops.Div")(_ops.to_raw_op(div)) + + +def div_eager_fallback(x: Annotated[Any, TV_Div_T], y: Annotated[Any, TV_Div_T], name, ctx) -> Annotated[Any, TV_Div_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.uint64, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Div", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Div", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DivNoNan_T = TypeVar("TV_DivNoNan_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def div_no_nan(x: Annotated[Any, TV_DivNoNan_T], y: Annotated[Any, TV_DivNoNan_T], name=None) -> Annotated[Any, TV_DivNoNan_T]: + r"""Returns 0 if the denominator is zero. + + + *NOTE*: `DivNoNan` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `float32`, `bfloat16`, `float64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DivNoNan", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return div_no_nan_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DivNoNan", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DivNoNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DivNoNan = tf_export("raw_ops.DivNoNan")(_ops.to_raw_op(div_no_nan)) + + +def div_no_nan_eager_fallback(x: Annotated[Any, TV_DivNoNan_T], y: Annotated[Any, TV_DivNoNan_T], name, ctx) -> Annotated[Any, TV_DivNoNan_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.half, _dtypes.float32, _dtypes.bfloat16, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DivNoNan", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DivNoNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Equal_T = TypeVar("TV_Equal_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def equal(x: Annotated[Any, TV_Equal_T], y: Annotated[Any, TV_Equal_T], incompatible_shape_error:bool=True, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x == y) element-wise. + + *NOTE*: `Equal` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + ```python + x = tf.constant([2, 4]) + y = tf.constant(2) + tf.math.equal(x, y) ==> array([True, False]) + + x = tf.constant([2, 4]) + y = tf.constant([2, 4]) + tf.math.equal(x, y) ==> array([True, True]) + ``` + + Args: + x: A `Tensor`. + y: A `Tensor`. Must have the same type as `x`. + incompatible_shape_error: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Equal", name, x, y, "incompatible_shape_error", + incompatible_shape_error) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return equal_eager_fallback( + x, y, incompatible_shape_error=incompatible_shape_error, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if incompatible_shape_error is None: + incompatible_shape_error = True + incompatible_shape_error = _execute.make_bool(incompatible_shape_error, "incompatible_shape_error") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Equal", x=x, y=y, incompatible_shape_error=incompatible_shape_error, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "incompatible_shape_error", + _op._get_attr_bool("incompatible_shape_error")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Equal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Equal = tf_export("raw_ops.Equal")(_ops.to_raw_op(equal)) + + +def equal_eager_fallback(x: Annotated[Any, TV_Equal_T], y: Annotated[Any, TV_Equal_T], incompatible_shape_error: bool, name, ctx) -> Annotated[Any, _atypes.Bool]: + if incompatible_shape_error is None: + incompatible_shape_error = True + incompatible_shape_error = _execute.make_bool(incompatible_shape_error, "incompatible_shape_error") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, []) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "incompatible_shape_error", + incompatible_shape_error) + _result = _execute.execute(b"Equal", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Equal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Erf_T = TypeVar("TV_Erf_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.erf', v1=['math.erf', 'erf']) +@deprecated_endpoints('erf') +def erf(x: Annotated[Any, TV_Erf_T], name=None) -> Annotated[Any, TV_Erf_T]: + r"""Computes the [Gauss error function](https://en.wikipedia.org/wiki/Error_function) of `x` element-wise. In statistics, for non-negative values of $x$, the error function has the following interpretation: for a random variable $Y$ that is normally distributed with mean 0 and variance $1/\sqrt{2}$, $erf(x)$ is the probability that $Y$ falls in the range $[−x, x]$. + + For example: + + >>> tf.math.erf([[1.0, 2.0, 3.0], [0.0, -1.0, -2.0]]) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Erf", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_erf( + (x, name,), None) + if _result is not NotImplemented: + return _result + return erf_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + erf, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_erf( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Erf", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + erf, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Erf", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Erf = tf_export("raw_ops.Erf")(_ops.to_raw_op(erf)) +_dispatcher_for_erf = erf._tf_type_based_dispatcher.Dispatch + + +def erf_eager_fallback(x: Annotated[Any, TV_Erf_T], name, ctx) -> Annotated[Any, TV_Erf_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Erf", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Erf", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Erfc_T = TypeVar("TV_Erfc_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.erfc', v1=['math.erfc', 'erfc']) +@deprecated_endpoints('erfc') +def erfc(x: Annotated[Any, TV_Erfc_T], name=None) -> Annotated[Any, TV_Erfc_T]: + r"""Computes the complementary error function of `x` element-wise. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Erfc", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_erfc( + (x, name,), None) + if _result is not NotImplemented: + return _result + return erfc_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + erfc, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_erfc( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Erfc", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + erfc, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Erfc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Erfc = tf_export("raw_ops.Erfc")(_ops.to_raw_op(erfc)) +_dispatcher_for_erfc = erfc._tf_type_based_dispatcher.Dispatch + + +def erfc_eager_fallback(x: Annotated[Any, TV_Erfc_T], name, ctx) -> Annotated[Any, TV_Erfc_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Erfc", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Erfc", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Erfinv_T = TypeVar("TV_Erfinv_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def erfinv(x: Annotated[Any, TV_Erfinv_T], name=None) -> Annotated[Any, TV_Erfinv_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Erfinv", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return erfinv_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Erfinv", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Erfinv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Erfinv = tf_export("raw_ops.Erfinv")(_ops.to_raw_op(erfinv)) + + +def erfinv_eager_fallback(x: Annotated[Any, TV_Erfinv_T], name, ctx) -> Annotated[Any, TV_Erfinv_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Erfinv", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Erfinv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_EuclideanNorm_T = TypeVar("TV_EuclideanNorm_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_EuclideanNorm_Tidx = TypeVar("TV_EuclideanNorm_Tidx", _atypes.Int32, _atypes.Int64) + +def euclidean_norm(input: Annotated[Any, TV_EuclideanNorm_T], axis: Annotated[Any, TV_EuclideanNorm_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_EuclideanNorm_T]: + r"""Computes the euclidean norm of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EuclideanNorm", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return euclidean_norm_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EuclideanNorm", input=input, reduction_indices=axis, + keep_dims=keep_dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EuclideanNorm", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EuclideanNorm = tf_export("raw_ops.EuclideanNorm")(_ops.to_raw_op(euclidean_norm)) + + +def euclidean_norm_eager_fallback(input: Annotated[Any, TV_EuclideanNorm_T], axis: Annotated[Any, TV_EuclideanNorm_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_EuclideanNorm_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"EuclideanNorm", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EuclideanNorm", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Exp_T = TypeVar("TV_Exp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def exp(x: Annotated[Any, TV_Exp_T], name=None) -> Annotated[Any, TV_Exp_T]: + r"""Computes exponential of x element-wise. \\(y = e^x\\). + + This function computes the exponential of every element in the input tensor. + i.e. `exp(x)` or `e^(x)`, where `x` is the input tensor. + `e` denotes Euler's number and is approximately equal to 2.718281. + Output is positive for any real input. + + ```python + x = tf.constant(2.0) + tf.math.exp(x) ==> 7.389056 + + x = tf.constant([2.0, 8.0]) + tf.math.exp(x) ==> array([7.389056, 2980.958], dtype=float32) + ``` + + For complex numbers, the exponential value is calculated as follows: + + ``` + e^(x+iy) = e^x * e^iy = e^x * (cos y + i sin y) + ``` + + Let's consider complex number 1+1j as an example. + e^1 * (cos 1 + i sin 1) = 2.7182818284590 * (0.54030230586+0.8414709848j) + + ```python + x = tf.constant(1 + 1j) + tf.math.exp(x) ==> 1.4686939399158851+2.2873552871788423j + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Exp", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return exp_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Exp", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Exp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Exp = tf_export("raw_ops.Exp")(_ops.to_raw_op(exp)) + + +def exp_eager_fallback(x: Annotated[Any, TV_Exp_T], name, ctx) -> Annotated[Any, TV_Exp_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Exp", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Exp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Expm1_T = TypeVar("TV_Expm1_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.expm1', v1=['math.expm1', 'expm1']) +@deprecated_endpoints('expm1') +def expm1(x: Annotated[Any, TV_Expm1_T], name=None) -> Annotated[Any, TV_Expm1_T]: + r"""Computes `exp(x) - 1` element-wise. + + i.e. `exp(x) - 1` or `e^(x) - 1`, where `x` is the input tensor. + `e` denotes Euler's number and is approximately equal to 2.718281. + + ```python + x = tf.constant(2.0) + tf.math.expm1(x) ==> 6.389056 + + x = tf.constant([2.0, 8.0]) + tf.math.expm1(x) ==> array([6.389056, 2979.958], dtype=float32) + + x = tf.constant(1 + 1j) + tf.math.expm1(x) ==> (0.46869393991588515+2.2873552871788423j) + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Expm1", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_expm1( + (x, name,), None) + if _result is not NotImplemented: + return _result + return expm1_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + expm1, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_expm1( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Expm1", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + expm1, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Expm1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Expm1 = tf_export("raw_ops.Expm1")(_ops.to_raw_op(expm1)) +_dispatcher_for_expm1 = expm1._tf_type_based_dispatcher.Dispatch + + +def expm1_eager_fallback(x: Annotated[Any, TV_Expm1_T], name, ctx) -> Annotated[Any, TV_Expm1_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Expm1", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Expm1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Floor_T = TypeVar("TV_Floor_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def floor(x: Annotated[Any, TV_Floor_T], name=None) -> Annotated[Any, TV_Floor_T]: + r"""Returns element-wise largest integer not greater than x. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Floor", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return floor_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Floor", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Floor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Floor = tf_export("raw_ops.Floor")(_ops.to_raw_op(floor)) + + +def floor_eager_fallback(x: Annotated[Any, TV_Floor_T], name, ctx) -> Annotated[Any, TV_Floor_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Floor", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Floor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FloorDiv_T = TypeVar("TV_FloorDiv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['floor_div']) +@deprecated_endpoints('floor_div') +def floor_div(x: Annotated[Any, TV_FloorDiv_T], y: Annotated[Any, TV_FloorDiv_T], name=None) -> Annotated[Any, TV_FloorDiv_T]: + r"""Returns x // y element-wise. + + *NOTE*: `floor_div` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `uint64`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FloorDiv", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_floor_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return floor_div_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + floor_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_floor_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FloorDiv", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + floor_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FloorDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FloorDiv = tf_export("raw_ops.FloorDiv")(_ops.to_raw_op(floor_div)) +_dispatcher_for_floor_div = floor_div._tf_type_based_dispatcher.Dispatch + + +def floor_div_eager_fallback(x: Annotated[Any, TV_FloorDiv_T], y: Annotated[Any, TV_FloorDiv_T], name, ctx) -> Annotated[Any, TV_FloorDiv_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.uint64, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"FloorDiv", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FloorDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FloorMod_T = TypeVar("TV_FloorMod_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.floormod', 'math.mod', v1=['math.floormod', 'floormod', 'math.mod', 'mod']) +@deprecated_endpoints('floormod', 'mod') +def floor_mod(x: Annotated[Any, TV_FloorMod_T], y: Annotated[Any, TV_FloorMod_T], name=None) -> Annotated[Any, TV_FloorMod_T]: + r"""Returns element-wise remainder of division. + + This follows Python semantics in that the + result here is consistent with a flooring divide. E.g. + `floor(x / y) * y + floormod(x, y) = x`, regardless of the signs of x and y. + + *NOTE*: `math.floormod` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `bfloat16`, `half`, `float32`, `float64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FloorMod", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_floor_mod( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return floor_mod_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + floor_mod, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_floor_mod( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FloorMod", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + floor_mod, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FloorMod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FloorMod = tf_export("raw_ops.FloorMod")(_ops.to_raw_op(floor_mod)) +_dispatcher_for_floor_mod = floor_mod._tf_type_based_dispatcher.Dispatch + + +def floor_mod_eager_fallback(x: Annotated[Any, TV_FloorMod_T], y: Annotated[Any, TV_FloorMod_T], name, ctx) -> Annotated[Any, TV_FloorMod_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"FloorMod", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FloorMod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Greater_T = TypeVar("TV_Greater_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.greater', 'greater') +def greater(x: Annotated[Any, TV_Greater_T], y: Annotated[Any, TV_Greater_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x > y) element-wise. + + *NOTE*: `math.greater` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Example: + + ```python + x = tf.constant([5, 4, 6]) + y = tf.constant([5, 2, 5]) + tf.math.greater(x, y) ==> [False, True, True] + + x = tf.constant([5, 4, 6]) + y = tf.constant([5]) + tf.math.greater(x, y) ==> [False, False, True] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Greater", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_greater( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return greater_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + greater, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_greater( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Greater", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + greater, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Greater", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Greater = tf_export("raw_ops.Greater")(_ops.to_raw_op(greater)) +_dispatcher_for_greater = greater._tf_type_based_dispatcher.Dispatch + + +def greater_eager_fallback(x: Annotated[Any, TV_Greater_T], y: Annotated[Any, TV_Greater_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Greater", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Greater", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_GreaterEqual_T = TypeVar("TV_GreaterEqual_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.greater_equal', 'greater_equal') +def greater_equal(x: Annotated[Any, TV_GreaterEqual_T], y: Annotated[Any, TV_GreaterEqual_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x >= y) element-wise. + + *NOTE*: `math.greater_equal` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Example: + + ```python + x = tf.constant([5, 4, 6, 7]) + y = tf.constant([5, 2, 5, 10]) + tf.math.greater_equal(x, y) ==> [True, True, True, False] + + x = tf.constant([5, 4, 6, 7]) + y = tf.constant([5]) + tf.math.greater_equal(x, y) ==> [True, False, True, True] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GreaterEqual", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_greater_equal( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return greater_equal_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + greater_equal, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_greater_equal( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GreaterEqual", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + greater_equal, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GreaterEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GreaterEqual = tf_export("raw_ops.GreaterEqual")(_ops.to_raw_op(greater_equal)) +_dispatcher_for_greater_equal = greater_equal._tf_type_based_dispatcher.Dispatch + + +def greater_equal_eager_fallback(x: Annotated[Any, TV_GreaterEqual_T], y: Annotated[Any, TV_GreaterEqual_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GreaterEqual", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GreaterEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_HistogramFixedWidth_T = TypeVar("TV_HistogramFixedWidth_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) +TV_HistogramFixedWidth_dtype = TypeVar("TV_HistogramFixedWidth_dtype", _atypes.Int32, _atypes.Int64) + +def _histogram_fixed_width(values: Annotated[Any, TV_HistogramFixedWidth_T], value_range: Annotated[Any, TV_HistogramFixedWidth_T], nbins: Annotated[Any, _atypes.Int32], dtype:TV_HistogramFixedWidth_dtype=_dtypes.int32, name=None) -> Annotated[Any, TV_HistogramFixedWidth_dtype]: + r"""Return histogram of values. + + Given the tensor `values`, this operation returns a rank 1 histogram counting + the number of entries in `values` that fall into every bin. The bins are + equal width and determined by the arguments `value_range` and `nbins`. + + ```python + # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) + nbins = 5 + value_range = [0.0, 5.0] + new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] + + with tf.get_default_session() as sess: + hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) + variables.global_variables_initializer().run() + sess.run(hist) => [2, 1, 1, 0, 2] + ``` + + Args: + values: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + Numeric `Tensor`. + value_range: A `Tensor`. Must have the same type as `values`. + Shape [2] `Tensor` of same `dtype` as `values`. + values <= value_range[0] will be mapped to hist[0], + values >= value_range[1] will be mapped to hist[-1]. + nbins: A `Tensor` of type `int32`. + Scalar `int32 Tensor`. Number of histogram bins. + dtype: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "HistogramFixedWidth", name, values, value_range, nbins, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _histogram_fixed_width_eager_fallback( + values, value_range, nbins, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.int32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "HistogramFixedWidth", values=values, value_range=value_range, + nbins=nbins, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "dtype", + _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "HistogramFixedWidth", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +HistogramFixedWidth = tf_export("raw_ops.HistogramFixedWidth")(_ops.to_raw_op(_histogram_fixed_width)) + + +def _histogram_fixed_width_eager_fallback(values: Annotated[Any, TV_HistogramFixedWidth_T], value_range: Annotated[Any, TV_HistogramFixedWidth_T], nbins: Annotated[Any, _atypes.Int32], dtype: TV_HistogramFixedWidth_dtype, name, ctx) -> Annotated[Any, TV_HistogramFixedWidth_dtype]: + if dtype is None: + dtype = _dtypes.int32 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, _inputs_T = _execute.args_to_matching_eager([values, value_range], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + (values, value_range) = _inputs_T + nbins = _ops.convert_to_tensor(nbins, _dtypes.int32) + _inputs_flat = [values, value_range, nbins] + _attrs = ("T", _attr_T, "dtype", dtype) + _result = _execute.execute(b"HistogramFixedWidth", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "HistogramFixedWidth", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Igamma_T = TypeVar("TV_Igamma_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.igamma', v1=['math.igamma', 'igamma']) +@deprecated_endpoints('igamma') +def igamma(a: Annotated[Any, TV_Igamma_T], x: Annotated[Any, TV_Igamma_T], name=None) -> Annotated[Any, TV_Igamma_T]: + r"""Compute the lower regularized incomplete Gamma function `P(a, x)`. + + The lower regularized incomplete Gamma function is defined as: + + + \\(P(a, x) = gamma(a, x) / Gamma(a) = 1 - Q(a, x)\\) + + where + + \\(gamma(a, x) = \\int_{0}^{x} t^{a-1} exp(-t) dt\\) + + is the lower incomplete Gamma function. + + Note, above `Q(a, x)` (`Igammac`) is the upper regularized complete + Gamma function. + + Args: + a: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + x: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Igamma", name, a, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_igamma( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + return igamma_eager_fallback( + a, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + igamma, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_igamma( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Igamma", a=a, x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + igamma, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Igamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Igamma = tf_export("raw_ops.Igamma")(_ops.to_raw_op(igamma)) +_dispatcher_for_igamma = igamma._tf_type_based_dispatcher.Dispatch + + +def igamma_eager_fallback(a: Annotated[Any, TV_Igamma_T], x: Annotated[Any, TV_Igamma_T], name, ctx) -> Annotated[Any, TV_Igamma_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (a, x) = _inputs_T + _inputs_flat = [a, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Igamma", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Igamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IgammaGradA_T = TypeVar("TV_IgammaGradA_T", _atypes.Float32, _atypes.Float64) + +def igamma_grad_a(a: Annotated[Any, TV_IgammaGradA_T], x: Annotated[Any, TV_IgammaGradA_T], name=None) -> Annotated[Any, TV_IgammaGradA_T]: + r"""Computes the gradient of `igamma(a, x)` wrt `a`. + + Args: + a: A `Tensor`. Must be one of the following types: `float32`, `float64`. + x: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IgammaGradA", name, a, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return igamma_grad_a_eager_fallback( + a, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IgammaGradA", a=a, x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IgammaGradA", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IgammaGradA = tf_export("raw_ops.IgammaGradA")(_ops.to_raw_op(igamma_grad_a)) + + +def igamma_grad_a_eager_fallback(a: Annotated[Any, TV_IgammaGradA_T], x: Annotated[Any, TV_IgammaGradA_T], name, ctx) -> Annotated[Any, TV_IgammaGradA_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], ctx, [_dtypes.float32, _dtypes.float64, ]) + (a, x) = _inputs_T + _inputs_flat = [a, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"IgammaGradA", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IgammaGradA", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Igammac_T = TypeVar("TV_Igammac_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.igammac', v1=['math.igammac', 'igammac']) +@deprecated_endpoints('igammac') +def igammac(a: Annotated[Any, TV_Igammac_T], x: Annotated[Any, TV_Igammac_T], name=None) -> Annotated[Any, TV_Igammac_T]: + r"""Compute the upper regularized incomplete Gamma function `Q(a, x)`. + + The upper regularized incomplete Gamma function is defined as: + + \\(Q(a, x) = Gamma(a, x) / Gamma(a) = 1 - P(a, x)\\) + + where + + \\(Gamma(a, x) = \int_{x}^{\infty} t^{a-1} exp(-t) dt\\) + + is the upper incomplete Gamma function. + + Note, above `P(a, x)` (`Igamma`) is the lower regularized complete + Gamma function. + + Args: + a: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + x: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Igammac", name, a, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_igammac( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + return igammac_eager_fallback( + a, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + igammac, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_igammac( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Igammac", a=a, x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + igammac, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Igammac", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Igammac = tf_export("raw_ops.Igammac")(_ops.to_raw_op(igammac)) +_dispatcher_for_igammac = igammac._tf_type_based_dispatcher.Dispatch + + +def igammac_eager_fallback(a: Annotated[Any, TV_Igammac_T], x: Annotated[Any, TV_Igammac_T], name, ctx) -> Annotated[Any, TV_Igammac_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (a, x) = _inputs_T + _inputs_flat = [a, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Igammac", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Igammac", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Imag_T = TypeVar("TV_Imag_T", _atypes.Complex128, _atypes.Complex64) +TV_Imag_Tout = TypeVar("TV_Imag_Tout", _atypes.Float32, _atypes.Float64) + +def imag(input: Annotated[Any, TV_Imag_T], Tout:TV_Imag_Tout=_dtypes.float32, name=None) -> Annotated[Any, TV_Imag_Tout]: + r"""Returns the imaginary part of a complex number. + + Given a tensor `input` of complex numbers, this operation returns a tensor of + type `float` that is the imaginary part of each element in `input`. All + elements in `input` must be complex numbers of the form \\(a + bj\\), where *a* + is the real part and *b* is the imaginary part returned by this operation. + + For example: + + ``` + # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] + tf.imag(input) ==> [4.75, 5.75] + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Imag", name, input, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return imag_eager_fallback( + input, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Imag", input=input, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Imag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Imag = tf_export("raw_ops.Imag")(_ops.to_raw_op(imag)) + + +def imag_eager_fallback(input: Annotated[Any, TV_Imag_T], Tout: TV_Imag_Tout, name, ctx) -> Annotated[Any, TV_Imag_Tout]: + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"Imag", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Imag", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Inv_T = TypeVar("TV_Inv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def inv(x: Annotated[Any, TV_Inv_T], name=None) -> Annotated[Any, TV_Inv_T]: + r"""Computes the reciprocal of x element-wise. + + I.e., \\(y = 1 / x\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Inv", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return inv_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Inv", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Inv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Inv = tf_export("raw_ops.Inv")(_ops.to_raw_op(inv)) + + +def inv_eager_fallback(x: Annotated[Any, TV_Inv_T], name, ctx) -> Annotated[Any, TV_Inv_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Inv", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Inv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InvGrad_T = TypeVar("TV_InvGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def inv_grad(y: Annotated[Any, TV_InvGrad_T], dy: Annotated[Any, TV_InvGrad_T], name=None) -> Annotated[Any, TV_InvGrad_T]: + r"""Computes the gradient for the inverse of `x` wrt its input. + + Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` + is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InvGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return inv_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InvGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InvGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InvGrad = tf_export("raw_ops.InvGrad")(_ops.to_raw_op(inv_grad)) + + +def inv_grad_eager_fallback(y: Annotated[Any, TV_InvGrad_T], dy: Annotated[Any, TV_InvGrad_T], name, ctx) -> Annotated[Any, TV_InvGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InvGrad", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InvGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IsFinite_T = TypeVar("TV_IsFinite_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.is_finite', v1=['math.is_finite', 'debugging.is_finite', 'is_finite']) +@deprecated_endpoints('debugging.is_finite', 'is_finite') +def is_finite(x: Annotated[Any, TV_IsFinite_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns which elements of x are finite. + + @compatibility(numpy) + Equivalent to np.isfinite + @end_compatibility + + Example: + + ```python + x = tf.constant([5.0, 4.8, 6.8, np.inf, np.nan]) + tf.math.is_finite(x) ==> [True, True, True, False, False] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsFinite", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_is_finite( + (x, name,), None) + if _result is not NotImplemented: + return _result + return is_finite_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_finite, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_is_finite( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsFinite", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_finite, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsFinite", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsFinite = tf_export("raw_ops.IsFinite")(_ops.to_raw_op(is_finite)) +_dispatcher_for_is_finite = is_finite._tf_type_based_dispatcher.Dispatch + + +def is_finite_eager_fallback(x: Annotated[Any, TV_IsFinite_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"IsFinite", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsFinite", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IsInf_T = TypeVar("TV_IsInf_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.is_inf', v1=['math.is_inf', 'debugging.is_inf', 'is_inf']) +@deprecated_endpoints('debugging.is_inf', 'is_inf') +def is_inf(x: Annotated[Any, TV_IsInf_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns which elements of x are Inf. + + @compatibility(numpy) + Equivalent to np.isinf + @end_compatibility + + Example: + + ```python + x = tf.constant([5.0, np.inf, 6.8, np.inf]) + tf.math.is_inf(x) ==> [False, True, False, True] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsInf", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_is_inf( + (x, name,), None) + if _result is not NotImplemented: + return _result + return is_inf_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_inf, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_is_inf( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsInf", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_inf, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsInf", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsInf = tf_export("raw_ops.IsInf")(_ops.to_raw_op(is_inf)) +_dispatcher_for_is_inf = is_inf._tf_type_based_dispatcher.Dispatch + + +def is_inf_eager_fallback(x: Annotated[Any, TV_IsInf_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"IsInf", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsInf", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IsNan_T = TypeVar("TV_IsNan_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.is_nan', v1=['math.is_nan', 'debugging.is_nan', 'is_nan']) +@deprecated_endpoints('debugging.is_nan', 'is_nan') +def is_nan(x: Annotated[Any, TV_IsNan_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns which elements of x are NaN. + + @compatibility(numpy) + Equivalent to np.isnan + @end_compatibility + + Example: + + ```python + x = tf.constant([5.0, np.nan, 6.8, np.nan, np.inf]) + tf.math.is_nan(x) ==> [False, True, False, True, False] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsNan", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_is_nan( + (x, name,), None) + if _result is not NotImplemented: + return _result + return is_nan_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_nan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_is_nan( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsNan", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_nan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsNan = tf_export("raw_ops.IsNan")(_ops.to_raw_op(is_nan)) +_dispatcher_for_is_nan = is_nan._tf_type_based_dispatcher.Dispatch + + +def is_nan_eager_fallback(x: Annotated[Any, TV_IsNan_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"IsNan", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Less_T = TypeVar("TV_Less_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.less', 'less') +def less(x: Annotated[Any, TV_Less_T], y: Annotated[Any, TV_Less_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x < y) element-wise. + + *NOTE*: `math.less` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Example: + + ```python + x = tf.constant([5, 4, 6]) + y = tf.constant([5]) + tf.math.less(x, y) ==> [False, True, False] + + x = tf.constant([5, 4, 6]) + y = tf.constant([5, 6, 7]) + tf.math.less(x, y) ==> [False, True, True] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Less", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_less( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return less_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + less, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_less( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Less", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + less, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Less", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Less = tf_export("raw_ops.Less")(_ops.to_raw_op(less)) +_dispatcher_for_less = less._tf_type_based_dispatcher.Dispatch + + +def less_eager_fallback(x: Annotated[Any, TV_Less_T], y: Annotated[Any, TV_Less_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Less", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Less", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LessEqual_T = TypeVar("TV_LessEqual_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.less_equal', 'less_equal') +def less_equal(x: Annotated[Any, TV_LessEqual_T], y: Annotated[Any, TV_LessEqual_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x <= y) element-wise. + + *NOTE*: `math.less_equal` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Example: + + ```python + x = tf.constant([5, 4, 6]) + y = tf.constant([5]) + tf.math.less_equal(x, y) ==> [True, True, False] + + x = tf.constant([5, 4, 6]) + y = tf.constant([5, 6, 6]) + tf.math.less_equal(x, y) ==> [True, True, True] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LessEqual", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_less_equal( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return less_equal_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + less_equal, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_less_equal( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LessEqual", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + less_equal, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LessEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LessEqual = tf_export("raw_ops.LessEqual")(_ops.to_raw_op(less_equal)) +_dispatcher_for_less_equal = less_equal._tf_type_based_dispatcher.Dispatch + + +def less_equal_eager_fallback(x: Annotated[Any, TV_LessEqual_T], y: Annotated[Any, TV_LessEqual_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"LessEqual", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LessEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Lgamma_T = TypeVar("TV_Lgamma_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.lgamma', v1=['math.lgamma', 'lgamma']) +@deprecated_endpoints('lgamma') +def lgamma(x: Annotated[Any, TV_Lgamma_T], name=None) -> Annotated[Any, TV_Lgamma_T]: + r"""Computes the log of the absolute value of `Gamma(x)` element-wise. + + For positive numbers, this function computes log((input - 1)!) for every element in the tensor. + `lgamma(5) = log((5-1)!) = log(4!) = log(24) = 3.1780539` + + Example: + + ```python + x = tf.constant([0, 0.5, 1, 4.5, -4, -5.6]) + tf.math.lgamma(x) ==> [inf, 0.5723649, 0., 2.4537368, inf, -4.6477685] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Lgamma", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_lgamma( + (x, name,), None) + if _result is not NotImplemented: + return _result + return lgamma_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lgamma, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_lgamma( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Lgamma", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lgamma, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Lgamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Lgamma = tf_export("raw_ops.Lgamma")(_ops.to_raw_op(lgamma)) +_dispatcher_for_lgamma = lgamma._tf_type_based_dispatcher.Dispatch + + +def lgamma_eager_fallback(x: Annotated[Any, TV_Lgamma_T], name, ctx) -> Annotated[Any, TV_Lgamma_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Lgamma", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Lgamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LinSpace_T = TypeVar("TV_LinSpace_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_LinSpace_Tidx = TypeVar("TV_LinSpace_Tidx", _atypes.Int32, _atypes.Int64) + +def lin_space(start: Annotated[Any, TV_LinSpace_T], stop: Annotated[Any, TV_LinSpace_T], num: Annotated[Any, TV_LinSpace_Tidx], name=None) -> Annotated[Any, TV_LinSpace_T]: + r"""Generates values in an interval. + + A sequence of `num` evenly-spaced values are generated beginning at `start`. + If `num > 1`, the values in the sequence increase by + `(stop - start) / (num - 1)`, so that the last one is exactly `stop`. + + For example: + + ``` + tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0] + ``` + + Args: + start: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + 0-D tensor. First entry in the range. + stop: A `Tensor`. Must have the same type as `start`. + 0-D tensor. Last entry in the range. + num: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D tensor. Number of values to generate. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `start`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LinSpace", name, start, stop, num) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lin_space_eager_fallback( + start, stop, num, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LinSpace", start=start, stop=stop, num=num, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LinSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LinSpace = tf_export("raw_ops.LinSpace")(_ops.to_raw_op(lin_space)) + + +def lin_space_eager_fallback(start: Annotated[Any, TV_LinSpace_T], stop: Annotated[Any, TV_LinSpace_T], num: Annotated[Any, TV_LinSpace_Tidx], name, ctx) -> Annotated[Any, TV_LinSpace_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([start, stop], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (start, stop) = _inputs_T + _attr_Tidx, (num,) = _execute.args_to_matching_eager([num], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [start, stop, num] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"LinSpace", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LinSpace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Log_T = TypeVar("TV_Log_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.log', v1=['math.log', 'log']) +@deprecated_endpoints('log') +def log(x: Annotated[Any, TV_Log_T], name=None) -> Annotated[Any, TV_Log_T]: + r"""Computes natural logarithm of x element-wise. + + I.e., \\(y = \log_e x\\). + + Example: + >>> x = tf.constant([0, 0.5, 1, 5]) + >>> tf.math.log(x) + + + See: https://en.wikipedia.org/wiki/Logarithm + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Log", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_log( + (x, name,), None) + if _result is not NotImplemented: + return _result + return log_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + log, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_log( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Log", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + log, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Log", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Log = tf_export("raw_ops.Log")(_ops.to_raw_op(log)) +_dispatcher_for_log = log._tf_type_based_dispatcher.Dispatch + + +def log_eager_fallback(x: Annotated[Any, TV_Log_T], name, ctx) -> Annotated[Any, TV_Log_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Log", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Log", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Log1p_T = TypeVar("TV_Log1p_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.log1p', v1=['math.log1p', 'log1p']) +@deprecated_endpoints('log1p') +def log1p(x: Annotated[Any, TV_Log1p_T], name=None) -> Annotated[Any, TV_Log1p_T]: + r"""Computes natural logarithm of (1 + x) element-wise. + + I.e., \\(y = \log_e (1 + x)\\). + + Example: + >>> x = tf.constant([0, 0.5, 1, 5]) + >>> tf.math.log1p(x) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Log1p", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_log1p( + (x, name,), None) + if _result is not NotImplemented: + return _result + return log1p_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + log1p, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_log1p( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Log1p", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + log1p, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Log1p", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Log1p = tf_export("raw_ops.Log1p")(_ops.to_raw_op(log1p)) +_dispatcher_for_log1p = log1p._tf_type_based_dispatcher.Dispatch + + +def log1p_eager_fallback(x: Annotated[Any, TV_Log1p_T], name, ctx) -> Annotated[Any, TV_Log1p_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Log1p", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Log1p", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.logical_and', 'logical_and') +def logical_and(x: Annotated[Any, _atypes.Bool], y: Annotated[Any, _atypes.Bool], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of x AND y element-wise. + + Logical AND function. + + Requires that `x` and `y` have the same shape or have + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shapes. For example, `x` and `y` can be: + + - Two single elements of type `bool`. + - One `tf.Tensor` of type `bool` and one single `bool`, where the result will + be calculated by applying logical AND with the single element to each + element in the larger Tensor. + - Two `tf.Tensor` objects of type `bool` of the same shape. In this case, + the result will be the element-wise logical AND of the two input tensors. + + You can also use the `&` operator instead. + + Usage: + + >>> a = tf.constant([True]) + >>> b = tf.constant([False]) + >>> tf.math.logical_and(a, b) + + >>> a & b + + + >>> c = tf.constant([True]) + >>> x = tf.constant([False, True, True, False]) + >>> tf.math.logical_and(c, x) + + >>> c & x + + + >>> y = tf.constant([False, False, True, True]) + >>> z = tf.constant([False, True, False, True]) + >>> tf.math.logical_and(y, z) + + >>> y & z + + + This op also supports broadcasting + + >>> tf.logical_and([[True, False]], [[True], [False]]) + + + The reduction version of this elementwise operation is `tf.math.reduce_all`. + + Args: + x: A `tf.Tensor` of type bool. + y: A `tf.Tensor` of type bool. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of type bool with the shape that `x` and `y` broadcast to. + + Args: + x: A `Tensor` of type `bool`. + y: A `Tensor` of type `bool`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogicalAnd", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_logical_and( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return logical_and_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_and, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_logical_and( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogicalAnd", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_and, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogicalAnd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LogicalAnd = tf_export("raw_ops.LogicalAnd")(_ops.to_raw_op(logical_and)) +_dispatcher_for_logical_and = logical_and._tf_type_based_dispatcher.Dispatch + + +def logical_and_eager_fallback(x: Annotated[Any, _atypes.Bool], y: Annotated[Any, _atypes.Bool], name, ctx) -> Annotated[Any, _atypes.Bool]: + x = _ops.convert_to_tensor(x, _dtypes.bool) + y = _ops.convert_to_tensor(y, _dtypes.bool) + _inputs_flat = [x, y] + _attrs = None + _result = _execute.execute(b"LogicalAnd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogicalAnd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.logical_not', 'logical_not') +def logical_not(x: Annotated[Any, _atypes.Bool], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of `NOT x` element-wise. + + Example: + + >>> tf.math.logical_not(tf.constant([True, False])) + + + Args: + x: A `Tensor` of type `bool`. A `Tensor` of type `bool`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogicalNot", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_logical_not( + (x, name,), None) + if _result is not NotImplemented: + return _result + return logical_not_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_not, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_logical_not( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogicalNot", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_not, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogicalNot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LogicalNot = tf_export("raw_ops.LogicalNot")(_ops.to_raw_op(logical_not)) +_dispatcher_for_logical_not = logical_not._tf_type_based_dispatcher.Dispatch + + +def logical_not_eager_fallback(x: Annotated[Any, _atypes.Bool], name, ctx) -> Annotated[Any, _atypes.Bool]: + x = _ops.convert_to_tensor(x, _dtypes.bool) + _inputs_flat = [x] + _attrs = None + _result = _execute.execute(b"LogicalNot", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogicalNot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.logical_or', 'logical_or') +def logical_or(x: Annotated[Any, _atypes.Bool], y: Annotated[Any, _atypes.Bool], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of x OR y element-wise. + + Logical OR function. + + Requires that `x` and `y` have the same shape or have + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shapes. For example, `x` and `y` can be: + + - Two single elements of type `bool`. + - One `tf.Tensor` of type `bool` and one single `bool`, where the result will + be calculated by applying logical OR with the single element to each + element in the larger Tensor. + - Two `tf.Tensor` objects of type `bool` of the same shape. In this case, + the result will be the element-wise logical OR of the two input tensors. + + You can also use the `|` operator instead. + + Usage: + + >>> a = tf.constant([True]) + >>> b = tf.constant([False]) + >>> tf.math.logical_or(a, b) + + >>> a | b + + + >>> c = tf.constant([False]) + >>> x = tf.constant([False, True, True, False]) + >>> tf.math.logical_or(c, x) + + >>> c | x + + + >>> y = tf.constant([False, False, True, True]) + >>> z = tf.constant([False, True, False, True]) + >>> tf.math.logical_or(y, z) + + >>> y | z + + + This op also supports broadcasting + + >>> tf.logical_or([[True, False]], [[True], [False]]) + + + The reduction version of this elementwise operation is `tf.math.reduce_any`. + + Args: + x: A `tf.Tensor` of type bool. + y: A `tf.Tensor` of type bool. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of type bool with the shape that `x` and `y` broadcast to. + + Args: + x: A `Tensor` of type `bool`. + y: A `Tensor` of type `bool`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogicalOr", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_logical_or( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return logical_or_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_or, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_logical_or( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogicalOr", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + logical_or, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogicalOr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LogicalOr = tf_export("raw_ops.LogicalOr")(_ops.to_raw_op(logical_or)) +_dispatcher_for_logical_or = logical_or._tf_type_based_dispatcher.Dispatch + + +def logical_or_eager_fallback(x: Annotated[Any, _atypes.Bool], y: Annotated[Any, _atypes.Bool], name, ctx) -> Annotated[Any, _atypes.Bool]: + x = _ops.convert_to_tensor(x, _dtypes.bool) + y = _ops.convert_to_tensor(y, _dtypes.bool) + _inputs_flat = [x, y] + _attrs = None + _result = _execute.execute(b"LogicalOr", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogicalOr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MatMul_T = TypeVar("TV_MatMul_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def mat_mul(a: Annotated[Any, TV_MatMul_T], b: Annotated[Any, TV_MatMul_T], transpose_a:bool=False, transpose_b:bool=False, name=None) -> Annotated[Any, TV_MatMul_T]: + r"""Multiply the matrix "a" by the matrix "b". + + The inputs must be two-dimensional matrices and the inner dimension of + "a" (after being transposed if transpose_a is true) must match the + outer dimension of "b" (after being transposed if transposed_b is + true). + + *Note*: The default kernel implementation for MatMul on GPUs uses + cublas. + + Args: + a: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`. + b: A `Tensor`. Must have the same type as `a`. + transpose_a: An optional `bool`. Defaults to `False`. + If true, "a" is transposed before multiplication. + transpose_b: An optional `bool`. Defaults to `False`. + If true, "b" is transposed before multiplication. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MatMul", name, a, b, "transpose_a", transpose_a, "transpose_b", + transpose_b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mat_mul_eager_fallback( + a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MatMul", a=a, b=b, transpose_a=transpose_a, transpose_b=transpose_b, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("transpose_a", _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MatMul = tf_export("raw_ops.MatMul")(_ops.to_raw_op(mat_mul)) + + +def mat_mul_eager_fallback(a: Annotated[Any, TV_MatMul_T], b: Annotated[Any, TV_MatMul_T], transpose_a: bool, transpose_b: bool, name, ctx) -> Annotated[Any, TV_MatMul_T]: + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, ]) + (a, b) = _inputs_T + _inputs_flat = [a, b] + _attrs = ("transpose_a", transpose_a, "transpose_b", transpose_b, "T", + _attr_T) + _result = _execute.execute(b"MatMul", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Max_T = TypeVar("TV_Max_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Max_Tidx = TypeVar("TV_Max_Tidx", _atypes.Int32, _atypes.Int64) + +def _max(input: Annotated[Any, TV_Max_T], axis: Annotated[Any, TV_Max_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_Max_T]: + r"""Computes the maximum of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Max", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _max_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Max", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Max", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Max = tf_export("raw_ops.Max")(_ops.to_raw_op(_max)) + + +def _max_eager_fallback(input: Annotated[Any, TV_Max_T], axis: Annotated[Any, TV_Max_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_Max_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Max", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Max", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Maximum_T = TypeVar("TV_Maximum_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.maximum', 'maximum') +def maximum(x: Annotated[Any, TV_Maximum_T], y: Annotated[Any, TV_Maximum_T], name=None) -> Annotated[Any, TV_Maximum_T]: + r"""Returns the max of x and y (i.e. x > y ? x : y) element-wise. + + Example: + + >>> x = tf.constant([0., 0., 0., 0.]) + >>> y = tf.constant([-2., 0., 2., 5.]) + >>> tf.math.maximum(x, y) + + + Note that `maximum` supports [broadcast semantics](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) for `x` and `y`. + + >>> x = tf.constant([-5., 0., 0., 0.]) + >>> y = tf.constant([-3.]) + >>> tf.math.maximum(x, y) + + + The reduction version of this elementwise operation is `tf.math.reduce_max` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Maximum", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_maximum( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return maximum_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + maximum, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_maximum( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Maximum", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + maximum, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Maximum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Maximum = tf_export("raw_ops.Maximum")(_ops.to_raw_op(maximum)) +_dispatcher_for_maximum = maximum._tf_type_based_dispatcher.Dispatch + + +def maximum_eager_fallback(x: Annotated[Any, TV_Maximum_T], y: Annotated[Any, TV_Maximum_T], name, ctx) -> Annotated[Any, TV_Maximum_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Maximum", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Maximum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Mean_T = TypeVar("TV_Mean_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Mean_Tidx = TypeVar("TV_Mean_Tidx", _atypes.Int32, _atypes.Int64) + +def mean(input: Annotated[Any, TV_Mean_T], axis: Annotated[Any, TV_Mean_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_Mean_T]: + r"""Computes the mean of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Mean", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mean_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Mean", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Mean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Mean = tf_export("raw_ops.Mean")(_ops.to_raw_op(mean)) + + +def mean_eager_fallback(input: Annotated[Any, TV_Mean_T], axis: Annotated[Any, TV_Mean_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_Mean_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Mean", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Mean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Min_T = TypeVar("TV_Min_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Min_Tidx = TypeVar("TV_Min_Tidx", _atypes.Int32, _atypes.Int64) + +def _min(input: Annotated[Any, TV_Min_T], axis: Annotated[Any, TV_Min_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_Min_T]: + r"""Computes the minimum of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Min", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _min_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Min", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Min", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Min = tf_export("raw_ops.Min")(_ops.to_raw_op(_min)) + + +def _min_eager_fallback(input: Annotated[Any, TV_Min_T], axis: Annotated[Any, TV_Min_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_Min_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Min", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Min", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Minimum_T = TypeVar("TV_Minimum_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.minimum', 'minimum') +def minimum(x: Annotated[Any, TV_Minimum_T], y: Annotated[Any, TV_Minimum_T], name=None) -> Annotated[Any, TV_Minimum_T]: + r"""Returns the min of x and y (i.e. x < y ? x : y) element-wise. + + Both inputs are number-type tensors (except complex). `minimum` expects that + both tensors have the same `dtype`. + + Examples: + + >>> x = tf.constant([0., 0., 0., 0.]) + >>> y = tf.constant([-5., -2., 0., 3.]) + >>> tf.math.minimum(x, y) + + + Note that `minimum` supports [broadcast semantics](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) for `x` and `y`. + + >>> x = tf.constant([-5., 0., 0., 0.]) + >>> y = tf.constant([-3.]) + >>> tf.math.minimum(x, y) + + + The reduction version of this elementwise operation is `tf.math.reduce_min` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Minimum", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_minimum( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return minimum_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + minimum, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_minimum( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Minimum", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + minimum, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Minimum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Minimum = tf_export("raw_ops.Minimum")(_ops.to_raw_op(minimum)) +_dispatcher_for_minimum = minimum._tf_type_based_dispatcher.Dispatch + + +def minimum_eager_fallback(x: Annotated[Any, TV_Minimum_T], y: Annotated[Any, TV_Minimum_T], name, ctx) -> Annotated[Any, TV_Minimum_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.uint8, _dtypes.int16, _dtypes.uint16, _dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Minimum", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Minimum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Mod_T = TypeVar("TV_Mod_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def mod(x: Annotated[Any, TV_Mod_T], y: Annotated[Any, TV_Mod_T], name=None) -> Annotated[Any, TV_Mod_T]: + r"""Returns element-wise remainder of division. This emulates C semantics in that + + the result here is consistent with a truncating divide. E.g. + `tf.truncatediv(x, y) * y + truncate_mod(x, y) = x`. + + *NOTE*: `Mod` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `int32`, `int64`, `half`, `half`, `bfloat16`, `float32`, `float64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Mod", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mod_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Mod", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Mod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Mod = tf_export("raw_ops.Mod")(_ops.to_raw_op(mod)) + + +def mod_eager_fallback(x: Annotated[Any, TV_Mod_T], y: Annotated[Any, TV_Mod_T], name, ctx) -> Annotated[Any, TV_Mod_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.half, _dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Mod", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Mod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Mul_T = TypeVar("TV_Mul_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def mul(x: Annotated[Any, TV_Mul_T], y: Annotated[Any, TV_Mul_T], name=None) -> Annotated[Any, TV_Mul_T]: + r"""Returns x * y element-wise. + + *NOTE*: `Multiply` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `uint64`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Mul", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mul_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Mul", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Mul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Mul = tf_export("raw_ops.Mul")(_ops.to_raw_op(mul)) + + +def mul_eager_fallback(x: Annotated[Any, TV_Mul_T], y: Annotated[Any, TV_Mul_T], name, ctx) -> Annotated[Any, TV_Mul_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.uint64, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Mul", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Mul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MulNoNan_T = TypeVar("TV_MulNoNan_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def mul_no_nan(x: Annotated[Any, TV_MulNoNan_T], y: Annotated[Any, TV_MulNoNan_T], name=None) -> Annotated[Any, TV_MulNoNan_T]: + r"""Returns x * y element-wise. Returns zero if y is zero, even if x if infinite or NaN. + + *NOTE*: `MulNoNan` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MulNoNan", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mul_no_nan_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MulNoNan", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MulNoNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MulNoNan = tf_export("raw_ops.MulNoNan")(_ops.to_raw_op(mul_no_nan)) + + +def mul_no_nan_eager_fallback(x: Annotated[Any, TV_MulNoNan_T], y: Annotated[Any, TV_MulNoNan_T], name, ctx) -> Annotated[Any, TV_MulNoNan_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"MulNoNan", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MulNoNan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Ndtri_T = TypeVar("TV_Ndtri_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def ndtri(x: Annotated[Any, TV_Ndtri_T], name=None) -> Annotated[Any, TV_Ndtri_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Ndtri", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ndtri_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Ndtri", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Ndtri", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Ndtri = tf_export("raw_ops.Ndtri")(_ops.to_raw_op(ndtri)) + + +def ndtri_eager_fallback(x: Annotated[Any, TV_Ndtri_T], name, ctx) -> Annotated[Any, TV_Ndtri_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Ndtri", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Ndtri", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Neg_T = TypeVar("TV_Neg_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.negative', 'negative') +def neg(x: Annotated[Any, TV_Neg_T], name=None) -> Annotated[Any, TV_Neg_T]: + r"""Computes numerical negative value element-wise. + + I.e., \\(y = -x\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Neg", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_neg( + (x, name,), None) + if _result is not NotImplemented: + return _result + return neg_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + neg, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_neg( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Neg", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + neg, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Neg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Neg = tf_export("raw_ops.Neg")(_ops.to_raw_op(neg)) +_dispatcher_for_neg = neg._tf_type_based_dispatcher.Dispatch + + +def neg_eager_fallback(x: Annotated[Any, TV_Neg_T], name, ctx) -> Annotated[Any, TV_Neg_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Neg", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Neg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NextAfter_T = TypeVar("TV_NextAfter_T", _atypes.Float32, _atypes.Float64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.nextafter') +def next_after(x1: Annotated[Any, TV_NextAfter_T], x2: Annotated[Any, TV_NextAfter_T], name=None) -> Annotated[Any, TV_NextAfter_T]: + r"""Returns the next representable value of `x1` in the direction of `x2`, element-wise. + + This operation returns the same result as the C++ std::nextafter function. + + It can also return a subnormal number. + + @compatibility(cpp) + Equivalent to C++ std::nextafter function. + @end_compatibility + + Args: + x1: A `Tensor`. Must be one of the following types: `float64`, `float32`. + x2: A `Tensor`. Must have the same type as `x1`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x1`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NextAfter", name, x1, x2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_next_after( + (x1, x2, name,), None) + if _result is not NotImplemented: + return _result + return next_after_eager_fallback( + x1, x2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + next_after, (), dict(x1=x1, x2=x2, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_next_after( + (x1, x2, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NextAfter", x1=x1, x2=x2, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + next_after, (), dict(x1=x1, x2=x2, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NextAfter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NextAfter = tf_export("raw_ops.NextAfter")(_ops.to_raw_op(next_after)) +_dispatcher_for_next_after = next_after._tf_type_based_dispatcher.Dispatch + + +def next_after_eager_fallback(x1: Annotated[Any, TV_NextAfter_T], x2: Annotated[Any, TV_NextAfter_T], name, ctx) -> Annotated[Any, TV_NextAfter_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x1, x2], ctx, [_dtypes.float64, _dtypes.float32, ], _dtypes.float32) + (x1, x2) = _inputs_T + _inputs_flat = [x1, x2] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"NextAfter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NextAfter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NotEqual_T = TypeVar("TV_NotEqual_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def not_equal(x: Annotated[Any, TV_NotEqual_T], y: Annotated[Any, TV_NotEqual_T], incompatible_shape_error:bool=True, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns the truth value of (x != y) element-wise. + + *NOTE*: `NotEqual` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. + y: A `Tensor`. Must have the same type as `x`. + incompatible_shape_error: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NotEqual", name, x, y, "incompatible_shape_error", + incompatible_shape_error) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return not_equal_eager_fallback( + x, y, incompatible_shape_error=incompatible_shape_error, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if incompatible_shape_error is None: + incompatible_shape_error = True + incompatible_shape_error = _execute.make_bool(incompatible_shape_error, "incompatible_shape_error") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NotEqual", x=x, y=y, + incompatible_shape_error=incompatible_shape_error, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "incompatible_shape_error", + _op._get_attr_bool("incompatible_shape_error")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NotEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NotEqual = tf_export("raw_ops.NotEqual")(_ops.to_raw_op(not_equal)) + + +def not_equal_eager_fallback(x: Annotated[Any, TV_NotEqual_T], y: Annotated[Any, TV_NotEqual_T], incompatible_shape_error: bool, name, ctx) -> Annotated[Any, _atypes.Bool]: + if incompatible_shape_error is None: + incompatible_shape_error = True + incompatible_shape_error = _execute.make_bool(incompatible_shape_error, "incompatible_shape_error") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, []) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T, "incompatible_shape_error", + incompatible_shape_error) + _result = _execute.execute(b"NotEqual", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NotEqual", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Polygamma_T = TypeVar("TV_Polygamma_T", _atypes.Float32, _atypes.Float64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.polygamma', v1=['math.polygamma', 'polygamma']) +@deprecated_endpoints('polygamma') +def polygamma(a: Annotated[Any, TV_Polygamma_T], x: Annotated[Any, TV_Polygamma_T], name=None) -> Annotated[Any, TV_Polygamma_T]: + r"""Compute the polygamma function \\(\psi^{(n)}(x)\\). + + The polygamma function is defined as: + + + \\(\psi^{(a)}(x) = \frac{d^a}{dx^a} \psi(x)\\) + + where \\(\psi(x)\\) is the digamma function. + The polygamma function is defined only for non-negative integer orders \\a\\. + + Args: + a: A `Tensor`. Must be one of the following types: `float32`, `float64`. + x: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Polygamma", name, a, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_polygamma( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + return polygamma_eager_fallback( + a, x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polygamma, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_polygamma( + (a, x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Polygamma", a=a, x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polygamma, (), dict(a=a, x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Polygamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Polygamma = tf_export("raw_ops.Polygamma")(_ops.to_raw_op(polygamma)) +_dispatcher_for_polygamma = polygamma._tf_type_based_dispatcher.Dispatch + + +def polygamma_eager_fallback(a: Annotated[Any, TV_Polygamma_T], x: Annotated[Any, TV_Polygamma_T], name, ctx) -> Annotated[Any, TV_Polygamma_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, x], ctx, [_dtypes.float32, _dtypes.float64, ]) + (a, x) = _inputs_T + _inputs_flat = [a, x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Polygamma", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Polygamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Pow_T = TypeVar("TV_Pow_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def _pow(x: Annotated[Any, TV_Pow_T], y: Annotated[Any, TV_Pow_T], name=None) -> Annotated[Any, TV_Pow_T]: + r"""Computes the power of one value to another. + + Given a tensor `x` and a tensor `y`, this operation computes \\(x^y\\) for + corresponding elements in `x` and `y`. For example: + + ``` + # tensor 'x' is [[2, 2]], [3, 3]] + # tensor 'y' is [[8, 16], [2, 3]] + tf.pow(x, y) ==> [[256, 65536], [9, 27]] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `half`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Pow", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _pow_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Pow", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Pow", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Pow = tf_export("raw_ops.Pow")(_ops.to_raw_op(_pow)) + + +def _pow_eager_fallback(x: Annotated[Any, TV_Pow_T], y: Annotated[Any, TV_Pow_T], name, ctx) -> Annotated[Any, TV_Pow_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.half, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Pow", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Pow", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Prod_T = TypeVar("TV_Prod_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Prod_Tidx = TypeVar("TV_Prod_Tidx", _atypes.Int32, _atypes.Int64) + +def prod(input: Annotated[Any, TV_Prod_T], axis: Annotated[Any, TV_Prod_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_Prod_T]: + r"""Computes the product of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Prod", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return prod_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Prod", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Prod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Prod = tf_export("raw_ops.Prod")(_ops.to_raw_op(prod)) + + +def prod_eager_fallback(input: Annotated[Any, TV_Prod_T], axis: Annotated[Any, TV_Prod_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_Prod_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Prod", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Prod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QuantizeDownAndShrinkRangeOutput = collections.namedtuple( + "QuantizeDownAndShrinkRange", + ["output", "output_min", "output_max"]) + + +TV_QuantizeDownAndShrinkRange_Tinput = TypeVar("TV_QuantizeDownAndShrinkRange_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizeDownAndShrinkRange_out_type = TypeVar("TV_QuantizeDownAndShrinkRange_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantize_down_and_shrink_range(input: Annotated[Any, TV_QuantizeDownAndShrinkRange_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], out_type: TV_QuantizeDownAndShrinkRange_out_type, name=None): + r"""Convert the quantized 'input' tensor into a lower-precision 'output', using the + + actual distribution of the values to maximize the usage of the lower bit depth + and adjusting the output min and max ranges accordingly. + + [input_min, input_max] are scalar floats that specify the range for the float + interpretation of the 'input' data. For example, if input_min is -1.0f and + input_max is 1.0f, and we are dealing with quint16 quantized data, then a 0 + value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. + + This operator tries to squeeze as much precision as possible into an output with + a lower bit depth by calculating the actual min and max values found in the + data. For example, maybe that quint16 input has no values lower than 16,384 and + none higher than 49,152. That means only half the range is actually needed, all + the float interpretations are between -0.5f and 0.5f, so if we want to compress + the data into a quint8 output, we can use that range rather than the theoretical + -1.0f to 1.0f that is suggested by the input min and max. + + In practice, this is most useful for taking output from operations like + QuantizedMatMul that can produce higher bit-depth outputs than their inputs and + may have large potential output ranges, but in practice have a distribution of + input values that only uses a small fraction of the possible range. By feeding + that output into this operator, we can reduce it from 32 bits down to 8 with + minimal loss of accuracy. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + input_min: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + input_max: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. + The type of the output. Should be a lower bit depth than Tinput. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor` of type `out_type`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizeDownAndShrinkRange", name, input, input_min, input_max, + "out_type", out_type) + _result = _QuantizeDownAndShrinkRangeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantize_down_and_shrink_range_eager_fallback( + input, input_min, input_max, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizeDownAndShrinkRange", input=input, input_min=input_min, + input_max=input_max, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizeDownAndShrinkRange", _inputs_flat, _attrs, _result) + _result = _QuantizeDownAndShrinkRangeOutput._make(_result) + return _result + +QuantizeDownAndShrinkRange = tf_export("raw_ops.QuantizeDownAndShrinkRange")(_ops.to_raw_op(quantize_down_and_shrink_range)) + + +def quantize_down_and_shrink_range_eager_fallback(input: Annotated[Any, TV_QuantizeDownAndShrinkRange_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], out_type: TV_QuantizeDownAndShrinkRange_out_type, name, ctx): + out_type = _execute.make_type(out_type, "out_type") + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + _inputs_flat = [input, input_min, input_max] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) + _result = _execute.execute(b"QuantizeDownAndShrinkRange", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizeDownAndShrinkRange", _inputs_flat, _attrs, _result) + _result = _QuantizeDownAndShrinkRangeOutput._make(_result) + return _result + +_QuantizedAddOutput = collections.namedtuple( + "QuantizedAdd", + ["z", "min_z", "max_z"]) + + +TV_QuantizedAdd_T1 = TypeVar("TV_QuantizedAdd_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedAdd_T2 = TypeVar("TV_QuantizedAdd_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedAdd_Toutput = TypeVar("TV_QuantizedAdd_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_add(x: Annotated[Any, TV_QuantizedAdd_T1], y: Annotated[Any, TV_QuantizedAdd_T2], min_x: Annotated[Any, _atypes.Float32], max_x: Annotated[Any, _atypes.Float32], min_y: Annotated[Any, _atypes.Float32], max_y: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedAdd_Toutput=_dtypes.qint32, name=None): + r"""Returns x + y element-wise, working on quantized buffers. + + Args: + x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + y: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_x: A `Tensor` of type `float32`. + The float value that the lowest quantized `x` value represents. + max_x: A `Tensor` of type `float32`. + The float value that the highest quantized `x` value represents. + min_y: A `Tensor` of type `float32`. + The float value that the lowest quantized `y` value represents. + max_y: A `Tensor` of type `float32`. + The float value that the highest quantized `y` value represents. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (z, min_z, max_z). + + z: A `Tensor` of type `Toutput`. + min_z: A `Tensor` of type `float32`. + max_z: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedAdd", name, x, y, min_x, max_x, min_y, max_y, + "Toutput", Toutput) + _result = _QuantizedAddOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_add_eager_fallback( + x, y, min_x, max_x, min_y, max_y, Toutput=Toutput, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedAdd", x=x, y=y, min_x=min_x, max_x=max_x, min_y=min_y, + max_y=max_y, Toutput=Toutput, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Toutput", _op._get_attr_type("Toutput")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedAdd", _inputs_flat, _attrs, _result) + _result = _QuantizedAddOutput._make(_result) + return _result + +QuantizedAdd = tf_export("raw_ops.QuantizedAdd")(_ops.to_raw_op(quantized_add)) + + +def quantized_add_eager_fallback(x: Annotated[Any, TV_QuantizedAdd_T1], y: Annotated[Any, TV_QuantizedAdd_T2], min_x: Annotated[Any, _atypes.Float32], max_x: Annotated[Any, _atypes.Float32], min_y: Annotated[Any, _atypes.Float32], max_y: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedAdd_Toutput, name, ctx): + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + _attr_T1, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (y,) = _execute.args_to_matching_eager([y], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_x = _ops.convert_to_tensor(min_x, _dtypes.float32) + max_x = _ops.convert_to_tensor(max_x, _dtypes.float32) + min_y = _ops.convert_to_tensor(min_y, _dtypes.float32) + max_y = _ops.convert_to_tensor(max_y, _dtypes.float32) + _inputs_flat = [x, y, min_x, max_x, min_y, max_y] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput) + _result = _execute.execute(b"QuantizedAdd", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedAdd", _inputs_flat, _attrs, _result) + _result = _QuantizedAddOutput._make(_result) + return _result + +_QuantizedMatMulOutput = collections.namedtuple( + "QuantizedMatMul", + ["out", "min_out", "max_out"]) + + +TV_QuantizedMatMul_T1 = TypeVar("TV_QuantizedMatMul_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMul_T2 = TypeVar("TV_QuantizedMatMul_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMul_Toutput = TypeVar("TV_QuantizedMatMul_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMul_Tactivation = TypeVar("TV_QuantizedMatMul_Tactivation", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mat_mul(a: Annotated[Any, TV_QuantizedMatMul_T1], b: Annotated[Any, TV_QuantizedMatMul_T2], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMatMul_Toutput=_dtypes.qint32, transpose_a:bool=False, transpose_b:bool=False, Tactivation:TV_QuantizedMatMul_Tactivation=_dtypes.quint8, name=None): + r"""Perform a quantized matrix multiplication of `a` by the matrix `b`. + + The inputs must be two-dimensional matrices and the inner dimension of + `a` (after being transposed if `transpose_a` is non-zero) must match the + outer dimension of `b` (after being transposed if `transposed_b` is + non-zero). + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + Must be a two-dimensional tensor. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + Must be a two-dimensional tensor. + min_a: A `Tensor` of type `float32`. + The float value that the lowest quantized `a` value represents. + max_a: A `Tensor` of type `float32`. + The float value that the highest quantized `a` value represents. + min_b: A `Tensor` of type `float32`. + The float value that the lowest quantized `b` value represents. + max_b: A `Tensor` of type `float32`. + The float value that the highest quantized `b` value represents. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + transpose_a: An optional `bool`. Defaults to `False`. + If true, `a` is transposed before multiplication. + transpose_b: An optional `bool`. Defaults to `False`. + If true, `b` is transposed before multiplication. + Tactivation: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + The type of output produced by activation function + following this operation. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, min_out, max_out). + + out: A `Tensor` of type `Toutput`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMul", name, a, b, min_a, max_a, min_b, max_b, + "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", + transpose_b, "Tactivation", Tactivation) + _result = _QuantizedMatMulOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_eager_fallback( + a, b, min_a, max_a, min_b, max_b, Toutput=Toutput, + transpose_a=transpose_a, transpose_b=transpose_b, + Tactivation=Tactivation, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if Tactivation is None: + Tactivation = _dtypes.quint8 + Tactivation = _execute.make_type(Tactivation, "Tactivation") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMul", a=a, b=b, min_a=min_a, max_a=max_a, min_b=min_b, + max_b=max_b, Toutput=Toutput, + transpose_a=transpose_a, transpose_b=transpose_b, + Tactivation=Tactivation, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Toutput", _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "Tactivation", + _op._get_attr_type("Tactivation")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMul", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulOutput._make(_result) + return _result + +QuantizedMatMul = tf_export("raw_ops.QuantizedMatMul")(_ops.to_raw_op(quantized_mat_mul)) + + +def quantized_mat_mul_eager_fallback(a: Annotated[Any, TV_QuantizedMatMul_T1], b: Annotated[Any, TV_QuantizedMatMul_T2], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMul_Toutput, transpose_a: bool, transpose_b: bool, Tactivation: TV_QuantizedMatMul_Tactivation, name, ctx): + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if Tactivation is None: + Tactivation = _dtypes.quint8 + Tactivation = _execute.make_type(Tactivation, "Tactivation") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + _inputs_flat = [a, b, min_a, max_a, min_b, max_b] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput, "transpose_a", + transpose_a, "transpose_b", transpose_b, "Tactivation", Tactivation) + _result = _execute.execute(b"QuantizedMatMul", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMul", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulOutput._make(_result) + return _result + +_QuantizedMulOutput = collections.namedtuple( + "QuantizedMul", + ["z", "min_z", "max_z"]) + + +TV_QuantizedMul_T1 = TypeVar("TV_QuantizedMul_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMul_T2 = TypeVar("TV_QuantizedMul_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMul_Toutput = TypeVar("TV_QuantizedMul_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mul(x: Annotated[Any, TV_QuantizedMul_T1], y: Annotated[Any, TV_QuantizedMul_T2], min_x: Annotated[Any, _atypes.Float32], max_x: Annotated[Any, _atypes.Float32], min_y: Annotated[Any, _atypes.Float32], max_y: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMul_Toutput=_dtypes.qint32, name=None): + r"""Returns x * y element-wise, working on quantized buffers. + + Args: + x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + y: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_x: A `Tensor` of type `float32`. + The float value that the lowest quantized `x` value represents. + max_x: A `Tensor` of type `float32`. + The float value that the highest quantized `x` value represents. + min_y: A `Tensor` of type `float32`. + The float value that the lowest quantized `y` value represents. + max_y: A `Tensor` of type `float32`. + The float value that the highest quantized `y` value represents. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (z, min_z, max_z). + + z: A `Tensor` of type `Toutput`. + min_z: A `Tensor` of type `float32`. + max_z: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMul", name, x, y, min_x, max_x, min_y, max_y, + "Toutput", Toutput) + _result = _QuantizedMulOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mul_eager_fallback( + x, y, min_x, max_x, min_y, max_y, Toutput=Toutput, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMul", x=x, y=y, min_x=min_x, max_x=max_x, min_y=min_y, + max_y=max_y, Toutput=Toutput, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Toutput", _op._get_attr_type("Toutput")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMul", _inputs_flat, _attrs, _result) + _result = _QuantizedMulOutput._make(_result) + return _result + +QuantizedMul = tf_export("raw_ops.QuantizedMul")(_ops.to_raw_op(quantized_mul)) + + +def quantized_mul_eager_fallback(x: Annotated[Any, TV_QuantizedMul_T1], y: Annotated[Any, TV_QuantizedMul_T2], min_x: Annotated[Any, _atypes.Float32], max_x: Annotated[Any, _atypes.Float32], min_y: Annotated[Any, _atypes.Float32], max_y: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMul_Toutput, name, ctx): + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + _attr_T1, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (y,) = _execute.args_to_matching_eager([y], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_x = _ops.convert_to_tensor(min_x, _dtypes.float32) + max_x = _ops.convert_to_tensor(max_x, _dtypes.float32) + min_y = _ops.convert_to_tensor(min_y, _dtypes.float32) + max_y = _ops.convert_to_tensor(max_y, _dtypes.float32) + _inputs_flat = [x, y, min_x, max_x, min_y, max_y] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput) + _result = _execute.execute(b"QuantizedMul", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMul", _inputs_flat, _attrs, _result) + _result = _QuantizedMulOutput._make(_result) + return _result + + +TV_RaggedBincount_Tidx = TypeVar("TV_RaggedBincount_Tidx", _atypes.Int32, _atypes.Int64) +TV_RaggedBincount_T = TypeVar("TV_RaggedBincount_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def ragged_bincount(splits: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedBincount_Tidx], size: Annotated[Any, TV_RaggedBincount_Tidx], weights: Annotated[Any, TV_RaggedBincount_T], binary_output:bool=False, name=None) -> Annotated[Any, TV_RaggedBincount_T]: + r"""Counts the number of occurrences of each value in an integer array. + + Outputs a vector with length `size` and the same dtype as `weights`. If + `weights` are empty, then index `i` stores the number of times the value `i` is + counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of + the value in `weights` at each index where the corresponding value in `arr` is + `i`. + + Values in `arr` outside of the range [0, size) are ignored. + + Args: + splits: A `Tensor` of type `int64`. 1D int64 `Tensor`. + values: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2D int `Tensor`. + size: A `Tensor`. Must have the same type as `values`. + non-negative int scalar `Tensor`. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + is an int32, int64, float32, or float64 `Tensor` with the same + shape as `input`, or a length-0 `Tensor`, in which case it acts as all weights + equal to 1. + binary_output: An optional `bool`. Defaults to `False`. + bool; Whether the kernel should count the appearance or number of occurrences. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedBincount", name, splits, values, size, weights, + "binary_output", binary_output) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_bincount_eager_fallback( + splits, values, size, weights, binary_output=binary_output, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedBincount", splits=splits, values=values, size=size, + weights=weights, binary_output=binary_output, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx"), "T", + _op._get_attr_type("T"), "binary_output", + _op._get_attr_bool("binary_output")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RaggedBincount = tf_export("raw_ops.RaggedBincount")(_ops.to_raw_op(ragged_bincount)) + + +def ragged_bincount_eager_fallback(splits: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedBincount_Tidx], size: Annotated[Any, TV_RaggedBincount_Tidx], weights: Annotated[Any, TV_RaggedBincount_T], binary_output: bool, name, ctx) -> Annotated[Any, TV_RaggedBincount_T]: + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([values, size], ctx, [_dtypes.int32, _dtypes.int64, ]) + (values, size) = _inputs_Tidx + _attr_T, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + splits = _ops.convert_to_tensor(splits, _dtypes.int64) + _inputs_flat = [splits, values, size, weights] + _attrs = ("Tidx", _attr_Tidx, "T", _attr_T, "binary_output", binary_output) + _result = _execute.execute(b"RaggedBincount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Range_Tidx = TypeVar("TV_Range_Tidx", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32) + +def _range(start: Annotated[Any, TV_Range_Tidx], limit: Annotated[Any, TV_Range_Tidx], delta: Annotated[Any, TV_Range_Tidx], name=None) -> Annotated[Any, TV_Range_Tidx]: + r"""Creates a sequence of numbers. + + This operation creates a sequence of numbers that begins at `start` and + extends by increments of `delta` up to but not including `limit`. + + For example: + + ``` + # 'start' is 3 + # 'limit' is 18 + # 'delta' is 3 + tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15] + ``` + + Args: + start: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint16`, `uint32`. + 0-D (scalar). First entry in the sequence. + limit: A `Tensor`. Must have the same type as `start`. + 0-D (scalar). Upper limit of sequence, exclusive. + delta: A `Tensor`. Must have the same type as `start`. + 0-D (scalar). Optional. Default is 1. Number that increments `start`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `start`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Range", name, start, limit, delta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _range_eager_fallback( + start, limit, delta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Range", start=start, limit=limit, delta=delta, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Range", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Range = tf_export("raw_ops.Range")(_ops.to_raw_op(_range)) + + +def _range_eager_fallback(start: Annotated[Any, TV_Range_Tidx], limit: Annotated[Any, TV_Range_Tidx], delta: Annotated[Any, TV_Range_Tidx], name, ctx) -> Annotated[Any, TV_Range_Tidx]: + _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([start, limit, delta], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint16, _dtypes.uint32, ], _dtypes.int32) + (start, limit, delta) = _inputs_Tidx + _inputs_flat = [start, limit, delta] + _attrs = ("Tidx", _attr_Tidx) + _result = _execute.execute(b"Range", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Range", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Real_T = TypeVar("TV_Real_T", _atypes.Complex128, _atypes.Complex64) +TV_Real_Tout = TypeVar("TV_Real_Tout", _atypes.Float32, _atypes.Float64) + +def real(input: Annotated[Any, TV_Real_T], Tout:TV_Real_Tout=_dtypes.float32, name=None) -> Annotated[Any, TV_Real_Tout]: + r"""Returns the real part of a complex number. + + Given a tensor `input` of complex numbers, this operation returns a tensor of + type `float` that is the real part of each element in `input`. All elements in + `input` must be complex numbers of the form \\(a + bj\\), where *a* is the real + part returned by this operation and *b* is the imaginary part. + + For example: + + ``` + # tensor 'input' is [-2.25 + 4.75j, 3.25 + 5.75j] + tf.real(input) ==> [-2.25, 3.25] + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + Tout: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Real", name, input, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return real_eager_fallback( + input, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Real", input=input, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tout", + _op._get_attr_type("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Real", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Real = tf_export("raw_ops.Real")(_ops.to_raw_op(real)) + + +def real_eager_fallback(input: Annotated[Any, TV_Real_T], Tout: TV_Real_Tout, name, ctx) -> Annotated[Any, TV_Real_Tout]: + if Tout is None: + Tout = _dtypes.float32 + Tout = _execute.make_type(Tout, "Tout") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "Tout", Tout) + _result = _execute.execute(b"Real", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Real", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RealDiv_T = TypeVar("TV_RealDiv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('realdiv') +def real_div(x: Annotated[Any, TV_RealDiv_T], y: Annotated[Any, TV_RealDiv_T], name=None) -> Annotated[Any, TV_RealDiv_T]: + r"""Returns x / y element-wise for real types. + + If `x` and `y` are reals, this will return the floating-point division. + + *NOTE*: `Div` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `uint64`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RealDiv", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_real_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return real_div_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + real_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_real_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RealDiv", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + real_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RealDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RealDiv = tf_export("raw_ops.RealDiv")(_ops.to_raw_op(real_div)) +_dispatcher_for_real_div = real_div._tf_type_based_dispatcher.Dispatch + + +def real_div_eager_fallback(x: Annotated[Any, TV_RealDiv_T], y: Annotated[Any, TV_RealDiv_T], name, ctx) -> Annotated[Any, TV_RealDiv_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.uint64, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RealDiv", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RealDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Reciprocal_T = TypeVar("TV_Reciprocal_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.reciprocal', v1=['math.reciprocal', 'reciprocal']) +@deprecated_endpoints('reciprocal') +def reciprocal(x: Annotated[Any, TV_Reciprocal_T], name=None) -> Annotated[Any, TV_Reciprocal_T]: + r"""Computes the reciprocal of x element-wise. + + I.e., \\(y = 1 / x\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Reciprocal", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_reciprocal( + (x, name,), None) + if _result is not NotImplemented: + return _result + return reciprocal_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reciprocal, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_reciprocal( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Reciprocal", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reciprocal, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Reciprocal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Reciprocal = tf_export("raw_ops.Reciprocal")(_ops.to_raw_op(reciprocal)) +_dispatcher_for_reciprocal = reciprocal._tf_type_based_dispatcher.Dispatch + + +def reciprocal_eager_fallback(x: Annotated[Any, TV_Reciprocal_T], name, ctx) -> Annotated[Any, TV_Reciprocal_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Reciprocal", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Reciprocal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReciprocalGrad_T = TypeVar("TV_ReciprocalGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def reciprocal_grad(y: Annotated[Any, TV_ReciprocalGrad_T], dy: Annotated[Any, TV_ReciprocalGrad_T], name=None) -> Annotated[Any, TV_ReciprocalGrad_T]: + r"""Computes the gradient for the inverse of `x` wrt its input. + + Specifically, `grad = -dy * y*y`, where `y = 1/x`, and `dy` + is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReciprocalGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reciprocal_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReciprocalGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReciprocalGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReciprocalGrad = tf_export("raw_ops.ReciprocalGrad")(_ops.to_raw_op(reciprocal_grad)) + + +def reciprocal_grad_eager_fallback(y: Annotated[Any, TV_ReciprocalGrad_T], dy: Annotated[Any, TV_ReciprocalGrad_T], name, ctx) -> Annotated[Any, TV_ReciprocalGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ReciprocalGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReciprocalGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_RequantizationRangeOutput = collections.namedtuple( + "RequantizationRange", + ["output_min", "output_max"]) + + +TV_RequantizationRange_Tinput = TypeVar("TV_RequantizationRange_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def requantization_range(input: Annotated[Any, TV_RequantizationRange_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], name=None): + r"""Computes a range that covers the actual values present in a quantized tensor. + + Given a quantized tensor described by `(input, input_min, input_max)`, outputs a + range that covers the actual values present in that tensor. This op is typically + used to produce the `requested_output_min` and `requested_output_max` for + `Requantize`. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + input_min: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + input_max: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_min, output_max). + + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RequantizationRange", name, input, input_min, input_max) + _result = _RequantizationRangeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return requantization_range_eager_fallback( + input, input_min, input_max, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RequantizationRange", input=input, input_min=input_min, + input_max=input_max, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RequantizationRange", _inputs_flat, _attrs, _result) + _result = _RequantizationRangeOutput._make(_result) + return _result + +RequantizationRange = tf_export("raw_ops.RequantizationRange")(_ops.to_raw_op(requantization_range)) + + +def requantization_range_eager_fallback(input: Annotated[Any, TV_RequantizationRange_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], name, ctx): + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + _inputs_flat = [input, input_min, input_max] + _attrs = ("Tinput", _attr_Tinput) + _result = _execute.execute(b"RequantizationRange", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RequantizationRange", _inputs_flat, _attrs, _result) + _result = _RequantizationRangeOutput._make(_result) + return _result + +_RequantizationRangePerChannelOutput = collections.namedtuple( + "RequantizationRangePerChannel", + ["output_min", "output_max"]) + + +TV_RequantizationRangePerChannel_T = TypeVar("TV_RequantizationRangePerChannel_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def requantization_range_per_channel(input: Annotated[Any, TV_RequantizationRangePerChannel_T], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], clip_value_max: float, name=None): + r"""Computes requantization range per channel. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + input_min: A `Tensor` of type `float32`. + The minimum value of the input tensor + input_max: A `Tensor` of type `float32`. + The maximum value of the input tensor. + clip_value_max: A `float`. + The maximum value of the output that needs to be clipped. + Example: set this to 6 for Relu6. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_min, output_max). + + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RequantizationRangePerChannel", name, input, input_min, + input_max, "clip_value_max", clip_value_max) + _result = _RequantizationRangePerChannelOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return requantization_range_per_channel_eager_fallback( + input, input_min, input_max, clip_value_max=clip_value_max, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + clip_value_max = _execute.make_float(clip_value_max, "clip_value_max") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RequantizationRangePerChannel", input=input, input_min=input_min, + input_max=input_max, + clip_value_max=clip_value_max, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "clip_value_max", + _op.get_attr("clip_value_max")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RequantizationRangePerChannel", _inputs_flat, _attrs, _result) + _result = _RequantizationRangePerChannelOutput._make(_result) + return _result + +RequantizationRangePerChannel = tf_export("raw_ops.RequantizationRangePerChannel")(_ops.to_raw_op(requantization_range_per_channel)) + + +def requantization_range_per_channel_eager_fallback(input: Annotated[Any, TV_RequantizationRangePerChannel_T], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], clip_value_max: float, name, ctx): + clip_value_max = _execute.make_float(clip_value_max, "clip_value_max") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ], _dtypes.qint32) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + _inputs_flat = [input, input_min, input_max] + _attrs = ("T", _attr_T, "clip_value_max", clip_value_max) + _result = _execute.execute(b"RequantizationRangePerChannel", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RequantizationRangePerChannel", _inputs_flat, _attrs, _result) + _result = _RequantizationRangePerChannelOutput._make(_result) + return _result + +_RequantizeOutput = collections.namedtuple( + "Requantize", + ["output", "output_min", "output_max"]) + + +TV_Requantize_Tinput = TypeVar("TV_Requantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_Requantize_out_type = TypeVar("TV_Requantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def requantize(input: Annotated[Any, TV_Requantize_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], requested_output_min: Annotated[Any, _atypes.Float32], requested_output_max: Annotated[Any, _atypes.Float32], out_type: TV_Requantize_out_type, name=None): + r"""Converts the quantized `input` tensor into a lower-precision `output`. + + Converts the quantized `input` tensor into a lower-precision `output`, using the + output range specified with `requested_output_min` and `requested_output_max`. + + `[input_min, input_max]` are scalar floats that specify the range for the float + interpretation of the `input` data. For example, if `input_min` is -1.0f and + `input_max` is 1.0f, and we are dealing with `quint16` quantized data, then a 0 + value in the 16-bit data should be interpreted as -1.0f, and a 65535 means 1.0f. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + input_min: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + input_max: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + requested_output_min: A `Tensor` of type `float32`. + The float value that the minimum quantized output value represents. + requested_output_max: A `Tensor` of type `float32`. + The float value that the maximum quantized output value represents. + out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. + The type of the output. Should be a lower bit depth than Tinput. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor` of type `out_type`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Requantize", name, input, input_min, input_max, + requested_output_min, requested_output_max, "out_type", out_type) + _result = _RequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return requantize_eager_fallback( + input, input_min, input_max, requested_output_min, + requested_output_max, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Requantize", input=input, input_min=input_min, input_max=input_max, + requested_output_min=requested_output_min, + requested_output_max=requested_output_max, + out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Requantize", _inputs_flat, _attrs, _result) + _result = _RequantizeOutput._make(_result) + return _result + +Requantize = tf_export("raw_ops.Requantize")(_ops.to_raw_op(requantize)) + + +def requantize_eager_fallback(input: Annotated[Any, TV_Requantize_Tinput], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], requested_output_min: Annotated[Any, _atypes.Float32], requested_output_max: Annotated[Any, _atypes.Float32], out_type: TV_Requantize_out_type, name, ctx): + out_type = _execute.make_type(out_type, "out_type") + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + requested_output_min = _ops.convert_to_tensor(requested_output_min, _dtypes.float32) + requested_output_max = _ops.convert_to_tensor(requested_output_max, _dtypes.float32) + _inputs_flat = [input, input_min, input_max, requested_output_min, requested_output_max] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) + _result = _execute.execute(b"Requantize", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Requantize", _inputs_flat, _attrs, _result) + _result = _RequantizeOutput._make(_result) + return _result + +_RequantizePerChannelOutput = collections.namedtuple( + "RequantizePerChannel", + ["output", "output_min", "output_max"]) + + +TV_RequantizePerChannel_T = TypeVar("TV_RequantizePerChannel_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_RequantizePerChannel_out_type = TypeVar("TV_RequantizePerChannel_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def requantize_per_channel(input: Annotated[Any, TV_RequantizePerChannel_T], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], requested_output_min: Annotated[Any, _atypes.Float32], requested_output_max: Annotated[Any, _atypes.Float32], out_type:TV_RequantizePerChannel_out_type=_dtypes.quint8, name=None): + r"""Requantizes input with min and max values known per channel. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + input_min: A `Tensor` of type `float32`. + The minimum value of the input tensor + input_max: A `Tensor` of type `float32`. + The maximum value of the input tensor. + requested_output_min: A `Tensor` of type `float32`. + The minimum value of the output tensor requested. + requested_output_max: A `Tensor` of type `float32`. + The maximum value of the output tensor requested. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + The quantized type of output tensor that needs to be converted. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, output_min, output_max). + + output: A `Tensor` of type `out_type`. + output_min: A `Tensor` of type `float32`. + output_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RequantizePerChannel", name, input, input_min, input_max, + requested_output_min, requested_output_max, "out_type", out_type) + _result = _RequantizePerChannelOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return requantize_per_channel_eager_fallback( + input, input_min, input_max, requested_output_min, + requested_output_max, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RequantizePerChannel", input=input, input_min=input_min, + input_max=input_max, + requested_output_min=requested_output_min, + requested_output_max=requested_output_max, + out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RequantizePerChannel", _inputs_flat, _attrs, _result) + _result = _RequantizePerChannelOutput._make(_result) + return _result + +RequantizePerChannel = tf_export("raw_ops.RequantizePerChannel")(_ops.to_raw_op(requantize_per_channel)) + + +def requantize_per_channel_eager_fallback(input: Annotated[Any, TV_RequantizePerChannel_T], input_min: Annotated[Any, _atypes.Float32], input_max: Annotated[Any, _atypes.Float32], requested_output_min: Annotated[Any, _atypes.Float32], requested_output_max: Annotated[Any, _atypes.Float32], out_type: TV_RequantizePerChannel_out_type, name, ctx): + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ], _dtypes.qint32) + input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) + input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) + requested_output_min = _ops.convert_to_tensor(requested_output_min, _dtypes.float32) + requested_output_max = _ops.convert_to_tensor(requested_output_max, _dtypes.float32) + _inputs_flat = [input, input_min, input_max, requested_output_min, requested_output_max] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"RequantizePerChannel", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RequantizePerChannel", _inputs_flat, _attrs, _result) + _result = _RequantizePerChannelOutput._make(_result) + return _result + + +TV_Rint_T = TypeVar("TV_Rint_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.rint', v1=['math.rint', 'rint']) +@deprecated_endpoints('rint') +def rint(x: Annotated[Any, TV_Rint_T], name=None) -> Annotated[Any, TV_Rint_T]: + r"""Returns element-wise integer closest to x. + + If the result is midway between two representable values, + the even representable is chosen. + For example: + + ``` + rint(-1.5) ==> -2.0 + rint(0.5000001) ==> 1.0 + rint([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) ==> [-2., -2., -0., 0., 2., 2., 2.] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Rint", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_rint( + (x, name,), None) + if _result is not NotImplemented: + return _result + return rint_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rint, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_rint( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Rint", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rint, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Rint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Rint = tf_export("raw_ops.Rint")(_ops.to_raw_op(rint)) +_dispatcher_for_rint = rint._tf_type_based_dispatcher.Dispatch + + +def rint_eager_fallback(x: Annotated[Any, TV_Rint_T], name, ctx) -> Annotated[Any, TV_Rint_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Rint", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Rint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Round_T = TypeVar("TV_Round_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def round(x: Annotated[Any, TV_Round_T], name=None) -> Annotated[Any, TV_Round_T]: + r"""Rounds the values of a tensor to the nearest integer, element-wise. + + Rounds half to even. Also known as bankers rounding. If you want to round + according to the current system rounding mode use std::cint. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Round", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return round_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Round", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Round", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Round = tf_export("raw_ops.Round")(_ops.to_raw_op(round)) + + +def round_eager_fallback(x: Annotated[Any, TV_Round_T], name, ctx) -> Annotated[Any, TV_Round_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Round", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Round", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Rsqrt_T = TypeVar("TV_Rsqrt_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def rsqrt(x: Annotated[Any, TV_Rsqrt_T], name=None) -> Annotated[Any, TV_Rsqrt_T]: + r"""Computes reciprocal of square root of x element-wise. + + I.e., \\(y = 1 / \sqrt{x}\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Rsqrt", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rsqrt_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Rsqrt", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Rsqrt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Rsqrt = tf_export("raw_ops.Rsqrt")(_ops.to_raw_op(rsqrt)) + + +def rsqrt_eager_fallback(x: Annotated[Any, TV_Rsqrt_T], name, ctx) -> Annotated[Any, TV_Rsqrt_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Rsqrt", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Rsqrt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RsqrtGrad_T = TypeVar("TV_RsqrtGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def rsqrt_grad(y: Annotated[Any, TV_RsqrtGrad_T], dy: Annotated[Any, TV_RsqrtGrad_T], name=None) -> Annotated[Any, TV_RsqrtGrad_T]: + r"""Computes the gradient for the rsqrt of `x` wrt its input. + + Specifically, `grad = dy * -0.5 * y^3`, where `y = rsqrt(x)`, and `dy` + is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RsqrtGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rsqrt_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RsqrtGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RsqrtGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RsqrtGrad = tf_export("raw_ops.RsqrtGrad")(_ops.to_raw_op(rsqrt_grad)) + + +def rsqrt_grad_eager_fallback(y: Annotated[Any, TV_RsqrtGrad_T], dy: Annotated[Any, TV_RsqrtGrad_T], name, ctx) -> Annotated[Any, TV_RsqrtGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RsqrtGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RsqrtGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentMax_T = TypeVar("TV_SegmentMax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentMax_Tindices = TypeVar("TV_SegmentMax_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.segment_max', v1=['math.segment_max', 'segment_max']) +@deprecated_endpoints('segment_max') +def segment_max(data: Annotated[Any, TV_SegmentMax_T], segment_ids: Annotated[Any, TV_SegmentMax_Tindices], name=None) -> Annotated[Any, TV_SegmentMax_T]: + r"""Computes the maximum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \max_j(data_j)\\) where `max` is over `j` such + that `segment_ids[j] == i`. + + If the max is empty for a given segment ID `i`, `output[i] = 0`. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + +
+ +
+ + For example: + + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> tf.math.segment_max(c, tf.constant([0, 0, 1])).numpy() + array([[4, 3, 3, 4], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentMax", name, data, segment_ids) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_segment_max( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + return segment_max_eager_fallback( + data, segment_ids, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_max, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_segment_max( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentMax", data=data, segment_ids=segment_ids, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_max, (), dict(data=data, segment_ids=segment_ids, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentMax = tf_export("raw_ops.SegmentMax")(_ops.to_raw_op(segment_max)) +_dispatcher_for_segment_max = segment_max._tf_type_based_dispatcher.Dispatch + + +def segment_max_eager_fallback(data: Annotated[Any, TV_SegmentMax_T], segment_ids: Annotated[Any, TV_SegmentMax_Tindices], name, ctx) -> Annotated[Any, TV_SegmentMax_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [data, segment_ids] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SegmentMax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentMaxV2_T = TypeVar("TV_SegmentMaxV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentMaxV2_Tindices = TypeVar("TV_SegmentMaxV2_Tindices", _atypes.Int32, _atypes.Int64) +TV_SegmentMaxV2_Tnumsegments = TypeVar("TV_SegmentMaxV2_Tnumsegments", _atypes.Int32, _atypes.Int64) + +def segment_max_v2(data: Annotated[Any, TV_SegmentMaxV2_T], segment_ids: Annotated[Any, TV_SegmentMaxV2_Tindices], num_segments: Annotated[Any, TV_SegmentMaxV2_Tnumsegments], name=None) -> Annotated[Any, TV_SegmentMaxV2_T]: + r"""Computes the maximum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \max_j(data_j)\\) where `max` is over `j` such + that `segment_ids[j] == i`. + + If the maximum is empty for a given segment ID `i`, it outputs the smallest + possible value for the specific numeric type, + `output[i] = numeric_limits::lowest()`. + + Note: That this op is currently only supported with jit_compile=True. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + + The only difference with SegmentMax is the additional input `num_segments`. + This helps in evaluating the output shape in compile time. + `num_segments` should be consistent with segment_ids. + e.g. Max(segment_ids) should be equal to `num_segments` - 1 for a 1-d segment_ids + With inconsistent num_segments, the op still runs. only difference is, + the output takes the size of num_segments irrespective of size of segment_ids and data. + for num_segments less than expected output size, the last elements are ignored + for num_segments more than the expected output size, last elements are assigned + smallest possible value for the specific numeric type. + + For example: + + >>> @tf.function(jit_compile=True) + ... def test(c): + ... return tf.raw_ops.SegmentMaxV2(data=c, segment_ids=tf.constant([0, 0, 1]), num_segments=2) + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> test(c).numpy() + array([[4, 3, 3, 4], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + The values must be less than `num_segments`. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentMaxV2", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return segment_max_v2_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentMaxV2", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentMaxV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentMaxV2 = tf_export("raw_ops.SegmentMaxV2")(_ops.to_raw_op(segment_max_v2)) + + +def segment_max_v2_eager_fallback(data: Annotated[Any, TV_SegmentMaxV2_T], segment_ids: Annotated[Any, TV_SegmentMaxV2_Tindices], num_segments: Annotated[Any, TV_SegmentMaxV2_Tnumsegments], name, ctx) -> Annotated[Any, TV_SegmentMaxV2_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"SegmentMaxV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentMaxV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentMean_T = TypeVar("TV_SegmentMean_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentMean_Tindices = TypeVar("TV_SegmentMean_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.segment_mean', v1=['math.segment_mean', 'segment_mean']) +@deprecated_endpoints('segment_mean') +def segment_mean(data: Annotated[Any, TV_SegmentMean_T], segment_ids: Annotated[Any, TV_SegmentMean_Tindices], name=None) -> Annotated[Any, TV_SegmentMean_T]: + r"""Computes the mean along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \frac{\sum_j data_j}{N}\\) where `mean` is + over `j` such that `segment_ids[j] == i` and `N` is the total number of + values summed. + + If the mean is empty for a given segment ID `i`, `output[i] = 0`. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as a smaller following index when computing the numerator + of the mean. + +
+ +
+ + For example: + + >>> c = tf.constant([[1.0,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> tf.math.segment_mean(c, tf.constant([0, 0, 1])).numpy() + array([[2.5, 2.5, 2.5, 2.5], + [5., 6., 7., 8.]], dtype=float32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentMean", name, data, segment_ids) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_segment_mean( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + return segment_mean_eager_fallback( + data, segment_ids, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_mean, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_segment_mean( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentMean", data=data, segment_ids=segment_ids, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_mean, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentMean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentMean = tf_export("raw_ops.SegmentMean")(_ops.to_raw_op(segment_mean)) +_dispatcher_for_segment_mean = segment_mean._tf_type_based_dispatcher.Dispatch + + +def segment_mean_eager_fallback(data: Annotated[Any, TV_SegmentMean_T], segment_ids: Annotated[Any, TV_SegmentMean_Tindices], name, ctx) -> Annotated[Any, TV_SegmentMean_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [data, segment_ids] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SegmentMean", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentMean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentMin_T = TypeVar("TV_SegmentMin_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentMin_Tindices = TypeVar("TV_SegmentMin_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.segment_min', v1=['math.segment_min', 'segment_min']) +@deprecated_endpoints('segment_min') +def segment_min(data: Annotated[Any, TV_SegmentMin_T], segment_ids: Annotated[Any, TV_SegmentMin_Tindices], name=None) -> Annotated[Any, TV_SegmentMin_T]: + r"""Computes the minimum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \min_j(data_j)\\) where `min` is over `j` such + that `segment_ids[j] == i`. + + If the min is empty for a given segment ID `i`, `output[i] = 0`. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + +
+ +
+ + For example: + + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> tf.math.segment_min(c, tf.constant([0, 0, 1])).numpy() + array([[1, 2, 2, 1], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentMin", name, data, segment_ids) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_segment_min( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + return segment_min_eager_fallback( + data, segment_ids, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_min, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_segment_min( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentMin", data=data, segment_ids=segment_ids, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_min, (), dict(data=data, segment_ids=segment_ids, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentMin = tf_export("raw_ops.SegmentMin")(_ops.to_raw_op(segment_min)) +_dispatcher_for_segment_min = segment_min._tf_type_based_dispatcher.Dispatch + + +def segment_min_eager_fallback(data: Annotated[Any, TV_SegmentMin_T], segment_ids: Annotated[Any, TV_SegmentMin_Tindices], name, ctx) -> Annotated[Any, TV_SegmentMin_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [data, segment_ids] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SegmentMin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentMinV2_T = TypeVar("TV_SegmentMinV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentMinV2_Tindices = TypeVar("TV_SegmentMinV2_Tindices", _atypes.Int32, _atypes.Int64) +TV_SegmentMinV2_Tnumsegments = TypeVar("TV_SegmentMinV2_Tnumsegments", _atypes.Int32, _atypes.Int64) + +def segment_min_v2(data: Annotated[Any, TV_SegmentMinV2_T], segment_ids: Annotated[Any, TV_SegmentMinV2_Tindices], num_segments: Annotated[Any, TV_SegmentMinV2_Tnumsegments], name=None) -> Annotated[Any, TV_SegmentMinV2_T]: + r"""Computes the minimum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \min_j(data_j)\\) where `min` is over `j` such + that `segment_ids[j] == i`. + + If the minimum is empty for a given segment ID `i`, it outputs the largest + possible value for the specific numeric type, + `output[i] = numeric_limits::max()`. + + Note: That this op is currently only supported with jit_compile=True. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + + The only difference with SegmentMin is the additional input `num_segments`. + This helps in evaluating the output shape in compile time. + `num_segments` should be consistent with segment_ids. + e.g. Max(segment_ids) should be equal to `num_segments` - 1 for a 1-d segment_ids + With inconsistent num_segments, the op still runs. only difference is, + the output takes the size of num_segments irrespective of size of segment_ids and data. + for num_segments less than expected output size, the last elements are ignored + for num_segments more than the expected output size, last elements are assigned + the largest possible value for the specific numeric type. + + For example: + + >>> @tf.function(jit_compile=True) + ... def test(c): + ... return tf.raw_ops.SegmentMinV2(data=c, segment_ids=tf.constant([0, 0, 1]), num_segments=2) + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> test(c).numpy() + array([[1, 2, 2, 1], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + The values must be less than `num_segments`. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentMinV2", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return segment_min_v2_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentMinV2", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentMinV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentMinV2 = tf_export("raw_ops.SegmentMinV2")(_ops.to_raw_op(segment_min_v2)) + + +def segment_min_v2_eager_fallback(data: Annotated[Any, TV_SegmentMinV2_T], segment_ids: Annotated[Any, TV_SegmentMinV2_Tindices], num_segments: Annotated[Any, TV_SegmentMinV2_Tnumsegments], name, ctx) -> Annotated[Any, TV_SegmentMinV2_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"SegmentMinV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentMinV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentProd_T = TypeVar("TV_SegmentProd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentProd_Tindices = TypeVar("TV_SegmentProd_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.segment_prod', v1=['math.segment_prod', 'segment_prod']) +@deprecated_endpoints('segment_prod') +def segment_prod(data: Annotated[Any, TV_SegmentProd_T], segment_ids: Annotated[Any, TV_SegmentProd_Tindices], name=None) -> Annotated[Any, TV_SegmentProd_T]: + r"""Computes the product along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \prod_j data_j\\) where the product is over `j` such + that `segment_ids[j] == i`. + + If the product is empty for a given segment ID `i`, `output[i] = 1`. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + +
+ +
+ + For example: + + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> tf.math.segment_prod(c, tf.constant([0, 0, 1])).numpy() + array([[4, 6, 6, 4], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentProd", name, data, segment_ids) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_segment_prod( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + return segment_prod_eager_fallback( + data, segment_ids, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_prod, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_segment_prod( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentProd", data=data, segment_ids=segment_ids, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_prod, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentProd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentProd = tf_export("raw_ops.SegmentProd")(_ops.to_raw_op(segment_prod)) +_dispatcher_for_segment_prod = segment_prod._tf_type_based_dispatcher.Dispatch + + +def segment_prod_eager_fallback(data: Annotated[Any, TV_SegmentProd_T], segment_ids: Annotated[Any, TV_SegmentProd_Tindices], name, ctx) -> Annotated[Any, TV_SegmentProd_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [data, segment_ids] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SegmentProd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentProd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentProdV2_T = TypeVar("TV_SegmentProdV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentProdV2_Tindices = TypeVar("TV_SegmentProdV2_Tindices", _atypes.Int32, _atypes.Int64) +TV_SegmentProdV2_Tnumsegments = TypeVar("TV_SegmentProdV2_Tnumsegments", _atypes.Int32, _atypes.Int64) + +def segment_prod_v2(data: Annotated[Any, TV_SegmentProdV2_T], segment_ids: Annotated[Any, TV_SegmentProdV2_Tindices], num_segments: Annotated[Any, TV_SegmentProdV2_Tnumsegments], name=None) -> Annotated[Any, TV_SegmentProdV2_T]: + r"""Computes the product along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \prod_j data_j\\) where the product is over `j` such + that `segment_ids[j] == i`. + + If the product is empty for a given segment ID `i`, `output[i] = 1`. + + Note: That this op is currently only supported with jit_compile=True. + + The only difference with SegmentProd is the additional input `num_segments`. + This helps in evaluating the output shape in compile time. + `num_segments` should be consistent with segment_ids. + e.g. Max(segment_ids) - 1 should be equal to `num_segments` for a 1-d segment_ids + With inconsistent num_segments, the op still runs. only difference is, + the output takes the size of num_segments irrespective of size of segment_ids and data. + for num_segments less than expected output size, the last elements are ignored + for num_segments more than the expected output size, last elements are assigned 1. + + For example: + + >>> @tf.function(jit_compile=True) + ... def test(c): + ... return tf.raw_ops.SegmentProdV2(data=c, segment_ids=tf.constant([0, 0, 1]), num_segments=2) + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> test(c).numpy() + array([[4, 6, 6, 4], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + The values must be less than `num_segments`. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentProdV2", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return segment_prod_v2_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentProdV2", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentProdV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentProdV2 = tf_export("raw_ops.SegmentProdV2")(_ops.to_raw_op(segment_prod_v2)) + + +def segment_prod_v2_eager_fallback(data: Annotated[Any, TV_SegmentProdV2_T], segment_ids: Annotated[Any, TV_SegmentProdV2_Tindices], num_segments: Annotated[Any, TV_SegmentProdV2_Tnumsegments], name, ctx) -> Annotated[Any, TV_SegmentProdV2_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"SegmentProdV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentProdV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentSum_T = TypeVar("TV_SegmentSum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentSum_Tindices = TypeVar("TV_SegmentSum_Tindices", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.segment_sum', v1=['math.segment_sum', 'segment_sum']) +@deprecated_endpoints('segment_sum') +def segment_sum(data: Annotated[Any, TV_SegmentSum_T], segment_ids: Annotated[Any, TV_SegmentSum_Tindices], name=None) -> Annotated[Any, TV_SegmentSum_T]: + r"""Computes the sum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \sum_j data_j\\) where sum is over `j` such + that `segment_ids[j] == i`. + + If the sum is empty for a given segment ID `i`, `output[i] = 0`. + + Caution: On CPU, values in `segment_ids` are always validated to be sorted, + and an error is thrown for indices that are not increasing. On GPU, this + does not throw an error for unsorted indices. On GPU, out-of-order indices + result in safe but unspecified behavior, which may include treating + out-of-order indices as the same as a smaller following index. + +
+ +
+ + For example: + + >>> c = tf.constant([[1,2,3,4], [4, 3, 2, 1], [5,6,7,8]]) + >>> tf.math.segment_sum(c, tf.constant([0, 0, 1])).numpy() + array([[5, 5, 5, 5], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentSum", name, data, segment_ids) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_segment_sum( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + return segment_sum_eager_fallback( + data, segment_ids, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_sum, (), dict(data=data, segment_ids=segment_ids, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_segment_sum( + (data, segment_ids, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentSum", data=data, segment_ids=segment_ids, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + segment_sum, (), dict(data=data, segment_ids=segment_ids, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentSum = tf_export("raw_ops.SegmentSum")(_ops.to_raw_op(segment_sum)) +_dispatcher_for_segment_sum = segment_sum._tf_type_based_dispatcher.Dispatch + + +def segment_sum_eager_fallback(data: Annotated[Any, TV_SegmentSum_T], segment_ids: Annotated[Any, TV_SegmentSum_Tindices], name, ctx) -> Annotated[Any, TV_SegmentSum_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [data, segment_ids] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SegmentSum", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SegmentSumV2_T = TypeVar("TV_SegmentSumV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SegmentSumV2_Tindices = TypeVar("TV_SegmentSumV2_Tindices", _atypes.Int32, _atypes.Int64) +TV_SegmentSumV2_Tnumsegments = TypeVar("TV_SegmentSumV2_Tnumsegments", _atypes.Int32, _atypes.Int64) + +def segment_sum_v2(data: Annotated[Any, TV_SegmentSumV2_T], segment_ids: Annotated[Any, TV_SegmentSumV2_Tindices], num_segments: Annotated[Any, TV_SegmentSumV2_Tnumsegments], name=None) -> Annotated[Any, TV_SegmentSumV2_T]: + r"""Computes the sum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output_i = \sum_j data_j\\) where sum is over `j` such + that `segment_ids[j] == i`. + + If the sum is empty for a given segment ID `i`, `output[i] = 0`. + + Note that this op is currently only supported with jit_compile=True. + + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor whose size is equal to the size of `data`'s + first dimension. Values should be sorted and can be repeated. + The values must be less than `num_segments`. + + Caution: The values are always validated to be sorted on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SegmentSumV2", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return segment_sum_v2_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SegmentSumV2", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SegmentSumV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SegmentSumV2 = tf_export("raw_ops.SegmentSumV2")(_ops.to_raw_op(segment_sum_v2)) + + +def segment_sum_v2_eager_fallback(data: Annotated[Any, TV_SegmentSumV2_T], segment_ids: Annotated[Any, TV_SegmentSumV2_Tindices], num_segments: Annotated[Any, TV_SegmentSumV2_Tnumsegments], name, ctx) -> Annotated[Any, TV_SegmentSumV2_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"SegmentSumV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SegmentSumV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Select_T = TypeVar("TV_Select_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def select(condition: Annotated[Any, _atypes.Bool], x: Annotated[Any, TV_Select_T], y: Annotated[Any, TV_Select_T], name=None) -> Annotated[Any, TV_Select_T]: + r"""Selects elements from `x` or `y`, depending on `condition`. + + The `x`, and `y` tensors must all have the same shape, and the + output will also have that shape. + + The `condition` tensor must be a scalar if `x` and `y` are scalars. + If `x` and `y` are vectors or higher rank, then `condition` must be either a + scalar, a vector with size matching the first dimension of `x`, or must have + the same shape as `x`. + + The `condition` tensor acts as a mask that chooses, based on the value at each + element, whether the corresponding element / row in the output should be + taken from `x` (if true) or `y` (if false). + + If `condition` is a vector and `x` and `y` are higher rank matrices, then + it chooses which row (outer dimension) to copy from `x` and `y`. + If `condition` has the same shape as `x` and `y`, then it chooses which + element to copy from `x` and `y`. + + For example: + + ```python + # 'condition' tensor is [[True, False] + # [False, True]] + # 't' is [[1, 2], + # [3, 4]] + # 'e' is [[5, 6], + # [7, 8]] + select(condition, t, e) # => [[1, 6], [7, 4]] + + + # 'condition' tensor is [True, False] + # 't' is [[1, 2], + # [3, 4]] + # 'e' is [[5, 6], + # [7, 8]] + select(condition, t, e) ==> [[1, 2], + [7, 8]] + + ``` + + Args: + condition: A `Tensor` of type `bool`. + x: A `Tensor` which may have the same shape as `condition`. + If `condition` is rank 1, `x` may have higher rank, + but its first dimension must match the size of `condition`. + y: A `Tensor` with the same type and shape as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Select", name, condition, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return select_eager_fallback( + condition, x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Select", condition=condition, t=x, e=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Select", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Select = tf_export("raw_ops.Select")(_ops.to_raw_op(select)) + + +def select_eager_fallback(condition: Annotated[Any, _atypes.Bool], x: Annotated[Any, TV_Select_T], y: Annotated[Any, TV_Select_T], name, ctx) -> Annotated[Any, TV_Select_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, []) + (x, y) = _inputs_T + condition = _ops.convert_to_tensor(condition, _dtypes.bool) + _inputs_flat = [condition, x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Select", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Select", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SelectV2_T = TypeVar("TV_SelectV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def select_v2(condition: Annotated[Any, _atypes.Bool], t: Annotated[Any, TV_SelectV2_T], e: Annotated[Any, TV_SelectV2_T], name=None) -> Annotated[Any, TV_SelectV2_T]: + r"""TODO: add doc. + + Args: + condition: A `Tensor` of type `bool`. + t: A `Tensor`. + e: A `Tensor`. Must have the same type as `t`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SelectV2", name, condition, t, e) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return select_v2_eager_fallback( + condition, t, e, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SelectV2", condition=condition, t=t, e=e, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SelectV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SelectV2 = tf_export("raw_ops.SelectV2")(_ops.to_raw_op(select_v2)) + + +def select_v2_eager_fallback(condition: Annotated[Any, _atypes.Bool], t: Annotated[Any, TV_SelectV2_T], e: Annotated[Any, TV_SelectV2_T], name, ctx) -> Annotated[Any, TV_SelectV2_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([t, e], ctx, []) + (t, e) = _inputs_T + condition = _ops.convert_to_tensor(condition, _dtypes.bool) + _inputs_flat = [condition, t, e] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SelectV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SelectV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sigmoid_T = TypeVar("TV_Sigmoid_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def sigmoid(x: Annotated[Any, TV_Sigmoid_T], name=None) -> Annotated[Any, TV_Sigmoid_T]: + r"""Computes sigmoid of `x` element-wise. + + Specifically, `y = 1 / (1 + exp(-x))`. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sigmoid", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sigmoid_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sigmoid", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sigmoid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sigmoid = tf_export("raw_ops.Sigmoid")(_ops.to_raw_op(sigmoid)) + + +def sigmoid_eager_fallback(x: Annotated[Any, TV_Sigmoid_T], name, ctx) -> Annotated[Any, TV_Sigmoid_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sigmoid", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sigmoid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SigmoidGrad_T = TypeVar("TV_SigmoidGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def sigmoid_grad(y: Annotated[Any, TV_SigmoidGrad_T], dy: Annotated[Any, TV_SigmoidGrad_T], name=None) -> Annotated[Any, TV_SigmoidGrad_T]: + r"""Computes the gradient of the sigmoid of `x` wrt its input. + + Specifically, `grad = dy * y * (1 - y)`, where `y = sigmoid(x)`, and + `dy` is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SigmoidGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sigmoid_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SigmoidGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SigmoidGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SigmoidGrad = tf_export("raw_ops.SigmoidGrad")(_ops.to_raw_op(sigmoid_grad)) + + +def sigmoid_grad_eager_fallback(y: Annotated[Any, TV_SigmoidGrad_T], dy: Annotated[Any, TV_SigmoidGrad_T], name, ctx) -> Annotated[Any, TV_SigmoidGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SigmoidGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SigmoidGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sign_T = TypeVar("TV_Sign_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8) + +def sign(x: Annotated[Any, TV_Sign_T], name=None) -> Annotated[Any, TV_Sign_T]: + r"""Returns an element-wise indication of the sign of a number. + + `y = sign(x) = -1` if `x < 0`; 0 if `x == 0`; 1 if `x > 0`. + + For complex numbers, `y = sign(x) = x / |x|` if `x != 0`, otherwise `y = 0`. + + Example usage: + >>> tf.math.sign([0., 2., -3.]) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sign", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sign_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sign", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sign = tf_export("raw_ops.Sign")(_ops.to_raw_op(sign)) + + +def sign_eager_fallback(x: Annotated[Any, TV_Sign_T], name, ctx) -> Annotated[Any, TV_Sign_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sign", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sin_T = TypeVar("TV_Sin_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.sin', 'sin') +def sin(x: Annotated[Any, TV_Sin_T], name=None) -> Annotated[Any, TV_Sin_T]: + r"""Computes sine of x element-wise. + + Given an input tensor, this function computes sine of every + element in the tensor. Input range is `(-inf, inf)` and + output range is `[-1,1]`. + + ```python + x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 200, 10, float("inf")]) + tf.math.sin(x) ==> [nan -0.4121185 -0.47942555 0.84147096 0.9320391 -0.87329733 -0.54402107 nan] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sin", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sin( + (x, name,), None) + if _result is not NotImplemented: + return _result + return sin_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sin, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sin( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sin", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sin, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sin = tf_export("raw_ops.Sin")(_ops.to_raw_op(sin)) +_dispatcher_for_sin = sin._tf_type_based_dispatcher.Dispatch + + +def sin_eager_fallback(x: Annotated[Any, TV_Sin_T], name, ctx) -> Annotated[Any, TV_Sin_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sin", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sinh_T = TypeVar("TV_Sinh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.sinh', 'sinh') +def sinh(x: Annotated[Any, TV_Sinh_T], name=None) -> Annotated[Any, TV_Sinh_T]: + r"""Computes hyperbolic sine of x element-wise. + + Given an input tensor, this function computes hyperbolic sine of every + element in the tensor. Input range is `[-inf,inf]` and output range + is `[-inf,inf]`. + + ```python + x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 2, 10, float("inf")]) + tf.math.sinh(x) ==> [-inf -4.0515420e+03 -5.2109528e-01 1.1752012e+00 1.5094614e+00 3.6268604e+00 1.1013232e+04 inf] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sinh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sinh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return sinh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sinh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sinh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sinh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sinh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sinh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sinh = tf_export("raw_ops.Sinh")(_ops.to_raw_op(sinh)) +_dispatcher_for_sinh = sinh._tf_type_based_dispatcher.Dispatch + + +def sinh_eager_fallback(x: Annotated[Any, TV_Sinh_T], name, ctx) -> Annotated[Any, TV_Sinh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sinh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sinh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SobolSample_dtype = TypeVar("TV_SobolSample_dtype", _atypes.Float32, _atypes.Float64) + +def sobol_sample(dim: Annotated[Any, _atypes.Int32], num_results: Annotated[Any, _atypes.Int32], skip: Annotated[Any, _atypes.Int32], dtype:TV_SobolSample_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_SobolSample_dtype]: + r"""Generates points from the Sobol sequence. + + Creates a Sobol sequence with `num_results` samples. Each sample has dimension + `dim`. Skips the first `skip` samples. + + Args: + dim: A `Tensor` of type `int32`. + Positive scalar `Tensor` representing each sample's dimension. + num_results: A `Tensor` of type `int32`. + Positive scalar `Tensor` of dtype int32. The number of Sobol points to return + in the output. + skip: A `Tensor` of type `int32`. + Positive scalar `Tensor` of dtype int32. The number of initial points of the + Sobol sequence to skip. + dtype: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the sample. One of: `float32` or `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SobolSample", name, dim, num_results, skip, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sobol_sample_eager_fallback( + dim, num_results, skip, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SobolSample", dim=dim, num_results=num_results, skip=skip, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SobolSample", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SobolSample = tf_export("raw_ops.SobolSample")(_ops.to_raw_op(sobol_sample)) + + +def sobol_sample_eager_fallback(dim: Annotated[Any, _atypes.Int32], num_results: Annotated[Any, _atypes.Int32], skip: Annotated[Any, _atypes.Int32], dtype: TV_SobolSample_dtype, name, ctx) -> Annotated[Any, TV_SobolSample_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + dim = _ops.convert_to_tensor(dim, _dtypes.int32) + num_results = _ops.convert_to_tensor(num_results, _dtypes.int32) + skip = _ops.convert_to_tensor(skip, _dtypes.int32) + _inputs_flat = [dim, num_results, skip] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"SobolSample", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SobolSample", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseBincount_Tidx = TypeVar("TV_SparseBincount_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseBincount_T = TypeVar("TV_SparseBincount_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def sparse_bincount(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseBincount_Tidx], dense_shape: Annotated[Any, _atypes.Int64], size: Annotated[Any, TV_SparseBincount_Tidx], weights: Annotated[Any, TV_SparseBincount_T], binary_output:bool=False, name=None) -> Annotated[Any, TV_SparseBincount_T]: + r"""Counts the number of occurrences of each value in an integer array. + + Outputs a vector with length `size` and the same dtype as `weights`. If + `weights` are empty, then index `i` stores the number of times the value `i` is + counted in `arr`. If `weights` are non-empty, then index `i` stores the sum of + the value in `weights` at each index where the corresponding value in `arr` is + `i`. + + Values in `arr` outside of the range [0, size) are ignored. + + Args: + indices: A `Tensor` of type `int64`. 2D int64 `Tensor`. + values: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1D int `Tensor`. + dense_shape: A `Tensor` of type `int64`. 1D int64 `Tensor`. + size: A `Tensor`. Must have the same type as `values`. + non-negative int scalar `Tensor`. + weights: A `Tensor`. Must be one of the following types: `int32`, `int64`, `float32`, `float64`. + is an int32, int64, float32, or float64 `Tensor` with the same + shape as `input`, or a length-0 `Tensor`, in which case it acts as all weights + equal to 1. + binary_output: An optional `bool`. Defaults to `False`. + bool; Whether the kernel should count the appearance or number of occurrences. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `weights`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseBincount", name, indices, values, dense_shape, size, + weights, "binary_output", binary_output) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_bincount_eager_fallback( + indices, values, dense_shape, size, weights, + binary_output=binary_output, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseBincount", indices=indices, values=values, + dense_shape=dense_shape, size=size, weights=weights, + binary_output=binary_output, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tidx", _op._get_attr_type("Tidx"), "T", + _op._get_attr_type("T"), "binary_output", + _op._get_attr_bool("binary_output")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseBincount = tf_export("raw_ops.SparseBincount")(_ops.to_raw_op(sparse_bincount)) + + +def sparse_bincount_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseBincount_Tidx], dense_shape: Annotated[Any, _atypes.Int64], size: Annotated[Any, TV_SparseBincount_Tidx], weights: Annotated[Any, TV_SparseBincount_T], binary_output: bool, name, ctx) -> Annotated[Any, TV_SparseBincount_T]: + if binary_output is None: + binary_output = False + binary_output = _execute.make_bool(binary_output, "binary_output") + _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([values, size], ctx, [_dtypes.int32, _dtypes.int64, ]) + (values, size) = _inputs_Tidx + _attr_T, (weights,) = _execute.args_to_matching_eager([weights], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.float32, _dtypes.float64, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [indices, values, dense_shape, size, weights] + _attrs = ("Tidx", _attr_Tidx, "T", _attr_T, "binary_output", binary_output) + _result = _execute.execute(b"SparseBincount", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseBincount", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatMul_Ta = TypeVar("TV_SparseMatMul_Ta", _atypes.BFloat16, _atypes.Float32) +TV_SparseMatMul_Tb = TypeVar("TV_SparseMatMul_Tb", _atypes.BFloat16, _atypes.Float32) + +def sparse_mat_mul(a: Annotated[Any, TV_SparseMatMul_Ta], b: Annotated[Any, TV_SparseMatMul_Tb], transpose_a:bool=False, transpose_b:bool=False, a_is_sparse:bool=False, b_is_sparse:bool=False, name=None) -> Annotated[Any, _atypes.Float32]: + r"""Multiply matrix "a" by matrix "b". + + The inputs must be two-dimensional matrices and the inner dimension of "a" must + match the outer dimension of "b". Both "a" and "b" must be `Tensor`s not + `SparseTensor`s. This op is optimized for the case where at least one of "a" or + "b" is sparse, in the sense that they have a large proportion of zero values. + The breakeven for using this versus a dense matrix multiply on one platform was + 30% zero values in the sparse matrix. + + The gradient computation of this operation will only take advantage of sparsity + in the input gradient when that gradient comes from a Relu. + + Args: + a: A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. + b: A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. + transpose_a: An optional `bool`. Defaults to `False`. + transpose_b: An optional `bool`. Defaults to `False`. + a_is_sparse: An optional `bool`. Defaults to `False`. + b_is_sparse: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatMul", name, a, b, "transpose_a", transpose_a, + "transpose_b", transpose_b, "a_is_sparse", a_is_sparse, "b_is_sparse", + b_is_sparse) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_mat_mul_eager_fallback( + a, b, transpose_a=transpose_a, transpose_b=transpose_b, + a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if a_is_sparse is None: + a_is_sparse = False + a_is_sparse = _execute.make_bool(a_is_sparse, "a_is_sparse") + if b_is_sparse is None: + b_is_sparse = False + b_is_sparse = _execute.make_bool(b_is_sparse, "b_is_sparse") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatMul", a=a, b=b, transpose_a=transpose_a, + transpose_b=transpose_b, a_is_sparse=a_is_sparse, + b_is_sparse=b_is_sparse, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("transpose_a", _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "a_is_sparse", + _op._get_attr_bool("a_is_sparse"), "b_is_sparse", + _op._get_attr_bool("b_is_sparse"), "Ta", + _op._get_attr_type("Ta"), "Tb", _op._get_attr_type("Tb")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatMul = tf_export("raw_ops.SparseMatMul")(_ops.to_raw_op(sparse_mat_mul)) + + +def sparse_mat_mul_eager_fallback(a: Annotated[Any, TV_SparseMatMul_Ta], b: Annotated[Any, TV_SparseMatMul_Tb], transpose_a: bool, transpose_b: bool, a_is_sparse: bool, b_is_sparse: bool, name, ctx) -> Annotated[Any, _atypes.Float32]: + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if a_is_sparse is None: + a_is_sparse = False + a_is_sparse = _execute.make_bool(a_is_sparse, "a_is_sparse") + if b_is_sparse is None: + b_is_sparse = False + b_is_sparse = _execute.make_bool(b_is_sparse, "b_is_sparse") + _attr_Ta, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.float32, _dtypes.bfloat16, ], _dtypes.float32) + _attr_Tb, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.float32, _dtypes.bfloat16, ], _dtypes.float32) + _inputs_flat = [a, b] + _attrs = ("transpose_a", transpose_a, "transpose_b", transpose_b, + "a_is_sparse", a_is_sparse, "b_is_sparse", b_is_sparse, "Ta", _attr_Ta, + "Tb", _attr_Tb) + _result = _execute.execute(b"SparseMatMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentMean_T = TypeVar("TV_SparseSegmentMean_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentMean_Tidx = TypeVar("TV_SparseSegmentMean_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentMean_Tsegmentids = TypeVar("TV_SparseSegmentMean_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_mean(data: Annotated[Any, TV_SparseSegmentMean_T], indices: Annotated[Any, TV_SparseSegmentMean_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMean_Tsegmentids], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentMean_T]: + r"""Computes the mean along sparse segments of a tensor. + + See `tf.sparse.segment_sum` for usage examples. + + Like `SegmentMean`, but `segment_ids` can have rank less than `data`'s first + dimension, selecting a subset of dimension 0, specified by `indices`. + + Args: + data: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentMean", name, data, indices, segment_ids, + "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_mean_eager_fallback( + data, indices, segment_ids, sparse_gradient=sparse_gradient, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentMean", data=data, indices=indices, + segment_ids=segment_ids, + sparse_gradient=sparse_gradient, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentMean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentMean = tf_export("raw_ops.SparseSegmentMean")(_ops.to_raw_op(sparse_segment_mean)) + + +def sparse_segment_mean_eager_fallback(data: Annotated[Any, TV_SparseSegmentMean_T], indices: Annotated[Any, TV_SparseSegmentMean_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMean_Tsegmentids], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentMean_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids, "sparse_gradient", sparse_gradient) + _result = _execute.execute(b"SparseSegmentMean", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentMean", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentMeanGrad_T = TypeVar("TV_SparseSegmentMeanGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentMeanGrad_Tidx = TypeVar("TV_SparseSegmentMeanGrad_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentMeanGrad_Tsegmentids = TypeVar("TV_SparseSegmentMeanGrad_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_mean_grad(grad: Annotated[Any, TV_SparseSegmentMeanGrad_T], indices: Annotated[Any, TV_SparseSegmentMeanGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_SparseSegmentMeanGrad_T]: + r"""Computes gradients for SparseSegmentMean. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is output_dim0. + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentMean op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentMean op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentMean op. + output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentMean op. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentMeanGrad", name, grad, indices, segment_ids, + output_dim0) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_mean_grad_eager_fallback( + grad, indices, segment_ids, output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentMeanGrad", grad=grad, indices=indices, + segment_ids=segment_ids, + output_dim0=output_dim0, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentMeanGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentMeanGrad = tf_export("raw_ops.SparseSegmentMeanGrad")(_ops.to_raw_op(sparse_segment_mean_grad)) + + +def sparse_segment_mean_grad_eager_fallback(grad: Annotated[Any, TV_SparseSegmentMeanGrad_T], indices: Annotated[Any, TV_SparseSegmentMeanGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_SparseSegmentMeanGrad_T]: + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + output_dim0 = _ops.convert_to_tensor(output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentMeanGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentMeanGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseSegmentMeanGradV2Output = collections.namedtuple( + "SparseSegmentMeanGradV2", + ["output", "sorted_unique_indices"]) + + +TV_SparseSegmentMeanGradV2_T = TypeVar("TV_SparseSegmentMeanGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentMeanGradV2_Tidx = TypeVar("TV_SparseSegmentMeanGradV2_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentMeanGradV2_Tsegmentids = TypeVar("TV_SparseSegmentMeanGradV2_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_mean_grad_v2(grad: Annotated[Any, TV_SparseSegmentMeanGradV2_T], indices: Annotated[Any, TV_SparseSegmentMeanGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name=None): + r"""Computes gradients for SparseSegmentMean. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is the number of unique indexes in "indices". Also returns vector + "sorted_unique_indices" containing the corresponding indexes from "indices". + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentMean op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentMean op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentMean op. + dense_output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentMean op. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, sorted_unique_indices). + + output: A `Tensor`. Has the same type as `grad`. + sorted_unique_indices: A `Tensor`. Has the same type as `indices`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentMeanGradV2", name, grad, indices, segment_ids, + dense_output_dim0) + _result = _SparseSegmentMeanGradV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_mean_grad_v2_eager_fallback( + grad, indices, segment_ids, dense_output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentMeanGradV2", grad=grad, indices=indices, + segment_ids=segment_ids, + dense_output_dim0=dense_output_dim0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentMeanGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentMeanGradV2Output._make(_result) + return _result + +SparseSegmentMeanGradV2 = tf_export("raw_ops.SparseSegmentMeanGradV2")(_ops.to_raw_op(sparse_segment_mean_grad_v2)) + + +def sparse_segment_mean_grad_v2_eager_fallback(grad: Annotated[Any, TV_SparseSegmentMeanGradV2_T], indices: Annotated[Any, TV_SparseSegmentMeanGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name, ctx): + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + dense_output_dim0 = _ops.convert_to_tensor(dense_output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, dense_output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentMeanGradV2", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentMeanGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentMeanGradV2Output._make(_result) + return _result + + +TV_SparseSegmentMeanWithNumSegments_T = TypeVar("TV_SparseSegmentMeanWithNumSegments_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentMeanWithNumSegments_Tidx = TypeVar("TV_SparseSegmentMeanWithNumSegments_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentMeanWithNumSegments_Tnumsegments = TypeVar("TV_SparseSegmentMeanWithNumSegments_Tnumsegments", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentMeanWithNumSegments_Tsegmentids = TypeVar("TV_SparseSegmentMeanWithNumSegments_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_mean_with_num_segments(data: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tnumsegments], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentMeanWithNumSegments_T]: + r"""Computes the mean along sparse segments of a tensor. + + Like `SparseSegmentMean`, but allows missing ids in `segment_ids`. If an id is + missing, the `output` tensor at that position will be zeroed. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Args: + data: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Should equal the number of distinct segment IDs. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentMeanWithNumSegments", name, data, indices, + segment_ids, num_segments, "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_mean_with_num_segments_eager_fallback( + data, indices, segment_ids, num_segments, + sparse_gradient=sparse_gradient, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentMeanWithNumSegments", data=data, indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tnumsegments", + _op._get_attr_type("Tnumsegments"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentMeanWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentMeanWithNumSegments = tf_export("raw_ops.SparseSegmentMeanWithNumSegments")(_ops.to_raw_op(sparse_segment_mean_with_num_segments)) + + +def sparse_segment_mean_with_num_segments_eager_fallback(data: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentMeanWithNumSegments_Tnumsegments], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentMeanWithNumSegments_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", + _attr_Tnumsegments, "Tsegmentids", _attr_Tsegmentids, "sparse_gradient", + sparse_gradient) + _result = _execute.execute(b"SparseSegmentMeanWithNumSegments", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentMeanWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentSqrtN_T = TypeVar("TV_SparseSegmentSqrtN_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSqrtN_Tidx = TypeVar("TV_SparseSegmentSqrtN_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSqrtN_Tsegmentids = TypeVar("TV_SparseSegmentSqrtN_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sqrt_n(data: Annotated[Any, TV_SparseSegmentSqrtN_T], indices: Annotated[Any, TV_SparseSegmentSqrtN_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtN_Tsegmentids], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentSqrtN_T]: + r"""Computes the sum along sparse segments of a tensor divided by the sqrt of N. + + N is the size of the segment being reduced. + + See `tf.sparse.segment_sum` for usage examples. + + Args: + data: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSqrtN", name, data, indices, segment_ids, + "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sqrt_n_eager_fallback( + data, indices, segment_ids, sparse_gradient=sparse_gradient, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSqrtN", data=data, indices=indices, + segment_ids=segment_ids, + sparse_gradient=sparse_gradient, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSqrtN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSqrtN = tf_export("raw_ops.SparseSegmentSqrtN")(_ops.to_raw_op(sparse_segment_sqrt_n)) + + +def sparse_segment_sqrt_n_eager_fallback(data: Annotated[Any, TV_SparseSegmentSqrtN_T], indices: Annotated[Any, TV_SparseSegmentSqrtN_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtN_Tsegmentids], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentSqrtN_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids, "sparse_gradient", sparse_gradient) + _result = _execute.execute(b"SparseSegmentSqrtN", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSqrtN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentSqrtNGrad_T = TypeVar("TV_SparseSegmentSqrtNGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSqrtNGrad_Tidx = TypeVar("TV_SparseSegmentSqrtNGrad_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSqrtNGrad_Tsegmentids = TypeVar("TV_SparseSegmentSqrtNGrad_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sqrt_n_grad(grad: Annotated[Any, TV_SparseSegmentSqrtNGrad_T], indices: Annotated[Any, TV_SparseSegmentSqrtNGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_SparseSegmentSqrtNGrad_T]: + r"""Computes gradients for SparseSegmentSqrtN. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is output_dim0. + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentSqrtN op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentSqrtN op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentSqrtN op. + output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentSqrtN op. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSqrtNGrad", name, grad, indices, segment_ids, + output_dim0) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sqrt_n_grad_eager_fallback( + grad, indices, segment_ids, output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSqrtNGrad", grad=grad, indices=indices, + segment_ids=segment_ids, + output_dim0=output_dim0, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSqrtNGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSqrtNGrad = tf_export("raw_ops.SparseSegmentSqrtNGrad")(_ops.to_raw_op(sparse_segment_sqrt_n_grad)) + + +def sparse_segment_sqrt_n_grad_eager_fallback(grad: Annotated[Any, TV_SparseSegmentSqrtNGrad_T], indices: Annotated[Any, TV_SparseSegmentSqrtNGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_SparseSegmentSqrtNGrad_T]: + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + output_dim0 = _ops.convert_to_tensor(output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentSqrtNGrad", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSqrtNGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseSegmentSqrtNGradV2Output = collections.namedtuple( + "SparseSegmentSqrtNGradV2", + ["output", "sorted_unique_indices"]) + + +TV_SparseSegmentSqrtNGradV2_T = TypeVar("TV_SparseSegmentSqrtNGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSqrtNGradV2_Tidx = TypeVar("TV_SparseSegmentSqrtNGradV2_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSqrtNGradV2_Tsegmentids = TypeVar("TV_SparseSegmentSqrtNGradV2_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sqrt_n_grad_v2(grad: Annotated[Any, TV_SparseSegmentSqrtNGradV2_T], indices: Annotated[Any, TV_SparseSegmentSqrtNGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name=None): + r"""Computes gradients for SparseSegmentSqrtN. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is the number of unique indexes in "indices". Also returns vector + "sorted_unique_indices" containing the corresponding indexes from "indices". + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentSqrtN op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentSqrtN op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentSqrtN op. + dense_output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentSqrtN op. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, sorted_unique_indices). + + output: A `Tensor`. Has the same type as `grad`. + sorted_unique_indices: A `Tensor`. Has the same type as `indices`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSqrtNGradV2", name, grad, indices, segment_ids, + dense_output_dim0) + _result = _SparseSegmentSqrtNGradV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sqrt_n_grad_v2_eager_fallback( + grad, indices, segment_ids, dense_output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSqrtNGradV2", grad=grad, indices=indices, + segment_ids=segment_ids, + dense_output_dim0=dense_output_dim0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSqrtNGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentSqrtNGradV2Output._make(_result) + return _result + +SparseSegmentSqrtNGradV2 = tf_export("raw_ops.SparseSegmentSqrtNGradV2")(_ops.to_raw_op(sparse_segment_sqrt_n_grad_v2)) + + +def sparse_segment_sqrt_n_grad_v2_eager_fallback(grad: Annotated[Any, TV_SparseSegmentSqrtNGradV2_T], indices: Annotated[Any, TV_SparseSegmentSqrtNGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name, ctx): + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + dense_output_dim0 = _ops.convert_to_tensor(dense_output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, dense_output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentSqrtNGradV2", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSqrtNGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentSqrtNGradV2Output._make(_result) + return _result + + +TV_SparseSegmentSqrtNWithNumSegments_T = TypeVar("TV_SparseSegmentSqrtNWithNumSegments_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSqrtNWithNumSegments_Tidx = TypeVar("TV_SparseSegmentSqrtNWithNumSegments_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSqrtNWithNumSegments_Tnumsegments = TypeVar("TV_SparseSegmentSqrtNWithNumSegments_Tnumsegments", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSqrtNWithNumSegments_Tsegmentids = TypeVar("TV_SparseSegmentSqrtNWithNumSegments_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sqrt_n_with_num_segments(data: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tnumsegments], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_T]: + r"""Computes the sum along sparse segments of a tensor divided by the sqrt of N. + + N is the size of the segment being reduced. + + Like `SparseSegmentSqrtN`, but allows missing ids in `segment_ids`. If an id is + missing, the `output` tensor at that position will be zeroed. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Args: + data: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Should equal the number of distinct segment IDs. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSqrtNWithNumSegments", name, data, indices, + segment_ids, num_segments, "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sqrt_n_with_num_segments_eager_fallback( + data, indices, segment_ids, num_segments, + sparse_gradient=sparse_gradient, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSqrtNWithNumSegments", data=data, indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tnumsegments", + _op._get_attr_type("Tnumsegments"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSqrtNWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSqrtNWithNumSegments = tf_export("raw_ops.SparseSegmentSqrtNWithNumSegments")(_ops.to_raw_op(sparse_segment_sqrt_n_with_num_segments)) + + +def sparse_segment_sqrt_n_with_num_segments_eager_fallback(data: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_Tnumsegments], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentSqrtNWithNumSegments_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", + _attr_Tnumsegments, "Tsegmentids", _attr_Tsegmentids, "sparse_gradient", + sparse_gradient) + _result = _execute.execute(b"SparseSegmentSqrtNWithNumSegments", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSqrtNWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentSum_T = TypeVar("TV_SparseSegmentSum_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseSegmentSum_Tidx = TypeVar("TV_SparseSegmentSum_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSum_Tsegmentids = TypeVar("TV_SparseSegmentSum_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sum(data: Annotated[Any, TV_SparseSegmentSum_T], indices: Annotated[Any, TV_SparseSegmentSum_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSum_Tsegmentids], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentSum_T]: + r"""Computes the sum along sparse segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Like `SegmentSum`, but `segment_ids` can have rank less than `data`'s first + dimension, selecting a subset of dimension 0, specified by `indices`. + + For example: + + ```python + c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) + + # Select two rows, one segment. + tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) + # => [[0 0 0 0]] + + # Select two rows, two segment. + tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) + # => [[ 1 2 3 4] + # [-1 -2 -3 -4]] + + # Select all rows, two segments. + tf.sparse_segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) + # => [[0 0 0 0] + # [5 6 7 8]] + + # Which is equivalent to: + tf.segment_sum(c, tf.constant([0, 0, 1])) + ``` + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSum", name, data, indices, segment_ids, + "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sum_eager_fallback( + data, indices, segment_ids, sparse_gradient=sparse_gradient, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSum", data=data, indices=indices, + segment_ids=segment_ids, + sparse_gradient=sparse_gradient, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSum = tf_export("raw_ops.SparseSegmentSum")(_ops.to_raw_op(sparse_segment_sum)) + + +def sparse_segment_sum_eager_fallback(data: Annotated[Any, TV_SparseSegmentSum_T], indices: Annotated[Any, TV_SparseSegmentSum_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSum_Tsegmentids], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentSum_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids, "sparse_gradient", sparse_gradient) + _result = _execute.execute(b"SparseSegmentSum", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSegmentSumGrad_T = TypeVar("TV_SparseSegmentSumGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSumGrad_Tidx = TypeVar("TV_SparseSegmentSumGrad_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSumGrad_Tsegmentids = TypeVar("TV_SparseSegmentSumGrad_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sum_grad(grad: Annotated[Any, TV_SparseSegmentSumGrad_T], indices: Annotated[Any, TV_SparseSegmentSumGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_SparseSegmentSumGrad_T]: + r"""Computes gradients for SparseSegmentSum. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is output_dim0. + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentSum op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentSum op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentSum op. + output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentSum op. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSumGrad", name, grad, indices, segment_ids, + output_dim0) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sum_grad_eager_fallback( + grad, indices, segment_ids, output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSumGrad", grad=grad, indices=indices, + segment_ids=segment_ids, + output_dim0=output_dim0, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSumGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSumGrad = tf_export("raw_ops.SparseSegmentSumGrad")(_ops.to_raw_op(sparse_segment_sum_grad)) + + +def sparse_segment_sum_grad_eager_fallback(grad: Annotated[Any, TV_SparseSegmentSumGrad_T], indices: Annotated[Any, TV_SparseSegmentSumGrad_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumGrad_Tsegmentids], output_dim0: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_SparseSegmentSumGrad_T]: + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + output_dim0 = _ops.convert_to_tensor(output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentSumGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSumGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseSegmentSumGradV2Output = collections.namedtuple( + "SparseSegmentSumGradV2", + ["output", "sorted_unique_indices"]) + + +TV_SparseSegmentSumGradV2_T = TypeVar("TV_SparseSegmentSumGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSegmentSumGradV2_Tidx = TypeVar("TV_SparseSegmentSumGradV2_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSumGradV2_Tsegmentids = TypeVar("TV_SparseSegmentSumGradV2_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sum_grad_v2(grad: Annotated[Any, TV_SparseSegmentSumGradV2_T], indices: Annotated[Any, TV_SparseSegmentSumGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name=None): + r"""Computes gradients for SparseSegmentSum. + + Returns tensor "output" with same shape as grad, except for dimension 0 whose + value is the number of unique indexes in "indices". Also returns vector + "sorted_unique_indices" containing the corresponding indexes from "indices". + + Args: + grad: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + gradient propagated to the SparseSegmentSum op. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + indices passed to the corresponding SparseSegmentSum op. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + segment_ids passed to the corresponding SparseSegmentSum op. + dense_output_dim0: A `Tensor` of type `int32`. + dimension 0 of "data" passed to SparseSegmentSum op. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, sorted_unique_indices). + + output: A `Tensor`. Has the same type as `grad`. + sorted_unique_indices: A `Tensor`. Has the same type as `indices`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSumGradV2", name, grad, indices, segment_ids, + dense_output_dim0) + _result = _SparseSegmentSumGradV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sum_grad_v2_eager_fallback( + grad, indices, segment_ids, dense_output_dim0, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSumGradV2", grad=grad, indices=indices, + segment_ids=segment_ids, + dense_output_dim0=dense_output_dim0, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tsegmentids", + _op._get_attr_type("Tsegmentids")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSumGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentSumGradV2Output._make(_result) + return _result + +SparseSegmentSumGradV2 = tf_export("raw_ops.SparseSegmentSumGradV2")(_ops.to_raw_op(sparse_segment_sum_grad_v2)) + + +def sparse_segment_sum_grad_v2_eager_fallback(grad: Annotated[Any, TV_SparseSegmentSumGradV2_T], indices: Annotated[Any, TV_SparseSegmentSumGradV2_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumGradV2_Tsegmentids], dense_output_dim0: Annotated[Any, _atypes.Int32], name, ctx): + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + dense_output_dim0 = _ops.convert_to_tensor(dense_output_dim0, _dtypes.int32) + _inputs_flat = [grad, indices, segment_ids, dense_output_dim0] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tsegmentids", + _attr_Tsegmentids) + _result = _execute.execute(b"SparseSegmentSumGradV2", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSumGradV2", _inputs_flat, _attrs, _result) + _result = _SparseSegmentSumGradV2Output._make(_result) + return _result + + +TV_SparseSegmentSumWithNumSegments_T = TypeVar("TV_SparseSegmentSumWithNumSegments_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseSegmentSumWithNumSegments_Tidx = TypeVar("TV_SparseSegmentSumWithNumSegments_Tidx", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSumWithNumSegments_Tnumsegments = TypeVar("TV_SparseSegmentSumWithNumSegments_Tnumsegments", _atypes.Int32, _atypes.Int64) +TV_SparseSegmentSumWithNumSegments_Tsegmentids = TypeVar("TV_SparseSegmentSumWithNumSegments_Tsegmentids", _atypes.Int32, _atypes.Int64) + +def sparse_segment_sum_with_num_segments(data: Annotated[Any, TV_SparseSegmentSumWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tnumsegments], sparse_gradient:bool=False, name=None) -> Annotated[Any, TV_SparseSegmentSumWithNumSegments_T]: + r"""Computes the sum along sparse segments of a tensor. + + Like `SparseSegmentSum`, but allows missing ids in `segment_ids`. If an id is + missing, the `output` tensor at that position will be zeroed. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/sparse#Segmentation) + for an explanation of segments. + + For example: + + ```python + c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) + + tf.sparse_segment_sum_with_num_segments( + c, tf.constant([0, 1]), tf.constant([0, 0]), num_segments=3) + # => [[0 0 0 0] + # [0 0 0 0] + # [0 0 0 0]] + + tf.sparse_segment_sum_with_num_segments(c, + tf.constant([0, 1]), + tf.constant([0, 2], + num_segments=4)) + # => [[ 1 2 3 4] + # [ 0 0 0 0] + # [-1 -2 -3 -4] + # [ 0 0 0 0]] + ``` + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Has same rank as `segment_ids`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1-D tensor. Values should be sorted and can be repeated. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Should equal the number of distinct segment IDs. + sparse_gradient: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSegmentSumWithNumSegments", name, data, indices, + segment_ids, num_segments, "sparse_gradient", sparse_gradient) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_segment_sum_with_num_segments_eager_fallback( + data, indices, segment_ids, num_segments, + sparse_gradient=sparse_gradient, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSegmentSumWithNumSegments", data=data, indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tidx", + _op._get_attr_type("Tidx"), "Tnumsegments", + _op._get_attr_type("Tnumsegments"), "Tsegmentids", + _op._get_attr_type("Tsegmentids"), "sparse_gradient", + _op._get_attr_bool("sparse_gradient")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSegmentSumWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSegmentSumWithNumSegments = tf_export("raw_ops.SparseSegmentSumWithNumSegments")(_ops.to_raw_op(sparse_segment_sum_with_num_segments)) + + +def sparse_segment_sum_with_num_segments_eager_fallback(data: Annotated[Any, TV_SparseSegmentSumWithNumSegments_T], indices: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tidx], segment_ids: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tsegmentids], num_segments: Annotated[Any, TV_SparseSegmentSumWithNumSegments_Tnumsegments], sparse_gradient: bool, name, ctx) -> Annotated[Any, TV_SparseSegmentSumWithNumSegments_T]: + if sparse_gradient is None: + sparse_gradient = False + sparse_gradient = _execute.make_bool(sparse_gradient, "sparse_gradient") + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tsegmentids, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, indices, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tidx", _attr_Tidx, "Tnumsegments", + _attr_Tnumsegments, "Tsegmentids", _attr_Tsegmentids, "sparse_gradient", + sparse_gradient) + _result = _execute.execute(b"SparseSegmentSumWithNumSegments", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSegmentSumWithNumSegments", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sqrt_T = TypeVar("TV_Sqrt_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def sqrt(x: Annotated[Any, TV_Sqrt_T], name=None) -> Annotated[Any, TV_Sqrt_T]: + r"""Computes square root of x element-wise. + + I.e., \\(y = \sqrt{x} = x^{1/2}\\). + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sqrt", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sqrt_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sqrt", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sqrt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sqrt = tf_export("raw_ops.Sqrt")(_ops.to_raw_op(sqrt)) + + +def sqrt_eager_fallback(x: Annotated[Any, TV_Sqrt_T], name, ctx) -> Annotated[Any, TV_Sqrt_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sqrt", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sqrt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SqrtGrad_T = TypeVar("TV_SqrtGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def sqrt_grad(y: Annotated[Any, TV_SqrtGrad_T], dy: Annotated[Any, TV_SqrtGrad_T], name=None) -> Annotated[Any, TV_SqrtGrad_T]: + r"""Computes the gradient for the sqrt of `x` wrt its input. + + Specifically, `grad = dy * 0.5 / y`, where `y = sqrt(x)`, and `dy` + is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SqrtGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sqrt_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SqrtGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SqrtGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SqrtGrad = tf_export("raw_ops.SqrtGrad")(_ops.to_raw_op(sqrt_grad)) + + +def sqrt_grad_eager_fallback(y: Annotated[Any, TV_SqrtGrad_T], dy: Annotated[Any, TV_SqrtGrad_T], name, ctx) -> Annotated[Any, TV_SqrtGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SqrtGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SqrtGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Square_T = TypeVar("TV_Square_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.square', 'square') +def square(x: Annotated[Any, TV_Square_T], name=None) -> Annotated[Any, TV_Square_T]: + r"""Computes square of x element-wise. + + I.e., \\(y = x * x = x^2\\). + + >>> tf.math.square([-2., 0., 3.]) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Square", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_square( + (x, name,), None) + if _result is not NotImplemented: + return _result + return square_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + square, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_square( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Square", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + square, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Square", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Square = tf_export("raw_ops.Square")(_ops.to_raw_op(square)) +_dispatcher_for_square = square._tf_type_based_dispatcher.Dispatch + + +def square_eager_fallback(x: Annotated[Any, TV_Square_T], name, ctx) -> Annotated[Any, TV_Square_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.uint32, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Square", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Square", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SquaredDifference_T = TypeVar("TV_SquaredDifference_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.squared_difference', v1=['math.squared_difference', 'squared_difference']) +@deprecated_endpoints('squared_difference') +def squared_difference(x: Annotated[Any, TV_SquaredDifference_T], y: Annotated[Any, TV_SquaredDifference_T], name=None) -> Annotated[Any, TV_SquaredDifference_T]: + r"""Returns conj(x - y)(x - y) element-wise. + + *NOTE*: `math.squared_difference` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SquaredDifference", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_squared_difference( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return squared_difference_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + squared_difference, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_squared_difference( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SquaredDifference", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + squared_difference, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SquaredDifference", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SquaredDifference = tf_export("raw_ops.SquaredDifference")(_ops.to_raw_op(squared_difference)) +_dispatcher_for_squared_difference = squared_difference._tf_type_based_dispatcher.Dispatch + + +def squared_difference_eager_fallback(x: Annotated[Any, TV_SquaredDifference_T], y: Annotated[Any, TV_SquaredDifference_T], name, ctx) -> Annotated[Any, TV_SquaredDifference_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SquaredDifference", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SquaredDifference", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sub_T = TypeVar("TV_Sub_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sub(x: Annotated[Any, TV_Sub_T], y: Annotated[Any, TV_Sub_T], name=None) -> Annotated[Any, TV_Sub_T]: + r"""Returns x - y element-wise. + + *NOTE*: `tf.subtract` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Both input and output have a range `(-inf, inf)`. + + Example usages below. + + Subtract operation between an array and a scalar: + + >>> x = [1, 2, 3, 4, 5] + >>> y = 1 + >>> tf.subtract(x, y) + + >>> tf.subtract(y, x) + + + Note that binary `-` operator can be used instead: + + >>> x = tf.convert_to_tensor([1, 2, 3, 4, 5]) + >>> y = tf.convert_to_tensor(1) + >>> x - y + + + Subtract operation between an array and a tensor of same shape: + + >>> x = [1, 2, 3, 4, 5] + >>> y = tf.constant([5, 4, 3, 2, 1]) + >>> tf.subtract(y, x) + + + **Warning**: If one of the inputs (`x` or `y`) is a tensor and the other is a + non-tensor, the non-tensor input will adopt (or get casted to) the data type + of the tensor input. This can potentially cause unwanted overflow or underflow + conversion. + + For example, + + >>> x = tf.constant([1, 2], dtype=tf.int8) + >>> y = [2**8 + 1, 2**8 + 2] + >>> tf.subtract(x, y) + + + When subtracting two input values of different shapes, `tf.subtract` follows the + [general broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules) + . The two input array shapes are compared element-wise. Starting with the + trailing dimensions, the two dimensions either have to be equal or one of them + needs to be `1`. + + For example, + + >>> x = np.ones(6).reshape(2, 3, 1) + >>> y = np.ones(6).reshape(2, 1, 3) + >>> tf.subtract(x, y) + + + Example with inputs of different dimensions: + + >>> x = np.ones(6).reshape(2, 3, 1) + >>> y = np.ones(6).reshape(1, 6) + >>> tf.subtract(x, y) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `uint32`, `uint64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sub", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sub_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sub", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sub = tf_export("raw_ops.Sub")(_ops.to_raw_op(sub)) + + +def sub_eager_fallback(x: Annotated[Any, TV_Sub_T], y: Annotated[Any, TV_Sub_T], name, ctx) -> Annotated[Any, TV_Sub_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, _dtypes.uint32, _dtypes.uint64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Sub", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Sum_T = TypeVar("TV_Sum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Sum_Tidx = TypeVar("TV_Sum_Tidx", _atypes.Int32, _atypes.Int64) + +def _sum(input: Annotated[Any, TV_Sum_T], axis: Annotated[Any, TV_Sum_Tidx], keep_dims:bool=False, name=None) -> Annotated[Any, TV_Sum_T]: + r"""Computes the sum of elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keep_dims` is true, the reduced dimensions are + retained with length 1. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The tensor to reduce. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The dimensions to reduce. Must be in the range + `[-rank(input), rank(input))`. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Sum", name, input, axis, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _sum_eager_fallback( + input, axis, keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Sum", input=input, reduction_indices=axis, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T"), "Tidx", _op._get_attr_type("Tidx")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Sum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Sum = tf_export("raw_ops.Sum")(_ops.to_raw_op(_sum)) + + +def _sum_eager_fallback(input: Annotated[Any, TV_Sum_T], axis: Annotated[Any, TV_Sum_Tidx], keep_dims: bool, name, ctx) -> Annotated[Any, TV_Sum_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, axis] + _attrs = ("keep_dims", keep_dims, "T", _attr_T, "Tidx", _attr_Tidx) + _result = _execute.execute(b"Sum", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Sum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Tan_T = TypeVar("TV_Tan_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.tan', 'tan') +def tan(x: Annotated[Any, TV_Tan_T], name=None) -> Annotated[Any, TV_Tan_T]: + r"""Computes tan of x element-wise. + + Given an input tensor, this function computes tangent of every + element in the tensor. Input range is `(-inf, inf)` and + output range is `(-inf, inf)`. If input lies outside the boundary, `nan` + is returned. + + ```python + x = tf.constant([-float("inf"), -9, -0.5, 1, 1.2, 200, 10000, float("inf")]) + tf.math.tan(x) ==> [nan 0.45231566 -0.5463025 1.5574077 2.572152 -1.7925274 0.32097113 nan] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Tan", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tan( + (x, name,), None) + if _result is not NotImplemented: + return _result + return tan_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tan( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Tan", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tan, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Tan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Tan = tf_export("raw_ops.Tan")(_ops.to_raw_op(tan)) +_dispatcher_for_tan = tan._tf_type_based_dispatcher.Dispatch + + +def tan_eager_fallback(x: Annotated[Any, TV_Tan_T], name, ctx) -> Annotated[Any, TV_Tan_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Tan", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Tan", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Tanh_T = TypeVar("TV_Tanh_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.tanh', 'nn.tanh', 'tanh') +def tanh(x: Annotated[Any, TV_Tanh_T], name=None) -> Annotated[Any, TV_Tanh_T]: + r"""Computes hyperbolic tangent of `x` element-wise. + + Given an input tensor, this function computes hyperbolic tangent of every + element in the tensor. Input range is `[-inf, inf]` and + output range is `[-1,1]`. + + >>> x = tf.constant([-float("inf"), -5, -0.5, 1, 1.2, 2, 3, float("inf")]) + >>> tf.math.tanh(x) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Tanh", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_tanh( + (x, name,), None) + if _result is not NotImplemented: + return _result + return tanh_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tanh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_tanh( + (x, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Tanh", x=x, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + tanh, (), dict(x=x, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Tanh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Tanh = tf_export("raw_ops.Tanh")(_ops.to_raw_op(tanh)) +_dispatcher_for_tanh = tanh._tf_type_based_dispatcher.Dispatch + + +def tanh_eager_fallback(x: Annotated[Any, TV_Tanh_T], name, ctx) -> Annotated[Any, TV_Tanh_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Tanh", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Tanh", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TanhGrad_T = TypeVar("TV_TanhGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def tanh_grad(y: Annotated[Any, TV_TanhGrad_T], dy: Annotated[Any, TV_TanhGrad_T], name=None) -> Annotated[Any, TV_TanhGrad_T]: + r"""Computes the gradient for the tanh of `x` wrt its input. + + Specifically, `grad = dy * (1 - y*y)`, where `y = tanh(x)`, and `dy` + is the corresponding input gradient. + + Args: + y: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`. + dy: A `Tensor`. Must have the same type as `y`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `y`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TanhGrad", name, y, dy) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tanh_grad_eager_fallback( + y, dy, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TanhGrad", y=y, dy=dy, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TanhGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TanhGrad = tf_export("raw_ops.TanhGrad")(_ops.to_raw_op(tanh_grad)) + + +def tanh_grad_eager_fallback(y: Annotated[Any, TV_TanhGrad_T], dy: Annotated[Any, TV_TanhGrad_T], name, ctx) -> Annotated[Any, TV_TanhGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([y, dy], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (y, dy) = _inputs_T + _inputs_flat = [y, dy] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TanhGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TanhGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TruncateDiv_T = TypeVar("TV_TruncateDiv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('truncatediv') +def truncate_div(x: Annotated[Any, TV_TruncateDiv_T], y: Annotated[Any, TV_TruncateDiv_T], name=None) -> Annotated[Any, TV_TruncateDiv_T]: + r"""Returns x / y element-wise, rounded towards zero. + + Truncation designates that negative numbers will round fractional quantities + toward zero. I.e. -7 / 5 = -1. This matches C semantics but it is different + than Python semantics. See `FloorDiv` for a division function that matches + Python Semantics. + + *NOTE*: `truncatediv` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `uint32`, `uint64`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TruncateDiv", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_truncate_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return truncate_div_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + truncate_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_truncate_div( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TruncateDiv", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + truncate_div, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TruncateDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TruncateDiv = tf_export("raw_ops.TruncateDiv")(_ops.to_raw_op(truncate_div)) +_dispatcher_for_truncate_div = truncate_div._tf_type_based_dispatcher.Dispatch + + +def truncate_div_eager_fallback(x: Annotated[Any, TV_TruncateDiv_T], y: Annotated[Any, TV_TruncateDiv_T], name, ctx) -> Annotated[Any, TV_TruncateDiv_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.uint8, _dtypes.int8, _dtypes.uint16, _dtypes.int16, _dtypes.int32, _dtypes.uint32, _dtypes.uint64, _dtypes.int64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TruncateDiv", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TruncateDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TruncateMod_T = TypeVar("TV_TruncateMod_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('truncatemod') +def truncate_mod(x: Annotated[Any, TV_TruncateMod_T], y: Annotated[Any, TV_TruncateMod_T], name=None) -> Annotated[Any, TV_TruncateMod_T]: + r"""Returns element-wise remainder of division. This emulates C semantics in that + + the result here is consistent with a truncating divide. E.g. `truncate(x / y) * + y + truncate_mod(x, y) = x`. + + *NOTE*: `truncatemod` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `int32`, `int64`, `bfloat16`, `half`, `float32`, `float64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TruncateMod", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_truncate_mod( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return truncate_mod_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + truncate_mod, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_truncate_mod( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TruncateMod", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + truncate_mod, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TruncateMod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TruncateMod = tf_export("raw_ops.TruncateMod")(_ops.to_raw_op(truncate_mod)) +_dispatcher_for_truncate_mod = truncate_mod._tf_type_based_dispatcher.Dispatch + + +def truncate_mod_eager_fallback(x: Annotated[Any, TV_TruncateMod_T], y: Annotated[Any, TV_TruncateMod_T], name, ctx) -> Annotated[Any, TV_TruncateMod_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TruncateMod", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TruncateMod", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnsortedSegmentMax_T = TypeVar("TV_UnsortedSegmentMax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_UnsortedSegmentMax_Tindices = TypeVar("TV_UnsortedSegmentMax_Tindices", _atypes.Int32, _atypes.Int64) +TV_UnsortedSegmentMax_Tnumsegments = TypeVar("TV_UnsortedSegmentMax_Tnumsegments", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.unsorted_segment_max', v1=['math.unsorted_segment_max', 'unsorted_segment_max']) +@deprecated_endpoints('unsorted_segment_max') +def unsorted_segment_max(data: Annotated[Any, TV_UnsortedSegmentMax_T], segment_ids: Annotated[Any, TV_UnsortedSegmentMax_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentMax_Tnumsegments], name=None) -> Annotated[Any, TV_UnsortedSegmentMax_T]: + r"""Computes the maximum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + This operator is similar to `tf.math.unsorted_segment_sum`, + Instead of computing the sum over segments, it computes the maximum such that: + + \\(output_i = \max_{j...} data[j...]\\) where max is over tuples `j...` such + that `segment_ids[j...] == i`. + + If the maximum is empty for a given segment ID `i`, it outputs the smallest + possible value for the specific numeric type, + `output[i] = numeric_limits::lowest()`. + + If the given segment ID `i` is negative, then the corresponding value is + dropped, and will not be included in the result. + + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + +
+ +
+ + For example: + + >>> c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) + >>> tf.math.unsorted_segment_max(c, tf.constant([0, 1, 0]), num_segments=2).numpy() + array([[4, 3, 3, 4], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor whose shape is a prefix of `data.shape`. + The values must be less than `num_segments`. + + Caution: The values are always validated to be in range on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnsortedSegmentMax", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unsorted_segment_max( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + return unsorted_segment_max_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_max, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unsorted_segment_max( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnsortedSegmentMax", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_max, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnsortedSegmentMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnsortedSegmentMax = tf_export("raw_ops.UnsortedSegmentMax")(_ops.to_raw_op(unsorted_segment_max)) +_dispatcher_for_unsorted_segment_max = unsorted_segment_max._tf_type_based_dispatcher.Dispatch + + +def unsorted_segment_max_eager_fallback(data: Annotated[Any, TV_UnsortedSegmentMax_T], segment_ids: Annotated[Any, TV_UnsortedSegmentMax_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentMax_Tnumsegments], name, ctx) -> Annotated[Any, TV_UnsortedSegmentMax_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"UnsortedSegmentMax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnsortedSegmentMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnsortedSegmentMin_T = TypeVar("TV_UnsortedSegmentMin_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_UnsortedSegmentMin_Tindices = TypeVar("TV_UnsortedSegmentMin_Tindices", _atypes.Int32, _atypes.Int64) +TV_UnsortedSegmentMin_Tnumsegments = TypeVar("TV_UnsortedSegmentMin_Tnumsegments", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.unsorted_segment_min', v1=['math.unsorted_segment_min', 'unsorted_segment_min']) +@deprecated_endpoints('unsorted_segment_min') +def unsorted_segment_min(data: Annotated[Any, TV_UnsortedSegmentMin_T], segment_ids: Annotated[Any, TV_UnsortedSegmentMin_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentMin_Tnumsegments], name=None) -> Annotated[Any, TV_UnsortedSegmentMin_T]: + r"""Computes the minimum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + This operator is similar to `tf.math.unsorted_segment_sum`, + Instead of computing the sum over segments, it computes the minimum such that: + + \\(output_i = \min_{j...} data_[j...]\\) where min is over tuples `j...` such + that `segment_ids[j...] == i`. + + If the minimum is empty for a given segment ID `i`, it outputs the largest + possible value for the specific numeric type, + `output[i] = numeric_limits::max()`. + + For example: + + >>> c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) + >>> tf.math.unsorted_segment_min(c, tf.constant([0, 1, 0]), num_segments=2).numpy() + array([[1, 2, 2, 1], + [5, 6, 7, 8]], dtype=int32) + + If the given segment ID `i` is negative, then the corresponding value is + dropped, and will not be included in the result. + + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor whose shape is a prefix of `data.shape`. + The values must be less than `num_segments`. + + Caution: The values are always validated to be in range on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnsortedSegmentMin", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unsorted_segment_min( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + return unsorted_segment_min_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_min, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unsorted_segment_min( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnsortedSegmentMin", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_min, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnsortedSegmentMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnsortedSegmentMin = tf_export("raw_ops.UnsortedSegmentMin")(_ops.to_raw_op(unsorted_segment_min)) +_dispatcher_for_unsorted_segment_min = unsorted_segment_min._tf_type_based_dispatcher.Dispatch + + +def unsorted_segment_min_eager_fallback(data: Annotated[Any, TV_UnsortedSegmentMin_T], segment_ids: Annotated[Any, TV_UnsortedSegmentMin_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentMin_Tnumsegments], name, ctx) -> Annotated[Any, TV_UnsortedSegmentMin_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"UnsortedSegmentMin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnsortedSegmentMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnsortedSegmentProd_T = TypeVar("TV_UnsortedSegmentProd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_UnsortedSegmentProd_Tindices = TypeVar("TV_UnsortedSegmentProd_Tindices", _atypes.Int32, _atypes.Int64) +TV_UnsortedSegmentProd_Tnumsegments = TypeVar("TV_UnsortedSegmentProd_Tnumsegments", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.unsorted_segment_prod', v1=['math.unsorted_segment_prod', 'unsorted_segment_prod']) +@deprecated_endpoints('unsorted_segment_prod') +def unsorted_segment_prod(data: Annotated[Any, TV_UnsortedSegmentProd_T], segment_ids: Annotated[Any, TV_UnsortedSegmentProd_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentProd_Tnumsegments], name=None) -> Annotated[Any, TV_UnsortedSegmentProd_T]: + r"""Computes the product along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + This operator is similar to `tf.math.unsorted_segment_sum`, + Instead of computing the sum over segments, it computes the product of all + entries belonging to a segment such that: + + \\(output_i = \prod_{j...} data[j...]\\) where the product is over tuples + `j...` such that `segment_ids[j...] == i`. + + For example: + + >>> c = tf.constant([[1,2,3,4], [5,6,7,8], [4,3,2,1]]) + >>> tf.math.unsorted_segment_prod(c, tf.constant([0, 1, 0]), num_segments=2).numpy() + array([[4, 6, 6, 4], + [5, 6, 7, 8]], dtype=int32) + + If there is no entry for a given segment ID `i`, it outputs 1. + + If the given segment ID `i` is negative, then the corresponding value is + dropped, and will not be included in the result. + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor whose shape is a prefix of `data.shape`. + The values must be less than `num_segments`. + + Caution: The values are always validated to be in range on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnsortedSegmentProd", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unsorted_segment_prod( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + return unsorted_segment_prod_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_prod, (), dict(data=data, + segment_ids=segment_ids, + num_segments=num_segments, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unsorted_segment_prod( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnsortedSegmentProd", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_prod, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnsortedSegmentProd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnsortedSegmentProd = tf_export("raw_ops.UnsortedSegmentProd")(_ops.to_raw_op(unsorted_segment_prod)) +_dispatcher_for_unsorted_segment_prod = unsorted_segment_prod._tf_type_based_dispatcher.Dispatch + + +def unsorted_segment_prod_eager_fallback(data: Annotated[Any, TV_UnsortedSegmentProd_T], segment_ids: Annotated[Any, TV_UnsortedSegmentProd_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentProd_Tnumsegments], name, ctx) -> Annotated[Any, TV_UnsortedSegmentProd_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"UnsortedSegmentProd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnsortedSegmentProd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnsortedSegmentSum_T = TypeVar("TV_UnsortedSegmentSum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_UnsortedSegmentSum_Tindices = TypeVar("TV_UnsortedSegmentSum_Tindices", _atypes.Int16, _atypes.Int32, _atypes.Int64) +TV_UnsortedSegmentSum_Tnumsegments = TypeVar("TV_UnsortedSegmentSum_Tnumsegments", _atypes.Int32, _atypes.Int64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.unsorted_segment_sum', v1=['math.unsorted_segment_sum', 'unsorted_segment_sum']) +@deprecated_endpoints('unsorted_segment_sum') +def unsorted_segment_sum(data: Annotated[Any, TV_UnsortedSegmentSum_T], segment_ids: Annotated[Any, TV_UnsortedSegmentSum_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentSum_Tnumsegments], name=None) -> Annotated[Any, TV_UnsortedSegmentSum_T]: + r"""Computes the sum along segments of a tensor. + + Read + [the section on segmentation](https://tensorflow.org/api_docs/python/tf/math#Segmentation) + for an explanation of segments. + + Computes a tensor such that + \\(output[i] = \sum_{j...} data[j...]\\) where the sum is over tuples `j...` such + that `segment_ids[j...] == i`. Unlike `SegmentSum`, `segment_ids` + need not be sorted and need not cover all values in the full + range of valid values. + + If the sum is empty for a given segment ID `i`, `output[i] = 0`. + If the given segment ID `i` is negative, the value is dropped and will not be + added to the sum of the segment. + + `num_segments` should equal the number of distinct segment IDs. + + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + +
+ +
+ + >>> c = [[1,2,3,4], [5,6,7,8], [4,3,2,1]] + >>> tf.math.unsorted_segment_sum(c, [0, 1, 0], num_segments=2).numpy() + array([[5, 5, 5, 5], + [5, 6, 7, 8]], dtype=int32) + + Args: + data: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + segment_ids: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + A tensor whose shape is a prefix of `data.shape`. + The values must be less than `num_segments`. + + Caution: The values are always validated to be in range on CPU, never validated + on GPU. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `data`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnsortedSegmentSum", name, data, segment_ids, num_segments) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unsorted_segment_sum( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + return unsorted_segment_sum_eager_fallback( + data, segment_ids, num_segments, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_sum, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unsorted_segment_sum( + (data, segment_ids, num_segments, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnsortedSegmentSum", data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unsorted_segment_sum, (), dict(data=data, segment_ids=segment_ids, + num_segments=num_segments, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnsortedSegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnsortedSegmentSum = tf_export("raw_ops.UnsortedSegmentSum")(_ops.to_raw_op(unsorted_segment_sum)) +_dispatcher_for_unsorted_segment_sum = unsorted_segment_sum._tf_type_based_dispatcher.Dispatch + + +def unsorted_segment_sum_eager_fallback(data: Annotated[Any, TV_UnsortedSegmentSum_T], segment_ids: Annotated[Any, TV_UnsortedSegmentSum_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentSum_Tnumsegments], name, ctx) -> Annotated[Any, TV_UnsortedSegmentSum_T]: + _attr_T, (data,) = _execute.args_to_matching_eager([data], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [data, segment_ids, num_segments] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "Tnumsegments", + _attr_Tnumsegments) + _result = _execute.execute(b"UnsortedSegmentSum", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnsortedSegmentSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Xdivy_T = TypeVar("TV_Xdivy_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def xdivy(x: Annotated[Any, TV_Xdivy_T], y: Annotated[Any, TV_Xdivy_T], name=None) -> Annotated[Any, TV_Xdivy_T]: + r"""Returns 0 if x == 0, and x / y otherwise, elementwise. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Xdivy", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return xdivy_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Xdivy", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Xdivy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Xdivy = tf_export("raw_ops.Xdivy")(_ops.to_raw_op(xdivy)) + + +def xdivy_eager_fallback(x: Annotated[Any, TV_Xdivy_T], y: Annotated[Any, TV_Xdivy_T], name, ctx) -> Annotated[Any, TV_Xdivy_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Xdivy", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Xdivy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Xlog1py_T = TypeVar("TV_Xlog1py_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def xlog1py(x: Annotated[Any, TV_Xlog1py_T], y: Annotated[Any, TV_Xlog1py_T], name=None) -> Annotated[Any, TV_Xlog1py_T]: + r"""Returns 0 if x == 0, and x * log1p(y) otherwise, elementwise. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Xlog1py", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return xlog1py_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Xlog1py", x=x, y=y, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Xlog1py", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Xlog1py = tf_export("raw_ops.Xlog1py")(_ops.to_raw_op(xlog1py)) + + +def xlog1py_eager_fallback(x: Annotated[Any, TV_Xlog1py_T], y: Annotated[Any, TV_Xlog1py_T], name, ctx) -> Annotated[Any, TV_Xlog1py_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Xlog1py", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Xlog1py", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Xlogy_T = TypeVar("TV_Xlogy_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.xlogy') +def xlogy(x: Annotated[Any, TV_Xlogy_T], y: Annotated[Any, TV_Xlogy_T], name=None) -> Annotated[Any, TV_Xlogy_T]: + r"""Returns 0 if x == 0, and x * log(y) otherwise, elementwise. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Xlogy", name, x, y) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_xlogy( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + return xlogy_eager_fallback( + x, y, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + xlogy, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_xlogy( + (x, y, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Xlogy", x=x, y=y, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + xlogy, (), dict(x=x, y=y, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Xlogy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Xlogy = tf_export("raw_ops.Xlogy")(_ops.to_raw_op(xlogy)) +_dispatcher_for_xlogy = xlogy._tf_type_based_dispatcher.Dispatch + + +def xlogy_eager_fallback(x: Annotated[Any, TV_Xlogy_T], y: Annotated[Any, TV_Xlogy_T], name, ctx) -> Annotated[Any, TV_Xlogy_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (x, y) = _inputs_T + _inputs_flat = [x, y] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Xlogy", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Xlogy", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Zeta_T = TypeVar("TV_Zeta_T", _atypes.Float32, _atypes.Float64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('math.zeta', v1=['math.zeta', 'zeta']) +@deprecated_endpoints('zeta') +def zeta(x: Annotated[Any, TV_Zeta_T], q: Annotated[Any, TV_Zeta_T], name=None) -> Annotated[Any, TV_Zeta_T]: + r"""Compute the Hurwitz zeta function \\(\zeta(x, q)\\). + + The Hurwitz zeta function is defined as: + + + \\(\zeta(x, q) = \sum_{n=0}^{\infty} (q + n)^{-x}\\) + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`. + q: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Zeta", name, x, q) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_zeta( + (x, q, name,), None) + if _result is not NotImplemented: + return _result + return zeta_eager_fallback( + x, q, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + zeta, (), dict(x=x, q=q, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_zeta( + (x, q, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Zeta", x=x, q=q, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + zeta, (), dict(x=x, q=q, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Zeta", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Zeta = tf_export("raw_ops.Zeta")(_ops.to_raw_op(zeta)) +_dispatcher_for_zeta = zeta._tf_type_based_dispatcher.Dispatch + + +def zeta_eager_fallback(x: Annotated[Any, TV_Zeta_T], q: Annotated[Any, TV_Zeta_T], name, ctx) -> Annotated[Any, TV_Zeta_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, q], ctx, [_dtypes.float32, _dtypes.float64, ]) + (x, q) = _inputs_T + _inputs_flat = [x, q] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Zeta", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Zeta", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nccl_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nccl_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a021d747073edcf9c3c51aedfe26ca88e99b46df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nccl_ops.py @@ -0,0 +1,258 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_NcclAllReduce_T = TypeVar("TV_NcclAllReduce_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def nccl_all_reduce(input: Annotated[Any, TV_NcclAllReduce_T], reduction: str, num_devices: int, shared_name: str, name=None) -> Annotated[Any, TV_NcclAllReduce_T]: + r"""Outputs a tensor containing the reduction across all input tensors. + + Outputs a tensor containing the reduction across all input tensors passed to ops + within the same `shared_name. + + The graph should be constructed so if one op runs with shared_name value `c`, + then `num_devices` ops will run with shared_name value `c`. Failure to do so + will cause the graph execution to fail to complete. + + input: the input to the reduction + data: the value of the reduction across all `num_devices` devices. + reduction: the reduction operation to perform. + num_devices: The number of devices participating in this reduction. + shared_name: Identifier that shared between ops of the same reduction. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + reduction: A `string` from: `"min", "max", "prod", "sum"`. + num_devices: An `int`. + shared_name: A `string`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NcclAllReduce", name, input, "reduction", reduction, + "num_devices", num_devices, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return nccl_all_reduce_eager_fallback( + input, reduction=reduction, num_devices=num_devices, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + reduction = _execute.make_str(reduction, "reduction") + num_devices = _execute.make_int(num_devices, "num_devices") + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NcclAllReduce", input=input, reduction=reduction, + num_devices=num_devices, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reduction", _op.get_attr("reduction"), "T", + _op._get_attr_type("T"), "num_devices", + _op._get_attr_int("num_devices"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NcclAllReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NcclAllReduce = tf_export("raw_ops.NcclAllReduce")(_ops.to_raw_op(nccl_all_reduce)) + + +def nccl_all_reduce_eager_fallback(input: Annotated[Any, TV_NcclAllReduce_T], reduction: str, num_devices: int, shared_name: str, name, ctx) -> Annotated[Any, TV_NcclAllReduce_T]: + reduction = _execute.make_str(reduction, "reduction") + num_devices = _execute.make_int(num_devices, "num_devices") + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input] + _attrs = ("reduction", reduction, "T", _attr_T, "num_devices", num_devices, + "shared_name", shared_name) + _result = _execute.execute(b"NcclAllReduce", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NcclAllReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NcclBroadcast_T = TypeVar("TV_NcclBroadcast_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def nccl_broadcast(input: Annotated[Any, TV_NcclBroadcast_T], shape, name=None) -> Annotated[Any, TV_NcclBroadcast_T]: + r"""Sends `input` to all devices that are connected to the output. + + Sends `input` to all devices that are connected to the output. + + The graph should be constructed so that all ops connected to the output have a + valid device assignment, and the op itself is assigned one of these devices. + + input: The input to the broadcast. + output: The same as input. + shape: The shape of the input tensor. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + shape: A `tf.TensorShape` or list of `ints`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NcclBroadcast", name, input, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return nccl_broadcast_eager_fallback( + input, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NcclBroadcast", input=input, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "shape", _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NcclBroadcast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NcclBroadcast = tf_export("raw_ops.NcclBroadcast")(_ops.to_raw_op(nccl_broadcast)) + + +def nccl_broadcast_eager_fallback(input: Annotated[Any, TV_NcclBroadcast_T], shape, name, ctx) -> Annotated[Any, TV_NcclBroadcast_T]: + shape = _execute.make_shape(shape, "shape") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "shape", shape) + _result = _execute.execute(b"NcclBroadcast", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NcclBroadcast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_NcclReduce_T = TypeVar("TV_NcclReduce_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def nccl_reduce(input: Annotated[List[Any], TV_NcclReduce_T], reduction: str, name=None) -> Annotated[Any, TV_NcclReduce_T]: + r"""Reduces `input` from `num_devices` using `reduction` to a single device. + + Reduces `input` from `num_devices` using `reduction` to a single device. + + The graph should be constructed so that all inputs have a valid device + assignment, and the op itself is assigned one of these devices. + + input: The input to the reduction. + data: the value of the reduction across all `num_devices` devices. + reduction: the reduction operation to perform. + + Args: + input: A list of at least 1 `Tensor` objects with the same type in: `half`, `float32`, `float64`, `int32`, `int64`. + reduction: A `string` from: `"min", "max", "prod", "sum"`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NcclReduce", name, input, "reduction", reduction) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return nccl_reduce_eager_fallback( + input, reduction=reduction, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(input, (list, tuple)): + raise TypeError( + "Expected list for 'input' argument to " + "'nccl_reduce' Op, not %r." % input) + _attr_num_devices = len(input) + reduction = _execute.make_str(reduction, "reduction") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NcclReduce", input=input, reduction=reduction, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reduction", _op.get_attr("reduction"), "T", + _op._get_attr_type("T"), "num_devices", + _op._get_attr_int("num_devices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NcclReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NcclReduce = tf_export("raw_ops.NcclReduce")(_ops.to_raw_op(nccl_reduce)) + + +def nccl_reduce_eager_fallback(input: Annotated[List[Any], TV_NcclReduce_T], reduction: str, name, ctx) -> Annotated[Any, TV_NcclReduce_T]: + if not isinstance(input, (list, tuple)): + raise TypeError( + "Expected list for 'input' argument to " + "'nccl_reduce' Op, not %r." % input) + _attr_num_devices = len(input) + reduction = _execute.make_str(reduction, "reduction") + _attr_T, input = _execute.args_to_matching_eager(list(input), ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = list(input) + _attrs = ("reduction", reduction, "T", _attr_T, "num_devices", + _attr_num_devices) + _result = _execute.execute(b"NcclReduce", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NcclReduce", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nn_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nn_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..235d6f2d7049cd0e913c455d110a5ca6919f95f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_nn_ops.py @@ -0,0 +1,12646 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_ApproxTopKOutput = collections.namedtuple( + "ApproxTopK", + ["values", "indices"]) + + +TV_ApproxTopK_T = TypeVar("TV_ApproxTopK_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('approx_top_k') +def approx_top_k(input: Annotated[Any, TV_ApproxTopK_T], k: int, reduction_dimension:int=-1, recall_target:float=0.95, is_max_k:bool=True, reduction_input_size_override:int=-1, aggregate_to_topk:bool=True, name=None): + r"""Returns min/max k values and their indices of the input operand in an approximate manner. + + See https://arxiv.org/abs/2206.14286 for the algorithm details. + This op is only optimized on TPU currently. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + Array to search. Must be at least 1-D of the floating type + k: An `int` that is `>= 0`. Specifies the number of min/max-k. + reduction_dimension: An optional `int`. Defaults to `-1`. + Integer dimension along which to search. Default: -1. + recall_target: An optional `float`. Defaults to `0.95`. + Recall target for the approximation. Range in (0,1] + is_max_k: An optional `bool`. Defaults to `True`. + When true, computes max-k; otherwise computes min-k. + reduction_input_size_override: An optional `int`. Defaults to `-1`. + When set to a positive value, it overrides the size determined by + `input[reduction_dim]` for evaluating the recall. This option is useful when + the given `input` is only a subset of the overall computation in SPMD or + distributed pipelines, where the true input size cannot be deferred by the + `input` shape. + aggregate_to_topk: An optional `bool`. Defaults to `True`. + When true, aggregates approximate results to top-k. When false, returns the + approximate results. The number of the approximate results is implementation + defined and is greater equals to the specified `k`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (values, indices). + + values: A `Tensor`. Has the same type as `input`. + indices: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ApproxTopK", name, input, "k", k, "reduction_dimension", + reduction_dimension, "recall_target", recall_target, "is_max_k", + is_max_k, "reduction_input_size_override", + reduction_input_size_override, "aggregate_to_topk", aggregate_to_topk) + _result = _ApproxTopKOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_approx_top_k( + (input, k, reduction_dimension, recall_target, is_max_k, + reduction_input_size_override, aggregate_to_topk, name,), None) + if _result is not NotImplemented: + return _result + return approx_top_k_eager_fallback( + input, k=k, reduction_dimension=reduction_dimension, + recall_target=recall_target, is_max_k=is_max_k, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + approx_top_k, (), dict(input=input, k=k, + reduction_dimension=reduction_dimension, + recall_target=recall_target, + is_max_k=is_max_k, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_approx_top_k( + (input, k, reduction_dimension, recall_target, is_max_k, + reduction_input_size_override, aggregate_to_topk, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + k = _execute.make_int(k, "k") + if reduction_dimension is None: + reduction_dimension = -1 + reduction_dimension = _execute.make_int(reduction_dimension, "reduction_dimension") + if recall_target is None: + recall_target = 0.95 + recall_target = _execute.make_float(recall_target, "recall_target") + if is_max_k is None: + is_max_k = True + is_max_k = _execute.make_bool(is_max_k, "is_max_k") + if reduction_input_size_override is None: + reduction_input_size_override = -1 + reduction_input_size_override = _execute.make_int(reduction_input_size_override, "reduction_input_size_override") + if aggregate_to_topk is None: + aggregate_to_topk = True + aggregate_to_topk = _execute.make_bool(aggregate_to_topk, "aggregate_to_topk") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApproxTopK", input=input, k=k, + reduction_dimension=reduction_dimension, + recall_target=recall_target, is_max_k=is_max_k, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + approx_top_k, (), dict(input=input, k=k, + reduction_dimension=reduction_dimension, + recall_target=recall_target, + is_max_k=is_max_k, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("k", _op._get_attr_int("k"), "reduction_dimension", + _op._get_attr_int("reduction_dimension"), "recall_target", + _op.get_attr("recall_target"), "is_max_k", + _op._get_attr_bool("is_max_k"), "reduction_input_size_override", + _op._get_attr_int("reduction_input_size_override"), + "aggregate_to_topk", _op._get_attr_bool("aggregate_to_topk"), + "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApproxTopK", _inputs_flat, _attrs, _result) + _result = _ApproxTopKOutput._make(_result) + return _result + +ApproxTopK = tf_export("raw_ops.ApproxTopK")(_ops.to_raw_op(approx_top_k)) +_dispatcher_for_approx_top_k = approx_top_k._tf_type_based_dispatcher.Dispatch + + +def approx_top_k_eager_fallback(input: Annotated[Any, TV_ApproxTopK_T], k: int, reduction_dimension: int, recall_target: float, is_max_k: bool, reduction_input_size_override: int, aggregate_to_topk: bool, name, ctx): + k = _execute.make_int(k, "k") + if reduction_dimension is None: + reduction_dimension = -1 + reduction_dimension = _execute.make_int(reduction_dimension, "reduction_dimension") + if recall_target is None: + recall_target = 0.95 + recall_target = _execute.make_float(recall_target, "recall_target") + if is_max_k is None: + is_max_k = True + is_max_k = _execute.make_bool(is_max_k, "is_max_k") + if reduction_input_size_override is None: + reduction_input_size_override = -1 + reduction_input_size_override = _execute.make_int(reduction_input_size_override, "reduction_input_size_override") + if aggregate_to_topk is None: + aggregate_to_topk = True + aggregate_to_topk = _execute.make_bool(aggregate_to_topk, "aggregate_to_topk") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("k", k, "reduction_dimension", reduction_dimension, + "recall_target", recall_target, "is_max_k", is_max_k, + "reduction_input_size_override", reduction_input_size_override, + "aggregate_to_topk", aggregate_to_topk, "T", _attr_T) + _result = _execute.execute(b"ApproxTopK", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ApproxTopK", _inputs_flat, _attrs, _result) + _result = _ApproxTopKOutput._make(_result) + return _result + + +TV_AvgPool_T = TypeVar("TV_AvgPool_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def avg_pool(value: Annotated[Any, TV_AvgPool_T], ksize, strides, padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_AvgPool_T]: + r"""Performs average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Args: + value: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, height, width, channels]`. + ksize: A list of `ints` that has length `>= 4`. + The size of the sliding window for each dimension of `value`. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of `value`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AvgPool", name, value, "ksize", ksize, "strides", strides, + "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return avg_pool_eager_fallback( + value, ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AvgPool", value=value, ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AvgPool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AvgPool = tf_export("raw_ops.AvgPool")(_ops.to_raw_op(avg_pool)) + + +def avg_pool_eager_fallback(value: Annotated[Any, TV_AvgPool_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_AvgPool_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [value] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"AvgPool", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AvgPool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AvgPool3D_T = TypeVar("TV_AvgPool3D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def avg_pool3d(input: Annotated[Any, TV_AvgPool3D_T], ksize, strides, padding: str, data_format:str="NDHWC", name=None) -> Annotated[Any, TV_AvgPool3D_T]: + r"""Performs 3D average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` window in + `value`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Shape `[batch, depth, rows, cols, channels]` tensor to pool over. + ksize: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The size of the window for each dimension of + the input tensor. Must have `ksize[0] = ksize[4] = 1`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AvgPool3D", name, input, "ksize", ksize, "strides", strides, + "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return avg_pool3d_eager_fallback( + input, ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool3d' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AvgPool3D", input=input, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AvgPool3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AvgPool3D = tf_export("raw_ops.AvgPool3D")(_ops.to_raw_op(avg_pool3d)) + + +def avg_pool3d_eager_fallback(input: Annotated[Any, TV_AvgPool3D_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_AvgPool3D_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool3d' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [input] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"AvgPool3D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AvgPool3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AvgPool3DGrad_T = TypeVar("TV_AvgPool3DGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def avg_pool3d_grad(orig_input_shape: Annotated[Any, _atypes.Int32], grad: Annotated[Any, TV_AvgPool3DGrad_T], ksize, strides, padding: str, data_format:str="NDHWC", name=None) -> Annotated[Any, TV_AvgPool3DGrad_T]: + r"""Computes gradients of average pooling function. + + Args: + orig_input_shape: A `Tensor` of type `int32`. + The original input dimensions. + grad: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Output backprop of shape `[batch, depth, rows, cols, channels]`. + ksize: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The size of the window for each dimension of + the input tensor. Must have `ksize[0] = ksize[4] = 1`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AvgPool3DGrad", name, orig_input_shape, grad, "ksize", ksize, + "strides", strides, "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return avg_pool3d_grad_eager_fallback( + orig_input_shape, grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool3d_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool3d_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AvgPool3DGrad", orig_input_shape=orig_input_shape, grad=grad, + ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AvgPool3DGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AvgPool3DGrad = tf_export("raw_ops.AvgPool3DGrad")(_ops.to_raw_op(avg_pool3d_grad)) + + +def avg_pool3d_grad_eager_fallback(orig_input_shape: Annotated[Any, _atypes.Int32], grad: Annotated[Any, TV_AvgPool3DGrad_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_AvgPool3DGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool3d_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool3d_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + orig_input_shape = _ops.convert_to_tensor(orig_input_shape, _dtypes.int32) + _inputs_flat = [orig_input_shape, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"AvgPool3DGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AvgPool3DGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AvgPoolGrad_T = TypeVar("TV_AvgPoolGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def avg_pool_grad(orig_input_shape: Annotated[Any, _atypes.Int32], grad: Annotated[Any, TV_AvgPoolGrad_T], ksize, strides, padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_AvgPoolGrad_T]: + r"""Computes gradients of the average pooling function. + + Args: + orig_input_shape: A `Tensor` of type `int32`. + 1-D. Shape of the original input to `avg_pool`. + grad: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. + the output of `avg_pool`. + ksize: A list of `ints` that has length `>= 4`. + The size of the sliding window for each dimension of the input. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the input. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AvgPoolGrad", name, orig_input_shape, grad, "ksize", ksize, + "strides", strides, "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return avg_pool_grad_eager_fallback( + orig_input_shape, grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AvgPoolGrad", orig_input_shape=orig_input_shape, grad=grad, + ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AvgPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AvgPoolGrad = tf_export("raw_ops.AvgPoolGrad")(_ops.to_raw_op(avg_pool_grad)) + + +def avg_pool_grad_eager_fallback(orig_input_shape: Annotated[Any, _atypes.Int32], grad: Annotated[Any, TV_AvgPoolGrad_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_AvgPoolGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'avg_pool_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'avg_pool_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + orig_input_shape = _ops.convert_to_tensor(orig_input_shape, _dtypes.int32) + _inputs_flat = [orig_input_shape, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"AvgPoolGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AvgPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BatchNormWithGlobalNormalization_T = TypeVar("TV_BatchNormWithGlobalNormalization_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def _batch_norm_with_global_normalization(t: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], m: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], v: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], beta: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], gamma: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], variance_epsilon: float, scale_after_normalization: bool, name=None) -> Annotated[Any, TV_BatchNormWithGlobalNormalization_T]: + r"""Batch normalization. + + This op is deprecated. Prefer `tf.nn.batch_normalization`. + + Args: + t: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A 4D input Tensor. + m: A `Tensor`. Must have the same type as `t`. + A 1D mean Tensor with size matching the last dimension of t. + This is the first output from tf.nn.moments, + or a saved moving average thereof. + v: A `Tensor`. Must have the same type as `t`. + A 1D variance Tensor with size matching the last dimension of t. + This is the second output from tf.nn.moments, + or a saved moving average thereof. + beta: A `Tensor`. Must have the same type as `t`. + A 1D beta Tensor with size matching the last dimension of t. + An offset to be added to the normalized tensor. + gamma: A `Tensor`. Must have the same type as `t`. + A 1D gamma Tensor with size matching the last dimension of t. + If "scale_after_normalization" is true, this tensor will be multiplied + with the normalized tensor. + variance_epsilon: A `float`. A small float number to avoid dividing by 0. + scale_after_normalization: A `bool`. + A bool indicating whether the resulted tensor + needs to be multiplied with gamma. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchNormWithGlobalNormalization", name, t, m, v, beta, gamma, + "variance_epsilon", variance_epsilon, "scale_after_normalization", + scale_after_normalization) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _batch_norm_with_global_normalization_eager_fallback( + t, m, v, beta, gamma, variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchNormWithGlobalNormalization", t=t, m=m, v=v, beta=beta, + gamma=gamma, + variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "variance_epsilon", + _op.get_attr("variance_epsilon"), "scale_after_normalization", + _op._get_attr_bool("scale_after_normalization")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchNormWithGlobalNormalization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchNormWithGlobalNormalization = tf_export("raw_ops.BatchNormWithGlobalNormalization")(_ops.to_raw_op(_batch_norm_with_global_normalization)) + + +def _batch_norm_with_global_normalization_eager_fallback(t: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], m: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], v: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], beta: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], gamma: Annotated[Any, TV_BatchNormWithGlobalNormalization_T], variance_epsilon: float, scale_after_normalization: bool, name, ctx) -> Annotated[Any, TV_BatchNormWithGlobalNormalization_T]: + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _attr_T, _inputs_T = _execute.args_to_matching_eager([t, m, v, beta, gamma], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (t, m, v, beta, gamma) = _inputs_T + _inputs_flat = [t, m, v, beta, gamma] + _attrs = ("T", _attr_T, "variance_epsilon", variance_epsilon, + "scale_after_normalization", scale_after_normalization) + _result = _execute.execute(b"BatchNormWithGlobalNormalization", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchNormWithGlobalNormalization", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_BatchNormWithGlobalNormalizationGradOutput = collections.namedtuple( + "BatchNormWithGlobalNormalizationGrad", + ["dx", "dm", "dv", "db", "dg"]) + + +TV_BatchNormWithGlobalNormalizationGrad_T = TypeVar("TV_BatchNormWithGlobalNormalizationGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def batch_norm_with_global_normalization_grad(t: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], m: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], v: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], gamma: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], backprop: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], variance_epsilon: float, scale_after_normalization: bool, name=None): + r"""Gradients for batch normalization. + + This op is deprecated. See `tf.nn.batch_normalization`. + + Args: + t: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A 4D input Tensor. + m: A `Tensor`. Must have the same type as `t`. + A 1D mean Tensor with size matching the last dimension of t. + This is the first output from tf.nn.moments, + or a saved moving average thereof. + v: A `Tensor`. Must have the same type as `t`. + A 1D variance Tensor with size matching the last dimension of t. + This is the second output from tf.nn.moments, + or a saved moving average thereof. + gamma: A `Tensor`. Must have the same type as `t`. + A 1D gamma Tensor with size matching the last dimension of t. + If "scale_after_normalization" is true, this Tensor will be multiplied + with the normalized Tensor. + backprop: A `Tensor`. Must have the same type as `t`. 4D backprop Tensor. + variance_epsilon: A `float`. A small float number to avoid dividing by 0. + scale_after_normalization: A `bool`. + A bool indicating whether the resulted tensor + needs to be multiplied with gamma. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (dx, dm, dv, db, dg). + + dx: A `Tensor`. Has the same type as `t`. + dm: A `Tensor`. Has the same type as `t`. + dv: A `Tensor`. Has the same type as `t`. + db: A `Tensor`. Has the same type as `t`. + dg: A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchNormWithGlobalNormalizationGrad", name, t, m, v, gamma, + backprop, "variance_epsilon", variance_epsilon, + "scale_after_normalization", scale_after_normalization) + _result = _BatchNormWithGlobalNormalizationGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_norm_with_global_normalization_grad_eager_fallback( + t, m, v, gamma, backprop, variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchNormWithGlobalNormalizationGrad", t=t, m=m, v=v, gamma=gamma, + backprop=backprop, + variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "variance_epsilon", + _op.get_attr("variance_epsilon"), "scale_after_normalization", + _op._get_attr_bool("scale_after_normalization")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchNormWithGlobalNormalizationGrad", _inputs_flat, _attrs, _result) + _result = _BatchNormWithGlobalNormalizationGradOutput._make(_result) + return _result + +BatchNormWithGlobalNormalizationGrad = tf_export("raw_ops.BatchNormWithGlobalNormalizationGrad")(_ops.to_raw_op(batch_norm_with_global_normalization_grad)) + + +def batch_norm_with_global_normalization_grad_eager_fallback(t: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], m: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], v: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], gamma: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], backprop: Annotated[Any, TV_BatchNormWithGlobalNormalizationGrad_T], variance_epsilon: float, scale_after_normalization: bool, name, ctx): + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _attr_T, _inputs_T = _execute.args_to_matching_eager([t, m, v, gamma, backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (t, m, v, gamma, backprop) = _inputs_T + _inputs_flat = [t, m, v, gamma, backprop] + _attrs = ("T", _attr_T, "variance_epsilon", variance_epsilon, + "scale_after_normalization", scale_after_normalization) + _result = _execute.execute(b"BatchNormWithGlobalNormalizationGrad", 5, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchNormWithGlobalNormalizationGrad", _inputs_flat, _attrs, _result) + _result = _BatchNormWithGlobalNormalizationGradOutput._make(_result) + return _result + + +TV_BiasAdd_T = TypeVar("TV_BiasAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def bias_add(value: Annotated[Any, TV_BiasAdd_T], bias: Annotated[Any, TV_BiasAdd_T], data_format:str="NHWC", name=None) -> Annotated[Any, TV_BiasAdd_T]: + r"""Adds `bias` to `value`. + + This is a special case of `tf.add` where `bias` is restricted to be 1-D. + Broadcasting is supported, so `value` may have any number of dimensions. + + Args: + value: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Any number of dimensions. + bias: A `Tensor`. Must have the same type as `value`. + 1-D with size the last dimension of `value`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the bias tensor will be added to the last dimension + of the value tensor. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + The tensor will be added to "in_channels", the third-to-the-last + dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BiasAdd", name, value, bias, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bias_add_eager_fallback( + value, bias, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BiasAdd", value=value, bias=bias, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BiasAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BiasAdd = tf_export("raw_ops.BiasAdd")(_ops.to_raw_op(bias_add)) + + +def bias_add_eager_fallback(value: Annotated[Any, TV_BiasAdd_T], bias: Annotated[Any, TV_BiasAdd_T], data_format: str, name, ctx) -> Annotated[Any, TV_BiasAdd_T]: + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([value, bias], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (value, bias) = _inputs_T + _inputs_flat = [value, bias] + _attrs = ("T", _attr_T, "data_format", data_format) + _result = _execute.execute(b"BiasAdd", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BiasAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BiasAddGrad_T = TypeVar("TV_BiasAddGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def bias_add_grad(out_backprop: Annotated[Any, TV_BiasAddGrad_T], data_format:str="NHWC", name=None) -> Annotated[Any, TV_BiasAddGrad_T]: + r"""The backward operation for "BiasAdd" on the "bias" tensor. + + It accumulates all the values from out_backprop into the feature dimension. + For NHWC data format, the feature dimension is the last. For NCHW data format, + the feature dimension is the third-to-last. + + Args: + out_backprop: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Any number of dimensions. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the bias tensor will be added to the last dimension + of the value tensor. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + The tensor will be added to "in_channels", the third-to-the-last + dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `out_backprop`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BiasAddGrad", name, out_backprop, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bias_add_grad_eager_fallback( + out_backprop, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BiasAddGrad", out_backprop=out_backprop, data_format=data_format, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BiasAddGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BiasAddGrad = tf_export("raw_ops.BiasAddGrad")(_ops.to_raw_op(bias_add_grad)) + + +def bias_add_grad_eager_fallback(out_backprop: Annotated[Any, TV_BiasAddGrad_T], data_format: str, name, ctx) -> Annotated[Any, TV_BiasAddGrad_T]: + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (out_backprop,) = _execute.args_to_matching_eager([out_backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [out_backprop] + _attrs = ("T", _attr_T, "data_format", data_format) + _result = _execute.execute(b"BiasAddGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BiasAddGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BiasAddV1_T = TypeVar("TV_BiasAddV1_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def bias_add_v1(value: Annotated[Any, TV_BiasAddV1_T], bias: Annotated[Any, TV_BiasAddV1_T], name=None) -> Annotated[Any, TV_BiasAddV1_T]: + r"""Adds `bias` to `value`. + + This is a deprecated version of BiasAdd and will be soon removed. + + This is a special case of `tf.add` where `bias` is restricted to be 1-D. + Broadcasting is supported, so `value` may have any number of dimensions. + + Args: + value: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Any number of dimensions. + bias: A `Tensor`. Must have the same type as `value`. + 1-D with size the last dimension of `value`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BiasAddV1", name, value, bias) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bias_add_v1_eager_fallback( + value, bias, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BiasAddV1", value=value, bias=bias, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BiasAddV1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BiasAddV1 = tf_export("raw_ops.BiasAddV1")(_ops.to_raw_op(bias_add_v1)) + + +def bias_add_v1_eager_fallback(value: Annotated[Any, TV_BiasAddV1_T], bias: Annotated[Any, TV_BiasAddV1_T], name, ctx) -> Annotated[Any, TV_BiasAddV1_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([value, bias], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (value, bias) = _inputs_T + _inputs_flat = [value, bias] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BiasAddV1", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BiasAddV1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv_T = TypeVar("TV_Conv_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('conv') +def conv(input: Annotated[Any, TV_Conv_T], filter: Annotated[Any, TV_Conv_T], strides, padding: str, explicit_paddings=[], data_format:str="CHANNELS_LAST", dilations=[], batch_dims:int=1, groups:int=1, name=None) -> Annotated[Any, TV_Conv_T]: + r"""Computes a N-D convolution given (N+1+batch_dims)-D `input` and (N+2)-D `filter` tensors. + + General function for computing a N-D convolution. It is required that + `1 <= N <= 3`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`. + Tensor of type T and shape `batch_shape + spatial_shape + [in_channels]` in the + case that `channels_last_format = true` or shape + `batch_shape + [in_channels] + spatial_shape` if `channels_last_format = false`. + spatial_shape is N-dimensional with `N=2` or `N=3`. + Also note that `batch_shape` is dictated by the parameter `batch_dims` + and defaults to 1. + filter: A `Tensor`. Must have the same type as `input`. + An `(N+2)-D` Tensor with the same type as `input` and shape + `spatial_filter_shape + [in_channels, out_channels]`, where spatial_filter_shape + is N-dimensional with `N=2` or `N=3`. + strides: A list of `ints`. + 1-D tensor of length `N+2`. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[N+1] = 1`. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"CHANNELS_FIRST", "CHANNELS_LAST"`. Defaults to `"CHANNELS_LAST"`. + Used to set the data format. By default `CHANNELS_FIRST`, uses + `NHWC (2D) / NDHWC (3D)` or if `CHANNELS_LAST`, uses `NCHW (2D) / NCDHW (3D)`. + dilations: An optional list of `ints`. Defaults to `[]`. + 1-D tensor of length `N+2`. The dilation factor for each dimension of + `input`. If set to `k > 1`, there will be `k-1` skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `channels_last_format`, see above for details. Dilations in the batch + and depth dimensions must be 1. + batch_dims: An optional `int`. Defaults to `1`. + A positive integer specifying the number of batch dimensions for the input + tensor. Should be less than the rank of the input tensor. + groups: An optional `int`. Defaults to `1`. + A positive integer specifying the number of groups in which the input is split + along the channel axis. Each group is convolved separately with + `filters / groups` filters. The output is the concatenation of all the groups + results along the channel axis. Input channels and filters must both be + divisible by groups. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv", name, input, filter, "strides", strides, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", + data_format, "dilations", dilations, "batch_dims", batch_dims, + "groups", groups) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_conv( + (input, filter, strides, padding, explicit_paddings, data_format, + dilations, batch_dims, groups, name,), None) + if _result is not NotImplemented: + return _result + return conv_eager_fallback( + input, filter, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, batch_dims=batch_dims, groups=groups, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv, (), dict(input=input, filter=filter, strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + batch_dims=batch_dims, groups=groups, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_conv( + (input, filter, strides, padding, explicit_paddings, data_format, + dilations, batch_dims, groups, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "CHANNELS_LAST" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if batch_dims is None: + batch_dims = 1 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + if groups is None: + groups = 1 + groups = _execute.make_int(groups, "groups") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv", input=input, filter=filter, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, batch_dims=batch_dims, groups=groups, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv, (), dict(input=input, filter=filter, strides=strides, + padding=padding, explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + batch_dims=batch_dims, groups=groups, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "explicit_paddings", _op.get_attr("explicit_paddings"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations"), "batch_dims", + _op._get_attr_int("batch_dims"), "groups", + _op._get_attr_int("groups")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv = tf_export("raw_ops.Conv")(_ops.to_raw_op(conv)) +_dispatcher_for_conv = conv._tf_type_based_dispatcher.Dispatch + + +def conv_eager_fallback(input: Annotated[Any, TV_Conv_T], filter: Annotated[Any, TV_Conv_T], strides, padding: str, explicit_paddings, data_format: str, dilations, batch_dims: int, groups: int, name, ctx) -> Annotated[Any, TV_Conv_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "CHANNELS_LAST" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if batch_dims is None: + batch_dims = 1 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + if groups is None: + groups = 1 + groups = _execute.make_int(groups, "groups") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, ]) + (input, filter) = _inputs_T + _inputs_flat = [input, filter] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations, "batch_dims", batch_dims, "groups", groups) + _result = _execute.execute(b"Conv", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv2D_T = TypeVar("TV_Conv2D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32) + +def conv2d(input: Annotated[Any, TV_Conv2D_T], filter: Annotated[Any, TV_Conv2D_T], strides, padding: str, use_cudnn_on_gpu:bool=True, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv2D_T]: + r"""Computes a 2-D convolution given 4-D `input` and `filter` tensors. + + Given an input tensor of shape `[batch, in_height, in_width, in_channels]` + and a filter / kernel tensor of shape + `[filter_height, filter_width, in_channels, out_channels]`, this op + performs the following: + + 1. Flattens the filter to a 2-D matrix with shape + `[filter_height * filter_width * in_channels, output_channels]`. + 2. Extracts image patches from the input tensor to form a *virtual* + tensor of shape `[batch, out_height, out_width, + filter_height * filter_width * in_channels]`. + 3. For each patch, right-multiplies the filter matrix and the image patch + vector. + + In detail, with the default NHWC format, + + output[b, i, j, k] = + sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] * + filter[di, dj, q, k] + + Must have `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertices strides, `strides = [1, stride, stride, 1]`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`. + A 4-D tensor. The dimension order is interpreted according to the value + of `data_format`, see below for details. + filter: A `Tensor`. Must have the same type as `input`. + A 4-D tensor of shape + `[filter_height, filter_width, in_channels, out_channels]` + strides: A list of `ints`. + 1-D tensor of length 4. The stride of the sliding window for each + dimension of `input`. The dimension order is determined by the value of + `data_format`, see below for details. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, height, width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `data_format`, see above for details. Dilations in the batch and + depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv2D", name, input, filter, "strides", strides, + "use_cudnn_on_gpu", use_cudnn_on_gpu, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv2d_eager_fallback( + input, filter, strides=strides, use_cudnn_on_gpu=use_cudnn_on_gpu, + padding=padding, explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv2D", input=input, filter=filter, strides=strides, + padding=padding, use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "use_cudnn_on_gpu", + _op._get_attr_bool("use_cudnn_on_gpu"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv2D = tf_export("raw_ops.Conv2D")(_ops.to_raw_op(conv2d)) + + +def conv2d_eager_fallback(input: Annotated[Any, TV_Conv2D_T], filter: Annotated[Any, TV_Conv2D_T], strides, padding: str, use_cudnn_on_gpu: bool, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv2D_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, ]) + (input, filter) = _inputs_T + _inputs_flat = [input, filter] + _attrs = ("T", _attr_T, "strides", strides, "use_cudnn_on_gpu", + use_cudnn_on_gpu, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv2D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv2DBackpropFilter_T = TypeVar("TV_Conv2DBackpropFilter_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def conv2d_backprop_filter(input: Annotated[Any, TV_Conv2DBackpropFilter_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_Conv2DBackpropFilter_T], strides, padding: str, use_cudnn_on_gpu:bool=True, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv2DBackpropFilter_T]: + r"""Computes the gradients of convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + filter_sizes: A `Tensor` of type `int32`. + An integer vector representing the tensor shape of `filter`, + where `filter` is a 4-D + `[filter_height, filter_width, in_channels, out_channels]` tensor. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified with + format. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv2DBackpropFilter", name, input, filter_sizes, out_backprop, + "strides", strides, "use_cudnn_on_gpu", use_cudnn_on_gpu, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv2d_backprop_filter_eager_fallback( + input, filter_sizes, out_backprop, strides=strides, + use_cudnn_on_gpu=use_cudnn_on_gpu, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_filter' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv2DBackpropFilter", input=input, filter_sizes=filter_sizes, + out_backprop=out_backprop, strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "use_cudnn_on_gpu", + _op._get_attr_bool("use_cudnn_on_gpu"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv2DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv2DBackpropFilter = tf_export("raw_ops.Conv2DBackpropFilter")(_ops.to_raw_op(conv2d_backprop_filter)) + + +def conv2d_backprop_filter_eager_fallback(input: Annotated[Any, TV_Conv2DBackpropFilter_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_Conv2DBackpropFilter_T], strides, padding: str, use_cudnn_on_gpu: bool, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv2DBackpropFilter_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_filter' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, out_backprop) = _inputs_T + filter_sizes = _ops.convert_to_tensor(filter_sizes, _dtypes.int32) + _inputs_flat = [input, filter_sizes, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "use_cudnn_on_gpu", + use_cudnn_on_gpu, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv2DBackpropFilter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv2DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv2DBackpropFilterV2_T = TypeVar("TV_Conv2DBackpropFilterV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('conv2d_backprop_filter_v2') +def conv2d_backprop_filter_v2(input: Annotated[Any, TV_Conv2DBackpropFilterV2_T], filter: Annotated[Any, TV_Conv2DBackpropFilterV2_T], out_backprop: Annotated[Any, TV_Conv2DBackpropFilterV2_T], strides, padding: str, use_cudnn_on_gpu:bool=True, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv2DBackpropFilterV2_T]: + r"""Computes the gradients of convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + filter: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[filter_height, filter_width, in_channels, out_channels]`. + Only shape of tensor is used. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified with + format. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv2DBackpropFilterV2", name, input, filter, out_backprop, + "strides", strides, "use_cudnn_on_gpu", use_cudnn_on_gpu, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_conv2d_backprop_filter_v2( + (input, filter, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name,), None) + if _result is not NotImplemented: + return _result + return conv2d_backprop_filter_v2_eager_fallback( + input, filter, out_backprop, strides=strides, + use_cudnn_on_gpu=use_cudnn_on_gpu, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv2d_backprop_filter_v2, (), dict(input=input, filter=filter, + out_backprop=out_backprop, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_conv2d_backprop_filter_v2( + (input, filter, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv2DBackpropFilterV2", input=input, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv2d_backprop_filter_v2, (), dict(input=input, filter=filter, + out_backprop=out_backprop, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "use_cudnn_on_gpu", + _op._get_attr_bool("use_cudnn_on_gpu"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv2DBackpropFilterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv2DBackpropFilterV2 = tf_export("raw_ops.Conv2DBackpropFilterV2")(_ops.to_raw_op(conv2d_backprop_filter_v2)) +_dispatcher_for_conv2d_backprop_filter_v2 = conv2d_backprop_filter_v2._tf_type_based_dispatcher.Dispatch + + +def conv2d_backprop_filter_v2_eager_fallback(input: Annotated[Any, TV_Conv2DBackpropFilterV2_T], filter: Annotated[Any, TV_Conv2DBackpropFilterV2_T], out_backprop: Annotated[Any, TV_Conv2DBackpropFilterV2_T], strides, padding: str, use_cudnn_on_gpu: bool, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv2DBackpropFilterV2_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_filter_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "use_cudnn_on_gpu", + use_cudnn_on_gpu, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv2DBackpropFilterV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv2DBackpropFilterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv2DBackpropInput_T = TypeVar("TV_Conv2DBackpropInput_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32) + +def conv2d_backprop_input(input_sizes: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_Conv2DBackpropInput_T], out_backprop: Annotated[Any, TV_Conv2DBackpropInput_T], strides, padding: str, use_cudnn_on_gpu:bool=True, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv2DBackpropInput_T]: + r"""Computes the gradients of convolution with respect to the input. + + Args: + input_sizes: A `Tensor` of type `int32`. + An integer vector representing the shape of `input`, + where `input` is a 4-D `[batch, height, width, channels]` tensor. + filter: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`. + 4-D with shape + `[filter_height, filter_width, in_channels, out_channels]`. + out_backprop: A `Tensor`. Must have the same type as `filter`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified with + format. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `filter`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv2DBackpropInput", name, input_sizes, filter, out_backprop, + "strides", strides, "use_cudnn_on_gpu", use_cudnn_on_gpu, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv2d_backprop_input_eager_fallback( + input_sizes, filter, out_backprop, strides=strides, + use_cudnn_on_gpu=use_cudnn_on_gpu, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_input' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv2DBackpropInput", input_sizes=input_sizes, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "use_cudnn_on_gpu", + _op._get_attr_bool("use_cudnn_on_gpu"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv2DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv2DBackpropInput = tf_export("raw_ops.Conv2DBackpropInput")(_ops.to_raw_op(conv2d_backprop_input)) + + +def conv2d_backprop_input_eager_fallback(input_sizes: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_Conv2DBackpropInput_T], out_backprop: Annotated[Any, TV_Conv2DBackpropInput_T], strides, padding: str, use_cudnn_on_gpu: bool, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv2DBackpropInput_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_input' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([filter, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, ]) + (filter, out_backprop) = _inputs_T + input_sizes = _ops.convert_to_tensor(input_sizes, _dtypes.int32) + _inputs_flat = [input_sizes, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "use_cudnn_on_gpu", + use_cudnn_on_gpu, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv2DBackpropInput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv2DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv2DBackpropInputV2_T = TypeVar("TV_Conv2DBackpropInputV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('conv2d_backprop_input_v2') +def conv2d_backprop_input_v2(input: Annotated[Any, TV_Conv2DBackpropInputV2_T], filter: Annotated[Any, TV_Conv2DBackpropInputV2_T], out_backprop: Annotated[Any, TV_Conv2DBackpropInputV2_T], strides, padding: str, use_cudnn_on_gpu:bool=True, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv2DBackpropInputV2_T]: + r"""Computes the gradients of convolution with respect to the input. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + Only shape of tensor is used. + filter: A `Tensor`. Must have the same type as `input`. 4-D with shape + `[filter_height, filter_width, in_channels, out_channels]`. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified with + format. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, the list of explicit padding amounts. For the ith + dimension, the amount of padding inserted before and after the dimension is + `explicit_paddings[2 * i]` and `explicit_paddings[2 * i + 1]`, respectively. If + `padding` is not `"EXPLICIT"`, `explicit_paddings` must be empty. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv2DBackpropInputV2", name, input, filter, out_backprop, + "strides", strides, "use_cudnn_on_gpu", use_cudnn_on_gpu, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_conv2d_backprop_input_v2( + (input, filter, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name,), None) + if _result is not NotImplemented: + return _result + return conv2d_backprop_input_v2_eager_fallback( + input, filter, out_backprop, strides=strides, + use_cudnn_on_gpu=use_cudnn_on_gpu, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv2d_backprop_input_v2, (), dict(input=input, filter=filter, + out_backprop=out_backprop, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_conv2d_backprop_input_v2( + (input, filter, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv2DBackpropInputV2", input=input, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv2d_backprop_input_v2, (), dict(input=input, filter=filter, + out_backprop=out_backprop, + strides=strides, padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "use_cudnn_on_gpu", + _op._get_attr_bool("use_cudnn_on_gpu"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv2DBackpropInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv2DBackpropInputV2 = tf_export("raw_ops.Conv2DBackpropInputV2")(_ops.to_raw_op(conv2d_backprop_input_v2)) +_dispatcher_for_conv2d_backprop_input_v2 = conv2d_backprop_input_v2._tf_type_based_dispatcher.Dispatch + + +def conv2d_backprop_input_v2_eager_fallback(input: Annotated[Any, TV_Conv2DBackpropInputV2_T], filter: Annotated[Any, TV_Conv2DBackpropInputV2_T], out_backprop: Annotated[Any, TV_Conv2DBackpropInputV2_T], strides, padding: str, use_cudnn_on_gpu: bool, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv2DBackpropInputV2_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if use_cudnn_on_gpu is None: + use_cudnn_on_gpu = True + use_cudnn_on_gpu = _execute.make_bool(use_cudnn_on_gpu, "use_cudnn_on_gpu") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv2d_backprop_input_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "use_cudnn_on_gpu", + use_cudnn_on_gpu, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv2DBackpropInputV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv2DBackpropInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv3D_T = TypeVar("TV_Conv3D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def conv3d(input: Annotated[Any, TV_Conv3D_T], filter: Annotated[Any, TV_Conv3D_T], strides, padding: str, data_format:str="NDHWC", dilations=[1, 1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv3D_T]: + r"""Computes a 3-D convolution given 5-D `input` and `filter` tensors. + + In signal processing, cross-correlation is a measure of similarity of + two waveforms as a function of a time-lag applied to one of them. This + is also known as a sliding dot product or sliding inner-product. + + Our Conv3D implements a form of cross-correlation. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Shape `[batch, in_depth, in_height, in_width, in_channels]`. + filter: A `Tensor`. Must have the same type as `input`. + Shape `[filter_depth, filter_height, filter_width, in_channels, + out_channels]`. `in_channels` must match between `input` and `filter`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. + 1-D tensor of length 5. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `data_format`, see above for details. Dilations in the batch and + depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv3D", name, input, filter, "strides", strides, "padding", + padding, "data_format", data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv3d_eager_fallback( + input, filter, strides=strides, padding=padding, + data_format=data_format, dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv3D", input=input, filter=filter, strides=strides, + padding=padding, data_format=data_format, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv3D = tf_export("raw_ops.Conv3D")(_ops.to_raw_op(conv3d)) + + +def conv3d_eager_fallback(input: Annotated[Any, TV_Conv3D_T], filter: Annotated[Any, TV_Conv3D_T], strides, padding: str, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv3D_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, filter) = _inputs_T + _inputs_flat = [input, filter] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv3D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv3DBackpropFilter_T = TypeVar("TV_Conv3DBackpropFilter_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def conv3d_backprop_filter(input: Annotated[Any, TV_Conv3DBackpropFilter_T], filter: Annotated[Any, TV_Conv3DBackpropFilter_T], out_backprop: Annotated[Any, TV_Conv3DBackpropFilter_T], strides, padding: str, dilations=[1, 1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv3DBackpropFilter_T]: + r"""Computes the gradients of 3-D convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + Shape `[batch, depth, rows, cols, in_channels]`. + filter: A `Tensor`. Must have the same type as `input`. + Shape `[depth, rows, cols, in_channels, out_channels]`. + `in_channels` must match between `input` and `filter`. + out_backprop: A `Tensor`. Must have the same type as `input`. + Backprop signal of shape `[batch, out_depth, out_rows, out_cols, + out_channels]`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv3DBackpropFilter", name, input, filter, out_backprop, + "strides", strides, "padding", padding, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv3d_backprop_filter_eager_fallback( + input, filter, out_backprop, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv3DBackpropFilter", input=input, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, dilations=dilations, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv3DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv3DBackpropFilter = tf_export("raw_ops.Conv3DBackpropFilter")(_ops.to_raw_op(conv3d_backprop_filter)) + + +def conv3d_backprop_filter_eager_fallback(input: Annotated[Any, TV_Conv3DBackpropFilter_T], filter: Annotated[Any, TV_Conv3DBackpropFilter_T], out_backprop: Annotated[Any, TV_Conv3DBackpropFilter_T], strides, padding: str, dilations, name, ctx) -> Annotated[Any, TV_Conv3DBackpropFilter_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, "dilations", + dilations) + _result = _execute.execute(b"Conv3DBackpropFilter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv3DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv3DBackpropFilterV2_T = TypeVar("TV_Conv3DBackpropFilterV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['nn.conv3d_backprop_filter', 'nn.conv3d_backprop_filter_v2']) +@deprecated_endpoints('nn.conv3d_backprop_filter', 'nn.conv3d_backprop_filter_v2') +def conv3d_backprop_filter_v2(input: Annotated[Any, TV_Conv3DBackpropFilterV2_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_Conv3DBackpropFilterV2_T], strides, padding: str, data_format:str="NDHWC", dilations=[1, 1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv3DBackpropFilterV2_T]: + r"""Computes the gradients of 3-D convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Shape `[batch, depth, rows, cols, in_channels]`. + filter_sizes: A `Tensor` of type `int32`. + An integer vector representing the tensor shape of `filter`, + where `filter` is a 5-D + `[filter_depth, filter_height, filter_width, in_channels, out_channels]` + tensor. + out_backprop: A `Tensor`. Must have the same type as `input`. + Backprop signal of shape `[batch, out_depth, out_rows, out_cols, + out_channels]`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. + 1-D tensor of length 5. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `data_format`, see above for details. Dilations in the batch and + depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv3DBackpropFilterV2", name, input, filter_sizes, + out_backprop, "strides", strides, "padding", padding, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_conv3d_backprop_filter_v2( + (input, filter_sizes, out_backprop, strides, padding, data_format, + dilations, name,), None) + if _result is not NotImplemented: + return _result + return conv3d_backprop_filter_v2_eager_fallback( + input, filter_sizes, out_backprop, strides=strides, padding=padding, + data_format=data_format, dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv3d_backprop_filter_v2, (), dict(input=input, + filter_sizes=filter_sizes, + out_backprop=out_backprop, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_conv3d_backprop_filter_v2( + (input, filter_sizes, out_backprop, strides, padding, data_format, + dilations, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_filter_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_filter_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv3DBackpropFilterV2", input=input, filter_sizes=filter_sizes, + out_backprop=out_backprop, strides=strides, + padding=padding, data_format=data_format, + dilations=dilations, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + conv3d_backprop_filter_v2, (), dict(input=input, + filter_sizes=filter_sizes, + out_backprop=out_backprop, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv3DBackpropFilterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv3DBackpropFilterV2 = tf_export("raw_ops.Conv3DBackpropFilterV2")(_ops.to_raw_op(conv3d_backprop_filter_v2)) +_dispatcher_for_conv3d_backprop_filter_v2 = conv3d_backprop_filter_v2._tf_type_based_dispatcher.Dispatch + + +def conv3d_backprop_filter_v2_eager_fallback(input: Annotated[Any, TV_Conv3DBackpropFilterV2_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_Conv3DBackpropFilterV2_T], strides, padding: str, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv3DBackpropFilterV2_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_filter_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_filter_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, out_backprop) = _inputs_T + filter_sizes = _ops.convert_to_tensor(filter_sizes, _dtypes.int32) + _inputs_flat = [input, filter_sizes, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "data_format", data_format, "dilations", dilations) + _result = _execute.execute(b"Conv3DBackpropFilterV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv3DBackpropFilterV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv3DBackpropInput_T = TypeVar("TV_Conv3DBackpropInput_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def conv3d_backprop_input(input: Annotated[Any, TV_Conv3DBackpropInput_T], filter: Annotated[Any, TV_Conv3DBackpropInput_T], out_backprop: Annotated[Any, TV_Conv3DBackpropInput_T], strides, padding: str, dilations=[1, 1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv3DBackpropInput_T]: + r"""Computes the gradients of 3-D convolution with respect to the input. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + Shape `[batch, depth, rows, cols, in_channels]`. + filter: A `Tensor`. Must have the same type as `input`. + Shape `[depth, rows, cols, in_channels, out_channels]`. + `in_channels` must match between `input` and `filter`. + out_backprop: A `Tensor`. Must have the same type as `input`. + Backprop signal of shape `[batch, out_depth, out_rows, out_cols, + out_channels]`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv3DBackpropInput", name, input, filter, out_backprop, + "strides", strides, "padding", padding, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv3d_backprop_input_eager_fallback( + input, filter, out_backprop, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv3DBackpropInput", input=input, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, dilations=dilations, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv3DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv3DBackpropInput = tf_export("raw_ops.Conv3DBackpropInput")(_ops.to_raw_op(conv3d_backprop_input)) + + +def conv3d_backprop_input_eager_fallback(input: Annotated[Any, TV_Conv3DBackpropInput_T], filter: Annotated[Any, TV_Conv3DBackpropInput_T], out_backprop: Annotated[Any, TV_Conv3DBackpropInput_T], strides, padding: str, dilations, name, ctx) -> Annotated[Any, TV_Conv3DBackpropInput_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, "dilations", + dilations) + _result = _execute.execute(b"Conv3DBackpropInput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv3DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Conv3DBackpropInputV2_T = TypeVar("TV_Conv3DBackpropInputV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_Conv3DBackpropInputV2_Tshape = TypeVar("TV_Conv3DBackpropInputV2_Tshape", _atypes.Int32, _atypes.Int64) + +def conv3d_backprop_input_v2(input_sizes: Annotated[Any, TV_Conv3DBackpropInputV2_Tshape], filter: Annotated[Any, TV_Conv3DBackpropInputV2_T], out_backprop: Annotated[Any, TV_Conv3DBackpropInputV2_T], strides, padding: str, data_format:str="NDHWC", dilations=[1, 1, 1, 1, 1], name=None) -> Annotated[Any, TV_Conv3DBackpropInputV2_T]: + r"""Computes the gradients of 3-D convolution with respect to the input. + + Args: + input_sizes: A `Tensor`. Must be one of the following types: `int32`, `int64`. + An integer vector representing the tensor shape of `input`, + where `input` is a 5-D + `[batch, depth, rows, cols, in_channels]` tensor. + filter: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Shape `[depth, rows, cols, in_channels, out_channels]`. + `in_channels` must match between `input` and `filter`. + out_backprop: A `Tensor`. Must have the same type as `filter`. + Backprop signal of shape `[batch, out_depth, out_rows, out_cols, + out_channels]`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. + 1-D tensor of length 5. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `data_format`, see above for details. Dilations in the batch and + depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `filter`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Conv3DBackpropInputV2", name, input_sizes, filter, + out_backprop, "strides", strides, "padding", padding, "data_format", + data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return conv3d_backprop_input_v2_eager_fallback( + input_sizes, filter, out_backprop, strides=strides, padding=padding, + data_format=data_format, dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_input_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_input_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Conv3DBackpropInputV2", input_sizes=input_sizes, filter=filter, + out_backprop=out_backprop, strides=strides, + padding=padding, data_format=data_format, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Conv3DBackpropInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Conv3DBackpropInputV2 = tf_export("raw_ops.Conv3DBackpropInputV2")(_ops.to_raw_op(conv3d_backprop_input_v2)) + + +def conv3d_backprop_input_v2_eager_fallback(input_sizes: Annotated[Any, TV_Conv3DBackpropInputV2_Tshape], filter: Annotated[Any, TV_Conv3DBackpropInputV2_T], out_backprop: Annotated[Any, TV_Conv3DBackpropInputV2_T], strides, padding: str, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_Conv3DBackpropInputV2_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'conv3d_backprop_input_v2' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'conv3d_backprop_input_v2' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([filter, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (filter, out_backprop) = _inputs_T + _attr_Tshape, (input_sizes,) = _execute.args_to_matching_eager([input_sizes], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input_sizes, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "data_format", data_format, "dilations", dilations, "Tshape", _attr_Tshape) + _result = _execute.execute(b"Conv3DBackpropInputV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Conv3DBackpropInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DataFormatDimMap_T = TypeVar("TV_DataFormatDimMap_T", _atypes.Int32, _atypes.Int64) + +def data_format_dim_map(x: Annotated[Any, TV_DataFormatDimMap_T], src_format:str="NHWC", dst_format:str="NCHW", name=None) -> Annotated[Any, TV_DataFormatDimMap_T]: + r"""Returns the dimension index in the destination data format given the one in + + the source data format. + + Args: + x: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor with each element as a dimension index in source data format. + Must be in the range [-4, 4). + src_format: An optional `string`. Defaults to `"NHWC"`. + source data format. + dst_format: An optional `string`. Defaults to `"NCHW"`. + destination data format. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataFormatDimMap", name, x, "src_format", src_format, + "dst_format", dst_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_format_dim_map_eager_fallback( + x, src_format=src_format, dst_format=dst_format, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if src_format is None: + src_format = "NHWC" + src_format = _execute.make_str(src_format, "src_format") + if dst_format is None: + dst_format = "NCHW" + dst_format = _execute.make_str(dst_format, "dst_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataFormatDimMap", x=x, src_format=src_format, dst_format=dst_format, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "src_format", + _op.get_attr("src_format"), "dst_format", + _op.get_attr("dst_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataFormatDimMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataFormatDimMap = tf_export("raw_ops.DataFormatDimMap")(_ops.to_raw_op(data_format_dim_map)) + + +def data_format_dim_map_eager_fallback(x: Annotated[Any, TV_DataFormatDimMap_T], src_format: str, dst_format: str, name, ctx) -> Annotated[Any, TV_DataFormatDimMap_T]: + if src_format is None: + src_format = "NHWC" + src_format = _execute.make_str(src_format, "src_format") + if dst_format is None: + dst_format = "NCHW" + dst_format = _execute.make_str(dst_format, "dst_format") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x] + _attrs = ("T", _attr_T, "src_format", src_format, "dst_format", dst_format) + _result = _execute.execute(b"DataFormatDimMap", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataFormatDimMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DataFormatVecPermute_T = TypeVar("TV_DataFormatVecPermute_T", _atypes.Int32, _atypes.Int64) + +def data_format_vec_permute(x: Annotated[Any, TV_DataFormatVecPermute_T], src_format:str="NHWC", dst_format:str="NCHW", name=None) -> Annotated[Any, TV_DataFormatVecPermute_T]: + r"""Permute input tensor from `src_format` to `dst_format`. + + Given source and destination format strings of length n=4 or 5, the input + tensor must be a vector of size n or n-2, or a 2D tensor of shape + (n, 2) or (n-2, 2). + + If the first dimension of the input tensor is n-2, it is assumed that + non-spatial dimensions are omitted (i.e `N`, `C`). + + For example, with `src_format` of `NHWC`, `dst_format` of `NCHW`, and input: + ``` + [1, 2, 3, 4] + ``` + , the output will be: + ``` + [1, 4, 2, 3] + ``` + With `src_format` of `NDHWC`, `dst_format` of `NCDHW`, and input: + ``` + [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]] + ``` + , the output will be: + ``` + [[1, 6], [5, 10], [2, 7], [3, 8], [4, 9]] + ``` + With `src_format` of `NHWC`, `dst_format` of `NCHW`, and input: + ``` + [1, 2] + ``` + , the output will be: + ``` + [1, 2] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Tensor of rank 1 or 2 in source data format. + src_format: An optional `string`. Defaults to `"NHWC"`. + source data format. + dst_format: An optional `string`. Defaults to `"NCHW"`. + destination data format. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DataFormatVecPermute", name, x, "src_format", src_format, + "dst_format", dst_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return data_format_vec_permute_eager_fallback( + x, src_format=src_format, dst_format=dst_format, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if src_format is None: + src_format = "NHWC" + src_format = _execute.make_str(src_format, "src_format") + if dst_format is None: + dst_format = "NCHW" + dst_format = _execute.make_str(dst_format, "dst_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DataFormatVecPermute", x=x, src_format=src_format, + dst_format=dst_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "src_format", + _op.get_attr("src_format"), "dst_format", + _op.get_attr("dst_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DataFormatVecPermute", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DataFormatVecPermute = tf_export("raw_ops.DataFormatVecPermute")(_ops.to_raw_op(data_format_vec_permute)) + + +def data_format_vec_permute_eager_fallback(x: Annotated[Any, TV_DataFormatVecPermute_T], src_format: str, dst_format: str, name, ctx) -> Annotated[Any, TV_DataFormatVecPermute_T]: + if src_format is None: + src_format = "NHWC" + src_format = _execute.make_str(src_format, "src_format") + if dst_format is None: + dst_format = "NCHW" + dst_format = _execute.make_str(dst_format, "dst_format") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [x] + _attrs = ("T", _attr_T, "src_format", src_format, "dst_format", dst_format) + _result = _execute.execute(b"DataFormatVecPermute", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DataFormatVecPermute", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DepthwiseConv2dNative_T = TypeVar("TV_DepthwiseConv2dNative_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def depthwise_conv2d_native(input: Annotated[Any, TV_DepthwiseConv2dNative_T], filter: Annotated[Any, TV_DepthwiseConv2dNative_T], strides, padding: str, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_DepthwiseConv2dNative_T]: + r"""Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors. + + Given an input tensor of shape `[batch, in_height, in_width, in_channels]` + and a filter / kernel tensor of shape + `[filter_height, filter_width, in_channels, channel_multiplier]`, containing + `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies + a different filter to each input channel (expanding from 1 channel to + `channel_multiplier` channels for each), then concatenates the results + together. Thus, the output has `in_channels * channel_multiplier` channels. + + ``` + for k in 0..in_channels-1 + for q in 0..channel_multiplier-1 + output[b, i, j, k * channel_multiplier + q] = + sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] * + filter[di, dj, k, q] + ``` + + Must have `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertices strides, `strides = [1, stride, stride, 1]`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + filter: A `Tensor`. Must have the same type as `input`. + strides: A list of `ints`. + 1-D of length 4. The stride of the sliding window for each dimension + of `input`. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, height, width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DepthwiseConv2dNative", name, input, filter, "strides", + strides, "padding", padding, "explicit_paddings", explicit_paddings, + "data_format", data_format, "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return depthwise_conv2d_native_eager_fallback( + input, filter, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DepthwiseConv2dNative", input=input, filter=filter, strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, dilations=dilations, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "explicit_paddings", _op.get_attr("explicit_paddings"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DepthwiseConv2dNative", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DepthwiseConv2dNative = tf_export("raw_ops.DepthwiseConv2dNative")(_ops.to_raw_op(depthwise_conv2d_native)) + + +def depthwise_conv2d_native_eager_fallback(input: Annotated[Any, TV_DepthwiseConv2dNative_T], filter: Annotated[Any, TV_DepthwiseConv2dNative_T], strides, padding: str, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_DepthwiseConv2dNative_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, filter) = _inputs_T + _inputs_flat = [input, filter] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + _result = _execute.execute(b"DepthwiseConv2dNative", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DepthwiseConv2dNative", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DepthwiseConv2dNativeBackpropFilter_T = TypeVar("TV_DepthwiseConv2dNativeBackpropFilter_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def depthwise_conv2d_native_backprop_filter(input: Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T], strides, padding: str, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T]: + r"""Computes the gradients of depthwise convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape based on `data_format`. For example, if + `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height, + in_width, in_channels]` tensor. + filter_sizes: A `Tensor` of type `int32`. + An integer vector representing the tensor shape of `filter`, + where `filter` is a 4-D + `[filter_height, filter_width, in_channels, depthwise_multiplier]` tensor. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape based on `data_format`. + For example, if `data_format` is 'NHWC' then + out_backprop shape is `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, height, width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DepthwiseConv2dNativeBackpropFilter", name, input, + filter_sizes, out_backprop, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return depthwise_conv2d_native_backprop_filter_eager_fallback( + input, filter_sizes, out_backprop, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DepthwiseConv2dNativeBackpropFilter", input=input, + filter_sizes=filter_sizes, + out_backprop=out_backprop, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "explicit_paddings", _op.get_attr("explicit_paddings"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DepthwiseConv2dNativeBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DepthwiseConv2dNativeBackpropFilter = tf_export("raw_ops.DepthwiseConv2dNativeBackpropFilter")(_ops.to_raw_op(depthwise_conv2d_native_backprop_filter)) + + +def depthwise_conv2d_native_backprop_filter_eager_fallback(input: Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T], filter_sizes: Annotated[Any, _atypes.Int32], out_backprop: Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T], strides, padding: str, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_DepthwiseConv2dNativeBackpropFilter_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native_backprop_filter' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, out_backprop) = _inputs_T + filter_sizes = _ops.convert_to_tensor(filter_sizes, _dtypes.int32) + _inputs_flat = [input, filter_sizes, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + _result = _execute.execute(b"DepthwiseConv2dNativeBackpropFilter", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DepthwiseConv2dNativeBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DepthwiseConv2dNativeBackpropInput_T = TypeVar("TV_DepthwiseConv2dNativeBackpropInput_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def depthwise_conv2d_native_backprop_input(input_sizes: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T], out_backprop: Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T], strides, padding: str, explicit_paddings=[], data_format:str="NHWC", dilations=[1, 1, 1, 1], name=None) -> Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T]: + r"""Computes the gradients of depthwise convolution with respect to the input. + + Args: + input_sizes: A `Tensor` of type `int32`. + An integer vector representing the shape of `input`, based + on `data_format`. For example, if `data_format` is 'NHWC' then + `input` is a 4-D `[batch, height, width, channels]` tensor. + filter: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape + `[filter_height, filter_width, in_channels, depthwise_multiplier]`. + out_backprop: A `Tensor`. Must have the same type as `filter`. + 4-D with shape based on `data_format`. + For example, if `data_format` is 'NHWC' then + out_backprop shape is `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, height, width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each filter + element on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `filter`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DepthwiseConv2dNativeBackpropInput", name, input_sizes, filter, + out_backprop, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return depthwise_conv2d_native_backprop_input_eager_fallback( + input_sizes, filter, out_backprop, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DepthwiseConv2dNativeBackpropInput", input_sizes=input_sizes, + filter=filter, + out_backprop=out_backprop, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "explicit_paddings", _op.get_attr("explicit_paddings"), + "data_format", _op.get_attr("data_format"), "dilations", + _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DepthwiseConv2dNativeBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DepthwiseConv2dNativeBackpropInput = tf_export("raw_ops.DepthwiseConv2dNativeBackpropInput")(_ops.to_raw_op(depthwise_conv2d_native_backprop_input)) + + +def depthwise_conv2d_native_backprop_input_eager_fallback(input_sizes: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T], out_backprop: Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T], strides, padding: str, explicit_paddings, data_format: str, dilations, name, ctx) -> Annotated[Any, TV_DepthwiseConv2dNativeBackpropInput_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'depthwise_conv2d_native_backprop_input' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_T, _inputs_T = _execute.args_to_matching_eager([filter, out_backprop], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (filter, out_backprop) = _inputs_T + input_sizes = _ops.convert_to_tensor(input_sizes, _dtypes.int32) + _inputs_flat = [input_sizes, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, + "dilations", dilations) + _result = _execute.execute(b"DepthwiseConv2dNativeBackpropInput", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DepthwiseConv2dNativeBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Dilation2D_T = TypeVar("TV_Dilation2D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def dilation2d(input: Annotated[Any, TV_Dilation2D_T], filter: Annotated[Any, TV_Dilation2D_T], strides, rates, padding: str, name=None) -> Annotated[Any, TV_Dilation2D_T]: + r"""Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors. + + The `input` tensor has shape `[batch, in_height, in_width, depth]` and the + `filter` tensor has shape `[filter_height, filter_width, depth]`, i.e., each + input channel is processed independently of the others with its own structuring + function. The `output` tensor has shape + `[batch, out_height, out_width, depth]`. The spatial dimensions of the output + tensor depend on the `padding` algorithm. We currently only support the default + "NHWC" `data_format`. + + In detail, the grayscale morphological 2-D dilation is the max-sum correlation + (for consistency with `conv2d`, we use unmirrored filters): + + output[b, y, x, c] = + max_{dy, dx} input[b, + strides[1] * y + rates[1] * dy, + strides[2] * x + rates[2] * dx, + c] + + filter[dy, dx, c] + + Max-pooling is a special case when the filter has size equal to the pooling + kernel size and contains all zeros. + + Note on duality: The dilation of `input` by the `filter` is equal to the + negation of the erosion of `-input` by the reflected `filter`. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 4-D with shape `[batch, in_height, in_width, depth]`. + filter: A `Tensor`. Must have the same type as `input`. + 3-D with shape `[filter_height, filter_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the input + tensor. Must be: `[1, stride_height, stride_width, 1]`. + rates: A list of `ints` that has length `>= 4`. + The input stride for atrous morphological dilation. Must be: + `[1, rate_height, rate_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Dilation2D", name, input, filter, "strides", strides, "rates", + rates, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dilation2d_eager_fallback( + input, filter, strides=strides, rates=rates, padding=padding, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Dilation2D", input=input, filter=filter, strides=strides, + rates=rates, padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "rates", _op.get_attr("rates"), + "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Dilation2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Dilation2D = tf_export("raw_ops.Dilation2D")(_ops.to_raw_op(dilation2d)) + + +def dilation2d_eager_fallback(input: Annotated[Any, TV_Dilation2D_T], filter: Annotated[Any, TV_Dilation2D_T], strides, rates, padding: str, name, ctx) -> Annotated[Any, TV_Dilation2D_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (input, filter) = _inputs_T + _inputs_flat = [input, filter] + _attrs = ("T", _attr_T, "strides", strides, "rates", rates, "padding", + padding) + _result = _execute.execute(b"Dilation2D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Dilation2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Dilation2DBackpropFilter_T = TypeVar("TV_Dilation2DBackpropFilter_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def dilation2d_backprop_filter(input: Annotated[Any, TV_Dilation2DBackpropFilter_T], filter: Annotated[Any, TV_Dilation2DBackpropFilter_T], out_backprop: Annotated[Any, TV_Dilation2DBackpropFilter_T], strides, rates, padding: str, name=None) -> Annotated[Any, TV_Dilation2DBackpropFilter_T]: + r"""Computes the gradient of morphological 2-D dilation with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 4-D with shape `[batch, in_height, in_width, depth]`. + filter: A `Tensor`. Must have the same type as `input`. + 3-D with shape `[filter_height, filter_width, depth]`. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + 1-D of length 4. The stride of the sliding window for each dimension of + the input tensor. Must be: `[1, stride_height, stride_width, 1]`. + rates: A list of `ints` that has length `>= 4`. + 1-D of length 4. The input stride for atrous morphological dilation. + Must be: `[1, rate_height, rate_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Dilation2DBackpropFilter", name, input, filter, out_backprop, + "strides", strides, "rates", rates, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dilation2d_backprop_filter_eager_fallback( + input, filter, out_backprop, strides=strides, rates=rates, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d_backprop_filter' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Dilation2DBackpropFilter", input=input, filter=filter, + out_backprop=out_backprop, + strides=strides, rates=rates, + padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "rates", _op.get_attr("rates"), + "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Dilation2DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Dilation2DBackpropFilter = tf_export("raw_ops.Dilation2DBackpropFilter")(_ops.to_raw_op(dilation2d_backprop_filter)) + + +def dilation2d_backprop_filter_eager_fallback(input: Annotated[Any, TV_Dilation2DBackpropFilter_T], filter: Annotated[Any, TV_Dilation2DBackpropFilter_T], out_backprop: Annotated[Any, TV_Dilation2DBackpropFilter_T], strides, rates, padding: str, name, ctx) -> Annotated[Any, TV_Dilation2DBackpropFilter_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d_backprop_filter' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d_backprop_filter' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "rates", rates, "padding", + padding) + _result = _execute.execute(b"Dilation2DBackpropFilter", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Dilation2DBackpropFilter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Dilation2DBackpropInput_T = TypeVar("TV_Dilation2DBackpropInput_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def dilation2d_backprop_input(input: Annotated[Any, TV_Dilation2DBackpropInput_T], filter: Annotated[Any, TV_Dilation2DBackpropInput_T], out_backprop: Annotated[Any, TV_Dilation2DBackpropInput_T], strides, rates, padding: str, name=None) -> Annotated[Any, TV_Dilation2DBackpropInput_T]: + r"""Computes the gradient of morphological 2-D dilation with respect to the input. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 4-D with shape `[batch, in_height, in_width, depth]`. + filter: A `Tensor`. Must have the same type as `input`. + 3-D with shape `[filter_height, filter_width, depth]`. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + 1-D of length 4. The stride of the sliding window for each dimension of + the input tensor. Must be: `[1, stride_height, stride_width, 1]`. + rates: A list of `ints` that has length `>= 4`. + 1-D of length 4. The input stride for atrous morphological dilation. + Must be: `[1, rate_height, rate_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Dilation2DBackpropInput", name, input, filter, out_backprop, + "strides", strides, "rates", rates, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dilation2d_backprop_input_eager_fallback( + input, filter, out_backprop, strides=strides, rates=rates, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d_backprop_input' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Dilation2DBackpropInput", input=input, filter=filter, + out_backprop=out_backprop, strides=strides, + rates=rates, padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "strides", + _op.get_attr("strides"), "rates", _op.get_attr("rates"), + "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Dilation2DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Dilation2DBackpropInput = tf_export("raw_ops.Dilation2DBackpropInput")(_ops.to_raw_op(dilation2d_backprop_input)) + + +def dilation2d_backprop_input_eager_fallback(input: Annotated[Any, TV_Dilation2DBackpropInput_T], filter: Annotated[Any, TV_Dilation2DBackpropInput_T], out_backprop: Annotated[Any, TV_Dilation2DBackpropInput_T], strides, rates, padding: str, name, ctx) -> Annotated[Any, TV_Dilation2DBackpropInput_T]: + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'dilation2d_backprop_input' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + if not isinstance(rates, (list, tuple)): + raise TypeError( + "Expected list for 'rates' argument to " + "'dilation2d_backprop_input' Op, not %r." % rates) + rates = [_execute.make_int(_i, "rates") for _i in rates] + padding = _execute.make_str(padding, "padding") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter, out_backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (input, filter, out_backprop) = _inputs_T + _inputs_flat = [input, filter, out_backprop] + _attrs = ("T", _attr_T, "strides", strides, "rates", rates, "padding", + padding) + _result = _execute.execute(b"Dilation2DBackpropInput", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Dilation2DBackpropInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Elu_T = TypeVar("TV_Elu_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.elu') +def elu(features: Annotated[Any, TV_Elu_T], name=None) -> Annotated[Any, TV_Elu_T]: + r"""Computes the exponential linear function. + + The ELU function is defined as: + + * $ e ^ x - 1 $ if $ x < 0 $ + * $ x $ if $ x >= 0 $ + + Examples: + + >>> tf.nn.elu(1.0) + + >>> tf.nn.elu(0.0) + + >>> tf.nn.elu(-1000.0) + + + See [Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) + ](http://arxiv.org/abs/1511.07289) + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Elu", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_elu( + (features, name,), None) + if _result is not NotImplemented: + return _result + return elu_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + elu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_elu( + (features, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Elu", features=features, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + elu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Elu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Elu = tf_export("raw_ops.Elu")(_ops.to_raw_op(elu)) +_dispatcher_for_elu = elu._tf_type_based_dispatcher.Dispatch + + +def elu_eager_fallback(features: Annotated[Any, TV_Elu_T], name, ctx) -> Annotated[Any, TV_Elu_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Elu", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Elu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_EluGrad_T = TypeVar("TV_EluGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def elu_grad(gradients: Annotated[Any, TV_EluGrad_T], outputs: Annotated[Any, TV_EluGrad_T], name=None) -> Annotated[Any, TV_EluGrad_T]: + r"""Computes gradients for the exponential linear (Elu) operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The backpropagated gradients to the corresponding Elu operation. + outputs: A `Tensor`. Must have the same type as `gradients`. + The outputs of the corresponding Elu operation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EluGrad", name, gradients, outputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return elu_grad_eager_fallback( + gradients, outputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EluGrad", gradients=gradients, outputs=outputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EluGrad = tf_export("raw_ops.EluGrad")(_ops.to_raw_op(elu_grad)) + + +def elu_grad_eager_fallback(gradients: Annotated[Any, TV_EluGrad_T], outputs: Annotated[Any, TV_EluGrad_T], name, ctx) -> Annotated[Any, TV_EluGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, outputs], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (gradients, outputs) = _inputs_T + _inputs_flat = [gradients, outputs] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"EluGrad", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FractionalAvgPoolOutput = collections.namedtuple( + "FractionalAvgPool", + ["output", "row_pooling_sequence", "col_pooling_sequence"]) + + +TV_FractionalAvgPool_T = TypeVar("TV_FractionalAvgPool_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def fractional_avg_pool(value: Annotated[Any, TV_FractionalAvgPool_T], pooling_ratio, pseudo_random:bool=False, overlapping:bool=False, deterministic:bool=False, seed:int=0, seed2:int=0, name=None): + r"""Performs fractional average pooling on the input. + + Fractional average pooling is similar to Fractional max pooling in the pooling + region generation step. The only difference is that after pooling regions are + generated, a mean operation is performed instead of a max operation in each + pooling region. + + Args: + value: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`. + 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: A list of `floats` that has length `>= 4`. + Pooling ratio for each dimension of `value`, currently only + supports row and col dimension and should be >= 1.0. For example, a valid + pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements + must be 1.0 because we don't allow pooling on batch and channels + dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions + respectively. + pseudo_random: An optional `bool`. Defaults to `False`. + When set to True, generates the pooling sequence in a + pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin + Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for + difference between pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. + When set to True, it means when pooling, the values at the boundary + of adjacent pooling cells are used by both cells. For example: + + `index 0 1 2 3 4` + + `value 20 5 16 3 7` + + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. + The result would be [41/3, 26/3] for fractional avg pooling. + deterministic: An optional `bool`. Defaults to `False`. + When set to True, a fixed pooling region will be used when + iterating over a FractionalAvgPool node in the computation graph. Mainly used + in unit test to make FractionalAvgPool deterministic. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, row_pooling_sequence, col_pooling_sequence). + + output: A `Tensor`. Has the same type as `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FractionalAvgPool", name, value, "pooling_ratio", + pooling_ratio, "pseudo_random", pseudo_random, "overlapping", + overlapping, "deterministic", deterministic, "seed", seed, "seed2", + seed2) + _result = _FractionalAvgPoolOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fractional_avg_pool_eager_fallback( + value, pooling_ratio=pooling_ratio, pseudo_random=pseudo_random, + overlapping=overlapping, deterministic=deterministic, seed=seed, + seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(pooling_ratio, (list, tuple)): + raise TypeError( + "Expected list for 'pooling_ratio' argument to " + "'fractional_avg_pool' Op, not %r." % pooling_ratio) + pooling_ratio = [_execute.make_float(_f, "pooling_ratio") for _f in pooling_ratio] + if pseudo_random is None: + pseudo_random = False + pseudo_random = _execute.make_bool(pseudo_random, "pseudo_random") + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + if deterministic is None: + deterministic = False + deterministic = _execute.make_bool(deterministic, "deterministic") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FractionalAvgPool", value=value, pooling_ratio=pooling_ratio, + pseudo_random=pseudo_random, + overlapping=overlapping, + deterministic=deterministic, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pooling_ratio", _op.get_attr("pooling_ratio"), "pseudo_random", + _op._get_attr_bool("pseudo_random"), "overlapping", + _op._get_attr_bool("overlapping"), "deterministic", + _op._get_attr_bool("deterministic"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2"), + "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FractionalAvgPool", _inputs_flat, _attrs, _result) + _result = _FractionalAvgPoolOutput._make(_result) + return _result + +FractionalAvgPool = tf_export("raw_ops.FractionalAvgPool")(_ops.to_raw_op(fractional_avg_pool)) + + +def fractional_avg_pool_eager_fallback(value: Annotated[Any, TV_FractionalAvgPool_T], pooling_ratio, pseudo_random: bool, overlapping: bool, deterministic: bool, seed: int, seed2: int, name, ctx): + if not isinstance(pooling_ratio, (list, tuple)): + raise TypeError( + "Expected list for 'pooling_ratio' argument to " + "'fractional_avg_pool' Op, not %r." % pooling_ratio) + pooling_ratio = [_execute.make_float(_f, "pooling_ratio") for _f in pooling_ratio] + if pseudo_random is None: + pseudo_random = False + pseudo_random = _execute.make_bool(pseudo_random, "pseudo_random") + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + if deterministic is None: + deterministic = False + deterministic = _execute.make_bool(deterministic, "deterministic") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [value] + _attrs = ("pooling_ratio", pooling_ratio, "pseudo_random", pseudo_random, + "overlapping", overlapping, "deterministic", deterministic, "seed", seed, + "seed2", seed2, "T", _attr_T) + _result = _execute.execute(b"FractionalAvgPool", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FractionalAvgPool", _inputs_flat, _attrs, _result) + _result = _FractionalAvgPoolOutput._make(_result) + return _result + + +TV_FractionalAvgPoolGrad_T = TypeVar("TV_FractionalAvgPoolGrad_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def fractional_avg_pool_grad(orig_input_tensor_shape: Annotated[Any, _atypes.Int64], out_backprop: Annotated[Any, TV_FractionalAvgPoolGrad_T], row_pooling_sequence: Annotated[Any, _atypes.Int64], col_pooling_sequence: Annotated[Any, _atypes.Int64], overlapping:bool=False, name=None) -> Annotated[Any, TV_FractionalAvgPoolGrad_T]: + r"""Computes gradient of the FractionalAvgPool function. + + Unlike FractionalMaxPoolGrad, we don't need to find arg_max for + FractionalAvgPoolGrad, we just need to evenly back-propagate each element of + out_backprop to those indices that form the same pooling cell. Therefore, we + just need to know the shape of original input tensor, instead of the whole + tensor. + + Args: + orig_input_tensor_shape: A `Tensor` of type `int64`. + Original input tensor shape for `fractional_avg_pool` + out_backprop: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`. + 4-D with shape `[batch, height, width, channels]`. Gradients + w.r.t. the output of `fractional_avg_pool`. + row_pooling_sequence: A `Tensor` of type `int64`. + row pooling sequence, form pooling region with + col_pooling_sequence. + col_pooling_sequence: A `Tensor` of type `int64`. + column pooling sequence, form pooling region with + row_pooling sequence. + overlapping: An optional `bool`. Defaults to `False`. + When set to True, it means when pooling, the values at the boundary + of adjacent pooling cells are used by both cells. For example: + + `index 0 1 2 3 4` + + `value 20 5 16 3 7` + + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. + The result would be [41/3, 26/3] for fractional avg pooling. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `out_backprop`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FractionalAvgPoolGrad", name, orig_input_tensor_shape, + out_backprop, row_pooling_sequence, col_pooling_sequence, + "overlapping", overlapping) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fractional_avg_pool_grad_eager_fallback( + orig_input_tensor_shape, out_backprop, row_pooling_sequence, + col_pooling_sequence, overlapping=overlapping, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FractionalAvgPoolGrad", orig_input_tensor_shape=orig_input_tensor_shape, + out_backprop=out_backprop, + row_pooling_sequence=row_pooling_sequence, + col_pooling_sequence=col_pooling_sequence, + overlapping=overlapping, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("overlapping", _op._get_attr_bool("overlapping"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FractionalAvgPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FractionalAvgPoolGrad = tf_export("raw_ops.FractionalAvgPoolGrad")(_ops.to_raw_op(fractional_avg_pool_grad)) + + +def fractional_avg_pool_grad_eager_fallback(orig_input_tensor_shape: Annotated[Any, _atypes.Int64], out_backprop: Annotated[Any, TV_FractionalAvgPoolGrad_T], row_pooling_sequence: Annotated[Any, _atypes.Int64], col_pooling_sequence: Annotated[Any, _atypes.Int64], overlapping: bool, name, ctx) -> Annotated[Any, TV_FractionalAvgPoolGrad_T]: + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + _attr_T, (out_backprop,) = _execute.args_to_matching_eager([out_backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + orig_input_tensor_shape = _ops.convert_to_tensor(orig_input_tensor_shape, _dtypes.int64) + row_pooling_sequence = _ops.convert_to_tensor(row_pooling_sequence, _dtypes.int64) + col_pooling_sequence = _ops.convert_to_tensor(col_pooling_sequence, _dtypes.int64) + _inputs_flat = [orig_input_tensor_shape, out_backprop, row_pooling_sequence, col_pooling_sequence] + _attrs = ("overlapping", overlapping, "T", _attr_T) + _result = _execute.execute(b"FractionalAvgPoolGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FractionalAvgPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FractionalMaxPoolOutput = collections.namedtuple( + "FractionalMaxPool", + ["output", "row_pooling_sequence", "col_pooling_sequence"]) + + +TV_FractionalMaxPool_T = TypeVar("TV_FractionalMaxPool_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def fractional_max_pool(value: Annotated[Any, TV_FractionalMaxPool_T], pooling_ratio, pseudo_random:bool=False, overlapping:bool=False, deterministic:bool=False, seed:int=0, seed2:int=0, name=None): + r"""Performs fractional max pooling on the input. + + Fractional max pooling is slightly different than regular max pooling. In + regular max pooling, you downsize an input set by taking the maximum value of + smaller N x N subsections of the set (often 2x2), and try to reduce the set by + a factor of N, where N is an integer. Fractional max pooling, as you might + expect from the word "fractional", means that the overall reduction ratio N + does not have to be an integer. + + The sizes of the pooling regions are generated randomly but are fairly uniform. + For example, let's look at the height dimension, and the constraints on the + list of rows that will be pool boundaries. + + First we define the following: + + 1. input_row_length : the number of rows from the input set + 2. output_row_length : which will be smaller than the input + 3. alpha = input_row_length / output_row_length : our reduction ratio + 4. K = floor(alpha) + 5. row_pooling_sequence : this is the result list of pool boundary rows + + Then, row_pooling_sequence should satisfy: + + 1. a[0] = 0 : the first value of the sequence is 0 + 2. a[end] = input_row_length : the last value of the sequence is the size + 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size + 4. length(row_pooling_sequence) = output_row_length+1 + + For more details on fractional max pooling, see this paper: + [Benjamin Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) + + Args: + value: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`. + 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: A list of `floats` that has length `>= 4`. + Pooling ratio for each dimension of `value`, currently only + supports row and col dimension and should be >= 1.0. For example, a valid + pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements + must be 1.0 because we don't allow pooling on batch and channels + dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions + respectively. + pseudo_random: An optional `bool`. Defaults to `False`. + When set to True, generates the pooling sequence in a + pseudorandom fashion, otherwise, in a random fashion. Check paper [Benjamin + Graham, Fractional Max-Pooling](http://arxiv.org/abs/1412.6071) for + difference between pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. + When set to True, it means when pooling, the values at the boundary + of adjacent pooling cells are used by both cells. For example: + + `index 0 1 2 3 4` + + `value 20 5 16 3 7` + + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. + The result would be [20, 16] for fractional max pooling. + deterministic: An optional `bool`. Defaults to `False`. + When set to True, a fixed pooling region will be used when + iterating over a FractionalMaxPool node in the computation graph. Mainly used + in unit test to make FractionalMaxPool deterministic. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + An second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, row_pooling_sequence, col_pooling_sequence). + + output: A `Tensor`. Has the same type as `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FractionalMaxPool", name, value, "pooling_ratio", + pooling_ratio, "pseudo_random", pseudo_random, "overlapping", + overlapping, "deterministic", deterministic, "seed", seed, "seed2", + seed2) + _result = _FractionalMaxPoolOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fractional_max_pool_eager_fallback( + value, pooling_ratio=pooling_ratio, pseudo_random=pseudo_random, + overlapping=overlapping, deterministic=deterministic, seed=seed, + seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(pooling_ratio, (list, tuple)): + raise TypeError( + "Expected list for 'pooling_ratio' argument to " + "'fractional_max_pool' Op, not %r." % pooling_ratio) + pooling_ratio = [_execute.make_float(_f, "pooling_ratio") for _f in pooling_ratio] + if pseudo_random is None: + pseudo_random = False + pseudo_random = _execute.make_bool(pseudo_random, "pseudo_random") + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + if deterministic is None: + deterministic = False + deterministic = _execute.make_bool(deterministic, "deterministic") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FractionalMaxPool", value=value, pooling_ratio=pooling_ratio, + pseudo_random=pseudo_random, + overlapping=overlapping, + deterministic=deterministic, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pooling_ratio", _op.get_attr("pooling_ratio"), "pseudo_random", + _op._get_attr_bool("pseudo_random"), "overlapping", + _op._get_attr_bool("overlapping"), "deterministic", + _op._get_attr_bool("deterministic"), "seed", + _op._get_attr_int("seed"), "seed2", _op._get_attr_int("seed2"), + "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FractionalMaxPool", _inputs_flat, _attrs, _result) + _result = _FractionalMaxPoolOutput._make(_result) + return _result + +FractionalMaxPool = tf_export("raw_ops.FractionalMaxPool")(_ops.to_raw_op(fractional_max_pool)) + + +def fractional_max_pool_eager_fallback(value: Annotated[Any, TV_FractionalMaxPool_T], pooling_ratio, pseudo_random: bool, overlapping: bool, deterministic: bool, seed: int, seed2: int, name, ctx): + if not isinstance(pooling_ratio, (list, tuple)): + raise TypeError( + "Expected list for 'pooling_ratio' argument to " + "'fractional_max_pool' Op, not %r." % pooling_ratio) + pooling_ratio = [_execute.make_float(_f, "pooling_ratio") for _f in pooling_ratio] + if pseudo_random is None: + pseudo_random = False + pseudo_random = _execute.make_bool(pseudo_random, "pseudo_random") + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + if deterministic is None: + deterministic = False + deterministic = _execute.make_bool(deterministic, "deterministic") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [value] + _attrs = ("pooling_ratio", pooling_ratio, "pseudo_random", pseudo_random, + "overlapping", overlapping, "deterministic", deterministic, "seed", seed, + "seed2", seed2, "T", _attr_T) + _result = _execute.execute(b"FractionalMaxPool", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FractionalMaxPool", _inputs_flat, _attrs, _result) + _result = _FractionalMaxPoolOutput._make(_result) + return _result + + +TV_FractionalMaxPoolGrad_T = TypeVar("TV_FractionalMaxPoolGrad_T", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def fractional_max_pool_grad(orig_input: Annotated[Any, TV_FractionalMaxPoolGrad_T], orig_output: Annotated[Any, TV_FractionalMaxPoolGrad_T], out_backprop: Annotated[Any, TV_FractionalMaxPoolGrad_T], row_pooling_sequence: Annotated[Any, _atypes.Int64], col_pooling_sequence: Annotated[Any, _atypes.Int64], overlapping:bool=False, name=None) -> Annotated[Any, TV_FractionalMaxPoolGrad_T]: + r"""Computes gradient of the FractionalMaxPool function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `int64`. + Original input for `fractional_max_pool` + orig_output: A `Tensor`. Must have the same type as `orig_input`. + Original output for `fractional_max_pool` + out_backprop: A `Tensor`. Must have the same type as `orig_input`. + 4-D with shape `[batch, height, width, channels]`. Gradients + w.r.t. the output of `fractional_max_pool`. + row_pooling_sequence: A `Tensor` of type `int64`. + row pooling sequence, form pooling region with + col_pooling_sequence. + col_pooling_sequence: A `Tensor` of type `int64`. + column pooling sequence, form pooling region with + row_pooling sequence. + overlapping: An optional `bool`. Defaults to `False`. + When set to True, it means when pooling, the values at the boundary + of adjacent pooling cells are used by both cells. For example: + + `index 0 1 2 3 4` + + `value 20 5 16 3 7` + + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. + The result would be [20, 16] for fractional max pooling. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FractionalMaxPoolGrad", name, orig_input, orig_output, + out_backprop, row_pooling_sequence, col_pooling_sequence, + "overlapping", overlapping) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fractional_max_pool_grad_eager_fallback( + orig_input, orig_output, out_backprop, row_pooling_sequence, + col_pooling_sequence, overlapping=overlapping, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FractionalMaxPoolGrad", orig_input=orig_input, + orig_output=orig_output, + out_backprop=out_backprop, + row_pooling_sequence=row_pooling_sequence, + col_pooling_sequence=col_pooling_sequence, + overlapping=overlapping, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("overlapping", _op._get_attr_bool("overlapping"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FractionalMaxPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FractionalMaxPoolGrad = tf_export("raw_ops.FractionalMaxPoolGrad")(_ops.to_raw_op(fractional_max_pool_grad)) + + +def fractional_max_pool_grad_eager_fallback(orig_input: Annotated[Any, TV_FractionalMaxPoolGrad_T], orig_output: Annotated[Any, TV_FractionalMaxPoolGrad_T], out_backprop: Annotated[Any, TV_FractionalMaxPoolGrad_T], row_pooling_sequence: Annotated[Any, _atypes.Int64], col_pooling_sequence: Annotated[Any, _atypes.Int64], overlapping: bool, name, ctx) -> Annotated[Any, TV_FractionalMaxPoolGrad_T]: + if overlapping is None: + overlapping = False + overlapping = _execute.make_bool(overlapping, "overlapping") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, out_backprop], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + (orig_input, orig_output, out_backprop) = _inputs_T + row_pooling_sequence = _ops.convert_to_tensor(row_pooling_sequence, _dtypes.int64) + col_pooling_sequence = _ops.convert_to_tensor(col_pooling_sequence, _dtypes.int64) + _inputs_flat = [orig_input, orig_output, out_backprop, row_pooling_sequence, col_pooling_sequence] + _attrs = ("overlapping", overlapping, "T", _attr_T) + _result = _execute.execute(b"FractionalMaxPoolGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FractionalMaxPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FusedBatchNormOutput = collections.namedtuple( + "FusedBatchNorm", + ["y", "batch_mean", "batch_variance", "reserve_space_1", "reserve_space_2"]) + + +TV_FusedBatchNorm_T = TypeVar("TV_FusedBatchNorm_T", bound=_atypes.Float32) + +def _fused_batch_norm(x: Annotated[Any, TV_FusedBatchNorm_T], scale: Annotated[Any, TV_FusedBatchNorm_T], offset: Annotated[Any, TV_FusedBatchNorm_T], mean: Annotated[Any, TV_FusedBatchNorm_T], variance: Annotated[Any, TV_FusedBatchNorm_T], epsilon:float=0.0001, exponential_avg_factor:float=1, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + x: A `Tensor`. Must be one of the following types: `float32`. + A 4D Tensor for input data. + scale: A `Tensor`. Must have the same type as `x`. + A 1D Tensor for scaling factor, to scale the normalized x. + offset: A `Tensor`. Must have the same type as `x`. + A 1D Tensor for offset, to shift to the normalized x. + mean: A `Tensor`. Must have the same type as `x`. + A 1D Tensor for population mean. Used for inference only; + must be empty for training. + variance: A `Tensor`. Must have the same type as `x`. + A 1D Tensor for population variance. Used for inference only; + must be empty for training. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + exponential_avg_factor: An optional `float`. Defaults to `1`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + The data format for x and y. Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, batch_mean, batch_variance, reserve_space_1, reserve_space_2). + + y: A `Tensor`. Has the same type as `x`. + batch_mean: A `Tensor`. Has the same type as `x`. + batch_variance: A `Tensor`. Has the same type as `x`. + reserve_space_1: A `Tensor`. Has the same type as `x`. + reserve_space_2: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNorm", name, x, scale, offset, mean, variance, + "epsilon", epsilon, "exponential_avg_factor", exponential_avg_factor, + "data_format", data_format, "is_training", is_training) + _result = _FusedBatchNormOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return _fused_batch_norm_eager_fallback( + x, scale, offset, mean, variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNorm", x=x, scale=scale, offset=offset, mean=mean, + variance=variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "epsilon", + _op.get_attr("epsilon"), "exponential_avg_factor", + _op.get_attr("exponential_avg_factor"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNorm", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormOutput._make(_result) + return _result + +FusedBatchNorm = tf_export("raw_ops.FusedBatchNorm")(_ops.to_raw_op(_fused_batch_norm)) + + +def _fused_batch_norm_eager_fallback(x: Annotated[Any, TV_FusedBatchNorm_T], scale: Annotated[Any, TV_FusedBatchNorm_T], offset: Annotated[Any, TV_FusedBatchNorm_T], mean: Annotated[Any, TV_FusedBatchNorm_T], variance: Annotated[Any, TV_FusedBatchNorm_T], epsilon: float, exponential_avg_factor: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, scale, offset, mean, variance], ctx, [_dtypes.float32, ]) + (x, scale, offset, mean, variance) = _inputs_T + _inputs_flat = [x, scale, offset, mean, variance] + _attrs = ("T", _attr_T, "epsilon", epsilon, "exponential_avg_factor", + exponential_avg_factor, "data_format", data_format, "is_training", + is_training) + _result = _execute.execute(b"FusedBatchNorm", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNorm", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormOutput._make(_result) + return _result + +_FusedBatchNormGradOutput = collections.namedtuple( + "FusedBatchNormGrad", + ["x_backprop", "scale_backprop", "offset_backprop", "reserve_space_3", "reserve_space_4"]) + + +TV_FusedBatchNormGrad_T = TypeVar("TV_FusedBatchNormGrad_T", bound=_atypes.Float32) + +def fused_batch_norm_grad(y_backprop: Annotated[Any, TV_FusedBatchNormGrad_T], x: Annotated[Any, TV_FusedBatchNormGrad_T], scale: Annotated[Any, TV_FusedBatchNormGrad_T], reserve_space_1: Annotated[Any, TV_FusedBatchNormGrad_T], reserve_space_2: Annotated[Any, TV_FusedBatchNormGrad_T], epsilon:float=0.0001, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Gradient for batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + y_backprop: A `Tensor`. Must be one of the following types: `float32`. + A 4D Tensor for the gradient with respect to y. + x: A `Tensor`. Must have the same type as `y_backprop`. + A 4D Tensor for input data. + scale: A `Tensor`. Must have the same type as `y_backprop`. + A 1D Tensor for scaling factor, to scale the normalized x. + reserve_space_1: A `Tensor`. Must have the same type as `y_backprop`. + When is_training is True, a 1D Tensor for the computed batch + mean to be reused in gradient computation. When is_training is + False, a 1D Tensor for the population mean to be reused in both + 1st and 2nd order gradient computation. + reserve_space_2: A `Tensor`. Must have the same type as `y_backprop`. + When is_training is True, a 1D Tensor for the computed batch + variance (inverted variance in the cuDNN case) to be reused in + gradient computation. When is_training is False, a 1D Tensor + for the population variance to be reused in both 1st and 2nd + order gradient computation. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + The data format for y_backprop, x, x_backprop. + Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (x_backprop, scale_backprop, offset_backprop, reserve_space_3, reserve_space_4). + + x_backprop: A `Tensor`. Has the same type as `y_backprop`. + scale_backprop: A `Tensor`. Has the same type as `y_backprop`. + offset_backprop: A `Tensor`. Has the same type as `y_backprop`. + reserve_space_3: A `Tensor`. Has the same type as `y_backprop`. + reserve_space_4: A `Tensor`. Has the same type as `y_backprop`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNormGrad", name, y_backprop, x, scale, + reserve_space_1, reserve_space_2, "epsilon", epsilon, "data_format", + data_format, "is_training", is_training) + _result = _FusedBatchNormGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_batch_norm_grad_eager_fallback( + y_backprop, x, scale, reserve_space_1, reserve_space_2, + epsilon=epsilon, data_format=data_format, is_training=is_training, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNormGrad", y_backprop=y_backprop, x=x, scale=scale, + reserve_space_1=reserve_space_1, + reserve_space_2=reserve_space_2, + epsilon=epsilon, data_format=data_format, + is_training=is_training, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "epsilon", + _op.get_attr("epsilon"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNormGrad", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradOutput._make(_result) + return _result + +FusedBatchNormGrad = tf_export("raw_ops.FusedBatchNormGrad")(_ops.to_raw_op(fused_batch_norm_grad)) + + +def fused_batch_norm_grad_eager_fallback(y_backprop: Annotated[Any, TV_FusedBatchNormGrad_T], x: Annotated[Any, TV_FusedBatchNormGrad_T], scale: Annotated[Any, TV_FusedBatchNormGrad_T], reserve_space_1: Annotated[Any, TV_FusedBatchNormGrad_T], reserve_space_2: Annotated[Any, TV_FusedBatchNormGrad_T], epsilon: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([y_backprop, x, scale, reserve_space_1, reserve_space_2], ctx, [_dtypes.float32, ]) + (y_backprop, x, scale, reserve_space_1, reserve_space_2) = _inputs_T + _inputs_flat = [y_backprop, x, scale, reserve_space_1, reserve_space_2] + _attrs = ("T", _attr_T, "epsilon", epsilon, "data_format", data_format, + "is_training", is_training) + _result = _execute.execute(b"FusedBatchNormGrad", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNormGrad", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradOutput._make(_result) + return _result + +_FusedBatchNormGradV2Output = collections.namedtuple( + "FusedBatchNormGradV2", + ["x_backprop", "scale_backprop", "offset_backprop", "reserve_space_3", "reserve_space_4"]) + + +TV_FusedBatchNormGradV2_T = TypeVar("TV_FusedBatchNormGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) +TV_FusedBatchNormGradV2_U = TypeVar("TV_FusedBatchNormGradV2_U", bound=_atypes.Float32) + +def fused_batch_norm_grad_v2(y_backprop: Annotated[Any, TV_FusedBatchNormGradV2_T], x: Annotated[Any, TV_FusedBatchNormGradV2_T], scale: Annotated[Any, _atypes.Float32], reserve_space_1: Annotated[Any, TV_FusedBatchNormGradV2_U], reserve_space_2: Annotated[Any, TV_FusedBatchNormGradV2_U], epsilon:float=0.0001, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Gradient for batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + y_backprop: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + A 4D Tensor for the gradient with respect to y. + x: A `Tensor`. Must have the same type as `y_backprop`. + A 4D Tensor for input data. + scale: A `Tensor` of type `float32`. + A 1D Tensor for scaling factor, to scale the normalized x. + reserve_space_1: A `Tensor`. Must be one of the following types: `float32`. + When is_training is True, a 1D Tensor for the computed batch + mean to be reused in gradient computation. When is_training is + False, a 1D Tensor for the population mean to be reused in both + 1st and 2nd order gradient computation. + reserve_space_2: A `Tensor`. Must have the same type as `reserve_space_1`. + When is_training is True, a 1D Tensor for the computed batch + variance (inverted variance in the cuDNN case) to be reused in + gradient computation. When is_training is False, a 1D Tensor + for the population variance to be reused in both 1st and 2nd + order gradient computation. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + The data format for y_backprop, x, x_backprop. + Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (x_backprop, scale_backprop, offset_backprop, reserve_space_3, reserve_space_4). + + x_backprop: A `Tensor`. Has the same type as `y_backprop`. + scale_backprop: A `Tensor`. Has the same type as `reserve_space_1`. + offset_backprop: A `Tensor`. Has the same type as `reserve_space_1`. + reserve_space_3: A `Tensor`. Has the same type as `reserve_space_1`. + reserve_space_4: A `Tensor`. Has the same type as `reserve_space_1`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNormGradV2", name, y_backprop, x, scale, + reserve_space_1, reserve_space_2, "epsilon", epsilon, "data_format", + data_format, "is_training", is_training) + _result = _FusedBatchNormGradV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_batch_norm_grad_v2_eager_fallback( + y_backprop, x, scale, reserve_space_1, reserve_space_2, + epsilon=epsilon, data_format=data_format, is_training=is_training, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNormGradV2", y_backprop=y_backprop, x=x, scale=scale, + reserve_space_1=reserve_space_1, + reserve_space_2=reserve_space_2, + epsilon=epsilon, data_format=data_format, + is_training=is_training, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "U", _op._get_attr_type("U"), + "epsilon", _op.get_attr("epsilon"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNormGradV2", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradV2Output._make(_result) + return _result + +FusedBatchNormGradV2 = tf_export("raw_ops.FusedBatchNormGradV2")(_ops.to_raw_op(fused_batch_norm_grad_v2)) + + +def fused_batch_norm_grad_v2_eager_fallback(y_backprop: Annotated[Any, TV_FusedBatchNormGradV2_T], x: Annotated[Any, TV_FusedBatchNormGradV2_T], scale: Annotated[Any, _atypes.Float32], reserve_space_1: Annotated[Any, TV_FusedBatchNormGradV2_U], reserve_space_2: Annotated[Any, TV_FusedBatchNormGradV2_U], epsilon: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([y_backprop, x], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + (y_backprop, x) = _inputs_T + _attr_U, _inputs_U = _execute.args_to_matching_eager([reserve_space_1, reserve_space_2], ctx, [_dtypes.float32, ]) + (reserve_space_1, reserve_space_2) = _inputs_U + scale = _ops.convert_to_tensor(scale, _dtypes.float32) + _inputs_flat = [y_backprop, x, scale, reserve_space_1, reserve_space_2] + _attrs = ("T", _attr_T, "U", _attr_U, "epsilon", epsilon, "data_format", + data_format, "is_training", is_training) + _result = _execute.execute(b"FusedBatchNormGradV2", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNormGradV2", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradV2Output._make(_result) + return _result + +_FusedBatchNormGradV3Output = collections.namedtuple( + "FusedBatchNormGradV3", + ["x_backprop", "scale_backprop", "offset_backprop", "reserve_space_4", "reserve_space_5"]) + + +TV_FusedBatchNormGradV3_T = TypeVar("TV_FusedBatchNormGradV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) +TV_FusedBatchNormGradV3_U = TypeVar("TV_FusedBatchNormGradV3_U", bound=_atypes.Float32) + +def fused_batch_norm_grad_v3(y_backprop: Annotated[Any, TV_FusedBatchNormGradV3_T], x: Annotated[Any, TV_FusedBatchNormGradV3_T], scale: Annotated[Any, _atypes.Float32], reserve_space_1: Annotated[Any, TV_FusedBatchNormGradV3_U], reserve_space_2: Annotated[Any, TV_FusedBatchNormGradV3_U], reserve_space_3: Annotated[Any, TV_FusedBatchNormGradV3_U], epsilon:float=0.0001, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Gradient for batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + y_backprop: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + A 4D Tensor for the gradient with respect to y. + x: A `Tensor`. Must have the same type as `y_backprop`. + A 4D Tensor for input data. + scale: A `Tensor` of type `float32`. + A 1D Tensor for scaling factor, to scale the normalized x. + reserve_space_1: A `Tensor`. Must be one of the following types: `float32`. + When is_training is True, a 1D Tensor for the computed batch + mean to be reused in gradient computation. When is_training is + False, a 1D Tensor for the population mean to be reused in both + 1st and 2nd order gradient computation. + reserve_space_2: A `Tensor`. Must have the same type as `reserve_space_1`. + When is_training is True, a 1D Tensor for the computed batch + variance (inverted variance in the cuDNN case) to be reused in + gradient computation. When is_training is False, a 1D Tensor + for the population variance to be reused in both 1st and 2nd + order gradient computation. + reserve_space_3: A `Tensor`. Must have the same type as `reserve_space_1`. + When is_training is True, a 1D Tensor for some intermediate results to be reused + in gradient computation. When is_training is False, a dummy empty Tensor will be + created. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + data_format: An optional `string` from: `"NHWC", "NCHW", "NDHWC", "NCDHW"`. Defaults to `"NHWC"`. + The data format for y_backprop, x, x_backprop. + Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (x_backprop, scale_backprop, offset_backprop, reserve_space_4, reserve_space_5). + + x_backprop: A `Tensor`. Has the same type as `y_backprop`. + scale_backprop: A `Tensor`. Has the same type as `reserve_space_1`. + offset_backprop: A `Tensor`. Has the same type as `reserve_space_1`. + reserve_space_4: A `Tensor`. Has the same type as `reserve_space_1`. + reserve_space_5: A `Tensor`. Has the same type as `reserve_space_1`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNormGradV3", name, y_backprop, x, scale, + reserve_space_1, reserve_space_2, reserve_space_3, "epsilon", epsilon, + "data_format", data_format, "is_training", is_training) + _result = _FusedBatchNormGradV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_batch_norm_grad_v3_eager_fallback( + y_backprop, x, scale, reserve_space_1, reserve_space_2, + reserve_space_3, epsilon=epsilon, data_format=data_format, + is_training=is_training, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNormGradV3", y_backprop=y_backprop, x=x, scale=scale, + reserve_space_1=reserve_space_1, + reserve_space_2=reserve_space_2, + reserve_space_3=reserve_space_3, + epsilon=epsilon, data_format=data_format, + is_training=is_training, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "U", _op._get_attr_type("U"), + "epsilon", _op.get_attr("epsilon"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNormGradV3", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradV3Output._make(_result) + return _result + +FusedBatchNormGradV3 = tf_export("raw_ops.FusedBatchNormGradV3")(_ops.to_raw_op(fused_batch_norm_grad_v3)) + + +def fused_batch_norm_grad_v3_eager_fallback(y_backprop: Annotated[Any, TV_FusedBatchNormGradV3_T], x: Annotated[Any, TV_FusedBatchNormGradV3_T], scale: Annotated[Any, _atypes.Float32], reserve_space_1: Annotated[Any, TV_FusedBatchNormGradV3_U], reserve_space_2: Annotated[Any, TV_FusedBatchNormGradV3_U], reserve_space_3: Annotated[Any, TV_FusedBatchNormGradV3_U], epsilon: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, _inputs_T = _execute.args_to_matching_eager([y_backprop, x], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + (y_backprop, x) = _inputs_T + _attr_U, _inputs_U = _execute.args_to_matching_eager([reserve_space_1, reserve_space_2, reserve_space_3], ctx, [_dtypes.float32, ]) + (reserve_space_1, reserve_space_2, reserve_space_3) = _inputs_U + scale = _ops.convert_to_tensor(scale, _dtypes.float32) + _inputs_flat = [y_backprop, x, scale, reserve_space_1, reserve_space_2, reserve_space_3] + _attrs = ("T", _attr_T, "U", _attr_U, "epsilon", epsilon, "data_format", + data_format, "is_training", is_training) + _result = _execute.execute(b"FusedBatchNormGradV3", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNormGradV3", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormGradV3Output._make(_result) + return _result + +_FusedBatchNormV2Output = collections.namedtuple( + "FusedBatchNormV2", + ["y", "batch_mean", "batch_variance", "reserve_space_1", "reserve_space_2"]) + + +TV_FusedBatchNormV2_T = TypeVar("TV_FusedBatchNormV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) +TV_FusedBatchNormV2_U = TypeVar("TV_FusedBatchNormV2_U", bound=_atypes.Float32) + +def fused_batch_norm_v2(x: Annotated[Any, TV_FusedBatchNormV2_T], scale: Annotated[Any, TV_FusedBatchNormV2_U], offset: Annotated[Any, TV_FusedBatchNormV2_U], mean: Annotated[Any, TV_FusedBatchNormV2_U], variance: Annotated[Any, TV_FusedBatchNormV2_U], epsilon:float=0.0001, exponential_avg_factor:float=1, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + A 4D Tensor for input data. + scale: A `Tensor`. Must be one of the following types: `float32`. + A 1D Tensor for scaling factor, to scale the normalized x. + offset: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for offset, to shift to the normalized x. + mean: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for population mean. Used for inference only; + must be empty for training. + variance: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for population variance. Used for inference only; + must be empty for training. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + exponential_avg_factor: An optional `float`. Defaults to `1`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + The data format for x and y. Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, batch_mean, batch_variance, reserve_space_1, reserve_space_2). + + y: A `Tensor`. Has the same type as `x`. + batch_mean: A `Tensor`. Has the same type as `scale`. + batch_variance: A `Tensor`. Has the same type as `scale`. + reserve_space_1: A `Tensor`. Has the same type as `scale`. + reserve_space_2: A `Tensor`. Has the same type as `scale`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNormV2", name, x, scale, offset, mean, variance, + "epsilon", epsilon, "exponential_avg_factor", exponential_avg_factor, + "data_format", data_format, "is_training", is_training) + _result = _FusedBatchNormV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_batch_norm_v2_eager_fallback( + x, scale, offset, mean, variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNormV2", x=x, scale=scale, offset=offset, mean=mean, + variance=variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "U", _op._get_attr_type("U"), + "epsilon", _op.get_attr("epsilon"), "exponential_avg_factor", + _op.get_attr("exponential_avg_factor"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNormV2", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormV2Output._make(_result) + return _result + +FusedBatchNormV2 = tf_export("raw_ops.FusedBatchNormV2")(_ops.to_raw_op(fused_batch_norm_v2)) + + +def fused_batch_norm_v2_eager_fallback(x: Annotated[Any, TV_FusedBatchNormV2_T], scale: Annotated[Any, TV_FusedBatchNormV2_U], offset: Annotated[Any, TV_FusedBatchNormV2_U], mean: Annotated[Any, TV_FusedBatchNormV2_U], variance: Annotated[Any, TV_FusedBatchNormV2_U], epsilon: float, exponential_avg_factor: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + _attr_U, _inputs_U = _execute.args_to_matching_eager([scale, offset, mean, variance], ctx, [_dtypes.float32, ]) + (scale, offset, mean, variance) = _inputs_U + _inputs_flat = [x, scale, offset, mean, variance] + _attrs = ("T", _attr_T, "U", _attr_U, "epsilon", epsilon, + "exponential_avg_factor", exponential_avg_factor, "data_format", + data_format, "is_training", is_training) + _result = _execute.execute(b"FusedBatchNormV2", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNormV2", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormV2Output._make(_result) + return _result + +_FusedBatchNormV3Output = collections.namedtuple( + "FusedBatchNormV3", + ["y", "batch_mean", "batch_variance", "reserve_space_1", "reserve_space_2", "reserve_space_3"]) + + +TV_FusedBatchNormV3_T = TypeVar("TV_FusedBatchNormV3_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) +TV_FusedBatchNormV3_U = TypeVar("TV_FusedBatchNormV3_U", _atypes.BFloat16, _atypes.Float32) + +def fused_batch_norm_v3(x: Annotated[Any, TV_FusedBatchNormV3_T], scale: Annotated[Any, TV_FusedBatchNormV3_U], offset: Annotated[Any, TV_FusedBatchNormV3_U], mean: Annotated[Any, TV_FusedBatchNormV3_U], variance: Annotated[Any, TV_FusedBatchNormV3_U], epsilon:float=0.0001, exponential_avg_factor:float=1, data_format:str="NHWC", is_training:bool=True, name=None): + r"""Batch normalization. + + Note that the size of 4D Tensors are defined by either "NHWC" or "NCHW". + The size of 1D Tensors matches the dimension C of the 4D Tensors. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + A 4D Tensor for input data. + scale: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`. + A 1D Tensor for scaling factor, to scale the normalized x. + offset: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for offset, to shift to the normalized x. + mean: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for population mean. Used for inference only; + must be empty for training. + variance: A `Tensor`. Must have the same type as `scale`. + A 1D Tensor for population variance. Used for inference only; + must be empty for training. + epsilon: An optional `float`. Defaults to `0.0001`. + A small float number added to the variance of x. + exponential_avg_factor: An optional `float`. Defaults to `1`. + data_format: An optional `string` from: `"NHWC", "NCHW", "NDHWC", "NCDHW"`. Defaults to `"NHWC"`. + The data format for x and y. Either "NHWC" (default) or "NCHW". + is_training: An optional `bool`. Defaults to `True`. + A bool value to indicate the operation is for training (default) + or inference. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (y, batch_mean, batch_variance, reserve_space_1, reserve_space_2, reserve_space_3). + + y: A `Tensor`. Has the same type as `x`. + batch_mean: A `Tensor`. Has the same type as `scale`. + batch_variance: A `Tensor`. Has the same type as `scale`. + reserve_space_1: A `Tensor`. Has the same type as `scale`. + reserve_space_2: A `Tensor`. Has the same type as `scale`. + reserve_space_3: A `Tensor`. Has the same type as `scale`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedBatchNormV3", name, x, scale, offset, mean, variance, + "epsilon", epsilon, "exponential_avg_factor", exponential_avg_factor, + "data_format", data_format, "is_training", is_training) + _result = _FusedBatchNormV3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_batch_norm_v3_eager_fallback( + x, scale, offset, mean, variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedBatchNormV3", x=x, scale=scale, offset=offset, mean=mean, + variance=variance, epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, is_training=is_training, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "U", _op._get_attr_type("U"), + "epsilon", _op.get_attr("epsilon"), "exponential_avg_factor", + _op.get_attr("exponential_avg_factor"), "data_format", + _op.get_attr("data_format"), "is_training", + _op._get_attr_bool("is_training")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedBatchNormV3", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormV3Output._make(_result) + return _result + +FusedBatchNormV3 = tf_export("raw_ops.FusedBatchNormV3")(_ops.to_raw_op(fused_batch_norm_v3)) + + +def fused_batch_norm_v3_eager_fallback(x: Annotated[Any, TV_FusedBatchNormV3_T], scale: Annotated[Any, TV_FusedBatchNormV3_U], offset: Annotated[Any, TV_FusedBatchNormV3_U], mean: Annotated[Any, TV_FusedBatchNormV3_U], variance: Annotated[Any, TV_FusedBatchNormV3_U], epsilon: float, exponential_avg_factor: float, data_format: str, is_training: bool, name, ctx): + if epsilon is None: + epsilon = 0.0001 + epsilon = _execute.make_float(epsilon, "epsilon") + if exponential_avg_factor is None: + exponential_avg_factor = 1 + exponential_avg_factor = _execute.make_float(exponential_avg_factor, "exponential_avg_factor") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + if is_training is None: + is_training = True + is_training = _execute.make_bool(is_training, "is_training") + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + _attr_U, _inputs_U = _execute.args_to_matching_eager([scale, offset, mean, variance], ctx, [_dtypes.bfloat16, _dtypes.float32, ]) + (scale, offset, mean, variance) = _inputs_U + _inputs_flat = [x, scale, offset, mean, variance] + _attrs = ("T", _attr_T, "U", _attr_U, "epsilon", epsilon, + "exponential_avg_factor", exponential_avg_factor, "data_format", + data_format, "is_training", is_training) + _result = _execute.execute(b"FusedBatchNormV3", 6, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedBatchNormV3", _inputs_flat, _attrs, _result) + _result = _FusedBatchNormV3Output._make(_result) + return _result + + +TV_FusedPadConv2D_T = TypeVar("TV_FusedPadConv2D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def fused_pad_conv2d(input: Annotated[Any, TV_FusedPadConv2D_T], paddings: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_FusedPadConv2D_T], mode: str, strides, padding: str, name=None) -> Annotated[Any, TV_FusedPadConv2D_T]: + r"""Performs a padding as a preprocess during a convolution. + + Similar to FusedResizeAndPadConv2d, this op allows for an optimized + implementation where the spatial padding transformation stage is fused with the + im2col lookup, but in this case without the bilinear filtering required for + resizing. Fusing the padding prevents the need to write out the intermediate + results as whole tensors, reducing memory pressure, and we can get some latency + gains by merging the transformation calculations. + The data_format attribute for Conv2D isn't supported by this op, and 'NHWC' + order is used instead. + Internally this op uses a single per-graph scratch buffer, which means that it + will block if multiple versions are being run in parallel. This is because this + operator is primarily an optimization to minimize memory usage. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + paddings: A `Tensor` of type `int32`. + A two-column matrix specifying the padding sizes. The number of + rows must be the same as the rank of `input`. + filter: A `Tensor`. Must have the same type as `input`. 4-D with shape + `[filter_height, filter_width, in_channels, out_channels]`. + mode: A `string` from: `"REFLECT", "SYMMETRIC"`. + strides: A list of `ints`. + 1-D of length 4. The stride of the sliding window for each dimension + of `input`. Must be in the same order as the dimension specified with format. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedPadConv2D", name, input, paddings, filter, "mode", mode, + "strides", strides, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_pad_conv2d_eager_fallback( + input, paddings, filter, mode=mode, strides=strides, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + mode = _execute.make_str(mode, "mode") + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'fused_pad_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedPadConv2D", input=input, paddings=paddings, filter=filter, + mode=mode, strides=strides, padding=padding, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "mode", _op.get_attr("mode"), + "strides", _op.get_attr("strides"), "padding", + _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedPadConv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FusedPadConv2D = tf_export("raw_ops.FusedPadConv2D")(_ops.to_raw_op(fused_pad_conv2d)) + + +def fused_pad_conv2d_eager_fallback(input: Annotated[Any, TV_FusedPadConv2D_T], paddings: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_FusedPadConv2D_T], mode: str, strides, padding: str, name, ctx) -> Annotated[Any, TV_FusedPadConv2D_T]: + mode = _execute.make_str(mode, "mode") + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'fused_pad_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (input, filter) = _inputs_T + paddings = _ops.convert_to_tensor(paddings, _dtypes.int32) + _inputs_flat = [input, paddings, filter] + _attrs = ("T", _attr_T, "mode", mode, "strides", strides, "padding", + padding) + _result = _execute.execute(b"FusedPadConv2D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedPadConv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FusedResizeAndPadConv2D_T = TypeVar("TV_FusedResizeAndPadConv2D_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def fused_resize_and_pad_conv2d(input: Annotated[Any, TV_FusedResizeAndPadConv2D_T], size: Annotated[Any, _atypes.Int32], paddings: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_FusedResizeAndPadConv2D_T], mode: str, strides, padding: str, resize_align_corners:bool=False, name=None) -> Annotated[Any, TV_FusedResizeAndPadConv2D_T]: + r"""Performs a resize and padding as a preprocess during a convolution. + + It's often possible to do spatial transformations more efficiently as part of + the packing stage of a convolution, so this op allows for an optimized + implementation where these stages are fused together. This prevents the need to + write out the intermediate results as whole tensors, reducing memory pressure, + and we can get some latency gains by merging the transformation calculations. + The data_format attribute for Conv2D isn't supported by this op, and defaults to + 'NHWC' order. + Internally this op uses a single per-graph scratch buffer, which means that it + will block if multiple versions are being run in parallel. This is because this + operator is primarily an optimization to minimize memory usage. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + size: A `Tensor` of type `int32`. + A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The + new size for the images. + paddings: A `Tensor` of type `int32`. + A two-column matrix specifying the padding sizes. The number of + rows must be the same as the rank of `input`. + filter: A `Tensor`. Must have the same type as `input`. 4-D with shape + `[filter_height, filter_width, in_channels, out_channels]`. + mode: A `string` from: `"REFLECT", "SYMMETRIC"`. + strides: A list of `ints`. + 1-D of length 4. The stride of the sliding window for each dimension + of `input`. Must be in the same order as the dimension specified with format. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + resize_align_corners: An optional `bool`. Defaults to `False`. + If true, the centers of the 4 corner pixels of the input and output tensors are + aligned, preserving the values at the corner pixels. Defaults to false. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FusedResizeAndPadConv2D", name, input, size, paddings, filter, + "resize_align_corners", resize_align_corners, "mode", mode, "strides", + strides, "padding", padding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fused_resize_and_pad_conv2d_eager_fallback( + input, size, paddings, filter, + resize_align_corners=resize_align_corners, mode=mode, + strides=strides, padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + mode = _execute.make_str(mode, "mode") + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'fused_resize_and_pad_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if resize_align_corners is None: + resize_align_corners = False + resize_align_corners = _execute.make_bool(resize_align_corners, "resize_align_corners") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FusedResizeAndPadConv2D", input=input, size=size, paddings=paddings, + filter=filter, mode=mode, strides=strides, + padding=padding, + resize_align_corners=resize_align_corners, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "resize_align_corners", + _op._get_attr_bool("resize_align_corners"), "mode", + _op.get_attr("mode"), "strides", _op.get_attr("strides"), + "padding", _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FusedResizeAndPadConv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FusedResizeAndPadConv2D = tf_export("raw_ops.FusedResizeAndPadConv2D")(_ops.to_raw_op(fused_resize_and_pad_conv2d)) + + +def fused_resize_and_pad_conv2d_eager_fallback(input: Annotated[Any, TV_FusedResizeAndPadConv2D_T], size: Annotated[Any, _atypes.Int32], paddings: Annotated[Any, _atypes.Int32], filter: Annotated[Any, TV_FusedResizeAndPadConv2D_T], mode: str, strides, padding: str, resize_align_corners: bool, name, ctx) -> Annotated[Any, TV_FusedResizeAndPadConv2D_T]: + mode = _execute.make_str(mode, "mode") + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'fused_resize_and_pad_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if resize_align_corners is None: + resize_align_corners = False + resize_align_corners = _execute.make_bool(resize_align_corners, "resize_align_corners") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, filter], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (input, filter) = _inputs_T + size = _ops.convert_to_tensor(size, _dtypes.int32) + paddings = _ops.convert_to_tensor(paddings, _dtypes.int32) + _inputs_flat = [input, size, paddings, filter] + _attrs = ("T", _attr_T, "resize_align_corners", resize_align_corners, + "mode", mode, "strides", strides, "padding", padding) + _result = _execute.execute(b"FusedResizeAndPadConv2D", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FusedResizeAndPadConv2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InTopK_T = TypeVar("TV_InTopK_T", _atypes.Int32, _atypes.Int64) + +def in_top_k(predictions: Annotated[Any, _atypes.Float32], targets: Annotated[Any, TV_InTopK_T], k: int, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Says whether the targets are in the top `K` predictions. + + This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the + prediction for the target class is among the top `k` predictions among + all predictions for example `i`. Note that the behavior of `InTopK` differs + from the `TopK` op in its handling of ties; if multiple classes have the + same prediction value and straddle the top-`k` boundary, all of those + classes are considered to be in the top `k`. + + More formally, let + + \\(predictions_i\\) be the predictions for all classes for example `i`, + \\(targets_i\\) be the target class for example `i`, + \\(out_i\\) be the output for example `i`, + + $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ + + Args: + predictions: A `Tensor` of type `float32`. + A `batch_size` x `classes` tensor. + targets: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `batch_size` vector of class ids. + k: An `int`. Number of top elements to look at for computing precision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InTopK", name, predictions, targets, "k", k) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return in_top_k_eager_fallback( + predictions, targets, k=k, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + k = _execute.make_int(k, "k") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InTopK", predictions=predictions, targets=targets, k=k, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("k", _op._get_attr_int("k"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InTopK", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InTopK = tf_export("raw_ops.InTopK")(_ops.to_raw_op(in_top_k)) + + +def in_top_k_eager_fallback(predictions: Annotated[Any, _atypes.Float32], targets: Annotated[Any, TV_InTopK_T], k: int, name, ctx) -> Annotated[Any, _atypes.Bool]: + k = _execute.make_int(k, "k") + _attr_T, (targets,) = _execute.args_to_matching_eager([targets], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + predictions = _ops.convert_to_tensor(predictions, _dtypes.float32) + _inputs_flat = [predictions, targets] + _attrs = ("k", k, "T", _attr_T) + _result = _execute.execute(b"InTopK", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InTopK", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InTopKV2_T = TypeVar("TV_InTopKV2_T", _atypes.Int32, _atypes.Int64) + +def in_top_kv2(predictions: Annotated[Any, _atypes.Float32], targets: Annotated[Any, TV_InTopKV2_T], k: Annotated[Any, TV_InTopKV2_T], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Says whether the targets are in the top `K` predictions. + + This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the + prediction for the target class is among the top `k` predictions among + all predictions for example `i`. Note that the behavior of `InTopK` differs + from the `TopK` op in its handling of ties; if multiple classes have the + same prediction value and straddle the top-`k` boundary, all of those + classes are considered to be in the top `k`. + + More formally, let + + \\(predictions_i\\) be the predictions for all classes for example `i`, + \\(targets_i\\) be the target class for example `i`, + \\(out_i\\) be the output for example `i`, + + $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ + + Args: + predictions: A `Tensor` of type `float32`. + A `batch_size` x `classes` tensor. + targets: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `batch_size` vector of class ids. + k: A `Tensor`. Must have the same type as `targets`. + Number of top elements to look at for computing precision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InTopKV2", name, predictions, targets, k) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return in_top_kv2_eager_fallback( + predictions, targets, k, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InTopKV2", predictions=predictions, targets=targets, k=k, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InTopKV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InTopKV2 = tf_export("raw_ops.InTopKV2")(_ops.to_raw_op(in_top_kv2)) + + +def in_top_kv2_eager_fallback(predictions: Annotated[Any, _atypes.Float32], targets: Annotated[Any, TV_InTopKV2_T], k: Annotated[Any, TV_InTopKV2_T], name, ctx) -> Annotated[Any, _atypes.Bool]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([targets, k], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + (targets, k) = _inputs_T + predictions = _ops.convert_to_tensor(predictions, _dtypes.float32) + _inputs_flat = [predictions, targets, k] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"InTopKV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InTopKV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_IsotonicRegressionOutput = collections.namedtuple( + "IsotonicRegression", + ["output", "segments"]) + + +TV_IsotonicRegression_T = TypeVar("TV_IsotonicRegression_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_IsotonicRegression_output_dtype = TypeVar("TV_IsotonicRegression_output_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def isotonic_regression(input: Annotated[Any, TV_IsotonicRegression_T], output_dtype:TV_IsotonicRegression_output_dtype=_dtypes.float32, name=None): + r"""Solves a batch of isotonic regression problems. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + A (batch_size, dim)-tensor holding a batch of inputs. + output_dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + Dtype of output. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, segments). + + output: A `Tensor` of type `output_dtype`. + segments: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsotonicRegression", name, input, "output_dtype", output_dtype) + _result = _IsotonicRegressionOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return isotonic_regression_eager_fallback( + input, output_dtype=output_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_dtype is None: + output_dtype = _dtypes.float32 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsotonicRegression", input=input, output_dtype=output_dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "output_dtype", + _op._get_attr_type("output_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsotonicRegression", _inputs_flat, _attrs, _result) + _result = _IsotonicRegressionOutput._make(_result) + return _result + +IsotonicRegression = tf_export("raw_ops.IsotonicRegression")(_ops.to_raw_op(isotonic_regression)) + + +def isotonic_regression_eager_fallback(input: Annotated[Any, TV_IsotonicRegression_T], output_dtype: TV_IsotonicRegression_output_dtype, name, ctx): + if output_dtype is None: + output_dtype = _dtypes.float32 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "output_dtype", output_dtype) + _result = _execute.execute(b"IsotonicRegression", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsotonicRegression", _inputs_flat, _attrs, _result) + _result = _IsotonicRegressionOutput._make(_result) + return _result + + +TV_L2Loss_T = TypeVar("TV_L2Loss_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.l2_loss') +def l2_loss(t: Annotated[Any, TV_L2Loss_T], name=None) -> Annotated[Any, TV_L2Loss_T]: + r"""L2 Loss. + + Computes half the L2 norm of a tensor without the `sqrt`: + + output = sum(t ** 2) / 2 + + Args: + t: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + Typically 2-D, but may have any dimensions. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "L2Loss", name, t) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_l2_loss( + (t, name,), None) + if _result is not NotImplemented: + return _result + return l2_loss_eager_fallback( + t, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + l2_loss, (), dict(t=t, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_l2_loss( + (t, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "L2Loss", t=t, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + l2_loss, (), dict(t=t, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "L2Loss", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +L2Loss = tf_export("raw_ops.L2Loss")(_ops.to_raw_op(l2_loss)) +_dispatcher_for_l2_loss = l2_loss._tf_type_based_dispatcher.Dispatch + + +def l2_loss_eager_fallback(t: Annotated[Any, TV_L2Loss_T], name, ctx) -> Annotated[Any, TV_L2Loss_T]: + _attr_T, (t,) = _execute.args_to_matching_eager([t], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [t] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"L2Loss", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "L2Loss", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LRN_T = TypeVar("TV_LRN_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.local_response_normalization', 'nn.lrn') +def lrn(input: Annotated[Any, TV_LRN_T], depth_radius:int=5, bias:float=1, alpha:float=1, beta:float=0.5, name=None) -> Annotated[Any, TV_LRN_T]: + r"""Local Response Normalization. + + The 4-D `input` tensor is treated as a 3-D array of 1-D vectors (along the last + dimension), and each vector is normalized independently. Within a given vector, + each component is divided by the weighted, squared sum of inputs within + `depth_radius`. In detail, + + sqr_sum[a, b, c, d] = + sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2) + output = input / (bias + alpha * sqr_sum) ** beta + + For details, see [Krizhevsky et al., ImageNet classification with deep + convolutional neural networks (NIPS 2012)](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks). + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + 4-D. + depth_radius: An optional `int`. Defaults to `5`. + 0-D. Half-width of the 1-D normalization window. + bias: An optional `float`. Defaults to `1`. + An offset (usually positive to avoid dividing by 0). + alpha: An optional `float`. Defaults to `1`. + A scale factor, usually positive. + beta: An optional `float`. Defaults to `0.5`. An exponent. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LRN", name, input, "depth_radius", depth_radius, "bias", bias, + "alpha", alpha, "beta", beta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_lrn( + (input, depth_radius, bias, alpha, beta, name,), None) + if _result is not NotImplemented: + return _result + return lrn_eager_fallback( + input, depth_radius=depth_radius, bias=bias, alpha=alpha, beta=beta, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lrn, (), dict(input=input, depth_radius=depth_radius, bias=bias, + alpha=alpha, beta=beta, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_lrn( + (input, depth_radius, bias, alpha, beta, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if depth_radius is None: + depth_radius = 5 + depth_radius = _execute.make_int(depth_radius, "depth_radius") + if bias is None: + bias = 1 + bias = _execute.make_float(bias, "bias") + if alpha is None: + alpha = 1 + alpha = _execute.make_float(alpha, "alpha") + if beta is None: + beta = 0.5 + beta = _execute.make_float(beta, "beta") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LRN", input=input, depth_radius=depth_radius, bias=bias, alpha=alpha, + beta=beta, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + lrn, (), dict(input=input, depth_radius=depth_radius, bias=bias, + alpha=alpha, beta=beta, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("depth_radius", _op._get_attr_int("depth_radius"), "bias", + _op.get_attr("bias"), "alpha", _op.get_attr("alpha"), "beta", + _op.get_attr("beta"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LRN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LRN = tf_export("raw_ops.LRN")(_ops.to_raw_op(lrn)) +_dispatcher_for_lrn = lrn._tf_type_based_dispatcher.Dispatch + + +def lrn_eager_fallback(input: Annotated[Any, TV_LRN_T], depth_radius: int, bias: float, alpha: float, beta: float, name, ctx) -> Annotated[Any, TV_LRN_T]: + if depth_radius is None: + depth_radius = 5 + depth_radius = _execute.make_int(depth_radius, "depth_radius") + if bias is None: + bias = 1 + bias = _execute.make_float(bias, "bias") + if alpha is None: + alpha = 1 + alpha = _execute.make_float(alpha, "alpha") + if beta is None: + beta = 0.5 + beta = _execute.make_float(beta, "beta") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ], _dtypes.float32) + _inputs_flat = [input] + _attrs = ("depth_radius", depth_radius, "bias", bias, "alpha", alpha, + "beta", beta, "T", _attr_T) + _result = _execute.execute(b"LRN", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LRN", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LRNGrad_T = TypeVar("TV_LRNGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) + +def lrn_grad(input_grads: Annotated[Any, TV_LRNGrad_T], input_image: Annotated[Any, TV_LRNGrad_T], output_image: Annotated[Any, TV_LRNGrad_T], depth_radius:int=5, bias:float=1, alpha:float=1, beta:float=0.5, name=None) -> Annotated[Any, TV_LRNGrad_T]: + r"""Gradients for Local Response Normalization. + + Args: + input_grads: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + 4-D with shape `[batch, height, width, channels]`. + input_image: A `Tensor`. Must have the same type as `input_grads`. + 4-D with shape `[batch, height, width, channels]`. + output_image: A `Tensor`. Must have the same type as `input_grads`. + 4-D with shape `[batch, height, width, channels]`. + depth_radius: An optional `int`. Defaults to `5`. A depth radius. + bias: An optional `float`. Defaults to `1`. + An offset (usually > 0 to avoid dividing by 0). + alpha: An optional `float`. Defaults to `1`. + A scale factor, usually positive. + beta: An optional `float`. Defaults to `0.5`. An exponent. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input_grads`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LRNGrad", name, input_grads, input_image, output_image, + "depth_radius", depth_radius, "bias", bias, "alpha", alpha, "beta", + beta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lrn_grad_eager_fallback( + input_grads, input_image, output_image, depth_radius=depth_radius, + bias=bias, alpha=alpha, beta=beta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if depth_radius is None: + depth_radius = 5 + depth_radius = _execute.make_int(depth_radius, "depth_radius") + if bias is None: + bias = 1 + bias = _execute.make_float(bias, "bias") + if alpha is None: + alpha = 1 + alpha = _execute.make_float(alpha, "alpha") + if beta is None: + beta = 0.5 + beta = _execute.make_float(beta, "beta") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LRNGrad", input_grads=input_grads, input_image=input_image, + output_image=output_image, depth_radius=depth_radius, + bias=bias, alpha=alpha, beta=beta, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("depth_radius", _op._get_attr_int("depth_radius"), "bias", + _op.get_attr("bias"), "alpha", _op.get_attr("alpha"), "beta", + _op.get_attr("beta"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LRNGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LRNGrad = tf_export("raw_ops.LRNGrad")(_ops.to_raw_op(lrn_grad)) + + +def lrn_grad_eager_fallback(input_grads: Annotated[Any, TV_LRNGrad_T], input_image: Annotated[Any, TV_LRNGrad_T], output_image: Annotated[Any, TV_LRNGrad_T], depth_radius: int, bias: float, alpha: float, beta: float, name, ctx) -> Annotated[Any, TV_LRNGrad_T]: + if depth_radius is None: + depth_radius = 5 + depth_radius = _execute.make_int(depth_radius, "depth_radius") + if bias is None: + bias = 1 + bias = _execute.make_float(bias, "bias") + if alpha is None: + alpha = 1 + alpha = _execute.make_float(alpha, "alpha") + if beta is None: + beta = 0.5 + beta = _execute.make_float(beta, "beta") + _attr_T, _inputs_T = _execute.args_to_matching_eager([input_grads, input_image, output_image], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ], _dtypes.float32) + (input_grads, input_image, output_image) = _inputs_T + _inputs_flat = [input_grads, input_image, output_image] + _attrs = ("depth_radius", depth_radius, "bias", bias, "alpha", alpha, + "beta", beta, "T", _attr_T) + _result = _execute.execute(b"LRNGrad", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LRNGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LeakyRelu_T = TypeVar("TV_LeakyRelu_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def leaky_relu(features: Annotated[Any, TV_LeakyRelu_T], alpha:float=0.2, name=None) -> Annotated[Any, TV_LeakyRelu_T]: + r"""Computes rectified linear: `max(features, features * alpha)`. + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + alpha: An optional `float`. Defaults to `0.2`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LeakyRelu", name, features, "alpha", alpha) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return leaky_relu_eager_fallback( + features, alpha=alpha, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if alpha is None: + alpha = 0.2 + alpha = _execute.make_float(alpha, "alpha") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LeakyRelu", features=features, alpha=alpha, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("alpha", _op.get_attr("alpha"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LeakyRelu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LeakyRelu = tf_export("raw_ops.LeakyRelu")(_ops.to_raw_op(leaky_relu)) + + +def leaky_relu_eager_fallback(features: Annotated[Any, TV_LeakyRelu_T], alpha: float, name, ctx) -> Annotated[Any, TV_LeakyRelu_T]: + if alpha is None: + alpha = 0.2 + alpha = _execute.make_float(alpha, "alpha") + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ], _dtypes.float32) + _inputs_flat = [features] + _attrs = ("alpha", alpha, "T", _attr_T) + _result = _execute.execute(b"LeakyRelu", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LeakyRelu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LeakyReluGrad_T = TypeVar("TV_LeakyReluGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def leaky_relu_grad(gradients: Annotated[Any, TV_LeakyReluGrad_T], features: Annotated[Any, TV_LeakyReluGrad_T], alpha:float=0.2, name=None) -> Annotated[Any, TV_LeakyReluGrad_T]: + r"""Computes rectified linear gradients for a LeakyRelu operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The backpropagated gradients to the corresponding LeakyRelu operation. + features: A `Tensor`. Must have the same type as `gradients`. + The features passed as input to the corresponding LeakyRelu operation, + OR the outputs of that operation (both work equivalently). + alpha: An optional `float`. Defaults to `0.2`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LeakyReluGrad", name, gradients, features, "alpha", alpha) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return leaky_relu_grad_eager_fallback( + gradients, features, alpha=alpha, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if alpha is None: + alpha = 0.2 + alpha = _execute.make_float(alpha, "alpha") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LeakyReluGrad", gradients=gradients, features=features, alpha=alpha, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("alpha", _op.get_attr("alpha"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LeakyReluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LeakyReluGrad = tf_export("raw_ops.LeakyReluGrad")(_ops.to_raw_op(leaky_relu_grad)) + + +def leaky_relu_grad_eager_fallback(gradients: Annotated[Any, TV_LeakyReluGrad_T], features: Annotated[Any, TV_LeakyReluGrad_T], alpha: float, name, ctx) -> Annotated[Any, TV_LeakyReluGrad_T]: + if alpha is None: + alpha = 0.2 + alpha = _execute.make_float(alpha, "alpha") + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ], _dtypes.float32) + (gradients, features) = _inputs_T + _inputs_flat = [gradients, features] + _attrs = ("alpha", alpha, "T", _attr_T) + _result = _execute.execute(b"LeakyReluGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LeakyReluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_LogSoftmax_T = TypeVar("TV_LogSoftmax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def log_softmax(logits: Annotated[Any, TV_LogSoftmax_T], name=None) -> Annotated[Any, TV_LogSoftmax_T]: + r"""Computes log softmax activations. + + For each batch `i` and class `j` we have + + logsoftmax[i, j] = logits[i, j] - log(sum(exp(logits[i]))) + + Args: + logits: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 2-D with shape `[batch_size, num_classes]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `logits`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LogSoftmax", name, logits) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return log_softmax_eager_fallback( + logits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LogSoftmax", logits=logits, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LogSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +LogSoftmax = tf_export("raw_ops.LogSoftmax")(_ops.to_raw_op(log_softmax)) + + +def log_softmax_eager_fallback(logits: Annotated[Any, TV_LogSoftmax_T], name, ctx) -> Annotated[Any, TV_LogSoftmax_T]: + _attr_T, (logits,) = _execute.args_to_matching_eager([logits], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [logits] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"LogSoftmax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LogSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPool_T = TypeVar("TV_MaxPool_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt8, _atypes.UInt16, _atypes.UInt8) + +def max_pool(input: Annotated[Any, TV_MaxPool_T], ksize, strides, padding: str, explicit_paddings=[], data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPool_T]: + r"""Performs max pooling on the input. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`. + 4-D input to pool over. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPool", name, input, "ksize", ksize, "strides", strides, + "padding", padding, "explicit_paddings", explicit_paddings, + "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_eager_fallback( + input, ksize=ksize, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, data_format=data_format, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'max_pool' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPool", input=input, ksize=ksize, strides=strides, padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "ksize", _op.get_attr("ksize"), + "strides", _op.get_attr("strides"), "padding", + _op.get_attr("padding"), "explicit_paddings", + _op.get_attr("explicit_paddings"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPool = tf_export("raw_ops.MaxPool")(_ops.to_raw_op(max_pool)) + + +def max_pool_eager_fallback(input: Annotated[Any, TV_MaxPool_T], ksize, strides, padding: str, explicit_paddings, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPool_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'max_pool' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.uint16, _dtypes.qint8, ], _dtypes.float32) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "ksize", ksize, "strides", strides, "padding", + padding, "explicit_paddings", explicit_paddings, "data_format", data_format) + _result = _execute.execute(b"MaxPool", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPool", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPool3D_T = TypeVar("TV_MaxPool3D_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) + +def max_pool3d(input: Annotated[Any, TV_MaxPool3D_T], ksize, strides, padding: str, data_format:str="NDHWC", name=None) -> Annotated[Any, TV_MaxPool3D_T]: + r"""Performs 3D max pooling on the input. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + Shape `[batch, depth, rows, cols, channels]` tensor to pool over. + ksize: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The size of the window for each dimension of + the input tensor. Must have `ksize[0] = ksize[4] = 1`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPool3D", name, input, "ksize", ksize, "strides", strides, + "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool3d_eager_fallback( + input, ksize=ksize, strides=strides, padding=padding, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPool3D", input=input, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPool3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPool3D = tf_export("raw_ops.MaxPool3D")(_ops.to_raw_op(max_pool3d)) + + +def max_pool3d_eager_fallback(input: Annotated[Any, TV_MaxPool3D_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPool3D_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ]) + _inputs_flat = [input] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"MaxPool3D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPool3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPool3DGrad_T = TypeVar("TV_MaxPool3DGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Half) +TV_MaxPool3DGrad_TInput = TypeVar("TV_MaxPool3DGrad_TInput", _atypes.BFloat16, _atypes.Float32, _atypes.Half) + +def max_pool3d_grad(orig_input: Annotated[Any, TV_MaxPool3DGrad_TInput], orig_output: Annotated[Any, TV_MaxPool3DGrad_TInput], grad: Annotated[Any, TV_MaxPool3DGrad_T], ksize, strides, padding: str, data_format:str="NDHWC", name=None) -> Annotated[Any, TV_MaxPool3DGrad_T]: + r"""Computes gradients of 3D max pooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`. + Output backprop of shape `[batch, depth, rows, cols, channels]`. + ksize: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The size of the window for each dimension of + the input tensor. Must have `ksize[0] = ksize[4] = 1`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPool3DGrad", name, orig_input, orig_output, grad, "ksize", + ksize, "strides", strides, "padding", padding, "data_format", + data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool3d_grad_eager_fallback( + orig_input, orig_output, grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPool3DGrad", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T"), "TInput", _op._get_attr_type("TInput")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPool3DGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPool3DGrad = tf_export("raw_ops.MaxPool3DGrad")(_ops.to_raw_op(max_pool3d_grad)) + + +def max_pool3d_grad_eager_fallback(orig_input: Annotated[Any, TV_MaxPool3DGrad_TInput], orig_output: Annotated[Any, TV_MaxPool3DGrad_TInput], grad: Annotated[Any, TV_MaxPool3DGrad_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPool3DGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (grad,) = _execute.args_to_matching_eager([grad], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ], _dtypes.float32) + _attr_TInput, _inputs_TInput = _execute.args_to_matching_eager([orig_input, orig_output], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, ], _dtypes.float32) + (orig_input, orig_output) = _inputs_TInput + _inputs_flat = [orig_input, orig_output, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T, "TInput", _attr_TInput) + _result = _execute.execute(b"MaxPool3DGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPool3DGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPool3DGradGrad_T = TypeVar("TV_MaxPool3DGradGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool3d_grad_grad(orig_input: Annotated[Any, TV_MaxPool3DGradGrad_T], orig_output: Annotated[Any, TV_MaxPool3DGradGrad_T], grad: Annotated[Any, TV_MaxPool3DGradGrad_T], ksize, strides, padding: str, data_format:str="NDHWC", name=None) -> Annotated[Any, TV_MaxPool3DGradGrad_T]: + r"""Computes second-order gradients of the maxpooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must have the same type as `orig_input`. + Output backprop of shape `[batch, depth, rows, cols, channels]`. + ksize: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The size of the window for each dimension of + the input tensor. Must have `ksize[0] = ksize[4] = 1`. + strides: A list of `ints` that has length `>= 5`. + 1-D tensor of length 5. The stride of the sliding window for each + dimension of `input`. Must have `strides[0] = strides[4] = 1`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. + The data format of the input and output data. With the + default format "NDHWC", the data is stored in the order of: + [batch, in_depth, in_height, in_width, in_channels]. + Alternatively, the format could be "NCDHW", the data storage order is: + [batch, in_channels, in_depth, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPool3DGradGrad", name, orig_input, orig_output, grad, + "ksize", ksize, "strides", strides, "padding", padding, "data_format", + data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool3d_grad_grad_eager_fallback( + orig_input, orig_output, grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d_grad_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d_grad_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPool3DGradGrad", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPool3DGradGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPool3DGradGrad = tf_export("raw_ops.MaxPool3DGradGrad")(_ops.to_raw_op(max_pool3d_grad_grad)) + + +def max_pool3d_grad_grad_eager_fallback(orig_input: Annotated[Any, TV_MaxPool3DGradGrad_T], orig_output: Annotated[Any, TV_MaxPool3DGradGrad_T], grad: Annotated[Any, TV_MaxPool3DGradGrad_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPool3DGradGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool3d_grad_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool3d_grad_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NDHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (orig_input, orig_output, grad) = _inputs_T + _inputs_flat = [orig_input, orig_output, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"MaxPool3DGradGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPool3DGradGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGrad_T = TypeVar("TV_MaxPoolGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad(orig_input: Annotated[Any, TV_MaxPoolGrad_T], orig_output: Annotated[Any, TV_MaxPoolGrad_T], grad: Annotated[Any, TV_MaxPoolGrad_T], ksize, strides, padding: str, explicit_paddings=[], data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPoolGrad_T]: + r"""Computes gradients of the maxpooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must have the same type as `orig_input`. + 4-D. Gradients w.r.t. the output of `max_pool`. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID", "EXPLICIT"`. + The type of padding algorithm to use. + explicit_paddings: An optional list of `ints`. Defaults to `[]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGrad", name, orig_input, orig_output, grad, "ksize", + ksize, "strides", strides, "padding", padding, "explicit_paddings", + explicit_paddings, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_eager_fallback( + orig_input, orig_output, grad, ksize=ksize, strides=strides, + padding=padding, explicit_paddings=explicit_paddings, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'max_pool_grad' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGrad", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, explicit_paddings=explicit_paddings, + data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "explicit_paddings", _op.get_attr("explicit_paddings"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGrad = tf_export("raw_ops.MaxPoolGrad")(_ops.to_raw_op(max_pool_grad)) + + +def max_pool_grad_eager_fallback(orig_input: Annotated[Any, TV_MaxPoolGrad_T], orig_output: Annotated[Any, TV_MaxPoolGrad_T], grad: Annotated[Any, TV_MaxPoolGrad_T], ksize, strides, padding: str, explicit_paddings, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPoolGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if explicit_paddings is None: + explicit_paddings = [] + if not isinstance(explicit_paddings, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_paddings' argument to " + "'max_pool_grad' Op, not %r." % explicit_paddings) + explicit_paddings = [_execute.make_int(_i, "explicit_paddings") for _i in explicit_paddings] + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ], _dtypes.float32) + (orig_input, orig_output, grad) = _inputs_T + _inputs_flat = [orig_input, orig_output, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "explicit_paddings", explicit_paddings, "data_format", data_format, "T", + _attr_T) + _result = _execute.execute(b"MaxPoolGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGradGrad_T = TypeVar("TV_MaxPoolGradGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad_grad(orig_input: Annotated[Any, TV_MaxPoolGradGrad_T], orig_output: Annotated[Any, TV_MaxPoolGradGrad_T], grad: Annotated[Any, TV_MaxPoolGradGrad_T], ksize, strides, padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPoolGradGrad_T]: + r"""Computes second-order gradients of the maxpooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must have the same type as `orig_input`. + 4-D. Gradients of gradients w.r.t. the input of `max_pool`. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGradGrad", name, orig_input, orig_output, grad, "ksize", + ksize, "strides", strides, "padding", padding, "data_format", + data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_grad_eager_fallback( + orig_input, orig_output, grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGradGrad", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "data_format", _op.get_attr("data_format"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGradGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGradGrad = tf_export("raw_ops.MaxPoolGradGrad")(_ops.to_raw_op(max_pool_grad_grad)) + + +def max_pool_grad_grad_eager_fallback(orig_input: Annotated[Any, TV_MaxPoolGradGrad_T], orig_output: Annotated[Any, TV_MaxPoolGradGrad_T], grad: Annotated[Any, TV_MaxPoolGradGrad_T], ksize, strides, padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPoolGradGrad_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_grad' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_grad' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (orig_input, orig_output, grad) = _inputs_T + _inputs_flat = [orig_input, orig_output, grad] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"MaxPoolGradGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGradGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGradGradV2_T = TypeVar("TV_MaxPoolGradGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad_grad_v2(orig_input: Annotated[Any, TV_MaxPoolGradGradV2_T], orig_output: Annotated[Any, TV_MaxPoolGradGradV2_T], grad: Annotated[Any, TV_MaxPoolGradGradV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPoolGradGradV2_T]: + r"""Computes second-order gradients of the maxpooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must have the same type as `orig_input`. + 4-D. Gradients of gradients w.r.t. the input of `max_pool`. + ksize: A `Tensor` of type `int32`. + The size of the window for each dimension of the input tensor. + strides: A `Tensor` of type `int32`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGradGradV2", name, orig_input, orig_output, grad, ksize, + strides, "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_grad_v2_eager_fallback( + orig_input, orig_output, grad, ksize, strides, padding=padding, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGradGradV2", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("padding", _op.get_attr("padding"), "data_format", + _op.get_attr("data_format"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGradGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGradGradV2 = tf_export("raw_ops.MaxPoolGradGradV2")(_ops.to_raw_op(max_pool_grad_grad_v2)) + + +def max_pool_grad_grad_v2_eager_fallback(orig_input: Annotated[Any, TV_MaxPoolGradGradV2_T], orig_output: Annotated[Any, TV_MaxPoolGradGradV2_T], grad: Annotated[Any, TV_MaxPoolGradGradV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPoolGradGradV2_T]: + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (orig_input, orig_output, grad) = _inputs_T + ksize = _ops.convert_to_tensor(ksize, _dtypes.int32) + strides = _ops.convert_to_tensor(strides, _dtypes.int32) + _inputs_flat = [orig_input, orig_output, grad, ksize, strides] + _attrs = ("padding", padding, "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"MaxPoolGradGradV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGradGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGradGradWithArgmax_Targmax = TypeVar("TV_MaxPoolGradGradWithArgmax_Targmax", _atypes.Int32, _atypes.Int64) +TV_MaxPoolGradGradWithArgmax_T = TypeVar("TV_MaxPoolGradGradWithArgmax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad_grad_with_argmax(input: Annotated[Any, TV_MaxPoolGradGradWithArgmax_T], grad: Annotated[Any, TV_MaxPoolGradGradWithArgmax_T], argmax: Annotated[Any, TV_MaxPoolGradGradWithArgmax_Targmax], ksize, strides, padding: str, include_batch_in_index:bool=False, name=None) -> Annotated[Any, TV_MaxPoolGradGradWithArgmax_T]: + r"""Computes second-order gradients of the maxpooling function. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input. + grad: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the + input of `max_pool`. + argmax: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The indices of the maximum values chosen for each output of `max_pool`. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + include_batch_in_index: An optional `bool`. Defaults to `False`. + Whether to include batch dimension in flattened index of `argmax`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGradGradWithArgmax", name, input, grad, argmax, "ksize", + ksize, "strides", strides, "padding", padding, + "include_batch_in_index", include_batch_in_index) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_grad_with_argmax_eager_fallback( + input, grad, argmax, ksize=ksize, strides=strides, padding=padding, + include_batch_in_index=include_batch_in_index, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_grad_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_grad_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGradGradWithArgmax", input=input, grad=grad, argmax=argmax, + ksize=ksize, strides=strides, + padding=padding, + include_batch_in_index=include_batch_in_index, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "include_batch_in_index", + _op._get_attr_bool("include_batch_in_index"), "Targmax", + _op._get_attr_type("Targmax"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGradGradWithArgmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGradGradWithArgmax = tf_export("raw_ops.MaxPoolGradGradWithArgmax")(_ops.to_raw_op(max_pool_grad_grad_with_argmax)) + + +def max_pool_grad_grad_with_argmax_eager_fallback(input: Annotated[Any, TV_MaxPoolGradGradWithArgmax_T], grad: Annotated[Any, TV_MaxPoolGradGradWithArgmax_T], argmax: Annotated[Any, TV_MaxPoolGradGradWithArgmax_Targmax], ksize, strides, padding: str, include_batch_in_index: bool, name, ctx) -> Annotated[Any, TV_MaxPoolGradGradWithArgmax_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_grad_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_grad_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _attr_Targmax, (argmax,) = _execute.args_to_matching_eager([argmax], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (input, grad) = _inputs_T + _inputs_flat = [input, grad, argmax] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "include_batch_in_index", include_batch_in_index, "Targmax", _attr_Targmax, + "T", _attr_T) + _result = _execute.execute(b"MaxPoolGradGradWithArgmax", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGradGradWithArgmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGradV2_T = TypeVar("TV_MaxPoolGradV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad_v2(orig_input: Annotated[Any, TV_MaxPoolGradV2_T], orig_output: Annotated[Any, TV_MaxPoolGradV2_T], grad: Annotated[Any, TV_MaxPoolGradV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPoolGradV2_T]: + r"""Computes gradients of the maxpooling function. + + Args: + orig_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input tensor. + orig_output: A `Tensor`. Must have the same type as `orig_input`. + The original output tensor. + grad: A `Tensor`. Must have the same type as `orig_input`. + 4-D. Gradients w.r.t. the output of `max_pool`. + ksize: A `Tensor` of type `int32`. + The size of the window for each dimension of the input tensor. + strides: A `Tensor` of type `int32`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `orig_input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGradV2", name, orig_input, orig_output, grad, ksize, + strides, "padding", padding, "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_v2_eager_fallback( + orig_input, orig_output, grad, ksize, strides, padding=padding, + data_format=data_format, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGradV2", orig_input=orig_input, orig_output=orig_output, + grad=grad, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("padding", _op.get_attr("padding"), "data_format", + _op.get_attr("data_format"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGradV2 = tf_export("raw_ops.MaxPoolGradV2")(_ops.to_raw_op(max_pool_grad_v2)) + + +def max_pool_grad_v2_eager_fallback(orig_input: Annotated[Any, TV_MaxPoolGradV2_T], orig_output: Annotated[Any, TV_MaxPoolGradV2_T], grad: Annotated[Any, TV_MaxPoolGradV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPoolGradV2_T]: + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, _inputs_T = _execute.args_to_matching_eager([orig_input, orig_output, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ], _dtypes.float32) + (orig_input, orig_output, grad) = _inputs_T + ksize = _ops.convert_to_tensor(ksize, _dtypes.int32) + strides = _ops.convert_to_tensor(strides, _dtypes.int32) + _inputs_flat = [orig_input, orig_output, grad, ksize, strides] + _attrs = ("padding", padding, "data_format", data_format, "T", _attr_T) + _result = _execute.execute(b"MaxPoolGradV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolGradWithArgmax_Targmax = TypeVar("TV_MaxPoolGradWithArgmax_Targmax", _atypes.Int32, _atypes.Int64) +TV_MaxPoolGradWithArgmax_T = TypeVar("TV_MaxPoolGradWithArgmax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_grad_with_argmax(input: Annotated[Any, TV_MaxPoolGradWithArgmax_T], grad: Annotated[Any, TV_MaxPoolGradWithArgmax_T], argmax: Annotated[Any, TV_MaxPoolGradWithArgmax_Targmax], ksize, strides, padding: str, include_batch_in_index:bool=False, name=None) -> Annotated[Any, TV_MaxPoolGradWithArgmax_T]: + r"""Computes gradients of the maxpooling function. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The original input. + grad: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, height, width, channels]`. Gradients w.r.t. the + output of `max_pool`. + argmax: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The indices of the maximum values chosen for each output of `max_pool`. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + include_batch_in_index: An optional `bool`. Defaults to `False`. + Whether to include batch dimension in flattened index of `argmax`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolGradWithArgmax", name, input, grad, argmax, "ksize", + ksize, "strides", strides, "padding", padding, + "include_batch_in_index", include_batch_in_index) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_grad_with_argmax_eager_fallback( + input, grad, argmax, ksize=ksize, strides=strides, padding=padding, + include_batch_in_index=include_batch_in_index, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolGradWithArgmax", input=input, grad=grad, argmax=argmax, + ksize=ksize, strides=strides, + padding=padding, + include_batch_in_index=include_batch_in_index, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "include_batch_in_index", + _op._get_attr_bool("include_batch_in_index"), "Targmax", + _op._get_attr_type("Targmax"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolGradWithArgmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolGradWithArgmax = tf_export("raw_ops.MaxPoolGradWithArgmax")(_ops.to_raw_op(max_pool_grad_with_argmax)) + + +def max_pool_grad_with_argmax_eager_fallback(input: Annotated[Any, TV_MaxPoolGradWithArgmax_T], grad: Annotated[Any, TV_MaxPoolGradWithArgmax_T], argmax: Annotated[Any, TV_MaxPoolGradWithArgmax_Targmax], ksize, strides, padding: str, include_batch_in_index: bool, name, ctx) -> Annotated[Any, TV_MaxPoolGradWithArgmax_T]: + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_grad_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_grad_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _attr_Targmax, (argmax,) = _execute.args_to_matching_eager([argmax], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_T, _inputs_T = _execute.args_to_matching_eager([input, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (input, grad) = _inputs_T + _inputs_flat = [input, grad, argmax] + _attrs = ("ksize", ksize, "strides", strides, "padding", padding, + "include_batch_in_index", include_batch_in_index, "Targmax", _attr_Targmax, + "T", _attr_T) + _result = _execute.execute(b"MaxPoolGradWithArgmax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolGradWithArgmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_MaxPoolV2_T = TypeVar("TV_MaxPoolV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt8, _atypes.UInt16, _atypes.UInt8) + +def max_pool_v2(input: Annotated[Any, TV_MaxPoolV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format:str="NHWC", name=None) -> Annotated[Any, TV_MaxPoolV2_T]: + r"""Performs max pooling on the input. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, `int8`, `uint16`, `qint8`. + 4-D input to pool over. + ksize: A `Tensor` of type `int32`. + The size of the window for each dimension of the input tensor. + strides: A `Tensor` of type `int32`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolV2", name, input, ksize, strides, "padding", padding, + "data_format", data_format) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_v2_eager_fallback( + input, ksize, strides, padding=padding, data_format=data_format, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolV2", input=input, ksize=ksize, strides=strides, + padding=padding, data_format=data_format, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "padding", + _op.get_attr("padding"), "data_format", + _op.get_attr("data_format")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MaxPoolV2 = tf_export("raw_ops.MaxPoolV2")(_ops.to_raw_op(max_pool_v2)) + + +def max_pool_v2_eager_fallback(input: Annotated[Any, TV_MaxPoolV2_T], ksize: Annotated[Any, _atypes.Int32], strides: Annotated[Any, _atypes.Int32], padding: str, data_format: str, name, ctx) -> Annotated[Any, TV_MaxPoolV2_T]: + padding = _execute.make_str(padding, "padding") + if data_format is None: + data_format = "NHWC" + data_format = _execute.make_str(data_format, "data_format") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.uint16, _dtypes.qint8, ], _dtypes.float32) + ksize = _ops.convert_to_tensor(ksize, _dtypes.int32) + strides = _ops.convert_to_tensor(strides, _dtypes.int32) + _inputs_flat = [input, ksize, strides] + _attrs = ("T", _attr_T, "padding", padding, "data_format", data_format) + _result = _execute.execute(b"MaxPoolV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_MaxPoolWithArgmaxOutput = collections.namedtuple( + "MaxPoolWithArgmax", + ["output", "argmax"]) + + +TV_MaxPoolWithArgmax_Targmax = TypeVar("TV_MaxPoolWithArgmax_Targmax", _atypes.Int32, _atypes.Int64) +TV_MaxPoolWithArgmax_T = TypeVar("TV_MaxPoolWithArgmax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def max_pool_with_argmax(input: Annotated[Any, TV_MaxPoolWithArgmax_T], ksize, strides, padding: str, Targmax:TV_MaxPoolWithArgmax_Targmax=_dtypes.int64, include_batch_in_index:bool=False, name=None): + r"""Performs max pooling on the input and outputs both max values and indices. + + The indices in `argmax` are flattened, so that a maximum value at position + `[b, y, x, c]` becomes flattened index: + `(y * width + x) * channels + c` if `include_batch_in_index` is False; + `((b * height + y) * width + x) * channels + c` if `include_batch_in_index` is True. + + The indices returned are always in `[0, height) x [0, width)` before flattening, + even if padding is involved and the mathematically correct answer is outside + (either negative or too large). This is a bug, but fixing it is difficult to do + in a safe backwards compatible way, especially due to flattening. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 4-D with shape `[batch, height, width, channels]`. Input to pool over. + ksize: A list of `ints` that has length `>= 4`. + The size of the window for each dimension of the input tensor. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + Targmax: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + include_batch_in_index: An optional `bool`. Defaults to `False`. + Whether to include batch dimension in flattened index of `argmax`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, argmax). + + output: A `Tensor`. Has the same type as `input`. + argmax: A `Tensor` of type `Targmax`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MaxPoolWithArgmax", name, input, "ksize", ksize, "strides", + strides, "Targmax", Targmax, "padding", padding, + "include_batch_in_index", include_batch_in_index) + _result = _MaxPoolWithArgmaxOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return max_pool_with_argmax_eager_fallback( + input, ksize=ksize, strides=strides, Targmax=Targmax, + padding=padding, include_batch_in_index=include_batch_in_index, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if Targmax is None: + Targmax = _dtypes.int64 + Targmax = _execute.make_type(Targmax, "Targmax") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MaxPoolWithArgmax", input=input, ksize=ksize, strides=strides, + padding=padding, Targmax=Targmax, + include_batch_in_index=include_batch_in_index, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("ksize", _op.get_attr("ksize"), "strides", + _op.get_attr("strides"), "Targmax", + _op._get_attr_type("Targmax"), "padding", + _op.get_attr("padding"), "include_batch_in_index", + _op._get_attr_bool("include_batch_in_index"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MaxPoolWithArgmax", _inputs_flat, _attrs, _result) + _result = _MaxPoolWithArgmaxOutput._make(_result) + return _result + +MaxPoolWithArgmax = tf_export("raw_ops.MaxPoolWithArgmax")(_ops.to_raw_op(max_pool_with_argmax)) + + +def max_pool_with_argmax_eager_fallback(input: Annotated[Any, TV_MaxPoolWithArgmax_T], ksize, strides, padding: str, Targmax: TV_MaxPoolWithArgmax_Targmax, include_batch_in_index: bool, name, ctx): + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'max_pool_with_argmax' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'max_pool_with_argmax' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if Targmax is None: + Targmax = _dtypes.int64 + Targmax = _execute.make_type(Targmax, "Targmax") + if include_batch_in_index is None: + include_batch_in_index = False + include_batch_in_index = _execute.make_bool(include_batch_in_index, "include_batch_in_index") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [input] + _attrs = ("ksize", ksize, "strides", strides, "Targmax", Targmax, "padding", + padding, "include_batch_in_index", include_batch_in_index, "T", _attr_T) + _result = _execute.execute(b"MaxPoolWithArgmax", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MaxPoolWithArgmax", _inputs_flat, _attrs, _result) + _result = _MaxPoolWithArgmaxOutput._make(_result) + return _result + + +TV_NthElement_T = TypeVar("TV_NthElement_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def nth_element(input: Annotated[Any, TV_NthElement_T], n: Annotated[Any, _atypes.Int32], reverse:bool=False, name=None) -> Annotated[Any, TV_NthElement_T]: + r"""Finds values of the `n`-th order statistic for the last dimension. + + If the input is a vector (rank-1), finds the entries which is the nth-smallest + value in the vector and outputs their values as scalar tensor. + + For matrices (resp. higher rank input), computes the entries which is the + nth-smallest value in each row (resp. vector along the last dimension). Thus, + + values.shape = input.shape[:-1] + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D or higher with last dimension at least `n+1`. + n: A `Tensor` of type `int32`. + 0-D. Position of sorted vector to select along the last dimension (along + each row for matrices). Valid range of n is `[0, input.shape[:-1])` + reverse: An optional `bool`. Defaults to `False`. + When set to True, find the nth-largest value in the vector and vice + versa. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NthElement", name, input, n, "reverse", reverse) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return nth_element_eager_fallback( + input, n, reverse=reverse, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NthElement", input=input, n=n, reverse=reverse, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("reverse", _op._get_attr_bool("reverse"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NthElement", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NthElement = tf_export("raw_ops.NthElement")(_ops.to_raw_op(nth_element)) + + +def nth_element_eager_fallback(input: Annotated[Any, TV_NthElement_T], n: Annotated[Any, _atypes.Int32], reverse: bool, name, ctx) -> Annotated[Any, TV_NthElement_T]: + if reverse is None: + reverse = False + reverse = _execute.make_bool(reverse, "reverse") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + n = _ops.convert_to_tensor(n, _dtypes.int32) + _inputs_flat = [input, n] + _attrs = ("reverse", reverse, "T", _attr_T) + _result = _execute.execute(b"NthElement", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NthElement", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QuantizedAvgPoolOutput = collections.namedtuple( + "QuantizedAvgPool", + ["output", "min_output", "max_output"]) + + +TV_QuantizedAvgPool_T = TypeVar("TV_QuantizedAvgPool_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_avg_pool(input: Annotated[Any, TV_QuantizedAvgPool_T], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], ksize, strides, padding: str, name=None): + r"""Produces the average pool of the input tensor for quantized types. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + 4-D with shape `[batch, height, width, channels]`. + min_input: A `Tensor` of type `float32`. + The float value that the lowest quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the highest quantized input value represents. + ksize: A list of `ints`. + The size of the window for each dimension of the input tensor. + The length must be 4 to match the number of dimensions of the input. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + tensor. The length must be 4 to match the number of dimensions of the input. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor`. Has the same type as `input`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedAvgPool", name, input, min_input, max_input, "ksize", + ksize, "strides", strides, "padding", padding) + _result = _QuantizedAvgPoolOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_avg_pool_eager_fallback( + input, min_input, max_input, ksize=ksize, strides=strides, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'quantized_avg_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_avg_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedAvgPool", input=input, min_input=min_input, + max_input=max_input, ksize=ksize, strides=strides, + padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "ksize", _op.get_attr("ksize"), + "strides", _op.get_attr("strides"), "padding", + _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedAvgPool", _inputs_flat, _attrs, _result) + _result = _QuantizedAvgPoolOutput._make(_result) + return _result + +QuantizedAvgPool = tf_export("raw_ops.QuantizedAvgPool")(_ops.to_raw_op(quantized_avg_pool)) + + +def quantized_avg_pool_eager_fallback(input: Annotated[Any, TV_QuantizedAvgPool_T], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], ksize, strides, padding: str, name, ctx): + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'quantized_avg_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_avg_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + _inputs_flat = [input, min_input, max_input] + _attrs = ("T", _attr_T, "ksize", ksize, "strides", strides, "padding", + padding) + _result = _execute.execute(b"QuantizedAvgPool", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedAvgPool", _inputs_flat, _attrs, _result) + _result = _QuantizedAvgPoolOutput._make(_result) + return _result + +_QuantizedBatchNormWithGlobalNormalizationOutput = collections.namedtuple( + "QuantizedBatchNormWithGlobalNormalization", + ["result", "result_min", "result_max"]) + + +TV_QuantizedBatchNormWithGlobalNormalization_Tinput = TypeVar("TV_QuantizedBatchNormWithGlobalNormalization_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedBatchNormWithGlobalNormalization_out_type = TypeVar("TV_QuantizedBatchNormWithGlobalNormalization_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_batch_norm_with_global_normalization(t: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], t_min: Annotated[Any, _atypes.Float32], t_max: Annotated[Any, _atypes.Float32], m: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], m_min: Annotated[Any, _atypes.Float32], m_max: Annotated[Any, _atypes.Float32], v: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], v_min: Annotated[Any, _atypes.Float32], v_max: Annotated[Any, _atypes.Float32], beta: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], beta_min: Annotated[Any, _atypes.Float32], beta_max: Annotated[Any, _atypes.Float32], gamma: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], gamma_min: Annotated[Any, _atypes.Float32], gamma_max: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedBatchNormWithGlobalNormalization_out_type, variance_epsilon: float, scale_after_normalization: bool, name=None): + r"""Quantized Batch normalization. + + This op is deprecated and will be removed in the future. Prefer + `tf.nn.batch_normalization`. + + Args: + t: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A 4D input Tensor. + t_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized input. + t_max: A `Tensor` of type `float32`. + The value represented by the highest quantized input. + m: A `Tensor`. Must have the same type as `t`. + A 1D mean Tensor with size matching the last dimension of t. + This is the first output from tf.nn.moments, + or a saved moving average thereof. + m_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized mean. + m_max: A `Tensor` of type `float32`. + The value represented by the highest quantized mean. + v: A `Tensor`. Must have the same type as `t`. + A 1D variance Tensor with size matching the last dimension of t. + This is the second output from tf.nn.moments, + or a saved moving average thereof. + v_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized variance. + v_max: A `Tensor` of type `float32`. + The value represented by the highest quantized variance. + beta: A `Tensor`. Must have the same type as `t`. + A 1D beta Tensor with size matching the last dimension of t. + An offset to be added to the normalized tensor. + beta_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized offset. + beta_max: A `Tensor` of type `float32`. + The value represented by the highest quantized offset. + gamma: A `Tensor`. Must have the same type as `t`. + A 1D gamma Tensor with size matching the last dimension of t. + If "scale_after_normalization" is true, this tensor will be multiplied + with the normalized tensor. + gamma_min: A `Tensor` of type `float32`. + The value represented by the lowest quantized gamma. + gamma_max: A `Tensor` of type `float32`. + The value represented by the highest quantized gamma. + out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. + variance_epsilon: A `float`. A small float number to avoid dividing by 0. + scale_after_normalization: A `bool`. + A bool indicating whether the resulted tensor + needs to be multiplied with gamma. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (result, result_min, result_max). + + result: A `Tensor` of type `out_type`. + result_min: A `Tensor` of type `float32`. + result_max: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedBatchNormWithGlobalNormalization", name, t, t_min, + t_max, m, m_min, m_max, v, v_min, v_max, beta, beta_min, beta_max, + gamma, gamma_min, gamma_max, "out_type", out_type, "variance_epsilon", + variance_epsilon, "scale_after_normalization", + scale_after_normalization) + _result = _QuantizedBatchNormWithGlobalNormalizationOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_batch_norm_with_global_normalization_eager_fallback( + t, t_min, t_max, m, m_min, m_max, v, v_min, v_max, beta, beta_min, + beta_max, gamma, gamma_min, gamma_max, out_type=out_type, + variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedBatchNormWithGlobalNormalization", t=t, t_min=t_min, + t_max=t_max, m=m, + m_min=m_min, m_max=m_max, + v=v, v_min=v_min, + v_max=v_max, beta=beta, + beta_min=beta_min, + beta_max=beta_max, + gamma=gamma, + gamma_min=gamma_min, + gamma_max=gamma_max, + out_type=out_type, + variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type"), "variance_epsilon", + _op.get_attr("variance_epsilon"), "scale_after_normalization", + _op._get_attr_bool("scale_after_normalization")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedBatchNormWithGlobalNormalization", _inputs_flat, _attrs, _result) + _result = _QuantizedBatchNormWithGlobalNormalizationOutput._make(_result) + return _result + +QuantizedBatchNormWithGlobalNormalization = tf_export("raw_ops.QuantizedBatchNormWithGlobalNormalization")(_ops.to_raw_op(quantized_batch_norm_with_global_normalization)) + + +def quantized_batch_norm_with_global_normalization_eager_fallback(t: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], t_min: Annotated[Any, _atypes.Float32], t_max: Annotated[Any, _atypes.Float32], m: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], m_min: Annotated[Any, _atypes.Float32], m_max: Annotated[Any, _atypes.Float32], v: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], v_min: Annotated[Any, _atypes.Float32], v_max: Annotated[Any, _atypes.Float32], beta: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], beta_min: Annotated[Any, _atypes.Float32], beta_max: Annotated[Any, _atypes.Float32], gamma: Annotated[Any, TV_QuantizedBatchNormWithGlobalNormalization_Tinput], gamma_min: Annotated[Any, _atypes.Float32], gamma_max: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedBatchNormWithGlobalNormalization_out_type, variance_epsilon: float, scale_after_normalization: bool, name, ctx): + out_type = _execute.make_type(out_type, "out_type") + variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") + scale_after_normalization = _execute.make_bool(scale_after_normalization, "scale_after_normalization") + _attr_Tinput, _inputs_Tinput = _execute.args_to_matching_eager([t, m, v, beta, gamma], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + (t, m, v, beta, gamma) = _inputs_Tinput + t_min = _ops.convert_to_tensor(t_min, _dtypes.float32) + t_max = _ops.convert_to_tensor(t_max, _dtypes.float32) + m_min = _ops.convert_to_tensor(m_min, _dtypes.float32) + m_max = _ops.convert_to_tensor(m_max, _dtypes.float32) + v_min = _ops.convert_to_tensor(v_min, _dtypes.float32) + v_max = _ops.convert_to_tensor(v_max, _dtypes.float32) + beta_min = _ops.convert_to_tensor(beta_min, _dtypes.float32) + beta_max = _ops.convert_to_tensor(beta_max, _dtypes.float32) + gamma_min = _ops.convert_to_tensor(gamma_min, _dtypes.float32) + gamma_max = _ops.convert_to_tensor(gamma_max, _dtypes.float32) + _inputs_flat = [t, t_min, t_max, m, m_min, m_max, v, v_min, v_max, beta, beta_min, beta_max, gamma, gamma_min, gamma_max] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type, "variance_epsilon", + variance_epsilon, "scale_after_normalization", scale_after_normalization) + _result = _execute.execute(b"QuantizedBatchNormWithGlobalNormalization", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedBatchNormWithGlobalNormalization", _inputs_flat, _attrs, _result) + _result = _QuantizedBatchNormWithGlobalNormalizationOutput._make(_result) + return _result + +_QuantizedBiasAddOutput = collections.namedtuple( + "QuantizedBiasAdd", + ["output", "min_out", "max_out"]) + + +TV_QuantizedBiasAdd_T1 = TypeVar("TV_QuantizedBiasAdd_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedBiasAdd_T2 = TypeVar("TV_QuantizedBiasAdd_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedBiasAdd_out_type = TypeVar("TV_QuantizedBiasAdd_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_bias_add(input: Annotated[Any, TV_QuantizedBiasAdd_T1], bias: Annotated[Any, TV_QuantizedBiasAdd_T2], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_bias: Annotated[Any, _atypes.Float32], max_bias: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedBiasAdd_out_type, name=None): + r"""Adds Tensor 'bias' to Tensor 'input' for Quantized types. + + Broadcasts the values of bias on dimensions 0..N-2 of 'input'. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A 1D bias Tensor with size matching the last dimension of 'input'. + min_input: A `Tensor` of type `float32`. + The float value that the lowest quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the highest quantized input value represents. + min_bias: A `Tensor` of type `float32`. + The float value that the lowest quantized bias value represents. + max_bias: A `Tensor` of type `float32`. + The float value that the highest quantized bias value represents. + out_type: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_out, max_out). + + output: A `Tensor` of type `out_type`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedBiasAdd", name, input, bias, min_input, max_input, + min_bias, max_bias, "out_type", out_type) + _result = _QuantizedBiasAddOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_bias_add_eager_fallback( + input, bias, min_input, max_input, min_bias, max_bias, + out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedBiasAdd", input=input, bias=bias, min_input=min_input, + max_input=max_input, min_bias=min_bias, + max_bias=max_bias, out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "out_type", _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedBiasAdd", _inputs_flat, _attrs, _result) + _result = _QuantizedBiasAddOutput._make(_result) + return _result + +QuantizedBiasAdd = tf_export("raw_ops.QuantizedBiasAdd")(_ops.to_raw_op(quantized_bias_add)) + + +def quantized_bias_add_eager_fallback(input: Annotated[Any, TV_QuantizedBiasAdd_T1], bias: Annotated[Any, TV_QuantizedBiasAdd_T2], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_bias: Annotated[Any, _atypes.Float32], max_bias: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedBiasAdd_out_type, name, ctx): + out_type = _execute.make_type(out_type, "out_type") + _attr_T1, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_bias = _ops.convert_to_tensor(min_bias, _dtypes.float32) + max_bias = _ops.convert_to_tensor(max_bias, _dtypes.float32) + _inputs_flat = [input, bias, min_input, max_input, min_bias, max_bias] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "out_type", out_type) + _result = _execute.execute(b"QuantizedBiasAdd", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedBiasAdd", _inputs_flat, _attrs, _result) + _result = _QuantizedBiasAddOutput._make(_result) + return _result + +_QuantizedConv2DOutput = collections.namedtuple( + "QuantizedConv2D", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2D_Tinput = TypeVar("TV_QuantizedConv2D_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2D_Tfilter = TypeVar("TV_QuantizedConv2D_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2D_out_type = TypeVar("TV_QuantizedConv2D_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d(input: Annotated[Any, TV_QuantizedConv2D_Tinput], filter: Annotated[Any, TV_QuantizedConv2D_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2D_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], name=None): + r"""Computes a 2D convolution given quantized 4D input and filter tensors. + + The inputs are quantized tensors where the lowest value represents the real + number of the associated minimum, and the highest represents the maximum. + This means that you can only interpret the quantized output in the same way, by + taking the returned minimum and maximum values into account. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter's input_depth dimension must match input's depth dimensions. + min_input: A `Tensor` of type `float32`. + The float value that the lowest quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the highest quantized input value represents. + min_filter: A `Tensor` of type `float32`. + The float value that the lowest quantized filter value represents. + max_filter: A `Tensor` of type `float32`. + The float value that the highest quantized filter value represents. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by the + value of `data_format`, see above for details. Dilations in the batch and + depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2D", name, input, filter, min_input, max_input, + min_filter, max_filter, "out_type", out_type, "strides", strides, + "padding", padding, "dilations", dilations) + _result = _QuantizedConv2DOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2D", input=input, filter=filter, min_input=min_input, + max_input=max_input, min_filter=min_filter, + max_filter=max_filter, strides=strides, + padding=padding, out_type=out_type, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2D", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DOutput._make(_result) + return _result + +QuantizedConv2D = tf_export("raw_ops.QuantizedConv2D")(_ops.to_raw_op(quantized_conv2d)) + + +def quantized_conv2d_eager_fallback(input: Annotated[Any, TV_QuantizedConv2D_Tinput], filter: Annotated[Any, TV_QuantizedConv2D_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2D_out_type, dilations, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations) + _result = _execute.execute(b"QuantizedConv2D", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2D", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DOutput._make(_result) + return _result + +_QuantizedConv2DAndReluOutput = collections.namedtuple( + "QuantizedConv2DAndRelu", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DAndRelu_Tinput = TypeVar("TV_QuantizedConv2DAndRelu_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndRelu_Tfilter = TypeVar("TV_QuantizedConv2DAndRelu_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndRelu_out_type = TypeVar("TV_QuantizedConv2DAndRelu_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_and_relu(input: Annotated[Any, TV_QuantizedConv2DAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndRelu_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DAndRelu_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DAndRelu", name, input, filter, min_input, + max_input, min_filter, max_filter, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _QuantizedConv2DAndReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_and_relu_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DAndRelu", input=input, filter=filter, + min_input=min_input, max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, strides=strides, + padding=padding, out_type=out_type, + dilations=dilations, + padding_list=padding_list, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndReluOutput._make(_result) + return _result + +QuantizedConv2DAndRelu = tf_export("raw_ops.QuantizedConv2DAndRelu")(_ops.to_raw_op(quantized_conv2d_and_relu)) + + +def quantized_conv2d_and_relu_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndRelu_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DAndRelu_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DAndRelu", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndReluOutput._make(_result) + return _result + +_QuantizedConv2DAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DAndReluAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DAndReluAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DAndReluAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndReluAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DAndReluAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndReluAndRequantize_out_type = TypeVar("TV_QuantizedConv2DAndReluAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_and_relu_and_requantize(input: Annotated[Any, TV_QuantizedConv2DAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndReluAndRequantize_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DAndReluAndRequantize_out_type=_dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DAndReluAndRequantize", name, input, filter, + min_input, max_input, min_filter, max_filter, min_freezed_output, + max_freezed_output, "out_type", out_type, "strides", strides, + "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _QuantizedConv2DAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_and_relu_and_requantize_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, out_type=out_type, + strides=strides, padding=padding, dilations=dilations, + padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DAndReluAndRequantize", input=input, filter=filter, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DAndReluAndRequantize = tf_export("raw_ops.QuantizedConv2DAndReluAndRequantize")(_ops.to_raw_op(quantized_conv2d_and_relu_and_requantize)) + + +def quantized_conv2d_and_relu_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndReluAndRequantize_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DAndReluAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DAndReluAndRequantize", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedConv2DAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DAndRequantize_out_type = TypeVar("TV_QuantizedConv2DAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_and_requantize(input: Annotated[Any, TV_QuantizedConv2DAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndRequantize_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DAndRequantize_out_type=_dtypes.qint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DAndRequantize", name, input, filter, min_input, + max_input, min_filter, max_filter, min_freezed_output, + max_freezed_output, "out_type", out_type, "strides", strides, + "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _QuantizedConv2DAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_and_requantize_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, out_type=out_type, + strides=strides, padding=padding, dilations=dilations, + padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DAndRequantize", input=input, filter=filter, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + strides=strides, padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DAndRequantize = tf_export("raw_ops.QuantizedConv2DAndRequantize")(_ops.to_raw_op(quantized_conv2d_and_requantize)) + + +def quantized_conv2d_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DAndRequantize_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DAndRequantize", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DAndRequantizeOutput._make(_result) + return _result + +_QuantizedConv2DPerChannelOutput = collections.namedtuple( + "QuantizedConv2DPerChannel", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DPerChannel_Tinput = TypeVar("TV_QuantizedConv2DPerChannel_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DPerChannel_Tfilter = TypeVar("TV_QuantizedConv2DPerChannel_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DPerChannel_out_type = TypeVar("TV_QuantizedConv2DPerChannel_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_per_channel(input: Annotated[Any, TV_QuantizedConv2DPerChannel_Tinput], filter: Annotated[Any, TV_QuantizedConv2DPerChannel_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DPerChannel_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], name=None): + r"""Computes QuantizedConv2D per channel. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original filter tensor. + min_input: A `Tensor` of type `float32`. + The minimum value of the input tensor + max_input: A `Tensor` of type `float32`. + The maximum value of the input tensor. + min_filter: A `Tensor` of type `float32`. + The minimum value of the filter tensor. + max_filter: A `Tensor` of type `float32`. + The maximum value of the filter tensor. + strides: A list of `ints`. list of stride values. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + The quantized type of output tensor that needs to be converted. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + list of dilation values. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DPerChannel", name, input, filter, min_input, + max_input, min_filter, max_filter, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations) + _result = _QuantizedConv2DPerChannelOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_per_channel_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_per_channel' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_per_channel' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DPerChannel", input=input, filter=filter, + min_input=min_input, max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, strides=strides, + padding=padding, out_type=out_type, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DPerChannel", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DPerChannelOutput._make(_result) + return _result + +QuantizedConv2DPerChannel = tf_export("raw_ops.QuantizedConv2DPerChannel")(_ops.to_raw_op(quantized_conv2d_per_channel)) + + +def quantized_conv2d_per_channel_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DPerChannel_Tinput], filter: Annotated[Any, TV_QuantizedConv2DPerChannel_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DPerChannel_out_type, dilations, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_per_channel' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_per_channel' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations) + _result = _execute.execute(b"QuantizedConv2DPerChannel", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DPerChannel", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DPerChannelOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasOutput = collections.namedtuple( + "QuantizedConv2DWithBias", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBias_Tinput = TypeVar("TV_QuantizedConv2DWithBias_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBias_Tfilter = TypeVar("TV_QuantizedConv2DWithBias_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBias_out_type = TypeVar("TV_QuantizedConv2DWithBias_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias(input: Annotated[Any, TV_QuantizedConv2DWithBias_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBias_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBias_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor` of type `float32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBias", name, input, filter, bias, min_input, + max_input, min_filter, max_filter, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _QuantizedConv2DWithBiasOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBias", input=input, filter=filter, bias=bias, + min_input=min_input, max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, strides=strides, + padding=padding, out_type=out_type, + dilations=dilations, + padding_list=padding_list, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasOutput._make(_result) + return _result + +QuantizedConv2DWithBias = tf_export("raw_ops.QuantizedConv2DWithBias")(_ops.to_raw_op(quantized_conv2d_with_bias)) + + +def quantized_conv2d_with_bias_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBias_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBias_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBias_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBias", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasAndReluOutput = collections.namedtuple( + "QuantizedConv2DWithBiasAndRelu", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasAndRelu_Tinput = TypeVar("TV_QuantizedConv2DWithBiasAndRelu_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndRelu_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasAndRelu_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndRelu_out_type = TypeVar("TV_QuantizedConv2DWithBiasAndRelu_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_and_relu(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasAndRelu_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor` of type `float32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasAndRelu", name, input, filter, bias, + min_input, max_input, min_filter, max_filter, "out_type", out_type, + "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasAndReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_and_relu_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasAndRelu", input=input, filter=filter, + bias=bias, min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + strides=strides, padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndReluOutput._make(_result) + return _result + +QuantizedConv2DWithBiasAndRelu = tf_export("raw_ops.QuantizedConv2DWithBiasAndRelu")(_ops.to_raw_op(quantized_conv2d_with_bias_and_relu)) + + +def quantized_conv2d_with_bias_and_relu_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasAndRelu_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasAndRelu", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndReluOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DWithBiasAndReluAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tbias = TypeVar("TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedConv2DWithBiasAndReluAndRequantize_out_type = TypeVar("TV_QuantizedConv2DWithBiasAndReluAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_and_relu_and_requantize(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasAndReluAndRequantize_out_type=_dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasAndReluAndRequantize", name, input, + filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, "out_type", out_type, + "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_and_relu_and_requantize_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, out_type=out_type, + strides=strides, padding=padding, dilations=dilations, + padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasAndReluAndRequantize", input=input, + filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "Tbias", + _op._get_attr_type("Tbias"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DWithBiasAndReluAndRequantize = tf_export("raw_ops.QuantizedConv2DWithBiasAndReluAndRequantize")(_ops.to_raw_op(quantized_conv2d_with_bias_and_relu_and_requantize)) + + +def quantized_conv2d_with_bias_and_relu_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasAndReluAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "Tbias", + _attr_Tbias, "out_type", out_type, "strides", strides, "padding", padding, + "dilations", dilations, "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasAndReluAndRequantize", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DWithBiasAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DWithBiasAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasAndRequantize_Tbias = TypeVar("TV_QuantizedConv2DWithBiasAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedConv2DWithBiasAndRequantize_out_type = TypeVar("TV_QuantizedConv2DWithBiasAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_and_requantize(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasAndRequantize_out_type=_dtypes.qint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasAndRequantize", name, input, filter, + bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, "out_type", out_type, + "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_and_requantize_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, out_type=out_type, + strides=strides, padding=padding, dilations=dilations, + padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasAndRequantize", input=input, filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "Tbias", + _op._get_attr_type("Tbias"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DWithBiasAndRequantize = tf_export("raw_ops.QuantizedConv2DWithBiasAndRequantize")(_ops.to_raw_op(quantized_conv2d_with_bias_and_requantize)) + + +def quantized_conv2d_with_bias_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "Tbias", + _attr_Tbias, "out_type", out_type, "strides", strides, "padding", padding, + "dilations", dilations, "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasAndRequantize", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasAndRequantizeOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasSignedSumAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tbias = TypeVar("TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tsummand = TypeVar("TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tsummand", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_out_type = TypeVar("TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize(input: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], summand: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tsummand], min_summand: Annotated[Any, _atypes.Float32], max_summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_out_type=_dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + summand: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_summand: A `Tensor` of type `float32`. + max_summand: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", name, + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, summand, min_summand, + max_summand, "out_type", out_type, "strides", strides, "padding", + padding, "dilations", dilations, "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasSignedSumAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, summand, min_summand, + max_summand, out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", input=input, + filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + summand=summand, + min_summand=min_summand, + max_summand=max_summand, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "Tbias", + _op._get_attr_type("Tbias"), "Tsummand", + _op._get_attr_type("Tsummand"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSignedSumAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DWithBiasSignedSumAndReluAndRequantize = tf_export("raw_ops.QuantizedConv2DWithBiasSignedSumAndReluAndRequantize")(_ops.to_raw_op(quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize)) + + +def quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], summand: Annotated[Any, TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_Tsummand], min_summand: Annotated[Any, _atypes.Float32], max_summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasSignedSumAndReluAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_signed_sum_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + _attr_Tsummand, (summand,) = _execute.args_to_matching_eager([summand], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + min_summand = _ops.convert_to_tensor(min_summand, _dtypes.float32) + max_summand = _ops.convert_to_tensor(max_summand, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output, summand, min_summand, max_summand] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "Tbias", + _attr_Tbias, "Tsummand", _attr_Tsummand, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasSignedSumAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSignedSumAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasSumAndReluOutput = collections.namedtuple( + "QuantizedConv2DWithBiasSumAndRelu", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasSumAndRelu_Tinput = TypeVar("TV_QuantizedConv2DWithBiasSumAndRelu_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSumAndRelu_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasSumAndRelu_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSumAndRelu_out_type = TypeVar("TV_QuantizedConv2DWithBiasSumAndRelu_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_sum_and_relu(input: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasSumAndRelu_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor` of type `float32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + summand: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasSumAndRelu", name, input, filter, bias, + min_input, max_input, min_filter, max_filter, summand, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", + dilations, "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasSumAndReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_sum_and_relu_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + summand, out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasSumAndRelu", input=input, filter=filter, + bias=bias, min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + summand=summand, strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasSumAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSumAndReluOutput._make(_result) + return _result + +QuantizedConv2DWithBiasSumAndRelu = tf_export("raw_ops.QuantizedConv2DWithBiasSumAndRelu")(_ops.to_raw_op(quantized_conv2d_with_bias_sum_and_relu)) + + +def quantized_conv2d_with_bias_sum_and_relu_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasSumAndRelu_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_sum_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + summand = _ops.convert_to_tensor(summand, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, summand] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasSumAndRelu", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasSumAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSumAndReluOutput._make(_result) + return _result + +_QuantizedConv2DWithBiasSumAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedConv2DWithBiasSumAndReluAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tinput = TypeVar("TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tfilter = TypeVar("TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tbias = TypeVar("TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tsummand = TypeVar("TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tsummand", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_out_type = TypeVar("TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_conv2d_with_bias_sum_and_relu_and_requantize(input: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], summand: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tsummand], min_summand: Annotated[Any, _atypes.Float32], max_summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_out_type=_dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_input: A `Tensor` of type `float32`. + max_input: A `Tensor` of type `float32`. + min_filter: A `Tensor` of type `float32`. + max_filter: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + summand: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_summand: A `Tensor` of type `float32`. + max_summand: A `Tensor` of type `float32`. + strides: A list of `ints`. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedConv2DWithBiasSumAndReluAndRequantize", name, input, + filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, summand, min_summand, + max_summand, "out_type", out_type, "strides", strides, "padding", + padding, "dilations", dilations, "padding_list", padding_list) + _result = _QuantizedConv2DWithBiasSumAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_conv2d_with_bias_sum_and_relu_and_requantize_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, summand, min_summand, + max_summand, out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedConv2DWithBiasSumAndReluAndRequantize", input=input, + filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + summand=summand, + min_summand=min_summand, + max_summand=max_summand, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "Tbias", + _op._get_attr_type("Tbias"), "Tsummand", + _op._get_attr_type("Tsummand"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedConv2DWithBiasSumAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSumAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedConv2DWithBiasSumAndReluAndRequantize = tf_export("raw_ops.QuantizedConv2DWithBiasSumAndReluAndRequantize")(_ops.to_raw_op(quantized_conv2d_with_bias_sum_and_relu_and_requantize)) + + +def quantized_conv2d_with_bias_sum_and_relu_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], summand: Annotated[Any, TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_Tsummand], min_summand: Annotated[Any, _atypes.Float32], max_summand: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedConv2DWithBiasSumAndReluAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_conv2d_with_bias_sum_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + _attr_Tsummand, (summand,) = _execute.args_to_matching_eager([summand], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + min_summand = _ops.convert_to_tensor(min_summand, _dtypes.float32) + max_summand = _ops.convert_to_tensor(max_summand, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output, summand, min_summand, max_summand] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "Tbias", + _attr_Tbias, "Tsummand", _attr_Tsummand, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations, "padding_list", + padding_list) + _result = _execute.execute(b"QuantizedConv2DWithBiasSumAndReluAndRequantize", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedConv2DWithBiasSumAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedConv2DWithBiasSumAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedDepthwiseConv2DOutput = collections.namedtuple( + "QuantizedDepthwiseConv2D", + ["output", "min_output", "max_output"]) + + +TV_QuantizedDepthwiseConv2D_Tinput = TypeVar("TV_QuantizedDepthwiseConv2D_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2D_Tfilter = TypeVar("TV_QuantizedDepthwiseConv2D_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2D_out_type = TypeVar("TV_QuantizedDepthwiseConv2D_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_depthwise_conv2d(input: Annotated[Any, TV_QuantizedDepthwiseConv2D_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2D_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedDepthwiseConv2D_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], name=None): + r"""Computes quantized depthwise Conv2D. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original filter tensor. + min_input: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + min_filter: A `Tensor` of type `float32`. + The float value that the minimum quantized filter value represents. + max_filter: A `Tensor` of type `float32`. + The float value that the maximum quantized filter value represents. + strides: A list of `ints`. List of stride values. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + The type of the output. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + List of dilation values. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedDepthwiseConv2D", name, input, filter, min_input, + max_input, min_filter, max_filter, "out_type", out_type, "strides", + strides, "padding", padding, "dilations", dilations) + _result = _QuantizedDepthwiseConv2DOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_depthwise_conv2d_eager_fallback( + input, filter, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedDepthwiseConv2D", input=input, filter=filter, + min_input=min_input, max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, strides=strides, + padding=padding, out_type=out_type, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedDepthwiseConv2D", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DOutput._make(_result) + return _result + +QuantizedDepthwiseConv2D = tf_export("raw_ops.QuantizedDepthwiseConv2D")(_ops.to_raw_op(quantized_depthwise_conv2d)) + + +def quantized_depthwise_conv2d_eager_fallback(input: Annotated[Any, TV_QuantizedDepthwiseConv2D_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2D_Tfilter], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedDepthwiseConv2D_out_type, dilations, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations) + _result = _execute.execute(b"QuantizedDepthwiseConv2D", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedDepthwiseConv2D", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DOutput._make(_result) + return _result + +_QuantizedDepthwiseConv2DWithBiasOutput = collections.namedtuple( + "QuantizedDepthwiseConv2DWithBias", + ["output", "min_output", "max_output"]) + + +TV_QuantizedDepthwiseConv2DWithBias_Tinput = TypeVar("TV_QuantizedDepthwiseConv2DWithBias_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBias_Tfilter = TypeVar("TV_QuantizedDepthwiseConv2DWithBias_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBias_out_type = TypeVar("TV_QuantizedDepthwiseConv2DWithBias_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_depthwise_conv2d_with_bias(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBias_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBias_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedDepthwiseConv2DWithBias_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], name=None): + r"""Computes quantized depthwise Conv2D with Bias. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original filter tensor. + bias: A `Tensor` of type `float32`. The original bias tensor. + min_input: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + min_filter: A `Tensor` of type `float32`. + The float value that the minimum quantized filter value represents. + max_filter: A `Tensor` of type `float32`. + The float value that the maximum quantized filter value represents. + strides: A list of `ints`. List of stride values. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + The type of the output. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + List of dilation values. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedDepthwiseConv2DWithBias", name, input, filter, bias, + min_input, max_input, min_filter, max_filter, "out_type", out_type, + "strides", strides, "padding", padding, "dilations", dilations) + _result = _QuantizedDepthwiseConv2DWithBiasOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_depthwise_conv2d_with_bias_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedDepthwiseConv2DWithBias", input=input, filter=filter, + bias=bias, min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + strides=strides, padding=padding, + out_type=out_type, + dilations=dilations, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasOutput._make(_result) + return _result + +QuantizedDepthwiseConv2DWithBias = tf_export("raw_ops.QuantizedDepthwiseConv2DWithBias")(_ops.to_raw_op(quantized_depthwise_conv2d_with_bias)) + + +def quantized_depthwise_conv2d_with_bias_eager_fallback(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBias_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBias_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedDepthwiseConv2DWithBias_out_type, dilations, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations) + _result = _execute.execute(b"QuantizedDepthwiseConv2DWithBias", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasOutput._make(_result) + return _result + +_QuantizedDepthwiseConv2DWithBiasAndReluOutput = collections.namedtuple( + "QuantizedDepthwiseConv2DWithBiasAndRelu", + ["output", "min_output", "max_output"]) + + +TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tinput = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tfilter = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBiasAndRelu_out_type = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndRelu_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_depthwise_conv2d_with_bias_and_relu(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedDepthwiseConv2DWithBiasAndRelu_out_type=_dtypes.qint32, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""Computes quantized depthwise Conv2D with Bias and Relu. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original filter tensor. + bias: A `Tensor` of type `float32`. The original bias tensor. + min_input: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + min_filter: A `Tensor` of type `float32`. + The float value that the minimum quantized filter value represents. + max_filter: A `Tensor` of type `float32`. + The float value that the maximum quantized filter value represents. + strides: A list of `ints`. List of stride values. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + The type of the output. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + List of dilation values. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedDepthwiseConv2DWithBiasAndRelu", name, input, filter, + bias, min_input, max_input, min_filter, max_filter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", + dilations, "padding_list", padding_list) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_depthwise_conv2d_with_bias_and_relu_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + out_type=out_type, strides=strides, padding=padding, + dilations=dilations, padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedDepthwiseConv2DWithBiasAndRelu", input=input, filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluOutput._make(_result) + return _result + +QuantizedDepthwiseConv2DWithBiasAndRelu = tf_export("raw_ops.QuantizedDepthwiseConv2DWithBiasAndRelu")(_ops.to_raw_op(quantized_depthwise_conv2d_with_bias_and_relu)) + + +def quantized_depthwise_conv2d_with_bias_and_relu_eager_fallback(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndRelu_Tfilter], bias: Annotated[Any, _atypes.Float32], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedDepthwiseConv2DWithBiasAndRelu_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.qint32 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "out_type", + out_type, "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _execute.execute(b"QuantizedDepthwiseConv2DWithBiasAndRelu", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluOutput._make(_result) + return _result + +_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", + ["output", "min_output", "max_output"]) + + +TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tinput = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tfilter = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tfilter", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tbias = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_out_type = TypeVar("TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_depthwise_conv2d_with_bias_and_relu_and_requantize(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type:TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_out_type=_dtypes.quint8, dilations=[1, 1, 1, 1], padding_list=[], name=None): + r"""Computes quantized depthwise Conv2D with Bias, Relu and Requantize. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original input tensor. + filter: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The original filter tensor. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + The original bias tensor. + min_input: A `Tensor` of type `float32`. + The float value that the minimum quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the maximum quantized input value represents. + min_filter: A `Tensor` of type `float32`. + The float value that the minimum quantized filter value represents. + max_filter: A `Tensor` of type `float32`. + The float value that the maximum quantized filter value represents. + min_freezed_output: A `Tensor` of type `float32`. + The minimum float value of the output tensor. + max_freezed_output: A `Tensor` of type `float32`. + The maximum float value of the output tensor. + strides: A list of `ints`. List of stride values. + padding: A `string` from: `"SAME", "VALID"`. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + The type of the output. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + List of dilation values. + padding_list: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor` of type `out_type`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", name, + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, "out_type", out_type, + "strides", strides, "padding", padding, "dilations", dilations, + "padding_list", padding_list) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_depthwise_conv2d_with_bias_and_relu_and_requantize_eager_fallback( + input, filter, bias, min_input, max_input, min_filter, max_filter, + min_freezed_output, max_freezed_output, out_type=out_type, + strides=strides, padding=padding, dilations=dilations, + padding_list=padding_list, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", input=input, + filter=filter, + bias=bias, + min_input=min_input, + max_input=max_input, + min_filter=min_filter, + max_filter=max_filter, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + strides=strides, + padding=padding, + out_type=out_type, + dilations=dilations, + padding_list=padding_list, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "Tfilter", + _op._get_attr_type("Tfilter"), "Tbias", + _op._get_attr_type("Tbias"), "out_type", + _op._get_attr_type("out_type"), "strides", + _op.get_attr("strides"), "padding", _op.get_attr("padding"), + "dilations", _op.get_attr("dilations"), "padding_list", + _op.get_attr("padding_list")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize = tf_export("raw_ops.QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize")(_ops.to_raw_op(quantized_depthwise_conv2d_with_bias_and_relu_and_requantize)) + + +def quantized_depthwise_conv2d_with_bias_and_relu_and_requantize_eager_fallback(input: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tinput], filter: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tfilter], bias: Annotated[Any, TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_Tbias], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], min_filter: Annotated[Any, _atypes.Float32], max_filter: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], strides, padding: str, out_type: TV_QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize_out_type, dilations, padding_list, name, ctx): + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + if dilations is None: + dilations = [1, 1, 1, 1] + if not isinstance(dilations, (list, tuple)): + raise TypeError( + "Expected list for 'dilations' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % dilations) + dilations = [_execute.make_int(_i, "dilations") for _i in dilations] + if padding_list is None: + padding_list = [] + if not isinstance(padding_list, (list, tuple)): + raise TypeError( + "Expected list for 'padding_list' argument to " + "'quantized_depthwise_conv2d_with_bias_and_relu_and_requantize' Op, not %r." % padding_list) + padding_list = [_execute.make_int(_i, "padding_list") for _i in padding_list] + _attr_Tinput, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tfilter, (filter,) = _execute.args_to_matching_eager([filter], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + min_filter = _ops.convert_to_tensor(min_filter, _dtypes.float32) + max_filter = _ops.convert_to_tensor(max_filter, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [input, filter, bias, min_input, max_input, min_filter, max_filter, min_freezed_output, max_freezed_output] + _attrs = ("Tinput", _attr_Tinput, "Tfilter", _attr_Tfilter, "Tbias", + _attr_Tbias, "out_type", out_type, "strides", strides, "padding", padding, + "dilations", dilations, "padding_list", padding_list) + _result = _execute.execute(b"QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedDepthwiseConv2DWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedMatMulWithBiasOutput = collections.namedtuple( + "QuantizedMatMulWithBias", + ["out", "min_out", "max_out"]) + + +TV_QuantizedMatMulWithBias_T1 = TypeVar("TV_QuantizedMatMulWithBias_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBias_T2 = TypeVar("TV_QuantizedMatMulWithBias_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBias_Tbias = TypeVar("TV_QuantizedMatMulWithBias_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedMatMulWithBias_Toutput = TypeVar("TV_QuantizedMatMulWithBias_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mat_mul_with_bias(a: Annotated[Any, TV_QuantizedMatMulWithBias_T1], b: Annotated[Any, TV_QuantizedMatMulWithBias_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBias_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMatMulWithBias_Toutput=_dtypes.qint32, transpose_a:bool=False, transpose_b:bool=False, input_quant_mode:str="MIN_FIRST", name=None): + r"""Performs a quantized matrix multiplication of `a` by the matrix `b` with bias +add. + + The inputs must be two-dimensional matrices and 1D bias vector. And the inner + dimension of `a` (after being transposed if `transpose_a` is non-zero) must + match the outer dimension of `b` (after being transposed if `transposed_b` is + non-zero). Then do broadcast add operation with bias values on the matrix + multiplication result. The bias size must match inner dimension of `b`. + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + A 1D bias tensor with size matching inner dimension of `b` (after being + transposed if `transposed_b` is non-zero). + min_a: A `Tensor` of type `float32`. + The float value that the lowest quantized `a` value represents. + max_a: A `Tensor` of type `float32`. + The float value that the highest quantized `a` value represents. + min_b: A `Tensor` of type `float32`. + The float value that the lowest quantized `b` value represents. + max_b: A `Tensor` of type `float32`. + The float value that the highest quantized `b` value represents. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + transpose_a: An optional `bool`. Defaults to `False`. + If true, `a` is transposed before multiplication. + transpose_b: An optional `bool`. Defaults to `False`. + If true, `b` is transposed before multiplication. + input_quant_mode: An optional `string` from: `"MIN_FIRST", "SCALED"`. Defaults to `"MIN_FIRST"`. + Input data quantization mode. Either MIN_FIRST(default) or SCALED. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, min_out, max_out). + + out: A `Tensor` of type `Toutput`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMulWithBias", name, a, b, bias, min_a, max_a, + min_b, max_b, "Toutput", Toutput, "transpose_a", transpose_a, + "transpose_b", transpose_b, "input_quant_mode", input_quant_mode) + _result = _QuantizedMatMulWithBiasOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_with_bias_eager_fallback( + a, b, bias, min_a, max_a, min_b, max_b, Toutput=Toutput, + transpose_a=transpose_a, transpose_b=transpose_b, + input_quant_mode=input_quant_mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMulWithBias", a=a, b=b, bias=bias, min_a=min_a, + max_a=max_a, min_b=min_b, max_b=max_b, + Toutput=Toutput, transpose_a=transpose_a, + transpose_b=transpose_b, + input_quant_mode=input_quant_mode, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Tbias", _op._get_attr_type("Tbias"), "Toutput", + _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "input_quant_mode", + _op.get_attr("input_quant_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMulWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasOutput._make(_result) + return _result + +QuantizedMatMulWithBias = tf_export("raw_ops.QuantizedMatMulWithBias")(_ops.to_raw_op(quantized_mat_mul_with_bias)) + + +def quantized_mat_mul_with_bias_eager_fallback(a: Annotated[Any, TV_QuantizedMatMulWithBias_T1], b: Annotated[Any, TV_QuantizedMatMulWithBias_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBias_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBias_Toutput, transpose_a: bool, transpose_b: bool, input_quant_mode: str, name, ctx): + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + _inputs_flat = [a, b, bias, min_a, max_a, min_b, max_b] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Tbias", _attr_Tbias, "Toutput", + Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, + "input_quant_mode", input_quant_mode) + _result = _execute.execute(b"QuantizedMatMulWithBias", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMulWithBias", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasOutput._make(_result) + return _result + + +TV_QuantizedMatMulWithBiasAndDequantize_T1 = TypeVar("TV_QuantizedMatMulWithBiasAndDequantize_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndDequantize_T2 = TypeVar("TV_QuantizedMatMulWithBiasAndDequantize_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndDequantize_Tbias = TypeVar("TV_QuantizedMatMulWithBiasAndDequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedMatMulWithBiasAndDequantize_Toutput = TypeVar("TV_QuantizedMatMulWithBiasAndDequantize_Toutput", bound=_atypes.Float32) + +def quantized_mat_mul_with_bias_and_dequantize(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBiasAndDequantize_Toutput, transpose_a:bool=False, transpose_b:bool=False, input_quant_mode:str="MIN_FIRST", name=None) -> Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_Toutput]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_a: A `Tensor` of type `float32`. + max_a: A `Tensor` of type `float32`. + min_b: A `Tensor` of type `float32`. + max_b: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + Toutput: A `tf.DType` from: `tf.float32`. + transpose_a: An optional `bool`. Defaults to `False`. + transpose_b: An optional `bool`. Defaults to `False`. + input_quant_mode: An optional `string` from: `"MIN_FIRST", "SCALED"`. Defaults to `"MIN_FIRST"`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Toutput`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMulWithBiasAndDequantize", name, a, b, bias, min_a, + max_a, min_b, max_b, min_freezed_output, max_freezed_output, + "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", + transpose_b, "input_quant_mode", input_quant_mode) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_with_bias_and_dequantize_eager_fallback( + a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, + max_freezed_output, Toutput=Toutput, transpose_a=transpose_a, + transpose_b=transpose_b, input_quant_mode=input_quant_mode, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMulWithBiasAndDequantize", a=a, b=b, bias=bias, + min_a=min_a, max_a=max_a, + min_b=min_b, max_b=max_b, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + Toutput=Toutput, + transpose_a=transpose_a, + transpose_b=transpose_b, + input_quant_mode=input_quant_mode, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Tbias", _op._get_attr_type("Tbias"), "Toutput", + _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "input_quant_mode", + _op.get_attr("input_quant_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMulWithBiasAndDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +QuantizedMatMulWithBiasAndDequantize = tf_export("raw_ops.QuantizedMatMulWithBiasAndDequantize")(_ops.to_raw_op(quantized_mat_mul_with_bias_and_dequantize)) + + +def quantized_mat_mul_with_bias_and_dequantize_eager_fallback(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBiasAndDequantize_Toutput, transpose_a: bool, transpose_b: bool, input_quant_mode: str, name, ctx) -> Annotated[Any, TV_QuantizedMatMulWithBiasAndDequantize_Toutput]: + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, max_freezed_output] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Tbias", _attr_Tbias, "Toutput", + Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, + "input_quant_mode", input_quant_mode) + _result = _execute.execute(b"QuantizedMatMulWithBiasAndDequantize", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMulWithBiasAndDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_QuantizedMatMulWithBiasAndReluOutput = collections.namedtuple( + "QuantizedMatMulWithBiasAndRelu", + ["out", "min_out", "max_out"]) + + +TV_QuantizedMatMulWithBiasAndRelu_T1 = TypeVar("TV_QuantizedMatMulWithBiasAndRelu_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndRelu_T2 = TypeVar("TV_QuantizedMatMulWithBiasAndRelu_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndRelu_Toutput = TypeVar("TV_QuantizedMatMulWithBiasAndRelu_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mat_mul_with_bias_and_relu(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndRelu_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndRelu_T2], bias: Annotated[Any, _atypes.Float32], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMatMulWithBiasAndRelu_Toutput=_dtypes.qint32, transpose_a:bool=False, transpose_b:bool=False, input_quant_mode:str="MIN_FIRST", name=None): + r"""Perform a quantized matrix multiplication of `a` by the matrix `b` with bias +add and relu fusion. + + The inputs must be two-dimensional matrices and 1D bias vector. And the inner + dimension of `a` (after being transposed if `transpose_a` is non-zero) must + match the outer dimension of `b` (after being transposed if `transposed_b` is + non-zero). Then do broadcast add operation with bias values on the matrix + multiplication result. The bias size must match inner dimension of `b`. Then do + relu activation to get non-negative result. + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`. + bias: A `Tensor` of type `float32`. + A 1D bias tensor with size matching with inner dimension of `b` (after being + transposed if `transposed_b` is non-zero). + min_a: A `Tensor` of type `float32`. + The float value that the lowest quantized `a` value represents. + max_a: A `Tensor` of type `float32`. + The float value that the highest quantized `a` value represents. + min_b: A `Tensor` of type `float32`. + The float value that the lowest quantized `b` value represents. + max_b: A `Tensor` of type `float32`. + The float value that the highest quantized `b` value represents. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.qint32`. + transpose_a: An optional `bool`. Defaults to `False`. + If true, `a` is transposed before multiplication. + transpose_b: An optional `bool`. Defaults to `False`. + If true, `b` is transposed before multiplication. + input_quant_mode: An optional `string` from: `"MIN_FIRST", "SCALED"`. Defaults to `"MIN_FIRST"`. + Input data quantization mode. Either MIN_FIRST(default) or SCALED. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, min_out, max_out). + + out: A `Tensor` of type `Toutput`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMulWithBiasAndRelu", name, a, b, bias, min_a, + max_a, min_b, max_b, "Toutput", Toutput, "transpose_a", transpose_a, + "transpose_b", transpose_b, "input_quant_mode", input_quant_mode) + _result = _QuantizedMatMulWithBiasAndReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_with_bias_and_relu_eager_fallback( + a, b, bias, min_a, max_a, min_b, max_b, Toutput=Toutput, + transpose_a=transpose_a, transpose_b=transpose_b, + input_quant_mode=input_quant_mode, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMulWithBiasAndRelu", a=a, b=b, bias=bias, min_a=min_a, + max_a=max_a, min_b=min_b, + max_b=max_b, Toutput=Toutput, + transpose_a=transpose_a, + transpose_b=transpose_b, + input_quant_mode=input_quant_mode, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Toutput", _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "input_quant_mode", + _op.get_attr("input_quant_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMulWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndReluOutput._make(_result) + return _result + +QuantizedMatMulWithBiasAndRelu = tf_export("raw_ops.QuantizedMatMulWithBiasAndRelu")(_ops.to_raw_op(quantized_mat_mul_with_bias_and_relu)) + + +def quantized_mat_mul_with_bias_and_relu_eager_fallback(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndRelu_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndRelu_T2], bias: Annotated[Any, _atypes.Float32], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBiasAndRelu_Toutput, transpose_a: bool, transpose_b: bool, input_quant_mode: str, name, ctx): + if Toutput is None: + Toutput = _dtypes.qint32 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + bias = _ops.convert_to_tensor(bias, _dtypes.float32) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + _inputs_flat = [a, b, bias, min_a, max_a, min_b, max_b] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Toutput", Toutput, "transpose_a", + transpose_a, "transpose_b", transpose_b, "input_quant_mode", + input_quant_mode) + _result = _execute.execute(b"QuantizedMatMulWithBiasAndRelu", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMulWithBiasAndRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndReluOutput._make(_result) + return _result + +_QuantizedMatMulWithBiasAndReluAndRequantizeOutput = collections.namedtuple( + "QuantizedMatMulWithBiasAndReluAndRequantize", + ["out", "min_out", "max_out"]) + + +TV_QuantizedMatMulWithBiasAndReluAndRequantize_T1 = TypeVar("TV_QuantizedMatMulWithBiasAndReluAndRequantize_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndReluAndRequantize_T2 = TypeVar("TV_QuantizedMatMulWithBiasAndReluAndRequantize_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndReluAndRequantize_Tbias = TypeVar("TV_QuantizedMatMulWithBiasAndReluAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedMatMulWithBiasAndReluAndRequantize_Toutput = TypeVar("TV_QuantizedMatMulWithBiasAndReluAndRequantize_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mat_mul_with_bias_and_relu_and_requantize(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMatMulWithBiasAndReluAndRequantize_Toutput=_dtypes.quint8, transpose_a:bool=False, transpose_b:bool=False, input_quant_mode:str="MIN_FIRST", name=None): + r"""Perform a quantized matrix multiplication of `a` by the matrix `b` with bias +add and relu and requantize fusion. + + The inputs must be two-dimensional matrices and 1D bias vector. And the inner + dimension of `a` (after being transposed if `transpose_a` is non-zero) must + match the outer dimension of `b` (after being transposed if `transposed_b` is + non-zero). Then do broadcast add operation with bias values on the matrix + multiplication result. The bias size must match inner dimension of `b`. Then do + relu activation to get non-negative result. Then do requantize operation to get + final uint8 result. + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied. Must be a two-dimensional tensor of type `quint8`. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + A matrix to be multiplied and must be a two-dimensional tensor of type `qint8`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + A 1D bias tensor with size matching with inner dimension of `b` (after being + transposed if `transposed_b` is non-zero). + min_a: A `Tensor` of type `float32`. + The float value that the lowest quantized `a` value represents. + max_a: A `Tensor` of type `float32`. + The float value that the highest quantized `a` value represents. + min_b: A `Tensor` of type `float32`. + The float value that the lowest quantized `b` value represents. + max_b: A `Tensor` of type `float32`. + The float value that the highest quantized `b` value represents. + min_freezed_output: A `Tensor` of type `float32`. + The float value that the highest quantized output value after requantize. + max_freezed_output: A `Tensor` of type `float32`. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + transpose_a: An optional `bool`. Defaults to `False`. + If true, `a` is transposed before multiplication. + transpose_b: An optional `bool`. Defaults to `False`. + If true, `b` is transposed before multiplication. + input_quant_mode: An optional `string` from: `"MIN_FIRST", "SCALED"`. Defaults to `"MIN_FIRST"`. + Input data quantization mode. Either MIN_FIRST(default) or SCALED. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, min_out, max_out). + + out: A `Tensor` of type `Toutput`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMulWithBiasAndReluAndRequantize", name, a, b, bias, + min_a, max_a, min_b, max_b, min_freezed_output, max_freezed_output, + "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", + transpose_b, "input_quant_mode", input_quant_mode) + _result = _QuantizedMatMulWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_with_bias_and_relu_and_requantize_eager_fallback( + a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, + max_freezed_output, Toutput=Toutput, transpose_a=transpose_a, + transpose_b=transpose_b, input_quant_mode=input_quant_mode, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.quint8 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMulWithBiasAndReluAndRequantize", a=a, b=b, bias=bias, + min_a=min_a, + max_a=max_a, + min_b=min_b, + max_b=max_b, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + Toutput=Toutput, + transpose_a=transpose_a, + transpose_b=transpose_b, + input_quant_mode=input_quant_mode, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Tbias", _op._get_attr_type("Tbias"), "Toutput", + _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "input_quant_mode", + _op.get_attr("input_quant_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMulWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +QuantizedMatMulWithBiasAndReluAndRequantize = tf_export("raw_ops.QuantizedMatMulWithBiasAndReluAndRequantize")(_ops.to_raw_op(quantized_mat_mul_with_bias_and_relu_and_requantize)) + + +def quantized_mat_mul_with_bias_and_relu_and_requantize_eager_fallback(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndReluAndRequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBiasAndReluAndRequantize_Toutput, transpose_a: bool, transpose_b: bool, input_quant_mode: str, name, ctx): + if Toutput is None: + Toutput = _dtypes.quint8 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, max_freezed_output] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Tbias", _attr_Tbias, "Toutput", + Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, + "input_quant_mode", input_quant_mode) + _result = _execute.execute(b"QuantizedMatMulWithBiasAndReluAndRequantize", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMulWithBiasAndReluAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndReluAndRequantizeOutput._make(_result) + return _result + +_QuantizedMatMulWithBiasAndRequantizeOutput = collections.namedtuple( + "QuantizedMatMulWithBiasAndRequantize", + ["out", "min_out", "max_out"]) + + +TV_QuantizedMatMulWithBiasAndRequantize_T1 = TypeVar("TV_QuantizedMatMulWithBiasAndRequantize_T1", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndRequantize_T2 = TypeVar("TV_QuantizedMatMulWithBiasAndRequantize_T2", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedMatMulWithBiasAndRequantize_Tbias = TypeVar("TV_QuantizedMatMulWithBiasAndRequantize_Tbias", _atypes.Float32, _atypes.QInt32) +TV_QuantizedMatMulWithBiasAndRequantize_Toutput = TypeVar("TV_QuantizedMatMulWithBiasAndRequantize_Toutput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_mat_mul_with_bias_and_requantize(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput:TV_QuantizedMatMulWithBiasAndRequantize_Toutput=_dtypes.quint8, transpose_a:bool=False, transpose_b:bool=False, input_quant_mode:str="MIN_FIRST", name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + b: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + bias: A `Tensor`. Must be one of the following types: `float32`, `qint32`. + min_a: A `Tensor` of type `float32`. + max_a: A `Tensor` of type `float32`. + min_b: A `Tensor` of type `float32`. + max_b: A `Tensor` of type `float32`. + min_freezed_output: A `Tensor` of type `float32`. + max_freezed_output: A `Tensor` of type `float32`. + Toutput: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + transpose_a: An optional `bool`. Defaults to `False`. + transpose_b: An optional `bool`. Defaults to `False`. + input_quant_mode: An optional `string` from: `"MIN_FIRST", "SCALED"`. Defaults to `"MIN_FIRST"`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out, min_out, max_out). + + out: A `Tensor` of type `Toutput`. + min_out: A `Tensor` of type `float32`. + max_out: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMatMulWithBiasAndRequantize", name, a, b, bias, min_a, + max_a, min_b, max_b, min_freezed_output, max_freezed_output, + "Toutput", Toutput, "transpose_a", transpose_a, "transpose_b", + transpose_b, "input_quant_mode", input_quant_mode) + _result = _QuantizedMatMulWithBiasAndRequantizeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_mat_mul_with_bias_and_requantize_eager_fallback( + a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, + max_freezed_output, Toutput=Toutput, transpose_a=transpose_a, + transpose_b=transpose_b, input_quant_mode=input_quant_mode, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Toutput is None: + Toutput = _dtypes.quint8 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMatMulWithBiasAndRequantize", a=a, b=b, bias=bias, + min_a=min_a, max_a=max_a, + min_b=min_b, max_b=max_b, + min_freezed_output=min_freezed_output, + max_freezed_output=max_freezed_output, + Toutput=Toutput, + transpose_a=transpose_a, + transpose_b=transpose_b, + input_quant_mode=input_quant_mode, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T1", _op._get_attr_type("T1"), "T2", _op._get_attr_type("T2"), + "Tbias", _op._get_attr_type("Tbias"), "Toutput", + _op._get_attr_type("Toutput"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "input_quant_mode", + _op.get_attr("input_quant_mode")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMatMulWithBiasAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndRequantizeOutput._make(_result) + return _result + +QuantizedMatMulWithBiasAndRequantize = tf_export("raw_ops.QuantizedMatMulWithBiasAndRequantize")(_ops.to_raw_op(quantized_mat_mul_with_bias_and_requantize)) + + +def quantized_mat_mul_with_bias_and_requantize_eager_fallback(a: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_T1], b: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_T2], bias: Annotated[Any, TV_QuantizedMatMulWithBiasAndRequantize_Tbias], min_a: Annotated[Any, _atypes.Float32], max_a: Annotated[Any, _atypes.Float32], min_b: Annotated[Any, _atypes.Float32], max_b: Annotated[Any, _atypes.Float32], min_freezed_output: Annotated[Any, _atypes.Float32], max_freezed_output: Annotated[Any, _atypes.Float32], Toutput: TV_QuantizedMatMulWithBiasAndRequantize_Toutput, transpose_a: bool, transpose_b: bool, input_quant_mode: str, name, ctx): + if Toutput is None: + Toutput = _dtypes.quint8 + Toutput = _execute.make_type(Toutput, "Toutput") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if input_quant_mode is None: + input_quant_mode = "MIN_FIRST" + input_quant_mode = _execute.make_str(input_quant_mode, "input_quant_mode") + _attr_T1, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_T2, (b,) = _execute.args_to_matching_eager([b], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + _attr_Tbias, (bias,) = _execute.args_to_matching_eager([bias], ctx, [_dtypes.float32, _dtypes.qint32, ]) + min_a = _ops.convert_to_tensor(min_a, _dtypes.float32) + max_a = _ops.convert_to_tensor(max_a, _dtypes.float32) + min_b = _ops.convert_to_tensor(min_b, _dtypes.float32) + max_b = _ops.convert_to_tensor(max_b, _dtypes.float32) + min_freezed_output = _ops.convert_to_tensor(min_freezed_output, _dtypes.float32) + max_freezed_output = _ops.convert_to_tensor(max_freezed_output, _dtypes.float32) + _inputs_flat = [a, b, bias, min_a, max_a, min_b, max_b, min_freezed_output, max_freezed_output] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "Tbias", _attr_Tbias, "Toutput", + Toutput, "transpose_a", transpose_a, "transpose_b", transpose_b, + "input_quant_mode", input_quant_mode) + _result = _execute.execute(b"QuantizedMatMulWithBiasAndRequantize", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMatMulWithBiasAndRequantize", _inputs_flat, _attrs, _result) + _result = _QuantizedMatMulWithBiasAndRequantizeOutput._make(_result) + return _result + +_QuantizedMaxPoolOutput = collections.namedtuple( + "QuantizedMaxPool", + ["output", "min_output", "max_output"]) + + +TV_QuantizedMaxPool_T = TypeVar("TV_QuantizedMaxPool_T", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_max_pool(input: Annotated[Any, TV_QuantizedMaxPool_T], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], ksize, strides, padding: str, name=None): + r"""Produces the max pool of the input tensor for quantized types. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + The 4D (batch x rows x cols x depth) Tensor to MaxReduce over. + min_input: A `Tensor` of type `float32`. + The float value that the lowest quantized input value represents. + max_input: A `Tensor` of type `float32`. + The float value that the highest quantized input value represents. + ksize: A list of `ints`. + The size of the window for each dimension of the input tensor. + The length must be 4 to match the number of dimensions of the input. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + tensor. The length must be 4 to match the number of dimensions of the input. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, min_output, max_output). + + output: A `Tensor`. Has the same type as `input`. + min_output: A `Tensor` of type `float32`. + max_output: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedMaxPool", name, input, min_input, max_input, "ksize", + ksize, "strides", strides, "padding", padding) + _result = _QuantizedMaxPoolOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_max_pool_eager_fallback( + input, min_input, max_input, ksize=ksize, strides=strides, + padding=padding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'quantized_max_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_max_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedMaxPool", input=input, min_input=min_input, + max_input=max_input, ksize=ksize, strides=strides, + padding=padding, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "ksize", _op.get_attr("ksize"), + "strides", _op.get_attr("strides"), "padding", + _op.get_attr("padding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedMaxPool", _inputs_flat, _attrs, _result) + _result = _QuantizedMaxPoolOutput._make(_result) + return _result + +QuantizedMaxPool = tf_export("raw_ops.QuantizedMaxPool")(_ops.to_raw_op(quantized_max_pool)) + + +def quantized_max_pool_eager_fallback(input: Annotated[Any, TV_QuantizedMaxPool_T], min_input: Annotated[Any, _atypes.Float32], max_input: Annotated[Any, _atypes.Float32], ksize, strides, padding: str, name, ctx): + if not isinstance(ksize, (list, tuple)): + raise TypeError( + "Expected list for 'ksize' argument to " + "'quantized_max_pool' Op, not %r." % ksize) + ksize = [_execute.make_int(_i, "ksize") for _i in ksize] + if not isinstance(strides, (list, tuple)): + raise TypeError( + "Expected list for 'strides' argument to " + "'quantized_max_pool' Op, not %r." % strides) + strides = [_execute.make_int(_i, "strides") for _i in strides] + padding = _execute.make_str(padding, "padding") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_input = _ops.convert_to_tensor(min_input, _dtypes.float32) + max_input = _ops.convert_to_tensor(max_input, _dtypes.float32) + _inputs_flat = [input, min_input, max_input] + _attrs = ("T", _attr_T, "ksize", ksize, "strides", strides, "padding", + padding) + _result = _execute.execute(b"QuantizedMaxPool", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedMaxPool", _inputs_flat, _attrs, _result) + _result = _QuantizedMaxPoolOutput._make(_result) + return _result + +_QuantizedReluOutput = collections.namedtuple( + "QuantizedRelu", + ["activations", "min_activations", "max_activations"]) + + +TV_QuantizedRelu_Tinput = TypeVar("TV_QuantizedRelu_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedRelu_out_type = TypeVar("TV_QuantizedRelu_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_relu(features: Annotated[Any, TV_QuantizedRelu_Tinput], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type:TV_QuantizedRelu_out_type=_dtypes.quint8, name=None): + r"""Computes Quantized Rectified Linear: `max(features, 0)` + + Args: + features: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_features: A `Tensor` of type `float32`. + The float value that the lowest quantized value represents. + max_features: A `Tensor` of type `float32`. + The float value that the highest quantized value represents. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (activations, min_activations, max_activations). + + activations: A `Tensor` of type `out_type`. + min_activations: A `Tensor` of type `float32`. + max_activations: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedRelu", name, features, min_features, max_features, + "out_type", out_type) + _result = _QuantizedReluOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_relu_eager_fallback( + features, min_features, max_features, out_type=out_type, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedRelu", features=features, min_features=min_features, + max_features=max_features, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedReluOutput._make(_result) + return _result + +QuantizedRelu = tf_export("raw_ops.QuantizedRelu")(_ops.to_raw_op(quantized_relu)) + + +def quantized_relu_eager_fallback(features: Annotated[Any, TV_QuantizedRelu_Tinput], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedRelu_out_type, name, ctx): + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _attr_Tinput, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_features = _ops.convert_to_tensor(min_features, _dtypes.float32) + max_features = _ops.convert_to_tensor(max_features, _dtypes.float32) + _inputs_flat = [features, min_features, max_features] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) + _result = _execute.execute(b"QuantizedRelu", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedRelu", _inputs_flat, _attrs, _result) + _result = _QuantizedReluOutput._make(_result) + return _result + +_QuantizedRelu6Output = collections.namedtuple( + "QuantizedRelu6", + ["activations", "min_activations", "max_activations"]) + + +TV_QuantizedRelu6_Tinput = TypeVar("TV_QuantizedRelu6_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedRelu6_out_type = TypeVar("TV_QuantizedRelu6_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_relu6(features: Annotated[Any, TV_QuantizedRelu6_Tinput], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type:TV_QuantizedRelu6_out_type=_dtypes.quint8, name=None): + r"""Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)` + + Args: + features: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + min_features: A `Tensor` of type `float32`. + The float value that the lowest quantized value represents. + max_features: A `Tensor` of type `float32`. + The float value that the highest quantized value represents. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (activations, min_activations, max_activations). + + activations: A `Tensor` of type `out_type`. + min_activations: A `Tensor` of type `float32`. + max_activations: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedRelu6", name, features, min_features, max_features, + "out_type", out_type) + _result = _QuantizedRelu6Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_relu6_eager_fallback( + features, min_features, max_features, out_type=out_type, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedRelu6", features=features, min_features=min_features, + max_features=max_features, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedRelu6", _inputs_flat, _attrs, _result) + _result = _QuantizedRelu6Output._make(_result) + return _result + +QuantizedRelu6 = tf_export("raw_ops.QuantizedRelu6")(_ops.to_raw_op(quantized_relu6)) + + +def quantized_relu6_eager_fallback(features: Annotated[Any, TV_QuantizedRelu6_Tinput], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedRelu6_out_type, name, ctx): + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _attr_Tinput, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + min_features = _ops.convert_to_tensor(min_features, _dtypes.float32) + max_features = _ops.convert_to_tensor(max_features, _dtypes.float32) + _inputs_flat = [features, min_features, max_features] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) + _result = _execute.execute(b"QuantizedRelu6", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedRelu6", _inputs_flat, _attrs, _result) + _result = _QuantizedRelu6Output._make(_result) + return _result + +_QuantizedReluXOutput = collections.namedtuple( + "QuantizedReluX", + ["activations", "min_activations", "max_activations"]) + + +TV_QuantizedReluX_Tinput = TypeVar("TV_QuantizedReluX_Tinput", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) +TV_QuantizedReluX_out_type = TypeVar("TV_QuantizedReluX_out_type", _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8) + +def quantized_relu_x(features: Annotated[Any, TV_QuantizedReluX_Tinput], max_value: Annotated[Any, _atypes.Float32], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type:TV_QuantizedReluX_out_type=_dtypes.quint8, name=None): + r"""Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)` + + Args: + features: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. + max_value: A `Tensor` of type `float32`. + min_features: A `Tensor` of type `float32`. + The float value that the lowest quantized value represents. + max_features: A `Tensor` of type `float32`. + The float value that the highest quantized value represents. + out_type: An optional `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to `tf.quint8`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (activations, min_activations, max_activations). + + activations: A `Tensor` of type `out_type`. + min_activations: A `Tensor` of type `float32`. + max_activations: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "QuantizedReluX", name, features, max_value, min_features, + max_features, "out_type", out_type) + _result = _QuantizedReluXOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return quantized_relu_x_eager_fallback( + features, max_value, min_features, max_features, out_type=out_type, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "QuantizedReluX", features=features, max_value=max_value, + min_features=min_features, + max_features=max_features, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tinput", _op._get_attr_type("Tinput"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "QuantizedReluX", _inputs_flat, _attrs, _result) + _result = _QuantizedReluXOutput._make(_result) + return _result + +QuantizedReluX = tf_export("raw_ops.QuantizedReluX")(_ops.to_raw_op(quantized_relu_x)) + + +def quantized_relu_x_eager_fallback(features: Annotated[Any, TV_QuantizedReluX_Tinput], max_value: Annotated[Any, _atypes.Float32], min_features: Annotated[Any, _atypes.Float32], max_features: Annotated[Any, _atypes.Float32], out_type: TV_QuantizedReluX_out_type, name, ctx): + if out_type is None: + out_type = _dtypes.quint8 + out_type = _execute.make_type(out_type, "out_type") + _attr_Tinput, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.qint16, _dtypes.quint16, ]) + max_value = _ops.convert_to_tensor(max_value, _dtypes.float32) + min_features = _ops.convert_to_tensor(min_features, _dtypes.float32) + max_features = _ops.convert_to_tensor(max_features, _dtypes.float32) + _inputs_flat = [features, max_value, min_features, max_features] + _attrs = ("Tinput", _attr_Tinput, "out_type", out_type) + _result = _execute.execute(b"QuantizedReluX", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "QuantizedReluX", _inputs_flat, _attrs, _result) + _result = _QuantizedReluXOutput._make(_result) + return _result + + +TV_Relu_T = TypeVar("TV_Relu_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.relu') +def relu(features: Annotated[Any, TV_Relu_T], name=None) -> Annotated[Any, TV_Relu_T]: + r"""Computes rectified linear: `max(features, 0)`. + + See: https://en.wikipedia.org/wiki/Rectifier_(neural_networks) + Example usage: + >>> tf.nn.relu([-2., 0., 3.]).numpy() + array([0., 0., 3.], dtype=float32) + + Args: + features: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Relu", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_relu( + (features, name,), None) + if _result is not NotImplemented: + return _result + return relu_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + relu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_relu( + (features, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Relu", features=features, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + relu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Relu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Relu = tf_export("raw_ops.Relu")(_ops.to_raw_op(relu)) +_dispatcher_for_relu = relu._tf_type_based_dispatcher.Dispatch + + +def relu_eager_fallback(features: Annotated[Any, TV_Relu_T], name, ctx) -> Annotated[Any, TV_Relu_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.qint8, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Relu", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Relu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Relu6_T = TypeVar("TV_Relu6_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def relu6(features: Annotated[Any, TV_Relu6_T], name=None) -> Annotated[Any, TV_Relu6_T]: + r"""Computes rectified linear 6: `min(max(features, 0), 6)`. + + Args: + features: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Relu6", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return relu6_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Relu6", features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Relu6", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Relu6 = tf_export("raw_ops.Relu6")(_ops.to_raw_op(relu6)) + + +def relu6_eager_fallback(features: Annotated[Any, TV_Relu6_T], name, ctx) -> Annotated[Any, TV_Relu6_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Relu6", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Relu6", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Relu6Grad_T = TypeVar("TV_Relu6Grad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def relu6_grad(gradients: Annotated[Any, TV_Relu6Grad_T], features: Annotated[Any, TV_Relu6Grad_T], name=None) -> Annotated[Any, TV_Relu6Grad_T]: + r"""Computes rectified linear 6 gradients for a Relu6 operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The backpropagated gradients to the corresponding Relu6 operation. + features: A `Tensor`. Must have the same type as `gradients`. + The features passed as input to the corresponding Relu6 operation, or + its output; using either one produces the same result. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Relu6Grad", name, gradients, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return relu6_grad_eager_fallback( + gradients, features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Relu6Grad", gradients=gradients, features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Relu6Grad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Relu6Grad = tf_export("raw_ops.Relu6Grad")(_ops.to_raw_op(relu6_grad)) + + +def relu6_grad_eager_fallback(gradients: Annotated[Any, TV_Relu6Grad_T], features: Annotated[Any, TV_Relu6Grad_T], name, ctx) -> Annotated[Any, TV_Relu6Grad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, features], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (gradients, features) = _inputs_T + _inputs_flat = [gradients, features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Relu6Grad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Relu6Grad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReluGrad_T = TypeVar("TV_ReluGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def relu_grad(gradients: Annotated[Any, TV_ReluGrad_T], features: Annotated[Any, TV_ReluGrad_T], name=None) -> Annotated[Any, TV_ReluGrad_T]: + r"""Computes rectified linear gradients for a Relu operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + The backpropagated gradients to the corresponding Relu operation. + features: A `Tensor`. Must have the same type as `gradients`. + The features passed as input to the corresponding Relu operation, OR + the outputs of that operation (both work equivalently). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReluGrad", name, gradients, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return relu_grad_eager_fallback( + gradients, features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReluGrad", gradients=gradients, features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReluGrad = tf_export("raw_ops.ReluGrad")(_ops.to_raw_op(relu_grad)) + + +def relu_grad_eager_fallback(gradients: Annotated[Any, TV_ReluGrad_T], features: Annotated[Any, TV_ReluGrad_T], name, ctx) -> Annotated[Any, TV_ReluGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, features], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (gradients, features) = _inputs_T + _inputs_flat = [gradients, features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"ReluGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Selu_T = TypeVar("TV_Selu_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.selu') +def selu(features: Annotated[Any, TV_Selu_T], name=None) -> Annotated[Any, TV_Selu_T]: + r"""Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)` + + if < 0, `scale * features` otherwise. + + To be used together with + `initializer = tf.variance_scaling_initializer(factor=1.0, mode='FAN_IN')`. + For correct dropout, use `tf.contrib.nn.alpha_dropout`. + + See [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Selu", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_selu( + (features, name,), None) + if _result is not NotImplemented: + return _result + return selu_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + selu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_selu( + (features, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Selu", features=features, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + selu, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Selu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Selu = tf_export("raw_ops.Selu")(_ops.to_raw_op(selu)) +_dispatcher_for_selu = selu._tf_type_based_dispatcher.Dispatch + + +def selu_eager_fallback(features: Annotated[Any, TV_Selu_T], name, ctx) -> Annotated[Any, TV_Selu_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Selu", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Selu", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SeluGrad_T = TypeVar("TV_SeluGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def selu_grad(gradients: Annotated[Any, TV_SeluGrad_T], outputs: Annotated[Any, TV_SeluGrad_T], name=None) -> Annotated[Any, TV_SeluGrad_T]: + r"""Computes gradients for the scaled exponential linear (Selu) operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The backpropagated gradients to the corresponding Selu operation. + outputs: A `Tensor`. Must have the same type as `gradients`. + The outputs of the corresponding Selu operation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SeluGrad", name, gradients, outputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return selu_grad_eager_fallback( + gradients, outputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SeluGrad", gradients=gradients, outputs=outputs, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SeluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SeluGrad = tf_export("raw_ops.SeluGrad")(_ops.to_raw_op(selu_grad)) + + +def selu_grad_eager_fallback(gradients: Annotated[Any, TV_SeluGrad_T], outputs: Annotated[Any, TV_SeluGrad_T], name, ctx) -> Annotated[Any, TV_SeluGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, outputs], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (gradients, outputs) = _inputs_T + _inputs_flat = [gradients, outputs] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SeluGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SeluGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Softmax_T = TypeVar("TV_Softmax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def softmax(logits: Annotated[Any, TV_Softmax_T], name=None) -> Annotated[Any, TV_Softmax_T]: + r"""Computes softmax activations. + + For each batch `i` and class `j` we have + + $$softmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))$$ + + Args: + logits: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + 2-D with shape `[batch_size, num_classes]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `logits`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Softmax", name, logits) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return softmax_eager_fallback( + logits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Softmax", logits=logits, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Softmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Softmax = tf_export("raw_ops.Softmax")(_ops.to_raw_op(softmax)) + + +def softmax_eager_fallback(logits: Annotated[Any, TV_Softmax_T], name, ctx) -> Annotated[Any, TV_Softmax_T]: + _attr_T, (logits,) = _execute.args_to_matching_eager([logits], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [logits] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Softmax", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Softmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SoftmaxCrossEntropyWithLogitsOutput = collections.namedtuple( + "SoftmaxCrossEntropyWithLogits", + ["loss", "backprop"]) + + +TV_SoftmaxCrossEntropyWithLogits_T = TypeVar("TV_SoftmaxCrossEntropyWithLogits_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def softmax_cross_entropy_with_logits(features: Annotated[Any, TV_SoftmaxCrossEntropyWithLogits_T], labels: Annotated[Any, TV_SoftmaxCrossEntropyWithLogits_T], name=None): + r"""Computes softmax cross entropy cost and gradients to backpropagate. + + Inputs are the logits, not probabilities. + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + batch_size x num_classes matrix + labels: A `Tensor`. Must have the same type as `features`. + batch_size x num_classes matrix + The caller must ensure that each batch of labels represents a valid + probability distribution. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (loss, backprop). + + loss: A `Tensor`. Has the same type as `features`. + backprop: A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SoftmaxCrossEntropyWithLogits", name, features, labels) + _result = _SoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return softmax_cross_entropy_with_logits_eager_fallback( + features, labels, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SoftmaxCrossEntropyWithLogits", features=features, labels=labels, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SoftmaxCrossEntropyWithLogits", _inputs_flat, _attrs, _result) + _result = _SoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + +SoftmaxCrossEntropyWithLogits = tf_export("raw_ops.SoftmaxCrossEntropyWithLogits")(_ops.to_raw_op(softmax_cross_entropy_with_logits)) + + +def softmax_cross_entropy_with_logits_eager_fallback(features: Annotated[Any, TV_SoftmaxCrossEntropyWithLogits_T], labels: Annotated[Any, TV_SoftmaxCrossEntropyWithLogits_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([features, labels], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (features, labels) = _inputs_T + _inputs_flat = [features, labels] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SoftmaxCrossEntropyWithLogits", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SoftmaxCrossEntropyWithLogits", _inputs_flat, _attrs, _result) + _result = _SoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + + +TV_Softplus_T = TypeVar("TV_Softplus_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def softplus(features: Annotated[Any, TV_Softplus_T], name=None) -> Annotated[Any, TV_Softplus_T]: + r"""TODO: add doc. + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Softplus", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return softplus_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Softplus", features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Softplus", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Softplus = tf_export("raw_ops.Softplus")(_ops.to_raw_op(softplus)) + + +def softplus_eager_fallback(features: Annotated[Any, TV_Softplus_T], name, ctx) -> Annotated[Any, TV_Softplus_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Softplus", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Softplus", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SoftplusGrad_T = TypeVar("TV_SoftplusGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def softplus_grad(gradients: Annotated[Any, TV_SoftplusGrad_T], features: Annotated[Any, TV_SoftplusGrad_T], name=None) -> Annotated[Any, TV_SoftplusGrad_T]: + r"""Computes softplus gradients for a softplus operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The backpropagated gradients to the corresponding softplus operation. + features: A `Tensor`. Must have the same type as `gradients`. + The features passed as input to the corresponding softplus operation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SoftplusGrad", name, gradients, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return softplus_grad_eager_fallback( + gradients, features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SoftplusGrad", gradients=gradients, features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SoftplusGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SoftplusGrad = tf_export("raw_ops.SoftplusGrad")(_ops.to_raw_op(softplus_grad)) + + +def softplus_grad_eager_fallback(gradients: Annotated[Any, TV_SoftplusGrad_T], features: Annotated[Any, TV_SoftplusGrad_T], name, ctx) -> Annotated[Any, TV_SoftplusGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (gradients, features) = _inputs_T + _inputs_flat = [gradients, features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SoftplusGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SoftplusGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Softsign_T = TypeVar("TV_Softsign_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('nn.softsign', 'math.softsign') +def softsign(features: Annotated[Any, TV_Softsign_T], name=None) -> Annotated[Any, TV_Softsign_T]: + r"""Computes softsign: `features / (abs(features) + 1)`. + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Softsign", name, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_softsign( + (features, name,), None) + if _result is not NotImplemented: + return _result + return softsign_eager_fallback( + features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + softsign, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_softsign( + (features, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Softsign", features=features, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + softsign, (), dict(features=features, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Softsign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Softsign = tf_export("raw_ops.Softsign")(_ops.to_raw_op(softsign)) +_dispatcher_for_softsign = softsign._tf_type_based_dispatcher.Dispatch + + +def softsign_eager_fallback(features: Annotated[Any, TV_Softsign_T], name, ctx) -> Annotated[Any, TV_Softsign_T]: + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Softsign", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Softsign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SoftsignGrad_T = TypeVar("TV_SoftsignGrad_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def softsign_grad(gradients: Annotated[Any, TV_SoftsignGrad_T], features: Annotated[Any, TV_SoftsignGrad_T], name=None) -> Annotated[Any, TV_SoftsignGrad_T]: + r"""Computes softsign gradients for a softsign operation. + + Args: + gradients: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The backpropagated gradients to the corresponding softsign operation. + features: A `Tensor`. Must have the same type as `gradients`. + The features passed as input to the corresponding softsign operation. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `gradients`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SoftsignGrad", name, gradients, features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return softsign_grad_eager_fallback( + gradients, features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SoftsignGrad", gradients=gradients, features=features, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SoftsignGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SoftsignGrad = tf_export("raw_ops.SoftsignGrad")(_ops.to_raw_op(softsign_grad)) + + +def softsign_grad_eager_fallback(gradients: Annotated[Any, TV_SoftsignGrad_T], features: Annotated[Any, TV_SoftsignGrad_T], name, ctx) -> Annotated[Any, TV_SoftsignGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([gradients, features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (gradients, features) = _inputs_T + _inputs_flat = [gradients, features] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SoftsignGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SoftsignGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseSoftmaxCrossEntropyWithLogitsOutput = collections.namedtuple( + "SparseSoftmaxCrossEntropyWithLogits", + ["loss", "backprop"]) + + +TV_SparseSoftmaxCrossEntropyWithLogits_T = TypeVar("TV_SparseSoftmaxCrossEntropyWithLogits_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_SparseSoftmaxCrossEntropyWithLogits_Tlabels = TypeVar("TV_SparseSoftmaxCrossEntropyWithLogits_Tlabels", _atypes.Int32, _atypes.Int64) + +def sparse_softmax_cross_entropy_with_logits(features: Annotated[Any, TV_SparseSoftmaxCrossEntropyWithLogits_T], labels: Annotated[Any, TV_SparseSoftmaxCrossEntropyWithLogits_Tlabels], name=None): + r"""Computes softmax cross entropy cost and gradients to backpropagate. + + Unlike `SoftmaxCrossEntropyWithLogits`, this operation does not accept + a matrix of label probabilities, but rather a single label per row + of features. This label is considered to have probability 1.0 for the + given row. + + Inputs are the logits, not probabilities. + + Args: + features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + batch_size x num_classes matrix + labels: A `Tensor`. Must be one of the following types: `int32`, `int64`. + batch_size vector with values in [0, num_classes). + This is the label for the given minibatch entry. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (loss, backprop). + + loss: A `Tensor`. Has the same type as `features`. + backprop: A `Tensor`. Has the same type as `features`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSoftmaxCrossEntropyWithLogits", name, features, labels) + _result = _SparseSoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_softmax_cross_entropy_with_logits_eager_fallback( + features, labels, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSoftmaxCrossEntropyWithLogits", features=features, + labels=labels, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tlabels", + _op._get_attr_type("Tlabels")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSoftmaxCrossEntropyWithLogits", _inputs_flat, _attrs, _result) + _result = _SparseSoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + +SparseSoftmaxCrossEntropyWithLogits = tf_export("raw_ops.SparseSoftmaxCrossEntropyWithLogits")(_ops.to_raw_op(sparse_softmax_cross_entropy_with_logits)) + + +def sparse_softmax_cross_entropy_with_logits_eager_fallback(features: Annotated[Any, TV_SparseSoftmaxCrossEntropyWithLogits_T], labels: Annotated[Any, TV_SparseSoftmaxCrossEntropyWithLogits_Tlabels], name, ctx): + _attr_T, (features,) = _execute.args_to_matching_eager([features], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + _attr_Tlabels, (labels,) = _execute.args_to_matching_eager([labels], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [features, labels] + _attrs = ("T", _attr_T, "Tlabels", _attr_Tlabels) + _result = _execute.execute(b"SparseSoftmaxCrossEntropyWithLogits", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSoftmaxCrossEntropyWithLogits", _inputs_flat, _attrs, _result) + _result = _SparseSoftmaxCrossEntropyWithLogitsOutput._make(_result) + return _result + +_TopKOutput = collections.namedtuple( + "TopK", + ["values", "indices"]) + + +TV_TopK_T = TypeVar("TV_TopK_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def top_k(input: Annotated[Any, TV_TopK_T], k: int, sorted:bool=True, name=None): + r"""Finds values and indices of the `k` largest elements for the last dimension. + + If the input is a vector (rank-1), finds the `k` largest entries in the vector + and outputs their values and indices as vectors. Thus `values[j]` is the + `j`-th largest entry in `input`, and its index is `indices[j]`. + + For matrices (resp. higher rank input), computes the top `k` entries in each + row (resp. vector along the last dimension). Thus, + + values.shape = indices.shape = input.shape[:-1] + [k] + + If two elements are equal, the lower-index element appears first. + + If `k` varies dynamically, use `TopKV2` below. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D or higher with last dimension at least `k`. + k: An `int` that is `>= 0`. + Number of top elements to look for along the last dimension (along each + row for matrices). + sorted: An optional `bool`. Defaults to `True`. + If true the resulting `k` elements will be sorted by the values in + descending order. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (values, indices). + + values: A `Tensor`. Has the same type as `input`. + indices: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TopK", name, input, "k", k, "sorted", sorted) + _result = _TopKOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return top_k_eager_fallback( + input, k=k, sorted=sorted, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + k = _execute.make_int(k, "k") + if sorted is None: + sorted = True + sorted = _execute.make_bool(sorted, "sorted") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TopK", input=input, k=k, sorted=sorted, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("k", _op._get_attr_int("k"), "sorted", + _op._get_attr_bool("sorted"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TopK", _inputs_flat, _attrs, _result) + _result = _TopKOutput._make(_result) + return _result + +TopK = tf_export("raw_ops.TopK")(_ops.to_raw_op(top_k)) + + +def top_k_eager_fallback(input: Annotated[Any, TV_TopK_T], k: int, sorted: bool, name, ctx): + k = _execute.make_int(k, "k") + if sorted is None: + sorted = True + sorted = _execute.make_bool(sorted, "sorted") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _inputs_flat = [input] + _attrs = ("k", k, "sorted", sorted, "T", _attr_T) + _result = _execute.execute(b"TopK", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TopK", _inputs_flat, _attrs, _result) + _result = _TopKOutput._make(_result) + return _result + +_TopKV2Output = collections.namedtuple( + "TopKV2", + ["values", "indices"]) + + +TV_TopKV2_T = TypeVar("TV_TopKV2_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_TopKV2_Tk = TypeVar("TV_TopKV2_Tk", _atypes.Int16, _atypes.Int32, _atypes.Int64) +TV_TopKV2_index_type = TypeVar("TV_TopKV2_index_type", _atypes.Int16, _atypes.Int32, _atypes.Int64) + +def top_kv2(input: Annotated[Any, TV_TopKV2_T], k: Annotated[Any, TV_TopKV2_Tk], sorted:bool=True, index_type:TV_TopKV2_index_type=_dtypes.int32, name=None): + r"""Finds values and indices of the `k` largest elements for the last dimension. + + If the input is a vector (rank-1), finds the `k` largest entries in the vector + and outputs their values and indices as vectors. Thus `values[j]` is the + `j`-th largest entry in `input`, and its index is `indices[j]`. + + For matrices (resp. higher rank input), computes the top `k` entries in each + row (resp. vector along the last dimension). Thus, + + values.shape = indices.shape = input.shape[:-1] + [k] + + If two elements are equal, the lower-index element appears first. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D or higher with last dimension at least `k`. + k: A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. + 0-D. Number of top elements to look for along the last dimension (along each + row for matrices). + sorted: An optional `bool`. Defaults to `True`. + If true the resulting `k` elements will be sorted by the values in + descending order. + index_type: An optional `tf.DType` from: `tf.int16, tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (values, indices). + + values: A `Tensor`. Has the same type as `input`. + indices: A `Tensor` of type `index_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TopKV2", name, input, k, "sorted", sorted, "index_type", + index_type) + _result = _TopKV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return top_kv2_eager_fallback( + input, k, sorted=sorted, index_type=index_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if sorted is None: + sorted = True + sorted = _execute.make_bool(sorted, "sorted") + if index_type is None: + index_type = _dtypes.int32 + index_type = _execute.make_type(index_type, "index_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TopKV2", input=input, k=k, sorted=sorted, index_type=index_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sorted", _op._get_attr_bool("sorted"), "T", + _op._get_attr_type("T"), "Tk", _op._get_attr_type("Tk"), + "index_type", _op._get_attr_type("index_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TopKV2", _inputs_flat, _attrs, _result) + _result = _TopKV2Output._make(_result) + return _result + +TopKV2 = tf_export("raw_ops.TopKV2")(_ops.to_raw_op(top_kv2)) + + +def top_kv2_eager_fallback(input: Annotated[Any, TV_TopKV2_T], k: Annotated[Any, TV_TopKV2_Tk], sorted: bool, index_type: TV_TopKV2_index_type, name, ctx): + if sorted is None: + sorted = True + sorted = _execute.make_bool(sorted, "sorted") + if index_type is None: + index_type = _dtypes.int32 + index_type = _execute.make_type(index_type, "index_type") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tk, (k,) = _execute.args_to_matching_eager([k], ctx, [_dtypes.int16, _dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _inputs_flat = [input, k] + _attrs = ("sorted", sorted, "T", _attr_T, "Tk", _attr_Tk, "index_type", + index_type) + _result = _execute.execute(b"TopKV2", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TopKV2", _inputs_flat, _attrs, _result) + _result = _TopKV2Output._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_optional_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_optional_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9e5ca47d4381eb3c50da1917a7f3bfd099236d88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_optional_ops.py @@ -0,0 +1,262 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def optional_from_value(components, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Constructs an Optional variant from a tuple of tensors. + + Args: + components: A list of `Tensor` objects. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptionalFromValue", name, components) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optional_from_value_eager_fallback( + components, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptionalFromValue", components=components, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Toutput_types", _op.get_attr("Toutput_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptionalFromValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptionalFromValue = tf_export("raw_ops.OptionalFromValue")(_ops.to_raw_op(optional_from_value)) + + +def optional_from_value_eager_fallback(components, name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_Toutput_types, components = _execute.convert_to_mixed_eager_tensors(components, ctx) + _inputs_flat = list(components) + _attrs = ("Toutput_types", _attr_Toutput_types) + _result = _execute.execute(b"OptionalFromValue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptionalFromValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def optional_get_value(optional: Annotated[Any, _atypes.Variant], output_types, output_shapes, name=None): + r"""Returns the value stored in an Optional variant or raises an error if none exists. + + Args: + optional: A `Tensor` of type `variant`. + output_types: A list of `tf.DTypes` that has length `>= 1`. + output_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`) that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `output_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptionalGetValue", name, optional, "output_types", + output_types, "output_shapes", output_shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optional_get_value_eager_fallback( + optional, output_types=output_types, output_shapes=output_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optional_get_value' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optional_get_value' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptionalGetValue", optional=optional, output_types=output_types, + output_shapes=output_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("output_types", _op.get_attr("output_types"), "output_shapes", + _op.get_attr("output_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptionalGetValue", _inputs_flat, _attrs, _result) + return _result + +OptionalGetValue = tf_export("raw_ops.OptionalGetValue")(_ops.to_raw_op(optional_get_value)) + + +def optional_get_value_eager_fallback(optional: Annotated[Any, _atypes.Variant], output_types, output_shapes, name, ctx): + if not isinstance(output_types, (list, tuple)): + raise TypeError( + "Expected list for 'output_types' argument to " + "'optional_get_value' Op, not %r." % output_types) + output_types = [_execute.make_type(_t, "output_types") for _t in output_types] + if not isinstance(output_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'output_shapes' argument to " + "'optional_get_value' Op, not %r." % output_shapes) + output_shapes = [_execute.make_shape(_s, "output_shapes") for _s in output_shapes] + optional = _ops.convert_to_tensor(optional, _dtypes.variant) + _inputs_flat = [optional] + _attrs = ("output_types", output_types, "output_shapes", output_shapes) + _result = _execute.execute(b"OptionalGetValue", len(output_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptionalGetValue", _inputs_flat, _attrs, _result) + return _result + + +def optional_has_value(optional: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Returns true if and only if the given Optional variant has a value. + + Args: + optional: A `Tensor` of type `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptionalHasValue", name, optional) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optional_has_value_eager_fallback( + optional, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptionalHasValue", optional=optional, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptionalHasValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptionalHasValue = tf_export("raw_ops.OptionalHasValue")(_ops.to_raw_op(optional_has_value)) + + +def optional_has_value_eager_fallback(optional: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Bool]: + optional = _ops.convert_to_tensor(optional, _dtypes.variant) + _inputs_flat = [optional] + _attrs = None + _result = _execute.execute(b"OptionalHasValue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptionalHasValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def optional_none(name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates an Optional variant with no value. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OptionalNone", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return optional_none_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OptionalNone", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "OptionalNone", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OptionalNone = tf_export("raw_ops.OptionalNone")(_ops.to_raw_op(optional_none)) + + +def optional_none_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Variant]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"OptionalNone", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OptionalNone", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_parsing_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_parsing_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..89ad75abddf8b84c4ff623c2f8d8e89c085cb2aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_parsing_ops.py @@ -0,0 +1,2352 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def decode_csv(records: Annotated[Any, _atypes.String], record_defaults, field_delim:str=",", use_quote_delim:bool=True, na_value:str="", select_cols=[], name=None): + r"""Convert CSV records to tensors. Each column maps to one tensor. + + RFC 4180 format is expected for the CSV records. + (https://tools.ietf.org/html/rfc4180) + Note that we allow leading and trailing spaces with int or float field. + + Args: + records: A `Tensor` of type `string`. + Each string is a record/row in the csv and all records should have + the same format. + record_defaults: A list of `Tensor` objects with types from: `float32`, `float64`, `int32`, `int64`, `string`. + One tensor per column of the input record, with either a + scalar default value for that column or an empty vector if the column is + required. + field_delim: An optional `string`. Defaults to `","`. + char delimiter to separate fields in a record. + use_quote_delim: An optional `bool`. Defaults to `True`. + If false, treats double quotation marks as regular + characters inside of the string fields (ignoring RFC 4180, Section 2, + Bullet 5). + na_value: An optional `string`. Defaults to `""`. + Additional string to recognize as NA/NaN. + select_cols: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `record_defaults`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeCSV", name, records, record_defaults, "field_delim", + field_delim, "use_quote_delim", use_quote_delim, "na_value", na_value, + "select_cols", select_cols) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_csv_eager_fallback( + records, record_defaults, field_delim=field_delim, + use_quote_delim=use_quote_delim, na_value=na_value, + select_cols=select_cols, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if field_delim is None: + field_delim = "," + field_delim = _execute.make_str(field_delim, "field_delim") + if use_quote_delim is None: + use_quote_delim = True + use_quote_delim = _execute.make_bool(use_quote_delim, "use_quote_delim") + if na_value is None: + na_value = "" + na_value = _execute.make_str(na_value, "na_value") + if select_cols is None: + select_cols = [] + if not isinstance(select_cols, (list, tuple)): + raise TypeError( + "Expected list for 'select_cols' argument to " + "'decode_csv' Op, not %r." % select_cols) + select_cols = [_execute.make_int(_i, "select_cols") for _i in select_cols] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeCSV", records=records, record_defaults=record_defaults, + field_delim=field_delim, use_quote_delim=use_quote_delim, + na_value=na_value, select_cols=select_cols, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("OUT_TYPE", _op.get_attr("OUT_TYPE"), "field_delim", + _op.get_attr("field_delim"), "use_quote_delim", + _op._get_attr_bool("use_quote_delim"), "na_value", + _op.get_attr("na_value"), "select_cols", + _op.get_attr("select_cols")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeCSV", _inputs_flat, _attrs, _result) + return _result + +DecodeCSV = tf_export("raw_ops.DecodeCSV")(_ops.to_raw_op(decode_csv)) + + +def decode_csv_eager_fallback(records: Annotated[Any, _atypes.String], record_defaults, field_delim: str, use_quote_delim: bool, na_value: str, select_cols, name, ctx): + if field_delim is None: + field_delim = "," + field_delim = _execute.make_str(field_delim, "field_delim") + if use_quote_delim is None: + use_quote_delim = True + use_quote_delim = _execute.make_bool(use_quote_delim, "use_quote_delim") + if na_value is None: + na_value = "" + na_value = _execute.make_str(na_value, "na_value") + if select_cols is None: + select_cols = [] + if not isinstance(select_cols, (list, tuple)): + raise TypeError( + "Expected list for 'select_cols' argument to " + "'decode_csv' Op, not %r." % select_cols) + select_cols = [_execute.make_int(_i, "select_cols") for _i in select_cols] + _attr_OUT_TYPE, record_defaults = _execute.convert_to_mixed_eager_tensors(record_defaults, ctx) + records = _ops.convert_to_tensor(records, _dtypes.string) + _inputs_flat = [records] + list(record_defaults) + _attrs = ("OUT_TYPE", _attr_OUT_TYPE, "field_delim", field_delim, + "use_quote_delim", use_quote_delim, "na_value", na_value, "select_cols", + select_cols) + _result = _execute.execute(b"DecodeCSV", len(record_defaults), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeCSV", _inputs_flat, _attrs, _result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.decode_compressed', v1=['io.decode_compressed', 'decode_compressed']) +@deprecated_endpoints('decode_compressed') +def decode_compressed(bytes: Annotated[Any, _atypes.String], compression_type:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Decompress strings. + + This op decompresses each element of the `bytes` input `Tensor`, which + is assumed to be compressed using the given `compression_type`. + + The `output` is a string `Tensor` of the same shape as `bytes`, + each element containing the decompressed data from the corresponding + element in `bytes`. + + Args: + bytes: A `Tensor` of type `string`. + A Tensor of string which is compressed. + compression_type: An optional `string`. Defaults to `""`. + A scalar containing either (i) the empty string (no + compression), (ii) "ZLIB", or (iii) "GZIP". + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeCompressed", name, bytes, "compression_type", + compression_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_decode_compressed( + (bytes, compression_type, name,), None) + if _result is not NotImplemented: + return _result + return decode_compressed_eager_fallback( + bytes, compression_type=compression_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_compressed, (), dict(bytes=bytes, + compression_type=compression_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_decode_compressed( + (bytes, compression_type, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeCompressed", bytes=bytes, compression_type=compression_type, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_compressed, (), dict(bytes=bytes, + compression_type=compression_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("compression_type", _op.get_attr("compression_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeCompressed", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeCompressed = tf_export("raw_ops.DecodeCompressed")(_ops.to_raw_op(decode_compressed)) +_dispatcher_for_decode_compressed = decode_compressed._tf_type_based_dispatcher.Dispatch + + +def decode_compressed_eager_fallback(bytes: Annotated[Any, _atypes.String], compression_type: str, name, ctx) -> Annotated[Any, _atypes.String]: + if compression_type is None: + compression_type = "" + compression_type = _execute.make_str(compression_type, "compression_type") + bytes = _ops.convert_to_tensor(bytes, _dtypes.string) + _inputs_flat = [bytes] + _attrs = ("compression_type", compression_type) + _result = _execute.execute(b"DecodeCompressed", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeCompressed", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def decode_json_example(json_examples: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Convert JSON-encoded Example records to binary protocol buffer strings. + + + Note: This is **not** a general purpose JSON parsing op. + + This op converts JSON-serialized + `tf.train.Example` (created with `json_format.MessageToJson`, following the + [standard JSON mapping](https://developers.google.com/protocol-buffers/docs/proto3#json)) + to a binary-serialized `tf.train.Example` (equivalent to + `Example.SerializeToString()`) suitable for conversion to tensors with + `tf.io.parse_example`. + + Args: + json_examples: A `Tensor` of type `string`. + Each string is a JSON object serialized according to the JSON + mapping of the Example proto. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeJSONExample", name, json_examples) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_json_example_eager_fallback( + json_examples, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeJSONExample", json_examples=json_examples, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeJSONExample", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeJSONExample = tf_export("raw_ops.DecodeJSONExample")(_ops.to_raw_op(decode_json_example)) + + +def decode_json_example_eager_fallback(json_examples: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + json_examples = _ops.convert_to_tensor(json_examples, _dtypes.string) + _inputs_flat = [json_examples] + _attrs = None + _result = _execute.execute(b"DecodeJSONExample", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeJSONExample", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DecodePaddedRaw_out_type = TypeVar("TV_DecodePaddedRaw_out_type", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def decode_padded_raw(input_bytes: Annotated[Any, _atypes.String], fixed_length: Annotated[Any, _atypes.Int32], out_type: TV_DecodePaddedRaw_out_type, little_endian:bool=True, name=None) -> Annotated[Any, TV_DecodePaddedRaw_out_type]: + r"""Reinterpret the bytes of a string as a vector of numbers. + + Args: + input_bytes: A `Tensor` of type `string`. Tensor of string to be decoded. + fixed_length: A `Tensor` of type `int32`. + Length in bytes for each element of the decoded output. Must be a multiple + of the size of the output type. + out_type: A `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.uint16, tf.uint8, tf.int16, tf.int8, tf.int64, tf.bfloat16`. + little_endian: An optional `bool`. Defaults to `True`. + Whether the input `input_bytes` is in little-endian order. Ignored for + `out_type` values that are stored in a single byte, like `uint8` + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodePaddedRaw", name, input_bytes, fixed_length, "out_type", + out_type, "little_endian", little_endian) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_padded_raw_eager_fallback( + input_bytes, fixed_length, out_type=out_type, + little_endian=little_endian, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + if little_endian is None: + little_endian = True + little_endian = _execute.make_bool(little_endian, "little_endian") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodePaddedRaw", input_bytes=input_bytes, fixed_length=fixed_length, + out_type=out_type, little_endian=little_endian, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("out_type", _op._get_attr_type("out_type"), "little_endian", + _op._get_attr_bool("little_endian")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodePaddedRaw", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodePaddedRaw = tf_export("raw_ops.DecodePaddedRaw")(_ops.to_raw_op(decode_padded_raw)) + + +def decode_padded_raw_eager_fallback(input_bytes: Annotated[Any, _atypes.String], fixed_length: Annotated[Any, _atypes.Int32], out_type: TV_DecodePaddedRaw_out_type, little_endian: bool, name, ctx) -> Annotated[Any, TV_DecodePaddedRaw_out_type]: + out_type = _execute.make_type(out_type, "out_type") + if little_endian is None: + little_endian = True + little_endian = _execute.make_bool(little_endian, "little_endian") + input_bytes = _ops.convert_to_tensor(input_bytes, _dtypes.string) + fixed_length = _ops.convert_to_tensor(fixed_length, _dtypes.int32) + _inputs_flat = [input_bytes, fixed_length] + _attrs = ("out_type", out_type, "little_endian", little_endian) + _result = _execute.execute(b"DecodePaddedRaw", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodePaddedRaw", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DecodeRaw_out_type = TypeVar("TV_DecodeRaw_out_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt8) + +def decode_raw(bytes: Annotated[Any, _atypes.String], out_type: TV_DecodeRaw_out_type, little_endian:bool=True, name=None) -> Annotated[Any, TV_DecodeRaw_out_type]: + r"""Reinterpret the bytes of a string as a vector of numbers. + + Args: + bytes: A `Tensor` of type `string`. + All the elements must have the same length. + out_type: A `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.uint16, tf.uint8, tf.int16, tf.int8, tf.int64, tf.complex64, tf.complex128, tf.bool, tf.bfloat16`. + little_endian: An optional `bool`. Defaults to `True`. + Whether the input `bytes` are in little-endian order. + Ignored for `out_type` values that are stored in a single byte like + `uint8`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeRaw", name, bytes, "out_type", out_type, "little_endian", + little_endian) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return decode_raw_eager_fallback( + bytes, out_type=out_type, little_endian=little_endian, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + if little_endian is None: + little_endian = True + little_endian = _execute.make_bool(little_endian, "little_endian") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeRaw", bytes=bytes, out_type=out_type, + little_endian=little_endian, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("out_type", _op._get_attr_type("out_type"), "little_endian", + _op._get_attr_bool("little_endian")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeRaw", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeRaw = tf_export("raw_ops.DecodeRaw")(_ops.to_raw_op(decode_raw)) + + +def decode_raw_eager_fallback(bytes: Annotated[Any, _atypes.String], out_type: TV_DecodeRaw_out_type, little_endian: bool, name, ctx) -> Annotated[Any, TV_DecodeRaw_out_type]: + out_type = _execute.make_type(out_type, "out_type") + if little_endian is None: + little_endian = True + little_endian = _execute.make_bool(little_endian, "little_endian") + bytes = _ops.convert_to_tensor(bytes, _dtypes.string) + _inputs_flat = [bytes] + _attrs = ("out_type", out_type, "little_endian", little_endian) + _result = _execute.execute(b"DecodeRaw", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeRaw", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_ParseExampleOutput = collections.namedtuple( + "ParseExample", + ["sparse_indices", "sparse_values", "sparse_shapes", "dense_values"]) + + +def parse_example(serialized: Annotated[Any, _atypes.String], names: Annotated[Any, _atypes.String], sparse_keys: Annotated[List[Any], _atypes.String], dense_keys: Annotated[List[Any], _atypes.String], dense_defaults, sparse_types, dense_shapes, name=None): + r"""Transforms a vector of brain.Example protos (as strings) into typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A vector containing a batch of binary serialized Example protos. + names: A `Tensor` of type `string`. + A vector containing the names of the serialized protos. + May contain, for example, table key (descriptive) names for the + corresponding serialized protos. These are purely useful for debugging + purposes, and the presence of values here has no effect on the output. + May also be an empty vector if no names are available. + If non-empty, this vector must be the same length as "serialized". + sparse_keys: A list of `Tensor` objects with type `string`. + A list of Nsparse string Tensors (scalars). + The keys expected in the Examples' features associated with sparse values. + dense_keys: A list of `Tensor` objects with type `string`. + A list of Ndense string Tensors (scalars). + The keys expected in the Examples' features associated with dense values. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Ndense Tensors (some may be empty). + dense_defaults[j] provides default values + when the example's feature_map lacks dense_key[j]. If an empty Tensor is + provided for dense_defaults[j], then the Feature dense_keys[j] is required. + The input type is inferred from dense_defaults[j], even when it's empty. + If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, + then the shape of dense_defaults[j] must match that of dense_shapes[j]. + If dense_shapes[j] has an undefined major dimension (variable strides dense + feature), dense_defaults[j] must contain a single element: + the padding element. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of Nsparse types; the data types of data in each Feature + given in sparse_keys. + Currently the ParseExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + A list of Ndense shapes; the shapes of data in each Feature + given in dense_keys. + The number of elements in the Feature corresponding to dense_key[j] + must always equal dense_shapes[j].NumEntries(). + If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output + Tensor dense_values[j] will be (|serialized|, D0, D1, ..., DN): + The dense outputs are just the inputs row-stacked by batch. + This works for dense_shapes[j] = (-1, D1, ..., DN). In this case + the shape of the output Tensor dense_values[j] will be + (|serialized|, M, D1, .., DN), where M is the maximum number of blocks + of elements of length D1 * .... * DN, across all minibatch entries + in the input. Any minibatch entry with less than M blocks of elements of + length D1 * ... * DN will be padded with the corresponding default_value + scalar element along the second dimension. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shapes, dense_values). + + sparse_indices: A list with the same length as `sparse_keys` of `Tensor` objects with type `int64`. + sparse_values: A list of `Tensor` objects of type `sparse_types`. + sparse_shapes: A list with the same length as `sparse_keys` of `Tensor` objects with type `int64`. + dense_values: A list of `Tensor` objects. Has the same type as `dense_defaults`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseExample", name, serialized, names, sparse_keys, + dense_keys, dense_defaults, "sparse_types", sparse_types, + "dense_shapes", dense_shapes) + _result = _ParseExampleOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_example_eager_fallback( + serialized, names, sparse_keys, dense_keys, dense_defaults, + sparse_types=sparse_types, dense_shapes=dense_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example' Op, not %r." % sparse_keys) + _attr_Nsparse = len(sparse_keys) + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example' Op, not %r." % dense_keys) + _attr_Ndense = len(dense_keys) + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseExample", serialized=serialized, names=names, + sparse_keys=sparse_keys, dense_keys=dense_keys, + dense_defaults=dense_defaults, + sparse_types=sparse_types, dense_shapes=dense_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Nsparse", _op._get_attr_int("Nsparse"), "Ndense", + _op._get_attr_int("Ndense"), "sparse_types", + _op.get_attr("sparse_types"), "Tdense", _op.get_attr("Tdense"), + "dense_shapes", _op.get_attr("dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseExample", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_Nsparse]] + _result[_attr_Nsparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + _attr_Nsparse]] + _result[2 + _attr_Nsparse:] + _result = _result[:3] + [_result[3:]] + _result = _ParseExampleOutput._make(_result) + return _result + +ParseExample = tf_export("raw_ops.ParseExample")(_ops.to_raw_op(parse_example)) + + +def parse_example_eager_fallback(serialized: Annotated[Any, _atypes.String], names: Annotated[Any, _atypes.String], sparse_keys: Annotated[List[Any], _atypes.String], dense_keys: Annotated[List[Any], _atypes.String], dense_defaults, sparse_types, dense_shapes, name, ctx): + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_example' Op, not %r." % sparse_keys) + _attr_Nsparse = len(sparse_keys) + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_example' Op, not %r." % dense_keys) + _attr_Ndense = len(dense_keys) + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + names = _ops.convert_to_tensor(names, _dtypes.string) + sparse_keys = _ops.convert_n_to_tensor(sparse_keys, _dtypes.string) + dense_keys = _ops.convert_n_to_tensor(dense_keys, _dtypes.string) + _inputs_flat = [serialized, names] + list(sparse_keys) + list(dense_keys) + list(dense_defaults) + _attrs = ("Nsparse", _attr_Nsparse, "Ndense", _attr_Ndense, "sparse_types", + sparse_types, "Tdense", _attr_Tdense, "dense_shapes", dense_shapes) + _result = _execute.execute(b"ParseExample", _attr_Nsparse + + len(sparse_types) + _attr_Nsparse + + len(dense_defaults), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseExample", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_Nsparse]] + _result[_attr_Nsparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + _attr_Nsparse]] + _result[2 + _attr_Nsparse:] + _result = _result[:3] + [_result[3:]] + _result = _ParseExampleOutput._make(_result) + return _result + +_ParseExampleV2Output = collections.namedtuple( + "ParseExampleV2", + ["sparse_indices", "sparse_values", "sparse_shapes", "dense_values", "ragged_values", "ragged_row_splits"]) + + +def parse_example_v2(serialized: Annotated[Any, _atypes.String], names: Annotated[Any, _atypes.String], sparse_keys: Annotated[Any, _atypes.String], dense_keys: Annotated[Any, _atypes.String], ragged_keys: Annotated[Any, _atypes.String], dense_defaults, num_sparse: int, sparse_types, ragged_value_types, ragged_split_types, dense_shapes, name=None): + r"""Transforms a vector of tf.Example protos (as strings) into typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A scalar or vector containing binary serialized Example protos. + names: A `Tensor` of type `string`. + A tensor containing the names of the serialized protos. + Corresponds 1:1 with the `serialized` tensor. + May contain, for example, table key (descriptive) names for the + corresponding serialized protos. These are purely useful for debugging + purposes, and the presence of values here has no effect on the output. + May also be an empty vector if no names are available. + If non-empty, this tensor must have the same shape as "serialized". + sparse_keys: A `Tensor` of type `string`. Vector of strings. + The keys expected in the Examples' features associated with sparse values. + dense_keys: A `Tensor` of type `string`. Vector of strings. + The keys expected in the Examples' features associated with dense values. + ragged_keys: A `Tensor` of type `string`. Vector of strings. + The keys expected in the Examples' features associated with ragged values. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Tensors (some may be empty). Corresponds 1:1 with `dense_keys`. + dense_defaults[j] provides default values + when the example's feature_map lacks dense_key[j]. If an empty Tensor is + provided for dense_defaults[j], then the Feature dense_keys[j] is required. + The input type is inferred from dense_defaults[j], even when it's empty. + If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, + then the shape of dense_defaults[j] must match that of dense_shapes[j]. + If dense_shapes[j] has an undefined major dimension (variable strides dense + feature), dense_defaults[j] must contain a single element: + the padding element. + num_sparse: An `int` that is `>= 0`. The number of sparse keys. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `num_sparse` types; the data types of data in each Feature + given in sparse_keys. + Currently the ParseExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + ragged_value_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `num_ragged` types; the data types of data in each Feature + given in ragged_keys (where `num_ragged = sparse_keys.size()`). + Currently the ParseExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + ragged_split_types: A list of `tf.DTypes` from: `tf.int32, tf.int64`. + A list of `num_ragged` types; the data types of row_splits in each Feature + given in ragged_keys (where `num_ragged = sparse_keys.size()`). + May be DT_INT32 or DT_INT64. + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + A list of `num_dense` shapes; the shapes of data in each Feature + given in dense_keys (where `num_dense = dense_keys.size()`). + The number of elements in the Feature corresponding to dense_key[j] + must always equal dense_shapes[j].NumEntries(). + If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output + Tensor dense_values[j] will be (|serialized|, D0, D1, ..., DN): + The dense outputs are just the inputs row-stacked by batch. + This works for dense_shapes[j] = (-1, D1, ..., DN). In this case + the shape of the output Tensor dense_values[j] will be + (|serialized|, M, D1, .., DN), where M is the maximum number of blocks + of elements of length D1 * .... * DN, across all minibatch entries + in the input. Any minibatch entry with less than M blocks of elements of + length D1 * ... * DN will be padded with the corresponding default_value + scalar element along the second dimension. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shapes, dense_values, ragged_values, ragged_row_splits). + + sparse_indices: A list of `num_sparse` `Tensor` objects with type `int64`. + sparse_values: A list of `Tensor` objects of type `sparse_types`. + sparse_shapes: A list of `num_sparse` `Tensor` objects with type `int64`. + dense_values: A list of `Tensor` objects. Has the same type as `dense_defaults`. + ragged_values: A list of `Tensor` objects of type `ragged_value_types`. + ragged_row_splits: A list of `Tensor` objects of type `ragged_split_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseExampleV2", name, serialized, names, sparse_keys, + dense_keys, ragged_keys, dense_defaults, "num_sparse", num_sparse, + "sparse_types", sparse_types, "ragged_value_types", + ragged_value_types, "ragged_split_types", ragged_split_types, + "dense_shapes", dense_shapes) + _result = _ParseExampleV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_example_v2_eager_fallback( + serialized, names, sparse_keys, dense_keys, ragged_keys, + dense_defaults, num_sparse=num_sparse, sparse_types=sparse_types, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, dense_shapes=dense_shapes, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_sparse = _execute.make_int(num_sparse, "num_sparse") + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_v2' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_v2' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_v2' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_v2' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseExampleV2", serialized=serialized, names=names, + sparse_keys=sparse_keys, dense_keys=dense_keys, + ragged_keys=ragged_keys, + dense_defaults=dense_defaults, + num_sparse=num_sparse, sparse_types=sparse_types, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, + dense_shapes=dense_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tdense", _op.get_attr("Tdense"), "num_sparse", + _op._get_attr_int("num_sparse"), "sparse_types", + _op.get_attr("sparse_types"), "ragged_value_types", + _op.get_attr("ragged_value_types"), "ragged_split_types", + _op.get_attr("ragged_split_types"), "dense_shapes", + _op.get_attr("dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseExampleV2", _inputs_flat, _attrs, _result) + _result = [_result[:num_sparse]] + _result[num_sparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + num_sparse]] + _result[2 + num_sparse:] + _result = _result[:3] + [_result[3:3 + len(dense_defaults)]] + _result[3 + len(dense_defaults):] + _result = _result[:4] + [_result[4:4 + len(ragged_value_types)]] + _result[4 + len(ragged_value_types):] + _result = _result[:5] + [_result[5:]] + _result = _ParseExampleV2Output._make(_result) + return _result + +ParseExampleV2 = tf_export("raw_ops.ParseExampleV2")(_ops.to_raw_op(parse_example_v2)) + + +def parse_example_v2_eager_fallback(serialized: Annotated[Any, _atypes.String], names: Annotated[Any, _atypes.String], sparse_keys: Annotated[Any, _atypes.String], dense_keys: Annotated[Any, _atypes.String], ragged_keys: Annotated[Any, _atypes.String], dense_defaults, num_sparse: int, sparse_types, ragged_value_types, ragged_split_types, dense_shapes, name, ctx): + num_sparse = _execute.make_int(num_sparse, "num_sparse") + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_example_v2' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_value_types' argument to " + "'parse_example_v2' Op, not %r." % ragged_value_types) + ragged_value_types = [_execute.make_type(_t, "ragged_value_types") for _t in ragged_value_types] + if not isinstance(ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'ragged_split_types' argument to " + "'parse_example_v2' Op, not %r." % ragged_split_types) + ragged_split_types = [_execute.make_type(_t, "ragged_split_types") for _t in ragged_split_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_example_v2' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + names = _ops.convert_to_tensor(names, _dtypes.string) + sparse_keys = _ops.convert_to_tensor(sparse_keys, _dtypes.string) + dense_keys = _ops.convert_to_tensor(dense_keys, _dtypes.string) + ragged_keys = _ops.convert_to_tensor(ragged_keys, _dtypes.string) + _inputs_flat = [serialized, names, sparse_keys, dense_keys, ragged_keys] + list(dense_defaults) + _attrs = ("Tdense", _attr_Tdense, "num_sparse", num_sparse, "sparse_types", + sparse_types, "ragged_value_types", ragged_value_types, + "ragged_split_types", ragged_split_types, "dense_shapes", dense_shapes) + _result = _execute.execute(b"ParseExampleV2", num_sparse + len(sparse_types) + + num_sparse + len(dense_defaults) + + len(ragged_value_types) + + len(ragged_split_types), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseExampleV2", _inputs_flat, _attrs, _result) + _result = [_result[:num_sparse]] + _result[num_sparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + num_sparse]] + _result[2 + num_sparse:] + _result = _result[:3] + [_result[3:3 + len(dense_defaults)]] + _result[3 + len(dense_defaults):] + _result = _result[:4] + [_result[4:4 + len(ragged_value_types)]] + _result[4 + len(ragged_value_types):] + _result = _result[:5] + [_result[5:]] + _result = _ParseExampleV2Output._make(_result) + return _result + +_ParseSequenceExampleOutput = collections.namedtuple( + "ParseSequenceExample", + ["context_sparse_indices", "context_sparse_values", "context_sparse_shapes", "context_dense_values", "feature_list_sparse_indices", "feature_list_sparse_values", "feature_list_sparse_shapes", "feature_list_dense_values", "feature_list_dense_lengths"]) + + +def parse_sequence_example(serialized: Annotated[Any, _atypes.String], debug_name: Annotated[Any, _atypes.String], context_dense_defaults, feature_list_dense_missing_assumed_empty, context_sparse_keys, context_dense_keys, feature_list_sparse_keys, feature_list_dense_keys, Ncontext_sparse:int=0, Ncontext_dense:int=0, Nfeature_list_sparse:int=0, Nfeature_list_dense:int=0, context_sparse_types=[], feature_list_dense_types=[], context_dense_shapes=[], feature_list_sparse_types=[], feature_list_dense_shapes=[], name=None): + r"""Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A vector containing binary serialized SequenceExample protos. + debug_name: A `Tensor` of type `string`. + A vector containing the names of the serialized protos. + May contain, for example, table key (descriptive) name for the + corresponding serialized proto. This is purely useful for debugging + purposes, and the presence of values here has no effect on the output. + May also be an empty vector if no name is available. + context_dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Ncontext_dense Tensors (some may be empty). + context_dense_defaults[j] provides default values + when the SequenceExample's context map lacks context_dense_key[j]. + If an empty Tensor is provided for context_dense_defaults[j], + then the Feature context_dense_keys[j] is required. + The input type is inferred from context_dense_defaults[j], even when it's + empty. If context_dense_defaults[j] is not empty, its shape must match + context_dense_shapes[j]. + feature_list_dense_missing_assumed_empty: A list of `strings`. + A vector listing the + FeatureList keys which may be missing from the SequenceExamples. If the + associated FeatureList is missing, it is treated as empty. By default, + any FeatureList not listed in this vector must exist in the SequenceExamples. + context_sparse_keys: A list of `strings`. + A list of Ncontext_sparse string Tensors (scalars). + The keys expected in the Examples' features associated with context_sparse + values. + context_dense_keys: A list of `strings`. + A list of Ncontext_dense string Tensors (scalars). + The keys expected in the SequenceExamples' context features associated with + dense values. + feature_list_sparse_keys: A list of `strings`. + A list of Nfeature_list_sparse string Tensors + (scalars). The keys expected in the FeatureLists associated with sparse + values. + feature_list_dense_keys: A list of `strings`. + A list of Nfeature_list_dense string Tensors (scalars). + The keys expected in the SequenceExamples' feature_lists associated + with lists of dense values. + Ncontext_sparse: An optional `int` that is `>= 0`. Defaults to `0`. + Ncontext_dense: An optional `int` that is `>= 0`. Defaults to `0`. + Nfeature_list_sparse: An optional `int` that is `>= 0`. Defaults to `0`. + Nfeature_list_dense: An optional `int` that is `>= 0`. Defaults to `0`. + context_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Ncontext_sparse types; the data types of data in + each context Feature given in context_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + feature_list_dense_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + context_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Ncontext_dense shapes; the shapes of data in + each context Feature given in context_dense_keys. + The number of elements in the Feature corresponding to context_dense_key[j] + must always equal context_dense_shapes[j].NumEntries(). + The shape of context_dense_values[j] will match context_dense_shapes[j]. + feature_list_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Nfeature_list_sparse types; the data types + of data in each FeatureList given in feature_list_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + feature_list_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Nfeature_list_dense shapes; the shapes of + data in each FeatureList given in feature_list_dense_keys. + The shape of each Feature in the FeatureList corresponding to + feature_list_dense_key[j] must always equal + feature_list_dense_shapes[j].NumEntries(). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (context_sparse_indices, context_sparse_values, context_sparse_shapes, context_dense_values, feature_list_sparse_indices, feature_list_sparse_values, feature_list_sparse_shapes, feature_list_dense_values, feature_list_dense_lengths). + + context_sparse_indices: A list of `Ncontext_sparse` `Tensor` objects with type `int64`. + context_sparse_values: A list of `Tensor` objects of type `context_sparse_types`. + context_sparse_shapes: A list of `Ncontext_sparse` `Tensor` objects with type `int64`. + context_dense_values: A list of `Tensor` objects. Has the same type as `context_dense_defaults`. + feature_list_sparse_indices: A list of `Nfeature_list_sparse` `Tensor` objects with type `int64`. + feature_list_sparse_values: A list of `Tensor` objects of type `feature_list_sparse_types`. + feature_list_sparse_shapes: A list of `Nfeature_list_sparse` `Tensor` objects with type `int64`. + feature_list_dense_values: A list of `Tensor` objects of type `feature_list_dense_types`. + feature_list_dense_lengths: A list of `Nfeature_list_dense` `Tensor` objects with type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseSequenceExample", name, serialized, debug_name, + context_dense_defaults, "feature_list_dense_missing_assumed_empty", + feature_list_dense_missing_assumed_empty, "context_sparse_keys", + context_sparse_keys, "context_dense_keys", context_dense_keys, + "feature_list_sparse_keys", feature_list_sparse_keys, + "feature_list_dense_keys", feature_list_dense_keys, "Ncontext_sparse", + Ncontext_sparse, "Ncontext_dense", Ncontext_dense, + "Nfeature_list_sparse", Nfeature_list_sparse, "Nfeature_list_dense", + Nfeature_list_dense, "context_sparse_types", context_sparse_types, + "feature_list_dense_types", feature_list_dense_types, + "context_dense_shapes", context_dense_shapes, + "feature_list_sparse_types", feature_list_sparse_types, + "feature_list_dense_shapes", feature_list_dense_shapes) + _result = _ParseSequenceExampleOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_sequence_example_eager_fallback( + serialized, debug_name, context_dense_defaults, + feature_list_dense_missing_assumed_empty=feature_list_dense_missing_assumed_empty, + context_sparse_keys=context_sparse_keys, + context_dense_keys=context_dense_keys, + feature_list_sparse_keys=feature_list_sparse_keys, + feature_list_dense_keys=feature_list_dense_keys, + Ncontext_sparse=Ncontext_sparse, Ncontext_dense=Ncontext_dense, + Nfeature_list_sparse=Nfeature_list_sparse, + Nfeature_list_dense=Nfeature_list_dense, + context_sparse_types=context_sparse_types, + feature_list_dense_types=feature_list_dense_types, + context_dense_shapes=context_dense_shapes, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_dense_shapes=feature_list_dense_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(feature_list_dense_missing_assumed_empty, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_missing_assumed_empty' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_missing_assumed_empty) + feature_list_dense_missing_assumed_empty = [_execute.make_str(_s, "feature_list_dense_missing_assumed_empty") for _s in feature_list_dense_missing_assumed_empty] + if not isinstance(context_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_keys' argument to " + "'parse_sequence_example' Op, not %r." % context_sparse_keys) + context_sparse_keys = [_execute.make_str(_s, "context_sparse_keys") for _s in context_sparse_keys] + if not isinstance(context_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_keys' argument to " + "'parse_sequence_example' Op, not %r." % context_dense_keys) + context_dense_keys = [_execute.make_str(_s, "context_dense_keys") for _s in context_dense_keys] + if not isinstance(feature_list_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_keys' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_sparse_keys) + feature_list_sparse_keys = [_execute.make_str(_s, "feature_list_sparse_keys") for _s in feature_list_sparse_keys] + if not isinstance(feature_list_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_keys' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_keys) + feature_list_dense_keys = [_execute.make_str(_s, "feature_list_dense_keys") for _s in feature_list_dense_keys] + if Ncontext_sparse is None: + Ncontext_sparse = 0 + Ncontext_sparse = _execute.make_int(Ncontext_sparse, "Ncontext_sparse") + if Ncontext_dense is None: + Ncontext_dense = 0 + Ncontext_dense = _execute.make_int(Ncontext_dense, "Ncontext_dense") + if Nfeature_list_sparse is None: + Nfeature_list_sparse = 0 + Nfeature_list_sparse = _execute.make_int(Nfeature_list_sparse, "Nfeature_list_sparse") + if Nfeature_list_dense is None: + Nfeature_list_dense = 0 + Nfeature_list_dense = _execute.make_int(Nfeature_list_dense, "Nfeature_list_dense") + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_sequence_example' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_sequence_example' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseSequenceExample", serialized=serialized, debug_name=debug_name, + context_dense_defaults=context_dense_defaults, + feature_list_dense_missing_assumed_empty=feature_list_dense_missing_assumed_empty, + context_sparse_keys=context_sparse_keys, + context_dense_keys=context_dense_keys, + feature_list_sparse_keys=feature_list_sparse_keys, + feature_list_dense_keys=feature_list_dense_keys, + Ncontext_sparse=Ncontext_sparse, + Ncontext_dense=Ncontext_dense, + Nfeature_list_sparse=Nfeature_list_sparse, + Nfeature_list_dense=Nfeature_list_dense, + context_sparse_types=context_sparse_types, + feature_list_dense_types=feature_list_dense_types, + context_dense_shapes=context_dense_shapes, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_dense_shapes=feature_list_dense_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("feature_list_dense_missing_assumed_empty", + _op.get_attr("feature_list_dense_missing_assumed_empty"), + "context_sparse_keys", _op.get_attr("context_sparse_keys"), + "context_dense_keys", _op.get_attr("context_dense_keys"), + "feature_list_sparse_keys", + _op.get_attr("feature_list_sparse_keys"), + "feature_list_dense_keys", + _op.get_attr("feature_list_dense_keys"), "Ncontext_sparse", + _op._get_attr_int("Ncontext_sparse"), "Ncontext_dense", + _op._get_attr_int("Ncontext_dense"), "Nfeature_list_sparse", + _op._get_attr_int("Nfeature_list_sparse"), + "Nfeature_list_dense", _op._get_attr_int("Nfeature_list_dense"), + "context_sparse_types", _op.get_attr("context_sparse_types"), + "Tcontext_dense", _op.get_attr("Tcontext_dense"), + "feature_list_dense_types", + _op.get_attr("feature_list_dense_types"), + "context_dense_shapes", _op.get_attr("context_dense_shapes"), + "feature_list_sparse_types", + _op.get_attr("feature_list_sparse_types"), + "feature_list_dense_shapes", + _op.get_attr("feature_list_dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseSequenceExample", _inputs_flat, _attrs, _result) + _result = [_result[:Ncontext_sparse]] + _result[Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + Ncontext_sparse]] + _result[2 + Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + Nfeature_list_sparse]] + _result[4 + Nfeature_list_sparse:] + _result = _result[:5] + [_result[5:5 + len(feature_list_sparse_types)]] + _result[5 + len(feature_list_sparse_types):] + _result = _result[:6] + [_result[6:6 + Nfeature_list_sparse]] + _result[6 + Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:7 + len(feature_list_dense_types)]] + _result[7 + len(feature_list_dense_types):] + _result = _result[:8] + [_result[8:]] + _result = _ParseSequenceExampleOutput._make(_result) + return _result + +ParseSequenceExample = tf_export("raw_ops.ParseSequenceExample")(_ops.to_raw_op(parse_sequence_example)) + + +def parse_sequence_example_eager_fallback(serialized: Annotated[Any, _atypes.String], debug_name: Annotated[Any, _atypes.String], context_dense_defaults, feature_list_dense_missing_assumed_empty, context_sparse_keys, context_dense_keys, feature_list_sparse_keys, feature_list_dense_keys, Ncontext_sparse: int, Ncontext_dense: int, Nfeature_list_sparse: int, Nfeature_list_dense: int, context_sparse_types, feature_list_dense_types, context_dense_shapes, feature_list_sparse_types, feature_list_dense_shapes, name, ctx): + if not isinstance(feature_list_dense_missing_assumed_empty, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_missing_assumed_empty' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_missing_assumed_empty) + feature_list_dense_missing_assumed_empty = [_execute.make_str(_s, "feature_list_dense_missing_assumed_empty") for _s in feature_list_dense_missing_assumed_empty] + if not isinstance(context_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_keys' argument to " + "'parse_sequence_example' Op, not %r." % context_sparse_keys) + context_sparse_keys = [_execute.make_str(_s, "context_sparse_keys") for _s in context_sparse_keys] + if not isinstance(context_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_keys' argument to " + "'parse_sequence_example' Op, not %r." % context_dense_keys) + context_dense_keys = [_execute.make_str(_s, "context_dense_keys") for _s in context_dense_keys] + if not isinstance(feature_list_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_keys' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_sparse_keys) + feature_list_sparse_keys = [_execute.make_str(_s, "feature_list_sparse_keys") for _s in feature_list_sparse_keys] + if not isinstance(feature_list_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_keys' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_keys) + feature_list_dense_keys = [_execute.make_str(_s, "feature_list_dense_keys") for _s in feature_list_dense_keys] + if Ncontext_sparse is None: + Ncontext_sparse = 0 + Ncontext_sparse = _execute.make_int(Ncontext_sparse, "Ncontext_sparse") + if Ncontext_dense is None: + Ncontext_dense = 0 + Ncontext_dense = _execute.make_int(Ncontext_dense, "Ncontext_dense") + if Nfeature_list_sparse is None: + Nfeature_list_sparse = 0 + Nfeature_list_sparse = _execute.make_int(Nfeature_list_sparse, "Nfeature_list_sparse") + if Nfeature_list_dense is None: + Nfeature_list_dense = 0 + Nfeature_list_dense = _execute.make_int(Nfeature_list_dense, "Nfeature_list_dense") + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_sequence_example' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_sequence_example' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_sequence_example' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _attr_Tcontext_dense, context_dense_defaults = _execute.convert_to_mixed_eager_tensors(context_dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + debug_name = _ops.convert_to_tensor(debug_name, _dtypes.string) + _inputs_flat = [serialized, debug_name] + list(context_dense_defaults) + _attrs = ("feature_list_dense_missing_assumed_empty", + feature_list_dense_missing_assumed_empty, "context_sparse_keys", + context_sparse_keys, "context_dense_keys", context_dense_keys, + "feature_list_sparse_keys", feature_list_sparse_keys, + "feature_list_dense_keys", feature_list_dense_keys, "Ncontext_sparse", + Ncontext_sparse, "Ncontext_dense", Ncontext_dense, "Nfeature_list_sparse", + Nfeature_list_sparse, "Nfeature_list_dense", Nfeature_list_dense, + "context_sparse_types", context_sparse_types, "Tcontext_dense", + _attr_Tcontext_dense, "feature_list_dense_types", feature_list_dense_types, + "context_dense_shapes", context_dense_shapes, "feature_list_sparse_types", + feature_list_sparse_types, "feature_list_dense_shapes", + feature_list_dense_shapes) + _result = _execute.execute(b"ParseSequenceExample", Ncontext_sparse + + len(context_sparse_types) + Ncontext_sparse + + len(context_dense_defaults) + + Nfeature_list_sparse + + len(feature_list_sparse_types) + + Nfeature_list_sparse + + len(feature_list_dense_types) + + Nfeature_list_dense, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseSequenceExample", _inputs_flat, _attrs, _result) + _result = [_result[:Ncontext_sparse]] + _result[Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + Ncontext_sparse]] + _result[2 + Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + Nfeature_list_sparse]] + _result[4 + Nfeature_list_sparse:] + _result = _result[:5] + [_result[5:5 + len(feature_list_sparse_types)]] + _result[5 + len(feature_list_sparse_types):] + _result = _result[:6] + [_result[6:6 + Nfeature_list_sparse]] + _result[6 + Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:7 + len(feature_list_dense_types)]] + _result[7 + len(feature_list_dense_types):] + _result = _result[:8] + [_result[8:]] + _result = _ParseSequenceExampleOutput._make(_result) + return _result + +_ParseSequenceExampleV2Output = collections.namedtuple( + "ParseSequenceExampleV2", + ["context_sparse_indices", "context_sparse_values", "context_sparse_shapes", "context_dense_values", "context_ragged_values", "context_ragged_row_splits", "feature_list_sparse_indices", "feature_list_sparse_values", "feature_list_sparse_shapes", "feature_list_dense_values", "feature_list_dense_lengths", "feature_list_ragged_values", "feature_list_ragged_outer_splits", "feature_list_ragged_inner_splits"]) + + +def parse_sequence_example_v2(serialized: Annotated[Any, _atypes.String], debug_name: Annotated[Any, _atypes.String], context_sparse_keys: Annotated[Any, _atypes.String], context_dense_keys: Annotated[Any, _atypes.String], context_ragged_keys: Annotated[Any, _atypes.String], feature_list_sparse_keys: Annotated[Any, _atypes.String], feature_list_dense_keys: Annotated[Any, _atypes.String], feature_list_ragged_keys: Annotated[Any, _atypes.String], feature_list_dense_missing_assumed_empty: Annotated[Any, _atypes.Bool], context_dense_defaults, Ncontext_sparse:int=0, context_sparse_types=[], context_ragged_value_types=[], context_ragged_split_types=[], context_dense_shapes=[], Nfeature_list_sparse:int=0, Nfeature_list_dense:int=0, feature_list_dense_types=[], feature_list_sparse_types=[], feature_list_ragged_value_types=[], feature_list_ragged_split_types=[], feature_list_dense_shapes=[], name=None): + r"""Transforms a vector of tf.io.SequenceExample protos (as strings) into +typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A scalar or vector containing binary serialized SequenceExample protos. + debug_name: A `Tensor` of type `string`. + A scalar or vector containing the names of the serialized protos. + May contain, for example, table key (descriptive) name for the + corresponding serialized proto. This is purely useful for debugging + purposes, and the presence of values here has no effect on the output. + May also be an empty vector if no name is available. + context_sparse_keys: A `Tensor` of type `string`. + The keys expected in the Examples' features associated with context_sparse + values. + context_dense_keys: A `Tensor` of type `string`. + The keys expected in the SequenceExamples' context features associated with + dense values. + context_ragged_keys: A `Tensor` of type `string`. + The keys expected in the Examples' features associated with context_ragged + values. + feature_list_sparse_keys: A `Tensor` of type `string`. + The keys expected in the FeatureLists associated with sparse values. + feature_list_dense_keys: A `Tensor` of type `string`. + The keys expected in the SequenceExamples' feature_lists associated + with lists of dense values. + feature_list_ragged_keys: A `Tensor` of type `string`. + The keys expected in the FeatureLists associated with ragged values. + feature_list_dense_missing_assumed_empty: A `Tensor` of type `bool`. + A vector corresponding 1:1 with feature_list_dense_keys, indicating which + features may be missing from the SequenceExamples. If the associated + FeatureList is missing, it is treated as empty. + context_dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Ncontext_dense Tensors (some may be empty). + context_dense_defaults[j] provides default values + when the SequenceExample's context map lacks context_dense_key[j]. + If an empty Tensor is provided for context_dense_defaults[j], + then the Feature context_dense_keys[j] is required. + The input type is inferred from context_dense_defaults[j], even when it's + empty. If context_dense_defaults[j] is not empty, its shape must match + context_dense_shapes[j]. + Ncontext_sparse: An optional `int` that is `>= 0`. Defaults to `0`. + context_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Ncontext_sparse types; the data types of data in + each context Feature given in context_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + context_ragged_value_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + RaggedTensor.value dtypes for the ragged context features. + context_ragged_split_types: An optional list of `tf.DTypes` from: `tf.int32, tf.int64`. Defaults to `[]`. + RaggedTensor.row_split dtypes for the ragged context features. + context_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Ncontext_dense shapes; the shapes of data in + each context Feature given in context_dense_keys. + The number of elements in the Feature corresponding to context_dense_key[j] + must always equal context_dense_shapes[j].NumEntries(). + The shape of context_dense_values[j] will match context_dense_shapes[j]. + Nfeature_list_sparse: An optional `int` that is `>= 0`. Defaults to `0`. + Nfeature_list_dense: An optional `int` that is `>= 0`. Defaults to `0`. + feature_list_dense_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + feature_list_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Nfeature_list_sparse types; the data types + of data in each FeatureList given in feature_list_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + feature_list_ragged_value_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + RaggedTensor.value dtypes for the ragged FeatureList features. + feature_list_ragged_split_types: An optional list of `tf.DTypes` from: `tf.int32, tf.int64`. Defaults to `[]`. + RaggedTensor.row_split dtypes for the ragged FeatureList features. + feature_list_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Nfeature_list_dense shapes; the shapes of + data in each FeatureList given in feature_list_dense_keys. + The shape of each Feature in the FeatureList corresponding to + feature_list_dense_key[j] must always equal + feature_list_dense_shapes[j].NumEntries(). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (context_sparse_indices, context_sparse_values, context_sparse_shapes, context_dense_values, context_ragged_values, context_ragged_row_splits, feature_list_sparse_indices, feature_list_sparse_values, feature_list_sparse_shapes, feature_list_dense_values, feature_list_dense_lengths, feature_list_ragged_values, feature_list_ragged_outer_splits, feature_list_ragged_inner_splits). + + context_sparse_indices: A list of `Ncontext_sparse` `Tensor` objects with type `int64`. + context_sparse_values: A list of `Tensor` objects of type `context_sparse_types`. + context_sparse_shapes: A list of `Ncontext_sparse` `Tensor` objects with type `int64`. + context_dense_values: A list of `Tensor` objects. Has the same type as `context_dense_defaults`. + context_ragged_values: A list of `Tensor` objects of type `context_ragged_value_types`. + context_ragged_row_splits: A list of `Tensor` objects of type `context_ragged_split_types`. + feature_list_sparse_indices: A list of `Nfeature_list_sparse` `Tensor` objects with type `int64`. + feature_list_sparse_values: A list of `Tensor` objects of type `feature_list_sparse_types`. + feature_list_sparse_shapes: A list of `Nfeature_list_sparse` `Tensor` objects with type `int64`. + feature_list_dense_values: A list of `Tensor` objects of type `feature_list_dense_types`. + feature_list_dense_lengths: A list of `Nfeature_list_dense` `Tensor` objects with type `int64`. + feature_list_ragged_values: A list of `Tensor` objects of type `feature_list_ragged_value_types`. + feature_list_ragged_outer_splits: A list of `Tensor` objects of type `feature_list_ragged_split_types`. + feature_list_ragged_inner_splits: A list of `Tensor` objects of type `feature_list_ragged_split_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseSequenceExampleV2", name, serialized, debug_name, + context_sparse_keys, context_dense_keys, context_ragged_keys, + feature_list_sparse_keys, feature_list_dense_keys, + feature_list_ragged_keys, feature_list_dense_missing_assumed_empty, + context_dense_defaults, "Ncontext_sparse", Ncontext_sparse, + "context_sparse_types", context_sparse_types, + "context_ragged_value_types", context_ragged_value_types, + "context_ragged_split_types", context_ragged_split_types, + "context_dense_shapes", context_dense_shapes, "Nfeature_list_sparse", + Nfeature_list_sparse, "Nfeature_list_dense", Nfeature_list_dense, + "feature_list_dense_types", feature_list_dense_types, + "feature_list_sparse_types", feature_list_sparse_types, + "feature_list_ragged_value_types", feature_list_ragged_value_types, + "feature_list_ragged_split_types", feature_list_ragged_split_types, + "feature_list_dense_shapes", feature_list_dense_shapes) + _result = _ParseSequenceExampleV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_sequence_example_v2_eager_fallback( + serialized, debug_name, context_sparse_keys, context_dense_keys, + context_ragged_keys, feature_list_sparse_keys, + feature_list_dense_keys, feature_list_ragged_keys, + feature_list_dense_missing_assumed_empty, context_dense_defaults, + Ncontext_sparse=Ncontext_sparse, + context_sparse_types=context_sparse_types, + context_ragged_value_types=context_ragged_value_types, + context_ragged_split_types=context_ragged_split_types, + context_dense_shapes=context_dense_shapes, + Nfeature_list_sparse=Nfeature_list_sparse, + Nfeature_list_dense=Nfeature_list_dense, + feature_list_dense_types=feature_list_dense_types, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_ragged_value_types=feature_list_ragged_value_types, + feature_list_ragged_split_types=feature_list_ragged_split_types, + feature_list_dense_shapes=feature_list_dense_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Ncontext_sparse is None: + Ncontext_sparse = 0 + Ncontext_sparse = _execute.make_int(Ncontext_sparse, "Ncontext_sparse") + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if context_ragged_value_types is None: + context_ragged_value_types = [] + if not isinstance(context_ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_ragged_value_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_ragged_value_types) + context_ragged_value_types = [_execute.make_type(_t, "context_ragged_value_types") for _t in context_ragged_value_types] + if context_ragged_split_types is None: + context_ragged_split_types = [] + if not isinstance(context_ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_ragged_split_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_ragged_split_types) + context_ragged_split_types = [_execute.make_type(_t, "context_ragged_split_types") for _t in context_ragged_split_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if Nfeature_list_sparse is None: + Nfeature_list_sparse = 0 + Nfeature_list_sparse = _execute.make_int(Nfeature_list_sparse, "Nfeature_list_sparse") + if Nfeature_list_dense is None: + Nfeature_list_dense = 0 + Nfeature_list_dense = _execute.make_int(Nfeature_list_dense, "Nfeature_list_dense") + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_ragged_value_types is None: + feature_list_ragged_value_types = [] + if not isinstance(feature_list_ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_ragged_value_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_ragged_value_types) + feature_list_ragged_value_types = [_execute.make_type(_t, "feature_list_ragged_value_types") for _t in feature_list_ragged_value_types] + if feature_list_ragged_split_types is None: + feature_list_ragged_split_types = [] + if not isinstance(feature_list_ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_ragged_split_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_ragged_split_types) + feature_list_ragged_split_types = [_execute.make_type(_t, "feature_list_ragged_split_types") for _t in feature_list_ragged_split_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseSequenceExampleV2", serialized=serialized, + debug_name=debug_name, + context_sparse_keys=context_sparse_keys, + context_dense_keys=context_dense_keys, + context_ragged_keys=context_ragged_keys, + feature_list_sparse_keys=feature_list_sparse_keys, + feature_list_dense_keys=feature_list_dense_keys, + feature_list_ragged_keys=feature_list_ragged_keys, + feature_list_dense_missing_assumed_empty=feature_list_dense_missing_assumed_empty, + context_dense_defaults=context_dense_defaults, + Ncontext_sparse=Ncontext_sparse, + context_sparse_types=context_sparse_types, + context_ragged_value_types=context_ragged_value_types, + context_ragged_split_types=context_ragged_split_types, + context_dense_shapes=context_dense_shapes, + Nfeature_list_sparse=Nfeature_list_sparse, + Nfeature_list_dense=Nfeature_list_dense, + feature_list_dense_types=feature_list_dense_types, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_ragged_value_types=feature_list_ragged_value_types, + feature_list_ragged_split_types=feature_list_ragged_split_types, + feature_list_dense_shapes=feature_list_dense_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Ncontext_sparse", _op._get_attr_int("Ncontext_sparse"), + "Tcontext_dense", _op.get_attr("Tcontext_dense"), + "context_sparse_types", _op.get_attr("context_sparse_types"), + "context_ragged_value_types", + _op.get_attr("context_ragged_value_types"), + "context_ragged_split_types", + _op.get_attr("context_ragged_split_types"), + "context_dense_shapes", _op.get_attr("context_dense_shapes"), + "Nfeature_list_sparse", + _op._get_attr_int("Nfeature_list_sparse"), + "Nfeature_list_dense", _op._get_attr_int("Nfeature_list_dense"), + "feature_list_dense_types", + _op.get_attr("feature_list_dense_types"), + "feature_list_sparse_types", + _op.get_attr("feature_list_sparse_types"), + "feature_list_ragged_value_types", + _op.get_attr("feature_list_ragged_value_types"), + "feature_list_ragged_split_types", + _op.get_attr("feature_list_ragged_split_types"), + "feature_list_dense_shapes", + _op.get_attr("feature_list_dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseSequenceExampleV2", _inputs_flat, _attrs, _result) + _result = [_result[:Ncontext_sparse]] + _result[Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + Ncontext_sparse]] + _result[2 + Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + len(context_ragged_value_types)]] + _result[4 + len(context_ragged_value_types):] + _result = _result[:5] + [_result[5:5 + len(context_ragged_split_types)]] + _result[5 + len(context_ragged_split_types):] + _result = _result[:6] + [_result[6:6 + Nfeature_list_sparse]] + _result[6 + Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:7 + len(feature_list_sparse_types)]] + _result[7 + len(feature_list_sparse_types):] + _result = _result[:8] + [_result[8:8 + Nfeature_list_sparse]] + _result[8 + Nfeature_list_sparse:] + _result = _result[:9] + [_result[9:9 + len(feature_list_dense_types)]] + _result[9 + len(feature_list_dense_types):] + _result = _result[:10] + [_result[10:10 + Nfeature_list_dense]] + _result[10 + Nfeature_list_dense:] + _result = _result[:11] + [_result[11:11 + len(feature_list_ragged_value_types)]] + _result[11 + len(feature_list_ragged_value_types):] + _result = _result[:12] + [_result[12:12 + len(feature_list_ragged_split_types)]] + _result[12 + len(feature_list_ragged_split_types):] + _result = _result[:13] + [_result[13:]] + _result = _ParseSequenceExampleV2Output._make(_result) + return _result + +ParseSequenceExampleV2 = tf_export("raw_ops.ParseSequenceExampleV2")(_ops.to_raw_op(parse_sequence_example_v2)) + + +def parse_sequence_example_v2_eager_fallback(serialized: Annotated[Any, _atypes.String], debug_name: Annotated[Any, _atypes.String], context_sparse_keys: Annotated[Any, _atypes.String], context_dense_keys: Annotated[Any, _atypes.String], context_ragged_keys: Annotated[Any, _atypes.String], feature_list_sparse_keys: Annotated[Any, _atypes.String], feature_list_dense_keys: Annotated[Any, _atypes.String], feature_list_ragged_keys: Annotated[Any, _atypes.String], feature_list_dense_missing_assumed_empty: Annotated[Any, _atypes.Bool], context_dense_defaults, Ncontext_sparse: int, context_sparse_types, context_ragged_value_types, context_ragged_split_types, context_dense_shapes, Nfeature_list_sparse: int, Nfeature_list_dense: int, feature_list_dense_types, feature_list_sparse_types, feature_list_ragged_value_types, feature_list_ragged_split_types, feature_list_dense_shapes, name, ctx): + if Ncontext_sparse is None: + Ncontext_sparse = 0 + Ncontext_sparse = _execute.make_int(Ncontext_sparse, "Ncontext_sparse") + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if context_ragged_value_types is None: + context_ragged_value_types = [] + if not isinstance(context_ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_ragged_value_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_ragged_value_types) + context_ragged_value_types = [_execute.make_type(_t, "context_ragged_value_types") for _t in context_ragged_value_types] + if context_ragged_split_types is None: + context_ragged_split_types = [] + if not isinstance(context_ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_ragged_split_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_ragged_split_types) + context_ragged_split_types = [_execute.make_type(_t, "context_ragged_split_types") for _t in context_ragged_split_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_sequence_example_v2' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if Nfeature_list_sparse is None: + Nfeature_list_sparse = 0 + Nfeature_list_sparse = _execute.make_int(Nfeature_list_sparse, "Nfeature_list_sparse") + if Nfeature_list_dense is None: + Nfeature_list_dense = 0 + Nfeature_list_dense = _execute.make_int(Nfeature_list_dense, "Nfeature_list_dense") + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_ragged_value_types is None: + feature_list_ragged_value_types = [] + if not isinstance(feature_list_ragged_value_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_ragged_value_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_ragged_value_types) + feature_list_ragged_value_types = [_execute.make_type(_t, "feature_list_ragged_value_types") for _t in feature_list_ragged_value_types] + if feature_list_ragged_split_types is None: + feature_list_ragged_split_types = [] + if not isinstance(feature_list_ragged_split_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_ragged_split_types' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_ragged_split_types) + feature_list_ragged_split_types = [_execute.make_type(_t, "feature_list_ragged_split_types") for _t in feature_list_ragged_split_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_sequence_example_v2' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _attr_Tcontext_dense, context_dense_defaults = _execute.convert_to_mixed_eager_tensors(context_dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + debug_name = _ops.convert_to_tensor(debug_name, _dtypes.string) + context_sparse_keys = _ops.convert_to_tensor(context_sparse_keys, _dtypes.string) + context_dense_keys = _ops.convert_to_tensor(context_dense_keys, _dtypes.string) + context_ragged_keys = _ops.convert_to_tensor(context_ragged_keys, _dtypes.string) + feature_list_sparse_keys = _ops.convert_to_tensor(feature_list_sparse_keys, _dtypes.string) + feature_list_dense_keys = _ops.convert_to_tensor(feature_list_dense_keys, _dtypes.string) + feature_list_ragged_keys = _ops.convert_to_tensor(feature_list_ragged_keys, _dtypes.string) + feature_list_dense_missing_assumed_empty = _ops.convert_to_tensor(feature_list_dense_missing_assumed_empty, _dtypes.bool) + _inputs_flat = [serialized, debug_name, context_sparse_keys, context_dense_keys, context_ragged_keys, feature_list_sparse_keys, feature_list_dense_keys, feature_list_ragged_keys, feature_list_dense_missing_assumed_empty] + list(context_dense_defaults) + _attrs = ("Ncontext_sparse", Ncontext_sparse, "Tcontext_dense", + _attr_Tcontext_dense, "context_sparse_types", context_sparse_types, + "context_ragged_value_types", context_ragged_value_types, + "context_ragged_split_types", context_ragged_split_types, + "context_dense_shapes", context_dense_shapes, "Nfeature_list_sparse", + Nfeature_list_sparse, "Nfeature_list_dense", Nfeature_list_dense, + "feature_list_dense_types", feature_list_dense_types, + "feature_list_sparse_types", feature_list_sparse_types, + "feature_list_ragged_value_types", feature_list_ragged_value_types, + "feature_list_ragged_split_types", feature_list_ragged_split_types, + "feature_list_dense_shapes", feature_list_dense_shapes) + _result = _execute.execute(b"ParseSequenceExampleV2", Ncontext_sparse + + len(context_sparse_types) + Ncontext_sparse + + len(context_dense_defaults) + + len(context_ragged_value_types) + + len(context_ragged_split_types) + + Nfeature_list_sparse + + len(feature_list_sparse_types) + + Nfeature_list_sparse + + len(feature_list_dense_types) + + Nfeature_list_dense + + len(feature_list_ragged_value_types) + + len(feature_list_ragged_split_types) + + len(feature_list_ragged_split_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseSequenceExampleV2", _inputs_flat, _attrs, _result) + _result = [_result[:Ncontext_sparse]] + _result[Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + Ncontext_sparse]] + _result[2 + Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + len(context_ragged_value_types)]] + _result[4 + len(context_ragged_value_types):] + _result = _result[:5] + [_result[5:5 + len(context_ragged_split_types)]] + _result[5 + len(context_ragged_split_types):] + _result = _result[:6] + [_result[6:6 + Nfeature_list_sparse]] + _result[6 + Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:7 + len(feature_list_sparse_types)]] + _result[7 + len(feature_list_sparse_types):] + _result = _result[:8] + [_result[8:8 + Nfeature_list_sparse]] + _result[8 + Nfeature_list_sparse:] + _result = _result[:9] + [_result[9:9 + len(feature_list_dense_types)]] + _result[9 + len(feature_list_dense_types):] + _result = _result[:10] + [_result[10:10 + Nfeature_list_dense]] + _result[10 + Nfeature_list_dense:] + _result = _result[:11] + [_result[11:11 + len(feature_list_ragged_value_types)]] + _result[11 + len(feature_list_ragged_value_types):] + _result = _result[:12] + [_result[12:12 + len(feature_list_ragged_split_types)]] + _result[12 + len(feature_list_ragged_split_types):] + _result = _result[:13] + [_result[13:]] + _result = _ParseSequenceExampleV2Output._make(_result) + return _result + +_ParseSingleExampleOutput = collections.namedtuple( + "ParseSingleExample", + ["sparse_indices", "sparse_values", "sparse_shapes", "dense_values"]) + + +def parse_single_example(serialized: Annotated[Any, _atypes.String], dense_defaults, num_sparse: int, sparse_keys, dense_keys, sparse_types, dense_shapes, name=None): + r"""Transforms a tf.Example proto (as a string) into typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A vector containing a batch of binary serialized Example protos. + dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Tensors (some may be empty), whose length matches + the length of `dense_keys`. dense_defaults[j] provides default values + when the example's feature_map lacks dense_key[j]. If an empty Tensor is + provided for dense_defaults[j], then the Feature dense_keys[j] is required. + The input type is inferred from dense_defaults[j], even when it's empty. + If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, + then the shape of dense_defaults[j] must match that of dense_shapes[j]. + If dense_shapes[j] has an undefined major dimension (variable strides dense + feature), dense_defaults[j] must contain a single element: + the padding element. + num_sparse: An `int` that is `>= 0`. + The number of sparse features to be parsed from the example. This + must match the lengths of `sparse_keys` and `sparse_types`. + sparse_keys: A list of `strings`. A list of `num_sparse` strings. + The keys expected in the Examples' features associated with sparse values. + dense_keys: A list of `strings`. + The keys expected in the Examples' features associated with dense + values. + sparse_types: A list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. + A list of `num_sparse` types; the data types of data in each + Feature given in sparse_keys. + Currently the ParseSingleExample op supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + dense_shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of data in each Feature given in dense_keys. + The length of this list must match the length of `dense_keys`. The + number of elements in the Feature corresponding to dense_key[j] must + always equal dense_shapes[j].NumEntries(). If dense_shapes[j] == + (D0, D1, ..., DN) then the shape of output Tensor dense_values[j] + will be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1, + ..., DN), the shape of the output Tensor dense_values[j] will be (M, + D1, .., DN), where M is the number of blocks of elements of length + D1 * .... * DN, in the input. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shapes, dense_values). + + sparse_indices: A list of `num_sparse` `Tensor` objects with type `int64`. + sparse_values: A list of `Tensor` objects of type `sparse_types`. + sparse_shapes: A list of `num_sparse` `Tensor` objects with type `int64`. + dense_values: A list of `Tensor` objects. Has the same type as `dense_defaults`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseSingleExample", name, serialized, dense_defaults, + "num_sparse", num_sparse, "sparse_keys", sparse_keys, "dense_keys", + dense_keys, "sparse_types", sparse_types, "dense_shapes", + dense_shapes) + _result = _ParseSingleExampleOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_single_example_eager_fallback( + serialized, dense_defaults, num_sparse=num_sparse, + sparse_keys=sparse_keys, dense_keys=dense_keys, + sparse_types=sparse_types, dense_shapes=dense_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_sparse = _execute.make_int(num_sparse, "num_sparse") + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_single_example' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_single_example' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_single_example' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_single_example' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseSingleExample", serialized=serialized, + dense_defaults=dense_defaults, + num_sparse=num_sparse, sparse_keys=sparse_keys, + dense_keys=dense_keys, + sparse_types=sparse_types, + dense_shapes=dense_shapes, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_sparse", _op._get_attr_int("num_sparse"), "sparse_keys", + _op.get_attr("sparse_keys"), "dense_keys", + _op.get_attr("dense_keys"), "sparse_types", + _op.get_attr("sparse_types"), "Tdense", _op.get_attr("Tdense"), + "dense_shapes", _op.get_attr("dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseSingleExample", _inputs_flat, _attrs, _result) + _result = [_result[:num_sparse]] + _result[num_sparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + num_sparse]] + _result[2 + num_sparse:] + _result = _result[:3] + [_result[3:]] + _result = _ParseSingleExampleOutput._make(_result) + return _result + +ParseSingleExample = tf_export("raw_ops.ParseSingleExample")(_ops.to_raw_op(parse_single_example)) + + +def parse_single_example_eager_fallback(serialized: Annotated[Any, _atypes.String], dense_defaults, num_sparse: int, sparse_keys, dense_keys, sparse_types, dense_shapes, name, ctx): + num_sparse = _execute.make_int(num_sparse, "num_sparse") + if not isinstance(sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_keys' argument to " + "'parse_single_example' Op, not %r." % sparse_keys) + sparse_keys = [_execute.make_str(_s, "sparse_keys") for _s in sparse_keys] + if not isinstance(dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'dense_keys' argument to " + "'parse_single_example' Op, not %r." % dense_keys) + dense_keys = [_execute.make_str(_s, "dense_keys") for _s in dense_keys] + if not isinstance(sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_types' argument to " + "'parse_single_example' Op, not %r." % sparse_types) + sparse_types = [_execute.make_type(_t, "sparse_types") for _t in sparse_types] + if not isinstance(dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'dense_shapes' argument to " + "'parse_single_example' Op, not %r." % dense_shapes) + dense_shapes = [_execute.make_shape(_s, "dense_shapes") for _s in dense_shapes] + _attr_Tdense, dense_defaults = _execute.convert_to_mixed_eager_tensors(dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + _inputs_flat = [serialized] + list(dense_defaults) + _attrs = ("num_sparse", num_sparse, "sparse_keys", sparse_keys, + "dense_keys", dense_keys, "sparse_types", sparse_types, "Tdense", + _attr_Tdense, "dense_shapes", dense_shapes) + _result = _execute.execute(b"ParseSingleExample", num_sparse + + len(sparse_types) + num_sparse + + len(dense_defaults), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseSingleExample", _inputs_flat, _attrs, _result) + _result = [_result[:num_sparse]] + _result[num_sparse:] + _result = _result[:1] + [_result[1:1 + len(sparse_types)]] + _result[1 + len(sparse_types):] + _result = _result[:2] + [_result[2:2 + num_sparse]] + _result[2 + num_sparse:] + _result = _result[:3] + [_result[3:]] + _result = _ParseSingleExampleOutput._make(_result) + return _result + +_ParseSingleSequenceExampleOutput = collections.namedtuple( + "ParseSingleSequenceExample", + ["context_sparse_indices", "context_sparse_values", "context_sparse_shapes", "context_dense_values", "feature_list_sparse_indices", "feature_list_sparse_values", "feature_list_sparse_shapes", "feature_list_dense_values"]) + + +def parse_single_sequence_example(serialized: Annotated[Any, _atypes.String], feature_list_dense_missing_assumed_empty: Annotated[Any, _atypes.String], context_sparse_keys: Annotated[List[Any], _atypes.String], context_dense_keys: Annotated[List[Any], _atypes.String], feature_list_sparse_keys: Annotated[List[Any], _atypes.String], feature_list_dense_keys: Annotated[List[Any], _atypes.String], context_dense_defaults, debug_name: Annotated[Any, _atypes.String], context_sparse_types=[], feature_list_dense_types=[], context_dense_shapes=[], feature_list_sparse_types=[], feature_list_dense_shapes=[], name=None): + r"""Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors. + + Args: + serialized: A `Tensor` of type `string`. + A scalar containing a binary serialized SequenceExample proto. + feature_list_dense_missing_assumed_empty: A `Tensor` of type `string`. + A vector listing the + FeatureList keys which may be missing from the SequenceExample. If the + associated FeatureList is missing, it is treated as empty. By default, + any FeatureList not listed in this vector must exist in the SequenceExample. + context_sparse_keys: A list of `Tensor` objects with type `string`. + A list of Ncontext_sparse string Tensors (scalars). + The keys expected in the Examples' features associated with context_sparse + values. + context_dense_keys: A list of `Tensor` objects with type `string`. + A list of Ncontext_dense string Tensors (scalars). + The keys expected in the SequenceExamples' context features associated with + dense values. + feature_list_sparse_keys: A list of `Tensor` objects with type `string`. + A list of Nfeature_list_sparse string Tensors + (scalars). The keys expected in the FeatureLists associated with sparse + values. + feature_list_dense_keys: A list of `Tensor` objects with type `string`. + A list of Nfeature_list_dense string Tensors (scalars). + The keys expected in the SequenceExamples' feature_lists associated + with lists of dense values. + context_dense_defaults: A list of `Tensor` objects with types from: `float32`, `int64`, `string`. + A list of Ncontext_dense Tensors (some may be empty). + context_dense_defaults[j] provides default values + when the SequenceExample's context map lacks context_dense_key[j]. + If an empty Tensor is provided for context_dense_defaults[j], + then the Feature context_dense_keys[j] is required. + The input type is inferred from context_dense_defaults[j], even when it's + empty. If context_dense_defaults[j] is not empty, its shape must match + context_dense_shapes[j]. + debug_name: A `Tensor` of type `string`. + A scalar containing the name of the serialized proto. + May contain, for example, table key (descriptive) name for the + corresponding serialized proto. This is purely useful for debugging + purposes, and the presence of values here has no effect on the output. + May also be an empty scalar if no name is available. + context_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Ncontext_sparse types; the data types of data in + each context Feature given in context_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + feature_list_dense_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + context_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Ncontext_dense shapes; the shapes of data in + each context Feature given in context_dense_keys. + The number of elements in the Feature corresponding to context_dense_key[j] + must always equal context_dense_shapes[j].NumEntries(). + The shape of context_dense_values[j] will match context_dense_shapes[j]. + feature_list_sparse_types: An optional list of `tf.DTypes` from: `tf.float32, tf.int64, tf.string`. Defaults to `[]`. + A list of Nfeature_list_sparse types; the data types + of data in each FeatureList given in feature_list_sparse_keys. + Currently the ParseSingleSequenceExample supports DT_FLOAT (FloatList), + DT_INT64 (Int64List), and DT_STRING (BytesList). + feature_list_dense_shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`. + A list of Nfeature_list_dense shapes; the shapes of + data in each FeatureList given in feature_list_dense_keys. + The shape of each Feature in the FeatureList corresponding to + feature_list_dense_key[j] must always equal + feature_list_dense_shapes[j].NumEntries(). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (context_sparse_indices, context_sparse_values, context_sparse_shapes, context_dense_values, feature_list_sparse_indices, feature_list_sparse_values, feature_list_sparse_shapes, feature_list_dense_values). + + context_sparse_indices: A list with the same length as `context_sparse_keys` of `Tensor` objects with type `int64`. + context_sparse_values: A list of `Tensor` objects of type `context_sparse_types`. + context_sparse_shapes: A list with the same length as `context_sparse_keys` of `Tensor` objects with type `int64`. + context_dense_values: A list of `Tensor` objects. Has the same type as `context_dense_defaults`. + feature_list_sparse_indices: A list with the same length as `feature_list_sparse_keys` of `Tensor` objects with type `int64`. + feature_list_sparse_values: A list of `Tensor` objects of type `feature_list_sparse_types`. + feature_list_sparse_shapes: A list with the same length as `feature_list_sparse_keys` of `Tensor` objects with type `int64`. + feature_list_dense_values: A list of `Tensor` objects of type `feature_list_dense_types`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseSingleSequenceExample", name, serialized, + feature_list_dense_missing_assumed_empty, context_sparse_keys, + context_dense_keys, feature_list_sparse_keys, feature_list_dense_keys, + context_dense_defaults, debug_name, "context_sparse_types", + context_sparse_types, "feature_list_dense_types", + feature_list_dense_types, "context_dense_shapes", + context_dense_shapes, "feature_list_sparse_types", + feature_list_sparse_types, "feature_list_dense_shapes", + feature_list_dense_shapes) + _result = _ParseSingleSequenceExampleOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parse_single_sequence_example_eager_fallback( + serialized, feature_list_dense_missing_assumed_empty, + context_sparse_keys, context_dense_keys, feature_list_sparse_keys, + feature_list_dense_keys, context_dense_defaults, debug_name, + context_sparse_types=context_sparse_types, + feature_list_dense_types=feature_list_dense_types, + context_dense_shapes=context_dense_shapes, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_dense_shapes=feature_list_dense_shapes, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(context_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % context_sparse_keys) + _attr_Ncontext_sparse = len(context_sparse_keys) + if not isinstance(context_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % context_dense_keys) + _attr_Ncontext_dense = len(context_dense_keys) + if not isinstance(feature_list_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_sparse_keys) + _attr_Nfeature_list_sparse = len(feature_list_sparse_keys) + if not isinstance(feature_list_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_keys) + _attr_Nfeature_list_dense = len(feature_list_dense_keys) + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_single_sequence_example' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_single_sequence_example' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseSingleSequenceExample", serialized=serialized, + feature_list_dense_missing_assumed_empty=feature_list_dense_missing_assumed_empty, + context_sparse_keys=context_sparse_keys, + context_dense_keys=context_dense_keys, + feature_list_sparse_keys=feature_list_sparse_keys, + feature_list_dense_keys=feature_list_dense_keys, + context_dense_defaults=context_dense_defaults, + debug_name=debug_name, + context_sparse_types=context_sparse_types, + feature_list_dense_types=feature_list_dense_types, + context_dense_shapes=context_dense_shapes, + feature_list_sparse_types=feature_list_sparse_types, + feature_list_dense_shapes=feature_list_dense_shapes, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Ncontext_sparse", _op._get_attr_int("Ncontext_sparse"), + "Ncontext_dense", _op._get_attr_int("Ncontext_dense"), + "Nfeature_list_sparse", + _op._get_attr_int("Nfeature_list_sparse"), + "Nfeature_list_dense", _op._get_attr_int("Nfeature_list_dense"), + "context_sparse_types", _op.get_attr("context_sparse_types"), + "Tcontext_dense", _op.get_attr("Tcontext_dense"), + "feature_list_dense_types", + _op.get_attr("feature_list_dense_types"), + "context_dense_shapes", _op.get_attr("context_dense_shapes"), + "feature_list_sparse_types", + _op.get_attr("feature_list_sparse_types"), + "feature_list_dense_shapes", + _op.get_attr("feature_list_dense_shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseSingleSequenceExample", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_Ncontext_sparse]] + _result[_attr_Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + _attr_Ncontext_sparse]] + _result[2 + _attr_Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + _attr_Nfeature_list_sparse]] + _result[4 + _attr_Nfeature_list_sparse:] + _result = _result[:5] + [_result[5:5 + len(feature_list_sparse_types)]] + _result[5 + len(feature_list_sparse_types):] + _result = _result[:6] + [_result[6:6 + _attr_Nfeature_list_sparse]] + _result[6 + _attr_Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:]] + _result = _ParseSingleSequenceExampleOutput._make(_result) + return _result + +ParseSingleSequenceExample = tf_export("raw_ops.ParseSingleSequenceExample")(_ops.to_raw_op(parse_single_sequence_example)) + + +def parse_single_sequence_example_eager_fallback(serialized: Annotated[Any, _atypes.String], feature_list_dense_missing_assumed_empty: Annotated[Any, _atypes.String], context_sparse_keys: Annotated[List[Any], _atypes.String], context_dense_keys: Annotated[List[Any], _atypes.String], feature_list_sparse_keys: Annotated[List[Any], _atypes.String], feature_list_dense_keys: Annotated[List[Any], _atypes.String], context_dense_defaults, debug_name: Annotated[Any, _atypes.String], context_sparse_types, feature_list_dense_types, context_dense_shapes, feature_list_sparse_types, feature_list_dense_shapes, name, ctx): + if not isinstance(context_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % context_sparse_keys) + _attr_Ncontext_sparse = len(context_sparse_keys) + if not isinstance(context_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % context_dense_keys) + _attr_Ncontext_dense = len(context_dense_keys) + if not isinstance(feature_list_sparse_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_sparse_keys) + _attr_Nfeature_list_sparse = len(feature_list_sparse_keys) + if not isinstance(feature_list_dense_keys, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_keys' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_keys) + _attr_Nfeature_list_dense = len(feature_list_dense_keys) + if context_sparse_types is None: + context_sparse_types = [] + if not isinstance(context_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'context_sparse_types' argument to " + "'parse_single_sequence_example' Op, not %r." % context_sparse_types) + context_sparse_types = [_execute.make_type(_t, "context_sparse_types") for _t in context_sparse_types] + if feature_list_dense_types is None: + feature_list_dense_types = [] + if not isinstance(feature_list_dense_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_types' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_types) + feature_list_dense_types = [_execute.make_type(_t, "feature_list_dense_types") for _t in feature_list_dense_types] + if context_dense_shapes is None: + context_dense_shapes = [] + if not isinstance(context_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'context_dense_shapes' argument to " + "'parse_single_sequence_example' Op, not %r." % context_dense_shapes) + context_dense_shapes = [_execute.make_shape(_s, "context_dense_shapes") for _s in context_dense_shapes] + if feature_list_sparse_types is None: + feature_list_sparse_types = [] + if not isinstance(feature_list_sparse_types, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_sparse_types' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_sparse_types) + feature_list_sparse_types = [_execute.make_type(_t, "feature_list_sparse_types") for _t in feature_list_sparse_types] + if feature_list_dense_shapes is None: + feature_list_dense_shapes = [] + if not isinstance(feature_list_dense_shapes, (list, tuple)): + raise TypeError( + "Expected list for 'feature_list_dense_shapes' argument to " + "'parse_single_sequence_example' Op, not %r." % feature_list_dense_shapes) + feature_list_dense_shapes = [_execute.make_shape(_s, "feature_list_dense_shapes") for _s in feature_list_dense_shapes] + _attr_Tcontext_dense, context_dense_defaults = _execute.convert_to_mixed_eager_tensors(context_dense_defaults, ctx) + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + feature_list_dense_missing_assumed_empty = _ops.convert_to_tensor(feature_list_dense_missing_assumed_empty, _dtypes.string) + context_sparse_keys = _ops.convert_n_to_tensor(context_sparse_keys, _dtypes.string) + context_dense_keys = _ops.convert_n_to_tensor(context_dense_keys, _dtypes.string) + feature_list_sparse_keys = _ops.convert_n_to_tensor(feature_list_sparse_keys, _dtypes.string) + feature_list_dense_keys = _ops.convert_n_to_tensor(feature_list_dense_keys, _dtypes.string) + debug_name = _ops.convert_to_tensor(debug_name, _dtypes.string) + _inputs_flat = [serialized, feature_list_dense_missing_assumed_empty] + list(context_sparse_keys) + list(context_dense_keys) + list(feature_list_sparse_keys) + list(feature_list_dense_keys) + list(context_dense_defaults) + [debug_name] + _attrs = ("Ncontext_sparse", _attr_Ncontext_sparse, "Ncontext_dense", + _attr_Ncontext_dense, "Nfeature_list_sparse", _attr_Nfeature_list_sparse, + "Nfeature_list_dense", _attr_Nfeature_list_dense, "context_sparse_types", + context_sparse_types, "Tcontext_dense", _attr_Tcontext_dense, + "feature_list_dense_types", feature_list_dense_types, + "context_dense_shapes", context_dense_shapes, "feature_list_sparse_types", + feature_list_sparse_types, "feature_list_dense_shapes", + feature_list_dense_shapes) + _result = _execute.execute(b"ParseSingleSequenceExample", + _attr_Ncontext_sparse + len(context_sparse_types) + + _attr_Ncontext_sparse + + len(context_dense_defaults) + + _attr_Nfeature_list_sparse + + len(feature_list_sparse_types) + + _attr_Nfeature_list_sparse + + len(feature_list_dense_types), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseSingleSequenceExample", _inputs_flat, _attrs, _result) + _result = [_result[:_attr_Ncontext_sparse]] + _result[_attr_Ncontext_sparse:] + _result = _result[:1] + [_result[1:1 + len(context_sparse_types)]] + _result[1 + len(context_sparse_types):] + _result = _result[:2] + [_result[2:2 + _attr_Ncontext_sparse]] + _result[2 + _attr_Ncontext_sparse:] + _result = _result[:3] + [_result[3:3 + len(context_dense_defaults)]] + _result[3 + len(context_dense_defaults):] + _result = _result[:4] + [_result[4:4 + _attr_Nfeature_list_sparse]] + _result[4 + _attr_Nfeature_list_sparse:] + _result = _result[:5] + [_result[5:5 + len(feature_list_sparse_types)]] + _result[5 + len(feature_list_sparse_types):] + _result = _result[:6] + [_result[6:6 + _attr_Nfeature_list_sparse]] + _result[6 + _attr_Nfeature_list_sparse:] + _result = _result[:7] + [_result[7:]] + _result = _ParseSingleSequenceExampleOutput._make(_result) + return _result + + +TV_ParseTensor_out_type = TypeVar("TV_ParseTensor_out_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.parse_tensor', v1=['io.parse_tensor', 'parse_tensor']) +@deprecated_endpoints('parse_tensor') +def parse_tensor(serialized: Annotated[Any, _atypes.String], out_type: TV_ParseTensor_out_type, name=None) -> Annotated[Any, TV_ParseTensor_out_type]: + r"""Transforms a serialized tensorflow.TensorProto proto into a Tensor. + + Args: + serialized: A `Tensor` of type `string`. + A scalar string containing a serialized TensorProto proto. + out_type: A `tf.DType`. + The type of the serialized tensor. The provided type must match the + type of the serialized tensor and no implicit conversion will take place. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParseTensor", name, serialized, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_parse_tensor( + (serialized, out_type, name,), None) + if _result is not NotImplemented: + return _result + return parse_tensor_eager_fallback( + serialized, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + parse_tensor, (), dict(serialized=serialized, out_type=out_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_parse_tensor( + (serialized, out_type, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + out_type = _execute.make_type(out_type, "out_type") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParseTensor", serialized=serialized, out_type=out_type, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + parse_tensor, (), dict(serialized=serialized, out_type=out_type, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("out_type", _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParseTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParseTensor = tf_export("raw_ops.ParseTensor")(_ops.to_raw_op(parse_tensor)) +_dispatcher_for_parse_tensor = parse_tensor._tf_type_based_dispatcher.Dispatch + + +def parse_tensor_eager_fallback(serialized: Annotated[Any, _atypes.String], out_type: TV_ParseTensor_out_type, name, ctx) -> Annotated[Any, TV_ParseTensor_out_type]: + out_type = _execute.make_type(out_type, "out_type") + serialized = _ops.convert_to_tensor(serialized, _dtypes.string) + _inputs_flat = [serialized] + _attrs = ("out_type", out_type) + _result = _execute.execute(b"ParseTensor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParseTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SerializeTensor_T = TypeVar("TV_SerializeTensor_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def serialize_tensor(tensor: Annotated[Any, TV_SerializeTensor_T], name=None) -> Annotated[Any, _atypes.String]: + r"""Transforms a Tensor into a serialized TensorProto proto. + + Args: + tensor: A `Tensor`. A Tensor of type `T`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SerializeTensor", name, tensor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return serialize_tensor_eager_fallback( + tensor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SerializeTensor", tensor=tensor, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SerializeTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SerializeTensor = tf_export("raw_ops.SerializeTensor")(_ops.to_raw_op(serialize_tensor)) + + +def serialize_tensor_eager_fallback(tensor: Annotated[Any, TV_SerializeTensor_T], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _inputs_flat = [tensor] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SerializeTensor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SerializeTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StringToNumber_out_type = TypeVar("TV_StringToNumber_out_type", _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) + +def string_to_number(string_tensor: Annotated[Any, _atypes.String], out_type:TV_StringToNumber_out_type=_dtypes.float32, name=None) -> Annotated[Any, TV_StringToNumber_out_type]: + r"""Converts each string in the input Tensor to the specified numeric type. + + (Note that int32 overflow results in an error while float overflow + results in a rounded value.) + + Example: + + >>> strings = ["5.0", "3.0", "7.0"] + >>> tf.strings.to_number(strings) + + + Args: + string_tensor: A `Tensor` of type `string`. + out_type: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.float32`. + The numeric type to interpret each string in `string_tensor` as. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringToNumber", name, string_tensor, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_to_number_eager_fallback( + string_tensor, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.float32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringToNumber", string_tensor=string_tensor, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("out_type", _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringToNumber", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringToNumber = tf_export("raw_ops.StringToNumber")(_ops.to_raw_op(string_to_number)) + + +def string_to_number_eager_fallback(string_tensor: Annotated[Any, _atypes.String], out_type: TV_StringToNumber_out_type, name, ctx) -> Annotated[Any, TV_StringToNumber_out_type]: + if out_type is None: + out_type = _dtypes.float32 + out_type = _execute.make_type(out_type, "out_type") + string_tensor = _ops.convert_to_tensor(string_tensor, _dtypes.string) + _inputs_flat = [string_tensor] + _attrs = ("out_type", out_type) + _result = _execute.execute(b"StringToNumber", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringToNumber", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d11841e1e6d04640feb65ddee358a986aa12b817 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_array_ops.py @@ -0,0 +1,525 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_RaggedCrossOutput = collections.namedtuple( + "RaggedCross", + ["output_values", "output_row_splits"]) + + +TV_RaggedCross_out_values_type = TypeVar("TV_RaggedCross_out_values_type", _atypes.Int64, _atypes.String) +TV_RaggedCross_out_row_splits_type = TypeVar("TV_RaggedCross_out_row_splits_type", _atypes.Int32, _atypes.Int64) + +def ragged_cross(ragged_values, ragged_row_splits, sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_values, sparse_shape: Annotated[List[Any], _atypes.Int64], dense_inputs, input_order: str, hashed_output: bool, num_buckets: int, hash_key: int, out_values_type: TV_RaggedCross_out_values_type, out_row_splits_type: TV_RaggedCross_out_row_splits_type, name=None): + r"""Generates a feature cross from a list of tensors, and returns it as a +RaggedTensor. See `tf.ragged.cross` for more details. + + Args: + ragged_values: A list of `Tensor` objects with types from: `int64`, `string`. + The values tensor for each RaggedTensor input. + ragged_row_splits: A list of `Tensor` objects with types from: `int32`, `int64`. + The row_splits tensor for each RaggedTensor input. + sparse_indices: A list of `Tensor` objects with type `int64`. + The indices tensor for each SparseTensor input. + sparse_values: A list of `Tensor` objects with types from: `int64`, `string`. + The values tensor for each SparseTensor input. + sparse_shape: A list with the same length as `sparse_indices` of `Tensor` objects with type `int64`. + The dense_shape tensor for each SparseTensor input. + dense_inputs: A list of `Tensor` objects with types from: `int64`, `string`. + The tf.Tensor inputs. + input_order: A `string`. + String specifying the tensor type for each input. The `i`th character in + this string specifies the type of the `i`th input, and is one of: 'R' (ragged), + 'D' (dense), or 'S' (sparse). This attr is used to ensure that the crossed + values are combined in the order of the inputs from the call to tf.ragged.cross. + hashed_output: A `bool`. + num_buckets: An `int` that is `>= 0`. + hash_key: An `int`. + out_values_type: A `tf.DType` from: `tf.int64, tf.string`. + out_row_splits_type: A `tf.DType` from: `tf.int32, tf.int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_values, output_row_splits). + + output_values: A `Tensor` of type `out_values_type`. + output_row_splits: A `Tensor` of type `out_row_splits_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedCross", name, ragged_values, ragged_row_splits, + sparse_indices, sparse_values, sparse_shape, dense_inputs, + "input_order", input_order, "hashed_output", hashed_output, + "num_buckets", num_buckets, "hash_key", hash_key, "out_values_type", + out_values_type, "out_row_splits_type", out_row_splits_type) + _result = _RaggedCrossOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_cross_eager_fallback( + ragged_values, ragged_row_splits, sparse_indices, sparse_values, + sparse_shape, dense_inputs, input_order=input_order, + hashed_output=hashed_output, num_buckets=num_buckets, + hash_key=hash_key, out_values_type=out_values_type, + out_row_splits_type=out_row_splits_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'ragged_cross' Op, not %r." % sparse_indices) + _attr_Nsparse = len(sparse_indices) + if not isinstance(sparse_shape, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_shape' argument to " + "'ragged_cross' Op, not %r." % sparse_shape) + if len(sparse_shape) != _attr_Nsparse: + raise ValueError( + "List argument 'sparse_shape' to 'ragged_cross' Op with length %d " + "must match length %d of argument 'sparse_indices'." % + (len(sparse_shape), _attr_Nsparse)) + input_order = _execute.make_str(input_order, "input_order") + hashed_output = _execute.make_bool(hashed_output, "hashed_output") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + hash_key = _execute.make_int(hash_key, "hash_key") + out_values_type = _execute.make_type(out_values_type, "out_values_type") + out_row_splits_type = _execute.make_type(out_row_splits_type, "out_row_splits_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedCross", ragged_values=ragged_values, + ragged_row_splits=ragged_row_splits, + sparse_indices=sparse_indices, + sparse_values=sparse_values, sparse_shape=sparse_shape, + dense_inputs=dense_inputs, input_order=input_order, + hashed_output=hashed_output, num_buckets=num_buckets, + hash_key=hash_key, out_values_type=out_values_type, + out_row_splits_type=out_row_splits_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Nsparse", _op._get_attr_int("Nsparse"), "input_order", + _op.get_attr("input_order"), "hashed_output", + _op._get_attr_bool("hashed_output"), "num_buckets", + _op._get_attr_int("num_buckets"), "hash_key", + _op._get_attr_int("hash_key"), "ragged_values_types", + _op.get_attr("ragged_values_types"), "ragged_splits_types", + _op.get_attr("ragged_splits_types"), "sparse_values_types", + _op.get_attr("sparse_values_types"), "dense_types", + _op.get_attr("dense_types"), "out_values_type", + _op._get_attr_type("out_values_type"), "out_row_splits_type", + _op._get_attr_type("out_row_splits_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedCross", _inputs_flat, _attrs, _result) + _result = _RaggedCrossOutput._make(_result) + return _result + +RaggedCross = tf_export("raw_ops.RaggedCross")(_ops.to_raw_op(ragged_cross)) + + +def ragged_cross_eager_fallback(ragged_values, ragged_row_splits, sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_values, sparse_shape: Annotated[List[Any], _atypes.Int64], dense_inputs, input_order: str, hashed_output: bool, num_buckets: int, hash_key: int, out_values_type: TV_RaggedCross_out_values_type, out_row_splits_type: TV_RaggedCross_out_row_splits_type, name, ctx): + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'ragged_cross' Op, not %r." % sparse_indices) + _attr_Nsparse = len(sparse_indices) + if not isinstance(sparse_shape, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_shape' argument to " + "'ragged_cross' Op, not %r." % sparse_shape) + if len(sparse_shape) != _attr_Nsparse: + raise ValueError( + "List argument 'sparse_shape' to 'ragged_cross' Op with length %d " + "must match length %d of argument 'sparse_indices'." % + (len(sparse_shape), _attr_Nsparse)) + input_order = _execute.make_str(input_order, "input_order") + hashed_output = _execute.make_bool(hashed_output, "hashed_output") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + hash_key = _execute.make_int(hash_key, "hash_key") + out_values_type = _execute.make_type(out_values_type, "out_values_type") + out_row_splits_type = _execute.make_type(out_row_splits_type, "out_row_splits_type") + _attr_ragged_values_types, ragged_values = _execute.convert_to_mixed_eager_tensors(ragged_values, ctx) + _attr_ragged_splits_types, ragged_row_splits = _execute.convert_to_mixed_eager_tensors(ragged_row_splits, ctx) + _attr_sparse_values_types, sparse_values = _execute.convert_to_mixed_eager_tensors(sparse_values, ctx) + _attr_dense_types, dense_inputs = _execute.convert_to_mixed_eager_tensors(dense_inputs, ctx) + sparse_indices = _ops.convert_n_to_tensor(sparse_indices, _dtypes.int64) + sparse_shape = _ops.convert_n_to_tensor(sparse_shape, _dtypes.int64) + _inputs_flat = list(ragged_values) + list(ragged_row_splits) + list(sparse_indices) + list(sparse_values) + list(sparse_shape) + list(dense_inputs) + _attrs = ("Nsparse", _attr_Nsparse, "input_order", input_order, + "hashed_output", hashed_output, "num_buckets", num_buckets, "hash_key", + hash_key, "ragged_values_types", _attr_ragged_values_types, + "ragged_splits_types", _attr_ragged_splits_types, "sparse_values_types", + _attr_sparse_values_types, "dense_types", _attr_dense_types, + "out_values_type", out_values_type, "out_row_splits_type", + out_row_splits_type) + _result = _execute.execute(b"RaggedCross", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedCross", _inputs_flat, _attrs, _result) + _result = _RaggedCrossOutput._make(_result) + return _result + +_RaggedFillEmptyRowsOutput = collections.namedtuple( + "RaggedFillEmptyRows", + ["output_value_rowids", "output_values", "empty_row_indicator", "reverse_index_map"]) + + +TV_RaggedFillEmptyRows_T = TypeVar("TV_RaggedFillEmptyRows_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ragged_fill_empty_rows') +def ragged_fill_empty_rows(value_rowids: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedFillEmptyRows_T], nrows: Annotated[Any, _atypes.Int64], default_value: Annotated[Any, TV_RaggedFillEmptyRows_T], name=None): + r"""TODO: add doc. + + Args: + value_rowids: A `Tensor` of type `int64`. + values: A `Tensor`. + nrows: A `Tensor` of type `int64`. + default_value: A `Tensor`. Must have the same type as `values`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_value_rowids, output_values, empty_row_indicator, reverse_index_map). + + output_value_rowids: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `values`. + empty_row_indicator: A `Tensor` of type `bool`. + reverse_index_map: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedFillEmptyRows", name, value_rowids, values, nrows, + default_value) + _result = _RaggedFillEmptyRowsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ragged_fill_empty_rows( + (value_rowids, values, nrows, default_value, name,), None) + if _result is not NotImplemented: + return _result + return ragged_fill_empty_rows_eager_fallback( + value_rowids, values, nrows, default_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ragged_fill_empty_rows, (), dict(value_rowids=value_rowids, + values=values, nrows=nrows, + default_value=default_value, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ragged_fill_empty_rows( + (value_rowids, values, nrows, default_value, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedFillEmptyRows", value_rowids=value_rowids, values=values, + nrows=nrows, default_value=default_value, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ragged_fill_empty_rows, (), dict(value_rowids=value_rowids, + values=values, nrows=nrows, + default_value=default_value, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedFillEmptyRows", _inputs_flat, _attrs, _result) + _result = _RaggedFillEmptyRowsOutput._make(_result) + return _result + +RaggedFillEmptyRows = tf_export("raw_ops.RaggedFillEmptyRows")(_ops.to_raw_op(ragged_fill_empty_rows)) +_dispatcher_for_ragged_fill_empty_rows = ragged_fill_empty_rows._tf_type_based_dispatcher.Dispatch + + +def ragged_fill_empty_rows_eager_fallback(value_rowids: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_RaggedFillEmptyRows_T], nrows: Annotated[Any, _atypes.Int64], default_value: Annotated[Any, TV_RaggedFillEmptyRows_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([values, default_value], ctx, []) + (values, default_value) = _inputs_T + value_rowids = _ops.convert_to_tensor(value_rowids, _dtypes.int64) + nrows = _ops.convert_to_tensor(nrows, _dtypes.int64) + _inputs_flat = [value_rowids, values, nrows, default_value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RaggedFillEmptyRows", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedFillEmptyRows", _inputs_flat, _attrs, _result) + _result = _RaggedFillEmptyRowsOutput._make(_result) + return _result + +_RaggedFillEmptyRowsGradOutput = collections.namedtuple( + "RaggedFillEmptyRowsGrad", + ["d_values", "d_default_value"]) + + +TV_RaggedFillEmptyRowsGrad_T = TypeVar("TV_RaggedFillEmptyRowsGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ragged_fill_empty_rows_grad') +def ragged_fill_empty_rows_grad(reverse_index_map: Annotated[Any, _atypes.Int64], grad_values: Annotated[Any, TV_RaggedFillEmptyRowsGrad_T], name=None): + r"""TODO: add doc. + + Args: + reverse_index_map: A `Tensor` of type `int64`. + grad_values: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d_values, d_default_value). + + d_values: A `Tensor`. Has the same type as `grad_values`. + d_default_value: A `Tensor`. Has the same type as `grad_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedFillEmptyRowsGrad", name, reverse_index_map, grad_values) + _result = _RaggedFillEmptyRowsGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ragged_fill_empty_rows_grad( + (reverse_index_map, grad_values, name,), None) + if _result is not NotImplemented: + return _result + return ragged_fill_empty_rows_grad_eager_fallback( + reverse_index_map, grad_values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ragged_fill_empty_rows_grad, (), dict(reverse_index_map=reverse_index_map, + grad_values=grad_values, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ragged_fill_empty_rows_grad( + (reverse_index_map, grad_values, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedFillEmptyRowsGrad", reverse_index_map=reverse_index_map, + grad_values=grad_values, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ragged_fill_empty_rows_grad, (), dict(reverse_index_map=reverse_index_map, + grad_values=grad_values, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedFillEmptyRowsGrad", _inputs_flat, _attrs, _result) + _result = _RaggedFillEmptyRowsGradOutput._make(_result) + return _result + +RaggedFillEmptyRowsGrad = tf_export("raw_ops.RaggedFillEmptyRowsGrad")(_ops.to_raw_op(ragged_fill_empty_rows_grad)) +_dispatcher_for_ragged_fill_empty_rows_grad = ragged_fill_empty_rows_grad._tf_type_based_dispatcher.Dispatch + + +def ragged_fill_empty_rows_grad_eager_fallback(reverse_index_map: Annotated[Any, _atypes.Int64], grad_values: Annotated[Any, TV_RaggedFillEmptyRowsGrad_T], name, ctx): + _attr_T, (grad_values,) = _execute.args_to_matching_eager([grad_values], ctx, []) + reverse_index_map = _ops.convert_to_tensor(reverse_index_map, _dtypes.int64) + _inputs_flat = [reverse_index_map, grad_values] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RaggedFillEmptyRowsGrad", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedFillEmptyRowsGrad", _inputs_flat, _attrs, _result) + _result = _RaggedFillEmptyRowsGradOutput._make(_result) + return _result + +_RaggedGatherOutput = collections.namedtuple( + "RaggedGather", + ["output_nested_splits", "output_dense_values"]) + + +TV_RaggedGather_Tvalues = TypeVar("TV_RaggedGather_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedGather_Tindices = TypeVar("TV_RaggedGather_Tindices", _atypes.Int32, _atypes.Int64) +TV_RaggedGather_Tsplits = TypeVar("TV_RaggedGather_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_gather(params_nested_splits: Annotated[List[Any], TV_RaggedGather_Tsplits], params_dense_values: Annotated[Any, TV_RaggedGather_Tvalues], indices: Annotated[Any, TV_RaggedGather_Tindices], OUTPUT_RAGGED_RANK: int, name=None): + r"""Gather ragged slices from `params` axis `0` according to `indices`. + + Outputs a `RaggedTensor` output composed from `output_dense_values` and + `output_nested_splits`, such that: + + ```python + output.shape = indices.shape + params.shape[1:] + output.ragged_rank = indices.shape.ndims + params.ragged_rank + output[i...j, d0...dn] = params[indices[i...j], d0...dn] + ``` + + where + + * `params = + ragged.from_nested_row_splits(params_dense_values, params_nested_splits)` + provides the values that should be gathered. + * `indices` ia a dense tensor with dtype `int32` or `int64`, indicating which + values should be gathered. + * `output = + ragged.from_nested_row_splits(output_dense_values, output_nested_splits)` + is the output tensor. + + (Note: This c++ op is used to implement the higher-level python + `tf.ragged.gather` op, which also supports ragged indices.) + + Args: + params_nested_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + The `nested_row_splits` tensors that define the row-partitioning for the + `params` RaggedTensor input. + params_dense_values: A `Tensor`. + The `flat_values` for the `params` RaggedTensor. There was a terminology change + at the python level from dense_values to flat_values, so dense_values is the + deprecated name. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Indices in the outermost dimension of `params` of the values that should be + gathered. + OUTPUT_RAGGED_RANK: An `int` that is `>= 0`. + The ragged rank of the output RaggedTensor. `output_nested_splits` will contain + this number of `row_splits` tensors. This value should equal + `indices.shape.ndims + params.ragged_rank - 1`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_nested_splits, output_dense_values). + + output_nested_splits: A list of `OUTPUT_RAGGED_RANK` `Tensor` objects with the same type as `params_nested_splits`. + output_dense_values: A `Tensor`. Has the same type as `params_dense_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedGather", name, params_nested_splits, params_dense_values, + indices, "OUTPUT_RAGGED_RANK", OUTPUT_RAGGED_RANK) + _result = _RaggedGatherOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_gather_eager_fallback( + params_nested_splits, params_dense_values, indices, + OUTPUT_RAGGED_RANK=OUTPUT_RAGGED_RANK, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(params_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'params_nested_splits' argument to " + "'ragged_gather' Op, not %r." % params_nested_splits) + _attr_PARAMS_RAGGED_RANK = len(params_nested_splits) + OUTPUT_RAGGED_RANK = _execute.make_int(OUTPUT_RAGGED_RANK, "OUTPUT_RAGGED_RANK") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedGather", params_nested_splits=params_nested_splits, + params_dense_values=params_dense_values, + indices=indices, + OUTPUT_RAGGED_RANK=OUTPUT_RAGGED_RANK, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tvalues", _op._get_attr_type("Tvalues"), "Tindices", + _op._get_attr_type("Tindices"), "Tsplits", + _op._get_attr_type("Tsplits"), "PARAMS_RAGGED_RANK", + _op._get_attr_int("PARAMS_RAGGED_RANK"), "OUTPUT_RAGGED_RANK", + _op._get_attr_int("OUTPUT_RAGGED_RANK")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedGather", _inputs_flat, _attrs, _result) + _result = [_result[:OUTPUT_RAGGED_RANK]] + _result[OUTPUT_RAGGED_RANK:] + _result = _RaggedGatherOutput._make(_result) + return _result + +RaggedGather = tf_export("raw_ops.RaggedGather")(_ops.to_raw_op(ragged_gather)) + + +def ragged_gather_eager_fallback(params_nested_splits: Annotated[List[Any], TV_RaggedGather_Tsplits], params_dense_values: Annotated[Any, TV_RaggedGather_Tvalues], indices: Annotated[Any, TV_RaggedGather_Tindices], OUTPUT_RAGGED_RANK: int, name, ctx): + if not isinstance(params_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'params_nested_splits' argument to " + "'ragged_gather' Op, not %r." % params_nested_splits) + _attr_PARAMS_RAGGED_RANK = len(params_nested_splits) + OUTPUT_RAGGED_RANK = _execute.make_int(OUTPUT_RAGGED_RANK, "OUTPUT_RAGGED_RANK") + _attr_Tvalues, (params_dense_values,) = _execute.args_to_matching_eager([params_dense_values], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tsplits, params_nested_splits = _execute.args_to_matching_eager(list(params_nested_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = list(params_nested_splits) + [params_dense_values, indices] + _attrs = ("Tvalues", _attr_Tvalues, "Tindices", _attr_Tindices, "Tsplits", + _attr_Tsplits, "PARAMS_RAGGED_RANK", _attr_PARAMS_RAGGED_RANK, + "OUTPUT_RAGGED_RANK", OUTPUT_RAGGED_RANK) + _result = _execute.execute(b"RaggedGather", OUTPUT_RAGGED_RANK + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedGather", _inputs_flat, _attrs, _result) + _result = [_result[:OUTPUT_RAGGED_RANK]] + _result[OUTPUT_RAGGED_RANK:] + _result = _RaggedGatherOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_conversion_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_conversion_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b067a25a7589b86be54c5b34f2ae41757863fcd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_conversion_ops.py @@ -0,0 +1,544 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_RaggedTensorFromVariantOutput = collections.namedtuple( + "RaggedTensorFromVariant", + ["output_nested_splits", "output_dense_values"]) + + +TV_RaggedTensorFromVariant_Tvalues = TypeVar("TV_RaggedTensorFromVariant_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedTensorFromVariant_Tsplits = TypeVar("TV_RaggedTensorFromVariant_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_tensor_from_variant(encoded_ragged: Annotated[Any, _atypes.Variant], input_ragged_rank: int, output_ragged_rank: int, Tvalues: TV_RaggedTensorFromVariant_Tvalues, Tsplits:TV_RaggedTensorFromVariant_Tsplits=_dtypes.int64, name=None): + r"""Decodes a `variant` Tensor into a `RaggedTensor`. + + Decodes the given `variant` Tensor and returns a `RaggedTensor`. The input + could be a scalar, meaning it encodes a single `RaggedTensor` with ragged_rank + `output_ragged_rank`. It could also have an arbitrary rank, in which case each + element is decoded into a `RaggedTensor` with ragged_rank `input_ragged_rank` + and these are then stacked according to the input shape to output a single + `RaggedTensor` with ragged_rank `output_ragged_rank`. Each `variant` element in + the input Tensor is decoded by retrieving from the element a 1-D `variant` + Tensor with `input_ragged_rank + 1` Tensors, corresponding to the splits and + values of the decoded `RaggedTensor`. If `input_ragged_rank` is -1, then it is + inferred as `output_ragged_rank` - `rank(encoded_ragged)`. See + `RaggedTensorToVariant` for the corresponding encoding logic. + + Args: + encoded_ragged: A `Tensor` of type `variant`. + A `variant` Tensor containing encoded `RaggedTensor`s. + input_ragged_rank: An `int` that is `>= -1`. + The ragged rank of each encoded `RaggedTensor` component in the input. If set to + -1, this is inferred as `output_ragged_rank` - `rank(encoded_ragged)` + output_ragged_rank: An `int` that is `>= 0`. + The expected ragged rank of the output `RaggedTensor`. The following must hold: + `output_ragged_rank = rank(encoded_ragged) + input_ragged_rank`. + Tvalues: A `tf.DType`. + Tsplits: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_nested_splits, output_dense_values). + + output_nested_splits: A list of `output_ragged_rank` `Tensor` objects with type `Tsplits`. + output_dense_values: A `Tensor` of type `Tvalues`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedTensorFromVariant", name, encoded_ragged, + "input_ragged_rank", input_ragged_rank, "output_ragged_rank", + output_ragged_rank, "Tvalues", Tvalues, "Tsplits", Tsplits) + _result = _RaggedTensorFromVariantOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_tensor_from_variant_eager_fallback( + encoded_ragged, input_ragged_rank=input_ragged_rank, + output_ragged_rank=output_ragged_rank, Tvalues=Tvalues, + Tsplits=Tsplits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + input_ragged_rank = _execute.make_int(input_ragged_rank, "input_ragged_rank") + output_ragged_rank = _execute.make_int(output_ragged_rank, "output_ragged_rank") + Tvalues = _execute.make_type(Tvalues, "Tvalues") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedTensorFromVariant", encoded_ragged=encoded_ragged, + input_ragged_rank=input_ragged_rank, + output_ragged_rank=output_ragged_rank, + Tvalues=Tvalues, Tsplits=Tsplits, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("input_ragged_rank", _op._get_attr_int("input_ragged_rank"), + "output_ragged_rank", _op._get_attr_int("output_ragged_rank"), + "Tvalues", _op._get_attr_type("Tvalues"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedTensorFromVariant", _inputs_flat, _attrs, _result) + _result = [_result[:output_ragged_rank]] + _result[output_ragged_rank:] + _result = _RaggedTensorFromVariantOutput._make(_result) + return _result + +RaggedTensorFromVariant = tf_export("raw_ops.RaggedTensorFromVariant")(_ops.to_raw_op(ragged_tensor_from_variant)) + + +def ragged_tensor_from_variant_eager_fallback(encoded_ragged: Annotated[Any, _atypes.Variant], input_ragged_rank: int, output_ragged_rank: int, Tvalues: TV_RaggedTensorFromVariant_Tvalues, Tsplits: TV_RaggedTensorFromVariant_Tsplits, name, ctx): + input_ragged_rank = _execute.make_int(input_ragged_rank, "input_ragged_rank") + output_ragged_rank = _execute.make_int(output_ragged_rank, "output_ragged_rank") + Tvalues = _execute.make_type(Tvalues, "Tvalues") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + encoded_ragged = _ops.convert_to_tensor(encoded_ragged, _dtypes.variant) + _inputs_flat = [encoded_ragged] + _attrs = ("input_ragged_rank", input_ragged_rank, "output_ragged_rank", + output_ragged_rank, "Tvalues", Tvalues, "Tsplits", Tsplits) + _result = _execute.execute(b"RaggedTensorFromVariant", output_ragged_rank + + 1, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedTensorFromVariant", _inputs_flat, _attrs, _result) + _result = [_result[:output_ragged_rank]] + _result[output_ragged_rank:] + _result = _RaggedTensorFromVariantOutput._make(_result) + return _result + +_RaggedTensorToSparseOutput = collections.namedtuple( + "RaggedTensorToSparse", + ["sparse_indices", "sparse_values", "sparse_dense_shape"]) + + +TV_RaggedTensorToSparse_T = TypeVar("TV_RaggedTensorToSparse_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedTensorToSparse_Tsplits = TypeVar("TV_RaggedTensorToSparse_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_tensor_to_sparse(rt_nested_splits: Annotated[List[Any], TV_RaggedTensorToSparse_Tsplits], rt_dense_values: Annotated[Any, TV_RaggedTensorToSparse_T], name=None): + r"""Converts a `RaggedTensor` into a `SparseTensor` with the same values. + + input=ragged.from_nested_row_splits(rt_dense_values, rt_nested_splits) + output=SparseTensor(indices=sparse_indices, values=sparse_values, + dense_shape=sparse_dense_shape) + + Args: + rt_nested_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + The `row_splits` for the `RaggedTensor`. + rt_dense_values: A `Tensor`. The `flat_values` for the `RaggedTensor`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_dense_shape). + + sparse_indices: A `Tensor` of type `int64`. + sparse_values: A `Tensor`. Has the same type as `rt_dense_values`. + sparse_dense_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedTensorToSparse", name, rt_nested_splits, rt_dense_values) + _result = _RaggedTensorToSparseOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_tensor_to_sparse_eager_fallback( + rt_nested_splits, rt_dense_values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(rt_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'rt_nested_splits' argument to " + "'ragged_tensor_to_sparse' Op, not %r." % rt_nested_splits) + _attr_RAGGED_RANK = len(rt_nested_splits) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedTensorToSparse", rt_nested_splits=rt_nested_splits, + rt_dense_values=rt_dense_values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("RAGGED_RANK", _op._get_attr_int("RAGGED_RANK"), "T", + _op._get_attr_type("T"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedTensorToSparse", _inputs_flat, _attrs, _result) + _result = _RaggedTensorToSparseOutput._make(_result) + return _result + +RaggedTensorToSparse = tf_export("raw_ops.RaggedTensorToSparse")(_ops.to_raw_op(ragged_tensor_to_sparse)) + + +def ragged_tensor_to_sparse_eager_fallback(rt_nested_splits: Annotated[List[Any], TV_RaggedTensorToSparse_Tsplits], rt_dense_values: Annotated[Any, TV_RaggedTensorToSparse_T], name, ctx): + if not isinstance(rt_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'rt_nested_splits' argument to " + "'ragged_tensor_to_sparse' Op, not %r." % rt_nested_splits) + _attr_RAGGED_RANK = len(rt_nested_splits) + _attr_T, (rt_dense_values,) = _execute.args_to_matching_eager([rt_dense_values], ctx, []) + _attr_Tsplits, rt_nested_splits = _execute.args_to_matching_eager(list(rt_nested_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = list(rt_nested_splits) + [rt_dense_values] + _attrs = ("RAGGED_RANK", _attr_RAGGED_RANK, "T", _attr_T, "Tsplits", + _attr_Tsplits) + _result = _execute.execute(b"RaggedTensorToSparse", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedTensorToSparse", _inputs_flat, _attrs, _result) + _result = _RaggedTensorToSparseOutput._make(_result) + return _result + + +TV_RaggedTensorToTensor_T = TypeVar("TV_RaggedTensorToTensor_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedTensorToTensor_Tindex = TypeVar("TV_RaggedTensorToTensor_Tindex", _atypes.Int32, _atypes.Int64) +TV_RaggedTensorToTensor_Tshape = TypeVar("TV_RaggedTensorToTensor_Tshape", _atypes.Int32, _atypes.Int64) + +def ragged_tensor_to_tensor(shape: Annotated[Any, TV_RaggedTensorToTensor_Tshape], values: Annotated[Any, TV_RaggedTensorToTensor_T], default_value: Annotated[Any, TV_RaggedTensorToTensor_T], row_partition_tensors: Annotated[List[Any], TV_RaggedTensorToTensor_Tindex], row_partition_types, name=None) -> Annotated[Any, TV_RaggedTensorToTensor_T]: + r"""Create a dense tensor from a ragged tensor, possibly altering its shape. + + The `ragged_to_dense` op creates a dense tensor from a list of row partition + tensors, a value vector, and default values. If the shape is unspecified, the + minimal shape required to contain all the elements in the ragged tensor (the + natural shape) will be used. If some dimensions are left unspecified, then the + size of the natural shape is used in that dimension. + + The default_value will be broadcast to the output shape. After that, the values + from the ragged tensor overwrite the default values. Note that the default_value + must have less dimensions than the value. + + The row partition tensors are in the order of the dimensions. + At present, the types can be: + * "ROW_SPLITS": the row_splits tensor from the ragged tensor. + * "VALUE_ROWIDS": the value_rowids tensor from the ragged tensor. + * "FIRST_DIM_SIZE": if value_rowids is used for the first dimension, then it + is preceded by "FIRST_DIM_SIZE". + + Args: + shape: A `Tensor`. Must be one of the following types: `int64`, `int32`. + The desired shape of the output tensor. If left unspecified (empty), + the minimal shape required to contain all the elements in the ragged tensor + (the natural shape) will be used. If some dimensions are left unspecified, then + the size of the natural shape is used in that dimension. + + Note that dense dimensions cannot be modified by the shape argument. Trying to + change the size of a dense dimension will cause the op to fail. + Examples: + natural shape: [4, 5, 6] + shape: -1 + output shape: [4, 5, 6] + + natural shape: [4, 5, 6] + shape: [3, -1, 2] + output shape: [3, 5, 2] + + natural shape: [4, 5, 6] + shape: [3, 7, 2] + output shape: [3, 7, 2] + values: A `Tensor`. + A 1D tensor representing the values of the ragged tensor. + default_value: A `Tensor`. Must have the same type as `values`. + The default_value when the shape is larger than the ragged tensor. The + default_value is broadcast until it is the shape of the output tensor, and + then overwritten by values in the ragged tensor. The default value must be + compatible with this broadcast operation, and must have fewer dimensions than + the value tensor. + row_partition_tensors: A list of at least 1 `Tensor` objects with the same type in: `int64`, `int32`. + row_partition_types: A list of `strings`. + The types of the row partition tensors. At present, these can be: + * "ROW_SPLITS": the row_splits tensor from the ragged tensor. + * "VALUE_ROWIDS": the value_rowids tensor from the ragged tensor. + * "FIRST_DIM_SIZE": if value_rowids is used for the first dimension, then it + is preceeded by "FIRST_DIM_SIZE". + The tensors are in the order of the dimensions. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedTensorToTensor", name, shape, values, default_value, + row_partition_tensors, "row_partition_types", row_partition_types) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_tensor_to_tensor_eager_fallback( + shape, values, default_value, row_partition_tensors, + row_partition_types=row_partition_types, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(row_partition_tensors, (list, tuple)): + raise TypeError( + "Expected list for 'row_partition_tensors' argument to " + "'ragged_tensor_to_tensor' Op, not %r." % row_partition_tensors) + _attr_num_row_partition_tensors = len(row_partition_tensors) + if not isinstance(row_partition_types, (list, tuple)): + raise TypeError( + "Expected list for 'row_partition_types' argument to " + "'ragged_tensor_to_tensor' Op, not %r." % row_partition_types) + row_partition_types = [_execute.make_str(_s, "row_partition_types") for _s in row_partition_types] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedTensorToTensor", shape=shape, values=values, + default_value=default_value, + row_partition_tensors=row_partition_tensors, + row_partition_types=row_partition_types, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindex", + _op._get_attr_type("Tindex"), "Tshape", + _op._get_attr_type("Tshape"), "num_row_partition_tensors", + _op._get_attr_int("num_row_partition_tensors"), + "row_partition_types", _op.get_attr("row_partition_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedTensorToTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RaggedTensorToTensor = tf_export("raw_ops.RaggedTensorToTensor")(_ops.to_raw_op(ragged_tensor_to_tensor)) + + +def ragged_tensor_to_tensor_eager_fallback(shape: Annotated[Any, TV_RaggedTensorToTensor_Tshape], values: Annotated[Any, TV_RaggedTensorToTensor_T], default_value: Annotated[Any, TV_RaggedTensorToTensor_T], row_partition_tensors: Annotated[List[Any], TV_RaggedTensorToTensor_Tindex], row_partition_types, name, ctx) -> Annotated[Any, TV_RaggedTensorToTensor_T]: + if not isinstance(row_partition_tensors, (list, tuple)): + raise TypeError( + "Expected list for 'row_partition_tensors' argument to " + "'ragged_tensor_to_tensor' Op, not %r." % row_partition_tensors) + _attr_num_row_partition_tensors = len(row_partition_tensors) + if not isinstance(row_partition_types, (list, tuple)): + raise TypeError( + "Expected list for 'row_partition_types' argument to " + "'ragged_tensor_to_tensor' Op, not %r." % row_partition_types) + row_partition_types = [_execute.make_str(_s, "row_partition_types") for _s in row_partition_types] + _attr_T, _inputs_T = _execute.args_to_matching_eager([values, default_value], ctx, []) + (values, default_value) = _inputs_T + _attr_Tindex, row_partition_tensors = _execute.args_to_matching_eager(list(row_partition_tensors), ctx, [_dtypes.int64, _dtypes.int32, ]) + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int64, _dtypes.int32, ]) + _inputs_flat = [shape, values, default_value] + list(row_partition_tensors) + _attrs = ("T", _attr_T, "Tindex", _attr_Tindex, "Tshape", _attr_Tshape, + "num_row_partition_tensors", _attr_num_row_partition_tensors, + "row_partition_types", row_partition_types) + _result = _execute.execute(b"RaggedTensorToTensor", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedTensorToTensor", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RaggedTensorToVariant_Tvalues = TypeVar("TV_RaggedTensorToVariant_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedTensorToVariant_Tsplits = TypeVar("TV_RaggedTensorToVariant_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_tensor_to_variant(rt_nested_splits: Annotated[List[Any], TV_RaggedTensorToVariant_Tsplits], rt_dense_values: Annotated[Any, TV_RaggedTensorToVariant_Tvalues], batched_input: bool, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Encodes a `RaggedTensor` into a `variant` Tensor. + + + Encodes the given `RaggedTensor` and returns a `variant` Tensor. If + `batched_input` is True, then input `RaggedTensor` is unbatched along the + zero-th dimension, each component `RaggedTensor` is encoded into a scalar + `variant` Tensor, and these are stacked to return a 1-D `variant` Tensor. + If `batched_input` is False, then the input `RaggedTensor` is encoded as is and + a scalar `variant` Tensor is returned. A `RaggedTensor` is encoded by first + creating a 1-D `variant` Tensor with `ragged_rank + 1` elements, containing the + splits and values Tensors of the `RaggedTensor`. Then the 1-D `variant` Tensor + is wrapped in a scalar `variant` Tensor. See `RaggedTensorFromVariant` for the + corresponding decoding logic. + + Args: + rt_nested_splits: A list of `Tensor` objects with the same type in: `int32`, `int64`. + A list of one or more Tensors representing the splits of the input + `RaggedTensor`. + rt_dense_values: A `Tensor`. + A Tensor representing the values of the input `RaggedTensor`. + batched_input: A `bool`. + A `bool` denoting whether the input is a batched `RaggedTensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedTensorToVariant", name, rt_nested_splits, + rt_dense_values, "batched_input", batched_input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_tensor_to_variant_eager_fallback( + rt_nested_splits, rt_dense_values, batched_input=batched_input, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(rt_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'rt_nested_splits' argument to " + "'ragged_tensor_to_variant' Op, not %r." % rt_nested_splits) + _attr_RAGGED_RANK = len(rt_nested_splits) + batched_input = _execute.make_bool(batched_input, "batched_input") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedTensorToVariant", rt_nested_splits=rt_nested_splits, + rt_dense_values=rt_dense_values, + batched_input=batched_input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("RAGGED_RANK", _op._get_attr_int("RAGGED_RANK"), "Tvalues", + _op._get_attr_type("Tvalues"), "Tsplits", + _op._get_attr_type("Tsplits"), "batched_input", + _op._get_attr_bool("batched_input")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedTensorToVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RaggedTensorToVariant = tf_export("raw_ops.RaggedTensorToVariant")(_ops.to_raw_op(ragged_tensor_to_variant)) + + +def ragged_tensor_to_variant_eager_fallback(rt_nested_splits: Annotated[List[Any], TV_RaggedTensorToVariant_Tsplits], rt_dense_values: Annotated[Any, TV_RaggedTensorToVariant_Tvalues], batched_input: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(rt_nested_splits, (list, tuple)): + raise TypeError( + "Expected list for 'rt_nested_splits' argument to " + "'ragged_tensor_to_variant' Op, not %r." % rt_nested_splits) + _attr_RAGGED_RANK = len(rt_nested_splits) + batched_input = _execute.make_bool(batched_input, "batched_input") + _attr_Tvalues, (rt_dense_values,) = _execute.args_to_matching_eager([rt_dense_values], ctx, []) + _attr_Tsplits, rt_nested_splits = _execute.args_to_matching_eager(list(rt_nested_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = list(rt_nested_splits) + [rt_dense_values] + _attrs = ("RAGGED_RANK", _attr_RAGGED_RANK, "Tvalues", _attr_Tvalues, + "Tsplits", _attr_Tsplits, "batched_input", batched_input) + _result = _execute.execute(b"RaggedTensorToVariant", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedTensorToVariant", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RaggedTensorToVariantGradient_Tvalues = TypeVar("TV_RaggedTensorToVariantGradient_Tvalues", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_RaggedTensorToVariantGradient_Tsplits = TypeVar("TV_RaggedTensorToVariantGradient_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_tensor_to_variant_gradient(encoded_ragged_grad: Annotated[Any, _atypes.Variant], row_splits: Annotated[Any, TV_RaggedTensorToVariantGradient_Tsplits], dense_values_shape: Annotated[Any, _atypes.Int32], Tvalues: TV_RaggedTensorToVariantGradient_Tvalues, name=None) -> Annotated[Any, TV_RaggedTensorToVariantGradient_Tvalues]: + r"""Helper used to compute the gradient for `RaggedTensorToVariant`. + + Computes the gradient for the dense_values input to the RaggedTensorToVariant + op, given the variant-encoded ragged gradients of the outputs, along with + the outer row-splits and the shape of the dense-values that were provided as + inputs to the RaggedTensorToVariant op. + + Args: + encoded_ragged_grad: A `Tensor` of type `variant`. + A `variant` Tensor containing encoded `RaggedTensor` gradients. + row_splits: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Outermost row-splits that were used as input to the RaggedTensorToVariant op. + dense_values_shape: A `Tensor` of type `int32`. + Shape of the dense_values that was used as an input to the + RaggedTensorToVariant op. + Tvalues: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tvalues`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedTensorToVariantGradient", name, encoded_ragged_grad, + row_splits, dense_values_shape, "Tvalues", Tvalues) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_tensor_to_variant_gradient_eager_fallback( + encoded_ragged_grad, row_splits, dense_values_shape, + Tvalues=Tvalues, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tvalues = _execute.make_type(Tvalues, "Tvalues") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedTensorToVariantGradient", encoded_ragged_grad=encoded_ragged_grad, + row_splits=row_splits, + dense_values_shape=dense_values_shape, + Tvalues=Tvalues, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tvalues", _op._get_attr_type("Tvalues"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedTensorToVariantGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RaggedTensorToVariantGradient = tf_export("raw_ops.RaggedTensorToVariantGradient")(_ops.to_raw_op(ragged_tensor_to_variant_gradient)) + + +def ragged_tensor_to_variant_gradient_eager_fallback(encoded_ragged_grad: Annotated[Any, _atypes.Variant], row_splits: Annotated[Any, TV_RaggedTensorToVariantGradient_Tsplits], dense_values_shape: Annotated[Any, _atypes.Int32], Tvalues: TV_RaggedTensorToVariantGradient_Tvalues, name, ctx) -> Annotated[Any, TV_RaggedTensorToVariantGradient_Tvalues]: + Tvalues = _execute.make_type(Tvalues, "Tvalues") + _attr_Tsplits, (row_splits,) = _execute.args_to_matching_eager([row_splits], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + encoded_ragged_grad = _ops.convert_to_tensor(encoded_ragged_grad, _dtypes.variant) + dense_values_shape = _ops.convert_to_tensor(dense_values_shape, _dtypes.int32) + _inputs_flat = [encoded_ragged_grad, row_splits, dense_values_shape] + _attrs = ("Tvalues", Tvalues, "Tsplits", _attr_Tsplits) + _result = _execute.execute(b"RaggedTensorToVariantGradient", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedTensorToVariantGradient", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e7aa90eb3843e2a755557a77c2a1f93dca219d64 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_ragged_math_ops.py @@ -0,0 +1,120 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_RaggedRangeOutput = collections.namedtuple( + "RaggedRange", + ["rt_nested_splits", "rt_dense_values"]) + + +TV_RaggedRange_T = TypeVar("TV_RaggedRange_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Int32, _atypes.Int64) +TV_RaggedRange_Tsplits = TypeVar("TV_RaggedRange_Tsplits", _atypes.Int32, _atypes.Int64) + +def ragged_range(starts: Annotated[Any, TV_RaggedRange_T], limits: Annotated[Any, TV_RaggedRange_T], deltas: Annotated[Any, TV_RaggedRange_T], Tsplits:TV_RaggedRange_Tsplits=_dtypes.int64, name=None): + r"""Returns a `RaggedTensor` containing the specified sequences of numbers. + + + Returns a `RaggedTensor` `result` composed from `rt_dense_values` and + `rt_nested_splits`, such that + `result[i] = range(starts[i], limits[i], deltas[i])`. + + ```python + (rt_nested_splits, rt_dense_values) = ragged_range( + starts=[2, 5, 8], limits=[3, 5, 12], deltas=1) + result = tf.ragged.from_row_splits(rt_dense_values, rt_nested_splits) + print(result) + + ``` + + The input tensors `starts`, `limits`, and `deltas` may be scalars or vectors. + The vector inputs must all have the same size. Scalar inputs are broadcast + to match the size of the vector inputs. + + Args: + starts: A `Tensor`. Must be one of the following types: `bfloat16`, `float32`, `float64`, `int32`, `int64`. + The starts of each range. + limits: A `Tensor`. Must have the same type as `starts`. + The limits of each range. + deltas: A `Tensor`. Must have the same type as `starts`. + The deltas of each range. + Tsplits: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (rt_nested_splits, rt_dense_values). + + rt_nested_splits: A `Tensor` of type `Tsplits`. + rt_dense_values: A `Tensor`. Has the same type as `starts`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RaggedRange", name, starts, limits, deltas, "Tsplits", Tsplits) + _result = _RaggedRangeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return ragged_range_eager_fallback( + starts, limits, deltas, Tsplits=Tsplits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RaggedRange", starts=starts, limits=limits, deltas=deltas, + Tsplits=Tsplits, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RaggedRange", _inputs_flat, _attrs, _result) + _result = _RaggedRangeOutput._make(_result) + return _result + +RaggedRange = tf_export("raw_ops.RaggedRange")(_ops.to_raw_op(ragged_range)) + + +def ragged_range_eager_fallback(starts: Annotated[Any, TV_RaggedRange_T], limits: Annotated[Any, TV_RaggedRange_T], deltas: Annotated[Any, TV_RaggedRange_T], Tsplits: TV_RaggedRange_Tsplits, name, ctx): + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + _attr_T, _inputs_T = _execute.args_to_matching_eager([starts, limits, deltas], ctx, [_dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ], _dtypes.int32) + (starts, limits, deltas) = _inputs_T + _inputs_flat = [starts, limits, deltas] + _attrs = ("T", _attr_T, "Tsplits", Tsplits) + _result = _execute.execute(b"RaggedRange", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RaggedRange", _inputs_flat, _attrs, _result) + _result = _RaggedRangeOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_index_shuffle_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_index_shuffle_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8165ce335317d46c0c78b169e85b22d3f7b4d5be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_index_shuffle_ops.py @@ -0,0 +1,138 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_RandomIndexShuffle_dtype = TypeVar("TV_RandomIndexShuffle_dtype", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) +TV_RandomIndexShuffle_Tseed = TypeVar("TV_RandomIndexShuffle_Tseed", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('random_index_shuffle') +def random_index_shuffle(index: Annotated[Any, TV_RandomIndexShuffle_dtype], seed: Annotated[Any, TV_RandomIndexShuffle_Tseed], max_index: Annotated[Any, TV_RandomIndexShuffle_dtype], rounds:int=4, name=None) -> Annotated[Any, TV_RandomIndexShuffle_dtype]: + r"""Outputs the position of `value` in a permutation of [0, ..., max_index]. + + Output values are a bijection of the `index` for any combination and `seed` and `max_index`. + + If multiple inputs are vectors (matrix in case of seed) then the size of the + first dimension must match. + + The outputs are deterministic. + + Args: + index: A `Tensor`. Must be one of the following types: `int32`, `uint32`, `int64`, `uint64`. + A scalar tensor or a vector of dtype `dtype`. The index (or indices) to be shuffled. Must be within [0, max_index]. + seed: A `Tensor`. Must be one of the following types: `int32`, `uint32`, `int64`, `uint64`. + A tensor of dtype `Tseed` and shape [3] or [n, 3]. The random seed. + max_index: A `Tensor`. Must have the same type as `index`. + A scalar tensor or vector of dtype `dtype`. The upper bound(s) of the interval (inclusive). + rounds: An optional `int`. Defaults to `4`. + The number of rounds to use the in block cipher. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `index`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomIndexShuffle", name, index, seed, max_index, "rounds", + rounds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_random_index_shuffle( + (index, seed, max_index, rounds, name,), None) + if _result is not NotImplemented: + return _result + return random_index_shuffle_eager_fallback( + index, seed, max_index, rounds=rounds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + random_index_shuffle, (), dict(index=index, seed=seed, + max_index=max_index, rounds=rounds, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_random_index_shuffle( + (index, seed, max_index, rounds, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if rounds is None: + rounds = 4 + rounds = _execute.make_int(rounds, "rounds") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomIndexShuffle", index=index, seed=seed, max_index=max_index, + rounds=rounds, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + random_index_shuffle, (), dict(index=index, seed=seed, + max_index=max_index, rounds=rounds, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("rounds", _op._get_attr_int("rounds"), "dtype", + _op._get_attr_type("dtype"), "Tseed", + _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomIndexShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomIndexShuffle = tf_export("raw_ops.RandomIndexShuffle")(_ops.to_raw_op(random_index_shuffle)) +_dispatcher_for_random_index_shuffle = random_index_shuffle._tf_type_based_dispatcher.Dispatch + + +def random_index_shuffle_eager_fallback(index: Annotated[Any, TV_RandomIndexShuffle_dtype], seed: Annotated[Any, TV_RandomIndexShuffle_Tseed], max_index: Annotated[Any, TV_RandomIndexShuffle_dtype], rounds: int, name, ctx) -> Annotated[Any, TV_RandomIndexShuffle_dtype]: + if rounds is None: + rounds = 4 + rounds = _execute.make_int(rounds, "rounds") + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([index, max_index], ctx, [_dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, ]) + (index, max_index) = _inputs_dtype + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.uint32, _dtypes.int64, _dtypes.uint64, ]) + _inputs_flat = [index, seed, max_index] + _attrs = ("rounds", rounds, "dtype", _attr_dtype, "Tseed", _attr_Tseed) + _result = _execute.execute(b"RandomIndexShuffle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomIndexShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a999eefba38f68fcdff3a6ec041f0b299e2c717a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_random_ops.py @@ -0,0 +1,981 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Multinomial_T = TypeVar("TV_Multinomial_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_Multinomial_output_dtype = TypeVar("TV_Multinomial_output_dtype", _atypes.Int32, _atypes.Int64) + +def multinomial(logits: Annotated[Any, TV_Multinomial_T], num_samples: Annotated[Any, _atypes.Int32], seed:int=0, seed2:int=0, output_dtype:TV_Multinomial_output_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_Multinomial_output_dtype]: + r"""Draws samples from a multinomial distribution. + + Args: + logits: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` + represents the unnormalized log probabilities for all classes. + num_samples: A `Tensor` of type `int32`. + 0-D. Number of independent samples to draw for each row slice. + seed: An optional `int`. Defaults to `0`. + If either seed or seed2 is set to be non-zero, the internal random number + generator is seeded by the given seed. Otherwise, a random seed is used. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + output_dtype: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Multinomial", name, logits, num_samples, "seed", seed, "seed2", + seed2, "output_dtype", output_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return multinomial_eager_fallback( + logits, num_samples, seed=seed, seed2=seed2, + output_dtype=output_dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if output_dtype is None: + output_dtype = _dtypes.int64 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Multinomial", logits=logits, num_samples=num_samples, seed=seed, + seed2=seed2, output_dtype=output_dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "T", _op._get_attr_type("T"), + "output_dtype", _op._get_attr_type("output_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Multinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Multinomial = tf_export("raw_ops.Multinomial")(_ops.to_raw_op(multinomial)) + + +def multinomial_eager_fallback(logits: Annotated[Any, TV_Multinomial_T], num_samples: Annotated[Any, _atypes.Int32], seed: int, seed2: int, output_dtype: TV_Multinomial_output_dtype, name, ctx) -> Annotated[Any, TV_Multinomial_output_dtype]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if output_dtype is None: + output_dtype = _dtypes.int64 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _attr_T, (logits,) = _execute.args_to_matching_eager([logits], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + num_samples = _ops.convert_to_tensor(num_samples, _dtypes.int32) + _inputs_flat = [logits, num_samples] + _attrs = ("seed", seed, "seed2", seed2, "T", _attr_T, "output_dtype", + output_dtype) + _result = _execute.execute(b"Multinomial", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Multinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ParameterizedTruncatedNormal_dtype = TypeVar("TV_ParameterizedTruncatedNormal_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_ParameterizedTruncatedNormal_T = TypeVar("TV_ParameterizedTruncatedNormal_T", _atypes.Int32, _atypes.Int64) + +def parameterized_truncated_normal(shape: Annotated[Any, TV_ParameterizedTruncatedNormal_T], means: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], stdevs: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], minvals: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], maxvals: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_ParameterizedTruncatedNormal_dtype]: + r"""Outputs random values from a normal distribution. The parameters may each be a + + scalar which applies to the entire output, or a vector of length shape[0] which + stores the parameters for each batch. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. Batches are indexed by the 0th dimension. + means: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + The mean parameter of each batch. + stdevs: A `Tensor`. Must have the same type as `means`. + The standard deviation parameter of each batch. Must be greater than 0. + minvals: A `Tensor`. Must have the same type as `means`. + The minimum cutoff. May be -infinity. + maxvals: A `Tensor`. Must have the same type as `means`. + The maximum cutoff. May be +infinity, and must be more than the minval + for each batch. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `means`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ParameterizedTruncatedNormal", name, shape, means, stdevs, + minvals, maxvals, "seed", seed, "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return parameterized_truncated_normal_eager_fallback( + shape, means, stdevs, minvals, maxvals, seed=seed, seed2=seed2, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ParameterizedTruncatedNormal", shape=shape, means=means, + stdevs=stdevs, minvals=minvals, + maxvals=maxvals, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "dtype", + _op._get_attr_type("dtype"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ParameterizedTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ParameterizedTruncatedNormal = tf_export("raw_ops.ParameterizedTruncatedNormal")(_ops.to_raw_op(parameterized_truncated_normal)) + + +def parameterized_truncated_normal_eager_fallback(shape: Annotated[Any, TV_ParameterizedTruncatedNormal_T], means: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], stdevs: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], minvals: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], maxvals: Annotated[Any, TV_ParameterizedTruncatedNormal_dtype], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_ParameterizedTruncatedNormal_dtype]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([means, stdevs, minvals, maxvals], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, ]) + (means, stdevs, minvals, maxvals) = _inputs_dtype + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [shape, means, stdevs, minvals, maxvals] + _attrs = ("seed", seed, "seed2", seed2, "dtype", _attr_dtype, "T", _attr_T) + _result = _execute.execute(b"ParameterizedTruncatedNormal", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ParameterizedTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomGamma_S = TypeVar("TV_RandomGamma_S", _atypes.Int32, _atypes.Int64) +TV_RandomGamma_T = TypeVar("TV_RandomGamma_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def random_gamma(shape: Annotated[Any, TV_RandomGamma_S], alpha: Annotated[Any, TV_RandomGamma_T], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomGamma_T]: + r"""Outputs random values from the Gamma distribution(s) described by alpha. + + This op uses the algorithm by Marsaglia et al. to acquire samples via + transformation-rejection from pairs of uniform and normal random variables. + See http://dl.acm.org/citation.cfm?id=358414 + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D integer tensor. Shape of independent samples to draw from each + distribution described by the shape parameters given in alpha. + alpha: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + A tensor in which each scalar is a "shape" parameter describing the + associated gamma distribution. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `alpha`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomGamma", name, shape, alpha, "seed", seed, "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_gamma_eager_fallback( + shape, alpha, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomGamma", shape=shape, alpha=alpha, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "S", _op._get_attr_type("S"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomGamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomGamma = tf_export("raw_ops.RandomGamma")(_ops.to_raw_op(random_gamma)) + + +def random_gamma_eager_fallback(shape: Annotated[Any, TV_RandomGamma_S], alpha: Annotated[Any, TV_RandomGamma_T], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomGamma_T]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_T, (alpha,) = _execute.args_to_matching_eager([alpha], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [shape, alpha] + _attrs = ("seed", seed, "seed2", seed2, "S", _attr_S, "T", _attr_T) + _result = _execute.execute(b"RandomGamma", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomGamma", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomGammaGrad_T = TypeVar("TV_RandomGammaGrad_T", _atypes.Float32, _atypes.Float64) + +def random_gamma_grad(alpha: Annotated[Any, TV_RandomGammaGrad_T], sample: Annotated[Any, TV_RandomGammaGrad_T], name=None) -> Annotated[Any, TV_RandomGammaGrad_T]: + r"""Computes the derivative of a Gamma random sample w.r.t. `alpha`. + + Args: + alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`. + sample: A `Tensor`. Must have the same type as `alpha`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `alpha`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomGammaGrad", name, alpha, sample) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_gamma_grad_eager_fallback( + alpha, sample, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomGammaGrad", alpha=alpha, sample=sample, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomGammaGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomGammaGrad = tf_export("raw_ops.RandomGammaGrad")(_ops.to_raw_op(random_gamma_grad)) + + +def random_gamma_grad_eager_fallback(alpha: Annotated[Any, TV_RandomGammaGrad_T], sample: Annotated[Any, TV_RandomGammaGrad_T], name, ctx) -> Annotated[Any, TV_RandomGammaGrad_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([alpha, sample], ctx, [_dtypes.float32, _dtypes.float64, ]) + (alpha, sample) = _inputs_T + _inputs_flat = [alpha, sample] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"RandomGammaGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomGammaGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomPoisson_S = TypeVar("TV_RandomPoisson_S", _atypes.Int32, _atypes.Int64) +TV_RandomPoisson_dtype = TypeVar("TV_RandomPoisson_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def random_poisson(shape: Annotated[Any, TV_RandomPoisson_S], rate: Annotated[Any, TV_RandomPoisson_dtype], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomPoisson_dtype]: + r"""Use RandomPoissonV2 instead. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + rate: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + seed: An optional `int`. Defaults to `0`. + seed2: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `rate`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomPoisson", name, shape, rate, "seed", seed, "seed2", + seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_poisson_eager_fallback( + shape, rate, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomPoisson", shape=shape, rate=rate, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "S", _op._get_attr_type("S"), + "dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomPoisson", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomPoisson = tf_export("raw_ops.RandomPoisson")(_ops.to_raw_op(random_poisson)) + + +def random_poisson_eager_fallback(shape: Annotated[Any, TV_RandomPoisson_S], rate: Annotated[Any, TV_RandomPoisson_dtype], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomPoisson_dtype]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_dtype, (rate,) = _execute.args_to_matching_eager([rate], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [shape, rate] + _attrs = ("seed", seed, "seed2", seed2, "S", _attr_S, "dtype", _attr_dtype) + _result = _execute.execute(b"RandomPoisson", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomPoisson", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomPoissonV2_S = TypeVar("TV_RandomPoissonV2_S", _atypes.Int32, _atypes.Int64) +TV_RandomPoissonV2_R = TypeVar("TV_RandomPoissonV2_R", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_RandomPoissonV2_dtype = TypeVar("TV_RandomPoissonV2_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def random_poisson_v2(shape: Annotated[Any, TV_RandomPoissonV2_S], rate: Annotated[Any, TV_RandomPoissonV2_R], seed:int=0, seed2:int=0, dtype:TV_RandomPoissonV2_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_RandomPoissonV2_dtype]: + r"""Outputs random values from the Poisson distribution(s) described by rate. + + This op uses two algorithms, depending on rate. If rate >= 10, then + the algorithm by Hormann is used to acquire samples via + transformation-rejection. + See http://www.sciencedirect.com/science/article/pii/0167668793909974. + + Otherwise, Knuth's algorithm is used to acquire samples via multiplying uniform + random variables. + See Donald E. Knuth (1969). Seminumerical Algorithms. The Art of Computer + Programming, Volume 2. Addison Wesley + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 1-D integer tensor. Shape of independent samples to draw from each + distribution described by the shape parameters given in rate. + rate: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + A tensor in which each scalar is a "rate" parameter describing the + associated poisson distribution. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + dtype: An optional `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomPoissonV2", name, shape, rate, "seed", seed, "seed2", + seed2, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_poisson_v2_eager_fallback( + shape, rate, seed=seed, seed2=seed2, dtype=dtype, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomPoissonV2", shape=shape, rate=rate, seed=seed, seed2=seed2, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "S", _op._get_attr_type("S"), "R", + _op._get_attr_type("R"), "dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomPoissonV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomPoissonV2 = tf_export("raw_ops.RandomPoissonV2")(_ops.to_raw_op(random_poisson_v2)) + + +def random_poisson_v2_eager_fallback(shape: Annotated[Any, TV_RandomPoissonV2_S], rate: Annotated[Any, TV_RandomPoissonV2_R], seed: int, seed2: int, dtype: TV_RandomPoissonV2_dtype, name, ctx) -> Annotated[Any, TV_RandomPoissonV2_dtype]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_R, (rate,) = _execute.args_to_matching_eager([rate], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ], _dtypes.float64) + _inputs_flat = [shape, rate] + _attrs = ("seed", seed, "seed2", seed2, "S", _attr_S, "R", _attr_R, "dtype", + dtype) + _result = _execute.execute(b"RandomPoissonV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomPoissonV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomShuffle_T = TypeVar("TV_RandomShuffle_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def random_shuffle(value: Annotated[Any, TV_RandomShuffle_T], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomShuffle_T]: + r"""Randomly shuffles a tensor along its first dimension. + + The tensor is shuffled along dimension 0, such that each `value[j]` is mapped + to one and only one `output[i]`. For example, a mapping that might occur for a + 3x2 tensor is: + + ``` + [[1, 2], [[5, 6], + [3, 4], ==> [1, 2], + [5, 6]] [3, 4]] + ``` + + Args: + value: A `Tensor`. The tensor to be shuffled. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomShuffle", name, value, "seed", seed, "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_shuffle_eager_fallback( + value, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomShuffle", value=value, seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomShuffle = tf_export("raw_ops.RandomShuffle")(_ops.to_raw_op(random_shuffle)) + + +def random_shuffle_eager_fallback(value: Annotated[Any, TV_RandomShuffle_T], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomShuffle_T]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + _inputs_flat = [value] + _attrs = ("seed", seed, "seed2", seed2, "T", _attr_T) + _result = _execute.execute(b"RandomShuffle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomStandardNormal_dtype = TypeVar("TV_RandomStandardNormal_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_RandomStandardNormal_T = TypeVar("TV_RandomStandardNormal_T", _atypes.Int32, _atypes.Int64) + +def random_standard_normal(shape: Annotated[Any, TV_RandomStandardNormal_T], dtype: TV_RandomStandardNormal_dtype, seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomStandardNormal_dtype]: + r"""Outputs random values from a normal distribution. + + The generated values will have mean 0 and standard deviation 1. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + dtype: A `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. + The type of the output. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomStandardNormal", name, shape, "seed", seed, "seed2", + seed2, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_standard_normal_eager_fallback( + shape, seed=seed, seed2=seed2, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomStandardNormal", shape=shape, dtype=dtype, seed=seed, + seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "dtype", + _op._get_attr_type("dtype"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomStandardNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomStandardNormal = tf_export("raw_ops.RandomStandardNormal")(_ops.to_raw_op(random_standard_normal)) + + +def random_standard_normal_eager_fallback(shape: Annotated[Any, TV_RandomStandardNormal_T], dtype: TV_RandomStandardNormal_dtype, seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomStandardNormal_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [shape] + _attrs = ("seed", seed, "seed2", seed2, "dtype", dtype, "T", _attr_T) + _result = _execute.execute(b"RandomStandardNormal", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomStandardNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomUniform_dtype = TypeVar("TV_RandomUniform_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_RandomUniform_T = TypeVar("TV_RandomUniform_T", _atypes.Int32, _atypes.Int64) + +def random_uniform(shape: Annotated[Any, TV_RandomUniform_T], dtype: TV_RandomUniform_dtype, seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomUniform_dtype]: + r"""Outputs random values from a uniform distribution. + + The generated values follow a uniform distribution in the range `[0, 1)`. The + lower bound 0 is included in the range, while the upper bound 1 is excluded. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + dtype: A `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. + The type of the output. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomUniform", name, shape, "seed", seed, "seed2", seed2, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_uniform_eager_fallback( + shape, seed=seed, seed2=seed2, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomUniform", shape=shape, dtype=dtype, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "dtype", + _op._get_attr_type("dtype"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomUniform = tf_export("raw_ops.RandomUniform")(_ops.to_raw_op(random_uniform)) + + +def random_uniform_eager_fallback(shape: Annotated[Any, TV_RandomUniform_T], dtype: TV_RandomUniform_dtype, seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomUniform_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [shape] + _attrs = ("seed", seed, "seed2", seed2, "dtype", dtype, "T", _attr_T) + _result = _execute.execute(b"RandomUniform", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RandomUniformInt_Tout = TypeVar("TV_RandomUniformInt_Tout", _atypes.Int32, _atypes.Int64) +TV_RandomUniformInt_T = TypeVar("TV_RandomUniformInt_T", _atypes.Int32, _atypes.Int64) + +def random_uniform_int(shape: Annotated[Any, TV_RandomUniformInt_T], minval: Annotated[Any, TV_RandomUniformInt_Tout], maxval: Annotated[Any, TV_RandomUniformInt_Tout], seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_RandomUniformInt_Tout]: + r"""Outputs random integers from a uniform distribution. + + The generated values are uniform integers in the range `[minval, maxval)`. + The lower bound `minval` is included in the range, while the upper bound + `maxval` is excluded. + + The random integers are slightly biased unless `maxval - minval` is an exact + power of two. The bias is small for values of `maxval - minval` significantly + smaller than the range of the output (either `2^32` or `2^64`). + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + minval: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D. Inclusive lower bound on the generated integers. + maxval: A `Tensor`. Must have the same type as `minval`. + 0-D. Exclusive upper bound on the generated integers. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `minval`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RandomUniformInt", name, shape, minval, maxval, "seed", seed, + "seed2", seed2) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return random_uniform_int_eager_fallback( + shape, minval, maxval, seed=seed, seed2=seed2, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RandomUniformInt", shape=shape, minval=minval, maxval=maxval, + seed=seed, seed2=seed2, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "Tout", _op._get_attr_type("Tout"), + "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RandomUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RandomUniformInt = tf_export("raw_ops.RandomUniformInt")(_ops.to_raw_op(random_uniform_int)) + + +def random_uniform_int_eager_fallback(shape: Annotated[Any, TV_RandomUniformInt_T], minval: Annotated[Any, TV_RandomUniformInt_Tout], maxval: Annotated[Any, TV_RandomUniformInt_Tout], seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_RandomUniformInt_Tout]: + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_Tout, _inputs_Tout = _execute.args_to_matching_eager([minval, maxval], ctx, [_dtypes.int32, _dtypes.int64, ]) + (minval, maxval) = _inputs_Tout + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [shape, minval, maxval] + _attrs = ("seed", seed, "seed2", seed2, "Tout", _attr_Tout, "T", _attr_T) + _result = _execute.execute(b"RandomUniformInt", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RandomUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TruncatedNormal_dtype = TypeVar("TV_TruncatedNormal_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_TruncatedNormal_T = TypeVar("TV_TruncatedNormal_T", _atypes.Int32, _atypes.Int64) + +def truncated_normal(shape: Annotated[Any, TV_TruncatedNormal_T], dtype: TV_TruncatedNormal_dtype, seed:int=0, seed2:int=0, name=None) -> Annotated[Any, TV_TruncatedNormal_dtype]: + r"""Outputs random values from a truncated normal distribution. + + The generated values follow a normal distribution with mean 0 and standard + deviation 1, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + dtype: A `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. + The type of the output. + seed: An optional `int`. Defaults to `0`. + If either `seed` or `seed2` are set to be non-zero, the random number + generator is seeded by the given seed. Otherwise, it is seeded by a + random seed. + seed2: An optional `int`. Defaults to `0`. + A second seed to avoid seed collision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TruncatedNormal", name, shape, "seed", seed, "seed2", seed2, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return truncated_normal_eager_fallback( + shape, seed=seed, seed2=seed2, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TruncatedNormal", shape=shape, dtype=dtype, seed=seed, seed2=seed2, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("seed", _op._get_attr_int("seed"), "seed2", + _op._get_attr_int("seed2"), "dtype", + _op._get_attr_type("dtype"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TruncatedNormal = tf_export("raw_ops.TruncatedNormal")(_ops.to_raw_op(truncated_normal)) + + +def truncated_normal_eager_fallback(shape: Annotated[Any, TV_TruncatedNormal_T], dtype: TV_TruncatedNormal_dtype, seed: int, seed2: int, name, ctx) -> Annotated[Any, TV_TruncatedNormal_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if seed is None: + seed = 0 + seed = _execute.make_int(seed, "seed") + if seed2 is None: + seed2 = 0 + seed2 = _execute.make_int(seed2, "seed2") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _inputs_flat = [shape] + _attrs = ("seed", seed, "seed2", seed2, "dtype", dtype, "T", _attr_T) + _result = _execute.execute(b"TruncatedNormal", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_resource_variable_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_resource_variable_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2f51ec061305534faa1739225b2461b8a9f8b9da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_resource_variable_ops.py @@ -0,0 +1,1478 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AssignAddVariableOp_dtype = TypeVar("TV_AssignAddVariableOp_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def assign_add_variable_op(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignAddVariableOp_dtype], name=None): + r"""Adds a value to the current value of a variable. + + Any ReadVariableOp with a control dependency on this op is guaranteed to + see the incremented value or a subsequent newer one. + + Args: + resource: A `Tensor` of type `resource`. + handle to the resource in which to store the variable. + value: A `Tensor`. the value by which the variable will be incremented. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssignAddVariableOp", name, resource, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assign_add_variable_op_eager_fallback( + resource, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssignAddVariableOp", resource=resource, value=value, name=name) + return _op +AssignAddVariableOp = tf_export("raw_ops.AssignAddVariableOp")(_ops.to_raw_op(assign_add_variable_op)) + + +def assign_add_variable_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignAddVariableOp_dtype], name, ctx): + _attr_dtype, (value,) = _execute.args_to_matching_eager([value], ctx, []) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, value] + _attrs = ("dtype", _attr_dtype) + _result = _execute.execute(b"AssignAddVariableOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_AssignSubVariableOp_dtype = TypeVar("TV_AssignSubVariableOp_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def assign_sub_variable_op(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignSubVariableOp_dtype], name=None): + r"""Subtracts a value from the current value of a variable. + + Any ReadVariableOp with a control dependency on this op is guaranteed to + see the decremented value or a subsequent newer one. + + Args: + resource: A `Tensor` of type `resource`. + handle to the resource in which to store the variable. + value: A `Tensor`. the value by which the variable will be incremented. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssignSubVariableOp", name, resource, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assign_sub_variable_op_eager_fallback( + resource, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssignSubVariableOp", resource=resource, value=value, name=name) + return _op +AssignSubVariableOp = tf_export("raw_ops.AssignSubVariableOp")(_ops.to_raw_op(assign_sub_variable_op)) + + +def assign_sub_variable_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignSubVariableOp_dtype], name, ctx): + _attr_dtype, (value,) = _execute.args_to_matching_eager([value], ctx, []) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, value] + _attrs = ("dtype", _attr_dtype) + _result = _execute.execute(b"AssignSubVariableOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_AssignVariableOp_dtype = TypeVar("TV_AssignVariableOp_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def assign_variable_op(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignVariableOp_dtype], validate_shape:bool=False, name=None): + r"""Assigns a new value to a variable. + + Any ReadVariableOp with a control dependency on this op is guaranteed to return + this value or a subsequent newer value of the variable. + + Args: + resource: A `Tensor` of type `resource`. + handle to the resource in which to store the variable. + value: A `Tensor`. the value to set the new tensor to use. + validate_shape: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AssignVariableOp", name, resource, value, "validate_shape", + validate_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return assign_variable_op_eager_fallback( + resource, value, validate_shape=validate_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if validate_shape is None: + validate_shape = False + validate_shape = _execute.make_bool(validate_shape, "validate_shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssignVariableOp", resource=resource, value=value, + validate_shape=validate_shape, name=name) + return _op +AssignVariableOp = tf_export("raw_ops.AssignVariableOp")(_ops.to_raw_op(assign_variable_op)) + + +def assign_variable_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], value: Annotated[Any, TV_AssignVariableOp_dtype], validate_shape: bool, name, ctx): + if validate_shape is None: + validate_shape = False + validate_shape = _execute.make_bool(validate_shape, "validate_shape") + _attr_dtype, (value,) = _execute.args_to_matching_eager([value], ctx, []) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, value] + _attrs = ("dtype", _attr_dtype, "validate_shape", validate_shape) + _result = _execute.execute(b"AssignVariableOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def consume_mutex_lock(mutex_lock: Annotated[Any, _atypes.Variant], name=None): + r"""This op consumes a lock created by `MutexLock`. + + This op exists to consume a tensor created by `MutexLock` (other than + direct control dependencies). It should be the only that consumes the tensor, + and will raise an error if it is not. Its only purpose is to keep the + mutex lock tensor alive until it is consumed by this op. + + **NOTE**: This operation must run on the same device as its input. This may + be enforced via the `colocate_with` mechanism. + + Args: + mutex_lock: A `Tensor` of type `variant`. + A tensor returned by `MutexLock`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConsumeMutexLock", name, mutex_lock) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return consume_mutex_lock_eager_fallback( + mutex_lock, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConsumeMutexLock", mutex_lock=mutex_lock, name=name) + return _op +ConsumeMutexLock = tf_export("raw_ops.ConsumeMutexLock")(_ops.to_raw_op(consume_mutex_lock)) + + +def consume_mutex_lock_eager_fallback(mutex_lock: Annotated[Any, _atypes.Variant], name, ctx): + mutex_lock = _ops.convert_to_tensor(mutex_lock, _dtypes.variant) + _inputs_flat = [mutex_lock] + _attrs = None + _result = _execute.execute(b"ConsumeMutexLock", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def destroy_resource_op(resource: Annotated[Any, _atypes.Resource], ignore_lookup_error:bool=True, name=None): + r"""Deletes the resource specified by the handle. + + All subsequent operations using the resource will result in a NotFound + error status. + + Args: + resource: A `Tensor` of type `resource`. handle to the resource to delete. + ignore_lookup_error: An optional `bool`. Defaults to `True`. + whether to ignore the error when the resource + doesn't exist. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DestroyResourceOp", name, resource, "ignore_lookup_error", + ignore_lookup_error) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return destroy_resource_op_eager_fallback( + resource, ignore_lookup_error=ignore_lookup_error, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if ignore_lookup_error is None: + ignore_lookup_error = True + ignore_lookup_error = _execute.make_bool(ignore_lookup_error, "ignore_lookup_error") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DestroyResourceOp", resource=resource, + ignore_lookup_error=ignore_lookup_error, + name=name) + return _op +DestroyResourceOp = tf_export("raw_ops.DestroyResourceOp")(_ops.to_raw_op(destroy_resource_op)) + + +def destroy_resource_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], ignore_lookup_error: bool, name, ctx): + if ignore_lookup_error is None: + ignore_lookup_error = True + ignore_lookup_error = _execute.make_bool(ignore_lookup_error, "ignore_lookup_error") + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = ("ignore_lookup_error", ignore_lookup_error) + _result = _execute.execute(b"DestroyResourceOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def disable_copy_on_read(resource: Annotated[Any, _atypes.Resource], name=None): + r"""Turns off the copy-on-read mode. + + Turns off the copy-on-read mode of a resource variable. If the variable is not in copy-on-read mode, this op has no effect. + + Args: + resource: A `Tensor` of type `resource`. + The resource handle of the resource variable. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DisableCopyOnRead", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return disable_copy_on_read_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DisableCopyOnRead", resource=resource, name=name) + return _op +DisableCopyOnRead = tf_export("raw_ops.DisableCopyOnRead")(_ops.to_raw_op(disable_copy_on_read)) + + +def disable_copy_on_read_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx): + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"DisableCopyOnRead", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def mutex_lock(mutex: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Locks a mutex resource. The output is the lock. So long as the lock tensor + + is alive, any other request to use `MutexLock` with this mutex will wait. + + This is particularly useful for creating a critical section when used in + conjunction with `MutexLockIdentity`: + + ```python + + mutex = mutex_v2( + shared_name=handle_name, container=container, name=name) + + def execute_in_critical_section(fn, *args, **kwargs): + lock = gen_resource_variable_ops.mutex_lock(mutex) + + with ops.control_dependencies([lock]): + r = fn(*args, **kwargs) + + with ops.control_dependencies(nest.flatten(r)): + with ops.colocate_with(mutex): + ensure_lock_exists = mutex_lock_identity(lock) + + # Make sure that if any element of r is accessed, all of + # them are executed together. + r = nest.map_structure(tf.identity, r) + + with ops.control_dependencies([ensure_lock_exists]): + return nest.map_structure(tf.identity, r) + ``` + + While `fn` is running in the critical section, no other functions which wish to + use this critical section may run. + + Often the use case is that two executions of the same graph, in parallel, + wish to run `fn`; and we wish to ensure that only one of them executes + at a time. This is especially important if `fn` modifies one or more + variables at a time. + + It is also useful if two separate functions must share a resource, but we + wish to ensure the usage is exclusive. + + Args: + mutex: A `Tensor` of type `resource`. The mutex resource to lock. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MutexLock", name, mutex) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mutex_lock_eager_fallback( + mutex, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutexLock", mutex=mutex, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutexLock", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutexLock = tf_export("raw_ops.MutexLock")(_ops.to_raw_op(mutex_lock)) + + +def mutex_lock_eager_fallback(mutex: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Variant]: + mutex = _ops.convert_to_tensor(mutex, _dtypes.resource) + _inputs_flat = [mutex] + _attrs = None + _result = _execute.execute(b"MutexLock", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MutexLock", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def mutex_v2(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a Mutex resource that can be locked by `MutexLock`. + + Args: + container: An optional `string`. Defaults to `""`. + If non-empty, this variable is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this variable is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MutexV2", name, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return mutex_v2_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MutexV2", container=container, shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MutexV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MutexV2 = tf_export("raw_ops.MutexV2")(_ops.to_raw_op(mutex_v2)) + + +def mutex_v2_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"MutexV2", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MutexV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReadVariableOp_dtype = TypeVar("TV_ReadVariableOp_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def read_variable_op(resource: Annotated[Any, _atypes.Resource], dtype: TV_ReadVariableOp_dtype, name=None) -> Annotated[Any, TV_ReadVariableOp_dtype]: + r"""Reads the value of a variable. + + The tensor returned by this operation is immutable. + + The value returned by this operation is guaranteed to be influenced by all the + writes on which this operation depends directly or indirectly, and to not be + influenced by any of the writes which depend directly or indirectly on this + operation. + + Args: + resource: A `Tensor` of type `resource`. + handle to the resource in which to store the variable. + dtype: A `tf.DType`. the dtype of the value. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReadVariableOp", name, resource, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return read_variable_op_eager_fallback( + resource, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReadVariableOp", resource=resource, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReadVariableOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReadVariableOp = tf_export("raw_ops.ReadVariableOp")(_ops.to_raw_op(read_variable_op)) + + +def read_variable_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], dtype: TV_ReadVariableOp_dtype, name, ctx) -> Annotated[Any, TV_ReadVariableOp_dtype]: + dtype = _execute.make_type(dtype, "dtype") + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"ReadVariableOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReadVariableOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceGather_dtype = TypeVar("TV_ResourceGather_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceGather_Tindices = TypeVar("TV_ResourceGather_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_gather(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceGather_Tindices], dtype: TV_ResourceGather_dtype, batch_dims:int=0, validate_indices:bool=True, name=None) -> Annotated[Any, TV_ResourceGather_dtype]: + r"""Gather slices from the variable pointed to by `resource` according to `indices`. + + `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). + Produces an output tensor with shape `indices.shape + params.shape[1:]` where: + + ```python + # Scalar indices + output[:, ..., :] = params[indices, :, ... :] + + # Vector indices + output[i, :, ..., :] = params[indices[i], :, ... :] + + # Higher rank indices + output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :] + ``` + + Args: + resource: A `Tensor` of type `resource`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + dtype: A `tf.DType`. + batch_dims: An optional `int`. Defaults to `0`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceGather", name, resource, indices, "batch_dims", + batch_dims, "validate_indices", validate_indices, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_gather_eager_fallback( + resource, indices, batch_dims=batch_dims, + validate_indices=validate_indices, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if batch_dims is None: + batch_dims = 0 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceGather", resource=resource, indices=indices, dtype=dtype, + batch_dims=batch_dims, + validate_indices=validate_indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("batch_dims", _op._get_attr_int("batch_dims"), + "validate_indices", _op._get_attr_bool("validate_indices"), + "dtype", _op._get_attr_type("dtype"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceGather = tf_export("raw_ops.ResourceGather")(_ops.to_raw_op(resource_gather)) + + +def resource_gather_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceGather_Tindices], dtype: TV_ResourceGather_dtype, batch_dims: int, validate_indices: bool, name, ctx) -> Annotated[Any, TV_ResourceGather_dtype]: + dtype = _execute.make_type(dtype, "dtype") + if batch_dims is None: + batch_dims = 0 + batch_dims = _execute.make_int(batch_dims, "batch_dims") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices] + _attrs = ("batch_dims", batch_dims, "validate_indices", validate_indices, + "dtype", dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceGather", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceGather", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceGatherNd_dtype = TypeVar("TV_ResourceGatherNd_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceGatherNd_Tindices = TypeVar("TV_ResourceGatherNd_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_gather_nd(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceGatherNd_Tindices], dtype: TV_ResourceGatherNd_dtype, name=None) -> Annotated[Any, TV_ResourceGatherNd_dtype]: + r"""TODO: add doc. + + Args: + resource: A `Tensor` of type `resource`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + dtype: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceGatherNd", name, resource, indices, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_gather_nd_eager_fallback( + resource, indices, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceGatherNd", resource=resource, indices=indices, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceGatherNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceGatherNd = tf_export("raw_ops.ResourceGatherNd")(_ops.to_raw_op(resource_gather_nd)) + + +def resource_gather_nd_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceGatherNd_Tindices], dtype: TV_ResourceGatherNd_dtype, name, ctx) -> Annotated[Any, TV_ResourceGatherNd_dtype]: + dtype = _execute.make_type(dtype, "dtype") + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices] + _attrs = ("dtype", dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceGatherNd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceGatherNd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceScatterAdd_dtype = TypeVar("TV_ResourceScatterAdd_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterAdd_Tindices = TypeVar("TV_ResourceScatterAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_add(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterAdd_Tindices], updates: Annotated[Any, TV_ResourceScatterAdd_dtype], name=None): + r"""Adds sparse updates to the variable referenced by `resource`. + + This operation computes + + # Scalar indices + ref[indices, ...] += updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] += updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] += updates[i, ..., j, ...] + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterAdd", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_add_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterAdd", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterAdd = tf_export("raw_ops.ResourceScatterAdd")(_ops.to_raw_op(resource_scatter_add)) + + +def resource_scatter_add_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterAdd_Tindices], updates: Annotated[Any, TV_ResourceScatterAdd_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterAdd", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterDiv_dtype = TypeVar("TV_ResourceScatterDiv_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterDiv_Tindices = TypeVar("TV_ResourceScatterDiv_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_div(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterDiv_Tindices], updates: Annotated[Any, TV_ResourceScatterDiv_dtype], name=None): + r"""Divides sparse updates into the variable referenced by `resource`. + + This operation computes + + # Scalar indices + ref[indices, ...] /= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] /= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...] + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions multiply. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterDiv", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_div_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterDiv", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterDiv = tf_export("raw_ops.ResourceScatterDiv")(_ops.to_raw_op(resource_scatter_div)) + + +def resource_scatter_div_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterDiv_Tindices], updates: Annotated[Any, TV_ResourceScatterDiv_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterDiv", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterMax_dtype = TypeVar("TV_ResourceScatterMax_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterMax_Tindices = TypeVar("TV_ResourceScatterMax_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_max(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMax_Tindices], updates: Annotated[Any, TV_ResourceScatterMax_dtype], name=None): + r"""Reduces sparse updates into the variable referenced by `resource` using the `max` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = max(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions are combined. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterMax", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_max_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterMax", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterMax = tf_export("raw_ops.ResourceScatterMax")(_ops.to_raw_op(resource_scatter_max)) + + +def resource_scatter_max_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMax_Tindices], updates: Annotated[Any, TV_ResourceScatterMax_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterMax", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterMin_dtype = TypeVar("TV_ResourceScatterMin_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterMin_Tindices = TypeVar("TV_ResourceScatterMin_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_min(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMin_Tindices], updates: Annotated[Any, TV_ResourceScatterMin_dtype], name=None): + r"""Reduces sparse updates into the variable referenced by `resource` using the `min` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = min(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions are combined. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterMin", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_min_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterMin", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterMin = tf_export("raw_ops.ResourceScatterMin")(_ops.to_raw_op(resource_scatter_min)) + + +def resource_scatter_min_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMin_Tindices], updates: Annotated[Any, TV_ResourceScatterMin_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterMin", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterMul_dtype = TypeVar("TV_ResourceScatterMul_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterMul_Tindices = TypeVar("TV_ResourceScatterMul_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_mul(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMul_Tindices], updates: Annotated[Any, TV_ResourceScatterMul_dtype], name=None): + r"""Multiplies sparse updates into the variable referenced by `resource`. + + This operation computes + + # Scalar indices + ref[indices, ...] *= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] *= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...] + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions multiply. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterMul", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_mul_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterMul", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterMul = tf_export("raw_ops.ResourceScatterMul")(_ops.to_raw_op(resource_scatter_mul)) + + +def resource_scatter_mul_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterMul_Tindices], updates: Annotated[Any, TV_ResourceScatterMul_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterMul", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterSub_dtype = TypeVar("TV_ResourceScatterSub_dtype", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceScatterSub_Tindices = TypeVar("TV_ResourceScatterSub_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_sub(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterSub_Tindices], updates: Annotated[Any, TV_ResourceScatterSub_dtype], name=None): + r"""Subtracts sparse updates from the variable referenced by `resource`. + + This operation computes + + # Scalar indices + ref[indices, ...] -= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] -= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterSub", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_sub_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterSub", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterSub = tf_export("raw_ops.ResourceScatterSub")(_ops.to_raw_op(resource_scatter_sub)) + + +def resource_scatter_sub_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterSub_Tindices], updates: Annotated[Any, TV_ResourceScatterSub_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterSub", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterUpdate_dtype = TypeVar("TV_ResourceScatterUpdate_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterUpdate_Tindices = TypeVar("TV_ResourceScatterUpdate_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_update(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterUpdate_Tindices], updates: Annotated[Any, TV_ResourceScatterUpdate_dtype], name=None): + r"""Assigns sparse updates to the variable referenced by `resource`. + + This operation computes + + # Scalar indices + ref[indices, ...] = updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] = updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] + + Args: + resource: A `Tensor` of type `resource`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. A tensor of updated values to add to `ref`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterUpdate", name, resource, indices, updates) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_update_eager_fallback( + resource, indices, updates, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterUpdate", resource=resource, indices=indices, + updates=updates, name=name) + return _op +ResourceScatterUpdate = tf_export("raw_ops.ResourceScatterUpdate")(_ops.to_raw_op(resource_scatter_update)) + + +def resource_scatter_update_eager_fallback(resource: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterUpdate_Tindices], updates: Annotated[Any, TV_ResourceScatterUpdate_dtype], name, ctx): + _attr_dtype, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, indices, updates] + _attrs = ("dtype", _attr_dtype, "Tindices", _attr_Tindices) + _result = _execute.execute(b"ResourceScatterUpdate", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_VarHandleOp_dtype = TypeVar("TV_VarHandleOp_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def var_handle_op(dtype: TV_VarHandleOp_dtype, shape, container:str="", shared_name:str="", debug_name:str="", allowed_devices=[], name=None) -> Annotated[Any, _atypes.Resource]: + r"""Creates a handle to a Variable resource. + + Args: + dtype: A `tf.DType`. the type of this variable. Must agree with the dtypes + of all ops using this variable. + shape: A `tf.TensorShape` or list of `ints`. + The (possibly partially specified) shape of this variable. + container: An optional `string`. Defaults to `""`. + the container this variable is placed in. + shared_name: An optional `string`. Defaults to `""`. + the name by which this variable is referred to. + debug_name: An optional `string`. Defaults to `""`. + the user-given name, which still applies in anonymous mode. + allowed_devices: An optional list of `strings`. Defaults to `[]`. + DEPRECATED. The allowed devices containing the resource variable. Set when the + output ResourceHandle represents a per-replica/partitioned resource variable. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "VarHandleOp", name, "container", container, "shared_name", + shared_name, "debug_name", debug_name, "dtype", dtype, "shape", shape, + "allowed_devices", allowed_devices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return var_handle_op_eager_fallback( + container=container, shared_name=shared_name, debug_name=debug_name, + dtype=dtype, shape=shape, allowed_devices=allowed_devices, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if debug_name is None: + debug_name = "" + debug_name = _execute.make_str(debug_name, "debug_name") + if allowed_devices is None: + allowed_devices = [] + if not isinstance(allowed_devices, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_devices' argument to " + "'var_handle_op' Op, not %r." % allowed_devices) + allowed_devices = [_execute.make_str(_s, "allowed_devices") for _s in allowed_devices] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "VarHandleOp", dtype=dtype, shape=shape, container=container, + shared_name=shared_name, debug_name=debug_name, + allowed_devices=allowed_devices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name"), "debug_name", + _op.get_attr("debug_name"), "dtype", + _op._get_attr_type("dtype"), "shape", _op.get_attr("shape"), + "allowed_devices", _op.get_attr("allowed_devices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "VarHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +VarHandleOp = tf_export("raw_ops.VarHandleOp")(_ops.to_raw_op(var_handle_op)) + + +def var_handle_op_eager_fallback(dtype: TV_VarHandleOp_dtype, shape, container: str, shared_name: str, debug_name: str, allowed_devices, name, ctx) -> Annotated[Any, _atypes.Resource]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if debug_name is None: + debug_name = "" + debug_name = _execute.make_str(debug_name, "debug_name") + if allowed_devices is None: + allowed_devices = [] + if not isinstance(allowed_devices, (list, tuple)): + raise TypeError( + "Expected list for 'allowed_devices' argument to " + "'var_handle_op' Op, not %r." % allowed_devices) + allowed_devices = [_execute.make_str(_s, "allowed_devices") for _s in allowed_devices] + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name, "debug_name", + debug_name, "dtype", dtype, "shape", shape, "allowed_devices", + allowed_devices) + _result = _execute.execute(b"VarHandleOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "VarHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def var_is_initialized_op(resource: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Checks whether a resource handle-based variable has been initialized. + + Args: + resource: A `Tensor` of type `resource`. the input resource handle. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "VarIsInitializedOp", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return var_is_initialized_op_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "VarIsInitializedOp", resource=resource, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "VarIsInitializedOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +VarIsInitializedOp = tf_export("raw_ops.VarIsInitializedOp")(_ops.to_raw_op(var_is_initialized_op)) + + +def var_is_initialized_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"VarIsInitializedOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "VarIsInitializedOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_VariableShape_out_type = TypeVar("TV_VariableShape_out_type", _atypes.Int32, _atypes.Int64) + +def variable_shape(input: Annotated[Any, _atypes.Resource], out_type:TV_VariableShape_out_type=_dtypes.int32, name=None) -> Annotated[Any, TV_VariableShape_out_type]: + r"""Returns the shape of the variable pointed to by `resource`. + + This operation returns a 1-D integer tensor representing the shape of `input`. + + For example: + + ``` + # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] + shape(t) ==> [2, 2, 3] + ``` + + Args: + input: A `Tensor` of type `resource`. + out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "VariableShape", name, input, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return variable_shape_eager_fallback( + input, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "VariableShape", input=input, out_type=out_type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("out_type", _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "VariableShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +VariableShape = tf_export("raw_ops.VariableShape")(_ops.to_raw_op(variable_shape)) + + +def variable_shape_eager_fallback(input: Annotated[Any, _atypes.Resource], out_type: TV_VariableShape_out_type, name, ctx) -> Annotated[Any, TV_VariableShape_out_type]: + if out_type is None: + out_type = _dtypes.int32 + out_type = _execute.make_type(out_type, "out_type") + input = _ops.convert_to_tensor(input, _dtypes.resource) + _inputs_flat = [input] + _attrs = ("out_type", out_type) + _result = _execute.execute(b"VariableShape", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "VariableShape", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_rnn_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_rnn_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..586ba8e3b0ae3b24684be2c336a0b782a7d8f0c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_rnn_ops.py @@ -0,0 +1,1056 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_BlockLSTMOutput = collections.namedtuple( + "BlockLSTM", + ["i", "cs", "f", "o", "ci", "co", "h"]) + + +TV_BlockLSTM_T = TypeVar("TV_BlockLSTM_T", _atypes.Float32, _atypes.Half) + +def block_lstm(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTM_T], cs_prev: Annotated[Any, TV_BlockLSTM_T], h_prev: Annotated[Any, TV_BlockLSTM_T], w: Annotated[Any, TV_BlockLSTM_T], wci: Annotated[Any, TV_BlockLSTM_T], wcf: Annotated[Any, TV_BlockLSTM_T], wco: Annotated[Any, TV_BlockLSTM_T], b: Annotated[Any, TV_BlockLSTM_T], forget_bias:float=1, cell_clip:float=3, use_peephole:bool=False, name=None): + r"""Computes the LSTM cell forward propagation for all the time steps. + + This is equivalent to applying LSTMBlockCell in a loop, like so: + + ```python + for x1 in unpack(x): + i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock( + x1, cs_prev, h_prev, w, wci, wcf, wco, b) + cs_prev = cs1 + h_prev = h1 + i.append(i1) + cs.append(cs1) + f.append(f1) + o.append(o1) + ci.append(ci1) + co.append(co1) + h.append(h1) + return pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h) + ``` + + Args: + seq_len_max: A `Tensor` of type `int64`. + Maximum time length actually used by this input. Outputs are padded + with zeros beyond this length. + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + Value of the initial cell state. + h_prev: A `Tensor`. Must have the same type as `x`. + Initial output of cell (to be used for peephole). + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + forget_bias: An optional `float`. Defaults to `1`. The forget gate bias. + cell_clip: An optional `float`. Defaults to `3`. + Value to clip the 'cs' value to. + use_peephole: An optional `bool`. Defaults to `False`. + Whether to use peephole weights. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (i, cs, f, o, ci, co, h). + + i: A `Tensor`. Has the same type as `x`. + cs: A `Tensor`. Has the same type as `x`. + f: A `Tensor`. Has the same type as `x`. + o: A `Tensor`. Has the same type as `x`. + ci: A `Tensor`. Has the same type as `x`. + co: A `Tensor`. Has the same type as `x`. + h: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BlockLSTM", name, seq_len_max, x, cs_prev, h_prev, w, wci, wcf, + wco, b, "forget_bias", forget_bias, "cell_clip", cell_clip, + "use_peephole", use_peephole) + _result = _BlockLSTMOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return block_lstm_eager_fallback( + seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, + forget_bias=forget_bias, cell_clip=cell_clip, + use_peephole=use_peephole, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if forget_bias is None: + forget_bias = 1 + forget_bias = _execute.make_float(forget_bias, "forget_bias") + if cell_clip is None: + cell_clip = 3 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BlockLSTM", seq_len_max=seq_len_max, x=x, cs_prev=cs_prev, + h_prev=h_prev, w=w, wci=wci, wcf=wcf, wco=wco, b=b, + forget_bias=forget_bias, cell_clip=cell_clip, + use_peephole=use_peephole, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("forget_bias", _op.get_attr("forget_bias"), "cell_clip", + _op.get_attr("cell_clip"), "use_peephole", + _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BlockLSTM", _inputs_flat, _attrs, _result) + _result = _BlockLSTMOutput._make(_result) + return _result + +BlockLSTM = tf_export("raw_ops.BlockLSTM")(_ops.to_raw_op(block_lstm)) + + +def block_lstm_eager_fallback(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTM_T], cs_prev: Annotated[Any, TV_BlockLSTM_T], h_prev: Annotated[Any, TV_BlockLSTM_T], w: Annotated[Any, TV_BlockLSTM_T], wci: Annotated[Any, TV_BlockLSTM_T], wcf: Annotated[Any, TV_BlockLSTM_T], wco: Annotated[Any, TV_BlockLSTM_T], b: Annotated[Any, TV_BlockLSTM_T], forget_bias: float, cell_clip: float, use_peephole: bool, name, ctx): + if forget_bias is None: + forget_bias = 1 + forget_bias = _execute.make_float(forget_bias, "forget_bias") + if cell_clip is None: + cell_clip = 3 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b) = _inputs_T + seq_len_max = _ops.convert_to_tensor(seq_len_max, _dtypes.int64) + _inputs_flat = [seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b] + _attrs = ("forget_bias", forget_bias, "cell_clip", cell_clip, + "use_peephole", use_peephole, "T", _attr_T) + _result = _execute.execute(b"BlockLSTM", 7, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BlockLSTM", _inputs_flat, _attrs, _result) + _result = _BlockLSTMOutput._make(_result) + return _result + +_BlockLSTMGradOutput = collections.namedtuple( + "BlockLSTMGrad", + ["x_grad", "cs_prev_grad", "h_prev_grad", "w_grad", "wci_grad", "wcf_grad", "wco_grad", "b_grad"]) + + +TV_BlockLSTMGrad_T = TypeVar("TV_BlockLSTMGrad_T", _atypes.Float32, _atypes.Half) + +def block_lstm_grad(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMGrad_T], cs_prev: Annotated[Any, TV_BlockLSTMGrad_T], h_prev: Annotated[Any, TV_BlockLSTMGrad_T], w: Annotated[Any, TV_BlockLSTMGrad_T], wci: Annotated[Any, TV_BlockLSTMGrad_T], wcf: Annotated[Any, TV_BlockLSTMGrad_T], wco: Annotated[Any, TV_BlockLSTMGrad_T], b: Annotated[Any, TV_BlockLSTMGrad_T], i: Annotated[Any, TV_BlockLSTMGrad_T], cs: Annotated[Any, TV_BlockLSTMGrad_T], f: Annotated[Any, TV_BlockLSTMGrad_T], o: Annotated[Any, TV_BlockLSTMGrad_T], ci: Annotated[Any, TV_BlockLSTMGrad_T], co: Annotated[Any, TV_BlockLSTMGrad_T], h: Annotated[Any, TV_BlockLSTMGrad_T], cs_grad: Annotated[Any, TV_BlockLSTMGrad_T], h_grad: Annotated[Any, TV_BlockLSTMGrad_T], use_peephole: bool, name=None): + r"""Computes the LSTM cell backward propagation for the entire time sequence. + + This implementation is to be used in conjunction of LSTMBlock. + + Args: + seq_len_max: A `Tensor` of type `int64`. + Maximum time length actually used by this input. Outputs are padded + with zeros beyond this length. + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + Value of the initial cell state. + h_prev: A `Tensor`. Must have the same type as `x`. + Initial output of cell (to be used for peephole). + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + i: A `Tensor`. Must have the same type as `x`. + The input gate over the whole time sequence. + cs: A `Tensor`. Must have the same type as `x`. + The cell state before the tanh over the whole time sequence. + f: A `Tensor`. Must have the same type as `x`. + The forget gate over the whole time sequence. + o: A `Tensor`. Must have the same type as `x`. + The output gate over the whole time sequence. + ci: A `Tensor`. Must have the same type as `x`. + The cell input over the whole time sequence. + co: A `Tensor`. Must have the same type as `x`. + The cell after the tanh over the whole time sequence. + h: A `Tensor`. Must have the same type as `x`. + The output h vector over the whole time sequence. + cs_grad: A `Tensor`. Must have the same type as `x`. + The current gradient of cs. + h_grad: A `Tensor`. Must have the same type as `x`. + The gradient of h vector. + use_peephole: A `bool`. Whether to use peephole weights. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad). + + x_grad: A `Tensor`. Has the same type as `x`. + cs_prev_grad: A `Tensor`. Has the same type as `x`. + h_prev_grad: A `Tensor`. Has the same type as `x`. + w_grad: A `Tensor`. Has the same type as `x`. + wci_grad: A `Tensor`. Has the same type as `x`. + wcf_grad: A `Tensor`. Has the same type as `x`. + wco_grad: A `Tensor`. Has the same type as `x`. + b_grad: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BlockLSTMGrad", name, seq_len_max, x, cs_prev, h_prev, w, wci, + wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad, "use_peephole", + use_peephole) + _result = _BlockLSTMGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return block_lstm_grad_eager_fallback( + seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, + ci, co, h, cs_grad, h_grad, use_peephole=use_peephole, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BlockLSTMGrad", seq_len_max=seq_len_max, x=x, cs_prev=cs_prev, + h_prev=h_prev, w=w, wci=wci, wcf=wcf, wco=wco, b=b, + i=i, cs=cs, f=f, o=o, ci=ci, co=co, h=h, + cs_grad=cs_grad, h_grad=h_grad, + use_peephole=use_peephole, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("use_peephole", _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BlockLSTMGrad", _inputs_flat, _attrs, _result) + _result = _BlockLSTMGradOutput._make(_result) + return _result + +BlockLSTMGrad = tf_export("raw_ops.BlockLSTMGrad")(_ops.to_raw_op(block_lstm_grad)) + + +def block_lstm_grad_eager_fallback(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMGrad_T], cs_prev: Annotated[Any, TV_BlockLSTMGrad_T], h_prev: Annotated[Any, TV_BlockLSTMGrad_T], w: Annotated[Any, TV_BlockLSTMGrad_T], wci: Annotated[Any, TV_BlockLSTMGrad_T], wcf: Annotated[Any, TV_BlockLSTMGrad_T], wco: Annotated[Any, TV_BlockLSTMGrad_T], b: Annotated[Any, TV_BlockLSTMGrad_T], i: Annotated[Any, TV_BlockLSTMGrad_T], cs: Annotated[Any, TV_BlockLSTMGrad_T], f: Annotated[Any, TV_BlockLSTMGrad_T], o: Annotated[Any, TV_BlockLSTMGrad_T], ci: Annotated[Any, TV_BlockLSTMGrad_T], co: Annotated[Any, TV_BlockLSTMGrad_T], h: Annotated[Any, TV_BlockLSTMGrad_T], cs_grad: Annotated[Any, TV_BlockLSTMGrad_T], h_grad: Annotated[Any, TV_BlockLSTMGrad_T], use_peephole: bool, name, ctx): + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad) = _inputs_T + seq_len_max = _ops.convert_to_tensor(seq_len_max, _dtypes.int64) + _inputs_flat = [seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad] + _attrs = ("use_peephole", use_peephole, "T", _attr_T) + _result = _execute.execute(b"BlockLSTMGrad", 8, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BlockLSTMGrad", _inputs_flat, _attrs, _result) + _result = _BlockLSTMGradOutput._make(_result) + return _result + +_BlockLSTMGradV2Output = collections.namedtuple( + "BlockLSTMGradV2", + ["x_grad", "cs_prev_grad", "h_prev_grad", "w_grad", "wci_grad", "wcf_grad", "wco_grad", "b_grad"]) + + +TV_BlockLSTMGradV2_T = TypeVar("TV_BlockLSTMGradV2_T", _atypes.Float32, _atypes.Half) + +def block_lstm_grad_v2(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMGradV2_T], cs_prev: Annotated[Any, TV_BlockLSTMGradV2_T], h_prev: Annotated[Any, TV_BlockLSTMGradV2_T], w: Annotated[Any, TV_BlockLSTMGradV2_T], wci: Annotated[Any, TV_BlockLSTMGradV2_T], wcf: Annotated[Any, TV_BlockLSTMGradV2_T], wco: Annotated[Any, TV_BlockLSTMGradV2_T], b: Annotated[Any, TV_BlockLSTMGradV2_T], i: Annotated[Any, TV_BlockLSTMGradV2_T], cs: Annotated[Any, TV_BlockLSTMGradV2_T], f: Annotated[Any, TV_BlockLSTMGradV2_T], o: Annotated[Any, TV_BlockLSTMGradV2_T], ci: Annotated[Any, TV_BlockLSTMGradV2_T], co: Annotated[Any, TV_BlockLSTMGradV2_T], h: Annotated[Any, TV_BlockLSTMGradV2_T], cs_grad: Annotated[Any, TV_BlockLSTMGradV2_T], h_grad: Annotated[Any, TV_BlockLSTMGradV2_T], use_peephole: bool, name=None): + r"""Computes the LSTM cell backward propagation for the entire time sequence. + + This implementation is to be used in conjunction of BlockLSTMV2. + + Args: + seq_len_max: A `Tensor` of type `int64`. + Maximum time length actually used by this input. Outputs are padded + with zeros beyond this length. + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + Value of the initial cell state. + h_prev: A `Tensor`. Must have the same type as `x`. + Initial output of cell (to be used for peephole). + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + i: A `Tensor`. Must have the same type as `x`. + The input gate over the whole time sequence. + cs: A `Tensor`. Must have the same type as `x`. + The cell state before the tanh over the whole time sequence. + f: A `Tensor`. Must have the same type as `x`. + The forget gate over the whole time sequence. + o: A `Tensor`. Must have the same type as `x`. + The output gate over the whole time sequence. + ci: A `Tensor`. Must have the same type as `x`. + The cell input over the whole time sequence. + co: A `Tensor`. Must have the same type as `x`. + The cell after the tanh over the whole time sequence. + h: A `Tensor`. Must have the same type as `x`. + The output h vector over the whole time sequence. + cs_grad: A `Tensor`. Must have the same type as `x`. + The current gradient of cs. + h_grad: A `Tensor`. Must have the same type as `x`. + The gradient of h vector. + use_peephole: A `bool`. Whether to use peephole weights. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, b_grad). + + x_grad: A `Tensor`. Has the same type as `x`. + cs_prev_grad: A `Tensor`. Has the same type as `x`. + h_prev_grad: A `Tensor`. Has the same type as `x`. + w_grad: A `Tensor`. Has the same type as `x`. + wci_grad: A `Tensor`. Has the same type as `x`. + wcf_grad: A `Tensor`. Has the same type as `x`. + wco_grad: A `Tensor`. Has the same type as `x`. + b_grad: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BlockLSTMGradV2", name, seq_len_max, x, cs_prev, h_prev, w, + wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad, + "use_peephole", use_peephole) + _result = _BlockLSTMGradV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return block_lstm_grad_v2_eager_fallback( + seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, + ci, co, h, cs_grad, h_grad, use_peephole=use_peephole, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BlockLSTMGradV2", seq_len_max=seq_len_max, x=x, cs_prev=cs_prev, + h_prev=h_prev, w=w, wci=wci, wcf=wcf, wco=wco, b=b, + i=i, cs=cs, f=f, o=o, ci=ci, co=co, h=h, + cs_grad=cs_grad, h_grad=h_grad, + use_peephole=use_peephole, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("use_peephole", _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BlockLSTMGradV2", _inputs_flat, _attrs, _result) + _result = _BlockLSTMGradV2Output._make(_result) + return _result + +BlockLSTMGradV2 = tf_export("raw_ops.BlockLSTMGradV2")(_ops.to_raw_op(block_lstm_grad_v2)) + + +def block_lstm_grad_v2_eager_fallback(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMGradV2_T], cs_prev: Annotated[Any, TV_BlockLSTMGradV2_T], h_prev: Annotated[Any, TV_BlockLSTMGradV2_T], w: Annotated[Any, TV_BlockLSTMGradV2_T], wci: Annotated[Any, TV_BlockLSTMGradV2_T], wcf: Annotated[Any, TV_BlockLSTMGradV2_T], wco: Annotated[Any, TV_BlockLSTMGradV2_T], b: Annotated[Any, TV_BlockLSTMGradV2_T], i: Annotated[Any, TV_BlockLSTMGradV2_T], cs: Annotated[Any, TV_BlockLSTMGradV2_T], f: Annotated[Any, TV_BlockLSTMGradV2_T], o: Annotated[Any, TV_BlockLSTMGradV2_T], ci: Annotated[Any, TV_BlockLSTMGradV2_T], co: Annotated[Any, TV_BlockLSTMGradV2_T], h: Annotated[Any, TV_BlockLSTMGradV2_T], cs_grad: Annotated[Any, TV_BlockLSTMGradV2_T], h_grad: Annotated[Any, TV_BlockLSTMGradV2_T], use_peephole: bool, name, ctx): + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad) = _inputs_T + seq_len_max = _ops.convert_to_tensor(seq_len_max, _dtypes.int64) + _inputs_flat = [seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, h, cs_grad, h_grad] + _attrs = ("use_peephole", use_peephole, "T", _attr_T) + _result = _execute.execute(b"BlockLSTMGradV2", 8, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BlockLSTMGradV2", _inputs_flat, _attrs, _result) + _result = _BlockLSTMGradV2Output._make(_result) + return _result + +_BlockLSTMV2Output = collections.namedtuple( + "BlockLSTMV2", + ["i", "cs", "f", "o", "ci", "co", "h"]) + + +TV_BlockLSTMV2_T = TypeVar("TV_BlockLSTMV2_T", _atypes.Float32, _atypes.Half) + +def block_lstmv2(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMV2_T], cs_prev: Annotated[Any, TV_BlockLSTMV2_T], h_prev: Annotated[Any, TV_BlockLSTMV2_T], w: Annotated[Any, TV_BlockLSTMV2_T], wci: Annotated[Any, TV_BlockLSTMV2_T], wcf: Annotated[Any, TV_BlockLSTMV2_T], wco: Annotated[Any, TV_BlockLSTMV2_T], b: Annotated[Any, TV_BlockLSTMV2_T], cell_clip:float=0, use_peephole:bool=False, name=None): + r"""Computes the LSTM cell forward propagation for all the time steps. + + This is equivalent to applying LSTMBlockCell in a loop, like so: + + ```python + for x1 in unpack(x): + i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock( + x1, cs_prev, h_prev, w, wci, wcf, wco, b) + cs_prev = cs1 + h_prev = h1 + i.append(i1) + cs.append(cs1) + f.append(f1) + o.append(o1) + ci.append(ci1) + co.append(co1) + h.append(h1) + return pack(i), pack(cs), pack(f), pack(o), pack(ci), pack(ch), pack(h) + + Note that unlike LSTMBlockCell (and BlockLSTM) which uses ICFO gate layout, + this op uses IFCO. So in order for the following snippet to be equivalent + all gate-related outputs should be reordered. + ``` + + Args: + seq_len_max: A `Tensor` of type `int64`. + Maximum time length actually used by this input. Outputs are padded + with zeros beyond this length. + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The sequence input to the LSTM, shape (timelen, batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + Value of the initial cell state. + h_prev: A `Tensor`. Must have the same type as `x`. + Initial output of cell (to be used for peephole). + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + cell_clip: An optional `float`. Defaults to `0`. + Value to clip the 'cs' value to. + use_peephole: An optional `bool`. Defaults to `False`. + Whether to use peephole weights. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (i, cs, f, o, ci, co, h). + + i: A `Tensor`. Has the same type as `x`. + cs: A `Tensor`. Has the same type as `x`. + f: A `Tensor`. Has the same type as `x`. + o: A `Tensor`. Has the same type as `x`. + ci: A `Tensor`. Has the same type as `x`. + co: A `Tensor`. Has the same type as `x`. + h: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BlockLSTMV2", name, seq_len_max, x, cs_prev, h_prev, w, wci, + wcf, wco, b, "cell_clip", cell_clip, "use_peephole", use_peephole) + _result = _BlockLSTMV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return block_lstmv2_eager_fallback( + seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b, + cell_clip=cell_clip, use_peephole=use_peephole, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if cell_clip is None: + cell_clip = 0 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BlockLSTMV2", seq_len_max=seq_len_max, x=x, cs_prev=cs_prev, + h_prev=h_prev, w=w, wci=wci, wcf=wcf, wco=wco, b=b, + cell_clip=cell_clip, use_peephole=use_peephole, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("cell_clip", _op.get_attr("cell_clip"), "use_peephole", + _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BlockLSTMV2", _inputs_flat, _attrs, _result) + _result = _BlockLSTMV2Output._make(_result) + return _result + +BlockLSTMV2 = tf_export("raw_ops.BlockLSTMV2")(_ops.to_raw_op(block_lstmv2)) + + +def block_lstmv2_eager_fallback(seq_len_max: Annotated[Any, _atypes.Int64], x: Annotated[Any, TV_BlockLSTMV2_T], cs_prev: Annotated[Any, TV_BlockLSTMV2_T], h_prev: Annotated[Any, TV_BlockLSTMV2_T], w: Annotated[Any, TV_BlockLSTMV2_T], wci: Annotated[Any, TV_BlockLSTMV2_T], wcf: Annotated[Any, TV_BlockLSTMV2_T], wco: Annotated[Any, TV_BlockLSTMV2_T], b: Annotated[Any, TV_BlockLSTMV2_T], cell_clip: float, use_peephole: bool, name, ctx): + if cell_clip is None: + cell_clip = 0 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b) = _inputs_T + seq_len_max = _ops.convert_to_tensor(seq_len_max, _dtypes.int64) + _inputs_flat = [seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b] + _attrs = ("cell_clip", cell_clip, "use_peephole", use_peephole, "T", + _attr_T) + _result = _execute.execute(b"BlockLSTMV2", 7, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BlockLSTMV2", _inputs_flat, _attrs, _result) + _result = _BlockLSTMV2Output._make(_result) + return _result + +_GRUBlockCellOutput = collections.namedtuple( + "GRUBlockCell", + ["r", "u", "c", "h"]) + + +TV_GRUBlockCell_T = TypeVar("TV_GRUBlockCell_T", bound=_atypes.Float32) + +def gru_block_cell(x: Annotated[Any, TV_GRUBlockCell_T], h_prev: Annotated[Any, TV_GRUBlockCell_T], w_ru: Annotated[Any, TV_GRUBlockCell_T], w_c: Annotated[Any, TV_GRUBlockCell_T], b_ru: Annotated[Any, TV_GRUBlockCell_T], b_c: Annotated[Any, TV_GRUBlockCell_T], name=None): + r"""Computes the GRU cell forward propagation for 1 time step. + + Args + x: Input to the GRU cell. + h_prev: State input from the previous GRU cell. + w_ru: Weight matrix for the reset and update gate. + w_c: Weight matrix for the cell connection gate. + b_ru: Bias vector for the reset and update gate. + b_c: Bias vector for the cell connection gate. + + Returns + r: Output of the reset gate. + u: Output of the update gate. + c: Output of the cell connection gate. + h: Current state of the GRU cell. + + Note on notation of the variables: + + Concatenation of a and b is represented by a_b + Element-wise dot product of a and b is represented by ab + Element-wise dot product is represented by \circ + Matrix multiplication is represented by * + + Biases are initialized with : + `b_ru` - constant_initializer(1.0) + `b_c` - constant_initializer(0.0) + + This kernel op implements the following mathematical equations: + + ``` + x_h_prev = [x, h_prev] + + [r_bar u_bar] = x_h_prev * w_ru + b_ru + + r = sigmoid(r_bar) + u = sigmoid(u_bar) + + h_prevr = h_prev \circ r + + x_h_prevr = [x h_prevr] + + c_bar = x_h_prevr * w_c + b_c + c = tanh(c_bar) + + h = (1-u) \circ c + u \circ h_prev + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`. + h_prev: A `Tensor`. Must have the same type as `x`. + w_ru: A `Tensor`. Must have the same type as `x`. + w_c: A `Tensor`. Must have the same type as `x`. + b_ru: A `Tensor`. Must have the same type as `x`. + b_c: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (r, u, c, h). + + r: A `Tensor`. Has the same type as `x`. + u: A `Tensor`. Has the same type as `x`. + c: A `Tensor`. Has the same type as `x`. + h: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GRUBlockCell", name, x, h_prev, w_ru, w_c, b_ru, b_c) + _result = _GRUBlockCellOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return gru_block_cell_eager_fallback( + x, h_prev, w_ru, w_c, b_ru, b_c, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GRUBlockCell", x=x, h_prev=h_prev, w_ru=w_ru, w_c=w_c, b_ru=b_ru, + b_c=b_c, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GRUBlockCell", _inputs_flat, _attrs, _result) + _result = _GRUBlockCellOutput._make(_result) + return _result + +GRUBlockCell = tf_export("raw_ops.GRUBlockCell")(_ops.to_raw_op(gru_block_cell)) + + +def gru_block_cell_eager_fallback(x: Annotated[Any, TV_GRUBlockCell_T], h_prev: Annotated[Any, TV_GRUBlockCell_T], w_ru: Annotated[Any, TV_GRUBlockCell_T], w_c: Annotated[Any, TV_GRUBlockCell_T], b_ru: Annotated[Any, TV_GRUBlockCell_T], b_c: Annotated[Any, TV_GRUBlockCell_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, h_prev, w_ru, w_c, b_ru, b_c], ctx, [_dtypes.float32, ]) + (x, h_prev, w_ru, w_c, b_ru, b_c) = _inputs_T + _inputs_flat = [x, h_prev, w_ru, w_c, b_ru, b_c] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GRUBlockCell", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GRUBlockCell", _inputs_flat, _attrs, _result) + _result = _GRUBlockCellOutput._make(_result) + return _result + +_GRUBlockCellGradOutput = collections.namedtuple( + "GRUBlockCellGrad", + ["d_x", "d_h_prev", "d_c_bar", "d_r_bar_u_bar"]) + + +TV_GRUBlockCellGrad_T = TypeVar("TV_GRUBlockCellGrad_T", bound=_atypes.Float32) + +def gru_block_cell_grad(x: Annotated[Any, TV_GRUBlockCellGrad_T], h_prev: Annotated[Any, TV_GRUBlockCellGrad_T], w_ru: Annotated[Any, TV_GRUBlockCellGrad_T], w_c: Annotated[Any, TV_GRUBlockCellGrad_T], b_ru: Annotated[Any, TV_GRUBlockCellGrad_T], b_c: Annotated[Any, TV_GRUBlockCellGrad_T], r: Annotated[Any, TV_GRUBlockCellGrad_T], u: Annotated[Any, TV_GRUBlockCellGrad_T], c: Annotated[Any, TV_GRUBlockCellGrad_T], d_h: Annotated[Any, TV_GRUBlockCellGrad_T], name=None): + r"""Computes the GRU cell back-propagation for 1 time step. + + Args + x: Input to the GRU cell. + h_prev: State input from the previous GRU cell. + w_ru: Weight matrix for the reset and update gate. + w_c: Weight matrix for the cell connection gate. + b_ru: Bias vector for the reset and update gate. + b_c: Bias vector for the cell connection gate. + r: Output of the reset gate. + u: Output of the update gate. + c: Output of the cell connection gate. + d_h: Gradients of the h_new wrt to objective function. + + Returns + d_x: Gradients of the x wrt to objective function. + d_h_prev: Gradients of the h wrt to objective function. + d_c_bar Gradients of the c_bar wrt to objective function. + d_r_bar_u_bar Gradients of the r_bar & u_bar wrt to objective function. + + This kernel op implements the following mathematical equations: + + Note on notation of the variables: + + Concatenation of a and b is represented by a_b + Element-wise dot product of a and b is represented by ab + Element-wise dot product is represented by \circ + Matrix multiplication is represented by * + + Additional notes for clarity: + + `w_ru` can be segmented into 4 different matrices. + ``` + w_ru = [w_r_x w_u_x + w_r_h_prev w_u_h_prev] + ``` + Similarly, `w_c` can be segmented into 2 different matrices. + ``` + w_c = [w_c_x w_c_h_prevr] + ``` + Same goes for biases. + ``` + b_ru = [b_ru_x b_ru_h] + b_c = [b_c_x b_c_h] + ``` + Another note on notation: + ``` + d_x = d_x_component_1 + d_x_component_2 + + where d_x_component_1 = d_r_bar * w_r_x^T + d_u_bar * w_r_x^T + and d_x_component_2 = d_c_bar * w_c_x^T + + d_h_prev = d_h_prev_component_1 + d_h_prevr \circ r + d_h \circ u + where d_h_prev_componenet_1 = d_r_bar * w_r_h_prev^T + d_u_bar * w_r_h_prev^T + ``` + + Mathematics behind the Gradients below: + ``` + d_c_bar = d_h \circ (1-u) \circ (1-c \circ c) + d_u_bar = d_h \circ (h-c) \circ u \circ (1-u) + + d_r_bar_u_bar = [d_r_bar d_u_bar] + + [d_x_component_1 d_h_prev_component_1] = d_r_bar_u_bar * w_ru^T + + [d_x_component_2 d_h_prevr] = d_c_bar * w_c^T + + d_x = d_x_component_1 + d_x_component_2 + + d_h_prev = d_h_prev_component_1 + d_h_prevr \circ r + u + ``` + Below calculation is performed in the python wrapper for the Gradients + (not in the gradient kernel.) + ``` + d_w_ru = x_h_prevr^T * d_c_bar + + d_w_c = x_h_prev^T * d_r_bar_u_bar + + d_b_ru = sum of d_r_bar_u_bar along axis = 0 + + d_b_c = sum of d_c_bar along axis = 0 + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`. + h_prev: A `Tensor`. Must have the same type as `x`. + w_ru: A `Tensor`. Must have the same type as `x`. + w_c: A `Tensor`. Must have the same type as `x`. + b_ru: A `Tensor`. Must have the same type as `x`. + b_c: A `Tensor`. Must have the same type as `x`. + r: A `Tensor`. Must have the same type as `x`. + u: A `Tensor`. Must have the same type as `x`. + c: A `Tensor`. Must have the same type as `x`. + d_h: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d_x, d_h_prev, d_c_bar, d_r_bar_u_bar). + + d_x: A `Tensor`. Has the same type as `x`. + d_h_prev: A `Tensor`. Has the same type as `x`. + d_c_bar: A `Tensor`. Has the same type as `x`. + d_r_bar_u_bar: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GRUBlockCellGrad", name, x, h_prev, w_ru, w_c, b_ru, b_c, r, u, + c, d_h) + _result = _GRUBlockCellGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return gru_block_cell_grad_eager_fallback( + x, h_prev, w_ru, w_c, b_ru, b_c, r, u, c, d_h, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GRUBlockCellGrad", x=x, h_prev=h_prev, w_ru=w_ru, w_c=w_c, b_ru=b_ru, + b_c=b_c, r=r, u=u, c=c, d_h=d_h, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "GRUBlockCellGrad", _inputs_flat, _attrs, _result) + _result = _GRUBlockCellGradOutput._make(_result) + return _result + +GRUBlockCellGrad = tf_export("raw_ops.GRUBlockCellGrad")(_ops.to_raw_op(gru_block_cell_grad)) + + +def gru_block_cell_grad_eager_fallback(x: Annotated[Any, TV_GRUBlockCellGrad_T], h_prev: Annotated[Any, TV_GRUBlockCellGrad_T], w_ru: Annotated[Any, TV_GRUBlockCellGrad_T], w_c: Annotated[Any, TV_GRUBlockCellGrad_T], b_ru: Annotated[Any, TV_GRUBlockCellGrad_T], b_c: Annotated[Any, TV_GRUBlockCellGrad_T], r: Annotated[Any, TV_GRUBlockCellGrad_T], u: Annotated[Any, TV_GRUBlockCellGrad_T], c: Annotated[Any, TV_GRUBlockCellGrad_T], d_h: Annotated[Any, TV_GRUBlockCellGrad_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, h_prev, w_ru, w_c, b_ru, b_c, r, u, c, d_h], ctx, [_dtypes.float32, ]) + (x, h_prev, w_ru, w_c, b_ru, b_c, r, u, c, d_h) = _inputs_T + _inputs_flat = [x, h_prev, w_ru, w_c, b_ru, b_c, r, u, c, d_h] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"GRUBlockCellGrad", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GRUBlockCellGrad", _inputs_flat, _attrs, _result) + _result = _GRUBlockCellGradOutput._make(_result) + return _result + +_LSTMBlockCellOutput = collections.namedtuple( + "LSTMBlockCell", + ["i", "cs", "f", "o", "ci", "co", "h"]) + + +TV_LSTMBlockCell_T = TypeVar("TV_LSTMBlockCell_T", _atypes.Float32, _atypes.Half) + +def lstm_block_cell(x: Annotated[Any, TV_LSTMBlockCell_T], cs_prev: Annotated[Any, TV_LSTMBlockCell_T], h_prev: Annotated[Any, TV_LSTMBlockCell_T], w: Annotated[Any, TV_LSTMBlockCell_T], wci: Annotated[Any, TV_LSTMBlockCell_T], wcf: Annotated[Any, TV_LSTMBlockCell_T], wco: Annotated[Any, TV_LSTMBlockCell_T], b: Annotated[Any, TV_LSTMBlockCell_T], forget_bias:float=1, cell_clip:float=3, use_peephole:bool=False, name=None): + r"""Computes the LSTM cell forward propagation for 1 time step. + + This implementation uses 1 weight matrix and 1 bias vector, and there's an + optional peephole connection. + + This kernel op implements the following mathematical equations: + + ```python + xh = [x, h_prev] + [i, f, ci, o] = xh * w + b + f = f + forget_bias + + if not use_peephole: + wci = wcf = wco = 0 + + i = sigmoid(cs_prev * wci + i) + f = sigmoid(cs_prev * wcf + f) + ci = tanh(ci) + + cs = ci .* i + cs_prev .* f + cs = clip(cs, cell_clip) + + o = sigmoid(cs * wco + o) + co = tanh(cs) + h = co .* o + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The input to the LSTM cell, shape (batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + Value of the cell state at previous time step. + h_prev: A `Tensor`. Must have the same type as `x`. + Output of the previous cell at previous time step. + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + forget_bias: An optional `float`. Defaults to `1`. The forget gate bias. + cell_clip: An optional `float`. Defaults to `3`. + Value to clip the 'cs' value to. + use_peephole: An optional `bool`. Defaults to `False`. + Whether to use peephole weights. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (i, cs, f, o, ci, co, h). + + i: A `Tensor`. Has the same type as `x`. + cs: A `Tensor`. Has the same type as `x`. + f: A `Tensor`. Has the same type as `x`. + o: A `Tensor`. Has the same type as `x`. + ci: A `Tensor`. Has the same type as `x`. + co: A `Tensor`. Has the same type as `x`. + h: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LSTMBlockCell", name, x, cs_prev, h_prev, w, wci, wcf, wco, b, + "forget_bias", forget_bias, "cell_clip", cell_clip, "use_peephole", + use_peephole) + _result = _LSTMBlockCellOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lstm_block_cell_eager_fallback( + x, cs_prev, h_prev, w, wci, wcf, wco, b, forget_bias=forget_bias, + cell_clip=cell_clip, use_peephole=use_peephole, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if forget_bias is None: + forget_bias = 1 + forget_bias = _execute.make_float(forget_bias, "forget_bias") + if cell_clip is None: + cell_clip = 3 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LSTMBlockCell", x=x, cs_prev=cs_prev, h_prev=h_prev, w=w, wci=wci, + wcf=wcf, wco=wco, b=b, forget_bias=forget_bias, + cell_clip=cell_clip, use_peephole=use_peephole, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("forget_bias", _op.get_attr("forget_bias"), "cell_clip", + _op.get_attr("cell_clip"), "use_peephole", + _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LSTMBlockCell", _inputs_flat, _attrs, _result) + _result = _LSTMBlockCellOutput._make(_result) + return _result + +LSTMBlockCell = tf_export("raw_ops.LSTMBlockCell")(_ops.to_raw_op(lstm_block_cell)) + + +def lstm_block_cell_eager_fallback(x: Annotated[Any, TV_LSTMBlockCell_T], cs_prev: Annotated[Any, TV_LSTMBlockCell_T], h_prev: Annotated[Any, TV_LSTMBlockCell_T], w: Annotated[Any, TV_LSTMBlockCell_T], wci: Annotated[Any, TV_LSTMBlockCell_T], wcf: Annotated[Any, TV_LSTMBlockCell_T], wco: Annotated[Any, TV_LSTMBlockCell_T], b: Annotated[Any, TV_LSTMBlockCell_T], forget_bias: float, cell_clip: float, use_peephole: bool, name, ctx): + if forget_bias is None: + forget_bias = 1 + forget_bias = _execute.make_float(forget_bias, "forget_bias") + if cell_clip is None: + cell_clip = 3 + cell_clip = _execute.make_float(cell_clip, "cell_clip") + if use_peephole is None: + use_peephole = False + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b) = _inputs_T + _inputs_flat = [x, cs_prev, h_prev, w, wci, wcf, wco, b] + _attrs = ("forget_bias", forget_bias, "cell_clip", cell_clip, + "use_peephole", use_peephole, "T", _attr_T) + _result = _execute.execute(b"LSTMBlockCell", 7, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LSTMBlockCell", _inputs_flat, _attrs, _result) + _result = _LSTMBlockCellOutput._make(_result) + return _result + +_LSTMBlockCellGradOutput = collections.namedtuple( + "LSTMBlockCellGrad", + ["cs_prev_grad", "dicfo", "wci_grad", "wcf_grad", "wco_grad"]) + + +TV_LSTMBlockCellGrad_T = TypeVar("TV_LSTMBlockCellGrad_T", _atypes.Float32, _atypes.Half) + +def lstm_block_cell_grad(x: Annotated[Any, TV_LSTMBlockCellGrad_T], cs_prev: Annotated[Any, TV_LSTMBlockCellGrad_T], h_prev: Annotated[Any, TV_LSTMBlockCellGrad_T], w: Annotated[Any, TV_LSTMBlockCellGrad_T], wci: Annotated[Any, TV_LSTMBlockCellGrad_T], wcf: Annotated[Any, TV_LSTMBlockCellGrad_T], wco: Annotated[Any, TV_LSTMBlockCellGrad_T], b: Annotated[Any, TV_LSTMBlockCellGrad_T], i: Annotated[Any, TV_LSTMBlockCellGrad_T], cs: Annotated[Any, TV_LSTMBlockCellGrad_T], f: Annotated[Any, TV_LSTMBlockCellGrad_T], o: Annotated[Any, TV_LSTMBlockCellGrad_T], ci: Annotated[Any, TV_LSTMBlockCellGrad_T], co: Annotated[Any, TV_LSTMBlockCellGrad_T], cs_grad: Annotated[Any, TV_LSTMBlockCellGrad_T], h_grad: Annotated[Any, TV_LSTMBlockCellGrad_T], use_peephole: bool, name=None): + r"""Computes the LSTM cell backward propagation for 1 timestep. + + This implementation is to be used in conjunction of LSTMBlockCell. + + Args: + x: A `Tensor`. Must be one of the following types: `half`, `float32`. + The input to the LSTM cell, shape (batch_size, num_inputs). + cs_prev: A `Tensor`. Must have the same type as `x`. + The previous cell state. + h_prev: A `Tensor`. Must have the same type as `x`. The previous h state. + w: A `Tensor`. Must have the same type as `x`. The weight matrix. + wci: A `Tensor`. Must have the same type as `x`. + The weight matrix for input gate peephole connection. + wcf: A `Tensor`. Must have the same type as `x`. + The weight matrix for forget gate peephole connection. + wco: A `Tensor`. Must have the same type as `x`. + The weight matrix for output gate peephole connection. + b: A `Tensor`. Must have the same type as `x`. The bias vector. + i: A `Tensor`. Must have the same type as `x`. The input gate. + cs: A `Tensor`. Must have the same type as `x`. + The cell state before the tanh. + f: A `Tensor`. Must have the same type as `x`. The forget gate. + o: A `Tensor`. Must have the same type as `x`. The output gate. + ci: A `Tensor`. Must have the same type as `x`. The cell input. + co: A `Tensor`. Must have the same type as `x`. The cell after the tanh. + cs_grad: A `Tensor`. Must have the same type as `x`. + The current gradient of cs. + h_grad: A `Tensor`. Must have the same type as `x`. + The gradient of h vector. + use_peephole: A `bool`. Whether the cell uses peephole connections. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (cs_prev_grad, dicfo, wci_grad, wcf_grad, wco_grad). + + cs_prev_grad: A `Tensor`. Has the same type as `x`. + dicfo: A `Tensor`. Has the same type as `x`. + wci_grad: A `Tensor`. Has the same type as `x`. + wcf_grad: A `Tensor`. Has the same type as `x`. + wco_grad: A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LSTMBlockCellGrad", name, x, cs_prev, h_prev, w, wci, wcf, wco, + b, i, cs, f, o, ci, co, cs_grad, h_grad, "use_peephole", use_peephole) + _result = _LSTMBlockCellGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return lstm_block_cell_grad_eager_fallback( + x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, + cs_grad, h_grad, use_peephole=use_peephole, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LSTMBlockCellGrad", x=x, cs_prev=cs_prev, h_prev=h_prev, w=w, + wci=wci, wcf=wcf, wco=wco, b=b, i=i, cs=cs, f=f, + o=o, ci=ci, co=co, cs_grad=cs_grad, + h_grad=h_grad, use_peephole=use_peephole, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("use_peephole", _op._get_attr_bool("use_peephole"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "LSTMBlockCellGrad", _inputs_flat, _attrs, _result) + _result = _LSTMBlockCellGradOutput._make(_result) + return _result + +LSTMBlockCellGrad = tf_export("raw_ops.LSTMBlockCellGrad")(_ops.to_raw_op(lstm_block_cell_grad)) + + +def lstm_block_cell_grad_eager_fallback(x: Annotated[Any, TV_LSTMBlockCellGrad_T], cs_prev: Annotated[Any, TV_LSTMBlockCellGrad_T], h_prev: Annotated[Any, TV_LSTMBlockCellGrad_T], w: Annotated[Any, TV_LSTMBlockCellGrad_T], wci: Annotated[Any, TV_LSTMBlockCellGrad_T], wcf: Annotated[Any, TV_LSTMBlockCellGrad_T], wco: Annotated[Any, TV_LSTMBlockCellGrad_T], b: Annotated[Any, TV_LSTMBlockCellGrad_T], i: Annotated[Any, TV_LSTMBlockCellGrad_T], cs: Annotated[Any, TV_LSTMBlockCellGrad_T], f: Annotated[Any, TV_LSTMBlockCellGrad_T], o: Annotated[Any, TV_LSTMBlockCellGrad_T], ci: Annotated[Any, TV_LSTMBlockCellGrad_T], co: Annotated[Any, TV_LSTMBlockCellGrad_T], cs_grad: Annotated[Any, TV_LSTMBlockCellGrad_T], h_grad: Annotated[Any, TV_LSTMBlockCellGrad_T], use_peephole: bool, name, ctx): + use_peephole = _execute.make_bool(use_peephole, "use_peephole") + _attr_T, _inputs_T = _execute.args_to_matching_eager([x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, cs_grad, h_grad], ctx, [_dtypes.half, _dtypes.float32, ]) + (x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, cs_grad, h_grad) = _inputs_T + _inputs_flat = [x, cs_prev, h_prev, w, wci, wcf, wco, b, i, cs, f, o, ci, co, cs_grad, h_grad] + _attrs = ("use_peephole", use_peephole, "T", _attr_T) + _result = _execute.execute(b"LSTMBlockCellGrad", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "LSTMBlockCellGrad", _inputs_flat, _attrs, _result) + _result = _LSTMBlockCellGradOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_script_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_script_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..887cf7afb14db19423c453fc2035d0dc8d138052 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_script_ops.py @@ -0,0 +1,250 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def eager_py_func(input, token: str, Tout, is_async:bool=False, name=None): + r"""Eagerly executes a python function to compute func(input)->output. The + + semantics of the input, output, and attributes are the same as those for + PyFunc. + + Args: + input: A list of `Tensor` objects. + token: A `string`. + Tout: A list of `tf.DTypes`. + is_async: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EagerPyFunc", name, input, "token", token, "is_async", + is_async, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return eager_py_func_eager_fallback( + input, token=token, is_async=is_async, Tout=Tout, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'eager_py_func' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if is_async is None: + is_async = False + is_async = _execute.make_bool(is_async, "is_async") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EagerPyFunc", input=input, token=token, Tout=Tout, is_async=is_async, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("token", _op.get_attr("token"), "is_async", + _op._get_attr_bool("is_async"), "Tin", _op.get_attr("Tin"), + "Tout", _op.get_attr("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EagerPyFunc", _inputs_flat, _attrs, _result) + return _result + +EagerPyFunc = tf_export("raw_ops.EagerPyFunc")(_ops.to_raw_op(eager_py_func)) + + +def eager_py_func_eager_fallback(input, token: str, Tout, is_async: bool, name, ctx): + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'eager_py_func' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if is_async is None: + is_async = False + is_async = _execute.make_bool(is_async, "is_async") + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("token", token, "is_async", is_async, "Tin", _attr_Tin, "Tout", + Tout) + _result = _execute.execute(b"EagerPyFunc", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EagerPyFunc", _inputs_flat, _attrs, _result) + return _result + + +def py_func(input, token: str, Tout, name=None): + r"""Invokes a python function to compute func(input)->output. + + This operation is considered stateful. For a stateless version, see + PyFuncStateless. + + Args: + input: A list of `Tensor` objects. + List of Tensors that will provide input to the Op. + token: A `string`. + A token representing a registered python function in this address space. + Tout: A list of `tf.DTypes`. Data types of the outputs from the op. + The length of the list specifies the number of outputs. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PyFunc", name, input, "token", token, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return py_func_eager_fallback( + input, token=token, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'py_func' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PyFunc", input=input, token=token, Tout=Tout, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("token", _op.get_attr("token"), "Tin", _op.get_attr("Tin"), + "Tout", _op.get_attr("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PyFunc", _inputs_flat, _attrs, _result) + return _result + +PyFunc = tf_export("raw_ops.PyFunc")(_ops.to_raw_op(py_func)) + + +def py_func_eager_fallback(input, token: str, Tout, name, ctx): + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'py_func' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("token", token, "Tin", _attr_Tin, "Tout", Tout) + _result = _execute.execute(b"PyFunc", len(Tout), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PyFunc", _inputs_flat, _attrs, _result) + return _result + + +def py_func_stateless(input, token: str, Tout, name=None): + r"""A stateless version of PyFunc. + + Args: + input: A list of `Tensor` objects. + token: A `string`. + Tout: A list of `tf.DTypes`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PyFuncStateless", name, input, "token", token, "Tout", Tout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return py_func_stateless_eager_fallback( + input, token=token, Tout=Tout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'py_func_stateless' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PyFuncStateless", input=input, token=token, Tout=Tout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("token", _op.get_attr("token"), "Tin", _op.get_attr("Tin"), + "Tout", _op.get_attr("Tout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PyFuncStateless", _inputs_flat, _attrs, _result) + return _result + +PyFuncStateless = tf_export("raw_ops.PyFuncStateless")(_ops.to_raw_op(py_func_stateless)) + + +def py_func_stateless_eager_fallback(input, token: str, Tout, name, ctx): + token = _execute.make_str(token, "token") + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'py_func_stateless' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + _attr_Tin, input = _execute.convert_to_mixed_eager_tensors(input, ctx) + _inputs_flat = list(input) + _attrs = ("token", token, "Tin", _attr_Tin, "Tout", Tout) + _result = _execute.execute(b"PyFuncStateless", len(Tout), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PyFuncStateless", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sdca_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sdca_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..431c25fc62de7c551bab065f8ed9f5c3c95c04ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sdca_ops.py @@ -0,0 +1,800 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['train.sdca_fprint']) +@deprecated_endpoints('train.sdca_fprint') +def sdca_fprint(input: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Computes fingerprints of the input strings. + + Args: + input: A `Tensor` of type `string`. + vector of strings to compute fingerprints on. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SdcaFprint", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sdca_fprint( + (input, name,), None) + if _result is not NotImplemented: + return _result + return sdca_fprint_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sdca_fprint, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sdca_fprint( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SdcaFprint", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sdca_fprint, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "SdcaFprint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SdcaFprint = tf_export("raw_ops.SdcaFprint")(_ops.to_raw_op(sdca_fprint)) +_dispatcher_for_sdca_fprint = sdca_fprint._tf_type_based_dispatcher.Dispatch + + +def sdca_fprint_eager_fallback(input: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Int64]: + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"SdcaFprint", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SdcaFprint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SdcaOptimizerOutput = collections.namedtuple( + "SdcaOptimizer", + ["out_example_state_data", "out_delta_sparse_weights", "out_delta_dense_weights"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['train.sdca_optimizer']) +@deprecated_endpoints('train.sdca_optimizer') +def sdca_optimizer(sparse_example_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_values: Annotated[List[Any], _atypes.Float32], dense_features: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], example_labels: Annotated[Any, _atypes.Float32], sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_weights: Annotated[List[Any], _atypes.Float32], dense_weights: Annotated[List[Any], _atypes.Float32], example_state_data: Annotated[Any, _atypes.Float32], loss_type: str, l1: float, l2: float, num_loss_partitions: int, num_inner_iterations: int, adaptative:bool=True, name=None): + r"""Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for + + linear models with L1 + L2 regularization. As global optimization objective is + strongly-convex, the optimizer optimizes the dual objective at each step. The + optimizer applies each update one example at a time. Examples are sampled + uniformly, and the optimizer is learning rate free and enjoys linear convergence + rate. + + [Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
+ Shai Shalev-Shwartz, Tong Zhang. 2012 + + $$Loss Objective = \sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$ + + [Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
+ Chenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan, + Peter Richtarik, Martin Takac. 2015 + + [Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
+ Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 + + Args: + sparse_example_indices: A list of `Tensor` objects with type `int64`. + a list of vectors which contain example indices. + sparse_feature_indices: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. + a list of vectors which contain feature indices. + sparse_feature_values: A list of `Tensor` objects with type `float32`. + a list of vectors which contains feature value + associated with each feature group. + dense_features: A list of `Tensor` objects with type `float32`. + a list of matrices which contains the dense feature values. + example_weights: A `Tensor` of type `float32`. + a vector which contains the weight associated with each + example. + example_labels: A `Tensor` of type `float32`. + a vector which contains the label/target associated with each + example. + sparse_indices: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. + a list of vectors where each value is the indices which has + corresponding weights in sparse_weights. This field maybe omitted for the + dense approach. + sparse_weights: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. + a list of vectors where each value is the weight associated with + a sparse feature group. + dense_weights: A list with the same length as `dense_features` of `Tensor` objects with type `float32`. + a list of vectors where the values are the weights associated + with a dense feature group. + example_state_data: A `Tensor` of type `float32`. + a list of vectors containing the example state data. + loss_type: A `string` from: `"logistic_loss", "squared_loss", "hinge_loss", "smooth_hinge_loss", "poisson_loss"`. + Type of the primal loss. Currently SdcaSolver supports logistic, + squared and hinge losses. + l1: A `float`. Symmetric l1 regularization strength. + l2: A `float`. Symmetric l2 regularization strength. + num_loss_partitions: An `int` that is `>= 1`. + Number of partitions of the global loss function. + num_inner_iterations: An `int` that is `>= 1`. + Number of iterations per mini-batch. + adaptative: An optional `bool`. Defaults to `True`. + Whether to use Adaptive SDCA for the inner loop. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out_example_state_data, out_delta_sparse_weights, out_delta_dense_weights). + + out_example_state_data: A `Tensor` of type `float32`. + out_delta_sparse_weights: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. + out_delta_dense_weights: A list with the same length as `dense_features` of `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SdcaOptimizer", name, sparse_example_indices, + sparse_feature_indices, sparse_feature_values, dense_features, + example_weights, example_labels, sparse_indices, sparse_weights, + dense_weights, example_state_data, "loss_type", loss_type, + "adaptative", adaptative, "l1", l1, "l2", l2, "num_loss_partitions", + num_loss_partitions, "num_inner_iterations", num_inner_iterations) + _result = _SdcaOptimizerOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sdca_optimizer( + (sparse_example_indices, sparse_feature_indices, + sparse_feature_values, dense_features, example_weights, + example_labels, sparse_indices, sparse_weights, dense_weights, + example_state_data, loss_type, l1, l2, num_loss_partitions, + num_inner_iterations, adaptative, name,), None) + if _result is not NotImplemented: + return _result + return sdca_optimizer_eager_fallback( + sparse_example_indices, sparse_feature_indices, + sparse_feature_values, dense_features, example_weights, + example_labels, sparse_indices, sparse_weights, dense_weights, + example_state_data, loss_type=loss_type, adaptative=adaptative, + l1=l1, l2=l2, num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sdca_optimizer, (), dict(sparse_example_indices=sparse_example_indices, + sparse_feature_indices=sparse_feature_indices, + sparse_feature_values=sparse_feature_values, + dense_features=dense_features, + example_weights=example_weights, + example_labels=example_labels, + sparse_indices=sparse_indices, + sparse_weights=sparse_weights, + dense_weights=dense_weights, + example_state_data=example_state_data, + loss_type=loss_type, l1=l1, l2=l2, + num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, + adaptative=adaptative, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sdca_optimizer( + (sparse_example_indices, sparse_feature_indices, + sparse_feature_values, dense_features, example_weights, + example_labels, sparse_indices, sparse_weights, dense_weights, + example_state_data, loss_type, l1, l2, num_loss_partitions, + num_inner_iterations, adaptative, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_example_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_example_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_example_indices) + _attr_num_sparse_features = len(sparse_example_indices) + if not isinstance(sparse_feature_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_feature_indices) + if len(sparse_feature_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_feature_indices' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_feature_indices), _attr_num_sparse_features)) + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_indices) + if len(sparse_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_indices' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_indices), _attr_num_sparse_features)) + if not isinstance(sparse_weights, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_weights' argument to " + "'sdca_optimizer' Op, not %r." % sparse_weights) + if len(sparse_weights) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_weights' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_weights), _attr_num_sparse_features)) + if not isinstance(sparse_feature_values, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_values' argument to " + "'sdca_optimizer' Op, not %r." % sparse_feature_values) + _attr_num_sparse_features_with_values = len(sparse_feature_values) + if not isinstance(dense_features, (list, tuple)): + raise TypeError( + "Expected list for 'dense_features' argument to " + "'sdca_optimizer' Op, not %r." % dense_features) + _attr_num_dense_features = len(dense_features) + if not isinstance(dense_weights, (list, tuple)): + raise TypeError( + "Expected list for 'dense_weights' argument to " + "'sdca_optimizer' Op, not %r." % dense_weights) + if len(dense_weights) != _attr_num_dense_features: + raise ValueError( + "List argument 'dense_weights' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'dense_features'." % + (len(dense_weights), _attr_num_dense_features)) + loss_type = _execute.make_str(loss_type, "loss_type") + l1 = _execute.make_float(l1, "l1") + l2 = _execute.make_float(l2, "l2") + num_loss_partitions = _execute.make_int(num_loss_partitions, "num_loss_partitions") + num_inner_iterations = _execute.make_int(num_inner_iterations, "num_inner_iterations") + if adaptative is None: + adaptative = True + adaptative = _execute.make_bool(adaptative, "adaptative") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SdcaOptimizer", sparse_example_indices=sparse_example_indices, + sparse_feature_indices=sparse_feature_indices, + sparse_feature_values=sparse_feature_values, + dense_features=dense_features, + example_weights=example_weights, + example_labels=example_labels, + sparse_indices=sparse_indices, + sparse_weights=sparse_weights, + dense_weights=dense_weights, + example_state_data=example_state_data, + loss_type=loss_type, l1=l1, l2=l2, + num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, + adaptative=adaptative, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sdca_optimizer, (), dict(sparse_example_indices=sparse_example_indices, + sparse_feature_indices=sparse_feature_indices, + sparse_feature_values=sparse_feature_values, + dense_features=dense_features, + example_weights=example_weights, + example_labels=example_labels, + sparse_indices=sparse_indices, + sparse_weights=sparse_weights, + dense_weights=dense_weights, + example_state_data=example_state_data, + loss_type=loss_type, l1=l1, l2=l2, + num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, + adaptative=adaptative, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("loss_type", _op.get_attr("loss_type"), "adaptative", + _op._get_attr_bool("adaptative"), "num_sparse_features", + _op._get_attr_int("num_sparse_features"), + "num_sparse_features_with_values", + _op._get_attr_int("num_sparse_features_with_values"), + "num_dense_features", _op._get_attr_int("num_dense_features"), + "l1", _op.get_attr("l1"), "l2", _op.get_attr("l2"), + "num_loss_partitions", _op._get_attr_int("num_loss_partitions"), + "num_inner_iterations", + _op._get_attr_int("num_inner_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SdcaOptimizer", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:1 + _attr_num_sparse_features]] + _result[1 + _attr_num_sparse_features:] + _result = _result[:2] + [_result[2:]] + _result = _SdcaOptimizerOutput._make(_result) + return _result + +SdcaOptimizer = tf_export("raw_ops.SdcaOptimizer")(_ops.to_raw_op(sdca_optimizer)) +_dispatcher_for_sdca_optimizer = sdca_optimizer._tf_type_based_dispatcher.Dispatch + + +def sdca_optimizer_eager_fallback(sparse_example_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_values: Annotated[List[Any], _atypes.Float32], dense_features: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], example_labels: Annotated[Any, _atypes.Float32], sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_weights: Annotated[List[Any], _atypes.Float32], dense_weights: Annotated[List[Any], _atypes.Float32], example_state_data: Annotated[Any, _atypes.Float32], loss_type: str, l1: float, l2: float, num_loss_partitions: int, num_inner_iterations: int, adaptative: bool, name, ctx): + if not isinstance(sparse_example_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_example_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_example_indices) + _attr_num_sparse_features = len(sparse_example_indices) + if not isinstance(sparse_feature_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_feature_indices) + if len(sparse_feature_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_feature_indices' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_feature_indices), _attr_num_sparse_features)) + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'sdca_optimizer' Op, not %r." % sparse_indices) + if len(sparse_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_indices' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_indices), _attr_num_sparse_features)) + if not isinstance(sparse_weights, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_weights' argument to " + "'sdca_optimizer' Op, not %r." % sparse_weights) + if len(sparse_weights) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_weights' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_weights), _attr_num_sparse_features)) + if not isinstance(sparse_feature_values, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_values' argument to " + "'sdca_optimizer' Op, not %r." % sparse_feature_values) + _attr_num_sparse_features_with_values = len(sparse_feature_values) + if not isinstance(dense_features, (list, tuple)): + raise TypeError( + "Expected list for 'dense_features' argument to " + "'sdca_optimizer' Op, not %r." % dense_features) + _attr_num_dense_features = len(dense_features) + if not isinstance(dense_weights, (list, tuple)): + raise TypeError( + "Expected list for 'dense_weights' argument to " + "'sdca_optimizer' Op, not %r." % dense_weights) + if len(dense_weights) != _attr_num_dense_features: + raise ValueError( + "List argument 'dense_weights' to 'sdca_optimizer' Op with length %d " + "must match length %d of argument 'dense_features'." % + (len(dense_weights), _attr_num_dense_features)) + loss_type = _execute.make_str(loss_type, "loss_type") + l1 = _execute.make_float(l1, "l1") + l2 = _execute.make_float(l2, "l2") + num_loss_partitions = _execute.make_int(num_loss_partitions, "num_loss_partitions") + num_inner_iterations = _execute.make_int(num_inner_iterations, "num_inner_iterations") + if adaptative is None: + adaptative = True + adaptative = _execute.make_bool(adaptative, "adaptative") + sparse_example_indices = _ops.convert_n_to_tensor(sparse_example_indices, _dtypes.int64) + sparse_feature_indices = _ops.convert_n_to_tensor(sparse_feature_indices, _dtypes.int64) + sparse_feature_values = _ops.convert_n_to_tensor(sparse_feature_values, _dtypes.float32) + dense_features = _ops.convert_n_to_tensor(dense_features, _dtypes.float32) + example_weights = _ops.convert_to_tensor(example_weights, _dtypes.float32) + example_labels = _ops.convert_to_tensor(example_labels, _dtypes.float32) + sparse_indices = _ops.convert_n_to_tensor(sparse_indices, _dtypes.int64) + sparse_weights = _ops.convert_n_to_tensor(sparse_weights, _dtypes.float32) + dense_weights = _ops.convert_n_to_tensor(dense_weights, _dtypes.float32) + example_state_data = _ops.convert_to_tensor(example_state_data, _dtypes.float32) + _inputs_flat = list(sparse_example_indices) + list(sparse_feature_indices) + list(sparse_feature_values) + list(dense_features) + [example_weights, example_labels] + list(sparse_indices) + list(sparse_weights) + list(dense_weights) + [example_state_data] + _attrs = ("loss_type", loss_type, "adaptative", adaptative, + "num_sparse_features", _attr_num_sparse_features, + "num_sparse_features_with_values", _attr_num_sparse_features_with_values, + "num_dense_features", _attr_num_dense_features, "l1", l1, "l2", l2, + "num_loss_partitions", num_loss_partitions, "num_inner_iterations", + num_inner_iterations) + _result = _execute.execute(b"SdcaOptimizer", _attr_num_sparse_features + + _attr_num_dense_features + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SdcaOptimizer", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:1 + _attr_num_sparse_features]] + _result[1 + _attr_num_sparse_features:] + _result = _result[:2] + [_result[2:]] + _result = _SdcaOptimizerOutput._make(_result) + return _result + +_SdcaOptimizerV2Output = collections.namedtuple( + "SdcaOptimizerV2", + ["out_example_state_data", "out_delta_sparse_weights", "out_delta_dense_weights"]) + + +def sdca_optimizer_v2(sparse_example_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_values: Annotated[List[Any], _atypes.Float32], dense_features: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], example_labels: Annotated[Any, _atypes.Float32], sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_weights: Annotated[List[Any], _atypes.Float32], dense_weights: Annotated[List[Any], _atypes.Float32], example_state_data: Annotated[Any, _atypes.Float32], loss_type: str, l1: float, l2: float, num_loss_partitions: int, num_inner_iterations: int, adaptive:bool=True, name=None): + r"""Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for + + linear models with L1 + L2 regularization. As global optimization objective is + strongly-convex, the optimizer optimizes the dual objective at each step. The + optimizer applies each update one example at a time. Examples are sampled + uniformly, and the optimizer is learning rate free and enjoys linear convergence + rate. + + [Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
+ Shai Shalev-Shwartz, Tong Zhang. 2012 + + $$Loss Objective = \sum f_{i} (wx_{i}) + (l2 / 2) * |w|^2 + l1 * |w|$$ + + [Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
+ Chenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan, + Peter Richtarik, Martin Takac. 2015 + + [Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
+ Dominik Csiba, Zheng Qu, Peter Richtarik. 2015 + + Args: + sparse_example_indices: A list of `Tensor` objects with type `int64`. + a list of vectors which contain example indices. + sparse_feature_indices: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. + a list of vectors which contain feature indices. + sparse_feature_values: A list of `Tensor` objects with type `float32`. + a list of vectors which contains feature value + associated with each feature group. + dense_features: A list of `Tensor` objects with type `float32`. + a list of matrices which contains the dense feature values. + example_weights: A `Tensor` of type `float32`. + a vector which contains the weight associated with each + example. + example_labels: A `Tensor` of type `float32`. + a vector which contains the label/target associated with each + example. + sparse_indices: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. + a list of vectors where each value is the indices which has + corresponding weights in sparse_weights. This field maybe omitted for the + dense approach. + sparse_weights: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. + a list of vectors where each value is the weight associated with + a sparse feature group. + dense_weights: A list with the same length as `dense_features` of `Tensor` objects with type `float32`. + a list of vectors where the values are the weights associated + with a dense feature group. + example_state_data: A `Tensor` of type `float32`. + a list of vectors containing the example state data. + loss_type: A `string` from: `"logistic_loss", "squared_loss", "hinge_loss", "smooth_hinge_loss", "poisson_loss"`. + Type of the primal loss. Currently SdcaSolver supports logistic, + squared and hinge losses. + l1: A `float`. Symmetric l1 regularization strength. + l2: A `float`. Symmetric l2 regularization strength. + num_loss_partitions: An `int` that is `>= 1`. + Number of partitions of the global loss function. + num_inner_iterations: An `int` that is `>= 1`. + Number of iterations per mini-batch. + adaptive: An optional `bool`. Defaults to `True`. + Whether to use Adaptive SDCA for the inner loop. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (out_example_state_data, out_delta_sparse_weights, out_delta_dense_weights). + + out_example_state_data: A `Tensor` of type `float32`. + out_delta_sparse_weights: A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. + out_delta_dense_weights: A list with the same length as `dense_features` of `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SdcaOptimizerV2", name, sparse_example_indices, + sparse_feature_indices, sparse_feature_values, dense_features, + example_weights, example_labels, sparse_indices, sparse_weights, + dense_weights, example_state_data, "loss_type", loss_type, "adaptive", + adaptive, "l1", l1, "l2", l2, "num_loss_partitions", + num_loss_partitions, "num_inner_iterations", num_inner_iterations) + _result = _SdcaOptimizerV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sdca_optimizer_v2_eager_fallback( + sparse_example_indices, sparse_feature_indices, + sparse_feature_values, dense_features, example_weights, + example_labels, sparse_indices, sparse_weights, dense_weights, + example_state_data, loss_type=loss_type, adaptive=adaptive, l1=l1, + l2=l2, num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sparse_example_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_example_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_example_indices) + _attr_num_sparse_features = len(sparse_example_indices) + if not isinstance(sparse_feature_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_feature_indices) + if len(sparse_feature_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_feature_indices' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_feature_indices), _attr_num_sparse_features)) + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_indices) + if len(sparse_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_indices' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_indices), _attr_num_sparse_features)) + if not isinstance(sparse_weights, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_weights' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_weights) + if len(sparse_weights) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_weights' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_weights), _attr_num_sparse_features)) + if not isinstance(sparse_feature_values, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_values' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_feature_values) + _attr_num_sparse_features_with_values = len(sparse_feature_values) + if not isinstance(dense_features, (list, tuple)): + raise TypeError( + "Expected list for 'dense_features' argument to " + "'sdca_optimizer_v2' Op, not %r." % dense_features) + _attr_num_dense_features = len(dense_features) + if not isinstance(dense_weights, (list, tuple)): + raise TypeError( + "Expected list for 'dense_weights' argument to " + "'sdca_optimizer_v2' Op, not %r." % dense_weights) + if len(dense_weights) != _attr_num_dense_features: + raise ValueError( + "List argument 'dense_weights' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'dense_features'." % + (len(dense_weights), _attr_num_dense_features)) + loss_type = _execute.make_str(loss_type, "loss_type") + l1 = _execute.make_float(l1, "l1") + l2 = _execute.make_float(l2, "l2") + num_loss_partitions = _execute.make_int(num_loss_partitions, "num_loss_partitions") + num_inner_iterations = _execute.make_int(num_inner_iterations, "num_inner_iterations") + if adaptive is None: + adaptive = True + adaptive = _execute.make_bool(adaptive, "adaptive") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SdcaOptimizerV2", sparse_example_indices=sparse_example_indices, + sparse_feature_indices=sparse_feature_indices, + sparse_feature_values=sparse_feature_values, + dense_features=dense_features, + example_weights=example_weights, + example_labels=example_labels, + sparse_indices=sparse_indices, + sparse_weights=sparse_weights, + dense_weights=dense_weights, + example_state_data=example_state_data, + loss_type=loss_type, l1=l1, l2=l2, + num_loss_partitions=num_loss_partitions, + num_inner_iterations=num_inner_iterations, + adaptive=adaptive, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("loss_type", _op.get_attr("loss_type"), "adaptive", + _op._get_attr_bool("adaptive"), "num_sparse_features", + _op._get_attr_int("num_sparse_features"), + "num_sparse_features_with_values", + _op._get_attr_int("num_sparse_features_with_values"), + "num_dense_features", _op._get_attr_int("num_dense_features"), + "l1", _op.get_attr("l1"), "l2", _op.get_attr("l2"), + "num_loss_partitions", _op._get_attr_int("num_loss_partitions"), + "num_inner_iterations", + _op._get_attr_int("num_inner_iterations")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SdcaOptimizerV2", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:1 + _attr_num_sparse_features]] + _result[1 + _attr_num_sparse_features:] + _result = _result[:2] + [_result[2:]] + _result = _SdcaOptimizerV2Output._make(_result) + return _result + +SdcaOptimizerV2 = tf_export("raw_ops.SdcaOptimizerV2")(_ops.to_raw_op(sdca_optimizer_v2)) + + +def sdca_optimizer_v2_eager_fallback(sparse_example_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_indices: Annotated[List[Any], _atypes.Int64], sparse_feature_values: Annotated[List[Any], _atypes.Float32], dense_features: Annotated[List[Any], _atypes.Float32], example_weights: Annotated[Any, _atypes.Float32], example_labels: Annotated[Any, _atypes.Float32], sparse_indices: Annotated[List[Any], _atypes.Int64], sparse_weights: Annotated[List[Any], _atypes.Float32], dense_weights: Annotated[List[Any], _atypes.Float32], example_state_data: Annotated[Any, _atypes.Float32], loss_type: str, l1: float, l2: float, num_loss_partitions: int, num_inner_iterations: int, adaptive: bool, name, ctx): + if not isinstance(sparse_example_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_example_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_example_indices) + _attr_num_sparse_features = len(sparse_example_indices) + if not isinstance(sparse_feature_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_feature_indices) + if len(sparse_feature_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_feature_indices' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_feature_indices), _attr_num_sparse_features)) + if not isinstance(sparse_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_indices' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_indices) + if len(sparse_indices) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_indices' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_indices), _attr_num_sparse_features)) + if not isinstance(sparse_weights, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_weights' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_weights) + if len(sparse_weights) != _attr_num_sparse_features: + raise ValueError( + "List argument 'sparse_weights' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'sparse_example_indices'." % + (len(sparse_weights), _attr_num_sparse_features)) + if not isinstance(sparse_feature_values, (list, tuple)): + raise TypeError( + "Expected list for 'sparse_feature_values' argument to " + "'sdca_optimizer_v2' Op, not %r." % sparse_feature_values) + _attr_num_sparse_features_with_values = len(sparse_feature_values) + if not isinstance(dense_features, (list, tuple)): + raise TypeError( + "Expected list for 'dense_features' argument to " + "'sdca_optimizer_v2' Op, not %r." % dense_features) + _attr_num_dense_features = len(dense_features) + if not isinstance(dense_weights, (list, tuple)): + raise TypeError( + "Expected list for 'dense_weights' argument to " + "'sdca_optimizer_v2' Op, not %r." % dense_weights) + if len(dense_weights) != _attr_num_dense_features: + raise ValueError( + "List argument 'dense_weights' to 'sdca_optimizer_v2' Op with length %d " + "must match length %d of argument 'dense_features'." % + (len(dense_weights), _attr_num_dense_features)) + loss_type = _execute.make_str(loss_type, "loss_type") + l1 = _execute.make_float(l1, "l1") + l2 = _execute.make_float(l2, "l2") + num_loss_partitions = _execute.make_int(num_loss_partitions, "num_loss_partitions") + num_inner_iterations = _execute.make_int(num_inner_iterations, "num_inner_iterations") + if adaptive is None: + adaptive = True + adaptive = _execute.make_bool(adaptive, "adaptive") + sparse_example_indices = _ops.convert_n_to_tensor(sparse_example_indices, _dtypes.int64) + sparse_feature_indices = _ops.convert_n_to_tensor(sparse_feature_indices, _dtypes.int64) + sparse_feature_values = _ops.convert_n_to_tensor(sparse_feature_values, _dtypes.float32) + dense_features = _ops.convert_n_to_tensor(dense_features, _dtypes.float32) + example_weights = _ops.convert_to_tensor(example_weights, _dtypes.float32) + example_labels = _ops.convert_to_tensor(example_labels, _dtypes.float32) + sparse_indices = _ops.convert_n_to_tensor(sparse_indices, _dtypes.int64) + sparse_weights = _ops.convert_n_to_tensor(sparse_weights, _dtypes.float32) + dense_weights = _ops.convert_n_to_tensor(dense_weights, _dtypes.float32) + example_state_data = _ops.convert_to_tensor(example_state_data, _dtypes.float32) + _inputs_flat = list(sparse_example_indices) + list(sparse_feature_indices) + list(sparse_feature_values) + list(dense_features) + [example_weights, example_labels] + list(sparse_indices) + list(sparse_weights) + list(dense_weights) + [example_state_data] + _attrs = ("loss_type", loss_type, "adaptive", adaptive, + "num_sparse_features", _attr_num_sparse_features, + "num_sparse_features_with_values", _attr_num_sparse_features_with_values, + "num_dense_features", _attr_num_dense_features, "l1", l1, "l2", l2, + "num_loss_partitions", num_loss_partitions, "num_inner_iterations", + num_inner_iterations) + _result = _execute.execute(b"SdcaOptimizerV2", _attr_num_sparse_features + + _attr_num_dense_features + 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SdcaOptimizerV2", _inputs_flat, _attrs, _result) + _result = _result[:1] + [_result[1:1 + _attr_num_sparse_features]] + _result[1 + _attr_num_sparse_features:] + _result = _result[:2] + [_result[2:]] + _result = _SdcaOptimizerV2Output._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export(v1=['train.sdca_shrink_l1']) +@deprecated_endpoints('train.sdca_shrink_l1') +def sdca_shrink_l1(weights: Annotated[List[Any], _atypes.Float32], l1: float, l2: float, name=None): + r"""Applies L1 regularization shrink step on the parameters. + + Args: + weights: A list of `Tensor` objects with type mutable `float32`. + a list of vectors where each value is the weight associated with a + feature group. + l1: A `float`. Symmetric l1 regularization strength. + l2: A `float`. + Symmetric l2 regularization strength. Should be a positive float. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sdca_shrink_l1 op does not support eager execution. Arg 'weights' is a ref.") + else: + _result = _dispatcher_for_sdca_shrink_l1( + (weights, l1, l2, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(weights, (list, tuple)): + raise TypeError( + "Expected list for 'weights' argument to " + "'sdca_shrink_l1' Op, not %r." % weights) + _attr_num_features = len(weights) + l1 = _execute.make_float(l1, "l1") + l2 = _execute.make_float(l2, "l2") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SdcaShrinkL1", weights=weights, l1=l1, l2=l2, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sdca_shrink_l1, (), dict(weights=weights, l1=l1, l2=l2, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +SdcaShrinkL1 = tf_export("raw_ops.SdcaShrinkL1")(_ops.to_raw_op(sdca_shrink_l1)) +_dispatcher_for_sdca_shrink_l1 = sdca_shrink_l1._tf_type_based_dispatcher.Dispatch + + +def sdca_shrink_l1_eager_fallback(weights: Annotated[List[Any], _atypes.Float32], l1: float, l2: float, name, ctx): + raise RuntimeError("sdca_shrink_l1 op does not support eager execution. Arg 'weights' is a ref.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sendrecv_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sendrecv_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2f64081db3bc417bfe158c4b9c67f64955ffb43e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sendrecv_ops.py @@ -0,0 +1,201 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Recv_tensor_type = TypeVar("TV_Recv_tensor_type", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def recv(tensor_type: TV_Recv_tensor_type, tensor_name: str, send_device: str, send_device_incarnation: int, recv_device: str, client_terminated:bool=False, name=None) -> Annotated[Any, TV_Recv_tensor_type]: + r"""Receives the named tensor from send_device on recv_device. + + Args: + tensor_type: A `tf.DType`. + tensor_name: A `string`. The name of the tensor to receive. + send_device: A `string`. The name of the device sending the tensor. + send_device_incarnation: An `int`. The current incarnation of send_device. + recv_device: A `string`. The name of the device receiving the tensor. + client_terminated: An optional `bool`. Defaults to `False`. + If set to true, this indicates that the node was added + to the graph as a result of a client-side feed or fetch of Tensor data, + in which case the corresponding send or recv is expected to be managed + locally by the caller. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `tensor_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Recv", name, "tensor_type", tensor_type, "tensor_name", + tensor_name, "send_device", send_device, "send_device_incarnation", + send_device_incarnation, "recv_device", recv_device, + "client_terminated", client_terminated) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return recv_eager_fallback( + tensor_type=tensor_type, tensor_name=tensor_name, + send_device=send_device, + send_device_incarnation=send_device_incarnation, + recv_device=recv_device, client_terminated=client_terminated, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + tensor_type = _execute.make_type(tensor_type, "tensor_type") + tensor_name = _execute.make_str(tensor_name, "tensor_name") + send_device = _execute.make_str(send_device, "send_device") + send_device_incarnation = _execute.make_int(send_device_incarnation, "send_device_incarnation") + recv_device = _execute.make_str(recv_device, "recv_device") + if client_terminated is None: + client_terminated = False + client_terminated = _execute.make_bool(client_terminated, "client_terminated") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Recv", tensor_type=tensor_type, tensor_name=tensor_name, + send_device=send_device, + send_device_incarnation=send_device_incarnation, + recv_device=recv_device, client_terminated=client_terminated, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("tensor_type", _op._get_attr_type("tensor_type"), "tensor_name", + _op.get_attr("tensor_name"), "send_device", + _op.get_attr("send_device"), "send_device_incarnation", + _op._get_attr_int("send_device_incarnation"), "recv_device", + _op.get_attr("recv_device"), "client_terminated", + _op._get_attr_bool("client_terminated")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Recv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Recv = tf_export("raw_ops.Recv")(_ops.to_raw_op(recv)) + + +def recv_eager_fallback(tensor_type: TV_Recv_tensor_type, tensor_name: str, send_device: str, send_device_incarnation: int, recv_device: str, client_terminated: bool, name, ctx) -> Annotated[Any, TV_Recv_tensor_type]: + tensor_type = _execute.make_type(tensor_type, "tensor_type") + tensor_name = _execute.make_str(tensor_name, "tensor_name") + send_device = _execute.make_str(send_device, "send_device") + send_device_incarnation = _execute.make_int(send_device_incarnation, "send_device_incarnation") + recv_device = _execute.make_str(recv_device, "recv_device") + if client_terminated is None: + client_terminated = False + client_terminated = _execute.make_bool(client_terminated, "client_terminated") + _inputs_flat = [] + _attrs = ("tensor_type", tensor_type, "tensor_name", tensor_name, + "send_device", send_device, "send_device_incarnation", + send_device_incarnation, "recv_device", recv_device, "client_terminated", + client_terminated) + _result = _execute.execute(b"Recv", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Recv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Send_T = TypeVar("TV_Send_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def send(tensor: Annotated[Any, TV_Send_T], tensor_name: str, send_device: str, send_device_incarnation: int, recv_device: str, client_terminated:bool=False, name=None): + r"""Sends the named tensor from send_device to recv_device. + + Args: + tensor: A `Tensor`. The tensor to send. + tensor_name: A `string`. The name of the tensor to send. + send_device: A `string`. The name of the device sending the tensor. + send_device_incarnation: An `int`. The current incarnation of send_device. + recv_device: A `string`. The name of the device receiving the tensor. + client_terminated: An optional `bool`. Defaults to `False`. + If set to true, this indicates that the node was added + to the graph as a result of a client-side feed or fetch of Tensor data, + in which case the corresponding send or recv is expected to be managed + locally by the caller. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Send", name, tensor, "tensor_name", tensor_name, "send_device", + send_device, "send_device_incarnation", send_device_incarnation, + "recv_device", recv_device, "client_terminated", client_terminated) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return send_eager_fallback( + tensor, tensor_name=tensor_name, send_device=send_device, + send_device_incarnation=send_device_incarnation, + recv_device=recv_device, client_terminated=client_terminated, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + tensor_name = _execute.make_str(tensor_name, "tensor_name") + send_device = _execute.make_str(send_device, "send_device") + send_device_incarnation = _execute.make_int(send_device_incarnation, "send_device_incarnation") + recv_device = _execute.make_str(recv_device, "recv_device") + if client_terminated is None: + client_terminated = False + client_terminated = _execute.make_bool(client_terminated, "client_terminated") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Send", tensor=tensor, tensor_name=tensor_name, + send_device=send_device, + send_device_incarnation=send_device_incarnation, + recv_device=recv_device, client_terminated=client_terminated, + name=name) + return _op +Send = tf_export("raw_ops.Send")(_ops.to_raw_op(send)) + + +def send_eager_fallback(tensor: Annotated[Any, TV_Send_T], tensor_name: str, send_device: str, send_device_incarnation: int, recv_device: str, client_terminated: bool, name, ctx): + tensor_name = _execute.make_str(tensor_name, "tensor_name") + send_device = _execute.make_str(send_device, "send_device") + send_device_incarnation = _execute.make_int(send_device_incarnation, "send_device_incarnation") + recv_device = _execute.make_str(recv_device, "recv_device") + if client_terminated is None: + client_terminated = False + client_terminated = _execute.make_bool(client_terminated, "client_terminated") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + _inputs_flat = [tensor] + _attrs = ("T", _attr_T, "tensor_name", tensor_name, "send_device", + send_device, "send_device_incarnation", send_device_incarnation, + "recv_device", recv_device, "client_terminated", client_terminated) + _result = _execute.execute(b"Send", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_set_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_set_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9e47c01a4e5d06f8912b45ca46b126c4d5a6fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_set_ops.py @@ -0,0 +1,462 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_DenseToDenseSetOperationOutput = collections.namedtuple( + "DenseToDenseSetOperation", + ["result_indices", "result_values", "result_shape"]) + + +TV_DenseToDenseSetOperation_T = TypeVar("TV_DenseToDenseSetOperation_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt8) + +def dense_to_dense_set_operation(set1: Annotated[Any, TV_DenseToDenseSetOperation_T], set2: Annotated[Any, TV_DenseToDenseSetOperation_T], set_operation: str, validate_indices:bool=True, name=None): + r"""Applies set operation along last dimension of 2 `Tensor` inputs. + + See SetOperationOp::SetOperationFromContext for values of `set_operation`. + + Output `result` is a `SparseTensor` represented by `result_indices`, + `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this + has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` + dimension contains the result of `set_operation` applied to the corresponding + `[0...n-1]` dimension of `set`. + + Args: + set1: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`. + `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. + Dimension `n` contains values in a set, duplicates are allowed but ignored. + set2: A `Tensor`. Must have the same type as `set1`. + `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set1`. + Dimension `n` contains values in a set, duplicates are allowed but ignored. + set_operation: A `string`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (result_indices, result_values, result_shape). + + result_indices: A `Tensor` of type `int64`. + result_values: A `Tensor`. Has the same type as `set1`. + result_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseToDenseSetOperation", name, set1, set2, "set_operation", + set_operation, "validate_indices", validate_indices) + _result = _DenseToDenseSetOperationOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_to_dense_set_operation_eager_fallback( + set1, set2, set_operation=set_operation, + validate_indices=validate_indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseToDenseSetOperation", set1=set1, set2=set2, + set_operation=set_operation, + validate_indices=validate_indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("set_operation", _op.get_attr("set_operation"), + "validate_indices", _op._get_attr_bool("validate_indices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseToDenseSetOperation", _inputs_flat, _attrs, _result) + _result = _DenseToDenseSetOperationOutput._make(_result) + return _result + +DenseToDenseSetOperation = tf_export("raw_ops.DenseToDenseSetOperation")(_ops.to_raw_op(dense_to_dense_set_operation)) + + +def dense_to_dense_set_operation_eager_fallback(set1: Annotated[Any, TV_DenseToDenseSetOperation_T], set2: Annotated[Any, TV_DenseToDenseSetOperation_T], set_operation: str, validate_indices: bool, name, ctx): + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_T, _inputs_T = _execute.args_to_matching_eager([set1, set2], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.string, ]) + (set1, set2) = _inputs_T + _inputs_flat = [set1, set2] + _attrs = ("set_operation", set_operation, "validate_indices", + validate_indices, "T", _attr_T) + _result = _execute.execute(b"DenseToDenseSetOperation", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseToDenseSetOperation", _inputs_flat, _attrs, _result) + _result = _DenseToDenseSetOperationOutput._make(_result) + return _result + +_DenseToSparseSetOperationOutput = collections.namedtuple( + "DenseToSparseSetOperation", + ["result_indices", "result_values", "result_shape"]) + + +TV_DenseToSparseSetOperation_T = TypeVar("TV_DenseToSparseSetOperation_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt8) + +def dense_to_sparse_set_operation(set1: Annotated[Any, TV_DenseToSparseSetOperation_T], set2_indices: Annotated[Any, _atypes.Int64], set2_values: Annotated[Any, TV_DenseToSparseSetOperation_T], set2_shape: Annotated[Any, _atypes.Int64], set_operation: str, validate_indices:bool=True, name=None): + r"""Applies set operation along last dimension of `Tensor` and `SparseTensor`. + + See SetOperationOp::SetOperationFromContext for values of `set_operation`. + + Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, + and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same + as `set1`. Dimension `n` contains values in a set, duplicates are allowed but + ignored. + + If `validate_indices` is `True`, this op validates the order and range of `set2` + indices. + + Output `result` is a `SparseTensor` represented by `result_indices`, + `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this + has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` + dimension contains the result of `set_operation` applied to the corresponding + `[0...n-1]` dimension of `set`. + + Args: + set1: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`. + `Tensor` with rank `n`. 1st `n-1` dimensions must be the same as `set2`. + Dimension `n` contains values in a set, duplicates are allowed but ignored. + set2_indices: A `Tensor` of type `int64`. + 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major + order. + set2_values: A `Tensor`. Must have the same type as `set1`. + 1D `Tensor`, values of a `SparseTensor`. Must be in row-major + order. + set2_shape: A `Tensor` of type `int64`. + 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must + be the same as the 1st `n-1` dimensions of `set1`, `result_shape[n]` is the + max set size across `n-1` dimensions. + set_operation: A `string`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (result_indices, result_values, result_shape). + + result_indices: A `Tensor` of type `int64`. + result_values: A `Tensor`. Has the same type as `set1`. + result_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseToSparseSetOperation", name, set1, set2_indices, + set2_values, set2_shape, "set_operation", set_operation, + "validate_indices", validate_indices) + _result = _DenseToSparseSetOperationOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_to_sparse_set_operation_eager_fallback( + set1, set2_indices, set2_values, set2_shape, + set_operation=set_operation, validate_indices=validate_indices, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseToSparseSetOperation", set1=set1, set2_indices=set2_indices, + set2_values=set2_values, + set2_shape=set2_shape, + set_operation=set_operation, + validate_indices=validate_indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("set_operation", _op.get_attr("set_operation"), + "validate_indices", _op._get_attr_bool("validate_indices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseToSparseSetOperation", _inputs_flat, _attrs, _result) + _result = _DenseToSparseSetOperationOutput._make(_result) + return _result + +DenseToSparseSetOperation = tf_export("raw_ops.DenseToSparseSetOperation")(_ops.to_raw_op(dense_to_sparse_set_operation)) + + +def dense_to_sparse_set_operation_eager_fallback(set1: Annotated[Any, TV_DenseToSparseSetOperation_T], set2_indices: Annotated[Any, _atypes.Int64], set2_values: Annotated[Any, TV_DenseToSparseSetOperation_T], set2_shape: Annotated[Any, _atypes.Int64], set_operation: str, validate_indices: bool, name, ctx): + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_T, _inputs_T = _execute.args_to_matching_eager([set1, set2_values], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.string, ]) + (set1, set2_values) = _inputs_T + set2_indices = _ops.convert_to_tensor(set2_indices, _dtypes.int64) + set2_shape = _ops.convert_to_tensor(set2_shape, _dtypes.int64) + _inputs_flat = [set1, set2_indices, set2_values, set2_shape] + _attrs = ("set_operation", set_operation, "validate_indices", + validate_indices, "T", _attr_T) + _result = _execute.execute(b"DenseToSparseSetOperation", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseToSparseSetOperation", _inputs_flat, _attrs, _result) + _result = _DenseToSparseSetOperationOutput._make(_result) + return _result + + +TV_SetSize_T = TypeVar("TV_SetSize_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt8) + +def set_size(set_indices: Annotated[Any, _atypes.Int64], set_values: Annotated[Any, TV_SetSize_T], set_shape: Annotated[Any, _atypes.Int64], validate_indices:bool=True, name=None) -> Annotated[Any, _atypes.Int32]: + r"""Number of unique elements along last dimension of input `set`. + + Input `set` is a `SparseTensor` represented by `set_indices`, `set_values`, + and `set_shape`. The last dimension contains values in a set, duplicates are + allowed but ignored. + + If `validate_indices` is `True`, this op validates the order and range of `set` + indices. Setting is to `False` while passing invalid arguments results in + undefined behavior. + + Args: + set_indices: A `Tensor` of type `int64`. + 2D `Tensor`, indices of a `SparseTensor`. + set_values: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`. + 1D `Tensor`, values of a `SparseTensor`. + set_shape: A `Tensor` of type `int64`. + 1D `Tensor`, shape of a `SparseTensor`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SetSize", name, set_indices, set_values, set_shape, + "validate_indices", validate_indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return set_size_eager_fallback( + set_indices, set_values, set_shape, + validate_indices=validate_indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SetSize", set_indices=set_indices, set_values=set_values, + set_shape=set_shape, validate_indices=validate_indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("validate_indices", _op._get_attr_bool("validate_indices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SetSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SetSize = tf_export("raw_ops.SetSize")(_ops.to_raw_op(set_size)) + + +def set_size_eager_fallback(set_indices: Annotated[Any, _atypes.Int64], set_values: Annotated[Any, TV_SetSize_T], set_shape: Annotated[Any, _atypes.Int64], validate_indices: bool, name, ctx) -> Annotated[Any, _atypes.Int32]: + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_T, (set_values,) = _execute.args_to_matching_eager([set_values], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.string, ]) + set_indices = _ops.convert_to_tensor(set_indices, _dtypes.int64) + set_shape = _ops.convert_to_tensor(set_shape, _dtypes.int64) + _inputs_flat = [set_indices, set_values, set_shape] + _attrs = ("validate_indices", validate_indices, "T", _attr_T) + _result = _execute.execute(b"SetSize", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SetSize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseToSparseSetOperationOutput = collections.namedtuple( + "SparseToSparseSetOperation", + ["result_indices", "result_values", "result_shape"]) + + +TV_SparseToSparseSetOperation_T = TypeVar("TV_SparseToSparseSetOperation_T", _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt8) + +def sparse_to_sparse_set_operation(set1_indices: Annotated[Any, _atypes.Int64], set1_values: Annotated[Any, TV_SparseToSparseSetOperation_T], set1_shape: Annotated[Any, _atypes.Int64], set2_indices: Annotated[Any, _atypes.Int64], set2_values: Annotated[Any, TV_SparseToSparseSetOperation_T], set2_shape: Annotated[Any, _atypes.Int64], set_operation: str, validate_indices:bool=True, name=None): + r"""Applies set operation along last dimension of 2 `SparseTensor` inputs. + + See SetOperationOp::SetOperationFromContext for values of `set_operation`. + + If `validate_indices` is `True`, `SparseToSparseSetOperation` validates the + order and range of `set1` and `set2` indices. + + Input `set1` is a `SparseTensor` represented by `set1_indices`, `set1_values`, + and `set1_shape`. For `set1` ranked `n`, 1st `n-1` dimensions must be the same + as `set2`. Dimension `n` contains values in a set, duplicates are allowed but + ignored. + + Input `set2` is a `SparseTensor` represented by `set2_indices`, `set2_values`, + and `set2_shape`. For `set2` ranked `n`, 1st `n-1` dimensions must be the same + as `set1`. Dimension `n` contains values in a set, duplicates are allowed but + ignored. + + If `validate_indices` is `True`, this op validates the order and range of `set1` + and `set2` indices. + + Output `result` is a `SparseTensor` represented by `result_indices`, + `result_values`, and `result_shape`. For `set1` and `set2` ranked `n`, this + has rank `n` and the same 1st `n-1` dimensions as `set1` and `set2`. The `nth` + dimension contains the result of `set_operation` applied to the corresponding + `[0...n-1]` dimension of `set`. + + Args: + set1_indices: A `Tensor` of type `int64`. + 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major + order. + set1_values: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `string`. + 1D `Tensor`, values of a `SparseTensor`. Must be in row-major + order. + set1_shape: A `Tensor` of type `int64`. + 1D `Tensor`, shape of a `SparseTensor`. `set1_shape[0...n-1]` must + be the same as `set2_shape[0...n-1]`, `set1_shape[n]` is the + max set size across `0...n-1` dimensions. + set2_indices: A `Tensor` of type `int64`. + 2D `Tensor`, indices of a `SparseTensor`. Must be in row-major + order. + set2_values: A `Tensor`. Must have the same type as `set1_values`. + 1D `Tensor`, values of a `SparseTensor`. Must be in row-major + order. + set2_shape: A `Tensor` of type `int64`. + 1D `Tensor`, shape of a `SparseTensor`. `set2_shape[0...n-1]` must + be the same as `set1_shape[0...n-1]`, `set2_shape[n]` is the + max set size across `0...n-1` dimensions. + set_operation: A `string`. + validate_indices: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (result_indices, result_values, result_shape). + + result_indices: A `Tensor` of type `int64`. + result_values: A `Tensor`. Has the same type as `set1_values`. + result_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseToSparseSetOperation", name, set1_indices, set1_values, + set1_shape, set2_indices, set2_values, set2_shape, "set_operation", + set_operation, "validate_indices", validate_indices) + _result = _SparseToSparseSetOperationOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_to_sparse_set_operation_eager_fallback( + set1_indices, set1_values, set1_shape, set2_indices, set2_values, + set2_shape, set_operation=set_operation, + validate_indices=validate_indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseToSparseSetOperation", set1_indices=set1_indices, + set1_values=set1_values, + set1_shape=set1_shape, + set2_indices=set2_indices, + set2_values=set2_values, + set2_shape=set2_shape, + set_operation=set_operation, + validate_indices=validate_indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("set_operation", _op.get_attr("set_operation"), + "validate_indices", _op._get_attr_bool("validate_indices"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseToSparseSetOperation", _inputs_flat, _attrs, _result) + _result = _SparseToSparseSetOperationOutput._make(_result) + return _result + +SparseToSparseSetOperation = tf_export("raw_ops.SparseToSparseSetOperation")(_ops.to_raw_op(sparse_to_sparse_set_operation)) + + +def sparse_to_sparse_set_operation_eager_fallback(set1_indices: Annotated[Any, _atypes.Int64], set1_values: Annotated[Any, TV_SparseToSparseSetOperation_T], set1_shape: Annotated[Any, _atypes.Int64], set2_indices: Annotated[Any, _atypes.Int64], set2_values: Annotated[Any, TV_SparseToSparseSetOperation_T], set2_shape: Annotated[Any, _atypes.Int64], set_operation: str, validate_indices: bool, name, ctx): + set_operation = _execute.make_str(set_operation, "set_operation") + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_T, _inputs_T = _execute.args_to_matching_eager([set1_values, set2_values], ctx, [_dtypes.int8, _dtypes.int16, _dtypes.int32, _dtypes.int64, _dtypes.uint8, _dtypes.uint16, _dtypes.string, ]) + (set1_values, set2_values) = _inputs_T + set1_indices = _ops.convert_to_tensor(set1_indices, _dtypes.int64) + set1_shape = _ops.convert_to_tensor(set1_shape, _dtypes.int64) + set2_indices = _ops.convert_to_tensor(set2_indices, _dtypes.int64) + set2_shape = _ops.convert_to_tensor(set2_shape, _dtypes.int64) + _inputs_flat = [set1_indices, set1_values, set1_shape, set2_indices, set2_values, set2_shape] + _attrs = ("set_operation", set_operation, "validate_indices", + validate_indices, "T", _attr_T) + _result = _execute.execute(b"SparseToSparseSetOperation", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseToSparseSetOperation", _inputs_flat, _attrs, _result) + _result = _SparseToSparseSetOperationOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sparse_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sparse_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa990180537e6e28846d34430e8262f08dbc188 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sparse_ops.py @@ -0,0 +1,3427 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AddManySparseToTensorsMap_T = TypeVar("TV_AddManySparseToTensorsMap_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def add_many_sparse_to_tensors_map(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_AddManySparseToTensorsMap_T], sparse_shape: Annotated[Any, _atypes.Int64], container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int64]: + r"""Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. + + A `SparseTensor` of rank `R` is represented by three tensors: `sparse_indices`, + `sparse_values`, and `sparse_shape`, where + + ```sparse_indices.shape[1] == sparse_shape.shape[0] == R``` + + An `N`-minibatch of `SparseTensor` objects is represented as a `SparseTensor` + having a first `sparse_indices` column taking values between `[0, N)`, where + the minibatch size `N == sparse_shape[0]`. + + The input `SparseTensor` must have rank `R` greater than 1, and the first + dimension is treated as the minibatch dimension. Elements of the `SparseTensor` + must be sorted in increasing order of this first dimension. The stored + `SparseTensor` objects pointed to by each row of the output `sparse_handles` + will have rank `R-1`. + + The `SparseTensor` values can then be read out as part of a minibatch by passing + the given keys as vector elements to `TakeManySparseFromTensorsMap`. To ensure + the correct `SparseTensorsMap` is accessed, ensure that the same + `container` and `shared_name` are passed to that Op. If no `shared_name` + is provided here, instead use the *name* of the Operation created by calling + `AddManySparseToTensorsMap` as the `shared_name` passed to + `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. + + Args: + sparse_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the minibatch `SparseTensor`. + `sparse_indices[:, 0]` must be ordered values in `[0, N)`. + sparse_values: A `Tensor`. + 1-D. The `values` of the minibatch `SparseTensor`. + sparse_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the minibatch `SparseTensor`. + The minibatch size `N == sparse_shape[0]`. + container: An optional `string`. Defaults to `""`. + The container name for the `SparseTensorsMap` created by this op. + shared_name: An optional `string`. Defaults to `""`. + The shared name for the `SparseTensorsMap` created by this op. + If blank, the new Operation's unique name is used. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AddManySparseToTensorsMap", name, sparse_indices, + sparse_values, sparse_shape, "container", container, "shared_name", + shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return add_many_sparse_to_tensors_map_eager_fallback( + sparse_indices, sparse_values, sparse_shape, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AddManySparseToTensorsMap", sparse_indices=sparse_indices, + sparse_values=sparse_values, + sparse_shape=sparse_shape, + container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AddManySparseToTensorsMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AddManySparseToTensorsMap = tf_export("raw_ops.AddManySparseToTensorsMap")(_ops.to_raw_op(add_many_sparse_to_tensors_map)) + + +def add_many_sparse_to_tensors_map_eager_fallback(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_AddManySparseToTensorsMap_T], sparse_shape: Annotated[Any, _atypes.Int64], container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int64]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_T, (sparse_values,) = _execute.args_to_matching_eager([sparse_values], ctx, []) + sparse_indices = _ops.convert_to_tensor(sparse_indices, _dtypes.int64) + sparse_shape = _ops.convert_to_tensor(sparse_shape, _dtypes.int64) + _inputs_flat = [sparse_indices, sparse_values, sparse_shape] + _attrs = ("T", _attr_T, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"AddManySparseToTensorsMap", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AddManySparseToTensorsMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AddSparseToTensorsMap_T = TypeVar("TV_AddSparseToTensorsMap_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def add_sparse_to_tensors_map(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_AddSparseToTensorsMap_T], sparse_shape: Annotated[Any, _atypes.Int64], container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Int64]: + r"""Add a `SparseTensor` to a `SparseTensorsMap` return its handle. + + A `SparseTensor` is represented by three tensors: `sparse_indices`, + `sparse_values`, and `sparse_shape`. + + This operator takes the given `SparseTensor` and adds it to a container + object (a `SparseTensorsMap`). A unique key within this container is generated + in the form of an `int64`, and this is the value that is returned. + + The `SparseTensor` can then be read out as part of a minibatch by passing + the key as a vector element to `TakeManySparseFromTensorsMap`. To ensure + the correct `SparseTensorsMap` is accessed, ensure that the same + `container` and `shared_name` are passed to that Op. If no `shared_name` + is provided here, instead use the *name* of the Operation created by calling + `AddSparseToTensorsMap` as the `shared_name` passed to + `TakeManySparseFromTensorsMap`. Ensure the Operations are colocated. + + Args: + sparse_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the `SparseTensor`. + sparse_values: A `Tensor`. 1-D. The `values` of the `SparseTensor`. + sparse_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the `SparseTensor`. + container: An optional `string`. Defaults to `""`. + The container name for the `SparseTensorsMap` created by this op. + shared_name: An optional `string`. Defaults to `""`. + The shared name for the `SparseTensorsMap` created by this op. + If blank, the new Operation's unique name is used. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AddSparseToTensorsMap", name, sparse_indices, sparse_values, + sparse_shape, "container", container, "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return add_sparse_to_tensors_map_eager_fallback( + sparse_indices, sparse_values, sparse_shape, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AddSparseToTensorsMap", sparse_indices=sparse_indices, + sparse_values=sparse_values, + sparse_shape=sparse_shape, + container=container, shared_name=shared_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AddSparseToTensorsMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AddSparseToTensorsMap = tf_export("raw_ops.AddSparseToTensorsMap")(_ops.to_raw_op(add_sparse_to_tensors_map)) + + +def add_sparse_to_tensors_map_eager_fallback(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_AddSparseToTensorsMap_T], sparse_shape: Annotated[Any, _atypes.Int64], container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Int64]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _attr_T, (sparse_values,) = _execute.args_to_matching_eager([sparse_values], ctx, []) + sparse_indices = _ops.convert_to_tensor(sparse_indices, _dtypes.int64) + sparse_shape = _ops.convert_to_tensor(sparse_shape, _dtypes.int64) + _inputs_flat = [sparse_indices, sparse_values, sparse_shape] + _attrs = ("T", _attr_T, "container", container, "shared_name", shared_name) + _result = _execute.execute(b"AddSparseToTensorsMap", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AddSparseToTensorsMap", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_DeserializeManySparseOutput = collections.namedtuple( + "DeserializeManySparse", + ["sparse_indices", "sparse_values", "sparse_shape"]) + + +TV_DeserializeManySparse_dtype = TypeVar("TV_DeserializeManySparse_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def deserialize_many_sparse(serialized_sparse: Annotated[Any, _atypes.String], dtype: TV_DeserializeManySparse_dtype, name=None): + r"""Deserialize and concatenate `SparseTensors` from a serialized minibatch. + + The input `serialized_sparse` must be a string matrix of shape `[N x 3]` where + `N` is the minibatch size and the rows correspond to packed outputs of + `SerializeSparse`. The ranks of the original `SparseTensor` objects + must all match. When the final `SparseTensor` is created, it has rank one + higher than the ranks of the incoming `SparseTensor` objects + (they have been concatenated along a new row dimension). + + The output `SparseTensor` object's shape values for all dimensions but the + first are the max across the input `SparseTensor` objects' shape values + for the corresponding dimensions. Its first shape value is `N`, the minibatch + size. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `SparseReorder` to restore index ordering. + + For example, if the serialized input is a `[2 x 3]` matrix representing two + original `SparseTensor` objects: + + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + + and + + index = [ 2] + [10] + values = [4, 5] + shape = [30] + + then the final deserialized `SparseTensor` will be: + + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + + Args: + serialized_sparse: A `Tensor` of type `string`. + 2-D, The `N` serialized `SparseTensor` objects. + Must have 3 columns. + dtype: A `tf.DType`. The `dtype` of the serialized `SparseTensor` objects. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shape). + + sparse_indices: A `Tensor` of type `int64`. + sparse_values: A `Tensor` of type `dtype`. + sparse_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeserializeManySparse", name, serialized_sparse, "dtype", + dtype) + _result = _DeserializeManySparseOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return deserialize_many_sparse_eager_fallback( + serialized_sparse, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeserializeManySparse", serialized_sparse=serialized_sparse, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DeserializeManySparse", _inputs_flat, _attrs, _result) + _result = _DeserializeManySparseOutput._make(_result) + return _result + +DeserializeManySparse = tf_export("raw_ops.DeserializeManySparse")(_ops.to_raw_op(deserialize_many_sparse)) + + +def deserialize_many_sparse_eager_fallback(serialized_sparse: Annotated[Any, _atypes.String], dtype: TV_DeserializeManySparse_dtype, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + serialized_sparse = _ops.convert_to_tensor(serialized_sparse, _dtypes.string) + _inputs_flat = [serialized_sparse] + _attrs = ("dtype", dtype) + _result = _execute.execute(b"DeserializeManySparse", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DeserializeManySparse", _inputs_flat, _attrs, _result) + _result = _DeserializeManySparseOutput._make(_result) + return _result + +_DeserializeSparseOutput = collections.namedtuple( + "DeserializeSparse", + ["sparse_indices", "sparse_values", "sparse_shape"]) + + +TV_DeserializeSparse_dtype = TypeVar("TV_DeserializeSparse_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_DeserializeSparse_Tserialized = TypeVar("TV_DeserializeSparse_Tserialized", _atypes.String, _atypes.Variant) + +def deserialize_sparse(serialized_sparse: Annotated[Any, TV_DeserializeSparse_Tserialized], dtype: TV_DeserializeSparse_dtype, name=None): + r"""Deserialize `SparseTensor` objects. + + The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where + the last dimension stores serialized `SparseTensor` objects and the other N + dimensions (N >= 0) correspond to a batch. The ranks of the original + `SparseTensor` objects must all match. When the final `SparseTensor` is + created, its rank is the rank of the incoming `SparseTensor` objects plus N; + the sparse tensors have been concatenated along new dimensions, one for each + batch. + + The output `SparseTensor` object's shape values for the original dimensions + are the max across the input `SparseTensor` objects' shape values for the + corresponding dimensions. The new dimensions match the size of the batch. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `SparseReorder` to restore index ordering. + + For example, if the serialized input is a `[2 x 3]` matrix representing two + original `SparseTensor` objects: + + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + + and + + index = [ 2] + [10] + values = [4, 5] + shape = [30] + + then the final deserialized `SparseTensor` will be: + + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + + Args: + serialized_sparse: A `Tensor`. Must be one of the following types: `string`, `variant`. + The serialized `SparseTensor` objects. The last dimension + must have 3 columns. + dtype: A `tf.DType`. The `dtype` of the serialized `SparseTensor` objects. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shape). + + sparse_indices: A `Tensor` of type `int64`. + sparse_values: A `Tensor` of type `dtype`. + sparse_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DeserializeSparse", name, serialized_sparse, "dtype", dtype) + _result = _DeserializeSparseOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return deserialize_sparse_eager_fallback( + serialized_sparse, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DeserializeSparse", serialized_sparse=serialized_sparse, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tserialized", + _op._get_attr_type("Tserialized")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DeserializeSparse", _inputs_flat, _attrs, _result) + _result = _DeserializeSparseOutput._make(_result) + return _result + +DeserializeSparse = tf_export("raw_ops.DeserializeSparse")(_ops.to_raw_op(deserialize_sparse)) + + +def deserialize_sparse_eager_fallback(serialized_sparse: Annotated[Any, TV_DeserializeSparse_Tserialized], dtype: TV_DeserializeSparse_dtype, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + _attr_Tserialized, (serialized_sparse,) = _execute.args_to_matching_eager([serialized_sparse], ctx, [_dtypes.string, _dtypes.variant, ], _dtypes.string) + _inputs_flat = [serialized_sparse] + _attrs = ("dtype", dtype, "Tserialized", _attr_Tserialized) + _result = _execute.execute(b"DeserializeSparse", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DeserializeSparse", _inputs_flat, _attrs, _result) + _result = _DeserializeSparseOutput._make(_result) + return _result + + +TV_SerializeManySparse_T = TypeVar("TV_SerializeManySparse_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SerializeManySparse_out_type = TypeVar("TV_SerializeManySparse_out_type", _atypes.String, _atypes.Variant) + +def serialize_many_sparse(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_SerializeManySparse_T], sparse_shape: Annotated[Any, _atypes.Int64], out_type:TV_SerializeManySparse_out_type=_dtypes.string, name=None) -> Annotated[Any, TV_SerializeManySparse_out_type]: + r"""Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object. + + The `SparseTensor` must have rank `R` greater than 1, and the first dimension + is treated as the minibatch dimension. Elements of the `SparseTensor` + must be sorted in increasing order of this first dimension. The serialized + `SparseTensor` objects going into each row of `serialized_sparse` will have + rank `R-1`. + + The minibatch size `N` is extracted from `sparse_shape[0]`. + + Args: + sparse_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the minibatch `SparseTensor`. + sparse_values: A `Tensor`. + 1-D. The `values` of the minibatch `SparseTensor`. + sparse_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the minibatch `SparseTensor`. + out_type: An optional `tf.DType` from: `tf.string, tf.variant`. Defaults to `tf.string`. + The `dtype` to use for serialization; the supported types are `string` + (default) and `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SerializeManySparse", name, sparse_indices, sparse_values, + sparse_shape, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return serialize_many_sparse_eager_fallback( + sparse_indices, sparse_values, sparse_shape, out_type=out_type, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.string + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SerializeManySparse", sparse_indices=sparse_indices, + sparse_values=sparse_values, + sparse_shape=sparse_shape, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SerializeManySparse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SerializeManySparse = tf_export("raw_ops.SerializeManySparse")(_ops.to_raw_op(serialize_many_sparse)) + + +def serialize_many_sparse_eager_fallback(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_SerializeManySparse_T], sparse_shape: Annotated[Any, _atypes.Int64], out_type: TV_SerializeManySparse_out_type, name, ctx) -> Annotated[Any, TV_SerializeManySparse_out_type]: + if out_type is None: + out_type = _dtypes.string + out_type = _execute.make_type(out_type, "out_type") + _attr_T, (sparse_values,) = _execute.args_to_matching_eager([sparse_values], ctx, []) + sparse_indices = _ops.convert_to_tensor(sparse_indices, _dtypes.int64) + sparse_shape = _ops.convert_to_tensor(sparse_shape, _dtypes.int64) + _inputs_flat = [sparse_indices, sparse_values, sparse_shape] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"SerializeManySparse", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SerializeManySparse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SerializeSparse_T = TypeVar("TV_SerializeSparse_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SerializeSparse_out_type = TypeVar("TV_SerializeSparse_out_type", _atypes.String, _atypes.Variant) + +def serialize_sparse(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_SerializeSparse_T], sparse_shape: Annotated[Any, _atypes.Int64], out_type:TV_SerializeSparse_out_type=_dtypes.string, name=None) -> Annotated[Any, TV_SerializeSparse_out_type]: + r"""Serialize a `SparseTensor` into a `[3]` `Tensor` object. + + Args: + sparse_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the `SparseTensor`. + sparse_values: A `Tensor`. 1-D. The `values` of the `SparseTensor`. + sparse_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the `SparseTensor`. + out_type: An optional `tf.DType` from: `tf.string, tf.variant`. Defaults to `tf.string`. + The `dtype` to use for serialization; the supported types are `string` + (default) and `variant`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SerializeSparse", name, sparse_indices, sparse_values, + sparse_shape, "out_type", out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return serialize_sparse_eager_fallback( + sparse_indices, sparse_values, sparse_shape, out_type=out_type, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if out_type is None: + out_type = _dtypes.string + out_type = _execute.make_type(out_type, "out_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SerializeSparse", sparse_indices=sparse_indices, + sparse_values=sparse_values, + sparse_shape=sparse_shape, out_type=out_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SerializeSparse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SerializeSparse = tf_export("raw_ops.SerializeSparse")(_ops.to_raw_op(serialize_sparse)) + + +def serialize_sparse_eager_fallback(sparse_indices: Annotated[Any, _atypes.Int64], sparse_values: Annotated[Any, TV_SerializeSparse_T], sparse_shape: Annotated[Any, _atypes.Int64], out_type: TV_SerializeSparse_out_type, name, ctx) -> Annotated[Any, TV_SerializeSparse_out_type]: + if out_type is None: + out_type = _dtypes.string + out_type = _execute.make_type(out_type, "out_type") + _attr_T, (sparse_values,) = _execute.args_to_matching_eager([sparse_values], ctx, []) + sparse_indices = _ops.convert_to_tensor(sparse_indices, _dtypes.int64) + sparse_shape = _ops.convert_to_tensor(sparse_shape, _dtypes.int64) + _inputs_flat = [sparse_indices, sparse_values, sparse_shape] + _attrs = ("T", _attr_T, "out_type", out_type) + _result = _execute.execute(b"SerializeSparse", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SerializeSparse", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseAddOutput = collections.namedtuple( + "SparseAdd", + ["sum_indices", "sum_values", "sum_shape"]) + + +TV_SparseAdd_T = TypeVar("TV_SparseAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseAdd_Treal = TypeVar("TV_SparseAdd_Treal", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_add(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseAdd_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseAdd_T], b_shape: Annotated[Any, _atypes.Int64], thresh: Annotated[Any, TV_SparseAdd_Treal], name=None): + r"""Adds two `SparseTensor` objects to produce another `SparseTensor`. + + The input `SparseTensor` objects' indices are assumed ordered in standard + lexicographic order. If this is not the case, before this step run + `SparseReorder` to restore index ordering. + + By default, if two values sum to zero at some index, the output `SparseTensor` + would still include that particular location in its index, storing a zero in the + corresponding value slot. To override this, callers can specify `thresh`, + indicating that if the sum has a magnitude strictly smaller than `thresh`, its + corresponding value and index would then not be included. In particular, + `thresh == 0` (default) means everything is kept and actual thresholding happens + only for a positive value. + + In the following shapes, `nnz` is the count after taking `thresh` into account. + + Args: + a_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the first `SparseTensor`, size `[nnz, ndims]` Matrix. + a_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. The `values` of the first `SparseTensor`, size `[nnz]` Vector. + a_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the first `SparseTensor`, size `[ndims]` Vector. + b_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the second `SparseTensor`, size `[nnz, ndims]` Matrix. + b_values: A `Tensor`. Must have the same type as `a_values`. + 1-D. The `values` of the second `SparseTensor`, size `[nnz]` Vector. + b_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the second `SparseTensor`, size `[ndims]` Vector. + thresh: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 0-D. The magnitude threshold that determines if an output value/index + pair takes space. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sum_indices, sum_values, sum_shape). + + sum_indices: A `Tensor` of type `int64`. + sum_values: A `Tensor`. Has the same type as `a_values`. + sum_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseAdd", name, a_indices, a_values, a_shape, b_indices, + b_values, b_shape, thresh) + _result = _SparseAddOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_add_eager_fallback( + a_indices, a_values, a_shape, b_indices, b_values, b_shape, thresh, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseAdd", a_indices=a_indices, a_values=a_values, a_shape=a_shape, + b_indices=b_indices, b_values=b_values, b_shape=b_shape, + thresh=thresh, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Treal", + _op._get_attr_type("Treal")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseAdd", _inputs_flat, _attrs, _result) + _result = _SparseAddOutput._make(_result) + return _result + +SparseAdd = tf_export("raw_ops.SparseAdd")(_ops.to_raw_op(sparse_add)) + + +def sparse_add_eager_fallback(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseAdd_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseAdd_T], b_shape: Annotated[Any, _atypes.Int64], thresh: Annotated[Any, TV_SparseAdd_Treal], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([a_values, b_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (a_values, b_values) = _inputs_T + _attr_Treal, (thresh,) = _execute.args_to_matching_eager([thresh], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + a_indices = _ops.convert_to_tensor(a_indices, _dtypes.int64) + a_shape = _ops.convert_to_tensor(a_shape, _dtypes.int64) + b_indices = _ops.convert_to_tensor(b_indices, _dtypes.int64) + b_shape = _ops.convert_to_tensor(b_shape, _dtypes.int64) + _inputs_flat = [a_indices, a_values, a_shape, b_indices, b_values, b_shape, thresh] + _attrs = ("T", _attr_T, "Treal", _attr_Treal) + _result = _execute.execute(b"SparseAdd", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseAdd", _inputs_flat, _attrs, _result) + _result = _SparseAddOutput._make(_result) + return _result + +_SparseAddGradOutput = collections.namedtuple( + "SparseAddGrad", + ["a_val_grad", "b_val_grad"]) + + +TV_SparseAddGrad_T = TypeVar("TV_SparseAddGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_add_grad(backprop_val_grad: Annotated[Any, TV_SparseAddGrad_T], a_indices: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], sum_indices: Annotated[Any, _atypes.Int64], name=None): + r"""The gradient operator for the SparseAdd op. + + The SparseAdd op calculates A + B, where A, B, and the sum are all represented + as `SparseTensor` objects. This op takes in the upstream gradient w.r.t. + non-empty values of the sum, and outputs the gradients w.r.t. the non-empty + values of A and B. + + Args: + backprop_val_grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D with shape `[nnz(sum)]`. The gradient with respect to + the non-empty values of the sum. + a_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the `SparseTensor` A, size `[nnz(A), ndims]`. + b_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the `SparseTensor` B, size `[nnz(B), ndims]`. + sum_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the sum `SparseTensor`, size + `[nnz(sum), ndims]`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a_val_grad, b_val_grad). + + a_val_grad: A `Tensor`. Has the same type as `backprop_val_grad`. + b_val_grad: A `Tensor`. Has the same type as `backprop_val_grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseAddGrad", name, backprop_val_grad, a_indices, b_indices, + sum_indices) + _result = _SparseAddGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_add_grad_eager_fallback( + backprop_val_grad, a_indices, b_indices, sum_indices, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseAddGrad", backprop_val_grad=backprop_val_grad, + a_indices=a_indices, b_indices=b_indices, + sum_indices=sum_indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseAddGrad", _inputs_flat, _attrs, _result) + _result = _SparseAddGradOutput._make(_result) + return _result + +SparseAddGrad = tf_export("raw_ops.SparseAddGrad")(_ops.to_raw_op(sparse_add_grad)) + + +def sparse_add_grad_eager_fallback(backprop_val_grad: Annotated[Any, TV_SparseAddGrad_T], a_indices: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], sum_indices: Annotated[Any, _atypes.Int64], name, ctx): + _attr_T, (backprop_val_grad,) = _execute.args_to_matching_eager([backprop_val_grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + a_indices = _ops.convert_to_tensor(a_indices, _dtypes.int64) + b_indices = _ops.convert_to_tensor(b_indices, _dtypes.int64) + sum_indices = _ops.convert_to_tensor(sum_indices, _dtypes.int64) + _inputs_flat = [backprop_val_grad, a_indices, b_indices, sum_indices] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseAddGrad", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseAddGrad", _inputs_flat, _attrs, _result) + _result = _SparseAddGradOutput._make(_result) + return _result + +_SparseConcatOutput = collections.namedtuple( + "SparseConcat", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseConcat_T = TypeVar("TV_SparseConcat_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_concat(indices: Annotated[List[Any], _atypes.Int64], values: Annotated[List[Any], TV_SparseConcat_T], shapes: Annotated[List[Any], _atypes.Int64], concat_dim: int, name=None): + r"""Concatenates a list of `SparseTensor` along the specified dimension. + + Concatenation is with respect to the dense versions of these sparse tensors. + It is assumed that each input is a `SparseTensor` whose elements are ordered + along increasing dimension number. + + All inputs' shapes must match, except for the concat dimension. The + `indices`, `values`, and `shapes` lists must have the same length. + + The output shape is identical to the inputs', except along the concat + dimension, where it is the sum of the inputs' sizes along that dimension. + + The output elements will be resorted to preserve the sort order along + increasing dimension number. + + This op runs in `O(M log M)` time, where `M` is the total number of non-empty + values across all inputs. This is due to the need for an internal sort in + order to concatenate efficiently across an arbitrary dimension. + + For example, if `concat_dim = 1` and the inputs are + + sp_inputs[0]: shape = [2, 3] + [0, 2]: "a" + [1, 0]: "b" + [1, 1]: "c" + + sp_inputs[1]: shape = [2, 4] + [0, 1]: "d" + [0, 2]: "e" + + then the output will be + + shape = [2, 7] + [0, 2]: "a" + [0, 4]: "d" + [0, 5]: "e" + [1, 0]: "b" + [1, 1]: "c" + + Graphically this is equivalent to doing + + [ a] concat [ d e ] = [ a d e ] + [b c ] [ ] [b c ] + + Args: + indices: A list of at least 2 `Tensor` objects with type `int64`. + 2-D. Indices of each input `SparseTensor`. + values: A list with the same length as `indices` of `Tensor` objects with the same type. + 1-D. Non-empty values of each `SparseTensor`. + shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`. + 1-D. Shapes of each `SparseTensor`. + concat_dim: An `int`. + Dimension to concatenate along. Must be in range [-rank, rank), + where rank is the number of dimensions in each input `SparseTensor`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `values`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseConcat", name, indices, values, shapes, "concat_dim", + concat_dim) + _result = _SparseConcatOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_concat_eager_fallback( + indices, values, shapes, concat_dim=concat_dim, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_concat' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'sparse_concat' Op, not %r." % values) + if len(values) != _attr_N: + raise ValueError( + "List argument 'values' to 'sparse_concat' Op with length %d " + "must match length %d of argument 'indices'." % + (len(values), _attr_N)) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_concat' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_concat' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + concat_dim = _execute.make_int(concat_dim, "concat_dim") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseConcat", indices=indices, values=values, shapes=shapes, + concat_dim=concat_dim, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("concat_dim", _op._get_attr_int("concat_dim"), "N", + _op._get_attr_int("N"), "T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseConcat", _inputs_flat, _attrs, _result) + _result = _SparseConcatOutput._make(_result) + return _result + +SparseConcat = tf_export("raw_ops.SparseConcat")(_ops.to_raw_op(sparse_concat)) + + +def sparse_concat_eager_fallback(indices: Annotated[List[Any], _atypes.Int64], values: Annotated[List[Any], TV_SparseConcat_T], shapes: Annotated[List[Any], _atypes.Int64], concat_dim: int, name, ctx): + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_concat' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(values, (list, tuple)): + raise TypeError( + "Expected list for 'values' argument to " + "'sparse_concat' Op, not %r." % values) + if len(values) != _attr_N: + raise ValueError( + "List argument 'values' to 'sparse_concat' Op with length %d " + "must match length %d of argument 'indices'." % + (len(values), _attr_N)) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_concat' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_concat' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + concat_dim = _execute.make_int(concat_dim, "concat_dim") + _attr_T, values = _execute.args_to_matching_eager(list(values), ctx, []) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int64) + shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64) + _inputs_flat = list(indices) + list(values) + list(shapes) + _attrs = ("concat_dim", concat_dim, "N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"SparseConcat", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseConcat", _inputs_flat, _attrs, _result) + _result = _SparseConcatOutput._make(_result) + return _result + +_SparseCrossOutput = collections.namedtuple( + "SparseCross", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseCross_out_type = TypeVar("TV_SparseCross_out_type", _atypes.Int64, _atypes.String) +TV_SparseCross_internal_type = TypeVar("TV_SparseCross_internal_type", _atypes.Int64, _atypes.String) + +def sparse_cross(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, hashed_output: bool, num_buckets: int, hash_key: int, out_type: TV_SparseCross_out_type, internal_type: TV_SparseCross_internal_type, name=None): + r"""Generates sparse cross from a list of sparse and dense tensors. + + The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each + representing features of one feature column. It outputs a 2D `SparseTensor` with + the batchwise crosses of these features. + + For example, if the inputs are + + inputs[0]: SparseTensor with shape = [2, 2] + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + + inputs[1]: SparseTensor with shape = [2, 1] + [0, 0]: "d" + [1, 0]: "e" + + inputs[2]: Tensor [["f"], ["g"]] + + then the output will be + + shape = [2, 2] + [0, 0]: "a_X_d_X_f" + [1, 0]: "b_X_e_X_g" + [1, 1]: "c_X_e_X_g" + + if hashed_output=true then the output will be + + shape = [2, 2] + [0, 0]: FingerprintCat64( + Fingerprint64("f"), FingerprintCat64( + Fingerprint64("d"), Fingerprint64("a"))) + [1, 0]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("b"))) + [1, 1]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("c"))) + + Args: + indices: A list of `Tensor` objects with type `int64`. + 2-D. Indices of each input `SparseTensor`. + values: A list of `Tensor` objects with types from: `int64`, `string`. + 1-D. values of each `SparseTensor`. + shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`. + 1-D. Shapes of each `SparseTensor`. + dense_inputs: A list of `Tensor` objects with types from: `int64`, `string`. + 2-D. Columns represented by dense `Tensor`. + hashed_output: A `bool`. + If true, returns the hash of the cross instead of the string. + This will allow us avoiding string manipulations. + num_buckets: An `int` that is `>= 0`. It is used if hashed_output is true. + output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. + hash_key: An `int`. + Specify the hash_key that will be used by the `FingerprintCat64` + function to combine the crosses fingerprints. + out_type: A `tf.DType` from: `tf.int64, tf.string`. + internal_type: A `tf.DType` from: `tf.int64, tf.string`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor` of type `out_type`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseCross", name, indices, values, shapes, dense_inputs, + "hashed_output", hashed_output, "num_buckets", num_buckets, + "hash_key", hash_key, "out_type", out_type, "internal_type", + internal_type) + _result = _SparseCrossOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_cross_eager_fallback( + indices, values, shapes, dense_inputs, hashed_output=hashed_output, + num_buckets=num_buckets, hash_key=hash_key, out_type=out_type, + internal_type=internal_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + hashed_output = _execute.make_bool(hashed_output, "hashed_output") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + hash_key = _execute.make_int(hash_key, "hash_key") + out_type = _execute.make_type(out_type, "out_type") + internal_type = _execute.make_type(internal_type, "internal_type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseCross", indices=indices, values=values, shapes=shapes, + dense_inputs=dense_inputs, hashed_output=hashed_output, + num_buckets=num_buckets, hash_key=hash_key, + out_type=out_type, internal_type=internal_type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "hashed_output", + _op._get_attr_bool("hashed_output"), "num_buckets", + _op._get_attr_int("num_buckets"), "hash_key", + _op._get_attr_int("hash_key"), "sparse_types", + _op.get_attr("sparse_types"), "dense_types", + _op.get_attr("dense_types"), "out_type", + _op._get_attr_type("out_type"), "internal_type", + _op._get_attr_type("internal_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseCross", _inputs_flat, _attrs, _result) + _result = _SparseCrossOutput._make(_result) + return _result + +SparseCross = tf_export("raw_ops.SparseCross")(_ops.to_raw_op(sparse_cross)) + + +def sparse_cross_eager_fallback(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, hashed_output: bool, num_buckets: int, hash_key: int, out_type: TV_SparseCross_out_type, internal_type: TV_SparseCross_internal_type, name, ctx): + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + hashed_output = _execute.make_bool(hashed_output, "hashed_output") + num_buckets = _execute.make_int(num_buckets, "num_buckets") + hash_key = _execute.make_int(hash_key, "hash_key") + out_type = _execute.make_type(out_type, "out_type") + internal_type = _execute.make_type(internal_type, "internal_type") + _attr_sparse_types, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + _attr_dense_types, dense_inputs = _execute.convert_to_mixed_eager_tensors(dense_inputs, ctx) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int64) + shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64) + _inputs_flat = list(indices) + list(values) + list(shapes) + list(dense_inputs) + _attrs = ("N", _attr_N, "hashed_output", hashed_output, "num_buckets", + num_buckets, "hash_key", hash_key, "sparse_types", _attr_sparse_types, + "dense_types", _attr_dense_types, "out_type", out_type, "internal_type", + internal_type) + _result = _execute.execute(b"SparseCross", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseCross", _inputs_flat, _attrs, _result) + _result = _SparseCrossOutput._make(_result) + return _result + +_SparseCrossHashedOutput = collections.namedtuple( + "SparseCrossHashed", + ["output_indices", "output_values", "output_shape"]) + + +def sparse_cross_hashed(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, num_buckets: Annotated[Any, _atypes.Int64], strong_hash: Annotated[Any, _atypes.Bool], salt: Annotated[Any, _atypes.Int64], name=None): + r"""Generates sparse cross from a list of sparse and dense tensors. + + The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each + representing features of one feature column. It outputs a 2D `SparseTensor` with + the batchwise crosses of these features. + + For example, if the inputs are + + inputs[0]: SparseTensor with shape = [2, 2] + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + + inputs[1]: SparseTensor with shape = [2, 1] + [0, 0]: "d" + [1, 0]: "e" + + inputs[2]: Tensor [["f"], ["g"]] + + then the output will be + + shape = [2, 2] + [0, 0]: "a_X_d_X_f" + [1, 0]: "b_X_e_X_g" + [1, 1]: "c_X_e_X_g" + + if hashed_output=true then the output will be + + shape = [2, 2] + [0, 0]: FingerprintCat64( + Fingerprint64("f"), FingerprintCat64( + Fingerprint64("d"), Fingerprint64("a"))) + [1, 0]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("b"))) + [1, 1]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("c"))) + + Args: + indices: A list of `Tensor` objects with type `int64`. + 2-D. Indices of each input `SparseTensor`. + values: A list of `Tensor` objects with types from: `int64`, `string`. + 1-D. values of each `SparseTensor`. + shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`. + 1-D. Shapes of each `SparseTensor`. + dense_inputs: A list of `Tensor` objects with types from: `int64`, `string`. + 2-D. Columns represented by dense `Tensor`. + num_buckets: A `Tensor` of type `int64`. + It is used if hashed_output is true. + output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. + strong_hash: A `Tensor` of type `bool`. + boolean, if true, siphash with salt will be used instead of farmhash. + salt: A `Tensor` of type `int64`. + Specify the salt that will be used by the siphash function. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor` of type `int64`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseCrossHashed", name, indices, values, shapes, + dense_inputs, num_buckets, strong_hash, salt) + _result = _SparseCrossHashedOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_cross_hashed_eager_fallback( + indices, values, shapes, dense_inputs, num_buckets, strong_hash, + salt, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross_hashed' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross_hashed' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross_hashed' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseCrossHashed", indices=indices, values=values, shapes=shapes, + dense_inputs=dense_inputs, + num_buckets=num_buckets, strong_hash=strong_hash, + salt=salt, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "sparse_types", + _op.get_attr("sparse_types"), "dense_types", + _op.get_attr("dense_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseCrossHashed", _inputs_flat, _attrs, _result) + _result = _SparseCrossHashedOutput._make(_result) + return _result + +SparseCrossHashed = tf_export("raw_ops.SparseCrossHashed")(_ops.to_raw_op(sparse_cross_hashed)) + + +def sparse_cross_hashed_eager_fallback(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, num_buckets: Annotated[Any, _atypes.Int64], strong_hash: Annotated[Any, _atypes.Bool], salt: Annotated[Any, _atypes.Int64], name, ctx): + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross_hashed' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross_hashed' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross_hashed' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + _attr_sparse_types, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + _attr_dense_types, dense_inputs = _execute.convert_to_mixed_eager_tensors(dense_inputs, ctx) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int64) + shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64) + num_buckets = _ops.convert_to_tensor(num_buckets, _dtypes.int64) + strong_hash = _ops.convert_to_tensor(strong_hash, _dtypes.bool) + salt = _ops.convert_to_tensor(salt, _dtypes.int64) + _inputs_flat = list(indices) + list(values) + list(shapes) + list(dense_inputs) + [num_buckets, strong_hash, salt] + _attrs = ("N", _attr_N, "sparse_types", _attr_sparse_types, "dense_types", + _attr_dense_types) + _result = _execute.execute(b"SparseCrossHashed", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseCrossHashed", _inputs_flat, _attrs, _result) + _result = _SparseCrossHashedOutput._make(_result) + return _result + +_SparseCrossV2Output = collections.namedtuple( + "SparseCrossV2", + ["output_indices", "output_values", "output_shape"]) + + +def sparse_cross_v2(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, sep: Annotated[Any, _atypes.String], name=None): + r"""Generates sparse cross from a list of sparse and dense tensors. + + The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each + representing features of one feature column. It outputs a 2D `SparseTensor` with + the batchwise crosses of these features. + + For example, if the inputs are + + inputs[0]: SparseTensor with shape = [2, 2] + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + + inputs[1]: SparseTensor with shape = [2, 1] + [0, 0]: "d" + [1, 0]: "e" + + inputs[2]: Tensor [["f"], ["g"]] + + then the output will be + + shape = [2, 2] + [0, 0]: "a_X_d_X_f" + [1, 0]: "b_X_e_X_g" + [1, 1]: "c_X_e_X_g" + + if hashed_output=true then the output will be + + shape = [2, 2] + [0, 0]: FingerprintCat64( + Fingerprint64("f"), FingerprintCat64( + Fingerprint64("d"), Fingerprint64("a"))) + [1, 0]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("b"))) + [1, 1]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("c"))) + + Args: + indices: A list of `Tensor` objects with type `int64`. + 2-D. Indices of each input `SparseTensor`. + values: A list of `Tensor` objects with types from: `int64`, `string`. + 1-D. values of each `SparseTensor`. + shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`. + 1-D. Shapes of each `SparseTensor`. + dense_inputs: A list of `Tensor` objects with types from: `int64`, `string`. + 2-D. Columns represented by dense `Tensor`. + sep: A `Tensor` of type `string`. + string used when joining a list of string inputs, can be used as separator later. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor` of type `string`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseCrossV2", name, indices, values, shapes, dense_inputs, + sep) + _result = _SparseCrossV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_cross_v2_eager_fallback( + indices, values, shapes, dense_inputs, sep, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross_v2' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross_v2' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross_v2' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseCrossV2", indices=indices, values=values, shapes=shapes, + dense_inputs=dense_inputs, sep=sep, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "sparse_types", + _op.get_attr("sparse_types"), "dense_types", + _op.get_attr("dense_types")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseCrossV2", _inputs_flat, _attrs, _result) + _result = _SparseCrossV2Output._make(_result) + return _result + +SparseCrossV2 = tf_export("raw_ops.SparseCrossV2")(_ops.to_raw_op(sparse_cross_v2)) + + +def sparse_cross_v2_eager_fallback(indices: Annotated[List[Any], _atypes.Int64], values, shapes: Annotated[List[Any], _atypes.Int64], dense_inputs, sep: Annotated[Any, _atypes.String], name, ctx): + if not isinstance(indices, (list, tuple)): + raise TypeError( + "Expected list for 'indices' argument to " + "'sparse_cross_v2' Op, not %r." % indices) + _attr_N = len(indices) + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'sparse_cross_v2' Op, not %r." % shapes) + if len(shapes) != _attr_N: + raise ValueError( + "List argument 'shapes' to 'sparse_cross_v2' Op with length %d " + "must match length %d of argument 'indices'." % + (len(shapes), _attr_N)) + _attr_sparse_types, values = _execute.convert_to_mixed_eager_tensors(values, ctx) + _attr_dense_types, dense_inputs = _execute.convert_to_mixed_eager_tensors(dense_inputs, ctx) + indices = _ops.convert_n_to_tensor(indices, _dtypes.int64) + shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64) + sep = _ops.convert_to_tensor(sep, _dtypes.string) + _inputs_flat = list(indices) + list(values) + list(shapes) + list(dense_inputs) + [sep] + _attrs = ("N", _attr_N, "sparse_types", _attr_sparse_types, "dense_types", + _attr_dense_types) + _result = _execute.execute(b"SparseCrossV2", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseCrossV2", _inputs_flat, _attrs, _result) + _result = _SparseCrossV2Output._make(_result) + return _result + + +TV_SparseDenseCwiseAdd_T = TypeVar("TV_SparseDenseCwiseAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_dense_cwise_add(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseAdd_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseAdd_T], name=None) -> Annotated[Any, TV_SparseDenseCwiseAdd_T]: + r"""Adds up a SparseTensor and a dense Tensor, using these special rules: + + (1) Broadcasts the dense side to have the same shape as the sparse side, if + eligible; + (2) Then, only the dense values pointed to by the indices of the SparseTensor + participate in the cwise addition. + + By these rules, the result is a logical SparseTensor with exactly the same + indices and shape, but possibly with different non-zero values. The output of + this Op is the resultant non-zero values. + + Args: + sp_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + sp_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `sp_indices`. + sp_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + dense: A `Tensor`. Must have the same type as `sp_values`. + `R`-D. The dense Tensor operand. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `sp_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseDenseCwiseAdd", name, sp_indices, sp_values, sp_shape, + dense) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_dense_cwise_add_eager_fallback( + sp_indices, sp_values, sp_shape, dense, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseDenseCwiseAdd", sp_indices=sp_indices, sp_values=sp_values, + sp_shape=sp_shape, dense=dense, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseDenseCwiseAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseDenseCwiseAdd = tf_export("raw_ops.SparseDenseCwiseAdd")(_ops.to_raw_op(sparse_dense_cwise_add)) + + +def sparse_dense_cwise_add_eager_fallback(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseAdd_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseAdd_T], name, ctx) -> Annotated[Any, TV_SparseDenseCwiseAdd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([sp_values, dense], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (sp_values, dense) = _inputs_T + sp_indices = _ops.convert_to_tensor(sp_indices, _dtypes.int64) + sp_shape = _ops.convert_to_tensor(sp_shape, _dtypes.int64) + _inputs_flat = [sp_indices, sp_values, sp_shape, dense] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseDenseCwiseAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseDenseCwiseAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseDenseCwiseDiv_T = TypeVar("TV_SparseDenseCwiseDiv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_dense_cwise_div(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseDiv_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseDiv_T], name=None) -> Annotated[Any, TV_SparseDenseCwiseDiv_T]: + r"""Component-wise divides a SparseTensor by a dense Tensor. + + *Limitation*: this Op only broadcasts the dense side to the sparse side, but not + the other direction. + + Args: + sp_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + sp_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `sp_indices`. + sp_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + dense: A `Tensor`. Must have the same type as `sp_values`. + `R`-D. The dense Tensor operand. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `sp_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseDenseCwiseDiv", name, sp_indices, sp_values, sp_shape, + dense) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_dense_cwise_div_eager_fallback( + sp_indices, sp_values, sp_shape, dense, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseDenseCwiseDiv", sp_indices=sp_indices, sp_values=sp_values, + sp_shape=sp_shape, dense=dense, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseDenseCwiseDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseDenseCwiseDiv = tf_export("raw_ops.SparseDenseCwiseDiv")(_ops.to_raw_op(sparse_dense_cwise_div)) + + +def sparse_dense_cwise_div_eager_fallback(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseDiv_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseDiv_T], name, ctx) -> Annotated[Any, TV_SparseDenseCwiseDiv_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([sp_values, dense], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (sp_values, dense) = _inputs_T + sp_indices = _ops.convert_to_tensor(sp_indices, _dtypes.int64) + sp_shape = _ops.convert_to_tensor(sp_shape, _dtypes.int64) + _inputs_flat = [sp_indices, sp_values, sp_shape, dense] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseDenseCwiseDiv", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseDenseCwiseDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseDenseCwiseMul_T = TypeVar("TV_SparseDenseCwiseMul_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_dense_cwise_mul(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseMul_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseMul_T], name=None) -> Annotated[Any, TV_SparseDenseCwiseMul_T]: + r"""Component-wise multiplies a SparseTensor by a dense Tensor. + + The output locations corresponding to the implicitly zero elements in the sparse + tensor will be zero (i.e., will not take up storage space), regardless of the + contents of the dense tensor (even if it's +/-INF and that INF*0 == NaN). + + *Limitation*: this Op only broadcasts the dense side to the sparse side, but not + the other direction. + + Args: + sp_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + sp_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `sp_indices`. + sp_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + dense: A `Tensor`. Must have the same type as `sp_values`. + `R`-D. The dense Tensor operand. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `sp_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseDenseCwiseMul", name, sp_indices, sp_values, sp_shape, + dense) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_dense_cwise_mul_eager_fallback( + sp_indices, sp_values, sp_shape, dense, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseDenseCwiseMul", sp_indices=sp_indices, sp_values=sp_values, + sp_shape=sp_shape, dense=dense, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseDenseCwiseMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseDenseCwiseMul = tf_export("raw_ops.SparseDenseCwiseMul")(_ops.to_raw_op(sparse_dense_cwise_mul)) + + +def sparse_dense_cwise_mul_eager_fallback(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseDenseCwiseMul_T], sp_shape: Annotated[Any, _atypes.Int64], dense: Annotated[Any, TV_SparseDenseCwiseMul_T], name, ctx) -> Annotated[Any, TV_SparseDenseCwiseMul_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([sp_values, dense], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (sp_values, dense) = _inputs_T + sp_indices = _ops.convert_to_tensor(sp_indices, _dtypes.int64) + sp_shape = _ops.convert_to_tensor(sp_shape, _dtypes.int64) + _inputs_flat = [sp_indices, sp_values, sp_shape, dense] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseDenseCwiseMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseDenseCwiseMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseFillEmptyRowsOutput = collections.namedtuple( + "SparseFillEmptyRows", + ["output_indices", "output_values", "empty_row_indicator", "reverse_index_map"]) + + +TV_SparseFillEmptyRows_T = TypeVar("TV_SparseFillEmptyRows_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_fill_empty_rows(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseFillEmptyRows_T], dense_shape: Annotated[Any, _atypes.Int64], default_value: Annotated[Any, TV_SparseFillEmptyRows_T], name=None): + r"""Fills empty rows in the input 2-D `SparseTensor` with a default value. + + The input `SparseTensor` is represented via the tuple of inputs + (`indices`, `values`, `dense_shape`). The output `SparseTensor` has the + same `dense_shape` but with indices `output_indices` and values + `output_values`. + + This op inserts a single entry for every row that doesn't have any values. + The index is created as `[row, 0, ..., 0]` and the inserted value + is `default_value`. + + For example, suppose `sp_input` has shape `[5, 6]` and non-empty values: + + [0, 1]: a + [0, 3]: b + [2, 0]: c + [3, 1]: d + + Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values: + + [0, 1]: a + [0, 3]: b + [1, 0]: default_value + [2, 0]: c + [3, 1]: d + [4, 0]: default_value + + The output `SparseTensor` will be in row-major order and will have the + same shape as the input. + + This op also returns an indicator vector shaped `[dense_shape[0]]` such that + + empty_row_indicator[i] = True iff row i was an empty row. + + And a reverse index map vector shaped `[indices.shape[0]]` that is used during + backpropagation, + + reverse_index_map[j] = out_j s.t. indices[j, :] == output_indices[out_j, :] + + Args: + indices: A `Tensor` of type `int64`. + 2-D. the indices of the sparse tensor. + values: A `Tensor`. 1-D. the values of the sparse tensor. + dense_shape: A `Tensor` of type `int64`. + 1-D. the shape of the sparse tensor. + default_value: A `Tensor`. Must have the same type as `values`. + 0-D. default value to insert into location `[row, 0, ..., 0]` + for rows missing from the input sparse tensor. + output indices: 2-D. the indices of the filled sparse tensor. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, empty_row_indicator, reverse_index_map). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `values`. + empty_row_indicator: A `Tensor` of type `bool`. + reverse_index_map: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseFillEmptyRows", name, indices, values, dense_shape, + default_value) + _result = _SparseFillEmptyRowsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_fill_empty_rows_eager_fallback( + indices, values, dense_shape, default_value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseFillEmptyRows", indices=indices, values=values, + dense_shape=dense_shape, + default_value=default_value, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseFillEmptyRows", _inputs_flat, _attrs, _result) + _result = _SparseFillEmptyRowsOutput._make(_result) + return _result + +SparseFillEmptyRows = tf_export("raw_ops.SparseFillEmptyRows")(_ops.to_raw_op(sparse_fill_empty_rows)) + + +def sparse_fill_empty_rows_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseFillEmptyRows_T], dense_shape: Annotated[Any, _atypes.Int64], default_value: Annotated[Any, TV_SparseFillEmptyRows_T], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([values, default_value], ctx, []) + (values, default_value) = _inputs_T + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [indices, values, dense_shape, default_value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseFillEmptyRows", 4, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseFillEmptyRows", _inputs_flat, _attrs, _result) + _result = _SparseFillEmptyRowsOutput._make(_result) + return _result + +_SparseFillEmptyRowsGradOutput = collections.namedtuple( + "SparseFillEmptyRowsGrad", + ["d_values", "d_default_value"]) + + +TV_SparseFillEmptyRowsGrad_T = TypeVar("TV_SparseFillEmptyRowsGrad_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_fill_empty_rows_grad(reverse_index_map: Annotated[Any, _atypes.Int64], grad_values: Annotated[Any, TV_SparseFillEmptyRowsGrad_T], name=None): + r"""The gradient of SparseFillEmptyRows. + + Takes vectors reverse_index_map, shaped `[N]`, and grad_values, + shaped `[N_full]`, where `N_full >= N` and copies data into either + `d_values` or `d_default_value`. Here `d_values` is shaped `[N]` and + `d_default_value` is a scalar. + + d_values[j] = grad_values[reverse_index_map[j]] + d_default_value = sum_{k : 0 .. N_full - 1} ( + grad_values[k] * 1{k not in reverse_index_map}) + + Args: + reverse_index_map: A `Tensor` of type `int64`. + 1-D. The reverse index map from SparseFillEmptyRows. + grad_values: A `Tensor`. 1-D. The gradients from backprop. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d_values, d_default_value). + + d_values: A `Tensor`. Has the same type as `grad_values`. + d_default_value: A `Tensor`. Has the same type as `grad_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseFillEmptyRowsGrad", name, reverse_index_map, grad_values) + _result = _SparseFillEmptyRowsGradOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_fill_empty_rows_grad_eager_fallback( + reverse_index_map, grad_values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseFillEmptyRowsGrad", reverse_index_map=reverse_index_map, + grad_values=grad_values, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseFillEmptyRowsGrad", _inputs_flat, _attrs, _result) + _result = _SparseFillEmptyRowsGradOutput._make(_result) + return _result + +SparseFillEmptyRowsGrad = tf_export("raw_ops.SparseFillEmptyRowsGrad")(_ops.to_raw_op(sparse_fill_empty_rows_grad)) + + +def sparse_fill_empty_rows_grad_eager_fallback(reverse_index_map: Annotated[Any, _atypes.Int64], grad_values: Annotated[Any, TV_SparseFillEmptyRowsGrad_T], name, ctx): + _attr_T, (grad_values,) = _execute.args_to_matching_eager([grad_values], ctx, []) + reverse_index_map = _ops.convert_to_tensor(reverse_index_map, _dtypes.int64) + _inputs_flat = [reverse_index_map, grad_values] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseFillEmptyRowsGrad", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseFillEmptyRowsGrad", _inputs_flat, _attrs, _result) + _result = _SparseFillEmptyRowsGradOutput._make(_result) + return _result + + +TV_SparseReduceMax_T = TypeVar("TV_SparseReduceMax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_reduce_max(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceMax_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims:bool=False, name=None) -> Annotated[Any, TV_SparseReduceMax_T]: + r"""Computes the max of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_max()`. In particular, this Op also returns a dense `Tensor` + instead of a sparse one. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + input_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `input_indices`. + input_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + reduction_axes: A `Tensor` of type `int32`. + 1-D. Length-`K` vector containing the reduction axes. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReduceMax", name, input_indices, input_values, + input_shape, reduction_axes, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reduce_max_eager_fallback( + input_indices, input_values, input_shape, reduction_axes, + keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReduceMax", input_indices=input_indices, + input_values=input_values, input_shape=input_shape, + reduction_axes=reduction_axes, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReduceMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseReduceMax = tf_export("raw_ops.SparseReduceMax")(_ops.to_raw_op(sparse_reduce_max)) + + +def sparse_reduce_max_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceMax_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims: bool, name, ctx) -> Annotated[Any, TV_SparseReduceMax_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input_values,) = _execute.args_to_matching_eager([input_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + reduction_axes = _ops.convert_to_tensor(reduction_axes, _dtypes.int32) + _inputs_flat = [input_indices, input_values, input_shape, reduction_axes] + _attrs = ("keep_dims", keep_dims, "T", _attr_T) + _result = _execute.execute(b"SparseReduceMax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReduceMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseReduceMaxSparseOutput = collections.namedtuple( + "SparseReduceMaxSparse", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseReduceMaxSparse_T = TypeVar("TV_SparseReduceMaxSparse_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_reduce_max_sparse(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceMaxSparse_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims:bool=False, name=None): + r"""Computes the max of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_max()`. In contrast to SparseReduceMax, this Op returns a + SparseTensor. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + input_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `input_indices`. + input_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + reduction_axes: A `Tensor` of type `int32`. + 1-D. Length-`K` vector containing the reduction axes. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `input_values`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReduceMaxSparse", name, input_indices, input_values, + input_shape, reduction_axes, "keep_dims", keep_dims) + _result = _SparseReduceMaxSparseOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reduce_max_sparse_eager_fallback( + input_indices, input_values, input_shape, reduction_axes, + keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReduceMaxSparse", input_indices=input_indices, + input_values=input_values, + input_shape=input_shape, + reduction_axes=reduction_axes, + keep_dims=keep_dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReduceMaxSparse", _inputs_flat, _attrs, _result) + _result = _SparseReduceMaxSparseOutput._make(_result) + return _result + +SparseReduceMaxSparse = tf_export("raw_ops.SparseReduceMaxSparse")(_ops.to_raw_op(sparse_reduce_max_sparse)) + + +def sparse_reduce_max_sparse_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceMaxSparse_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims: bool, name, ctx): + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input_values,) = _execute.args_to_matching_eager([input_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + reduction_axes = _ops.convert_to_tensor(reduction_axes, _dtypes.int32) + _inputs_flat = [input_indices, input_values, input_shape, reduction_axes] + _attrs = ("keep_dims", keep_dims, "T", _attr_T) + _result = _execute.execute(b"SparseReduceMaxSparse", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReduceMaxSparse", _inputs_flat, _attrs, _result) + _result = _SparseReduceMaxSparseOutput._make(_result) + return _result + + +TV_SparseReduceSum_T = TypeVar("TV_SparseReduceSum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_reduce_sum(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceSum_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims:bool=False, name=None) -> Annotated[Any, TV_SparseReduceSum_T]: + r"""Computes the sum of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor` + instead of a sparse one. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + input_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `input_indices`. + input_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + reduction_axes: A `Tensor` of type `int32`. + 1-D. Length-`K` vector containing the reduction axes. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReduceSum", name, input_indices, input_values, + input_shape, reduction_axes, "keep_dims", keep_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reduce_sum_eager_fallback( + input_indices, input_values, input_shape, reduction_axes, + keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReduceSum", input_indices=input_indices, + input_values=input_values, input_shape=input_shape, + reduction_axes=reduction_axes, keep_dims=keep_dims, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReduceSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseReduceSum = tf_export("raw_ops.SparseReduceSum")(_ops.to_raw_op(sparse_reduce_sum)) + + +def sparse_reduce_sum_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceSum_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims: bool, name, ctx) -> Annotated[Any, TV_SparseReduceSum_T]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input_values,) = _execute.args_to_matching_eager([input_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + reduction_axes = _ops.convert_to_tensor(reduction_axes, _dtypes.int32) + _inputs_flat = [input_indices, input_values, input_shape, reduction_axes] + _attrs = ("keep_dims", keep_dims, "T", _attr_T) + _result = _execute.execute(b"SparseReduceSum", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReduceSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseReduceSumSparseOutput = collections.namedtuple( + "SparseReduceSumSparse", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseReduceSumSparse_T = TypeVar("TV_SparseReduceSumSparse_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_reduce_sum_sparse(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceSumSparse_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims:bool=False, name=None): + r"""Computes the sum of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a + SparseTensor. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keep_dims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + input_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `input_indices`. + input_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + reduction_axes: A `Tensor` of type `int32`. + 1-D. Length-`K` vector containing the reduction axes. + keep_dims: An optional `bool`. Defaults to `False`. + If true, retain reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `input_values`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReduceSumSparse", name, input_indices, input_values, + input_shape, reduction_axes, "keep_dims", keep_dims) + _result = _SparseReduceSumSparseOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reduce_sum_sparse_eager_fallback( + input_indices, input_values, input_shape, reduction_axes, + keep_dims=keep_dims, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReduceSumSparse", input_indices=input_indices, + input_values=input_values, + input_shape=input_shape, + reduction_axes=reduction_axes, + keep_dims=keep_dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReduceSumSparse", _inputs_flat, _attrs, _result) + _result = _SparseReduceSumSparseOutput._make(_result) + return _result + +SparseReduceSumSparse = tf_export("raw_ops.SparseReduceSumSparse")(_ops.to_raw_op(sparse_reduce_sum_sparse)) + + +def sparse_reduce_sum_sparse_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReduceSumSparse_T], input_shape: Annotated[Any, _atypes.Int64], reduction_axes: Annotated[Any, _atypes.Int32], keep_dims: bool, name, ctx): + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + _attr_T, (input_values,) = _execute.args_to_matching_eager([input_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + reduction_axes = _ops.convert_to_tensor(reduction_axes, _dtypes.int32) + _inputs_flat = [input_indices, input_values, input_shape, reduction_axes] + _attrs = ("keep_dims", keep_dims, "T", _attr_T) + _result = _execute.execute(b"SparseReduceSumSparse", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReduceSumSparse", _inputs_flat, _attrs, _result) + _result = _SparseReduceSumSparseOutput._make(_result) + return _result + +_SparseReorderOutput = collections.namedtuple( + "SparseReorder", + ["output_indices", "output_values"]) + + +TV_SparseReorder_T = TypeVar("TV_SparseReorder_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_reorder(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReorder_T], input_shape: Annotated[Any, _atypes.Int64], name=None): + r"""Reorders a SparseTensor into the canonical, row-major ordering. + + Note that by convention, all sparse ops preserve the canonical ordering along + increasing dimension number. The only time ordering can be violated is during + manual manipulation of the indices and values vectors to add entries. + + Reordering does not affect the shape of the SparseTensor. + + If the tensor has rank `R` and `N` non-empty values, `input_indices` has + shape `[N, R]`, input_values has length `N`, and input_shape has length `R`. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, possibly not in canonical ordering. + input_values: A `Tensor`. + 1-D. `N` non-empty values corresponding to `input_indices`. + input_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `input_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReorder", name, input_indices, input_values, input_shape) + _result = _SparseReorderOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reorder_eager_fallback( + input_indices, input_values, input_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReorder", input_indices=input_indices, + input_values=input_values, input_shape=input_shape, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReorder", _inputs_flat, _attrs, _result) + _result = _SparseReorderOutput._make(_result) + return _result + +SparseReorder = tf_export("raw_ops.SparseReorder")(_ops.to_raw_op(sparse_reorder)) + + +def sparse_reorder_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_values: Annotated[Any, TV_SparseReorder_T], input_shape: Annotated[Any, _atypes.Int64], name, ctx): + _attr_T, (input_values,) = _execute.args_to_matching_eager([input_values], ctx, []) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + _inputs_flat = [input_indices, input_values, input_shape] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseReorder", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReorder", _inputs_flat, _attrs, _result) + _result = _SparseReorderOutput._make(_result) + return _result + +_SparseReshapeOutput = collections.namedtuple( + "SparseReshape", + ["output_indices", "output_shape"]) + + +def sparse_reshape(input_indices: Annotated[Any, _atypes.Int64], input_shape: Annotated[Any, _atypes.Int64], new_shape: Annotated[Any, _atypes.Int64], name=None): + r"""Reshapes a SparseTensor to represent values in a new dense shape. + + This operation has the same semantics as reshape on the represented dense + tensor. The `input_indices` are recomputed based on the requested `new_shape`. + + If one component of `new_shape` is the special value -1, the size of that + dimension is computed so that the total dense size remains constant. At + most one component of `new_shape` can be -1. The number of dense elements + implied by `new_shape` must be the same as the number of dense elements + originally implied by `input_shape`. + + Reshaping does not affect the order of values in the SparseTensor. + + If the input tensor has rank `R_in` and `N` non-empty values, and `new_shape` + has length `R_out`, then `input_indices` has shape `[N, R_in]`, + `input_shape` has length `R_in`, `output_indices` has shape `[N, R_out]`, and + `output_shape` has length `R_out`. + + Args: + input_indices: A `Tensor` of type `int64`. + 2-D. `N x R_in` matrix with the indices of non-empty values in a + SparseTensor. + input_shape: A `Tensor` of type `int64`. + 1-D. `R_in` vector with the input SparseTensor's dense shape. + new_shape: A `Tensor` of type `int64`. + 1-D. `R_out` vector with the requested new dense shape. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseReshape", name, input_indices, input_shape, new_shape) + _result = _SparseReshapeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_reshape_eager_fallback( + input_indices, input_shape, new_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseReshape", input_indices=input_indices, input_shape=input_shape, + new_shape=new_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseReshape", _inputs_flat, _attrs, _result) + _result = _SparseReshapeOutput._make(_result) + return _result + +SparseReshape = tf_export("raw_ops.SparseReshape")(_ops.to_raw_op(sparse_reshape)) + + +def sparse_reshape_eager_fallback(input_indices: Annotated[Any, _atypes.Int64], input_shape: Annotated[Any, _atypes.Int64], new_shape: Annotated[Any, _atypes.Int64], name, ctx): + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_shape = _ops.convert_to_tensor(input_shape, _dtypes.int64) + new_shape = _ops.convert_to_tensor(new_shape, _dtypes.int64) + _inputs_flat = [input_indices, input_shape, new_shape] + _attrs = None + _result = _execute.execute(b"SparseReshape", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseReshape", _inputs_flat, _attrs, _result) + _result = _SparseReshapeOutput._make(_result) + return _result + +_SparseSliceOutput = collections.namedtuple( + "SparseSlice", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseSlice_T = TypeVar("TV_SparseSlice_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_slice(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseSlice_T], shape: Annotated[Any, _atypes.Int64], start: Annotated[Any, _atypes.Int64], size: Annotated[Any, _atypes.Int64], name=None): + r"""Slice a `SparseTensor` based on the `start` and `size`. + + For example, if the input is + + input_tensor = shape = [2, 7] + [ a d e ] + [b c ] + + Graphically the output tensors are: + + sparse_slice([0, 0], [2, 4]) = shape = [2, 4] + [ a ] + [b c ] + + sparse_slice([0, 4], [2, 3]) = shape = [2, 3] + [ d e ] + [ ] + + Args: + indices: A `Tensor` of type `int64`. + 2-D tensor represents the indices of the sparse tensor. + values: A `Tensor`. 1-D tensor represents the values of the sparse tensor. + shape: A `Tensor` of type `int64`. + 1-D. tensor represents the shape of the sparse tensor. + start: A `Tensor` of type `int64`. + 1-D. tensor represents the start of the slice. + size: A `Tensor` of type `int64`. + 1-D. tensor represents the size of the slice. + output indices: A list of 1-D tensors represents the indices of the output + sparse tensors. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `values`. + output_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSlice", name, indices, values, shape, start, size) + _result = _SparseSliceOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_slice_eager_fallback( + indices, values, shape, start, size, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSlice", indices=indices, values=values, shape=shape, + start=start, size=size, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSlice", _inputs_flat, _attrs, _result) + _result = _SparseSliceOutput._make(_result) + return _result + +SparseSlice = tf_export("raw_ops.SparseSlice")(_ops.to_raw_op(sparse_slice)) + + +def sparse_slice_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseSlice_T], shape: Annotated[Any, _atypes.Int64], start: Annotated[Any, _atypes.Int64], size: Annotated[Any, _atypes.Int64], name, ctx): + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, []) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + shape = _ops.convert_to_tensor(shape, _dtypes.int64) + start = _ops.convert_to_tensor(start, _dtypes.int64) + size = _ops.convert_to_tensor(size, _dtypes.int64) + _inputs_flat = [indices, values, shape, start, size] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseSlice", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSlice", _inputs_flat, _attrs, _result) + _result = _SparseSliceOutput._make(_result) + return _result + + +TV_SparseSliceGrad_T = TypeVar("TV_SparseSliceGrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_slice_grad(backprop_val_grad: Annotated[Any, TV_SparseSliceGrad_T], input_indices: Annotated[Any, _atypes.Int64], input_start: Annotated[Any, _atypes.Int64], output_indices: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, TV_SparseSliceGrad_T]: + r"""The gradient operator for the SparseSlice op. + + This op takes in the upstream gradient w.r.t. non-empty values of + the sliced `SparseTensor`, and outputs the gradients w.r.t. + the non-empty values of input `SparseTensor`. + + Args: + backprop_val_grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. The gradient with respect to + the non-empty values of the sliced `SparseTensor`. + input_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the input `SparseTensor`. + input_start: A `Tensor` of type `int64`. + 1-D. tensor represents the start of the slice. + output_indices: A `Tensor` of type `int64`. + 2-D. The `indices` of the sliced `SparseTensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `backprop_val_grad`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSliceGrad", name, backprop_val_grad, input_indices, + input_start, output_indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_slice_grad_eager_fallback( + backprop_val_grad, input_indices, input_start, output_indices, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSliceGrad", backprop_val_grad=backprop_val_grad, + input_indices=input_indices, + input_start=input_start, + output_indices=output_indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSliceGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSliceGrad = tf_export("raw_ops.SparseSliceGrad")(_ops.to_raw_op(sparse_slice_grad)) + + +def sparse_slice_grad_eager_fallback(backprop_val_grad: Annotated[Any, TV_SparseSliceGrad_T], input_indices: Annotated[Any, _atypes.Int64], input_start: Annotated[Any, _atypes.Int64], output_indices: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, TV_SparseSliceGrad_T]: + _attr_T, (backprop_val_grad,) = _execute.args_to_matching_eager([backprop_val_grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + input_indices = _ops.convert_to_tensor(input_indices, _dtypes.int64) + input_start = _ops.convert_to_tensor(input_start, _dtypes.int64) + output_indices = _ops.convert_to_tensor(output_indices, _dtypes.int64) + _inputs_flat = [backprop_val_grad, input_indices, input_start, output_indices] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseSliceGrad", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSliceGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseSoftmax_T = TypeVar("TV_SparseSoftmax_T", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def sparse_softmax(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseSoftmax_T], sp_shape: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, TV_SparseSoftmax_T]: + r"""Applies softmax to a batched N-D `SparseTensor`. + + The inputs represent an N-D SparseTensor with logical shape `[..., B, C]` + (where `N >= 2`), and with indices sorted in the canonical lexicographic order. + + This op is equivalent to applying the normal `tf.nn.softmax()` to each innermost + logical submatrix with shape `[B, C]`, but with the catch that *the implicitly + zero elements do not participate*. Specifically, the algorithm is equivalent + to the following: + + (1) Applies `tf.nn.softmax()` to a densified view of each innermost submatrix + with shape `[B, C]`, along the size-C dimension; + (2) Masks out the original implicitly-zero locations; + (3) Renormalizes the remaining elements. + + Hence, the `SparseTensor` result has exactly the same non-zero indices and + shape. + + Args: + sp_indices: A `Tensor` of type `int64`. + 2-D. `NNZ x R` matrix with the indices of non-empty values in a + SparseTensor, in canonical ordering. + sp_values: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + 1-D. `NNZ` non-empty values corresponding to `sp_indices`. + sp_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `sp_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSoftmax", name, sp_indices, sp_values, sp_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_softmax_eager_fallback( + sp_indices, sp_values, sp_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSoftmax", sp_indices=sp_indices, sp_values=sp_values, + sp_shape=sp_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseSoftmax = tf_export("raw_ops.SparseSoftmax")(_ops.to_raw_op(sparse_softmax)) + + +def sparse_softmax_eager_fallback(sp_indices: Annotated[Any, _atypes.Int64], sp_values: Annotated[Any, TV_SparseSoftmax_T], sp_shape: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, TV_SparseSoftmax_T]: + _attr_T, (sp_values,) = _execute.args_to_matching_eager([sp_values], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + sp_indices = _ops.convert_to_tensor(sp_indices, _dtypes.int64) + sp_shape = _ops.convert_to_tensor(sp_shape, _dtypes.int64) + _inputs_flat = [sp_indices, sp_values, sp_shape] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseSoftmax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_SparseSparseMaximumOutput = collections.namedtuple( + "SparseSparseMaximum", + ["output_indices", "output_values"]) + + +TV_SparseSparseMaximum_T = TypeVar("TV_SparseSparseMaximum_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_sparse_maximum(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseSparseMaximum_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseSparseMaximum_T], b_shape: Annotated[Any, _atypes.Int64], name=None): + r"""Returns the element-wise max of two SparseTensors. + + Assumes the two SparseTensors have the same shape, i.e., no broadcasting. + + Args: + a_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, in the canonical lexicographic ordering. + a_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `a_indices`. + a_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + b_indices: A `Tensor` of type `int64`. + counterpart to `a_indices` for the other operand. + b_values: A `Tensor`. Must have the same type as `a_values`. + counterpart to `a_values` for the other operand; must be of the same dtype. + b_shape: A `Tensor` of type `int64`. + counterpart to `a_shape` for the other operand; the two shapes must be equal. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `a_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSparseMaximum", name, a_indices, a_values, a_shape, + b_indices, b_values, b_shape) + _result = _SparseSparseMaximumOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_sparse_maximum_eager_fallback( + a_indices, a_values, a_shape, b_indices, b_values, b_shape, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSparseMaximum", a_indices=a_indices, a_values=a_values, + a_shape=a_shape, b_indices=b_indices, + b_values=b_values, b_shape=b_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSparseMaximum", _inputs_flat, _attrs, _result) + _result = _SparseSparseMaximumOutput._make(_result) + return _result + +SparseSparseMaximum = tf_export("raw_ops.SparseSparseMaximum")(_ops.to_raw_op(sparse_sparse_maximum)) + + +def sparse_sparse_maximum_eager_fallback(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseSparseMaximum_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseSparseMaximum_T], b_shape: Annotated[Any, _atypes.Int64], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([a_values, b_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (a_values, b_values) = _inputs_T + a_indices = _ops.convert_to_tensor(a_indices, _dtypes.int64) + a_shape = _ops.convert_to_tensor(a_shape, _dtypes.int64) + b_indices = _ops.convert_to_tensor(b_indices, _dtypes.int64) + b_shape = _ops.convert_to_tensor(b_shape, _dtypes.int64) + _inputs_flat = [a_indices, a_values, a_shape, b_indices, b_values, b_shape] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseSparseMaximum", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSparseMaximum", _inputs_flat, _attrs, _result) + _result = _SparseSparseMaximumOutput._make(_result) + return _result + +_SparseSparseMinimumOutput = collections.namedtuple( + "SparseSparseMinimum", + ["output_indices", "output_values"]) + + +TV_SparseSparseMinimum_T = TypeVar("TV_SparseSparseMinimum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def sparse_sparse_minimum(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseSparseMinimum_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseSparseMinimum_T], b_shape: Annotated[Any, _atypes.Int64], name=None): + r"""Returns the element-wise min of two SparseTensors. + + Assumes the two SparseTensors have the same shape, i.e., no broadcasting. + + Args: + a_indices: A `Tensor` of type `int64`. + 2-D. `N x R` matrix with the indices of non-empty values in a + SparseTensor, in the canonical lexicographic ordering. + a_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. `N` non-empty values corresponding to `a_indices`. + a_shape: A `Tensor` of type `int64`. + 1-D. Shape of the input SparseTensor. + b_indices: A `Tensor` of type `int64`. + counterpart to `a_indices` for the other operand. + b_values: A `Tensor`. Must have the same type as `a_values`. + counterpart to `a_values` for the other operand; must be of the same dtype. + b_shape: A `Tensor` of type `int64`. + counterpart to `a_shape` for the other operand; the two shapes must be equal. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values). + + output_indices: A `Tensor` of type `int64`. + output_values: A `Tensor`. Has the same type as `a_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSparseMinimum", name, a_indices, a_values, a_shape, + b_indices, b_values, b_shape) + _result = _SparseSparseMinimumOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_sparse_minimum_eager_fallback( + a_indices, a_values, a_shape, b_indices, b_values, b_shape, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSparseMinimum", a_indices=a_indices, a_values=a_values, + a_shape=a_shape, b_indices=b_indices, + b_values=b_values, b_shape=b_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSparseMinimum", _inputs_flat, _attrs, _result) + _result = _SparseSparseMinimumOutput._make(_result) + return _result + +SparseSparseMinimum = tf_export("raw_ops.SparseSparseMinimum")(_ops.to_raw_op(sparse_sparse_minimum)) + + +def sparse_sparse_minimum_eager_fallback(a_indices: Annotated[Any, _atypes.Int64], a_values: Annotated[Any, TV_SparseSparseMinimum_T], a_shape: Annotated[Any, _atypes.Int64], b_indices: Annotated[Any, _atypes.Int64], b_values: Annotated[Any, TV_SparseSparseMinimum_T], b_shape: Annotated[Any, _atypes.Int64], name, ctx): + _attr_T, _inputs_T = _execute.args_to_matching_eager([a_values, b_values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (a_values, b_values) = _inputs_T + a_indices = _ops.convert_to_tensor(a_indices, _dtypes.int64) + a_shape = _ops.convert_to_tensor(a_shape, _dtypes.int64) + b_indices = _ops.convert_to_tensor(b_indices, _dtypes.int64) + b_shape = _ops.convert_to_tensor(b_shape, _dtypes.int64) + _inputs_flat = [a_indices, a_values, a_shape, b_indices, b_values, b_shape] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseSparseMinimum", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSparseMinimum", _inputs_flat, _attrs, _result) + _result = _SparseSparseMinimumOutput._make(_result) + return _result + +_SparseSplitOutput = collections.namedtuple( + "SparseSplit", + ["output_indices", "output_values", "output_shape"]) + + +TV_SparseSplit_T = TypeVar("TV_SparseSplit_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_split(split_dim: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseSplit_T], shape: Annotated[Any, _atypes.Int64], num_split: int, name=None): + r"""Split a `SparseTensor` into `num_split` tensors along one dimension. + + If the `shape[split_dim]` is not an integer multiple of `num_split`. Slices + `[0 : shape[split_dim] % num_split]` gets one extra dimension. + For example, if `split_dim = 1` and `num_split = 2` and the input is + + input_tensor = shape = [2, 7] + [ a d e ] + [b c ] + + Graphically the output tensors are: + + output_tensor[0] = shape = [2, 4] + [ a ] + [b c ] + + output_tensor[1] = shape = [2, 3] + [ d e ] + [ ] + + Args: + split_dim: A `Tensor` of type `int64`. + 0-D. The dimension along which to split. Must be in the range + `[0, rank(shape))`. + indices: A `Tensor` of type `int64`. + 2-D tensor represents the indices of the sparse tensor. + values: A `Tensor`. 1-D tensor represents the values of the sparse tensor. + shape: A `Tensor` of type `int64`. + 1-D. tensor represents the shape of the sparse tensor. + output indices: A list of 1-D tensors represents the indices of the output + sparse tensors. + num_split: An `int` that is `>= 1`. The number of ways to split. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output_indices, output_values, output_shape). + + output_indices: A list of `num_split` `Tensor` objects with type `int64`. + output_values: A list of `num_split` `Tensor` objects with the same type as `values`. + output_shape: A list of `num_split` `Tensor` objects with type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseSplit", name, split_dim, indices, values, shape, + "num_split", num_split) + _result = _SparseSplitOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_split_eager_fallback( + split_dim, indices, values, shape, num_split=num_split, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_split = _execute.make_int(num_split, "num_split") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseSplit", split_dim=split_dim, indices=indices, values=values, + shape=shape, num_split=num_split, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_split", _op._get_attr_int("num_split"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseSplit", _inputs_flat, _attrs, _result) + _result = [_result[:num_split]] + _result[num_split:] + _result = _result[:1] + [_result[1:1 + num_split]] + _result[1 + num_split:] + _result = _result[:2] + [_result[2:]] + _result = _SparseSplitOutput._make(_result) + return _result + +SparseSplit = tf_export("raw_ops.SparseSplit")(_ops.to_raw_op(sparse_split)) + + +def sparse_split_eager_fallback(split_dim: Annotated[Any, _atypes.Int64], indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseSplit_T], shape: Annotated[Any, _atypes.Int64], num_split: int, name, ctx): + num_split = _execute.make_int(num_split, "num_split") + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, []) + split_dim = _ops.convert_to_tensor(split_dim, _dtypes.int64) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + shape = _ops.convert_to_tensor(shape, _dtypes.int64) + _inputs_flat = [split_dim, indices, values, shape] + _attrs = ("num_split", num_split, "T", _attr_T) + _result = _execute.execute(b"SparseSplit", num_split + num_split + + num_split, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseSplit", _inputs_flat, _attrs, _result) + _result = [_result[:num_split]] + _result[num_split:] + _result = _result[:1] + [_result[1:1 + num_split]] + _result[1 + num_split:] + _result = _result[:2] + [_result[2:]] + _result = _SparseSplitOutput._make(_result) + return _result + + +TV_SparseTensorDenseAdd_T = TypeVar("TV_SparseTensorDenseAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseTensorDenseAdd_Tindices = TypeVar("TV_SparseTensorDenseAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_tensor_dense_add(a_indices: Annotated[Any, TV_SparseTensorDenseAdd_Tindices], a_values: Annotated[Any, TV_SparseTensorDenseAdd_T], a_shape: Annotated[Any, TV_SparseTensorDenseAdd_Tindices], b: Annotated[Any, TV_SparseTensorDenseAdd_T], name=None) -> Annotated[Any, TV_SparseTensorDenseAdd_T]: + r"""Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`. + + This Op does not require `a_indices` be sorted in standard lexicographic order. + + Args: + a_indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D. The `indices` of the `SparseTensor`, with shape `[nnz, ndims]`. + a_values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + 1-D. The `values` of the `SparseTensor`, with shape `[nnz]`. + a_shape: A `Tensor`. Must have the same type as `a_indices`. + 1-D. The `shape` of the `SparseTensor`, with shape `[ndims]`. + b: A `Tensor`. Must have the same type as `a_values`. + `ndims`-D Tensor. With shape `a_shape`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseTensorDenseAdd", name, a_indices, a_values, a_shape, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_tensor_dense_add_eager_fallback( + a_indices, a_values, a_shape, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseTensorDenseAdd", a_indices=a_indices, a_values=a_values, + a_shape=a_shape, b=b, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseTensorDenseAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseTensorDenseAdd = tf_export("raw_ops.SparseTensorDenseAdd")(_ops.to_raw_op(sparse_tensor_dense_add)) + + +def sparse_tensor_dense_add_eager_fallback(a_indices: Annotated[Any, TV_SparseTensorDenseAdd_Tindices], a_values: Annotated[Any, TV_SparseTensorDenseAdd_T], a_shape: Annotated[Any, TV_SparseTensorDenseAdd_Tindices], b: Annotated[Any, TV_SparseTensorDenseAdd_T], name, ctx) -> Annotated[Any, TV_SparseTensorDenseAdd_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a_values, b], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (a_values, b) = _inputs_T + _attr_Tindices, _inputs_Tindices = _execute.args_to_matching_eager([a_indices, a_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + (a_indices, a_shape) = _inputs_Tindices + _inputs_flat = [a_indices, a_values, a_shape, b] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) + _result = _execute.execute(b"SparseTensorDenseAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseTensorDenseAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseTensorDenseMatMul_T = TypeVar("TV_SparseTensorDenseMatMul_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SparseTensorDenseMatMul_Tindices = TypeVar("TV_SparseTensorDenseMatMul_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_tensor_dense_mat_mul(a_indices: Annotated[Any, TV_SparseTensorDenseMatMul_Tindices], a_values: Annotated[Any, TV_SparseTensorDenseMatMul_T], a_shape: Annotated[Any, _atypes.Int64], b: Annotated[Any, TV_SparseTensorDenseMatMul_T], adjoint_a:bool=False, adjoint_b:bool=False, name=None) -> Annotated[Any, TV_SparseTensorDenseMatMul_T]: + r"""Multiply SparseTensor (of rank 2) "A" by dense matrix "B". + + No validity checking is performed on the indices of A. However, the following + input format is recommended for optimal behavior: + + if adjoint_a == false: + A should be sorted in lexicographically increasing order. Use SparseReorder + if you're not sure. + if adjoint_a == true: + A should be sorted in order of increasing dimension 1 (i.e., "column major" + order instead of "row major" order). + + Args: + a_indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2-D. The `indices` of the `SparseTensor`, size `[nnz, 2]` Matrix. + a_values: A `Tensor`. + 1-D. The `values` of the `SparseTensor`, size `[nnz]` Vector. + a_shape: A `Tensor` of type `int64`. + 1-D. The `shape` of the `SparseTensor`, size `[2]` Vector. + b: A `Tensor`. Must have the same type as `a_values`. + 2-D. A dense Matrix. + adjoint_a: An optional `bool`. Defaults to `False`. + Use the adjoint of A in the matrix multiply. If A is complex, this + is transpose(conj(A)). Otherwise it's transpose(A). + adjoint_b: An optional `bool`. Defaults to `False`. + Use the adjoint of B in the matrix multiply. If B is complex, this + is transpose(conj(B)). Otherwise it's transpose(B). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseTensorDenseMatMul", name, a_indices, a_values, a_shape, + b, "adjoint_a", adjoint_a, "adjoint_b", adjoint_b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_tensor_dense_mat_mul_eager_fallback( + a_indices, a_values, a_shape, b, adjoint_a=adjoint_a, + adjoint_b=adjoint_b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseTensorDenseMatMul", a_indices=a_indices, a_values=a_values, + a_shape=a_shape, b=b, adjoint_a=adjoint_a, + adjoint_b=adjoint_b, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "adjoint_a", + _op._get_attr_bool("adjoint_a"), "adjoint_b", + _op._get_attr_bool("adjoint_b")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseTensorDenseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseTensorDenseMatMul = tf_export("raw_ops.SparseTensorDenseMatMul")(_ops.to_raw_op(sparse_tensor_dense_mat_mul)) + + +def sparse_tensor_dense_mat_mul_eager_fallback(a_indices: Annotated[Any, TV_SparseTensorDenseMatMul_Tindices], a_values: Annotated[Any, TV_SparseTensorDenseMatMul_T], a_shape: Annotated[Any, _atypes.Int64], b: Annotated[Any, TV_SparseTensorDenseMatMul_T], adjoint_a: bool, adjoint_b: bool, name, ctx) -> Annotated[Any, TV_SparseTensorDenseMatMul_T]: + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + _attr_T, _inputs_T = _execute.args_to_matching_eager([a_values, b], ctx, []) + (a_values, b) = _inputs_T + _attr_Tindices, (a_indices,) = _execute.args_to_matching_eager([a_indices], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + a_shape = _ops.convert_to_tensor(a_shape, _dtypes.int64) + _inputs_flat = [a_indices, a_values, a_shape, b] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "adjoint_a", adjoint_a, + "adjoint_b", adjoint_b) + _result = _execute.execute(b"SparseTensorDenseMatMul", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseTensorDenseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseToDense_T = TypeVar("TV_SparseToDense_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_SparseToDense_Tindices = TypeVar("TV_SparseToDense_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_to_dense(sparse_indices: Annotated[Any, TV_SparseToDense_Tindices], output_shape: Annotated[Any, TV_SparseToDense_Tindices], sparse_values: Annotated[Any, TV_SparseToDense_T], default_value: Annotated[Any, TV_SparseToDense_T], validate_indices:bool=True, name=None) -> Annotated[Any, TV_SparseToDense_T]: + r"""Converts a sparse representation into a dense tensor. + + Builds an array `dense` with shape `output_shape` such that + + ``` + # If sparse_indices is scalar + dense[i] = (i == sparse_indices ? sparse_values : default_value) + + # If sparse_indices is a vector, then for each i + dense[sparse_indices[i]] = sparse_values[i] + + # If sparse_indices is an n by d matrix, then for each i in [0, n) + dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i] + ``` + + All other values in `dense` are set to `default_value`. If `sparse_values` is a + scalar, all sparse indices are set to this single value. + + Indices should be sorted in lexicographic order, and indices must not + contain any repeats. If `validate_indices` is true, these properties + are checked during execution. + + Args: + sparse_indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 0-D, 1-D, or 2-D. `sparse_indices[i]` contains the complete + index where `sparse_values[i]` will be placed. + output_shape: A `Tensor`. Must have the same type as `sparse_indices`. + 1-D. Shape of the dense output tensor. + sparse_values: A `Tensor`. + 1-D. Values corresponding to each row of `sparse_indices`, + or a scalar value to be used for all sparse indices. + default_value: A `Tensor`. Must have the same type as `sparse_values`. + Scalar value to set for indices not specified in + `sparse_indices`. + validate_indices: An optional `bool`. Defaults to `True`. + If true, indices are checked to make sure they are sorted in + lexicographic order and that there are no repeats. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `sparse_values`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseToDense", name, sparse_indices, output_shape, + sparse_values, default_value, "validate_indices", validate_indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_to_dense_eager_fallback( + sparse_indices, output_shape, sparse_values, default_value, + validate_indices=validate_indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseToDense", sparse_indices=sparse_indices, + output_shape=output_shape, + sparse_values=sparse_values, + default_value=default_value, + validate_indices=validate_indices, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("validate_indices", _op._get_attr_bool("validate_indices"), "T", + _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseToDense", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseToDense = tf_export("raw_ops.SparseToDense")(_ops.to_raw_op(sparse_to_dense)) + + +def sparse_to_dense_eager_fallback(sparse_indices: Annotated[Any, TV_SparseToDense_Tindices], output_shape: Annotated[Any, TV_SparseToDense_Tindices], sparse_values: Annotated[Any, TV_SparseToDense_T], default_value: Annotated[Any, TV_SparseToDense_T], validate_indices: bool, name, ctx) -> Annotated[Any, TV_SparseToDense_T]: + if validate_indices is None: + validate_indices = True + validate_indices = _execute.make_bool(validate_indices, "validate_indices") + _attr_T, _inputs_T = _execute.args_to_matching_eager([sparse_values, default_value], ctx, []) + (sparse_values, default_value) = _inputs_T + _attr_Tindices, _inputs_Tindices = _execute.args_to_matching_eager([sparse_indices, output_shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + (sparse_indices, output_shape) = _inputs_Tindices + _inputs_flat = [sparse_indices, output_shape, sparse_values, default_value] + _attrs = ("validate_indices", validate_indices, "T", _attr_T, "Tindices", + _attr_Tindices) + _result = _execute.execute(b"SparseToDense", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseToDense", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TakeManySparseFromTensorsMapOutput = collections.namedtuple( + "TakeManySparseFromTensorsMap", + ["sparse_indices", "sparse_values", "sparse_shape"]) + + +TV_TakeManySparseFromTensorsMap_dtype = TypeVar("TV_TakeManySparseFromTensorsMap_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def take_many_sparse_from_tensors_map(sparse_handles: Annotated[Any, _atypes.Int64], dtype: TV_TakeManySparseFromTensorsMap_dtype, container:str="", shared_name:str="", name=None): + r"""Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. + + The input `sparse_handles` must be an `int64` matrix of shape `[N, 1]` where + `N` is the minibatch size and the rows correspond to the output handles of + `AddSparseToTensorsMap` or `AddManySparseToTensorsMap`. The ranks of the + original `SparseTensor` objects that went into the given input ops must all + match. When the final `SparseTensor` is created, it has rank one + higher than the ranks of the incoming `SparseTensor` objects + (they have been concatenated along a new row dimension on the left). + + The output `SparseTensor` object's shape values for all dimensions but the + first are the max across the input `SparseTensor` objects' shape values + for the corresponding dimensions. Its first shape value is `N`, the minibatch + size. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `SparseReorder` to restore index ordering. + + For example, if the handles represent an input, which is a `[2, 3]` matrix + representing two original `SparseTensor` objects: + + ``` + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + ``` + + and + + ``` + index = [ 2] + [10] + values = [4, 5] + shape = [30] + ``` + + then the final `SparseTensor` will be: + + ``` + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + ``` + + Args: + sparse_handles: A `Tensor` of type `int64`. + 1-D, The `N` serialized `SparseTensor` objects. + Shape: `[N]`. + dtype: A `tf.DType`. + The `dtype` of the `SparseTensor` objects stored in the + `SparseTensorsMap`. + container: An optional `string`. Defaults to `""`. + The container name for the `SparseTensorsMap` read by this op. + shared_name: An optional `string`. Defaults to `""`. + The shared name for the `SparseTensorsMap` read by this op. + It should not be blank; rather the `shared_name` or unique Operation name + of the Op that created the original `SparseTensorsMap` should be used. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (sparse_indices, sparse_values, sparse_shape). + + sparse_indices: A `Tensor` of type `int64`. + sparse_values: A `Tensor` of type `dtype`. + sparse_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TakeManySparseFromTensorsMap", name, sparse_handles, "dtype", + dtype, "container", container, "shared_name", shared_name) + _result = _TakeManySparseFromTensorsMapOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return take_many_sparse_from_tensors_map_eager_fallback( + sparse_handles, dtype=dtype, container=container, + shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TakeManySparseFromTensorsMap", sparse_handles=sparse_handles, + dtype=dtype, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TakeManySparseFromTensorsMap", _inputs_flat, _attrs, _result) + _result = _TakeManySparseFromTensorsMapOutput._make(_result) + return _result + +TakeManySparseFromTensorsMap = tf_export("raw_ops.TakeManySparseFromTensorsMap")(_ops.to_raw_op(take_many_sparse_from_tensors_map)) + + +def take_many_sparse_from_tensors_map_eager_fallback(sparse_handles: Annotated[Any, _atypes.Int64], dtype: TV_TakeManySparseFromTensorsMap_dtype, container: str, shared_name: str, name, ctx): + dtype = _execute.make_type(dtype, "dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + sparse_handles = _ops.convert_to_tensor(sparse_handles, _dtypes.int64) + _inputs_flat = [sparse_handles] + _attrs = ("dtype", dtype, "container", container, "shared_name", + shared_name) + _result = _execute.execute(b"TakeManySparseFromTensorsMap", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TakeManySparseFromTensorsMap", _inputs_flat, _attrs, _result) + _result = _TakeManySparseFromTensorsMapOutput._make(_result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_special_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_special_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9e6a52091797ce68ada5ff9472befd1a12909c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_special_math_ops.py @@ -0,0 +1,975 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_BesselI0_T = TypeVar("TV_BesselI0_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_i0(x: Annotated[Any, TV_BesselI0_T], name=None) -> Annotated[Any, TV_BesselI0_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselI0", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_i0_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselI0", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselI0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselI0 = tf_export("raw_ops.BesselI0")(_ops.to_raw_op(bessel_i0)) + + +def bessel_i0_eager_fallback(x: Annotated[Any, TV_BesselI0_T], name, ctx) -> Annotated[Any, TV_BesselI0_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselI0", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselI0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselI0e_T = TypeVar("TV_BesselI0e_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_i0e(x: Annotated[Any, TV_BesselI0e_T], name=None) -> Annotated[Any, TV_BesselI0e_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselI0e", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_i0e_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselI0e", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselI0e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselI0e = tf_export("raw_ops.BesselI0e")(_ops.to_raw_op(bessel_i0e)) + + +def bessel_i0e_eager_fallback(x: Annotated[Any, TV_BesselI0e_T], name, ctx) -> Annotated[Any, TV_BesselI0e_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselI0e", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselI0e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselI1_T = TypeVar("TV_BesselI1_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_i1(x: Annotated[Any, TV_BesselI1_T], name=None) -> Annotated[Any, TV_BesselI1_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselI1", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_i1_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselI1", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselI1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselI1 = tf_export("raw_ops.BesselI1")(_ops.to_raw_op(bessel_i1)) + + +def bessel_i1_eager_fallback(x: Annotated[Any, TV_BesselI1_T], name, ctx) -> Annotated[Any, TV_BesselI1_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselI1", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselI1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselI1e_T = TypeVar("TV_BesselI1e_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_i1e(x: Annotated[Any, TV_BesselI1e_T], name=None) -> Annotated[Any, TV_BesselI1e_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselI1e", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_i1e_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselI1e", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselI1e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselI1e = tf_export("raw_ops.BesselI1e")(_ops.to_raw_op(bessel_i1e)) + + +def bessel_i1e_eager_fallback(x: Annotated[Any, TV_BesselI1e_T], name, ctx) -> Annotated[Any, TV_BesselI1e_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselI1e", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselI1e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselJ0_T = TypeVar("TV_BesselJ0_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_j0(x: Annotated[Any, TV_BesselJ0_T], name=None) -> Annotated[Any, TV_BesselJ0_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselJ0", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_j0_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselJ0", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselJ0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselJ0 = tf_export("raw_ops.BesselJ0")(_ops.to_raw_op(bessel_j0)) + + +def bessel_j0_eager_fallback(x: Annotated[Any, TV_BesselJ0_T], name, ctx) -> Annotated[Any, TV_BesselJ0_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselJ0", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselJ0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselJ1_T = TypeVar("TV_BesselJ1_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_j1(x: Annotated[Any, TV_BesselJ1_T], name=None) -> Annotated[Any, TV_BesselJ1_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselJ1", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_j1_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselJ1", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselJ1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselJ1 = tf_export("raw_ops.BesselJ1")(_ops.to_raw_op(bessel_j1)) + + +def bessel_j1_eager_fallback(x: Annotated[Any, TV_BesselJ1_T], name, ctx) -> Annotated[Any, TV_BesselJ1_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselJ1", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselJ1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselK0_T = TypeVar("TV_BesselK0_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_k0(x: Annotated[Any, TV_BesselK0_T], name=None) -> Annotated[Any, TV_BesselK0_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselK0", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_k0_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselK0", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselK0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselK0 = tf_export("raw_ops.BesselK0")(_ops.to_raw_op(bessel_k0)) + + +def bessel_k0_eager_fallback(x: Annotated[Any, TV_BesselK0_T], name, ctx) -> Annotated[Any, TV_BesselK0_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselK0", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselK0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselK0e_T = TypeVar("TV_BesselK0e_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_k0e(x: Annotated[Any, TV_BesselK0e_T], name=None) -> Annotated[Any, TV_BesselK0e_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselK0e", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_k0e_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselK0e", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselK0e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselK0e = tf_export("raw_ops.BesselK0e")(_ops.to_raw_op(bessel_k0e)) + + +def bessel_k0e_eager_fallback(x: Annotated[Any, TV_BesselK0e_T], name, ctx) -> Annotated[Any, TV_BesselK0e_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselK0e", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselK0e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselK1_T = TypeVar("TV_BesselK1_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_k1(x: Annotated[Any, TV_BesselK1_T], name=None) -> Annotated[Any, TV_BesselK1_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselK1", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_k1_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselK1", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselK1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselK1 = tf_export("raw_ops.BesselK1")(_ops.to_raw_op(bessel_k1)) + + +def bessel_k1_eager_fallback(x: Annotated[Any, TV_BesselK1_T], name, ctx) -> Annotated[Any, TV_BesselK1_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselK1", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselK1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselK1e_T = TypeVar("TV_BesselK1e_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_k1e(x: Annotated[Any, TV_BesselK1e_T], name=None) -> Annotated[Any, TV_BesselK1e_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselK1e", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_k1e_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselK1e", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselK1e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselK1e = tf_export("raw_ops.BesselK1e")(_ops.to_raw_op(bessel_k1e)) + + +def bessel_k1e_eager_fallback(x: Annotated[Any, TV_BesselK1e_T], name, ctx) -> Annotated[Any, TV_BesselK1e_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselK1e", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselK1e", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselY0_T = TypeVar("TV_BesselY0_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_y0(x: Annotated[Any, TV_BesselY0_T], name=None) -> Annotated[Any, TV_BesselY0_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselY0", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_y0_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselY0", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselY0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselY0 = tf_export("raw_ops.BesselY0")(_ops.to_raw_op(bessel_y0)) + + +def bessel_y0_eager_fallback(x: Annotated[Any, TV_BesselY0_T], name, ctx) -> Annotated[Any, TV_BesselY0_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselY0", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselY0", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_BesselY1_T = TypeVar("TV_BesselY1_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def bessel_y1(x: Annotated[Any, TV_BesselY1_T], name=None) -> Annotated[Any, TV_BesselY1_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BesselY1", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return bessel_y1_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BesselY1", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "BesselY1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BesselY1 = tf_export("raw_ops.BesselY1")(_ops.to_raw_op(bessel_y1)) + + +def bessel_y1_eager_fallback(x: Annotated[Any, TV_BesselY1_T], name, ctx) -> Annotated[Any, TV_BesselY1_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"BesselY1", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BesselY1", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Dawsn_T = TypeVar("TV_Dawsn_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def dawsn(x: Annotated[Any, TV_Dawsn_T], name=None) -> Annotated[Any, TV_Dawsn_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Dawsn", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dawsn_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Dawsn", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Dawsn", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Dawsn = tf_export("raw_ops.Dawsn")(_ops.to_raw_op(dawsn)) + + +def dawsn_eager_fallback(x: Annotated[Any, TV_Dawsn_T], name, ctx) -> Annotated[Any, TV_Dawsn_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Dawsn", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Dawsn", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Expint_T = TypeVar("TV_Expint_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def expint(x: Annotated[Any, TV_Expint_T], name=None) -> Annotated[Any, TV_Expint_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Expint", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return expint_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Expint", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Expint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Expint = tf_export("raw_ops.Expint")(_ops.to_raw_op(expint)) + + +def expint_eager_fallback(x: Annotated[Any, TV_Expint_T], name, ctx) -> Annotated[Any, TV_Expint_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Expint", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Expint", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FresnelCos_T = TypeVar("TV_FresnelCos_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def fresnel_cos(x: Annotated[Any, TV_FresnelCos_T], name=None) -> Annotated[Any, TV_FresnelCos_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FresnelCos", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fresnel_cos_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FresnelCos", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FresnelCos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FresnelCos = tf_export("raw_ops.FresnelCos")(_ops.to_raw_op(fresnel_cos)) + + +def fresnel_cos_eager_fallback(x: Annotated[Any, TV_FresnelCos_T], name, ctx) -> Annotated[Any, TV_FresnelCos_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"FresnelCos", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FresnelCos", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FresnelSin_T = TypeVar("TV_FresnelSin_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def fresnel_sin(x: Annotated[Any, TV_FresnelSin_T], name=None) -> Annotated[Any, TV_FresnelSin_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FresnelSin", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return fresnel_sin_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FresnelSin", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FresnelSin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FresnelSin = tf_export("raw_ops.FresnelSin")(_ops.to_raw_op(fresnel_sin)) + + +def fresnel_sin_eager_fallback(x: Annotated[Any, TV_FresnelSin_T], name, ctx) -> Annotated[Any, TV_FresnelSin_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"FresnelSin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FresnelSin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Spence_T = TypeVar("TV_Spence_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) + +def spence(x: Annotated[Any, TV_Spence_T], name=None) -> Annotated[Any, TV_Spence_T]: + r"""TODO: add doc. + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Spence", name, x) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return spence_eager_fallback( + x, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Spence", x=x, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Spence", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Spence = tf_export("raw_ops.Spence")(_ops.to_raw_op(spence)) + + +def spence_eager_fallback(x: Annotated[Any, TV_Spence_T], name, ctx) -> Annotated[Any, TV_Spence_T]: + _attr_T, (x,) = _execute.args_to_matching_eager([x], ctx, [_dtypes.bfloat16, _dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _inputs_flat = [x] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Spence", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Spence", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_spectral_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_spectral_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8413e29ef4008b0894452a4c356328d13aac35e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_spectral_ops.py @@ -0,0 +1,1815 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def batch_fft(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchFFT", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_fft_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchFFT", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchFFT = tf_export("raw_ops.BatchFFT")(_ops.to_raw_op(batch_fft)) + + +def batch_fft_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchFFT", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_fft2d(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchFFT2D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_fft2d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchFFT2D", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchFFT2D = tf_export("raw_ops.BatchFFT2D")(_ops.to_raw_op(batch_fft2d)) + + +def batch_fft2d_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchFFT2D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_fft3d(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchFFT3D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_fft3d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchFFT3D", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchFFT3D = tf_export("raw_ops.BatchFFT3D")(_ops.to_raw_op(batch_fft3d)) + + +def batch_fft3d_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchFFT3D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_ifft(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchIFFT", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_ifft_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchIFFT", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchIFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchIFFT = tf_export("raw_ops.BatchIFFT")(_ops.to_raw_op(batch_ifft)) + + +def batch_ifft_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchIFFT", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchIFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_ifft2d(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchIFFT2D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_ifft2d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchIFFT2D", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchIFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchIFFT2D = tf_export("raw_ops.BatchIFFT2D")(_ops.to_raw_op(batch_ifft2d)) + + +def batch_ifft2d_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchIFFT2D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchIFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def batch_ifft3d(input: Annotated[Any, _atypes.Complex64], name=None) -> Annotated[Any, _atypes.Complex64]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "BatchIFFT3D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return batch_ifft3d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "BatchIFFT3D", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "BatchIFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +BatchIFFT3D = tf_export("raw_ops.BatchIFFT3D")(_ops.to_raw_op(batch_ifft3d)) + + +def batch_ifft3d_eager_fallback(input: Annotated[Any, _atypes.Complex64], name, ctx) -> Annotated[Any, _atypes.Complex64]: + input = _ops.convert_to_tensor(input, _dtypes.complex64) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"BatchIFFT3D", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "BatchIFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FFT_Tcomplex = TypeVar("TV_FFT_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.fft', v1=['signal.fft', 'spectral.fft', 'fft']) +@deprecated_endpoints('spectral.fft', 'fft') +def fft(input: Annotated[Any, TV_FFT_Tcomplex], name=None) -> Annotated[Any, TV_FFT_Tcomplex]: + r"""Fast Fourier transform. + + Computes the 1-dimensional discrete Fourier transform over the inner-most + dimension of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FFT", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fft( + (input, name,), None) + if _result is not NotImplemented: + return _result + return fft_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fft( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FFT", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FFT = tf_export("raw_ops.FFT")(_ops.to_raw_op(fft)) +_dispatcher_for_fft = fft._tf_type_based_dispatcher.Dispatch + + +def fft_eager_fallback(input: Annotated[Any, TV_FFT_Tcomplex], name, ctx) -> Annotated[Any, TV_FFT_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"FFT", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FFT2D_Tcomplex = TypeVar("TV_FFT2D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.fft2d', v1=['signal.fft2d', 'spectral.fft2d', 'fft2d']) +@deprecated_endpoints('spectral.fft2d', 'fft2d') +def fft2d(input: Annotated[Any, TV_FFT2D_Tcomplex], name=None) -> Annotated[Any, TV_FFT2D_Tcomplex]: + r"""2D fast Fourier transform. + + Computes the 2-dimensional discrete Fourier transform over the inner-most + 2 dimensions of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FFT2D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fft2d( + (input, name,), None) + if _result is not NotImplemented: + return _result + return fft2d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft2d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fft2d( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FFT2D", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft2d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FFT2D = tf_export("raw_ops.FFT2D")(_ops.to_raw_op(fft2d)) +_dispatcher_for_fft2d = fft2d._tf_type_based_dispatcher.Dispatch + + +def fft2d_eager_fallback(input: Annotated[Any, TV_FFT2D_Tcomplex], name, ctx) -> Annotated[Any, TV_FFT2D_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"FFT2D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FFT3D_Tcomplex = TypeVar("TV_FFT3D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.fft3d', v1=['signal.fft3d', 'spectral.fft3d', 'fft3d']) +@deprecated_endpoints('spectral.fft3d', 'fft3d') +def fft3d(input: Annotated[Any, TV_FFT3D_Tcomplex], name=None) -> Annotated[Any, TV_FFT3D_Tcomplex]: + r"""3D fast Fourier transform. + + Computes the 3-dimensional discrete Fourier transform over the inner-most 3 + dimensions of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FFT3D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fft3d( + (input, name,), None) + if _result is not NotImplemented: + return _result + return fft3d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft3d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fft3d( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FFT3D", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fft3d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FFT3D = tf_export("raw_ops.FFT3D")(_ops.to_raw_op(fft3d)) +_dispatcher_for_fft3d = fft3d._tf_type_based_dispatcher.Dispatch + + +def fft3d_eager_fallback(input: Annotated[Any, TV_FFT3D_Tcomplex], name, ctx) -> Annotated[Any, TV_FFT3D_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"FFT3D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_FFTND_Tcomplex = TypeVar("TV_FFTND_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('fftnd') +def fftnd(input: Annotated[Any, TV_FFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_FFTND_Tcomplex]: + r"""ND fast Fourier transform. + + Computes the n-dimensional discrete Fourier transform over + designated dimensions of `input`. The designated dimensions of + `input` are assumed to be the result of `FFTND`. + + If fft_length[i]shape(input)[i], the input is padded with zeros. If fft_length + is not given, the default shape(input) is used. + + Axes mean the dimensions to perform the transform on. Default is to perform on + all axes. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor. The FFT length for each dimension. + axes: A `Tensor` of type `int32`. + An int32 tensor with a same shape as fft_length. Axes to perform the transform. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FFTND", name, input, fft_length, axes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_fftnd( + (input, fft_length, axes, name,), None) + if _result is not NotImplemented: + return _result + return fftnd_eager_fallback( + input, fft_length, axes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_fftnd( + (input, fft_length, axes, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FFTND", input=input, fft_length=fft_length, axes=axes, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + fftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "FFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FFTND = tf_export("raw_ops.FFTND")(_ops.to_raw_op(fftnd)) +_dispatcher_for_fftnd = fftnd._tf_type_based_dispatcher.Dispatch + + +def fftnd_eager_fallback(input: Annotated[Any, TV_FFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_FFTND_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + axes = _ops.convert_to_tensor(axes, _dtypes.int32) + _inputs_flat = [input, fft_length, axes] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"FFTND", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IFFT_Tcomplex = TypeVar("TV_IFFT_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.ifft', v1=['signal.ifft', 'spectral.ifft', 'ifft']) +@deprecated_endpoints('spectral.ifft', 'ifft') +def ifft(input: Annotated[Any, TV_IFFT_Tcomplex], name=None) -> Annotated[Any, TV_IFFT_Tcomplex]: + r"""Inverse fast Fourier transform. + + Computes the inverse 1-dimensional discrete Fourier transform over the + inner-most dimension of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IFFT", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ifft( + (input, name,), None) + if _result is not NotImplemented: + return _result + return ifft_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ifft( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IFFT", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IFFT = tf_export("raw_ops.IFFT")(_ops.to_raw_op(ifft)) +_dispatcher_for_ifft = ifft._tf_type_based_dispatcher.Dispatch + + +def ifft_eager_fallback(input: Annotated[Any, TV_IFFT_Tcomplex], name, ctx) -> Annotated[Any, TV_IFFT_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IFFT", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IFFT2D_Tcomplex = TypeVar("TV_IFFT2D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.ifft2d', v1=['signal.ifft2d', 'spectral.ifft2d', 'ifft2d']) +@deprecated_endpoints('spectral.ifft2d', 'ifft2d') +def ifft2d(input: Annotated[Any, TV_IFFT2D_Tcomplex], name=None) -> Annotated[Any, TV_IFFT2D_Tcomplex]: + r"""Inverse 2D fast Fourier transform. + + Computes the inverse 2-dimensional discrete Fourier transform over the + inner-most 2 dimensions of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IFFT2D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ifft2d( + (input, name,), None) + if _result is not NotImplemented: + return _result + return ifft2d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft2d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ifft2d( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IFFT2D", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft2d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IFFT2D = tf_export("raw_ops.IFFT2D")(_ops.to_raw_op(ifft2d)) +_dispatcher_for_ifft2d = ifft2d._tf_type_based_dispatcher.Dispatch + + +def ifft2d_eager_fallback(input: Annotated[Any, TV_IFFT2D_Tcomplex], name, ctx) -> Annotated[Any, TV_IFFT2D_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IFFT2D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IFFT3D_Tcomplex = TypeVar("TV_IFFT3D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('signal.ifft3d', v1=['signal.ifft3d', 'spectral.ifft3d', 'ifft3d']) +@deprecated_endpoints('spectral.ifft3d', 'ifft3d') +def ifft3d(input: Annotated[Any, TV_IFFT3D_Tcomplex], name=None) -> Annotated[Any, TV_IFFT3D_Tcomplex]: + r"""Inverse 3D fast Fourier transform. + + Computes the inverse 3-dimensional discrete Fourier transform over the + inner-most 3 dimensions of `input`. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IFFT3D", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ifft3d( + (input, name,), None) + if _result is not NotImplemented: + return _result + return ifft3d_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft3d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ifft3d( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IFFT3D", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifft3d, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IFFT3D = tf_export("raw_ops.IFFT3D")(_ops.to_raw_op(ifft3d)) +_dispatcher_for_ifft3d = ifft3d._tf_type_based_dispatcher.Dispatch + + +def ifft3d_eager_fallback(input: Annotated[Any, TV_IFFT3D_Tcomplex], name, ctx) -> Annotated[Any, TV_IFFT3D_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + _inputs_flat = [input] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IFFT3D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IFFTND_Tcomplex = TypeVar("TV_IFFTND_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ifftnd') +def ifftnd(input: Annotated[Any, TV_IFFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_IFFTND_Tcomplex]: + r"""ND inverse fast Fourier transform. + + Computes the n-dimensional inverse discrete Fourier transform over designated + dimensions of `input`. The designated dimensions of `input` are assumed to be + the result of `IFFTND`. + + If fft_length[i]shape(input)[i], the input is padded with zeros. If fft_length + is not given, the default shape(input) is used. + + Axes mean the dimensions to perform the transform on. Default is to perform on + all axes. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor. The FFT length for each dimension. + axes: A `Tensor` of type `int32`. + An int32 tensor with a same shape as fft_length. Axes to perform the transform. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IFFTND", name, input, fft_length, axes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_ifftnd( + (input, fft_length, axes, name,), None) + if _result is not NotImplemented: + return _result + return ifftnd_eager_fallback( + input, fft_length, axes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_ifftnd( + (input, fft_length, axes, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IFFTND", input=input, fft_length=fft_length, axes=axes, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ifftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tcomplex", _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IFFTND = tf_export("raw_ops.IFFTND")(_ops.to_raw_op(ifftnd)) +_dispatcher_for_ifftnd = ifftnd._tf_type_based_dispatcher.Dispatch + + +def ifftnd_eager_fallback(input: Annotated[Any, TV_IFFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_IFFTND_Tcomplex]: + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + axes = _ops.convert_to_tensor(axes, _dtypes.int32) + _inputs_flat = [input, fft_length, axes] + _attrs = ("Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IFFTND", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IRFFT_Treal = TypeVar("TV_IRFFT_Treal", _atypes.Float32, _atypes.Float64) +TV_IRFFT_Tcomplex = TypeVar("TV_IRFFT_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def irfft(input: Annotated[Any, TV_IRFFT_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal:TV_IRFFT_Treal=_dtypes.float32, name=None) -> Annotated[Any, TV_IRFFT_Treal]: + r"""Inverse real-valued fast Fourier transform. + + Computes the inverse 1-dimensional discrete Fourier transform of a real-valued + signal over the inner-most dimension of `input`. + + The inner-most dimension of `input` is assumed to be the result of `RFFT`: the + `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. If + `fft_length` is not provided, it is computed from the size of the inner-most + dimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to + compute `input` is odd, it should be provided since it cannot be inferred + properly. + + Along the axis `IRFFT` is computed on, if `fft_length / 2 + 1` is smaller + than the corresponding dimension of `input`, the dimension is cropped. If it is + larger, the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [1]. The FFT length. + Treal: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Treal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IRFFT", name, input, fft_length, "Treal", Treal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return irfft_eager_fallback( + input, fft_length, Treal=Treal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IRFFT", input=input, fft_length=fft_length, Treal=Treal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IRFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IRFFT = tf_export("raw_ops.IRFFT")(_ops.to_raw_op(irfft)) + + +def irfft_eager_fallback(input: Annotated[Any, TV_IRFFT_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal: TV_IRFFT_Treal, name, ctx) -> Annotated[Any, TV_IRFFT_Treal]: + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", Treal, "Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IRFFT", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IRFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IRFFT2D_Treal = TypeVar("TV_IRFFT2D_Treal", _atypes.Float32, _atypes.Float64) +TV_IRFFT2D_Tcomplex = TypeVar("TV_IRFFT2D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def irfft2d(input: Annotated[Any, TV_IRFFT2D_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal:TV_IRFFT2D_Treal=_dtypes.float32, name=None) -> Annotated[Any, TV_IRFFT2D_Treal]: + r"""Inverse 2D real-valued fast Fourier transform. + + Computes the inverse 2-dimensional discrete Fourier transform of a real-valued + signal over the inner-most 2 dimensions of `input`. + + The inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`: + The inner-most dimension contains the `fft_length / 2 + 1` unique components of + the DFT of a real-valued signal. If `fft_length` is not provided, it is computed + from the size of the inner-most 2 dimensions of `input`. If the FFT length used + to compute `input` is odd, it should be provided since it cannot be inferred + properly. + + Along each axis `IRFFT2D` is computed on, if `fft_length` (or + `fft_length / 2 + 1` for the inner-most dimension) is smaller than the + corresponding dimension of `input`, the dimension is cropped. If it is larger, + the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [2]. The FFT length for each dimension. + Treal: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Treal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IRFFT2D", name, input, fft_length, "Treal", Treal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return irfft2d_eager_fallback( + input, fft_length, Treal=Treal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IRFFT2D", input=input, fft_length=fft_length, Treal=Treal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IRFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IRFFT2D = tf_export("raw_ops.IRFFT2D")(_ops.to_raw_op(irfft2d)) + + +def irfft2d_eager_fallback(input: Annotated[Any, TV_IRFFT2D_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal: TV_IRFFT2D_Treal, name, ctx) -> Annotated[Any, TV_IRFFT2D_Treal]: + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", Treal, "Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IRFFT2D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IRFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IRFFT3D_Treal = TypeVar("TV_IRFFT3D_Treal", _atypes.Float32, _atypes.Float64) +TV_IRFFT3D_Tcomplex = TypeVar("TV_IRFFT3D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def irfft3d(input: Annotated[Any, TV_IRFFT3D_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal:TV_IRFFT3D_Treal=_dtypes.float32, name=None) -> Annotated[Any, TV_IRFFT3D_Treal]: + r"""Inverse 3D real-valued fast Fourier transform. + + Computes the inverse 3-dimensional discrete Fourier transform of a real-valued + signal over the inner-most 3 dimensions of `input`. + + The inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`: + The inner-most dimension contains the `fft_length / 2 + 1` unique components of + the DFT of a real-valued signal. If `fft_length` is not provided, it is computed + from the size of the inner-most 3 dimensions of `input`. If the FFT length used + to compute `input` is odd, it should be provided since it cannot be inferred + properly. + + Along each axis `IRFFT3D` is computed on, if `fft_length` (or + `fft_length / 2 + 1` for the inner-most dimension) is smaller than the + corresponding dimension of `input`, the dimension is cropped. If it is larger, + the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [3]. The FFT length for each dimension. + Treal: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Treal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IRFFT3D", name, input, fft_length, "Treal", Treal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return irfft3d_eager_fallback( + input, fft_length, Treal=Treal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IRFFT3D", input=input, fft_length=fft_length, Treal=Treal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IRFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IRFFT3D = tf_export("raw_ops.IRFFT3D")(_ops.to_raw_op(irfft3d)) + + +def irfft3d_eager_fallback(input: Annotated[Any, TV_IRFFT3D_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], Treal: TV_IRFFT3D_Treal, name, ctx) -> Annotated[Any, TV_IRFFT3D_Treal]: + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", Treal, "Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IRFFT3D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IRFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_IRFFTND_Treal = TypeVar("TV_IRFFTND_Treal", _atypes.Float32, _atypes.Float64) +TV_IRFFTND_Tcomplex = TypeVar("TV_IRFFTND_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('irfftnd') +def irfftnd(input: Annotated[Any, TV_IRFFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], Treal:TV_IRFFTND_Treal=_dtypes.float32, name=None) -> Annotated[Any, TV_IRFFTND_Treal]: + r"""ND inverse real fast Fourier transform. + + Computes the n-dimensional inverse real discrete Fourier transform over + designated dimensions of `input`. The designated dimensions of `input` are + assumed to be the result of `IRFFTND`. The inner-most dimension contains the + `fft_length / 2 + 1` unique components of the DFT of a real-valued signal. + + If fft_length[i]shape(input)[i], the input is padded with zeros. If fft_length + is not given, the default shape(input) is used. + + Axes mean the dimensions to perform the transform on. Default is to perform on + all axes. + + Args: + input: A `Tensor`. Must be one of the following types: `complex64`, `complex128`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor. The FFT length for each dimension. + axes: A `Tensor` of type `int32`. + An int32 tensor with a same shape as fft_length. Axes to perform the transform. + Treal: An optional `tf.DType` from: `tf.float32, tf.float64`. Defaults to `tf.float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Treal`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IRFFTND", name, input, fft_length, axes, "Treal", Treal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_irfftnd( + (input, fft_length, axes, Treal, name,), None) + if _result is not NotImplemented: + return _result + return irfftnd_eager_fallback( + input, fft_length, axes, Treal=Treal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + irfftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + Treal=Treal, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_irfftnd( + (input, fft_length, axes, Treal, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IRFFTND", input=input, fft_length=fft_length, axes=axes, Treal=Treal, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + irfftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + Treal=Treal, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IRFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IRFFTND = tf_export("raw_ops.IRFFTND")(_ops.to_raw_op(irfftnd)) +_dispatcher_for_irfftnd = irfftnd._tf_type_based_dispatcher.Dispatch + + +def irfftnd_eager_fallback(input: Annotated[Any, TV_IRFFTND_Tcomplex], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], Treal: TV_IRFFTND_Treal, name, ctx) -> Annotated[Any, TV_IRFFTND_Treal]: + if Treal is None: + Treal = _dtypes.float32 + Treal = _execute.make_type(Treal, "Treal") + _attr_Tcomplex, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.complex64, _dtypes.complex128, ], _dtypes.complex64) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + axes = _ops.convert_to_tensor(axes, _dtypes.int32) + _inputs_flat = [input, fft_length, axes] + _attrs = ("Treal", Treal, "Tcomplex", _attr_Tcomplex) + _result = _execute.execute(b"IRFFTND", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IRFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RFFT_Treal = TypeVar("TV_RFFT_Treal", _atypes.Float32, _atypes.Float64) +TV_RFFT_Tcomplex = TypeVar("TV_RFFT_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def rfft(input: Annotated[Any, TV_RFFT_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex:TV_RFFT_Tcomplex=_dtypes.complex64, name=None) -> Annotated[Any, TV_RFFT_Tcomplex]: + r"""Real-valued fast Fourier transform. + + Computes the 1-dimensional discrete Fourier transform of a real-valued signal + over the inner-most dimension of `input`. + + Since the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the + `fft_length / 2 + 1` unique components of the FFT: the zero-frequency term, + followed by the `fft_length / 2` positive-frequency terms. + + Along the axis `RFFT` is computed on, if `fft_length` is smaller than the + corresponding dimension of `input`, the dimension is cropped. If it is larger, + the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`. + A float32 tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [1]. The FFT length. + Tcomplex: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tcomplex`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RFFT", name, input, fft_length, "Tcomplex", Tcomplex) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rfft_eager_fallback( + input, fft_length, Tcomplex=Tcomplex, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RFFT", input=input, fft_length=fft_length, Tcomplex=Tcomplex, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RFFT = tf_export("raw_ops.RFFT")(_ops.to_raw_op(rfft)) + + +def rfft_eager_fallback(input: Annotated[Any, TV_RFFT_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex: TV_RFFT_Tcomplex, name, ctx) -> Annotated[Any, TV_RFFT_Tcomplex]: + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _attr_Treal, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", _attr_Treal, "Tcomplex", Tcomplex) + _result = _execute.execute(b"RFFT", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RFFT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RFFT2D_Treal = TypeVar("TV_RFFT2D_Treal", _atypes.Float32, _atypes.Float64) +TV_RFFT2D_Tcomplex = TypeVar("TV_RFFT2D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def rfft2d(input: Annotated[Any, TV_RFFT2D_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex:TV_RFFT2D_Tcomplex=_dtypes.complex64, name=None) -> Annotated[Any, TV_RFFT2D_Tcomplex]: + r"""2D real-valued fast Fourier transform. + + Computes the 2-dimensional discrete Fourier transform of a real-valued signal + over the inner-most 2 dimensions of `input`. + + Since the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the + `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension + of `output`: the zero-frequency term, followed by the `fft_length / 2` + positive-frequency terms. + + Along each axis `RFFT2D` is computed on, if `fft_length` is smaller than the + corresponding dimension of `input`, the dimension is cropped. If it is larger, + the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`. + A float32 tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [2]. The FFT length for each dimension. + Tcomplex: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tcomplex`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RFFT2D", name, input, fft_length, "Tcomplex", Tcomplex) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rfft2d_eager_fallback( + input, fft_length, Tcomplex=Tcomplex, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RFFT2D", input=input, fft_length=fft_length, Tcomplex=Tcomplex, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RFFT2D = tf_export("raw_ops.RFFT2D")(_ops.to_raw_op(rfft2d)) + + +def rfft2d_eager_fallback(input: Annotated[Any, TV_RFFT2D_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex: TV_RFFT2D_Tcomplex, name, ctx) -> Annotated[Any, TV_RFFT2D_Tcomplex]: + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _attr_Treal, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", _attr_Treal, "Tcomplex", Tcomplex) + _result = _execute.execute(b"RFFT2D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RFFT2D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RFFT3D_Treal = TypeVar("TV_RFFT3D_Treal", _atypes.Float32, _atypes.Float64) +TV_RFFT3D_Tcomplex = TypeVar("TV_RFFT3D_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +def rfft3d(input: Annotated[Any, TV_RFFT3D_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex:TV_RFFT3D_Tcomplex=_dtypes.complex64, name=None) -> Annotated[Any, TV_RFFT3D_Tcomplex]: + r"""3D real-valued fast Fourier transform. + + Computes the 3-dimensional discrete Fourier transform of a real-valued signal + over the inner-most 3 dimensions of `input`. + + Since the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the + `fft_length / 2 + 1` unique components of the FFT for the inner-most dimension + of `output`: the zero-frequency term, followed by the `fft_length / 2` + positive-frequency terms. + + Along each axis `RFFT3D` is computed on, if `fft_length` is smaller than the + corresponding dimension of `input`, the dimension is cropped. If it is larger, + the dimension is padded with zeros. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`. + A float32 tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor of shape [3]. The FFT length for each dimension. + Tcomplex: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tcomplex`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RFFT3D", name, input, fft_length, "Tcomplex", Tcomplex) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rfft3d_eager_fallback( + input, fft_length, Tcomplex=Tcomplex, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RFFT3D", input=input, fft_length=fft_length, Tcomplex=Tcomplex, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RFFT3D = tf_export("raw_ops.RFFT3D")(_ops.to_raw_op(rfft3d)) + + +def rfft3d_eager_fallback(input: Annotated[Any, TV_RFFT3D_Treal], fft_length: Annotated[Any, _atypes.Int32], Tcomplex: TV_RFFT3D_Tcomplex, name, ctx) -> Annotated[Any, TV_RFFT3D_Tcomplex]: + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _attr_Treal, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + _inputs_flat = [input, fft_length] + _attrs = ("Treal", _attr_Treal, "Tcomplex", Tcomplex) + _result = _execute.execute(b"RFFT3D", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RFFT3D", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RFFTND_Treal = TypeVar("TV_RFFTND_Treal", _atypes.Float32, _atypes.Float64) +TV_RFFTND_Tcomplex = TypeVar("TV_RFFTND_Tcomplex", _atypes.Complex128, _atypes.Complex64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('rfftnd') +def rfftnd(input: Annotated[Any, TV_RFFTND_Treal], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], Tcomplex:TV_RFFTND_Tcomplex=_dtypes.complex64, name=None) -> Annotated[Any, TV_RFFTND_Tcomplex]: + r"""ND fast real Fourier transform. + + Computes the n-dimensional real discrete Fourier transform over designated + dimensions of `input`. The designated dimensions of `input` are assumed to be + the result of `RFFTND`. The length of the last axis transformed will be + fft_length[-1]//2+1. + + If fft_length[i]shape(input)[i], the input is padded with zeros. If fft_length + is not given, the default shape(input) is used. + + Axes mean the dimensions to perform the transform on. Default is to perform on + all axes. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`. + A complex tensor. + fft_length: A `Tensor` of type `int32`. + An int32 tensor. The FFT length for each dimension. + axes: A `Tensor` of type `int32`. + An int32 tensor with a same shape as fft_length. Axes to perform the transform. + Tcomplex: An optional `tf.DType` from: `tf.complex64, tf.complex128`. Defaults to `tf.complex64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tcomplex`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RFFTND", name, input, fft_length, axes, "Tcomplex", Tcomplex) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_rfftnd( + (input, fft_length, axes, Tcomplex, name,), None) + if _result is not NotImplemented: + return _result + return rfftnd_eager_fallback( + input, fft_length, axes, Tcomplex=Tcomplex, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rfftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + Tcomplex=Tcomplex, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_rfftnd( + (input, fft_length, axes, Tcomplex, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RFFTND", input=input, fft_length=fft_length, axes=axes, + Tcomplex=Tcomplex, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + rfftnd, (), dict(input=input, fft_length=fft_length, axes=axes, + Tcomplex=Tcomplex, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Treal", _op._get_attr_type("Treal"), "Tcomplex", + _op._get_attr_type("Tcomplex")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RFFTND = tf_export("raw_ops.RFFTND")(_ops.to_raw_op(rfftnd)) +_dispatcher_for_rfftnd = rfftnd._tf_type_based_dispatcher.Dispatch + + +def rfftnd_eager_fallback(input: Annotated[Any, TV_RFFTND_Treal], fft_length: Annotated[Any, _atypes.Int32], axes: Annotated[Any, _atypes.Int32], Tcomplex: TV_RFFTND_Tcomplex, name, ctx) -> Annotated[Any, TV_RFFTND_Tcomplex]: + if Tcomplex is None: + Tcomplex = _dtypes.complex64 + Tcomplex = _execute.make_type(Tcomplex, "Tcomplex") + _attr_Treal, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + axes = _ops.convert_to_tensor(axes, _dtypes.int32) + _inputs_flat = [input, fft_length, axes] + _attrs = ("Treal", _attr_Treal, "Tcomplex", Tcomplex) + _result = _execute.execute(b"RFFTND", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RFFTND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_state_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_state_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3669ef93c6ef6c83930688e9a27aafe860ba3420 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_state_ops.py @@ -0,0 +1,1842 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_Assign_T = TypeVar("TV_Assign_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def assign(ref: Annotated[Any, TV_Assign_T], value: Annotated[Any, TV_Assign_T], validate_shape:bool=True, use_locking:bool=True, name=None) -> Annotated[Any, TV_Assign_T]: + r"""Update 'ref' by assigning 'value' to it. + + This operation outputs "ref" after the assignment is done. + This makes it easier to chain operations that need to use the reset value. + + Args: + ref: A mutable `Tensor`. + Should be from a `Variable` node. May be uninitialized. + value: A `Tensor`. Must have the same type as `ref`. + The value to be assigned to the variable. + validate_shape: An optional `bool`. Defaults to `True`. + If true, the operation will validate that the shape + of 'value' matches the shape of the Tensor being assigned to. If false, + 'ref' will take on the shape of 'value'. + use_locking: An optional `bool`. Defaults to `True`. + If True, the assignment will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("assign op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if validate_shape is None: + validate_shape = True + validate_shape = _execute.make_bool(validate_shape, "validate_shape") + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Assign", ref=ref, value=value, validate_shape=validate_shape, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "validate_shape", + _op._get_attr_bool("validate_shape"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Assign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Assign = tf_export("raw_ops.Assign")(_ops.to_raw_op(assign)) + + +def assign_eager_fallback(ref: Annotated[Any, TV_Assign_T], value: Annotated[Any, TV_Assign_T], validate_shape: bool, use_locking: bool, name, ctx) -> Annotated[Any, TV_Assign_T]: + raise RuntimeError("assign op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_AssignAdd_T = TypeVar("TV_AssignAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def assign_add(ref: Annotated[Any, TV_AssignAdd_T], value: Annotated[Any, TV_AssignAdd_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_AssignAdd_T]: + r"""Update 'ref' by adding 'value' to it. + + This operation outputs "ref" after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + value: A `Tensor`. Must have the same type as `ref`. + The value to be added to the variable. + use_locking: An optional `bool`. Defaults to `False`. + If True, the addition will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("assign_add op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssignAdd", ref=ref, value=value, use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AssignAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AssignAdd = tf_export("raw_ops.AssignAdd")(_ops.to_raw_op(assign_add)) + + +def assign_add_eager_fallback(ref: Annotated[Any, TV_AssignAdd_T], value: Annotated[Any, TV_AssignAdd_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_AssignAdd_T]: + raise RuntimeError("assign_add op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_AssignSub_T = TypeVar("TV_AssignSub_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def assign_sub(ref: Annotated[Any, TV_AssignSub_T], value: Annotated[Any, TV_AssignSub_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_AssignSub_T]: + r"""Update 'ref' by subtracting 'value' from it. + + This operation outputs "ref" after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + value: A `Tensor`. Must have the same type as `ref`. + The value to be subtracted to the variable. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("assign_sub op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AssignSub", ref=ref, value=value, use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AssignSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AssignSub = tf_export("raw_ops.AssignSub")(_ops.to_raw_op(assign_sub)) + + +def assign_sub_eager_fallback(ref: Annotated[Any, TV_AssignSub_T], value: Annotated[Any, TV_AssignSub_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_AssignSub_T]: + raise RuntimeError("assign_sub op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_CountUpTo_T = TypeVar("TV_CountUpTo_T", _atypes.Int32, _atypes.Int64) + +def count_up_to(ref: Annotated[Any, TV_CountUpTo_T], limit: int, name=None) -> Annotated[Any, TV_CountUpTo_T]: + r"""Increments 'ref' until it reaches 'limit'. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `int32`, `int64`. + Should be from a scalar `Variable` node. + limit: An `int`. + If incrementing ref would bring it above limit, instead generates an + 'OutOfRange' error. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("count_up_to op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + limit = _execute.make_int(limit, "limit") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CountUpTo", ref=ref, limit=limit, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("limit", _op._get_attr_int("limit"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CountUpTo", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CountUpTo = tf_export("raw_ops.CountUpTo")(_ops.to_raw_op(count_up_to)) + + +def count_up_to_eager_fallback(ref: Annotated[Any, TV_CountUpTo_T], limit: int, name, ctx) -> Annotated[Any, TV_CountUpTo_T]: + raise RuntimeError("count_up_to op does not support eager execution. Arg 'ref' is a ref.") + +TV_DestroyTemporaryVariable_T = TypeVar("TV_DestroyTemporaryVariable_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def destroy_temporary_variable(ref: Annotated[Any, TV_DestroyTemporaryVariable_T], var_name: str, name=None) -> Annotated[Any, TV_DestroyTemporaryVariable_T]: + r"""Destroys the temporary variable and returns its final value. + + Sets output to the value of the Tensor pointed to by 'ref', then destroys + the temporary variable called 'var_name'. + All other uses of 'ref' *must* have executed before this op. + This is typically achieved by chaining the ref through each assign op, or by + using control dependencies. + + Outputs the final value of the tensor pointed to by 'ref'. + + Args: + ref: A mutable `Tensor`. A reference to the temporary variable tensor. + var_name: A `string`. + Name of the temporary variable, usually the name of the matching + 'TemporaryVariable' op. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("destroy_temporary_variable op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + var_name = _execute.make_str(var_name, "var_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DestroyTemporaryVariable", ref=ref, var_name=var_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "var_name", + _op.get_attr("var_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DestroyTemporaryVariable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DestroyTemporaryVariable = tf_export("raw_ops.DestroyTemporaryVariable")(_ops.to_raw_op(destroy_temporary_variable)) + + +def destroy_temporary_variable_eager_fallback(ref: Annotated[Any, TV_DestroyTemporaryVariable_T], var_name: str, name, ctx) -> Annotated[Any, TV_DestroyTemporaryVariable_T]: + raise RuntimeError("destroy_temporary_variable op does not support eager execution. Arg 'ref' is a ref.") + +TV_IsVariableInitialized_dtype = TypeVar("TV_IsVariableInitialized_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def is_variable_initialized(ref: Annotated[Any, TV_IsVariableInitialized_dtype], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Checks whether a tensor has been initialized. + + Outputs boolean scalar indicating whether the tensor has been initialized. + + Args: + ref: A mutable `Tensor`. + Should be from a `Variable` node. May be uninitialized. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("is_variable_initialized op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsVariableInitialized", ref=ref, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsVariableInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsVariableInitialized = tf_export("raw_ops.IsVariableInitialized")(_ops.to_raw_op(is_variable_initialized)) + + +def is_variable_initialized_eager_fallback(ref: Annotated[Any, TV_IsVariableInitialized_dtype], name, ctx) -> Annotated[Any, _atypes.Bool]: + raise RuntimeError("is_variable_initialized op does not support eager execution. Arg 'ref' is a ref.") + +TV_ResourceCountUpTo_T = TypeVar("TV_ResourceCountUpTo_T", _atypes.Int32, _atypes.Int64) + +def resource_count_up_to(resource: Annotated[Any, _atypes.Resource], limit: int, T: TV_ResourceCountUpTo_T, name=None) -> Annotated[Any, TV_ResourceCountUpTo_T]: + r"""Increments variable pointed to by 'resource' until it reaches 'limit'. + + Args: + resource: A `Tensor` of type `resource`. + Should be from a scalar `Variable` node. + limit: An `int`. + If incrementing ref would bring it above limit, instead generates an + 'OutOfRange' error. + T: A `tf.DType` from: `tf.int32, tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceCountUpTo", name, resource, "limit", limit, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_count_up_to_eager_fallback( + resource, limit=limit, T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + limit = _execute.make_int(limit, "limit") + T = _execute.make_type(T, "T") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceCountUpTo", resource=resource, limit=limit, T=T, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("limit", _op._get_attr_int("limit"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceCountUpTo", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceCountUpTo = tf_export("raw_ops.ResourceCountUpTo")(_ops.to_raw_op(resource_count_up_to)) + + +def resource_count_up_to_eager_fallback(resource: Annotated[Any, _atypes.Resource], limit: int, T: TV_ResourceCountUpTo_T, name, ctx) -> Annotated[Any, TV_ResourceCountUpTo_T]: + limit = _execute.make_int(limit, "limit") + T = _execute.make_type(T, "T") + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = ("limit", limit, "T", T) + _result = _execute.execute(b"ResourceCountUpTo", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceCountUpTo", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ResourceScatterNdAdd_T = TypeVar("TV_ResourceScatterNdAdd_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterNdAdd_Tindices = TypeVar("TV_ResourceScatterNdAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_nd_add(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdAdd_Tindices], updates: Annotated[Any, TV_ResourceScatterNdAdd_T], use_locking:bool=True, name=None): + r"""Applies sparse addition to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that addition would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + add = tf.scatter_nd_add(ref, indices, updates) + with tf.Session() as sess: + print sess.run(add) + ``` + + The resulting update to ref would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A `Tensor` of type `resource`. + A resource handle. Must be from a VarHandleOp. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. A Tensor. Must have the same type as ref. A tensor of + values to add to ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterNdAdd", name, ref, indices, updates, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_nd_add_eager_fallback( + ref, indices, updates, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterNdAdd", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + return _op +ResourceScatterNdAdd = tf_export("raw_ops.ResourceScatterNdAdd")(_ops.to_raw_op(resource_scatter_nd_add)) + + +def resource_scatter_nd_add_eager_fallback(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdAdd_Tindices], updates: Annotated[Any, TV_ResourceScatterNdAdd_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceScatterNdAdd", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterNdMax_T = TypeVar("TV_ResourceScatterNdMax_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterNdMax_Tindices = TypeVar("TV_ResourceScatterNdMax_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_nd_max(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdMax_Tindices], updates: Annotated[Any, TV_ResourceScatterNdMax_T], use_locking:bool=True, name=None): + r"""TODO: add doc. + + Args: + ref: A `Tensor` of type `resource`. + A resource handle. Must be from a VarHandleOp. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. A Tensor. Must have the same type as ref. A tensor of + values whose element wise max is taken with ref + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterNdMax", name, ref, indices, updates, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_nd_max_eager_fallback( + ref, indices, updates, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterNdMax", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + return _op +ResourceScatterNdMax = tf_export("raw_ops.ResourceScatterNdMax")(_ops.to_raw_op(resource_scatter_nd_max)) + + +def resource_scatter_nd_max_eager_fallback(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdMax_Tindices], updates: Annotated[Any, TV_ResourceScatterNdMax_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceScatterNdMax", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterNdMin_T = TypeVar("TV_ResourceScatterNdMin_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterNdMin_Tindices = TypeVar("TV_ResourceScatterNdMin_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_nd_min(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdMin_Tindices], updates: Annotated[Any, TV_ResourceScatterNdMin_T], use_locking:bool=True, name=None): + r"""TODO: add doc. + + Args: + ref: A `Tensor` of type `resource`. + A resource handle. Must be from a VarHandleOp. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. A Tensor. Must have the same type as ref. A tensor of + values whose element wise min is taken with ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterNdMin", name, ref, indices, updates, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_nd_min_eager_fallback( + ref, indices, updates, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterNdMin", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + return _op +ResourceScatterNdMin = tf_export("raw_ops.ResourceScatterNdMin")(_ops.to_raw_op(resource_scatter_nd_min)) + + +def resource_scatter_nd_min_eager_fallback(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdMin_Tindices], updates: Annotated[Any, TV_ResourceScatterNdMin_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceScatterNdMin", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterNdSub_T = TypeVar("TV_ResourceScatterNdSub_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterNdSub_Tindices = TypeVar("TV_ResourceScatterNdSub_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_nd_sub(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdSub_Tindices], updates: Annotated[Any, TV_ResourceScatterNdSub_T], use_locking:bool=True, name=None): + r"""Applies sparse subtraction to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to subtract 4 scattered elements from a rank-1 tensor + with 8 elements. In Python, that subtraction would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8], use_resource=True) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + sub = tf.scatter_nd_sub(ref, indices, updates) + with tf.Session() as sess: + print sess.run(sub) + ``` + + The resulting update to ref would look like this: + + [1, -9, 3, -6, -4, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A `Tensor` of type `resource`. + A resource handle. Must be from a VarHandleOp. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. A Tensor. Must have the same type as ref. A tensor of + values to add to ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterNdSub", name, ref, indices, updates, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_nd_sub_eager_fallback( + ref, indices, updates, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterNdSub", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + return _op +ResourceScatterNdSub = tf_export("raw_ops.ResourceScatterNdSub")(_ops.to_raw_op(resource_scatter_nd_sub)) + + +def resource_scatter_nd_sub_eager_fallback(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdSub_Tindices], updates: Annotated[Any, TV_ResourceScatterNdSub_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceScatterNdSub", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceScatterNdUpdate_T = TypeVar("TV_ResourceScatterNdUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ResourceScatterNdUpdate_Tindices = TypeVar("TV_ResourceScatterNdUpdate_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_scatter_nd_update(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdUpdate_Tindices], updates: Annotated[Any, TV_ResourceScatterNdUpdate_T], use_locking:bool=True, name=None): + r"""Applies sparse `updates` to individual values or slices within a given + + variable according to `indices`. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to update 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + update = tf.scatter_nd_update(ref, indices, updates) + with tf.Session() as sess: + print sess.run(update) + ``` + + The resulting update to ref would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A `Tensor` of type `resource`. + A resource handle. Must be from a VarHandleOp. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. + A Tensor. Must have the same type as ref. A tensor of updated + values to add to ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceScatterNdUpdate", name, ref, indices, updates, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_scatter_nd_update_eager_fallback( + ref, indices, updates, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceScatterNdUpdate", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + return _op +ResourceScatterNdUpdate = tf_export("raw_ops.ResourceScatterNdUpdate")(_ops.to_raw_op(resource_scatter_nd_update)) + + +def resource_scatter_nd_update_eager_fallback(ref: Annotated[Any, _atypes.Resource], indices: Annotated[Any, TV_ResourceScatterNdUpdate_Tindices], updates: Annotated[Any, TV_ResourceScatterNdUpdate_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, (updates,) = _execute.args_to_matching_eager([updates], ctx, []) + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + ref = _ops.convert_to_tensor(ref, _dtypes.resource) + _inputs_flat = [ref, indices, updates] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceScatterNdUpdate", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ScatterAdd_T = TypeVar("TV_ScatterAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterAdd_Tindices = TypeVar("TV_ScatterAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_add(ref: Annotated[Any, TV_ScatterAdd_T], indices: Annotated[Any, TV_ScatterAdd_Tindices], updates: Annotated[Any, TV_ScatterAdd_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterAdd_T]: + r"""Adds sparse updates to a variable reference. + + This operation computes + + # Scalar indices + ref[indices, ...] += updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] += updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] += updates[i, ..., j, ...] + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to add to `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the addition will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_add op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterAdd", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterAdd = tf_export("raw_ops.ScatterAdd")(_ops.to_raw_op(scatter_add)) + + +def scatter_add_eager_fallback(ref: Annotated[Any, TV_ScatterAdd_T], indices: Annotated[Any, TV_ScatterAdd_Tindices], updates: Annotated[Any, TV_ScatterAdd_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterAdd_T]: + raise RuntimeError("scatter_add op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterDiv_T = TypeVar("TV_ScatterDiv_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterDiv_Tindices = TypeVar("TV_ScatterDiv_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_div(ref: Annotated[Any, TV_ScatterDiv_T], indices: Annotated[Any, TV_ScatterDiv_Tindices], updates: Annotated[Any, TV_ScatterDiv_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterDiv_T]: + r"""Divides a variable reference by sparse updates. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] /= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] /= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions divide. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of values that `ref` is divided by. + use_locking: An optional `bool`. Defaults to `False`. + If True, the operation will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_div op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterDiv", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterDiv", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterDiv = tf_export("raw_ops.ScatterDiv")(_ops.to_raw_op(scatter_div)) + + +def scatter_div_eager_fallback(ref: Annotated[Any, TV_ScatterDiv_T], indices: Annotated[Any, TV_ScatterDiv_Tindices], updates: Annotated[Any, TV_ScatterDiv_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterDiv_T]: + raise RuntimeError("scatter_div op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterMax_T = TypeVar("TV_ScatterMax_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_ScatterMax_Tindices = TypeVar("TV_ScatterMax_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_max(ref: Annotated[Any, TV_ScatterMax_T], indices: Annotated[Any, TV_ScatterMax_Tindices], updates: Annotated[Any, TV_ScatterMax_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterMax_T]: + r"""Reduces sparse updates into a variable reference using the `max` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = max(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions combine. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`, `int64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to reduce into `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the update will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_max op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterMax", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterMax = tf_export("raw_ops.ScatterMax")(_ops.to_raw_op(scatter_max)) + + +def scatter_max_eager_fallback(ref: Annotated[Any, TV_ScatterMax_T], indices: Annotated[Any, TV_ScatterMax_Tindices], updates: Annotated[Any, TV_ScatterMax_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterMax_T]: + raise RuntimeError("scatter_max op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterMin_T = TypeVar("TV_ScatterMin_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_ScatterMin_Tindices = TypeVar("TV_ScatterMin_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_min(ref: Annotated[Any, TV_ScatterMin_T], indices: Annotated[Any, TV_ScatterMin_Tindices], updates: Annotated[Any, TV_ScatterMin_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterMin_T]: + r"""Reduces sparse updates into a variable reference using the `min` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = min(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], updates[i, ..., j, ...]) + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions combine. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`, `int64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to reduce into `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the update will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_min op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterMin", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterMin = tf_export("raw_ops.ScatterMin")(_ops.to_raw_op(scatter_min)) + + +def scatter_min_eager_fallback(ref: Annotated[Any, TV_ScatterMin_T], indices: Annotated[Any, TV_ScatterMin_Tindices], updates: Annotated[Any, TV_ScatterMin_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterMin_T]: + raise RuntimeError("scatter_min op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterMul_T = TypeVar("TV_ScatterMul_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterMul_Tindices = TypeVar("TV_ScatterMul_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_mul(ref: Annotated[Any, TV_ScatterMul_T], indices: Annotated[Any, TV_ScatterMul_Tindices], updates: Annotated[Any, TV_ScatterMul_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterMul_T]: + r"""Multiplies sparse updates into a variable reference. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] *= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] *= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions multiply. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to multiply to `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the operation will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_mul op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterMul", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterMul = tf_export("raw_ops.ScatterMul")(_ops.to_raw_op(scatter_mul)) + + +def scatter_mul_eager_fallback(ref: Annotated[Any, TV_ScatterMul_T], indices: Annotated[Any, TV_ScatterMul_Tindices], updates: Annotated[Any, TV_ScatterMul_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterMul_T]: + raise RuntimeError("scatter_mul op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterNdAdd_T = TypeVar("TV_ScatterNdAdd_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterNdAdd_Tindices = TypeVar("TV_ScatterNdAdd_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_add(ref: Annotated[Any, TV_ScatterNdAdd_T], indices: Annotated[Any, TV_ScatterNdAdd_Tindices], updates: Annotated[Any, TV_ScatterNdAdd_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterNdAdd_T]: + r"""Applies sparse addition to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that addition would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + add = tf.scatter_nd_add(ref, indices, updates) + with tf.Session() as sess: + print sess.run(add) + ``` + + The resulting update to ref would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated values + to add to ref. + use_locking: An optional `bool`. Defaults to `False`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_nd_add op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdAdd", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdAdd = tf_export("raw_ops.ScatterNdAdd")(_ops.to_raw_op(scatter_nd_add)) + + +def scatter_nd_add_eager_fallback(ref: Annotated[Any, TV_ScatterNdAdd_T], indices: Annotated[Any, TV_ScatterNdAdd_Tindices], updates: Annotated[Any, TV_ScatterNdAdd_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterNdAdd_T]: + raise RuntimeError("scatter_nd_add op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterNdMax_T = TypeVar("TV_ScatterNdMax_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterNdMax_Tindices = TypeVar("TV_ScatterNdMax_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_max(ref: Annotated[Any, TV_ScatterNdMax_T], indices: Annotated[Any, TV_ScatterNdMax_Tindices], updates: Annotated[Any, TV_ScatterNdMax_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterNdMax_T]: + r"""Computes element-wise maximum. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated values + to add to ref. + use_locking: An optional `bool`. Defaults to `False`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_nd_max op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdMax", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdMax = tf_export("raw_ops.ScatterNdMax")(_ops.to_raw_op(scatter_nd_max)) + + +def scatter_nd_max_eager_fallback(ref: Annotated[Any, TV_ScatterNdMax_T], indices: Annotated[Any, TV_ScatterNdMax_Tindices], updates: Annotated[Any, TV_ScatterNdMax_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterNdMax_T]: + raise RuntimeError("scatter_nd_max op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterNdMin_T = TypeVar("TV_ScatterNdMin_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterNdMin_Tindices = TypeVar("TV_ScatterNdMin_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_min(ref: Annotated[Any, TV_ScatterNdMin_T], indices: Annotated[Any, TV_ScatterNdMin_Tindices], updates: Annotated[Any, TV_ScatterNdMin_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterNdMin_T]: + r"""Computes element-wise minimum. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated values + to add to ref. + use_locking: An optional `bool`. Defaults to `False`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_nd_min op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdMin", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdMin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdMin = tf_export("raw_ops.ScatterNdMin")(_ops.to_raw_op(scatter_nd_min)) + + +def scatter_nd_min_eager_fallback(ref: Annotated[Any, TV_ScatterNdMin_T], indices: Annotated[Any, TV_ScatterNdMin_Tindices], updates: Annotated[Any, TV_ScatterNdMin_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterNdMin_T]: + raise RuntimeError("scatter_nd_min op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterNdSub_T = TypeVar("TV_ScatterNdSub_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterNdSub_Tindices = TypeVar("TV_ScatterNdSub_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_sub(ref: Annotated[Any, TV_ScatterNdSub_T], indices: Annotated[Any, TV_ScatterNdSub_Tindices], updates: Annotated[Any, TV_ScatterNdSub_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterNdSub_T]: + r"""Applies sparse subtraction to individual values or slices in a Variable. + + within a given variable according to `indices`. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to subtract 4 scattered elements from a rank-1 tensor + with 8 elements. In Python, that subtraction would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + sub = tf.scatter_nd_sub(ref, indices, updates) + with tf.Session() as sess: + print sess.run(sub) + ``` + + The resulting update to ref would look like this: + + [1, -9, 3, -6, -4, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated values + to subtract from ref. + use_locking: An optional `bool`. Defaults to `False`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_nd_sub op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdSub", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdSub = tf_export("raw_ops.ScatterNdSub")(_ops.to_raw_op(scatter_nd_sub)) + + +def scatter_nd_sub_eager_fallback(ref: Annotated[Any, TV_ScatterNdSub_T], indices: Annotated[Any, TV_ScatterNdSub_Tindices], updates: Annotated[Any, TV_ScatterNdSub_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterNdSub_T]: + raise RuntimeError("scatter_nd_sub op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterNdUpdate_T = TypeVar("TV_ScatterNdUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ScatterNdUpdate_Tindices = TypeVar("TV_ScatterNdUpdate_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_nd_update(ref: Annotated[Any, TV_ScatterNdUpdate_T], indices: Annotated[Any, TV_ScatterNdUpdate_Tindices], updates: Annotated[Any, TV_ScatterNdUpdate_T], use_locking:bool=True, name=None) -> Annotated[Any, TV_ScatterNdUpdate_T]: + r"""Applies sparse `updates` to individual values or slices within a given + + variable according to `indices`. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape \\([d_0, ..., d_{Q-2}, K]\\) where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + $$[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].$$ + + For example, say we want to update 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + update = tf.scatter_nd_update(ref, indices, updates) + with tf.Session() as sess: + print sess.run(update) + ``` + + The resulting update to ref would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + See also `tf.scatter_update` and `tf.batch_scatter_update`. + + Args: + ref: A mutable `Tensor`. A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A Tensor. Must be one of the following types: int32, int64. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated + values to add to ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_nd_update op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterNdUpdate", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterNdUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterNdUpdate = tf_export("raw_ops.ScatterNdUpdate")(_ops.to_raw_op(scatter_nd_update)) + + +def scatter_nd_update_eager_fallback(ref: Annotated[Any, TV_ScatterNdUpdate_T], indices: Annotated[Any, TV_ScatterNdUpdate_Tindices], updates: Annotated[Any, TV_ScatterNdUpdate_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterNdUpdate_T]: + raise RuntimeError("scatter_nd_update op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterSub_T = TypeVar("TV_ScatterSub_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ScatterSub_Tindices = TypeVar("TV_ScatterSub_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_sub(ref: Annotated[Any, TV_ScatterSub_T], indices: Annotated[Any, TV_ScatterSub_Tindices], updates: Annotated[Any, TV_ScatterSub_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ScatterSub_T]: + r"""Subtracts sparse updates to a variable reference. + + ```python + # Scalar indices + ref[indices, ...] -= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] -= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their (negated) contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to subtract from `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_sub op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterSub", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterSub", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterSub = tf_export("raw_ops.ScatterSub")(_ops.to_raw_op(scatter_sub)) + + +def scatter_sub_eager_fallback(ref: Annotated[Any, TV_ScatterSub_T], indices: Annotated[Any, TV_ScatterSub_Tindices], updates: Annotated[Any, TV_ScatterSub_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterSub_T]: + raise RuntimeError("scatter_sub op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_ScatterUpdate_T = TypeVar("TV_ScatterUpdate_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_ScatterUpdate_Tindices = TypeVar("TV_ScatterUpdate_Tindices", _atypes.Int32, _atypes.Int64) + +def scatter_update(ref: Annotated[Any, TV_ScatterUpdate_T], indices: Annotated[Any, TV_ScatterUpdate_Tindices], updates: Annotated[Any, TV_ScatterUpdate_T], use_locking:bool=True, name=None) -> Annotated[Any, TV_ScatterUpdate_T]: + r"""Applies sparse updates to a variable reference. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] = updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] = updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + If values in `ref` is to be updated more than once, because there are + duplicate entries in `indices`, the order at which the updates happen + for each value is undefined. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`. + +
+ +
+ + See also `tf.batch_scatter_update` and `tf.scatter_nd_update`. + + Args: + ref: A mutable `Tensor`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to store in `ref`. + use_locking: An optional `bool`. Defaults to `True`. + If True, the assignment will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("scatter_update op does not support eager execution. Arg 'output_ref' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = True + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ScatterUpdate", ref=ref, indices=indices, updates=updates, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ScatterUpdate", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ScatterUpdate = tf_export("raw_ops.ScatterUpdate")(_ops.to_raw_op(scatter_update)) + + +def scatter_update_eager_fallback(ref: Annotated[Any, TV_ScatterUpdate_T], indices: Annotated[Any, TV_ScatterUpdate_Tindices], updates: Annotated[Any, TV_ScatterUpdate_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ScatterUpdate_T]: + raise RuntimeError("scatter_update op does not support eager execution. Arg 'output_ref' is a ref.") + +TV_TemporaryVariable_dtype = TypeVar("TV_TemporaryVariable_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def temporary_variable(shape, dtype: TV_TemporaryVariable_dtype, var_name:str="", name=None) -> Annotated[Any, TV_TemporaryVariable_dtype]: + r"""Returns a tensor that may be mutated, but only persists within a single step. + + This is an experimental op for internal use only and it is possible to use this + op in unsafe ways. DO NOT USE unless you fully understand the risks. + + It is the caller's responsibility to ensure that 'ref' is eventually passed to a + matching 'DestroyTemporaryVariable' op after all other uses have completed. + + Outputs a ref to the tensor state so it may be read or modified. + + E.g. + var = state_ops._temporary_variable([1, 2], types.float_) + var_name = var.op.name + var = state_ops.assign(var, [[4.0, 5.0]]) + var = state_ops.assign_add(var, [[6.0, 7.0]]) + final = state_ops._destroy_temporary_variable(var, var_name=var_name) + + Args: + shape: A `tf.TensorShape` or list of `ints`. + The shape of the variable tensor. + dtype: A `tf.DType`. The type of elements in the variable tensor. + var_name: An optional `string`. Defaults to `""`. + Overrides the name used for the temporary variable resource. Default + value is the name of the 'TemporaryVariable' op (which is guaranteed unique). + name: A name for the operation (optional). + + Returns: + A mutable `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("temporary_variable op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + dtype = _execute.make_type(dtype, "dtype") + if var_name is None: + var_name = "" + var_name = _execute.make_str(var_name, "var_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TemporaryVariable", shape=shape, dtype=dtype, var_name=var_name, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shape", _op.get_attr("shape"), "dtype", + _op._get_attr_type("dtype"), "var_name", + _op.get_attr("var_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TemporaryVariable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TemporaryVariable = tf_export("raw_ops.TemporaryVariable")(_ops.to_raw_op(temporary_variable)) + + +def temporary_variable_eager_fallback(shape, dtype: TV_TemporaryVariable_dtype, var_name: str, name, ctx) -> Annotated[Any, TV_TemporaryVariable_dtype]: + raise RuntimeError("temporary_variable op does not support eager execution. Arg 'ref' is a ref.") + +TV_Variable_dtype = TypeVar("TV_Variable_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def variable(shape, dtype: TV_Variable_dtype, container:str="", shared_name:str="", name=None) -> Annotated[Any, TV_Variable_dtype]: + r"""Use VariableV2 instead. + + Args: + shape: A `tf.TensorShape` or list of `ints`. + dtype: A `tf.DType`. + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("variable op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + dtype = _execute.make_type(dtype, "dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Variable", shape=shape, dtype=dtype, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shape", _op.get_attr("shape"), "dtype", + _op._get_attr_type("dtype"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Variable", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Variable = tf_export("raw_ops.Variable")(_ops.to_raw_op(variable)) + + +def variable_eager_fallback(shape, dtype: TV_Variable_dtype, container: str, shared_name: str, name, ctx) -> Annotated[Any, TV_Variable_dtype]: + raise RuntimeError("variable op does not support eager execution. Arg 'ref' is a ref.") + +TV_VariableV2_dtype = TypeVar("TV_VariableV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def variable_v2(shape, dtype: TV_VariableV2_dtype, container:str="", shared_name:str="", name=None) -> Annotated[Any, TV_VariableV2_dtype]: + r"""Holds state in the form of a tensor that persists across steps. + + Outputs a ref to the tensor state so it may be read or modified. + TODO(zhifengc/mrry): Adds a pointer to a more detail document + about sharing states in tensorflow. + + Args: + shape: A `tf.TensorShape` or list of `ints`. + The shape of the variable tensor. + dtype: A `tf.DType`. The type of elements in the variable tensor. + container: An optional `string`. Defaults to `""`. + If non-empty, this variable is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional `string`. Defaults to `""`. + If non-empty, this variable is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("variable_v2 op does not support eager execution. Arg 'ref' is a ref.") + # Add nodes to the TensorFlow graph. + shape = _execute.make_shape(shape, "shape") + dtype = _execute.make_type(dtype, "dtype") + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "VariableV2", shape=shape, dtype=dtype, container=container, + shared_name=shared_name, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shape", _op.get_attr("shape"), "dtype", + _op._get_attr_type("dtype"), "container", + _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "VariableV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +VariableV2 = tf_export("raw_ops.VariableV2")(_ops.to_raw_op(variable_v2)) + + +def variable_v2_eager_fallback(shape, dtype: TV_VariableV2_dtype, container: str, shared_name: str, name, ctx) -> Annotated[Any, TV_VariableV2_dtype]: + raise RuntimeError("variable_v2 op does not support eager execution. Arg 'ref' is a ref.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateful_random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateful_random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ef5549c2d4d86ab4421fda56ee52bf3833de32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateful_random_ops.py @@ -0,0 +1,748 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_NonDeterministicInts_dtype = TypeVar("TV_NonDeterministicInts_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_NonDeterministicInts_shape_dtype = TypeVar("TV_NonDeterministicInts_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def non_deterministic_ints(shape: Annotated[Any, TV_NonDeterministicInts_shape_dtype], dtype:TV_NonDeterministicInts_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_NonDeterministicInts_dtype]: + r"""Non-deterministically generates some integers. + + This op may use some OS-provided source of non-determinism (e.g. an RNG), so each execution will give different results. + + Args: + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.int64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NonDeterministicInts", name, shape, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return non_deterministic_ints_eager_fallback( + shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NonDeterministicInts", shape=shape, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NonDeterministicInts", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +NonDeterministicInts = tf_export("raw_ops.NonDeterministicInts")(_ops.to_raw_op(non_deterministic_ints)) + + +def non_deterministic_ints_eager_fallback(shape: Annotated[Any, TV_NonDeterministicInts_shape_dtype], dtype: TV_NonDeterministicInts_dtype, name, ctx) -> Annotated[Any, TV_NonDeterministicInts_dtype]: + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + _inputs_flat = [shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"NonDeterministicInts", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NonDeterministicInts", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def rng_read_and_skip(resource: Annotated[Any, _atypes.Resource], alg: Annotated[Any, _atypes.Int32], delta: Annotated[Any, _atypes.UInt64], name=None) -> Annotated[Any, _atypes.Int64]: + r"""Advance the counter of a counter-based RNG. + + The state of the RNG after + `rng_read_and_skip(n)` will be the same as that after `uniform([n])` + (or any other distribution). The actual increment added to the + counter is an unspecified implementation choice. + + In the case that the input algorithm is RNG_ALG_AUTO_SELECT, the counter in the state needs to be of size int64[2], the current maximal counter size among algorithms. In this case, this op will manage the counter as if it is an 128-bit integer with layout [lower_64bits, higher_64bits]. If an algorithm needs less than 128 bits for the counter, it should use the left portion of the int64[2]. In this way, the int64[2] is compatible with all current RNG algorithms (Philox, ThreeFry and xla::RandomAlgorithm::RNG_DEFAULT). Downstream RNG ops can thus use this counter with any RNG algorithm. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. The state consists of the counter followed by the key. + alg: A `Tensor` of type `int32`. The RNG algorithm. + delta: A `Tensor` of type `uint64`. The amount of advancement. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RngReadAndSkip", name, resource, alg, delta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rng_read_and_skip_eager_fallback( + resource, alg, delta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RngReadAndSkip", resource=resource, alg=alg, delta=delta, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RngReadAndSkip", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RngReadAndSkip = tf_export("raw_ops.RngReadAndSkip")(_ops.to_raw_op(rng_read_and_skip)) + + +def rng_read_and_skip_eager_fallback(resource: Annotated[Any, _atypes.Resource], alg: Annotated[Any, _atypes.Int32], delta: Annotated[Any, _atypes.UInt64], name, ctx) -> Annotated[Any, _atypes.Int64]: + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + delta = _ops.convert_to_tensor(delta, _dtypes.uint64) + _inputs_flat = [resource, alg, delta] + _attrs = None + _result = _execute.execute(b"RngReadAndSkip", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RngReadAndSkip", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def rng_skip(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], delta: Annotated[Any, _atypes.Int64], name=None): + r"""Advance the counter of a counter-based RNG. + + The state of the RNG after + `rng_skip(n)` will be the same as that after `stateful_uniform([n])` + (or any other distribution). The actual increment added to the + counter is an unspecified implementation detail. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + delta: A `Tensor` of type `int64`. The amount of advancement. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RngSkip", name, resource, algorithm, delta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return rng_skip_eager_fallback( + resource, algorithm, delta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RngSkip", resource=resource, algorithm=algorithm, delta=delta, + name=name) + return _op +RngSkip = tf_export("raw_ops.RngSkip")(_ops.to_raw_op(rng_skip)) + + +def rng_skip_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], delta: Annotated[Any, _atypes.Int64], name, ctx): + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + delta = _ops.convert_to_tensor(delta, _dtypes.int64) + _inputs_flat = [resource, algorithm, delta] + _attrs = None + _result = _execute.execute(b"RngSkip", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +TV_StatefulRandomBinomial_S = TypeVar("TV_StatefulRandomBinomial_S", _atypes.Int32, _atypes.Int64) +TV_StatefulRandomBinomial_T = TypeVar("TV_StatefulRandomBinomial_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_StatefulRandomBinomial_dtype = TypeVar("TV_StatefulRandomBinomial_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def stateful_random_binomial(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulRandomBinomial_S], counts: Annotated[Any, TV_StatefulRandomBinomial_T], probs: Annotated[Any, TV_StatefulRandomBinomial_T], dtype:TV_StatefulRandomBinomial_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_StatefulRandomBinomial_dtype]: + r"""TODO: add doc. + + Args: + resource: A `Tensor` of type `resource`. + algorithm: A `Tensor` of type `int64`. + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + counts: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + probs: A `Tensor`. Must have the same type as `counts`. + dtype: An optional `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulRandomBinomial", name, resource, algorithm, shape, + counts, probs, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_random_binomial_eager_fallback( + resource, algorithm, shape, counts, probs, dtype=dtype, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulRandomBinomial", resource=resource, algorithm=algorithm, + shape=shape, counts=counts, probs=probs, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("S", _op._get_attr_type("S"), "T", _op._get_attr_type("T"), + "dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulRandomBinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulRandomBinomial = tf_export("raw_ops.StatefulRandomBinomial")(_ops.to_raw_op(stateful_random_binomial)) + + +def stateful_random_binomial_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulRandomBinomial_S], counts: Annotated[Any, TV_StatefulRandomBinomial_T], probs: Annotated[Any, TV_StatefulRandomBinomial_T], dtype: TV_StatefulRandomBinomial_dtype, name, ctx) -> Annotated[Any, TV_StatefulRandomBinomial_dtype]: + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_T, _inputs_T = _execute.args_to_matching_eager([counts, probs], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ], _dtypes.float64) + (counts, probs) = _inputs_T + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape, counts, probs] + _attrs = ("S", _attr_S, "T", _attr_T, "dtype", dtype) + _result = _execute.execute(b"StatefulRandomBinomial", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulRandomBinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulStandardNormal_dtype = TypeVar("TV_StatefulStandardNormal_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulStandardNormal_shape_dtype = TypeVar("TV_StatefulStandardNormal_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_standard_normal(resource: Annotated[Any, _atypes.Resource], shape: Annotated[Any, TV_StatefulStandardNormal_shape_dtype], dtype:TV_StatefulStandardNormal_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatefulStandardNormal_dtype]: + r"""Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2' + + The generated values will have mean 0 and standard deviation 1. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulStandardNormal", name, resource, shape, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_standard_normal_eager_fallback( + resource, shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulStandardNormal", resource=resource, shape=shape, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulStandardNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulStandardNormal = tf_export("raw_ops.StatefulStandardNormal")(_ops.to_raw_op(stateful_standard_normal)) + + +def stateful_standard_normal_eager_fallback(resource: Annotated[Any, _atypes.Resource], shape: Annotated[Any, TV_StatefulStandardNormal_shape_dtype], dtype: TV_StatefulStandardNormal_dtype, name, ctx) -> Annotated[Any, TV_StatefulStandardNormal_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource, shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulStandardNormal", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulStandardNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulStandardNormalV2_dtype = TypeVar("TV_StatefulStandardNormalV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulStandardNormalV2_shape_dtype = TypeVar("TV_StatefulStandardNormalV2_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_standard_normal_v2(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulStandardNormalV2_shape_dtype], dtype:TV_StatefulStandardNormalV2_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatefulStandardNormalV2_dtype]: + r"""Outputs random values from a normal distribution. + + The generated values will have mean 0 and standard deviation 1. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulStandardNormalV2", name, resource, algorithm, shape, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_standard_normal_v2_eager_fallback( + resource, algorithm, shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulStandardNormalV2", resource=resource, algorithm=algorithm, + shape=shape, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulStandardNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulStandardNormalV2 = tf_export("raw_ops.StatefulStandardNormalV2")(_ops.to_raw_op(stateful_standard_normal_v2)) + + +def stateful_standard_normal_v2_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulStandardNormalV2_shape_dtype], dtype: TV_StatefulStandardNormalV2_dtype, name, ctx) -> Annotated[Any, TV_StatefulStandardNormalV2_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulStandardNormalV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulStandardNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulTruncatedNormal_dtype = TypeVar("TV_StatefulTruncatedNormal_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulTruncatedNormal_shape_dtype = TypeVar("TV_StatefulTruncatedNormal_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_truncated_normal(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulTruncatedNormal_shape_dtype], dtype:TV_StatefulTruncatedNormal_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatefulTruncatedNormal_dtype]: + r"""Outputs random values from a truncated normal distribution. + + The generated values follow a normal distribution with mean 0 and standard + deviation 1, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulTruncatedNormal", name, resource, algorithm, shape, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_truncated_normal_eager_fallback( + resource, algorithm, shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulTruncatedNormal", resource=resource, algorithm=algorithm, + shape=shape, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulTruncatedNormal = tf_export("raw_ops.StatefulTruncatedNormal")(_ops.to_raw_op(stateful_truncated_normal)) + + +def stateful_truncated_normal_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulTruncatedNormal_shape_dtype], dtype: TV_StatefulTruncatedNormal_dtype, name, ctx) -> Annotated[Any, TV_StatefulTruncatedNormal_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulTruncatedNormal", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulUniform_dtype = TypeVar("TV_StatefulUniform_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulUniform_shape_dtype = TypeVar("TV_StatefulUniform_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_uniform(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniform_shape_dtype], dtype:TV_StatefulUniform_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatefulUniform_dtype]: + r"""Outputs random values from a uniform distribution. + + The generated values follow a uniform distribution in the range `[0, 1)`. The + lower bound 0 is included in the range, while the upper bound 1 is excluded. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulUniform", name, resource, algorithm, shape, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_uniform_eager_fallback( + resource, algorithm, shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulUniform", resource=resource, algorithm=algorithm, + shape=shape, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulUniform = tf_export("raw_ops.StatefulUniform")(_ops.to_raw_op(stateful_uniform)) + + +def stateful_uniform_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniform_shape_dtype], dtype: TV_StatefulUniform_dtype, name, ctx) -> Annotated[Any, TV_StatefulUniform_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulUniform", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulUniformFullInt_dtype = TypeVar("TV_StatefulUniformFullInt_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulUniformFullInt_shape_dtype = TypeVar("TV_StatefulUniformFullInt_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_uniform_full_int(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniformFullInt_shape_dtype], dtype:TV_StatefulUniformFullInt_dtype=_dtypes.uint64, name=None) -> Annotated[Any, TV_StatefulUniformFullInt_dtype]: + r"""Outputs random integers from a uniform distribution. + + The generated values are uniform integers covering the whole range of `dtype`. + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + shape: A `Tensor`. The shape of the output tensor. + dtype: An optional `tf.DType`. Defaults to `tf.uint64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulUniformFullInt", name, resource, algorithm, shape, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_uniform_full_int_eager_fallback( + resource, algorithm, shape, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulUniformFullInt", resource=resource, algorithm=algorithm, + shape=shape, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulUniformFullInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulUniformFullInt = tf_export("raw_ops.StatefulUniformFullInt")(_ops.to_raw_op(stateful_uniform_full_int)) + + +def stateful_uniform_full_int_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniformFullInt_shape_dtype], dtype: TV_StatefulUniformFullInt_dtype, name, ctx) -> Annotated[Any, TV_StatefulUniformFullInt_dtype]: + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape] + _attrs = ("dtype", dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulUniformFullInt", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulUniformFullInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatefulUniformInt_dtype = TypeVar("TV_StatefulUniformInt_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_StatefulUniformInt_shape_dtype = TypeVar("TV_StatefulUniformInt_shape_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateful_uniform_int(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniformInt_shape_dtype], minval: Annotated[Any, TV_StatefulUniformInt_dtype], maxval: Annotated[Any, TV_StatefulUniformInt_dtype], name=None) -> Annotated[Any, TV_StatefulUniformInt_dtype]: + r"""Outputs random integers from a uniform distribution. + + The generated values are uniform integers in the range `[minval, maxval)`. + The lower bound `minval` is included in the range, while the upper bound + `maxval` is excluded. + + The random integers are slightly biased unless `maxval - minval` is an exact + power of two. The bias is small for values of `maxval - minval` significantly + smaller than the range of the output (either `2^32` or `2^64`). + + Args: + resource: A `Tensor` of type `resource`. + The handle of the resource variable that stores the state of the RNG. + algorithm: A `Tensor` of type `int64`. The RNG algorithm. + shape: A `Tensor`. The shape of the output tensor. + minval: A `Tensor`. Minimum value (inclusive, scalar). + maxval: A `Tensor`. Must have the same type as `minval`. + Maximum value (exclusive, scalar). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `minval`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatefulUniformInt", name, resource, algorithm, shape, minval, + maxval) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateful_uniform_int_eager_fallback( + resource, algorithm, shape, minval, maxval, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatefulUniformInt", resource=resource, algorithm=algorithm, + shape=shape, minval=minval, maxval=maxval, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatefulUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatefulUniformInt = tf_export("raw_ops.StatefulUniformInt")(_ops.to_raw_op(stateful_uniform_int)) + + +def stateful_uniform_int_eager_fallback(resource: Annotated[Any, _atypes.Resource], algorithm: Annotated[Any, _atypes.Int64], shape: Annotated[Any, TV_StatefulUniformInt_shape_dtype], minval: Annotated[Any, TV_StatefulUniformInt_dtype], maxval: Annotated[Any, TV_StatefulUniformInt_dtype], name, ctx) -> Annotated[Any, TV_StatefulUniformInt_dtype]: + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([minval, maxval], ctx, [], _dtypes.int64) + (minval, maxval) = _inputs_dtype + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [], _dtypes.int64) + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + algorithm = _ops.convert_to_tensor(algorithm, _dtypes.int64) + _inputs_flat = [resource, algorithm, shape, minval, maxval] + _attrs = ("dtype", _attr_dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatefulUniformInt", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatefulUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecd7b200f8a68b67384f0cfd20b6ed7e3182ade --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops.py @@ -0,0 +1,810 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_StatelessMultinomial_T = TypeVar("TV_StatelessMultinomial_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_StatelessMultinomial_Tseed = TypeVar("TV_StatelessMultinomial_Tseed", _atypes.Int32, _atypes.Int64) +TV_StatelessMultinomial_output_dtype = TypeVar("TV_StatelessMultinomial_output_dtype", _atypes.Int32, _atypes.Int64) + +def stateless_multinomial(logits: Annotated[Any, TV_StatelessMultinomial_T], num_samples: Annotated[Any, _atypes.Int32], seed: Annotated[Any, TV_StatelessMultinomial_Tseed], output_dtype:TV_StatelessMultinomial_output_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_StatelessMultinomial_output_dtype]: + r"""Draws samples from a multinomial distribution. + + Args: + logits: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` + represents the unnormalized log probabilities for all classes. + num_samples: A `Tensor` of type `int32`. + 0-D. Number of independent samples to draw for each row slice. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + output_dtype: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessMultinomial", name, logits, num_samples, seed, + "output_dtype", output_dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_multinomial_eager_fallback( + logits, num_samples, seed, output_dtype=output_dtype, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if output_dtype is None: + output_dtype = _dtypes.int64 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessMultinomial", logits=logits, num_samples=num_samples, + seed=seed, output_dtype=output_dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tseed", + _op._get_attr_type("Tseed"), "output_dtype", + _op._get_attr_type("output_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessMultinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessMultinomial = tf_export("raw_ops.StatelessMultinomial")(_ops.to_raw_op(stateless_multinomial)) + + +def stateless_multinomial_eager_fallback(logits: Annotated[Any, TV_StatelessMultinomial_T], num_samples: Annotated[Any, _atypes.Int32], seed: Annotated[Any, TV_StatelessMultinomial_Tseed], output_dtype: TV_StatelessMultinomial_output_dtype, name, ctx) -> Annotated[Any, TV_StatelessMultinomial_output_dtype]: + if output_dtype is None: + output_dtype = _dtypes.int64 + output_dtype = _execute.make_type(output_dtype, "output_dtype") + _attr_T, (logits,) = _execute.args_to_matching_eager([logits], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + num_samples = _ops.convert_to_tensor(num_samples, _dtypes.int32) + _inputs_flat = [logits, num_samples, seed] + _attrs = ("T", _attr_T, "Tseed", _attr_Tseed, "output_dtype", output_dtype) + _result = _execute.execute(b"StatelessMultinomial", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessMultinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessParameterizedTruncatedNormal_S = TypeVar("TV_StatelessParameterizedTruncatedNormal_S", _atypes.Int32, _atypes.Int64) +TV_StatelessParameterizedTruncatedNormal_Tseed = TypeVar("TV_StatelessParameterizedTruncatedNormal_Tseed", _atypes.Int32, _atypes.Int64) +TV_StatelessParameterizedTruncatedNormal_dtype = TypeVar("TV_StatelessParameterizedTruncatedNormal_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half) + +def stateless_parameterized_truncated_normal(shape: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_S], seed: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_Tseed], means: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], stddevs: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], minvals: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], maxvals: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], name=None) -> Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype]: + r"""TODO: add doc. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + means: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + The mean parameter of each batch. + stddevs: A `Tensor`. Must have the same type as `means`. + The standard deviation parameter of each batch. Must be greater than 0. + minvals: A `Tensor`. Must have the same type as `means`. + The minimum cutoff. May be -infinity. + maxvals: A `Tensor`. Must have the same type as `means`. + The maximum cutoff. May be +infinity, and must be more than the minval + for each batch. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `means`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessParameterizedTruncatedNormal", name, shape, seed, + means, stddevs, minvals, maxvals) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_parameterized_truncated_normal_eager_fallback( + shape, seed, means, stddevs, minvals, maxvals, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessParameterizedTruncatedNormal", shape=shape, seed=seed, + means=means, stddevs=stddevs, + minvals=minvals, + maxvals=maxvals, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("S", _op._get_attr_type("S"), "Tseed", + _op._get_attr_type("Tseed"), "dtype", + _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessParameterizedTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessParameterizedTruncatedNormal = tf_export("raw_ops.StatelessParameterizedTruncatedNormal")(_ops.to_raw_op(stateless_parameterized_truncated_normal)) + + +def stateless_parameterized_truncated_normal_eager_fallback(shape: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_S], seed: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_Tseed], means: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], stddevs: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], minvals: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], maxvals: Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype], name, ctx) -> Annotated[Any, TV_StatelessParameterizedTruncatedNormal_dtype]: + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([means, stddevs, minvals, maxvals], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + (means, stddevs, minvals, maxvals) = _inputs_dtype + _inputs_flat = [shape, seed, means, stddevs, minvals, maxvals] + _attrs = ("S", _attr_S, "Tseed", _attr_Tseed, "dtype", _attr_dtype) + _result = _execute.execute(b"StatelessParameterizedTruncatedNormal", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessParameterizedTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomBinomial_S = TypeVar("TV_StatelessRandomBinomial_S", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomBinomial_Tseed = TypeVar("TV_StatelessRandomBinomial_Tseed", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomBinomial_T = TypeVar("TV_StatelessRandomBinomial_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_StatelessRandomBinomial_dtype = TypeVar("TV_StatelessRandomBinomial_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) + +def stateless_random_binomial(shape: Annotated[Any, TV_StatelessRandomBinomial_S], seed: Annotated[Any, TV_StatelessRandomBinomial_Tseed], counts: Annotated[Any, TV_StatelessRandomBinomial_T], probs: Annotated[Any, TV_StatelessRandomBinomial_T], dtype:TV_StatelessRandomBinomial_dtype=_dtypes.int64, name=None) -> Annotated[Any, TV_StatelessRandomBinomial_dtype]: + r"""Outputs deterministic pseudorandom random numbers from a binomial distribution. + + Outputs random values from a binomial distribution. + + The outputs are a deterministic function of `shape`, `seed`, `counts`, and `probs`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + counts: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + The counts of the binomial distribution. Must be broadcastable with `probs`, + and broadcastable with the rightmost dimensions of `shape`. + probs: A `Tensor`. Must have the same type as `counts`. + The probability of success for the binomial distribution. Must be broadcastable + with `counts` and broadcastable with the rightmost dimensions of `shape`. + dtype: An optional `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomBinomial", name, shape, seed, counts, probs, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_binomial_eager_fallback( + shape, seed, counts, probs, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomBinomial", shape=shape, seed=seed, counts=counts, + probs=probs, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("S", _op._get_attr_type("S"), "Tseed", + _op._get_attr_type("Tseed"), "T", _op._get_attr_type("T"), + "dtype", _op._get_attr_type("dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomBinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomBinomial = tf_export("raw_ops.StatelessRandomBinomial")(_ops.to_raw_op(stateless_random_binomial)) + + +def stateless_random_binomial_eager_fallback(shape: Annotated[Any, TV_StatelessRandomBinomial_S], seed: Annotated[Any, TV_StatelessRandomBinomial_Tseed], counts: Annotated[Any, TV_StatelessRandomBinomial_T], probs: Annotated[Any, TV_StatelessRandomBinomial_T], dtype: TV_StatelessRandomBinomial_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomBinomial_dtype]: + if dtype is None: + dtype = _dtypes.int64 + dtype = _execute.make_type(dtype, "dtype") + _attr_S, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _attr_T, _inputs_T = _execute.args_to_matching_eager([counts, probs], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ], _dtypes.float64) + (counts, probs) = _inputs_T + _inputs_flat = [shape, seed, counts, probs] + _attrs = ("S", _attr_S, "Tseed", _attr_Tseed, "T", _attr_T, "dtype", dtype) + _result = _execute.execute(b"StatelessRandomBinomial", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomBinomial", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomGammaV2_dtype = TypeVar("TV_StatelessRandomGammaV2_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomGammaV2_T = TypeVar("TV_StatelessRandomGammaV2_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomGammaV2_Tseed = TypeVar("TV_StatelessRandomGammaV2_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_gamma_v2(shape: Annotated[Any, TV_StatelessRandomGammaV2_T], seed: Annotated[Any, TV_StatelessRandomGammaV2_Tseed], alpha: Annotated[Any, TV_StatelessRandomGammaV2_dtype], name=None) -> Annotated[Any, TV_StatelessRandomGammaV2_dtype]: + r"""Outputs deterministic pseudorandom random numbers from a gamma distribution. + + Outputs random values from a gamma distribution. + + The outputs are a deterministic function of `shape`, `seed`, and `alpha`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + alpha: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + The concentration of the gamma distribution. Shape must match the rightmost + dimensions of `shape`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `alpha`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomGammaV2", name, shape, seed, alpha) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_gamma_v2_eager_fallback( + shape, seed, alpha, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomGammaV2", shape=shape, seed=seed, alpha=alpha, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomGammaV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomGammaV2 = tf_export("raw_ops.StatelessRandomGammaV2")(_ops.to_raw_op(stateless_random_gamma_v2)) + + +def stateless_random_gamma_v2_eager_fallback(shape: Annotated[Any, TV_StatelessRandomGammaV2_T], seed: Annotated[Any, TV_StatelessRandomGammaV2_Tseed], alpha: Annotated[Any, TV_StatelessRandomGammaV2_dtype], name, ctx) -> Annotated[Any, TV_StatelessRandomGammaV2_dtype]: + _attr_dtype, (alpha,) = _execute.args_to_matching_eager([alpha], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed, alpha] + _attrs = ("dtype", _attr_dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomGammaV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomGammaV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomNormal_dtype = TypeVar("TV_StatelessRandomNormal_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomNormal_T = TypeVar("TV_StatelessRandomNormal_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomNormal_Tseed = TypeVar("TV_StatelessRandomNormal_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_normal(shape: Annotated[Any, TV_StatelessRandomNormal_T], seed: Annotated[Any, TV_StatelessRandomNormal_Tseed], dtype:TV_StatelessRandomNormal_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessRandomNormal_dtype]: + r"""Outputs deterministic pseudorandom values from a normal distribution. + + The generated values will have mean 0 and standard deviation 1. + + The outputs are a deterministic function of `shape` and `seed`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomNormal", name, shape, seed, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_normal_eager_fallback( + shape, seed, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomNormal", shape=shape, seed=seed, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomNormal = tf_export("raw_ops.StatelessRandomNormal")(_ops.to_raw_op(stateless_random_normal)) + + +def stateless_random_normal_eager_fallback(shape: Annotated[Any, TV_StatelessRandomNormal_T], seed: Annotated[Any, TV_StatelessRandomNormal_Tseed], dtype: TV_StatelessRandomNormal_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomNormal_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed] + _attrs = ("dtype", dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomNormal", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomPoisson_Rtype = TypeVar("TV_StatelessRandomPoisson_Rtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_StatelessRandomPoisson_dtype = TypeVar("TV_StatelessRandomPoisson_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.Int64) +TV_StatelessRandomPoisson_T = TypeVar("TV_StatelessRandomPoisson_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomPoisson_Tseed = TypeVar("TV_StatelessRandomPoisson_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_poisson(shape: Annotated[Any, TV_StatelessRandomPoisson_T], seed: Annotated[Any, TV_StatelessRandomPoisson_Tseed], lam: Annotated[Any, TV_StatelessRandomPoisson_Rtype], dtype: TV_StatelessRandomPoisson_dtype, name=None) -> Annotated[Any, TV_StatelessRandomPoisson_dtype]: + r"""Outputs deterministic pseudorandom random numbers from a Poisson distribution. + + Outputs random values from a Poisson distribution. + + The outputs are a deterministic function of `shape`, `seed`, and `lam`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + lam: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`. + The rate of the Poisson distribution. Shape must match the rightmost dimensions + of `shape`. + dtype: A `tf.DType` from: `tf.half, tf.float32, tf.float64, tf.int32, tf.int64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomPoisson", name, shape, seed, lam, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_poisson_eager_fallback( + shape, seed, lam, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomPoisson", shape=shape, seed=seed, lam=lam, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Rtype", _op._get_attr_type("Rtype"), "dtype", + _op._get_attr_type("dtype"), "T", _op._get_attr_type("T"), + "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomPoisson", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomPoisson = tf_export("raw_ops.StatelessRandomPoisson")(_ops.to_raw_op(stateless_random_poisson)) + + +def stateless_random_poisson_eager_fallback(shape: Annotated[Any, TV_StatelessRandomPoisson_T], seed: Annotated[Any, TV_StatelessRandomPoisson_Tseed], lam: Annotated[Any, TV_StatelessRandomPoisson_Rtype], dtype: TV_StatelessRandomPoisson_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomPoisson_dtype]: + dtype = _execute.make_type(dtype, "dtype") + _attr_Rtype, (lam,) = _execute.args_to_matching_eager([lam], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.int64, ]) + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed, lam] + _attrs = ("Rtype", _attr_Rtype, "dtype", dtype, "T", _attr_T, "Tseed", + _attr_Tseed) + _result = _execute.execute(b"StatelessRandomPoisson", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomPoisson", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniform_dtype = TypeVar("TV_StatelessRandomUniform_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomUniform_T = TypeVar("TV_StatelessRandomUniform_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomUniform_Tseed = TypeVar("TV_StatelessRandomUniform_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_uniform(shape: Annotated[Any, TV_StatelessRandomUniform_T], seed: Annotated[Any, TV_StatelessRandomUniform_Tseed], dtype:TV_StatelessRandomUniform_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessRandomUniform_dtype]: + r"""Outputs deterministic pseudorandom random values from a uniform distribution. + + The generated values follow a uniform distribution in the range `[0, 1)`. The + lower bound 0 is included in the range, while the upper bound 1 is excluded. + + The outputs are a deterministic function of `shape` and `seed`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniform", name, shape, seed, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_eager_fallback( + shape, seed, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniform", shape=shape, seed=seed, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniform = tf_export("raw_ops.StatelessRandomUniform")(_ops.to_raw_op(stateless_random_uniform)) + + +def stateless_random_uniform_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniform_T], seed: Annotated[Any, TV_StatelessRandomUniform_Tseed], dtype: TV_StatelessRandomUniform_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomUniform_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed] + _attrs = ("dtype", dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomUniform", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniform", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniformFullInt_dtype = TypeVar("TV_StatelessRandomUniformFullInt_dtype", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) +TV_StatelessRandomUniformFullInt_T = TypeVar("TV_StatelessRandomUniformFullInt_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomUniformFullInt_Tseed = TypeVar("TV_StatelessRandomUniformFullInt_Tseed", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) + +def stateless_random_uniform_full_int(shape: Annotated[Any, TV_StatelessRandomUniformFullInt_T], seed: Annotated[Any, TV_StatelessRandomUniformFullInt_Tseed], dtype:TV_StatelessRandomUniformFullInt_dtype=_dtypes.uint64, name=None) -> Annotated[Any, TV_StatelessRandomUniformFullInt_dtype]: + r"""Outputs deterministic pseudorandom random integers from a uniform distribution. + + The generated values are uniform integers covering the whole range of `dtype`. + + The outputs are a deterministic function of `shape` and `seed`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`, `uint32`, `uint64`. + 2 seeds (shape [2]). + dtype: An optional `tf.DType` from: `tf.int32, tf.int64, tf.uint32, tf.uint64`. Defaults to `tf.uint64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniformFullInt", name, shape, seed, "dtype", + dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_full_int_eager_fallback( + shape, seed, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniformFullInt", shape=shape, seed=seed, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniformFullInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniformFullInt = tf_export("raw_ops.StatelessRandomUniformFullInt")(_ops.to_raw_op(stateless_random_uniform_full_int)) + + +def stateless_random_uniform_full_int_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniformFullInt_T], seed: Annotated[Any, TV_StatelessRandomUniformFullInt_Tseed], dtype: TV_StatelessRandomUniformFullInt_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomUniformFullInt_dtype]: + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.uint32, _dtypes.uint64, ], _dtypes.int64) + _inputs_flat = [shape, seed] + _attrs = ("dtype", dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomUniformFullInt", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniformFullInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniformInt_dtype = TypeVar("TV_StatelessRandomUniformInt_dtype", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomUniformInt_T = TypeVar("TV_StatelessRandomUniformInt_T", _atypes.Int32, _atypes.Int64) +TV_StatelessRandomUniformInt_Tseed = TypeVar("TV_StatelessRandomUniformInt_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_uniform_int(shape: Annotated[Any, TV_StatelessRandomUniformInt_T], seed: Annotated[Any, TV_StatelessRandomUniformInt_Tseed], minval: Annotated[Any, TV_StatelessRandomUniformInt_dtype], maxval: Annotated[Any, TV_StatelessRandomUniformInt_dtype], name=None) -> Annotated[Any, TV_StatelessRandomUniformInt_dtype]: + r"""Outputs deterministic pseudorandom random integers from a uniform distribution. + + The generated values follow a uniform distribution in the range `[minval, maxval)`. + + The outputs are a deterministic function of `shape`, `seed`, `minval`, and `maxval`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + minval: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Minimum value (inclusive, scalar). + maxval: A `Tensor`. Must have the same type as `minval`. + Maximum value (exclusive, scalar). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `minval`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniformInt", name, shape, seed, minval, maxval) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_int_eager_fallback( + shape, seed, minval, maxval, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniformInt", shape=shape, seed=seed, minval=minval, + maxval=maxval, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniformInt = tf_export("raw_ops.StatelessRandomUniformInt")(_ops.to_raw_op(stateless_random_uniform_int)) + + +def stateless_random_uniform_int_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniformInt_T], seed: Annotated[Any, TV_StatelessRandomUniformInt_Tseed], minval: Annotated[Any, TV_StatelessRandomUniformInt_dtype], maxval: Annotated[Any, TV_StatelessRandomUniformInt_dtype], name, ctx) -> Annotated[Any, TV_StatelessRandomUniformInt_dtype]: + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([minval, maxval], ctx, [_dtypes.int32, _dtypes.int64, ]) + (minval, maxval) = _inputs_dtype + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed, minval, maxval] + _attrs = ("dtype", _attr_dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomUniformInt", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniformInt", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessTruncatedNormal_dtype = TypeVar("TV_StatelessTruncatedNormal_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessTruncatedNormal_T = TypeVar("TV_StatelessTruncatedNormal_T", _atypes.Int32, _atypes.Int64) +TV_StatelessTruncatedNormal_Tseed = TypeVar("TV_StatelessTruncatedNormal_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_truncated_normal(shape: Annotated[Any, TV_StatelessTruncatedNormal_T], seed: Annotated[Any, TV_StatelessTruncatedNormal_Tseed], dtype:TV_StatelessTruncatedNormal_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessTruncatedNormal_dtype]: + r"""Outputs deterministic pseudorandom values from a truncated normal distribution. + + The generated values follow a normal distribution with mean 0 and standard + deviation 1, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + The outputs are a deterministic function of `shape` and `seed`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessTruncatedNormal", name, shape, seed, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_truncated_normal_eager_fallback( + shape, seed, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessTruncatedNormal", shape=shape, seed=seed, dtype=dtype, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "T", + _op._get_attr_type("T"), "Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessTruncatedNormal = tf_export("raw_ops.StatelessTruncatedNormal")(_ops.to_raw_op(stateless_truncated_normal)) + + +def stateless_truncated_normal_eager_fallback(shape: Annotated[Any, TV_StatelessTruncatedNormal_T], seed: Annotated[Any, TV_StatelessTruncatedNormal_Tseed], dtype: TV_StatelessTruncatedNormal_dtype, name, ctx) -> Annotated[Any, TV_StatelessTruncatedNormal_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_T, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [shape, seed] + _attrs = ("dtype", dtype, "T", _attr_T, "Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessTruncatedNormal", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessTruncatedNormal", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..66b01a6b4d0b25abdb96c78494d5f5b086479f46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_stateless_random_ops_v2.py @@ -0,0 +1,781 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_StatelessRandomGammaV3_dtype = TypeVar("TV_StatelessRandomGammaV3_dtype", _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomGammaV3_shape_dtype = TypeVar("TV_StatelessRandomGammaV3_shape_dtype", _atypes.Int32, _atypes.Int64) + +def stateless_random_gamma_v3(shape: Annotated[Any, TV_StatelessRandomGammaV3_shape_dtype], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], alpha: Annotated[Any, TV_StatelessRandomGammaV3_dtype], name=None) -> Annotated[Any, TV_StatelessRandomGammaV3_dtype]: + r"""Outputs deterministic pseudorandom random numbers from a gamma distribution. + + Outputs random values from a gamma distribution. + + The outputs are a deterministic function of the inputs. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + alpha: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. + The concentration of the gamma distribution. Shape must match the rightmost + dimensions of `shape`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `alpha`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomGammaV3", name, shape, key, counter, alg, alpha) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_gamma_v3_eager_fallback( + shape, key, counter, alg, alpha, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomGammaV3", shape=shape, key=key, counter=counter, + alg=alg, alpha=alpha, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape_dtype", + _op._get_attr_type("shape_dtype")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomGammaV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomGammaV3 = tf_export("raw_ops.StatelessRandomGammaV3")(_ops.to_raw_op(stateless_random_gamma_v3)) + + +def stateless_random_gamma_v3_eager_fallback(shape: Annotated[Any, TV_StatelessRandomGammaV3_shape_dtype], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], alpha: Annotated[Any, TV_StatelessRandomGammaV3_dtype], name, ctx) -> Annotated[Any, TV_StatelessRandomGammaV3_dtype]: + _attr_dtype, (alpha,) = _execute.args_to_matching_eager([alpha], ctx, [_dtypes.half, _dtypes.float32, _dtypes.float64, ]) + _attr_shape_dtype, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg, alpha] + _attrs = ("dtype", _attr_dtype, "shape_dtype", _attr_shape_dtype) + _result = _execute.execute(b"StatelessRandomGammaV3", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomGammaV3", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def stateless_random_get_alg(name=None) -> Annotated[Any, _atypes.Int32]: + r"""Picks the best counter-based RNG algorithm based on device. + + This op picks the best counter-based RNG algorithm based on device. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomGetAlg", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_get_alg_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomGetAlg", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomGetAlg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomGetAlg = tf_export("raw_ops.StatelessRandomGetAlg")(_ops.to_raw_op(stateless_random_get_alg)) + + +def stateless_random_get_alg_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"StatelessRandomGetAlg", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomGetAlg", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_StatelessRandomGetKeyCounterOutput = collections.namedtuple( + "StatelessRandomGetKeyCounter", + ["key", "counter"]) + + +TV_StatelessRandomGetKeyCounter_Tseed = TypeVar("TV_StatelessRandomGetKeyCounter_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_get_key_counter(seed: Annotated[Any, TV_StatelessRandomGetKeyCounter_Tseed], name=None): + r"""Scrambles seed into key and counter, using the best algorithm based on device. + + This op scrambles a shape-[2] seed into a key and a counter, both needed by counter-based RNG algorithms. The scrambing uses the best algorithm based on device. The scrambling is opaque but approximately satisfies the property that different seed results in different key/counter pair (which will in turn result in different random numbers). + + Args: + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, counter). + + key: A `Tensor` of type `uint64`. + counter: A `Tensor` of type `uint64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomGetKeyCounter", name, seed) + _result = _StatelessRandomGetKeyCounterOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_get_key_counter_eager_fallback( + seed, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomGetKeyCounter", seed=seed, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomGetKeyCounter", _inputs_flat, _attrs, _result) + _result = _StatelessRandomGetKeyCounterOutput._make(_result) + return _result + +StatelessRandomGetKeyCounter = tf_export("raw_ops.StatelessRandomGetKeyCounter")(_ops.to_raw_op(stateless_random_get_key_counter)) + + +def stateless_random_get_key_counter_eager_fallback(seed: Annotated[Any, TV_StatelessRandomGetKeyCounter_Tseed], name, ctx): + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [seed] + _attrs = ("Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomGetKeyCounter", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomGetKeyCounter", _inputs_flat, _attrs, _result) + _result = _StatelessRandomGetKeyCounterOutput._make(_result) + return _result + +_StatelessRandomGetKeyCounterAlgOutput = collections.namedtuple( + "StatelessRandomGetKeyCounterAlg", + ["key", "counter", "alg"]) + + +TV_StatelessRandomGetKeyCounterAlg_Tseed = TypeVar("TV_StatelessRandomGetKeyCounterAlg_Tseed", _atypes.Int32, _atypes.Int64) + +def stateless_random_get_key_counter_alg(seed: Annotated[Any, TV_StatelessRandomGetKeyCounterAlg_Tseed], name=None): + r"""Picks the best algorithm based on device, and scrambles seed into key and counter. + + This op picks the best counter-based RNG algorithm based on device, and scrambles a shape-[2] seed into a key and a counter, both needed by the counter-based algorithm. The scrambling is opaque but approximately satisfies the property that different seed results in different key/counter pair (which will in turn result in different random numbers). + + Args: + seed: A `Tensor`. Must be one of the following types: `int32`, `int64`. + 2 seeds (shape [2]). + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (key, counter, alg). + + key: A `Tensor` of type `uint64`. + counter: A `Tensor` of type `uint64`. + alg: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomGetKeyCounterAlg", name, seed) + _result = _StatelessRandomGetKeyCounterAlgOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_get_key_counter_alg_eager_fallback( + seed, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomGetKeyCounterAlg", seed=seed, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tseed", _op._get_attr_type("Tseed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomGetKeyCounterAlg", _inputs_flat, _attrs, _result) + _result = _StatelessRandomGetKeyCounterAlgOutput._make(_result) + return _result + +StatelessRandomGetKeyCounterAlg = tf_export("raw_ops.StatelessRandomGetKeyCounterAlg")(_ops.to_raw_op(stateless_random_get_key_counter_alg)) + + +def stateless_random_get_key_counter_alg_eager_fallback(seed: Annotated[Any, TV_StatelessRandomGetKeyCounterAlg_Tseed], name, ctx): + _attr_Tseed, (seed,) = _execute.args_to_matching_eager([seed], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + _inputs_flat = [seed] + _attrs = ("Tseed", _attr_Tseed) + _result = _execute.execute(b"StatelessRandomGetKeyCounterAlg", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomGetKeyCounterAlg", _inputs_flat, _attrs, _result) + _result = _StatelessRandomGetKeyCounterAlgOutput._make(_result) + return _result + + +TV_StatelessRandomNormalV2_dtype = TypeVar("TV_StatelessRandomNormalV2_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomNormalV2_Tshape = TypeVar("TV_StatelessRandomNormalV2_Tshape", _atypes.Int32, _atypes.Int64) + +def stateless_random_normal_v2(shape: Annotated[Any, TV_StatelessRandomNormalV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype:TV_StatelessRandomNormalV2_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessRandomNormalV2_dtype]: + r"""Outputs deterministic pseudorandom values from a normal distribution. + + The generated values will have mean 0 and standard deviation 1. + + The outputs are a deterministic function of `shape`, `key`, `counter` and `alg`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomNormalV2", name, shape, key, counter, alg, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_normal_v2_eager_fallback( + shape, key, counter, alg, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomNormalV2", shape=shape, key=key, counter=counter, + alg=alg, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomNormalV2 = tf_export("raw_ops.StatelessRandomNormalV2")(_ops.to_raw_op(stateless_random_normal_v2)) + + +def stateless_random_normal_v2_eager_fallback(shape: Annotated[Any, TV_StatelessRandomNormalV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype: TV_StatelessRandomNormalV2_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomNormalV2_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg] + _attrs = ("dtype", dtype, "Tshape", _attr_Tshape) + _result = _execute.execute(b"StatelessRandomNormalV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniformFullIntV2_dtype = TypeVar("TV_StatelessRandomUniformFullIntV2_dtype", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) +TV_StatelessRandomUniformFullIntV2_Tshape = TypeVar("TV_StatelessRandomUniformFullIntV2_Tshape", _atypes.Int32, _atypes.Int64) + +def stateless_random_uniform_full_int_v2(shape: Annotated[Any, TV_StatelessRandomUniformFullIntV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype:TV_StatelessRandomUniformFullIntV2_dtype=_dtypes.uint64, name=None) -> Annotated[Any, TV_StatelessRandomUniformFullIntV2_dtype]: + r"""Outputs deterministic pseudorandom random integers from a uniform distribution. + + The generated values are uniform integers covering the whole range of `dtype`. + + The outputs are a deterministic function of `shape`, `key`, `counter` and `alg`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + dtype: An optional `tf.DType` from: `tf.int32, tf.int64, tf.uint32, tf.uint64`. Defaults to `tf.uint64`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniformFullIntV2", name, shape, key, counter, + alg, "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_full_int_v2_eager_fallback( + shape, key, counter, alg, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniformFullIntV2", shape=shape, key=key, + counter=counter, alg=alg, + dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniformFullIntV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniformFullIntV2 = tf_export("raw_ops.StatelessRandomUniformFullIntV2")(_ops.to_raw_op(stateless_random_uniform_full_int_v2)) + + +def stateless_random_uniform_full_int_v2_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniformFullIntV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype: TV_StatelessRandomUniformFullIntV2_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomUniformFullIntV2_dtype]: + if dtype is None: + dtype = _dtypes.uint64 + dtype = _execute.make_type(dtype, "dtype") + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg] + _attrs = ("dtype", dtype, "Tshape", _attr_Tshape) + _result = _execute.execute(b"StatelessRandomUniformFullIntV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniformFullIntV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniformIntV2_dtype = TypeVar("TV_StatelessRandomUniformIntV2_dtype", _atypes.Int32, _atypes.Int64, _atypes.UInt32, _atypes.UInt64) +TV_StatelessRandomUniformIntV2_Tshape = TypeVar("TV_StatelessRandomUniformIntV2_Tshape", _atypes.Int32, _atypes.Int64) + +def stateless_random_uniform_int_v2(shape: Annotated[Any, TV_StatelessRandomUniformIntV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], minval: Annotated[Any, TV_StatelessRandomUniformIntV2_dtype], maxval: Annotated[Any, TV_StatelessRandomUniformIntV2_dtype], name=None) -> Annotated[Any, TV_StatelessRandomUniformIntV2_dtype]: + r"""Outputs deterministic pseudorandom random integers from a uniform distribution. + + The generated values follow a uniform distribution in the range `[minval, maxval)`. + + The outputs are a deterministic function of `shape`, `key`, `counter`, `alg`, `minval` and `maxval`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + minval: A `Tensor`. Must be one of the following types: `int32`, `int64`, `uint32`, `uint64`. + Minimum value (inclusive, scalar). + maxval: A `Tensor`. Must have the same type as `minval`. + Maximum value (exclusive, scalar). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `minval`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniformIntV2", name, shape, key, counter, alg, + minval, maxval) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_int_v2_eager_fallback( + shape, key, counter, alg, minval, maxval, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniformIntV2", shape=shape, key=key, counter=counter, + alg=alg, minval=minval, maxval=maxval, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniformIntV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniformIntV2 = tf_export("raw_ops.StatelessRandomUniformIntV2")(_ops.to_raw_op(stateless_random_uniform_int_v2)) + + +def stateless_random_uniform_int_v2_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniformIntV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], minval: Annotated[Any, TV_StatelessRandomUniformIntV2_dtype], maxval: Annotated[Any, TV_StatelessRandomUniformIntV2_dtype], name, ctx) -> Annotated[Any, TV_StatelessRandomUniformIntV2_dtype]: + _attr_dtype, _inputs_dtype = _execute.args_to_matching_eager([minval, maxval], ctx, [_dtypes.int32, _dtypes.int64, _dtypes.uint32, _dtypes.uint64, ]) + (minval, maxval) = _inputs_dtype + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg, minval, maxval] + _attrs = ("dtype", _attr_dtype, "Tshape", _attr_Tshape) + _result = _execute.execute(b"StatelessRandomUniformIntV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniformIntV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessRandomUniformV2_dtype = TypeVar("TV_StatelessRandomUniformV2_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessRandomUniformV2_Tshape = TypeVar("TV_StatelessRandomUniformV2_Tshape", _atypes.Int32, _atypes.Int64) + +def stateless_random_uniform_v2(shape: Annotated[Any, TV_StatelessRandomUniformV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype:TV_StatelessRandomUniformV2_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessRandomUniformV2_dtype]: + r"""Outputs deterministic pseudorandom random values from a uniform distribution. + + The generated values follow a uniform distribution in the range `[0, 1)`. The + lower bound 0 is included in the range, while the upper bound 1 is excluded. + + The outputs are a deterministic function of `shape`, `key`, `counter` and `alg`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessRandomUniformV2", name, shape, key, counter, alg, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_random_uniform_v2_eager_fallback( + shape, key, counter, alg, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessRandomUniformV2", shape=shape, key=key, counter=counter, + alg=alg, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessRandomUniformV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessRandomUniformV2 = tf_export("raw_ops.StatelessRandomUniformV2")(_ops.to_raw_op(stateless_random_uniform_v2)) + + +def stateless_random_uniform_v2_eager_fallback(shape: Annotated[Any, TV_StatelessRandomUniformV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype: TV_StatelessRandomUniformV2_dtype, name, ctx) -> Annotated[Any, TV_StatelessRandomUniformV2_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg] + _attrs = ("dtype", dtype, "Tshape", _attr_Tshape) + _result = _execute.execute(b"StatelessRandomUniformV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessRandomUniformV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessShuffle_T = TypeVar("TV_StatelessShuffle_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def stateless_shuffle(value: Annotated[Any, TV_StatelessShuffle_T], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_StatelessShuffle_T]: + r"""Randomly and deterministically shuffles a tensor along its first dimension. + + The tensor is shuffled along dimension 0, such that each `value[j]` is mapped + to one and only one `output[i]`. For example, a mapping that might occur for a + 3x2 tensor is: + + ``` + [[1, 2], [[5, 6], + [3, 4], ==> [1, 2], + [5, 6]] [3, 4]] + ``` + + The outputs are a deterministic function of `value`, `key`, `counter` and `alg`. + + Args: + value: A `Tensor`. The tensor to be shuffled. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `value`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessShuffle", name, value, key, counter, alg) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_shuffle_eager_fallback( + value, key, counter, alg, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessShuffle", value=value, key=key, counter=counter, alg=alg, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessShuffle = tf_export("raw_ops.StatelessShuffle")(_ops.to_raw_op(stateless_shuffle)) + + +def stateless_shuffle_eager_fallback(value: Annotated[Any, TV_StatelessShuffle_T], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_StatelessShuffle_T]: + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, []) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [value, key, counter, alg] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"StatelessShuffle", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessShuffle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_StatelessTruncatedNormalV2_dtype = TypeVar("TV_StatelessTruncatedNormalV2_dtype", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half) +TV_StatelessTruncatedNormalV2_Tshape = TypeVar("TV_StatelessTruncatedNormalV2_Tshape", _atypes.Int32, _atypes.Int64) + +def stateless_truncated_normal_v2(shape: Annotated[Any, TV_StatelessTruncatedNormalV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype:TV_StatelessTruncatedNormalV2_dtype=_dtypes.float32, name=None) -> Annotated[Any, TV_StatelessTruncatedNormalV2_dtype]: + r"""Outputs deterministic pseudorandom values from a truncated normal distribution. + + The generated values follow a normal distribution with mean 0 and standard + deviation 1, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + The outputs are a deterministic function of `shape`, `key`, `counter` and `alg`. + + Args: + shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The shape of the output tensor. + key: A `Tensor` of type `uint64`. + Key for the counter-based RNG algorithm (shape uint64[1]). + counter: A `Tensor` of type `uint64`. + Initial counter for the counter-based RNG algorithm (shape uint64[2] or uint64[1] depending on the algorithm). If a larger vector is given, only the needed portion on the left (i.e. [:N]) will be used. + alg: A `Tensor` of type `int32`. The RNG algorithm (shape int32[]). + dtype: An optional `tf.DType` from: `tf.half, tf.bfloat16, tf.float32, tf.float64`. Defaults to `tf.float32`. + The type of the output. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StatelessTruncatedNormalV2", name, shape, key, counter, alg, + "dtype", dtype) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return stateless_truncated_normal_v2_eager_fallback( + shape, key, counter, alg, dtype=dtype, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StatelessTruncatedNormalV2", shape=shape, key=key, counter=counter, + alg=alg, dtype=dtype, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "Tshape", + _op._get_attr_type("Tshape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StatelessTruncatedNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StatelessTruncatedNormalV2 = tf_export("raw_ops.StatelessTruncatedNormalV2")(_ops.to_raw_op(stateless_truncated_normal_v2)) + + +def stateless_truncated_normal_v2_eager_fallback(shape: Annotated[Any, TV_StatelessTruncatedNormalV2_Tshape], key: Annotated[Any, _atypes.UInt64], counter: Annotated[Any, _atypes.UInt64], alg: Annotated[Any, _atypes.Int32], dtype: TV_StatelessTruncatedNormalV2_dtype, name, ctx) -> Annotated[Any, TV_StatelessTruncatedNormalV2_dtype]: + if dtype is None: + dtype = _dtypes.float32 + dtype = _execute.make_type(dtype, "dtype") + _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + key = _ops.convert_to_tensor(key, _dtypes.uint64) + counter = _ops.convert_to_tensor(counter, _dtypes.uint64) + alg = _ops.convert_to_tensor(alg, _dtypes.int32) + _inputs_flat = [shape, key, counter, alg] + _attrs = ("dtype", dtype, "Tshape", _attr_Tshape) + _result = _execute.execute(b"StatelessTruncatedNormalV2", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StatelessTruncatedNormalV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_string_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_string_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb9429bdf1732f2dcde16ab9445c1b3235801b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_string_ops.py @@ -0,0 +1,2848 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AsString_T = TypeVar("TV_AsString_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.as_string', 'as_string', v1=['dtypes.as_string', 'strings.as_string', 'as_string']) +@deprecated_endpoints('dtypes.as_string') +def as_string(input: Annotated[Any, TV_AsString_T], precision:int=-1, scientific:bool=False, shortest:bool=False, width:int=-1, fill:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Converts each entry in the given tensor to strings. + + Supports many numeric types and boolean. + + For Unicode, see the + [https://www.tensorflow.org/tutorials/representation/unicode](Working with Unicode text) + tutorial. + + Examples: + + >>> tf.strings.as_string([3, 2]) + + >>> tf.strings.as_string([3.1415926, 2.71828], precision=2).numpy() + array([b'3.14', b'2.72'], dtype=object) + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `complex64`, `complex128`, `bool`, `variant`, `string`. + precision: An optional `int`. Defaults to `-1`. + The post-decimal precision to use for floating point numbers. + Only used if precision > -1. + scientific: An optional `bool`. Defaults to `False`. + Use scientific notation for floating point numbers. + shortest: An optional `bool`. Defaults to `False`. + Use shortest representation (either scientific or standard) for + floating point numbers. + width: An optional `int`. Defaults to `-1`. + Pad pre-decimal numbers to this width. + Applies to both floating point and integer numbers. + Only used if width > -1. + fill: An optional `string`. Defaults to `""`. + The value to pad if width > -1. If empty, pads with spaces. + Another typical value is '0'. String cannot be longer than 1 character. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AsString", name, input, "precision", precision, "scientific", + scientific, "shortest", shortest, "width", width, "fill", fill) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_as_string( + (input, precision, scientific, shortest, width, fill, name,), None) + if _result is not NotImplemented: + return _result + return as_string_eager_fallback( + input, precision=precision, scientific=scientific, + shortest=shortest, width=width, fill=fill, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + as_string, (), dict(input=input, precision=precision, + scientific=scientific, shortest=shortest, + width=width, fill=fill, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_as_string( + (input, precision, scientific, shortest, width, fill, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if precision is None: + precision = -1 + precision = _execute.make_int(precision, "precision") + if scientific is None: + scientific = False + scientific = _execute.make_bool(scientific, "scientific") + if shortest is None: + shortest = False + shortest = _execute.make_bool(shortest, "shortest") + if width is None: + width = -1 + width = _execute.make_int(width, "width") + if fill is None: + fill = "" + fill = _execute.make_str(fill, "fill") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AsString", input=input, precision=precision, scientific=scientific, + shortest=shortest, width=width, fill=fill, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + as_string, (), dict(input=input, precision=precision, + scientific=scientific, shortest=shortest, + width=width, fill=fill, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "precision", + _op._get_attr_int("precision"), "scientific", + _op._get_attr_bool("scientific"), "shortest", + _op._get_attr_bool("shortest"), "width", + _op._get_attr_int("width"), "fill", _op.get_attr("fill")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AsString", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AsString = tf_export("raw_ops.AsString")(_ops.to_raw_op(as_string)) +_dispatcher_for_as_string = as_string._tf_type_based_dispatcher.Dispatch + + +def as_string_eager_fallback(input: Annotated[Any, TV_AsString_T], precision: int, scientific: bool, shortest: bool, width: int, fill: str, name, ctx) -> Annotated[Any, _atypes.String]: + if precision is None: + precision = -1 + precision = _execute.make_int(precision, "precision") + if scientific is None: + scientific = False + scientific = _execute.make_bool(scientific, "scientific") + if shortest is None: + shortest = False + shortest = _execute.make_bool(shortest, "shortest") + if width is None: + width = -1 + width = _execute.make_int(width, "width") + if fill is None: + fill = "" + fill = _execute.make_str(fill, "fill") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.complex64, _dtypes.complex128, _dtypes.bool, _dtypes.variant, _dtypes.string, ]) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "precision", precision, "scientific", scientific, + "shortest", shortest, "width", width, "fill", fill) + _result = _execute.execute(b"AsString", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AsString", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.decode_base64', v1=['io.decode_base64', 'decode_base64']) +@deprecated_endpoints('decode_base64') +def decode_base64(input: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Decode web-safe base64-encoded strings. + + Input may or may not have padding at the end. See + [EncodeBase64](https://www.tensorflow.org/api_docs/python/tf/io/encode_base64) + for padding. Web-safe means that input must use - and _ instead of + and /. + + Args: + input: A `Tensor` of type `string`. Base64 strings to decode. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DecodeBase64", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_decode_base64( + (input, name,), None) + if _result is not NotImplemented: + return _result + return decode_base64_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_base64, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_decode_base64( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DecodeBase64", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + decode_base64, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DecodeBase64", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DecodeBase64 = tf_export("raw_ops.DecodeBase64")(_ops.to_raw_op(decode_base64)) +_dispatcher_for_decode_base64 = decode_base64._tf_type_based_dispatcher.Dispatch + + +def decode_base64_eager_fallback(input: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"DecodeBase64", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DecodeBase64", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('io.encode_base64', v1=['io.encode_base64', 'encode_base64']) +@deprecated_endpoints('encode_base64') +def encode_base64(input: Annotated[Any, _atypes.String], pad:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Encode strings into web-safe base64 format. + + Refer to [this article](https://en.wikipedia.org/wiki/Base64) for more information on + base64 format. Base64 strings may have padding with '=' at the + end so that the encoded has length multiple of 4. See Padding section of the + link above. + + Web-safe means that the encoder uses - and _ instead of + and /. + + Args: + input: A `Tensor` of type `string`. Strings to be encoded. + pad: An optional `bool`. Defaults to `False`. + Bool whether padding is applied at the ends. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EncodeBase64", name, input, "pad", pad) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_encode_base64( + (input, pad, name,), None) + if _result is not NotImplemented: + return _result + return encode_base64_eager_fallback( + input, pad=pad, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_base64, (), dict(input=input, pad=pad, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_encode_base64( + (input, pad, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if pad is None: + pad = False + pad = _execute.make_bool(pad, "pad") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EncodeBase64", input=input, pad=pad, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + encode_base64, (), dict(input=input, pad=pad, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pad", _op._get_attr_bool("pad")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "EncodeBase64", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +EncodeBase64 = tf_export("raw_ops.EncodeBase64")(_ops.to_raw_op(encode_base64)) +_dispatcher_for_encode_base64 = encode_base64._tf_type_based_dispatcher.Dispatch + + +def encode_base64_eager_fallback(input: Annotated[Any, _atypes.String], pad: bool, name, ctx) -> Annotated[Any, _atypes.String]: + if pad is None: + pad = False + pad = _execute.make_bool(pad, "pad") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("pad", pad) + _result = _execute.execute(b"EncodeBase64", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "EncodeBase64", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def reduce_join(inputs: Annotated[Any, _atypes.String], reduction_indices: Annotated[Any, _atypes.Int32], keep_dims:bool=False, separator:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Joins a string Tensor across the given dimensions. + + Computes the string join across dimensions in the given string Tensor of shape + `[\\(d_0, d_1, ..., d_{n-1}\\)]`. Returns a new Tensor created by joining the input + strings with the given separator (default: empty string). Negative indices are + counted backwards from the end, with `-1` being equivalent to `n - 1`. If + indices are not specified, joins across all dimensions beginning from `n - 1` + through `0`. + + For example: + + ```python + # tensor `a` is [["a", "b"], ["c", "d"]] + tf.reduce_join(a, 0) ==> ["ac", "bd"] + tf.reduce_join(a, 1) ==> ["ab", "cd"] + tf.reduce_join(a, -2) = tf.reduce_join(a, 0) ==> ["ac", "bd"] + tf.reduce_join(a, -1) = tf.reduce_join(a, 1) ==> ["ab", "cd"] + tf.reduce_join(a, 0, keep_dims=True) ==> [["ac", "bd"]] + tf.reduce_join(a, 1, keep_dims=True) ==> [["ab"], ["cd"]] + tf.reduce_join(a, 0, separator=".") ==> ["a.c", "b.d"] + tf.reduce_join(a, [0, 1]) ==> "acbd" + tf.reduce_join(a, [1, 0]) ==> "abcd" + tf.reduce_join(a, []) ==> [["a", "b"], ["c", "d"]] + tf.reduce_join(a) = tf.reduce_join(a, [1, 0]) ==> "abcd" + ``` + + Args: + inputs: A `Tensor` of type `string`. + The input to be joined. All reduced indices must have non-zero size. + reduction_indices: A `Tensor` of type `int32`. + The dimensions to reduce over. Dimensions are reduced in the + order specified. Omitting `reduction_indices` is equivalent to passing + `[n-1, n-2, ..., 0]`. Negative indices from `-n` to `-1` are supported. + keep_dims: An optional `bool`. Defaults to `False`. + If `True`, retain reduced dimensions with length `1`. + separator: An optional `string`. Defaults to `""`. + The separator to use when joining. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReduceJoin", name, inputs, reduction_indices, "keep_dims", + keep_dims, "separator", separator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return reduce_join_eager_fallback( + inputs, reduction_indices, keep_dims=keep_dims, separator=separator, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReduceJoin", inputs=inputs, reduction_indices=reduction_indices, + keep_dims=keep_dims, separator=separator, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("keep_dims", _op._get_attr_bool("keep_dims"), "separator", + _op.get_attr("separator")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReduceJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ReduceJoin = tf_export("raw_ops.ReduceJoin")(_ops.to_raw_op(reduce_join)) + + +def reduce_join_eager_fallback(inputs: Annotated[Any, _atypes.String], reduction_indices: Annotated[Any, _atypes.Int32], keep_dims: bool, separator: str, name, ctx) -> Annotated[Any, _atypes.String]: + if keep_dims is None: + keep_dims = False + keep_dims = _execute.make_bool(keep_dims, "keep_dims") + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + inputs = _ops.convert_to_tensor(inputs, _dtypes.string) + reduction_indices = _ops.convert_to_tensor(reduction_indices, _dtypes.int32) + _inputs_flat = [inputs, reduction_indices] + _attrs = ("keep_dims", keep_dims, "separator", separator) + _result = _execute.execute(b"ReduceJoin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReduceJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def regex_full_match(input: Annotated[Any, _atypes.String], pattern: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.Bool]: + r"""Check if the input matches the regex pattern. + + The input is a string tensor of any shape. The pattern is a scalar + string tensor which is applied to every element of the input tensor. + The boolean values (True or False) of the output tensor indicate + if the input matches the regex pattern provided. + + The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) + + Examples: + + >>> tf.strings.regex_full_match(["TF lib", "lib TF"], ".*lib$") + + >>> tf.strings.regex_full_match(["TF lib", "lib TF"], ".*TF$") + + + Args: + input: A `Tensor` of type `string`. + A string tensor of the text to be processed. + pattern: A `Tensor` of type `string`. + A scalar string tensor containing the regular expression to match the input. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RegexFullMatch", name, input, pattern) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return regex_full_match_eager_fallback( + input, pattern, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RegexFullMatch", input=input, pattern=pattern, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RegexFullMatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RegexFullMatch = tf_export("raw_ops.RegexFullMatch")(_ops.to_raw_op(regex_full_match)) + + +def regex_full_match_eager_fallback(input: Annotated[Any, _atypes.String], pattern: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.Bool]: + input = _ops.convert_to_tensor(input, _dtypes.string) + pattern = _ops.convert_to_tensor(pattern, _dtypes.string) + _inputs_flat = [input, pattern] + _attrs = None + _result = _execute.execute(b"RegexFullMatch", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RegexFullMatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def regex_replace(input: Annotated[Any, _atypes.String], pattern: Annotated[Any, _atypes.String], rewrite: Annotated[Any, _atypes.String], replace_global:bool=True, name=None) -> Annotated[Any, _atypes.String]: + r"""Replaces matches of the `pattern` regular expression in `input` with the +replacement string provided in `rewrite`. + + It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) + + Args: + input: A `Tensor` of type `string`. The text to be processed. + pattern: A `Tensor` of type `string`. + The regular expression to be matched in the `input` strings. + rewrite: A `Tensor` of type `string`. + The rewrite string to be substituted for the `pattern` expression where it is + matched in the `input` strings. + replace_global: An optional `bool`. Defaults to `True`. + If True, the replacement is global (that is, all matches of the `pattern` regular + expression in each input string are rewritten), otherwise the `rewrite` + substitution is only made for the first `pattern` match. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RegexReplace", name, input, pattern, rewrite, "replace_global", + replace_global) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return regex_replace_eager_fallback( + input, pattern, rewrite, replace_global=replace_global, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if replace_global is None: + replace_global = True + replace_global = _execute.make_bool(replace_global, "replace_global") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RegexReplace", input=input, pattern=pattern, rewrite=rewrite, + replace_global=replace_global, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("replace_global", _op._get_attr_bool("replace_global")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RegexReplace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RegexReplace = tf_export("raw_ops.RegexReplace")(_ops.to_raw_op(regex_replace)) + + +def regex_replace_eager_fallback(input: Annotated[Any, _atypes.String], pattern: Annotated[Any, _atypes.String], rewrite: Annotated[Any, _atypes.String], replace_global: bool, name, ctx) -> Annotated[Any, _atypes.String]: + if replace_global is None: + replace_global = True + replace_global = _execute.make_bool(replace_global, "replace_global") + input = _ops.convert_to_tensor(input, _dtypes.string) + pattern = _ops.convert_to_tensor(pattern, _dtypes.string) + rewrite = _ops.convert_to_tensor(rewrite, _dtypes.string) + _inputs_flat = [input, pattern, rewrite] + _attrs = ("replace_global", replace_global) + _result = _execute.execute(b"RegexReplace", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RegexReplace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def static_regex_full_match(input: Annotated[Any, _atypes.String], pattern: str, name=None) -> Annotated[Any, _atypes.Bool]: + r"""Check if the input matches the regex pattern. + + The input is a string tensor of any shape. The pattern is the + regular expression to be matched with every element of the input tensor. + The boolean values (True or False) of the output tensor indicate + if the input matches the regex pattern provided. + + The pattern follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) + + Args: + input: A `Tensor` of type `string`. + A string tensor of the text to be processed. + pattern: A `string`. The regular expression to match the input. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StaticRegexFullMatch", name, input, "pattern", pattern) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return static_regex_full_match_eager_fallback( + input, pattern=pattern, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + pattern = _execute.make_str(pattern, "pattern") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StaticRegexFullMatch", input=input, pattern=pattern, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pattern", _op.get_attr("pattern")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StaticRegexFullMatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StaticRegexFullMatch = tf_export("raw_ops.StaticRegexFullMatch")(_ops.to_raw_op(static_regex_full_match)) + + +def static_regex_full_match_eager_fallback(input: Annotated[Any, _atypes.String], pattern: str, name, ctx) -> Annotated[Any, _atypes.Bool]: + pattern = _execute.make_str(pattern, "pattern") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("pattern", pattern) + _result = _execute.execute(b"StaticRegexFullMatch", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StaticRegexFullMatch", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def static_regex_replace(input: Annotated[Any, _atypes.String], pattern: str, rewrite: str, replace_global:bool=True, name=None) -> Annotated[Any, _atypes.String]: + r"""Replaces the match of pattern in input with rewrite. + + It follows the re2 syntax (https://github.com/google/re2/wiki/Syntax) + + Args: + input: A `Tensor` of type `string`. The text to be processed. + pattern: A `string`. The regular expression to match the input. + rewrite: A `string`. The rewrite to be applied to the matched expression. + replace_global: An optional `bool`. Defaults to `True`. + If True, the replacement is global, otherwise the replacement + is done only on the first match. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StaticRegexReplace", name, input, "pattern", pattern, + "rewrite", rewrite, "replace_global", replace_global) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return static_regex_replace_eager_fallback( + input, pattern=pattern, rewrite=rewrite, + replace_global=replace_global, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + pattern = _execute.make_str(pattern, "pattern") + rewrite = _execute.make_str(rewrite, "rewrite") + if replace_global is None: + replace_global = True + replace_global = _execute.make_bool(replace_global, "replace_global") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StaticRegexReplace", input=input, pattern=pattern, rewrite=rewrite, + replace_global=replace_global, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("pattern", _op.get_attr("pattern"), "rewrite", + _op.get_attr("rewrite"), "replace_global", + _op._get_attr_bool("replace_global")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StaticRegexReplace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StaticRegexReplace = tf_export("raw_ops.StaticRegexReplace")(_ops.to_raw_op(static_regex_replace)) + + +def static_regex_replace_eager_fallback(input: Annotated[Any, _atypes.String], pattern: str, rewrite: str, replace_global: bool, name, ctx) -> Annotated[Any, _atypes.String]: + pattern = _execute.make_str(pattern, "pattern") + rewrite = _execute.make_str(rewrite, "rewrite") + if replace_global is None: + replace_global = True + replace_global = _execute.make_bool(replace_global, "replace_global") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("pattern", pattern, "rewrite", rewrite, "replace_global", + replace_global) + _result = _execute.execute(b"StaticRegexReplace", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StaticRegexReplace", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def string_format(inputs, template:str="%s", placeholder:str="%s", summarize:int=3, name=None) -> Annotated[Any, _atypes.String]: + r"""Formats a string template using a list of tensors. + + Formats a string template using a list of tensors, pretty-printing tensor summaries. + + Args: + inputs: A list of `Tensor` objects. + The list of tensors to format into the placeholder string. + template: An optional `string`. Defaults to `"%s"`. + A string, the template to format tensor summaries into. + placeholder: An optional `string`. Defaults to `"%s"`. + A string, at each placeholder in the template a subsequent tensor summary will be inserted. + summarize: An optional `int`. Defaults to `3`. + When formatting the tensor summaries print the first and last summarize entries of each tensor dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringFormat", name, inputs, "template", template, + "placeholder", placeholder, "summarize", summarize) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_format_eager_fallback( + inputs, template=template, placeholder=placeholder, + summarize=summarize, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if template is None: + template = "%s" + template = _execute.make_str(template, "template") + if placeholder is None: + placeholder = "%s" + placeholder = _execute.make_str(placeholder, "placeholder") + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringFormat", inputs=inputs, template=template, + placeholder=placeholder, summarize=summarize, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T"), "template", _op.get_attr("template"), + "placeholder", _op.get_attr("placeholder"), "summarize", + _op._get_attr_int("summarize")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringFormat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringFormat = tf_export("raw_ops.StringFormat")(_ops.to_raw_op(string_format)) + + +def string_format_eager_fallback(inputs, template: str, placeholder: str, summarize: int, name, ctx) -> Annotated[Any, _atypes.String]: + if template is None: + template = "%s" + template = _execute.make_str(template, "template") + if placeholder is None: + placeholder = "%s" + placeholder = _execute.make_str(placeholder, "placeholder") + if summarize is None: + summarize = 3 + summarize = _execute.make_int(summarize, "summarize") + _attr_T, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx) + _inputs_flat = list(inputs) + _attrs = ("T", _attr_T, "template", template, "placeholder", placeholder, + "summarize", summarize) + _result = _execute.execute(b"StringFormat", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringFormat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def string_join(inputs: Annotated[List[Any], _atypes.String], separator:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Joins the strings in the given list of string tensors into one tensor; + + with the given separator (default is an empty separator). + + Examples: + + >>> s = ["hello", "world", "tensorflow"] + >>> tf.strings.join(s, " ") + + + Args: + inputs: A list of `Tensor` objects with type `string`. + A list of string tensors. The tensors must all have the same shape, + or be scalars. Scalars may be mixed in; these will be broadcast to the shape + of non-scalar inputs. + separator: An optional `string`. Defaults to `""`. + string, an optional join separator. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringJoin", name, inputs, "separator", separator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_join_eager_fallback( + inputs, separator=separator, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'string_join' Op, not %r." % inputs) + _attr_N = len(inputs) + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringJoin", inputs=inputs, separator=separator, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "separator", + _op.get_attr("separator")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringJoin = tf_export("raw_ops.StringJoin")(_ops.to_raw_op(string_join)) + + +def string_join_eager_fallback(inputs: Annotated[List[Any], _atypes.String], separator: str, name, ctx) -> Annotated[Any, _atypes.String]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'string_join' Op, not %r." % inputs) + _attr_N = len(inputs) + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + inputs = _ops.convert_n_to_tensor(inputs, _dtypes.string) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "separator", separator) + _result = _execute.execute(b"StringJoin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def string_length(input: Annotated[Any, _atypes.String], unit:str="BYTE", name=None) -> Annotated[Any, _atypes.Int32]: + r"""String lengths of `input`. + + Computes the length of each string given in the input tensor. + + >>> strings = tf.constant(['Hello','TensorFlow', '\U0001F642']) + >>> tf.strings.length(strings).numpy() # default counts bytes + array([ 5, 10, 4], dtype=int32) + >>> tf.strings.length(strings, unit="UTF8_CHAR").numpy() + array([ 5, 10, 1], dtype=int32) + + Args: + input: A `Tensor` of type `string`. + The strings for which to compute the length for each element. + unit: An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to `"BYTE"`. + The unit that is counted to compute string length. One of: `"BYTE"` (for + the number of bytes in each string) or `"UTF8_CHAR"` (for the number of UTF-8 + encoded Unicode code points in each string). Results are undefined + if `unit=UTF8_CHAR` and the `input` strings do not contain structurally + valid UTF-8. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringLength", name, input, "unit", unit) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_length_eager_fallback( + input, unit=unit, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if unit is None: + unit = "BYTE" + unit = _execute.make_str(unit, "unit") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringLength", input=input, unit=unit, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("unit", _op.get_attr("unit")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringLength", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringLength = tf_export("raw_ops.StringLength")(_ops.to_raw_op(string_length)) + + +def string_length_eager_fallback(input: Annotated[Any, _atypes.String], unit: str, name, ctx) -> Annotated[Any, _atypes.Int32]: + if unit is None: + unit = "BYTE" + unit = _execute.make_str(unit, "unit") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("unit", unit) + _result = _execute.execute(b"StringLength", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringLength", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.lower') +def string_lower(input: Annotated[Any, _atypes.String], encoding:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Converts all uppercase characters into their respective lowercase replacements. + + Example: + + >>> tf.strings.lower("CamelCase string and ALL CAPS") + + + Args: + input: A `Tensor` of type `string`. The input to be lower-cased. + encoding: An optional `string`. Defaults to `""`. + Character encoding of `input`. Allowed values are '' and 'utf-8'. + Value '' is interpreted as ASCII. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringLower", name, input, "encoding", encoding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_lower( + (input, encoding, name,), None) + if _result is not NotImplemented: + return _result + return string_lower_eager_fallback( + input, encoding=encoding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_lower, (), dict(input=input, encoding=encoding, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_lower( + (input, encoding, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringLower", input=input, encoding=encoding, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_lower, (), dict(input=input, encoding=encoding, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("encoding", _op.get_attr("encoding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringLower", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringLower = tf_export("raw_ops.StringLower")(_ops.to_raw_op(string_lower)) +_dispatcher_for_string_lower = string_lower._tf_type_based_dispatcher.Dispatch + + +def string_lower_eager_fallback(input: Annotated[Any, _atypes.String], encoding: str, name, ctx) -> Annotated[Any, _atypes.String]: + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("encoding", encoding) + _result = _execute.execute(b"StringLower", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringLower", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_StringNGramsOutput = collections.namedtuple( + "StringNGrams", + ["ngrams", "ngrams_splits"]) + + +TV_StringNGrams_Tsplits = TypeVar("TV_StringNGrams_Tsplits", _atypes.Int32, _atypes.Int64) + +def string_n_grams(data: Annotated[Any, _atypes.String], data_splits: Annotated[Any, TV_StringNGrams_Tsplits], separator: str, ngram_widths, left_pad: str, right_pad: str, pad_width: int, preserve_short_sequences: bool, name=None): + r"""Creates ngrams from ragged string data. + + This op accepts a ragged tensor with 1 ragged dimension containing only + strings and outputs a ragged tensor with 1 ragged dimension containing ngrams + of that string, joined along the innermost axis. + + Args: + data: A `Tensor` of type `string`. + The values tensor of the ragged string tensor to make ngrams out of. Must be a + 1D string tensor. + data_splits: A `Tensor`. Must be one of the following types: `int32`, `int64`. + The splits tensor of the ragged string tensor to make ngrams out of. + separator: A `string`. + The string to append between elements of the token. Use "" for no separator. + ngram_widths: A list of `ints`. The sizes of the ngrams to create. + left_pad: A `string`. + The string to use to pad the left side of the ngram sequence. Only used if + pad_width != 0. + right_pad: A `string`. + The string to use to pad the right side of the ngram sequence. Only used if + pad_width != 0. + pad_width: An `int`. + The number of padding elements to add to each side of each + sequence. Note that padding will never be greater than 'ngram_widths'-1 + regardless of this value. If `pad_width=-1`, then add `max(ngram_widths)-1` + elements. + preserve_short_sequences: A `bool`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (ngrams, ngrams_splits). + + ngrams: A `Tensor` of type `string`. + ngrams_splits: A `Tensor`. Has the same type as `data_splits`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringNGrams", name, data, data_splits, "separator", separator, + "ngram_widths", ngram_widths, "left_pad", left_pad, "right_pad", + right_pad, "pad_width", pad_width, "preserve_short_sequences", + preserve_short_sequences) + _result = _StringNGramsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_n_grams_eager_fallback( + data, data_splits, separator=separator, ngram_widths=ngram_widths, + left_pad=left_pad, right_pad=right_pad, pad_width=pad_width, + preserve_short_sequences=preserve_short_sequences, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + separator = _execute.make_str(separator, "separator") + if not isinstance(ngram_widths, (list, tuple)): + raise TypeError( + "Expected list for 'ngram_widths' argument to " + "'string_n_grams' Op, not %r." % ngram_widths) + ngram_widths = [_execute.make_int(_i, "ngram_widths") for _i in ngram_widths] + left_pad = _execute.make_str(left_pad, "left_pad") + right_pad = _execute.make_str(right_pad, "right_pad") + pad_width = _execute.make_int(pad_width, "pad_width") + preserve_short_sequences = _execute.make_bool(preserve_short_sequences, "preserve_short_sequences") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringNGrams", data=data, data_splits=data_splits, + separator=separator, ngram_widths=ngram_widths, + left_pad=left_pad, right_pad=right_pad, + pad_width=pad_width, + preserve_short_sequences=preserve_short_sequences, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("separator", _op.get_attr("separator"), "ngram_widths", + _op.get_attr("ngram_widths"), "left_pad", + _op.get_attr("left_pad"), "right_pad", + _op.get_attr("right_pad"), "pad_width", + _op._get_attr_int("pad_width"), "preserve_short_sequences", + _op._get_attr_bool("preserve_short_sequences"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringNGrams", _inputs_flat, _attrs, _result) + _result = _StringNGramsOutput._make(_result) + return _result + +StringNGrams = tf_export("raw_ops.StringNGrams")(_ops.to_raw_op(string_n_grams)) + + +def string_n_grams_eager_fallback(data: Annotated[Any, _atypes.String], data_splits: Annotated[Any, TV_StringNGrams_Tsplits], separator: str, ngram_widths, left_pad: str, right_pad: str, pad_width: int, preserve_short_sequences: bool, name, ctx): + separator = _execute.make_str(separator, "separator") + if not isinstance(ngram_widths, (list, tuple)): + raise TypeError( + "Expected list for 'ngram_widths' argument to " + "'string_n_grams' Op, not %r." % ngram_widths) + ngram_widths = [_execute.make_int(_i, "ngram_widths") for _i in ngram_widths] + left_pad = _execute.make_str(left_pad, "left_pad") + right_pad = _execute.make_str(right_pad, "right_pad") + pad_width = _execute.make_int(pad_width, "pad_width") + preserve_short_sequences = _execute.make_bool(preserve_short_sequences, "preserve_short_sequences") + _attr_Tsplits, (data_splits,) = _execute.args_to_matching_eager([data_splits], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + data = _ops.convert_to_tensor(data, _dtypes.string) + _inputs_flat = [data, data_splits] + _attrs = ("separator", separator, "ngram_widths", ngram_widths, "left_pad", + left_pad, "right_pad", right_pad, "pad_width", pad_width, + "preserve_short_sequences", preserve_short_sequences, "Tsplits", + _attr_Tsplits) + _result = _execute.execute(b"StringNGrams", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringNGrams", _inputs_flat, _attrs, _result) + _result = _StringNGramsOutput._make(_result) + return _result + +_StringSplitOutput = collections.namedtuple( + "StringSplit", + ["indices", "values", "shape"]) + + +def string_split(input: Annotated[Any, _atypes.String], delimiter: Annotated[Any, _atypes.String], skip_empty:bool=True, name=None): + r"""Split elements of `input` based on `delimiter` into a `SparseTensor`. + + Let N be the size of source (typically N will be the batch size). Split each + element of `input` based on `delimiter` and return a `SparseTensor` + containing the splitted tokens. Empty tokens are ignored. + + `delimiter` can be empty, or a string of split characters. If `delimiter` is an + empty string, each element of `input` is split into individual single-byte + character strings, including splitting of UTF-8 multibyte sequences. Otherwise + every character of `delimiter` is a potential split point. + + For example: + N = 2, input[0] is 'hello world' and input[1] is 'a b c', then the output + will be + + indices = [0, 0; + 0, 1; + 1, 0; + 1, 1; + 1, 2] + shape = [2, 3] + values = ['hello', 'world', 'a', 'b', 'c'] + + Args: + input: A `Tensor` of type `string`. 1-D. Strings to split. + delimiter: A `Tensor` of type `string`. + 0-D. Delimiter characters (bytes), or empty string. + skip_empty: An optional `bool`. Defaults to `True`. + A `bool`. If `True`, skip the empty strings from the result. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, values, shape). + + indices: A `Tensor` of type `int64`. + values: A `Tensor` of type `string`. + shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringSplit", name, input, delimiter, "skip_empty", skip_empty) + _result = _StringSplitOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_split_eager_fallback( + input, delimiter, skip_empty=skip_empty, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if skip_empty is None: + skip_empty = True + skip_empty = _execute.make_bool(skip_empty, "skip_empty") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringSplit", input=input, delimiter=delimiter, + skip_empty=skip_empty, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("skip_empty", _op._get_attr_bool("skip_empty")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringSplit", _inputs_flat, _attrs, _result) + _result = _StringSplitOutput._make(_result) + return _result + +StringSplit = tf_export("raw_ops.StringSplit")(_ops.to_raw_op(string_split)) + + +def string_split_eager_fallback(input: Annotated[Any, _atypes.String], delimiter: Annotated[Any, _atypes.String], skip_empty: bool, name, ctx): + if skip_empty is None: + skip_empty = True + skip_empty = _execute.make_bool(skip_empty, "skip_empty") + input = _ops.convert_to_tensor(input, _dtypes.string) + delimiter = _ops.convert_to_tensor(delimiter, _dtypes.string) + _inputs_flat = [input, delimiter] + _attrs = ("skip_empty", skip_empty) + _result = _execute.execute(b"StringSplit", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringSplit", _inputs_flat, _attrs, _result) + _result = _StringSplitOutput._make(_result) + return _result + +_StringSplitV2Output = collections.namedtuple( + "StringSplitV2", + ["indices", "values", "shape"]) + + +def string_split_v2(input: Annotated[Any, _atypes.String], sep: Annotated[Any, _atypes.String], maxsplit:int=-1, name=None): + r"""Split elements of `source` based on `sep` into a `SparseTensor`. + + Let N be the size of source (typically N will be the batch size). Split each + element of `source` based on `sep` and return a `SparseTensor` + containing the split tokens. Empty tokens are ignored. + + For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c', + then the output will be + ``` + st.indices = [0, 0; + 0, 1; + 1, 0; + 1, 1; + 1, 2] + st.shape = [2, 3] + st.values = ['hello', 'world', 'a', 'b', 'c'] + ``` + + If `sep` is given, consecutive delimiters are not grouped together and are + deemed to delimit empty strings. For example, source of `"1<>2<><>3"` and + sep of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty + string, consecutive whitespace are regarded as a single separator, and the + result will contain no empty strings at the startor end if the string has + leading or trailing whitespace. + + Note that the above mentioned behavior matches python's str.split. + + Args: + input: A `Tensor` of type `string`. + `1-D` string `Tensor`, the strings to split. + sep: A `Tensor` of type `string`. + `0-D` string `Tensor`, the delimiter character. + maxsplit: An optional `int`. Defaults to `-1`. + An `int`. If `maxsplit > 0`, limit of the split of the result. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, values, shape). + + indices: A `Tensor` of type `int64`. + values: A `Tensor` of type `string`. + shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringSplitV2", name, input, sep, "maxsplit", maxsplit) + _result = _StringSplitV2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_split_v2_eager_fallback( + input, sep, maxsplit=maxsplit, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if maxsplit is None: + maxsplit = -1 + maxsplit = _execute.make_int(maxsplit, "maxsplit") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringSplitV2", input=input, sep=sep, maxsplit=maxsplit, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("maxsplit", _op._get_attr_int("maxsplit")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringSplitV2", _inputs_flat, _attrs, _result) + _result = _StringSplitV2Output._make(_result) + return _result + +StringSplitV2 = tf_export("raw_ops.StringSplitV2")(_ops.to_raw_op(string_split_v2)) + + +def string_split_v2_eager_fallback(input: Annotated[Any, _atypes.String], sep: Annotated[Any, _atypes.String], maxsplit: int, name, ctx): + if maxsplit is None: + maxsplit = -1 + maxsplit = _execute.make_int(maxsplit, "maxsplit") + input = _ops.convert_to_tensor(input, _dtypes.string) + sep = _ops.convert_to_tensor(sep, _dtypes.string) + _inputs_flat = [input, sep] + _attrs = ("maxsplit", maxsplit) + _result = _execute.execute(b"StringSplitV2", 3, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringSplitV2", _inputs_flat, _attrs, _result) + _result = _StringSplitV2Output._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.strip', v1=['strings.strip', 'string_strip']) +@deprecated_endpoints('string_strip') +def string_strip(input: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Strip leading and trailing whitespaces from the Tensor. + + Examples: + + >>> tf.strings.strip(["\nTensorFlow", " The python library "]).numpy() + array([b'TensorFlow', b'The python library'], dtype=object) + + Args: + input: A `Tensor` of type `string`. A string `Tensor` of any shape. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringStrip", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_strip( + (input, name,), None) + if _result is not NotImplemented: + return _result + return string_strip_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_strip, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_strip( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringStrip", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_strip, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringStrip", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringStrip = tf_export("raw_ops.StringStrip")(_ops.to_raw_op(string_strip)) +_dispatcher_for_string_strip = string_strip._tf_type_based_dispatcher.Dispatch + + +def string_strip_eager_fallback(input: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"StringStrip", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringStrip", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def string_to_hash_bucket(string_tensor: Annotated[Any, _atypes.String], num_buckets: int, name=None) -> Annotated[Any, _atypes.Int64]: + r"""Converts each string in the input Tensor to its hash mod by a number of buckets. + + The hash function is deterministic on the content of the string within the + process. + + Note that the hash function may change from time to time. + This functionality will be deprecated and it's recommended to use + `tf.string_to_hash_bucket_fast()` or `tf.string_to_hash_bucket_strong()`. + + Args: + string_tensor: A `Tensor` of type `string`. + num_buckets: An `int` that is `>= 1`. The number of buckets. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringToHashBucket", name, string_tensor, "num_buckets", + num_buckets) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return string_to_hash_bucket_eager_fallback( + string_tensor, num_buckets=num_buckets, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_buckets = _execute.make_int(num_buckets, "num_buckets") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringToHashBucket", string_tensor=string_tensor, + num_buckets=num_buckets, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_buckets", _op._get_attr_int("num_buckets")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringToHashBucket", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringToHashBucket = tf_export("raw_ops.StringToHashBucket")(_ops.to_raw_op(string_to_hash_bucket)) + + +def string_to_hash_bucket_eager_fallback(string_tensor: Annotated[Any, _atypes.String], num_buckets: int, name, ctx) -> Annotated[Any, _atypes.Int64]: + num_buckets = _execute.make_int(num_buckets, "num_buckets") + string_tensor = _ops.convert_to_tensor(string_tensor, _dtypes.string) + _inputs_flat = [string_tensor] + _attrs = ("num_buckets", num_buckets) + _result = _execute.execute(b"StringToHashBucket", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringToHashBucket", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.to_hash_bucket_fast', v1=['strings.to_hash_bucket_fast', 'string_to_hash_bucket_fast']) +@deprecated_endpoints('string_to_hash_bucket_fast') +def string_to_hash_bucket_fast(input: Annotated[Any, _atypes.String], num_buckets: int, name=None) -> Annotated[Any, _atypes.Int64]: + r"""Converts each string in the input Tensor to its hash mod by a number of buckets. + + The hash function is deterministic on the content of the string within the + process and will never change. However, it is not suitable for cryptography. + This function may be used when CPU time is scarce and inputs are trusted or + unimportant. There is a risk of adversaries constructing inputs that all hash + to the same bucket. To prevent this problem, use a strong hash function with + `tf.string_to_hash_bucket_strong`. + + Examples: + + >>> tf.strings.to_hash_bucket_fast(["Hello", "TensorFlow", "2.x"], 3).numpy() + array([0, 2, 2]) + + Args: + input: A `Tensor` of type `string`. The strings to assign a hash bucket. + num_buckets: An `int` that is `>= 1`. The number of buckets. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringToHashBucketFast", name, input, "num_buckets", + num_buckets) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_to_hash_bucket_fast( + (input, num_buckets, name,), None) + if _result is not NotImplemented: + return _result + return string_to_hash_bucket_fast_eager_fallback( + input, num_buckets=num_buckets, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_to_hash_bucket_fast, (), dict(input=input, + num_buckets=num_buckets, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_to_hash_bucket_fast( + (input, num_buckets, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + num_buckets = _execute.make_int(num_buckets, "num_buckets") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringToHashBucketFast", input=input, num_buckets=num_buckets, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_to_hash_bucket_fast, (), dict(input=input, + num_buckets=num_buckets, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_buckets", _op._get_attr_int("num_buckets")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringToHashBucketFast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringToHashBucketFast = tf_export("raw_ops.StringToHashBucketFast")(_ops.to_raw_op(string_to_hash_bucket_fast)) +_dispatcher_for_string_to_hash_bucket_fast = string_to_hash_bucket_fast._tf_type_based_dispatcher.Dispatch + + +def string_to_hash_bucket_fast_eager_fallback(input: Annotated[Any, _atypes.String], num_buckets: int, name, ctx) -> Annotated[Any, _atypes.Int64]: + num_buckets = _execute.make_int(num_buckets, "num_buckets") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("num_buckets", num_buckets) + _result = _execute.execute(b"StringToHashBucketFast", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringToHashBucketFast", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.to_hash_bucket_strong', v1=['strings.to_hash_bucket_strong', 'string_to_hash_bucket_strong']) +@deprecated_endpoints('string_to_hash_bucket_strong') +def string_to_hash_bucket_strong(input: Annotated[Any, _atypes.String], num_buckets: int, key, name=None) -> Annotated[Any, _atypes.Int64]: + r"""Converts each string in the input Tensor to its hash mod by a number of buckets. + + The hash function is deterministic on the content of the string within the + process. The hash function is a keyed hash function, where attribute `key` + defines the key of the hash function. `key` is an array of 2 elements. + + A strong hash is important when inputs may be malicious, e.g. URLs with + additional components. Adversaries could try to make their inputs hash to the + same bucket for a denial-of-service attack or to skew the results. A strong + hash can be used to make it difficult to find inputs with a skewed hash value + distribution over buckets. This requires that the hash function is + seeded by a high-entropy (random) "key" unknown to the adversary. + + The additional robustness comes at a cost of roughly 4x higher compute + time than `tf.string_to_hash_bucket_fast`. + + Examples: + + >>> tf.strings.to_hash_bucket_strong(["Hello", "TF"], 3, [1, 2]).numpy() + array([2, 0]) + + Args: + input: A `Tensor` of type `string`. The strings to assign a hash bucket. + num_buckets: An `int` that is `>= 1`. The number of buckets. + key: A list of `ints`. + The key used to seed the hash function, passed as a list of two uint64 + elements. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringToHashBucketStrong", name, input, "num_buckets", + num_buckets, "key", key) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_to_hash_bucket_strong( + (input, num_buckets, key, name,), None) + if _result is not NotImplemented: + return _result + return string_to_hash_bucket_strong_eager_fallback( + input, num_buckets=num_buckets, key=key, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_to_hash_bucket_strong, (), dict(input=input, + num_buckets=num_buckets, + key=key, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_to_hash_bucket_strong( + (input, num_buckets, key, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + num_buckets = _execute.make_int(num_buckets, "num_buckets") + if not isinstance(key, (list, tuple)): + raise TypeError( + "Expected list for 'key' argument to " + "'string_to_hash_bucket_strong' Op, not %r." % key) + key = [_execute.make_int(_i, "key") for _i in key] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringToHashBucketStrong", input=input, num_buckets=num_buckets, + key=key, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_to_hash_bucket_strong, (), dict(input=input, + num_buckets=num_buckets, + key=key, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_buckets", _op._get_attr_int("num_buckets"), "key", + _op.get_attr("key")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringToHashBucketStrong", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringToHashBucketStrong = tf_export("raw_ops.StringToHashBucketStrong")(_ops.to_raw_op(string_to_hash_bucket_strong)) +_dispatcher_for_string_to_hash_bucket_strong = string_to_hash_bucket_strong._tf_type_based_dispatcher.Dispatch + + +def string_to_hash_bucket_strong_eager_fallback(input: Annotated[Any, _atypes.String], num_buckets: int, key, name, ctx) -> Annotated[Any, _atypes.Int64]: + num_buckets = _execute.make_int(num_buckets, "num_buckets") + if not isinstance(key, (list, tuple)): + raise TypeError( + "Expected list for 'key' argument to " + "'string_to_hash_bucket_strong' Op, not %r." % key) + key = [_execute.make_int(_i, "key") for _i in key] + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("num_buckets", num_buckets, "key", key) + _result = _execute.execute(b"StringToHashBucketStrong", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringToHashBucketStrong", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.upper') +def string_upper(input: Annotated[Any, _atypes.String], encoding:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""Converts all lowercase characters into their respective uppercase replacements. + + Example: + + >>> tf.strings.upper("CamelCase string and ALL CAPS") + + + Args: + input: A `Tensor` of type `string`. The input to be upper-cased. + encoding: An optional `string`. Defaults to `""`. + Character encoding of `input`. Allowed values are '' and 'utf-8'. + Value '' is interpreted as ASCII. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringUpper", name, input, "encoding", encoding) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_upper( + (input, encoding, name,), None) + if _result is not NotImplemented: + return _result + return string_upper_eager_fallback( + input, encoding=encoding, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_upper, (), dict(input=input, encoding=encoding, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_upper( + (input, encoding, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringUpper", input=input, encoding=encoding, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_upper, (), dict(input=input, encoding=encoding, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("encoding", _op.get_attr("encoding")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StringUpper", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StringUpper = tf_export("raw_ops.StringUpper")(_ops.to_raw_op(string_upper)) +_dispatcher_for_string_upper = string_upper._tf_type_based_dispatcher.Dispatch + + +def string_upper_eager_fallback(input: Annotated[Any, _atypes.String], encoding: str, name, ctx) -> Annotated[Any, _atypes.String]: + if encoding is None: + encoding = "" + encoding = _execute.make_str(encoding, "encoding") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("encoding", encoding) + _result = _execute.execute(b"StringUpper", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StringUpper", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Substr_T = TypeVar("TV_Substr_T", _atypes.Int32, _atypes.Int64) + +def substr(input: Annotated[Any, _atypes.String], pos: Annotated[Any, TV_Substr_T], len: Annotated[Any, TV_Substr_T], unit:str="BYTE", name=None) -> Annotated[Any, _atypes.String]: + r"""Return substrings from `Tensor` of strings. + + For each string in the input `Tensor`, creates a substring starting at index + `pos` with a total length of `len`. + + If `len` defines a substring that would extend beyond the length of the input + string, or if `len` is negative, then as many characters as possible are used. + + A negative `pos` indicates distance within the string backwards from the end. + + If `pos` specifies an index which is out of range for any of the input strings, + then an `InvalidArgumentError` is thrown. + + `pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on + Op creation. + + *NOTE*: `Substr` supports broadcasting up to two dimensions. More about + broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + --- + + Examples + + Using scalar `pos` and `len`: + + ```python + input = [b'Hello', b'World'] + position = 1 + length = 3 + + output = [b'ell', b'orl'] + ``` + + Using `pos` and `len` with same shape as `input`: + + ```python + input = [[b'ten', b'eleven', b'twelve'], + [b'thirteen', b'fourteen', b'fifteen'], + [b'sixteen', b'seventeen', b'eighteen']] + position = [[1, 2, 3], + [1, 2, 3], + [1, 2, 3]] + length = [[2, 3, 4], + [4, 3, 2], + [5, 5, 5]] + + output = [[b'en', b'eve', b'lve'], + [b'hirt', b'urt', b'te'], + [b'ixtee', b'vente', b'hteen']] + ``` + + Broadcasting `pos` and `len` onto `input`: + + ``` + input = [[b'ten', b'eleven', b'twelve'], + [b'thirteen', b'fourteen', b'fifteen'], + [b'sixteen', b'seventeen', b'eighteen'], + [b'nineteen', b'twenty', b'twentyone']] + position = [1, 2, 3] + length = [1, 2, 3] + + output = [[b'e', b'ev', b'lve'], + [b'h', b'ur', b'tee'], + [b'i', b've', b'hte'], + [b'i', b'en', b'nty']] + ``` + + Broadcasting `input` onto `pos` and `len`: + + ``` + input = b'thirteen' + position = [1, 5, 7] + length = [3, 2, 1] + + output = [b'hir', b'ee', b'n'] + ``` + + Raises: + + * `ValueError`: If the first argument cannot be converted to a + Tensor of `dtype string`. + * `InvalidArgumentError`: If indices are out of range. + * `ValueError`: If `pos` and `len` are not the same shape. + + Args: + input: A `Tensor` of type `string`. Tensor of strings + pos: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Scalar defining the position of first character in each substring + len: A `Tensor`. Must have the same type as `pos`. + Scalar defining the number of characters to include in each substring + unit: An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to `"BYTE"`. + The unit that is used to create the substring. One of: `"BYTE"` (for + defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 + encoded Unicode code points). The default is `"BYTE"`. Results are undefined if + `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid + UTF-8. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Substr", name, input, pos, len, "unit", unit) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return substr_eager_fallback( + input, pos, len, unit=unit, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if unit is None: + unit = "BYTE" + unit = _execute.make_str(unit, "unit") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Substr", input=input, pos=pos, len=len, unit=unit, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "unit", _op.get_attr("unit")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Substr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Substr = tf_export("raw_ops.Substr")(_ops.to_raw_op(substr)) + + +def substr_eager_fallback(input: Annotated[Any, _atypes.String], pos: Annotated[Any, TV_Substr_T], len: Annotated[Any, TV_Substr_T], unit: str, name, ctx) -> Annotated[Any, _atypes.String]: + if unit is None: + unit = "BYTE" + unit = _execute.make_str(unit, "unit") + _attr_T, _inputs_T = _execute.args_to_matching_eager([pos, len], ctx, [_dtypes.int32, _dtypes.int64, ]) + (pos, len) = _inputs_T + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input, pos, len] + _attrs = ("T", _attr_T, "unit", unit) + _result = _execute.execute(b"Substr", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Substr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_UnicodeDecodeOutput = collections.namedtuple( + "UnicodeDecode", + ["row_splits", "char_values"]) + + +TV_UnicodeDecode_Tsplits = TypeVar("TV_UnicodeDecode_Tsplits", _atypes.Int32, _atypes.Int64) + +def unicode_decode(input: Annotated[Any, _atypes.String], input_encoding: str, errors:str="replace", replacement_char:int=65533, replace_control_characters:bool=False, Tsplits:TV_UnicodeDecode_Tsplits=_dtypes.int64, name=None): + r"""Decodes each string in `input` into a sequence of Unicode code points. + + The character codepoints for all strings are returned using a single vector + `char_values`, with strings expanded to characters in row-major order. + + The `row_splits` tensor indicates where the codepoints for + each input string begin and end within the `char_values` tensor. + In particular, the values for the `i`th + string (in row-major order) are stored in the slice + `[row_splits[i]:row_splits[i+1]]`. Thus: + + * `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th + character in the `i`th string (in row-major order). + * `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th + string (in row-major order). + + Args: + input: A `Tensor` of type `string`. + The text to be decoded. Can have any shape. Note that the output is flattened + to a vector of char values. + input_encoding: A `string`. + Text encoding of the input strings. This is any of the encodings supported + by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. + errors: An optional `string` from: `"strict", "replace", "ignore"`. Defaults to `"replace"`. + Error handling policy when there is invalid formatting found in the input. + The value of 'strict' will cause the operation to produce a InvalidArgument + error on any invalid input formatting. A value of 'replace' (the default) will + cause the operation to replace any invalid formatting in the input with the + `replacement_char` codepoint. A value of 'ignore' will cause the operation to + skip any invalid formatting in the input and produce no corresponding output + character. + replacement_char: An optional `int`. Defaults to `65533`. + The replacement character codepoint to be used in place of any invalid + formatting in the input when `errors='replace'`. Any valid unicode codepoint may + be used. The default value is the default unicode replacement character is + 0xFFFD or U+65533.) + replace_control_characters: An optional `bool`. Defaults to `False`. + Whether to replace the C0 control characters (00-1F) with the + `replacement_char`. Default is false. + Tsplits: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (row_splits, char_values). + + row_splits: A `Tensor` of type `Tsplits`. + char_values: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnicodeDecode", name, input, "input_encoding", input_encoding, + "errors", errors, "replacement_char", replacement_char, + "replace_control_characters", replace_control_characters, "Tsplits", + Tsplits) + _result = _UnicodeDecodeOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unicode_decode_eager_fallback( + input, input_encoding=input_encoding, errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + Tsplits=Tsplits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + input_encoding = _execute.make_str(input_encoding, "input_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnicodeDecode", input=input, input_encoding=input_encoding, + errors=errors, replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + Tsplits=Tsplits, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("input_encoding", _op.get_attr("input_encoding"), "errors", + _op.get_attr("errors"), "replacement_char", + _op._get_attr_int("replacement_char"), + "replace_control_characters", + _op._get_attr_bool("replace_control_characters"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnicodeDecode", _inputs_flat, _attrs, _result) + _result = _UnicodeDecodeOutput._make(_result) + return _result + +UnicodeDecode = tf_export("raw_ops.UnicodeDecode")(_ops.to_raw_op(unicode_decode)) + + +def unicode_decode_eager_fallback(input: Annotated[Any, _atypes.String], input_encoding: str, errors: str, replacement_char: int, replace_control_characters: bool, Tsplits: TV_UnicodeDecode_Tsplits, name, ctx): + input_encoding = _execute.make_str(input_encoding, "input_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("input_encoding", input_encoding, "errors", errors, + "replacement_char", replacement_char, "replace_control_characters", + replace_control_characters, "Tsplits", Tsplits) + _result = _execute.execute(b"UnicodeDecode", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnicodeDecode", _inputs_flat, _attrs, _result) + _result = _UnicodeDecodeOutput._make(_result) + return _result + +_UnicodeDecodeWithOffsetsOutput = collections.namedtuple( + "UnicodeDecodeWithOffsets", + ["row_splits", "char_values", "char_to_byte_starts"]) + + +TV_UnicodeDecodeWithOffsets_Tsplits = TypeVar("TV_UnicodeDecodeWithOffsets_Tsplits", _atypes.Int32, _atypes.Int64) + +def unicode_decode_with_offsets(input: Annotated[Any, _atypes.String], input_encoding: str, errors:str="replace", replacement_char:int=65533, replace_control_characters:bool=False, Tsplits:TV_UnicodeDecodeWithOffsets_Tsplits=_dtypes.int64, name=None): + r"""Decodes each string in `input` into a sequence of Unicode code points. + + The character codepoints for all strings are returned using a single vector + `char_values`, with strings expanded to characters in row-major order. + Similarly, the character start byte offsets are returned using a single vector + `char_to_byte_starts`, with strings expanded in row-major order. + + The `row_splits` tensor indicates where the codepoints and start offsets for + each input string begin and end within the `char_values` and + `char_to_byte_starts` tensors. In particular, the values for the `i`th + string (in row-major order) are stored in the slice + `[row_splits[i]:row_splits[i+1]]`. Thus: + + * `char_values[row_splits[i]+j]` is the Unicode codepoint for the `j`th + character in the `i`th string (in row-major order). + * `char_to_bytes_starts[row_splits[i]+j]` is the start byte offset for the `j`th + character in the `i`th string (in row-major order). + * `row_splits[i+1] - row_splits[i]` is the number of characters in the `i`th + string (in row-major order). + + Args: + input: A `Tensor` of type `string`. + The text to be decoded. Can have any shape. Note that the output is flattened + to a vector of char values. + input_encoding: A `string`. + Text encoding of the input strings. This is any of the encodings supported + by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. + errors: An optional `string` from: `"strict", "replace", "ignore"`. Defaults to `"replace"`. + Error handling policy when there is invalid formatting found in the input. + The value of 'strict' will cause the operation to produce a InvalidArgument + error on any invalid input formatting. A value of 'replace' (the default) will + cause the operation to replace any invalid formatting in the input with the + `replacement_char` codepoint. A value of 'ignore' will cause the operation to + skip any invalid formatting in the input and produce no corresponding output + character. + replacement_char: An optional `int`. Defaults to `65533`. + The replacement character codepoint to be used in place of any invalid + formatting in the input when `errors='replace'`. Any valid unicode codepoint may + be used. The default value is the default unicode replacement character is + 0xFFFD or U+65533.) + replace_control_characters: An optional `bool`. Defaults to `False`. + Whether to replace the C0 control characters (00-1F) with the + `replacement_char`. Default is false. + Tsplits: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (row_splits, char_values, char_to_byte_starts). + + row_splits: A `Tensor` of type `Tsplits`. + char_values: A `Tensor` of type `int32`. + char_to_byte_starts: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnicodeDecodeWithOffsets", name, input, "input_encoding", + input_encoding, "errors", errors, "replacement_char", + replacement_char, "replace_control_characters", + replace_control_characters, "Tsplits", Tsplits) + _result = _UnicodeDecodeWithOffsetsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unicode_decode_with_offsets_eager_fallback( + input, input_encoding=input_encoding, errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + Tsplits=Tsplits, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + input_encoding = _execute.make_str(input_encoding, "input_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnicodeDecodeWithOffsets", input=input, + input_encoding=input_encoding, + errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + Tsplits=Tsplits, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("input_encoding", _op.get_attr("input_encoding"), "errors", + _op.get_attr("errors"), "replacement_char", + _op._get_attr_int("replacement_char"), + "replace_control_characters", + _op._get_attr_bool("replace_control_characters"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnicodeDecodeWithOffsets", _inputs_flat, _attrs, _result) + _result = _UnicodeDecodeWithOffsetsOutput._make(_result) + return _result + +UnicodeDecodeWithOffsets = tf_export("raw_ops.UnicodeDecodeWithOffsets")(_ops.to_raw_op(unicode_decode_with_offsets)) + + +def unicode_decode_with_offsets_eager_fallback(input: Annotated[Any, _atypes.String], input_encoding: str, errors: str, replacement_char: int, replace_control_characters: bool, Tsplits: TV_UnicodeDecodeWithOffsets_Tsplits, name, ctx): + input_encoding = _execute.make_str(input_encoding, "input_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + if Tsplits is None: + Tsplits = _dtypes.int64 + Tsplits = _execute.make_type(Tsplits, "Tsplits") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("input_encoding", input_encoding, "errors", errors, + "replacement_char", replacement_char, "replace_control_characters", + replace_control_characters, "Tsplits", Tsplits) + _result = _execute.execute(b"UnicodeDecodeWithOffsets", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnicodeDecodeWithOffsets", _inputs_flat, _attrs, _result) + _result = _UnicodeDecodeWithOffsetsOutput._make(_result) + return _result + + +TV_UnicodeEncode_Tsplits = TypeVar("TV_UnicodeEncode_Tsplits", _atypes.Int32, _atypes.Int64) + +def unicode_encode(input_values: Annotated[Any, _atypes.Int32], input_splits: Annotated[Any, TV_UnicodeEncode_Tsplits], output_encoding: str, errors:str="replace", replacement_char:int=65533, name=None) -> Annotated[Any, _atypes.String]: + r"""Encode a tensor of ints into unicode strings. + + Returns a vector of strings, where `output[i]` is constructed by encoding the + Unicode codepoints in `input_values[input_splits[i]:input_splits[i+1]]` + using `output_encoding`. + + --- + + Example: + + ``` + input_values = [72, 101, 108, 108, 111, 87, 111, 114, 108, 100] + input_splits = [0, 5, 10] + output_encoding = 'UTF-8' + + output = ['Hello', 'World'] + ``` + + Args: + input_values: A `Tensor` of type `int32`. + A 1D tensor containing the unicode codepoints that should be encoded. + input_splits: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A 1D tensor specifying how the unicode codepoints should be split into strings. + In particular, `output[i]` is constructed by encoding the codepoints in the + slice `input_values[input_splits[i]:input_splits[i+1]]`. + output_encoding: A `string` from: `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. + Unicode encoding of the output strings. Valid encodings are: `"UTF-8", + "UTF-16-BE", and "UTF-32-BE"`. + errors: An optional `string` from: `"ignore", "replace", "strict"`. Defaults to `"replace"`. + Error handling policy when there is invalid formatting found in the input. + The value of 'strict' will cause the operation to produce a InvalidArgument + error on any invalid input formatting. A value of 'replace' (the default) will + cause the operation to replace any invalid formatting in the input with the + `replacement_char` codepoint. A value of 'ignore' will cause the operation to + skip any invalid formatting in the input and produce no corresponding output + character. + replacement_char: An optional `int`. Defaults to `65533`. + The replacement character codepoint to be used in place of any invalid + formatting in the input when `errors='replace'`. Any valid unicode codepoint may + be used. The default value is the default unicode replacement character is + 0xFFFD (U+65533). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnicodeEncode", name, input_values, input_splits, "errors", + errors, "output_encoding", output_encoding, "replacement_char", + replacement_char) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unicode_encode_eager_fallback( + input_values, input_splits, errors=errors, + output_encoding=output_encoding, replacement_char=replacement_char, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + output_encoding = _execute.make_str(output_encoding, "output_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnicodeEncode", input_values=input_values, input_splits=input_splits, + output_encoding=output_encoding, errors=errors, + replacement_char=replacement_char, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("errors", _op.get_attr("errors"), "output_encoding", + _op.get_attr("output_encoding"), "replacement_char", + _op._get_attr_int("replacement_char"), "Tsplits", + _op._get_attr_type("Tsplits")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnicodeEncode", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnicodeEncode = tf_export("raw_ops.UnicodeEncode")(_ops.to_raw_op(unicode_encode)) + + +def unicode_encode_eager_fallback(input_values: Annotated[Any, _atypes.Int32], input_splits: Annotated[Any, TV_UnicodeEncode_Tsplits], output_encoding: str, errors: str, replacement_char: int, name, ctx) -> Annotated[Any, _atypes.String]: + output_encoding = _execute.make_str(output_encoding, "output_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + _attr_Tsplits, (input_splits,) = _execute.args_to_matching_eager([input_splits], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int64) + input_values = _ops.convert_to_tensor(input_values, _dtypes.int32) + _inputs_flat = [input_values, input_splits] + _attrs = ("errors", errors, "output_encoding", output_encoding, + "replacement_char", replacement_char, "Tsplits", _attr_Tsplits) + _result = _execute.execute(b"UnicodeEncode", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnicodeEncode", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.unicode_script') +def unicode_script(input: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Determine the script codes of a given tensor of Unicode integer code points. + + This operation converts Unicode code points to script codes corresponding to + each code point. Script codes correspond to International Components for + Unicode (ICU) UScriptCode values. + + See + [ICU project docs](http://icu-project.org/apiref/icu4c/uscript_8h.html) + for more details on script codes. + + For an example, see the unicode strings guide on [unicode scripts] + (https://www.tensorflow.org/tutorials/load_data/unicode#representing_unicode). + + Returns -1 (USCRIPT_INVALID_CODE) for invalid codepoints. Output shape will + match input shape. + + Examples: + + >>> tf.strings.unicode_script([1, 31, 38]) + + + Args: + input: A `Tensor` of type `int32`. A Tensor of int32 Unicode code points. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnicodeScript", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unicode_script( + (input, name,), None) + if _result is not NotImplemented: + return _result + return unicode_script_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unicode_script, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unicode_script( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnicodeScript", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unicode_script, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnicodeScript", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnicodeScript = tf_export("raw_ops.UnicodeScript")(_ops.to_raw_op(unicode_script)) +_dispatcher_for_unicode_script = unicode_script._tf_type_based_dispatcher.Dispatch + + +def unicode_script_eager_fallback(input: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Int32]: + input = _ops.convert_to_tensor(input, _dtypes.int32) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"UnicodeScript", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnicodeScript", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('strings.unicode_transcode') +def unicode_transcode(input: Annotated[Any, _atypes.String], input_encoding: str, output_encoding: str, errors:str="replace", replacement_char:int=65533, replace_control_characters:bool=False, name=None) -> Annotated[Any, _atypes.String]: + r"""Transcode the input text from a source encoding to a destination encoding. + + The input is a string tensor of any shape. The output is a string tensor of + the same shape containing the transcoded strings. Output strings are always + valid unicode. If the input contains invalid encoding positions, the + `errors` attribute sets the policy for how to deal with them. If the default + error-handling policy is used, invalid formatting will be substituted in the + output by the `replacement_char`. If the errors policy is to `ignore`, any + invalid encoding positions in the input are skipped and not included in the + output. If it set to `strict` then any invalid formatting will result in an + InvalidArgument error. + + This operation can be used with `output_encoding = input_encoding` to enforce + correct formatting for inputs even if they are already in the desired encoding. + + If the input is prefixed by a Byte Order Mark needed to determine encoding + (e.g. if the encoding is UTF-16 and the BOM indicates big-endian), then that + BOM will be consumed and not emitted into the output. If the input encoding + is marked with an explicit endianness (e.g. UTF-16-BE), then the BOM is + interpreted as a non-breaking-space and is preserved in the output (including + always for UTF-8). + + The end result is that if the input is marked as an explicit endianness the + transcoding is faithful to all codepoints in the source. If it is not marked + with an explicit endianness, the BOM is not considered part of the string itself + but as metadata, and so is not preserved in the output. + + Examples: + + >>> tf.strings.unicode_transcode(["Hello", "TensorFlow", "2.x"], "UTF-8", "UTF-16-BE") + + >>> tf.strings.unicode_transcode(["A", "B", "C"], "US ASCII", "UTF-8").numpy() + array([b'A', b'B', b'C'], dtype=object) + + Args: + input: A `Tensor` of type `string`. + The text to be processed. Can have any shape. + input_encoding: A `string`. + Text encoding of the input strings. This is any of the encodings supported + by ICU ucnv algorithmic converters. Examples: `"UTF-16", "US ASCII", "UTF-8"`. + output_encoding: A `string` from: `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. + The unicode encoding to use in the output. Must be one of + `"UTF-8", "UTF-16-BE", "UTF-32-BE"`. Multi-byte encodings will be big-endian. + errors: An optional `string` from: `"strict", "replace", "ignore"`. Defaults to `"replace"`. + Error handling policy when there is invalid formatting found in the input. + The value of 'strict' will cause the operation to produce a InvalidArgument + error on any invalid input formatting. A value of 'replace' (the default) will + cause the operation to replace any invalid formatting in the input with the + `replacement_char` codepoint. A value of 'ignore' will cause the operation to + skip any invalid formatting in the input and produce no corresponding output + character. + replacement_char: An optional `int`. Defaults to `65533`. + The replacement character codepoint to be used in place of any invalid + formatting in the input when `errors='replace'`. Any valid unicode codepoint may + be used. The default value is the default unicode replacement character is + 0xFFFD or U+65533.) + + Note that for UTF-8, passing a replacement character expressible in 1 byte, such + as ' ', will preserve string alignment to the source since invalid bytes will be + replaced with a 1-byte replacement. For UTF-16-BE and UTF-16-LE, any 1 or 2 byte + replacement character will preserve byte alignment to the source. + replace_control_characters: An optional `bool`. Defaults to `False`. + Whether to replace the C0 control characters (00-1F) with the + `replacement_char`. Default is false. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnicodeTranscode", name, input, "input_encoding", + input_encoding, "output_encoding", output_encoding, "errors", errors, + "replacement_char", replacement_char, "replace_control_characters", + replace_control_characters) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unicode_transcode( + (input, input_encoding, output_encoding, errors, replacement_char, + replace_control_characters, name,), None) + if _result is not NotImplemented: + return _result + return unicode_transcode_eager_fallback( + input, input_encoding=input_encoding, + output_encoding=output_encoding, errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unicode_transcode, (), dict(input=input, + input_encoding=input_encoding, + output_encoding=output_encoding, + errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unicode_transcode( + (input, input_encoding, output_encoding, errors, replacement_char, + replace_control_characters, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + input_encoding = _execute.make_str(input_encoding, "input_encoding") + output_encoding = _execute.make_str(output_encoding, "output_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnicodeTranscode", input=input, input_encoding=input_encoding, + output_encoding=output_encoding, errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unicode_transcode, (), dict(input=input, + input_encoding=input_encoding, + output_encoding=output_encoding, + errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("input_encoding", _op.get_attr("input_encoding"), + "output_encoding", _op.get_attr("output_encoding"), "errors", + _op.get_attr("errors"), "replacement_char", + _op._get_attr_int("replacement_char"), + "replace_control_characters", + _op._get_attr_bool("replace_control_characters")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnicodeTranscode", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnicodeTranscode = tf_export("raw_ops.UnicodeTranscode")(_ops.to_raw_op(unicode_transcode)) +_dispatcher_for_unicode_transcode = unicode_transcode._tf_type_based_dispatcher.Dispatch + + +def unicode_transcode_eager_fallback(input: Annotated[Any, _atypes.String], input_encoding: str, output_encoding: str, errors: str, replacement_char: int, replace_control_characters: bool, name, ctx) -> Annotated[Any, _atypes.String]: + input_encoding = _execute.make_str(input_encoding, "input_encoding") + output_encoding = _execute.make_str(output_encoding, "output_encoding") + if errors is None: + errors = "replace" + errors = _execute.make_str(errors, "errors") + if replacement_char is None: + replacement_char = 65533 + replacement_char = _execute.make_int(replacement_char, "replacement_char") + if replace_control_characters is None: + replace_control_characters = False + replace_control_characters = _execute.make_bool(replace_control_characters, "replace_control_characters") + input = _ops.convert_to_tensor(input, _dtypes.string) + _inputs_flat = [input] + _attrs = ("input_encoding", input_encoding, "output_encoding", + output_encoding, "errors", errors, "replacement_char", replacement_char, + "replace_control_characters", replace_control_characters) + _result = _execute.execute(b"UnicodeTranscode", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnicodeTranscode", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UnsortedSegmentJoin_Tindices = TypeVar("TV_UnsortedSegmentJoin_Tindices", _atypes.Int32, _atypes.Int64) +TV_UnsortedSegmentJoin_Tnumsegments = TypeVar("TV_UnsortedSegmentJoin_Tnumsegments", _atypes.Int32, _atypes.Int64) + +def unsorted_segment_join(inputs: Annotated[Any, _atypes.String], segment_ids: Annotated[Any, TV_UnsortedSegmentJoin_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentJoin_Tnumsegments], separator:str="", name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + inputs: A `Tensor` of type `string`. + segment_ids: A `Tensor`. Must be one of the following types: `int32`, `int64`. + num_segments: A `Tensor`. Must be one of the following types: `int32`, `int64`. + separator: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UnsortedSegmentJoin", name, inputs, segment_ids, num_segments, + "separator", separator) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return unsorted_segment_join_eager_fallback( + inputs, segment_ids, num_segments, separator=separator, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UnsortedSegmentJoin", inputs=inputs, segment_ids=segment_ids, + num_segments=num_segments, separator=separator, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("separator", _op.get_attr("separator"), "Tindices", + _op._get_attr_type("Tindices"), "Tnumsegments", + _op._get_attr_type("Tnumsegments")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UnsortedSegmentJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UnsortedSegmentJoin = tf_export("raw_ops.UnsortedSegmentJoin")(_ops.to_raw_op(unsorted_segment_join)) + + +def unsorted_segment_join_eager_fallback(inputs: Annotated[Any, _atypes.String], segment_ids: Annotated[Any, TV_UnsortedSegmentJoin_Tindices], num_segments: Annotated[Any, TV_UnsortedSegmentJoin_Tnumsegments], separator: str, name, ctx) -> Annotated[Any, _atypes.String]: + if separator is None: + separator = "" + separator = _execute.make_str(separator, "separator") + _attr_Tindices, (segment_ids,) = _execute.args_to_matching_eager([segment_ids], ctx, [_dtypes.int32, _dtypes.int64, ]) + _attr_Tnumsegments, (num_segments,) = _execute.args_to_matching_eager([num_segments], ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + inputs = _ops.convert_to_tensor(inputs, _dtypes.string) + _inputs_flat = [inputs, segment_ids, num_segments] + _attrs = ("separator", separator, "Tindices", _attr_Tindices, + "Tnumsegments", _attr_Tnumsegments) + _result = _execute.execute(b"UnsortedSegmentJoin", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UnsortedSegmentJoin", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_summary_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_summary_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1b1970dc0aacd15f3582252afcfe1983978fe7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_summary_ops.py @@ -0,0 +1,733 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def close_summary_writer(writer: Annotated[Any, _atypes.Resource], name=None): + r"""TODO: add doc. + + Args: + writer: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CloseSummaryWriter", name, writer) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return close_summary_writer_eager_fallback( + writer, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CloseSummaryWriter", writer=writer, name=name) + return _op +CloseSummaryWriter = tf_export("raw_ops.CloseSummaryWriter")(_ops.to_raw_op(close_summary_writer)) + + +def close_summary_writer_eager_fallback(writer: Annotated[Any, _atypes.Resource], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + _inputs_flat = [writer] + _attrs = None + _result = _execute.execute(b"CloseSummaryWriter", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def create_summary_db_writer(writer: Annotated[Any, _atypes.Resource], db_uri: Annotated[Any, _atypes.String], experiment_name: Annotated[Any, _atypes.String], run_name: Annotated[Any, _atypes.String], user_name: Annotated[Any, _atypes.String], name=None): + r"""TODO: add doc. + + Args: + writer: A `Tensor` of type `resource`. + db_uri: A `Tensor` of type `string`. + experiment_name: A `Tensor` of type `string`. + run_name: A `Tensor` of type `string`. + user_name: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CreateSummaryDbWriter", name, writer, db_uri, experiment_name, + run_name, user_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return create_summary_db_writer_eager_fallback( + writer, db_uri, experiment_name, run_name, user_name, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CreateSummaryDbWriter", writer=writer, db_uri=db_uri, + experiment_name=experiment_name, + run_name=run_name, user_name=user_name, + name=name) + return _op +CreateSummaryDbWriter = tf_export("raw_ops.CreateSummaryDbWriter")(_ops.to_raw_op(create_summary_db_writer)) + + +def create_summary_db_writer_eager_fallback(writer: Annotated[Any, _atypes.Resource], db_uri: Annotated[Any, _atypes.String], experiment_name: Annotated[Any, _atypes.String], run_name: Annotated[Any, _atypes.String], user_name: Annotated[Any, _atypes.String], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + db_uri = _ops.convert_to_tensor(db_uri, _dtypes.string) + experiment_name = _ops.convert_to_tensor(experiment_name, _dtypes.string) + run_name = _ops.convert_to_tensor(run_name, _dtypes.string) + user_name = _ops.convert_to_tensor(user_name, _dtypes.string) + _inputs_flat = [writer, db_uri, experiment_name, run_name, user_name] + _attrs = None + _result = _execute.execute(b"CreateSummaryDbWriter", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def create_summary_file_writer(writer: Annotated[Any, _atypes.Resource], logdir: Annotated[Any, _atypes.String], max_queue: Annotated[Any, _atypes.Int32], flush_millis: Annotated[Any, _atypes.Int32], filename_suffix: Annotated[Any, _atypes.String], name=None): + r"""TODO: add doc. + + Args: + writer: A `Tensor` of type `resource`. + logdir: A `Tensor` of type `string`. + max_queue: A `Tensor` of type `int32`. + flush_millis: A `Tensor` of type `int32`. + filename_suffix: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CreateSummaryFileWriter", name, writer, logdir, max_queue, + flush_millis, filename_suffix) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return create_summary_file_writer_eager_fallback( + writer, logdir, max_queue, flush_millis, filename_suffix, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CreateSummaryFileWriter", writer=writer, logdir=logdir, + max_queue=max_queue, + flush_millis=flush_millis, + filename_suffix=filename_suffix, name=name) + return _op +CreateSummaryFileWriter = tf_export("raw_ops.CreateSummaryFileWriter")(_ops.to_raw_op(create_summary_file_writer)) + + +def create_summary_file_writer_eager_fallback(writer: Annotated[Any, _atypes.Resource], logdir: Annotated[Any, _atypes.String], max_queue: Annotated[Any, _atypes.Int32], flush_millis: Annotated[Any, _atypes.Int32], filename_suffix: Annotated[Any, _atypes.String], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + logdir = _ops.convert_to_tensor(logdir, _dtypes.string) + max_queue = _ops.convert_to_tensor(max_queue, _dtypes.int32) + flush_millis = _ops.convert_to_tensor(flush_millis, _dtypes.int32) + filename_suffix = _ops.convert_to_tensor(filename_suffix, _dtypes.string) + _inputs_flat = [writer, logdir, max_queue, flush_millis, filename_suffix] + _attrs = None + _result = _execute.execute(b"CreateSummaryFileWriter", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def flush_summary_writer(writer: Annotated[Any, _atypes.Resource], name=None): + r"""TODO: add doc. + + Args: + writer: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FlushSummaryWriter", name, writer) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return flush_summary_writer_eager_fallback( + writer, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FlushSummaryWriter", writer=writer, name=name) + return _op +FlushSummaryWriter = tf_export("raw_ops.FlushSummaryWriter")(_ops.to_raw_op(flush_summary_writer)) + + +def flush_summary_writer_eager_fallback(writer: Annotated[Any, _atypes.Resource], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + _inputs_flat = [writer] + _attrs = None + _result = _execute.execute(b"FlushSummaryWriter", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def import_event(writer: Annotated[Any, _atypes.Resource], event: Annotated[Any, _atypes.String], name=None): + r"""TODO: add doc. + + Args: + writer: A `Tensor` of type `resource`. + event: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ImportEvent", name, writer, event) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return import_event_eager_fallback( + writer, event, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ImportEvent", writer=writer, event=event, name=name) + return _op +ImportEvent = tf_export("raw_ops.ImportEvent")(_ops.to_raw_op(import_event)) + + +def import_event_eager_fallback(writer: Annotated[Any, _atypes.Resource], event: Annotated[Any, _atypes.String], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + event = _ops.convert_to_tensor(event, _dtypes.string) + _inputs_flat = [writer, event] + _attrs = None + _result = _execute.execute(b"ImportEvent", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def summary_writer(shared_name:str="", container:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + shared_name: An optional `string`. Defaults to `""`. + container: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SummaryWriter", name, "shared_name", shared_name, "container", + container) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return summary_writer_eager_fallback( + shared_name=shared_name, container=container, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if container is None: + container = "" + container = _execute.make_str(container, "container") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SummaryWriter", shared_name=shared_name, container=container, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("shared_name", _op.get_attr("shared_name"), "container", + _op.get_attr("container")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SummaryWriter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SummaryWriter = tf_export("raw_ops.SummaryWriter")(_ops.to_raw_op(summary_writer)) + + +def summary_writer_eager_fallback(shared_name: str, container: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + if container is None: + container = "" + container = _execute.make_str(container, "container") + _inputs_flat = [] + _attrs = ("shared_name", shared_name, "container", container) + _result = _execute.execute(b"SummaryWriter", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SummaryWriter", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def write_audio_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Float32], max_outputs:int=3, name=None): + r"""Writes an audio summary. + + Writes encoded audio summary `tensor` at `step` with `tag` using summary `writer`. + `sample_rate` is the audio sample rate is Hz. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tag: A `Tensor` of type `string`. + tensor: A `Tensor` of type `float32`. + sample_rate: A `Tensor` of type `float32`. + max_outputs: An optional `int` that is `>= 1`. Defaults to `3`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteAudioSummary", name, writer, step, tag, tensor, + sample_rate, "max_outputs", max_outputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_audio_summary_eager_fallback( + writer, step, tag, tensor, sample_rate, max_outputs=max_outputs, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteAudioSummary", writer=writer, step=step, tag=tag, tensor=tensor, + sample_rate=sample_rate, max_outputs=max_outputs, + name=name) + return _op +WriteAudioSummary = tf_export("raw_ops.WriteAudioSummary")(_ops.to_raw_op(write_audio_summary)) + + +def write_audio_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, _atypes.Float32], sample_rate: Annotated[Any, _atypes.Float32], max_outputs: int, name, ctx): + if max_outputs is None: + max_outputs = 3 + max_outputs = _execute.make_int(max_outputs, "max_outputs") + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + tensor = _ops.convert_to_tensor(tensor, _dtypes.float32) + sample_rate = _ops.convert_to_tensor(sample_rate, _dtypes.float32) + _inputs_flat = [writer, step, tag, tensor, sample_rate] + _attrs = ("max_outputs", max_outputs) + _result = _execute.execute(b"WriteAudioSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def write_graph_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, _atypes.String], name=None): + r"""Writes a graph summary. + + Writes TensorFlow graph `tensor` at `step` using summary `writer`. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tensor: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteGraphSummary", name, writer, step, tensor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_graph_summary_eager_fallback( + writer, step, tensor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteGraphSummary", writer=writer, step=step, tensor=tensor, + name=name) + return _op +WriteGraphSummary = tf_export("raw_ops.WriteGraphSummary")(_ops.to_raw_op(write_graph_summary)) + + +def write_graph_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, _atypes.String], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tensor = _ops.convert_to_tensor(tensor, _dtypes.string) + _inputs_flat = [writer, step, tensor] + _attrs = None + _result = _execute.execute(b"WriteGraphSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_WriteHistogramSummary_T = TypeVar("TV_WriteHistogramSummary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def write_histogram_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], values: Annotated[Any, TV_WriteHistogramSummary_T], name=None): + r"""Writes a histogram summary. + + Writes histogram `values` at `step` with `tag` using summary `writer`. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tag: A `Tensor` of type `string`. + values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `bool`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteHistogramSummary", name, writer, step, tag, values) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_histogram_summary_eager_fallback( + writer, step, tag, values, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteHistogramSummary", writer=writer, step=step, tag=tag, + values=values, name=name) + return _op +WriteHistogramSummary = tf_export("raw_ops.WriteHistogramSummary")(_ops.to_raw_op(write_histogram_summary)) + + +def write_histogram_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], values: Annotated[Any, TV_WriteHistogramSummary_T], name, ctx): + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.bool, ], _dtypes.float32) + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [writer, step, tag, values] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"WriteHistogramSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_WriteImageSummary_T = TypeVar("TV_WriteImageSummary_T", _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.UInt8) + +def write_image_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_WriteImageSummary_T], bad_color: Annotated[Any, _atypes.UInt8], max_images:int=3, name=None): + r"""Writes an image summary. + + Writes image `tensor` at `step` with `tag` using summary `writer`. + `tensor` is image with shape [height, width, channels]. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tag: A `Tensor` of type `string`. + tensor: A `Tensor`. Must be one of the following types: `uint8`, `float64`, `float32`, `half`. + bad_color: A `Tensor` of type `uint8`. + max_images: An optional `int` that is `>= 1`. Defaults to `3`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteImageSummary", name, writer, step, tag, tensor, bad_color, + "max_images", max_images) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_image_summary_eager_fallback( + writer, step, tag, tensor, bad_color, max_images=max_images, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if max_images is None: + max_images = 3 + max_images = _execute.make_int(max_images, "max_images") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteImageSummary", writer=writer, step=step, tag=tag, tensor=tensor, + bad_color=bad_color, max_images=max_images, + name=name) + return _op +WriteImageSummary = tf_export("raw_ops.WriteImageSummary")(_ops.to_raw_op(write_image_summary)) + + +def write_image_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], tensor: Annotated[Any, TV_WriteImageSummary_T], bad_color: Annotated[Any, _atypes.UInt8], max_images: int, name, ctx): + if max_images is None: + max_images = 3 + max_images = _execute.make_int(max_images, "max_images") + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, [_dtypes.uint8, _dtypes.float64, _dtypes.float32, _dtypes.half, ], _dtypes.float32) + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + bad_color = _ops.convert_to_tensor(bad_color, _dtypes.uint8) + _inputs_flat = [writer, step, tag, tensor, bad_color] + _attrs = ("max_images", max_images, "T", _attr_T) + _result = _execute.execute(b"WriteImageSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def write_raw_proto_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, _atypes.String], name=None): + r"""Writes a serialized proto summary. + + Writes `tensor`, a serialized proto at `step` using summary `writer`. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tensor: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteRawProtoSummary", name, writer, step, tensor) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_raw_proto_summary_eager_fallback( + writer, step, tensor, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteRawProtoSummary", writer=writer, step=step, tensor=tensor, + name=name) + return _op +WriteRawProtoSummary = tf_export("raw_ops.WriteRawProtoSummary")(_ops.to_raw_op(write_raw_proto_summary)) + + +def write_raw_proto_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, _atypes.String], name, ctx): + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tensor = _ops.convert_to_tensor(tensor, _dtypes.string) + _inputs_flat = [writer, step, tensor] + _attrs = None + _result = _execute.execute(b"WriteRawProtoSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_WriteScalarSummary_T = TypeVar("TV_WriteScalarSummary_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def write_scalar_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], value: Annotated[Any, TV_WriteScalarSummary_T], name=None): + r"""Writes a scalar summary. + + Writes scalar `value` at `step` with `tag` using summary `writer`. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tag: A `Tensor` of type `string`. + value: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteScalarSummary", name, writer, step, tag, value) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_scalar_summary_eager_fallback( + writer, step, tag, value, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteScalarSummary", writer=writer, step=step, tag=tag, value=value, + name=name) + return _op +WriteScalarSummary = tf_export("raw_ops.WriteScalarSummary")(_ops.to_raw_op(write_scalar_summary)) + + +def write_scalar_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tag: Annotated[Any, _atypes.String], value: Annotated[Any, TV_WriteScalarSummary_T], name, ctx): + _attr_T, (value,) = _execute.args_to_matching_eager([value], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.int64, _dtypes.bfloat16, _dtypes.uint16, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + _inputs_flat = [writer, step, tag, value] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"WriteScalarSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_WriteSummary_T = TypeVar("TV_WriteSummary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def write_summary(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, TV_WriteSummary_T], tag: Annotated[Any, _atypes.String], summary_metadata: Annotated[Any, _atypes.String], name=None): + r"""Writes a tensor summary. + + Writes `tensor` at `step` with `tag` using summary `writer`. + + Args: + writer: A `Tensor` of type `resource`. + step: A `Tensor` of type `int64`. + tensor: A `Tensor`. + tag: A `Tensor` of type `string`. + summary_metadata: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WriteSummary", name, writer, step, tensor, tag, + summary_metadata) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return write_summary_eager_fallback( + writer, step, tensor, tag, summary_metadata, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WriteSummary", writer=writer, step=step, tensor=tensor, tag=tag, + summary_metadata=summary_metadata, name=name) + return _op +WriteSummary = tf_export("raw_ops.WriteSummary")(_ops.to_raw_op(write_summary)) + + +def write_summary_eager_fallback(writer: Annotated[Any, _atypes.Resource], step: Annotated[Any, _atypes.Int64], tensor: Annotated[Any, TV_WriteSummary_T], tag: Annotated[Any, _atypes.String], summary_metadata: Annotated[Any, _atypes.String], name, ctx): + _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], ctx, []) + writer = _ops.convert_to_tensor(writer, _dtypes.resource) + step = _ops.convert_to_tensor(step, _dtypes.int64) + tag = _ops.convert_to_tensor(tag, _dtypes.string) + summary_metadata = _ops.convert_to_tensor(summary_metadata, _dtypes.string) + _inputs_flat = [writer, step, tensor, tag, summary_metadata] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"WriteSummary", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sync_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sync_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3e5433d53ce4ed750f41ba90f51c45e89340cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_sync_ops.py @@ -0,0 +1,67 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +def sync_device(name=None): + r"""Synchronizes the device this op is run on. + + Only GPU ops are asynchrous in TensorFlow, and so this only has an effect when + run on GPUs. On GPUs, this op synchronizes the GPU's compute stream. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SyncDevice", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sync_device_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SyncDevice", name=name) + return _op +SyncDevice = tf_export("raw_ops.SyncDevice")(_ops.to_raw_op(sync_device)) + + +def sync_device_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"SyncDevice", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d31d1dfc52bff8055bfbe9fb0b9609bdb73709 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_ops.py @@ -0,0 +1,6675 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AllToAll_T = TypeVar("TV_AllToAll_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def all_to_all(input: Annotated[Any, TV_AllToAll_T], group_assignment: Annotated[Any, _atypes.Int32], concat_dimension: int, split_dimension: int, split_count: int, name=None) -> Annotated[Any, TV_AllToAll_T]: + r"""An Op to exchange data across TPU replicas. + + On each replica, the input is split into `split_count` blocks along + `split_dimension` and send to the other replicas given group_assignment. After + receiving `split_count` - 1 blocks from other replicas, we concatenate the + blocks along `concat_dimension` as the output. + + For example, suppose there are 2 TPU replicas: + replica 0 receives input: `[[A, B]]` + replica 1 receives input: `[[C, D]]` + + group_assignment=`[[0, 1]]` + concat_dimension=0 + split_dimension=1 + split_count=2 + + replica 0's output: `[[A], [C]]` + replica 1's output: `[[B], [D]]` + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. + The local input to the sum. + group_assignment: A `Tensor` of type `int32`. An int32 tensor with shape + [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the + replica ids in the ith subgroup. + concat_dimension: An `int`. The dimension number to concatenate. + split_dimension: An `int`. The dimension number to split. + split_count: An `int`. + The number of splits, this number must equal to the sub-group + size(group_assignment.get_shape()[1]) + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AllToAll", name, input, group_assignment, "concat_dimension", + concat_dimension, "split_dimension", split_dimension, "split_count", + split_count) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return all_to_all_eager_fallback( + input, group_assignment, concat_dimension=concat_dimension, + split_dimension=split_dimension, split_count=split_count, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + concat_dimension = _execute.make_int(concat_dimension, "concat_dimension") + split_dimension = _execute.make_int(split_dimension, "split_dimension") + split_count = _execute.make_int(split_count, "split_count") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AllToAll", input=input, group_assignment=group_assignment, + concat_dimension=concat_dimension, + split_dimension=split_dimension, split_count=split_count, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "concat_dimension", + _op._get_attr_int("concat_dimension"), "split_dimension", + _op._get_attr_int("split_dimension"), "split_count", + _op._get_attr_int("split_count")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AllToAll", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AllToAll = tf_export("raw_ops.AllToAll")(_ops.to_raw_op(all_to_all)) + + +def all_to_all_eager_fallback(input: Annotated[Any, TV_AllToAll_T], group_assignment: Annotated[Any, _atypes.Int32], concat_dimension: int, split_dimension: int, split_count: int, name, ctx) -> Annotated[Any, TV_AllToAll_T]: + concat_dimension = _execute.make_int(concat_dimension, "concat_dimension") + split_dimension = _execute.make_int(split_dimension, "split_dimension") + split_count = _execute.make_int(split_count, "split_count") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, _dtypes.bool, ]) + group_assignment = _ops.convert_to_tensor(group_assignment, _dtypes.int32) + _inputs_flat = [input, group_assignment] + _attrs = ("T", _attr_T, "concat_dimension", concat_dimension, + "split_dimension", split_dimension, "split_count", split_count) + _result = _execute.execute(b"AllToAll", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AllToAll", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_AssignVariableXlaConcatND_T = TypeVar("TV_AssignVariableXlaConcatND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def assign_variable_xla_concat_nd(resource: Annotated[Any, _atypes.Resource], inputs: Annotated[List[Any], TV_AssignVariableXlaConcatND_T], num_concats, paddings=[], name=None): + r"""Concats input tensor across all dimensions. + + An op which merges slices the input tensor based on the given num_splits + attribute, strips paddings optionally, and writes the merged tensor without + paddings to the resource variable. + + This op may be generated via the TPU bridge. + + For example, with `input` tensor: + ``` + [[0, 1], + [4, 5]] + [[2, 3], + [6, 7]] + [[8, 9], + [12, 13]] + [[10, 11], + [14, 15]] + ``` + `num_splits`: + ``` + [2, 2] + ``` + and `paddings`: + ``` + [1, 1] + ``` + the expected `outputs` is: + ``` + [[0, 1, 2], + [4, 5, 6], + [8, 9, 10]] + ``` + + Args: + resource: A `Tensor` of type `resource`. + Resource variable for concatenated input tensors across all dimensions. + } + in_arg { + name: "inputs" + description: < Annotated[Any, TV_CollectivePermute_T]: + r"""An Op to permute tensors across replicated TPU instances. + + Each instance supplies its own input. + + For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing + source_target_pairs=`[[0,1],[1,2],[2,3],[3,0]]` gets the outputs: + `[D, A, B, C]`. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The local input to be permuted. Currently only supports float and + bfloat16. + source_target_pairs: A `Tensor` of type `int32`. + A tensor with shape [num_pairs, 2]. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CollectivePermute", name, input, source_target_pairs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return collective_permute_eager_fallback( + input, source_target_pairs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CollectivePermute", input=input, + source_target_pairs=source_target_pairs, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CollectivePermute", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CollectivePermute = tf_export("raw_ops.CollectivePermute")(_ops.to_raw_op(collective_permute)) + + +def collective_permute_eager_fallback(input: Annotated[Any, TV_CollectivePermute_T], source_target_pairs: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_CollectivePermute_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + source_target_pairs = _ops.convert_to_tensor(source_target_pairs, _dtypes.int32) + _inputs_flat = [input, source_target_pairs] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"CollectivePermute", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CollectivePermute", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def configure_distributed_tpu(embedding_config:str="", tpu_embedding_config:str="", is_global_init:bool=False, enable_whole_mesh_compilations:bool=False, compilation_failure_closes_chips:bool=True, tpu_cancellation_closes_chips:int=0, name=None) -> Annotated[Any, _atypes.String]: + r"""Sets up the centralized structures for a distributed TPU system. + + Args: + embedding_config: An optional `string`. Defaults to `""`. + Reserved. Do not use. + tpu_embedding_config: An optional `string`. Defaults to `""`. + Serialized tensorflow.tpu.TPUEmbeddingConfiguration that + describes the embedding lookups of the program. + is_global_init: An optional `bool`. Defaults to `False`. + Reserved. Do not use. + enable_whole_mesh_compilations: An optional `bool`. Defaults to `False`. + compilation_failure_closes_chips: An optional `bool`. Defaults to `True`. + tpu_cancellation_closes_chips: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConfigureDistributedTPU", name, "embedding_config", + embedding_config, "tpu_embedding_config", tpu_embedding_config, + "is_global_init", is_global_init, "enable_whole_mesh_compilations", + enable_whole_mesh_compilations, "compilation_failure_closes_chips", + compilation_failure_closes_chips, "tpu_cancellation_closes_chips", + tpu_cancellation_closes_chips) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return configure_distributed_tpu_eager_fallback( + embedding_config=embedding_config, + tpu_embedding_config=tpu_embedding_config, + is_global_init=is_global_init, + enable_whole_mesh_compilations=enable_whole_mesh_compilations, + compilation_failure_closes_chips=compilation_failure_closes_chips, + tpu_cancellation_closes_chips=tpu_cancellation_closes_chips, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if embedding_config is None: + embedding_config = "" + embedding_config = _execute.make_str(embedding_config, "embedding_config") + if tpu_embedding_config is None: + tpu_embedding_config = "" + tpu_embedding_config = _execute.make_str(tpu_embedding_config, "tpu_embedding_config") + if is_global_init is None: + is_global_init = False + is_global_init = _execute.make_bool(is_global_init, "is_global_init") + if enable_whole_mesh_compilations is None: + enable_whole_mesh_compilations = False + enable_whole_mesh_compilations = _execute.make_bool(enable_whole_mesh_compilations, "enable_whole_mesh_compilations") + if compilation_failure_closes_chips is None: + compilation_failure_closes_chips = True + compilation_failure_closes_chips = _execute.make_bool(compilation_failure_closes_chips, "compilation_failure_closes_chips") + if tpu_cancellation_closes_chips is None: + tpu_cancellation_closes_chips = 0 + tpu_cancellation_closes_chips = _execute.make_int(tpu_cancellation_closes_chips, "tpu_cancellation_closes_chips") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConfigureDistributedTPU", embedding_config=embedding_config, + tpu_embedding_config=tpu_embedding_config, + is_global_init=is_global_init, + enable_whole_mesh_compilations=enable_whole_mesh_compilations, + compilation_failure_closes_chips=compilation_failure_closes_chips, + tpu_cancellation_closes_chips=tpu_cancellation_closes_chips, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("embedding_config", _op.get_attr("embedding_config"), + "tpu_embedding_config", _op.get_attr("tpu_embedding_config"), + "is_global_init", _op._get_attr_bool("is_global_init"), + "enable_whole_mesh_compilations", + _op._get_attr_bool("enable_whole_mesh_compilations"), + "compilation_failure_closes_chips", + _op._get_attr_bool("compilation_failure_closes_chips"), + "tpu_cancellation_closes_chips", + _op._get_attr_int("tpu_cancellation_closes_chips")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ConfigureDistributedTPU", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ConfigureDistributedTPU = tf_export("raw_ops.ConfigureDistributedTPU")(_ops.to_raw_op(configure_distributed_tpu)) + + +def configure_distributed_tpu_eager_fallback(embedding_config: str, tpu_embedding_config: str, is_global_init: bool, enable_whole_mesh_compilations: bool, compilation_failure_closes_chips: bool, tpu_cancellation_closes_chips: int, name, ctx) -> Annotated[Any, _atypes.String]: + if embedding_config is None: + embedding_config = "" + embedding_config = _execute.make_str(embedding_config, "embedding_config") + if tpu_embedding_config is None: + tpu_embedding_config = "" + tpu_embedding_config = _execute.make_str(tpu_embedding_config, "tpu_embedding_config") + if is_global_init is None: + is_global_init = False + is_global_init = _execute.make_bool(is_global_init, "is_global_init") + if enable_whole_mesh_compilations is None: + enable_whole_mesh_compilations = False + enable_whole_mesh_compilations = _execute.make_bool(enable_whole_mesh_compilations, "enable_whole_mesh_compilations") + if compilation_failure_closes_chips is None: + compilation_failure_closes_chips = True + compilation_failure_closes_chips = _execute.make_bool(compilation_failure_closes_chips, "compilation_failure_closes_chips") + if tpu_cancellation_closes_chips is None: + tpu_cancellation_closes_chips = 0 + tpu_cancellation_closes_chips = _execute.make_int(tpu_cancellation_closes_chips, "tpu_cancellation_closes_chips") + _inputs_flat = [] + _attrs = ("embedding_config", embedding_config, "tpu_embedding_config", + tpu_embedding_config, "is_global_init", is_global_init, + "enable_whole_mesh_compilations", enable_whole_mesh_compilations, + "compilation_failure_closes_chips", compilation_failure_closes_chips, + "tpu_cancellation_closes_chips", tpu_cancellation_closes_chips) + _result = _execute.execute(b"ConfigureDistributedTPU", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ConfigureDistributedTPU", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def configure_tpu_embedding(config: str, name=None): + r"""Sets up TPUEmbedding in a distributed TPU system. + + Args: + config: A `string`. + Serialized tensorflow.tpu.TPUEmbeddingConfiguration that + describes the embedding lookups of the program. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ConfigureTPUEmbedding", name, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return configure_tpu_embedding_eager_fallback( + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ConfigureTPUEmbedding", config=config, name=name) + return _op +ConfigureTPUEmbedding = tf_export("raw_ops.ConfigureTPUEmbedding")(_ops.to_raw_op(configure_tpu_embedding)) + + +def configure_tpu_embedding_eager_fallback(config: str, name, ctx): + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("config", config) + _result = _execute.execute(b"ConfigureTPUEmbedding", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_CrossReplicaSum_T = TypeVar("TV_CrossReplicaSum_T", _atypes.BFloat16, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int32, _atypes.UInt32) + +def cross_replica_sum(input: Annotated[Any, TV_CrossReplicaSum_T], group_assignment: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, TV_CrossReplicaSum_T]: + r"""An Op to sum inputs across replicated TPU instances. + + Each instance supplies its own input. + + For example, suppose there are 8 TPU instances: `[A, B, C, D, E, F, G, H]`. + Passing group_assignment=`[[0,2,4,6],[1,3,5,7]]` sets `A, C, E, G` as group 0, + and `B, D, F, H` as group 1. Thus we get the outputs: + `[A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H, A+C+E+G, B+D+F+H]`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`, `int32`, `uint32`. + The local input to the sum. + group_assignment: A `Tensor` of type `int32`. An int32 tensor with shape + [num_groups, num_replicas_per_group]. `group_assignment[i]` represents the + replica ids in the ith subgroup. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CrossReplicaSum", name, input, group_assignment) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return cross_replica_sum_eager_fallback( + input, group_assignment, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CrossReplicaSum", input=input, group_assignment=group_assignment, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CrossReplicaSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CrossReplicaSum = tf_export("raw_ops.CrossReplicaSum")(_ops.to_raw_op(cross_replica_sum)) + + +def cross_replica_sum_eager_fallback(input: Annotated[Any, TV_CrossReplicaSum_T], group_assignment: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, TV_CrossReplicaSum_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.half, _dtypes.bfloat16, _dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint32, ]) + group_assignment = _ops.convert_to_tensor(group_assignment, _dtypes.int32) + _inputs_flat = [input, group_assignment] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"CrossReplicaSum", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CrossReplicaSum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T1 = TypeVar("TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T1", _atypes.Int32, _atypes.Int64) +TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T2 = TypeVar("TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T2", _atypes.Int32, _atypes.Int64) +TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T3 = TypeVar("TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T3", _atypes.Float32, _atypes.Float64) + +def dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch(sample_indices_or_row_splits: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: Annotated[Any, _atypes.Int32], combiners=[], name=None): + r"""Eases the porting of code that uses tf.nn.embedding_lookup_sparse(). + + embedding_indices[i] and aggregation_weights[i] correspond + to the ith feature. + + The tensors at corresponding positions in the three input lists (sample_indices, + embedding_indices and aggregation_weights) must have the same shape, i.e. rank 1 + with dim_size() equal to the total number of lookups into the table described by + the corresponding feature. + + Args: + sample_indices_or_row_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 2 Tensors specifying the training example to which the + corresponding embedding_indices and aggregation_weights values belong. + If the size of its first dimension is 0, we assume each embedding_indices + belongs to a different sample. Both int32 and int64 are allowed and will + be converted to int32 internally. + + Or a list of rank 1 Tensors specifying the row splits for splitting + embedding_indices and aggregation_weights into rows. It corresponds to + ids.row_splits in embedding_lookup(), when ids is a RaggedTensor. When + enqueuing N-D ragged tensor, only the last dimension is allowed to be ragged. + the row splits is 1-D dense tensor. When empty, we assume a dense tensor is + passed to the op Both int32 and int64 are allowed and will be converted to + int32 internally. + embedding_indices: A list with the same length as `sample_indices_or_row_splits` of `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors, indices into the embedding + tables. Both int32 and int64 are allowed and will be converted to + int32 internally. + aggregation_weights: A list with the same length as `sample_indices_or_row_splits` of `Tensor` objects with the same type in: `float32`, `float64`. + A list of rank 1 Tensors containing per training + example aggregation weights. Both float32 and float64 are allowed and will + be converted to float32 internally. + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + device_ordinal: A `Tensor` of type `int32`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + combiners: An optional list of `strings`. Defaults to `[]`. + A list of string scalars, one for each embedding table that specify + how to normalize the embedding activations after weighted summation. + Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have + the sum of the weights be 0 for 'mean' or the sum of the squared weights be + 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for + all tables. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DynamicEnqueueTPUEmbeddingArbitraryTensorBatch", name, + sample_indices_or_row_splits, embedding_indices, aggregation_weights, + mode_override, device_ordinal, "combiners", combiners) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch_eager_fallback( + sample_indices_or_row_splits, embedding_indices, + aggregation_weights, mode_override, device_ordinal, + combiners=combiners, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_indices_or_row_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices_or_row_splits' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % sample_indices_or_row_splits) + _attr_N = len(sample_indices_or_row_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(aggregation_weights), _attr_N)) + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DynamicEnqueueTPUEmbeddingArbitraryTensorBatch", sample_indices_or_row_splits=sample_indices_or_row_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + device_ordinal=device_ordinal, + combiners=combiners, + name=name) + return _op +DynamicEnqueueTPUEmbeddingArbitraryTensorBatch = tf_export("raw_ops.DynamicEnqueueTPUEmbeddingArbitraryTensorBatch")(_ops.to_raw_op(dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch)) + + +def dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch_eager_fallback(sample_indices_or_row_splits: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingArbitraryTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: Annotated[Any, _atypes.Int32], combiners, name, ctx): + if not isinstance(sample_indices_or_row_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices_or_row_splits' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % sample_indices_or_row_splits) + _attr_N = len(sample_indices_or_row_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(aggregation_weights), _attr_N)) + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'dynamic_enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _attr_T1, sample_indices_or_row_splits = _execute.args_to_matching_eager(list(sample_indices_or_row_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + device_ordinal = _ops.convert_to_tensor(device_ordinal, _dtypes.int32) + _inputs_flat = list(sample_indices_or_row_splits) + list(embedding_indices) + list(aggregation_weights) + [mode_override, device_ordinal] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "combiners", combiners) + _result = _execute.execute(b"DynamicEnqueueTPUEmbeddingArbitraryTensorBatch", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T1 = TypeVar("TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T1", _atypes.Int32, _atypes.Int64) +TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T2 = TypeVar("TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T2", _atypes.Int32, _atypes.Int64) +TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T3 = TypeVar("TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T3", _atypes.Float32, _atypes.Float64) + +def dynamic_enqueue_tpu_embedding_ragged_tensor_batch(sample_splits: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: Annotated[Any, _atypes.Int32], table_ids, combiners=[], max_sequence_lengths=[], num_features=[], name=None): + r"""TODO: add doc. + + Args: + sample_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + embedding_indices: A list with the same length as `sample_splits` of `Tensor` objects with the same type in: `int32`, `int64`. + aggregation_weights: A list with the same length as `sample_splits` of `Tensor` objects with the same type in: `float32`, `float64`. + mode_override: A `Tensor` of type `string`. + device_ordinal: A `Tensor` of type `int32`. + table_ids: A list of `ints`. + combiners: An optional list of `strings`. Defaults to `[]`. + max_sequence_lengths: An optional list of `ints`. Defaults to `[]`. + num_features: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DynamicEnqueueTPUEmbeddingRaggedTensorBatch", name, + sample_splits, embedding_indices, aggregation_weights, mode_override, + device_ordinal, "combiners", combiners, "table_ids", table_ids, + "max_sequence_lengths", max_sequence_lengths, "num_features", + num_features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dynamic_enqueue_tpu_embedding_ragged_tensor_batch_eager_fallback( + sample_splits, embedding_indices, aggregation_weights, + mode_override, device_ordinal, combiners=combiners, + table_ids=table_ids, max_sequence_lengths=max_sequence_lengths, + num_features=num_features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_splits' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % sample_splits) + _attr_N = len(sample_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DynamicEnqueueTPUEmbeddingRaggedTensorBatch", sample_splits=sample_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + device_ordinal=device_ordinal, + table_ids=table_ids, + combiners=combiners, + max_sequence_lengths=max_sequence_lengths, + num_features=num_features, + name=name) + return _op +DynamicEnqueueTPUEmbeddingRaggedTensorBatch = tf_export("raw_ops.DynamicEnqueueTPUEmbeddingRaggedTensorBatch")(_ops.to_raw_op(dynamic_enqueue_tpu_embedding_ragged_tensor_batch)) + + +def dynamic_enqueue_tpu_embedding_ragged_tensor_batch_eager_fallback(sample_splits: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_DynamicEnqueueTPUEmbeddingRaggedTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: Annotated[Any, _atypes.Int32], table_ids, combiners, max_sequence_lengths, num_features, name, ctx): + if not isinstance(sample_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_splits' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % sample_splits) + _attr_N = len(sample_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'dynamic_enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _attr_T1, sample_splits = _execute.args_to_matching_eager(list(sample_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + device_ordinal = _ops.convert_to_tensor(device_ordinal, _dtypes.int32) + _inputs_flat = list(sample_splits) + list(embedding_indices) + list(aggregation_weights) + [mode_override, device_ordinal] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "combiners", combiners, "table_ids", table_ids, "max_sequence_lengths", + max_sequence_lengths, "num_features", num_features) + _result = _execute.execute(b"DynamicEnqueueTPUEmbeddingRaggedTensorBatch", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T1 = TypeVar("TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T1", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T2 = TypeVar("TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T2", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T3 = TypeVar("TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T3", _atypes.Float32, _atypes.Float64) + +def enqueue_tpu_embedding_arbitrary_tensor_batch(sample_indices_or_row_splits: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal:int=-1, combiners=[], name=None): + r"""Eases the porting of code that uses tf.nn.embedding_lookup_sparse(). + + embedding_indices[i] and aggregation_weights[i] correspond + to the ith feature. + + The tensors at corresponding positions in the three input lists (sample_indices, + embedding_indices and aggregation_weights) must have the same shape, i.e. rank 1 + with dim_size() equal to the total number of lookups into the table described by + the corresponding feature. + + Args: + sample_indices_or_row_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 2 Tensors specifying the training example to which the + corresponding embedding_indices and aggregation_weights values belong. + If the size of its first dimension is 0, we assume each embedding_indices + belongs to a different sample. Both int32 and int64 are allowed and will + be converted to int32 internally. + + Or a list of rank 1 Tensors specifying the row splits for splitting + embedding_indices and aggregation_weights into rows. It corresponds to + ids.row_splits in embedding_lookup(), when ids is a RaggedTensor. When + enqueuing N-D ragged tensor, only the last dimension is allowed to be ragged. + the row splits is 1-D dense tensor. When empty, we assume a dense tensor is + passed to the op Both int32 and int64 are allowed and will be converted to + int32 internally. + embedding_indices: A list with the same length as `sample_indices_or_row_splits` of `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors, indices into the embedding + tables. Both int32 and int64 are allowed and will be converted to + int32 internally. + aggregation_weights: A list with the same length as `sample_indices_or_row_splits` of `Tensor` objects with the same type in: `float32`, `float64`. + A list of rank 1 Tensors containing per training + example aggregation weights. Both float32 and float64 are allowed and will + be converted to float32 internally. + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + combiners: An optional list of `strings`. Defaults to `[]`. + A list of string scalars, one for each embedding table that specify + how to normalize the embedding activations after weighted summation. + Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have + the sum of the weights be 0 for 'mean' or the sum of the squared weights be + 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for + all tables. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnqueueTPUEmbeddingArbitraryTensorBatch", name, + sample_indices_or_row_splits, embedding_indices, aggregation_weights, + mode_override, "device_ordinal", device_ordinal, "combiners", + combiners) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enqueue_tpu_embedding_arbitrary_tensor_batch_eager_fallback( + sample_indices_or_row_splits, embedding_indices, + aggregation_weights, mode_override, device_ordinal=device_ordinal, + combiners=combiners, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_indices_or_row_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices_or_row_splits' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % sample_indices_or_row_splits) + _attr_N = len(sample_indices_or_row_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(aggregation_weights), _attr_N)) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnqueueTPUEmbeddingArbitraryTensorBatch", sample_indices_or_row_splits=sample_indices_or_row_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + device_ordinal=device_ordinal, + combiners=combiners, + name=name) + return _op +EnqueueTPUEmbeddingArbitraryTensorBatch = tf_export("raw_ops.EnqueueTPUEmbeddingArbitraryTensorBatch")(_ops.to_raw_op(enqueue_tpu_embedding_arbitrary_tensor_batch)) + + +def enqueue_tpu_embedding_arbitrary_tensor_batch_eager_fallback(sample_indices_or_row_splits: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingArbitraryTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: int, combiners, name, ctx): + if not isinstance(sample_indices_or_row_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices_or_row_splits' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % sample_indices_or_row_splits) + _attr_N = len(sample_indices_or_row_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_arbitrary_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices_or_row_splits'." % + (len(aggregation_weights), _attr_N)) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_arbitrary_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _attr_T1, sample_indices_or_row_splits = _execute.args_to_matching_eager(list(sample_indices_or_row_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + _inputs_flat = list(sample_indices_or_row_splits) + list(embedding_indices) + list(aggregation_weights) + [mode_override] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "device_ordinal", device_ordinal, "combiners", combiners) + _result = _execute.execute(b"EnqueueTPUEmbeddingArbitraryTensorBatch", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def enqueue_tpu_embedding_integer_batch(batch: Annotated[List[Any], _atypes.Int32], mode_override: Annotated[Any, _atypes.String], device_ordinal:int=-1, name=None): + r"""An op that enqueues a list of input batch tensors to TPUEmbedding. + + Args: + batch: A list of at least 1 `Tensor` objects with type `int32`. + A list of 1D tensors, one for each embedding table, containing the + indices into the tables. + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnqueueTPUEmbeddingIntegerBatch", name, batch, mode_override, + "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enqueue_tpu_embedding_integer_batch_eager_fallback( + batch, mode_override, device_ordinal=device_ordinal, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(batch, (list, tuple)): + raise TypeError( + "Expected list for 'batch' argument to " + "'enqueue_tpu_embedding_integer_batch' Op, not %r." % batch) + _attr_N = len(batch) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnqueueTPUEmbeddingIntegerBatch", batch=batch, + mode_override=mode_override, + device_ordinal=device_ordinal, + name=name) + return _op +EnqueueTPUEmbeddingIntegerBatch = tf_export("raw_ops.EnqueueTPUEmbeddingIntegerBatch")(_ops.to_raw_op(enqueue_tpu_embedding_integer_batch)) + + +def enqueue_tpu_embedding_integer_batch_eager_fallback(batch: Annotated[List[Any], _atypes.Int32], mode_override: Annotated[Any, _atypes.String], device_ordinal: int, name, ctx): + if not isinstance(batch, (list, tuple)): + raise TypeError( + "Expected list for 'batch' argument to " + "'enqueue_tpu_embedding_integer_batch' Op, not %r." % batch) + _attr_N = len(batch) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + batch = _ops.convert_n_to_tensor(batch, _dtypes.int32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + _inputs_flat = list(batch) + [mode_override] + _attrs = ("N", _attr_N, "device_ordinal", device_ordinal) + _result = _execute.execute(b"EnqueueTPUEmbeddingIntegerBatch", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_EnqueueTPUEmbeddingRaggedTensorBatch_T1 = TypeVar("TV_EnqueueTPUEmbeddingRaggedTensorBatch_T1", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingRaggedTensorBatch_T2 = TypeVar("TV_EnqueueTPUEmbeddingRaggedTensorBatch_T2", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingRaggedTensorBatch_T3 = TypeVar("TV_EnqueueTPUEmbeddingRaggedTensorBatch_T3", _atypes.Float32, _atypes.Float64) + +def enqueue_tpu_embedding_ragged_tensor_batch(sample_splits: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], table_ids, device_ordinal:int=-1, combiners=[], max_sequence_lengths=[], num_features=[], name=None): + r"""Eases the porting of code that uses tf.nn.embedding_lookup(). + + sample_splits[i], embedding_indices[i] and aggregation_weights[i] correspond + to the ith feature. table_ids[i] indicates which embedding table to look up ith + feature. + + The tensors at corresponding positions in two of the input lists, + embedding_indices and aggregation_weights, must have the same shape, i.e. rank 1 + with dim_size() equal to the total number of lookups into the table described by + the corresponding feature. + + Args: + sample_splits: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors specifying the break points for splitting + embedding_indices and aggregation_weights into rows. + It corresponds to ids.row_splits in embedding_lookup(), when ids is a + RaggedTensor. + embedding_indices: A list with the same length as `sample_splits` of `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors, indices into the embedding tables. + It corresponds to ids.values in embedding_lookup(), when ids is a RaggedTensor. + aggregation_weights: A list with the same length as `sample_splits` of `Tensor` objects with the same type in: `float32`, `float64`. + A list of rank 1 Tensors containing per training example + aggregation weights. It corresponds to the values field of a RaggedTensor + with the same row_splits as ids in embedding_lookup(), when ids is a + RaggedTensor. + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + table_ids: A list of `ints`. + A list of integers specifying the identifier of the embedding table + (offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the + corresponding input. The ith input is looked up using table_ids[i]. The size + of the table_ids list must be equal to that of sample_indices, + embedding_indices and aggregation_weights. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + combiners: An optional list of `strings`. Defaults to `[]`. + A list of string scalars, one for each embedding table that specify + how to normalize the embedding activations after weighted summation. + Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have + the sum of the weights be 0 for 'mean' or the sum of the squared weights be + 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for + all tables. + max_sequence_lengths: An optional list of `ints`. Defaults to `[]`. + num_features: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnqueueTPUEmbeddingRaggedTensorBatch", name, sample_splits, + embedding_indices, aggregation_weights, mode_override, + "device_ordinal", device_ordinal, "combiners", combiners, "table_ids", + table_ids, "max_sequence_lengths", max_sequence_lengths, + "num_features", num_features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enqueue_tpu_embedding_ragged_tensor_batch_eager_fallback( + sample_splits, embedding_indices, aggregation_weights, + mode_override, device_ordinal=device_ordinal, combiners=combiners, + table_ids=table_ids, max_sequence_lengths=max_sequence_lengths, + num_features=num_features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_splits' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % sample_splits) + _attr_N = len(sample_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnqueueTPUEmbeddingRaggedTensorBatch", sample_splits=sample_splits, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + table_ids=table_ids, + device_ordinal=device_ordinal, + combiners=combiners, + max_sequence_lengths=max_sequence_lengths, + num_features=num_features, + name=name) + return _op +EnqueueTPUEmbeddingRaggedTensorBatch = tf_export("raw_ops.EnqueueTPUEmbeddingRaggedTensorBatch")(_ops.to_raw_op(enqueue_tpu_embedding_ragged_tensor_batch)) + + +def enqueue_tpu_embedding_ragged_tensor_batch_eager_fallback(sample_splits: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingRaggedTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], table_ids, device_ordinal: int, combiners, max_sequence_lengths, num_features, name, ctx): + if not isinstance(sample_splits, (list, tuple)): + raise TypeError( + "Expected list for 'sample_splits' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % sample_splits) + _attr_N = len(sample_splits) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_ragged_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_splits'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'enqueue_tpu_embedding_ragged_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _attr_T1, sample_splits = _execute.args_to_matching_eager(list(sample_splits), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + _inputs_flat = list(sample_splits) + list(embedding_indices) + list(aggregation_weights) + [mode_override] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "device_ordinal", device_ordinal, "combiners", combiners, "table_ids", + table_ids, "max_sequence_lengths", max_sequence_lengths, "num_features", + num_features) + _result = _execute.execute(b"EnqueueTPUEmbeddingRaggedTensorBatch", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_EnqueueTPUEmbeddingSparseBatch_T1 = TypeVar("TV_EnqueueTPUEmbeddingSparseBatch_T1", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingSparseBatch_T2 = TypeVar("TV_EnqueueTPUEmbeddingSparseBatch_T2", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingSparseBatch_T3 = TypeVar("TV_EnqueueTPUEmbeddingSparseBatch_T3", _atypes.Float32, _atypes.Float64) + +def enqueue_tpu_embedding_sparse_batch(sample_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal:int=-1, combiners=[], name=None): + r"""An op that enqueues TPUEmbedding input indices from a SparseTensor. + + This Op eases the porting of code that uses embedding_lookup_sparse(), + although some Python preprocessing of the SparseTensor arguments to + embedding_lookup_sparse() is required to produce the arguments to this Op, + since only a single EnqueueTPUEmbeddingSparseBatch Op is allowed per training + step. + + The tensors at corresponding positions in the three input lists + must have the same shape, i.e. rank 1 with dim_size() equal to the total + number of lookups into the table described by the corresponding table_id. + + Args: + sample_indices: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors specifying the training example and + feature to which the corresponding embedding_indices and aggregation_weights + values belong. sample_indices[i] must equal b * nf + f, where nf is the + number of features from the corresponding table, f is in [0, nf), and + b is in [0, batch size). + embedding_indices: A list with the same length as `sample_indices` of `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors, indices into the embedding tables. + aggregation_weights: A list with the same length as `sample_indices` of `Tensor` objects with the same type in: `float32`, `float64`. + A list of rank 1 Tensors containing per sample -- i.e. per + (training example, feature) -- aggregation weights. + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + combiners: An optional list of `strings`. Defaults to `[]`. + A list of string scalars, one for each embedding table that specify + how to normalize the embedding activations after weighted summation. + Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have + the sum of the weights be 0 for 'mean' or the sum of the squared weights be + 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for + all tables. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnqueueTPUEmbeddingSparseBatch", name, sample_indices, + embedding_indices, aggregation_weights, mode_override, + "device_ordinal", device_ordinal, "combiners", combiners) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enqueue_tpu_embedding_sparse_batch_eager_fallback( + sample_indices, embedding_indices, aggregation_weights, + mode_override, device_ordinal=device_ordinal, combiners=combiners, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % sample_indices) + _attr_N = len(sample_indices) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_sparse_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_sparse_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(aggregation_weights), _attr_N)) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnqueueTPUEmbeddingSparseBatch", sample_indices=sample_indices, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + device_ordinal=device_ordinal, + combiners=combiners, name=name) + return _op +EnqueueTPUEmbeddingSparseBatch = tf_export("raw_ops.EnqueueTPUEmbeddingSparseBatch")(_ops.to_raw_op(enqueue_tpu_embedding_sparse_batch)) + + +def enqueue_tpu_embedding_sparse_batch_eager_fallback(sample_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseBatch_T3], mode_override: Annotated[Any, _atypes.String], device_ordinal: int, combiners, name, ctx): + if not isinstance(sample_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % sample_indices) + _attr_N = len(sample_indices) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_sparse_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_sparse_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(aggregation_weights), _attr_N)) + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_sparse_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + _attr_T1, sample_indices = _execute.args_to_matching_eager(list(sample_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + _inputs_flat = list(sample_indices) + list(embedding_indices) + list(aggregation_weights) + [mode_override] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "device_ordinal", device_ordinal, "combiners", combiners) + _result = _execute.execute(b"EnqueueTPUEmbeddingSparseBatch", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_EnqueueTPUEmbeddingSparseTensorBatch_T1 = TypeVar("TV_EnqueueTPUEmbeddingSparseTensorBatch_T1", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingSparseTensorBatch_T2 = TypeVar("TV_EnqueueTPUEmbeddingSparseTensorBatch_T2", _atypes.Int32, _atypes.Int64) +TV_EnqueueTPUEmbeddingSparseTensorBatch_T3 = TypeVar("TV_EnqueueTPUEmbeddingSparseTensorBatch_T3", _atypes.Float32, _atypes.Float64) + +def enqueue_tpu_embedding_sparse_tensor_batch(sample_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], table_ids, device_ordinal:int=-1, combiners=[], max_sequence_lengths=[], num_features=[], name=None): + r"""Eases the porting of code that uses tf.nn.embedding_lookup_sparse(). + + sample_indices[i], embedding_indices[i] and aggregation_weights[i] correspond + to the ith feature. table_ids[i] indicates which embedding table to look up ith + feature. + + The tensors at corresponding positions in the three input lists (sample_indices, + embedding_indices and aggregation_weights) must have the same shape, i.e. rank 1 + with dim_size() equal to the total number of lookups into the table described by + the corresponding feature. + + Args: + sample_indices: A list of at least 1 `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors specifying the training example to + which the corresponding embedding_indices and aggregation_weights values + belong. It corresponds to sp_ids.indices[:,0] in embedding_lookup_sparse(). + embedding_indices: A list with the same length as `sample_indices` of `Tensor` objects with the same type in: `int32`, `int64`. + A list of rank 1 Tensors, indices into the embedding tables. + It corresponds to sp_ids.values in embedding_lookup_sparse(). + aggregation_weights: A list with the same length as `sample_indices` of `Tensor` objects with the same type in: `float32`, `float64`. + A list of rank 1 Tensors containing per training example + aggregation weights. It corresponds to sp_weights.values in + embedding_lookup_sparse(). + mode_override: A `Tensor` of type `string`. + A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', 'inference', + 'training', 'backward_pass_only'}. When set to 'unspecified', the mode set + in TPUEmbeddingConfiguration is used, otherwise mode_override is used. + table_ids: A list of `ints`. + A list of integers specifying the identifier of the embedding table + (offset of TableDescriptor in the TPUEmbeddingConfiguration) to lookup the + corresponding input. The ith input is looked up using table_ids[i]. The size + of the table_ids list must be equal to that of sample_indices, + embedding_indices and aggregation_weights. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. Should be >= 0 and less than the number + of TPU cores in the task on which the node is placed. + combiners: An optional list of `strings`. Defaults to `[]`. + A list of string scalars, one for each embedding table that specify + how to normalize the embedding activations after weighted summation. + Supported combiners are 'mean', 'sum', or 'sqrtn'. It is invalid to have + the sum of the weights be 0 for 'mean' or the sum of the squared weights be + 0 for 'sqrtn'. If combiners isn't passed, the default is to use 'sum' for + all tables. + max_sequence_lengths: An optional list of `ints`. Defaults to `[]`. + num_features: An optional list of `ints`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "EnqueueTPUEmbeddingSparseTensorBatch", name, sample_indices, + embedding_indices, aggregation_weights, mode_override, + "device_ordinal", device_ordinal, "combiners", combiners, "table_ids", + table_ids, "max_sequence_lengths", max_sequence_lengths, + "num_features", num_features) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return enqueue_tpu_embedding_sparse_tensor_batch_eager_fallback( + sample_indices, embedding_indices, aggregation_weights, + mode_override, device_ordinal=device_ordinal, combiners=combiners, + table_ids=table_ids, max_sequence_lengths=max_sequence_lengths, + num_features=num_features, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(sample_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % sample_indices) + _attr_N = len(sample_indices) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_sparse_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_sparse_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "EnqueueTPUEmbeddingSparseTensorBatch", sample_indices=sample_indices, + embedding_indices=embedding_indices, + aggregation_weights=aggregation_weights, + mode_override=mode_override, + table_ids=table_ids, + device_ordinal=device_ordinal, + combiners=combiners, + max_sequence_lengths=max_sequence_lengths, + num_features=num_features, + name=name) + return _op +EnqueueTPUEmbeddingSparseTensorBatch = tf_export("raw_ops.EnqueueTPUEmbeddingSparseTensorBatch")(_ops.to_raw_op(enqueue_tpu_embedding_sparse_tensor_batch)) + + +def enqueue_tpu_embedding_sparse_tensor_batch_eager_fallback(sample_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T1], embedding_indices: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T2], aggregation_weights: Annotated[List[Any], TV_EnqueueTPUEmbeddingSparseTensorBatch_T3], mode_override: Annotated[Any, _atypes.String], table_ids, device_ordinal: int, combiners, max_sequence_lengths, num_features, name, ctx): + if not isinstance(sample_indices, (list, tuple)): + raise TypeError( + "Expected list for 'sample_indices' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % sample_indices) + _attr_N = len(sample_indices) + if not isinstance(embedding_indices, (list, tuple)): + raise TypeError( + "Expected list for 'embedding_indices' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % embedding_indices) + if len(embedding_indices) != _attr_N: + raise ValueError( + "List argument 'embedding_indices' to 'enqueue_tpu_embedding_sparse_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(embedding_indices), _attr_N)) + if not isinstance(aggregation_weights, (list, tuple)): + raise TypeError( + "Expected list for 'aggregation_weights' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % aggregation_weights) + if len(aggregation_weights) != _attr_N: + raise ValueError( + "List argument 'aggregation_weights' to 'enqueue_tpu_embedding_sparse_tensor_batch' Op with length %d " + "must match length %d of argument 'sample_indices'." % + (len(aggregation_weights), _attr_N)) + if not isinstance(table_ids, (list, tuple)): + raise TypeError( + "Expected list for 'table_ids' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % table_ids) + table_ids = [_execute.make_int(_i, "table_ids") for _i in table_ids] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + if combiners is None: + combiners = [] + if not isinstance(combiners, (list, tuple)): + raise TypeError( + "Expected list for 'combiners' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % combiners) + combiners = [_execute.make_str(_s, "combiners") for _s in combiners] + if max_sequence_lengths is None: + max_sequence_lengths = [] + if not isinstance(max_sequence_lengths, (list, tuple)): + raise TypeError( + "Expected list for 'max_sequence_lengths' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % max_sequence_lengths) + max_sequence_lengths = [_execute.make_int(_i, "max_sequence_lengths") for _i in max_sequence_lengths] + if num_features is None: + num_features = [] + if not isinstance(num_features, (list, tuple)): + raise TypeError( + "Expected list for 'num_features' argument to " + "'enqueue_tpu_embedding_sparse_tensor_batch' Op, not %r." % num_features) + num_features = [_execute.make_int(_i, "num_features") for _i in num_features] + _attr_T1, sample_indices = _execute.args_to_matching_eager(list(sample_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T2, embedding_indices = _execute.args_to_matching_eager(list(embedding_indices), ctx, [_dtypes.int32, _dtypes.int64, ], _dtypes.int32) + _attr_T3, aggregation_weights = _execute.args_to_matching_eager(list(aggregation_weights), ctx, [_dtypes.float32, _dtypes.float64, ], _dtypes.float32) + mode_override = _ops.convert_to_tensor(mode_override, _dtypes.string) + _inputs_flat = list(sample_indices) + list(embedding_indices) + list(aggregation_weights) + [mode_override] + _attrs = ("T1", _attr_T1, "T2", _attr_T2, "T3", _attr_T3, "N", _attr_N, + "device_ordinal", device_ordinal, "combiners", combiners, "table_ids", + table_ids, "max_sequence_lengths", max_sequence_lengths, "num_features", + num_features) + _result = _execute.execute(b"EnqueueTPUEmbeddingSparseTensorBatch", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_InfeedDequeue_dtype = TypeVar("TV_InfeedDequeue_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def infeed_dequeue(dtype: TV_InfeedDequeue_dtype, shape, name=None) -> Annotated[Any, TV_InfeedDequeue_dtype]: + r"""A placeholder op for a value that will be fed into the computation. + + Args: + dtype: A `tf.DType`. The type of elements in the tensor. + shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InfeedDequeue", name, "dtype", dtype, "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return infeed_dequeue_eager_fallback( + dtype=dtype, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InfeedDequeue", dtype=dtype, shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InfeedDequeue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +InfeedDequeue = tf_export("raw_ops.InfeedDequeue")(_ops.to_raw_op(infeed_dequeue)) + + +def infeed_dequeue_eager_fallback(dtype: TV_InfeedDequeue_dtype, shape, name, ctx) -> Annotated[Any, TV_InfeedDequeue_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape) + _result = _execute.execute(b"InfeedDequeue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InfeedDequeue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def infeed_dequeue_tuple(dtypes, shapes, name=None): + r"""Fetches multiple values from infeed as an XLA tuple. + + Args: + dtypes: A list of `tf.DTypes` that has length `>= 1`. + The element types of each element in `outputs`. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of each tensor in `outputs`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InfeedDequeueTuple", name, "dtypes", dtypes, "shapes", shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return infeed_dequeue_tuple_eager_fallback( + dtypes=dtypes, shapes=shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'infeed_dequeue_tuple' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'infeed_dequeue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InfeedDequeueTuple", dtypes=dtypes, shapes=shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("dtypes", _op.get_attr("dtypes"), "shapes", + _op.get_attr("shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "InfeedDequeueTuple", _inputs_flat, _attrs, _result) + return _result + +InfeedDequeueTuple = tf_export("raw_ops.InfeedDequeueTuple")(_ops.to_raw_op(infeed_dequeue_tuple)) + + +def infeed_dequeue_tuple_eager_fallback(dtypes, shapes, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'infeed_dequeue_tuple' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'infeed_dequeue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + _inputs_flat = [] + _attrs = ("dtypes", dtypes, "shapes", shapes) + _result = _execute.execute(b"InfeedDequeueTuple", len(dtypes), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "InfeedDequeueTuple", _inputs_flat, _attrs, _result) + return _result + + +TV_InfeedEnqueue_dtype = TypeVar("TV_InfeedEnqueue_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def infeed_enqueue(input: Annotated[Any, TV_InfeedEnqueue_dtype], shape=[], layout=[], device_ordinal:int=-1, name=None): + r"""An op which feeds a single Tensor value into the computation. + + Args: + input: A `Tensor`. + A tensor that will be provided using the infeed mechanism. + shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + The shape of the tensor. + layout: An optional list of `ints`. Defaults to `[]`. + A vector holding the requested layout in minor-to-major sequence. + If a layout attribute is passed, but its values are all -1, the layout will + be computed by the infeed operation. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. This should be -1 when the Op + is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InfeedEnqueue", name, input, "shape", shape, "layout", layout, + "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return infeed_enqueue_eager_fallback( + input, shape=shape, layout=layout, device_ordinal=device_ordinal, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if shape is None: + shape = [] + shape = _execute.make_shape(shape, "shape") + if layout is None: + layout = [] + if not isinstance(layout, (list, tuple)): + raise TypeError( + "Expected list for 'layout' argument to " + "'infeed_enqueue' Op, not %r." % layout) + layout = [_execute.make_int(_i, "layout") for _i in layout] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InfeedEnqueue", input=input, shape=shape, layout=layout, + device_ordinal=device_ordinal, name=name) + return _op +InfeedEnqueue = tf_export("raw_ops.InfeedEnqueue")(_ops.to_raw_op(infeed_enqueue)) + + +def infeed_enqueue_eager_fallback(input: Annotated[Any, TV_InfeedEnqueue_dtype], shape, layout, device_ordinal: int, name, ctx): + if shape is None: + shape = [] + shape = _execute.make_shape(shape, "shape") + if layout is None: + layout = [] + if not isinstance(layout, (list, tuple)): + raise TypeError( + "Expected list for 'layout' argument to " + "'infeed_enqueue' Op, not %r." % layout) + layout = [_execute.make_int(_i, "layout") for _i in layout] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _attr_dtype, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("dtype", _attr_dtype, "shape", shape, "layout", layout, + "device_ordinal", device_ordinal) + _result = _execute.execute(b"InfeedEnqueue", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def infeed_enqueue_prelinearized_buffer(input: Annotated[Any, _atypes.Variant], device_ordinal:int=-1, name=None): + r"""An op which enqueues prelinearized buffer into TPU infeed. + + Args: + input: A `Tensor` of type `variant`. + A variant tensor representing linearized output. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. This should be -1 when the Op is running on a TPU device + and = 0 when the Op is running on the CPU device. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InfeedEnqueuePrelinearizedBuffer", name, input, + "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return infeed_enqueue_prelinearized_buffer_eager_fallback( + input, device_ordinal=device_ordinal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InfeedEnqueuePrelinearizedBuffer", input=input, + device_ordinal=device_ordinal, + name=name) + return _op +InfeedEnqueuePrelinearizedBuffer = tf_export("raw_ops.InfeedEnqueuePrelinearizedBuffer")(_ops.to_raw_op(infeed_enqueue_prelinearized_buffer)) + + +def infeed_enqueue_prelinearized_buffer_eager_fallback(input: Annotated[Any, _atypes.Variant], device_ordinal: int, name, ctx): + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + input = _ops.convert_to_tensor(input, _dtypes.variant) + _inputs_flat = [input] + _attrs = ("device_ordinal", device_ordinal) + _result = _execute.execute(b"InfeedEnqueuePrelinearizedBuffer", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def infeed_enqueue_tuple(inputs, shapes, layouts=[], device_ordinal:int=-1, name=None): + r"""Feeds multiple Tensor values into the computation as an XLA tuple. + + Args: + inputs: A list of `Tensor` objects. + A list of tensors that will be provided using the infeed mechanism. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of each tensor in `inputs`. + layouts: An optional list of `ints`. Defaults to `[]`. + A vector holding the requested layout in minor-to-major sequence for + all the tuple shapes, in the order the shapes appear in the "shapes" input. + The layout elements for a sub-shape can be set to -1, in which case the + corresponding layout will be computed by the infeed operation. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. This should be -1 when the Op + is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InfeedEnqueueTuple", name, inputs, "shapes", shapes, "layouts", + layouts, "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return infeed_enqueue_tuple_eager_fallback( + inputs, shapes=shapes, layouts=layouts, + device_ordinal=device_ordinal, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'infeed_enqueue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if layouts is None: + layouts = [] + if not isinstance(layouts, (list, tuple)): + raise TypeError( + "Expected list for 'layouts' argument to " + "'infeed_enqueue_tuple' Op, not %r." % layouts) + layouts = [_execute.make_int(_i, "layouts") for _i in layouts] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InfeedEnqueueTuple", inputs=inputs, shapes=shapes, layouts=layouts, + device_ordinal=device_ordinal, name=name) + return _op +InfeedEnqueueTuple = tf_export("raw_ops.InfeedEnqueueTuple")(_ops.to_raw_op(infeed_enqueue_tuple)) + + +def infeed_enqueue_tuple_eager_fallback(inputs, shapes, layouts, device_ordinal: int, name, ctx): + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'infeed_enqueue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if layouts is None: + layouts = [] + if not isinstance(layouts, (list, tuple)): + raise TypeError( + "Expected list for 'layouts' argument to " + "'infeed_enqueue_tuple' Op, not %r." % layouts) + layouts = [_execute.make_int(_i, "layouts") for _i in layouts] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _attr_dtypes, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx) + _inputs_flat = list(inputs) + _attrs = ("dtypes", _attr_dtypes, "shapes", shapes, "layouts", layouts, + "device_ordinal", device_ordinal) + _result = _execute.execute(b"InfeedEnqueueTuple", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def is_tpu_embedding_initialized(config:str="", name=None) -> Annotated[Any, _atypes.Bool]: + r"""Whether TPU Embedding is initialized in a distributed TPU system. + + Args: + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsTPUEmbeddingInitialized", name, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return is_tpu_embedding_initialized_eager_fallback( + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsTPUEmbeddingInitialized", config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsTPUEmbeddingInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsTPUEmbeddingInitialized = tf_export("raw_ops.IsTPUEmbeddingInitialized")(_ops.to_raw_op(is_tpu_embedding_initialized)) + + +def is_tpu_embedding_initialized_eager_fallback(config: str, name, ctx) -> Annotated[Any, _atypes.Bool]: + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("config", config) + _result = _execute.execute(b"IsTPUEmbeddingInitialized", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsTPUEmbeddingInitialized", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def load_tpu_embedding_adam_parameters(parameters: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], velocities: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load ADAM embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the ADAM optimization algorithm. + momenta: A `Tensor` of type `float32`. + Value of momenta used in the ADAM optimization algorithm. + velocities: A `Tensor` of type `float32`. + Value of velocities used in the ADAM optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingADAMParameters", name, parameters, momenta, + velocities, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_adam_parameters_eager_fallback( + parameters, momenta, velocities, table_id=table_id, + table_name=table_name, num_shards=num_shards, shard_id=shard_id, + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingADAMParameters", parameters=parameters, + momenta=momenta, + velocities=velocities, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingADAMParameters = tf_export("raw_ops.LoadTPUEmbeddingADAMParameters")(_ops.to_raw_op(load_tpu_embedding_adam_parameters)) + + +def load_tpu_embedding_adam_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], velocities: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + momenta = _ops.convert_to_tensor(momenta, _dtypes.float32) + velocities = _ops.convert_to_tensor(velocities, _dtypes.float32) + _inputs_flat = [parameters, momenta, velocities] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingADAMParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_adadelta_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], updates: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load Adadelta embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the Adadelta optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the Adadelta optimization algorithm. + updates: A `Tensor` of type `float32`. + Value of updates used in the Adadelta optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingAdadeltaParameters", name, parameters, + accumulators, updates, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_adadelta_parameters_eager_fallback( + parameters, accumulators, updates, table_id=table_id, + table_name=table_name, num_shards=num_shards, shard_id=shard_id, + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingAdadeltaParameters", parameters=parameters, + accumulators=accumulators, + updates=updates, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingAdadeltaParameters = tf_export("raw_ops.LoadTPUEmbeddingAdadeltaParameters")(_ops.to_raw_op(load_tpu_embedding_adadelta_parameters)) + + +def load_tpu_embedding_adadelta_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], updates: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + updates = _ops.convert_to_tensor(updates, _dtypes.float32) + _inputs_flat = [parameters, accumulators, updates] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingAdadeltaParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_adagrad_momentum_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load Adagrad Momentum embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the Adagrad Momentum optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the Adagrad Momentum optimization algorithm. + momenta: A `Tensor` of type `float32`. + Value of momenta used in the Adagrad Momentum optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingAdagradMomentumParameters", name, parameters, + accumulators, momenta, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_adagrad_momentum_parameters_eager_fallback( + parameters, accumulators, momenta, table_id=table_id, + table_name=table_name, num_shards=num_shards, shard_id=shard_id, + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingAdagradMomentumParameters", parameters=parameters, + accumulators=accumulators, + momenta=momenta, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingAdagradMomentumParameters = tf_export("raw_ops.LoadTPUEmbeddingAdagradMomentumParameters")(_ops.to_raw_op(load_tpu_embedding_adagrad_momentum_parameters)) + + +def load_tpu_embedding_adagrad_momentum_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + momenta = _ops.convert_to_tensor(momenta, _dtypes.float32) + _inputs_flat = [parameters, accumulators, momenta] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingAdagradMomentumParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_adagrad_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load Adagrad embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the Adagrad optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the Adagrad optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingAdagradParameters", name, parameters, + accumulators, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_adagrad_parameters_eager_fallback( + parameters, accumulators, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingAdagradParameters", parameters=parameters, + accumulators=accumulators, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingAdagradParameters = tf_export("raw_ops.LoadTPUEmbeddingAdagradParameters")(_ops.to_raw_op(load_tpu_embedding_adagrad_parameters)) + + +def load_tpu_embedding_adagrad_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + _inputs_flat = [parameters, accumulators] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingAdagradParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_centered_rms_prop_parameters(parameters: Annotated[Any, _atypes.Float32], ms: Annotated[Any, _atypes.Float32], mom: Annotated[Any, _atypes.Float32], mg: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load centered RMSProp embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the centered RMSProp optimization algorithm. + ms: A `Tensor` of type `float32`. + Value of ms used in the centered RMSProp optimization algorithm. + mom: A `Tensor` of type `float32`. + Value of mom used in the centered RMSProp optimization algorithm. + mg: A `Tensor` of type `float32`. + Value of mg used in the centered RMSProp optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingCenteredRMSPropParameters", name, parameters, + ms, mom, mg, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_centered_rms_prop_parameters_eager_fallback( + parameters, ms, mom, mg, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingCenteredRMSPropParameters", parameters=parameters, + ms=ms, mom=mom, mg=mg, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingCenteredRMSPropParameters = tf_export("raw_ops.LoadTPUEmbeddingCenteredRMSPropParameters")(_ops.to_raw_op(load_tpu_embedding_centered_rms_prop_parameters)) + + +def load_tpu_embedding_centered_rms_prop_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], ms: Annotated[Any, _atypes.Float32], mom: Annotated[Any, _atypes.Float32], mg: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + ms = _ops.convert_to_tensor(ms, _dtypes.float32) + mom = _ops.convert_to_tensor(mom, _dtypes.float32) + mg = _ops.convert_to_tensor(mg, _dtypes.float32) + _inputs_flat = [parameters, ms, mom, mg] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingCenteredRMSPropParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_ftrl_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], linears: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load FTRL embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the FTRL optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the FTRL optimization algorithm. + linears: A `Tensor` of type `float32`. + Value of linears used in the FTRL optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingFTRLParameters", name, parameters, + accumulators, linears, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_ftrl_parameters_eager_fallback( + parameters, accumulators, linears, table_id=table_id, + table_name=table_name, num_shards=num_shards, shard_id=shard_id, + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingFTRLParameters", parameters=parameters, + accumulators=accumulators, + linears=linears, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingFTRLParameters = tf_export("raw_ops.LoadTPUEmbeddingFTRLParameters")(_ops.to_raw_op(load_tpu_embedding_ftrl_parameters)) + + +def load_tpu_embedding_ftrl_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], linears: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + linears = _ops.convert_to_tensor(linears, _dtypes.float32) + _inputs_flat = [parameters, accumulators, linears] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingFTRLParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_frequency_estimator_parameters(parameters: Annotated[Any, _atypes.Float32], last_hit_step: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load frequency estimator embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the frequency estimator optimization algorithm. + last_hit_step: A `Tensor` of type `float32`. + Value of last_hit_step used in the frequency estimator optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingFrequencyEstimatorParameters", name, + parameters, last_hit_step, "table_id", table_id, "table_name", + table_name, "num_shards", num_shards, "shard_id", shard_id, "config", + config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_frequency_estimator_parameters_eager_fallback( + parameters, last_hit_step, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingFrequencyEstimatorParameters", parameters=parameters, + last_hit_step=last_hit_step, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + return _op +LoadTPUEmbeddingFrequencyEstimatorParameters = tf_export("raw_ops.LoadTPUEmbeddingFrequencyEstimatorParameters")(_ops.to_raw_op(load_tpu_embedding_frequency_estimator_parameters)) + + +def load_tpu_embedding_frequency_estimator_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], last_hit_step: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + last_hit_step = _ops.convert_to_tensor(last_hit_step, _dtypes.float32) + _inputs_flat = [parameters, last_hit_step] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingFrequencyEstimatorParameters", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_mdl_adagrad_light_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], weights: Annotated[Any, _atypes.Float32], benefits: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load MDL Adagrad Light embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the MDL Adagrad Light optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the MDL Adagrad Light optimization algorithm. + weights: A `Tensor` of type `float32`. + Value of weights used in the MDL Adagrad Light optimization algorithm. + benefits: A `Tensor` of type `float32`. + Value of benefits used in the MDL Adagrad Light optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingMDLAdagradLightParameters", name, parameters, + accumulators, weights, benefits, "table_id", table_id, "table_name", + table_name, "num_shards", num_shards, "shard_id", shard_id, "config", + config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_mdl_adagrad_light_parameters_eager_fallback( + parameters, accumulators, weights, benefits, table_id=table_id, + table_name=table_name, num_shards=num_shards, shard_id=shard_id, + config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingMDLAdagradLightParameters", parameters=parameters, + accumulators=accumulators, + weights=weights, + benefits=benefits, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingMDLAdagradLightParameters = tf_export("raw_ops.LoadTPUEmbeddingMDLAdagradLightParameters")(_ops.to_raw_op(load_tpu_embedding_mdl_adagrad_light_parameters)) + + +def load_tpu_embedding_mdl_adagrad_light_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], weights: Annotated[Any, _atypes.Float32], benefits: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + weights = _ops.convert_to_tensor(weights, _dtypes.float32) + benefits = _ops.convert_to_tensor(benefits, _dtypes.float32) + _inputs_flat = [parameters, accumulators, weights, benefits] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingMDLAdagradLightParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_momentum_parameters(parameters: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load Momentum embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the Momentum optimization algorithm. + momenta: A `Tensor` of type `float32`. + Value of momenta used in the Momentum optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingMomentumParameters", name, parameters, momenta, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_momentum_parameters_eager_fallback( + parameters, momenta, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingMomentumParameters", parameters=parameters, + momenta=momenta, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingMomentumParameters = tf_export("raw_ops.LoadTPUEmbeddingMomentumParameters")(_ops.to_raw_op(load_tpu_embedding_momentum_parameters)) + + +def load_tpu_embedding_momentum_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], momenta: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + momenta = _ops.convert_to_tensor(momenta, _dtypes.float32) + _inputs_flat = [parameters, momenta] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingMomentumParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_proximal_adagrad_parameters(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load proximal Adagrad embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the proximal Adagrad optimization algorithm. + accumulators: A `Tensor` of type `float32`. + Value of accumulators used in the proximal Adagrad optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingProximalAdagradParameters", name, parameters, + accumulators, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_proximal_adagrad_parameters_eager_fallback( + parameters, accumulators, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingProximalAdagradParameters", parameters=parameters, + accumulators=accumulators, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingProximalAdagradParameters = tf_export("raw_ops.LoadTPUEmbeddingProximalAdagradParameters")(_ops.to_raw_op(load_tpu_embedding_proximal_adagrad_parameters)) + + +def load_tpu_embedding_proximal_adagrad_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], accumulators: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + accumulators = _ops.convert_to_tensor(accumulators, _dtypes.float32) + _inputs_flat = [parameters, accumulators] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingProximalAdagradParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_proximal_yogi_parameters(parameters: Annotated[Any, _atypes.Float32], v: Annotated[Any, _atypes.Float32], m: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""TODO: add doc. + + Args: + parameters: A `Tensor` of type `float32`. + v: A `Tensor` of type `float32`. + m: A `Tensor` of type `float32`. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingProximalYogiParameters", name, parameters, v, + m, "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_proximal_yogi_parameters_eager_fallback( + parameters, v, m, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingProximalYogiParameters", parameters=parameters, v=v, + m=m, num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingProximalYogiParameters = tf_export("raw_ops.LoadTPUEmbeddingProximalYogiParameters")(_ops.to_raw_op(load_tpu_embedding_proximal_yogi_parameters)) + + +def load_tpu_embedding_proximal_yogi_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], v: Annotated[Any, _atypes.Float32], m: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + v = _ops.convert_to_tensor(v, _dtypes.float32) + m = _ops.convert_to_tensor(m, _dtypes.float32) + _inputs_flat = [parameters, v, m] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingProximalYogiParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_rms_prop_parameters(parameters: Annotated[Any, _atypes.Float32], ms: Annotated[Any, _atypes.Float32], mom: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load RMSProp embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the RMSProp optimization algorithm. + ms: A `Tensor` of type `float32`. + Value of ms used in the RMSProp optimization algorithm. + mom: A `Tensor` of type `float32`. + Value of mom used in the RMSProp optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingRMSPropParameters", name, parameters, ms, mom, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_rms_prop_parameters_eager_fallback( + parameters, ms, mom, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingRMSPropParameters", parameters=parameters, ms=ms, + mom=mom, num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + return _op +LoadTPUEmbeddingRMSPropParameters = tf_export("raw_ops.LoadTPUEmbeddingRMSPropParameters")(_ops.to_raw_op(load_tpu_embedding_rms_prop_parameters)) + + +def load_tpu_embedding_rms_prop_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], ms: Annotated[Any, _atypes.Float32], mom: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + ms = _ops.convert_to_tensor(ms, _dtypes.float32) + mom = _ops.convert_to_tensor(mom, _dtypes.float32) + _inputs_flat = [parameters, ms, mom] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingRMSPropParameters", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def load_tpu_embedding_stochastic_gradient_descent_parameters(parameters: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Load SGD embedding parameters. + + An op that loads optimization parameters into HBM for embedding. Must be + preceded by a ConfigureTPUEmbeddingHost op that sets up the correct + embedding table configuration. For example, this op is used to install + parameters that are loaded from a checkpoint before a training loop is + executed. + + Args: + parameters: A `Tensor` of type `float32`. + Value of parameters used in the stochastic gradient descent optimization algorithm. + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "LoadTPUEmbeddingStochasticGradientDescentParameters", name, + parameters, "table_id", table_id, "table_name", table_name, + "num_shards", num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return load_tpu_embedding_stochastic_gradient_descent_parameters_eager_fallback( + parameters, table_id=table_id, table_name=table_name, + num_shards=num_shards, shard_id=shard_id, config=config, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "LoadTPUEmbeddingStochasticGradientDescentParameters", parameters=parameters, + num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + return _op +LoadTPUEmbeddingStochasticGradientDescentParameters = tf_export("raw_ops.LoadTPUEmbeddingStochasticGradientDescentParameters")(_ops.to_raw_op(load_tpu_embedding_stochastic_gradient_descent_parameters)) + + +def load_tpu_embedding_stochastic_gradient_descent_parameters_eager_fallback(parameters: Annotated[Any, _atypes.Float32], num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + parameters = _ops.convert_to_tensor(parameters, _dtypes.float32) + _inputs_flat = [parameters] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"LoadTPUEmbeddingStochasticGradientDescentParameters", + 0, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_OutfeedDequeue_dtype = TypeVar("TV_OutfeedDequeue_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def outfeed_dequeue(dtype: TV_OutfeedDequeue_dtype, shape, device_ordinal:int=-1, name=None) -> Annotated[Any, TV_OutfeedDequeue_dtype]: + r"""Retrieves a single tensor from the computation outfeed. + + This operation will block indefinitely until data is available. + + Args: + dtype: A `tf.DType`. The type of elements in the tensor. + shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. This should be -1 when the Op + is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedDequeue", name, "dtype", dtype, "shape", shape, + "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_dequeue_eager_fallback( + dtype=dtype, shape=shape, device_ordinal=device_ordinal, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedDequeue", dtype=dtype, shape=shape, + device_ordinal=device_ordinal, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "device_ordinal", + _op._get_attr_int("device_ordinal")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutfeedDequeue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OutfeedDequeue = tf_export("raw_ops.OutfeedDequeue")(_ops.to_raw_op(outfeed_dequeue)) + + +def outfeed_dequeue_eager_fallback(dtype: TV_OutfeedDequeue_dtype, shape, device_ordinal: int, name, ctx) -> Annotated[Any, TV_OutfeedDequeue_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _inputs_flat = [] + _attrs = ("dtype", dtype, "shape", shape, "device_ordinal", device_ordinal) + _result = _execute.execute(b"OutfeedDequeue", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutfeedDequeue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def outfeed_dequeue_tuple(dtypes, shapes, device_ordinal:int=-1, name=None): + r"""Retrieve multiple values from the computation outfeed. + + This operation will block indefinitely until data is available. Output `i` + corresponds to XLA tuple element `i`. + + Args: + dtypes: A list of `tf.DTypes` that has length `>= 1`. + The element types of each element in `outputs`. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of each tensor in `outputs`. + device_ordinal: An optional `int`. Defaults to `-1`. + The TPU device to use. This should be -1 when the Op + is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedDequeueTuple", name, "dtypes", dtypes, "shapes", shapes, + "device_ordinal", device_ordinal) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_dequeue_tuple_eager_fallback( + dtypes=dtypes, shapes=shapes, device_ordinal=device_ordinal, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'outfeed_dequeue_tuple' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'outfeed_dequeue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedDequeueTuple", dtypes=dtypes, shapes=shapes, + device_ordinal=device_ordinal, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("dtypes", _op.get_attr("dtypes"), "shapes", + _op.get_attr("shapes"), "device_ordinal", + _op._get_attr_int("device_ordinal")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutfeedDequeueTuple", _inputs_flat, _attrs, _result) + return _result + +OutfeedDequeueTuple = tf_export("raw_ops.OutfeedDequeueTuple")(_ops.to_raw_op(outfeed_dequeue_tuple)) + + +def outfeed_dequeue_tuple_eager_fallback(dtypes, shapes, device_ordinal: int, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'outfeed_dequeue_tuple' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'outfeed_dequeue_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if device_ordinal is None: + device_ordinal = -1 + device_ordinal = _execute.make_int(device_ordinal, "device_ordinal") + _inputs_flat = [] + _attrs = ("dtypes", dtypes, "shapes", shapes, "device_ordinal", + device_ordinal) + _result = _execute.execute(b"OutfeedDequeueTuple", len(dtypes), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutfeedDequeueTuple", _inputs_flat, _attrs, _result) + return _result + + +def outfeed_dequeue_tuple_v2(device_ordinal: Annotated[Any, _atypes.Int32], dtypes, shapes, name=None): + r"""Retrieve multiple values from the computation outfeed. Device ordinal is a +tensor allowing dynamic outfeed. + + This operation will block indefinitely until data is available. Output `i` + corresponds to XLA tuple element `i`. + + Args: + device_ordinal: A `Tensor` of type `int32`. + An int scalar tensor, representing the TPU device to use. This should be -1 when + the Op is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + dtypes: A list of `tf.DTypes` that has length `>= 1`. + The element types of each element in `outputs`. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of each tensor in `outputs`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `dtypes`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedDequeueTupleV2", name, device_ordinal, "dtypes", dtypes, + "shapes", shapes) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_dequeue_tuple_v2_eager_fallback( + device_ordinal, dtypes=dtypes, shapes=shapes, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'outfeed_dequeue_tuple_v2' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'outfeed_dequeue_tuple_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedDequeueTupleV2", device_ordinal=device_ordinal, dtypes=dtypes, + shapes=shapes, name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("dtypes", _op.get_attr("dtypes"), "shapes", + _op.get_attr("shapes")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutfeedDequeueTupleV2", _inputs_flat, _attrs, _result) + return _result + +OutfeedDequeueTupleV2 = tf_export("raw_ops.OutfeedDequeueTupleV2")(_ops.to_raw_op(outfeed_dequeue_tuple_v2)) + + +def outfeed_dequeue_tuple_v2_eager_fallback(device_ordinal: Annotated[Any, _atypes.Int32], dtypes, shapes, name, ctx): + if not isinstance(dtypes, (list, tuple)): + raise TypeError( + "Expected list for 'dtypes' argument to " + "'outfeed_dequeue_tuple_v2' Op, not %r." % dtypes) + dtypes = [_execute.make_type(_t, "dtypes") for _t in dtypes] + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'outfeed_dequeue_tuple_v2' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + device_ordinal = _ops.convert_to_tensor(device_ordinal, _dtypes.int32) + _inputs_flat = [device_ordinal] + _attrs = ("dtypes", dtypes, "shapes", shapes) + _result = _execute.execute(b"OutfeedDequeueTupleV2", len(dtypes), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutfeedDequeueTupleV2", _inputs_flat, _attrs, _result) + return _result + + +TV_OutfeedDequeueV2_dtype = TypeVar("TV_OutfeedDequeueV2_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def outfeed_dequeue_v2(device_ordinal: Annotated[Any, _atypes.Int32], dtype: TV_OutfeedDequeueV2_dtype, shape, name=None) -> Annotated[Any, TV_OutfeedDequeueV2_dtype]: + r"""Retrieves a single tensor from the computation outfeed. Device ordinal is a +tensor allowing dynamic outfeed. + + This operation will block indefinitely until data is available. + + Args: + device_ordinal: A `Tensor` of type `int32`. + An int scalar tensor, representing the TPU device to use. This should be -1 when + the Op is running on a TPU device, and >= 0 when the Op is running on the CPU + device. + dtype: A `tf.DType`. The type of elements in the tensor. + shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `dtype`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedDequeueV2", name, device_ordinal, "dtype", dtype, + "shape", shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_dequeue_v2_eager_fallback( + device_ordinal, dtype=dtype, shape=shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedDequeueV2", device_ordinal=device_ordinal, dtype=dtype, + shape=shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutfeedDequeueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OutfeedDequeueV2 = tf_export("raw_ops.OutfeedDequeueV2")(_ops.to_raw_op(outfeed_dequeue_v2)) + + +def outfeed_dequeue_v2_eager_fallback(device_ordinal: Annotated[Any, _atypes.Int32], dtype: TV_OutfeedDequeueV2_dtype, shape, name, ctx) -> Annotated[Any, TV_OutfeedDequeueV2_dtype]: + dtype = _execute.make_type(dtype, "dtype") + shape = _execute.make_shape(shape, "shape") + device_ordinal = _ops.convert_to_tensor(device_ordinal, _dtypes.int32) + _inputs_flat = [device_ordinal] + _attrs = ("dtype", dtype, "shape", shape) + _result = _execute.execute(b"OutfeedDequeueV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutfeedDequeueV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_OutfeedEnqueue_dtype = TypeVar("TV_OutfeedEnqueue_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def outfeed_enqueue(input: Annotated[Any, TV_OutfeedEnqueue_dtype], name=None): + r"""Enqueue a Tensor on the computation outfeed. + + Args: + input: A `Tensor`. A tensor that will be inserted into the outfeed queue. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedEnqueue", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_enqueue_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedEnqueue", input=input, name=name) + return _op +OutfeedEnqueue = tf_export("raw_ops.OutfeedEnqueue")(_ops.to_raw_op(outfeed_enqueue)) + + +def outfeed_enqueue_eager_fallback(input: Annotated[Any, TV_OutfeedEnqueue_dtype], name, ctx): + _attr_dtype, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("dtype", _attr_dtype) + _result = _execute.execute(b"OutfeedEnqueue", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +def outfeed_enqueue_tuple(inputs, name=None): + r"""Enqueue multiple Tensor values on the computation outfeed. + + Args: + inputs: A list of `Tensor` objects. + A list of tensors that will be inserted into the outfeed queue as an + XLA tuple. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutfeedEnqueueTuple", name, inputs) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return outfeed_enqueue_tuple_eager_fallback( + inputs, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutfeedEnqueueTuple", inputs=inputs, name=name) + return _op +OutfeedEnqueueTuple = tf_export("raw_ops.OutfeedEnqueueTuple")(_ops.to_raw_op(outfeed_enqueue_tuple)) + + +def outfeed_enqueue_tuple_eager_fallback(inputs, name, ctx): + _attr_dtypes, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx) + _inputs_flat = list(inputs) + _attrs = ("dtypes", _attr_dtypes) + _result = _execute.execute(b"OutfeedEnqueueTuple", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_Prelinearize_dtype = TypeVar("TV_Prelinearize_dtype", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def prelinearize(input: Annotated[Any, TV_Prelinearize_dtype], shape=[], layout=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""An op which linearizes one Tensor value to an opaque variant tensor. + + Args: + input: A `Tensor`. A tensor that will be linearized. + shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `[]`. + The shape of the tensor. + layout: An optional list of `ints`. Defaults to `[]`. + A vector holding the requested layout in minor-to-major sequence. If a layout + attribute is passed but its values are all -1 the layout will be computed by + the infeed operation. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Prelinearize", name, input, "shape", shape, "layout", layout) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return prelinearize_eager_fallback( + input, shape=shape, layout=layout, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if shape is None: + shape = [] + shape = _execute.make_shape(shape, "shape") + if layout is None: + layout = [] + if not isinstance(layout, (list, tuple)): + raise TypeError( + "Expected list for 'layout' argument to " + "'prelinearize' Op, not %r." % layout) + layout = [_execute.make_int(_i, "layout") for _i in layout] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Prelinearize", input=input, shape=shape, layout=layout, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtype", _op._get_attr_type("dtype"), "shape", + _op.get_attr("shape"), "layout", _op.get_attr("layout")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Prelinearize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Prelinearize = tf_export("raw_ops.Prelinearize")(_ops.to_raw_op(prelinearize)) + + +def prelinearize_eager_fallback(input: Annotated[Any, TV_Prelinearize_dtype], shape, layout, name, ctx) -> Annotated[Any, _atypes.Variant]: + if shape is None: + shape = [] + shape = _execute.make_shape(shape, "shape") + if layout is None: + layout = [] + if not isinstance(layout, (list, tuple)): + raise TypeError( + "Expected list for 'layout' argument to " + "'prelinearize' Op, not %r." % layout) + layout = [_execute.make_int(_i, "layout") for _i in layout] + _attr_dtype, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("dtype", _attr_dtype, "shape", shape, "layout", layout) + _result = _execute.execute(b"Prelinearize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Prelinearize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def prelinearize_tuple(inputs, shapes, layouts=[], name=None) -> Annotated[Any, _atypes.Variant]: + r"""An op which linearizes multiple Tensor values to an opaque variant tensor. + + Args: + inputs: A list of `Tensor` objects. + A list of tensors that will be provided using the infeed mechanism. + shapes: A list of shapes (each a `tf.TensorShape` or list of `ints`). + The shapes of each tensor in `inputs`. + layouts: An optional list of `ints`. Defaults to `[]`. + A vector holding the requested layout in minor-to-major sequence for all the + tuple shapes in the order the shapes appear in the "shapes" input. The layout + elements for a sub-shape can be set to -1 in which case the corresponding layout + will be computed by the infeed operation. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PrelinearizeTuple", name, inputs, "shapes", shapes, "layouts", + layouts) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return prelinearize_tuple_eager_fallback( + inputs, shapes=shapes, layouts=layouts, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'prelinearize_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if layouts is None: + layouts = [] + if not isinstance(layouts, (list, tuple)): + raise TypeError( + "Expected list for 'layouts' argument to " + "'prelinearize_tuple' Op, not %r." % layouts) + layouts = [_execute.make_int(_i, "layouts") for _i in layouts] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PrelinearizeTuple", inputs=inputs, shapes=shapes, layouts=layouts, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("dtypes", _op.get_attr("dtypes"), "shapes", + _op.get_attr("shapes"), "layouts", _op.get_attr("layouts")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PrelinearizeTuple", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PrelinearizeTuple = tf_export("raw_ops.PrelinearizeTuple")(_ops.to_raw_op(prelinearize_tuple)) + + +def prelinearize_tuple_eager_fallback(inputs, shapes, layouts, name, ctx) -> Annotated[Any, _atypes.Variant]: + if not isinstance(shapes, (list, tuple)): + raise TypeError( + "Expected list for 'shapes' argument to " + "'prelinearize_tuple' Op, not %r." % shapes) + shapes = [_execute.make_shape(_s, "shapes") for _s in shapes] + if layouts is None: + layouts = [] + if not isinstance(layouts, (list, tuple)): + raise TypeError( + "Expected list for 'layouts' argument to " + "'prelinearize_tuple' Op, not %r." % layouts) + layouts = [_execute.make_int(_i, "layouts") for _i in layouts] + _attr_dtypes, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx) + _inputs_flat = list(inputs) + _attrs = ("dtypes", _attr_dtypes, "shapes", shapes, "layouts", layouts) + _result = _execute.execute(b"PrelinearizeTuple", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PrelinearizeTuple", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ReadVariableXlaSplitND_T = TypeVar("TV_ReadVariableXlaSplitND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def read_variable_xla_split_nd(resource: Annotated[Any, _atypes.Resource], T: TV_ReadVariableXlaSplitND_T, N: int, num_splits, paddings=[], name=None): + r"""Splits resource variable input tensor across all dimensions. + + An op which splits the resource variable input tensor based on the given + num_splits attribute, pads slices optionally, and returned the slices. Slices + are returned in row-major order. + + This op may be generated via the TPU bridge. + + For example, with `input` tensor: + ``` + [[0, 1, 2], + [3, 4, 5], + [6, 7, 8]] + ``` + `num_splits`: + ``` + [2, 2] + ``` + and `paddings`: + ``` + [1, 1] + ``` + the expected `outputs` is: + ``` + [[0, 1], + [3, 4]] + [[2, 0], + [5, 0]] + [[6, 7], + [0, 0]] + [[8, 0], + [0, 0]] + ``` + + Args: + resource: A `Tensor` of type `resource`. + Resource variable of input tensor to split across all dimensions. + } + out_arg { + name: "outputs" + description: <= 1`. + num_splits: A list of `ints`. + Number of ways to split per dimension. Shape dimensions must be evenly + divisible. + paddings: An optional list of `ints`. Defaults to `[]`. + Optional list of right paddings per dimension of input tensor to apply before + splitting. This can be used to make a dimension evenly divisible. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReadVariableXlaSplitND", name, resource, "T", T, "N", N, + "num_splits", num_splits, "paddings", paddings) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return read_variable_xla_split_nd_eager_fallback( + resource, T=T, N=N, num_splits=num_splits, paddings=paddings, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + if not isinstance(num_splits, (list, tuple)): + raise TypeError( + "Expected list for 'num_splits' argument to " + "'read_variable_xla_split_nd' Op, not %r." % num_splits) + num_splits = [_execute.make_int(_i, "num_splits") for _i in num_splits] + if paddings is None: + paddings = [] + if not isinstance(paddings, (list, tuple)): + raise TypeError( + "Expected list for 'paddings' argument to " + "'read_variable_xla_split_nd' Op, not %r." % paddings) + paddings = [_execute.make_int(_i, "paddings") for _i in paddings] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReadVariableXlaSplitND", resource=resource, T=T, N=N, + num_splits=num_splits, paddings=paddings, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N"), + "num_splits", _op.get_attr("num_splits"), "paddings", + _op.get_attr("paddings")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ReadVariableXlaSplitND", _inputs_flat, _attrs, _result) + return _result + +ReadVariableXlaSplitND = tf_export("raw_ops.ReadVariableXlaSplitND")(_ops.to_raw_op(read_variable_xla_split_nd)) + + +def read_variable_xla_split_nd_eager_fallback(resource: Annotated[Any, _atypes.Resource], T: TV_ReadVariableXlaSplitND_T, N: int, num_splits, paddings, name, ctx): + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + if not isinstance(num_splits, (list, tuple)): + raise TypeError( + "Expected list for 'num_splits' argument to " + "'read_variable_xla_split_nd' Op, not %r." % num_splits) + num_splits = [_execute.make_int(_i, "num_splits") for _i in num_splits] + if paddings is None: + paddings = [] + if not isinstance(paddings, (list, tuple)): + raise TypeError( + "Expected list for 'paddings' argument to " + "'read_variable_xla_split_nd' Op, not %r." % paddings) + paddings = [_execute.make_int(_i, "paddings") for _i in paddings] + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = ("T", T, "N", N, "num_splits", num_splits, "paddings", paddings) + _result = _execute.execute(b"ReadVariableXlaSplitND", N, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ReadVariableXlaSplitND", _inputs_flat, _attrs, _result) + return _result + + +def recv_tpu_embedding_activations(num_outputs: int, config: str, name=None): + r"""An op that receives embedding activations on the TPU. + + The TPU system performs the embedding lookups and aggregations specified by + the arguments to TPUEmbeddingEnqueue(Integer/Sparse/SparseTensor)Batch. The + results of these aggregations are visible to the Tensorflow Graph as the + outputs of a RecvTPUEmbeddingActivations op. This op returns a list containing + one Tensor of activations per table specified in the model. There can be at + most one RecvTPUEmbeddingActivations op in the TPU graph. + + Args: + num_outputs: An `int` that is `>= 1`. + The number of output activation tensors, equal to the number of + embedding tables in the model. + config: A `string`. Serialized TPUEmbeddingConfiguration proto. + name: A name for the operation (optional). + + Returns: + A list of `num_outputs` `Tensor` objects with type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RecvTPUEmbeddingActivations", name, "num_outputs", num_outputs, + "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return recv_tpu_embedding_activations_eager_fallback( + num_outputs=num_outputs, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_outputs = _execute.make_int(num_outputs, "num_outputs") + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RecvTPUEmbeddingActivations", num_outputs=num_outputs, config=config, + name=name) + _result = _outputs[:] + if not _result: + return _op + if _execute.must_record_gradient(): + _attrs = ("num_outputs", _op._get_attr_int("num_outputs"), "config", + _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RecvTPUEmbeddingActivations", _inputs_flat, _attrs, _result) + return _result + +RecvTPUEmbeddingActivations = tf_export("raw_ops.RecvTPUEmbeddingActivations")(_ops.to_raw_op(recv_tpu_embedding_activations)) + + +def recv_tpu_embedding_activations_eager_fallback(num_outputs: int, config: str, name, ctx): + num_outputs = _execute.make_int(num_outputs, "num_outputs") + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("num_outputs", num_outputs, "config", config) + _result = _execute.execute(b"RecvTPUEmbeddingActivations", num_outputs, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RecvTPUEmbeddingActivations", _inputs_flat, _attrs, _result) + return _result + +_RetrieveTPUEmbeddingADAMParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingADAMParameters", + ["parameters", "momenta", "velocities"]) + + +def retrieve_tpu_embedding_adam_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve ADAM embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, momenta, velocities). + + parameters: A `Tensor` of type `float32`. + momenta: A `Tensor` of type `float32`. + velocities: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingADAMParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingADAMParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_adam_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingADAMParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingADAMParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingADAMParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingADAMParameters = tf_export("raw_ops.RetrieveTPUEmbeddingADAMParameters")(_ops.to_raw_op(retrieve_tpu_embedding_adam_parameters)) + + +def retrieve_tpu_embedding_adam_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingADAMParameters", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingADAMParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingADAMParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingAdadeltaParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingAdadeltaParameters", + ["parameters", "accumulators", "updates"]) + + +def retrieve_tpu_embedding_adadelta_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve Adadelta embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators, updates). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + updates: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingAdadeltaParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingAdadeltaParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_adadelta_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingAdadeltaParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingAdadeltaParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdadeltaParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingAdadeltaParameters = tf_export("raw_ops.RetrieveTPUEmbeddingAdadeltaParameters")(_ops.to_raw_op(retrieve_tpu_embedding_adadelta_parameters)) + + +def retrieve_tpu_embedding_adadelta_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingAdadeltaParameters", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingAdadeltaParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdadeltaParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingAdagradMomentumParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingAdagradMomentumParameters", + ["parameters", "accumulators", "momenta"]) + + +def retrieve_tpu_embedding_adagrad_momentum_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve Adagrad Momentum embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators, momenta). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + momenta: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingAdagradMomentumParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingAdagradMomentumParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_adagrad_momentum_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingAdagradMomentumParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingAdagradMomentumParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdagradMomentumParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingAdagradMomentumParameters = tf_export("raw_ops.RetrieveTPUEmbeddingAdagradMomentumParameters")(_ops.to_raw_op(retrieve_tpu_embedding_adagrad_momentum_parameters)) + + +def retrieve_tpu_embedding_adagrad_momentum_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingAdagradMomentumParameters", + 3, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingAdagradMomentumParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdagradMomentumParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingAdagradParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingAdagradParameters", + ["parameters", "accumulators"]) + + +def retrieve_tpu_embedding_adagrad_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve Adagrad embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingAdagradParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingAdagradParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_adagrad_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingAdagradParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingAdagradParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdagradParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingAdagradParameters = tf_export("raw_ops.RetrieveTPUEmbeddingAdagradParameters")(_ops.to_raw_op(retrieve_tpu_embedding_adagrad_parameters)) + + +def retrieve_tpu_embedding_adagrad_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingAdagradParameters", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingAdagradParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingAdagradParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingCenteredRMSPropParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingCenteredRMSPropParameters", + ["parameters", "ms", "mom", "mg"]) + + +def retrieve_tpu_embedding_centered_rms_prop_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve centered RMSProp embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, ms, mom, mg). + + parameters: A `Tensor` of type `float32`. + ms: A `Tensor` of type `float32`. + mom: A `Tensor` of type `float32`. + mg: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingCenteredRMSPropParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingCenteredRMSPropParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_centered_rms_prop_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingCenteredRMSPropParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingCenteredRMSPropParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingCenteredRMSPropParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingCenteredRMSPropParameters = tf_export("raw_ops.RetrieveTPUEmbeddingCenteredRMSPropParameters")(_ops.to_raw_op(retrieve_tpu_embedding_centered_rms_prop_parameters)) + + +def retrieve_tpu_embedding_centered_rms_prop_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingCenteredRMSPropParameters", + 4, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingCenteredRMSPropParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingCenteredRMSPropParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingFTRLParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingFTRLParameters", + ["parameters", "accumulators", "linears"]) + + +def retrieve_tpu_embedding_ftrl_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve FTRL embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators, linears). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + linears: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingFTRLParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingFTRLParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_ftrl_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingFTRLParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingFTRLParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingFTRLParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingFTRLParameters = tf_export("raw_ops.RetrieveTPUEmbeddingFTRLParameters")(_ops.to_raw_op(retrieve_tpu_embedding_ftrl_parameters)) + + +def retrieve_tpu_embedding_ftrl_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingFTRLParameters", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingFTRLParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingFTRLParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingFrequencyEstimatorParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingFrequencyEstimatorParameters", + ["parameters", "last_hit_step"]) + + +def retrieve_tpu_embedding_frequency_estimator_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve frequency estimator embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, last_hit_step). + + parameters: A `Tensor` of type `float32`. + last_hit_step: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingFrequencyEstimatorParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingFrequencyEstimatorParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_frequency_estimator_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingFrequencyEstimatorParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingFrequencyEstimatorParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingFrequencyEstimatorParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingFrequencyEstimatorParameters = tf_export("raw_ops.RetrieveTPUEmbeddingFrequencyEstimatorParameters")(_ops.to_raw_op(retrieve_tpu_embedding_frequency_estimator_parameters)) + + +def retrieve_tpu_embedding_frequency_estimator_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingFrequencyEstimatorParameters", + 2, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingFrequencyEstimatorParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingFrequencyEstimatorParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingMDLAdagradLightParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingMDLAdagradLightParameters", + ["parameters", "accumulators", "weights", "benefits"]) + + +def retrieve_tpu_embedding_mdl_adagrad_light_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve MDL Adagrad Light embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators, weights, benefits). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + weights: A `Tensor` of type `float32`. + benefits: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingMDLAdagradLightParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingMDLAdagradLightParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_mdl_adagrad_light_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingMDLAdagradLightParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingMDLAdagradLightParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingMDLAdagradLightParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingMDLAdagradLightParameters = tf_export("raw_ops.RetrieveTPUEmbeddingMDLAdagradLightParameters")(_ops.to_raw_op(retrieve_tpu_embedding_mdl_adagrad_light_parameters)) + + +def retrieve_tpu_embedding_mdl_adagrad_light_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingMDLAdagradLightParameters", + 4, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingMDLAdagradLightParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingMDLAdagradLightParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingMomentumParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingMomentumParameters", + ["parameters", "momenta"]) + + +def retrieve_tpu_embedding_momentum_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve Momentum embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, momenta). + + parameters: A `Tensor` of type `float32`. + momenta: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingMomentumParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingMomentumParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_momentum_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingMomentumParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingMomentumParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingMomentumParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingMomentumParameters = tf_export("raw_ops.RetrieveTPUEmbeddingMomentumParameters")(_ops.to_raw_op(retrieve_tpu_embedding_momentum_parameters)) + + +def retrieve_tpu_embedding_momentum_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingMomentumParameters", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingMomentumParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingMomentumParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingProximalAdagradParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingProximalAdagradParameters", + ["parameters", "accumulators"]) + + +def retrieve_tpu_embedding_proximal_adagrad_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve proximal Adagrad embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, accumulators). + + parameters: A `Tensor` of type `float32`. + accumulators: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingProximalAdagradParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingProximalAdagradParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_proximal_adagrad_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingProximalAdagradParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingProximalAdagradParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingProximalAdagradParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingProximalAdagradParameters = tf_export("raw_ops.RetrieveTPUEmbeddingProximalAdagradParameters")(_ops.to_raw_op(retrieve_tpu_embedding_proximal_adagrad_parameters)) + + +def retrieve_tpu_embedding_proximal_adagrad_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingProximalAdagradParameters", + 2, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingProximalAdagradParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingProximalAdagradParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingProximalYogiParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingProximalYogiParameters", + ["parameters", "v", "m"]) + + +def retrieve_tpu_embedding_proximal_yogi_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""TODO: add doc. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, v, m). + + parameters: A `Tensor` of type `float32`. + v: A `Tensor` of type `float32`. + m: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingProximalYogiParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingProximalYogiParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_proximal_yogi_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingProximalYogiParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingProximalYogiParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingProximalYogiParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingProximalYogiParameters = tf_export("raw_ops.RetrieveTPUEmbeddingProximalYogiParameters")(_ops.to_raw_op(retrieve_tpu_embedding_proximal_yogi_parameters)) + + +def retrieve_tpu_embedding_proximal_yogi_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingProximalYogiParameters", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingProximalYogiParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingProximalYogiParametersOutput._make(_result) + return _result + +_RetrieveTPUEmbeddingRMSPropParametersOutput = collections.namedtuple( + "RetrieveTPUEmbeddingRMSPropParameters", + ["parameters", "ms", "mom"]) + + +def retrieve_tpu_embedding_rms_prop_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None): + r"""Retrieve RMSProp embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (parameters, ms, mom). + + parameters: A `Tensor` of type `float32`. + ms: A `Tensor` of type `float32`. + mom: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingRMSPropParameters", name, "table_id", + table_id, "table_name", table_name, "num_shards", num_shards, + "shard_id", shard_id, "config", config) + _result = _RetrieveTPUEmbeddingRMSPropParametersOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_rms_prop_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingRMSPropParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingRMSPropParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingRMSPropParametersOutput._make(_result) + return _result + +RetrieveTPUEmbeddingRMSPropParameters = tf_export("raw_ops.RetrieveTPUEmbeddingRMSPropParameters")(_ops.to_raw_op(retrieve_tpu_embedding_rms_prop_parameters)) + + +def retrieve_tpu_embedding_rms_prop_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx): + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingRMSPropParameters", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingRMSPropParameters", _inputs_flat, _attrs, _result) + _result = _RetrieveTPUEmbeddingRMSPropParametersOutput._make(_result) + return _result + + +def retrieve_tpu_embedding_stochastic_gradient_descent_parameters(num_shards: int, shard_id: int, table_id:int=-1, table_name:str="", config:str="", name=None) -> Annotated[Any, _atypes.Float32]: + r"""Retrieve SGD embedding parameters. + + An op that retrieves optimization parameters from embedding to host + memory. Must be preceded by a ConfigureTPUEmbeddingHost op that sets up + the correct embedding table configuration. For example, this op is + used to retrieve updated parameters before saving a checkpoint. + + Args: + num_shards: An `int`. + shard_id: An `int`. + table_id: An optional `int`. Defaults to `-1`. + table_name: An optional `string`. Defaults to `""`. + config: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RetrieveTPUEmbeddingStochasticGradientDescentParameters", name, + "table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return retrieve_tpu_embedding_stochastic_gradient_descent_parameters_eager_fallback( + table_id=table_id, table_name=table_name, num_shards=num_shards, + shard_id=shard_id, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RetrieveTPUEmbeddingStochasticGradientDescentParameters", num_shards=num_shards, + shard_id=shard_id, + table_id=table_id, + table_name=table_name, + config=config, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "table_name", + _op.get_attr("table_name"), "num_shards", + _op._get_attr_int("num_shards"), "shard_id", + _op._get_attr_int("shard_id"), "config", _op.get_attr("config")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RetrieveTPUEmbeddingStochasticGradientDescentParameters", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RetrieveTPUEmbeddingStochasticGradientDescentParameters = tf_export("raw_ops.RetrieveTPUEmbeddingStochasticGradientDescentParameters")(_ops.to_raw_op(retrieve_tpu_embedding_stochastic_gradient_descent_parameters)) + + +def retrieve_tpu_embedding_stochastic_gradient_descent_parameters_eager_fallback(num_shards: int, shard_id: int, table_id: int, table_name: str, config: str, name, ctx) -> Annotated[Any, _atypes.Float32]: + num_shards = _execute.make_int(num_shards, "num_shards") + shard_id = _execute.make_int(shard_id, "shard_id") + if table_id is None: + table_id = -1 + table_id = _execute.make_int(table_id, "table_id") + if table_name is None: + table_name = "" + table_name = _execute.make_str(table_name, "table_name") + if config is None: + config = "" + config = _execute.make_str(config, "config") + _inputs_flat = [] + _attrs = ("table_id", table_id, "table_name", table_name, "num_shards", + num_shards, "shard_id", shard_id, "config", config) + _result = _execute.execute(b"RetrieveTPUEmbeddingStochasticGradientDescentParameters", + 1, inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RetrieveTPUEmbeddingStochasticGradientDescentParameters", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def send_tpu_embedding_gradients(inputs: Annotated[List[Any], _atypes.Float32], learning_rates: Annotated[List[Any], _atypes.Float32], config: str, name=None): + r"""Performs gradient updates of embedding tables. + + Args: + inputs: A list of at least 1 `Tensor` objects with type `float32`. + A TensorList of gradients with which to update embedding tables. + This argument has the same length and shapes as the return value of + RecvTPUEmbeddingActivations, but contains gradients of the model's loss + with respect to the embedding activations. The embedding tables are updated + from these gradients via the optimizer specified in the TPU embedding + configuration given to tpu.initialize_system. + learning_rates: A list of `Tensor` objects with type `float32`. + A TensorList of float32 scalars, one for each dynamic learning + rate tag: see the comments in + //third_party/tensorflow/core/protobuf/tpu/optimization_parameters.proto. + Multiple tables can share the same dynamic learning rate tag as specified + in the configuration. If the learning rates for all tables are constant, + this list should be empty. + config: A `string`. Serialized TPUEmbeddingConfiguration proto. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SendTPUEmbeddingGradients", name, inputs, learning_rates, + "config", config) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return send_tpu_embedding_gradients_eager_fallback( + inputs, learning_rates, config=config, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'send_tpu_embedding_gradients' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(learning_rates, (list, tuple)): + raise TypeError( + "Expected list for 'learning_rates' argument to " + "'send_tpu_embedding_gradients' Op, not %r." % learning_rates) + _attr_NN = len(learning_rates) + config = _execute.make_str(config, "config") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SendTPUEmbeddingGradients", inputs=inputs, + learning_rates=learning_rates, + config=config, name=name) + return _op +SendTPUEmbeddingGradients = tf_export("raw_ops.SendTPUEmbeddingGradients")(_ops.to_raw_op(send_tpu_embedding_gradients)) + + +def send_tpu_embedding_gradients_eager_fallback(inputs: Annotated[List[Any], _atypes.Float32], learning_rates: Annotated[List[Any], _atypes.Float32], config: str, name, ctx): + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'send_tpu_embedding_gradients' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(learning_rates, (list, tuple)): + raise TypeError( + "Expected list for 'learning_rates' argument to " + "'send_tpu_embedding_gradients' Op, not %r." % learning_rates) + _attr_NN = len(learning_rates) + config = _execute.make_str(config, "config") + inputs = _ops.convert_n_to_tensor(inputs, _dtypes.float32) + learning_rates = _ops.convert_n_to_tensor(learning_rates, _dtypes.float32) + _inputs_flat = list(inputs) + list(learning_rates) + _attrs = ("N", _attr_N, "NN", _attr_NN, "config", config) + _result = _execute.execute(b"SendTPUEmbeddingGradients", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def shutdown_distributed_tpu(name=None): + r"""Shuts down a running distributed TPU system. + + The op returns an error if no system is running. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ShutdownDistributedTPU", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return shutdown_distributed_tpu_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ShutdownDistributedTPU", name=name) + return _op +ShutdownDistributedTPU = tf_export("raw_ops.ShutdownDistributedTPU")(_ops.to_raw_op(shutdown_distributed_tpu)) + + +def shutdown_distributed_tpu_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"ShutdownDistributedTPU", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +def tpu_compilation_result(name=None) -> Annotated[Any, _atypes.String]: + r"""Returns the result of a TPU compilation. + + This operation returns the result of a TPU compilation as a serialized + CompilationResultProto, which holds a status and an error message if an error + occurred during compilation. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUCompilationResult", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_compilation_result_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUCompilationResult", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUCompilationResult", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUCompilationResult = tf_export("raw_ops.TPUCompilationResult")(_ops.to_raw_op(tpu_compilation_result)) + + +def tpu_compilation_result_eager_fallback(name, ctx) -> Annotated[Any, _atypes.String]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"TPUCompilationResult", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUCompilationResult", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tpu_embedding_activations(embedding_variable: Annotated[Any, _atypes.Float32], sliced_activations: Annotated[Any, _atypes.Float32], table_id: int, lookup_id: int, name=None) -> Annotated[Any, _atypes.Float32]: + r"""An op enabling differentiation of TPU Embeddings. + + This op simply returns its first input, which is assumed to have been sliced + from the Tensors returned by TPUEmbeddingDequeueActivations. The presence of + this op, and its first argument being a trainable Variable, enables automatic + differentiation of graphs containing embeddings via the TPU Embedding Python + libraries. + + Args: + embedding_variable: A `Tensor` of type `float32`. + A trainable variable, enabling optimizers to find this op. + sliced_activations: A `Tensor` of type `float32`. + The embedding activations Tensor to return. + table_id: An `int` that is `>= 0`. + The id of the table in the embedding layer configuration from which + these activations were computed. + lookup_id: An `int` that is `>= 0`. + Identifier of the set of embedding indices which produced these + activations. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUEmbeddingActivations", name, embedding_variable, + sliced_activations, "table_id", table_id, "lookup_id", lookup_id) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_embedding_activations_eager_fallback( + embedding_variable, sliced_activations, table_id=table_id, + lookup_id=lookup_id, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + table_id = _execute.make_int(table_id, "table_id") + lookup_id = _execute.make_int(lookup_id, "lookup_id") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUEmbeddingActivations", embedding_variable=embedding_variable, + sliced_activations=sliced_activations, + table_id=table_id, lookup_id=lookup_id, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("table_id", _op._get_attr_int("table_id"), "lookup_id", + _op._get_attr_int("lookup_id")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUEmbeddingActivations", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUEmbeddingActivations = tf_export("raw_ops.TPUEmbeddingActivations")(_ops.to_raw_op(tpu_embedding_activations)) + + +def tpu_embedding_activations_eager_fallback(embedding_variable: Annotated[Any, _atypes.Float32], sliced_activations: Annotated[Any, _atypes.Float32], table_id: int, lookup_id: int, name, ctx) -> Annotated[Any, _atypes.Float32]: + table_id = _execute.make_int(table_id, "table_id") + lookup_id = _execute.make_int(lookup_id, "lookup_id") + embedding_variable = _ops.convert_to_tensor(embedding_variable, _dtypes.float32) + sliced_activations = _ops.convert_to_tensor(sliced_activations, _dtypes.float32) + _inputs_flat = [embedding_variable, sliced_activations] + _attrs = ("table_id", table_id, "lookup_id", lookup_id) + _result = _execute.execute(b"TPUEmbeddingActivations", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUEmbeddingActivations", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tpu_ordinal_selector(name=None) -> Annotated[Any, _atypes.Int32]: + r"""A TPU core selector Op. + + This Op produces a set of TPU cores (for warm-up) or a single TPU core + (for regular inference) to execute the TPU program on. The output is + consumed by TPUPartitionedCall. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUOrdinalSelector", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_ordinal_selector_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUOrdinalSelector", name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUOrdinalSelector", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUOrdinalSelector = tf_export("raw_ops.TPUOrdinalSelector")(_ops.to_raw_op(tpu_ordinal_selector)) + + +def tpu_ordinal_selector_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"TPUOrdinalSelector", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUOrdinalSelector", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def tpu_partitioned_call(args, device_ordinal: Annotated[Any, _atypes.Int32], Tout, f, autotuner_thresh:int=0, name=None): + r"""Calls a function placed on a specified TPU device. + + Args: + args: A list of `Tensor` objects. The arguments to the function. + device_ordinal: A `Tensor` of type `int32`. + The TPU device ordinal to run the function on. + Tout: A list of `tf.DTypes`. The types of the outputs of the function. + f: A function decorated with @Defun. The function to call. + autotuner_thresh: An optional `int`. Defaults to `0`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUPartitionedCall", name, args, device_ordinal, "Tout", Tout, + "f", f, "autotuner_thresh", autotuner_thresh) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_partitioned_call_eager_fallback( + args, device_ordinal, Tout=Tout, f=f, + autotuner_thresh=autotuner_thresh, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'tpu_partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if autotuner_thresh is None: + autotuner_thresh = 0 + autotuner_thresh = _execute.make_int(autotuner_thresh, "autotuner_thresh") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUPartitionedCall", args=args, device_ordinal=device_ordinal, + Tout=Tout, f=f, + autotuner_thresh=autotuner_thresh, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op.get_attr("Tin"), "Tout", _op.get_attr("Tout"), "f", + _op.get_attr("f"), "autotuner_thresh", + _op._get_attr_int("autotuner_thresh")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUPartitionedCall", _inputs_flat, _attrs, _result) + return _result + +TPUPartitionedCall = tf_export("raw_ops.TPUPartitionedCall")(_ops.to_raw_op(tpu_partitioned_call)) + + +def tpu_partitioned_call_eager_fallback(args, device_ordinal: Annotated[Any, _atypes.Int32], Tout, f, autotuner_thresh: int, name, ctx): + if not isinstance(Tout, (list, tuple)): + raise TypeError( + "Expected list for 'Tout' argument to " + "'tpu_partitioned_call' Op, not %r." % Tout) + Tout = [_execute.make_type(_t, "Tout") for _t in Tout] + if autotuner_thresh is None: + autotuner_thresh = 0 + autotuner_thresh = _execute.make_int(autotuner_thresh, "autotuner_thresh") + _attr_Tin, args = _execute.convert_to_mixed_eager_tensors(args, ctx) + device_ordinal = _ops.convert_to_tensor(device_ordinal, _dtypes.int32) + _inputs_flat = list(args) + [device_ordinal] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "f", f, "autotuner_thresh", + autotuner_thresh) + _result = _execute.execute(b"TPUPartitionedCall", len(Tout), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUPartitionedCall", _inputs_flat, _attrs, _result) + return _result + + +def tpu_replicate_metadata(num_replicas: int, num_cores_per_replica:int=1, topology:str="", use_tpu:bool=True, device_assignment=[], computation_shape=[], host_compute_core=[], padding_map=[], step_marker_location:str="STEP_MARK_AT_ENTRY", allow_soft_placement:bool=False, use_spmd_for_xla_partitioning:bool=False, tpu_compile_options_proto:str="", name=None): + r"""Metadata indicating how the TPU computation should be replicated. + + This operation holds the metadata common to operations of a `tpu.replicate()` computation subgraph. + + Args: + num_replicas: An `int` that is `>= 0`. + Number of replicas of the computation + num_cores_per_replica: An optional `int`. Defaults to `1`. + Number of cores per replica. Used for model parallelism. + topology: An optional `string`. Defaults to `""`. + TopologyProto indicating the topology of the TPU pod slice. + use_tpu: An optional `bool`. Defaults to `True`. + Whether to place the computation on the TPU. + device_assignment: An optional list of `ints`. Defaults to `[]`. + The assignment of devices for the computation. + computation_shape: An optional list of `ints`. Defaults to `[]`. + DEPRECATED. Use num_cores_per_replica instead. + host_compute_core: An optional list of `strings`. Defaults to `[]`. + padding_map: An optional list of `strings`. Defaults to `[]`. + step_marker_location: An optional `string`. Defaults to `"STEP_MARK_AT_ENTRY"`. + allow_soft_placement: An optional `bool`. Defaults to `False`. + use_spmd_for_xla_partitioning: An optional `bool`. Defaults to `False`. + tpu_compile_options_proto: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUReplicateMetadata", name, "num_replicas", num_replicas, + "num_cores_per_replica", num_cores_per_replica, "topology", topology, + "use_tpu", use_tpu, "device_assignment", device_assignment, + "computation_shape", computation_shape, "host_compute_core", + host_compute_core, "padding_map", padding_map, "step_marker_location", + step_marker_location, "allow_soft_placement", allow_soft_placement, + "use_spmd_for_xla_partitioning", use_spmd_for_xla_partitioning, + "tpu_compile_options_proto", tpu_compile_options_proto) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_replicate_metadata_eager_fallback( + num_replicas=num_replicas, + num_cores_per_replica=num_cores_per_replica, topology=topology, + use_tpu=use_tpu, device_assignment=device_assignment, + computation_shape=computation_shape, + host_compute_core=host_compute_core, padding_map=padding_map, + step_marker_location=step_marker_location, + allow_soft_placement=allow_soft_placement, + use_spmd_for_xla_partitioning=use_spmd_for_xla_partitioning, + tpu_compile_options_proto=tpu_compile_options_proto, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_replicas = _execute.make_int(num_replicas, "num_replicas") + if num_cores_per_replica is None: + num_cores_per_replica = 1 + num_cores_per_replica = _execute.make_int(num_cores_per_replica, "num_cores_per_replica") + if topology is None: + topology = "" + topology = _execute.make_str(topology, "topology") + if use_tpu is None: + use_tpu = True + use_tpu = _execute.make_bool(use_tpu, "use_tpu") + if device_assignment is None: + device_assignment = [] + if not isinstance(device_assignment, (list, tuple)): + raise TypeError( + "Expected list for 'device_assignment' argument to " + "'tpu_replicate_metadata' Op, not %r." % device_assignment) + device_assignment = [_execute.make_int(_i, "device_assignment") for _i in device_assignment] + if computation_shape is None: + computation_shape = [] + if not isinstance(computation_shape, (list, tuple)): + raise TypeError( + "Expected list for 'computation_shape' argument to " + "'tpu_replicate_metadata' Op, not %r." % computation_shape) + computation_shape = [_execute.make_int(_i, "computation_shape") for _i in computation_shape] + if host_compute_core is None: + host_compute_core = [] + if not isinstance(host_compute_core, (list, tuple)): + raise TypeError( + "Expected list for 'host_compute_core' argument to " + "'tpu_replicate_metadata' Op, not %r." % host_compute_core) + host_compute_core = [_execute.make_str(_s, "host_compute_core") for _s in host_compute_core] + if padding_map is None: + padding_map = [] + if not isinstance(padding_map, (list, tuple)): + raise TypeError( + "Expected list for 'padding_map' argument to " + "'tpu_replicate_metadata' Op, not %r." % padding_map) + padding_map = [_execute.make_str(_s, "padding_map") for _s in padding_map] + if step_marker_location is None: + step_marker_location = "STEP_MARK_AT_ENTRY" + step_marker_location = _execute.make_str(step_marker_location, "step_marker_location") + if allow_soft_placement is None: + allow_soft_placement = False + allow_soft_placement = _execute.make_bool(allow_soft_placement, "allow_soft_placement") + if use_spmd_for_xla_partitioning is None: + use_spmd_for_xla_partitioning = False + use_spmd_for_xla_partitioning = _execute.make_bool(use_spmd_for_xla_partitioning, "use_spmd_for_xla_partitioning") + if tpu_compile_options_proto is None: + tpu_compile_options_proto = "" + tpu_compile_options_proto = _execute.make_str(tpu_compile_options_proto, "tpu_compile_options_proto") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUReplicateMetadata", num_replicas=num_replicas, + num_cores_per_replica=num_cores_per_replica, + topology=topology, use_tpu=use_tpu, + device_assignment=device_assignment, + computation_shape=computation_shape, + host_compute_core=host_compute_core, + padding_map=padding_map, + step_marker_location=step_marker_location, + allow_soft_placement=allow_soft_placement, + use_spmd_for_xla_partitioning=use_spmd_for_xla_partitioning, + tpu_compile_options_proto=tpu_compile_options_proto, + name=name) + return _op +TPUReplicateMetadata = tf_export("raw_ops.TPUReplicateMetadata")(_ops.to_raw_op(tpu_replicate_metadata)) + + +def tpu_replicate_metadata_eager_fallback(num_replicas: int, num_cores_per_replica: int, topology: str, use_tpu: bool, device_assignment, computation_shape, host_compute_core, padding_map, step_marker_location: str, allow_soft_placement: bool, use_spmd_for_xla_partitioning: bool, tpu_compile_options_proto: str, name, ctx): + num_replicas = _execute.make_int(num_replicas, "num_replicas") + if num_cores_per_replica is None: + num_cores_per_replica = 1 + num_cores_per_replica = _execute.make_int(num_cores_per_replica, "num_cores_per_replica") + if topology is None: + topology = "" + topology = _execute.make_str(topology, "topology") + if use_tpu is None: + use_tpu = True + use_tpu = _execute.make_bool(use_tpu, "use_tpu") + if device_assignment is None: + device_assignment = [] + if not isinstance(device_assignment, (list, tuple)): + raise TypeError( + "Expected list for 'device_assignment' argument to " + "'tpu_replicate_metadata' Op, not %r." % device_assignment) + device_assignment = [_execute.make_int(_i, "device_assignment") for _i in device_assignment] + if computation_shape is None: + computation_shape = [] + if not isinstance(computation_shape, (list, tuple)): + raise TypeError( + "Expected list for 'computation_shape' argument to " + "'tpu_replicate_metadata' Op, not %r." % computation_shape) + computation_shape = [_execute.make_int(_i, "computation_shape") for _i in computation_shape] + if host_compute_core is None: + host_compute_core = [] + if not isinstance(host_compute_core, (list, tuple)): + raise TypeError( + "Expected list for 'host_compute_core' argument to " + "'tpu_replicate_metadata' Op, not %r." % host_compute_core) + host_compute_core = [_execute.make_str(_s, "host_compute_core") for _s in host_compute_core] + if padding_map is None: + padding_map = [] + if not isinstance(padding_map, (list, tuple)): + raise TypeError( + "Expected list for 'padding_map' argument to " + "'tpu_replicate_metadata' Op, not %r." % padding_map) + padding_map = [_execute.make_str(_s, "padding_map") for _s in padding_map] + if step_marker_location is None: + step_marker_location = "STEP_MARK_AT_ENTRY" + step_marker_location = _execute.make_str(step_marker_location, "step_marker_location") + if allow_soft_placement is None: + allow_soft_placement = False + allow_soft_placement = _execute.make_bool(allow_soft_placement, "allow_soft_placement") + if use_spmd_for_xla_partitioning is None: + use_spmd_for_xla_partitioning = False + use_spmd_for_xla_partitioning = _execute.make_bool(use_spmd_for_xla_partitioning, "use_spmd_for_xla_partitioning") + if tpu_compile_options_proto is None: + tpu_compile_options_proto = "" + tpu_compile_options_proto = _execute.make_str(tpu_compile_options_proto, "tpu_compile_options_proto") + _inputs_flat = [] + _attrs = ("num_replicas", num_replicas, "num_cores_per_replica", + num_cores_per_replica, "topology", topology, "use_tpu", use_tpu, + "device_assignment", device_assignment, "computation_shape", + computation_shape, "host_compute_core", host_compute_core, "padding_map", + padding_map, "step_marker_location", step_marker_location, + "allow_soft_placement", allow_soft_placement, + "use_spmd_for_xla_partitioning", use_spmd_for_xla_partitioning, + "tpu_compile_options_proto", tpu_compile_options_proto) + _result = _execute.execute(b"TPUReplicateMetadata", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_TPUReplicatedInput_T = TypeVar("TV_TPUReplicatedInput_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_replicated_input(inputs: Annotated[List[Any], TV_TPUReplicatedInput_T], is_mirrored_variable:bool=False, index:int=-1, is_packed:bool=False, name=None) -> Annotated[Any, TV_TPUReplicatedInput_T]: + r"""Connects N inputs to an N-way replicated TPU computation. + + This operation holds a replicated input to a `tpu.replicate()` computation subgraph. + Each replicated input has the same shape and type alongside the output. + + For example: + ``` + %a = "tf.opA"() + %b = "tf.opB"() + %replicated_input = "tf.TPUReplicatedInput"(%a, %b) + %computation = "tf.Computation"(%replicated_input) + ``` + The above computation has a replicated input of two replicas. + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + is_mirrored_variable: An optional `bool`. Defaults to `False`. + index: An optional `int`. Defaults to `-1`. + is_packed: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUReplicatedInput", name, inputs, "is_mirrored_variable", + is_mirrored_variable, "index", index, "is_packed", is_packed) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_replicated_input_eager_fallback( + inputs, is_mirrored_variable=is_mirrored_variable, index=index, + is_packed=is_packed, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_replicated_input' Op, not %r." % inputs) + _attr_N = len(inputs) + if is_mirrored_variable is None: + is_mirrored_variable = False + is_mirrored_variable = _execute.make_bool(is_mirrored_variable, "is_mirrored_variable") + if index is None: + index = -1 + index = _execute.make_int(index, "index") + if is_packed is None: + is_packed = False + is_packed = _execute.make_bool(is_packed, "is_packed") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUReplicatedInput", inputs=inputs, + is_mirrored_variable=is_mirrored_variable, + index=index, is_packed=is_packed, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "is_mirrored_variable", + _op._get_attr_bool("is_mirrored_variable"), "index", + _op._get_attr_int("index"), "is_packed", + _op._get_attr_bool("is_packed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUReplicatedInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUReplicatedInput = tf_export("raw_ops.TPUReplicatedInput")(_ops.to_raw_op(tpu_replicated_input)) + + +def tpu_replicated_input_eager_fallback(inputs: Annotated[List[Any], TV_TPUReplicatedInput_T], is_mirrored_variable: bool, index: int, is_packed: bool, name, ctx) -> Annotated[Any, TV_TPUReplicatedInput_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_replicated_input' Op, not %r." % inputs) + _attr_N = len(inputs) + if is_mirrored_variable is None: + is_mirrored_variable = False + is_mirrored_variable = _execute.make_bool(is_mirrored_variable, "is_mirrored_variable") + if index is None: + index = -1 + index = _execute.make_int(index, "index") + if is_packed is None: + is_packed = False + is_packed = _execute.make_bool(is_packed, "is_packed") + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "T", _attr_T, "is_mirrored_variable", + is_mirrored_variable, "index", index, "is_packed", is_packed) + _result = _execute.execute(b"TPUReplicatedInput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUReplicatedInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TPUReplicatedOutput_T = TypeVar("TV_TPUReplicatedOutput_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_replicated_output(input: Annotated[Any, TV_TPUReplicatedOutput_T], num_replicas: int, name=None): + r"""Connects N outputs from an N-way replicated TPU computation. + + This operation holds a replicated output from a `tpu.replicate()` computation subgraph. + Each replicated output has the same shape and type alongside the input. + + For example: + ``` + %computation = "tf.Computation"() + %replicated_output:2 = "tf.TPUReplicatedOutput"(%computation) + ``` + The above computation has a replicated output of two replicas. + + Args: + input: A `Tensor`. + num_replicas: An `int` that is `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `num_replicas` `Tensor` objects with the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUReplicatedOutput", name, input, "num_replicas", + num_replicas) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_replicated_output_eager_fallback( + input, num_replicas=num_replicas, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_replicas = _execute.make_int(num_replicas, "num_replicas") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUReplicatedOutput", input=input, num_replicas=num_replicas, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("num_replicas", _op._get_attr_int("num_replicas"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUReplicatedOutput", _inputs_flat, _attrs, _result) + return _result + +TPUReplicatedOutput = tf_export("raw_ops.TPUReplicatedOutput")(_ops.to_raw_op(tpu_replicated_output)) + + +def tpu_replicated_output_eager_fallback(input: Annotated[Any, TV_TPUReplicatedOutput_T], num_replicas: int, name, ctx): + num_replicas = _execute.make_int(num_replicas, "num_replicas") + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("num_replicas", num_replicas, "T", _attr_T) + _result = _execute.execute(b"TPUReplicatedOutput", num_replicas, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUReplicatedOutput", _inputs_flat, _attrs, _result) + return _result + + +def worker_heartbeat(request: Annotated[Any, _atypes.String], name=None) -> Annotated[Any, _atypes.String]: + r"""Worker heartbeat op. + + Heartbeats may be sent periodically to indicate the coordinator is still active, + to retrieve the current worker status and to expedite shutdown when necessary. + + Args: + request: A `Tensor` of type `string`. + A string tensor containing a serialized WorkerHeartbeatRequest + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "WorkerHeartbeat", name, request) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return worker_heartbeat_eager_fallback( + request, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "WorkerHeartbeat", request=request, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "WorkerHeartbeat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +WorkerHeartbeat = tf_export("raw_ops.WorkerHeartbeat")(_ops.to_raw_op(worker_heartbeat)) + + +def worker_heartbeat_eager_fallback(request: Annotated[Any, _atypes.String], name, ctx) -> Annotated[Any, _atypes.String]: + request = _ops.convert_to_tensor(request, _dtypes.string) + _inputs_flat = [request] + _attrs = None + _result = _execute.execute(b"WorkerHeartbeat", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "WorkerHeartbeat", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_XlaConcatND_T = TypeVar("TV_XlaConcatND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def xla_concat_nd(inputs: Annotated[List[Any], TV_XlaConcatND_T], num_concats, paddings=[], name=None) -> Annotated[Any, TV_XlaConcatND_T]: + r"""Concats input tensor across all dimensions. + + An op which merges slices the input tensor based on the given num_splits + attribute, strips paddings optionally, and returns the merged tensor without + paddings. + + This op may be generated via the TPU bridge. + + For example, with `input` tensor: + ``` + [[0, 1], + [4, 5]] + [[2, 3], + [6, 7]] + [[8, 9], + [12, 13]] + [[10, 11], + [14, 15]] + ``` + `num_splits`: + ``` + [2, 2] + ``` + and `paddings`: + ``` + [1, 1] + ``` + the expected `outputs` is: + ``` + [[0, 1, 2], + [4, 5, 6], + [8, 9, 10]] + ``` + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + Input tensor slices in row-major order to merge across all dimensions. All + inputs must have the same shape. + } + out_arg { + name: "output" + description: < Annotated[Any, TV_XlaConcatND_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'xla_concat_nd' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(num_concats, (list, tuple)): + raise TypeError( + "Expected list for 'num_concats' argument to " + "'xla_concat_nd' Op, not %r." % num_concats) + num_concats = [_execute.make_int(_i, "num_concats") for _i in num_concats] + if paddings is None: + paddings = [] + if not isinstance(paddings, (list, tuple)): + raise TypeError( + "Expected list for 'paddings' argument to " + "'xla_concat_nd' Op, not %r." % paddings) + paddings = [_execute.make_int(_i, "paddings") for _i in paddings] + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("T", _attr_T, "N", _attr_N, "num_concats", num_concats, + "paddings", paddings) + _result = _execute.execute(b"XlaConcatND", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "XlaConcatND", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_XlaSplitND_T = TypeVar("TV_XlaSplitND_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def xla_split_nd(input: Annotated[Any, TV_XlaSplitND_T], N: int, num_splits, paddings=[], name=None): + r"""Splits input tensor across all dimensions. + + An op which slices the input tensor based on the given num_splits attribute, + pads slices optionally, and returned the slices. Slices are returned in + row-major order. + + This op may be generated via the TPU bridge. + + For example, with `input` tensor: + ``` + [[0, 1, 2], + [3, 4, 5], + [6, 7, 8]] + ``` + `num_splits`: + ``` + [2, 2] + ``` + and `paddings`: + ``` + [1, 1] + ``` + the expected `outputs` is: + ``` + [[0, 1], + [3, 4]] + [[2, 0], + [5, 0]] + [[6, 7], + [0, 0]] + [[8, 0], + [0, 0]] + ``` + + Args: + input: A `Tensor`. Input tensor to split across all dimensions. + } + out_arg { + name: "outputs" + description: <= 1`. + num_splits: A list of `ints`. + Number of ways to split per dimension. Shape dimensions must be evenly + divisible. + paddings: An optional list of `ints`. Defaults to `[]`. + Optional list of right paddings per dimension of input tensor to apply before + splitting. This can be used to make a dimension evenly divisible. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "XlaSplitND", name, input, "N", N, "num_splits", num_splits, + "paddings", paddings) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return xla_split_nd_eager_fallback( + input, N=N, num_splits=num_splits, paddings=paddings, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + N = _execute.make_int(N, "N") + if not isinstance(num_splits, (list, tuple)): + raise TypeError( + "Expected list for 'num_splits' argument to " + "'xla_split_nd' Op, not %r." % num_splits) + num_splits = [_execute.make_int(_i, "num_splits") for _i in num_splits] + if paddings is None: + paddings = [] + if not isinstance(paddings, (list, tuple)): + raise TypeError( + "Expected list for 'paddings' argument to " + "'xla_split_nd' Op, not %r." % paddings) + paddings = [_execute.make_int(_i, "paddings") for _i in paddings] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "XlaSplitND", input=input, N=N, num_splits=num_splits, + paddings=paddings, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N"), + "num_splits", _op.get_attr("num_splits"), "paddings", + _op.get_attr("paddings")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "XlaSplitND", _inputs_flat, _attrs, _result) + return _result + +XlaSplitND = tf_export("raw_ops.XlaSplitND")(_ops.to_raw_op(xla_split_nd)) + + +def xla_split_nd_eager_fallback(input: Annotated[Any, TV_XlaSplitND_T], N: int, num_splits, paddings, name, ctx): + N = _execute.make_int(N, "N") + if not isinstance(num_splits, (list, tuple)): + raise TypeError( + "Expected list for 'num_splits' argument to " + "'xla_split_nd' Op, not %r." % num_splits) + num_splits = [_execute.make_int(_i, "num_splits") for _i in num_splits] + if paddings is None: + paddings = [] + if not isinstance(paddings, (list, tuple)): + raise TypeError( + "Expected list for 'paddings' argument to " + "'xla_split_nd' Op, not %r." % paddings) + paddings = [_execute.make_int(_i, "paddings") for _i in paddings] + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + _inputs_flat = [input] + _attrs = ("T", _attr_T, "N", N, "num_splits", num_splits, "paddings", + paddings) + _result = _execute.execute(b"XlaSplitND", N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "XlaSplitND", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_partition_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_partition_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9b61abfa8797e6007c5826bf8292a3800543a8c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_tpu_partition_ops.py @@ -0,0 +1,351 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_TPUPartitionedInput_T = TypeVar("TV_TPUPartitionedInput_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_partitioned_input(inputs: Annotated[List[Any], TV_TPUPartitionedInput_T], partition_dim:int=0, name=None) -> Annotated[Any, TV_TPUPartitionedInput_T]: + r"""An op that groups a list of partitioned inputs together. This op + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + A list of partitioned inputs which must have the same shape. + partition_dim: An optional `int`. Defaults to `0`. + An integer describles which dimension is partitioned. -1 means + those inputs are replicated. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUPartitionedInput", name, inputs, "partition_dim", + partition_dim) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_partitioned_input_eager_fallback( + inputs, partition_dim=partition_dim, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_partitioned_input' Op, not %r." % inputs) + _attr_N = len(inputs) + if partition_dim is None: + partition_dim = 0 + partition_dim = _execute.make_int(partition_dim, "partition_dim") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUPartitionedInput", inputs=inputs, partition_dim=partition_dim, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "partition_dim", _op._get_attr_int("partition_dim")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUPartitionedInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUPartitionedInput = tf_export("raw_ops.TPUPartitionedInput")(_ops.to_raw_op(tpu_partitioned_input)) + + +def tpu_partitioned_input_eager_fallback(inputs: Annotated[List[Any], TV_TPUPartitionedInput_T], partition_dim: int, name, ctx) -> Annotated[Any, TV_TPUPartitionedInput_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_partitioned_input' Op, not %r." % inputs) + _attr_N = len(inputs) + if partition_dim is None: + partition_dim = 0 + partition_dim = _execute.make_int(partition_dim, "partition_dim") + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "T", _attr_T, "partition_dim", partition_dim) + _result = _execute.execute(b"TPUPartitionedInput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUPartitionedInput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TPUPartitionedInputV2_T = TypeVar("TV_TPUPartitionedInputV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_partitioned_input_v2(inputs: Annotated[List[Any], TV_TPUPartitionedInputV2_T], partition_dims, is_packed:bool=False, name=None) -> Annotated[Any, TV_TPUPartitionedInputV2_T]: + r"""An op that groups a list of partitioned inputs together. Supports ND sharding. + + Args: + inputs: A list of at least 1 `Tensor` objects with the same type. + A list of partitioned inputs which must have the same shape. + partition_dims: A list of `ints`. + A list of integers describing how each dimension is partitioned. Emptiness + indicates the inputs are replicated. + is_packed: An optional `bool`. Defaults to `False`. + Indicates whether the input is a packed resource. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUPartitionedInputV2", name, inputs, "partition_dims", + partition_dims, "is_packed", is_packed) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_partitioned_input_v2_eager_fallback( + inputs, partition_dims=partition_dims, is_packed=is_packed, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_partitioned_input_v2' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(partition_dims, (list, tuple)): + raise TypeError( + "Expected list for 'partition_dims' argument to " + "'tpu_partitioned_input_v2' Op, not %r." % partition_dims) + partition_dims = [_execute.make_int(_i, "partition_dims") for _i in partition_dims] + if is_packed is None: + is_packed = False + is_packed = _execute.make_bool(is_packed, "is_packed") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUPartitionedInputV2", inputs=inputs, partition_dims=partition_dims, + is_packed=is_packed, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N"), "T", _op._get_attr_type("T"), + "partition_dims", _op.get_attr("partition_dims"), "is_packed", + _op._get_attr_bool("is_packed")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUPartitionedInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TPUPartitionedInputV2 = tf_export("raw_ops.TPUPartitionedInputV2")(_ops.to_raw_op(tpu_partitioned_input_v2)) + + +def tpu_partitioned_input_v2_eager_fallback(inputs: Annotated[List[Any], TV_TPUPartitionedInputV2_T], partition_dims, is_packed: bool, name, ctx) -> Annotated[Any, TV_TPUPartitionedInputV2_T]: + if not isinstance(inputs, (list, tuple)): + raise TypeError( + "Expected list for 'inputs' argument to " + "'tpu_partitioned_input_v2' Op, not %r." % inputs) + _attr_N = len(inputs) + if not isinstance(partition_dims, (list, tuple)): + raise TypeError( + "Expected list for 'partition_dims' argument to " + "'tpu_partitioned_input_v2' Op, not %r." % partition_dims) + partition_dims = [_execute.make_int(_i, "partition_dims") for _i in partition_dims] + if is_packed is None: + is_packed = False + is_packed = _execute.make_bool(is_packed, "is_packed") + _attr_T, inputs = _execute.args_to_matching_eager(list(inputs), ctx, []) + _inputs_flat = list(inputs) + _attrs = ("N", _attr_N, "T", _attr_T, "partition_dims", partition_dims, + "is_packed", is_packed) + _result = _execute.execute(b"TPUPartitionedInputV2", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUPartitionedInputV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TPUPartitionedOutput_T = TypeVar("TV_TPUPartitionedOutput_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_partitioned_output(inputs: Annotated[Any, TV_TPUPartitionedOutput_T], num_splits: int, partition_dim:int=0, name=None): + r"""An op that demultiplexes a tensor to be sharded by XLA to a list of partitioned + + outputs outside the XLA computation. + + Args: + inputs: A `Tensor`. + A tensor which represents the full shape of partitioned tensors. + num_splits: An `int` that is `>= 1`. + partition_dim: An optional `int`. Defaults to `0`. + An integer describles which dimension is partitioned. + name: A name for the operation (optional). + + Returns: + A list of `num_splits` `Tensor` objects with the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUPartitionedOutput", name, inputs, "num_splits", num_splits, + "partition_dim", partition_dim) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_partitioned_output_eager_fallback( + inputs, num_splits=num_splits, partition_dim=partition_dim, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_splits = _execute.make_int(num_splits, "num_splits") + if partition_dim is None: + partition_dim = 0 + partition_dim = _execute.make_int(partition_dim, "partition_dim") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUPartitionedOutput", inputs=inputs, num_splits=num_splits, + partition_dim=partition_dim, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_splits", + _op._get_attr_int("num_splits"), "partition_dim", + _op._get_attr_int("partition_dim")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUPartitionedOutput", _inputs_flat, _attrs, _result) + return _result + +TPUPartitionedOutput = tf_export("raw_ops.TPUPartitionedOutput")(_ops.to_raw_op(tpu_partitioned_output)) + + +def tpu_partitioned_output_eager_fallback(inputs: Annotated[Any, TV_TPUPartitionedOutput_T], num_splits: int, partition_dim: int, name, ctx): + num_splits = _execute.make_int(num_splits, "num_splits") + if partition_dim is None: + partition_dim = 0 + partition_dim = _execute.make_int(partition_dim, "partition_dim") + _attr_T, (inputs,) = _execute.args_to_matching_eager([inputs], ctx, []) + _inputs_flat = [inputs] + _attrs = ("T", _attr_T, "num_splits", num_splits, "partition_dim", + partition_dim) + _result = _execute.execute(b"TPUPartitionedOutput", num_splits, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUPartitionedOutput", _inputs_flat, _attrs, _result) + return _result + + +TV_TPUPartitionedOutputV2_T = TypeVar("TV_TPUPartitionedOutputV2_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def tpu_partitioned_output_v2(inputs: Annotated[Any, TV_TPUPartitionedOutputV2_T], num_splits: int, partition_dims, name=None): + r"""An op that demultiplexes a tensor to be sharded by XLA to a list of partitioned + + outputs outside the XLA computation. Supports ND sharding. + + Args: + inputs: A `Tensor`. + A tensor which represents the full shape of partitioned tensors. + num_splits: An `int` that is `>= 1`. + partition_dims: A list of `ints`. + A list of integers describing how each dimension is partitioned. Emptiness + indicates the inputs are replicated. + name: A name for the operation (optional). + + Returns: + A list of `num_splits` `Tensor` objects with the same type as `inputs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TPUPartitionedOutputV2", name, inputs, "num_splits", + num_splits, "partition_dims", partition_dims) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return tpu_partitioned_output_v2_eager_fallback( + inputs, num_splits=num_splits, partition_dims=partition_dims, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + num_splits = _execute.make_int(num_splits, "num_splits") + if not isinstance(partition_dims, (list, tuple)): + raise TypeError( + "Expected list for 'partition_dims' argument to " + "'tpu_partitioned_output_v2' Op, not %r." % partition_dims) + partition_dims = [_execute.make_int(_i, "partition_dims") for _i in partition_dims] + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TPUPartitionedOutputV2", inputs=inputs, num_splits=num_splits, + partition_dims=partition_dims, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "num_splits", + _op._get_attr_int("num_splits"), "partition_dims", + _op.get_attr("partition_dims")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TPUPartitionedOutputV2", _inputs_flat, _attrs, _result) + return _result + +TPUPartitionedOutputV2 = tf_export("raw_ops.TPUPartitionedOutputV2")(_ops.to_raw_op(tpu_partitioned_output_v2)) + + +def tpu_partitioned_output_v2_eager_fallback(inputs: Annotated[Any, TV_TPUPartitionedOutputV2_T], num_splits: int, partition_dims, name, ctx): + num_splits = _execute.make_int(num_splits, "num_splits") + if not isinstance(partition_dims, (list, tuple)): + raise TypeError( + "Expected list for 'partition_dims' argument to " + "'tpu_partitioned_output_v2' Op, not %r." % partition_dims) + partition_dims = [_execute.make_int(_i, "partition_dims") for _i in partition_dims] + _attr_T, (inputs,) = _execute.args_to_matching_eager([inputs], ctx, []) + _inputs_flat = [inputs] + _attrs = ("T", _attr_T, "num_splits", num_splits, "partition_dims", + partition_dims) + _result = _execute.execute(b"TPUPartitionedOutputV2", num_splits, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TPUPartitionedOutputV2", _inputs_flat, _attrs, _result) + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_training_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_training_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6709891b53b859b801ca0b3960dee8d2b4b7cf24 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_training_ops.py @@ -0,0 +1,4350 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_ApplyAdaMax_T = TypeVar("TV_ApplyAdaMax_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_ada_max(var: Annotated[Any, TV_ApplyAdaMax_T], m: Annotated[Any, TV_ApplyAdaMax_T], v: Annotated[Any, TV_ApplyAdaMax_T], beta1_power: Annotated[Any, TV_ApplyAdaMax_T], lr: Annotated[Any, TV_ApplyAdaMax_T], beta1: Annotated[Any, TV_ApplyAdaMax_T], beta2: Annotated[Any, TV_ApplyAdaMax_T], epsilon: Annotated[Any, TV_ApplyAdaMax_T], grad: Annotated[Any, TV_ApplyAdaMax_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyAdaMax_T]: + r"""Update '*var' according to the AdaMax algorithm. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + v_t <- max(beta2 * v_{t-1}, abs(g)) + variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon) + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + m: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + v: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + beta1_power: A `Tensor`. Must have the same type as `var`. + Must be a scalar. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + beta1: A `Tensor`. Must have the same type as `var`. + Momentum factor. Must be a scalar. + beta2: A `Tensor`. Must have the same type as `var`. + Momentum factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, m, and v tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_ada_max op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdaMax", var=var, m=m, v=v, beta1_power=beta1_power, lr=lr, + beta1=beta1, beta2=beta2, epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdaMax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdaMax = tf_export("raw_ops.ApplyAdaMax")(_ops.to_raw_op(apply_ada_max)) + + +def apply_ada_max_eager_fallback(var: Annotated[Any, TV_ApplyAdaMax_T], m: Annotated[Any, TV_ApplyAdaMax_T], v: Annotated[Any, TV_ApplyAdaMax_T], beta1_power: Annotated[Any, TV_ApplyAdaMax_T], lr: Annotated[Any, TV_ApplyAdaMax_T], beta1: Annotated[Any, TV_ApplyAdaMax_T], beta2: Annotated[Any, TV_ApplyAdaMax_T], epsilon: Annotated[Any, TV_ApplyAdaMax_T], grad: Annotated[Any, TV_ApplyAdaMax_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyAdaMax_T]: + raise RuntimeError("apply_ada_max op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAdadelta_T = TypeVar("TV_ApplyAdadelta_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_adadelta(var: Annotated[Any, TV_ApplyAdadelta_T], accum: Annotated[Any, TV_ApplyAdadelta_T], accum_update: Annotated[Any, TV_ApplyAdadelta_T], lr: Annotated[Any, TV_ApplyAdadelta_T], rho: Annotated[Any, TV_ApplyAdadelta_T], epsilon: Annotated[Any, TV_ApplyAdadelta_T], grad: Annotated[Any, TV_ApplyAdadelta_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyAdadelta_T]: + r"""Update '*var' according to the adadelta scheme. + + accum = rho() * accum + (1 - rho()) * grad.square(); + update = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad; + update_accum = rho() * update_accum + (1 - rho()) * update.square(); + var -= update; + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + accum_update: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var, accum and update_accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_adadelta op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdadelta", var=var, accum=accum, accum_update=accum_update, + lr=lr, rho=rho, epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdadelta", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdadelta = tf_export("raw_ops.ApplyAdadelta")(_ops.to_raw_op(apply_adadelta)) + + +def apply_adadelta_eager_fallback(var: Annotated[Any, TV_ApplyAdadelta_T], accum: Annotated[Any, TV_ApplyAdadelta_T], accum_update: Annotated[Any, TV_ApplyAdadelta_T], lr: Annotated[Any, TV_ApplyAdadelta_T], rho: Annotated[Any, TV_ApplyAdadelta_T], epsilon: Annotated[Any, TV_ApplyAdadelta_T], grad: Annotated[Any, TV_ApplyAdadelta_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyAdadelta_T]: + raise RuntimeError("apply_adadelta op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAdagrad_T = TypeVar("TV_ApplyAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_adagrad(var: Annotated[Any, TV_ApplyAdagrad_T], accum: Annotated[Any, TV_ApplyAdagrad_T], lr: Annotated[Any, TV_ApplyAdagrad_T], grad: Annotated[Any, TV_ApplyAdagrad_T], use_locking:bool=False, update_slots:bool=True, name=None) -> Annotated[Any, TV_ApplyAdagrad_T]: + r"""Update '*var' according to the adagrad scheme. + + accum += grad * grad + var -= lr * grad * (1 / sqrt(accum)) + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_adagrad op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdagrad", var=var, accum=accum, lr=lr, grad=grad, + use_locking=use_locking, update_slots=update_slots, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "update_slots", + _op._get_attr_bool("update_slots")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdagrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdagrad = tf_export("raw_ops.ApplyAdagrad")(_ops.to_raw_op(apply_adagrad)) + + +def apply_adagrad_eager_fallback(var: Annotated[Any, TV_ApplyAdagrad_T], accum: Annotated[Any, TV_ApplyAdagrad_T], lr: Annotated[Any, TV_ApplyAdagrad_T], grad: Annotated[Any, TV_ApplyAdagrad_T], use_locking: bool, update_slots: bool, name, ctx) -> Annotated[Any, TV_ApplyAdagrad_T]: + raise RuntimeError("apply_adagrad op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAdagradDA_T = TypeVar("TV_ApplyAdagradDA_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_adagrad_da(var: Annotated[Any, TV_ApplyAdagradDA_T], gradient_accumulator: Annotated[Any, TV_ApplyAdagradDA_T], gradient_squared_accumulator: Annotated[Any, TV_ApplyAdagradDA_T], grad: Annotated[Any, TV_ApplyAdagradDA_T], lr: Annotated[Any, TV_ApplyAdagradDA_T], l1: Annotated[Any, TV_ApplyAdagradDA_T], l2: Annotated[Any, TV_ApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyAdagradDA_T]: + r"""Update '*var' according to the proximal adagrad scheme. + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + gradient_accumulator: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + gradient_squared_accumulator: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + global_step: A `Tensor` of type `int64`. + Training step number. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_adagrad_da op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdagradDA", var=var, gradient_accumulator=gradient_accumulator, + gradient_squared_accumulator=gradient_squared_accumulator, + grad=grad, lr=lr, l1=l1, l2=l2, + global_step=global_step, use_locking=use_locking, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdagradDA", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdagradDA = tf_export("raw_ops.ApplyAdagradDA")(_ops.to_raw_op(apply_adagrad_da)) + + +def apply_adagrad_da_eager_fallback(var: Annotated[Any, TV_ApplyAdagradDA_T], gradient_accumulator: Annotated[Any, TV_ApplyAdagradDA_T], gradient_squared_accumulator: Annotated[Any, TV_ApplyAdagradDA_T], grad: Annotated[Any, TV_ApplyAdagradDA_T], lr: Annotated[Any, TV_ApplyAdagradDA_T], l1: Annotated[Any, TV_ApplyAdagradDA_T], l2: Annotated[Any, TV_ApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyAdagradDA_T]: + raise RuntimeError("apply_adagrad_da op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAdagradV2_T = TypeVar("TV_ApplyAdagradV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_adagrad_v2(var: Annotated[Any, TV_ApplyAdagradV2_T], accum: Annotated[Any, TV_ApplyAdagradV2_T], lr: Annotated[Any, TV_ApplyAdagradV2_T], epsilon: Annotated[Any, TV_ApplyAdagradV2_T], grad: Annotated[Any, TV_ApplyAdagradV2_T], use_locking:bool=False, update_slots:bool=True, name=None) -> Annotated[Any, TV_ApplyAdagradV2_T]: + r"""Update '*var' according to the adagrad scheme. + + accum += grad * grad + var -= lr * grad * (1 / sqrt(accum)) + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_adagrad_v2 op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdagradV2", var=var, accum=accum, lr=lr, epsilon=epsilon, + grad=grad, use_locking=use_locking, + update_slots=update_slots, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "update_slots", + _op._get_attr_bool("update_slots")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdagradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdagradV2 = tf_export("raw_ops.ApplyAdagradV2")(_ops.to_raw_op(apply_adagrad_v2)) + + +def apply_adagrad_v2_eager_fallback(var: Annotated[Any, TV_ApplyAdagradV2_T], accum: Annotated[Any, TV_ApplyAdagradV2_T], lr: Annotated[Any, TV_ApplyAdagradV2_T], epsilon: Annotated[Any, TV_ApplyAdagradV2_T], grad: Annotated[Any, TV_ApplyAdagradV2_T], use_locking: bool, update_slots: bool, name, ctx) -> Annotated[Any, TV_ApplyAdagradV2_T]: + raise RuntimeError("apply_adagrad_v2 op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAdam_T = TypeVar("TV_ApplyAdam_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_adam(var: Annotated[Any, TV_ApplyAdam_T], m: Annotated[Any, TV_ApplyAdam_T], v: Annotated[Any, TV_ApplyAdam_T], beta1_power: Annotated[Any, TV_ApplyAdam_T], beta2_power: Annotated[Any, TV_ApplyAdam_T], lr: Annotated[Any, TV_ApplyAdam_T], beta1: Annotated[Any, TV_ApplyAdam_T], beta2: Annotated[Any, TV_ApplyAdam_T], epsilon: Annotated[Any, TV_ApplyAdam_T], grad: Annotated[Any, TV_ApplyAdam_T], use_locking:bool=False, use_nesterov:bool=False, name=None) -> Annotated[Any, TV_ApplyAdam_T]: + r"""Update '*var' according to the Adam algorithm. + + $$\text{lr}_t := \mathrm{lr} \cdot \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t}$$ + $$m_t := \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g$$ + $$v_t := \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g^2$$ + $$\text{var} := \begin{cases} \text{var} - (m_t \beta_1 + g \cdot (1 - \beta_1))\cdot\text{lr}_t/(\sqrt{v_t} + \epsilon), &\text{if use_nesterov}\\\\ \text{var} - m_t \cdot \text{lr}_t /(\sqrt{v_t} + \epsilon), &\text{otherwise} \end{cases}$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + m: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + v: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + beta1_power: A `Tensor`. Must have the same type as `var`. + Must be a scalar. + beta2_power: A `Tensor`. Must have the same type as `var`. + Must be a scalar. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + beta1: A `Tensor`. Must have the same type as `var`. + Momentum factor. Must be a scalar. + beta2: A `Tensor`. Must have the same type as `var`. + Momentum factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, m, and v tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, uses the nesterov update. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_adam op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAdam", var=var, m=m, v=v, beta1_power=beta1_power, + beta2_power=beta2_power, lr=lr, beta1=beta1, beta2=beta2, + epsilon=epsilon, grad=grad, use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "use_nesterov", + _op._get_attr_bool("use_nesterov")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAdam", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAdam = tf_export("raw_ops.ApplyAdam")(_ops.to_raw_op(apply_adam)) + + +def apply_adam_eager_fallback(var: Annotated[Any, TV_ApplyAdam_T], m: Annotated[Any, TV_ApplyAdam_T], v: Annotated[Any, TV_ApplyAdam_T], beta1_power: Annotated[Any, TV_ApplyAdam_T], beta2_power: Annotated[Any, TV_ApplyAdam_T], lr: Annotated[Any, TV_ApplyAdam_T], beta1: Annotated[Any, TV_ApplyAdam_T], beta2: Annotated[Any, TV_ApplyAdam_T], epsilon: Annotated[Any, TV_ApplyAdam_T], grad: Annotated[Any, TV_ApplyAdam_T], use_locking: bool, use_nesterov: bool, name, ctx) -> Annotated[Any, TV_ApplyAdam_T]: + raise RuntimeError("apply_adam op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyAddSign_T = TypeVar("TV_ApplyAddSign_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_add_sign(var: Annotated[Any, TV_ApplyAddSign_T], m: Annotated[Any, TV_ApplyAddSign_T], lr: Annotated[Any, TV_ApplyAddSign_T], alpha: Annotated[Any, TV_ApplyAddSign_T], sign_decay: Annotated[Any, TV_ApplyAddSign_T], beta: Annotated[Any, TV_ApplyAddSign_T], grad: Annotated[Any, TV_ApplyAddSign_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyAddSign_T]: + r"""Update '*var' according to the AddSign update. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + update <- (alpha + sign_decay * sign(g) *sign(m)) * g + variable <- variable - lr_t * update + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + m: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + alpha: A `Tensor`. Must have the same type as `var`. Must be a scalar. + sign_decay: A `Tensor`. Must have the same type as `var`. + Must be a scalar. + beta: A `Tensor`. Must have the same type as `var`. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and m tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_add_sign op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyAddSign", var=var, m=m, lr=lr, alpha=alpha, + sign_decay=sign_decay, beta=beta, grad=grad, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyAddSign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyAddSign = tf_export("raw_ops.ApplyAddSign")(_ops.to_raw_op(apply_add_sign)) + + +def apply_add_sign_eager_fallback(var: Annotated[Any, TV_ApplyAddSign_T], m: Annotated[Any, TV_ApplyAddSign_T], lr: Annotated[Any, TV_ApplyAddSign_T], alpha: Annotated[Any, TV_ApplyAddSign_T], sign_decay: Annotated[Any, TV_ApplyAddSign_T], beta: Annotated[Any, TV_ApplyAddSign_T], grad: Annotated[Any, TV_ApplyAddSign_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyAddSign_T]: + raise RuntimeError("apply_add_sign op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyCenteredRMSProp_T = TypeVar("TV_ApplyCenteredRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_centered_rms_prop(var: Annotated[Any, TV_ApplyCenteredRMSProp_T], mg: Annotated[Any, TV_ApplyCenteredRMSProp_T], ms: Annotated[Any, TV_ApplyCenteredRMSProp_T], mom: Annotated[Any, TV_ApplyCenteredRMSProp_T], lr: Annotated[Any, TV_ApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ApplyCenteredRMSProp_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyCenteredRMSProp_T]: + r"""Update '*var' according to the centered RMSProp algorithm. + + The centered RMSProp algorithm uses an estimate of the centered second moment + (i.e., the variance) for normalization, as opposed to regular RMSProp, which + uses the (uncentered) second moment. This often helps with training, but is + slightly more expensive in terms of computation and memory. + + Note that in dense implementation of this algorithm, mg, ms, and mom will + update even if the grad is zero, but in this sparse implementation, mg, ms, + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + mean_grad = decay * mean_grad + (1-decay) * gradient + + Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) + + mg <- rho * mg_{t-1} + (1-rho) * grad + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon) + var <- var - mom + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + mg: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + ms: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + mom: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `var`. + Momentum Scale. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, mg, ms, and mom tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_centered_rms_prop op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyCenteredRMSProp", var=var, mg=mg, ms=ms, mom=mom, lr=lr, + rho=rho, momentum=momentum, epsilon=epsilon, + grad=grad, use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyCenteredRMSProp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyCenteredRMSProp = tf_export("raw_ops.ApplyCenteredRMSProp")(_ops.to_raw_op(apply_centered_rms_prop)) + + +def apply_centered_rms_prop_eager_fallback(var: Annotated[Any, TV_ApplyCenteredRMSProp_T], mg: Annotated[Any, TV_ApplyCenteredRMSProp_T], ms: Annotated[Any, TV_ApplyCenteredRMSProp_T], mom: Annotated[Any, TV_ApplyCenteredRMSProp_T], lr: Annotated[Any, TV_ApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ApplyCenteredRMSProp_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyCenteredRMSProp_T]: + raise RuntimeError("apply_centered_rms_prop op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyFtrl_T = TypeVar("TV_ApplyFtrl_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_ftrl(var: Annotated[Any, TV_ApplyFtrl_T], accum: Annotated[Any, TV_ApplyFtrl_T], linear: Annotated[Any, TV_ApplyFtrl_T], grad: Annotated[Any, TV_ApplyFtrl_T], lr: Annotated[Any, TV_ApplyFtrl_T], l1: Annotated[Any, TV_ApplyFtrl_T], l2: Annotated[Any, TV_ApplyFtrl_T], lr_power: Annotated[Any, TV_ApplyFtrl_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None) -> Annotated[Any, TV_ApplyFtrl_T]: + r"""Update '*var' according to the Ftrl-proximal scheme. + + accum_new = accum + grad * grad + linear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + linear: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + lr_power: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_ftrl op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyFtrl", var=var, accum=accum, linear=linear, grad=grad, lr=lr, + l1=l1, l2=l2, lr_power=lr_power, use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "multiply_linear_by_lr", + _op._get_attr_bool("multiply_linear_by_lr")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyFtrl", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyFtrl = tf_export("raw_ops.ApplyFtrl")(_ops.to_raw_op(apply_ftrl)) + + +def apply_ftrl_eager_fallback(var: Annotated[Any, TV_ApplyFtrl_T], accum: Annotated[Any, TV_ApplyFtrl_T], linear: Annotated[Any, TV_ApplyFtrl_T], grad: Annotated[Any, TV_ApplyFtrl_T], lr: Annotated[Any, TV_ApplyFtrl_T], l1: Annotated[Any, TV_ApplyFtrl_T], l2: Annotated[Any, TV_ApplyFtrl_T], lr_power: Annotated[Any, TV_ApplyFtrl_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx) -> Annotated[Any, TV_ApplyFtrl_T]: + raise RuntimeError("apply_ftrl op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyFtrlV2_T = TypeVar("TV_ApplyFtrlV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_ftrl_v2(var: Annotated[Any, TV_ApplyFtrlV2_T], accum: Annotated[Any, TV_ApplyFtrlV2_T], linear: Annotated[Any, TV_ApplyFtrlV2_T], grad: Annotated[Any, TV_ApplyFtrlV2_T], lr: Annotated[Any, TV_ApplyFtrlV2_T], l1: Annotated[Any, TV_ApplyFtrlV2_T], l2: Annotated[Any, TV_ApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ApplyFtrlV2_T], lr_power: Annotated[Any, TV_ApplyFtrlV2_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None) -> Annotated[Any, TV_ApplyFtrlV2_T]: + r"""Update '*var' according to the Ftrl-proximal scheme. + + grad_with_shrinkage = grad + 2 * l2_shrinkage * var + accum_new = accum + grad * grad + linear += grad_with_shrinkage - + (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + linear: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 shrinkage regularization. Must be a scalar. + l2_shrinkage: A `Tensor`. Must have the same type as `var`. + lr_power: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_ftrl_v2 op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyFtrlV2", var=var, accum=accum, linear=linear, grad=grad, lr=lr, + l1=l1, l2=l2, l2_shrinkage=l2_shrinkage, + lr_power=lr_power, use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "multiply_linear_by_lr", + _op._get_attr_bool("multiply_linear_by_lr")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyFtrlV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyFtrlV2 = tf_export("raw_ops.ApplyFtrlV2")(_ops.to_raw_op(apply_ftrl_v2)) + + +def apply_ftrl_v2_eager_fallback(var: Annotated[Any, TV_ApplyFtrlV2_T], accum: Annotated[Any, TV_ApplyFtrlV2_T], linear: Annotated[Any, TV_ApplyFtrlV2_T], grad: Annotated[Any, TV_ApplyFtrlV2_T], lr: Annotated[Any, TV_ApplyFtrlV2_T], l1: Annotated[Any, TV_ApplyFtrlV2_T], l2: Annotated[Any, TV_ApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ApplyFtrlV2_T], lr_power: Annotated[Any, TV_ApplyFtrlV2_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx) -> Annotated[Any, TV_ApplyFtrlV2_T]: + raise RuntimeError("apply_ftrl_v2 op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyGradientDescent_T = TypeVar("TV_ApplyGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_gradient_descent(var: Annotated[Any, TV_ApplyGradientDescent_T], alpha: Annotated[Any, TV_ApplyGradientDescent_T], delta: Annotated[Any, TV_ApplyGradientDescent_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyGradientDescent_T]: + r"""Update '*var' by subtracting 'alpha' * 'delta' from it. + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + alpha: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + delta: A `Tensor`. Must have the same type as `var`. The change. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyGradientDescent", var=var, alpha=alpha, delta=delta, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyGradientDescent", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyGradientDescent = tf_export("raw_ops.ApplyGradientDescent")(_ops.to_raw_op(apply_gradient_descent)) + + +def apply_gradient_descent_eager_fallback(var: Annotated[Any, TV_ApplyGradientDescent_T], alpha: Annotated[Any, TV_ApplyGradientDescent_T], delta: Annotated[Any, TV_ApplyGradientDescent_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyGradientDescent_T]: + raise RuntimeError("apply_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyMomentum_T = TypeVar("TV_ApplyMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_momentum(var: Annotated[Any, TV_ApplyMomentum_T], accum: Annotated[Any, TV_ApplyMomentum_T], lr: Annotated[Any, TV_ApplyMomentum_T], grad: Annotated[Any, TV_ApplyMomentum_T], momentum: Annotated[Any, TV_ApplyMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None) -> Annotated[Any, TV_ApplyMomentum_T]: + r"""Update '*var' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + accum = accum * momentum + grad + var -= lr * accum + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + momentum: A `Tensor`. Must have the same type as `var`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var - lr * momentum * accum, so in the end, the var you get is actually + var - lr * momentum * accum. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_momentum op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyMomentum", var=var, accum=accum, lr=lr, grad=grad, + momentum=momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking"), "use_nesterov", + _op._get_attr_bool("use_nesterov")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyMomentum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyMomentum = tf_export("raw_ops.ApplyMomentum")(_ops.to_raw_op(apply_momentum)) + + +def apply_momentum_eager_fallback(var: Annotated[Any, TV_ApplyMomentum_T], accum: Annotated[Any, TV_ApplyMomentum_T], lr: Annotated[Any, TV_ApplyMomentum_T], grad: Annotated[Any, TV_ApplyMomentum_T], momentum: Annotated[Any, TV_ApplyMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx) -> Annotated[Any, TV_ApplyMomentum_T]: + raise RuntimeError("apply_momentum op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyPowerSign_T = TypeVar("TV_ApplyPowerSign_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_power_sign(var: Annotated[Any, TV_ApplyPowerSign_T], m: Annotated[Any, TV_ApplyPowerSign_T], lr: Annotated[Any, TV_ApplyPowerSign_T], logbase: Annotated[Any, TV_ApplyPowerSign_T], sign_decay: Annotated[Any, TV_ApplyPowerSign_T], beta: Annotated[Any, TV_ApplyPowerSign_T], grad: Annotated[Any, TV_ApplyPowerSign_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyPowerSign_T]: + r"""Update '*var' according to the AddSign update. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + update <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g + variable <- variable - lr_t * update + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + m: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + logbase: A `Tensor`. Must have the same type as `var`. Must be a scalar. + sign_decay: A `Tensor`. Must have the same type as `var`. + Must be a scalar. + beta: A `Tensor`. Must have the same type as `var`. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and m tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_power_sign op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyPowerSign", var=var, m=m, lr=lr, logbase=logbase, + sign_decay=sign_decay, beta=beta, grad=grad, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyPowerSign", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyPowerSign = tf_export("raw_ops.ApplyPowerSign")(_ops.to_raw_op(apply_power_sign)) + + +def apply_power_sign_eager_fallback(var: Annotated[Any, TV_ApplyPowerSign_T], m: Annotated[Any, TV_ApplyPowerSign_T], lr: Annotated[Any, TV_ApplyPowerSign_T], logbase: Annotated[Any, TV_ApplyPowerSign_T], sign_decay: Annotated[Any, TV_ApplyPowerSign_T], beta: Annotated[Any, TV_ApplyPowerSign_T], grad: Annotated[Any, TV_ApplyPowerSign_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyPowerSign_T]: + raise RuntimeError("apply_power_sign op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyProximalAdagrad_T = TypeVar("TV_ApplyProximalAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_proximal_adagrad(var: Annotated[Any, TV_ApplyProximalAdagrad_T], accum: Annotated[Any, TV_ApplyProximalAdagrad_T], lr: Annotated[Any, TV_ApplyProximalAdagrad_T], l1: Annotated[Any, TV_ApplyProximalAdagrad_T], l2: Annotated[Any, TV_ApplyProximalAdagrad_T], grad: Annotated[Any, TV_ApplyProximalAdagrad_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyProximalAdagrad_T]: + r"""Update '*var' and '*accum' according to FOBOS with Adagrad learning rate. + + accum += grad * grad + prox_v = var - lr * grad * (1 / sqrt(accum)) + var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_proximal_adagrad op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyProximalAdagrad", var=var, accum=accum, lr=lr, l1=l1, l2=l2, + grad=grad, use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyProximalAdagrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyProximalAdagrad = tf_export("raw_ops.ApplyProximalAdagrad")(_ops.to_raw_op(apply_proximal_adagrad)) + + +def apply_proximal_adagrad_eager_fallback(var: Annotated[Any, TV_ApplyProximalAdagrad_T], accum: Annotated[Any, TV_ApplyProximalAdagrad_T], lr: Annotated[Any, TV_ApplyProximalAdagrad_T], l1: Annotated[Any, TV_ApplyProximalAdagrad_T], l2: Annotated[Any, TV_ApplyProximalAdagrad_T], grad: Annotated[Any, TV_ApplyProximalAdagrad_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyProximalAdagrad_T]: + raise RuntimeError("apply_proximal_adagrad op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyProximalGradientDescent_T = TypeVar("TV_ApplyProximalGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_proximal_gradient_descent(var: Annotated[Any, TV_ApplyProximalGradientDescent_T], alpha: Annotated[Any, TV_ApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ApplyProximalGradientDescent_T], delta: Annotated[Any, TV_ApplyProximalGradientDescent_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyProximalGradientDescent_T]: + r"""Update '*var' as FOBOS algorithm with fixed learning rate. + + prox_v = var - alpha * delta + var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + alpha: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + delta: A `Tensor`. Must have the same type as `var`. The change. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_proximal_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyProximalGradientDescent", var=var, alpha=alpha, l1=l1, l2=l2, + delta=delta, use_locking=use_locking, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyProximalGradientDescent", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyProximalGradientDescent = tf_export("raw_ops.ApplyProximalGradientDescent")(_ops.to_raw_op(apply_proximal_gradient_descent)) + + +def apply_proximal_gradient_descent_eager_fallback(var: Annotated[Any, TV_ApplyProximalGradientDescent_T], alpha: Annotated[Any, TV_ApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ApplyProximalGradientDescent_T], delta: Annotated[Any, TV_ApplyProximalGradientDescent_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyProximalGradientDescent_T]: + raise RuntimeError("apply_proximal_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + +TV_ApplyRMSProp_T = TypeVar("TV_ApplyRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def apply_rms_prop(var: Annotated[Any, TV_ApplyRMSProp_T], ms: Annotated[Any, TV_ApplyRMSProp_T], mom: Annotated[Any, TV_ApplyRMSProp_T], lr: Annotated[Any, TV_ApplyRMSProp_T], rho: Annotated[Any, TV_ApplyRMSProp_T], momentum: Annotated[Any, TV_ApplyRMSProp_T], epsilon: Annotated[Any, TV_ApplyRMSProp_T], grad: Annotated[Any, TV_ApplyRMSProp_T], use_locking:bool=False, name=None) -> Annotated[Any, TV_ApplyRMSProp_T]: + r"""Update '*var' according to the RMSProp algorithm. + + Note that in dense implementation of this algorithm, ms and mom will + update even if the grad is zero, but in this sparse implementation, ms + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + Delta = learning_rate * gradient / sqrt(mean_square + epsilon) + + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) + var <- var - mom + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + ms: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + mom: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `var`. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, ms, and mom tensors is protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("apply_rms_prop op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ApplyRMSProp", var=var, ms=ms, mom=mom, lr=lr, rho=rho, + momentum=momentum, epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ApplyRMSProp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ApplyRMSProp = tf_export("raw_ops.ApplyRMSProp")(_ops.to_raw_op(apply_rms_prop)) + + +def apply_rms_prop_eager_fallback(var: Annotated[Any, TV_ApplyRMSProp_T], ms: Annotated[Any, TV_ApplyRMSProp_T], mom: Annotated[Any, TV_ApplyRMSProp_T], lr: Annotated[Any, TV_ApplyRMSProp_T], rho: Annotated[Any, TV_ApplyRMSProp_T], momentum: Annotated[Any, TV_ApplyRMSProp_T], epsilon: Annotated[Any, TV_ApplyRMSProp_T], grad: Annotated[Any, TV_ApplyRMSProp_T], use_locking: bool, name, ctx) -> Annotated[Any, TV_ApplyRMSProp_T]: + raise RuntimeError("apply_rms_prop op does not support eager execution. Arg 'out' is a ref.") + +TV_ResourceApplyAdaMax_T = TypeVar("TV_ResourceApplyAdaMax_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_ada_max(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdaMax_T], lr: Annotated[Any, TV_ResourceApplyAdaMax_T], beta1: Annotated[Any, TV_ResourceApplyAdaMax_T], beta2: Annotated[Any, TV_ResourceApplyAdaMax_T], epsilon: Annotated[Any, TV_ResourceApplyAdaMax_T], grad: Annotated[Any, TV_ResourceApplyAdaMax_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the AdaMax algorithm. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + v_t <- max(beta2 * v_{t-1}, abs(g)) + variable <- variable - learning_rate / (1 - beta1^t) * m_t / (v_t + epsilon) + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + m: A `Tensor` of type `resource`. Should be from a Variable(). + v: A `Tensor` of type `resource`. Should be from a Variable(). + beta1_power: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Must be a scalar. + lr: A `Tensor`. Must have the same type as `beta1_power`. + Scaling factor. Must be a scalar. + beta1: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + beta2: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `beta1_power`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `beta1_power`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, m, and v tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdaMax", name, var, m, v, beta1_power, lr, beta1, + beta2, epsilon, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_ada_max_eager_fallback( + var, m, v, beta1_power, lr, beta1, beta2, epsilon, grad, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdaMax", var=var, m=m, v=v, beta1_power=beta1_power, + lr=lr, beta1=beta1, beta2=beta2, + epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyAdaMax = tf_export("raw_ops.ResourceApplyAdaMax")(_ops.to_raw_op(resource_apply_ada_max)) + + +def resource_apply_ada_max_eager_fallback(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdaMax_T], lr: Annotated[Any, TV_ResourceApplyAdaMax_T], beta1: Annotated[Any, TV_ResourceApplyAdaMax_T], beta2: Annotated[Any, TV_ResourceApplyAdaMax_T], epsilon: Annotated[Any, TV_ResourceApplyAdaMax_T], grad: Annotated[Any, TV_ResourceApplyAdaMax_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([beta1_power, lr, beta1, beta2, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (beta1_power, lr, beta1, beta2, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + m = _ops.convert_to_tensor(m, _dtypes.resource) + v = _ops.convert_to_tensor(v, _dtypes.resource) + _inputs_flat = [var, m, v, beta1_power, lr, beta1, beta2, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyAdaMax", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyAdadelta_T = TypeVar("TV_ResourceApplyAdadelta_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adadelta(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], accum_update: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdadelta_T], rho: Annotated[Any, TV_ResourceApplyAdadelta_T], epsilon: Annotated[Any, TV_ResourceApplyAdadelta_T], grad: Annotated[Any, TV_ResourceApplyAdadelta_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the adadelta scheme. + + accum = rho() * accum + (1 - rho()) * grad.square(); + update = (update_accum + epsilon).sqrt() * (accum + epsilon()).rsqrt() * grad; + update_accum = rho() * update_accum + (1 - rho()) * update.square(); + var -= update; + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + accum_update: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `lr`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var, accum and update_accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdadelta", name, var, accum, accum_update, lr, + rho, epsilon, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adadelta_eager_fallback( + var, accum, accum_update, lr, rho, epsilon, grad, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdadelta", var=var, accum=accum, + accum_update=accum_update, lr=lr, rho=rho, + epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyAdadelta = tf_export("raw_ops.ResourceApplyAdadelta")(_ops.to_raw_op(resource_apply_adadelta)) + + +def resource_apply_adadelta_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], accum_update: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdadelta_T], rho: Annotated[Any, TV_ResourceApplyAdadelta_T], epsilon: Annotated[Any, TV_ResourceApplyAdadelta_T], grad: Annotated[Any, TV_ResourceApplyAdadelta_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + accum_update = _ops.convert_to_tensor(accum_update, _dtypes.resource) + _inputs_flat = [var, accum, accum_update, lr, rho, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyAdadelta", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyAdagrad_T = TypeVar("TV_ResourceApplyAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adagrad(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdagrad_T], grad: Annotated[Any, TV_ResourceApplyAdagrad_T], use_locking:bool=False, update_slots:bool=True, name=None): + r"""Update '*var' according to the adagrad scheme. + + accum += grad * grad + var -= lr * grad * (1 / sqrt(accum)) + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdagrad", name, var, accum, lr, grad, + "use_locking", use_locking, "update_slots", update_slots) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adagrad_eager_fallback( + var, accum, lr, grad, use_locking=use_locking, + update_slots=update_slots, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdagrad", var=var, accum=accum, lr=lr, grad=grad, + use_locking=use_locking, + update_slots=update_slots, name=name) + return _op +ResourceApplyAdagrad = tf_export("raw_ops.ResourceApplyAdagrad")(_ops.to_raw_op(resource_apply_adagrad)) + + +def resource_apply_adagrad_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdagrad_T], grad: Annotated[Any, TV_ResourceApplyAdagrad_T], use_locking: bool, update_slots: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking, "update_slots", + update_slots) + _result = _execute.execute(b"ResourceApplyAdagrad", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyAdagradDA_T = TypeVar("TV_ResourceApplyAdagradDA_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adagrad_da(var: Annotated[Any, _atypes.Resource], gradient_accumulator: Annotated[Any, _atypes.Resource], gradient_squared_accumulator: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyAdagradDA_T], lr: Annotated[Any, TV_ResourceApplyAdagradDA_T], l1: Annotated[Any, TV_ResourceApplyAdagradDA_T], l2: Annotated[Any, TV_ResourceApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking:bool=False, name=None): + r"""Update '*var' according to the proximal adagrad scheme. + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + gradient_accumulator: A `Tensor` of type `resource`. + Should be from a Variable(). + gradient_squared_accumulator: A `Tensor` of type `resource`. + Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + lr: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 regularization. Must be a scalar. + global_step: A `Tensor` of type `int64`. + Training step number. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdagradDA", name, var, gradient_accumulator, + gradient_squared_accumulator, grad, lr, l1, l2, global_step, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adagrad_da_eager_fallback( + var, gradient_accumulator, gradient_squared_accumulator, grad, lr, + l1, l2, global_step, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdagradDA", var=var, + gradient_accumulator=gradient_accumulator, + gradient_squared_accumulator=gradient_squared_accumulator, + grad=grad, lr=lr, l1=l1, l2=l2, + global_step=global_step, + use_locking=use_locking, name=name) + return _op +ResourceApplyAdagradDA = tf_export("raw_ops.ResourceApplyAdagradDA")(_ops.to_raw_op(resource_apply_adagrad_da)) + + +def resource_apply_adagrad_da_eager_fallback(var: Annotated[Any, _atypes.Resource], gradient_accumulator: Annotated[Any, _atypes.Resource], gradient_squared_accumulator: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyAdagradDA_T], lr: Annotated[Any, TV_ResourceApplyAdagradDA_T], l1: Annotated[Any, TV_ResourceApplyAdagradDA_T], l2: Annotated[Any, TV_ResourceApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + gradient_accumulator = _ops.convert_to_tensor(gradient_accumulator, _dtypes.resource) + gradient_squared_accumulator = _ops.convert_to_tensor(gradient_squared_accumulator, _dtypes.resource) + global_step = _ops.convert_to_tensor(global_step, _dtypes.int64) + _inputs_flat = [var, gradient_accumulator, gradient_squared_accumulator, grad, lr, l1, l2, global_step] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyAdagradDA", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyAdagradV2_T = TypeVar("TV_ResourceApplyAdagradV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adagrad_v2(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdagradV2_T], epsilon: Annotated[Any, TV_ResourceApplyAdagradV2_T], grad: Annotated[Any, TV_ResourceApplyAdagradV2_T], use_locking:bool=False, update_slots:bool=True, name=None): + r"""Update '*var' according to the adagrad scheme. + + accum += grad * grad + var -= lr * grad * (1 / (sqrt(accum) + epsilon)) + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `lr`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdagradV2", name, var, accum, lr, epsilon, grad, + "use_locking", use_locking, "update_slots", update_slots) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adagrad_v2_eager_fallback( + var, accum, lr, epsilon, grad, use_locking=use_locking, + update_slots=update_slots, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdagradV2", var=var, accum=accum, lr=lr, + epsilon=epsilon, grad=grad, + use_locking=use_locking, + update_slots=update_slots, name=name) + return _op +ResourceApplyAdagradV2 = tf_export("raw_ops.ResourceApplyAdagradV2")(_ops.to_raw_op(resource_apply_adagrad_v2)) + + +def resource_apply_adagrad_v2_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAdagradV2_T], epsilon: Annotated[Any, TV_ResourceApplyAdagradV2_T], grad: Annotated[Any, TV_ResourceApplyAdagradV2_T], use_locking: bool, update_slots: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking, "update_slots", + update_slots) + _result = _execute.execute(b"ResourceApplyAdagradV2", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyAdam_T = TypeVar("TV_ResourceApplyAdam_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adam(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdam_T], beta2_power: Annotated[Any, TV_ResourceApplyAdam_T], lr: Annotated[Any, TV_ResourceApplyAdam_T], beta1: Annotated[Any, TV_ResourceApplyAdam_T], beta2: Annotated[Any, TV_ResourceApplyAdam_T], epsilon: Annotated[Any, TV_ResourceApplyAdam_T], grad: Annotated[Any, TV_ResourceApplyAdam_T], use_locking:bool=False, use_nesterov:bool=False, name=None): + r"""Update '*var' according to the Adam algorithm. + + $$\text{lr}_t := \mathrm{lr} \cdot \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t}$$ + $$m_t := \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g$$ + $$v_t := \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g^2$$ + $$\text{var} := \begin{cases} \text{var} - (m_t \beta_1 + g \cdot (1 - \beta_1))\cdot\text{lr}_t/(\sqrt{v_t} + \epsilon), &\text{if use_nesterov}\\\\ \text{var} - m_t \cdot \text{lr}_t /(\sqrt{v_t} + \epsilon), &\text{otherwise} \end{cases}$$ + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + m: A `Tensor` of type `resource`. Should be from a Variable(). + v: A `Tensor` of type `resource`. Should be from a Variable(). + beta1_power: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Must be a scalar. + beta2_power: A `Tensor`. Must have the same type as `beta1_power`. + Must be a scalar. + lr: A `Tensor`. Must have the same type as `beta1_power`. + Scaling factor. Must be a scalar. + beta1: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + beta2: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `beta1_power`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `beta1_power`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, m, and v tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, uses the nesterov update. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdam", name, var, m, v, beta1_power, beta2_power, + lr, beta1, beta2, epsilon, grad, "use_locking", use_locking, + "use_nesterov", use_nesterov) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adam_eager_fallback( + var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, + grad, use_locking=use_locking, use_nesterov=use_nesterov, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdam", var=var, m=m, v=v, beta1_power=beta1_power, + beta2_power=beta2_power, lr=lr, beta1=beta1, + beta2=beta2, epsilon=epsilon, grad=grad, + use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + return _op +ResourceApplyAdam = tf_export("raw_ops.ResourceApplyAdam")(_ops.to_raw_op(resource_apply_adam)) + + +def resource_apply_adam_eager_fallback(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdam_T], beta2_power: Annotated[Any, TV_ResourceApplyAdam_T], lr: Annotated[Any, TV_ResourceApplyAdam_T], beta1: Annotated[Any, TV_ResourceApplyAdam_T], beta2: Annotated[Any, TV_ResourceApplyAdam_T], epsilon: Annotated[Any, TV_ResourceApplyAdam_T], grad: Annotated[Any, TV_ResourceApplyAdam_T], use_locking: bool, use_nesterov: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _attr_T, _inputs_T = _execute.args_to_matching_eager([beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + m = _ops.convert_to_tensor(m, _dtypes.resource) + v = _ops.convert_to_tensor(v, _dtypes.resource) + _inputs_flat = [var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking, "use_nesterov", + use_nesterov) + _result = _execute.execute(b"ResourceApplyAdam", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyAdamWithAmsgrad_T = TypeVar("TV_ResourceApplyAdamWithAmsgrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_adam_with_amsgrad(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], vhat: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta2_power: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], lr: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta1: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta2: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], epsilon: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], grad: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the Adam algorithm. + + $$\text{lr}_t := \mathrm{learning_rate} * \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ + $$m_t := \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ + $$v_t := \beta_2 * v_{t-1} + (1 - \beta_2) * g * g$$ + $$\hat{v}_t := max{\hat{v}_{t-1}, v_t}$$ + $$\text{variable} := \text{variable} - \text{lr}_t * m_t / (\sqrt{\hat{v}_t} + \epsilon)$$ + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + m: A `Tensor` of type `resource`. Should be from a Variable(). + v: A `Tensor` of type `resource`. Should be from a Variable(). + vhat: A `Tensor` of type `resource`. Should be from a Variable(). + beta1_power: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Must be a scalar. + beta2_power: A `Tensor`. Must have the same type as `beta1_power`. + Must be a scalar. + lr: A `Tensor`. Must have the same type as `beta1_power`. + Scaling factor. Must be a scalar. + beta1: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + beta2: A `Tensor`. Must have the same type as `beta1_power`. + Momentum factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `beta1_power`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `beta1_power`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, m, and v tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAdamWithAmsgrad", name, var, m, v, vhat, + beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_adam_with_amsgrad_eager_fallback( + var, m, v, vhat, beta1_power, beta2_power, lr, beta1, beta2, + epsilon, grad, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAdamWithAmsgrad", var=var, m=m, v=v, vhat=vhat, + beta1_power=beta1_power, + beta2_power=beta2_power, lr=lr, + beta1=beta1, beta2=beta2, + epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyAdamWithAmsgrad = tf_export("raw_ops.ResourceApplyAdamWithAmsgrad")(_ops.to_raw_op(resource_apply_adam_with_amsgrad)) + + +def resource_apply_adam_with_amsgrad_eager_fallback(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], v: Annotated[Any, _atypes.Resource], vhat: Annotated[Any, _atypes.Resource], beta1_power: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta2_power: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], lr: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta1: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], beta2: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], epsilon: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], grad: Annotated[Any, TV_ResourceApplyAdamWithAmsgrad_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + m = _ops.convert_to_tensor(m, _dtypes.resource) + v = _ops.convert_to_tensor(v, _dtypes.resource) + vhat = _ops.convert_to_tensor(vhat, _dtypes.resource) + _inputs_flat = [var, m, v, vhat, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyAdamWithAmsgrad", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyAddSign_T = TypeVar("TV_ResourceApplyAddSign_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_add_sign(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAddSign_T], alpha: Annotated[Any, TV_ResourceApplyAddSign_T], sign_decay: Annotated[Any, TV_ResourceApplyAddSign_T], beta: Annotated[Any, TV_ResourceApplyAddSign_T], grad: Annotated[Any, TV_ResourceApplyAddSign_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the AddSign update. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + update <- (alpha + sign_decay * sign(g) *sign(m)) * g + variable <- variable - lr_t * update + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + m: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + alpha: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + sign_decay: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + beta: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and m tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyAddSign", name, var, m, lr, alpha, sign_decay, + beta, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_add_sign_eager_fallback( + var, m, lr, alpha, sign_decay, beta, grad, use_locking=use_locking, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyAddSign", var=var, m=m, lr=lr, alpha=alpha, + sign_decay=sign_decay, beta=beta, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyAddSign = tf_export("raw_ops.ResourceApplyAddSign")(_ops.to_raw_op(resource_apply_add_sign)) + + +def resource_apply_add_sign_eager_fallback(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyAddSign_T], alpha: Annotated[Any, TV_ResourceApplyAddSign_T], sign_decay: Annotated[Any, TV_ResourceApplyAddSign_T], beta: Annotated[Any, TV_ResourceApplyAddSign_T], grad: Annotated[Any, TV_ResourceApplyAddSign_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, alpha, sign_decay, beta, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, alpha, sign_decay, beta, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + m = _ops.convert_to_tensor(m, _dtypes.resource) + _inputs_flat = [var, m, lr, alpha, sign_decay, beta, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyAddSign", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyCenteredRMSProp_T = TypeVar("TV_ResourceApplyCenteredRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_centered_rms_prop(var: Annotated[Any, _atypes.Resource], mg: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the centered RMSProp algorithm. + + The centered RMSProp algorithm uses an estimate of the centered second moment + (i.e., the variance) for normalization, as opposed to regular RMSProp, which + uses the (uncentered) second moment. This often helps with training, but is + slightly more expensive in terms of computation and memory. + + Note that in dense implementation of this algorithm, mg, ms, and mom will + update even if the grad is zero, but in this sparse implementation, mg, ms, + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + mean_grad = decay * mean_grad + (1-decay) * gradient + + Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) + + mg <- rho * mg_{t-1} + (1-rho) * grad + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms - mg * mg + epsilon) + var <- var - mom + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + mg: A `Tensor` of type `resource`. Should be from a Variable(). + ms: A `Tensor` of type `resource`. Should be from a Variable(). + mom: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `lr`. + Momentum Scale. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `lr`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, mg, ms, and mom tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyCenteredRMSProp", name, var, mg, ms, mom, lr, rho, + momentum, epsilon, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_centered_rms_prop_eager_fallback( + var, mg, ms, mom, lr, rho, momentum, epsilon, grad, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyCenteredRMSProp", var=var, mg=mg, ms=ms, mom=mom, lr=lr, + rho=rho, momentum=momentum, + epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyCenteredRMSProp = tf_export("raw_ops.ResourceApplyCenteredRMSProp")(_ops.to_raw_op(resource_apply_centered_rms_prop)) + + +def resource_apply_centered_rms_prop_eager_fallback(var: Annotated[Any, _atypes.Resource], mg: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ResourceApplyCenteredRMSProp_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, momentum, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, momentum, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + mg = _ops.convert_to_tensor(mg, _dtypes.resource) + ms = _ops.convert_to_tensor(ms, _dtypes.resource) + mom = _ops.convert_to_tensor(mom, _dtypes.resource) + _inputs_flat = [var, mg, ms, mom, lr, rho, momentum, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyCenteredRMSProp", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyFtrl_T = TypeVar("TV_ResourceApplyFtrl_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_ftrl(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyFtrl_T], lr: Annotated[Any, TV_ResourceApplyFtrl_T], l1: Annotated[Any, TV_ResourceApplyFtrl_T], l2: Annotated[Any, TV_ResourceApplyFtrl_T], lr_power: Annotated[Any, TV_ResourceApplyFtrl_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None): + r"""Update '*var' according to the Ftrl-proximal scheme. + + accum_new = accum + grad * grad + linear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + linear: A `Tensor` of type `resource`. Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + lr: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 regularization. Must be a scalar. + lr_power: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyFtrl", name, var, accum, linear, grad, lr, l1, l2, + lr_power, "use_locking", use_locking, "multiply_linear_by_lr", + multiply_linear_by_lr) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_ftrl_eager_fallback( + var, accum, linear, grad, lr, l1, l2, lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyFtrl", var=var, accum=accum, linear=linear, grad=grad, + lr=lr, l1=l1, l2=l2, lr_power=lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + return _op +ResourceApplyFtrl = tf_export("raw_ops.ResourceApplyFtrl")(_ops.to_raw_op(resource_apply_ftrl)) + + +def resource_apply_ftrl_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyFtrl_T], lr: Annotated[Any, TV_ResourceApplyFtrl_T], l1: Annotated[Any, TV_ResourceApplyFtrl_T], l2: Annotated[Any, TV_ResourceApplyFtrl_T], lr_power: Annotated[Any, TV_ResourceApplyFtrl_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2, lr_power], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2, lr_power) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + linear = _ops.convert_to_tensor(linear, _dtypes.resource) + _inputs_flat = [var, accum, linear, grad, lr, l1, l2, lr_power] + _attrs = ("T", _attr_T, "use_locking", use_locking, "multiply_linear_by_lr", + multiply_linear_by_lr) + _result = _execute.execute(b"ResourceApplyFtrl", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyFtrlV2_T = TypeVar("TV_ResourceApplyFtrlV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_ftrl_v2(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyFtrlV2_T], lr: Annotated[Any, TV_ResourceApplyFtrlV2_T], l1: Annotated[Any, TV_ResourceApplyFtrlV2_T], l2: Annotated[Any, TV_ResourceApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ResourceApplyFtrlV2_T], lr_power: Annotated[Any, TV_ResourceApplyFtrlV2_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None): + r"""Update '*var' according to the Ftrl-proximal scheme. + + accum_new = accum + grad * grad + grad_with_shrinkage = grad + 2 * l2_shrinkage * var + linear += grad_with_shrinkage + + (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + linear: A `Tensor` of type `resource`. Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + lr: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 shrinkage regularization. Must be a scalar. + l2_shrinkage: A `Tensor`. Must have the same type as `grad`. + lr_power: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyFtrlV2", name, var, accum, linear, grad, lr, l1, + l2, l2_shrinkage, lr_power, "use_locking", use_locking, + "multiply_linear_by_lr", multiply_linear_by_lr) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_ftrl_v2_eager_fallback( + var, accum, linear, grad, lr, l1, l2, l2_shrinkage, lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyFtrlV2", var=var, accum=accum, linear=linear, grad=grad, + lr=lr, l1=l1, l2=l2, l2_shrinkage=l2_shrinkage, + lr_power=lr_power, use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + return _op +ResourceApplyFtrlV2 = tf_export("raw_ops.ResourceApplyFtrlV2")(_ops.to_raw_op(resource_apply_ftrl_v2)) + + +def resource_apply_ftrl_v2_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceApplyFtrlV2_T], lr: Annotated[Any, TV_ResourceApplyFtrlV2_T], l1: Annotated[Any, TV_ResourceApplyFtrlV2_T], l2: Annotated[Any, TV_ResourceApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ResourceApplyFtrlV2_T], lr_power: Annotated[Any, TV_ResourceApplyFtrlV2_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2, l2_shrinkage, lr_power], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2, l2_shrinkage, lr_power) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + linear = _ops.convert_to_tensor(linear, _dtypes.resource) + _inputs_flat = [var, accum, linear, grad, lr, l1, l2, l2_shrinkage, lr_power] + _attrs = ("T", _attr_T, "use_locking", use_locking, "multiply_linear_by_lr", + multiply_linear_by_lr) + _result = _execute.execute(b"ResourceApplyFtrlV2", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyGradientDescent_T = TypeVar("TV_ResourceApplyGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_gradient_descent(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceApplyGradientDescent_T], delta: Annotated[Any, TV_ResourceApplyGradientDescent_T], use_locking:bool=False, name=None): + r"""Update '*var' by subtracting 'alpha' * 'delta' from it. + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + delta: A `Tensor`. Must have the same type as `alpha`. The change. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyGradientDescent", name, var, alpha, delta, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_gradient_descent_eager_fallback( + var, alpha, delta, use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyGradientDescent", var=var, alpha=alpha, delta=delta, + use_locking=use_locking, name=name) + return _op +ResourceApplyGradientDescent = tf_export("raw_ops.ResourceApplyGradientDescent")(_ops.to_raw_op(resource_apply_gradient_descent)) + + +def resource_apply_gradient_descent_eager_fallback(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceApplyGradientDescent_T], delta: Annotated[Any, TV_ResourceApplyGradientDescent_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([alpha, delta], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (alpha, delta) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + _inputs_flat = [var, alpha, delta] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyGradientDescent", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyKerasMomentum_T = TypeVar("TV_ResourceApplyKerasMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_keras_momentum(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyKerasMomentum_T], grad: Annotated[Any, TV_ResourceApplyKerasMomentum_T], momentum: Annotated[Any, TV_ResourceApplyKerasMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None): + r"""Update '*var' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + accum = accum * momentum - lr * grad + var += accum + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + momentum: A `Tensor`. Must have the same type as `lr`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var + momentum * accum, so in the end, the var you get is actually + var + momentum * accum. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyKerasMomentum", name, var, accum, lr, grad, + momentum, "use_locking", use_locking, "use_nesterov", use_nesterov) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_keras_momentum_eager_fallback( + var, accum, lr, grad, momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyKerasMomentum", var=var, accum=accum, lr=lr, grad=grad, + momentum=momentum, + use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + return _op +ResourceApplyKerasMomentum = tf_export("raw_ops.ResourceApplyKerasMomentum")(_ops.to_raw_op(resource_apply_keras_momentum)) + + +def resource_apply_keras_momentum_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyKerasMomentum_T], grad: Annotated[Any, TV_ResourceApplyKerasMomentum_T], momentum: Annotated[Any, TV_ResourceApplyKerasMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad, momentum], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad, momentum) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad, momentum] + _attrs = ("T", _attr_T, "use_locking", use_locking, "use_nesterov", + use_nesterov) + _result = _execute.execute(b"ResourceApplyKerasMomentum", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyMomentum_T = TypeVar("TV_ResourceApplyMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_momentum(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyMomentum_T], grad: Annotated[Any, TV_ResourceApplyMomentum_T], momentum: Annotated[Any, TV_ResourceApplyMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None): + r"""Update '*var' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + accum = accum * momentum + grad + var -= lr * accum + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + momentum: A `Tensor`. Must have the same type as `lr`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var - lr * momentum * accum, so in the end, the var you get is actually + var - lr * momentum * accum. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyMomentum", name, var, accum, lr, grad, momentum, + "use_locking", use_locking, "use_nesterov", use_nesterov) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_momentum_eager_fallback( + var, accum, lr, grad, momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyMomentum", var=var, accum=accum, lr=lr, grad=grad, + momentum=momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + return _op +ResourceApplyMomentum = tf_export("raw_ops.ResourceApplyMomentum")(_ops.to_raw_op(resource_apply_momentum)) + + +def resource_apply_momentum_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyMomentum_T], grad: Annotated[Any, TV_ResourceApplyMomentum_T], momentum: Annotated[Any, TV_ResourceApplyMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad, momentum], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad, momentum) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad, momentum] + _attrs = ("T", _attr_T, "use_locking", use_locking, "use_nesterov", + use_nesterov) + _result = _execute.execute(b"ResourceApplyMomentum", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceApplyPowerSign_T = TypeVar("TV_ResourceApplyPowerSign_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_power_sign(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyPowerSign_T], logbase: Annotated[Any, TV_ResourceApplyPowerSign_T], sign_decay: Annotated[Any, TV_ResourceApplyPowerSign_T], beta: Annotated[Any, TV_ResourceApplyPowerSign_T], grad: Annotated[Any, TV_ResourceApplyPowerSign_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the AddSign update. + + m_t <- beta1 * m_{t-1} + (1 - beta1) * g + update <- exp(logbase * sign_decay * sign(g) * sign(m_t)) * g + variable <- variable - lr_t * update + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + m: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + logbase: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + sign_decay: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + beta: A `Tensor`. Must have the same type as `lr`. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and m tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyPowerSign", name, var, m, lr, logbase, sign_decay, + beta, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_power_sign_eager_fallback( + var, m, lr, logbase, sign_decay, beta, grad, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyPowerSign", var=var, m=m, lr=lr, logbase=logbase, + sign_decay=sign_decay, beta=beta, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyPowerSign = tf_export("raw_ops.ResourceApplyPowerSign")(_ops.to_raw_op(resource_apply_power_sign)) + + +def resource_apply_power_sign_eager_fallback(var: Annotated[Any, _atypes.Resource], m: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyPowerSign_T], logbase: Annotated[Any, TV_ResourceApplyPowerSign_T], sign_decay: Annotated[Any, TV_ResourceApplyPowerSign_T], beta: Annotated[Any, TV_ResourceApplyPowerSign_T], grad: Annotated[Any, TV_ResourceApplyPowerSign_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, logbase, sign_decay, beta, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, logbase, sign_decay, beta, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + m = _ops.convert_to_tensor(m, _dtypes.resource) + _inputs_flat = [var, m, lr, logbase, sign_decay, beta, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyPowerSign", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyProximalAdagrad_T = TypeVar("TV_ResourceApplyProximalAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_proximal_adagrad(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], l1: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], l2: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], grad: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], use_locking:bool=False, name=None): + r"""Update '*var' and '*accum' according to FOBOS with Adagrad learning rate. + + accum += grad * grad + prox_v = var - lr * grad * (1 / sqrt(accum)) + var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `lr`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `lr`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyProximalAdagrad", name, var, accum, lr, l1, l2, + grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_proximal_adagrad_eager_fallback( + var, accum, lr, l1, l2, grad, use_locking=use_locking, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyProximalAdagrad", var=var, accum=accum, lr=lr, l1=l1, + l2=l2, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyProximalAdagrad = tf_export("raw_ops.ResourceApplyProximalAdagrad")(_ops.to_raw_op(resource_apply_proximal_adagrad)) + + +def resource_apply_proximal_adagrad_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], l1: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], l2: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], grad: Annotated[Any, TV_ResourceApplyProximalAdagrad_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, l1, l2, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, l1, l2, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, l1, l2, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyProximalAdagrad", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyProximalGradientDescent_T = TypeVar("TV_ResourceApplyProximalGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_proximal_gradient_descent(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], delta: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], use_locking:bool=False, name=None): + r"""Update '*var' as FOBOS algorithm with fixed learning rate. + + prox_v = var - alpha * delta + var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `alpha`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `alpha`. + L2 regularization. Must be a scalar. + delta: A `Tensor`. Must have the same type as `alpha`. The change. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyProximalGradientDescent", name, var, alpha, l1, + l2, delta, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_proximal_gradient_descent_eager_fallback( + var, alpha, l1, l2, delta, use_locking=use_locking, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyProximalGradientDescent", var=var, alpha=alpha, l1=l1, + l2=l2, delta=delta, + use_locking=use_locking, + name=name) + return _op +ResourceApplyProximalGradientDescent = tf_export("raw_ops.ResourceApplyProximalGradientDescent")(_ops.to_raw_op(resource_apply_proximal_gradient_descent)) + + +def resource_apply_proximal_gradient_descent_eager_fallback(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], delta: Annotated[Any, TV_ResourceApplyProximalGradientDescent_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([alpha, l1, l2, delta], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (alpha, l1, l2, delta) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + _inputs_flat = [var, alpha, l1, l2, delta] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyProximalGradientDescent", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceApplyRMSProp_T = TypeVar("TV_ResourceApplyRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) + +def resource_apply_rms_prop(var: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyRMSProp_T], rho: Annotated[Any, TV_ResourceApplyRMSProp_T], momentum: Annotated[Any, TV_ResourceApplyRMSProp_T], epsilon: Annotated[Any, TV_ResourceApplyRMSProp_T], grad: Annotated[Any, TV_ResourceApplyRMSProp_T], use_locking:bool=False, name=None): + r"""Update '*var' according to the RMSProp algorithm. + + Note that in dense implementation of this algorithm, ms and mom will + update even if the grad is zero, but in this sparse implementation, ms + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + Delta = learning_rate * gradient / sqrt(mean_square + epsilon) + + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) + var <- var - mom + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + ms: A `Tensor` of type `resource`. Should be from a Variable(). + mom: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `lr`. + epsilon: A `Tensor`. Must have the same type as `lr`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, ms, and mom tensors is protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceApplyRMSProp", name, var, ms, mom, lr, rho, momentum, + epsilon, grad, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_apply_rms_prop_eager_fallback( + var, ms, mom, lr, rho, momentum, epsilon, grad, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceApplyRMSProp", var=var, ms=ms, mom=mom, lr=lr, rho=rho, + momentum=momentum, epsilon=epsilon, grad=grad, + use_locking=use_locking, name=name) + return _op +ResourceApplyRMSProp = tf_export("raw_ops.ResourceApplyRMSProp")(_ops.to_raw_op(resource_apply_rms_prop)) + + +def resource_apply_rms_prop_eager_fallback(var: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceApplyRMSProp_T], rho: Annotated[Any, TV_ResourceApplyRMSProp_T], momentum: Annotated[Any, TV_ResourceApplyRMSProp_T], epsilon: Annotated[Any, TV_ResourceApplyRMSProp_T], grad: Annotated[Any, TV_ResourceApplyRMSProp_T], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, momentum, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, momentum, epsilon, grad) = _inputs_T + var = _ops.convert_to_tensor(var, _dtypes.resource) + ms = _ops.convert_to_tensor(ms, _dtypes.resource) + mom = _ops.convert_to_tensor(mom, _dtypes.resource) + _inputs_flat = [var, ms, mom, lr, rho, momentum, epsilon, grad] + _attrs = ("T", _attr_T, "use_locking", use_locking) + _result = _execute.execute(b"ResourceApplyRMSProp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_ResourceSparseApplyAdadelta_T = TypeVar("TV_ResourceSparseApplyAdadelta_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyAdadelta_Tindices = TypeVar("TV_ResourceSparseApplyAdadelta_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_adadelta(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], accum_update: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], rho: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], epsilon: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], grad: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], indices: Annotated[Any, TV_ResourceSparseApplyAdadelta_Tindices], use_locking:bool=False, name=None): + r"""var: Should be from a Variable(). + + Args: + var: A `Tensor` of type `resource`. + accum: A `Tensor` of type `resource`. Should be from a Variable(). + accum_update: A `Tensor` of type `resource`. + : Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `lr`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyAdadelta", name, var, accum, accum_update, + lr, rho, epsilon, grad, indices, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_adadelta_eager_fallback( + var, accum, accum_update, lr, rho, epsilon, grad, indices, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyAdadelta", var=var, accum=accum, + accum_update=accum_update, lr=lr, + rho=rho, epsilon=epsilon, grad=grad, + indices=indices, + use_locking=use_locking, name=name) + return _op +ResourceSparseApplyAdadelta = tf_export("raw_ops.ResourceSparseApplyAdadelta")(_ops.to_raw_op(resource_sparse_apply_adadelta)) + + +def resource_sparse_apply_adadelta_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], accum_update: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], rho: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], epsilon: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], grad: Annotated[Any, TV_ResourceSparseApplyAdadelta_T], indices: Annotated[Any, TV_ResourceSparseApplyAdadelta_Tindices], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, epsilon, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + accum_update = _ops.convert_to_tensor(accum_update, _dtypes.resource) + _inputs_flat = [var, accum, accum_update, lr, rho, epsilon, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyAdadelta", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyAdagrad_T = TypeVar("TV_ResourceSparseApplyAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyAdagrad_Tindices = TypeVar("TV_ResourceSparseApplyAdagrad_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_adagrad(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdagrad_T], grad: Annotated[Any, TV_ResourceSparseApplyAdagrad_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagrad_Tindices], use_locking:bool=False, update_slots:bool=True, name=None): + r"""Update relevant entries in '*var' and '*accum' according to the adagrad scheme. + + That is for rows we have grad for, we update var and accum as follows: + accum += grad * grad + var -= lr * grad * (1 / sqrt(accum)) + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyAdagrad", name, var, accum, lr, grad, + indices, "use_locking", use_locking, "update_slots", update_slots) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_adagrad_eager_fallback( + var, accum, lr, grad, indices, use_locking=use_locking, + update_slots=update_slots, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyAdagrad", var=var, accum=accum, lr=lr, grad=grad, + indices=indices, + use_locking=use_locking, + update_slots=update_slots, name=name) + return _op +ResourceSparseApplyAdagrad = tf_export("raw_ops.ResourceSparseApplyAdagrad")(_ops.to_raw_op(resource_sparse_apply_adagrad)) + + +def resource_sparse_apply_adagrad_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdagrad_T], grad: Annotated[Any, TV_ResourceSparseApplyAdagrad_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagrad_Tindices], use_locking: bool, update_slots: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "update_slots", update_slots) + _result = _execute.execute(b"ResourceSparseApplyAdagrad", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyAdagradDA_T = TypeVar("TV_ResourceSparseApplyAdagradDA_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyAdagradDA_Tindices = TypeVar("TV_ResourceSparseApplyAdagradDA_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_adagrad_da(var: Annotated[Any, _atypes.Resource], gradient_accumulator: Annotated[Any, _atypes.Resource], gradient_squared_accumulator: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagradDA_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], l1: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], l2: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking:bool=False, name=None): + r"""Update entries in '*var' and '*accum' according to the proximal adagrad scheme. + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + gradient_accumulator: A `Tensor` of type `resource`. + Should be from a Variable(). + gradient_squared_accumulator: A `Tensor` of type `resource`. + Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `grad`. + Learning rate. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 regularization. Must be a scalar. + global_step: A `Tensor` of type `int64`. + Training step number. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyAdagradDA", name, var, gradient_accumulator, + gradient_squared_accumulator, grad, indices, lr, l1, l2, global_step, + "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_adagrad_da_eager_fallback( + var, gradient_accumulator, gradient_squared_accumulator, grad, + indices, lr, l1, l2, global_step, use_locking=use_locking, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyAdagradDA", var=var, + gradient_accumulator=gradient_accumulator, + gradient_squared_accumulator=gradient_squared_accumulator, + grad=grad, indices=indices, lr=lr, + l1=l1, l2=l2, global_step=global_step, + use_locking=use_locking, name=name) + return _op +ResourceSparseApplyAdagradDA = tf_export("raw_ops.ResourceSparseApplyAdagradDA")(_ops.to_raw_op(resource_sparse_apply_adagrad_da)) + + +def resource_sparse_apply_adagrad_da_eager_fallback(var: Annotated[Any, _atypes.Resource], gradient_accumulator: Annotated[Any, _atypes.Resource], gradient_squared_accumulator: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagradDA_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], l1: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], l2: Annotated[Any, TV_ResourceSparseApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + gradient_accumulator = _ops.convert_to_tensor(gradient_accumulator, _dtypes.resource) + gradient_squared_accumulator = _ops.convert_to_tensor(gradient_squared_accumulator, _dtypes.resource) + global_step = _ops.convert_to_tensor(global_step, _dtypes.int64) + _inputs_flat = [var, gradient_accumulator, gradient_squared_accumulator, grad, indices, lr, l1, l2, global_step] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyAdagradDA", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyAdagradV2_T = TypeVar("TV_ResourceSparseApplyAdagradV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyAdagradV2_Tindices = TypeVar("TV_ResourceSparseApplyAdagradV2_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_adagrad_v2(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], epsilon: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], grad: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagradV2_Tindices], use_locking:bool=False, update_slots:bool=True, name=None): + r"""Update relevant entries in '*var' and '*accum' according to the adagrad scheme. + + That is for rows we have grad for, we update var and accum as follows: + accum += grad * grad + var -= lr * grad * (1 / sqrt(accum)) + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `lr`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyAdagradV2", name, var, accum, lr, epsilon, + grad, indices, "use_locking", use_locking, "update_slots", + update_slots) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_adagrad_v2_eager_fallback( + var, accum, lr, epsilon, grad, indices, use_locking=use_locking, + update_slots=update_slots, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyAdagradV2", var=var, accum=accum, lr=lr, + epsilon=epsilon, grad=grad, + indices=indices, + use_locking=use_locking, + update_slots=update_slots, name=name) + return _op +ResourceSparseApplyAdagradV2 = tf_export("raw_ops.ResourceSparseApplyAdagradV2")(_ops.to_raw_op(resource_sparse_apply_adagrad_v2)) + + +def resource_sparse_apply_adagrad_v2_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], epsilon: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], grad: Annotated[Any, TV_ResourceSparseApplyAdagradV2_T], indices: Annotated[Any, TV_ResourceSparseApplyAdagradV2_Tindices], use_locking: bool, update_slots: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, epsilon, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, epsilon, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "update_slots", update_slots) + _result = _execute.execute(b"ResourceSparseApplyAdagradV2", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyCenteredRMSProp_T = TypeVar("TV_ResourceSparseApplyCenteredRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyCenteredRMSProp_Tindices = TypeVar("TV_ResourceSparseApplyCenteredRMSProp_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_centered_rms_prop(var: Annotated[Any, _atypes.Resource], mg: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], indices: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_Tindices], use_locking:bool=False, name=None): + r"""Update '*var' according to the centered RMSProp algorithm. + + The centered RMSProp algorithm uses an estimate of the centered second moment + (i.e., the variance) for normalization, as opposed to regular RMSProp, which + uses the (uncentered) second moment. This often helps with training, but is + slightly more expensive in terms of computation and memory. + + Note that in dense implementation of this algorithm, mg, ms, and mom will + update even if the grad is zero, but in this sparse implementation, mg, ms, + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + mean_grad = decay * mean_grad + (1-decay) * gradient + Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) + + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) + var <- var - mom + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + mg: A `Tensor` of type `resource`. Should be from a Variable(). + ms: A `Tensor` of type `resource`. Should be from a Variable(). + mom: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `lr`. + epsilon: A `Tensor`. Must have the same type as `lr`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var, ms and mom. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, mg, ms, and mom tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyCenteredRMSProp", name, var, mg, ms, mom, + lr, rho, momentum, epsilon, grad, indices, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_centered_rms_prop_eager_fallback( + var, mg, ms, mom, lr, rho, momentum, epsilon, grad, indices, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyCenteredRMSProp", var=var, mg=mg, ms=ms, mom=mom, + lr=lr, rho=rho, + momentum=momentum, + epsilon=epsilon, grad=grad, + indices=indices, + use_locking=use_locking, + name=name) + return _op +ResourceSparseApplyCenteredRMSProp = tf_export("raw_ops.ResourceSparseApplyCenteredRMSProp")(_ops.to_raw_op(resource_sparse_apply_centered_rms_prop)) + + +def resource_sparse_apply_centered_rms_prop_eager_fallback(var: Annotated[Any, _atypes.Resource], mg: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], rho: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], grad: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_T], indices: Annotated[Any, TV_ResourceSparseApplyCenteredRMSProp_Tindices], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, momentum, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, momentum, epsilon, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + mg = _ops.convert_to_tensor(mg, _dtypes.resource) + ms = _ops.convert_to_tensor(ms, _dtypes.resource) + mom = _ops.convert_to_tensor(mom, _dtypes.resource) + _inputs_flat = [var, mg, ms, mom, lr, rho, momentum, epsilon, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyCenteredRMSProp", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyFtrl_T = TypeVar("TV_ResourceSparseApplyFtrl_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyFtrl_Tindices = TypeVar("TV_ResourceSparseApplyFtrl_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_ftrl(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyFtrl_T], indices: Annotated[Any, TV_ResourceSparseApplyFtrl_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyFtrl_T], l1: Annotated[Any, TV_ResourceSparseApplyFtrl_T], l2: Annotated[Any, TV_ResourceSparseApplyFtrl_T], lr_power: Annotated[Any, TV_ResourceSparseApplyFtrl_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None): + r"""Update relevant entries in '*var' according to the Ftrl-proximal scheme. + + That is for rows we have grad for, we update var, accum and linear as follows: + accum_new = accum + grad * grad + linear += grad - (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + linear: A `Tensor` of type `resource`. Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 regularization. Must be a scalar. + lr_power: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyFtrl", name, var, accum, linear, grad, + indices, lr, l1, l2, lr_power, "use_locking", use_locking, + "multiply_linear_by_lr", multiply_linear_by_lr) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_ftrl_eager_fallback( + var, accum, linear, grad, indices, lr, l1, l2, lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyFtrl", var=var, accum=accum, linear=linear, + grad=grad, indices=indices, lr=lr, l1=l1, + l2=l2, lr_power=lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + return _op +ResourceSparseApplyFtrl = tf_export("raw_ops.ResourceSparseApplyFtrl")(_ops.to_raw_op(resource_sparse_apply_ftrl)) + + +def resource_sparse_apply_ftrl_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyFtrl_T], indices: Annotated[Any, TV_ResourceSparseApplyFtrl_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyFtrl_T], l1: Annotated[Any, TV_ResourceSparseApplyFtrl_T], l2: Annotated[Any, TV_ResourceSparseApplyFtrl_T], lr_power: Annotated[Any, TV_ResourceSparseApplyFtrl_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2, lr_power], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2, lr_power) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + linear = _ops.convert_to_tensor(linear, _dtypes.resource) + _inputs_flat = [var, accum, linear, grad, indices, lr, l1, l2, lr_power] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "multiply_linear_by_lr", multiply_linear_by_lr) + _result = _execute.execute(b"ResourceSparseApplyFtrl", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyFtrlV2_T = TypeVar("TV_ResourceSparseApplyFtrlV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyFtrlV2_Tindices = TypeVar("TV_ResourceSparseApplyFtrlV2_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_ftrl_v2(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], indices: Annotated[Any, TV_ResourceSparseApplyFtrlV2_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l1: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l2: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], lr_power: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None): + r"""Update relevant entries in '*var' according to the Ftrl-proximal scheme. + + That is for rows we have grad for, we update var, accum and linear as follows: + grad_with_shrinkage = grad + 2 * l2_shrinkage * var + accum_new = accum + grad_with_shrinkage * grad_with_shrinkage + linear += grad_with_shrinkage + + (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + linear: A `Tensor` of type `resource`. Should be from a Variable(). + grad: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `grad`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `grad`. + L2 shrinkage regularization. Must be a scalar. + l2_shrinkage: A `Tensor`. Must have the same type as `grad`. + lr_power: A `Tensor`. Must have the same type as `grad`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyFtrlV2", name, var, accum, linear, grad, + indices, lr, l1, l2, l2_shrinkage, lr_power, "use_locking", + use_locking, "multiply_linear_by_lr", multiply_linear_by_lr) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_ftrl_v2_eager_fallback( + var, accum, linear, grad, indices, lr, l1, l2, l2_shrinkage, + lr_power, use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyFtrlV2", var=var, accum=accum, linear=linear, + grad=grad, indices=indices, lr=lr, l1=l1, + l2=l2, l2_shrinkage=l2_shrinkage, + lr_power=lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + return _op +ResourceSparseApplyFtrlV2 = tf_export("raw_ops.ResourceSparseApplyFtrlV2")(_ops.to_raw_op(resource_sparse_apply_ftrl_v2)) + + +def resource_sparse_apply_ftrl_v2_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], linear: Annotated[Any, _atypes.Resource], grad: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], indices: Annotated[Any, TV_ResourceSparseApplyFtrlV2_Tindices], lr: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l1: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l2: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], lr_power: Annotated[Any, TV_ResourceSparseApplyFtrlV2_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _attr_T, _inputs_T = _execute.args_to_matching_eager([grad, lr, l1, l2, l2_shrinkage, lr_power], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (grad, lr, l1, l2, l2_shrinkage, lr_power) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + linear = _ops.convert_to_tensor(linear, _dtypes.resource) + _inputs_flat = [var, accum, linear, grad, indices, lr, l1, l2, l2_shrinkage, lr_power] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "multiply_linear_by_lr", multiply_linear_by_lr) + _result = _execute.execute(b"ResourceSparseApplyFtrlV2", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyKerasMomentum_T = TypeVar("TV_ResourceSparseApplyKerasMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyKerasMomentum_Tindices = TypeVar("TV_ResourceSparseApplyKerasMomentum_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_keras_momentum(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], grad: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], indices: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_Tindices], momentum: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None): + r"""Update relevant entries in '*var' and '*accum' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + That is for rows we have grad for, we update var and accum as follows: + + accum = accum * momentum - lr * grad + var += accum + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + momentum: A `Tensor`. Must have the same type as `lr`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var + momentum * accum, so in the end, the var you get is actually + var + momentum * accum. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyKerasMomentum", name, var, accum, lr, grad, + indices, momentum, "use_locking", use_locking, "use_nesterov", + use_nesterov) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_keras_momentum_eager_fallback( + var, accum, lr, grad, indices, momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyKerasMomentum", var=var, accum=accum, lr=lr, + grad=grad, indices=indices, + momentum=momentum, + use_locking=use_locking, + use_nesterov=use_nesterov, + name=name) + return _op +ResourceSparseApplyKerasMomentum = tf_export("raw_ops.ResourceSparseApplyKerasMomentum")(_ops.to_raw_op(resource_sparse_apply_keras_momentum)) + + +def resource_sparse_apply_keras_momentum_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], grad: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], indices: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_Tindices], momentum: Annotated[Any, TV_ResourceSparseApplyKerasMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad, momentum], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad, momentum) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad, indices, momentum] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "use_nesterov", use_nesterov) + _result = _execute.execute(b"ResourceSparseApplyKerasMomentum", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyMomentum_T = TypeVar("TV_ResourceSparseApplyMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyMomentum_Tindices = TypeVar("TV_ResourceSparseApplyMomentum_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_momentum(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyMomentum_T], grad: Annotated[Any, TV_ResourceSparseApplyMomentum_T], indices: Annotated[Any, TV_ResourceSparseApplyMomentum_Tindices], momentum: Annotated[Any, TV_ResourceSparseApplyMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None): + r"""Update relevant entries in '*var' and '*accum' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + That is for rows we have grad for, we update var and accum as follows: + + accum = accum * momentum + grad + var -= lr * accum + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + momentum: A `Tensor`. Must have the same type as `lr`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var - lr * momentum * accum, so in the end, the var you get is actually + var - lr * momentum * accum. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyMomentum", name, var, accum, lr, grad, + indices, momentum, "use_locking", use_locking, "use_nesterov", + use_nesterov) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_momentum_eager_fallback( + var, accum, lr, grad, indices, momentum, use_locking=use_locking, + use_nesterov=use_nesterov, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyMomentum", var=var, accum=accum, lr=lr, grad=grad, + indices=indices, momentum=momentum, + use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + return _op +ResourceSparseApplyMomentum = tf_export("raw_ops.ResourceSparseApplyMomentum")(_ops.to_raw_op(resource_sparse_apply_momentum)) + + +def resource_sparse_apply_momentum_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyMomentum_T], grad: Annotated[Any, TV_ResourceSparseApplyMomentum_T], indices: Annotated[Any, TV_ResourceSparseApplyMomentum_Tindices], momentum: Annotated[Any, TV_ResourceSparseApplyMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, grad, momentum], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, grad, momentum) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, grad, indices, momentum] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking, "use_nesterov", use_nesterov) + _result = _execute.execute(b"ResourceSparseApplyMomentum", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyProximalAdagrad_T = TypeVar("TV_ResourceSparseApplyProximalAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyProximalAdagrad_Tindices = TypeVar("TV_ResourceSparseApplyProximalAdagrad_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_proximal_adagrad(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], l1: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], l2: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], grad: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], indices: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_Tindices], use_locking:bool=False, name=None): + r"""Sparse update entries in '*var' and '*accum' according to FOBOS algorithm. + + That is for rows we have grad for, we update var and accum as follows: + accum += grad * grad + prox_v = var + prox_v -= lr * grad * (1 / sqrt(accum)) + var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0} + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + accum: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Learning rate. Must be a scalar. + l1: A `Tensor`. Must have the same type as `lr`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `lr`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyProximalAdagrad", name, var, accum, lr, l1, + l2, grad, indices, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_proximal_adagrad_eager_fallback( + var, accum, lr, l1, l2, grad, indices, use_locking=use_locking, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyProximalAdagrad", var=var, accum=accum, lr=lr, + l1=l1, l2=l2, grad=grad, + indices=indices, + use_locking=use_locking, + name=name) + return _op +ResourceSparseApplyProximalAdagrad = tf_export("raw_ops.ResourceSparseApplyProximalAdagrad")(_ops.to_raw_op(resource_sparse_apply_proximal_adagrad)) + + +def resource_sparse_apply_proximal_adagrad_eager_fallback(var: Annotated[Any, _atypes.Resource], accum: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], l1: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], l2: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], grad: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_T], indices: Annotated[Any, TV_ResourceSparseApplyProximalAdagrad_Tindices], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, l1, l2, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, l1, l2, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + accum = _ops.convert_to_tensor(accum, _dtypes.resource) + _inputs_flat = [var, accum, lr, l1, l2, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyProximalAdagrad", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyProximalGradientDescent_T = TypeVar("TV_ResourceSparseApplyProximalGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyProximalGradientDescent_Tindices = TypeVar("TV_ResourceSparseApplyProximalGradientDescent_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_proximal_gradient_descent(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], grad: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], indices: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_Tindices], use_locking:bool=False, name=None): + r"""Sparse update '*var' as FOBOS algorithm with fixed learning rate. + + That is for rows we have grad for, we update var as follows: + prox_v = var - alpha * grad + var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0} + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `alpha`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `alpha`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `alpha`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyProximalGradientDescent", name, var, alpha, + l1, l2, grad, indices, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_proximal_gradient_descent_eager_fallback( + var, alpha, l1, l2, grad, indices, use_locking=use_locking, + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyProximalGradientDescent", var=var, alpha=alpha, + l1=l1, l2=l2, grad=grad, + indices=indices, + use_locking=use_locking, + name=name) + return _op +ResourceSparseApplyProximalGradientDescent = tf_export("raw_ops.ResourceSparseApplyProximalGradientDescent")(_ops.to_raw_op(resource_sparse_apply_proximal_gradient_descent)) + + +def resource_sparse_apply_proximal_gradient_descent_eager_fallback(var: Annotated[Any, _atypes.Resource], alpha: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], l1: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], l2: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], grad: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_T], indices: Annotated[Any, TV_ResourceSparseApplyProximalGradientDescent_Tindices], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([alpha, l1, l2, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (alpha, l1, l2, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + _inputs_flat = [var, alpha, l1, l2, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyProximalGradientDescent", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_ResourceSparseApplyRMSProp_T = TypeVar("TV_ResourceSparseApplyRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_ResourceSparseApplyRMSProp_Tindices = TypeVar("TV_ResourceSparseApplyRMSProp_Tindices", _atypes.Int32, _atypes.Int64) + +def resource_sparse_apply_rms_prop(var: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], rho: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], momentum: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], epsilon: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], grad: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], indices: Annotated[Any, TV_ResourceSparseApplyRMSProp_Tindices], use_locking:bool=False, name=None): + r"""Update '*var' according to the RMSProp algorithm. + + Note that in dense implementation of this algorithm, ms and mom will + update even if the grad is zero, but in this sparse implementation, ms + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + Delta = learning_rate * gradient / sqrt(mean_square + epsilon) + + ms <- rho * ms_{t-1} + (1-rho) * grad * grad + mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) + var <- var - mom + + Args: + var: A `Tensor` of type `resource`. Should be from a Variable(). + ms: A `Tensor` of type `resource`. Should be from a Variable(). + mom: A `Tensor` of type `resource`. Should be from a Variable(). + lr: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `lr`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `lr`. + epsilon: A `Tensor`. Must have the same type as `lr`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `lr`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var, ms and mom. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, ms, and mom tensors is protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceSparseApplyRMSProp", name, var, ms, mom, lr, rho, + momentum, epsilon, grad, indices, "use_locking", use_locking) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return resource_sparse_apply_rms_prop_eager_fallback( + var, ms, mom, lr, rho, momentum, epsilon, grad, indices, + use_locking=use_locking, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceSparseApplyRMSProp", var=var, ms=ms, mom=mom, lr=lr, rho=rho, + momentum=momentum, epsilon=epsilon, + grad=grad, indices=indices, + use_locking=use_locking, name=name) + return _op +ResourceSparseApplyRMSProp = tf_export("raw_ops.ResourceSparseApplyRMSProp")(_ops.to_raw_op(resource_sparse_apply_rms_prop)) + + +def resource_sparse_apply_rms_prop_eager_fallback(var: Annotated[Any, _atypes.Resource], ms: Annotated[Any, _atypes.Resource], mom: Annotated[Any, _atypes.Resource], lr: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], rho: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], momentum: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], epsilon: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], grad: Annotated[Any, TV_ResourceSparseApplyRMSProp_T], indices: Annotated[Any, TV_ResourceSparseApplyRMSProp_Tindices], use_locking: bool, name, ctx): + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lr, rho, momentum, epsilon, grad], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.int32, _dtypes.uint8, _dtypes.int16, _dtypes.int8, _dtypes.complex64, _dtypes.int64, _dtypes.qint8, _dtypes.quint8, _dtypes.qint32, _dtypes.bfloat16, _dtypes.qint16, _dtypes.quint16, _dtypes.uint16, _dtypes.complex128, _dtypes.half, _dtypes.uint32, _dtypes.uint64, ]) + (lr, rho, momentum, epsilon, grad) = _inputs_T + _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], ctx, [_dtypes.int32, _dtypes.int64, ]) + var = _ops.convert_to_tensor(var, _dtypes.resource) + ms = _ops.convert_to_tensor(ms, _dtypes.resource) + mom = _ops.convert_to_tensor(mom, _dtypes.resource) + _inputs_flat = [var, ms, mom, lr, rho, momentum, epsilon, grad, indices] + _attrs = ("T", _attr_T, "Tindices", _attr_Tindices, "use_locking", + use_locking) + _result = _execute.execute(b"ResourceSparseApplyRMSProp", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_SparseApplyAdadelta_T = TypeVar("TV_SparseApplyAdadelta_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyAdadelta_Tindices = TypeVar("TV_SparseApplyAdadelta_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_adadelta(var: Annotated[Any, TV_SparseApplyAdadelta_T], accum: Annotated[Any, TV_SparseApplyAdadelta_T], accum_update: Annotated[Any, TV_SparseApplyAdadelta_T], lr: Annotated[Any, TV_SparseApplyAdadelta_T], rho: Annotated[Any, TV_SparseApplyAdadelta_T], epsilon: Annotated[Any, TV_SparseApplyAdadelta_T], grad: Annotated[Any, TV_SparseApplyAdadelta_T], indices: Annotated[Any, TV_SparseApplyAdadelta_Tindices], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyAdadelta_T]: + r"""var: Should be from a Variable(). + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + accum_update: A mutable `Tensor`. Must have the same type as `var`. + : Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay factor. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_adadelta op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyAdadelta", var=var, accum=accum, + accum_update=accum_update, lr=lr, rho=rho, + epsilon=epsilon, grad=grad, indices=indices, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyAdadelta", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyAdadelta = tf_export("raw_ops.SparseApplyAdadelta")(_ops.to_raw_op(sparse_apply_adadelta)) + + +def sparse_apply_adadelta_eager_fallback(var: Annotated[Any, TV_SparseApplyAdadelta_T], accum: Annotated[Any, TV_SparseApplyAdadelta_T], accum_update: Annotated[Any, TV_SparseApplyAdadelta_T], lr: Annotated[Any, TV_SparseApplyAdadelta_T], rho: Annotated[Any, TV_SparseApplyAdadelta_T], epsilon: Annotated[Any, TV_SparseApplyAdadelta_T], grad: Annotated[Any, TV_SparseApplyAdadelta_T], indices: Annotated[Any, TV_SparseApplyAdadelta_Tindices], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyAdadelta_T]: + raise RuntimeError("sparse_apply_adadelta op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyAdagrad_T = TypeVar("TV_SparseApplyAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyAdagrad_Tindices = TypeVar("TV_SparseApplyAdagrad_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_adagrad(var: Annotated[Any, TV_SparseApplyAdagrad_T], accum: Annotated[Any, TV_SparseApplyAdagrad_T], lr: Annotated[Any, TV_SparseApplyAdagrad_T], grad: Annotated[Any, TV_SparseApplyAdagrad_T], indices: Annotated[Any, TV_SparseApplyAdagrad_Tindices], use_locking:bool=False, update_slots:bool=True, name=None) -> Annotated[Any, TV_SparseApplyAdagrad_T]: + r"""Update relevant entries in '*var' and '*accum' according to the adagrad scheme. + + That is for rows we have grad for, we update var and accum as follows: + $$accum += grad * grad$$ + $$var -= lr * grad * (1 / sqrt(accum))$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_adagrad op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyAdagrad", var=var, accum=accum, lr=lr, grad=grad, + indices=indices, use_locking=use_locking, + update_slots=update_slots, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking"), "update_slots", + _op._get_attr_bool("update_slots")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyAdagrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyAdagrad = tf_export("raw_ops.SparseApplyAdagrad")(_ops.to_raw_op(sparse_apply_adagrad)) + + +def sparse_apply_adagrad_eager_fallback(var: Annotated[Any, TV_SparseApplyAdagrad_T], accum: Annotated[Any, TV_SparseApplyAdagrad_T], lr: Annotated[Any, TV_SparseApplyAdagrad_T], grad: Annotated[Any, TV_SparseApplyAdagrad_T], indices: Annotated[Any, TV_SparseApplyAdagrad_Tindices], use_locking: bool, update_slots: bool, name, ctx) -> Annotated[Any, TV_SparseApplyAdagrad_T]: + raise RuntimeError("sparse_apply_adagrad op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyAdagradDA_T = TypeVar("TV_SparseApplyAdagradDA_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyAdagradDA_Tindices = TypeVar("TV_SparseApplyAdagradDA_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_adagrad_da(var: Annotated[Any, TV_SparseApplyAdagradDA_T], gradient_accumulator: Annotated[Any, TV_SparseApplyAdagradDA_T], gradient_squared_accumulator: Annotated[Any, TV_SparseApplyAdagradDA_T], grad: Annotated[Any, TV_SparseApplyAdagradDA_T], indices: Annotated[Any, TV_SparseApplyAdagradDA_Tindices], lr: Annotated[Any, TV_SparseApplyAdagradDA_T], l1: Annotated[Any, TV_SparseApplyAdagradDA_T], l2: Annotated[Any, TV_SparseApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyAdagradDA_T]: + r"""Update entries in '*var' and '*accum' according to the proximal adagrad scheme. + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + gradient_accumulator: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + gradient_squared_accumulator: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + global_step: A `Tensor` of type `int64`. + Training step number. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_adagrad_da op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyAdagradDA", var=var, + gradient_accumulator=gradient_accumulator, + gradient_squared_accumulator=gradient_squared_accumulator, + grad=grad, indices=indices, lr=lr, l1=l1, + l2=l2, global_step=global_step, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyAdagradDA", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyAdagradDA = tf_export("raw_ops.SparseApplyAdagradDA")(_ops.to_raw_op(sparse_apply_adagrad_da)) + + +def sparse_apply_adagrad_da_eager_fallback(var: Annotated[Any, TV_SparseApplyAdagradDA_T], gradient_accumulator: Annotated[Any, TV_SparseApplyAdagradDA_T], gradient_squared_accumulator: Annotated[Any, TV_SparseApplyAdagradDA_T], grad: Annotated[Any, TV_SparseApplyAdagradDA_T], indices: Annotated[Any, TV_SparseApplyAdagradDA_Tindices], lr: Annotated[Any, TV_SparseApplyAdagradDA_T], l1: Annotated[Any, TV_SparseApplyAdagradDA_T], l2: Annotated[Any, TV_SparseApplyAdagradDA_T], global_step: Annotated[Any, _atypes.Int64], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyAdagradDA_T]: + raise RuntimeError("sparse_apply_adagrad_da op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyAdagradV2_T = TypeVar("TV_SparseApplyAdagradV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyAdagradV2_Tindices = TypeVar("TV_SparseApplyAdagradV2_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_adagrad_v2(var: Annotated[Any, TV_SparseApplyAdagradV2_T], accum: Annotated[Any, TV_SparseApplyAdagradV2_T], lr: Annotated[Any, TV_SparseApplyAdagradV2_T], epsilon: Annotated[Any, TV_SparseApplyAdagradV2_T], grad: Annotated[Any, TV_SparseApplyAdagradV2_T], indices: Annotated[Any, TV_SparseApplyAdagradV2_Tindices], use_locking:bool=False, update_slots:bool=True, name=None) -> Annotated[Any, TV_SparseApplyAdagradV2_T]: + r"""Update relevant entries in '*var' and '*accum' according to the adagrad scheme. + + That is for rows we have grad for, we update var and accum as follows: + $$accum += grad * grad$$ + $$var -= lr * grad * (1 / sqrt(accum))$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + epsilon: A `Tensor`. Must have the same type as `var`. + Constant factor. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + update_slots: An optional `bool`. Defaults to `True`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_adagrad_v2 op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if update_slots is None: + update_slots = True + update_slots = _execute.make_bool(update_slots, "update_slots") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyAdagradV2", var=var, accum=accum, lr=lr, epsilon=epsilon, + grad=grad, indices=indices, + use_locking=use_locking, + update_slots=update_slots, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking"), "update_slots", + _op._get_attr_bool("update_slots")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyAdagradV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyAdagradV2 = tf_export("raw_ops.SparseApplyAdagradV2")(_ops.to_raw_op(sparse_apply_adagrad_v2)) + + +def sparse_apply_adagrad_v2_eager_fallback(var: Annotated[Any, TV_SparseApplyAdagradV2_T], accum: Annotated[Any, TV_SparseApplyAdagradV2_T], lr: Annotated[Any, TV_SparseApplyAdagradV2_T], epsilon: Annotated[Any, TV_SparseApplyAdagradV2_T], grad: Annotated[Any, TV_SparseApplyAdagradV2_T], indices: Annotated[Any, TV_SparseApplyAdagradV2_Tindices], use_locking: bool, update_slots: bool, name, ctx) -> Annotated[Any, TV_SparseApplyAdagradV2_T]: + raise RuntimeError("sparse_apply_adagrad_v2 op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyCenteredRMSProp_T = TypeVar("TV_SparseApplyCenteredRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyCenteredRMSProp_Tindices = TypeVar("TV_SparseApplyCenteredRMSProp_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_centered_rms_prop(var: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], mg: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], ms: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], mom: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], lr: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], rho: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], grad: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], indices: Annotated[Any, TV_SparseApplyCenteredRMSProp_Tindices], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyCenteredRMSProp_T]: + r"""Update '*var' according to the centered RMSProp algorithm. + + The centered RMSProp algorithm uses an estimate of the centered second moment + (i.e., the variance) for normalization, as opposed to regular RMSProp, which + uses the (uncentered) second moment. This often helps with training, but is + slightly more expensive in terms of computation and memory. + + Note that in dense implementation of this algorithm, mg, ms, and mom will + update even if the grad is zero, but in this sparse implementation, mg, ms, + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + mean_grad = decay * mean_grad + (1-decay) * gradient + Delta = learning_rate * gradient / sqrt(mean_square + epsilon - mean_grad ** 2) + + $$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$ + $$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$ + $$var <- var - mom$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + mg: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + ms: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + mom: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `var`. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var, ms and mom. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, mg, ms, and mom tensors is + protected by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_centered_rms_prop op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyCenteredRMSProp", var=var, mg=mg, ms=ms, mom=mom, lr=lr, + rho=rho, momentum=momentum, + epsilon=epsilon, grad=grad, + indices=indices, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyCenteredRMSProp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyCenteredRMSProp = tf_export("raw_ops.SparseApplyCenteredRMSProp")(_ops.to_raw_op(sparse_apply_centered_rms_prop)) + + +def sparse_apply_centered_rms_prop_eager_fallback(var: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], mg: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], ms: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], mom: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], lr: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], rho: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], momentum: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], epsilon: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], grad: Annotated[Any, TV_SparseApplyCenteredRMSProp_T], indices: Annotated[Any, TV_SparseApplyCenteredRMSProp_Tindices], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyCenteredRMSProp_T]: + raise RuntimeError("sparse_apply_centered_rms_prop op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyFtrl_T = TypeVar("TV_SparseApplyFtrl_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyFtrl_Tindices = TypeVar("TV_SparseApplyFtrl_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_ftrl(var: Annotated[Any, TV_SparseApplyFtrl_T], accum: Annotated[Any, TV_SparseApplyFtrl_T], linear: Annotated[Any, TV_SparseApplyFtrl_T], grad: Annotated[Any, TV_SparseApplyFtrl_T], indices: Annotated[Any, TV_SparseApplyFtrl_Tindices], lr: Annotated[Any, TV_SparseApplyFtrl_T], l1: Annotated[Any, TV_SparseApplyFtrl_T], l2: Annotated[Any, TV_SparseApplyFtrl_T], lr_power: Annotated[Any, TV_SparseApplyFtrl_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None) -> Annotated[Any, TV_SparseApplyFtrl_T]: + r"""Update relevant entries in '*var' according to the Ftrl-proximal scheme. + + That is for rows we have grad for, we update var, accum and linear as follows: + $$accum_new = accum + grad * grad$$ + $$linear += grad + (accum_{new}^{-lr_{power}} - accum^{-lr_{power}} / lr * var$$ + $$quadratic = 1.0 / (accum_{new}^{lr_{power}} * lr) + 2 * l2$$ + $$var = (sign(linear) * l1 - linear) / quadratic\ if\ |linear| > l1\ else\ 0.0$$ + $$accum = accum_{new}$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + linear: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + lr_power: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_ftrl op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyFtrl", var=var, accum=accum, linear=linear, grad=grad, + indices=indices, lr=lr, l1=l1, l2=l2, + lr_power=lr_power, use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking"), "multiply_linear_by_lr", + _op._get_attr_bool("multiply_linear_by_lr")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyFtrl", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyFtrl = tf_export("raw_ops.SparseApplyFtrl")(_ops.to_raw_op(sparse_apply_ftrl)) + + +def sparse_apply_ftrl_eager_fallback(var: Annotated[Any, TV_SparseApplyFtrl_T], accum: Annotated[Any, TV_SparseApplyFtrl_T], linear: Annotated[Any, TV_SparseApplyFtrl_T], grad: Annotated[Any, TV_SparseApplyFtrl_T], indices: Annotated[Any, TV_SparseApplyFtrl_Tindices], lr: Annotated[Any, TV_SparseApplyFtrl_T], l1: Annotated[Any, TV_SparseApplyFtrl_T], l2: Annotated[Any, TV_SparseApplyFtrl_T], lr_power: Annotated[Any, TV_SparseApplyFtrl_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx) -> Annotated[Any, TV_SparseApplyFtrl_T]: + raise RuntimeError("sparse_apply_ftrl op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyFtrlV2_T = TypeVar("TV_SparseApplyFtrlV2_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyFtrlV2_Tindices = TypeVar("TV_SparseApplyFtrlV2_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_ftrl_v2(var: Annotated[Any, TV_SparseApplyFtrlV2_T], accum: Annotated[Any, TV_SparseApplyFtrlV2_T], linear: Annotated[Any, TV_SparseApplyFtrlV2_T], grad: Annotated[Any, TV_SparseApplyFtrlV2_T], indices: Annotated[Any, TV_SparseApplyFtrlV2_Tindices], lr: Annotated[Any, TV_SparseApplyFtrlV2_T], l1: Annotated[Any, TV_SparseApplyFtrlV2_T], l2: Annotated[Any, TV_SparseApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_SparseApplyFtrlV2_T], lr_power: Annotated[Any, TV_SparseApplyFtrlV2_T], use_locking:bool=False, multiply_linear_by_lr:bool=False, name=None) -> Annotated[Any, TV_SparseApplyFtrlV2_T]: + r"""Update relevant entries in '*var' according to the Ftrl-proximal scheme. + + That is for rows we have grad for, we update var, accum and linear as follows: + grad_with_shrinkage = grad + 2 * l2_shrinkage * var + accum_new = accum + grad * grad + linear += grad_with_shrinkage - + (accum_new^(-lr_power) - accum^(-lr_power)) / lr * var + quadratic = 1.0 / (accum_new^(lr_power) * lr) + 2 * l2 + var = (sign(linear) * l1 - linear) / quadratic if |linear| > l1 else 0.0 + accum = accum_new + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + linear: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 shrinkage regularization. Must be a scalar. + l2_shrinkage: A `Tensor`. Must have the same type as `var`. + lr_power: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + multiply_linear_by_lr: An optional `bool`. Defaults to `False`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_ftrl_v2 op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if multiply_linear_by_lr is None: + multiply_linear_by_lr = False + multiply_linear_by_lr = _execute.make_bool(multiply_linear_by_lr, "multiply_linear_by_lr") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyFtrlV2", var=var, accum=accum, linear=linear, grad=grad, + indices=indices, lr=lr, l1=l1, l2=l2, + l2_shrinkage=l2_shrinkage, lr_power=lr_power, + use_locking=use_locking, + multiply_linear_by_lr=multiply_linear_by_lr, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking"), "multiply_linear_by_lr", + _op._get_attr_bool("multiply_linear_by_lr")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyFtrlV2", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyFtrlV2 = tf_export("raw_ops.SparseApplyFtrlV2")(_ops.to_raw_op(sparse_apply_ftrl_v2)) + + +def sparse_apply_ftrl_v2_eager_fallback(var: Annotated[Any, TV_SparseApplyFtrlV2_T], accum: Annotated[Any, TV_SparseApplyFtrlV2_T], linear: Annotated[Any, TV_SparseApplyFtrlV2_T], grad: Annotated[Any, TV_SparseApplyFtrlV2_T], indices: Annotated[Any, TV_SparseApplyFtrlV2_Tindices], lr: Annotated[Any, TV_SparseApplyFtrlV2_T], l1: Annotated[Any, TV_SparseApplyFtrlV2_T], l2: Annotated[Any, TV_SparseApplyFtrlV2_T], l2_shrinkage: Annotated[Any, TV_SparseApplyFtrlV2_T], lr_power: Annotated[Any, TV_SparseApplyFtrlV2_T], use_locking: bool, multiply_linear_by_lr: bool, name, ctx) -> Annotated[Any, TV_SparseApplyFtrlV2_T]: + raise RuntimeError("sparse_apply_ftrl_v2 op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyMomentum_T = TypeVar("TV_SparseApplyMomentum_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyMomentum_Tindices = TypeVar("TV_SparseApplyMomentum_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_momentum(var: Annotated[Any, TV_SparseApplyMomentum_T], accum: Annotated[Any, TV_SparseApplyMomentum_T], lr: Annotated[Any, TV_SparseApplyMomentum_T], grad: Annotated[Any, TV_SparseApplyMomentum_T], indices: Annotated[Any, TV_SparseApplyMomentum_Tindices], momentum: Annotated[Any, TV_SparseApplyMomentum_T], use_locking:bool=False, use_nesterov:bool=False, name=None) -> Annotated[Any, TV_SparseApplyMomentum_T]: + r"""Update relevant entries in '*var' and '*accum' according to the momentum scheme. + + Set use_nesterov = True if you want to use Nesterov momentum. + + That is for rows we have grad for, we update var and accum as follows: + + $$accum = accum * momentum + grad$$ + $$var -= lr * accum$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + momentum: A `Tensor`. Must have the same type as `var`. + Momentum. Must be a scalar. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var and accum tensors will be protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + use_nesterov: An optional `bool`. Defaults to `False`. + If `True`, the tensor passed to compute grad will be + var - lr * momentum * accum, so in the end, the var you get is actually + var - lr * momentum * accum. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_momentum op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + if use_nesterov is None: + use_nesterov = False + use_nesterov = _execute.make_bool(use_nesterov, "use_nesterov") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyMomentum", var=var, accum=accum, lr=lr, grad=grad, + indices=indices, momentum=momentum, + use_locking=use_locking, + use_nesterov=use_nesterov, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking"), "use_nesterov", + _op._get_attr_bool("use_nesterov")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyMomentum", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyMomentum = tf_export("raw_ops.SparseApplyMomentum")(_ops.to_raw_op(sparse_apply_momentum)) + + +def sparse_apply_momentum_eager_fallback(var: Annotated[Any, TV_SparseApplyMomentum_T], accum: Annotated[Any, TV_SparseApplyMomentum_T], lr: Annotated[Any, TV_SparseApplyMomentum_T], grad: Annotated[Any, TV_SparseApplyMomentum_T], indices: Annotated[Any, TV_SparseApplyMomentum_Tindices], momentum: Annotated[Any, TV_SparseApplyMomentum_T], use_locking: bool, use_nesterov: bool, name, ctx) -> Annotated[Any, TV_SparseApplyMomentum_T]: + raise RuntimeError("sparse_apply_momentum op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyProximalAdagrad_T = TypeVar("TV_SparseApplyProximalAdagrad_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyProximalAdagrad_Tindices = TypeVar("TV_SparseApplyProximalAdagrad_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_proximal_adagrad(var: Annotated[Any, TV_SparseApplyProximalAdagrad_T], accum: Annotated[Any, TV_SparseApplyProximalAdagrad_T], lr: Annotated[Any, TV_SparseApplyProximalAdagrad_T], l1: Annotated[Any, TV_SparseApplyProximalAdagrad_T], l2: Annotated[Any, TV_SparseApplyProximalAdagrad_T], grad: Annotated[Any, TV_SparseApplyProximalAdagrad_T], indices: Annotated[Any, TV_SparseApplyProximalAdagrad_Tindices], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyProximalAdagrad_T]: + r"""Sparse update entries in '*var' and '*accum' according to FOBOS algorithm. + + That is for rows we have grad for, we update var and accum as follows: + $$accum += grad * grad$$ + $$prox_v = var$$ + $$prox_v -= lr * grad * (1 / sqrt(accum))$$ + $$var = sign(prox_v)/(1+lr*l2) * max{|prox_v|-lr*l1,0}$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + accum: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Learning rate. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, updating of the var and accum tensors will be protected by + a lock; otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_proximal_adagrad op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyProximalAdagrad", var=var, accum=accum, lr=lr, l1=l1, + l2=l2, grad=grad, indices=indices, + use_locking=use_locking, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyProximalAdagrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyProximalAdagrad = tf_export("raw_ops.SparseApplyProximalAdagrad")(_ops.to_raw_op(sparse_apply_proximal_adagrad)) + + +def sparse_apply_proximal_adagrad_eager_fallback(var: Annotated[Any, TV_SparseApplyProximalAdagrad_T], accum: Annotated[Any, TV_SparseApplyProximalAdagrad_T], lr: Annotated[Any, TV_SparseApplyProximalAdagrad_T], l1: Annotated[Any, TV_SparseApplyProximalAdagrad_T], l2: Annotated[Any, TV_SparseApplyProximalAdagrad_T], grad: Annotated[Any, TV_SparseApplyProximalAdagrad_T], indices: Annotated[Any, TV_SparseApplyProximalAdagrad_Tindices], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyProximalAdagrad_T]: + raise RuntimeError("sparse_apply_proximal_adagrad op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyProximalGradientDescent_T = TypeVar("TV_SparseApplyProximalGradientDescent_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyProximalGradientDescent_Tindices = TypeVar("TV_SparseApplyProximalGradientDescent_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_proximal_gradient_descent(var: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], alpha: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], l1: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], l2: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], grad: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], indices: Annotated[Any, TV_SparseApplyProximalGradientDescent_Tindices], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyProximalGradientDescent_T]: + r"""Sparse update '*var' as FOBOS algorithm with fixed learning rate. + + That is for rows we have grad for, we update var as follows: + $$prox_v = var - alpha * grad$$ + $$var = sign(prox_v)/(1+alpha*l2) * max{|prox_v|-alpha*l1,0}$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + alpha: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + l1: A `Tensor`. Must have the same type as `var`. + L1 regularization. Must be a scalar. + l2: A `Tensor`. Must have the same type as `var`. + L2 regularization. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var and accum. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_proximal_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyProximalGradientDescent", var=var, alpha=alpha, l1=l1, + l2=l2, grad=grad, + indices=indices, + use_locking=use_locking, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyProximalGradientDescent", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyProximalGradientDescent = tf_export("raw_ops.SparseApplyProximalGradientDescent")(_ops.to_raw_op(sparse_apply_proximal_gradient_descent)) + + +def sparse_apply_proximal_gradient_descent_eager_fallback(var: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], alpha: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], l1: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], l2: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], grad: Annotated[Any, TV_SparseApplyProximalGradientDescent_T], indices: Annotated[Any, TV_SparseApplyProximalGradientDescent_Tindices], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyProximalGradientDescent_T]: + raise RuntimeError("sparse_apply_proximal_gradient_descent op does not support eager execution. Arg 'out' is a ref.") + +TV_SparseApplyRMSProp_T = TypeVar("TV_SparseApplyRMSProp_T", _atypes.BFloat16, _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.UInt16, _atypes.UInt32, _atypes.UInt64, _atypes.UInt8) +TV_SparseApplyRMSProp_Tindices = TypeVar("TV_SparseApplyRMSProp_Tindices", _atypes.Int32, _atypes.Int64) + +def sparse_apply_rms_prop(var: Annotated[Any, TV_SparseApplyRMSProp_T], ms: Annotated[Any, TV_SparseApplyRMSProp_T], mom: Annotated[Any, TV_SparseApplyRMSProp_T], lr: Annotated[Any, TV_SparseApplyRMSProp_T], rho: Annotated[Any, TV_SparseApplyRMSProp_T], momentum: Annotated[Any, TV_SparseApplyRMSProp_T], epsilon: Annotated[Any, TV_SparseApplyRMSProp_T], grad: Annotated[Any, TV_SparseApplyRMSProp_T], indices: Annotated[Any, TV_SparseApplyRMSProp_Tindices], use_locking:bool=False, name=None) -> Annotated[Any, TV_SparseApplyRMSProp_T]: + r"""Update '*var' according to the RMSProp algorithm. + + Note that in dense implementation of this algorithm, ms and mom will + update even if the grad is zero, but in this sparse implementation, ms + and mom will not update in iterations during which the grad is zero. + + mean_square = decay * mean_square + (1-decay) * gradient ** 2 + Delta = learning_rate * gradient / sqrt(mean_square + epsilon) + + $$ms <- rho * ms_{t-1} + (1-rho) * grad * grad$$ + $$mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon)$$ + $$var <- var - mom$$ + + Args: + var: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `qint16`, `quint16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. + Should be from a Variable(). + ms: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + mom: A mutable `Tensor`. Must have the same type as `var`. + Should be from a Variable(). + lr: A `Tensor`. Must have the same type as `var`. + Scaling factor. Must be a scalar. + rho: A `Tensor`. Must have the same type as `var`. + Decay rate. Must be a scalar. + momentum: A `Tensor`. Must have the same type as `var`. + epsilon: A `Tensor`. Must have the same type as `var`. + Ridge term. Must be a scalar. + grad: A `Tensor`. Must have the same type as `var`. The gradient. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A vector of indices into the first dimension of var, ms and mom. + use_locking: An optional `bool`. Defaults to `False`. + If `True`, updating of the var, ms, and mom tensors is protected + by a lock; otherwise the behavior is undefined, but may exhibit less + contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `var`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("sparse_apply_rms_prop op does not support eager execution. Arg 'out' is a ref.") + # Add nodes to the TensorFlow graph. + if use_locking is None: + use_locking = False + use_locking = _execute.make_bool(use_locking, "use_locking") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseApplyRMSProp", var=var, ms=ms, mom=mom, lr=lr, rho=rho, + momentum=momentum, epsilon=epsilon, grad=grad, + indices=indices, use_locking=use_locking, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "Tindices", + _op._get_attr_type("Tindices"), "use_locking", + _op._get_attr_bool("use_locking")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseApplyRMSProp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseApplyRMSProp = tf_export("raw_ops.SparseApplyRMSProp")(_ops.to_raw_op(sparse_apply_rms_prop)) + + +def sparse_apply_rms_prop_eager_fallback(var: Annotated[Any, TV_SparseApplyRMSProp_T], ms: Annotated[Any, TV_SparseApplyRMSProp_T], mom: Annotated[Any, TV_SparseApplyRMSProp_T], lr: Annotated[Any, TV_SparseApplyRMSProp_T], rho: Annotated[Any, TV_SparseApplyRMSProp_T], momentum: Annotated[Any, TV_SparseApplyRMSProp_T], epsilon: Annotated[Any, TV_SparseApplyRMSProp_T], grad: Annotated[Any, TV_SparseApplyRMSProp_T], indices: Annotated[Any, TV_SparseApplyRMSProp_Tindices], use_locking: bool, name, ctx) -> Annotated[Any, TV_SparseApplyRMSProp_T]: + raise RuntimeError("sparse_apply_rms_prop op does not support eager execution. Arg 'out' is a ref.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_uniform_quant_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_uniform_quant_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1ef163f90c504b7367f600470c11433245b6e878 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gen_uniform_quant_ops.py @@ -0,0 +1,1767 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_UniformDequantize_Tin = TypeVar("TV_UniformDequantize_Tin", _atypes.QInt32, _atypes.QInt8) +TV_UniformDequantize_Tout = TypeVar("TV_UniformDequantize_Tout", bound=_atypes.Float32) + +def uniform_dequantize(input: Annotated[Any, TV_UniformDequantize_Tin], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformDequantize_Tout, quantization_min_val: int, quantization_max_val: int, quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformDequantize_Tout]: + r"""Perform dequantization on the quantized Tensor `input`. + + Given quantized `input` which was quantized using `scales` and `zero_points`, performs dequantization using the formula: + dequantized_data = (quantized_data - zero_point) * scale. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `qint32`. + Must be a Tensor of Tin. + scales: A `Tensor` of type `float32`. + The float value(s) used as scale(s) when quantizing original data that input represents. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (input.dim_size(quantization_axis),) (per-axis quantization). + zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point(s) when quantizing original data that input represents. + Same shape condition as scales. + Tout: A `tf.DType` from: `tf.float32`. + The type of output Tensor. A tf.DType from: tf.qint8, tf.qint32 + quantization_min_val: An `int`. + The quantization min value that was used when input was quantized. + The purpose of this attribute is typically (but not limited to) to indicate narrow range, where this is set to: + `(Tin lowest) + 1` if narrow range, and `(Tin lowest)` otherwise. + For example, if Tin is qint8, this is set to -127 if narrow range quantized or -128 if not. + quantization_max_val: An `int`. + The quantization max value that was used when input was quantized. + The purpose of this attribute is typically (but not limited to) indicate narrow range, where this is set to: + `(Tout max)` for both narrow range and not narrow range. + For example, if Tin is qint8, this is set to 127. + quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. Otherwise, it must be set within range [0, input.dims()). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformDequantize", name, input, scales, zero_points, "Tout", + Tout, "quantization_axis", quantization_axis, "quantization_min_val", + quantization_min_val, "quantization_max_val", quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_dequantize_eager_fallback( + input, scales, zero_points, Tout=Tout, + quantization_axis=quantization_axis, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformDequantize", input=input, scales=scales, + zero_points=zero_points, Tout=Tout, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, + quantization_axis=quantization_axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout"), "quantization_axis", + _op._get_attr_int("quantization_axis"), "quantization_min_val", + _op._get_attr_int("quantization_min_val"), + "quantization_max_val", + _op._get_attr_int("quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformDequantize = tf_export("raw_ops.UniformDequantize")(_ops.to_raw_op(uniform_dequantize)) + + +def uniform_dequantize_eager_fallback(input: Annotated[Any, TV_UniformDequantize_Tin], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformDequantize_Tout, quantization_min_val: int, quantization_max_val: int, quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformDequantize_Tout]: + Tout = _execute.make_type(Tout, "Tout") + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _attr_Tin, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.qint32, ]) + scales = _ops.convert_to_tensor(scales, _dtypes.float32) + zero_points = _ops.convert_to_tensor(zero_points, _dtypes.int32) + _inputs_flat = [input, scales, zero_points] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "quantization_axis", + quantization_axis, "quantization_min_val", quantization_min_val, + "quantization_max_val", quantization_max_val) + _result = _execute.execute(b"UniformDequantize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformDequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantize_Tin = TypeVar("TV_UniformQuantize_Tin", bound=_atypes.Float32) +TV_UniformQuantize_Tout = TypeVar("TV_UniformQuantize_Tout", _atypes.QInt32, _atypes.QInt8) + +def uniform_quantize(input: Annotated[Any, TV_UniformQuantize_Tin], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantize_Tout, quantization_min_val: int, quantization_max_val: int, quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantize_Tout]: + r"""Perform quantization on Tensor `input`. + + Given `input`, `scales` and `zero_points`, performs quantization using the formula: + quantized_data = floor(input_data * (1.0f / scale) + 0.5f) + zero_point + + Args: + input: A `Tensor`. Must be one of the following types: `float32`. + Must be a Tensor of Tin. + scales: A `Tensor` of type `float32`. + The float value(s) to use as scale(s) to quantize `input`. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (input.dim_size(quantization_axis),) (per-axis quantization). + zero_points: A `Tensor` of type `int32`. + The int32 value(s) to use as zero_point(s) to quantize `input`. + Same shape condition as scales. + Tout: A `tf.DType` from: `tf.qint8, tf.qint32`. + The type of output Tensor. A tf.DType from: tf.float32 + quantization_min_val: An `int`. + The quantization min value to quantize `input`. + The purpose of this attribute is typically (but not limited to) to indicate narrow range, where this is set to: + `(Tin lowest) + 1` if narrow range, and `(Tin lowest)` otherwise. + For example, if Tin is qint8, this is set to -127 if narrow range quantized or -128 if not. + quantization_max_val: An `int`. + The quantization max value to quantize `input`. + The purpose of this attribute is typically (but not limited to) indicate narrow range, where this is set to: + `(Tout max)` for both narrow range and not narrow range. + For example, if Tin is qint8, this is set to 127. + quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. Otherwise, it must be set within range [0, input.dims()). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantize", name, input, scales, zero_points, "Tout", + Tout, "quantization_axis", quantization_axis, "quantization_min_val", + quantization_min_val, "quantization_max_val", quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantize_eager_fallback( + input, scales, zero_points, Tout=Tout, + quantization_axis=quantization_axis, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantize", input=input, scales=scales, + zero_points=zero_points, Tout=Tout, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, + quantization_axis=quantization_axis, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout"), "quantization_axis", + _op._get_attr_int("quantization_axis"), "quantization_min_val", + _op._get_attr_int("quantization_min_val"), + "quantization_max_val", + _op._get_attr_int("quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantize = tf_export("raw_ops.UniformQuantize")(_ops.to_raw_op(uniform_quantize)) + + +def uniform_quantize_eager_fallback(input: Annotated[Any, TV_UniformQuantize_Tin], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantize_Tout, quantization_min_val: int, quantization_max_val: int, quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantize_Tout]: + Tout = _execute.make_type(Tout, "Tout") + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _attr_Tin, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.float32, ]) + scales = _ops.convert_to_tensor(scales, _dtypes.float32) + zero_points = _ops.convert_to_tensor(zero_points, _dtypes.int32) + _inputs_flat = [input, scales, zero_points] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "quantization_axis", + quantization_axis, "quantization_min_val", quantization_min_val, + "quantization_max_val", quantization_max_val) + _result = _execute.execute(b"UniformQuantize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedAdd_T = TypeVar("TV_UniformQuantizedAdd_T", bound=_atypes.QInt32) + +def uniform_quantized_add(lhs: Annotated[Any, TV_UniformQuantizedAdd_T], rhs: Annotated[Any, TV_UniformQuantizedAdd_T], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, lhs_quantization_axis:int=-1, rhs_quantization_axis:int=-1, output_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedAdd_T]: + r"""Perform quantized add of quantized Tensor `lhs` and quantized Tensor `rhs` to make quantized `output`. + + Given quantized `lhs` and quantized `rhs`, performs quantized add on `lhs` and `rhs` to make quantized `output`. + + `UniformQuantizedAdd` follows Numpy broadcasting rules. + The two input array shapes are compared element-wise. + Starting with the trailing dimensions, the two dimensions either have to be equal or one of them needs to be 1. + + `lhs` and `rhs` must be quantized Tensor, where data value is quantized using the formula: + ``` + quantized_data = clip(original_data / scale + zero_point, quantization_min_val, quantization_max_val) + ``` + `output` is also quantized, using the same formula. + + If `lhs` and `output` is both per-axis quantized, the quantization axis must match. + Also, if `rhs` and `output` is both per-axis quantized, the quantization axis must match. + *Match* means the axis must match when adding, regarding the broadcasting. + i.e. For both operands `lhs` and `rhs`, + if `operand.quantization_axis` >= 0 and `output.quantization_axis` >= 0, + `operand.dims` - `operand.quantization_axis` must be equal to `output.dims` - `output.quantization_axis`. + + Args: + lhs: A `Tensor`. Must be one of the following types: `qint32`. + Must be a quantized tensor. + rhs: A `Tensor`. Must have the same type as `lhs`. + Must be a quantized tensor. + lhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale factors when quantizing the original data that `lhs` represents. + lhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that `lhs` represents. + Must have same shape with `lhs_scales`. + rhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale factors when quantizing the original data that `rhs` represents. + rhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that `rhs` represents. + Must have same shape with `rhs_scales`. + output_scales: A `Tensor` of type `float32`. + The float value(s) to use as scale factors when quantizing original data that `output` represents. + output_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that output represents. + Must have same shape with `output_scales`. + lhs_quantization_min_val: An `int`. + The min value of the quantized data stored in `lhs`. + For example, if `Tin` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + lhs_quantization_max_val: An `int`. + The max value of the quantized data stored in `lhs`. + For example, if `Tin` is `qint8`, this must be set to 127. + rhs_quantization_min_val: An `int`. + The min value of the quantized data stored in `rhs`. + For example, if `Tin` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + rhs_quantization_max_val: An `int`. + The max value of the quantized data stored in `rhs`. + For example, if `Tin` is `qint8`, this must be set to 127. + output_quantization_min_val: An `int`. + The min value of the quantized data stored in `output`. + For example, if `Tout` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + output_quantization_max_val: An `int`. + The max value of the quantized data stored in `output`. + For example, if `Tout` is `qint8`, this must be set to 127. + lhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `lhs`, only per-tensor quantization is supported. + Thus, this must be set to -1. + Other values will raise error at OpKernel construction. + rhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `rhs`, only per-tensor quantization + or per-channel quantization along `kernel_output_feature_dimension` is supported. + Thus, this must be set to -1 or `dimension_numbers.kernel_output_feature_dimension`. + Other values will raise error at OpKernel construction. + output_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `output`, only per-tensor quantization or per-channel quantization along `output_feature_dimension` is supported. + Thus, this must be set to -1 or `dimension_numbers.output_feature_dimension`. + Other values will raise error at OpKernel construction. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `lhs`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedAdd", name, lhs, rhs, lhs_scales, + lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, + output_zero_points, "lhs_quantization_axis", lhs_quantization_axis, + "lhs_quantization_min_val", lhs_quantization_min_val, + "lhs_quantization_max_val", lhs_quantization_max_val, + "rhs_quantization_axis", rhs_quantization_axis, + "rhs_quantization_min_val", rhs_quantization_min_val, + "rhs_quantization_max_val", rhs_quantization_max_val, + "output_quantization_axis", output_quantization_axis, + "output_quantization_min_val", output_quantization_min_val, + "output_quantization_max_val", output_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_add_eager_fallback( + lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, + output_scales, output_zero_points, + lhs_quantization_axis=lhs_quantization_axis, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_axis=rhs_quantization_axis, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_axis=output_quantization_axis, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedAdd", lhs=lhs, rhs=rhs, lhs_scales=lhs_scales, + lhs_zero_points=lhs_zero_points, + rhs_scales=rhs_scales, + rhs_zero_points=rhs_zero_points, + output_scales=output_scales, + output_zero_points=output_zero_points, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, + lhs_quantization_axis=lhs_quantization_axis, + rhs_quantization_axis=rhs_quantization_axis, + output_quantization_axis=output_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("lhs_quantization_axis", + _op._get_attr_int("lhs_quantization_axis"), + "lhs_quantization_min_val", + _op._get_attr_int("lhs_quantization_min_val"), + "lhs_quantization_max_val", + _op._get_attr_int("lhs_quantization_max_val"), + "rhs_quantization_axis", + _op._get_attr_int("rhs_quantization_axis"), + "rhs_quantization_min_val", + _op._get_attr_int("rhs_quantization_min_val"), + "rhs_quantization_max_val", + _op._get_attr_int("rhs_quantization_max_val"), + "output_quantization_axis", + _op._get_attr_int("output_quantization_axis"), + "output_quantization_min_val", + _op._get_attr_int("output_quantization_min_val"), + "output_quantization_max_val", + _op._get_attr_int("output_quantization_max_val"), "T", + _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedAdd = tf_export("raw_ops.UniformQuantizedAdd")(_ops.to_raw_op(uniform_quantized_add)) + + +def uniform_quantized_add_eager_fallback(lhs: Annotated[Any, TV_UniformQuantizedAdd_T], rhs: Annotated[Any, TV_UniformQuantizedAdd_T], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, lhs_quantization_axis: int, rhs_quantization_axis: int, output_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedAdd_T]: + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([lhs, rhs], ctx, [_dtypes.qint32, ]) + (lhs, rhs) = _inputs_T + lhs_scales = _ops.convert_to_tensor(lhs_scales, _dtypes.float32) + lhs_zero_points = _ops.convert_to_tensor(lhs_zero_points, _dtypes.int32) + rhs_scales = _ops.convert_to_tensor(rhs_scales, _dtypes.float32) + rhs_zero_points = _ops.convert_to_tensor(rhs_zero_points, _dtypes.int32) + output_scales = _ops.convert_to_tensor(output_scales, _dtypes.float32) + output_zero_points = _ops.convert_to_tensor(output_zero_points, _dtypes.int32) + _inputs_flat = [lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, output_zero_points] + _attrs = ("lhs_quantization_axis", lhs_quantization_axis, + "lhs_quantization_min_val", lhs_quantization_min_val, + "lhs_quantization_max_val", lhs_quantization_max_val, + "rhs_quantization_axis", rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val, "output_quantization_axis", + output_quantization_axis, "output_quantization_min_val", + output_quantization_min_val, "output_quantization_max_val", + output_quantization_max_val, "T", _attr_T) + _result = _execute.execute(b"UniformQuantizedAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedClipByValue_T = TypeVar("TV_UniformQuantizedClipByValue_T", bound=_atypes.QInt32) + +def uniform_quantized_clip_by_value(operand: Annotated[Any, TV_UniformQuantizedClipByValue_T], min: Annotated[Any, TV_UniformQuantizedClipByValue_T], max: Annotated[Any, TV_UniformQuantizedClipByValue_T], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], quantization_min_val: int, quantization_max_val: int, quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedClipByValue_T]: + r"""Perform clip by value on the quantized Tensor `operand`. + + Given quantized `operand` which was quantized using `scales` and `zero_points`, performs clip by value using `min` and `max` values. + If quantization_axis is -1 (per-tensor quantized), the entire operand is clipped using scalar min, max. + Otherwise (per-channel quantized), the clipping is also done per-channel. + + Args: + operand: A `Tensor`. Must be one of the following types: `qint32`. + Must be a Tensor of T. + min: A `Tensor`. Must have the same type as `operand`. + The min value(s) to clip operand. Must be a Tensor of T. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (operand.dim_size(quantization_axis),) (per-axis quantization). + max: A `Tensor`. Must have the same type as `operand`. + The min value(s) to clip operand. Must be a Tensor of T. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (operand.dim_size(quantization_axis),) (per-axis quantization). + scales: A `Tensor` of type `float32`. + The float value(s) used as scale(s) when quantizing `operand`, `min` and `max`. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (operand.dim_size(quantization_axis),) (per-axis quantization). + zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point(s) when quantizing `operand`, `min` and `max`. + Same shape condition as scales. + quantization_min_val: An `int`. + The quantization min value that was used when operand was quantized. + quantization_max_val: An `int`. + The quantization max value that was used when operand was quantized. + quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. Otherwise, it must be set within range [0, operand.dims()). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `operand`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedClipByValue", name, operand, min, max, scales, + zero_points, "quantization_axis", quantization_axis, + "quantization_min_val", quantization_min_val, "quantization_max_val", + quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_clip_by_value_eager_fallback( + operand, min, max, scales, zero_points, + quantization_axis=quantization_axis, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedClipByValue", operand=operand, min=min, max=max, + scales=scales, zero_points=zero_points, + quantization_min_val=quantization_min_val, + quantization_max_val=quantization_max_val, + quantization_axis=quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "quantization_axis", + _op._get_attr_int("quantization_axis"), "quantization_min_val", + _op._get_attr_int("quantization_min_val"), + "quantization_max_val", + _op._get_attr_int("quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedClipByValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedClipByValue = tf_export("raw_ops.UniformQuantizedClipByValue")(_ops.to_raw_op(uniform_quantized_clip_by_value)) + + +def uniform_quantized_clip_by_value_eager_fallback(operand: Annotated[Any, TV_UniformQuantizedClipByValue_T], min: Annotated[Any, TV_UniformQuantizedClipByValue_T], max: Annotated[Any, TV_UniformQuantizedClipByValue_T], scales: Annotated[Any, _atypes.Float32], zero_points: Annotated[Any, _atypes.Int32], quantization_min_val: int, quantization_max_val: int, quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedClipByValue_T]: + quantization_min_val = _execute.make_int(quantization_min_val, "quantization_min_val") + quantization_max_val = _execute.make_int(quantization_max_val, "quantization_max_val") + if quantization_axis is None: + quantization_axis = -1 + quantization_axis = _execute.make_int(quantization_axis, "quantization_axis") + _attr_T, _inputs_T = _execute.args_to_matching_eager([operand, min, max], ctx, [_dtypes.qint32, ]) + (operand, min, max) = _inputs_T + scales = _ops.convert_to_tensor(scales, _dtypes.float32) + zero_points = _ops.convert_to_tensor(zero_points, _dtypes.int32) + _inputs_flat = [operand, min, max, scales, zero_points] + _attrs = ("T", _attr_T, "quantization_axis", quantization_axis, + "quantization_min_val", quantization_min_val, "quantization_max_val", + quantization_max_val) + _result = _execute.execute(b"UniformQuantizedClipByValue", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedClipByValue", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedConvolution_Tin = TypeVar("TV_UniformQuantizedConvolution_Tin", bound=_atypes.QInt8) +TV_UniformQuantizedConvolution_Tout = TypeVar("TV_UniformQuantizedConvolution_Tout", bound=_atypes.QInt32) + +def uniform_quantized_convolution(lhs: Annotated[Any, TV_UniformQuantizedConvolution_Tin], rhs: Annotated[Any, TV_UniformQuantizedConvolution_Tin], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedConvolution_Tout, padding: str, lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, window_strides=[], explicit_padding=[], lhs_dilation=[], rhs_dilation=[], batch_group_count:int=1, feature_group_count:int=1, dimension_numbers:str="", lhs_quantization_axis:int=-1, rhs_quantization_axis:int=-1, output_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedConvolution_Tout]: + r"""Perform quantized convolution of quantized Tensor `lhs` and quantized Tensor `rhs`. to make quantized `output`. + + Given quantized `lhs` and quantized `rhs`, performs quantized dot on `lhs` and `rhs` to make quantized `output`. + + `lhs` and `rhs` must be Tensors of same rank, and meet following shape conditions. + - `lhs_feature` % `feature_group_count` == 0 + - `lhs_feature` % `rhs_input_feature` == 0 + - `lhs_feature` / `feature_group_count` == `rhs_input_feature` + - `rhs_output_feature` % `feature_group_count` == 0 + - `lhs_batch` % `batch_group_count` == 0 + - `rhs_output_feature` % `batch_group_count` == 0 + + `lhs` and `rhs` must be quantized Tensor, where data value is quantized using the formula: + ``` + quantized_data = clip(original_data / scale + zero_point, quantization_min_val, quantization_max_val) + ``` + `output` is also quantized, using the same formula. + If `rhs` is per-tensor quantized, `output` must be also per-tensor quantized. + + Args: + lhs: A `Tensor`. Must be one of the following types: `qint8`. + Must be a quantized tensor, rank >= 3. + rhs: A `Tensor`. Must have the same type as `lhs`. + Must be a quantized tensor, same rank as `lhs`. + lhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale factors when quantizing the original data that `lhs` represents. + Must be a scalar `Tensor` (`lhs` supports only per-tensor quantization). + lhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that `lhs` represents. + Same shape condition as `lhs_scales`. + rhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale factors when quantizing the original data that `rhs` represents. + Must be a scalar `Tensor` for per-tensor quantization, + or 1D `Tensor` of size `rhs.dim_size(kernel_output_feature_dimension)`, for per-channel quantization. + rhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that `rhs` represents. + Same shape condition as `rhs_scales`. + output_scales: A `Tensor` of type `float32`. + The float value(s) to use as scale factors when quantizing original data that `output` represents. + Must be a scalar `Tensor` for per-tensor quantization, + or 1D `Tensor` of size `rhs.dim_size(kernel_output_feature_dimension)` + - which is equal to `output.dim_size(output_feature_dimension)`, + for per-channel quantization. + If `rhs` is per-tensor quantized, output must be also per-tensor quantized. + This means that if `rhs_scales` and `rhs_zero_points` are scalar `Tensor`s, `output_scales` and `output_zero_points` must be scalar `Tensor`s as well. + output_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero points when quantizing original data that output represents. + Same shape condition as `output_scales`. + Tout: A `tf.DType` from: `tf.qint32`. The type of `output` `Tensor`. + padding: A `string`. + string from: `"SAME"`, `"VALID"`, or `"EXPLICIT"`, indicating the type of padding algorithm to use. + lhs_quantization_min_val: An `int`. + The min value of the quantized data stored in `lhs`. + For example, if `Tin` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + lhs_quantization_max_val: An `int`. + The max value of the quantized data stored in `lhs`. + For example, if `Tin` is `qint8`, this must be set to 127. + rhs_quantization_min_val: An `int`. + The min value of the quantized data stored in `rhs`. + For example, if `Tin` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + rhs_quantization_max_val: An `int`. + The max value of the quantized data stored in `rhs`. + For example, if `Tin` is `qint8`, this must be set to 127. + output_quantization_min_val: An `int`. + The min value of the quantized data stored in `output`. + For example, if `Tout` is `qint8`, this must be set to -127 if narrow range quantized or -128 if not. + output_quantization_max_val: An `int`. + The max value of the quantized data stored in `output`. + For example, if `Tout` is `qint8`, this must be set to 127. + window_strides: An optional list of `ints`. Defaults to `[]`. + The stride of the sliding window for each spatial dimension of `lhs`. + Must be an empty list (default) or a list of size (number of spatial dimensions). + If an empty list is provided, the stride for each spatial dimension is set to 1. + explicit_padding: An optional list of `ints`. Defaults to `[]`. + If `padding` is `"EXPLICIT"`, must be set as a list indicating + the explicit paddings at the start and end of each `lhs` spatial dimension. + Otherwise, this must be empty. + + (If used,) Must be a list of size `2 * (number of lhs spatial dimensions)`, + where `(explicit_padding[2 * i], explicit_padding[2 * i + 1])` indicates + `(start_padding, end_padding)` of `spatial_dimensions[i]`. + lhs_dilation: An optional list of `ints`. Defaults to `[]`. + The dilation factor to apply in each spatial dimension of `lhs`. + Must be an empty list (default) or a list of size (number of `lhs` spatial dimensions). + If empty list, the dilation for each `lhs` spatial dimension is set to 1. + rhs_dilation: An optional list of `ints`. Defaults to `[]`. + The dilation factor to apply in each spatial dimension of `rhs`. + Must be an empty list (default) or a list of size (number of `rhs` spatial dimensions). + If empty list, the dilation for each `rhs` spatial dimension is set to 1. + batch_group_count: An optional `int`. Defaults to `1`. + The number of batch groups. Used for grouped filters. + Must be a divisor of `output_feature`. + feature_group_count: An optional `int`. Defaults to `1`. + The number of feature groups. Used for grouped convolutions. + Must be a divisor of both `lhs_feature` and `output_feature`. + dimension_numbers: An optional `string`. Defaults to `""`. + Structure of dimension information for the convolution op. + Must be an empty string (default) or a serialized string of `tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr` proto. + If empty string, the default is `("NCHW", "OIHW", "NCHW")` (for a 2D convolution). + lhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `lhs`, only per-tensor quantization is supported. + Thus, this must be set to -1. + Other values will raise error at OpKernel construction. + rhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `rhs`, only per-tensor quantization + or per-channel quantization along `kernel_output_feature_dimension` is supported. + Thus, this must be set to -1 or `dimension_numbers.kernel_output_feature_dimension`. + Other values will raise error at OpKernel construction. + output_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `output`, only per-tensor quantization or per-channel quantization along `output_feature_dimension` is supported. + Thus, this must be set to -1 or `dimension_numbers.output_feature_dimension`. + Other values will raise error at OpKernel construction. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedConvolution", name, lhs, rhs, lhs_scales, + lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, + output_zero_points, "Tout", Tout, "window_strides", window_strides, + "padding", padding, "explicit_padding", explicit_padding, + "lhs_dilation", lhs_dilation, "rhs_dilation", rhs_dilation, + "batch_group_count", batch_group_count, "feature_group_count", + feature_group_count, "dimension_numbers", dimension_numbers, + "lhs_quantization_axis", lhs_quantization_axis, + "lhs_quantization_min_val", lhs_quantization_min_val, + "lhs_quantization_max_val", lhs_quantization_max_val, + "rhs_quantization_axis", rhs_quantization_axis, + "rhs_quantization_min_val", rhs_quantization_min_val, + "rhs_quantization_max_val", rhs_quantization_max_val, + "output_quantization_axis", output_quantization_axis, + "output_quantization_min_val", output_quantization_min_val, + "output_quantization_max_val", output_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_convolution_eager_fallback( + lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, + output_scales, output_zero_points, Tout=Tout, + window_strides=window_strides, padding=padding, + explicit_padding=explicit_padding, lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, batch_group_count=batch_group_count, + feature_group_count=feature_group_count, + dimension_numbers=dimension_numbers, + lhs_quantization_axis=lhs_quantization_axis, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_axis=rhs_quantization_axis, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_axis=output_quantization_axis, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + padding = _execute.make_str(padding, "padding") + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if window_strides is None: + window_strides = [] + if not isinstance(window_strides, (list, tuple)): + raise TypeError( + "Expected list for 'window_strides' argument to " + "'uniform_quantized_convolution' Op, not %r." % window_strides) + window_strides = [_execute.make_int(_i, "window_strides") for _i in window_strides] + if explicit_padding is None: + explicit_padding = [] + if not isinstance(explicit_padding, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_padding' argument to " + "'uniform_quantized_convolution' Op, not %r." % explicit_padding) + explicit_padding = [_execute.make_int(_i, "explicit_padding") for _i in explicit_padding] + if lhs_dilation is None: + lhs_dilation = [] + if not isinstance(lhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'lhs_dilation' argument to " + "'uniform_quantized_convolution' Op, not %r." % lhs_dilation) + lhs_dilation = [_execute.make_int(_i, "lhs_dilation") for _i in lhs_dilation] + if rhs_dilation is None: + rhs_dilation = [] + if not isinstance(rhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'rhs_dilation' argument to " + "'uniform_quantized_convolution' Op, not %r." % rhs_dilation) + rhs_dilation = [_execute.make_int(_i, "rhs_dilation") for _i in rhs_dilation] + if batch_group_count is None: + batch_group_count = 1 + batch_group_count = _execute.make_int(batch_group_count, "batch_group_count") + if feature_group_count is None: + feature_group_count = 1 + feature_group_count = _execute.make_int(feature_group_count, "feature_group_count") + if dimension_numbers is None: + dimension_numbers = "" + dimension_numbers = _execute.make_str(dimension_numbers, "dimension_numbers") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedConvolution", lhs=lhs, rhs=rhs, + lhs_scales=lhs_scales, + lhs_zero_points=lhs_zero_points, + rhs_scales=rhs_scales, + rhs_zero_points=rhs_zero_points, + output_scales=output_scales, + output_zero_points=output_zero_points, + Tout=Tout, padding=padding, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, + window_strides=window_strides, + explicit_padding=explicit_padding, + lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, + batch_group_count=batch_group_count, + feature_group_count=feature_group_count, + dimension_numbers=dimension_numbers, + lhs_quantization_axis=lhs_quantization_axis, + rhs_quantization_axis=rhs_quantization_axis, + output_quantization_axis=output_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout"), "window_strides", + _op.get_attr("window_strides"), "padding", + _op.get_attr("padding"), "explicit_padding", + _op.get_attr("explicit_padding"), "lhs_dilation", + _op.get_attr("lhs_dilation"), "rhs_dilation", + _op.get_attr("rhs_dilation"), "batch_group_count", + _op._get_attr_int("batch_group_count"), "feature_group_count", + _op._get_attr_int("feature_group_count"), "dimension_numbers", + _op.get_attr("dimension_numbers"), "lhs_quantization_axis", + _op._get_attr_int("lhs_quantization_axis"), + "lhs_quantization_min_val", + _op._get_attr_int("lhs_quantization_min_val"), + "lhs_quantization_max_val", + _op._get_attr_int("lhs_quantization_max_val"), + "rhs_quantization_axis", + _op._get_attr_int("rhs_quantization_axis"), + "rhs_quantization_min_val", + _op._get_attr_int("rhs_quantization_min_val"), + "rhs_quantization_max_val", + _op._get_attr_int("rhs_quantization_max_val"), + "output_quantization_axis", + _op._get_attr_int("output_quantization_axis"), + "output_quantization_min_val", + _op._get_attr_int("output_quantization_min_val"), + "output_quantization_max_val", + _op._get_attr_int("output_quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedConvolution", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedConvolution = tf_export("raw_ops.UniformQuantizedConvolution")(_ops.to_raw_op(uniform_quantized_convolution)) + + +def uniform_quantized_convolution_eager_fallback(lhs: Annotated[Any, TV_UniformQuantizedConvolution_Tin], rhs: Annotated[Any, TV_UniformQuantizedConvolution_Tin], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedConvolution_Tout, padding: str, lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, window_strides, explicit_padding, lhs_dilation, rhs_dilation, batch_group_count: int, feature_group_count: int, dimension_numbers: str, lhs_quantization_axis: int, rhs_quantization_axis: int, output_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedConvolution_Tout]: + Tout = _execute.make_type(Tout, "Tout") + padding = _execute.make_str(padding, "padding") + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if window_strides is None: + window_strides = [] + if not isinstance(window_strides, (list, tuple)): + raise TypeError( + "Expected list for 'window_strides' argument to " + "'uniform_quantized_convolution' Op, not %r." % window_strides) + window_strides = [_execute.make_int(_i, "window_strides") for _i in window_strides] + if explicit_padding is None: + explicit_padding = [] + if not isinstance(explicit_padding, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_padding' argument to " + "'uniform_quantized_convolution' Op, not %r." % explicit_padding) + explicit_padding = [_execute.make_int(_i, "explicit_padding") for _i in explicit_padding] + if lhs_dilation is None: + lhs_dilation = [] + if not isinstance(lhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'lhs_dilation' argument to " + "'uniform_quantized_convolution' Op, not %r." % lhs_dilation) + lhs_dilation = [_execute.make_int(_i, "lhs_dilation") for _i in lhs_dilation] + if rhs_dilation is None: + rhs_dilation = [] + if not isinstance(rhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'rhs_dilation' argument to " + "'uniform_quantized_convolution' Op, not %r." % rhs_dilation) + rhs_dilation = [_execute.make_int(_i, "rhs_dilation") for _i in rhs_dilation] + if batch_group_count is None: + batch_group_count = 1 + batch_group_count = _execute.make_int(batch_group_count, "batch_group_count") + if feature_group_count is None: + feature_group_count = 1 + feature_group_count = _execute.make_int(feature_group_count, "feature_group_count") + if dimension_numbers is None: + dimension_numbers = "" + dimension_numbers = _execute.make_str(dimension_numbers, "dimension_numbers") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _attr_Tin, _inputs_Tin = _execute.args_to_matching_eager([lhs, rhs], ctx, [_dtypes.qint8, ]) + (lhs, rhs) = _inputs_Tin + lhs_scales = _ops.convert_to_tensor(lhs_scales, _dtypes.float32) + lhs_zero_points = _ops.convert_to_tensor(lhs_zero_points, _dtypes.int32) + rhs_scales = _ops.convert_to_tensor(rhs_scales, _dtypes.float32) + rhs_zero_points = _ops.convert_to_tensor(rhs_zero_points, _dtypes.int32) + output_scales = _ops.convert_to_tensor(output_scales, _dtypes.float32) + output_zero_points = _ops.convert_to_tensor(output_zero_points, _dtypes.int32) + _inputs_flat = [lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, output_zero_points] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "window_strides", window_strides, + "padding", padding, "explicit_padding", explicit_padding, "lhs_dilation", + lhs_dilation, "rhs_dilation", rhs_dilation, "batch_group_count", + batch_group_count, "feature_group_count", feature_group_count, + "dimension_numbers", dimension_numbers, "lhs_quantization_axis", + lhs_quantization_axis, "lhs_quantization_min_val", lhs_quantization_min_val, + "lhs_quantization_max_val", lhs_quantization_max_val, + "rhs_quantization_axis", rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val, "output_quantization_axis", + output_quantization_axis, "output_quantization_min_val", + output_quantization_min_val, "output_quantization_max_val", + output_quantization_max_val) + _result = _execute.execute(b"UniformQuantizedConvolution", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedConvolution", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedConvolutionHybrid_Tlhs = TypeVar("TV_UniformQuantizedConvolutionHybrid_Tlhs", bound=_atypes.Float32) +TV_UniformQuantizedConvolutionHybrid_Trhs = TypeVar("TV_UniformQuantizedConvolutionHybrid_Trhs", bound=_atypes.QInt8) +TV_UniformQuantizedConvolutionHybrid_Tout = TypeVar("TV_UniformQuantizedConvolutionHybrid_Tout", bound=_atypes.Float32) + +def uniform_quantized_convolution_hybrid(lhs: Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Tlhs], rhs: Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Trhs], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedConvolutionHybrid_Tout, padding: str, rhs_quantization_min_val: int, rhs_quantization_max_val: int, window_strides=[], explicit_padding=[], lhs_dilation=[], rhs_dilation=[], batch_group_count:int=1, feature_group_count:int=1, dimension_numbers:str="", rhs_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Tout]: + r"""Perform hybrid quantized convolution of float Tensor `lhs` and quantized Tensor `rhs`. + + Given float `lhs` and quantized `rhs`, internally performs quantization on `lhs`, + and then performs quantized convolution on quantized `lhs` and `rhs`. + + The internal quantization on `lhs` is a quantization to `Trhs`, dynamic range, + per-batch (per-axis along axis `dimension_numbers.input_batch_dimension`), asymmetric, + and not narrow range (the range is [Trhs_MIN, Trhs_MAX]). + + `lhs` and `rhs` must be Tensors of same rank, and meet following shape conditions. + - lhs_feature % feature_group_count == 0 + - lhs_feature % rhs_input_feature == 0 + - lhs_feature / feature_group_count == rhs_input_feature + - rhs_output_feature % feature_group_count == 0 + - lhs_batch % batch_group_count == 0 + - rhs_output_feature % batch_group_count == 0 + + `rhs` must be quantized Tensor, where its data value is quantized using the formula: + quantized_data = clip(original_data / scale + zero_point, quantization_min_val, quantization_max_val). + + Args: + lhs: A `Tensor`. Must be one of the following types: `float32`. + Must be a non-quantized Tensor of `Tlhs`, rank >= 3. + rhs: A `Tensor`. Must be one of the following types: `qint8`. + Must be a quantized Tensor of `Trhs`, same rank as `lhs`. + rhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale factors when quantizing the original data that `rhs` represents. + Must be a scalar Tensor for per-tensor quantization, + or 1D Tensor of size `rhs.dim_size(kernel_output_feature_dimension)`, for per-channel quantization. + rhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point when quantizing original data that `rhs` represents. + Same shape condition as `rhs_scales`. + Tout: A `tf.DType` from: `tf.float32`. The type of output Tensor. + padding: A `string`. + string from: `"SAME"`, `"VALID"`, or `"EXPLICIT"`, indicating the type of padding algorithm to use. + rhs_quantization_min_val: An `int`. + The min value of the quantized data stored in `rhs`. + For example, if `Trhs` is qint8, this must be set to -127 if narrow range quantized or -128 if not. + rhs_quantization_max_val: An `int`. + The max value of the quantized data stored in `rhs`. + For example, if `Trhs` is qint8, this must be set to 127. + window_strides: An optional list of `ints`. Defaults to `[]`. + The stride of the sliding window for each spatial dimension of `lhs`. + Must be an empty list (default) or a list of size (number of spatial dimensions). + If an empty list is provided, the stride for each spatial dimension is set to 1. + explicit_padding: An optional list of `ints`. Defaults to `[]`. + If `padding` Attr is `"EXPLICIT"`, must be set as a list indicating + the explicit paddings at the start and end of each lhs spatial dimension. + Otherwise, this Attr is must be empty. + + (If used,) Must be a list of size 2 * (number of lhs spatial dimensions), + where (explicit_padding[2 * i], explicit_padding[2 * i + 1]) indicates + spatial_dimensions[i] (start_padding, end_padding). + lhs_dilation: An optional list of `ints`. Defaults to `[]`. + The dilation factor to apply in each spatial dimension of `lhs`. + Must be an empty list (default) or a list of size (number of lhs spatial dimensions). + If empty list, the dilation for each lhs spatial dimension is set to 1. + rhs_dilation: An optional list of `ints`. Defaults to `[]`. + The dilation factor to apply in each spatial dimension of `rhs`. + Must be an empty list (default) or a list of size (number of rhs spatial dimensions). + If empty list, the dilation for each rhs spatial dimension is set to 1. + batch_group_count: An optional `int`. Defaults to `1`. + The number of batch groups. Used for grouped filters. + Must be a divisor of output_feature. + feature_group_count: An optional `int`. Defaults to `1`. + The number of feature groups. Used for grouped convolutions. + Must be a divisor of both lhs_feature and output_feature. + dimension_numbers: An optional `string`. Defaults to `""`. + Structure of dimension information for the convolution op. + Must be an empty string (default) or a serialized string of tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr proto. + If empty string, the default is `("NCHW", "OIHW", "NCHW")` (for a 2D convolution). + rhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For the `rhs`, only per-tensor quantization + or per-channel quantization along kernel_output_feature_dimension is supported. + Thus, this attribute must be set to -1 or `dimension_numbers.kernel_output_feature_dimension`. + Other values will raise error at OpKernel construction. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedConvolutionHybrid", name, lhs, rhs, rhs_scales, + rhs_zero_points, "Tout", Tout, "window_strides", window_strides, + "padding", padding, "explicit_padding", explicit_padding, + "lhs_dilation", lhs_dilation, "rhs_dilation", rhs_dilation, + "batch_group_count", batch_group_count, "feature_group_count", + feature_group_count, "dimension_numbers", dimension_numbers, + "rhs_quantization_axis", rhs_quantization_axis, + "rhs_quantization_min_val", rhs_quantization_min_val, + "rhs_quantization_max_val", rhs_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_convolution_hybrid_eager_fallback( + lhs, rhs, rhs_scales, rhs_zero_points, Tout=Tout, + window_strides=window_strides, padding=padding, + explicit_padding=explicit_padding, lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, batch_group_count=batch_group_count, + feature_group_count=feature_group_count, + dimension_numbers=dimension_numbers, + rhs_quantization_axis=rhs_quantization_axis, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + padding = _execute.make_str(padding, "padding") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + if window_strides is None: + window_strides = [] + if not isinstance(window_strides, (list, tuple)): + raise TypeError( + "Expected list for 'window_strides' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % window_strides) + window_strides = [_execute.make_int(_i, "window_strides") for _i in window_strides] + if explicit_padding is None: + explicit_padding = [] + if not isinstance(explicit_padding, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_padding' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % explicit_padding) + explicit_padding = [_execute.make_int(_i, "explicit_padding") for _i in explicit_padding] + if lhs_dilation is None: + lhs_dilation = [] + if not isinstance(lhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'lhs_dilation' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % lhs_dilation) + lhs_dilation = [_execute.make_int(_i, "lhs_dilation") for _i in lhs_dilation] + if rhs_dilation is None: + rhs_dilation = [] + if not isinstance(rhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'rhs_dilation' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % rhs_dilation) + rhs_dilation = [_execute.make_int(_i, "rhs_dilation") for _i in rhs_dilation] + if batch_group_count is None: + batch_group_count = 1 + batch_group_count = _execute.make_int(batch_group_count, "batch_group_count") + if feature_group_count is None: + feature_group_count = 1 + feature_group_count = _execute.make_int(feature_group_count, "feature_group_count") + if dimension_numbers is None: + dimension_numbers = "" + dimension_numbers = _execute.make_str(dimension_numbers, "dimension_numbers") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedConvolutionHybrid", lhs=lhs, rhs=rhs, + rhs_scales=rhs_scales, + rhs_zero_points=rhs_zero_points, + Tout=Tout, padding=padding, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + window_strides=window_strides, + explicit_padding=explicit_padding, + lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, + batch_group_count=batch_group_count, + feature_group_count=feature_group_count, + dimension_numbers=dimension_numbers, + rhs_quantization_axis=rhs_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tlhs", _op._get_attr_type("Tlhs"), "Trhs", + _op._get_attr_type("Trhs"), "Tout", _op._get_attr_type("Tout"), + "window_strides", _op.get_attr("window_strides"), "padding", + _op.get_attr("padding"), "explicit_padding", + _op.get_attr("explicit_padding"), "lhs_dilation", + _op.get_attr("lhs_dilation"), "rhs_dilation", + _op.get_attr("rhs_dilation"), "batch_group_count", + _op._get_attr_int("batch_group_count"), "feature_group_count", + _op._get_attr_int("feature_group_count"), "dimension_numbers", + _op.get_attr("dimension_numbers"), "rhs_quantization_axis", + _op._get_attr_int("rhs_quantization_axis"), + "rhs_quantization_min_val", + _op._get_attr_int("rhs_quantization_min_val"), + "rhs_quantization_max_val", + _op._get_attr_int("rhs_quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedConvolutionHybrid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedConvolutionHybrid = tf_export("raw_ops.UniformQuantizedConvolutionHybrid")(_ops.to_raw_op(uniform_quantized_convolution_hybrid)) + + +def uniform_quantized_convolution_hybrid_eager_fallback(lhs: Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Tlhs], rhs: Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Trhs], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedConvolutionHybrid_Tout, padding: str, rhs_quantization_min_val: int, rhs_quantization_max_val: int, window_strides, explicit_padding, lhs_dilation, rhs_dilation, batch_group_count: int, feature_group_count: int, dimension_numbers: str, rhs_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedConvolutionHybrid_Tout]: + Tout = _execute.make_type(Tout, "Tout") + padding = _execute.make_str(padding, "padding") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + if window_strides is None: + window_strides = [] + if not isinstance(window_strides, (list, tuple)): + raise TypeError( + "Expected list for 'window_strides' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % window_strides) + window_strides = [_execute.make_int(_i, "window_strides") for _i in window_strides] + if explicit_padding is None: + explicit_padding = [] + if not isinstance(explicit_padding, (list, tuple)): + raise TypeError( + "Expected list for 'explicit_padding' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % explicit_padding) + explicit_padding = [_execute.make_int(_i, "explicit_padding") for _i in explicit_padding] + if lhs_dilation is None: + lhs_dilation = [] + if not isinstance(lhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'lhs_dilation' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % lhs_dilation) + lhs_dilation = [_execute.make_int(_i, "lhs_dilation") for _i in lhs_dilation] + if rhs_dilation is None: + rhs_dilation = [] + if not isinstance(rhs_dilation, (list, tuple)): + raise TypeError( + "Expected list for 'rhs_dilation' argument to " + "'uniform_quantized_convolution_hybrid' Op, not %r." % rhs_dilation) + rhs_dilation = [_execute.make_int(_i, "rhs_dilation") for _i in rhs_dilation] + if batch_group_count is None: + batch_group_count = 1 + batch_group_count = _execute.make_int(batch_group_count, "batch_group_count") + if feature_group_count is None: + feature_group_count = 1 + feature_group_count = _execute.make_int(feature_group_count, "feature_group_count") + if dimension_numbers is None: + dimension_numbers = "" + dimension_numbers = _execute.make_str(dimension_numbers, "dimension_numbers") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + _attr_Tlhs, (lhs,) = _execute.args_to_matching_eager([lhs], ctx, [_dtypes.float32, ]) + _attr_Trhs, (rhs,) = _execute.args_to_matching_eager([rhs], ctx, [_dtypes.qint8, ]) + rhs_scales = _ops.convert_to_tensor(rhs_scales, _dtypes.float32) + rhs_zero_points = _ops.convert_to_tensor(rhs_zero_points, _dtypes.int32) + _inputs_flat = [lhs, rhs, rhs_scales, rhs_zero_points] + _attrs = ("Tlhs", _attr_Tlhs, "Trhs", _attr_Trhs, "Tout", Tout, + "window_strides", window_strides, "padding", padding, "explicit_padding", + explicit_padding, "lhs_dilation", lhs_dilation, "rhs_dilation", + rhs_dilation, "batch_group_count", batch_group_count, "feature_group_count", + feature_group_count, "dimension_numbers", dimension_numbers, + "rhs_quantization_axis", rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val) + _result = _execute.execute(b"UniformQuantizedConvolutionHybrid", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedConvolutionHybrid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedDot_Tin = TypeVar("TV_UniformQuantizedDot_Tin", bound=_atypes.QInt8) +TV_UniformQuantizedDot_Tout = TypeVar("TV_UniformQuantizedDot_Tout", bound=_atypes.QInt32) + +def uniform_quantized_dot(lhs: Annotated[Any, TV_UniformQuantizedDot_Tin], rhs: Annotated[Any, TV_UniformQuantizedDot_Tin], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedDot_Tout, lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, lhs_quantization_axis:int=-1, rhs_quantization_axis:int=-1, output_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedDot_Tout]: + r"""Perform quantized dot of quantized Tensor `lhs` and quantized Tensor `rhs` to make quantized `output`. + + Given quantized `lhs` and quantized `rhs`, performs quantized dot on `lhs` and `rhs` to make quantized `output`. + `lhs` and `rhs` must be 2D Tensors and the lhs.dim_size(1) must match rhs.dim_size(0). + `lhs` and `rhs` must be quantized Tensor, where data value is quantized using the formula: + quantized_data = clip(original_data / scale + zero_point, quantization_min_val, quantization_max_val). + `output` is also quantized, using the same formula. + If `rhs` is per-tensor quantized, `output` must be also per-tensor quantized. + + Args: + lhs: A `Tensor`. Must be one of the following types: `qint8`. + Must be a 2D Tensor of Tin. + rhs: A `Tensor`. Must have the same type as `lhs`. + Must be a 2D Tensor of Tin. + lhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale when quantizing original data that lhs represents. + Must be a scalar Tensor (lhs supports only per-tensor quantization). + lhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point when quantizing original data that lhs represents. + Same shape condition as lhs_scales. + rhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale when quantizing original data that rhs represents. + Must be a scalar Tensor (per-tensor quantization) or 1D Tensor of size (rhs.dim_size(1),) (per-channel quantization). + rhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point when quantizing original data that rhs represents. + Same shape condition as rhs_scales. + output_scales: A `Tensor` of type `float32`. + The float value(s) to use as scales when quantizing original data that output represents. + Must be a scalar Tensor (per-tensor quantization) or 1D Tensor of size (output.dim_size(1),) (per-channel quantization). + If rhs is per-tensor quantized, output must be also per-tensor quantized. + This means that if rhs_scales and rhs_zero_points are scalar Tensors, output_scales and output_zero_points must be scalar Tensors as well. + output_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point when quantizing original data that output represents. + Same shape condition as rhs_scales. + Tout: A `tf.DType` from: `tf.qint32`. The type of output Tensor. + lhs_quantization_min_val: An `int`. + The min value of the quantized data stored in lhs. + For example, if Tin is qint8, this must be set to -127 if narrow range quantized or -128 if not. + lhs_quantization_max_val: An `int`. + The max value of the quantized data stored in rhs. + For example, if Tin is qint8, this must be set to 127. + rhs_quantization_min_val: An `int`. + The min value of the quantized data stored in rhs. + For example, if Trhs is qint8, this must be set to -127 if narrow range quantized or -128 if not. + rhs_quantization_max_val: An `int`. + The max value of the quantized data stored in rhs. + For example, if Trhs is qint8, this must be set to 127. + output_quantization_min_val: An `int`. + The min value of the quantized data stored in output. + For example, if Tout is qint8, this must be set to -127 if narrow range quantized or -128 if not. + output_quantization_max_val: An `int`. + The max value of the quantized data stored in output. + For example, if Tout is qint8, this must be set to 127. + lhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For dot op lhs, only per-tensor quantization is supported. + Thus, this attribute must be set to -1. Other values are rejected. + rhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For dot op rhs, only per-tensor quantization or per-channel quantization along dimension 1 is supported. + Thus, this attribute must be set to -1 or 1. Other values are rejected. + output_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For dot op output, only per-tensor quantization or per-channel quantization along dimension 1 is supported. + Thus, this attribute must be set to -1 or 1. Other values are rejected. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedDot", name, lhs, rhs, lhs_scales, + lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, + output_zero_points, "Tout", Tout, "lhs_quantization_axis", + lhs_quantization_axis, "lhs_quantization_min_val", + lhs_quantization_min_val, "lhs_quantization_max_val", + lhs_quantization_max_val, "rhs_quantization_axis", + rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val, "output_quantization_axis", + output_quantization_axis, "output_quantization_min_val", + output_quantization_min_val, "output_quantization_max_val", + output_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_dot_eager_fallback( + lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, + output_scales, output_zero_points, Tout=Tout, + lhs_quantization_axis=lhs_quantization_axis, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_axis=rhs_quantization_axis, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_axis=output_quantization_axis, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedDot", lhs=lhs, rhs=rhs, lhs_scales=lhs_scales, + lhs_zero_points=lhs_zero_points, + rhs_scales=rhs_scales, + rhs_zero_points=rhs_zero_points, + output_scales=output_scales, + output_zero_points=output_zero_points, + Tout=Tout, + lhs_quantization_min_val=lhs_quantization_min_val, + lhs_quantization_max_val=lhs_quantization_max_val, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, + lhs_quantization_axis=lhs_quantization_axis, + rhs_quantization_axis=rhs_quantization_axis, + output_quantization_axis=output_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout"), "lhs_quantization_axis", + _op._get_attr_int("lhs_quantization_axis"), + "lhs_quantization_min_val", + _op._get_attr_int("lhs_quantization_min_val"), + "lhs_quantization_max_val", + _op._get_attr_int("lhs_quantization_max_val"), + "rhs_quantization_axis", + _op._get_attr_int("rhs_quantization_axis"), + "rhs_quantization_min_val", + _op._get_attr_int("rhs_quantization_min_val"), + "rhs_quantization_max_val", + _op._get_attr_int("rhs_quantization_max_val"), + "output_quantization_axis", + _op._get_attr_int("output_quantization_axis"), + "output_quantization_min_val", + _op._get_attr_int("output_quantization_min_val"), + "output_quantization_max_val", + _op._get_attr_int("output_quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedDot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedDot = tf_export("raw_ops.UniformQuantizedDot")(_ops.to_raw_op(uniform_quantized_dot)) + + +def uniform_quantized_dot_eager_fallback(lhs: Annotated[Any, TV_UniformQuantizedDot_Tin], rhs: Annotated[Any, TV_UniformQuantizedDot_Tin], lhs_scales: Annotated[Any, _atypes.Float32], lhs_zero_points: Annotated[Any, _atypes.Int32], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedDot_Tout, lhs_quantization_min_val: int, lhs_quantization_max_val: int, rhs_quantization_min_val: int, rhs_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, lhs_quantization_axis: int, rhs_quantization_axis: int, output_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedDot_Tout]: + Tout = _execute.make_type(Tout, "Tout") + lhs_quantization_min_val = _execute.make_int(lhs_quantization_min_val, "lhs_quantization_min_val") + lhs_quantization_max_val = _execute.make_int(lhs_quantization_max_val, "lhs_quantization_max_val") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if lhs_quantization_axis is None: + lhs_quantization_axis = -1 + lhs_quantization_axis = _execute.make_int(lhs_quantization_axis, "lhs_quantization_axis") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _attr_Tin, _inputs_Tin = _execute.args_to_matching_eager([lhs, rhs], ctx, [_dtypes.qint8, ]) + (lhs, rhs) = _inputs_Tin + lhs_scales = _ops.convert_to_tensor(lhs_scales, _dtypes.float32) + lhs_zero_points = _ops.convert_to_tensor(lhs_zero_points, _dtypes.int32) + rhs_scales = _ops.convert_to_tensor(rhs_scales, _dtypes.float32) + rhs_zero_points = _ops.convert_to_tensor(rhs_zero_points, _dtypes.int32) + output_scales = _ops.convert_to_tensor(output_scales, _dtypes.float32) + output_zero_points = _ops.convert_to_tensor(output_zero_points, _dtypes.int32) + _inputs_flat = [lhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, output_zero_points] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "lhs_quantization_axis", + lhs_quantization_axis, "lhs_quantization_min_val", lhs_quantization_min_val, + "lhs_quantization_max_val", lhs_quantization_max_val, + "rhs_quantization_axis", rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val, "output_quantization_axis", + output_quantization_axis, "output_quantization_min_val", + output_quantization_min_val, "output_quantization_max_val", + output_quantization_max_val) + _result = _execute.execute(b"UniformQuantizedDot", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedDot", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformQuantizedDotHybrid_Tlhs = TypeVar("TV_UniformQuantizedDotHybrid_Tlhs", bound=_atypes.Float32) +TV_UniformQuantizedDotHybrid_Trhs = TypeVar("TV_UniformQuantizedDotHybrid_Trhs", bound=_atypes.QInt8) +TV_UniformQuantizedDotHybrid_Tout = TypeVar("TV_UniformQuantizedDotHybrid_Tout", bound=_atypes.Float32) + +def uniform_quantized_dot_hybrid(lhs: Annotated[Any, TV_UniformQuantizedDotHybrid_Tlhs], rhs: Annotated[Any, TV_UniformQuantizedDotHybrid_Trhs], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedDotHybrid_Tout, rhs_quantization_min_val: int, rhs_quantization_max_val: int, rhs_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformQuantizedDotHybrid_Tout]: + r"""Perform hybrid quantized dot of float Tensor `lhs` and quantized Tensor `rhs`. + + Given float `lhs` and quantized `rhs`, internally performs quantization on `lhs`, and then performs quantized dot on quantized lhs and `rhs`. + The internal quantization on `lhs` is a quantization to qint8, dynamic range, per-batch (per-axis along axis 0), asymmetric, and not narrow range (the range is [-128, 127]). + `lhs` and `rhs` must be 2D Tensors and the lhs.dim_size(1) must match rhs.dim_size(0). + `rhs` must be quantized Tensor, where its data value is quantized using the formula: + quantized_data = clip(original_data / scale + zero_point, quantization_min_val, quantization_max_val). + + Args: + lhs: A `Tensor`. Must be one of the following types: `float32`. + Must be a 2D Tensor of Tlhs. + rhs: A `Tensor`. Must be one of the following types: `qint8`. + Must be a 2D Tensor of Trhs. + rhs_scales: A `Tensor` of type `float32`. + The float value(s) used as scale when quantizing original data that rhs represents. + Must be a scalar Tensor (per-tensor quantization) or 1D Tensor of size (rhs.dim_size(1),) (per-channel quantization). + rhs_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point when quantizing original data that rhs represents. + Same shape condition as rhs_scales. + Tout: A `tf.DType` from: `tf.float32`. The type of output Tensor. + rhs_quantization_min_val: An `int`. + The min value of the quantized data stored in rhs. + For example, if Trhs is qint8, this must be set to -127 if narrow range quantized or -128 if not. + rhs_quantization_max_val: An `int`. + The max value of the quantized data stored in rhs. + For example, if Trhs is qint8, this must be set to 127. + rhs_quantization_axis: An optional `int`. Defaults to `-1`. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. + For dot op rhs, only per-tensor quantization or per-channel quantization along dimension 1 is supported. + Thus, this attribute must be set to -1 or 1. Other values are rejected. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformQuantizedDotHybrid", name, lhs, rhs, rhs_scales, + rhs_zero_points, "Tout", Tout, "rhs_quantization_axis", + rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_quantized_dot_hybrid_eager_fallback( + lhs, rhs, rhs_scales, rhs_zero_points, Tout=Tout, + rhs_quantization_axis=rhs_quantization_axis, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformQuantizedDotHybrid", lhs=lhs, rhs=rhs, rhs_scales=rhs_scales, + rhs_zero_points=rhs_zero_points, + Tout=Tout, + rhs_quantization_min_val=rhs_quantization_min_val, + rhs_quantization_max_val=rhs_quantization_max_val, + rhs_quantization_axis=rhs_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tlhs", _op._get_attr_type("Tlhs"), "Trhs", + _op._get_attr_type("Trhs"), "Tout", _op._get_attr_type("Tout"), + "rhs_quantization_axis", + _op._get_attr_int("rhs_quantization_axis"), + "rhs_quantization_min_val", + _op._get_attr_int("rhs_quantization_min_val"), + "rhs_quantization_max_val", + _op._get_attr_int("rhs_quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformQuantizedDotHybrid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformQuantizedDotHybrid = tf_export("raw_ops.UniformQuantizedDotHybrid")(_ops.to_raw_op(uniform_quantized_dot_hybrid)) + + +def uniform_quantized_dot_hybrid_eager_fallback(lhs: Annotated[Any, TV_UniformQuantizedDotHybrid_Tlhs], rhs: Annotated[Any, TV_UniformQuantizedDotHybrid_Trhs], rhs_scales: Annotated[Any, _atypes.Float32], rhs_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformQuantizedDotHybrid_Tout, rhs_quantization_min_val: int, rhs_quantization_max_val: int, rhs_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformQuantizedDotHybrid_Tout]: + Tout = _execute.make_type(Tout, "Tout") + rhs_quantization_min_val = _execute.make_int(rhs_quantization_min_val, "rhs_quantization_min_val") + rhs_quantization_max_val = _execute.make_int(rhs_quantization_max_val, "rhs_quantization_max_val") + if rhs_quantization_axis is None: + rhs_quantization_axis = -1 + rhs_quantization_axis = _execute.make_int(rhs_quantization_axis, "rhs_quantization_axis") + _attr_Tlhs, (lhs,) = _execute.args_to_matching_eager([lhs], ctx, [_dtypes.float32, ]) + _attr_Trhs, (rhs,) = _execute.args_to_matching_eager([rhs], ctx, [_dtypes.qint8, ]) + rhs_scales = _ops.convert_to_tensor(rhs_scales, _dtypes.float32) + rhs_zero_points = _ops.convert_to_tensor(rhs_zero_points, _dtypes.int32) + _inputs_flat = [lhs, rhs, rhs_scales, rhs_zero_points] + _attrs = ("Tlhs", _attr_Tlhs, "Trhs", _attr_Trhs, "Tout", Tout, + "rhs_quantization_axis", rhs_quantization_axis, "rhs_quantization_min_val", + rhs_quantization_min_val, "rhs_quantization_max_val", + rhs_quantization_max_val) + _result = _execute.execute(b"UniformQuantizedDotHybrid", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformQuantizedDotHybrid", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_UniformRequantize_Tin = TypeVar("TV_UniformRequantize_Tin", _atypes.QInt32, _atypes.QInt8) +TV_UniformRequantize_Tout = TypeVar("TV_UniformRequantize_Tout", _atypes.QInt32, _atypes.QInt8) + +def uniform_requantize(input: Annotated[Any, TV_UniformRequantize_Tin], input_scales: Annotated[Any, _atypes.Float32], input_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformRequantize_Tout, input_quantization_min_val: int, input_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, input_quantization_axis:int=-1, output_quantization_axis:int=-1, name=None) -> Annotated[Any, TV_UniformRequantize_Tout]: + r"""Given quantized tensor `input`, requantize it with new quantization parameters. + + Given quantized tensor `input`, which was quantized using {input_scales, input_zero_points, input_quantization_axis, input_quantization_min_val, input_quantization_max_val}, + requantize it to a tensor, which is quantized using {output_scales, output_zero_points, output_quantization_axis, output_quantization_min_val, output_quantization_max_val}. + The requantization is done by using the formula: + output_quantized_data = clip( + (input_quantized_data - input_zero_point) * (input_scale / output_scale) + output_zero_point, + output_quantization_min_val, + output_quantization_max_val) + + Per-tensor and per-axis quantization supported cases are followings: + * per-tensor -> per-tensor + * per-tensor -> per-axis + * per-axis -> per-axis where input_quantization_axis equals output_quantization_axis. + i.e. At least one among input_quantization_axis and output_quantization_axis must be -1, or two must be equal. + + Args: + input: A `Tensor`. Must be one of the following types: `qint8`, `qint32`. + Must be a Tensor of Tin. + input_scales: A `Tensor` of type `float32`. + The float value(s) used as scale(s) when quantizing original data that `input` represents. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (input.dim_size(quantization_axis),) (per-axis quantization). + input_zero_points: A `Tensor` of type `int32`. + The int32 value(s) used as zero_point(s) when quantizing original data that `input` represents. + Same shape condition as scales. + output_scales: A `Tensor` of type `float32`. + The float value(s) to use as new scale(s) to quantize original data that `input` represents. + Must be a scalar Tensor if quantization_axis is -1 (per-tensor quantization), otherwise 1D Tensor of size (input.dim_size(quantization_axis),) (per-axis quantization). + output_zero_points: A `Tensor` of type `int32`. + The int32 value(s) to use as new zero_point(s) to quantize original data that `input` represents. + Same shape condition as scales. + Tout: A `tf.DType` from: `tf.qint8, tf.qint32`. + The type of output Tensor. A tf.DType from: tf.qint8, tf.qint32 + input_quantization_min_val: An `int`. + The quantization min value that was used when quantizing original data that `input` represents. + The purpose of this attribute is typically (but not limited to) to indicate narrow range, where this is set to: + `(Tin lowest) + 1` if narrow range, and `(Tin lowest)` otherwise. + For example, if Tin is qint8, this is set to -127 if narrow range quantized or -128 if not. + input_quantization_max_val: An `int`. + The quantization max value that was used when quantizing original data that `input` represents. + The purpose of this attribute is typically (but not limited to) indicate narrow range, where this is set to: + `(Tout max)` for both narrow range and not narrow range. + For example, if Tin is qint8, this is set to 127. + output_quantization_min_val: An `int`. + The new quantization min value to quantize original data that `input` represents. + output_quantization_max_val: An `int`. + The new quantization max value to quantize original data that `input` represents. + input_quantization_axis: An optional `int`. Defaults to `-1`. + The quantization axis that was used when quantizing original data that `input` represents. + Indicates the dimension index of the tensor where per-axis quantization is applied for the slices along that dimension. + If set to -1 (default), this indicates per-tensor quantization. Otherwise, it must be set within range [0, input.dims()). + output_quantization_axis: An optional `int`. Defaults to `-1`. + The new quantization axis to use to quantize original data that `input` represents. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `Tout`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "UniformRequantize", name, input, input_scales, + input_zero_points, output_scales, output_zero_points, "Tout", Tout, + "input_quantization_axis", input_quantization_axis, + "input_quantization_min_val", input_quantization_min_val, + "input_quantization_max_val", input_quantization_max_val, + "output_quantization_axis", output_quantization_axis, + "output_quantization_min_val", output_quantization_min_val, + "output_quantization_max_val", output_quantization_max_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return uniform_requantize_eager_fallback( + input, input_scales, input_zero_points, output_scales, + output_zero_points, Tout=Tout, + input_quantization_axis=input_quantization_axis, + input_quantization_min_val=input_quantization_min_val, + input_quantization_max_val=input_quantization_max_val, + output_quantization_axis=output_quantization_axis, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, name=name, + ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + Tout = _execute.make_type(Tout, "Tout") + input_quantization_min_val = _execute.make_int(input_quantization_min_val, "input_quantization_min_val") + input_quantization_max_val = _execute.make_int(input_quantization_max_val, "input_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if input_quantization_axis is None: + input_quantization_axis = -1 + input_quantization_axis = _execute.make_int(input_quantization_axis, "input_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "UniformRequantize", input=input, input_scales=input_scales, + input_zero_points=input_zero_points, + output_scales=output_scales, + output_zero_points=output_zero_points, Tout=Tout, + input_quantization_min_val=input_quantization_min_val, + input_quantization_max_val=input_quantization_max_val, + output_quantization_min_val=output_quantization_min_val, + output_quantization_max_val=output_quantization_max_val, + input_quantization_axis=input_quantization_axis, + output_quantization_axis=output_quantization_axis, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("Tin", _op._get_attr_type("Tin"), "Tout", + _op._get_attr_type("Tout"), "input_quantization_axis", + _op._get_attr_int("input_quantization_axis"), + "input_quantization_min_val", + _op._get_attr_int("input_quantization_min_val"), + "input_quantization_max_val", + _op._get_attr_int("input_quantization_max_val"), + "output_quantization_axis", + _op._get_attr_int("output_quantization_axis"), + "output_quantization_min_val", + _op._get_attr_int("output_quantization_min_val"), + "output_quantization_max_val", + _op._get_attr_int("output_quantization_max_val")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "UniformRequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +UniformRequantize = tf_export("raw_ops.UniformRequantize")(_ops.to_raw_op(uniform_requantize)) + + +def uniform_requantize_eager_fallback(input: Annotated[Any, TV_UniformRequantize_Tin], input_scales: Annotated[Any, _atypes.Float32], input_zero_points: Annotated[Any, _atypes.Int32], output_scales: Annotated[Any, _atypes.Float32], output_zero_points: Annotated[Any, _atypes.Int32], Tout: TV_UniformRequantize_Tout, input_quantization_min_val: int, input_quantization_max_val: int, output_quantization_min_val: int, output_quantization_max_val: int, input_quantization_axis: int, output_quantization_axis: int, name, ctx) -> Annotated[Any, TV_UniformRequantize_Tout]: + Tout = _execute.make_type(Tout, "Tout") + input_quantization_min_val = _execute.make_int(input_quantization_min_val, "input_quantization_min_val") + input_quantization_max_val = _execute.make_int(input_quantization_max_val, "input_quantization_max_val") + output_quantization_min_val = _execute.make_int(output_quantization_min_val, "output_quantization_min_val") + output_quantization_max_val = _execute.make_int(output_quantization_max_val, "output_quantization_max_val") + if input_quantization_axis is None: + input_quantization_axis = -1 + input_quantization_axis = _execute.make_int(input_quantization_axis, "input_quantization_axis") + if output_quantization_axis is None: + output_quantization_axis = -1 + output_quantization_axis = _execute.make_int(output_quantization_axis, "output_quantization_axis") + _attr_Tin, (input,) = _execute.args_to_matching_eager([input], ctx, [_dtypes.qint8, _dtypes.qint32, ]) + input_scales = _ops.convert_to_tensor(input_scales, _dtypes.float32) + input_zero_points = _ops.convert_to_tensor(input_zero_points, _dtypes.int32) + output_scales = _ops.convert_to_tensor(output_scales, _dtypes.float32) + output_zero_points = _ops.convert_to_tensor(output_zero_points, _dtypes.int32) + _inputs_flat = [input, input_scales, input_zero_points, output_scales, output_zero_points] + _attrs = ("Tin", _attr_Tin, "Tout", Tout, "input_quantization_axis", + input_quantization_axis, "input_quantization_min_val", + input_quantization_min_val, "input_quantization_max_val", + input_quantization_max_val, "output_quantization_axis", + output_quantization_axis, "output_quantization_min_val", + output_quantization_min_val, "output_quantization_max_val", + output_quantization_max_val) + _result = _execute.execute(b"UniformRequantize", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "UniformRequantize", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed4aee3d47c6baee731f961c97f81252a7c9491 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker.py @@ -0,0 +1,393 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Gradient checker for any ops, graphs. + +The gradient checker verifies numerically that an op/graph properly +computes the gradients +""" +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +def _product(t): + if isinstance(t, int): + return t + else: + y = 1 + for x in t: + y *= x + return y + + +def _extra_feeds(extra_feed_dict, new_feeds): + if not extra_feed_dict: + return new_feeds + r = {} + r.update(extra_feed_dict) + r.update(new_feeds) + return r + + +def _compute_theoretical_jacobian(x, x_shape, x_data, dy, dy_shape, dx, + extra_feed_dict): + """Computes the theoretical Jacobian for dy/dx. + + Computes the theoretical Jacobian using the ops generated by + compute_gradient(). + + Args: + x: the tensor "x". + x_shape: the dimensions of x as a tuple or an array of ints. + x_data: a numpy parray as the input data for x + dy: the tensor "dy". + dy_shape: the dimensions of dy as a tuple or an array of ints. + dx: Tensor or IndexedSlices representing dx + extra_feed_dict: dict that allows fixing specified tensor values + during the jacobian calculation. + + Returns: + A 2-d numpy array representing the Jacobian for dy/dx. It has "x_size" rows + and "dy_size" columns where "x_size" is the number of elements in x and + "dy_size" is the number of elements in dy. + + Raises: + ValueError: If `dy` is empty but the gradient is nonzero. + """ + # Complex vectors are treated as vectors of twice as many reals. + if x.dtype.is_complex: + x_shape = tuple(x_shape) + (2,) + dy_factor = 2 if dy.dtype.is_complex else 1 + + # To compute the jacobian, we treat x and y as one-dimensional vectors. + x_size = _product(x_shape) + x_val_size = _product(x_shape[1:]) # This is used for sparse gradients + dy_size = _product(dy_shape) * dy_factor + + # Allocate 2-D Jacobian, with x dimensions smashed into the first + # dimension and y dimensions smashed into the second. + jacobian = np.zeros((x_size, dy_size), + dtype=x.dtype.real_dtype.as_numpy_dtype) + + # For each of the entry of dy, we set this to be 1 and + # everything else to be 0 and compute the backprop -- this will give us one + # one column of the Jacobian matrix. + dy_data = np.zeros(dy_shape, dtype=dy.dtype.as_numpy_dtype) + dy_data_flat = dy_data.ravel().view(dy.dtype.real_dtype.as_numpy_dtype) + sess = ops.get_default_session() + for col in range(dy_size): + dy_data_flat[col] = 1 + if isinstance(dx, indexed_slices.IndexedSlices): + backprop_indices, backprop_values = sess.run( + [dx.indices, dx.values], + feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) + for i, v in zip(backprop_indices, backprop_values): + r_begin = i * x_val_size + r_end = r_begin + x_val_size + jacobian[r_begin:r_end, col] += v.flat + else: + assert isinstance(dx, tensor.Tensor), "dx = " + str(dx) + backprop = sess.run( + dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) + jacobian[:, col] = backprop.ravel().view(jacobian.dtype) + dy_data_flat[col] = 0 + + # If the output is empty, run the gradients at least once and make sure + # they produce zeros. + if not dy_size: + backprop = sess.run( + dx, feed_dict=_extra_feeds(extra_feed_dict, {x: x_data, dy: dy_data})) + if backprop.shape != x_data.shape: + raise ValueError("Empty gradient has wrong shape: expected %s, got %s" % + (x_data.shape, backprop.shape)) + if np.any(backprop): + raise ValueError("Empty tensor with nonzero gradients") + + logging.vlog(1, "Theoretical Jacobian =\n%s", jacobian) + return jacobian + + +def _compute_numeric_jacobian(x, x_shape, x_data, y, y_shape, delta, + extra_feed_dict): + """Computes the numeric Jacobian for dy/dx. + + Computes the numeric Jacobian by slightly perturbing the inputs and + measuring the differences on the output. + + Args: + x: the tensor "x". + x_shape: the dimensions of x as a tuple or an array of ints. + x_data: a numpy array as the input data for x + y: the tensor "y". + y_shape: the dimensions of y as a tuple or an array of ints. + delta: the amount of perturbation we give to the input + extra_feed_dict: dict that allows fixing specified tensor values + during the jacobian calculation. + + Returns: + A 2-d numpy array representing the Jacobian for dy/dx. It has "x_size" rows + and "y_size" columns where "x_size" is the number of elements in x and + "y_size" is the number of elements in y. + """ + # bfloat16 doesn't have enough bits to represent high precision numbers such + # as delta. Convert to float32 here. Since numeric_jacobian is expected to + # be the groundtruth to compare against, it shouldn't lose any information. + if x.dtype == dtypes.bfloat16: + x = math_ops.cast(x, dtypes.float32) # TODO(wangpeng): Now that the new x + # is an output of the old x, isn't feeding to the new x a mistake? + if y.dtype == dtypes.bfloat16: + y = math_ops.cast(y, dtypes.float32) + if x_data.dtype == dtypes.bfloat16.as_numpy_dtype: + x_data = x_data.astype(np.float32) + + # To compute the jacobian, we treat x and y as one-dimensional vectors + x_size = _product(x_shape) * (2 if x.dtype.is_complex else 1) + y_size = _product(y_shape) * (2 if y.dtype.is_complex else 1) + x_dtype = x.dtype.real_dtype.as_numpy_dtype + y_dtype = y.dtype.real_dtype.as_numpy_dtype + + # Make sure we have the right types + x_data = np.asarray(x_data, dtype=x.dtype.as_numpy_dtype) + scale = np.asarray(2 * delta, dtype=y_dtype)[()] + + jacobian = np.zeros((x_size, y_size), dtype=x_dtype) + # For each of the entry of x, we slightly perturbs this by adding and + # subtracting a delta and then compute difference between the outputs. This + # will give us one row of the Jacobian matrix. + for row in range(x_size): + x_pos = x_data.copy() + x_neg = x_data.copy() + x_pos.ravel().view(x_dtype)[row] += delta + y_pos = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_pos})) + x_neg.ravel().view(x_dtype)[row] -= delta + y_neg = y.eval(feed_dict=_extra_feeds(extra_feed_dict, {x: x_neg})) + diff = (y_pos - y_neg) / scale + jacobian[row, :] = diff.ravel().view(y_dtype) + + logging.vlog(1, "Numeric Jacobian =\n%s", jacobian) + return jacobian + + +def _compute_dx_and_dy(x, y, y_shape): + """Returns a node to compute gradient of y wrt x.""" + # We make up a dy so that we can compute the gradients. We don't really use + # the value of dy -- we will always feed it. We need to add an identity node + # so that we can always feed it properly. Otherwise, for the Add operation, + # dx is the same as dy and we cannot fetch the tensor that we are feeding. + with x.graph.as_default(): + dy_orig = constant_op.constant(1.0, shape=y_shape, dtype=y.dtype) + dy = array_ops.identity(dy_orig) + # We compute the gradients for y wrt. x + grads = gradients.gradients(y, x, dy) + assert len(grads) == 1 + return grads[0], dy_orig + + +def _compute_gradient(x, + x_shape, + dx, + y, + y_shape, + dy, + x_init_value=None, + delta=1e-3, + extra_feed_dict=None): + """Computes the theoretical and numerical jacobian.""" + t = dtypes.as_dtype(x.dtype) + allowed_types = [dtypes.float16, dtypes.bfloat16, dtypes.float32, + dtypes.float64, dtypes.complex64, dtypes.complex128] + assert t.base_dtype in allowed_types, "Don't support type %s for x" % t.name + t2 = dtypes.as_dtype(y.dtype) + assert t2.base_dtype in allowed_types, "Don't support type %s for y" % t2.name + + if x_init_value is not None: + i_shape = list(x_init_value.shape) + assert(list(x_shape) == i_shape), "x_shape = %s, init_data shape = %s" % ( + x_shape, i_shape) + x_data = x_init_value + else: + x_data = np.random.random_sample(x_shape).astype(t.as_numpy_dtype) + if t.is_complex: + x_data.imag = np.random.random_sample(x_shape) + + jacob_t = _compute_theoretical_jacobian( + x, x_shape, x_data, dy, y_shape, dx, extra_feed_dict=extra_feed_dict) + jacob_n = _compute_numeric_jacobian( + x, x_shape, x_data, y, y_shape, delta, extra_feed_dict=extra_feed_dict) + return jacob_t, jacob_n + + +def _compute_gradient_list(x, + x_shape, + y, + y_shape, + x_init_value=None, + delta=1e-3, + init_targets=None, + extra_feed_dict=None): + """Compute gradients for a list of x values.""" + assert isinstance(x, list) + dx, dy = zip(*[_compute_dx_and_dy(xi, y, y_shape) for xi in x]) + + if init_targets is not None: + assert isinstance(init_targets, (list, tuple)) + for init in init_targets: + init.run() + if x_init_value is None: + x_init_value = [None] * len(x) + # pylint: disable=g-complex-comprehension + ret = [_compute_gradient(xi, x_shapei, dxi, y, y_shape, dyi, x_init_valuei, + delta, extra_feed_dict=extra_feed_dict) + for xi, x_shapei, dxi, dyi, x_init_valuei in zip(x, x_shape, dx, dy, + x_init_value)] + return ret + + +@tf_export(v1=["test.compute_gradient"]) +@deprecation.deprecated( + date=None, + instructions="Use tf.test.compute_gradient in 2.0, which has better " + "support for functions. Note that the two versions have different usage, " + "so code change is needed.") +def compute_gradient(x, + x_shape, + y, + y_shape, + x_init_value=None, + delta=1e-3, + init_targets=None, + extra_feed_dict=None): + """Computes and returns the theoretical and numerical Jacobian. + + If `x` or `y` is complex, the Jacobian will still be real but the + corresponding Jacobian dimension(s) will be twice as large. This is required + even if both input and output is complex since TensorFlow graphs are not + necessarily holomorphic, and may have gradients not expressible as complex + numbers. For example, if `x` is complex with shape `[m]` and `y` is complex + with shape `[n]`, each Jacobian `J` will have shape `[m * 2, n * 2]` with + + J[:m, :n] = d(Re y)/d(Re x) + J[:m, n:] = d(Im y)/d(Re x) + J[m:, :n] = d(Re y)/d(Im x) + J[m:, n:] = d(Im y)/d(Im x) + + Args: + x: a tensor or list of tensors + x_shape: the dimensions of x as a tuple or an array of ints. If x is a list, + then this is the list of shapes. + y: a tensor + y_shape: the dimensions of y as a tuple or an array of ints. + x_init_value: (optional) a numpy array of the same shape as "x" + representing the initial value of x. If x is a list, this should be a list + of numpy arrays. If this is none, the function will pick a random tensor + as the initial value. + delta: (optional) the amount of perturbation. + init_targets: list of targets to run to initialize model params. + extra_feed_dict: dict that allows fixing specified tensor values + during the Jacobian calculation. + + Returns: + Two 2-d numpy arrays representing the theoretical and numerical + Jacobian for dy/dx. Each has "x_size" rows and "y_size" columns + where "x_size" is the number of elements in x and "y_size" is the + number of elements in y. If x is a list, returns a list of two numpy arrays. + """ + # TODO(mrry): remove argument `init_targets` + if extra_feed_dict is None: + extra_feed_dict = {} + + if isinstance(x, list): + return _compute_gradient_list(x, x_shape, y, y_shape, x_init_value, delta, + init_targets, extra_feed_dict=extra_feed_dict) + else: + if init_targets is not None: + assert isinstance(init_targets, (list, tuple)) + for init in init_targets: + init.run() + dx, dy = _compute_dx_and_dy(x, y, y_shape) + ret = _compute_gradient(x, x_shape, dx, y, y_shape, dy, x_init_value, delta, + extra_feed_dict=extra_feed_dict) + return ret + + +def _compute_error(grad): + if isinstance(grad, tuple): + grad = [grad] + error = 0 + for j_t, j_n in grad: + if j_t.size or j_n.size: # Handle zero size tensors correctly + error = np.maximum(error, np.fabs(j_t - j_n).max()) + return error + + +@tf_export(v1=["test.compute_gradient_error"]) +@deprecation.deprecated( + date=None, + instructions="Use tf.test.compute_gradient in 2.0, which has better " + "support for functions. Note that the two versions have different usage, " + "so code change is needed.") +def compute_gradient_error(x, + x_shape, + y, + y_shape, + x_init_value=None, + delta=1e-3, + init_targets=None, + extra_feed_dict=None): + """Computes the gradient error. + + Computes the maximum error for dy/dx between the computed Jacobian and the + numerically estimated Jacobian. + + This function will modify the tensors passed in as it adds more operations + and hence changing the consumers of the operations of the input tensors. + + This function adds operations to the current session. To compute the error + using a particular device, such as a GPU, use the standard methods for + setting a device (e.g. using with sess.graph.device() or setting a device + function in the session constructor). + + Args: + x: a tensor or list of tensors + x_shape: the dimensions of x as a tuple or an array of ints. If x is a list, + then this is the list of shapes. + y: a tensor + y_shape: the dimensions of y as a tuple or an array of ints. + x_init_value: (optional) a numpy array of the same shape as "x" + representing the initial value of x. If x is a list, this should be a list + of numpy arrays. If this is none, the function will pick a random tensor + as the initial value. + delta: (optional) the amount of perturbation. + init_targets: list of targets to run to initialize model params. + extra_feed_dict: dict that allows fixing specified tensor values + during the Jacobian calculation. + + Returns: + The maximum error in between the two Jacobians. + """ + grad = compute_gradient(x, x_shape, y, y_shape, x_init_value, delta, + init_targets, extra_feed_dict=extra_feed_dict) + return _compute_error(grad) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..85f9f2f5cea46887df593033ab53b2b647ee5631 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradient_checker_v2.py @@ -0,0 +1,364 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradient checker for functions. + +The gradient checker verifies numerically that an function properly +computes the gradients +""" +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients_impl # pylint: disable=unused-import +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.tf_export import tf_export + + +def _product(t): + if isinstance(t, int): + return t + else: + y = 1 + for x in t: + y *= x + return y + + +def _eval_indexed_slices(a): + """Converts IndexedSlices to IndexedSlicesValue with numpy indices/values. + + When eager execution is enabled, converts IndexedSlices + to IndexedSlicesValue with numpy indices/values. + + Args: + a: any value. + + Returns: + If a is IndexedSlices and eager execution is enabled, calls numpy() on a's + fields. Otherwise returns a unchanged. + """ + if (isinstance(a, indexed_slices.IndexedSlices) and + context.executing_eagerly()): + return indexed_slices.IndexedSlicesValue( + indices=[x.numpy() for x in a.indices], + values=[x.numpy() for x in a.values], + dense_shape=a.dense_shape) + return a + + +def _to_numpy(a): + """Converts Tensors, EagerTensors, and IndexedSlicesValue to numpy arrays. + + Args: + a: any value. + + Returns: + If a is EagerTensor or Tensor, returns the evaluation of a by calling + numpy() or run(). If a is IndexedSlicesValue, constructs the corresponding + dense numpy array. Otherwise returns a unchanged. + """ + if isinstance(a, ops.EagerTensor): + return a.numpy() + if isinstance(a, tensor.Tensor): + sess = ops.get_default_session() + return sess.run(a) + if isinstance(a, indexed_slices.IndexedSlicesValue): + arr = np.zeros(a.dense_shape) + assert len(a.values) == len(a.indices), ( + "IndexedSlicesValue has %s value slices but %s indices\n%s" % + (a.values, a.indices, a)) + for values_slice, index in zip(a.values, a.indices): + assert 0 <= index < len(arr), ( + "IndexedSlicesValue has invalid index %s\n%s" % (index, a)) + arr[index] += values_slice + return arr + return a + + +def _prepare(f, xs_dtypes, xs_shapes): + """Return a function that executes 'f'. + + In TF 2.x, this is the same as `f`. + In TF 1.x, returns a Python function that executes the graph defined by `f` + in a Session. + + Args: + f: the function. + xs_dtypes: dtypes of f's arguments. + xs_shapes: shapes of f's arguments. + + Returns: + """ + if context.executing_eagerly(): + + def decorated_eager(*xs_data): + return f(*map(ops.convert_to_tensor, xs_data)) + + return decorated_eager + xs = [ + array_ops.placeholder(x_dtype, shape=x_shape) + for x_dtype, x_shape in zip(xs_dtypes, xs_shapes) + ] + y = f(*xs) + sess = ops.get_default_session() + + def decorated_graph(*xs_data): + xs_data = [_to_numpy(a) for a in xs_data] + return sess.run(y, feed_dict=dict(zip(xs, xs_data))) + + return decorated_graph + + +def _compute_theoretical_jacobian(f, y_shape, y_dtype, xs, param): + """Computes the theoretical Jacobian for f regarding xs[param]. + + One can think of the relation among f, xs and y as y = f(xs). + + Args: + f: the function. + y_shape: the shape of the result. + y_dtype: the dtype of the result. + xs: a list of tensors. + param: the index of the target parameter. + + Returns: + A 2-d numpy array representing the Jacobian. It has "y_size" rows + and "x_size" columns where "x_size" is the number of elements in xs[param] + and "y_size" is the number of elements in the result. + + Raises: + ValueError: If result is empty but the gradient is nonzero. + """ + x = xs[param] + # Complex vectors are treated as vectors of twice as many reals. + x_shape = tuple(x.shape) + (2,) if x.dtype.is_complex else x.shape + y_factor = 2 if y_dtype.is_complex else 1 + + # To compute the jacobian, we treat x and y as one-dimensional vectors. + x_size = _product(x_shape) + x_val_size = _product(x_shape[1:]) # This is used for sparse gradients + y_size = _product(y_shape) * y_factor + + # Allocate 2-D Jacobian, with y dimensions smashed into the first + # dimension and x dimensions smashed into the second. + jacobian = np.zeros((y_size, x_size), dtype=x.dtype.real_dtype.as_numpy_dtype) + + # For each of the entry of dy, we set this to be 1 and + # everything else to be 0 and compute the gradients -- this will give us one + # row of the Jacobian matrix. + dy_data = np.zeros(y_shape, dtype=y_dtype.as_numpy_dtype) + dy_data_flat = dy_data.ravel().view(y_dtype.real_dtype.as_numpy_dtype) + grad_fn_unprep = backprop.gradients_function(f, [param]) + grad_fn = _prepare(lambda dy, *xs: grad_fn_unprep(*xs, dy=dy), + [y_dtype] + [z.dtype for z in xs], + [None] + [z.shape for z in xs]) + for row in range(y_size): + dy_data_flat[row] = 1 + grad = _to_numpy(grad_fn(dy_data, *xs)[0]) + grad = _eval_indexed_slices(grad) + if isinstance(grad, indexed_slices.IndexedSlicesValue): + for i, v in zip(grad.indices, grad.values): + c_begin = i * x_val_size + c_end = c_begin + x_val_size + jacobian[row, c_begin:c_end] += v.flat + elif grad is not None: + jacobian[row, :] = grad.ravel().view(jacobian.dtype) + # This reset of `dy_data_flat` needs to happen after `grad` is copied to + # `jacobian` because `grad` and `dy_data_flat` may share memory. + dy_data_flat[row] = 0 + + # If the output is empty, run the gradients at least once and make sure + # they produce zeros. + if y_size == 0: # don't use 'not y_size', because y_size may not be an int + grad = _to_numpy(grad_fn(dy_data, *xs)[0]) + if grad.shape != x.shape: + raise ValueError("Empty gradient has wrong shape: expected %s, got %s" % + (x.shape, grad.shape)) + if np.any(grad): + raise ValueError("Empty tensor with nonzero gradients") + + logging.vlog(1, "Theoretical Jacobian =\n%s", jacobian) + return jacobian + + +def _compute_numeric_jacobian(f, y_size, y_dtype, xs, param, delta): + """Computes the numeric Jacobian for f regarding xs[param]. + + One can think of the relation among f, xs and y as y = f(xs). + + Args: + f: the function. + y_size: the number of elements of the result. + y_dtype: the dtype of the result. + xs: a list of tensors. + param: the index of the target parameter. + delta: the amount of perturbation we give to the input. + + Returns: + A 2-d numpy array representing the Jacobian. It has "y_size" rows + and "x_size" columns where "x_size" is the number of elements in xs[param] + and "y_size" is the number of elements in the result. + """ + x_shape = xs[param].shape + x_dtype = xs[param].dtype + + # To compute the jacobian, we treat x and y as one-dimensional vectors + x_size = _product(x_shape) * (2 if x_dtype.is_complex else 1) + y_size = y_size * (2 if y_dtype.is_complex else 1) + x_dtype = x_dtype.real_dtype.as_numpy_dtype + y_dtype = y_dtype.real_dtype.as_numpy_dtype + + xs_dtypes = [x.dtype for x in xs] + xs_shapes = [x.shape for x in xs] + # Converts xs to numpy arrays to do in-place perturbation. + # Calls asarray() to avoid copying in ravel() later. + xs = [np.asarray(_to_numpy(x)) for x in xs] + x = xs[param] + + # Make sure we have the right types + scale = np.asarray(2 * delta, dtype=y_dtype)[()] + + jacobian = np.zeros((y_size, x_size), dtype=x_dtype) + + # For each of the entry of x, we slightly perturbs this by adding and + # subtracting a delta and then compute difference between the outputs. This + # will give us one column of the Jacobian matrix. + f = _prepare(f, xs_dtypes, xs_shapes) + for col in range(x_size): + original = x.ravel().view(x_dtype)[col] + x.ravel().view(x_dtype)[col] += delta + y_pos = _to_numpy(f(*xs)) + x.ravel().view(x_dtype)[col] = original + x.ravel().view(x_dtype)[col] -= delta + y_neg = _to_numpy(f(*xs)) + x.ravel().view(x_dtype)[col] = original + diff = (y_pos - y_neg) / scale + jacobian[:, col] = diff.ravel().view(y_dtype) + + logging.vlog(1, "Numeric Jacobian =\n%s", jacobian) + return jacobian + + +def _compute_gradient(f, y_shape, y_dtype, xs, param, delta): + """Computes the theoretical and numerical jacobian.""" + x = xs[param] + t = x.dtype + allowed_types = [ + dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, + dtypes.complex64, dtypes.complex128 + ] + assert t.base_dtype in allowed_types, ("Cannot compute gradient for " + "unsupported type %s of argument %s" % + (t.name, param)) + t2 = y_dtype + assert t2.base_dtype in allowed_types, ("Cannot compute gradient for " + "unsupported type %s of y" % t2.name) + y_size = _product(y_shape) + jacob_t = _compute_theoretical_jacobian(f, y_shape, y_dtype, xs, param) + jacob_n = _compute_numeric_jacobian(f, y_size, y_dtype, xs, param, delta) + return jacob_t, jacob_n + + +def _compute_gradient_list(f, xs, delta): + """Compute gradients for a list of x values.""" + # convert xs to tensors so that dtype and shape have uniform types + xs = [ops.convert_to_tensor(x) for x in xs] + # run the function to get info of the result + xs_dtypes = [x.dtype for x in xs] + xs_shapes = [x.shape for x in xs] + f_temp = _prepare(f, xs_dtypes, xs_shapes) + y = f_temp(*xs) + return tuple( + zip(*[ + _compute_gradient(f, y.shape, dtypes.as_dtype(y.dtype), xs, i, delta) + for i in range(len(xs)) + ])) + + +@tf_export("test.compute_gradient", v1=[]) +def compute_gradient(f, x, delta=None): + """Computes the theoretical and numeric Jacobian of `f`. + + With y = f(x), computes the theoretical and numeric Jacobian dy/dx. + + Args: + f: the function. + x: the arguments for the function as a list or tuple of values convertible + to a Tensor. + delta: (optional) perturbation used to compute numeric Jacobian. + + Returns: + A pair of lists, where the first is a list of 2-d numpy arrays representing + the theoretical Jacobians for each argument, and the second list is the + numerical ones. Each 2-d array has "y_size" rows + and "x_size" columns where "x_size" is the number of elements in the + corresponding argument and "y_size" is the number of elements in f(x). + + Raises: + ValueError: If result is empty but the gradient is nonzero. + ValueError: If x is not list, but any other type. + + Example: + + >>> @tf.function + ... def test_func(x): + ... return x*x + ... + >>> + >>> class MyTest(tf.test.TestCase): + ... + ... def test_gradient_of_test_func(self): + ... theoretical, numerical = tf.test.compute_gradient(test_func, [1.0]) + ... # ((array([[2.]], dtype=float32),), + ... # (array([[2.000004]], dtype=float32),)) + ... self.assertAllClose(theoretical, numerical) + + """ + if not isinstance(x, (list, tuple)): + raise ValueError( + "`x` must be a list or tuple of values convertible to a Tensor " + "(arguments to `f`), not a %s" % type(x)) + if delta is None: + # By default, we use a step size for the central finite difference + # approximation that is exactly representable as a binary floating + # point number, since this reduces the amount of noise due to rounding + # in the approximation of some functions. + delta = 1.0 / 1024 + return _compute_gradient_list(f, x, delta) + + +def max_error(grad1, grad2): + """Computes maximum elementwise gap. + + Computes the maximum elementwise gap between two lists of tensors of the same + shape. + + Args: + grad1: a lists of tensors. + grad2: a lists of tensors with the same shape as grad1. + + Returns: + The maximum elementwise gap between the two. + """ + error = 0 + for j_t, j_n in zip(grad1, grad2): + if j_t.size or j_n.size: # Handle zero size tensors correctly + error = np.maximum(error, np.fabs(j_t - j_n).max()) + return error diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..be98d631f8b6fe497203850217f22682319b577a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients.py @@ -0,0 +1,26 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implements the graph generation for computation of gradients.""" + +# pylint: disable=unused-import +from tensorflow.python.eager import function +from tensorflow.python.eager.backprop import GradientTape +from tensorflow.python.eager.forwardprop import ForwardAccumulator +from tensorflow.python.ops.custom_gradient import custom_gradient +from tensorflow.python.ops.gradients_util import AggregationMethod +from tensorflow.python.ops.gradients_impl import gradients +from tensorflow.python.ops.gradients_impl import hessians +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d2e7742354745345ea776e728cb1ebcc202022 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_impl.py @@ -0,0 +1,487 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implements the graph generation for computation of gradients.""" + +from tensorflow.compiler.jit.ops import xla_ops_grad # pylint: disable=unused-import +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_grad # pylint: disable=unused-import +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops # pylint: disable=unused-import +from tensorflow.python.ops import control_flow_grad # pylint: disable=unused-import +from tensorflow.python.ops import cudnn_rnn_grad # pylint: disable=unused-import +from tensorflow.python.ops import gradients_util +from tensorflow.python.ops import image_grad # pylint: disable=unused-import +from tensorflow.python.ops import linalg_grad # pylint: disable=unused-import +from tensorflow.python.ops import linalg_ops # pylint: disable=unused-import +from tensorflow.python.ops import logging_ops # pylint: disable=unused-import +from tensorflow.python.ops import manip_grad # pylint: disable=unused-import +from tensorflow.python.ops import math_grad # pylint: disable=unused-import +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nccl_ops # pylint: disable=unused-import +from tensorflow.python.ops import optional_grad # pylint: disable=unused-import +from tensorflow.python.ops import proto_ops # pylint: disable=unused-import +from tensorflow.python.ops import random_grad # pylint: disable=unused-import +from tensorflow.python.ops import rnn_grad # pylint: disable=unused-import +from tensorflow.python.ops import sdca_ops # pylint: disable=unused-import +from tensorflow.python.ops import sets # pylint: disable=unused-import +from tensorflow.python.ops import sparse_grad # pylint: disable=unused-import +from tensorflow.python.ops import tensor_array_grad # pylint: disable=unused-import +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_grad # pylint: disable=unused-import +from tensorflow.python.ops.signal import fft_ops # pylint: disable=unused-import +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.training import checkpoint_ops # pylint: disable=unused-import +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["gradients"]) +def gradients(ys, + xs, + grad_ys=None, + name="gradients", + colocate_gradients_with_ops=False, + gate_gradients=False, + aggregation_method=None, + stop_gradients=None, + unconnected_gradients=UnconnectedGradients.NONE): + """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. + + `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` + is a list of `Tensor`, holding the gradients received by the + `ys`. The list must be the same length as `ys`. + + `gradients()` adds ops to the graph to output the derivatives of `ys` with + respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where + each tensor is the `sum(dy/dx)` for y in `ys` and for x in `xs`. + + `grad_ys` is a list of tensors of the same length as `ys` that holds + the initial gradients for each y in `ys`. When `grad_ys` is None, + we fill in a tensor of '1's of the shape of y for each y in `ys`. A + user can provide their own initial `grad_ys` to compute the + derivatives using a different initial gradient for each y (e.g., if + one wanted to weight the gradient differently for each value in + each y). + + `stop_gradients` is a `Tensor` or a list of tensors to be considered constant + with respect to all `xs`. These tensors will not be backpropagated through, + as though they had been explicitly disconnected using `stop_gradient`. Among + other things, this allows computation of partial derivatives as opposed to + total derivatives. For example: + + ```python + a = tf.constant(0.) + b = 2 * a + g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) + ``` + + Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the + total derivatives `tf.gradients(a + b, [a, b])`, which take into account the + influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is + equivalent to: + + ```python + a = tf.stop_gradient(tf.constant(0.)) + b = tf.stop_gradient(2 * a) + g = tf.gradients(a + b, [a, b]) + ``` + + `stop_gradients` provides a way of stopping gradient after the graph has + already been constructed, as compared to `tf.stop_gradient` which is used + during graph construction. When the two approaches are combined, + backpropagation stops at both `tf.stop_gradient` nodes and nodes in + `stop_gradients`, whichever is encountered first. + + All integer tensors are considered constant with respect to all `xs`, as if + they were included in `stop_gradients`. + + `unconnected_gradients` determines the value returned for each x in xs if it + is unconnected in the graph to ys. By default this is None to safeguard + against errors. Mathematically these gradients are zero which can be requested + using the `'zero'` option. `tf.UnconnectedGradients` provides the + following options and behaviors: + + ```python + a = tf.ones([1, 2]) + b = tf.ones([3, 1]) + g1 = tf.gradients([b], [a], unconnected_gradients='none') + sess.run(g1) # [None] + + g2 = tf.gradients([b], [a], unconnected_gradients='zero') + sess.run(g2) # [array([[0., 0.]], dtype=float32)] + ``` + + Let us take one practical example which comes during the back propogation + phase. This function is used to evaluate the derivatives of the cost function + with respect to Weights `Ws` and Biases `bs`. Below sample implementation + provides the exaplantion of what it is actually used for : + + ```python + Ws = tf.constant(0.) + bs = 2 * Ws + cost = Ws + bs # This is just an example. So, please ignore the formulas. + g = tf.gradients(cost, [Ws, bs]) + dCost_dW, dCost_db = g + ``` + + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + grad_ys: Optional. A `Tensor` or list of tensors the same size as + `ys` and holding the gradients computed for each y in `ys`. + name: Optional name to use for grouping all the gradient ops together. + defaults to 'gradients'. + colocate_gradients_with_ops: If True, try colocating gradients with + the corresponding op. + gate_gradients: If True, add a tuple around the gradients returned + for an operations. This avoids some race conditions. + aggregation_method: Specifies the method used to combine gradient terms. + Accepted values are constants defined in the class `AggregationMethod`. + stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate + through. + unconnected_gradients: Optional. Specifies the gradient value returned when + the given input tensors are unconnected. Accepted values are constants + defined in the class `tf.UnconnectedGradients` and the default value is + `none`. + + Returns: + A list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` + for y in `ys` and for x in `xs`. + + Raises: + LookupError: if one of the operations between `x` and `y` does not + have a registered gradient function. + ValueError: if the arguments are invalid. + RuntimeError: if called in Eager mode. + + """ + # Creating the gradient graph for control flow mutates Operations. + # _mutation_lock ensures a Session.run call cannot occur between creating and + # mutating new ops. + # pylint: disable=protected-access + with ops.get_default_graph()._mutation_lock(): + return gradients_util._GradientsHelper( + ys, xs, grad_ys, name, colocate_gradients_with_ops, + gate_gradients, aggregation_method, stop_gradients, + unconnected_gradients) + # pylint: enable=protected-access + + +@tf_export("gradients", v1=[]) +def gradients_v2(ys, # pylint: disable=invalid-name + xs, + grad_ys=None, + name="gradients", + gate_gradients=False, + aggregation_method=None, + stop_gradients=None, + unconnected_gradients=UnconnectedGradients.NONE): + """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. + + `tf.gradients` is only valid in a graph context. In particular, + it is valid in the context of a `tf.function` wrapper, where code + is executing as a graph. + + `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` + is a list of `Tensor`, holding the gradients received by the + `ys`. The list must be the same length as `ys`. + + `gradients()` adds ops to the graph to output the derivatives of `ys` with + respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where + each tensor is the `sum(dy/dx)` for y in `ys` and for x in `xs`. + + `grad_ys` is a list of tensors of the same length as `ys` that holds + the initial gradients for each y in `ys`. When `grad_ys` is None, + we fill in a tensor of '1's of the shape of y for each y in `ys`. A + user can provide their own initial `grad_ys` to compute the + derivatives using a different initial gradient for each y (e.g., if + one wanted to weight the gradient differently for each value in + each y). + + `stop_gradients` is a `Tensor` or a list of tensors to be considered constant + with respect to all `xs`. These tensors will not be backpropagated through, + as though they had been explicitly disconnected using `stop_gradient`. Among + other things, this allows computation of partial derivatives as opposed to + total derivatives. For example: + + >>> @tf.function + ... def example(): + ... a = tf.constant(0.) + ... b = 2 * a + ... return tf.gradients(a + b, [a, b], stop_gradients=[a, b]) + >>> example() + [, + ] + + Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the + total derivatives `tf.gradients(a + b, [a, b])`, which take into account the + influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is + equivalent to: + + >>> @tf.function + ... def example(): + ... a = tf.stop_gradient(tf.constant(0.)) + ... b = tf.stop_gradient(2 * a) + ... return tf.gradients(a + b, [a, b]) + >>> example() + [, + ] + + `stop_gradients` provides a way of stopping gradient after the graph has + already been constructed, as compared to `tf.stop_gradient` which is used + during graph construction. When the two approaches are combined, + backpropagation stops at both `tf.stop_gradient` nodes and nodes in + `stop_gradients`, whichever is encountered first. + + All integer tensors are considered constant with respect to all `xs`, as if + they were included in `stop_gradients`. + + `unconnected_gradients` determines the value returned for each x in xs if it + is unconnected in the graph to ys. By default this is None to safeguard + against errors. Mathematically these gradients are zero which can be requested + using the `'zero'` option. `tf.UnconnectedGradients` provides the + following options and behaviors: + + >>> @tf.function + ... def example(use_zero): + ... a = tf.ones([1, 2]) + ... b = tf.ones([3, 1]) + ... if use_zero: + ... return tf.gradients([b], [a], unconnected_gradients='zero') + ... else: + ... return tf.gradients([b], [a], unconnected_gradients='none') + >>> example(False) + [None] + >>> example(True) + [] + + Let us take one practical example which comes during the back propogation + phase. This function is used to evaluate the derivatives of the cost function + with respect to Weights `Ws` and Biases `bs`. Below sample implementation + provides the exaplantion of what it is actually used for : + + >>> @tf.function + ... def example(): + ... Ws = tf.constant(0.) + ... bs = 2 * Ws + ... cost = Ws + bs # This is just an example. Please ignore the formulas. + ... g = tf.gradients(cost, [Ws, bs]) + ... dCost_dW, dCost_db = g + ... return dCost_dW, dCost_db + >>> example() + (, + ) + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + grad_ys: Optional. A `Tensor` or list of tensors the same size as + `ys` and holding the gradients computed for each y in `ys`. + name: Optional name to use for grouping all the gradient ops together. + defaults to 'gradients'. + gate_gradients: If True, add a tuple around the gradients returned + for an operations. This avoids some race conditions. + aggregation_method: Specifies the method used to combine gradient terms. + Accepted values are constants defined in the class `AggregationMethod`. + stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate + through. + unconnected_gradients: Optional. Specifies the gradient value returned when + the given input tensors are unconnected. Accepted values are constants + defined in the class `tf.UnconnectedGradients` and the default value is + `none`. + + Returns: + A list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` + for y in `ys` and for x in `xs`. + + Raises: + LookupError: if one of the operations between `x` and `y` does not + have a registered gradient function. + ValueError: if the arguments are invalid. + RuntimeError: if called in Eager mode. + + """ + # Creating the gradient graph for control flow mutates Operations. + # _mutation_lock ensures a Session.run call cannot occur between creating and + # mutating new ops. + # pylint: disable=protected-access + with ops.get_default_graph()._mutation_lock(): + return gradients_util._GradientsHelper( + ys, xs, grad_ys, name, True, gate_gradients, + aggregation_method, stop_gradients, + unconnected_gradients) + # pylint: enable=protected-access + + +# TODO(vrv): Make this available when we want to make it public. +def _hessian_vector_product(ys, xs, v): + """Multiply the Hessian of `ys` wrt `xs` by `v`. + + This is an efficient construction that uses a backprop-like approach + to compute the product between the Hessian and another vector. The + Hessian is usually too large to be explicitly computed or even + represented, but this method allows us to at least multiply by it + for the same big-O cost as backprop. + + Implicit Hessian-vector products are the main practical, scalable way + of using second derivatives with neural networks. They allow us to + do things like construct Krylov subspaces and approximate conjugate + gradient descent. + + Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, + x, v)` will return an expression that evaluates to the same values + as (A + A.T) `v`. + + Args: + ys: A scalar value, or a tensor or list of tensors to be summed to + yield a scalar. + xs: A list of tensors that we should construct the Hessian over. + v: A list of tensors, with the same shapes as xs, that we want to + multiply by the Hessian. + + Returns: + A list of tensors (or if the list would be length 1, a single tensor) + containing the product between the Hessian and `v`. + + Raises: + ValueError: `xs` and `v` have different length. + + """ + + # Validate the input + length = len(xs) + if len(v) != length: + raise ValueError("xs and v must have the same length.") + + # First backprop + grads = gradients(ys, xs) + + assert len(grads) == length + elemwise_products = [ + math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem)) + for grad_elem, v_elem in zip(grads, v) + if grad_elem is not None + ] + + # Second backprop + return gradients(elemwise_products, xs) + + +@tf_export(v1=["hessians"]) +def hessians(ys, + xs, + name="hessians", + colocate_gradients_with_ops=False, + gate_gradients=False, + aggregation_method=None): + """Constructs the Hessian of sum of `ys` with respect to `x` in `xs`. + + `hessians()` adds ops to the graph to output the Hessian matrix of `ys` + with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` + where each tensor is the Hessian of `sum(ys)`. + + The Hessian is a matrix of second-order partial derivatives of a scalar + tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details). + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + name: Optional name to use for grouping all the gradient ops together. + defaults to 'hessians'. + colocate_gradients_with_ops: See `gradients()` documentation for details. + gate_gradients: See `gradients()` documentation for details. + aggregation_method: See `gradients()` documentation for details. + + Returns: + A list of Hessian matrices of `sum(ys)` for each `x` in `xs`. + + Raises: + LookupError: if one of the operations between `xs` and `ys` does not + have a registered gradient function. + """ + xs = gradients_util._AsList(xs) # pylint: disable=protected-access + kwargs = { + "colocate_gradients_with_ops": colocate_gradients_with_ops, + "gate_gradients": gate_gradients, + "aggregation_method": aggregation_method + } + # Compute first-order derivatives and iterate for each x in xs. + hessians = [] + _gradients = gradients(ys, xs, **kwargs) + for gradient, x in zip(_gradients, xs): + # change shape to one-dimension without graph branching + gradient = array_ops.reshape(gradient, [-1]) + + # Declare an iterator and tensor array loop variables for the gradients. + n = array_ops.size(x) + loop_vars = [ + array_ops.constant(0, dtypes.int32), + tensor_array_ops.TensorArray(x.dtype, n) + ] + # Iterate over all elements of the gradient and compute second order + # derivatives. + _, hessian = while_loop.while_loop( + lambda j, _: j < n, + lambda j, result: (j + 1, + result.write(j, gradients(gradient[j], x)[0])), + loop_vars + ) + + _shape = array_ops.shape(x) + _reshaped_hessian = array_ops.reshape(hessian.stack(), + array_ops.concat((_shape, _shape), 0)) + hessians.append(_reshaped_hessian) + return hessians + + +@tf_export("hessians", v1=[]) +def HessiansV2(ys, + xs, + gate_gradients=False, + aggregation_method=None, + name="hessians"): + """Constructs the Hessian of sum of `ys` with respect to `x` in `xs`. + + `hessians()` adds ops to the graph to output the Hessian matrix of `ys` + with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` + where each tensor is the Hessian of `sum(ys)`. + + The Hessian is a matrix of second-order partial derivatives of a scalar + tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details). + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + gate_gradients: See `gradients()` documentation for details. + aggregation_method: See `gradients()` documentation for details. + name: Optional name to use for grouping all the gradient ops together. + defaults to 'hessians'. + + Returns: + A list of Hessian matrices of `sum(ys)` for each `x` in `xs`. + + Raises: + LookupError: if one of the operations between `xs` and `ys` does not + have a registered gradient function. + """ + return hessians( + ys, + xs, + name=name, + colocate_gradients_with_ops=True, + gate_gradients=gate_gradients, + aggregation_method=aggregation_method) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_util.py new file mode 100644 index 0000000000000000000000000000000000000000..fa568ea706cf3633f9fe94369007ccdd5ac52eb4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/gradients_util.py @@ -0,0 +1,1089 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implements the graph generation for computation of gradients.""" + +import collections +import contextlib + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_state +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import object_identity +from tensorflow.python.util import variable_utils +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +def _MarkReachedOps(from_ops, reached_ops, func_graphs): + """Mark all ops reached from "from_ops". + + Args: + from_ops: list of Operations. + reached_ops: set of Operations. + func_graphs: list of FuncGraphs. This method will traverse through + these functions if they capture from_ops or any reachable ops. + """ + queue = collections.deque() + queue.extend(from_ops) + while queue: + op = queue.popleft() + if op not in reached_ops: + reached_ops.add(op) + for output in op.outputs: + if backprop_util.IsTrainable(output): + queue.extend(_Consumers(output, func_graphs)) + + +def _PendingCount( + to_ops: list[ops.Operation], + from_ops: list[ops.Operation], + colocate_gradients_with_ops, + func_graphs, + xs_set, +): + """Initialize the pending count for ops between two lists of Operations. + + 'pending_count[op]' indicates the number of backprop inputs + to this operation. + + Args: + to_ops: list of Operations. + from_ops: list of Operations. + colocate_gradients_with_ops: Python bool. See docstring of gradients(). + func_graphs: list of FuncGraphs. This method will traverse through + these functions if they capture from_ops or any reachable ops. This is + useful if to_ops occur in a function and from_ops are in an outer function + or graph. + xs_set: ObjectIdentitySet of Tensors. + + Returns: + A tuple containing: (1) the subset of to_ops reachable from from_ops by a + path of zero or more backpropagatable tensors, (2) a mapping from operation + to the number of backprop inputs to that op, and (3) a ControlFlowState + object which is not None if the ops between from_ops and to_ops contain + control flow loops. + """ + # Mark reachable ops from from_ops. + reached_ops = set() + _MarkReachedOps(from_ops, reached_ops, func_graphs) + # X in reached_ops iff X is reachable from from_ops by a path of zero or more + # backpropagatable tensors. + + reachable_to_ops = set(op for op in to_ops if op in reached_ops) + + # Mark between ops. + between_ops = set() + between_op_list = [] + queue = collections.deque() + queue.extend(to_ops) + while queue: + op = queue.popleft() + # We are interested in this op. + if op in reached_ops: + between_ops.add(op) + between_op_list.append(op) + # Clear the boolean so we won't add the inputs again. + reached_ops.remove(op) + for inp in _NonEagerInputs(op, xs_set): + queue.append(inp.op) + # X in between_ops iff X is on a path of zero or more backpropagatable tensors + # between from_ops and to_ops + + # 'loop_state' is None if there are no while loops. + loop_state = control_flow_state.MaybeCreateControlFlowState( + between_op_list, between_ops, colocate_gradients_with_ops) + + # Initialize pending count for between ops. + pending_count = collections.defaultdict(int) + for op in between_op_list: + for x in _NonEagerInputs(op, xs_set): + if x.op in between_ops: + pending_count[x.op] += 1 + + return reachable_to_ops, pending_count, loop_state + + +def _AsList(x): + return x if isinstance(x, (list, tuple)) else [x] + + +def _DefaultGradYs(grad_ys, + ys, + colocate_gradients_with_ops, + gradient_uid="__unsupported__"): + """Fill in default values for grad_ys. + + Args: + grad_ys: List of gradients, can contain None. + ys: List of tensors. + colocate_gradients_with_ops: If True, try colocating gradients with + the corresponding op. + gradient_uid: A unique identifier within the graph indicating + which invocation of gradients is being executed. Used to cluster + ops for compilation. + + Returns: + A list of gradients to use, without None. + + Raises: + ValueError: If sizes of gradients and inputs don't match + TypeError: If type of any gradient is not valid for its input. + """ + if len(grad_ys) != len(ys): + raise ValueError(f"Length mismatch. Passed {len(grad_ys)} grad_ys for " + f"{len(ys)} ys") + grad_ys = indexed_slices.convert_n_to_tensor_or_indexed_slices( + grad_ys, name="grad_y") + new_grad_ys = [] + for i, (y, grad_y) in enumerate(zip(ys, grad_ys)): + with _maybe_colocate_with(y.op, gradient_uid, colocate_gradients_with_ops): + if grad_y is None: + if y.dtype.is_complex: + raise TypeError( + f"Gradients of complex tensors ({y}) must set grad_ys (y.dtype = " + f"{dtypes.as_dtype(y.dtype).name})" + ) + new_grad_ys.append( + array_ops.ones( + array_ops.shape(y), dtype=y.dtype, name="grad_ys_%d" % i + ) + ) + continue + if y.dtype.is_floating or y.dtype.is_integer: + if not grad_y.dtype.is_floating and not grad_y.dtype.is_integer: + raise TypeError( + f"Gradient type {dtypes.as_dtype(grad_y.dtype).name} generated " + f"for real or integer-valued tensor {y} with type " + f"{dtypes.as_dtype(y.dtype).name} must be real or integer" + ) + elif y.dtype.is_complex: + if not grad_y.dtype.is_complex: + raise TypeError( + f"Gradient type {dtypes.as_dtype(grad_y.dtype).name} generated " + f"for complex-valued tensor {y} with type " + f"{dtypes.as_dtype(y.dtype).name} must be real" + ) + elif y.dtype == dtypes.variant: + if grad_y.dtype != dtypes.variant: + raise TypeError( + f"Gradient type {dtypes.as_dtype(grad_y.dtype).name} generated " + f"for variant tensor {y} with type " + f"{dtypes.as_dtype(y.dtype).name} must be variant" + ) + elif y.dtype == dtypes.resource: + # We assume y is the handle of a ResourceVariable. The gradient of a + # ResourceVariable should be a numeric value, not another resource. + if grad_y.dtype == dtypes.resource: + raise TypeError( + f"Input gradient {grad_y} for resource tensor {y} " + "should not be a resource" + ) + else: + raise TypeError( + f"Tensor {y} with type {dtypes.as_dtype(y.dtype).name} must be " + "numeric to obtain a default gradient" + ) + # Create a grad_y tensor in the name scope of the gradient. + # Required for TensorArrays to identify which gradient call a + # grad_y value is coming from. + if isinstance(grad_y, indexed_slices.IndexedSlices): + new_grad_ys.append( + indexed_slices.IndexedSlices( + indices=( + array_ops.identity( + grad_y.indices, name="grad_ys_%d_indices" % i + ) + if isinstance(grad_y.indices, tensor_lib.Tensor) + else grad_y.indices + ), + values=( + array_ops.identity( + grad_y.values, name="grad_ys_%d_values" % i + ) + if isinstance(grad_y.values, tensor_lib.Tensor) + else grad_y.values + ), + dense_shape=( + array_ops.identity( + grad_y.dense_shape, name="grad_ys_%d_shape" % i + ) + if isinstance(grad_y.dense_shape, tensor_lib.Tensor) + else grad_y.dense_shape + ), + ) + ) + else: + new_grad_ys.append(array_ops.identity(grad_y, name="grad_ys_%d" % i)) + + return new_grad_ys + + +def _VerifyGeneratedGradients(grads, op: ops.Operation): + """Verify that gradients are valid in number and type. + + Args: + grads: List of generated gradients. + op: Operation for which the gradients where generated. + + Raises: + ValueError: if sizes of gradients and inputs don't match. + TypeError: if type of any gradient is not valid for its input. + """ + # While ops have inputs added to them during the gradient computation, so we + # skip the below check. See while_v2 for details. + if op.type == "While" or op.type == "StatelessWhile": + return + + if len(grads) != len(op.inputs): + raise ValueError( + f"Num gradients {len(grads)} generated for op " + f"{op.node_def} do not match num inputs {len(op.inputs)}" + ) + + +def _StopOps( + from_ops: list[ops.Operation], + stop_gradient_ops: list[ops.Operation], + pending_count, + xs_set, +): + """The set of ops that terminate the gradient computation. + + This computes the frontier of the forward graph *before* which backprop + should stop. Operations in the returned set will not be differentiated. + This set is defined as the subset of `from_ops` containing ops that have + no predecessor in `from_ops`. `pending_count` is the result of + `_PendingCount(xs, from_ops)`. An 'op' has predecessors in `from_ops` + iff pending_count[op] > 0. + + In addition, none of `stop_gradient_ops` will be differentiated. + + Args: + from_ops: list of Operations. + stop_gradient_ops: list of Operations never to backprop through. + pending_count: mapping from operation to number of backprop inputs. + xs_set: ObjectIdentitySet of Tensors. + + Returns: + The set of operations. + """ + stop_ops = set() + for op in from_ops: + is_stop_op = True + for inp in _NonEagerInputs(op, xs_set): + if pending_count[inp.op] > 0: + is_stop_op = False + break + if is_stop_op: + stop_ops.add(op) + stop_ops.update(op for op in stop_gradient_ops) + return stop_ops + + +@contextlib.contextmanager +def _maybe_colocate_with( # pylint: disable=invalid-name + op: ops.Operation, + gradient_uid, + colocate_gradients_with_ops, +): + """Context to colocate with `op` if `colocate_gradients_with_ops`.""" + if colocate_gradients_with_ops: + with ops._colocate_with_for_gradient(op, gradient_uid): # pylint: disable=protected-access + yield + else: + yield + + +def _IsPartitionedCall(op: ops.Operation): + return op.type == "PartitionedCall" or op.type == "StatefulPartitionedCall" + + +def _SymGrad(op: ops.Operation, out_grads): + """Backprop through a function call node op given its outputs' gradients.""" + f_in = [x for x in op.inputs] + out_grads + f_types = [default_gradient.get_zeros_dtype(x) for x in op.inputs] + f = attr_value_pb2.NameAttrList() + if _IsPartitionedCall(op): + f.name = op.get_attr("f").name + else: + f.name = op.type + for k in op.node_def.attr: + f.attr[k].CopyFrom(op.node_def.attr[k]) + in_grads = gen_functional_ops.symbolic_gradient(input=f_in, Tout=f_types, f=f) + return in_grads + + +def _MaybeCompile(scope, op: ops.Operation, func, grad_fn): + """Compile the calculation in grad_fn if op was marked as compiled.""" + scope = scope.rstrip("/").replace("/", "_") + if func is not None: + xla_compile = func.cached_definition.attr["_XlaCompile"].b + xla_separate_compiled_gradients = func.cached_definition.attr[ + "_XlaSeparateCompiledGradients"].b + xla_scope = func.cached_definition.attr["_XlaScope"].s.decode() + else: + try: + xla_compile = op.get_attr("_XlaCompile") + xla_separate_compiled_gradients = op.get_attr( + "_XlaSeparateCompiledGradients") + xla_scope = op.get_attr("_XlaScope").decode() + except ValueError: + xla_compile = False + + if not xla_compile: + return grad_fn() # Exit early + + # If the gradients are supposed to be compiled separately, we give them a + # _XlaScope name that is based on the name_scope of the gradients. Otherwise + # they just inherit the existing _XlaScope name, which lets them be merged + # together with the non-gradient computation. + if xla_separate_compiled_gradients: + xla_grad_scope = "%s_grad_%s" % (xla_scope, scope) + else: + xla_grad_scope = xla_scope + + attrs = { + "_XlaCompile": attr_value_pb2.AttrValue(b=xla_compile), + "_XlaScope": attr_value_pb2.AttrValue(s=xla_grad_scope.encode()) + } + with ops.get_default_graph()._attr_scope(attrs): # pylint: disable=protected-access + return grad_fn() + + +def _RaiseNoGradWrtInitialLoopValError( + op: ops.Operation, + from_ops: list[ops.Operation], + xs_set, +): + """Raises an error if we backprop through a loop var.""" + # Find the nearest 'to_op' reachable from 'op' to provide a more helpful error + # message. + target_op = None + queue = collections.deque([op]) + visited = set() + while queue: + curr_op = queue.popleft() + if curr_op in visited: continue + visited.add(curr_op) + if curr_op in from_ops: + target_op = curr_op + break + queue.extend(t.op for t in _NonEagerInputs(curr_op, xs_set)) + assert target_op + raise ValueError( + "Cannot compute gradient inside while loop with respect to op " + f"'{target_op.name}'. We do not support taking the gradient wrt or " + "through the initial value of a loop variable. Gradients can be computed " + "through loop invariants or wrt the input parameters to the loop body.") + + +def _IsFunction(graph): + # isinstance check for FuncGraphs that avoids the explicit dependency + # on func_graph.py and function.py + return isinstance(graph, ops.Graph) and graph._building_function # pylint: disable=protected-access + + +def _Captures(func_graph): + assert _IsFunction(func_graph) + return func_graph.captures + + +def _MaybeCaptured(t): + """If t is a captured value placeholder, returns the original captured value. + + Args: + t: Tensor + + Returns: + A tensor, potentially from a different Graph/FuncGraph. + """ + # pylint: disable=protected-access + if (not isinstance(t, ops.EagerTensor) and + _IsFunction(t.op.graph) and t.op.type == "Placeholder"): + for input_t, placeholder_t in _Captures(t.op.graph): + if t is placeholder_t: + return _MaybeCaptured(input_t) + # pylint: enable=protected-access + return t + + +def _NonEagerInputs(op: ops.Operation, xs_set): + """Returns the inputs of op, crossing closure boundaries where necessary. + + Does not return any captured EagerTensors, i.e., the number of tensors + returned may be less than the actual number of inputs. + + Args: + op: Operation + xs_set: ObjectIdentitySet of Tensors we are differentiating w.r.t. + + Returns: + A list of tensors. The tensors may be from multiple Graph/FuncGraphs if op + is in a FuncGraph and has captured inputs. + """ + return [t for t in _Inputs(op, xs_set) if not isinstance(t, ops.EagerTensor)] + + +# TODO(skyewm): plumbing xs through everywhere is ugly, consider making +# _GradientsHelper a class with xs as a member variable. +def _Inputs(op: ops.Operation, xs_set): + """Returns the inputs of op, crossing closure boundaries where necessary. + + Args: + op: Operation + xs_set: ObjectIdentitySet of Tensors we are differentiating w.r.t. + + Returns: + A list of tensors. The tensors may be from multiple Graph/FuncGraphs if op + is in a FuncGraph and has captured inputs. + """ + if _IsFunction(op.graph): # pylint: disable=protected-access + inputs = [] + for t in op.inputs: + # If we're differentiating w.r.t. `t`, do not attempt to traverse through + # it to a captured value. The algorithm needs to "see" `t` in this case, + # even if it's a function input for a captured value, whereas usually we'd + # like to traverse through these closures as if the captured value was the + # direct input to op. + if t not in xs_set: + t = _MaybeCaptured(t) + inputs.append(t) + return inputs + else: + return op.inputs + + +def _Consumers(t, func_graphs): + """Returns the consumers of t, crossing closure boundaries where necessary. + + Args: + t: Tensor + func_graphs: a list of FuncGraphs that may have captured t. + + Returns: + A list of tensors. The tensors will be from the current graph and/or + func_graphs. + """ + consumers = t.consumers() + for func in func_graphs: + for input_t, placeholder in _Captures(func): + if input_t is t: + consumers.extend(_Consumers(placeholder, func_graphs)) + return consumers + + +def _GradientsHelper(ys, + xs, + grad_ys=None, + name="gradients", + colocate_gradients_with_ops=False, + gate_gradients=False, + aggregation_method=None, + stop_gradients=None, + unconnected_gradients=UnconnectedGradients.NONE, + src_graph=None): + """Implementation of gradients().""" + if context.executing_eagerly(): + raise RuntimeError("tf.gradients is not supported when eager execution " + "is enabled. Use tf.GradientTape instead.") + ys = variable_utils.convert_variables_to_tensors(_AsList(ys)) + xs = [ + x.handle if resource_variable_ops.is_resource_variable(x) else x + for x in _AsList(xs) + ] + if grad_ys is not None: + grad_ys = _AsList(grad_ys) + + # Handle CompositeTensors. + if (any(isinstance(x, composite_tensor.CompositeTensor) for x in xs) or + any(isinstance(y, composite_tensor.CompositeTensor) for y in ys)): + flat_xs = composite_tensor_gradient.get_flat_tensors_for_gradients(xs) + flat_ys = composite_tensor_gradient.get_flat_tensors_for_gradients(ys) + flat_grad_ys = ( + None if grad_ys is None else + composite_tensor_gradient.get_flat_tensors_for_gradients(grad_ys)) + flat_grads = _GradientsHelper(flat_ys, flat_xs, flat_grad_ys, name, + colocate_gradients_with_ops, gate_gradients, + aggregation_method, stop_gradients, + unconnected_gradients, src_graph) + return composite_tensor_gradient.replace_flat_tensors_for_gradients( + xs, flat_grads) + + if src_graph is None: + src_graph = ops.get_default_graph() + try: + unconnected_gradients = UnconnectedGradients(unconnected_gradients) + except ValueError: + raise ValueError( + f"Unknown value for unconnected_gradients: '{unconnected_gradients}'") + + # If src_graph is a _FuncGraph (i.e. a function body), gather it and all + # ancestor graphs. This is necessary for correctly handling captured values. + func_graphs = [] + curr_graph = src_graph + while _IsFunction(curr_graph): + func_graphs.append(curr_graph) + curr_graph = curr_graph.outer_graph + + stop_gradients = [] if stop_gradients is None else _AsList(stop_gradients) + if grad_ys is None: + grad_ys = [None] * len(ys) + + with ops.name_scope( + name, "gradients", + list(ys) + list(xs) + list(stop_gradients) + list(grad_ys)) as grad_scope: + # Get a uid for this call to gradients that can be used to help + # cluster ops for compilation. + gradient_uid = ops.get_default_graph().unique_name("uid") + ys = indexed_slices.convert_n_to_tensor_or_indexed_slices(ys, name="y") + xs = indexed_slices.internal_convert_n_to_tensor_or_indexed_slices( + xs, name="x", as_ref=True) + xs_set = object_identity.ObjectIdentitySet(xs) + grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops, + gradient_uid) + + # The approach we take here is as follows: Create a list of all ops in the + # subgraph between the ys and xs. Visit these ops in reverse order of ids + # to ensure that when we visit an op the gradients w.r.t its outputs have + # been collected. Then aggregate these gradients if needed, call the op's + # gradient function, and add the generated gradients to the gradients for + # its input. + + # Initialize the pending count for ops in the connected subgraph from ys + # to the xs. + to_ops = [t.op for t in ys] + from_ops = [t.op for t in xs] + stop_gradient_ops = [t.op for t in stop_gradients] + reachable_to_ops, pending_count, loop_state = _PendingCount( + to_ops, from_ops, colocate_gradients_with_ops, func_graphs, xs_set) + + # Iterate over the collected ops. + # + # grads: op => list of gradients received on each output endpoint of the + # op. The gradients for each endpoint are initially collected as a list. + # When it is time to call the op's gradient function, for each endpoint we + # aggregate the list of received gradients into a Add() Operation if there + # is more than one. + grads = {} + + # Add the initial gradients for the ys. + for y, grad_y in zip(ys, grad_ys): + _SetGrad(grads, y, grad_y) + + # Initialize queue with to_ops. + queue = collections.deque() + # Add the ops in 'to_ops' into the queue. + to_ops_set = set() + for op in to_ops: + # 'ready' handles the case where one output gradient relies on + # another output's gradient. + ready = (pending_count[op] == 0) + if ready and op not in to_ops_set and op in reachable_to_ops: + to_ops_set.add(op) + queue.append(op) + + if loop_state: + loop_exits = loop_state.ProcessUnusedLoopExits(pending_count, to_ops_set) + for y in loop_exits: + if backprop_util.IsTrainable(y): + _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) + queue.append(y.op) + + stop_ops = _StopOps(from_ops, stop_gradient_ops, pending_count, xs_set) + while queue: + # generate gradient subgraph for op. + op = queue.popleft() + with _maybe_colocate_with(op, gradient_uid, colocate_gradients_with_ops): + if loop_state: + loop_state.EnterGradWhileContext(op, before=True) + out_grads = _AggregatedGrads(grads, op, gradient_uid, loop_state, + aggregation_method) + if loop_state: + loop_state.ExitGradWhileContext(op, before=True) + + grad_fn = None + func_call = None + is_partitioned_call = _IsPartitionedCall(op) + # pylint: disable=protected-access + is_func_call = src_graph._is_function(op.type) or is_partitioned_call + # pylint: enable=protected-access + has_out_grads = any( + isinstance(g, tensor_lib.Tensor) or g for g in out_grads + ) + if has_out_grads and (op not in stop_ops): + try: + grad_fn = ops.get_gradient_function(op) + except LookupError: + if is_func_call: + if is_partitioned_call: + func_name = compat.as_bytes(op.get_attr("f").name) + func_call = src_graph._get_function( # pylint: disable=protected-access + func_name) + # When a graph is imported, the FunctionDefs are not copied over + # to each sub-graph so we recursively search the outer graphs + # for the FunctionDef. + if not func_call and hasattr(src_graph, "outer_graph"): + graph = src_graph.outer_graph + while graph is not None: + func_call = graph._get_function(func_name) # pylint: disable=protected-access + if func_call is not None: + break + if hasattr(graph, "outer_graph"): + graph = graph.outer_graph + else: + break + else: + func_call = src_graph._get_function(op.type) # pylint: disable=protected-access + # Note that __defun is not set if the graph is + # imported. If it's set, we prefer to access the original + # defun. + func_call = getattr(op, "__defun", func_call) + grad_fn = func_call.python_grad_func + else: + raise LookupError( + "No gradient defined for operation" + f"'{op.name}' (op type: {op.type}). " + "In general every operation must have an associated " + "`@tf.RegisterGradient` for correct autodiff, which this " + "op is lacking. If you want to pretend this " + "operation is a constant in your program, you may insert " + "`tf.stop_gradient`. This can be useful to silence the " + "error in cases where you know gradients are not needed, " + "e.g. the forward pass of tf.custom_gradient. " + "Please see more details in " + "https://www.tensorflow.org/api_docs/python/tf/custom_gradient.") # pylint: disable=line-too-long + if loop_state: + loop_state.EnterGradWhileContext(op, before=False) + + # NOTE(skyewm): We don't support computing gradients wrt a loop variable + # unless it's within the context of a single iteration (i.e. the + # gradient is wrt to the loop parameter in the body function, not wrt or + # through the initial value). This means if we're in a while loop + # context, we should never see a switch node from this context. + # pylint: disable=protected-access + if (control_flow_util.IsSwitch(op) and + op._control_flow_context is not None and + op._control_flow_context.IsWhileContext() and + op._control_flow_context == + ops.get_default_graph()._get_control_flow_context()): + _RaiseNoGradWrtInitialLoopValError(op, from_ops, xs_set) + # pylint: enable=protected-access + + if (grad_fn or is_func_call) and has_out_grads: + # NOTE: If _AggregatedGrads didn't compute a value for the i'th + # output, it means that the cost does not depend on output[i], + # therefore dC/doutput[i] is 0. + for i, out_grad in enumerate(out_grads): + if ( + not isinstance(out_grad, tensor_lib.Tensor) and not out_grad + ) and ( + (not grad_fn and is_func_call) + or backprop_util.IsTrainable(op.outputs[i]) + ): + # Only trainable outputs or outputs for a function call that + # will use SymbolicGradient get a zero gradient. Gradient + # functions should ignore the gradient for other outputs. + # TODO(apassos) gradients of resource handles might be an + # issue here because of zeros. + if loop_state: + out_grads[i] = loop_state.ZerosLikeV1WhileLoop(op, i) + elif default_gradient.supports_default_grad(op.outputs[i]): + # TODO(b/143286622): The supports_default_grad check is needed + # because While op emits non-differentiable resource tensors + # as outputs. Remove this check when that is not the case. + out_grads[i] = control_flow_state.ZerosLike(op, i) + with ops.name_scope(op.name + "_grad"): + # pylint: disable=protected-access + with src_graph._original_op(op): + # pylint: enable=protected-access + if grad_fn: + # If grad_fn was found, do not use SymbolicGradient even for + # functions. + in_grads = _MaybeCompile(grad_scope, op, func_call, + lambda: grad_fn(op, *out_grads)) + else: + # For function call ops, we add a 'SymbolicGradient' + # node to the graph to compute gradients. + in_grads = _MaybeCompile(grad_scope, op, func_call, + lambda: _SymGrad(op, out_grads)) + in_grads = _AsList(in_grads) + _VerifyGeneratedGradients(in_grads, op) + if gate_gradients and len([x for x in in_grads + if x is not None]) > 1: + with ops.device(None): + with ops._colocate_with_for_gradient( # pylint: disable=protected-access + None, + gradient_uid, + ignore_existing=True): + in_grads = control_flow_ops.tuple(in_grads) + _LogOpGradients(op, out_grads, in_grads) + else: + # If no grad_fn is defined or none of out_grads is available, + # just propagate a list of None backwards. + in_grads = [None] * len(_Inputs(op, xs_set)) + # Note: we don't filter out eager inputs here because the inputs need to + # line up with in_grads. + for i, (t_in, in_grad) in enumerate(zip(_Inputs(op, xs_set), in_grads)): + if in_grad is not None: + if (isinstance(in_grad, tensor_lib.Tensor) and + t_in.dtype != dtypes.resource): + try: + in_grad.set_shape(t_in.get_shape()) + except ValueError: + raise ValueError( + "Incompatible shapes between op input and calculated " + f"input gradient. Forward operation: {op.name}. Input " + f"index: {i}. Original input shape: {t_in.shape}. " + f"Calculated input gradient shape: {in_grad.shape}") + if not isinstance(t_in, ops.EagerTensor): + _SetGrad(grads, t_in, in_grad) + if loop_state: + loop_state.ExitGradWhileContext(op, before=False) + + # Update pending count for the inputs of op and enqueue ready ops. + _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state, + xs_set) + + if loop_state: + loop_state.PostProcessing() + return [_GetGrad(grads, x, unconnected_gradients) for x in xs] + + +def _HasAnyNotNoneGrads(grads, op: ops.Operation): + """Return true iff op has real gradient.""" + out_grads = _GetGrads(grads, op) + for out_grad in out_grads: + if isinstance(out_grad, (tensor_lib.Tensor, indexed_slices.IndexedSlices)): + return True + if out_grad and isinstance(out_grad, collections_abc.Sequence): + if any(g is not None for g in out_grad): + return True + return False + + +def _UpdatePendingAndEnqueueReady( + grads, op: ops.Operation, queue, pending_count, loop_state, xs_set +): + """Update pending count for the inputs of op and enqueue ready ops.""" + for x in _NonEagerInputs(op, xs_set): + pending_count[x.op] -= 1 + ready = pending_count[x.op] == 0 + if loop_state and not ready: + ready = pending_count[x.op] > 0 and control_flow_util.IsLoopSwitch(x.op) + if ready: + if control_flow_util.IsLoopExit(x.op): + # if x is an exit without real gradient, defer processing them. + grad_state = loop_state.GetGradState(x.op, before=False) + grad_state.deferred_exits.append(x) + grad_state.pending_exits_count -= 1 + if grad_state.pending_exits_count == 0: + # We now have all the exits so process them. + has_not_none_grad = False + for y in grad_state.deferred_exits: + if _HasAnyNotNoneGrads(grads, y.op): + has_not_none_grad = True + queue.append(y.op) + else: + grad_state.unused_exits.append(y) + if has_not_none_grad: + # For an unused exit, if it has trainable outputs, backprop + # a zero gradient. Otherwise, just ignore it. + for y in grad_state.unused_exits: + if backprop_util.IsTrainable(y): + _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) + queue.append(y.op) + else: + # All exits are "unused" so use None as gradient. + for y in grad_state.unused_exits: + queue.append(y.op) + else: + queue.append(x.op) + + +def _SetGrad(grads, t, grad): + """Sets gradient "grad" in "grads" for tensor "t".""" + op = t.op + op_grads = grads.get(op) + if not op_grads: + op_grads = [[] for _ in range(len(op.outputs))] + grads[op] = op_grads + t_grads = op_grads[t.value_index] + if isinstance(t_grads, list): + t_grads.append(grad) + else: + assert control_flow_util.IsLoopSwitch(op) + op_grads[t.value_index] = grad + + +def _ZerosLike(t): + t_dtype = default_gradient.get_zeros_dtype(t) + if t.dtype == dtypes.resource: + return array_ops.zeros( + resource_variable_ops.variable_shape(t), dtype=t_dtype) + else: + return array_ops.zeros_like(t, dtype=t_dtype) + + +def _GetGrad(grads, t, unconnected_gradients): + """Gets gradient for tensor "t".""" + op = t.op + op_grads = grads.get(op) + if not op_grads: + if unconnected_gradients == UnconnectedGradients.ZERO: + return _ZerosLike(t) + elif unconnected_gradients == UnconnectedGradients.NONE: + return None + else: + raise ValueError( + f"Unknown value for unconnected_gradients: '{unconnected_gradients}'") + + t_grad = op_grads[t.value_index] + # This can happen if some other output of `t.op` has non-None grad. + if unconnected_gradients == UnconnectedGradients.ZERO and t_grad is None: + return _ZerosLike(t) + + assert not isinstance( + t_grad, list), ("gradients list should have been aggregated by now.") + return t_grad + + +def _GetGrads(grads, op: ops.Operation): + """Gets all gradients for op.""" + if op in grads: + return grads[op] + else: + return [[] for _ in range(len(op.outputs))] + + +def _AccumulatorShape(inputs): + shape = tensor_shape.unknown_shape() + for i in inputs: + if isinstance(i, tensor_lib.Tensor): + shape = shape.merge_with(i.get_shape()) + return shape + + +def _LogOpGradients(op: ops.Operation, out_grads, in_grads): + """Log the in and out grads of an op.""" + logging.vlog(1, "Gradient for '" + op.name + "'") + + def _FilterGrad(x): + if x is None: + return False + if isinstance(x, (list, tuple)): + return bool(x) + else: + return True + + logging.vlog(1, " in --> %s", + ", ".join(x.name for x in out_grads if _FilterGrad(x))) + logging.vlog(1, " out --> %s", + ", ".join(x.name for x in in_grads if _FilterGrad(x))) + + +def _MultiDeviceAddN(tensor_list, gradient_uid): + """Adds tensors from potentially multiple devices.""" + # Basic function structure comes from control_flow_ops.group(). + # Sort tensors according to their devices. + tensors_on_device = collections.defaultdict(lambda: []) + for tensor in tensor_list: + tensors_on_device[tensor.device].append(tensor) + + # For each device, add the tensors on that device first. + # Then gather the partial sums from multiple devices. + # TODO(sjhwang): Create hierarchical aggregation tree as pbar's suggestion. + # E.g., aggregate per GPU, then per task, and so on. + summands = [] + + def DeviceKey(dev): + return "" if dev is None else dev + + for dev in sorted(tensors_on_device, key=DeviceKey): + tensors = tensors_on_device[dev] + with ops._colocate_with_for_gradient( # pylint: disable=protected-access + tensors[0].op, + gradient_uid, + ignore_existing=True): + summands.append(math_ops.add_n(tensors)) + + return math_ops.add_n(summands) + + +@tf_export("AggregationMethod") +class AggregationMethod: + """A class listing aggregation methods used to combine gradients. + + Computing partial derivatives can require aggregating gradient + contributions. This class lists the various methods that can + be used to combine gradients in the graph. + + The following aggregation methods are part of the stable API for + aggregating gradients: + + * `ADD_N`: All of the gradient terms are summed as part of one + operation using the "AddN" op (see `tf.add_n`). This + method has the property that all gradients must be ready and + buffered separately in memory before any aggregation is performed. + * `DEFAULT`: The system-chosen default aggregation method. + + The following aggregation methods are experimental and may not + be supported in future releases: + + * `EXPERIMENTAL_TREE`: Gradient terms are summed in pairs using + the "AddN" op. This method of summing gradients may reduce + performance, but it can improve memory utilization because the + gradients can be released earlier. + * `EXPERIMENTAL_ACCUMULATE_N`: Same as `EXPERIMENTAL_TREE`. + + Example usage when computing gradient: + + >>> @tf.function + ... def example(): + ... x = tf.constant(1.0) + ... y = x * 2.0 + ... z = y + y + y + y + ... return tf.gradients(z, [x, y], + ... aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) + >>> example() + [, + ] + + """ + ADD_N = 0 + DEFAULT = ADD_N + # The following are experimental and may not be supported in future releases. + EXPERIMENTAL_TREE = 1 + EXPERIMENTAL_ACCUMULATE_N = 2 # An alias for EXPERIMENTAL_ADD_N = 1 + + +def _AggregatedGrads(grads, + op, + gradient_uid, + loop_state, + aggregation_method=None): + """Get the aggregated gradients for op. + + Args: + grads: The map of memoized gradients. + op: The op to get gradients for. + gradient_uid: A unique identifier within the graph indicating + which invocation of gradients is being executed. Used to cluster + ops for compilation. + loop_state: An object for maintaining the state of the while loops in the + graph. It is of type ControlFlowState. None if the graph + contains no while loops. + aggregation_method: Specifies the method used to combine gradient terms. + Accepted values are constants defined in the class `AggregationMethod`. + + Returns: + A list of gradients, one per each output of `op`. If the gradients + for a particular output is a list, this function aggregates it + before returning. + + Raises: + TypeError: if the incoming grads are not Tensors or IndexedSlices. + ValueError: if the arguments are invalid. + + """ + if aggregation_method is None: + aggregation_method = AggregationMethod.DEFAULT + valid_aggregation_methods = [ + AggregationMethod.ADD_N, AggregationMethod.EXPERIMENTAL_TREE, + AggregationMethod.EXPERIMENTAL_ACCUMULATE_N] + if aggregation_method not in valid_aggregation_methods: + raise ValueError( + f"Invalid `aggregation_method` specified {aggregation_method}. " + f"Accepted values are {valid_aggregation_methods}.") + out_grads = _GetGrads(grads, op) + for i, out_grad in enumerate(out_grads): + if loop_state: + if isinstance( + out_grad, (tensor_lib.Tensor, indexed_slices.IndexedSlices)): + assert control_flow_util.IsLoopSwitch(op) + continue + # Grads have to be Tensors or IndexedSlices + if (isinstance(out_grad, collections_abc.Sequence) and not all( + isinstance(g, (tensor_lib.Tensor, indexed_slices.IndexedSlices)) + for g in out_grad + if g is not None)): + raise TypeError(f"Invalid gradient {out_grad} [index = {i}]. Gradients " + "have to be either all Tensors or all IndexedSlices") + # Aggregate multiple gradients, and convert [] to None. + if out_grad: + if len(out_grad) < 2: + used = "nop" + out_grads[i] = out_grad[0] + elif all( + isinstance(g, tensor_lib.Tensor) for g in out_grad if g is not None): + tensor_shape = _AccumulatorShape(out_grad) + if aggregation_method in [ + AggregationMethod.EXPERIMENTAL_TREE, + AggregationMethod.EXPERIMENTAL_ACCUMULATE_N + ]: + # Aggregate all gradients by doing pairwise sums: this may + # reduce performance, but it can improve memory because the + # gradients can be released earlier. + # + # TODO(vrv): Consider replacing this with a version of + # tf.AddN() that eagerly frees its inputs as soon as they are + # ready, so the order of this tree does not become a problem. + used = "tree" + with ops.name_scope(op.name + "_gradient_sum"): + running_sum = out_grad[0] + for grad in out_grad[1:]: + running_sum = math_ops.add_n([running_sum, grad]) + out_grads[i] = running_sum + else: + used = "add_n" + out_grads[i] = _MultiDeviceAddN(out_grad, gradient_uid) + logging.vlog(2, " _AggregatedGrads %d x %s using %s", len(out_grad), + tensor_shape, used) + else: + out_grads[i] = backprop_util.AggregateIndexedSlicesGradients(out_grad) # pylint: disable=protected-access + else: # not out_grad + # out_grads[i] is [], thus its aggregation is simply None. + out_grads[i] = None + return out_grads + + +# Represents the output of TFE_Py_TapeSetPossibleGradientTypes. Real enums are +# unfortunately too slow to use here. +POSSIBLE_GRADIENT_TYPES_NONE = 0 +POSSIBLE_GRADIENT_TYPES_FIRST_ORDER = 1 +POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER = 2 + + +def PossibleTapeGradientTypes(tensors): + """Determines whether and how `args` may require tape gradients.""" + return pywrap_tfe.TFE_Py_TapeSetPossibleGradientTypes(tensors) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/handle_data_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/handle_data_util.py new file mode 100644 index 0000000000000000000000000000000000000000..d2ece077a20535f436a0e01afafc02af673697cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/handle_data_util.py @@ -0,0 +1,89 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Decorator to overrides the gradient for a function.""" + +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.types import core +from tensorflow.python.util import compat + + +def get_resource_handle_data(graph_op): + assert (isinstance(graph_op, core.Symbol) + and not isinstance(graph_op, core.Value)) + + with graph_op.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + handle_data = pywrap_tf_session.GetHandleShapeAndType( + c_graph, graph_op._as_tf_output()) # pylint: disable=protected-access + + return cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData.FromString( + compat.as_bytes(handle_data)) + + +def get_handle_data(source_t): + """Obtains HandleData from a tensor.""" + if isinstance(source_t, core.Value): + return source_t._handle_data # pylint: disable=protected-access + return get_resource_handle_data(source_t) + + +def copy_handle_data(source_t, target_t): + """Copies HandleData for variant and resource type tensors if available. + + The CppShapeInferenceResult::HandleData proto contains information about the + shapes and types of the element tensors of resource/variant type tensors. + We need to copy this across function boundaries, i.e., when capturing a + placeholder or when returning a function tensor as output. If we don't do this + the element tensors will have unknown shapes, e.g., if a TensorList variant + tensor is captured as a placeholder, elements popped from that list would have + unknown shape. + + Args: + source_t: The tensor to copy HandleData from. + target_t: The tensor to copy HandleData to. + """ + if (target_t.dtype == dtypes.resource or + target_t.dtype == dtypes.variant): + handle_data = get_handle_data(source_t) + set_handle_data(target_t, handle_data) + + +def set_handle_data(target_t, handle_data): + """Sets handle data on the giver tensor.""" + if ( + handle_data is None + or not handle_data.is_set + or not handle_data.shape_and_type + ): + return + + # pylint: disable=protected-access + if isinstance(target_t, core.Value): + target_t._handle_data = handle_data + return + with target_t.graph._c_graph.get() as c_graph: + pywrap_tf_session.SetHandleShapeAndType(c_graph, target_t._as_tf_output(), + handle_data.SerializeToString()) + # pylint: enable=protected-access + + +def create_handle_data(shape, dtype): + handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData() + handle_data.is_set = True + handle_data.shape_and_type.append( + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType( + shape=shape.as_proto(), dtype=dtype.as_datatype_enum)) + return handle_data diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/histogram_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/histogram_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f68e3ab560efc025f4ff869bae84cc6f260f5f3b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/histogram_ops.py @@ -0,0 +1,149 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# pylint: disable=g-short-docstring-punctuation +"""Histograms. +""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('histogram_fixed_width_bins') +@dispatch.add_dispatch_support +def histogram_fixed_width_bins(values, + value_range, + nbins=100, + dtype=dtypes.int32, + name=None): + """Bins the given values for use in a histogram. + + Given the tensor `values`, this operation returns a rank 1 `Tensor` + representing the indices of a histogram into which each element + of `values` would be binned. The bins are equal width and + determined by the arguments `value_range` and `nbins`. + + Args: + values: Numeric `Tensor`. + value_range: Shape [2] `Tensor` of same `dtype` as `values`. + values <= value_range[0] will be mapped to hist[0], + values >= value_range[1] will be mapped to hist[-1]. + nbins: Scalar `int32 Tensor`. Number of histogram bins. + dtype: dtype for returned histogram. + name: A name for this operation (defaults to 'histogram_fixed_width'). + + Returns: + A `Tensor` holding the indices of the binned values whose shape matches + `values`. + + Raises: + TypeError: If any unsupported dtype is provided. + tf.errors.InvalidArgumentError: If value_range does not + satisfy value_range[0] < value_range[1]. + + Examples: + + >>> # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) + ... + >>> nbins = 5 + >>> value_range = [0.0, 5.0] + >>> new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] + >>> indices = tf.histogram_fixed_width_bins(new_values, value_range, nbins=5) + >>> indices.numpy() + array([0, 0, 1, 2, 4, 4], dtype=int32) + """ + with ops.name_scope(name, 'histogram_fixed_width_bins', + [values, value_range, nbins]): + values = ops.convert_to_tensor(values, name='values') + shape = array_ops.shape(values) + + values = array_ops.reshape(values, [-1]) + value_range = ops.convert_to_tensor(value_range, name='value_range') + nbins = ops.convert_to_tensor(nbins, dtype=dtypes.int32, name='nbins') + check = control_flow_assert.Assert( + math_ops.greater(nbins, 0), ['nbins %s must > 0' % nbins]) + nbins = control_flow_ops.with_dependencies([check], nbins) + nbins_float = math_ops.cast(nbins, values.dtype) + + # Map tensor values that fall within value_range to [0, 1]. + scaled_values = math_ops.truediv( + values - value_range[0], + value_range[1] - value_range[0], + name='scaled_values') + + # map tensor values within the open interval value_range to {0,.., nbins-1}, + # values outside the open interval will be zero or less, or nbins or more. + indices = math_ops.floor(nbins_float * scaled_values, name='indices') + + # Clip edge cases (e.g. value = value_range[1]) or "outliers." + indices = math_ops.cast( + clip_ops.clip_by_value(indices, 0, nbins_float - 1), dtypes.int32) + return array_ops.reshape(indices, shape) + + +@tf_export('histogram_fixed_width') +@dispatch.add_dispatch_support +def histogram_fixed_width(values, + value_range, + nbins=100, + dtype=dtypes.int32, + name=None): + """Return histogram of values. + + Given the tensor `values`, this operation returns a rank 1 histogram counting + the number of entries in `values` that fell into every bin. The bins are + equal width and determined by the arguments `value_range` and `nbins`. + + Args: + values: Numeric `Tensor`. + value_range: Shape [2] `Tensor` of same `dtype` as `values`. + values <= value_range[0] will be mapped to hist[0], + values >= value_range[1] will be mapped to hist[-1]. + nbins: Scalar `int32 Tensor`. Number of histogram bins. + dtype: dtype for returned histogram. + name: A name for this operation (defaults to 'histogram_fixed_width'). + + Returns: + A 1-D `Tensor` holding histogram of values. + + Raises: + TypeError: If any unsupported dtype is provided. + tf.errors.InvalidArgumentError: If value_range does not + satisfy value_range[0] < value_range[1]. + + Examples: + + >>> # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) + ... + >>> nbins = 5 + >>> value_range = [0.0, 5.0] + >>> new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] + >>> hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) + >>> hist.numpy() + array([2, 1, 1, 0, 2], dtype=int32) + """ + with ops.name_scope(name, 'histogram_fixed_width', + [values, value_range, nbins]) as name: + # pylint: disable=protected-access + return gen_math_ops._histogram_fixed_width( + values, value_range, nbins, dtype=dtype, name=name) + # pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..5ececc014fbff76aed3bfa220ed4d47ef20a6383 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad.py @@ -0,0 +1,378 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Contains Gradient functions for image ops.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import math_ops + + +@ops.RegisterGradient("ResizeNearestNeighbor") +def _ResizeNearestNeighborGrad(op: ops.Operation, grad): + """The derivatives for nearest neighbor resizing. + + Args: + op: The ResizeNearestNeighbor op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input and the output. + """ + image = op.inputs[0] + if image.get_shape()[1:3].is_fully_defined(): + image_shape = image.get_shape()[1:3] + else: + image_shape = array_ops.shape(image)[1:3] + + grads = gen_image_ops.resize_nearest_neighbor_grad( + grad, + image_shape, + align_corners=op.get_attr("align_corners"), + half_pixel_centers=op.get_attr("half_pixel_centers")) + return [grads, None] + + +@ops.RegisterGradient("ResizeBilinear") +def _ResizeBilinearGrad(op: ops.Operation, grad): + """The derivatives for bilinear resizing. + + Args: + op: The ResizeBilinear op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input. + """ + grad0 = gen_image_ops.resize_bilinear_grad( + grad, + op.inputs[0], + align_corners=op.get_attr("align_corners"), + half_pixel_centers=op.get_attr("half_pixel_centers")) + return [grad0, None] + + +@ops.RegisterGradient("ScaleAndTranslate") +def _ScaleAndTranslateGrad(op, grad): + """The derivatives for ScaleAndTranslate transformation op. + + Args: + op: The ScaleAndTranslate op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input. + """ + + grad0 = gen_image_ops.scale_and_translate_grad( + grad, + op.inputs[0], + op.inputs[2], + op.inputs[3], + kernel_type=op.get_attr("kernel_type"), + antialias=op.get_attr("antialias")) + return [grad0, None, None, None] + + +@ops.RegisterGradient("ResizeBicubic") +def _ResizeBicubicGrad(op: ops.Operation, grad): + """The derivatives for bicubic resizing. + + Args: + op: The ResizeBicubic op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input. + """ + allowed_types = [dtypes.float32, dtypes.float64] + grad0 = None + if op.inputs[0].dtype in allowed_types: + grad0 = gen_image_ops.resize_bicubic_grad( + grad, + op.inputs[0], + align_corners=op.get_attr("align_corners"), + half_pixel_centers=op.get_attr("half_pixel_centers")) + return [grad0, None] + + +@ops.RegisterGradient("CropAndResize") +def _CropAndResizeGrad(op: ops.Operation, grad): + """The derivatives for crop_and_resize. + + We back-propagate to the image only when the input image tensor has floating + point dtype but we always back-propagate to the input boxes tensor. + + Args: + op: The CropAndResize op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input image, boxes, as well as the always-None + gradients w.r.t. box_ind and crop_size. + """ + image = op.inputs[0] + if image.get_shape().is_fully_defined(): + image_shape = image.get_shape().as_list() + else: + image_shape = array_ops.shape(image) + + allowed_types = [dtypes.float16, dtypes.float32, dtypes.float64] + if op.inputs[0].dtype in allowed_types: + # pylint: disable=protected-access + grad0 = gen_image_ops.crop_and_resize_grad_image( + grad, op.inputs[1], op.inputs[2], image_shape, T=op.get_attr("T"), + method=op.get_attr("method")) + # pylint: enable=protected-access + else: + grad0 = None + + # `grad0` is the gradient to the input image pixels and it + # has been implemented for nearest neighbor and bilinear sampling + # respectively. `grad1` is the gradient to the input crop boxes' coordinates. + # When using nearest neighbor sampling, the gradient to crop boxes' + # coordinates are not well defined. In practice, we still approximate + # grad1 using the gradient derived from bilinear sampling. + grad1 = gen_image_ops.crop_and_resize_grad_boxes( + grad, op.inputs[0], op.inputs[1], op.inputs[2]) + + return [grad0, grad1, None, None] + + +def _CustomReciprocal(x): + """Wrapper function around `math_ops.div_no_nan()` to perform a "safe" reciprocal incase the input is zero. Avoids divide by zero and NaNs. + + Input: + x -> input tensor to be reciprocat-ed. + Returns: + x_reciprocal -> reciprocal of x without NaNs. + """ + return math_ops.div_no_nan(math_ops.cast(1.0, x.dtype), x) + + +@ops.RegisterGradient("RGBToHSV") +def _RGBToHSVGrad(op: ops.Operation, grad): + """The gradients for `rgb_to_hsv` operation. + + This function is a piecewise continuous function as defined here: + https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB + We perform the multivariate derivative and compute all partial derivatives + separately before adding them in the end. Formulas are given before each + partial derivative calculation. + + Args: + op: The `rgb_to_hsv` `Operation` that we are differentiating. + grad: Gradient with respect to the output of the `rgb_to_hsv` op. + + Returns: + Gradients with respect to the input of `rgb_to_hsv`. + """ + # Input Channels + reds = op.inputs[0][..., 0] + greens = op.inputs[0][..., 1] + blues = op.inputs[0][..., 2] + # Output Channels + saturation = op.outputs[0][..., 1] + value = op.outputs[0][..., 2] + + dtype = op.inputs[0].dtype + + # Mask/Indicator for max and min values of each pixel. + # Arbitrary assignment in case of tie breakers with R>G>B. + # Max values + red_biggest = math_ops.cast((reds >= blues) & \ + (reds >= greens), dtype) + green_biggest = math_ops.cast((greens > reds) & \ + (greens >= blues), dtype) + blue_biggest = math_ops.cast((blues > reds) & \ + (blues > greens), dtype) + # Min values + red_smallest = math_ops.cast((reds < blues) & \ + (reds < greens), dtype) + green_smallest = math_ops.cast((greens <= reds) & \ + (greens < blues), dtype) + blue_smallest = math_ops.cast((blues <= reds) & \ + (blues <= greens), dtype) + + # Derivatives of R, G, B wrt Value slice + dv_dr = red_biggest + dv_dg = green_biggest + dv_db = blue_biggest + + # Derivatives of R, G, B wrt Saturation slice + + # The first term in the addition is the case when the corresponding color + # from (r,g,b) was "MAX" + # -> derivative = MIN/square(MAX), MIN could be one of the other two colors + # The second term is the case when the corresponding color from + # (r,g,b) was "MIN" + # -> derivative = -1/MAX, MAX could be one of the other two colours. + ds_dr = math_ops.cast(reds > 0, dtype) * math_ops.add( + red_biggest * math_ops.add(green_smallest * greens, blue_smallest * blues) + * _CustomReciprocal(math_ops.square(reds)), red_smallest * -1 * + _CustomReciprocal((green_biggest * greens) + (blue_biggest * blues))) + ds_dg = math_ops.cast(greens > 0, dtype) * math_ops.add( + green_biggest * math_ops.add(red_smallest * reds, blue_smallest * blues) * + _CustomReciprocal(math_ops.square(greens)), green_smallest * -1 * + _CustomReciprocal((red_biggest * reds) + (blue_biggest * blues))) + ds_db = math_ops.cast(blues > 0, dtype) * math_ops.add( + blue_biggest * math_ops.add(green_smallest * greens, red_smallest * reds) + * _CustomReciprocal(math_ops.square(blues)), blue_smallest * -1 * + _CustomReciprocal((green_biggest * greens) + (red_biggest * reds))) + + # Derivatives of R, G, B wrt Hue slice + + # Need to go case by case for each color. + # for red, dh_dr -> dh_dr_1 + dh_dr_2 + dh_dr_3 + dh_dr_4 + dh_dr_5 + # dh_dr_1 -> + # if red was MAX, then derivative = 60 * -1 * (G-B)/square(MAX-MIN) == 60 *\ + # -1 * (greens-blues) * reciprocal(square(saturation)) * \ + # reciprocal(square(value)) + # elif green was MAX, there are two subcases + # ie when red was MIN and when red was NOT MIN + # dh_dr_2 -> + # if red was MIN (use UV rule) -> 60 * ((1 * -1/(MAX-MIN)) +\ + # (B-R)*(-1/square(MAX-MIN) * -1)) == 60 * (blues - greens) *\ + # reciprocal(square(reds - greens)) + # dh_dr_3 -> + # if red was NOT MIN -> 60 * -1/MAX-MIN == -60 * reciprocal(greens-blues) + # elif blue was MAX, there are two subcases + # dh_dr_4 -> + # if red was MIN (similarly use the UV rule) -> 60 * (blues - greens) *\ + # reciprocal(square(blues - reds)) + # dh_dr_5 -> + # if red was NOT MIN -> 60 * 1/MAX-MIN == 60 * reciprocal(blues-greens) + dh_dr_1 = 60 * ( + math_ops.cast(reds > 0, dtype) * red_biggest * -1 * + (greens - blues) * _CustomReciprocal(math_ops.square(saturation)) * + _CustomReciprocal(math_ops.square(value))) + dh_dr_2 = 60 * ( + math_ops.cast(greens > 0, dtype) * green_biggest * red_smallest * + (blues - greens) * _CustomReciprocal(math_ops.square(reds - greens))) + dh_dr_3 = 60 * ( + math_ops.cast(greens > 0, dtype) * green_biggest * blue_smallest * -1 * + _CustomReciprocal(greens - blues)) + dh_dr_4 = 60 * ( + math_ops.cast(blues > 0, dtype) * blue_biggest * red_smallest * + (blues - greens) * _CustomReciprocal(math_ops.square(blues - reds))) + dh_dr_5 = 60 * ( + math_ops.cast(blues > 0, dtype) * blue_biggest * green_smallest * + _CustomReciprocal(blues - greens)) + + dh_dr = dh_dr_1 + dh_dr_2 + dh_dr_3 + dh_dr_4 + dh_dr_5 + # Converting from degrees to [0,1] scale as specified in + # https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_hsv + dh_dr = dh_dr / 360 + + # for green, dh_dg -> dh_dg_1 + dh_dg_2 + dh_dg_3 + dh_dg_4 + dh_dg_5 + # dh_dg_1 -> + # if green was MAX, then derivative = 60 * -1 * (B-R)/square(MAX-MIN) == 60 *\ + # -1 * (blues - reds) * reciprocal(square(saturation)) * \ + # reciprocal(square(value)) + # elif red was MAX, there are two subcases ie + # when green was MIN and when green was NOT MIN + # dh_dg_2 -> + # if green was MIN (use UV rule) -> 60 * ((1 * 1/(MAX-MIN)) + \ + # (greens-blues) * (-1/square(MAX-MIN) * -1)) == 60 * \ + # ((reciprocal(reds-greens) + (greens-blues) * \ + # reciprocal(square(reds-greens)))) + # dh_dg_3 -> + # if green was NOT MIN -> 60 * 1/MAX-MIN == 60 * reciprocal(reds - blues) + # elif blue was MAX, there are two subcases + # dh_dg_4 -> + # if green was MIN (similarly use the UV rule) -> 60 * -1 * \ + # (reciprocal(blues - greens) + (reds-greens)* -1 * \ + # reciprocal(square(blues-greens))) + # dh_dr_5 -> + # if green was NOT MIN -> 60 * -1/MAX-MIN == -60 * reciprocal(blues - reds) + dh_dg_1 = 60 * ( + math_ops.cast(greens > 0, dtype) * green_biggest * -1 * + (blues - reds) * _CustomReciprocal(math_ops.square(saturation)) * + _CustomReciprocal(math_ops.square(value))) + dh_dg_2 = 60 * ( + math_ops.cast(reds > 0, dtype) * red_biggest * green_smallest * + (reds - blues) * _CustomReciprocal(math_ops.square(reds - greens))) + dh_dg_3 = 60 * ( + math_ops.cast(reds > 0, dtype) * red_biggest * blue_smallest * + _CustomReciprocal(reds - blues)) + dh_dg_4 = 60 * ( + math_ops.cast(blues > 0, dtype) * blue_biggest * green_smallest * + (reds - blues) * _CustomReciprocal(math_ops.square(blues - greens))) + dh_dg_5 = 60 * ( + math_ops.cast(blues > 0, dtype) * blue_biggest * red_smallest * -1 * + _CustomReciprocal(blues - reds)) + + dh_dg = dh_dg_1 + dh_dg_2 + dh_dg_3 + dh_dg_4 + dh_dg_5 + # Converting from degrees to [0,1] scale as specified in + # https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_hsv + dh_dg = dh_dg / 360 + + # for blue, dh_db -> dh_db_1 + dh_db_2 + dh_db_3 + dh_db_4 + dh_db_5 + # dh_db_1 -> + # if blue was MAX, then derivative = 60 * -1 * (R-G)/square(MAX-MIN) == 60 *\ + # -1 * reciprocal(square(saturation)) * reciprocal(square(value)) + # elif red was MAX, there are two subcases + # ie when blue was MIN and when blue was NOT MIN + # dh_dg_2 -> + # if blue was MIN (use UV rule) -> 60 * ((1 * -1/(MAX-MIN)) + \ + # (greens-blues) * (-1/square(MAX-MIN) * -1)) == 60 * (greens - reds) *\ + # reciprocal(square(reds - blues)) + # dh_dg_3 -> + # if blue was NOT MIN -> 60 * -1/MAX-MIN == 60 * -1 * \ + # reciprocal(reds - greens) + # elif green was MAX, there are two subcases + # dh_dg_4 -> + # if blue was MIN (similarly use the UV rule) -> 60 * -1 * \ + # (reciprocal(greens - blues) + (blues - reds) * -1 * \ + # reciprocal(square(greens - blues))) + # dh_dr_5 -> + # if blue was NOT MIN -> 60 * 1/MAX-MIN == 60 * reciprocal(greens - reds) + dh_db_1 = 60 * ( + math_ops.cast(blues > 0, dtype) * blue_biggest * -1 * + (reds - greens) * _CustomReciprocal(math_ops.square(saturation)) * + _CustomReciprocal(math_ops.square(value))) + dh_db_2 = 60 * ( + math_ops.cast(reds > 0, dtype) * red_biggest * blue_smallest * + (greens - reds) * _CustomReciprocal(math_ops.square(reds - blues))) + dh_db_3 = 60 * ( + math_ops.cast(reds > 0, dtype) * red_biggest * green_smallest * -1 * + _CustomReciprocal(reds - greens)) + dh_db_4 = 60 * ( + math_ops.cast(greens > 0, dtype) * green_biggest * blue_smallest * + (greens - reds) * _CustomReciprocal(math_ops.square(greens - blues))) + dh_db_5 = 60 * ( + math_ops.cast(greens > 0, dtype) * green_biggest * red_smallest * + _CustomReciprocal(greens - reds)) + + dh_db = dh_db_1 + dh_db_2 + dh_db_3 + dh_db_4 + dh_db_5 + # Converting from degrees to [0,1] scale as specified in + # https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_hsv + dh_db = dh_db / 360 + + # Gradients wrt to inputs + dv_drgb = array_ops_stack.stack( + [grad[..., 2] * dv_dr, grad[..., 2] * dv_dg, grad[..., 2] * dv_db], + axis=-1) + ds_drgb = array_ops_stack.stack( + [grad[..., 1] * ds_dr, grad[..., 1] * ds_dg, grad[..., 1] * ds_db], + axis=-1) + dh_drgb = array_ops_stack.stack( + [grad[..., 0] * dh_dr, grad[..., 0] * dh_dg, grad[..., 0] * dh_db], + axis=-1) + + gradient_input = math_ops.add(math_ops.add(dv_drgb, ds_drgb), dh_drgb) + return gradient_input diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..fc84f3054f96560d997cae20778517650f42e70e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_grad_test_base.py @@ -0,0 +1,648 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for Python ops defined in image_grad.py.""" + +from absl.testing import parameterized +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +@test_util.for_all_test_methods(test_util.disable_xla, + 'align_corners=False not supported by XLA') +class ResizeNearestNeighborOpTestBase(test.TestCase): + + TYPES = [np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype] + + def testShapeIsCorrectAfterOp(self): + in_shape = [1, 2, 2, 1] + out_shape = [1, 4, 6, 1] + + for nptype in self.TYPES: + x = np.arange(0, 4).reshape(in_shape).astype(nptype) + + input_tensor = constant_op.constant(x, shape=in_shape) + resize_out = image_ops.resize_nearest_neighbor(input_tensor, + out_shape[1:3]) + with self.cached_session(): + self.assertEqual(out_shape, list(resize_out.get_shape())) + resize_out = self.evaluate(resize_out) + self.assertEqual(out_shape, list(resize_out.shape)) + + def testGradFromResizeToLargerInBothDims(self): + in_shape = [1, 2, 3, 1] + out_shape = (1, 4, 6, 1) + + for nptype in self.TYPES: + x = np.arange(0, 6).reshape(in_shape).astype(nptype) + + def resize_nn(t, shape=out_shape): + return image_ops.resize_nearest_neighbor(t, shape[1:3]) + + with self.cached_session(): + input_tensor = constant_op.constant(x, shape=in_shape) + err = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient( + resize_nn, [input_tensor], delta=1 / 8)) + self.assertLess(err, 1e-3) + + def testGradFromResizeToSmallerInBothDims(self): + in_shape = [1, 4, 6, 1] + out_shape = (1, 2, 3, 1) + + for nptype in self.TYPES: + x = np.arange(0, 24).reshape(in_shape).astype(nptype) + + def resize_nn(t, shape=out_shape): + return image_ops.resize_nearest_neighbor(t, shape[1:3]) + + with self.cached_session(): + input_tensor = constant_op.constant(x, shape=in_shape) + err = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient( + resize_nn, [input_tensor], delta=1 / 8)) + self.assertLess(err, 1e-3) + + def testCompareGpuVsCpu(self): + in_shape = [1, 4, 6, 3] + out_shape = (1, 8, 16, 3) + + for nptype in self.TYPES: + x = np.arange(0, np.prod(in_shape)).reshape(in_shape).astype(nptype) + for align_corners in [True, False]: + + def resize_nn(t, shape=out_shape, align_corners=align_corners): + return image_ops.resize_nearest_neighbor( + t, shape[1:3], align_corners=align_corners) + + with self.cached_session(use_gpu=False): + input_tensor = constant_op.constant(x, shape=in_shape) + grad_cpu = gradient_checker_v2.compute_gradient( + resize_nn, [input_tensor], delta=1 / 8) + + with self.cached_session(): + input_tensor = constant_op.constant(x, shape=in_shape) + grad_gpu = gradient_checker_v2.compute_gradient( + resize_nn, [input_tensor], delta=1 / 8) + + self.assertAllClose(grad_cpu, grad_gpu, rtol=1e-5, atol=1e-5) + + +class ResizeBilinearOpTestBase(test.TestCase, parameterized.TestCase): + + def _itGen(self, smaller_shape, larger_shape): + up_sample = (smaller_shape, larger_shape) + down_sample = (larger_shape, smaller_shape) + pass_through = (larger_shape, larger_shape) + shape_pairs = (up_sample, down_sample, pass_through) + # Align corners is deprecated in TF2.0, but align_corners==False is not + # supported by XLA. + options = [(True, False)] + if not test_util.is_xla_enabled(): + options += [(False, True), (False, False)] + for align_corners, half_pixel_centers in options: + for in_shape, out_shape in shape_pairs: + yield in_shape, out_shape, align_corners, half_pixel_centers + + def _getJacobians(self, + in_shape, + out_shape, + align_corners=False, + half_pixel_centers=False, + dtype=np.float32, + use_gpu=False, + force_gpu=False): + with self.cached_session(use_gpu=use_gpu, force_gpu=force_gpu): + # Input values should not influence gradients + x = np.arange(np.prod(in_shape)).reshape(in_shape).astype(dtype) + input_tensor = constant_op.constant(x, shape=in_shape) + + def func(in_tensor): + return image_ops.resize_bilinear( + in_tensor, + out_shape[1:3], + align_corners=align_corners, + half_pixel_centers=half_pixel_centers) + + return gradient_checker_v2.compute_gradient(func, [input_tensor]) + + @parameterized.parameters(set((True, context.executing_eagerly()))) + def _testShapesParameterized(self, use_tape): + + TEST_CASES = [[1, 1], [2, 3], [5, 4]] # pylint: disable=invalid-name + + for batch_size, channel_count in TEST_CASES: + smaller_shape = [batch_size, 2, 3, channel_count] + larger_shape = [batch_size, 4, 6, channel_count] + for in_shape, out_shape, _, _ in self._itGen(smaller_shape, larger_shape): + with test_util.AbstractGradientTape(use_tape=use_tape) as tape: + # Input values should not influence shapes + x = np.arange(np.prod(in_shape)).reshape(in_shape).astype(np.float32) + input_tensor = constant_op.constant(x, shape=in_shape) + tape.watch(input_tensor) + resized_tensor = image_ops.resize_bilinear(input_tensor, + out_shape[1:3]) + self.assertEqual(out_shape, list(resized_tensor.get_shape())) + + grad_tensor = tape.gradient(resized_tensor, input_tensor) + self.assertEqual(in_shape, list(grad_tensor.get_shape())) + with self.cached_session(): + resized_values = self.evaluate(resized_tensor) + self.assertEqual(out_shape, list(resized_values.shape)) + grad_values = self.evaluate(grad_tensor) + self.assertEqual(in_shape, list(grad_values.shape)) + + @parameterized.parameters({ + 'batch_size': 1, + 'channel_count': 1 + }, { + 'batch_size': 4, + 'channel_count': 3 + }, { + 'batch_size': 3, + 'channel_count': 2 + }) + def testGradients(self, batch_size, channel_count): + smaller_shape = [batch_size, 2, 3, channel_count] + larger_shape = [batch_size, 5, 6, channel_count] + for in_shape, out_shape, align_corners, half_pixel_centers in \ + self._itGen(smaller_shape, larger_shape): + jacob_a, jacob_n = self._getJacobians(in_shape, out_shape, align_corners, + half_pixel_centers) + threshold = 5e-3 + self.assertAllClose(jacob_a, jacob_n, threshold, threshold) + + def testTypes(self): + in_shape = [1, 4, 6, 1] + out_shape = [1, 2, 3, 1] + for use_gpu in [False, True]: + for dtype in [ + np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype + ]: + jacob_a, jacob_n = self._getJacobians( + in_shape, out_shape, dtype=dtype, use_gpu=use_gpu) + if dtype in (np.float16, dtypes.bfloat16.as_numpy_dtype): + # Compare fp16/bf16 analytical gradients to fp32 numerical gradients, + # since fp16/bf16 numerical gradients are too imprecise unless great + # care is taken with choosing the inputs and the delta. This is + # a weaker, but pragmatic, check (in particular, it does not test + # the op itself, only its gradient). + _, jacob_n = self._getJacobians( + in_shape, out_shape, dtype=np.float32, use_gpu=use_gpu) + threshold = 1e-3 + if dtype == np.float64: + threshold = 1e-5 + self.assertAllClose(jacob_a, jacob_n, threshold, threshold) + + @parameterized.parameters(set((True, context.executing_eagerly()))) + def testGradOnUnsupportedType(self, use_tape): + in_shape = [1, 4, 6, 1] + out_shape = [1, 2, 3, 1] + + with test_util.AbstractGradientTape(use_tape=use_tape) as tape: + x = np.arange(0, 24).reshape(in_shape).astype(np.uint8) + input_tensor = constant_op.constant(x, shape=in_shape) + tape.watch(input_tensor) + resize_out = image_ops.resize_bilinear(input_tensor, out_shape[1:3]) + with self.cached_session(): + grad = tape.gradient(resize_out, [input_tensor]) + self.assertEqual([None], grad) + + def _gpuVsCpuCase(self, in_shape, out_shape, align_corners, + half_pixel_centers, dtype): + grad = {} + for use_gpu in [False, True]: + grad[use_gpu] = self._getJacobians( + in_shape, + out_shape, + align_corners, + half_pixel_centers, + dtype=dtype, + use_gpu=use_gpu) + threshold = 1e-4 + # Note that this is comparing both analytical and numerical Jacobians + self.assertAllClose(grad[False], grad[True], rtol=threshold, atol=threshold) + + @parameterized.parameters({ + 'batch_size': 1, + 'channel_count': 1 + }, { + 'batch_size': 2, + 'channel_count': 3 + }, { + 'batch_size': 5, + 'channel_count': 4 + }) + def testCompareGpuVsCpu(self, batch_size, channel_count): + smaller_shape = [batch_size, 4, 6, channel_count] + larger_shape = [batch_size, 8, 16, channel_count] + for params in self._itGen(smaller_shape, larger_shape): + self._gpuVsCpuCase(*params, dtype=np.float32) + + def testCompareGpuVsCpuFloat64(self): + in_shape = [1, 5, 7, 1] + out_shape = [1, 9, 11, 1] + # Note that there is no 16-bit floating-point format registered for GPU + self._gpuVsCpuCase( + in_shape, + out_shape, + align_corners=True, + half_pixel_centers=False, + dtype=np.float64) + + +class ResizeBicubicOpTestBase(test.TestCase, parameterized.TestCase): + """Tests resize bicubic ops.""" + + def testShapeIsCorrectAfterOp(self): + in_shape = [1, 2, 2, 1] + out_shape = [1, 4, 6, 1] + + x = np.arange(0, 4).reshape(in_shape).astype(np.float32) + + for align_corners in [True, False]: + input_tensor = constant_op.constant(x, shape=in_shape) + resize_out = image_ops.resize_bicubic( + input_tensor, out_shape[1:3], align_corners=align_corners) + with self.cached_session(): + self.assertEqual(out_shape, list(resize_out.get_shape())) + resize_out = self.evaluate(resize_out) + self.assertEqual(out_shape, list(resize_out.shape)) + + def testGradFromResizeToLargerInBothDims(self): + in_shape = [1, 2, 3, 1] + out_shape = [1, 4, 6, 1] + + x = np.arange(0, 6).reshape(in_shape).astype(np.float32) + input_tensor = constant_op.constant(x, shape=in_shape) + + for align_corners in [True, False]: + + def func(input_tensor, align_corners=align_corners): + return image_ops.resize_bicubic( + input_tensor, out_shape[1:3], align_corners=align_corners) + + with self.cached_session(): + err = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(func, [input_tensor])) + + self.assertLess(err, 1e-3) + + def testGradFromResizeToSmallerInBothDims(self): + in_shape = [1, 4, 6, 1] + out_shape = [1, 2, 3, 1] + + x = np.arange(0, 24).reshape(in_shape).astype(np.float32) + input_tensor = constant_op.constant(x, shape=in_shape) + + for align_corners in [True, False]: + + def func(input_tensor, align_corners=align_corners): + return image_ops.resize_bicubic( + input_tensor, out_shape[1:3], align_corners=align_corners) + + with self.cached_session(): + err = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(func, [input_tensor])) + + self.assertLess(err, 1e-3) + + @parameterized.parameters(set((True, context.executing_eagerly()))) + def testGradOnUnsupportedType(self, use_tape): + with test_util.AbstractGradientTape(use_tape=use_tape) as tape: + in_shape = [1, 4, 6, 1] + out_shape = [1, 2, 3, 1] + + x = np.arange(0, 24).reshape(in_shape).astype(np.uint8) + input_tensor = constant_op.constant(x, shape=in_shape) + tape.watch(input_tensor) + + resize_out = image_ops.resize_bicubic(input_tensor, out_shape[1:3]) + with self.cached_session(): + grad = tape.gradient(resize_out, [input_tensor]) + self.assertEqual([None], grad) + + +class ScaleAndTranslateOpTestBase(test.TestCase): + """Tests scale and translate op.""" + + def testGrads(self): + in_shape = [1, 2, 3, 1] + out_shape = [1, 4, 6, 1] + + x = np.arange(0, 6).reshape(in_shape).astype(np.float32) + + kernel_types = [ + 'lanczos1', 'lanczos3', 'lanczos5', 'gaussian', 'box', 'triangle', + 'keyscubic', 'mitchellcubic' + ] + scales = [(1.0, 1.0), (0.37, 0.47), (2.1, 2.1)] + translations = [(0.0, 0.0), (3.14, 1.19), (2.1, 3.1), (100.0, 200.0)] + for scale in scales: + for translation in translations: + for kernel_type in kernel_types: + for antialias in [True, False]: + with self.cached_session(): + input_tensor = constant_op.constant(x, shape=in_shape) + + def scale_trans(input_tensor, + scale=scale, + translation=translation, + kernel_type=kernel_type, + antialias=antialias): + # pylint: disable=cell-var-from-loop + return image_ops.scale_and_translate( + input_tensor, + out_shape[1:3], + scale=constant_op.constant(scale), + translation=constant_op.constant(translation), + kernel_type=kernel_type, + antialias=antialias) + + err = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(scale_trans, + [input_tensor])) + + self.assertLess(err, 1e-3) + + def testIdentityGrads(self): + """Tests that Gradients for 1.0 scale should be ones for some kernels.""" + in_shape = [1, 2, 3, 1] + out_shape = [1, 4, 6, 1] + + x = np.arange(0, 6).reshape(in_shape).astype(np.float32) + + kernel_types = ['lanczos1', 'lanczos3', 'lanczos5', 'triangle', 'keyscubic'] + scale = (1.0, 1.0) + translation = (0.0, 0.0) + antialias = True + for kernel_type in kernel_types: + with self.cached_session(): + input_tensor = constant_op.constant(x, shape=in_shape) + with backprop.GradientTape() as tape: + tape.watch(input_tensor) + scale_and_translate_out = image_ops.scale_and_translate( + input_tensor, + out_shape[1:3], + scale=constant_op.constant(scale), + translation=constant_op.constant(translation), + kernel_type=kernel_type, + antialias=antialias) + grad = tape.gradient(scale_and_translate_out, input_tensor)[0] + grad_v = self.evaluate(grad) + self.assertAllClose(np.ones_like(grad_v), grad_v) + + +class CropAndResizeOpTestBase(test.TestCase): + + def testShapeIsCorrectAfterOp(self): + batch = 2 + image_height = 3 + image_width = 4 + crop_height = 4 + crop_width = 5 + depth = 2 + num_boxes = 2 + + image_shape = [batch, image_height, image_width, depth] + crop_size = [crop_height, crop_width] + crops_shape = [num_boxes, crop_height, crop_width, depth] + + image = np.arange(0, batch * image_height * image_width * + depth).reshape(image_shape).astype(np.float32) + boxes = np.array([[0, 0, 1, 1], [.1, .2, .7, .8]], dtype=np.float32) + box_ind = np.array([0, 1], dtype=np.int32) + + crops = image_ops.crop_and_resize( + constant_op.constant(image, shape=image_shape), + constant_op.constant(boxes, shape=[num_boxes, 4]), + constant_op.constant(box_ind, shape=[num_boxes]), + constant_op.constant(crop_size, shape=[2])) + with self.session(): + self.assertEqual(crops_shape, list(crops.get_shape())) + crops = self.evaluate(crops) + self.assertEqual(crops_shape, list(crops.shape)) + + def _randomUniformAvoidAnchors(self, low, high, anchors, radius, num_samples): + """Generate samples that are far enough from a set of anchor points. + + We generate uniform samples in [low, high], then reject those that are less + than radius away from any point in anchors. We stop after we have accepted + num_samples samples. + + Args: + low: The lower end of the interval. + high: The upper end of the interval. + anchors: A list of length num_crops with anchor points to avoid. + radius: Distance threshold for the samples from the anchors. + num_samples: How many samples to produce. + + Returns: + samples: A list of length num_samples with the accepted samples. + """ + self.assertTrue(low < high) + self.assertTrue(radius >= 0) + num_anchors = len(anchors) + # Make sure that at least half of the interval is not forbidden. + self.assertTrue(2 * radius * num_anchors < 0.5 * (high - low)) + anchors = np.reshape(anchors, num_anchors) + samples = [] + while len(samples) < num_samples: + sample = np.random.uniform(low, high) + if np.all(np.fabs(sample - anchors) > radius): + samples.append(sample) + return samples + + def testGradRandomBoxes(self): + """Test that the gradient is correct for randomly generated boxes. + + The mapping is piecewise differentiable with respect to the box coordinates. + The points where the function is not differentiable are those which are + mapped to image pixels, i.e., the normalized y coordinates in + np.linspace(0, 1, image_height) and normalized x coordinates in + np.linspace(0, 1, image_width). Make sure that the box coordinates are + sufficiently far away from those rectangular grid centers that are points of + discontinuity, so that the finite difference Jacobian is close to the + computed one. + """ + np.random.seed(1) # Make it reproducible. + delta = 1e-3 + radius = 2 * delta + low, high = -0.5, 1.5 # Also covers the case of extrapolation. + + image_height = 4 + for image_width in range(1, 3): + for crop_height in range(1, 3): + for crop_width in range(2, 4): + for depth in range(1, 3): + for num_boxes in range(1, 3): + + batch = num_boxes + image_shape = [batch, image_height, image_width, depth] + crop_size = [crop_height, crop_width] + + image = np.arange(0, batch * image_height * image_width * + depth).reshape(image_shape).astype(np.float32) + boxes = [] + for _ in range(num_boxes): + # pylint: disable=unbalanced-tuple-unpacking + y1, y2 = self._randomUniformAvoidAnchors( + low, high, np.linspace(0, 1, image_height), radius, 2) + x1, x2 = self._randomUniformAvoidAnchors( + low, high, np.linspace(0, 1, image_width), radius, 2) + # pylint: enable=unbalanced-tuple-unpacking + boxes.append([y1, x1, y2, x2]) + + boxes = np.array(boxes, dtype=np.float32) + box_ind = np.arange(batch, dtype=np.int32) + + image_tensor = constant_op.constant(image, shape=image_shape) + boxes_tensor = constant_op.constant(boxes, shape=[num_boxes, 4]) + box_ind_tensor = constant_op.constant(box_ind, shape=[num_boxes]) + + def crop_resize(image_tensor, boxes_tensor): + # pylint: disable=cell-var-from-loop + return image_ops.crop_and_resize( + image_tensor, boxes_tensor, box_ind_tensor, + constant_op.constant(crop_size, shape=[2])) + + with test_util.device(use_gpu=True): + with self.cached_session(): + # pylint: disable=cell-var-from-loop + if (config.is_op_determinism_enabled() and + test_util.is_gpu_available()): + with self.assertRaises(errors_impl.UnimplementedError): + gradient_checker_v2.compute_gradient( + lambda x: crop_resize(x, boxes_tensor), + [image_tensor]) + with self.assertRaises(errors_impl.UnimplementedError): + gradient_checker_v2.compute_gradient( + lambda x: crop_resize(image_tensor, x), + [boxes_tensor]) + else: + err1 = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient( + lambda x: crop_resize(x, boxes_tensor), + [image_tensor])) + err2 = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient( + lambda x: crop_resize(image_tensor, x), + [boxes_tensor])) + err = max(err1, err2) + self.assertLess(err, 2e-3) + + +@test_util.run_all_in_graph_and_eager_modes +class RGBToHSVOpTestBase(test.TestCase): + + TYPES = [np.float32, np.float64] + + def testShapeIsCorrectAfterOp(self): + in_shape = [2, 20, 30, 3] + out_shape = [2, 20, 30, 3] + + for nptype in self.TYPES: + x = np.random.randint(0, high=255, size=[2, 20, 30, 3]).astype(nptype) + rgb_input_tensor = constant_op.constant(x, shape=in_shape) + hsv_out = gen_image_ops.rgb_to_hsv(rgb_input_tensor) + with self.cached_session(): + self.assertEqual(out_shape, list(hsv_out.get_shape())) + hsv_out = self.evaluate(hsv_out) + self.assertEqual(out_shape, list(hsv_out.shape)) + + def testRGBToHSVGradSimpleCase(self): + + def f(x): + return gen_image_ops.rgb_to_hsv(x) + + for nptype in self.TYPES: + # Building a simple input tensor to avoid any discontinuity + x = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, + 0.9]]).astype(nptype) + rgb_input_tensor = constant_op.constant(x, shape=x.shape) + # Computing Analytical and Numerical gradients of f(x) + analytical, numerical = gradient_checker_v2.compute_gradient( + f, [rgb_input_tensor]) + self.assertAllClose(numerical, analytical, atol=1e-4) + + def testRGBToHSVGradRandomCase(self): + + def f(x): + return gen_image_ops.rgb_to_hsv(x) + + np.random.seed(0) + # Building a simple input tensor to avoid any discontinuity + x = np.random.rand(1, 5, 5, 3).astype(np.float32) + rgb_input_tensor = constant_op.constant(x, shape=x.shape) + # Computing Analytical and Numerical gradients of f(x) + self.assertLess( + gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(f, [rgb_input_tensor])), 1e-4) + + def testRGBToHSVGradSpecialCaseRGreatest(self): + # This test tests a specific subset of the input space + # with a dummy function implemented with native TF operations. + in_shape = [2, 10, 20, 3] + + def f(x): + return gen_image_ops.rgb_to_hsv(x) + + def f_dummy(x): + # This dummy function is a implementation of RGB to HSV using + # primitive TF functions for one particular case when R>G>B. + r = x[..., 0] + g = x[..., 1] + b = x[..., 2] + # Since MAX = r and MIN = b, we get the following h,s,v values. + v = r + s = 1 - math_ops.div_no_nan(b, r) + h = 60 * math_ops.div_no_nan(g - b, r - b) + h = h / 360 + return array_ops_stack.stack([h, s, v], axis=-1) + + # Building a custom input tensor where R>G>B + x_reds = np.ones((in_shape[0], in_shape[1], in_shape[2])).astype(np.float32) + x_greens = 0.5 * np.ones( + (in_shape[0], in_shape[1], in_shape[2])).astype(np.float32) + x_blues = 0.2 * np.ones( + (in_shape[0], in_shape[1], in_shape[2])).astype(np.float32) + x = np.stack([x_reds, x_greens, x_blues], axis=-1) + rgb_input_tensor = constant_op.constant(x, shape=in_shape) + + # Computing Analytical and Numerical gradients of f(x) + analytical, numerical = gradient_checker_v2.compute_gradient( + f, [rgb_input_tensor]) + # Computing Analytical and Numerical gradients of f_dummy(x) + analytical_dummy, numerical_dummy = gradient_checker_v2.compute_gradient( + f_dummy, [rgb_input_tensor]) + self.assertAllClose(numerical, analytical, atol=1e-4) + self.assertAllClose(analytical_dummy, analytical, atol=1e-4) + self.assertAllClose(numerical_dummy, numerical, atol=1e-4) + + +if __name__ == '__main__': + test.main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c938f4ad44af3935e7a1501cfad794fcf136db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops.py @@ -0,0 +1,305 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Image ops. + +The `tf.image` module contains various functions for image +processing and decoding-encoding Ops. + +Many of the encoding/decoding functions are also available in the +core `tf.io` module. + +## Image processing + +### Resizing + +The resizing Ops accept input images as tensors of several types. They always +output resized images as float32 tensors. + +The convenience function `tf.image.resize` supports both 4-D +and 3-D tensors as input and output. 4-D tensors are for batches of images, +3-D tensors for individual images. + +Resized images will be distorted if their original aspect ratio is not the +same as size. To avoid distortions see tf.image.resize_with_pad. + +* `tf.image.resize` +* `tf.image.resize_with_pad` +* `tf.image.resize_with_crop_or_pad` + +The Class `tf.image.ResizeMethod` provides various resize methods like +`bilinear`, `nearest_neighbor`. + +### Converting Between Colorspaces + +Image ops work either on individual images or on batches of images, depending on +the shape of their input Tensor. + +If 3-D, the shape is `[height, width, channels]`, and the Tensor represents one +image. If 4-D, the shape is `[batch_size, height, width, channels]`, and the +Tensor represents `batch_size` images. + +Currently, `channels` can usefully be 1, 2, 3, or 4. Single-channel images are +grayscale, images with 3 channels are encoded as either RGB or HSV. Images +with 2 or 4 channels include an alpha channel, which has to be stripped from the +image before passing the image to most image processing functions (and can be +re-attached later). + +Internally, images are either stored in as one `float32` per channel per pixel +(implicitly, values are assumed to lie in `[0,1)`) or one `uint8` per channel +per pixel (values are assumed to lie in `[0,255]`). + +TensorFlow can convert between images in RGB or HSV or YIQ. + +* `tf.image.rgb_to_grayscale`, `tf.image.grayscale_to_rgb` +* `tf.image.rgb_to_hsv`, `tf.image.hsv_to_rgb` +* `tf.image.rgb_to_yiq`, `tf.image.yiq_to_rgb` +* `tf.image.rgb_to_yuv`, `tf.image.yuv_to_rgb` +* `tf.image.image_gradients` +* `tf.image.convert_image_dtype` + +### Image Adjustments + +TensorFlow provides functions to adjust images in various ways: brightness, +contrast, hue, and saturation. Each adjustment can be done with predefined +parameters or with random parameters picked from predefined intervals. Random +adjustments are often useful to expand a training set and reduce overfitting. + +If several adjustments are chained it is advisable to minimize the number of +redundant conversions by first converting the images to the most natural data +type and representation. + +* `tf.image.adjust_brightness` +* `tf.image.adjust_contrast` +* `tf.image.adjust_gamma` +* `tf.image.adjust_hue` +* `tf.image.adjust_jpeg_quality` +* `tf.image.adjust_saturation` +* `tf.image.random_brightness` +* `tf.image.random_contrast` +* `tf.image.random_hue` +* `tf.image.random_saturation` +* `tf.image.per_image_standardization` + +### Working with Bounding Boxes + +* `tf.image.draw_bounding_boxes` +* `tf.image.combined_non_max_suppression` +* `tf.image.generate_bounding_box_proposals` +* `tf.image.non_max_suppression` +* `tf.image.non_max_suppression_overlaps` +* `tf.image.non_max_suppression_padded` +* `tf.image.non_max_suppression_with_scores` +* `tf.image.pad_to_bounding_box` +* `tf.image.sample_distorted_bounding_box` + +### Cropping + +* `tf.image.central_crop` +* `tf.image.crop_and_resize` +* `tf.image.crop_to_bounding_box` +* `tf.io.decode_and_crop_jpeg` +* `tf.image.extract_glimpse` +* `tf.image.random_crop` +* `tf.image.resize_with_crop_or_pad` + +### Flipping, Rotating and Transposing + +* `tf.image.flip_left_right` +* `tf.image.flip_up_down` +* `tf.image.random_flip_left_right` +* `tf.image.random_flip_up_down` +* `tf.image.rot90` +* `tf.image.transpose` + +## Image decoding and encoding + +TensorFlow provides Ops to decode and encode JPEG and PNG formats. Encoded +images are represented by scalar string Tensors, decoded images by 3-D uint8 +tensors of shape `[height, width, channels]`. (PNG also supports uint16.) + +Note: `decode_gif` returns a 4-D array `[num_frames, height, width, 3]` + +The encode and decode Ops apply to one image at a time. Their input and output +are all of variable size. If you need fixed size images, pass the output of +the decode Ops to one of the cropping and resizing Ops. + +* `tf.io.decode_bmp` +* `tf.io.decode_gif` +* `tf.io.decode_image` +* `tf.io.decode_jpeg` +* `tf.io.decode_and_crop_jpeg` +* `tf.io.decode_png` +* `tf.io.encode_jpeg` +* `tf.io.encode_png` + +API docstring: tensorflow.image +""" +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import linalg_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_image_ops import * +from tensorflow.python.ops.image_ops_impl import * +# pylint: enable=wildcard-import + +# TODO(drpng): remove these once internal use has discontinued. +# pylint: disable=unused-import +from tensorflow.python.ops.image_ops_impl import _Check3DImage +from tensorflow.python.ops.image_ops_impl import _ImageDimensions +# pylint: enable=unused-import + +_IMAGE_DTYPES = frozenset([ + dtypes.uint8, dtypes.int32, dtypes.int64, dtypes.float16, dtypes.float32, + dtypes.float64 +]) + + +def flat_transforms_to_matrices(transforms): + """Converts `tf.contrib.image` projective transforms to affine matrices. + + Note that the output matrices map output coordinates to input coordinates. For + the forward transformation matrix, call `tf.linalg.inv` on the result. + + Args: + transforms: Vector of length 8, or batches of transforms with shape `(N, + 8)`. + + Returns: + 3D tensor of matrices with shape `(N, 3, 3)`. The output matrices map the + *output coordinates* (in homogeneous coordinates) of each transform to the + corresponding *input coordinates*. + + Raises: + ValueError: If `transforms` have an invalid shape. + """ + with ops.name_scope("flat_transforms_to_matrices"): + transforms = ops.convert_to_tensor(transforms, name="transforms") + if transforms.shape.ndims not in (1, 2): + raise ValueError("Transforms should be 1D or 2D, got: %s" % transforms) + # Make the transform(s) 2D in case the input is a single transform. + transforms = array_ops.reshape(transforms, constant_op.constant([-1, 8])) + num_transforms = array_ops.shape(transforms)[0] + # Add a column of ones for the implicit last entry in the matrix. + return array_ops.reshape( + array_ops.concat( + [transforms, array_ops.ones([num_transforms, 1])], axis=1), + constant_op.constant([-1, 3, 3])) + + +def matrices_to_flat_transforms(transform_matrices): + """Converts affine matrices to `tf.contrib.image` projective transforms. + + Note that we expect matrices that map output coordinates to input coordinates. + To convert forward transformation matrices, call `tf.linalg.inv` on the + matrices and use the result here. + + Args: + transform_matrices: One or more affine transformation matrices, for the + reverse transformation in homogeneous coordinates. Shape `(3, 3)` or `(N, + 3, 3)`. + + Returns: + 2D tensor of flat transforms with shape `(N, 8)`, which may be passed into + `tf.contrib.image.transform`. + + Raises: + ValueError: If `transform_matrices` have an invalid shape. + """ + with ops.name_scope("matrices_to_flat_transforms"): + transform_matrices = ops.convert_to_tensor( + transform_matrices, name="transform_matrices") + if transform_matrices.shape.ndims not in (2, 3): + raise ValueError("Matrices should be 2D or 3D, got: %s" % + transform_matrices) + # Flatten each matrix. + transforms = array_ops.reshape(transform_matrices, + constant_op.constant([-1, 9])) + # Divide each matrix by the last entry (normally 1). + transforms /= transforms[:, 8:9] + return transforms[:, :8] + + +@ops.RegisterGradient("ImageProjectiveTransformV2") +def _image_projective_transform_grad(op, grad): + """Computes the gradient for ImageProjectiveTransform.""" + images = op.inputs[0] + transforms = op.inputs[1] + interpolation = op.get_attr("interpolation") + fill_mode = op.get_attr("fill_mode") + + image_or_images = ops.convert_to_tensor(images, name="images") + transform_or_transforms = ops.convert_to_tensor( + transforms, name="transforms", dtype=dtypes.float32) + + if image_or_images.dtype.base_dtype not in _IMAGE_DTYPES: + raise TypeError("Invalid dtype %s." % image_or_images.dtype) + if len(transform_or_transforms.get_shape()) == 1: + transforms = transform_or_transforms[None] + elif len(transform_or_transforms.get_shape()) == 2: + transforms = transform_or_transforms + else: + raise TypeError("Transforms should have rank 1 or 2.") + + # Invert transformations + transforms = flat_transforms_to_matrices(transforms=transforms) + inverse = linalg_ops.matrix_inverse(transforms) + transforms = matrices_to_flat_transforms(inverse) + output = gen_image_ops.image_projective_transform_v2( + images=grad, + transforms=transforms, + output_shape=array_ops.shape(image_or_images)[1:3], + interpolation=interpolation, + fill_mode=fill_mode) + return [output, None, None] + + +@ops.RegisterGradient("ImageProjectiveTransformV3") +def _image_projective_transform_v3_grad(op, grad): + """Computes the gradient for ImageProjectiveTransform.""" + images = op.inputs[0] + transforms = op.inputs[1] + interpolation = op.get_attr("interpolation") + fill_mode = op.get_attr("fill_mode") + + image_or_images = ops.convert_to_tensor(images, name="images") + transform_or_transforms = ops.convert_to_tensor( + transforms, name="transforms", dtype=dtypes.float32) + + if image_or_images.dtype.base_dtype not in _IMAGE_DTYPES: + raise TypeError("Invalid dtype %s." % image_or_images.dtype) + if len(transform_or_transforms.get_shape()) == 1: + transforms = transform_or_transforms[None] + elif len(transform_or_transforms.get_shape()) == 2: + transforms = transform_or_transforms + else: + raise TypeError("Transforms should have rank 1 or 2.") + + # Invert transformations + transforms = flat_transforms_to_matrices(transforms=transforms) + inverse = linalg_ops.matrix_inverse(transforms) + transforms = matrices_to_flat_transforms(inverse) + output = gen_image_ops.image_projective_transform_v3( + images=grad, + transforms=transforms, + output_shape=array_ops.shape(image_or_images)[1:3], + interpolation=interpolation, + fill_mode=fill_mode, + fill_value=0.0) + return [output, None, None, None] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..4195f4439b568c3738f217d6f7e3ccea063082b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/image_ops_impl.py @@ -0,0 +1,5941 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of image ops.""" + +import functools +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_case +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import ref_variable # pylint: disable=unused-import +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops import while_loop +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +ops.NotDifferentiable('RandomCrop') +# TODO(b/31222613): This op may be differentiable, and there may be +# latent bugs here. +ops.NotDifferentiable('HSVToRGB') +ops.NotDifferentiable('DrawBoundingBoxes') +ops.NotDifferentiable('SampleDistortedBoundingBox') +ops.NotDifferentiable('SampleDistortedBoundingBoxV2') +# TODO(bsteiner): Implement the gradient function for extract_glimpse +# TODO(b/31222613): This op may be differentiable, and there may be +# latent bugs here. +ops.NotDifferentiable('ExtractGlimpse') +ops.NotDifferentiable('NonMaxSuppression') +ops.NotDifferentiable('NonMaxSuppressionV2') +ops.NotDifferentiable('NonMaxSuppressionWithOverlaps') +ops.NotDifferentiable('GenerateBoundingBoxProposals') + + +# pylint: disable=invalid-name +def _assert(cond, ex_type, msg): + """A polymorphic assert, works with tensors and boolean expressions. + + If `cond` is not a tensor, behave like an ordinary assert statement, except + that a empty list is returned. If `cond` is a tensor, return a list + containing a single TensorFlow assert op. + + Args: + cond: Something evaluates to a boolean value. May be a tensor. + ex_type: The exception class to use. + msg: The error message. + + Returns: + A list, containing at most one assert op. + """ + if _is_tensor(cond): + return [control_flow_assert.Assert(cond, [msg])] + else: + if not cond: + raise ex_type(msg) + else: + return [] + + +def _is_tensor(x): + """Returns `True` if `x` is a symbolic tensor-like object. + + Args: + x: A python object to check. + + Returns: + `True` if `x` is a `tf.Tensor` or `tf.Variable`, otherwise `False`. + """ + return isinstance(x, (tensor_lib.Tensor, variables.Variable)) + + +def _ImageDimensions(image, rank): + """Returns the dimensions of an image tensor. + + Args: + image: A rank-D Tensor. For 3-D of shape: `[height, width, channels]`. + rank: The expected rank of the image + + Returns: + A list of corresponding to the dimensions of the + input image. Dimensions that are statically known are python integers, + otherwise, they are integer scalar tensors. + """ + if image.get_shape().is_fully_defined(): + return image.get_shape().as_list() + else: + static_shape = image.get_shape().with_rank(rank).as_list() + dynamic_shape = array_ops_stack.unstack(array_ops.shape(image), rank) + return [ + s if s is not None else d for s, d in zip(static_shape, dynamic_shape) + ] + + +def _Check3DImage(image, require_static=True): + """Assert that we are working with a properly shaped image. + + Args: + image: 3-D Tensor of shape [height, width, channels] + require_static: If `True`, requires that all dimensions of `image` are known + and non-zero. + + Raises: + ValueError: if `image.shape` is not a 3-vector. + + Returns: + An empty list, if `image` has fully defined dimensions. Otherwise, a list + containing an assert op is returned. + """ + try: + image_shape = image.get_shape().with_rank(3) + except ValueError: + raise ValueError("'image' (shape %s) must be three-dimensional." % + image.shape) + if require_static and not image_shape.is_fully_defined(): + raise ValueError("'image' (shape %s) must be fully defined." % image_shape) + if any(x == 0 for x in image_shape): + raise ValueError("all dims of 'image.shape' must be > 0: %s" % image_shape) + if not image_shape.is_fully_defined(): + return [ + check_ops.assert_positive( + array_ops.shape(image), + ["all dims of 'image.shape' " + 'must be > 0.']) + ] + else: + return [] + + +def _Assert3DImage(image): + """Assert that we are working with a properly shaped image. + + Performs the check statically if possible (i.e. if the shape + is statically known). Otherwise adds a control dependency + to an assert op that checks the dynamic shape. + + Args: + image: 3-D Tensor of shape [height, width, channels] + + Raises: + ValueError: if `image.shape` is not a 3-vector. + + Returns: + If the shape of `image` could be verified statically, `image` is + returned unchanged, otherwise there will be a control dependency + added that asserts the correct dynamic shape. + """ + return control_flow_ops.with_dependencies( + _Check3DImage(image, require_static=False), image) + + +def _AssertAtLeast3DImage(image): + """Assert that we are working with a properly shaped image. + + Performs the check statically if possible (i.e. if the shape + is statically known). Otherwise adds a control dependency + to an assert op that checks the dynamic shape. + + Args: + image: >= 3-D Tensor of size [*, height, width, depth] + + Raises: + ValueError: if image.shape is not a [>= 3] vector. + + Returns: + If the shape of `image` could be verified statically, `image` is + returned unchanged, otherwise there will be a control dependency + added that asserts the correct dynamic shape. + """ + return control_flow_ops.with_dependencies( + _CheckAtLeast3DImage(image, require_static=False), image) + + +def _CheckAtLeast3DImage(image, require_static=True): + """Assert that we are working with a properly shaped image. + + Args: + image: >= 3-D Tensor of size [*, height, width, depth] + require_static: If `True`, requires that all dimensions of `image` are known + and non-zero. + + Raises: + ValueError: if image.shape is not a [>= 3] vector. + + Returns: + An empty list, if `image` has fully defined dimensions. Otherwise, a list + containing an assert op is returned. + """ + try: + if image.get_shape().ndims is None: + image_shape = image.get_shape().with_rank(3) + else: + image_shape = image.get_shape().with_rank_at_least(3) + except ValueError: + raise ValueError("'image' (shape %s) must be at least three-dimensional." % + image.shape) + if require_static and not image_shape.is_fully_defined(): + raise ValueError('\'image\' must be fully defined.') + if any(x == 0 for x in image_shape[-3:]): + raise ValueError('inner 3 dims of \'image.shape\' must be > 0: %s' % + image_shape) + if not image_shape[-3:].is_fully_defined(): + return [ + check_ops.assert_positive( + array_ops.shape(image)[-3:], + ["inner 3 dims of 'image.shape' " + 'must be > 0.']), + check_ops.assert_greater_equal( + array_ops.rank(image), + 3, + message="'image' must be at least three-dimensional.") + ] + else: + return [] + + +def _AssertGrayscaleImage(image): + """Assert that we are working with a properly shaped grayscale image. + + Performs the check statically if possible (i.e. if the shape + is statically known). Otherwise adds a control dependency + to an assert op that checks the dynamic shape. + + Args: + image: >= 2-D Tensor of size [*, 1] + + Raises: + ValueError: if image.shape is not a [>= 2] vector or if + last dimension is not size 1. + + Returns: + If the shape of `image` could be verified statically, `image` is + returned unchanged, otherwise there will be a control dependency + added that asserts the correct dynamic shape. + """ + return control_flow_ops.with_dependencies( + _CheckGrayscaleImage(image, require_static=False), image) + + +def _CheckGrayscaleImage(image, require_static=True): + """Assert that we are working with properly shaped grayscale image. + + Args: + image: >= 2-D Tensor of size [*, 1] + require_static: Boolean, whether static shape is required. + + Raises: + ValueError: if image.shape is not a [>= 2] vector or if + last dimension is not size 1. + + Returns: + An empty list, if `image` has fully defined dimensions. Otherwise, a list + containing an assert op is returned. + """ + try: + if image.get_shape().ndims is None: + image_shape = image.get_shape().with_rank(2) + else: + image_shape = image.get_shape().with_rank_at_least(2) + except ValueError: + raise ValueError('A grayscale image (shape %s) must be at least ' + 'two-dimensional.' % image.shape) + if require_static and not image_shape.is_fully_defined(): + raise ValueError('\'image\' must be fully defined.') + if image_shape.is_fully_defined(): + if image_shape[-1] != 1: + raise ValueError('Last dimension of a grayscale image should be size 1.') + if not image_shape.is_fully_defined(): + return [ + check_ops.assert_equal( + array_ops.shape(image)[-1], + 1, + message='Last dimension of a grayscale image should be size 1.'), + check_ops.assert_greater_equal( + array_ops.rank(image), + 3, + message='A grayscale image must be at least two-dimensional.') + ] + else: + return [] + + +def fix_image_flip_shape(image, result): + """Set the shape to 3 dimensional if we don't know anything else. + + Args: + image: original image size + result: flipped or transformed image + + Returns: + An image whose shape is at least (None, None, None). + """ + + image_shape = image.get_shape() + if image_shape == tensor_shape.unknown_shape(): + result.set_shape([None, None, None]) + else: + result.set_shape(image_shape) + return result + + +@tf_export('image.random_flip_up_down') +@dispatch.add_dispatch_support +def random_flip_up_down(image, seed=None): + """Randomly flips an image vertically (upside down). + + With a 1 in 2 chance, outputs the contents of `image` flipped along the first + dimension, which is `height`. Otherwise, output the image as-is. + When passing a batch of images, each image will be randomly flipped + independent of other images. + + Example usage: + + >>> image = np.array([[[1], [2]], [[3], [4]]]) + >>> tf.image.random_flip_up_down(image, 3).numpy().tolist() + [[[3], [4]], [[1], [2]]] + + Randomly flip multiple images. + + >>> images = np.array( + ... [ + ... [[[1], [2]], [[3], [4]]], + ... [[[5], [6]], [[7], [8]]] + ... ]) + >>> tf.image.random_flip_up_down(images, 4).numpy().tolist() + [[[[3], [4]], [[1], [2]]], [[[5], [6]], [[7], [8]]]] + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_flip_up_down`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + seed: A Python integer. Used to create a random seed. See + `tf.compat.v1.set_random_seed` for behavior. + + Returns: + A tensor of the same type and shape as `image`. + Raises: + ValueError: if the shape of `image` not supported. + """ + random_func = functools.partial(random_ops.random_uniform, seed=seed) + return _random_flip(image, 0, random_func, 'random_flip_up_down') + + +@tf_export('image.random_flip_left_right') +@dispatch.add_dispatch_support +def random_flip_left_right(image, seed=None): + """Randomly flip an image horizontally (left to right). + + With a 1 in 2 chance, outputs the contents of `image` flipped along the + second dimension, which is `width`. Otherwise output the image as-is. + When passing a batch of images, each image will be randomly flipped + independent of other images. + + Example usage: + + >>> image = np.array([[[1], [2]], [[3], [4]]]) + >>> tf.image.random_flip_left_right(image, 5).numpy().tolist() + [[[2], [1]], [[4], [3]]] + + Randomly flip multiple images. + + >>> images = np.array( + ... [ + ... [[[1], [2]], [[3], [4]]], + ... [[[5], [6]], [[7], [8]]] + ... ]) + >>> tf.image.random_flip_left_right(images, 6).numpy().tolist() + [[[[2], [1]], [[4], [3]]], [[[5], [6]], [[7], [8]]]] + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_flip_left_right`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + seed: A Python integer. Used to create a random seed. See + `tf.compat.v1.set_random_seed` for behavior. + + Returns: + A tensor of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + random_func = functools.partial(random_ops.random_uniform, seed=seed) + return _random_flip(image, 1, random_func, 'random_flip_left_right') + + +@tf_export('image.stateless_random_flip_left_right', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_flip_left_right(image, seed): + """Randomly flip an image horizontally (left to right) deterministically. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Example usage: + + >>> image = np.array([[[1], [2]], [[3], [4]]]) + >>> seed = (2, 3) + >>> tf.image.stateless_random_flip_left_right(image, seed).numpy().tolist() + [[[2], [1]], [[4], [3]]] + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Returns: + A tensor of the same type and shape as `image`. + """ + random_func = functools.partial( + stateless_random_ops.stateless_random_uniform, seed=seed) + return _random_flip( + image, 1, random_func, 'stateless_random_flip_left_right') + + +@tf_export('image.stateless_random_flip_up_down', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_flip_up_down(image, seed): + """Randomly flip an image vertically (upside down) deterministically. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Example usage: + + >>> image = np.array([[[1], [2]], [[3], [4]]]) + >>> seed = (2, 3) + >>> tf.image.stateless_random_flip_up_down(image, seed).numpy().tolist() + [[[3], [4]], [[1], [2]]] + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Returns: + A tensor of the same type and shape as `image`. + """ + random_func = functools.partial( + stateless_random_ops.stateless_random_uniform, seed=seed) + return _random_flip( + image, 0, random_func, 'stateless_random_flip_up_down') + + +def _random_flip(image, flip_index, random_func, scope_name): + """Randomly (50% chance) flip an image along axis `flip_index`. + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + flip_index: Dimension along which to flip the image. + Vertical is 0, Horizontal is 1. + random_func: partial function for calling either stateful or stateless + random ops with `seed` parameter specified. + scope_name: Name of the scope in which the ops are added. + + Returns: + A tensor of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + with ops.name_scope(None, scope_name, [image]) as scope: + image = ops.convert_to_tensor(image, name='image') + image = _AssertAtLeast3DImage(image) + shape = image.get_shape() + + def f_rank3(): + uniform_random = random_func(shape=[], minval=0, maxval=1.0) + mirror_cond = math_ops.less(uniform_random, .5) + result = tf_cond.cond( + mirror_cond, + lambda: array_ops.reverse(image, [flip_index]), + lambda: image, + name=scope) + return fix_image_flip_shape(image, result) + + def f_rank4(): + batch_size = array_ops.shape(image)[0] + uniform_random = random_func(shape=[batch_size], minval=0, maxval=1.0) + flips = math_ops.round( + array_ops.reshape(uniform_random, [batch_size, 1, 1, 1])) + flips = math_ops.cast(flips, image.dtype) + flipped_input = array_ops.reverse(image, [flip_index + 1]) + return flips * flipped_input + (1 - flips) * image + + if shape.ndims is None: + rank = array_ops.rank(image) + return tf_cond.cond(math_ops.equal(rank, 3), f_rank3, f_rank4) + if shape.ndims == 3: + return f_rank3() + elif shape.ndims == 4: + return f_rank4() + else: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % shape) + + +@tf_export('image.flip_left_right') +@dispatch.add_dispatch_support +def flip_left_right(image): + """Flip an image horizontally (left to right). + + Outputs the contents of `image` flipped along the width dimension. + + See also `tf.reverse`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.flip_left_right(x) + + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + + Returns: + A tensor of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + return _flip(image, 1, 'flip_left_right') + + +@tf_export('image.flip_up_down') +@dispatch.add_dispatch_support +def flip_up_down(image): + """Flip an image vertically (upside down). + + Outputs the contents of `image` flipped along the height dimension. + + See also `reverse()`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.flip_up_down(x) + + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + + Returns: + A `Tensor` of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + return _flip(image, 0, 'flip_up_down') + + +def _flip(image, flip_index, scope_name): + """Flip an image either horizontally or vertically. + + Outputs the contents of `image` flipped along the dimension `flip_index`. + + See also `reverse()`. + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + flip_index: 0 For vertical, 1 for horizontal. + scope_name: string, scope name. + + Returns: + A `Tensor` of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + with ops.name_scope(None, scope_name, [image]): + image = ops.convert_to_tensor(image, name='image') + image = _AssertAtLeast3DImage(image) + shape = image.get_shape() + + def f_rank3(): + return fix_image_flip_shape(image, array_ops.reverse(image, [flip_index])) + + def f_rank4(): + return array_ops.reverse(image, [flip_index + 1]) + + if shape.ndims is None: + rank = array_ops.rank(image) + return tf_cond.cond(math_ops.equal(rank, 3), f_rank3, f_rank4) + elif shape.ndims == 3: + return f_rank3() + elif shape.ndims == 4: + return f_rank4() + else: + raise ValueError( + '\'image\' (shape %s)must have either 3 or 4 dimensions.' % shape) + + +@tf_export('image.rot90') +@dispatch.add_dispatch_support +def rot90(image, k=1, name=None): + """Rotate image(s) by 90 degrees. + + + For example: + + >>> a=tf.constant([[[1],[2]], + ... [[3],[4]]]) + >>> # rotating `a` counter clockwise by 90 degrees + >>> a_rot=tf.image.rot90(a) + >>> print(a_rot[...,0].numpy()) + [[2 4] + [1 3]] + >>> # rotating `a` counter clockwise by 270 degrees + >>> a_rot=tf.image.rot90(a, k=3) + >>> print(a_rot[...,0].numpy()) + [[3 1] + [4 2]] + >>> # rotating `a` clockwise by 180 degrees + >>> a_rot=tf.image.rot90(a, k=-2) + >>> print(a_rot[...,0].numpy()) + [[4 3] + [2 1]] + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + k: A scalar integer tensor. The number of times the image(s) are rotated by + 90 degrees. + name: A name for this operation (optional). + + Returns: + A rotated tensor of the same type and shape as `image`. + + Raises: + ValueError: if the shape of `image` not supported. + """ + with ops.name_scope(name, 'rot90', [image, k]) as scope: + image = ops.convert_to_tensor(image, name='image') + image = _AssertAtLeast3DImage(image) + k = ops.convert_to_tensor(k, dtype=dtypes.int32, name='k') + k.get_shape().assert_has_rank(0) + k = math_ops.mod(k, 4) + + shape = image.get_shape() + if shape.ndims is None: + rank = array_ops.rank(image) + + def f_rank3(): + return _rot90_3D(image, k, scope) + + def f_rank4(): + return _rot90_4D(image, k, scope) + + return tf_cond.cond(math_ops.equal(rank, 3), f_rank3, f_rank4) + elif shape.ndims == 3: + return _rot90_3D(image, k, scope) + elif shape.ndims == 4: + return _rot90_4D(image, k, scope) + else: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % shape) + + +def _rot90_3D(image, k, name_scope): + """Rotate image counter-clockwise by 90 degrees `k` times. + + Args: + image: 3-D Tensor of shape `[height, width, channels]`. + k: A scalar integer. The number of times the image is rotated by 90 degrees. + name_scope: A valid TensorFlow name scope. + + Returns: + A 3-D tensor of the same type and shape as `image`. + + """ + + def _rot90(): + return array_ops.transpose(array_ops.reverse_v2(image, [1]), [1, 0, 2]) + + def _rot180(): + return array_ops.reverse_v2(image, [0, 1]) + + def _rot270(): + return array_ops.reverse_v2(array_ops.transpose(image, [1, 0, 2]), [1]) + + cases = [(math_ops.equal(k, 1), _rot90), (math_ops.equal(k, 2), _rot180), + (math_ops.equal(k, 3), _rot270)] + + result = control_flow_case.case( + cases, default=lambda: image, exclusive=True, name=name_scope) + result.set_shape([None, None, image.get_shape()[2]]) + return result + + +def _rot90_4D(images, k, name_scope): + """Rotate batch of images counter-clockwise by 90 degrees `k` times. + + Args: + images: 4-D Tensor of shape `[height, width, channels]`. + k: A scalar integer. The number of times the images are rotated by 90 + degrees. + name_scope: A valid TensorFlow name scope. + + Returns: + A 4-D `Tensor` of the same type and shape as `images`. + """ + + def _rot90(): + return array_ops.transpose(array_ops.reverse_v2(images, [2]), [0, 2, 1, 3]) + + def _rot180(): + return array_ops.reverse_v2(images, [1, 2]) + + def _rot270(): + return array_ops.reverse_v2(array_ops.transpose(images, [0, 2, 1, 3]), [2]) + + cases = [(math_ops.equal(k, 1), _rot90), (math_ops.equal(k, 2), _rot180), + (math_ops.equal(k, 3), _rot270)] + + result = control_flow_case.case( + cases, default=lambda: images, exclusive=True, name=name_scope) + shape = result.get_shape() + result.set_shape([shape[0], None, None, shape[3]]) + return result + + +@tf_export('image.transpose', v1=['image.transpose', 'image.transpose_image']) +@dispatch.add_dispatch_support +def transpose(image, name=None): + """Transpose image(s) by swapping the height and width dimension. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.transpose(x) + + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + name: A name for this operation (optional). + + Returns: + If `image` was 4-D, a 4-D float Tensor of shape + `[batch, width, height, channels]` + If `image` was 3-D, a 3-D float Tensor of shape + `[width, height, channels]` + + Raises: + ValueError: if the shape of `image` not supported. + + Usage Example: + + >>> image = [[[1, 2], [3, 4]], + ... [[5, 6], [7, 8]], + ... [[9, 10], [11, 12]]] + >>> image = tf.constant(image) + >>> tf.image.transpose(image) + + """ + with ops.name_scope(name, 'transpose', [image]): + image = ops.convert_to_tensor(image, name='image') + image = _AssertAtLeast3DImage(image) + shape = image.get_shape() + if shape.ndims is None: + rank = array_ops.rank(image) + + def f_rank3(): + return array_ops.transpose(image, [1, 0, 2], name=name) + + def f_rank4(): + return array_ops.transpose(image, [0, 2, 1, 3], name=name) + + return tf_cond.cond(math_ops.equal(rank, 3), f_rank3, f_rank4) + elif shape.ndims == 3: + return array_ops.transpose(image, [1, 0, 2], name=name) + elif shape.ndims == 4: + return array_ops.transpose(image, [0, 2, 1, 3], name=name) + else: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % shape) + + +@tf_export('image.central_crop') +@dispatch.add_dispatch_support +def central_crop(image, central_fraction): + """Crop the central region of the image(s). + + Remove the outer parts of an image but retain the central region of the image + along each dimension. If we specify `central_fraction = 0.5`, this function + returns the region marked with "X" in the below diagram. The larger the value + of `central_fraction`, the larger the dimension of the region to be cropped + and retained. + + -------- + | | + | XXXX | + | XXXX | + | | where "X" is the central 50% of the image. + -------- + + This function works on either a single image (`image` is a 3-D Tensor), or a + batch of images (`image` is a 4-D Tensor). + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0], + ... [7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]], + ... [[13.0, 14.0, 15.0], + ... [16.0, 17.0, 18.0], + ... [19.0, 20.0, 21.0], + ... [22.0, 23.0, 24.0]], + ... [[25.0, 26.0, 27.0], + ... [28.0, 29.0, 30.0], + ... [31.0, 32.0, 33.0], + ... [34.0, 35.0, 36.0]], + ... [[37.0, 38.0, 39.0], + ... [40.0, 41.0, 42.0], + ... [43.0, 44.0, 45.0], + ... [46.0, 47.0, 48.0]]] + >>> tf.image.central_crop(x, 0.5) + + + Args: + image: Either a 3-D float Tensor of shape [height, width, depth], or a 4-D + Tensor of shape [batch_size, height, width, depth]. + central_fraction: float (0, 1], fraction of size to crop + + Raises: + ValueError: if central_crop_fraction is not within (0, 1]. + + Returns: + 3-D / 4-D float Tensor, as per the input. + """ + with ops.name_scope(None, 'central_crop', [image]): + image = ops.convert_to_tensor(image, name='image') + central_fraction_static = tensor_util.constant_value(central_fraction) + if central_fraction_static is not None: + if central_fraction_static <= 0.0 or central_fraction_static > 1.0: + raise ValueError('central_fraction must be within (0, 1]') + if central_fraction_static == 1.0: + return image + else: + assert_ops = _assert( + math_ops.logical_or(central_fraction > 0.0, central_fraction <= 1.0), + ValueError, 'central_fraction must be within (0, 1]') + image = control_flow_ops.with_dependencies(assert_ops, image) + + _AssertAtLeast3DImage(image) + rank = image.get_shape().ndims + if rank != 3 and rank != 4: + raise ValueError('`image` should either be a Tensor with rank = 3 or ' + 'rank = 4. Had rank = {}.'.format(rank)) + + # Helper method to return the `idx`-th dimension of `tensor`, along with + # a boolean signifying if the dimension is dynamic. + def _get_dim(tensor, idx): + static_shape = tensor.get_shape().dims[idx].value + if static_shape is not None: + return static_shape, False + return array_ops.shape(tensor)[idx], True + + # Get the height, width, depth (and batch size, if the image is a 4-D + # tensor). + if rank == 3: + img_h, dynamic_h = _get_dim(image, 0) + img_w, dynamic_w = _get_dim(image, 1) + img_d = image.get_shape()[2] + else: + img_bs = image.get_shape()[0] + img_h, dynamic_h = _get_dim(image, 1) + img_w, dynamic_w = _get_dim(image, 2) + img_d = image.get_shape()[3] + + dynamic_h = dynamic_h or (central_fraction_static is None) + dynamic_w = dynamic_w or (central_fraction_static is None) + + # Compute the bounding boxes for the crop. The type and value of the + # bounding boxes depend on the `image` tensor's rank and whether / not the + # dimensions are statically defined. + if dynamic_h: + img_hd = math_ops.cast(img_h, dtypes.float64) + bbox_h_start = math_ops.cast( + (img_hd - img_hd * math_ops.cast(central_fraction, dtypes.float64)) / + 2, dtypes.int32) + else: + img_hd = float(img_h) + bbox_h_start = int((img_hd - img_hd * central_fraction_static) / 2) + + if dynamic_w: + img_wd = math_ops.cast(img_w, dtypes.float64) + bbox_w_start = math_ops.cast( + (img_wd - img_wd * math_ops.cast(central_fraction, dtypes.float64)) / + 2, dtypes.int32) + else: + img_wd = float(img_w) + bbox_w_start = int((img_wd - img_wd * central_fraction_static) / 2) + + bbox_h_size = img_h - bbox_h_start * 2 + bbox_w_size = img_w - bbox_w_start * 2 + + if rank == 3: + bbox_begin = array_ops_stack.stack([bbox_h_start, bbox_w_start, 0]) + bbox_size = array_ops_stack.stack([bbox_h_size, bbox_w_size, -1]) + else: + bbox_begin = array_ops_stack.stack([0, bbox_h_start, bbox_w_start, 0]) + bbox_size = array_ops_stack.stack([-1, bbox_h_size, bbox_w_size, -1]) + + image = array_ops.slice(image, bbox_begin, bbox_size) + + # Reshape the `image` tensor to the desired size. + if rank == 3: + image.set_shape([ + None if dynamic_h else bbox_h_size, + None if dynamic_w else bbox_w_size, img_d + ]) + else: + image.set_shape([ + img_bs, None if dynamic_h else bbox_h_size, + None if dynamic_w else bbox_w_size, img_d + ]) + return image + + +@tf_export('image.pad_to_bounding_box') +@dispatch.add_dispatch_support +def pad_to_bounding_box(image, offset_height, offset_width, target_height, + target_width): + """Pad `image` with zeros to the specified `height` and `width`. + + Adds `offset_height` rows of zeros on top, `offset_width` columns of + zeros on the left, and then pads the image on the bottom and right + with zeros until it has dimensions `target_height`, `target_width`. + + This op does nothing if `offset_*` is zero and the image already has size + `target_height` by `target_width`. + + Usage Example: + + >>> x = [[[1., 2., 3.], + ... [4., 5., 6.]], + ... [[7., 8., 9.], + ... [10., 11., 12.]]] + >>> padded_image = tf.image.pad_to_bounding_box(x, 1, 1, 4, 4) + >>> padded_image + + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + offset_height: Number of rows of zeros to add on top. + offset_width: Number of columns of zeros to add on the left. + target_height: Height of output image. + target_width: Width of output image. + + Returns: + If `image` was 4-D, a 4-D float Tensor of shape + `[batch, target_height, target_width, channels]` + If `image` was 3-D, a 3-D float Tensor of shape + `[target_height, target_width, channels]` + + Raises: + ValueError: If the shape of `image` is incompatible with the `offset_*` or + `target_*` arguments, or either `offset_height` or `offset_width` is + negative. + """ + return pad_to_bounding_box_internal( + image, + offset_height, + offset_width, + target_height, + target_width, + check_dims=True) + + +# TODO(b/190099338) Remove this internal method and remap call sites to call +# image_ops.pad_to_bounding_box when asserts are no longer serialized. See also +# b/204377079#comment6 for more context. +def pad_to_bounding_box_internal(image, offset_height, offset_width, + target_height, target_width, check_dims): + """Pad `image` with zeros to the specified `height` and `width`. + + Adds `offset_height` rows of zeros on top, `offset_width` columns of + zeros on the left, and then pads the image on the bottom and right + with zeros until it has dimensions `target_height`, `target_width`. + + This op does nothing if `offset_*` is zero and the image already has size + `target_height` by `target_width`. + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + offset_height: Number of rows of zeros to add on top.Must be 0-D `Tensor` of + dtype int32 or int64. Can also a python integer. + offset_width: Number of columns of zeros to add on the left.Must be 0-D + `Tensor` of dtype int32 or int64. Can also a python integer. + target_height: Height of output image.Must be 0-D `Tensor` of dtype int32 or + int64. Can also a python integer. + target_width: Width of output image.Must be 0-D `Tensor` of dtype int32 or + int64. Can also a python integer. + check_dims: If True, assert that dimensions are non-negative and in range. + In multi-GPU distributed settings, assertions can cause program slowdown. + Setting this parameter to `False` avoids this, resulting in faster speed + in some situations, with the tradeoff being that some error checking is + not happening. + + Returns: + If `image` was 4-D, a 4-D float Tensor of shape + `[batch, target_height, target_width, channels]` + If `image` was 3-D, a 3-D float Tensor of shape + `[target_height, target_width, channels]` + + Raises: + ValueError: If the shape of `image` is incompatible with the `offset_*` or + `target_*` arguments, or either `offset_height` or `offset_width` is + negative. Not raised if `check_dims` is `False`. + """ + with ops.name_scope(None, 'pad_to_bounding_box', [image]): + image = ops.convert_to_tensor(image, name='image') + + is_batch = True + image_shape = image.get_shape() + if image_shape.ndims == 3: + is_batch = False + image = array_ops.expand_dims(image, 0) + elif image_shape.ndims is None: + is_batch = False + image = array_ops.expand_dims(image, 0) + image.set_shape([None] * 4) + elif image_shape.ndims != 4: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % + image_shape) + + batch, height, width, depth = _ImageDimensions(image, rank=4) + + after_padding_width = target_width - offset_width - width + + after_padding_height = target_height - offset_height - height + + if check_dims: + assert_ops = _CheckAtLeast3DImage(image, require_static=False) + assert_ops += _assert(offset_height >= 0, ValueError, + 'offset_height must be >= 0') + assert_ops += _assert(offset_width >= 0, ValueError, + 'offset_width must be >= 0') + assert_ops += _assert(after_padding_width >= 0, ValueError, + 'width must be <= target - offset') + assert_ops += _assert(after_padding_height >= 0, ValueError, + 'height must be <= target - offset') + image = control_flow_ops.with_dependencies(assert_ops, image) + + # Do not pad on the depth dimensions. + paddings = array_ops.reshape( + array_ops_stack.stack([ + 0, 0, offset_height, after_padding_height, offset_width, + after_padding_width, 0, 0 + ]), [4, 2]) + padded = array_ops.pad(image, paddings) + + padded_shape = [ + None if _is_tensor(i) else i + for i in [batch, target_height, target_width, depth] + ] + padded.set_shape(padded_shape) + + if not is_batch: + padded = array_ops.squeeze(padded, axis=[0]) + + return padded + + +@tf_export('image.crop_to_bounding_box') +@dispatch.add_dispatch_support +def crop_to_bounding_box(image, offset_height, offset_width, target_height, + target_width): + """Crops an `image` to a specified bounding box. + + This op cuts a rectangular bounding box out of `image`. The top-left corner + of the bounding box is at `offset_height, offset_width` in `image`, and the + lower-right corner is at + `offset_height + target_height, offset_width + target_width`. + + Example Usage: + + >>> image = tf.constant(np.arange(1, 28, dtype=np.float32), shape=[3, 3, 3]) + >>> image[:,:,0] # print the first channel of the 3-D tensor + + >>> cropped_image = tf.image.crop_to_bounding_box(image, 0, 0, 2, 2) + >>> cropped_image[:,:,0] # print the first channel of the cropped 3-D tensor + + + Args: + image: 4-D `Tensor` of shape `[batch, height, width, channels]` or 3-D + `Tensor` of shape `[height, width, channels]`. + offset_height: Vertical coordinate of the top-left corner of the bounding + box in `image`. Must be 0-D int32 `Tensor` or python integer. + offset_width: Horizontal coordinate of the top-left corner of the bounding + box in `image`. Must be 0-D int32 `Tensor` or python integer. + target_height: Height of the bounding box. Must be 0-D int32 `Tensor` or + python integer. + target_width: Width of the bounding box. Must be 0-D int32 `Tensor` or + python integer. + + Returns: + If `image` was 4-D, a 4-D `Tensor` of shape + `[batch, target_height, target_width, channels]`. + If `image` was 3-D, a 3-D `Tensor` of shape + `[target_height, target_width, channels]`. + It has the same dtype with `image`. + + Raises: + ValueError: `image` is not a 3-D or 4-D `Tensor`. + ValueError: `offset_width < 0` or `offset_height < 0`. + ValueError: `target_width <= 0` or `target_height <= 0`. + ValueError: `width < offset_width + target_width` or + `height < offset_height + target_height`. + """ + with ops.name_scope(None, 'crop_to_bounding_box', [image]): + image = ops.convert_to_tensor(image, name='image') + + is_batch = True + image_shape = image.get_shape() + if image_shape.ndims == 3: + is_batch = False + image = array_ops.expand_dims(image, 0) + elif image_shape.ndims is None: + is_batch = False + image = array_ops.expand_dims(image, 0) + image.set_shape([None] * 4) + elif image_shape.ndims != 4: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % + image_shape) + + assert_ops = _CheckAtLeast3DImage(image, require_static=False) + + batch, height, width, depth = _ImageDimensions(image, rank=4) + + assert_ops += _assert(offset_width >= 0, ValueError, + 'offset_width must be >= 0.') + assert_ops += _assert(offset_height >= 0, ValueError, + 'offset_height must be >= 0.') + assert_ops += _assert(target_width > 0, ValueError, + 'target_width must be > 0.') + assert_ops += _assert(target_height > 0, ValueError, + 'target_height must be > 0.') + assert_ops += _assert(width >= (target_width + offset_width), ValueError, + 'width must be >= target + offset.') + assert_ops += _assert(height >= (target_height + offset_height), ValueError, + 'height must be >= target + offset.') + image = control_flow_ops.with_dependencies(assert_ops, image) + + cropped = array_ops.slice( + image, + array_ops_stack.stack([0, offset_height, offset_width, 0]), + array_ops_stack.stack([ + array_ops.shape(image)[0], + target_height, + target_width, + array_ops.shape(image)[3]])) + + cropped_shape = [ + None if _is_tensor(i) else i + for i in [batch, target_height, target_width, depth] + ] + cropped.set_shape(cropped_shape) + + if not is_batch: + cropped = array_ops.squeeze(cropped, axis=[0]) + + return cropped + + +@tf_export( + 'image.resize_with_crop_or_pad', + v1=['image.resize_with_crop_or_pad', 'image.resize_image_with_crop_or_pad']) +@dispatch.add_dispatch_support +def resize_image_with_crop_or_pad(image, target_height, target_width): + """Crops and/or pads an image to a target width and height. + + Resizes an image to a target width and height by either centrally + cropping the image or padding it evenly with zeros. + + If `width` or `height` is greater than the specified `target_width` or + `target_height` respectively, this op centrally crops along that dimension. + + For example: + + >>> image = np.arange(75).reshape(5, 5, 3) # create 3-D image input + >>> image[:,:,0] # print first channel just for demo purposes + array([[ 0, 3, 6, 9, 12], + [15, 18, 21, 24, 27], + [30, 33, 36, 39, 42], + [45, 48, 51, 54, 57], + [60, 63, 66, 69, 72]]) + >>> image = tf.image.resize_with_crop_or_pad(image, 3, 3) # crop + >>> # print first channel for demo purposes; centrally cropped output + >>> image[:,:,0] + + + If `width` or `height` is smaller than the specified `target_width` or + `target_height` respectively, this op centrally pads with 0 along that + dimension. + + For example: + + >>> image = np.arange(1, 28).reshape(3, 3, 3) # create 3-D image input + >>> image[:,:,0] # print first channel just for demo purposes + array([[ 1, 4, 7], + [10, 13, 16], + [19, 22, 25]]) + >>> image = tf.image.resize_with_crop_or_pad(image, 5, 5) # pad + >>> # print first channel for demo purposes; we should see 0 paddings + >>> image[:,:,0] + + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + target_height: Target height. + target_width: Target width. + + Raises: + ValueError: if `target_height` or `target_width` are zero or negative. + + Returns: + Cropped and/or padded image. + If `images` was 4-D, a 4-D float Tensor of shape + `[batch, new_height, new_width, channels]`. + If `images` was 3-D, a 3-D float Tensor of shape + `[new_height, new_width, channels]`. + """ + with ops.name_scope(None, 'resize_image_with_crop_or_pad', [image]): + image = ops.convert_to_tensor(image, name='image') + image_shape = image.get_shape() + is_batch = True + if image_shape.ndims == 3: + is_batch = False + image = array_ops.expand_dims(image, 0) + elif image_shape.ndims is None: + is_batch = False + image = array_ops.expand_dims(image, 0) + image.set_shape([None] * 4) + elif image_shape.ndims != 4: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % + image_shape) + + assert_ops = _CheckAtLeast3DImage(image, require_static=False) + assert_ops += _assert(target_width > 0, ValueError, + 'target_width must be > 0.') + assert_ops += _assert(target_height > 0, ValueError, + 'target_height must be > 0.') + + image = control_flow_ops.with_dependencies(assert_ops, image) + # `crop_to_bounding_box` and `pad_to_bounding_box` have their own checks. + # Make sure our checks come first, so that error messages are clearer. + if _is_tensor(target_height): + target_height = control_flow_ops.with_dependencies( + assert_ops, target_height) + if _is_tensor(target_width): + target_width = control_flow_ops.with_dependencies(assert_ops, + target_width) + + def max_(x, y): + if _is_tensor(x) or _is_tensor(y): + return math_ops.maximum(x, y) + else: + return max(x, y) + + def min_(x, y): + if _is_tensor(x) or _is_tensor(y): + return math_ops.minimum(x, y) + else: + return min(x, y) + + def equal_(x, y): + if _is_tensor(x) or _is_tensor(y): + return math_ops.equal(x, y) + else: + return x == y + + _, height, width, _ = _ImageDimensions(image, rank=4) + width_diff = target_width - width + offset_crop_width = max_(-width_diff // 2, 0) + offset_pad_width = max_(width_diff // 2, 0) + + height_diff = target_height - height + offset_crop_height = max_(-height_diff // 2, 0) + offset_pad_height = max_(height_diff // 2, 0) + + # Maybe crop if needed. + cropped = crop_to_bounding_box(image, offset_crop_height, offset_crop_width, + min_(target_height, height), + min_(target_width, width)) + + # Maybe pad if needed. + resized = pad_to_bounding_box(cropped, offset_pad_height, offset_pad_width, + target_height, target_width) + + # In theory all the checks below are redundant. + if resized.get_shape().ndims is None: + raise ValueError('resized contains no shape.') + + _, resized_height, resized_width, _ = _ImageDimensions(resized, rank=4) + + assert_ops = [] + assert_ops += _assert( + equal_(resized_height, target_height), ValueError, + 'resized height is not correct.') + assert_ops += _assert( + equal_(resized_width, target_width), ValueError, + 'resized width is not correct.') + + resized = control_flow_ops.with_dependencies(assert_ops, resized) + + if not is_batch: + resized = array_ops.squeeze(resized, axis=[0]) + + return resized + + +@tf_export(v1=['image.ResizeMethod']) +class ResizeMethodV1: + """See `v1.image.resize` for details.""" + BILINEAR = 0 + NEAREST_NEIGHBOR = 1 + BICUBIC = 2 + AREA = 3 + + +@tf_export('image.ResizeMethod', v1=[]) +class ResizeMethod: + """See `tf.image.resize` for details.""" + BILINEAR = 'bilinear' + NEAREST_NEIGHBOR = 'nearest' + BICUBIC = 'bicubic' + AREA = 'area' + LANCZOS3 = 'lanczos3' + LANCZOS5 = 'lanczos5' + GAUSSIAN = 'gaussian' + MITCHELLCUBIC = 'mitchellcubic' + + +def _resize_images_common(images, resizer_fn, size, preserve_aspect_ratio, name, + skip_resize_if_same): + """Core functionality for v1 and v2 resize functions.""" + with ops.name_scope(name, 'resize', [images, size]): + images = ops.convert_to_tensor(images, name='images') + if images.get_shape().ndims is None: + raise ValueError('\'images\' contains no shape.') + # TODO(shlens): Migrate this functionality to the underlying Op's. + is_batch = True + if images.get_shape().ndims == 3: + is_batch = False + images = array_ops.expand_dims(images, 0) + elif images.get_shape().ndims != 4: + raise ValueError('\'images\' must have either 3 or 4 dimensions.') + + _, height, width, _ = images.get_shape().as_list() + + try: + size = ops.convert_to_tensor(size, dtypes.int32, name='size') + except (TypeError, ValueError): + raise ValueError('\'size\' must be a 1-D int32 Tensor') + if not size.get_shape().is_compatible_with([2]): + raise ValueError('\'size\' must be a 1-D Tensor of 2 elements: ' + 'new_height, new_width') + + if preserve_aspect_ratio: + # Get the current shapes of the image, even if dynamic. + _, current_height, current_width, _ = _ImageDimensions(images, rank=4) + + # do the computation to find the right scale and height/width. + scale_factor_height = ( + math_ops.cast(size[0], dtypes.float32) / + math_ops.cast(current_height, dtypes.float32)) + scale_factor_width = ( + math_ops.cast(size[1], dtypes.float32) / + math_ops.cast(current_width, dtypes.float32)) + scale_factor = math_ops.minimum(scale_factor_height, scale_factor_width) + scaled_height_const = math_ops.cast( + math_ops.round(scale_factor * + math_ops.cast(current_height, dtypes.float32)), + dtypes.int32) + scaled_width_const = math_ops.cast( + math_ops.round(scale_factor * + math_ops.cast(current_width, dtypes.float32)), + dtypes.int32) + + # NOTE: Reset the size and other constants used later. + size = ops.convert_to_tensor([scaled_height_const, scaled_width_const], + dtypes.int32, + name='size') + + size_const_as_shape = tensor_util.constant_value_as_shape(size) + new_height_const = tensor_shape.dimension_at_index(size_const_as_shape, + 0).value + new_width_const = tensor_shape.dimension_at_index(size_const_as_shape, + 1).value + + # If we can determine that the height and width will be unmodified by this + # transformation, we avoid performing the resize. + if skip_resize_if_same and all( + x is not None + for x in [new_width_const, width, new_height_const, height]) and ( + width == new_width_const and height == new_height_const): + if not is_batch: + images = array_ops.squeeze(images, axis=[0]) + return images + + images = resizer_fn(images, size) + + # NOTE(mrry): The shape functions for the resize ops cannot unpack + # the packed values in `new_size`, so set the shape here. + images.set_shape([None, new_height_const, new_width_const, None]) + + if not is_batch: + images = array_ops.squeeze(images, axis=[0]) + return images + + +@tf_export(v1=['image.resize_images', 'image.resize']) +@dispatch.add_dispatch_support +def resize_images(images, + size, + method=ResizeMethodV1.BILINEAR, + align_corners=False, + preserve_aspect_ratio=False, + name=None): + """Resize `images` to `size` using the specified `method`. + + Resized images will be distorted if their original aspect ratio is not + the same as `size`. To avoid distortions see + `tf.image.resize_with_pad` or `tf.image.resize_with_crop_or_pad`. + + The `method` can be one of: + + * `tf.image.ResizeMethod.BILINEAR`: [Bilinear interpolation.]( + https://en.wikipedia.org/wiki/Bilinear_interpolation) + * `tf.image.ResizeMethod.NEAREST_NEIGHBOR`: [ + Nearest neighbor interpolation.]( + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation) + * `tf.image.ResizeMethod.BICUBIC`: [Bicubic interpolation.]( + https://en.wikipedia.org/wiki/Bicubic_interpolation) + * `tf.image.ResizeMethod.AREA`: Area interpolation. + + The return value has the same type as `images` if `method` is + `tf.image.ResizeMethod.NEAREST_NEIGHBOR`. It will also have the same type + as `images` if the size of `images` can be statically determined to be the + same as `size`, because `images` is returned in this case. Otherwise, the + return value has type `float32`. + + Args: + images: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The new + size for the images. + method: ResizeMethod. Defaults to `tf.image.ResizeMethod.BILINEAR`. + align_corners: bool. If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the corner + pixels. Defaults to `False`. + preserve_aspect_ratio: Whether to preserve the aspect ratio. If this is set, + then `images` will be resized to a size that fits in `size` while + preserving the aspect ratio of the original image. Scales up the image if + `size` is bigger than the current size of the `image`. Defaults to False. + name: A name for this operation (optional). + + Raises: + ValueError: if the shape of `images` is incompatible with the + shape arguments to this function + ValueError: if `size` has invalid shape or type. + ValueError: if an unsupported resize method is specified. + + Returns: + If `images` was 4-D, a 4-D float Tensor of shape + `[batch, new_height, new_width, channels]`. + If `images` was 3-D, a 3-D float Tensor of shape + `[new_height, new_width, channels]`. + """ + + def resize_fn(images_t, new_size): + """Legacy resize core function, passed to _resize_images_common.""" + if method == ResizeMethodV1.BILINEAR or method == ResizeMethod.BILINEAR: + return gen_image_ops.resize_bilinear( + images_t, new_size, align_corners=align_corners) + elif (method == ResizeMethodV1.NEAREST_NEIGHBOR or + method == ResizeMethod.NEAREST_NEIGHBOR): + return gen_image_ops.resize_nearest_neighbor( + images_t, new_size, align_corners=align_corners) + elif method == ResizeMethodV1.BICUBIC or method == ResizeMethod.BICUBIC: + return gen_image_ops.resize_bicubic( + images_t, new_size, align_corners=align_corners) + elif method == ResizeMethodV1.AREA or method == ResizeMethod.AREA: + return gen_image_ops.resize_area( + images_t, new_size, align_corners=align_corners) + else: + raise ValueError('Resize method is not implemented: {}'.format(method)) + + return _resize_images_common( + images, + resize_fn, + size, + preserve_aspect_ratio=preserve_aspect_ratio, + name=name, + skip_resize_if_same=True) + + +@tf_export('image.resize', v1=[]) +@dispatch.add_dispatch_support +def resize_images_v2(images, + size, + method=ResizeMethod.BILINEAR, + preserve_aspect_ratio=False, + antialias=False, + name=None): + """Resize `images` to `size` using the specified `method`. + + Resized images will be distorted if their original aspect ratio is not + the same as `size`. To avoid distortions see + `tf.image.resize_with_pad`. + + >>> image = tf.constant([ + ... [1,0,0,0,0], + ... [0,1,0,0,0], + ... [0,0,1,0,0], + ... [0,0,0,1,0], + ... [0,0,0,0,1], + ... ]) + >>> # Add "batch" and "channels" dimensions + >>> image = image[tf.newaxis, ..., tf.newaxis] + >>> image.shape.as_list() # [batch, height, width, channels] + [1, 5, 5, 1] + >>> tf.image.resize(image, [3,5])[0,...,0].numpy() + array([[0.6666667, 0.3333333, 0. , 0. , 0. ], + [0. , 0. , 1. , 0. , 0. ], + [0. , 0. , 0. , 0.3333335, 0.6666665]], + dtype=float32) + + It works equally well with a single image instead of a batch of images: + + >>> tf.image.resize(image[0], [3,5]).shape.as_list() + [3, 5, 1] + + When `antialias` is true, the sampling filter will anti-alias the input image + as well as interpolate. When downsampling an image with [anti-aliasing]( + https://en.wikipedia.org/wiki/Spatial_anti-aliasing) the sampling filter + kernel is scaled in order to properly anti-alias the input image signal. + `antialias` has no effect when upsampling an image: + + >>> a = tf.image.resize(image, [5,10]) + >>> b = tf.image.resize(image, [5,10], antialias=True) + >>> tf.reduce_max(abs(a - b)).numpy() + 0.0 + + The `method` argument expects an item from the `image.ResizeMethod` enum, or + the string equivalent. The options are: + + * `bilinear`: [Bilinear interpolation.]( + https://en.wikipedia.org/wiki/Bilinear_interpolation) If `antialias` is + true, becomes a hat/tent filter function with radius 1 when downsampling. + * `lanczos3`: [Lanczos kernel]( + https://en.wikipedia.org/wiki/Lanczos_resampling) with radius 3. + High-quality practical filter but may have some ringing, especially on + synthetic images. + * `lanczos5`: [Lanczos kernel] ( + https://en.wikipedia.org/wiki/Lanczos_resampling) with radius 5. + Very-high-quality filter but may have stronger ringing. + * `bicubic`: [Cubic interpolant]( + https://en.wikipedia.org/wiki/Bicubic_interpolation) of Keys. Equivalent to + Catmull-Rom kernel. Reasonably good quality and faster than Lanczos3Kernel, + particularly when upsampling. + * `gaussian`: [Gaussian kernel]( + https://en.wikipedia.org/wiki/Gaussian_filter) with radius 3, + sigma = 1.5 / 3.0. + * `nearest`: [Nearest neighbor interpolation.]( + https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation) + `antialias` has no effect when used with nearest neighbor interpolation. + * `area`: Anti-aliased resampling with area interpolation. + `antialias` has no effect when used with area interpolation; it + always anti-aliases. + * `mitchellcubic`: Mitchell-Netravali Cubic non-interpolating filter. + For synthetic images (especially those lacking proper prefiltering), less + ringing than Keys cubic kernel but less sharp. + + Note: Near image edges the filtering kernel may be partially outside the + image boundaries. For these pixels, only input pixels inside the image will be + included in the filter sum, and the output value will be appropriately + normalized. + + The return value has type `float32`, unless the `method` is + `ResizeMethod.NEAREST_NEIGHBOR`, then the return dtype is the dtype + of `images`: + + >>> nn = tf.image.resize(image, [5,7], method='nearest') + >>> nn[0,...,0].numpy() + array([[1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 1]], dtype=int32) + + With `preserve_aspect_ratio=True`, the aspect ratio is preserved, so `size` + is the maximum for each dimension: + + >>> max_10_20 = tf.image.resize(image, [10,20], preserve_aspect_ratio=True) + >>> max_10_20.shape.as_list() + [1, 10, 10, 1] + + Args: + images: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + size: A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The new + size for the images. + method: An `image.ResizeMethod`, or string equivalent. Defaults to + `bilinear`. + preserve_aspect_ratio: Whether to preserve the aspect ratio. If this is set, + then `images` will be resized to a size that fits in `size` while + preserving the aspect ratio of the original image. Scales up the image if + `size` is bigger than the current size of the `image`. Defaults to False. + antialias: Whether to use an anti-aliasing filter when downsampling an + image. + name: A name for this operation (optional). + + Raises: + ValueError: if the shape of `images` is incompatible with the + shape arguments to this function + ValueError: if `size` has an invalid shape or type. + ValueError: if an unsupported resize method is specified. + + Returns: + If `images` was 4-D, a 4-D float Tensor of shape + `[batch, new_height, new_width, channels]`. + If `images` was 3-D, a 3-D float Tensor of shape + `[new_height, new_width, channels]`. + """ + + def resize_fn(images_t, new_size): + """Resize core function, passed to _resize_images_common.""" + scale_and_translate_methods = [ + ResizeMethod.LANCZOS3, ResizeMethod.LANCZOS5, ResizeMethod.GAUSSIAN, + ResizeMethod.MITCHELLCUBIC + ] + + def resize_with_scale_and_translate(method): + scale = ( + math_ops.cast(new_size, dtype=dtypes.float32) / + math_ops.cast(array_ops.shape(images_t)[1:3], dtype=dtypes.float32)) + return gen_image_ops.scale_and_translate( + images_t, + new_size, + scale, + array_ops.zeros([2]), + kernel_type=method, + antialias=antialias) + + if method == ResizeMethod.BILINEAR: + if antialias: + return resize_with_scale_and_translate('triangle') + else: + return gen_image_ops.resize_bilinear( + images_t, new_size, half_pixel_centers=True) + elif method == ResizeMethod.NEAREST_NEIGHBOR: + return gen_image_ops.resize_nearest_neighbor( + images_t, new_size, half_pixel_centers=True) + elif method == ResizeMethod.BICUBIC: + if antialias: + return resize_with_scale_and_translate('keyscubic') + else: + return gen_image_ops.resize_bicubic( + images_t, new_size, half_pixel_centers=True) + elif method == ResizeMethod.AREA: + return gen_image_ops.resize_area(images_t, new_size) + elif method in scale_and_translate_methods: + return resize_with_scale_and_translate(method) + else: + raise ValueError('Resize method is not implemented: {}'.format(method)) + + return _resize_images_common( + images, + resize_fn, + size, + preserve_aspect_ratio=preserve_aspect_ratio, + name=name, + skip_resize_if_same=False) + + +def _resize_image_with_pad_common(image, target_height, target_width, + resize_fn): + """Core functionality for v1 and v2 resize_image_with_pad functions.""" + with ops.name_scope(None, 'resize_image_with_pad', [image]): + image = ops.convert_to_tensor(image, name='image') + image_shape = image.get_shape() + is_batch = True + if image_shape.ndims == 3: + is_batch = False + image = array_ops.expand_dims(image, 0) + elif image_shape.ndims is None: + is_batch = False + image = array_ops.expand_dims(image, 0) + image.set_shape([None] * 4) + elif image_shape.ndims != 4: + raise ValueError( + '\'image\' (shape %s) must have either 3 or 4 dimensions.' % + image_shape) + + assert_ops = _CheckAtLeast3DImage(image, require_static=False) + assert_ops += _assert(target_width > 0, ValueError, + 'target_width must be > 0.') + assert_ops += _assert(target_height > 0, ValueError, + 'target_height must be > 0.') + + image = control_flow_ops.with_dependencies(assert_ops, image) + + def max_(x, y): + if _is_tensor(x) or _is_tensor(y): + return math_ops.maximum(x, y) + else: + return max(x, y) + + _, height, width, _ = _ImageDimensions(image, rank=4) + + # convert values to float, to ease divisions + f_height = math_ops.cast(height, dtype=dtypes.float32) + f_width = math_ops.cast(width, dtype=dtypes.float32) + f_target_height = math_ops.cast(target_height, dtype=dtypes.float32) + f_target_width = math_ops.cast(target_width, dtype=dtypes.float32) + + # Find the ratio by which the image must be adjusted + # to fit within the target + ratio = max_(f_width / f_target_width, f_height / f_target_height) + resized_height_float = f_height / ratio + resized_width_float = f_width / ratio + resized_height = math_ops.cast( + math_ops.floor(resized_height_float), dtype=dtypes.int32) + resized_width = math_ops.cast( + math_ops.floor(resized_width_float), dtype=dtypes.int32) + + padding_height = (f_target_height - resized_height_float) / 2 + padding_width = (f_target_width - resized_width_float) / 2 + f_padding_height = math_ops.floor(padding_height) + f_padding_width = math_ops.floor(padding_width) + p_height = max_(0, math_ops.cast(f_padding_height, dtype=dtypes.int32)) + p_width = max_(0, math_ops.cast(f_padding_width, dtype=dtypes.int32)) + + # Resize first, then pad to meet requested dimensions + resized = resize_fn(image, [resized_height, resized_width]) + + padded = pad_to_bounding_box(resized, p_height, p_width, target_height, + target_width) + + if padded.get_shape().ndims is None: + raise ValueError('padded contains no shape.') + + _ImageDimensions(padded, rank=4) + + if not is_batch: + padded = array_ops.squeeze(padded, axis=[0]) + + return padded + + +@tf_export(v1=['image.resize_image_with_pad']) +@dispatch.add_dispatch_support +def resize_image_with_pad_v1(image, + target_height, + target_width, + method=ResizeMethodV1.BILINEAR, + align_corners=False): + """Resizes and pads an image to a target width and height. + + Resizes an image to a target width and height by keeping + the aspect ratio the same without distortion. If the target + dimensions don't match the image dimensions, the image + is resized and then padded with zeroes to match requested + dimensions. + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + target_height: Target height. + target_width: Target width. + method: Method to use for resizing image. See `resize_images()` + align_corners: bool. If True, the centers of the 4 corner pixels of the + input and output tensors are aligned, preserving the values at the corner + pixels. Defaults to `False`. + + Raises: + ValueError: if `target_height` or `target_width` are zero or negative. + + Returns: + Resized and padded image. + If `images` was 4-D, a 4-D float Tensor of shape + `[batch, new_height, new_width, channels]`. + If `images` was 3-D, a 3-D float Tensor of shape + `[new_height, new_width, channels]`. + """ + + def _resize_fn(im, new_size): + return resize_images(im, new_size, method, align_corners=align_corners) + + return _resize_image_with_pad_common(image, target_height, target_width, + _resize_fn) + + +@tf_export('image.resize_with_pad', v1=[]) +@dispatch.add_dispatch_support +def resize_image_with_pad_v2(image, + target_height, + target_width, + method=ResizeMethod.BILINEAR, + antialias=False): + """Resizes and pads an image to a target width and height. + + Resizes an image to a target width and height by keeping + the aspect ratio the same without distortion. If the target + dimensions don't match the image dimensions, the image + is resized and then padded with zeroes to match requested + dimensions. + + Args: + image: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + target_height: Target height. + target_width: Target width. + method: Method to use for resizing image. See `image.resize()` + antialias: Whether to use anti-aliasing when resizing. See 'image.resize()'. + + Raises: + ValueError: if `target_height` or `target_width` are zero or negative. + + Returns: + Resized and padded image. + If `images` was 4-D, a 4-D float Tensor of shape + `[batch, new_height, new_width, channels]`. + If `images` was 3-D, a 3-D float Tensor of shape + `[new_height, new_width, channels]`. + """ + + def _resize_fn(im, new_size): + return resize_images_v2(im, new_size, method, antialias=antialias) + + return _resize_image_with_pad_common(image, target_height, target_width, + _resize_fn) + + +@tf_export('image.per_image_standardization') +@dispatch.add_dispatch_support +def per_image_standardization(image): + """Linearly scales each image in `image` to have mean 0 and variance 1. + + For each 3-D image `x` in `image`, computes `(x - mean) / adjusted_stddev`, + where + + - `mean` is the average of all values in `x` + - `adjusted_stddev = max(stddev, 1.0/sqrt(N))` is capped away from 0 to + protect against division by 0 when handling uniform images + - `N` is the number of elements in `x` + - `stddev` is the standard deviation of all values in `x` + + Example Usage: + + >>> image = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) + >>> image # 3-D tensor + + >>> new_image = tf.image.per_image_standardization(image) + >>> new_image # 3-D tensor with mean ~= 0 and variance ~= 1 + + + Args: + image: An n-D `Tensor` with at least 3 dimensions, the last 3 of which are + the dimensions of each image. + + Returns: + A `Tensor` with the same shape as `image` and its dtype is `float32`. + + Raises: + ValueError: The shape of `image` has fewer than 3 dimensions. + """ + with ops.name_scope(None, 'per_image_standardization', [image]) as scope: + image = ops.convert_to_tensor(image, name='image') + image = _AssertAtLeast3DImage(image) + + image = math_ops.cast(image, dtype=dtypes.float32) + num_pixels = math_ops.reduce_prod(array_ops.shape(image)[-3:]) + image_mean = math_ops.reduce_mean(image, axis=[-1, -2, -3], keepdims=True) + + # Apply a minimum normalization that protects us against uniform images. + stddev = math_ops.reduce_std(image, axis=[-1, -2, -3], keepdims=True) + min_stddev = math_ops.rsqrt(math_ops.cast(num_pixels, dtypes.float32)) + adjusted_stddev = math_ops.maximum(stddev, min_stddev) + + image -= image_mean + image = math_ops.divide(image, adjusted_stddev, name=scope) + return image + + +@tf_export('image.random_brightness') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def random_brightness(image, max_delta, seed=None): + """Adjust the brightness of images by a random factor. + + Equivalent to `adjust_brightness()` using a `delta` randomly picked in the + interval `[-max_delta, max_delta)`. + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_brightness`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: An image or images to adjust. + max_delta: float, must be non-negative. + seed: A Python integer. Used to create a random seed. See + `tf.compat.v1.set_random_seed` for behavior. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.random_brightness(x, 0.2) + + + Returns: + The brightness-adjusted image(s). + + Raises: + ValueError: if `max_delta` is negative. + """ + if max_delta < 0: + raise ValueError('max_delta must be non-negative.') + + delta = random_ops.random_uniform([], -max_delta, max_delta, seed=seed) + return adjust_brightness(image, delta) + + +@tf_export('image.stateless_random_brightness', v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def stateless_random_brightness(image, max_delta, seed): + """Adjust the brightness of images by a random factor deterministically. + + Equivalent to `adjust_brightness()` using a `delta` randomly picked in the + interval `[-max_delta, max_delta)`. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> seed = (1, 2) + >>> tf.image.stateless_random_brightness(x, 0.2, seed) + + + Args: + image: An image or images to adjust. + max_delta: float, must be non-negative. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Returns: + The brightness-adjusted image(s). + + Raises: + ValueError: if `max_delta` is negative. + """ + if max_delta < 0: + raise ValueError('max_delta must be non-negative.') + + delta = stateless_random_ops.stateless_random_uniform( + shape=[], minval=-max_delta, maxval=max_delta, seed=seed) + return adjust_brightness(image, delta) + + +@tf_export('image.random_contrast') +@dispatch.add_dispatch_support +def random_contrast(image, lower, upper, seed=None): + """Adjust the contrast of an image or images by a random factor. + + Equivalent to `adjust_contrast()` but uses a `contrast_factor` randomly + picked in the interval `[lower, upper)`. + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_contrast`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: An image tensor with 3 or more dimensions. + lower: float. Lower bound for the random contrast factor. + upper: float. Upper bound for the random contrast factor. + seed: A Python integer. Used to create a random seed. See + `tf.compat.v1.set_random_seed` for behavior. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.random_contrast(x, 0.2, 0.5) + + + Returns: + The contrast-adjusted image(s). + + Raises: + ValueError: if `upper <= lower` or if `lower < 0`. + """ + if upper <= lower: + raise ValueError('upper must be > lower.') + + if lower < 0: + raise ValueError('lower must be non-negative.') + + contrast_factor = random_ops.random_uniform([], lower, upper, seed=seed) + return adjust_contrast(image, contrast_factor) + + +@tf_export('image.stateless_random_contrast', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_contrast(image, lower, upper, seed): + """Adjust the contrast of images by a random factor deterministically. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Args: + image: An image tensor with 3 or more dimensions. + lower: float. Lower bound for the random contrast factor. + upper: float. Upper bound for the random contrast factor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> seed = (1, 2) + >>> tf.image.stateless_random_contrast(x, 0.2, 0.5, seed) + + + Returns: + The contrast-adjusted image(s). + + Raises: + ValueError: if `upper <= lower` or if `lower < 0`. + """ + if upper <= lower: + raise ValueError('upper must be > lower.') + + if lower < 0: + raise ValueError('lower must be non-negative.') + + contrast_factor = stateless_random_ops.stateless_random_uniform( + shape=[], minval=lower, maxval=upper, seed=seed) + return adjust_contrast(image, contrast_factor) + + +@tf_export('image.adjust_brightness') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def adjust_brightness(image, delta): + """Adjust the brightness of RGB or Grayscale images. + + This is a convenience method that converts RGB images to float + representation, adjusts their brightness, and then converts them back to the + original data type. If several adjustments are chained, it is advisable to + minimize the number of redundant conversions. + + The value `delta` is added to all components of the tensor `image`. `image` is + converted to `float` and scaled appropriately if it is in fixed-point + representation, and `delta` is converted to the same data type. For regular + images, `delta` should be in the range `(-1,1)`, as it is added to the image + in floating point representation, where pixel values are in the `[0,1)` range. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_brightness(x, delta=0.1) + + + Args: + image: RGB image or images to adjust. + delta: A scalar. Amount to add to the pixel values. + + Returns: + A brightness-adjusted tensor of the same shape and type as `image`. + """ + with ops.name_scope(None, 'adjust_brightness', [image, delta]) as name: + image = ops.convert_to_tensor(image, name='image') + # Remember original dtype to so we can convert back if needed + orig_dtype = image.dtype + + if orig_dtype in [dtypes.float16, dtypes.float32]: + flt_image = image + else: + flt_image = convert_image_dtype(image, dtypes.float32) + + adjusted = math_ops.add( + flt_image, math_ops.cast(delta, flt_image.dtype), name=name) + + return convert_image_dtype(adjusted, orig_dtype, saturate=True) + + +@tf_export('image.adjust_contrast') +@dispatch.add_dispatch_support +def adjust_contrast(images, contrast_factor): + """Adjust contrast of RGB or grayscale images. + + This is a convenience method that converts RGB images to float + representation, adjusts their contrast, and then converts them back to the + original data type. If several adjustments are chained, it is advisable to + minimize the number of redundant conversions. + + `images` is a tensor of at least 3 dimensions. The last 3 dimensions are + interpreted as `[height, width, channels]`. The other dimensions only + represent a collection of images, such as `[batch, height, width, channels].` + + Contrast is adjusted independently for each channel of each image. + + For each channel, this Op computes the mean of the image pixels in the + channel and then adjusts each component `x` of each pixel to + `(x - mean) * contrast_factor + mean`. + + `contrast_factor` must be in the interval `(-inf, inf)`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_contrast(x, 2.) + + + Args: + images: Images to adjust. At least 3-D. + contrast_factor: A float multiplier for adjusting contrast. + + Returns: + The contrast-adjusted image or images. + """ + with ops.name_scope(None, 'adjust_contrast', + [images, contrast_factor]) as name: + images = ops.convert_to_tensor(images, name='images') + # Remember original dtype to so we can convert back if needed + orig_dtype = images.dtype + + if orig_dtype in (dtypes.float16, dtypes.float32): + flt_images = images + else: + flt_images = convert_image_dtype(images, dtypes.float32) + + adjusted = gen_image_ops.adjust_contrastv2( + flt_images, contrast_factor=contrast_factor, name=name) + + return convert_image_dtype(adjusted, orig_dtype, saturate=True) + + +@tf_export('image.adjust_gamma') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def adjust_gamma(image, gamma=1, gain=1): + """Performs [Gamma Correction](http://en.wikipedia.org/wiki/Gamma_correction). + + on the input image. + + Also known as Power Law Transform. This function converts the + input images at first to float representation, then transforms them + pixelwise according to the equation `Out = gain * In**gamma`, + and then converts the back to the original data type. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_gamma(x, 0.2) + + + Args: + image : RGB image or images to adjust. + gamma : A scalar or tensor. Non-negative real number. + gain : A scalar or tensor. The constant multiplier. + + Returns: + A Tensor. A Gamma-adjusted tensor of the same shape and type as `image`. + + Raises: + ValueError: If gamma is negative. + Notes: + For gamma greater than 1, the histogram will shift towards left and + the output image will be darker than the input image. + For gamma less than 1, the histogram will shift towards right and + the output image will be brighter than the input image. + References: + [Wikipedia](http://en.wikipedia.org/wiki/Gamma_correction) + """ + + with ops.name_scope(None, 'adjust_gamma', [image, gamma, gain]) as name: + image = ops.convert_to_tensor(image, name='image') + # Remember original dtype to so we can convert back if needed + orig_dtype = image.dtype + + if orig_dtype in [dtypes.float16, dtypes.float32]: + flt_image = image + else: + flt_image = convert_image_dtype(image, dtypes.float32) + + assert_op = _assert(gamma >= 0, ValueError, + 'Gamma should be a non-negative real number.') + if assert_op: + gamma = control_flow_ops.with_dependencies(assert_op, gamma) + + # According to the definition of gamma correction. + adjusted_img = gain * flt_image**gamma + + return convert_image_dtype(adjusted_img, orig_dtype, saturate=True) + + +@tf_export('image.convert_image_dtype') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def convert_image_dtype(image, dtype, saturate=False, name=None): + """Convert `image` to `dtype`, scaling its values if needed. + + The operation supports data types (for `image` and `dtype`) of + `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, + `float16`, `float32`, `float64`, `bfloat16`. + + Images that are represented using floating point values are expected to have + values in the range [0,1). Image data stored in integer data types are + expected to have values in the range `[0,MAX]`, where `MAX` is the largest + positive representable number for the data type. + + This op converts between data types, scaling the values appropriately before + casting. + + Usage Example: + + >>> x = [[[1, 2, 3], [4, 5, 6]], + ... [[7, 8, 9], [10, 11, 12]]] + >>> x_int8 = tf.convert_to_tensor(x, dtype=tf.int8) + >>> tf.image.convert_image_dtype(x_int8, dtype=tf.float16, saturate=False) + + + Converting integer types to floating point types returns normalized floating + point values in the range [0, 1); the values are normalized by the `MAX` value + of the input dtype. Consider the following two examples: + + >>> a = [[[1], [2]], [[3], [4]]] + >>> a_int8 = tf.convert_to_tensor(a, dtype=tf.int8) + >>> tf.image.convert_image_dtype(a_int8, dtype=tf.float32) + + + >>> a_int32 = tf.convert_to_tensor(a, dtype=tf.int32) + >>> tf.image.convert_image_dtype(a_int32, dtype=tf.float32) + + + Despite having identical values of `a` and output dtype of `float32`, the + outputs differ due to the different input dtypes (`int8` vs. `int32`). This + is, again, because the values are normalized by the `MAX` value of the input + dtype. + + Note that converting floating point values to integer type may lose precision. + In the example below, an image tensor `b` of dtype `float32` is converted to + `int8` and back to `float32`. The final output, however, is different from + the original input `b` due to precision loss. + + >>> b = [[[0.12], [0.34]], [[0.56], [0.78]]] + >>> b_float32 = tf.convert_to_tensor(b, dtype=tf.float32) + >>> b_int8 = tf.image.convert_image_dtype(b_float32, dtype=tf.int8) + >>> tf.image.convert_image_dtype(b_int8, dtype=tf.float32) + + + Scaling up from an integer type (input dtype) to another integer type (output + dtype) will not map input dtype's `MAX` to output dtype's `MAX` but converting + back and forth should result in no change. For example, as shown below, the + `MAX` value of int8 (=127) is not mapped to the `MAX` value of int16 (=32,767) + but, when scaled back, we get the same, original values of `c`. + + >>> c = [[[1], [2]], [[127], [127]]] + >>> c_int8 = tf.convert_to_tensor(c, dtype=tf.int8) + >>> c_int16 = tf.image.convert_image_dtype(c_int8, dtype=tf.int16) + >>> print(c_int16) + tf.Tensor( + [[[ 256] + [ 512]] + [[32512] + [32512]]], shape=(2, 2, 1), dtype=int16) + >>> c_int8_back = tf.image.convert_image_dtype(c_int16, dtype=tf.int8) + >>> print(c_int8_back) + tf.Tensor( + [[[ 1] + [ 2]] + [[127] + [127]]], shape=(2, 2, 1), dtype=int8) + + Scaling down from an integer type to another integer type can be a lossy + conversion. Notice in the example below that converting `int16` to `uint8` and + back to `int16` has lost precision. + + >>> d = [[[1000], [2000]], [[3000], [4000]]] + >>> d_int16 = tf.convert_to_tensor(d, dtype=tf.int16) + >>> d_uint8 = tf.image.convert_image_dtype(d_int16, dtype=tf.uint8) + >>> d_int16_back = tf.image.convert_image_dtype(d_uint8, dtype=tf.int16) + >>> print(d_int16_back) + tf.Tensor( + [[[ 896] + [1920]] + [[2944] + [3968]]], shape=(2, 2, 1), dtype=int16) + + Note that converting from floating point inputs to integer types may lead to + over/underflow problems. Set saturate to `True` to avoid such problem in + problematic conversions. If enabled, saturation will clip the output into the + allowed range before performing a potentially dangerous cast (and only before + performing such a cast, i.e., when casting from a floating point to an integer + type, and when casting from a signed to an unsigned type; `saturate` has no + effect on casts between floats, or on casts that increase the type's range). + + Args: + image: An image. + dtype: A `DType` to convert `image` to. + saturate: If `True`, clip the input before casting (if necessary). + name: A name for this operation (optional). + + Returns: + `image`, converted to `dtype`. + + Raises: + AttributeError: Raises an attribute error when dtype is neither + float nor integer. + """ + image = ops.convert_to_tensor(image, name='image') + dtype = dtypes.as_dtype(dtype) + if not dtype.is_floating and not dtype.is_integer: + raise AttributeError('dtype must be either floating point or integer') + if not image.dtype.is_floating and not image.dtype.is_integer: + raise AttributeError('image dtype must be either floating point or integer') + if dtype == image.dtype: + return array_ops.identity(image, name=name) + + with ops.name_scope(name, 'convert_image', [image]) as name: + # Both integer: use integer multiplication in the larger range + if image.dtype.is_integer and dtype.is_integer: + scale_in = image.dtype.max + scale_out = dtype.max + if scale_in > scale_out: + # Scaling down, scale first, then cast. The scaling factor will + # cause in.max to be mapped to above out.max but below out.max+1, + # so that the output is safely in the supported range. + scale = (scale_in + 1) // (scale_out + 1) + scaled = math_ops.floordiv(image, scale) + + if saturate: + return math_ops.saturate_cast(scaled, dtype, name=name) + else: + return math_ops.cast(scaled, dtype, name=name) + else: + # Scaling up, cast first, then scale. The scale will not map in.max to + # out.max, but converting back and forth should result in no change. + if saturate: + cast = math_ops.saturate_cast(image, dtype) + else: + cast = math_ops.cast(image, dtype) + scale = (scale_out + 1) // (scale_in + 1) + return math_ops.multiply(cast, scale, name=name) + elif image.dtype.is_floating and dtype.is_floating: + # Both float: Just cast, no possible overflows in the allowed ranges. + # Note: We're ignoring float overflows. If your image dynamic range + # exceeds float range, you're on your own. + return math_ops.cast(image, dtype, name=name) + else: + if image.dtype.is_integer: + # Converting to float: first cast, then scale. No saturation possible. + cast = math_ops.cast(image, dtype) + scale = 1. / image.dtype.max + return math_ops.multiply(cast, scale, name=name) + else: + # Converting from float: first scale, then cast + scale = dtype.max + 0.5 # avoid rounding problems in the cast + scaled = math_ops.multiply(image, scale) + if saturate: + return math_ops.saturate_cast(scaled, dtype, name=name) + else: + return math_ops.cast(scaled, dtype, name=name) + + +@tf_export('image.rgb_to_grayscale') +@dispatch.add_dispatch_support +def rgb_to_grayscale(images, name=None): + """Converts one or more images from RGB to Grayscale. + + Outputs a tensor of the same `DType` and rank as `images`. The size of the + last dimension of the output is 1, containing the Grayscale value of the + pixels. + + >>> original = tf.constant([[[1.0, 2.0, 3.0]]]) + >>> converted = tf.image.rgb_to_grayscale(original) + >>> print(converted.numpy()) + [[[1.81...]]] + + Args: + images: The RGB tensor to convert. The last dimension must have size 3 and + should contain RGB values. + name: A name for the operation (optional). + + Returns: + The converted grayscale image(s). + """ + with ops.name_scope(name, 'rgb_to_grayscale', [images]) as name: + images = ops.convert_to_tensor(images, name='images') + # Remember original dtype to so we can convert back if needed + orig_dtype = images.dtype + flt_image = convert_image_dtype(images, dtypes.float32) + + # Reference for converting between RGB and grayscale. + # https://en.wikipedia.org/wiki/Luma_%28video%29 + rgb_weights = [0.2989, 0.5870, 0.1140] + gray_float = math_ops.tensordot(flt_image, rgb_weights, [-1, -1]) + gray_float = array_ops.expand_dims(gray_float, -1) + return convert_image_dtype(gray_float, orig_dtype, name=name) + + +@tf_export('image.grayscale_to_rgb') +@dispatch.add_dispatch_support +def grayscale_to_rgb(images, name=None): + """Converts one or more images from Grayscale to RGB. + + Outputs a tensor of the same `DType` and rank as `images`. The size of the + last dimension of the output is 3, containing the RGB value of the pixels. + The input images' last dimension must be size 1. + + >>> original = tf.constant([[[1.0], [2.0], [3.0]]]) + >>> converted = tf.image.grayscale_to_rgb(original) + >>> print(converted.numpy()) + [[[1. 1. 1.] + [2. 2. 2.] + [3. 3. 3.]]] + + Args: + images: The Grayscale tensor to convert. The last dimension must be size 1. + name: A name for the operation (optional). + + Returns: + The converted grayscale image(s). + """ + with ops.name_scope(name, 'grayscale_to_rgb', [images]) as name: + images = _AssertGrayscaleImage(images) + + images = ops.convert_to_tensor(images, name='images') + rank_1 = array_ops.expand_dims(array_ops.rank(images) - 1, 0) + shape_list = ([array_ops.ones(rank_1, dtype=dtypes.int32)] + + [array_ops.expand_dims(3, 0)]) + multiples = array_ops.concat(shape_list, 0) + rgb = array_ops.tile(images, multiples, name=name) + rgb.set_shape(images.get_shape()[:-1].concatenate([3])) + return rgb + + +# pylint: disable=invalid-name +@tf_export('image.random_hue') +@dispatch.add_dispatch_support +def random_hue(image, max_delta, seed=None): + """Adjust the hue of RGB images by a random factor. + + Equivalent to `adjust_hue()` but uses a `delta` randomly + picked in the interval `[-max_delta, max_delta)`. + + `max_delta` must be in the interval `[0, 0.5]`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.random_hue(x, 0.2) + + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_hue`. Unlike using the `seed` param with + `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same + results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: RGB image or images. The size of the last dimension must be 3. + max_delta: float. The maximum value for the random delta. + seed: An operation-specific seed. It will be used in conjunction with the + graph-level seed to determine the real seeds that will be used in this + operation. Please see the documentation of set_random_seed for its + interaction with the graph-level random seed. + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `max_delta` is invalid. + """ + if max_delta > 0.5: + raise ValueError('max_delta must be <= 0.5.') + + if max_delta < 0: + raise ValueError('max_delta must be non-negative.') + + delta = random_ops.random_uniform([], -max_delta, max_delta, seed=seed) + return adjust_hue(image, delta) + + +@tf_export('image.stateless_random_hue', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_hue(image, max_delta, seed): + """Adjust the hue of RGB images by a random factor deterministically. + + Equivalent to `adjust_hue()` but uses a `delta` randomly picked in the + interval `[-max_delta, max_delta)`. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + `max_delta` must be in the interval `[0, 0.5]`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> seed = (1, 2) + >>> tf.image.stateless_random_hue(x, 0.2, seed) + + + Args: + image: RGB image or images. The size of the last dimension must be 3. + max_delta: float. The maximum value for the random delta. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `max_delta` is invalid. + """ + if max_delta > 0.5: + raise ValueError('max_delta must be <= 0.5.') + + if max_delta < 0: + raise ValueError('max_delta must be non-negative.') + + delta = stateless_random_ops.stateless_random_uniform( + shape=[], minval=-max_delta, maxval=max_delta, seed=seed) + return adjust_hue(image, delta) + + +@tf_export('image.adjust_hue') +@dispatch.add_dispatch_support +def adjust_hue(image, delta, name=None): + """Adjust hue of RGB images. + + This is a convenience method that converts an RGB image to float + representation, converts it to HSV, adds an offset to the + hue channel, converts back to RGB and then back to the original + data type. If several adjustments are chained it is advisable to minimize + the number of redundant conversions. + + `image` is an RGB image. The image hue is adjusted by converting the + image(s) to HSV and rotating the hue channel (H) by + `delta`. The image is then converted back to RGB. + + `delta` must be in the interval `[-1, 1]`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_hue(x, 0.2) + + + Args: + image: RGB image or images. The size of the last dimension must be 3. + delta: float. How much to add to the hue channel. + name: A name for this operation (optional). + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + InvalidArgumentError: image must have at least 3 dimensions. + InvalidArgumentError: The size of the last dimension must be 3. + ValueError: if `delta` is not in the interval of `[-1, 1]`. + + Usage Example: + + >>> image = [[[1, 2, 3], [4, 5, 6]], + ... [[7, 8, 9], [10, 11, 12]], + ... [[13, 14, 15], [16, 17, 18]]] + >>> image = tf.constant(image) + >>> tf.image.adjust_hue(image, 0.2) + + """ + with ops.name_scope(name, 'adjust_hue', [image]) as name: + if context.executing_eagerly(): + if delta < -1 or delta > 1: + raise ValueError('delta must be in the interval [-1, 1]') + image = ops.convert_to_tensor(image, name='image') + # Remember original dtype to so we can convert back if needed + orig_dtype = image.dtype + if orig_dtype in (dtypes.float16, dtypes.float32): + flt_image = image + else: + flt_image = convert_image_dtype(image, dtypes.float32) + + rgb_altered = gen_image_ops.adjust_hue(flt_image, delta) + + return convert_image_dtype(rgb_altered, orig_dtype) + + +# pylint: disable=invalid-name +@tf_export('image.random_jpeg_quality') +@dispatch.add_dispatch_support +def random_jpeg_quality(image, min_jpeg_quality, max_jpeg_quality, seed=None): + """Randomly changes jpeg encoding quality for inducing jpeg noise. + + `min_jpeg_quality` must be in the interval `[0, 100]` and less than + `max_jpeg_quality`. + `max_jpeg_quality` must be in the interval `[0, 100]`. + + Usage Example: + + >>> x = tf.constant([[[1, 2, 3], + ... [4, 5, 6]], + ... [[7, 8, 9], + ... [10, 11, 12]]], dtype=tf.uint8) + >>> tf.image.random_jpeg_quality(x, 75, 95) + + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_jpeg_quality`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: 3D image. Size of the last dimension must be 1 or 3. + min_jpeg_quality: Minimum jpeg encoding quality to use. + max_jpeg_quality: Maximum jpeg encoding quality to use. + seed: An operation-specific seed. It will be used in conjunction with the + graph-level seed to determine the real seeds that will be used in this + operation. Please see the documentation of set_random_seed for its + interaction with the graph-level random seed. + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `min_jpeg_quality` or `max_jpeg_quality` is invalid. + """ + if (min_jpeg_quality < 0 or max_jpeg_quality < 0 or min_jpeg_quality > 100 or + max_jpeg_quality > 100): + raise ValueError('jpeg encoding range must be between 0 and 100.') + + if min_jpeg_quality >= max_jpeg_quality: + raise ValueError('`min_jpeg_quality` must be less than `max_jpeg_quality`.') + + jpeg_quality = random_ops.random_uniform([], + min_jpeg_quality, + max_jpeg_quality, + seed=seed, + dtype=dtypes.int32) + return adjust_jpeg_quality(image, jpeg_quality) + + +@tf_export('image.stateless_random_jpeg_quality', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_jpeg_quality(image, + min_jpeg_quality, + max_jpeg_quality, + seed): + """Deterministically radomize jpeg encoding quality for inducing jpeg noise. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + `min_jpeg_quality` must be in the interval `[0, 100]` and less than + `max_jpeg_quality`. + `max_jpeg_quality` must be in the interval `[0, 100]`. + + Usage Example: + + >>> x = tf.constant([[[1, 2, 3], + ... [4, 5, 6]], + ... [[7, 8, 9], + ... [10, 11, 12]]], dtype=tf.uint8) + >>> seed = (1, 2) + >>> tf.image.stateless_random_jpeg_quality(x, 75, 95, seed) + + + Args: + image: 3D image. Size of the last dimension must be 1 or 3. + min_jpeg_quality: Minimum jpeg encoding quality to use. + max_jpeg_quality: Maximum jpeg encoding quality to use. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `min_jpeg_quality` or `max_jpeg_quality` is invalid. + """ + if (min_jpeg_quality < 0 or max_jpeg_quality < 0 or min_jpeg_quality > 100 or + max_jpeg_quality > 100): + raise ValueError('jpeg encoding range must be between 0 and 100.') + + if min_jpeg_quality >= max_jpeg_quality: + raise ValueError('`min_jpeg_quality` must be less than `max_jpeg_quality`.') + + jpeg_quality = stateless_random_ops.stateless_random_uniform( + shape=[], minval=min_jpeg_quality, maxval=max_jpeg_quality, seed=seed, + dtype=dtypes.int32) + return adjust_jpeg_quality(image, jpeg_quality) + + +@tf_export('image.adjust_jpeg_quality') +@dispatch.add_dispatch_support +def adjust_jpeg_quality(image, jpeg_quality, name=None): + """Adjust jpeg encoding quality of an image. + + This is a convenience method that converts an image to uint8 representation, + encodes it to jpeg with `jpeg_quality`, decodes it, and then converts back + to the original data type. + + `jpeg_quality` must be in the interval `[0, 100]`. + + Usage Examples: + + >>> x = [[[0.01, 0.02, 0.03], + ... [0.04, 0.05, 0.06]], + ... [[0.07, 0.08, 0.09], + ... [0.10, 0.11, 0.12]]] + >>> x_jpeg = tf.image.adjust_jpeg_quality(x, 75) + >>> x_jpeg.numpy() + array([[[0.00392157, 0.01960784, 0.03137255], + [0.02745098, 0.04313726, 0.05490196]], + [[0.05882353, 0.07450981, 0.08627451], + [0.08235294, 0.09803922, 0.10980393]]], dtype=float32) + + Note that floating point values are expected to have values in the range + [0,1) and values outside this range are clipped. + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_jpeg_quality(x, 75) + + + Note that `jpeg_quality` 100 is still lossy compresson. + + >>> x = tf.constant([[[1, 2, 3], + ... [4, 5, 6]], + ... [[7, 8, 9], + ... [10, 11, 12]]], dtype=tf.uint8) + >>> tf.image.adjust_jpeg_quality(x, 100) + + + Args: + image: 3D image. The size of the last dimension must be None, 1 or 3. + jpeg_quality: Python int or Tensor of type int32. jpeg encoding quality. + name: A name for this operation (optional). + + Returns: + Adjusted image, same shape and DType as `image`. + + Raises: + InvalidArgumentError: quality must be in [0,100] + InvalidArgumentError: image must have 1 or 3 channels + """ + with ops.name_scope(name, 'adjust_jpeg_quality', [image]): + image = ops.convert_to_tensor(image, name='image') + channels = image.shape.as_list()[-1] + # Remember original dtype to so we can convert back if needed + orig_dtype = image.dtype + image = convert_image_dtype(image, dtypes.uint8, saturate=True) + if not _is_tensor(jpeg_quality): + # If jpeg_quality is a int (not tensor). + jpeg_quality = ops.convert_to_tensor(jpeg_quality, dtype=dtypes.int32) + image = gen_image_ops.encode_jpeg_variable_quality(image, jpeg_quality) + + image = gen_image_ops.decode_jpeg(image, channels=channels) + return convert_image_dtype(image, orig_dtype, saturate=True) + + +@tf_export('image.random_saturation') +@dispatch.add_dispatch_support +def random_saturation(image, lower, upper, seed=None): + """Adjust the saturation of RGB images by a random factor. + + Equivalent to `adjust_saturation()` but uses a `saturation_factor` randomly + picked in the interval `[lower, upper)`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.random_saturation(x, 5, 10) + + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_saturation`. Unlike using the `seed` param + with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the + same results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + image: RGB image or images. The size of the last dimension must be 3. + lower: float. Lower bound for the random saturation factor. + upper: float. Upper bound for the random saturation factor. + seed: An operation-specific seed. It will be used in conjunction with the + graph-level seed to determine the real seeds that will be used in this + operation. Please see the documentation of set_random_seed for its + interaction with the graph-level random seed. + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `upper <= lower` or if `lower < 0`. + """ + if upper <= lower: + raise ValueError('upper must be > lower.') + + if lower < 0: + raise ValueError('lower must be non-negative.') + + saturation_factor = random_ops.random_uniform([], lower, upper, seed=seed) + return adjust_saturation(image, saturation_factor) + + +@tf_export('image.stateless_random_saturation', v1=[]) +@dispatch.add_dispatch_support +def stateless_random_saturation(image, lower, upper, seed=None): + """Adjust the saturation of RGB images by a random factor deterministically. + + Equivalent to `adjust_saturation()` but uses a `saturation_factor` randomly + picked in the interval `[lower, upper)`. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> seed = (1, 2) + >>> tf.image.stateless_random_saturation(x, 0.5, 1.0, seed) + + + Args: + image: RGB image or images. The size of the last dimension must be 3. + lower: float. Lower bound for the random saturation factor. + upper: float. Upper bound for the random saturation factor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + ValueError: if `upper <= lower` or if `lower < 0`. + """ + if upper <= lower: + raise ValueError('upper must be > lower.') + + if lower < 0: + raise ValueError('lower must be non-negative.') + + saturation_factor = stateless_random_ops.stateless_random_uniform( + shape=[], minval=lower, maxval=upper, seed=seed) + return adjust_saturation(image, saturation_factor) + + +@tf_export('image.adjust_saturation') +@dispatch.add_dispatch_support +def adjust_saturation(image, saturation_factor, name=None): + """Adjust saturation of RGB images. + + This is a convenience method that converts RGB images to float + representation, converts them to HSV, adds an offset to the + saturation channel, converts back to RGB and then back to the original + data type. If several adjustments are chained it is advisable to minimize + the number of redundant conversions. + + `image` is an RGB image or images. The image saturation is adjusted by + converting the images to HSV and multiplying the saturation (S) channel by + `saturation_factor` and clipping. The images are then converted back to RGB. + + `saturation_factor` must be in the interval `[0, inf)`. + + Usage Example: + + >>> x = [[[1.0, 2.0, 3.0], + ... [4.0, 5.0, 6.0]], + ... [[7.0, 8.0, 9.0], + ... [10.0, 11.0, 12.0]]] + >>> tf.image.adjust_saturation(x, 0.5) + + + Args: + image: RGB image or images. The size of the last dimension must be 3. + saturation_factor: float. Factor to multiply the saturation by. + name: A name for this operation (optional). + + Returns: + Adjusted image(s), same shape and DType as `image`. + + Raises: + InvalidArgumentError: input must have 3 channels + """ + with ops.name_scope(name, 'adjust_saturation', [image]) as name: + image = ops.convert_to_tensor(image, name='image') + # Remember original dtype to so we can convert back if needed + orig_dtype = image.dtype + if orig_dtype in (dtypes.float16, dtypes.float32): + flt_image = image + else: + flt_image = convert_image_dtype(image, dtypes.float32) + + adjusted = gen_image_ops.adjust_saturation(flt_image, saturation_factor) + + return convert_image_dtype(adjusted, orig_dtype) + + +@tf_export('io.is_jpeg', 'image.is_jpeg', v1=['io.is_jpeg', 'image.is_jpeg']) +def is_jpeg(contents, name=None): + r"""Convenience function to check if the 'contents' encodes a JPEG image. + + Args: + contents: 0-D `string`. The encoded image bytes. + name: A name for the operation (optional) + + Returns: + A scalar boolean tensor indicating if 'contents' may be a JPEG image. + is_jpeg is susceptible to false positives. + """ + # Normal JPEGs start with \xff\xd8\xff\xe0 + # JPEG with EXIF starts with \xff\xd8\xff\xe1 + # Use \xff\xd8\xff to cover both. + with ops.name_scope(name, 'is_jpeg'): + substr = string_ops.substr(contents, 0, 3) + return math_ops.equal(substr, b'\xff\xd8\xff', name=name) + + +def _is_png(contents, name=None): + r"""Convenience function to check if the 'contents' encodes a PNG image. + + Args: + contents: 0-D `string`. The encoded image bytes. + name: A name for the operation (optional) + + Returns: + A scalar boolean tensor indicating if 'contents' may be a PNG image. + is_png is susceptible to false positives. + """ + with ops.name_scope(name, 'is_png'): + substr = string_ops.substr(contents, 0, 3) + return math_ops.equal(substr, b'\211PN', name=name) + + +decode_and_crop_jpeg = tf_export( + 'io.decode_and_crop_jpeg', + 'image.decode_and_crop_jpeg', + v1=['io.decode_and_crop_jpeg', 'image.decode_and_crop_jpeg'])( + dispatch.add_dispatch_support(gen_image_ops.decode_and_crop_jpeg)) + +decode_bmp = tf_export( + 'io.decode_bmp', + 'image.decode_bmp', + v1=['io.decode_bmp', 'image.decode_bmp'])( + dispatch.add_dispatch_support(gen_image_ops.decode_bmp)) +decode_gif = tf_export( + 'io.decode_gif', + 'image.decode_gif', + v1=['io.decode_gif', 'image.decode_gif'])( + dispatch.add_dispatch_support(gen_image_ops.decode_gif)) +decode_jpeg = tf_export( + 'io.decode_jpeg', + 'image.decode_jpeg', + v1=['io.decode_jpeg', 'image.decode_jpeg'])( + dispatch.add_dispatch_support(gen_image_ops.decode_jpeg)) +decode_png = tf_export( + 'io.decode_png', + 'image.decode_png', + v1=['io.decode_png', 'image.decode_png'])( + dispatch.add_dispatch_support(gen_image_ops.decode_png)) + +encode_jpeg = tf_export( + 'io.encode_jpeg', + 'image.encode_jpeg', + v1=['io.encode_jpeg', 'image.encode_jpeg'])( + dispatch.add_dispatch_support(gen_image_ops.encode_jpeg)) +extract_jpeg_shape = tf_export( + 'io.extract_jpeg_shape', + 'image.extract_jpeg_shape', + v1=['io.extract_jpeg_shape', 'image.extract_jpeg_shape'])( + dispatch.add_dispatch_support(gen_image_ops.extract_jpeg_shape)) + + +@tf_export('io.encode_png', 'image.encode_png') +@dispatch.add_dispatch_support +def encode_png(image, compression=-1, name=None): + r"""PNG-encode an image. + + `image` is a rank-N Tensor of type uint8 or uint16 with shape `batch_dims + + [height, width, channels]`, where `channels` is: + + * 1: for grayscale. + * 2: for grayscale + alpha. + * 3: for RGB. + * 4: for RGBA. + + The ZLIB compression level, `compression`, can be -1 for the PNG-encoder + default or a value from 0 to 9. 9 is the highest compression level, + generating the smallest output, but is slower. + + Args: + image: A `Tensor`. Must be one of the following types: `uint8`, `uint16`. + Rank N >= 3 with shape `batch_dims + [height, width, channels]`. + compression: An optional `int`. Defaults to `-1`. Compression level. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + return gen_image_ops.encode_png( + ops.convert_to_tensor(image), compression, name) + + +@tf_export( + 'io.decode_image', + 'image.decode_image', + v1=['io.decode_image', 'image.decode_image']) +@dispatch.add_dispatch_support +def decode_image(contents, + channels=None, + dtype=dtypes.uint8, + name=None, + expand_animations=True): + """Function for `decode_bmp`, `decode_gif`, `decode_jpeg`, and `decode_png`. + + Detects whether an image is a BMP, GIF, JPEG, or PNG, and performs the + appropriate operation to convert the input bytes `string` into a `Tensor` + of type `dtype`. + + Note: `decode_gif` returns a 4-D array `[num_frames, height, width, 3]`, as + opposed to `decode_bmp`, `decode_jpeg` and `decode_png`, which return 3-D + arrays `[height, width, num_channels]`. Make sure to take this into account + when constructing your graph if you are intermixing GIF files with BMP, JPEG, + and/or PNG files. Alternately, set the `expand_animations` argument of this + function to `False`, in which case the op will return 3-dimensional tensors + and will truncate animated GIF files to the first frame. + + NOTE: If the first frame of an animated GIF does not occupy the entire + canvas (maximum frame width x maximum frame height), then it fills the + unoccupied areas (in the first frame) with zeros (black). For frames after the + first frame that does not occupy the entire canvas, it uses the previous + frame to fill the unoccupied areas. + + Args: + contents: A `Tensor` of type `string`. 0-D. The encoded image bytes. + channels: An optional `int`. Defaults to `0`. Number of color channels for + the decoded image. + dtype: The desired DType of the returned `Tensor`. + name: A name for the operation (optional) + expand_animations: An optional `bool`. Defaults to `True`. Controls the + shape of the returned op's output. If `True`, the returned op will produce + a 3-D tensor for PNG, JPEG, and BMP files; and a 4-D tensor for all GIFs, + whether animated or not. If, `False`, the returned op will produce a 3-D + tensor for all file types and will truncate animated GIFs to the first + frame. + + Returns: + `Tensor` with type `dtype` and a 3- or 4-dimensional shape, depending on + the file type and the value of the `expand_animations` parameter. + + Raises: + ValueError: On incorrect number of channels. + """ + with ops.name_scope(name, 'decode_image'): + channels = 0 if channels is None else channels + if dtype not in [dtypes.float32, dtypes.uint8, dtypes.uint16]: + dest_dtype = dtype + dtype = dtypes.uint16 + return convert_image_dtype( + gen_image_ops.decode_image( + contents=contents, + channels=channels, + expand_animations=expand_animations, + dtype=dtype), dest_dtype) + else: + return gen_image_ops.decode_image( + contents=contents, + channels=channels, + expand_animations=expand_animations, + dtype=dtype) + + +@tf_export('image.total_variation') +@dispatch.add_dispatch_support +def total_variation(images, name=None): + """Calculate and return the total variation for one or more images. + + The total variation is the sum of the absolute differences for neighboring + pixel-values in the input images. This measures how much noise is in the + images. + + This can be used as a loss-function during optimization so as to suppress + noise in images. If you have a batch of images, then you should calculate + the scalar loss-value as the sum: + `loss = tf.reduce_sum(tf.image.total_variation(images))` + + This implements the anisotropic 2-D version of the formula described here: + + https://en.wikipedia.org/wiki/Total_variation_denoising + + Args: + images: 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor + of shape `[height, width, channels]`. + name: A name for the operation (optional). + + Raises: + ValueError: if images.shape is not a 3-D or 4-D vector. + + Returns: + The total variation of `images`. + + If `images` was 4-D, return a 1-D float Tensor of shape `[batch]` with the + total variation for each image in the batch. + If `images` was 3-D, return a scalar float with the total variation for + that image. + """ + + with ops.name_scope(name, 'total_variation'): + ndims = images.get_shape().ndims + + if ndims == 3: + # The input is a single image with shape [height, width, channels]. + + # Calculate the difference of neighboring pixel-values. + # The images are shifted one pixel along the height and width by slicing. + pixel_dif1 = images[1:, :, :] - images[:-1, :, :] + pixel_dif2 = images[:, 1:, :] - images[:, :-1, :] + + # Sum for all axis. (None is an alias for all axis.) + sum_axis = None + elif ndims == 4: + # The input is a batch of images with shape: + # [batch, height, width, channels]. + + # Calculate the difference of neighboring pixel-values. + # The images are shifted one pixel along the height and width by slicing. + pixel_dif1 = images[:, 1:, :, :] - images[:, :-1, :, :] + pixel_dif2 = images[:, :, 1:, :] - images[:, :, :-1, :] + + # Only sum for the last 3 axis. + # This results in a 1-D tensor with the total variation for each image. + sum_axis = [1, 2, 3] + else: + raise ValueError('\'images\' must be either 3 or 4-dimensional.') + + # Calculate the total variation by taking the absolute value of the + # pixel-differences and summing over the appropriate axis. + tot_var = ( + math_ops.reduce_sum(math_ops.abs(pixel_dif1), axis=sum_axis) + + math_ops.reduce_sum(math_ops.abs(pixel_dif2), axis=sum_axis)) + + return tot_var + + +@tf_export('image.sample_distorted_bounding_box', v1=[]) +@dispatch.add_dispatch_support +def sample_distorted_bounding_box_v2(image_size, + bounding_boxes, + seed=0, + min_object_covered=0.1, + aspect_ratio_range=None, + area_range=None, + max_attempts=None, + use_image_if_no_bounding_boxes=None, + name=None): + """Generate a single randomly distorted bounding box for an image. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving + its content, i.e. *data augmentation*. This Op outputs a randomly distorted + localization of an object, i.e. bounding box, given an `image_size`, + `bounding_boxes` and a series of constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to + visualize what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. + The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width + and the height of the underlying image. + + For example, + + ```python + # Generate a single distorted bounding box. + begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( + tf.shape(image), + bounding_boxes=bounding_boxes, + min_object_covered=0.1) + + # Draw the bounding box in an image summary. + image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), + bbox_for_draw) + tf.compat.v1.summary.image('images_with_box', image_with_box) + + # Employ the bounding box to distort the image. + distorted_image = tf.slice(image, begin, size) + ``` + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = true` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_sample_distorted_bounding_box`. Unlike using the `seed` + param with `tf.image.random_*` ops, `tf.image.stateless_random_*` ops + guarantee the same results given the same seed independent of how many times + the function is called, and independent of global seed settings + (e.g. tf.random.set_seed). + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, + `int16`, `int32`, `int64`. 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. 3-D with shape `[batch, N, 4]` + describing the N bounding boxes associated with the image. + seed: An optional `int`. Defaults to `0`. If `seed` is set to non-zero, the + random number generator is seeded by the given `seed`. Otherwise, it is + seeded by a random seed. + min_object_covered: A Tensor of type `float32`. Defaults to `0.1`. The + cropped area of the image must contain at least this fraction of any + bounding box supplied. The value of this parameter should be non-negative. + In the case of 0, the cropped area does not need to overlap any of the + bounding boxes supplied. + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, + 1.33]`. The cropped area of the image must have an aspect `ratio = width / + height` within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. The + cropped area of the image must contain a fraction of the supplied image + within this range. + max_attempts: An optional `int`. Defaults to `100`. Number of attempts at + generating a cropped region of the image of the specified constraints. + After `max_attempts` failures, return the entire image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. If true, assume an + implicit bounding box covering the whole input. If false, raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[offset_height, offset_width, 0]`. Provide as input to + `tf.slice`. + size: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[target_height, target_width, -1]`. Provide as input to + `tf.slice`. + bboxes: A `Tensor` of type `float32`. 3-D with shape `[1, 1, 4]` containing + the distorted bounding box. + Provide as input to `tf.image.draw_bounding_boxes`. + + Raises: + ValueError: If no seed is specified and op determinism is enabled. + """ + if seed: + seed1, seed2 = random_seed.get_seed(seed) + else: + if config.is_op_determinism_enabled(): + raise ValueError( + f'tf.image.sample_distorted_bounding_box requires a non-zero seed to ' + f'be passed in when determinism is enabled, but got seed={seed}. ' + f'Please pass in a non-zero seed, e.g. by passing "seed=1".') + seed1, seed2 = (0, 0) + with ops.name_scope(name, 'sample_distorted_bounding_box'): + return gen_image_ops.sample_distorted_bounding_box_v2( + image_size, + bounding_boxes, + seed=seed1, + seed2=seed2, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + + +@tf_export('image.stateless_sample_distorted_bounding_box', v1=[]) +@dispatch.add_dispatch_support +def stateless_sample_distorted_bounding_box(image_size, + bounding_boxes, + seed, + min_object_covered=0.1, + aspect_ratio_range=None, + area_range=None, + max_attempts=None, + use_image_if_no_bounding_boxes=None, + name=None): + """Generate a randomly distorted bounding box for an image deterministically. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving + its content, i.e. *data augmentation*. This Op, given the same `seed`, + deterministically outputs a randomly distorted localization of an object, i.e. + bounding box, given an `image_size`, `bounding_boxes` and a series of + constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to + visualize what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. + The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width + and the height of the underlying image. + + The output of this Op is guaranteed to be the same given the same `seed` and + is independent of how many times the function is called, and independent of + global seed settings (e.g. `tf.random.set_seed`). + + Example usage: + + >>> image = np.array([[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]]) + >>> bbox = tf.constant( + ... [0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) + >>> seed = (1, 2) + >>> # Generate a single distorted bounding box. + >>> bbox_begin, bbox_size, bbox_draw = ( + ... tf.image.stateless_sample_distorted_bounding_box( + ... tf.shape(image), bounding_boxes=bbox, seed=seed)) + >>> # Employ the bounding box to distort the image. + >>> tf.slice(image, bbox_begin, bbox_size) + + >>> # Draw the bounding box in an image summary. + >>> colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + >>> tf.image.draw_bounding_boxes( + ... tf.expand_dims(tf.cast(image, tf.float32),0), bbox_draw, colors) + + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = true` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, + `int16`, `int32`, `int64`. 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. 3-D with shape `[batch, N, 4]` + describing the N bounding boxes associated with the image. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + min_object_covered: A Tensor of type `float32`. Defaults to `0.1`. The + cropped area of the image must contain at least this fraction of any + bounding box supplied. The value of this parameter should be non-negative. + In the case of 0, the cropped area does not need to overlap any of the + bounding boxes supplied. + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, + 1.33]`. The cropped area of the image must have an aspect `ratio = width / + height` within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. The + cropped area of the image must contain a fraction of the supplied image + within this range. + max_attempts: An optional `int`. Defaults to `100`. Number of attempts at + generating a cropped region of the image of the specified constraints. + After `max_attempts` failures, return the entire image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. If true, assume an + implicit bounding box covering the whole input. If false, raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[offset_height, offset_width, 0]`. Provide as input to + `tf.slice`. + size: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[target_height, target_width, -1]`. Provide as input to + `tf.slice`. + bboxes: A `Tensor` of type `float32`. 3-D with shape `[1, 1, 4]` containing + the distorted bounding box. + Provide as input to `tf.image.draw_bounding_boxes`. + """ + with ops.name_scope(name, 'stateless_sample_distorted_bounding_box'): + return gen_image_ops.stateless_sample_distorted_bounding_box( + image_size=image_size, + bounding_boxes=bounding_boxes, + seed=seed, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + + +@tf_export(v1=['image.sample_distorted_bounding_box']) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, + instructions='`seed2` arg is deprecated.' + 'Use sample_distorted_bounding_box_v2 instead.') +def sample_distorted_bounding_box(image_size, + bounding_boxes, + seed=None, + seed2=None, + min_object_covered=0.1, + aspect_ratio_range=None, + area_range=None, + max_attempts=None, + use_image_if_no_bounding_boxes=None, + name=None): + """Generate a single randomly distorted bounding box for an image. + + Bounding box annotations are often supplied in addition to ground-truth labels + in image recognition or object localization tasks. A common technique for + training such a system is to randomly distort an image while preserving + its content, i.e. *data augmentation*. This Op outputs a randomly distorted + localization of an object, i.e. bounding box, given an `image_size`, + `bounding_boxes` and a series of constraints. + + The output of this Op is a single bounding box that may be used to crop the + original image. The output is returned as 3 tensors: `begin`, `size` and + `bboxes`. The first 2 tensors can be fed directly into `tf.slice` to crop the + image. The latter may be supplied to `tf.image.draw_bounding_boxes` to + visualize what the bounding box looks like. + + Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. + The + bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and + height of the underlying image. + + For example, + + ```python + # Generate a single distorted bounding box. + begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box( + tf.shape(image), + bounding_boxes=bounding_boxes, + min_object_covered=0.1) + + # Draw the bounding box in an image summary. + image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0), + bbox_for_draw) + tf.compat.v1.summary.image('images_with_box', image_with_box) + + # Employ the bounding box to distort the image. + distorted_image = tf.slice(image, begin, size) + ``` + + Note that if no bounding box information is available, setting + `use_image_if_no_bounding_boxes = True` will assume there is a single implicit + bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is + false and no bounding boxes are supplied, an error is raised. + + Args: + image_size: A `Tensor`. Must be one of the following types: `uint8`, `int8`, + `int16`, `int32`, `int64`. 1-D, containing `[height, width, channels]`. + bounding_boxes: A `Tensor` of type `float32`. 3-D with shape `[batch, N, 4]` + describing the N bounding boxes associated with the image. + seed: An optional `int`. Defaults to `0`. If either `seed` or `seed2` are + set to non-zero, the random number generator is seeded by the given + `seed`. Otherwise, it is seeded by a random seed. + seed2: An optional `int`. Defaults to `0`. A second seed to avoid seed + collision. + min_object_covered: A Tensor of type `float32`. Defaults to `0.1`. The + cropped area of the image must contain at least this fraction of any + bounding box supplied. The value of this parameter should be non-negative. + In the case of 0, the cropped area does not need to overlap any of the + bounding boxes supplied. + aspect_ratio_range: An optional list of `floats`. Defaults to `[0.75, + 1.33]`. The cropped area of the image must have an aspect ratio = width / + height within this range. + area_range: An optional list of `floats`. Defaults to `[0.05, 1]`. The + cropped area of the image must contain a fraction of the supplied image + within this range. + max_attempts: An optional `int`. Defaults to `100`. Number of attempts at + generating a cropped region of the image of the specified constraints. + After `max_attempts` failures, return the entire image. + use_image_if_no_bounding_boxes: An optional `bool`. Defaults to `False`. + Controls behavior if no bounding boxes supplied. If true, assume an + implicit bounding box covering the whole input. If false, raise an error. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (begin, size, bboxes). + + begin: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[offset_height, offset_width, 0]`. Provide as input to + `tf.slice`. + size: A `Tensor`. Has the same type as `image_size`. 1-D, containing + `[target_height, target_width, -1]`. Provide as input to + `tf.slice`. + bboxes: A `Tensor` of type `float32`. 3-D with shape `[1, 1, 4]` containing + the distorted bounding box. + Provide as input to `tf.image.draw_bounding_boxes`. + + Raises: + ValueError: If no seed is specified and op determinism is enabled. + """ + if not seed and not seed2 and config.is_op_determinism_enabled(): + raise ValueError( + f'tf.compat.v1.image.sample_distorted_bounding_box requires "seed" or ' + f'"seed2" to be non-zero when determinism is enabled. Please pass in ' + f'a non-zero seed, e.g. by passing "seed=1". Got seed={seed} and ' + f"seed2={seed2}") + with ops.name_scope(name, 'sample_distorted_bounding_box'): + return gen_image_ops.sample_distorted_bounding_box_v2( + image_size, + bounding_boxes, + seed=seed, + seed2=seed2, + min_object_covered=min_object_covered, + aspect_ratio_range=aspect_ratio_range, + area_range=area_range, + max_attempts=max_attempts, + use_image_if_no_bounding_boxes=use_image_if_no_bounding_boxes, + name=name) + + +@tf_export('image.non_max_suppression') +@dispatch.add_dispatch_support +def non_max_suppression(boxes, + scores, + max_output_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + name=None): + """Greedily selects a subset of bounding boxes in descending order of score. + + Prunes away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval `[0, 1]`) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Note that this + algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather` operation. For example: + ```python + selected_indices = tf.image.non_max_suppression( + boxes, scores, max_output_size, iou_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + ``` + + Args: + boxes: A 2-D float `Tensor` of shape `[num_boxes, 4]`. + scores: A 1-D float `Tensor` of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A scalar integer `Tensor` representing the maximum number + of boxes to be selected by non-max suppression. + iou_threshold: A 0-D float tensor representing the threshold for deciding + whether boxes overlap too much with respect to IOU. + score_threshold: A 0-D float tensor representing the threshold for deciding + when to remove boxes based on score. + name: A name for the operation (optional). + + Returns: + selected_indices: A 1-D integer `Tensor` of shape `[M]` representing the + selected indices from the boxes tensor, where `M <= max_output_size`. + """ + with ops.name_scope(name, 'non_max_suppression'): + iou_threshold = ops.convert_to_tensor(iou_threshold, name='iou_threshold') + score_threshold = ops.convert_to_tensor( + score_threshold, name='score_threshold') + return gen_image_ops.non_max_suppression_v3(boxes, scores, max_output_size, + iou_threshold, score_threshold) + + +@tf_export('image.non_max_suppression_with_scores') +@dispatch.add_dispatch_support +def non_max_suppression_with_scores(boxes, + scores, + max_output_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + soft_nms_sigma=0.0, + name=None): + """Greedily selects a subset of bounding boxes in descending order of score. + + Prunes away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval `[0, 1]`) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Note that this + algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather` operation. For example: + ```python + selected_indices, selected_scores = tf.image.non_max_suppression_padded( + boxes, scores, max_output_size, iou_threshold=1.0, score_threshold=0.1, + soft_nms_sigma=0.5) + selected_boxes = tf.gather(boxes, selected_indices) + ``` + + This function generalizes the `tf.image.non_max_suppression` op by also + supporting a Soft-NMS (with Gaussian weighting) mode (c.f. + Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score + of other overlapping boxes instead of directly causing them to be pruned. + Consequently, in contrast to `tf.image.non_max_suppression`, + `tf.image.non_max_suppression_with_scores` returns the new scores of each + input box in the second output, `selected_scores`. + + To enable this Soft-NMS mode, set the `soft_nms_sigma` parameter to be + larger than 0. When `soft_nms_sigma` equals 0, the behavior of + `tf.image.non_max_suppression_with_scores` is identical to that of + `tf.image.non_max_suppression` (except for the extra output) both in function + and in running time. + + Note that when `soft_nms_sigma` > 0, Soft-NMS is performed and `iou_threshold` + is ignored. `iou_threshold` is only used for standard NMS. + + Args: + boxes: A 2-D float `Tensor` of shape `[num_boxes, 4]`. + scores: A 1-D float `Tensor` of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A scalar integer `Tensor` representing the maximum number + of boxes to be selected by non-max suppression. + iou_threshold: A 0-D float tensor representing the threshold for deciding + whether boxes overlap too much with respect to IOU. + score_threshold: A 0-D float tensor representing the threshold for deciding + when to remove boxes based on score. + soft_nms_sigma: A 0-D float tensor representing the sigma parameter for Soft + NMS; see Bodla et al (c.f. https://arxiv.org/abs/1704.04503). When + `soft_nms_sigma=0.0` (which is default), we fall back to standard (hard) + NMS. + name: A name for the operation (optional). + + Returns: + selected_indices: A 1-D integer `Tensor` of shape `[M]` representing the + selected indices from the boxes tensor, where `M <= max_output_size`. + selected_scores: A 1-D float tensor of shape `[M]` representing the + corresponding scores for each selected box, where `M <= max_output_size`. + Scores only differ from corresponding input scores when using Soft NMS + (i.e. when `soft_nms_sigma>0`) + """ + with ops.name_scope(name, 'non_max_suppression_with_scores'): + iou_threshold = ops.convert_to_tensor(iou_threshold, name='iou_threshold') + score_threshold = ops.convert_to_tensor( + score_threshold, name='score_threshold') + soft_nms_sigma = ops.convert_to_tensor( + soft_nms_sigma, name='soft_nms_sigma') + (selected_indices, selected_scores, + _) = gen_image_ops.non_max_suppression_v5( + boxes, + scores, + max_output_size, + iou_threshold, + score_threshold, + soft_nms_sigma, + pad_to_max_output_size=False) + return selected_indices, selected_scores + + +@tf_export('image.non_max_suppression_overlaps') +@dispatch.add_dispatch_support +def non_max_suppression_with_overlaps(overlaps, + scores, + max_output_size, + overlap_threshold=0.5, + score_threshold=float('-inf'), + name=None): + """Greedily selects a subset of bounding boxes in descending order of score. + + Prunes away boxes that have high overlap with previously selected boxes. + N-by-n overlap values are supplied as square matrix. + The output of this operation is a set of integers indexing into the input + collection of bounding boxes representing the selected boxes. The bounding + box coordinates corresponding to the selected indices can then be obtained + using the `tf.gather` operation. For example: + ```python + selected_indices = tf.image.non_max_suppression_overlaps( + overlaps, scores, max_output_size, iou_threshold) + selected_boxes = tf.gather(boxes, selected_indices) + ``` + + Args: + overlaps: A 2-D float `Tensor` of shape `[num_boxes, num_boxes]` + representing the n-by-n box overlap values. + scores: A 1-D float `Tensor` of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A scalar integer `Tensor` representing the maximum number + of boxes to be selected by non-max suppression. + overlap_threshold: A 0-D float tensor representing the threshold for + deciding whether boxes overlap too much with respect to the provided + overlap values. + score_threshold: A 0-D float tensor representing the threshold for deciding + when to remove boxes based on score. + name: A name for the operation (optional). + + Returns: + selected_indices: A 1-D integer `Tensor` of shape `[M]` representing the + selected indices from the overlaps tensor, where `M <= max_output_size`. + """ + with ops.name_scope(name, 'non_max_suppression_overlaps'): + overlap_threshold = ops.convert_to_tensor( + overlap_threshold, name='overlap_threshold') + # pylint: disable=protected-access + return gen_image_ops.non_max_suppression_with_overlaps( + overlaps, scores, max_output_size, overlap_threshold, score_threshold) + # pylint: enable=protected-access + + +_rgb_to_yiq_kernel = [[0.299, 0.59590059, 0.2115], + [0.587, -0.27455667, -0.52273617], + [0.114, -0.32134392, 0.31119955]] + + +@tf_export('image.rgb_to_yiq') +@dispatch.add_dispatch_support +def rgb_to_yiq(images): + """Converts one or more images from RGB to YIQ. + + Outputs a tensor of the same shape as the `images` tensor, containing the YIQ + value of the pixels. + The output is only well defined if the value in images are in [0,1]. + + Usage Example: + + >>> x = tf.constant([[[1.0, 2.0, 3.0]]]) + >>> tf.image.rgb_to_yiq(x) + + + Args: + images: 2-D or higher rank. Image data to convert. Last dimension must be + size 3. + + Returns: + images: tensor with the same shape as `images`. + """ + images = ops.convert_to_tensor(images, name='images') + kernel = ops.convert_to_tensor( + _rgb_to_yiq_kernel, dtype=images.dtype, name='kernel') + ndims = images.get_shape().ndims + return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]]) + + +_yiq_to_rgb_kernel = [[1, 1, 1], [0.95598634, -0.27201283, -1.10674021], + [0.6208248, -0.64720424, 1.70423049]] + + +@tf_export('image.yiq_to_rgb') +@dispatch.add_dispatch_support +def yiq_to_rgb(images): + """Converts one or more images from YIQ to RGB. + + Outputs a tensor of the same shape as the `images` tensor, containing the RGB + value of the pixels. + The output is only well defined if the Y value in images are in [0,1], + I value are in [-0.5957,0.5957] and Q value are in [-0.5226,0.5226]. + + Args: + images: 2-D or higher rank. Image data to convert. Last dimension must be + size 3. + + Returns: + images: tensor with the same shape as `images`. + """ + images = ops.convert_to_tensor(images, name='images') + kernel = ops.convert_to_tensor( + _yiq_to_rgb_kernel, dtype=images.dtype, name='kernel') + ndims = images.get_shape().ndims + return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]]) + + +_rgb_to_yuv_kernel = [[0.299, -0.14714119, 0.61497538], + [0.587, -0.28886916, -0.51496512], + [0.114, 0.43601035, -0.10001026]] + + +@tf_export('image.rgb_to_yuv') +@dispatch.add_dispatch_support +def rgb_to_yuv(images): + """Converts one or more images from RGB to YUV. + + Outputs a tensor of the same shape as the `images` tensor, containing the YUV + value of the pixels. + The output is only well defined if the value in images are in [0, 1]. + There are two ways of representing an image: [0, 255] pixel values range or + [0, 1] (as float) pixel values range. Users need to convert the input image + into a float [0, 1] range. + + Args: + images: 2-D or higher rank. Image data to convert. Last dimension must be + size 3. + + Returns: + images: tensor with the same shape as `images`. + """ + images = ops.convert_to_tensor(images, name='images') + kernel = ops.convert_to_tensor( + _rgb_to_yuv_kernel, dtype=images.dtype, name='kernel') + ndims = images.get_shape().ndims + return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]]) + + +_yuv_to_rgb_kernel = [[1, 1, 1], [0, -0.394642334, 2.03206185], + [1.13988303, -0.58062185, 0]] + + +@tf_export('image.yuv_to_rgb') +@dispatch.add_dispatch_support +def yuv_to_rgb(images): + """Converts one or more images from YUV to RGB. + + Outputs a tensor of the same shape as the `images` tensor, containing the RGB + value of the pixels. + The output is only well defined if the Y value in images are in [0,1], + U and V value are in [-0.5,0.5]. + + As per the above description, you need to scale your YUV images if their + pixel values are not in the required range. Below given example illustrates + preprocessing of each channel of images before feeding them to `yuv_to_rgb`. + + ```python + yuv_images = tf.random.uniform(shape=[100, 64, 64, 3], maxval=255) + last_dimension_axis = len(yuv_images.shape) - 1 + yuv_tensor_images = tf.truediv( + tf.subtract( + yuv_images, + tf.reduce_min(yuv_images) + ), + tf.subtract( + tf.reduce_max(yuv_images), + tf.reduce_min(yuv_images) + ) + ) + y, u, v = tf.split(yuv_tensor_images, 3, axis=last_dimension_axis) + target_uv_min, target_uv_max = -0.5, 0.5 + u = u * (target_uv_max - target_uv_min) + target_uv_min + v = v * (target_uv_max - target_uv_min) + target_uv_min + preprocessed_yuv_images = tf.concat([y, u, v], axis=last_dimension_axis) + rgb_tensor_images = tf.image.yuv_to_rgb(preprocessed_yuv_images) + ``` + + Args: + images: 2-D or higher rank. Image data to convert. Last dimension must be + size 3. + + Returns: + images: tensor with the same shape as `images`. + """ + images = ops.convert_to_tensor(images, name='images') + kernel = ops.convert_to_tensor( + _yuv_to_rgb_kernel, dtype=images.dtype, name='kernel') + ndims = images.get_shape().ndims + return math_ops.tensordot(images, kernel, axes=[[ndims - 1], [0]]) + + +def _verify_compatible_image_shapes(img1, img2): + """Checks if two image tensors are compatible for applying SSIM or PSNR. + + This function checks if two sets of images have ranks at least 3, and if the + last three dimensions match. + + Args: + img1: Tensor containing the first image batch. + img2: Tensor containing the second image batch. + + Returns: + A tuple containing: the first tensor shape, the second tensor shape, and a + list of control_flow_ops.Assert() ops implementing the checks. + + Raises: + ValueError: When static shape check fails. + """ + shape1 = img1.get_shape().with_rank_at_least(3) + shape2 = img2.get_shape().with_rank_at_least(3) + shape1[-3:].assert_is_compatible_with(shape2[-3:]) + + if shape1.ndims is not None and shape2.ndims is not None: + for dim1, dim2 in zip( + reversed(shape1.dims[:-3]), reversed(shape2.dims[:-3])): + if not (dim1 == 1 or dim2 == 1 or dim1.is_compatible_with(dim2)): + raise ValueError('Two images are not compatible: %s and %s' % + (shape1, shape2)) + + # Now assign shape tensors. + shape1, shape2 = array_ops.shape_n([img1, img2]) + + # TODO(sjhwang): Check if shape1[:-3] and shape2[:-3] are broadcastable. + checks = [] + checks.append( + control_flow_assert.Assert( + math_ops.greater_equal(array_ops.size(shape1), 3), [shape1, shape2], + summarize=10)) + checks.append( + control_flow_assert.Assert( + math_ops.reduce_all(math_ops.equal(shape1[-3:], shape2[-3:])), + [shape1, shape2], + summarize=10)) + return shape1, shape2, checks + + +@tf_export('image.psnr') +@dispatch.add_dispatch_support +def psnr(a, b, max_val, name=None): + """Returns the Peak Signal-to-Noise Ratio between a and b. + + This is intended to be used on signals (or images). Produces a PSNR value for + each image in batch. + + The last three dimensions of input are expected to be [height, width, depth]. + + Example: + + ```python + # Read images from file. + im1 = tf.decode_png('path/to/im1.png') + im2 = tf.decode_png('path/to/im2.png') + # Compute PSNR over tf.uint8 Tensors. + psnr1 = tf.image.psnr(im1, im2, max_val=255) + + # Compute PSNR over tf.float32 Tensors. + im1 = tf.image.convert_image_dtype(im1, tf.float32) + im2 = tf.image.convert_image_dtype(im2, tf.float32) + psnr2 = tf.image.psnr(im1, im2, max_val=1.0) + # psnr1 and psnr2 both have type tf.float32 and are almost equal. + ``` + + Args: + a: First set of images. + b: Second set of images. + max_val: The dynamic range of the images (i.e., the difference between the + maximum the and minimum allowed values). + name: Namespace to embed the computation in. + + Returns: + The scalar PSNR between a and b. The returned tensor has type `tf.float32` + and shape [batch_size, 1]. + """ + with ops.name_scope(name, 'PSNR', [a, b]): + # Need to convert the images to float32. Scale max_val accordingly so that + # PSNR is computed correctly. + max_val = math_ops.cast(max_val, a.dtype) + max_val = convert_image_dtype(max_val, dtypes.float32) + a = convert_image_dtype(a, dtypes.float32) + b = convert_image_dtype(b, dtypes.float32) + mse = math_ops.reduce_mean(math_ops.squared_difference(a, b), [-3, -2, -1]) + psnr_val = math_ops.subtract( + 20 * math_ops.log(max_val) / math_ops.log(10.0), + np.float32(10 / np.log(10)) * math_ops.log(mse), + name='psnr') + + _, _, checks = _verify_compatible_image_shapes(a, b) + with ops.control_dependencies(checks): + return array_ops.identity(psnr_val) + + +def _ssim_helper(x, y, reducer, max_val, compensation=1.0, k1=0.01, k2=0.03): + r"""Helper function for computing SSIM. + + SSIM estimates covariances with weighted sums. The default parameters + use a biased estimate of the covariance: + Suppose `reducer` is a weighted sum, then the mean estimators are + \mu_x = \sum_i w_i x_i, + \mu_y = \sum_i w_i y_i, + where w_i's are the weighted-sum weights, and covariance estimator is + cov_{xy} = \sum_i w_i (x_i - \mu_x) (y_i - \mu_y) + with assumption \sum_i w_i = 1. This covariance estimator is biased, since + E[cov_{xy}] = (1 - \sum_i w_i ^ 2) Cov(X, Y). + For SSIM measure with unbiased covariance estimators, pass as `compensation` + argument (1 - \sum_i w_i ^ 2). + + Args: + x: First set of images. + y: Second set of images. + reducer: Function that computes 'local' averages from the set of images. For + non-convolutional version, this is usually tf.reduce_mean(x, [1, 2]), and + for convolutional version, this is usually tf.nn.avg_pool2d or + tf.nn.conv2d with weighted-sum kernel. + max_val: The dynamic range (i.e., the difference between the maximum + possible allowed value and the minimum allowed value). + compensation: Compensation factor. See above. + k1: Default value 0.01 + k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so + it would be better if we took the values in the range of 0 < K2 < 0.4). + + Returns: + A pair containing the luminance measure, and the contrast-structure measure. + """ + + c1 = (k1 * max_val)**2 + c2 = (k2 * max_val)**2 + + # SSIM luminance measure is + # (2 * mu_x * mu_y + c1) / (mu_x ** 2 + mu_y ** 2 + c1). + mean0 = reducer(x) + mean1 = reducer(y) + num0 = mean0 * mean1 * 2.0 + den0 = math_ops.square(mean0) + math_ops.square(mean1) + luminance = (num0 + c1) / (den0 + c1) + + # SSIM contrast-structure measure is + # (2 * cov_{xy} + c2) / (cov_{xx} + cov_{yy} + c2). + # Note that `reducer` is a weighted sum with weight w_k, \sum_i w_i = 1, then + # cov_{xy} = \sum_i w_i (x_i - \mu_x) (y_i - \mu_y) + # = \sum_i w_i x_i y_i - (\sum_i w_i x_i) (\sum_j w_j y_j). + num1 = reducer(x * y) * 2.0 + den1 = reducer(math_ops.square(x) + math_ops.square(y)) + c2 *= compensation + cs = (num1 - num0 + c2) / (den1 - den0 + c2) + + # SSIM score is the product of the luminance and contrast-structure measures. + return luminance, cs + + +def _fspecial_gauss(size, sigma): + """Function to mimic the 'fspecial' gaussian MATLAB function.""" + size = ops.convert_to_tensor(size, dtypes.int32) + sigma = ops.convert_to_tensor(sigma) + + coords = math_ops.cast(math_ops.range(size), sigma.dtype) + coords -= math_ops.cast(size - 1, sigma.dtype) / 2.0 + + g = math_ops.square(coords) + g *= -0.5 / math_ops.square(sigma) + + g = array_ops.reshape(g, shape=[1, -1]) + array_ops.reshape(g, shape=[-1, 1]) + g = array_ops.reshape(g, shape=[1, -1]) # For tf.nn.softmax(). + g = nn_ops.softmax(g) + return array_ops.reshape(g, shape=[size, size, 1, 1]) + + +def _ssim_per_channel(img1, + img2, + max_val=1.0, + filter_size=11, + filter_sigma=1.5, + k1=0.01, + k2=0.03, + return_index_map=False): + """Computes SSIM index between img1 and img2 per color channel. + + This function matches the standard SSIM implementation from: + Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image + quality assessment: from error visibility to structural similarity. IEEE + transactions on image processing. + + Details: + - 11x11 Gaussian filter of width 1.5 is used. + - k1 = 0.01, k2 = 0.03 as in the original paper. + + Args: + img1: First image batch. + img2: Second image batch. + max_val: The dynamic range of the images (i.e., the difference between the + maximum the and minimum allowed values). + filter_size: Default value 11 (size of gaussian filter). + filter_sigma: Default value 1.5 (width of gaussian filter). + k1: Default value 0.01 + k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so + it would be better if we took the values in the range of 0 < K2 < 0.4). + return_index_map: If True returns local SSIM map instead of the global mean. + + Returns: + A pair of tensors containing and channel-wise SSIM and contrast-structure + values. The shape is [..., channels]. + """ + filter_size = constant_op.constant(filter_size, dtype=dtypes.int32) + filter_sigma = constant_op.constant(filter_sigma, dtype=img1.dtype) + + shape1, shape2 = array_ops.shape_n([img1, img2]) + checks = [ + control_flow_assert.Assert( + math_ops.reduce_all( + math_ops.greater_equal(shape1[-3:-1], filter_size)), + [shape1, filter_size], + summarize=8), + control_flow_assert.Assert( + math_ops.reduce_all( + math_ops.greater_equal(shape2[-3:-1], filter_size)), + [shape2, filter_size], + summarize=8) + ] + + # Enforce the check to run before computation. + with ops.control_dependencies(checks): + img1 = array_ops.identity(img1) + + # TODO(sjhwang): Try to cache kernels and compensation factor. + kernel = _fspecial_gauss(filter_size, filter_sigma) + kernel = array_ops.tile(kernel, multiples=[1, 1, shape1[-1], 1]) + + # The correct compensation factor is `1.0 - tf.reduce_sum(tf.square(kernel))`, + # but to match MATLAB implementation of MS-SSIM, we use 1.0 instead. + compensation = 1.0 + + # TODO(sjhwang): Try FFT. + # TODO(sjhwang): Gaussian kernel is separable in space. Consider applying + # 1-by-n and n-by-1 Gaussian filters instead of an n-by-n filter. + def reducer(x): + shape = array_ops.shape(x) + x = array_ops.reshape(x, shape=array_ops.concat([[-1], shape[-3:]], 0)) + y = nn_impl.depthwise_conv2d( + x, kernel, strides=[1, 1, 1, 1], padding='VALID') + return array_ops.reshape( + y, array_ops.concat([shape[:-3], array_ops.shape(y)[1:]], 0)) + + luminance, cs = _ssim_helper(img1, img2, reducer, max_val, compensation, k1, + k2) + + # Average over the second and the third from the last: height, width. + if return_index_map: + ssim_val = luminance * cs + else: + axes = constant_op.constant([-3, -2], dtype=dtypes.int32) + ssim_val = math_ops.reduce_mean(luminance * cs, axes) + cs = math_ops.reduce_mean(cs, axes) + return ssim_val, cs + + +@tf_export('image.ssim') +@dispatch.add_dispatch_support +def ssim(img1, + img2, + max_val, + filter_size=11, + filter_sigma=1.5, + k1=0.01, + k2=0.03, + return_index_map=False): + """Computes SSIM index between img1 and img2. + + This function is based on the standard SSIM implementation from: + Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image + quality assessment: from error visibility to structural similarity. IEEE + transactions on image processing. + + Note: The true SSIM is only defined on grayscale. This function does not + perform any colorspace transform. (If the input is already YUV, then it will + compute YUV SSIM average.) + + Details: + - 11x11 Gaussian filter of width 1.5 is used. + - k1 = 0.01, k2 = 0.03 as in the original paper. + + The image sizes must be at least 11x11 because of the filter size. + + Example: + + ```python + # Read images (of size 255 x 255) from file. + im1 = tf.image.decode_image(tf.io.read_file('path/to/im1.png')) + im2 = tf.image.decode_image(tf.io.read_file('path/to/im2.png')) + tf.shape(im1) # `img1.png` has 3 channels; shape is `(255, 255, 3)` + tf.shape(im2) # `img2.png` has 3 channels; shape is `(255, 255, 3)` + # Add an outer batch for each image. + im1 = tf.expand_dims(im1, axis=0) + im2 = tf.expand_dims(im2, axis=0) + # Compute SSIM over tf.uint8 Tensors. + ssim1 = tf.image.ssim(im1, im2, max_val=255, filter_size=11, + filter_sigma=1.5, k1=0.01, k2=0.03) + + # Compute SSIM over tf.float32 Tensors. + im1 = tf.image.convert_image_dtype(im1, tf.float32) + im2 = tf.image.convert_image_dtype(im2, tf.float32) + ssim2 = tf.image.ssim(im1, im2, max_val=1.0, filter_size=11, + filter_sigma=1.5, k1=0.01, k2=0.03) + # ssim1 and ssim2 both have type tf.float32 and are almost equal. + ``` + + Args: + img1: First image batch. 4-D Tensor of shape `[batch, height, width, + channels]` with only Positive Pixel Values. + img2: Second image batch. 4-D Tensor of shape `[batch, height, width, + channels]` with only Positive Pixel Values. + max_val: The dynamic range of the images (i.e., the difference between the + maximum the and minimum allowed values). + filter_size: Default value 11 (size of gaussian filter). + filter_sigma: Default value 1.5 (width of gaussian filter). + k1: Default value 0.01 + k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so + it would be better if we took the values in the range of 0 < K2 < 0.4). + return_index_map: If True returns local SSIM map instead of the global mean. + + Returns: + A tensor containing an SSIM value for each image in batch or a tensor + containing an SSIM value for each pixel for each image in batch if + return_index_map is True. Returned SSIM values are in range (-1, 1], when + pixel values are non-negative. Returns a tensor with shape: + broadcast(img1.shape[:-3], img2.shape[:-3]) or broadcast(img1.shape[:-1], + img2.shape[:-1]). + """ + with ops.name_scope(None, 'SSIM', [img1, img2]): + # Convert to tensor if needed. + img1 = ops.convert_to_tensor(img1, name='img1') + img2 = ops.convert_to_tensor(img2, name='img2') + # Shape checking. + _, _, checks = _verify_compatible_image_shapes(img1, img2) + with ops.control_dependencies(checks): + img1 = array_ops.identity(img1) + + # Need to convert the images to float32. Scale max_val accordingly so that + # SSIM is computed correctly. + max_val = math_ops.cast(max_val, img1.dtype) + max_val = convert_image_dtype(max_val, dtypes.float32) + img1 = convert_image_dtype(img1, dtypes.float32) + img2 = convert_image_dtype(img2, dtypes.float32) + ssim_per_channel, _ = _ssim_per_channel(img1, img2, max_val, filter_size, + filter_sigma, k1, k2, + return_index_map) + # Compute average over color channels. + return math_ops.reduce_mean(ssim_per_channel, [-1]) + + +# Default values obtained by Wang et al. +_MSSSIM_WEIGHTS = (0.0448, 0.2856, 0.3001, 0.2363, 0.1333) + + +@tf_export('image.ssim_multiscale') +@dispatch.add_dispatch_support +def ssim_multiscale(img1, + img2, + max_val, + power_factors=_MSSSIM_WEIGHTS, + filter_size=11, + filter_sigma=1.5, + k1=0.01, + k2=0.03): + """Computes the MS-SSIM between img1 and img2. + + This function assumes that `img1` and `img2` are image batches, i.e. the last + three dimensions are [height, width, channels]. + + Note: The true SSIM is only defined on grayscale. This function does not + perform any colorspace transform. (If the input is already YUV, then it will + compute YUV SSIM average.) + + Original paper: Wang, Zhou, Eero P. Simoncelli, and Alan C. Bovik. "Multiscale + structural similarity for image quality assessment." Signals, Systems and + Computers, 2004. + + Args: + img1: First image batch with only Positive Pixel Values. + img2: Second image batch with only Positive Pixel Values. Must have the + same rank as img1. + max_val: The dynamic range of the images (i.e., the difference between the + maximum the and minimum allowed values). + power_factors: Iterable of weights for each of the scales. The number of + scales used is the length of the list. Index 0 is the unscaled + resolution's weight and each increasing scale corresponds to the image + being downsampled by 2. Defaults to (0.0448, 0.2856, 0.3001, 0.2363, + 0.1333), which are the values obtained in the original paper. + filter_size: Default value 11 (size of gaussian filter). + filter_sigma: Default value 1.5 (width of gaussian filter). + k1: Default value 0.01 + k2: Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so + it would be better if we took the values in the range of 0 < K2 < 0.4). + + Returns: + A tensor containing an MS-SSIM value for each image in batch. The values + are in range [0, 1]. Returns a tensor with shape: + broadcast(img1.shape[:-3], img2.shape[:-3]). + """ + with ops.name_scope(None, 'MS-SSIM', [img1, img2]): + # Convert to tensor if needed. + img1 = ops.convert_to_tensor(img1, name='img1') + img2 = ops.convert_to_tensor(img2, name='img2') + # Shape checking. + shape1, shape2, checks = _verify_compatible_image_shapes(img1, img2) + with ops.control_dependencies(checks): + img1 = array_ops.identity(img1) + + # Need to convert the images to float32. Scale max_val accordingly so that + # SSIM is computed correctly. + max_val = math_ops.cast(max_val, img1.dtype) + max_val = convert_image_dtype(max_val, dtypes.float32) + img1 = convert_image_dtype(img1, dtypes.float32) + img2 = convert_image_dtype(img2, dtypes.float32) + + imgs = [img1, img2] + shapes = [shape1, shape2] + + # img1 and img2 are assumed to be a (multi-dimensional) batch of + # 3-dimensional images (height, width, channels). `heads` contain the batch + # dimensions, and `tails` contain the image dimensions. + heads = [s[:-3] for s in shapes] + tails = [s[-3:] for s in shapes] + + divisor = [1, 2, 2, 1] + divisor_tensor = constant_op.constant(divisor[1:], dtype=dtypes.int32) + + def do_pad(images, remainder): + padding = array_ops.expand_dims(remainder, -1) + padding = array_ops.pad(padding, [[1, 0], [1, 0]]) + return [array_ops.pad(x, padding, mode='SYMMETRIC') for x in images] + + mcs = [] + for k in range(len(power_factors)): + with ops.name_scope(None, 'Scale%d' % k, imgs): + if k > 0: + # Avg pool takes rank 4 tensors. Flatten leading dimensions. + flat_imgs = [ + array_ops.reshape(x, array_ops.concat([[-1], t], 0)) + for x, t in zip(imgs, tails) + ] + + remainder = tails[0] % divisor_tensor + need_padding = math_ops.reduce_any(math_ops.not_equal(remainder, 0)) + # pylint: disable=cell-var-from-loop + padded = tf_cond.cond(need_padding, + lambda: do_pad(flat_imgs, remainder), + lambda: flat_imgs) + # pylint: enable=cell-var-from-loop + + downscaled = [ + nn_ops.avg_pool( + x, ksize=divisor, strides=divisor, padding='VALID') + for x in padded + ] + tails = [x[1:] for x in array_ops.shape_n(downscaled)] + imgs = [ + array_ops.reshape(x, array_ops.concat([h, t], 0)) + for x, h, t in zip(downscaled, heads, tails) + ] + + # Overwrite previous ssim value since we only need the last one. + ssim_per_channel, cs = _ssim_per_channel( + *imgs, + max_val=max_val, + filter_size=filter_size, + filter_sigma=filter_sigma, + k1=k1, + k2=k2) + mcs.append(nn_ops.relu(cs)) + + # Remove the cs score for the last scale. In the MS-SSIM calculation, + # we use the l(p) at the highest scale. l(p) * cs(p) is ssim(p). + mcs.pop() # Remove the cs score for the last scale. + mcs_and_ssim = array_ops_stack.stack( + mcs + [nn_ops.relu(ssim_per_channel)], axis=-1) + # Take weighted geometric mean across the scale axis. + ms_ssim = math_ops.reduce_prod( + math_ops.pow(mcs_and_ssim, power_factors), [-1]) + + return math_ops.reduce_mean(ms_ssim, [-1]) # Avg over color channels. + + +@tf_export('image.image_gradients') +@dispatch.add_dispatch_support +def image_gradients(image): + """Returns image gradients (dy, dx) for each color channel. + + Both output tensors have the same shape as the input: [batch_size, h, w, + d]. The gradient values are organized so that [I(x+1, y) - I(x, y)] is in + location (x, y). That means that dy will always have zeros in the last row, + and dx will always have zeros in the last column. + + Usage Example: + ```python + BATCH_SIZE = 1 + IMAGE_HEIGHT = 5 + IMAGE_WIDTH = 5 + CHANNELS = 1 + image = tf.reshape(tf.range(IMAGE_HEIGHT * IMAGE_WIDTH * CHANNELS, + delta=1, dtype=tf.float32), + shape=(BATCH_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, CHANNELS)) + dy, dx = tf.image.image_gradients(image) + print(image[0, :,:,0]) + tf.Tensor( + [[ 0. 1. 2. 3. 4.] + [ 5. 6. 7. 8. 9.] + [10. 11. 12. 13. 14.] + [15. 16. 17. 18. 19.] + [20. 21. 22. 23. 24.]], shape=(5, 5), dtype=float32) + print(dy[0, :,:,0]) + tf.Tensor( + [[5. 5. 5. 5. 5.] + [5. 5. 5. 5. 5.] + [5. 5. 5. 5. 5.] + [5. 5. 5. 5. 5.] + [0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32) + print(dx[0, :,:,0]) + tf.Tensor( + [[1. 1. 1. 1. 0.] + [1. 1. 1. 1. 0.] + [1. 1. 1. 1. 0.] + [1. 1. 1. 1. 0.] + [1. 1. 1. 1. 0.]], shape=(5, 5), dtype=float32) + ``` + + Args: + image: Tensor with shape [batch_size, h, w, d]. + + Returns: + Pair of tensors (dy, dx) holding the vertical and horizontal image + gradients (1-step finite difference). + + Raises: + ValueError: If `image` is not a 4D tensor. + """ + if image.get_shape().ndims != 4: + raise ValueError('image_gradients expects a 4D tensor ' + '[batch_size, h, w, d], not {}.'.format(image.get_shape())) + image_shape = array_ops.shape(image) + batch_size, height, width, depth = array_ops_stack.unstack(image_shape) + dy = image[:, 1:, :, :] - image[:, :-1, :, :] + dx = image[:, :, 1:, :] - image[:, :, :-1, :] + + # Return tensors with same size as original image by concatenating + # zeros. Place the gradient [I(x+1,y) - I(x,y)] on the base pixel (x, y). + shape = array_ops_stack.stack([batch_size, 1, width, depth]) + dy = array_ops.concat([dy, array_ops.zeros(shape, image.dtype)], 1) + dy = array_ops.reshape(dy, image_shape) + + shape = array_ops_stack.stack([batch_size, height, 1, depth]) + dx = array_ops.concat([dx, array_ops.zeros(shape, image.dtype)], 2) + dx = array_ops.reshape(dx, image_shape) + + return dy, dx + + +@tf_export('image.sobel_edges') +@dispatch.add_dispatch_support +def sobel_edges(image): + """Returns a tensor holding Sobel edge maps. + + Example usage: + + For general usage, `image` would be loaded from a file as below: + + ```python + image_bytes = tf.io.read_file(path_to_image_file) + image = tf.image.decode_image(image_bytes) + image = tf.cast(image, tf.float32) + image = tf.expand_dims(image, 0) + ``` + But for demo purposes, we are using randomly generated values for `image`: + + >>> image = tf.random.uniform( + ... maxval=255, shape=[1, 28, 28, 3], dtype=tf.float32) + >>> sobel = tf.image.sobel_edges(image) + >>> sobel_y = np.asarray(sobel[0, :, :, :, 0]) # sobel in y-direction + >>> sobel_x = np.asarray(sobel[0, :, :, :, 1]) # sobel in x-direction + + For displaying the sobel results, PIL's [Image Module]( + https://pillow.readthedocs.io/en/stable/reference/Image.html) can be used: + + ```python + # Display edge maps for the first channel (at index 0) + Image.fromarray(sobel_y[..., 0] / 4 + 0.5).show() + Image.fromarray(sobel_x[..., 0] / 4 + 0.5).show() + ``` + + Args: + image: Image tensor with shape [batch_size, h, w, d] and type float32 or + float64. The image(s) must be 2x2 or larger. + + Returns: + Tensor holding edge maps for each channel. Returns a tensor with shape + [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]], + [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter. + """ + # Define vertical and horizontal Sobel filters. + static_image_shape = image.get_shape() + image_shape = array_ops.shape(image) + kernels = [[[-1, -2, -1], [0, 0, 0], [1, 2, 1]], + [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]] + num_kernels = len(kernels) + kernels = np.transpose(np.asarray(kernels), (1, 2, 0)) + kernels = np.expand_dims(kernels, -2) + kernels_tf = constant_op.constant(kernels, dtype=image.dtype) + + kernels_tf = array_ops.tile( + kernels_tf, [1, 1, image_shape[-1], 1], name='sobel_filters') + + # Use depth-wise convolution to calculate edge maps per channel. + pad_sizes = [[0, 0], [1, 1], [1, 1], [0, 0]] + padded = array_ops.pad(image, pad_sizes, mode='REFLECT') + + # Output tensor has shape [batch_size, h, w, d * num_kernels]. + strides = [1, 1, 1, 1] + output = nn_impl.depthwise_conv2d(padded, kernels_tf, strides, 'VALID') + + # Reshape to [batch_size, h, w, d, num_kernels]. + shape = array_ops.concat([image_shape, [num_kernels]], 0) + output = array_ops.reshape(output, shape=shape) + output.set_shape(static_image_shape.concatenate([num_kernels])) + return output + + +@tf_export(v1=['image.resize_bicubic']) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, + instructions=( + 'Use `tf.image.resize(...method=ResizeMethod.BICUBIC...)` instead.' + ), +) +def resize_bicubic(images, + size, + align_corners=False, + name=None, + half_pixel_centers=False): + return gen_image_ops.resize_bicubic( + images=images, + size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + + +@tf_export(v1=['image.resize_bilinear']) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, + instructions=( + 'Use `tf.image.resize(...method=ResizeMethod.BILINEAR...)` instead.' + ), +) +def resize_bilinear(images, + size, + align_corners=False, + name=None, + half_pixel_centers=False): + return gen_image_ops.resize_bilinear( + images=images, + size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + + +@tf_export(v1=['image.resize_nearest_neighbor']) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, + instructions=( + 'Use `tf.image.resize(...method=ResizeMethod.NEAREST_NEIGHBOR...)` ' + 'instead.' + ), +) +def resize_nearest_neighbor(images, + size, + align_corners=False, + name=None, + half_pixel_centers=False): + return gen_image_ops.resize_nearest_neighbor( + images=images, + size=size, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers, + name=name) + + +resize_area_deprecation = deprecation.deprecated( + date=None, + instructions=( + 'Use `tf.image.resize(...method=ResizeMethod.AREA...)` instead.')) +resize_area = tf_export(v1=['image.resize_area'])( + resize_area_deprecation( + dispatch.add_dispatch_support(gen_image_ops.resize_area) + ) +) + + +@tf_export('image.crop_and_resize', v1=[]) +@dispatch.add_dispatch_support +def crop_and_resize_v2(image, + boxes, + box_indices, + crop_size, + method='bilinear', + extrapolation_value=.0, + name=None): + """Extracts crops from the input image tensor and resizes them. + + Extracts crops from the input image tensor and resizes them using bilinear + sampling or nearest neighbor sampling (possibly with aspect ratio change) to a + common output size specified by `crop_size`. This is more general than the + `crop_to_bounding_box` op which extracts a fixed size slice from the input + image and does not allow resizing or aspect ratio change. The crops occur + first and then the resize. + + Returns a tensor with `crops` from the input `image` at positions defined at + the bounding box locations in `boxes`. The cropped boxes are all resized (with + bilinear or nearest neighbor interpolation) to a fixed + `size = [crop_height, crop_width]`. The result is a 4-D tensor + `[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned. + In particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical + results to using `tf.compat.v1.image.resize_bilinear()` or + `tf.compat.v1.image.resize_nearest_neighbor()`(depends on the `method` + argument) with + `align_corners=True`. + + Args: + image: A 4-D tensor of shape `[batch, image_height, image_width, depth]`. + Both `image_height` and `image_width` need to be positive. + boxes: A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor + specifies the coordinates of a box in the `box_ind[i]` image and is + specified in normalized coordinates `[y1, x1, y2, x2]`. A normalized + coordinate value of `y` is mapped to the image coordinate at `y * + (image_height - 1)`, so as the `[0, 1]` interval of normalized image + height is mapped to `[0, image_height - 1]` in image height coordinates. + We do allow `y1` > `y2`, in which case the sampled crop is an up-down + flipped version of the original image. The width dimension is treated + similarly. Normalized coordinates outside the `[0, 1]` range are allowed, + in which case we use `extrapolation_value` to extrapolate the input image + values. + box_indices: A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, + batch)`. The value of `box_ind[i]` specifies the image that the `i`-th box + refers to. + crop_size: A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. + All cropped image patches are resized to this size. The aspect ratio of + the image content is not preserved. Both `crop_height` and `crop_width` + need to be positive. + method: An optional string specifying the sampling method for resizing. It + can be either `"bilinear"` or `"nearest"` and default to `"bilinear"`. + Currently two sampling methods are supported: Bilinear and Nearest + Neighbor. + extrapolation_value: An optional `float`. Defaults to `0.0`. Value used for + extrapolation, when applicable. + name: A name for the operation (optional). + + Returns: + A 4-D tensor of shape `[num_boxes, crop_height, crop_width, depth]`. + + Usage example: + + >>> BATCH_SIZE = 1 + >>> NUM_BOXES = 5 + >>> IMAGE_HEIGHT = 256 + >>> IMAGE_WIDTH = 256 + >>> CHANNELS = 3 + >>> CROP_SIZE = (24, 24) + + >>> image = tf.random.normal(shape=( + ... BATCH_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, CHANNELS) ) + >>> boxes = tf.random.uniform(shape=(NUM_BOXES, 4)) + >>> box_indices = tf.random.uniform(shape=(NUM_BOXES,), minval=0, + ... maxval=BATCH_SIZE, dtype=tf.int32) + >>> output = tf.image.crop_and_resize(image, boxes, box_indices, CROP_SIZE) + >>> output.shape + TensorShape([5, 24, 24, 3]) + + Example with linear interpolation: + + >>> image = np.arange(0, 18, 2).astype('float32').reshape(3, 3) + >>> result = tf.image.crop_and_resize( + ... image[None, :, :, None], + ... np.asarray([[0.5,0.5,1,1]]), [0], [3, 3], method='bilinear') + >>> result[0][:, :, 0] + + + Example with nearest interpolation: + + >>> image = np.arange(0, 18, 2).astype('float32').reshape(3, 3) + >>> result = tf.image.crop_and_resize( + ... image[None, :, :, None], + ... np.asarray([[0.5,0.5,1,1]]), [0], [3, 3], method='nearest') + >>> result[0][:, :, 0] + + + + """ + return gen_image_ops.crop_and_resize(image, boxes, box_indices, crop_size, + method, extrapolation_value, name) + + +@tf_export(v1=['image.crop_and_resize']) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + 'box_ind is deprecated, use box_indices instead', + 'box_ind') +def crop_and_resize_v1( # pylint: disable=missing-docstring + image, + boxes, + box_ind=None, + crop_size=None, + method='bilinear', + extrapolation_value=0, + name=None, + box_indices=None): + box_ind = deprecation.deprecated_argument_lookup('box_indices', box_indices, + 'box_ind', box_ind) + return gen_image_ops.crop_and_resize(image, boxes, box_ind, crop_size, method, + extrapolation_value, name) + + +crop_and_resize_v1.__doc__ = gen_image_ops.crop_and_resize.__doc__ + + +@tf_export(v1=['image.extract_glimpse']) +@dispatch.add_dispatch_support +def extract_glimpse( + input, # pylint: disable=redefined-builtin + size, + offsets, + centered=True, + normalized=True, + uniform_noise=True, + name=None): + """Extracts a glimpse from the input tensor. + + Returns a set of windows called glimpses extracted at location + `offsets` from the input tensor. If the windows only partially + overlaps the inputs, the non-overlapping areas will be filled with + random noise. + + The result is a 4-D tensor of shape `[batch_size, glimpse_height, + glimpse_width, channels]`. The channels and batch dimensions are the + same as that of the input tensor. The height and width of the output + windows are specified in the `size` parameter. + + The argument `normalized` and `centered` controls how the windows are built: + + * If the coordinates are normalized but not centered, 0.0 and 1.0 + correspond to the minimum and maximum of each height and width + dimension. + * If the coordinates are both normalized and centered, they range from + -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper + left corner, the lower right corner is located at (1.0, 1.0) and the + center is at (0, 0). + * If the coordinates are not normalized they are interpreted as + numbers of pixels. + + Usage Example: + + >>> x = [[[[0.0], + ... [1.0], + ... [2.0]], + ... [[3.0], + ... [4.0], + ... [5.0]], + ... [[6.0], + ... [7.0], + ... [8.0]]]] + >>> tf.compat.v1.image.extract_glimpse(x, size=(2, 2), offsets=[[1, 1]], + ... centered=False, normalized=False) + + + Args: + input: A `Tensor` of type `float32`. A 4-D float tensor of shape + `[batch_size, height, width, channels]`. + size: A `Tensor` of type `int32`. A 1-D tensor of 2 elements containing the + size of the glimpses to extract. The glimpse height must be specified + first, following by the glimpse width. + offsets: A `Tensor` of type `float32`. A 2-D integer tensor of shape + `[batch_size, 2]` containing the y, x locations of the center of each + window. + centered: An optional `bool`. Defaults to `True`. indicates if the offset + coordinates are centered relative to the image, in which case the (0, 0) + offset is relative to the center of the input images. If false, the (0,0) + offset corresponds to the upper left corner of the input images. + normalized: An optional `bool`. Defaults to `True`. indicates if the offset + coordinates are normalized. + uniform_noise: An optional `bool`. Defaults to `True`. indicates if the + noise should be generated using a uniform distribution or a Gaussian + distribution. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + return gen_image_ops.extract_glimpse( + input=input, + size=size, + offsets=offsets, + centered=centered, + normalized=normalized, + uniform_noise=uniform_noise, + name=name) + + +@tf_export('image.extract_glimpse', v1=[]) +@dispatch.add_dispatch_support +def extract_glimpse_v2( + input, # pylint: disable=redefined-builtin + size, + offsets, + centered=True, + normalized=True, + noise='uniform', + name=None): + """Extracts a glimpse from the input tensor. + + Returns a set of windows called glimpses extracted at location + `offsets` from the input tensor. If the windows only partially + overlaps the inputs, the non-overlapping areas will be filled with + random noise. + + The result is a 4-D tensor of shape `[batch_size, glimpse_height, + glimpse_width, channels]`. The channels and batch dimensions are the + same as that of the input tensor. The height and width of the output + windows are specified in the `size` parameter. + + The argument `normalized` and `centered` controls how the windows are built: + + * If the coordinates are normalized but not centered, 0.0 and 1.0 + correspond to the minimum and maximum of each height and width + dimension. + * If the coordinates are both normalized and centered, they range from + -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper + left corner, the lower right corner is located at (1.0, 1.0) and the + center is at (0, 0). + * If the coordinates are not normalized they are interpreted as + numbers of pixels. + + Usage Example: + + >>> x = [[[[0.0], + ... [1.0], + ... [2.0]], + ... [[3.0], + ... [4.0], + ... [5.0]], + ... [[6.0], + ... [7.0], + ... [8.0]]]] + >>> tf.image.extract_glimpse(x, size=(2, 2), offsets=[[1, 1]], + ... centered=False, normalized=False) + + + Args: + input: A `Tensor` of type `float32`. A 4-D float tensor of shape + `[batch_size, height, width, channels]`. + size: A `Tensor` of type `int32`. A 1-D tensor of 2 elements containing the + size of the glimpses to extract. The glimpse height must be specified + first, following by the glimpse width. + offsets: A `Tensor` of type `float32`. A 2-D integer tensor of shape + `[batch_size, 2]` containing the y, x locations of the center of each + window. + centered: An optional `bool`. Defaults to `True`. indicates if the offset + coordinates are centered relative to the image, in which case the (0, 0) + offset is relative to the center of the input images. If false, the (0,0) + offset corresponds to the upper left corner of the input images. + normalized: An optional `bool`. Defaults to `True`. indicates if the offset + coordinates are normalized. + noise: An optional `string`. Defaults to `uniform`. indicates if the noise + should be `uniform` (uniform distribution), `gaussian` (gaussian + distribution), or `zero` (zero padding). + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + return gen_image_ops.extract_glimpse_v2( + input=input, + size=size, + offsets=offsets, + centered=centered, + normalized=normalized, + noise=noise, + uniform_noise=False, + name=name) + + +@tf_export('image.combined_non_max_suppression') +@dispatch.add_dispatch_support +def combined_non_max_suppression(boxes, + scores, + max_output_size_per_class, + max_total_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + pad_per_class=False, + clip_boxes=True, + name=None): + """Greedily selects a subset of bounding boxes in descending order of score. + + This operation performs non_max_suppression on the inputs per batch, across + all classes. + Prunes away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm + is agnostic to where the origin is in the coordinate system. Also note that + this algorithm is invariant to orthogonal transformations and translations + of the coordinate system; thus translating or reflections of the coordinate + system result in the same boxes being selected by the algorithm. + The output of this operation is the final boxes, scores and classes tensor + returned after performing non_max_suppression. + + Args: + boxes: A 4-D float `Tensor` of shape `[batch_size, num_boxes, q, 4]`. If `q` + is 1 then same boxes are used for all classes otherwise, if `q` is equal + to number of classes, class-specific boxes are used. + scores: A 3-D float `Tensor` of shape `[batch_size, num_boxes, num_classes]` + representing a single score corresponding to each box (each row of boxes). + max_output_size_per_class: A scalar integer `Tensor` representing the + maximum number of boxes to be selected by non-max suppression per class + max_total_size: A int32 scalar representing maximum number of boxes retained + over all classes. Note that setting this value to a large number may + result in OOM error depending on the system workload. + iou_threshold: A float representing the threshold for deciding whether boxes + overlap too much with respect to IOU. + score_threshold: A float representing the threshold for deciding when to + remove boxes based on score. + pad_per_class: If false, the output nmsed boxes, scores and classes are + padded/clipped to `max_total_size`. If true, the output nmsed boxes, + scores and classes are padded to be of length + `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in + which case it is clipped to `max_total_size`. Defaults to false. + clip_boxes: If true, the coordinates of output nmsed boxes will be clipped + to [0, 1]. If false, output the box coordinates as it is. Defaults to + true. + name: A name for the operation (optional). + + Returns: + 'nmsed_boxes': A [batch_size, max_detections, 4] float32 tensor + containing the non-max suppressed boxes. + 'nmsed_scores': A [batch_size, max_detections] float32 tensor containing + the scores for the boxes. + 'nmsed_classes': A [batch_size, max_detections] float32 tensor + containing the class for boxes. + 'valid_detections': A [batch_size] int32 tensor indicating the number of + valid detections per batch item. Only the top valid_detections[i] entries + in nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the + entries are zero paddings. + """ + with ops.name_scope(name, 'combined_non_max_suppression'): + iou_threshold = ops.convert_to_tensor( + iou_threshold, dtype=dtypes.float32, name='iou_threshold') + score_threshold = ops.convert_to_tensor( + score_threshold, dtype=dtypes.float32, name='score_threshold') + + # Convert `max_total_size` to tensor *without* setting the `dtype` param. + # This allows us to catch `int32` overflow case with `max_total_size` + # whose expected dtype is `int32` by the op registration. Any number within + # `int32` will get converted to `int32` tensor. Anything larger will get + # converted to `int64`. Passing in `int64` for `max_total_size` to the op + # will throw dtype mismatch exception. + # TODO(b/173251596): Once there is a more general solution to warn against + # int overflow conversions, revisit this check. + max_total_size = ops.convert_to_tensor(max_total_size) + + return gen_image_ops.combined_non_max_suppression( + boxes, scores, max_output_size_per_class, max_total_size, iou_threshold, + score_threshold, pad_per_class, clip_boxes) + + +def _bbox_overlap(boxes_a, boxes_b): + """Calculates the overlap (iou - intersection over union) between boxes_a and boxes_b. + + Args: + boxes_a: a tensor with a shape of [batch_size, N, 4]. N is the number of + boxes per image. The last dimension is the pixel coordinates in + [ymin, xmin, ymax, xmax] form. + boxes_b: a tensor with a shape of [batch_size, M, 4]. M is the number of + boxes. The last dimension is the pixel coordinates in + [ymin, xmin, ymax, xmax] form. + Returns: + intersection_over_union: a tensor with as a shape of [batch_size, N, M], + representing the ratio of intersection area over union area (IoU) between + two boxes + """ + with ops.name_scope('bbox_overlap'): + a_y_min, a_x_min, a_y_max, a_x_max = array_ops.split( + value=boxes_a, num_or_size_splits=4, axis=2) + b_y_min, b_x_min, b_y_max, b_x_max = array_ops.split( + value=boxes_b, num_or_size_splits=4, axis=2) + + # Calculates the intersection area. + i_xmin = math_ops.maximum( + a_x_min, array_ops.transpose(b_x_min, [0, 2, 1])) + i_xmax = math_ops.minimum( + a_x_max, array_ops.transpose(b_x_max, [0, 2, 1])) + i_ymin = math_ops.maximum( + a_y_min, array_ops.transpose(b_y_min, [0, 2, 1])) + i_ymax = math_ops.minimum( + a_y_max, array_ops.transpose(b_y_max, [0, 2, 1])) + i_area = math_ops.maximum( + (i_xmax - i_xmin), 0) * math_ops.maximum((i_ymax - i_ymin), 0) + + # Calculates the union area. + a_area = (a_y_max - a_y_min) * (a_x_max - a_x_min) + b_area = (b_y_max - b_y_min) * (b_x_max - b_x_min) + EPSILON = 1e-8 + # Adds a small epsilon to avoid divide-by-zero. + u_area = a_area + array_ops.transpose(b_area, [0, 2, 1]) - i_area + EPSILON + + # Calculates IoU. + intersection_over_union = i_area / u_area + + return intersection_over_union + + +def _self_suppression(iou, _, iou_sum, iou_threshold): + """Suppress boxes in the same tile. + + Compute boxes that cannot be suppressed by others (i.e., + can_suppress_others), and then use them to suppress boxes in the same tile. + + Args: + iou: a tensor of shape [batch_size, num_boxes_with_padding] representing + intersection over union. + iou_sum: a scalar tensor. + iou_threshold: a scalar tensor. + + Returns: + iou_suppressed: a tensor of shape [batch_size, num_boxes_with_padding]. + iou_diff: a scalar tensor representing whether any box is supressed in + this step. + iou_sum_new: a scalar tensor of shape [batch_size] that represents + the iou sum after suppression. + iou_threshold: a scalar tensor. + """ + batch_size = array_ops.shape(iou)[0] + can_suppress_others = math_ops.cast( + array_ops.reshape( + math_ops.reduce_max(iou, 1) < iou_threshold, [batch_size, -1, 1]), + iou.dtype) + iou_after_suppression = array_ops.reshape( + math_ops.cast( + math_ops.reduce_max(can_suppress_others * iou, 1) < iou_threshold, + iou.dtype), + [batch_size, -1, 1]) * iou + iou_sum_new = math_ops.reduce_sum(iou_after_suppression, [1, 2]) + return [ + iou_after_suppression, + math_ops.reduce_any(iou_sum - iou_sum_new > iou_threshold), iou_sum_new, + iou_threshold + ] + + +def _cross_suppression(boxes, box_slice, iou_threshold, inner_idx, tile_size): + """Suppress boxes between different tiles. + + Args: + boxes: a tensor of shape [batch_size, num_boxes_with_padding, 4] + box_slice: a tensor of shape [batch_size, tile_size, 4] + iou_threshold: a scalar tensor + inner_idx: a scalar tensor representing the tile index of the tile + that is used to supress box_slice + tile_size: an integer representing the number of boxes in a tile + + Returns: + boxes: unchanged boxes as input + box_slice_after_suppression: box_slice after suppression + iou_threshold: unchanged + """ + batch_size = array_ops.shape(boxes)[0] + new_slice = array_ops.slice( + boxes, [0, inner_idx * tile_size, 0], + [batch_size, tile_size, 4]) + iou = _bbox_overlap(new_slice, box_slice) + box_slice_after_suppression = array_ops.expand_dims( + math_ops.cast(math_ops.reduce_all(iou < iou_threshold, [1]), + box_slice.dtype), + 2) * box_slice + return boxes, box_slice_after_suppression, iou_threshold, inner_idx + 1 + + +def _suppression_loop_body(boxes, iou_threshold, output_size, idx, tile_size): + """Process boxes in the range [idx*tile_size, (idx+1)*tile_size). + + Args: + boxes: a tensor with a shape of [batch_size, anchors, 4]. + iou_threshold: a float representing the threshold for deciding whether boxes + overlap too much with respect to IOU. + output_size: an int32 tensor of size [batch_size]. Representing the number + of selected boxes for each batch. + idx: an integer scalar representing induction variable. + tile_size: an integer representing the number of boxes in a tile + + Returns: + boxes: updated boxes. + iou_threshold: pass down iou_threshold to the next iteration. + output_size: the updated output_size. + idx: the updated induction variable. + """ + with ops.name_scope('suppression_loop_body'): + num_tiles = array_ops.shape(boxes)[1] // tile_size + batch_size = array_ops.shape(boxes)[0] + + def cross_suppression_func(boxes, box_slice, iou_threshold, inner_idx): + return _cross_suppression(boxes, box_slice, iou_threshold, inner_idx, + tile_size) + + # Iterates over tiles that can possibly suppress the current tile. + box_slice = array_ops.slice(boxes, [0, idx * tile_size, 0], + [batch_size, tile_size, 4]) + _, box_slice, _, _ = while_loop.while_loop( + lambda _boxes, _box_slice, _threshold, inner_idx: inner_idx < idx, + cross_suppression_func, + [boxes, box_slice, iou_threshold, + constant_op.constant(0)]) + + # Iterates over the current tile to compute self-suppression. + iou = _bbox_overlap(box_slice, box_slice) + mask = array_ops.expand_dims( + array_ops.reshape( + math_ops.range(tile_size), [1, -1]) > array_ops.reshape( + math_ops.range(tile_size), [-1, 1]), 0) + iou *= math_ops.cast( + math_ops.logical_and(mask, iou >= iou_threshold), iou.dtype) + suppressed_iou, _, _, _ = while_loop.while_loop( + lambda _iou, loop_condition, _iou_sum, _: loop_condition, + _self_suppression, [ + iou, + constant_op.constant(True), + math_ops.reduce_sum(iou, [1, 2]), iou_threshold + ]) + suppressed_box = math_ops.reduce_sum(suppressed_iou, 1) > 0 + box_slice *= array_ops.expand_dims( + 1.0 - math_ops.cast(suppressed_box, box_slice.dtype), 2) + + # Uses box_slice to update the input boxes. + mask = array_ops.reshape( + math_ops.cast( + math_ops.equal(math_ops.range(num_tiles), idx), boxes.dtype), + [1, -1, 1, 1]) + boxes = array_ops.tile(array_ops.expand_dims( + box_slice, [1]), [1, num_tiles, 1, 1]) * mask + array_ops.reshape( + boxes, [batch_size, num_tiles, tile_size, 4]) * (1 - mask) + boxes = array_ops.reshape(boxes, [batch_size, -1, 4]) + + # Updates output_size. + output_size += math_ops.reduce_sum( + math_ops.cast( + math_ops.reduce_any(box_slice > 0, [2]), dtypes.int32), [1]) + return boxes, iou_threshold, output_size, idx + 1 + + +@tf_export('image.non_max_suppression_padded') +@dispatch.add_dispatch_support +def non_max_suppression_padded(boxes, + scores, + max_output_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + pad_to_max_output_size=False, + name=None, + sorted_input=False, + canonicalized_coordinates=False, + tile_size=512): + """Greedily selects a subset of bounding boxes in descending order of score. + + Performs algorithmically equivalent operation to tf.image.non_max_suppression, + with the addition of an optional parameter which zero-pads the output to + be of size `max_output_size`. + The output of this operation is a tuple containing the set of integers + indexing into the input collection of bounding boxes representing the selected + boxes and the number of valid indices in the index set. The bounding box + coordinates corresponding to the selected indices can then be obtained using + the `tf.slice` and `tf.gather` operations. For example: + ```python + selected_indices_padded, num_valid = tf.image.non_max_suppression_padded( + boxes, scores, max_output_size, iou_threshold, + score_threshold, pad_to_max_output_size=True) + selected_indices = tf.slice( + selected_indices_padded, tf.constant([0]), num_valid) + selected_boxes = tf.gather(boxes, selected_indices) + ``` + + Args: + boxes: a tensor of rank 2 or higher with a shape of [..., num_boxes, 4]. + Dimensions except the last two are batch dimensions. + scores: a tensor of rank 1 or higher with a shape of [..., num_boxes]. + max_output_size: a scalar integer `Tensor` representing the maximum number + of boxes to be selected by non max suppression. Note that setting this + value to a large number may result in OOM error depending on the system + workload. + iou_threshold: a float representing the threshold for deciding whether boxes + overlap too much with respect to IoU (intersection over union). + score_threshold: a float representing the threshold for box scores. Boxes + with a score that is not larger than this threshold will be suppressed. + pad_to_max_output_size: whether to pad the output idx to max_output_size. + Must be set to True when the input is a batch of images. + name: name of operation. + sorted_input: a boolean indicating whether the input boxes and scores + are sorted in descending order by the score. + canonicalized_coordinates: if box coordinates are given as + `[y_min, x_min, y_max, x_max]`, setting to True eliminate redundant + computation to canonicalize box coordinates. + tile_size: an integer representing the number of boxes in a tile, i.e., + the maximum number of boxes per image that can be used to suppress other + boxes in parallel; larger tile_size means larger parallelism and + potentially more redundant work. + Returns: + idx: a tensor with a shape of [..., num_boxes] representing the + indices selected by non-max suppression. The leading dimensions + are the batch dimensions of the input boxes. All numbers are within + [0, num_boxes). For each image (i.e., idx[i]), only the first num_valid[i] + indices (i.e., idx[i][:num_valid[i]]) are valid. + num_valid: a tensor of rank 0 or higher with a shape of [...] + representing the number of valid indices in idx. Its dimensions are the + batch dimensions of the input boxes. + Raises: + ValueError: When set pad_to_max_output_size to False for batched input. + """ + with ops.name_scope(name, 'non_max_suppression_padded'): + if not pad_to_max_output_size: + # pad_to_max_output_size may be set to False only when the shape of + # boxes is [num_boxes, 4], i.e., a single image. We make best effort to + # detect violations at compile time. If `boxes` does not have a static + # rank, the check allows computation to proceed. + if boxes.get_shape().rank is not None and boxes.get_shape().rank > 2: + raise ValueError("'pad_to_max_output_size' (value {}) must be True for " + 'batched input'.format(pad_to_max_output_size)) + if name is None: + name = '' + idx, num_valid = non_max_suppression_padded_v2( + boxes, scores, max_output_size, iou_threshold, score_threshold, + sorted_input, canonicalized_coordinates, tile_size) + # def_function.function seems to lose shape information, so set it here. + if not pad_to_max_output_size: + idx = idx[0, :num_valid] + else: + batch_dims = array_ops.concat([ + array_ops.shape(boxes)[:-2], + array_ops.expand_dims(max_output_size, 0) + ], 0) + idx = array_ops.reshape(idx, batch_dims) + return idx, num_valid + + +# TODO(b/158709815): Improve performance regression due to +# def_function.function. +@def_function.function( + experimental_implements='non_max_suppression_padded_v2') +def non_max_suppression_padded_v2(boxes, + scores, + max_output_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + sorted_input=False, + canonicalized_coordinates=False, + tile_size=512): + """Non-maximum suppression. + + Prunes away boxes that have high intersection-over-union (IOU) overlap + with previously selected boxes. Bounding boxes are supplied as + `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the coordinates of any + diagonal pair of box corners and the coordinates can be provided as normalized + (i.e., lying in the interval `[0, 1]`) or absolute. The bounding box + coordinates are cannonicalized to `[y_min, x_min, y_max, x_max]`, + where `(y_min, x_min)` and `(y_max, x_mas)` are the coordinates of the lower + left and upper right corner. User may indiciate the input box coordinates are + already canonicalized to eliminate redundant work by setting + canonicalized_coordinates to `True`. Note that this algorithm is agnostic to + where the origin is in the coordinate system. Note that this algorithm is + invariant to orthogonal transformations and translations of the coordinate + system; thus translating or reflections of the coordinate system result in the + same boxes being selected by the algorithm. + + Similar to tf.image.non_max_suppression, non_max_suppression_padded + implements hard NMS but can operate on a batch of images and improves + performance by titling the bounding boxes. Non_max_suppression_padded should + be preferred over tf.image_non_max_suppression when running on devices with + abundant parallelsim for higher computation speed. For soft NMS, refer to + tf.image.non_max_suppression_with_scores. + + While a serial NMS algorithm iteratively uses the highest-scored unprocessed + box to suppress boxes, this algorithm uses many boxes to suppress other boxes + in parallel. The key idea is to partition boxes into tiles based on their + score and suppresses boxes tile by tile, thus achieving parallelism within a + tile. The tile size determines the degree of parallelism. + + In cross suppression (using boxes of tile A to suppress boxes of tile B), + all boxes in A can independently suppress boxes in B. + + Self suppression (suppressing boxes of the same tile) needs to be iteratively + applied until there's no more suppression. In each iteration, boxes that + cannot be suppressed are used to suppress boxes in the same tile. + + boxes = boxes.pad_to_multiply_of(tile_size) + num_tiles = len(boxes) // tile_size + output_boxes = [] + for i in range(num_tiles): + box_tile = boxes[i*tile_size : (i+1)*tile_size] + for j in range(i - 1): + # in parallel suppress boxes in box_tile using boxes from suppressing_tile + suppressing_tile = boxes[j*tile_size : (j+1)*tile_size] + iou = _bbox_overlap(box_tile, suppressing_tile) + # if the box is suppressed in iou, clear it to a dot + box_tile *= _update_boxes(iou) + # Iteratively handle the diagnal tile. + iou = _box_overlap(box_tile, box_tile) + iou_changed = True + while iou_changed: + # boxes that are not suppressed by anything else + suppressing_boxes = _get_suppressing_boxes(iou) + # boxes that are suppressed by suppressing_boxes + suppressed_boxes = _get_suppressed_boxes(iou, suppressing_boxes) + # clear iou to 0 for boxes that are suppressed, as they cannot be used + # to suppress other boxes any more + new_iou = _clear_iou(iou, suppressed_boxes) + iou_changed = (new_iou != iou) + iou = new_iou + # remaining boxes that can still suppress others, are selected boxes. + output_boxes.append(_get_suppressing_boxes(iou)) + if len(output_boxes) >= max_output_size: + break + + Args: + boxes: a tensor of rank 2 or higher with a shape of [..., num_boxes, 4]. + Dimensions except the last two are batch dimensions. The last dimension + represents box coordinates, given as [y_1, x_1, y_2, x_2]. The coordinates + on each dimension can be given in any order + (see also `canonicalized_coordinates`) but must describe a box with + a positive area. + scores: a tensor of rank 1 or higher with a shape of [..., num_boxes]. + max_output_size: a scalar integer `Tensor` representing the maximum number + of boxes to be selected by non max suppression. + iou_threshold: a float representing the threshold for deciding whether boxes + overlap too much with respect to IoU (intersection over union). + score_threshold: a float representing the threshold for box scores. Boxes + with a score that is not larger than this threshold will be suppressed. + sorted_input: a boolean indicating whether the input boxes and scores + are sorted in descending order by the score. + canonicalized_coordinates: if box coordinates are given as + `[y_min, x_min, y_max, x_max]`, setting to True eliminate redundant + computation to canonicalize box coordinates. + tile_size: an integer representing the number of boxes in a tile, i.e., + the maximum number of boxes per image that can be used to suppress other + boxes in parallel; larger tile_size means larger parallelism and + potentially more redundant work. + Returns: + idx: a tensor with a shape of [..., num_boxes] representing the + indices selected by non-max suppression. The leading dimensions + are the batch dimensions of the input boxes. All numbers are within + [0, num_boxes). For each image (i.e., idx[i]), only the first num_valid[i] + indices (i.e., idx[i][:num_valid[i]]) are valid. + num_valid: a tensor of rank 0 or higher with a shape of [...] + representing the number of valid indices in idx. Its dimensions are the + batch dimensions of the input boxes. + Raises: + ValueError: When set pad_to_max_output_size to False for batched input. + """ + def _sort_scores_and_boxes(scores, boxes): + """Sort boxes based their score from highest to lowest. + + Args: + scores: a tensor with a shape of [batch_size, num_boxes] representing + the scores of boxes. + boxes: a tensor with a shape of [batch_size, num_boxes, 4] representing + the boxes. + Returns: + sorted_scores: a tensor with a shape of [batch_size, num_boxes] + representing the sorted scores. + sorted_boxes: a tensor representing the sorted boxes. + sorted_scores_indices: a tensor with a shape of [batch_size, num_boxes] + representing the index of the scores in a sorted descending order. + """ + with ops.name_scope('sort_scores_and_boxes'): + sorted_scores_indices = sort_ops.argsort( + scores, axis=1, direction='DESCENDING') + sorted_scores = array_ops.gather( + scores, sorted_scores_indices, axis=1, batch_dims=1 + ) + sorted_boxes = array_ops.gather( + boxes, sorted_scores_indices, axis=1, batch_dims=1 + ) + return sorted_scores, sorted_boxes, sorted_scores_indices + + batch_dims = array_ops.shape(boxes)[:-2] + num_boxes = array_ops.shape(boxes)[-2] + boxes = array_ops.reshape(boxes, [-1, num_boxes, 4]) + scores = array_ops.reshape(scores, [-1, num_boxes]) + batch_size = array_ops.shape(boxes)[0] + if score_threshold != float('-inf'): + with ops.name_scope('filter_by_score'): + score_mask = math_ops.cast(scores > score_threshold, scores.dtype) + scores *= score_mask + box_mask = array_ops.expand_dims( + math_ops.cast(score_mask, boxes.dtype), 2) + boxes *= box_mask + + if not canonicalized_coordinates: + with ops.name_scope('canonicalize_coordinates'): + y_1, x_1, y_2, x_2 = array_ops.split( + value=boxes, num_or_size_splits=4, axis=2) + y_1_is_min = math_ops.reduce_all( + math_ops.less_equal(y_1[0, 0, 0], y_2[0, 0, 0])) + y_min, y_max = tf_cond.cond( + y_1_is_min, lambda: (y_1, y_2), lambda: (y_2, y_1)) + x_1_is_min = math_ops.reduce_all( + math_ops.less_equal(x_1[0, 0, 0], x_2[0, 0, 0])) + x_min, x_max = tf_cond.cond( + x_1_is_min, lambda: (x_1, x_2), lambda: (x_2, x_1)) + boxes = array_ops.concat([y_min, x_min, y_max, x_max], axis=2) + # TODO(@bhack): https://github.com/tensorflow/tensorflow/issues/56089 + # this will be required after deprecation + #else: + # y_1, x_1, y_2, x_2 = array_ops.split( + # value=boxes, num_or_size_splits=4, axis=2) + + if not sorted_input: + scores, boxes, sorted_indices = _sort_scores_and_boxes(scores, boxes) + else: + # Default value required for Autograph. + sorted_indices = array_ops.zeros_like(scores, dtype=dtypes.int32) + + pad = math_ops.cast( + math_ops.ceil( + math_ops.cast( + math_ops.maximum(num_boxes, max_output_size), dtypes.float32) / + math_ops.cast(tile_size, dtypes.float32)), + dtypes.int32) * tile_size - num_boxes + boxes = array_ops.pad( + math_ops.cast(boxes, dtypes.float32), [[0, 0], [0, pad], [0, 0]]) + scores = array_ops.pad( + math_ops.cast(scores, dtypes.float32), [[0, 0], [0, pad]]) + num_boxes_after_padding = num_boxes + pad + num_iterations = num_boxes_after_padding // tile_size + def _loop_cond(unused_boxes, unused_threshold, output_size, idx): + return math_ops.logical_and( + math_ops.reduce_min(output_size) < max_output_size, + idx < num_iterations) + + def suppression_loop_body(boxes, iou_threshold, output_size, idx): + return _suppression_loop_body( + boxes, iou_threshold, output_size, idx, tile_size) + + selected_boxes, _, output_size, _ = while_loop.while_loop( + _loop_cond, + suppression_loop_body, + [ + boxes, iou_threshold, + array_ops.zeros([batch_size], dtypes.int32), + constant_op.constant(0) + ], + shape_invariants=[ + tensor_shape.TensorShape([None, None, 4]), + tensor_shape.TensorShape([]), + tensor_shape.TensorShape([None]), + tensor_shape.TensorShape([]), + ], + ) + num_valid = math_ops.minimum(output_size, max_output_size) + idx = num_boxes_after_padding - math_ops.cast( + nn_ops.top_k( + math_ops.cast(math_ops.reduce_any( + selected_boxes > 0, [2]), dtypes.int32) * + array_ops.expand_dims( + math_ops.range(num_boxes_after_padding, 0, -1), 0), + max_output_size)[0], dtypes.int32) + idx = math_ops.minimum(idx, num_boxes - 1) + + if not sorted_input: + index_offsets = math_ops.range(batch_size) * num_boxes + gather_idx = array_ops.reshape( + idx + array_ops.expand_dims(index_offsets, 1), [-1]) + idx = array_ops.reshape( + array_ops.gather(array_ops.reshape(sorted_indices, [-1]), + gather_idx), + [batch_size, -1]) + invalid_index = array_ops.zeros([batch_size, max_output_size], + dtype=dtypes.int32) + idx_index = array_ops.expand_dims(math_ops.range(max_output_size), 0) + num_valid_expanded = array_ops.expand_dims(num_valid, 1) + idx = array_ops.where(idx_index < num_valid_expanded, + idx, invalid_index) + + num_valid = array_ops.reshape(num_valid, batch_dims) + return idx, num_valid + + +def non_max_suppression_padded_v1(boxes, + scores, + max_output_size, + iou_threshold=0.5, + score_threshold=float('-inf'), + pad_to_max_output_size=False, + name=None): + """Greedily selects a subset of bounding boxes in descending order of score. + + Performs algorithmically equivalent operation to tf.image.non_max_suppression, + with the addition of an optional parameter which zero-pads the output to + be of size `max_output_size`. + The output of this operation is a tuple containing the set of integers + indexing into the input collection of bounding boxes representing the selected + boxes and the number of valid indices in the index set. The bounding box + coordinates corresponding to the selected indices can then be obtained using + the `tf.slice` and `tf.gather` operations. For example: + ```python + selected_indices_padded, num_valid = tf.image.non_max_suppression_padded( + boxes, scores, max_output_size, iou_threshold, + score_threshold, pad_to_max_output_size=True) + selected_indices = tf.slice( + selected_indices_padded, tf.constant([0]), num_valid) + selected_boxes = tf.gather(boxes, selected_indices) + ``` + + Args: + boxes: A 2-D float `Tensor` of shape `[num_boxes, 4]`. + scores: A 1-D float `Tensor` of shape `[num_boxes]` representing a single + score corresponding to each box (each row of boxes). + max_output_size: A scalar integer `Tensor` representing the maximum number + of boxes to be selected by non-max suppression. + iou_threshold: A float representing the threshold for deciding whether boxes + overlap too much with respect to IOU. + score_threshold: A float representing the threshold for deciding when to + remove boxes based on score. + pad_to_max_output_size: bool. If True, size of `selected_indices` output is + padded to `max_output_size`. + name: A name for the operation (optional). + + Returns: + selected_indices: A 1-D integer `Tensor` of shape `[M]` representing the + selected indices from the boxes tensor, where `M <= max_output_size`. + valid_outputs: A scalar integer `Tensor` denoting how many elements in + `selected_indices` are valid. Valid elements occur first, then padding. + """ + with ops.name_scope(name, 'non_max_suppression_padded'): + iou_threshold = ops.convert_to_tensor(iou_threshold, name='iou_threshold') + score_threshold = ops.convert_to_tensor( + score_threshold, name='score_threshold') + return gen_image_ops.non_max_suppression_v4(boxes, scores, max_output_size, + iou_threshold, score_threshold, + pad_to_max_output_size) + + +@tf_export('image.draw_bounding_boxes', v1=[]) +@dispatch.add_dispatch_support +def draw_bounding_boxes_v2(images, boxes, colors, name=None): + """Draw bounding boxes on a batch of images. + + Outputs a copy of `images` but draws on top of the pixels zero or more + bounding boxes specified by the locations in `boxes`. The coordinates of the + each bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. + The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width + and the height of the underlying image. + + For example, if an image is 100 x 200 pixels (height x width) and the bounding + box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of + the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates). + + Parts of the bounding box may fall outside the image. + + Args: + images: A `Tensor`. Must be one of the following types: `float32`, `half`. + 4-D with shape `[batch, height, width, depth]`. A batch of images. + boxes: A `Tensor` of type `float32`. 3-D with shape `[batch, + num_bounding_boxes, 4]` containing bounding boxes. + colors: A `Tensor` of type `float32`. 2-D. A list of RGBA colors to cycle + through for the boxes. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `images`. + + Usage Example: + + >>> # create an empty image + >>> img = tf.zeros([1, 3, 3, 3]) + >>> # draw a box around the image + >>> box = np.array([0, 0, 1, 1]) + >>> boxes = box.reshape([1, 1, 4]) + >>> # alternate between red and blue + >>> colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + >>> tf.image.draw_bounding_boxes(img, boxes, colors) + + """ + if colors is None: + return gen_image_ops.draw_bounding_boxes(images, boxes, name) + return gen_image_ops.draw_bounding_boxes_v2(images, boxes, colors, name) + + +@tf_export(v1=['image.draw_bounding_boxes']) +@dispatch.add_dispatch_support +def draw_bounding_boxes(images, boxes, name=None, colors=None): + """Draw bounding boxes on a batch of images. + + Outputs a copy of `images` but draws on top of the pixels zero or more + bounding boxes specified by the locations in `boxes`. The coordinates of the + each bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. + The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width + and the height of the underlying image. + + For example, if an image is 100 x 200 pixels (height x width) and the bounding + box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of + the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates). + + Parts of the bounding box may fall outside the image. + + Args: + images: A `Tensor`. Must be one of the following types: `float32`, `half`. + 4-D with shape `[batch, height, width, depth]`. A batch of images. + boxes: A `Tensor` of type `float32`. 3-D with shape `[batch, + num_bounding_boxes, 4]` containing bounding boxes. + name: A name for the operation (optional). + colors: A `Tensor` of type `float32`. 2-D. A list of RGBA colors to cycle + through for the boxes. + + Returns: + A `Tensor`. Has the same type as `images`. + + Usage Example: + + >>> # create an empty image + >>> img = tf.zeros([1, 3, 3, 3]) + >>> # draw a box around the image + >>> box = np.array([0, 0, 1, 1]) + >>> boxes = box.reshape([1, 1, 4]) + >>> # alternate between red and blue + >>> colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + >>> tf.image.draw_bounding_boxes(img, boxes, colors) + + """ + return draw_bounding_boxes_v2(images, boxes, colors, name) + + +@tf_export('image.generate_bounding_box_proposals') +@dispatch.add_dispatch_support +def generate_bounding_box_proposals(scores, + bbox_deltas, + image_info, + anchors, + nms_threshold=0.7, + pre_nms_topn=6000, + min_size=16, + post_nms_topn=300, + name=None): + """Generate bounding box proposals from encoded bounding boxes. + + Args: + scores: A 4-D float `Tensor` of shape + `[num_images, height, width, num_achors]` containing scores of + the boxes for given anchors, can be unsorted. + bbox_deltas: A 4-D float `Tensor` of shape + `[num_images, height, width, 4 x num_anchors]` encoding boxes + with respect to each anchor. Coordinates are given + in the form `[dy, dx, dh, dw]`. + image_info: A 2-D float `Tensor` of shape `[num_images, 5]` + containing image information Height, Width, Scale. + anchors: A 2-D float `Tensor` of shape `[num_anchors, 4]` + describing the anchor boxes. + Boxes are formatted in the form `[y1, x1, y2, x2]`. + nms_threshold: A scalar float `Tensor` for non-maximal-suppression + threshold. Defaults to 0.7. + pre_nms_topn: A scalar int `Tensor` for the number of + top scoring boxes to be used as input. Defaults to 6000. + min_size: A scalar float `Tensor`. Any box that has a smaller size + than min_size will be discarded. Defaults to 16. + post_nms_topn: An integer. Maximum number of rois in the output. + name: A name for this operation (optional). + + Returns: + rois: Region of interest boxes sorted by their scores. + roi_probabilities: scores of the ROI boxes in the ROIs' `Tensor`. + """ + return gen_image_ops.generate_bounding_box_proposals( + scores=scores, + bbox_deltas=bbox_deltas, + image_info=image_info, + anchors=anchors, + nms_threshold=nms_threshold, + pre_nms_topn=pre_nms_topn, + min_size=min_size, + post_nms_topn=post_nms_topn, + name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..35ce2be00ba2931d5bda5483165a5626f41d9075 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops.py @@ -0,0 +1,1833 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations often used for initializing tensors. + +All variable initializers returned by functions in this file should have the +following signature: + +def _initializer(shape, dtype=dtypes.float32, partition_info=None): + Args: + shape: List of `int` representing the shape of the output `Tensor`. Some + initializers may also be able to accept a `Tensor`. + dtype: (Optional) Type of the output `Tensor`. + partition_info: (Optional) variable_scope._PartitionInfo object holding + additional information about how the variable is partitioned. May be + `None` if the variable is not partitioned. + + Returns: + A `Tensor` of type `dtype` and `shape`. +""" +import math + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.deprecation import deprecated_arg_values +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import tf_export + + +class Initializer: + """Initializer base class: all initializers inherit from this class.""" + + def __call__(self, shape, dtype=None, partition_info=None): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. If not provided use the initializer + dtype. + partition_info: Optional information about the possible partitioning of a + tensor. + """ + raise NotImplementedError + + def get_config(self): + """Returns the configuration of the initializer as a JSON-serializable dict. + + Returns: + A JSON-serializable Python dict. + """ + return {} + + @classmethod + def from_config(cls, config): + """Instantiates an initializer from a configuration dictionary. + + Example: + + ```python + initializer = RandomUniform(-1, 1) + config = initializer.get_config() + initializer = RandomUniform.from_config(config) + ``` + + Args: + config: A Python dictionary. It will typically be the output of + `get_config`. + + Returns: + An Initializer instance. + """ + return cls(**config) + + +@tf_export(v1=["initializers.zeros", "zeros_initializer"]) +@deprecation.deprecated_endpoints("initializers.zeros") +class Zeros(Initializer): + """Initializer that generates tensors initialized to 0. + + @compatibility(TF2) + `tf.compat.v1.zeros_initializer` is compatible with eager execution + and `tf.function`. + + To migrate to TF2, please use `tf.zeros_initializer` instead. The `dtype` + argument in `tf.compat.v1.zeros_initializer.__init__()` does not exist in + `tf.zeros_initializer.__init__()`. However, you can specify the `dtype` in + `__call__()` in both cases. + + #### Structural Mapping to TF2 + + Before: + + ```python + initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32) + variable = tf.Variable(initializer(shape=[3, 3])) + ``` + + After: + + ```python + initializer = tf.zeros_initializer() + variable = tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------------- | :--------------- | :------------------------- | + | `dtype` | `dtype` | In `__call__()` method | + | `partition_info` | - | (`__call__` arg in TF1) Not supported | + + + #### Before & After Usage Example + + Before: + + >>> initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32) + >>> tf.Variable(initializer(shape=[3])).numpy() + array([0., 0., 0.], dtype=float32) + >>> tf.Variable(initializer(shape=[3, 3])).numpy() + array([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]], dtype=float32) + >>> initializer = tf.compat.v1.zeros_initializer() + >>> tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy() + array([0., 0., 0.], dtype=float32) + >>> tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy() + array([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]], dtype=float32) + + After: + + >>> initializer = tf.zeros_initializer() + >>> tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy() + array([0., 0., 0.], dtype=float32) + >>> tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy() + array([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]], dtype=float32) + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, dtype=dtypes.float32): + self.dtype = dtypes.as_dtype(dtype) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + return array_ops.zeros(shape, dtype) + + def get_config(self): + return {"dtype": self.dtype.name} + + +@tf_export(v1=["initializers.ones", "ones_initializer"]) +@deprecation.deprecated_endpoints("initializers.ones", "ones_initializer") +class Ones(Initializer): + """Initializer that generates tensors initialized to 1. + + @compatibility(TF2) + This API is compatible with TF2 behavior and `tf.function`, and can be + migrated immediately with `tf.keras.initializers.ones`. + + Before: + >>> initializer = tf.compat.v1.keras.initializers.ones() + >>> initializer((1, 1)) + + + After: + >>> initializer = tf.keras.initializers.ones() + >>> initializer((1, 1)) + + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, dtype=dtypes.float32): + self.dtype = dtypes.as_dtype(dtype) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + return array_ops.ones(shape, dtype) + + def get_config(self): + return {"dtype": self.dtype.name} + + +@tf_export(v1=["initializers.constant", "constant_initializer"]) +@deprecation.deprecated_endpoints("constant_initializer") +class Constant(Initializer): + """Initializer that generates tensors with constant values. + + The resulting tensor is populated with values of type `dtype`, as + specified by arguments `value` following the desired `shape` of the + new tensor (see examples below). + + The argument `value` can be a constant value, or a list of values of type + `dtype`. If `value` is a list, then the length of the list must be less + than or equal to the number of elements implied by the desired shape of the + tensor. In the case where the total number of elements in `value` is less + than the number of elements required by the tensor shape, the last element + in `value` will be used to fill the remaining entries. If the total number of + elements in `value` is greater than the number of elements required by the + tensor shape, the initializer will raise a `ValueError`. + + Args: + value: A Python scalar, list or tuple of values, or a N-dimensional numpy + array. All elements of the initialized variable will be set to the + corresponding value in the `value` argument. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. + verify_shape: Boolean that enables verification of the shape of `value`. If + `True`, the initializer will throw an error if the shape of `value` is not + compatible with the shape of the initialized tensor. + + Raises: + TypeError: If the input `value` is not one of the expected types. + + Examples: + The following example can be rewritten using a numpy.ndarray instead + of the `value` list, even reshaped, as shown in the two commented lines + below the `value` list initialization. + + >>> value = [0, 1, 2, 3, 4, 5, 6, 7] + >>> init = tf.compat.v1.constant_initializer(value) + >>> # fitting shape + >>> with tf.compat.v1.Session(): + ... x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init) + ... x.initializer.run() + ... print(x.eval()) + [[0. 1. 2. 3.] + [4. 5. 6. 7.]] + >>> # Larger shape + >>> with tf.compat.v1.Session(): + ... y = tf.compat.v1.get_variable('y', shape=[3, 4], initializer=init) + ... y.initializer.run() + ... print(y.eval()) + [[0. 1. 2. 3.] + [4. 5. 6. 7.] + [7. 7. 7. 7.]] + >>> # Smaller shape + >>> with tf.compat.v1.Session(): + ... z = tf.compat.v1.get_variable('z', shape=[2, 3], initializer=init) + Traceback (most recent call last): + ... + ValueError: Too many elements provided. Needed at most 6, but received 8 + >>> # Shape verification + >>> init_verify = tf.compat.v1.constant_initializer(value, verify_shape=True) + >>> with tf.compat.v1.Session(): + ... u = tf.compat.v1.get_variable('u', shape=[3, 4], + ... initializer=init_verify) + Traceback (most recent call last): + ... + TypeError: Expected Tensor's shape: (3, 4), got (8,). + + @compatibility(TF2) + Although it is a legacy API endpoint, `tf.compat.v1.constant_initializer` + is compatible with eager execution and `tf.function`. + + To migrate to a non-legacy TF2 API, please use `tf.constant_initializer` + instead. The `dtype` + argument in `tf.compat.v1.constant_initializer.__init__()` does not exist in + `tf.constant_initializer.__init__()`. However, you can specify the `dtype` in + `__call__()` in both cases. + + In the `compat.v1` symbol, if `verify_shape` is set to `True`, an exception + is raised when initializing a variable with a different shape from + `value`. If set to `False`, `value` is reshaped to initialize the variable + if necessary. An exception would only be raised when the number of + elements are different. + + The `verify_shape` argument is not supported in TF2. Using + `tf.constant_initializer` is equivalent to setting `verify_shape` to `False`. + + #### Structural Mapping to TF2 + + Before: + + ```python + value = [0, 1, 2, 3, 4, 5, 6, 7] + initializer = tf.compat.v1.constant_initializer( + value=value, + dtype=tf.float32, + verify_shape=False) + variable = tf.Variable(initializer(shape=[2, 4])) + ``` + + After: + + ```python + value = [0, 1, 2, 3, 4, 5, 6, 7] + initializer = tf.constant_initializer(value=value) + tf.Variable(initializer(shape=[2, 4], dtype=tf.float32)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :--------------- | :-------------------------- | + | `value` | `value` | In constructor | + | `dtype` | `dtype` | In `__call__()` method | + | `verify_shape` | Not Supported | Equivalent to set to `False`| + | `partition_info` | - | (`__call__` arg in TF1) Not supported | + + + #### Before & After Usage Example + + Before: + + >>> value = [1., 2., 3., 4.] + >>> initializer = tf.compat.v1.constant_initializer( + ... value=value, dtype=tf.float32, verify_shape=True) + >>> tf.Variable(initializer(shape=[2, 2])).numpy() + Traceback (most recent call last): + ... + TypeError: Expected Tensor's shape: (2, 2), got (4,). + >>> initializer = tf.compat.v1.constant_initializer( + ... value=value, dtype=tf.float32, verify_shape=False) + >>> tf.Variable(initializer(shape=[2, 2])).numpy() + array([[1., 2.], + [3., 4.]], dtype=float32) + + After: + + >>> value = [1., 2., 3., 4.] + >>> initializer = tf.constant_initializer(value=value) + >>> tf.Variable(initializer(shape=[2, 2], dtype=tf.float32)).numpy() + array([[1., 2.], + [3., 4.]], dtype=float32) + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + @deprecated_args(None, "Objects must now be the required shape or no shape " + "can be specified", "verify_shape") + def __init__(self, value=0, dtype=dtypes.float32, verify_shape=False): + if not (np.isscalar(value) or isinstance(value, (list, tuple, np.ndarray))): + raise TypeError( + f"Invalid type for initial value={value} of type: " + f"{type(value).__name__}. Expected Python scalar, list or tuple of " + "values, or numpy.ndarray.") + + self.value = value + self.dtype = dtypes.as_dtype(dtype) + self._verify_shape = verify_shape + + def __call__(self, shape, dtype=None, partition_info=None, verify_shape=None): + if dtype is None: + dtype = self.dtype + if verify_shape is None: + verify_shape = self._verify_shape + return constant_op.constant_v1( + self.value, dtype=dtype, shape=shape, verify_shape=verify_shape) + + def get_config(self): + # We don't include `verify_shape` for compatibility with Keras. + # `verify_shape` should be passed as an argument to `__call__` rather + # than as a constructor argument: conceptually it isn't a property + # of the initializer. + return {"value": self.value, "dtype": self.dtype.name} + + +@tf_export(v1=["initializers.random_uniform", "random_uniform_initializer"]) +@deprecation.deprecated_endpoints("initializers.random_uniform") +class RandomUniform(Initializer): + """Initializer that generates tensors with a uniform distribution. + + Args: + minval: A python scalar or a scalar tensor. Lower bound of the range of + random values to generate. + maxval: A python scalar or a scalar tensor. Upper bound of the range of + random values to generate. Defaults to 1 for float types. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. + + @compatibility(TF2) + Although it is a legacy compat.v1 API, this symbol is compatible with eager + execution and `tf.function`. + + To switch to TF2, switch to using either + `tf.initializers.RandomUniform` or `tf.keras.initializers.RandomUniform` + (neither from `compat.v1`) and + pass the dtype when calling the initializer. Keep in mind that + the default minval, maxval and the behavior of fixed seeds have changed. + + #### Structural Mapping to TF2 + + Before: + + ```python + initializer = tf.compat.v1.random_uniform_initializer( + minval=minval, + maxval=maxval, + seed=seed, + dtype=dtype) + + weight_one = tf.Variable(initializer(shape_one)) + weight_two = tf.Variable(initializer(shape_two)) + ``` + + After: + + ```python + initializer = tf.initializers.RandomUniform( + minval=minval, + maxval=maxval, + seed=seed) + + weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) + weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `minval` | `minval` | Default changes from 0 to -0.05 | + | `maxval` | `maxval` | Default changes from 1.0 to 0.05 | + | `seed` | `seed` | | + | `dtype` | `dtype` | The TF2 native api only takes it | + : : : as a `__call__` arg, not a constructor arg. : + | `partition_info` | - | (`__call__` arg in TF1) Not supported | + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, minval=.0, maxval=None, seed=None, dtype=dtypes.float32): + self.minval = minval + self.maxval = maxval + self.seed = seed + self.dtype = dtypes.as_dtype(dtype) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + return random_ops.random_uniform( + shape, self.minval, self.maxval, dtype, seed=self.seed) + + def get_config(self): + return { + "minval": self.minval, + "maxval": self.maxval, + "seed": self.seed, + "dtype": self.dtype.name + } + + +@tf_export(v1=["initializers.random_normal", "random_normal_initializer"]) +@deprecation.deprecated_endpoints("initializers.random_normal") +class RandomNormal(Initializer): + """Initializer that generates tensors with a normal distribution. + + Args: + mean: a python scalar or a scalar tensor. Mean of the random values to + generate. + stddev: a python scalar or a scalar tensor. Standard deviation of the random + values to generate. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + + @compatibility(TF2) + Although it is a legacy `compat.v1` API, this symbol is compatible with eager + execution and `tf.function`. + + To switch to TF2, switch to using either + `tf.initializers.RandomNormal` or `tf.keras.initializers.RandomNormal` + (neither from `compat.v1`) and + pass the dtype when calling the initializer. Keep in mind that + the default stddev and the behavior of fixed seeds have changed. + + #### Structural Mapping to TF2 + + Before: + + ```python + initializer = tf.compat.v1.random_normal_initializer( + mean=mean, + stddev=stddev, + seed=seed, + dtype=dtype) + + weight_one = tf.Variable(initializer(shape_one)) + weight_two = tf.Variable(initializer(shape_two)) + ``` + + After: + + ```python + initializer = tf.initializers.RandomNormal( + mean=mean, + seed=seed, + stddev=stddev) + + weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) + weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :----------------- | :-------------- | :------------------------- | + | `mean` | `mean` | No change to defaults | + | `stddev` | `stddev` | Default changes from 1.0 to 0.05 | + | `seed` | `seed` | | + | `dtype` | `dtype` | The TF2 native api only takes it as a | + : : : `__call__` arg, not a constructor arg. : + | `partition_info` | - | (`__call__` arg in TF1) Not supported. | + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32): + self.mean = mean + self.stddev = stddev + self.seed = seed + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + return random_ops.random_normal( + shape, self.mean, self.stddev, dtype, seed=self.seed) + + def get_config(self): + return { + "mean": self.mean, + "stddev": self.stddev, + "seed": self.seed, + "dtype": self.dtype.name + } + + +@tf_export(v1=["initializers.truncated_normal", "truncated_normal_initializer"]) +@deprecation.deprecated_endpoints("initializers.truncated_normal", + "truncated_normal_initializer") +class TruncatedNormal(Initializer): + """Initializer that generates a truncated normal distribution. + + These values are similar to values from a `random_normal_initializer` + except that values more than two standard deviations from the mean + are discarded and re-drawn. This is the recommended initializer for + neural network weights and filters. + + Args: + mean: a python scalar or a scalar tensor. Mean of the random values to + generate. + stddev: a python scalar or a scalar tensor. Standard deviation of the random + values to generate. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + + @compatibility(TF2) + Although it is a legacy `compat.v1` API, this symbol is compatible with eager + execution and `tf.function`. + + To switch to TF2, switch to using either + `tf.initializers.truncated_normal` or `tf.keras.initializers.TruncatedNormal` + (neither from `compat.v1`) and + pass the dtype when calling the initializer. Keep in mind that + the default stddev and the behavior of fixed seeds have changed. + + #### Structural Mapping to TF2 + + Before: + + ```python + initializer = tf.compat.v1.truncated_normal_initializer( + mean=mean, + stddev=stddev, + seed=seed, + dtype=dtype) + + weight_one = tf.Variable(initializer(shape_one)) + weight_two = tf.Variable(initializer(shape_two)) + ``` + + After: + + ```python + initializer = tf.initializers.truncated_normal( + mean=mean, + seed=seed, + stddev=stddev) + + weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) + weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `mean` | `mean` | No change to defaults | + | `stddev` | `stddev` | Default changes from 1.0 to 0.05 | + | `seed` | `seed` | | + | `dtype` | `dtype` | The TF2 native api only takes it | + : : : as a `__call__` arg, not a constructor arg. : + | `partition_info` | - | (`__call__` arg in TF1) Not supported | + + @end_compatibility + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32): + self.mean = mean + self.stddev = stddev + self.seed = seed + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + return random_ops.truncated_normal( + shape, self.mean, self.stddev, dtype, seed=self.seed) + + def get_config(self): + return { + "mean": self.mean, + "stddev": self.stddev, + "seed": self.seed, + "dtype": self.dtype.name + } + + +@tf_export(v1=[ + "initializers.uniform_unit_scaling", "uniform_unit_scaling_initializer" +]) +@deprecation.deprecated_endpoints("uniform_unit_scaling_initializer", + "initializers.uniform_unit_scaling") +class UniformUnitScaling(Initializer): + """Initializer that generates tensors without scaling variance. + + When initializing a deep network, it is in principle advantageous to keep + the scale of the input variance constant, so it does not explode or diminish + by reaching the final layer. If the input is `x` and the operation `x * W`, + and we want to initialize `W` uniformly at random, we need to pick `W` from + + [-sqrt(3) / sqrt(dim), sqrt(3) / sqrt(dim)] + + to keep the scale intact, where `dim = W.shape[0]` (the size of the input). + A similar calculation for convolutional networks gives an analogous result + with `dim` equal to the product of the first 3 dimensions. When + nonlinearities are present, we need to multiply this by a constant `factor`. + See (Sussillo et al., 2014) for deeper motivation, experiments + and the calculation of constants. In section 2.3 there, the constants were + numerically computed: for a linear layer it's 1.0, relu: ~1.43, tanh: ~1.15. + + Args: + factor: Float. A multiplicative factor by which the values will be scaled. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Sussillo et al., 2014](https://arxiv.org/abs/1412.6558) + ([pdf](http://arxiv.org/pdf/1412.6558.pdf)) + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + @deprecated(None, + "Use tf.initializers.variance_scaling instead with distribution=" + "uniform to get equivalent behavior.") + def __init__(self, factor=1.0, seed=None, dtype=dtypes.float32): + self.factor = factor + self.seed = seed + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + scale_shape = shape + if partition_info is not None: + scale_shape = partition_info.full_shape + + input_size = 1.0 + # Estimating input size is not possible to do perfectly, but we try. + # The estimate, obtained by multiplying all dimensions but the last one, + # is the right thing for matrix multiply and convolutions (see above). + for dim in scale_shape[:-1]: + input_size *= float(dim) + # Avoid errors when initializing zero-size tensors. + input_size = max(input_size, 1.0) + max_val = math.sqrt(3 / input_size) * self.factor + return random_ops.random_uniform( + shape, -max_val, max_val, dtype, seed=self.seed) + + def get_config(self): + return {"factor": self.factor, "seed": self.seed, "dtype": self.dtype.name} + + +@tf_export(v1=["initializers.variance_scaling", "variance_scaling_initializer"]) +@deprecation.deprecated_endpoints("initializers.variance_scaling", + "variance_scaling_initializer") +class VarianceScaling(Initializer): + """Initializer capable of adapting its scale to the shape of weights tensors. + + @compatibility(TF2) + Although it is a legacy `compat.v1` API, this symbol is compatible with eager + execution and `tf.function`. + + To switch to TF2 APIs, move to using either + `tf.initializers.variance_scaling` or `tf.keras.initializers.VarianceScaling` + (neither from `compat.v1`) and + pass the dtype when calling the initializer. + + #### Structural Mapping to TF2 + + Before: + + ```python + initializer = tf.compat.v1.variance_scaling_initializer( + scale=scale, + mode=mode, + distribution=distribution + seed=seed, + dtype=dtype) + + weight_one = tf.Variable(initializer(shape_one)) + weight_two = tf.Variable(initializer(shape_two)) + ``` + + After: + + ```python + initializer = tf.keras.initializers.VarianceScaling( + scale=scale, + mode=mode, + distribution=distribution + seed=seed) + + weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) + weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :----------------- | :-------------- | :------------------------- | + | `scale` | `scale` | No change to defaults | + | `mode` | `mode` | No change to defaults | + | `distribution` | `distribution` | No change to defaults. | + : : : 'normal' maps to 'truncated_normal' : + | `seed` | `seed` | | + | `dtype` | `dtype` | The TF2 api only takes it | + : : : as a `__call__` arg, not a constructor arg. : + | `partition_info` | - | (`__call__` arg in TF1) Not supported | + + @end_compatibility + + With `distribution="truncated_normal" or "untruncated_normal"`, + samples are drawn from a truncated/untruncated normal + distribution with a mean of zero and a standard deviation (after truncation, + if used) `stddev = sqrt(scale / n)` + where n is: + - number of input units in the weight tensor, if mode = "fan_in" + - number of output units, if mode = "fan_out" + - average of the numbers of input and output units, if mode = "fan_avg" + + With `distribution="uniform"`, samples are drawn from a uniform distribution + within [-limit, limit], with `limit = sqrt(3 * scale / n)`. + + Args: + scale: Scaling factor (positive float). + mode: One of "fan_in", "fan_out", "fan_avg". + distribution: Random distribution to use. One of "normal", "uniform". + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + + Raises: + ValueError: In case of an invalid value for the "scale", mode" or + "distribution" arguments. + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + @deprecated_arg_values( + None, + "`normal` is a deprecated alias for `truncated_normal`", + distribution="normal") + def __init__(self, + scale=1.0, + mode="fan_in", + distribution="truncated_normal", + seed=None, + dtype=dtypes.float32): + if scale <= 0.: + raise ValueError("Argument `scale` must be a positive float. Received: " + f"{scale}") + if mode not in {"fan_in", "fan_out", "fan_avg"}: + raise ValueError("Argument `mode` should be one of ('fan_in', 'fan_out', " + f"'fan_avg'). Received: {mode}") + distribution = distribution.lower() + if distribution not in { + "normal", "uniform", "truncated_normal", "untruncated_normal" + }: + raise ValueError("Argument `distribution` should be one of ('normal', " + "uniform', 'truncated_normal', 'untruncated_normal'). " + f"Received: {distribution}") + self.scale = scale + self.mode = mode + self.distribution = distribution + self.seed = seed + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + scale = self.scale + scale_shape = shape + if partition_info is not None: + scale_shape = partition_info.full_shape + fan_in, fan_out = _compute_fans(scale_shape) + if self.mode == "fan_in": + scale /= max(1., fan_in) + elif self.mode == "fan_out": + scale /= max(1., fan_out) + else: + scale /= max(1., (fan_in + fan_out) / 2.) + if self.distribution == "normal" or self.distribution == "truncated_normal": + # constant taken from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.) + stddev = math.sqrt(scale) / .87962566103423978 + return random_ops.truncated_normal( + shape, 0.0, stddev, dtype, seed=self.seed) + elif self.distribution == "untruncated_normal": + stddev = math.sqrt(scale) + return random_ops.random_normal(shape, 0.0, stddev, dtype, seed=self.seed) + else: + limit = math.sqrt(3.0 * scale) + return random_ops.random_uniform( + shape, -limit, limit, dtype, seed=self.seed) + + def get_config(self): + return { + "scale": self.scale, + "mode": self.mode, + "distribution": self.distribution, + "seed": self.seed, + "dtype": self.dtype.name + } + + +@tf_export(v1=["initializers.orthogonal", "orthogonal_initializer"]) +@deprecation.deprecated_endpoints("initializers.orthogonal", + "orthogonal_initializer") +class Orthogonal(Initializer): + """Initializer that generates an orthogonal matrix. + + If the shape of the tensor to initialize is two-dimensional, it is initialized + with an orthogonal matrix obtained from the QR decomposition of a matrix of + random numbers drawn from a normal distribution. + If the matrix has fewer rows than columns then the output will have orthogonal + rows. Otherwise, the output will have orthogonal columns. + + If the shape of the tensor to initialize is more than two-dimensional, + a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])` + is initialized, where `n` is the length of the shape vector. + The matrix is subsequently reshaped to give a tensor of the desired shape. + + Args: + gain: multiplicative factor to apply to the orthogonal matrix + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) + ([pdf](https://arxiv.org/pdf/1312.6120.pdf)) + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, gain=1.0, seed=None, dtype=dtypes.float32): + self.gain = gain + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + self.seed = seed + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + # Check the shape + if len(shape) < 2: + raise ValueError("The tensor to initialize, specified by argument `shape`" + " must be at least two-dimensional. Received shape=" + f"{shape}") + # Flatten the input shape with the last dimension remaining + # its original shape so it works for conv2d + num_rows = 1 + for dim in shape[:-1]: + num_rows *= dim + num_rows = int(num_rows) + num_cols = int(shape[-1]) + if num_rows < num_cols: + flat_shape = (num_cols, num_rows) + else: + flat_shape = (num_rows, num_cols) + + # Generate a random matrix + a = random_ops.random_normal(flat_shape, dtype=dtype, seed=self.seed) + # Compute the qr factorization + q, r = gen_linalg_ops.qr(a, full_matrices=False) + # Make Q uniform + d = array_ops.diag_part(r) + q *= math_ops.sign(d) + if num_rows < num_cols: + q = array_ops.matrix_transpose(q) + return self.gain * array_ops.reshape(q, shape) + + def get_config(self): + return {"gain": self.gain, "seed": self.seed, "dtype": self.dtype.name} + + +# Note these haven't been ported to TF2.0. They are not currently visible and +# the tests are non trivial to port +class ConvolutionDeltaOrthogonal(Initializer): + """Initializer that generates a delta orthogonal kernel for ConvNets. + + The shape of the tensor must have length 3, 4 or 5. The number of input + filters must not exceed the number of output filters. The center pixels of the + tensor form an orthogonal matrix. Other pixels are set to be zero. See + algorithm 2 in (Xiao et al., 2018). + + + Args: + gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1. + The 2-norm of an input is multiplied by a factor of `gain` after applying + this convolution. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html) + ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf)) + """ + + def __init__(self, gain=1.0, seed=None, dtype=dtypes.float32): + self.gain = gain + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + self.seed = seed + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + # Check the shape + if len(shape) < 3 or len(shape) > 5: + raise ValueError("The tensor to initialize, specified by argument `shape`" + " must be at least three-dimensional and at most " + f"five-dimensional. Received shape={shape}") + + if shape[-2] > shape[-1]: + raise ValueError(f"In_filters, specified by shape[-2]={shape[-2]} cannot " + "be greater than out_filters, specified by " + f"shape[-1]={shape[-1]}.") + + # Generate a random matrix + a = random_ops.random_normal([shape[-1], shape[-1]], + dtype=dtype, + seed=self.seed) + # Compute the qr factorization + q, r = gen_linalg_ops.qr(a, full_matrices=False) + # Make Q uniform + d = array_ops.diag_part(r) + q *= math_ops.sign(d) + q = q[:shape[-2], :] + q *= math_ops.cast(self.gain, dtype=dtype) + if len(shape) == 3: + weight = array_ops.scatter_nd([[(shape[0] - 1) // 2]], + array_ops.expand_dims(q, 0), shape) + elif len(shape) == 4: + weight = array_ops.scatter_nd([[(shape[0] - 1) // 2, + (shape[1] - 1) // 2]], + array_ops.expand_dims(q, 0), shape) + else: + weight = array_ops.scatter_nd([[(shape[0] - 1) // 2, (shape[1] - 1) // 2, + (shape[2] - 1) // 2]], + array_ops.expand_dims(q, 0), shape) + return weight + + def get_config(self): + return {"gain": self.gain, "seed": self.seed, "dtype": self.dtype.name} + + +class ConvolutionOrthogonal(Initializer): + """Initializer that generates orthogonal kernel for ConvNets. + + Base class used to construct 1D, 2D and 3D orthogonal kernels for convolution. + + Args: + gain: multiplicative factor to apply to the orthogonal matrix. Default is 1. + The 2-norm of an input is multiplied by a factor of `gain` after applying + this convolution. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html) + ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf)) + """ + + def __init__(self, gain=1.0, seed=None, dtype=dtypes.float32): + self.gain = gain + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + self.seed = seed + + def __call__(self, shape, dtype=None, partition_info=None): + raise NotImplementedError + + def get_config(self): + return {"gain": self.gain, "seed": self.seed, "dtype": self.dtype.name} + + # Helper functions. + def _orthogonal_matrix(self, n): + """Construct an n x n orthogonal matrix. + + Args: + n: Dimension. + + Returns: + A n x n orthogonal matrix. + """ + a = random_ops.random_normal([n, n], dtype=self.dtype, seed=self.seed) + if self.seed: + self.seed += 1 + q, r = gen_linalg_ops.qr(a) + d = array_ops.diag_part(r) + # make q uniform + q *= math_ops.sign(d) + return q + + def _symmetric_projection(self, n): + """Compute a n x n symmetric projection matrix. + + Args: + n: Dimension. + + Returns: + A n x n symmetric projection matrix, i.e. a matrix P s.t. P=P*P, P=P^T. + """ + q = self._orthogonal_matrix(n) + # randomly zeroing out some columns + mask = math_ops.cast( + random_ops.random_normal([n], seed=self.seed) > 0, self.dtype) + if self.seed: + self.seed += 1 + c = math_ops.multiply(q, mask) + return math_ops.matmul(c, array_ops.matrix_transpose(c)) + + +class ConvolutionOrthogonal2D(ConvolutionOrthogonal): + """Initializer that generates a 2D orthogonal kernel for ConvNets. + + The shape of the tensor must have length 4. The number of input + filters must not exceed the number of output filters. + The orthogonality(==isometry) is exact when the inputs are circular padded. + There are finite-width effects with non-circular padding (e.g. zero padding). + See algorithm 1 in (Xiao et al., 2018). + + Args: + gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1. + This has the effect of scaling the output 2-norm by a factor of `gain`. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html) + ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf)) + """ + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + if len(shape) != 4: + raise ValueError("The tensor to initialize, specified by argument `shape`" + f" must be four-dimensional. Received: {shape}") + + if shape[-2] > shape[-1]: + raise ValueError(f"In_filters, specified by shape[-2]={shape[-2]} cannot " + "be greater than out_filters, specified by " + f"shape[-1]={shape[-1]}.") + + if shape[0] != shape[1]: + raise ValueError(f"Kernel sizes, specified by shape[0]={shape[0]} and " + f"shape[1]={shape[1]} must be equal.") + + kernel = self._orthogonal_kernel(shape[0], shape[2], shape[3]) + kernel *= math_ops.cast(self.gain, dtype=dtype) + return kernel + + def _dict_to_tensor(self, x, k1, k2): + """Convert a dictionary to a tensor. + + Args: + x: A k1 * k2 dictionary. + k1: First dimension of x. + k2: Second dimension of x. + + Returns: + A k1 * k2 tensor. + """ + + return array_ops_stack.stack([ + array_ops_stack.stack([x[i, j] for j in range(k2)]) for i in range(k1)]) + + def _block_orth(self, p1, p2): + """Construct a 2 x 2 kernel. + + Used to construct orthgonal kernel. + + Args: + p1: A symmetric projection matrix. + p2: A symmetric projection matrix. + + Returns: + A 2 x 2 kernel [[p1p2, p1(1-p2)], + [(1-p1)p2, (1-p1)(1-p2)]]. + Raises: + ValueError: If the dimensions of p1 and p2 are different. + """ + if p1.shape.as_list() != p2.shape.as_list(): + raise ValueError("The dimension of the matrices must be the same. " + f"Received p1.shape={p1.shape} and p2.shape={p2.shape}.") + n = p1.shape.as_list()[0] + kernel2x2 = {} + eye = linalg_ops_impl.eye(n, dtype=self.dtype) + kernel2x2[0, 0] = math_ops.matmul(p1, p2) + kernel2x2[0, 1] = math_ops.matmul(p1, (eye - p2)) + kernel2x2[1, 0] = math_ops.matmul((eye - p1), p2) + kernel2x2[1, 1] = math_ops.matmul((eye - p1), (eye - p2)) + + return kernel2x2 + + def _matrix_conv(self, m1, m2): + """Matrix convolution. + + Args: + m1: A k x k dictionary, each element is a n x n matrix. + m2: A l x l dictionary, each element is a n x n matrix. + + Returns: + (k + l - 1) * (k + l - 1) dictionary each element is a n x n matrix. + Raises: + ValueError: if the entries of m1 and m2 are of different dimensions. + """ + + n = (m1[0, 0]).shape.as_list()[0] + if n != (m2[0, 0]).shape.as_list()[0]: + raise ValueError("The entries in matrices m1 and m2 must have the same " + f"dimensions. Received m1[0, 0].shape={m1[0, 0].shape} " + f"and m2[0, 0].shape={m2[0, 0].shape}.") + k = int(np.sqrt(len(m1))) + l = int(np.sqrt(len(m2))) + result = {} + size = k + l - 1 + # Compute matrix convolution between m1 and m2. + for i in range(size): + for j in range(size): + result[i, j] = array_ops.zeros([n, n], self.dtype) + for index1 in range(min(k, i + 1)): + for index2 in range(min(k, j + 1)): + if (i - index1) < l and (j - index2) < l: + result[i, j] += math_ops.matmul(m1[index1, index2], + m2[i - index1, j - index2]) + return result + + def _orthogonal_kernel(self, ksize, cin, cout): + """Construct orthogonal kernel for convolution. + + Args: + ksize: Kernel size. + cin: Number of input channels. + cout: Number of output channels. + + Returns: + An [ksize, ksize, cin, cout] orthogonal kernel. + Raises: + ValueError: If cin > cout. + """ + if cin > cout: + raise ValueError(f"The number of input channels (cin={cin}) cannot exceed" + f" the number of output channels (cout={cout}).") + orth = self._orthogonal_matrix(cout)[0:cin, :] + if ksize == 1: + return array_ops.expand_dims(array_ops.expand_dims(orth, 0), 0) + + p = self._block_orth( + self._symmetric_projection(cout), self._symmetric_projection(cout)) + for _ in range(ksize - 2): + temp = self._block_orth( + self._symmetric_projection(cout), self._symmetric_projection(cout)) + p = self._matrix_conv(p, temp) + for i in range(ksize): + for j in range(ksize): + p[i, j] = math_ops.matmul(orth, p[i, j]) + + return self._dict_to_tensor(p, ksize, ksize) + + +class ConvolutionOrthogonal1D(ConvolutionOrthogonal): + """Initializer that generates a 1D orthogonal kernel for ConvNets. + + The shape of the tensor must have length 3. The number of input + filters must not exceed the number of output filters. + The orthogonality(==isometry) is exact when the inputs are circular padded. + There are finite-width effects with non-circular padding (e.g. zero padding). + See algorithm 1 in (Xiao et al., 2018). + + Args: + gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1. + The 2-norm of an input is multiplied by a factor of `gain` after applying + this convolution. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html) + ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf)) + """ + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + if len(shape) != 3: + raise ValueError("The tensor to initialize, specified by argument `shape`" + f" must be three-dimensional. Received shape={shape}") + + if shape[-2] > shape[-1]: + raise ValueError(f"In_filters, specified by shape[-2]={shape[-2]} cannot " + "be greater than out_filters, specified by " + f"shape[-1]={shape[-1]}.") + + kernel = self._orthogonal_kernel(shape[0], shape[-2], shape[-1]) + kernel *= math_ops.cast(self.gain, dtype=dtype) + return kernel + + def _dict_to_tensor(self, x, k): + """Convert a dictionary to a tensor. + + Args: + x: A dictionary of length k. + k: Dimension of x. + + Returns: + A tensor with the same dimension. + """ + + return array_ops_stack.stack([x[i] for i in range(k)]) + + def _block_orth(self, projection_matrix): + """Construct a kernel. + + Used to construct orthgonal kernel. + + Args: + projection_matrix: A symmetric projection matrix of size n x n. + + Returns: + [projection_matrix, (1 - projection_matrix)]. + """ + n = projection_matrix.shape.as_list()[0] + kernel = {} + eye = linalg_ops_impl.eye(n, dtype=self.dtype) + kernel[0] = projection_matrix + kernel[1] = eye - projection_matrix + return kernel + + def _matrix_conv(self, m1, m2): + """Matrix convolution. + + Args: + m1: A dictionary of length k, each element is a n x n matrix. + m2: A dictionary of length l, each element is a n x n matrix. + + Returns: + (k + l - 1) dictionary each element is a n x n matrix. + Raises: + ValueError: Ff the entries of m1 and m2 are of different dimensions. + """ + + n = (m1[0]).shape.as_list()[0] + if n != (m2[0]).shape.as_list()[0]: + raise ValueError("The entries in matrices m1 and m2 must have the same " + f"dimensions. Received m1[0].shape={m1[0].shape} " + f"and m2[0].shape={m2[0].shape}.") + k = len(m1) + l = len(m2) + result = {} + size = k + l - 1 + # Compute matrix convolution between m1 and m2. + for i in range(size): + result[i] = array_ops.zeros([n, n], self.dtype) + for index in range(min(k, i + 1)): + if (i - index) < l: + result[i] += math_ops.matmul(m1[index], m2[i - index]) + return result + + def _orthogonal_kernel(self, ksize, cin, cout): + """Construct orthogonal kernel for convolution. + + Args: + ksize: Kernel size. + cin: Number of input channels. + cout: Number of output channels. + + Returns: + An [ksize, ksize, cin, cout] orthogonal kernel. + Raises: + ValueError: If cin > cout. + """ + if cin > cout: + raise ValueError(f"The number of input channels (cin={cin}) cannot exceed" + f" the number of output channels (cout={cout}).") + orth = self._orthogonal_matrix(cout)[0:cin, :] + if ksize == 1: + return array_ops.expand_dims(orth, 0) + + p = self._block_orth(self._symmetric_projection(cout)) + for _ in range(ksize - 2): + temp = self._block_orth(self._symmetric_projection(cout)) + p = self._matrix_conv(p, temp) + for i in range(ksize): + p[i] = math_ops.matmul(orth, p[i]) + + return self._dict_to_tensor(p, ksize) + + +class ConvolutionOrthogonal3D(ConvolutionOrthogonal): + """Initializer that generates a 3D orthogonal kernel for ConvNets. + + The shape of the tensor must have length 5. The number of input + filters must not exceed the number of output filters. + The orthogonality(==isometry) is exact when the inputs are circular padded. + There are finite-width effects with non-circular padding (e.g. zero padding). + See algorithm 1 (Xiao et al., 2018). + + Args: + gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1. + The 2-norm of an input is multiplied by a factor of `gain` after applying + this convolution. + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html) + ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf)) + """ + + def __call__(self, shape, dtype=None, partition_info=None): + if dtype is None: + dtype = self.dtype + if len(shape) != 5: + raise ValueError("The tensor to initialize, specified by argument `shape`" + f" must be five-dimensional. Received shape={shape}") + + if shape[-2] > shape[-1]: + raise ValueError(f"In_filters, specified by shape[-2]={shape[-2]} cannot " + "be greater than out_filters, specified by " + f"shape[-1]={shape[-1]}.") + + if shape[0] != shape[1] or shape[0] != shape[2]: + raise ValueError(f"Kernel sizes, specified by shape[0]={shape[0]}, " + f"shape[1]={shape[1]} and shape[2]={shape[2]} must be " + "equal.") + + kernel = self._orthogonal_kernel(shape[0], shape[-2], shape[-1]) + kernel *= math_ops.cast(self.gain, dtype=dtype) + return kernel + + def _dict_to_tensor(self, x, k1, k2, k3): + """Convert a dictionary to a tensor. + + Args: + x: A k1 * k2 dictionary. + k1: First dimension of x. + k2: Second dimension of x. + k3: Third dimension of x. + + Returns: + A k1 * k2 * k3 tensor. + """ + + return array_ops_stack.stack([array_ops_stack.stack( + [array_ops_stack.stack([x[i, j, k] for k in range(k3)]) + for j in range(k2)]) for i in range(k1)]) + + def _block_orth(self, p1, p2, p3): + """Construct a 3 x 3 kernel. + + Used to construct orthgonal kernel. + + Args: + p1: A symmetric projection matrix. + p2: A symmetric projection matrix. + p3: A symmetric projection matrix. + + Returns: + A 2 x 2 x 2 kernel. + Raises: + ValueError: If the dimensions of p1, p2 and p3 are different. + """ + p1_shape = p1.shape.as_list() + if p1_shape != p2.shape.as_list() or p1_shape != p3.shape.as_list(): + raise ValueError("The dimension of the matrices must be the same. " + f"Received p1.shape={p1.shape}, p2.shape={p2.shape} and" + f" p3.shape={p3.shape}.") + n = p1_shape[0] + eye = linalg_ops_impl.eye(n, dtype=self.dtype) + kernel2x2x2 = {} + + def matmul(p1, p2, p3): + return math_ops.matmul(math_ops.matmul(p1, p2), p3) + + def cast(i, p): + """Return p or (1-p).""" + return i * p + (1 - i) * (eye - p) + + for i in [0, 1]: + for j in [0, 1]: + for k in [0, 1]: + kernel2x2x2[i, j, k] = matmul(cast(i, p1), cast(j, p2), cast(k, p3)) + return kernel2x2x2 + + def _matrix_conv(self, m1, m2): + """Matrix convolution. + + Args: + m1: is a k x k x k dictionary, each element is a n x n matrix. + m2: is a l x l x l dictionary, each element is a n x n matrix. + + Returns: + (k + l - 1) x (k + l - 1) x (k + l - 1) dictionary each + element is a n x n matrix. + Raises: + ValueError: if the entries of m1 and m2 are of different dimensions. + """ + + n = (m1[0, 0, 0]).shape.as_list()[0] + if n != (m2[0, 0, 0]).shape.as_list()[0]: + raise ValueError("The entries in matrices m1 and m2 must have the same " + "dimensions. Received m1[0, 0, 0].shape=" + f"{m1[0, 0, 0].shape} and m2[0, 0, 0].shape=" + f"{m2[0, 0, 0].shape}.") + k = int(np.cbrt(len(m1))) + l = int(np.cbrt(len(m2))) + result = {} + size = k + l - 1 + # Compute matrix convolution between m1 and m2. + for i in range(size): + for j in range(size): + for r in range(size): + result[i, j, r] = array_ops.zeros([n, n], self.dtype) + for index1 in range(min(k, i + 1)): + for index2 in range(min(k, j + 1)): + for index3 in range(min(k, r + 1)): + if (i - index1) < l and (j - index2) < l and (r - index3) < l: + result[i, j, r] += math_ops.matmul( + m1[index1, index2, index3], + m2[i - index1, j - index2, r - index3]) + return result + + def _orthogonal_kernel(self, ksize, cin, cout): + """Construct orthogonal kernel for convolution. + + Args: + ksize: Kernel size. + cin: Number of input channels. + cout: Number of output channels. + + Returns: + An [ksize, ksize, ksize, cin, cout] orthogonal kernel. + Raises: + ValueError: If cin > cout. + """ + if cin > cout: + raise ValueError(f"The number of input channels (cin={cin}) cannot exceed" + f" the number of output channels (cout={cout}).") + orth = self._orthogonal_matrix(cout)[0:cin, :] + if ksize == 1: + return array_ops.expand_dims( + array_ops.expand_dims(array_ops.expand_dims(orth, 0), 0), 0) + + p = self._block_orth( + self._symmetric_projection(cout), self._symmetric_projection(cout), + self._symmetric_projection(cout)) + for _ in range(ksize - 2): + temp = self._block_orth( + self._symmetric_projection(cout), self._symmetric_projection(cout), + self._symmetric_projection(cout)) + p = self._matrix_conv(p, temp) + for i in range(ksize): + for j in range(ksize): + for k in range(ksize): + p[i, j, k] = math_ops.matmul(orth, p[i, j, k]) + + return self._dict_to_tensor(p, ksize, ksize, ksize) + + +@tf_export(v1=["initializers.identity"]) +@deprecation.deprecated_endpoints("initializers.identity") +class Identity(Initializer): + """Initializer that generates the identity matrix. + + Only use for 2D matrices. + + Args: + gain: Multiplicative factor to apply to the identity matrix. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, gain=1.0, dtype=dtypes.float32): + self.gain = gain + self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype)) + + def __call__(self, shape, dtype=None, partition_info=None): + full_shape = shape if partition_info is None else partition_info.full_shape + if len(full_shape) != 2: + raise ValueError("The tensor to initialize, specified by argument `shape`" + " must be at least two-dimensional. Received shape=" + f"{shape}") + if dtype is None: + dtype = self.dtype + if isinstance(full_shape, tensor_shape.TensorShape): + full_shape = full_shape.as_list() + initializer = linalg_ops_impl.eye(*full_shape, dtype=dtype) + if partition_info is not None: + initializer = array_ops.slice(initializer, partition_info.var_offset, + shape) + return self.gain * initializer + + def get_config(self): + return {"gain": self.gain, "dtype": self.dtype.name} + + +@tf_export(v1=["glorot_uniform_initializer", "initializers.glorot_uniform"]) +@deprecation.deprecated_endpoints("glorot_uniform_initializer", + "initializers.glorot_uniform") +class GlorotUniform(VarianceScaling): + """The Glorot uniform initializer, also called Xavier uniform initializer. + + It draws samples from a uniform distribution within [-limit, limit] + where `limit` is `sqrt(6 / (fan_in + fan_out))` + where `fan_in` is the number of input units in the weight tensor + and `fan_out` is the number of output units in the weight tensor. + + Args: + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) + ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, seed=None, dtype=dtypes.float32): + super(GlorotUniform, self).__init__( + scale=1.0, mode="fan_avg", distribution="uniform", seed=seed) + + def get_config(self): + return {"seed": self.seed, "dtype": self.dtype.name} + + +@tf_export(v1=["glorot_normal_initializer", "initializers.glorot_normal"]) +@deprecation.deprecated_endpoints("glorot_normal_initializer", + "initializers.glorot_normal") +class GlorotNormal(VarianceScaling): + """The Glorot normal initializer, also called Xavier normal initializer. + + It draws samples from a truncated normal distribution centered on 0 + with standard deviation (after truncation) given by + `stddev = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number + of input units in the weight tensor and `fan_out` is the number of + output units in the weight tensor. + + Args: + seed: A Python integer. Used to create random seeds. See + `tf.compat.v1.set_random_seed` for behavior. + dtype: Default data type, used if no `dtype` argument is provided when + calling the initializer. Only floating point types are supported. + References: + [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) + ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) + """ + + @deprecated_args(None, + "Call initializer instance with the dtype argument instead " + "of passing it to the constructor", "dtype") + def __init__(self, seed=None, dtype=dtypes.float32): + super(GlorotNormal, self).__init__( + scale=1.0, mode="fan_avg", distribution="truncated_normal", seed=seed) + + def get_config(self): + return {"seed": self.seed, "dtype": self.dtype.name} + + +# Aliases. + +# pylint: disable=invalid-name +zeros_initializer = Zeros +ones_initializer = Ones +constant_initializer = Constant +random_uniform_initializer = RandomUniform +random_normal_initializer = RandomNormal +truncated_normal_initializer = TruncatedNormal +uniform_unit_scaling_initializer = UniformUnitScaling +variance_scaling_initializer = VarianceScaling +glorot_uniform_initializer = GlorotUniform +glorot_normal_initializer = GlorotNormal +orthogonal_initializer = Orthogonal +identity_initializer = Identity +convolutional_delta_orthogonal = ConvolutionDeltaOrthogonal +convolutional_orthogonal_1d = ConvolutionOrthogonal1D +convolutional_orthogonal_2d = ConvolutionOrthogonal2D +convolutional_orthogonal_3d = ConvolutionOrthogonal3D +# pylint: enable=invalid-name + + +@tf_export(v1=["initializers.lecun_normal"]) +def lecun_normal(seed=None): + """LeCun normal initializer. + + It draws samples from a truncated normal distribution centered on 0 + with standard deviation (after truncation) given by + `stddev = sqrt(1 / fan_in)` where `fan_in` is the number of + input units in the weight tensor. + + Args: + seed: A Python integer. Used to seed the random generator. + + Returns: + An initializer. + + References: + - Self-Normalizing Neural Networks, + [Klambauer et al., + 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) + # pylint: disable=line-too-long + ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) + - Efficient Backprop, + [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) + """ + return VarianceScaling( + scale=1., mode="fan_in", distribution="truncated_normal", seed=seed) + + +@tf_export(v1=["initializers.lecun_uniform"]) +def lecun_uniform(seed=None): + """LeCun uniform initializer. + + It draws samples from a uniform distribution within [-limit, limit] + where `limit` is `sqrt(3 / fan_in)` + where `fan_in` is the number of input units in the weight tensor. + + Args: + seed: A Python integer. Used to seed the random generator. + + Returns: + An initializer. + + References: + - Self-Normalizing Neural Networks, + [Klambauer et al., + 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) + # pylint: disable=line-too-long + ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) + - Efficient Backprop, + [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) + """ + return VarianceScaling( + scale=1., mode="fan_in", distribution="uniform", seed=seed) + + +@tf_export(v1=["initializers.he_normal"]) +def he_normal(seed=None): + """He normal initializer. + + It draws samples from a truncated normal distribution centered on 0 + with standard deviation (after truncation) given by + `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of + input units in the weight tensor. + + Args: + seed: A Python integer. Used to seed the random generator. + + Returns: + An initializer. + + References: + [He et al., 2015] + (https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) + # pylint: disable=line-too-long + ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) + """ + return VarianceScaling( + scale=2., mode="fan_in", distribution="truncated_normal", seed=seed) + + +@tf_export(v1=["initializers.he_uniform"]) +def he_uniform(seed=None): + """He uniform variance scaling initializer. + + It draws samples from a uniform distribution within [-limit, limit] + where `limit` is `sqrt(6 / fan_in)` + where `fan_in` is the number of input units in the weight tensor. + + Args: + seed: A Python integer. Used to seed the random generator. + + Returns: + An initializer. + + References: + [He et al., 2015] + (https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) + # pylint: disable=line-too-long + ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) + """ + return VarianceScaling( + scale=2., mode="fan_in", distribution="uniform", seed=seed) + + +# Utility functions. + + +def _compute_fans(shape): + """Computes the number of input and output units for a weight shape. + + Args: + shape: Integer shape tuple or TF tensor shape. + + Returns: + A tuple of integer scalars (fan_in, fan_out). + """ + if len(shape) < 1: # Just to avoid errors for constants. + fan_in = fan_out = 1 + elif len(shape) == 1: + fan_in = fan_out = shape[0] + elif len(shape) == 2: + fan_in = shape[0] + fan_out = shape[1] + else: + # Assuming convolution kernels (2D, 3D, or more). + # kernel shape: (..., input_depth, depth) + receptive_field_size = 1 + for dim in shape[:-2]: + receptive_field_size *= dim + fan_in = shape[-2] * receptive_field_size + fan_out = shape[-1] * receptive_field_size + return int(fan_in), int(fan_out) + + +def _assert_float_dtype(dtype): + """Validate and return floating point type based on `dtype`. + + `dtype` must be a floating point type. + + Args: + dtype: The data type to validate. + + Returns: + Validated type. + + Raises: + ValueError: if `dtype` is not a floating point type. + """ + if not dtype.is_floating: + raise ValueError("Argument `dtype` is expected to be floating point. " + f"Received: {dtype}.") + return dtype diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..7de7e80d89be1278504d9591a50359d095309f12 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/init_ops_v2.py @@ -0,0 +1,1119 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Initializers for TF 2.""" +import math + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.ops.init_ops import _compute_fans +from tensorflow.python.util.tf_export import tf_export + +_PARTITION_SHAPE = "partition_shape" +_PARTITION_OFFSET = "partition_offset" + + +class Initializer: + """Initializer base class: all initializers inherit from this class. + + Initializers should implement a `__call__` method with the following + signature: + + ```python + def __call__(self, shape, dtype=None, **kwargs): + # returns a tensor of shape `shape` and dtype `dtype` + # containing values drawn from a distribution of your choice. + ``` + """ + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. If not provided will return tensor + of `tf.float32`. + **kwargs: Additional keyword arguments. Accepted values: + `partition_shape` and `partition_offset`. Used when creating a single + partition in a partitioned variable. `partition_shape` is the shape of + the partition (i.e. the shape of the returned tensor) and + `partition_offset` is a tuple of `int` specifying the offset of this + partition w.r.t each axis. For example, a tensor of shape `(30, 100)` + can be partitioned into two partitions: `p0` of shape `(10, 100)` and + `p1` of shape `(20, 100)`; if the initializer is called with + `partition_shape=(20, 100)` and `partition_offset=(10, 0)`, it should + return the value for `p1`. + """ + raise NotImplementedError + + def get_config(self): + """Returns the configuration of the initializer as a JSON-serializable dict. + + Returns: + A JSON-serializable Python dict. + """ + return {} + + @classmethod + def from_config(cls, config): + """Instantiates an initializer from a configuration dictionary. + + Example: + + ```python + initializer = RandomUniform(-1, 1) + config = initializer.get_config() + initializer = RandomUniform.from_config(config) + ``` + + Args: + config: A Python dictionary. + It will typically be the output of `get_config`. + + Returns: + An Initializer instance. + """ + config.pop("dtype", None) + return cls(**config) + + def _validate_kwargs(self, kwargs, support_partition=True): + for kwarg in kwargs: + if kwarg not in [_PARTITION_SHAPE, _PARTITION_OFFSET]: + raise TypeError( + "Keyword argument should be one of " + f"{list([_PARTITION_SHAPE, _PARTITION_OFFSET])}. Received: {kwarg}") + elif not support_partition: + raise ValueError( + f"{self.__class__.__name__} initializer doesn't support " + "partition-related arguments") + + +@tf_export("zeros_initializer", v1=[]) +class Zeros(Initializer): + """Initializer that generates tensors initialized to 0. + + Initializers allow you to pre-specify an initialization strategy, encoded in + the Initializer object, without knowing the shape and dtype of the variable + being initialized. + + Examples: + + >>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.zeros_initializer()) + >>> v1 + + >>> v2 + + >>> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.ones_initializer()) + >>> v1 + + >>> v2 + + >>> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.constant_initializer(2.)) + >>> v1 + + >>> v2 + + >>> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) + (, >> value = [0, 1, 2, 3, 4, 5, 6, 7] + >>> init = tf.constant_initializer(value) + >>> # Fitting shape + >>> tf.Variable(init(shape=[2, 4], dtype=tf.float32)) + + >>> # Larger shape + >>> tf.Variable(init(shape=[3, 4], dtype=tf.float32)) + Traceback (most recent call last): + ... + TypeError: ...value has 8 elements, shape is (3, 4) with 12 elements... + >>> # Smaller shape + >>> tf.Variable(init(shape=[2, 3], dtype=tf.float32)) + Traceback (most recent call last): + ... + TypeError: ...value has 8 elements, shape is (2, 3) with 6 elements... + + Args: + value: A Python scalar, list or tuple of values, or a N-dimensional numpy + array. All elements of the initialized variable will be set to the + corresponding value in the `value` argument. + support_partition: If true, the initizer supports passing partition + offset and partition shape arguments to variable creators. This is + particularly useful when initializing sharded variables where each + variable shard is initialized to a slice of constant initializer. + + Raises: + TypeError: If the input `value` is not one of the expected types. + """ + + def __init__(self, value=0, support_partition=False): + if not (np.isscalar(value) or isinstance(value, (list, tuple, np.ndarray))): + raise TypeError( + f"Invalid type for initial value: {type(value).__name__}. Expected " + "Python scalar, list or tuple of values, or numpy.ndarray.") + self.value = value + self.support_partition = support_partition + + def __call__(self, shape, dtype=None, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. If not provided the dtype of the + tensor created will be the type of the inital value. + **kwargs: Additional keyword arguments. + + Raises: + TypeError: If the initializer cannot create a tensor of the requested + dtype. + """ + self._validate_kwargs(kwargs, support_partition=self.support_partition) + if dtype is not None: + dtype = dtypes.as_dtype(dtype) + return constant_op.constant(self.value, dtype=dtype, shape=shape) + + def get_config(self): + return {"value": self.value} + + +@tf_export("random_uniform_initializer", v1=[]) +class RandomUniform(Initializer): + """Initializer that generates tensors with a uniform distribution. + + Initializers allow you to pre-specify an initialization strategy, encoded in + the Initializer object, without knowing the shape and dtype of the variable + being initialized. + + Examples: + + >>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.ones_initializer()) + >>> v1 + + >>> v2 + + >>> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, + ... tf.random_normal_initializer(mean=1., stddev=2.)) + >>> v1 + + >>> v2 + >> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables( + ... 3, tf.initializers.TruncatedNormal(mean=1., stddev=2.)) + >>> v1 + + >>> v2 + >> make_variables(4, tf.initializers.RandomUniform(minval=-1., maxval=1.)) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.VarianceScaling(scale=1.)) + >>> v1 + + >>> v2 + >> make_variables(4, tf.initializers.VarianceScaling(distribution='uniform')) + (, >> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.Orthogonal()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.Orthogonal(gain=0.5)) + (>> def make_variable(k, initializer): + ... return tf.Variable(initializer(shape=[k, k], dtype=tf.float32)) + >>> make_variable(2, tf.initializers.Identity()) + + >>> make_variable(3, tf.initializers.Identity(gain=0.5)) + + + Args: + gain: Multiplicative factor to apply to the identity matrix. + """ + + def __init__(self, gain=1.0): + self.gain = gain + + def __call__(self, shape, dtype=dtypes.float32, **kwargs): + """Returns a tensor object initialized as specified by the initializer. + + Args: + shape: Shape of the tensor. + dtype: Optional dtype of the tensor. Only floating point types are + supported. + **kwargs: Additional keyword arguments. + + Raises: + ValueError: If the dtype is not floating point + ValueError: If the requested shape does not have exactly two axes. + """ + self._validate_kwargs(kwargs, support_partition=False) + dtype = _assert_float_dtype(dtype) + if len(shape) != 2: + raise ValueError("The tensor to initialize, specified by argument `shape`" + " must be at least two-dimensional. Received shape=" + f"{shape}") + initializer = linalg_ops_impl.eye(*shape, dtype=dtype) + return self.gain * initializer + + def get_config(self): + return {"gain": self.gain} + + +class GlorotUniform(VarianceScaling): + """The Glorot uniform initializer, also called Xavier uniform initializer. + + Initializers allow you to pre-specify an initialization strategy, encoded in + the Initializer object, without knowing the shape and dtype of the variable + being initialized. + + Draws samples from a uniform distribution within [-limit, limit] where `limit` + is `sqrt(6 / (fan_in + fan_out))` where `fan_in` is the number of input units + in the weight tensor and `fan_out` is the number of output units in the weight + tensor. + + Examples: + + >>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.GlorotUniform()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.GlorotNormal()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.lecun_normal()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.lecun_uniform()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.he_normal()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> def make_variables(k, initializer): + ... return (tf.Variable(initializer(shape=[k, k], dtype=tf.float32)), + ... tf.Variable(initializer(shape=[k, k, k], dtype=tf.float32))) + >>> v1, v2 = make_variables(3, tf.initializers.he_uniform()) + >>> v1 + >> v2 + >> make_variables(4, tf.initializers.RandomNormal()) + (>> with open("/tmp/file.txt", "w") as f: + ... f.write("asdf") + ... + 4 + >>> tf.io.read_file("/tmp/file.txt") + + + Example of using the op in a function to read an image, decode it and reshape + the tensor containing the pixel data: + + >>> @tf.function + ... def load_image(filename): + ... raw = tf.io.read_file(filename) + ... image = tf.image.decode_png(raw, channels=3) + ... # the `print` executes during tracing. + ... print("Initial shape: ", image.shape) + ... image.set_shape([28, 28, 3]) + ... print("Final shape: ", image.shape) + ... return image + + Args: + filename: string. filename to read from. + name: string. Optional name for the op. + + Returns: + A tensor of dtype "string", with the file contents. + """ + return gen_io_ops.read_file(filename, name) + + +@tf_export( + "io.serialize_tensor", v1=["io.serialize_tensor", "serialize_tensor"]) +def serialize_tensor(tensor, name=None): + r"""Transforms a Tensor into a serialized TensorProto proto. + + This operation transforms data in a `tf.Tensor` into a `tf.Tensor` of type + `tf.string` containing the data in a binary string in little-endian format. + This operation can transform scalar data and linear arrays, but it is most + useful in converting multidimensional arrays into a format accepted by binary + storage formats such as a `TFRecord` or `tf.train.Example`. + + See also: + - `tf.io.parse_tensor`: inverse operation of `tf.io.serialize_tensor` that + transforms a scalar string containing a serialized Tensor in little-endian + format into a Tensor of a specified type. + - `tf.ensure_shape`: `parse_tensor` cannot statically determine the shape of + the parsed tensor. Use `tf.ensure_shape` to set the static shape when running + under a `tf.function` + - `.SerializeToString`, serializes a proto to a binary-string + + Example of serializing scalar data: + + >>> t = tf.constant(1) + >>> tf.io.serialize_tensor(t) + + + Example of storing non-scalar data into a `tf.train.Example`: + + >>> t1 = [[1, 2]] + >>> t2 = [[7, 8]] + >>> nonscalar = tf.concat([t1, t2], 0) + >>> nonscalar + + + Serialize the data using `tf.io.serialize_tensor`. + + >>> serialized_nonscalar = tf.io.serialize_tensor(nonscalar) + >>> serialized_nonscalar + + + Store the data in a `tf.train.Feature`. + + >>> feature_of_bytes = tf.train.Feature( + ... bytes_list=tf.train.BytesList(value=[serialized_nonscalar.numpy()])) + >>> feature_of_bytes + bytes_list { + value: "\010...\000" + } + + Put the `tf.train.Feature` message into a `tf.train.Example`. + + >>> features_for_example = { + ... 'feature0': feature_of_bytes + ... } + >>> example_proto = tf.train.Example( + ... features=tf.train.Features(feature=features_for_example)) + >>> example_proto + features { + feature { + key: "feature0" + value { + bytes_list { + value: "\010...\000" + } + } + } + } + + Args: + tensor: A `tf.Tensor`. + name: string. Optional name for the op. + + Returns: + A Tensor of dtype string. + """ + return gen_parsing_ops.serialize_tensor(tensor, name) + + +@tf_export(v1=["ReaderBase"]) +class ReaderBase: + """Base class for different Reader types, that produce a record every step. + + Conceptually, Readers convert string 'work units' into records (key, + value pairs). Typically the 'work units' are filenames and the + records are extracted from the contents of those files. We want a + single record produced per step, but a work unit can correspond to + many records. + + Therefore we introduce some decoupling using a queue. The queue + contains the work units and the Reader dequeues from the queue when + it is asked to produce a record (via Read()) but it has finished the + last work unit. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + + def __init__(self, reader_ref, supports_serialize=False): + """Creates a new ReaderBase. + + Args: + reader_ref: The operation that implements the reader. + supports_serialize: True if the reader implementation can + serialize its state. + + Raises: + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError( + "Readers are not supported when eager execution is enabled. " + "Instead, please use tf.data to get data into your model.") + + self._reader_ref = reader_ref + self._supports_serialize = supports_serialize + + @property + def reader_ref(self): + """Op that implements the reader.""" + return self._reader_ref + + def read(self, queue, name=None): + """Returns the next record (key, value) pair produced by a reader. + + Will dequeue a work unit from queue if necessary (e.g. when the + Reader needs to start reading from a new file since it has + finished with the previous file). + + Args: + queue: A Queue or a mutable string Tensor representing a handle + to a Queue, with string work items. + name: A name for the operation (optional). + + Returns: + A tuple of Tensors (key, value). + key: A string scalar Tensor. + value: A string scalar Tensor. + """ + if isinstance(queue, tensor_lib.Tensor): + queue_ref = queue + else: + queue_ref = queue.queue_ref + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_read_v2(self._reader_ref, queue_ref, name=name) + else: + # For compatibility with pre-resource queues, create a ref(string) tensor + # which can be looked up as the same queue by a resource manager. + old_queue_op = gen_data_flow_ops.fake_queue(queue_ref) + return gen_io_ops.reader_read(self._reader_ref, old_queue_op, name=name) + + def read_up_to(self, queue, num_records, # pylint: disable=invalid-name + name=None): + """Returns up to num_records (key, value) pairs produced by a reader. + + Will dequeue a work unit from queue if necessary (e.g., when the + Reader needs to start reading from a new file since it has + finished with the previous file). + It may return less than num_records even before the last batch. + + Args: + queue: A Queue or a mutable string Tensor representing a handle + to a Queue, with string work items. + num_records: Number of records to read. + name: A name for the operation (optional). + + Returns: + A tuple of Tensors (keys, values). + keys: A 1-D string Tensor. + values: A 1-D string Tensor. + """ + if isinstance(queue, tensor_lib.Tensor): + queue_ref = queue + else: + queue_ref = queue.queue_ref + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_read_up_to_v2(self._reader_ref, + queue_ref, + num_records, + name=name) + else: + # For compatibility with pre-resource queues, create a ref(string) tensor + # which can be looked up as the same queue by a resource manager. + old_queue_op = gen_data_flow_ops.fake_queue(queue_ref) + return gen_io_ops.reader_read_up_to(self._reader_ref, + old_queue_op, + num_records, + name=name) + + def num_records_produced(self, name=None): + """Returns the number of records this reader has produced. + + This is the same as the number of Read executions that have + succeeded. + + Args: + name: A name for the operation (optional). + + Returns: + An int64 Tensor. + + """ + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_num_records_produced_v2(self._reader_ref, + name=name) + else: + return gen_io_ops.reader_num_records_produced(self._reader_ref, + name=name) + + def num_work_units_completed(self, name=None): + """Returns the number of work units this reader has finished processing. + + Args: + name: A name for the operation (optional). + + Returns: + An int64 Tensor. + """ + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_num_work_units_completed_v2(self._reader_ref, + name=name) + else: + return gen_io_ops.reader_num_work_units_completed(self._reader_ref, + name=name) + + def serialize_state(self, name=None): + """Produce a string tensor that encodes the state of a reader. + + Not all Readers support being serialized, so this can produce an + Unimplemented error. + + Args: + name: A name for the operation (optional). + + Returns: + A string Tensor. + """ + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_serialize_state_v2(self._reader_ref, name=name) + else: + return gen_io_ops.reader_serialize_state(self._reader_ref, name=name) + + def restore_state(self, state, name=None): + """Restore a reader to a previously saved state. + + Not all Readers support being restored, so this can produce an + Unimplemented error. + + Args: + state: A string Tensor. + Result of a SerializeState of a Reader with matching type. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_restore_state_v2( + self._reader_ref, state, name=name) + else: + return gen_io_ops.reader_restore_state(self._reader_ref, state, name=name) + + @property + def supports_serialize(self): + """Whether the Reader implementation can serialize its state.""" + return self._supports_serialize + + def reset(self, name=None): + """Restore a reader to its initial clean state. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + if self._reader_ref.dtype == dtypes.resource: + return gen_io_ops.reader_reset_v2(self._reader_ref, name=name) + else: + return gen_io_ops.reader_reset(self._reader_ref, name=name) + + +ops.NotDifferentiable("ReaderRead") +ops.NotDifferentiable("ReaderReadUpTo") +ops.NotDifferentiable("ReaderNumRecordsProduced") +ops.NotDifferentiable("ReaderNumWorkUnitsCompleted") +ops.NotDifferentiable("ReaderSerializeState") +ops.NotDifferentiable("ReaderRestoreState") +ops.NotDifferentiable("ReaderReset") + + +@tf_export(v1=["WholeFileReader"]) +class WholeFileReader(ReaderBase): + """A Reader that outputs the entire contents of a file as a value. + + To use, enqueue filenames in a Queue. The output of Read will + be a filename (key) and the contents of that file (value). + + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.map(tf.read_file)`.") + def __init__(self, name=None): + """Create a WholeFileReader. + + Args: + name: A name for the operation (optional). + """ + rr = gen_io_ops.whole_file_reader_v2(name=name) + super(WholeFileReader, self).__init__(rr, supports_serialize=True) + + +ops.NotDifferentiable("WholeFileReader") + + +@tf_export(v1=["TextLineReader"]) +class TextLineReader(ReaderBase): + """A Reader that outputs the lines of a file delimited by newlines. + + Newlines are stripped from the output. + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + # TODO(josh11b): Support serializing and restoring state. + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.TextLineDataset`.") + def __init__(self, skip_header_lines=None, name=None): + """Create a TextLineReader. + + Args: + skip_header_lines: An optional int. Defaults to 0. Number of lines + to skip from the beginning of every file. + name: A name for the operation (optional). + """ + rr = gen_io_ops.text_line_reader_v2(skip_header_lines=skip_header_lines, + name=name) + super(TextLineReader, self).__init__(rr) + + +ops.NotDifferentiable("TextLineReader") + + +@tf_export(v1=["FixedLengthRecordReader"]) +class FixedLengthRecordReader(ReaderBase): + """A Reader that outputs fixed-length records from a file. + + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + # TODO(josh11b): Support serializing and restoring state. + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.FixedLengthRecordDataset`.") + def __init__(self, + record_bytes, + header_bytes=None, + footer_bytes=None, + hop_bytes=None, + name=None, + encoding=None): + """Create a FixedLengthRecordReader. + + Args: + record_bytes: An int. + header_bytes: An optional int. Defaults to 0. + footer_bytes: An optional int. Defaults to 0. + hop_bytes: An optional int. Defaults to 0. + name: A name for the operation (optional). + encoding: The type of encoding for the file. Defaults to none. + """ + rr = gen_io_ops.fixed_length_record_reader_v2( + record_bytes=record_bytes, + header_bytes=header_bytes, + footer_bytes=footer_bytes, + hop_bytes=hop_bytes, + encoding=encoding, + name=name) + super(FixedLengthRecordReader, self).__init__(rr) + + +ops.NotDifferentiable("FixedLengthRecordReader") + + +@tf_export(v1=["TFRecordReader"]) +class TFRecordReader(ReaderBase): + """A Reader that outputs the records from a TFRecords file. + + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + # TODO(josh11b): Support serializing and restoring state. + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.TFRecordDataset`.") + def __init__(self, name=None, options=None): + """Create a TFRecordReader. + + Args: + name: A name for the operation (optional). + options: A TFRecordOptions object (optional). + """ + compression_type = python_io.TFRecordOptions.get_compression_type_string( + options) + + rr = gen_io_ops.tf_record_reader_v2( + name=name, compression_type=compression_type) + super(TFRecordReader, self).__init__(rr) + + +ops.NotDifferentiable("TFRecordReader") + + +@tf_export(v1=["LMDBReader"]) +class LMDBReader(ReaderBase): + """A Reader that outputs the records from a LMDB file. + + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.contrib.data.LMDBDataset`.") + def __init__(self, name=None, options=None): + """Create a LMDBReader. + + Args: + name: A name for the operation (optional). + options: A LMDBRecordOptions object (optional). + """ + del options + rr = gen_io_ops.lmdb_reader(name=name) + super(LMDBReader, self).__init__(rr) + + +ops.NotDifferentiable("LMDBReader") + + +@tf_export(v1=["IdentityReader"]) +class IdentityReader(ReaderBase): + """A Reader that outputs the queued work as both the key and value. + + To use, enqueue strings in a Queue. Read will take the front + work string and output (work, work). + + See ReaderBase for supported methods. + + @compatibility(eager) + Readers are not compatible with eager execution. Instead, please + use `tf.data` to get data into your model. + @end_compatibility + """ + + @deprecation.deprecated( + None, "Queue-based input pipelines have been replaced by `tf.data`. Use " + "`tf.data.Dataset.map(...)`.") + def __init__(self, name=None): + """Create a IdentityReader. + + Args: + name: A name for the operation (optional). + """ + rr = gen_io_ops.identity_reader_v2(name=name) + super(IdentityReader, self).__init__(rr, supports_serialize=True) + + +ops.NotDifferentiable("IdentityReader") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..057a4cc30cc582db9dbac5aa6dcdae53ad74aab4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg.py @@ -0,0 +1,49 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Public API for tf.linalg namespace.""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import,unused-import +from tensorflow.python.ops.linalg.linalg_impl import * +from tensorflow.python.ops.linalg.linear_operator import * +from tensorflow.python.ops.linalg.linear_operator_adjoint import * +from tensorflow.python.ops.linalg.linear_operator_block_diag import * +from tensorflow.python.ops.linalg.linear_operator_block_lower_triangular import * +from tensorflow.python.ops.linalg.linear_operator_circulant import * +from tensorflow.python.ops.linalg.linear_operator_composition import * +from tensorflow.python.ops.linalg.linear_operator_diag import * +from tensorflow.python.ops.linalg.linear_operator_full_matrix import * +from tensorflow.python.ops.linalg.linear_operator_householder import * +from tensorflow.python.ops.linalg.linear_operator_identity import * +from tensorflow.python.ops.linalg.linear_operator_inversion import * +from tensorflow.python.ops.linalg.linear_operator_kronecker import * +from tensorflow.python.ops.linalg.linear_operator_low_rank_update import * +from tensorflow.python.ops.linalg.linear_operator_lower_triangular import * +from tensorflow.python.ops.linalg.linear_operator_permutation import * +from tensorflow.python.ops.linalg.linear_operator_toeplitz import * +from tensorflow.python.ops.linalg.linear_operator_tridiag import * +from tensorflow.python.ops.linalg.linear_operator_zeros import * +# pylint: enable=wildcard-import + +# Seal API. +# pylint: disable=undefined-variable +del ops +del array_ops +del gen_linalg_ops +del linalg_ops +del math_ops +del special_math_ops +del tf_export +# pylint: enable=undefined-variable diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..66f0a5ac12a12f08b9b0bcef6c2f4afc3456afbe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linalg_impl.py @@ -0,0 +1,1588 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for linear algebra.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +# Linear algebra ops. +band_part = array_ops.matrix_band_part +cholesky = linalg_ops.cholesky +cholesky_solve = linalg_ops.cholesky_solve +det = linalg_ops.matrix_determinant +slogdet = gen_linalg_ops.log_matrix_determinant +tf_export('linalg.slogdet')(dispatch.add_dispatch_support(slogdet)) +diag = array_ops.matrix_diag +diag_part = array_ops.matrix_diag_part +eigh = linalg_ops.self_adjoint_eig +eigvalsh = linalg_ops.self_adjoint_eigvals +einsum = special_math_ops.einsum +eye = linalg_ops.eye +inv = linalg_ops.matrix_inverse +logm = gen_linalg_ops.matrix_logarithm +lu = gen_linalg_ops.lu +tf_export('linalg.logm')(dispatch.add_dispatch_support(logm)) +lstsq = linalg_ops.matrix_solve_ls +norm = linalg_ops.norm +qr = linalg_ops.qr +set_diag = array_ops.matrix_set_diag +solve = linalg_ops.matrix_solve +sqrtm = linalg_ops.matrix_square_root +svd = linalg_ops.svd +tensordot = math_ops.tensordot +trace = math_ops.trace +transpose = array_ops.matrix_transpose +triangular_solve = linalg_ops.matrix_triangular_solve + + +@tf_export('linalg.logdet') +@dispatch.add_dispatch_support +def logdet(matrix, name=None): + """Computes log of the determinant of a hermitian positive definite matrix. + + ```python + # Compute the determinant of a matrix while reducing the chance of over- or + underflow: + A = ... # shape 10 x 10 + det = tf.exp(tf.linalg.logdet(A)) # scalar + ``` + + Args: + matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, + or `complex128` with shape `[..., M, M]`. + name: A name to give this `Op`. Defaults to `logdet`. + + Returns: + The natural log of the determinant of `matrix`. + + @compatibility(numpy) + Equivalent to numpy.linalg.slogdet, although no sign is returned since only + hermitian positive definite matrices are supported. + @end_compatibility + """ + # This uses the property that the log det(A) = 2*sum(log(real(diag(C)))) + # where C is the cholesky decomposition of A. + with ops.name_scope(name, 'logdet', [matrix]): + chol = gen_linalg_ops.cholesky(matrix) + return 2.0 * math_ops.reduce_sum( + math_ops.log(math_ops.real(array_ops.matrix_diag_part(chol))), + axis=[-1]) + + +@tf_export('linalg.adjoint') +@dispatch.add_dispatch_support +def adjoint(matrix, name=None): + """Transposes the last two dimensions of and conjugates tensor `matrix`. + + For example: + + ```python + x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], + [4 + 4j, 5 + 5j, 6 + 6j]]) + tf.linalg.adjoint(x) # [[1 - 1j, 4 - 4j], + # [2 - 2j, 5 - 5j], + # [3 - 3j, 6 - 6j]] + ``` + + Args: + matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, + or `complex128` with shape `[..., M, M]`. + name: A name to give this `Op` (optional). + + Returns: + The adjoint (a.k.a. Hermitian transpose a.k.a. conjugate transpose) of + matrix. + """ + with ops.name_scope(name, 'adjoint', [matrix]): + matrix = ops.convert_to_tensor(matrix, name='matrix') + return array_ops.matrix_transpose(matrix, conjugate=True) + + +# This section is ported nearly verbatim from Eigen's implementation: +# https://eigen.tuxfamily.org/dox/unsupported/MatrixExponential_8h_source.html +def _matrix_exp_pade3(matrix): + """3rd-order Pade approximant for matrix exponential.""" + b = [120.0, 60.0, 12.0] + b = [constant_op.constant(x, matrix.dtype) for x in b] + ident = linalg_ops.eye( + array_ops.shape(matrix)[-2], + batch_shape=array_ops.shape(matrix)[:-2], + dtype=matrix.dtype) + matrix_2 = math_ops.matmul(matrix, matrix) + tmp = matrix_2 + b[1] * ident + matrix_u = math_ops.matmul(matrix, tmp) + matrix_v = b[2] * matrix_2 + b[0] * ident + return matrix_u, matrix_v + + +def _matrix_exp_pade5(matrix): + """5th-order Pade approximant for matrix exponential.""" + b = [30240.0, 15120.0, 3360.0, 420.0, 30.0] + b = [constant_op.constant(x, matrix.dtype) for x in b] + ident = linalg_ops.eye( + array_ops.shape(matrix)[-2], + batch_shape=array_ops.shape(matrix)[:-2], + dtype=matrix.dtype) + matrix_2 = math_ops.matmul(matrix, matrix) + matrix_4 = math_ops.matmul(matrix_2, matrix_2) + tmp = matrix_4 + b[3] * matrix_2 + b[1] * ident + matrix_u = math_ops.matmul(matrix, tmp) + matrix_v = b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident + return matrix_u, matrix_v + + +def _matrix_exp_pade7(matrix): + """7th-order Pade approximant for matrix exponential.""" + b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0] + b = [constant_op.constant(x, matrix.dtype) for x in b] + ident = linalg_ops.eye( + array_ops.shape(matrix)[-2], + batch_shape=array_ops.shape(matrix)[:-2], + dtype=matrix.dtype) + matrix_2 = math_ops.matmul(matrix, matrix) + matrix_4 = math_ops.matmul(matrix_2, matrix_2) + matrix_6 = math_ops.matmul(matrix_4, matrix_2) + tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident + matrix_u = math_ops.matmul(matrix, tmp) + matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident + return matrix_u, matrix_v + + +def _matrix_exp_pade9(matrix): + """9th-order Pade approximant for matrix exponential.""" + b = [ + 17643225600.0, 8821612800.0, 2075673600.0, 302702400.0, 30270240.0, + 2162160.0, 110880.0, 3960.0, 90.0 + ] + b = [constant_op.constant(x, matrix.dtype) for x in b] + ident = linalg_ops.eye( + array_ops.shape(matrix)[-2], + batch_shape=array_ops.shape(matrix)[:-2], + dtype=matrix.dtype) + matrix_2 = math_ops.matmul(matrix, matrix) + matrix_4 = math_ops.matmul(matrix_2, matrix_2) + matrix_6 = math_ops.matmul(matrix_4, matrix_2) + matrix_8 = math_ops.matmul(matrix_6, matrix_2) + tmp = ( + matrix_8 + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + + b[1] * ident) + matrix_u = math_ops.matmul(matrix, tmp) + matrix_v = ( + b[8] * matrix_8 + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + + b[0] * ident) + return matrix_u, matrix_v + + +def _matrix_exp_pade13(matrix): + """13th-order Pade approximant for matrix exponential.""" + b = [ + 64764752532480000.0, 32382376266240000.0, 7771770303897600.0, + 1187353796428800.0, 129060195264000.0, 10559470521600.0, 670442572800.0, + 33522128640.0, 1323241920.0, 40840800.0, 960960.0, 16380.0, 182.0 + ] + b = [constant_op.constant(x, matrix.dtype) for x in b] + ident = linalg_ops.eye( + array_ops.shape(matrix)[-2], + batch_shape=array_ops.shape(matrix)[:-2], + dtype=matrix.dtype) + matrix_2 = math_ops.matmul(matrix, matrix) + matrix_4 = math_ops.matmul(matrix_2, matrix_2) + matrix_6 = math_ops.matmul(matrix_4, matrix_2) + tmp_u = ( + math_ops.matmul(matrix_6, matrix_6 + b[11] * matrix_4 + b[9] * matrix_2) + + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident) + matrix_u = math_ops.matmul(matrix, tmp_u) + tmp_v = b[12] * matrix_6 + b[10] * matrix_4 + b[8] * matrix_2 + matrix_v = ( + math_ops.matmul(matrix_6, tmp_v) + b[6] * matrix_6 + b[4] * matrix_4 + + b[2] * matrix_2 + b[0] * ident) + return matrix_u, matrix_v + + +@tf_export('linalg.expm') +@dispatch.add_dispatch_support +def matrix_exponential(input, name=None): # pylint: disable=redefined-builtin + r"""Computes the matrix exponential of one or more square matrices. + + $$exp(A) = \sum_{n=0}^\infty A^n/n!$$ + + The exponential is computed using a combination of the scaling and squaring + method and the Pade approximation. Details can be found in: + Nicholas J. Higham, "The scaling and squaring method for the matrix + exponential revisited," SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005. + + The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions + form square matrices. The output is a tensor of the same shape as the input + containing the exponential for all input submatrices `[..., :, :]`. + + Args: + input: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or + `complex128` with shape `[..., M, M]`. + name: A name to give this `Op` (optional). + + Returns: + the matrix exponential of the input. + + Raises: + ValueError: An unsupported type is provided as input. + + @compatibility(scipy) + Equivalent to scipy.linalg.expm + @end_compatibility + """ + with ops.name_scope(name, 'matrix_exponential', [input]): + matrix = ops.convert_to_tensor(input, name='input') + if matrix.shape[-2:] == [0, 0]: + return matrix + batch_shape = matrix.shape[:-2] + if not batch_shape.is_fully_defined(): + batch_shape = array_ops.shape(matrix)[:-2] + + # reshaping the batch makes the where statements work better + matrix = array_ops.reshape( + matrix, array_ops.concat(([-1], array_ops.shape(matrix)[-2:]), axis=0)) + l1_norm = math_ops.reduce_max( + math_ops.reduce_sum( + math_ops.abs(matrix), + axis=array_ops.size(array_ops.shape(matrix)) - 2), + axis=-1)[..., array_ops.newaxis, array_ops.newaxis] + + const = lambda x: constant_op.constant(x, l1_norm.dtype) + + def _nest_where(vals, cases): + assert len(vals) == len(cases) - 1 + if len(vals) == 1: + return array_ops.where_v2( + math_ops.less(l1_norm, const(vals[0])), cases[0], cases[1]) + else: + return array_ops.where_v2( + math_ops.less(l1_norm, const(vals[0])), cases[0], + _nest_where(vals[1:], cases[1:])) + + if matrix.dtype in [dtypes.float16, dtypes.float32, dtypes.complex64]: + maxnorm = const(3.925724783138660) + squarings = math_ops.maximum( + math_ops.floor( + math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) + u3, v3 = _matrix_exp_pade3(matrix) + u5, v5 = _matrix_exp_pade5(matrix) + u7, v7 = _matrix_exp_pade7( + matrix / + math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype)) + conds = (4.258730016922831e-001, 1.880152677804762e+000) + u = _nest_where(conds, (u3, u5, u7)) + v = _nest_where(conds, (v3, v5, v7)) + elif matrix.dtype in [dtypes.float64, dtypes.complex128]: + maxnorm = const(5.371920351148152) + squarings = math_ops.maximum( + math_ops.floor( + math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) + u3, v3 = _matrix_exp_pade3(matrix) + u5, v5 = _matrix_exp_pade5(matrix) + u7, v7 = _matrix_exp_pade7(matrix) + u9, v9 = _matrix_exp_pade9(matrix) + u13, v13 = _matrix_exp_pade13( + matrix / + math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype)) + conds = (1.495585217958292e-002, 2.539398330063230e-001, + 9.504178996162932e-001, 2.097847961257068e+000) + u = _nest_where(conds, (u3, u5, u7, u9, u13)) + v = _nest_where(conds, (v3, v5, v7, v9, v13)) + else: + raise ValueError('tf.linalg.expm does not support matrices of type %s' % + matrix.dtype) + + is_finite = math_ops.is_finite(math_ops.reduce_max(l1_norm)) + nan = constant_op.constant(np.nan, matrix.dtype) + result = tf_cond.cond( + is_finite, lambda: linalg_ops.matrix_solve(-u + v, u + v), + lambda: array_ops.fill(array_ops.shape(matrix), nan)) + max_squarings = math_ops.reduce_max(squarings) + i = const(0.0) + + def c(i, _): + return tf_cond.cond(is_finite, + lambda: math_ops.less(i, max_squarings), + lambda: constant_op.constant(False)) + + def b(i, r): + return i + 1, array_ops.where_v2( + math_ops.less(i, squarings), math_ops.matmul(r, r), r) + + _, result = while_loop.while_loop(c, b, [i, result]) + if not matrix.shape.is_fully_defined(): + return array_ops.reshape( + result, + array_ops.concat((batch_shape, array_ops.shape(result)[-2:]), axis=0)) + return array_ops.reshape(result, batch_shape.concatenate(result.shape[-2:])) + + +@tf_export('linalg.banded_triangular_solve', v1=[]) +def banded_triangular_solve( + bands, + rhs, + lower=True, + adjoint=False, # pylint: disable=redefined-outer-name + name=None): + r"""Solve triangular systems of equations with a banded solver. + + `bands` is a tensor of shape `[..., K, M]`, where `K` represents the number + of bands stored. This corresponds to a batch of `M` by `M` matrices, whose + `K` subdiagonals (when `lower` is `True`) are stored. + + This operator broadcasts the batch dimensions of `bands` and the batch + dimensions of `rhs`. + + + Examples: + + Storing 2 bands of a 3x3 matrix. + Note that first element in the second row is ignored due to + the 'LEFT_RIGHT' padding. + + >>> x = [[2., 3., 4.], [1., 2., 3.]] + >>> x2 = [[2., 3., 4.], [10000., 2., 3.]] + >>> y = tf.zeros([3, 3]) + >>> z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(-1, 0)) + >>> z + + >>> soln = tf.linalg.banded_triangular_solve(x, tf.ones([3, 1])) + >>> soln + + >>> are_equal = soln == tf.linalg.banded_triangular_solve(x2, tf.ones([3, 1])) + >>> tf.reduce_all(are_equal).numpy() + True + >>> are_equal = soln == tf.linalg.triangular_solve(z, tf.ones([3, 1])) + >>> tf.reduce_all(are_equal).numpy() + True + + Storing 2 superdiagonals of a 4x4 matrix. Because of the 'LEFT_RIGHT' padding + the last element of the first row is ignored. + + >>> x = [[2., 3., 4., 5.], [-1., -2., -3., -4.]] + >>> y = tf.zeros([4, 4]) + >>> z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(0, 1)) + >>> z + + >>> soln = tf.linalg.banded_triangular_solve(x, tf.ones([4, 1]), lower=False) + >>> soln + + >>> are_equal = (soln == tf.linalg.triangular_solve( + ... z, tf.ones([4, 1]), lower=False)) + >>> tf.reduce_all(are_equal).numpy() + True + + + Args: + bands: A `Tensor` describing the bands of the left hand side, with shape + `[..., K, M]`. The `K` rows correspond to the diagonal to the `K - 1`-th + diagonal (the diagonal is the top row) when `lower` is `True` and + otherwise the `K - 1`-th superdiagonal to the diagonal (the diagonal is + the bottom row) when `lower` is `False`. The bands are stored with + 'LEFT_RIGHT' alignment, where the superdiagonals are padded on the right + and subdiagonals are padded on the left. This is the alignment cuSPARSE + uses. See `tf.linalg.set_diag` for more details. + rhs: A `Tensor` of shape [..., M] or [..., M, N] and with the same dtype as + `diagonals`. Note that if the shape of `rhs` and/or `diags` isn't known + statically, `rhs` will be treated as a matrix rather than a vector. + lower: An optional `bool`. Defaults to `True`. Boolean indicating whether + `bands` represents a lower or upper triangular matrix. + adjoint: An optional `bool`. Defaults to `False`. Boolean indicating whether + to solve with the matrix's block-wise adjoint. + name: A name to give this `Op` (optional). + + Returns: + A `Tensor` of shape [..., M] or [..., M, N] containing the solutions. + """ + with ops.name_scope(name, 'banded_triangular_solve', [bands, rhs]): + return gen_linalg_ops.banded_triangular_solve( + bands, rhs, lower=lower, adjoint=adjoint) + + +@tf_export('linalg.tridiagonal_solve') +@dispatch.add_dispatch_support +def tridiagonal_solve(diagonals, + rhs, + diagonals_format='compact', + transpose_rhs=False, + conjugate_rhs=False, + name=None, + partial_pivoting=True, + perturb_singular=False): + r"""Solves tridiagonal systems of equations. + + The input can be supplied in various formats: `matrix`, `sequence` and + `compact`, specified by the `diagonals_format` arg. + + In `matrix` format, `diagonals` must be a tensor of shape `[..., M, M]`, with + two inner-most dimensions representing the square tridiagonal matrices. + Elements outside of the three diagonals will be ignored. + + In `sequence` format, `diagonals` are supplied as a tuple or list of three + tensors of shapes `[..., N]`, `[..., M]`, `[..., N]` representing + superdiagonals, diagonals, and subdiagonals, respectively. `N` can be either + `M-1` or `M`; in the latter case, the last element of superdiagonal and the + first element of subdiagonal will be ignored. + + In `compact` format the three diagonals are brought together into one tensor + of shape `[..., 3, M]`, with last two dimensions containing superdiagonals, + diagonals, and subdiagonals, in order. Similarly to `sequence` format, + elements `diagonals[..., 0, M-1]` and `diagonals[..., 2, 0]` are ignored. + + The `compact` format is recommended as the one with best performance. In case + you need to cast a tensor into a compact format manually, use `tf.gather_nd`. + An example for a tensor of shape [m, m]: + + ```python + rhs = tf.constant([...]) + matrix = tf.constant([[...]]) + m = matrix.shape[0] + dummy_idx = [0, 0] # An arbitrary element to use as a dummy + indices = [[[i, i + 1] for i in range(m - 1)] + [dummy_idx], # Superdiagonal + [[i, i] for i in range(m)], # Diagonal + [dummy_idx] + [[i + 1, i] for i in range(m - 1)]] # Subdiagonal + diagonals=tf.gather_nd(matrix, indices) + x = tf.linalg.tridiagonal_solve(diagonals, rhs) + ``` + + Regardless of the `diagonals_format`, `rhs` is a tensor of shape `[..., M]` or + `[..., M, K]`. The latter allows to simultaneously solve K systems with the + same left-hand sides and K different right-hand sides. If `transpose_rhs` + is set to `True` the expected shape is `[..., M]` or `[..., K, M]`. + + The batch dimensions, denoted as `...`, must be the same in `diagonals` and + `rhs`. + + The output is a tensor of the same shape as `rhs`: either `[..., M]` or + `[..., M, K]`. + + The op isn't guaranteed to raise an error if the input matrix is not + invertible. `tf.debugging.check_numerics` can be applied to the output to + detect invertibility problems. + + **Note**: with large batch sizes, the computation on the GPU may be slow, if + either `partial_pivoting=True` or there are multiple right-hand sides + (`K > 1`). If this issue arises, consider if it's possible to disable pivoting + and have `K = 1`, or, alternatively, consider using CPU. + + On CPU, solution is computed via Gaussian elimination with or without partial + pivoting, depending on `partial_pivoting` parameter. On GPU, Nvidia's cuSPARSE + library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv + + Args: + diagonals: A `Tensor` or tuple of `Tensor`s describing left-hand sides. The + shape depends of `diagonals_format`, see description above. Must be + `float32`, `float64`, `complex64`, or `complex128`. + rhs: A `Tensor` of shape [..., M] or [..., M, K] and with the same dtype as + `diagonals`. Note that if the shape of `rhs` and/or `diags` isn't known + statically, `rhs` will be treated as a matrix rather than a vector. + diagonals_format: one of `matrix`, `sequence`, or `compact`. Default is + `compact`. + transpose_rhs: If `True`, `rhs` is transposed before solving (has no effect + if the shape of rhs is [..., M]). + conjugate_rhs: If `True`, `rhs` is conjugated before solving. + name: A name to give this `Op` (optional). + partial_pivoting: whether to perform partial pivoting. `True` by default. + Partial pivoting makes the procedure more stable, but slower. Partial + pivoting is unnecessary in some cases, including diagonally dominant and + symmetric positive definite matrices (see e.g. theorem 9.12 in [1]). + perturb_singular: whether to perturb singular matrices to return a finite + result. `False` by default. If true, solutions to systems involving + a singular matrix will be computed by perturbing near-zero pivots in + the partially pivoted LU decomposition. Specifically, tiny pivots are + perturbed by an amount of order `eps * max_{ij} |U(i,j)|` to avoid + overflow. Here `U` is the upper triangular part of the LU decomposition, + and `eps` is the machine precision. This is useful for solving + numerically singular systems when computing eigenvectors by inverse + iteration. + If `partial_pivoting` is `False`, `perturb_singular` must be `False` as + well. + + Returns: + A `Tensor` of shape [..., M] or [..., M, K] containing the solutions. + If the input matrix is singular, the result is undefined. + + Raises: + ValueError: Is raised if any of the following conditions hold: + 1. An unsupported type is provided as input, + 2. the input tensors have incorrect shapes, + 3. `perturb_singular` is `True` but `partial_pivoting` is not. + UnimplementedError: Whenever `partial_pivoting` is true and the backend is + XLA, or whenever `perturb_singular` is true and the backend is + XLA or GPU. + + [1] Nicholas J. Higham (2002). Accuracy and Stability of Numerical Algorithms: + Second Edition. SIAM. p. 175. ISBN 978-0-89871-802-7. + + """ + if perturb_singular and not partial_pivoting: + raise ValueError('partial_pivoting must be True if perturb_singular is.') + + if diagonals_format == 'compact': + return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, + conjugate_rhs, partial_pivoting, + perturb_singular, name) + + if diagonals_format == 'sequence': + if not isinstance(diagonals, (tuple, list)) or len(diagonals) != 3: + raise ValueError('Expected diagonals to be a sequence of length 3.') + + superdiag, maindiag, subdiag = diagonals + if (not subdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1]) or + not superdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1])): + raise ValueError( + 'Tensors representing the three diagonals must have the same shape,' + 'except for the last dimension, got {}, {}, {}'.format( + subdiag.shape, maindiag.shape, superdiag.shape)) + + m = tensor_shape.dimension_value(maindiag.shape[-1]) + + def pad_if_necessary(t, name, last_dim_padding): + n = tensor_shape.dimension_value(t.shape[-1]) + if not n or n == m: + return t + if n == m - 1: + paddings = ([[0, 0] for _ in range(len(t.shape) - 1)] + + [last_dim_padding]) + return array_ops.pad(t, paddings) + raise ValueError('Expected {} to be have length {} or {}, got {}.'.format( + name, m, m - 1, n)) + + subdiag = pad_if_necessary(subdiag, 'subdiagonal', [1, 0]) + superdiag = pad_if_necessary(superdiag, 'superdiagonal', [0, 1]) + + diagonals = array_ops_stack.stack((superdiag, maindiag, subdiag), axis=-2) + return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, + conjugate_rhs, partial_pivoting, + perturb_singular, name) + + if diagonals_format == 'matrix': + m1 = tensor_shape.dimension_value(diagonals.shape[-1]) + m2 = tensor_shape.dimension_value(diagonals.shape[-2]) + if m1 and m2 and m1 != m2: + raise ValueError( + 'Expected last two dimensions of diagonals to be same, got {} and {}' + .format(m1, m2)) + m = m1 or m2 + diagonals = array_ops.matrix_diag_part( + diagonals, k=(-1, 1), padding_value=0., align='LEFT_RIGHT') + return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, + conjugate_rhs, partial_pivoting, + perturb_singular, name) + + raise ValueError('Unrecognized diagonals_format: {}'.format(diagonals_format)) + + +def _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, + conjugate_rhs, partial_pivoting, + perturb_singular, name): + """Helper function used after the input has been cast to compact form.""" + diags_rank, rhs_rank = diagonals.shape.rank, rhs.shape.rank + + # If we know the rank of the diagonal tensor, do some static checking. + if diags_rank: + if diags_rank < 2: + raise ValueError( + 'Expected diagonals to have rank at least 2, got {}'.format( + diags_rank)) + if rhs_rank and rhs_rank != diags_rank and rhs_rank != diags_rank - 1: + raise ValueError('Expected the rank of rhs to be {} or {}, got {}'.format( + diags_rank - 1, diags_rank, rhs_rank)) + if (rhs_rank and not diagonals.shape[:-2].is_compatible_with( + rhs.shape[:diags_rank - 2])): + raise ValueError('Batch shapes {} and {} are incompatible'.format( + diagonals.shape[:-2], rhs.shape[:diags_rank - 2])) + + if diagonals.shape[-2] and diagonals.shape[-2] != 3: + raise ValueError('Expected 3 diagonals got {}'.format(diagonals.shape[-2])) + + def check_num_lhs_matches_num_rhs(): + if (diagonals.shape[-1] and rhs.shape[-2] and + diagonals.shape[-1] != rhs.shape[-2]): + raise ValueError('Expected number of left-hand sided and right-hand ' + 'sides to be equal, got {} and {}'.format( + diagonals.shape[-1], rhs.shape[-2])) + + if rhs_rank and diags_rank and rhs_rank == diags_rank - 1: + # Rhs provided as a vector, ignoring transpose_rhs + if conjugate_rhs: + rhs = math_ops.conj(rhs) + rhs = array_ops.expand_dims(rhs, -1) + check_num_lhs_matches_num_rhs() + return array_ops.squeeze( + linalg_ops.tridiagonal_solve(diagonals, rhs, partial_pivoting, + perturb_singular, name), -1) + + if transpose_rhs: + rhs = array_ops.matrix_transpose(rhs, conjugate=conjugate_rhs) + elif conjugate_rhs: + rhs = math_ops.conj(rhs) + + check_num_lhs_matches_num_rhs() + return linalg_ops.tridiagonal_solve(diagonals, rhs, partial_pivoting, + perturb_singular, name) + + +@tf_export('linalg.tridiagonal_matmul') +@dispatch.add_dispatch_support +def tridiagonal_matmul(diagonals, rhs, diagonals_format='compact', name=None): + r"""Multiplies tridiagonal matrix by matrix. + + `diagonals` is representation of 3-diagonal NxN matrix, which depends on + `diagonals_format`. + + In `matrix` format, `diagonals` must be a tensor of shape `[..., M, M]`, with + two inner-most dimensions representing the square tridiagonal matrices. + Elements outside of the three diagonals will be ignored. + + If `sequence` format, `diagonals` is list or tuple of three tensors: + `[superdiag, maindiag, subdiag]`, each having shape [..., M]. Last element + of `superdiag` first element of `subdiag` are ignored. + + In `compact` format the three diagonals are brought together into one tensor + of shape `[..., 3, M]`, with last two dimensions containing superdiagonals, + diagonals, and subdiagonals, in order. Similarly to `sequence` format, + elements `diagonals[..., 0, M-1]` and `diagonals[..., 2, 0]` are ignored. + + The `sequence` format is recommended as the one with the best performance. + + `rhs` is matrix to the right of multiplication. It has shape `[..., M, N]`. + + Example: + + ```python + superdiag = tf.constant([-1, -1, 0], dtype=tf.float64) + maindiag = tf.constant([2, 2, 2], dtype=tf.float64) + subdiag = tf.constant([0, -1, -1], dtype=tf.float64) + diagonals = [superdiag, maindiag, subdiag] + rhs = tf.constant([[1, 1], [1, 1], [1, 1]], dtype=tf.float64) + x = tf.linalg.tridiagonal_matmul(diagonals, rhs, diagonals_format='sequence') + ``` + + Args: + diagonals: A `Tensor` or tuple of `Tensor`s describing left-hand sides. The + shape depends of `diagonals_format`, see description above. Must be + `float32`, `float64`, `complex64`, or `complex128`. + rhs: A `Tensor` of shape [..., M, N] and with the same dtype as `diagonals`. + diagonals_format: one of `sequence`, or `compact`. Default is `compact`. + name: A name to give this `Op` (optional). + + Returns: + A `Tensor` of shape [..., M, N] containing the result of multiplication. + + Raises: + ValueError: An unsupported type is provided as input, or when the input + tensors have incorrect shapes. + """ + if diagonals_format == 'compact': + superdiag = diagonals[..., 0, :] + maindiag = diagonals[..., 1, :] + subdiag = diagonals[..., 2, :] + elif diagonals_format == 'sequence': + superdiag, maindiag, subdiag = diagonals + elif diagonals_format == 'matrix': + m1 = tensor_shape.dimension_value(diagonals.shape[-1]) + m2 = tensor_shape.dimension_value(diagonals.shape[-2]) + if m1 and m2 and m1 != m2: + raise ValueError( + 'Expected last two dimensions of diagonals to be same, got {} and {}' + .format(m1, m2)) + diags = array_ops.matrix_diag_part( + diagonals, k=(-1, 1), padding_value=0., align='LEFT_RIGHT') + superdiag = diags[..., 0, :] + maindiag = diags[..., 1, :] + subdiag = diags[..., 2, :] + else: + raise ValueError('Unrecognized diagonals_format: %s' % diagonals_format) + + # C++ backend requires matrices. + # Converting 1-dimensional vectors to matrices with 1 row. + superdiag = array_ops.expand_dims(superdiag, -2) + maindiag = array_ops.expand_dims(maindiag, -2) + subdiag = array_ops.expand_dims(subdiag, -2) + + return linalg_ops.tridiagonal_mat_mul(superdiag, maindiag, subdiag, rhs, name) + + +def _maybe_validate_matrix(a, validate_args): + """Checks that input is a `float` matrix.""" + assertions = [] + if not a.dtype.is_floating: + raise TypeError('Input `a` must have `float`-like `dtype` ' + '(saw {}).'.format(a.dtype.name)) + if a.shape is not None and a.shape.rank is not None: + if a.shape.rank < 2: + raise ValueError('Input `a` must have at least 2 dimensions ' + '(saw: {}).'.format(a.shape.rank)) + elif validate_args: + assertions.append( + check_ops.assert_rank_at_least( + a, rank=2, message='Input `a` must have at least 2 dimensions.')) + return assertions + + +@tf_export('linalg.matrix_rank') +@dispatch.add_dispatch_support +def matrix_rank(a, tol=None, validate_args=False, name=None): + """Compute the matrix rank of one or more matrices. + + Args: + a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be + pseudo-inverted. + tol: Threshold below which the singular value is counted as 'zero'. + Default value: `None` (i.e., `eps * max(rows, cols) * max(singular_val)`). + validate_args: When `True`, additional assertions might be embedded in the + graph. + Default value: `False` (i.e., no graph assertions are added). + name: Python `str` prefixed to ops created by this function. + Default value: 'matrix_rank'. + + Returns: + matrix_rank: (Batch of) `int32` scalars representing the number of non-zero + singular values. + """ + with ops.name_scope(name or 'matrix_rank'): + a = ops.convert_to_tensor(a, dtype_hint=dtypes.float32, name='a') + assertions = _maybe_validate_matrix(a, validate_args) + if assertions: + with ops.control_dependencies(assertions): + a = array_ops.identity(a) + s = svd(a, compute_uv=False) + if tol is None: + if (a.shape[-2:]).is_fully_defined(): + m = np.max(a.shape[-2:].as_list()) + else: + m = math_ops.reduce_max(array_ops.shape(a)[-2:]) + eps = np.finfo(a.dtype.as_numpy_dtype).eps + tol = ( + eps * math_ops.cast(m, a.dtype) * + math_ops.reduce_max(s, axis=-1, keepdims=True)) + return math_ops.reduce_sum(math_ops.cast(s > tol, dtypes.int32), axis=-1) + + +@tf_export('linalg.pinv') +@dispatch.add_dispatch_support +def pinv(a, rcond=None, validate_args=False, name=None): + """Compute the Moore-Penrose pseudo-inverse of one or more matrices. + + Calculate the [generalized inverse of a matrix]( + https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) using its + singular-value decomposition (SVD) and including all large singular values. + + The pseudo-inverse of a matrix `A`, is defined as: 'the matrix that 'solves' + [the least-squares problem] `A @ x = b`,' i.e., if `x_hat` is a solution, then + `A_pinv` is the matrix such that `x_hat = A_pinv @ b`. It can be shown that if + `U @ Sigma @ V.T = A` is the singular value decomposition of `A`, then + `A_pinv = V @ inv(Sigma) U^T`. [(Strang, 1980)][1] + + This function is analogous to [`numpy.linalg.pinv`]( + https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.pinv.html). + It differs only in default value of `rcond`. In `numpy.linalg.pinv`, the + default `rcond` is `1e-15`. Here the default is + `10. * max(num_rows, num_cols) * np.finfo(dtype).eps`. + + Args: + a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be + pseudo-inverted. + rcond: `Tensor` of small singular value cutoffs. Singular values smaller + (in modulus) than `rcond` * largest_singular_value (again, in modulus) are + set to zero. Must broadcast against `tf.shape(a)[:-2]`. + Default value: `10. * max(num_rows, num_cols) * np.finfo(a.dtype).eps`. + validate_args: When `True`, additional assertions might be embedded in the + graph. + Default value: `False` (i.e., no graph assertions are added). + name: Python `str` prefixed to ops created by this function. + Default value: 'pinv'. + + Returns: + a_pinv: (Batch of) pseudo-inverse of input `a`. Has same shape as `a` except + rightmost two dimensions are transposed. + + Raises: + TypeError: if input `a` does not have `float`-like `dtype`. + ValueError: if input `a` has fewer than 2 dimensions. + + #### Examples + + ```python + import tensorflow as tf + import tensorflow_probability as tfp + + a = tf.constant([[1., 0.4, 0.5], + [0.4, 0.2, 0.25], + [0.5, 0.25, 0.35]]) + tf.matmul(tf.linalg.pinv(a), a) + # ==> array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]], dtype=float32) + + a = tf.constant([[1., 0.4, 0.5, 1.], + [0.4, 0.2, 0.25, 2.], + [0.5, 0.25, 0.35, 3.]]) + tf.matmul(tf.linalg.pinv(a), a) + # ==> array([[ 0.76, 0.37, 0.21, -0.02], + [ 0.37, 0.43, -0.33, 0.02], + [ 0.21, -0.33, 0.81, 0.01], + [-0.02, 0.02, 0.01, 1. ]], dtype=float32) + ``` + + #### References + + [1]: G. Strang. 'Linear Algebra and Its Applications, 2nd Ed.' Academic Press, + Inc., 1980, pp. 139-142. + """ + with ops.name_scope(name or 'pinv'): + a = ops.convert_to_tensor(a, name='a') + + assertions = _maybe_validate_matrix(a, validate_args) + if assertions: + with ops.control_dependencies(assertions): + a = array_ops.identity(a) + + dtype = a.dtype.as_numpy_dtype + + if rcond is None: + + def get_dim_size(dim): + dim_val = tensor_shape.dimension_value(a.shape[dim]) + if dim_val is not None: + return dim_val + return array_ops.shape(a)[dim] + + num_rows = get_dim_size(-2) + num_cols = get_dim_size(-1) + if isinstance(num_rows, int) and isinstance(num_cols, int): + max_rows_cols = float(max(num_rows, num_cols)) + else: + max_rows_cols = math_ops.cast( + math_ops.maximum(num_rows, num_cols), dtype) + rcond = 10. * max_rows_cols * np.finfo(dtype).eps + + rcond = ops.convert_to_tensor(rcond, dtype=dtype, name='rcond') + + # Calculate pseudo inverse via SVD. + # Note: if a is Hermitian then u == v. (We might observe additional + # performance by explicitly setting `v = u` in such cases.) + [ + singular_values, # Sigma + left_singular_vectors, # U + right_singular_vectors, # V + ] = svd( + a, full_matrices=False, compute_uv=True) + + # Saturate small singular values to inf. This has the effect of make + # `1. / s = 0.` while not resulting in `NaN` gradients. + cutoff = rcond * math_ops.reduce_max(singular_values, axis=-1) + singular_values = array_ops.where_v2( + singular_values > array_ops.expand_dims_v2(cutoff, -1), singular_values, + np.array(np.inf, dtype)) + + # By the definition of the SVD, `a == u @ s @ v^H`, and the pseudo-inverse + # is defined as `pinv(a) == v @ inv(s) @ u^H`. + a_pinv = math_ops.matmul( + right_singular_vectors / array_ops.expand_dims_v2(singular_values, -2), + left_singular_vectors, + adjoint_b=True) + + if a.shape is not None and a.shape.rank is not None: + a_pinv.set_shape(a.shape[:-2].concatenate([a.shape[-1], a.shape[-2]])) + + return a_pinv + + +@tf_export('linalg.lu_solve') +@dispatch.add_dispatch_support +def lu_solve(lower_upper, perm, rhs, validate_args=False, name=None): + """Solves systems of linear eqns `A X = RHS`, given LU factorizations. + + Note: this function does not verify the implied matrix is actually invertible + nor is this condition checked even when `validate_args=True`. + + Args: + lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P, + matmul(L, U)) = X` then `lower_upper = L + U - eye`. + perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) = + X` then `perm = argmax(P)`. + rhs: Matrix-shaped float `Tensor` representing targets for which to solve; + `A X = RHS`. To handle vector cases, use: `lu_solve(..., rhs[..., + tf.newaxis])[..., 0]`. + validate_args: Python `bool` indicating whether arguments should be checked + for correctness. Note: this function does not verify the implied matrix is + actually invertible, even when `validate_args=True`. + Default value: `False` (i.e., don't validate arguments). + name: Python `str` name given to ops managed by this object. + Default value: `None` (i.e., 'lu_solve'). + + Returns: + x: The `X` in `A @ X = RHS`. + + #### Examples + + ```python + import numpy as np + import tensorflow as tf + import tensorflow_probability as tfp + + x = [[[1., 2], + [3, 4]], + [[7, 8], + [3, 4]]] + inv_x = tf.linalg.lu_solve(*tf.linalg.lu(x), rhs=tf.eye(2)) + tf.assert_near(tf.matrix_inverse(x), inv_x) + # ==> True + ``` + + """ + + with ops.name_scope(name or 'lu_solve'): + lower_upper = ops.convert_to_tensor( + lower_upper, dtype_hint=dtypes.float32, name='lower_upper') + perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm') + rhs = ops.convert_to_tensor(rhs, dtype_hint=lower_upper.dtype, name='rhs') + + assertions = _lu_solve_assertions(lower_upper, perm, rhs, validate_args) + if assertions: + with ops.control_dependencies(assertions): + lower_upper = array_ops.identity(lower_upper) + perm = array_ops.identity(perm) + rhs = array_ops.identity(rhs) + + if (rhs.shape.rank == 2 and perm.shape.rank == 1): + # Both rhs and perm have scalar batch_shape. + permuted_rhs = array_ops.gather(rhs, perm, axis=-2) + else: + # Either rhs or perm have non-scalar batch_shape or we can't determine + # this information statically. + rhs_shape = array_ops.shape(rhs) + broadcast_batch_shape = array_ops.broadcast_dynamic_shape( + rhs_shape[:-2], + array_ops.shape(perm)[:-1]) + d, m = rhs_shape[-2], rhs_shape[-1] + rhs_broadcast_shape = array_ops.concat([broadcast_batch_shape, [d, m]], + axis=0) + + # Tile out rhs. + broadcast_rhs = array_ops.broadcast_to(rhs, rhs_broadcast_shape) + broadcast_rhs = array_ops.reshape(broadcast_rhs, [-1, d, m]) + + # Tile out perm and add batch indices. + broadcast_perm = array_ops.broadcast_to(perm, rhs_broadcast_shape[:-1]) + broadcast_perm = array_ops.reshape(broadcast_perm, [-1, d]) + broadcast_batch_size = math_ops.reduce_prod(broadcast_batch_shape) + broadcast_batch_indices = array_ops.broadcast_to( + math_ops.range(broadcast_batch_size)[:, array_ops.newaxis], + [broadcast_batch_size, d]) + broadcast_perm = array_ops_stack.stack( + [broadcast_batch_indices, broadcast_perm], axis=-1) + + permuted_rhs = array_ops.gather_nd(broadcast_rhs, broadcast_perm) + permuted_rhs = array_ops.reshape(permuted_rhs, rhs_broadcast_shape) + + lower = set_diag( + band_part(lower_upper, num_lower=-1, num_upper=0), + array_ops.ones( + array_ops.shape(lower_upper)[:-1], dtype=lower_upper.dtype)) + return triangular_solve( + lower_upper, # Only upper is accessed. + triangular_solve(lower, permuted_rhs), + lower=False) + + +@tf_export('linalg.lu_matrix_inverse') +@dispatch.add_dispatch_support +def lu_matrix_inverse(lower_upper, perm, validate_args=False, name=None): + """Computes the inverse given the LU decomposition(s) of one or more matrices. + + This op is conceptually identical to, + + ```python + inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X)) + tf.assert_near(tf.matrix_inverse(X), inv_X) + # ==> True + ``` + + Note: this function does not verify the implied matrix is actually invertible + nor is this condition checked even when `validate_args=True`. + + Args: + lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P, + matmul(L, U)) = X` then `lower_upper = L + U - eye`. + perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) = + X` then `perm = argmax(P)`. + validate_args: Python `bool` indicating whether arguments should be checked + for correctness. Note: this function does not verify the implied matrix is + actually invertible, even when `validate_args=True`. + Default value: `False` (i.e., don't validate arguments). + name: Python `str` name given to ops managed by this object. + Default value: `None` (i.e., 'lu_matrix_inverse'). + + Returns: + inv_x: The matrix_inv, i.e., + `tf.matrix_inverse(tf.linalg.lu_reconstruct(lu, perm))`. + + #### Examples + + ```python + import numpy as np + import tensorflow as tf + import tensorflow_probability as tfp + + x = [[[3., 4], [1, 2]], + [[7., 8], [3, 4]]] + inv_x = tf.linalg.lu_matrix_inverse(*tf.linalg.lu(x)) + tf.assert_near(tf.matrix_inverse(x), inv_x) + # ==> True + ``` + + """ + + with ops.name_scope(name or 'lu_matrix_inverse'): + lower_upper = ops.convert_to_tensor( + lower_upper, dtype_hint=dtypes.float32, name='lower_upper') + perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm') + assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args) + if assertions: + with ops.control_dependencies(assertions): + lower_upper = array_ops.identity(lower_upper) + perm = array_ops.identity(perm) + shape = array_ops.shape(lower_upper) + return lu_solve( + lower_upper, + perm, + rhs=eye(shape[-1], batch_shape=shape[:-2], dtype=lower_upper.dtype), + validate_args=False) + + +@tf_export('linalg.lu_reconstruct') +@dispatch.add_dispatch_support +def lu_reconstruct(lower_upper, perm, validate_args=False, name=None): + """The reconstruct one or more matrices from their LU decomposition(s). + + Args: + lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P, + matmul(L, U)) = X` then `lower_upper = L + U - eye`. + perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) = + X` then `perm = argmax(P)`. + validate_args: Python `bool` indicating whether arguments should be checked + for correctness. + Default value: `False` (i.e., don't validate arguments). + name: Python `str` name given to ops managed by this object. + Default value: `None` (i.e., 'lu_reconstruct'). + + Returns: + x: The original input to `tf.linalg.lu`, i.e., `x` as in, + `lu_reconstruct(*tf.linalg.lu(x))`. + + #### Examples + + ```python + import numpy as np + import tensorflow as tf + import tensorflow_probability as tfp + + x = [[[3., 4], [1, 2]], + [[7., 8], [3, 4]]] + x_reconstructed = tf.linalg.lu_reconstruct(*tf.linalg.lu(x)) + tf.assert_near(x, x_reconstructed) + # ==> True + ``` + + """ + with ops.name_scope(name or 'lu_reconstruct'): + lower_upper = ops.convert_to_tensor( + lower_upper, dtype_hint=dtypes.float32, name='lower_upper') + perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm') + + assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args) + if assertions: + with ops.control_dependencies(assertions): + lower_upper = array_ops.identity(lower_upper) + perm = array_ops.identity(perm) + + shape = array_ops.shape(lower_upper) + + lower = set_diag( + band_part(lower_upper, num_lower=-1, num_upper=0), + array_ops.ones(shape[:-1], dtype=lower_upper.dtype)) + upper = band_part(lower_upper, num_lower=0, num_upper=-1) + x = math_ops.matmul(lower, upper) + + if (lower_upper.shape is None or lower_upper.shape.rank is None or + lower_upper.shape.rank != 2): + # We either don't know the batch rank or there are >0 batch dims. + batch_size = math_ops.reduce_prod(shape[:-2]) + d = shape[-1] + x = array_ops.reshape(x, [batch_size, d, d]) + perm = array_ops.reshape(perm, [batch_size, d]) + perm = map_fn.map_fn(array_ops.invert_permutation, perm) + batch_indices = array_ops.broadcast_to( + math_ops.range(batch_size)[:, array_ops.newaxis], [batch_size, d]) + x = array_ops.gather_nd( + x, array_ops_stack.stack([batch_indices, perm], axis=-1)) + x = array_ops.reshape(x, shape) + else: + x = array_ops.gather(x, array_ops.invert_permutation(perm)) + + x.set_shape(lower_upper.shape) + return x + + +def lu_reconstruct_assertions(lower_upper, perm, validate_args): + """Returns list of assertions related to `lu_reconstruct` assumptions.""" + assertions = [] + + message = 'Input `lower_upper` must have at least 2 dimensions.' + if lower_upper.shape.rank is not None and lower_upper.shape.rank < 2: + raise ValueError(message) + elif validate_args: + assertions.append( + check_ops.assert_rank_at_least_v2(lower_upper, rank=2, message=message)) + + message = '`rank(lower_upper)` must equal `rank(perm) + 1`' + if lower_upper.shape.rank is not None and perm.shape.rank is not None: + if lower_upper.shape.rank != perm.shape.rank + 1: + raise ValueError(message) + elif validate_args: + assertions.append( + check_ops.assert_rank( + lower_upper, rank=array_ops.rank(perm) + 1, message=message)) + + message = '`lower_upper` must be square.' + if lower_upper.shape[:-2].is_fully_defined(): + if lower_upper.shape[-2] != lower_upper.shape[-1]: + raise ValueError(message) + elif validate_args: + m, n = array_ops.split( + array_ops.shape(lower_upper)[-2:], num_or_size_splits=2) + assertions.append(check_ops.assert_equal(m, n, message=message)) + + return assertions + + +def _lu_solve_assertions(lower_upper, perm, rhs, validate_args): + """Returns list of assertions related to `lu_solve` assumptions.""" + assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args) + + message = 'Input `rhs` must have at least 2 dimensions.' + if rhs.shape.ndims is not None: + if rhs.shape.ndims < 2: + raise ValueError(message) + elif validate_args: + assertions.append( + check_ops.assert_rank_at_least(rhs, rank=2, message=message)) + + message = '`lower_upper.shape[-1]` must equal `rhs.shape[-1]`.' + if (lower_upper.shape[-1] is not None and rhs.shape[-2] is not None): + if lower_upper.shape[-1] != rhs.shape[-2]: + raise ValueError(message) + elif validate_args: + assertions.append( + check_ops.assert_equal( + array_ops.shape(lower_upper)[-1], + array_ops.shape(rhs)[-2], + message=message)) + + return assertions + + +@tf_export('linalg.eigh_tridiagonal') +@dispatch.add_dispatch_support +def eigh_tridiagonal(alpha, + beta, + eigvals_only=True, + select='a', + select_range=None, + tol=None, + name=None): + """Computes the eigenvalues of a Hermitian tridiagonal matrix. + + Args: + alpha: A real or complex tensor of shape (n), the diagonal elements of the + matrix. NOTE: If alpha is complex, the imaginary part is ignored (assumed + zero) to satisfy the requirement that the matrix be Hermitian. + beta: A real or complex tensor of shape (n-1), containing the elements of + the first super-diagonal of the matrix. If beta is complex, the first + sub-diagonal of the matrix is assumed to be the conjugate of beta to + satisfy the requirement that the matrix be Hermitian + eigvals_only: If False, both eigenvalues and corresponding eigenvectors are + computed. If True, only eigenvalues are computed. Default is True. + select: Optional string with values in {‘a’, ‘v’, ‘i’} (default is 'a') that + determines which eigenvalues to calculate: + 'a': all eigenvalues. + ‘v’: eigenvalues in the interval (min, max] given by `select_range`. + 'i’: eigenvalues with indices min <= i <= max. + select_range: Size 2 tuple or list or tensor specifying the range of + eigenvalues to compute together with select. If select is 'a', + select_range is ignored. + tol: Optional scalar. The absolute tolerance to which each eigenvalue is + required. An eigenvalue (or cluster) is considered to have converged if it + lies in an interval of this width. If tol is None (default), the value + eps*|T|_2 is used where eps is the machine precision, and |T|_2 is the + 2-norm of the matrix T. + name: Optional name of the op. + + Returns: + eig_vals: The eigenvalues of the matrix in non-decreasing order. + eig_vectors: If `eigvals_only` is False the eigenvectors are returned in + the second output argument. + + Raises: + ValueError: If input values are invalid. + NotImplemented: Computing eigenvectors for `eigvals_only` = False is + not implemented yet. + + This op implements a subset of the functionality of + scipy.linalg.eigh_tridiagonal. + + Note: The result is undefined if the input contains +/-inf or NaN, or if + any value in beta has a magnitude greater than + `numpy.sqrt(numpy.finfo(beta.dtype.as_numpy_dtype).max)`. + + + TODO(b/187527398): + Add support for outer batch dimensions. + + #### Examples + + ```python + import numpy + eigvals = tf.linalg.eigh_tridiagonal([0.0, 0.0, 0.0], [1.0, 1.0]) + eigvals_expected = [-numpy.sqrt(2.0), 0.0, numpy.sqrt(2.0)] + tf.assert_near(eigvals_expected, eigvals) + # ==> True + ``` + + """ + with ops.name_scope(name or 'eigh_tridiagonal'): + + def _compute_eigenvalues(alpha, beta): + """Computes all eigenvalues of a Hermitian tridiagonal matrix.""" + + def _sturm(alpha, beta_sq, pivmin, alpha0_perturbation, x): + """Implements the Sturm sequence recurrence.""" + with ops.name_scope('sturm'): + n = alpha.shape[0] + zeros = array_ops.zeros(array_ops.shape(x), dtype=dtypes.int32) + ones = array_ops.ones(array_ops.shape(x), dtype=dtypes.int32) + + # The first step in the Sturm sequence recurrence + # requires special care if x is equal to alpha[0]. + def sturm_step0(): + q = alpha[0] - x + count = array_ops.where(q < 0, ones, zeros) + q = array_ops.where( + math_ops.equal(alpha[0], x), alpha0_perturbation, q) + return q, count + + # Subsequent steps all take this form: + def sturm_step(i, q, count): + q = alpha[i] - beta_sq[i - 1] / q - x + count = array_ops.where(q <= pivmin, count + 1, count) + q = array_ops.where(q <= pivmin, math_ops.minimum(q, -pivmin), q) + return q, count + + # The first step initializes q and count. + q, count = sturm_step0() + + # Peel off ((n-1) % blocksize) steps from the main loop, so we can run + # the bulk of the iterations unrolled by a factor of blocksize. + blocksize = 16 + i = 1 + peel = (n - 1) % blocksize + unroll_cnt = peel + + def unrolled_steps(start, q, count): + for j in range(unroll_cnt): + q, count = sturm_step(start + j, q, count) + return start + unroll_cnt, q, count + + i, q, count = unrolled_steps(i, q, count) + + # Run the remaining steps of the Sturm sequence using a partially + # unrolled while loop. + unroll_cnt = blocksize + cond = lambda i, q, count: math_ops.less(i, n) + _, _, count = while_loop.while_loop( + cond, unrolled_steps, [i, q, count], back_prop=False) + return count + + with ops.name_scope('compute_eigenvalues'): + if alpha.dtype.is_complex: + alpha = math_ops.real(alpha) + beta_sq = math_ops.real(math_ops.conj(beta) * beta) + beta_abs = math_ops.sqrt(beta_sq) + else: + beta_sq = math_ops.square(beta) + beta_abs = math_ops.abs(beta) + + # Estimate the largest and smallest eigenvalues of T using the + # Gershgorin circle theorem. + finfo = np.finfo(alpha.dtype.as_numpy_dtype) + off_diag_abs_row_sum = array_ops.concat( + [beta_abs[:1], beta_abs[:-1] + beta_abs[1:], beta_abs[-1:]], axis=0) + lambda_est_max = math_ops.minimum( + finfo.max, math_ops.reduce_max(alpha + off_diag_abs_row_sum)) + lambda_est_min = math_ops.maximum( + finfo.min, math_ops.reduce_min(alpha - off_diag_abs_row_sum)) + # Upper bound on 2-norm of T. + t_norm = math_ops.maximum( + math_ops.abs(lambda_est_min), math_ops.abs(lambda_est_max)) + + # Compute the smallest allowed pivot in the Sturm sequence to avoid + # overflow. + one = np.ones([], dtype=alpha.dtype.as_numpy_dtype) + safemin = np.maximum(one / finfo.max, (one + finfo.eps) * finfo.tiny) + pivmin = safemin * math_ops.maximum(one, math_ops.reduce_max(beta_sq)) + alpha0_perturbation = math_ops.square(finfo.eps * beta_abs[0]) + abs_tol = finfo.eps * t_norm + if tol: + abs_tol = math_ops.maximum(tol, abs_tol) + # In the worst case, when the absolute tolerance is eps*lambda_est_max + # and lambda_est_max = -lambda_est_min, we have to take as many + # bisection steps as there are bits in the mantissa plus 1. + max_it = finfo.nmant + 1 + + # Determine the indices of the desired eigenvalues, based on select + # and select_range. + asserts = None + if select == 'a': + target_counts = math_ops.range(n) + elif select == 'i': + asserts = check_ops.assert_less_equal( + select_range[0], + select_range[1], + message='Got empty index range in select_range.') + target_counts = math_ops.range(select_range[0], select_range[1] + 1) + elif select == 'v': + asserts = check_ops.assert_less( + select_range[0], + select_range[1], + message='Got empty interval in select_range.') + else: + raise ValueError("'select must have a value in {'a', 'i', 'v'}.") + + if asserts: + with ops.control_dependencies([asserts]): + alpha = array_ops.identity(alpha) + + # Run binary search for all desired eigenvalues in parallel, starting + # from an interval slightly wider than the estimated + # [lambda_est_min, lambda_est_max]. + fudge = 2.1 # We widen starting interval the Gershgorin interval a bit. + norm_slack = math_ops.cast(n, alpha.dtype) * fudge * finfo.eps * t_norm + if select in {'a', 'i'}: + lower = lambda_est_min - norm_slack - 2 * fudge * pivmin + upper = lambda_est_max + norm_slack + fudge * pivmin + else: + # Count the number of eigenvalues in the given range. + lower = select_range[0] - norm_slack - 2 * fudge * pivmin + upper = select_range[1] + norm_slack + fudge * pivmin + first = _sturm(alpha, beta_sq, pivmin, alpha0_perturbation, lower) + last = _sturm(alpha, beta_sq, pivmin, alpha0_perturbation, upper) + target_counts = math_ops.range(first, last) + + # Pre-broadcast the scalars used in the Sturm sequence for improved + # performance. + upper = math_ops.minimum(upper, finfo.max) + lower = math_ops.maximum(lower, finfo.min) + target_shape = array_ops.shape(target_counts) + lower = array_ops.broadcast_to(lower, shape=target_shape) + upper = array_ops.broadcast_to(upper, shape=target_shape) + pivmin = array_ops.broadcast_to(pivmin, target_shape) + alpha0_perturbation = array_ops.broadcast_to(alpha0_perturbation, + target_shape) + + # We compute the midpoint as 0.5*lower + 0.5*upper to avoid overflow in + # (lower + upper) or (upper - lower) when the matrix has eigenvalues + # with magnitude greater than finfo.max / 2. + def midpoint(lower, upper): + return (0.5 * lower) + (0.5 * upper) + + def continue_binary_search(i, lower, upper): + return math_ops.logical_and( + math_ops.less(i, max_it), + math_ops.less(abs_tol, math_ops.reduce_max(upper - lower))) + + def binary_search_step(i, lower, upper): + mid = midpoint(lower, upper) + counts = _sturm(alpha, beta_sq, pivmin, alpha0_perturbation, mid) + lower = array_ops.where(counts <= target_counts, mid, lower) + upper = array_ops.where(counts > target_counts, mid, upper) + return i + 1, lower, upper + + # Start parallel binary searches. + _, lower, upper = while_loop.while_loop(continue_binary_search, + binary_search_step, + [0, lower, upper]) + return midpoint(lower, upper) + + def _compute_eigenvectors(alpha, beta, eigvals): + """Implements inverse iteration to compute eigenvectors.""" + with ops.name_scope('compute_eigenvectors'): + k = array_ops.size(eigvals) + n = array_ops.size(alpha) + alpha = math_ops.cast(alpha, dtype=beta.dtype) + + # Eigenvectors corresponding to cluster of close eigenvalues are + # not unique and need to be explicitly orthogonalized. Here we + # identify such clusters. Note: This function assumes that + # eigenvalues are sorted in non-decreasing order. + gap = eigvals[1:] - eigvals[:-1] + eps = np.finfo(eigvals.dtype.as_numpy_dtype).eps + t_norm = math_ops.maximum( + math_ops.abs(eigvals[0]), math_ops.abs(eigvals[-1])) + gaptol = np.sqrt(eps) * t_norm + # Find the beginning and end of runs of eigenvectors corresponding + # to eigenvalues closer than "gaptol", which will need to be + # orthogonalized against each other. + close = math_ops.less(gap, gaptol) + left_neighbor_close = array_ops.concat([[False], close], axis=0) + right_neighbor_close = array_ops.concat([close, [False]], axis=0) + ortho_interval_start = math_ops.logical_and( + math_ops.logical_not(left_neighbor_close), right_neighbor_close) + ortho_interval_start = array_ops.squeeze( + array_ops.where_v2(ortho_interval_start), axis=-1) + ortho_interval_end = math_ops.logical_and( + left_neighbor_close, math_ops.logical_not(right_neighbor_close)) + ortho_interval_end = array_ops.squeeze( + array_ops.where_v2(ortho_interval_end), axis=-1) + 1 + num_clusters = array_ops.size(ortho_interval_end) + + # We perform inverse iteration for all eigenvectors in parallel, + # starting from a random set of vectors, until all have converged. + v0 = math_ops.cast( + stateless_random_ops.stateless_random_normal( + shape=(k, n), seed=[7, 42]), + dtype=beta.dtype) + nrm_v = norm(v0, axis=1) + v0 = v0 / nrm_v[:, array_ops.newaxis] + zero_nrm = constant_op.constant(0, shape=nrm_v.shape, dtype=nrm_v.dtype) + + # Replicate alpha-eigvals(ik) and beta across the k eigenvectors so we + # can solve the k systems + # [T - eigvals(i)*eye(n)] x_i = r_i + # simultaneously using the batching mechanism. + eigvals_cast = math_ops.cast(eigvals, dtype=beta.dtype) + alpha_shifted = ( + alpha[array_ops.newaxis, :] - eigvals_cast[:, array_ops.newaxis]) + beta = array_ops.tile(beta[array_ops.newaxis, :], [k, 1]) + diags = [beta, alpha_shifted, math_ops.conj(beta)] + + def orthogonalize_close_eigenvectors(eigenvectors): + # Eigenvectors corresponding to a cluster of close eigenvalues are not + # uniquely defined, but the subspace they span is. To avoid numerical + # instability, we explicitly mutually orthogonalize such eigenvectors + # after each step of inverse iteration. It is customary to use + # modified Gram-Schmidt for this, but this is not very efficient + # on some platforms, so here we defer to the QR decomposition in + # TensorFlow. + def orthogonalize_cluster(cluster_idx, eigenvectors): + start = ortho_interval_start[cluster_idx] + end = ortho_interval_end[cluster_idx] + update_indices = array_ops.expand_dims( + math_ops.range(start, end), -1) + vectors_in_cluster = eigenvectors[start:end, :] + # We use the builtin QR factorization to orthonormalize the + # vectors in the cluster. + q, _ = qr(transpose(vectors_in_cluster)) + vectors_to_update = transpose(q) + eigenvectors = array_ops.tensor_scatter_nd_update( + eigenvectors, update_indices, vectors_to_update) + return cluster_idx + 1, eigenvectors + + _, eigenvectors = while_loop.while_loop( + lambda i, ev: math_ops.less(i, num_clusters), + orthogonalize_cluster, [0, eigenvectors]) + return eigenvectors + + def continue_iteration(i, _, nrm_v, nrm_v_old): + max_it = 5 # Taken from LAPACK xSTEIN. + min_norm_growth = 0.1 + norm_growth_factor = constant_op.constant( + 1 + min_norm_growth, dtype=nrm_v.dtype) + # We stop the inverse iteration when we reach the maximum number of + # iterations or the norm growths is less than 10%. + return math_ops.logical_and( + math_ops.less(i, max_it), + math_ops.reduce_any( + math_ops.greater_equal( + math_ops.real(nrm_v), + math_ops.real(norm_growth_factor * nrm_v_old)))) + + def inverse_iteration_step(i, v, nrm_v, nrm_v_old): + v = tridiagonal_solve( + diags, + v, + diagonals_format='sequence', + partial_pivoting=True, + perturb_singular=True) + nrm_v_old = nrm_v + nrm_v = norm(v, axis=1) + v = v / nrm_v[:, array_ops.newaxis] + v = orthogonalize_close_eigenvectors(v) + return i + 1, v, nrm_v, nrm_v_old + + _, v, nrm_v, _ = while_loop.while_loop(continue_iteration, + inverse_iteration_step, + [0, v0, nrm_v, zero_nrm]) + return transpose(v) + + alpha = ops.convert_to_tensor(alpha, name='alpha') + n = alpha.shape[0] + if n <= 1: + return math_ops.real(alpha) + beta = ops.convert_to_tensor(beta, name='beta') + + if alpha.dtype != beta.dtype: + raise ValueError("'alpha' and 'beta' must have the same type.") + + eigvals = _compute_eigenvalues(alpha, beta) + if eigvals_only: + return eigvals + + eigvectors = _compute_eigenvectors(alpha, beta, eigvals) + return eigvals, eigvectors diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..591d50d1c089a4f323b1b14c0dcbbe5adb7c08b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator.py @@ -0,0 +1,1690 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base class for linear operators.""" + +import abc +import contextlib + +import numpy as np + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.module import module +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.ops.linalg import slicing +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +__all__ = ["LinearOperator"] + + +# pylint: disable=protected-access +class _LinearOperatorGradient( + composite_tensor_gradient.CompositeTensorGradient): + """Composite tensor gradient for `LinearOperator`.""" + + def get_gradient_components(self, value): + return value._type_spec._to_components(value) + + def replace_gradient_components(self, value, components): + flat_components = nest.flatten(components) + + # If all component gradients are disconnected, return None. + if all(c is None for c in flat_components): + return None + + # TODO(b/286565628): Update this once `CompositeTensorGradient` fully + # supports `tf.UnconnectedGradients.ZERO`. + # Replace individual disconnected component gradients with zeros. + value_components = value._type_spec._to_components(value) + flat_grad_components = [] + for gc, vc in zip(flat_components, nest.flatten(value_components)): + if gc is None: + flat_grad_components.append( + nest.map_structure( + lambda x: array_ops.zeros_like(x, dtype=value.dtype), + vc, + expand_composites=True)) + else: + flat_grad_components.append(gc) + grad_components = nest.pack_sequence_as( + value_components, flat_grad_components) + return value._type_spec._from_components(grad_components) +# pylint: enable=protected-access + + +# TODO(langmore) Use matrix_solve_ls for singular or non-square matrices. +@tf_export("linalg.LinearOperator") +class LinearOperator( + module.Module, composite_tensor.CompositeTensor, metaclass=abc.ABCMeta): + """Base class defining a [batch of] linear operator[s]. + + Subclasses of `LinearOperator` provide access to common methods on a + (batch) matrix, without the need to materialize the matrix. This allows: + + * Matrix free computations + * Operators that take advantage of special structure, while providing a + consistent API to users. + + #### Subclassing + + To enable a public method, subclasses should implement the leading-underscore + version of the method. The argument signature should be identical except for + the omission of `name="..."`. For example, to enable + `matmul(x, adjoint=False, name="matmul")` a subclass should implement + `_matmul(x, adjoint=False)`. + + #### Performance contract + + Subclasses should only implement the assert methods + (e.g. `assert_non_singular`) if they can be done in less than `O(N^3)` + time. + + Class docstrings should contain an explanation of computational complexity. + Since this is a high-performance library, attention should be paid to detail, + and explanations can include constants as well as Big-O notation. + + #### Shape compatibility + + `LinearOperator` subclasses should operate on a [batch] matrix with + compatible shape. Class docstrings should define what is meant by compatible + shape. Some subclasses may not support batching. + + Examples: + + `x` is a batch matrix with compatible shape for `matmul` if + + ``` + operator.shape = [B1,...,Bb] + [M, N], b >= 0, + x.shape = [B1,...,Bb] + [N, R] + ``` + + `rhs` is a batch matrix with compatible shape for `solve` if + + ``` + operator.shape = [B1,...,Bb] + [M, N], b >= 0, + rhs.shape = [B1,...,Bb] + [M, R] + ``` + + #### Example docstring for subclasses. + + This operator acts like a (batch) matrix `A` with shape + `[B1,...,Bb, M, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `m x n` matrix. Again, this matrix `A` may not be materialized, but for + purposes of identifying and working with compatible arguments the shape is + relevant. + + Examples: + + ```python + some_tensor = ... shape = ???? + operator = MyLinOp(some_tensor) + + operator.shape() + ==> [2, 4, 4] + + operator.log_abs_determinant() + ==> Shape [2] Tensor + + x = ... Shape [2, 4, 5] Tensor + + operator.matmul(x) + ==> Shape [2, 4, 5] Tensor + ``` + + #### Shape compatibility + + This operator acts on batch matrices with compatible shape. + FILL IN WHAT IS MEANT BY COMPATIBLE SHAPE + + #### Performance + + FILL THIS IN + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + + #### Initialization parameters + + All subclasses of `LinearOperator` are expected to pass a `parameters` + argument to `super().__init__()`. This should be a `dict` containing + the unadulterated arguments passed to the subclass `__init__`. For example, + `MyLinearOperator` with an initializer should look like: + + ```python + def __init__(self, operator, is_square=False, name=None): + parameters = dict( + operator=operator, + is_square=is_square, + name=name + ) + ... + super().__init__(..., parameters=parameters) + ``` + + Users can then access `my_linear_operator.parameters` to see all arguments + passed to its initializer. + """ + + # TODO(b/143910018) Remove graph_parents in V3. + @deprecation.deprecated_args(None, "Do not pass `graph_parents`. They will " + " no longer be used.", "graph_parents") + def __init__(self, + dtype, + graph_parents=None, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name=None, + parameters=None): + """Initialize the `LinearOperator`. + + **This is a private method for subclass use.** + **Subclasses should copy-paste this `__init__` documentation.** + + Args: + dtype: The type of the this `LinearOperator`. Arguments to `matmul` and + `solve` will have to be this type. + graph_parents: (Deprecated) Python list of graph prerequisites of this + `LinearOperator` Typically tensors that are passed during initialization + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `dtype` is real, this is equivalent to being symmetric. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + parameters: Python `dict` of parameters used to instantiate this + `LinearOperator`. + + Raises: + ValueError: If any member of graph_parents is `None` or not a `Tensor`. + ValueError: If hints are set incorrectly. + """ + # Check and auto-set flags. + if is_positive_definite: + if is_non_singular is False: + raise ValueError("A positive definite matrix is always non-singular.") + is_non_singular = True + + if is_non_singular: + if is_square is False: + raise ValueError("A non-singular matrix is always square.") + is_square = True + + if is_self_adjoint: + if is_square is False: + raise ValueError("A self-adjoint matrix is always square.") + is_square = True + + self._is_square_set_or_implied_by_hints = is_square + + if graph_parents is not None: + self._set_graph_parents(graph_parents) + else: + self._graph_parents = [] + self._dtype = dtypes.as_dtype(dtype).base_dtype if dtype else dtype + self._is_non_singular = is_non_singular + self._is_self_adjoint = is_self_adjoint + self._is_positive_definite = is_positive_definite + self._parameters = self._no_dependency(parameters) + self._parameters_sanitized = False + self._name = name or type(self).__name__ + + @contextlib.contextmanager + def _name_scope(self, name=None): # pylint: disable=method-hidden + """Helper function to standardize op scope.""" + full_name = self.name + if name is not None: + full_name += "/" + name + with ops.name_scope(full_name) as scope: + yield scope + + @property + def parameters(self): + """Dictionary of parameters used to instantiate this `LinearOperator`.""" + return dict(self._parameters) + + @property + def dtype(self): + """The `DType` of `Tensor`s handled by this `LinearOperator`.""" + return self._dtype + + @property + def name(self): + """Name prepended to all ops created by this `LinearOperator`.""" + return self._name + + @property + @deprecation.deprecated(None, "Do not call `graph_parents`.") + def graph_parents(self): + """List of graph dependencies of this `LinearOperator`.""" + return self._graph_parents + + @property + def is_non_singular(self): + return self._is_non_singular + + @property + def is_self_adjoint(self): + return self._is_self_adjoint + + @property + def is_positive_definite(self): + return self._is_positive_definite + + @property + def is_square(self): + """Return `True/False` depending on if this operator is square.""" + # Static checks done after __init__. Why? Because domain/range dimension + # sometimes requires lots of work done in the derived class after init. + auto_square_check = self.domain_dimension == self.range_dimension + if self._is_square_set_or_implied_by_hints is False and auto_square_check: + raise ValueError( + "User set is_square hint to False, but the operator was square.") + if self._is_square_set_or_implied_by_hints is None: + return auto_square_check + + return self._is_square_set_or_implied_by_hints + + @abc.abstractmethod + def _shape(self): + # Write this in derived class to enable all static shape methods. + raise NotImplementedError("_shape is not implemented.") + + @property + def shape(self): + """`TensorShape` of this `LinearOperator`. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns + `TensorShape([B1,...,Bb, M, N])`, equivalent to `A.shape`. + + Returns: + `TensorShape`, statically determined, may be undefined. + """ + return self._shape() + + def _shape_tensor(self): + # This is not an abstractmethod, since we want derived classes to be able to + # override this with optional kwargs, which can reduce the number of + # `convert_to_tensor` calls. See derived classes for examples. + raise NotImplementedError("_shape_tensor is not implemented.") + + def shape_tensor(self, name="shape_tensor"): + """Shape of this `LinearOperator`, determined at runtime. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns a `Tensor` holding + `[B1,...,Bb, M, N]`, equivalent to `tf.shape(A)`. + + Args: + name: A name for this `Op`. + + Returns: + `int32` `Tensor` + """ + with self._name_scope(name): # pylint: disable=not-callable + # Prefer to use statically defined shape if available. + if self.shape.is_fully_defined(): + return linear_operator_util.shape_tensor(self.shape.as_list()) + else: + return self._shape_tensor() + + @property + def batch_shape(self): + """`TensorShape` of batch dimensions of this `LinearOperator`. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns + `TensorShape([B1,...,Bb])`, equivalent to `A.shape[:-2]` + + Returns: + `TensorShape`, statically determined, may be undefined. + """ + # Derived classes get this "for free" once .shape is implemented. + return self.shape[:-2] + + def batch_shape_tensor(self, name="batch_shape_tensor"): + """Shape of batch dimensions of this operator, determined at runtime. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns a `Tensor` holding + `[B1,...,Bb]`. + + Args: + name: A name for this `Op`. + + Returns: + `int32` `Tensor` + """ + # Derived classes get this "for free" once .shape() is implemented. + with self._name_scope(name): # pylint: disable=not-callable + return self._batch_shape_tensor() + + def _batch_shape_tensor(self, shape=None): + # `shape` may be passed in if this can be pre-computed in a + # more efficient manner, e.g. without excessive Tensor conversions. + if self.batch_shape.is_fully_defined(): + return linear_operator_util.shape_tensor( + self.batch_shape.as_list(), name="batch_shape") + else: + shape = self.shape_tensor() if shape is None else shape + return shape[:-2] + + @property + def tensor_rank(self, name="tensor_rank"): + """Rank (in the sense of tensors) of matrix corresponding to this operator. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`. + + Args: + name: A name for this `Op`. + + Returns: + Python integer, or None if the tensor rank is undefined. + """ + # Derived classes get this "for free" once .shape() is implemented. + with self._name_scope(name): # pylint: disable=not-callable + return self.shape.ndims + + def tensor_rank_tensor(self, name="tensor_rank_tensor"): + """Rank (in the sense of tensors) of matrix corresponding to this operator. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`. + + Args: + name: A name for this `Op`. + + Returns: + `int32` `Tensor`, determined at runtime. + """ + # Derived classes get this "for free" once .shape() is implemented. + with self._name_scope(name): # pylint: disable=not-callable + return self._tensor_rank_tensor() + + def _tensor_rank_tensor(self, shape=None): + # `shape` may be passed in if this can be pre-computed in a + # more efficient manner, e.g. without excessive Tensor conversions. + if self.tensor_rank is not None: + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.tensor_rank + ) + else: + shape = self.shape_tensor() if shape is None else shape + return array_ops.size(shape) + + @property + def domain_dimension(self): + """Dimension (in the sense of vector spaces) of the domain of this operator. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `N`. + + Returns: + `Dimension` object. + """ + # Derived classes get this "for free" once .shape is implemented. + if self.shape.rank is None: + return tensor_shape.Dimension(None) + else: + return self.shape.dims[-1] + + def domain_dimension_tensor(self, name="domain_dimension_tensor"): + """Dimension (in the sense of vector spaces) of the domain of this operator. + + Determined at runtime. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `N`. + + Args: + name: A name for this `Op`. + + Returns: + `int32` `Tensor` + """ + # Derived classes get this "for free" once .shape() is implemented. + with self._name_scope(name): # pylint: disable=not-callable + return self._domain_dimension_tensor() + + def _domain_dimension_tensor(self, shape=None): + # `shape` may be passed in if this can be pre-computed in a + # more efficient manner, e.g. without excessive Tensor conversions. + dim_value = tensor_shape.dimension_value(self.domain_dimension) + if dim_value is not None: + return tensor_conversion.convert_to_tensor_v2_with_dispatch(dim_value) + else: + shape = self.shape_tensor() if shape is None else shape + return shape[-1] + + @property + def range_dimension(self): + """Dimension (in the sense of vector spaces) of the range of this operator. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `M`. + + Returns: + `Dimension` object. + """ + # Derived classes get this "for free" once .shape is implemented. + if self.shape.dims: + return self.shape.dims[-2] + else: + return tensor_shape.Dimension(None) + + def range_dimension_tensor(self, name="range_dimension_tensor"): + """Dimension (in the sense of vector spaces) of the range of this operator. + + Determined at runtime. + + If this operator acts like the batch matrix `A` with + `A.shape = [B1,...,Bb, M, N]`, then this returns `M`. + + Args: + name: A name for this `Op`. + + Returns: + `int32` `Tensor` + """ + # Derived classes get this "for free" once .shape() is implemented. + with self._name_scope(name): # pylint: disable=not-callable + return self._range_dimension_tensor() + + def _range_dimension_tensor(self, shape=None): + # `shape` may be passed in if this can be pre-computed in a + # more efficient manner, e.g. without excessive Tensor conversions. + dim_value = tensor_shape.dimension_value(self.range_dimension) + if dim_value is not None: + return tensor_conversion.convert_to_tensor_v2_with_dispatch(dim_value) + else: + shape = self.shape_tensor() if shape is None else shape + return shape[-2] + + def _assert_non_singular(self): + """Private default implementation of _assert_non_singular.""" + logging.warn( + "Using (possibly slow) default implementation of assert_non_singular." + " Requires conversion to a dense matrix and O(N^3) operations.") + if self._can_use_cholesky(): + return self.assert_positive_definite() + else: + singular_values = linalg_ops.svd(self.to_dense(), compute_uv=False) + # TODO(langmore) Add .eig and .cond as methods. + cond = (math_ops.reduce_max(singular_values, axis=-1) / + math_ops.reduce_min(singular_values, axis=-1)) + return check_ops.assert_less( + cond, + self._max_condition_number_to_be_non_singular(), + message="Singular matrix up to precision epsilon.") + + def _max_condition_number_to_be_non_singular(self): + """Return the maximum condition number that we consider nonsingular.""" + with ops.name_scope("max_nonsingular_condition_number"): + dtype_eps = np.finfo(self.dtype.as_numpy_dtype).eps + eps = math_ops.cast( + math_ops.reduce_max([ + 100., + math_ops.cast(self.range_dimension_tensor(), self.dtype), + math_ops.cast(self.domain_dimension_tensor(), self.dtype) + ]), self.dtype) * dtype_eps + return 1. / eps + + def assert_non_singular(self, name="assert_non_singular"): + """Returns an `Op` that asserts this operator is non singular. + + This operator is considered non-singular if + + ``` + ConditionNumber < max{100, range_dimension, domain_dimension} * eps, + eps := np.finfo(self.dtype.as_numpy_dtype).eps + ``` + + Args: + name: A string name to prepend to created ops. + + Returns: + An `Assert` `Op`, that, when run, will raise an `InvalidArgumentError` if + the operator is singular. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._assert_non_singular() + + def _assert_positive_definite(self): + """Default implementation of _assert_positive_definite.""" + logging.warn( + "Using (possibly slow) default implementation of " + "assert_positive_definite." + " Requires conversion to a dense matrix and O(N^3) operations.") + # If the operator is self-adjoint, then checking that + # Cholesky decomposition succeeds + results in positive diag is necessary + # and sufficient. + if self.is_self_adjoint: + return check_ops.assert_positive( + array_ops.matrix_diag_part(linalg_ops.cholesky(self.to_dense())), + message="Matrix was not positive definite.") + # We have no generic check for positive definite. + raise NotImplementedError("assert_positive_definite is not implemented.") + + def assert_positive_definite(self, name="assert_positive_definite"): + """Returns an `Op` that asserts this operator is positive definite. + + Here, positive definite means that the quadratic form `x^H A x` has positive + real part for all nonzero `x`. Note that we do not require the operator to + be self-adjoint to be positive definite. + + Args: + name: A name to give this `Op`. + + Returns: + An `Assert` `Op`, that, when run, will raise an `InvalidArgumentError` if + the operator is not positive definite. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._assert_positive_definite() + + def _assert_self_adjoint(self): + dense = self.to_dense() + logging.warn( + "Using (possibly slow) default implementation of assert_self_adjoint." + " Requires conversion to a dense matrix.") + return check_ops.assert_equal( + dense, + linalg.adjoint(dense), + message="Matrix was not equal to its adjoint.") + + def assert_self_adjoint(self, name="assert_self_adjoint"): + """Returns an `Op` that asserts this operator is self-adjoint. + + Here we check that this operator is *exactly* equal to its hermitian + transpose. + + Args: + name: A string name to prepend to created ops. + + Returns: + An `Assert` `Op`, that, when run, will raise an `InvalidArgumentError` if + the operator is not self-adjoint. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._assert_self_adjoint() + + def _check_input_dtype(self, arg): + """Check that arg.dtype == self.dtype.""" + if arg.dtype.base_dtype != self.dtype: + raise TypeError( + "Expected argument to have dtype %s. Found: %s in tensor %s" % + (self.dtype, arg.dtype, arg)) + + @abc.abstractmethod + def _matmul(self, x, adjoint=False, adjoint_arg=False): + raise NotImplementedError("_matmul is not implemented.") + + def matmul( + self, + x, + adjoint=False, + adjoint_arg=False, + name="matmul", + ): + """Transform [batch] matrix `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + X = ... # shape [..., N, R], batch matrix, R > 0. + + Y = operator.matmul(X) + Y.shape + ==> [..., M, R] + + Y[..., :, r] = sum_j A[..., :, j] X[j, r] + ``` + + Args: + x: `LinearOperator` or `Tensor` with compatible shape and same `dtype` as + `self`. See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + adjoint_arg: Python `bool`. If `True`, compute `A x^H` where `x^H` is + the hermitian transpose (transposition and complex conjugation). + name: A name for this `Op`. + + Returns: + A `LinearOperator` or `Tensor` with shape `[..., M, R]` and same `dtype` + as `self`. + """ + if isinstance(x, LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = x.adjoint() if adjoint_arg else x + + if (right_operator.range_dimension is not None and + left_operator.domain_dimension is not None and + right_operator.range_dimension != left_operator.domain_dimension): + raise ValueError( + "Operators are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_matmul(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + + self_dim = -2 if adjoint else -1 + arg_dim = -1 if adjoint_arg else -2 + tensor_shape.dimension_at_index( + self.shape, self_dim).assert_is_compatible_with( + x.shape[arg_dim]) + + return self._matmul(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _linop_matmul( + self, left_operator: "LinearOperator", right_operator: "LinearOperator" + ) -> "LinearOperator": + # instance of linear_operator_identity.LinearOperatorIdentity + if hasattr(right_operator, "_ones_diag") and not hasattr( + right_operator, "multiplier" + ): + return left_operator + + # instance of linear_operator_zeros.LinearOperatorZeros + elif hasattr(right_operator, "_zeros_diag"): + if not right_operator.is_square or not left_operator.is_square: + raise ValueError( + "Matmul with non-square `LinearOperator`s or " + "non-square `LinearOperatorZeros` not supported at this time." + ) + return right_operator + + else: + # Generic matmul of two `LinearOperator`s. + is_square = property_hint_util.is_square(left_operator, right_operator) + is_non_singular = None + is_self_adjoint = None + is_positive_definite = None + + if is_square: + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator + ) + # is_square can be None, so the explicit check for False is needed. + elif is_square is False: # pylint:disable=g-bool-id-comparison + is_non_singular = False + is_self_adjoint = False + is_positive_definite = False + + # LinearOperator outputs a LinearOperatorComposition instance, which + # inherits from LinearOperator. The inline import is necessary to avoid + # errors due to this cyclic dependency. + from tensorflow.python.ops.linalg import linear_operator_composition # pylint: disable=g-import-not-at-top + + return linear_operator_composition.LinearOperatorComposition( + operators=[left_operator, right_operator], + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + ) + + def __matmul__(self, other): + return self.matmul(other) + + def _matvec(self, x, adjoint=False): + x_mat = array_ops.expand_dims(x, axis=-1) + y_mat = self.matmul(x_mat, adjoint=adjoint) + return array_ops.squeeze(y_mat, axis=-1) + + def matvec(self, x, adjoint=False, name="matvec"): + """Transform [batch] vector `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + + X = ... # shape [..., N], batch vector + + Y = operator.matvec(X) + Y.shape + ==> [..., M] + + Y[..., :] = sum_j A[..., :, j] X[..., j] + ``` + + Args: + x: `Tensor` with compatible shape and same `dtype` as `self`. + `x` is treated as a [batch] vector meaning for every set of leading + dimensions, the last dimension defines a vector. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + name: A name for this `Op`. + + Returns: + A `Tensor` with shape `[..., M]` and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + self_dim = -2 if adjoint else -1 + tensor_shape.dimension_at_index( + self.shape, self_dim).assert_is_compatible_with(x.shape[-1]) + return self._matvec(x, adjoint=adjoint) + + def _determinant(self): + logging.warn( + "Using (possibly slow) default implementation of determinant." + " Requires conversion to a dense matrix and O(N^3) operations.") + if self._can_use_cholesky(): + return math_ops.exp(self.log_abs_determinant()) + return linalg_ops.matrix_determinant(self.to_dense()) + + def determinant(self, name="det"): + """Determinant for every batch member. + + Args: + name: A name for this `Op`. + + Returns: + `Tensor` with shape `self.batch_shape` and same `dtype` as `self`. + + Raises: + NotImplementedError: If `self.is_square` is `False`. + """ + if self.is_square is False: + raise NotImplementedError( + "Determinant not implemented for an operator that is expected to " + "not be square.") + with self._name_scope(name): # pylint: disable=not-callable + return self._determinant() + + def _log_abs_determinant(self): + logging.warn( + "Using (possibly slow) default implementation of determinant." + " Requires conversion to a dense matrix and O(N^3) operations.") + if self._can_use_cholesky(): + diag = array_ops.matrix_diag_part(linalg_ops.cholesky(self.to_dense())) + return 2 * math_ops.reduce_sum(math_ops.log(diag), axis=[-1]) + _, log_abs_det = linalg.slogdet(self.to_dense()) + return log_abs_det + + def log_abs_determinant(self, name="log_abs_det"): + """Log absolute value of determinant for every batch member. + + Args: + name: A name for this `Op`. + + Returns: + `Tensor` with shape `self.batch_shape` and same `dtype` as `self`. + + Raises: + NotImplementedError: If `self.is_square` is `False`. + """ + if self.is_square is False: + raise NotImplementedError( + "Determinant not implemented for an operator that is expected to " + "not be square.") + with self._name_scope(name): # pylint: disable=not-callable + return self._log_abs_determinant() + + def _dense_solve(self, rhs, adjoint=False, adjoint_arg=False): + """Solve by conversion to a dense matrix.""" + if self.is_square is False: # pylint: disable=g-bool-id-comparison + raise NotImplementedError( + "Solve is not yet implemented for non-square operators.") + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + if self._can_use_cholesky(): + return linalg_ops.cholesky_solve( + linalg_ops.cholesky(self.to_dense()), rhs) + return linear_operator_util.matrix_solve_with_broadcast( + self.to_dense(), rhs, adjoint=adjoint) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + """Default implementation of _solve.""" + logging.warn( + "Using (possibly slow) default implementation of solve." + " Requires conversion to a dense matrix and O(N^3) operations.") + return self._dense_solve(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def solve(self, rhs, adjoint=False, adjoint_arg=False, name="solve"): + """Solve (exact or approx) `R` (batch) systems of equations: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve R > 0 linear systems for every member of the batch. + RHS = ... # shape [..., M, R] + + X = operator.solve(RHS) + # X[..., :, r] is the solution to the r'th linear system + # sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r] + + operator.matmul(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator and compatible shape. + `rhs` is treated like a [batch] matrix meaning for every set of leading + dimensions, the last two dimensions defines a matrix. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + adjoint_arg: Python `bool`. If `True`, solve `A X = rhs^H` where `rhs^H` + is the hermitian transpose (transposition and complex conjugation). + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N, R]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + if self.is_non_singular is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "be singular.") + if self.is_square is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "not be square.") + if isinstance(rhs, LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = rhs.adjoint() if adjoint_arg else rhs + + if (right_operator.range_dimension is not None and + left_operator.domain_dimension is not None and + right_operator.range_dimension != left_operator.domain_dimension): + raise ValueError( + "Operators are incompatible. Expected `rhs` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_solve(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + + self_dim = -1 if adjoint else -2 + arg_dim = -1 if adjoint_arg else -2 + tensor_shape.dimension_at_index( + self.shape, self_dim).assert_is_compatible_with( + rhs.shape[arg_dim]) + + return self._solve(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _linop_solve( + self, left_operator: "LinearOperator", right_operator: "LinearOperator" + ) -> "LinearOperator": + # instance of linear_operator_identity.LinearOperatorIdentity + if hasattr(right_operator, "_ones_diag") and not hasattr( + right_operator, "multiplier" + ): + return left_operator.inverse() + + # Generic solve of two `LinearOperator`s. + is_square = property_hint_util.is_square(left_operator, right_operator) + is_non_singular = None + is_self_adjoint = None + is_positive_definite = None + + if is_square: + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator + ) + elif is_square is False: # pylint:disable=g-bool-id-comparison + is_non_singular = False + is_self_adjoint = False + is_positive_definite = False + + # LinearOperator outputs a LinearOperatorComposition instance that contains + # a LinearOperatorInversion instance, both of which + # inherit from LinearOperator. The inline import is necessary to avoid + # errors due to this cyclic dependency. + from tensorflow.python.ops.linalg import linear_operator_composition # pylint: disable=g-import-not-at-top + from tensorflow.python.ops.linalg import linear_operator_inversion # pylint: disable=g-import-not-at-top + + return linear_operator_composition.LinearOperatorComposition( + operators=[ + linear_operator_inversion.LinearOperatorInversion(left_operator), + right_operator, + ], + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + ) + + def _solvevec(self, rhs, adjoint=False): + """Default implementation of _solvevec.""" + rhs_mat = array_ops.expand_dims(rhs, axis=-1) + solution_mat = self.solve(rhs_mat, adjoint=adjoint) + return array_ops.squeeze(solution_mat, axis=-1) + + def solvevec(self, rhs, adjoint=False, name="solve"): + """Solve single equation with best effort: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve one linear system for every member of the batch. + RHS = ... # shape [..., M] + + X = operator.solvevec(RHS) + # X is the solution to the linear system + # sum_j A[..., :, j] X[..., j] = RHS[..., :] + + operator.matvec(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator. + `rhs` is treated like a [batch] vector meaning for every set of leading + dimensions, the last dimension defines a vector. See class docstring + for definition of compatibility regarding batch dimensions. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + with self._name_scope(name): # pylint: disable=not-callable + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + self_dim = -1 if adjoint else -2 + tensor_shape.dimension_at_index( + self.shape, self_dim).assert_is_compatible_with(rhs.shape[-1]) + + return self._solvevec(rhs, adjoint=adjoint) + + def adjoint(self, name: str = "adjoint") -> "LinearOperator": + """Returns the adjoint of the current `LinearOperator`. + + Given `A` representing this `LinearOperator`, return `A*`. + Note that calling `self.adjoint()` and `self.H` are equivalent. + + Args: + name: A name for this `Op`. + + Returns: + `LinearOperator` which represents the adjoint of this `LinearOperator`. + """ + if self.is_self_adjoint is True: # pylint: disable=g-bool-id-comparison + return self + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_adjoint() + + # self.H is equivalent to self.adjoint(). + H = property(adjoint, None) + + def _linop_adjoint(self) -> "LinearOperator": + from tensorflow.python.ops.linalg import linear_operator_adjoint # pylint: disable=g-import-not-at-top + return linear_operator_adjoint.LinearOperatorAdjoint( + self, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=self.is_square) + + def inverse(self, name: str = "inverse") -> "LinearOperator": + """Returns the Inverse of this `LinearOperator`. + + Given `A` representing this `LinearOperator`, return a `LinearOperator` + representing `A^-1`. + + Args: + name: A name scope to use for ops added by this method. + + Returns: + `LinearOperator` representing inverse of this matrix. + + Raises: + ValueError: When the `LinearOperator` is not hinted to be `non_singular`. + """ + if self.is_square is False: # pylint: disable=g-bool-id-comparison + raise ValueError("Cannot take the Inverse: This operator represents " + "a non square matrix.") + if self.is_non_singular is False: # pylint: disable=g-bool-id-comparison + raise ValueError("Cannot take the Inverse: This operator represents " + "a singular matrix.") + + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_inverse() + + def _linop_inverse(self) -> "LinearOperator": + # The in-line import is necessary because linear_operator_inversion.py + # depends on linear_operator.py. The in-line import works because the two + # files are now in the same build target, but if the import were at the top + # of the file there would be a partially-initialized module error caused by + # the code cycle. + from tensorflow.python.ops.linalg import linear_operator_inversion # pylint: disable=g-import-not-at-top + return linear_operator_inversion.LinearOperatorInversion( + self, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=self.is_square) + + def cholesky(self, name: str = "cholesky") -> "LinearOperator": + """Returns a Cholesky factor as a `LinearOperator`. + + Given `A` representing this `LinearOperator`, if `A` is positive definite + self-adjoint, return `L`, where `A = L L^T`, i.e. the cholesky + decomposition. + + Args: + name: A name for this `Op`. + + Returns: + `LinearOperator` which represents the lower triangular matrix + in the Cholesky decomposition. + + Raises: + ValueError: When the `LinearOperator` is not hinted to be positive + definite and self adjoint. + """ + + if not self._can_use_cholesky(): + raise ValueError("Cannot take the Cholesky decomposition: " + "Not a positive definite self adjoint matrix.") + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_cholesky() + + def _linop_cholesky(self) -> "LinearOperator": + from tensorflow.python.ops.linalg import linear_operator_lower_triangular # pylint: disable=g-import-not-at-top + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + linalg_ops.cholesky(self.to_dense()), + is_non_singular=True, + is_self_adjoint=False, + is_square=True) + + def _to_dense(self): + """Generic and often inefficient implementation. Override often.""" + if self.batch_shape.is_fully_defined(): + batch_shape = self.batch_shape + else: + batch_shape = self.batch_shape_tensor() + + dim_value = tensor_shape.dimension_value(self.domain_dimension) + if dim_value is not None: + n = dim_value + else: + n = self.domain_dimension_tensor() + + eye = linalg_ops.eye(num_rows=n, batch_shape=batch_shape, dtype=self.dtype) + return self.matmul(eye) + + def to_dense(self, name="to_dense"): + """Return a dense (batch) matrix representing this operator.""" + with self._name_scope(name): # pylint: disable=not-callable + return self._to_dense() + + def _diag_part(self): + """Generic and often inefficient implementation. Override often.""" + return array_ops.matrix_diag_part(self.to_dense()) + + def diag_part(self, name="diag_part"): + """Efficiently get the [batch] diagonal part of this operator. + + If this operator has shape `[B1,...,Bb, M, N]`, this returns a + `Tensor` `diagonal`, of shape `[B1,...,Bb, min(M, N)]`, where + `diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]`. + + ``` + my_operator = LinearOperatorDiag([1., 2.]) + + # Efficiently get the diagonal + my_operator.diag_part() + ==> [1., 2.] + + # Equivalent, but inefficient method + tf.linalg.diag_part(my_operator.to_dense()) + ==> [1., 2.] + ``` + + Args: + name: A name for this `Op`. + + Returns: + diag_part: A `Tensor` of same `dtype` as self. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._diag_part() + + def _trace(self): + return math_ops.reduce_sum(self.diag_part(), axis=-1) + + def trace(self, name="trace"): + """Trace of the linear operator, equal to sum of `self.diag_part()`. + + If the operator is square, this is also the sum of the eigenvalues. + + Args: + name: A name for this `Op`. + + Returns: + Shape `[B1,...,Bb]` `Tensor` of same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._trace() + + def _add_to_tensor(self, x): + # Override if a more efficient implementation is available. + return self.to_dense() + x + + def add_to_tensor(self, x, name="add_to_tensor"): + """Add matrix represented by this operator to `x`. Equivalent to `A + x`. + + Args: + x: `Tensor` with same `dtype` and shape broadcastable to `self.shape`. + name: A name to give this `Op`. + + Returns: + A `Tensor` with broadcast shape and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + return self._add_to_tensor(x) + + def _eigvals(self): + return linalg_ops.self_adjoint_eigvals(self.to_dense()) + + def eigvals(self, name="eigvals"): + """Returns the eigenvalues of this linear operator. + + If the operator is marked as self-adjoint (via `is_self_adjoint`) + this computation can be more efficient. + + Note: This currently only supports self-adjoint operators. + + Args: + name: A name for this `Op`. + + Returns: + Shape `[B1,...,Bb, N]` `Tensor` of same `dtype` as `self`. + """ + if not self.is_self_adjoint: + raise NotImplementedError("Only self-adjoint matrices are supported.") + with self._name_scope(name): # pylint: disable=not-callable + return self._eigvals() + + def _cond(self): + if not self.is_self_adjoint: + # In general the condition number is the ratio of the + # absolute value of the largest and smallest singular values. + vals = linalg_ops.svd(self.to_dense(), compute_uv=False) + else: + # For self-adjoint matrices, and in general normal matrices, + # we can use eigenvalues. + vals = math_ops.abs(self._eigvals()) + + return (math_ops.reduce_max(vals, axis=-1) / + math_ops.reduce_min(vals, axis=-1)) + + def cond(self, name="cond"): + """Returns the condition number of this linear operator. + + Args: + name: A name for this `Op`. + + Returns: + Shape `[B1,...,Bb]` `Tensor` of same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + return self._cond() + + def _can_use_cholesky(self): + return self.is_self_adjoint and self.is_positive_definite + + def _set_graph_parents(self, graph_parents): + """Set self._graph_parents. Called during derived class init. + + This method allows derived classes to set graph_parents, without triggering + a deprecation warning (which is invoked if `graph_parents` is passed during + `__init__`. + + Args: + graph_parents: Iterable over Tensors. + """ + # TODO(b/143910018) Remove this function in V3. + graph_parents = [] if graph_parents is None else graph_parents + for i, t in enumerate(graph_parents): + if t is None or not (linear_operator_util.is_ref(t) or + tensor_util.is_tf_type(t)): + raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t)) + self._graph_parents = graph_parents + + @property + def _composite_tensor_fields(self): + """A tuple of parameter names to rebuild the `LinearOperator`. + + The tuple contains the names of kwargs to the `LinearOperator`'s constructor + that the `TypeSpec` needs to rebuild the `LinearOperator` instance. + + "is_non_singular", "is_self_adjoint", "is_positive_definite", and + "is_square" are common to all `LinearOperator` subclasses and may be + omitted. + """ + return () + + @property + def _composite_tensor_prefer_static_fields(self): + """A tuple of names referring to parameters that may be treated statically. + + This is a subset of `_composite_tensor_fields`, and contains the names of + of `Tensor`-like args to the `LinearOperator`s constructor that may be + stored as static values, if they are statically known. These are typically + shapes or axis values. + """ + return () + + @property + def _type_spec(self): + # This property will be overwritten by the `@make_composite_tensor` + # decorator. However, we need it so that a valid subclass of the `ABCMeta` + # class `CompositeTensor` can be constructed and passed to the + # `@make_composite_tensor` decorator. + pass + + def _convert_variables_to_tensors(self): + """Recursively converts ResourceVariables in the LinearOperator to Tensors. + + The usage of `self._type_spec._from_components` violates the contract of + `CompositeTensor`, since it is called on a different nested structure + (one containing only `Tensor`s) than `self.type_spec` specifies (one that + may contain `ResourceVariable`s). Since `LinearOperator`'s + `_from_components` method just passes the contents of the nested structure + to `__init__` to rebuild the operator, and any `LinearOperator` that may be + instantiated with `ResourceVariables` may also be instantiated with + `Tensor`s, this usage is valid. + + Returns: + tensor_operator: `self` with all internal Variables converted to Tensors. + """ + # pylint: disable=protected-access + components = self._type_spec._to_components(self) + tensor_components = variable_utils.convert_variables_to_tensors( + components) + return self._type_spec._from_components(tensor_components) + # pylint: enable=protected-access + + def __getitem__(self, slices): + return slicing.batch_slice(self, params_overrides={}, slices=slices) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + """A dict of names to number of dimensions contributing to an operator. + + This is a dictionary of parameter names to `int`s specifying the + number of right-most dimensions contributing to the **matrix** shape of the + densified operator. + If the parameter is a `Tensor`, this is mapped to an `int`. + If the parameter is a `LinearOperator` (called `A`), this specifies the + number of batch dimensions of `A` contributing to this `LinearOperator`s + matrix shape. + If the parameter is a structure, this is a structure of the same type of + `int`s. + """ + return () + + __composite_gradient__ = _LinearOperatorGradient() + + +class _LinearOperatorSpec(type_spec.BatchableTypeSpec): + """A tf.TypeSpec for `LinearOperator` objects.""" + + __slots__ = ("_param_specs", "_non_tensor_params", "_prefer_static_fields") + + def __init__(self, param_specs, non_tensor_params, prefer_static_fields): + """Initializes a new `_LinearOperatorSpec`. + + Args: + param_specs: Python `dict` of `tf.TypeSpec` instances that describe + kwargs to the `LinearOperator`'s constructor that are `Tensor`-like or + `CompositeTensor` subclasses. + non_tensor_params: Python `dict` containing non-`Tensor` and non- + `CompositeTensor` kwargs to the `LinearOperator`'s constructor. + prefer_static_fields: Python `tuple` of strings corresponding to the names + of `Tensor`-like args to the `LinearOperator`s constructor that may be + stored as static values, if known. These are typically shapes, indices, + or axis values. + """ + self._param_specs = param_specs + self._non_tensor_params = non_tensor_params + self._prefer_static_fields = prefer_static_fields + + @classmethod + def from_operator(cls, operator): + """Builds a `_LinearOperatorSpec` from a `LinearOperator` instance. + + Args: + operator: An instance of `LinearOperator`. + + Returns: + linear_operator_spec: An instance of `_LinearOperatorSpec` to be used as + the `TypeSpec` of `operator`. + """ + validation_fields = ("is_non_singular", "is_self_adjoint", + "is_positive_definite", "is_square") + kwargs = _extract_attrs( + operator, + keys=set(operator._composite_tensor_fields + validation_fields)) # pylint: disable=protected-access + + non_tensor_params = {} + param_specs = {} + for k, v in list(kwargs.items()): + type_spec_or_v = _extract_type_spec_recursively(v) + is_tensor = [isinstance(x, type_spec.TypeSpec) + for x in nest.flatten(type_spec_or_v)] + if all(is_tensor): + param_specs[k] = type_spec_or_v + elif not any(is_tensor): + non_tensor_params[k] = v + else: + raise NotImplementedError(f"Field {k} contains a mix of `Tensor` and " + f" non-`Tensor` values.") + + return cls( + param_specs=param_specs, + non_tensor_params=non_tensor_params, + prefer_static_fields=operator._composite_tensor_prefer_static_fields) # pylint: disable=protected-access + + def _to_components(self, obj): + return _extract_attrs(obj, keys=list(self._param_specs)) + + def _from_components(self, components): + kwargs = dict(self._non_tensor_params, **components) + return self.value_type(**kwargs) + + @property + def _component_specs(self): + return self._param_specs + + def _serialize(self): + return (self._param_specs, + self._non_tensor_params, + self._prefer_static_fields) + + def _copy(self, **overrides): + kwargs = { + "param_specs": self._param_specs, + "non_tensor_params": self._non_tensor_params, + "prefer_static_fields": self._prefer_static_fields + } + kwargs.update(overrides) + return type(self)(**kwargs) + + def _batch(self, batch_size): + """Returns a TypeSpec representing a batch of objects with this TypeSpec.""" + return self._copy( + param_specs=nest.map_structure( + lambda spec: spec._batch(batch_size), # pylint: disable=protected-access + self._param_specs)) + + def _unbatch(self, batch_size): + """Returns a TypeSpec representing a single element of this TypeSpec.""" + return self._copy( + param_specs=nest.map_structure( + lambda spec: spec._unbatch(), # pylint: disable=protected-access + self._param_specs)) + + +def make_composite_tensor(cls, module_name="tf.linalg"): + """Class decorator to convert `LinearOperator`s to `CompositeTensor`.""" + + spec_name = "{}Spec".format(cls.__name__) + spec_type = type(spec_name, (_LinearOperatorSpec,), {"value_type": cls}) + type_spec_registry.register("{}.{}".format(module_name, spec_name))(spec_type) + cls._type_spec = property(spec_type.from_operator) # pylint: disable=protected-access + return cls + + +def _extract_attrs(op, keys): + """Extract constructor kwargs to reconstruct `op`. + + Args: + op: A `LinearOperator` instance. + keys: A Python `tuple` of strings indicating the names of the constructor + kwargs to extract from `op`. + + Returns: + kwargs: A Python `dict` of kwargs to `op`'s constructor, keyed by `keys`. + """ + + kwargs = {} + not_found = object() + for k in keys: + srcs = [ + getattr(op, k, not_found), getattr(op, "_" + k, not_found), + getattr(op, "parameters", {}).get(k, not_found), + ] + if any(v is not not_found for v in srcs): + kwargs[k] = [v for v in srcs if v is not not_found][0] + else: + raise ValueError( + f"Could not determine an appropriate value for field `{k}` in object " + f" `{op}`. Looked for \n" + f" 1. an attr called `{k}`,\n" + f" 2. an attr called `_{k}`,\n" + f" 3. an entry in `op.parameters` with key '{k}'.") + if k in op._composite_tensor_prefer_static_fields and kwargs[k] is not None: # pylint: disable=protected-access + if tensor_util.is_tensor(kwargs[k]): + static_val = tensor_util.constant_value(kwargs[k]) + if static_val is not None: + kwargs[k] = static_val + if isinstance(kwargs[k], (np.ndarray, np.generic)): + kwargs[k] = kwargs[k].tolist() + return kwargs + + +def _extract_type_spec_recursively(value): + """Return (collection of) `TypeSpec`(s) for `value` if it includes `Tensor`s. + + If `value` is a `Tensor` or `CompositeTensor`, return its `TypeSpec`. If + `value` is a collection containing `Tensor` values, recursively supplant them + with their respective `TypeSpec`s in a collection of parallel stucture. + + If `value` is none of the above, return it unchanged. + + Args: + value: a Python `object` to (possibly) turn into a (collection of) + `tf.TypeSpec`(s). + + Returns: + spec: the `TypeSpec` or collection of `TypeSpec`s corresponding to `value` + or `value`, if no `Tensor`s are found. + """ + if isinstance(value, composite_tensor.CompositeTensor): + return value._type_spec # pylint: disable=protected-access + if isinstance(value, variables.Variable): + return resource_variable_ops.VariableSpec( + value.shape, dtype=value.dtype, trainable=value.trainable) + if tensor_util.is_tensor(value): + return tensor_spec.TensorSpec(value.shape, value.dtype) + # Unwrap trackable data structures to comply with `Type_Spec._serialize` + # requirements. `ListWrapper`s are converted to `list`s, and for other + # trackable data structures, the `__wrapped__` attribute is used. + if isinstance(value, list): + return list(_extract_type_spec_recursively(v) for v in value) + if isinstance(value, data_structures.TrackableDataStructure): + return _extract_type_spec_recursively(value.__wrapped__) + if isinstance(value, tuple): + return type(value)(_extract_type_spec_recursively(x) for x in value) + if isinstance(value, dict): + return type(value)((k, _extract_type_spec_recursively(v)) + for k, v in value.items()) + return value + + +# Overrides for tf.linalg functions. This allows a LinearOperator to be used in +# place of a Tensor. +# For instance tf.trace(linop) and linop.trace() both work. + + +@dispatch.dispatch_for_types(linalg.adjoint, LinearOperator) +def _adjoint(matrix, name=None): + return matrix.adjoint(name) + + +@dispatch.dispatch_for_types(linalg.cholesky, LinearOperator) +def _cholesky(input, name=None): # pylint:disable=redefined-builtin + return input.cholesky(name) + + +# The signature has to match with the one in python/op/array_ops.py, +# so we have k, padding_value, and align even though we don't use them here. +# pylint:disable=unused-argument +@dispatch.dispatch_for_types(linalg.diag_part, LinearOperator) +def _diag_part( + input, # pylint:disable=redefined-builtin + name="diag_part", + k=0, + padding_value=0, + align="RIGHT_LEFT"): + return input.diag_part(name) +# pylint:enable=unused-argument + + +@dispatch.dispatch_for_types(linalg.det, LinearOperator) +def _det(input, name=None): # pylint:disable=redefined-builtin + return input.determinant(name) + + +@dispatch.dispatch_for_types(linalg.inv, LinearOperator) +def _inverse(input, adjoint=False, name=None): # pylint:disable=redefined-builtin + inv = input.inverse(name) + if adjoint: + inv = inv.adjoint() + return inv + + +@dispatch.dispatch_for_types(linalg.logdet, LinearOperator) +def _logdet(matrix, name=None): + if matrix.is_positive_definite and matrix.is_self_adjoint: + return matrix.log_abs_determinant(name) + raise ValueError("Expected matrix to be self-adjoint positive definite.") + + +@dispatch.dispatch_for_types(math_ops.matmul, LinearOperator) +def _matmul( # pylint:disable=missing-docstring + a, + b, + transpose_a=False, + transpose_b=False, + adjoint_a=False, + adjoint_b=False, + a_is_sparse=False, + b_is_sparse=False, + output_type=None, # pylint: disable=unused-argument + name=None): + if transpose_a or transpose_b: + raise ValueError("Transposing not supported at this time.") + if a_is_sparse or b_is_sparse: + raise ValueError("Sparse methods not supported at this time.") + if not isinstance(a, LinearOperator): + # We use the identity (B^HA^H)^H = AB + adjoint_matmul = b.matmul( + a, + adjoint=(not adjoint_b), + adjoint_arg=(not adjoint_a), + name=name) + return linalg.adjoint(adjoint_matmul) + return a.matmul( + b, adjoint=adjoint_a, adjoint_arg=adjoint_b, name=name) + + +@dispatch.dispatch_for_types(linalg.solve, LinearOperator) +def _solve( + matrix, + rhs, + adjoint=False, + name=None): + if not isinstance(matrix, LinearOperator): + raise ValueError("Passing in `matrix` as a Tensor and `rhs` as a " + "LinearOperator is not supported.") + return matrix.solve(rhs, adjoint=adjoint, name=name) + + +@dispatch.dispatch_for_types(linalg.trace, LinearOperator) +def _trace(x, name=None): + return x.trace(name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_addition.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_addition.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4061362c541414774415c34d195cfef16f3c9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_addition.py @@ -0,0 +1,437 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Add one or more `LinearOperators` efficiently.""" + +import abc + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_diag +from tensorflow.python.ops.linalg import linear_operator_full_matrix +from tensorflow.python.ops.linalg import linear_operator_identity +from tensorflow.python.ops.linalg import linear_operator_lower_triangular + +__all__ = [] + + +def add_operators(operators, + operator_name=None, + addition_tiers=None, + name=None): + """Efficiently add one or more linear operators. + + Given operators `[A1, A2,...]`, this `Op` returns a possibly shorter list of + operators `[B1, B2,...]` such that + + ```sum_k Ak.matmul(x) = sum_k Bk.matmul(x).``` + + The operators `Bk` result by adding some of the `Ak`, as allowed by + `addition_tiers`. + + Example of efficient adding of diagonal operators. + + ```python + A1 = LinearOperatorDiag(diag=[1., 1.], name="A1") + A2 = LinearOperatorDiag(diag=[2., 2.], name="A2") + + # Use two tiers, the first contains an Adder that returns Diag. Since both + # A1 and A2 are Diag, they can use this Adder. The second tier will not be + # used. + addition_tiers = [ + [_AddAndReturnDiag()], + [_AddAndReturnMatrix()]] + B_list = add_operators([A1, A2], addition_tiers=addition_tiers) + + len(B_list) + ==> 1 + + B_list[0].__class__.__name__ + ==> 'LinearOperatorDiag' + + B_list[0].to_dense() + ==> [[3., 0.], + [0., 3.]] + + B_list[0].name + ==> 'Add/A1__A2/' + ``` + + Args: + operators: Iterable of `LinearOperator` objects with same `dtype`, domain + and range dimensions, and broadcastable batch shapes. + operator_name: String name for returned `LinearOperator`. Defaults to + concatenation of "Add/A__B/" that indicates the order of addition steps. + addition_tiers: List tiers, like `[tier_0, tier_1, ...]`, where `tier_i` + is a list of `Adder` objects. This function attempts to do all additions + in tier `i` before trying tier `i + 1`. + name: A name for this `Op`. Defaults to `add_operators`. + + Returns: + Subclass of `LinearOperator`. Class and order of addition may change as new + (and better) addition strategies emerge. + + Raises: + ValueError: If `operators` argument is empty. + ValueError: If shapes are incompatible. + """ + # Default setting + if addition_tiers is None: + addition_tiers = _DEFAULT_ADDITION_TIERS + + # Argument checking. + check_ops.assert_proper_iterable(operators) + operators = list(reversed(operators)) + if len(operators) < 1: + raise ValueError( + f"Argument `operators` must contain at least one operator. " + f"Received: {operators}.") + if not all( + isinstance(op, linear_operator.LinearOperator) for op in operators): + raise TypeError( + f"Argument `operators` must contain only LinearOperator instances. " + f"Received: {operators}.") + _static_check_for_same_dimensions(operators) + _static_check_for_broadcastable_batch_shape(operators) + + with ops.name_scope(name or "add_operators"): + + # Additions done in one of the tiers. Try tier 0, 1,... + ops_to_try_at_next_tier = list(operators) + for tier in addition_tiers: + ops_to_try_at_this_tier = ops_to_try_at_next_tier + ops_to_try_at_next_tier = [] + while ops_to_try_at_this_tier: + op1 = ops_to_try_at_this_tier.pop() + op2, adder = _pop_a_match_at_tier(op1, ops_to_try_at_this_tier, tier) + if op2 is not None: + # Will try to add the result of this again at this same tier. + new_operator = adder.add(op1, op2, operator_name) + ops_to_try_at_this_tier.append(new_operator) + else: + ops_to_try_at_next_tier.append(op1) + + return ops_to_try_at_next_tier + + +def _pop_a_match_at_tier(op1, operator_list, tier): + # Search from the back of list to the front in order to create nice default + # order of operations. + for i in range(1, len(operator_list) + 1): + op2 = operator_list[-i] + for adder in tier: + if adder.can_add(op1, op2): + return operator_list.pop(-i), adder + return None, None + + +def _infer_hints_allowing_override(op1, op2, hints): + """Infer hints from op1 and op2. hints argument is an override. + + Args: + op1: LinearOperator + op2: LinearOperator + hints: _Hints object holding "is_X" boolean hints to use for returned + operator. + If some hint is None, try to set using op1 and op2. If the + hint is provided, ignore op1 and op2 hints. This allows an override + of previous hints, but does not allow forbidden hints (e.g. you still + cannot say a real diagonal operator is not self-adjoint. + + Returns: + _Hints object. + """ + hints = hints or _Hints() + # If A, B are self-adjoint, then so is A + B. + if hints.is_self_adjoint is None: + is_self_adjoint = op1.is_self_adjoint and op2.is_self_adjoint + else: + is_self_adjoint = hints.is_self_adjoint + + # If A, B are positive definite, then so is A + B. + if hints.is_positive_definite is None: + is_positive_definite = op1.is_positive_definite and op2.is_positive_definite + else: + is_positive_definite = hints.is_positive_definite + + # A positive definite operator is always non-singular. + if is_positive_definite and hints.is_positive_definite is None: + is_non_singular = True + else: + is_non_singular = hints.is_non_singular + + return _Hints( + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite) + + +def _static_check_for_same_dimensions(operators): + """ValueError if operators determined to have different dimensions.""" + if len(operators) < 2: + return + + domain_dimensions = [ + (op.name, tensor_shape.dimension_value(op.domain_dimension)) + for op in operators + if tensor_shape.dimension_value(op.domain_dimension) is not None] + if len(set(value for name, value in domain_dimensions)) > 1: + raise ValueError(f"All `operators` must have the same `domain_dimension`. " + f"Received: {domain_dimensions}.") + + range_dimensions = [ + (op.name, tensor_shape.dimension_value(op.range_dimension)) + for op in operators + if tensor_shape.dimension_value(op.range_dimension) is not None] + if len(set(value for name, value in range_dimensions)) > 1: + raise ValueError(f"All operators must have the same `range_dimension`. " + f"Received: {range_dimensions}.") + + +def _static_check_for_broadcastable_batch_shape(operators): + """ValueError if operators determined to have non-broadcastable shapes.""" + if len(operators) < 2: + return + + # This will fail if they cannot be broadcast together. + batch_shape = operators[0].batch_shape + for op in operators[1:]: + batch_shape = array_ops.broadcast_static_shape(batch_shape, op.batch_shape) + + +class _Hints: + """Holds 'is_X' flags that every LinearOperator is initialized with.""" + + def __init__(self, + is_non_singular=None, + is_positive_definite=None, + is_self_adjoint=None): + self.is_non_singular = is_non_singular + self.is_positive_definite = is_positive_definite + self.is_self_adjoint = is_self_adjoint + + +################################################################################ +# Classes to add two linear operators. +################################################################################ + + +class _Adder(metaclass=abc.ABCMeta): + """Abstract base class to add two operators. + + Each `Adder` acts independently, adding everything it can, paying no attention + as to whether another `Adder` could have done the addition more efficiently. + """ + + @property + def name(self): + return self.__class__.__name__ + + @abc.abstractmethod + def can_add(self, op1, op2): + """Returns `True` if this `Adder` can add `op1` and `op2`. Else `False`.""" + pass + + @abc.abstractmethod + def _add(self, op1, op2, operator_name, hints): + # Derived classes can assume op1 and op2 have been validated, e.g. they have + # the same dtype, and their domain/range dimensions match. + pass + + def add(self, op1, op2, operator_name, hints=None): + """Return new `LinearOperator` acting like `op1 + op2`. + + Args: + op1: `LinearOperator` + op2: `LinearOperator`, with `shape` and `dtype` such that adding to + `op1` is allowed. + operator_name: `String` name to give to returned `LinearOperator` + hints: `_Hints` object. Returned `LinearOperator` will be created with + these hints. + + Returns: + `LinearOperator` + """ + updated_hints = _infer_hints_allowing_override(op1, op2, hints) + + if operator_name is None: + operator_name = "Add/" + op1.name + "__" + op2.name + "/" + + scope_name = self.name + if scope_name.startswith("_"): + scope_name = scope_name[1:] + with ops.name_scope(scope_name): + return self._add(op1, op2, operator_name, updated_hints) + + +class _AddAndReturnScaledIdentity(_Adder): + """Handles additions resulting in an Identity family member. + + The Identity (`LinearOperatorScaledIdentity`, `LinearOperatorIdentity`) family + is closed under addition. This `Adder` respects that, and returns an Identity + """ + + def can_add(self, op1, op2): + types = {_type(op1), _type(op2)} + return not types.difference(_IDENTITY_FAMILY) + + def _add(self, op1, op2, operator_name, hints): + # Will build a LinearOperatorScaledIdentity. + + if _type(op1) == _SCALED_IDENTITY: + multiplier_1 = op1.multiplier + else: + multiplier_1 = array_ops.ones(op1.batch_shape_tensor(), dtype=op1.dtype) + + if _type(op2) == _SCALED_IDENTITY: + multiplier_2 = op2.multiplier + else: + multiplier_2 = array_ops.ones(op2.batch_shape_tensor(), dtype=op2.dtype) + + return linear_operator_identity.LinearOperatorScaledIdentity( + num_rows=op1.range_dimension_tensor(), + multiplier=multiplier_1 + multiplier_2, + is_non_singular=hints.is_non_singular, + is_self_adjoint=hints.is_self_adjoint, + is_positive_definite=hints.is_positive_definite, + name=operator_name) + + +class _AddAndReturnDiag(_Adder): + """Handles additions resulting in a Diag operator.""" + + def can_add(self, op1, op2): + types = {_type(op1), _type(op2)} + return not types.difference(_DIAG_LIKE) + + def _add(self, op1, op2, operator_name, hints): + return linear_operator_diag.LinearOperatorDiag( + diag=op1.diag_part() + op2.diag_part(), + is_non_singular=hints.is_non_singular, + is_self_adjoint=hints.is_self_adjoint, + is_positive_definite=hints.is_positive_definite, + name=operator_name) + + +class _AddAndReturnTriL(_Adder): + """Handles additions resulting in a TriL operator.""" + + def can_add(self, op1, op2): + types = {_type(op1), _type(op2)} + return not types.difference(_DIAG_LIKE.union({_TRIL})) + + def _add(self, op1, op2, operator_name, hints): + if _type(op1) in _EFFICIENT_ADD_TO_TENSOR: + op_add_to_tensor, op_other = op1, op2 + else: + op_add_to_tensor, op_other = op2, op1 + + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + tril=op_add_to_tensor.add_to_tensor(op_other.to_dense()), + is_non_singular=hints.is_non_singular, + is_self_adjoint=hints.is_self_adjoint, + is_positive_definite=hints.is_positive_definite, + name=operator_name) + + +class _AddAndReturnMatrix(_Adder): + """"Handles additions resulting in a `LinearOperatorFullMatrix`.""" + + def can_add(self, op1, op2): # pylint: disable=unused-argument + return isinstance(op1, linear_operator.LinearOperator) and isinstance( + op2, linear_operator.LinearOperator) + + def _add(self, op1, op2, operator_name, hints): + if _type(op1) in _EFFICIENT_ADD_TO_TENSOR: + op_add_to_tensor, op_other = op1, op2 + else: + op_add_to_tensor, op_other = op2, op1 + return linear_operator_full_matrix.LinearOperatorFullMatrix( + matrix=op_add_to_tensor.add_to_tensor(op_other.to_dense()), + is_non_singular=hints.is_non_singular, + is_self_adjoint=hints.is_self_adjoint, + is_positive_definite=hints.is_positive_definite, + name=operator_name) + + +################################################################################ +# Constants designating types of LinearOperators +################################################################################ + +# Type name constants for LinearOperator classes. +_IDENTITY = "identity" +_SCALED_IDENTITY = "scaled_identity" +_DIAG = "diag" +_TRIL = "tril" +_MATRIX = "matrix" + +# Groups of operators. +_DIAG_LIKE = {_DIAG, _IDENTITY, _SCALED_IDENTITY} +_IDENTITY_FAMILY = {_IDENTITY, _SCALED_IDENTITY} +# operators with an efficient .add_to_tensor() method. +_EFFICIENT_ADD_TO_TENSOR = _DIAG_LIKE + +# Supported LinearOperator classes. +SUPPORTED_OPERATORS = [ + linear_operator_diag.LinearOperatorDiag, + linear_operator_lower_triangular.LinearOperatorLowerTriangular, + linear_operator_full_matrix.LinearOperatorFullMatrix, + linear_operator_identity.LinearOperatorIdentity, + linear_operator_identity.LinearOperatorScaledIdentity +] + + +def _type(operator): + """Returns the type name constant (e.g. _TRIL) for operator.""" + if isinstance(operator, linear_operator_diag.LinearOperatorDiag): + return _DIAG + if isinstance(operator, + linear_operator_lower_triangular.LinearOperatorLowerTriangular): + return _TRIL + if isinstance(operator, linear_operator_full_matrix.LinearOperatorFullMatrix): + return _MATRIX + if isinstance(operator, linear_operator_identity.LinearOperatorIdentity): + return _IDENTITY + if isinstance(operator, + linear_operator_identity.LinearOperatorScaledIdentity): + return _SCALED_IDENTITY + raise TypeError(f"Expected operator to be one of [LinearOperatorDiag, " + f"LinearOperatorLowerTriangular, LinearOperatorFullMatrix, " + f"LinearOperatorIdentity, LinearOperatorScaledIdentity]. " + f"Received: {operator}") + + +################################################################################ +# Addition tiers: +# We attempt to use Adders in tier K before K+1. +# +# Organize tiers to +# (i) reduce O(..) complexity of forming final operator, and +# (ii) produce the "most efficient" final operator. +# Dev notes: +# * Results of addition at tier K will be added at tier K or higher. +# * Tiers may change, and we warn the user that it may change. +################################################################################ + +# Note that the final tier, _AddAndReturnMatrix, will convert everything to a +# dense matrix. So it is sometimes very inefficient. +_DEFAULT_ADDITION_TIERS = [ + [_AddAndReturnScaledIdentity()], + [_AddAndReturnDiag()], + [_AddAndReturnTriL()], + [_AddAndReturnMatrix()], +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_adjoint.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_adjoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e63f9d7d3af384535b237025f00dac3449f8168f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_adjoint.py @@ -0,0 +1,238 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Takes the adjoint of a `LinearOperator`.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorAdjoint"] + + +@tf_export("linalg.LinearOperatorAdjoint") +@linear_operator.make_composite_tensor +class LinearOperatorAdjoint(linear_operator.LinearOperator): + """`LinearOperator` representing the adjoint of another operator. + + This operator represents the adjoint of another operator. + + ```python + # Create a 2 x 2 linear operator. + operator = LinearOperatorFullMatrix([[1 - i., 3.], [0., 1. + i]]) + operator_adjoint = LinearOperatorAdjoint(operator) + + operator_adjoint.to_dense() + ==> [[1. + i, 0.] + [3., 1 - i]] + + operator_adjoint.shape + ==> [2, 2] + + operator_adjoint.log_abs_determinant() + ==> - log(2) + + x = ... Shape [2, 4] Tensor + operator_adjoint.matmul(x) + ==> Shape [2, 4] Tensor, equal to operator.matmul(x, adjoint=True) + ``` + + #### Performance + + The performance of `LinearOperatorAdjoint` depends on the underlying + operators performance. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operator, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name=None): + r"""Initialize a `LinearOperatorAdjoint`. + + `LinearOperatorAdjoint` is initialized with an operator `A`. The `solve` + and `matmul` methods effectively flip the `adjoint` argument. E.g. + + ``` + A = MyLinearOperator(...) + B = LinearOperatorAdjoint(A) + x = [....] # a vector + + assert A.matvec(x, adjoint=True) == B.matvec(x, adjoint=False) + ``` + + Args: + operator: `LinearOperator` object. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. Default is `operator.name + + "_adjoint"`. + + Raises: + ValueError: If `operator.is_non_singular` is False. + """ + parameters = dict( + operator=operator, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name, + ) + + self._operator = operator + + # The congruency of is_non_singular and is_self_adjoint was checked in the + # base operator. + combine_hint = ( + linear_operator_util.use_operator_or_provided_hint_unless_contradicting) + + is_square = combine_hint( + operator, "is_square", is_square, + "An operator is square if and only if its adjoint is square.") + + is_non_singular = combine_hint( + operator, "is_non_singular", is_non_singular, + "An operator is non-singular if and only if its adjoint is " + "non-singular.") + + is_self_adjoint = combine_hint( + operator, "is_self_adjoint", is_self_adjoint, + "An operator is self-adjoint if and only if its adjoint is " + "self-adjoint.") + + is_positive_definite = combine_hint( + operator, "is_positive_definite", is_positive_definite, + "An operator is positive-definite if and only if its adjoint is " + "positive-definite.") + + # Initialization. + if name is None: + name = operator.name + "_adjoint" + with ops.name_scope(name): + super(LinearOperatorAdjoint, self).__init__( + dtype=operator.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def operator(self): + """The operator before taking the adjoint.""" + return self._operator + + def _linop_adjoint(self) -> linear_operator.LinearOperator: + return self.operator + + def _assert_non_singular(self): + return self.operator.assert_non_singular() + + def _assert_positive_definite(self): + return self.operator.assert_positive_definite() + + def _assert_self_adjoint(self): + return self.operator.assert_self_adjoint() + + def _shape(self): + # Rotate last dimension + shape = self.operator.shape + return shape[:-2].concatenate([shape[-1], shape[-2]]) + + def _shape_tensor(self): + # Rotate last dimension + shape = self.operator.shape_tensor() + return array_ops.concat([ + shape[:-2], [shape[-1], shape[-2]]], axis=-1) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + return self.operator.matmul( + x, adjoint=(not adjoint), adjoint_arg=adjoint_arg) + + def _matvec(self, x, adjoint=False): + return self.operator.matvec(x, adjoint=(not adjoint)) + + def _determinant(self): + if self.is_self_adjoint: + return self.operator.determinant() + return math_ops.conj(self.operator.determinant()) + + def _log_abs_determinant(self): + return self.operator.log_abs_determinant() + + def _trace(self): + if self.is_self_adjoint: + return self.operator.trace() + return math_ops.conj(self.operator.trace()) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + return self.operator.solve( + rhs, adjoint=(not adjoint), adjoint_arg=adjoint_arg) + + def _solvevec(self, rhs, adjoint=False): + return self.operator.solvevec(rhs, adjoint=(not adjoint)) + + def _to_dense(self): + if self.is_self_adjoint: + return self.operator.to_dense() + return linalg.adjoint(self.operator.to_dense()) + + def _add_to_tensor(self, x): + return self.to_dense() + x + + def _eigvals(self): + eigvals = self.operator.eigvals() + if not self.operator.is_self_adjoint: + eigvals = math_ops.conj(eigvals) + return eigvals + + def _cond(self): + return self.operator.cond() + + @property + def _composite_tensor_fields(self): + return ("operator",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"operator": 0} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_diag.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf53df3173d3cc81fea7d3d815f471baf641489 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_diag.py @@ -0,0 +1,818 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Create a Block Diagonal operator from one or more `LinearOperators`.""" + +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorBlockDiag"] + + +@tf_export("linalg.LinearOperatorBlockDiag") +@linear_operator.make_composite_tensor +class LinearOperatorBlockDiag(linear_operator.LinearOperator): + """Combines one or more `LinearOperators` in to a Block Diagonal matrix. + + This operator combines one or more linear operators `[op1,...,opJ]`, + building a new `LinearOperator`, whose underlying matrix representation + has each operator `opi` on the main diagonal, and zero's elsewhere. + + #### Shape compatibility + + If `opj` acts like a [batch] matrix `Aj`, then `op_combined` acts like + the [batch] matrix formed by having each matrix `Aj` on the main + diagonal. + + Each `opj` is required to represent a matrix, and hence will have + shape `batch_shape_j + [M_j, N_j]`. + + If `opj` has shape `batch_shape_j + [M_j, N_j]`, then the combined operator + has shape `broadcast_batch_shape + [sum M_j, sum N_j]`, where + `broadcast_batch_shape` is the mutual broadcast of `batch_shape_j`, + `j = 1,...,J`, assuming the intermediate batch shapes broadcast. + + Arguments to `matmul`, `matvec`, `solve`, and `solvevec` may either be single + `Tensor`s or lists of `Tensor`s that are interpreted as blocks. The `j`th + element of a blockwise list of `Tensor`s must have dimensions that match + `opj` for the given method. If a list of blocks is input, then a list of + blocks is returned as well. + + When the `opj` are not guaranteed to be square, this operator's methods might + fail due to the combined operator not being square and/or lack of efficient + methods. + + ```python + # Create a 4 x 4 linear operator combined of two 2 x 2 operators. + operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]]) + operator_2 = LinearOperatorFullMatrix([[1., 0.], [0., 1.]]) + operator = LinearOperatorBlockDiag([operator_1, operator_2]) + + operator.to_dense() + ==> [[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 0.], + [0., 0., 0., 1.]] + + operator.shape + ==> [4, 4] + + operator.log_abs_determinant() + ==> scalar Tensor + + x1 = ... # Shape [2, 2] Tensor + x2 = ... # Shape [2, 2] Tensor + x = tf.concat([x1, x2], 0) # Shape [2, 4] Tensor + operator.matmul(x) + ==> tf.concat([operator_1.matmul(x1), operator_2.matmul(x2)]) + + # Create a 5 x 4 linear operator combining three blocks. + operator_1 = LinearOperatorFullMatrix([[1.], [3.]]) + operator_2 = LinearOperatorFullMatrix([[1., 6.]]) + operator_3 = LinearOperatorFullMatrix([[2.], [7.]]) + operator = LinearOperatorBlockDiag([operator_1, operator_2, operator_3]) + + operator.to_dense() + ==> [[1., 0., 0., 0.], + [3., 0., 0., 0.], + [0., 1., 6., 0.], + [0., 0., 0., 2.]] + [0., 0., 0., 7.]] + + operator.shape + ==> [5, 4] + + + # Create a [2, 3] batch of 4 x 4 linear operators. + matrix_44 = tf.random.normal(shape=[2, 3, 4, 4]) + operator_44 = LinearOperatorFullMatrix(matrix) + + # Create a [1, 3] batch of 5 x 5 linear operators. + matrix_55 = tf.random.normal(shape=[1, 3, 5, 5]) + operator_55 = LinearOperatorFullMatrix(matrix_55) + + # Combine to create a [2, 3] batch of 9 x 9 operators. + operator_99 = LinearOperatorBlockDiag([operator_44, operator_55]) + + # Create a shape [2, 3, 9] vector. + x = tf.random.normal(shape=[2, 3, 9]) + operator_99.matmul(x) + ==> Shape [2, 3, 9] Tensor + + # Create a blockwise list of vectors. + x = [tf.random.normal(shape=[2, 3, 4]), tf.random.normal(shape=[2, 3, 5])] + operator_99.matmul(x) + ==> [Shape [2, 3, 4] Tensor, Shape [2, 3, 5] Tensor] + ``` + + #### Performance + + The performance of `LinearOperatorBlockDiag` on any operation is equal to + the sum of the individual operators' operations. + + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operators, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=True, + name=None): + r"""Initialize a `LinearOperatorBlockDiag`. + + `LinearOperatorBlockDiag` is initialized with a list of operators + `[op_1,...,op_J]`. + + Args: + operators: Iterable of `LinearOperator` objects, each with + the same `dtype` and composable shape. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + This is true by default, and will raise a `ValueError` otherwise. + name: A name for this `LinearOperator`. Default is the individual + operators names joined with `_o_`. + + Raises: + TypeError: If all operators do not have the same `dtype`. + ValueError: If `operators` is empty or are non-square. + """ + parameters = dict( + operators=operators, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + # Validate operators. + check_ops.assert_proper_iterable(operators) + operators = list(operators) + if not operators: + raise ValueError( + "Expected a non-empty list of operators. Found: %s" % operators) + self._operators = operators + + # Define diagonal operators, for functions that are shared across blockwise + # `LinearOperator` types. + self._diagonal_operators = operators + + # Validate dtype. + dtype = operators[0].dtype + for operator in operators: + if operator.dtype != dtype: + name_type = (str((o.name, o.dtype)) for o in operators) + raise TypeError( + "Expected all operators to have the same dtype. Found %s" + % " ".join(name_type)) + + # Auto-set and check hints. + if all(operator.is_non_singular for operator in operators): + if is_non_singular is False: + raise ValueError( + "The direct sum of non-singular operators is always non-singular.") + is_non_singular = True + + if all(operator.is_self_adjoint for operator in operators): + if is_self_adjoint is False: + raise ValueError( + "The direct sum of self-adjoint operators is always self-adjoint.") + is_self_adjoint = True + + if all(operator.is_positive_definite for operator in operators): + if is_positive_definite is False: + raise ValueError( + "The direct sum of positive definite operators is always " + "positive definite.") + is_positive_definite = True + + if name is None: + # Using ds to mean direct sum. + name = "_ds_".join(operator.name for operator in operators) + with ops.name_scope(name): + super(LinearOperatorBlockDiag, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def operators(self): + return self._operators + + def _block_range_dimensions(self): + return [op.range_dimension for op in self._diagonal_operators] + + def _block_domain_dimensions(self): + return [op.domain_dimension for op in self._diagonal_operators] + + def _block_range_dimension_tensors(self): + return [op.range_dimension_tensor() for op in self._diagonal_operators] + + def _block_domain_dimension_tensors(self): + return [op.domain_dimension_tensor() for op in self._diagonal_operators] + + def _shape(self): + # Get final matrix shape. + domain_dimension = sum(self._block_domain_dimensions()) + range_dimension = sum(self._block_range_dimensions()) + matrix_shape = tensor_shape.TensorShape([range_dimension, domain_dimension]) + + # Get broadcast batch shape. + # broadcast_shape checks for compatibility. + batch_shape = self.operators[0].batch_shape + for operator in self.operators[1:]: + batch_shape = common_shapes.broadcast_shape( + batch_shape, operator.batch_shape) + + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + # Avoid messy broadcasting if possible. + if self.shape.is_fully_defined(): + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.shape.as_list(), dtype=dtypes.int32, name="shape" + ) + + domain_dimension = sum(self._block_domain_dimension_tensors()) + range_dimension = sum(self._block_range_dimension_tensors()) + matrix_shape = array_ops_stack.stack([range_dimension, domain_dimension]) + + # Dummy Tensor of zeros. Will never be materialized. + zeros = array_ops.zeros(shape=self.operators[0].batch_shape_tensor()) + for operator in self.operators[1:]: + zeros += array_ops.zeros(shape=operator.batch_shape_tensor()) + batch_shape = array_ops.shape(zeros) + + return array_ops.concat((batch_shape, matrix_shape), 0) + + def _linop_adjoint(self) -> "LinearOperatorBlockDiag": + # We take the adjoint of each block on the diagonal. + return LinearOperatorBlockDiag( + operators=[operator.adjoint() for operator in self.operators], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_cholesky(self) -> "LinearOperatorBlockDiag": + # We take the cholesky of each block on the diagonal. + return LinearOperatorBlockDiag( + operators=[operator.cholesky() for operator in self.operators], + is_non_singular=True, + is_self_adjoint=None, # Let the operators passed in decide. + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorBlockDiag": + # We take the inverse of each block on the diagonal. + return LinearOperatorBlockDiag( + operators=[ + operator.inverse() for operator in self.operators], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_matmul( + self, + left_operator: "LinearOperatorBlockDiag", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if isinstance(right_operator, LinearOperatorBlockDiag): + return LinearOperatorBlockDiag( + operators=[ + o1.matmul(o2) for o1, o2 in zip( + left_operator.operators, right_operator.operators)], + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + # In general, a product of self-adjoint positive-definite + # block diagonal matrices is not self-adjoint. + is_self_adjoint=None, + # In general, a product of positive-definite block diagonal + # matrices is not positive-definite. + is_positive_definite=None, + is_square=True) + return super()._linop_matmul(left_operator, right_operator) + + def _linop_solve( + self, + left_operator: "LinearOperatorBlockDiag", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if isinstance(right_operator, LinearOperatorBlockDiag): + return LinearOperatorBlockDiag( + operators=[ + o1.solve(o2) for o1, o2 in zip( + left_operator.operators, right_operator.operators)], + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + # In general, a solve of self-adjoint positive-definite block diagonal + # matrices is not self-=adjoint. + is_self_adjoint=None, + # In general, a solve of positive-definite block diagonal matrices is + # not positive-definite. + is_positive_definite=None, + is_square=True) + return super()._linop_solve(left_operator, right_operator) + + # TODO(b/188080761): Add a more efficient implementation of `cond` that + # constructs the condition number from the blockwise singular values. + + def matmul(self, x, adjoint=False, adjoint_arg=False, name="matmul"): + """Transform [batch] matrix `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + X = ... # shape [..., N, R], batch matrix, R > 0. + + Y = operator.matmul(X) + Y.shape + ==> [..., M, R] + + Y[..., :, r] = sum_j A[..., :, j] X[j, r] + ``` + + Args: + x: `LinearOperator`, `Tensor` with compatible shape and same `dtype` as + `self`, or a blockwise iterable of `LinearOperator`s or `Tensor`s. See + class docstring for definition of shape compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + adjoint_arg: Python `bool`. If `True`, compute `A x^H` where `x^H` is + the hermitian transpose (transposition and complex conjugation). + name: A name for this `Op`. + + Returns: + A `LinearOperator` or `Tensor` with shape `[..., M, R]` and same `dtype` + as `self`, or if `x` is blockwise, a list of `Tensor`s with shapes that + concatenate to `[..., M, R]`. + """ + def _check_operators_agree(r, l, message): + if (r.range_dimension is not None and + l.domain_dimension is not None and + r.range_dimension != l.domain_dimension): + raise ValueError(message) + + if isinstance(x, linear_operator.LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = x.adjoint() if adjoint_arg else x + + _check_operators_agree( + right_operator, left_operator, + "Operators are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + + # We can efficiently multiply BlockDiag LinearOperators if the number of + # blocks agree. + if isinstance(x, LinearOperatorBlockDiag): + if len(left_operator.operators) != len(right_operator.operators): + raise ValueError( + "Can not efficiently multiply two `LinearOperatorBlockDiag`s " + "together when number of blocks differ.") + + for o1, o2 in zip(left_operator.operators, right_operator.operators): + _check_operators_agree( + o2, o1, + "Blocks are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + o1.domain_dimension, o2.range_dimension)) + + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_matmul(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + arg_dim = -1 if adjoint_arg else -2 + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, x, arg_dim): + for i, block in enumerate(x): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[arg_dim]) + x[i] = block + else: + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + op_dimension = (self.range_dimension if adjoint + else self.domain_dimension) + op_dimension.assert_is_compatible_with(x.shape[arg_dim]) + return self._matmul(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + arg_dim = -1 if adjoint_arg else -2 + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + block_dimensions_fn = ( + self._block_range_dimension_tensors if adjoint + else self._block_domain_dimension_tensors) + blockwise_arg = linear_operator_util.arg_is_blockwise( + block_dimensions, x, arg_dim) + if blockwise_arg: + split_x = x + + else: + split_dim = -1 if adjoint_arg else -2 + # Split input by rows normally, and otherwise columns. + split_x = linear_operator_util.split_arg_into_blocks( + block_dimensions, block_dimensions_fn, x, axis=split_dim) + + result_list = [] + for index, operator in enumerate(self.operators): + result_list += [operator.matmul( + split_x[index], adjoint=adjoint, adjoint_arg=adjoint_arg)] + + if blockwise_arg: + return result_list + + result_list = linear_operator_util.broadcast_matrix_batch_dims( + result_list) + return array_ops.concat(result_list, axis=-2) + + def matvec(self, x, adjoint=False, name="matvec"): + """Transform [batch] vector `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matric A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + + X = ... # shape [..., N], batch vector + + Y = operator.matvec(X) + Y.shape + ==> [..., M] + + Y[..., :] = sum_j A[..., :, j] X[..., j] + ``` + + Args: + x: `Tensor` with compatible shape and same `dtype` as `self`, or an + iterable of `Tensor`s (for blockwise operators). `Tensor`s are treated + a [batch] vectors, meaning for every set of leading dimensions, the last + dimension defines a vector. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + name: A name for this `Op`. + + Returns: + A `Tensor` with shape `[..., M]` and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, x, -1): + for i, block in enumerate(x): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[-1]) + x[i] = block + x_mat = [block[..., array_ops.newaxis] for block in x] + y_mat = self.matmul(x_mat, adjoint=adjoint) + return [array_ops.squeeze(y, axis=-1) for y in y_mat] + + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + op_dimension = (self.range_dimension if adjoint + else self.domain_dimension) + op_dimension.assert_is_compatible_with(x.shape[-1]) + x_mat = x[..., array_ops.newaxis] + y_mat = self.matmul(x_mat, adjoint=adjoint) + return array_ops.squeeze(y_mat, axis=-1) + + def _determinant(self): + result = self.operators[0].determinant() + for operator in self.operators[1:]: + result *= operator.determinant() + return result + + def _log_abs_determinant(self): + result = self.operators[0].log_abs_determinant() + for operator in self.operators[1:]: + result += operator.log_abs_determinant() + return result + + def solve(self, rhs, adjoint=False, adjoint_arg=False, name="solve"): + """Solve (exact or approx) `R` (batch) systems of equations: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve R > 0 linear systems for every member of the batch. + RHS = ... # shape [..., M, R] + + X = operator.solve(RHS) + # X[..., :, r] is the solution to the r'th linear system + # sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r] + + operator.matmul(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator and compatible shape, + or a list of `Tensor`s (for blockwise operators). `Tensor`s are treated + like a [batch] matrices meaning for every set of leading dimensions, the + last two dimensions defines a matrix. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + adjoint_arg: Python `bool`. If `True`, solve `A X = rhs^H` where `rhs^H` + is the hermitian transpose (transposition and complex conjugation). + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N, R]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + if self.is_non_singular is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "be singular.") + if self.is_square is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "not be square.") + + def _check_operators_agree(r, l, message): + if (r.range_dimension is not None and + l.domain_dimension is not None and + r.range_dimension != l.domain_dimension): + raise ValueError(message) + + if isinstance(rhs, linear_operator.LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = rhs.adjoint() if adjoint_arg else rhs + + _check_operators_agree( + right_operator, left_operator, + "Operators are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + + # We can efficiently solve BlockDiag LinearOperators if the number of + # blocks agree. + if isinstance(right_operator, LinearOperatorBlockDiag): + if len(left_operator.operators) != len(right_operator.operators): + raise ValueError( + "Can not efficiently solve `LinearOperatorBlockDiag` when " + "number of blocks differ.") + + for o1, o2 in zip(left_operator.operators, right_operator.operators): + _check_operators_agree( + o2, o1, + "Blocks are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + o1.domain_dimension, o2.range_dimension)) + + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_solve(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_domain_dimensions() if adjoint + else self._block_range_dimensions()) + arg_dim = -1 if adjoint_arg else -2 + blockwise_arg = linear_operator_util.arg_is_blockwise( + block_dimensions, rhs, arg_dim) + + if blockwise_arg: + split_rhs = rhs + for i, block in enumerate(split_rhs): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[arg_dim]) + split_rhs[i] = block + else: + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + op_dimension = (self.domain_dimension if adjoint + else self.range_dimension) + op_dimension.assert_is_compatible_with(rhs.shape[arg_dim]) + split_dim = -1 if adjoint_arg else -2 + # Split input by rows normally, and otherwise columns. + split_rhs = linear_operator_util.split_arg_into_blocks( + self._block_domain_dimensions(), + self._block_domain_dimension_tensors, + rhs, axis=split_dim) + + solution_list = [] + for index, operator in enumerate(self.operators): + solution_list += [operator.solve( + split_rhs[index], adjoint=adjoint, adjoint_arg=adjoint_arg)] + + if blockwise_arg: + return solution_list + + solution_list = linear_operator_util.broadcast_matrix_batch_dims( + solution_list) + return array_ops.concat(solution_list, axis=-2) + + def solvevec(self, rhs, adjoint=False, name="solve"): + """Solve single equation with best effort: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve one linear system for every member of the batch. + RHS = ... # shape [..., M] + + X = operator.solvevec(RHS) + # X is the solution to the linear system + # sum_j A[..., :, j] X[..., j] = RHS[..., :] + + operator.matvec(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator, or list of `Tensor`s + (for blockwise operators). `Tensor`s are treated as [batch] vectors, + meaning for every set of leading dimensions, the last dimension defines + a vector. See class docstring for definition of compatibility regarding + batch dimensions. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_domain_dimensions() if adjoint + else self._block_range_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, rhs, -1): + for i, block in enumerate(rhs): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[-1]) + rhs[i] = block + rhs_mat = [array_ops.expand_dims(block, axis=-1) for block in rhs] + solution_mat = self.solve(rhs_mat, adjoint=adjoint) + return [array_ops.squeeze(x, axis=-1) for x in solution_mat] + + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + op_dimension = (self.domain_dimension if adjoint + else self.range_dimension) + op_dimension.assert_is_compatible_with(rhs.shape[-1]) + rhs_mat = array_ops.expand_dims(rhs, axis=-1) + solution_mat = self.solve(rhs_mat, adjoint=adjoint) + return array_ops.squeeze(solution_mat, axis=-1) + + def _diag_part(self): + if not all(operator.is_square for operator in self.operators): + raise NotImplementedError( + "`diag_part` not implemented for an operator whose blocks are not " + "square.") + diag_list = [] + for operator in self.operators: + # Extend the axis for broadcasting. + diag_list += [operator.diag_part()[..., array_ops.newaxis]] + diag_list = linear_operator_util.broadcast_matrix_batch_dims(diag_list) + diagonal = array_ops.concat(diag_list, axis=-2) + return array_ops.squeeze(diagonal, axis=-1) + + def _trace(self): + if not all(operator.is_square for operator in self.operators): + raise NotImplementedError( + "`trace` not implemented for an operator whose blocks are not " + "square.") + result = self.operators[0].trace() + for operator in self.operators[1:]: + result += operator.trace() + return result + + def _to_dense(self): + num_cols = 0 + rows = [] + broadcasted_blocks = [operator.to_dense() for operator in self.operators] + broadcasted_blocks = linear_operator_util.broadcast_matrix_batch_dims( + broadcasted_blocks) + for block in broadcasted_blocks: + batch_row_shape = array_ops.shape(block)[:-1] + + zeros_to_pad_before_shape = array_ops.concat( + [batch_row_shape, [num_cols]], axis=-1) + zeros_to_pad_before = array_ops.zeros( + shape=zeros_to_pad_before_shape, dtype=block.dtype) + num_cols += array_ops.shape(block)[-1] + zeros_to_pad_after_shape = array_ops.concat( + [batch_row_shape, + [self.domain_dimension_tensor() - num_cols]], axis=-1) + zeros_to_pad_after = array_ops.zeros( + shape=zeros_to_pad_after_shape, dtype=block.dtype) + + rows.append(array_ops.concat( + [zeros_to_pad_before, block, zeros_to_pad_after], axis=-1)) + + mat = array_ops.concat(rows, axis=-2) + mat.set_shape(self.shape) + return mat + + def _assert_non_singular(self): + return control_flow_ops.group([ + operator.assert_non_singular() for operator in self.operators]) + + def _assert_self_adjoint(self): + return control_flow_ops.group([ + operator.assert_self_adjoint() for operator in self.operators]) + + def _assert_positive_definite(self): + return control_flow_ops.group([ + operator.assert_positive_definite() for operator in self.operators]) + + def _eigvals(self): + if not all(operator.is_square for operator in self.operators): + raise NotImplementedError( + "`eigvals` not implemented for an operator whose blocks are not " + "square.") + eig_list = [] + for operator in self.operators: + # Extend the axis for broadcasting. + eig_list += [operator.eigvals()[..., array_ops.newaxis]] + eig_list = linear_operator_util.broadcast_matrix_batch_dims(eig_list) + eigs = array_ops.concat(eig_list, axis=-2) + return array_ops.squeeze(eigs, axis=-1) + + @property + def _composite_tensor_fields(self): + return ("operators",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"operators": [0] * len(self.operators)} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_lower_triangular.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_lower_triangular.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9caf67d3f5dd3c1e5b6c91f92d1e9ce575ccfb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_block_lower_triangular.py @@ -0,0 +1,986 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Create a blockwise lower-triangular operator from `LinearOperators`.""" + +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_addition +from tensorflow.python.ops.linalg import linear_operator_full_matrix +from tensorflow.python.ops.linalg import linear_operator_identity +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorBlockLowerTriangular"] + + +@tf_export("linalg.LinearOperatorBlockLowerTriangular") +@linear_operator.make_composite_tensor +class LinearOperatorBlockLowerTriangular(linear_operator.LinearOperator): + """Combines `LinearOperators` into a blockwise lower-triangular matrix. + + This operator is initialized with a nested list of linear operators, which + are combined into a new `LinearOperator` whose underlying matrix + representation is square and has each operator on or below the main diagonal, + and zero's elsewhere. Each element of the outer list is a list of + `LinearOperators` corresponding to a row-partition of the blockwise structure. + The number of `LinearOperator`s in row-partion `i` must be equal to `i`. + + For example, a blockwise `3 x 3` `LinearOperatorBlockLowerTriangular` is + initialized with the list `[[op_00], [op_10, op_11], [op_20, op_21, op_22]]`, + where the `op_ij`, `i < 3, j <= i`, are `LinearOperator` instances. The + `LinearOperatorBlockLowerTriangular` behaves as the following blockwise + matrix, where `0` represents appropriately-sized [batch] matrices of zeros: + + ```none + [[op_00, 0, 0], + [op_10, op_11, 0], + [op_20, op_21, op_22]] + ``` + + Each `op_jj` on the diagonal is required to represent a square matrix, and + hence will have shape `batch_shape_j + [M_j, M_j]`. `LinearOperator`s in row + `j` of the blockwise structure must have `range_dimension` equal to that of + `op_jj`, and `LinearOperators` in column `j` must have `domain_dimension` + equal to that of `op_jj`. + + If each `op_jj` on the diagonal has shape `batch_shape_j + [M_j, M_j]`, then + the combined operator has shape `broadcast_batch_shape + [sum M_j, sum M_j]`, + where `broadcast_batch_shape` is the mutual broadcast of `batch_shape_j`, + `j = 0, 1, ..., J`, assuming the intermediate batch shapes broadcast. + Even if the combined shape is well defined, the combined operator's + methods may fail due to lack of broadcasting ability in the defining + operators' methods. + + For example, to create a 4 x 4 linear operator combined of three 2 x 2 + operators: + >>> operator_0 = tf.linalg.LinearOperatorFullMatrix([[1., 2.], [3., 4.]]) + >>> operator_1 = tf.linalg.LinearOperatorFullMatrix([[1., 0.], [0., 1.]]) + >>> operator_2 = tf.linalg.LinearOperatorLowerTriangular([[5., 6.], [7., 8]]) + >>> operator = LinearOperatorBlockLowerTriangular( + ... [[operator_0], [operator_1, operator_2]]) + + >>> operator.to_dense() + + + >>> operator.shape + TensorShape([4, 4]) + + >>> operator.log_abs_determinant() + + + >>> x0 = [[1., 6.], [-3., 4.]] + >>> x1 = [[0., 2.], [4., 0.]] + >>> x = tf.concat([x0, x1], 0) # Shape [2, 4] Tensor + >>> operator.matmul(x) + + + The above `matmul` is equivalent to: + >>> tf.concat([operator_0.matmul(x0), + ... operator_1.matmul(x0) + operator_2.matmul(x1)], axis=0) + + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [M, N], with b >= 0 + x.shape = [B1,...,Bb] + [N, R], with R >= 0. + ``` + + For example: + + Create a [2, 3] batch of 4 x 4 linear operators: + >>> matrix_44 = tf.random.normal(shape=[2, 3, 4, 4]) + >>> operator_44 = tf.linalg.LinearOperatorFullMatrix(matrix_44) + + Create a [1, 3] batch of 5 x 4 linear operators: + >>> matrix_54 = tf.random.normal(shape=[1, 3, 5, 4]) + >>> operator_54 = tf.linalg.LinearOperatorFullMatrix(matrix_54) + + Create a [1, 3] batch of 5 x 5 linear operators: + >>> matrix_55 = tf.random.normal(shape=[1, 3, 5, 5]) + >>> operator_55 = tf.linalg.LinearOperatorFullMatrix(matrix_55) + + Combine to create a [2, 3] batch of 9 x 9 operators: + >>> operator_99 = LinearOperatorBlockLowerTriangular( + ... [[operator_44], [operator_54, operator_55]]) + >>> operator_99.shape + TensorShape([2, 3, 9, 9]) + + Create a shape [2, 1, 9] batch of vectors and apply the operator to it. + >>> x = tf.random.normal(shape=[2, 1, 9]) + >>> y = operator_99.matvec(x) + >>> y.shape + TensorShape([2, 3, 9]) + + Create a blockwise list of vectors and apply the operator to it. A blockwise + list is returned. + >>> x4 = tf.random.normal(shape=[2, 1, 4]) + >>> x5 = tf.random.normal(shape=[2, 3, 5]) + >>> y_blockwise = operator_99.matvec([x4, x5]) + >>> y_blockwise[0].shape + TensorShape([2, 3, 4]) + >>> y_blockwise[1].shape + TensorShape([2, 3, 5]) + + #### Performance + + Suppose `operator` is a `LinearOperatorBlockLowerTriangular` consisting of `D` + row-partitions and `D` column-partitions, such that the total number of + operators is `N = D * (D + 1) // 2`. + + * `operator.matmul` has complexity equal to the sum of the `matmul` + complexities of the individual operators. + * `operator.solve` has complexity equal to the sum of the `solve` complexities + of the operators on the diagonal and the `matmul` complexities of the + operators off the diagonal. + * `operator.determinant` has complexity equal to the sum of the `determinant` + complexities of the operators on the diagonal. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operators, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorBlockLowerTriangular"): + r"""Initialize a `LinearOperatorBlockLowerTriangular`. + + `LinearOperatorBlockLowerTriangular` is initialized with a list of lists of + operators `[[op_0], [op_1, op_2], [op_3, op_4, op_5],...]`. + + Args: + operators: Iterable of iterables of `LinearOperator` objects, each with + the same `dtype`. Each element of `operators` corresponds to a row- + partition, in top-to-bottom order. The operators in each row-partition + are filled in left-to-right. For example, + `operators = [[op_0], [op_1, op_2], [op_3, op_4, op_5]]` creates a + `LinearOperatorBlockLowerTriangular` with full block structure + `[[op_0, 0, 0], [op_1, op_2, 0], [op_3, op_4, op_5]]`. The number of + operators in the `i`th row must be equal to `i`, such that each operator + falls on or below the diagonal of the blockwise structure. + `LinearOperator`s that fall on the diagonal (the last elements of each + row) must be square. The other `LinearOperator`s must have domain + dimension equal to the domain dimension of the `LinearOperator`s in the + same column-partition, and range dimension equal to the range dimension + of the `LinearOperator`s in the same row-partition. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + This will raise a `ValueError` if set to `False`. + name: A name for this `LinearOperator`. + + Raises: + TypeError: If all operators do not have the same `dtype`. + ValueError: If `operators` is empty, contains an erroneous number of + elements, or contains operators with incompatible shapes. + """ + parameters = dict( + operators=operators, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + # Validate operators. + check_ops.assert_proper_iterable(operators) + for row in operators: + check_ops.assert_proper_iterable(row) + operators = [list(row) for row in operators] + + if not operators: + raise ValueError(f"Argument `operators` must be a list of >=1 operators. " + f"Received: {operators}.") + self._operators = operators + self._diagonal_operators = [row[-1] for row in operators] + + dtype = operators[0][0].dtype + self._validate_dtype(dtype) + is_non_singular = self._validate_non_singular(is_non_singular) + self._validate_num_operators() + self._validate_operator_dimensions() + is_square = self._validate_square(is_square) + with ops.name_scope(name): + super(LinearOperatorBlockLowerTriangular, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _validate_num_operators(self): + for i, row in enumerate(self.operators): + if len(row) != i + 1: + raise ValueError( + f"Argument `operators[{i}]` must contain `{i + 1}` blocks. " + f"Received: {len(row)} blocks.") + + def _validate_operator_dimensions(self): + """Check that `operators` have compatible dimensions.""" + for i in range(1, len(self.operators)): + for j in range(i): + op = self.operators[i][j] + + # `above_op` is the operator directly above `op` in the blockwise + # structure, in row partition `i-1`, column partition `j`. `op` should + # have the same `domain_dimension` as `above_op`. + above_op = self.operators[i - 1][j] + + # `right_op` is the operator to the right of `op` in the blockwise + # structure, in row partition `i`, column partition `j+1`. `op` should + # have the same `range_dimension` as `right_op`. + right_op = self.operators[i][j + 1] + + if (op.domain_dimension is not None and + above_op.domain_dimension is not None): + if op.domain_dimension != above_op.domain_dimension: + raise ValueError(f"Argument `operators[{i}][{j}].domain_dimension` " + f"({op.domain_dimension}) must be the same as " + f"`operators[{i-1}][{j}].domain_dimension` " + f"({above_op.domain_dimension}).") + if (op.range_dimension is not None and + right_op.range_dimension is not None): + if op.range_dimension != right_op.range_dimension: + raise ValueError(f"Argument `operators[{i}][{j}].range_dimension` " + f"({op.range_dimension}) must be the same as " + f"`operators[{i}][{j + 1}].range_dimension` " + f"({right_op.range_dimension}).") + + # pylint: disable=g-bool-id-comparison + def _validate_non_singular(self, is_non_singular): + if all(op.is_non_singular for op in self._diagonal_operators): + if is_non_singular is False: + raise ValueError( + f"A blockwise lower-triangular operator with non-singular " + f"operators on the main diagonal is always non-singular. " + f"Expected argument `is_non_singular` to be True. " + f"Received: {is_non_singular}.") + return True + if any(op.is_non_singular is False for op in self._diagonal_operators): + if is_non_singular is True: + raise ValueError( + f"A blockwise lower-triangular operator with a singular operator " + f"on the main diagonal is always singular. Expected argument " + f"`is_non_singular` to be True. Received: {is_non_singular}.") + return False + + def _validate_square(self, is_square): + if is_square is False: + raise ValueError(f"`LinearOperatorBlockLowerTriangular` must be square. " + f"Expected argument `is_square` to be True. " + f"Received: {is_square}.") + for i, op in enumerate(self._diagonal_operators): + if op.is_square is False: + raise ValueError( + f"Matrices on the diagonal (the final elements of each " + f"row-partition in the `operators` list) must be square. Expected " + f"argument `operators[{i}][-1].is_square` to be True. " + f"Received: {op.is_square}.") + return True + # pylint: enable=g-bool-id-comparison + + def _validate_dtype(self, dtype): + for i, row in enumerate(self.operators): + for operator in row: + if operator.dtype != dtype: + name_type = (str((o.name, o.dtype)) for o in row) + raise TypeError( + "Expected all operators to have the same dtype. Found {} in row " + "{} and {} in row 0.".format(name_type, i, str(dtype))) + + @property + def operators(self): + return self._operators + + def _block_range_dimensions(self): + return [op.range_dimension for op in self._diagonal_operators] + + def _block_domain_dimensions(self): + return [op.domain_dimension for op in self._diagonal_operators] + + def _block_range_dimension_tensors(self): + return [op.range_dimension_tensor() for op in self._diagonal_operators] + + def _block_domain_dimension_tensors(self): + return [op.domain_dimension_tensor() for op in self._diagonal_operators] + + def _shape(self): + # Get final matrix shape. + domain_dimension = sum(self._block_domain_dimensions()) + range_dimension = sum(self._block_range_dimensions()) + matrix_shape = tensor_shape.TensorShape([domain_dimension, range_dimension]) + + # Get broadcast batch shape. + # broadcast_shape checks for compatibility. + batch_shape = self.operators[0][0].batch_shape + for row in self.operators[1:]: + for operator in row: + batch_shape = common_shapes.broadcast_shape( + batch_shape, operator.batch_shape) + + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + # Avoid messy broadcasting if possible. + if self.shape.is_fully_defined(): + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.shape.as_list(), dtype=dtypes.int32, name="shape" + ) + + domain_dimension = sum(self._block_domain_dimension_tensors()) + range_dimension = sum(self._block_range_dimension_tensors()) + matrix_shape = array_ops_stack.stack([domain_dimension, range_dimension]) + + batch_shape = self.operators[0][0].batch_shape_tensor() + for row in self.operators[1:]: + for operator in row: + batch_shape = array_ops.broadcast_dynamic_shape( + batch_shape, operator.batch_shape_tensor()) + + return array_ops.concat((batch_shape, matrix_shape), 0) + + def _linop_inverse(self) -> "LinearOperatorBlockLowerTriangular": + """Inverse of LinearOperatorBlockLowerTriangular. + + We recursively apply the identity: + + ```none + |A 0|' = | A' 0| + |B C| |-C'BA' C'| + ``` + + where `A` is n-by-n, `B` is m-by-n, + `C` is m-by-m, and `'` denotes inverse. + + This identity can be verified through multiplication: + + ```none + |A 0|| A' 0| + |B C||-C'BA' C'| + + = | AA' 0| + |BA'-CC'BA' CC'| + + = |I 0| + |0 I| + ``` + Returns: + A 'LinearOperatorBlockLowerTriangular'. + """ + if len(self.operators) == 1: + return (LinearOperatorBlockLowerTriangular( + [[self.operators[0][0].inverse()]], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=(self. + is_positive_definite), + is_square=True)) + + blockwise_dim = len(self.operators) + + # Calculate the inverse of the `LinearOperatorBlockLowerTriangular` + # representing all but the last row of `self` with + # a recursive call (the matrix `A'` in the docstring definition). + upper_left_inverse = ( + LinearOperatorBlockLowerTriangular(self.operators[:-1]).inverse()) + + bottom_row = self.operators[-1] + bottom_right_inverse = bottom_row[-1].inverse() + + # Find the bottom row of the inverse (equal to `[-C'BA', C']` + # in the docstring definition, where `C` is the bottom-right operator of + # `self` and `B` is the set of operators in the + # bottom row excluding `C`). To find `-C'BA'`, we first iterate over the + # column partitions of `A'`. + inverse_bottom_row = [] + for i in range(blockwise_dim - 1): + # Find the `i`-th block of `BA'`. + blocks = [] + for j in range(i, blockwise_dim - 1): + result = bottom_row[j].matmul(upper_left_inverse.operators[j][i]) + if not any( + isinstance(result, op_type) + for op_type in linear_operator_addition.SUPPORTED_OPERATORS + ): + result = linear_operator_full_matrix.LinearOperatorFullMatrix( + result.to_dense()) + blocks.append(result) + + summed_blocks = linear_operator_addition.add_operators(blocks) + assert len(summed_blocks) == 1 + block = summed_blocks[0] + + # Find the `i`-th block of `-C'BA'`. + block = bottom_right_inverse.matmul(block) + block = linear_operator_identity.LinearOperatorScaledIdentity( + num_rows=bottom_right_inverse.domain_dimension_tensor(), + multiplier=math_ops.cast(-1, dtype=block.dtype)).matmul(block) + inverse_bottom_row.append(block) + + # `C'` is the last block of the inverted linear operator. + inverse_bottom_row.append(bottom_right_inverse) + + return (LinearOperatorBlockLowerTriangular( + upper_left_inverse.operators + [inverse_bottom_row], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=(self.is_positive_definite), + is_square=True)) + + def matmul(self, x, adjoint=False, adjoint_arg=False, name="matmul"): + """Transform [batch] matrix `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + X = ... # shape [..., N, R], batch matrix, R > 0. + + Y = operator.matmul(X) + Y.shape + ==> [..., M, R] + + Y[..., :, r] = sum_j A[..., :, j] X[j, r] + ``` + + Args: + x: `LinearOperator`, `Tensor` with compatible shape and same `dtype` as + `self`, or a blockwise iterable of `LinearOperator`s or `Tensor`s. See + class docstring for definition of shape compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + adjoint_arg: Python `bool`. If `True`, compute `A x^H` where `x^H` is + the hermitian transpose (transposition and complex conjugation). + name: A name for this `Op`. + + Returns: + A `LinearOperator` or `Tensor` with shape `[..., M, R]` and same `dtype` + as `self`, or if `x` is blockwise, a list of `Tensor`s with shapes that + concatenate to `[..., M, R]`. + """ + if isinstance(x, linear_operator.LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = x.adjoint() if adjoint_arg else x + + if (right_operator.range_dimension is not None and + left_operator.domain_dimension is not None and + right_operator.range_dimension != left_operator.domain_dimension): + raise ValueError( + "Operators are incompatible. Expected `x` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_matmul(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + arg_dim = -1 if adjoint_arg else -2 + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, x, arg_dim): + for i, block in enumerate(x): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[arg_dim]) + x[i] = block + else: + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + op_dimension = (self.range_dimension if adjoint + else self.domain_dimension) + op_dimension.assert_is_compatible_with(x.shape[arg_dim]) + return self._matmul(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + arg_dim = -1 if adjoint_arg else -2 + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + blockwise_arg = linear_operator_util.arg_is_blockwise( + block_dimensions, x, arg_dim) + if blockwise_arg: + split_x = x + else: + split_dim = -1 if adjoint_arg else -2 + # Split input by columns if adjoint_arg is True, else rows + split_x = linear_operator_util.split_arg_into_blocks( + self._block_domain_dimensions(), + self._block_domain_dimension_tensors, + x, axis=split_dim) + + result_list = [] + # Iterate over row-partitions (i.e. column-partitions of the adjoint). + if adjoint: + for index in range(len(self.operators)): + # Begin with the operator on the diagonal and apply it to the + # respective `rhs` block. + result = self.operators[index][index].matmul( + split_x[index], adjoint=adjoint, adjoint_arg=adjoint_arg) + + # Iterate top to bottom over the operators in the remainder of the + # column-partition (i.e. left to right over the row-partition of the + # adjoint), apply the operator to the respective `rhs` block and + # accumulate the sum. For example, given the + # `LinearOperatorBlockLowerTriangular`: + # + # op = [[A, 0, 0], + # [B, C, 0], + # [D, E, F]] + # + # if `index = 1`, the following loop calculates: + # `y_1 = (C.matmul(x_1, adjoint=adjoint) + + # E.matmul(x_2, adjoint=adjoint)`, + # where `x_1` and `x_2` are splits of `x`. + for j in range(index + 1, len(self.operators)): + result += self.operators[j][index].matmul( + split_x[j], adjoint=adjoint, adjoint_arg=adjoint_arg) + result_list.append(result) + else: + for row in self.operators: + # Begin with the left-most operator in the row-partition and apply it + # to the first `rhs` block. + result = row[0].matmul( + split_x[0], adjoint=adjoint, adjoint_arg=adjoint_arg) + # Iterate left to right over the operators in the remainder of the row + # partition, apply the operator to the respective `rhs` block, and + # accumulate the sum. + for j, operator in enumerate(row[1:]): + result += operator.matmul( + split_x[j + 1], adjoint=adjoint, adjoint_arg=adjoint_arg) + result_list.append(result) + + if blockwise_arg: + return result_list + + result_list = linear_operator_util.broadcast_matrix_batch_dims( + result_list) + return array_ops.concat(result_list, axis=-2) + + def matvec(self, x, adjoint=False, name="matvec"): + """Transform [batch] vector `x` with left multiplication: `x --> Ax`. + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + + X = ... # shape [..., N], batch vector + + Y = operator.matvec(X) + Y.shape + ==> [..., M] + + Y[..., :] = sum_j A[..., :, j] X[..., j] + ``` + + Args: + x: `Tensor` with compatible shape and same `dtype` as `self`, or an + iterable of `Tensor`s. `Tensor`s are treated a [batch] vectors, meaning + for every set of leading dimensions, the last dimension defines a + vector. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, left multiply by the adjoint: `A^H x`. + name: A name for this `Op`. + + Returns: + A `Tensor` with shape `[..., M]` and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_range_dimensions() if adjoint + else self._block_domain_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, x, -1): + for i, block in enumerate(x): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[-1]) + x[i] = block + x_mat = [block[..., array_ops.newaxis] for block in x] + y_mat = self.matmul(x_mat, adjoint=adjoint) + return [array_ops.squeeze(y, axis=-1) for y in y_mat] + + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + self._check_input_dtype(x) + op_dimension = (self.range_dimension if adjoint + else self.domain_dimension) + op_dimension.assert_is_compatible_with(x.shape[-1]) + x_mat = x[..., array_ops.newaxis] + y_mat = self.matmul(x_mat, adjoint=adjoint) + return array_ops.squeeze(y_mat, axis=-1) + + def _determinant(self): + if all(op.is_positive_definite for op in self._diagonal_operators): + return math_ops.exp(self._log_abs_determinant()) + result = self._diagonal_operators[0].determinant() + for op in self._diagonal_operators[1:]: + result *= op.determinant() + return result + + def _log_abs_determinant(self): + result = self._diagonal_operators[0].log_abs_determinant() + for op in self._diagonal_operators[1:]: + result += op.log_abs_determinant() + return result + + def solve(self, rhs, adjoint=False, adjoint_arg=False, name="solve"): + """Solve (exact or approx) `R` (batch) systems of equations: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Given the blockwise `n + 1`-by-`n + 1` linear operator: + + op = [[A_00 0 ... 0 ... 0], + [A_10 A_11 ... 0 ... 0], + ... + [A_k0 A_k1 ... A_kk ... 0], + ... + [A_n0 A_n1 ... A_nk ... A_nn]] + + we find `x = op.solve(y)` by observing that + + `y_k = A_k0.matmul(x_0) + A_k1.matmul(x_1) + ... + A_kk.matmul(x_k)` + + and therefore + + `x_k = A_kk.solve(y_k - + A_k0.matmul(x_0) - ... - A_k(k-1).matmul(x_(k-1)))` + + where `x_k` and `y_k` are the `k`th blocks obtained by decomposing `x` + and `y` along their appropriate axes. + + We first solve `x_0 = A_00.solve(y_0)`. Proceeding inductively, we solve + for `x_k`, `k = 1..n`, given `x_0..x_(k-1)`. + + The adjoint case is solved similarly, beginning with + `x_n = A_nn.solve(y_n, adjoint=True)` and proceeding backwards. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve R > 0 linear systems for every member of the batch. + RHS = ... # shape [..., M, R] + + X = operator.solve(RHS) + # X[..., :, r] is the solution to the r'th linear system + # sum_j A[..., :, j] X[..., j, r] = RHS[..., :, r] + + operator.matmul(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator and compatible shape, + or a list of `Tensor`s. `Tensor`s are treated like a [batch] matrices + meaning for every set of leading dimensions, the last two dimensions + defines a matrix. + See class docstring for definition of compatibility. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + adjoint_arg: Python `bool`. If `True`, solve `A X = rhs^H` where `rhs^H` + is the hermitian transpose (transposition and complex conjugation). + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N, R]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + if self.is_non_singular is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "be singular.") + if self.is_square is False: + raise NotImplementedError( + "Exact solve not implemented for an operator that is expected to " + "not be square.") + if isinstance(rhs, linear_operator.LinearOperator): + left_operator = self.adjoint() if adjoint else self + right_operator = rhs.adjoint() if adjoint_arg else rhs + + if (right_operator.range_dimension is not None and + left_operator.domain_dimension is not None and + right_operator.range_dimension != left_operator.domain_dimension): + raise ValueError( + "Operators are incompatible. Expected `rhs` to have dimension" + " {} but got {}.".format( + left_operator.domain_dimension, right_operator.range_dimension)) + with self._name_scope(name): # pylint: disable=not-callable + return self._linop_solve(left_operator, right_operator) + + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_domain_dimensions() if adjoint + else self._block_range_dimensions()) + arg_dim = -1 if adjoint_arg else -2 + blockwise_arg = linear_operator_util.arg_is_blockwise( + block_dimensions, rhs, arg_dim) + if blockwise_arg: + for i, block in enumerate(rhs): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[arg_dim]) + rhs[i] = block + if adjoint_arg: + split_rhs = [linalg.adjoint(y) for y in rhs] + else: + split_rhs = rhs + + else: + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + op_dimension = (self.domain_dimension if adjoint + else self.range_dimension) + op_dimension.assert_is_compatible_with(rhs.shape[arg_dim]) + + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + split_rhs = linear_operator_util.split_arg_into_blocks( + self._block_domain_dimensions(), + self._block_domain_dimension_tensors, + rhs, axis=-2) + + solution_list = [] + if adjoint: + # For an adjoint blockwise lower-triangular linear operator, the system + # must be solved bottom to top. Iterate backwards over rows of the + # adjoint (i.e. columns of the non-adjoint operator). + for index in reversed(range(len(self.operators))): + y = split_rhs[index] + # Iterate top to bottom over the operators in the off-diagonal portion + # of the column-partition (i.e. row-partition of the adjoint), apply + # the operator to the respective block of the solution found in + # previous iterations, and subtract the result from the `rhs` block. + # For example,let `A`, `B`, and `D` be the linear operators in the top + # row-partition of the adjoint of + # `LinearOperatorBlockLowerTriangular([[A], [B, C], [D, E, F]])`, + # and `x_1` and `x_2` be blocks of the solution found in previous + # iterations of the outer loop. The following loop (when `index == 0`) + # expresses + # `Ax_0 + Bx_1 + Dx_2 = y_0` as `Ax_0 = y_0*`, where + # `y_0* = y_0 - Bx_1 - Dx_2`. + for j in reversed(range(index + 1, len(self.operators))): + y = y - self.operators[j][index].matmul( + solution_list[len(self.operators) - 1 - j], + adjoint=adjoint) + # Continuing the example above, solve `Ax_0 = y_0*` for `x_0`. + solution_list.append( + self._diagonal_operators[index].solve(y, adjoint=adjoint)) + solution_list.reverse() + else: + # Iterate top to bottom over the row-partitions. + for row, y in zip(self.operators, split_rhs): + # Iterate left to right over the operators in the off-diagonal portion + # of the row-partition, apply the operator to the block of the + # solution found in previous iterations, and subtract the result from + # the `rhs` block. For example, let `D`, `E`, and `F` be the linear + # operators in the bottom row-partition of + # `LinearOperatorBlockLowerTriangular([[A], [B, C], [D, E, F]])` and + # `x_0` and `x_1` be blocks of the solution found in previous + # iterations of the outer loop. The following loop + # (when `index == 2`), expresses + # `Dx_0 + Ex_1 + Fx_2 = y_2` as `Fx_2 = y_2*`, where + # `y_2* = y_2 - D_x0 - Ex_1`. + for i, operator in enumerate(row[:-1]): + y = y - operator.matmul(solution_list[i], adjoint=adjoint) + # Continuing the example above, solve `Fx_2 = y_2*` for `x_2`. + solution_list.append(row[-1].solve(y, adjoint=adjoint)) + + if blockwise_arg: + return solution_list + + solution_list = linear_operator_util.broadcast_matrix_batch_dims( + solution_list) + return array_ops.concat(solution_list, axis=-2) + + def solvevec(self, rhs, adjoint=False, name="solve"): + """Solve single equation with best effort: `A X = rhs`. + + The returned `Tensor` will be close to an exact solution if `A` is well + conditioned. Otherwise closeness will vary. See class docstring for details. + + Examples: + + ```python + # Make an operator acting like batch matrix A. Assume A.shape = [..., M, N] + operator = LinearOperator(...) + operator.shape = [..., M, N] + + # Solve one linear system for every member of the batch. + RHS = ... # shape [..., M] + + X = operator.solvevec(RHS) + # X is the solution to the linear system + # sum_j A[..., :, j] X[..., j] = RHS[..., :] + + operator.matvec(X) + ==> RHS + ``` + + Args: + rhs: `Tensor` with same `dtype` as this operator, or list of `Tensor`s + (for blockwise operators). `Tensor`s are treated as [batch] vectors, + meaning for every set of leading dimensions, the last dimension defines + a vector. See class docstring for definition of compatibility regarding + batch dimensions. + adjoint: Python `bool`. If `True`, solve the system involving the adjoint + of this `LinearOperator`: `A^H X = rhs`. + name: A name scope to use for ops added by this method. + + Returns: + `Tensor` with shape `[...,N]` and same `dtype` as `rhs`. + + Raises: + NotImplementedError: If `self.is_non_singular` or `is_square` is False. + """ + with self._name_scope(name): # pylint: disable=not-callable + block_dimensions = (self._block_domain_dimensions() if adjoint + else self._block_range_dimensions()) + if linear_operator_util.arg_is_blockwise(block_dimensions, rhs, -1): + for i, block in enumerate(rhs): + if not isinstance(block, linear_operator.LinearOperator): + block = tensor_conversion.convert_to_tensor_v2_with_dispatch(block) + self._check_input_dtype(block) + block_dimensions[i].assert_is_compatible_with(block.shape[-1]) + rhs[i] = block + rhs_mat = [array_ops.expand_dims(block, axis=-1) for block in rhs] + solution_mat = self.solve(rhs_mat, adjoint=adjoint) + return [array_ops.squeeze(x, axis=-1) for x in solution_mat] + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs" + ) + self._check_input_dtype(rhs) + op_dimension = (self.domain_dimension if adjoint + else self.range_dimension) + op_dimension.assert_is_compatible_with(rhs.shape[-1]) + rhs_mat = array_ops.expand_dims(rhs, axis=-1) + solution_mat = self.solve(rhs_mat, adjoint=adjoint) + return array_ops.squeeze(solution_mat, axis=-1) + + def _diag_part(self): + diag_list = [] + for op in self._diagonal_operators: + # Extend the axis, since `broadcast_matrix_batch_dims` treats all but the + # final two dimensions as batch dimensions. + diag_list.append(op.diag_part()[..., array_ops.newaxis]) + diag_list = linear_operator_util.broadcast_matrix_batch_dims(diag_list) + diagonal = array_ops.concat(diag_list, axis=-2) + return array_ops.squeeze(diagonal, axis=-1) + + def _trace(self): + result = self._diagonal_operators[0].trace() + for op in self._diagonal_operators[1:]: + result += op.trace() + return result + + def _to_dense(self): + num_cols = 0 + dense_rows = [] + flat_broadcast_operators = linear_operator_util.broadcast_matrix_batch_dims( + [op.to_dense() for row in self.operators for op in row]) # pylint: disable=g-complex-comprehension + broadcast_operators = [ + flat_broadcast_operators[i * (i + 1) // 2:(i + 1) * (i + 2) // 2] + for i in range(len(self.operators))] + for row_blocks in broadcast_operators: + batch_row_shape = array_ops.shape(row_blocks[0])[:-1] + num_cols += array_ops.shape(row_blocks[-1])[-1] + zeros_to_pad_after_shape = array_ops.concat( + [batch_row_shape, + [self.domain_dimension_tensor() - num_cols]], axis=-1) + zeros_to_pad_after = array_ops.zeros( + shape=zeros_to_pad_after_shape, dtype=self.dtype) + + row_blocks.append(zeros_to_pad_after) + dense_rows.append(array_ops.concat(row_blocks, axis=-1)) + + mat = array_ops.concat(dense_rows, axis=-2) + mat.set_shape(self.shape) + return mat + + def _assert_non_singular(self): + return control_flow_ops.group([ + op.assert_non_singular() for op in self._diagonal_operators]) + + def _eigvals(self): + eig_list = [] + for op in self._diagonal_operators: + # Extend the axis for broadcasting. + eig_list.append(op.eigvals()[..., array_ops.newaxis]) + eig_list = linear_operator_util.broadcast_matrix_batch_dims(eig_list) + eigs = array_ops.concat(eig_list, axis=-2) + return array_ops.squeeze(eigs, axis=-1) + + @property + def _composite_tensor_fields(self): + return ("operators",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + # None of the operators contribute to the matrix shape. + return {"operators": nest.map_structure(lambda _: 0, self.operators)} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_circulant.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_circulant.py new file mode 100644 index 0000000000000000000000000000000000000000..e2980332db95e988d9012608bcb2c9fbd3713dcc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_circulant.py @@ -0,0 +1,1473 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` coming from a [[nested] block] circulant matrix.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.distributions import util as distribution_util +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.ops.signal import fft_ops +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "LinearOperatorCirculant", + "LinearOperatorCirculant2D", + "LinearOperatorCirculant3D", +] + +# Different FFT Ops will be used for different block depths. +_FFT_OP = {1: fft_ops.fft, 2: fft_ops.fft2d, 3: fft_ops.fft3d} +_IFFT_OP = {1: fft_ops.ifft, 2: fft_ops.ifft2d, 3: fft_ops.ifft3d} + + +def exponential_power_convolution_kernel( + grid_shape, + length_scale, + power=None, + divisor=None, + zero_inflation=None, +): + """Make an exponentiated convolution kernel. + + In signal processing, a [kernel] + (https://en.wikipedia.org/wiki/Kernel_(image_processing)) `h` can be convolved + with a signal `x` to filter its spectral content. + + This function makes a `d-dimensional` convolution kernel `h` of shape + `grid_shape = [N0, N1, ...]`. For `n` a multi-index with `n[i] < Ni / 2`, + + ```h[n] = exp{sum(|n / (length_scale * grid_shape)|**power) / divisor}.``` + + For other `n`, `h` is extended to be circularly symmetric. That is + + ```h[n0 % N0, ...] = h[(-n0) % N0, ...]``` + + Since `h` is circularly symmetric and real valued, `H = FFTd[h]` is the + spectrum of a symmetric (real) circulant operator `A`. + + #### Example uses + + ``` + # Matern one-half kernel, d=1. + # Will be positive definite without zero_inflation. + h = exponential_power_convolution_kernel( + grid_shape=[10], length_scale=[0.1], power=1) + A = LinearOperatorCirculant( + tf.signal.fft(tf.cast(h, tf.complex64)), + is_self_adjoint=True, is_positive_definite=True) + + # Gaussian RBF kernel, d=3. + # Needs zero_inflation since `length_scale` is long enough to cause aliasing. + h = exponential_power_convolution_kernel( + grid_shape=[10, 10, 10], length_scale=[0.1, 0.2, 0.2], power=2, + zero_inflation=0.15) + A = LinearOperatorCirculant3D( + tf.signal.fft3d(tf.cast(h, tf.complex64)), + is_self_adjoint=True, is_positive_definite=True) + ``` + + Args: + grid_shape: Length `d` (`d` in {1, 2, 3}) list-like of Python integers. The + shape of the grid on which the convolution kernel is defined. + length_scale: Length `d` `float` `Tensor`. The scale at which the kernel + decays in each direction, as a fraction of `grid_shape`. + power: Scalar `Tensor` of same `dtype` as `length_scale`, default `2`. + Higher (lower) `power` results in nearby points being more (less) + correlated, and far away points being less (more) correlated. + divisor: Scalar `Tensor` of same `dtype` as `length_scale`. The slope of + decay of `log(kernel)` in terms of fractional grid points, along each + axis, at `length_scale`, is `power/divisor`. By default, `divisor` is set + to `power`. This means, by default, `power=2` results in an exponentiated + quadratic (Gaussian) kernel, and `power=1` is a Matern one-half. + zero_inflation: Scalar `Tensor` of same `dtype` as `length_scale`, in + `[0, 1]`. Let `delta` be the Kronecker delta. That is, + `delta[0, ..., 0] = 1` and all other entries are `0`. Then + `zero_inflation` modifies the return value via + `h --> (1 - zero_inflation) * h + zero_inflation * delta`. This may be + needed to ensure a positive definite kernel, especially if `length_scale` + is large enough for aliasing and `power > 1`. + + Returns: + `Tensor` of shape `grid_shape` with same `dtype` as `length_scale`. + """ + nd = len(grid_shape) + + length_scale = tensor_conversion.convert_to_tensor_v2_with_dispatch( + length_scale, name="length_scale" + ) + dtype = length_scale.dtype + + power = 2. if power is None else power + power = tensor_conversion.convert_to_tensor_v2_with_dispatch( + power, name="power", dtype=dtype + ) + divisor = power if divisor is None else divisor + divisor = tensor_conversion.convert_to_tensor_v2_with_dispatch( + divisor, name="divisor", dtype=dtype + ) + + # With K = grid_shape[i], we implicitly assume the grid vertices along the + # ith dimension are at: + # 0 = 0 / (K - 1), 1 / (K - 1), 2 / (K - 1), ..., (K - 1) / (K - 1) = 1. + zero = math_ops.cast(0., dtype) + one = math_ops.cast(1., dtype) + ts = [math_ops.linspace(zero, one, num=n) for n in grid_shape] + + log_vals = [] + for i, x in enumerate(array_ops.meshgrid(*ts, indexing="ij")): + # midpoint[i] is the vertex just to the left of 1 / 2. + # ifftshift will shift this vertex to position 0. + midpoint = ts[i][math_ops.cast( + math_ops.floor(one / 2. * grid_shape[i]), dtypes.int32)] + log_vals.append(-(math_ops.abs( + (x - midpoint) / length_scale[i]))**power / divisor) + kernel = math_ops.exp( + fft_ops.ifftshift(sum(log_vals), axes=[-i for i in range(1, nd + 1)])) + + if zero_inflation: + # delta.shape = grid_shape, delta[0, 0, 0] = 1., all other entries are 0. + zero_inflation = tensor_conversion.convert_to_tensor_v2_with_dispatch( + zero_inflation, name="zero_inflation", dtype=dtype + ) + delta = array_ops.pad( + array_ops.reshape(one, [1] * nd), [[0, dim - 1] for dim in grid_shape]) + kernel = (1. - zero_inflation) * kernel + zero_inflation * delta + + return kernel + + +# TODO(langmore) Add transformations that create common spectrums, e.g. +# starting with the convolution kernel +# start with half a spectrum, and create a Hermitian one. +# common filters. +# TODO(langmore) Support rectangular Toeplitz matrices. +class _BaseLinearOperatorCirculant(linear_operator.LinearOperator): + """Base class for circulant operators. Not user facing. + + `LinearOperator` acting like a [batch] [[nested] block] circulant matrix. + """ + + def __init__(self, + spectrum: tensor.Tensor, + block_depth: int, + input_output_dtype=dtypes.complex64, + is_non_singular: bool = None, + is_self_adjoint: bool = None, + is_positive_definite: bool = None, + is_square: bool = True, + parameters=None, + name="LinearOperatorCirculant"): + r"""Initialize an `_BaseLinearOperatorCirculant`. + + Args: + spectrum: Shape `[B1,...,Bb] + N` `Tensor`, where `rank(N) in {1, 2, 3}`. + Allowed dtypes: `float16`, `float32`, `float64`, `complex64`, + `complex128`. Type can be different than `input_output_dtype` + block_depth: Python integer, either 1, 2, or 3. Will be 1 for circulant, + 2 for block circulant, and 3 for nested block circulant. + input_output_dtype: `dtype` for input/output. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `spectrum` is real, this will always be true. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix\ + #Extension_for_non_symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + parameters: Python `dict` of parameters used to instantiate this + `LinearOperator`. + name: A name to prepend to all ops created by this class. + + Raises: + ValueError: If `block_depth` is not an allowed value. + TypeError: If `spectrum` is not an allowed type. + """ + + allowed_block_depths = [1, 2, 3] + + self._name = name + + if block_depth not in allowed_block_depths: + raise ValueError( + f"Argument `block_depth` must be one of {allowed_block_depths}. " + f"Received: {block_depth}.") + self._block_depth = block_depth + + with ops.name_scope(name, values=[spectrum]): + self._spectrum = self._check_spectrum_and_return_tensor(spectrum) + + # Check and auto-set hints. + if not self.spectrum.dtype.is_complex: + if is_self_adjoint is False: + raise ValueError( + f"A real spectrum always corresponds to a self-adjoint operator. " + f"Expected argument `is_self_adjoint` to be True when " + f"`spectrum.dtype.is_complex` = True. " + f"Received: {is_self_adjoint}.") + is_self_adjoint = True + + if is_square is False: + raise ValueError( + f"A [[nested] block] circulant operator is always square. " + f"Expected argument `is_square` to be True. Received: {is_square}.") + is_square = True + + super(_BaseLinearOperatorCirculant, self).__init__( + dtype=dtypes.as_dtype(input_output_dtype), + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_spectrum_and_return_tensor(self, spectrum): + """Static check of spectrum. Then return `Tensor` version.""" + spectrum = linear_operator_util.convert_nonref_to_tensor(spectrum, + name="spectrum") + + if spectrum.shape.ndims is not None: + if spectrum.shape.ndims < self.block_depth: + raise ValueError( + f"Argument `spectrum` must have at least {self.block_depth} " + f"dimensions. Received: {spectrum}.") + return spectrum + + @property + def block_depth(self): + """Depth of recursively defined circulant blocks defining this `Operator`. + + With `A` the dense representation of this `Operator`, + + `block_depth = 1` means `A` is symmetric circulant. For example, + + ``` + A = |w z y x| + |x w z y| + |y x w z| + |z y x w| + ``` + + `block_depth = 2` means `A` is block symmetric circulant with symmetric + circulant blocks. For example, with `W`, `X`, `Y`, `Z` symmetric circulant, + + ``` + A = |W Z Y X| + |X W Z Y| + |Y X W Z| + |Z Y X W| + ``` + + `block_depth = 3` means `A` is block symmetric circulant with block + symmetric circulant blocks. + + Returns: + Python `integer`. + """ + return self._block_depth + + def block_shape_tensor(self): + """Shape of the block dimensions of `self.spectrum`.""" + # If spectrum.shape = [s0, s1, s2], and block_depth = 2, + # block_shape = [s1, s2] + return self._block_shape_tensor() + + def _block_shape_tensor(self, spectrum_shape=None): + if self.block_shape.is_fully_defined(): + return linear_operator_util.shape_tensor( + self.block_shape.as_list(), name="block_shape") + spectrum_shape = ( + array_ops.shape(self.spectrum) + if spectrum_shape is None else spectrum_shape) + return spectrum_shape[-self.block_depth:] + + def _linop_adjoint(self) -> "_BaseLinearOperatorCirculant": + spectrum = self.spectrum + if spectrum.dtype.is_complex: + spectrum = math_ops.conj(spectrum) + + # Conjugating the spectrum is sufficient to get the adjoint. + return _BaseLinearOperatorCirculant( + spectrum=spectrum, + block_depth=self.block_depth, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_inverse(self) -> "_BaseLinearOperatorCirculant": + return _BaseLinearOperatorCirculant( + spectrum=1. / self.spectrum, + block_depth=self.block_depth, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True, + input_output_dtype=self.dtype) + + def _linop_matmul( + self, + left_operator: "_BaseLinearOperatorCirculant", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if (not isinstance(right_operator, _BaseLinearOperatorCirculant) + or not isinstance(left_operator, type(right_operator))): + return super()._linop_matmul(left_operator, right_operator) + + return _BaseLinearOperatorCirculant( + spectrum=left_operator.spectrum * right_operator.spectrum, + block_depth=left_operator.block_depth, + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator), + is_positive_definite=( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)), + is_square=True) + + def _linop_solve( + self, + left_operator: "_BaseLinearOperatorCirculant", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if (not isinstance(right_operator, _BaseLinearOperatorCirculant) + or not isinstance(left_operator, type(right_operator))): + return super()._linop_solve(left_operator, right_operator) + + return _BaseLinearOperatorCirculant( + spectrum=right_operator.spectrum / left_operator.spectrum, + block_depth=left_operator.block_depth, + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator), + is_positive_definite=( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)), + is_square=True) + + @property + def block_shape(self): + return self.spectrum.shape[-self.block_depth:] + + @property + def spectrum(self) -> tensor.Tensor: + return self._spectrum + + def _vectorize_then_blockify(self, matrix): + """Shape batch matrix to batch vector, then blockify trailing dimensions.""" + # Suppose + # matrix.shape = [m0, m1, m2, m3], + # and matrix is a matrix because the final two dimensions are matrix dims. + # self.block_depth = 2, + # self.block_shape = [b0, b1] (note b0 * b1 = m2). + # We will reshape matrix to + # [m3, m0, m1, b0, b1]. + + # Vectorize: Reshape to batch vector. + # [m0, m1, m2, m3] --> [m3, m0, m1, m2] + # This is called "vectorize" because we have taken the final two matrix dims + # and turned this into a size m3 batch of vectors. + vec = distribution_util.rotate_transpose(matrix, shift=1) + + # Blockify: Blockfy trailing dimensions. + # [m3, m0, m1, m2] --> [m3, m0, m1, b0, b1] + if (vec.shape.is_fully_defined() and + self.block_shape.is_fully_defined()): + # vec_leading_shape = [m3, m0, m1], + # the parts of vec that will not be blockified. + vec_leading_shape = vec.shape[:-1] + final_shape = vec_leading_shape.concatenate(self.block_shape) + else: + vec_leading_shape = array_ops.shape(vec)[:-1] + final_shape = array_ops.concat( + (vec_leading_shape, self.block_shape_tensor()), 0) + return array_ops.reshape(vec, final_shape) + + def _unblockify(self, x): + """Flatten the trailing block dimensions.""" + # Suppose + # x.shape = [v0, v1, v2, v3], + # self.block_depth = 2. + # Then + # leading shape = [v0, v1] + # block shape = [v2, v3]. + # We will reshape x to + # [v0, v1, v2*v3]. + if x.shape.is_fully_defined(): + # x_shape = [v0, v1, v2, v3] + x_shape = x.shape.as_list() + # x_leading_shape = [v0, v1] + x_leading_shape = x_shape[:-self.block_depth] + # x_block_shape = [v2, v3] + x_block_shape = x_shape[-self.block_depth:] + # flat_shape = [v0, v1, v2*v3] + flat_shape = x_leading_shape + [np.prod(x_block_shape)] + else: + x_shape = array_ops.shape(x) + x_leading_shape = x_shape[:-self.block_depth] + x_block_shape = x_shape[-self.block_depth:] + flat_shape = array_ops.concat( + (x_leading_shape, [math_ops.reduce_prod(x_block_shape)]), 0) + return array_ops.reshape(x, flat_shape) + + def _unblockify_then_matricize(self, vec): + """Flatten the block dimensions then reshape to a batch matrix.""" + # Suppose + # vec.shape = [v0, v1, v2, v3], + # self.block_depth = 2. + # Then + # leading shape = [v0, v1] + # block shape = [v2, v3]. + # We will reshape vec to + # [v1, v2*v3, v0]. + + # Un-blockify: Flatten block dimensions. Reshape + # [v0, v1, v2, v3] --> [v0, v1, v2*v3]. + vec_flat = self._unblockify(vec) + + # Matricize: Reshape to batch matrix. + # [v0, v1, v2*v3] --> [v1, v2*v3, v0], + # representing a shape [v1] batch of [v2*v3, v0] matrices. + matrix = distribution_util.rotate_transpose(vec_flat, shift=-1) + return matrix + + def _fft(self, x): + """FFT along the last self.block_depth dimensions of x. + + Args: + x: `Tensor` with floating or complex `dtype`. + Should be in the form returned by self._vectorize_then_blockify. + + Returns: + `Tensor` with `dtype` `complex64`. + """ + x_complex = _to_complex(x) + return _FFT_OP[self.block_depth](x_complex) + + def _ifft(self, x): + """IFFT along the last self.block_depth dimensions of x. + + Args: + x: `Tensor` with floating or complex dtype. Should be in the form + returned by self._vectorize_then_blockify. + + Returns: + `Tensor` with `dtype` `complex64`. + """ + x_complex = _to_complex(x) + return _IFFT_OP[self.block_depth](x_complex) + + def convolution_kernel(self, name="convolution_kernel"): + """Convolution kernel corresponding to `self.spectrum`. + + The `D` dimensional DFT of this kernel is the frequency domain spectrum of + this operator. + + Args: + name: A name to give this `Op`. + + Returns: + `Tensor` with `dtype` `self.dtype`. + """ + with self._name_scope(name): # pylint: disable=not-callable + h = self._ifft(_to_complex(self.spectrum)) + return math_ops.cast(h, self.dtype) + + def _shape(self): + s_shape = self._spectrum.shape + # Suppose spectrum.shape = [a, b, c, d] + # block_depth = 2 + # Then: + # batch_shape = [a, b] + # N = c*d + # and we want to return + # [a, b, c*d, c*d] + batch_shape = s_shape[:-self.block_depth] + # trailing_dims = [c, d] + trailing_dims = s_shape[-self.block_depth:] + if trailing_dims.is_fully_defined(): + n = np.prod(trailing_dims.as_list()) + else: + n = None + n_x_n = tensor_shape.TensorShape([n, n]) + return batch_shape.concatenate(n_x_n) + + def _shape_tensor(self, spectrum=None): + spectrum = self.spectrum if spectrum is None else spectrum + # See self.shape for explanation of steps + s_shape = array_ops.shape(spectrum) + batch_shape = s_shape[:-self.block_depth] + trailing_dims = s_shape[-self.block_depth:] + n = math_ops.reduce_prod(trailing_dims) + n_x_n = [n, n] + return array_ops.concat((batch_shape, n_x_n), 0) + + def assert_hermitian_spectrum(self, name="assert_hermitian_spectrum"): + """Returns an `Op` that asserts this operator has Hermitian spectrum. + + This operator corresponds to a real-valued matrix if and only if its + spectrum is Hermitian. + + Args: + name: A name to give this `Op`. + + Returns: + An `Op` that asserts this operator has Hermitian spectrum. + """ + eps = np.finfo(self.dtype.real_dtype.as_numpy_dtype).eps + with self._name_scope(name): # pylint: disable=not-callable + # Assume linear accumulation of error. + max_err = eps * self.domain_dimension_tensor() + imag_convolution_kernel = math_ops.imag(self.convolution_kernel()) + return check_ops.assert_less( + math_ops.abs(imag_convolution_kernel), + max_err, + message="Spectrum was not Hermitian") + + def _assert_non_singular(self): + return linear_operator_util.assert_no_entries_with_modulus_zero( + self.spectrum, + message="Singular operator: Spectrum contained zero values.") + + def _assert_positive_definite(self): + # This operator has the action Ax = F^H D F x, + # where D is the diagonal matrix with self.spectrum on the diag. Therefore, + # = , + # Since F is bijective, the condition for positive definite is the same as + # for a diagonal matrix, i.e. real part of spectrum is positive. + message = ( + "Not positive definite: Real part of spectrum was not all positive.") + return check_ops.assert_positive( + math_ops.real(self.spectrum), message=message) + + def _assert_self_adjoint(self): + # Recall correspondence between symmetry and real transforms. See docstring + return linear_operator_util.assert_zero_imag_part( + self.spectrum, + message=( + "Not self-adjoint: The spectrum contained non-zero imaginary part." + )) + + def _broadcast_batch_dims(self, x, spectrum): + """Broadcast batch dims of batch matrix `x` and spectrum.""" + spectrum = tensor_conversion.convert_to_tensor_v2_with_dispatch( + spectrum, name="spectrum" + ) + # spectrum.shape = batch_shape + block_shape + # First make spectrum a batch matrix with + # spectrum.shape = batch_shape + [prod(block_shape), 1] + batch_shape = self._batch_shape_tensor( + shape=self._shape_tensor(spectrum=spectrum)) + spec_mat = array_ops.reshape( + spectrum, array_ops.concat((batch_shape, [-1, 1]), axis=0)) + # Second, broadcast, possibly requiring an addition of array of zeros. + x, spec_mat = linear_operator_util.broadcast_matrix_batch_dims((x, + spec_mat)) + # Third, put the block shape back into spectrum. + x_batch_shape = array_ops.shape(x)[:-2] + spectrum_shape = array_ops.shape(spectrum) + spectrum = array_ops.reshape( + spec_mat, + array_ops.concat( + (x_batch_shape, + self._block_shape_tensor(spectrum_shape=spectrum_shape)), + axis=0)) + + return x, spectrum + + def _cond(self): + # Regardless of whether the operator is real, it is always diagonalizable by + # the Fourier basis F. I.e. A = F S F^H, with S a diagonal matrix + # containing the spectrum. We then have: + # A A^H = F SS^H F^H = F K F^H, + # where K = diag with squared absolute values of the spectrum. + # So in all cases, + abs_singular_values = math_ops.abs(self._unblockify(self.spectrum)) + return (math_ops.reduce_max(abs_singular_values, axis=-1) / + math_ops.reduce_min(abs_singular_values, axis=-1)) + + def _eigvals(self): + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + self._unblockify(self.spectrum) + ) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + x = linalg.adjoint(x) if adjoint_arg else x + # With F the matrix of a DFT, and F^{-1}, F^H the inverse and Hermitian + # transpose, one can show that F^{-1} = F^{H} is the IDFT matrix. Therefore + # matmul(x) = F^{-1} diag(spectrum) F x, + # = F^{H} diag(spectrum) F x, + # so that + # matmul(x, adjoint=True) = F^{H} diag(conj(spectrum)) F x. + spectrum = _to_complex(self.spectrum) + if adjoint: + spectrum = math_ops.conj(spectrum) + + x = math_ops.cast(x, spectrum.dtype) + + x, spectrum = self._broadcast_batch_dims(x, spectrum) + + x_vb = self._vectorize_then_blockify(x) + fft_x_vb = self._fft(x_vb) + block_vector_result = self._ifft(spectrum * fft_x_vb) + y = self._unblockify_then_matricize(block_vector_result) + + return math_ops.cast(y, self.dtype) + + def _determinant(self): + axis = [-(i + 1) for i in range(self.block_depth)] + det = math_ops.reduce_prod(self.spectrum, axis=axis) + return math_ops.cast(det, self.dtype) + + def _log_abs_determinant(self): + axis = [-(i + 1) for i in range(self.block_depth)] + lad = math_ops.reduce_sum( + math_ops.log(math_ops.abs(self.spectrum)), axis=axis) + return math_ops.cast(lad, self.dtype) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + spectrum = _to_complex(self.spectrum) + if adjoint: + spectrum = math_ops.conj(spectrum) + + rhs, spectrum = self._broadcast_batch_dims(rhs, spectrum) + + rhs_vb = self._vectorize_then_blockify(rhs) + fft_rhs_vb = self._fft(rhs_vb) + solution_vb = self._ifft(fft_rhs_vb / spectrum) + x = self._unblockify_then_matricize(solution_vb) + return math_ops.cast(x, self.dtype) + + def _diag_part(self): + # Get ones in shape of diag, which is [B1,...,Bb, N] + # Also get the size of the diag, "N". + if self.shape.is_fully_defined(): + diag_shape = self.shape[:-1] + diag_size = self.domain_dimension.value + else: + diag_shape = self.shape_tensor()[:-1] + diag_size = self.domain_dimension_tensor() + ones_diag = array_ops.ones(diag_shape, dtype=self.dtype) + + # As proved in comments in self._trace, the value on the diag is constant, + # repeated N times. This value is the trace divided by N. + + # The handling of self.shape = (0, 0) is tricky, and is the reason we choose + # to compute trace and use that to compute diag_part, rather than computing + # the value on the diagonal ("diag_value") directly. Both result in a 0/0, + # but in different places, and the current method gives the right result in + # the end. + + # Here, if self.shape = (0, 0), then self.trace() = 0., and then + # diag_value = 0. / 0. = NaN. + diag_value = self.trace() / math_ops.cast(diag_size, self.dtype) + + # If self.shape = (0, 0), then ones_diag = [] (empty tensor), and then + # the following line is NaN * [] = [], as needed. + return diag_value[..., array_ops.newaxis] * ones_diag + + def _trace(self): + # The diagonal of the [[nested] block] circulant operator is the mean of + # the spectrum. + # Proof: For the [0,...,0] element, this follows from the IDFT formula. + # Then the result follows since all diagonal elements are the same. + + # Therefore, the trace is the sum of the spectrum. + + # Get shape of diag along with the axis over which to reduce the spectrum. + # We will reduce the spectrum over all block indices. + if self.spectrum.shape.is_fully_defined(): + spec_rank = self.spectrum.shape.ndims + axis = np.arange(spec_rank - self.block_depth, spec_rank, dtype=np.int32) + else: + spec_rank = array_ops.rank(self.spectrum) + axis = math_ops.range(spec_rank - self.block_depth, spec_rank) + + # Real diag part "re_d". + # Suppose spectrum.shape = [B1,...,Bb, N1, N2] + # self.shape = [B1,...,Bb, N, N], with N1 * N2 = N. + # re_d_value.shape = [B1,...,Bb] + re_d_value = math_ops.reduce_sum(math_ops.real(self.spectrum), axis=axis) + + if not self.dtype.is_complex: + return math_ops.cast(re_d_value, self.dtype) + + # Imaginary part, "im_d". + if self.is_self_adjoint: + im_d_value = array_ops.zeros_like(re_d_value) + else: + im_d_value = math_ops.reduce_sum(math_ops.imag(self.spectrum), axis=axis) + + return math_ops.cast(math_ops.complex(re_d_value, im_d_value), self.dtype) + + @property + def _composite_tensor_fields(self): + return ("spectrum", "input_output_dtype") + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"spectrum": self.block_depth} + + +@tf_export("linalg.LinearOperatorCirculant") +@linear_operator.make_composite_tensor +class LinearOperatorCirculant(_BaseLinearOperatorCirculant): + """`LinearOperator` acting like a circulant matrix. + + This operator acts like a circulant matrix `A` with + shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + #### Description in terms of circulant matrices + + Circulant means the entries of `A` are generated by a single vector, the + convolution kernel `h`: `A_{mn} := h_{m-n mod N}`. With `h = [w, x, y, z]`, + + ``` + A = |w z y x| + |x w z y| + |y x w z| + |z y x w| + ``` + + This means that the result of matrix multiplication `v = Au` has `Lth` column + given circular convolution between `h` with the `Lth` column of `u`. + + #### Description in terms of the frequency spectrum + + There is an equivalent description in terms of the [batch] spectrum `H` and + Fourier transforms. Here we consider `A.shape = [N, N]` and ignore batch + dimensions. Define the discrete Fourier transform (DFT) and its inverse by + + ``` + DFT[ h[n] ] = H[k] := sum_{n = 0}^{N - 1} h_n e^{-i 2pi k n / N} + IDFT[ H[k] ] = h[n] = N^{-1} sum_{k = 0}^{N - 1} H_k e^{i 2pi k n / N} + ``` + + From these definitions, we see that + + ``` + H[0] = sum_{n = 0}^{N - 1} h_n + H[1] = "the first positive frequency" + H[N - 1] = "the first negative frequency" + ``` + + Loosely speaking, with `*` element-wise multiplication, matrix multiplication + is equal to the action of a Fourier multiplier: `A u = IDFT[ H * DFT[u] ]`. + Precisely speaking, given `[N, R]` matrix `u`, let `DFT[u]` be the `[N, R]` + matrix with `rth` column equal to the DFT of the `rth` column of `u`. + Define the `IDFT` similarly. + Matrix multiplication may be expressed columnwise: + + ```(A u)_r = IDFT[ H * (DFT[u])_r ]``` + + #### Operator properties deduced from the spectrum. + + Letting `U` be the `kth` Euclidean basis vector, and `U = IDFT[u]`. + The above formulas show that`A U = H_k * U`. We conclude that the elements + of `H` are the eigenvalues of this operator. Therefore + + * This operator is positive definite if and only if `Real{H} > 0`. + + A general property of Fourier transforms is the correspondence between + Hermitian functions and real valued transforms. + + Suppose `H.shape = [B1,...,Bb, N]`. We say that `H` is a Hermitian spectrum + if, with `%` meaning modulus division, + + ```H[..., n % N] = ComplexConjugate[ H[..., (-n) % N] ]``` + + * This operator corresponds to a real matrix if and only if `H` is Hermitian. + * This operator is self-adjoint if and only if `H` is real. + + See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. + + #### Example of a self-adjoint positive definite operator + + ```python + # spectrum is real ==> operator is self-adjoint + # spectrum is positive ==> operator is positive definite + spectrum = [6., 4, 2] + + operator = LinearOperatorCirculant(spectrum) + + # IFFT[spectrum] + operator.convolution_kernel() + ==> [4 + 0j, 1 + 0.58j, 1 - 0.58j] + + operator.to_dense() + ==> [[4 + 0.0j, 1 - 0.6j, 1 + 0.6j], + [1 + 0.6j, 4 + 0.0j, 1 - 0.6j], + [1 - 0.6j, 1 + 0.6j, 4 + 0.0j]] + ``` + + #### Example of defining in terms of a real convolution kernel + + ```python + # convolution_kernel is real ==> spectrum is Hermitian. + convolution_kernel = [1., 2., 1.]] + spectrum = tf.signal.fft(tf.cast(convolution_kernel, tf.complex64)) + + # spectrum is Hermitian ==> operator is real. + # spectrum is shape [3] ==> operator is shape [3, 3] + # We force the input/output type to be real, which allows this to operate + # like a real matrix. + operator = LinearOperatorCirculant(spectrum, input_output_dtype=tf.float32) + + operator.to_dense() + ==> [[ 1, 1, 2], + [ 2, 1, 1], + [ 1, 2, 1]] + ``` + + #### Example of Hermitian spectrum + + ```python + # spectrum is shape [3] ==> operator is shape [3, 3] + # spectrum is Hermitian ==> operator is real. + spectrum = [1, 1j, -1j] + + operator = LinearOperatorCirculant(spectrum) + + operator.to_dense() + ==> [[ 0.33 + 0j, 0.91 + 0j, -0.24 + 0j], + [-0.24 + 0j, 0.33 + 0j, 0.91 + 0j], + [ 0.91 + 0j, -0.24 + 0j, 0.33 + 0j] + ``` + + #### Example of forcing real `dtype` when spectrum is Hermitian + + ```python + # spectrum is shape [4] ==> operator is shape [4, 4] + # spectrum is real ==> operator is self-adjoint + # spectrum is Hermitian ==> operator is real + # spectrum has positive real part ==> operator is positive-definite. + spectrum = [6., 4, 2, 4] + + # Force the input dtype to be float32. + # Cast the output to float32. This is fine because the operator will be + # real due to Hermitian spectrum. + operator = LinearOperatorCirculant(spectrum, input_output_dtype=tf.float32) + + operator.shape + ==> [4, 4] + + operator.to_dense() + ==> [[4, 1, 0, 1], + [1, 4, 1, 0], + [0, 1, 4, 1], + [1, 0, 1, 4]] + + # convolution_kernel = tf.signal.ifft(spectrum) + operator.convolution_kernel() + ==> [4, 1, 0, 1] + ``` + + #### Performance + + Suppose `operator` is a `LinearOperatorCirculant` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` is `O(R*N*Log[N])` + * `operator.solve(x)` is `O(R*N*Log[N])` + * `operator.determinant()` involves a size `N` `reduce_prod`. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + + References: + Toeplitz and Circulant Matrices - A Review: + [Gray, 2006](https://www.nowpublishers.com/article/Details/CIT-006) + ([pdf](https://ee.stanford.edu/~gray/toeplitz.pdf)) + """ + + def __init__(self, + spectrum: tensor.Tensor, + input_output_dtype=dtypes.complex64, + is_non_singular: bool = None, + is_self_adjoint: bool = None, + is_positive_definite: bool = None, + is_square: bool = True, + name="LinearOperatorCirculant"): + r"""Initialize an `LinearOperatorCirculant`. + + This `LinearOperator` is initialized to have shape `[B1,...,Bb, N, N]` + by providing `spectrum`, a `[B1,...,Bb, N]` `Tensor`. + + If `input_output_dtype = DTYPE`: + + * Arguments to methods such as `matmul` or `solve` must be `DTYPE`. + * Values returned by all methods, such as `matmul` or `determinant` will be + cast to `DTYPE`. + + Note that if the spectrum is not Hermitian, then this operator corresponds + to a complex matrix with non-zero imaginary part. In this case, setting + `input_output_dtype` to a real type will forcibly cast the output to be + real, resulting in incorrect results! + + If on the other hand the spectrum is Hermitian, then this operator + corresponds to a real-valued matrix, and setting `input_output_dtype` to + a real type is fine. + + Args: + spectrum: Shape `[B1,...,Bb, N]` `Tensor`. Allowed dtypes: `float16`, + `float32`, `float64`, `complex64`, `complex128`. Type can be different + than `input_output_dtype` + input_output_dtype: `dtype` for input/output. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `spectrum` is real, this will always be true. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix\ + #Extension_for_non_symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name to prepend to all ops created by this class. + """ + parameters = dict( + spectrum=spectrum, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + super(LinearOperatorCirculant, self).__init__( + spectrum, + block_depth=1, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _linop_adjoint(self) -> "LinearOperatorCirculant": + spectrum = self.spectrum + if spectrum.dtype.is_complex: + spectrum = math_ops.conj(spectrum) + + # Conjugating the spectrum is sufficient to get the adjoint. + return LinearOperatorCirculant( + spectrum=spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorCirculant": + return LinearOperatorCirculant( + spectrum=1. / self.spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True, + input_output_dtype=self.dtype) + + def _linop_solve( + self, + left_operator: "LinearOperatorCirculant", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if not isinstance(right_operator, LinearOperatorCirculant): + return super()._linop_solve(left_operator, right_operator) + + return LinearOperatorCirculant( + spectrum=right_operator.spectrum / left_operator.spectrum, + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator), + is_positive_definite=( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)), + is_square=True) + + +@tf_export("linalg.LinearOperatorCirculant2D") +@linear_operator.make_composite_tensor +class LinearOperatorCirculant2D(_BaseLinearOperatorCirculant): + """`LinearOperator` acting like a block circulant matrix. + + This operator acts like a block circulant matrix `A` with + shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + #### Description in terms of block circulant matrices + + If `A` is block circulant, with block sizes `N0, N1` (`N0 * N1 = N`): + `A` has a block circulant structure, composed of `N0 x N0` blocks, with each + block an `N1 x N1` circulant matrix. + + For example, with `W`, `X`, `Y`, `Z` each circulant, + + ``` + A = |W Z Y X| + |X W Z Y| + |Y X W Z| + |Z Y X W| + ``` + + Note that `A` itself will not in general be circulant. + + #### Description in terms of the frequency spectrum + + There is an equivalent description in terms of the [batch] spectrum `H` and + Fourier transforms. Here we consider `A.shape = [N, N]` and ignore batch + dimensions. + + If `H.shape = [N0, N1]`, (`N0 * N1 = N`): + Loosely speaking, matrix multiplication is equal to the action of a + Fourier multiplier: `A u = IDFT2[ H DFT2[u] ]`. + Precisely speaking, given `[N, R]` matrix `u`, let `DFT2[u]` be the + `[N0, N1, R]` `Tensor` defined by re-shaping `u` to `[N0, N1, R]` and taking + a two dimensional DFT across the first two dimensions. Let `IDFT2` be the + inverse of `DFT2`. Matrix multiplication may be expressed columnwise: + + ```(A u)_r = IDFT2[ H * (DFT2[u])_r ]``` + + #### Operator properties deduced from the spectrum. + + * This operator is positive definite if and only if `Real{H} > 0`. + + A general property of Fourier transforms is the correspondence between + Hermitian functions and real valued transforms. + + Suppose `H.shape = [B1,...,Bb, N0, N1]`, we say that `H` is a Hermitian + spectrum if, with `%` indicating modulus division, + + ``` + H[..., n0 % N0, n1 % N1] = ComplexConjugate[ H[..., (-n0) % N0, (-n1) % N1 ]. + ``` + + * This operator corresponds to a real matrix if and only if `H` is Hermitian. + * This operator is self-adjoint if and only if `H` is real. + + See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. + + ### Example of a self-adjoint positive definite operator + + ```python + # spectrum is real ==> operator is self-adjoint + # spectrum is positive ==> operator is positive definite + spectrum = [[1., 2., 3.], + [4., 5., 6.], + [7., 8., 9.]] + + operator = LinearOperatorCirculant2D(spectrum) + + # IFFT[spectrum] + operator.convolution_kernel() + ==> [[5.0+0.0j, -0.5-.3j, -0.5+.3j], + [-1.5-.9j, 0, 0], + [-1.5+.9j, 0, 0]] + + operator.to_dense() + ==> Complex self adjoint 9 x 9 matrix. + ``` + + #### Example of defining in terms of a real convolution kernel, + + ```python + # convolution_kernel is real ==> spectrum is Hermitian. + convolution_kernel = [[1., 2., 1.], [5., -1., 1.]] + spectrum = tf.signal.fft2d(tf.cast(convolution_kernel, tf.complex64)) + + # spectrum is shape [2, 3] ==> operator is shape [6, 6] + # spectrum is Hermitian ==> operator is real. + operator = LinearOperatorCirculant2D(spectrum, input_output_dtype=tf.float32) + ``` + + #### Performance + + Suppose `operator` is a `LinearOperatorCirculant` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` is `O(R*N*Log[N])` + * `operator.solve(x)` is `O(R*N*Log[N])` + * `operator.determinant()` involves a size `N` `reduce_prod`. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + spectrum: tensor.Tensor, + input_output_dtype=dtypes.complex64, + is_non_singular: bool = None, + is_self_adjoint: bool = None, + is_positive_definite: bool = None, + is_square: bool = True, + name="LinearOperatorCirculant2D"): + r"""Initialize an `LinearOperatorCirculant2D`. + + This `LinearOperator` is initialized to have shape `[B1,...,Bb, N, N]` + by providing `spectrum`, a `[B1,...,Bb, N0, N1]` `Tensor` with `N0*N1 = N`. + + If `input_output_dtype = DTYPE`: + + * Arguments to methods such as `matmul` or `solve` must be `DTYPE`. + * Values returned by all methods, such as `matmul` or `determinant` will be + cast to `DTYPE`. + + Note that if the spectrum is not Hermitian, then this operator corresponds + to a complex matrix with non-zero imaginary part. In this case, setting + `input_output_dtype` to a real type will forcibly cast the output to be + real, resulting in incorrect results! + + If on the other hand the spectrum is Hermitian, then this operator + corresponds to a real-valued matrix, and setting `input_output_dtype` to + a real type is fine. + + Args: + spectrum: Shape `[B1,...,Bb, N0, N1]` `Tensor`. Allowed dtypes: + `float16`, `float32`, `float64`, `complex64`, `complex128`. + Type can be different than `input_output_dtype` + input_output_dtype: `dtype` for input/output. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `spectrum` is real, this will always be true. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix\ + #Extension_for_non_symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name to prepend to all ops created by this class. + """ + parameters = dict( + spectrum=spectrum, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + super(LinearOperatorCirculant2D, self).__init__( + spectrum, + block_depth=2, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _linop_adjoint(self) -> "LinearOperatorCirculant2D": + spectrum = self.spectrum + if spectrum.dtype.is_complex: + spectrum = math_ops.conj(spectrum) + + # Conjugating the spectrum is sufficient to get the adjoint. + return LinearOperatorCirculant2D( + spectrum=spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorCirculant2D": + return LinearOperatorCirculant2D( + spectrum=1. / self.spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True, + input_output_dtype=self.dtype) + + def _linop_solve( + self, + left_operator: "LinearOperatorCirculant2D", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if not isinstance(right_operator, LinearOperatorCirculant2D): + return super()._linop_solve(left_operator, right_operator) + + return LinearOperatorCirculant2D( + spectrum=right_operator.spectrum / left_operator.spectrum, + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator), + is_positive_definite=( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)), + is_square=True) + + +@tf_export("linalg.LinearOperatorCirculant3D") +@linear_operator.make_composite_tensor +class LinearOperatorCirculant3D(_BaseLinearOperatorCirculant): + """`LinearOperator` acting like a nested block circulant matrix. + + This operator acts like a block circulant matrix `A` with + shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + #### Description in terms of block circulant matrices + + If `A` is nested block circulant, with block sizes `N0, N1, N2` + (`N0 * N1 * N2 = N`): + `A` has a block structure, composed of `N0 x N0` blocks, with each + block an `N1 x N1` block circulant matrix. + + For example, with `W`, `X`, `Y`, `Z` each block circulant, + + ``` + A = |W Z Y X| + |X W Z Y| + |Y X W Z| + |Z Y X W| + ``` + + Note that `A` itself will not in general be circulant. + + #### Description in terms of the frequency spectrum + + There is an equivalent description in terms of the [batch] spectrum `H` and + Fourier transforms. Here we consider `A.shape = [N, N]` and ignore batch + dimensions. + + If `H.shape = [N0, N1, N2]`, (`N0 * N1 * N2 = N`): + Loosely speaking, matrix multiplication is equal to the action of a + Fourier multiplier: `A u = IDFT3[ H DFT3[u] ]`. + Precisely speaking, given `[N, R]` matrix `u`, let `DFT3[u]` be the + `[N0, N1, N2, R]` `Tensor` defined by re-shaping `u` to `[N0, N1, N2, R]` and + taking a three dimensional DFT across the first three dimensions. Let `IDFT3` + be the inverse of `DFT3`. Matrix multiplication may be expressed columnwise: + + ```(A u)_r = IDFT3[ H * (DFT3[u])_r ]``` + + #### Operator properties deduced from the spectrum. + + * This operator is positive definite if and only if `Real{H} > 0`. + + A general property of Fourier transforms is the correspondence between + Hermitian functions and real valued transforms. + + Suppose `H.shape = [B1,...,Bb, N0, N1, N2]`, we say that `H` is a Hermitian + spectrum if, with `%` meaning modulus division, + + ``` + H[..., n0 % N0, n1 % N1, n2 % N2] + = ComplexConjugate[ H[..., (-n0) % N0, (-n1) % N1, (-n2) % N2] ]. + ``` + + * This operator corresponds to a real matrix if and only if `H` is Hermitian. + * This operator is self-adjoint if and only if `H` is real. + + See e.g. "Discrete-Time Signal Processing", Oppenheim and Schafer. + + ### Examples + + See `LinearOperatorCirculant` and `LinearOperatorCirculant2D` for examples. + + #### Performance + + Suppose `operator` is a `LinearOperatorCirculant` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` is `O(R*N*Log[N])` + * `operator.solve(x)` is `O(R*N*Log[N])` + * `operator.determinant()` involves a size `N` `reduce_prod`. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + spectrum: tensor.Tensor, + input_output_dtype=dtypes.complex64, + is_non_singular: bool = None, + is_self_adjoint: bool = None, + is_positive_definite: bool = None, + is_square: bool = True, + name="LinearOperatorCirculant3D"): + """Initialize an `LinearOperatorCirculant`. + + This `LinearOperator` is initialized to have shape `[B1,...,Bb, N, N]` + by providing `spectrum`, a `[B1,...,Bb, N0, N1, N2]` `Tensor` + with `N0*N1*N2 = N`. + + If `input_output_dtype = DTYPE`: + + * Arguments to methods such as `matmul` or `solve` must be `DTYPE`. + * Values returned by all methods, such as `matmul` or `determinant` will be + cast to `DTYPE`. + + Note that if the spectrum is not Hermitian, then this operator corresponds + to a complex matrix with non-zero imaginary part. In this case, setting + `input_output_dtype` to a real type will forcibly cast the output to be + real, resulting in incorrect results! + + If on the other hand the spectrum is Hermitian, then this operator + corresponds to a real-valued matrix, and setting `input_output_dtype` to + a real type is fine. + + Args: + spectrum: Shape `[B1,...,Bb, N0, N1, N2]` `Tensor`. Allowed dtypes: + `float16`, `float32`, `float64`, `complex64`, `complex128`. + Type can be different than `input_output_dtype` + input_output_dtype: `dtype` for input/output. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `spectrum` is real, this will always be true. + is_positive_definite: Expect that this operator is positive definite, + meaning the real part of all eigenvalues is positive. We do not require + the operator to be self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix + #Extension_for_non_symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name to prepend to all ops created by this class. + """ + parameters = dict( + spectrum=spectrum, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + super(LinearOperatorCirculant3D, self).__init__( + spectrum, + block_depth=3, + input_output_dtype=input_output_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _linop_adjoint(self) -> "LinearOperatorCirculant3D": + spectrum = self.spectrum + if spectrum.dtype.is_complex: + spectrum = math_ops.conj(spectrum) + + # Conjugating the spectrum is sufficient to get the adjoint. + return LinearOperatorCirculant3D( + spectrum=spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorCirculant3D": + return LinearOperatorCirculant3D( + spectrum=1. / self.spectrum, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True, + input_output_dtype=self.dtype) + + def _linop_solve( + self, + left_operator: "LinearOperatorCirculant3D", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + if not isinstance(right_operator, LinearOperatorCirculant3D): + return super()._linop_solve(left_operator, right_operator) + + return LinearOperatorCirculant3D( + spectrum=right_operator.spectrum / left_operator.spectrum, + is_non_singular=property_hint_util.combined_non_singular_hint( + left_operator, right_operator), + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator), + is_positive_definite=( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)), + is_square=True) + + +def _to_complex(x): + if x.dtype.is_complex: + return x + dtype = dtypes.complex64 + + if x.dtype == dtypes.float64: + dtype = dtypes.complex128 + return math_ops.cast(x, dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_composition.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_composition.py new file mode 100644 index 0000000000000000000000000000000000000000..f81a17ae4d5717f995c69a272e405360a8025863 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_composition.py @@ -0,0 +1,404 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Composes one or more `LinearOperators`.""" + +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_lower_triangular +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorComposition"] + + +@tf_export("linalg.LinearOperatorComposition") +@linear_operator.make_composite_tensor +class LinearOperatorComposition(linear_operator.LinearOperator): + """Composes one or more `LinearOperators`. + + This operator composes one or more linear operators `[op1,...,opJ]`, + building a new `LinearOperator` with action defined by: + + ``` + op_composed(x) := op1(op2(...(opJ(x)...)) + ``` + + If `opj` acts like [batch] matrix `Aj`, then `op_composed` acts like the + [batch] matrix formed with the multiplication `A1 A2...AJ`. + + If `opj` has shape `batch_shape_j + [M_j, N_j]`, then we must have + `N_j = M_{j+1}`, in which case the composed operator has shape equal to + `broadcast_batch_shape + [M_1, N_J]`, where `broadcast_batch_shape` is the + mutual broadcast of `batch_shape_j`, `j = 1,...,J`, assuming the intermediate + batch shapes broadcast. Even if the composed shape is well defined, the + composed operator's methods may fail due to lack of broadcasting ability in + the defining operators' methods. + + ```python + # Create a 2 x 2 linear operator composed of two 2 x 2 operators. + operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]]) + operator_2 = LinearOperatorFullMatrix([[1., 0.], [0., 1.]]) + operator = LinearOperatorComposition([operator_1, operator_2]) + + operator.to_dense() + ==> [[1., 2.] + [3., 4.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor + + # Create a [2, 3] batch of 4 x 5 linear operators. + matrix_45 = tf.random.normal(shape=[2, 3, 4, 5]) + operator_45 = LinearOperatorFullMatrix(matrix) + + # Create a [2, 3] batch of 5 x 6 linear operators. + matrix_56 = tf.random.normal(shape=[2, 3, 5, 6]) + operator_56 = LinearOperatorFullMatrix(matrix_56) + + # Compose to create a [2, 3] batch of 4 x 6 operators. + operator_46 = LinearOperatorComposition([operator_45, operator_56]) + + # Create a shape [2, 3, 6, 2] vector. + x = tf.random.normal(shape=[2, 3, 6, 2]) + operator.matmul(x) + ==> Shape [2, 3, 4, 2] Tensor + ``` + + #### Performance + + The performance of `LinearOperatorComposition` on any operation is equal to + the sum of the individual operators' operations. + + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operators, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name=None): + r"""Initialize a `LinearOperatorComposition`. + + `LinearOperatorComposition` is initialized with a list of operators + `[op_1,...,op_J]`. For the `matmul` method to be well defined, the + composition `op_i.matmul(op_{i+1}(x))` must be defined. Other methods have + similar constraints. + + Args: + operators: Iterable of `LinearOperator` objects, each with + the same `dtype` and composable shape. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. Default is the individual + operators names joined with `_o_`. + + Raises: + TypeError: If all operators do not have the same `dtype`. + ValueError: If `operators` is empty. + """ + parameters = dict( + operators=operators, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name) + + # Validate operators. + check_ops.assert_proper_iterable(operators) + operators = list(operators) + if not operators: + raise ValueError( + "Expected a non-empty list of operators. Found: %s" % operators) + self._operators = operators + + # Validate dtype. + dtype = operators[0].dtype + for operator in operators: + if operator.dtype != dtype: + name_type = (str((o.name, o.dtype)) for o in operators) + raise TypeError( + "Expected all operators to have the same dtype. Found %s" + % " ".join(name_type)) + + # Auto-set and check hints. + if all(operator.is_non_singular for operator in operators): + if is_non_singular is False: # pylint:disable=g-bool-id-comparison + raise ValueError( + "The composition of non-singular operators is always non-singular.") + is_non_singular = True + + if _composition_must_be_self_adjoint(operators): + if is_self_adjoint is False: # pylint:disable=g-bool-id-comparison + raise ValueError( + "The composition was determined to be self-adjoint but user " + "provided incorrect `False` hint.") + is_self_adjoint = True + + if linear_operator_util.is_aat_form(operators): + if is_square is False: # pylint:disable=g-bool-id-comparison + raise ValueError( + "The composition was determined have the form " + "A @ A.H, hence it must be square. The user " + "provided an incorrect `False` hint.") + is_square = True + + if linear_operator_util.is_aat_form(operators) and is_non_singular: + if is_positive_definite is False: # pylint:disable=g-bool-id-comparison + raise ValueError( + "The composition was determined to be non-singular and have the " + "form A @ A.H, hence it must be positive-definite. The user " + "provided an incorrect `False` hint.") + is_positive_definite = True + + # Initialization. + + if name is None: + name = "_o_".join(operator.name for operator in operators) + with ops.name_scope(name): + super(LinearOperatorComposition, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def operators(self): + return self._operators + + def _shape(self): + # Get final matrix shape. + domain_dimension = self.operators[0].domain_dimension + for operator in self.operators[1:]: + domain_dimension.assert_is_compatible_with(operator.range_dimension) + domain_dimension = operator.domain_dimension + + matrix_shape = tensor_shape.TensorShape( + [self.operators[0].range_dimension, + self.operators[-1].domain_dimension]) + + # Get broadcast batch shape. + # broadcast_shape checks for compatibility. + batch_shape = self.operators[0].batch_shape + for operator in self.operators[1:]: + batch_shape = common_shapes.broadcast_shape( + batch_shape, operator.batch_shape) + + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + # Avoid messy broadcasting if possible. + if self.shape.is_fully_defined(): + return ops.convert_to_tensor( + self.shape.as_list(), dtype=dtypes.int32, name="shape") + + # Don't check the matrix dimensions. That would add unnecessary Asserts to + # the graph. Things will fail at runtime naturally if shapes are + # incompatible. + matrix_shape = array_ops_stack.stack([ + self.operators[0].range_dimension_tensor(), + self.operators[-1].domain_dimension_tensor() + ]) + + # Dummy Tensor of zeros. Will never be materialized. + zeros = array_ops.zeros(shape=self.operators[0].batch_shape_tensor()) + for operator in self.operators[1:]: + zeros += array_ops.zeros(shape=operator.batch_shape_tensor()) + batch_shape = array_ops.shape(zeros) + + return array_ops.concat((batch_shape, matrix_shape), 0) + + def _linop_cholesky(self) -> linear_operator.LinearOperator: + """Computes Cholesky(LinearOperatorComposition).""" + # L @ L.H will be handled with special code below. Why is L @ L.H the most + # important special case? + # Note that Diag @ Diag.H and Diag @ TriL and TriL @ Diag are already + # compressed to Diag or TriL by diag matmul + # registration. Similarly for Identity and ScaledIdentity. + # So these would not appear in a LinearOperatorComposition unless explicitly + # constructed as such. So the most important thing to check is L @ L.H. + def _is_llt_product(self): + """Determines if linop = L @ L.H for L = LinearOperatorLowerTriangular.""" + if len(self.operators) != 2: + return False + if not linear_operator_util.is_aat_form(self.operators): + return False + return isinstance( + self.operators[0], + linear_operator_lower_triangular.LinearOperatorLowerTriangular) + + if not _is_llt_product(self): + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + linalg_ops.cholesky(self.to_dense()), + is_non_singular=True, + is_self_adjoint=False, + is_square=True) + + left_op = self.operators[0] + + # left_op.is_positive_definite ==> op already has positive diag,return it. + if left_op.is_positive_definite: + return left_op + + # Recall that the base class has already verified + # linop.is_positive_definite, else linop.cholesky() would have raised. + # So in particular, we know the diagonal has nonzero entries. + # In the generic case, we make op have positive diag by dividing each row + # by the sign of the diag. This is equivalent to setting A = L @ D where + # D is diag(sign(1 / L.diag_part())). Then A is lower triangular with + # positive diag and A @ A^H = L @ D @ D^H @ L^H = L @ L^H = linop. + # This also works for complex L, + # since sign(x + iy) = exp(i * angle(x + iy)). + diag_sign = array_ops.expand_dims( + math_ops.sign(left_op.diag_part()), axis=-2) + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + tril=left_op.tril / diag_sign, + is_non_singular=left_op.is_non_singular, + # L.is_self_adjoint ==> L is diagonal ==> L @ D is diagonal ==> SA + # L.is_self_adjoint is False ==> L not diagonal ==> L @ D not diag ... + is_self_adjoint=left_op.is_self_adjoint, + # L.is_positive_definite ==> L has positive diag ==> L = L @ D + # ==> (L @ D).is_positive_definite. + # L.is_positive_definite is False could result + # in L @ D being PD or not. + # Consider L = [[1, 0], [-2, 1]] and quadratic form with x = [1, 1]. + # Note we will already return left_op if left_op.is_positive_definite + # above, but to be explicit write this below. + is_positive_definite=True if left_op.is_positive_definite else None, + is_square=True, + ) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + # If self.operators = [A, B], and not adjoint, then + # matmul_order_list = [B, A]. + # As a result, we return A.matmul(B.matmul(x)) + if adjoint: + matmul_order_list = self.operators + else: + matmul_order_list = list(reversed(self.operators)) + + result = matmul_order_list[0].matmul( + x, adjoint=adjoint, adjoint_arg=adjoint_arg) + for operator in matmul_order_list[1:]: + result = operator.matmul(result, adjoint=adjoint) + return result + + def _determinant(self): + result = self.operators[0].determinant() + for operator in self.operators[1:]: + result *= operator.determinant() + return result + + def _log_abs_determinant(self): + result = self.operators[0].log_abs_determinant() + for operator in self.operators[1:]: + result += operator.log_abs_determinant() + return result + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + # TODO(langmore) Implement solve using solve_ls if some intermediate + # operator maps to a high dimensional space. + # In that case, an exact solve may still be possible. + + # If self.operators = [A, B], and not adjoint, then + # solve_order_list = [A, B]. + # As a result, we return B.solve(A.solve(x)) + if adjoint: + solve_order_list = list(reversed(self.operators)) + else: + solve_order_list = self.operators + + solution = solve_order_list[0].solve( + rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + for operator in solve_order_list[1:]: + solution = operator.solve(solution, adjoint=adjoint) + return solution + + def _assert_non_singular(self): + if all(operator.is_square for operator in self.operators): + asserts = [operator.assert_non_singular() for operator in self.operators] + return control_flow_ops.group(asserts) + return super(LinearOperatorComposition, self)._assert_non_singular() + + @property + def _composite_tensor_fields(self): + return ("operators",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"operators": [0] * len(self.operators)} + + +def _composition_must_be_self_adjoint(operators): + """Runs some checks to see if composition operators must be SA. + + Args: + operators: List of LinearOperators. + + Returns: + True if the composition must be SA. False if it is not SA OR if we did not + determine whether the composition is SA. + """ + if len(operators) == 1 and operators[0].is_self_adjoint: + return True + + # Check for forms like A @ A.H or (A1 @ A2) @ (A2.H @ A1.H) or ... + if linear_operator_util.is_aat_form(operators): + return True + + # Done checking...could still be SA. + # We may not catch some cases. E.g. (A @ I) @ A.H is SA, but is not AAT form. + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_diag.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..37bfe78d9f46c77c0b658237506520cf2a1c97e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_diag.py @@ -0,0 +1,388 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a diagonal matrix.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_lower_triangular +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorDiag",] + + +@tf_export("linalg.LinearOperatorDiag") +@linear_operator.make_composite_tensor +class LinearOperatorDiag(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] square diagonal matrix. + + This operator acts like a [batch] diagonal matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + `LinearOperatorDiag` is initialized with a (batch) vector. + + ```python + # Create a 2 x 2 diagonal linear operator. + diag = [1., -1.] + operator = LinearOperatorDiag(diag) + + operator.to_dense() + ==> [[1., 0.] + [0., -1.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor + + # Create a [2, 3] batch of 4 x 4 linear operators. + diag = tf.random.normal(shape=[2, 3, 4]) + operator = LinearOperatorDiag(diag) + + # Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible + # since the batch dimensions, [2, 1], are broadcast to + # operator.batch_shape = [2, 3]. + y = tf.random.normal(shape=[2, 1, 4, 2]) + x = operator.solve(y) + ==> operator.matmul(x) = y + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + #### Performance + + Suppose `operator` is a `LinearOperatorDiag` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` involves `N * R` multiplications. + * `operator.solve(x)` involves `N` divisions and `N * R` multiplications. + * `operator.determinant()` involves a size `N` `reduce_prod`. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + diag, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorDiag"): + r"""Initialize a `LinearOperatorDiag`. + + Args: + diag: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`. + The diagonal of the operator. Allowed dtypes: `float16`, `float32`, + `float64`, `complex64`, `complex128`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `diag.dtype` is real, this is auto-set to `True`. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + + Raises: + TypeError: If `diag.dtype` is not an allowed type. + ValueError: If `diag.dtype` is real, and `is_self_adjoint` is not `True`. + """ + parameters = dict( + diag=diag, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[diag]): + self._diag = linear_operator_util.convert_nonref_to_tensor( + diag, name="diag") + self._check_diag(self._diag) + + # Check and auto-set hints. + if not self._diag.dtype.is_complex: + if is_self_adjoint is False: + raise ValueError("A real diagonal operator is always self adjoint.") + else: + is_self_adjoint = True + + if is_square is False: + raise ValueError("Only square diagonal operators currently supported.") + is_square = True + + super(LinearOperatorDiag, self).__init__( + dtype=self._diag.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_diag(self, diag): + """Static check of diag.""" + if diag.shape.ndims is not None and diag.shape.ndims < 1: + raise ValueError("Argument diag must have at least 1 dimension. " + "Found: %s" % diag) + + def _shape(self): + # If d_shape = [5, 3], we return [5, 3, 3]. + d_shape = self._diag.shape + return d_shape.concatenate(d_shape[-1:]) + + def _shape_tensor(self): + d_shape = array_ops.shape(self._diag) + k = d_shape[-1] + return array_ops.concat((d_shape, [k]), 0) + + @property + def diag(self): + return self._diag + + def _linop_inverse(self) -> "LinearOperatorDiag": + return LinearOperatorDiag( + 1. / self.diag, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_matmul( + self, + left_operator: "LinearOperatorDiag", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator) + is_self_adjoint = property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator) + is_positive_definite = ( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)) + if isinstance(right_operator, LinearOperatorDiag): + return LinearOperatorDiag( + diag=left_operator.diag * right_operator.diag, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True, + ) + # instance of linear_operator_identity.LinearOperatorScaledIdentity + elif hasattr(right_operator, "_ones_diag") and hasattr( + right_operator, "multiplier" + ): + return LinearOperatorDiag( + diag=left_operator.diag * right_operator.multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + elif isinstance( + right_operator, + linear_operator_lower_triangular.LinearOperatorLowerTriangular, + ): + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + tril=left_operator.diag[..., None] * right_operator.to_dense(), + is_non_singular=is_non_singular, + # This is safe to do since the Triangular matrix is only self-adjoint + # when it is a diagonal matrix, and hence commutes. + is_self_adjoint=is_self_adjoint, + is_positive_definite=None, + is_square=True) + else: + return super()._linop_matmul(left_operator, right_operator) + + def _linop_solve( + self, + left_operator: "LinearOperatorDiag", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator) + is_self_adjoint = property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator) + is_positive_definite = ( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)) + if isinstance(right_operator, LinearOperatorDiag): + return LinearOperatorDiag( + diag=right_operator.diag / left_operator.diag, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + # instance of linear_operator_identity.LinearOperatorScaledIdentity + elif (hasattr(right_operator, "_ones_diag") + and hasattr(right_operator, "multiplier")): + return LinearOperatorDiag( + diag=right_operator.multiplier / left_operator.diag, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + elif isinstance( + right_operator, + linear_operator_lower_triangular.LinearOperatorLowerTriangular): + return linear_operator_lower_triangular.LinearOperatorLowerTriangular( + tril=right_operator.to_dense() / left_operator.diag[..., None], + is_non_singular=is_non_singular, + # This is safe to do since the Triangular matrix is only self-adjoint + # when it is a diagonal matrix, and hence commutes. + is_self_adjoint=is_self_adjoint, + is_positive_definite=None, + is_square=True) + else: + return super()._linop_solve(left_operator, right_operator) + + def _assert_non_singular(self): + return linear_operator_util.assert_no_entries_with_modulus_zero( + self._diag, + message="Singular operator: Diagonal contained zero values.") + + def _assert_positive_definite(self): + if self.dtype.is_complex: + message = ( + "Diagonal operator had diagonal entries with non-positive real part, " + "thus was not positive definite.") + else: + message = ( + "Real diagonal operator had non-positive diagonal entries, " + "thus was not positive definite.") + + return check_ops.assert_positive( + math_ops.real(self._diag), + message=message) + + def _assert_self_adjoint(self): + return linear_operator_util.assert_zero_imag_part( + self._diag, + message=( + "This diagonal operator contained non-zero imaginary values. " + " Thus it was not self-adjoint.")) + + def _linop_adjoint(self) -> "LinearOperatorDiag": + diag = self.diag + if diag.dtype.is_complex: + diag = math_ops.conj(diag) + + return LinearOperatorDiag( + diag=diag, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_cholesky(self) -> "LinearOperatorDiag": + return LinearOperatorDiag( + math_ops.sqrt(self.diag), + is_non_singular=True, + is_self_adjoint=True, + is_positive_definite=True, + is_square=True) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + diag_term = math_ops.conj(self._diag) if adjoint else self._diag + x = linalg.adjoint(x) if adjoint_arg else x + diag_mat = array_ops.expand_dims(diag_term, -1) + return diag_mat * x + + def _matvec(self, x, adjoint=False): + diag_term = math_ops.conj(self._diag) if adjoint else self._diag + return diag_term * x + + def _determinant(self): + return math_ops.reduce_prod(self._diag, axis=[-1]) + + def _log_abs_determinant(self): + log_det = math_ops.reduce_sum( + math_ops.log(math_ops.abs(self._diag)), axis=[-1]) + if self.dtype.is_complex: + log_det = math_ops.cast(log_det, dtype=self.dtype) + return log_det + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + diag_term = math_ops.conj(self._diag) if adjoint else self._diag + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + inv_diag_mat = array_ops.expand_dims(1. / diag_term, -1) + return rhs * inv_diag_mat + + def _to_dense(self): + return array_ops.matrix_diag(self._diag) + + def _diag_part(self): + return self.diag + + def _add_to_tensor(self, x): + x_diag = array_ops.matrix_diag_part(x) + new_diag = self._diag + x_diag + return array_ops.matrix_set_diag(x, new_diag) + + def _eigvals(self): + return tensor_conversion.convert_to_tensor_v2_with_dispatch(self.diag) + + def _cond(self): + abs_diag = math_ops.abs(self.diag) + return (math_ops.reduce_max(abs_diag, axis=-1) / + math_ops.reduce_min(abs_diag, axis=-1)) + + @property + def _composite_tensor_fields(self): + return ("diag",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"diag": 1} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_full_matrix.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_full_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..579f2d7c74db4555fa283ec0666d9faea361503e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_full_matrix.py @@ -0,0 +1,207 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` that wraps a [batch] matrix.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorFullMatrix"] + + +@tf_export("linalg.LinearOperatorFullMatrix") +@linear_operator.make_composite_tensor +class LinearOperatorFullMatrix(linear_operator.LinearOperator): + """`LinearOperator` that wraps a [batch] matrix. + + This operator wraps a [batch] matrix `A` (which is a `Tensor`) with shape + `[B1,...,Bb, M, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `M x N` matrix. + + ```python + # Create a 2 x 2 linear operator. + matrix = [[1., 2.], [3., 4.]] + operator = LinearOperatorFullMatrix(matrix) + + operator.to_dense() + ==> [[1., 2.] + [3., 4.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor + + # Create a [2, 3] batch of 4 x 4 linear operators. + matrix = tf.random.normal(shape=[2, 3, 4, 4]) + operator = LinearOperatorFullMatrix(matrix) + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [M, N], with b >= 0 + x.shape = [B1,...,Bb] + [N, R], with R >= 0. + ``` + + #### Performance + + `LinearOperatorFullMatrix` has exactly the same performance as would be + achieved by using standard `TensorFlow` matrix ops. Intelligent choices are + made based on the following initialization hints. + + * If `dtype` is real, and `is_self_adjoint` and `is_positive_definite`, a + Cholesky factorization is used for the determinant and solve. + + In all cases, suppose `operator` is a `LinearOperatorFullMatrix` of shape + `[M, N]`, and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` is `O(M * N * R)`. + * If `M=N`, `operator.solve(x)` is `O(N^3 * R)`. + * If `M=N`, `operator.determinant()` is `O(N^3)`. + + If instead `operator` and `x` have shape `[B1,...,Bb, M, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + matrix, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorFullMatrix"): + r"""Initialize a `LinearOperatorFullMatrix`. + + Args: + matrix: Shape `[B1,...,Bb, M, N]` with `b >= 0`, `M, N >= 0`. + Allowed dtypes: `float16`, `float32`, `float64`, `complex64`, + `complex128`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + + Raises: + TypeError: If `diag.dtype` is not an allowed type. + """ + parameters = dict( + matrix=matrix, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[matrix]): + self._matrix = linear_operator_util.convert_nonref_to_tensor( + matrix, name="matrix") + self._check_matrix(self._matrix) + + super(LinearOperatorFullMatrix, self).__init__( + dtype=self._matrix.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_matrix(self, matrix): + """Static check of the `matrix` argument.""" + allowed_dtypes = [ + dtypes.float16, + dtypes.float32, + dtypes.float64, + dtypes.complex64, + dtypes.complex128, + ] + + matrix = tensor_conversion.convert_to_tensor_v2_with_dispatch( + matrix, name="matrix" + ) + + dtype = matrix.dtype + if dtype not in allowed_dtypes: + raise TypeError(f"Argument `matrix` must have dtype in {allowed_dtypes}. " + f"Received: {dtype}.") + + if matrix.shape.ndims is not None and matrix.shape.ndims < 2: + raise ValueError(f"Argument `matrix` must have at least 2 dimensions. " + f"Received: {matrix}.") + + @property + def matrix(self): + """The matrix defining this operator.""" + return self._matrix + + def _shape(self): + return self._matrix.shape + + def _shape_tensor(self): + return array_ops.shape(self._matrix) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + return math_ops.matmul( + self._matrix, x, adjoint_a=adjoint, adjoint_b=adjoint_arg) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + return self._dense_solve(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _to_dense(self): + return self._matrix + + @property + def _composite_tensor_fields(self): + return ("matrix",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"matrix": 2} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_householder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_householder.py new file mode 100644 index 0000000000000000000000000000000000000000..975c4d2fa162f5836f9c7aa8299adca33e471385 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_householder.py @@ -0,0 +1,285 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a Householder transformation.""" + +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorHouseholder",] + + +@tf_export("linalg.LinearOperatorHouseholder") +@linear_operator.make_composite_tensor +class LinearOperatorHouseholder(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] of Householder transformations. + + This operator acts like a [batch] of householder reflections with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + `LinearOperatorHouseholder` is initialized with a (batch) vector. + + A Householder reflection, defined via a vector `v`, which reflects points + in `R^n` about the hyperplane orthogonal to `v` and through the origin. + + ```python + # Create a 2 x 2 householder transform. + vec = [1 / np.sqrt(2), 1. / np.sqrt(2)] + operator = LinearOperatorHouseholder(vec) + + operator.to_dense() + ==> [[0., -1.] + [-1., -0.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + reflection_axis, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorHouseholder"): + r"""Initialize a `LinearOperatorHouseholder`. + + Args: + reflection_axis: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`. + The vector defining the hyperplane to reflect about. + Allowed dtypes: `float16`, `float32`, `float64`, `complex64`, + `complex128`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. This is autoset to true + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + This is autoset to false. + is_square: Expect that this operator acts like square [batch] matrices. + This is autoset to true. + name: A name for this `LinearOperator`. + + Raises: + ValueError: `is_self_adjoint` is not `True`, `is_positive_definite` is + not `False` or `is_square` is not `True`. + """ + parameters = dict( + reflection_axis=reflection_axis, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[reflection_axis]): + self._reflection_axis = linear_operator_util.convert_nonref_to_tensor( + reflection_axis, name="reflection_axis") + self._check_reflection_axis(self._reflection_axis) + + # Check and auto-set hints. + if is_self_adjoint is False: # pylint:disable=g-bool-id-comparison + raise ValueError("A Householder operator is always self adjoint.") + else: + is_self_adjoint = True + + if is_positive_definite is True: # pylint:disable=g-bool-id-comparison + raise ValueError( + "A Householder operator is always non-positive definite.") + else: + is_positive_definite = False + + if is_square is False: # pylint:disable=g-bool-id-comparison + raise ValueError("A Householder operator is always square.") + is_square = True + + super(LinearOperatorHouseholder, self).__init__( + dtype=self._reflection_axis.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_reflection_axis(self, reflection_axis): + """Static check of reflection_axis.""" + if (reflection_axis.shape.ndims is not None and + reflection_axis.shape.ndims < 1): + raise ValueError( + "Argument reflection_axis must have at least 1 dimension. " + "Found: %s" % reflection_axis) + + def _shape(self): + # If d_shape = [5, 3], we return [5, 3, 3]. + d_shape = self._reflection_axis.shape + return d_shape.concatenate(d_shape[-1:]) + + def _shape_tensor(self): + d_shape = array_ops.shape(self._reflection_axis) + k = d_shape[-1] + return array_ops.concat((d_shape, [k]), 0) + + def _assert_non_singular(self): + return control_flow_ops.no_op("assert_non_singular") + + def _assert_positive_definite(self): + raise errors.InvalidArgumentError( + node_def=None, op=None, message="Householder operators are always " + "non-positive definite.") + + def _assert_self_adjoint(self): + return control_flow_ops.no_op("assert_self_adjoint") + + def _linop_adjoint(self) -> "LinearOperatorHouseholder": + return self + + def _linop_inverse(self) -> "LinearOperatorHouseholder": + return self + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + # Given a vector `v`, we would like to reflect `x` about the hyperplane + # orthogonal to `v` going through the origin. We first project `x` to `v` + # to get v * dot(v, x) / dot(v, v). After we project, we can reflect the + # projection about the hyperplane by flipping sign to get + # -v * dot(v, x) / dot(v, v). Finally, we can add back the component + # that is orthogonal to v. This is invariant under reflection, since the + # whole hyperplane is invariant. This component is equal to x - v * dot(v, + # x) / dot(v, v), giving the formula x - 2 * v * dot(v, x) / dot(v, v) + # for the reflection. + + # Note that because this is a reflection, it lies in O(n) (for real vector + # spaces) or U(n) (for complex vector spaces), and thus is its own adjoint. + reflection_axis = tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.reflection_axis + ) + x = linalg.adjoint(x) if adjoint_arg else x + normalized_axis = nn.l2_normalize(reflection_axis, axis=-1) + mat = normalized_axis[..., array_ops.newaxis] + x_dot_normalized_v = math_ops.matmul(mat, x, adjoint_a=True) + + return x - 2 * mat * x_dot_normalized_v + + def _trace(self): + # We have (n - 1) +1 eigenvalues and a single -1 eigenvalue. + shape = self.shape_tensor() + return math_ops.cast( + self._domain_dimension_tensor(shape=shape) - 2, + self.dtype) * array_ops.ones( + shape=self._batch_shape_tensor(shape=shape), dtype=self.dtype) + + def _determinant(self): + # For householder transformations, the determinant is -1. + return -array_ops.ones(shape=self.batch_shape_tensor(), dtype=self.dtype) # pylint: disable=invalid-unary-operand-type + + def _log_abs_determinant(self): + # Orthogonal matrix -> log|Q| = 0. + return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + # A householder reflection is a reflection, hence is idempotent. Thus we + # can just apply a matmul. + return self._matmul(rhs, adjoint, adjoint_arg) + + def _to_dense(self): + reflection_axis = tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.reflection_axis + ) + normalized_axis = nn.l2_normalize(reflection_axis, axis=-1) + mat = normalized_axis[..., array_ops.newaxis] + matrix = -2 * math_ops.matmul(mat, mat, adjoint_b=True) + return array_ops.matrix_set_diag( + matrix, 1. + array_ops.matrix_diag_part(matrix)) + + def _diag_part(self): + reflection_axis = tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.reflection_axis + ) + normalized_axis = nn.l2_normalize(reflection_axis, axis=-1) + return 1. - 2 * normalized_axis * math_ops.conj(normalized_axis) + + def _eigvals(self): + # We have (n - 1) +1 eigenvalues and a single -1 eigenvalue. + result_shape = array_ops.shape(self.reflection_axis) + n = result_shape[-1] + ones_shape = array_ops.concat([result_shape[:-1], [n - 1]], axis=-1) + neg_shape = array_ops.concat([result_shape[:-1], [1]], axis=-1) + eigvals = array_ops.ones(shape=ones_shape, dtype=self.dtype) + eigvals = array_ops.concat( + [-array_ops.ones(shape=neg_shape, dtype=self.dtype), eigvals], axis=-1) # pylint: disable=invalid-unary-operand-type + return eigvals + + def _cond(self): + # Householder matrices are rotations which have condition number 1. + return array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype) + + @property + def reflection_axis(self): + return self._reflection_axis + + @property + def _composite_tensor_fields(self): + return ("reflection_axis",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"reflection_axis": 1} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_identity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_identity.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3fc2d5a85fff7f1576924381d6642d81ad1bf8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_identity.py @@ -0,0 +1,929 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like the identity matrix.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_diag +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "LinearOperatorIdentity", + "LinearOperatorScaledIdentity", +] + + +class BaseLinearOperatorIdentity(linear_operator.LinearOperator): + """Base class for Identity operators.""" + + def _check_num_rows_possibly_add_asserts(self): + """Static check of init arg `num_rows`, possibly add asserts.""" + # Possibly add asserts. + if self._assert_proper_shapes: + self._num_rows = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._num_rows, + 0, + message="Argument num_rows must be a 0-D Tensor."), + check_ops.assert_non_negative( + self._num_rows, + message="Argument num_rows must be non-negative."), + ], self._num_rows) + + # Static checks. + if not self._num_rows.dtype.is_integer: + raise TypeError("Argument num_rows must be integer type. Found:" + " %s" % self._num_rows) + + num_rows_static = self._num_rows_static + + if num_rows_static is None: + return # Cannot do any other static checks. + + if num_rows_static.ndim != 0: + raise ValueError("Argument num_rows must be a 0-D Tensor. Found:" + " %s" % num_rows_static) + + if num_rows_static < 0: + raise ValueError("Argument num_rows must be non-negative. Found:" + " %s" % num_rows_static) + + def _min_matrix_dim(self): + """Minimum of domain/range dimension, if statically available, else None.""" + domain_dim = tensor_shape.dimension_value(self.domain_dimension) + range_dim = tensor_shape.dimension_value(self.range_dimension) + if domain_dim is None or range_dim is None: + return None + return min(domain_dim, range_dim) + + def _min_matrix_dim_tensor(self): + """Minimum of domain/range dimension, as a tensor.""" + return math_ops.reduce_min(self.shape_tensor()[-2:]) + + def _ones_diag(self): + """Returns the diagonal of this operator as all ones.""" + if self.shape.is_fully_defined(): + d_shape = self.batch_shape.concatenate([self._min_matrix_dim()]) + else: + d_shape = array_ops.concat( + [self.batch_shape_tensor(), + [self._min_matrix_dim_tensor()]], axis=0) + + return array_ops.ones(shape=d_shape, dtype=self.dtype) + + +@tf_export("linalg.LinearOperatorIdentity") +@linear_operator.make_composite_tensor +class LinearOperatorIdentity(BaseLinearOperatorIdentity): + """`LinearOperator` acting like a [batch] square identity matrix. + + This operator acts like a [batch] identity matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + `LinearOperatorIdentity` is initialized with `num_rows`, and optionally + `batch_shape`, and `dtype` arguments. If `batch_shape` is `None`, this + operator efficiently passes through all arguments. If `batch_shape` is + provided, broadcasting may occur, which will require making copies. + + ```python + # Create a 2 x 2 identity matrix. + operator = LinearOperatorIdentity(num_rows=2, dtype=tf.float32) + + operator.to_dense() + ==> [[1., 0.] + [0., 1.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> 0. + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor, same as x. + + y = tf.random.normal(shape=[3, 2, 4]) + # Note that y.shape is compatible with operator.shape because operator.shape + # is broadcast to [3, 2, 2]. + # This broadcast does NOT require copying data, since we can infer that y + # will be passed through without changing shape. We are always able to infer + # this if the operator has no batch_shape. + x = operator.solve(y) + ==> Shape [3, 2, 4] Tensor, same as y. + + # Create a 2-batch of 2x2 identity matrices + operator = LinearOperatorIdentity(num_rows=2, batch_shape=[2]) + operator.to_dense() + ==> [[[1., 0.] + [0., 1.]], + [[1., 0.] + [0., 1.]]] + + # Here, even though the operator has a batch shape, the input is the same as + # the output, so x can be passed through without a copy. The operator is able + # to detect that no broadcast is necessary because both x and the operator + # have statically defined shape. + x = ... Shape [2, 2, 3] + operator.matmul(x) + ==> Shape [2, 2, 3] Tensor, same as x + + # Here the operator and x have different batch_shape, and are broadcast. + # This requires a copy, since the output is different size than the input. + x = ... Shape [1, 2, 3] + operator.matmul(x) + ==> Shape [2, 2, 3] Tensor, equal to [x, x] + ``` + + ### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + ### Performance + + If `batch_shape` initialization arg is `None`: + + * `operator.matmul(x)` is `O(1)` + * `operator.solve(x)` is `O(1)` + * `operator.determinant()` is `O(1)` + + If `batch_shape` initialization arg is provided, and static checks cannot + rule out the need to broadcast: + + * `operator.matmul(x)` is `O(D1*...*Dd*N*R)` + * `operator.solve(x)` is `O(D1*...*Dd*N*R)` + * `operator.determinant()` is `O(B1*...*Bb)` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + num_rows, + batch_shape=None, + dtype=None, + is_non_singular=True, + is_self_adjoint=True, + is_positive_definite=True, + is_square=True, + assert_proper_shapes=False, + name="LinearOperatorIdentity"): + r"""Initialize a `LinearOperatorIdentity`. + + The `LinearOperatorIdentity` is initialized with arguments defining `dtype` + and shape. + + This operator is able to broadcast the leading (batch) dimensions, which + sometimes requires copying data. If `batch_shape` is `None`, the operator + can take arguments of any batch shape without copying. See examples. + + Args: + num_rows: Scalar non-negative integer `Tensor`. Number of rows in the + corresponding identity matrix. + batch_shape: Optional `1-D` integer `Tensor`. The shape of the leading + dimensions. If `None`, this operator has no leading dimensions. + dtype: Data type of the matrix that this operator represents. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + assert_proper_shapes: Python `bool`. If `False`, only perform static + checks that initialization and method arguments have proper shape. + If `True`, and static checks are inconclusive, add asserts to the graph. + name: A name for this `LinearOperator` + + Raises: + ValueError: If `num_rows` is determined statically to be non-scalar, or + negative. + ValueError: If `batch_shape` is determined statically to not be 1-D, or + negative. + ValueError: If any of the following is not `True`: + `{is_self_adjoint, is_non_singular, is_positive_definite}`. + TypeError: If `num_rows` or `batch_shape` is ref-type (e.g. Variable). + """ + parameters = dict( + num_rows=num_rows, + batch_shape=batch_shape, + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + assert_proper_shapes=assert_proper_shapes, + name=name) + + dtype = dtype or dtypes.float32 + self._assert_proper_shapes = assert_proper_shapes + + with ops.name_scope(name): + dtype = dtypes.as_dtype(dtype) + if not is_self_adjoint: + raise ValueError("An identity operator is always self adjoint.") + if not is_non_singular: + raise ValueError("An identity operator is always non-singular.") + if not is_positive_definite: + raise ValueError("An identity operator is always positive-definite.") + if not is_square: + raise ValueError("An identity operator is always square.") + + super(LinearOperatorIdentity, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + linear_operator_util.assert_not_ref_type(num_rows, "num_rows") + linear_operator_util.assert_not_ref_type(batch_shape, "batch_shape") + + self._num_rows = linear_operator_util.shape_tensor( + num_rows, name="num_rows") + self._num_rows_static = tensor_util.constant_value(self._num_rows) + self._check_num_rows_possibly_add_asserts() + + if batch_shape is None: + self._batch_shape_arg = None + else: + self._batch_shape_arg = linear_operator_util.shape_tensor( + batch_shape, name="batch_shape_arg") + self._batch_shape_static = tensor_util.constant_value( + self._batch_shape_arg) + self._check_batch_shape_possibly_add_asserts() + + def _shape(self): + matrix_shape = tensor_shape.TensorShape((self._num_rows_static, + self._num_rows_static)) + if self._batch_shape_arg is None: + return matrix_shape + + batch_shape = tensor_shape.TensorShape(self._batch_shape_static) + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + matrix_shape = array_ops_stack.stack( + (self._num_rows, self._num_rows), axis=0) + if self._batch_shape_arg is None: + return matrix_shape + + return array_ops.concat((self._batch_shape_arg, matrix_shape), 0) + + def _linop_adjoint(self) -> "LinearOperatorIdentity": + return self + + def _linop_cholesky(self) -> "LinearOperatorIdentity": + return LinearOperatorIdentity( + num_rows=self._num_rows, # pylint: disable=protected-access + batch_shape=self.batch_shape, + dtype=self.dtype, + is_non_singular=True, + is_self_adjoint=True, + is_positive_definite=True, + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorIdentity": + return self + + def _linop_matmul( + self, + left_operator: "LinearOperatorIdentity", + right_operator: linear_operator.LinearOperator, + ) -> "LinearOperatorIdentity": + del left_operator + return right_operator + + def _linop_solve( + self, + left_operator: "LinearOperatorIdentity", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + del left_operator + return right_operator + + def _assert_non_singular(self): + return control_flow_ops.no_op("assert_non_singular") + + def _assert_positive_definite(self): + return control_flow_ops.no_op("assert_positive_definite") + + def _assert_self_adjoint(self): + return control_flow_ops.no_op("assert_self_adjoint") + + def _possibly_broadcast_batch_shape(self, x): + """Return 'x', possibly after broadcasting the leading dimensions.""" + # If we have no batch shape, our batch shape broadcasts with everything! + if self._batch_shape_arg is None: + return x + + # Static attempt: + # If we determine that no broadcast is necessary, pass x through + # If we need a broadcast, add to an array of zeros. + # + # special_shape is the shape that, when broadcast with x's shape, will give + # the correct broadcast_shape. Note that + # We have already verified the second to last dimension of self.shape + # matches x's shape in assert_compatible_matrix_dimensions. + # Also, the final dimension of 'x' can have any shape. + # Therefore, the final two dimensions of special_shape are 1's. + special_shape = self.batch_shape.concatenate([1, 1]) + bshape = array_ops.broadcast_static_shape(x.shape, special_shape) + if special_shape.is_fully_defined(): + # bshape.is_fully_defined iff special_shape.is_fully_defined. + if bshape == x.shape: + return x + # Use the built in broadcasting of addition. + zeros = array_ops.zeros(shape=special_shape, dtype=self.dtype) + return x + zeros + + # Dynamic broadcast: + # Always add to an array of zeros, rather than using a "cond", since a + # cond would require copying data from GPU --> CPU. + special_shape = array_ops.concat((self.batch_shape_tensor(), [1, 1]), 0) + zeros = array_ops.zeros(shape=special_shape, dtype=self.dtype) + return x + zeros + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + # Note that adjoint has no effect since this matrix is self-adjoint. + x = linalg.adjoint(x) if adjoint_arg else x + if self._assert_proper_shapes: + aps = linear_operator_util.assert_compatible_matrix_dimensions(self, x) + x = control_flow_ops.with_dependencies([aps], x) + return self._possibly_broadcast_batch_shape(x) + + def _determinant(self): + return array_ops.ones(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _log_abs_determinant(self): + return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + return self._matmul(rhs, adjoint_arg=adjoint_arg) + + def _trace(self): + # Get Tensor of all ones of same shape as self.batch_shape. + if self.batch_shape.is_fully_defined(): + batch_of_ones = array_ops.ones(shape=self.batch_shape, dtype=self.dtype) + else: + batch_of_ones = array_ops.ones( + shape=self.batch_shape_tensor(), dtype=self.dtype) + + if self._min_matrix_dim() is not None: + return self._min_matrix_dim() * batch_of_ones + else: + return (math_ops.cast(self._min_matrix_dim_tensor(), self.dtype) * + batch_of_ones) + + def _diag_part(self): + return self._ones_diag() + + def add_to_tensor(self, mat, name="add_to_tensor"): + """Add matrix represented by this operator to `mat`. Equiv to `I + mat`. + + Args: + mat: `Tensor` with same `dtype` and shape broadcastable to `self`. + name: A name to give this `Op`. + + Returns: + A `Tensor` with broadcast shape and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + mat = tensor_conversion.convert_to_tensor_v2_with_dispatch( + mat, name="mat" + ) + mat_diag = array_ops.matrix_diag_part(mat) + new_diag = 1 + mat_diag + return array_ops.matrix_set_diag(mat, new_diag) + + def _eigvals(self): + return self._ones_diag() + + def _cond(self): + return array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype) + + def _check_num_rows_possibly_add_asserts(self): + """Static check of init arg `num_rows`, possibly add asserts.""" + # Possibly add asserts. + if self._assert_proper_shapes: + self._num_rows = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._num_rows, + 0, + message="Argument num_rows must be a 0-D Tensor."), + check_ops.assert_non_negative( + self._num_rows, + message="Argument num_rows must be non-negative."), + ], self._num_rows) + + # Static checks. + if not self._num_rows.dtype.is_integer: + raise TypeError("Argument num_rows must be integer type. Found:" + " %s" % self._num_rows) + + num_rows_static = self._num_rows_static + + if num_rows_static is None: + return # Cannot do any other static checks. + + if num_rows_static.ndim != 0: + raise ValueError("Argument num_rows must be a 0-D Tensor. Found:" + " %s" % num_rows_static) + + if num_rows_static < 0: + raise ValueError("Argument num_rows must be non-negative. Found:" + " %s" % num_rows_static) + + def _check_batch_shape_possibly_add_asserts(self): + """Static check of init arg `batch_shape`, possibly add asserts.""" + if self._batch_shape_arg is None: + return + + # Possibly add asserts + if self._assert_proper_shapes: + self._batch_shape_arg = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._batch_shape_arg, + 1, + message="Argument batch_shape must be a 1-D Tensor."), + check_ops.assert_non_negative( + self._batch_shape_arg, + message="Argument batch_shape must be non-negative."), + ], self._batch_shape_arg) + + # Static checks + if not self._batch_shape_arg.dtype.is_integer: + raise TypeError("Argument batch_shape must be integer type. Found:" + " %s" % self._batch_shape_arg) + + if self._batch_shape_static is None: + return # Cannot do any other static checks. + + if self._batch_shape_static.ndim != 1: + raise ValueError("Argument batch_shape must be a 1-D Tensor. Found:" + " %s" % self._batch_shape_static) + + if np.any(self._batch_shape_static < 0): + raise ValueError("Argument batch_shape must be non-negative. Found:" + "%s" % self._batch_shape_static) + + @property + def _composite_tensor_prefer_static_fields(self): + return ("num_rows", "batch_shape") + + @property + def _composite_tensor_fields(self): + return ("num_rows", "batch_shape", "dtype", "assert_proper_shapes") + + def __getitem__(self, slices): + # Slice the batch shape and return a new LinearOperatorIdentity. + # Use a proxy shape and slice it. Use this as the new batch shape + new_batch_shape = array_ops.shape( + array_ops.ones(self._batch_shape_arg)[slices]) + parameters = dict(self.parameters, batch_shape=new_batch_shape) + return LinearOperatorIdentity(**parameters) + + +@tf_export("linalg.LinearOperatorScaledIdentity") +@linear_operator.make_composite_tensor +class LinearOperatorScaledIdentity(BaseLinearOperatorIdentity): + """`LinearOperator` acting like a scaled [batch] identity matrix `A = c I`. + + This operator acts like a scaled [batch] identity matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + a scaled version of the `N x N` identity matrix. + + `LinearOperatorIdentity` is initialized with `num_rows`, and a `multiplier` + (a `Tensor`) of shape `[B1,...,Bb]`. `N` is set to `num_rows`, and the + `multiplier` determines the scale for each batch member. + + ```python + # Create a 2 x 2 scaled identity matrix. + operator = LinearOperatorIdentity(num_rows=2, multiplier=3.) + + operator.to_dense() + ==> [[3., 0.] + [0., 3.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> 2 * Log[3] + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> 3 * x + + y = tf.random.normal(shape=[3, 2, 4]) + # Note that y.shape is compatible with operator.shape because operator.shape + # is broadcast to [3, 2, 2]. + x = operator.solve(y) + ==> 3 * x + + # Create a 2-batch of 2x2 identity matrices + operator = LinearOperatorIdentity(num_rows=2, multiplier=5.) + operator.to_dense() + ==> [[[5., 0.] + [0., 5.]], + [[5., 0.] + [0., 5.]]] + + x = ... Shape [2, 2, 3] + operator.matmul(x) + ==> 5 * x + + # Here the operator and x have different batch_shape, and are broadcast. + x = ... Shape [1, 2, 3] + operator.matmul(x) + ==> 5 * x + ``` + + ### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + ### Performance + + * `operator.matmul(x)` is `O(D1*...*Dd*N*R)` + * `operator.solve(x)` is `O(D1*...*Dd*N*R)` + * `operator.determinant()` is `O(D1*...*Dd)` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + num_rows, + multiplier, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=True, + assert_proper_shapes=False, + name="LinearOperatorScaledIdentity"): + r"""Initialize a `LinearOperatorScaledIdentity`. + + The `LinearOperatorScaledIdentity` is initialized with `num_rows`, which + determines the size of each identity matrix, and a `multiplier`, + which defines `dtype`, batch shape, and scale of each matrix. + + This operator is able to broadcast the leading (batch) dimensions. + + Args: + num_rows: Scalar non-negative integer `Tensor`. Number of rows in the + corresponding identity matrix. + multiplier: `Tensor` of shape `[B1,...,Bb]`, or `[]` (a scalar). + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + assert_proper_shapes: Python `bool`. If `False`, only perform static + checks that initialization and method arguments have proper shape. + If `True`, and static checks are inconclusive, add asserts to the graph. + name: A name for this `LinearOperator` + + Raises: + ValueError: If `num_rows` is determined statically to be non-scalar, or + negative. + """ + parameters = dict( + num_rows=num_rows, + multiplier=multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + assert_proper_shapes=assert_proper_shapes, + name=name) + + self._assert_proper_shapes = assert_proper_shapes + + with ops.name_scope(name, values=[multiplier, num_rows]): + self._multiplier = linear_operator_util.convert_nonref_to_tensor( + multiplier, name="multiplier") + + # Check and auto-set hints. + if not self._multiplier.dtype.is_complex: + if is_self_adjoint is False: # pylint: disable=g-bool-id-comparison + raise ValueError("A real diagonal operator is always self adjoint.") + else: + is_self_adjoint = True + + if not is_square: + raise ValueError("A ScaledIdentity operator is always square.") + + linear_operator_util.assert_not_ref_type(num_rows, "num_rows") + + super(LinearOperatorScaledIdentity, self).__init__( + dtype=self._multiplier.dtype.base_dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + self._num_rows = linear_operator_util.shape_tensor( + num_rows, name="num_rows") + self._num_rows_static = tensor_util.constant_value(self._num_rows) + self._check_num_rows_possibly_add_asserts() + self._num_rows_cast_to_dtype = math_ops.cast(self._num_rows, self.dtype) + self._num_rows_cast_to_real_dtype = math_ops.cast(self._num_rows, + self.dtype.real_dtype) + + def _shape(self): + matrix_shape = tensor_shape.TensorShape((self._num_rows_static, + self._num_rows_static)) + + batch_shape = self.multiplier.shape + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + matrix_shape = array_ops_stack.stack( + (self._num_rows, self._num_rows), axis=0) + + batch_shape = array_ops.shape(self.multiplier) + return array_ops.concat((batch_shape, matrix_shape), 0) + + def _assert_non_singular(self): + return check_ops.assert_positive( + math_ops.abs(self.multiplier), message="LinearOperator was singular") + + def _assert_positive_definite(self): + return check_ops.assert_positive( + math_ops.real(self.multiplier), + message="LinearOperator was not positive definite.") + + def _assert_self_adjoint(self): + imag_multiplier = math_ops.imag(self.multiplier) + return check_ops.assert_equal( + array_ops.zeros_like(imag_multiplier), + imag_multiplier, + message="LinearOperator was not self-adjoint") + + def _make_multiplier_matrix(self, conjugate=False): + # Shape [B1,...Bb, 1, 1] + multiplier_matrix = array_ops.expand_dims( + array_ops.expand_dims(self.multiplier, -1), -1) + if conjugate: + multiplier_matrix = math_ops.conj(multiplier_matrix) + return multiplier_matrix + + def _linop_adjoint(self) -> "LinearOperatorScaledIdentity": + multiplier = self.multiplier + if multiplier.dtype.is_complex: + multiplier = math_ops.conj(multiplier) + + return LinearOperatorScaledIdentity( + num_rows=self._num_rows, + multiplier=multiplier, + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_cholesky(self) -> "LinearOperatorScaledIdentity": + return LinearOperatorScaledIdentity( + num_rows=self._num_rows, + multiplier=math_ops.sqrt(self.multiplier), + is_non_singular=True, + is_self_adjoint=True, + is_positive_definite=True, + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorScaledIdentity": + return LinearOperatorScaledIdentity( + num_rows=self._num_rows, + multiplier=1. / self.multiplier, + is_non_singular=self.is_non_singular, + is_self_adjoint=True, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_matmul( + self, + left_operator: "LinearOperatorScaledIdentity", + right_operator: linear_operator.LinearOperator, + ) -> "LinearOperatorScaledIdentity": + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator) + is_self_adjoint = property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator) + is_positive_definite = ( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)) + if isinstance(right_operator, LinearOperatorScaledIdentity): + return LinearOperatorScaledIdentity( + num_rows=left_operator.domain_dimension_tensor(), + multiplier=left_operator.multiplier * right_operator.multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + elif isinstance(right_operator, linear_operator_diag.LinearOperatorDiag): + return linear_operator_diag.LinearOperatorDiag( + diag=right_operator.diag * left_operator.multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + else: + return super()._linop_matmul(left_operator, right_operator) + + def _linop_solve( + self, + left_operator: "LinearOperatorScaledIdentity", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + is_non_singular = property_hint_util.combined_non_singular_hint( + left_operator, right_operator) + is_self_adjoint = property_hint_util.combined_commuting_self_adjoint_hint( + left_operator, right_operator) + is_positive_definite = ( + property_hint_util.combined_commuting_positive_definite_hint( + left_operator, right_operator)) + if isinstance(right_operator, LinearOperatorScaledIdentity): + return LinearOperatorScaledIdentity( + num_rows=left_operator.domain_dimension_tensor(), + multiplier=right_operator.multiplier / left_operator.multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + elif isinstance(right_operator, linear_operator_diag.LinearOperatorDiag): + return linear_operator_diag.LinearOperatorDiag( + diag=right_operator.diag / left_operator.multiplier, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=True) + else: + return super()._linop_solve(left_operator, right_operator) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + x = linalg.adjoint(x) if adjoint_arg else x + if self._assert_proper_shapes: + aps = linear_operator_util.assert_compatible_matrix_dimensions(self, x) + x = control_flow_ops.with_dependencies([aps], x) + return x * self._make_multiplier_matrix(conjugate=adjoint) + + def _determinant(self): + return self.multiplier**self._num_rows_cast_to_dtype + + def _log_abs_determinant(self): + return self._num_rows_cast_to_real_dtype * math_ops.log( + math_ops.abs(self.multiplier)) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + if self._assert_proper_shapes: + aps = linear_operator_util.assert_compatible_matrix_dimensions(self, rhs) + rhs = control_flow_ops.with_dependencies([aps], rhs) + return rhs / self._make_multiplier_matrix(conjugate=adjoint) + + def _trace(self): + # Get Tensor of all ones of same shape as self.batch_shape. + if self.batch_shape.is_fully_defined(): + batch_of_ones = array_ops.ones(shape=self.batch_shape, dtype=self.dtype) + else: + batch_of_ones = array_ops.ones( + shape=self.batch_shape_tensor(), dtype=self.dtype) + + if self._min_matrix_dim() is not None: + return self.multiplier * self._min_matrix_dim() * batch_of_ones + else: + return (self.multiplier * math_ops.cast(self._min_matrix_dim_tensor(), + self.dtype) * batch_of_ones) + + def _diag_part(self): + return self._ones_diag() * self.multiplier[..., array_ops.newaxis] + + def add_to_tensor(self, mat, name="add_to_tensor"): + """Add matrix represented by this operator to `mat`. Equiv to `I + mat`. + + Args: + mat: `Tensor` with same `dtype` and shape broadcastable to `self`. + name: A name to give this `Op`. + + Returns: + A `Tensor` with broadcast shape and same `dtype` as `self`. + """ + with self._name_scope(name): # pylint: disable=not-callable + # Shape [B1,...,Bb, 1] + multiplier_vector = array_ops.expand_dims(self.multiplier, -1) + + # Shape [C1,...,Cc, M, M] + mat = tensor_conversion.convert_to_tensor_v2_with_dispatch( + mat, name="mat" + ) + + # Shape [C1,...,Cc, M] + mat_diag = array_ops.matrix_diag_part(mat) + + # multiplier_vector broadcasts here. + new_diag = multiplier_vector + mat_diag + + return array_ops.matrix_set_diag(mat, new_diag) + + def _eigvals(self): + return self._ones_diag() * self.multiplier[..., array_ops.newaxis] + + def _cond(self): + # Condition number for a scalar time identity matrix is one, except when the + # scalar is zero. + return array_ops.where_v2( + math_ops.equal(self._multiplier, 0.), + math_ops.cast(np.nan, dtype=self.dtype), + math_ops.cast(1., dtype=self.dtype)) + + @property + def multiplier(self): + """The [batch] scalar `Tensor`, `c` in `cI`.""" + return self._multiplier + + @property + def _composite_tensor_prefer_static_fields(self): + return ("num_rows",) + + @property + def _composite_tensor_fields(self): + return ("num_rows", "multiplier", "assert_proper_shapes") + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"multiplier": 0} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_inversion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_inversion.py new file mode 100644 index 0000000000000000000000000000000000000000..f47a7d8eb0c360ca372eaf0925df157bae415605 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_inversion.py @@ -0,0 +1,231 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Inverts a non-singular `LinearOperator`.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorInversion"] + + +@tf_export("linalg.LinearOperatorInversion") +@linear_operator.make_composite_tensor +class LinearOperatorInversion(linear_operator.LinearOperator): + """`LinearOperator` representing the inverse of another operator. + + This operator represents the inverse of another operator. + + ```python + # Create a 2 x 2 linear operator. + operator = LinearOperatorFullMatrix([[1., 0.], [0., 2.]]) + operator_inv = LinearOperatorInversion(operator) + + operator_inv.to_dense() + ==> [[1., 0.] + [0., 0.5]] + + operator_inv.shape + ==> [2, 2] + + operator_inv.log_abs_determinant() + ==> - log(2) + + x = ... Shape [2, 4] Tensor + operator_inv.matmul(x) + ==> Shape [2, 4] Tensor, equal to operator.solve(x) + ``` + + #### Performance + + The performance of `LinearOperatorInversion` depends on the underlying + operators performance: `solve` and `matmul` are swapped, and determinant is + inverted. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operator, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name=None): + r"""Initialize a `LinearOperatorInversion`. + + `LinearOperatorInversion` is initialized with an operator `A`. The `solve` + and `matmul` methods are effectively swapped. E.g. + + ``` + A = MyLinearOperator(...) + B = LinearOperatorInversion(A) + x = [....] # a vector + + assert A.matvec(x) == B.solvevec(x) + ``` + + Args: + operator: `LinearOperator` object. If `operator.is_non_singular == False`, + an exception is raised. We do allow `operator.is_non_singular == None`, + in which case this operator will have `is_non_singular == None`. + Similarly for `is_self_adjoint` and `is_positive_definite`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. Default is `operator.name + + "_inv"`. + + Raises: + ValueError: If `operator.is_non_singular` is False. + """ + parameters = dict( + operator=operator, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + self._operator = operator + + # Auto-set and check hints. + if operator.is_non_singular is False or is_non_singular is False: + raise ValueError( + f"Argument `is_non_singular` or argument `operator` must have " + f"supplied hint `is_non_singular` equal to `True` or `None`. " + f"Found `operator.is_non_singular`: {operator.is_non_singular}, " + f"`is_non_singular`: {is_non_singular}.") + if operator.is_square is False or is_square is False: + raise ValueError( + f"Argument `is_square` or argument `operator` must have supplied " + f"hint `is_square` equal to `True` or `None`. Found " + f"`operator.is_square`: {operator.is_square}, " + f"`is_square`: {is_square}.") + + # The congruency of is_non_singular and is_self_adjoint was checked in the + # base operator. Other hints are, in this special case of inversion, ones + # that must be the same for base/derived operator. + combine_hint = ( + linear_operator_util.use_operator_or_provided_hint_unless_contradicting) + + is_square = combine_hint( + operator, "is_square", is_square, + "An operator is square if and only if its inverse is square.") + + is_non_singular = combine_hint( + operator, "is_non_singular", is_non_singular, + "An operator is non-singular if and only if its inverse is " + "non-singular.") + + is_self_adjoint = combine_hint( + operator, "is_self_adjoint", is_self_adjoint, + "An operator is self-adjoint if and only if its inverse is " + "self-adjoint.") + + is_positive_definite = combine_hint( + operator, "is_positive_definite", is_positive_definite, + "An operator is positive-definite if and only if its inverse is " + "positive-definite.") + + # Initialization. + if name is None: + name = operator.name + "_inv" + with ops.name_scope(name): + super(LinearOperatorInversion, self).__init__( + dtype=operator.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def operator(self) -> "LinearOperatorInversion": + """The operator before inversion.""" + return self._operator + + def _linop_inverse(self) -> linear_operator.LinearOperator: + return self.operator + + def _linop_solve( + self, + left_operator: "LinearOperatorInversion", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + """Solve inverse of generic `LinearOperator`s.""" + return left_operator.operator.matmul(right_operator) + + def _assert_non_singular(self): + return self.operator.assert_non_singular() + + def _assert_positive_definite(self): + return self.operator.assert_positive_definite() + + def _assert_self_adjoint(self): + return self.operator.assert_self_adjoint() + + def _shape(self): + return self.operator.shape + + def _shape_tensor(self): + return self.operator.shape_tensor() + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + return self.operator.solve(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _determinant(self): + return 1. / self.operator.determinant() + + def _log_abs_determinant(self): + return -1. * self.operator.log_abs_determinant() + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + return self.operator.matmul(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + + def _eigvals(self): + return 1. / self.operator.eigvals() + + def _cond(self): + return self.operator.cond() + + @property + def _composite_tensor_fields(self): + return ("operator",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"operator": 0} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_kronecker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_kronecker.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbcad12c4a4fa52ae307b327003e4850b7cc5bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_kronecker.py @@ -0,0 +1,538 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Construct the Kronecker product of one or more `LinearOperators`.""" + +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorKronecker"] + + +def _prefer_static_shape(x): + if x.shape.is_fully_defined(): + return x.shape + return array_ops.shape(x) + + +def _prefer_static_concat_shape(first_shape, second_shape_int_list): + """Concatenate a shape with a list of integers as statically as possible. + + Args: + first_shape: `TensorShape` or `Tensor` instance. If a `TensorShape`, + `first_shape.is_fully_defined()` must return `True`. + second_shape_int_list: `list` of scalar integer `Tensor`s. + + Returns: + `Tensor` representing concatenating `first_shape` and + `second_shape_int_list` as statically as possible. + """ + second_shape_int_list_static = [ + tensor_util.constant_value(s) for s in second_shape_int_list] + if (isinstance(first_shape, tensor_shape.TensorShape) and + all(s is not None for s in second_shape_int_list_static)): + return first_shape.concatenate(second_shape_int_list_static) + return array_ops.concat([first_shape, second_shape_int_list], axis=0) + + +@tf_export("linalg.LinearOperatorKronecker") +@linear_operator.make_composite_tensor +class LinearOperatorKronecker(linear_operator.LinearOperator): + """Kronecker product between two `LinearOperators`. + + This operator composes one or more linear operators `[op1,...,opJ]`, + building a new `LinearOperator` representing the Kronecker product: + `op1 x op2 x .. opJ` (we omit parentheses as the Kronecker product is + associative). + + If `opj` has shape `batch_shape_j + [M_j, N_j]`, then the composed operator + will have shape equal to `broadcast_batch_shape + [prod M_j, prod N_j]`, + where the product is over all operators. + + ```python + # Create a 4 x 4 linear operator composed of two 2 x 2 operators. + operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]]) + operator_2 = LinearOperatorFullMatrix([[1., 0.], [2., 1.]]) + operator = LinearOperatorKronecker([operator_1, operator_2]) + + operator.to_dense() + ==> [[1., 0., 2., 0.], + [2., 1., 4., 2.], + [3., 0., 4., 0.], + [6., 3., 8., 4.]] + + operator.shape + ==> [4, 4] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [4, 2] Tensor + operator.matmul(x) + ==> Shape [4, 2] Tensor + + # Create a [2, 3] batch of 4 x 5 linear operators. + matrix_45 = tf.random.normal(shape=[2, 3, 4, 5]) + operator_45 = LinearOperatorFullMatrix(matrix) + + # Create a [2, 3] batch of 5 x 6 linear operators. + matrix_56 = tf.random.normal(shape=[2, 3, 5, 6]) + operator_56 = LinearOperatorFullMatrix(matrix_56) + + # Compose to create a [2, 3] batch of 20 x 30 operators. + operator_large = LinearOperatorKronecker([operator_45, operator_56]) + + # Create a shape [2, 3, 20, 2] vector. + x = tf.random.normal(shape=[2, 3, 6, 2]) + operator_large.matmul(x) + ==> Shape [2, 3, 30, 2] Tensor + ``` + + #### Performance + + The performance of `LinearOperatorKronecker` on any operation is equal to + the sum of the individual operators' operations. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + operators, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name=None): + r"""Initialize a `LinearOperatorKronecker`. + + `LinearOperatorKronecker` is initialized with a list of operators + `[op_1,...,op_J]`. + + Args: + operators: Iterable of `LinearOperator` objects, each with + the same `dtype` and composable shape, representing the Kronecker + factors. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix\ + #Extension_for_non_symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. Default is the individual + operators names joined with `_x_`. + + Raises: + TypeError: If all operators do not have the same `dtype`. + ValueError: If `operators` is empty. + """ + parameters = dict( + operators=operators, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + # Validate operators. + check_ops.assert_proper_iterable(operators) + operators = list(operators) + if not operators: + raise ValueError(f"Argument `operators` must be a list of >=1 operators. " + f"Received: {operators}.") + self._operators = operators + + # Validate dtype. + dtype = operators[0].dtype + for operator in operators: + if operator.dtype != dtype: + name_type = (str((o.name, o.dtype)) for o in operators) + raise TypeError( + f"Expected every operation in argument `operators` to have the " + f"same dtype. Received {list(name_type)}.") + + # Auto-set and check hints. + # A Kronecker product is invertible, if and only if all factors are + # invertible. + if all(operator.is_non_singular for operator in operators): + if is_non_singular is False: + raise ValueError( + f"The Kronecker product of non-singular operators is always " + f"non-singular. Expected argument `is_non_singular` to be True. " + f"Received: {is_non_singular}.") + is_non_singular = True + + if all(operator.is_self_adjoint for operator in operators): + if is_self_adjoint is False: + raise ValueError( + f"The Kronecker product of self-adjoint operators is always " + f"self-adjoint. Expected argument `is_self_adjoint` to be True. " + f"Received: {is_self_adjoint}.") + is_self_adjoint = True + + # The eigenvalues of a Kronecker product are equal to the products of eigen + # values of the corresponding factors. + if all(operator.is_positive_definite for operator in operators): + if is_positive_definite is False: + raise ValueError( + f"The Kronecker product of positive-definite operators is always " + f"positive-definite. Expected argument `is_positive_definite` to " + f"be True. Received: {is_positive_definite}.") + is_positive_definite = True + + if name is None: + name = operators[0].name + for operator in operators[1:]: + name += "_x_" + operator.name + with ops.name_scope(name): + super(LinearOperatorKronecker, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def operators(self): + return self._operators + + def _shape(self): + # Get final matrix shape. + domain_dimension = self.operators[0].domain_dimension + for operator in self.operators[1:]: + domain_dimension = domain_dimension * operator.domain_dimension + + range_dimension = self.operators[0].range_dimension + for operator in self.operators[1:]: + range_dimension = range_dimension * operator.range_dimension + + matrix_shape = tensor_shape.TensorShape([ + range_dimension, domain_dimension]) + + # Get broadcast batch shape. + # broadcast_shape checks for compatibility. + batch_shape = self.operators[0].batch_shape + for operator in self.operators[1:]: + batch_shape = common_shapes.broadcast_shape( + batch_shape, operator.batch_shape) + + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + domain_dimension = self.operators[0].domain_dimension_tensor() + for operator in self.operators[1:]: + domain_dimension = domain_dimension * operator.domain_dimension_tensor() + + range_dimension = self.operators[0].range_dimension_tensor() + for operator in self.operators[1:]: + range_dimension = range_dimension * operator.range_dimension_tensor() + + matrix_shape = [range_dimension, domain_dimension] + + # Get broadcast batch shape. + # broadcast_shape checks for compatibility. + batch_shape = self.operators[0].batch_shape_tensor() + for operator in self.operators[1:]: + batch_shape = array_ops.broadcast_dynamic_shape( + batch_shape, operator.batch_shape_tensor()) + + return array_ops.concat((batch_shape, matrix_shape), 0) + + def _linop_adjoint(self) -> "LinearOperatorKronecker": + return LinearOperatorKronecker( + operators=[operator.adjoint() for operator in self.operators], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _linop_cholesky(self) -> "LinearOperatorKronecker": + # Cholesky decomposition of a Kronecker product is the Kronecker product + # of cholesky decompositions. + return LinearOperatorKronecker( + operators=[operator.cholesky() for operator in self.operators], + is_non_singular=True, + is_self_adjoint=None, # Let the operators passed in decide. + is_square=True) + + def _linop_inverse(self) -> "LinearOperatorKronecker": + # Inverse decomposition of a Kronecker product is the Kronecker product + # of inverse decompositions. + return LinearOperatorKronecker( + operators=[ + operator.inverse() for operator in self.operators], + is_non_singular=self.is_non_singular, + is_self_adjoint=self.is_self_adjoint, + is_positive_definite=self.is_positive_definite, + is_square=True) + + def _solve_matmul_internal( + self, + x, + solve_matmul_fn, + adjoint=False, + adjoint_arg=False): + # We heavily rely on Roth's column Lemma [1]: + # (A x B) * vec X = vec BXA^T + # where vec stacks all the columns of the matrix under each other. + # In our case, we use a variant of the lemma that is row-major + # friendly: (A x B) * vec' X = vec' AXB^T + # Where vec' reshapes a matrix into a vector. We can repeatedly apply this + # for a collection of kronecker products. + # Given that (A x B)^-1 = A^-1 x B^-1 and (A x B)^T = A^T x B^T, we can + # use the above to compute multiplications, solves with any composition of + # transposes. + output = x + + if adjoint_arg: + if self.dtype.is_complex: + output = math_ops.conj(output) + else: + output = linalg.transpose(output) + + for o in reversed(self.operators): + # Statically compute the reshape. + if adjoint: + operator_dimension = o.range_dimension_tensor() + else: + operator_dimension = o.domain_dimension_tensor() + output_shape = _prefer_static_shape(output) + + if tensor_util.constant_value(operator_dimension) is not None: + operator_dimension = tensor_util.constant_value(operator_dimension) + if output.shape[-2] is not None and output.shape[-1] is not None: + dim = int(output.shape[-2] * output_shape[-1] // operator_dimension) + else: + dim = math_ops.cast( + output_shape[-2] * output_shape[-1] // operator_dimension, + dtype=dtypes.int32) + + output_shape = _prefer_static_concat_shape( + output_shape[:-2], [dim, operator_dimension]) + output = array_ops.reshape(output, shape=output_shape) + + # Conjugate because we are trying to compute A @ B^T, but + # `LinearOperator` only supports `adjoint_arg`. + if self.dtype.is_complex: + output = math_ops.conj(output) + + output = solve_matmul_fn( + o, output, adjoint=adjoint, adjoint_arg=True) + + if adjoint_arg: + col_dim = _prefer_static_shape(x)[-2] + else: + col_dim = _prefer_static_shape(x)[-1] + + if adjoint: + row_dim = self.domain_dimension_tensor() + else: + row_dim = self.range_dimension_tensor() + + matrix_shape = [row_dim, col_dim] + + output = array_ops.reshape( + output, + _prefer_static_concat_shape( + _prefer_static_shape(output)[:-2], matrix_shape)) + + if x.shape.is_fully_defined(): + if adjoint_arg: + column_dim = x.shape[-2] + else: + column_dim = x.shape[-1] + broadcast_batch_shape = common_shapes.broadcast_shape( + x.shape[:-2], self.batch_shape) + if adjoint: + matrix_dimensions = [self.domain_dimension, column_dim] + else: + matrix_dimensions = [self.range_dimension, column_dim] + + output.set_shape(broadcast_batch_shape.concatenate( + matrix_dimensions)) + + return output + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + def matmul_fn(o, x, adjoint, adjoint_arg): + return o.matmul(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + return self._solve_matmul_internal( + x=x, + solve_matmul_fn=matmul_fn, + adjoint=adjoint, + adjoint_arg=adjoint_arg) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + def solve_fn(o, rhs, adjoint, adjoint_arg): + return o.solve(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + return self._solve_matmul_internal( + x=rhs, + solve_matmul_fn=solve_fn, + adjoint=adjoint, + adjoint_arg=adjoint_arg) + + def _determinant(self): + # Note that we have |X1 x X2| = |X1| ** n * |X2| ** m, where X1 is an m x m + # matrix, and X2 is an n x n matrix. We can iteratively apply this property + # to get the determinant of |X1 x X2 x X3 ...|. If T is the product of the + # domain dimension of all operators, then we have: + # |X1 x X2 x X3 ...| = + # |X1| ** (T / m) * |X2 x X3 ... | ** m = + # |X1| ** (T / m) * |X2| ** (m * (T / m) / n) * ... = + # |X1| ** (T / m) * |X2| ** (T / n) * | X3 x X4... | ** (m * n) + # And by doing induction we have product(|X_i| ** (T / dim(X_i))). + total = self.domain_dimension_tensor() + determinant = 1. + for operator in self.operators: + determinant = determinant * operator.determinant() ** math_ops.cast( + total / operator.domain_dimension_tensor(), + dtype=operator.dtype) + return determinant + + def _log_abs_determinant(self): + # This will be sum((total / dim(x_i)) * log |X_i|) + total = self.domain_dimension_tensor() + log_abs_det = 0. + for operator in self.operators: + log_abs_det += operator.log_abs_determinant() * math_ops.cast( + total / operator.domain_dimension_tensor(), + dtype=operator.dtype) + return log_abs_det + + def _trace(self): + # tr(A x B) = tr(A) * tr(B) + trace = 1. + for operator in self.operators: + trace = trace * operator.trace() + return trace + + def _diag_part(self): + diag_part = self.operators[0].diag_part() + for operator in self.operators[1:]: + diag_part = diag_part[..., :, array_ops.newaxis] + op_diag_part = operator.diag_part()[..., array_ops.newaxis, :] + diag_part = diag_part * op_diag_part + diag_part = array_ops.reshape( + diag_part, + shape=array_ops.concat( + [array_ops.shape(diag_part)[:-2], [-1]], axis=0)) + if self.range_dimension > self.domain_dimension: + diag_dimension = self.domain_dimension + else: + diag_dimension = self.range_dimension + diag_part.set_shape( + self.batch_shape.concatenate(diag_dimension)) + return diag_part + + def _to_dense(self): + product = self.operators[0].to_dense() + for operator in self.operators[1:]: + # Product has shape [B, R1, 1, C1, 1]. + product = product[ + ..., :, array_ops.newaxis, :, array_ops.newaxis] + # Operator has shape [B, 1, R2, 1, C2]. + op_to_mul = operator.to_dense()[ + ..., array_ops.newaxis, :, array_ops.newaxis, :] + # This is now [B, R1, R2, C1, C2]. + product = product * op_to_mul + # Now merge together dimensions to get [B, R1 * R2, C1 * C2]. + product_shape = _prefer_static_shape(product) + shape = _prefer_static_concat_shape( + product_shape[:-4], + [product_shape[-4] * product_shape[-3], + product_shape[-2] * product_shape[-1]]) + + product = array_ops.reshape(product, shape=shape) + product.set_shape(self.shape) + return product + + def _eigvals(self): + # This will be the kronecker product of all the eigenvalues. + # Note: It doesn't matter which kronecker product it is, since every + # kronecker product of the same matrices are similar. + eigvals = [operator.eigvals() for operator in self.operators] + # Now compute the kronecker product + product = eigvals[0] + for eigval in eigvals[1:]: + # Product has shape [B, R1, 1]. + product = product[..., array_ops.newaxis] + # Eigval has shape [B, 1, R2]. Produces shape [B, R1, R2]. + product = product * eigval[..., array_ops.newaxis, :] + # Reshape to [B, R1 * R2] + product = array_ops.reshape( + product, + shape=array_ops.concat([array_ops.shape(product)[:-2], [-1]], axis=0)) + product.set_shape(self.shape[:-1]) + return product + + def _assert_non_singular(self): + if all(operator.is_square for operator in self.operators): + asserts = [operator.assert_non_singular() for operator in self.operators] + return control_flow_ops.group(asserts) + else: + raise errors.InvalidArgumentError( + node_def=None, + op=None, + message="All Kronecker factors must be square for the product to be " + "invertible. Expected hint `is_square` to be True for every operator " + "in argument `operators`.") + + def _assert_self_adjoint(self): + if all(operator.is_square for operator in self.operators): + asserts = [operator.assert_self_adjoint() for operator in self.operators] + return control_flow_ops.group(asserts) + else: + raise errors.InvalidArgumentError( + node_def=None, + op=None, + message="All Kronecker factors must be square for the product to be " + "invertible. Expected hint `is_square` to be True for every operator " + "in argument `operators`.") + + @property + def _composite_tensor_fields(self): + return ("operators",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"operators": [0] * len(self.operators)} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_low_rank_update.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_low_rank_update.py new file mode 100644 index 0000000000000000000000000000000000000000..a326b9f99a62fd68e2dae34058f001875426ad0f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_low_rank_update.py @@ -0,0 +1,511 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Perturb a `LinearOperator` with a rank `K` update.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_diag +from tensorflow.python.ops.linalg import linear_operator_identity +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "LinearOperatorLowRankUpdate", +] + + +@tf_export("linalg.LinearOperatorLowRankUpdate") +@linear_operator.make_composite_tensor +class LinearOperatorLowRankUpdate(linear_operator.LinearOperator): + """Perturb a `LinearOperator` with a rank `K` update. + + This operator acts like a [batch] matrix `A` with shape + `[B1,...,Bb, M, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `M x N` matrix. + + `LinearOperatorLowRankUpdate` represents `A = L + U D V^H`, where + + ``` + L, is a LinearOperator representing [batch] M x N matrices + U, is a [batch] M x K matrix. Typically K << M. + D, is a [batch] K x K matrix. + V, is a [batch] N x K matrix. Typically K << N. + V^H is the Hermitian transpose (adjoint) of V. + ``` + + If `M = N`, determinants and solves are done using the matrix determinant + lemma and Woodbury identities, and thus require L and D to be non-singular. + + Solves and determinants will be attempted unless the "is_non_singular" + property of L and D is False. + + In the event that L and D are positive-definite, and U = V, solves and + determinants can be done using a Cholesky factorization. + + ```python + # Create a 3 x 3 diagonal linear operator. + diag_operator = LinearOperatorDiag( + diag_update=[1., 2., 3.], is_non_singular=True, is_self_adjoint=True, + is_positive_definite=True) + + # Perturb with a rank 2 perturbation + operator = LinearOperatorLowRankUpdate( + operator=diag_operator, + u=[[1., 2.], [-1., 3.], [0., 0.]], + diag_update=[11., 12.], + v=[[1., 2.], [-1., 3.], [10., 10.]]) + + operator.shape + ==> [3, 3] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [3, 4] Tensor + operator.matmul(x) + ==> Shape [3, 4] Tensor + ``` + + ### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [M, N], with b >= 0 + x.shape = [B1,...,Bb] + [N, R], with R >= 0. + ``` + + ### Performance + + Suppose `operator` is a `LinearOperatorLowRankUpdate` of shape `[M, N]`, + made from a rank `K` update of `base_operator` which performs `.matmul(x)` on + `x` having `x.shape = [N, R]` with `O(L_matmul*N*R)` complexity (and similarly + for `solve`, `determinant`. Then, if `x.shape = [N, R]`, + + * `operator.matmul(x)` is `O(L_matmul*N*R + K*N*R)` + + and if `M = N`, + + * `operator.solve(x)` is `O(L_matmul*N*R + N*K*R + K^2*R + K^3)` + * `operator.determinant()` is `O(L_determinant + L_solve*N*K + K^2*N + K^3)` + + If instead `operator` and `x` have shape `[B1,...,Bb, M, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular`, `self_adjoint`, `positive_definite`, + `diag_update_positive` and `square`. These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + base_operator, + u, + diag_update=None, + v=None, + is_diag_update_positive=None, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorLowRankUpdate"): + """Initialize a `LinearOperatorLowRankUpdate`. + + This creates a `LinearOperator` of the form `A = L + U D V^H`, with + `L` a `LinearOperator`, `U, V` both [batch] matrices, and `D` a [batch] + diagonal matrix. + + If `L` is non-singular, solves and determinants are available. + Solves/determinants both involve a solve/determinant of a `K x K` system. + In the event that L and D are self-adjoint positive-definite, and U = V, + this can be done using a Cholesky factorization. The user should set the + `is_X` matrix property hints, which will trigger the appropriate code path. + + Args: + base_operator: Shape `[B1,...,Bb, M, N]`. + u: Shape `[B1,...,Bb, M, K]` `Tensor` of same `dtype` as `base_operator`. + This is `U` above. + diag_update: Optional shape `[B1,...,Bb, K]` `Tensor` with same `dtype` + as `base_operator`. This is the diagonal of `D` above. + Defaults to `D` being the identity operator. + v: Optional `Tensor` of same `dtype` as `u` and shape `[B1,...,Bb, N, K]` + Defaults to `v = u`, in which case the perturbation is symmetric. + If `M != N`, then `v` must be set since the perturbation is not square. + is_diag_update_positive: Python `bool`. + If `True`, expect `diag_update > 0`. + is_non_singular: Expect that this operator is non-singular. + Default is `None`, unless `is_positive_definite` is auto-set to be + `True` (see below). + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. Default is `None`, unless `base_operator` is self-adjoint + and `v = None` (meaning `u=v`), in which case this defaults to `True`. + is_positive_definite: Expect that this operator is positive definite. + Default is `None`, unless `base_operator` is positive-definite + `v = None` (meaning `u=v`), and `is_diag_update_positive`, in which case + this defaults to `True`. + Note that we say an operator is positive definite when the quadratic + form `x^H A x` has positive real part for all nonzero `x`. + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + + Raises: + ValueError: If `is_X` flags are set in an inconsistent way. + """ + parameters = dict( + base_operator=base_operator, + u=u, + diag_update=diag_update, + v=v, + is_diag_update_positive=is_diag_update_positive, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + dtype = base_operator.dtype + + if diag_update is not None: + if is_diag_update_positive and dtype.is_complex: + logging.warn("Note: setting is_diag_update_positive with a complex " + "dtype means that diagonal is real and positive.") + + if diag_update is None: + if is_diag_update_positive is False: + raise ValueError( + "Default diagonal is the identity, which is positive. However, " + "user set 'is_diag_update_positive' to False.") + is_diag_update_positive = True + + # In this case, we can use a Cholesky decomposition to help us solve/det. + self._use_cholesky = ( + base_operator.is_positive_definite and base_operator.is_self_adjoint + and is_diag_update_positive + and v is None) + + # Possibly auto-set some characteristic flags from None to True. + # If the Flags were set (by the user) incorrectly to False, then raise. + if base_operator.is_self_adjoint and v is None and not dtype.is_complex: + if is_self_adjoint is False: + raise ValueError( + "A = L + UDU^H, with L self-adjoint and D real diagonal. Since" + " UDU^H is self-adjoint, this must be a self-adjoint operator.") + is_self_adjoint = True + + # The condition for using a cholesky is sufficient for SPD, and + # we no weaker choice of these hints leads to SPD. Therefore, + # the following line reads "if hints indicate SPD..." + if self._use_cholesky: + if ( + is_positive_definite is False + or is_self_adjoint is False + or is_non_singular is False): + raise ValueError( + "Arguments imply this is self-adjoint positive-definite operator.") + is_positive_definite = True + is_self_adjoint = True + + with ops.name_scope(name): + + # Create U and V. + self._u = linear_operator_util.convert_nonref_to_tensor(u, name="u") + if v is None: + self._v = self._u + else: + self._v = linear_operator_util.convert_nonref_to_tensor(v, name="v") + + if diag_update is None: + self._diag_update = None + else: + self._diag_update = linear_operator_util.convert_nonref_to_tensor( + diag_update, name="diag_update") + + # Create base_operator L. + self._base_operator = base_operator + + super(LinearOperatorLowRankUpdate, self).__init__( + dtype=self._base_operator.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + # Create the diagonal operator D. + self._set_diag_operators(diag_update, is_diag_update_positive) + self._is_diag_update_positive = is_diag_update_positive + + self._check_shapes() + + def _check_shapes(self): + """Static check that shapes are compatible.""" + # Broadcast shape also checks that u and v are compatible. + uv_shape = array_ops.broadcast_static_shape( + self.u.shape, self.v.shape) + + batch_shape = array_ops.broadcast_static_shape( + self.base_operator.batch_shape, uv_shape[:-2]) + + tensor_shape.Dimension( + self.base_operator.domain_dimension).assert_is_compatible_with( + uv_shape[-2]) + + if self._diag_update is not None: + tensor_shape.dimension_at_index(uv_shape, -1).assert_is_compatible_with( + self._diag_update.shape[-1]) + array_ops.broadcast_static_shape( + batch_shape, self._diag_update.shape[:-1]) + + def _set_diag_operators(self, diag_update, is_diag_update_positive): + """Set attributes self._diag_update and self._diag_operator.""" + if diag_update is not None: + self._diag_operator = linear_operator_diag.LinearOperatorDiag( + self._diag_update, is_positive_definite=is_diag_update_positive) + else: + if tensor_shape.dimension_value(self.u.shape[-1]) is not None: + r = tensor_shape.dimension_value(self.u.shape[-1]) + else: + r = array_ops.shape(self.u)[-1] + self._diag_operator = linear_operator_identity.LinearOperatorIdentity( + num_rows=r, dtype=self.dtype) + + @property + def u(self): + """If this operator is `A = L + U D V^H`, this is the `U`.""" + return self._u + + @property + def v(self): + """If this operator is `A = L + U D V^H`, this is the `V`.""" + return self._v + + @property + def is_diag_update_positive(self): + """If this operator is `A = L + U D V^H`, this hints `D > 0` elementwise.""" + return self._is_diag_update_positive + + @property + def diag_update(self): + """If this operator is `A = L + U D V^H`, this is the diagonal of `D`.""" + return self._diag_update + + @property + def diag_operator(self): + """If this operator is `A = L + U D V^H`, this is `D`.""" + return self._diag_operator + + @property + def base_operator(self): + """If this operator is `A = L + U D V^H`, this is the `L`.""" + return self._base_operator + + def _assert_self_adjoint(self): + # Recall this operator is: + # A = L + UDV^H. + # So in one case self-adjoint depends only on L + if self.u is self.v and self.diag_update is None: + return self.base_operator.assert_self_adjoint() + # In all other cases, sufficient conditions for self-adjoint can be found + # efficiently. However, those conditions are not necessary conditions. + return super(LinearOperatorLowRankUpdate, self).assert_self_adjoint() + + def _shape(self): + batch_shape = array_ops.broadcast_static_shape( + self.base_operator.batch_shape, + self.diag_operator.batch_shape) + batch_shape = array_ops.broadcast_static_shape( + batch_shape, + self.u.shape[:-2]) + batch_shape = array_ops.broadcast_static_shape( + batch_shape, + self.v.shape[:-2]) + return batch_shape.concatenate(self.base_operator.shape[-2:]) + + def _shape_tensor(self): + batch_shape = array_ops.broadcast_dynamic_shape( + self.base_operator.batch_shape_tensor(), + self.diag_operator.batch_shape_tensor()) + batch_shape = array_ops.broadcast_dynamic_shape( + batch_shape, + array_ops.shape(self.u)[:-2]) + batch_shape = array_ops.broadcast_dynamic_shape( + batch_shape, + array_ops.shape(self.v)[:-2]) + return array_ops.concat( + [batch_shape, self.base_operator.shape_tensor()[-2:]], axis=0) + + def _get_uv_as_tensors(self): + """Get (self.u, self.v) as tensors (in case they were refs).""" + u = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.u) + if self.v is self.u: + v = u + else: + v = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.v) + return u, v + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + u, v = self._get_uv_as_tensors() + l = self.base_operator + d = self.diag_operator + + leading_term = l.matmul(x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + if adjoint: + uh_x = math_ops.matmul(u, x, adjoint_a=True, adjoint_b=adjoint_arg) + d_uh_x = d.matmul(uh_x, adjoint=adjoint) + v_d_uh_x = math_ops.matmul(v, d_uh_x) + return leading_term + v_d_uh_x + else: + vh_x = math_ops.matmul(v, x, adjoint_a=True, adjoint_b=adjoint_arg) + d_vh_x = d.matmul(vh_x, adjoint=adjoint) + u_d_vh_x = math_ops.matmul(u, d_vh_x) + return leading_term + u_d_vh_x + + def _determinant(self): + if self.is_positive_definite: + return math_ops.exp(self.log_abs_determinant()) + # The matrix determinant lemma gives + # https://en.wikipedia.org/wiki/Matrix_determinant_lemma + # det(L + UDV^H) = det(D^{-1} + V^H L^{-1} U) det(D) det(L) + # = det(C) det(D) det(L) + # where C is sometimes known as the capacitance matrix, + # C := D^{-1} + V^H L^{-1} U + u, v = self._get_uv_as_tensors() + det_c = linalg_ops.matrix_determinant(self._make_capacitance(u=u, v=v)) + det_d = self.diag_operator.determinant() + det_l = self.base_operator.determinant() + return det_c * det_d * det_l + + def _diag_part(self): + # [U D V^T]_{ii} = sum_{jk} U_{ij} D_{jk} V_{ik} + # = sum_{j} U_{ij} D_{jj} V_{ij} + u, v = self._get_uv_as_tensors() + product = u * math_ops.conj(v) + if self.diag_update is not None: + product *= array_ops.expand_dims(self.diag_update, axis=-2) + return ( + math_ops.reduce_sum(product, axis=-1) + self.base_operator.diag_part()) + + def _log_abs_determinant(self): + u, v = self._get_uv_as_tensors() + # Recall + # det(L + UDV^H) = det(D^{-1} + V^H L^{-1} U) det(D) det(L) + # = det(C) det(D) det(L) + log_abs_det_d = self.diag_operator.log_abs_determinant() + log_abs_det_l = self.base_operator.log_abs_determinant() + + if self._use_cholesky: + chol_cap_diag = array_ops.matrix_diag_part( + linalg_ops.cholesky(self._make_capacitance(u=u, v=v))) + log_abs_det_c = 2 * math_ops.reduce_sum( + math_ops.log(chol_cap_diag), axis=[-1]) + else: + det_c = linalg_ops.matrix_determinant(self._make_capacitance(u=u, v=v)) + log_abs_det_c = math_ops.log(math_ops.abs(det_c)) + if self.dtype.is_complex: + log_abs_det_c = math_ops.cast(log_abs_det_c, dtype=self.dtype) + + return log_abs_det_c + log_abs_det_d + log_abs_det_l + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + if self.base_operator.is_non_singular is False: + raise ValueError( + "Solve not implemented unless this is a perturbation of a " + "non-singular LinearOperator.") + # The Woodbury formula gives: + # https://en.wikipedia.org/wiki/Woodbury_matrix_identity + # (L + UDV^H)^{-1} + # = L^{-1} - L^{-1} U (D^{-1} + V^H L^{-1} U)^{-1} V^H L^{-1} + # = L^{-1} - L^{-1} U C^{-1} V^H L^{-1} + # where C is the capacitance matrix, C := D^{-1} + V^H L^{-1} U + # Note also that, with ^{-H} being the inverse of the adjoint, + # (L + UDV^H)^{-H} + # = L^{-H} - L^{-H} V C^{-H} U^H L^{-H} + l = self.base_operator + if adjoint: + # If adjoint, U and V have flipped roles in the operator. + v, u = self._get_uv_as_tensors() + # Capacitance should still be computed with u=self.u and v=self.v, which + # after the "flip" on the line above means u=v, v=u. I.e. no need to + # "flip" in the capacitance call, since the call to + # matrix_solve_with_broadcast below is done with the `adjoint` argument, + # and this takes care of things. + capacitance = self._make_capacitance(u=v, v=u) + else: + u, v = self._get_uv_as_tensors() + capacitance = self._make_capacitance(u=u, v=v) + + # L^{-1} rhs + linv_rhs = l.solve(rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + # V^H L^{-1} rhs + vh_linv_rhs = math_ops.matmul(v, linv_rhs, adjoint_a=True) + # C^{-1} V^H L^{-1} rhs + if self._use_cholesky: + capinv_vh_linv_rhs = linalg_ops.cholesky_solve( + linalg_ops.cholesky(capacitance), vh_linv_rhs) + else: + capinv_vh_linv_rhs = linear_operator_util.matrix_solve_with_broadcast( + capacitance, vh_linv_rhs, adjoint=adjoint) + # U C^{-1} V^H M^{-1} rhs + u_capinv_vh_linv_rhs = math_ops.matmul(u, capinv_vh_linv_rhs) + # L^{-1} U C^{-1} V^H L^{-1} rhs + linv_u_capinv_vh_linv_rhs = l.solve(u_capinv_vh_linv_rhs, adjoint=adjoint) + + # L^{-1} - L^{-1} U C^{-1} V^H L^{-1} + return linv_rhs - linv_u_capinv_vh_linv_rhs + + def _make_capacitance(self, u, v): + # C := D^{-1} + V^H L^{-1} U + # which is sometimes known as the "capacitance" matrix. + + # L^{-1} U + linv_u = self.base_operator.solve(u) + # V^H L^{-1} U + vh_linv_u = math_ops.matmul(v, linv_u, adjoint_a=True) + + # D^{-1} + V^H L^{-1} V + capacitance = self._diag_operator.inverse().add_to_tensor(vh_linv_u) + return capacitance + + @property + def _composite_tensor_fields(self): + return ("base_operator", "u", "diag_update", "v", "is_diag_update_positive") + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return { + "base_operator": 0, + "u": 2, + "diag_update": 1, + "v": 2 + } diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_lower_triangular.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_lower_triangular.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f54a622240f61656044927df5f434a120ce755 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_lower_triangular.py @@ -0,0 +1,245 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a lower triangular matrix.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.linalg import property_hint_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "LinearOperatorLowerTriangular", +] + + +@tf_export("linalg.LinearOperatorLowerTriangular") +@linear_operator.make_composite_tensor +class LinearOperatorLowerTriangular(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] square lower triangular matrix. + + This operator acts like a [batch] lower triangular matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. + + `LinearOperatorLowerTriangular` is initialized with a `Tensor` having + dimensions `[B1,...,Bb, N, N]`. The upper triangle of the last two + dimensions is ignored. + + ```python + # Create a 2 x 2 lower-triangular linear operator. + tril = [[1., 2.], [3., 4.]] + operator = LinearOperatorLowerTriangular(tril) + + # The upper triangle is ignored. + operator.to_dense() + ==> [[1., 0.] + [3., 4.]] + + operator.shape + ==> [2, 2] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor + + # Create a [2, 3] batch of 4 x 4 linear operators. + tril = tf.random.normal(shape=[2, 3, 4, 4]) + operator = LinearOperatorLowerTriangular(tril) + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [B1,...,Bb] + [N, R], with R >= 0. + ``` + + #### Performance + + Suppose `operator` is a `LinearOperatorLowerTriangular` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` involves `N^2 * R` multiplications. + * `operator.solve(x)` involves `N * R` size `N` back-substitutions. + * `operator.determinant()` involves a size `N` `reduce_prod`. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + tril, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorLowerTriangular"): + r"""Initialize a `LinearOperatorLowerTriangular`. + + Args: + tril: Shape `[B1,...,Bb, N, N]` with `b >= 0`, `N >= 0`. + The lower triangular part of `tril` defines this operator. The strictly + upper triangle is ignored. + is_non_singular: Expect that this operator is non-singular. + This operator is non-singular if and only if its diagonal elements are + all non-zero. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. This operator is self-adjoint only if it is diagonal with + real-valued diagonal entries. In this case it is advised to use + `LinearOperatorDiag`. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + + Raises: + ValueError: If `is_square` is `False`. + """ + parameters = dict( + tril=tril, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + if is_square is False: + raise ValueError( + "Only square lower triangular operators supported at this time.") + is_square = True + + with ops.name_scope(name, values=[tril]): + self._tril = linear_operator_util.convert_nonref_to_tensor(tril, + name="tril") + self._check_tril(self._tril) + + super(LinearOperatorLowerTriangular, self).__init__( + dtype=self._tril.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + @property + def tril(self): + """The lower triangular matrix defining this operator.""" + return self._tril + + def _check_tril(self, tril): + """Static check of the `tril` argument.""" + + if tril.shape.ndims is not None and tril.shape.ndims < 2: + raise ValueError( + "Argument tril must have at least 2 dimensions. Found: %s" + % tril) + + def _get_tril(self): + """Gets the `tril` kwarg, with upper part zero-d out.""" + return array_ops.matrix_band_part(self._tril, -1, 0) + + def _get_diag(self): + """Gets the diagonal part of `tril` kwarg.""" + return array_ops.matrix_diag_part(self._tril) + + def _shape(self): + return self._tril.shape + + def _shape_tensor(self): + return array_ops.shape(self._tril) + + def _assert_non_singular(self): + return linear_operator_util.assert_no_entries_with_modulus_zero( + self._get_diag(), + message="Singular operator: Diagonal contained zero values.") + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + return math_ops.matmul( + self._get_tril(), x, adjoint_a=adjoint, adjoint_b=adjoint_arg) + + def _linop_matmul( + self, + left_operator: "LinearOperatorLowerTriangular", + right_operator: linear_operator.LinearOperator, + ) -> linear_operator.LinearOperator: + # instance check of linear_operator_diag.LinearOperatorDiag + if hasattr(right_operator, "_check_diag"): + return LinearOperatorLowerTriangular( + tril=left_operator.to_dense() * right_operator.diag, + is_non_singular=property_hint_util.combined_non_singular_hint( + right_operator, left_operator), + # This is safe to do since the Triangular matrix is only self-adjoint + # when it is a diagonal matrix, and hence commutes. + is_self_adjoint=property_hint_util.combined_commuting_self_adjoint_hint( + right_operator, left_operator), + is_positive_definite=None, + is_square=True) + return super()._linop_matmul(left_operator, right_operator) + + def _determinant(self): + return math_ops.reduce_prod(self._get_diag(), axis=[-1]) + + def _log_abs_determinant(self): + return math_ops.reduce_sum( + math_ops.log(math_ops.abs(self._get_diag())), axis=[-1]) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + rhs = linalg.adjoint(rhs) if adjoint_arg else rhs + return linalg.triangular_solve( + self._get_tril(), rhs, lower=True, adjoint=adjoint) + + def _to_dense(self): + return self._get_tril() + + def _eigvals(self): + return self._get_diag() + + @property + def _composite_tensor_fields(self): + return ("tril",) + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"tril": 2} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_permutation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_permutation.py new file mode 100644 index 0000000000000000000000000000000000000000..31f07732ef151ada0d5f1bbd31d30c424fef5135 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_permutation.py @@ -0,0 +1,271 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a permutation matrix.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorPermutation",] + + +@tf_export("linalg.LinearOperatorPermutation") +@linear_operator.make_composite_tensor +class LinearOperatorPermutation(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] of permutation matrices. + + This operator acts like a [batch] of permutations with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + `LinearOperatorPermutation` is initialized with a (batch) vector. + + A permutation, is defined by an integer vector `v` whose values are unique + and are in the range `[0, ... n]`. Applying the permutation on an input + matrix has the folllowing meaning: the value of `v` at index `i` + says to move the `v[i]`-th row of the input matrix to the `i`-th row. + Because all values are unique, this will result in a permutation of the + rows the input matrix. Note, that the permutation vector `v` has the same + semantics as `tf.transpose`. + + ```python + # Create a 3 x 3 permutation matrix that swaps the last two columns. + vec = [0, 2, 1] + operator = LinearOperatorPermutation(vec) + + operator.to_dense() + ==> [[1., 0., 0.] + [0., 0., 1.] + [0., 1., 0.]] + + operator.shape + ==> [3, 3] + + # This will be zero. + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [3, 4] Tensor + operator.matmul(x) + ==> Shape [3, 4] Tensor + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + perm, + dtype=dtypes.float32, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorPermutation"): + r"""Initialize a `LinearOperatorPermutation`. + + Args: + perm: Shape `[B1,...,Bb, N]` Integer `Tensor` with `b >= 0` + `N >= 0`. An integer vector that represents the permutation to apply. + Note that this argument is same as `tf.transpose`. However, this + permutation is applied on the rows, while the permutation in + `tf.transpose` is applied on the dimensions of the `Tensor`. `perm` + is required to have unique entries from `{0, 1, ... N-1}`. + dtype: The `dtype` of arguments to this operator. Default: `float32`. + Allowed dtypes: `float16`, `float32`, `float64`, `complex64`, + `complex128`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. This is autoset to true + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + This is autoset to false. + is_square: Expect that this operator acts like square [batch] matrices. + This is autoset to true. + name: A name for this `LinearOperator`. + + Raises: + ValueError: `is_self_adjoint` is not `True`, `is_positive_definite` is + not `False` or `is_square` is not `True`. + """ + parameters = dict( + perm=perm, + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[perm]): + self._perm = linear_operator_util.convert_nonref_to_tensor( + perm, name="perm") + self._check_perm(self._perm) + + # Check and auto-set hints. + if is_non_singular is False: # pylint:disable=g-bool-id-comparison + raise ValueError(f"A Permutation operator is always non-singular. " + f"Expected argument `is_non_singular` to be True. " + f"Received: {is_non_singular}.") + + if is_square is False: # pylint:disable=g-bool-id-comparison + raise ValueError(f"A Permutation operator is always square. " + f"Expected argument `is_square` to be True. " + f"Received: {is_square}.") + is_square = True + + super(LinearOperatorPermutation, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_perm(self, perm): + """Static check of perm.""" + if (perm.shape.ndims is not None and perm.shape.ndims < 1): + raise ValueError(f"Argument `perm` must have at least 1 dimension. " + f"Received: {perm}.") + if not perm.dtype.is_integer: + raise TypeError(f"Argument `perm` must be integer dtype. " + f"Received: {perm}.") + # Check that the permutation satisfies the uniqueness constraint. + static_perm = tensor_util.constant_value(perm) + if static_perm is not None: + sorted_perm = np.sort(static_perm, axis=-1) + if np.any(sorted_perm != np.arange(0, static_perm.shape[-1])): + raise ValueError( + f"Argument `perm` must be a vector of unique integers from " + f"0 to {static_perm.shape[-1] - 1}.") + + def _shape(self): + perm_shape = self._perm.shape + return perm_shape.concatenate(perm_shape[-1:]) + + def _shape_tensor(self): + perm_shape = array_ops.shape(self._perm) + k = perm_shape[-1] + return array_ops.concat((perm_shape, [k]), 0) + + def _assert_non_singular(self): + return control_flow_ops.no_op("assert_non_singular") + + def _domain_dimension_tensor(self, perm=None): + perm = perm if perm is not None else self.perm + return array_ops.shape(perm)[-1] + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + perm = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.perm) + if adjoint and not self.is_self_adjoint: + # TODO(srvasude): invert_permutation doesn't work on batches so we use + # argsort. + perm = sort_ops.argsort(perm, axis=-1) + x = linalg.adjoint(x) if adjoint_arg else x + + # We need to broadcast x and the permutation since tf.gather doesn't + # broadcast. + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(x)[:-1], array_ops.shape(perm)) + k = array_ops.shape(x)[-1] + broadcast_x_shape = array_ops.concat([broadcast_shape, [k]], axis=-1) + x = array_ops.broadcast_to(x, broadcast_x_shape) + perm = array_ops.broadcast_to(perm, broadcast_shape) + + m = array_ops.shape(x)[-2] + x = array_ops.reshape(x, [-1, m, k]) + perm = array_ops.reshape(perm, [-1, m]) + + y = array_ops.gather(x, perm, axis=-2, batch_dims=1) + return array_ops.reshape(y, broadcast_x_shape) + + # TODO(srvasude): Permutation parity is equivalent to the determinant. + + def _log_abs_determinant(self): + # Permutation matrices have determinant +/- 1. + return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + # The inverse of a permutation matrix is the transpose matrix. + # Apply a matmul and flip the adjoint bit. + return self._matmul(rhs, adjoint=(not adjoint), adjoint_arg=adjoint_arg) + + def _to_dense(self): + perm = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.perm) + return math_ops.cast(math_ops.equal( + math_ops.range(0, self._domain_dimension_tensor(perm)), + perm[..., array_ops.newaxis]), self.dtype) + + def _diag_part(self): + perm = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.perm) + return math_ops.cast(math_ops.equal( + math_ops.range(0, self._domain_dimension_tensor(perm)), + perm), self.dtype) + + def _cond(self): + # Permutation matrices are rotations which have condition number 1. + return array_ops.ones(self.batch_shape_tensor(), dtype=self.dtype) + + @property + def perm(self): + return self._perm + + @property + def _composite_tensor_fields(self): + return ("perm", "dtype") + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"perm": 1} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdbe9ddba43aac788218567e6554dcfa4ee42c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_test_util.py @@ -0,0 +1,1432 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for testing `LinearOperator` and sub-classes.""" + +import abc +import itertools + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import test_util +from tensorflow.python.module import module +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops import while_v2 +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.platform import test +from tensorflow.python.saved_model import load as load_model +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.saved_model import save as save_model +from tensorflow.python.util import nest + + +class OperatorShapesInfo: + """Object encoding expected shape for a test. + + Encodes the expected shape of a matrix for a test. Also + allows additional metadata for the test harness. + """ + + def __init__(self, shape, **kwargs): + self.shape = shape + self.__dict__.update(kwargs) + + +class CheckTapeSafeSkipOptions: + + # Skip checking this particular method. + DETERMINANT = "determinant" + DIAG_PART = "diag_part" + LOG_ABS_DETERMINANT = "log_abs_determinant" + TRACE = "trace" + + +class LinearOperatorDerivedClassTest(test.TestCase, metaclass=abc.ABCMeta): + """Tests for derived classes. + + Subclasses should implement every abstractmethod, and this will enable all + test methods to work. + """ + + # Absolute/relative tolerance for tests. + _atol = { + dtypes.float16: 1e-3, + dtypes.float32: 1e-6, + dtypes.float64: 1e-12, + dtypes.complex64: 1e-6, + dtypes.complex128: 1e-12 + } + + _rtol = { + dtypes.float16: 1e-3, + dtypes.float32: 1e-6, + dtypes.float64: 1e-12, + dtypes.complex64: 1e-6, + dtypes.complex128: 1e-12 + } + + def assertAC(self, x, y, check_dtype=False): + """Derived classes can set _atol, _rtol to get different tolerance.""" + dtype = dtypes.as_dtype(x.dtype) + atol = self._atol[dtype] + rtol = self._rtol[dtype] + self.assertAllClose(x, y, atol=atol, rtol=rtol) + if check_dtype: + self.assertDTypeEqual(x, y.dtype) + + @staticmethod + def adjoint_options(): + return [False, True] + + @staticmethod + def adjoint_arg_options(): + return [False, True] + + @staticmethod + def dtypes_to_test(): + # TODO(langmore) Test tf.float16 once tf.linalg.solve works in 16bit. + return [dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128] + + @staticmethod + def use_placeholder_options(): + return [False, True] + + @staticmethod + def use_blockwise_arg(): + return False + + @staticmethod + def operator_shapes_infos(): + """Returns list of OperatorShapesInfo, encapsulating the shape to test.""" + raise NotImplementedError("operator_shapes_infos has not been implemented.") + + @abc.abstractmethod + def operator_and_matrix( + self, shapes_info, dtype, use_placeholder, + ensure_self_adjoint_and_pd=False): + """Build a batch matrix and an Operator that should have similar behavior. + + Every operator acts like a (batch) matrix. This method returns both + together, and is used by tests. + + Args: + shapes_info: `OperatorShapesInfo`, encoding shape information about the + operator. + dtype: Numpy dtype. Data type of returned array/operator. + use_placeholder: Python bool. If True, initialize the operator with a + placeholder of undefined shape and correct dtype. + ensure_self_adjoint_and_pd: If `True`, + construct this operator to be Hermitian Positive Definite, as well + as ensuring the hints `is_positive_definite` and `is_self_adjoint` + are set. + This is useful for testing methods such as `cholesky`. + + Returns: + operator: `LinearOperator` subclass instance. + mat: `Tensor` representing operator. + """ + # Create a matrix as a numpy array with desired shape/dtype. + # Create a LinearOperator that should have the same behavior as the matrix. + raise NotImplementedError("Not implemented yet.") + + @abc.abstractmethod + def make_rhs(self, operator, adjoint, with_batch=True): + """Make a rhs appropriate for calling operator.solve(rhs). + + Args: + operator: A `LinearOperator` + adjoint: Python `bool`. If `True`, we are making a 'rhs' value for the + adjoint operator. + with_batch: Python `bool`. If `True`, create `rhs` with the same batch + shape as operator, and otherwise create a matrix without any batch + shape. + + Returns: + A `Tensor` + """ + raise NotImplementedError("make_rhs is not defined.") + + @abc.abstractmethod + def make_x(self, operator, adjoint, with_batch=True): + """Make an 'x' appropriate for calling operator.matmul(x). + + Args: + operator: A `LinearOperator` + adjoint: Python `bool`. If `True`, we are making an 'x' value for the + adjoint operator. + with_batch: Python `bool`. If `True`, create `x` with the same batch shape + as operator, and otherwise create a matrix without any batch shape. + + Returns: + A `Tensor` + """ + raise NotImplementedError("make_x is not defined.") + + @staticmethod + def skip_these_tests(): + """List of test names to skip.""" + # Subclasses should over-ride if they want to skip some tests. + # To skip "test_foo", add "foo" to this list. + return [] + + @staticmethod + def optional_tests(): + """List of optional test names to run.""" + # Subclasses should over-ride if they want to add optional tests. + # To add "test_foo", add "foo" to this list. + return [] + + def assertRaisesError(self, msg): + """assertRaisesRegexp or OpError, depending on context.executing_eagerly.""" + if context.executing_eagerly(): + return self.assertRaisesRegexp(Exception, msg) + return self.assertRaisesOpError(msg) + + def check_convert_variables_to_tensors(self, operator): + """Checks that internal Variables are correctly converted to Tensors.""" + self.assertIsInstance(operator, composite_tensor.CompositeTensor) + tensor_operator = composite_tensor.convert_variables_to_tensors(operator) + self.assertIs(type(operator), type(tensor_operator)) + self.assertEmpty(tensor_operator.variables) + self._check_tensors_equal_variables(operator, tensor_operator) + + def _check_tensors_equal_variables(self, obj, tensor_obj): + """Checks that Variables in `obj` have equivalent Tensors in `tensor_obj.""" + if isinstance(obj, variables.Variable): + self.assertAllClose(ops.convert_to_tensor(obj), + ops.convert_to_tensor(tensor_obj)) + elif isinstance(obj, composite_tensor.CompositeTensor): + params = getattr(obj, "parameters", {}) + tensor_params = getattr(tensor_obj, "parameters", {}) + self.assertAllEqual(params.keys(), tensor_params.keys()) + self._check_tensors_equal_variables(params, tensor_params) + elif nest.is_mapping(obj): + for k, v in obj.items(): + self._check_tensors_equal_variables(v, tensor_obj[k]) + elif nest.is_nested(obj): + for x, y in zip(obj, tensor_obj): + self._check_tensors_equal_variables(x, y) + else: + # We only check Tensor, CompositeTensor, and nested structure parameters. + pass + + def check_tape_safe(self, operator, skip_options=None): + """Check gradients are not None w.r.t. operator.variables. + + Meant to be called from the derived class. + + This ensures grads are not w.r.t every variable in operator.variables. If + more fine-grained testing is needed, a custom test should be written. + + Args: + operator: LinearOperator. Exact checks done will depend on hints. + skip_options: Optional list of CheckTapeSafeSkipOptions. + Makes this test skip particular checks. + """ + skip_options = skip_options or [] + + if not operator.variables: + raise AssertionError("`operator.variables` was empty") + + def _assert_not_none(iterable): + for item in iterable: + self.assertIsNotNone(item) + + # Tape tests that can be run on every operator below. + with backprop.GradientTape() as tape: + grad = tape.gradient(operator.to_dense(), operator.variables) + _assert_not_none(grad) + + with backprop.GradientTape() as tape: + var_grad = tape.gradient(operator, operator.variables) + _assert_not_none(var_grad) + nest.assert_same_structure(var_grad, grad) + + with backprop.GradientTape() as tape: + _assert_not_none( + tape.gradient(operator.adjoint().to_dense(), operator.variables)) + + x = math_ops.cast( + array_ops.ones(shape=operator.H.shape_tensor()[:-1]), operator.dtype) + + with backprop.GradientTape() as tape: + _assert_not_none(tape.gradient(operator.matvec(x), operator.variables)) + + # Tests for square, but possibly non-singular operators below. + if not operator.is_square: + return + + for option in [ + CheckTapeSafeSkipOptions.DETERMINANT, + CheckTapeSafeSkipOptions.LOG_ABS_DETERMINANT, + CheckTapeSafeSkipOptions.DIAG_PART, + CheckTapeSafeSkipOptions.TRACE, + ]: + with backprop.GradientTape() as tape: + if option not in skip_options: + _assert_not_none( + tape.gradient(getattr(operator, option)(), operator.variables)) + + # Tests for non-singular operators below. + if operator.is_non_singular is False: # pylint: disable=g-bool-id-comparison + return + + with backprop.GradientTape() as tape: + _assert_not_none( + tape.gradient(operator.inverse().to_dense(), operator.variables)) + + with backprop.GradientTape() as tape: + _assert_not_none(tape.gradient(operator.solvevec(x), operator.variables)) + + # Tests for SPD operators below. + if not (operator.is_self_adjoint and operator.is_positive_definite): + return + + with backprop.GradientTape() as tape: + _assert_not_none( + tape.gradient(operator.cholesky().to_dense(), operator.variables)) + + +# pylint:disable=missing-docstring + + +def _test_slicing(use_placeholder, shapes_info, dtype): + def test_slicing(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + batch_shape = shapes_info.shape[:-2] + # Don't bother slicing for uninteresting batch shapes. + if not batch_shape or batch_shape[0] <= 1: + return + + slices = [slice(1, -1)] + if len(batch_shape) > 1: + # Slice out the last member. + slices += [..., slice(0, 1)] + sliced_operator = operator[slices] + matrix_slices = slices + [slice(None), slice(None)] + sliced_matrix = mat[matrix_slices] + sliced_op_dense = sliced_operator.to_dense() + op_dense_v, mat_v = sess.run([sliced_op_dense, sliced_matrix]) + self.assertAC(op_dense_v, mat_v) + return test_slicing + + +def _test_to_dense(use_placeholder, shapes_info, dtype): + def test_to_dense(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_dense = operator.to_dense() + if not use_placeholder: + self.assertAllEqual(shapes_info.shape, op_dense.shape) + op_dense_v, mat_v = sess.run([op_dense, mat]) + self.assertAC(op_dense_v, mat_v) + return test_to_dense + + +def _test_det(use_placeholder, shapes_info, dtype): + def test_det(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_det = operator.determinant() + if not use_placeholder: + self.assertAllEqual(shapes_info.shape[:-2], op_det.shape) + op_det_v, mat_det_v = sess.run( + [op_det, linalg_ops.matrix_determinant(mat)]) + self.assertAC(op_det_v, mat_det_v) + return test_det + + +def _test_log_abs_det(use_placeholder, shapes_info, dtype): + def test_log_abs_det(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_log_abs_det = operator.log_abs_determinant() + _, mat_log_abs_det = linalg.slogdet(mat) + if not use_placeholder: + self.assertAllEqual( + shapes_info.shape[:-2], op_log_abs_det.shape) + op_log_abs_det_v, mat_log_abs_det_v = sess.run( + [op_log_abs_det, mat_log_abs_det]) + self.assertAC(op_log_abs_det_v, mat_log_abs_det_v) + return test_log_abs_det + + +@test_util.run_without_tensor_float_32("Use FP32 in matmul") +def _test_operator_matmul_with_same_type(use_placeholder, shapes_info, dtype): + """op_a.matmul(op_b), in the case where the same type is returned.""" + def test_operator_matmul_with_same_type( + self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator_a, mat_a = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + operator_b, mat_b = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + + mat_matmul = math_ops.matmul(mat_a, mat_b) + op_matmul = operator_a.matmul(operator_b) + mat_matmul_v, op_matmul_v = sess.run([mat_matmul, op_matmul.to_dense()]) + + self.assertIsInstance(op_matmul, operator_a.__class__) + self.assertAC(mat_matmul_v, op_matmul_v) + return test_operator_matmul_with_same_type + + +def _test_operator_solve_with_same_type(use_placeholder, shapes_info, dtype): + """op_a.solve(op_b), in the case where the same type is returned.""" + def test_operator_solve_with_same_type( + self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator_a, mat_a = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + operator_b, mat_b = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + + mat_solve = linear_operator_util.matrix_solve_with_broadcast(mat_a, mat_b) + op_solve = operator_a.solve(operator_b) + mat_solve_v, op_solve_v = sess.run([mat_solve, op_solve.to_dense()]) + + self.assertIsInstance(op_solve, operator_a.__class__) + self.assertAC(mat_solve_v, op_solve_v) + return test_operator_solve_with_same_type + + +def _test_matmul_base( + self: "LinearOperatorDerivedClassTest", + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch): + # If batch dimensions are omitted, but there are + # no batch dimensions for the linear operator, then + # skip the test case. This is already checked with + # with_batch=True. + if not with_batch and len(shapes_info.shape) <= 2: + return + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + x = self.make_x( + operator, adjoint=adjoint, with_batch=with_batch) + # If adjoint_arg, compute A X^H^H = A X. + if adjoint_arg: + op_matmul = operator.matmul( + linalg.adjoint(x), + adjoint=adjoint, + adjoint_arg=adjoint_arg) + else: + op_matmul = operator.matmul(x, adjoint=adjoint) + mat_matmul = math_ops.matmul(mat, x, adjoint_a=adjoint) + if not use_placeholder: + self.assertAllEqual(op_matmul.shape, + mat_matmul.shape) + + # If the operator is blockwise, test both blockwise `x` and `Tensor` `x`; + # else test only `Tensor` `x`. In both cases, evaluate all results in a + # single `sess.run` call to avoid re-sampling the random `x` in graph mode. + if blockwise_arg and len(operator.operators) > 1: + # pylint: disable=protected-access + block_dimensions = ( + operator._block_range_dimensions() if adjoint else + operator._block_domain_dimensions()) + block_dimensions_fn = ( + operator._block_range_dimension_tensors if adjoint else + operator._block_domain_dimension_tensors) + # pylint: enable=protected-access + split_x = linear_operator_util.split_arg_into_blocks( + block_dimensions, + block_dimensions_fn, + x, axis=-2) + if adjoint_arg: + split_x = [linalg.adjoint(y) for y in split_x] + split_matmul = operator.matmul( + split_x, adjoint=adjoint, adjoint_arg=adjoint_arg) + + self.assertEqual(len(split_matmul), len(operator.operators)) + split_matmul = linear_operator_util.broadcast_matrix_batch_dims( + split_matmul) + fused_block_matmul = array_ops.concat(split_matmul, axis=-2) + op_matmul_v, mat_matmul_v, fused_block_matmul_v = sess.run([ + op_matmul, mat_matmul, fused_block_matmul]) + + # Check that the operator applied to blockwise input gives the same result + # as matrix multiplication. + self.assertAC(fused_block_matmul_v, mat_matmul_v) + else: + op_matmul_v, mat_matmul_v = sess.run([op_matmul, mat_matmul]) + + # Check that the operator applied to a `Tensor` gives the same result as + # matrix multiplication. + self.assertAC(op_matmul_v, mat_matmul_v) + + +@test_util.run_without_tensor_float_32("Use FP32 in matmul") +def _test_matmul( + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg): + def test_matmul(self: "LinearOperatorDerivedClassTest"): + _test_matmul_base( + self, + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch=True) + return test_matmul + + +@test_util.run_without_tensor_float_32("Use FP32 in matmul") +def _test_matmul_with_broadcast( + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg): + def test_matmul_with_broadcast(self: "LinearOperatorDerivedClassTest"): + _test_matmul_base( + self, + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch=True) + return test_matmul_with_broadcast + + +def _test_adjoint(use_placeholder, shapes_info, dtype): + def test_adjoint(self: "LinearOperatorDerivedClassTest"): + with self.test_session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_adjoint = operator.adjoint().to_dense() + op_adjoint_h = operator.H.to_dense() + mat_adjoint = linalg.adjoint(mat) + op_adjoint_v, op_adjoint_h_v, mat_adjoint_v = sess.run( + [op_adjoint, op_adjoint_h, mat_adjoint]) + self.assertAC(mat_adjoint_v, op_adjoint_v) + self.assertAC(mat_adjoint_v, op_adjoint_h_v) + return test_adjoint + + +def _test_cholesky(use_placeholder, shapes_info, dtype): + def test_cholesky(self: "LinearOperatorDerivedClassTest"): + with self.test_session(graph=ops.Graph()) as sess: + # This test fails to pass for float32 type by a small margin if we use + # random_seed.DEFAULT_GRAPH_SEED. The correct fix would be relaxing the + # test tolerance but the tolerance in this test is configured universally + # depending on its type. So instead of lowering tolerance for all tests + # or special casing this, just use a seed, +2, that makes this test pass. + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + 2 + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder, + ensure_self_adjoint_and_pd=True) + op_chol = operator.cholesky().to_dense() + mat_chol = linalg_ops.cholesky(mat) + op_chol_v, mat_chol_v = sess.run([op_chol, mat_chol]) + self.assertAC(mat_chol_v, op_chol_v) + return test_cholesky + + +def _test_eigvalsh(use_placeholder, shapes_info, dtype): + def test_eigvalsh(self: "LinearOperatorDerivedClassTest"): + with self.test_session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder, + ensure_self_adjoint_and_pd=True) + # Eigenvalues are real, so we'll cast these to float64 and sort + # for comparison. + op_eigvals = sort_ops.sort( + math_ops.cast(operator.eigvals(), dtype=dtypes.float64), axis=-1) + if dtype.is_complex: + mat = math_ops.cast(mat, dtype=dtypes.complex128) + else: + mat = math_ops.cast(mat, dtype=dtypes.float64) + mat_eigvals = sort_ops.sort( + math_ops.cast( + linalg_ops.self_adjoint_eigvals(mat), dtype=dtypes.float64), + axis=-1) + op_eigvals_v, mat_eigvals_v = sess.run([op_eigvals, mat_eigvals]) + + atol = self._atol[dtype] # pylint: disable=protected-access + rtol = self._rtol[dtype] # pylint: disable=protected-access + if dtype == dtypes.float32 or dtype == dtypes.complex64: + atol = 2e-4 + rtol = 2e-4 + self.assertAllClose(op_eigvals_v, mat_eigvals_v, atol=atol, rtol=rtol) + return test_eigvalsh + + +def _test_cond(use_placeholder, shapes_info, dtype): + def test_cond(self: "LinearOperatorDerivedClassTest"): + with self.test_session(graph=ops.Graph()) as sess: + # svd does not work with zero dimensional matrices, so we'll + # skip + if 0 in shapes_info.shape[-2:]: + return + + # ROCm platform does not yet support complex types + if test.is_built_with_rocm() and \ + ((dtype == dtypes.complex64) or (dtype == dtypes.complex128)): + return + + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + # Ensure self-adjoint and PD so we get finite condition numbers. + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder, + ensure_self_adjoint_and_pd=True) + # Eigenvalues are real, so we'll cast these to float64 and sort + # for comparison. + op_cond = operator.cond() + s = math_ops.abs(linalg_ops.svd(mat, compute_uv=False)) + mat_cond = math_ops.reduce_max(s, axis=-1) / math_ops.reduce_min( + s, axis=-1) + op_cond_v, mat_cond_v = sess.run([op_cond, mat_cond]) + + atol_override = { + dtypes.float16: 1e-2, + dtypes.float32: 1e-3, + dtypes.float64: 1e-6, + dtypes.complex64: 1e-3, + dtypes.complex128: 1e-6, + } + rtol_override = { + dtypes.float16: 1e-2, + dtypes.float32: 1e-3, + dtypes.float64: 1e-4, + dtypes.complex64: 1e-3, + dtypes.complex128: 1e-6, + } + atol = atol_override[dtype] + rtol = rtol_override[dtype] + self.assertAllClose(op_cond_v, mat_cond_v, atol=atol, rtol=rtol) + return test_cond + + +def _test_solve_base( + self: "LinearOperatorDerivedClassTest", + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch): + # If batch dimensions are omitted, but there are + # no batch dimensions for the linear operator, then + # skip the test case. This is already checked with + # with_batch=True. + if not with_batch and len(shapes_info.shape) <= 2: + return + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + rhs = self.make_rhs( + operator, adjoint=adjoint, with_batch=with_batch) + # If adjoint_arg, solve A X = (rhs^H)^H = rhs. + if adjoint_arg: + op_solve = operator.solve( + linalg.adjoint(rhs), + adjoint=adjoint, + adjoint_arg=adjoint_arg) + else: + op_solve = operator.solve( + rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + mat_solve = linear_operator_util.matrix_solve_with_broadcast( + mat, rhs, adjoint=adjoint) + if not use_placeholder: + self.assertAllEqual(op_solve.shape, + mat_solve.shape) + + # If the operator is blockwise, test both blockwise rhs and `Tensor` rhs; + # else test only `Tensor` rhs. In both cases, evaluate all results in a + # single `sess.run` call to avoid re-sampling the random rhs in graph mode. + if blockwise_arg and len(operator.operators) > 1: + # pylint: disable=protected-access + block_dimensions = ( + operator._block_range_dimensions() if adjoint else + operator._block_domain_dimensions()) + block_dimensions_fn = ( + operator._block_range_dimension_tensors if adjoint else + operator._block_domain_dimension_tensors) + # pylint: enable=protected-access + split_rhs = linear_operator_util.split_arg_into_blocks( + block_dimensions, + block_dimensions_fn, + rhs, axis=-2) + if adjoint_arg: + split_rhs = [linalg.adjoint(y) for y in split_rhs] + split_solve = operator.solve( + split_rhs, adjoint=adjoint, adjoint_arg=adjoint_arg) + self.assertEqual(len(split_solve), len(operator.operators)) + split_solve = linear_operator_util.broadcast_matrix_batch_dims( + split_solve) + fused_block_solve = array_ops.concat(split_solve, axis=-2) + op_solve_v, mat_solve_v, fused_block_solve_v = sess.run([ + op_solve, mat_solve, fused_block_solve]) + + # Check that the operator and matrix give the same solution when the rhs + # is blockwise. + self.assertAC(mat_solve_v, fused_block_solve_v) + else: + op_solve_v, mat_solve_v = sess.run([op_solve, mat_solve]) + + # Check that the operator and matrix give the same solution when the rhs is + # a `Tensor`. + self.assertAC(op_solve_v, mat_solve_v) + + +def _test_solve( + use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, blockwise_arg): + def test_solve(self: "LinearOperatorDerivedClassTest"): + _test_solve_base( + self, + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch=True) + return test_solve + + +def _test_solve_with_broadcast( + use_placeholder, shapes_info, dtype, adjoint, adjoint_arg, blockwise_arg): + def test_solve_with_broadcast(self: "LinearOperatorDerivedClassTest"): + _test_solve_base( + self, + use_placeholder, + shapes_info, + dtype, + adjoint, + adjoint_arg, + blockwise_arg, + with_batch=False) + return test_solve_with_broadcast + + +def _test_inverse(use_placeholder, shapes_info, dtype): + def test_inverse(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_inverse_v, mat_inverse_v = sess.run([ + operator.inverse().to_dense(), linalg.inv(mat)]) + self.assertAC(op_inverse_v, mat_inverse_v, check_dtype=True) + return test_inverse + + +def _test_trace(use_placeholder, shapes_info, dtype): + def test_trace(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_trace = operator.trace() + mat_trace = math_ops.trace(mat) + if not use_placeholder: + self.assertAllEqual(op_trace.shape, mat_trace.shape) + op_trace_v, mat_trace_v = sess.run([op_trace, mat_trace]) + self.assertAC(op_trace_v, mat_trace_v) + return test_trace + + +def _test_add_to_tensor(use_placeholder, shapes_info, dtype): + def test_add_to_tensor(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_plus_2mat = operator.add_to_tensor(2 * mat) + + if not use_placeholder: + self.assertAllEqual(shapes_info.shape, op_plus_2mat.shape) + + op_plus_2mat_v, mat_v = sess.run([op_plus_2mat, mat]) + + self.assertAC(op_plus_2mat_v, 3 * mat_v) + return test_add_to_tensor + + +def _test_diag_part(use_placeholder, shapes_info, dtype): + def test_diag_part(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + op_diag_part = operator.diag_part() + mat_diag_part = array_ops.matrix_diag_part(mat) + + if not use_placeholder: + self.assertAllEqual(mat_diag_part.shape, + op_diag_part.shape) + + op_diag_part_, mat_diag_part_ = sess.run( + [op_diag_part, mat_diag_part]) + + self.assertAC(op_diag_part_, mat_diag_part_) + return test_diag_part + + +@test_util.run_without_tensor_float_32("Use FP32 in matmul") +def _test_composite_tensor(use_placeholder, shapes_info, dtype): + def test_composite_tensor(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + self.assertIsInstance(operator, composite_tensor.CompositeTensor) + + flat = nest.flatten(operator, expand_composites=True) + unflat = nest.pack_sequence_as(operator, flat, expand_composites=True) + self.assertIsInstance(unflat, type(operator)) + + # Input the operator to a `tf.function`. + x = self.make_x(operator, adjoint=False) + op_y = def_function.function(lambda op: op.matmul(x))(unflat) + mat_y = math_ops.matmul(mat, x) + + if not use_placeholder: + self.assertAllEqual(mat_y.shape, op_y.shape) + + # Test while_loop. + def body(op): + return type(op)(**op.parameters), + op_out, = while_v2.while_loop( + cond=lambda _: True, + body=body, + loop_vars=(operator,), + maximum_iterations=3) + loop_y = op_out.matmul(x) + + op_y_, loop_y_, mat_y_ = sess.run([op_y, loop_y, mat_y]) + self.assertAC(op_y_, mat_y_) + self.assertAC(loop_y_, mat_y_) + + # Ensure that the `TypeSpec` can be encoded. + nested_structure_coder.encode_structure(operator._type_spec) # pylint: disable=protected-access + + return test_composite_tensor + + +@test_util.run_without_tensor_float_32("Use FP32 in matmul") +def _test_saved_model(use_placeholder, shapes_info, dtype): + def test_saved_model(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, mat = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + x = self.make_x(operator, adjoint=False) + + class Model(module.Module): + + def __init__(self, init_x): + self.x = nest.map_structure( + lambda x_: variables.Variable(x_, shape=None), + init_x) + + @def_function.function(input_signature=(operator._type_spec,)) # pylint: disable=protected-access + def do_matmul(self, op): + return op.matmul(self.x) + + saved_model_dir = self.get_temp_dir() + m1 = Model(x) + sess.run([v.initializer for v in m1.variables]) + sess.run(m1.x.assign(m1.x + 1.)) + + save_model.save(m1, saved_model_dir) + m2 = load_model.load(saved_model_dir) + sess.run(m2.x.initializer) + + sess.run(m2.x.assign(m2.x + 1.)) + y_op = m2.do_matmul(operator) + y_mat = math_ops.matmul(mat, m2.x) + + y_op_, y_mat_ = sess.run([y_op, y_mat]) + self.assertAC(y_op_, y_mat_) + + return test_saved_model + + +def _test_composite_tensor_gradient(use_placeholder, shapes_info, dtype): + def test_composite_tensor_gradient(self: "LinearOperatorDerivedClassTest"): + with self.session(graph=ops.Graph()) as sess: + sess.graph.seed = random_seed.DEFAULT_GRAPH_SEED + operator, _ = self.operator_and_matrix( + shapes_info, dtype, use_placeholder=use_placeholder) + x = self.make_x(operator, adjoint=False) + y = operator.matmul(x) + + op_g, = gradients_impl.gradients( + y, + operator, + grad_ys=array_ops.ones_like(y)) # Complex dtypes need grad_ys. + + def _unflatten_and_matmul(components): + unflat_op = nest.pack_sequence_as( + operator, components, expand_composites=True) + return unflat_op.matmul(x) + + flat_op = nest.flatten(operator, expand_composites=True) + y_ = _unflatten_and_matmul(flat_op) + flat_g = gradients_impl.gradients( + y_, + flat_op, + grad_ys=array_ops.ones_like(y_)) + + if all(g is None for g in flat_g): + self.assertIsNone(op_g) + else: + self.assertIsInstance(op_g, operator.__class__) + for g, ug in zip(nest.flatten(op_g, expand_composites=True), + nest.flatten(flat_g, expand_composites=True)): + self.assertAllClose(g, ug) + return test_composite_tensor_gradient + +# pylint:enable=missing-docstring + + +def add_tests(test_cls): + """Add tests for LinearOperator methods.""" + test_name_dict = { + # All test classes should be added here. + "add_to_tensor": _test_add_to_tensor, + "adjoint": _test_adjoint, + "cholesky": _test_cholesky, + "cond": _test_cond, + "composite_tensor": _test_composite_tensor, + "composite_tensor_gradient": _test_composite_tensor_gradient, + "det": _test_det, + "diag_part": _test_diag_part, + "eigvalsh": _test_eigvalsh, + "inverse": _test_inverse, + "log_abs_det": _test_log_abs_det, + "operator_matmul_with_same_type": _test_operator_matmul_with_same_type, + "operator_solve_with_same_type": _test_operator_solve_with_same_type, + "matmul": _test_matmul, + "matmul_with_broadcast": _test_matmul_with_broadcast, + "saved_model": _test_saved_model, + "slicing": _test_slicing, + "solve": _test_solve, + "solve_with_broadcast": _test_solve_with_broadcast, + "to_dense": _test_to_dense, + "trace": _test_trace, + } + optional_tests = [ + # Test classes need to explicitly add these to cls.optional_tests. + "operator_matmul_with_same_type", + "operator_solve_with_same_type", + ] + tests_with_adjoint_args = [ + "matmul", + "matmul_with_broadcast", + "solve", + "solve_with_broadcast", + ] + if set(test_cls.skip_these_tests()).intersection(test_cls.optional_tests()): + raise ValueError( + "Test class {test_cls} had intersecting 'skip_these_tests' " + f"{test_cls.skip_these_tests()} and 'optional_tests' " + f"{test_cls.optional_tests()}.") + + for name, test_template_fn in test_name_dict.items(): + if name in test_cls.skip_these_tests(): + continue + if name in optional_tests and name not in test_cls.optional_tests(): + continue + + for dtype, use_placeholder, shape_info in itertools.product( + test_cls.dtypes_to_test(), + test_cls.use_placeholder_options(), + test_cls.operator_shapes_infos()): + base_test_name = "_".join([ + "test", name, "_shape={},dtype={},use_placeholder={}".format( + shape_info.shape, dtype, use_placeholder)]) + if name in tests_with_adjoint_args: + for adjoint in test_cls.adjoint_options(): + for adjoint_arg in test_cls.adjoint_arg_options(): + test_name = base_test_name + ",adjoint={},adjoint_arg={}".format( + adjoint, adjoint_arg) + if hasattr(test_cls, test_name): + raise RuntimeError("Test %s defined more than once" % test_name) + setattr( + test_cls, + test_name, + test_util.run_deprecated_v1( + test_template_fn( # pylint: disable=too-many-function-args + use_placeholder, shape_info, dtype, adjoint, + adjoint_arg, test_cls.use_blockwise_arg()))) + else: + if hasattr(test_cls, base_test_name): + raise RuntimeError("Test %s defined more than once" % base_test_name) + setattr( + test_cls, + base_test_name, + test_util.run_deprecated_v1(test_template_fn( + use_placeholder, shape_info, dtype))) + + +class SquareLinearOperatorDerivedClassTest( + LinearOperatorDerivedClassTest, metaclass=abc.ABCMeta): + """Base test class appropriate for square operators. + + Sub-classes must still define all abstractmethods from + LinearOperatorDerivedClassTest that are not defined here. + """ + + @staticmethod + def operator_shapes_infos(): + shapes_info = OperatorShapesInfo + # non-batch operators (n, n) and batch operators. + return [ + shapes_info((0, 0)), + shapes_info((1, 1)), + shapes_info((1, 3, 3)), + shapes_info((3, 4, 4)), + shapes_info((2, 1, 4, 4))] + + def make_rhs(self, operator, adjoint, with_batch=True): + # This operator is square, so rhs and x will have same shape. + # adjoint value makes no difference because the operator shape doesn't + # change since it is square, but be pedantic. + return self.make_x(operator, adjoint=not adjoint, with_batch=with_batch) + + def make_x(self, operator, adjoint, with_batch=True): + # Value of adjoint makes no difference because the operator is square. + # Return the number of systems to solve, R, equal to 1 or 2. + r = self._get_num_systems(operator) + # If operator.shape = [B1,...,Bb, N, N] this returns a random matrix of + # shape [B1,...,Bb, N, R], R = 1 or 2. + if operator.shape.is_fully_defined(): + batch_shape = operator.batch_shape.as_list() + n = operator.domain_dimension.value + if with_batch: + x_shape = batch_shape + [n, r] + else: + x_shape = [n, r] + else: + batch_shape = operator.batch_shape_tensor() + n = operator.domain_dimension_tensor() + if with_batch: + x_shape = array_ops.concat((batch_shape, [n, r]), 0) + else: + x_shape = [n, r] + + return random_normal(x_shape, dtype=operator.dtype) + + def _get_num_systems(self, operator): + """Get some number, either 1 or 2, depending on operator.""" + if operator.tensor_rank is None or operator.tensor_rank % 2: + return 1 + else: + return 2 + + +class NonSquareLinearOperatorDerivedClassTest( + LinearOperatorDerivedClassTest, metaclass=abc.ABCMeta): + """Base test class appropriate for generic rectangular operators. + + Square shapes are never tested by this class, so if you want to test your + operator with a square shape, create two test classes, the other subclassing + SquareLinearOperatorFullMatrixTest. + + Sub-classes must still define all abstractmethods from + LinearOperatorDerivedClassTest that are not defined here. + """ + + @staticmethod + def skip_these_tests(): + """List of test names to skip.""" + return [ + "cholesky", + "eigvalsh", + "inverse", + "solve", + "solve_with_broadcast", + "det", + "log_abs_det", + ] + + @staticmethod + def operator_shapes_infos(): + shapes_info = OperatorShapesInfo + # non-batch operators (n, n) and batch operators. + return [ + shapes_info((2, 1)), + shapes_info((1, 2)), + shapes_info((1, 3, 2)), + shapes_info((3, 3, 4)), + shapes_info((2, 1, 2, 4))] + + def make_rhs(self, operator, adjoint, with_batch=True): + # TODO(langmore) Add once we're testing solve_ls. + raise NotImplementedError( + "make_rhs not implemented because we don't test solve") + + def make_x(self, operator, adjoint, with_batch=True): + # Return the number of systems for the argument 'x' for .matmul(x) + r = self._get_num_systems(operator) + # If operator.shape = [B1,...,Bb, M, N] this returns a random matrix of + # shape [B1,...,Bb, N, R], R = 1 or 2. + if operator.shape.is_fully_defined(): + batch_shape = operator.batch_shape.as_list() + if adjoint: + n = operator.range_dimension.value + else: + n = operator.domain_dimension.value + if with_batch: + x_shape = batch_shape + [n, r] + else: + x_shape = [n, r] + else: + batch_shape = operator.batch_shape_tensor() + if adjoint: + n = operator.range_dimension_tensor() + else: + n = operator.domain_dimension_tensor() + if with_batch: + x_shape = array_ops.concat((batch_shape, [n, r]), 0) + else: + x_shape = [n, r] + + return random_normal(x_shape, dtype=operator.dtype) + + def _get_num_systems(self, operator): + """Get some number, either 1 or 2, depending on operator.""" + if operator.tensor_rank is None or operator.tensor_rank % 2: + return 1 + else: + return 2 + + +def random_positive_definite_matrix(shape, + dtype, + oversampling_ratio=4, + force_well_conditioned=False): + """[batch] positive definite Wisart matrix. + + A Wishart(N, S) matrix is the S sample covariance matrix of an N-variate + (standard) Normal random variable. + + Args: + shape: `TensorShape` or Python list. Shape of the returned matrix. + dtype: `TensorFlow` `dtype` or Python dtype. + oversampling_ratio: S / N in the above. If S < N, the matrix will be + singular (unless `force_well_conditioned is True`). + force_well_conditioned: Python bool. If `True`, add `1` to the diagonal + of the Wishart matrix, then divide by 2, ensuring most eigenvalues are + close to 1. + + Returns: + `Tensor` with desired shape and dtype. + """ + dtype = dtypes.as_dtype(dtype) + if not tensor_util.is_tf_type(shape): + shape = tensor_shape.TensorShape(shape) + # Matrix must be square. + shape.dims[-1].assert_is_compatible_with(shape.dims[-2]) + shape = shape.as_list() + n = shape[-2] + s = oversampling_ratio * shape[-1] + wigner_shape = shape[:-2] + [n, s] + + with ops.name_scope("random_positive_definite_matrix"): + wigner = random_normal( + wigner_shape, + dtype=dtype, + stddev=math_ops.cast(1 / np.sqrt(s), dtype.real_dtype)) + wishart = math_ops.matmul(wigner, wigner, adjoint_b=True) + if force_well_conditioned: + wishart += linalg_ops.eye(n, dtype=dtype) + wishart /= math_ops.cast(2, dtype) + return wishart + + +def random_tril_matrix(shape, + dtype, + force_well_conditioned=False, + remove_upper=True): + """[batch] lower triangular matrix. + + Args: + shape: `TensorShape` or Python `list`. Shape of the returned matrix. + dtype: `TensorFlow` `dtype` or Python dtype + force_well_conditioned: Python `bool`. If `True`, returned matrix will have + eigenvalues with modulus in `(1, 2)`. Otherwise, eigenvalues are unit + normal random variables. + remove_upper: Python `bool`. + If `True`, zero out the strictly upper triangle. + If `False`, the lower triangle of returned matrix will have desired + properties, but will not have the strictly upper triangle zero'd out. + + Returns: + `Tensor` with desired shape and dtype. + """ + with ops.name_scope("random_tril_matrix"): + # Totally random matrix. Has no nice properties. + tril = random_normal(shape, dtype=dtype) + if remove_upper: + tril = array_ops.matrix_band_part(tril, -1, 0) + + # Create a diagonal with entries having modulus in [1, 2]. + if force_well_conditioned: + maxval = ops.convert_to_tensor(np.sqrt(2.), dtype=dtype.real_dtype) + diag = random_sign_uniform( + shape[:-1], dtype=dtype, minval=1., maxval=maxval) + tril = array_ops.matrix_set_diag(tril, diag) + + return tril + + +def random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None): + """Tensor with (possibly complex) Gaussian entries. + + Samples are distributed like + + ``` + N(mean, stddev^2), if dtype is real, + X + iY, where X, Y ~ N(mean, stddev^2) if dtype is complex. + ``` + + Args: + shape: `TensorShape` or Python list. Shape of the returned tensor. + mean: `Tensor` giving mean of normal to sample from. + stddev: `Tensor` giving stdev of normal to sample from. + dtype: `TensorFlow` `dtype` or numpy dtype + seed: Python integer seed for the RNG. + + Returns: + `Tensor` with desired shape and dtype. + """ + dtype = dtypes.as_dtype(dtype) + + with ops.name_scope("random_normal"): + samples = random_ops.random_normal( + shape, mean=mean, stddev=stddev, dtype=dtype.real_dtype, seed=seed) + if dtype.is_complex: + if seed is not None: + seed += 1234 + more_samples = random_ops.random_normal( + shape, mean=mean, stddev=stddev, dtype=dtype.real_dtype, seed=seed) + samples = math_ops.complex(samples, more_samples) + return samples + + +def random_uniform(shape, + minval=None, + maxval=None, + dtype=dtypes.float32, + seed=None): + """Tensor with (possibly complex) Uniform entries. + + Samples are distributed like + + ``` + Uniform[minval, maxval], if dtype is real, + X + iY, where X, Y ~ Uniform[minval, maxval], if dtype is complex. + ``` + + Args: + shape: `TensorShape` or Python list. Shape of the returned tensor. + minval: `0-D` `Tensor` giving the minimum values. + maxval: `0-D` `Tensor` giving the maximum values. + dtype: `TensorFlow` `dtype` or Python dtype + seed: Python integer seed for the RNG. + + Returns: + `Tensor` with desired shape and dtype. + """ + dtype = dtypes.as_dtype(dtype) + + with ops.name_scope("random_uniform"): + samples = random_ops.random_uniform( + shape, dtype=dtype.real_dtype, minval=minval, maxval=maxval, seed=seed) + if dtype.is_complex: + if seed is not None: + seed += 12345 + more_samples = random_ops.random_uniform( + shape, + dtype=dtype.real_dtype, + minval=minval, + maxval=maxval, + seed=seed) + samples = math_ops.complex(samples, more_samples) + return samples + + +def random_sign_uniform(shape, + minval=None, + maxval=None, + dtype=dtypes.float32, + seed=None): + """Tensor with (possibly complex) random entries from a "sign Uniform". + + Letting `Z` be a random variable equal to `-1` and `1` with equal probability, + Samples from this `Op` are distributed like + + ``` + Z * X, where X ~ Uniform[minval, maxval], if dtype is real, + Z * (X + iY), where X, Y ~ Uniform[minval, maxval], if dtype is complex. + ``` + + Args: + shape: `TensorShape` or Python list. Shape of the returned tensor. + minval: `0-D` `Tensor` giving the minimum values. + maxval: `0-D` `Tensor` giving the maximum values. + dtype: `TensorFlow` `dtype` or Python dtype + seed: Python integer seed for the RNG. + + Returns: + `Tensor` with desired shape and dtype. + """ + dtype = dtypes.as_dtype(dtype) + + with ops.name_scope("random_sign_uniform"): + unsigned_samples = random_uniform( + shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed) + if seed is not None: + seed += 12 + signs = math_ops.sign( + random_ops.random_uniform(shape, minval=-1., maxval=1., seed=seed)) + return unsigned_samples * math_ops.cast(signs, unsigned_samples.dtype) + + +def random_normal_correlated_columns(shape, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + eps=1e-4, + seed=None): + """Batch matrix with (possibly complex) Gaussian entries and correlated cols. + + Returns random batch matrix `A` with specified element-wise `mean`, `stddev`, + living close to an embedded hyperplane. + + Suppose `shape[-2:] = (M, N)`. + + If `M < N`, `A` is a random `M x N` [batch] matrix with iid Gaussian entries. + + If `M >= N`, then the columns of `A` will be made almost dependent as follows: + + ``` + L = random normal N x N-1 matrix, mean = 0, stddev = 1 / sqrt(N - 1) + B = random normal M x N-1 matrix, mean = 0, stddev = stddev. + + G = (L B^H)^H, a random normal M x N matrix, living on N-1 dim hyperplane + E = a random normal M x N matrix, mean = 0, stddev = eps + mu = a constant M x N matrix, equal to the argument "mean" + + A = G + E + mu + ``` + + Args: + shape: Python list of integers. + Shape of the returned tensor. Must be at least length two. + mean: `Tensor` giving mean of normal to sample from. + stddev: `Tensor` giving stdev of normal to sample from. + dtype: `TensorFlow` `dtype` or numpy dtype + eps: Distance each column is perturbed from the low-dimensional subspace. + seed: Python integer seed for the RNG. + + Returns: + `Tensor` with desired shape and dtype. + + Raises: + ValueError: If `shape` is not at least length 2. + """ + dtype = dtypes.as_dtype(dtype) + + if len(shape) < 2: + raise ValueError( + "Argument shape must be at least length 2. Found: %s" % shape) + + # Shape is the final shape, e.g. [..., M, N] + shape = list(shape) + batch_shape = shape[:-2] + m, n = shape[-2:] + + # If there is only one column, "they" are by definition correlated. + if n < 2 or n < m: + return random_normal( + shape, mean=mean, stddev=stddev, dtype=dtype, seed=seed) + + # Shape of the matrix with only n - 1 columns that we will embed in higher + # dimensional space. + smaller_shape = batch_shape + [m, n - 1] + + # Shape of the embedding matrix, mapping batch matrices + # from [..., N-1, M] to [..., N, M] + embedding_mat_shape = batch_shape + [n, n - 1] + + # This stddev for the embedding_mat ensures final result has correct stddev. + stddev_mat = 1 / np.sqrt(n - 1) + + with ops.name_scope("random_normal_correlated_columns"): + smaller_mat = random_normal( + smaller_shape, mean=0.0, stddev=stddev_mat, dtype=dtype, seed=seed) + + if seed is not None: + seed += 1287 + + embedding_mat = random_normal(embedding_mat_shape, dtype=dtype, seed=seed) + + embedded_t = math_ops.matmul(embedding_mat, smaller_mat, transpose_b=True) + embedded = array_ops.matrix_transpose(embedded_t) + + mean_mat = array_ops.ones_like(embedded) * mean + + return embedded + random_normal(shape, stddev=eps, dtype=dtype) + mean_mat diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_toeplitz.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_toeplitz.py new file mode 100644 index 0000000000000000000000000000000000000000..ea87ef6a61b55829ae0230782bf5b3c763d9c244 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_toeplitz.py @@ -0,0 +1,292 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a Toeplitz matrix.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_circulant +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.ops.signal import fft_ops +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["LinearOperatorToeplitz",] + + +@tf_export("linalg.LinearOperatorToeplitz") +@linear_operator.make_composite_tensor +class LinearOperatorToeplitz(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] of toeplitz matrices. + + This operator acts like a [batch] Toeplitz matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x N` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + #### Description in terms of toeplitz matrices + + Toeplitz means that `A` has constant diagonals. Hence, `A` can be generated + with two vectors. One represents the first column of the matrix, and the + other represents the first row. + + Below is a 4 x 4 example: + + ``` + A = |a b c d| + |e a b c| + |f e a b| + |g f e a| + ``` + + #### Example of a Toeplitz operator. + + ```python + # Create a 3 x 3 Toeplitz operator. + col = [1., 2., 3.] + row = [1., 4., -9.] + operator = LinearOperatorToeplitz(col, row) + + operator.to_dense() + ==> [[1., 4., -9.], + [2., 1., 4.], + [3., 2., 1.]] + + operator.shape + ==> [3, 3] + + operator.log_abs_determinant() + ==> scalar Tensor + + x = ... Shape [3, 4] Tensor + operator.matmul(x) + ==> Shape [3, 4] Tensor + ``` + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + col, + row, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name="LinearOperatorToeplitz"): + r"""Initialize a `LinearOperatorToeplitz`. + + Args: + col: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`. + The first column of the operator. Allowed dtypes: `float16`, `float32`, + `float64`, `complex64`, `complex128`. Note that the first entry of + `col` is assumed to be the same as the first entry of `row`. + row: Shape `[B1,...,Bb, N]` `Tensor` with `b >= 0` `N >= 0`. + The first row of the operator. Allowed dtypes: `float16`, `float32`, + `float64`, `complex64`, `complex128`. Note that the first entry of + `row` is assumed to be the same as the first entry of `col`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `diag.dtype` is real, this is auto-set to `True`. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + """ + parameters = dict( + col=col, + row=row, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[row, col]): + self._row = linear_operator_util.convert_nonref_to_tensor(row, name="row") + self._col = linear_operator_util.convert_nonref_to_tensor(col, name="col") + self._check_row_col(self._row, self._col) + + if is_square is False: # pylint:disable=g-bool-id-comparison + raise ValueError("Only square Toeplitz operators currently supported.") + is_square = True + + super(LinearOperatorToeplitz, self).__init__( + dtype=self._row.dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _check_row_col(self, row, col): + """Static check of row and column.""" + for name, tensor in [["row", row], ["col", col]]: + if tensor.shape.ndims is not None and tensor.shape.ndims < 1: + raise ValueError("Argument {} must have at least 1 dimension. " + "Found: {}".format(name, tensor)) + + if row.shape[-1] is not None and col.shape[-1] is not None: + if row.shape[-1] != col.shape[-1]: + raise ValueError( + "Expected square matrix, got row and col with mismatched " + "dimensions.") + + def _shape(self): + # If d_shape = [5, 3], we return [5, 3, 3]. + v_shape = array_ops.broadcast_static_shape( + self.row.shape, self.col.shape) + return v_shape.concatenate(v_shape[-1:]) + + def _shape_tensor(self, row=None, col=None): + row = self.row if row is None else row + col = self.col if col is None else col + v_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(row), + array_ops.shape(col)) + k = v_shape[-1] + return array_ops.concat((v_shape, [k]), 0) + + def _assert_self_adjoint(self): + return check_ops.assert_equal( + self.row, + self.col, + message=("row and col are not the same, and " + "so this operator is not self-adjoint.")) + + # TODO(srvasude): Add efficient solver and determinant calculations to this + # class (based on Levinson recursion.) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + # Given a Toeplitz matrix, we can embed it in a Circulant matrix to perform + # efficient matrix multiplications. Given a Toeplitz matrix with first row + # [t_0, t_1, ... t_{n-1}] and first column [t0, t_{-1}, ..., t_{-(n-1)}, + # let C by the circulant matrix with first column [t0, t_{-1}, ..., + # t_{-(n-1)}, 0, t_{n-1}, ..., t_1]. Also adjoin to our input vector `x` + # `n` zeros, to make it a vector of length `2n` (call it y). It can be shown + # that if we take the first n entries of `Cy`, this is equal to the Toeplitz + # multiplication. See: + # http://math.mit.edu/icg/resources/teaching/18.085-spring2015/toeplitz.pdf + # for more details. + x = linalg.adjoint(x) if adjoint_arg else x + expanded_x = array_ops.concat([x, array_ops.zeros_like(x)], axis=-2) + col = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.col) + row = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.row) + circulant_col = array_ops.concat( + [col, + array_ops.zeros_like(col[..., 0:1]), + array_ops.reverse(row[..., 1:], axis=[-1])], axis=-1) + circulant = linear_operator_circulant.LinearOperatorCirculant( + fft_ops.fft(_to_complex(circulant_col)), + input_output_dtype=row.dtype) + result = circulant.matmul(expanded_x, adjoint=adjoint, adjoint_arg=False) + + shape = self._shape_tensor(row=row, col=col) + return math_ops.cast( + result[..., :self._domain_dimension_tensor(shape=shape), :], + self.dtype) + + def _trace(self): + return math_ops.cast( + self.domain_dimension_tensor(), + dtype=self.dtype) * self.col[..., 0] + + def _diag_part(self): + diag_entry = self.col[..., 0:1] + return diag_entry * array_ops.ones( + [self.domain_dimension_tensor()], self.dtype) + + def _to_dense(self): + row = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.row) + col = tensor_conversion.convert_to_tensor_v2_with_dispatch(self.col) + total_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(row), array_ops.shape(col)) + n = array_ops.shape(row)[-1] + row = array_ops.broadcast_to(row, total_shape) + col = array_ops.broadcast_to(col, total_shape) + # We concatenate the column in reverse order to the row. + # This gives us 2*n + 1 elements. + elements = array_ops.concat( + [array_ops.reverse(col, axis=[-1]), row[..., 1:]], axis=-1) + # Given the above vector, the i-th row of the Toeplitz matrix + # is the last n elements of the above vector shifted i right + # (hence the first row is just the row vector provided, and + # the first element of each row will belong to the column vector). + # We construct these set of indices below. + indices = math_ops.mod( + # How much to shift right. This corresponds to `i`. + math_ops.range(0, n) + + # Specifies the last `n` indices. + math_ops.range(n - 1, -1, -1)[..., array_ops.newaxis], + # Mod out by the total number of elements to ensure the index is + # non-negative (for tf.gather) and < 2 * n - 1. + 2 * n - 1) + return array_ops.gather(elements, indices, axis=-1) + + @property + def col(self): + return self._col + + @property + def row(self): + return self._row + + @property + def _composite_tensor_fields(self): + return ("col", "row") + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + return {"col": 1, "row": 1} + + +def _to_complex(x): + dtype = dtypes.complex64 + if x.dtype in [dtypes.float64, dtypes.complex128]: + dtype = dtypes.complex128 + return math_ops.cast(x, dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_tridiag.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_tridiag.py new file mode 100644 index 0000000000000000000000000000000000000000..b5353cfc9ff9f8d1a07727a2339f1a302fc1cdb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_tridiag.py @@ -0,0 +1,401 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a tridiagonal matrix.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import manip_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = ['LinearOperatorTridiag',] + +_COMPACT = 'compact' +_MATRIX = 'matrix' +_SEQUENCE = 'sequence' +_DIAGONAL_FORMATS = frozenset({_COMPACT, _MATRIX, _SEQUENCE}) + + +@tf_export('linalg.LinearOperatorTridiag') +@linear_operator.make_composite_tensor +class LinearOperatorTridiag(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] square tridiagonal matrix. + + This operator acts like a [batch] square tridiagonal matrix `A` with shape + `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x M` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + Example usage: + + Create a 3 x 3 tridiagonal linear operator. + + >>> superdiag = [3., 4., 5.] + >>> diag = [1., -1., 2.] + >>> subdiag = [6., 7., 8] + >>> operator = tf.linalg.LinearOperatorTridiag( + ... [superdiag, diag, subdiag], + ... diagonals_format='sequence') + >>> operator.to_dense() + + >>> operator.shape + TensorShape([3, 3]) + + Scalar Tensor output. + + >>> operator.log_abs_determinant() + + + Create a [2, 3] batch of 4 x 4 linear operators. + + >>> diagonals = tf.random.normal(shape=[2, 3, 3, 4]) + >>> operator = tf.linalg.LinearOperatorTridiag( + ... diagonals, + ... diagonals_format='compact') + + Create a shape [2, 1, 4, 2] vector. Note that this shape is compatible + since the batch dimensions, [2, 1], are broadcast to + operator.batch_shape = [2, 3]. + + >>> y = tf.random.normal(shape=[2, 1, 4, 2]) + >>> x = operator.solve(y) + >>> x + + + #### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, N], with b >= 0 + x.shape = [C1,...,Cc] + [N, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb]. + ``` + + #### Performance + + Suppose `operator` is a `LinearOperatorTridiag` of shape `[N, N]`, + and `x.shape = [N, R]`. Then + + * `operator.matmul(x)` will take O(N * R) time. + * `operator.solve(x)` will take O(N * R) time. + + If instead `operator` and `x` have shape `[B1,...,Bb, N, N]` and + `[B1,...,Bb, N, R]`, every operation increases in complexity by `B1*...*Bb`. + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + diagonals, + diagonals_format=_COMPACT, + is_non_singular=None, + is_self_adjoint=None, + is_positive_definite=None, + is_square=None, + name='LinearOperatorTridiag'): + r"""Initialize a `LinearOperatorTridiag`. + + Args: + diagonals: `Tensor` or list of `Tensor`s depending on `diagonals_format`. + + If `diagonals_format=sequence`, this is a list of three `Tensor`'s each + with shape `[B1, ..., Bb, N]`, `b >= 0, N >= 0`, representing the + superdiagonal, diagonal and subdiagonal in that order. Note the + superdiagonal is padded with an element in the last position, and the + subdiagonal is padded with an element in the front. + + If `diagonals_format=matrix` this is a `[B1, ... Bb, N, N]` shaped + `Tensor` representing the full tridiagonal matrix. + + If `diagonals_format=compact` this is a `[B1, ... Bb, 3, N]` shaped + `Tensor` with the second to last dimension indexing the + superdiagonal, diagonal and subdiagonal in that order. Note the + superdiagonal is padded with an element in the last position, and the + subdiagonal is padded with an element in the front. + + In every case, these `Tensor`s are all floating dtype. + diagonals_format: one of `matrix`, `sequence`, or `compact`. Default is + `compact`. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. If `diag.dtype` is real, this is auto-set to `True`. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + name: A name for this `LinearOperator`. + + Raises: + TypeError: If `diag.dtype` is not an allowed type. + ValueError: If `diag.dtype` is real, and `is_self_adjoint` is not `True`. + """ + parameters = dict( + diagonals=diagonals, + diagonals_format=diagonals_format, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + name=name + ) + + with ops.name_scope(name, values=[diagonals]): + if diagonals_format not in _DIAGONAL_FORMATS: + raise ValueError( + f'Argument `diagonals_format` must be one of compact, matrix, or ' + f'sequence. Received : {diagonals_format}.') + if diagonals_format == _SEQUENCE: + self._diagonals = [linear_operator_util.convert_nonref_to_tensor( + d, name='diag_{}'.format(i)) for i, d in enumerate(diagonals)] + dtype = self._diagonals[0].dtype + else: + self._diagonals = linear_operator_util.convert_nonref_to_tensor( + diagonals, name='diagonals') + dtype = self._diagonals.dtype + self._diagonals_format = diagonals_format + + super(LinearOperatorTridiag, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + def _shape(self): + if self.diagonals_format == _MATRIX: + return self.diagonals.shape + if self.diagonals_format == _COMPACT: + # Remove the second to last dimension that contains the value 3. + d_shape = self.diagonals.shape[:-2].concatenate( + self.diagonals.shape[-1]) + else: + broadcast_shape = array_ops.broadcast_static_shape( + self.diagonals[0].shape[:-1], + self.diagonals[1].shape[:-1]) + broadcast_shape = array_ops.broadcast_static_shape( + broadcast_shape, + self.diagonals[2].shape[:-1]) + d_shape = broadcast_shape.concatenate(self.diagonals[1].shape[-1]) + return d_shape.concatenate(d_shape[-1]) + + def _shape_tensor(self, diagonals=None): + diagonals = diagonals if diagonals is not None else self.diagonals + if self.diagonals_format == _MATRIX: + return array_ops.shape(diagonals) + if self.diagonals_format == _COMPACT: + d_shape = array_ops.shape(diagonals[..., 0, :]) + else: + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(self.diagonals[0])[:-1], + array_ops.shape(self.diagonals[1])[:-1]) + broadcast_shape = array_ops.broadcast_dynamic_shape( + broadcast_shape, + array_ops.shape(self.diagonals[2])[:-1]) + d_shape = array_ops.concat( + [broadcast_shape, [array_ops.shape(self.diagonals[1])[-1]]], axis=0) + return array_ops.concat([d_shape, [d_shape[-1]]], axis=-1) + + def _assert_self_adjoint(self): + # Check the diagonal has non-zero imaginary, and the super and subdiagonals + # are conjugate. + + asserts = [] + diag_message = ( + 'This tridiagonal operator contained non-zero ' + 'imaginary values on the diagonal.') + off_diag_message = ( + 'This tridiagonal operator has non-conjugate ' + 'subdiagonal and superdiagonal.') + + if self.diagonals_format == _MATRIX: + asserts += [check_ops.assert_equal( + self.diagonals, linalg.adjoint(self.diagonals), + message='Matrix was not equal to its adjoint.')] + elif self.diagonals_format == _COMPACT: + diagonals = tensor_conversion.convert_to_tensor_v2_with_dispatch( + self.diagonals + ) + asserts += [linear_operator_util.assert_zero_imag_part( + diagonals[..., 1, :], message=diag_message)] + # Roll the subdiagonal so the shifted argument is at the end. + subdiag = manip_ops.roll(diagonals[..., 2, :], shift=-1, axis=-1) + asserts += [check_ops.assert_equal( + math_ops.conj(subdiag[..., :-1]), + diagonals[..., 0, :-1], + message=off_diag_message)] + else: + asserts += [linear_operator_util.assert_zero_imag_part( + self.diagonals[1], message=diag_message)] + subdiag = manip_ops.roll(self.diagonals[2], shift=-1, axis=-1) + asserts += [check_ops.assert_equal( + math_ops.conj(subdiag[..., :-1]), + self.diagonals[0][..., :-1], + message=off_diag_message)] + return control_flow_ops.group(asserts) + + def _construct_adjoint_diagonals(self, diagonals): + # Constructs adjoint tridiagonal matrix from diagonals. + if self.diagonals_format == _SEQUENCE: + diagonals = [math_ops.conj(d) for d in reversed(diagonals)] + # The subdiag and the superdiag swap places, so we need to shift the + # padding argument. + diagonals[0] = manip_ops.roll(diagonals[0], shift=-1, axis=-1) + diagonals[2] = manip_ops.roll(diagonals[2], shift=1, axis=-1) + return diagonals + elif self.diagonals_format == _MATRIX: + return linalg.adjoint(diagonals) + else: + diagonals = math_ops.conj(diagonals) + superdiag, diag, subdiag = array_ops_stack.unstack( + diagonals, num=3, axis=-2) + # The subdiag and the superdiag swap places, so we need + # to shift all arguments. + new_superdiag = manip_ops.roll(subdiag, shift=-1, axis=-1) + new_subdiag = manip_ops.roll(superdiag, shift=1, axis=-1) + return array_ops_stack.stack([new_superdiag, diag, new_subdiag], axis=-2) + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + diagonals = self.diagonals + if adjoint: + diagonals = self._construct_adjoint_diagonals(diagonals) + x = linalg.adjoint(x) if adjoint_arg else x + return linalg.tridiagonal_matmul( + diagonals, x, + diagonals_format=self.diagonals_format) + + def _solve(self, rhs, adjoint=False, adjoint_arg=False): + diagonals = self.diagonals + if adjoint: + diagonals = self._construct_adjoint_diagonals(diagonals) + + # TODO(b/144860784): Remove the broadcasting code below once + # tridiagonal_solve broadcasts. + + rhs_shape = array_ops.shape(rhs) + k = self._shape_tensor(diagonals)[-1] + broadcast_shape = array_ops.broadcast_dynamic_shape( + self._shape_tensor(diagonals)[:-2], rhs_shape[:-2]) + rhs = array_ops.broadcast_to( + rhs, array_ops.concat( + [broadcast_shape, rhs_shape[-2:]], axis=-1)) + if self.diagonals_format == _MATRIX: + diagonals = array_ops.broadcast_to( + diagonals, array_ops.concat( + [broadcast_shape, [k, k]], axis=-1)) + elif self.diagonals_format == _COMPACT: + diagonals = array_ops.broadcast_to( + diagonals, array_ops.concat( + [broadcast_shape, [3, k]], axis=-1)) + else: + diagonals = [ + array_ops.broadcast_to(d, array_ops.concat( + [broadcast_shape, [k]], axis=-1)) for d in diagonals] + + y = linalg.tridiagonal_solve( + diagonals, rhs, + diagonals_format=self.diagonals_format, + transpose_rhs=adjoint_arg, + conjugate_rhs=adjoint_arg) + return y + + def _diag_part(self): + if self.diagonals_format == _MATRIX: + return array_ops.matrix_diag_part(self.diagonals) + elif self.diagonals_format == _SEQUENCE: + diagonal = self.diagonals[1] + return array_ops.broadcast_to( + diagonal, self.shape_tensor()[:-1]) + else: + return self.diagonals[..., 1, :] + + def _to_dense(self): + if self.diagonals_format == _MATRIX: + return self.diagonals + + if self.diagonals_format == _COMPACT: + return gen_array_ops.matrix_diag_v3( + self.diagonals, + k=(-1, 1), + num_rows=-1, + num_cols=-1, + align='LEFT_RIGHT', + padding_value=0.) + + diagonals = [ + tensor_conversion.convert_to_tensor_v2_with_dispatch(d) + for d in self.diagonals + ] + diagonals = array_ops_stack.stack(diagonals, axis=-2) + + return gen_array_ops.matrix_diag_v3( + diagonals, + k=(-1, 1), + num_rows=-1, + num_cols=-1, + align='LEFT_RIGHT', + padding_value=0.) + + @property + def diagonals(self): + return self._diagonals + + @property + def diagonals_format(self): + return self._diagonals_format + + @property + def _composite_tensor_fields(self): + return ('diagonals', 'diagonals_format') + + @property + def _experimental_parameter_ndims_to_matrix_ndims(self): + diagonal_event_ndims = 2 + if self.diagonals_format == _SEQUENCE: + # For the diagonal and the super/sub diagonals. + diagonal_event_ndims = [1, 1, 1] + return { + 'diagonals': diagonal_event_ndims, + } diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ae601ff8781ce639c492a51da7a4a0e373616ce2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_util.py @@ -0,0 +1,627 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Internal utilities for `LinearOperator` classes.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.module import module +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables as variables_module +from tensorflow.python.util import nest + + +################################################################################ +# To make more friendly for TF2. +################################################################################ + + +def convert_nonref_to_tensor(value, dtype=None, dtype_hint=None, name=None): + """Converts the given `value` to a `Tensor` if input is nonreference type. + + This function converts Python objects of various types to `Tensor` objects + except if the input has nonreference semantics. Reference semantics are + characterized by `is_ref` and is any object which is a + `tf.Variable` or instance of `tf.Module`. This function accepts any input + which `tf.convert_to_tensor` would also. + + Note: This function diverges from default Numpy behavior for `float` and + `string` types when `None` is present in a Python list or scalar. Rather + than silently converting `None` values, an error will be thrown. + + Args: + value: An object whose type has a registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing, the + type is inferred from the type of `value`. + dtype_hint: Optional element type for the returned tensor, + used when dtype is None. In some cases, a caller may not have a + dtype in mind when converting to a tensor, so dtype_hint + can be used as a soft preference. If the conversion to + `dtype_hint` is not possible, this argument has no effect. + name: Optional name to use if a new `Tensor` is created. + + Returns: + tensor: A `Tensor` based on `value`. + + Raises: + TypeError: If no conversion function is registered for `value` to `dtype`. + RuntimeError: If a registered conversion function returns an invalid value. + ValueError: If the `value` is a tensor not of given `dtype` in graph mode. + + + #### Examples: + + ```python + + x = tf.Variable(0.) + y = convert_nonref_to_tensor(x) + x is y + # ==> True + + x = tf.constant(0.) + y = convert_nonref_to_tensor(x) + x is y + # ==> True + + x = np.array(0.) + y = convert_nonref_to_tensor(x) + x is y + # ==> False + tf.is_tensor(y) + # ==> True + + x = tfp.util.DeferredTensor(13.37, lambda x: x) + y = convert_nonref_to_tensor(x) + x is y + # ==> True + tf.is_tensor(y) + # ==> False + tf.equal(y, 13.37) + # ==> True + ``` + + """ + # We explicitly do not use a tf.name_scope to avoid graph clutter. + if value is None: + return None + if is_ref(value): + if dtype is None: + return value + dtype_base = base_dtype(dtype) + value_dtype_base = base_dtype(value.dtype) + if dtype_base != value_dtype_base: + raise TypeError( + f"Argument `value` must be of dtype `{dtype_name(dtype_base)}` " + f"Received: `{dtype_name(value_dtype_base)}`.") + return value + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + value, dtype=dtype, dtype_hint=dtype_hint, name=name + ) + + +def base_dtype(dtype): + """Returns a non-reference `dtype` based on this `dtype`.""" + dtype = dtypes.as_dtype(dtype) + if hasattr(dtype, "base_dtype"): + return dtype.base_dtype + return dtype + + +def dtype_name(dtype): + """Returns the string name for this `dtype`.""" + dtype = dtypes.as_dtype(dtype) + if hasattr(dtype, "name"): + return dtype.name + if hasattr(dtype, "__name__"): + return dtype.__name__ + return str(dtype) + + +def check_dtype(arg, dtype): + """Check that arg.dtype == self.dtype.""" + if arg.dtype.base_dtype != dtype: + raise TypeError( + f"Expected argument to have dtype {dtype}. Found: {arg.dtype} in " + f"tensor {arg}.") + + +def is_ref(x): + """Evaluates if the object has reference semantics. + + An object is deemed "reference" if it is a `tf.Variable` instance or is + derived from a `tf.Module` with `dtype` and `shape` properties. + + Args: + x: Any object. + + Returns: + is_ref: Python `bool` indicating input is has nonreference semantics, i.e., + is a `tf.Variable` or a `tf.Module` with `dtype` and `shape` properties. + """ + return ( + # Note: we check that tf.Variable is a class because we might be using a + # different backend other than TF. + isinstance(x, variables_module.Variable) or + (isinstance(x, module.Module) and hasattr(x, "dtype") and + hasattr(x, "shape"))) + + +def assert_not_ref_type(x, arg_name): + if is_ref(x): + raise TypeError( + f"Argument {arg_name} cannot be reference type. Found: {type(x)}.") + + +################################################################################ +# Asserts. +################################################################################ + + +def assert_no_entries_with_modulus_zero( + x, message=None, name="assert_no_entries_with_modulus_zero"): + """Returns `Op` that asserts Tensor `x` has no entries with modulus zero. + + Args: + x: Numeric `Tensor`, real, integer, or complex. + message: A string message to prepend to failure message. + name: A name to give this `Op`. + + Returns: + An `Op` that asserts `x` has no entries with modulus zero. + """ + with ops.name_scope(name, values=[x]): + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + dtype = x.dtype.base_dtype + should_be_nonzero = math_ops.abs(x) + zero = tensor_conversion.convert_to_tensor_v2_with_dispatch( + 0, dtype=dtype.real_dtype + ) + return check_ops.assert_less(zero, should_be_nonzero, message=message) + + +def assert_zero_imag_part(x, message=None, name="assert_zero_imag_part"): + """Returns `Op` that asserts Tensor `x` has no non-zero imaginary parts. + + Args: + x: Numeric `Tensor`, real, integer, or complex. + message: A string message to prepend to failure message. + name: A name to give this `Op`. + + Returns: + An `Op` that asserts `x` has no entries with modulus zero. + """ + with ops.name_scope(name, values=[x]): + x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x, name="x") + dtype = x.dtype.base_dtype + + if dtype.is_floating: + return control_flow_ops.no_op() + + zero = tensor_conversion.convert_to_tensor_v2_with_dispatch( + 0, dtype=dtype.real_dtype + ) + return check_ops.assert_equal(zero, math_ops.imag(x), message=message) + + +def assert_compatible_matrix_dimensions(operator, x): + """Assert that an argument to solve/matmul has proper domain dimension. + + If `operator.shape[-2:] = [M, N]`, and `x.shape[-2:] = [Q, R]`, then + `operator.matmul(x)` is defined only if `N = Q`. This `Op` returns an + `Assert` that "fires" if this is not the case. Static checks are already + done by the base class `LinearOperator`. + + Args: + operator: `LinearOperator`. + x: `Tensor`. + + Returns: + `Assert` `Op`. + """ + # Static checks are done in the base class. Only tensor asserts here. + assert_same_dd = check_ops.assert_equal( + array_ops.shape(x)[-2], + operator.domain_dimension_tensor(), + # This error message made to look similar to error raised by static check + # in the base class. + message=("Dimensions are not compatible. " + "shape[-2] of argument to be the same as this operator")) + + return assert_same_dd + + +def assert_is_batch_matrix(tensor): + """Static assert that `tensor` has rank `2` or higher.""" + sh = tensor.shape + if sh.ndims is not None and sh.ndims < 2: + raise ValueError( + f"Expected [batch] matrix to have at least two dimensions. Found: " + f"{tensor}.") + + +def shape_tensor(shape, name=None): + """Convert Tensor using default type, unless empty list or tuple.""" + # Works just like random_ops._ShapeTensor. + if isinstance(shape, (tuple, list)) and not shape: + dtype = dtypes.int32 + else: + dtype = None + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + shape, dtype=dtype, name=name + ) + + +################################################################################ +# Broadcasting versions of common linear algebra functions. +# TODO(b/77519145) Do this more efficiently in some special cases. +################################################################################ + + +def broadcast_matrix_batch_dims(batch_matrices, name=None): + """Broadcast leading dimensions of zero or more [batch] matrices. + + Example broadcasting one batch dim of two simple matrices. + + ```python + x = [[1, 2], + [3, 4]] # Shape [2, 2], no batch dims + + y = [[[1]]] # Shape [1, 1, 1], 1 batch dim of shape [1] + + x_bc, y_bc = broadcast_matrix_batch_dims([x, y]) + + x_bc + ==> [[[1, 2], + [3, 4]]] # Shape [1, 2, 2], 1 batch dim of shape [1]. + + y_bc + ==> same as y + ``` + + Example broadcasting many batch dims + + ```python + x = tf.random.normal(shape=(2, 3, 1, 4, 4)) + y = tf.random.normal(shape=(1, 3, 2, 5, 5)) + x_bc, y_bc = broadcast_matrix_batch_dims([x, y]) + + x_bc.shape + ==> (2, 3, 2, 4, 4) + + y_bc.shape + ==> (2, 3, 2, 5, 5) + ``` + + Args: + batch_matrices: Iterable of `Tensor`s, each having two or more dimensions. + name: A string name to prepend to created ops. + + Returns: + bcast_matrices: List of `Tensor`s, with `bcast_matrices[i]` containing + the values from `batch_matrices[i]`, with possibly broadcast batch dims. + + Raises: + ValueError: If any input `Tensor` is statically determined to have less + than two dimensions. + """ + with ops.name_scope( + name or "broadcast_matrix_batch_dims", values=batch_matrices): + check_ops.assert_proper_iterable(batch_matrices) + batch_matrices = list(batch_matrices) + + for i, mat in enumerate(batch_matrices): + batch_matrices[i] = tensor_conversion.convert_to_tensor_v2_with_dispatch( + mat + ) + assert_is_batch_matrix(batch_matrices[i]) + + if len(batch_matrices) < 2: + return batch_matrices + + # Try static broadcasting. + # bcast_batch_shape is the broadcast batch shape of ALL matrices. + # E.g. if batch_matrices = [x, y], with + # x.shape = [2, j, k] (batch shape = [2]) + # y.shape = [3, 1, l, m] (batch shape = [3, 1]) + # ==> bcast_batch_shape = [3, 2] + bcast_batch_shape = batch_matrices[0].shape[:-2] + for mat in batch_matrices[1:]: + bcast_batch_shape = array_ops.broadcast_static_shape( + bcast_batch_shape, + mat.shape[:-2]) + if bcast_batch_shape.is_fully_defined(): + for i, mat in enumerate(batch_matrices): + if mat.shape[:-2] != bcast_batch_shape: + bcast_shape = array_ops.concat( + [bcast_batch_shape.as_list(), array_ops.shape(mat)[-2:]], axis=0) + batch_matrices[i] = array_ops.broadcast_to(mat, bcast_shape) + return batch_matrices + + # Since static didn't work, do dynamic, which always copies data. + bcast_batch_shape = array_ops.shape(batch_matrices[0])[:-2] + for mat in batch_matrices[1:]: + bcast_batch_shape = array_ops.broadcast_dynamic_shape( + bcast_batch_shape, + array_ops.shape(mat)[:-2]) + for i, mat in enumerate(batch_matrices): + batch_matrices[i] = array_ops.broadcast_to( + mat, + array_ops.concat( + [bcast_batch_shape, array_ops.shape(mat)[-2:]], axis=0)) + + return batch_matrices + + +def matrix_solve_with_broadcast(matrix, rhs, adjoint=False, name=None): + """Solve systems of linear equations.""" + with ops.name_scope(name, "MatrixSolveWithBroadcast", [matrix, rhs]): + matrix = tensor_conversion.convert_to_tensor_v2_with_dispatch( + matrix, name="matrix" + ) + rhs = tensor_conversion.convert_to_tensor_v2_with_dispatch( + rhs, name="rhs", dtype=matrix.dtype + ) + + # If either matrix/rhs has extra dims, we can reshape to get rid of them. + matrix, rhs, reshape_inv, still_need_to_transpose = _reshape_for_efficiency( + matrix, rhs, adjoint_a=adjoint) + + # This will broadcast by brute force if we still need to. + matrix, rhs = broadcast_matrix_batch_dims([matrix, rhs]) + + solution = linalg_ops.matrix_solve( + matrix, rhs, adjoint=adjoint and still_need_to_transpose) + + return reshape_inv(solution) + + +def _reshape_for_efficiency(a, + b, + transpose_a=False, + transpose_b=False, + adjoint_a=False, + adjoint_b=False): + """Maybe reshape a, b, and return an inverse map. For matmul/solve.""" + def identity(x): + return x + + # At this point, we have not taken transpose/adjoint of a/b. + still_need_to_transpose = True + + if a.shape.ndims is None or b.shape.ndims is None: + return a, b, identity, still_need_to_transpose + + # This could be handled in the future, but seems less common. + if a.shape.ndims >= b.shape.ndims: + return a, b, identity, still_need_to_transpose + + # From now on, we might modify b, but will not modify a. + + # Suppose: + # a.shape = C + [m, n], b.shape = + # b.shape = S + C + [n, r] + b_extra_ndims = b.shape.ndims - a.shape.ndims + + # b_extra_sh = S, b_main_sh = C + [n, r] + b_extra_sh = array_ops.shape(b)[:b_extra_ndims] + b_main_sh = array_ops.shape(b)[b_extra_ndims:] + + # No reason to flip unless the extra dims of b are big enough. Why? + # Assume adjoint/transpose = False. Then... + # By not flipping, we have to replicate a to shape + # b_extra_sh + a.shape, + # which could use extra memory. But in all cases, the final output has shape + # b_extra_sh + a.shape[:-1] + [b.shape[-1]] + # So we only end up creating a larger object if the end dim of b is smaller + # than the end dim of a. This often happens, e.g. if b was a vector that was + # expanded to a matrix (by appending a singleton). + + # Since adjoint/transpose may not be False, we must make adjustments here. + # The dim of b that holds the multiple equations. + a_domain_sz_ = a.shape[-2 if adjoint_a or transpose_a else -1] + b_eq_sz_ = b.shape[-2 if adjoint_b or transpose_b else -1] + b_extra_sz_ = ( + np.prod(b.shape[:b_extra_ndims].as_list()) + if b.shape[:b_extra_ndims].is_fully_defined() else None) + if (a_domain_sz_ is not None and b_eq_sz_ is not None and + b_extra_sz_ is not None): + if b_extra_sz_ < 2 or a_domain_sz_ <= b_eq_sz_: + return a, b, identity, still_need_to_transpose + + # At this point, we're flipping for sure! + # Any transposes/adjoints will happen here explicitly, rather than in calling + # code. Why? To avoid having to write separate complex code for each case. + if adjoint_a: + a = array_ops.matrix_transpose(a, conjugate=True) + elif transpose_a: + a = array_ops.matrix_transpose(a, conjugate=False) + if adjoint_b: + b = array_ops.matrix_transpose(b, conjugate=True) + elif transpose_a: + b = array_ops.matrix_transpose(b, conjugate=False) + still_need_to_transpose = False + + # Recompute shapes, since the transpose/adjoint may have changed them. + b_extra_sh = array_ops.shape(b)[:b_extra_ndims] + b_main_sh = array_ops.shape(b)[b_extra_ndims:] + + # Permutation to put the extra dims at the end. + perm = ( + np.concatenate( + (np.arange(b_extra_ndims, b.shape.ndims), + np.arange(0, b_extra_ndims)), 0)) + b_extra_on_end = array_ops.transpose(b, perm=perm) + + # Now squash this end into one long dim. + b_squashed_end = array_ops.reshape( + b_extra_on_end, array_ops.concat((b_main_sh[:-1], [-1]), 0)) + + def reshape_inv(y): + # Expand the extra dims hanging off the end, "b_extra_sh". + # Note we use y_sh[:-1] + [b_main_sh[-1]] rather than b_main_sh, because y + # Could have different batch dims than a and b, because of broadcasting. + y_extra_shape = array_ops.concat( + (array_ops.shape(y)[:-1], [b_main_sh[-1]], b_extra_sh), 0) + y_extra_on_end = array_ops.reshape(y, y_extra_shape) + inverse_perm = np.argsort(perm) + return array_ops.transpose(y_extra_on_end, perm=inverse_perm) + + return a, b_squashed_end, reshape_inv, still_need_to_transpose + + +################################################################################ +# Helpers for hints. +################################################################################ + + +def is_adjoint_pair(x, y): + """True iff x and y are adjoints of each other (by id, not entries).""" + if x is y: # Note that if x is y then all of their hints are the same! + if x.is_self_adjoint is False: # pylint:disable=g-bool-id-comparison + return False + if x.is_self_adjoint: + return True + # Use the fact that if x = LinearOperatorAdjoint(y), then x.H is y. + return x.H is y or y.H is x + + +def is_aat_form(operators): + """Returns True if operators is of the form A @ A.H, possibly recursively.""" + operators = list(operators) + if not operators: + raise ValueError("AAT form is undefined for empty operators") + + if len(operators) % 2: + return False + + # Check for forms like (A1 @ A2) @ (A2.H @ A1.H) + return all( + is_adjoint_pair(operators[i], operators[-1 - i]) + for i in range(len(operators) // 2)) + + +def use_operator_or_provided_hint_unless_contradicting( + operator, hint_attr_name, provided_hint_value, message): + """Get combined hint in the case where operator.hint should equal hint. + + Args: + operator: LinearOperator that a meta-operator was initialized with. + hint_attr_name: String name for the attribute. + provided_hint_value: Bool or None. Value passed by user in initialization. + message: Error message to print if hints contradict. + + Returns: + True, False, or None. + + Raises: + ValueError: If hints contradict. + """ + op_hint = getattr(operator, hint_attr_name) + # pylint: disable=g-bool-id-comparison + if op_hint is False and provided_hint_value: + raise ValueError(message) + if op_hint and provided_hint_value is False: + raise ValueError(message) + if op_hint or provided_hint_value: + return True + if op_hint is False or provided_hint_value is False: + return False + # pylint: enable=g-bool-id-comparison + return None + + +################################################################################ +# Utilities for blockwise operators. +################################################################################ + + +def arg_is_blockwise(block_dimensions, arg, arg_split_dim): + """Detect if input should be interpreted as a list of blocks.""" + # Tuples and lists of length equal to the number of operators may be + # blockwise. + if (isinstance(arg, (tuple, list)) and len(arg) == len(block_dimensions)): + # If the elements of the iterable are not nested, interpret the input as + # blockwise. + if not any(nest.is_nested(x) for x in arg): + return True + else: + arg_dims = [ + tensor_conversion.convert_to_tensor_v2_with_dispatch(x).shape[ + arg_split_dim + ] + for x in arg + ] + self_dims = [dim.value for dim in block_dimensions] + + # If none of the operator dimensions are known, interpret the input as + # blockwise if its matching dimensions are unequal. + if all(self_d is None for self_d in self_dims): + + # A nested tuple/list with a single outermost element is not blockwise + if len(arg_dims) == 1: + return False + elif any(dim != arg_dims[0] for dim in arg_dims): + return True + else: + raise ValueError( + "Parsing of the input structure is ambiguous. Please input " + "a blockwise iterable of `Tensor`s or a single `Tensor`.") + + # If input dimensions equal the respective (known) blockwise operator + # dimensions, then the input is blockwise. + if all(self_d == arg_d or self_d is None + for self_d, arg_d in zip(self_dims, arg_dims)): + return True + + # If input dimensions equals are all equal, and are greater than or equal + # to the sum of the known operator dimensions, interpret the input as + # blockwise. + # input is not blockwise. + self_dim = sum(self_d for self_d in self_dims if self_d is not None) + if all(s == arg_dims[0] for s in arg_dims) and arg_dims[0] >= self_dim: + return False + + # If none of these conditions is met, the input shape is mismatched. + raise ValueError("Input dimension does not match operator dimension.") + else: + return False + + +def split_arg_into_blocks(block_dims, block_dims_fn, arg, axis=-1): + """Split `x` into blocks matching `operators`'s `domain_dimension`. + + Specifically, if we have a blockwise lower-triangular matrix, with block + sizes along the diagonal `[M_j, M_j] j = 0,1,2..J`, this method splits `arg` + on `axis` into `J` tensors, whose shape at `axis` is `M_j`. + + Args: + block_dims: Iterable of `TensorShapes`. + block_dims_fn: Callable returning an iterable of `Tensor`s. + arg: `Tensor`. `arg` is split into `J` tensors. + axis: Python `Integer` representing the axis to split `arg` on. + + Returns: + A list of `Tensor`s. + """ + block_sizes = [dim.value for dim in block_dims] + if any(d is None for d in block_sizes): + block_sizes = block_dims_fn() + return array_ops.split(arg, block_sizes, axis=axis) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_zeros.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..8adee6efe904b6ccac60d8edf9e72729c5061e65 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/linear_operator_zeros.py @@ -0,0 +1,500 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`LinearOperator` acting like a zero matrix.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.ops.linalg import linear_operator +from tensorflow.python.ops.linalg import linear_operator_util +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "LinearOperatorZeros", +] + + +@tf_export("linalg.LinearOperatorZeros") +@linear_operator.make_composite_tensor +class LinearOperatorZeros(linear_operator.LinearOperator): + """`LinearOperator` acting like a [batch] zero matrix. + + This operator acts like a [batch] zero matrix `A` with shape + `[B1,...,Bb, N, M]` for some `b >= 0`. The first `b` indices index a + batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is + an `N x M` matrix. This matrix `A` is not materialized, but for + purposes of broadcasting this shape will be relevant. + + `LinearOperatorZeros` is initialized with `num_rows`, and optionally + `num_columns, `batch_shape`, and `dtype` arguments. If `num_columns` is + `None`, then this operator will be initialized as a square matrix. If + `batch_shape` is `None`, this operator efficiently passes through all + arguments. If `batch_shape` is provided, broadcasting may occur, which will + require making copies. + + ```python + # Create a 2 x 2 zero matrix. + operator = LinearOperatorZero(num_rows=2, dtype=tf.float32) + + operator.to_dense() + ==> [[0., 0.] + [0., 0.]] + + operator.shape + ==> [2, 2] + + operator.determinant() + ==> 0. + + x = ... Shape [2, 4] Tensor + operator.matmul(x) + ==> Shape [2, 4] Tensor, same as x. + + # Create a 2-batch of 2x2 zero matrices + operator = LinearOperatorZeros(num_rows=2, batch_shape=[2]) + operator.to_dense() + ==> [[[0., 0.] + [0., 0.]], + [[0., 0.] + [0., 0.]]] + + # Here, even though the operator has a batch shape, the input is the same as + # the output, so x can be passed through without a copy. The operator is able + # to detect that no broadcast is necessary because both x and the operator + # have statically defined shape. + x = ... Shape [2, 2, 3] + operator.matmul(x) + ==> Shape [2, 2, 3] Tensor, same as tf.zeros_like(x) + + # Here the operator and x have different batch_shape, and are broadcast. + # This requires a copy, since the output is different size than the input. + x = ... Shape [1, 2, 3] + operator.matmul(x) + ==> Shape [2, 2, 3] Tensor, equal to tf.zeros_like([x, x]) + ``` + + ### Shape compatibility + + This operator acts on [batch] matrix with compatible shape. + `x` is a batch matrix with compatible shape for `matmul` and `solve` if + + ``` + operator.shape = [B1,...,Bb] + [N, M], with b >= 0 + x.shape = [C1,...,Cc] + [M, R], + and [C1,...,Cc] broadcasts with [B1,...,Bb] to [D1,...,Dd] + ``` + + #### Matrix property hints + + This `LinearOperator` is initialized with boolean flags of the form `is_X`, + for `X = non_singular, self_adjoint, positive_definite, square`. + These have the following meaning: + + * If `is_X == True`, callers should expect the operator to have the + property `X`. This is a promise that should be fulfilled, but is *not* a + runtime assert. For example, finite floating point precision may result + in these promises being violated. + * If `is_X == False`, callers should expect the operator to not have `X`. + * If `is_X == None` (the default), callers should have no expectation either + way. + """ + + def __init__(self, + num_rows, + num_columns=None, + batch_shape=None, + dtype=None, + is_non_singular=False, + is_self_adjoint=True, + is_positive_definite=False, + is_square=True, + assert_proper_shapes=False, + name="LinearOperatorZeros"): + r"""Initialize a `LinearOperatorZeros`. + + The `LinearOperatorZeros` is initialized with arguments defining `dtype` + and shape. + + This operator is able to broadcast the leading (batch) dimensions, which + sometimes requires copying data. If `batch_shape` is `None`, the operator + can take arguments of any batch shape without copying. See examples. + + Args: + num_rows: Scalar non-negative integer `Tensor`. Number of rows in the + corresponding zero matrix. + num_columns: Scalar non-negative integer `Tensor`. Number of columns in + the corresponding zero matrix. If `None`, defaults to the value of + `num_rows`. + batch_shape: Optional `1-D` integer `Tensor`. The shape of the leading + dimensions. If `None`, this operator has no leading dimensions. + dtype: Data type of the matrix that this operator represents. + is_non_singular: Expect that this operator is non-singular. + is_self_adjoint: Expect that this operator is equal to its hermitian + transpose. + is_positive_definite: Expect that this operator is positive definite, + meaning the quadratic form `x^H A x` has positive real part for all + nonzero `x`. Note that we do not require the operator to be + self-adjoint to be positive-definite. See: + https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices + is_square: Expect that this operator acts like square [batch] matrices. + assert_proper_shapes: Python `bool`. If `False`, only perform static + checks that initialization and method arguments have proper shape. + If `True`, and static checks are inconclusive, add asserts to the graph. + name: A name for this `LinearOperator` + + Raises: + ValueError: If `num_rows` is determined statically to be non-scalar, or + negative. + ValueError: If `num_columns` is determined statically to be non-scalar, + or negative. + ValueError: If `batch_shape` is determined statically to not be 1-D, or + negative. + ValueError: If any of the following is not `True`: + `{is_self_adjoint, is_non_singular, is_positive_definite}`. + """ + parameters = dict( + num_rows=num_rows, + num_columns=num_columns, + batch_shape=batch_shape, + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + assert_proper_shapes=assert_proper_shapes, + name=name + ) + + dtype = dtype or dtypes.float32 + self._assert_proper_shapes = assert_proper_shapes + + with ops.name_scope(name): + dtype = dtypes.as_dtype(dtype) + if not is_self_adjoint and is_square: + raise ValueError("A zero operator is always self adjoint.") + if is_non_singular: + raise ValueError("A zero operator is always singular.") + if is_positive_definite: + raise ValueError("A zero operator is always not positive-definite.") + + super(LinearOperatorZeros, self).__init__( + dtype=dtype, + is_non_singular=is_non_singular, + is_self_adjoint=is_self_adjoint, + is_positive_definite=is_positive_definite, + is_square=is_square, + parameters=parameters, + name=name) + + linear_operator_util.assert_not_ref_type(num_rows, "num_rows") + linear_operator_util.assert_not_ref_type(num_columns, "num_columns") + linear_operator_util.assert_not_ref_type(batch_shape, "batch_shape") + + self._num_rows = linear_operator_util.shape_tensor( + num_rows, name="num_rows") + self._num_rows_static = tensor_util.constant_value(self._num_rows) + + if num_columns is None: + num_columns = num_rows + + self._num_columns = linear_operator_util.shape_tensor( + num_columns, name="num_columns") + self._num_columns_static = tensor_util.constant_value(self._num_columns) + + self._check_domain_range_possibly_add_asserts() + + if (self._num_rows_static is not None and + self._num_columns_static is not None): + if is_square and self._num_rows_static != self._num_columns_static: + raise ValueError( + "LinearOperatorZeros initialized as is_square=True, but got " + "num_rows({}) != num_columns({})".format( + self._num_rows_static, + self._num_columns_static)) + + if batch_shape is None: + self._batch_shape_arg = None + else: + self._batch_shape_arg = linear_operator_util.shape_tensor( + batch_shape, name="batch_shape_arg") + self._batch_shape_static = tensor_util.constant_value( + self._batch_shape_arg) + self._check_batch_shape_possibly_add_asserts() + + def _shape(self): + matrix_shape = tensor_shape.TensorShape((self._num_rows_static, + self._num_columns_static)) + if self._batch_shape_arg is None: + return matrix_shape + + batch_shape = tensor_shape.TensorShape(self._batch_shape_static) + return batch_shape.concatenate(matrix_shape) + + def _shape_tensor(self): + matrix_shape = array_ops_stack.stack( + (self._num_rows, self._num_columns), axis=0) + if self._batch_shape_arg is None: + return matrix_shape + + return array_ops.concat((self._batch_shape_arg, matrix_shape), 0) + + def _assert_non_singular(self): + raise errors.InvalidArgumentError( + node_def=None, op=None, message="Zero operators are always " + "non-invertible.") + + def _assert_positive_definite(self): + raise errors.InvalidArgumentError( + node_def=None, op=None, message="Zero operators are always " + "non-positive definite.") + + def _assert_self_adjoint(self): + return control_flow_ops.no_op("assert_self_adjoint") + + def _possibly_broadcast_batch_shape(self, x): + """Return 'x', possibly after broadcasting the leading dimensions.""" + # If we have no batch shape, our batch shape broadcasts with everything! + if self._batch_shape_arg is None: + return x + + # Static attempt: + # If we determine that no broadcast is necessary, pass x through + # If we need a broadcast, add to an array of zeros. + # + # special_shape is the shape that, when broadcast with x's shape, will give + # the correct broadcast_shape. Note that + # We have already verified the second to last dimension of self.shape + # matches x's shape in assert_compatible_matrix_dimensions. + # Also, the final dimension of 'x' can have any shape. + # Therefore, the final two dimensions of special_shape are 1's. + special_shape = self.batch_shape.concatenate([1, 1]) + bshape = array_ops.broadcast_static_shape(x.shape, special_shape) + if special_shape.is_fully_defined(): + # bshape.is_fully_defined iff special_shape.is_fully_defined. + if bshape == x.shape: + return x + # Use the built in broadcasting of addition. + zeros = array_ops.zeros(shape=special_shape, dtype=self.dtype) + return x + zeros + + # Dynamic broadcast: + # Always add to an array of zeros, rather than using a "cond", since a + # cond would require copying data from GPU --> CPU. + special_shape = array_ops.concat((self.batch_shape_tensor(), [1, 1]), 0) + zeros = array_ops.zeros(shape=special_shape, dtype=self.dtype) + return x + zeros + + def _matmul(self, x, adjoint=False, adjoint_arg=False): + if self._assert_proper_shapes: + x = linalg.adjoint(x) if adjoint_arg else x + aps = linear_operator_util.assert_compatible_matrix_dimensions(self, x) + x = control_flow_ops.with_dependencies([aps], x) + if self.is_square: + # Note that adjoint has no effect since this matrix is self-adjoint. + if adjoint_arg: + output_shape = array_ops.concat([ + array_ops.shape(x)[:-2], + [array_ops.shape(x)[-1], array_ops.shape(x)[-2]]], axis=0) + else: + output_shape = array_ops.shape(x) + + return self._possibly_broadcast_batch_shape( + array_ops.zeros(shape=output_shape, dtype=x.dtype)) + + x_shape = array_ops.shape(x) + n = self._num_columns if adjoint else self._num_rows + m = x_shape[-2] if adjoint_arg else x_shape[-1] + + output_shape = array_ops.concat([x_shape[:-2], [n, m]], axis=0) + + zeros = array_ops.zeros(shape=output_shape, dtype=x.dtype) + return self._possibly_broadcast_batch_shape(zeros) + + def _linop_matmul( + self, + left_operator: "LinearOperatorZeros", + right_operator: linear_operator.LinearOperator + ) -> linear_operator.LinearOperator: + if not left_operator.is_square or not right_operator.is_square: + raise ValueError("Matmul with non-square `LinearOperator`s or non-square " + "`LinearOperatorZeros` not supported at this time.") + return left_operator + + def _determinant(self): + if self.batch_shape.is_fully_defined(): + return array_ops.zeros(shape=self.batch_shape, dtype=self.dtype) + else: + return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _trace(self): + # Get Tensor of all zeros of same shape as self.batch_shape. + if self.batch_shape.is_fully_defined(): + return array_ops.zeros(shape=self.batch_shape, dtype=self.dtype) + else: + return array_ops.zeros(shape=self.batch_shape_tensor(), dtype=self.dtype) + + def _diag_part(self): + return self._zeros_diag() + + def add_to_tensor(self, mat, name="add_to_tensor"): + """Add matrix represented by this operator to `mat`. Equiv to `I + mat`. + + Args: + mat: `Tensor` with same `dtype` and shape broadcastable to `self`. + name: A name to give this `Op`. + + Returns: + A `Tensor` with broadcast shape and same `dtype` as `self`. + """ + return self._possibly_broadcast_batch_shape(mat) + + def _check_domain_range_possibly_add_asserts(self): + """Static check of init arg `num_rows`, possibly add asserts.""" + # Possibly add asserts. + if self._assert_proper_shapes: + self._num_rows = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._num_rows, + 0, + message="Argument num_rows must be a 0-D Tensor."), + check_ops.assert_non_negative( + self._num_rows, + message="Argument num_rows must be non-negative."), + ], self._num_rows) + self._num_columns = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._num_columns, + 0, + message="Argument num_columns must be a 0-D Tensor."), + check_ops.assert_non_negative( + self._num_columns, + message="Argument num_columns must be non-negative."), + ], self._num_columns) + + # Static checks. + if not self._num_rows.dtype.is_integer: + raise TypeError("Argument num_rows must be integer type. Found:" + " %s" % self._num_rows) + + if not self._num_columns.dtype.is_integer: + raise TypeError("Argument num_columns must be integer type. Found:" + " %s" % self._num_columns) + + num_rows_static = self._num_rows_static + num_columns_static = self._num_columns_static + + if num_rows_static is not None: + if num_rows_static.ndim != 0: + raise ValueError("Argument num_rows must be a 0-D Tensor. Found:" + " %s" % num_rows_static) + + if num_rows_static < 0: + raise ValueError("Argument num_rows must be non-negative. Found:" + " %s" % num_rows_static) + if num_columns_static is not None: + if num_columns_static.ndim != 0: + raise ValueError("Argument num_columns must be a 0-D Tensor. Found:" + " %s" % num_columns_static) + + if num_columns_static < 0: + raise ValueError("Argument num_columns must be non-negative. Found:" + " %s" % num_columns_static) + + def _check_batch_shape_possibly_add_asserts(self): + """Static check of init arg `batch_shape`, possibly add asserts.""" + if self._batch_shape_arg is None: + return + + # Possibly add asserts + if self._assert_proper_shapes: + self._batch_shape_arg = control_flow_ops.with_dependencies([ + check_ops.assert_rank( + self._batch_shape_arg, + 1, + message="Argument batch_shape must be a 1-D Tensor."), + check_ops.assert_non_negative( + self._batch_shape_arg, + message="Argument batch_shape must be non-negative."), + ], self._batch_shape_arg) + + # Static checks + if not self._batch_shape_arg.dtype.is_integer: + raise TypeError("Argument batch_shape must be integer type. Found:" + " %s" % self._batch_shape_arg) + + if self._batch_shape_static is None: + return # Cannot do any other static checks. + + if self._batch_shape_static.ndim != 1: + raise ValueError("Argument batch_shape must be a 1-D Tensor. Found:" + " %s" % self._batch_shape_static) + + if np.any(self._batch_shape_static < 0): + raise ValueError("Argument batch_shape must be non-negative. Found:" + "%s" % self._batch_shape_static) + + def _min_matrix_dim(self): + """Minimum of domain/range dimension, if statically available, else None.""" + domain_dim = self.domain_dimension.value + range_dim = self.range_dimension.value + if domain_dim is None or range_dim is None: + return None + return min(domain_dim, range_dim) + + def _min_matrix_dim_tensor(self): + """Minimum of domain/range dimension, as a tensor.""" + return math_ops.reduce_min(self.shape_tensor()[-2:]) + + def _zeros_diag(self): + """Returns the diagonal of this operator as all zeros.""" + if self.shape.is_fully_defined(): + d_shape = self.batch_shape.concatenate([self._min_matrix_dim()]) + else: + d_shape = array_ops.concat( + [self.batch_shape_tensor(), + [self._min_matrix_dim_tensor()]], axis=0) + + return array_ops.zeros(shape=d_shape, dtype=self.dtype) + + def _eigvals(self): + return self._zeros_diag() + + @property + def _composite_tensor_prefer_static_fields(self): + return ("num_rows", "num_columns", "batch_shape") + + @property + def _composite_tensor_fields(self): + return ("num_rows", "num_columns", "batch_shape", "dtype", + "assert_proper_shapes") + + def __getitem__(self, slices): + # Slice the batch shape and return a new LinearOperatorIdentity. + # Use a proxy shape and slice it. Use this as the new batch shape + new_batch_shape = array_ops.shape( + array_ops.ones(self._batch_shape_arg)[slices]) + parameters = dict(self.parameters, batch_shape=new_batch_shape) + return LinearOperatorZeros(**parameters) + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/property_hint_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/property_hint_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7967348fb48c0c951d4f7c54f5d76af64312c339 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/property_hint_util.py @@ -0,0 +1,87 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Common utilities for LinearOperator property hints.""" + + +# Note: only use this method in the commuting case. +def combined_commuting_self_adjoint_hint(operator_a, operator_b): + """Get combined hint for self-adjoint-ness.""" + + # The property is preserved under composition when the operators commute. + if operator_a.is_self_adjoint and operator_b.is_self_adjoint: + return True + + # The property is not preserved when an operator with the property is composed + # with an operator without the property. + + # pylint:disable=g-bool-id-comparison + if ((operator_a.is_self_adjoint is True and + operator_b.is_self_adjoint is False) or + (operator_a.is_self_adjoint is False and + operator_b.is_self_adjoint is True)): + return False + # pylint:enable=g-bool-id-comparison + + # The property is not known when operators are not known to have the property + # or both operators don't have the property (the property for the complement + # class is not closed under composition). + return None + + +def is_square(operator_a, operator_b): + """Return a hint to whether the composition is square.""" + if operator_a.is_square and operator_b.is_square: + return True + if operator_a.is_square is False and operator_b.is_square is False: # pylint:disable=g-bool-id-comparison + # Let A have shape [B, M, N], B have shape [B, N, L]. + m = operator_a.range_dimension + l = operator_b.domain_dimension + if m is not None and l is not None: + return m == l + + if (operator_a.is_square != operator_b.is_square) and ( + operator_a.is_square is not None and operator_b.is_square is not None): + return False + + return None + + +# Note: Positive definiteness is only guaranteed to be preserved +# when the operators commute and are symmetric. Only use this method in +# commuting cases. +def combined_commuting_positive_definite_hint(operator_a, operator_b): + """Get combined PD hint for compositions.""" + # pylint:disable=g-bool-id-comparison + if (operator_a.is_positive_definite is True and + operator_a.is_self_adjoint is True and + operator_b.is_positive_definite is True and + operator_b.is_self_adjoint is True): + return True + # pylint:enable=g-bool-id-comparison + + return None + + +def combined_non_singular_hint(operator_a, operator_b): + """Get combined hint for when .""" + # If either operator is not-invertible the composition isn't. + + # pylint:disable=g-bool-id-comparison + if (operator_a.is_non_singular is False or + operator_b.is_non_singular is False): + return False + # pylint:enable=g-bool-id-comparison + + return operator_a.is_non_singular and operator_b.is_non_singular diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/slicing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..d099b420b1a18330afcd52dff3df0d9867c4b684 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/slicing.py @@ -0,0 +1,184 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for slicing in to a `LinearOperator`.""" + +import collections +import functools +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest + + +__all__ = ['batch_slice'] + + +def _prefer_static_where(condition, x, y): + args = [condition, x, y] + constant_args = [tensor_util.constant_value(a) for a in args] + # Do this statically. + if all(arg is not None for arg in constant_args): + condition_, x_, y_ = constant_args + return np.where(condition_, x_, y_) + return array_ops.where(condition, x, y) + + +def _broadcast_parameter_with_batch_shape( + param, param_ndims_to_matrix_ndims, batch_shape): + """Broadcasts `param` with the given batch shape, recursively.""" + if hasattr(param, 'batch_shape_tensor'): + # Recursively broadcast every parameter inside the operator. + override_dict = {} + for name, ndims in param._experimental_parameter_ndims_to_matrix_ndims.items(): # pylint:disable=protected-access,line-too-long + sub_param = getattr(param, name) + override_dict[name] = nest.map_structure_up_to( + sub_param, functools.partial( + _broadcast_parameter_with_batch_shape, + batch_shape=batch_shape), sub_param, ndims) + parameters = dict(param.parameters, **override_dict) + return type(param)(**parameters) + + base_shape = array_ops.concat( + [batch_shape, array_ops.ones( + [param_ndims_to_matrix_ndims], dtype=dtypes.int32)], axis=0) + return array_ops.broadcast_to( + param, + array_ops.broadcast_dynamic_shape(base_shape, array_ops.shape(param))) + + +def _sanitize_slices(slices, intended_shape, deficient_shape): + """Restricts slices to avoid overflowing size-1 (broadcast) dimensions. + + Args: + slices: iterable of slices received by `__getitem__`. + intended_shape: int `Tensor` shape for which the slices were intended. + deficient_shape: int `Tensor` shape to which the slices will be applied. + Must have the same rank as `intended_shape`. + Returns: + sanitized_slices: Python `list` of slice objects. + """ + sanitized_slices = [] + idx = 0 + for slc in slices: + if slc is Ellipsis: # Switch over to negative indexing. + if idx < 0: + raise ValueError('Found multiple `...` in slices {}'.format(slices)) + num_remaining_non_newaxis_slices = sum( + s is not array_ops.newaxis for s in slices[ + slices.index(Ellipsis) + 1:]) + idx = -num_remaining_non_newaxis_slices + elif slc is array_ops.newaxis: + pass + else: + is_broadcast = intended_shape[idx] > deficient_shape[idx] + if isinstance(slc, slice): + # Slices are denoted by start:stop:step. + start, stop, step = slc.start, slc.stop, slc.step + if start is not None: + start = _prefer_static_where(is_broadcast, 0, start) + if stop is not None: + stop = _prefer_static_where(is_broadcast, 1, stop) + if step is not None: + step = _prefer_static_where(is_broadcast, 1, step) + slc = slice(start, stop, step) + else: # int, or int Tensor, e.g. d[d.batch_shape_tensor()[0] // 2] + slc = _prefer_static_where(is_broadcast, 0, slc) + idx += 1 + sanitized_slices.append(slc) + return sanitized_slices + + +def _slice_single_param( + param, param_ndims_to_matrix_ndims, slices, batch_shape): + """Slices into the batch shape of a single parameter. + + Args: + param: The original parameter to slice; either a `Tensor` or an object + with batch shape (LinearOperator). + param_ndims_to_matrix_ndims: `int` number of right-most dimensions used for + inferring matrix shape of the `LinearOperator`. For non-Tensor + parameters, this is the number of this param's batch dimensions used by + the matrix shape of the parent object. + slices: iterable of slices received by `__getitem__`. + batch_shape: The parameterized object's batch shape `Tensor`. + + Returns: + new_param: Instance of the same type as `param`, batch-sliced according to + `slices`. + """ + # Broadcast the parammeter to have full batch rank. + param = _broadcast_parameter_with_batch_shape( + param, param_ndims_to_matrix_ndims, array_ops.ones_like(batch_shape)) + + if hasattr(param, 'batch_shape_tensor'): + param_batch_shape = param.batch_shape_tensor() + else: + param_batch_shape = array_ops.shape(param) + # Truncate by param_ndims_to_matrix_ndims + param_batch_rank = array_ops.size(param_batch_shape) + param_batch_shape = param_batch_shape[ + :(param_batch_rank - param_ndims_to_matrix_ndims)] + + # At this point the param should have full batch rank, *unless* it's an + # atomic object like `tfb.Identity()` incapable of having any batch rank. + if (tensor_util.constant_value(array_ops.size(batch_shape)) != 0 and + tensor_util.constant_value(array_ops.size(param_batch_shape)) == 0): + return param + param_slices = _sanitize_slices( + slices, intended_shape=batch_shape, deficient_shape=param_batch_shape) + + # Extend `param_slices` (which represents slicing into the + # parameter's batch shape) with the parameter's event ndims. For example, if + # `params_ndims == 1`, then `[i, ..., j]` would become `[i, ..., j, :]`. + if param_ndims_to_matrix_ndims > 0: + if Ellipsis not in [ + slc for slc in slices if not tensor_util.is_tensor(slc)]: + param_slices.append(Ellipsis) + param_slices += [slice(None)] * param_ndims_to_matrix_ndims + return param.__getitem__(tuple(param_slices)) + + +def batch_slice(linop, params_overrides, slices): + """Slices `linop` along its batch dimensions. + + Args: + linop: A `LinearOperator` instance. + params_overrides: A `dict` of parameter overrides. + slices: A `slice` or `int` or `int` `Tensor` or `tf.newaxis` or `tuple` + thereof. (e.g. the argument of a `__getitem__` method). + + Returns: + new_linop: A batch-sliced `LinearOperator`. + """ + if not isinstance(slices, collections.abc.Sequence): + slices = (slices,) + if len(slices) == 1 and slices[0] is Ellipsis: + override_dict = {} + else: + batch_shape = linop.batch_shape_tensor() + override_dict = {} + for param_name, param_ndims_to_matrix_ndims in linop._experimental_parameter_ndims_to_matrix_ndims.items(): # pylint:disable=protected-access,line-too-long + param = getattr(linop, param_name) + # These represent optional `Tensor` parameters. + if param is not None: + override_dict[param_name] = nest.map_structure_up_to( + param, functools.partial( + _slice_single_param, slices=slices, batch_shape=batch_shape), + param, param_ndims_to_matrix_ndims) + override_dict.update(params_overrides) + parameters = dict(linop.parameters, **override_dict) + return type(linop)(**parameters) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/conjugate_gradient.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/conjugate_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..08f764797dd146e0404b0440a4d744614b60af9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/conjugate_gradient.py @@ -0,0 +1,138 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Preconditioned Conjugate Gradient.""" + +import collections + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.linalg import linalg_impl as linalg +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('linalg.experimental.conjugate_gradient') +@dispatch.add_dispatch_support +def conjugate_gradient(operator, + rhs, + preconditioner=None, + x=None, + tol=1e-5, + max_iter=20, + name='conjugate_gradient'): + r"""Conjugate gradient solver. + + Solves a linear system of equations `A*x = rhs` for self-adjoint, positive + definite matrix `A` and right-hand side vector `rhs`, using an iterative, + matrix-free algorithm where the action of the matrix A is represented by + `operator`. The iteration terminates when either the number of iterations + exceeds `max_iter` or when the residual norm has been reduced to `tol` + times its initial value, i.e. \\(||rhs - A x_k|| <= tol ||rhs||\\). + + Args: + operator: A `LinearOperator` that is self-adjoint and positive definite. + rhs: A possibly batched vector of shape `[..., N]` containing the right-hand + size vector. + preconditioner: A `LinearOperator` that approximates the inverse of `A`. + An efficient preconditioner could dramatically improve the rate of + convergence. If `preconditioner` represents matrix `M`(`M` approximates + `A^{-1}`), the algorithm uses `preconditioner.apply(x)` to estimate + `A^{-1}x`. For this to be useful, the cost of applying `M` should be + much lower than computing `A^{-1}` directly. + x: A possibly batched vector of shape `[..., N]` containing the initial + guess for the solution. + tol: A float scalar convergence tolerance. + max_iter: An integer giving the maximum number of iterations. + name: A name scope for the operation. + + Returns: + output: A namedtuple representing the final state with fields: + - i: A scalar `int32` `Tensor`. Number of iterations executed. + - x: A rank-1 `Tensor` of shape `[..., N]` containing the computed + solution. + - r: A rank-1 `Tensor` of shape `[.., M]` containing the residual vector. + - p: A rank-1 `Tensor` of shape `[..., N]`. `A`-conjugate basis vector. + - gamma: \\(r \dot M \dot r\\), equivalent to \\(||r||_2^2\\) when + `preconditioner=None`. + """ + if not (operator.is_self_adjoint and operator.is_positive_definite): + raise ValueError('Expected a self-adjoint, positive definite operator.') + + cg_state = collections.namedtuple('CGState', ['i', 'x', 'r', 'p', 'gamma']) + + def stopping_criterion(i, state): + return math_ops.logical_and( + i < max_iter, + math_ops.reduce_any(linalg.norm(state.r, axis=-1) > tol)) + + def dot(x, y): + return array_ops.squeeze( + math_ops.matvec( + x[..., array_ops.newaxis], + y, adjoint_a=True), axis=-1) + + def cg_step(i, state): # pylint: disable=missing-docstring + z = math_ops.matvec(operator, state.p) + alpha = state.gamma / dot(state.p, z) + x = state.x + alpha[..., array_ops.newaxis] * state.p + r = state.r - alpha[..., array_ops.newaxis] * z + if preconditioner is None: + q = r + else: + q = preconditioner.matvec(r) + gamma = dot(r, q) + beta = gamma / state.gamma + p = q + beta[..., array_ops.newaxis] * state.p + return i + 1, cg_state(i + 1, x, r, p, gamma) + + # We now broadcast initial shapes so that we have fixed shapes per iteration. + + with ops.name_scope(name): + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(rhs)[:-1], + operator.batch_shape_tensor()) + if preconditioner is not None: + broadcast_shape = array_ops.broadcast_dynamic_shape( + broadcast_shape, + preconditioner.batch_shape_tensor() + ) + broadcast_rhs_shape = array_ops.concat([ + broadcast_shape, [array_ops.shape(rhs)[-1]]], axis=-1) + r0 = array_ops.broadcast_to(rhs, broadcast_rhs_shape) + tol *= linalg.norm(r0, axis=-1) + + if x is None: + x = array_ops.zeros( + broadcast_rhs_shape, dtype=rhs.dtype.base_dtype) + else: + r0 = rhs - math_ops.matvec(operator, x) + if preconditioner is None: + p0 = r0 + else: + p0 = math_ops.matvec(preconditioner, r0) + gamma0 = dot(r0, p0) + i = constant_op.constant(0, dtype=dtypes.int32) + state = cg_state(i=i, x=x, r=r0, p=p0, gamma=gamma0) + _, state = while_loop.while_loop(stopping_criterion, cg_step, [i, state]) + return cg_state( + state.i, + x=state.x, + r=state.r, + p=state.p, + gamma=state.gamma) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/gen_sparse_csr_matrix_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/gen_sparse_csr_matrix_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b109248bd3c981c4ade276e9b753f3bd8c404cce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/gen_sparse_csr_matrix_ops.py @@ -0,0 +1,1388 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated +_CSRSparseMatrixComponentsOutput = collections.namedtuple( + "CSRSparseMatrixComponents", + ["row_ptrs", "col_inds", "values"]) + + +TV_CSRSparseMatrixComponents_type = TypeVar("TV_CSRSparseMatrixComponents_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def csr_sparse_matrix_components(csr_sparse_matrix: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], type: TV_CSRSparseMatrixComponents_type, name=None): + r"""Reads out the CSR components at batch `index`. + + This op is meant only for debugging / testing, and its interface is not expected + to be stable. + + Args: + csr_sparse_matrix: A `Tensor` of type `variant`. + A batched CSRSparseMatrix. + index: A `Tensor` of type `int32`. + The index in `csr_sparse_matrix`'s batch. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (row_ptrs, col_inds, values). + + row_ptrs: A `Tensor` of type `int32`. + col_inds: A `Tensor` of type `int32`. + values: A `Tensor` of type `type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CSRSparseMatrixComponents", name, csr_sparse_matrix, index, + "type", type) + _result = _CSRSparseMatrixComponentsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return csr_sparse_matrix_components_eager_fallback( + csr_sparse_matrix, index, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CSRSparseMatrixComponents", csr_sparse_matrix=csr_sparse_matrix, + index=index, type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CSRSparseMatrixComponents", _inputs_flat, _attrs, _result) + _result = _CSRSparseMatrixComponentsOutput._make(_result) + return _result + +CSRSparseMatrixComponents = tf_export("raw_ops.CSRSparseMatrixComponents")(_ops.to_raw_op(csr_sparse_matrix_components)) + + +def csr_sparse_matrix_components_eager_fallback(csr_sparse_matrix: Annotated[Any, _atypes.Variant], index: Annotated[Any, _atypes.Int32], type: TV_CSRSparseMatrixComponents_type, name, ctx): + type = _execute.make_type(type, "type") + csr_sparse_matrix = _ops.convert_to_tensor(csr_sparse_matrix, _dtypes.variant) + index = _ops.convert_to_tensor(index, _dtypes.int32) + _inputs_flat = [csr_sparse_matrix, index] + _attrs = ("type", type) + _result = _execute.execute(b"CSRSparseMatrixComponents", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CSRSparseMatrixComponents", _inputs_flat, _attrs, _result) + _result = _CSRSparseMatrixComponentsOutput._make(_result) + return _result + + +TV_CSRSparseMatrixToDense_type = TypeVar("TV_CSRSparseMatrixToDense_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def csr_sparse_matrix_to_dense(sparse_input: Annotated[Any, _atypes.Variant], type: TV_CSRSparseMatrixToDense_type, name=None) -> Annotated[Any, TV_CSRSparseMatrixToDense_type]: + r"""Convert a (possibly batched) CSRSparseMatrix to dense. + + Args: + sparse_input: A `Tensor` of type `variant`. A batched CSRSparseMatrix. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CSRSparseMatrixToDense", name, sparse_input, "type", type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return csr_sparse_matrix_to_dense_eager_fallback( + sparse_input, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CSRSparseMatrixToDense", sparse_input=sparse_input, type=type, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CSRSparseMatrixToDense", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CSRSparseMatrixToDense = tf_export("raw_ops.CSRSparseMatrixToDense")(_ops.to_raw_op(csr_sparse_matrix_to_dense)) + + +def csr_sparse_matrix_to_dense_eager_fallback(sparse_input: Annotated[Any, _atypes.Variant], type: TV_CSRSparseMatrixToDense_type, name, ctx) -> Annotated[Any, TV_CSRSparseMatrixToDense_type]: + type = _execute.make_type(type, "type") + sparse_input = _ops.convert_to_tensor(sparse_input, _dtypes.variant) + _inputs_flat = [sparse_input] + _attrs = ("type", type) + _result = _execute.execute(b"CSRSparseMatrixToDense", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CSRSparseMatrixToDense", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_CSRSparseMatrixToSparseTensorOutput = collections.namedtuple( + "CSRSparseMatrixToSparseTensor", + ["indices", "values", "dense_shape"]) + + +TV_CSRSparseMatrixToSparseTensor_type = TypeVar("TV_CSRSparseMatrixToSparseTensor_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def csr_sparse_matrix_to_sparse_tensor(sparse_matrix: Annotated[Any, _atypes.Variant], type: TV_CSRSparseMatrixToSparseTensor_type, name=None): + r"""Converts a (possibly batched) CSRSparesMatrix to a SparseTensor. + + Args: + sparse_matrix: A `Tensor` of type `variant`. + A (possibly batched) CSRSparseMatrix. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (indices, values, dense_shape). + + indices: A `Tensor` of type `int64`. + values: A `Tensor` of type `type`. + dense_shape: A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CSRSparseMatrixToSparseTensor", name, sparse_matrix, "type", + type) + _result = _CSRSparseMatrixToSparseTensorOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return csr_sparse_matrix_to_sparse_tensor_eager_fallback( + sparse_matrix, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CSRSparseMatrixToSparseTensor", sparse_matrix=sparse_matrix, + type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CSRSparseMatrixToSparseTensor", _inputs_flat, _attrs, _result) + _result = _CSRSparseMatrixToSparseTensorOutput._make(_result) + return _result + +CSRSparseMatrixToSparseTensor = tf_export("raw_ops.CSRSparseMatrixToSparseTensor")(_ops.to_raw_op(csr_sparse_matrix_to_sparse_tensor)) + + +def csr_sparse_matrix_to_sparse_tensor_eager_fallback(sparse_matrix: Annotated[Any, _atypes.Variant], type: TV_CSRSparseMatrixToSparseTensor_type, name, ctx): + type = _execute.make_type(type, "type") + sparse_matrix = _ops.convert_to_tensor(sparse_matrix, _dtypes.variant) + _inputs_flat = [sparse_matrix] + _attrs = ("type", type) + _result = _execute.execute(b"CSRSparseMatrixToSparseTensor", 3, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CSRSparseMatrixToSparseTensor", _inputs_flat, _attrs, _result) + _result = _CSRSparseMatrixToSparseTensorOutput._make(_result) + return _result + + +TV_DenseToCSRSparseMatrix_T = TypeVar("TV_DenseToCSRSparseMatrix_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def dense_to_csr_sparse_matrix(dense_input: Annotated[Any, TV_DenseToCSRSparseMatrix_T], indices: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Converts a dense tensor to a (possibly batched) CSRSparseMatrix. + + Args: + dense_input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `complex64`, `complex128`. + A Dense tensor. + indices: A `Tensor` of type `int64`. Indices of nonzero elements. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DenseToCSRSparseMatrix", name, dense_input, indices) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return dense_to_csr_sparse_matrix_eager_fallback( + dense_input, indices, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DenseToCSRSparseMatrix", dense_input=dense_input, indices=indices, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DenseToCSRSparseMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DenseToCSRSparseMatrix = tf_export("raw_ops.DenseToCSRSparseMatrix")(_ops.to_raw_op(dense_to_csr_sparse_matrix)) + + +def dense_to_csr_sparse_matrix_eager_fallback(dense_input: Annotated[Any, TV_DenseToCSRSparseMatrix_T], indices: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_T, (dense_input,) = _execute.args_to_matching_eager([dense_input], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + _inputs_flat = [dense_input, indices] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DenseToCSRSparseMatrix", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DenseToCSRSparseMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixAdd_T = TypeVar("TV_SparseMatrixAdd_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_matrix_add(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, _atypes.Variant], alpha: Annotated[Any, TV_SparseMatrixAdd_T], beta: Annotated[Any, TV_SparseMatrixAdd_T], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Sparse addition of two CSR matrices, C = alpha * A + beta * B. + + The gradients of SparseMatrixAdd outputs with respect to alpha and beta are not + currently defined (TensorFlow will return zeros for these entries). + + Args: + a: A `Tensor` of type `variant`. A CSRSparseMatrix. + b: A `Tensor` of type `variant`. A CSRSparseMatrix. + alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`, `complex64`, `complex128`. + A constant scalar. + beta: A `Tensor`. Must have the same type as `alpha`. A constant scalar. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixAdd", name, a, b, alpha, beta) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_add_eager_fallback( + a, b, alpha, beta, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixAdd", a=a, b=b, alpha=alpha, beta=beta, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixAdd = tf_export("raw_ops.SparseMatrixAdd")(_ops.to_raw_op(sparse_matrix_add)) + + +def sparse_matrix_add_eager_fallback(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, _atypes.Variant], alpha: Annotated[Any, TV_SparseMatrixAdd_T], beta: Annotated[Any, TV_SparseMatrixAdd_T], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([alpha, beta], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + (alpha, beta) = _inputs_T + a = _ops.convert_to_tensor(a, _dtypes.variant) + b = _ops.convert_to_tensor(b, _dtypes.variant) + _inputs_flat = [a, b, alpha, beta] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseMatrixAdd", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixAdd", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixMatMul_T = TypeVar("TV_SparseMatrixMatMul_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_matrix_mat_mul(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, TV_SparseMatrixMatMul_T], transpose_a:bool=False, transpose_b:bool=False, adjoint_a:bool=False, adjoint_b:bool=False, transpose_output:bool=False, conjugate_output:bool=False, name=None) -> Annotated[Any, TV_SparseMatrixMatMul_T]: + r"""Matrix-multiplies a sparse matrix with a dense matrix. + + Returns a dense matrix. + For inputs A and B, where A is CSR and B is dense; this op returns a dense C; + + If transpose_output is false, returns: + ``` + C = A . B + ``` + + If transpose_output is `true`, returns: + ``` + C = transpose(A . B) = transpose(B) . transpose(A) + ``` + where the transposition is performed along the two innermost (matrix) + dimensions. + + If conjugate_output is `true`, returns: + ``` + C = conjugate(A . B) = conjugate(A) . conjugate(B) + ``` + + If both conjugate_output and transpose_output are `true`, returns: + ``` + C = conjugate(transpose(A . B)) = conjugate(transpose(B)) . + conjugate(transpose(A)) + ``` + + Args: + a: A `Tensor` of type `variant`. A CSRSparseMatrix. + b: A `Tensor`. A dense tensor. + transpose_a: An optional `bool`. Defaults to `False`. + Indicates whether `a` should be transposed. + transpose_b: An optional `bool`. Defaults to `False`. + Indicates whether `b` should be transposed. + adjoint_a: An optional `bool`. Defaults to `False`. + Indicates whether `a` should be conjugate-transposed. + adjoint_b: An optional `bool`. Defaults to `False`. + Indicates whether `b` should be conjugate-transposed. + transpose_output: An optional `bool`. Defaults to `False`. + Transposes the product of `a` and `b`. + conjugate_output: An optional `bool`. Defaults to `False`. + Conjugates the product of `a` and `b`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `b`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixMatMul", name, a, b, "transpose_a", transpose_a, + "transpose_b", transpose_b, "adjoint_a", adjoint_a, "adjoint_b", + adjoint_b, "transpose_output", transpose_output, "conjugate_output", + conjugate_output) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_mat_mul_eager_fallback( + a, b, transpose_a=transpose_a, transpose_b=transpose_b, + adjoint_a=adjoint_a, adjoint_b=adjoint_b, + transpose_output=transpose_output, + conjugate_output=conjugate_output, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + if transpose_output is None: + transpose_output = False + transpose_output = _execute.make_bool(transpose_output, "transpose_output") + if conjugate_output is None: + conjugate_output = False + conjugate_output = _execute.make_bool(conjugate_output, "conjugate_output") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixMatMul", a=a, b=b, transpose_a=transpose_a, + transpose_b=transpose_b, adjoint_a=adjoint_a, + adjoint_b=adjoint_b, + transpose_output=transpose_output, + conjugate_output=conjugate_output, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "adjoint_a", + _op._get_attr_bool("adjoint_a"), "adjoint_b", + _op._get_attr_bool("adjoint_b"), "transpose_output", + _op._get_attr_bool("transpose_output"), "conjugate_output", + _op._get_attr_bool("conjugate_output")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixMatMul = tf_export("raw_ops.SparseMatrixMatMul")(_ops.to_raw_op(sparse_matrix_mat_mul)) + + +def sparse_matrix_mat_mul_eager_fallback(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, TV_SparseMatrixMatMul_T], transpose_a: bool, transpose_b: bool, adjoint_a: bool, adjoint_b: bool, transpose_output: bool, conjugate_output: bool, name, ctx) -> Annotated[Any, TV_SparseMatrixMatMul_T]: + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + if transpose_output is None: + transpose_output = False + transpose_output = _execute.make_bool(transpose_output, "transpose_output") + if conjugate_output is None: + conjugate_output = False + conjugate_output = _execute.make_bool(conjugate_output, "conjugate_output") + _attr_T, (b,) = _execute.args_to_matching_eager([b], ctx, []) + a = _ops.convert_to_tensor(a, _dtypes.variant) + _inputs_flat = [a, b] + _attrs = ("T", _attr_T, "transpose_a", transpose_a, "transpose_b", + transpose_b, "adjoint_a", adjoint_a, "adjoint_b", adjoint_b, + "transpose_output", transpose_output, "conjugate_output", conjugate_output) + _result = _execute.execute(b"SparseMatrixMatMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixMul_T = TypeVar("TV_SparseMatrixMul_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +def sparse_matrix_mul(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, TV_SparseMatrixMul_T], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Element-wise multiplication of a sparse matrix with a dense tensor. + + Returns a sparse matrix. + + The dense tensor `b` may be either a scalar; otherwise `a` must be a rank-3 + `SparseMatrix`; in this case `b` must be shaped `[batch_size, 1, 1]` and the + multiply operation broadcasts. + + **NOTE** even if `b` is zero, the sparsity structure of the output does not + change. + + Args: + a: A `Tensor` of type `variant`. A CSRSparseMatrix. + b: A `Tensor`. A dense tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixMul", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_mul_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixMul", a=a, b=b, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixMul = tf_export("raw_ops.SparseMatrixMul")(_ops.to_raw_op(sparse_matrix_mul)) + + +def sparse_matrix_mul_eager_fallback(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, TV_SparseMatrixMul_T], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_T, (b,) = _execute.args_to_matching_eager([b], ctx, []) + a = _ops.convert_to_tensor(a, _dtypes.variant) + _inputs_flat = [a, b] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseMatrixMul", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sparse_matrix_nnz(sparse_matrix: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Returns the number of nonzeroes of `sparse_matrix`. + + Args: + sparse_matrix: A `Tensor` of type `variant`. A CSRSparseMatrix. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixNNZ", name, sparse_matrix) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_nnz_eager_fallback( + sparse_matrix, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixNNZ", sparse_matrix=sparse_matrix, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixNNZ", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixNNZ = tf_export("raw_ops.SparseMatrixNNZ")(_ops.to_raw_op(sparse_matrix_nnz)) + + +def sparse_matrix_nnz_eager_fallback(sparse_matrix: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int32]: + sparse_matrix = _ops.convert_to_tensor(sparse_matrix, _dtypes.variant) + _inputs_flat = [sparse_matrix] + _attrs = None + _result = _execute.execute(b"SparseMatrixNNZ", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixNNZ", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +def sparse_matrix_ordering_amd(input: Annotated[Any, _atypes.Variant], name=None) -> Annotated[Any, _atypes.Int32]: + r"""Computes the Approximate Minimum Degree (AMD) ordering of `input`. + + Computes the Approximate Minimum Degree (AMD) ordering for a sparse matrix. + + The returned permutation may be used to permute the rows and columns of the + given sparse matrix. This typically results in permuted sparse matrix's sparse + Cholesky (or other decompositions) in having fewer zero fill-in compared to + decomposition of the original matrix. + + The input sparse matrix may have rank 2 or rank 3. The output Tensor, + representing would then have rank 1 or 2 respectively, with the same batch + shape as the input. + + Each component of the input sparse matrix must represent a square symmetric + matrix; only the lower triangular part of the matrix is read. The values of the + sparse matrix does not affect the returned permutation, only the sparsity + pattern of the sparse matrix is used. Hence, a single AMD ordering may be + reused for the Cholesky decompositions of sparse matrices with the same sparsity + pattern but with possibly different values. + + Each batch component of the output permutation represents a permutation of `N` + elements, where the input sparse matrix components each have `N` rows. That is, + the component contains each of the integers `{0, .. N-1}` exactly once. The + `i`th element represents the row index that the `i`th row maps to. + + Usage example: + + ```python + from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops + + a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]]) + a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32) + a_dense_shape = [4, 4] + + with tf.Session() as sess: + # Define (COO format) SparseTensor over Numpy array. + a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape) + + # Convert SparseTensors to CSR SparseMatrix. + a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + a_st.indices, a_st.values, a_st.dense_shape) + + # Obtain the AMD Ordering for the CSR SparseMatrix. + ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix) + + ordering_amd_value = sess.run(ordering_amd) + ``` + + `ordering_amd_value` stores the AMD ordering: `[1 2 3 0]`. + + input: A `CSRSparseMatrix`. + + Args: + input: A `Tensor` of type `variant`. A `CSRSparseMatrix`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixOrderingAMD", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_ordering_amd_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixOrderingAMD", input=input, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixOrderingAMD", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixOrderingAMD = tf_export("raw_ops.SparseMatrixOrderingAMD")(_ops.to_raw_op(sparse_matrix_ordering_amd)) + + +def sparse_matrix_ordering_amd_eager_fallback(input: Annotated[Any, _atypes.Variant], name, ctx) -> Annotated[Any, _atypes.Int32]: + input = _ops.convert_to_tensor(input, _dtypes.variant) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"SparseMatrixOrderingAMD", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixOrderingAMD", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixSoftmax_type = TypeVar("TV_SparseMatrixSoftmax_type", _atypes.Float32, _atypes.Float64) + +def sparse_matrix_softmax(logits: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSoftmax_type, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Calculates the softmax of a CSRSparseMatrix. + + Calculate the softmax of the innermost dimensions of a SparseMatrix. + + Missing values are treated as `-inf` (i.e., logits of zero probability); and + the output has the same sparsity structure as the input (though missing values + in the output may now be treated as having probability zero). + + Args: + logits: A `Tensor` of type `variant`. A CSRSparseMatrix. + type: A `tf.DType` from: `tf.float32, tf.float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixSoftmax", name, logits, "type", type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_softmax_eager_fallback( + logits, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixSoftmax", logits=logits, type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixSoftmax = tf_export("raw_ops.SparseMatrixSoftmax")(_ops.to_raw_op(sparse_matrix_softmax)) + + +def sparse_matrix_softmax_eager_fallback(logits: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSoftmax_type, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + logits = _ops.convert_to_tensor(logits, _dtypes.variant) + _inputs_flat = [logits] + _attrs = ("type", type) + _result = _execute.execute(b"SparseMatrixSoftmax", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixSoftmax", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixSoftmaxGrad_type = TypeVar("TV_SparseMatrixSoftmaxGrad_type", _atypes.Float32, _atypes.Float64) + +def sparse_matrix_softmax_grad(softmax: Annotated[Any, _atypes.Variant], grad_softmax: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSoftmaxGrad_type, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Calculates the gradient of the SparseMatrixSoftmax op. + + Args: + softmax: A `Tensor` of type `variant`. A CSRSparseMatrix. + grad_softmax: A `Tensor` of type `variant`. The gradient of `softmax`. + type: A `tf.DType` from: `tf.float32, tf.float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixSoftmaxGrad", name, softmax, grad_softmax, "type", + type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_softmax_grad_eager_fallback( + softmax, grad_softmax, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixSoftmaxGrad", softmax=softmax, grad_softmax=grad_softmax, + type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixSoftmaxGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixSoftmaxGrad = tf_export("raw_ops.SparseMatrixSoftmaxGrad")(_ops.to_raw_op(sparse_matrix_softmax_grad)) + + +def sparse_matrix_softmax_grad_eager_fallback(softmax: Annotated[Any, _atypes.Variant], grad_softmax: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSoftmaxGrad_type, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + softmax = _ops.convert_to_tensor(softmax, _dtypes.variant) + grad_softmax = _ops.convert_to_tensor(grad_softmax, _dtypes.variant) + _inputs_flat = [softmax, grad_softmax] + _attrs = ("type", type) + _result = _execute.execute(b"SparseMatrixSoftmaxGrad", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixSoftmaxGrad", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixSparseCholesky_type = TypeVar("TV_SparseMatrixSparseCholesky_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_matrix_sparse_cholesky(input: Annotated[Any, _atypes.Variant], permutation: Annotated[Any, _atypes.Int32], type: TV_SparseMatrixSparseCholesky_type, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Computes the sparse Cholesky decomposition of `input`. + + Computes the Sparse Cholesky decomposition of a sparse matrix, with the given + fill-in reducing permutation. + + The input sparse matrix and the fill-in reducing permutation `permutation` must + have compatible shapes. If the sparse matrix has rank 3; with the batch + dimension `B`, then the `permutation` must be of rank 2; with the same batch + dimension `B`. There is no support for broadcasting. + + Furthermore, each component vector of `permutation` must be of length `N`, + containing each of the integers {0, 1, ..., N - 1} exactly once, where `N` is + the number of rows of each component of the sparse matrix. + + Each component of the input sparse matrix must represent a symmetric positive + definite (SPD) matrix; although only the lower triangular part of the matrix is + read. If any individual component is not SPD, then an InvalidArgument error is + thrown. + + The returned sparse matrix has the same dense shape as the input sparse matrix. + For each component `A` of the input sparse matrix, the corresponding output + sparse matrix represents `L`, the lower triangular Cholesky factor satisfying + the following identity: + + ``` + A = L * Lt + ``` + + where Lt denotes the transpose of L (or its conjugate transpose, if `type` is + `complex64` or `complex128`). + + The `type` parameter denotes the type of the matrix elements. The supported + types are: `float32`, `float64`, `complex64` and `complex128`. + + Usage example: + + ```python + from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops + + a_indices = np.array([[0, 0], [1, 1], [2, 1], [2, 2], [3, 3]]) + a_values = np.array([1.0, 2.0, 1.0, 3.0, 4.0], np.float32) + a_dense_shape = [4, 4] + + with tf.Session() as sess: + # Define (COO format) SparseTensor over Numpy array. + a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape) + + # Convert SparseTensors to CSR SparseMatrix. + a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + a_st.indices, a_st.values, a_st.dense_shape) + + # Obtain the Sparse Cholesky factor using AMD Ordering for reducing zero + # fill-in (number of structural non-zeros in the sparse Cholesky factor). + ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(sparse_matrix) + cholesky_sparse_matrices = ( + sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky( + sparse_matrix, ordering_amd, type=tf.float32)) + + # Convert the CSRSparseMatrix Cholesky factor to a dense Tensor + dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense( + cholesky_sparse_matrices, tf.float32) + + # Evaluate the dense Tensor value. + dense_cholesky_value = sess.run(dense_cholesky) + ``` + + `dense_cholesky_value` stores the dense Cholesky factor: + + ``` + [[ 1. 0. 0. 0.] + [ 0. 1.41 0. 0.] + [ 0. 0.70 1.58 0.] + [ 0. 0. 0. 2.]] + ``` + + + input: A `CSRSparseMatrix`. + permutation: A `Tensor`. + type: The type of `input`. + + Args: + input: A `Tensor` of type `variant`. A `CSRSparseMatrix`. + permutation: A `Tensor` of type `int32`. + A fill-in reducing permutation matrix. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixSparseCholesky", name, input, permutation, "type", + type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_sparse_cholesky_eager_fallback( + input, permutation, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixSparseCholesky", input=input, permutation=permutation, + type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixSparseCholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixSparseCholesky = tf_export("raw_ops.SparseMatrixSparseCholesky")(_ops.to_raw_op(sparse_matrix_sparse_cholesky)) + + +def sparse_matrix_sparse_cholesky_eager_fallback(input: Annotated[Any, _atypes.Variant], permutation: Annotated[Any, _atypes.Int32], type: TV_SparseMatrixSparseCholesky_type, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + input = _ops.convert_to_tensor(input, _dtypes.variant) + permutation = _ops.convert_to_tensor(permutation, _dtypes.int32) + _inputs_flat = [input, permutation] + _attrs = ("type", type) + _result = _execute.execute(b"SparseMatrixSparseCholesky", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixSparseCholesky", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixSparseMatMul_type = TypeVar("TV_SparseMatrixSparseMatMul_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_matrix_sparse_mat_mul(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSparseMatMul_type, transpose_a:bool=False, transpose_b:bool=False, adjoint_a:bool=False, adjoint_b:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Sparse-matrix-multiplies two CSR matrices `a` and `b`. + + Performs a matrix multiplication of a sparse matrix `a` with a sparse matrix + `b`; returns a sparse matrix `a * b`, unless either `a` or `b` is transposed or + adjointed. + + Each matrix may be transposed or adjointed (conjugated and transposed) + according to the Boolean parameters `transpose_a`, `adjoint_a`, `transpose_b` + and `adjoint_b`. At most one of `transpose_a` or `adjoint_a` may be True. + Similarly, at most one of `transpose_b` or `adjoint_b` may be True. + + The inputs must have compatible shapes. That is, the inner dimension of `a` + must be equal to the outer dimension of `b`. This requirement is adjusted + according to whether either `a` or `b` is transposed or adjointed. + + The `type` parameter denotes the type of the matrix elements. Both `a` and `b` + must have the same type. The supported types are: `float32`, `float64`, + `complex64` and `complex128`. + + Both `a` and `b` must have the same rank. Broadcasting is not supported. If they + have rank 3, each batch of 2D CSRSparseMatrices within `a` and `b` must have the + same dense shape. + + The sparse matrix product may have numeric (non-structural) zeros. + TODO(anudhyan): Consider adding a boolean attribute to control whether to prune + zeros. + + Usage example: + + ```python + from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops + + a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]]) + a_values = np.array([1.0, 5.0, -1.0, -2.0], np.float32) + a_dense_shape = [4, 5] + + b_indices = np.array([[0, 0], [3, 0], [3, 1]]) + b_values = np.array([2.0, 7.0, 8.0], np.float32) + b_dense_shape = [5, 3] + + with tf.Session() as sess: + # Define (COO format) Sparse Tensors over Numpy arrays + a_st = tf.sparse.SparseTensor(a_indices, a_values, a_dense_shape) + b_st = tf.sparse.SparseTensor(b_indices, b_values, b_dense_shape) + + # Convert SparseTensors to CSR SparseMatrix + a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + a_st.indices, a_st.values, a_st.dense_shape) + b_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + b_st.indices, b_st.values, b_st.dense_shape) + + # Compute the CSR SparseMatrix matrix multiplication + c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul( + a=a_sm, b=b_sm, type=tf.float32) + + # Convert the CSR SparseMatrix product to a dense Tensor + c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense( + c_sm, tf.float32) + # Evaluate the dense Tensor value + c_sm_dense_value = sess.run(c_sm_dense) + ``` + + `c_sm_dense_value` stores the dense matrix product: + + ``` + [[ 2. 0. 0.] + [ 0. 0. 0.] + [ 35. 40. 0.] + [ -4. 0. 0.]] + ``` + + a: A `CSRSparseMatrix`. + b: A `CSRSparseMatrix` with the same type and rank as `a`. + type: The type of both `a` and `b`. + transpose_a: If True, `a` transposed before multiplication. + transpose_b: If True, `b` transposed before multiplication. + adjoint_a: If True, `a` adjointed before multiplication. + adjoint_b: If True, `b` adjointed before multiplication. + + Args: + a: A `Tensor` of type `variant`. A CSRSparseMatrix. + b: A `Tensor` of type `variant`. A CSRSparseMatrix. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + transpose_a: An optional `bool`. Defaults to `False`. + Indicates whether `a` should be transposed. + transpose_b: An optional `bool`. Defaults to `False`. + Indicates whether `b` should be transposed. + adjoint_a: An optional `bool`. Defaults to `False`. + Indicates whether `a` should be conjugate-transposed. + adjoint_b: An optional `bool`. Defaults to `False`. + Indicates whether `b` should be conjugate-transposed. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixSparseMatMul", name, a, b, "type", type, + "transpose_a", transpose_a, "transpose_b", transpose_b, "adjoint_a", + adjoint_a, "adjoint_b", adjoint_b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_sparse_mat_mul_eager_fallback( + a, b, type=type, transpose_a=transpose_a, transpose_b=transpose_b, + adjoint_a=adjoint_a, adjoint_b=adjoint_b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixSparseMatMul", a=a, b=b, type=type, + transpose_a=transpose_a, + transpose_b=transpose_b, + adjoint_a=adjoint_a, adjoint_b=adjoint_b, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type"), "transpose_a", + _op._get_attr_bool("transpose_a"), "transpose_b", + _op._get_attr_bool("transpose_b"), "adjoint_a", + _op._get_attr_bool("adjoint_a"), "adjoint_b", + _op._get_attr_bool("adjoint_b")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixSparseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixSparseMatMul = tf_export("raw_ops.SparseMatrixSparseMatMul")(_ops.to_raw_op(sparse_matrix_sparse_mat_mul)) + + +def sparse_matrix_sparse_mat_mul_eager_fallback(a: Annotated[Any, _atypes.Variant], b: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixSparseMatMul_type, transpose_a: bool, transpose_b: bool, adjoint_a: bool, adjoint_b: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + if transpose_a is None: + transpose_a = False + transpose_a = _execute.make_bool(transpose_a, "transpose_a") + if transpose_b is None: + transpose_b = False + transpose_b = _execute.make_bool(transpose_b, "transpose_b") + if adjoint_a is None: + adjoint_a = False + adjoint_a = _execute.make_bool(adjoint_a, "adjoint_a") + if adjoint_b is None: + adjoint_b = False + adjoint_b = _execute.make_bool(adjoint_b, "adjoint_b") + a = _ops.convert_to_tensor(a, _dtypes.variant) + b = _ops.convert_to_tensor(b, _dtypes.variant) + _inputs_flat = [a, b] + _attrs = ("type", type, "transpose_a", transpose_a, "transpose_b", + transpose_b, "adjoint_a", adjoint_a, "adjoint_b", adjoint_b) + _result = _execute.execute(b"SparseMatrixSparseMatMul", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixSparseMatMul", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixTranspose_type = TypeVar("TV_SparseMatrixTranspose_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_matrix_transpose(input: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixTranspose_type, conjugate:bool=False, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Transposes the inner (matrix) dimensions of a CSRSparseMatrix. + + Transposes the inner (matrix) dimensions of a SparseMatrix and optionally + conjugates its values. + + Args: + input: A `Tensor` of type `variant`. A CSRSparseMatrix. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + conjugate: An optional `bool`. Defaults to `False`. + Indicates whether `input` should be conjugated. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixTranspose", name, input, "conjugate", conjugate, + "type", type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_transpose_eager_fallback( + input, conjugate=conjugate, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + if conjugate is None: + conjugate = False + conjugate = _execute.make_bool(conjugate, "conjugate") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixTranspose", input=input, type=type, conjugate=conjugate, + name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("conjugate", _op._get_attr_bool("conjugate"), "type", + _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixTranspose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixTranspose = tf_export("raw_ops.SparseMatrixTranspose")(_ops.to_raw_op(sparse_matrix_transpose)) + + +def sparse_matrix_transpose_eager_fallback(input: Annotated[Any, _atypes.Variant], type: TV_SparseMatrixTranspose_type, conjugate: bool, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + if conjugate is None: + conjugate = False + conjugate = _execute.make_bool(conjugate, "conjugate") + input = _ops.convert_to_tensor(input, _dtypes.variant) + _inputs_flat = [input] + _attrs = ("conjugate", conjugate, "type", type) + _result = _execute.execute(b"SparseMatrixTranspose", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixTranspose", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseMatrixZeros_type = TypeVar("TV_SparseMatrixZeros_type", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_matrix_zeros(dense_shape: Annotated[Any, _atypes.Int64], type: TV_SparseMatrixZeros_type, name=None) -> Annotated[Any, _atypes.Variant]: + r"""Creates an all-zeros CSRSparseMatrix with shape `dense_shape`. + + Args: + dense_shape: A `Tensor` of type `int64`. The desired matrix shape. + type: A `tf.DType` from: `tf.float32, tf.float64, tf.complex64, tf.complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseMatrixZeros", name, dense_shape, "type", type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_matrix_zeros_eager_fallback( + dense_shape, type=type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + type = _execute.make_type(type, "type") + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseMatrixZeros", dense_shape=dense_shape, type=type, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("type", _op._get_attr_type("type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseMatrixZeros", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseMatrixZeros = tf_export("raw_ops.SparseMatrixZeros")(_ops.to_raw_op(sparse_matrix_zeros)) + + +def sparse_matrix_zeros_eager_fallback(dense_shape: Annotated[Any, _atypes.Int64], type: TV_SparseMatrixZeros_type, name, ctx) -> Annotated[Any, _atypes.Variant]: + type = _execute.make_type(type, "type") + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [dense_shape] + _attrs = ("type", type) + _result = _execute.execute(b"SparseMatrixZeros", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseMatrixZeros", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_SparseTensorToCSRSparseMatrix_T = TypeVar("TV_SparseTensorToCSRSparseMatrix_T", _atypes.Complex128, _atypes.Complex64, _atypes.Float32, _atypes.Float64) + +def sparse_tensor_to_csr_sparse_matrix(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseTensorToCSRSparseMatrix_T], dense_shape: Annotated[Any, _atypes.Int64], name=None) -> Annotated[Any, _atypes.Variant]: + r"""Converts a SparseTensor to a (possibly batched) CSRSparseMatrix. + + Args: + indices: A `Tensor` of type `int64`. SparseTensor indices. + values: A `Tensor`. Must be one of the following types: `float32`, `float64`, `complex64`, `complex128`. + SparseTensor values. + dense_shape: A `Tensor` of type `int64`. SparseTensor dense shape. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `variant`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SparseTensorToCSRSparseMatrix", name, indices, values, + dense_shape) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + return sparse_tensor_to_csr_sparse_matrix_eager_fallback( + indices, values, dense_shape, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + # Add nodes to the TensorFlow graph. + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SparseTensorToCSRSparseMatrix", indices=indices, values=values, + dense_shape=dense_shape, name=name) + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SparseTensorToCSRSparseMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SparseTensorToCSRSparseMatrix = tf_export("raw_ops.SparseTensorToCSRSparseMatrix")(_ops.to_raw_op(sparse_tensor_to_csr_sparse_matrix)) + + +def sparse_tensor_to_csr_sparse_matrix_eager_fallback(indices: Annotated[Any, _atypes.Int64], values: Annotated[Any, TV_SparseTensorToCSRSparseMatrix_T], dense_shape: Annotated[Any, _atypes.Int64], name, ctx) -> Annotated[Any, _atypes.Variant]: + _attr_T, (values,) = _execute.args_to_matching_eager([values], ctx, [_dtypes.float32, _dtypes.float64, _dtypes.complex64, _dtypes.complex128, ]) + indices = _ops.convert_to_tensor(indices, _dtypes.int64) + dense_shape = _ops.convert_to_tensor(dense_shape, _dtypes.int64) + _inputs_flat = [indices, values, dense_shape] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SparseTensorToCSRSparseMatrix", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SparseTensorToCSRSparseMatrix", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1162ab04e359623126f8f2dd38004275a255c01f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse.py @@ -0,0 +1,26 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Public API for tf.linalg.sparse namespace.""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.linalg.sparse.conjugate_gradient import conjugate_gradient +from tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_grad import * +from tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops import * +# pylint: enable=wildcard-import + +__all__ = [ + 'conjugate_gradient' +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..dc931e5d6f756c51035e02bdf187cf7c3c879b18 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_grad.py @@ -0,0 +1,364 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""CSR Sparse Matrix Gradients.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops + + +@ops.RegisterGradient("DenseToCSRSparseMatrix") +def _DenseToCSRSparseMatrixGrad(op: ops.Operation, grad): + """Gradient for dense_to_csr_sparse_matrix op.""" + grad_values = ( + sparse_csr_matrix_ops.csr_sparse_matrix_to_dense( + grad, type=op.get_attr("T"))) + # inputs to fw op were: params, indices. + return (grad_values, None) + + +@ops.RegisterGradient("CSRSparseMatrixToDense") +def _CSRSparseMatrixToDenseGrad(op: ops.Operation, grad): + """Gradient for csr_sparse_matrix_to_dense op.""" + coo_sparse_tensor = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor( + op.inputs[0], type=grad.dtype) + return sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + indices=coo_sparse_tensor.indices, + values=array_ops.gather_nd(grad, coo_sparse_tensor.indices), + dense_shape=grad.shape) + + +@ops.RegisterGradient("SparseTensorToCSRSparseMatrix") +def _SparseTensorToCSRSparseMatrixGrad(op: ops.Operation, grad): + """Gradient for sparse_tensor_to_csr_sparse_matrix op.""" + grad_values = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor( + grad, type=op.get_attr("T")).values + return (None, grad_values, None) + + +@ops.RegisterGradient("CSRSparseMatrixToSparseTensor") +def _CSRSparseMatrixToSparseTensorGrad(op: ops.Operation, *grads): + """Gradient for csr_sparse_matrix_to_sparse_tensor op.""" + return sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + indices=op.outputs[0], values=grads[1], dense_shape=op.outputs[2]) + + +ops.NotDifferentiable("SparseMatrixNNZ") + +ops.NotDifferentiable("SparseMatrixZeros") + + +def _PruneSparseTensor(unpruned, pruned_pattern): + """Helper function to prune COO sparse tensor. + + Given two sparse tensors 'unpruned' and 'pruned_pattern', generates another + sparse tensor with indices and values fron 'unpruned' only if its indices also + occur in pruned_pattern. + + Args: + unpruned: COO matrix with unpruned indices + pruned_pattern: COO matrix with pruned pattern. + + TODO(tabakg): This is far from optimal. Consider a C++ implementation. + + Returns: + Indices, values, and dense_shape of the pruned matrix. + """ + pruned_indices = sparse_ops.sparse_reshape( + pruned_pattern, shape=(-1,)).indices[..., 0] + unpruned_indices = sparse_ops.sparse_reshape( + unpruned, shape=(-1,)).indices[..., 0] + best_match = array_ops.searchsorted(unpruned_indices, pruned_indices) + keep_indices = array_ops.gather( + best_match, + array_ops.where( + math_ops.equal( + array_ops.gather(unpruned_indices, best_match), pruned_indices))) + return (array_ops.gather_nd(unpruned.indices, keep_indices), + array_ops.gather_nd(unpruned.values, + keep_indices), pruned_pattern.dense_shape) + + +def _PruneCSRMatrix(unpruned, pruned_pattern): + """TODO(tabakg): Consider re-writing in C++.""" + _, dtype = sparse_csr_matrix_ops.dense_shape_and_type(pruned_pattern) + coo_unpruned = sparse_tensor.SparseTensor( + *sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor( + unpruned, type=dtype)) + coo_pruned_pattern = sparse_tensor.SparseTensor( + *sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor( + pruned_pattern, type=dtype)) + return sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + *_PruneSparseTensor(coo_unpruned, coo_pruned_pattern)) + + +@ops.RegisterGradient("SparseMatrixAdd") +def _SparseMatrixAddGrad(op: ops.Operation, grad): + """Gradient for sparse_matrix_add op.""" + # input to sparse_matrix_add is (a, b, alpha, beta) + # with a, b CSR and alpha beta scalars. + # output is: alpha * a + beta * b + + # d(a*A + b*B)/dA . grad = a * grad + + # May have gotten the transposes wrong below. + # d(a*A + b*B)/da . grad = tr(A' . grad) + + # For now, only implement gradients w.r.t. A and B. + # TODO(ebrevdo): Implement reduce_sum for SparseMatrix so that we + # can implement gradients w.r.t. a and b. + (a_csr, b_csr, alpha, beta) = op.inputs + return (sparse_csr_matrix_ops.sparse_matrix_mul( + _PruneCSRMatrix(grad, a_csr), alpha), + sparse_csr_matrix_ops.sparse_matrix_mul( + _PruneCSRMatrix(grad, b_csr), beta), None, None) + + +def _PrunedDenseMatrixMultiplication(a, + b, + indices, + transpose_a=False, + adjoint_a=False, + transpose_b=False, + adjoint_b=False): + """Multiplies two dense matrices at selected indices. + + The two inputs `a` and `b` must have matching rank (2 or 3). If using rank 3, + the first rank is used for the batch number. The last two dimensions should + also be compatible for matrix multiplication. + + TODO(tabakg): Consider C++ implementation. There is also a more efficient way + to handle transposes here. + + Args: + a: The left dense matrix (or batched matrices). + b: The right dense matrix (or batched matrices). + indices: The selected output indices where values should be produced. Other + indices will be pruned (not computed in the first place). Indices are + specified as a tensor of shape (length, rank), where length is the number + of entries and rank is the rank of the dense inputs (2 or 3). + transpose_a: Whether to transpose a. + adjoint_a: Whether to take the conjugate transpose of a. + transpose_b: Whether to transpose b. + adjoint_b: Whether to take the conjugate transpose of b. + + Returns: + A CSR matrix. + """ + transpose_a = transpose_a or adjoint_a + transpose_b = transpose_b or adjoint_b + + a = math_ops.conj(a) if adjoint_a else a + b = math_ops.conj(b) if adjoint_b else b + + rank = len(a.shape) + dense_shape = (a.shape[-1] if transpose_a else a.shape[-2], + b.shape[-2] if transpose_b else b.shape[-1]) + if rank == 2: + rows = indices[:, 0] + cols = indices[:, 1] + transpose = array_ops.transpose + gather_op = array_ops.gather + elif rank == 3: + dense_shape = (a.shape[0],) + dense_shape + rows = indices[:, :2] + cols = array_ops_stack.stack([indices[:, 0], indices[:, 2]], axis=1) + transpose = lambda x: array_ops.transpose(x, perm=[0, 2, 1]) + gather_op = array_ops.gather_nd + + a_rows = gather_op(transpose(a) if transpose_a else a, indices=rows) + b_cols = gather_op(b if transpose_b else transpose(b), indices=cols) + values = math_ops.reduce_sum(a_rows * b_cols, axis=1) + + return sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix( + indices=indices, values=values, dense_shape=dense_shape) + + +@ops.RegisterGradient("SparseMatrixTranspose") +def _SparseMatrixTransposeGrad(op: ops.Operation, grad): + """Gradient for sparse_matrix_transpose op.""" + return sparse_csr_matrix_ops.sparse_matrix_transpose( + grad, type=op.get_attr("type"), conjugate=op.get_attr("conjugate")) + + +@ops.RegisterGradient("SparseMatrixSoftmax") +def _SparseMatrixSoftmaxGrad(op: ops.Operation, grad_softmax): + """Gradient for sparse_matrix_softmax op.""" + softmax = op.outputs[0] + return sparse_csr_matrix_ops.sparse_matrix_softmax_grad( + softmax, grad_softmax, type=op.get_attr("type")) + + +@ops.RegisterGradient("SparseMatrixMatMul") +def _SparseMatrixMatMulGrad(op: ops.Operation, grad): + """Gradient for sparse_matrix_mat_mul op.""" + # input to sparse_matrix_mat_mul is (A, B) with CSR A and dense B. + # Output is dense: + # C = opA(A) . opB(B) if transpose_output = false + # C = (opA(A) . opB(B))' = opB(B)' . opA(A)' if transpose_output = true. + # where opA = transpose if transpose_a = True else identity + # and opB = transpose if transpose_b = True else identity + + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + adj_a = op.get_attr("adjoint_a") + adj_b = op.get_attr("adjoint_b") + transpose_output = op.get_attr("transpose_output") + conjugate_output = op.get_attr("conjugate_output") + a = op.inputs[0] # sparse matrix + b = op.inputs[1] # dense matrix + conj = math_ops.conj + sparse_matmul = sparse_csr_matrix_ops.sparse_matrix_mat_mul + + def matmul(x, y, **kwargs): # pylint: disable=invalid-name + return _PrunedDenseMatrixMultiplication( + x, + y, + indices=sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor( + a, type=x.dtype).indices, + **kwargs) + + if conjugate_output: + grad = conj(grad) + if not transpose_output: + # C = opA(A) . opB(B) + if not adj_a and not adj_b: + a = conj(a) + b = conj(b) + if not t_a: + grad_a = matmul(grad, b, transpose_b=not t_b) + else: + grad_a = matmul(b, grad, transpose_a=t_b, transpose_b=True) + grad_b = sparse_matmul(a, grad, transpose_a=not t_a, transpose_output=t_b) + elif not t_a and not t_b: + if not adj_a: + grad_a = matmul(grad, b, adjoint_b=not adj_b) + else: + grad_a = matmul(b, grad, adjoint_a=adj_b, adjoint_b=True) + grad_b = sparse_matmul( + a, + grad, + adjoint_a=not adj_a, + transpose_output=adj_b, + conjugate_output=adj_b) + elif adj_a and t_b: + grad_a = matmul(b, grad, transpose_a=True, adjoint_b=True) + grad_b = sparse_matmul(a, grad, transpose_output=True) + elif t_a and adj_b: + grad_a = matmul(b, grad, transpose_a=True, transpose_b=True) + grad_b = sparse_matmul( + conj(a), grad, transpose_output=True, conjugate_output=True) + else: + # C = (opA(A) . opB(B))' = opB(B)' . opA(A)' + if not adj_a and not adj_b: + a = conj(a) + b = conj(b) + if not t_a: + grad_a = matmul(grad, b, transpose_a=True, transpose_b=not t_b) + else: + grad_a = matmul(b, grad, transpose_a=t_b) + grad_b = sparse_matmul( + a, grad, transpose_a=not t_a, transpose_b=True, transpose_output=t_b) + elif not t_a and not t_b: + if not adj_a: + grad_a = matmul(grad, b, transpose_a=True, adjoint_b=not adj_b) + else: + grad_a = matmul(b, conj(grad), adjoint_a=adj_b) + grad_b = sparse_matmul( + a, + grad, + adjoint_a=not adj_a, + transpose_b=True, + transpose_output=adj_b, + conjugate_output=adj_b) + elif adj_a and t_b: + grad_a = matmul(b, conj(grad), transpose_a=True) + grad_b = sparse_matmul(a, grad, transpose_b=True, transpose_output=True) + elif t_a and adj_b: + grad_a = matmul(b, grad, transpose_a=True) + grad_b = sparse_matmul(a, grad, adjoint_b=True, transpose_output=True) + + return (grad_a, grad_b) + + +@ops.RegisterGradient("SparseMatrixSparseMatMul") +def _SparseMatrixSparseMatMulGrad(op: ops.Operation, grad): + """Gradient for sparse_matrix_sparse_mat_mul op.""" + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + adj_a = op.get_attr("adjoint_a") + adj_b = op.get_attr("adjoint_b") + dtype = op.get_attr("type") + + # input to sparse_matrix_sparse_mat_mul is (A, B) with CSR A and B. + # Output is CSR: + # C = opA(A) . opB(B) + # where opA = transpose if transpose_a = True else identity + # and opB = transpose if transpose_b = True else identity + a = op.inputs[0] + b = op.inputs[1] + conj = math_ops.conj + matmul = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul + if not t_a and not t_b: + if not adj_a: + if not adj_b: + grad_a = matmul(grad, b, adjoint_b=True, type=dtype) + grad_b = matmul(a, grad, adjoint_a=True, type=dtype) + else: + grad_a = matmul(grad, b, type=dtype) + grad_b = matmul(grad, a, adjoint_a=True, type=dtype) + else: + if not adj_b: + grad_a = matmul(b, grad, adjoint_b=True, type=dtype) + grad_b = matmul(a, grad, type=dtype) + else: + grad_a = matmul(b, grad, adjoint_a=True, adjoint_b=True, type=dtype) + grad_b = matmul(grad, a, adjoint_a=True, adjoint_b=True, type=dtype) + elif not adj_a and not adj_b: + if not t_a and t_b: + grad_a = matmul(grad, conj(b), type=dtype) + grad_b = matmul(grad, conj(a), transpose_a=True, type=dtype) + elif t_a and not t_b: + grad_a = matmul(conj(b), grad, transpose_b=True, type=dtype) + grad_b = matmul(conj(a), grad, type=dtype) + else: + grad_a = matmul(b, grad, adjoint_a=True, transpose_b=True, type=dtype) + grad_b = matmul(grad, a, transpose_a=True, adjoint_b=True, type=dtype) + elif adj_a and t_b: + grad_a = matmul(b, grad, transpose_a=True, adjoint_b=True, type=dtype) + grad_b = matmul(grad, a, transpose_a=True, transpose_b=True, type=dtype) + elif t_a and adj_b: + grad_a = matmul(b, grad, transpose_a=True, transpose_b=True, type=dtype) + grad_b = matmul(grad, a, adjoint_a=True, transpose_b=True, type=dtype) + + # TODO(tabakg): There should be a C++ function for sparse-sparse + # multiplication with pre-determined indices, instead of pruning after the + # multiplication. + return (_PruneCSRMatrix(grad_a, a), _PruneCSRMatrix(grad_b, b)) + + +@ops.RegisterGradient("SparseMatrixMul") +def _SparseMatrixMulGrad(op: ops.Operation, grad): + """Gradient for sparse_matrix_mul op.""" + # input to sparse_matrix_mul is (A, B) with CSR A and dense B. + # Output is CSR: + # C = A .* B + del op + del grad + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9e5ab10faaabd41b7a85aa39313bdb9db6c0fd40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py @@ -0,0 +1,376 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""CSR Sparse Matrix Operations.""" + +import abc +import collections + +# pylint: disable=g-direct-tensorflow-import, wildcard-import +from tensorflow.python.eager import context +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops.linalg.sparse import gen_sparse_csr_matrix_ops as sm_ops +from tensorflow.python.ops.linalg.sparse.gen_sparse_csr_matrix_ops import * + + +__all__ = [ + "SparseMatrix", + "CSRSparseMatrix", + "matmul", + "dense_shape_and_type", +] +# pylint: disable=invalid-name +__all__ += [_x for _x in dir(sm_ops) if not _x.startswith("_")] + + +class DenseShapeAndType( + collections.namedtuple("DenseShapeAndType", ("shape", "dtype"))): + pass + + +def _get_handle_data(tensor): + return resource_variable_ops.get_eager_safe_handle_data(tensor) + + +def _create_handle_data_proto(shape_proto, dtype_enum): + """Create handle data based on shape and dtype protos.""" + variant_shape_and_type_data = \ + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData() + variant_shape_and_type_data.is_set = True + # NOTE(ebrevdo): shape_and_type lacks append() in some versions of protobuf. + variant_shape_and_type_data.shape_and_type.extend([ + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType( + shape=shape_proto, dtype=dtype_enum) + ]) + return variant_shape_and_type_data + + +def _make_handle_data(tensor): + """Create handle data based on tensor shape and dtype.""" + return _create_handle_data_proto(tensor.shape.as_proto(), + tensor.dtype.as_datatype_enum) + + +def get_shape_and_type(matrix): + """Return matrix's shape and type if available.""" + handle_data = getattr(matrix, "_handle_data", None) + if handle_data is None: + return None + if len(handle_data.shape_and_type) != 1: + raise ValueError( + "shape_and_type array in _handle_data must have length one, but saw: %d" + % len(handle_data.shape_and_type)) + return handle_data.shape_and_type[0] + + +def dense_shape_and_type(matrix): + """Get dense shape and dtype of the tf.Tensor containing the matrix. + + Args: + matrix: A `tf.Tensor` of type `tf.variant` storing a sparse matrix. + + Returns: + An instance of `ShapeAndType` with properties `shape` (a `tf.TensorShape`) + and `dtype` (a `tf.DType`). + + Raises: + TypeError: if `matrix` is not a tensor or its dtype is not variant. + ValueError: if `matrix` lacks static handle data containing the dense + shape and dtype. + """ + if not isinstance(matrix, tensor_lib.Tensor): + raise TypeError("matrix should be a tensor, but saw: %s" % (matrix,)) + if matrix.dtype != dtypes.variant: + raise TypeError( + "expected matrix to be type tf.variant, but saw: %s" % (matrix.dtype,)) + handle_data = _get_handle_data(matrix) + if not handle_data or not handle_data.is_set: + raise ValueError("matrix has missing handle data: %s" % (matrix,)) + if len(handle_data.shape_and_type) != 1: + raise ValueError("len(matrix.handle_data.shape_and_type) != 1: '%s'" % + (handle_data.shape_and_type,)) + return DenseShapeAndType( + tensor_shape.TensorShape(handle_data.shape_and_type[0].shape), + dtypes.DType(handle_data.shape_and_type[0].dtype)) + + +def matmul_shape_inference(a, b, c, transpose_a, transpose_b, adjoint_a, + adjoint_b): + """Helper function for matmul to set the result matrix's handle data.""" + c_handle = getattr(c, "_handle_data", None) + a_shape_and_type = get_shape_and_type(a) + b_shape_and_type = get_shape_and_type(b) + if (c_handle is None and a_shape_and_type is not None and + b_shape_and_type is not None): + + transpose_a = transpose_a or adjoint_a + transpose_b = transpose_b or adjoint_b + + a_shape = a_shape_and_type.shape + b_shape = b_shape_and_type.shape + rank = len(a_shape.dim) + + # Creates the output shape. + c_rows = a_shape.dim[rank - (1 if transpose_a else 2)].size + c_cols = b_shape.dim[rank - (2 if transpose_b else 1)].size + c_shape = tensor_shape.TensorShape(a_shape) + c_shape = tensor_shape.TensorShape(c_shape[:rank - 2] + [c_rows, c_cols]) + c_handle = _create_handle_data_proto(c_shape.as_proto(), + a_shape_and_type.dtype) + return c_handle + + +def matmul(a, + b, + transpose_a=False, + transpose_b=False, + adjoint_a=False, + adjoint_b=False, + name=None): + """Perform a sparse matrix matmul between `a` and `b`. + + Performs a contraction between `a` and `b` along the two innermost dimensions. + If both `a` and `b` are instances of `SparseMatrix`, returns a new instance + of `SparseMatrix` (same type as `a`). If one is not an instance of + `SparseMatrix`, returns a dense `Tensor`: + + ``` + c = opA(a) . opB(b) + ``` + where `opA` (resp. `opB`) is the transpose or hermitian transpose depending + on the values of `transpose_a` (resp. `transpose_b`) and `adjoint_a` + (resp. `adjoint_b`). + + Args: + a: `Tensor` or `SparseMatrix`, having rank `2` or `3`. + b: `Tensor` or `SparseMatrix`, having rank `2` or `3`. + transpose_a: Python `bool`. + transpose_b: Python `bool`. + adjoint_a: Python `bool`. + adjoint_b: Python `bool`. + name: Optional name to use when creating ops. + + Returns: + A `SparseMatrix` if both `a` and `b` are instances of `SparseMatrix`, + otherwise a dense `Tensor`. + """ + if not isinstance(a, SparseMatrix) and not isinstance(b, SparseMatrix): + return math_ops.matmul( + a, + b, + transpose_a=transpose_a, + transpose_b=transpose_b, + adjoint_a=adjoint_a, + adjoint_b=adjoint_b, + name=name) + + # pylint: disable=protected-access + a_matrix = a._matrix if isinstance(a, SparseMatrix) else a + b_matrix = b._matrix if isinstance(b, SparseMatrix) else b + with ops.name_scope(name, "SparseMatrixMatMul", [a_matrix, b_matrix]): + if isinstance(a, SparseMatrix) and isinstance(b, SparseMatrix): + if not (isinstance(a, type(b)) or isinstance(b, type(a))): + raise TypeError("SparseMatrix types don't inherit from each other: " + "%s and %s" % (type(a), type(b))) + c = sm_ops.sparse_matrix_sparse_mat_mul( + a_matrix, + b_matrix, + transpose_a=transpose_a, + transpose_b=transpose_b, + adjoint_a=adjoint_a, + adjoint_b=adjoint_b, + type=a.dtype) + + # In eager mode, shape inference functions are not called, and the output + # shape is not set. We have to infer the output shape here. + # TODO(penporn): Set this from the C++ kernel instead. + c_handle = matmul_shape_inference(a_matrix, b_matrix, c, transpose_a, + transpose_b, adjoint_a, adjoint_b) + return a._from_matrix(c, handle_data=c_handle) + + elif isinstance(a, SparseMatrix): + return sm_ops.sparse_matrix_mat_mul( + a_matrix, + b, + transpose_a=transpose_a, + transpose_b=transpose_b, + adjoint_a=adjoint_a, + adjoint_b=adjoint_b) + else: + # opA(A) . opB(B) = t(nopB(B) . nopA(A)) + if not adjoint_a and not adjoint_b: + return sm_ops.sparse_matrix_mat_mul( + b_matrix, + a, + transpose_a=not transpose_b, + transpose_b=not transpose_a, + transpose_output=True) + elif not transpose_a and not transpose_b: + return sm_ops.sparse_matrix_mat_mul( + b_matrix, + a, + adjoint_a=not adjoint_b, + adjoint_b=not adjoint_a, + transpose_output=True, + conjugate_output=True) + else: + return sm_ops.sparse_matrix_mat_mul( + b_matrix, + math_ops.conj(a), + transpose_output=True, + conjugate_output=adjoint_b) + + +class SparseMatrix(metaclass=abc.ABCMeta): + """Abstract class for sparse matrix types.""" + + @abc.abstractmethod + def __init__(self): + self._eager_mode = context.executing_eagerly() + + @abc.abstractproperty + def _matrix(self): + pass + + @abc.abstractmethod + def _from_matrix(self, matrix, handle_data=None): + pass + + @abc.abstractmethod + def to_dense(self): + pass + + @abc.abstractmethod + def to_sparse_tensor(self): + pass + + @property + def graph(self): + return self._matrix.graph + + @property + def shape(self): + return dense_shape_and_type(self._matrix).shape + + @property + def dtype(self): + return dense_shape_and_type(self._matrix).dtype + + @property + def eager_handle_data(self): + """Return the matrix's handle data iff in eager mode.""" + return _get_handle_data(self._matrix) if self._eager_mode else None + + def conj(self): + return self._from_matrix( + math_ops.conj(self._matrix), self.eager_handle_data) + + def hermitian_transpose(self): + """Return the hermitian transpose of the matrix.""" + return self._from_matrix( + sm_ops.sparse_matrix_transpose( + self._matrix, conjugate=True, type=self.dtype), + self.eager_handle_data) + + def nnz(self): + """Number of stored values, including explicit zeros.""" + return sm_ops.sparse_matrix_nnz(self._matrix) + + nonzero = nnz + + def sorted_indices(self): + # TODO(ebrevdo): A more efficient implementation? + return self.to_sparse_tensor().indices + + def transpose(self): + return self._from_matrix( + sm_ops.sparse_matrix_transpose(self._matrix, type=self.dtype), + self.eager_handle_data) + + +class CSRSparseMatrix(SparseMatrix): + """(Optionally batched) CSR Sparse Matrix.""" + + def __init__(self, value, indices=None, name=None): + """Construct a CSRSparseMatrix from a dense matrix or SparseTensor. + + Args: + value: A dense `2D` or `3D` Tensor or `SparseTensor`. + indices: The nonzero indices of `value` + (if `value` is not a `SparseTensor`). + name: Optional op name. + + Raises: + ValueError: if `value` is a `SparseTensor` and `indices` is not `None`. + """ + del name # Unused. + super(CSRSparseMatrix, self).__init__() + if isinstance(value, sparse_tensor.SparseTensor): + if indices is not None: + raise ValueError("indices must be None if value is a SparseTensor.") + self._dtype = value.dtype + self._csr_matrix = sm_ops.sparse_tensor_to_csr_sparse_matrix( + indices=value.indices, + values=value.values, + dense_shape=value.dense_shape) + else: + value = ops.convert_to_tensor(value) + self._dtype = value.dtype + if indices is not None: + indices = ops.convert_to_tensor(indices, dtype=dtypes.int64) + else: + indices = array_ops.stop_gradient(array_ops.where(value)) + self._csr_matrix = sm_ops.dense_to_csr_sparse_matrix(value, indices) + + # Eager mode doesn't call shape inference functions, so we have to set the + # shape and dtype handle data directly. + if self._eager_mode: + # pylint: disable=protected-access + self._csr_matrix._handle_data = _make_handle_data(value) + # pylint: enable=protected-access + + @property + def _matrix(self): + return self._csr_matrix + + def _from_matrix(self, matrix, handle_data=None): + assert ( + isinstance(matrix, tensor_lib.Tensor) and matrix.dtype == dtypes.variant + ) + ret = type(self).__new__(type(self)) + # pylint: disable=protected-access + ret._dtype = self._dtype + if self._eager_mode: + if matrix._handle_data is None: + matrix._handle_data = handle_data + assert matrix._handle_data is not None + ret._csr_matrix = matrix + # pylint: enable=protected-access + return ret + + def to_dense(self): + return sm_ops.csr_sparse_matrix_to_dense(self._matrix, type=self.dtype) + + def to_sparse_tensor(self): + r = sm_ops.csr_sparse_matrix_to_sparse_tensor(self._matrix, type=self.dtype) + return sparse_tensor.SparseTensor( + indices=r.indices, values=r.values, dense_shape=r.dense_shape) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..10daa688d49ce268030212f756f1d42ba4152325 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_grad.py @@ -0,0 +1,1077 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in linalg_ops.py. + +Useful reference for derivative formulas is (Mike Giles, 2008). + +Ionescu et al. (2015) provide a detailed derivation of formulas for +backpropagating through spectral layers (SVD and Eig). + +References: + An extended collection of matrix derivative results for + forward and reverse mode automatic differentiation: + [Mike Giles, 2008] + (https://ora.ox.ac.uk/objects/uuid:8d0c0a29-c92b-4153-a1d2-38b276e93124) + ([pdf](http://eprints.maths.ox.ac.uk/1079/1/NA-08-01.pdf)) + Matrix Backpropagation for Deep Networks with Structured Layers + [Ionescu et al., 2015] + (https://www.cv-foundation.org/openaccess/content_iccv_2015/html/Ionescu_Matrix_Backpropagation_for_ICCV_2015_paper.html) + ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/Ionescu_Matrix_Backpropagation_for_ICCV_2015_paper.pdf)) + Training Deep Networks with Structured Layers by Matrix Backpropagation: + [Ionescu et al., 2015](https://arxiv.org/abs/1509.07838) + ([pdf](https://arxiv.org/pdf/1509.07838.pdf)) +""" +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl as _linalg + + +@ops.RegisterGradient("MatrixInverse") +def _MatrixInverseGrad(op: ops.Operation, grad): + """Gradient for MatrixInverse.""" + ainv = op.outputs[0] + op_adjoint = op.get_attr("adjoint") + return -math_ops.matmul( # pylint: disable=invalid-unary-operand-type + ainv, + math_ops.matmul(grad, ainv, adjoint_a=op_adjoint, + adjoint_b=not op_adjoint), + adjoint_a=not op_adjoint) + + +@ops.RegisterGradient("Einsum") +def _EinsumGrad(op: ops.Operation, grad): + """Gradient for Einsum.""" + ellipsis = "..." + + def _GetAxisFromLabel(subscripts, label): + """Returns the axis (possibly negative) corresponding to a label. + + Returns the axis index of the axis label if it is before an ellipsis (or if + the ellipsis is not present), and the negative index if it occurs after the + ellipsis. E.g. index of `b` in `ab...cd`, is `1`, but that of `c` is `-2`. + + For multiple occurrences, returns the leftmost one. If not found, returns + None. + + Args: + subscripts: A string denoting the einsum subscript (e.g. `ab...cd`) + label: The single character axis label. + """ + splits = subscripts.split(ellipsis) + index = splits[0].find(label) + if index != -1: + return index + if len(splits) < 2: + return None + index = splits[1].find(label) + if index != -1: + return index - len(splits[1]) + return None + + def _GetBcastSubshape(subscripts): + """Returns a tuple denoting the slice mapping to ellipsis. + + For a given subscript, returns a tuple (start, end) denoting the start + axis index and the (negative) end axis index respectively. For any input + Tensor `x` described by the subscript, `x[start:end]` would be the slice + represented by the ellipsis. E.g. For `ab...cd` returns `[1, -2]`. + + If ellipsis is not present in `subscripts`, returns `(0, 0)`. + + Args: + subscripts: A string denoting the einsum subscript. + """ + start = subscripts.find(ellipsis) + if start == -1: + return 0, 0 + remaining = len(subscripts) - (start + len(ellipsis)) + end = -remaining if remaining > 0 else None + return start, end + + def _GetReducedSubscripts(reduced_label_set, input_shape, subscripts): + """Returns reduced subscripts and their corresponding dimensions and axes. + + Given a set of axis labels, returns their concatenated subscript, their + corresponding dimensions from input_shape, and their corresponding axes. + Note that the concatenated subscript `reduced_subs` may have axis labels + from `reduced_label_set` in any order. For example, for the reduced label + set `{b, d}`, subscripts `aabbcd` and input shape `[2,2,5,5,3,4]`, returns + subscripts `bd`, dimensions `[5,4]` and axes `[2,5]`. + + Args: + reduced_label_set: Set of axis labels which appear in `subscripts`. + input_shape: A `Tensor` representing the shape of the einsum operand + corresponding to `subscripts`. + subscripts: A string denoting the einsum subscript. + + Returns: + reduced_subs: Subscripts formed by a concatenation of labels in + `reduced_label_set`. + reduced_dims: Dimensions from `input_shape` corresponding to each label + in `reduced_subs`. + reduced_axes: Axes described by `subscripts` corresponding to each label + in `reduced_subs`. If there are multiple occurrences in `subscripts`, + we consider only the leftmost one. + + """ + # Concatenate the sequence of reduced axis labels. + reduced_subs = "".join(list(reduced_label_set)) + # Get the axis (may be positive, negative or zero) for each of the reduced + # labels. If the same label appears multiple times, get the left-most axis. + reduced_axes = [_GetAxisFromLabel(subscripts, s) for s in reduced_subs] + # Get the corresponding dimensions for each reduced axis. + reduced_dims = array_ops_stack.stack( + [input_shape[ax] for ax in reduced_axes]) + return reduced_subs, reduced_dims, reduced_axes + + def _GetGradReduced(output_grad, output_subs, input_subs, input_shape, + reduced_label_set): + """Returns the gradient wrt input for a unary einsum with reductions. + + Args: + output_grad: The gradient wrt the output of a unary einsum operation. + output_subs: The output subscript. (E.g. `ac` for equation `abc->ac`). + input_subs: The input subscript. (E.g. `abc` for equation `abc->ac`). + input_shape: A `Tensor` representing the shape of the input operand. + reduced_label_set: The set of axis labels appearing in `input_subs` but + not in `output_subs`. + """ + # Let's say the einsum operation was "aabbcd->ca", where axis labels 'b' and + # 'd' are reduced with input_shape [2,2,5,5,3,4]. Then obtain the reduced + # subscripts "bd", corresponding dimensions [5,4] and axes [2,5]. + reduced_subs, reduced_dims, reduced_axes = _GetReducedSubscripts( + reduced_label_set, input_shape, input_subs) + # Whether either the input or the output subscripts have a repeated label. + # This is true for "aabbcd->ca" or "abd->cca" but false for "abcd->ca". + has_repeated_labels = ( + len(set(input_subs)) + len(set(output_subs)) < + len(input_subs) + len(output_subs)) + # Compute the input subscripts without the reduced axis labels, e.g. "aac" + # for the equation "aabbcd->ca". + input_subs_without_reduced_labels = "".join( + [s for s in input_subs if s not in reduced_label_set]) + + # The gradient wrt the input for the equation "abc->ac" (or, equivalently + # reduce_sum(..., axis=1)) is just the gradient of the output tiled N times + # along axis 1, where label 'b' represents a dimension of size N. + # + # If we're not dealing with repeated labels, and the non-reduced labels + # doesn't need to be transposed, then just tiling is enough and there is no + # need to call another einsum. For example, tiling is sufficient for + # "abcd->ac". But for equations like "aabbcd->ac" (generalized traces) or + # "abc->ca" (transpose), we'd need another einsum operation after tiling. + if (not has_repeated_labels and + input_subs_without_reduced_labels == output_subs): + # Obtain the shape of the output, as if keepdims=True on reduce sum. E.g. + # for the equation "abcd->ac" with input shape [2,5,3,4], we get the + # reduced shape [2,1,3,1]. + reduced_shape = math_ops.reduced_shape( + input_shape, ops.convert_to_tensor(reduced_axes)) + # Reshaping the gradient (wrt "ac") to [2,1,3,1] and broadcasting it to + # the shape [2,5,3,4] results in the gradient wrt "abcd". + return array_ops.broadcast_to( + array_ops.reshape(output_grad, reduced_shape), input_shape) + + # If we *do* have traces or transpose operations, then prepend the extra + # reduced dimensions to the front. E.g. Given the equation "aabbcd->ca" we'd + # first obtain the VJP for "bdca->ca", and then the VJP for "aabbcd->bdca". + # + # Obtain the input shape with reduced dimensions prepended, viz. [5,4,3,2]. + # This is the shape of the intermediate "bdca". + grad_shape_with_reduced_labels = array_ops.concat( + [reduced_dims, array_ops.shape(output_grad)], axis=0) + # Obtain the output shape of the reduction-only equation "bdca->ca" as if + # keepdims=True; viz. [1,1,3,2]. Since we prepended the reduced labels, we + # just have to prepend that many 1s to the output shape. + reduced_shape = ( + array_ops.concat([ + array_ops.ones(len(reduced_label_set), dtype=dtypes.int32), + array_ops.shape(output_grad) + ], + axis=0)) + # Compute the VJP for the intermediate (viz. "bdca->ca") for which + # broadcasting is sufficient. + broadcasted_grad = array_ops.broadcast_to( + array_ops.reshape(output_grad, reduced_shape), + grad_shape_with_reduced_labels) + # Compute the VJP for the final step (viz. "aabbcd->bdca"). We can use + # einsum with the input and output subscripts reversed (viz. "bdca->aabbcd") + # since the output axis labels now appear in the input subscripts. + return gen_linalg_ops.einsum([broadcasted_grad], + "{}->{}".format(reduced_subs + output_subs, + input_subs)) + + def _GetGradWrt(output_grad, other_operand, input_shape, input_subs, + other_subs, output_subs): + """Returns the gradient wrt an input operand for a binary einsum. + + This function does not handle (un)broadcasting. This must be done separately + on the returned gradient. + + Args: + output_grad: The gradient wrt the output of a binary einsum operation. + other_operand: The complementary `Tensor` operand i.e. which is not the + input operand. + input_shape: A `Tensor` representing the shape of input operand. + input_subs: The subscripts of the input operand. + other_subs: The subscripts of the complementary operand. + output_subs: The output subscripts. + """ + # Claim: For the einsum operation z = einsum("{eq_x},{eq_y}->{eq_z}", x, y), + # where the equation involves only Tensor contractions, generalized traces + # and transposes, the input gradients are given by the vector-jacobian + # products (VJPs): + # + # grad_wrt_x = einsum("{eq_y},{eq_z}->{eq_x}", y, grad_wrt_z) + # grad_wrt_y = einsum("{eq_x},{eq_z}->{eq_y}", x, grad_wrt_z} + # + # where grad_wrt_x and grad_wrt_y are the gradients with respect to inputs + # x and y and grad_wrt_z is the given gradient with respect to output z. + # + # Proof: For unary einsum equations involving only transpose ("ij->ji") and + # traces ("ii->i"), the linear mapping's Jacobian at input x is given + # by the function itself. We can verify that the linear map given by the + # VJP are einsums with the equations "ji->ij" and "i->ii" respectively, + # where the latter represents 'un-tracing', or filling the diagonal with + # the input axis and non-diagonal entries are zeros. + # Furthermore, recall that matrix multiplication, which is + # represented by the equation "ab,bc->ac", has its VJPs given by the + # einsum equations "ac,bc->ab" and "ab,ac->bc" (see, for example + # https://math.stackexchange.com/a/2755680). Combined with transposes and + # traces we can rewrite Tensor contractions as regular matrix + # multiplication. Since each of these operations have their VJPs described + # by einsums of the required pattern, the result follows. + # + # Accordingly, einsum operations except for those with reductions, e.g. + # "abc,cd->ad" have their VJPs defined by: + # "{output_subs},{other_subs}->{input_subs}". + # + # But if there is a reduction, this would lead to the equation "ad,cd->abc" + # which is invalid because the reduced axis label 'b' is present in the + # output but not in any of the inputs. Therefore, we compute the VJP in two + # steps: first we obtain VJP for "ac,cd->ad" and then we compute the VJP of + # "abc->ac" or, equivalently, reduce_sum(..., axis=1). + # + # Compute the set of input axis labels which doesn't appear in either the + # output subscripts or the other operand's subscript. E.g. the set {'b'} for + # the equation "abc,cd->ad". + reduced_label_set = set(input_subs).difference( + set(output_subs + other_subs + ".")) + # Obtain the input subscripts with the reduced axis labels removed. E.g. + # "ac" in the above example. + left_subs = "".join(s for s in input_subs if s not in reduced_label_set) + + # Compute the gradient wrt the input, without accounting for the operation + # "abc->ac". So, now we have the VJP of the operation "ac,cd->ad". + grad_reduced = gen_linalg_ops.einsum([output_grad, other_operand], + "{},{}->{}".format( + output_subs, other_subs, + left_subs)) + # If the reduced_label_set is empty, then we already have the gradient + # wrt the input. + if not reduced_label_set: + return grad_reduced + # Otherwise, we currently have the gradient wrt the output of the reduction + # operation "abc->ac". Invoke the subroutine for the gradient for unary + # einsum with reductions. + return _GetGradReduced(grad_reduced, left_subs, input_subs, input_shape, + reduced_label_set) + + equation = op.get_attr("equation") + if isinstance(equation, bytes): + equation = equation.decode() + input_subs, output_subs = equation.split("->") + + if len(op.inputs) == 1: + # For the unary einsum z = einsum("{eq_x}->{eq_z}", x), the gradient wrt the + # input (VJP) is given by the reversed equation: + # grad_wrt_x = einsum("{eq_z}->{eq_x}", grad_wrt_z) + # (See the justification in _GetGradWrt). This is valid unless there are + # reduced axis labels; i.e. axis labels appearing in the input but not in + # the output subscripts. + input_shape = array_ops.shape(op.inputs[0]) + # Find the axis labels which appear only in the input. + reduced_label_set = set(input_subs).difference(set(output_subs + ellipsis)) + if not reduced_label_set: + # Return the einsum given by the reversed equation, since we don't have + # reduced axes. + return gen_linalg_ops.einsum([grad], + "{}->{}".format(output_subs, input_subs)) + # We do have reduced axes, so we invoke the subroutine for reduced unary + # einsums. + return _GetGradReduced(grad, output_subs, input_subs, input_shape, + reduced_label_set) + + x_subs, y_subs = input_subs.split(",") + # Add ellipsis for broadcasted dimensions if any operand does not have it. + # This is because the equation "...ij,jk->ik" may be valid if the 0th input's + # batch shape is empty, but the VJP equation "jk,ik->...ij" is not valid + # because only the output subscripts contain ellipsis. + if ellipsis in output_subs: + if ellipsis not in x_subs: + x_subs += ellipsis + if ellipsis not in y_subs: + y_subs += ellipsis + + # Obtain the gradients wrt the inputs x and y, without taking into account + # the unbroadcasting. + x, y = op.inputs[0], op.inputs[1] + if grad.dtype.is_complex: + x = math_ops.conj(x) + y = math_ops.conj(y) + + x_shape = array_ops.shape(x) + y_shape = array_ops.shape(y) + grad_x = _GetGradWrt(grad, y, x_shape, x_subs, y_subs, output_subs) + grad_y = _GetGradWrt(grad, x, y_shape, y_subs, x_subs, output_subs) + + if ellipsis not in output_subs: + # If no ellipsis in the output; then no need to unbroadcast. + return grad_x, grad_y + + # Below we handle the case that broadcasting between x and y was necessary, + # with x and y having possibly different batch shapes. + + # Obtain the range of axes which map to ellipsis. E.g. for subscripts 'ab...c' + # and shape of rank 10; the range [3:-1] denotes the broadcasted axes. + bx_start, bx_end = _GetBcastSubshape(x_subs) + by_start, by_end = _GetBcastSubshape(y_subs) + # If the static batch shapes are equal, we don't need to unbroadcast. + x_shape_static = x.get_shape() + y_shape_static = y.get_shape() + if (x_shape_static.is_fully_defined() and + y_shape_static.is_fully_defined() and + x_shape_static[bx_start:bx_end] == y_shape_static[by_start:by_end]): + return grad_x, grad_y + + # Sum the gradient across the broadcasted axes. + rx, ry = array_ops.broadcast_gradient_args(x_shape[bx_start:bx_end], + y_shape[by_start:by_end]) + grad_x = array_ops.reshape( + math_ops.reduce_sum(grad_x, bx_start + rx), x_shape) + grad_y = array_ops.reshape( + math_ops.reduce_sum(grad_y, by_start + ry), y_shape) + return grad_x, grad_y + + +@ops.RegisterGradient("MatrixDeterminant") +def _MatrixDeterminantGrad(op: ops.Operation, grad): + """Gradient for MatrixDeterminant.""" + a = op.inputs[0] + c = op.outputs[0] + a_adj_inv = linalg_ops.matrix_inverse(a, adjoint=True) + multipliers = array_ops.reshape(grad * c, + array_ops.concat([array_ops.shape(c), [1, 1]], + 0)) + return multipliers * a_adj_inv + + +@ops.RegisterGradient("MatrixSquareRoot") +def _MatrixSquareRootGrad(op: ops.Operation, grad): + """Gradient for MatrixSquareRoot.""" + + # Let A be an m x m square matrix (or batch of matrices) + # Let R = sqrtm(A) + # By definition, A = RR + # Take the differential: dA = d(RR) = RdR + dRR + # Solve the resulting Sylvester equation for dR + + # Used to find Kronecker products within the Sylvester equation + def _KroneckerProduct(b1, b2): + """Computes the Kronecker product of two batches of square matrices.""" + b1_shape = array_ops.shape(b1) + b2_shape = array_ops.shape(b2) + b1_order = b1_shape[-1] + b2_order = b2_shape[-1] + + shape_slice_size = [math_ops.subtract(array_ops.size(b1_shape), 2)] + shape_slice = array_ops.slice(b1_shape, [0], + shape_slice_size) # Same for both batches + b1_reshape_shape = array_ops.concat( + [shape_slice, [b1_order], [1], [b1_order], [1]], 0) + b2_reshape_shape = array_ops.concat( + [shape_slice, [1], [b2_order], [1], [b2_order]], 0) + + b1_reshape = array_ops.reshape(b1, b1_reshape_shape) + b2_reshape = array_ops.reshape(b2, b2_reshape_shape) + + order_prod = b1_order * b2_order + kprod_shape = array_ops.concat([shape_slice, [order_prod], [order_prod]], 0) + return array_ops.reshape(b1_reshape * b2_reshape, kprod_shape) + + sqrtm = op.outputs[0] # R + shape = array_ops.shape(sqrtm) + order = shape[-1] # m + matrix_count = math_ops.reduce_prod(shape[0:-2]) + + # Get batch of m x m identity matrices + eye = linalg_ops.eye(order, dtype=sqrtm.dtype) # m x m identity matrix + eye_flat = array_ops.reshape(eye, [-1]) + eye_tiled = array_ops.tile(eye_flat, [matrix_count]) + eye_batch = array_ops.reshape(eye_tiled, shape) + + # The transpose of R is taken in the k1 term instead of k2 in + # order to prevent redundant transposition of R (i.e. (R')' = R) + sqrtm_transpose = array_ops.matrix_transpose(sqrtm) + k1 = _KroneckerProduct(eye_batch, sqrtm_transpose) + k2 = _KroneckerProduct(sqrtm, eye_batch) + ksum = math_ops.add(k1, k2) + + # Vectorize dA + shape_slice_size = [math_ops.subtract(array_ops.size(shape), 2)] + shape_slice = array_ops.slice(shape, [0], shape_slice_size) + shape_vec_da = array_ops.concat([shape_slice, [order * order], [1]], 0) + vec_da = array_ops.reshape(array_ops.matrix_transpose(grad), shape_vec_da) + + # Solve for vec(dR) + vec_dsqrtm = linalg_ops.matrix_solve(ksum, vec_da) + + # Solve for dR by inverse vectorizing vec(dR) + dsqrtm_transpose = array_ops.reshape(vec_dsqrtm, shape) + return array_ops.matrix_transpose(dsqrtm_transpose) + + +@ops.RegisterGradient("LogMatrixDeterminant") +def _LogMatrixDeterminantGrad(op: ops.Operation, _, grad_b): + """Gradient for LogMatrixDeterminant.""" + a = op.inputs[0] + c = op.outputs[1] + a_adj_inv = linalg_ops.matrix_inverse(a, adjoint=True) + multipliers = array_ops.reshape( + grad_b, array_ops.concat([array_ops.shape(c), [1, 1]], 0)) + return multipliers * a_adj_inv + + +@ops.RegisterGradient("Cholesky") +def _CholeskyGrad(op: ops.Operation, grad): + """Gradient for Cholesky.""" + + # Gradient is l^{-H} @ ((l^{H} @ grad) * (tril(ones)-1/2*eye)) @ l^{-1} + l = op.outputs[0] + num_rows = array_ops.shape(l)[-1] + batch_shape = array_ops.shape(l)[:-2] + l_inverse = linalg_ops.matrix_triangular_solve(l, + linalg_ops.eye( + num_rows, + batch_shape=batch_shape, + dtype=l.dtype)) + + middle = math_ops.matmul(l, grad, adjoint_a=True) + middle = array_ops.matrix_set_diag(middle, + 0.5 * array_ops.matrix_diag_part(middle)) + middle = array_ops.matrix_band_part(middle, -1, 0) + + grad_a = math_ops.matmul( + math_ops.matmul(l_inverse, middle, adjoint_a=True), l_inverse) + + grad_a += _linalg.adjoint(grad_a) + return grad_a * 0.5 + + +@ops.RegisterGradient("Qr") +def _QrGrad(op: ops.Operation, dq, dr): + """Gradient for Qr.""" + + # The methodology is explained in detail in https://arxiv.org/abs/2009.10071 + # QR and LQ Decomposition Matrix Backpropagation Algorithms for + # Square, Wide, and Deep, Real and Complex, Matrices and Their Software + # Implementation + q, r = op.outputs + if (r.shape.ndims is None or r.shape.as_list()[-2] is None or + r.shape.as_list()[-1] is None): + raise NotImplementedError("QrGrad not implemented with dynamic shapes. " + f"Received r.shape: {r.shape}") + if (r.shape.dims[-2].value > r.shape.dims[-1].value and + q.shape.dims[-2].value == q.shape.dims[-1].value): + raise NotImplementedError("QrGrad not implemented when nrows > ncols " + "and full_matrices is true. Received r.shape=" + f"{r.shape} with nrows={r.shape.dims[-2]}" + f"and ncols={r.shape.dims[-1]}.") + + def _TriangularSolve(x, r): + """Equiv to matmul(x, adjoint(matrix_inverse(r))) if r is upper-tri.""" + return _linalg.adjoint( + linalg_ops.matrix_triangular_solve( + r, _linalg.adjoint(x), lower=False, adjoint=False)) + + def _QrGradSquareAndDeepMatrices(q, r, dq, dr): + """Gradient for matrix orders num_rows >= num_cols + and full_matrices is false. + """ + qdq = math_ops.matmul(q, dq, adjoint_a=True) + qdq_ = qdq - _linalg.adjoint(qdq) + rdr = math_ops.matmul(r, dr, adjoint_b=True) + rdr_ = rdr - _linalg.adjoint(rdr) + tril = array_ops.matrix_band_part(qdq_ + rdr_, -1, 0) + + grad_a = math_ops.matmul(q, dr + _TriangularSolve(tril, r)) + grad_b = _TriangularSolve(dq - math_ops.matmul(q, qdq), r) + ret = grad_a + grad_b + + if q.dtype.is_complex: + # need to add a correction to the gradient formula for complex case + m = rdr - _linalg.adjoint(qdq) + eyem = _linalg.set_diag(array_ops.zeros_like(m), _linalg.diag_part(m)) + correction = eyem - math_ops.cast(math_ops.real(eyem), q.dtype) + ret = ret + _TriangularSolve( + math_ops.matmul(q, _linalg.adjoint(correction)), r) + + return ret + + num_rows, num_cols = q.shape.dims[-2].value, r.shape.dims[-1] + + if num_rows >= num_cols: + return _QrGradSquareAndDeepMatrices(q, r, dq, dr) + + # Partition a = [x, y], r = [u, v] and reduce to the square case + a = op.inputs[0] + y = a[..., :, num_rows:] + u = r[..., :, :num_rows] + dv = dr[..., :, num_rows:] + du = dr[..., :, :num_rows] + dy = math_ops.matmul(q, dv) + dx = _QrGradSquareAndDeepMatrices(q, u, + dq + math_ops.matmul(y, dv, adjoint_b=True), + du) + return array_ops.concat([dx, dy], axis=-1) + + +@ops.RegisterGradient("MatrixSolve") +def _MatrixSolveGrad(op: ops.Operation, grad): + """Gradient for MatrixSolve.""" + a = op.inputs[0] + adjoint_a = op.get_attr("adjoint") + c = op.outputs[0] + grad_b = linalg_ops.matrix_solve(a, grad, adjoint=not adjoint_a) + if adjoint_a: + grad_a = -math_ops.matmul(c, grad_b, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + else: + grad_a = -math_ops.matmul(grad_b, c, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + return (grad_a, grad_b) + + +@ops.RegisterGradient("MatrixSolveLs") +def _MatrixSolveLsGrad(op: ops.Operation, grad): + """Gradients for MatrixSolveLs.""" + + # TODO(rmlarsen): The implementation could be more efficient: + # a) Output the Cholesky factorization from forward op instead of + # recomputing it here. + # b) Implement a symmetric rank-k update op instead of computing + # x*z + transpose(x*z). This pattern occurs other places in TensorFlow. + # pylint: disable=g-doc-args + def _Overdetermined(op: ops.Operation, grad): + """Gradients for the overdetermined case of MatrixSolveLs. + + This is the backprop for the solution to the normal equations of the first + kind: + X = F(A, B) = (A^T * A + lambda * I)^{-1} * A^T * B + which solve the least squares problem + min ||A * X - B||_F^2 + lambda ||X||_F^2. + """ + a = op.inputs[0] + b = op.inputs[1] + x = op.outputs[0] + l2_regularizer = math_ops.cast(op.inputs[2], a.dtype.base_dtype) + # pylint: disable=protected-access + chol = linalg_ops._RegularizedGramianCholesky( + a, l2_regularizer=l2_regularizer, first_kind=True) + # pylint: enable=protected-access + # Temporary z = (A^T * A + lambda * I)^{-1} * grad. + z = linalg_ops.cholesky_solve(chol, grad) + xzt = math_ops.matmul(x, z, adjoint_b=True) + zx_sym = xzt + array_ops.matrix_transpose(xzt) + grad_a = -math_ops.matmul(a, zx_sym) + math_ops.matmul(b, z, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + grad_b = math_ops.matmul(a, z) + return (grad_a, grad_b, None) + + # pylint: disable=g-doc-args + def _Underdetermined(op: ops.Operation, grad): + """Gradients for the underdetermined case of MatrixSolveLs. + + This is the backprop for the solution to the normal equations of the second + kind: + X = F(A, B) = A * (A*A^T + lambda*I)^{-1} * B + that (for lambda=0) solve the least squares problem + min ||X||_F subject to A*X = B. + """ + a = op.inputs[0] + b = op.inputs[1] + l2_regularizer = math_ops.cast(op.inputs[2], a.dtype.base_dtype) + # pylint: disable=protected-access + chol = linalg_ops._RegularizedGramianCholesky( + a, l2_regularizer=l2_regularizer, first_kind=False) + # pylint: enable=protected-access + grad_b = linalg_ops.cholesky_solve(chol, math_ops.matmul(a, grad)) + # Temporary tmp = (A * A^T + lambda * I)^{-1} * B. + tmp = linalg_ops.cholesky_solve(chol, b) + a1 = math_ops.matmul(tmp, a, adjoint_a=True) + a1 = -math_ops.matmul(grad_b, a1) # pylint: disable=invalid-unary-operand-type + a2 = grad - math_ops.matmul(a, grad_b, adjoint_a=True) + a2 = math_ops.matmul(tmp, a2, adjoint_b=True) + grad_a = a1 + a2 + return (grad_a, grad_b, None) + + fast = op.get_attr("fast") + if fast is False: + raise ValueError("Gradient not defined for fast=False") + matrix_shape = op.inputs[0].get_shape()[-2:] + if matrix_shape.is_fully_defined(): + if matrix_shape[-2] >= matrix_shape[-1]: + return _Overdetermined(op, grad) + else: + return _Underdetermined(op, grad) + else: + # We have to defer determining the shape to runtime and use + # conditional execution of the appropriate graph. + matrix_shape = array_ops.shape(op.inputs[0])[-2:] + return cond.cond(matrix_shape[-2] >= matrix_shape[-1], + lambda: _Overdetermined(op, grad), + lambda: _Underdetermined(op, grad)) + + +@ops.RegisterGradient("BandedTriangularSolve") +def _BandedTriangularSolveGrad(op: ops.Operation, grad): + """Gradient for BandedTriangularSolve.""" + a = op.inputs[0] + b = op.inputs[1] + num_bands = array_ops.shape(a)[-2] + adjoint_a = op.get_attr("adjoint") + lower_a = op.get_attr("lower") + c = op.outputs[0] + grad_b = linalg_ops.banded_triangular_solve( + a, grad, lower=lower_a, adjoint=not adjoint_a) + if adjoint_a: + grad_a = -math_ops.matmul(c, grad_b, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + else: + grad_a = -math_ops.matmul(grad_b, c, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + if lower_a: + grad_a = array_ops.matrix_diag_part( + grad_a, k=(-(num_bands - 1), 0), align="LEFT_RIGHT") + else: + grad_a = array_ops.matrix_diag_part( + grad_a, k=(0, num_bands - 1), align="LEFT_RIGHT") + # If the static batch shapes are equal, we don't need to unbroadcast. + if (a.shape.is_fully_defined() and b.shape.is_fully_defined() and + a.shape[:-2] == b.shape[:-2]): + return grad_a, grad_b + a_shape = array_ops.shape(a) + b_shape = array_ops.shape(b) + ra, rb = array_ops.broadcast_gradient_args(a_shape[:-2], b_shape[:-2]) + grad_a = array_ops.reshape(math_ops.reduce_sum(grad_a, axis=ra), a_shape) + grad_b = array_ops.reshape(math_ops.reduce_sum(grad_b, axis=rb), b_shape) + return grad_a, grad_b + + +@ops.RegisterGradient("MatrixTriangularSolve") +def _MatrixTriangularSolveGrad(op: ops.Operation, grad): + """Gradient for MatrixTriangularSolve.""" + a = op.inputs[0] + b = op.inputs[1] + adjoint_a = op.get_attr("adjoint") + lower_a = op.get_attr("lower") + c = op.outputs[0] + grad_b = linalg_ops.matrix_triangular_solve( + a, grad, lower=lower_a, adjoint=not adjoint_a) + if adjoint_a: + grad_a = -math_ops.matmul(c, grad_b, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + else: + grad_a = -math_ops.matmul(grad_b, c, adjoint_b=True) # pylint: disable=invalid-unary-operand-type + if lower_a: + grad_a = array_ops.matrix_band_part(grad_a, -1, 0) + else: + grad_a = array_ops.matrix_band_part(grad_a, 0, -1) + # If the static batch shapes are equal, we don't need to unbroadcast. + if (a.shape.is_fully_defined() and b.shape.is_fully_defined() and + a.shape[:-2] == b.shape[:-2]): + return grad_a, grad_b + a_shape = array_ops.shape(a) + b_shape = array_ops.shape(b) + ra, rb = array_ops.broadcast_gradient_args(a_shape[:-2], b_shape[:-2]) + grad_a = array_ops.reshape(math_ops.reduce_sum(grad_a, axis=ra), a_shape) + grad_b = array_ops.reshape(math_ops.reduce_sum(grad_b, axis=rb), b_shape) + return grad_a, grad_b + + +# To avoid nan in cases with degenerate eigenvalues or +# degenerate/zero singular values in calculations of +# f and s_inv_mat, we introduce a Lorentz broadening. +def _SafeReciprocal(x, epsilon=1e-20): + return x * math_ops.reciprocal(x * x + epsilon) + + +# pylint: disable=g-doc-args +@ops.RegisterGradient("Eig") +def _EigGrad(op: ops.Operation, grad_e, grad_v): + """Gradient for Eig. + + Based on eq. 4.77 from paper by + Christoph Boeddeker et al. + https://arxiv.org/abs/1701.00392 + See also + "Computation of eigenvalue and eigenvector derivatives + for a general complex-valued eigensystem" by Nico van der Aa. + As for now only distinct eigenvalue case is considered. + """ + e = op.outputs[0] + compute_v = op.get_attr("compute_v") + # a = op.inputs[0], which satisfies + # a[...,:,:] * v[...,:,i] = e[...,i] * v[...,i] + with ops.control_dependencies([grad_e, grad_v]): + if compute_v: + v = op.outputs[1] + vt = _linalg.adjoint(v) + # Construct the matrix f(i,j) = (i != j ? 1 / (e_i - e_j) : 0). + # Notice that because of the term involving f, the gradient becomes + # infinite (or NaN in practice) when eigenvalues are not unique. + # Mathematically this should not be surprising, since for (k-fold) + # degenerate eigenvalues, the corresponding eigenvectors are only defined + # up to arbitrary rotation in a (k-dimensional) subspace. + f = array_ops.matrix_set_diag( + _SafeReciprocal( + array_ops.expand_dims(e, -2) - array_ops.expand_dims(e, -1)), + array_ops.zeros_like(e)) + f = math_ops.conj(f) + vgv = math_ops.matmul(vt, grad_v) + mid = array_ops.matrix_diag(grad_e) + diag_grad_part = array_ops.matrix_diag( + array_ops.matrix_diag_part( + math_ops.cast(math_ops.real(vgv), vgv.dtype))) + mid += f * (vgv - math_ops.matmul(math_ops.matmul(vt, v), diag_grad_part)) + # vt is formally invertible as long as the original matrix is + # diagonalizable. However, in practice, vt may + # be ill-conditioned when matrix original matrix is close to + # non-diagonalizable one + grad_a = linalg_ops.matrix_solve(vt, math_ops.matmul(mid, vt)) + else: + _, v = linalg_ops.eig(op.inputs[0]) + vt = _linalg.adjoint(v) + # vt is formally invertible as long as the original matrix is + # diagonalizable. However, in practice, vt may + # be ill-conditioned when matrix original matrix is close to + # non-diagonalizable one + grad_a = linalg_ops.matrix_solve( + vt, math_ops.matmul(array_ops.matrix_diag(grad_e), vt)) + return math_ops.cast(grad_a, op.inputs[0].dtype) + + +@ops.RegisterGradient("SelfAdjointEigV2") +def _SelfAdjointEigV2Grad(op: ops.Operation, grad_e, grad_v): + """Gradient for SelfAdjointEigV2.""" + e = op.outputs[0] + compute_v = op.get_attr("compute_v") + # a = op.inputs[0], which satisfies + # a[...,:,:] * v[...,:,i] = e[...,i] * v[...,i] + with ops.control_dependencies([grad_e, grad_v]): + if compute_v: + v = op.outputs[1] + # Construct the matrix f(i,j) = (i != j ? 1 / (e_i - e_j) : 0). + # Notice that because of the term involving f, the gradient becomes + # infinite (or NaN in practice) when eigenvalues are not unique. + # Mathematically this should not be surprising, since for (k-fold) + # degenerate eigenvalues, the corresponding eigenvectors are only defined + # up to arbitrary rotation in a (k-dimensional) subspace. + f = array_ops.matrix_set_diag( + _SafeReciprocal( + array_ops.expand_dims(e, -2) - array_ops.expand_dims(e, -1)), + array_ops.zeros_like(e)) + grad_a = math_ops.matmul( + v, + math_ops.matmul( + array_ops.matrix_diag(grad_e) + + f * math_ops.matmul(v, grad_v, adjoint_a=True), + v, + adjoint_b=True)) + else: + _, v = linalg_ops.self_adjoint_eig(op.inputs[0]) + grad_a = math_ops.matmul(v, + math_ops.matmul( + array_ops.matrix_diag(grad_e), + v, + adjoint_b=True)) + # The forward op only depends on the lower triangular part of a, so here we + # symmetrize and take the lower triangle + grad_a = array_ops.matrix_band_part(grad_a + _linalg.adjoint(grad_a), -1, 0) + grad_a = array_ops.matrix_set_diag(grad_a, + 0.5 * array_ops.matrix_diag_part(grad_a)) + return grad_a + + +@ops.RegisterGradient("Svd") +def _SvdGrad(op: ops.Operation, grad_s, grad_u, grad_v): + """Gradient for the singular value decomposition.""" + + # The derivation for the compute_uv=False case, and most of + # the derivation for the full_matrices=True case, are in + # Giles' paper (see reference at top of file). A derivation for + # the full_matrices=False case is available at + # https://j-towns.github.io/papers/svd-derivative.pdf + # The derivation for complex valued SVD can be found in + # https://re-ra.xyz/misc/complexsvd.pdf or + # https://giggleliu.github.io/2019/04/02/einsumbp.html + a = op.inputs[0] + a_shape = a.get_shape().with_rank_at_least(2) + grad_s = math_ops.cast(grad_s, a.dtype) + grad_s_mat = array_ops.matrix_diag(grad_s) + + if not op.get_attr("compute_uv"): + s, u, v = linalg_ops.svd(a, compute_uv=True) + grad_a = math_ops.matmul(u, math_ops.matmul(grad_s_mat, v, adjoint_b=True)) + grad_a.set_shape(a_shape) + return grad_a + + full_matrices = op.get_attr("full_matrices") + + grad_u_shape = grad_u.get_shape().with_rank_at_least(2) + grad_v_shape = grad_v.get_shape().with_rank_at_least(2) + m = a_shape.dims[-2].merge_with(grad_u_shape[-2]) + n = a_shape.dims[-1].merge_with(grad_v_shape[-2]) + batch_shape = a_shape[:-2].merge_with(grad_u_shape[:-2]).merge_with( + grad_v_shape[:-2]) + a_shape = batch_shape.concatenate([m, n]) + + m = a_shape.dims[-2].value + n = a_shape.dims[-1].value + # TODO(rmlarsen): Make this work with placeholders. + if m is None or n is None: + raise NotImplementedError( + "SVD gradient has not been implemented for input with unknown " + "inner matrix shape.") + + s = op.outputs[0] + u = op.outputs[1] + v = op.outputs[2] + s = math_ops.cast(s, a.dtype) + + use_adjoint = False + if m > n: + # Compute the gradient for A^H = V * S^T * U^H, and (implicitly) take the + # Hermitian transpose of the gradient at the end. + use_adjoint = True + m, n = n, m + u, v = v, u + grad_u, grad_v = grad_v, grad_u + + with ops.control_dependencies([grad_s, grad_u, grad_v]): + if full_matrices and abs(m - n) > 1: + raise NotImplementedError( + "svd gradient is not implemented for abs(m - n) > 1 " + f"when full_matrices is True. Received: m={m} and n={n} from " + f"op input={a} with shape={a_shape}.") + s_mat = array_ops.matrix_diag(s) + s2 = math_ops.square(s) + + # NOTICE: Because of the term involving f, the gradient becomes + # infinite (or NaN in practice) when singular values are not unique. + # Mathematically this should not be surprising, since for (k-fold) + # degenerate singular values, the corresponding singular vectors are + # only defined up a (k-dimensional) subspace. In practice, this can + # lead to numerical instability when singular values are close but not + # exactly equal. + + s_shape = array_ops.shape(s) + f = array_ops.matrix_set_diag( + _SafeReciprocal( + array_ops.expand_dims(s2, -2) - array_ops.expand_dims(s2, -1)), + array_ops.zeros_like(s)) + s_inv_mat = array_ops.matrix_diag(_SafeReciprocal(s)) + + v1 = v[..., :, :m] + grad_v1 = grad_v[..., :, :m] + + u_gu = math_ops.matmul(u, grad_u, adjoint_a=True) + v_gv = math_ops.matmul(v1, grad_v1, adjoint_a=True) + + f_u = f * u_gu + f_v = f * v_gv + + term1_nouv = ( + grad_s_mat + math_ops.matmul(f_u + _linalg.adjoint(f_u), s_mat) + + math_ops.matmul(s_mat, f_v + _linalg.adjoint(f_v))) + + term1 = math_ops.matmul(u, math_ops.matmul(term1_nouv, v1, adjoint_b=True)) + + if m == n: + grad_a_before_transpose = term1 + else: + gv1t = array_ops.matrix_transpose(grad_v1, conjugate=True) + gv1t_v1 = math_ops.matmul(gv1t, v1) + term2_nous = gv1t - math_ops.matmul(gv1t_v1, v1, adjoint_b=True) + + if full_matrices: + v2 = v[..., :, m:n] + grad_v2 = grad_v[..., :, m:n] + + v1t_gv2 = math_ops.matmul(v1, grad_v2, adjoint_a=True) + term2_nous -= math_ops.matmul(v1t_gv2, v2, adjoint_b=True) + + u_s_inv = math_ops.matmul(u, s_inv_mat) + term2 = math_ops.matmul(u_s_inv, term2_nous) + + grad_a_before_transpose = term1 + term2 + + if a.dtype.is_complex: + eye = _linalg.eye(s_shape[-1], batch_shape=s_shape[:-1], dtype=a.dtype) + l = eye * v_gv + term3_nouv = math_ops.matmul(s_inv_mat, _linalg.adjoint(l) - l) + term3 = 1 / 2. * math_ops.matmul( + u, math_ops.matmul(term3_nouv, v1, adjoint_b=True)) + + grad_a_before_transpose += term3 + + if use_adjoint: + grad_a = array_ops.matrix_transpose( + grad_a_before_transpose, conjugate=True) + else: + grad_a = grad_a_before_transpose + + grad_a.set_shape(a_shape) + return grad_a + + +def _LeftShift(x): + """Shifts next-to-last dimension to the left, adding zero on the right.""" + rank = array_ops.rank(x) + zeros = array_ops.zeros((rank - 2, 2), dtype=dtypes.int32) + pad = array_ops.concat([zeros, array_ops.constant([[0, 1], [0, 0]])], axis=0) + return array_ops.pad(x[..., 1:, :], pad) + + +def _RightShift(x): + """Shifts next-to-last dimension to the right, adding zero on the left.""" + rank = array_ops.rank(x) + zeros = array_ops.zeros((rank - 2, 2), dtype=dtypes.int32) + pad = array_ops.concat([zeros, array_ops.constant([[1, 0], [0, 0]])], axis=0) + return array_ops.pad(x[..., :-1, :], pad) + + +@ops.RegisterGradient("TridiagonalMatMul") +def _TridiagonalMatMulGrad(op: ops.Operation, grad): + """Gradient for TridiagonalMatMul.""" + superdiag_conj = array_ops.matrix_transpose(op.inputs[0], conjugate=True) + maindiag_conj = array_ops.matrix_transpose(op.inputs[1], conjugate=True) + subdiag_conj = array_ops.matrix_transpose(op.inputs[2], conjugate=True) + rhs_conj = math_ops.conj(op.inputs[3]) + + superdiag_grad = math_ops.reduce_sum(_LeftShift(rhs_conj) * grad, axis=-1) + maindiag_grad = math_ops.reduce_sum(rhs_conj * grad, axis=-1) + subdiag_grad = math_ops.reduce_sum(_RightShift(rhs_conj) * grad, axis=-1) + rhs_grad = _RightShift(superdiag_conj * grad) + \ + maindiag_conj * grad + _LeftShift(subdiag_conj * grad) + + superdiag_grad = array_ops.expand_dims(superdiag_grad, -2) + maindiag_grad = array_ops.expand_dims(maindiag_grad, -2) + subdiag_grad = array_ops.expand_dims(subdiag_grad, -2) + + return superdiag_grad, maindiag_grad, subdiag_grad, rhs_grad + + +@ops.RegisterGradient("TridiagonalSolve") +def _TridiagonalSolveGrad(op: ops.Operation, grad): + """Gradient for TridiagonalSolveGrad.""" + diags = op.inputs[0] + x = op.outputs[0] + partial_pivoting = op.get_attr("partial_pivoting") + perturb_singular = op.get_attr("perturb_singular") + + # Transposing the matrix within tridiagonal_solve kernel by interchanging + # superdiagonal and subdiagonal wouldn't work on GPU due to mismatch with + # paddings required by cusparse*gtsv routines. + # So constructing the transposed matrix in Python. + diags_transposed = _TransposeTridiagonalMatrix(diags) + + grad_rhs = linalg_ops.tridiagonal_solve( + diags_transposed, + grad, + partial_pivoting=partial_pivoting, + perturb_singular=perturb_singular) + grad_diags = -_MatmulExtractingThreeDiagonals(grad_rhs, x) # pylint: disable=invalid-unary-operand-type + return grad_diags, grad_rhs + + +def _TransposeTridiagonalMatrix(diags): + """Transposes a tridiagonal matrix. + + Args: + diags: the diagonals of the input matrix in the compact form (see + linalg_ops.tridiagonal_solve). + + Returns: + Diagonals of the transposed matrix in the compact form. + """ + + diag = diags[..., 1, :] + + if diags.shape.is_fully_defined(): + # For fully defined tensor we can concat with a tensor of zeros, which is + # faster than using array_ops.pad(). + zeros = array_ops.zeros(list(diags.shape[:-2]) + [1], dtype=diags.dtype) + superdiag = array_ops.concat((diags[..., 2, 1:], zeros), axis=-1) + subdiag = array_ops.concat((zeros, diags[..., 0, :-1]), axis=-1) + else: + rank = array_ops.rank(diags) + zeros = array_ops.zeros((rank - 2, 2), dtype=dtypes.int32) + superdiag_pad = array_ops.concat((zeros, array_ops.constant([[0, 1]])), + axis=0) + superdiag = array_ops.pad(diags[..., 2, 1:], superdiag_pad) + subdiag_pad = array_ops.concat((zeros, array_ops.constant([[1, 0]])), + axis=0) + subdiag = array_ops.pad(diags[..., 0, :-1], subdiag_pad) + return array_ops_stack.stack([superdiag, diag, subdiag], axis=-2) + + +def _MatmulExtractingThreeDiagonals(x, y_tr): + """Multiplies matrices and extracts three diagonals from the product. + + With sizes M x K and K x M, this function takes O(MK) time and O(M) space, + while using math_ops.matmul, and then extracting the diagonals would take + O(M^2 K) time and O(M^2) space. + + Args: + x: first matrix + y_tr: second matrix transposed + + Returns: + Diagonals of the product in compact format (see + linalg_ops.tridiagonal_solve) + + """ + diag = math_ops.reduce_sum(x * y_tr, axis=-1) + + if y_tr.shape.is_fully_defined(): + zeros = array_ops.zeros( + list(x.shape[:-2]) + [1, x.shape[-1]], dtype=x.dtype) + superdiag = math_ops.reduce_sum( + x * array_ops.concat((y_tr[..., 1:, :], zeros), axis=-2), axis=-1) + subdiag = math_ops.reduce_sum( + x * array_ops.concat((zeros, y_tr[..., :-1, :]), axis=-2), axis=-1) + else: + rank = array_ops.rank(y_tr) + zeros = array_ops.zeros((rank - 2, 2), dtype=dtypes.int32) + superdiag_pad = array_ops.concat( + (zeros, array_ops.constant([[0, 1], [0, 0]])), axis=0) + superdiag = math_ops.reduce_sum( + x * array_ops.pad(y_tr[..., 1:, :], superdiag_pad), axis=-1) + subdiag_pad = array_ops.concat( + (zeros, array_ops.constant([[1, 0], [0, 0]])), axis=0) + subdiag = math_ops.reduce_sum( + x * array_ops.pad(y_tr[..., :-1, :], subdiag_pad), axis=-1) + return array_ops_stack.stack([superdiag, diag, subdiag], axis=-2) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e6463390cbb736125ca0255266d3c67d9d1a84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops.py @@ -0,0 +1,791 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for linear algebra. + +API docstring: tensorflow.linalg +""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops_impl +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_linalg_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +# Names below are lower_case. +# pylint: disable=invalid-name + + +def _RegularizedGramianCholesky(matrix, l2_regularizer, first_kind): + r"""Computes Cholesky factorization of regularized gramian matrix. + + Below we will use the following notation for each pair of matrix and + right-hand sides in the batch: + + `matrix`=\\(A \in \Re^{m \times n}\\), + `output`=\\(C \in \Re^{\min(m, n) \times \min(m,n)}\\), + `l2_regularizer`=\\(\lambda\\). + + If `first_kind` is True, returns the Cholesky factorization \\(L\\) such that + \\(L L^H = A^H A + \lambda I\\). + If `first_kind` is False, returns the Cholesky factorization \\(L\\) such that + \\(L L^H = A A^H + \lambda I\\). + + Args: + matrix: `Tensor` of shape `[..., M, N]`. + l2_regularizer: 0-D `double` `Tensor`. Ignored if `fast=False`. + first_kind: bool. Controls what gramian matrix to factor. + Returns: + output: `Tensor` of shape `[..., min(M,N), min(M,N)]` whose inner-most 2 + dimensions contain the Cholesky factors \\(L\\) described above. + """ + + gramian = math_ops.matmul( + matrix, matrix, adjoint_a=first_kind, adjoint_b=not first_kind) + if isinstance(l2_regularizer, tensor_lib.Tensor) or l2_regularizer != 0: + matrix_shape = array_ops.shape(matrix) + batch_shape = matrix_shape[:-2] + if first_kind: + small_dim = matrix_shape[-1] + else: + small_dim = matrix_shape[-2] + identity = eye(small_dim, batch_shape=batch_shape, dtype=matrix.dtype) + small_dim_static = matrix.shape[-1 if first_kind else -2] + identity.set_shape( + matrix.shape[:-2].concatenate([small_dim_static, small_dim_static])) + gramian += l2_regularizer * identity + return gen_linalg_ops.cholesky(gramian) + + +@tf_export( + 'linalg.triangular_solve', + v1=['linalg.triangular_solve', 'matrix_triangular_solve']) +@dispatch.add_dispatch_support +def matrix_triangular_solve(matrix, rhs, lower=True, adjoint=False, name=None): + """Solve systems of linear equations with upper or lower triangular matrices. + + `matrix` is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form + square matrices. If `lower` is `True` then the strictly upper triangular part + of each inner-most matrix is assumed to be zero and not accessed. If `lower` + is `False` then the strictly lower triangular part of each inner-most matrix + is assumed to be zero and not accessed. `rhs` is a tensor of shape + `[..., M, N]`. + + The output is a tensor of shape `[..., M, N]`. If `adjoint` is `True` then the + innermost matrices in output satisfy matrix equations ` + sum_k matrix[..., i, k] * output[..., k, j] = rhs[..., i, j]`. + If `adjoint` is `False` then the + innermost matrices in output satisfy matrix equations + `sum_k adjoint(matrix[..., i, k]) * output[..., k, j] = rhs[..., i, j]`. + + Example: + + >>> a = tf.constant([[3, 0, 0, 0], + ... [2, 1, 0, 0], + ... [1, 0, 1, 0], + ... [1, 1, 1, 1]], dtype=tf.float32) + + >>> b = tf.constant([[4], [2], [4], [2]], dtype=tf.float32) + >>> x = tf.linalg.triangular_solve(a, b, lower=True) + >>> x + + >>> tf.matmul(a, x) + + + Args: + matrix: A `Tensor`. Must be one of the following types: `float64`, + `float32`, `half`, `complex64`, `complex128`. Shape is `[..., M, M]`. + rhs: A `Tensor`. Must have the same type as `matrix`. Shape is `[..., M, + N]`. + lower: An optional `bool`. Defaults to `True`. Boolean indicating whether + the innermost matrices in matrix are lower or upper triangular. + adjoint: An optional `bool`. Defaults to `False`. Boolean indicating whether + to solve with matrix or its (block-wise) adjoint. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as matrix, and shape is `[..., M, N]`. + + """ + with ops.name_scope(name, 'triangular_solve', [matrix, rhs]): + return gen_linalg_ops.matrix_triangular_solve( + matrix, rhs, lower=lower, adjoint=adjoint) + + +@tf_export( + 'linalg.cholesky_solve', v1=['linalg.cholesky_solve', 'cholesky_solve']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('cholesky_solve') +def cholesky_solve(chol, rhs, name=None): + """Solves systems of linear eqns `A X = RHS`, given Cholesky factorizations. + + Specifically, returns `X` from `A X = RHS`, where `A = L L^T`, `L` is the + `chol` arg and `RHS` is the `rhs` arg. + + ```python + # Solve 10 separate 2x2 linear systems: + A = ... # shape 10 x 2 x 2 + RHS = ... # shape 10 x 2 x 1 + chol = tf.linalg.cholesky(A) # shape 10 x 2 x 2 + X = tf.linalg.cholesky_solve(chol, RHS) # shape 10 x 2 x 1 + # tf.matmul(A, X) ~ RHS + X[3, :, 0] # Solution to the linear system A[3, :, :] x = RHS[3, :, 0] + + # Solve five linear systems (K = 5) for every member of the length 10 batch. + A = ... # shape 10 x 2 x 2 + RHS = ... # shape 10 x 2 x 5 + ... + X[3, :, 2] # Solution to the linear system A[3, :, :] x = RHS[3, :, 2] + ``` + + Args: + chol: A `Tensor`. Must be `float32` or `float64`, shape is `[..., M, M]`. + Cholesky factorization of `A`, e.g. `chol = tf.linalg.cholesky(A)`. + For that reason, only the lower triangular parts (including the diagonal) + of the last two dimensions of `chol` are used. The strictly upper part is + assumed to be zero and not accessed. + rhs: A `Tensor`, same type as `chol`, shape is `[..., M, K]`. + name: A name to give this `Op`. Defaults to `cholesky_solve`. + + Returns: + Solution to `A x = rhs`, shape `[..., M, K]`. + """ + # To solve C C^* x = rhs, we + # 1. Solve C y = rhs for y, thus y = C^* x + # 2. Solve C^* x = y for x + with ops.name_scope(name, 'cholesky_solve', [chol, rhs]): + y = gen_linalg_ops.matrix_triangular_solve( + chol, rhs, adjoint=False, lower=True) + x = gen_linalg_ops.matrix_triangular_solve( + chol, y, adjoint=True, lower=True) + return x + + +@tf_export('eye', 'linalg.eye') +@dispatch.add_dispatch_support +def eye(num_rows, + num_columns=None, + batch_shape=None, + dtype=dtypes.float32, + name=None): + """Construct an identity matrix, or a batch of matrices. + + See also `tf.ones`, `tf.zeros`, `tf.fill`, `tf.one_hot`. + + ```python + # Construct one identity matrix. + tf.eye(2) + ==> [[1., 0.], + [0., 1.]] + + # Construct a batch of 3 identity matrices, each 2 x 2. + # batch_identity[i, :, :] is a 2 x 2 identity matrix, i = 0, 1, 2. + batch_identity = tf.eye(2, batch_shape=[3]) + + # Construct one 2 x 3 "identity" matrix + tf.eye(2, num_columns=3) + ==> [[ 1., 0., 0.], + [ 0., 1., 0.]] + ``` + + Args: + num_rows: Non-negative `int32` scalar `Tensor` giving the number of rows + in each batch matrix. + num_columns: Optional non-negative `int32` scalar `Tensor` giving the number + of columns in each batch matrix. Defaults to `num_rows`. + batch_shape: A list or tuple of Python integers or a 1-D `int32` `Tensor`. + If provided, the returned `Tensor` will have leading batch dimensions of + this shape. + dtype: The type of an element in the resulting `Tensor` + name: A name for this `Op`. Defaults to "eye". + + Returns: + A `Tensor` of shape `batch_shape + [num_rows, num_columns]` + """ + return linalg_ops_impl.eye(num_rows, + num_columns=num_columns, + batch_shape=batch_shape, + dtype=dtype, + name=name) + + +@tf_export('linalg.lstsq', v1=['linalg.lstsq', 'matrix_solve_ls']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('matrix_solve_ls') +def matrix_solve_ls(matrix, rhs, l2_regularizer=0.0, fast=True, name=None): + r"""Solves one or more linear least-squares problems. + + `matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions + form `M`-by-`N` matrices. Rhs is a tensor of shape `[..., M, K]` whose + inner-most 2 dimensions form `M`-by-`K` matrices. The computed output is a + `Tensor` of shape `[..., N, K]` whose inner-most 2 dimensions form `M`-by-`K` + matrices that solve the equations + `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]` in the least squares + sense. + + Below we will use the following notation for each pair of matrix and + right-hand sides in the batch: + + `matrix`=\\(A \in \Re^{m \times n}\\), + `rhs`=\\(B \in \Re^{m \times k}\\), + `output`=\\(X \in \Re^{n \times k}\\), + `l2_regularizer`=\\(\lambda\\). + + If `fast` is `True`, then the solution is computed by solving the normal + equations using Cholesky decomposition. Specifically, if \\(m \ge n\\) then + \\(X = (A^T A + \lambda I)^{-1} A^T B\\), which solves the least-squares + problem \\(X = \mathrm{argmin}_{Z \in \Re^{n \times k}} ||A Z - B||_F^2 + + \lambda ||Z||_F^2\\). If \\(m \lt n\\) then `output` is computed as + \\(X = A^T (A A^T + \lambda I)^{-1} B\\), which (for \\(\lambda = 0\\)) is + the minimum-norm solution to the under-determined linear system, i.e. + \\(X = \mathrm{argmin}_{Z \in \Re^{n \times k}} ||Z||_F^2 \\), subject to + \\(A Z = B\\). Notice that the fast path is only numerically stable when + \\(A\\) is numerically full rank and has a condition number + \\(\mathrm{cond}(A) \lt \frac{1}{\sqrt{\epsilon_{mach}}}\\) or\\(\lambda\\) + is sufficiently large. + + If `fast` is `False` an algorithm based on the numerically robust complete + orthogonal decomposition is used. This computes the minimum-norm + least-squares solution, even when \\(A\\) is rank deficient. This path is + typically 6-7 times slower than the fast path. If `fast` is `False` then + `l2_regularizer` is ignored. + + Args: + matrix: `Tensor` of shape `[..., M, N]`. + rhs: `Tensor` of shape `[..., M, K]`. + l2_regularizer: 0-D `double` `Tensor`. Ignored if `fast=False`. + fast: bool. Defaults to `True`. + name: string, optional name of the operation. + + Returns: + output: `Tensor` of shape `[..., N, K]` whose inner-most 2 dimensions form + `M`-by-`K` matrices that solve the equations + `matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]` in the least + squares sense. + + Raises: + NotImplementedError: linalg.lstsq is currently disabled for complex128 + and l2_regularizer != 0 due to poor accuracy. + """ + + # pylint: disable=long-lambda + def _use_composite_impl(fast, tensor_shape): + """Determines whether to use the composite or specialized CPU kernel. + + When the total size of the tensor is larger than the cache size and the + batch size is large compared to the smallest matrix dimension, then the + composite implementation is inefficient since it has to read the entire + tensor from memory multiple times. In this case we fall back to the + original CPU kernel, which does all the computational steps on each + matrix separately. + + Only fast mode is supported by the composite impl, so `False` is returned + if `fast` is `False`. + + Args: + fast: bool indicating if fast mode in the solver was requested. + tensor_shape: The shape of the tensor. + + Returns: + True if the composite impl should be used. False otherwise. + """ + if fast is False: + return False + batch_shape = tensor_shape[:-2] + matrix_shape = tensor_shape[-2:] + if not tensor_shape.is_fully_defined(): + return True + tensor_size = tensor_shape.num_elements() * matrix.dtype.size + is_io_bound = batch_shape.num_elements() > np.min(matrix_shape) + L2_CACHE_SIZE_GUESSTIMATE = 256000 + if tensor_size > L2_CACHE_SIZE_GUESSTIMATE and is_io_bound: + return False + else: + return True + + def _overdetermined(matrix, rhs, l2_regularizer): + """Computes (A^H*A + l2_regularizer)^{-1} * A^H * rhs.""" + chol = _RegularizedGramianCholesky( + matrix, l2_regularizer=l2_regularizer, first_kind=True) + return cholesky_solve(chol, math_ops.matmul(matrix, rhs, adjoint_a=True)) + + def _underdetermined(matrix, rhs, l2_regularizer): + """Computes A^H * (A*A^H + l2_regularizer)^{-1} * rhs.""" + chol = _RegularizedGramianCholesky( + matrix, l2_regularizer=l2_regularizer, first_kind=False) + return math_ops.matmul(matrix, cholesky_solve(chol, rhs), adjoint_a=True) + + def _composite_impl(matrix, rhs, l2_regularizer): + """Composite implementation of matrix_solve_ls that supports GPU.""" + with ops.name_scope(name, 'matrix_solve_ls', [matrix, rhs, l2_regularizer]): + matrix_shape = matrix.get_shape()[-2:] + if matrix_shape.is_fully_defined(): + if matrix_shape[-2] >= matrix_shape[-1]: + return _overdetermined(matrix, rhs, l2_regularizer) + else: + return _underdetermined(matrix, rhs, l2_regularizer) + else: + # We have to defer determining the shape to runtime and use + # conditional execution of the appropriate graph. + matrix_shape = array_ops.shape(matrix)[-2:] + return cond.cond( + matrix_shape[-2] >= matrix_shape[-1], + lambda: _overdetermined(matrix, rhs, l2_regularizer), + lambda: _underdetermined(matrix, rhs, l2_regularizer)) + + matrix = ops.convert_to_tensor(matrix, name='matrix') + if matrix.dtype == dtypes.complex128 and l2_regularizer != 0: + # TODO(rmlarsen): Investigate and fix accuracy bug. + raise NotImplementedError('matrix_solve_ls is currently disabled for ' + 'complex128 and l2_regularizer != 0 due to ' + 'poor accuracy.') + tensor_shape = matrix.get_shape() + if _use_composite_impl(fast, tensor_shape): + return _composite_impl(matrix, rhs, l2_regularizer) + else: + return gen_linalg_ops.matrix_solve_ls( + matrix, rhs, l2_regularizer, fast=fast, name=name) + + +@tf_export('linalg.eig', 'eig', v1=[]) +@dispatch.add_dispatch_support +def eig(tensor, name=None): + """Computes the eigen decomposition of a batch of matrices. + + The eigenvalues + and eigenvectors for a non-Hermitian matrix in general are complex. The + eigenvectors are not guaranteed to be linearly independent. + + Computes the eigenvalues and right eigenvectors of the innermost + N-by-N matrices in `tensor` such that + `tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i]`, for i=0...N-1. + + Args: + tensor: `Tensor` of shape `[..., N, N]`. Only the lower triangular part of + each inner inner matrix is referenced. + name: string, optional name of the operation. + + Returns: + e: Eigenvalues. Shape is `[..., N]`. The eigenvalues are not necessarily + ordered. + v: Eigenvectors. Shape is `[..., N, N]`. The columns of the inner most + matrices contain eigenvectors of the corresponding matrices in `tensor` + """ + if tensor.dtype == dtypes.float32 or tensor.dtype == dtypes.complex64: + out_dtype = dtypes.complex64 + elif tensor.dtype == dtypes.float64 or tensor.dtype == dtypes.complex128: + out_dtype = dtypes.complex128 + e, v = gen_linalg_ops.eig(tensor, Tout=out_dtype, compute_v=True, name=name) + return e, v + + +@tf_export('linalg.eigvals', 'eigvals', v1=[]) +@dispatch.add_dispatch_support +def eigvals(tensor, name=None): + """Computes the eigenvalues of one or more matrices. + + Note: If your program backpropagates through this function, you should replace + it with a call to tf.linalg.eig (possibly ignoring the second output) to + avoid computing the eigen decomposition twice. This is because the + eigenvectors are used to compute the gradient w.r.t. the eigenvalues. See + _SelfAdjointEigV2Grad in linalg_grad.py. + + Args: + tensor: `Tensor` of shape `[..., N, N]`. + name: string, optional name of the operation. + + Returns: + e: Eigenvalues. Shape is `[..., N]`. The vector `e[..., :]` contains the `N` + eigenvalues of `tensor[..., :, :]`. + """ + if tensor.dtype == dtypes.float32 or tensor.dtype == dtypes.complex64: + out_dtype = dtypes.complex64 + elif tensor.dtype == dtypes.float64 or tensor.dtype == dtypes.complex128: + out_dtype = dtypes.complex128 + e, _ = gen_linalg_ops.eig(tensor, Tout=out_dtype, compute_v=False, name=name) + return e + + +@tf_export('linalg.eigh', v1=['linalg.eigh', 'self_adjoint_eig']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('self_adjoint_eig') +def self_adjoint_eig(tensor, name=None): + """Computes the eigen decomposition of a batch of self-adjoint matrices. + + Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices + in `tensor` such that + `tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i]`, for i=0...N-1. + + Args: + tensor: `Tensor` of shape `[..., N, N]`. Only the lower triangular part of + each inner inner matrix is referenced. + name: string, optional name of the operation. + + Returns: + e: Eigenvalues. Shape is `[..., N]`. Sorted in non-decreasing order. + v: Eigenvectors. Shape is `[..., N, N]`. The columns of the inner most + matrices contain eigenvectors of the corresponding matrices in `tensor` + """ + e, v = gen_linalg_ops.self_adjoint_eig_v2(tensor, compute_v=True, name=name) + return e, v + + +@tf_export('linalg.eigvalsh', v1=['linalg.eigvalsh', 'self_adjoint_eigvals']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('self_adjoint_eigvals') +def self_adjoint_eigvals(tensor, name=None): + """Computes the eigenvalues of one or more self-adjoint matrices. + + Note: If your program backpropagates through this function, you should replace + it with a call to tf.linalg.eigh (possibly ignoring the second output) to + avoid computing the eigen decomposition twice. This is because the + eigenvectors are used to compute the gradient w.r.t. the eigenvalues. See + _SelfAdjointEigV2Grad in linalg_grad.py. + + Args: + tensor: `Tensor` of shape `[..., N, N]`. + name: string, optional name of the operation. + + Returns: + e: Eigenvalues. Shape is `[..., N]`. The vector `e[..., :]` contains the `N` + eigenvalues of `tensor[..., :, :]`. + """ + e, _ = gen_linalg_ops.self_adjoint_eig_v2(tensor, compute_v=False, name=name) + return e + + +@tf_export('linalg.svd', v1=['linalg.svd', 'svd']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('svd') +def svd(tensor, full_matrices=False, compute_uv=True, name=None): + r"""Computes the singular value decompositions of one or more matrices. + + Computes the SVD of each inner matrix in `tensor` such that + `tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * + transpose(conj(v[..., :, :]))` + + ```python + # a is a tensor. + # s is a tensor of singular values. + # u is a tensor of left singular vectors. + # v is a tensor of right singular vectors. + s, u, v = svd(a) + s = svd(a, compute_uv=False) + ``` + + Args: + tensor: `Tensor` of shape `[..., M, N]`. Let `P` be the minimum of `M` and + `N`. + full_matrices: If true, compute full-sized `u` and `v`. If false + (the default), compute only the leading `P` singular vectors. + Ignored if `compute_uv` is `False`. + compute_uv: If `True` then left and right singular vectors will be + computed and returned in `u` and `v`, respectively. Otherwise, only the + singular values will be computed, which can be significantly faster. + name: string, optional name of the operation. + + Returns: + s: Singular values. Shape is `[..., P]`. The values are sorted in reverse + order of magnitude, so s[..., 0] is the largest value, s[..., 1] is the + second largest, etc. + u: Left singular vectors. If `full_matrices` is `False` (default) then + shape is `[..., M, P]`; if `full_matrices` is `True` then shape is + `[..., M, M]`. Not returned if `compute_uv` is `False`. + v: Right singular vectors. If `full_matrices` is `False` (default) then + shape is `[..., N, P]`. If `full_matrices` is `True` then shape is + `[..., N, N]`. Not returned if `compute_uv` is `False`. + + @compatibility(numpy) + Mostly equivalent to numpy.linalg.svd, except that + * The order of output arguments here is `s`, `u`, `v` when `compute_uv` is + `True`, as opposed to `u`, `s`, `v` for numpy.linalg.svd. + * full_matrices is `False` by default as opposed to `True` for + numpy.linalg.svd. + * tf.linalg.svd uses the standard definition of the SVD + \\(A = U \Sigma V^H\\), such that the left singular vectors of `a` are + the columns of `u`, while the right singular vectors of `a` are the + columns of `v`. On the other hand, numpy.linalg.svd returns the adjoint + \\(V^H\\) as the third output argument. + ```python + import tensorflow as tf + import numpy as np + s, u, v = tf.linalg.svd(a) + tf_a_approx = tf.matmul(u, tf.matmul(tf.linalg.diag(s), v, adjoint_b=True)) + u, s, v_adj = np.linalg.svd(a, full_matrices=False) + np_a_approx = np.dot(u, np.dot(np.diag(s), v_adj)) + # tf_a_approx and np_a_approx should be numerically close. + ``` + @end_compatibility + """ + s, u, v = gen_linalg_ops.svd( + tensor, compute_uv=compute_uv, full_matrices=full_matrices, name=name) + if compute_uv: + return math_ops.real(s), u, v + else: + return math_ops.real(s) + + +# pylint: disable=redefined-builtin +@tf_export('norm', 'linalg.norm', v1=[]) +@dispatch.add_dispatch_support +def norm_v2(tensor, + ord='euclidean', + axis=None, + keepdims=None, + name=None): + r"""Computes the norm of vectors, matrices, and tensors. + + This function can compute several different vector norms (the 1-norm, the + Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and + matrix norms (Frobenius, 1-norm, 2-norm and inf-norm). + + Args: + tensor: `Tensor` of types `float32`, `float64`, `complex64`, `complex128` + ord: Order of the norm. Supported values are `'fro'`, `'euclidean'`, + `1`, `2`, `np.inf` and any positive real number yielding the corresponding + p-norm. Default is `'euclidean'` which is equivalent to Frobenius norm if + `tensor` is a matrix and equivalent to 2-norm for vectors. + Some restrictions apply: + a) The Frobenius norm `'fro'` is not defined for vectors, + b) If axis is a 2-tuple (matrix norm), only `'euclidean'`, '`fro'`, `1`, + `2`, `np.inf` are supported. + See the description of `axis` on how to compute norms for a batch of + vectors or matrices stored in a tensor. + axis: If `axis` is `None` (the default), the input is considered a vector + and a single vector norm is computed over the entire set of values in the + tensor, i.e. `norm(tensor, ord=ord)` is equivalent to + `norm(reshape(tensor, [-1]), ord=ord)`. + If `axis` is a Python integer, the input is considered a batch of vectors, + and `axis` determines the axis in `tensor` over which to compute vector + norms. + If `axis` is a 2-tuple of Python integers it is considered a batch of + matrices and `axis` determines the axes in `tensor` over which to compute + a matrix norm. + Negative indices are supported. Example: If you are passing a tensor that + can be either a matrix or a batch of matrices at runtime, pass + `axis=[-2,-1]` instead of `axis=None` to make sure that matrix norms are + computed. + keepdims: If True, the axis indicated in `axis` are kept with size 1. + Otherwise, the dimensions in `axis` are removed from the output shape. + name: The name of the op. + + Returns: + output: A `Tensor` of the same type as tensor, containing the vector or + matrix norms. If `keepdims` is True then the rank of output is equal to + the rank of `tensor`. Otherwise, if `axis` is none the output is a scalar, + if `axis` is an integer, the rank of `output` is one less than the rank + of `tensor`, if `axis` is a 2-tuple the rank of `output` is two less + than the rank of `tensor`. + + Raises: + ValueError: If `ord` or `axis` is invalid. + + @compatibility(numpy) + Mostly equivalent to numpy.linalg.norm. + Not supported: ord <= 0, 2-norm for matrices, nuclear norm. + Other differences: + a) If axis is `None`, treats the flattened `tensor` as a vector + regardless of rank. + b) Explicitly supports 'euclidean' norm as the default, including for + higher order tensors. + @end_compatibility + """ + return norm(tensor=tensor, + ord=ord, + axis=axis, + keepdims=keepdims, + name=name) + + +# pylint: disable=redefined-builtin +@tf_export(v1=['norm', 'linalg.norm']) +@dispatch.add_dispatch_support +@deprecation.deprecated_args( + None, 'keep_dims is deprecated, use keepdims instead', 'keep_dims') +def norm(tensor, + ord='euclidean', + axis=None, + keepdims=None, + name=None, + keep_dims=None): + r"""Computes the norm of vectors, matrices, and tensors. + + This function can compute several different vector norms (the 1-norm, the + Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and + matrix norms (Frobenius, 1-norm, 2-norm and inf-norm). + + Args: + tensor: `Tensor` of types `float32`, `float64`, `complex64`, `complex128` + ord: Order of the norm. Supported values are 'fro', 'euclidean', + `1`, `2`, `np.inf` and any positive real number yielding the corresponding + p-norm. Default is 'euclidean' which is equivalent to Frobenius norm if + `tensor` is a matrix and equivalent to 2-norm for vectors. + Some restrictions apply: + a) The Frobenius norm `fro` is not defined for vectors, + b) If axis is a 2-tuple (matrix norm), only 'euclidean', 'fro', `1`, + `2`, `np.inf` are supported. + See the description of `axis` on how to compute norms for a batch of + vectors or matrices stored in a tensor. + axis: If `axis` is `None` (the default), the input is considered a vector + and a single vector norm is computed over the entire set of values in the + tensor, i.e. `norm(tensor, ord=ord)` is equivalent to + `norm(reshape(tensor, [-1]), ord=ord)`. + If `axis` is a Python integer, the input is considered a batch of vectors, + and `axis` determines the axis in `tensor` over which to compute vector + norms. + If `axis` is a 2-tuple of Python integers it is considered a batch of + matrices and `axis` determines the axes in `tensor` over which to compute + a matrix norm. + Negative indices are supported. Example: If you are passing a tensor that + can be either a matrix or a batch of matrices at runtime, pass + `axis=[-2,-1]` instead of `axis=None` to make sure that matrix norms are + computed. + keepdims: If True, the axis indicated in `axis` are kept with size 1. + Otherwise, the dimensions in `axis` are removed from the output shape. + name: The name of the op. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + output: A `Tensor` of the same type as tensor, containing the vector or + matrix norms. If `keepdims` is True then the rank of output is equal to + the rank of `tensor`. Otherwise, if `axis` is none the output is a scalar, + if `axis` is an integer, the rank of `output` is one less than the rank + of `tensor`, if `axis` is a 2-tuple the rank of `output` is two less + than the rank of `tensor`. + + Raises: + ValueError: If `ord` or `axis` is invalid. + + @compatibility(numpy) + Mostly equivalent to numpy.linalg.norm. + Not supported: ord <= 0, 2-norm for matrices, nuclear norm. + Other differences: + a) If axis is `None`, treats the flattened `tensor` as a vector + regardless of rank. + b) Explicitly supports 'euclidean' norm as the default, including for + higher order tensors. + @end_compatibility + """ + keepdims = deprecation.deprecated_argument_lookup('keepdims', keepdims, + 'keep_dims', keep_dims) + if keepdims is None: + keepdims = False + + is_matrix_norm = ((isinstance(axis, tuple) or isinstance(axis, list)) and + len(axis) == 2) + if is_matrix_norm: + axis = tuple(axis) + if (not isinstance(axis[0], int) or not isinstance(axis[1], int) or + axis[0] == axis[1]): + raise ValueError( + "'axis' must be None, an integer, or a tuple of 2 " + f"unique integers, got {axis}") + supported_matrix_norms = ['euclidean', 'fro', 1, 2, np.inf] + if ord not in supported_matrix_norms: + raise ValueError(f"'ord' must be a supported matrix norm in " + f"{supported_matrix_norms}, got {ord}") + else: + if not (isinstance(axis, int) or axis is None): + raise ValueError( + "'axis' must be None, an integer, or a " + f"tuple of 2 unique integers, got {axis}") + + supported_vector_norms = ['euclidean', 1, 2, np.inf] + if (not np.isreal(ord) or ord <= 0) and ord not in supported_vector_norms: + raise ValueError(f"'ord' must be a supported vector norm, got {ord}") + if axis is not None: + axis = (axis,) + + with ops.name_scope(name, 'norm', [tensor]): + tensor = ops.convert_to_tensor(tensor) + + if ord in ['fro', 'euclidean', 2, 2.0]: + if is_matrix_norm and ord in [2, 2.0]: + rank = array_ops.rank(tensor) + positive_axis = map_fn.map_fn( + lambda i: cond.cond( + i >= 0, + lambda: i, + lambda: i + rank), + ops.convert_to_tensor(axis)) + axes = math_ops.range(rank) + perm_before = array_ops.concat([ + gen_array_ops.list_diff(axes, positive_axis, dtypes.int32)[0], + positive_axis + ], + axis=0) + perm_after = map_fn.map_fn( + lambda i: math_ops.cast( + array_ops.squeeze( + array_ops.where_v2(math_ops.equal(perm_before, i))), + dtype=dtypes.int32), axes) + permed = array_ops.transpose(tensor, perm=perm_before) + matrix_2_norm = array_ops.expand_dims( + math_ops.reduce_max( + math_ops.abs(gen_linalg_ops.svd(permed, compute_uv=False)[0]), + axis=-1, + keepdims=True), + axis=-1) + result = array_ops.transpose(matrix_2_norm, perm=perm_after) + else: + # NOTE: we unfortunately cannot use tf.math.reduce_euclidean_norm, since + # this introduces a new op that is not supported in XLA, and breaks + # many existing TPU workloads (e.g. ResNet). + result = math_ops.sqrt( + math_ops.reduce_sum( + tensor * math_ops.conj(tensor), axis, keepdims=True)) + else: + result = math_ops.abs(tensor) + if ord == 1: + sum_axis = None if axis is None else axis[0] + result = math_ops.reduce_sum(result, sum_axis, keepdims=True) + if is_matrix_norm: + result = math_ops.reduce_max(result, axis[-1], keepdims=True) + elif ord == np.inf: + if is_matrix_norm: + result = math_ops.reduce_sum(result, axis[1], keepdims=True) + max_axis = None if axis is None else axis[0] + result = math_ops.reduce_max(result, max_axis, keepdims=True) + else: + # General p-norms (positive p only) + result = math_ops.pow( + math_ops.reduce_sum(math_ops.pow(result, ord), axis, keepdims=True), + 1.0 / ord) + if not keepdims: + result = array_ops.squeeze(result, axis) + return result + + +# pylint: enable=invalid-name,redefined-builtin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..45393ccba5349b79e3a185d3c463c7b297607e31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/linalg_ops_impl.py @@ -0,0 +1,83 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for linear algebra.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import compat + +# Names below are lower_case. +# pylint: disable=invalid-name + + +def eye(num_rows, + num_columns=None, + batch_shape=None, + dtype=dtypes.float32, + name=None): + """Construct an identity matrix, or a batch of matrices. + + See `linalg_ops.eye`. + """ + with ops.name_scope( + name, default_name='eye', values=[num_rows, num_columns, batch_shape]): + is_square = num_columns is None + batch_shape = [] if batch_shape is None else batch_shape + num_columns = num_rows if num_columns is None else num_columns + + # We cannot statically infer what the diagonal size should be: + if (isinstance(num_rows, tensor.Tensor) or + isinstance(num_columns, tensor.Tensor)): + diag_size = math_ops.minimum(num_rows, num_columns) + else: + # We can statically infer the diagonal size, and whether it is square. + if not isinstance(num_rows, compat.integral_types) or not isinstance( + num_columns, compat.integral_types): + raise TypeError( + 'Arguments `num_rows` and `num_columns` must be positive integer ' + f'values. Received: num_rows={num_rows}, num_columns={num_columns}') + is_square = num_rows == num_columns + diag_size = np.minimum(num_rows, num_columns) + + # We can not statically infer the shape of the tensor. + if isinstance(batch_shape, tensor.Tensor) or isinstance( + diag_size, tensor.Tensor + ): + batch_shape = ops.convert_to_tensor( + batch_shape, name='shape', dtype=dtypes.int32 + ) + diag_shape = array_ops.concat((batch_shape, [diag_size]), axis=0) + if not is_square: + shape = array_ops.concat((batch_shape, [num_rows, num_columns]), axis=0) + # We can statically infer everything. + else: + batch_shape = list(batch_shape) + diag_shape = batch_shape + [diag_size] + if not is_square: + shape = batch_shape + [num_rows, num_columns] + + diag_ones = array_ops.ones(diag_shape, dtype=dtype) + if is_square: + return array_ops.matrix_diag(diag_ones) + else: + zero_matrix = array_ops.zeros(shape, dtype=dtype) + return array_ops.matrix_set_diag(zero_matrix, diag_ones) + +# pylint: enable=invalid-name,redefined-builtin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/list_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/list_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..32cf7ae96fcd65389442b0810fe65fb58dc76388 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/list_ops.py @@ -0,0 +1,408 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops to manipulate lists of tensors.""" + +# pylint: disable=g-bad-name +import numpy as np + +from tensorflow.core.framework import full_type_pb2 +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_list_ops +from tensorflow.python.ops import handle_data_util +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_list_ops import * +# pylint: enable=wildcard-import + + +ops.NotDifferentiable("TensorListConcatLists") +ops.NotDifferentiable("TensorListElementShape") +ops.NotDifferentiable("TensorListLength") +ops.NotDifferentiable("TensorListPushBackBatch") + + +def empty_tensor_list(element_shape, + element_dtype, + max_num_elements=None, + name=None): + if max_num_elements is None: + max_num_elements = -1 + + return gen_list_ops.empty_tensor_list( + element_shape=_build_element_shape(element_shape), + element_dtype=element_dtype, + max_num_elements=max_num_elements, + name=name) + + +def _set_handle_data(list_handle, element_shape, element_dtype): + """Sets type information on `list_handle` for consistency with graphs.""" + # TODO(b/169968286): It would be better if we had a consistent story for + # creating handle data from eager operations (shared with VarHandleOp). + if isinstance(list_handle, ops.EagerTensor): + if tensor_util.is_tf_type(element_shape): + element_shape = tensor_shape.TensorShape(None) + elif not isinstance(element_shape, tensor_shape.TensorShape): + element_shape = tensor_shape.TensorShape(element_shape) + handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData() + handle_data.is_set = True + # TODO(b/191472076): This duplicates type inference. Clean up. + handle_data.shape_and_type.append( + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType( + shape=element_shape.as_proto(), + dtype=element_dtype.as_datatype_enum, + type=full_type_pb2.FullTypeDef(type_id=full_type_pb2.TFT_ARRAY))) + list_handle._handle_data = handle_data # pylint: disable=protected-access + + +def tensor_list_reserve(element_shape, num_elements, element_dtype, name=None): + result = gen_list_ops.tensor_list_reserve( + element_shape=_build_element_shape(element_shape), + num_elements=num_elements, + element_dtype=element_dtype, + name=name) + # TODO(b/169968286): gen_ops needs to ensure the metadata is properly + # populated for eager operations. + _set_handle_data(result, element_shape, element_dtype) + return result + + +def tensor_list_from_tensor(tensor, element_shape, name=None): + tensor = ops.convert_to_tensor(tensor) + result = gen_list_ops.tensor_list_from_tensor( + tensor=tensor, + element_shape=_build_element_shape(element_shape), + name=name) + _set_handle_data(result, tensor.shape, tensor.dtype) + return result + + +def tensor_list_get_item(input_handle, index, element_dtype, element_shape=None, + name=None): + return gen_list_ops.tensor_list_get_item( + input_handle=input_handle, + index=index, + element_shape=_build_element_shape(element_shape), + element_dtype=element_dtype, + name=name) + + +def tensor_list_pop_back(input_handle, element_dtype, name=None): + return gen_list_ops.tensor_list_pop_back( + input_handle=input_handle, + element_shape=-1, + element_dtype=element_dtype, + name=name) + + +def tensor_list_gather(input_handle, + indices, + element_dtype, + element_shape=None, + name=None): + return gen_list_ops.tensor_list_gather( + input_handle=input_handle, + indices=indices, + element_shape=_build_element_shape(element_shape), + element_dtype=element_dtype, + name=name) + + +def tensor_list_scatter(tensor, + indices, + element_shape=None, + input_handle=None, + name=None): + """Returns a TensorList created or updated by scattering `tensor`.""" + tensor = ops.convert_to_tensor(tensor) + if input_handle is not None: + output_handle = gen_list_ops.tensor_list_scatter_into_existing_list( + input_handle=input_handle, tensor=tensor, indices=indices, name=name) + handle_data_util.copy_handle_data(input_handle, output_handle) + return output_handle + else: + output_handle = gen_list_ops.tensor_list_scatter_v2( + tensor=tensor, + indices=indices, + element_shape=_build_element_shape(element_shape), + num_elements=-1, + name=name) + _set_handle_data(output_handle, element_shape, tensor.dtype) + return output_handle + + +def tensor_list_stack(input_handle, + element_dtype, + num_elements=-1, + element_shape=None, + name=None): + return gen_list_ops.tensor_list_stack( + input_handle=input_handle, + element_shape=_build_element_shape(element_shape), + element_dtype=element_dtype, + num_elements=num_elements, + name=name) + + +def tensor_list_concat(input_handle, element_dtype, element_shape=None, + name=None): + # Ignore the lengths output of TensorListConcat. It is only used during + # gradient computation. + return gen_list_ops.tensor_list_concat_v2( + input_handle=input_handle, + element_dtype=element_dtype, + element_shape=_build_element_shape(element_shape), + leading_dims=ops.convert_to_tensor([], dtype=dtypes.int64), + name=name)[0] + + +def tensor_list_split(tensor, element_shape, lengths, name=None): + return gen_list_ops.tensor_list_split( + tensor=tensor, + element_shape=_build_element_shape(element_shape), + lengths=lengths, + name=name) + + +def tensor_list_set_item(input_handle, + index, + item, + resize_if_index_out_of_bounds=False, + name=None): + """Sets `item` at `index` in input list.""" + output_handle = gen_list_ops.tensor_list_set_item( + input_handle=input_handle, + index=index, + item=item, + name=name, + resize_if_index_out_of_bounds=resize_if_index_out_of_bounds, + ) + handle_data_util.copy_handle_data(input_handle, output_handle) + return output_handle + + +@ops.RegisterGradient("TensorListPushBack") +def _PushBackGrad(op: ops.Operation, dresult): + return gen_list_ops.tensor_list_pop_back( + dresult, + element_shape=array_ops.shape(op.inputs[1]), + element_dtype=op.get_attr("element_dtype")) + + +@ops.RegisterGradient("TensorListPopBack") +def _PopBackGrad(op: ops.Operation, dlist, delement): + if dlist is None: + dlist = empty_tensor_list( + element_dtype=delement.dtype, + element_shape=gen_list_ops.tensor_list_element_shape( + op.outputs[0], shape_type=dtypes.int32)) + if delement is None: + delement = array_ops.zeros_like(op.outputs[1]) + return gen_list_ops.tensor_list_push_back(dlist, delement), None + + +@ops.RegisterGradient("TensorListStack") +def _TensorListStackGrad(unused_op: ops.Operation, dtensor): + return tensor_list_from_tensor(dtensor, element_shape=dtensor.shape[1:]), None + + +@ops.RegisterGradient("TensorListConcat") +@ops.RegisterGradient("TensorListConcatV2") +def _TensorListConcatGrad(op: ops.Operation, dtensor, unused_dlengths): + """Gradient function for TensorListConcat.""" + dlist = tensor_list_split( + dtensor, + element_shape=gen_list_ops.tensor_list_element_shape( + op.inputs[0], shape_type=dtypes.int32), + lengths=op.outputs[1]) + if op.type == "TensorListConcatV2": + return dlist, None, None + else: + return dlist + + +@ops.RegisterGradient("TensorListSplit") +def _TensorListSplitGrad(op: ops.Operation, dlist): + tensor, _, lengths = op.inputs + element_shape = array_ops.slice(array_ops.shape(tensor), [1], [-1]) + element_shape = array_ops.concat([[-1], element_shape], axis=0) + return gen_list_ops.tensor_list_concat_v2( + dlist, + element_shape=element_shape, + leading_dims=lengths, + element_dtype=op.inputs[0].dtype)[0], None, None + + +@ops.RegisterGradient("TensorListFromTensor") +def _TensorListFromTensorGrad(op: ops.Operation, dlist): + """Gradient for TensorListFromTensor.""" + t = op.inputs[0] + if t.shape.dims and t.shape.dims[0].value is not None: + num_elements = t.shape.dims[0].value + else: + num_elements = None + if dlist is None: + dlist = empty_tensor_list( + element_dtype=t.dtype, + element_shape=gen_list_ops.tensor_list_element_shape( + op.outputs[0], shape_type=dtypes.int32)) + tensor_grad = gen_list_ops.tensor_list_stack( + dlist, + element_shape=array_ops.slice(array_ops.shape(t), [1], [-1]), + element_dtype=t.dtype, + num_elements=num_elements) + shape_grad = None + return tensor_grad, shape_grad + + +@ops.RegisterGradient("TensorListGetItem") +def _TensorListGetItemGrad(op: ops.Operation, ditem): + """Gradient for TensorListGetItem.""" + list_size = gen_list_ops.tensor_list_length(op.inputs[0]) + list_grad = gen_list_ops.tensor_list_set_item( + gen_list_ops.tensor_list_reserve( + gen_list_ops.tensor_list_element_shape(op.inputs[0], + shape_type=dtypes.int32), + list_size, element_dtype=ditem.dtype), + index=op.inputs[1], + item=ditem) + index_grad = None + element_shape_grad = None + return list_grad, index_grad, element_shape_grad + + +@ops.RegisterGradient("TensorListSetItem") +def _TensorListSetItemGrad(op: ops.Operation, dlist): + """Gradient function for TensorListSetItem.""" + input_list, index, item = op.inputs + list_grad = gen_list_ops.tensor_list_set_item( + dlist, index=index, item=array_ops.zeros_like(item) + ) + index_grad = None + element_grad = tensor_list_get_item( + dlist, + index, + element_shape=array_ops.shape(item), + element_dtype=item.dtype, + ) + if op.get_attr( + "resize_if_index_out_of_bounds" + ): + input_list_size = gen_list_ops.tensor_list_length(input_list) + list_grad = gen_list_ops.tensor_list_resize(list_grad, input_list_size) + return list_grad, index_grad, element_grad + + +@ops.RegisterGradient("TensorListResize") +def _TensorListResizeGrad(op: ops.Operation, dlist): + input_list, _ = op.inputs + input_list_size = gen_list_ops.tensor_list_length(input_list) + return gen_list_ops.tensor_list_resize(dlist, input_list_size), None + + +@ops.RegisterGradient("TensorListGather") +def _TensorListGatherGrad(op: ops.Operation, dtensor): + """Gradient function for TensorListGather.""" + input_list, indices, _ = op.inputs + element_shape = gen_list_ops.tensor_list_element_shape( + input_list, shape_type=dtypes.int32) + num_elements = gen_list_ops.tensor_list_length(input_list) + dlist = tensor_list_reserve(element_shape, num_elements, dtensor.dtype) + dlist = tensor_list_scatter( + tensor=dtensor, indices=indices, input_handle=dlist) + return dlist, None, None + + +@ops.RegisterGradient("TensorListScatter") +@ops.RegisterGradient("TensorListScatterV2") +def _TensorListScatterGrad(op: ops.Operation, dlist): + """Gradient function for TensorListScatter.""" + tensor = op.inputs[0] + indices = op.inputs[1] + dtensor = gen_list_ops.tensor_list_gather( + dlist, + indices, + element_shape=array_ops.slice(array_ops.shape(tensor), [1], [-1]), + element_dtype=tensor.dtype) + if op.type == "TensorListScatterV2": + return dtensor, None, None, None + else: + return dtensor, None, None + + +@ops.RegisterGradient("TensorListScatterIntoExistingList") +def _TensorListScatterIntoExistingListGrad(op: ops.Operation, dlist): + """Gradient function for TensorListScatterIntoExistingList.""" + _, tensor, indices = op.inputs + dtensor = gen_list_ops.tensor_list_gather( + dlist, + indices, + element_shape=array_ops.slice(array_ops.shape(tensor), [1], [-1]), + element_dtype=tensor.dtype) + zeros = array_ops.zeros_like(tensor) + dlist = tensor_list_scatter(zeros, indices, indices, input_handle=dlist) + return dlist, dtensor, None + + +def _build_element_shape(shape): + """Converts shape to a format understood by list_ops for element_shape. + + If `shape` is already a `Tensor` it is returned as-is. We do not perform a + type check here. + + If shape is None or a TensorShape with unknown rank, -1 is returned. + + If shape is a scalar, an int32 tensor with empty list is returned. Note we + do directly return an empty list since ops.convert_to_tensor would conver it + to a float32 which is not a valid type for element_shape. + + If shape is a sequence of dims, None's in the list are replaced with -1. We + do not check the dtype of the other dims. + + Args: + shape: Could be None, Tensor, TensorShape or a list of dims (each dim could + be a None, scalar or Tensor). + + Returns: + A None-free shape that can be converted to a tensor. + """ + if isinstance(shape, tensor_lib.Tensor): + return shape + if isinstance(shape, tensor_shape.TensorShape): + # `TensorShape.as_list` requires rank to be known. + shape = shape.as_list() if shape else None + # Shape is unknown. + if shape is None: + return -1 + # Shape is numpy array or a scalar. + if isinstance(shape, (np.ndarray, np.generic)) or not shape: + return ops.convert_to_tensor(shape, dtype=dtypes.int32) + # Shape is a sequence of dimensions. Convert None dims to -1. + def convert(val): + if val is None: + return -1 + if isinstance(val, tensor_lib.Tensor): + return val + if isinstance(val, tensor_shape.Dimension): + return val.value if val.value is not None else -1 + return val + + return [convert(d) for d in shape] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/logging_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/logging_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d14b41af05404b22eb6d871a738222eeb087f350 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/logging_ops.py @@ -0,0 +1,701 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Logging and Summary Operations. + +API docstring: tensorflow.logging +""" +# pylint: disable=protected-access +import collections as py_collections +import os +import pprint +import random +import sys + +from absl import logging + +from tensorflow.python import pywrap_tfe +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_logging_ops +from tensorflow.python.ops import string_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_logging_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +def enable_interactive_logging(): + pywrap_tfe.TFE_Py_EnableInteractivePythonLogging() + +# Register printing to the cell output if we are in a Colab or Jupyter Notebook. +try: + get_ipython() # Exists in an ipython env like Jupyter or Colab + enable_interactive_logging() +except NameError: + pass + +# The python wrapper for Assert is in control_flow_ops, as the Assert +# call relies on certain conditionals for its dependencies. Use +# control_flow_ops.Assert. + +# Assert and Print are special symbols in Python 2, so we must +# have an upper-case version of them. When support for it is dropped, +# we can allow lowercase. +# See https://github.com/tensorflow/tensorflow/issues/18053 + + +# pylint: disable=invalid-name +@deprecated("2018-08-20", "Use tf.print instead of tf.Print. Note that " + "tf.print returns a no-output operator that directly " + "prints the output. Outside of defuns or eager mode, " + "this operator will not be executed unless it is " + "directly specified in session.run or used as a " + "control dependency for other operators. This is " + "only a concern in graph mode. Below is an example " + "of how to ensure tf.print executes in graph mode:\n") +@tf_export(v1=["Print"]) +@dispatch.add_dispatch_support +def Print(input_, data, message=None, first_n=None, summarize=None, name=None): + """Prints a list of tensors. + + This is an identity op (behaves like `tf.identity`) with the side effect + of printing `data` when evaluating. + + Note: This op prints to the standard error. It is not currently compatible + with jupyter notebook (printing to the notebook *server's* output, not into + the notebook). + + @compatibility(TF2) + This API is deprecated. Use `tf.print` instead. `tf.print` does not need the + `input_` argument. + + `tf.print` works in TF2 when executing eagerly and inside a `tf.function`. + + In TF1-styled sessions, an explicit control dependency declaration is needed + to execute the `tf.print` operation. Refer to the documentation of + `tf.print` for more details. + @end_compatibility + + Args: + input_: A tensor passed through this op. + data: A list of tensors to print out when op is evaluated. + message: A string, prefix of the error message. + first_n: Only log `first_n` number of times. Negative numbers log always; + this is the default. + summarize: Only print this many entries of each tensor. If None, then a + maximum of 3 elements are printed per input tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type and contents as `input_`. + + ```python + sess = tf.compat.v1.Session() + with sess.as_default(): + tensor = tf.range(10) + print_op = tf.print(tensor) + with tf.control_dependencies([print_op]): + out = tf.add(tensor, tensor) + sess.run(out) + ``` + """ + return gen_logging_ops._print(input_, data, message, first_n, summarize, name) + + +# pylint: enable=invalid-name + + +def _generate_placeholder_string(x, default_placeholder="{}"): + """Generate and return a string that does not appear in `x`.""" + placeholder = default_placeholder + rng = random.Random(5) + while placeholder in x: + placeholder = placeholder + str(rng.randint(0, 9)) + return placeholder + + +def _is_filepath(output_stream): + """Returns True if output_stream is a file path.""" + return isinstance(output_stream, str) and output_stream.startswith("file://") + + +# Temporarily disable pylint g-doc-args error to allow giving more context +# about what the kwargs are. +# Because we are using arbitrary-length positional arguments, python 2 +# does not support explicitly specifying the keyword arguments in the +# function definition. +# pylint: disable=g-doc-args +@tf_export("print") +@dispatch.add_dispatch_support +def print_v2(*inputs, **kwargs): + """Print the specified inputs. + + A TensorFlow operator that prints the specified inputs to a desired + output stream or logging level. The inputs may be dense or sparse Tensors, + primitive python objects, data structures that contain tensors, and printable + Python objects. Printed tensors will recursively show the first and last + elements of each dimension to summarize. + + Example: + Single-input usage: + + ```python + tensor = tf.range(10) + tf.print(tensor, output_stream=sys.stderr) + ``` + + (This prints "[0 1 2 ... 7 8 9]" to sys.stderr) + + Multi-input usage: + + ```python + tensor = tf.range(10) + tf.print("tensors:", tensor, {2: tensor * 2}, output_stream=sys.stdout) + ``` + + (This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to + sys.stdout) + + Changing the input separator: + ```python + tensor_a = tf.range(2) + tensor_b = tensor_a * 2 + tf.print(tensor_a, tensor_b, output_stream=sys.stderr, sep=',') + ``` + + (This prints "[0 1],[0 2]" to sys.stderr) + + Usage in a `tf.function`: + + ```python + @tf.function + def f(): + tensor = tf.range(10) + tf.print(tensor, output_stream=sys.stderr) + return tensor + + range_tensor = f() + ``` + + (This prints "[0 1 2 ... 7 8 9]" to sys.stderr) + + *Compatibility usage in TF 1.x graphs*: + + In graphs manually created outside of `tf.function`, this method returns + the created TF operator that prints the data. To make sure the + operator runs, users need to pass the produced op to + `tf.compat.v1.Session`'s run method, or to use the op as a control + dependency for executed ops by specifying + `with tf.compat.v1.control_dependencies([print_op])`. + + ```python + tf.compat.v1.disable_v2_behavior() # for TF1 compatibility only + + sess = tf.compat.v1.Session() + with sess.as_default(): + tensor = tf.range(10) + print_op = tf.print("tensors:", tensor, {2: tensor * 2}, + output_stream=sys.stdout) + with tf.control_dependencies([print_op]): + tripled_tensor = tensor * 3 + + sess.run(tripled_tensor) + ``` + + (This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to + sys.stdout) + + Note: In Jupyter notebooks and colabs, `tf.print` prints to the notebook + cell outputs. It will not write to the notebook kernel's console logs. + + Args: + *inputs: Positional arguments that are the inputs to print. Inputs in the + printed output will be separated by spaces. Inputs may be python + primitives, tensors, data structures such as dicts and lists that may + contain tensors (with the data structures possibly nested in arbitrary + ways), and printable python objects. + output_stream: The output stream, logging level, or file to print to. + Defaults to sys.stderr, but sys.stdout, tf.compat.v1.logging.info, + tf.compat.v1.logging.warning, tf.compat.v1.logging.error, + absl.logging.info, absl.logging.warning and absl.logging.error are also + supported. To print to a file, pass a string started with "file://" + followed by the file path, e.g., "file:///tmp/foo.out". + summarize: The first and last `summarize` elements within each dimension are + recursively printed per Tensor. If None, then the first 3 and last 3 + elements of each dimension are printed for each tensor. If set to -1, it + will print all elements of every tensor. + sep: The string to use to separate the inputs. Defaults to " ". + end: End character that is appended at the end the printed string. Defaults + to the newline character. + name: A name for the operation (optional). + + Returns: + None when executing eagerly. During graph tracing this returns + a TF operator that prints the specified inputs in the specified output + stream or logging level. This operator will be automatically executed + except inside of `tf.compat.v1` graphs and sessions. + + Raises: + ValueError: If an unsupported output stream is specified. + """ + # Because we are using arbitrary-length positional arguments, python 2 + # does not support explicitly specifying the keyword arguments in the + # function definition. So, we manually get the keyword arguments w/ default + # values here. + output_stream = kwargs.pop("output_stream", sys.stderr) + name = kwargs.pop("name", None) + summarize = kwargs.pop("summarize", 3) + sep = kwargs.pop("sep", " ") + end = kwargs.pop("end", os.linesep) + if kwargs: + raise ValueError("Unrecognized keyword arguments for tf.print: %s" % kwargs) + format_name = None + if name: + format_name = name + "_format" + + # Match the C++ string constants representing the different output streams. + # Keep this updated! + output_stream_to_constant = { + sys.stdout: "stdout", + sys.stderr: "stderr", + tf_logging.INFO: "log(info)", + tf_logging.info: "log(info)", + tf_logging.WARN: "log(warning)", + tf_logging.warning: "log(warning)", + tf_logging.warn: "log(warning)", + tf_logging.ERROR: "log(error)", + tf_logging.error: "log(error)", + logging.INFO: "log(info)", + logging.info: "log(info)", + logging.INFO: "log(info)", + logging.WARNING: "log(warning)", + logging.WARN: "log(warning)", + logging.warning: "log(warning)", + logging.warn: "log(warning)", + logging.ERROR: "log(error)", + logging.error: "log(error)", + } + + if _is_filepath(output_stream): + output_stream_string = output_stream + else: + output_stream_string = output_stream_to_constant.get(output_stream) + if not output_stream_string: + raise ValueError("Unsupported output stream, logging level, or file." + + str(output_stream) + + ". Supported streams are sys.stdout, " + "sys.stderr, tf.logging.info, " + "tf.logging.warning, tf.logging.error. " + + "File needs to be in the form of 'file://'.") + + # If we are only printing a single string scalar, there is no need to format + if (len(inputs) == 1 and tensor_util.is_tf_type(inputs[0]) and + (not isinstance(inputs[0], sparse_tensor.SparseTensor)) and + (inputs[0].shape.ndims == 0) and (inputs[0].dtype == dtypes.string)): + formatted_string = inputs[0] + # Otherwise, we construct an appropriate template for the tensors we are + # printing, and format the template using those tensors. + else: + # For each input to this print function, we extract any nested tensors, + # and construct an appropriate template to format representing the + # printed input. + templates = [] + tensors = [] + # If an input to the print function is of type `OrderedDict`, sort its + # elements by the keys for consistency with the ordering of `nest.flatten`. + # This is not needed for `dict` types because `pprint.pformat()` takes care + # of printing the template in a sorted fashion. + inputs_ordered_dicts_sorted = [] + for input_ in inputs: + if isinstance(input_, py_collections.OrderedDict): + inputs_ordered_dicts_sorted.append( + py_collections.OrderedDict(sorted(input_.items()))) + else: + inputs_ordered_dicts_sorted.append(input_) + tensor_free_structure = nest.map_structure( + lambda x: "" if tensor_util.is_tf_type(x) else x, + inputs_ordered_dicts_sorted) + + tensor_free_template = " ".join( + pprint.pformat(x) for x in tensor_free_structure) + placeholder = _generate_placeholder_string(tensor_free_template) + + for input_ in inputs: + placeholders = [] + # Use the nest utilities to flatten & process any nested elements in this + # input. The placeholder for a tensor in the template should be the + # placeholder string, and the placeholder for a non-tensor can just be + # the printed value of the non-tensor itself. + for x in nest.flatten(input_): + # support sparse tensors + if isinstance(x, sparse_tensor.SparseTensor): + tensors.extend([x.indices, x.values, x.dense_shape]) + placeholders.append( + "SparseTensor(indices={}, values={}, shape={})".format( + placeholder, placeholder, placeholder)) + elif tensor_util.is_tf_type(x): + tensors.append(x) + placeholders.append(placeholder) + else: + placeholders.append(x) + + if isinstance(input_, str): + # If the current input to format/print is a normal string, that string + # can act as the template. + cur_template = input_ + else: + # We pack the placeholders into a data structure that matches the + # input data structure format, then format that data structure + # into a string template. + # + # NOTE: We must use pprint.pformat here for building the template for + # unordered data structures such as `dict`, because `str` doesn't + # guarantee orderings, while pprint prints in sorted order. pprint + # will match the ordering of `nest.flatten`. + # This even works when nest.flatten reorders OrderedDicts, because + # pprint is printing *after* the OrderedDicts have been reordered. + cur_template = pprint.pformat( + nest.pack_sequence_as(input_, placeholders)) + templates.append(cur_template) + + # We join the templates for the various inputs into a single larger + # template. We also remove all quotes surrounding the placeholders, so that + # the formatted/printed output will not contain quotes around tensors. + # (example of where these quotes might appear: if we have added a + # placeholder string into a list, then pretty-formatted that list) + template = sep.join(templates) + template = template.replace("'" + placeholder + "'", placeholder) + formatted_string = string_ops.string_format( + inputs=tensors, + template=template, + placeholder=placeholder, + summarize=summarize, + name=format_name) + + return gen_logging_ops.print_v2( + formatted_string, output_stream=output_stream_string, name=name, end=end) + + +# pylint: enable=g-doc-args + + +@ops.RegisterGradient("Print") +def _PrintGrad(op, *grad): + return list(grad) + [None] * (len(op.inputs) - 1) + + +def _Collect(val, collections, default_collections): + if collections is None: + collections = default_collections + for key in collections: + ops.add_to_collection(key, val) + + +@deprecated( + "2016-11-30", "Please switch to tf.summary.histogram. Note that " + "tf.summary.histogram uses the node name instead of the tag. " + "This means that TensorFlow will automatically de-duplicate summary " + "names based on the scope they are created in.") +def histogram_summary(tag, values, collections=None, name=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with a histogram. + + This ops is deprecated. Please switch to tf.summary.histogram. + + For an explanation of why this op was deprecated, and information on how to + migrate, look + ['here'](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/deprecated/__init__.py) + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + + This op reports an `InvalidArgument` error if any value is not finite. + + Args: + tag: A `string` `Tensor`. 0-D. Tag to use for the summary value. + values: A real numeric `Tensor`. Any shape. Values to use to build the + histogram. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + with ops.name_scope(name, "HistogramSummary", [tag, values]) as scope: + val = gen_logging_ops.histogram_summary(tag=tag, values=values, name=scope) + _Collect(val, collections, [ops.GraphKeys.SUMMARIES]) + return val + + +@deprecated( + "2016-11-30", "Please switch to tf.summary.image. Note that " + "tf.summary.image uses the node name instead of the tag. " + "This means that TensorFlow will automatically de-duplicate summary " + "names based on the scope they are created in. Also, the max_images " + "argument was renamed to max_outputs.") +def image_summary(tag, tensor, max_images=3, collections=None, name=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with images. + + For an explanation of why this op was deprecated, and information on how to + migrate, look + ['here'](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/deprecated/__init__.py) + + The summary has up to `max_images` summary values containing images. The + images are built from `tensor` which must be 4-D with shape `[batch_size, + height, width, channels]` and where `channels` can be: + + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + + The images have the same number of channels as the input tensor. For float + input, the values are normalized one image at a time to fit in the range + `[0, 255]`. `uint8` values are unchanged. The op uses two different + normalization algorithms: + + * If the input values are all positive, they are rescaled so the largest one + is 255. + + * If any input value is negative, the values are shifted so input value 0.0 + is at 127. They are then rescaled so that either the smallest value is 0, + or the largest one is 255. + + The `tag` argument is a scalar `Tensor` of type `string`. It is used to + build the `tag` of the summary values: + + * If `max_images` is 1, the summary value tag is '*tag*/image'. + * If `max_images` is greater than 1, the summary value tags are + generated sequentially as '*tag*/image/0', '*tag*/image/1', etc. + + Args: + tag: A scalar `Tensor` of type `string`. Used to build the `tag` of the + summary values. + tensor: A 4-D `uint8` or `float32` `Tensor` of shape `[batch_size, height, + width, channels]` where `channels` is 1, 3, or 4. + max_images: Max number of batch elements to generate images for. + collections: Optional list of ops.GraphKeys. The collections to add the + summary to. Defaults to [ops.GraphKeys.SUMMARIES] + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + with ops.name_scope(name, "ImageSummary", [tag, tensor]) as scope: + val = gen_logging_ops.image_summary( + tag=tag, tensor=tensor, max_images=max_images, name=scope) + _Collect(val, collections, [ops.GraphKeys.SUMMARIES]) + return val + + +@deprecated( + "2016-11-30", "Please switch to tf.summary.audio. Note that " + "tf.summary.audio uses the node name instead of the tag. " + "This means that TensorFlow will automatically de-duplicate summary " + "names based on the scope they are created in.") +def audio_summary(tag, + tensor, + sample_rate, + max_outputs=3, + collections=None, + name=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with audio. + + This op is deprecated. Please switch to tf.summary.audio. + For an explanation of why this op was deprecated, and information on how to + migrate, look + ['here'](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/deprecated/__init__.py) + + The summary has up to `max_outputs` summary values containing audio. The + audio is built from `tensor` which must be 3-D with shape `[batch_size, + frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are + assumed to be in the range of `[-1.0, 1.0]` with a sample rate of + `sample_rate`. + + The `tag` argument is a scalar `Tensor` of type `string`. It is used to + build the `tag` of the summary values: + + * If `max_outputs` is 1, the summary value tag is '*tag*/audio'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*tag*/audio/0', '*tag*/audio/1', etc. + + Args: + tag: A scalar `Tensor` of type `string`. Used to build the `tag` of the + summary values. + tensor: A 3-D `float32` `Tensor` of shape `[batch_size, frames, channels]` + or a 2-D `float32` `Tensor` of shape `[batch_size, frames]`. + sample_rate: A Scalar `float32` `Tensor` indicating the sample rate of the + signal in hertz. + max_outputs: Max number of batch elements to generate audio for. + collections: Optional list of ops.GraphKeys. The collections to add the + summary to. Defaults to [ops.GraphKeys.SUMMARIES] + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + with ops.name_scope(name, "AudioSummary", [tag, tensor]) as scope: + sample_rate = ops.convert_to_tensor( + sample_rate, dtype=dtypes.float32, name="sample_rate") + val = gen_logging_ops.audio_summary_v2( + tag=tag, + tensor=tensor, + max_outputs=max_outputs, + sample_rate=sample_rate, + name=scope) + _Collect(val, collections, [ops.GraphKeys.SUMMARIES]) + return val + + +@deprecated("2016-11-30", "Please switch to tf.summary.merge.") +def merge_summary(inputs, collections=None, name=None): + # pylint: disable=line-too-long + """Merges summaries. + + This op is deprecated. Please switch to tf.compat.v1.summary.merge, which has + identical + behavior. + + This op creates a + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + protocol buffer that contains the union of all the values in the input + summaries. + + When the Op is run, it reports an `InvalidArgument` error if multiple values + in the summaries to merge use the same tag. + + Args: + inputs: A list of `string` `Tensor` objects containing serialized `Summary` + protocol buffers. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer resulting from the merging. + """ + with ops.name_scope(name, "MergeSummary", inputs): + val = gen_logging_ops.merge_summary(inputs=inputs, name=name) + _Collect(val, collections, []) + return val + + +@deprecated("2016-11-30", "Please switch to tf.summary.merge_all.") +def merge_all_summaries(key=ops.GraphKeys.SUMMARIES): + """Merges all summaries collected in the default graph. + + This op is deprecated. Please switch to tf.compat.v1.summary.merge_all, which + has + identical behavior. + + Args: + key: `GraphKey` used to collect the summaries. Defaults to + `GraphKeys.SUMMARIES`. + + Returns: + If no summaries were collected, returns None. Otherwise returns a scalar + `Tensor` of type `string` containing the serialized `Summary` protocol + buffer resulting from the merging. + """ + summary_ops = ops.get_collection(key) + if not summary_ops: + return None + else: + return merge_summary(summary_ops) + + +def get_summary_op(): + """Returns a single Summary op that would run all summaries. + + Either existing one from `SUMMARY_OP` collection or merges all existing + summaries. + + Returns: + If no summaries were collected, returns None. Otherwise returns a scalar + `Tensor` of type `string` containing the serialized `Summary` protocol + buffer resulting from the merging. + """ + summary_op = ops.get_collection(ops.GraphKeys.SUMMARY_OP) + if summary_op is not None: + if summary_op: + summary_op = summary_op[0] + else: + summary_op = None + if summary_op is None: + summary_op = merge_all_summaries() + if summary_op is not None: + ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op) + return summary_op + + +@deprecated( + "2016-11-30", "Please switch to tf.summary.scalar. Note that " + "tf.summary.scalar uses the node name instead of the tag. " + "This means that TensorFlow will automatically de-duplicate summary " + "names based on the scope they are created in. Also, passing a " + "tensor or list of tags to a scalar summary op is no longer " + "supported.") +def scalar_summary(tags, values, collections=None, name=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with scalar values. + + This ops is deprecated. Please switch to tf.summary.scalar. + For an explanation of why this op was deprecated, and information on how to + migrate, look + ['here'](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/deprecated/__init__.py) + + The input `tags` and `values` must have the same shape. The generated + summary has a summary value for each tag-value pair in `tags` and `values`. + + Args: + tags: A `string` `Tensor`. Tags for the summaries. + values: A real numeric Tensor. Values for the summaries. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + with ops.name_scope(name, "ScalarSummary", [tags, values]) as scope: + val = gen_logging_ops.scalar_summary(tags=tags, values=values, name=scope) + _Collect(val, collections, [ops.GraphKeys.SUMMARIES]) + return val + + +ops.NotDifferentiable("HistogramSummary") +ops.NotDifferentiable("ImageSummary") +ops.NotDifferentiable("AudioSummary") +ops.NotDifferentiable("AudioSummaryV2") +ops.NotDifferentiable("MergeSummary") +ops.NotDifferentiable("ScalarSummary") +ops.NotDifferentiable("TensorSummary") +ops.NotDifferentiable("TensorSummaryV2") +ops.NotDifferentiable("Timestamp") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/lookup_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/lookup_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1f3ed12756346dc331fb9cc8ba617e7d4377484b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/lookup_ops.py @@ -0,0 +1,2480 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Lookup operations.""" +# pylint: disable=g-bad-name +import collections +import functools +import uuid + +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_lookup_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import string_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_lookup_ops import * +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import asset +# pylint: enable=wildcard-import +from tensorflow.python.trackable import base as trackable_base +from tensorflow.python.trackable import resource +from tensorflow.python.training.saver import BaseSaverBuilder +from tensorflow.python.types import internal +from tensorflow.python.util import compat as compat_util +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["initialize_all_tables"]) +@deprecated(None, "Use `tf.tables_initializer` instead.") +def initialize_all_tables(name="init_all_tables"): + """Returns an Op that initializes all tables of the default graph. + + Args: + name: Optional name for the initialization op. + + Returns: + An Op that initializes all tables. Note that if there are + not tables the returned Op is a NoOp. + """ + return tables_initializer(name) + + +@tf_export(v1=["initializers.tables_initializer", "tables_initializer"]) +def tables_initializer(name="init_all_tables"): + """Returns an Op that initializes all tables of the default graph. + + Args: + name: Optional name for the initialization op. + + Returns: + An Op that initializes all tables. Note that if there are + not tables the returned Op is a NoOp. + + @compatibility(TF2) + `tf.compat.v1.tables_initializer` is no longer needed with eager execution and + `tf.function`. In TF2, when creating an initializable table like a + `tf.lookup.StaticHashTable`, the table will automatically be initialized on + creation. + + #### Before & After Usage Example + + Before: + + >>> with tf.compat.v1.Session(): + ... init = tf.compat.v1.lookup.KeyValueTensorInitializer(['a', 'b'], [1, 2]) + ... table = tf.compat.v1.lookup.StaticHashTable(init, default_value=-1) + ... tf.compat.v1.tables_initializer().run() + ... result = table.lookup(tf.constant(['a', 'c'])).eval() + >>> result + array([ 1, -1], dtype=int32) + + After: + + >>> init = tf.lookup.KeyValueTensorInitializer(['a', 'b'], [1, 2]) + >>> table = tf.lookup.StaticHashTable(init, default_value=-1) + >>> table.lookup(tf.constant(['a', 'c'])).numpy() + array([ 1, -1], dtype=int32) + + @end_compatibility + """ + initializers = ops.get_collection(ops.GraphKeys.TABLE_INITIALIZERS) + if initializers: + return control_flow_ops.group(*initializers, name=name) + return control_flow_ops.no_op(name=name) + + +def check_table_dtypes(table, key_dtype, value_dtype): + """Check that the given key_dtype and value_dtype matches the table dtypes. + + Args: + table: The table to check types against to. + key_dtype: The key data type to check. + value_dtype: The value data type to check. + + Raises: + TypeError: when 'key_dtype' or 'value_dtype' doesn't match the table data + types. + """ + if key_dtype.base_dtype != table.key_dtype: + raise TypeError(f"Invalid key dtype for table, expected {table.key_dtype} " + f"but got {key_dtype}.") + if value_dtype.base_dtype != table.value_dtype: + raise TypeError("Invalid value dtype for table, expected " + f"{table.value_dtype} but got {value_dtype}.") + + +class LookupInterface(resource.TrackableResource): + """Represent a lookup table that persists across different steps.""" + + def __init__(self, key_dtype, value_dtype): + """Construct a lookup table interface. + + Args: + key_dtype: The table key type. + value_dtype: The table value type. + """ + self._key_dtype = dtypes.as_dtype(key_dtype) + self._value_dtype = dtypes.as_dtype(value_dtype) + super(LookupInterface, self).__init__() + + def _create_resource(self): + raise NotImplementedError + + @property + def key_dtype(self): + """The table key dtype.""" + return self._key_dtype + + @property + def value_dtype(self): + """The table value dtype.""" + return self._value_dtype + + @property + def name(self): + """The name of the table.""" + return NotImplementedError + + def size(self, name=None): + """Compute the number of elements in this table.""" + raise NotImplementedError + + def lookup(self, keys, name=None): + """Looks up `keys` in a table, outputs the corresponding values.""" + raise NotImplementedError + + def __getitem__(self, keys): + """Looks up `keys` in a table, outputs the corresponding values.""" + return self.lookup(keys) + + +class InitializableLookupTableBase(LookupInterface): + """Initializable lookup table interface. + + An initializable lookup tables persist across different steps. + """ + + def __init__(self, default_value, initializer): + """Construct a table object from a table reference. + + If requires a table initializer object (subclass of `TableInitializerBase`). + It provides the table key and value types, as well as the op to initialize + the table. The caller is responsible to execute the initialization op. + + Args: + default_value: The value to use if a key is missing in the table. + initializer: The table initializer to use. + """ + super(InitializableLookupTableBase, self).__init__(initializer.key_dtype, + initializer.value_dtype) + self._default_value = ops.convert_to_tensor( + default_value, dtype=self._value_dtype) + self._default_value.get_shape().merge_with(tensor_shape.TensorShape([])) + if isinstance(initializer, trackable_base.Trackable): + self._initializer = self._track_trackable(initializer, "_initializer") + with ops.init_scope(): + self._resource_handle = self._create_resource() + if (not context.executing_eagerly() and + ops.get_default_graph()._get_control_flow_context() is not None): # pylint: disable=protected-access + with ops.init_scope(): + self._init_op = self._initialize() + else: + self._init_op = self._initialize() + + def _initialize(self): + return self._initializer.initialize(self) + + @property + def default_value(self): + """The default value of the table.""" + return self._default_value + + def size(self, name=None): + """Compute the number of elements in this table. + + Args: + name: A name for the operation (optional). + + Returns: + A scalar tensor containing the number of elements in this table. + """ + with ops.name_scope(name, "%s_Size" % self.name, [self.resource_handle]): + return gen_lookup_ops.lookup_table_size_v2(self.resource_handle) + + def lookup(self, keys, name=None): + """Looks up `keys` in a table, outputs the corresponding values. + + The `default_value` is used for keys not present in the table. + + Args: + keys: Keys to look up. May be either a `SparseTensor` or dense `Tensor`. + name: A name for the operation (optional). + + Returns: + A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged, + otherwise a dense `Tensor`. + + Raises: + TypeError: when `keys` or `default_value` doesn't match the table data + types. + """ + key_tensor = keys + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + if isinstance(keys, (sparse_tensor.SparseTensor, internal.RaggedTensor)): + key_tensor = keys.values + + if keys.dtype.base_dtype != self._key_dtype: + raise TypeError(f"Dtype of argument `keys` must be {self._key_dtype}, " + f"received: {keys.dtype}") + + with ops.name_scope( + name, "%s_Lookup" % self.name, + (self.resource_handle, key_tensor, self._default_value)): + values = gen_lookup_ops.lookup_table_find_v2(self.resource_handle, + key_tensor, + self._default_value) + + values.set_shape(key_tensor.get_shape()) + if isinstance(keys, sparse_tensor.SparseTensor): + return sparse_tensor.SparseTensor(keys.indices, values, keys.dense_shape) + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + elif isinstance(keys, internal.RaggedTensor): + return keys.with_values(values) + else: + return values + + +class InitializableLookupTableBaseV1(InitializableLookupTableBase): + + @property + def initializer(self): + return self._init_op + + +@registration.register_tf_serializable( + predicate=lambda obj: isinstance(obj, StaticHashTable)) +@tf_export("lookup.StaticHashTable", v1=[]) +class StaticHashTable(InitializableLookupTableBase): + """A generic hash table that is immutable once initialized. + + Example usage: + + >>> keys_tensor = tf.constant(['a', 'b', 'c']) + >>> vals_tensor = tf.constant([7, 8, 9]) + >>> input_tensor = tf.constant(['a', 'f']) + >>> table = tf.lookup.StaticHashTable( + ... tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), + ... default_value=-1) + >>> table.lookup(input_tensor).numpy() + array([ 7, -1], dtype=int32) + + Or for more pythonic code: + + >>> table[input_tensor].numpy() + array([ 7, -1], dtype=int32) + + The result of a lookup operation has the same shape as the argument: + + >>> input_tensor = tf.constant([['a', 'b'], ['c', 'd']]) + >>> table[input_tensor].numpy() + array([[ 7, 8], + [ 9, -1]], dtype=int32) + + + """ + + def __init__(self, + initializer, + default_value, + name=None, + experimental_is_anonymous=False): + """Creates a non-initialized `HashTable` object. + + Creates a table, the type of its keys and values are specified by the + initializer. + Before using the table you will have to initialize it. After initialization + the table will be immutable. + + Args: + initializer: The table initializer to use. See `HashTable` kernel for + supported key and value types. + default_value: The value to use if a key is missing in the table. + name: A name for the operation (optional). + experimental_is_anonymous: Whether to use anonymous mode for the + table (default is False). In anonymous mode, the table + resource can only be accessed via a resource handle. It can't + be looked up by a name. When all resource handles pointing to + that resource are gone, the resource will be deleted + automatically. + + Returns: + A `HashTable` object. + """ + self._initializer = initializer + self._default_value = default_value + self._is_anonymous = experimental_is_anonymous + if not self._is_anonymous: + self._shared_name = self._initializer._shared_name # pylint: disable=protected-access + if not self._shared_name: + # Force using a shared name so that StaticHashTable resources can be + # shared across different kernels. If no "shared_name" is set and + # "use_node_name_sharing" is False, then each kernel gets its own local + # resource. + self._shared_name = "hash_table_%s" % (str(uuid.uuid4()),) + self._name = name or "hash_table" + self._table_name = None + super(StaticHashTable, self).__init__(default_value, initializer) + self._value_shape = self._default_value.get_shape() + + def _create_resource(self): + if self._is_anonymous: + table_ref = gen_lookup_ops.anonymous_hash_table( + key_dtype=self._initializer.key_dtype, + value_dtype=self._initializer.value_dtype, + name=self._name) + else: + table_ref = gen_lookup_ops.hash_table_v2( + shared_name=self._shared_name, + key_dtype=self._initializer.key_dtype, + value_dtype=self._initializer.value_dtype, + name=self._name) + if context.executing_eagerly(): + self._table_name = None + else: + self._table_name = table_ref.op.name.split("/")[-1] + return table_ref + + @property + def name(self): + return self._table_name + + def export(self, name=None): + """Returns tensors of all keys and values in the table. + + Args: + name: A name for the operation (optional). + + Returns: + A pair of tensors with the first tensor containing all keys and the + second tensors containing all values in the table. + """ + with ops.name_scope(name, "%s_Export" % self.name, [self.resource_handle]): + exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2( + self.resource_handle, self._key_dtype, self._value_dtype) + + exported_values.set_shape(exported_keys.get_shape().concatenate( + self._value_shape)) + return exported_keys, exported_values + + def _serialize_to_proto(self, **unused_kwargs): + return None + + def _add_trackable_child(self, name, value): + setattr(self, name, value) + if isinstance(value, trackable_base.Trackable): + self._track_trackable(value, name) # pylint:disable=protected-access + + @classmethod + def _deserialize_from_proto(cls, **kwargs): + + class _RestoredStaticHashTable(resource.RestoredResource): # pylint: disable=protected-access + + @classmethod + def _resource_type(cls): + return "RestoredStaticHashTable" + + return _RestoredStaticHashTable._deserialize_from_proto(**kwargs) # pylint: disable=protected-access + + +@tf_export(v1=["lookup.StaticHashTable"]) +class StaticHashTableV1(StaticHashTable): + """A generic hash table that is immutable once initialized. + + When running in graph mode, you must evaluate the tensor returned by + `tf.tables_initializer()` before evaluating the tensor returned by + this class's `lookup()` method. Example usage in graph mode: + + ```python + keys_tensor = tf.constant([1, 2]) + vals_tensor = tf.constant([3, 4]) + input_tensor = tf.constant([1, 5]) + table = tf.lookup.StaticHashTable( + tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1) + out = table.lookup(input_tensor) + with tf.Session() as sess: + sess.run(tf.tables_initializer()) + print(sess.run(out)) + ``` + + Note that in graph mode if you set `experimental_is_anonymous` to + `True`, you should only call `Session.run` once, otherwise each + `Session.run` will create (and destroy) a new table unrelated to + each other, leading to errors such as "Table not initialized". + You can do so like this: + + ```python + keys_tensor = tf.constant([1, 2]) + vals_tensor = tf.constant([3, 4]) + input_tensor = tf.constant([1, 5]) + table = tf.lookup.StaticHashTable( + tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1, + experimental_is_anonymous=True) + with tf.control_dependencies([tf.tables_initializer()]): + out = table.lookup(input_tensor) + with tf.Session() as sess: + print(sess.run(out)) + ``` + + In eager mode, no special code is needed to initialize the table. + Example usage in eager mode: + + ```python + tf.enable_eager_execution() + keys_tensor = tf.constant([1, 2]) + vals_tensor = tf.constant([3, 4]) + input_tensor = tf.constant([1, 5]) + table = tf.lookup.StaticHashTable( + tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1) + print(table.lookup(input_tensor)) + ``` + """ + + @property + def initializer(self): + return self._init_op + + +# For backwards compatibility. This will be removed in TF 2.0. +class HashTable(StaticHashTableV1): + + @property + def init(self): + return self.initializer + + +class TableInitializerBase(trackable_base.Trackable): + """Base class for lookup table initializers.""" + + def __init__(self, key_dtype, value_dtype): + """Construct a table initializer object. + + Args: + key_dtype: Type of the table keys. + value_dtype: Type of the table values. + """ + self._key_dtype = dtypes.as_dtype(key_dtype) + self._value_dtype = dtypes.as_dtype(value_dtype) + + @property + def key_dtype(self): + """The expected table key dtype.""" + return self._key_dtype + + @property + def value_dtype(self): + """The expected table value dtype.""" + return self._value_dtype + + def initialize(self, table): + """Returns the table initialization op.""" + raise NotImplementedError + + @property + def _shared_name(self): + """Returns a shared name to be used by the table.""" + shared_name = "" + if context.executing_eagerly(): + # Ensure a unique name when eager execution is enabled to avoid spurious + # sharing issues. + # TODO(rohanj): Use context.anonymous_name() instead. + shared_name += str(ops.uid()) + return shared_name + + +@tf_export("lookup.KeyValueTensorInitializer") +class KeyValueTensorInitializer(TableInitializerBase): + """Table initializers given `keys` and `values` tensors. + + >>> keys_tensor = tf.constant(['a', 'b', 'c']) + >>> vals_tensor = tf.constant([7, 8, 9]) + >>> input_tensor = tf.constant(['a', 'f']) + >>> init = tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor) + >>> table = tf.lookup.StaticHashTable( + ... init, + ... default_value=-1) + >>> table.lookup(input_tensor).numpy() + array([ 7, -1], dtype=int32) + + """ + + def __init__(self, keys, values, key_dtype=None, value_dtype=None, name=None): + """Constructs a table initializer object based on keys and values tensors. + + Args: + keys: The tensor for the keys. + values: The tensor for the values. + key_dtype: The `keys` data type. Used when `keys` is a python array. + value_dtype: The `values` data type. Used when `values` is a python array. + name: A name for the operation (optional). + """ + if (not context.executing_eagerly() and + ops.get_default_graph()._get_control_flow_context() is not None): # pylint: disable=protected-access + with ops.init_scope(): + self._keys = ops.convert_to_tensor(keys, dtype=key_dtype, name="keys") + self._values = ops.convert_to_tensor( + values, dtype=value_dtype, name="values") + else: + self._keys = ops.convert_to_tensor(keys, dtype=key_dtype, name="keys") + self._values = ops.convert_to_tensor( + values, dtype=value_dtype, name="values") + self._name = name if name is not None else "key_value_init" + if context.executing_eagerly(): + # Ensure a unique name when eager execution is enabled to avoid spurious + # sharing issues. + # TODO(rohanj): Use context.anonymous_name() instead. + self._name += str(ops.uid()) + + super(KeyValueTensorInitializer, self).__init__(self._keys.dtype, + self._values.dtype) + + def initialize(self, table): + """Initializes the given `table` with `keys` and `values` tensors. + + Args: + table: The table to initialize. + + Returns: + The operation that initializes the table. + + Raises: + TypeError: when the keys and values data types do not match the table + key and value data types. + """ + check_table_dtypes(table, self._keys.dtype, self._values.dtype) + with ops.name_scope( + self._name, values=(table.resource_handle, self._keys, self._values)): + init_op = gen_lookup_ops.lookup_table_import_v2(table.resource_handle, + self._keys, self._values) + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op) + return init_op + + +@tf_export("lookup.TextFileIndex") +class TextFileIndex: + """The key and value content to get from each line. + + This class defines the key and value used for `tf.lookup.TextFileInitializer`. + + The key and value content to get from each line is specified either + by the following, or a value `>=0`. + * `TextFileIndex.LINE_NUMBER` means use the line number starting from zero, + expects data type int64. + * `TextFileIndex.WHOLE_LINE` means use the whole line content, expects data + type string. + + A value `>=0` means use the index (starting at zero) of the split line based + on `delimiter`. + """ + WHOLE_LINE = -2 + LINE_NUMBER = -1 + + +@tf_export("lookup.TextFileInitializer") +class TextFileInitializer(TableInitializerBase): + r"""Table initializers from a text file. + + This initializer assigns one entry in the table for each line in the file. + + The key and value type of the table to initialize is given by `key_dtype` and + `value_dtype`. + + The key and value content to get from each line is specified by + the `key_index` and `value_index`. + + * `TextFileIndex.LINE_NUMBER` means use the line number starting from zero, + expects data type int64. + * `TextFileIndex.WHOLE_LINE` means use the whole line content, expects data + type string. + * A value `>=0` means use the index (starting at zero) of the split line based + on `delimiter`. + + For example if we have a file with the following content: + + >>> import tempfile + >>> f = tempfile.NamedTemporaryFile(delete=False) + >>> content='\n'.join(["emerson 10", "lake 20", "palmer 30",]) + >>> f.file.write(content.encode('utf-8')) + >>> f.file.close() + + The following snippet initializes a table with the first column as keys and + second column as values: + + * `emerson -> 10` + * `lake -> 20` + * `palmer -> 30` + + >>> init= tf.lookup.TextFileInitializer( + ... filename=f.name, + ... key_dtype=tf.string, key_index=0, + ... value_dtype=tf.int64, value_index=1, + ... delimiter=" ") + >>> table = tf.lookup.StaticHashTable(init, default_value=-1) + >>> table.lookup(tf.constant(['palmer','lake','tarkus'])).numpy() + + Similarly to initialize the whole line as keys and the line number as values. + + * `emerson 10 -> 0` + * `lake 20 -> 1` + * `palmer 30 -> 2` + + >>> init = tf.lookup.TextFileInitializer( + ... filename=f.name, + ... key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE, + ... value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER) + >>> table = tf.lookup.StaticHashTable(init, -1) + >>> table.lookup(tf.constant('palmer 30')).numpy() + 2 + """ + + def __init__(self, + filename, + key_dtype, + key_index, + value_dtype, + value_index, + vocab_size=None, + delimiter="\t", + name=None, + value_index_offset=0): + """Constructs a table initializer object to populate from a text file. + + It generates one key-value pair per line. The type of table key and + value are specified by `key_dtype` and `value_dtype`, respectively. + Similarly the content of the key and value are specified by the key_index + and value_index. + + - TextFileIndex.LINE_NUMBER means use the line number starting from zero, + expects data type int64. + - TextFileIndex.WHOLE_LINE means use the whole line content, expects data + type string or int64. + - A value >=0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Args: + filename: The filename of the text file to be used for initialization. The + path must be accessible from wherever the graph is initialized (eg. + trainer or eval workers). The filename may be a scalar `Tensor`. + key_dtype: The `key` data type. + key_index: the index that represents information of a line to get the + table 'key' values from. + value_dtype: The `value` data type. + value_index: the index that represents information of a line to get the + table 'value' values from.' + vocab_size: The number of elements in the file, if known. + delimiter: The delimiter to separate fields in a line. + name: A name for the operation (optional). + value_index_offset: A number to add to all indices extracted from the file + This is useful for cases where a user would like to reserve one or more + low index values for control characters. For instance, if you would + like to ensure that no vocabulary item is mapped to index 0 (so you can + reserve 0 for a masking value), you can set value_index_offset to 1; + this will mean that the first vocabulary element is mapped to 1 + instead of 0. + + Raises: + ValueError: when the filename is empty, or when the table key and value + data types do not match the expected data types. + """ + if not isinstance(filename, tensor_lib.Tensor) and not filename: + raise ValueError("`filename` argument required for tf.lookup.TextFileInitializer") + + self._filename_arg = filename + key_dtype = dtypes.as_dtype(key_dtype) + value_dtype = dtypes.as_dtype(value_dtype) + + if key_index < -2: + raise ValueError(f"`key_index` should be >= -2, received: {key_index}.") + + if key_index == TextFileIndex.LINE_NUMBER and key_dtype != dtypes.int64: + raise ValueError("`key_dtype` must be int64 if `key_index` is " + f"{TextFileIndex.LINE_NUMBER}, received: {key_dtype}") + if ((key_index == TextFileIndex.WHOLE_LINE) and + (not key_dtype.is_integer) and (key_dtype != dtypes.string)): + raise ValueError( + "`key_dtype` should be either integer or string for `key_index` " + f"{TextFileIndex.WHOLE_LINE}, received: {key_dtype}") + if value_index < -2: + raise ValueError("`value_index` should be >= -2, received: " + f"{value_index}") + + if value_index == TextFileIndex.LINE_NUMBER and value_dtype != dtypes.int64: + raise ValueError("`value_dtype` must be int64 for `value_index` " + f"{TextFileIndex.LINE_NUMBER}, received: {value_dtype}") + if ((value_index == TextFileIndex.WHOLE_LINE) and + (not value_dtype.is_integer) and (value_dtype != dtypes.string)): + raise ValueError( + "`value_dtype` should be either integer or string for `value_index` " + f"{TextFileIndex.WHOLE_LINE}, received: {value_dtype}") + + if (vocab_size is not None) and (vocab_size <= 0): + raise ValueError(f"`vocab_size` should be > 0, received: {vocab_size}") + + self._key_index = key_index + self._value_index = value_index + self._vocab_size = vocab_size + self._delimiter = delimiter + self._name = name + self._filename = self._track_trackable( + asset.Asset(filename), "_filename") + self._offset = value_index_offset + + super(TextFileInitializer, self).__init__(key_dtype, value_dtype) + + def initialize(self, table): + """Initializes the table from a text file. + + Args: + table: The table to be initialized. + + Returns: + The operation that initializes the table. + + Raises: + TypeError: when the keys and values data types do not match the table + key and value data types. + """ + check_table_dtypes(table, self.key_dtype, self.value_dtype) + with ops.name_scope(self._name, "text_file_init", (table.resource_handle,)): + filename = ops.convert_to_tensor( + self._filename, dtypes.string, name="asset_filepath") + init_op = gen_lookup_ops.initialize_table_from_text_file_v2( + table.resource_handle, filename, self._key_index, self._value_index, + -1 if self._vocab_size is None else self._vocab_size, self._delimiter, + self._offset) + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op) + # If the filename tensor is anything other than a string constant (e.g., + # if it is a placeholder) then it does not make sense to track it as an + # asset. + if not context.executing_eagerly() and constant_op.is_constant(filename): + ops.add_to_collection(ops.GraphKeys.ASSET_FILEPATHS, filename) + return init_op + + @property + def _shared_name(self): + if self._vocab_size: + # Keep the shared_name: + # _____ + if self._offset: + shared_name = "hash_table_%s_%d_%s_%s_%s" % ( + self._filename_arg, self._vocab_size, self._key_index, + self._value_index, self._offset) + else: + shared_name = "hash_table_%s_%d_%s_%s" % ( + self._filename_arg, self._vocab_size, self._key_index, + self._value_index) + else: + # Keep the shared_name + # ____ + if self._offset: + shared_name = "hash_table_%s_%s_%s_%s" % ( + self._filename_arg, self._key_index, self._value_index, + self._offset) + else: + shared_name = "hash_table_%s_%s_%s" % ( + self._filename_arg, self._key_index, self._value_index) + + return shared_name + + +class TextFileStringTableInitializer(TextFileInitializer): + """Table initializer for `int64` IDs to string tables from a text file.""" + + def __init__(self, + filename, + key_column_index=TextFileIndex.LINE_NUMBER, + value_column_index=TextFileIndex.WHOLE_LINE, + vocab_size=None, + delimiter="\t", + name="text_file_string_table_init"): + """Constructs an initializer for an id-to-string table from a text file. + + It populates a table that its key and value types are int64 and string, + respectively. It generates one key-value pair per line. + The content of the key and value are specified by `key_column_index` + and `value_column_index`. + + - TextFileIndex.LINE_NUMBER means use the line number starting from zero, + expects data type int64. + - TextFileIndex.WHOLE_LINE means use the whole line content, expects data + type string or int64. + - A value >=0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Args: + filename: The filename of the text file to be used for initialization. The + path must be accessible from wherever the graph is initialized (eg. + trainer or eval workers). The filename may be a scalar `Tensor`. + key_column_index: The column index from the text file to get the keys + from. The default is to use the line number, starting from zero. + value_column_index: The column index from the text file to get the values + from. The default is to use the whole line content. + vocab_size: The number of elements in the file, if known. + delimiter: The delimiter to separate fields in a line. + name: Optional name for the op. + + Raises: + TypeError: when the filename is empty, or when the table key and value + data types do not match the expected data types. + """ + super(TextFileStringTableInitializer, self).__init__( + filename, + dtypes.int64, + key_column_index, + dtypes.string, + value_column_index, + vocab_size=vocab_size, + delimiter=delimiter, + name=name) + + +class TextFileIdTableInitializer(TextFileInitializer): + """Table initializer for string to `int64` IDs tables from a text file.""" + + def __init__(self, + filename, + key_column_index=TextFileIndex.WHOLE_LINE, + value_column_index=TextFileIndex.LINE_NUMBER, + vocab_size=None, + delimiter="\t", + name="text_file_id_table_init", + key_dtype=dtypes.string): + """Constructs an initializer for an string-to-id table from a text file. + + It populates a table that its key and value types are string and int64, + respectively. It generates one key-value pair per line. + The content of the key and value are specified by the key_index + and value_index. + + - TextFileIndex.LINE_NUMBER means use the line number starting from zero, + expects data type int64. + - TextFileIndex.WHOLE_LINE means use the whole line content, expects data + type string. + - A value >=0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Args: + filename: The filename of the text file to be used for initialization. The + path must be accessible from wherever the graph is initialized (eg. + trainer or eval workers). The filename may be a scalar `Tensor`. + key_column_index: The column index from the text file to get the `key` + values from. The default is to use the whole line content. + value_column_index: The column index from the text file to get the `value` + values from. The default is to use the line number, starting from zero. + vocab_size: The number of elements in the file, if known. + delimiter: The delimiter to separate fields in a line. + name: Optional name for the op. + key_dtype: The `key` data type. + + Raises: + TypeError: when the filename is empty, or when the table key and value + data types do not match the expected data types. + """ + super(TextFileIdTableInitializer, self).__init__( + filename, + key_dtype, + key_column_index, + dtypes.int64, + value_column_index, + vocab_size=vocab_size, + delimiter=delimiter, + name=name) + + +class HasherSpec(collections.namedtuple("HasherSpec", ["hasher", "key"])): + """A structure for the spec of the hashing function to use for hash buckets. + + `hasher` is the name of the hashing function to use (eg. "fasthash", + "stronghash"). + `key` is optional and specify the key to use for the hash function if + supported, currently only used by a strong hash. + + Fields: + hasher: The hasher name to use. + key: The key to be used by the hashing function, if required. + """ + __slots__ = () + + +FastHashSpec = HasherSpec("fasthash", None) # pylint: disable=invalid-name + + +class StrongHashSpec(HasherSpec): + """A structure to specify a key of the strong keyed hash spec. + + The strong hash requires a `key`, which is a list of 2 unsigned integer + numbers. These should be non-zero; random numbers generated from random.org + would be a fine choice. + + Fields: + key: The key to be used by the keyed hashing function. + """ + __slots__ = () + + def __new__(cls, key): + if len(key) != 2: + raise ValueError(f"`key` must have size 2, received {len(key)}") + + if not isinstance(key[0], compat_util.integral_types) or not isinstance( + key[1], compat_util.integral_types): + raise TypeError("Invalid key %s. Must be unsigned integer values." % key) + + return super(cls, StrongHashSpec).__new__(cls, "stronghash", key) + + +def _as_string(tensor): + if dtypes.string == tensor.dtype.base_dtype: + return tensor + return string_ops.as_string(tensor) + + +class IdTableWithHashBuckets(LookupInterface): + r"""String to Id table wrapper that assigns out-of-vocabulary keys to buckets. + + For example, if an instance of `IdTableWithHashBuckets` is initialized with a + string-to-id table that maps: + + * `emerson -> 0` + * `lake -> 1` + * `palmer -> 2` + + The `IdTableWithHashBuckets` object will performs the following mapping: + + * `emerson -> 0` + * `lake -> 1` + * `palmer -> 2` + * ` -> bucket_id`, where bucket_id will be between `3` and + `3 + num_oov_buckets - 1`, calculated by: + `hash() % num_oov_buckets + vocab_size` + + If input_tensor is `["emerson", "lake", "palmer", "king", "crimson"]`, + the lookup result is `[0, 1, 2, 4, 7]`. + + If `table` is None, only out-of-vocabulary buckets are used. + + Example usage: + + ```python + num_oov_buckets = 3 + input_tensor = tf.constant(["emerson", "lake", "palmer", "king", "crimnson"]) + table = tf.IdTableWithHashBuckets( + tf.StaticHashTable( + tf.lookup.TextFileInitializer( + filename, + key_dtype=tf.string, + key_index=tf.lookup.TextFileIndex.WHOLE_LINE, + value_dtype=tf.int64, + value_index=tf.lookup.TextFileIndex.LINE_NUMBER, + delimiter="\t"), + default_value), + num_oov_buckets) + out = table.lookup(input_tensor). + table.init.run() + print(out.eval()) + ``` + + The hash function used for generating out-of-vocabulary buckets ID is handled + by `hasher_spec`. + """ + + def __init__(self, + table, + num_oov_buckets, + hasher_spec=FastHashSpec, + name=None, + key_dtype=None): + """Construct a `IdTableWithHashBuckets` object. + + Args: + table: Table that maps `tf.string` or `tf.int64` keys to `tf.int64` ids. + num_oov_buckets: Number of buckets to use for out-of-vocabulary keys. + hasher_spec: A `HasherSpec` to specify the hash function to use for + assignation of out-of-vocabulary buckets (optional). + name: A name for the operation (optional). + key_dtype: Data type of keys passed to `lookup`. Defaults to + `table.key_dtype` if `table` is specified, otherwise `tf.string`. Must + be string or integer, and must be castable to `table.key_dtype`. + + Raises: + ValueError: when `table` in None and `num_oov_buckets` is not positive. + TypeError: when `hasher_spec` is invalid. + """ + # If a name ends with a '/' it is a "name scope", remove all trailing '/' + # characters to use as table name. + if name: + name = name.rstrip("/") + if table: + if key_dtype is None: + key_dtype = table.key_dtype + supported_table_key_dtypes = (dtypes.int64, dtypes.string) + if table.key_dtype not in supported_table_key_dtypes: + raise TypeError("Invalid `key_dtype`, expected one of " + f"{supported_table_key_dtypes}, received {key_dtype}.") + if table.key_dtype.is_integer != key_dtype.is_integer: + raise TypeError("Invalid `key dtype`, expected %s but got %s." % + ("integer" if key_dtype.is_integer else "non-integer", + table.key_dtype)) + if table.value_dtype != dtypes.int64: + raise TypeError("Invalid `value_dtype`: expected int64 but got %s." % + (table.value_dtype)) + self._table = table + name = name or self._table.name + else: + if num_oov_buckets <= 0: + raise ValueError("`oov_buckets` must be > 0 if no `table` is supplied.") + key_dtype = dtypes.string if key_dtype is None else key_dtype + self._table = None + name = name or "hash_bucket" + if (not key_dtype.is_integer) and (dtypes.string != key_dtype): + raise TypeError("Invalid `key_dtype`, expected integer or string, got " + f"{key_dtype}.") + self._num_oov_buckets = num_oov_buckets + + if not isinstance(hasher_spec, HasherSpec): + raise TypeError("`hasher_spec` must be of type HasherSpec, got " + f"{type(hasher_spec)}.") + self._hasher_spec = hasher_spec + if name: + self._table_name = name.split("/")[-1] + else: + self._table_name = None + super(IdTableWithHashBuckets, self).__init__(key_dtype, dtypes.int64) + + def _create_resource(self): + if self._table is not None: + return self._table._create_resource() # pylint: disable=protected-access + return None + + def _initialize(self): + if self._table is not None: + return self._table._initialize() # pylint: disable=protected-access + with ops.name_scope(None, "init"): + return control_flow_ops.no_op() + + @property + def initializer(self): + if self._table is not None: + return self._table._init_op # pylint: disable=protected-access + with ops.name_scope(None, "init"): + return control_flow_ops.no_op() + + @property + @deprecated("2018-12-15", "Use `initializer` instead.") + def init(self): + return self.initializer + + @property + def resource_handle(self): + if self._table is not None: + return self._table.resource_handle + return None + + @property + def name(self): + return self._table_name + + def size(self, name=None): + """Compute the number of elements in this table.""" + with ops.name_scope(name, "%s_Size" % self.name): + if self._table: + tsize = self._table.size() + else: + tsize = ops.convert_to_tensor(0, dtype=dtypes.int64) + return tsize + self._num_oov_buckets + + def _get_string_to_hash_bucket_fn(self, hasher_spec): + """Returns the string_to_hash_bucket op to use based on `hasher_spec`.""" + if not isinstance(hasher_spec, HasherSpec): + raise TypeError("`hasher_spec` must be of type HasherSpec, got " + f"{type(hasher_spec)}.") + if hasher_spec.hasher == "fasthash": + return string_ops.string_to_hash_bucket_fast + if hasher_spec.hasher == "legacy": + return string_ops.string_to_hash_bucket + if hasher_spec.hasher == "stronghash": + return functools.partial( + string_ops.string_to_hash_bucket_strong, key=hasher_spec.key) + raise ValueError( + f"Found unknown hasher {hasher_spec.hasher} in `hasher_spec`") + + def lookup(self, keys, name=None): + """Looks up `keys` in the table, outputs the corresponding values. + + It assigns out-of-vocabulary keys to buckets based in their hashes. + + Args: + keys: Keys to look up. May be either a `SparseTensor` or dense `Tensor`. + name: Optional name for the op. + + Returns: + A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged, + otherwise a dense `Tensor`. + + Raises: + TypeError: when `keys` doesn't match the table key data type. + """ + if keys.dtype.base_dtype != self._key_dtype: + raise TypeError(f"Dtype of argument `keys` must be {self._key_dtype}, " + f"received: {keys.dtype}") + values = keys + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + if isinstance(keys, (sparse_tensor.SparseTensor, internal.RaggedTensor)): + values = keys.values + if self._table and (self._table.key_dtype.base_dtype == dtypes.int64): + values = math_ops.cast(values, dtypes.int64) + + if self._num_oov_buckets == 0: + ids = self._table.lookup(values, name=name) + else: + # TODO(yleon): Consider moving this functionality to its own kernel. + with ops.name_scope(name, "%s_Lookup" % self.name): + str_to_hash_bucket = self._get_string_to_hash_bucket_fn( + self._hasher_spec) + buckets = str_to_hash_bucket( + _as_string(values), + num_buckets=self._num_oov_buckets, + name="hash_bucket") + if self._table: + ids = self._table.lookup(values) + buckets = math_ops.add(buckets, self._table.size()) + is_id_non_default = math_ops.not_equal(ids, self._table.default_value) + ids = array_ops.where_v2(is_id_non_default, ids, buckets) + else: + ids = buckets + if isinstance(keys, sparse_tensor.SparseTensor): + return sparse_tensor.SparseTensor(keys.indices, ids, keys.dense_shape) + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + elif isinstance(keys, internal.RaggedTensor): + return keys.with_values(ids) + return ids + + +@tf_export("lookup.StaticVocabularyTable", v1=[]) +class StaticVocabularyTable(LookupInterface): + r"""String to Id table that assigns out-of-vocabulary keys to hash buckets. + + For example, if an instance of `StaticVocabularyTable` is initialized with a + string-to-id initializer that maps: + + >>> init = tf.lookup.KeyValueTensorInitializer( + ... keys=tf.constant(['emerson', 'lake', 'palmer']), + ... values=tf.constant([0, 1, 2], dtype=tf.int64)) + >>> table = tf.lookup.StaticVocabularyTable( + ... init, + ... num_oov_buckets=5) + + The `Vocabulary` object will performs the following mapping: + + * `emerson -> 0` + * `lake -> 1` + * `palmer -> 2` + * ` -> bucket_id`, where `bucket_id` will be between `3` and + `3 + num_oov_buckets - 1 = 7`, calculated by: + `hash() % num_oov_buckets + vocab_size` + + If input_tensor is: + + >>> input_tensor = tf.constant(["emerson", "lake", "palmer", + ... "king", "crimson"]) + >>> table[input_tensor].numpy() + array([0, 1, 2, 6, 7]) + + If `initializer` is None, only out-of-vocabulary buckets are used. + + Example usage: + + >>> num_oov_buckets = 3 + >>> vocab = ["emerson", "lake", "palmer", "crimnson"] + >>> import tempfile + >>> f = tempfile.NamedTemporaryFile(delete=False) + >>> f.write('\n'.join(vocab).encode('utf-8')) + >>> f.close() + + >>> init = tf.lookup.TextFileInitializer( + ... f.name, + ... key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE, + ... value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER) + >>> table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets) + >>> table.lookup(tf.constant(["palmer", "crimnson" , "king", + ... "tarkus", "black", "moon"])).numpy() + array([2, 3, 5, 6, 6, 4]) + + The hash function used for generating out-of-vocabulary buckets ID is + Fingerprint64. + + Note that the out-of-vocabulary bucket IDs always range from the table `size` + up to `size + num_oov_buckets - 1` regardless of the table values, which could + cause unexpected collisions: + + >>> init = tf.lookup.KeyValueTensorInitializer( + ... keys=tf.constant(["emerson", "lake", "palmer"]), + ... values=tf.constant([1, 2, 3], dtype=tf.int64)) + >>> table = tf.lookup.StaticVocabularyTable( + ... init, + ... num_oov_buckets=1) + >>> input_tensor = tf.constant(["emerson", "lake", "palmer", "king"]) + >>> table[input_tensor].numpy() + array([1, 2, 3, 3]) + """ + + def __init__(self, + initializer, + num_oov_buckets, + lookup_key_dtype=None, + name=None, + experimental_is_anonymous=False): + """Construct a `StaticVocabularyTable` object. + + Args: + initializer: A `TableInitializerBase` object that contains the data used + to initialize the table. If None, then we only use out-of-vocab buckets. + num_oov_buckets: Number of buckets to use for out-of-vocabulary keys. Must + be greater than zero. If out-of-vocab buckets are not required, use + `StaticHashTable` instead. + lookup_key_dtype: Data type of keys passed to `lookup`. Defaults to + `initializer.key_dtype` if `initializer` is specified, otherwise + `tf.string`. Must be string or integer, and must be castable to + `initializer.key_dtype`. + name: A name for the operation (optional). + experimental_is_anonymous: Whether to use anonymous mode for the + table (default is False). In anonymous mode, the table + resource can only be accessed via a resource handle. It can't + be looked up by a name. When all resource handles pointing to + that resource are gone, the resource will be deleted + automatically. + + Raises: + ValueError: when `num_oov_buckets` is not positive. + TypeError: when lookup_key_dtype or initializer.key_dtype are not + integer or string. Also when initializer.value_dtype != int64. + """ + if num_oov_buckets <= 0: + raise ValueError("`num_oov_buckets` must be > 0; use StaticHashTable.") + # If a name ends with a '/' it is a "name scope", remove all trailing '/' + # characters to use as table name. + if name: + name = name.rstrip("/") + if initializer: + if lookup_key_dtype is None: + lookup_key_dtype = initializer.key_dtype + supported_table_key_dtypes = (dtypes.int64, dtypes.string) + if initializer.key_dtype not in supported_table_key_dtypes: + raise TypeError("Invalid `key_dtype`, expected one of %s, but got %s." % + (supported_table_key_dtypes, initializer.key_dtype)) + if initializer.key_dtype.is_integer != lookup_key_dtype.is_integer: + raise TypeError( + "Invalid `key_dtype`, expected %s but got %s." % + ("integer" if lookup_key_dtype.is_integer else "non-integer", + initializer.key_dtype)) + if initializer.value_dtype != dtypes.int64: + raise TypeError("Invalid `value_dtype`, expected %s but got %s." % + (dtypes.int64, initializer.value_dtype)) + if isinstance(initializer, trackable_base.Trackable): + self._initializer = self._track_trackable(initializer, "_initializer") + self._table = HashTable( + initializer, + default_value=-1, + experimental_is_anonymous=experimental_is_anonymous) + name = name or self._table.name + else: + lookup_key_dtype = dtypes.string + self._table = None + name = name or "hash_bucket" + if (not lookup_key_dtype.is_integer) and (dtypes.string != + lookup_key_dtype): + raise TypeError("Invalid `key_dtype`, expected integer or string, got " + f"{lookup_key_dtype}") + self._num_oov_buckets = num_oov_buckets + + self._table_name = None + if name is not None: + self._table_name = name.split("/")[-1] + super(StaticVocabularyTable, self).__init__(lookup_key_dtype, dtypes.int64) + + def _create_resource(self): + if self._table is not None: + return self._table._create_resource() # pylint: disable=protected-access + return None + + def _initialize(self): + if self._table is not None: + return self._table._initialize() # pylint: disable=protected-access + with ops.name_scope(None, "init"): + return control_flow_ops.no_op() + + @property + def resource_handle(self): + if self._table is not None: + return self._table.resource_handle + return None + + @property + def name(self): + return self._table_name + + def size(self, name=None): + """Compute the number of elements in this table.""" + with ops.name_scope(name, "%s_Size" % self.name): + if self._table: + tsize = self._table.size() + else: + tsize = ops.convert_to_tensor(0, dtype=dtypes.int64) + return tsize + self._num_oov_buckets + + def lookup(self, keys, name=None): + """Looks up `keys` in the table, outputs the corresponding values. + + It assigns out-of-vocabulary keys to buckets based in their hashes. + + Args: + keys: Keys to look up. May be either a `SparseTensor` or dense `Tensor`. + name: Optional name for the op. + + Returns: + A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged, + otherwise a dense `Tensor`. + + Raises: + TypeError: when `keys` doesn't match the table key data type. + """ + if keys.dtype.base_dtype != self._key_dtype: + raise TypeError(f"Dtype of argument `keys` must be {self._key_dtype}, " + f"received: {keys.dtype}") + values = keys + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + if isinstance(keys, (sparse_tensor.SparseTensor, internal.RaggedTensor)): + values = keys.values + if self._table and (self._table.key_dtype.base_dtype == dtypes.int64): + values = math_ops.cast(values, dtypes.int64) + + # TODO(yleon): Consider moving this functionality to its own kernel. + with ops.name_scope(name, "%s_Lookup" % self.name): + buckets = string_ops.string_to_hash_bucket_fast( + _as_string(values), + num_buckets=self._num_oov_buckets, + name="hash_bucket") + if self._table: + ids = self._table.lookup(values) + buckets = math_ops.add(buckets, self._table.size()) + is_id_non_default = math_ops.not_equal(ids, self._table.default_value) + ids = array_ops.where_v2(is_id_non_default, ids, buckets) + else: + ids = buckets + if isinstance(keys, sparse_tensor.SparseTensor): + return sparse_tensor.SparseTensor(keys.indices, ids, keys.dense_shape) + # TODO(b/296302236): Remove RaggedTensor check by adding ragged + # dispatching. + elif isinstance(keys, internal.RaggedTensor): + return keys.with_values(ids) + return ids + + +@tf_export(v1=["lookup.StaticVocabularyTable"]) +class StaticVocabularyTableV1(StaticVocabularyTable): + + @property + def initializer(self): + if self._table is not None: + return self._table._init_op # pylint: disable=protected-access + with ops.name_scope(None, "init"): + return control_flow_ops.no_op() + + +def index_table_from_file(vocabulary_file=None, + num_oov_buckets=0, + vocab_size=None, + default_value=-1, + hasher_spec=FastHashSpec, + key_dtype=dtypes.string, + name=None, + key_column_index=TextFileIndex.WHOLE_LINE, + value_column_index=TextFileIndex.LINE_NUMBER, + delimiter="\t"): + """Returns a lookup table that converts a string tensor into int64 IDs. + + This operation constructs a lookup table to convert tensor of strings into + int64 IDs. The mapping can be initialized from a vocabulary file specified in + `vocabulary_file`, where the whole line is the key and the zero-based line + number is the ID. + + Any lookup of an out-of-vocabulary token will return a bucket ID based on its + hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the + `default_value`. + The bucket ID range is + `[vocabulary size, vocabulary size + num_oov_buckets - 1]`. + + The underlying table must be initialized by calling + `session.run(tf.compat.v1.tables_initializer())` or + `session.run(table.init())` once. + + To specify multi-column vocabulary files, use key_column_index and + value_column_index and delimiter. + + - TextFileIndex.LINE_NUMBER means use the line number starting from zero, + expects data type int64. + - TextFileIndex.WHOLE_LINE means use the whole line content, expects data + type string. + - A value >=0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Sample Usages: + + If we have a vocabulary file "test.txt" with the following content: + + ``` + emerson + lake + palmer + ``` + + ```python + features = tf.constant(["emerson", "lake", "and", "palmer"]) + table = tf.lookup.index_table_from_file( + vocabulary_file="test.txt", num_oov_buckets=1) + ids = table.lookup(features) + ... + tf.compat.v1.tables_initializer().run() + + ids.eval() ==> [0, 1, 3, 2] # where 3 is the out-of-vocabulary bucket + ``` + + Args: + vocabulary_file: The vocabulary filename, may be a constant scalar `Tensor`. + num_oov_buckets: The number of out-of-vocabulary buckets. + vocab_size: Number of the elements in the vocabulary, if known. + default_value: The value to use for out-of-vocabulary feature values. + Defaults to -1. + hasher_spec: A `HasherSpec` to specify the hash function to use for + assignation of out-of-vocabulary buckets. + key_dtype: The `key` data type. + name: A name for this op (optional). + key_column_index: The column index from the text file to get the `key` + values from. The default is to use the whole line content. + value_column_index: The column index from the text file to get the `value` + values from. The default is to use the line number, starting from zero. + delimiter: The delimiter to separate fields in a line. + + Returns: + The lookup table to map a `key_dtype` `Tensor` to index `int64` `Tensor`. + + Raises: + ValueError: If `vocabulary_file` is not set. + ValueError: If `num_oov_buckets` is negative or `vocab_size` is not greater + than zero. + """ + if vocabulary_file is None or (isinstance(vocabulary_file, str) and + not vocabulary_file): + raise ValueError( + "`vocabulary_file` must be specified and must not be empty.") + if num_oov_buckets < 0: + raise ValueError( + "num_oov_buckets must be greater or equal than 0, got %d." % + num_oov_buckets) + if vocab_size is not None and vocab_size < 1: + vocab_file_value = vocabulary_file + if isinstance(vocabulary_file, tensor_lib.Tensor): + vocab_file_value = tensor_util.constant_value(vocabulary_file) or "?" + raise ValueError("`vocab_size` must be greater than 0, got %d for " + "vocabulary_file: %s." % (vocab_size, vocab_file_value)) + if (not key_dtype.is_integer) and (dtypes.string != key_dtype.base_dtype): + raise TypeError("Dtype for `keys` should be either integer or string.") + + with ops.name_scope(name, "string_to_index"): + table = None + with ops.name_scope(None, "hash_table"): + init = TextFileIdTableInitializer( + vocabulary_file, + vocab_size=vocab_size, + key_dtype=dtypes.int64 if key_dtype.is_integer else key_dtype, + name="table_init", + key_column_index=key_column_index, + value_column_index=value_column_index, + delimiter=delimiter) + + table = StaticHashTableV1(init, default_value) + if num_oov_buckets: + table = IdTableWithHashBuckets( + table, + num_oov_buckets=num_oov_buckets, + hasher_spec=hasher_spec, + key_dtype=key_dtype) + + return table + + +def index_table_from_tensor(vocabulary_list, + num_oov_buckets=0, + default_value=-1, + hasher_spec=FastHashSpec, + dtype=dtypes.string, + name=None): + """Returns a lookup table that converts a string tensor into int64 IDs. + + This operation constructs a lookup table to convert tensor of strings into + int64 IDs. The mapping can be initialized from a string `vocabulary_list` 1-D + tensor where each element is a key and corresponding index within the tensor + is the value. + + Any lookup of an out-of-vocabulary token will return a bucket ID based on its + hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the + `default_value`. The bucket ID range is + `[vocabulary list size, vocabulary list size + num_oov_buckets - 1]`. + + The underlying table must be initialized by calling + `session.run(tf.compat.v1.tables_initializer())` or + `session.run(table.init())` once. + + Elements in `vocabulary_list` cannot have duplicates, otherwise when executing + the table initializer op, it will throw a `FailedPreconditionError`. + + Sample Usages: + + ```python + vocabulary_list = tf.constant(["emerson", "lake", "palmer"]) + table = tf.lookup.index_table_from_tensor( + vocabulary_list=vocabulary_list, num_oov_buckets=1, default_value=-1) + features = tf.constant(["emerson", "lake", "and", "palmer"]) + ids = table.lookup(features) + ... + tf.compat.v1.tables_initializer().run() + + ids.eval() ==> [0, 1, 4, 2] + ``` + + Args: + vocabulary_list: A 1-D `Tensor` that specifies the mapping of keys to + indices. The type of this object must be castable to `dtype`. + num_oov_buckets: The number of out-of-vocabulary buckets. + default_value: The value to use for out-of-vocabulary feature values. + Defaults to -1. + hasher_spec: A `HasherSpec` to specify the hash function to use for + assignment of out-of-vocabulary buckets. + dtype: The type of values passed to `lookup`. Only string and integers are + supported. + name: A name for this op (optional). + + Returns: + The lookup table to map an input `Tensor` to index `int64` `Tensor`. + + Raises: + ValueError: If `vocabulary_list` is invalid. + ValueError: If `num_oov_buckets` is negative. + """ + if vocabulary_list is None: + raise ValueError("`vocabulary_list` must be specified.") + + if num_oov_buckets < 0: + raise ValueError( + "`num_oov_buckets` must be greater or equal than 0, got %d." % + num_oov_buckets) + + if (not dtype.is_integer) and (dtypes.string != dtype.base_dtype): + raise TypeError("`dtype` must either be integer or string.") + + with ops.name_scope(name, "string_to_index"): + keys = ops.convert_to_tensor(vocabulary_list) + if keys.dtype.is_integer != dtype.is_integer: + raise ValueError( + "Invalid `dtype`: Expected %s, got %s." % + ("integer" if dtype.is_integer else "non-integer", keys.dtype)) + if (not dtype.is_integer) and (keys.dtype.base_dtype != dtype): + raise ValueError("Invalid `dtype`: Expected %s, got %s." % + (dtype, keys.dtype)) + num_elements = array_ops.size(keys) + values = math_ops.cast(math_ops.range(num_elements), dtypes.int64) + + with ops.name_scope(None, "hash_table"): + table_keys = math_ops.cast( + keys, dtypes.int64) if keys.dtype.is_integer else keys + init = KeyValueTensorInitializer( + table_keys, + values, + table_keys.dtype.base_dtype, + dtypes.int64, + name="table_init") + table = StaticHashTableV1(init, default_value) + if num_oov_buckets: + table = IdTableWithHashBuckets( + table, + num_oov_buckets=num_oov_buckets, + hasher_spec=hasher_spec, + key_dtype=dtype) + return table + + +def index_to_string_table_from_file(vocabulary_file, + vocab_size=None, + default_value="UNK", + name=None, + key_column_index=TextFileIndex.LINE_NUMBER, + value_column_index=TextFileIndex.WHOLE_LINE, + delimiter="\t"): + """Returns a lookup table that maps a `Tensor` of indices into strings. + + This operation constructs a lookup table to map int64 indices into string + values. The table is initialized from a vocabulary file specified in + `vocabulary_file`, where the whole line is the value and the + zero-based line number is the index. + + Any input which does not have a corresponding index in the vocabulary file + (an out-of-vocabulary entry) is assigned the `default_value` + + The underlying table must be initialized by calling + `session.run(tf.compat.v1.tables_initializer())` or + `session.run(table.init())` once. + + To specify multi-column vocabulary files, use key_column_index and + value_column_index and delimiter. + + - TextFileIndex.LINE_NUMBER means use the line number starting from zero, + expects data type int64. + - TextFileIndex.WHOLE_LINE means use the whole line content, expects data + type string. + - A value >=0 means use the index (starting at zero) of the split line based + on `delimiter`. + + Sample Usages: + + If we have a vocabulary file "test.txt" with the following content: + + ``` + emerson + lake + palmer + ``` + + ```python + indices = tf.constant([1, 5], tf.int64) + table = tf.lookup.index_to_string_table_from_file( + vocabulary_file="test.txt", default_value="UNKNOWN") + values = table.lookup(indices) + ... + tf.compat.v1.tables_initializer().run() + + values.eval() ==> ["lake", "UNKNOWN"] + ``` + + Args: + vocabulary_file: The vocabulary filename, may be a constant scalar `Tensor`. + vocab_size: Number of the elements in the vocabulary, if known. + default_value: The value to use for out-of-vocabulary indices. + name: A name for this op (optional). + key_column_index: The column index from the text file to get the `key` + values from. The default is to use the line number, starting from zero. + value_column_index: The column index from the text file to get the `value` + values from. The default is to use the whole line content. + delimiter: The delimiter to separate fields in a line. + + Returns: + The lookup table to map a string values associated to a given index `int64` + `Tensors`. + + Raises: + ValueError: when `vocabulary_file` is empty. + ValueError: when `vocab_size` is invalid. + """ + if vocabulary_file is None or (isinstance(vocabulary_file, str) and + not vocabulary_file): + raise ValueError( + "`vocabulary_file` must be specified and must not be empty.") + + if vocab_size is not None and vocab_size < 1: + raise ValueError(f"`vocab_size` must be greater than 0, got {vocab_size}.") + + with ops.name_scope(name, "index_to_string"): + init = TextFileStringTableInitializer( + vocabulary_file, + vocab_size=vocab_size, + name="table_init", + key_column_index=key_column_index, + value_column_index=value_column_index, + delimiter=delimiter) + + # TODO(yleon): Use a more efficient structure. + return StaticHashTableV1(init, default_value) + + +def index_to_string_table_from_tensor(vocabulary_list, + default_value="UNK", + name=None): + """Returns a lookup table that maps a `Tensor` of indices into strings. + + This operation constructs a lookup table to map int64 indices into string + values. The mapping is initialized from a string `vocabulary_list` 1-D + `Tensor` where each element is a value and the corresponding index within the + tensor is the key. + + Any input which does not have a corresponding index in 'vocabulary_list' + (an out-of-vocabulary entry) is assigned the `default_value` + + The underlying table must be initialized by calling + `session.run(tf.compat.v1.tables_initializer())` or + `session.run(table.init())` once. + + Elements in `vocabulary_list` cannot have duplicates, otherwise when executing + the table initializer op, it will throw a `FailedPreconditionError`. + + Sample Usages: + + ```python + vocabulary_list = tf.constant(["emerson", "lake", "palmer"]) + indices = tf.constant([1, 5], tf.int64) + table = tf.lookup.index_to_string_table_from_tensor( + vocabulary_list, default_value="UNKNOWN") + values = table.lookup(indices) + ... + tf.compat.v1.tables_initializer().run() + + values.eval() ==> ["lake", "UNKNOWN"] + ``` + + Args: + vocabulary_list: A 1-D string `Tensor` that specifies the strings to map + from indices. + default_value: The value to use for out-of-vocabulary indices. + name: A name for this op (optional). + + Returns: + The lookup table to map a string values associated to a given index `int64` + `Tensors`. + + Raises: + ValueError: when `vocabulary_list` is not set. + """ + + if vocabulary_list is None: + raise ValueError("`vocabulary_list` argument must be specified.") + + with ops.name_scope(name, "index_to_string"): + vocabulary_list = ops.convert_to_tensor(vocabulary_list, dtypes.string) + num_elements = array_ops.size(vocabulary_list) + keys = math_ops.cast(math_ops.range(num_elements), dtypes.int64) + + init = KeyValueTensorInitializer( + keys, vocabulary_list, dtypes.int64, dtypes.string, name="table_init") + # TODO(yleon): Use a more efficient structure. + return StaticHashTableV1(init, default_value) + + +@tf_export("lookup.experimental.MutableHashTable") +@saveable_compat.legacy_saveable_name("table") +class MutableHashTable(LookupInterface): + """A generic mutable hash table implementation. + + Data can be inserted by calling the `insert` method and removed by calling the + `remove` method. It does not support initialization via the init method. + + `MutableHashTable` requires additional memory during checkpointing and restore + operations to create temporary key and value tensors. + + Example usage: + + >>> table = tf.lookup.experimental.MutableHashTable(key_dtype=tf.string, + ... value_dtype=tf.int64, + ... default_value=-1) + >>> keys_tensor = tf.constant(['a', 'b', 'c']) + >>> vals_tensor = tf.constant([7, 8, 9], dtype=tf.int64) + >>> input_tensor = tf.constant(['a', 'f']) + >>> table.insert(keys_tensor, vals_tensor) + >>> table.lookup(input_tensor).numpy() + array([ 7, -1]) + >>> table.remove(tf.constant(['c'])) + >>> table.lookup(keys_tensor).numpy() + array([ 7, 8, -1]) + >>> sorted(table.export()[0].numpy()) + [b'a', b'b'] + >>> sorted(table.export()[1].numpy()) + [7, 8] + """ + + def __init__(self, + key_dtype, + value_dtype, + default_value, + name="MutableHashTable", + checkpoint=True, + experimental_is_anonymous=False): + """Creates an empty `MutableHashTable` object. + + Creates a table, the type of its keys and values are specified by key_dtype + and value_dtype, respectively. + + Args: + key_dtype: the type of the key tensors. + value_dtype: the type of the value tensors. + default_value: The value to use if a key is missing in the table. + name: A name for the operation (optional). + checkpoint: if True, the contents of the table are saved to and restored + from checkpoints. If `shared_name` is empty for a checkpointed table, it + is shared using the table node name. + experimental_is_anonymous: Whether to use anonymous mode for the + table (default is False). In anonymous mode, the table + resource can only be accessed via a resource handle. It can't + be looked up by a name. When all resource handles pointing to + that resource are gone, the resource will be deleted + automatically. + + Returns: + A `MutableHashTable` object. + + Raises: + ValueError: If checkpoint is True and no name was specified. + """ + self._default_value = ops.convert_to_tensor( + default_value, dtype=value_dtype) + self._value_shape = self._default_value.get_shape() + self._checkpoint = checkpoint + self._key_dtype = key_dtype + self._value_dtype = value_dtype + self._name = name + self._is_anonymous = experimental_is_anonymous + if not self._is_anonymous: + self._shared_name = None + if context.executing_eagerly(): + # TODO(allenl): This will leak memory due to kernel caching by + # the shared_name attribute value (but is better than the + # alternative of sharing everything by default when executing + # eagerly; hopefully creating tables in a loop is uncommon). + self._shared_name = "table_%d" % (ops.uid(),) + super(MutableHashTable, self).__init__(key_dtype, value_dtype) + self._resource_handle = self._create_resource() + if checkpoint: + saveable = MutableHashTable._Saveable(self, name) + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) + + def _create_resource(self): + if self._is_anonymous: + if self._default_value.get_shape().ndims == 0: + table_ref = gen_lookup_ops.anonymous_mutable_hash_table( + key_dtype=self._key_dtype, + value_dtype=self._value_dtype, + name=self._name) + else: + table_ref = gen_lookup_ops.anonymous_mutable_hash_table_of_tensors( + key_dtype=self._key_dtype, + value_dtype=self._value_dtype, + value_shape=self._default_value.get_shape(), + name=self._name) + else: + # The table must be shared if checkpointing is requested for multi-worker + # training to work correctly. Use the node name if no shared_name has been + # explicitly specified. + use_node_name_sharing = self._checkpoint and self._shared_name is None + if self._default_value.get_shape().ndims == 0: + table_ref = gen_lookup_ops.mutable_hash_table_v2( + shared_name=self._shared_name, + use_node_name_sharing=use_node_name_sharing, + key_dtype=self._key_dtype, + value_dtype=self._value_dtype, + name=self._name) + else: + table_ref = gen_lookup_ops.mutable_hash_table_of_tensors_v2( + shared_name=self._shared_name, + use_node_name_sharing=use_node_name_sharing, + key_dtype=self._key_dtype, + value_dtype=self._value_dtype, + value_shape=self._default_value.get_shape(), + name=self._name) + + if context.executing_eagerly(): + self._table_name = None + else: + self._table_name = table_ref.op.name.split("/")[-1] + return table_ref + + @property + def name(self): + return self._table_name + + def size(self, name=None): + """Compute the number of elements in this table. + + Args: + name: A name for the operation (optional). + + Returns: + A scalar tensor containing the number of elements in this table. + """ + with ops.name_scope(name, "%s_Size" % self.name, [self.resource_handle]): + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_size_v2(self.resource_handle) + + def remove(self, keys, name=None): + """Removes `keys` and its associated values from the table. + + If a key is not present in the table, it is silently ignored. + + Args: + keys: Keys to remove. Can be a tensor of any shape. Must match the table's + key type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + if keys.dtype != self._key_dtype: + raise TypeError(f"Dtype of argument `keys` must be {self._key_dtype}, " + f"received: {keys.dtype}") + + with ops.name_scope(name, "%s_lookup_table_remove" % self.name, + (self.resource_handle, keys, self._default_value)): + op = gen_lookup_ops.lookup_table_remove_v2(self.resource_handle, keys) + + return op + + def lookup(self, keys, dynamic_default_values=None, name=None): + """Looks up `keys` in a table, outputs the corresponding values. + + The `default_value` is used for keys not present in the table. + + Args: + keys: Keys to look up. Can be a tensor of any shape. Must match the + table's key_dtype. + dynamic_default_values: The values to use if a key is missing in the + table. If None (by default), the `table.default_value` will be used. + Shape of `dynamic_default_values` must be same with + `table.default_value` or the lookup result tensor. + In the latter case, each key will have a different default value. + + For example: + + ```python + keys = [0, 1, 3] + dynamic_default_values = [[1, 3, 4], [2, 3, 9], [8, 3, 0]] + + # The key '0' will use [1, 3, 4] as default value. + # The key '1' will use [2, 3, 9] as default value. + # The key '3' will use [8, 3, 0] as default value. + ``` + + name: A name for the operation (optional). + + Returns: + A tensor containing the values in the same shape as `keys` using the + table's value type. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + with ops.name_scope(name, "%s_lookup_table_find" % self.name, + (self.resource_handle, keys, self._default_value)): + keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys") + with ops.colocate_with(self.resource_handle): + values = gen_lookup_ops.lookup_table_find_v2( + self.resource_handle, keys, dynamic_default_values + if dynamic_default_values is not None else self._default_value) + return values + + def insert(self, keys, values, name=None): + """Associates `keys` with `values`. + + Args: + keys: Keys to insert. Can be a tensor of any shape. Must match the table's + key type. + values: Values to be associated with keys. Must be a tensor of the same + shape as `keys` and match the table's value type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` or `values` doesn't match the table data + types. + """ + with ops.name_scope(name, "%s_lookup_table_insert" % self.name, + [self.resource_handle, keys, values]): + keys = ops.convert_to_tensor(keys, self._key_dtype, name="keys") + values = ops.convert_to_tensor(values, self._value_dtype, name="values") + with ops.colocate_with(self.resource_handle): + # pylint: disable=protected-access + op = gen_lookup_ops.lookup_table_insert_v2(self.resource_handle, keys, + values) + return op + + def export(self, name=None): + """Returns tensors of all keys and values in the table. + + Args: + name: A name for the operation (optional). + + Returns: + A pair of tensors with the first tensor containing all keys and the + second tensors containing all values in the table. + """ + with ops.name_scope(name, "%s_lookup_table_export_values" % self.name, + [self.resource_handle]): + with ops.colocate_with(self.resource_handle): + exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2( + self.resource_handle, self._key_dtype, self._value_dtype) + return exported_keys, exported_values + + def _serialize_to_tensors(self): + """Implements checkpointing protocols for `Trackable`.""" + tensors = self.export() + return {"-keys": tensors[0], "-values": tensors[1]} + + def _restore_from_tensors(self, restored_tensors): + """Implements checkpointing protocols for `Trackable`.""" + with ops.name_scope("%s_table_restore" % self._name): + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_import_v2( + self.resource_handle, + restored_tensors["-keys"], + restored_tensors["-values"]) + + def _copy_trackable_to_cpu(self, object_map): + """Implements checkpointing protocols for `Trackable`.""" + if self not in object_map: + # If self is not already populated in object map, instantiate the copy + object_map[self] = MutableHashTable( + self._key_dtype, + self._value_dtype, + self._default_value, + self._name, + self._checkpoint, + self._is_anonymous + ) + + # Copy values from `self` to copy of `self` + serialized = self._serialize_to_tensors() + object_map[self]._restore_from_tensors(serialized) # pylint: disable=protected-access + + # This class is needed for `MutableHashTable(checkpoint=True)`. + class _Saveable(BaseSaverBuilder.SaveableObject): + """SaveableObject implementation for DenseHashTable.""" + + def __init__(self, table, name, table_name=None): + tensors = table.export() + specs = [ + BaseSaverBuilder.SaveSpec(tensors[0], "", name + "-keys"), + BaseSaverBuilder.SaveSpec(tensors[1], "", name + "-values") + ] + self.table_name = table_name or name + # pylint: disable=protected-access + super(MutableHashTable._Saveable, self).__init__(table, specs, name) + + def restore(self, restored_tensors, restored_shapes): + del restored_shapes # unused + # pylint: disable=protected-access + with ops.name_scope("%s_table_restore" % self.table_name): + with ops.colocate_with(self.op.resource_handle): + return gen_lookup_ops.lookup_table_import_v2(self.op.resource_handle, + restored_tensors[0], + restored_tensors[1]) + + +@tf_export("lookup.experimental.DenseHashTable") +@saveable_compat.legacy_saveable_name("table") +class DenseHashTable(LookupInterface): + """A mutable hash table with faster lookups and higher memory usage. + + Data can be inserted by calling the `insert` method and removed by calling the + `remove` method. It does not support initialization via the init method. + + Compared to `MutableHashTable`, `DenseHashTable` offers generally faster + `insert`, `remove` and `lookup` operations, in exchange for a higher overall + memory footprint. + + It uses "open addressing" with quadratic reprobing to resolve collisions. This + requires specifying two keys in the key space, `empty_key` and `deleted_key`, + that can never inserted into the table. + + Unlike `MutableHashTable`, `DenseHashTable` does not require additional memory + for temporary tensors created during checkpointing and restore operations. + + Example usage: + + >>> table = tf.lookup.experimental.DenseHashTable( + ... key_dtype=tf.string, + ... value_dtype=tf.int64, + ... default_value=-1, + ... empty_key='', + ... deleted_key='$') + >>> keys = tf.constant(['a', 'b', 'c']) + >>> values = tf.constant([0, 1, 2], dtype=tf.int64) + >>> table.insert(keys, values) + >>> table.remove(tf.constant(['c'])) + >>> table.lookup(tf.constant(['a', 'b', 'c','d'])).numpy() + array([ 0, 1, -1, -1]) + """ + + # TODO(andreasst): consider extracting common code with MutableHashTable into + # a common superclass. + def __init__(self, + key_dtype, + value_dtype, + default_value, + empty_key, + deleted_key, + initial_num_buckets=None, + name="MutableDenseHashTable", + checkpoint=True, + experimental_is_anonymous=False): + """Creates an empty `DenseHashTable` object. + + Creates a table, the type of its keys and values are specified by key_dtype + and value_dtype, respectively. + + Args: + key_dtype: the type of the key tensors. + value_dtype: the type of the value tensors. + default_value: The value to use if a key is missing in the table. + empty_key: the key to use to represent empty buckets internally. Must not + be used in insert, remove or lookup operations. + deleted_key: the key to use to represent deleted buckets internally. Must + not be used in insert, remove or lookup operations and be different from + the empty_key. + initial_num_buckets: the initial number of buckets (optional, + default to 2^17=131072). Note that the default value is + relatively large (~1MB), so if you are going to create many + tables (likely the case when `experimental_is_anonymous` is + `True`), you should set `initial_num_buckets` to a smaller + value to reduce memory usage. + name: A name for the operation (optional). + checkpoint: if True, the contents of the table are saved to and restored + from checkpoints. If `shared_name` is empty for a checkpointed table, it + is shared using the table node name. + experimental_is_anonymous: Whether to use anonymous mode for the + table (default is False). In anonymous mode, the table + resource can only be accessed via a resource handle. It can't + be looked up by a name. When all resource handles pointing to + that resource are gone, the resource will be deleted + automatically. + + Returns: + A `DenseHashTable` object. + + Raises: + ValueError: If checkpoint is True and no name was specified. + """ + self._default_value = ops.convert_to_tensor( + default_value, dtype=value_dtype, name="default_value") + self._key_dtype = key_dtype + self._value_dtype = value_dtype + # TODO(b/201578996): Pick a good default for initial_num_buckets + # other than 2^17. + self._initial_num_buckets = initial_num_buckets + self._value_shape = self._default_value.get_shape() + self._checkpoint = checkpoint + self._name = name + self._empty_key = empty_key + self._deleted_key = deleted_key + self._is_anonymous = experimental_is_anonymous + if not self._is_anonymous: + self._shared_name = None + if context.executing_eagerly(): + # TODO(allenl): This will leak memory due to kernel caching by + # the shared_name attribute value (but is better than the + # alternative of sharing everything by default when executing + # eagerly; hopefully creating tables in a loop is uncommon). + self._shared_name = "table_%d" % (ops.uid(),) + super(DenseHashTable, self).__init__(key_dtype, value_dtype) + self._resource_handle = self._create_resource() + if checkpoint: + saveable = DenseHashTable._Saveable(self, name) + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) + + def _create_resource(self): + empty_key = ops.convert_to_tensor( + self._empty_key, dtype=self._key_dtype, name="empty_key") + deleted_key = ops.convert_to_tensor( + self._deleted_key, dtype=self._key_dtype, name="deleted_key") + if self._is_anonymous: + table_ref = gen_lookup_ops.anonymous_mutable_dense_hash_table( + empty_key=empty_key, + deleted_key=deleted_key, + value_dtype=self._value_dtype, + value_shape=self._value_shape, + initial_num_buckets=self._initial_num_buckets, + name=self._name) + else: + # The table must be shared if checkpointing is requested for multi-worker + # training to work correctly. Use the node name if no shared_name has been + # explicitly specified. + use_node_name_sharing = self._checkpoint and self._shared_name is None + table_ref = gen_lookup_ops.mutable_dense_hash_table_v2( + empty_key=empty_key, + deleted_key=deleted_key, + shared_name=self._shared_name, + use_node_name_sharing=use_node_name_sharing, + value_dtype=self._value_dtype, + value_shape=self._value_shape, + initial_num_buckets=self._initial_num_buckets, + name=self._name) + if context.executing_eagerly(): + self._table_name = None + else: + self._table_name = table_ref.op.name.split("/")[-1] + return table_ref + + @property + def name(self): + return self._table_name + + def size(self, name=None): + """Compute the number of elements in this table. + + Args: + name: A name for the operation (optional). + + Returns: + A scalar tensor containing the number of elements in this table. + """ + with ops.name_scope(name, "%s_Size" % self.name, [self.resource_handle]): + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_size_v2(self.resource_handle) + + def lookup(self, keys, name=None): + """Looks up `keys` in a table, outputs the corresponding values. + + The `default_value` is used for keys not present in the table. + + Args: + keys: Keys to look up. Can be a tensor of any shape. Must match the + table's key_dtype. + name: A name for the operation (optional). + + Returns: + A tensor containing the values in the same shape as `keys` using the + table's value type. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + with ops.name_scope(name, "%s_lookup_table_find" % self.name, + [self.resource_handle, keys]): + keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys") + with ops.colocate_with(self.resource_handle): + values = gen_lookup_ops.lookup_table_find_v2(self.resource_handle, keys, + self._default_value) + + return values + + def insert_or_assign(self, keys, values, name=None): + """Associates `keys` with `values`. + + Args: + keys: Keys to insert. Can be a tensor of any shape. Must match the table's + key type. + values: Values to be associated with keys. Must be a tensor of the same + shape as `keys` and match the table's value type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` or `values` doesn't match the table data + types. + """ + with ops.name_scope(name, "%s_lookup_table_insert" % self.name, + [self.resource_handle, keys, values]): + keys = ops.convert_to_tensor(keys, dtype=self._key_dtype, name="keys") + values = ops.convert_to_tensor( + values, dtype=self._value_dtype, name="values") + with ops.colocate_with(self.resource_handle): + op = gen_lookup_ops.lookup_table_insert_v2(self.resource_handle, keys, + values) + return op + + def insert(self, keys, values, name=None): + """Associates `keys` with `values`. + + Args: + keys: Keys to insert. Can be a tensor of any shape. Must match the table's + key type. + values: Values to be associated with keys. Must be a tensor of the same + shape as `keys` and match the table's value type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` or `values` doesn't match the table data + types. + """ + return self.insert_or_assign(keys, values, name) + + def erase(self, keys, name=None): + """Removes `keys` and its associated values from the table. + + If a key is not present in the table, it is silently ignored. + + Args: + keys: Keys to remove. Can be a tensor of any shape. Must match the table's + key type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + if keys.dtype != self._key_dtype: + raise TypeError("Signature mismatch. Keys must be dtype %s, got %s." % + (self._key_dtype, keys.dtype)) + + with ops.name_scope(name, "%s_lookup_table_remove" % self.name, + (self.resource_handle, keys, self._default_value)): + # pylint: disable=protected-access + op = gen_lookup_ops.lookup_table_remove_v2(self.resource_handle, keys) + + return op + + def remove(self, keys, name=None): + """Removes `keys` and its associated values from the table. + + If a key is not present in the table, it is silently ignored. + + Args: + keys: Keys to remove. Can be a tensor of any shape. Must match the table's + key type. + name: A name for the operation (optional). + + Returns: + The created Operation. + + Raises: + TypeError: when `keys` do not match the table data types. + """ + return self.erase(keys, name) + + def export(self, name=None): + """Returns tensors of all keys and values in the table. + + Args: + name: A name for the operation (optional). + + Returns: + A pair of tensors with the first tensor containing all keys and the + second tensors containing all values in the table. + """ + with ops.name_scope(name, "%s_lookup_table_export_values" % self.name, + [self.resource_handle]): + with ops.colocate_with(self.resource_handle): + exported_keys, exported_values = gen_lookup_ops.lookup_table_export_v2( + self.resource_handle, self._key_dtype, self._value_dtype) + + return exported_keys, exported_values + + def _serialize_to_tensors(self): + """Implements checkpointing interface in `Trackable`.""" + tensors = self.export() + return {"-keys": tensors[0], "-values": tensors[1]} + + def _restore_from_tensors(self, restored_tensors): + """Implements checkpointing interface in `Trackable`.""" + with ops.name_scope("%s_table_restore" % self._name): + with ops.colocate_with(self.resource_handle): + return gen_lookup_ops.lookup_table_import_v2( + self.resource_handle, + restored_tensors["-keys"], + restored_tensors["-values"]) + + def _copy_trackable_to_cpu(self, object_map): + """Implements checkpointing protocols for `Trackable`.""" + if self not in object_map: + # If self is not already populated in object map, instantiate the copy + object_map[self] = DenseHashTable( + self._key_dtype, + self._value_dtype, + self._default_value, + self._empty_key, + self._deleted_key, + self._initial_num_buckets, + self._name, + self._checkpoint, + self._is_anonymous + ) + + # Copy values from `self` to copy of `self` + serialized = self._serialize_to_tensors() + object_map[self]._restore_from_tensors(serialized) # pylint: disable=protected-access + + # This class is needed for `DenseHashTable(checkpoint=True)`. + class _Saveable(BaseSaverBuilder.SaveableObject): + """SaveableObject implementation for DenseHashTable.""" + + def __init__(self, table, name, table_name=None): + tensors = table.export() + specs = [ + BaseSaverBuilder.SaveSpec(tensors[0], "", name + "-keys"), + BaseSaverBuilder.SaveSpec(tensors[1], "", name + "-values") + ] + self.table_name = table_name or name + # pylint: disable=protected-access + super(DenseHashTable._Saveable, self).__init__(table, specs, name) + + def restore(self, restored_tensors, restored_shapes): + del restored_shapes # unused + # pylint: disable=protected-access + with ops.name_scope("%s_table_restore" % self.table_name): + with ops.colocate_with(self.op.resource_handle): + return gen_lookup_ops.lookup_table_import_v2(self.op.resource_handle, + restored_tensors[0], + restored_tensors[1]) + + +ops.NotDifferentiable("LookupTableFind") +ops.NotDifferentiable("LookupTableFindV2") +ops.NotDifferentiable("LookupTableInsert") +ops.NotDifferentiable("LookupTableInsertV2") +ops.NotDifferentiable("LookupTableSize") +ops.NotDifferentiable("LookupTableSizeV2") +ops.NotDifferentiable("HashTable") +ops.NotDifferentiable("HashTableV2") +ops.NotDifferentiable("InitializeTable") +ops.NotDifferentiable("InitializeTableV2") +ops.NotDifferentiable("InitializeTableFromTextFile") +ops.NotDifferentiable("InitializeTableFromTextFileV2") +ops.NotDifferentiable("MutableDenseHashTable") +ops.NotDifferentiable("MutableDenseHashTableV2") +ops.NotDifferentiable("MutableHashTable") +ops.NotDifferentiable("MutableHashTableV2") +ops.NotDifferentiable("MutableHashTableOfTensors") +ops.NotDifferentiable("MutableHashTableOfTensorsV2") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..dcedaa21bc91eb125694ed9fd625ff5d90706e8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses.py @@ -0,0 +1,25 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Loss operations for use in neural networks. + +Note: All the losses are added to the `GraphKeys.LOSSES` collection by default. + +API docstring: tensorflow.losses +""" + +# pylint: disable=wildcard-import +from tensorflow.python.ops.losses.losses_impl import * +from tensorflow.python.ops.losses.util import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a2b27faa46b3f39d17d09f99640a53c9c41aa9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/losses_impl.py @@ -0,0 +1,1102 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of Loss operations for use in neural networks.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import confusion_matrix +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import weights_broadcast_ops +from tensorflow.python.ops.losses import util +from tensorflow.python.util import dispatch +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.deprecation import deprecated_argument_lookup +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["losses.Reduction"]) +class Reduction: + """Types of loss reduction. + + Contains the following values: + + * `NONE`: Un-reduced weighted losses with the same shape as input. + * `SUM`: Scalar sum of weighted losses. + * `MEAN`: Scalar `SUM` divided by sum of weights. DEPRECATED. + * `SUM_OVER_BATCH_SIZE`: Scalar `SUM` divided by number of elements in losses. + * `SUM_OVER_NONZERO_WEIGHTS`: Scalar `SUM` divided by number of non-zero + weights. DEPRECATED. + * `SUM_BY_NONZERO_WEIGHTS`: Same as `SUM_OVER_NONZERO_WEIGHTS`. DEPRECATED. + """ + + NONE = "none" + SUM = "weighted_sum" + SUM_OVER_BATCH_SIZE = "weighted_sum_over_batch_size" + MEAN = "weighted_mean" + SUM_BY_NONZERO_WEIGHTS = "weighted_sum_by_nonzero_weights" + SUM_OVER_NONZERO_WEIGHTS = SUM_BY_NONZERO_WEIGHTS + + @classmethod + def all(cls): + return ( + cls.NONE, + cls.SUM, + cls.MEAN, + cls.SUM_OVER_BATCH_SIZE, + cls.SUM_OVER_NONZERO_WEIGHTS, + cls.SUM_BY_NONZERO_WEIGHTS) + + @classmethod + def validate(cls, key): + if key not in cls.all(): + raise ValueError(f"Invalid Reduction Key {key}. Key should be one of " + f"{cls.all()}.") + + +def _safe_mean(losses, num_present): + """Computes a safe mean of the losses. + + Args: + losses: `Tensor` whose elements contain individual loss measurements. + num_present: The number of measurable elements in `losses`. + + Returns: + A scalar representing the mean of `losses`. If `num_present` is zero, + then zero is returned. + """ + total_loss = math_ops.reduce_sum(losses) + return math_ops.div_no_nan(total_loss, num_present, name="value") + + +def _num_present(losses, weights, per_batch=False): + """Computes the number of elements in the loss function induced by `weights`. + + A given weights tensor induces different numbers of usable elements in the + `losses` tensor. The `weights` tensor is broadcast across `losses` for all + possible dimensions. For example, if `losses` is a tensor of dimension + `[4, 5, 6, 3]` and `weights` is a tensor of shape `[4, 5]`, then `weights` is, + in effect, tiled to match the shape of `losses`. Following this effective + tile, the total number of present elements is the number of non-zero weights. + + Args: + losses: `Tensor` of shape `[batch_size, d1, ... dN]`. + weights: `Tensor` of shape `[]`, `[batch_size]` or + `[batch_size, d1, ... dK]`, where K < N. + per_batch: Whether to return the number of elements per batch or as a sum + total. + + Returns: + The number of present (non-zero) elements in the losses tensor. If + `per_batch` is `True`, the value is returned as a tensor of size + `[batch_size]`. Otherwise, a single scalar tensor is returned. + """ + if ((isinstance(weights, float) and weights != 0.0) or + (context.executing_eagerly() and weights._rank() == 0 # pylint: disable=protected-access + and not math_ops.equal(weights, 0.0))): + return _num_elements(losses) + with ops.name_scope(None, "num_present", (losses, weights)) as scope: + weights = math_ops.cast(weights, dtype=dtypes.float32) + present = array_ops.where( + math_ops.equal(weights, 0.0), + array_ops.zeros_like(weights), + array_ops.ones_like(weights)) + present = weights_broadcast_ops.broadcast_weights(present, losses) + if per_batch: + return math_ops.reduce_sum( + present, + axis=math_ops.range(1, array_ops.rank(present)), + keepdims=True, + name=scope) + return math_ops.reduce_sum(present, name=scope) + + +def _num_elements(losses): + """Computes the number of elements in `losses` tensor.""" + with ops.name_scope(None, "num_elements", values=[losses]) as scope: + return math_ops.cast(array_ops.size(losses, name=scope), dtype=losses.dtype) + + +@tf_export(v1=["losses.compute_weighted_loss"]) +@dispatch.add_dispatch_support +def compute_weighted_loss( + losses, weights=1.0, scope=None, loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Computes the weighted loss. + + Args: + losses: `Tensor` of shape `[batch_size, d1, ... dN]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `losses`, and must be broadcastable to `losses` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + scope: the scope for the operations performed in computing the loss. + loss_collection: the loss will be added to these collections. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss `Tensor` of the same type as `losses`. If `reduction` is + `NONE`, this has the same shape as `losses`; otherwise, it is scalar. + + Raises: + ValueError: If `weights` is `None` or the shape is not compatible with + `losses`, or if the number of dimensions (rank) of either `losses` or + `weights` is missing. + + Note: + When calculating the gradient of a weighted loss contributions from + both `losses` and `weights` are considered. If your `weights` depend + on some model parameters but you do not want this to affect the loss + gradient, you need to apply `tf.stop_gradient` to `weights` before + passing them to `compute_weighted_loss`. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + Reduction.validate(reduction) + with ops.name_scope(scope, "weighted_loss", (losses, weights)): + # Save the `reduction` argument for loss normalization when distributing + # to multiple replicas. Used only for estimator + v1 optimizer flow. + ops.get_default_graph()._last_loss_reduction = reduction # pylint: disable=protected-access + + def compute_loss(losses, weights, loss_collection, reduction): + losses = ops.convert_to_tensor(losses) + input_dtype = losses.dtype + losses = math_ops.cast(losses, dtype=dtypes.float32) + weights = math_ops.cast(weights, dtype=dtypes.float32) + weighted_losses = math_ops.multiply(losses, weights) + if reduction == Reduction.NONE: + loss = weighted_losses + else: + loss = math_ops.reduce_sum(weighted_losses) + if reduction == Reduction.MEAN: + loss = _safe_mean( + loss, math_ops.reduce_sum(array_ops.ones_like(losses) * weights)) + elif (reduction == Reduction.SUM_BY_NONZERO_WEIGHTS or + reduction == Reduction.SUM_OVER_NONZERO_WEIGHTS): + loss = _safe_mean(loss, _num_present(losses, weights)) + elif reduction == Reduction.SUM_OVER_BATCH_SIZE: + loss = _safe_mean(loss, _num_elements(losses)) + + # Convert the result back to the input type. + loss = math_ops.cast(loss, input_dtype) + util.add_loss(loss, loss_collection) + return loss + + # Skip the assert_broadcastable in XLA context because asserts are not + # supported so it only causes unnecessary ops. Also skip it because it uses + # a DenseToDenseSetOperation op that is incompatible with XLA when + # the shape(s) are dynamic. + if control_flow_ops.get_enclosing_xla_context() is not None: + return compute_loss(losses, weights, loss_collection, reduction) + else: + with ops.control_dependencies( + (weights_broadcast_ops.assert_broadcastable(weights, losses),)): + return compute_loss(losses, weights, loss_collection, reduction) + + +@tf_export(v1=["losses.absolute_difference"]) +@dispatch.add_dispatch_support +def absolute_difference( + labels, predictions, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Adds an Absolute Difference loss to the training procedure. + + `weights` acts as a coefficient for the loss. If a scalar is provided, then + the loss is simply scaled by the given value. If `weights` is a `Tensor` of + shape `[batch_size]`, then the total loss for each sample of the batch is + rescaled by the corresponding element in the `weights` vector. If the shape of + `weights` matches the shape of `predictions`, then the loss of each + measurable element of `predictions` is scaled by the corresponding value of + `weights`. + + Args: + labels: The ground truth output tensor, same dimensions as 'predictions'. + predictions: The predicted outputs. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which this loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `predictions` doesn't match that of + `labels` or if the shape of `weights` is invalid or if `labels` + or `predictions` is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "absolute_difference", + (predictions, labels, weights)) as scope: + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + losses = math_ops.abs(math_ops.subtract(predictions, labels)) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.cosine_distance"]) +@dispatch.add_dispatch_support +@deprecated_args(None, "dim is deprecated, use axis instead", "dim") +def cosine_distance( + labels, predictions, axis=None, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS, + dim=None): + """Adds a cosine-distance loss to the training procedure. + + Note that the function assumes that `predictions` and `labels` are already + unit-normalized. + + Args: + labels: `Tensor` whose shape matches 'predictions' + predictions: An arbitrary matrix. + axis: The dimension along which the cosine distance is computed. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which this loss will be added. + reduction: Type of reduction to apply to loss. + dim: The old (deprecated) name for `axis`. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If `predictions` shape doesn't match `labels` shape, or + `axis`, `labels`, `predictions` or `weights` is `None`. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + axis = deprecated_argument_lookup("axis", axis, "dim", dim) + if axis is None: + raise ValueError("You must specify argument `axis`.") + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "cosine_distance_loss", + (predictions, labels, weights)) as scope: + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + + radial_diffs = math_ops.multiply(predictions, labels) + losses = 1 - math_ops.reduce_sum(radial_diffs, axis=(axis,), keepdims=True) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.hinge_loss"]) +@dispatch.add_dispatch_support +def hinge_loss(labels, logits, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Adds a hinge loss to the training procedure. + + Args: + labels: The ground truth output tensor. Its shape should match the shape of + logits. The values of the tensor are expected to be 0.0 or 1.0. Internally + the {0,1} labels are converted to {-1,1} when calculating the hinge loss. + logits: The logits, a float tensor. Note that logits are assumed to be + unbounded and 0-centered. A value > 0 (resp. < 0) is considered a positive + (resp. negative) binary prediction. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shapes of `logits` and `labels` don't match or + if `labels` or `logits` is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if logits is None: + raise ValueError("Argument `logits` must not be None.") + with ops.name_scope(scope, "hinge_loss", (logits, labels, weights)) as scope: + logits = math_ops.cast(logits, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + logits.get_shape().assert_is_compatible_with(labels.get_shape()) + # We first need to convert binary labels to -1/1 labels (as floats). + all_ones = array_ops.ones_like(labels) + labels = math_ops.subtract(2 * labels, all_ones) + losses = nn_ops.relu( + math_ops.subtract(all_ones, math_ops.multiply(labels, logits))) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.huber_loss"]) +@dispatch.add_dispatch_support +def huber_loss(labels, predictions, weights=1.0, delta=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Adds a [Huber Loss](https://en.wikipedia.org/wiki/Huber_loss) term to the training procedure. + + For each value x in `error=labels-predictions`, the following is calculated: + + ``` + 0.5 * x^2 if |x| <= d + 0.5 * d^2 + d * (|x| - d) if |x| > d + ``` + + where d is `delta`. + + `weights` acts as a coefficient for the loss. If a scalar is provided, then + the loss is simply scaled by the given value. If `weights` is a tensor of size + `[batch_size]`, then the total loss for each sample of the batch is rescaled + by the corresponding element in the `weights` vector. If the shape of + `weights` matches the shape of `predictions`, then the loss of each + measurable element of `predictions` is scaled by the corresponding value of + `weights`. + + Args: + labels: The ground truth output tensor, same dimensions as 'predictions'. + predictions: The predicted outputs. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + delta: `float`, the point where the huber loss function changes from a + quadratic to linear. + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `predictions` doesn't match that of `labels` or + if the shape of `weights` is invalid. Also if `labels` or + `predictions` is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "huber_loss", + (predictions, labels, weights)) as scope: + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + error = math_ops.subtract(predictions, labels) + abs_error = math_ops.abs(error) + quadratic = math_ops.minimum(abs_error, delta) + # The following expression is the same in value as + # tf.maximum(abs_error - delta, 0), but importantly the gradient for the + # expression when abs_error == delta is 0 (for tf.maximum it would be 1). + # This is necessary to avoid doubling the gradient, since there is already a + # nonzero contribution to the gradient from the quadratic term. + linear = math_ops.subtract(abs_error, quadratic) + losses = math_ops.add( + math_ops.multiply( + ops.convert_to_tensor(0.5, dtype=quadratic.dtype), + math_ops.multiply(quadratic, quadratic)), + math_ops.multiply(delta, linear)) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.log_loss"]) +@dispatch.add_dispatch_support +def log_loss(labels, predictions, weights=1.0, epsilon=1e-7, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Adds a Log Loss term to the training procedure. + + `weights` acts as a coefficient for the loss. If a scalar is provided, then + the loss is simply scaled by the given value. If `weights` is a tensor of size + `[batch_size]`, then the total loss for each sample of the batch is rescaled + by the corresponding element in the `weights` vector. If the shape of + `weights` matches the shape of `predictions`, then the loss of each + measurable element of `predictions` is scaled by the corresponding value of + `weights`. + + Args: + labels: The ground truth output tensor, same dimensions as 'predictions'. + predictions: The predicted outputs. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + epsilon: A small increment to add to avoid taking a log of zero. + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `predictions` doesn't match that of `labels` or + if the shape of `weights` is invalid. Also if `labels` or `predictions` + is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "log_loss", + (predictions, labels, weights)) as scope: + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + losses = -math_ops.multiply( + labels, + math_ops.log(predictions + epsilon)) - math_ops.multiply( + (1 - labels), math_ops.log(1 - predictions + epsilon)) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +# TODO(b/37208492): Add reduction arg. +@tf_export(v1=["losses.mean_pairwise_squared_error"]) +@dispatch.add_dispatch_support +def mean_pairwise_squared_error( + labels, predictions, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES): + """Adds a pairwise-errors-squared loss to the training procedure. + + Unlike `mean_squared_error`, which is a measure of the differences between + corresponding elements of `predictions` and `labels`, + `mean_pairwise_squared_error` is a measure of the differences between pairs of + corresponding elements of `predictions` and `labels`. + + For example, if `labels`=[a, b, c] and `predictions`=[x, y, z], there are + three pairs of differences are summed to compute the loss: + loss = [ ((a-b) - (x-y)).^2 + ((a-c) - (x-z)).^2 + ((b-c) - (y-z)).^2 ] / 3 + + Note that since the inputs are of shape `[batch_size, d0, ... dN]`, the + corresponding pairs are computed within each batch sample but not across + samples within a batch. For example, if `predictions` represents a batch of + 16 grayscale images of dimension [batch_size, 100, 200], then the set of pairs + is drawn from each image, but not across images. + + `weights` acts as a coefficient for the loss. If a scalar is provided, then + the loss is simply scaled by the given value. If `weights` is a tensor of size + `[batch_size]`, then the total loss for each sample of the batch is rescaled + by the corresponding element in the `weights` vector. + + Args: + labels: The ground truth output tensor, whose shape must match the shape of + `predictions`. + predictions: The predicted outputs, a tensor of size + `[batch_size, d0, .. dN]` where N+1 is the total number of dimensions in + `predictions`. + weights: Coefficients for the loss a scalar, a tensor of shape + `[batch_size]` or a tensor whose shape matches `predictions`. + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + + Returns: + A scalar `Tensor` that returns the weighted loss. + + Raises: + ValueError: If the shape of `predictions` doesn't match that of `labels` or + if the shape of `weights` is invalid. Also if `labels` or `predictions` + is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "mean_pairwise_squared_error", + (predictions, labels, weights)) as scope: + weights = math_ops.cast(weights, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + + def compute_loss(labels, predictions, weights, loss_collection): + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + + diffs = math_ops.subtract(predictions, labels) + + axis = math_ops.range(1, array_ops.rank(diffs)) + + sum_squares_diff_per_batch = math_ops.reduce_sum( + math_ops.square(diffs), axis=axis, keepdims=True) + num_present_per_batch = _num_present(diffs, weights, per_batch=True) + + term1 = 2.0 * math_ops.div_no_nan( + sum_squares_diff_per_batch, + math_ops.maximum(num_present_per_batch - 1, 0), + name="value") + + sum_diff = math_ops.reduce_sum(diffs, axis=axis, keepdims=True) + term2 = 2.0 * math_ops.div_no_nan( + math_ops.square(sum_diff), + math_ops.maximum( + math_ops.multiply(num_present_per_batch, + num_present_per_batch - 1), 0), + name="value") + + weighted_losses = math_ops.multiply(term1 - term2, weights) + loss = math_ops.reduce_sum(weighted_losses) + + mean_loss = array_ops.where( + math_ops.reduce_sum(num_present_per_batch) > 0, + loss, + array_ops.zeros_like(loss), + name="value") + util.add_loss(mean_loss, loss_collection) + return mean_loss + + # Skip the assert_broadcastable in XLA context because asserts are not + # supported so it only causes unnecessary ops. Also skip it because it uses + # a DenseToDenseSetOperation op that is incompatible with XLA when + # the shape(s) are dynamic. + if control_flow_ops.get_enclosing_xla_context() is not None: + return compute_loss(labels, predictions, weights, loss_collection) + else: + with ops.control_dependencies( + (weights_broadcast_ops.assert_broadcastable(weights, labels),)): + return compute_loss(labels, predictions, weights, loss_collection) + + +@tf_export(v1=["losses.mean_squared_error"]) +@dispatch.add_dispatch_support +def mean_squared_error( + labels, predictions, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Adds a Sum-of-Squares loss to the training procedure. + + `weights` acts as a coefficient for the loss. If a scalar is provided, then + the loss is simply scaled by the given value. If `weights` is a tensor of size + `[batch_size]`, then the total loss for each sample of the batch is rescaled + by the corresponding element in the `weights` vector. If the shape of + `weights` matches the shape of `predictions`, then the loss of each + measurable element of `predictions` is scaled by the corresponding value of + `weights`. + + Args: + labels: The ground truth output tensor, same dimensions as 'predictions'. + predictions: The predicted outputs. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `losses` dimension). + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same + shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `predictions` doesn't match that of `labels` or + if the shape of `weights` is invalid. Also if `labels` or `predictions` + is None. + + @compatibility(TF2) + + `tf.compat.v1.losses.mean_squared_error` is mostly compatible with eager + execution and `tf.function`. But, the `loss_collection` argument is + ignored when executing eagerly and no loss will be written to the loss + collections. You will need to either hold on to the return value manually + or rely on `tf.keras.Model` loss tracking. + + + To switch to native TF2 style, instantiate the + `tf.keras.losses.MeanSquaredError` class and call the object instead. + + + #### Structural Mapping to Native TF2 + + Before: + + ```python + loss = tf.compat.v1.losses.mean_squared_error( + labels=labels, + predictions=predictions, + weights=weights, + reduction=reduction) + ``` + + After: + + ```python + loss_fn = tf.keras.losses.MeanSquaredError( + reduction=reduction) + loss = loss_fn( + y_true=labels, + y_pred=predictions, + sample_weight=weights) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :--------------- | :------------------------- | + | `labels` | `y_true` | In `__call__()` method | + | `predictions` | `y_pred` | In `__call__()` method | + | `weights` | `sample_weight` | In `__call__()` method. | + : : : The shape requirements for `sample_weight` is different from : + : : : `weights`. Please check the [argument definition][api_docs] for : + : : : details. : + | `scope` | Not supported | - | + | `loss_collection` | Not supported | Losses should be tracked | + : : : explicitly or with Keras APIs, for example, [add_loss][add_loss], : + : : : instead of via collections : + | `reduction` | `reduction` | In constructor. Value of | + : : : `tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE`, : + : : : `tf.compat.v1.losses.Reduction.SUM`, : + : : : `tf.compat.v1.losses.Reduction.NONE` in : + : : : `tf.compat.v1.losses.softmax_cross_entropy` correspond to : + : : : `tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE`, : + : : : `tf.keras.losses.Reduction.SUM`, : + : : : `tf.keras.losses.Reduction.NONE`, respectively. If you : + : : : used other value for `reduction`, including the default value : + : : : `tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS`, there is : + : : : no directly corresponding value. Please modify the loss : + : : : implementation manually. : + + [add_loss]:https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss + [api_docs]:https://www.tensorflow.org/api_docs/python/tf/keras/losses/MeanSquaredError#__call__ + + + #### Before & After Usage Example + + Before: + + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 3, 5] + >>> weights = [0, 1, 0.25] + >>> # samples with zero-weight are excluded from calculation when `reduction` + >>> # argument is set to default value `Reduction.SUM_BY_NONZERO_WEIGHTS` + >>> tf.compat.v1.losses.mean_squared_error( + ... labels=y_true, + ... predictions=y_pred, + ... weights=weights).numpy() + 1.0 + + >>> tf.compat.v1.losses.mean_squared_error( + ... labels=y_true, + ... predictions=y_pred, + ... weights=weights, + ... reduction=tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE).numpy() + 0.66667 + + After: + + >>> y_true = [[1.0], [2.0], [3.0]] + >>> y_pred = [[1.0], [3.0], [5.0]] + >>> weights = [1, 1, 0.25] + >>> mse = tf.keras.losses.MeanSquaredError( + ... reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE) + >>> mse(y_true=y_true, y_pred=y_pred, sample_weight=weights).numpy() + 0.66667 + + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if predictions is None: + raise ValueError("Argument `predictions` must not be None.") + with ops.name_scope(scope, "mean_squared_error", + (predictions, labels, weights)) as scope: + predictions = math_ops.cast(predictions, dtype=dtypes.float32) + labels = math_ops.cast(labels, dtype=dtypes.float32) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + losses = math_ops.squared_difference(predictions, labels) + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.sigmoid_cross_entropy"]) +@dispatch.add_dispatch_support +def sigmoid_cross_entropy( + multi_class_labels, logits, weights=1.0, label_smoothing=0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Creates a cross-entropy loss using tf.nn.sigmoid_cross_entropy_with_logits. + + `weights` acts as a coefficient for the loss. If a scalar is provided, + then the loss is simply scaled by the given value. If `weights` is a + tensor of shape `[batch_size]`, then the loss weights apply to each + corresponding sample. + + If `label_smoothing` is nonzero, smooth the labels towards 1/2: + + new_multiclass_labels = multiclass_labels * (1 - label_smoothing) + + 0.5 * label_smoothing + + Args: + multi_class_labels: `[batch_size, num_classes]` target integer labels in + `{0, 1}`. + logits: Float `[batch_size, num_classes]` logits outputs of the network. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `multi_class_labels`, and must be broadcastable to `multi_class_labels` + (i.e., all dimensions must be either `1`, or the same as the + corresponding `losses` dimension). + label_smoothing: If greater than `0` then smooth the labels. + scope: The scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss `Tensor` of the same type as `logits`. If `reduction` is + `NONE`, this has the same shape as `logits`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `logits` doesn't match that of + `multi_class_labels` or if the shape of `weights` is invalid, or if + `weights` is None. Also if `multi_class_labels` or `logits` is None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if multi_class_labels is None: + raise ValueError("Argument `multi_class_labels` must not be None.") + if logits is None: + raise ValueError("Argument `logits` must not be None.") + with ops.name_scope(scope, "sigmoid_cross_entropy_loss", + (logits, multi_class_labels, weights)) as scope: + logits = ops.convert_to_tensor(logits) + multi_class_labels = math_ops.cast(multi_class_labels, logits.dtype) + logits.get_shape().assert_is_compatible_with(multi_class_labels.get_shape()) + + if label_smoothing > 0: + multi_class_labels = (multi_class_labels * (1 - label_smoothing) + + 0.5 * label_smoothing) + + losses = nn.sigmoid_cross_entropy_with_logits(labels=multi_class_labels, + logits=logits, + name="xentropy") + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +@tf_export(v1=["losses.softmax_cross_entropy"]) +@dispatch.add_dispatch_support +def softmax_cross_entropy( + onehot_labels, logits, weights=1.0, label_smoothing=0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + r"""Creates a cross-entropy loss using tf.nn.softmax_cross_entropy_with_logits_v2. + + `weights` acts as a coefficient for the loss. If a scalar is provided, + then the loss is simply scaled by the given value. If `weights` is a + tensor of shape `[batch_size]`, then the loss weights apply to each + corresponding sample. + + If `label_smoothing` is nonzero, smooth the labels towards 1/num_classes: + new_onehot_labels = onehot_labels * (1 - label_smoothing) + + label_smoothing / num_classes + + Note that `onehot_labels` and `logits` must have the same shape, + e.g. `[batch_size, num_classes]`. The shape of `weights` must be + broadcastable to loss, whose shape is decided by the shape of `logits`. + In case the shape of `logits` is `[batch_size, num_classes]`, loss is + a `Tensor` of shape `[batch_size]`. + + Args: + onehot_labels: One-hot-encoded labels. + logits: Logits outputs of the network. + weights: Optional `Tensor` that is broadcastable to loss. + label_smoothing: If greater than 0 then smooth the labels. + scope: the scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss `Tensor` of the same type as `logits`. If `reduction` is + `NONE`, this has shape `[batch_size]`; otherwise, it is scalar. + + Raises: + ValueError: If the shape of `logits` doesn't match that of `onehot_labels` + or if the shape of `weights` is invalid or if `weights` is None. Also if + `onehot_labels` or `logits` is None. + + @compatibility(TF2) + + `tf.compat.v1.losses.softmax_cross_entropy` is mostly compatible with eager + execution and `tf.function`. But, the `loss_collection` argument is + ignored when executing eagerly and no loss will be written to the loss + collections. You will need to either hold on to the return value manually + or rely on `tf.keras.Model` loss tracking. + + + To switch to native TF2 style, instantiate the + `tf.keras.losses.CategoricalCrossentropy` class with `from_logits` set + as `True` and call the object instead. + + + #### Structural Mapping to Native TF2 + + Before: + + ```python + loss = tf.compat.v1.losses.softmax_cross_entropy( + onehot_labels=onehot_labels, + logits=logits, + weights=weights, + label_smoothing=smoothing) + ``` + + After: + + ```python + loss_fn = tf.keras.losses.CategoricalCrossentropy( + from_logits=True, + label_smoothing=smoothing) + loss = loss_fn( + y_true=onehot_labels, + y_pred=logits, + sample_weight=weights) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :--------------- | :------------------------- | + | - | `from_logits` | Set `from_logits` as True | + : : : to have identical behavior : + | `onehot_labels` | `y_true` | In `__call__()` method | + | `logits` | `y_pred` | In `__call__()` method | + | `weights` | `sample_weight` | In `__call__()` method | + | `label_smoothing` | `label_smoothing`| In constructor | + | `scope` | Not supported | - | + | `loss_collection` | Not supported | Losses should be tracked | + : : : explicitly or with Keras : + : : : APIs, for example, : + : : : [add_loss][add_loss], : + : : : instead of via collections : + | `reduction` | `reduction` | In constructor. Value of | + : : : `tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE`, : + : : : `tf.compat.v1.losses.Reduction.SUM`, : + : : : `tf.compat.v1.losses.Reduction.NONE` in : + : : : `tf.compat.v1.losses.softmax_cross_entropy` correspond to : + : : : `tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE`, : + : : : `tf.keras.losses.Reduction.SUM`, : + : : : `tf.keras.losses.Reduction.NONE`, respectively. If you : + : : : used other value for `reduction`, including the default value : + : : : `tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS`, there is : + : : : no directly corresponding value. Please modify the loss : + : : : implementation manually. : + + [add_loss]:https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss + + + #### Before & After Usage Example + + Before: + + >>> y_true = [[0, 1, 0], [0, 0, 1]] + >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] + >>> weights = [0.3, 0.7] + >>> smoothing = 0.2 + >>> tf.compat.v1.losses.softmax_cross_entropy(y_true, y_pred, weights=weights, + ... label_smoothing=smoothing).numpy() + 0.57618 + + After: + + >>> cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True, + ... label_smoothing=smoothing) + >>> cce(y_true, y_pred, sample_weight=weights).numpy() + 0.57618 + + @end_compatibility + """ + if onehot_labels is None: + raise ValueError("Argument `onehot_labels` must not be None.") + if logits is None: + raise ValueError("Argument `logits` must not be None.") + with ops.name_scope(scope, "softmax_cross_entropy_loss", + (logits, onehot_labels, weights)) as scope: + logits = ops.convert_to_tensor(logits) + onehot_labels = math_ops.cast(onehot_labels, logits.dtype) + logits.get_shape().assert_is_compatible_with(onehot_labels.get_shape()) + + if label_smoothing > 0: + num_classes = math_ops.cast( + array_ops.shape(onehot_labels)[-1], logits.dtype) + smooth_positives = 1.0 - label_smoothing + smooth_negatives = label_smoothing / num_classes + onehot_labels = onehot_labels * smooth_positives + smooth_negatives + + onehot_labels = array_ops.stop_gradient( + onehot_labels, name="labels_stop_gradient") + losses = nn.softmax_cross_entropy_with_logits_v2( + labels=onehot_labels, logits=logits, name="xentropy") + + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) + + +# TODO(ptucker): Merge this with similar method in metrics_impl. +def _remove_squeezable_dimensions( + labels, predictions, weights=None, expected_rank_diff=0): + """Internal version of _remove_squeezable_dimensions which handles weights. + + Squeezes `predictions` and `labels` if their ranks differ from expected by + exactly 1. + Squeezes `weights` if its rank is 1 more than the new rank of `predictions` + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + labels: Label values, a `Tensor` whose dimensions match `predictions`. + predictions: Predicted values, a `Tensor` of arbitrary dimensions. + weights: Optional weight `Tensor`. It will be squeezed if it's not scalar, + and its rank is 1 more than the new rank of `labels`. + expected_rank_diff: Expected result of `rank(predictions) - rank(labels)`. + + Returns: + Tuple of `predictions`, `labels` and `weights`, possibly with the last + dimension squeezed. + """ + labels, predictions = confusion_matrix.remove_squeezable_dimensions( + labels, predictions, expected_rank_diff=expected_rank_diff) + + if weights is not None: + weights = ops.convert_to_tensor(weights) + labels_rank = labels.get_shape().ndims + weights_shape = weights.get_shape() + weights_rank = weights_shape.ndims + + if (labels_rank is not None) and (weights_rank is not None): + # Use static rank. + rank_diff = weights_rank - labels_rank + if rank_diff == 1: + weights = array_ops.squeeze(weights, [-1]) + return labels, predictions, weights + + # Use dynamic rank. + rank_diff = array_ops.rank(weights) - array_ops.rank(labels) + if (weights_rank is None) or ( + weights_rank > 0 and weights_shape.dims[-1].is_compatible_with(1)): + weights = cond.cond( + math_ops.equal(1, rank_diff), + lambda: array_ops.squeeze(weights, [-1]), + lambda: weights) + + return labels, predictions, weights + + +@tf_export(v1=["losses.sparse_softmax_cross_entropy"]) +@dispatch.add_dispatch_support +def sparse_softmax_cross_entropy( + labels, logits, weights=1.0, scope=None, + loss_collection=ops.GraphKeys.LOSSES, + reduction=Reduction.SUM_BY_NONZERO_WEIGHTS): + """Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`. + + `weights` acts as a coefficient for the loss. If a scalar is provided, + then the loss is simply scaled by the given value. If `weights` is a + tensor of shape `[batch_size]`, then the loss weights apply to each + corresponding sample. + + Args: + labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of + `labels` and result) and dtype `int32` or `int64`. Each entry in `labels` + must be an index in `[0, num_classes)`. Other values will raise an + exception when this op is run on CPU, and return `NaN` for corresponding + loss and gradient rows on GPU. + logits: Unscaled log probabilities of shape + `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32` or + `float64`. + weights: Coefficients for the loss. This must be scalar or broadcastable to + `labels` (i.e. same rank and each dimension is either 1 or the same). + scope: the scope for the operations performed in computing the loss. + loss_collection: collection to which the loss will be added. + reduction: Type of reduction to apply to loss. + + Returns: + Weighted loss `Tensor` of the same type as `logits`. If `reduction` is + `NONE`, this has the same shape as `labels`; otherwise, it is scalar. + + Raises: + ValueError: If the shapes of `logits`, `labels`, and `weights` are + incompatible, or if any of them are None. + + @compatibility(eager) + The `loss_collection` argument is ignored when executing eagerly. Consider + holding on to the return value or collecting losses via a `tf.keras.Model`. + @end_compatibility + """ + if labels is None: + raise ValueError("Argument `labels` must not be None.") + if logits is None: + raise ValueError("Argument `logits` must not be None.") + with ops.name_scope(scope, "sparse_softmax_cross_entropy_loss", + (logits, labels, weights)) as scope: + # As documented above in Args, labels contain class IDs and logits contains + # 1 probability per class ID, so we expect rank(logits) - rank(labels) == 1; + # therefore, expected_rank_diff=1. + labels, logits, weights = _remove_squeezable_dimensions( + labels, logits, weights, expected_rank_diff=1) + losses = nn.sparse_softmax_cross_entropy_with_logits(labels=labels, + logits=logits, + name="xentropy") + return compute_weighted_loss( + losses, weights, scope, loss_collection, reduction=reduction) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/util.py new file mode 100644 index 0000000000000000000000000000000000000000..2678b3ee7cad72f1ee537658eb36aa237c19179d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/losses/util.py @@ -0,0 +1,263 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for manipulating the loss collections.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import confusion_matrix +from tensorflow.python.ops import math_ops +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + + +def squeeze_or_expand_dimensions(y_pred, y_true=None, sample_weight=None): + """Squeeze or expand last dimension if needed. + + 1. Squeezes last dim of `y_pred` or `y_true` if their rank differs by 1 + (using `confusion_matrix.remove_squeezable_dimensions`). + 2. Squeezes or expands last dim of `sample_weight` if its rank differs by 1 + from the new rank of `y_pred`. + If `sample_weight` is scalar, it is kept scalar. + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + y_pred: Predicted values, a `Tensor` of arbitrary dimensions. + y_true: Optional label `Tensor` whose dimensions match `y_pred`. + sample_weight: Optional weight scalar or `Tensor` whose dimensions match + `y_pred`. + + Returns: + Tuple of `y_pred`, `y_true` and `sample_weight`. Each of them possibly has + the last dimension squeezed, + `sample_weight` could be extended by one dimension. + If `sample_weight` is None, (y_pred, y_true) is returned. + """ + y_pred_shape = y_pred.shape + y_pred_rank = y_pred_shape.ndims + if y_true is not None: + + # If sparse matrix is provided as `y_true`, the last dimension in `y_pred` + # may be > 1. Eg: y_true = [0, 1, 2] (shape=(3,)), + # y_pred = [[.9, .05, .05], [.5, .89, .6], [.05, .01, .94]] (shape=(3, 3)) + # In this case, we should not try to remove squeezable dimension. + y_true_shape = y_true.shape + y_true_rank = y_true_shape.ndims + if (y_true_rank is not None) and (y_pred_rank is not None): + # Use static rank for `y_true` and `y_pred`. + if (y_pred_rank - y_true_rank != 1) or y_pred_shape[-1] == 1: + y_true, y_pred = confusion_matrix.remove_squeezable_dimensions( + y_true, y_pred) + else: + # Use dynamic rank. + rank_diff = array_ops.rank(y_pred) - array_ops.rank(y_true) + squeeze_dims = lambda: confusion_matrix.remove_squeezable_dimensions( # pylint: disable=g-long-lambda + y_true, y_pred) + is_last_dim_1 = math_ops.equal(1, array_ops.shape(y_pred)[-1]) + maybe_squeeze_dims = lambda: cond.cond( # pylint: disable=g-long-lambda + is_last_dim_1, squeeze_dims, lambda: (y_true, y_pred)) + y_true, y_pred = cond.cond( + math_ops.equal(1, rank_diff), maybe_squeeze_dims, squeeze_dims) + + if sample_weight is None: + return y_pred, y_true + + weights_shape = sample_weight.shape + weights_rank = weights_shape.ndims + if weights_rank == 0: # If weights is scalar, do nothing. + return y_pred, y_true, sample_weight + + if (y_pred_rank is not None) and (weights_rank is not None): + # Use static rank. + if weights_rank - y_pred_rank == 1: + sample_weight = array_ops.squeeze(sample_weight, [-1]) + elif y_pred_rank - weights_rank == 1: + sample_weight = array_ops.expand_dims(sample_weight, [-1]) + return y_pred, y_true, sample_weight + + # Use dynamic rank. + weights_rank_tensor = array_ops.rank(sample_weight) + rank_diff = weights_rank_tensor - array_ops.rank(y_pred) + maybe_squeeze_weights = lambda: array_ops.squeeze(sample_weight, [-1]) + + def _maybe_expand_weights(): + expand_weights = lambda: array_ops.expand_dims(sample_weight, [-1]) + return cond.cond( + math_ops.equal(rank_diff, -1), expand_weights, lambda: sample_weight) + + def _maybe_adjust_weights(): + return cond.cond( + math_ops.equal(rank_diff, 1), maybe_squeeze_weights, + _maybe_expand_weights) + + # squeeze or expand last dim of `sample_weight` if its rank differs by 1 + # from the new rank of `y_pred`. + sample_weight = cond.cond( + math_ops.equal(weights_rank_tensor, 0), lambda: sample_weight, + _maybe_adjust_weights) + return y_pred, y_true, sample_weight + + +def scale_losses_by_sample_weight(losses, sample_weight): + """Scales loss values by the given sample weights. + + `sample_weight` dimensions are updated to match with the dimension of `losses` + if possible by using squeeze/expand/broadcast. + + Args: + losses: Loss tensor. + sample_weight: Sample weights tensor. + + Returns: + `losses` scaled by `sample_weight` with dtype float32. + """ + # TODO(psv): Handle the casting here in a better way, eg. if losses is float64 + # we do not want to lose precision. + losses = math_ops.cast(losses, dtypes.float32) + sample_weight = math_ops.cast(sample_weight, dtypes.float32) + + # Update dimensions of `sample_weight` to match with `losses` if possible. + losses, _, sample_weight = squeeze_or_expand_dimensions( + losses, None, sample_weight) + return math_ops.multiply(losses, sample_weight) + + +@tf_contextlib.contextmanager +def check_per_example_loss_rank(per_example_loss): + """Context manager that checks that the rank of per_example_loss is at least 1. + + Args: + per_example_loss: Per example loss tensor. + + Yields: + A context manager. + """ + loss_rank = per_example_loss.shape.rank + if loss_rank is not None: + # Handle static rank. + if loss_rank == 0: + raise ValueError( + "Invalid value passed for `per_example_loss`. Expected a tensor with " + f"at least rank 1. Received per_example_loss={per_example_loss} with " + f"rank {loss_rank}") + yield + else: + # Handle dynamic rank. + with ops.control_dependencies([ + check_ops.assert_greater_equal( + array_ops.rank(per_example_loss), + math_ops.cast(1, dtype=dtypes.int32), + message="Invalid value passed for `per_example_loss`. Expected a " + "tensor with at least rank 1.") + ]): + yield + + +@tf_export(v1=["losses.add_loss"]) +def add_loss(loss, loss_collection=ops.GraphKeys.LOSSES): + """Adds a externally defined loss to the collection of losses. + + Args: + loss: A loss `Tensor`. + loss_collection: Optional collection to add the loss to. + """ + # Since we have no way of figuring out when a training iteration starts or + # ends, holding on to a loss when executing eagerly is indistinguishable from + # leaking memory. We instead leave the collection empty. + if loss_collection and not context.executing_eagerly(): + ops.add_to_collection(loss_collection, loss) + + +@tf_export(v1=["losses.get_losses"]) +def get_losses(scope=None, loss_collection=ops.GraphKeys.LOSSES): + """Gets the list of losses from the loss_collection. + + Args: + scope: An optional scope name for filtering the losses to return. + loss_collection: Optional losses collection. + + Returns: + a list of loss tensors. + """ + return ops.get_collection(loss_collection, scope) + + +@tf_export(v1=["losses.get_regularization_losses"]) +def get_regularization_losses(scope=None): + """Gets the list of regularization losses. + + Args: + scope: An optional scope name for filtering the losses to return. + + Returns: + A list of regularization losses as Tensors. + """ + return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope) + + +@tf_export(v1=["losses.get_regularization_loss"]) +def get_regularization_loss(scope=None, name="total_regularization_loss"): + """Gets the total regularization loss. + + Args: + scope: An optional scope name for filtering the losses to return. + name: The name of the returned tensor. + + Returns: + A scalar regularization loss. + """ + losses = get_regularization_losses(scope) + if losses: + return math_ops.add_n(losses, name=name) + else: + return constant_op.constant(0.0) + + +@tf_export(v1=["losses.get_total_loss"]) +def get_total_loss(add_regularization_losses=True, + name="total_loss", + scope=None): + """Returns a tensor whose value represents the total loss. + + In particular, this adds any losses you have added with `tf.add_loss()` to + any regularization losses that have been added by regularization parameters + on layers constructors e.g. `tf.layers`. Be very sure to use this if you + are constructing a loss_op manually. Otherwise regularization arguments + on `tf.layers` methods will not function. + + Args: + add_regularization_losses: A boolean indicating whether or not to use the + regularization losses in the sum. + name: The name of the returned tensor. + scope: An optional scope name for filtering the losses to return. Note that + this filters the losses added with `tf.add_loss()` as well as the + regularization losses to that scope. + + Returns: + A `Tensor` whose value represents the total loss. + + Raises: + ValueError: if `losses` is not iterable. + """ + losses = get_losses(scope=scope) + if add_regularization_losses: + losses += get_regularization_losses(scope=scope) + return math_ops.add_n(losses, name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ea009a4926b434a00d8ab4aefd070e069757af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_grad.py @@ -0,0 +1,27 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in manip_ops.py.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import manip_ops + + +@ops.RegisterGradient("Roll") +def _RollGrad(op, grad): + # The gradient is just the roll reversed + shift = op.inputs[1] + axis = op.inputs[2] + roll_grad = manip_ops.roll(grad, -shift, axis) + return roll_grad, None, None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3008bab3b9d9b3b5b2d87678b5e448a29a390f47 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/manip_ops.py @@ -0,0 +1,35 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operators for manipulating tensors. + +API docstring: tensorflow.manip +""" + +from tensorflow.python.ops import gen_manip_ops as _gen_manip_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=protected-access +@tf_export('roll', v1=['roll', 'manip.roll']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('manip.roll') +def roll(input, shift, axis, name=None): # pylint: disable=redefined-builtin + return _gen_manip_ops.roll(input, shift, axis, name) + + +roll.__doc__ = _gen_manip_ops.roll.__doc__ +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_fn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..05e9aa1775032cac00ad59609627873e222d84dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_fn.py @@ -0,0 +1,653 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Functional operations.""" + + +import re + +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["map_fn"]) +@deprecation.deprecated_args(None, "Use fn_output_signature instead", "dtype") +def map_fn(fn, + elems, + dtype=None, + parallel_iterations=None, + back_prop=True, + swap_memory=False, + infer_shape=True, + name=None, + fn_output_signature=None): + """Transforms `elems` by applying `fn` to each element unstacked on axis 0. + + See also `tf.scan`. + + `map_fn` unstacks `elems` on axis 0 to obtain a sequence of elements; + calls `fn` to transform each element; and then stacks the transformed + values back together. + + #### Mapping functions with single-Tensor inputs and outputs + + If `elems` is a single tensor and `fn`'s signature is `tf.Tensor->tf.Tensor`, + then `map_fn(fn, elems)` is equivalent to + `tf.stack([fn(elem) for elem in tf.unstack(elems)])`. E.g.: + + >>> tf.map_fn(fn=lambda t: tf.range(t, t + 3), elems=tf.constant([3, 5, 2])) + + + `map_fn(fn, elems).shape = [elems.shape[0]] + fn(elems[0]).shape`. + + #### Mapping functions with multi-arity inputs and outputs + + `map_fn` also supports functions with multi-arity inputs and outputs: + + * If `elems` is a tuple (or nested structure) of tensors, then those tensors + must all have the same outer-dimension size (`num_elems`); and `fn` is + used to transform each tuple (or structure) of corresponding slices from + `elems`. E.g., if `elems` is a tuple `(t1, t2, t3)`, then `fn` is used to + transform each tuple of slices `(t1[i], t2[i], t3[i])` + (where `0 <= i < num_elems`). + + * If `fn` returns a tuple (or nested structure) of tensors, then the + result is formed by stacking corresponding elements from those structures. + + #### Specifying `fn`'s output signature + + If `fn`'s input and output signatures are different, then the output + signature must be specified using `fn_output_signature`. (The input and + output signatures are differ if their structures, dtypes, or tensor types do + not match). E.g.: + + >>> tf.map_fn(fn=tf.strings.length, # input & output have different dtypes + ... elems=tf.constant(["hello", "moon"]), + ... fn_output_signature=tf.int32) + + >>> tf.map_fn(fn=tf.strings.join, # input & output have different structures + ... elems=[tf.constant(['The', 'A']), tf.constant(['Dog', 'Cat'])], + ... fn_output_signature=tf.string) + + + `fn_output_signature` can be specified using any of the following: + + * A `tf.DType` or `tf.TensorSpec` (to describe a `tf.Tensor`) + * A `tf.RaggedTensorSpec` (to describe a `tf.RaggedTensor`) + * A `tf.SparseTensorSpec` (to describe a `tf.sparse.SparseTensor`) + * A (possibly nested) tuple, list, or dict containing the above types. + + #### RaggedTensors + + `map_fn` supports `tf.RaggedTensor` inputs and outputs. In particular: + + * If `elems` is a `RaggedTensor`, then `fn` will be called with each + row of that ragged tensor. + * If `elems` has only one ragged dimension, then the values passed to + `fn` will be `tf.Tensor`s. + * If `elems` has multiple ragged dimensions, then the values passed to + `fn` will be `tf.RaggedTensor`s with one fewer ragged dimension. + + * If the result of `map_fn` should be a `RaggedTensor`, then use a + `tf.RaggedTensorSpec` to specify `fn_output_signature`. + * If `fn` returns `tf.Tensor`s with varying sizes, then use a + `tf.RaggedTensorSpec` with `ragged_rank=0` to combine them into a + single ragged tensor (which will have ragged_rank=1). + * If `fn` returns `tf.RaggedTensor`s, then use a `tf.RaggedTensorSpec` + with the same `ragged_rank`. + + >>> # Example: RaggedTensor input + >>> rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]]) + >>> tf.map_fn(tf.reduce_sum, rt, fn_output_signature=tf.int32) + + + >>> # Example: RaggedTensor output + >>> elems = tf.constant([3, 5, 0, 2]) + >>> tf.map_fn(tf.range, elems, + ... fn_output_signature=tf.RaggedTensorSpec(shape=[None], + ... dtype=tf.int32)) + + + Note: `map_fn` should only be used if you need to map a function over the + *rows* of a `RaggedTensor`. If you wish to map a function over the + individual values, then you should use: + + * `tf.ragged.map_flat_values(fn, rt)` + (if fn is expressible as TensorFlow ops) + * `rt.with_flat_values(map_fn(fn, rt.flat_values))` + (otherwise) + + E.g.: + + >>> rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]]) + >>> tf.ragged.map_flat_values(lambda x: x + 2, rt) + + + #### SparseTensors + + `map_fn` supports `tf.sparse.SparseTensor` inputs and outputs. In particular: + + * If `elems` is a `SparseTensor`, then `fn` will be called with each row + of that sparse tensor. In particular, the value passed to `fn` will be a + `tf.sparse.SparseTensor` with one fewer dimension than `elems`. + + * If the result of `map_fn` should be a `SparseTensor`, then use a + `tf.SparseTensorSpec` to specify `fn_output_signature`. The individual + `SparseTensor`s returned by `fn` will be stacked into a single + `SparseTensor` with one more dimension. + + >>> # Example: SparseTensor input + >>> st = tf.sparse.SparseTensor([[0, 0], [2, 0], [2, 1]], [2, 3, 4], [4, 4]) + >>> tf.map_fn(tf.sparse.reduce_sum, st, fn_output_signature=tf.int32) + + + >>> # Example: SparseTensor output + >>> tf.sparse.to_dense( + ... tf.map_fn(tf.sparse.eye, tf.constant([2, 3]), + ... fn_output_signature=tf.SparseTensorSpec(None, tf.float32))) + + + Note: `map_fn` should only be used if you need to map a function over the + *rows* of a `SparseTensor`. If you wish to map a function over the nonzero + values, then you should use: + + * If the function is expressible as TensorFlow ops, use: + ```python + tf.sparse.SparseTensor(st.indices, fn(st.values), st.dense_shape) + ``` + * Otherwise, use: + ```python + tf.sparse.SparseTensor(st.indices, tf.map_fn(fn, st.values), + st.dense_shape) + ``` + + #### `map_fn` vs. vectorized operations + + `map_fn` will apply the operations used by `fn` to each element of `elems`, + resulting in `O(elems.shape[0])` total operations. This is somewhat + mitigated by the fact that `map_fn` can process elements in parallel. + However, a transform expressed using `map_fn` is still typically less + efficient than an equivalent transform expressed using vectorized operations. + + `map_fn` should typically only be used if one of the following is true: + + * It is difficult or expensive to express the desired transform with + vectorized operations. + * `fn` creates large intermediate values, so an equivalent vectorized + transform would take too much memory. + * Processing elements in parallel is more efficient than an equivalent + vectorized transform. + * Efficiency of the transform is not critical, and using `map_fn` is + more readable. + + E.g., the example given above that maps `fn=lambda t: tf.range(t, t + 3)` + across `elems` could be rewritten more efficiently using vectorized ops: + + >>> elems = tf.constant([3, 5, 2]) + >>> tf.range(3) + tf.expand_dims(elems, 1) + + + In some cases, `tf.vectorized_map` can be used to automatically convert a + function to a vectorized equivalent. + + #### Eager execution + + When executing eagerly, `map_fn` does not execute in parallel even if + `parallel_iterations` is set to a value > 1. You can still get the + performance benefits of running a function in parallel by using the + `tf.function` decorator: + + >>> fn=lambda t: tf.range(t, t + 3) + >>> @tf.function + ... def func(elems): + ... return tf.map_fn(fn, elems, parallel_iterations=3) + >>> func(tf.constant([3, 5, 2])) + + + + Note: if you use the `tf.function` decorator, any non-TensorFlow Python + code that you may have written in your function won't get executed. See + `tf.function` for more details. The recommendation would be to debug without + `tf.function` but switch to it to get performance benefits of running `map_fn` + in parallel. + + Args: + fn: The callable to be performed. It accepts one argument, which will have + the same (possibly nested) structure as `elems`. Its output must have the + same structure as `fn_output_signature` if one is provided; otherwise it + must have the same structure as `elems`. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unstacked along their first dimension. `fn` will be applied to the + nested sequence of the resulting slices. `elems` may include ragged and + sparse tensors. `elems` must consist of at least one tensor. + dtype: Deprecated: Equivalent to `fn_output_signature`. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. When graph building, the default value is 10. While executing + eagerly, the default value is set to 1. + back_prop: (optional) False disables support for back propagation. + swap_memory: (optional) True enables GPU-CPU memory swapping. + infer_shape: (optional) False disables tests for consistent output shapes. + name: (optional) Name prefix for the returned tensors. + fn_output_signature: The output signature of `fn`. Must be specified if + `fn`'s input and output signatures are different (i.e., if their + structures, dtypes, or tensor types do not match). + `fn_output_signature` can be specified using any of the following: + + * A `tf.DType` or `tf.TensorSpec` (to describe a `tf.Tensor`) + * A `tf.RaggedTensorSpec` (to describe a `tf.RaggedTensor`) + * A `tf.SparseTensorSpec` (to describe a `tf.sparse.SparseTensor`) + * A (possibly nested) tuple, list, or dict containing the above types. + + Returns: + A tensor or (possibly nested) sequence of tensors. Each tensor stacks the + results of applying `fn` to tensors unstacked from `elems` along the first + dimension, from first to last. The result may include ragged and sparse + tensors. + + Raises: + TypeError: if `fn` is not callable or the structure of the output of + `fn` and `fn_output_signature` do not match. + ValueError: if the lengths of the output of `fn` and `fn_output_signature` + do not match, or if the `elems` does not contain any tensor. + + Examples: + + >>> elems = np.array([1, 2, 3, 4, 5, 6]) + >>> tf.map_fn(lambda x: x * x, elems) + + + >>> elems = (np.array([1, 2, 3]), np.array([-1, 1, -1])) + >>> tf.map_fn(lambda x: x[0] * x[1], elems, fn_output_signature=tf.int64) + + + >>> elems = np.array([1, 2, 3]) + >>> tf.map_fn(lambda x: (x, -x), elems, + ... fn_output_signature=(tf.int64, tf.int64)) + (, + ) + """ + # This function uses a `while_loop` to call `fn` on each value of the input + # tensor(s) (unstacked on dimension 0). The following sequence of variables + # are used to transform the input tensor(s) (`elems`) into the output + # tensor(s) (`result`): + # + # - Preparing and unstacking input values for the while_loop: + # - elems: The input tensor(s) to map_fn. May include composite tensors. + # - elems_flat: Flattened list of tensors from elems (using nest.flatten) + # May include composite tensors. + # - elems_batchable: Concatenation of "batchable tensor lists" for each + # tensor in elems_flat. This "boxes" composite tensors + # into sliceable tf.Tensor objects. For more info see: + # TensorSpec._to_batched_tensor_list + # - elems_batchable_ta: List of TensorArrays used to unstack each Tensor + # in elems_batchable into elems_value_batchable. + # + # - Calling `fn` on each unstacked value in the body of the while_loop: + # - elems_value_batchable: Single unstacked value from elems_batchable. + # - elems_value_flat: Single unstacked value from elems_flat, + # constructed from elems_value_batchable (using + # TensorSpec._from_tensor_list). + # - elems_value: Single unstacked value from elems (the input to fn). + # - result_value: Result of calling `fn(elems_value)`. May contain + # composite tensors. + # - result_value_flat: Flattened list of tensors from result_value. + # May contain composite tensors. + # - result_value_batchable: Concatenation of batchable tensor lists for + # each tensor in result_value_flat + # (using TensorSpec._to_tensor_list). + # + # - Collecting and stacking output values from the while_loop: + # - result_batchable_ta: List of TensorArrays used to stack each tensor + # ta result_value_batchable into result_batchable. + # - result_batchable: Stacked tensors from result_batchable_ta. + # - result_flat: Flat list of tensors for the result, constructed from + # results bactchable (using TensorSpec._from_tensor_list). + # - result: Structured result value packed from results flat + # (using nest.pack_sequence_as). + + if fn_output_signature is None: + fn_output_signature = dtype + + if not callable(fn): + raise TypeError(f"The provided function {fn.__name__} is not callable." + "fn must be callable.") + + in_graph_mode = not context.executing_eagerly() + # Set the default number of parallel_iterations depending on graph/eager mode. + if in_graph_mode and not parallel_iterations: + parallel_iterations = 10 + elif not in_graph_mode and not parallel_iterations: + parallel_iterations = 1 + elif not in_graph_mode and parallel_iterations > 1: + logging.log_first_n( + logging.WARN, "Setting parallel_iterations > 1 has no " + "effect when executing eagerly. Consider calling map_fn" + " with tf.function to execute fn in " + "parallel.", 1) + parallel_iterations = 1 + + # Explicitly read values of ResourceVariables. + elems = variable_utils.convert_variables_to_tensors(elems) + # Flatten the input tensors, and get the TypeSpec for each one. + elems_flat = nest.flatten(elems) + + # Check in case this is an empty list + if len(elems_flat) == 0: + raise ValueError( + "elems must be a Tensor or (possibly nested) sequence of Tensors. " + "Got {}, which does not contain any Tensors.".format(elems)) + + elems_flat_signature = [type_spec.type_spec_from_value(e) for e in elems_flat] + elems_unflatten = lambda x: nest.pack_sequence_as(elems, x) + + # Flatten fn's output signature. + if fn_output_signature is None: + # If fn_output_signature was not specified, then assume that it matches the + # input signature. + result_flat_signature = [ + _most_general_type_spec(e)._unbatch() # pylint: disable=protected-access + for e in elems_flat + ] + result_unflatten = elems_unflatten + else: + result_flat_signature = [ + _dtype_to_spec(d) for d in nest.flatten(fn_output_signature) + ] + result_unflatten = lambda x: nest.pack_sequence_as(fn_output_signature, x) + + with ops.name_scope(name, "map", elems_flat): + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode: + # Any get_variable calls in fn will cache the first call locally + # and not issue repeated network I/O requests for each iteration. + varscope = vs.get_variable_scope() + varscope_caching_device_was_none = False + if varscope.caching_device is None: + # TODO(ebrevdo): Change to using colocate_with here and in other + # methods. + varscope.set_caching_device(lambda op: op.device) + varscope_caching_device_was_none = True + + elems_flat = [ + ops.convert_to_tensor_or_composite(t, name="elem") for t in elems_flat + ] + + # Check that inputs are not scalars. + first_elem = elems_flat[0] + if hasattr(first_elem, "shape"): + elems_static_shape = first_elem.shape + if elems_static_shape.ndims is not None and elems_static_shape.ndims < 1: + raise ValueError( + "Elements in elems must be 1+ dimensional Tensors, not scalars") + + # Box any composite tensors into tensor lists. + elems_batchable = _elems_flat_to_batchable(elems_flat) + + # Find the number of iterations, n. (may be known statically.) + n_static = tensor_shape.Dimension( + tensor_shape.dimension_value( + elems_batchable[0].get_shape().with_rank_at_least(1)[0])) + for tensor in elems_batchable[1:]: + n_static.assert_is_compatible_with( + tensor_shape.Dimension( + tensor_shape.dimension_value( + tensor.get_shape().with_rank_at_least(1)[0]))) + n = n_static.value or array_ops.shape(elems_batchable[0])[0] + + # Convert elems to tensor array. + # TODO(edloper): Should we set infer_shape=False for composite tensors? + elems_batchable_ta = [ + tensor_array_ops.TensorArray( + dtype=t.dtype, size=n, dynamic_size=False, infer_shape=True) + for t in elems_batchable + ] + # Unpack elements + elems_batchable_ta = [ + ta.unstack(t) for (ta, t) in zip(elems_batchable_ta, elems_batchable) + ] + + i = constant_op.constant(0) + + # Prepare result tensor array. + # TODO(edloper): Should we set infer_shape=False for composite tensors? + result_batchable_tensor_spec = ( + _result_flat_signature_to_batchable_tensor_spec(result_flat_signature)) + result_batchable_ta = [] + for spec in result_batchable_tensor_spec: + result_batchable_ta.append( + tensor_array_ops.TensorArray( + dtype=spec.dtype, size=n, dynamic_size=False, + infer_shape=infer_shape, element_shape=spec.shape)) + + def compute(i, tas): + """The loop body of map_fn. + + Args: + i: the loop counter + tas: the flat TensorArray accumulator list + + Returns: + (i + 1, tas): the updated counter + updated TensorArrays + + Raises: + TypeError: if fn_output_signature and result_value structure don't match + ValueType: if fn_output_signature and result_value lengths don't match + """ + elems_value_batchable = [ta.read(i) for ta in elems_batchable_ta] + elems_value_flat = _elems_value_batchable_to_flat(elems_value_batchable, + elems_flat_signature) + elems_value = elems_unflatten(elems_value_flat) + ag_ctx = autograph_ctx.control_status_ctx() + autographed_fn = autograph.tf_convert(fn, ag_ctx) + result_value = autographed_fn(elems_value) + nest.assert_same_structure(fn_output_signature or elems, result_value) + result_value_flat = nest.flatten(result_value) + result_value_batchable = _result_value_flat_to_batchable( + result_value_flat, result_flat_signature) + tas = [ + ta.write(i, value) for (ta, value) in zip(tas, result_value_batchable) + ] + return (i + 1, tas) + + _, r_a = while_loop.while_loop( + lambda i, _: i < n, + compute, (i, result_batchable_ta), + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + maximum_iterations=n) + result_batchable = [r.stack() for r in r_a] + + # Update each output tensor w/ static shape info about the outer dimension. + for r in result_batchable: + r.set_shape(tensor_shape.TensorShape(n_static).concatenate( + r.get_shape()[1:])) + + # TODO(akshayka): Remove the in_graph_mode check once caching devices are + # supported in Eager + if in_graph_mode and varscope_caching_device_was_none: + varscope.set_caching_device(None) + + result_flat = _result_batchable_to_flat(result_batchable, + result_flat_signature, + n_static) + result = result_unflatten(result_flat) + return result + + +def _dtype_to_spec(d): + if not isinstance(d, type_spec.TypeSpec): + d = tensor_spec.TensorSpec(None, d) + return d + + +def _most_general_type_spec(elem): + """Returns the most general TypeSpec for elem.""" + if isinstance(elem, composite_tensor.CompositeTensor): + try: + spec = elem._shape_invariant_to_type_spec(tensor_shape.TensorShape(None)) # pylint: disable=protected-access + except NotImplementedError: + spec = type_spec.type_spec_from_value(elem) + else: + spec = type_spec.type_spec_from_value(elem) + if isinstance(spec, tensor_spec.TensorSpec): + spec = tensor_spec.TensorSpec(None, spec.dtype) + return spec + + +def _result_flat_signature_to_batchable_tensor_spec(result_flat_signature): + """Converts result_flat_signature -> result_batchable_tensor_specs.""" + tensor_specs = [] + for spec in result_flat_signature: + if not isinstance(spec, type_spec.BatchableTypeSpec): + raise TypeError("map_fn can not generate %s outputs" % (spec,)) + tensor_specs.extend(spec._flat_tensor_specs) # pylint: disable=protected-access + return tensor_specs + + +def _elems_flat_to_batchable(elems_flat): + """Converts elems_flat -> elems_batchable.""" + elems_batchable = [] + for elems_tensor in elems_flat: + spec = type_spec.type_spec_from_value(elems_tensor) + if not isinstance(spec, type_spec.BatchableTypeSpec): + raise TypeError("map_fn can not consume %s inputs: got %r" % + (spec, elems_tensor)) + # pylint: disable=protected-access + elems_batchable.extend(spec._to_batched_tensor_list(elems_tensor)) + return elems_batchable + + +def _elems_value_batchable_to_flat(elems_value_batchable, elems_flat_signature): + """Converts elems_value_batchable -> elems_value_flat.""" + elems_value_flat = [] + i = 0 + for spec in elems_flat_signature: + # pylint: disable=protected-access + spec = spec._unbatch() + tensor_list = elems_value_batchable[i:i + len(spec._flat_tensor_specs)] + elems_value_flat.append(spec._from_compatible_tensor_list(tensor_list)) + i += len(tensor_list) + assert i == len(elems_value_batchable) + return elems_value_flat + + +def _result_value_flat_to_batchable(result_value_flat, result_flat_signature): + """Converts result_value_flat -> result_value_batchable.""" + result_value_batchable = [] + for (r_value, r_spec) in zip(result_value_flat, result_flat_signature): + if isinstance(r_spec, tensor_spec.TensorSpec): + result_value_batchable.append(r_value) + else: + if not r_spec.is_compatible_with(r_value): + raise ValueError( + "Error in map_fn:\n Expected `fn` to return a:\n %s\n" + " But it returned a:\n %s\n (value=%s)\n" + " To fix, update the `fn_output_signature` (or `dtype`) " + "argument to `map_fn`." % + (r_spec, type_spec.type_spec_from_value(r_value), r_value)) + result_value_batchable.extend(r_spec._to_tensor_list(r_value)) # pylint: disable=protected-access + return result_value_batchable + + +def _result_batchable_to_flat(result_batchable, result_flat_signature, + batch_size): + """Converts result_batchable -> result_flat.""" + result_flat = [] + i = 0 + for spec in result_flat_signature: + # pylint: disable=protected-access + num_tensors = len(spec._flat_tensor_specs) + result_flat.append( + spec._batch(batch_size)._from_compatible_tensor_list( + result_batchable[i:i + num_tensors])) + i += num_tensors + assert i == len(result_batchable) + return result_flat + + +@tf_export("map_fn", v1=[]) +@deprecation.deprecated_arg_values( + None, + """back_prop=False is deprecated. Consider using tf.stop_gradient instead. +Instead of: +results = tf.map_fn(fn, elems, back_prop=False) +Use: +results = tf.nest.map_structure(tf.stop_gradient, tf.map_fn(fn, elems))""", + warn_once=True, + back_prop=False) +@deprecation.deprecated_args(None, "Use fn_output_signature instead", "dtype") +def map_fn_v2(fn, + elems, + dtype=None, + parallel_iterations=None, + back_prop=True, + swap_memory=False, + infer_shape=True, + name=None, + fn_output_signature=None): + """Transform `elems` by applying `fn` to each element unstacked on axis 0.""" + if fn_output_signature is None: + fn_output_signature = dtype + return map_fn( + fn=fn, + elems=elems, + fn_output_signature=fn_output_signature, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + infer_shape=infer_shape, + name=name) + + +# Docstring for v2 is the same as v1, except that back_prop is deprecated. +map_fn_v2.__doc__ = re.sub( + r"( back_prop: \(optional\) )(.*)", + r"\1Deprecated: prefer using `tf.stop_gradient` instead. \2", + map_fn.__doc__) +assert "prefer using `tf.stop_gradient` instead" in map_fn_v2.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d6e809b89a4d76797ede5f33f960c1e27cfdee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/map_ops.py @@ -0,0 +1,72 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Ops to manipulate hashmap of tensors.""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import gen_map_ops +from tensorflow.python.ops.gen_map_ops import * + +ops.NotDifferentiable("EmptyTensorMap") + +def empty_tensor_map(): + return gen_map_ops.empty_tensor_map() + +def tensor_map_size(input_handle): + return gen_map_ops.tensor_map_size(input_handle) + +def tensor_map_insert(input_handle, key, value): + return gen_map_ops.tensor_map_insert(input_handle, key, value) + +def tensor_map_lookup(input_handle, key, value_dtype): + return gen_map_ops.tensor_map_lookup(input_handle, key, value_dtype) + +def tensor_map_erase(input_handle, key, value_dtype): + return gen_map_ops.tensor_map_erase(input_handle, key, value_dtype) + +def tensor_map_has_key(input_handle, key): + return gen_map_ops.tensor_map_has_key(input_handle, key) + + +def tensor_map_stack_keys(input_handle, key_dtype): + return gen_map_ops.tensor_map_stack_keys(input_handle, key_dtype) + + +@ops.RegisterGradient("TensorMapLookup") +def LookupGrad(op, dval): + _, k = op.inputs + map_grad = empty_tensor_map() + map_grad = tensor_map_insert(map_grad, k, dval) + key_grad = None + return map_grad, key_grad + +@ops.RegisterGradient("TensorMapInsert") +def InsertGrad(op, dmap): + _, k, v = op.inputs + key_grad = None + (value_grad, map_grad) = cond.cond( + tensor_map_has_key(dmap, k), lambda: + (tensor_map_lookup(dmap, k, v.dtype), tensor_map_erase(dmap, k, v.dtype)), + lambda: (array_ops.zeros_like(v), dmap)) + return map_grad, key_grad, value_grad + +@ops.RegisterGradient("TensorMapErase") +def EraseGrad(op, dmap): + key_grad = None + map_grad = dmap + return map_grad, key_grad diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..3a120565a1603b0229654152de093e9eb26bf7fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_grad.py @@ -0,0 +1,2023 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in math_ops.py.""" +import numpy as np + +from tensorflow.python.compat import compat +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices as indexed_slices_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import special_math_ops + + +@ops.RegisterGradient("ArgMax") +def _ArgMaxGrad(op: ops.Operation, grad): + del op, grad + return [None, None] + + +@ops.RegisterGradient("ArgMin") +def _ArgMinGrad(op: ops.Operation, grad): + del op, grad + return [None, None] + + +@ops.RegisterGradient("EuclideanNorm") +def _EuclideanNormGrad(op: ops.Operation, grad): + """Gradient for EuclideanNorm.""" + + output = op.outputs[0] + + if not op.get_attr("keep_dims"): + output_shape_kept_dims = math_ops.reduced_shape( + array_ops.shape(op.inputs[0]), op.inputs[1]) + output = array_ops.reshape(output, output_shape_kept_dims) + grad = array_ops.reshape(grad, output_shape_kept_dims) + + return math_ops.truediv(op.inputs[0], output / grad), None + + +def SmartBroadcastGradientArgs(x, y, grad=None): + """Version of `BroadcastGradientArgs` optimized for partially-known shapes. + + Args: + x: The first argument of a broadcasting binary op. + y: The second argument of a broadcasting binary op. + grad: Deprecated. + + Returns: + A pair of triples, one per argument with + * Shape of the argument (tensor); + * Reduction axes for the argument (list or tensor); + * Boolean indicating whether the reduction must be applied. + """ + del grad + x_shape = array_ops.shape(x) + y_shape = array_ops.shape(y) + + if (not context.executing_eagerly() and + isinstance(x, tensor.Tensor) and + isinstance(y, tensor.Tensor)): + x_axes, y_axes = _InferGradientReductionAxes(x.shape, y.shape) + else: + x_axes, y_axes = None, None + + if x_axes is None or y_axes is None: + # NOTE: In graph mode, this is never exercised for statically known shapes. + x_axes, y_axes = gen_array_ops.broadcast_gradient_args(x_shape, y_shape) + x_must_reduce = True + y_must_reduce = True + else: + x_must_reduce = x_axes or x.shape.rank < y.shape.rank + y_must_reduce = y_axes or y.shape.rank < x.shape.rank + + return (x_shape, x_axes, x_must_reduce), (y_shape, y_axes, y_must_reduce) + + +def _InferGradientReductionAxes(x_shape, y_shape): + """Infers the sets of axes that might have been broadcasted.""" + x_rank = x_shape.rank + y_rank = y_shape.rank + if x_rank is None or y_rank is None: + return None, None + + # Convert shapes for V1 compatibility, can be omitted in V2. + x_shape = x_shape.as_list() + y_shape = y_shape.as_list() + + b_rank = max(x_rank, y_rank) + x_axes = [] + y_axes = [] + for axis in range(b_rank): + x_dim = 1 if axis < b_rank - x_rank else x_shape[axis - (b_rank - x_rank)] + y_dim = 1 if axis < b_rank - y_rank else y_shape[axis - (b_rank - y_rank)] + if x_dim == 1 and y_dim != 1: + # It's safe to assume that x_dim was broadcasted. + x_axes.append(axis) + elif y_dim == 1 and x_dim != 1: + # It's safe to assume that y_dim was broadcasted. + y_axes.append(axis) + elif x_dim is None or y_dim is None: + # Broadcasting decision is dynamic (data-dependent). + return None, None + + return x_axes, y_axes + + +def _ReduceGradientArg(grad, shape_axes_must_reduce): + """Reduces gradients of one of the arguments of a broadcasting binary op.""" + shape, axes, must_reduce = shape_axes_must_reduce + if grad is not None and must_reduce: + # Applying keepdims=True in presence of unknown axes opens up some + # opportunities for optimizations. For example, _SumGrad below won't have to + # emit extra ops to recover reduced indices for broadcasting. + grad = math_ops.reduce_sum(grad, axes, keepdims=True) + grad = array_ops.reshape(grad, shape) + return grad + + +def _ReduceGradientArgs(x, y, gx, gy): + """Reduces gradients of both arguments of a broadcasting binary op.""" + if gx is not None or gy is not None: + bx, by = SmartBroadcastGradientArgs(x, y) + gx = _ReduceGradientArg(gx, bx) + gy = _ReduceGradientArg(gy, by) + return gx, gy + + +_EMPTY_TUPLE = () + + +def _IsScalar(x): + return x._shape_tuple() is _EMPTY_TUPLE # pylint: disable=protected-access + + +def _SafeShapeDiv(x, y): + """Divides `x / y` assuming `x, y >= 0`, treating `0 / 0 = 0`.""" + return x // math_ops.maximum(y, 1) + + +@ops.RegisterGradient("Sum") +def _SumGrad(op: ops.Operation, grad): + """Gradient for Sum.""" + # Fast path for when reducing to a scalar and ndims is known: adds only + # Reshape and Tile ops (and possibly a Shape). + input_0_shape = op.inputs[0]._shape_tuple() # pylint: disable=protected-access + if input_0_shape is not None: + axes = tensor_util.constant_value(op.inputs[1]) + if axes is not None: + rank = len(input_0_shape) + if np.array_equal(axes, np.arange(rank)): # Reduce all dims. + if context.executing_eagerly(): + ctx = context.context() + new_shape = ctx.ones_rank_cache().get(rank) + if new_shape is None: + new_shape = constant_op.constant([1] * rank, dtype=dtypes.int32) + ctx.ones_rank_cache().put(rank, new_shape) + else: + new_shape = [1] * rank + grad = array_ops.reshape(grad, new_shape) + # If shape is not fully defined (but rank is), we use Shape. + if None not in input_0_shape: + input_shape = constant_op.constant(input_0_shape, dtype=dtypes.int32) + else: + input_shape = array_ops.shape(op.inputs[0]) + return [array_ops.tile(grad, input_shape), None] + elif None not in input_0_shape and not context.executing_eagerly(): + # The shape and reduction indices are statically known, so we use a + # graph-level cache to avoid recomputing `reduced_shape()` for each + # invocation. + graph = ops.get_default_graph() + + # Canonicalize `axes` to be a tuple of indices. The incoming + # value may be a scalar or a vector, and may include negative indices. + axes = tuple(axes.reshape(-1)) + + try: + output_shape_kept_dims, tile_scaling = graph._reduced_shape_cache[ # pylint: disable=protected-access + (input_0_shape, axes)] + except KeyError: + + # Compute and cache `output_shape_kept_dims` and `tile_scaling`. + def EvaluateAsTuple(t): + if tensor_util.is_tf_type(t): + value = tensor_util.try_evaluate_constant(t) + assert value is not None + else: + value = t + return tuple(value) + + output_shape_kept_dims = EvaluateAsTuple( + math_ops.reduced_shape(input_0_shape, axes)) + tile_scaling = EvaluateAsTuple( + _SafeShapeDiv(input_0_shape, output_shape_kept_dims)) + graph._reduced_shape_cache[(input_0_shape, axes)] = ( # pylint:disable=protected-access + output_shape_kept_dims, tile_scaling) + + grad = array_ops.reshape(grad, output_shape_kept_dims) + return [array_ops.tile(grad, tile_scaling), None] + + input_shape = array_ops.shape(op.inputs[0]) + + if not op.get_attr("keep_dims"): + with ops.colocate_with(input_shape): + # TODO(apassos) remove this once device placement for eager ops makes + # more sense. + output_shape_kept_dims = math_ops.reduced_shape(input_shape, + op.inputs[1]) + grad = array_ops.reshape(grad, output_shape_kept_dims) + return [array_ops.broadcast_to(grad, input_shape), None] + + +def _MinOrMaxGrad(op: ops.Operation, grad): + """Gradient for Min or Max. Amazingly it's precisely the same code.""" + input_shape = array_ops.shape(op.inputs[0]) + y = op.outputs[0] + if not op.get_attr("keep_dims"): + output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) + y = array_ops.reshape(y, output_shape_kept_dims) + grad = array_ops.reshape(grad, output_shape_kept_dims) + else: + output_shape_kept_dims = array_ops.shape(y) + + # Compute the number of selected (maximum or minimum) elements in each + # reduction dimension. If there are multiple minimum or maximum elements + # then the gradient will be divided between them. + indicators = math_ops.cast(math_ops.equal(y, op.inputs[0]), grad.dtype) + num_selected = array_ops.reshape( + math_ops.reduce_sum(indicators, op.inputs[1]), output_shape_kept_dims) + + return [math_ops.divide(indicators, num_selected) * grad, None] + + +@ops.RegisterGradient("Max") +def _MaxGrad(op: ops.Operation, grad): + """Gradient for Max.""" + return _MinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("Min") +def _MinGrad(op: ops.Operation, grad): + return _MinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("Mean") +def _MeanGrad(op: ops.Operation, grad): + """Gradient for Mean.""" + sum_grad = _SumGrad(op, grad)[0] + input_shape = op.inputs[0]._shape_tuple() # pylint: disable=protected-access + output_shape = op.outputs[0]._shape_tuple() # pylint: disable=protected-access + if (input_shape is not None and output_shape is not None and + None not in input_shape and None not in output_shape): + input_size = np.prod(input_shape) + output_size = np.prod(output_shape) + factor = input_size // max(output_size, 1) + factor = constant_op.constant(factor, dtype=sum_grad.dtype) + else: + input_shape = array_ops.shape(op.inputs[0]) + input_rank = array_ops.size(input_shape) + axes = (op.inputs[1] + input_rank) % input_rank + factor = math_ops.reduce_prod(array_ops.gather(input_shape, axes)) + return math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), None + + +@ops.RegisterGradient("Prod") +def _ProdGrad(op: ops.Operation, grad): + """Gradient for Prod.""" + # The gradient can be expressed by dividing the product by each entry of the + # input tensor, but this approach can't deal with zeros in the input. + # Here, we avoid this problem by composing the output as a product of two + # cumprod operations. + + input_shape = array_ops.shape(op.inputs[0]) + # Reshape reduction indices for the case where the parameter is a scalar + reduction_indices = array_ops.reshape(op.inputs[1], [-1]) + + # Expand grad to full input shape + if not op.get_attr("keep_dims"): + output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]) + grad = array_ops.reshape(grad, output_shape_kept_dims) + + grad = array_ops.broadcast_to(grad, input_shape) + + # Pack all reduced dimensions into a single one, so we can perform the + # cumprod ops. If the reduction dims list is empty, it defaults to float32, + # so we need to cast here. We put all the shape-related ops on CPU to avoid + # copying back and forth, and since listdiff is CPU only. + with ops.device("/cpu:0"): + rank = array_ops.rank(op.inputs[0]) + reduction_indices = (reduction_indices + rank) % rank + reduced = math_ops.cast(reduction_indices, dtypes.int32) + idx = math_ops.range(0, rank) + other, _ = gen_array_ops.list_diff(idx, reduced, dtypes.int32) + perm = array_ops.concat([reduced, other], 0) + reduced_num = math_ops.reduce_prod(array_ops.gather(input_shape, reduced)) + other_num = math_ops.reduce_prod(array_ops.gather(input_shape, other)) + permuted = array_ops.transpose(op.inputs[0], perm) + permuted_shape = array_ops.shape(permuted) + reshaped = array_ops.reshape(permuted, (reduced_num, other_num)) + + # Calculate product, leaving out the current entry + left = math_ops.cumprod(reshaped, axis=0, exclusive=True) + right = math_ops.cumprod(reshaped, axis=0, exclusive=True, reverse=True) + # For complex inputs, the gradient is in the conjugate direction. + y = array_ops.reshape( + math_ops.conj(left) * math_ops.conj(right), permuted_shape) + + # Invert the transpose and reshape operations. + # Make sure to set the statically known shape information through a reshape. + out = grad * array_ops.transpose(y, array_ops.invert_permutation(perm)) + return array_ops.reshape(out, input_shape), None + + +@ops.RegisterGradient("SegmentSum") +def _SegmentSumGrad(op: ops.Operation, grad): + """Gradient for SegmentSum.""" + return array_ops.gather(grad, op.inputs[1]), None + + +@ops.RegisterGradient("SegmentMean") +def _SegmentMeanGrad(op: ops.Operation, grad): + """Gradient for SegmentMean.""" + input_rank = array_ops.rank(op.inputs[0]) + ones_shape = array_ops.concat([ + array_ops.shape(op.inputs[1]), + array_ops.ones( + array_ops.expand_dims(input_rank - 1, 0), dtype=dtypes.int32) + ], 0) + ones = array_ops.ones(ones_shape, dtype=grad.dtype) + scaled_grad = math_ops.divide(grad, math_ops.segment_sum(ones, op.inputs[1])) + return array_ops.gather(scaled_grad, op.inputs[1]), None + + +def _SparseSegmentReduceGradV2(op, grad, norm=None): + """Sparse gradient for SparseSegment(Sum|Mean|SqrtN)[WithNumSegments].""" + assert norm is None or norm == "mean" or norm == "sqrtn" + data = op.inputs[0] + indices = op.inputs[1] + segment_ids = op.inputs[2] + data_shape = array_ops.shape(op.inputs[0]) + dense_output_dim0 = data_shape[0] + grad_fn = ( + math_ops.sparse_segment_mean_grad_v2 + if norm == "mean" + else math_ops.sparse_segment_sqrt_n_grad_v2 + if norm == "sqrtn" + else math_ops.sparse_segment_sum_grad_v2 + ) + grad_values, sorted_unique_indices = grad_fn( + grad, indices, segment_ids, dense_output_dim0 + ) + return indexed_slices_lib.IndexedSlices( + grad_values, sorted_unique_indices, data_shape + ) + + +def _GetOpAttrOrNone(op, name): + """Returns the value of the attr of `op` with the given `name`, or None if no + + such attr exists. + """ + try: + return op.get_attr(name) + except ValueError: + return None + + +@ops.RegisterGradient("SparseSegmentSum") +def _SparseSegmentSumGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentSum.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad), None, None + dim0 = array_ops.shape(op.inputs[0])[0] + if compat.forward_compatible(2021, 6, 10): + return (math_ops.sparse_segment_sum_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None) + else: + return (math_ops.unsorted_segment_sum( + array_ops.gather(grad, op.inputs[2]), op.inputs[1], dim0), None, None) + + +@ops.RegisterGradient("SparseSegmentSumWithNumSegments") +def _SparseSegmentSumWithNumSegmentsGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentSumWithNumSegments.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad), None, None, None + dim0 = array_ops.shape(op.inputs[0])[0] + if compat.forward_compatible(2021, 6, 10): + return (math_ops.sparse_segment_sum_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None, None) + else: + return (math_ops.unsorted_segment_sum( + array_ops.gather(grad, op.inputs[2]), op.inputs[1], + dim0), None, None, None) + + +@ops.RegisterGradient("SparseSegmentMean") +def _SparseSegmentMeanGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentMean.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad, "mean"), None, None + dim0 = array_ops.shape(op.inputs[0])[0] + return (math_ops.sparse_segment_mean_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None) + + +@ops.RegisterGradient("SparseSegmentMeanWithNumSegments") +def _SparseSegmentMeanWithNumSegmentsGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentMeanWithNumSegments.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad, "mean"), None, None, None + dim0 = array_ops.shape(op.inputs[0])[0] + return (math_ops.sparse_segment_mean_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None, None) + + +@ops.RegisterGradient("SparseSegmentSqrtN") +def _SparseSegmentSqrtNGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentSqrtN.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad, "sqrtn"), None, None + dim0 = array_ops.shape(op.inputs[0])[0] + return (math_ops.sparse_segment_sqrt_n_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None) + + +@ops.RegisterGradient("SparseSegmentSqrtNWithNumSegments") +def _SparseSegmentSqrtNWithNumSegmentsGrad(op: ops.Operation, grad): + """Gradient for SparseSegmentSqrtNWithNumSegments.""" + if _GetOpAttrOrNone(op, "sparse_gradient"): + return _SparseSegmentReduceGradV2(op, grad, "sqrtn"), None, None, None + dim0 = array_ops.shape(op.inputs[0])[0] + return (math_ops.sparse_segment_sqrt_n_grad(grad, op.inputs[1], op.inputs[2], + dim0), None, None, None) + + +def _SegmentMinOrMaxGrad(op: ops.Operation, grad): + """ Gradient for SegmentMin and SegmentMax. """ + zeros = array_ops.zeros_like(op.inputs[0], dtype=op.inputs[0].dtype) + # Get the number of selected (minimum or maximum) elements in each segment. + gathered_outputs = array_ops.gather(op.outputs[0], op.inputs[1]) + is_selected = math_ops.equal(op.inputs[0], gathered_outputs) + num_selected = math_ops.segment_sum( + math_ops.cast(is_selected, grad.dtype), op.inputs[1]) + # Compute the gradient for each segment. The gradient for the ith segment is + # divided evenly among the selected elements in that segment. + weighted_grads = math_ops.divide(grad, num_selected) + gathered_grads = array_ops.gather(weighted_grads, op.inputs[1]) + return array_ops.where_v2(is_selected, gathered_grads, zeros), None + + +@ops.RegisterGradient("SegmentMin") +def _SegmentMinGrad(op: ops.Operation, grad): + """Gradient for SegmentMin.""" + return _SegmentMinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("SegmentMax") +def _SegmentMaxGrad(op: ops.Operation, grad): + """Gradient for SegmentMax.""" + return _SegmentMinOrMaxGrad(op, grad) + + +# pylint: disable=g-doc-args +@ops.RegisterGradient("SegmentProd") +def _SegmentProdGrad(op: ops.Operation, grad): + """Gradient for SegmentProd. + + The gradient can be expressed for each segment by dividing the segment's + product by each element of the segment input tensor, but this approach can't + deal with zeros in the input. + Unlike reduce_prod we can't use cumsum here as individual segments may have + a different number of elements. Therefore we consider three cases: + 1) A segment input contains no zeros and we can safely divide by the input + tensor. + 2) A segment contains exactly one zero. Then the gradient of each input of + the segment is zero except for the 0-input, there the gradient is + the product of the remaining segment entries. + 3) A segment contains at least two zeros. The gradient is zero for all + segment inputs. + """ + data = op.inputs[0] + segment_ids = op.inputs[1] + is_zero = math_ops.equal(data, 0) + num_zeros = gen_math_ops.segment_sum( + math_ops.cast(is_zero, dtype=dtypes.int32), segment_ids) + # handle case 3 and set the gradient to 0 for segments with more than one + # 0 as input + grad = array_ops.where_v2( + math_ops.greater(num_zeros, 1), array_ops.zeros_like(grad), grad) + # replace all zeros with ones and compute the segment_prod + non_zero_data = array_ops.where_v2(is_zero, array_ops.ones_like(data), data) + non_zero_prod = gen_math_ops.segment_prod(non_zero_data, segment_ids) + gathered_prod = array_ops.gather(op.outputs[0], segment_ids) + gathered_non_zero_prod = array_ops.gather(non_zero_prod, segment_ids) + prod_divided_by_el = gathered_prod / non_zero_data + # Now fetch the individual results for segments containing 0 and those that + # don't. + partial_derivative = array_ops.where_v2(is_zero, gathered_non_zero_prod, + prod_divided_by_el) + gathered_grad = array_ops.gather(grad, segment_ids) + return gathered_grad * partial_derivative, None + + +def _GatherDropNegatives(params, + ids, + zero_clipped_indices=None, + is_positive=None): + """ Helper function for unsorted segment ops. + + Gathers params for + positive segment ids and gathers 0 for inputs with negative segment id. + Also returns the clipped indices and a boolean mask with the same shape + as ids where a positive id is masked as true. With this, the latter two + can be passed as arguments to this function to reuse them. + """ + if zero_clipped_indices is None: + zero_clipped_indices = math_ops.maximum(ids, array_ops.zeros_like(ids)) + gathered = array_ops.gather(params, zero_clipped_indices) + if is_positive is None: + is_positive = math_ops.greater_equal(ids, 0) + # tf.where(condition, x, y) requires condition to have the same shape as x + # and y. + is_positive_shape = array_ops.shape(is_positive) + broadcastable_shape = array_ops.concat( + [ + is_positive_shape, + array_ops.ones( + [array_ops.rank(gathered) - array_ops.rank(is_positive)], + dtype=is_positive_shape.dtype, + ), + ], + axis=0, + ) + is_positive = array_ops.reshape(is_positive, broadcastable_shape) + is_positive = is_positive & array_ops.ones_like(gathered, dtype=dtypes.bool) + # replace gathered params of negative indices with 0 + zero_slice = array_ops.zeros_like(gathered) + return ( + array_ops.where_v2(is_positive, gathered, zero_slice), + zero_clipped_indices, + is_positive, + ) + + +def _UnsortedSegmentMinOrMaxGrad(op: ops.Operation, grad): + """Gradient for UnsortedSegmentMin and UnsortedSegmentMax.""" + # Get the number of selected (minimum or maximum) elements in each segment. + gathered_outputs, zero_clipped_indices, is_positive = _GatherDropNegatives( + op.outputs[0], op.inputs[1] + ) + is_selected = math_ops.equal(op.inputs[0], gathered_outputs) + is_selected = math_ops.logical_and(is_selected, is_positive) + num_selected = math_ops.unsorted_segment_sum( + math_ops.cast(is_selected, grad.dtype), op.inputs[1], op.inputs[2] + ) + # Compute the gradient for each segment. The gradient for the ith segment is + # divided evenly among the selected elements in that segment. + weighted_grads = math_ops.divide(grad, num_selected) + gathered_grads, _, _ = _GatherDropNegatives( + weighted_grads, None, zero_clipped_indices, is_positive + ) + zeros = array_ops.zeros_like(gathered_grads) + return array_ops.where_v2(is_selected, gathered_grads, zeros), None, None + + +@ops.RegisterGradient("UnsortedSegmentSum") +def _UnsortedSegmentSumGrad(op: ops.Operation, grad): + """Gradient for UnsortedSegmentSum.""" + return _GatherDropNegatives(grad, op.inputs[1])[0], None, None + + +@ops.RegisterGradient("UnsortedSegmentMax") +def _UnsortedSegmentMaxGrad(op: ops.Operation, grad): + """ Gradient for UnsortedSegmentMax. """ + return _UnsortedSegmentMinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("UnsortedSegmentMin") +def _UnsortedSegmentMinGrad(op: ops.Operation, grad): + """ Gradient for UnsortedSegmentMin. """ + return _UnsortedSegmentMinOrMaxGrad(op, grad) + + +@ops.RegisterGradient("UnsortedSegmentProd") +def _UnsortedSegmentProdGrad(op: ops.Operation, grad): + """ Gradient for UnsortedSegmentProd. + + The gradient can be expressed for each segment by dividing the segment's + product by each element of the segment input tensor, but this approach can't + deal with zeros in the input. + Unlike reduce_prod we can't use cumsum here as individual segments may have + a different number of elements. Therefore we consider three cases: + 1) A segment input contains no zeros and we can safely divide by the input + tensor. + 2) A segment contains exactly one zero. Then the gradient of each input of + the segment is zero except for the 0-input, there the gradient is + the product of the remaining segment entries. + 3) A segment contains at least two zeros. The gradient is zero for all + segment inputs. + """ + # Note that unsorted_segment_sum will filter out the negative indices, + # so we don't need to do a logical_and with is_positive here + is_zero = math_ops.equal(op.inputs[0], 0) + num_zeros = gen_math_ops.unsorted_segment_sum( + math_ops.cast(is_zero, dtype=dtypes.int32), op.inputs[1], op.inputs[2]) + # handle case 3 and set the gradient to 0 for segments with more than one + # 0 as input + grad = array_ops.where_v2( + math_ops.greater(num_zeros, 1), array_ops.zeros_like(grad), grad) + # replace all zeros with ones and compute the unsorted_segment_prod + non_zero_data = array_ops.where_v2(is_zero, array_ops.ones_like(op.inputs[0]), + op.inputs[0]) + non_zero_prod = gen_math_ops.unsorted_segment_prod(non_zero_data, + op.inputs[1], op.inputs[2]) + # clip the indices for gather to be positive + zero_clipped_indices = math_ops.maximum(op.inputs[1], + array_ops.zeros_like(op.inputs[1])) + gathered_prod = array_ops.gather(op.outputs[0], zero_clipped_indices) + gathered_non_zero_prod = array_ops.gather(non_zero_prod, zero_clipped_indices) + prod_divided_by_el = gathered_prod / op.inputs[0] # May contain nan/inf. + # Now fetch the individual results for segments containing 0 and those that + # don't. is_zero will also fetch results for entries with negative index + # but the following gather_drop_negatives sets the corresponding entry in + # grad to 0 for these + partial_derivative = array_ops.where_v2(is_zero, gathered_non_zero_prod, + prod_divided_by_el) + gathered_grad = _GatherDropNegatives(grad, op.inputs[1], + zero_clipped_indices)[0] + return gathered_grad * partial_derivative, None, None + + +@ops.RegisterGradient("Abs") +def _AbsGrad(op: ops.Operation, grad): + x = op.inputs[0] + return grad * math_ops.sign(x) + + +@ops.RegisterGradient("Neg") +def _NegGrad(_, grad): + """Returns -grad.""" + return -grad + + +@ops.RegisterGradient("Inv") +def _InvGrad(op: ops.Operation, grad): + """Returns -grad * (1 / x^2).""" + y = op.outputs[0] # y = 1 / x + return gen_math_ops.reciprocal_grad(y, grad) + + +@ops.RegisterGradient("Reciprocal") +def _ReciprocalGrad(op: ops.Operation, grad): + """Returns -grad * (1 / x^2).""" + y = op.outputs[0] # y = 1 / x + return gen_math_ops.reciprocal_grad(y, grad) + + +@ops.RegisterGradient("InvGrad") +def _InvGradGrad(op: ops.Operation, grad): + b = op.inputs[1] + # op.output[0]: y = -b * conj(a)^2 + with ops.control_dependencies([grad]): + ca = math_ops.conj(op.inputs[0]) + cg = math_ops.conj(grad) + return cg * -2.0 * b * ca, gen_math_ops.reciprocal_grad(ca, grad) + + +@ops.RegisterGradient("ReciprocalGrad") +def _ReciprocalGradGrad(op: ops.Operation, grad): + b = op.inputs[1] + # op.output[0]: y = -b * conj(a)^2 + with ops.control_dependencies([grad]): + ca = math_ops.conj(op.inputs[0]) + cg = math_ops.conj(grad) + return cg * -2.0 * b * ca, gen_math_ops.reciprocal_grad(ca, grad) + + +@ops.RegisterGradient("Square") +def _SquareGrad(op: ops.Operation, grad): + x = op.inputs[0] + # Added control dependencies to prevent 2*x from being computed too early. + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + y = constant_op.constant(2.0, dtype=x.dtype) + return math_ops.multiply(grad, math_ops.multiply(x, y)) + + +@ops.RegisterGradient("Sqrt") +def _SqrtGrad(op: ops.Operation, grad): + y = op.outputs[0] # y = x^(1/2) + return gen_math_ops.sqrt_grad(y, grad) + + +@ops.RegisterGradient("SqrtGrad") +def _SqrtGradGrad(op: ops.Operation, grad): + a = op.inputs[0] + y = op.outputs[0] # y = 0.5 * b / conj(a) + with ops.control_dependencies([grad]): + ga = grad / a + return -math_ops.conj(ga) * y, 0.5 * ga # pylint: disable=invalid-unary-operand-type + + +@ops.RegisterGradient("Rsqrt") +def _RsqrtGrad(op: ops.Operation, grad): + """Returns -0.5 * grad * conj(y)^3.""" + y = op.outputs[0] # y = x^(-1/2) + return gen_math_ops.rsqrt_grad(y, grad) + + +@ops.RegisterGradient("RsqrtGrad") +def _RsqrtGradGrad(op: ops.Operation, grad): + """Returns backprop gradient for f(a,b) = -0.5 * b * conj(a)^3.""" + a = op.inputs[0] # a = x^{-1/2} + b = op.inputs[1] # backprop gradient for a + with ops.control_dependencies([grad]): + ca = math_ops.conj(a) + cg = math_ops.conj(grad) + grad_a = -1.5 * cg * b * math_ops.square(ca) + grad_b = gen_math_ops.rsqrt_grad(ca, grad) + return grad_a, grad_b + + +@ops.RegisterGradient("Exp") +def _ExpGrad(op: ops.Operation, grad): + """Returns grad * exp(x).""" + y = op.outputs[0] # y = e^x + with ops.control_dependencies([grad]): + y = math_ops.conj(y) + return grad * y + + +@ops.RegisterGradient("Expm1") +def _Expm1Grad(op: ops.Operation, grad): + """Returns grad * exp(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + y = math_ops.exp(x) + return grad * y + + +@ops.RegisterGradient("Log") +def _LogGrad(op: ops.Operation, grad): + """Returns grad * (1/x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.reciprocal(x) + + +@ops.RegisterGradient("Log1p") +def _Log1pGrad(op: ops.Operation, grad): + """Returns grad * (1/(1 + x)).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.reciprocal(1 + x) + + +@ops.RegisterGradient("Xlogy") +def _XLogyGrad(op: ops.Operation, grad): + """Returns gradient of xlogy(x, y) with respect to x and y.""" + x = op.inputs[0] + y = op.inputs[1] + sx = array_ops.shape(x) + sy = array_ops.shape(y) + rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) + with ops.control_dependencies([grad]): + not_zero_x = math_ops.cast( + math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) + partial_x = gen_math_ops.xlogy(not_zero_x, y) + partial_y = gen_math_ops.xdivy(x, y) + return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), + array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy)) + + +@ops.RegisterGradient("Xlog1py") +def _XLog1pyGrad(op: ops.Operation, grad): + """Returns gradient of xlog1py(x, y) with respect to x and y.""" + x = op.inputs[0] + y = op.inputs[1] + sx = array_ops.shape(x) + sy = array_ops.shape(y) + rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) + with ops.control_dependencies([grad]): + not_zero_x = math_ops.cast( + math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) + partial_x = gen_math_ops.xlog1py(not_zero_x, y) + partial_y = gen_math_ops.xdivy(x, y + 1.) + return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), + array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy)) + + +@ops.RegisterGradient("Xdivy") +def _XDivyGrad(op: ops.Operation, grad): + """Returns gradient of xdivy(x, y) with respect to x and y.""" + x = op.inputs[0] + y = op.inputs[1] + sx = array_ops.shape(x) + sy = array_ops.shape(y) + rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) + with ops.control_dependencies([grad]): + not_zero_x = math_ops.cast( + math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) + partial_x = gen_math_ops.xdivy(not_zero_x, y) + partial_y = gen_math_ops.xdivy(math_ops.negative(x), y**2) + return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), + array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy)) + + +@ops.RegisterGradient("Sinh") +def _SinhGrad(op: ops.Operation, grad): + """Returns grad * cosh(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.cosh(x) + + +@ops.RegisterGradient("Cosh") +def _CoshGrad(op: ops.Operation, grad): + """Returns grad * sinh(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.sinh(x) + + +@ops.RegisterGradient("Tanh") +def _TanhGrad(op: ops.Operation, grad): + """Returns grad * (1 - tanh(x) * tanh(x)).""" + y = op.outputs[0] # y = tanh(x) + with ops.control_dependencies([grad]): + y = math_ops.conj(y) + return gen_math_ops.tanh_grad(y, grad) + + +@ops.RegisterGradient("Asinh") +def _AsinhGrad(op: ops.Operation, grad): + """Returns grad * 1/cosh(y).""" + y = op.outputs[0] + with ops.control_dependencies([grad]): + y = math_ops.conj(y) + return grad / math_ops.cosh(y) + + +@ops.RegisterGradient("Acosh") +def _AcoshGrad(op: ops.Operation, grad): + """Returns grad * 1/sinh(y).""" + y = op.outputs[0] + with ops.control_dependencies([grad]): + y = math_ops.conj(y) + return grad / math_ops.sinh(y) + + +@ops.RegisterGradient("Atanh") +def _AtanhGrad(op: ops.Operation, grad): + """Returns grad * 1/ (1 - x^2).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + x2 = math_ops.square(x) + one = constant_op.constant(1, dtype=grad.dtype) + inv = math_ops.reciprocal(math_ops.subtract(one, x2)) + return grad * inv + + +@ops.RegisterGradient("TanhGrad") +def _TanhGradGrad(op: ops.Operation, grad): + with ops.control_dependencies([grad]): + a = math_ops.conj(op.inputs[0]) + b = math_ops.conj(op.inputs[1]) + return grad * -2.0 * b * a, gen_math_ops.tanh_grad(a, grad) + + +@ops.RegisterGradient("Erf") +def _ErfGrad(op: ops.Operation, grad): + """Returns grad * 2/sqrt(pi) * exp(-x**2).""" + x = op.inputs[0] + two_over_root_pi = constant_op.constant(2 / np.sqrt(np.pi), dtype=grad.dtype) + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * two_over_root_pi * math_ops.exp(-math_ops.square(x)) + + +@ops.RegisterGradient("Erfc") +def _ErfcGrad(op: ops.Operation, grad): + """Returns -grad * 2/sqrt(pi) * exp(-x**2).""" + x = op.inputs[0] + minus_two_over_root_pi = constant_op.constant( + -2 / np.sqrt(np.pi), dtype=grad.dtype) + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * minus_two_over_root_pi * math_ops.exp(-math_ops.square(x)) + + +@ops.RegisterGradient("Erfinv") +def _ErfinvGrad(op: ops.Operation, grad): + """Returns grad * sqrt(pi) / 2 * exp(erfinv(x)**2).""" + root_pi_over_two = constant_op.constant(np.sqrt(np.pi) / 2, dtype=grad.dtype) + with ops.control_dependencies([grad]): + return grad * root_pi_over_two * math_ops.exp( + math_ops.square(op.outputs[0])) + + +@ops.RegisterGradient("Ndtri") +def _NdtriGrad(op: ops.Operation, grad): + """Returns grad * sqrt(2 * pi) * exp(ndtri(x)**2 / 2).""" + root_two_pi = constant_op.constant(np.sqrt(2 * np.pi), dtype=grad.dtype) + with ops.control_dependencies([grad]): + return grad * root_two_pi * math_ops.exp( + math_ops.square(op.outputs[0]) / 2.) + + +@ops.RegisterGradient("Lgamma") +def _LgammaGrad(op: ops.Operation, grad): + """Returns grad * digamma(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.digamma(x) + + +@ops.RegisterGradient("Digamma") +def _DigammaGrad(op: ops.Operation, grad): + """Compute gradient of the digamma function with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + partial_x = math_ops.polygamma(array_ops.constant(1, dtype=x.dtype), x) + return grad * partial_x + + +@ops.RegisterGradient("Dawsn") +def _DawsnGrad(op: ops.Operation, grad): + """Compute gradient of dawsn(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + return grad * (1. - 2 * x * y) + + +@ops.RegisterGradient("Expint") +def _ExpintGrad(op: ops.Operation, grad): + """Compute gradient of expint(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + return grad * math_ops.exp(x) / x + + +@ops.RegisterGradient("FresnelCos") +def _FresnelCosGrad(op: ops.Operation, grad): + """Compute gradient of fresnel_cos(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + return grad * math_ops.cos((np.pi / 2.) * math_ops.square(x)) + + +@ops.RegisterGradient("FresnelSin") +def _FresnelSinGrad(op: ops.Operation, grad): + """Compute gradient of fresnel_sin(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + return grad * math_ops.sin((np.pi / 2.) * math_ops.square(x)) + + +@ops.RegisterGradient("Spence") +def _SpenceGrad(op: ops.Operation, grad): + """Compute gradient of spence(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + partial_x = math_ops.log(x) / (1 - x) + partial_x = array_ops.where( + math_ops.equal(x, 1.), -array_ops.ones_like(x), partial_x) # pylint: disable=invalid-unary-operand-type + return grad * partial_x + + +@ops.RegisterGradient("BesselI0") +def _BesselI0Grad(op: ops.Operation, grad): + """Compute gradient of bessel_i0(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + partial_x = special_math_ops.bessel_i1(x) + return grad * partial_x + + +@ops.RegisterGradient("BesselI0e") +def _BesselI0eGrad(op: ops.Operation, grad): + """Compute gradient of bessel_i0e(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + partial_x = (special_math_ops.bessel_i1e(x) - math_ops.sign(x) * y) + return grad * partial_x + + +@ops.RegisterGradient("BesselI1") +def _BesselI1Grad(op: ops.Operation, grad): + """Compute gradient of bessel_i1(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # For x = 0, the correct gradient is 1.0. + # However, the main branch gives NaN because of the division by x, so + # we impute the gradient manually. + # An alternative solution is to express the gradient via bessel_i0 and + # bessel_i2, but the latter is not yet implemented in Eigen. + dy_dx = array_ops.where_v2( + math_ops.equal(x, 0.), math_ops.cast(1., x.dtype), + special_math_ops.bessel_i0(x) - math_ops.div(y, x)) + return grad * dy_dx + + +@ops.RegisterGradient("BesselI1e") +def _BesselI1eGrad(op: ops.Operation, grad): + """Compute gradient of bessel_i1e(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # For x = 0, the correct gradient is 0.5. + # However, the main branch gives NaN because of the division by x, so + # we impute the gradient manually. + # An alternative solution is to express the gradient via bessel_i0e and + # bessel_i2e, but the latter is not yet implemented in Eigen. + dy_dx = array_ops.where_v2( + math_ops.equal(x, 0.), math_ops.cast(0.5, x.dtype), + special_math_ops.bessel_i0e(x) - y * + (math_ops.sign(x) + math_ops.reciprocal(x))) + return grad * dy_dx + + +@ops.RegisterGradient("BesselK0") +def _BesselK0Grad(op: ops.Operation, grad): + """Compute gradient of bessel_k0(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + partial_x = -special_math_ops.bessel_k1(x) + return grad * partial_x + + +@ops.RegisterGradient("BesselK0e") +def _BesselK0eGrad(op: ops.Operation, grad): + """Compute gradient of bessel_k0e(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + partial_x = (y - special_math_ops.bessel_k1e(x)) + return grad * partial_x + + +@ops.RegisterGradient("BesselK1") +def _BesselK1Grad(op: ops.Operation, grad): + """Compute gradient of bessel_k1(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # At 0., this is NaN which is fine since the derivative is undefined + # at 0. + partial_x = -special_math_ops.bessel_k0(x) - math_ops.div(y, x) + return grad * partial_x + + +@ops.RegisterGradient("BesselK1e") +def _BesselK1eGrad(op: ops.Operation, grad): + """Compute gradient of bessel_k1e(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # At 0., this is NaN which is fine since the derivative is undefined + # at 0. + partial_x = ( + y * (1. - math_ops.reciprocal(x)) - special_math_ops.bessel_k0e(x)) + return grad * partial_x + + +@ops.RegisterGradient("BesselJ0") +def _BesselJ0Grad(op: ops.Operation, grad): + """Compute gradient of bessel_j0(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + partial_x = -special_math_ops.bessel_j1(x) + return grad * partial_x + + +@ops.RegisterGradient("BesselJ1") +def _BesselJ1Grad(op: ops.Operation, grad): + """Compute gradient of bessel_j1(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # For x = 0, the correct gradient is 0.5. + # However, the main branch gives NaN because of the division by x, so + # we impute the gradient manually. + # An alternative solution is to express the gradient via bessel_i0e and + # bessel_i2e, but the latter is not yet implemented in Eigen. + dy_dx = array_ops.where_v2( + math_ops.equal(x, 0.), math_ops.cast(0.5, x.dtype), + special_math_ops.bessel_j0(x) - math_ops.div(y, x)) + return grad * dy_dx + + +@ops.RegisterGradient("BesselY0") +def _BesselY0Grad(op: ops.Operation, grad): + """Compute gradient of bessel_y0(x) with respect to its argument.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + partial_x = -special_math_ops.bessel_y1(x) + return grad * partial_x + + +@ops.RegisterGradient("BesselY1") +def _BesselY1Grad(op: ops.Operation, grad): + """Compute gradient of bessel_y1(x) with respect to its argument.""" + x = op.inputs[0] + y = op.outputs[0] + with ops.control_dependencies([grad]): + # At 0., this is NaN which is fine since the derivative is undefined + # at 0. + partial_x = special_math_ops.bessel_y0(x) - math_ops.div(y, x) + return grad * partial_x + + +@ops.RegisterGradient("Igamma") +def _IgammaGrad(op: ops.Operation, grad): + """Returns gradient of igamma(a, x) with respect to a and x.""" + a = op.inputs[0] + x = op.inputs[1] + sa = array_ops.shape(a) + sx = array_ops.shape(x) + ra, rx = gen_array_ops.broadcast_gradient_args(sa, sx) + + with ops.control_dependencies([grad]): + partial_a = gen_math_ops.igamma_grad_a(a, x) + # Perform operations in log space before summing, because Gamma(a) + # and Gamma'(a) can grow large. + partial_x = math_ops.exp(-x + (a - 1) * math_ops.log(x) - + math_ops.lgamma(a)) + return (array_ops.reshape(math_ops.reduce_sum(partial_a * grad, ra), sa), + array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) + + +@ops.RegisterGradient("Igammac") +def _IgammacGrad(op: ops.Operation, grad): + """Returns gradient of igammac(a, x) = 1 - igamma(a, x) w.r.t. a and x.""" + igamma_grad_a, igamma_grad_x = _IgammaGrad(op, grad) + return (-igamma_grad_a, -igamma_grad_x) + + +@ops.RegisterGradient("Betainc") +def _BetaincGrad(op: ops.Operation, grad): + """Returns gradient of betainc(a, b, x) with respect to x.""" + # TODO(ebrevdo): Perhaps add the derivative w.r.t. a, b + a, b, x = op.inputs + + # two cases: x is a scalar and a/b are same-shaped tensors, or vice + # versa; so its sufficient to check against shape(a). + sa = array_ops.shape(a) + sx = array_ops.shape(x) + _, rx = gen_array_ops.broadcast_gradient_args(sa, sx) + + # Perform operations in log space before summing, because terms + # can grow large. + log_beta = ( + gen_math_ops.lgamma(a) + gen_math_ops.lgamma(b) - + gen_math_ops.lgamma(a + b)) + # We use xlog1py and xlogy since the derivatives should tend to + # zero one of the tails when a is 1. or b is 1. + partial_x = math_ops.exp(math_ops.xlog1py(b - 1, -x) + + math_ops.xlogy(a - 1, x) - log_beta) + + return ( + None, # da + None, # db + array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) + + +@ops.RegisterGradient("Zeta") +def _ZetaGrad(op: ops.Operation, grad): + """Returns gradient of zeta(x, q) with respect to x and q.""" + # TODO(tillahoffmann): Add derivative with respect to x + x = op.inputs[0] + q = op.inputs[1] + # Broadcast gradients + sx = array_ops.shape(x) + sq = array_ops.shape(q) + unused_rx, rq = gen_array_ops.broadcast_gradient_args(sx, sq) + # Evaluate gradient + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + q = math_ops.conj(q) + partial_q = -x * math_ops.zeta(x + 1, q) # pylint: disable=invalid-unary-operand-type + return (None, + array_ops.reshape(math_ops.reduce_sum(partial_q * grad, rq), sq)) + + +@ops.RegisterGradient("Polygamma") +def _PolygammaGrad(op: ops.Operation, grad): + """Returns gradient of psi(n, x) with respect to n and x.""" + # TODO(tillahoffmann): Add derivative with respect to n + n = op.inputs[0] + x = op.inputs[1] + # Broadcast gradients + sn = array_ops.shape(n) + sx = array_ops.shape(x) + unused_rn, rx = gen_array_ops.broadcast_gradient_args(sn, sx) + # Evaluate gradient + with ops.control_dependencies([grad]): + n = math_ops.conj(n) + x = math_ops.conj(x) + partial_x = math_ops.polygamma(n + 1, x) + return (None, + array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) + + +@ops.RegisterGradient("Sigmoid") +def _SigmoidGrad(op: ops.Operation, grad): + """Returns grad * sigmoid(x) * (1 - sigmoid(x)).""" + y = op.outputs[0] # y = sigmoid(x) + with ops.control_dependencies([grad]): + y = math_ops.conj(y) + return gen_math_ops.sigmoid_grad(y, grad) + + +@ops.RegisterGradient("SigmoidGrad") +def _SigmoidGradGrad(op: ops.Operation, grad): + with ops.control_dependencies([grad]): + a = math_ops.conj(op.inputs[0]) + b = math_ops.conj(op.inputs[1]) + gb = grad * b + return gb - 2.0 * gb * a, gen_math_ops.sigmoid_grad(a, grad) + + +@ops.RegisterGradient("Sign") +def _SignGrad(op: ops.Operation, _): + """Returns 0.""" + x = op.inputs[0] + return array_ops.zeros_like(x) + + +@ops.RegisterGradient("Sin") +def _SinGrad(op: ops.Operation, grad): + """Returns grad * cos(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return grad * math_ops.cos(x) + + +@ops.RegisterGradient("Cos") +def _CosGrad(op: ops.Operation, grad): + """Returns grad * -sin(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + return -grad * math_ops.sin(x) + + +@ops.RegisterGradient("Tan") +def _TanGrad(op: ops.Operation, grad): + """Returns grad * 1/sec^2(x).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + secx = math_ops.reciprocal(math_ops.cos(x)) + secx2 = math_ops.square(secx) + return secx2 * grad + + +@ops.RegisterGradient("Asin") +def _AsinGrad(op: ops.Operation, grad): + """Returns grad * 1/sqrt(1-x^2).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + x2 = math_ops.square(x) + one = constant_op.constant(1, dtype=grad.dtype) + den = math_ops.sqrt(math_ops.subtract(one, x2)) + inv = math_ops.reciprocal(den) + return grad * inv + + +@ops.RegisterGradient("Acos") +def _AcosGrad(op: ops.Operation, grad): + """Returns grad * -1/sqrt(1-x^2).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + x2 = math_ops.square(x) + one = constant_op.constant(1, dtype=grad.dtype) + den = math_ops.sqrt(math_ops.subtract(one, x2)) + inv = math_ops.reciprocal(den) + return -grad * inv + + +@ops.RegisterGradient("Atan") +def _AtanGrad(op: ops.Operation, grad): + """Returns grad * 1/ (1 + x^2).""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + x = math_ops.conj(x) + x2 = math_ops.square(x) + one = constant_op.constant(1, dtype=grad.dtype) + inv = math_ops.reciprocal(math_ops.add(one, x2)) + return grad * inv + + +@ops.RegisterGradient("Atan2") +def _Atan2Grad(op: ops.Operation, grad): + """Returns grad * x / (y^2 + x^2), grad * -y / (y^2 + x^2).""" + y = op.inputs[0] + x = op.inputs[1] + with ops.control_dependencies([grad]): + grad_inv = grad / (math_ops.square(y) + math_ops.square(x)) + gy = x * grad_inv + gx = -y * grad_inv + # pylint: disable=arguments-out-of-order + return _ReduceGradientArgs(y, x, gy, gx) + # pylint: enable=arguments-out-of-order + + +@ops.RegisterGradient("AddN") +def _AddNGrad(op: ops.Operation, grad): + """Copies the gradient to all inputs.""" + # Not broadcasting. + return [grad] * len(op.inputs) + + +def _ShapesFullySpecifiedAndEqual(x, y, grad): + # pylint: disable=protected-access + x_shape = x._shape_tuple() + y_shape = y._shape_tuple() + grad_shape = grad._shape_tuple() + # pylint: enable=protected-access + return (x_shape == y_shape and x_shape == grad_shape and + x_shape is not None and None not in x_shape) + + +@ops.RegisterGradient("Add") +@ops.RegisterGradient("AddV2") +def _AddGrad(op: ops.Operation, grad): + """Gradient for Add.""" + y = op.inputs[1] + try: + skip_input_indices = op.skip_input_indices or () + if 1 in skip_input_indices and _IsScalar(y): + return grad, None + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + + x = op.inputs[0] + if isinstance(grad, tensor.Tensor) and _ShapesFullySpecifiedAndEqual( + x, y, grad + ): + return grad, grad + + gx = None if 0 in skip_input_indices else grad + gy = None if 1 in skip_input_indices else grad + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Sub") +def _SubGrad(op: ops.Operation, grad): + """Gradient for Sub.""" + y = op.inputs[1] + try: + skip_input_indices = op.skip_input_indices or () + if 1 in skip_input_indices and _IsScalar(y): + return grad, None + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + + x = op.inputs[0] + if isinstance(grad, tensor.Tensor) and _ShapesFullySpecifiedAndEqual( + x, y, grad + ): + return grad, -grad + + gx = None if 0 in skip_input_indices else grad + gy = None if 1 in skip_input_indices else -grad + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Mul") +def _MulGrad(op: ops.Operation, grad): + """The gradient of scalar multiplication.""" + y = op.inputs[1] + try: + skip_input_indices = op.skip_input_indices or () + if 1 in skip_input_indices and _IsScalar(y): + return gen_math_ops.mul(grad, math_ops.conj(y)), None + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + + x = op.inputs[0] + if ( + isinstance(grad, tensor.Tensor) + and _ShapesFullySpecifiedAndEqual(x, y, grad) + and grad.dtype in (dtypes.int32, dtypes.float32) + ): + return gen_math_ops.mul(grad, y), gen_math_ops.mul(grad, x) + assert x.dtype.base_dtype == y.dtype.base_dtype, (x.dtype, " vs. ", y.dtype) + + if 0 in skip_input_indices: + gx = None + else: + gx = gen_math_ops.mul(grad, math_ops.conj(y)) + + if 1 in skip_input_indices: + gy = None + else: + gy = gen_math_ops.mul(math_ops.conj(x), grad) + + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("MulNoNan") +def _MulNoNanGrad(op: ops.Operation, grad): + """The gradient of scalar multiplication with NaN-suppression.""" + x = op.inputs[0] + y = op.inputs[1] + if isinstance(grad, tensor.Tensor) and _ShapesFullySpecifiedAndEqual( + x, y, grad + ): + return gen_math_ops.mul_no_nan(grad, y), gen_math_ops.mul_no_nan(x, grad) + + assert x.dtype.base_dtype == y.dtype.base_dtype, (x.dtype, " vs. ", y.dtype) + gx = gen_math_ops.mul_no_nan(grad, y) + gy = gen_math_ops.mul_no_nan(x, grad) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Div") +def _DivGrad(op: ops.Operation, grad): + """The gradient for the Div operator.""" + x = op.inputs[0] + y = op.inputs[1] + cx = math_ops.conj(x) + cy = math_ops.conj(y) + gx = math_ops.divide(grad, cy) + gy = grad * math_ops.divide(math_ops.divide(-cx, cy), cy) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("FloorDiv") +def _FloorDivGrad(_, unused_grad): + """The gradient for the FloorDiv operator.""" + return None, None + + +@ops.RegisterGradient("FloorMod") +def _FloorModGrad(op: ops.Operation, grad): + """Returns grad * (1, -floor(x/y)).""" + x = math_ops.conj(op.inputs[0]) + y = math_ops.conj(op.inputs[1]) + floor_xy = math_ops.floor_div(x, y) + gx = grad + gy = grad * math_ops.negative(floor_xy) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("TruncateDiv") +def _TruncateDivGrad(_, unused_grad): + return None, None + + +@ops.RegisterGradient("RealDiv") +def _RealDivGrad(op: ops.Operation, grad): + """RealDiv op gradient.""" + x = op.inputs[0] + y = op.inputs[1] + cx = math_ops.conj(op.inputs[0]) + cy = math_ops.conj(op.inputs[1]) + gx = math_ops.realdiv(grad, cy) + gy = grad * math_ops.realdiv(math_ops.realdiv(-cx, cy), cy) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("DivNoNan") +def _DivNoNanGrad(op: ops.Operation, grad): + """DivNoNan op gradient.""" + x = math_ops.conj(op.inputs[0]) + y = math_ops.conj(op.inputs[1]) + gx = math_ops.div_no_nan(grad, y) + gy = grad * math_ops.div_no_nan(math_ops.div_no_nan(-x, y), y) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Pow") +def _PowGrad(op: ops.Operation, grad): + """Returns grad * (y*x^(y-1), z*log(x)).""" + x = op.inputs[0] + y = op.inputs[1] + cx = math_ops.conj(x) + cy = math_ops.conj(y) + try: + skip_input_indices = op.skip_input_indices or () + if 1 in skip_input_indices and _IsScalar(y): + return grad * cy * math_ops.pow(cx, cy - 1), None + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + + if 0 in skip_input_indices: + gx = None + else: + gx = grad * cy * math_ops.pow(cx, cy - 1) + + if 1 in skip_input_indices: + gy = None + else: + # Avoid false singularity at x = 0 + if x.dtype.is_complex: + # real(x) < 0 is fine for the complex case + mask = math_ops.not_equal(cx, 0) + else: + # There's no sensible real value to return if x < 0, so return 0 + mask = cx > 0 + safe_x = array_ops.where(mask, cx, array_ops.ones_like(x)) + log_x = array_ops.where(mask, math_ops.log(safe_x), array_ops.zeros_like(x)) + gy = grad * math_ops.conj(op.outputs[0]) * log_x + + return _ReduceGradientArgs(x, y, gx, gy) + + +def _MaximumMinimumGradInputOnly(op: ops.Operation, grad, selector_op): + x = op.inputs[0] + y = op.inputs[1] + zeros = array_ops.zeros_like(grad) + xmask = selector_op(x, y) + xgrad = array_ops.where_v2(xmask, grad, zeros) + ygrad = None # Return None for ygrad since the config allows that. + return (xgrad, ygrad) + + +def _MaximumMinimumGrad(op: ops.Operation, grad, selector_op): + """Factor out the code for the gradient of Maximum or Minimum.""" + y = op.inputs[1] + try: + skip_input_indices = op.skip_input_indices or () + if 1 in skip_input_indices and _IsScalar(y): + # When we want to get gradients for the first input only, and the second + # input tensor is a scalar, we can do a much simpler calculation + return _MaximumMinimumGradInputOnly(op, grad, selector_op) + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + x = op.inputs[0] + zeros = array_ops.zeros_like(grad) + xmask = selector_op(x, y) + if 0 in skip_input_indices: + gx = None + else: + gx = array_ops.where_v2(xmask, grad, zeros) + if 1 in skip_input_indices: + gy = None + else: + gy = array_ops.where_v2(xmask, zeros, grad) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Maximum") +def _MaximumGrad(op: ops.Operation, grad): + """Returns grad*(x >= y, x < y) with type of grad.""" + return _MaximumMinimumGrad(op, grad, math_ops.greater_equal) + + +@ops.RegisterGradient("Minimum") +def _MinimumGrad(op: ops.Operation, grad): + """Returns grad*(x <= y, x > y) with type of grad.""" + return _MaximumMinimumGrad(op, grad, math_ops.less_equal) + + +@ops.RegisterGradient("SquaredDifference") +def _SquaredDifferenceGrad(op: ops.Operation, grad): + """Returns the gradient for (x-y)^2.""" + x = op.inputs[0] + y = op.inputs[1] + try: + skip_input_indices = op.skip_input_indices or () + except AttributeError: + # No gradient skipping, so do the full gradient computation + skip_input_indices = () + + with ops.control_dependencies([grad]): + # The parens ensure that if grad is IndexedSlices, it'll get multiplied by + # Tensor (not a number like 2.0) which causes it to convert to Tensor. + x_grad = math_ops.scalar_mul(2.0, grad) * (x - y) + + if isinstance(grad, tensor.Tensor) and _ShapesFullySpecifiedAndEqual( + x, y, grad + ): + return x_grad, -x_grad + + gx = None if 0 in skip_input_indices else x_grad + gy = None if 1 in skip_input_indices else -x_grad + return _ReduceGradientArgs(x, y, gx, gy) + + +# Logical operations have no gradients. +ops.NotDifferentiable("Less") +ops.NotDifferentiable("LessEqual") +ops.NotDifferentiable("Greater") +ops.NotDifferentiable("GreaterEqual") +ops.NotDifferentiable("Equal") +ops.NotDifferentiable("ApproximateEqual") +ops.NotDifferentiable("NotEqual") +ops.NotDifferentiable("LogicalAnd") +ops.NotDifferentiable("LogicalOr") +ops.NotDifferentiable("LogicalNot") + + +@ops.RegisterGradient("Select") +def _SelectGrad(op: ops.Operation, grad): + c = op.inputs[0] + x = op.inputs[1] + zeros = array_ops.zeros_like(x) + return ( + None, + array_ops.where(c, grad, zeros), + array_ops.where(c, zeros, grad), + ) + + +@ops.RegisterGradient("SelectV2") +def _SelectGradV2(op: ops.Operation, grad): + c = op.inputs[0] + x = op.inputs[1] + y = op.inputs[2] + z = op.outputs[0] + zeros = array_ops.zeros([], dtype=grad.dtype.base_dtype) + gx = array_ops.where_v2(c, grad, zeros) + gy = array_ops.where_v2(c, zeros, grad) + gx, _ = _ReduceGradientArgs(x, z, gx, None) + gy, _ = _ReduceGradientArgs(y, z, gy, None) + return None, gx, gy + + +def _MatMulGradAgainstFirstOnly(op: ops.Operation, grad): + """Gradient for MatMul, only for the first input.""" + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + b = math_ops.conj(op.inputs[1]) + if not t_a and not t_b: + grad_a = gen_math_ops.mat_mul(grad, b, transpose_b=True) + elif not t_a and t_b: + grad_a = gen_math_ops.mat_mul(grad, b) + elif t_a and not t_b: + grad_a = gen_math_ops.mat_mul(b, grad, transpose_b=True) + elif t_a and t_b: + grad_a = gen_math_ops.mat_mul(b, grad, transpose_a=True, transpose_b=True) + return grad_a, None + + +def _MatMulGradAgainstSecondOnly(op: ops.Operation, grad): + """Gradient for MatMul, only for the second input.""" + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + a = math_ops.conj(op.inputs[0]) + if not t_a and not t_b: + grad_b = gen_math_ops.mat_mul(a, grad, transpose_a=True) + elif not t_a and t_b: + grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True) + elif t_a and not t_b: + grad_b = gen_math_ops.mat_mul(a, grad) + elif t_a and t_b: + grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True, transpose_b=True) + return None, grad_b + + +@ops.RegisterGradient("MatMul") +def _MatMulGrad(op: ops.Operation, grad): + """Gradient for MatMul.""" + try: + skip_input_indices = op.skip_input_indices + if skip_input_indices is not None: + if 1 in skip_input_indices: + return _MatMulGradAgainstFirstOnly(op, grad) + elif 0 in skip_input_indices: + return _MatMulGradAgainstSecondOnly(op, grad) + except AttributeError: + # No gradient skipping, so do the full gradient computation + pass + + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + a = math_ops.conj(op.inputs[0]) + b = math_ops.conj(op.inputs[1]) + if not t_a and not t_b: + grad_a = gen_math_ops.mat_mul(grad, b, transpose_b=True) + grad_b = gen_math_ops.mat_mul(a, grad, transpose_a=True) + elif not t_a and t_b: + grad_a = gen_math_ops.mat_mul(grad, b) + grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True) + elif t_a and not t_b: + grad_a = gen_math_ops.mat_mul(b, grad, transpose_b=True) + grad_b = gen_math_ops.mat_mul(a, grad) + elif t_a and t_b: + grad_a = gen_math_ops.mat_mul(b, grad, transpose_a=True, transpose_b=True) + grad_b = gen_math_ops.mat_mul(grad, a, transpose_a=True, transpose_b=True) + return grad_a, grad_b + + +@ops.RegisterGradient("SparseMatMul") +def _SparseMatMulGrad(op: ops.Operation, grad): + """Gradient for SparseMatMul.""" + + t_a = op.get_attr("transpose_a") + t_b = op.get_attr("transpose_b") + is_sparse = {} + is_sparse[op.inputs[0].ref()] = op.get_attr("a_is_sparse") + is_sparse[op.inputs[1].ref()] = op.get_attr("b_is_sparse") + # Use heuristic to figure out if grad might be sparse + is_sparse[grad.ref()] = not context.executing_eagerly() and ( + grad.op.type == "ReluGrad") + + def _SparseMatMul(t1, t2, out_dtype, transpose_a=False, transpose_b=False): + """Helper function to create SparseMatMul op.""" + + assert t1.ref() in is_sparse and t2.ref() in is_sparse + t1_sparse = is_sparse[t1.ref()] + t2_sparse = is_sparse[t2.ref()] + if transpose_b: + t2 = array_ops.transpose(t2) + transpose_b = False + prod = math_ops.matmul( + t1, + t2, + transpose_a=transpose_a, + transpose_b=transpose_b, + a_is_sparse=t1_sparse, + b_is_sparse=t2_sparse) + if prod.dtype != out_dtype: + prod = math_ops.cast(prod, out_dtype) + return prod + + dtype_a = op.inputs[0].dtype + dtype_b = op.inputs[1].dtype + if not t_a and not t_b: + return (_SparseMatMul(grad, op.inputs[1], dtype_a, transpose_b=True), + _SparseMatMul(op.inputs[0], grad, dtype_b, transpose_a=True)) + elif not t_a and t_b: + return (_SparseMatMul(grad, op.inputs[1], dtype_a), + _SparseMatMul(grad, op.inputs[0], dtype_b, transpose_a=True)) + elif t_a and not t_b: + return (_SparseMatMul(op.inputs[1], grad, dtype_a, transpose_b=True), + _SparseMatMul(op.inputs[0], grad, dtype_b)) + elif t_a and t_b: + return (_SparseMatMul( + op.inputs[1], grad, dtype_a, transpose_a=True, transpose_b=True), + _SparseMatMul( + grad, op.inputs[0], dtype_b, transpose_a=True, + transpose_b=True)) + + +@ops.RegisterGradient("Floor") +def _FloorGrad(_, unused_grad): + return [None] + + +@ops.RegisterGradient("Ceil") +def _CeilGrad(_, unused_grad): + return [None] + + +@ops.RegisterGradient("Round") +def _RoundGrad(_, unused_grad): + return [None] + + +@ops.RegisterGradient("Rint") +def _RintGrad(_, unused_grad): + # the gradient of Rint is zero + return [None] + + +@ops.RegisterGradient("BatchMatMul") +def _BatchMatMul(op: ops.Operation, grad): + """Returns the gradient of x and y given the gradient of x * y.""" + x = op.inputs[0] + y = op.inputs[1] + adj_x = op.get_attr("adj_x") + adj_y = op.get_attr("adj_y") + + if not adj_x: + if not adj_y: + grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=True) + grad_y = math_ops.matmul(x, grad, adjoint_a=True, adjoint_b=False) + else: + grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=False) + grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=False) + else: + if not adj_y: + grad_x = math_ops.matmul(y, grad, adjoint_a=False, adjoint_b=True) + grad_y = math_ops.matmul(x, grad, adjoint_a=False, adjoint_b=False) + else: + grad_x = math_ops.matmul(y, grad, adjoint_a=True, adjoint_b=True) + grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=True) + + return grad_x, grad_y + + +@ops.RegisterGradient("BatchMatMulV2") +@ops.RegisterGradient("BatchMatMulV3") +def _BatchMatMulV2(op: ops.Operation, grad): + """Returns the gradient of x and y given the gradient of x * y.""" + x = op.inputs[0] + y = op.inputs[1] + adj_x = op.get_attr("adj_x") + adj_y = op.get_attr("adj_y") + + if not adj_x: + if not adj_y: + grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=True) + grad_y = math_ops.matmul(x, grad, adjoint_a=True, adjoint_b=False) + else: + grad_x = math_ops.matmul(grad, y, adjoint_a=False, adjoint_b=False) + grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=False) + else: + if not adj_y: + grad_x = math_ops.matmul(y, grad, adjoint_a=False, adjoint_b=True) + grad_y = math_ops.matmul(x, grad, adjoint_a=False, adjoint_b=False) + else: + grad_x = math_ops.matmul(y, grad, adjoint_a=True, adjoint_b=True) + grad_y = math_ops.matmul(grad, x, adjoint_a=True, adjoint_b=True) + + # Possibly reduce along the broadcasted batch dimensions, if broadcasting + # is required. + shape_x_static = x.get_shape() + shape_y_static = y.get_shape() + output_may_have_non_empty_batch_shape = ( + (shape_x_static.rank is None or shape_x_static.rank > 2) or + (shape_y_static.rank is None or shape_y_static.rank > 2)) + batch_shapes_match = ( + shape_x_static[:-2].is_fully_defined() and + shape_y_static[:-2].is_fully_defined() and + shape_x_static[:-2] == shape_y_static[:-2]) + if (not output_may_have_non_empty_batch_shape) or batch_shapes_match: + return grad_x, grad_y + + sx = array_ops.shape(x) + sy = array_ops.shape(y) + rx, ry = gen_array_ops.broadcast_gradient_args(sx[:-2], sy[:-2]) + grad_x = array_ops.reshape(math_ops.reduce_sum(grad_x, rx), sx) + grad_y = array_ops.reshape(math_ops.reduce_sum(grad_y, ry), sy) + return grad_x, grad_y + + +ops.NotDifferentiable("Range") +ops.NotDifferentiable("LinSpace") + + +@ops.RegisterGradient("Complex") +def _ComplexGrad(op: ops.Operation, grad): + """Returns the real and imaginary components of 'grad', respectively.""" + x = op.inputs[0] + y = op.inputs[1] + gx = math_ops.real(grad) + gy = math_ops.imag(grad) + return _ReduceGradientArgs(x, y, gx, gy) + + +@ops.RegisterGradient("Real") +def _RealGrad(_, grad): + """Returns 'grad' as the real part and set the imaginary part 0.""" + zero = constant_op.constant(0, dtype=grad.dtype) + return math_ops.complex(grad, zero) + + +@ops.RegisterGradient("Imag") +def _ImagGrad(_, grad): + """Returns 'grad' as the imaginary part and set the real part 0.""" + zero = constant_op.constant(0, dtype=grad.dtype) + return math_ops.complex(zero, grad) + + +@ops.RegisterGradient("Angle") +def _AngleGrad(op: ops.Operation, grad): + """Returns `-grad / (Im(x) + i Re(x))`.""" + x = op.inputs[0] + with ops.control_dependencies([grad]): + re = math_ops.real(x) + im = math_ops.imag(x) + z = math_ops.reciprocal(math_ops.complex(im, re)) + zero = constant_op.constant(0, dtype=grad.dtype) + complex_grad = math_ops.complex(grad, zero) + return -complex_grad * z + + +@ops.RegisterGradient("Conj") +def _ConjGrad(_, grad): + """Returns the complex conjugate of grad.""" + return math_ops.conj(grad) + + +@ops.RegisterGradient("ComplexAbs") +def _ComplexAbsGrad(op: ops.Operation, grad): + """Returns the gradient of ComplexAbs.""" + return math_ops.div_no_nan( + math_ops.complex( + grad, array_ops.zeros_like(grad)) * op.inputs[0], + math_ops.complex( + op.outputs[0], array_ops.zeros_like(op.outputs[0]))) + + +@ops.RegisterGradient("Cast") +def _CastGrad(op: ops.Operation, grad): + t = [ + dtypes.float16, dtypes.float32, dtypes.float64, dtypes.bfloat16, + dtypes.complex64, dtypes.complex128 + ] + src_type = op.inputs[0].dtype.base_dtype + dst_type = grad.dtype.base_dtype + if src_type in t and dst_type in t: + return math_ops.cast(grad, src_type) + else: + return None + + +@ops.RegisterGradient("Cross") +def _CrossGrad(op: ops.Operation, grad): + u = op.inputs[0] + v = op.inputs[1] + return (math_ops.cross(v, grad), math_ops.cross(grad, u)) + + +@ops.RegisterGradient("Cumsum") +def _CumsumGrad(op: ops.Operation, grad): + axis = op.inputs[1] + exclusive = op.get_attr("exclusive") + reverse = op.get_attr("reverse") + return [ + math_ops.cumsum(grad, axis, exclusive=exclusive, reverse=not reverse), + None + ] + + +@ops.RegisterGradient("Cumprod") +def _CumprodGrad(op: ops.Operation, grad): + x = op.inputs[0] + axis = op.inputs[1] + exclusive = op.get_attr("exclusive") + reverse = op.get_attr("reverse") + + prod = math_ops.cumprod(x, axis, exclusive=exclusive, reverse=reverse) + out = math_ops.cumsum( + prod * grad, axis, exclusive=exclusive, reverse=not reverse + ) + return [math_ops.div_no_nan(out, x), None] + + +# pylint: disable=missing-function-docstring +@ops.RegisterGradient("CumulativeLogsumexp") +def _CumulativeLogsumexpGrad(op: ops.Operation, grad): + x = op.inputs[0] + axis = op.inputs[1] + cumulative_logsumexp = op.outputs[0] + + exclusive = op.get_attr("exclusive") + reverse = op.get_attr("reverse") + + # Split the incoming gradient into positive and negative part + # in order to take logs. This is required for stable results. + log_grad_positive = array_ops.where_v2( + math_ops.greater(grad, 0), + math_ops.log(grad), + grad.dtype.min) + + log_grad_negative = array_ops.where_v2( + math_ops.less(grad, 0), + math_ops.log(-grad), + grad.dtype.min) + + output_pos = math_ops.exp( + math_ops.cumulative_logsumexp( + log_grad_positive - cumulative_logsumexp, + axis=axis, reverse=not reverse, exclusive=exclusive) + x) + + output_neg = math_ops.exp( + math_ops.cumulative_logsumexp( + log_grad_negative - cumulative_logsumexp, + axis=axis, reverse=not reverse, exclusive=exclusive) + x) + + return [output_pos - output_neg, None] + + +@ops.RegisterGradient("NextAfter") +def _NextAfterGrad(op: ops.Operation, grad): + """Returns gradient of nextafter(x1, x2) with respect to x1 and x2.""" + x1 = op.inputs[0] + x2 = op.inputs[1] + s_x1 = array_ops.shape(x1) + s_x2 = array_ops.shape(x2) + r_x1, r_x2 = gen_array_ops.broadcast_gradient_args(s_x1, s_x2) + with ops.control_dependencies([grad]): + partial_x1 = array_ops.ones(s_x1, dtype=x1.dtype) + partial_x2 = array_ops.zeros(s_x2, dtype=x2.dtype) + return (array_ops.reshape( + math_ops.reduce_sum(partial_x1 * grad, r_x1), s_x1), + array_ops.reshape( + math_ops.reduce_sum(partial_x2 * grad, r_x2), s_x2)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7645eaaae3931161b673ed6040b5858cb3245ef3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/math_ops.py @@ -0,0 +1,5857 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Math Operations. + +Note: Functions taking `Tensor` arguments can also take anything accepted by +`tf.convert_to_tensor`. + +Note: Elementwise binary operations in TensorFlow follow [numpy-style +broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). + +TensorFlow provides a variety of math functions including: + +* Basic arithmetic operators and trigonometric functions. +* Special math functions (like: `tf.math.igamma` and `tf.math.zeta`) +* Complex number functions (like: `tf.math.imag` and `tf.math.angle`) +* Reductions and scans (like: `tf.math.reduce_mean` and `tf.math.cumsum`) +* Segment functions (like: `tf.math.segment_sum`) + +See: `tf.linalg` for matrix and tensor functions. + + + +## About Segmentation + +TensorFlow provides several operations that you can use to perform common +math computations on tensor segments. +Here a segmentation is a partitioning of a tensor along +the first dimension, i.e. it defines a mapping from the first dimension onto +`segment_ids`. The `segment_ids` tensor should be the size of +the first dimension, `d0`, with consecutive IDs in the range `0` to `k`, +where `k [[0 0 0 0] +# [5 6 7 8]] +``` + +The standard `segment_*` functions assert that the segment indices are sorted. +If you have unsorted indices use the equivalent `unsorted_segment_` function. +These functions take an additional argument `num_segments` so that the output +tensor can be efficiently allocated. + +``` python +c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) +tf.math.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2) +# ==> [[ 6, 8, 10, 12], +# [-1, -2, -3, -4]] +``` + +API docstring: tensorflow.math +""" +import builtins +import numbers +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_bitwise_ops +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import gen_sparse_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_math_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import traceback_utils +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +# Aliases for some automatically-generated names. +nextafter = gen_math_ops.next_after + + +@tf_export("linspace", v1=["lin_space", "linspace"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("lin_space") +def linspace_nd(start, stop, num, name=None, axis=0): + r"""Generates evenly-spaced values in an interval along a given axis. + + A sequence of `num` evenly-spaced values are generated beginning at `start` + along a given `axis`. + If `num > 1`, the values in the sequence increase by + `(stop - start) / (num - 1)`, so that the last one is exactly `stop`. + If `num <= 0`, `ValueError` is raised. + + Matches + [np.linspace](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html)'s + behaviour + except when `num == 0`. + + For example: + + ``` + tf.linspace(10.0, 12.0, 3, name="linspace") => [ 10.0 11.0 12.0] + ``` + + `Start` and `stop` can be tensors of arbitrary size: + + >>> tf.linspace([0., 5.], [10., 40.], 5, axis=0) + + + `Axis` is where the values will be generated (the dimension in the + returned tensor which corresponds to the axis will be equal to `num`) + + >>> tf.linspace([0., 5.], [10., 40.], 5, axis=-1) + + + + + Args: + start: A `Tensor`. Must be one of the following types: `bfloat16`, + `float32`, `float64`. N-D tensor. First entry in the range. + stop: A `Tensor`. Must have the same type and shape as `start`. N-D tensor. + Last entry in the range. + num: A `Tensor`. Must be one of the following types: `int32`, `int64`. 0-D + tensor. Number of values to generate. + name: A name for the operation (optional). + axis: Axis along which the operation is performed (used only when N-D + tensors are provided). + + Returns: + A `Tensor`. Has the same type as `start`. + """ + + with ops.name_scope(name, "linspace", [start, stop]): + start = ops.convert_to_tensor(start, name="start") + # stop must be convertible to the same dtype as start + stop = ops.convert_to_tensor(stop, name="stop", dtype=start.dtype) + num_int = array_ops.convert_to_int_tensor(num, name="num") + num = cast(num_int, dtype=start.dtype) + + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(start), array_ops.shape(stop)) + start = array_ops.broadcast_to(start, broadcast_shape) + stop = array_ops.broadcast_to(stop, broadcast_shape) + + expanded_start = array_ops.expand_dims(start, axis=axis) + expanded_stop = array_ops.expand_dims(stop, axis=axis) + + shape = array_ops.shape(expanded_start) + ndims = array_ops.shape(shape)[0] + + axis = array_ops.where_v2(axis >= 0, axis, ndims + axis) + + # The purpose is to avoid having negative values when repeating. + num_fill = gen_math_ops.maximum(num_int - 2, 0) + # To avoid having negative values in the range or zero division + # the result is sliced in the end so a correct result is returned for + # num == 1, and num == 0. + n_steps = gen_math_ops.maximum(num_int - 1, 1) + delta = (expanded_stop - expanded_start) / cast(n_steps, + expanded_stop.dtype) + # Re-cast tensors as delta. + expanded_start = cast(expanded_start, delta.dtype) + expanded_stop = cast(expanded_stop, delta.dtype) + # If num < 0, we will throw exception in the range + # otherwise use the same div for delta + range_end = array_ops.where_v2(num_int >= 0, n_steps, -1) + # Even though range supports an output dtype, its limited + # (e.g. doesn't support half at the moment). + desired_range = cast(range(1, range_end, dtype=dtypes.int64), delta.dtype) + mask = gen_math_ops.equal(axis, range(ndims)) + # desired_range_shape is [1. 1. 1. ... 1. num_fill 1. 1. ... 1.], where the + # index of num_fill is equal to axis. + desired_range_shape = array_ops.where_v2(mask, num_fill, 1) + desired_range = array_ops.reshape(desired_range, desired_range_shape) + + res = expanded_start + delta * desired_range + + # Add the start and endpoints to the result, and slice out the desired + # portion. + all_tensors = (expanded_start, res, expanded_stop) + concatenated = array_ops.concat(all_tensors, axis=axis) + begin = array_ops.zeros_like(shape) + # Preserve shape information for final slice. + size = array_ops.concat( + (shape[0:axis], array_ops.reshape(num_int, [1]), shape[axis + 1 :]), + axis=0, + ) + return array_ops.slice(concatenated, begin, size) + + +linspace = linspace_nd + +arg_max = deprecation.deprecated(None, "Use `tf.math.argmax` instead")(arg_max) # pylint: disable=used-before-assignment +arg_min = deprecation.deprecated(None, "Use `tf.math.argmin` instead")(arg_min) # pylint: disable=used-before-assignment +tf_export(v1=["arg_max"])(dispatch.add_dispatch_support(arg_max)) +tf_export(v1=["arg_min"])(dispatch.add_dispatch_support(arg_min)) + + +# This is set by resource_variable_ops.py. It is included in this way since +# there is a circular dependency between math_ops and resource_variable_ops +_resource_variable_type = None + + +def _set_doc(doc): + + def _decorator(func): + func.__doc__ = doc + return func + + return _decorator + + +# pylint: disable=redefined-builtin +@tf_export(v1=["math.argmax", "argmax"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "Use the `axis` argument instead", + "dimension") +@_set_doc( + gen_math_ops.arg_max.__doc__.replace("dimensions", + "axes").replace("dimension", "axis")) +def argmax(input, + axis=None, + name=None, + dimension=None, + output_type=dtypes.int64): + axis = deprecation.deprecated_argument_lookup("axis", axis, "dimension", + dimension) + return argmax_v2(input, axis, output_type, name) + + +@tf_export("math.argmax", "argmax", v1=[]) +@dispatch.add_dispatch_support +def argmax_v2(input, axis=None, output_type=dtypes.int64, name=None): + """Returns the index with the largest value across axes of a tensor. + + In case of identity returns the smallest index. + + For example: + + >>> A = tf.constant([2, 20, 30, 3, 6]) + >>> tf.math.argmax(A) # A[2] is maximum in tensor A + + >>> B = tf.constant([[2, 20, 30, 3, 6], [3, 11, 16, 1, 8], + ... [14, 45, 23, 5, 27]]) + >>> tf.math.argmax(B, 0) + + >>> tf.math.argmax(B, 1) + + >>> C = tf.constant([0, 0, 0, 0]) + >>> tf.math.argmax(C) # Returns smallest index in case of ties + + + Args: + input: A `Tensor`. + axis: An integer, the axis to reduce across. Default to 0. + output_type: An optional output dtype (`tf.int32` or `tf.int64`). Defaults + to `tf.int64`. + name: An optional name for the operation. + + Returns: + A `Tensor` of type `output_type`. + """ + if axis is None: + axis = 0 + return gen_math_ops.arg_max(input, axis, name=name, output_type=output_type) + + +@tf_export(v1=["math.argmin", "argmin"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "Use the `axis` argument instead", + "dimension") +@_set_doc( + gen_math_ops.arg_min.__doc__.replace("dimensions", + "axes").replace("dimension", "axis")) +def argmin(input, + axis=None, + name=None, + dimension=None, + output_type=dtypes.int64): + axis = deprecation.deprecated_argument_lookup("axis", axis, "dimension", + dimension) + return argmin_v2(input, axis, output_type, name) + + +@tf_export("math.argmin", "argmin", v1=[]) +@dispatch.add_dispatch_support +def argmin_v2(input, axis=None, output_type=dtypes.int64, name=None): + """Returns the index with the smallest value across axes of a tensor. + + Returns the smallest index in case of ties. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, + `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, + `uint64`. + axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. + int32 or int64, must be in the range `-rank(input), rank(input))`. + Describes which axis of the input Tensor to reduce across. For vectors, + use axis = 0. + output_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to + `tf.int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `output_type`. + + Usage: + ```python + import tensorflow as tf + a = [1, 10, 26.9, 2.8, 166.32, 62.3] + b = tf.math.argmin(input = a) + c = tf.keras.backend.eval(b) + # c = 0 + # here a[0] = 1 which is the smallest element of a across axis 0 + ``` + """ + if axis is None: + axis = 0 + return gen_math_ops.arg_min(input, axis, name=name, output_type=output_type) + + +# pylint: enable=redefined-builtin + + +# pylint: disable=anomalous-backslash-in-string,protected-access +# pylint: disable=g-docstring-has-escape +@tf_export("math.abs", "abs") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def abs(x, name=None): # pylint: disable=redefined-builtin + r"""Computes the absolute value of a tensor. + + Given a tensor of integer or floating-point values, this operation returns a + tensor of the same type, where each element contains the absolute value of the + corresponding element in the input. + + Given a tensor `x` of complex numbers, this operation returns a tensor of type + `float32` or `float64` that is the absolute value of each element in `x`. For + a complex number \\(a + bj\\), its absolute value is computed as + \\(\sqrt{a^2 + b^2}\\). + + For example: + + >>> # real number + >>> x = tf.constant([-2.25, 3.25]) + >>> tf.abs(x) + + + >>> # complex number + >>> x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]]) + >>> tf.abs(x) + + + Args: + x: A `Tensor` or `SparseTensor` of type `float16`, `float32`, `float64`, + `int32`, `int64`, `complex64` or `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` of the same size, type and sparsity as `x`, + with absolute values. Note, for `complex64` or `complex128` input, the + returned `Tensor` will be of type `float32` or `float64`, respectively. + """ + with ops.name_scope(name, "Abs", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_complex: + return gen_math_ops.complex_abs(x, Tout=x.dtype.real_dtype, name=name) + return gen_math_ops._abs(x, name=name) + + +# pylint: enable=g-docstring-has-escape + + +# pylint: disable=redefined-builtin +def _bucketize(input, boundaries, name=None): + return gen_math_ops.bucketize(input=input, boundaries=boundaries, name=name) + + +# pylint: enable=redefined-builtin + + +class DivideDelegateWithName: + """Use Python2/Python3 division delegation to implement divide for tensors.""" + + def __init__(self, x, name): + """Construct DivideDelegateWithName. + + Args: + x: Tensor to use as left operand in operator overloads + name: The name that is preferred for the op created. + """ + self.x = x + self.name = name + + def __truediv__(self, y): + return _truediv_python3(self.x, y, self.name) + + def __floordiv__(self, y): + return floordiv(self.x, y, self.name) + + def __div__(self, y): + return _div_python2(self.x, y, self.name) + + +@tf_export("math.divide", "divide") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def divide(x, y, name=None): + """Computes Python style division of `x` by `y`. + + For example: + + >>> x = tf.constant([16, 12, 11]) + >>> y = tf.constant([4, 6, 2]) + >>> tf.divide(x,y) + + + Args: + x: A `Tensor` + y: A `Tensor` + name: A name for the operation (optional). + + Returns: + A `Tensor` with same shape as input + """ + + if name is not None: + # Cannot use tensors operator overload, because it has no way to track + # override names. Use a dummy class to track the runtime division behavior + return DivideDelegateWithName(x, name) / y + else: + # We do conversion here to make sure at least x is a tensor. + if not tensor_util.is_tf_type(x): + dtype = y.dtype.base_dtype if tensor_util.is_tf_type(y) else None + x = ops.convert_to_tensor(x, dtype=dtype) + return x / y + + +@tf_export("math.multiply", "multiply") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def multiply(x, y, name=None): + """Returns an element-wise x * y. + + For example: + + >>> x = tf.constant(([1, 2, 3, 4])) + >>> tf.math.multiply(x, x) + + + Since `tf.math.multiply` will convert its arguments to `Tensor`s, you can also + pass in non-`Tensor` arguments: + + >>> tf.math.multiply(7,6) + + + If `x.shape` is not the same as `y.shape`, they will be broadcast to a + compatible shape. (More about broadcasting + [here](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).) + + For example: + + >>> x = tf.ones([1, 2]); + >>> y = tf.ones([2, 1]); + >>> x * y # Taking advantage of operator overriding + + + The reduction version of this elementwise operation is `tf.math.reduce_prod` + + Args: + x: A Tensor. Must be one of the following types: `bfloat16`, + `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, + `int16`, `int32`, `int64`, `complex64`, `complex128`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + + A `Tensor`. Has the same type as `x`. + + Raises: + + * InvalidArgumentError: When `x` and `y` have incompatible shapes or types. + """ + + return gen_math_ops.mul(x, y, name) + + +# TODO(aselle): put deprecation in after another round of global code changes +@deprecation.deprecated( + "2016-12-30", + "`tf.mul(x, y)` is deprecated; use `tf.math.multiply(x, y)` or `x * y`") +def _mul(x, y, name=None): + return gen_math_ops.mul(x, y, name) + + +_mul.__doc__ = ( + gen_math_ops.mul.__doc__ + ("" if _mul.__doc__ is None else _mul.__doc__)) + + +@tf_export("math.subtract", "subtract") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def subtract(x, y, name=None): + return gen_math_ops.sub(x, y, name) + + +subtract.__doc__ = gen_math_ops.sub.__doc__ + + +# TODO(aselle): put deprecation in after another round of global code changes +@deprecation.deprecated( + "2016-12-30", + "`tf.sub(x, y)` is deprecated, please use `tf.subtract(x, y)` or `x - y`") +def _sub(x, y, name=None): + return gen_math_ops.sub(x, y, name) + + +_sub.__doc__ = ( + gen_math_ops.sub.__doc__ + ("" if _sub.__doc__ is None else _sub.__doc__)) + +negative = gen_math_ops.neg + + +# pylint: disable=g-docstring-has-escape +@deprecation.deprecated( + "2016-12-30", + "`tf.neg(x)` is deprecated, please use `tf.negative(x)` or `-x`") +def _neg(x, name=None): + """Computes numerical negative value element-wise. + + I.e., \\(y = -x\\). + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + """ + return negative(x, name) + + +# pylint: enable=g-docstring-has-escape + + +@tf_export(v1=["math.scalar_mul", "scalar_mul"]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def scalar_mul(scalar, x, name=None): + """Multiplies a scalar times a `Tensor` or `IndexedSlices` object. + + This is a special case of `tf.math.multiply`, where the first value must be a + `scalar`. Unlike the general form of `tf.math.multiply`, this is operation is + guaranteed to be efficient for `tf.IndexedSlices`. + + >>> x = tf.reshape(tf.range(30, dtype=tf.float32), [10, 3]) + >>> with tf.GradientTape() as g: + ... g.watch(x) + ... y = tf.gather(x, [1, 2]) # IndexedSlices + ... z = tf.math.scalar_mul(10.0, y) + + Args: + scalar: A 0-D scalar `Tensor`. Must have known shape. + x: A `Tensor` or `IndexedSlices` to be scaled. + name: A name for the operation (optional). + + Returns: + `scalar * x` of the same type (`Tensor` or `IndexedSlices`) as `x`. + + Raises: + ValueError: if scalar is not a 0-D `scalar`. + """ + base_dtype = dtypes.as_dtype(x.dtype).base_dtype + scalar = ops.convert_to_tensor( + scalar, dtype=base_dtype, name="scalar") + shape = scalar.get_shape() + if shape.ndims == 0: + if isinstance(x, indexed_slices.IndexedSlices): + return indexed_slices.IndexedSlices( + gen_math_ops.mul(scalar, x.values, name), x.indices, x.dense_shape) + else: + return gen_math_ops.mul(scalar, x, name) + else: + raise ValueError( + f"The input scalar must be a 0-D value. Received shape {shape}.") + + +@tf_export("math.softplus", "nn.softplus", v1=["math.softplus", "nn.softplus"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def softplus(features, name=None): + """Computes elementwise softplus: `softplus(x) = log(exp(x) + 1)`. + + `softplus` is a smooth approximation of `relu`. Like `relu`, `softplus` always + takes on positive values. + + + + Example: + + >>> import tensorflow as tf + >>> tf.math.softplus(tf.range(0, 2, dtype=tf.float32)).numpy() + array([0.6931472, 1.3132616], dtype=float32) + + Args: + features: `Tensor` + name: Optional: name to associate with this operation. + Returns: + `Tensor` + """ + return gen_nn_ops.softplus(features, name) + + +@tf_export("math.scalar_mul", "scalar_mul", v1=[]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +@_set_doc(scalar_mul.__doc__) +def scalar_mul_v2(scalar, x, name=None): + with ops.name_scope(name, "scalar_mul", [x]) as name: + return scalar_mul(scalar, x, name) + + +@tf_export("math.pow", "pow") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def pow(x, y, name=None): # pylint: disable=redefined-builtin + r"""Computes the power of one value to another. + + Given a tensor `x` and a tensor `y`, this operation computes \\(x^y\\) for + corresponding elements in `x` and `y`. For example: + + ```python + x = tf.constant([[2, 2], [3, 3]]) + y = tf.constant([[8, 16], [2, 3]]) + tf.pow(x, y) # [[256, 65536], [9, 27]] + ``` + + Args: + x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, + `complex64`, or `complex128`. + y: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, + `complex64`, or `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. + """ + with ops.name_scope(name, "Pow", [x]) as name: + return gen_math_ops._pow(x, y, name=name) + + +# pylint: disable=redefined-builtin,redefined-outer-name +@tf_export("dtypes.complex", "complex") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def complex(real, imag, name=None): + r"""Converts two real numbers to a complex number. + + Given a tensor `real` representing the real part of a complex number, and a + tensor `imag` representing the imaginary part of a complex number, this + operation returns complex numbers elementwise of the form \\(a + bj\\), where + *a* represents the `real` part and *b* represents the `imag` part. + + The input tensors `real` and `imag` must have the same shape. + + For example: + + ```python + real = tf.constant([2.25, 3.25]) + imag = tf.constant([4.75, 5.75]) + tf.complex(real, imag) # [[2.25 + 4.75j], [3.25 + 5.75j]] + ``` + + Args: + real: A `Tensor`. Must be one of the following types: `float32`, `float64`. + imag: A `Tensor`. Must have the same type as `real`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `complex64` or `complex128`. + + Raises: + TypeError: Real and imag must be correct types + """ + real = ops.convert_to_tensor(real, name="real") + imag = ops.convert_to_tensor(imag, name="imag") + with ops.name_scope(name, "Complex", [real, imag]) as name: + input_types = (real.dtype, imag.dtype) + if input_types == (dtypes.float64, dtypes.float64): + Tout = dtypes.complex128 + elif input_types == (dtypes.float32, dtypes.float32): + Tout = dtypes.complex64 + else: + raise TypeError( + f"The `real` and `imag` components have incorrect types: " + f"{real.dtype.name} {imag.dtype.name}. They must be consistent, and " + f"one of {[dtypes.float32, dtypes.float64]}") + return gen_math_ops._complex(real, imag, Tout=Tout, name=name) + + +@tf_export("math.sign", "sign") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def sign(x, name=None): + r"""Returns an element-wise indication of the sign of a number. + + `y = sign(x) = -1 if x < 0; 0 if x == 0; 1 if x > 0`. + + For complex numbers, `y = sign(x) = x / |x| if x != 0, otherwise y = 0`. + + Example usage: + + >>> # real number + >>> tf.math.sign([0., 2., -3.]) + + + >>> # complex number + >>> tf.math.sign([1 + 1j, 0 + 0j]) + + + Args: + x: A Tensor. Must be one of the following types: bfloat16, half, float32, + float64, int32, int64, complex64, complex128. + name: A name for the operation (optional). + + Returns: + A Tensor. Has the same type as x. + + If x is a SparseTensor, returns SparseTensor(x.indices, + tf.math.sign(x.values, ...), x.dense_shape). + """ + x = ops.convert_to_tensor(x) + if x.dtype.is_complex: + return gen_math_ops.div_no_nan( + x, + cast( + gen_math_ops.complex_abs( + x, + Tout=dtypes.float32 + if x.dtype == dtypes.complex64 else dtypes.float64), + dtype=x.dtype), + name=name) + return gen_math_ops.sign(x, name=name) + + +@tf_export("math.real", v1=["math.real", "real"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("real") +def real(input, name=None): + r"""Returns the real part of a complex (or real) tensor. + + Given a tensor `input`, this operation returns a tensor of type `float` that + is the real part of each element in `input` considered as a complex number. + + For example: + + ```python + x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j]) + tf.math.real(x) # [-2.25, 3.25] + ``` + + If `input` is already real, it is returned unchanged. + + Args: + input: A `Tensor`. Must have numeric type. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32` or `float64`. + """ + with ops.name_scope(name, "Real", [input]) as name: + input = ops.convert_to_tensor(input, name="input") + if input.dtype.is_complex: + real_dtype = input.dtype.real_dtype + return gen_math_ops.real(input, Tout=real_dtype, name=name) + elif input.dtype.is_numeric: + return input + else: + raise TypeError( + "input must be a numeric tensor, but got tensor with dtype {}".format( + input.dtype + ) + ) + + +@tf_export("math.imag", v1=["math.imag", "imag"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("imag") +def imag(input, name=None): + r"""Returns the imaginary part of a complex (or real) tensor. + + Given a tensor `input`, this operation returns a tensor of type `float` that + is the imaginary part of each element in `input` considered as a complex + number. If `input` is real, a tensor of all zeros is returned. + + For example: + + ```python + x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j]) + tf.math.imag(x) # [4.75, 5.75] + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float`, `double`, + `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32` or `float64`. + """ + with ops.name_scope(name, "Imag", [input]) as name: + input = ops.convert_to_tensor(input, name="input") + if input.dtype.is_complex: + return gen_math_ops.imag(input, Tout=input.dtype.real_dtype, name=name) + else: + return array_ops.zeros_like(input) + + +@tf_export("math.angle", v1=["math.angle", "angle"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("angle") +def angle(input, name=None): + r"""Returns the element-wise argument of a complex (or real) tensor. + + Given a tensor `input`, this operation returns a tensor of type `float` that + is the argument of each element in `input` considered as a complex number. + + The elements in `input` are considered to be complex numbers of the form + \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. + If `input` is real then *b* is zero by definition. + + The argument returned by this function is of the form \\(atan2(b, a)\\). + If `input` is real, a tensor of all zeros is returned. + + For example: + + ``` + input = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j], dtype=tf.complex64) + tf.math.angle(input).numpy() + # ==> array([2.0131705, 1.056345 ], dtype=float32) + ``` + + Args: + input: A `Tensor`. Must be one of the following types: `float`, `double`, + `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32` or `float64`. + """ + with ops.name_scope(name, "Angle", [input]) as name: + input = ops.convert_to_tensor(input, name="input") + if input.dtype.is_complex: + return gen_math_ops.angle(input, Tout=input.dtype.real_dtype, name=name) + else: + return array_ops.where(input < 0, np.pi * array_ops.ones_like(input), + array_ops.zeros_like(input)) + + +# pylint: enable=redefined-outer-name,redefined-builtin + + +@tf_export("math.round", "round") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def round(x, name=None): # pylint: disable=redefined-builtin + """Rounds the values of a tensor to the nearest integer, element-wise. + + Rounds half to even. Also known as bankers rounding. If you want to round + according to the current system rounding mode use tf::cint. + For example: + + ```python + x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5]) + tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ] + ``` + + Args: + x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, or `int64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of same shape and type as `x`. + """ + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_integer: + return x + else: + return gen_math_ops.round(x, name=name) + + +# TODO(mdan): Include a full_type argument to replace dtype. +@tf_export("cast", "dtypes.cast") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def cast(x, dtype, name=None): + """Casts a tensor to a new type. + + The operation casts `x` (in case of `Tensor`) or `x.values` + (in case of `SparseTensor` or `IndexedSlices`) to `dtype`. + + For example: + + >>> x = tf.constant([1.8, 2.2], dtype=tf.float32) + >>> tf.cast(x, tf.int32) + + + Notice `tf.cast` has an alias `tf.dtypes.cast`: + + >>> x = tf.constant([1.8, 2.2], dtype=tf.float32) + >>> tf.dtypes.cast(x, tf.int32) + + + The operation supports data types (for `x` and `dtype`) of + `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, `int64`, + `float16`, `float32`, `float64`, `complex64`, `complex128`, `bfloat16`. + In case of casting from complex types (`complex64`, `complex128`) to real + types, only the real part of `x` is returned. In case of casting from real + types to complex types (`complex64`, `complex128`), the imaginary part of the + returned value is set to `0`. The handling of complex types here matches the + behavior of numpy. + + Note casting nan and inf values to integral types has undefined behavior. + + Note this operation can lead to a loss of precision when converting native + Python `float` and `complex` variables to `tf.float64` or `tf.complex128` + tensors, since the input is first converted to the `float32` data type and + then widened. It is recommended to use `tf.convert_to_tensor` instead of + `tf.cast` for any non-tensor inputs. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices` of numeric type. It could + be `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `int32`, + `int64`, `float16`, `float32`, `float64`, `complex64`, `complex128`, + `bfloat16`. + dtype: The destination type. The list of supported dtypes is the same as + `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` and + same type as `dtype`. + + Raises: + TypeError: If `x` cannot be cast to the `dtype`. + + """ + base_type = dtypes.as_dtype(dtype).base_dtype + if isinstance( + x, (tensor_lib.Tensor, _resource_variable_type)) and base_type == x.dtype: + return x + with ops.name_scope(name, "Cast", [x]) as name: + if isinstance(x, sparse_tensor.SparseTensor): + values_cast = cast(x.values, base_type, name=name) + x = sparse_tensor.SparseTensor(x.indices, values_cast, x.dense_shape) + elif isinstance(x, indexed_slices.IndexedSlices): + values_cast = cast(x.values, base_type, name=name) + x = indexed_slices.IndexedSlices(values_cast, x.indices, x.dense_shape) + else: + # TODO(josh11b): If x is not already a Tensor, we could return + # ops.convert_to_tensor(x, dtype=dtype, ...) here, but that + # allows some conversions that cast() can't do, e.g. casting numbers to + # strings. + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_complex and base_type.is_floating: + logging.warn( + f"You are casting an input of type {x.dtype.name} to an " + f"incompatible dtype {base_type.name}. This will " + "discard the imaginary part and may not be what you " + "intended." + ) + if x.dtype != base_type: + x = gen_math_ops.cast(x, base_type, name=name) + return x + + +@tf_export("dtypes.saturate_cast", "saturate_cast") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def saturate_cast(value, dtype, name=None): + """Performs a safe saturating cast of `value` to `dtype`. + + This function casts the input to `dtype` without overflow. If + there is a danger that values would over or underflow in the cast, this op + applies the appropriate clamping before the cast. See `tf.cast` for more + details. + + Args: + value: A `Tensor`. + dtype: The desired output `DType`. + name: A name for the operation (optional). + + Returns: + `value` safely cast to `dtype`. + """ + # When casting to a type with smaller representable range, clamp. + # Note that this covers casting to unsigned types as well. + with ops.name_scope(name, "saturate_cast", [value]) as name: + value = ops.convert_to_tensor(value, name="value") + dtype = dtypes.as_dtype(dtype).base_dtype + + in_dtype = value.dtype + if in_dtype.is_complex: + if dtype.is_complex: + # Clamp real and imag components separately, if required. + real_in_dtype = in_dtype.real_dtype + real_out_dtype = dtype.real_dtype + if ( + real_in_dtype.min < real_out_dtype.min + or real_in_dtype.max > real_out_dtype.max + ): + value = gen_math_ops._clip_by_value( + value, + ops.convert_to_tensor( + builtins.complex(real_out_dtype.min, real_out_dtype.min), + dtype=in_dtype), + ops.convert_to_tensor( + builtins.complex(real_out_dtype.max, real_out_dtype.max), + dtype=in_dtype), + name="clamp") + return cast(value, dtype, name=name) + else: + # Extract real component and fall through to clamp+cast. + value = real(value) + logging.warn("Casting complex to real discards imaginary part.") + in_dtype = in_dtype.real_dtype + + # in_dtype is real, but out_dtype could be complex. + out_real_dtype = dtype.real_dtype + + # TODO: b/288437118 - unconditionally apply `clip_by_value` to fix `inf` + # behavior. + if in_dtype.min < out_real_dtype.min or in_dtype.max > out_real_dtype.max: + # The output min/max may not actually be representable in the + # in_dtype (e.g. casting float32 to uint32). This can lead to undefined + # behavior when trying to cast a value outside the valid range of the + # target type. We work around this by nudging the min/max to fall within + # the valid output range. The catch is that we may actually saturate + # to a value less than the true saturation limit, but this is the best we + # can do in order to avoid UB without introducing a separate SaturateCast + # op. + np_dtype = in_dtype.as_numpy_dtype + min_limit = np_dtype(np.maximum(in_dtype.min, out_real_dtype.min)) + if min_limit < out_real_dtype.min: + min_limit = np.nextafter(min_limit, np_dtype(0), dtype=np_dtype) + + max_limit = np_dtype(np.minimum(in_dtype.max, out_real_dtype.max)) + if max_limit > out_real_dtype.max: + max_limit = np.nextafter(max_limit, np_dtype(0), dtype=np_dtype) + + value = gen_math_ops._clip_by_value( + value, + ops.convert_to_tensor(min_limit, dtype=in_dtype), + ops.convert_to_tensor(max_limit, dtype=in_dtype), + name="clamp", + ) + return cast(value, dtype, name=name) + + +@tf_export(v1=["to_float"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_float(x, name="ToFloat"): + """Casts a tensor to type `float32`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `float32`. + + Raises: + TypeError: If `x` cannot be cast to the `float32`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.float32)`. There are no further issues with eager execution + or tf.function. + + Before: + + >>> tf.compat.v1.to_float(tf.constant(3.14, dtype=tf.double)) + + + After: + + >>> tf.cast(tf.constant(3.14, dtype=tf.double), tf.float32) + + + @end_compatibility + + """ + return cast(x, dtypes.float32, name=name) + + +@tf_export(v1=["to_double"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_double(x, name="ToDouble"): + """Casts a tensor to type `float64`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `float64`. + + Raises: + TypeError: If `x` cannot be cast to the `float64`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.double)`. There are no further issues with eager execution or + tf.function. + + Before: + + >>> tf.compat.v1.to_double(tf.constant(3.14, dtype=tf.float32)) + + + After: + + >>> tf.cast(tf.constant(3.14, dtype=tf.float32), tf.double) + + + @end_compatibility + + """ + return cast(x, dtypes.float64, name=name) + + +@tf_export(v1=["to_int32"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_int32(x, name="ToInt32"): + """Casts a tensor to type `int32`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `int32`. + + Raises: + TypeError: If `x` cannot be cast to the `int32`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.int32)`. There are no further issues with eager execution or + tf.function. + + Before: + + >>> tf.compat.v1.to_int32(tf.constant(1, dtype=tf.int64)) + + + After: + + >>> tf.cast(tf.constant(1, dtype=tf.int64), tf.int32) + + + @end_compatibility + + """ + return cast(x, dtypes.int32, name=name) + + +@tf_export(v1=["to_int64"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_int64(x, name="ToInt64"): + """Casts a tensor to type `int64`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `int64`. + + Raises: + TypeError: If `x` cannot be cast to the `int64`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.int64)`. There are no further issues with eager execution or + tf.function. + + Before: + + >>> tf.compat.v1.to_int64(tf.constant(1, dtype=tf.int32)) + + + After: + + >>> tf.cast(tf.constant(1, dtype=tf.int32), tf.int64) + + + @end_compatibility + + """ + return cast(x, dtypes.int64, name=name) + + +@tf_export(v1=["to_bfloat16"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_bfloat16(x, name="ToBFloat16"): + """Casts a tensor to type `bfloat16`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `bfloat16`. + + Raises: + TypeError: If `x` cannot be cast to the `bfloat16`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.bfloat16)`. There are no further issues with eager execution + or tf.function. + + Before: + + >>> tf.compat.v1.to_bfloat16(tf.constant(3.14, dtype=tf.float32)) + + + After: + + >>> tf.cast(tf.constant(3.14, dtype=tf.float32), tf.bfloat16) + + + @end_compatibility + + """ + return cast(x, dtypes.bfloat16, name=name) + + +@tf_export(v1=["to_complex64"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_complex64(x, name="ToComplex64"): + """Casts a tensor to type `complex64`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `complex64`. + + Raises: + TypeError: If `x` cannot be cast to the `complex64`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.complex64)`. There are no further issues with eager execution + or tf.function. + + Before: + + >>> tf.compat.v1.to_complex64(tf.constant(1. + 2.j, dtype=tf.complex128)) + + + After: + + >>> tf.cast(tf.constant(1. + 2.j, dtype=tf.complex128), tf.complex64) + + + @end_compatibility + + """ + return cast(x, dtypes.complex64, name=name) + + +@tf_export(v1=["to_complex128"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="Use `tf.cast` instead.") +def to_complex128(x, name="ToComplex128"): + """Casts a tensor to type `complex128`. + + Args: + x: A `Tensor` or `SparseTensor` or `IndexedSlices`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with + type `complex128`. + + Raises: + TypeError: If `x` cannot be cast to the `complex128`. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but has an exact replacement + `tf.cast(..., tf.complex128)`. There are no further issues with eager + execution or tf.function. + + Before: + + >>> tf.compat.v1.to_complex128(tf.constant(1. + 2.j, dtype=tf.complex64)) + + + After: + + >>> tf.cast(tf.constant(1. + 2.j, dtype=tf.complex64), tf.complex128) + + + @end_compatibility + + """ + return cast(x, dtypes.complex128, name=name) + + +tensor_lib.Tensor._override_operator("__neg__", gen_math_ops.neg) +tensor_lib.Tensor._override_operator("__abs__", abs) + + +def _maybe_get_dtype(x): + """Returns a numpy type if available from x. Skips if x is numpy.ndarray.""" + # Don't put np.ndarray in this list, because np.result_type looks at the + # value (not just dtype) of np.ndarray to decide the result type. + if isinstance(x, numbers.Real): + return x + if isinstance(x, tensor_lib.Tensor): + return x.dtype.as_numpy_dtype + if isinstance(x, dtypes.DType): + return x.as_numpy_dtype + if isinstance(x, tensor_shape.TensorShape): + return np.int32 + if isinstance(x, (list, tuple)): + raise ValueError(f"Cannot determine dtype. Got sequence {x}.") + return x + + +def maybe_promote_tensors(*tensors, force_same_dtype=False): + """Promotes tensors if numpy style promotion is enabled. + + This function promotes `tensors` according to numpy promotion rules + if numpy style promotion is enabled. Otherwise, if + `force_same_dtype` is `True`, it force-casts `tensors[1:]` to + `tensor[0]`'s dtype. Note that this force-cast can be problematic. + For example, when some `tensors[1:]` elements can be silently + downcasted. + + Args: + *tensors: the list of tensors to promote. + force_same_dtype: bool (optional, default to `False`). When numpy + style promotion is disabled and `force_same_dtype` is `True`, + this function will force-casts `tensors[1:]` to `tensor[0]`'s + dtype (which could be problematic). + + Returns: + The promoted list of tensors. + """ + if ops.is_auto_dtype_conversion_enabled(): + return tensors + if not tensors: + return tensors + if not ops.is_numpy_style_type_promotion(): + if not force_same_dtype: + return tensors + promoted_tensors = [] + promoted_tensors.append(tensors[0]) + dtype = tensors[0].dtype.base_dtype + for tensor in tensors[1:]: + promoted_tensors.append( + ops.convert_to_tensor(tensor, dtype, name="x")) + return promoted_tensors + result_type = np_dtypes._result_type( + *[_maybe_get_dtype(x) for x in nest.flatten(tensors)]) + def _promote_or_cast(x): + if isinstance(x, tensor_lib.Tensor): + x = cast(x, result_type) + else: + x = ops.convert_to_tensor(x, result_type) + return x + return [_promote_or_cast(x) for x in tensors] + + +def _OverrideBinaryOperatorHelper( + func, op_name, clazz_object=tensor_lib.Tensor): + """Register operators with different tensor and scalar versions. + + If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices, + sp_values, sp_shape, dense)` and outputs `(new_sp_values)`. + + Args: + func: the operator + op_name: name of the operator being overridden + clazz_object: class to override for. Either `Tensor` or `SparseTensor`. + """ + + @traceback_utils.filter_traceback + def binary_op_wrapper(x, y): + with ops.name_scope(None, op_name, [x, y]) as name: + try: + # force_same_dtype=False to preserve existing TF behavior + # TODO(b/178860388): Figure out why binary_op_wrapper and + # r_binary_op_wrapper use different force_same_dtype values. + x, y = maybe_promote_tensors(x, y) + return func(x, y, name=name) + except (TypeError, ValueError) as e: + # Even if dispatching the op failed, the RHS may be a tensor aware + # object that can implement the operator with knowledge of itself + # and the tensor. + # If the RHS is not tensor aware we still want to raise the + # original error from the LHS, because it may be more + # informative. + if hasattr(type(y), "__r%s__" % op_name): + try: + r_op = getattr(y, "__r%s__" % op_name) + out = r_op(x) + if out is NotImplemented: + raise + return out + except (TypeError, ValueError): + raise e + else: + raise + + @traceback_utils.filter_traceback + def binary_op_wrapper_sparse(sp_x, y): + with ops.name_scope(None, op_name, [sp_x, y]) as name: + y = ops.convert_to_tensor(y, dtype=sp_x.dtype.base_dtype, name="y") + return sparse_tensor.SparseTensor( + sp_x.indices, + func(sp_x.indices, sp_x.values, sp_x.dense_shape, y, name=name), + sp_x.dense_shape) + + @traceback_utils.filter_traceback + def r_binary_op_wrapper(y, x): + with ops.name_scope(None, op_name, [x, y]) as name: + # TODO(b/178860388): Figure out why binary_op_wrapper and + # r_binary_op_wrapper use different force_same_dtype values. + y, x = maybe_promote_tensors(y, x, force_same_dtype=True) + return func(x, y, name=name) + + # Propagate func.__doc__ to the wrappers + try: + doc = func.__doc__ + except AttributeError: + doc = None + binary_op_wrapper.__doc__ = doc + r_binary_op_wrapper.__doc__ = doc + binary_op_wrapper_sparse.__doc__ = doc + + if clazz_object is tensor_lib.Tensor: + clazz_object._override_operator("__%s__" % op_name, binary_op_wrapper) + del binary_op_wrapper + clazz_object._override_operator("__r%s__" % op_name, r_binary_op_wrapper) + del r_binary_op_wrapper + else: + clazz_object._override_operator("__%s__" % op_name, + binary_op_wrapper_sparse) + del binary_op_wrapper_sparse + + +# Conversion table for __truediv__. None entries mean no conversion required. +_TRUEDIV_TABLE = { + dtypes.uint8: dtypes.float32, + dtypes.int8: dtypes.float32, + dtypes.uint16: dtypes.float32, + dtypes.int16: dtypes.float32, + dtypes.uint32: dtypes.float64, + dtypes.int32: dtypes.float64, + dtypes.uint64: dtypes.float64, + dtypes.int64: dtypes.float64, + dtypes.bfloat16: None, + dtypes.float16: None, + dtypes.float32: None, + dtypes.float64: None, + dtypes.complex64: None, + dtypes.complex128: None, +} + + +# NOTE: the support of "sparse (true)div dense" is currently not baked in into +# "tf.(true_)div()". Until such an API decision is made, the supported usage is +# to explicitly use the "/" operator to invoke either truediv or div. +def _sparse_dense_truediv(sp_indices, sp_values, sp_shape, y, name=None): + """Internal helper function for 'sp_t / dense_t'.""" + with ops.name_scope(name, "truediv", + [sp_indices, sp_values, sp_shape, y]) as name: + sp_values = ops.convert_to_tensor(sp_values, name="sp_values") + y = ops.convert_to_tensor(y, name="y") + x_dtype = sp_values.dtype.base_dtype + y_dtype = y.dtype.base_dtype + if x_dtype != y_dtype: + raise TypeError(f"`x` and `y` must have the same dtype, " + f"got {x_dtype!r} != {y_dtype!r}.") + try: + dtype = _TRUEDIV_TABLE[x_dtype] + except KeyError: + raise TypeError( + f"Invalid dtype {x_dtype!r} in __truediv__. Expected one " + f"of {{{', '.join([repr(x) for x in _TRUEDIV_TABLE.keys()])}}}.") + if dtype is not None: + sp_values = cast(sp_values, dtype) + y = cast(y, dtype) + return gen_sparse_ops.sparse_dense_cwise_div( + sp_indices, sp_values, sp_shape, y, name=name) + + +def _truediv_python3(x, y, name=None): + with ops.name_scope(name, "truediv", [x, y]) as name: + x = ops.convert_to_tensor(x, name="x") + y = ops.convert_to_tensor(y, dtype_hint=x.dtype.base_dtype, name="y") + x_dtype = x.dtype.base_dtype + y_dtype = y.dtype.base_dtype + if x_dtype != y_dtype: + raise TypeError(f"`x` and `y` must have the same dtype, " + f"got {x_dtype!r} != {y_dtype!r}.") + try: + dtype = _TRUEDIV_TABLE[x_dtype] + except KeyError: + raise TypeError( + f"Invalid dtype {x_dtype!r} in __truediv__. Expected one " + f"of {{{', '.join([repr(x) for x in _TRUEDIV_TABLE.keys()])}}}.") + if dtype is not None: + x = cast(x, dtype) + y = cast(y, dtype) + return gen_math_ops.real_div(x, y, name=name) + + +def _div_python2(x, y, name=None): + """Divide two values using Python 2 semantics. + + Used for Tensor.__div__. + + Args: + x: `Tensor` numerator of real numeric type. + y: `Tensor` denominator of real numeric type. + name: A name for the operation (optional). + + Returns: + `x / y` returns the quotient of x and y. + """ + + with ops.name_scope(name, "div", [x, y]) as name: + x = ops.convert_to_tensor(x, name="x") + y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype) + x_dtype = x.dtype.base_dtype + y_dtype = y.dtype.base_dtype + if x_dtype != y_dtype: + raise TypeError(f"`x` and `y` must have the same dtype, " + f"got {x_dtype!r} != {y_dtype!r}.") + if x_dtype.is_floating or x_dtype.is_complex: + return gen_math_ops.real_div(x, y, name=name) + else: + return gen_math_ops.floor_div(x, y, name=name) + + +@tf_export("math.truediv", "truediv") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def truediv(x, y, name=None): + """Divides x / y elementwise (using Python 3 division operator semantics). + + NOTE: Prefer using the Tensor operator or tf.divide which obey Python + division operator semantics. + + This function forces Python 3 division operator semantics where all integer + arguments are cast to floating types first. This op is generated by normal + `x / y` division in Python 3 and in Python 2.7 with + `from __future__ import division`. If you want integer division that rounds + down, use `x // y` or `tf.math.floordiv`. + + `x` and `y` must have the same numeric type. If the inputs are floating + point, the output will have the same type. If the inputs are integral, the + inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32` + and `int64` (matching the behavior of Numpy). + + Args: + x: `Tensor` numerator of numeric type. + y: `Tensor` denominator of numeric type. + name: A name for the operation (optional). + + Returns: + `x / y` evaluated in floating point. + + Raises: + TypeError: If `x` and `y` have different dtypes. + """ + return _truediv_python3(x, y, name) + + +@tf_export(v1=["div"]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, + instructions="Deprecated in favor of operator or tf.math.divide.") +def div(x, y, name=None): + """Divides x / y elementwise (using Python 2 division operator semantics). + + @compatibility(TF2) + This function is deprecated in TF2. Prefer using the Tensor division operator, + `tf.divide`, or `tf.math.divide`, which obey the Python 3 division operator + semantics. + @end_compatibility + + + This function divides `x` and `y`, forcing Python 2 semantics. That is, if `x` + and `y` are both integers then the result will be an integer. This is in + contrast to Python 3, where division with `/` is always a float while division + with `//` is always an integer. + + Args: + x: `Tensor` numerator of real numeric type. + y: `Tensor` denominator of real numeric type. + name: A name for the operation (optional). + + Returns: + `x / y` returns the quotient of x and y. + """ + return _div_python2(x, y, name) + + +@tf_export("math.divide_no_nan", v1=["math.divide_no_nan", "div_no_nan"]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("div_no_nan") +def div_no_nan(x, y, name=None): + """Computes a safe divide which returns 0 if `y` (denominator) is zero. + + For example: + + >>> tf.constant(3.0) / 0.0 + + >>> tf.math.divide_no_nan(3.0, 0.0) + + + Note that 0 is returned if `y` is 0 even if `x` is nonfinite: + + >>> tf.math.divide_no_nan(np.nan, 0.0) + + + Args: + x: A `Tensor` of a floating or integer dtype. + y: A `Tensor` with the same dtype as `x` and a compatible shape. + name: A name for the operation (optional). + + Returns: + The element-wise quotient as in `tf.math.divide(x, y)`, + except that division by zero produces `0.0`, not `nan`. + """ + + with ops.name_scope(name, "div_no_nan", [x, y]) as name: + if not tensor_util.is_tf_type(x) and tensor_util.is_tf_type(y): + # Treat this case specially like divide() does above. + y = ops.convert_to_tensor(y, name="y") + x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name="x") + else: + x = ops.convert_to_tensor(x, name="x") + y = ops.convert_to_tensor(y, dtype_hint=x.dtype.base_dtype, name="y") + x_dtype = x.dtype.base_dtype + y_dtype = y.dtype.base_dtype + if x_dtype != y_dtype: + raise TypeError(f"`x` and `y` must have the same dtype, " + f"got {x_dtype!r} != {y_dtype!r}.") + try: + dtype = _TRUEDIV_TABLE[x_dtype] + except KeyError as e: + raise TypeError( + f"Invalid dtype {x_dtype!r} in tf.math.divide_no_nan. Expected one " + f"of {{{', '.join([repr(x) for x in _TRUEDIV_TABLE.keys()])}}}." + ) from e + if dtype is not None: + x = cast(x, dtype) + y = cast(y, dtype) + return gen_math_ops.div_no_nan(x, y, name=name) + + +@tf_export("math.multiply_no_nan") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def multiply_no_nan(x, y, name=None): + """Computes the product of x and y and returns 0 if the y is zero, even if x is NaN or infinite. + + Note this is noncommutative: if y is NaN or infinite and x is 0, the result + will be NaN. + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`. + y: A `Tensor` whose dtype is compatible with `x`. + name: A name for the operation (optional). + + Returns: + The element-wise value of the x times y. + """ + + with ops.name_scope(name, "multiply_no_nan", [x, y]) as name: + x = ops.convert_to_tensor(x, name="x") + y = ops.convert_to_tensor(y, name="y", dtype=x.dtype.base_dtype) + x_dtype = x.dtype.base_dtype + y_dtype = y.dtype.base_dtype + if x_dtype != y_dtype: + raise TypeError(f"`x` and `y` must have the same dtype, " + f"got {x_dtype!r} != {y_dtype!r}") + return gen_math_ops.mul_no_nan(x, y, name=name) + + +def mod(x, y, name=None): + r"""Returns element-wise remainder of division. + + This follows Python semantics in that the + result here is consistent with a flooring divide. E.g. + `floor(x / y) * y + floormod(x, y) = x`, regardless of the signs of x and y. + + *NOTE*: `math.floormod` supports broadcasting. More about broadcasting + [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + + Args: + x: A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, + `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `bfloat16`, `half`, + `float32`, `float64`. + y: A `Tensor`. Must have the same type as `x`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + with ops.name_scope(name, "mod", [x, y]) as name: + return gen_math_ops.floor_mod(x, y, name=name) + + +@tf_export("math.floordiv", v1=["math.floordiv", "floordiv"]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("floordiv") +def floordiv(x, y, name=None): + """Divides `x / y` elementwise, rounding toward the most negative integer. + + Mathematically, this is equivalent to floor(x / y). For example: + floor(8.4 / 4.0) = floor(2.1) = 2.0 + floor(-8.4 / 4.0) = floor(-2.1) = -3.0 + This is equivalent to the '//' operator in Python 3.0 and above. + + Note: `x` and `y` must have the same type, and the result will have the same + type as well. + + Args: + x: `Tensor` numerator of real numeric type. + y: `Tensor` denominator of real numeric type. + name: A name for the operation (optional). + + Returns: + `x / y` rounded toward -infinity. + + Raises: + TypeError: If the inputs are complex. + """ + with ops.name_scope(name, "floordiv", [x, y]) as name: + return gen_math_ops.floor_div(x, y, name=name) + + +realdiv = gen_math_ops.real_div +truncatediv = gen_math_ops.truncate_div +floor_div = gen_math_ops.floor_div +truncatemod = gen_math_ops.truncate_mod +floormod = gen_math_ops.floor_mod + + +@tf_export("__operators__.add", v1=[]) +@dispatch.add_dispatch_support +def _add_dispatch(x, y, name=None): + """The operation invoked by the `Tensor.__add__` operator. + + Purpose in the API: + + This method is exposed in TensorFlow's API so that library developers + can register dispatching for `Tensor.__add__` to allow it to handle + custom composite tensors & other custom objects. + + The API symbol is not intended to be called by users directly and does + appear in TensorFlow's generated documentation. + + Args: + x: The left-hand side of the `+` operator. + y: The right-hand side of the `+` operator. + name: an optional name for the operation. + + Returns: + The result of the elementwise `+` operation. + """ + if ops.is_auto_dtype_conversion_enabled(): + return add(x, y, name=name) + if not isinstance(y, tensor_lib.Tensor) and not isinstance( + y, sparse_tensor.SparseTensor): + y = ops.convert_to_tensor(y, dtype_hint=x.dtype.base_dtype, name="y") + if x.dtype == dtypes.string: + return gen_math_ops.add(x, y, name=name) + else: + return gen_math_ops.add_v2(x, y, name=name) + + +def _mul_dispatch(x, y, name=None): + """Dispatches cwise mul for "Dense*Dense" and "Dense*Sparse".""" + if isinstance(y, sparse_tensor.SparseTensor): # Case: Dense * Sparse. + new_vals = gen_sparse_ops.sparse_dense_cwise_mul(y.indices, y.values, + y.dense_shape, x, name) + return sparse_tensor.SparseTensor(y.indices, new_vals, y.dense_shape) + else: + return multiply(x, y, name=name) + + +# NOTE(aselle): When integer division is added for sparse_dense_cwise, +# div, truediv, and floordiv should be delegated appropriately for +# Python semantics, analogous to dense cwise tensor operations. +_OverrideBinaryOperatorHelper(gen_sparse_ops.sparse_dense_cwise_div, "div", + sparse_tensor.SparseTensor) +_OverrideBinaryOperatorHelper(_sparse_dense_truediv, "truediv", + sparse_tensor.SparseTensor) +_OverrideBinaryOperatorHelper(gen_sparse_ops.sparse_dense_cwise_mul, "mul", + sparse_tensor.SparseTensor) + +_OverrideBinaryOperatorHelper(_add_dispatch, "add") +_OverrideBinaryOperatorHelper(subtract, "sub") +_OverrideBinaryOperatorHelper(_mul_dispatch, "mul") +_OverrideBinaryOperatorHelper(div, "div") +_OverrideBinaryOperatorHelper(truediv, "truediv") +_OverrideBinaryOperatorHelper(floordiv, "floordiv") +_OverrideBinaryOperatorHelper(mod, "mod") +_OverrideBinaryOperatorHelper(pow, "pow") + + +@tf_export("math.logical_xor", v1=["math.logical_xor", "logical_xor"]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("logical_xor") +def logical_xor(x, y, name="LogicalXor"): + """Logical XOR function. + + x ^ y = (x | y) & ~(x & y) + + Requires that `x` and `y` have the same shape or have + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shapes. For example, `x` and `y` can be: + + - Two single elements of type `bool` + - One `tf.Tensor` of type `bool` and one single `bool`, where the result will + be calculated by applying logical XOR with the single element to each + element in the larger Tensor. + - Two `tf.Tensor` objects of type `bool` of the same shape. In this case, + the result will be the element-wise logical XOR of the two input tensors. + + Usage: + + >>> a = tf.constant([True]) + >>> b = tf.constant([False]) + >>> tf.math.logical_xor(a, b) + + + >>> c = tf.constant([True]) + >>> x = tf.constant([False, True, True, False]) + >>> tf.math.logical_xor(c, x) + + + >>> y = tf.constant([False, False, True, True]) + >>> z = tf.constant([False, True, False, True]) + >>> tf.math.logical_xor(y, z) + + + Args: + x: A `tf.Tensor` type bool. + y: A `tf.Tensor` of type bool. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of type bool with the same size as that of x or y. + """ + # TODO(alemi) Make this a cwise op if people end up relying on it. + return gen_math_ops.logical_and( + gen_math_ops.logical_or(x, y), + gen_math_ops.logical_not(gen_math_ops.logical_and(x, y)), + name=name) + + +def and_(x, y, name=None): + if x.dtype == dtypes.bool: + return gen_math_ops.logical_and(x, y, name) + return gen_bitwise_ops.bitwise_and(x, y) + + +def or_(x, y, name=None): + if x.dtype == dtypes.bool: + return gen_math_ops.logical_or(x, y, name) + return gen_bitwise_ops.bitwise_or(x, y) + + +def xor_(x, y, name=None): + if x.dtype == dtypes.bool: + return logical_xor(x, y, name) + return gen_bitwise_ops.bitwise_xor(x, y) + + +def invert_(x, name=None): + if x.dtype == dtypes.bool: + return gen_math_ops.logical_not(x, name=name) + return gen_bitwise_ops.invert(x, name=name) + + +_OverrideBinaryOperatorHelper(and_, "and") +_OverrideBinaryOperatorHelper(or_, "or") +_OverrideBinaryOperatorHelper(xor_, "xor") +tensor_lib.Tensor._override_operator("__invert__", invert_) + + +def _promote_dtypes_decorator(fn): + def wrapper(x, y, *args, **kwargs): + x, y = maybe_promote_tensors(x, y) + return fn(x, y, *args, **kwargs) + return tf_decorator.make_decorator(fn, wrapper) + + +tensor_lib.Tensor._override_operator("__lt__", _promote_dtypes_decorator( + gen_math_ops.less)) +tensor_lib.Tensor._override_operator("__le__", _promote_dtypes_decorator( + gen_math_ops.less_equal)) +tensor_lib.Tensor._override_operator("__gt__", _promote_dtypes_decorator( + gen_math_ops.greater)) +tensor_lib.Tensor._override_operator("__ge__", _promote_dtypes_decorator( + gen_math_ops.greater_equal)) + + +@tf_export("math.equal", "equal") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def equal(x, y, name=None): + """Returns the truth value of (x == y) element-wise. + + Performs a [broadcast]( + https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) with the + arguments and then an element-wise equality comparison, returning a Tensor of + boolean values. + + For example: + + >>> x = tf.constant([2, 4]) + >>> y = tf.constant(2) + >>> tf.math.equal(x, y) + + + >>> x = tf.constant([2, 4]) + >>> y = tf.constant([2, 4]) + >>> tf.math.equal(x, y) + + + Args: + x: A `tf.Tensor`. + y: A `tf.Tensor`. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of type bool with the same size as that of x or y. + + Raises: + `tf.errors.InvalidArgumentError`: If shapes of arguments are incompatible + """ + return gen_math_ops.equal(x, y, name=name) + + +@tf_export("math.not_equal", "not_equal") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def not_equal(x, y, name=None): + """Returns the truth value of (x != y) element-wise. + + Performs a [broadcast]( + https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) with the + arguments and then an element-wise inequality comparison, returning a Tensor + of boolean values. + + For example: + + >>> x = tf.constant([2, 4]) + >>> y = tf.constant(2) + >>> tf.math.not_equal(x, y) + + + >>> x = tf.constant([2, 4]) + >>> y = tf.constant([2, 4]) + >>> tf.math.not_equal(x, y) + + + Args: + x: A `tf.Tensor`. + y: A `tf.Tensor`. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of type bool with the same size as that of x or y. + + Raises: + `tf.errors.InvalidArgumentError`: If shapes of arguments are incompatible + """ + return gen_math_ops.not_equal(x, y, name=name) + + +@tf_export("__operators__.eq", v1=[]) +@dispatch.add_dispatch_support +def tensor_equals(self, other): + """The operation invoked by the `Tensor.__eq__` operator. + + Compares two tensors element-wise for equality if they are + broadcast-compatible; or returns False if they are not broadcast-compatible. + (Note that this behavior differs from `tf.math.equal`, which raises an + exception if the two tensors are not broadcast-compatible.) + + Purpose in the API: + + This method is exposed in TensorFlow's API so that library developers + can register dispatching for `Tensor.__eq__` to allow it to handle + custom composite tensors & other custom objects. + + The API symbol is not intended to be called by users directly and does + appear in TensorFlow's generated documentation. + + Args: + self: The left-hand side of the `==` operator. + other: The right-hand side of the `==` operator. + + Returns: + The result of the elementwise `==` operation, or `False` if the arguments + are not broadcast-compatible. + """ + if other is None: + return False + g = getattr(self, "graph", None) + if ( + tensor_lib.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + and (g is None or g.building_function) + ): + self, other = maybe_promote_tensors(self, other) + return gen_math_ops.equal(self, other, incompatible_shape_error=False) + else: + # In legacy graph mode, tensor equality is object equality + return self is other + + +@tf_export("__operators__.ne", v1=[]) +@dispatch.add_dispatch_support +def tensor_not_equals(self, other): + """The operation invoked by the `Tensor.__ne__` operator. + + Compares two tensors element-wise for inequality if they are + broadcast-compatible; or returns True if they are not broadcast-compatible. + (Note that this behavior differs from `tf.math.not_equal`, which raises an + exception if the two tensors are not broadcast-compatible.) + + Purpose in the API: + + This method is exposed in TensorFlow's API so that library developers + can register dispatching for `Tensor.__ne__` to allow it to handle + custom composite tensors & other custom objects. + + The API symbol is not intended to be called by users directly and does + appear in TensorFlow's generated documentation. + + Args: + self: The left-hand side of the `!=` operator. + other: The right-hand side of the `!=` operator. + + Returns: + The result of the elementwise `!=` operation, or `True` if the arguments + are not broadcast-compatible. + """ + if other is None: + return True + if ( + tensor_lib.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + ): + self, other = maybe_promote_tensors(self, other) + return gen_math_ops.not_equal(self, other, incompatible_shape_error=False) + else: + # In legacy graph mode, tensor equality is object equality + return self is not other + + +tensor_lib.Tensor._override_operator("__eq__", tensor_equals) +tensor_lib.Tensor._override_operator("__ne__", tensor_not_equals) + + +@tf_export("range") +@dispatch.add_dispatch_support +def range(start, limit=None, delta=1, dtype=None, name="range"): # pylint: disable=redefined-builtin + """Creates a sequence of numbers. + + Creates a sequence of numbers that begins at `start` and extends by + increments of `delta` up to but not including `limit`. + + The dtype of the resulting tensor is inferred from the inputs unless + it is provided explicitly. + + Like the Python builtin `range`, `start` defaults to 0, so that + `range(n) = range(0, n)`. + + For example: + + >>> start = 3 + >>> limit = 18 + >>> delta = 3 + >>> tf.range(start, limit, delta) + + + >>> start = 3 + >>> limit = 1 + >>> delta = -0.5 + >>> tf.range(start, limit, delta) + + + >>> limit = 5 + >>> tf.range(limit) + + + Args: + start: A 0-D `Tensor` (scalar). Acts as first entry in the range if `limit` + is not None; otherwise, acts as range limit and first entry defaults to 0. + limit: A 0-D `Tensor` (scalar). Upper limit of sequence, exclusive. If None, + defaults to the value of `start` while the first entry of the range + defaults to 0. + delta: A 0-D `Tensor` (scalar). Number that increments `start`. Defaults to + 1. + dtype: The type of the elements of the resulting tensor. + name: A name for the operation. Defaults to "range". + + Returns: + An 1-D `Tensor` of type `dtype`. + + @compatibility(numpy) + Equivalent to np.arange + @end_compatibility + """ + if limit is None: + start, limit = 0, start + + with ops.name_scope(name, "Range", [start, limit, delta]) as name: + if not isinstance(start, tensor_lib.Tensor): + start = ops.convert_to_tensor(start, dtype=dtype, name="start") + if not isinstance(limit, tensor_lib.Tensor): + limit = ops.convert_to_tensor(limit, dtype=dtype, name="limit") + if not isinstance(delta, tensor_lib.Tensor): + delta = ops.convert_to_tensor(delta, dtype=dtype, name="delta") + + # infer dtype if not explicitly provided + if dtype is None: + dtype_hierarchy = [ + dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64 + ] + assert all(arg.dtype in dtype_hierarchy for arg in [start, limit, delta]) + inferred_dtype = max([arg.dtype for arg in [start, limit, delta]], + key=dtype_hierarchy.index) + else: + inferred_dtype = dtype + # Always try to perform a cast even when start/limit/delta are already + # tensors. This will resolve the case where start/limit/delta's original's + # dtype is different from provided dtype. + start = cast(start, inferred_dtype) + limit = cast(limit, inferred_dtype) + delta = cast(delta, inferred_dtype) + + return gen_math_ops._range(start, limit, delta, name=name) + + +def _range_tensor_conversion_function(value, dtype=None, name=None, + as_ref=False): + del as_ref + return range(value.start, value.stop, value.step, dtype=dtype, name=name) + + +tensor_conversion_registry.register_tensor_conversion_function( + builtins.range, _range_tensor_conversion_function) + + +# Reduction operations +def _ReductionDims(x, axis): # pylint: disable=invalid-name + """Returns range(0, rank(x)) if axis is None.""" + if axis is not None: + return axis + else: + try: + x_rank = x.shape.rank + except AttributeError: + x_rank = None + + # Fast path: avoid creating Rank and Range ops if ndims is known. + if x_rank: + return constant_op.constant(np.arange(x_rank, dtype=np.int32)) + else: + # Otherwise, we rely on Range and Rank to do the right thing at run-time. + return range(0, array_ops.rank(x)) + + +def _has_fully_defined_shape(tensor): + """Returns true if tensor has a fully defined shape.""" + return isinstance(tensor, ops.EagerTensor) or tensor.shape.is_fully_defined() + + +def _may_reduce_to_scalar(keepdims, axis, output): + """Set a reduction's output shape to be a scalar if we are certain.""" + if not _has_fully_defined_shape(output) and (not keepdims) and ( + axis is None): + output.set_shape(()) + return output + + +@tf_export(v1=["math.reduce_sum", "reduce_sum"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_sum_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes the sum of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.add` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> # x has a shape of (2, 3) (two rows and three columns): + >>> x = tf.constant([[1, 1, 1], [1, 1, 1]]) + >>> x.numpy() + array([[1, 1, 1], + [1, 1, 1]], dtype=int32) + >>> # sum all the elements + >>> # 1 + 1 + 1 + 1 + 1+ 1 = 6 + >>> tf.reduce_sum(x).numpy() + 6 + >>> # reduce along the first dimension + >>> # the result is [1, 1, 1] + [1, 1, 1] = [2, 2, 2] + >>> tf.reduce_sum(x, 0).numpy() + array([2, 2, 2], dtype=int32) + >>> # reduce along the second dimension + >>> # the result is [1, 1] + [1, 1] + [1, 1] = [3, 3] + >>> tf.reduce_sum(x, 1).numpy() + array([3, 3], dtype=int32) + >>> # keep the original dimensions + >>> tf.reduce_sum(x, 1, keepdims=True).numpy() + array([[3], + [3]], dtype=int32) + >>> # reduce along both dimensions + >>> # the result is 1 + 1 + 1 + 1 + 1 + 1 = 6 + >>> # or, equivalently, reduce along rows, then reduce the resultant array + >>> # [1, 1, 1] + [1, 1, 1] = [2, 2, 2] + >>> # 2 + 2 + 2 = 6 + >>> tf.reduce_sum(x, [0, 1]).numpy() + 6 + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor, of the same dtype as the input_tensor. + + @compatibility(numpy) + Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to + int64 while tensorflow returns the same dtype as the input. + @end_compatibility + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_sum(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_sum", "reduce_sum", v1=[]) +@dispatch.add_dispatch_support +def reduce_sum(input_tensor, axis=None, keepdims=False, name=None): + """Computes the sum of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.add` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> # x has a shape of (2, 3) (two rows and three columns): + >>> x = tf.constant([[1, 1, 1], [1, 1, 1]]) + >>> x.numpy() + array([[1, 1, 1], + [1, 1, 1]], dtype=int32) + >>> # sum all the elements + >>> # 1 + 1 + 1 + 1 + 1+ 1 = 6 + >>> tf.reduce_sum(x).numpy() + 6 + >>> # reduce along the first dimension + >>> # the result is [1, 1, 1] + [1, 1, 1] = [2, 2, 2] + >>> tf.reduce_sum(x, 0).numpy() + array([2, 2, 2], dtype=int32) + >>> # reduce along the second dimension + >>> # the result is [1, 1] + [1, 1] + [1, 1] = [3, 3] + >>> tf.reduce_sum(x, 1).numpy() + array([3, 3], dtype=int32) + >>> # keep the original dimensions + >>> tf.reduce_sum(x, 1, keepdims=True).numpy() + array([[3], + [3]], dtype=int32) + >>> # reduce along both dimensions + >>> # the result is 1 + 1 + 1 + 1 + 1 + 1 = 6 + >>> # or, equivalently, reduce along rows, then reduce the resultant array + >>> # [1, 1, 1] + [1, 1, 1] = [2, 2, 2] + >>> # 2 + 2 + 2 = 6 + >>> tf.reduce_sum(x, [0, 1]).numpy() + 6 + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor)]`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor, of the same dtype as the input_tensor. + + @compatibility(numpy) + Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to + int64 while tensorflow returns the same dtype as the input. + @end_compatibility + """ + + return reduce_sum_with_dims(input_tensor, axis, keepdims, name, + _ReductionDims(input_tensor, axis)) + + +def reduce_sum_with_dims(input_tensor, + axis=None, + keepdims=False, + name=None, + dims=None): + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops._sum(input_tensor, dims, keepdims, name=name)) + + +@tf_export("math.reduce_euclidean_norm") +@dispatch.add_dispatch_support +def reduce_euclidean_norm(input_tensor, axis=None, keepdims=False, name=None): + """Computes the Euclidean norm of elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + ```python + x = tf.constant([[1, 2, 3], [1, 1, 1]]) # x.dtype is tf.int32 + tf.math.reduce_euclidean_norm(x) # returns 4 as dtype is tf.int32 + y = tf.constant([[1, 2, 3], [1, 1, 1]], dtype = tf.float32) + tf.math.reduce_euclidean_norm(y) # returns 4.1231055 which is sqrt(17) + tf.math.reduce_euclidean_norm(y, 0) # [sqrt(2), sqrt(5), sqrt(10)] + tf.math.reduce_euclidean_norm(y, 1) # [sqrt(14), sqrt(3)] + tf.math.reduce_euclidean_norm(y, 1, keepdims=True) # [[sqrt(14)], [sqrt(3)]] + tf.math.reduce_euclidean_norm(y, [0, 1]) # sqrt(17) + ``` + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor, of the same dtype as the input_tensor. + """ + keepdims = bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops.euclidean_norm( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export(v1=["math.count_nonzero", "count_nonzero"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +@deprecation.deprecated_args( + None, "reduction_indices is deprecated, use axis instead", + "reduction_indices") +def count_nonzero(input_tensor=None, + axis=None, + keepdims=None, + dtype=dtypes.int64, + name=None, + reduction_indices=None, + keep_dims=None, + input=None): # pylint: disable=redefined-builtin + """Computes number of nonzero elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + entry in `axis`. If `keepdims` is true, the reduced dimensions + are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a + tensor with a single element is returned. + + **NOTE** Floating point comparison to zero is done by exact floating point + equality check. Small values are **not** rounded to zero for purposes of + the nonzero check. + + For example: + + ```python + x = tf.constant([[0, 1, 0], [1, 1, 0]]) + tf.math.count_nonzero(x) # 3 + tf.math.count_nonzero(x, 0) # [1, 2, 0] + tf.math.count_nonzero(x, 1) # [1, 2] + tf.math.count_nonzero(x, 1, keepdims=True) # [[1], [2]] + tf.math.count_nonzero(x, [0, 1]) # 3 + ``` + + **NOTE** Strings are compared against zero-length empty string `""`. Any + string with a size greater than zero is already considered as nonzero. + + For example: + ```python + x = tf.constant(["", "a", " ", "b", ""]) + tf.math.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings. + ``` + + Args: + input_tensor: The tensor to reduce. Should be of numeric type, `bool`, or + `string`. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + dtype: The output dtype; defaults to `tf.int64`. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + input: Overrides input_tensor. For compatibility. + + Returns: + The reduced tensor (number of nonzero values). + """ + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + input_tensor = deprecation.deprecated_argument_lookup("input", input, + "input_tensor", + input_tensor) + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + + return count_nonzero_v2(input_tensor, axis, keepdims, dtype, name) + + +@tf_export("math.count_nonzero", v1=[]) +@dispatch.add_dispatch_support +def count_nonzero_v2( + input, # pylint: disable=redefined-builtin + axis=None, + keepdims=None, + dtype=dtypes.int64, + name=None): + """Computes number of nonzero elements across dimensions of a tensor. + + Reduces `input` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + entry in `axis`. If `keepdims` is true, the reduced dimensions + are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a + tensor with a single element is returned. + + **NOTE** Floating point comparison to zero is done by exact floating point + equality check. Small values are **not** rounded to zero for purposes of + the nonzero check. + + For example: + + ```python + x = tf.constant([[0, 1, 0], [1, 1, 0]]) + tf.math.count_nonzero(x) # 3 + tf.math.count_nonzero(x, 0) # [1, 2, 0] + tf.math.count_nonzero(x, 1) # [1, 2] + tf.math.count_nonzero(x, 1, keepdims=True) # [[1], [2]] + tf.math.count_nonzero(x, [0, 1]) # 3 + ``` + + **NOTE** Strings are compared against zero-length empty string `""`. Any + string with a size greater than zero is already considered as nonzero. + + For example: + ```python + x = tf.constant(["", "a", " ", "b", ""]) + tf.math.count_nonzero(x) # 3, with "a", " ", and "b" as nonzero strings. + ``` + + Args: + input: The tensor to reduce. Should be of numeric type, `bool`, or `string`. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input), rank(input))`. + keepdims: If true, retains reduced dimensions with length 1. + dtype: The output dtype; defaults to `tf.int64`. + name: A name for the operation (optional). + + Returns: + The reduced tensor (number of nonzero values). + """ + if keepdims is None: + keepdims = False + with ops.name_scope(name, "count_nonzero", [input]): + input = ops.convert_to_tensor(input, name="input") + # if the input is already of type bool, then there is no need + # to compare to zero. + if input.dtype == dtypes.bool: + predicate = input + else: + # A scalar of 'zero' is enough as `not_equal` will broadcast. + zero = array_ops.zeros([], dtype=input.dtype) + predicate = gen_math_ops.not_equal(input, zero) + return cast( + reduce_sum( + # int64 reduction happens on GPU + cast(predicate, dtypes.int64), + axis=axis, + keepdims=keepdims, + ), + dtype=dtype, + ) + + +@tf_export(v1=["math.reduce_mean", "reduce_mean"]) +@dispatch.add_dispatch_support +def reduce_mean_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes the mean of elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis` by computing the + mean of elements across the dimensions in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a tensor with a single + element is returned. + + For example: + + >>> x = tf.constant([[1., 1.], [2., 2.]]) + >>> tf.reduce_mean(x) + + >>> tf.reduce_mean(x, 0) + + >>> tf.reduce_mean(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.mean + + Please note that `np.mean` has a `dtype` parameter that could be used to + specify the output type. By default this is `dtype=float64`. On the other + hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`, + for example: + + >>> x = tf.constant([1, 0, 1, 0]) + >>> tf.reduce_mean(x) + + >>> y = tf.constant([1., 0., 1., 0.]) + >>> tf.reduce_mean(y) + + + @end_compatibility + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_mean(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_mean", "reduce_mean", v1=[]) +@dispatch.add_dispatch_support +def reduce_mean(input_tensor, axis=None, keepdims=False, name=None): + """Computes the mean of elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis` by computing the + mean of elements across the dimensions in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a tensor with a single + element is returned. + + For example: + + >>> x = tf.constant([[1., 1.], [2., 2.]]) + >>> tf.reduce_mean(x) + + >>> tf.reduce_mean(x, 0) + + >>> tf.reduce_mean(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.mean + + Please note that `np.mean` has a `dtype` parameter that could be used to + specify the output type. By default this is `dtype=float64`. On the other + hand, `tf.reduce_mean` has an aggressive type inference from `input_tensor`, + for example: + + >>> x = tf.constant([1, 0, 1, 0]) + >>> tf.reduce_mean(x) + + >>> y = tf.constant([1., 0., 1., 0.]) + >>> tf.reduce_mean(y) + + + @end_compatibility + """ + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops.mean( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export("math.reduce_variance") +@dispatch.add_dispatch_support +def reduce_variance(input_tensor, axis=None, keepdims=False, name=None): + """Computes the variance of elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[1., 2.], [3., 4.]]) + >>> tf.math.reduce_variance(x) + + >>> tf.math.reduce_variance(x, 0) + + >>> tf.math.reduce_variance(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have real or complex type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name scope for the associated operations (optional). + + Returns: + The reduced tensor, of the same dtype as the input_tensor. Note, for + `complex64` or `complex128` input, the returned `Tensor` will be of type + `float32` or `float64`, respectively. + + @compatibility(numpy) + Equivalent to np.var + + Please note `np.var` has a `dtype` parameter that could be used to specify the + output type. By default this is `dtype=float64`. On the other hand, + `tf.math.reduce_variance` has aggressive type inference from `input_tensor`. + @end_compatibility + """ + name = name if name else "reduce_variance" + with ops.name_scope(name): + input_tensor = ops.convert_to_tensor(input_tensor) + means = reduce_mean(input_tensor, axis=axis, keepdims=True) + if means.dtype.is_integer: + raise TypeError(f"Input must be either real or complex. " + f"Received integer type {means.dtype}.") + diff = input_tensor - means + if diff.dtype.is_complex: + # For complex values we need to take the absolute value before squaring. + # This is achieved by multiplying with the conjugate. + real_dtype = diff.dtype.real_dtype + squared_deviations = gen_math_ops.real( + gen_math_ops.mul(gen_math_ops.conj(diff), diff), Tout=real_dtype) + else: + squared_deviations = gen_math_ops.square(diff) + return reduce_mean(squared_deviations, axis=axis, keepdims=keepdims) + + +@tf_export("math.reduce_std") +@dispatch.add_dispatch_support +def reduce_std(input_tensor, axis=None, keepdims=False, name=None): + """Computes the standard deviation of elements across dimensions of a tensor. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[1., 2.], [3., 4.]]) + >>> tf.math.reduce_std(x) + + >>> tf.math.reduce_std(x, 0) + + >>> tf.math.reduce_std(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have real or complex type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name scope for the associated operations (optional). + + Returns: + The reduced tensor, of the same dtype as the input_tensor. Note, for + `complex64` or `complex128` input, the returned `Tensor` will be of type + `float32` or `float64`, respectively. + + @compatibility(numpy) + Equivalent to np.std + + Please note `np.std` has a `dtype` parameter that could be used to specify the + output type. By default this is `dtype=float64`. On the other hand, + `tf.math.reduce_std` has aggressive type inference from `input_tensor`. + @end_compatibility + """ + name = name if name else "reduce_std" + with ops.name_scope(name): + input_tensor = ops.convert_to_tensor(input_tensor) + variance = reduce_variance(input_tensor, axis=axis, keepdims=keepdims) + return gen_math_ops.sqrt(variance) + + +@tf_export("math.reduce_prod", "reduce_prod", v1=[]) +@dispatch.add_dispatch_support +def reduce_prod(input_tensor, axis=None, keepdims=False, name=None): + """Computes `tf.math.multiply` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.multiply` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + entry in `axis`. If `keepdims` is true, the reduced dimensions + are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[1., 2.], [3., 4.]]) + >>> tf.math.reduce_prod(x) + + >>> tf.math.reduce_prod(x, 0) + + >>> tf.math.reduce_prod(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.prod + @end_compatibility + """ + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops.prod( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export(v1=["math.reduce_prod", "reduce_prod"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_prod_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes `tf.math.multiply` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.multiply` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[1., 2.], [3., 4.]]) + >>> tf.math.reduce_prod(x) + + >>> tf.math.reduce_prod(x, 0) + + >>> tf.math.reduce_prod(x, 1) + + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.prod + @end_compatibility + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_prod(input_tensor, axis, keepdims, name) + + +@tf_export(v1=["math.reduce_min", "reduce_min"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_min_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes the `tf.math.minimum` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.minimum` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + Usage example: + + >>> x = tf.constant([5, 1, 2, 4]) + >>> tf.reduce_min(x) + + >>> x = tf.constant([-5, -1, -2, -4]) + >>> tf.reduce_min(x) + + >>> x = tf.constant([4, float('nan')]) + >>> tf.reduce_min(x) + + >>> x = tf.constant([float('nan'), float('nan')]) + >>> tf.reduce_min(x) + + >>> x = tf.constant([float('-inf'), float('inf')]) + >>> tf.reduce_min(x) + + + See the numpy docs for `np.amin` and `np.nanmin` behavior. + + Args: + input_tensor: The tensor to reduce. Should have real numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_min(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_min", "reduce_min", v1=[]) +@dispatch.add_dispatch_support +def reduce_min(input_tensor, axis=None, keepdims=False, name=None): + """Computes the `tf.math.minimum` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.minimum` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> a = tf.constant([ + ... [[1, 2], [3, 4]], + ... [[1, 2], [3, 4]] + ... ]) + >>> tf.reduce_min(a) + + + Choosing a specific axis returns minimum element in the given axis: + + >>> b = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> tf.reduce_min(b, axis=0) + + >>> tf.reduce_min(b, axis=1) + + + Setting `keepdims` to `True` retains the dimension of `input_tensor`: + + >>> tf.reduce_min(a, keepdims=True) + + >>> tf.math.reduce_min(a, axis=0, keepdims=True) + + + Args: + input_tensor: The tensor to reduce. Should have real numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.min + @end_compatibility + """ + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops._min( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export(v1=["math.reduce_max", "reduce_max"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_max_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes `tf.math.maximum` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.maximum` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + Usage example: + + >>> x = tf.constant([5, 1, 2, 4]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([-5, -1, -2, -4]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([4, float('nan')]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([float('nan'), float('nan')]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([float('-inf'), float('inf')]) + >>> tf.reduce_max(x) + + + See the numpy docs for `np.amax` and `np.nanmax` behavior. + + Args: + input_tensor: The tensor to reduce. Should have real numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_max(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_max", "reduce_max", v1=[]) +@dispatch.add_dispatch_support +def reduce_max(input_tensor, axis=None, keepdims=False, name=None): + """Computes `tf.math.maximum` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.maximum` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + Usage example: + + >>> x = tf.constant([5, 1, 2, 4]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([-5, -1, -2, -4]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([4, float('nan')]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([float('nan'), float('nan')]) + >>> tf.reduce_max(x) + + >>> x = tf.constant([float('-inf'), float('inf')]) + >>> tf.reduce_max(x) + + + See the numpy docs for `np.amax` and `np.nanmax` behavior. + + Args: + input_tensor: The tensor to reduce. Should have real numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + """ + return reduce_max_with_dims(input_tensor, axis, keepdims, name, + _ReductionDims(input_tensor, axis)) + + +def reduce_max_with_dims(input_tensor, + axis=None, + keepdims=False, + name=None, + dims=None): + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops._max(input_tensor, dims, keepdims, name=name)) + + +@tf_export(v1=["math.reduce_all", "reduce_all"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_all_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes `tf.math.logical_and` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.logical_and` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[True, True], [False, False]]) + >>> tf.math.reduce_all(x) + + >>> tf.math.reduce_all(x, 0) + + >>> tf.math.reduce_all(x, 1) + + + Args: + input_tensor: The boolean tensor to reduce. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.all + @end_compatibility + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_all(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_all", "reduce_all", v1=[]) +@dispatch.add_dispatch_support +def reduce_all(input_tensor, axis=None, keepdims=False, name=None): + """Computes `tf.math.logical_and` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.logical_and` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[True, True], [False, False]]) + >>> tf.math.reduce_all(x) + + >>> tf.math.reduce_all(x, 0) + + >>> tf.math.reduce_all(x, 1) + + + Args: + input_tensor: The boolean tensor to reduce. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.all + @end_compatibility + """ + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops._all( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export(v1=["math.reduce_any", "reduce_any"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_any_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes `tf.math.logical_or` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.logical_or` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[True, True], [False, False]]) + >>> tf.reduce_any(x) + + >>> tf.reduce_any(x, 0) + + >>> tf.reduce_any(x, 1) + + + Args: + input_tensor: The boolean tensor to reduce. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.any + @end_compatibility + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_any(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_any", "reduce_any", v1=[]) +@dispatch.add_dispatch_support +def reduce_any(input_tensor, axis=None, keepdims=False, name=None): + """Computes `tf.math.logical_or` of elements across dimensions of a tensor. + + This is the reduction operation for the elementwise `tf.math.logical_or` op. + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` is None, all dimensions are reduced, and a + tensor with a single element is returned. + + For example: + + >>> x = tf.constant([[True, True], [False, False]]) + >>> tf.reduce_any(x) + + >>> tf.reduce_any(x, 0) + + >>> tf.reduce_any(x, 1) + + + Args: + input_tensor: The boolean tensor to reduce. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + + @compatibility(numpy) + Equivalent to np.any + @end_compatibility + """ + keepdims = False if keepdims is None else bool(keepdims) + return _may_reduce_to_scalar( + keepdims, axis, + gen_math_ops._any( + input_tensor, _ReductionDims(input_tensor, axis), keepdims, + name=name)) + + +@tf_export(v1=["math.reduce_logsumexp", "reduce_logsumexp"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +def reduce_logsumexp_v1(input_tensor, + axis=None, + keepdims=None, + name=None, + reduction_indices=None, + keep_dims=None): + """Computes log(sum(exp(elements across dimensions of a tensor))). + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a + tensor with a single element is returned. + + This function is more numerically stable than log(sum(exp(input))). It avoids + overflows caused by taking the exp of large inputs and underflows caused by + taking the log of small inputs. + + For example: + + ```python + x = tf.constant([[0., 0., 0.], [0., 0., 0.]]) + tf.reduce_logsumexp(x) # log(6) + tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)] + tf.reduce_logsumexp(x, 1) # [log(3), log(3)] + tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]] + tf.reduce_logsumexp(x, [0, 1]) # log(6) + ``` + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + reduction_indices: The old (deprecated) name for axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced tensor. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + return reduce_logsumexp(input_tensor, axis, keepdims, name) + + +@tf_export("math.reduce_logsumexp", "reduce_logsumexp", v1=[]) +@dispatch.add_dispatch_support +def reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): + """Computes log(sum(exp(elements across dimensions of a tensor))). + + Reduces `input_tensor` along the dimensions given in `axis`. + Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each + of the entries in `axis`, which must be unique. If `keepdims` is true, the + reduced dimensions are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a + tensor with a single element is returned. + + This function is more numerically stable than log(sum(exp(input))). It avoids + overflows caused by taking the exp of large inputs and underflows caused by + taking the log of small inputs. + + For example: + + ```python + x = tf.constant([[0., 0., 0.], [0., 0., 0.]]) + tf.reduce_logsumexp(x) # log(6) + tf.reduce_logsumexp(x, 0) # [log(2), log(2), log(2)] + tf.reduce_logsumexp(x, 1) # [log(3), log(3)] + tf.reduce_logsumexp(x, 1, keepdims=True) # [[log(3)], [log(3)]] + tf.reduce_logsumexp(x, [0, 1]) # log(6) + ``` + + Args: + input_tensor: The tensor to reduce. Should have numeric type. + axis: The dimensions to reduce. If `None` (the default), reduces all + dimensions. Must be in the range `[-rank(input_tensor), + rank(input_tensor))`. + keepdims: If true, retains reduced dimensions with length 1. + name: A name for the operation (optional). + + Returns: + The reduced tensor. + """ + with ops.name_scope(name, "ReduceLogSumExp", [input_tensor]) as name: + raw_max = reduce_max(input_tensor, axis=axis, keepdims=True) + my_max = array_ops.stop_gradient( + gen_math_ops.select( + gen_math_ops.is_finite(raw_max), raw_max, + gen_array_ops.zeros_like(raw_max))) + result = gen_math_ops.log( + reduce_sum( + exp(subtract(input_tensor, my_max)), + axis=axis, + keepdims=keepdims)) + if not keepdims: + my_max = array_ops.reshape(my_max, gen_array_ops.shape(result)) + result = add(result, my_max, name=name) + return _may_reduce_to_scalar(keepdims, axis, result) + + +@tf_export("linalg.trace", v1=["linalg.trace", "trace"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("trace") +def trace(x, name=None): + """Compute the trace of a tensor `x`. + + `trace(x)` returns the sum along the main diagonal of each inner-most matrix + in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output + is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where + + `output[i, j, k, ..., l] = trace(x[i, j, k, ..., l, :, :])` + + For example: + + ```python + x = tf.constant([[1, 2], [3, 4]]) + tf.linalg.trace(x) # 5 + + x = tf.constant([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + tf.linalg.trace(x) # 15 + + x = tf.constant([[[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], + [[-1, -2, -3], + [-4, -5, -6], + [-7, -8, -9]]]) + tf.linalg.trace(x) # [15, -15] + ``` + + Args: + x: tensor. + name: A name for the operation (optional). + + Returns: + The trace of input tensor. + """ + with ops.name_scope(name, "Trace", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return reduce_sum(array_ops.matrix_diag_part(x), [-1], name=name) + + +@tf_export("linalg.matmul", "matmul") +@dispatch.add_dispatch_support +def matmul(a, + b, + transpose_a=False, + transpose_b=False, + adjoint_a=False, + adjoint_b=False, + a_is_sparse=False, + b_is_sparse=False, + output_type=None, + name=None): + """Multiplies matrix `a` by matrix `b`, producing `a` * `b`. + + The inputs must, following any transpositions, be tensors of rank >= 2 + where the inner 2 dimensions specify valid matrix multiplication dimensions, + and any further outer dimensions specify matching batch size. + + Both matrices must be of the same type. The supported types are: + `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, + `complex64`, `complex128`. + + Either matrix can be transposed or adjointed (conjugated and transposed) on + the fly by setting one of the corresponding flag to `True`. These are `False` + by default. + + If one or both of the matrices contain a lot of zeros, a more efficient + multiplication algorithm can be used by setting the corresponding + `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. + This optimization is only available for plain matrices (rank-2 tensors) with + datatypes `bfloat16` or `float32`. + + A simple 2-D tensor matrix multiplication: + + >>> a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) + >>> a # 2-D tensor + + >>> b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) + >>> b # 2-D tensor + + >>> c = tf.matmul(a, b) + >>> c # `a` * `b` + + + A batch matrix multiplication with batch shape [2]: + + >>> a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3]) + >>> a # 3-D tensor + + >>> b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2]) + >>> b # 3-D tensor + + >>> c = tf.matmul(a, b) + >>> c # `a` * `b` + + + Since python >= 3.5 the @ operator is supported + (see [PEP 465](https://www.python.org/dev/peps/pep-0465/)). In TensorFlow, + it simply calls the `tf.matmul()` function, so the following lines are + equivalent: + + >>> d = a @ b @ [[10], [11]] + >>> d = tf.matmul(tf.matmul(a, b), [[10], [11]]) + + Args: + a: `tf.Tensor` of type `float16`, `float32`, `float64`, `int32`, + `complex64`, `complex128` and rank > 1. + b: `tf.Tensor` with same type and rank as `a`. + transpose_a: If `True`, `a` is transposed before multiplication. + transpose_b: If `True`, `b` is transposed before multiplication. + adjoint_a: If `True`, `a` is conjugated and transposed before + multiplication. + adjoint_b: If `True`, `b` is conjugated and transposed before + multiplication. + a_is_sparse: If `True`, `a` is treated as a sparse matrix. Notice, this + **does not support `tf.sparse.SparseTensor`**, it just makes optimizations + that assume most values in `a` are zero. + See `tf.sparse.sparse_dense_matmul` + for some support for `tf.sparse.SparseTensor` multiplication. + b_is_sparse: If `True`, `b` is treated as a sparse matrix. Notice, this + **does not support `tf.sparse.SparseTensor`**, it just makes optimizations + that assume most values in `b` are zero. + See `tf.sparse.sparse_dense_matmul` + for some support for `tf.sparse.SparseTensor` multiplication. + output_type: The output datatype if needed. Defaults to None in which case + the output_type is the same as input type. Currently only works when input + tensors are type (u)int8 and output_type can be int32. + name: Name for the operation (optional). + + Returns: + A `tf.Tensor` of the same type as `a` and `b` where each inner-most matrix + is the product of the corresponding matrices in `a` and `b`, e.g. if all + transpose or adjoint attributes are `False`: + + `output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j])`, + for all indices `i`, `j`. + + Note: This is matrix product, not element-wise product. + + + Raises: + ValueError: If `transpose_a` and `adjoint_a`, or `transpose_b` and + `adjoint_b` are both set to `True`. + TypeError: If output_type is specified but the types of `a`, `b` and + `output_type` is not (u)int8, (u)int8 and int32. + """ + + with ops.name_scope(name, "MatMul", [a, b]) as name: + if transpose_a and adjoint_a: + raise ValueError( + f"Only one of `transpose_a` and `adjoint_a` can be True. " + f"Received `transpose_a`={transpose_a}, " + f"`adjoint_a`={adjoint_a}.") + if transpose_b and adjoint_b: + raise ValueError( + f"Only one of `transpose_b` and `adjoint_b` can be True. " + f"Received `transpose_b`={transpose_b}, " + f"`adjoint_b`={adjoint_b}.") + + if context.executing_eagerly(): + if not isinstance(a, (ops.EagerTensor, _resource_variable_type)): + a = ops.convert_to_tensor(a, name="a") + if not isinstance(b, (ops.EagerTensor, _resource_variable_type)): + b = ops.convert_to_tensor(b, dtype_hint=a.dtype.base_dtype, name="b") + else: + a = ops.convert_to_tensor(a, name="a") + b = ops.convert_to_tensor(b, dtype_hint=a.dtype.base_dtype, name="b") + + # TODO(apassos) remove _shape_tuple here when it is not needed. + a_shape = a._shape_tuple() # pylint: disable=protected-access + b_shape = b._shape_tuple() # pylint: disable=protected-access + + output_may_have_non_empty_batch_shape = ( + (a_shape is None or len(a_shape) > 2) or + (b_shape is None or len(b_shape) > 2)) + + # TODO(b/178749687): remove this boolean and all related branches once the + # bridges are ready. + # batch_matmul_v3 is for when input type is different from output type. + use_batch_matmul_v3 = False + if output_type and (output_type != a.dtype or output_type != b.dtype): + use_batch_matmul_v3 = True + + if (not a_is_sparse and + not b_is_sparse) and output_may_have_non_empty_batch_shape: + # BatchMatmul does not support transpose, so we conjugate the matrix and + # use adjoint instead. Conj() is a noop for real matrices. + if transpose_a: + a = conj(a) + adjoint_a = True + if transpose_b: + b = conj(b) + adjoint_b = True + if use_batch_matmul_v3: + return gen_math_ops.batch_mat_mul_v3( + a, b, adj_x=adjoint_a, adj_y=adjoint_b, Tout=output_type, name=name) + else: + return gen_math_ops.batch_mat_mul_v2( + a, b, adj_x=adjoint_a, adj_y=adjoint_b, name=name) + + # Neither matmul nor sparse_matmul support adjoint, so we conjugate + # the matrix and use transpose instead. Conj() is a noop for real + # matrices. + if adjoint_a: + a = conj(a) + transpose_a = True + if adjoint_b: + b = conj(b) + transpose_b = True + + use_sparse_matmul = False + if a_is_sparse or b_is_sparse: + sparse_matmul_types = [dtypes.bfloat16, dtypes.float32] + use_sparse_matmul = ( + a.dtype in sparse_matmul_types and b.dtype in sparse_matmul_types) + if (((a.dtype == dtypes.bfloat16 and + b.dtype not in (dtypes.int8, dtypes.uint8)) or + (b.dtype == dtypes.bfloat16 and + a.dtype not in (dtypes.int8, dtypes.uint8))) and a.dtype != b.dtype): + # matmul currently doesn't handle mixed-precision inputs other than + # fp16 * int8 which is supported in BatchMatMulV3. + use_sparse_matmul = True + if use_sparse_matmul: + ret = sparse_matmul( + a, + b, + transpose_a=transpose_a, + transpose_b=transpose_b, + a_is_sparse=a_is_sparse, + b_is_sparse=b_is_sparse, + name=name) + # sparse_matmul always returns float32, even with + # bfloat16 inputs. This prevents us from configuring bfloat16 training. + # casting to bfloat16 also matches non-sparse matmul behavior better. + if a.dtype == dtypes.bfloat16 and b.dtype == dtypes.bfloat16: + ret = cast(ret, dtypes.bfloat16) + return ret + else: + if use_batch_matmul_v3: + adjoint_a = adjoint_a or transpose_a + adjoint_b = adjoint_b or transpose_b + return gen_math_ops.batch_mat_mul_v3( + a, b, adj_x=adjoint_a, adj_y=adjoint_b, Tout=output_type, name=name) + else: + return gen_math_ops.mat_mul( + a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) + + +@tf_export("linalg.matvec") +@dispatch.add_dispatch_support +def matvec(a, + b, + transpose_a=False, + adjoint_a=False, + a_is_sparse=False, + b_is_sparse=False, + name=None): + """Multiplies matrix `a` by vector `b`, producing `a` * `b`. + + The matrix `a` must, following any transpositions, be a tensor of rank >= 2, + with `shape(a)[-1] == shape(b)[-1]`, and `shape(a)[:-2]` able to broadcast + with `shape(b)[:-1]`. + + Both `a` and `b` must be of the same type. The supported types are: + `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128`. + + Matrix `a` can be transposed or adjointed (conjugated and transposed) on + the fly by setting one of the corresponding flag to `True`. These are `False` + by default. + + If one or both of the inputs contain a lot of zeros, a more efficient + multiplication algorithm can be used by setting the corresponding + `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. + This optimization is only available for plain matrices/vectors (rank-2/1 + tensors) with datatypes `bfloat16` or `float32`. + + For example: + + ```python + # 2-D tensor `a` + # [[1, 2, 3], + # [4, 5, 6]] + a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) + + # 1-D tensor `b` + # [7, 9, 11] + b = tf.constant([7, 9, 11], shape=[3]) + + # `a` * `b` + # [ 58, 64] + c = tf.linalg.matvec(a, b) + + + # 3-D tensor `a` + # [[[ 1, 2, 3], + # [ 4, 5, 6]], + # [[ 7, 8, 9], + # [10, 11, 12]]] + a = tf.constant(np.arange(1, 13, dtype=np.int32), + shape=[2, 2, 3]) + + # 2-D tensor `b` + # [[13, 14, 15], + # [16, 17, 18]] + b = tf.constant(np.arange(13, 19, dtype=np.int32), + shape=[2, 3]) + + # `a` * `b` + # [[ 86, 212], + # [410, 563]] + c = tf.linalg.matvec(a, b) + ``` + + Args: + a: `Tensor` of type `float16`, `float32`, `float64`, `int32`, `complex64`, + `complex128` and rank > 1. + b: `Tensor` with same type as `a` and compatible dimensions. + transpose_a: If `True`, `a` is transposed before multiplication. + adjoint_a: If `True`, `a` is conjugated and transposed before + multiplication. + a_is_sparse: If `True`, `a` is treated as a sparse matrix. + b_is_sparse: If `True`, `b` is treated as a sparse matrix. + name: Name for the operation (optional). + + Returns: + A `Tensor` of the same type as `a` and `b` where each inner-most vector is + the product of the corresponding matrices in `a` and vectors in `b`, e.g. if + all transpose or adjoint attributes are `False`: + + `output`[..., i] = sum_k (`a`[..., i, k] * `b`[..., k]), for all indices i. + + Note: This is matrix-vector product, not element-wise product. + + + Raises: + ValueError: If transpose_a and adjoint_a are both set to True. + """ + with ops.name_scope(name, "MatVec", [a, b]) as name: + output = matmul( + a, + array_ops.expand_dims(b, axis=-1), + transpose_a=transpose_a, + adjoint_a=adjoint_a, + a_is_sparse=a_is_sparse, + b_is_sparse=b_is_sparse) + return array_ops.squeeze(output, axis=-1) + + +# TODO(b/178650720): Also support numpy-style type promotion in freestanding TF +# functions (e.g. tf.add). +def matmul_wrapper(a, b, name=None): # pylint: disable=missing-function-docstring + if ops.is_numpy_style_type_promotion(): + return a._matmul(b) + return matmul(a, b, name=name) +matmul_wrapper.__doc__ = matmul.__doc__ +_OverrideBinaryOperatorHelper(matmul_wrapper, "matmul") + +sparse_matmul = deprecation.deprecated(None, "Use `tf.linalg.matmul` instead")( + gen_math_ops.sparse_mat_mul) +tf_export(v1=["sparse_matmul"])(sparse_matmul) +@dispatch.add_dispatch_support + + +def _as_indexed_slices(x, optimize=True): + """Convert 'x' to IndexedSlices. + + Convert a dense Tensor to a block-sparse IndexedSlices. + + Args: + x: Either a Tensor object, or an IndexedSlices object. + optimize: if true, attempt to optimize the conversion of 'x'. + + Returns: + An IndexedSlices object. + + Raises: + TypeError: If 'x' is not a Tensor or an IndexedSlices object. + """ + # TODO(touts): op_scope + if not isinstance(x, (tensor_lib.Tensor, indexed_slices.IndexedSlices)): + raise TypeError(f"Not a Tensor or IndexedSlices: {type(x)}.") + if isinstance(x, indexed_slices.IndexedSlices): + return x + x_shape = array_ops.shape_internal(x, optimize=optimize) + return indexed_slices.IndexedSlices(x, range(0, x_shape[0]), x_shape) + + +def _as_indexed_slices_list(inputs, optimize=True): + """Convert all elements of 'inputs' to IndexedSlices. + + Additionally, homogenize the types of all the indices to + either int32 or int64. + + Args: + inputs: List containing either Tensor or IndexedSlices objects. + optimize: if true, attempt to optimize the conversion of each input. + + Returns: + A list of IndexedSlices objects. + + Raises: + TypeError: If 'inputs' is not a list or a tuple. + """ + if not isinstance(inputs, (list, tuple)): + raise TypeError(f"Expected a list or tuple, not {type(inputs)}.") + outputs = [_as_indexed_slices(i, optimize=optimize) for i in inputs] + with_int32_index = [ + o.indices for o in outputs if o.indices.dtype == dtypes.int32 + ] + if not with_int32_index or len(with_int32_index) == len(outputs): + return outputs + casted_outputs = [] + for o in outputs: + if o.indices.dtype == dtypes.int32: + casted_outputs.append( + indexed_slices.IndexedSlices(o.values, cast(o.indices, dtypes.int64), + o.dense_shape)) + else: + casted_outputs.append(o) + return casted_outputs + + +@tf_export("math.add", "add") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def add(x, y, name=None): + """Returns x + y element-wise. + + Example usages below. + + Add a scalar and a list: + + >>> x = [1, 2, 3, 4, 5] + >>> y = 1 + >>> tf.add(x, y) + + + Note that binary `+` operator can be used instead: + + >>> x = tf.convert_to_tensor([1, 2, 3, 4, 5]) + >>> y = tf.convert_to_tensor(1) + >>> x + y + + + Add a tensor and a list of same shape: + + >>> x = [1, 2, 3, 4, 5] + >>> y = tf.constant([1, 2, 3, 4, 5]) + >>> tf.add(x, y) + + + **Warning**: If one of the inputs (`x` or `y`) is a tensor and the other is a + non-tensor, the non-tensor input will adopt (or get casted to) the data type + of the tensor input. This can potentially cause unwanted overflow or underflow + conversion. + + For example, + + >>> x = tf.constant([1, 2], dtype=tf.int8) + >>> y = [2**7 + 1, 2**7 + 2] + >>> tf.add(x, y) + + + When adding two input values of different shapes, `Add` follows NumPy + broadcasting rules. The two input array shapes are compared element-wise. + Starting with the trailing dimensions, the two dimensions either have to be + equal or one of them needs to be `1`. + + For example, + + >>> x = np.ones(6).reshape(1, 2, 1, 3) + >>> y = np.ones(6).reshape(2, 1, 3, 1) + >>> tf.add(x, y).shape.as_list() + [2, 2, 3, 3] + + Another example with two arrays of different dimension. + + >>> x = np.ones([1, 2, 1, 4]) + >>> y = np.ones([3, 4]) + >>> tf.add(x, y).shape.as_list() + [1, 2, 3, 4] + + The reduction version of this elementwise operation is `tf.math.reduce_sum` + + Args: + x: A `tf.Tensor`. Must be one of the following types: bfloat16, half, + float16, float32, float64, uint8, uint16, uint32, uint64, int8, int16, + int32, int64, complex64, complex128, string. + y: A `tf.Tensor`. Must have the same type as x. + name: A name for the operation (optional) + """ + with ops.name_scope(name, "Add", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + y = ops.convert_to_tensor(y, dtype_hint=x.dtype.base_dtype, name="y") + if x.dtype == dtypes.string: + return gen_math_ops.add(x, y, name=name) + else: + return gen_math_ops.add_v2(x, y, name=name) + + +@tf_export("math.add_n", "add_n") +@dispatch.add_dispatch_support(iterable_parameters=["inputs"]) +def add_n(inputs, name=None): + """Returns the element-wise sum of a list of tensors. + + All inputs in the list must have the same shape. This op does not + [broadcast](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html) + its inputs. If you need broadcasting, use `tf.math.add` (or the `+` operator) + instead. + + For example: + + >>> a = tf.constant([[3, 5], [4, 8]]) + >>> b = tf.constant([[1, 6], [2, 9]]) + >>> tf.math.add_n([a, b, a]).numpy() + array([[ 7, 16], + [10, 25]], dtype=int32) + + See Also: + + * `tf.reduce_sum(inputs, axis=0)` - This performs the same mathematical + operation, but `tf.add_n` may be more efficient because it sums the + tensors directly. `reduce_sum` on the other hand calls + `tf.convert_to_tensor` on the list of tensors, unnecessarily stacking them + into a single tensor before summing. + + Args: + inputs: A list of `tf.Tensor` or `tf.IndexedSlices` objects, each with the + same shape and type. `tf.IndexedSlices` objects will be converted into + dense tensors prior to adding. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of the same shape and type as the elements of `inputs`. + + Raises: + ValueError: If `inputs` don't all have same shape and dtype or the shape + cannot be inferred. + """ + if not inputs or not isinstance(inputs, collections_abc.Iterable): + raise ValueError("Inputs must be an iterable of at least one " + "Tensor/IndexedSlices with the same dtype and shape.") + inputs = indexed_slices.convert_n_to_tensor_or_indexed_slices(inputs) + if not all( + isinstance(x, (tensor_lib.Tensor, indexed_slices.IndexedSlices)) + for x in inputs): + raise ValueError("Inputs must be an iterable of at least one " + "Tensor/IndexedSlices with the same dtype and shape.") + + if len(inputs) == 1: + if isinstance(inputs[0], indexed_slices.IndexedSlices): + values = ops.convert_to_tensor(inputs[0]) + else: + values = inputs[0] + if name: + return array_ops.identity(values, name=name) + return values + return gen_math_ops.add_n(inputs, name=name) + + +@tf_export("math.accumulate_n", v1=["math.accumulate_n", "accumulate_n"]) +@dispatch.add_dispatch_support +@deprecation.deprecated(None, "Use `tf.math.add_n` Instead") +def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None): + """Returns the element-wise sum of a list of tensors. + + Optionally, pass `shape` and `tensor_dtype` for shape and type checking, + otherwise, these are inferred. + + For example: + + >>> a = tf.constant([[1, 2], [3, 4]]) + >>> b = tf.constant([[5, 0], [0, 6]]) + >>> tf.math.accumulate_n([a, b, a]).numpy() + array([[ 7, 4], + [ 6, 14]], dtype=int32) + + >>> # Explicitly pass shape and type + >>> tf.math.accumulate_n( + ... [a, b, a], shape=[2, 2], tensor_dtype=tf.int32).numpy() + array([[ 7, 4], + [ 6, 14]], dtype=int32) + + Note: The input must be a list or tuple. This function does not handle + `IndexedSlices` + + See Also: + + * `tf.reduce_sum(inputs, axis=0)` - This performe the same mathematical + operation, but `tf.add_n` may be more efficient because it sums the + tensors directly. `reduce_sum` on the other hand calls + `tf.convert_to_tensor` on the list of tensors, unncessairly stacking them + into a single tensor before summing. + * `tf.add_n` - This is another python wrapper for the same Op. It has + nearly identical functionality. + + Args: + inputs: A list of `Tensor` objects, each with same shape and type. + shape: Expected shape of elements of `inputs` (optional). Also controls the + output shape of this op, which may affect type inference in other ops. A + value of `None` means "infer the input shape from the shapes in `inputs`". + tensor_dtype: Expected data type of `inputs` (optional). A value of `None` + means "infer the input dtype from `inputs[0]`". + name: A name for the operation (optional). + + Returns: + A `Tensor` of same shape and type as the elements of `inputs`. + + Raises: + ValueError: If `inputs` don't all have same shape and dtype or the shape + cannot be inferred. + """ + + def _input_error(): + return ValueError("inputs must be a list of at least one Tensor with the " + "same dtype and shape") + + if not inputs or not isinstance(inputs, (list, tuple)): + raise _input_error() + inputs = indexed_slices.convert_n_to_tensor_or_indexed_slices(inputs) + if not all(isinstance(x, tensor_lib.Tensor) for x in inputs): + raise _input_error() + if not all(x.dtype == inputs[0].dtype for x in inputs): + raise _input_error() + if shape is not None: + shape = tensor_shape.as_shape(shape) + else: + shape = tensor_shape.unknown_shape() + for input_tensor in inputs: + if isinstance(input_tensor, tensor_lib.Tensor): + shape = shape.merge_with(input_tensor.get_shape()) + + # tensor_dtype is for safety only; operator's output type computed in C++ + if tensor_dtype is not None and tensor_dtype != inputs[0].dtype: + raise TypeError( + f"The `tensor_dtype` argument is {tensor_dtype}, but `input` is of " + f"type {inputs[0].dtype}. These must be equal. Try casting the input " + f"to the desired type.") + + if len(inputs) == 1 and name is None: + return inputs[0] + elif len(inputs) == 1 and name is not None: + return array_ops.identity(inputs[0], name=name) + return add_n(inputs, name=name) + + +@ops.RegisterGradient("AccumulateNV2") +def _accumulate_n_grad(op, grad): + """Same as gradient for AddN. Copies the gradient to all inputs.""" + # Not broadcasting. + return [grad] * len(op.inputs) + + +@tf_export("math.sigmoid", "nn.sigmoid", "sigmoid") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def sigmoid(x, name=None): + r"""Computes sigmoid of `x` element-wise. + + Formula for calculating $\mathrm{sigmoid}(x) = y = 1 / (1 + \exp(-x))$. + + For $x \in (-\infty, \infty)$, $\mathrm{sigmoid}(x) \in (0, 1)$. + + Example Usage: + + If a positive number is large, then its sigmoid will approach to 1 since the + formula will be `y = / (1 + )` + + >>> x = tf.constant([0.0, 1.0, 50.0, 100.0]) + >>> tf.math.sigmoid(x) + + + If a negative number is large, its sigmoid will approach to 0 since the + formula will be `y = 1 / (1 + )` + + >>> x = tf.constant([-100.0, -50.0, -1.0, 0.0]) + >>> tf.math.sigmoid(x) + + + Args: + x: A Tensor with type `float16`, `float32`, `float64`, `complex64`, or + `complex128`. + name: A name for the operation (optional). + + Returns: + A Tensor with the same type as `x`. + + Usage Example: + + >>> x = tf.constant([-128.0, 0.0, 128.0], dtype=tf.float32) + >>> tf.sigmoid(x) + + + @compatibility(scipy) + Equivalent to scipy.special.expit + @end_compatibility + """ + with ops.name_scope(name, "Sigmoid", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return gen_math_ops.sigmoid(x, name=name) + + +@tf_export("math.log_sigmoid", v1=["math.log_sigmoid", "log_sigmoid"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("log_sigmoid") +def log_sigmoid(x, name=None): + """Computes log sigmoid of `x` element-wise. + + Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability, + we use `y = -tf.nn.softplus(-x)`. + + Args: + x: A Tensor with type `float32` or `float64`. + name: A name for the operation (optional). + + Returns: + A Tensor with the same type as `x`. + + Usage Example: + + If a positive number is large, then its log_sigmoid will approach to 0 since + the formula will be `y = log( / (1 + ) )` which + approximates to `log (1)` which is 0. + + >>> x = tf.constant([0.0, 1.0, 50.0, 100.0]) + >>> tf.math.log_sigmoid(x) + + + If a negative number is large, its log_sigmoid will approach to the number + itself since the formula will be `y = log( 1 / (1 + ) )` which is + `log (1) - log ( (1 + ) )` which approximates to `- ` + that is the number itself. + + >>> x = tf.constant([-100.0, -50.0, -1.0, 0.0]) + >>> tf.math.log_sigmoid(x) + + """ + with ops.name_scope(name, "LogSigmoid", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return gen_math_ops.neg(gen_nn_ops.softplus(-x), name=name) # pylint: disable=invalid-unary-operand-type + + +@tf_export("math.cumsum", "cumsum") +@dispatch.add_dispatch_support +def cumsum(x, axis=0, exclusive=False, reverse=False, name=None): + """Compute the cumulative sum of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumsum, which means that the first + element of the input is identical to the first element of the output: + For example: + + >>> # tf.cumsum([a, b, c]) # [a, a + b, a + b + c] + >>> x = tf.constant([2, 4, 6, 8]) + >>> tf.cumsum(x) + + + >>> # using varying `axis` values + >>> y = tf.constant([[2, 4, 6, 8], [1,3,5,7]]) + >>> tf.cumsum(y, axis=0) + + >>> tf.cumsum(y, axis=1) + + + By setting the `exclusive` kwarg to `True`, an exclusive cumsum is performed + instead: + + >>> # tf.cumsum([a, b, c], exclusive=True) => [0, a, a + b] + >>> x = tf.constant([2, 4, 6, 8]) + >>> tf.cumsum(x, exclusive=True) + + + By setting the `reverse` kwarg to `True`, the cumsum is performed in the + opposite direction: + + >>> # tf.cumsum([a, b, c], reverse=True) # [a + b + c, b + c, c] + >>> x = tf.constant([2, 4, 6, 8]) + >>> tf.cumsum(x, reverse=True) + + + This is more efficient than using separate `tf.reverse` ops. + The `reverse` and `exclusive` kwargs can also be combined: + + >>> # tf.cumsum([a, b, c], exclusive=True, reverse=True) # [b + c, c, 0] + >>> x = tf.constant([2, 4, 6, 8]) + >>> tf.cumsum(x, exclusive=True, reverse=True) + + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, + `complex128`, `qint8`, `quint8`, `qint32`, `half`. + axis: A `Tensor` of type `int32` (default: 0). Must be in the range + `[-rank(x), rank(x))`. + exclusive: If `True`, perform exclusive cumsum. + reverse: A `bool` (default: False). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + with ops.name_scope(name, "Cumsum", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return gen_math_ops.cumsum( + x, axis, exclusive=exclusive, reverse=reverse, name=name) + + +@tf_export("math.cumprod", v1=["math.cumprod", "cumprod"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("cumprod") +def cumprod(x, axis=0, exclusive=False, reverse=False, name=None): + """Compute the cumulative product of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumprod, which means that the + first element of the input is identical to the first element of the output: + + ```python + tf.math.cumprod([a, b, c]) # [a, a * b, a * b * c] + ``` + + By setting the `exclusive` kwarg to `True`, an exclusive cumprod is + performed + instead: + + ```python + tf.math.cumprod([a, b, c], exclusive=True) # [1, a, a * b] + ``` + + By setting the `reverse` kwarg to `True`, the cumprod is performed in the + opposite direction: + + ```python + tf.math.cumprod([a, b, c], reverse=True) # [a * b * c, b * c, c] + ``` + + This is more efficient than using separate `tf.reverse` ops. + The `reverse` and `exclusive` kwargs can also be combined: + + ```python + tf.math.cumprod([a, b, c], exclusive=True, reverse=True) # [b * c, c, 1] + ``` + + Args: + x: A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, + `complex128`, `qint8`, `quint8`, `qint32`, `half`. + axis: A `Tensor` of type `int32` (default: 0). Must be in the range + `[-rank(x), rank(x))`. + exclusive: If `True`, perform exclusive cumprod. + reverse: A `bool` (default: False). + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `x`. + """ + with ops.name_scope(name, "Cumprod", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return gen_math_ops.cumprod( + x, axis, exclusive=exclusive, reverse=reverse, name=name) + + +@tf_export("math.cumulative_logsumexp", v1=["math.cumulative_logsumexp"]) +@dispatch.add_dispatch_support +def cumulative_logsumexp(x, axis=0, exclusive=False, reverse=False, name=None): + """Compute the cumulative log-sum-exp of the tensor `x` along `axis`. + + By default, this op performs an inclusive cumulative log-sum-exp, which means + that the first element of the input is identical to the first element of + the output. + + This operation is significantly more numerically stable than the equivalent + tensorflow operation `tf.math.log(tf.math.cumsum(tf.math.exp(x)))`, although + computes the same result given infinite numerical precision. However, note + that in some cases, it may be less stable than `tf.math.reduce_logsumexp` + for a given element, as it applies the "log-sum-exp trick" in a different + way. + + More precisely, where `tf.math.reduce_logsumexp` uses the following trick: + + ``` + log(sum(exp(x))) == log(sum(exp(x - max(x)))) + max(x) + ``` + + it cannot be directly used here as there is no fast way of applying it + to each prefix `x[:i]`. Instead, this function implements a prefix + scan using pairwise log-add-exp, which is a commutative and associative + (up to floating point precision) operator: + + ``` + log_add_exp(x, y) = log(exp(x) + exp(y)) + = log(1 + exp(min(x, y) - max(x, y))) + max(x, y) + ``` + + However, reducing using the above operator leads to a different computation + tree (logs are taken repeatedly instead of only at the end), and the maximum + is only computed pairwise instead of over the entire prefix. In general, this + leads to a different and slightly less precise computation. + + Args: + x: A `Tensor`. Must be one of the following types: `float16`, `float32`, + `float64`. + axis: A `Tensor` of type `int32` or `int64` (default: 0). Must be in the + range `[-rank(x), rank(x))`. + exclusive: If `True`, perform exclusive cumulative log-sum-exp. + reverse: If `True`, performs the cumulative log-sum-exp in the reverse + direction. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same shape and type as `x`. + """ + with ops.name_scope(name, "CumulativeLogsumexp", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + return gen_math_ops.cumulative_logsumexp( + x, axis, exclusive=exclusive, reverse=reverse, name=name) + + +@tf_export("math.conj", v1=["math.conj", "conj"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("conj") +def conj(x, name=None): + r"""Returns the complex conjugate of a complex number. + + Given a tensor `x` of complex numbers, this operation returns a tensor of + complex numbers that are the complex conjugate of each element in `x`. The + complex numbers in `x` must be of the form \\(a + bj\\), where `a` is the + real part and `b` is the imaginary part. + + The complex conjugate returned by this operation is of the form \\(a - bj\\). + + For example: + + >>> x = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j]) + >>> tf.math.conj(x) + + + If `x` is real, it is returned unchanged. + + For example: + + >>> x = tf.constant([-2.25, 3.25]) + >>> tf.math.conj(x) + + + Args: + x: `Tensor` to conjugate. Must have numeric or variant type. + name: A name for the operation (optional). + + Returns: + A `Tensor` that is the conjugate of `x` (with the same type). + + Raises: + TypeError: If `x` is not a numeric tensor. + + @compatibility(numpy) + Equivalent to numpy.conj. + @end_compatibility + """ + if isinstance(x, tensor_lib.Tensor): + dt = x.dtype + if dt.is_floating or dt.is_integer: + return x + with ops.name_scope(name, "Conj", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_complex or x.dtype == dtypes.variant: + return gen_math_ops.conj(x, name=name) + elif x.dtype.is_floating or x.dtype.is_integer: + return x + else: + raise TypeError( + f"Expected numeric or variant tensor, got dtype {x.dtype!r}.") + + +def reduced_shape(input_shape, axes): + """Helper function for reduction ops. + + Args: + input_shape: 1-D Tensor, the shape of the Tensor being reduced. + axes: 1-D Tensor, the reduction axes. + + Returns: + A 1-D Tensor, the output shape as if keepdims were set to True. + """ + # TODO(allenl): Refactor `reduced_shape` to take the tensor corresponding to + # `input_shape` rather than `tf.shape` of it. Then we can check if the shape + # is fully defined here, which may be faster executing eagerly than running + # `tf.shape` and then fetching its constant value. + constant_input_shape = tensor_util.constant_value(input_shape) + if constant_input_shape is not None: + constant_axes = tensor_util.constant_value(axes) + if constant_axes is not None: + constant_axes = np.array(constant_axes, dtype=np.int32) + constant_input_shape = np.array(constant_input_shape, dtype=np.int32) + constant_input_shape[constant_axes] = 1 + return constant_input_shape + + # Example: + # cast needed for SparseTensor reductions + input_shape = cast(input_shape, dtypes.int32) # [2, 3, 5, 7] + axes = cast(axes, dtypes.int32) # [1, 2] + + input_rank = array_ops.size(input_shape) # 4 + axes = (axes + input_rank) % input_rank + axes_shape = array_ops.shape(axes) # [2] + return gen_data_flow_ops.dynamic_stitch( # [2, 1, 1, 7] + [ + range(input_rank), # [0, 1, 2, 3] + axes + ], # [1, 2] + [ + input_shape, # [2, 3, 5, 7] + array_ops.ones(axes_shape, dtype=dtypes.int32) + ]) # [1, 1] + + +def _unsorted_segment_N(data, segment_ids, num_segments): + """ Helper function for unsorted_segment_mean/_sqrtN. + + Computes the number + of segment entries with 0-entries set to 1 to allow division by N. + """ + num_segments = ops.convert_to_tensor(num_segments) + # bincount doesn't support negative indices so we use unsorted_segment_sum + segment_ids_shape = array_ops.shape_internal(segment_ids) + ones_tensor = array_ops.ones(segment_ids_shape, dtype=data.dtype) + n = gen_math_ops.unsorted_segment_sum(ones_tensor, segment_ids, num_segments) + # add dimensions for all non-reduced axes + broadcastable_shape = array_ops.concat( + [num_segments[array_ops.newaxis], + array_ops.ones([array_ops.rank(data) + - array_ops.rank(segment_ids)], + dtype=num_segments.dtype)], + axis=0) + n = array_ops.reshape(n, broadcastable_shape) + return gen_math_ops.maximum(n, 1) + + +@tf_export( + "math.unsorted_segment_mean", + v1=["math.unsorted_segment_mean", "unsorted_segment_mean"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("unsorted_segment_mean") +def unsorted_segment_mean(data, segment_ids, num_segments, name=None): + r"""Computes the mean along segments of a tensor. + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + This operator is similar to the `tf.math.unsorted_segment_sum` operator. + Instead of computing the sum over segments, it computes the mean of all + entries belonging to a segment such that: + + \\(output_i = 1/N_i \sum_{j...} data[j...]\\) where the sum is over tuples + `j...` such that `segment_ids[j...] == i` with \\N_i\\ being the number of + occurrences of id \\i\\. + + If there is no entry for a given segment ID `i`, it outputs 0. + + If the given segment ID `i` is negative, the value is dropped and will not + be added to the sum of the segment. + + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + + Args: + data: A `Tensor` with floating point or complex dtype. + segment_ids: An integer tensor whose shape is a prefix of `data.shape`. + The values must be less than `num_segments`. + The values are always validated to be in range on CPU, + never validated on GPU. + num_segments: An integer scalar `Tensor`. The number of distinct segment + IDs. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has same shape as data, except for the first `segment_ids.rank` + dimensions, which are replaced with a single dimension which has size + `num_segments`. + """ + with ops.name_scope(name, "UnsortedSegmentMean"): + data = ops.convert_to_tensor(data) + segment_ids = ops.convert_to_tensor(segment_ids) + N = _unsorted_segment_N(data, segment_ids, num_segments) + summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments) + return summed / N + + +@tf_export( + "math.unsorted_segment_sqrt_n", + v1=["math.unsorted_segment_sqrt_n", "unsorted_segment_sqrt_n"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("unsorted_segment_sqrt_n") +def unsorted_segment_sqrt_n(data, segment_ids, num_segments, name=None): + r"""Computes the sum along segments of a tensor divided by the sqrt(N). + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + This operator is similar to the `tf.math.unsorted_segment_sum` operator. + Additionally to computing the sum over segments, it divides the results by + sqrt(N). + + \\(output_i = 1/sqrt(N_i) \sum_{j...} data[j...]\\) where the sum is over + tuples `j...` such that `segment_ids[j...] == i` with \\N_i\\ being the + number of occurrences of id \\i\\. + + If there is no entry for a given segment ID `i`, it outputs 0. + + Note that this op only supports floating point and complex dtypes, + due to tf.sqrt only supporting these types. + + If the given segment ID `i` is negative, the value is dropped and will not + be added to the sum of the segment. + + Caution: On CPU, values in `segment_ids` are always validated to be less than + `num_segments`, and an error is thrown for out-of-bound indices. On GPU, this + does not throw an error for out-of-bound indices. On Gpu, out-of-bound indices + result in safe but unspecified behavior, which may include ignoring + out-of-bound indices or outputting a tensor with a 0 stored in the first + dimension of its shape if `num_segments` is 0. + + Args: + data: A `Tensor` with floating point or complex dtype. + segment_ids: An integer tensor whose shape is a prefix of `data.shape`. + The values must be in the range `[0, num_segments)`. + The values are always validated to be in range on CPU, + never validated on GPU. + num_segments: An integer scalar `Tensor`. The number of distinct segment + IDs. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has same shape as data, except for the first `segment_ids.rank` + dimensions, which are replaced with a single dimension which has size + `num_segments`. + """ + with ops.name_scope(name, "UnsortedSegmentSqrtN"): + data = ops.convert_to_tensor(data) + segment_ids = ops.convert_to_tensor(segment_ids) + N = _unsorted_segment_N(data, segment_ids, num_segments) + summed = gen_math_ops.unsorted_segment_sum(data, segment_ids, num_segments) + return summed / gen_math_ops.sqrt(N) + + +@tf_export(v1=["sparse.segment_sum", "sparse_segment_sum"]) +@deprecation.deprecated_endpoints("sparse_segment_sum") +def sparse_segment_sum( + data, + indices, + segment_ids, + name=None, + num_segments=None, + sparse_gradient=False, +): + r"""Computes the sum along sparse segments of a tensor. + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + Like `tf.math.segment_sum`, but `segment_ids` can have rank less than `data`'s + first dimension, selecting a subset of dimension 0, specified by `indices`. + `segment_ids` is allowed to have missing ids, in which case the output will + be zeros at those indices. In those cases `num_segments` is used to determine + the size of the output. + + For example: + + ```python + c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) + + # Select two rows, one segment. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) + # => [[0 0 0 0]] + + # Select two rows, two segment. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) + # => [[ 1 2 3 4] + # [-1 -2 -3 -4]] + + # With missing segment ids. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]), + num_segments=4) + # => [[ 1 2 3 4] + # [ 0 0 0 0] + # [-1 -2 -3 -4] + # [ 0 0 0 0]] + + # Select all rows, two segments. + tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) + # => [[0 0 0 0] + # [5 6 7 8]] + + # Which is equivalent to: + tf.math.segment_sum(c, tf.constant([0, 0, 1])) + ``` + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + name: A name for the operation (optional). + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (`IndexedSlices`) instead of + dense (`Tensor`). The sparse gradient will contain one non-zero row for + each unique index in `indices`. + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + if num_segments is not None: + return gen_math_ops.sparse_segment_sum_with_num_segments( + data=data, + indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + name=name, + ) + else: + return gen_math_ops.sparse_segment_sum( + data=data, + indices=indices, + segment_ids=segment_ids, + sparse_gradient=sparse_gradient, + name=name, + ) + + +@tf_export("sparse.segment_sum", v1=[]) +def sparse_segment_sum_v2( + data, + indices, + segment_ids, + num_segments=None, + name=None, + sparse_gradient=False, +): + r"""Computes the sum along sparse segments of a tensor. + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + Like `tf.math.segment_sum`, but `segment_ids` can have rank less than `data`'s + first dimension, selecting a subset of dimension 0, specified by `indices`. + `segment_ids` is allowed to have missing ids, in which case the output will + be zeros at those indices. In those cases `num_segments` is used to determine + the size of the output. + + For example: + + ```python + c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) + + # Select two rows, one segment. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) + # => [[0 0 0 0]] + + # Select two rows, two segment. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) + # => [[ 1 2 3 4] + # [-1 -2 -3 -4]] + + # With missing segment ids. + tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]), + num_segments=4) + # => [[ 1 2 3 4] + # [ 0 0 0 0] + # [-1 -2 -3 -4] + # [ 0 0 0 0]] + + # Select all rows, two segments. + tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) + # => [[0 0 0 0] + # [5 6 7 8]] + + # Which is equivalent to: + tf.math.segment_sum(c, tf.constant([0, 0, 1])) + ``` + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + name: A name for the operation (optional). + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (`IndexedSlices`) instead of + dense (`Tensor`). The sparse gradient will contain one non-zero row for + each unique index in `indices`. + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + return sparse_segment_sum( + data, + indices, + segment_ids, + name=name, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + ) + + +@tf_export(v1=["sparse.segment_mean", "sparse_segment_mean"]) +@deprecation.deprecated_endpoints("sparse_segment_mean") +def sparse_segment_mean( + data, + indices, + segment_ids, + name=None, + num_segments=None, + sparse_gradient=False, +): + r"""Computes the mean along sparse segments of a tensor. + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + Like `tf.math.segment_mean`, but `segment_ids` can have rank less than + `data`'s first dimension, selecting a subset of dimension 0, specified by + `indices`. + `segment_ids` is allowed to have missing ids, in which case the output will + be zeros at those indices. In those cases `num_segments` is used to determine + the size of the output. + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + name: A name for the operation (optional). + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (`IndexedSlices`) instead of + dense (`Tensor`). The sparse gradient will contain one non-zero row for + each unique index in `indices`. + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + if num_segments is not None: + return gen_math_ops.sparse_segment_mean_with_num_segments( + data=data, + indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + name=name, + sparse_gradient=sparse_gradient, + ) + else: + return gen_math_ops.sparse_segment_mean( + data=data, + indices=indices, + segment_ids=segment_ids, + name=name, + sparse_gradient=sparse_gradient, + ) + + +@tf_export("sparse.segment_mean", v1=[]) +def sparse_segment_mean_v2( + data, + indices, + segment_ids, + num_segments=None, + name=None, + sparse_gradient=False, +): + r"""Computes the mean along sparse segments of a tensor. + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + Like `tf.math.segment_mean`, but `segment_ids` can have rank less than + `data`'s first dimension, selecting a subset of dimension 0, specified by + `indices`. + `segment_ids` is allowed to have missing ids, in which case the output will + be zeros at those indices. In those cases `num_segments` is used to determine + the size of the output. + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + name: A name for the operation (optional). + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (`IndexedSlices`) instead of + dense (`Tensor`). The sparse gradient will contain one non-zero row for + each unique index in `indices`. + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + return sparse_segment_mean( + data, + indices, + segment_ids, + name=name, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + ) + + +@tf_export(v1=["sparse.segment_sqrt_n", "sparse_segment_sqrt_n"]) +@deprecation.deprecated_endpoints("sparse_segment_sqrt_n") +def sparse_segment_sqrt_n( + data, + indices, + segment_ids, + name=None, + num_segments=None, + sparse_gradient=False, +): + r"""Computes the sum along sparse segments of a tensor divided by the sqrt(N). + + `N` is the size of the segment being reduced. + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + name: A name for the operation (optional). + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (IndexedSlices) instead of dense + (Tensor). + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + if num_segments is not None: + return gen_math_ops.sparse_segment_sqrt_n_with_num_segments( + data=data, + indices=indices, + segment_ids=segment_ids, + num_segments=num_segments, + name=name, + sparse_gradient=sparse_gradient, + ) + else: + return gen_math_ops.sparse_segment_sqrt_n( + data=data, + indices=indices, + segment_ids=segment_ids, + name=name, + sparse_gradient=sparse_gradient, + ) + + +@tf_export("sparse.segment_sqrt_n", v1=[]) +def sparse_segment_sqrt_n_v2( + data, + indices, + segment_ids, + num_segments=None, + name=None, + sparse_gradient=False, +): + r"""Computes the sum along sparse segments of a tensor divided by the sqrt(N). + + Read [the section on + segmentation](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/math#about_segmentation) + for an explanation of segments. + + Like `tf.sparse.segment_mean`, but instead of dividing by the size of the + segment, `N`, divide by `sqrt(N)` instead. + + Args: + data: A `Tensor` with data that will be assembled in the output. + indices: A 1-D `Tensor` with indices into `data`. Has same rank as + `segment_ids`. + segment_ids: A 1-D `Tensor` with indices into the output `Tensor`. Values + should be sorted and can be repeated. + num_segments: An optional int32 scalar. Indicates the size of the output + `Tensor`. + name: A name for the operation (optional). + sparse_gradient: An optional `bool`. Defaults to `False`. If `True`, the + gradient of this function will be sparse (`IndexedSlices`) instead of + dense (`Tensor`). The sparse gradient will contain one non-zero row for + each unique index in `indices`. + + Returns: + A `tensor` of the shape as data, except for dimension 0 which + has size `k`, the number of segments specified via `num_segments` or + inferred for the last element in `segments_ids`. + """ + return sparse_segment_sqrt_n( + data, + indices, + segment_ids, + name=name, + num_segments=num_segments, + sparse_gradient=sparse_gradient, + ) + + +@tf_export("tensordot", "linalg.tensordot") +@dispatch.add_dispatch_support +def tensordot(a, b, axes, name=None): + r"""Tensor contraction of a and b along specified axes and outer product. + + Tensordot (also known as tensor contraction) sums the product of elements + from `a` and `b` over the indices specified by `axes`. + + This operation corresponds to `numpy.tensordot(a, b, axes)`. + + Example 1: When `a` and `b` are matrices (order 2), the case `axes=1` + is equivalent to matrix multiplication. + + Example 2: When `a` and `b` are matrices (order 2), the case + `axes = [[1], [0]]` is equivalent to matrix multiplication. + + Example 3: When `a` and `b` are matrices (order 2), the case `axes=0` gives + the outer product, a tensor of order 4. + + Example 4: Suppose that \\(a_{ijk}\\) and \\(b_{lmn}\\) represent two + tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor + \\(c_{jklm}\\) whose entry + corresponding to the indices \\((j,k,l,m)\\) is given by: + + \\( c_{jklm} = \sum_i a_{ijk} b_{lmi} \\). + + In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`. + + Args: + a: `Tensor` of type `float32` or `float64`. + b: `Tensor` with the same type as `a`. + axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k]. + If axes is a scalar, sum over the last N axes of a and the first N axes of + b in order. If axes is a list or `Tensor` the first and second row contain + the set of unique integers specifying axes along which the contraction is + computed, for `a` and `b`, respectively. The number of axes for `a` and + `b` must be equal. If `axes=0`, computes the outer product between `a` and + `b`. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as `a`. + + Raises: + ValueError: If the shapes of `a`, `b`, and `axes` are incompatible. + IndexError: If the values in axes exceed the rank of the corresponding + tensor. + """ + + def _tensordot_reshape(a, axes, flipped=False): + """Helper method to perform transpose and reshape for contraction op. + + This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul` + using `array_ops.transpose` and `array_ops.reshape`. The method takes a + tensor and performs the correct transpose and reshape operation for a given + set of indices. It returns the reshaped tensor as well as a list of indices + necessary to reshape the tensor again after matrix multiplication. + + Args: + a: `Tensor`. + axes: List or `int32` `Tensor` of unique indices specifying valid axes of + `a`. + flipped: An optional `bool`. Defaults to `False`. If `True`, the method + assumes that `a` is the second argument in the contraction operation. + + Returns: + A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is + the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is + either a list of integers or an `int32` `Tensor`, depending on whether + the shape of a is fully specified, and free_dims_static is either a list + of integers and None values, or None, representing the inferred + static shape of the free dimensions + """ + if a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple)): + shape_a = a.get_shape().as_list() + axes = [i if i >= 0 else i + len(shape_a) for i in axes] + free = [i for i in builtins.range(len(shape_a)) if i not in axes] + free_dims = [shape_a[i] for i in free] + prod_free = int(np.prod([shape_a[i] for i in free])) + prod_axes = int(np.prod([shape_a[i] for i in axes])) + perm = list(axes) + free if flipped else free + list(axes) + new_shape = [prod_axes, prod_free] if flipped else [prod_free, prod_axes] + if (perm != np.arange(len(shape_a))).any(): + a_trans = array_ops.transpose(a, perm) + else: + a_trans = a + if a_trans.get_shape().as_list() != new_shape: + reshaped_a = array_ops.reshape(a_trans, new_shape) + else: + reshaped_a = a_trans + return reshaped_a, free_dims, free_dims + else: + if a.get_shape().ndims is not None and isinstance(axes, (list, tuple)): + shape_a = a.get_shape().as_list() + axes = [i if i >= 0 else i + len(shape_a) for i in axes] + free = [i for i in builtins.range(len(shape_a)) if i not in axes] + axes_dims = [shape_a[i] for i in axes] + free_dims = [shape_a[i] for i in free] + free_dims_static = free_dims + axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name="axes") + free = ops.convert_to_tensor(free, dtype=dtypes.int32, name="free") + shape_a = array_ops.shape(a) + else: + free_dims_static = None + shape_a = array_ops.shape(a) + rank_a = array_ops.rank(a) + axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name="axes") + axes = array_ops.where(axes >= 0, axes, axes + rank_a) + free, _ = gen_array_ops.list_diff(range(rank_a), axes, dtypes.int32) + free_dims = array_ops.gather(shape_a, free) + axes_dims = array_ops.gather(shape_a, axes) + prod_free_dims = reduce_prod(free_dims) + prod_axes_dims = reduce_prod(axes_dims) + if flipped: + perm = array_ops.concat([axes, free], 0) + new_shape = array_ops_stack.stack([prod_axes_dims, prod_free_dims]) + else: + perm = array_ops.concat([free, axes], 0) + new_shape = array_ops_stack.stack([prod_free_dims, prod_axes_dims]) + reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape) + return reshaped_a, free_dims, free_dims_static + + def _tensordot_axes(a, axes): + """Generates two sets of contraction axes for the two tensor arguments.""" + a_shape = a.get_shape() + if isinstance(axes, compat.integral_types): + if axes < 0: + raise ValueError(f"`axes` must be at least 0. Received: {axes}.") + if a_shape.ndims is not None: + if axes > a_shape.ndims: + raise ValueError(f"`axes` must not be larger than the number of " + f"dimensions of tensor {a}. Received {axes}, vs " + f"tensor dimensions {a_shape.ndims}.") + return (list(builtins.range(a_shape.ndims - axes, + a_shape.ndims)), list(builtins.range(axes))) + else: + rank = array_ops.rank(a) + return (range(rank - axes, rank, + dtype=dtypes.int32), range(axes, dtype=dtypes.int32)) + elif isinstance(axes, (list, tuple)): + if len(axes) != 2: + raise ValueError( + f"`axes` must be an integer or have length 2. Received {axes}.") + a_axes = axes[0] + b_axes = axes[1] + if isinstance(a_axes, compat.integral_types) and \ + isinstance(b_axes, compat.integral_types): + a_axes = [a_axes] + b_axes = [b_axes] + if len(a_axes) != len(b_axes): + raise ValueError(f"Different number of contraction axes `a` and `b`, " + f"{len(a_axes)} != {len(b_axes)}.") + return a_axes, b_axes + else: + axes = ops.convert_to_tensor(axes, name="axes", dtype=dtypes.int32) + return axes[0], axes[1] + + with ops.name_scope(name, "Tensordot", [a, b, axes]) as name: + a = ops.convert_to_tensor(a, name="a") + b = ops.convert_to_tensor(b, name="b") + a_axes, b_axes = _tensordot_axes(a, axes) + a_reshape, a_free_dims, a_free_dims_static = _tensordot_reshape(a, a_axes) + b_reshape, b_free_dims, b_free_dims_static = _tensordot_reshape( + b, b_axes, True) + ab_matmul = matmul(a_reshape, b_reshape) + if isinstance(a_free_dims, list) and isinstance(b_free_dims, list): + if (ab_matmul.get_shape().is_fully_defined() and + ab_matmul.get_shape().as_list() == a_free_dims + b_free_dims): + return ab_matmul + else: + return array_ops.reshape( + ab_matmul, a_free_dims + b_free_dims, name=name) + else: + a_free_dims = ops.convert_to_tensor(a_free_dims, dtype=dtypes.int32) + b_free_dims = ops.convert_to_tensor(b_free_dims, dtype=dtypes.int32) + product = array_ops.reshape( + ab_matmul, array_ops.concat([a_free_dims, b_free_dims], 0), name=name) + if a_free_dims_static is not None and b_free_dims_static is not None: + product.set_shape(a_free_dims_static + b_free_dims_static) + return product + + +@tf_export("math.polyval") +@dispatch.add_dispatch_support +def polyval(coeffs, x, name=None): + r"""Computes the elementwise value of a polynomial. + + If `x` is a tensor and `coeffs` is a list n + 1 tensors, + this function returns the value of the n-th order polynomial + + `p(x) = coeffs[n-1] + coeffs[n-2] * x + ... + coeffs[0] * x**(n-1)` + + evaluated using Horner's method, i.e. + + ```python + p(x) = coeffs[n-1] + x * (coeffs[n-2] + ... + x * (coeffs[1] + x * coeffs[0])) + ``` + + Usage Example: + + >>> coefficients = [1.0, 2.5, -4.2] + >>> x = 5.0 + >>> y = tf.math.polyval(coefficients, x) + >>> y + + + Usage Example: + + >>> tf.math.polyval([2, 1, 0], 3) # evaluates 2 * (3**2) + 1 * (3**1) + 0 * (3**0) + + + `tf.math.polyval` can also be used in polynomial regression. Taking + advantage of this function can facilitate writing a polynomial equation + as compared to explicitly writing it out, especially for higher degree + polynomials. + + >>> x = tf.constant(3) + >>> theta1 = tf.Variable(2) + >>> theta2 = tf.Variable(1) + >>> theta3 = tf.Variable(0) + >>> tf.math.polyval([theta1, theta2, theta3], x) + + + Args: + coeffs: A list of `Tensor` representing the coefficients of the polynomial. + x: A `Tensor` representing the variable of the polynomial. + name: A name for the operation (optional). + + Returns: + A `tensor` of the shape as the expression p(x) with usual broadcasting + rules for element-wise addition and multiplication applied. + + @compatibility(numpy) + Equivalent to numpy.polyval. + @end_compatibility + """ + if not isinstance(coeffs, list): + raise ValueError( + f"Argument coeffs must be list type. Received type {type(coeffs)}.") + + with ops.name_scope(name, "polyval", nest.flatten(coeffs) + [x]) as name: + x = ops.convert_to_tensor(x, name="x") + if len(coeffs) < 1: + return array_ops.zeros_like(x, name=name) + coeffs = [ + ops.convert_to_tensor(coeff, name=("coeff_%d" % index)) + for index, coeff in enumerate(coeffs) + ] + p = coeffs[0] + for c in coeffs[1:]: + p = c + p * x + return p + + +@tf_export("math.reciprocal_no_nan") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def reciprocal_no_nan(x, name=None): + """Performs a safe reciprocal operation, element wise. + + If a particular element is zero, the reciprocal for that element is + also set to zero. + + For example: + ```python + x = tf.constant([2.0, 0.5, 0, 1], dtype=tf.float32) + tf.math.reciprocal_no_nan(x) # [ 0.5, 2, 0.0, 1.0 ] + ``` + + Args: + x: A `Tensor` of type `float16`, `float32`, `float64` `complex64` or + `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of same shape and type as `x`. + + Raises: + TypeError: x must be of a valid dtype. + + """ + + with ops.name_scope(name, "reciprocal_no_nan", [x]) as scope: + x = ops.convert_to_tensor(x, name="x") + one = constant_op.constant(1, dtype=x.dtype.base_dtype, name="one") + return gen_math_ops.div_no_nan(one, x, name=scope) + + +@tf_export("math.xdivy") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def xdivy(x, y, name=None): + """Computes `x / y`. + + Given `x` and `y`, computes `x / y`. This function safely returns + zero when `x = 0`, no matter what the value of `y` is. + + Example: + + >>> tf.math.xdivy(1., 2.) + + >>> tf.math.xdivy(0., 1.) + + >>> tf.math.xdivy(0., 0.) + + >>> tf.math.xdivy(1., 0.) + + + Args: + x: A `tf.Tensor` of type `half`, `float32`, `float64`, `complex64`, + `complex128` + y: A `tf.Tensor` of type `half`, `float32`, `float64`, `complex64`, + `complex128` + name: A name for the operation (optional). + + Returns: + `x / y`. + """ + with ops.name_scope(name, "xdivy", [x]): + return gen_math_ops.xdivy(x, y) + + +@tf_export("math.xlog1py") +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def xlog1py(x, y, name=None): + r"""Compute x * log1p(y). + + Given `x` and `y`, compute `x * log1p(y)`. This function safely returns + zero when `x = 0`, no matter what the value of `y` is. + + Example: + + >>> tf.math.xlog1py(0., 1.) + + >>> tf.math.xlog1py(1., 1.) + + >>> tf.math.xlog1py(2., 2.) + + >>> tf.math.xlog1py(0., -1.) + + + Args: + x: A `tf.Tensor` of type `half`, `float32`, `float64`, `complex64`, + `complex128` + y: A `tf.Tensor` of type `half`, `float32`, `float64`, `complex64`, + `complex128` + name: A name for the operation (optional). + + Returns: + `x * log1p(y)`. + + @compatibility(scipy) + Equivalent to scipy.special.xlog1py + @end_compatibility + """ + with ops.name_scope(name, "xlog1py", [x]): + return gen_math_ops.xlog1py(x, y) + + +@tf_export("math.erfinv") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def erfinv(x, name=None): + """Compute inverse error function. + + Given `x`, compute the inverse error function of `x`. This function + is the inverse of `tf.math.erf`. + + Args: + x: `Tensor` with type `float` or `double`. + name: A name for the operation (optional). + Returns: + Inverse error function of `x`. + """ + with ops.name_scope(name, "erfinv", [x]): + return gen_math_ops.erfinv(x) + + +@tf_export("math.ndtri") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def ndtri(x, name=None): + """Compute quantile of Standard Normal. + + Args: + x: `Tensor` with type `float` or `double`. + name: A name for the operation (optional). + Returns: + Inverse error function of `x`. + """ + with ops.name_scope(name, "ndtri", [x]): + return gen_math_ops.ndtri(x) + + +@tf_export("math.erfcinv") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def erfcinv(x, name=None): + """Computes the inverse of complementary error function. + + Given `x`, compute the inverse complementary error function of `x`. + This function is the inverse of `tf.math.erfc`, and is defined on + `[0, 2]`. + + >>> tf.math.erfcinv([0., 0.2, 1., 1.5, 2.]) + + + Args: + x: `Tensor` with type `float` or `double`. + name: A name for the operation (optional). + Returns: + Inverse complementary error function of `x`. + + @compatibility(numpy) + Equivalent to scipy.special.erfcinv + @end_compatibility + """ + with ops.name_scope(name, "erfcinv", [x]): + x = ops.convert_to_tensor(x, name="start") + return -ndtri(0.5 * x) * np.sqrt(0.5) + + +@tf_export("math.ceil", v1=["math.ceil", "ceil"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("ceil") +def ceil(x, name=None): + """Return the ceiling of the input, element-wise. + + For example: + + >>> tf.math.ceil([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) + + + Args: + x: A `tf.Tensor`. Must be one of the following types: `bfloat16`, `half`, + `float32`, `float64`. `int32` + name: A name for the operation (optional). + + Returns: + A `tf.Tensor`. Has the same type as `x`. + + @compatibility(numpy) + Equivalent to np.ceil + @end_compatibility + """ + return gen_math_ops.ceil(x, name) + + +@tf_export("math.sqrt", "sqrt") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def sqrt(x, name=None): # pylint: disable=redefined-builtin + r"""Computes element-wise square root of the input tensor. + + Note: This operation does not support integer types. + + >>> x = tf.constant([[4.0], [16.0]]) + >>> tf.sqrt(x) + + >>> y = tf.constant([[-4.0], [16.0]]) + >>> tf.sqrt(y) + + >>> z = tf.constant([[-1.0], [16.0]], dtype=tf.complex128) + >>> tf.sqrt(z) + + + Note: In order to support complex type, please provide an input tensor + of `complex64` or `complex128`. + + Args: + x: A `tf.Tensor` of type `bfloat16`, `half`, `float32`, `float64`, + `complex64`, `complex128` + name: A name for the operation (optional). + + Returns: + A `tf.Tensor` of same size, type and sparsity as `x`. + """ + return gen_math_ops.sqrt(x, name) + + +# pylint: disable=g-docstring-has-escape +@tf_export("math.exp", "exp") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def exp(x, name=None): + r"""Computes exponential of x element-wise. \\(y = e^x\\). + + This function computes the exponential of the input tensor element-wise. + i.e. `math.exp(x)` or \\(e^x\\), where `x` is the input tensor. + \\(e\\) denotes Euler's number and is approximately equal to 2.718281. + Output is positive for any real input. + + >>> x = tf.constant(2.0) + >>> tf.math.exp(x) + + + >>> x = tf.constant([2.0, 8.0]) + >>> tf.math.exp(x) + + + For complex numbers, the exponential value is calculated as + $$ + e^{x+iy} = {e^x} {e^{iy}} = {e^x} ({\cos (y) + i \sin (y)}) + $$ + + For `1+1j` the value would be computed as: + $$ + e^1 (\cos (1) + i \sin (1)) = 2.7182817 \times (0.5403023+0.84147096j) + $$ + + >>> x = tf.constant(1 + 1j) + >>> tf.math.exp(x) + + + Args: + x: A `tf.Tensor`. Must be one of the following types: `bfloat16`, `half`, + `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor`. Has the same type as `x`. + + @compatibility(numpy) + Equivalent to np.exp + @end_compatibility + """ + return gen_math_ops.exp(x, name) + + +# pylint: enable=g-docstring-has-escape + + +@tf_export("math.sobol_sample") +@dispatch.add_dispatch_support +def sobol_sample(dim, num_results, skip=0, dtype=dtypes.float32, name=None): + """Generates points from the Sobol sequence. + + Creates a Sobol sequence with `num_results` samples. Each sample has dimension + `dim`. Skips the first `skip` samples. + + Args: + dim: Positive scalar `Tensor` representing each sample's dimension. + num_results: Positive scalar `Tensor` of dtype int32. The number of Sobol + points to return in the output. + skip: (Optional) Positive scalar `Tensor` of dtype int32. The number of + initial points of the Sobol sequence to skip. Default value is 0. + dtype: (Optional) The `tf.Dtype` of the sample. One of: `tf.float32` or + `tf.float64`. Defaults to `tf.float32`. + name: (Optional) Python `str` name prefixed to ops created by this function. + + Returns: + `Tensor` of samples from Sobol sequence with `shape` [num_results, dim]. + """ + with ops.name_scope(name, "sobol", [dim, num_results, skip]): + return gen_math_ops.sobol_sample(dim, num_results, skip, dtype=dtype) + + +@tf_export("math.rsqrt", v1=["math.rsqrt", "rsqrt"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("rsqrt") +def rsqrt(x, name=None): + """Computes reciprocal of square root of x element-wise. + + For example: + + >>> x = tf.constant([2., 0., -2.]) + >>> tf.math.rsqrt(x) + + + Args: + x: A `tf.Tensor`. Must be one of the following types: `bfloat16`, `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `tf.Tensor`. Has the same type as `x`. + """ + return gen_math_ops.rsqrt(x, name) + + +@tf_export("math.acos", "acos") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def acos(x, name=None): + """Computes acos of x element-wise. + + Provided an input tensor, the `tf.math.acos` operation + returns the inverse cosine of each element of the tensor. + If `y = tf.math.cos(x)` then, `x = tf.math.acos(y)`. + + Input range is `[-1, 1]` and the output has a range of `[0, pi]`. + + For example: + + >>> x = tf.constant([1.0, -0.5, 3.4, 0.2, 0.0, -2], dtype = tf.float32) + >>> tf.math.acos(x) + + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, + `float32`, `float64`, `complex64`, `complex128`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as x. + """ + return gen_math_ops.acos(x, name) + + +@tf_export("math.floor", "floor") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def floor(x, name=None): + """Returns element-wise largest integer not greater than x. + + Both input range is `(-inf, inf)` and the + output range consists of all integer values. + + For example: + + >>> x = tf.constant([1.3324, -1.5, 5.555, -2.532, 0.99, float("inf")]) + >>> tf.floor(x).numpy() + array([ 1., -2., 5., -3., 0., inf], dtype=float32) + + Args: + x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as x. + """ + return gen_math_ops.floor(x, name) + + +# Register elementwise ops that don't have Python wrappers. +# Binary elementwise ops. +dispatch.register_binary_elementwise_api(gen_bitwise_ops.bitwise_and) +dispatch.register_binary_elementwise_api(gen_bitwise_ops.bitwise_or) +dispatch.register_binary_elementwise_api(gen_bitwise_ops.bitwise_xor) +dispatch.register_binary_elementwise_api(gen_bitwise_ops.left_shift) +dispatch.register_binary_elementwise_api(gen_bitwise_ops.right_shift) +dispatch.register_unary_elementwise_api(gen_bitwise_ops.invert) +dispatch.register_binary_elementwise_api(gen_math_ops.atan2) +dispatch.register_binary_elementwise_api(gen_math_ops.floor_div) +dispatch.register_binary_elementwise_api(gen_math_ops.floor_mod) +dispatch.register_binary_elementwise_api(gen_math_ops.greater) +dispatch.register_binary_elementwise_api(gen_math_ops.greater_equal) +dispatch.register_binary_elementwise_api(gen_math_ops.less) +dispatch.register_binary_elementwise_api(gen_math_ops.less_equal) +dispatch.register_binary_elementwise_api(gen_math_ops.logical_and) +dispatch.register_binary_elementwise_api(gen_math_ops.logical_or) +dispatch.register_binary_elementwise_api(gen_math_ops.maximum) +dispatch.register_binary_elementwise_api(gen_math_ops.minimum) +dispatch.register_binary_elementwise_api(gen_math_ops.real_div) +dispatch.register_binary_elementwise_api(gen_math_ops.squared_difference) +dispatch.register_binary_elementwise_api(gen_math_ops.truncate_div) +dispatch.register_binary_elementwise_api(gen_math_ops.truncate_mod) +dispatch.register_binary_elementwise_api(gen_math_ops.xlogy) +dispatch.register_binary_elementwise_api(gen_math_ops.zeta) + +# Unary elementwise ops. +dispatch.register_unary_elementwise_api(gen_math_ops.acosh) +dispatch.register_unary_elementwise_api(gen_math_ops.asin) +dispatch.register_unary_elementwise_api(gen_math_ops.asinh) +dispatch.register_unary_elementwise_api(gen_math_ops.atan) +dispatch.register_unary_elementwise_api(gen_math_ops.atanh) +dispatch.register_unary_elementwise_api(gen_math_ops.cos) +dispatch.register_unary_elementwise_api(gen_math_ops.cosh) +dispatch.register_unary_elementwise_api(gen_math_ops.digamma) +dispatch.register_unary_elementwise_api(gen_math_ops.erf) +dispatch.register_unary_elementwise_api(gen_math_ops.erfc) +dispatch.register_unary_elementwise_api(gen_math_ops.expm1) +dispatch.register_unary_elementwise_api(gen_math_ops.is_finite) +dispatch.register_unary_elementwise_api(gen_math_ops.is_inf) +dispatch.register_unary_elementwise_api(gen_math_ops.is_nan) +dispatch.register_unary_elementwise_api(gen_math_ops.lgamma) +dispatch.register_unary_elementwise_api(gen_math_ops.log) +dispatch.register_unary_elementwise_api(gen_math_ops.log1p) +dispatch.register_unary_elementwise_api(gen_math_ops.logical_not) +dispatch.register_unary_elementwise_api(gen_math_ops.neg) +dispatch.register_unary_elementwise_api(gen_math_ops.next_after) +dispatch.register_unary_elementwise_api(gen_math_ops.reciprocal) +dispatch.register_unary_elementwise_api(gen_math_ops.rint) +dispatch.register_unary_elementwise_api(gen_math_ops.sin) +dispatch.register_unary_elementwise_api(gen_math_ops.sinh) +dispatch.register_unary_elementwise_api(gen_math_ops.square) +dispatch.register_unary_elementwise_api(gen_math_ops.tan) +dispatch.register_unary_elementwise_api(gen_math_ops.tanh) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c290fcb6f931af6a876b166bcafd982b7bcc79dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics.py @@ -0,0 +1,20 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Evaluation-related metrics.""" +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.metrics_impl import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..860a4e9b92934991b8b8ed2ee84d9728d5557f91 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/metrics_impl.py @@ -0,0 +1,3934 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of tf.metrics module.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import confusion_matrix +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import sets +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.ops import weights_broadcast_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +def metric_variable(shape, dtype, validate_shape=True, name=None): + """Create variable in `GraphKeys.(LOCAL|METRIC_VARIABLES)` collections. + + If running in a `DistributionStrategy` context, the variable will be + "sync on read". This means: + + * The returned object will be a container with separate variables + per replica of the model. + + * When writing to the variable, e.g. using `assign_add` in a metric + update, the update will be applied to the variable local to the + replica. + + * To get a metric's result value, we need to sum the variable values + across the replicas before computing the final answer. Furthermore, + the final answer should be computed once instead of in every + replica. Both of these are accomplished by running the computation + of the final result value inside + `distribute_lib.get_replica_context().merge_call(fn)`. + Inside the `merge_call()`, ops are only added to the graph once + and access to a sync on read variable in a computation returns + the sum across all replicas. + + Args: + shape: Shape of the created variable. + dtype: Type of the created variable. + validate_shape: (Optional) Whether shape validation is enabled for + the created variable. + name: (Optional) String name of the created variable. + + Returns: + A (non-trainable) variable initialized to zero, or if inside a + `DistributionStrategy` scope a sync on read variable container. + """ + # Note that synchronization "ON_READ" implies trainable=False. + return variable_v1.VariableV1( + lambda: array_ops.zeros(shape, dtype), + trainable=False, + collections=[ + ops.GraphKeys.LOCAL_VARIABLES, ops.GraphKeys.METRIC_VARIABLES + ], + validate_shape=validate_shape, + synchronization=variables.VariableSynchronization.ON_READ, + aggregation=variables.VariableAggregation.SUM, + name=name) + + +def _remove_squeezable_dimensions(predictions, labels, weights): + """Squeeze or expand last dim if needed. + + Squeezes last dim of `predictions` or `labels` if their rank differs by 1 + (using confusion_matrix.remove_squeezable_dimensions). + Squeezes or expands last dim of `weights` if its rank differs by 1 from the + new rank of `predictions`. + + If `weights` is scalar, it is kept scalar. + + This will use static shape if available. Otherwise, it will add graph + operations, which could result in a performance hit. + + Args: + predictions: Predicted values, a `Tensor` of arbitrary dimensions. + labels: Optional label `Tensor` whose dimensions match `predictions`. + weights: Optional weight scalar or `Tensor` whose dimensions match + `predictions`. + + Returns: + Tuple of `predictions`, `labels` and `weights`. Each of them possibly has + the last dimension squeezed, `weights` could be extended by one dimension. + """ + predictions = ops.convert_to_tensor(predictions) + if labels is not None: + labels, predictions = confusion_matrix.remove_squeezable_dimensions( + labels, predictions) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + + if weights is None: + return predictions, labels, None + + weights = ops.convert_to_tensor(weights) + weights_shape = weights.get_shape() + weights_rank = weights_shape.ndims + if weights_rank == 0: + return predictions, labels, weights + + predictions_shape = predictions.get_shape() + predictions_rank = predictions_shape.ndims + if (predictions_rank is not None) and (weights_rank is not None): + # Use static rank. + if weights_rank - predictions_rank == 1: + weights = array_ops.squeeze(weights, [-1]) + elif predictions_rank - weights_rank == 1: + weights = array_ops.expand_dims(weights, [-1]) + else: + # Use dynamic rank. + weights_rank_tensor = array_ops.rank(weights) + rank_diff = weights_rank_tensor - array_ops.rank(predictions) + + def _maybe_expand_weights(): + return cond.cond( + math_ops.equal(rank_diff, -1), + lambda: array_ops.expand_dims(weights, [-1]), lambda: weights) + + # Don't attempt squeeze if it will fail based on static check. + if ((weights_rank is not None) and + (not weights_shape.dims[-1].is_compatible_with(1))): + maybe_squeeze_weights = lambda: weights + else: + maybe_squeeze_weights = lambda: array_ops.squeeze(weights, [-1]) + + def _maybe_adjust_weights(): + return cond.cond( + math_ops.equal(rank_diff, 1), maybe_squeeze_weights, + _maybe_expand_weights) + + # If weights are scalar, do nothing. Otherwise, try to add or remove a + # dimension to match predictions. + weights = cond.cond( + math_ops.equal(weights_rank_tensor, 0), lambda: weights, + _maybe_adjust_weights) + return predictions, labels, weights + + +def _maybe_expand_labels(labels, predictions): + """If necessary, expand `labels` along last dimension to match `predictions`. + + Args: + labels: `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN]. The latter implies + num_labels=1, in which case the result is an expanded `labels` with shape + [D1, ... DN, 1]. + predictions: `Tensor` with shape [D1, ... DN, num_classes]. + + Returns: + `labels` with the same rank as `predictions`. + + Raises: + ValueError: if `labels` has invalid shape. + """ + with ops.name_scope(None, 'expand_labels', (labels, predictions)) as scope: + labels = sparse_tensor.convert_to_tensor_or_sparse_tensor(labels) + + # If sparse, expand sparse shape. + if isinstance(labels, sparse_tensor.SparseTensor): + return cond.cond( + math_ops.equal( + array_ops.rank(predictions), + array_ops.size(labels.dense_shape) + 1), + lambda: sparse_ops.sparse_reshape( # pylint: disable=g-long-lambda + labels, + shape=array_ops.concat((labels.dense_shape, (1,)), 0), + name=scope), + lambda: labels) + + # Otherwise, try to use static shape. + labels_rank = labels.get_shape().ndims + if labels_rank is not None: + predictions_rank = predictions.get_shape().ndims + if predictions_rank is not None: + if predictions_rank == labels_rank: + return labels + if predictions_rank == labels_rank + 1: + return array_ops.expand_dims(labels, -1, name=scope) + raise ValueError( + f'Unexpected labels shape {labels.get_shape()} for predictions ' + f'shape {predictions.get_shape()}. Predictions rank should be the ' + 'same rank as labels rank or labels rank plus one .') + + # Otherwise, use dynamic shape. + return cond.cond( + math_ops.equal(array_ops.rank(predictions), + array_ops.rank(labels) + 1), + lambda: array_ops.expand_dims(labels, -1, name=scope), lambda: labels) + + +def _safe_scalar_div(numerator, denominator, name): + """Divides two values, returning 0 if the denominator is 0. + + Args: + numerator: A scalar `float64` `Tensor`. + denominator: A scalar `float64` `Tensor`. + name: Name for the returned op. + + Returns: + 0 if `denominator` == 0, else `numerator` / `denominator` + """ + numerator.get_shape().with_rank_at_most(1) + denominator.get_shape().with_rank_at_most(1) + return math_ops.div_no_nan(numerator, denominator, name=name) + + +def _streaming_confusion_matrix(labels, predictions, num_classes, weights=None): + """Calculate a streaming confusion matrix. + + Calculates a confusion matrix. For estimation over a stream of data, + the function creates an `update_op` operation. + + Args: + labels: A `Tensor` of ground truth labels with shape [batch size] and of + type `int32` or `int64`. The tensor will be flattened if its rank > 1. + predictions: A `Tensor` of prediction results for semantic labels, whose + shape is [batch size] and type `int32` or `int64`. The tensor will be + flattened if its rank > 1. + num_classes: The possible number of labels the prediction task can + have. This value must be provided, since a confusion matrix of + dimension = [num_classes, num_classes] will be allocated. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + + Returns: + total_cm: A `Tensor` representing the confusion matrix. + update_op: An operation that increments the confusion matrix. + """ + # Local variable to accumulate the predictions in the confusion matrix. + total_cm = metric_variable( + [num_classes, num_classes], dtypes.float64, name='total_confusion_matrix') + + # Cast the type to int64 required by confusion_matrix_ops. + predictions = math_ops.cast(predictions, dtypes.int64) + labels = math_ops.cast(labels, dtypes.int64) + num_classes = math_ops.cast(num_classes, dtypes.int64) + + # Flatten the input if its rank > 1. + if predictions.get_shape().ndims > 1: + predictions = array_ops.reshape(predictions, [-1]) + + if labels.get_shape().ndims > 1: + labels = array_ops.reshape(labels, [-1]) + + if (weights is not None) and (weights.get_shape().ndims > 1): + weights = array_ops.reshape(weights, [-1]) + + # Accumulate the prediction to current confusion matrix. + current_cm = confusion_matrix.confusion_matrix( + labels, predictions, num_classes, weights=weights, dtype=dtypes.float64) + update_op = state_ops.assign_add(total_cm, current_cm) + return total_cm, update_op + + +def _aggregate_across_replicas(metrics_collections, metric_value_fn, *args): + """Aggregate metric value across replicas.""" + def fn(distribution, *a): + """Call `metric_value_fn` in the correct control flow context.""" + if hasattr(distribution.extended, '_outer_control_flow_context'): + # If there was an outer context captured before this method was called, + # then we enter that context to create the metric value op. If the + # captured context is `None`, ops.control_dependencies(None) gives the + # desired behavior. Else we use `Enter` and `Exit` to enter and exit the + # captured context. + # This special handling is needed because sometimes the metric is created + # inside a while_loop (and perhaps a TPU rewrite context). But we don't + # want the value op to be evaluated every step or on the TPU. So we + # create it outside so that it can be evaluated at the end on the host, + # once the update ops have been evaluated. + + # pylint: disable=protected-access + if distribution.extended._outer_control_flow_context is None: + with ops.control_dependencies(None): + metric_value = metric_value_fn(distribution, *a) + else: + distribution.extended._outer_control_flow_context.Enter() + metric_value = metric_value_fn(distribution, *a) + distribution.extended._outer_control_flow_context.Exit() + # pylint: enable=protected-access + else: + metric_value = metric_value_fn(distribution, *a) + if metrics_collections: + ops.add_to_collections(metrics_collections, metric_value) + return metric_value + + return distribute_lib.get_replica_context().merge_call( + fn, args=args) + + +@tf_export(v1=['metrics.mean']) +def mean(values, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the (weighted) mean of the given values. + + The `mean` function creates two local variables, `total` and `count` + that are used to compute the average of `values`. This average is ultimately + returned as `mean` which is an idempotent operation that simply divides + `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `mean`. + `update_op` increments `total` with the reduced sum of the product of `values` + and `weights`, and it increments `count` with the reduced sum of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + values: A `Tensor` of arbitrary dimensions. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `values`, and must be broadcastable to `values` (i.e., all dimensions must + be either `1`, or the same as the corresponding `values` dimension). + metrics_collections: An optional list of collections that `mean` + should be added to. + updates_collections: An optional list of collections that `update_op` + should be added to. + name: An optional variable_scope name. + + Returns: + mean: A `Tensor` representing the current mean, the value of `total` divided + by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `mean_value`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match `values`, + or if either `metrics_collections` or `updates_collections` are not a list + or tuple. + RuntimeError: If eager execution is enabled. + + @compatibility(TF2) + `tf.compat.v1.metrics.mean` is not compatible with eager + execution or `tf.function`. + Please use `tf.keras.metrics.Mean` instead for TF2 migration. After + instantiating a `tf.keras.metrics.Mean` object, you can first call the + `update_state()` method to record the new values, and then call the + `result()` method to get the mean eagerly. You can also attach it to a + Keras model with the `add_metric` method. Please refer to the [migration + guide](https://www.tensorflow.org/guide/migrate#new-style_metrics_and_losses) + for more details. + + #### Structural Mapping to TF2 + + Before: + + ```python + mean, update_op = tf.compat.v1.metrics.mean( + values=values, + weights=weights, + metrics_collections=metrics_collections, + update_collections=update_collections, + name=name) + ``` + + After: + + ```python + m = tf.keras.metrics.Mean( + name=name) + + m.update_state( + values=values, + sample_weight=weights) + + mean = m.result() + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `values` | `values` | In `update_state()` method | + | `weights` | `sample_weight` | In `update_state()` method | + | `metrics_collections` | Not supported | Metrics should be tracked | + : : : explicitly or with Keras : + : : : APIs, for example, : + : : : [add_metric][add_metric], : + : : : instead of via collections : + | `updates_collections` | Not supported | - | + | `name` | `name` | In constructor | + + [add_metric]:https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_metric + + + #### Before & After Usage Example + + Before: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... values = [1, 2, 3] + ... mean, update_op = tf.compat.v1.metrics.mean(values) + ... global_init = tf.compat.v1.global_variables_initializer() + ... local_init = tf.compat.v1.local_variables_initializer() + >>> sess = tf.compat.v1.Session(graph=g) + >>> sess.run([global_init, local_init]) + >>> sess.run(update_op) + >>> sess.run(mean) + 2.0 + + + After: + + >>> m = tf.keras.metrics.Mean() + >>> m.update_state([1, 2, 3]) + >>> m.result().numpy() + 2.0 + + ```python + # Used within Keras model + model.add_metric(tf.keras.metrics.Mean()(values)) + ``` + + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean is not supported when eager execution ' + 'is enabled.') + + with variable_scope.variable_scope(name, 'mean', (values, weights)): + values = math_ops.cast(values, dtypes.float32) + + total = metric_variable([], dtypes.float32, name='total') + count = metric_variable([], dtypes.float32, name='count') + + if weights is None: + num_values = math_ops.cast(array_ops.size(values), dtypes.float32) + else: + values, _, weights = _remove_squeezable_dimensions( + predictions=values, labels=None, weights=weights) + weights = weights_broadcast_ops.broadcast_weights( + math_ops.cast(weights, dtypes.float32), values) + values = math_ops.multiply(values, weights) + num_values = math_ops.reduce_sum(weights) + + update_total_op = state_ops.assign_add(total, math_ops.reduce_sum(values)) + with ops.control_dependencies([values]): + update_count_op = state_ops.assign_add(count, num_values) + + def compute_mean(_, t, c): + return math_ops.div_no_nan(t, math_ops.maximum(c, 0), name='value') + + mean_t = _aggregate_across_replicas( + metrics_collections, compute_mean, total, count) + update_op = math_ops.div_no_nan( + update_total_op, math_ops.maximum(update_count_op, 0), name='update_op') + + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return mean_t, update_op + + +@tf_export(v1=['metrics.accuracy']) +def accuracy(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Calculates how often `predictions` matches `labels`. + + The `accuracy` function creates two local variables, `total` and + `count` that are used to compute the frequency with which `predictions` + matches `labels`. This frequency is ultimately returned as `accuracy`: an + idempotent operation that simply divides `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `accuracy`. + Internally, an `is_correct` operation computes a `Tensor` with elements 1.0 + where the corresponding elements of `predictions` and `labels` match and 0.0 + otherwise. Then `update_op` increments `total` with the reduced sum of the + product of `weights` and `is_correct`, and it increments `count` with the + reduced sum of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose shape matches + `predictions`. + predictions: The predicted values, a `Tensor` of any shape. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `accuracy` should + be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + accuracy: A `Tensor` representing the accuracy, the value of `total` divided + by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `accuracy`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + + @compatibility(TF2) + `tf.compat.v1.metrics.accuracy` is not compatible with eager + execution or `tf.function`. + Please use `tf.keras.metrics.Accuracy` instead for TF2 migration. After + instantiating a `tf.keras.metrics.Accuracy` object, you can first call the + `update_state()` method to record the prediction/labels, and then call the + `result()` method to get the accuracy eagerly. You can also attach it to a + Keras model when calling the `compile` method. Please refer to [this + guide](https://www.tensorflow.org/guide/migrate#new-style_metrics_and_losses) + for more details. + + #### Structural Mapping to Native TF2 + + Before: + + ```python + accuracy, update_op = tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=predictions, + weights=weights, + metrics_collections=metrics_collections, + update_collections=update_collections, + name=name) + ``` + + After: + + ```python + m = tf.keras.metrics.Accuracy( + name=name, + dtype=None) + + m.update_state( + y_true=labels, + y_pred=predictions, + sample_weight=weights) + + accuracy = m.result() + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `label` | `y_true` | In `update_state()` method | + | `predictions` | `y_true` | In `update_state()` method | + | `weights` | `sample_weight` | In `update_state()` method | + | `metrics_collections` | Not supported | Metrics should be tracked | + : : : explicitly or with Keras : + : : : APIs, for example, : + : : : [add_metric][add_metric], : + : : : instead of via collections : + | `updates_collections` | Not supported | - | + | `name` | `name` | In constructor | + + [add_metric]:https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_metric + + + #### Before & After Usage Example + + Before: + + >>> g = tf.Graph() + >>> with g.as_default(): + ... logits = [1, 2, 3] + ... labels = [0, 2, 3] + ... acc, acc_op = tf.compat.v1.metrics.accuracy(logits, labels) + ... global_init = tf.compat.v1.global_variables_initializer() + ... local_init = tf.compat.v1.local_variables_initializer() + >>> sess = tf.compat.v1.Session(graph=g) + >>> sess.run([global_init, local_init]) + >>> print(sess.run([acc, acc_op])) + [0.0, 0.66667] + + + After: + + >>> m = tf.keras.metrics.Accuracy() + >>> m.update_state([1, 2, 3], [0, 2, 3]) + >>> m.result().numpy() + 0.66667 + + ```python + # Used within Keras model + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.Accuracy()]) + ``` + + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.accuracy is not supported when eager ' + 'execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + if labels.dtype != predictions.dtype: + predictions = math_ops.cast(predictions, labels.dtype) + is_correct = math_ops.cast( + math_ops.equal(predictions, labels), dtypes.float32) + return mean(is_correct, weights, metrics_collections, updates_collections, + name or 'accuracy') + + +def _confusion_matrix_at_thresholds(labels, + predictions, + thresholds, + weights=None, + includes=None): + """Computes true_positives, false_negatives, true_negatives, false_positives. + + This function creates up to four local variables, `true_positives`, + `true_negatives`, `false_positives` and `false_negatives`. + `true_positive[i]` is defined as the total weight of values in `predictions` + above `thresholds[i]` whose corresponding entry in `labels` is `True`. + `false_negatives[i]` is defined as the total weight of values in `predictions` + at most `thresholds[i]` whose corresponding entry in `labels` is `True`. + `true_negatives[i]` is defined as the total weight of values in `predictions` + at most `thresholds[i]` whose corresponding entry in `labels` is `False`. + `false_positives[i]` is defined as the total weight of values in `predictions` + above `thresholds[i]` whose corresponding entry in `labels` is `False`. + + For estimation of these metrics over a stream of data, for each metric the + function respectively creates an `update_op` operation that updates the + variable and returns its value. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + includes: Tuple of keys to return, from 'tp', 'fn', 'tn', fp'. If `None`, + default to all four. + + Returns: + values: Dict of variables of shape `[len(thresholds)]`. Keys are from + `includes`. + update_ops: Dict of operations that increments the `values`. Keys are from + `includes`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + `includes` contains invalid keys. + """ + all_includes = ('tp', 'fn', 'tn', 'fp') + if includes is None: + includes = all_includes + else: + for include in includes: + if include not in all_includes: + raise ValueError(f'Invalid key: {include}') + + with ops.control_dependencies([ + check_ops.assert_greater_equal( + predictions, + math_ops.cast(0.0, dtype=predictions.dtype), + message='predictions must be in [0, 1]'), + check_ops.assert_less_equal( + predictions, + math_ops.cast(1.0, dtype=predictions.dtype), + message='predictions must be in [0, 1]') + ]): + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtypes.float32), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + + num_thresholds = len(thresholds) + + # Reshape predictions and labels. + predictions_2d = array_ops.reshape(predictions, [-1, 1]) + labels_2d = array_ops.reshape( + math_ops.cast(labels, dtype=dtypes.bool), [1, -1]) + + # Use static shape if known. + num_predictions = predictions_2d.get_shape().as_list()[0] + + # Otherwise use dynamic shape. + if num_predictions is None: + num_predictions = array_ops.shape(predictions_2d)[0] + thresh_tiled = array_ops.tile( + array_ops.expand_dims(array_ops.constant(thresholds), [1]), + array_ops_stack.stack([1, num_predictions])) + + # Tile the predictions after thresholding them across different thresholds. + pred_is_pos = math_ops.greater( + array_ops.tile(array_ops.transpose(predictions_2d), [num_thresholds, 1]), + thresh_tiled) + if ('fn' in includes) or ('tn' in includes): + pred_is_neg = math_ops.logical_not(pred_is_pos) + + # Tile labels by number of thresholds + label_is_pos = array_ops.tile(labels_2d, [num_thresholds, 1]) + if ('fp' in includes) or ('tn' in includes): + label_is_neg = math_ops.logical_not(label_is_pos) + + if weights is not None: + weights = weights_broadcast_ops.broadcast_weights( + math_ops.cast(weights, dtypes.float32), predictions) + weights_tiled = array_ops.tile( + array_ops.reshape(weights, [1, -1]), [num_thresholds, 1]) + thresh_tiled.get_shape().assert_is_compatible_with( + weights_tiled.get_shape()) + else: + weights_tiled = None + + values = {} + update_ops = {} + + if 'tp' in includes: + true_p = metric_variable( + [num_thresholds], dtypes.float32, name='true_positives') + is_true_positive = math_ops.cast( + math_ops.logical_and(label_is_pos, pred_is_pos), dtypes.float32) + if weights_tiled is not None: + is_true_positive *= weights_tiled + update_ops['tp'] = state_ops.assign_add(true_p, + math_ops.reduce_sum( + is_true_positive, 1)) + values['tp'] = true_p + + if 'fn' in includes: + false_n = metric_variable( + [num_thresholds], dtypes.float32, name='false_negatives') + is_false_negative = math_ops.cast( + math_ops.logical_and(label_is_pos, pred_is_neg), dtypes.float32) + if weights_tiled is not None: + is_false_negative *= weights_tiled + update_ops['fn'] = state_ops.assign_add(false_n, + math_ops.reduce_sum( + is_false_negative, 1)) + values['fn'] = false_n + + if 'tn' in includes: + true_n = metric_variable( + [num_thresholds], dtypes.float32, name='true_negatives') + is_true_negative = math_ops.cast( + math_ops.logical_and(label_is_neg, pred_is_neg), dtypes.float32) + if weights_tiled is not None: + is_true_negative *= weights_tiled + update_ops['tn'] = state_ops.assign_add(true_n, + math_ops.reduce_sum( + is_true_negative, 1)) + values['tn'] = true_n + + if 'fp' in includes: + false_p = metric_variable( + [num_thresholds], dtypes.float32, name='false_positives') + is_false_positive = math_ops.cast( + math_ops.logical_and(label_is_neg, pred_is_pos), dtypes.float32) + if weights_tiled is not None: + is_false_positive *= weights_tiled + update_ops['fp'] = state_ops.assign_add(false_p, + math_ops.reduce_sum( + is_false_positive, 1)) + values['fp'] = false_p + + return values, update_ops + + +def _aggregate_variable(v, collections): + f = lambda distribution, value: distribution.extended.read_var(value) + return _aggregate_across_replicas(collections, f, v) + + +@tf_export(v1=['metrics.auc']) +@deprecated(None, + 'The value of AUC returned by this may race with the update so ' + 'this is deprecated. Please use tf.keras.metrics.AUC instead.') +def auc(labels, + predictions, + weights=None, + num_thresholds=200, + metrics_collections=None, + updates_collections=None, + curve='ROC', + name=None, + summation_method='trapezoidal', + thresholds=None): + """Computes the approximate AUC via a Riemann sum. + + The `auc` function creates four local variables, `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` that are used to + compute the AUC. To discretize the AUC curve, a linearly spaced set of + thresholds is used to compute pairs of recall and precision values. The area + under the ROC-curve is therefore computed using the height of the recall + values by the false positive rate, while the area under the PR-curve is the + computed using the height of the precision values by the recall. + + This value is ultimately returned as `auc`, an idempotent operation that + computes the area under a discretized curve of precision versus recall values + (computed using the aforementioned variables). The `num_thresholds` variable + controls the degree of discretization with larger numbers of thresholds more + closely approximating the true AUC. The quality of the approximation may vary + dramatically depending on `num_thresholds`. + + For best results, `predictions` should be distributed approximately uniformly + in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC + approximation may be poor if this is not the case. Setting `summation_method` + to 'minoring' or 'majoring' can help quantify the error in the approximation + by providing lower or upper bound estimate of the AUC. The `thresholds` + parameter can be used to manually specify thresholds which split the + predictions more evenly. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `auc`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + num_thresholds: The number of thresholds to use when discretizing the roc + curve. + metrics_collections: An optional list of collections that `auc` should be + added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + curve: Specifies the name of the curve to be computed, 'ROC' [default] or + 'PR' for the Precision-Recall-curve. + name: An optional variable_scope name. + summation_method: Specifies the Riemann summation method used + (https://en.wikipedia.org/wiki/Riemann_sum): 'trapezoidal' [default] that + applies the trapezoidal rule; 'careful_interpolation', a variant of it + differing only by a more correct interpolation scheme for PR-AUC - + interpolating (true/false) positives but not the ratio that is precision; + 'minoring' that applies left summation for increasing intervals and right + summation for decreasing intervals; 'majoring' that does the opposite. + Note that 'careful_interpolation' is strictly preferred to 'trapezoidal' + (to be deprecated soon) as it applies the same method for ROC, and a + better one (see Davis & Goadrich 2006 for details) for the PR curve. + thresholds: An optional list of floating point values to use as the + thresholds for discretizing the curve. If set, the `num_thresholds` + parameter is ignored. Values should be in [0, 1]. Endpoint thresholds + equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be + automatically included with these to correctly handle predictions equal to + exactly 0 or 1. + + Returns: + auc: A scalar `Tensor` representing the current area-under-curve. + update_op: An operation that increments the `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` variables + appropriately and whose value matches `auc`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.auc is not supported when eager execution ' + 'is enabled.') + + with variable_scope.variable_scope(name, 'auc', + (labels, predictions, weights)): + if curve != 'ROC' and curve != 'PR': + raise ValueError(f'Curve must be either ROC or PR. Curve {curve} is ' + 'unknown.') + + kepsilon = 1e-7 # To account for floating point imprecisions. + if thresholds is not None: + # If specified, use the supplied thresholds. + thresholds = sorted(thresholds) + num_thresholds = len(thresholds) + 2 + else: + # Otherwise, linearly interpolate (num_thresholds - 2) thresholds in + # (0, 1). + thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) + for i in range(num_thresholds - 2)] + + # Add an endpoint "threshold" below zero and above one for either threshold + # method. + thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] + + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights) + + # Add epsilons to avoid dividing by 0. + epsilon = 1.0e-6 + + def interpolate_pr_auc(tp, fp, fn): + """Interpolation formula inspired by section 4 of (Davis et al., 2006). + + Note here we derive & use a closed formula not present in the paper + - as follows: + Modeling all of TP (true positive weight), + FP (false positive weight) and their sum P = TP + FP (positive weight) + as varying linearly within each interval [A, B] between successive + thresholds, we get + Precision = (TP_A + slope * (P - P_A)) / P + with slope = dTP / dP = (TP_B - TP_A) / (P_B - P_A). + The area within the interval is thus (slope / total_pos_weight) times + int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P} + int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P} + where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in + int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A) + Bringing back the factor (slope / total_pos_weight) we'd put aside, we get + slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight + where dTP == TP_B - TP_A. + Note that when P_A == 0 the above calculation simplifies into + int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A) + which is really equivalent to imputing constant precision throughout the + first bucket having >0 true positives. + + Args: + tp: true positive counts + fp: false positive counts + fn: false negative counts + + Returns: + pr_auc: an approximation of the area under the P-R curve. + + References: + The Relationship Between Precision-Recall and ROC Curves: + [Davis et al., 2006](https://dl.acm.org/citation.cfm?id=1143874) + ([pdf](https://www.biostat.wisc.edu/~page/rocpr.pdf)) + """ + dtp = tp[:num_thresholds - 1] - tp[1:] + p = tp + fp + prec_slope = math_ops.div_no_nan( + dtp, + math_ops.maximum(p[:num_thresholds - 1] - p[1:], 0), + name='prec_slope') + intercept = tp[1:] - math_ops.multiply(prec_slope, p[1:]) + safe_p_ratio = array_ops.where( + math_ops.logical_and(p[:num_thresholds - 1] > 0, p[1:] > 0), + math_ops.div_no_nan( + p[:num_thresholds - 1], + math_ops.maximum(p[1:], 0), + name='recall_relative_ratio'), array_ops.ones_like(p[1:])) + return math_ops.reduce_sum( + math_ops.div_no_nan( + prec_slope * (dtp + intercept * math_ops.log(safe_p_ratio)), + math_ops.maximum(tp[1:] + fn[1:], 0), + name='pr_auc_increment'), + name='interpolate_pr_auc') + + def compute_auc(tp, fn, tn, fp, name): + """Computes the roc-auc or pr-auc based on confusion counts.""" + if curve == 'PR': + if summation_method == 'trapezoidal': + logging.warning( + 'Trapezoidal rule is known to produce incorrect PR-AUCs; ' + 'please switch to "careful_interpolation" instead.') + elif summation_method == 'careful_interpolation': + # This one is a bit tricky and is handled separately. + return interpolate_pr_auc(tp, fp, fn) + rec = math_ops.divide(tp + epsilon, tp + fn + epsilon) + if curve == 'ROC': + fp_rate = math_ops.divide(fp, fp + tn + epsilon) + x = fp_rate + y = rec + else: # curve == 'PR'. + prec = math_ops.divide(tp + epsilon, tp + fp + epsilon) + x = rec + y = prec + if summation_method in ('trapezoidal', 'careful_interpolation'): + # Note that the case ('PR', 'careful_interpolation') has been handled + # above. + return math_ops.reduce_sum( + math_ops.multiply(x[:num_thresholds - 1] - x[1:], + (y[:num_thresholds - 1] + y[1:]) / 2.), + name=name) + elif summation_method == 'minoring': + return math_ops.reduce_sum( + math_ops.multiply(x[:num_thresholds - 1] - x[1:], + math_ops.minimum(y[:num_thresholds - 1], y[1:])), + name=name) + elif summation_method == 'majoring': + return math_ops.reduce_sum( + math_ops.multiply(x[:num_thresholds - 1] - x[1:], + math_ops.maximum(y[:num_thresholds - 1], y[1:])), + name=name) + else: + raise ValueError(f'Invalid summation_method: {summation_method} ' + 'summation_method should be \'trapezoidal\', ' + '\'careful_interpolation\', \'minoring\', or ' + '\'majoring\'.') + + # sum up the areas of all the trapeziums + def compute_auc_value(_, values): + return compute_auc(values['tp'], values['fn'], values['tn'], values['fp'], + 'value') + + auc_value = _aggregate_across_replicas( + metrics_collections, compute_auc_value, values) + update_op = compute_auc(update_ops['tp'], update_ops['fn'], + update_ops['tn'], update_ops['fp'], 'update_op') + + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return auc_value, update_op + + +@tf_export(v1=['metrics.mean_absolute_error']) +def mean_absolute_error(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the mean absolute error between the labels and predictions. + + The `mean_absolute_error` function creates two local variables, + `total` and `count` that are used to compute the mean absolute error. This + average is weighted by `weights`, and it is ultimately returned as + `mean_absolute_error`: an idempotent operation that simply divides `total` by + `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `mean_absolute_error`. Internally, an `absolute_errors` operation computes the + absolute value of the differences between `predictions` and `labels`. Then + `update_op` increments `total` with the reduced sum of the product of + `weights` and `absolute_errors`, and it increments `count` with the reduced + sum of `weights` + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of the same shape as `predictions`. + predictions: A `Tensor` of arbitrary shape. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that + `mean_absolute_error` should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + mean_absolute_error: A `Tensor` representing the current mean, the value of + `total` divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `mean_absolute_error`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_absolute_error is not supported ' + 'when eager execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + absolute_errors = math_ops.abs(predictions - labels) + return mean(absolute_errors, weights, metrics_collections, + updates_collections, name or 'mean_absolute_error') + + +@tf_export(v1=['metrics.mean_cosine_distance']) +def mean_cosine_distance(labels, + predictions, + dim, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the cosine distance between the labels and predictions. + + The `mean_cosine_distance` function creates two local variables, + `total` and `count` that are used to compute the average cosine distance + between `predictions` and `labels`. This average is weighted by `weights`, + and it is ultimately returned as `mean_distance`, which is an idempotent + operation that simply divides `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `mean_distance`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of arbitrary shape. + predictions: A `Tensor` of the same shape as `labels`. + dim: The dimension along which the cosine distance is computed. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). Also, + dimension `dim` must be `1`. + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + mean_distance: A `Tensor` representing the current mean, the value of + `total` divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_cosine_distance is not supported when ' + 'eager execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + radial_diffs = math_ops.multiply(predictions, labels) + radial_diffs = math_ops.reduce_sum( + radial_diffs, axis=[ + dim, + ], keepdims=True) + mean_distance, update_op = mean(radial_diffs, weights, None, None, name or + 'mean_cosine_distance') + mean_distance = math_ops.subtract(1.0, mean_distance) + update_op = math_ops.subtract(1.0, update_op) + + if metrics_collections: + ops.add_to_collections(metrics_collections, mean_distance) + + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return mean_distance, update_op + + +@tf_export(v1=['metrics.mean_per_class_accuracy']) +def mean_per_class_accuracy(labels, + predictions, + num_classes, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Calculates the mean of the per-class accuracies. + + Calculates the accuracy for each class, then takes the mean of that. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates the accuracy of each class and returns + them. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of ground truth labels with shape [batch size] and of + type `int32` or `int64`. The tensor will be flattened if its rank > 1. + predictions: A `Tensor` of prediction results for semantic labels, whose + shape is [batch size] and type `int32` or `int64`. The tensor will be + flattened if its rank > 1. + num_classes: The possible number of labels the prediction task can + have. This value must be provided, since two variables with shape = + [num_classes] will be allocated. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that + `mean_per_class_accuracy' + should be added to. + updates_collections: An optional list of collections `update_op` should be + added to. + name: An optional variable_scope name. + + Returns: + mean_accuracy: A `Tensor` representing the mean per class accuracy. + update_op: An operation that updates the accuracy tensor. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_per_class_accuracy is not supported ' + 'when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'mean_accuracy', + (predictions, labels, weights)): + labels = math_ops.cast(labels, dtypes.int64) + + # Flatten the input if its rank > 1. + if labels.get_shape().ndims > 1: + labels = array_ops.reshape(labels, [-1]) + + if predictions.get_shape().ndims > 1: + predictions = array_ops.reshape(predictions, [-1]) + + # Check if shape is compatible. + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + + total = metric_variable([num_classes], dtypes.float32, name='total') + count = metric_variable([num_classes], dtypes.float32, name='count') + + ones = array_ops.ones([array_ops.size(labels)], dtypes.float32) + + if labels.dtype != predictions.dtype: + predictions = math_ops.cast(predictions, labels.dtype) + is_correct = math_ops.cast( + math_ops.equal(predictions, labels), dtypes.float32) + + if weights is not None: + if weights.get_shape().ndims > 1: + weights = array_ops.reshape(weights, [-1]) + weights = math_ops.cast(weights, dtypes.float32) + + is_correct *= weights + ones *= weights + + update_total_op = state_ops.scatter_add(total, labels, ones) + update_count_op = state_ops.scatter_add(count, labels, is_correct) + + def compute_mean_accuracy(_, count, total): + per_class_accuracy = math_ops.div_no_nan( + count, math_ops.maximum(total, 0), name=None) + mean_accuracy_v = math_ops.reduce_mean( + per_class_accuracy, name='mean_accuracy') + return mean_accuracy_v + + mean_accuracy_v = _aggregate_across_replicas( + metrics_collections, compute_mean_accuracy, count, total) + + update_op = math_ops.div_no_nan( + update_count_op, math_ops.maximum(update_total_op, 0), name='update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return mean_accuracy_v, update_op + + +@tf_export(v1=['metrics.mean_iou']) +def mean_iou(labels, + predictions, + num_classes, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Calculate per-step mean Intersection-Over-Union (mIOU). + + Mean Intersection-Over-Union is a common evaluation metric for + semantic image segmentation, which first computes the IOU for each + semantic class and then computes the average over classes. + IOU is defined as follows: + IOU = true_positive / (true_positive + false_positive + false_negative). + The predictions are accumulated in a confusion matrix, weighted by `weights`, + and mIOU is then calculated from it. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `mean_iou`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of ground truth labels with shape [batch size] and of + type `int32` or `int64`. The tensor will be flattened if its rank > 1. + predictions: A `Tensor` of prediction results for semantic labels, whose + shape is [batch size] and type `int32` or `int64`. The tensor will be + flattened if its rank > 1. + num_classes: The possible number of labels the prediction task can + have. This value must be provided, since a confusion matrix of + dimension = [num_classes, num_classes] will be allocated. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `mean_iou` + should be added to. + updates_collections: An optional list of collections `update_op` should be + added to. + name: An optional variable_scope name. + + Returns: + mean_iou: A `Tensor` representing the mean intersection-over-union. + update_op: An operation that increments the confusion matrix. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_iou is not supported when ' + 'eager execution is enabled.') + + with variable_scope.variable_scope(name, 'mean_iou', + (predictions, labels, weights)): + # Check if shape is compatible. + predictions.get_shape().assert_is_compatible_with(labels.get_shape()) + + total_cm, update_op = _streaming_confusion_matrix(labels, predictions, + num_classes, weights) + + def compute_mean_iou(_, total_cm): + """Compute the mean intersection-over-union via the confusion matrix.""" + sum_over_row = math_ops.cast( + math_ops.reduce_sum(total_cm, 0), dtypes.float32) + sum_over_col = math_ops.cast( + math_ops.reduce_sum(total_cm, 1), dtypes.float32) + cm_diag = math_ops.cast(array_ops.diag_part(total_cm), dtypes.float32) + denominator = sum_over_row + sum_over_col - cm_diag + + # The mean is only computed over classes that appear in the + # label or prediction tensor. If the denominator is 0, we need to + # ignore the class. + num_valid_entries = math_ops.reduce_sum( + math_ops.cast( + math_ops.not_equal(denominator, 0), dtype=dtypes.float32)) + + # If the value of the denominator is 0, set it to 1 to avoid + # zero division. + denominator = array_ops.where( + math_ops.greater(denominator, 0), denominator, + array_ops.ones_like(denominator)) + iou = math_ops.divide(cm_diag, denominator) + + # If the number of valid entries is 0 (no classes) we return 0. + result = array_ops.where( + math_ops.greater(num_valid_entries, 0), + math_ops.reduce_sum(iou, name='mean_iou') / num_valid_entries, 0) + return result + + # TODO(priyag): Use outside_compilation if in TPU context. + mean_iou_v = _aggregate_across_replicas( + metrics_collections, compute_mean_iou, total_cm) + + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return mean_iou_v, update_op + + +@tf_export(v1=['metrics.mean_relative_error']) +def mean_relative_error(labels, + predictions, + normalizer, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the mean relative error by normalizing with the given values. + + The `mean_relative_error` function creates two local variables, + `total` and `count` that are used to compute the mean relative absolute error. + This average is weighted by `weights`, and it is ultimately returned as + `mean_relative_error`: an idempotent operation that simply divides `total` by + `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `mean_reative_error`. Internally, a `relative_errors` operation divides the + absolute value of the differences between `predictions` and `labels` by the + `normalizer`. Then `update_op` increments `total` with the reduced sum of the + product of `weights` and `relative_errors`, and it increments `count` with the + reduced sum of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of the same shape as `predictions`. + predictions: A `Tensor` of arbitrary shape. + normalizer: A `Tensor` of the same shape as `predictions`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that + `mean_relative_error` should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + mean_relative_error: A `Tensor` representing the current mean, the value of + `total` divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `mean_relative_error`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_relative_error is not supported when ' + 'eager execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + + predictions, normalizer = confusion_matrix.remove_squeezable_dimensions( + predictions, normalizer) + predictions.get_shape().assert_is_compatible_with(normalizer.get_shape()) + relative_errors = array_ops.where( + math_ops.equal(normalizer, 0.0), array_ops.zeros_like(labels), + math_ops.divide(math_ops.abs(labels - predictions), normalizer)) + return mean(relative_errors, weights, metrics_collections, + updates_collections, name or 'mean_relative_error') + + +@tf_export(v1=['metrics.mean_squared_error']) +def mean_squared_error(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the mean squared error between the labels and predictions. + + The `mean_squared_error` function creates two local variables, + `total` and `count` that are used to compute the mean squared error. + This average is weighted by `weights`, and it is ultimately returned as + `mean_squared_error`: an idempotent operation that simply divides `total` by + `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `mean_squared_error`. Internally, a `squared_error` operation computes the + element-wise square of the difference between `predictions` and `labels`. Then + `update_op` increments `total` with the reduced sum of the product of + `weights` and `squared_error`, and it increments `count` with the reduced sum + of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of the same shape as `predictions`. + predictions: A `Tensor` of arbitrary shape. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that + `mean_squared_error` should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + mean_squared_error: A `Tensor` representing the current mean, the value of + `total` divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `mean_squared_error`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_squared_error is not supported when ' + 'eager execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + squared_error = math_ops.squared_difference(labels, predictions) + return mean(squared_error, weights, metrics_collections, updates_collections, + name or 'mean_squared_error') + + +@tf_export(v1=['metrics.mean_tensor']) +def mean_tensor(values, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the element-wise (weighted) mean of the given tensors. + + In contrast to the `mean` function which returns a scalar with the + mean, this function returns an average tensor with the same shape as the + input tensors. + + The `mean_tensor` function creates two local variables, + `total_tensor` and `count_tensor` that are used to compute the average of + `values`. This average is ultimately returned as `mean` which is an idempotent + operation that simply divides `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `mean`. + `update_op` increments `total` with the reduced sum of the product of `values` + and `weights`, and it increments `count` with the reduced sum of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + values: A `Tensor` of arbitrary dimensions. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `values`, and must be broadcastable to `values` (i.e., all dimensions must + be either `1`, or the same as the corresponding `values` dimension). + metrics_collections: An optional list of collections that `mean` + should be added to. + updates_collections: An optional list of collections that `update_op` + should be added to. + name: An optional variable_scope name. + + Returns: + mean: A float `Tensor` representing the current mean, the value of `total` + divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `mean_value`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match `values`, + or if either `metrics_collections` or `updates_collections` are not a list + or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.mean_tensor is not supported when ' + 'eager execution is enabled.') + + with variable_scope.variable_scope(name, 'mean', (values, weights)): + values = math_ops.cast(values, dtypes.float32) + total = metric_variable( + values.get_shape(), dtypes.float32, name='total_tensor') + count = metric_variable( + values.get_shape(), dtypes.float32, name='count_tensor') + + num_values = array_ops.ones_like(values) + if weights is not None: + values, _, weights = _remove_squeezable_dimensions( + predictions=values, labels=None, weights=weights) + weights = weights_broadcast_ops.broadcast_weights( + math_ops.cast(weights, dtypes.float32), values) + values = math_ops.multiply(values, weights) + num_values = math_ops.multiply(num_values, weights) + + update_total_op = state_ops.assign_add(total, values) + with ops.control_dependencies([values]): + update_count_op = state_ops.assign_add(count, num_values) + + compute_mean = lambda _, t, c: math_ops.div_no_nan( # pylint: disable=g-long-lambda + t, math_ops.maximum(c, 0), name='value') + + mean_t = _aggregate_across_replicas( + metrics_collections, compute_mean, total, count) + + update_op = math_ops.div_no_nan( + update_total_op, math_ops.maximum(update_count_op, 0), name='update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return mean_t, update_op + + +@tf_export(v1=['metrics.percentage_below']) +def percentage_below(values, + threshold, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the percentage of values less than the given threshold. + + The `percentage_below` function creates two local variables, + `total` and `count` that are used to compute the percentage of `values` that + fall below `threshold`. This rate is weighted by `weights`, and it is + ultimately returned as `percentage` which is an idempotent operation that + simply divides `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `percentage`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + values: A numeric `Tensor` of arbitrary size. + threshold: A scalar threshold. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `values`, and must be broadcastable to `values` (i.e., all dimensions must + be either `1`, or the same as the corresponding `values` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + percentage: A `Tensor` representing the current mean, the value of `total` + divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match `values`, + or if either `metrics_collections` or `updates_collections` are not a list + or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.percentage_below is not supported when ' + 'eager execution is enabled.') + + is_below_threshold = math_ops.cast( + math_ops.less(values, threshold), dtypes.float32) + return mean(is_below_threshold, weights, metrics_collections, + updates_collections, name or 'percentage_below_threshold') + + +def _count_condition(values, + weights=None, + metrics_collections=None, + updates_collections=None): + """Sums the weights of cases where the given values are True. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + values: A `bool` `Tensor` of arbitrary size. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `values`, and must be broadcastable to `values` (i.e., all dimensions must + be either `1`, or the same as the corresponding `values` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + + Returns: + value_tensor: A `Tensor` representing the current value of the metric. + update_op: An operation that accumulates the error from a batch of data. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match `values`, + or if either `metrics_collections` or `updates_collections` are not a list + or tuple. + """ + check_ops.assert_type(values, dtypes.bool) + count = metric_variable([], dtypes.float32, name='count') + + values = math_ops.cast(values, dtypes.float32) + if weights is not None: + with ops.control_dependencies((check_ops.assert_rank_in( + weights, (0, array_ops.rank(values))),)): + weights = math_ops.cast(weights, dtypes.float32) + values = math_ops.multiply(values, weights) + + value_tensor = _aggregate_variable(count, metrics_collections) + + update_op = state_ops.assign_add(count, math_ops.reduce_sum(values)) + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return value_tensor, update_op + + +@tf_export(v1=['metrics.false_negatives']) +def false_negatives(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the total number of false negatives. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + value_tensor: A `Tensor` representing the current value of the metric. + update_op: An operation that accumulates the error from a batch of data. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match `values`, + or if either `metrics_collections` or `updates_collections` are not a list + or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.false_negatives is not supported when ' + 'eager execution is enabled.') + + with variable_scope.variable_scope(name, 'false_negatives', + (predictions, labels, weights)): + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + is_false_negative = math_ops.logical_and( + math_ops.equal(labels, True), math_ops.equal(predictions, False)) + return _count_condition(is_false_negative, weights, metrics_collections, + updates_collections) + + +@tf_export(v1=['metrics.false_negatives_at_thresholds']) +def false_negatives_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes false negatives at provided threshold values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `false_negatives` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + false_negatives: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that updates the `false_negatives` variable and + returns its current value. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.false_negatives_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'false_negatives', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights=weights, includes=('fn',)) + + fn_value = _aggregate_variable(values['fn'], metrics_collections) + + if updates_collections: + ops.add_to_collections(updates_collections, update_ops['fn']) + + return fn_value, update_ops['fn'] + + +@tf_export(v1=['metrics.false_positives']) +def false_positives(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Sum the weights of false positives. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + value_tensor: A `Tensor` representing the current value of the metric. + update_op: An operation that accumulates the error from a batch of data. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.false_positives is not supported when ' + 'eager execution is enabled.') + + with variable_scope.variable_scope(name, 'false_positives', + (predictions, labels, weights)): + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + is_false_positive = math_ops.logical_and( + math_ops.equal(labels, False), math_ops.equal(predictions, True)) + return _count_condition(is_false_positive, weights, metrics_collections, + updates_collections) + + +@tf_export(v1=['metrics.false_positives_at_thresholds']) +def false_positives_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes false positives at provided threshold values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `false_positives` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + false_positives: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that updates the `false_positives` variable and + returns its current value. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.false_positives_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'false_positives', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights=weights, includes=('fp',)) + + fp_value = _aggregate_variable(values['fp'], metrics_collections) + + if updates_collections: + ops.add_to_collections(updates_collections, update_ops['fp']) + + return fp_value, update_ops['fp'] + + +@tf_export(v1=['metrics.true_negatives']) +def true_negatives(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Sum the weights of true_negatives. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + value_tensor: A `Tensor` representing the current value of the metric. + update_op: An operation that accumulates the error from a batch of data. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.true_negatives is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'true_negatives', + (predictions, labels, weights)): + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + is_true_negative = math_ops.logical_and( + math_ops.equal(labels, False), math_ops.equal(predictions, False)) + return _count_condition(is_true_negative, weights, metrics_collections, + updates_collections) + + +@tf_export(v1=['metrics.true_negatives_at_thresholds']) +def true_negatives_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes true negatives at provided threshold values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `true_negatives` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + true_negatives: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that updates the `true_negatives` variable and + returns its current value. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.true_negatives_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'true_negatives', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights=weights, includes=('tn',)) + + tn_value = _aggregate_variable(values['tn'], metrics_collections) + + if updates_collections: + ops.add_to_collections(updates_collections, update_ops['tn']) + + return tn_value, update_ops['tn'] + + +@tf_export(v1=['metrics.true_positives']) +def true_positives(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Sum the weights of true_positives. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that the metric + value variable should be added to. + updates_collections: An optional list of collections that the metric update + ops should be added to. + name: An optional variable_scope name. + + Returns: + value_tensor: A `Tensor` representing the current value of the metric. + update_op: An operation that accumulates the error from a batch of data. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.true_positives is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'true_positives', + (predictions, labels, weights)): + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + is_true_positive = math_ops.logical_and( + math_ops.equal(labels, True), math_ops.equal(predictions, True)) + return _count_condition(is_true_positive, weights, metrics_collections, + updates_collections) + + +@tf_export(v1=['metrics.true_positives_at_thresholds']) +def true_positives_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes true positives at provided threshold values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` whose shape matches `predictions`. Will be cast to + `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `true_positives` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + true_positives: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that updates the `true_positives` variable and + returns its current value. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.true_positives_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'true_positives', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights=weights, includes=('tp',)) + + tp_value = _aggregate_variable(values['tp'], metrics_collections) + + if updates_collections: + ops.add_to_collections(updates_collections, update_ops['tp']) + + return tp_value, update_ops['tp'] + + +@tf_export(v1=['metrics.precision']) +def precision(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the precision of the predictions with respect to the labels. + + The `precision` function creates two local variables, + `true_positives` and `false_positives`, that are used to compute the + precision. This value is ultimately returned as `precision`, an idempotent + operation that simply divides `true_positives` by the sum of `true_positives` + and `false_positives`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `precision`. `update_op` weights each prediction by the corresponding value in + `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `precision` should + be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + precision: Scalar float `Tensor` with the value of `true_positives` + divided by the sum of `true_positives` and `false_positives`. + update_op: `Operation` that increments `true_positives` and + `false_positives` variables appropriately and whose value matches + `precision`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.precision is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'precision', + (predictions, labels, weights)): + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + + true_p, true_positives_update_op = true_positives( + labels, + predictions, + weights, + metrics_collections=None, + updates_collections=None, + name=None) + false_p, false_positives_update_op = false_positives( + labels, + predictions, + weights, + metrics_collections=None, + updates_collections=None, + name=None) + + def compute_precision(tp, fp, name): + return array_ops.where( + math_ops.greater(tp + fp, 0), math_ops.divide(tp, tp + fp), 0, name) + + def once_across_replicas(_, true_p, false_p): + return compute_precision(true_p, false_p, 'value') + + p = _aggregate_across_replicas(metrics_collections, once_across_replicas, + true_p, false_p) + + update_op = compute_precision(true_positives_update_op, + false_positives_update_op, 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return p, update_op + + +@tf_export(v1=['metrics.precision_at_thresholds']) +def precision_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes precision values for different `thresholds` on `predictions`. + + The `precision_at_thresholds` function creates four local variables, + `true_positives`, `true_negatives`, `false_positives` and `false_negatives` + for various values of thresholds. `precision[i]` is defined as the total + weight of values in `predictions` above `thresholds[i]` whose corresponding + entry in `labels` is `True`, divided by the total weight of values in + `predictions` above `thresholds[i]` (`true_positives[i] / (true_positives[i] + + false_positives[i])`). + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `precision`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `auc` should be + added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + precision: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that increments the `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` variables that + are used in the computation of `precision`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.precision_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'precision_at_thresholds', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights, includes=('tp', 'fp')) + + # Avoid division by zero. + epsilon = 1e-7 + + def compute_precision(tp, fp, name): + return math_ops.divide(tp, epsilon + tp + fp, name='precision_' + name) + + def precision_across_replicas(_, values): + return compute_precision(values['tp'], values['fp'], 'value') + + prec = _aggregate_across_replicas( + metrics_collections, precision_across_replicas, values) + + update_op = compute_precision(update_ops['tp'], update_ops['fp'], + 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return prec, update_op + + +@tf_export(v1=['metrics.recall']) +def recall(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the recall of the predictions with respect to the labels. + + The `recall` function creates two local variables, `true_positives` + and `false_negatives`, that are used to compute the recall. This value is + ultimately returned as `recall`, an idempotent operation that simply divides + `true_positives` by the sum of `true_positives` and `false_negatives`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` that updates these variables and returns the `recall`. `update_op` + weights each prediction by the corresponding value in `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: The predicted values, a `Tensor` of arbitrary dimensions. Will + be cast to `bool`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `recall` should + be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + recall: Scalar float `Tensor` with the value of `true_positives` divided + by the sum of `true_positives` and `false_negatives`. + update_op: `Operation` that increments `true_positives` and + `false_negatives` variables appropriately and whose value matches + `recall`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.recall is not supported is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'recall', + (predictions, labels, weights)): + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=math_ops.cast(predictions, dtype=dtypes.bool), + labels=math_ops.cast(labels, dtype=dtypes.bool), + weights=weights) + + true_p, true_positives_update_op = true_positives( + labels, + predictions, + weights, + metrics_collections=None, + updates_collections=None, + name=None) + false_n, false_negatives_update_op = false_negatives( + labels, + predictions, + weights, + metrics_collections=None, + updates_collections=None, + name=None) + + def compute_recall(true_p, false_n, name): + return array_ops.where( + math_ops.greater(true_p + false_n, 0), + math_ops.divide(true_p, true_p + false_n), 0, name) + + def once_across_replicas(_, true_p, false_n): + return compute_recall(true_p, false_n, 'value') + + rec = _aggregate_across_replicas( + metrics_collections, once_across_replicas, true_p, false_n) + + update_op = compute_recall(true_positives_update_op, + false_negatives_update_op, 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return rec, update_op + + +def _at_k_name(name, k=None, class_id=None): + if k is not None: + name = '%s_at_%d' % (name, k) + else: + name = '%s_at_k' % (name) + if class_id is not None: + name = '%s_class%d' % (name, class_id) + return name + + +def _select_class_id(ids, selected_id): + """Filter all but `selected_id` out of `ids`. + + Args: + ids: `int64` `Tensor` or `SparseTensor` of IDs. + selected_id: Int id to select. + + Returns: + `SparseTensor` of same dimensions as `ids`. This contains only the entries + equal to `selected_id`. + """ + ids = sparse_tensor.convert_to_tensor_or_sparse_tensor(ids) + if isinstance(ids, sparse_tensor.SparseTensor): + return sparse_ops.sparse_retain(ids, math_ops.equal(ids.values, + selected_id)) + + # TODO(ptucker): Make this more efficient, maybe add a sparse version of + # tf.equal and tf.reduce_any? + + # Shape of filled IDs is the same as `ids` with the last dim collapsed to 1. + ids_shape = array_ops.shape(ids, out_type=dtypes.int64) + ids_last_dim = array_ops.size(ids_shape) - 1 + filled_selected_id_shape = math_ops.reduced_shape(ids_shape, + array_ops.reshape( + ids_last_dim, [1])) + + # Intersect `ids` with the selected ID. + filled_selected_id = array_ops.fill(filled_selected_id_shape, + math_ops.cast(selected_id, dtypes.int64)) + result = sets.set_intersection(filled_selected_id, ids) + return sparse_tensor.SparseTensor( + indices=result.indices, values=result.values, dense_shape=ids_shape) + + +def _maybe_select_class_id(labels, predictions_idx, selected_id=None): + """If class ID is specified, filter all other classes. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: `int64` `Tensor` of class IDs, with shape [D1, ... DN, k] + where N >= 1. Commonly, N=1 and `predictions_idx` has shape + [batch size, k]. + selected_id: Int id to select. + + Returns: + Tuple of `labels` and `predictions_idx`, possibly with classes removed. + """ + if selected_id is None: + return labels, predictions_idx + return (_select_class_id(labels, selected_id), + _select_class_id(predictions_idx, selected_id)) + + +def _sparse_true_positive_at_k(labels, + predictions_idx, + class_id=None, + weights=None, + name=None): + """Calculates true positives for recall@k and precision@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + name: Name of operation. + + Returns: + A [D1, ... DN] `Tensor` of true positive counts. + """ + with ops.name_scope(name, 'true_positives', + (predictions_idx, labels, weights)): + labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, + class_id) + tp = sets.set_size(sets.set_intersection(predictions_idx, labels)) + tp = math_ops.cast(tp, dtypes.float64) + if weights is not None: + with ops.control_dependencies((weights_broadcast_ops.assert_broadcastable( + weights, tp),)): + weights = math_ops.cast(weights, dtypes.float64) + tp = math_ops.multiply(tp, weights) + return tp + + +def _streaming_sparse_true_positive_at_k(labels, + predictions_idx, + k=None, + class_id=None, + weights=None, + name=None): + """Calculates weighted per step true positives for recall@k and precision@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + k: Integer, k for @k metric. This is only used for default op name. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + name: Name of new variable, and namespace for other dependent ops. + + Returns: + A tuple of `Variable` and update `Operation`. + + Raises: + ValueError: If `weights` is not `None` and has an incompatible shape. + """ + with ops.name_scope(name, _at_k_name('true_positive', k, class_id=class_id), + (predictions_idx, labels, weights)) as scope: + tp = _sparse_true_positive_at_k( + predictions_idx=predictions_idx, + labels=labels, + class_id=class_id, + weights=weights) + batch_total_tp = math_ops.cast(math_ops.reduce_sum(tp), dtypes.float64) + + var = metric_variable([], dtypes.float64, name=scope) + return var, state_ops.assign_add(var, batch_total_tp, name='update') + + +def _sparse_false_negative_at_k(labels, + predictions_idx, + class_id=None, + weights=None): + """Calculates false negatives for recall@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + + Returns: + A [D1, ... DN] `Tensor` of false negative counts. + """ + with ops.name_scope(None, 'false_negatives', + (predictions_idx, labels, weights)): + labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, + class_id) + fn = sets.set_size( + sets.set_difference(predictions_idx, labels, aminusb=False)) + fn = math_ops.cast(fn, dtypes.float64) + if weights is not None: + with ops.control_dependencies((weights_broadcast_ops.assert_broadcastable( + weights, fn),)): + weights = math_ops.cast(weights, dtypes.float64) + fn = math_ops.multiply(fn, weights) + return fn + + +def _streaming_sparse_false_negative_at_k(labels, + predictions_idx, + k, + class_id=None, + weights=None, + name=None): + """Calculates weighted per step false negatives for recall@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + k: Integer, k for @k metric. This is only used for default op name. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + name: Name of new variable, and namespace for other dependent ops. + + Returns: + A tuple of `Variable` and update `Operation`. + + Raises: + ValueError: If `weights` is not `None` and has an incompatible shape. + """ + with ops.name_scope(name, _at_k_name('false_negative', k, class_id=class_id), + (predictions_idx, labels, weights)) as scope: + fn = _sparse_false_negative_at_k( + predictions_idx=predictions_idx, + labels=labels, + class_id=class_id, + weights=weights) + batch_total_fn = math_ops.cast(math_ops.reduce_sum(fn), dtypes.float64) + + var = metric_variable([], dtypes.float64, name=scope) + return var, state_ops.assign_add(var, batch_total_fn, name='update') + + +@tf_export(v1=['metrics.recall_at_k']) +def recall_at_k(labels, + predictions, + k, + class_id=None, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes recall@k of the predictions with respect to sparse labels. + + If `class_id` is specified, we calculate recall by considering only the + entries in the batch for which `class_id` is in the label, and computing + the fraction of them for which `class_id` is in the top-k `predictions`. + If `class_id` is not specified, we'll calculate recall as how often on + average a class among the labels of a batch entry is in the top-k + `predictions`. + + `sparse_recall_at_k` creates two local variables, + `true_positive_at_` and `false_negative_at_`, that are used to compute + the recall_at_k frequency. This frequency is ultimately returned as + `recall_at_`: an idempotent operation that simply divides + `true_positive_at_` by total (`true_positive_at_` + + `false_negative_at_`). + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `recall_at_`. Internally, a `top_k` operation computes a `Tensor` + indicating the top `k` `predictions`. Set operations applied to `top_k` and + `labels` calculate the true positives and false negatives weighted by + `weights`. Then `update_op` increments `true_positive_at_` and + `false_negative_at_` using these values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values + should be in range [0, num_classes), where num_classes is the last + dimension of `predictions`. Values outside this range always count + towards `false_negative_at_`. + predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where + N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. + The final dimension contains the logit values for each class. [D1, ... DN] + must match `labels`. + k: Integer, k for @k metric. + class_id: Integer class ID for which we want binary metrics. This should be + in range [0, num_classes), where num_classes is the last dimension of + `predictions`. If class_id is outside this range, the method returns NAN. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + recall: Scalar `float64` `Tensor` with the value of `true_positives` divided + by the sum of `true_positives` and `false_negatives`. + update_op: `Operation` that increments `true_positives` and + `false_negatives` variables appropriately, and whose value matches + `recall`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match + `predictions`, or if either `metrics_collections` or `updates_collections` + are not a list or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.recall_at_k is not ' + 'supported when eager execution is enabled.') + + with ops.name_scope(name, _at_k_name('recall', k, class_id=class_id), + (predictions, labels, weights)) as scope: + _, top_k_idx = nn.top_k(predictions, k) + return recall_at_top_k( + labels=labels, + predictions_idx=top_k_idx, + k=k, + class_id=class_id, + weights=weights, + metrics_collections=metrics_collections, + updates_collections=updates_collections, + name=scope) + + +@tf_export(v1=['metrics.recall_at_top_k']) +def recall_at_top_k(labels, + predictions_idx, + k=None, + class_id=None, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes recall@k of top-k predictions with respect to sparse labels. + + Differs from `recall_at_k` in that predictions must be in the form of top `k` + class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k` + for more details. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values + should be in range [0, num_classes), where num_classes is the last + dimension of `predictions`. Values outside this range always count + towards `false_negative_at_`. + predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. + Commonly, N=1 and predictions has shape [batch size, k]. The final + dimension contains the top `k` predicted class indices. [D1, ... DN] must + match `labels`. + k: Integer, k for @k metric. Only used for the default op name. + class_id: Integer class ID for which we want binary metrics. This should be + in range [0, num_classes), where num_classes is the last dimension of + `predictions`. If class_id is outside this range, the method returns NAN. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + recall: Scalar `float64` `Tensor` with the value of `true_positives` divided + by the sum of `true_positives` and `false_negatives`. + update_op: `Operation` that increments `true_positives` and + `false_negatives` variables appropriately, and whose value matches + `recall`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match + `predictions`, or if either `metrics_collections` or `updates_collections` + are not a list or tuple. + """ + with ops.name_scope(name, _at_k_name('recall', k, class_id=class_id), + (predictions_idx, labels, weights)) as scope: + labels = _maybe_expand_labels(labels, predictions_idx) + top_k_idx = math_ops.cast(predictions_idx, dtypes.int64) + tp, tp_update = _streaming_sparse_true_positive_at_k( + predictions_idx=top_k_idx, + labels=labels, + k=k, + class_id=class_id, + weights=weights) + fn, fn_update = _streaming_sparse_false_negative_at_k( + predictions_idx=top_k_idx, + labels=labels, + k=k, + class_id=class_id, + weights=weights) + + def compute_recall(_, tp, fn): + return math_ops.divide(tp, math_ops.add(tp, fn), name=scope) + + metric = _aggregate_across_replicas( + metrics_collections, compute_recall, tp, fn) + + update = math_ops.divide( + tp_update, math_ops.add(tp_update, fn_update), name='update') + if updates_collections: + ops.add_to_collections(updates_collections, update) + return metric, update + + +@tf_export(v1=['metrics.recall_at_thresholds']) +def recall_at_thresholds(labels, + predictions, + thresholds, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes various recall values for different `thresholds` on `predictions`. + + The `recall_at_thresholds` function creates four local variables, + `true_positives`, `true_negatives`, `false_positives` and `false_negatives` + for various values of thresholds. `recall[i]` is defined as the total weight + of values in `predictions` above `thresholds[i]` whose corresponding entry in + `labels` is `True`, divided by the total weight of `True` values in `labels` + (`true_positives[i] / (true_positives[i] + false_negatives[i])`). + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the `recall`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + thresholds: A python list or tuple of float thresholds in `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that `recall` should be + added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + recall: A float `Tensor` of shape `[len(thresholds)]`. + update_op: An operation that increments the `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` variables that + are used in the computation of `recall`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.recall_at_thresholds is not ' + 'supported when eager execution is enabled.') + + with variable_scope.variable_scope(name, 'recall_at_thresholds', + (predictions, labels, weights)): + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights, includes=('tp', 'fn')) + + # Avoid division by zero. + epsilon = 1e-7 + + def compute_recall(tp, fn, name): + return math_ops.divide(tp, epsilon + tp + fn, name='recall_' + name) + + def recall_across_replicas(_, values): + return compute_recall(values['tp'], values['fn'], 'value') + + rec = _aggregate_across_replicas( + metrics_collections, recall_across_replicas, values) + + update_op = compute_recall(update_ops['tp'], update_ops['fn'], 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return rec, update_op + + +@tf_export(v1=['metrics.root_mean_squared_error']) +def root_mean_squared_error(labels, + predictions, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the root mean squared error between the labels and predictions. + + The `root_mean_squared_error` function creates two local variables, + `total` and `count` that are used to compute the root mean squared error. + This average is weighted by `weights`, and it is ultimately returned as + `root_mean_squared_error`: an idempotent operation that takes the square root + of the division of `total` by `count`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `root_mean_squared_error`. Internally, a `squared_error` operation computes + the element-wise square of the difference between `predictions` and `labels`. + Then `update_op` increments `total` with the reduced sum of the product of + `weights` and `squared_error`, and it increments `count` with the reduced sum + of `weights`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: A `Tensor` of the same shape as `predictions`. + predictions: A `Tensor` of arbitrary shape. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + metrics_collections: An optional list of collections that + `root_mean_squared_error` should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + root_mean_squared_error: A `Tensor` representing the current mean, the value + of `total` divided by `count`. + update_op: An operation that increments the `total` and `count` variables + appropriately and whose value matches `root_mean_squared_error`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, or if + `weights` is not `None` and its shape doesn't match `predictions`, or if + either `metrics_collections` or `updates_collections` are not a list or + tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.root_mean_squared_error is not ' + 'supported when eager execution is enabled.') + + predictions, labels, weights = _remove_squeezable_dimensions( + predictions=predictions, labels=labels, weights=weights) + mse, update_mse_op = mean_squared_error(labels, predictions, weights, None, + None, name or + 'root_mean_squared_error') + + once_across_replicas = lambda _, mse: math_ops.sqrt(mse) + rmse = _aggregate_across_replicas( + metrics_collections, once_across_replicas, mse) + + update_rmse_op = math_ops.sqrt(update_mse_op) + if updates_collections: + ops.add_to_collections(updates_collections, update_rmse_op) + + return rmse, update_rmse_op + + +@tf_export(v1=['metrics.sensitivity_at_specificity']) +def sensitivity_at_specificity(labels, + predictions, + specificity, + weights=None, + num_thresholds=200, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the specificity at a given sensitivity. + + The `sensitivity_at_specificity` function creates four local + variables, `true_positives`, `true_negatives`, `false_positives` and + `false_negatives` that are used to compute the sensitivity at the given + specificity value. The threshold for the given specificity value is computed + and used to evaluate the corresponding sensitivity. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `sensitivity`. `update_op` increments the `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` counts with the weight of each case + found in the `predictions` and `labels`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + For additional information about specificity and sensitivity, see the + following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + specificity: A scalar value in range `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + num_thresholds: The number of thresholds to use for matching the given + specificity. + metrics_collections: An optional list of collections that `sensitivity` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + sensitivity: A scalar `Tensor` representing the sensitivity at the given + `specificity` value. + update_op: An operation that increments the `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` variables + appropriately and whose value matches `sensitivity`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, if + `weights` is not `None` and its shape doesn't match `predictions`, or if + `specificity` is not between 0 and 1, or if either `metrics_collections` + or `updates_collections` are not a list or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.sensitivity_at_specificity is not ' + 'supported when eager execution is enabled.') + + if specificity < 0 or specificity > 1: + raise ValueError('`specificity` must be in the range [0, 1]. Currently, ' + f'`specificity` got {specificity}.') + + with variable_scope.variable_scope(name, 'sensitivity_at_specificity', + (predictions, labels, weights)): + kepsilon = 1e-7 # to account for floating point imprecisions + thresholds = [ + (i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2) + ] + thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] + + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights) + + def compute_sensitivity_at_specificity(tp, tn, fp, fn, name): + specificities = math_ops.divide(tn, tn + fp + kepsilon) + tf_index = math_ops.argmin(math_ops.abs(specificities - specificity), 0) + tf_index = math_ops.cast(tf_index, dtypes.int32) + + # Now, we have the implicit threshold, so compute the sensitivity: + return math_ops.divide(tp[tf_index], + tp[tf_index] + fn[tf_index] + kepsilon, name) + + def sensitivity_across_replicas(_, values): + return compute_sensitivity_at_specificity( + values['tp'], values['tn'], values['fp'], values['fn'], 'value') + + sensitivity = _aggregate_across_replicas( + metrics_collections, sensitivity_across_replicas, values) + + update_op = compute_sensitivity_at_specificity( + update_ops['tp'], update_ops['tn'], update_ops['fp'], update_ops['fn'], + 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return sensitivity, update_op + + +def _expand_and_tile(tensor, multiple, dim=0, name=None): + """Slice `tensor` shape in 2, then tile along the sliced dimension. + + A new dimension is inserted in shape of `tensor` before `dim`, then values are + tiled `multiple` times along the new dimension. + + Args: + tensor: Input `Tensor` or `SparseTensor`. + multiple: Integer, number of times to tile. + dim: Integer, dimension along which to tile. + name: Name of operation. + + Returns: + `Tensor` result of expanding and tiling `tensor`. + + Raises: + ValueError: if `multiple` is less than 1, or `dim` is not in + `[-rank(tensor), rank(tensor)]`. + """ + if multiple < 1: + raise ValueError(f'Invalid argument multiple={multiple} for ' + 'expand_and_tile call. `multiple` must be an integer > 0') + with ops.name_scope(name, 'expand_and_tile', + (tensor, multiple, dim)) as scope: + # Sparse. + tensor = sparse_tensor.convert_to_tensor_or_sparse_tensor(tensor) + if isinstance(tensor, sparse_tensor.SparseTensor): + if dim < 0: + expand_dims = array_ops.reshape( + array_ops.size(tensor.dense_shape) + dim, [1]) + else: + expand_dims = [dim] + expanded_shape = array_ops.concat( + (array_ops.slice(tensor.dense_shape, [0], expand_dims), [1], + array_ops.slice(tensor.dense_shape, expand_dims, [-1])), + 0, + name='expanded_shape') + expanded = sparse_ops.sparse_reshape( + tensor, shape=expanded_shape, name='expand') + if multiple == 1: + return expanded + return sparse_ops.sparse_concat( + dim - 1 if dim < 0 else dim, [expanded] * multiple, name=scope) + + # Dense. + expanded = array_ops.expand_dims( + tensor, dim if (dim >= 0) else (dim - 1), name='expand') + if multiple == 1: + return expanded + ones = array_ops.ones_like(array_ops.shape(tensor)) + tile_multiples = array_ops.concat( + (ones[:dim], (multiple,), ones[dim:]), 0, name='multiples') + return array_ops.tile(expanded, tile_multiples, name=scope) + + +def _num_relevant(labels, k): + """Computes number of relevant values for each row in labels. + + For labels with shape [D1, ... DN, num_labels], this is the minimum of + `num_labels` and `k`. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. + k: Integer, k for @k metric. + + Returns: + Integer `Tensor` of shape [D1, ... DN], where each value is the number of + relevant values for that row. + + Raises: + ValueError: if inputs have invalid dtypes or values. + """ + if k < 1: + raise ValueError(f'Invalid k={k}') + with ops.name_scope(None, 'num_relevant', (labels,)) as scope: + # For SparseTensor, calculate separate count for each row. + labels = sparse_tensor.convert_to_tensor_or_sparse_tensor(labels) + if isinstance(labels, sparse_tensor.SparseTensor): + return math_ops.minimum(sets.set_size(labels), k, name=scope) + + # The relevant values for each (d1, ... dN) is the minimum of k and the + # number of labels along the last dimension that are non-negative. + num_labels = math_ops.reduce_sum( + array_ops.where_v2(math_ops.greater_equal(labels, 0), + array_ops.ones_like(labels), + array_ops.zeros_like(labels)), + axis=-1) + return math_ops.minimum(num_labels, k, name=scope) + + +def _sparse_average_precision_at_top_k(labels, predictions_idx): + """Computes average precision@k of predictions with respect to sparse labels. + + From en.wikipedia.org/wiki/Information_retrieval#Average_precision, formula + for each row is: + + AveP = sum_{i=1...k} P_{i} * rel_{i} / num_relevant_items + + A "row" is the elements in dimension [D1, ... DN] of `predictions_idx`, + `labels`, and the result `Tensors`. In the common case, this is [batch_size]. + Each row of the results contains the average precision for that row. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. + Values should be non-negative. Negative values are ignored. + predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. + Commonly, N=1 and `predictions_idx` has shape [batch size, k]. The final + dimension must be set and contains the top `k` predicted class indices. + [D1, ... DN] must match `labels`. Values should be in range + [0, num_classes). + + Returns: + `float64` `Tensor` of shape [D1, ... DN], where each value is the average + precision for that row. + + Raises: + ValueError: if the last dimension of predictions_idx is not set. + """ + with ops.name_scope(None, 'average_precision', + (predictions_idx, labels)) as scope: + predictions_idx = math_ops.cast( + predictions_idx, dtypes.int64, name='predictions_idx') + if predictions_idx.get_shape().ndims == 0: + raise ValueError('The rank of `predictions_idx` must be at least 1.') + k = predictions_idx.get_shape().as_list()[-1] + if k is None: + raise ValueError('The last dimension of predictions_idx must be set. ' + 'Currently, it is None.') + labels = _maybe_expand_labels(labels, predictions_idx) + + # Expand dims to produce [D1, ... DN, k, 1] tensor. This gives us a separate + # prediction for each k, so we can calculate separate true positive values + # for each k. + predictions_idx_per_k = array_ops.expand_dims( + predictions_idx, -1, name='predictions_idx_per_k') + + # Replicate labels k times to produce [D1, ... DN, k, num_labels] tensor. + labels_per_k = _expand_and_tile( + labels, multiple=k, dim=-1, name='labels_per_k') + + # The following tensors are all of shape [D1, ... DN, k], containing values + # per row, per k value. + # `relevant_per_k` (int32) - Relevance indicator, 1 if the prediction at + # that k value is correct, 0 otherwise. This is the "rel_{i}" term from + # the formula above. + # `tp_per_k` (int32) - True positive counts. + # `retrieved_per_k` (int32) - Number of predicted values at each k. This is + # the precision denominator. + # `precision_per_k` (float64) - Precision at each k. This is the "P_{i}" + # term from the formula above. + # `relevant_precision_per_k` (float64) - Relevant precisions; i.e., + # precisions at all k for which relevance indicator is true. + relevant_per_k = _sparse_true_positive_at_k( + labels_per_k, predictions_idx_per_k, name='relevant_per_k') + tp_per_k = math_ops.cumsum(relevant_per_k, axis=-1, name='tp_per_k') + retrieved_per_k = math_ops.cumsum( + array_ops.ones_like(relevant_per_k), axis=-1, name='retrieved_per_k') + precision_per_k = math_ops.divide( + math_ops.cast(tp_per_k, dtypes.float64), + math_ops.cast(retrieved_per_k, dtypes.float64), + name='precision_per_k') + relevant_precision_per_k = math_ops.multiply( + precision_per_k, + math_ops.cast(relevant_per_k, dtypes.float64), + name='relevant_precision_per_k') + + # Reduce along k dimension to get the sum, yielding a [D1, ... DN] tensor. + precision_sum = math_ops.reduce_sum( + relevant_precision_per_k, axis=(-1,), name='precision_sum') + + # Divide by number of relevant items to get average precision. These are + # the "num_relevant_items" and "AveP" terms from the formula above. + num_relevant_items = math_ops.cast(_num_relevant(labels, k), dtypes.float64) + return math_ops.divide(precision_sum, num_relevant_items, name=scope) + + +def _streaming_sparse_average_precision_at_top_k(labels, + predictions_idx, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes average precision@k of predictions with respect to sparse labels. + + `sparse_average_precision_at_top_k` creates two local variables, + `average_precision_at_/total` and `average_precision_at_/max`, that + are used to compute the frequency. This frequency is ultimately returned as + `average_precision_at_`: an idempotent operation that simply divides + `average_precision_at_/total` by `average_precision_at_/max`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `precision_at_`. Set operations applied to `top_k` and `labels` calculate + the true positives and false positives weighted by `weights`. Then `update_op` + increments `true_positive_at_` and `false_positive_at_` using these + values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. + Values should be non-negative. Negative values are ignored. + predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. + Commonly, N=1 and `predictions_idx` has shape [batch size, k]. The final + dimension contains the top `k` predicted class indices. [D1, ... DN] must + match `labels`. Values should be in range [0, num_classes). + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + mean_average_precision: Scalar `float64` `Tensor` with the mean average + precision values. + update: `Operation` that increments variables appropriately, and whose + value matches `metric`. + """ + with ops.name_scope(name, 'average_precision_at_top_k', + (predictions_idx, labels, weights)) as scope: + # Calculate per-example average precision, and apply weights. + average_precision = _sparse_average_precision_at_top_k( + predictions_idx=predictions_idx, labels=labels) + if weights is not None: + weights = weights_broadcast_ops.broadcast_weights( + math_ops.cast(weights, dtypes.float64), average_precision) + average_precision = math_ops.multiply(average_precision, weights) + + # Create accumulation variables and update ops for max average precision and + # total average precision. + with ops.name_scope(None, 'max', (average_precision,)) as max_scope: + # `max` is the max possible precision. Since max for any row is 1.0: + # - For the unweighted case, this is just the number of rows. + # - For the weighted case, it's the sum of the weights broadcast across + # `average_precision` rows. + max_var = metric_variable([], dtypes.float64, name=max_scope) + if weights is None: + batch_max = math_ops.cast( + array_ops.size(average_precision, name='batch_max'), dtypes.float64) + else: + batch_max = math_ops.reduce_sum(weights, name='batch_max') + max_update = state_ops.assign_add(max_var, batch_max, name='update') + with ops.name_scope(None, 'total', (average_precision,)) as total_scope: + total_var = metric_variable([], dtypes.float64, name=total_scope) + batch_total = math_ops.reduce_sum(average_precision, name='batch_total') + total_update = state_ops.assign_add(total_var, batch_total, name='update') + + # Divide total by max to get mean, for both vars and the update ops. + def precision_across_replicas(_, total_var, max_var): + return _safe_scalar_div(total_var, max_var, name='mean') + + mean_average_precision = _aggregate_across_replicas( + metrics_collections, precision_across_replicas, total_var, max_var) + + update = _safe_scalar_div(total_update, max_update, name=scope) + if updates_collections: + ops.add_to_collections(updates_collections, update) + + return mean_average_precision, update + + +def _clean_out_of_range_indices(labels, num_classes): + """Replaces large out-of-range labels by small out-of-range labels. + + Replaces any value in `labels` that is greater or equal to `num_classes` by + -1. Do this conditionally for efficiency in case there are no such values. + + Args: + labels: `int64` `Tensor` or `SparseTensor`. + num_classes: `int64` scalar `Tensor`. + Returns: + An `int64` `Tensor` or `SparseTensor` as `labels` with indices greater + or equal to num_classes replaced by -1. + """ + + def _labels_is_sparse(): + """Returns true is `labels` is a sparse tensor.""" + return isinstance(labels, (sparse_tensor.SparseTensor, + sparse_tensor.SparseTensorValue)) + + def _clean_out_of_range(values): + """Replaces by -1 any large out-of-range `values`.""" + return array_ops.where_v2(math_ops.greater_equal(values, num_classes), + -1 * array_ops.ones_like(values), values) + + def _clean_labels_out_of_range(): + """Replaces by -1 ane large out-of-range values in `labels`.""" + if _labels_is_sparse(): + return type(labels)(indices=labels.indices, + values=_clean_out_of_range(labels.values), + dense_shape=labels.dense_shape) + else: + return _clean_out_of_range(labels) + + max_labels = math_ops.reduce_max( + labels.values if _labels_is_sparse() else labels) + return cond.cond( + math_ops.greater_equal(max_labels, num_classes), + _clean_labels_out_of_range, + lambda: labels) + + +@tf_export(v1=['metrics.sparse_average_precision_at_k']) +@deprecated(None, 'Use average_precision_at_k instead') +def sparse_average_precision_at_k(labels, + predictions, + k, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Renamed to `average_precision_at_k`, please use that method instead.""" + return average_precision_at_k( + labels=labels, + predictions=predictions, + k=k, + weights=weights, + metrics_collections=metrics_collections, + updates_collections=updates_collections, + name=name) + + +@tf_export(v1=['metrics.average_precision_at_k']) +def average_precision_at_k(labels, + predictions, + k, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes average precision@k of predictions with respect to sparse labels. + + `average_precision_at_k` creates two local variables, + `average_precision_at_/total` and `average_precision_at_/max`, that + are used to compute the frequency. This frequency is ultimately returned as + `average_precision_at_`: an idempotent operation that simply divides + `average_precision_at_/total` by `average_precision_at_/max`. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `precision_at_`. Internally, a `top_k` operation computes a `Tensor` + indicating the top `k` `predictions`. Set operations applied to `top_k` and + `labels` calculate the true positives and false positives weighted by + `weights`. Then `update_op` increments `true_positive_at_` and + `false_positive_at_` using these values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values + should be in range [0, num_classes), where num_classes is the last + dimension of `predictions`. Values outside this range are ignored. + predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where + N >= 1. Commonly, N=1 and `predictions` has shape + [batch size, num_classes]. The final dimension contains the logit values + for each class. [D1, ... DN] must match `labels`. + k: Integer, k for @k metric. This will calculate an average precision for + range `[1,k]`, as documented above. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + mean_average_precision: Scalar `float64` `Tensor` with the mean average + precision values. + update: `Operation` that increments variables appropriately, and whose + value matches `metric`. + + Raises: + ValueError: if k is invalid. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.sparse_average_precision_at_k is not ' + 'supported when eager execution is enabled.') + + if k < 1: + raise ValueError(f'Invalid k={k}. `k` should be >= 1.') + with ops.name_scope(name, _at_k_name('average_precision', k), + (predictions, labels, weights)) as scope: + # Calculate top k indices to produce [D1, ... DN, k] tensor. + _, predictions_idx = nn.top_k(predictions, k) + # The documentation states that labels should be in [0, ..., num_classes), + # but num_classes is lost when predictions_idx replaces predictions. + # For conformity with the documentation, any label >= num_classes, which is + # ignored, is replaced by -1. + labels = _clean_out_of_range_indices( + labels, math_ops.cast(array_ops.shape(predictions)[-1], dtypes.int64)) + return _streaming_sparse_average_precision_at_top_k( + labels=labels, + predictions_idx=predictions_idx, + weights=weights, + metrics_collections=metrics_collections, + updates_collections=updates_collections, + name=scope) + + +def _sparse_false_positive_at_k(labels, + predictions_idx, + class_id=None, + weights=None): + """Calculates false positives for precision@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + + Returns: + A [D1, ... DN] `Tensor` of false positive counts. + """ + with ops.name_scope(None, 'false_positives', + (predictions_idx, labels, weights)): + labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, + class_id) + fp = sets.set_size( + sets.set_difference(predictions_idx, labels, aminusb=True)) + fp = math_ops.cast(fp, dtypes.float64) + if weights is not None: + with ops.control_dependencies((weights_broadcast_ops.assert_broadcastable( + weights, fp),)): + weights = math_ops.cast(weights, dtypes.float64) + fp = math_ops.multiply(fp, weights) + return fp + + +def _streaming_sparse_false_positive_at_k(labels, + predictions_idx, + k=None, + class_id=None, + weights=None, + name=None): + """Calculates weighted per step false positives for precision@k. + + If `class_id` is specified, calculate binary true positives for `class_id` + only. + If `class_id` is not specified, calculate metrics for `k` predicted vs + `n` label classes, where `n` is the 2nd dimension of `labels`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of + target classes for the associated prediction. Commonly, N=1 and `labels` + has shape [batch_size, num_labels]. [D1, ... DN] must match + `predictions_idx`. + predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, + top `k` predicted classes. For rank `n`, the first `n-1` dimensions must + match `labels`. + k: Integer, k for @k metric. This is only used for default op name. + class_id: Class for which we want binary metrics. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + name: Name of new variable, and namespace for other dependent ops. + + Returns: + A tuple of `Variable` and update `Operation`. + + Raises: + ValueError: If `weights` is not `None` and has an incompatible shape. + """ + with ops.name_scope(name, _at_k_name('false_positive', k, class_id=class_id), + (predictions_idx, labels, weights)) as scope: + fp = _sparse_false_positive_at_k( + predictions_idx=predictions_idx, + labels=labels, + class_id=class_id, + weights=weights) + batch_total_fp = math_ops.cast(math_ops.reduce_sum(fp), dtypes.float64) + + var = metric_variable([], dtypes.float64, name=scope) + return var, state_ops.assign_add(var, batch_total_fp, name='update') + + +@tf_export(v1=['metrics.precision_at_top_k']) +def precision_at_top_k(labels, + predictions_idx, + k=None, + class_id=None, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes precision@k of the predictions with respect to sparse labels. + + Differs from `sparse_precision_at_k` in that predictions must be in the form + of top `k` class indices, whereas `sparse_precision_at_k` expects logits. + Refer to `sparse_precision_at_k` for more details. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values + should be in range [0, num_classes), where num_classes is the last + dimension of `predictions`. Values outside this range are ignored. + predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where + N >= 1. Commonly, N=1 and predictions has shape [batch size, k]. + The final dimension contains the top `k` predicted class indices. + [D1, ... DN] must match `labels`. + k: Integer, k for @k metric. Only used for the default op name. + class_id: Integer class ID for which we want binary metrics. This should be + in range [0, num_classes], where num_classes is the last dimension of + `predictions`. If `class_id` is outside this range, the method returns + NAN. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + precision: Scalar `float64` `Tensor` with the value of `true_positives` + divided by the sum of `true_positives` and `false_positives`. + update_op: `Operation` that increments `true_positives` and + `false_positives` variables appropriately, and whose value matches + `precision`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match + `predictions`, or if either `metrics_collections` or `updates_collections` + are not a list or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.precision_at_top_k is not ' + 'supported when eager execution is enabled.') + + with ops.name_scope(name, _at_k_name('precision', k, class_id=class_id), + (predictions_idx, labels, weights)) as scope: + labels = _maybe_expand_labels(labels, predictions_idx) + top_k_idx = math_ops.cast(predictions_idx, dtypes.int64) + tp, tp_update = _streaming_sparse_true_positive_at_k( + predictions_idx=top_k_idx, + labels=labels, + k=k, + class_id=class_id, + weights=weights) + fp, fp_update = _streaming_sparse_false_positive_at_k( + predictions_idx=top_k_idx, + labels=labels, + k=k, + class_id=class_id, + weights=weights) + + def precision_across_replicas(_, tp, fp): + return math_ops.divide(tp, math_ops.add(tp, fp), name=scope) + + metric = _aggregate_across_replicas( + metrics_collections, precision_across_replicas, tp, fp) + + update = math_ops.divide( + tp_update, math_ops.add(tp_update, fp_update), name='update') + if updates_collections: + ops.add_to_collections(updates_collections, update) + return metric, update + + +@tf_export(v1=['metrics.sparse_precision_at_k']) +@deprecated(None, 'Use precision_at_k instead') +def sparse_precision_at_k(labels, + predictions, + k, + class_id=None, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Renamed to `precision_at_k`, please use that method instead.""" + return precision_at_k( + labels=labels, + predictions=predictions, + k=k, + class_id=class_id, + weights=weights, + metrics_collections=metrics_collections, + updates_collections=updates_collections, + name=name) + + +@tf_export(v1=['metrics.precision_at_k']) +def precision_at_k(labels, + predictions, + k, + class_id=None, + weights=None, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes precision@k of the predictions with respect to sparse labels. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is in the top-k highest + `predictions`, and computing the fraction of them for which `class_id` is + indeed a correct label. + If `class_id` is not specified, we'll calculate precision as how often on + average a class among the top-k classes with the highest predicted values + of a batch entry is correct and can be found in the label for that entry. + + `precision_at_k` creates two local variables, + `true_positive_at_` and `false_positive_at_`, that are used to compute + the precision@k frequency. This frequency is ultimately returned as + `precision_at_`: an idempotent operation that simply divides + `true_positive_at_` by total (`true_positive_at_` + + `false_positive_at_`). + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `precision_at_`. Internally, a `top_k` operation computes a `Tensor` + indicating the top `k` `predictions`. Set operations applied to `top_k` and + `labels` calculate the true positives and false positives weighted by + `weights`. Then `update_op` increments `true_positive_at_` and + `false_positive_at_` using these values. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + Args: + labels: `int64` `Tensor` or `SparseTensor` with shape + [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies + num_labels=1. N >= 1 and num_labels is the number of target classes for + the associated prediction. Commonly, N=1 and `labels` has shape + [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values + should be in range [0, num_classes), where num_classes is the last + dimension of `predictions`. Values outside this range are ignored. + predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where + N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. + The final dimension contains the logit values for each class. [D1, ... DN] + must match `labels`. + k: Integer, k for @k metric. + class_id: Integer class ID for which we want binary metrics. This should be + in range [0, num_classes], where num_classes is the last dimension of + `predictions`. If `class_id` is outside this range, the method returns + NAN. + weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of + `labels`. If the latter, it must be broadcastable to `labels` (i.e., all + dimensions must be either `1`, or the same as the corresponding `labels` + dimension). + metrics_collections: An optional list of collections that values should + be added to. + updates_collections: An optional list of collections that updates should + be added to. + name: Name of new update operation, and namespace for other dependent ops. + + Returns: + precision: Scalar `float64` `Tensor` with the value of `true_positives` + divided by the sum of `true_positives` and `false_positives`. + update_op: `Operation` that increments `true_positives` and + `false_positives` variables appropriately, and whose value matches + `precision`. + + Raises: + ValueError: If `weights` is not `None` and its shape doesn't match + `predictions`, or if either `metrics_collections` or `updates_collections` + are not a list or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.sparse_precision_at_k is not ' + 'supported when eager execution is enabled.') + + with ops.name_scope(name, _at_k_name('precision', k, class_id=class_id), + (predictions, labels, weights)) as scope: + _, top_k_idx = nn.top_k(predictions, k) + return precision_at_top_k( + labels=labels, + predictions_idx=top_k_idx, + k=k, + class_id=class_id, + weights=weights, + metrics_collections=metrics_collections, + updates_collections=updates_collections, + name=scope) + + +@tf_export(v1=['metrics.specificity_at_sensitivity']) +def specificity_at_sensitivity(labels, + predictions, + sensitivity, + weights=None, + num_thresholds=200, + metrics_collections=None, + updates_collections=None, + name=None): + """Computes the specificity at a given sensitivity. + + The `specificity_at_sensitivity` function creates four local + variables, `true_positives`, `true_negatives`, `false_positives` and + `false_negatives` that are used to compute the specificity at the given + sensitivity value. The threshold for the given sensitivity value is computed + and used to evaluate the corresponding specificity. + + For estimation of the metric over a stream of data, the function creates an + `update_op` operation that updates these variables and returns the + `specificity`. `update_op` increments the `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` counts with the weight of each case + found in the `predictions` and `labels`. + + If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. + + For additional information about specificity and sensitivity, see the + following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity + + Args: + labels: The ground truth values, a `Tensor` whose dimensions must match + `predictions`. Will be cast to `bool`. + predictions: A floating point `Tensor` of arbitrary shape and whose values + are in the range `[0, 1]`. + sensitivity: A scalar value in range `[0, 1]`. + weights: Optional `Tensor` whose rank is either 0, or the same rank as + `labels`, and must be broadcastable to `labels` (i.e., all dimensions must + be either `1`, or the same as the corresponding `labels` dimension). + num_thresholds: The number of thresholds to use for matching the given + sensitivity. + metrics_collections: An optional list of collections that `specificity` + should be added to. + updates_collections: An optional list of collections that `update_op` should + be added to. + name: An optional variable_scope name. + + Returns: + specificity: A scalar `Tensor` representing the specificity at the given + `sensitivity` value. + update_op: An operation that increments the `true_positives`, + `true_negatives`, `false_positives` and `false_negatives` variables + appropriately and whose value matches `specificity`. + + Raises: + ValueError: If `predictions` and `labels` have mismatched shapes, if + `weights` is not `None` and its shape doesn't match `predictions`, or if + `sensitivity` is not between 0 and 1, or if either `metrics_collections` + or `updates_collections` are not a list or tuple. + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('tf.metrics.specificity_at_sensitivity is not ' + 'supported when eager execution is enabled.') + + if sensitivity < 0 or sensitivity > 1: + raise ValueError('`sensitivity` must be in the range [0, 1]. Currently, ' + f'`sensitivity` is {sensitivity}.') + + with variable_scope.variable_scope(name, 'specificity_at_sensitivity', + (predictions, labels, weights)): + kepsilon = 1e-7 # to account for floating point imprecisions + thresholds = [ + (i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2) + ] + thresholds = [0.0 - kepsilon] + thresholds + [1.0 - kepsilon] + + values, update_ops = _confusion_matrix_at_thresholds( + labels, predictions, thresholds, weights) + + def compute_specificity_at_sensitivity(tp, tn, fp, fn, name): + """Computes the specificity at the given sensitivity. + + Args: + tp: True positives. + tn: True negatives. + fp: False positives. + fn: False negatives. + name: The name of the operation. + + Returns: + The specificity using the aggregated values. + """ + sensitivities = math_ops.divide(tp, tp + fn + kepsilon) + + # We'll need to use this trick until tf.argmax allows us to specify + # whether we should use the first or last index in case of ties. + min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity)) + indices_at_minval = math_ops.equal( + math_ops.abs(sensitivities - sensitivity), min_val) + indices_at_minval = math_ops.cast(indices_at_minval, dtypes.int64) + indices_at_minval = math_ops.cumsum(indices_at_minval) + tf_index = math_ops.argmax(indices_at_minval, 0) + tf_index = math_ops.cast(tf_index, dtypes.int32) + + # Now, we have the implicit threshold, so compute the specificity: + return math_ops.divide(tn[tf_index], + tn[tf_index] + fp[tf_index] + kepsilon, name) + + def specificity_across_replicas(_, values): + return compute_specificity_at_sensitivity( + values['tp'], values['tn'], values['fp'], values['fn'], 'value') + + specificity = _aggregate_across_replicas( + metrics_collections, specificity_across_replicas, values) + + update_op = compute_specificity_at_sensitivity( + update_ops['tp'], update_ops['tn'], update_ops['fp'], update_ops['fn'], + 'update_op') + if updates_collections: + ops.add_to_collections(updates_collections, update_op) + + return specificity, update_op diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nccl_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nccl_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4d847acecda917bb96ee79e383915dbed84d33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nccl_ops.py @@ -0,0 +1,267 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for GPU collective operations implemented using NVIDIA nccl.""" +import threading + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import device +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_nccl_ops + + +_module_lock = threading.Lock() +_shared_name_counter = 0 + + +def all_sum(tensors): + """Returns a list of tensors with the all-reduce sum across `tensors`. + + The computation is done with an all-reduce operation, so if only some of the + returned tensors are evaluated then the computation will hang. + + Args: + tensors: The input tensors across which to sum; must be assigned + to GPU devices. + + Returns: + List of tensors, each with the sum of the input tensors, where tensor i has + the same device as `tensors[i]`. + """ + return _apply_all_reduce('sum', tensors) + + +@ops.RegisterGradient('NcclAllReduce') +def _all_sum_grad(op, grad): + """The gradients for `all_sum`. + + Args: + op: The `all_sum` `Operation` that we are differentiating. + grad: Gradient with respect to the output of the `all_sum` op. + + Returns: + The gradient with respect to the output of `all_sum`. + + Raises: + LookupError: If `reduction` is not `sum`. + """ + if op.get_attr('reduction') != b'sum': + raise LookupError('No gradient defined for NcclAllReduce except for ' + 'reduction="sum".') + + _check_device(grad, expected=op.device) + num_devices = op.get_attr('num_devices') + shared_name = op.get_attr('shared_name') + b'_grad' + + with ops.device(op.device): + return gen_nccl_ops.nccl_all_reduce( + input=grad, + reduction='sum', + num_devices=num_devices, + shared_name=shared_name) + + +def all_prod(tensors): + """Returns a list of tensors with the all-reduce product across `tensors`. + + The computation is done with an all-reduce operation, so if only some of the + returned tensors are evaluated then the computation will hang. + + Args: + tensors: The input tensors across which to multiply; must be assigned + to GPU devices. + + Returns: + List of tensors, each with the product of the input tensors, where tensor i + has the same device as `tensors[i]`. + """ + return _apply_all_reduce('prod', tensors) + + +def all_min(tensors): + """Returns a list of tensors with the all-reduce min across `tensors`. + + The computation is done with an all-reduce operation, so if only some of the + returned tensors are evaluated then the computation will hang. + + Args: + tensors: The input tensors across which to reduce; must be assigned + to GPU devices. + + Returns: + List of tensors, each with the minimum of the input tensors, where tensor i + has the same device as `tensors[i]`. + """ + return _apply_all_reduce('min', tensors) + + +def all_max(tensors): + """Returns a list of tensors with the all-reduce max across `tensors`. + + The computation is done with an all-reduce operation, so if only some of the + returned tensors are evaluated then the computation will hang. + + Args: + tensors: The input tensors across which to reduce; must be assigned + to GPU devices. + + Returns: + List of tensors, each with the maximum of the input tensors, where tensor i + has the same device as `tensors[i]`. + """ + return _apply_all_reduce('max', tensors) + + +def reduce_sum(tensors): + """Returns a tensor with the reduce sum across `tensors`. + + The computation is done with a reduce operation, so only one tensor is + returned. + + Args: + tensors: The input tensors across which to sum; must be assigned + to GPU devices. + + Returns: + A tensor containing the sum of the input tensors. + + Raises: + LookupError: If context is not currently using a GPU device. + """ + return _apply_reduce('sum', tensors) + + +@ops.RegisterGradient('NcclReduce') +def _reduce_sum_grad(op, grad): + """The gradients for input `Operation` of `reduce_sum`. + + Args: + op: The `sum send` `Operation` that we are differentiating. + grad: Gradient with respect to the output of the `reduce_sum` op. + + Returns: + The gradient with respect to the input of `reduce_sum` op. + + Raises: + LookupError: If the reduction attribute of op is not `sum`. + """ + if op.get_attr('reduction') != b'sum': + raise LookupError('No gradient defined for NcclAllReduce except for ' + 'reduction="sum".') + _check_device(grad, expected=op.device) + + with ops.device(op.device): + result = gen_nccl_ops.nccl_broadcast(input=grad, shape=grad.shape) + + return [result] * len(op.inputs) + + +def broadcast(tensor): + """Returns a tensor that can be efficiently transferred to other devices. + + Args: + tensor: The tensor to send; must be assigned to a GPU device. + + Returns: + A tensor with the value of `src_tensor`, which can be used as input to + ops on other GPU devices. + """ + _check_device(tensor) + + with ops.device(tensor.device): + return gen_nccl_ops.nccl_broadcast(input=tensor, shape=tensor.shape) + + +@ops.RegisterGradient('NcclBroadcast') +def _broadcast_grad(op, accumulated_grad): + """The gradients for input `Operation` of `broadcast`. + + Args: + op: The `broadcast send` `Operation` that we are differentiating. + accumulated_grad: Accumulated gradients with respect to the output of the + `broadcast` op. + + Returns: + Gradients with respect to the input of `broadcast`. + """ + # Grab inputs of accumulated_grad and replace accumulation with reduce_sum. + grads = [t for t in accumulated_grad.op.inputs] + for t in grads: + _check_device(t) + + with ops.device(op.device): + return gen_nccl_ops.nccl_reduce(input=grads, reduction='sum') + + +def _apply_all_reduce(reduction, tensors): + """Helper function for all_* functions.""" + if not tensors: + raise ValueError('Must pass >0 tensors to all reduce operations') + + shared_name = _get_shared_name() + + def _all_reduce(): + """Call nccl allreduce.""" + res = [] + for t in tensors: + _check_device(t) + with ops.device(t.device): + res.append( + gen_nccl_ops.nccl_all_reduce( + input=t, + reduction=reduction, + num_devices=len(tensors), + shared_name=shared_name)) + return res + + if context.executing_eagerly(): + # Nccl ops will block unless they are executed concurrently such as in a + # graph or a defun. + return def_function.function(_all_reduce)() + else: + return _all_reduce() + + +def _apply_reduce(reduction, tensors): + """Helper function for reduce_* functions.""" + if not tensors: + raise ValueError('Must pass >0 tensors to reduce operations') + + for t in tensors: + _check_device(t) + result = gen_nccl_ops.nccl_reduce(input=tensors, reduction=reduction) + try: + next(t for t in tensors if t.device == result.device) + except StopIteration: + raise ValueError('One input tensor must be assigned to current device') + return result + + +def _get_shared_name(): + global _shared_name_counter + + with _module_lock: + val = _shared_name_counter + _shared_name_counter += 1 + return 'c%s' % val + + +def _check_device(tensor, expected=None): + if not device.canonical_name(tensor.device): + raise ValueError(f'Device assignment for tensor={tensor} required for nccl ' + 'collective ops') + if expected and expected != tensor.device: + raise ValueError(f'Expected device {expected}, got {tensor.device} for ' + f'tensor={tensor}.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..753f1708494d6358deaa2b9668249c11eaffc14d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn.py @@ -0,0 +1,42 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +# pylint: disable=unused-import,g-bad-import-order +"""Neural network support. + +See the [Neural network](https://tensorflow.org/api_guides/python/nn) guide. +""" +import sys as _sys + +# pylint: disable=unused-import +from tensorflow.python.ops import ctc_ops as _ctc_ops +from tensorflow.python.ops import embedding_ops as _embedding_ops +from tensorflow.python.ops import nn_grad as _nn_grad +from tensorflow.python.ops import nn_fused_batch_norm_grad as _nn_fused_batch_norm_grad +from tensorflow.python.ops import nn_ops as _nn_ops +from tensorflow.python.ops.math_ops import sigmoid +from tensorflow.python.ops.math_ops import tanh +# pylint: enable=unused-import + +# Bring more nn-associated functionality into this package. +# go/tf-wildcard-import +# pylint: disable=wildcard-import,unused-import +from tensorflow.python.ops.ctc_ops import * +from tensorflow.python.ops.nn_impl import * +from tensorflow.python.ops.nn_impl_distribute import * +from tensorflow.python.ops.nn_ops import * +from tensorflow.python.ops.candidate_sampling_ops import * +from tensorflow.python.ops.embedding_ops import * +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_fused_batch_norm_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_fused_batch_norm_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..245f65cdf287527a8514fc08ad1ca7786077677a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_fused_batch_norm_grad.py @@ -0,0 +1,166 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Batch norm gradients for operators defined in nn_ops.py.""" + +from tensorflow.python.eager import backprop +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops + + +def _BatchNormGrad(grad_y, + x, + scale, + pop_mean, + pop_var, + epsilon, + data_format, + is_training=True): + """Returns the gradients for the 3 inputs of BatchNorm. + + Args: + grad_y: A `Tensor` of 4 or 5 dimensions for gradient for y. + x: A `Tensor` of 4 or 5 dimensions for x. + scale: A `Tensor` of 1 dimension for scaling. + pop_mean: A `Tensor` of 1 dimension for the population mean. Only used when + is_training=False. + pop_var: A `Tensor` of 1 dimension for the population variance. Only used + when is_training=False. + epsilon: A small float number added to the variance of x. + data_format: The data format for input. Either b"NHWC" or b"NCHW". + is_training: A bool value to indicate the operation is for training + (default) or inference. + + Returns: + A tuple (grad_x, grad_scale, grad_offset), where grad_x is the gradient + for x, grad_scale the gradient for scale, and grad_offset the gradient + for offset. + """ + x_dtype = x.dtype.base_dtype + if x_dtype == dtypes.float16 or x_dtype == dtypes.bfloat16: + # float16 math is too imprecise, so we do the batch norm gradient + # computations in float32. + x = math_ops.cast(x, dtypes.float32) + grad_y = math_ops.cast(grad_y, dtypes.float32) + if is_training: + if data_format == b"NHWC": + keepdims = False + reduce_axis = [0, 1, 2] + elif data_format == b"NDHWC": + keepdims = False + reduce_axis = [0, 1, 2, 3] + elif data_format == b"NCHW": + keepdims = True + reduce_axis = [0, 2, 3] + shape = [1, array_ops.size(scale), 1, 1] + scale = array_ops.reshape(scale, shape) + else: + keepdims = True + reduce_axis = [0, 2, 3, 4] + shape = [1, array_ops.size(scale), 1, 1, 1] + scale = array_ops.reshape(scale, shape) + mean_grad_y = math_ops.reduce_mean(grad_y, reduce_axis, keepdims=keepdims) + mean_x = math_ops.reduce_mean(x, reduce_axis, keepdims=keepdims) + var_x = math_ops.reduce_mean( + math_ops.squared_difference(x, array_ops.stop_gradient(mean_x)), + reduce_axis, + keepdims=keepdims) + grad_y_offset = grad_y - mean_grad_y + x_offset = x - mean_x + mean = math_ops.reduce_mean( + grad_y * x_offset, axis=reduce_axis, keepdims=keepdims) + grad_x = scale * math_ops.rsqrt(var_x + epsilon) * ( + grad_y_offset - math_ops.reciprocal(var_x + epsilon) * mean * x_offset) + grad_scale = math_ops.rsqrt(var_x + epsilon) * math_ops.reduce_sum( + grad_y * x_offset, axis=reduce_axis, keepdims=keepdims) + if data_format == b"NCHW" or data_format == b"NCDHW": + grad_scale = array_ops.squeeze(grad_scale) + grad_offset = math_ops.reduce_sum(grad_y, axis=reduce_axis) + return math_ops.cast(grad_x, x_dtype), grad_scale, grad_offset + else: + if data_format == b"NHWC": + reduce_axis = [0, 1, 2] + elif data_format == b"NDHWC": + reduce_axis = [0, 1, 2, 3] + elif data_format == b"NCHW": + reduce_axis = [0, 2, 3] + shape = [1, array_ops.size(pop_mean), 1, 1] + pop_mean = array_ops.reshape(pop_mean, shape) + pop_var = array_ops.reshape(pop_var, shape) + scale = array_ops.reshape(scale, shape) + else: + reduce_axis = [0, 2, 3, 4] + shape = [1, array_ops.size(pop_mean), 1, 1, 1] + pop_mean = array_ops.reshape(pop_mean, shape) + pop_var = array_ops.reshape(pop_var, shape) + scale = array_ops.reshape(scale, shape) + + grad_offset = math_ops.reduce_sum(grad_y, axis=reduce_axis) + var_rsqrt = math_ops.rsqrt(pop_var + epsilon) + grad_scale = math_ops.reduce_sum( + grad_y * (x - pop_mean) * var_rsqrt, axis=reduce_axis) + grad_x = grad_y * scale * var_rsqrt + return math_ops.cast(grad_x, x_dtype), grad_scale, grad_offset + + +@ops.RegisterGradient("FusedBatchNormGrad") +def _FusedBatchNormGradGrad(op: ops.Operation, *grad): + """Returns the gradients for the 3 inputs of FusedBatchNormGrad. + + Args: + op: The FusedBatchNormGradOp for which we need to compute gradients. + *grad: An argument list for tensors of gradients wrt the outputs with + grad[0] as grad_grad_x, grad[1] as grad_grad_scale, grad[2] as + grad_grad_offset. + + Returns: + A tuple (grad_grad_y, grad_x, grad_scale, None, None), where grad_grad_y + is the gradient for grad_y, grad_x the gradient for x, grad_scale the + gradient for scale. + """ + data_format = op.get_attr("data_format") + epsilon = op.get_attr("epsilon") + is_training = op.get_attr("is_training") + grad_y = op.inputs[0] + x = op.inputs[1] + scale = op.inputs[2] + pop_mean = op.inputs[3] + pop_var = op.inputs[4] + grad_grad_x = grad[0] + grad_grad_scale = grad[1] + grad_grad_offset = grad[2] + with backprop.GradientTape() as tape: + tape.watch(grad_y) + tape.watch(x) + tape.watch(scale) + grad_x, grad_scale, grad_offset = _BatchNormGrad( + grad_y, x, scale, pop_mean, pop_var, epsilon, data_format, is_training) + grad_initial = [grad_grad_x, grad_grad_scale, grad_grad_offset] + grad_grad_y, grad_x, grad_scale = tape.gradient( + [grad_x, grad_scale, grad_offset], [grad_y, x, scale], grad_initial) + return grad_grad_y, grad_x, grad_scale, None, None + + +@ops.RegisterGradient("FusedBatchNormGradV2") +def _FusedBatchNormGradGradV2(op: ops.Operation, *grad): + return _FusedBatchNormGradGrad(op, *grad) + + +@ops.RegisterGradient("FusedBatchNormGradV3") +def _FusedBatchNormGradGradV3(op: ops.Operation, *grad): + grad_grad_y, grad_x, grad_scale, _, _ = _FusedBatchNormGradGrad(op, *grad) + return grad_grad_y, grad_x, grad_scale, None, None, None + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..8260caf0787fd21f5c73f0a2f2445f979e2c3bfa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_grad.py @@ -0,0 +1,1123 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in nn_ops.py.""" + +import functools +import itertools +import operator + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import math_ops + + +@ops.RegisterGradient("Conv2DBackpropInput") +def _Conv2DBackpropInputGrad(op: ops.Operation, grad): + """The derivatives for deconvolution. + + Args: + op: the Deconvolution op. + grad: the tensor representing the gradient w.r.t. the output + + Returns: + the gradients w.r.t. the input and the filter + """ + # We call the gen_nn_ops backprop functions instead of nn_ops backprop + # functions for performance reasons in Eager mode. See _Conv2DGrad. + return [ + None, + gen_nn_ops.conv2d_backprop_filter( + grad, + array_ops.shape(op.inputs[1]), + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"), + data_format=op.get_attr("data_format").decode()), + gen_nn_ops.conv2d( + grad, + op.inputs[1], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"), + data_format=op.get_attr("data_format").decode()) + ] + + +@ops.RegisterGradient("Conv2DBackpropFilter") +def _Conv2DBackpropFilterGrad(op: ops.Operation, grad): + # We call the gen_nn_ops backprop functions instead of nn_ops backprop + # functions for performance reasons in Eager mode. See _Conv2DGrad. + return [ + gen_nn_ops.conv2d_backprop_input( + array_ops.shape(op.inputs[0]), + grad, + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"), + data_format=op.get_attr("data_format").decode()), None, + gen_nn_ops.conv2d( + op.inputs[0], + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + use_cudnn_on_gpu=op.get_attr("use_cudnn_on_gpu"), + data_format=op.get_attr("data_format").decode()) + ] + + +@ops.RegisterGradient("DepthwiseConv2dNativeBackpropInput") +def _DepthwiseConv2dNativeBackpropInputGrad(op: ops.Operation, grad): + """The derivatives for deconvolution. + + Args: + op: the Deconvolution op. + grad: the tensor representing the gradient w.r.t. the output + + Returns: + the gradients w.r.t. the input and the filter + """ + return [ + None, + gen_nn_ops.depthwise_conv2d_native_backprop_filter( + grad, + array_ops.shape(op.inputs[1]), + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")), + gen_nn_ops.depthwise_conv2d_native( + grad, + op.inputs[1], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")) + ] + + +@ops.RegisterGradient("DepthwiseConv2dNativeBackpropFilter") +def _DepthwiseConv2dNativeBackpropFilterGrad(op: ops.Operation, grad): + return [ + gen_nn_ops.depthwise_conv2d_native_backprop_input( + array_ops.shape(op.inputs[0]), + grad, + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")), None, + gen_nn_ops.depthwise_conv2d_native( + op.inputs[0], + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")) + ] + + +@ops.RegisterGradient("Conv3D") +def _Conv3DGrad(op: ops.Operation, grad): + data_format = op.get_attr("data_format").decode() + shape_0, shape_1 = array_ops.shape_n([op.inputs[0], op.inputs[1]]) + return [ + gen_nn_ops.conv3d_backprop_input_v2( + shape_0, + op.inputs[1], + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format), + gen_nn_ops.conv3d_backprop_filter_v2( + op.inputs[0], + shape_1, + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format, + ), + ] + + +@ops.RegisterGradient("Conv3DBackpropInputV2") +def _Conv3DBackpropInputGrad(op: ops.Operation, grad): + data_format = op.get_attr("data_format").decode() + return [ + None, + gen_nn_ops.conv3d_backprop_filter_v2( + grad, + array_ops.shape(op.inputs[1]), + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format), + gen_nn_ops.conv3d( + grad, + op.inputs[1], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format) + ] + + +@ops.RegisterGradient("Conv3DBackpropFilterV2") +def _Conv3DBackpropFilterGrad(op: ops.Operation, grad): + data_format = op.get_attr("data_format").decode() + return [ + gen_nn_ops.conv3d_backprop_input_v2( + array_ops.shape(op.inputs[0]), + grad, + op.inputs[2], + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format), None, + gen_nn_ops.conv3d( + op.inputs[0], + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=data_format) + ] + + +@ops.RegisterGradient("AvgPool3D") +def _AvgPool3DGrad(op: ops.Operation, grad): + return gen_nn_ops.avg_pool3d_grad( + array_ops.shape(op.inputs[0]), + grad, + ksize=op.get_attr("ksize"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format").decode()) + + +@ops.RegisterGradient("AvgPool3DGrad") +def _AvgPool3DGradGrad(op: ops.Operation, grad): + return (array_ops.stop_gradient(op.inputs[0]), + gen_nn_ops.avg_pool3d( + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + op.get_attr("padding"), + data_format=op.get_attr("data_format").decode())) + + +@ops.RegisterGradient("MaxPool3D") +def _MaxPool3DGrad(op: ops.Operation, grad): + return gen_nn_ops.max_pool3d_grad( + op.inputs[0], + op.outputs[0], + grad, + ksize=op.get_attr("ksize"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format").decode()) + + +@ops.RegisterGradient("MaxPool3DGrad") +def _MaxPool3DGradGrad(op: ops.Operation, grad): + return (array_ops.zeros_like(op.inputs[0]), + array_ops.zeros_like(op.inputs[1]), + gen_nn_ops.max_pool3d_grad_grad( + op.inputs[0], + op.inputs[1], + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format").decode())) + + +@ops.RegisterGradient("MaxPool3DGradGrad") +def _MaxPool3DGradGradGrad(op: ops.Operation, grad): + return (array_ops.zeros_like(op.inputs[0]), + array_ops.zeros_like(op.inputs[1]), + gen_nn_ops.max_pool3d_grad( + op.inputs[0], + op.inputs[1], + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format").decode())) + + +@ops.RegisterGradient("Softmax") +def _SoftmaxGrad(op: ops.Operation, grad_softmax): + """The derivative of the softmax nonlinearity. + + We assume that probs is of shape [batch_size * dim] + The formula for dsoftmax / dx = (diag(softmax) - softmax * softmax'). + This matrix is diagonal minus a rank one matrix, so it is easy to implement + as follows: + + grad_x = grad_softmax * softmax - sum(grad_softmax * softmax) * softmax + + Args: + op: the Softmax op. + grad_softmax: the tensor representing the gradient w.r.t. the softmax + output. + + Returns: + gradient w.r.t the input to the softmax + + """ + softmax = op.outputs[0] + sum_channels = math_ops.reduce_sum(grad_softmax * softmax, -1, keepdims=True) + return (grad_softmax - sum_channels) * softmax + + +@ops.RegisterGradient("LogSoftmax") +def _LogSoftmaxGrad(op: ops.Operation, grad): + """The gradient for log_softmax. + + log_softmax = input - log(sum(exp(input)) + dlog_softmax/dinput = diag - softmax(input) + + Args: + op: The log softmax op. + grad: The tensor representing the gradient w.r.t. the output. + + Returns: + The gradients w.r.t. the input. + """ + softmax = math_ops.exp(op.outputs[0]) + return grad - math_ops.reduce_sum(grad, -1, keepdims=True) * softmax + + +@ops.RegisterGradient("BiasAdd") +def _BiasAddGrad(op: ops.Operation, received_grad): + """Return the gradients for the 2 inputs of bias_op. + + The first input of unused_bias_op is the tensor t, and its gradient is + just the gradient the unused_bias_op received. + + The second input of unused_bias_op is the bias vector which has one fewer + dimension than "received_grad" (the batch dimension.) Its gradient is the + received gradient Summed on the batch dimension, which is the first dimension. + + Args: + op: The BiasOp for which we need to generate gradients. + received_grad: Tensor. The gradients passed to the BiasOp. + + Returns: + Two tensors, the first one for the "tensor" input of the BiasOp, + the second one for the "bias" input of the BiasOp. + """ + try: + data_format = op.get_attr("data_format") + except ValueError: + data_format = None + return (received_grad, + gen_nn_ops.bias_add_grad( + out_backprop=received_grad, data_format=data_format)) + + +@ops.RegisterGradient("BiasAddGrad") +def _BiasAddGradGrad(op: ops.Operation, received_grad): + """Gradient for the BiasAddGrad op. + + Args: + op: BiasAddGrad op for which we are calculating gradients. + received_grad: The gradients passed to the BiasAddGrad op. + + Returns: + A single gradient Tensor for the input to BiasAddGrad (which + is the gradient of the bias term in BiasAdd) + """ + + try: + data_format = op.get_attr("data_format") + except ValueError: + data_format = None + + shape = array_ops.shape(op.inputs[0]) + bias_shape = array_ops.shape(received_grad) + + if data_format == b"NCHW": + expanded_shape = array_ops.concat([ + array_ops.ones_like(shape[:1]), bias_shape, + array_ops.ones_like(shape[2:]) + ], 0) + tile_mults = array_ops.concat([shape[:1], [1], shape[2:]], 0) + else: + expanded_shape = array_ops.concat( + [array_ops.ones_like(shape[:-1]), bias_shape], 0) + tile_mults = array_ops.concat([shape[:-1], [1]], 0) + + expanded_grad = array_ops.reshape(received_grad, expanded_shape) + return array_ops.tile(expanded_grad, tile_mults) + + +@ops.RegisterGradient("BiasAddV1") +def _BiasAddGradV1(unused_bias_op: ops.Operation, received_grad): + """Return the gradients for the 2 inputs of bias_op. + + The first input of unused_bias_op is the tensor t, and its gradient is + just the gradient the unused_bias_op received. + + The second input of unused_bias_op is the bias vector which has one fewer + dimension than "received_grad" (the batch dimension.) Its gradient is the + received gradient Summed on the batch dimension, which is the first dimension. + + Args: + unused_bias_op: The BiasOp for which we need to generate gradients. + received_grad: Tensor. The gradients passed to the BiasOp. + + Returns: + Two tensors, the first one for the "tensor" input of the BiasOp, + the second one for the "bias" input of the BiasOp. + """ + reduction_dim_tensor = math_ops.range(array_ops.rank(received_grad) - 1) + return (received_grad, math_ops.reduce_sum(received_grad, + reduction_dim_tensor)) + + +@ops.RegisterGradient("Relu") +def _ReluGrad(op: ops.Operation, grad): + return gen_nn_ops.relu_grad(grad, op.outputs[0]) + + +@ops.RegisterGradient("EluGrad") +def _EluGradGrad(op: ops.Operation, grad): + elu_x = op.inputs[1] + return (gen_nn_ops.elu_grad(grad, elu_x), + array_ops.where( + elu_x < 0, grad * op.inputs[0], array_ops.zeros_like(elu_x))) + + +@ops.RegisterGradient("SeluGrad") +def _SeluGradGrad(op: ops.Operation, grad): + selu_x = op.inputs[1] + return (gen_nn_ops.selu_grad(grad, selu_x), + array_ops.where( + selu_x < 0., grad * op.inputs[0], array_ops.zeros_like(selu_x))) + + +@ops.RegisterGradient("Relu6") +def _Relu6Grad(op: ops.Operation, grad): + return gen_nn_ops.relu6_grad(grad, op.outputs[0]) + + +@ops.RegisterGradient("Relu6Grad") +def _Relu6GradGrad(op: ops.Operation, grad): + x = op.inputs[1] + return (gen_nn_ops.relu6_grad(grad, x), array_ops.zeros_like(x)) + + +@ops.RegisterGradient("LeakyRelu") +def _LeakyReluGrad(op: ops.Operation, grad): + x = op.inputs[0] + alpha = op.get_attr("alpha") + return gen_nn_ops.leaky_relu_grad(grad, x, alpha=alpha) + + +@ops.RegisterGradient("LeakyReluGrad") +def _LeakyReluGradGrad(op: ops.Operation, grad): + x = op.inputs[1] + alpha = op.get_attr("alpha") + return (gen_nn_ops.leaky_relu_grad(grad, x, + alpha=alpha), array_ops.zeros_like(x)) + + +@ops.RegisterGradient("Elu") +def _EluGrad(op: ops.Operation, grad): + return gen_nn_ops.elu_grad(grad, op.outputs[0]) + + +@ops.RegisterGradient("Selu") +def _SeluGrad(op: ops.Operation, grad): + return gen_nn_ops.selu_grad(grad, op.outputs[0]) + + +@ops.RegisterGradient("Softplus") +def _SoftplusGrad(op: ops.Operation, grad): + return grad * math_ops.sigmoid(op.inputs[0]) + + +@ops.RegisterGradient("SoftplusGrad") +def _SoftplusGradGrad(op: ops.Operation, grad): + # Let: + # y = tf.nn.softplus(x) + # dx = gen_nn_ops.softplus_grad(dy, x) = dy / (1 + exp(-x)) + # This op computes (ddy, d2x) from op.inputs == [dy, x] and grad == ddx. + dy, x = op.inputs + with ops.control_dependencies([grad]): + ddy = gen_nn_ops.softplus_grad(grad, x) + d2x = grad * dy / (math_ops.exp(-x) + 2.0 + math_ops.exp(x)) + return (ddy, d2x) + + +@ops.RegisterGradient("Softsign") +def _SoftsignGrad(op: ops.Operation, grad): + return gen_nn_ops.softsign_grad(grad, op.inputs[0]) + + +@ops.RegisterGradient("ReluGrad") +def _ReluGradGrad(op: ops.Operation, grad): + x = op.inputs[1] + return (gen_nn_ops.relu_grad(grad, x), array_ops.zeros_like(x)) + + +def _BroadcastMul(vec, mat): + """Multiply after broadcasting vec to match dimensions of mat. + + Args: + vec: A 1-D tensor of dimension [D0] + mat: A 2-D tensor of dimension [D0, D1] + + Returns: + A tensor of dimension [D0, D1], the result of vec * mat + """ + # Reshape vec to [D0, 1] + vec = array_ops.expand_dims(vec, -1) + return vec * mat + + +@ops.RegisterGradient("SoftmaxCrossEntropyWithLogits") +def _SoftmaxCrossEntropyWithLogitsGrad(op: ops.Operation, grad_loss, grad_grad): + """Gradient function for SoftmaxCrossEntropyWithLogits.""" + # grad_loss is the backprop for cost, and we multiply it with the gradients + # (which is output[1]) + # grad_grad is the backprop for softmax gradient. + # + # Second derivative is just softmax derivative w.r.t. logits. + softmax_grad = op.outputs[1] + grad = _BroadcastMul(grad_loss, softmax_grad) + + logits = op.inputs[0] + if (grad_grad is not None and + not getattr(grad_grad, "_is_zeros_tensor", False)): + softmax = gen_nn_ops.softmax(logits) + + grad += ((grad_grad - array_ops.squeeze( + math_ops.matmul( + array_ops.expand_dims(grad_grad, 1), + array_ops.expand_dims(softmax, 2)), + axis=1)) * softmax) + + return grad, _BroadcastMul(grad_loss, -gen_nn_ops.log_softmax(logits)) # pylint: disable=invalid-unary-operand-type + + +@ops.RegisterGradient("SparseSoftmaxCrossEntropyWithLogits") +def _SparseSoftmaxCrossEntropyWithLogitsGrad(op: ops.Operation, + grad_loss, + grad_grad): + """Gradient function for SparseSoftmaxCrossEntropyWithLogits.""" + # grad_loss is the backprop for cost, and we multiply it with the gradients + # (which is output[1]) + # grad_grad is the backprop for softmax gradient. + # There is no gradient for the labels + # + # Second derivative is just softmax derivative w.r.t. logits. + softmax_grad = op.outputs[1] + grad = _BroadcastMul(grad_loss, softmax_grad) + + logits = op.inputs[0] + if (grad_grad is not None and + not getattr(grad_grad, "_is_zeros_tensor", False)): + softmax = gen_nn_ops.softmax(logits) + + grad += ((grad_grad - array_ops.squeeze( + math_ops.matmul( + array_ops.expand_dims(grad_grad, 1), + array_ops.expand_dims(softmax, 2)), + axis=1)) * softmax) + + return grad, None + + +@ops.RegisterGradient("Conv2D") +def _Conv2DGrad(op: ops.Operation, grad): + """Gradient function for Conv2D.""" + dilations = op.get_attr("dilations") + strides = op.get_attr("strides") + padding = op.get_attr("padding") + explicit_paddings = op.get_attr("explicit_paddings") + use_cudnn_on_gpu = op.get_attr("use_cudnn_on_gpu") + data_format = op.get_attr("data_format") + shape_0, shape_1 = array_ops.shape_n([op.inputs[0], op.inputs[1]]) + + # We call the gen_nn_ops backprop functions instead of nn_ops backprop + # functions for performance reasons in Eager mode. gen_nn_ops functions take a + # `explicit_paddings` parameter, but nn_ops functions do not. So if we were + # to use the nn_ops functions, we would have to convert `padding` and + # `explicit_paddings` into a single `padding` parameter, increasing overhead + # in Eager mode. + return [ + gen_nn_ops.conv2d_backprop_input( + shape_0, + op.inputs[1], + grad, + dilations=dilations, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format), + gen_nn_ops.conv2d_backprop_filter( + op.inputs[0], + shape_1, + grad, + dilations=dilations, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format) + ] + + +@ops.RegisterGradient("DepthwiseConv2dNative") +def _DepthwiseConv2dNativeGrad(op: ops.Operation, grad): + return [ + gen_nn_ops.depthwise_conv2d_native_backprop_input( + array_ops.shape(op.inputs[0]), + op.inputs[1], + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")), + gen_nn_ops.depthwise_conv2d_native_backprop_filter( + op.inputs[0], + array_ops.shape(op.inputs[1]), + grad, + dilations=op.get_attr("dilations"), + strides=op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")) + ] + + +@ops.RegisterGradient("Dilation2D") +def _Dilation2DGrad(op: ops.Operation, grad): + return [ + gen_nn_ops.dilation2d_backprop_input(op.inputs[0], op.inputs[1], grad, + op.get_attr("strides"), + op.get_attr("rates"), + op.get_attr("padding")), + gen_nn_ops.dilation2d_backprop_filter(op.inputs[0], op.inputs[1], grad, + op.get_attr("strides"), + op.get_attr("rates"), + op.get_attr("padding")) + ] + + +@ops.RegisterGradient("LRN") +def _LRNGrad(op: ops.Operation, grad): + depth_radius = op.get_attr("depth_radius") + bias = op.get_attr("bias") + alpha = op.get_attr("alpha") + beta = op.get_attr("beta") + return [ + gen_nn_ops.lrn_grad(grad, op.inputs[0], op.outputs[0], depth_radius, bias, + alpha, beta) + ] + + +@ops.RegisterGradient("AvgPool") +def _AvgPoolGrad(op: ops.Operation, grad): + return gen_nn_ops.avg_pool_grad( + array_ops.shape(op.inputs[0]), + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + op.get_attr("padding"), + data_format=op.get_attr("data_format")) + + +@ops.RegisterGradient("AvgPoolGrad") +def _AvgPoolGradGrad(op: ops.Operation, grad): + return (array_ops.stop_gradient(op.inputs[0]), + gen_nn_ops.avg_pool( + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + op.get_attr("padding"), + data_format=op.get_attr("data_format"))) + + +@ops.RegisterGradient("MaxPool") +def _MaxPoolGrad(op: ops.Operation, grad): + return gen_nn_ops.max_pool_grad( + op.inputs[0], + op.outputs[0], + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + explicit_paddings=op.get_attr("explicit_paddings"), + data_format=op.get_attr("data_format")) + + +@ops.RegisterGradient("MaxPoolV2") +def _MaxPoolGradV2(op: ops.Operation, grad): + ksize = op.inputs[1] + strides = op.inputs[2] + return gen_nn_ops.max_pool_grad_v2( + op.inputs[0], + op.outputs[0], + grad, + ksize, + strides, + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format")), None, None + + +@ops.RegisterGradient("MaxPoolWithArgmax") +def _MaxPoolGradWithArgmax(op: ops.Operation, grad, unused_argmax_grad): + del unused_argmax_grad + return gen_nn_ops.max_pool_grad_with_argmax( + op.inputs[0], + grad, + op.outputs[1], + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + include_batch_in_index=op.get_attr("include_batch_in_index"), + ) + + +@ops.RegisterGradient("MaxPoolGrad") +def _MaxPoolGradGrad(op, grad): + return ( + array_ops.zeros_like(op.inputs[0]), + array_ops.zeros_like(op.inputs[1]), + gen_nn_ops.max_pool_grad_grad( + op.inputs[0], + op.inputs[1], + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format"), + ), + ) + + +@ops.RegisterGradient("MaxPoolGradV2") +def _MaxPoolGradGradV2(op: ops.Operation, grad): + ksize = op.inputs[3] + strides = op.inputs[4] + return ( + array_ops.zeros_like(op.inputs[0]), + array_ops.zeros_like(op.inputs[1]), + gen_nn_ops.max_pool_grad_grad_v2( + op.inputs[0], + op.inputs[1], + grad, + ksize, + strides, + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format"), + ), + None, + None, + ) + + +@ops.RegisterGradient("MaxPoolGradGrad") +def _MaxPoolGradGradGrad(op: ops.Operation, grad): + return ( + array_ops.zeros_like(op.inputs[0]), + array_ops.zeros_like(op.inputs[1]), + gen_nn_ops.max_pool_grad( + op.inputs[0], + op.inputs[1], + grad, + op.get_attr("ksize"), + op.get_attr("strides"), + padding=op.get_attr("padding"), + data_format=op.get_attr("data_format"), + ), + ) + + +@ops.RegisterGradient("FractionalMaxPool") +def _FractionalMaxPoolGrad( + op: ops.Operation, grad_0, unused_grad_1, unused_grad_2 +): + """Returns gradient for FractionalMaxPool. + + Since FractionalMaxPool has three outputs, there are three gradients passed in + for each of the outputs. Only the first one is useful, the other two gradients + are empty. + + Args: + op: The FractionalMaxPoolOp. + grad_0: Gradient with respect to op.outputs[0] + unused_grad_1: Gradient with respect to op.outputs[1]/row_seq. It is empty. + unused_grad_2: Gradient with respect to op.outputs[2]/col_seq. It is empty. + + Returns: + Input backprop for FractionalMaxPool op. + """ + return gen_nn_ops.fractional_max_pool_grad( + op.inputs[0], + op.outputs[0], + grad_0, + op.outputs[1], + op.outputs[2], + op.get_attr("overlapping"), + ) + + +@ops.RegisterGradient("FractionalAvgPool") +def _FractionalAvgPoolGrad( + op: ops.Operation, grad_0, unused_grad_1, unused_grad_2 +): + """Returns gradient for FractionalAvgPool. + + Since FractionalAvgPool has three outputs, there are three gradients passed in + for each of the outputs. Only the first one is useful, the other two gradients + are empty. + + Args: + op: The FractionalAvgPoolOp. + grad_0: Gradient with respect to op.outputs[0] + unused_grad_1: Gradient with respect to op.outputs[1]/row_seq. It is empty. + unused_grad_2: Gradient with respect to op.outputs[2]/col_seq. It is empty. + + Returns: + Input backprop for FractionalAvgPool op. + """ + return gen_nn_ops.fractional_avg_pool_grad(op.inputs[0].get_shape(), grad_0, + op.outputs[1], op.outputs[2], + op.get_attr("overlapping")) + + +@ops.RegisterGradient("BatchNormWithGlobalNormalization") +def _BatchNormWithGlobalNormalizationGrad(op: ops.Operation, grad): + """Return the gradients for the 5 inputs of BatchNormWithGlobalNormalization. + + We do not backprop anything for the mean and var intentionally as they are + not being trained with backprop in the operation. + + Args: + op: The BatchNormOp for which we need to generate gradients. + grad: Tensor. The gradients passed to the BatchNormOp. + + Returns: + dx: Backprop for input, which is (grad * (g * rsqrt(v + epsilon))) + dm: Backprop for mean, which is + sum_over_rest(grad * g) * (-1 / rsqrt(v + epsilon)) + dv: Backprop for variance, which is + sum_over_rest(grad * g * (x - m)) * (-1/2) * (v + epsilon) ^ (-3/2) + db: Backprop for beta, which is grad reduced in all except the + last dimension. + dg: Backprop for gamma, which is (grad * ((x - m) * rsqrt(v + epsilon))) + """ + dx, dm, dv, db, dg = gen_nn_ops.batch_norm_with_global_normalization_grad( + op.inputs[0], op.inputs[1], op.inputs[2], op.inputs[4], grad, + op.get_attr("variance_epsilon"), op.get_attr("scale_after_normalization")) + return dx, dm, dv, db, dg + + +def _BaseFusedBatchNormGrad(op: ops.Operation, version, *grad): + """Return the gradients for the 3 inputs of BatchNorm. + + Args: + op: The BatchNormOp for which we need to compute gradients. + version: Integer indicating which version to use of the fused batch + norm gradient. + *grad: An argument list for tensors of gradients wrt the outputs + with grad[0] as grad_y. + + Returns: + grad_x: gradient for x, which is scale * rsqrt(variance + epsilon) * + [grad_y - mean(grad_y) - (x - mean(x)) * + mean(grad_y * (x - mean(x))) / (variance + epsilon)] + in training mode; grad_y * scale * rsqrt(pop_variance + epsilon) + in freeze mode. + + grad_scale: gradient for scale, which is sum(grad_y * (x - mean(x)) * + rsqrt(variance + epsilon)) in training mode; + sum(grad_y * (x - pop_mean) * rsqrt(pop_variance + epsilon)) + in freeze mode. + + grad_offset: gradient for offset, which is sum(grad_y) in training mode; + sum(grad_y) in freeze mode. + """ + x = op.inputs[0] + grad_y = grad[0] + scale = op.inputs[1] + epsilon = op.get_attr("epsilon") + data_format = op.get_attr("data_format") + is_training = op.get_attr("is_training") + if version == 2: + grad_fun = gen_nn_ops.fused_batch_norm_grad_v3 + elif version == 1: + grad_fun = gen_nn_ops.fused_batch_norm_grad_v2 + else: + grad_fun = gen_nn_ops.fused_batch_norm_grad + if is_training: + args = { + "y_backprop": grad_y, + "x": x, + "scale": scale, + "reserve_space_1": op.outputs[3], + "reserve_space_2": op.outputs[4], + "epsilon": epsilon, + "data_format": data_format, + "is_training": is_training + } + if version == 2: + args["reserve_space_3"] = op.outputs[5] + dx, dscale, doffset, _, _ = grad_fun(**args) + else: + pop_mean = op.inputs[3] + pop_var = op.inputs[4] + if data_format == b"NCHW": + x = array_ops.transpose(x, [0, 2, 3, 1]) + grad_y = array_ops.transpose(grad_y, [0, 2, 3, 1]) + elif data_format == b"NCDHW": + x = array_ops.transpose(x, [0, 2, 3, 4, 1]) + grad_y = array_ops.transpose(grad_y, [0, 2, 3, 4, 1]) + target_data_format = ("NHWC" if data_format in (b"NCHW", + b"NHWC") else "NDHWC") + args = { + "y_backprop": grad_y, + "x": x, + "scale": scale, + "reserve_space_1": pop_mean, + "reserve_space_2": pop_var, + "epsilon": epsilon, + "data_format": target_data_format, + "is_training": is_training + } + if version == 2: + args["reserve_space_3"] = op.outputs[5] + dx, dscale, doffset, _, _ = grad_fun(**args) + if data_format == b"NCHW": + dx = array_ops.transpose(dx, [0, 3, 1, 2]) + elif data_format == b"NCDHW": + dx = array_ops.transpose(dx, [0, 4, 1, 2, 3]) + return dx, dscale, doffset, None, None + + +@ops.RegisterGradient("FusedBatchNorm") +def _FusedBatchNormGrad(op: ops.Operation, *grad): + return _BaseFusedBatchNormGrad(op, 0, *grad) + + +@ops.RegisterGradient("FusedBatchNormV2") +def _FusedBatchNormV2Grad(op: ops.Operation, *grad): + return _BaseFusedBatchNormGrad(op, 1, *grad) + + +@ops.RegisterGradient("FusedBatchNormV3") +def _FusedBatchNormV3Grad(op: ops.Operation, *grad): + return _BaseFusedBatchNormGrad(op, 2, *grad) + + +@ops.RegisterGradient("L2Loss") +def _L2LossGrad(op: ops.Operation, grad): + """Return the gradients for L2Loss. + + Args: + op: The L2LossOp for which we need to generate gradients. + grad: Tensor containing a single number. + + Returns: + The gradient, which is (x * grad). + """ + return op.inputs[0] * grad + + +@ops.RegisterGradient("TopK") +@ops.RegisterGradient("TopKV2") +def _TopKGrad(op: ops.Operation, grad, _): + """Return the gradients for TopK. + + Args: + op: The TopKOp for which we need to generate gradients. + grad: Tensor. The gradients passed to the TopKOp. + + Returns: + A list of two tensors, the first being the gradient w.r.t to the input and + TopK, and the second being the gradient w.r.t. to the indices (all zero). + """ + in_shape = array_ops.shape(op.inputs[0]) + ind_shape = array_ops.shape(op.outputs[1]) + + # int32 is not supported on GPU hence up-casting + ind_lastdim = array_ops.gather( + math_ops.cast(ind_shape, dtypes.int64), + array_ops.size(ind_shape) - 1) + # Flatten indices to 2D. + ind_2d = array_ops.reshape( + op.outputs[1], array_ops_stack.stack([-1, ind_lastdim])) + + in_lastdim = array_ops.gather( + math_ops.cast(in_shape, dtypes.int64), + array_ops.size(in_shape) - 1) + outerdim = array_ops.shape(ind_2d)[0] + # Compute linear indices (flattened to 1D). + ind = array_ops.reshape( + ind_2d + math_ops.cast( + array_ops.expand_dims( + math_ops.range(0, + math_ops.cast(outerdim, dtypes.int64) * in_lastdim, + in_lastdim), -1), dtypes.int32), [-1]) + + # Substitute grad to appropriate locations and fill the rest with zeros, + # finally reshaping it to the original input shape. + return [ + array_ops.reshape( + array_ops.scatter_nd( + array_ops.expand_dims(ind, -1), array_ops.reshape(grad, [-1]), + [math_ops.reduce_prod(in_shape)]), in_shape), + array_ops.zeros([], dtype=dtypes.int32) + ] + + +@ops.RegisterGradient("ApproxTopK") +def _ApproxTopKGradient(op: ops.Operation, grad, _): + """Return the gradients for ApproxTopK. + + Args: + op: The ApproxTopK for which we need to generate gradients. + grad: The gradients for backprop. + + Returns: + Scattered gradient based on the top-k indices. + """ + # The code below is to generate the correct index and value mapping for + # scatter_nd to work properly. + # + # We use static evaluations as much as possible to reduce the runtime cost. + # That's said, use operation.shape instead of array_ops.shape; + # and use functools.reduce(operator.mul, ...) instead of math_ops.reduce_prod + idx_shape = op.outputs[1].shape + lifted_idx_shape = idx_shape + [1] + flat_shape_len = functools.reduce(operator.mul, idx_shape) + rank = idx_shape.rank + reduction_dim = op.get_attr("reduction_dimension") + if reduction_dim < 0: + reduction_dim = rank + reduction_dim + + def GetLiftedIdx(d): + if d == reduction_dim: + return array_ops.reshape(op.outputs[1], lifted_idx_shape) + iota_len = idx_shape[d] + iota_shape = list(itertools.repeat(1, rank + 1)) + iota_shape[d] = iota_len + iota = array_ops.reshape(math_ops.range(iota_len), iota_shape) + return array_ops.broadcast_to(iota, lifted_idx_shape) + + lifted_idx = array_ops.concat( + list(GetLiftedIdx(d) for d in range(rank)), axis=rank) + flat_idx = array_ops.reshape(lifted_idx, [flat_shape_len, rank]) + flat_grad = array_ops.reshape(grad, [flat_shape_len]) + return array_ops.scatter_nd(flat_idx, flat_grad, op.inputs[0].shape) + + +@ops.RegisterGradient("NthElement") +def _NthElementGrad(op: ops.Operation, grad): + """Return the gradients for NthElement. + + Args: + op: The NthElementOp for which we need to generate gradients. + grad: Tensor. The gradients passed to the NthElementOp + + Returns: + A list of two tensors, the first being the gradient w.r.t. the input, + the second being the gradient w.r.t. the N (None). + """ + input = op.inputs[0] # pylint: disable=redefined-builtin + output = op.outputs[0] + + # Compute the number of elements which equal to output in each reduction + # dimension. If there are multiple elements then the gradient will be + # divided between them. + indicators = math_ops.cast( + math_ops.equal(array_ops.expand_dims(output, -1), input), grad.dtype) + + grad = array_ops.expand_dims(grad, -1) + num_selected = array_ops.expand_dims(math_ops.reduce_sum(indicators, -1), -1) + + return [math_ops.divide(indicators, num_selected) * grad, None] + + +def _MeanAggregator(inputs, segments): + """Replaces each segment with its mean along the last axis. + + Specifically, each value in the `inputs` tensor gets replaced by the mean + value computed from the values that belong to the same segment. + + Args: + inputs: A 2-tensor. Aggregation is done over dimension 1. + segments: A 2-tensor, same shape as `input`. + + Returns: + The result, same shape and type as `inputs`. + """ + result = [] + for inputs_i, segments_i in zip( + array_ops.split(inputs, inputs.shape[0]), + array_ops.split(segments, segments.shape[0])): + # Note that we do not use tf.math.segment_mean, as it has no TPU support. + means_i = math_ops.unsorted_segment_mean( + inputs_i, segments_i, num_segments=math_ops.reduce_max(segments_i) + 1) + result.append( + array_ops.reshape(array_ops.gather(means_i, segments_i), [-1])) + return array_ops_stack.stack(result, axis=0) + + +# We have to register the gradients for these ops so that tensorflow will know +# how to differentiate them. +@ops.RegisterGradient("IsotonicRegression") +def _IsotonicRegressionGrad(op: ops.Operation, grad_output, grad_segments): + """Gradient for the isotonic regression function. + + Args: + op: The IsotonicRegression tensorflow op. + grad_output: Tensor of incoming gradients with respect to the output. + grad_segments: Tensor of incoming gradients with respect to the segments. + + Returns: + A tensor, same size as `grad_output` with the gradient with respect to + the input. + """ + del grad_segments # Discrete, non-differentiable. + segments = op.outputs[1] + return _MeanAggregator(grad_output, segments) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..230b0ea3b6368e30138b6f59c0ef47e680e4d0ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl.py @@ -0,0 +1,2311 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Implementation of Neural Net (NN) functions.""" + +import math + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import candidate_sampling_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import ctc_ops # pylint: disable=unused-import +from tensorflow.python.ops import custom_gradient +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_fused_batch_norm_grad # pylint: disable=unused-import +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import device_context +from tensorflow.python.util import dispatch +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.deprecation import deprecated_argument_lookup +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("nn.log_poisson_loss") +@dispatch.add_dispatch_support +def log_poisson_loss(targets, log_input, compute_full_loss=False, name=None): + """Computes log Poisson loss given `log_input`. + + Gives the log-likelihood loss between the prediction and the target under the + assumption that the target has a Poisson distribution. + Caveat: By default, this is not the exact loss, but the loss minus a + constant term [log(z!)]. That has no effect for optimization, but + does not play well with relative loss comparisons. To compute an + approximation of the log factorial term, specify + compute_full_loss=True to enable Stirling's Approximation. + + For brevity, let `c = log(x) = log_input`, `z = targets`. The log Poisson + loss is + + -log(exp(-x) * (x^z) / z!) + = -log(exp(-x) * (x^z)) + log(z!) + ~ -log(exp(-x)) - log(x^z) [+ z * log(z) - z + 0.5 * log(2 * pi * z)] + [ Note the second term is the Stirling's Approximation for log(z!). + It is invariant to x and does not affect optimization, though + important for correct relative loss comparisons. It is only + computed when compute_full_loss == True. ] + = x - z * log(x) [+ z * log(z) - z + 0.5 * log(2 * pi * z)] + = exp(c) - z * c [+ z * log(z) - z + 0.5 * log(2 * pi * z)] + + Args: + targets: A `Tensor` of the same type and shape as `log_input`. + log_input: A `Tensor` of type `float32` or `float64`. + compute_full_loss: whether to compute the full loss. If false, a constant + term is dropped in favor of more efficient optimization. + name: A name for the operation (optional). + + Returns: + A `Tensor` of the same shape as `log_input` with the componentwise + logistic losses. + + Raises: + ValueError: If `log_input` and `targets` do not have the same shape. + """ + with ops.name_scope(name, "log_poisson_loss", [log_input, targets]) as name: + log_input = ops.convert_to_tensor(log_input, name="log_input") + targets = ops.convert_to_tensor(targets, name="targets") + try: + targets.get_shape().assert_is_compatible_with(log_input.get_shape()) + except ValueError: + raise ValueError( + "`log_input` and `targets` must have the same shape, received " + f"({log_input.get_shape()} vs {targets.get_shape()}).") + + result = math_ops.exp(log_input) - log_input * targets + if compute_full_loss: + # need to create constant tensors here so that their dtypes can be matched + # to that of the targets. + point_five = constant_op.constant(0.5, dtype=targets.dtype) + two_pi = constant_op.constant(2 * math.pi, dtype=targets.dtype) + + stirling_approx = (targets * math_ops.log(targets)) - targets + ( + point_five * math_ops.log(two_pi * targets)) + zeros = array_ops.zeros_like(targets, dtype=targets.dtype) + ones = array_ops.ones_like(targets, dtype=targets.dtype) + cond = math_ops.logical_and(targets >= zeros, targets <= ones) + result += array_ops.where(cond, zeros, stirling_approx) + return result + + +@tf_export(v1=["nn.sigmoid_cross_entropy_with_logits"]) +@dispatch.add_dispatch_support +def sigmoid_cross_entropy_with_logits( + labels=None, + logits=None, + name=None): + """See sigmoid_cross_entropy_with_logits_v2.""" + # pylint: disable=protected-access + nn_ops._ensure_xent_args("sigmoid_cross_entropy_with_logits", labels, logits) + # pylint: enable=protected-access + + with ops.name_scope(name, "logistic_loss", [logits, labels]) as name: + logits = ops.convert_to_tensor(logits, name="logits") + labels = ops.convert_to_tensor(labels, name="labels") + try: + labels.get_shape().assert_is_compatible_with(logits.get_shape()) + except ValueError: + raise ValueError("`logits` and `labels` must have the same shape, " + f"received ({logits.get_shape()} vs " + f"{labels.get_shape()}).") + + # The logistic loss formula from above is + # x - x * z + log(1 + exp(-x)) + # For x < 0, a more numerically stable formula is + # -x * z + log(1 + exp(x)) + # Note that these two expressions can be combined into the following: + # max(x, 0) - x * z + log(1 + exp(-abs(x))) + # To allow computing gradients at zero, we define custom versions of max and + # abs functions. + zeros = array_ops.zeros_like(logits, dtype=logits.dtype) + cond = (logits >= zeros) + relu_logits = array_ops.where(cond, logits, zeros) + neg_abs_logits = array_ops.where(cond, -logits, logits) # pylint: disable=invalid-unary-operand-type + return math_ops.add( + relu_logits - logits * labels, + math_ops.log1p(math_ops.exp(neg_abs_logits)), + name=name) + + +# Note: intentionally calling this v2 to not allow existing code with indirect +# imports to ignore the sentinel behavior. +@tf_export("nn.sigmoid_cross_entropy_with_logits", v1=[]) +@dispatch.register_binary_elementwise_api +@dispatch.add_dispatch_support +def sigmoid_cross_entropy_with_logits_v2( # pylint: disable=invalid-name + labels=None, + logits=None, + name=None): + r"""Computes sigmoid cross entropy given `logits`. + + Measures the probability error in tasks with two outcomes in which each + outcome is independent and need not have a fully certain label. For instance, + one could perform a regression where the probability of an event happening is + known and used as a label. This loss may also be used for binary + classification, where labels are either zero or one. + + For brevity, let `x = logits`, `z = labels`. The logistic loss is + + z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) + = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) + = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) + = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) + = (1 - z) * x + log(1 + exp(-x)) + = x - x * z + log(1 + exp(-x)) + + For x < 0, to avoid overflow in exp(-x), we reformulate the above + + x - x * z + log(1 + exp(-x)) + = log(exp(x)) - x * z + log(1 + exp(-x)) + = - x * z + log(1 + exp(x)) + + Hence, to ensure stability and avoid overflow, the implementation uses this + equivalent formulation + + max(x, 0) - x * z + log(1 + exp(-abs(x))) + + `logits` and `labels` must have the same type and shape. + + >>> logits = tf.constant([1., -1., 0., 1., -1., 0., 0.]) + >>> labels = tf.constant([0., 0., 0., 1., 1., 1., 0.5]) + >>> tf.nn.sigmoid_cross_entropy_with_logits( + ... labels=labels, logits=logits).numpy() + array([1.3132617, 0.3132617, 0.6931472, 0.3132617, 1.3132617, 0.6931472, + 0.6931472], dtype=float32) + + Compared to the losses which handle multiple outcomes, + `tf.nn.softmax_cross_entropy_with_logits` for general multi-class + classification and `tf.nn.sparse_softmax_cross_entropy_with_logits` for more + efficient multi-class classification with hard labels, + `sigmoid_cross_entropy_with_logits` is a slight simplification for binary + classification: + + sigmoid(x) = softmax([x, 0])[0] + + $$\frac{1}{1 + e^{-x}} = \frac{e^x}{e^x + e^0}$$ + + While `sigmoid_cross_entropy_with_logits` works for soft binary labels + (probabilities between 0 and 1), it can also be used for binary classification + where the labels are hard. There is an equivalence between all three symbols + in this case, with a probability 0 indicating the second class or 1 indicating + the first class: + + >>> sigmoid_logits = tf.constant([1., -1., 0.]) + >>> softmax_logits = tf.stack([sigmoid_logits, tf.zeros_like(sigmoid_logits)], + ... axis=-1) + >>> soft_binary_labels = tf.constant([1., 1., 0.]) + >>> soft_multiclass_labels = tf.stack( + ... [soft_binary_labels, 1. - soft_binary_labels], axis=-1) + >>> hard_labels = tf.constant([0, 0, 1]) + >>> tf.nn.sparse_softmax_cross_entropy_with_logits( + ... labels=hard_labels, logits=softmax_logits).numpy() + array([0.31326166, 1.3132616 , 0.6931472 ], dtype=float32) + >>> tf.nn.softmax_cross_entropy_with_logits( + ... labels=soft_multiclass_labels, logits=softmax_logits).numpy() + array([0.31326166, 1.3132616, 0.6931472], dtype=float32) + >>> tf.nn.sigmoid_cross_entropy_with_logits( + ... labels=soft_binary_labels, logits=sigmoid_logits).numpy() + array([0.31326166, 1.3132616, 0.6931472], dtype=float32) + + Args: + labels: A `Tensor` of the same type and shape as `logits`. Between 0 and 1, + inclusive. + logits: A `Tensor` of type `float32` or `float64`. Any real number. + name: A name for the operation (optional). + + Returns: + A `Tensor` of the same shape as `logits` with the componentwise + logistic losses. + + Raises: + ValueError: If `logits` and `labels` do not have the same shape. + """ + return sigmoid_cross_entropy_with_logits( + logits=logits, labels=labels, name=name) + + +sigmoid_cross_entropy_with_logits.__doc__ = ( + sigmoid_cross_entropy_with_logits_v2.__doc__) + + +@tf_export("nn.weighted_cross_entropy_with_logits", v1=[]) +@dispatch.add_dispatch_support +def weighted_cross_entropy_with_logits_v2(labels, logits, pos_weight, + name=None): + """Computes a weighted cross entropy. + + This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`, + allows one to trade off recall and precision by up- or down-weighting the + cost of a positive error relative to a negative error. + + The usual cross-entropy cost is defined as: + + labels * -log(sigmoid(logits)) + + (1 - labels) * -log(1 - sigmoid(logits)) + + A value `pos_weight > 1` decreases the false negative count, hence increasing + the recall. + Conversely setting `pos_weight < 1` decreases the false positive count and + increases the precision. + This can be seen from the fact that `pos_weight` is introduced as a + multiplicative coefficient for the positive labels term + in the loss expression: + + labels * -log(sigmoid(logits)) * pos_weight + + (1 - labels) * -log(1 - sigmoid(logits)) + + For brevity, let `x = logits`, `z = labels`, `q = pos_weight`. + The loss is: + + qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) + = qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) + = qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) + = qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) + = (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x)) + = (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x)) + + Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow, + the implementation uses + + (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0)) + + `logits` and `labels` must have the same type and shape. + + >>> labels = tf.constant([1., 0.5, 0.]) + >>> logits = tf.constant([1.5, -0.1, -10.]) + >>> tf.nn.weighted_cross_entropy_with_logits( + ... labels=labels, logits=logits, pos_weight=tf.constant(1.5)).numpy() + array([3.0211994e-01, 8.8049585e-01, 4.5776367e-05], dtype=float32) + >>> tf.nn.weighted_cross_entropy_with_logits( + ... labels=labels, logits=logits, pos_weight=tf.constant(0.5)).numpy() + array([1.00706644e-01, 5.08297503e-01, 4.57763672e-05], dtype=float32) + + Args: + labels: A `Tensor` of the same type and shape as `logits`, with values + between 0 and 1 inclusive. + logits: A `Tensor` of type `float32` or `float64`, any real numbers. + pos_weight: A coefficient to use on the positive examples, typically a + scalar but otherwise broadcastable to the shape of `logits`. Its value + should be non-negative. + name: A name for the operation (optional). + + Returns: + A `Tensor` of the same shape as `logits` with the componentwise + weighted logistic losses. + + Raises: + ValueError: If `logits` and `labels` do not have the same shape. + """ + with ops.name_scope(name, "logistic_loss", [logits, labels]) as name: + logits = ops.convert_to_tensor(logits, name="logits") + labels = ops.convert_to_tensor(labels, name="labels") + try: + labels.get_shape().assert_is_compatible_with(logits.get_shape()) + except ValueError: + raise ValueError("`logits` and `labels` must have the same shape, " + f"received ({logits.get_shape()} vs " + f"{labels.get_shape()}).") + + # The logistic loss formula from above is + # (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x)) + # For x < 0, a more numerically stable formula is + # (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(x)) - l * x + # To avoid branching, we use the combined version + # (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0)) + log_weight = 1 + (pos_weight - 1) * labels + return math_ops.add( + (1 - labels) * logits, + log_weight * (math_ops.log1p(math_ops.exp(-math_ops.abs(logits))) + + nn_ops.relu(-logits)), # pylint: disable=invalid-unary-operand-type + name=name) + + +@tf_export(v1=["nn.weighted_cross_entropy_with_logits"]) +@dispatch.add_dispatch_support +@deprecated_args(None, "targets is deprecated, use labels instead", "targets") +def weighted_cross_entropy_with_logits(labels=None, + logits=None, + pos_weight=None, + name=None, + targets=None): + """Computes a weighted cross entropy. + + This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`, + allows one to trade off recall and precision by up- or down-weighting the + cost of a positive error relative to a negative error. + + The usual cross-entropy cost is defined as: + + labels * -log(sigmoid(logits)) + + (1 - labels) * -log(1 - sigmoid(logits)) + + A value `pos_weight > 1` decreases the false negative count, hence increasing + the recall. + Conversely setting `pos_weight < 1` decreases the false positive count and + increases the precision. + This can be seen from the fact that `pos_weight` is introduced as a + multiplicative coefficient for the positive labels term + in the loss expression: + + labels * -log(sigmoid(logits)) * pos_weight + + (1 - labels) * -log(1 - sigmoid(logits)) + + For brevity, let `x = logits`, `z = labels`, `q = pos_weight`. + The loss is: + + qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) + = qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) + = qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) + = qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) + = (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x)) + = (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x)) + + Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow, + the implementation uses + + (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0)) + + `logits` and `labels` must have the same type and shape. + + Args: + labels: A `Tensor` of the same type and shape as `logits`. + logits: A `Tensor` of type `float32` or `float64`. + pos_weight: A coefficient to use on the positive examples. + name: A name for the operation (optional). + targets: Deprecated alias for labels. + + Returns: + A `Tensor` of the same shape as `logits` with the componentwise + weighted logistic losses. + + Raises: + ValueError: If `logits` and `labels` do not have the same shape. + """ + labels = deprecated_argument_lookup("labels", labels, "targets", targets) + return weighted_cross_entropy_with_logits_v2(labels, logits, pos_weight, name) + + +@tf_export(v1=["nn.relu_layer"]) +@dispatch.add_dispatch_support +def relu_layer(x, weights, biases, name=None): + """Computes Relu(x * weight + biases). + + Args: + x: a 2D tensor. Dimensions typically: batch, in_units + weights: a 2D tensor. Dimensions typically: in_units, out_units + biases: a 1D tensor. Dimensions: out_units + name: A name for the operation (optional). If not specified + "nn_relu_layer" is used. + + Returns: + A 2-D Tensor computing relu(matmul(x, weights) + biases). + Dimensions typically: batch, out_units. + """ + with ops.name_scope(name, "relu_layer", [x, weights, biases]) as name: + x = ops.convert_to_tensor(x, name="x") + weights = ops.convert_to_tensor(weights, name="weights") + biases = ops.convert_to_tensor(biases, name="biases") + xw_plus_b = nn_ops.bias_add(math_ops.matmul(x, weights), biases) + return nn_ops.relu(xw_plus_b, name=name) + + +@tf_export("nn.silu", "nn.swish") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def swish(features, beta=1.0): + # pylint: disable=g-doc-args + """Computes the SiLU or Swish activation function: `x * sigmoid(beta * x)`. + + beta : Hyperparameter for Swish activation function. Default value 1.0. + + The SiLU activation function was introduced in "Gaussian Error Linear Units + (GELUs)" [Hendrycks et al. 2016](https://arxiv.org/abs/1606.08415) and + "Sigmoid-Weighted Linear Units for Neural Network Function Approximation in + Reinforcement Learning" + [Elfwing et al. 2017](https://arxiv.org/abs/1702.03118) and was independently + discovered (and called swish) in "Searching for Activation Functions" + [Ramachandran et al. 2017](https://arxiv.org/abs/1710.05941) + + Args: + features: A `Tensor` representing preactivation values. + beta: A 'Tensor' representing value of beta hyperparameter. + + Returns: + The activation value. + """ + # pylint: enable=g-doc-args + features = ops.convert_to_tensor(features, name="features") + beta = ops.convert_to_tensor(beta, name="beta") + beta = math_ops.cast(beta, features.dtype) + + @custom_gradient.custom_gradient + def swish_impl(features, beta): + + def grad(dy): + """Gradient for the Swish activation function.""" + # Naively, x * tf.nn.sigmoid(x) requires keeping both x and sigmoid(x) + # around for backprop, effectively doubling the tensor's memory + # consumption. We use a control dependency here so that sigmoid(features) + # is re-computed during backprop (the control dep prevents it being + # de-duped with the forward pass) and we can free the sigmoid(features) + # expression immediately after use during the forward pass. + with ops.control_dependencies([dy]): + sigmoid_features = math_ops.sigmoid(beta * features) + + activation_grad = ( + sigmoid_features * (1.0 + (beta * features) * + (1.0 - sigmoid_features))) + beta_grad = math_ops.reduce_sum( + dy * math_ops.square(features) * sigmoid_features * + (1.0 - sigmoid_features)) + return (dy * activation_grad, beta_grad) + + return features * math_ops.sigmoid(beta * features), grad + + return swish_impl(features, beta) + + +# pylint: disable=redefined-builtin +@tf_export("linalg.normalize") +@dispatch.add_dispatch_support +def normalize(tensor, ord="euclidean", axis=None, name=None): + """Normalizes `tensor` along dimension `axis` using specified norm. + + This uses `tf.linalg.norm` to compute the norm along `axis`. + + This function can compute several different vector norms (the 1-norm, the + Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and + matrix norms (Frobenius, 1-norm, 2-norm and inf-norm). + + Args: + tensor: `Tensor` of types `float32`, `float64`, `complex64`, `complex128` + ord: Order of the norm. Supported values are `'fro'`, `'euclidean'`, `1`, + `2`, `np.inf` and any positive real number yielding the corresponding + p-norm. Default is `'euclidean'` which is equivalent to Frobenius norm if + `tensor` is a matrix and equivalent to 2-norm for vectors. + Some restrictions apply: a) The Frobenius norm `'fro'` is not defined for + vectors, b) If axis is a 2-tuple (matrix norm), only `'euclidean'`, + '`fro'`, `1`, `2`, `np.inf` are supported. See the description of `axis` + on how to compute norms for a batch of vectors or matrices stored in a + tensor. + axis: If `axis` is `None` (the default), the input is considered a vector + and a single vector norm is computed over the entire set of values in the + tensor, i.e. `norm(tensor, ord=ord)` is equivalent to + `norm(reshape(tensor, [-1]), ord=ord)`. If `axis` is a Python integer, the + input is considered a batch of vectors, and `axis` determines the axis in + `tensor` over which to compute vector norms. If `axis` is a 2-tuple of + Python integers it is considered a batch of matrices and `axis` determines + the axes in `tensor` over which to compute a matrix norm. + Negative indices are supported. Example: If you are passing a tensor that + can be either a matrix or a batch of matrices at runtime, pass + `axis=[-2,-1]` instead of `axis=None` to make sure that matrix norms are + computed. + name: The name of the op. + + Returns: + normalized: A normalized `Tensor` with the same shape as `tensor`. + norm: The computed norms with the same shape and dtype `tensor` but the + final axis is 1 instead. Same as running + `tf.cast(tf.linalg.norm(tensor, ord, axis keepdims=True), tensor.dtype)`. + + Raises: + ValueError: If `ord` or `axis` is invalid. + """ + with ops.name_scope(name, "normalize", [tensor]) as name: + tensor = ops.convert_to_tensor(tensor) + norm = linalg_ops.norm(tensor, ord, axis, keepdims=True) + norm = math_ops.cast(norm, tensor.dtype) + normalized = tensor / norm + return normalized, norm + + +@tf_export("math.l2_normalize", "linalg.l2_normalize", "nn.l2_normalize", + v1=["math.l2_normalize", "linalg.l2_normalize", "nn.l2_normalize"]) +@dispatch.add_dispatch_support +@deprecated_args(None, "dim is deprecated, use axis instead", "dim") +def l2_normalize(x, axis=None, epsilon=1e-12, name=None, dim=None): + """Normalizes along dimension `axis` using an L2 norm. + + For a 1-D tensor with `axis = 0`, computes + + output = x / sqrt(max(sum(x**2), epsilon)) + + For `x` with more dimensions, independently normalizes each 1-D slice along + dimension `axis`. + + 1-D tensor example: + >>> x = tf.constant([3.0, 4.0]) + >>> tf.math.l2_normalize(x).numpy() + array([0.6, 0.8], dtype=float32) + + 2-D tensor example: + >>> x = tf.constant([[3.0], [4.0]]) + >>> tf.math.l2_normalize(x, 0).numpy() + array([[0.6], + [0.8]], dtype=float32) + + >>> x = tf.constant([[3.0], [4.0]]) + >>> tf.math.l2_normalize(x, 1).numpy() + array([[1.], + [1.]], dtype=float32) + + Args: + x: A `Tensor`. + axis: Dimension along which to normalize. A scalar or a vector of + integers. + epsilon: A lower bound value for the norm. Will use `sqrt(epsilon)` as the + divisor if `norm < sqrt(epsilon)`. + name: A name for this operation (optional). + dim: Deprecated, do not use. + + Returns: + A `Tensor` with the same shape as `x`. + """ + axis = deprecated_argument_lookup("axis", axis, "dim", dim) + with ops.name_scope(name, "l2_normalize", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + if x.dtype.is_complex: + square_real = math_ops.square(math_ops.real(x)) + square_imag = math_ops.square(math_ops.imag(x)) + square_sum = math_ops.real( + math_ops.reduce_sum(square_real + square_imag, axis, keepdims=True)) + x_inv_norm = math_ops.rsqrt(math_ops.maximum(square_sum, epsilon)) + norm_real = math_ops.multiply(math_ops.real(x), x_inv_norm) + norm_imag = math_ops.multiply(math_ops.imag(x), x_inv_norm) + return math_ops.complex(norm_real, norm_imag, name=name) + square_sum = math_ops.reduce_sum(math_ops.square(x), axis, keepdims=True) + x_inv_norm = math_ops.rsqrt(math_ops.maximum(square_sum, epsilon)) + return math_ops.multiply(x, x_inv_norm, name=name) + + +def _count_nonzero(input_tensor, dtype=dtypes.int64): + """Same as math_ops.count_nonzero. + + The reduction is done in dtype, which can be faster for 32-bit dtypes. + + Args: + input_tensor: numeric tensor + dtype: reduction dtype + + Returns: + number of nonzero values with type dtype + """ + with ops.name_scope("count_nonzero", values=[input_tensor]): + zero = array_ops.zeros([], dtype=input_tensor.dtype) + nonzero_count = math_ops.reduce_sum( + math_ops.cast( + math_ops.not_equal(input_tensor, zero), + dtype=dtype), name="nonzero_count") + return nonzero_count + + +@tf_export("math.zero_fraction", "nn.zero_fraction") +@dispatch.add_dispatch_support +def zero_fraction(value, name=None): + """Returns the fraction of zeros in `value`. + + If `value` is empty, the result is `nan`. + + This is useful in summaries to measure and report sparsity. For example, + + ```python + z = tf.nn.relu(...) + summ = tf.compat.v1.summary.scalar('sparsity', tf.nn.zero_fraction(z)) + ``` + + Args: + value: A tensor of numeric type. + name: A name for the operation (optional). + + Returns: + The fraction of zeros in `value`, with type `float32`. + """ + with ops.name_scope(name, "zero_fraction", [value]): + value = ops.convert_to_tensor(value, name="value") + size = array_ops.size(value, out_type=dtypes.int64) + # If the count is small, we can save memory/CPU with an int32 reduction. + num_nonzero = tf_cond.cond( + size <= dtypes.int32.max, + # pylint: disable=g-long-lambda + true_fn=lambda: math_ops.cast( + _count_nonzero(value, dtype=dtypes.int32), + dtype=dtypes.int64), + false_fn=lambda: _count_nonzero(value, dtype=dtypes.int64)) + + with ops.name_scope("counts_to_fraction"): + num_zero = size - num_nonzero + num_zero_float32 = math_ops.cast(num_zero, dtype=dtypes.float32) + size_float32 = math_ops.cast(size, dtype=dtypes.float32) + zero_fraction_float32 = num_zero_float32 / size_float32 + + return array_ops.identity(zero_fraction_float32, "fraction") + + +# pylint: disable=redefined-builtin +@tf_export(v1=["nn.depthwise_conv2d"]) +@dispatch.add_dispatch_support +def depthwise_conv2d(input, + filter, + strides, + padding, + rate=None, + name=None, + data_format=None, + dilations=None): + """Depthwise 2-D convolution. + + Given a 4D input tensor ('NHWC' or 'NCHW' data formats) + and a filter tensor of shape + `[filter_height, filter_width, in_channels, channel_multiplier]` + containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d` + applies a different filter to each input channel (expanding from 1 channel + to `channel_multiplier` channels for each), then concatenates the results + together. The output has `in_channels * channel_multiplier` channels. + + In detail, with the default NHWC format, + + output[b, i, j, k * channel_multiplier + q] = sum_{di, dj} + filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di, + strides[2] * j + rate[1] * dj, k] + + Must have `strides[0] = strides[3] = 1`. For the most common case of the + same horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + If any value in `rate` is greater than 1, we perform atrous depthwise + convolution, in which case all values in the `strides` tensor must be equal + to 1. + + Usage Example: + + >>> x = np.array([ + ... [1., 2.], + ... [3., 4.], + ... [5., 6.] + ... ], dtype=np.float32).reshape((1, 3, 2, 1)) + >>> kernel = np.array([ + ... [1., 2.], + ... [3., 4] + ... ], dtype=np.float32).reshape((2, 1, 1, 2)) + >>> tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], + ... padding='VALID').numpy() + array([[[[10., 14.], + [14., 20.]], + [[18., 26.], + [22., 32.]]]], dtype=float32) + + >>> tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], + ... padding=[[0, 0], [1, 0], [1, 0], [0, 0]] + ... ).numpy() + array([[[[ 0., 0.], + [ 3., 4.], + [ 6., 8.]], + [[ 0., 0.], + [10., 14.], + [14., 20.]], + [[ 0., 0.], + [18., 26.], + [22., 32.]]]], dtype=float32) + + Args: + input: 4-D with shape according to `data_format`. + filter: 4-D with shape + `[filter_height, filter_width, in_channels, channel_multiplier]`. + strides: 1-D of size 4. The stride of the sliding window for each + dimension of `input`. + padding: Controls how to pad the image before applying the convolution. Can + be the string `"SAME"` or `"VALID"` indicating the type of padding + algorithm to use, or a list indicating the explicit paddings at the start + and end of each dimension. When explicit padding is used and data_format + is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + rate: 1-D of size 2. The dilation rate in which we sample input values + across the `height` and `width` dimensions in atrous convolution. If it is + greater than 1, then all values of strides must be 1. + name: A name for this operation (optional). + data_format: The data format for input. Either "NHWC" (default) or "NCHW". + dilations: Alias of rate. + + Returns: + A 4-D `Tensor` with shape according to `data_format`. E.g., for + "NHWC" format, shape is + `[batch, out_height, out_width, in_channels * channel_multiplier].` + """ + rate = deprecated_argument_lookup("dilations", dilations, "rate", rate) + with ops.name_scope(name, "depthwise", [input, filter]) as name: + input = ops.convert_to_tensor(input, name="tensor_in") + filter = ops.convert_to_tensor(filter, name="filter_in") + if rate is None: + rate = [1, 1] + + # Use depthwise_conv2d_native if executing on TPU. + if device_context.enclosing_tpu_context() is not None: + if data_format == "NCHW": + dilations = [1, 1, rate[0], rate[1]] + else: + dilations = [1, rate[0], rate[1], 1] + return nn_ops.depthwise_conv2d_native( + input=input, + filter=filter, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + def op(input_converted, _, padding): + return nn_ops.depthwise_conv2d_native( + input=input_converted, + filter=filter, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + + return nn_ops.with_space_to_batch( + input=input, + filter_shape=array_ops.shape(filter), + dilation_rate=rate, + padding=padding, + data_format=data_format, + op=op) + + +@tf_export("nn.depthwise_conv2d", v1=[]) +@dispatch.add_dispatch_support +def depthwise_conv2d_v2(input, + filter, + strides, + padding, + data_format=None, + dilations=None, + name=None): + """Depthwise 2-D convolution. + + Given a 4D input tensor ('NHWC' or 'NCHW' data formats) + and a filter tensor of shape + `[filter_height, filter_width, in_channels, channel_multiplier]` + containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d` + applies a different filter to each input channel (expanding from 1 channel + to `channel_multiplier` channels for each), then concatenates the results + together. The output has `in_channels * channel_multiplier` channels. + + In detail, with the default NHWC format, + + output[b, i, j, k * channel_multiplier + q] = + sum_{di, dj} filter[di, dj, k, q] * + input[b, strides[1] * i + dilations[0] * di, + strides[2] * j + dilations[1] * dj, k] + + Must have `strides[0] = strides[3] = 1`. For the most common case of the + same horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + If any value in `dilations` is greater than 1, we perform atrous depthwise + convolution, in which case all values in the `strides` tensor must be equal + to 1. + + Usage Example: + + >>> x = np.array([ + ... [1., 2.], + ... [3., 4.], + ... [5., 6.] + ... ], dtype=np.float32).reshape((1, 3, 2, 1)) + >>> kernel = np.array([ + ... [1., 2.], + ... [3., 4] + ... ], dtype=np.float32).reshape((2, 1, 1, 2)) + >>> tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], + ... padding='VALID').numpy() + array([[[[10., 14.], + [14., 20.]], + [[18., 26.], + [22., 32.]]]], dtype=float32) + + >>> tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1], + ... padding=[[0, 0], [1, 0], [1, 0], [0, 0]]).numpy() + array([[[[ 0., 0.], + [ 3., 4.], + [ 6., 8.]], + [[ 0., 0.], + [10., 14.], + [14., 20.]], + [[ 0., 0.], + [18., 26.], + [22., 32.]]]], dtype=float32) + + Args: + input: 4-D with shape according to `data_format`. + filter: 4-D with shape + `[filter_height, filter_width, in_channels, channel_multiplier]`. + strides: 1-D of size 4. The stride of the sliding window for each + dimension of `input`. + padding: Controls how to pad the image before applying the convolution. Can + be the string `"SAME"` or `"VALID"` indicating the type of padding + algorithm to use, or a list indicating the explicit paddings at the start + and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format + is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: The data format for input. Either "NHWC" (default) or "NCHW". + dilations: 1-D of size 2. The dilation rate in which we sample input values + across the `height` and `width` dimensions in atrous convolution. If it is + greater than 1, then all values of strides must be 1. + name: A name for this operation (optional). + + Returns: + A 4-D `Tensor` with shape according to `data_format`. E.g., for + "NHWC" format, shape is + `[batch, out_height, out_width, in_channels * channel_multiplier].` + """ + return depthwise_conv2d(input=input, + filter=filter, + strides=strides, + padding=padding, + rate=dilations, + name=name, + data_format=data_format) + +# pylint: enable=redefined-builtin + + +# pylint: disable=redefined-builtin,line-too-long +@tf_export(v1=["nn.separable_conv2d"]) +@dispatch.add_dispatch_support +def separable_conv2d(input, + depthwise_filter, + pointwise_filter, + strides, + padding, + rate=None, + name=None, + data_format=None, + dilations=None): + """2-D convolution with separable filters. + + Performs a depthwise convolution that acts separately on channels followed by + a pointwise convolution that mixes channels. Note that this is separability + between dimensions `[1, 2]` and `3`, not spatial separability between + dimensions `1` and `2`. + + In detail, with the default NHWC format, + + output[b, i, j, k] = sum_{di, dj, q, r} + input[b, strides[1] * i + di, strides[2] * j + dj, q] * + depthwise_filter[di, dj, q, r] * + pointwise_filter[0, 0, q * channel_multiplier + r, k] + + `strides` controls the strides for the depthwise convolution only, since + the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have + `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + If any value in `rate` is greater than 1, we perform atrous depthwise + convolution, in which case all values in the `strides` tensor must be equal + to 1. + + Args: + input: 4-D `Tensor` with shape according to `data_format`. + depthwise_filter: 4-D `Tensor` with shape + `[filter_height, filter_width, in_channels, channel_multiplier]`. + Contains `in_channels` convolutional filters of depth 1. + pointwise_filter: 4-D `Tensor` with shape + `[1, 1, channel_multiplier * in_channels, out_channels]`. Pointwise + filter to mix channels after `depthwise_filter` has convolved spatially. + strides: 1-D of size 4. The strides for the depthwise convolution for + each dimension of `input`. + padding: Controls how to pad the image before applying the depthwise + convolution. Can be the string `"SAME"` or `"VALID"` indicating the type + of padding algorithm to use, or a Python list indicating the explicit + paddings at the start and end of each dimension. When explicit padding is + used and data_format is `"NHWC"`, this should be in the form `[[0, 0], + [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit + padding used and data_format is `"NCHW"`, this should be in the form + `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. + rate: 1-D of size 2. The dilation rate in which we sample input values + across the `height` and `width` dimensions in atrous convolution. If it is + greater than 1, then all values of strides must be 1. + name: A name for this operation (optional). + data_format: The data format for input. Either "NHWC" (default) or "NCHW". + dilations: Alias of rate. + + Returns: + A 4-D `Tensor` with shape according to 'data_format'. For + example, with data_format="NHWC", shape is [batch, out_height, + out_width, out_channels]. + """ + rate = deprecated_argument_lookup("dilations", dilations, "rate", rate) + with ops.name_scope(name, "separable_conv2d", + [input, depthwise_filter, pointwise_filter]) as name: + input = ops.convert_to_tensor(input, name="tensor_in") + depthwise_filter = ops.convert_to_tensor( + depthwise_filter, name="depthwise_filter") + pointwise_filter = ops.convert_to_tensor( + pointwise_filter, name="pointwise_filter") + + pointwise_filter_shape = pointwise_filter.get_shape().with_rank(4) + pointwise_filter_shape.dims[0].assert_is_compatible_with(1) + pointwise_filter_shape.dims[1].assert_is_compatible_with(1) + + if rate is None: + rate = [1, 1] + + # The layout of the ops in the graph are expected to be as follows: + # depthwise_conv2d // Conv2D op corresponding to native depthwise conv. + # separable_conv2d // Conv2D op corresponding to the pointwise conv. + + def op(input_converted, _, padding): + return nn_ops.depthwise_conv2d_native( + input=input_converted, + filter=depthwise_filter, + strides=strides, + padding=padding, + data_format=data_format, + name="depthwise") + + depthwise = nn_ops.with_space_to_batch( + input=input, + filter_shape=array_ops.shape(depthwise_filter), + dilation_rate=rate, + padding=padding, + data_format=data_format, + op=op) + + return nn_ops.conv2d( + depthwise, + pointwise_filter, [1, 1, 1, 1], + padding="VALID", + data_format=data_format, + name=name) + + +@tf_export("nn.separable_conv2d", v1=[]) +@dispatch.add_dispatch_support +def separable_conv2d_v2( + input, + depthwise_filter, + pointwise_filter, + strides, + padding, + data_format=None, + dilations=None, + name=None, +): + """2-D convolution with separable filters. + + Performs a depthwise convolution that acts separately on channels followed by + a pointwise convolution that mixes channels. Note that this is separability + between dimensions `[1, 2]` and `3`, not spatial separability between + dimensions `1` and `2`. + + In detail, with the default NHWC format, + + output[b, i, j, k] = sum_{di, dj, q, r} + input[b, strides[1] * i + di, strides[2] * j + dj, q] * + depthwise_filter[di, dj, q, r] * + pointwise_filter[0, 0, q * channel_multiplier + r, k] + + `strides` controls the strides for the depthwise convolution only, since + the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have + `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + If any value in `rate` is greater than 1, we perform atrous depthwise + convolution, in which case all values in the `strides` tensor must be equal + to 1. + + Args: + input: 4-D `Tensor` with shape according to `data_format`. + depthwise_filter: 4-D `Tensor` with shape `[filter_height, filter_width, + in_channels, channel_multiplier]`. Contains `in_channels` convolutional + filters of depth 1. + pointwise_filter: 4-D `Tensor` with shape `[1, 1, channel_multiplier * + in_channels, out_channels]`. Pointwise filter to mix channels after + `depthwise_filter` has convolved spatially. + strides: 1-D of size 4. The strides for the depthwise convolution for each + dimension of `input`. + padding: Controls how to pad the image before applying the depthwise + convolution. Can be the string `"SAME"` or `"VALID"` indicating the type + of padding algorithm to use, or a Python list indicating the explicit + paddings at the start and end of each dimension. When explicit padding is + used and data_format is `"NHWC"`, this should be in the form `[[0, 0], + [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit + padding used and data_format is `"NCHW"`, this should be in the form + `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: The data format for input. Either "NHWC" (default) or "NCHW". + dilations: 1-D of size 2. The dilation rate in which we sample input values + across the `height` and `width` dimensions in atrous convolution. If it is + greater than 1, then all values of strides must be 1. + name: A name for this operation (optional). + + Returns: + A 4-D `Tensor` with shape according to 'data_format'. For + example, with data_format="NHWC", shape is [batch, out_height, + out_width, out_channels]. + """ + return separable_conv2d( + input, + depthwise_filter, + pointwise_filter, + strides, + padding, + rate=dilations, + name=name, + data_format=data_format) + +# pylint: enable=redefined-builtin,line-too-long + + +@tf_export(v1=["nn.sufficient_statistics"]) +@dispatch.add_dispatch_support +def sufficient_statistics(x, axes, shift=None, keep_dims=None, name=None, + keepdims=None): + """Calculate the sufficient statistics for the mean and variance of `x`. + + These sufficient statistics are computed using the one pass algorithm on + an input that's optionally shifted. See: + https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data + + For example: + >>> t = [[1, 2, 3], [4, 5, 6]] + >>> sufficient_statistics(t, [1]) + (, , , None) + >>> sufficient_statistics(t, [-1]) + (, , , None) + + Args: + x: A `Tensor`. + axes: Array of ints. Axes along which to compute mean and variance. As in + Python, the axes can also be negative numbers. A negative axis is + interpreted as counting from the end of the rank, i.e., axis + + rank(values)-th dimension. + shift: A `Tensor` containing the value by which to shift the data for + numerical stability, or `None` if no shift is to be performed. A shift + close to the true mean provides the most numerically stable results. + keep_dims: produce statistics with the same dimensionality as the input. + name: Name used to scope the operations that compute the sufficient stats. + keepdims: Alias for keep_dims. + + Returns: + Four `Tensor` objects of the same type as `x`: + + * the count (number of elements to average over). + * the (possibly shifted) sum of the elements in the array. + * the (possibly shifted) sum of squares of the elements in the array. + * the shift by which the mean must be corrected or None if `shift` is None. + """ + axes = list(set(axes)) + keep_dims = deprecated_argument_lookup( + "keepdims", keepdims, "keep_dims", keep_dims) + if keep_dims is None: + keep_dims = False + with ops.name_scope(name, "sufficient_statistics", [x, shift]): + x = ops.convert_to_tensor(x, name="x") + x_shape = x.get_shape() + if x_shape.rank is not None and all( + x_shape.dims[d].value is not None for d in axes): + counts = 1 + for d in axes: + counts *= x_shape.dims[d].value + counts = constant_op.constant(counts, dtype=x.dtype) + else: # shape needs to be inferred at runtime. + # Normalize axes to be positive. Required for gather. + rank = array_ops.rank(x) + positive_axes = [axis + rank if axis < 0 else axis for axis in axes] + x_dims = array_ops.gather( + math_ops.cast(array_ops.shape(x), x.dtype), positive_axes) + counts = math_ops.reduce_prod(x_dims, name="count") + if shift is not None: + shift = ops.convert_to_tensor(shift, name="shift") + m_ss = math_ops.subtract(x, shift) + v_ss = math_ops.squared_difference(x, shift) + else: # no shift. + m_ss = x + v_ss = math_ops.square(x) + m_ss = math_ops.reduce_sum(m_ss, axes, keepdims=keep_dims, name="mean_ss") + v_ss = math_ops.reduce_sum(v_ss, axes, keepdims=keep_dims, name="var_ss") + return counts, m_ss, v_ss, shift + + +@tf_export("nn.sufficient_statistics", v1=[]) +@dispatch.add_dispatch_support +def sufficient_statistics_v2(x, axes, shift=None, keepdims=False, name=None): + """Calculate the sufficient statistics for the mean and variance of `x`. + + These sufficient statistics are computed using the one pass algorithm on + an input that's optionally shifted. See: + https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data + + Args: + x: A `Tensor`. + axes: Array of ints. Axes along which to compute mean and variance. + shift: A `Tensor` containing the value by which to shift the data for + numerical stability, or `None` if no shift is to be performed. A shift + close to the true mean provides the most numerically stable results. + keepdims: produce statistics with the same dimensionality as the input. + name: Name used to scope the operations that compute the sufficient stats. + + Returns: + Four `Tensor` objects of the same type as `x`: + + * the count (number of elements to average over). + * the (possibly shifted) sum of the elements in the array. + * the (possibly shifted) sum of squares of the elements in the array. + * the shift by which the mean must be corrected or None if `shift` is None. + """ + return sufficient_statistics( + x=x, axes=axes, shift=shift, keep_dims=keepdims, name=name) + + +@tf_export("nn.normalize_moments") +@dispatch.add_dispatch_support +def normalize_moments(counts, mean_ss, variance_ss, shift, name=None): + """Calculate the mean and variance of based on the sufficient statistics. + + Args: + counts: A `Tensor` containing the total count of the data (one value). + mean_ss: A `Tensor` containing the mean sufficient statistics: the (possibly + shifted) sum of the elements to average over. + variance_ss: A `Tensor` containing the variance sufficient statistics: the + (possibly shifted) squared sum of the data to compute the variance over. + shift: A `Tensor` containing the value by which the data is shifted for + numerical stability, or `None` if no shift was performed. + name: Name used to scope the operations that compute the moments. + + Returns: + Two `Tensor` objects: `mean` and `variance`. + """ + with ops.name_scope(name, "normalize", [counts, mean_ss, variance_ss, shift]): + divisor = math_ops.reciprocal(counts, name="divisor") + if shift is not None: + shifted_mean = math_ops.multiply(mean_ss, divisor, name="shifted_mean") + mean = math_ops.add(shifted_mean, shift, name="mean") + else: # no shift. + shifted_mean = math_ops.multiply(mean_ss, divisor, name="mean") + mean = shifted_mean + variance = math_ops.subtract( + math_ops.multiply(variance_ss, divisor), + math_ops.square(shifted_mean), + name="variance") + return (mean, variance) + + +@tf_export(v1=["nn.moments"]) +@dispatch.add_dispatch_support +def moments( + x, + axes, + shift=None, # pylint: disable=unused-argument + name=None, + keep_dims=None, + keepdims=None): + """Calculate the mean and variance of `x`. + + The mean and variance are calculated by aggregating the contents of `x` + across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean + and variance of a vector. + + Note: shift is currently not used; the true mean is computed and used. + + When using these moments for batch normalization (see + `tf.nn.batch_normalization`): + + * for so-called "global normalization", used with convolutional filters with + shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`. + * for simple batch normalization pass `axes=[0]` (batch only). + + Args: + x: A `Tensor`. + axes: Array of ints. Axes along which to compute mean and + variance. + shift: Not used in the current implementation + name: Name used to scope the operations that compute the moments. + keep_dims: produce moments with the same dimensionality as the input. + keepdims: Alias to keep_dims. + + Returns: + Two `Tensor` objects: `mean` and `variance`. + """ + keep_dims = deprecated_argument_lookup( + "keepdims", keepdims, "keep_dims", keep_dims) + if keep_dims is None: + keep_dims = False + with ops.name_scope(name, "moments", [x, axes]): + # The dynamic range of fp16 is too limited to support the collection of + # sufficient statistics. As a workaround we simply perform the operations + # on 32-bit floats before converting the mean and variance back to fp16 + y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x + # Compute true mean while keeping the dims for proper broadcasting. + mean = math_ops.reduce_mean(y, axes, keepdims=True, name="mean") + # sample variance, not unbiased variance + # Note: stop_gradient does not change the gradient that gets + # backpropagated to the mean from the variance calculation, + # because that gradient is zero + variance = math_ops.reduce_mean( + math_ops.squared_difference(y, array_ops.stop_gradient(mean)), + axes, + keepdims=True, + name="variance") + if not keep_dims: + mean = array_ops.squeeze(mean, axes) + variance = array_ops.squeeze(variance, axes) + if x.dtype == dtypes.float16: + return (math_ops.cast(mean, dtypes.float16), + math_ops.cast(variance, dtypes.float16)) + else: + return (mean, variance) + + +@tf_export("nn.moments", v1=[]) +@dispatch.add_dispatch_support +def moments_v2( + x, + axes, + shift=None, + keepdims=False, + name=None): + """Calculates the mean and variance of `x`. + + The mean and variance are calculated by aggregating the contents of `x` + across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean + and variance of a vector. + + Note: shift is currently not used; the true mean is computed and used. + + When using these moments for batch normalization (see + `tf.nn.batch_normalization`): + + * for so-called "global normalization", used with convolutional filters with + shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`. + * for simple batch normalization pass `axes=[0]` (batch only). + + Args: + x: A `Tensor`. + axes: Array of ints. Axes along which to compute mean and + variance. + shift: Not used in the current implementation. + keepdims: produce moments with the same dimensionality as the input. + name: Name used to scope the operations that compute the moments. + + Returns: + Two `Tensor` objects: `mean` and `variance`. + """ + return moments(x=x, axes=axes, shift=shift, name=name, keep_dims=keepdims) + + +@tf_export(v1=["nn.weighted_moments"]) +@dispatch.add_dispatch_support +def weighted_moments(x, axes, frequency_weights, name=None, keep_dims=None, + keepdims=None): + """Returns the frequency-weighted mean and variance of `x`. + + Args: + x: A tensor. + axes: 1-d tensor of int32 values; these are the axes along which + to compute mean and variance. + frequency_weights: A tensor of positive weights which can be + broadcast with x. + name: Name used to scope the operation. + keep_dims: Produce moments with the same dimensionality as the input. + keepdims: Alias of keep_dims. + + Returns: + Two tensors: `weighted_mean` and `weighted_variance`. + """ + keep_dims = deprecated_argument_lookup( + "keepdims", keepdims, "keep_dims", keep_dims) + if keep_dims is None: + keep_dims = False + with ops.name_scope(name, "weighted_moments", [x, frequency_weights, axes]): + x = ops.convert_to_tensor(x, name="x") + frequency_weights = ops.convert_to_tensor( + frequency_weights, name="frequency_weights") + + # Unlike moments(), this just uses a simpler two-pass method. + + # See comment in moments() WRT precision; it applies here too. + needs_cast = x.dtype == dtypes.float16 + if needs_cast: + x = math_ops.cast(x, dtypes.float32) + + if frequency_weights.dtype != x.dtype: + frequency_weights = math_ops.cast(frequency_weights, x.dtype) + + # Note that we use keep_dims=True for our reductions regardless of the arg; + # this is so that the results remain broadcast-compatible with the inputs. + weighted_input_sum = math_ops.reduce_sum( + frequency_weights * x, axes, name="weighted_input_sum", keepdims=True) + + # The shape of the weights isn't necessarily the same as x's + # shape, just broadcast-compatible with it -- so this expression + # performs broadcasting to give a per-item weight, with the same + # shape as (frequency_weights * x). This avoids having to reason + # through all the broadcast logic to compute a correct + # sum_of_weights. + broadcasted_weights = frequency_weights + array_ops.zeros_like(x) + + sum_of_weights = math_ops.reduce_sum( + broadcasted_weights, axes, name="sum_of_weights", keepdims=True) + + weighted_mean = math_ops.div_no_nan(weighted_input_sum, sum_of_weights) + + # Have the weighted mean; now on to variance: + weighted_distsq = math_ops.reduce_sum( + frequency_weights * math_ops.squared_difference(x, weighted_mean), + axes, + name="weighted_distsq", + keepdims=True) + + weighted_variance = math_ops.div_no_nan(weighted_distsq, sum_of_weights) + + if not keep_dims: + weighted_mean = array_ops.squeeze(weighted_mean, axis=axes) + weighted_variance = array_ops.squeeze( + weighted_variance, axis=axes) + + if needs_cast: + weighted_mean = math_ops.cast(weighted_mean, dtypes.float16) + weighted_variance = math_ops.cast(weighted_variance, dtypes.float16) + + return weighted_mean, weighted_variance + + +@tf_export("nn.weighted_moments", v1=[]) +@dispatch.add_dispatch_support +def weighted_moments_v2(x, axes, frequency_weights, keepdims=False, name=None): + """Returns the frequency-weighted mean and variance of `x`. + + Args: + x: A tensor. + axes: 1-d tensor of int32 values; these are the axes along which + to compute mean and variance. + frequency_weights: A tensor of positive weights which can be + broadcast with x. + keepdims: Produce moments with the same dimensionality as the input. + name: Name used to scope the operation. + + Returns: + Two tensors: `weighted_mean` and `weighted_variance`. + """ + return weighted_moments( + x=x, + axes=axes, + frequency_weights=frequency_weights, + name=name, + keep_dims=keepdims) + + +@tf_export("nn.batch_normalization") +@dispatch.add_dispatch_support +def batch_normalization(x, + mean, + variance, + offset, + scale, + variance_epsilon, + name=None): + r"""Batch normalization. + + Normalizes a tensor by `mean` and `variance`, and applies (optionally) a + `scale` \\(\gamma\\) to it, as well as an `offset` \\(\beta\\): + + \\(\frac{\gamma(x-\mu)}{\sigma}+\beta\\) + + `mean`, `variance`, `offset` and `scale` are all expected to be of one of two + shapes: + + * In all generality, they can have the same number of dimensions as the + input `x`, with identical sizes as `x` for the dimensions that are not + normalized over (the 'depth' dimension(s)), and dimension 1 for the + others which are being normalized over. + `mean` and `variance` in this case would typically be the outputs of + `tf.nn.moments(..., keepdims=True)` during training, or running averages + thereof during inference. + * In the common case where the 'depth' dimension is the last dimension in + the input tensor `x`, they may be one dimensional tensors of the same + size as the 'depth' dimension. + This is the case for example for the common `[batch, depth]` layout of + fully-connected layers, and `[batch, height, width, depth]` for + convolutions. + `mean` and `variance` in this case would typically be the outputs of + `tf.nn.moments(..., keepdims=False)` during training, or running averages + thereof during inference. + + See equation 11 in Algorithm 2 of source: + [Batch Normalization: Accelerating Deep Network Training by + Reducing Internal Covariate Shift; S. Ioffe, C. Szegedy] + (http://arxiv.org/abs/1502.03167). + + Args: + x: Input `Tensor` of arbitrary dimensionality. + mean: A mean `Tensor`. + variance: A variance `Tensor`. + offset: An offset `Tensor`, often denoted \\(\beta\\) in equations, or + None. If present, will be added to the normalized tensor. + scale: A scale `Tensor`, often denoted \\(\gamma\\) in equations, or + `None`. If present, the scale is applied to the normalized tensor. + variance_epsilon: A small float number to avoid dividing by 0. + name: A name for this operation (optional). + + Returns: + the normalized, scaled, offset tensor. + + References: + Batch Normalization - Accelerating Deep Network Training by Reducing + Internal Covariate Shift: + [Ioffe et al., 2015](http://arxiv.org/abs/1502.03167) + ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) + """ + with ops.name_scope(name, "batchnorm", [x, mean, variance, scale, offset]): + inv = math_ops.rsqrt(variance + variance_epsilon) + if scale is not None: + inv *= scale + # Note: tensorflow/contrib/quantize/python/fold_batch_norms.py depends on + # the precise order of ops that are generated by the expression below. + return x * math_ops.cast(inv, x.dtype) + math_ops.cast( + offset - mean * inv if offset is not None else -mean * inv, x.dtype) + + +@tf_export(v1=["nn.fused_batch_norm"]) +@dispatch.add_dispatch_support +def fused_batch_norm( + x, + scale, + offset, # pylint: disable=invalid-name + mean=None, + variance=None, + epsilon=0.001, + data_format="NHWC", + is_training=True, + name=None, + exponential_avg_factor=1.0): + r"""Batch normalization. + + + See Source: [Batch Normalization: Accelerating Deep Network Training by + Reducing Internal Covariate Shift; S. Ioffe, C. Szegedy] + (http://arxiv.org/abs/1502.03167). + + Args: + x: Input `Tensor` of 4 or 5 dimensions. + scale: A `Tensor` of 1 dimension for scaling. + offset: A `Tensor` of 1 dimension for bias. + mean: A `Tensor` of 1 dimension for population mean. The shape and meaning + of this argument depends on the value of is_training and + exponential_avg_factor as follows: + is_training==False (inference): + Mean must be a `Tensor` of the same shape as scale containing the + estimated population mean computed during training. + is_training==True and exponential_avg_factor == 1.0: + Mean must be None. + is_training==True and exponential_avg_factor != 1.0: + Mean must be a `Tensor` of the same shape as scale containing the + exponential running mean. + variance: A `Tensor` of 1 dimension for population variance. The shape and + meaning of this argument depends on the value of is_training and + exponential_avg_factor as follows: + is_training==False (inference): + Variance must be a `Tensor` of the same shape as scale containing + the estimated population variance computed during training. + is_training==True and exponential_avg_factor == 1.0: + Variance must be None. + is_training==True and exponential_avg_factor != 1.0: + Variance must be a `Tensor` of the same shape as scale containing + the exponential running variance. + epsilon: A small float number added to the variance of x. + data_format: The data format for x. Support "NHWC" (default) or "NCHW" for + 4D tenors and "NDHWC" or "NCDHW" for 5D tensors. + is_training: A bool value to specify if the operation is used for + training or inference. + name: A name for this operation (optional). + exponential_avg_factor: A float number (usually between 0 and 1) used + for controlling the decay of the running + population average of mean and variance. + If set to 1.0, the current batch average is + returned. + + Returns: + y: A 4D or 5D Tensor for the normalized, scaled, offsetted x. + running_mean: A 1D Tensor for the exponential running mean of x. + The output value is (1 - exponential_avg_factor) * mean + + exponential_avg_factor * batch_mean), where batch_mean + is the mean of the current batch in x. + running_var: A 1D Tensor for the exponential running variance + The output value is (1 - exponential_avg_factor) * variance + + exponential_avg_factor * batch_variance), where batch_variance + is the variance of the current batch in x. + + References: + Batch Normalization - Accelerating Deep Network Training by Reducing + Internal Covariate Shift: + [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) + ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) + """ + if (not is_training or exponential_avg_factor != 1.0) and ( + (mean is None) or (variance is None)): + raise ValueError("Both `mean` and `variance` must be a 1D tensor when " + "`is_training` is False or `exponential_avg_factor` != " + f"1.0. Received: `mean` {mean!r} and `variance` " + f"{variance!r}") + x = ops.convert_to_tensor(x, name="input") + scale = ops.convert_to_tensor(scale, name="scale") + offset = ops.convert_to_tensor(offset, name="offset") + if mean is None: + mean = constant_op.constant([]) + if variance is None: + variance = constant_op.constant([]) + + y, running_mean, running_var, _, _, _ = gen_nn_ops.fused_batch_norm_v3( + x, + scale, + offset, + mean, + variance, + epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, + is_training=is_training, + name=name) + return y, running_mean, running_var + + +@tf_export(v1=["nn.batch_norm_with_global_normalization"]) +@dispatch.add_dispatch_support +def batch_norm_with_global_normalization(t=None, + m=None, + v=None, + beta=None, + gamma=None, + variance_epsilon=None, + scale_after_normalization=None, + name=None, + input=None, # pylint: disable=redefined-builtin + mean=None, + variance=None): + """Batch normalization. + + This op is deprecated. See `tf.nn.batch_normalization`. + + Args: + t: A 4D input Tensor. + m: A 1D mean Tensor with size matching the last dimension of t. + This is the first output from tf.nn.moments, + or a saved moving average thereof. + v: A 1D variance Tensor with size matching the last dimension of t. + This is the second output from tf.nn.moments, + or a saved moving average thereof. + beta: A 1D beta Tensor with size matching the last dimension of t. + An offset to be added to the normalized tensor. + gamma: A 1D gamma Tensor with size matching the last dimension of t. + If "scale_after_normalization" is true, this tensor will be multiplied + with the normalized tensor. + variance_epsilon: A small float number to avoid dividing by 0. + scale_after_normalization: A bool indicating whether the resulted tensor + needs to be multiplied with gamma. + name: A name for this operation (optional). + input: Alias for t. + mean: Alias for m. + variance: Alias for v. + + Returns: + A batch-normalized `t`. + + References: + Batch Normalization - Accelerating Deep Network Training by Reducing + Internal Covariate Shift: + [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) + ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) + """ + t = deprecated_argument_lookup("input", input, "t", t) + m = deprecated_argument_lookup("mean", mean, "m", m) + v = deprecated_argument_lookup("variance", variance, "v", v) + return batch_normalization(t, m, v, beta, gamma if scale_after_normalization + else None, variance_epsilon, name) + + +# pylint: disable=redefined-builtin,line-too-long +@tf_export("nn.batch_norm_with_global_normalization", v1=[]) +@dispatch.add_dispatch_support +def batch_norm_with_global_normalization_v2(input, + mean, + variance, + beta, + gamma, + variance_epsilon, + scale_after_normalization, + name=None): + """Batch normalization. + + This op is deprecated. See `tf.nn.batch_normalization`. + + Args: + input: A 4D input Tensor. + mean: A 1D mean Tensor with size matching the last dimension of t. + This is the first output from tf.nn.moments, + or a saved moving average thereof. + variance: A 1D variance Tensor with size matching the last dimension of t. + This is the second output from tf.nn.moments, + or a saved moving average thereof. + beta: A 1D beta Tensor with size matching the last dimension of t. + An offset to be added to the normalized tensor. + gamma: A 1D gamma Tensor with size matching the last dimension of t. + If "scale_after_normalization" is true, this tensor will be multiplied + with the normalized tensor. + variance_epsilon: A small float number to avoid dividing by 0. + scale_after_normalization: A bool indicating whether the resulted tensor + needs to be multiplied with gamma. + name: A name for this operation (optional). + + Returns: + A batch-normalized `t`. + + References: + Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: + [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) + ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) + """ + return batch_norm_with_global_normalization(t=input, + m=mean, + v=variance, + beta=beta, + gamma=gamma, + variance_epsilon=variance_epsilon, + scale_after_normalization=scale_after_normalization, + name=name) + +# pylint: enable=redefined-builtin,line-too-long + + +def _sum_rows(x): + """Returns a vector summing up each row of the matrix x.""" + # _sum_rows(x) is equivalent to math_ops.reduce_sum(x, 1) when x is + # a matrix. The gradient of _sum_rows(x) is more efficient than + # reduce_sum(x, 1)'s gradient in today's implementation. Therefore, + # we use _sum_rows(x) in the nce_loss() computation since the loss + # is mostly used for training. + cols = array_ops.shape(x)[1] + ones_shape = array_ops_stack.stack([cols, 1]) + ones = array_ops.ones(ones_shape, x.dtype) + return array_ops.reshape(math_ops.matmul(x, ones), [-1]) + + +def _compute_sampled_logits(weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=1, + sampled_values=None, + subtract_log_q=True, + remove_accidental_hits=False, + partition_strategy="mod", + name=None, + seed=None): + """Helper function for nce_loss and sampled_softmax_loss functions. + + Computes sampled output training logits and labels suitable for implementing + e.g. noise-contrastive estimation (see nce_loss) or sampled softmax (see + sampled_softmax_loss). + + Note: In the case where num_true > 1, we assign to each target class + the target probability 1 / num_true so that the target probabilities + sum to 1 per-example. + + Args: + weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` + objects whose concatenation along dimension 0 has shape + `[num_classes, dim]`. The (possibly-partitioned) class embeddings. + biases: A `Tensor` of shape `[num_classes]`. The (possibly-partitioned) + class biases. + labels: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. Note that this format differs from + the `labels` argument of `nn.softmax_cross_entropy_with_logits`. + inputs: A `Tensor` of shape `[batch_size, dim]`. The forward + activations of the input network. + num_sampled: An `int`. The number of classes to randomly sample per batch. + num_classes: An `int`. The number of possible classes. + num_true: An `int`. The number of target classes per training example. + sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, + `sampled_expected_count`) returned by a `*_candidate_sampler` function. + (if None, we default to `log_uniform_candidate_sampler`) + subtract_log_q: A `bool`. whether to subtract the log expected count of + the labels in the sample to get the logits of the true labels. + Default is True. Turn off for Negative Sampling. + remove_accidental_hits: A `bool`. whether to remove "accidental hits" + where a sampled class equals one of the target classes. Default is + False. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. + Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. + name: A name for the operation (optional). + seed: random seed for candidate sampling. Default to None, which doesn't set + the op-level random seed for candidate sampling. + Returns: + out_logits: `Tensor` object with shape + `[batch_size, num_true + num_sampled]`, for passing to either + `nn.sigmoid_cross_entropy_with_logits` (NCE) or + `nn.softmax_cross_entropy_with_logits` (sampled softmax). + out_labels: A Tensor object with the same shape as `out_logits`. + """ + + if isinstance(weights, variables.PartitionedVariable): + weights = list(weights) + if not isinstance(weights, list): + weights = [weights] + + with ops.name_scope(name, "compute_sampled_logits", + weights + [biases, inputs, labels]): + if labels.dtype != dtypes.int64: + labels = math_ops.cast(labels, dtypes.int64) + labels_flat = array_ops.reshape(labels, [-1]) + + # Sample the negative labels. + # sampled shape: [num_sampled] tensor + # true_expected_count shape = [batch_size, 1] tensor + # sampled_expected_count shape = [num_sampled] tensor + if sampled_values is None: + sampled_values = candidate_sampling_ops.log_uniform_candidate_sampler( + true_classes=labels, + num_true=num_true, + num_sampled=num_sampled, + unique=True, + range_max=num_classes, + seed=seed) + # NOTE: pylint cannot tell that 'sampled_values' is a sequence + # pylint: disable=unpacking-non-sequence + sampled, true_expected_count, sampled_expected_count = ( + array_ops.stop_gradient(s) for s in sampled_values) + # pylint: enable=unpacking-non-sequence + sampled = math_ops.cast(sampled, dtypes.int64) + + # labels_flat is a [batch_size * num_true] tensor + # sampled is a [num_sampled] int tensor + all_ids = array_ops.concat([labels_flat, sampled], 0) + + # Retrieve the true weights and the logits of the sampled weights. + + # weights shape is [num_classes, dim] + all_w = embedding_ops.embedding_lookup( + weights, all_ids, partition_strategy=partition_strategy) + if all_w.dtype != inputs.dtype: + all_w = math_ops.cast(all_w, inputs.dtype) + + # true_w shape is [batch_size * num_true, dim] + true_w = array_ops.slice(all_w, [0, 0], + array_ops_stack.stack( + [array_ops.shape(labels_flat)[0], -1])) + + sampled_w = array_ops.slice( + all_w, + array_ops_stack.stack([array_ops.shape(labels_flat)[0], 0]), [-1, -1]) + # inputs has shape [batch_size, dim] + # sampled_w has shape [num_sampled, dim] + # Apply X*W', which yields [batch_size, num_sampled] + sampled_logits = math_ops.matmul(inputs, sampled_w, transpose_b=True) + + # Retrieve the true and sampled biases, compute the true logits, and + # add the biases to the true and sampled logits. + all_b = embedding_ops.embedding_lookup( + biases, all_ids, partition_strategy=partition_strategy) + if all_b.dtype != inputs.dtype: + all_b = math_ops.cast(all_b, inputs.dtype) + # true_b is a [batch_size * num_true] tensor + # sampled_b is a [num_sampled] float tensor + true_b = array_ops.slice(all_b, [0], array_ops.shape(labels_flat)) + sampled_b = array_ops.slice(all_b, array_ops.shape(labels_flat), [-1]) + + # inputs shape is [batch_size, dim] + # true_w shape is [batch_size * num_true, dim] + # row_wise_dots is [batch_size, num_true, dim] + dim = array_ops.shape(true_w)[1:2] + new_true_w_shape = array_ops.concat([[-1, num_true], dim], 0) + row_wise_dots = math_ops.multiply( + array_ops.expand_dims(inputs, 1), + array_ops.reshape(true_w, new_true_w_shape)) + # We want the row-wise dot plus biases which yields a + # [batch_size, num_true] tensor of true_logits. + dots_as_matrix = array_ops.reshape(row_wise_dots, + array_ops.concat([[-1], dim], 0)) + true_logits = array_ops.reshape(_sum_rows(dots_as_matrix), [-1, num_true]) + true_b = array_ops.reshape(true_b, [-1, num_true]) + true_logits += true_b + sampled_logits += sampled_b + + if remove_accidental_hits: + acc_hits = candidate_sampling_ops.compute_accidental_hits( + labels, sampled, num_true=num_true) + acc_indices, acc_ids, acc_weights = acc_hits + + # This is how SparseToDense expects the indices. + acc_indices_2d = array_ops.reshape(acc_indices, [-1, 1]) + acc_ids_2d_int32 = array_ops.reshape( + math_ops.cast(acc_ids, dtypes.int32), [-1, 1]) + sparse_indices = array_ops.concat([acc_indices_2d, acc_ids_2d_int32], 1, + "sparse_indices") + # Create sampled_logits_shape = [batch_size, num_sampled] + sampled_logits_shape = array_ops.concat( + [array_ops.shape(labels)[:1], + array_ops.expand_dims(num_sampled, 0)], 0) + if sampled_logits.dtype != acc_weights.dtype: + acc_weights = math_ops.cast(acc_weights, sampled_logits.dtype) + sampled_logits += gen_sparse_ops.sparse_to_dense( + sparse_indices, + sampled_logits_shape, + acc_weights, + default_value=0.0, + validate_indices=False) + + if subtract_log_q: + # Subtract log of Q(l), prior probability that l appears in sampled. + true_logits -= math_ops.log(true_expected_count) + sampled_logits -= math_ops.log(sampled_expected_count) + + # Construct output logits and labels. The true labels/logits start at col 0. + out_logits = array_ops.concat([true_logits, sampled_logits], 1) + + # true_logits is a float tensor, ones_like(true_logits) is a float + # tensor of ones. We then divide by num_true to ensure the per-example + # labels sum to 1.0, i.e. form a proper probability distribution. + out_labels = array_ops.concat([ + array_ops.ones_like(true_logits) / num_true, + array_ops.zeros_like(sampled_logits) + ], 1) + + return out_logits, out_labels + + +@tf_export("nn.nce_loss", v1=[]) +@dispatch.add_dispatch_support +def nce_loss_v2(weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=1, + sampled_values=None, + remove_accidental_hits=False, + name="nce_loss"): + """Computes and returns the noise-contrastive estimation training loss. + + See [Noise-contrastive estimation: A new estimation principle for + unnormalized statistical + models](https://arxiv.org/abs/1806.03664). + Also see our [Candidate Sampling Algorithms + Reference](https://www.tensorflow.org/extras/candidate_sampling.pdf) + + A common use case is to use this method for training, and calculate the full + sigmoid loss for evaluation or inference as in the following example: + + ```python + if mode == "train": + loss = tf.nn.nce_loss( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + ...) + elif mode == "eval": + logits = tf.matmul(inputs, tf.transpose(weights)) + logits = tf.nn.bias_add(logits, biases) + labels_one_hot = tf.one_hot(labels, n_classes) + loss = tf.nn.sigmoid_cross_entropy_with_logits( + labels=labels_one_hot, + logits=logits) + loss = tf.reduce_sum(loss, axis=1) + ``` + + Note: when doing embedding lookup on `weights` and `bias`, "div" partition + strategy will be used. Support for other partition strategy will be added + later. + + Note: By default this uses a log-uniform (Zipfian) distribution for sampling, + so your labels must be sorted in order of decreasing frequency to achieve + good results. For more details, see + `tf.random.log_uniform_candidate_sampler`. + + Note: In the case where `num_true` > 1, we assign to each target class + the target probability 1 / `num_true` so that the target probabilities + sum to 1 per-example. + + Note: It would be useful to allow a variable number of target classes per + example. We hope to provide this functionality in a future release. + For now, if you have a variable number of target classes, you can pad them + out to a constant number by either repeating them or by padding + with an otherwise unused class. + + Args: + weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` + objects whose concatenation along dimension 0 has shape [num_classes, + dim]. The (possibly-partitioned) class embeddings. + biases: A `Tensor` of shape `[num_classes]`. The class biases. + labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The + target classes. + inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of + the input network. + num_sampled: An `int`. The number of negative classes to randomly sample + per batch. This single sample of negative classes is evaluated for each + element in the batch. + num_classes: An `int`. The number of possible classes. + num_true: An `int`. The number of target classes per training example. + sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, + `sampled_expected_count`) returned by a `*_candidate_sampler` function. + (if None, we default to `log_uniform_candidate_sampler`) + remove_accidental_hits: A `bool`. Whether to remove "accidental hits" + where a sampled class equals one of the target classes. If set to `True`, + this is a "Sampled Logistic" loss instead of NCE, and we are learning to + generate log-odds instead of log probabilities. See our [Candidate + Sampling Algorithms Reference] + (https://www.tensorflow.org/extras/candidate_sampling.pdf). Default is + False. + name: A name for the operation (optional). + + Returns: + A `batch_size` 1-D tensor of per-example NCE losses. + """ + # TODO(yuefengz): get partition_strategy from either variables or distribution + # strategies. + return nce_loss( + weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=num_true, + sampled_values=sampled_values, + remove_accidental_hits=remove_accidental_hits, + partition_strategy="div", + name=name) + + +@tf_export(v1=["nn.nce_loss"]) +@dispatch.add_dispatch_support +def nce_loss(weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=1, + sampled_values=None, + remove_accidental_hits=False, + partition_strategy="mod", + name="nce_loss"): + """Computes and returns the noise-contrastive estimation training loss. + + A common use case is to use this method for training, and calculate the full + sigmoid loss for evaluation or inference. In this case, you must set + `partition_strategy="div"` for the two losses to be consistent, as in the + following example: + + ```python + if mode == "train": + loss = tf.nn.nce_loss( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + ..., + partition_strategy="div") + elif mode == "eval": + logits = tf.matmul(inputs, tf.transpose(weights)) + logits = tf.nn.bias_add(logits, biases) + labels_one_hot = tf.one_hot(labels, n_classes) + loss = tf.nn.sigmoid_cross_entropy_with_logits( + labels=labels_one_hot, + logits=logits) + loss = tf.reduce_sum(loss, axis=1) + ``` + + Note: By default this uses a log-uniform (Zipfian) distribution for sampling, + so your labels must be sorted in order of decreasing frequency to achieve + good results. For more details, see + `tf.random.log_uniform_candidate_sampler`. + + Note: In the case where `num_true` > 1, we assign to each target class + the target probability 1 / `num_true` so that the target probabilities + sum to 1 per-example. + + Note: It would be useful to allow a variable number of target classes per + example. We hope to provide this functionality in a future release. + For now, if you have a variable number of target classes, you can pad them + out to a constant number by either repeating them or by padding + with an otherwise unused class. + + Args: + weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` + objects whose concatenation along dimension 0 has shape + [num_classes, dim]. The (possibly-partitioned) class embeddings. + biases: A `Tensor` of shape `[num_classes]`. The class biases. + labels: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. + inputs: A `Tensor` of shape `[batch_size, dim]`. The forward + activations of the input network. + num_sampled: An `int`. The number of negative classes to randomly sample + per batch. This single sample of negative classes is evaluated for each + element in the batch. + num_classes: An `int`. The number of possible classes. + num_true: An `int`. The number of target classes per training example. + sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, + `sampled_expected_count`) returned by a `*_candidate_sampler` function. + (if None, we default to `log_uniform_candidate_sampler`) + remove_accidental_hits: A `bool`. Whether to remove "accidental hits" + where a sampled class equals one of the target classes. If set to + `True`, this is a "Sampled Logistic" loss instead of NCE, and we are + learning to generate log-odds instead of log probabilities. See + our Candidate Sampling Algorithms Reference + ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)). + Default is False. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. + Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. + name: A name for the operation (optional). + + Returns: + A `batch_size` 1-D tensor of per-example NCE losses. + + References: + Noise-contrastive estimation - A new estimation principle for unnormalized + statistical models: + [Gutmann et al., 2010](http://proceedings.mlr.press/v9/gutmann10a) + ([pdf](http://proceedings.mlr.press/v9/gutmann10a/gutmann10a.pdf)) + """ + logits, labels = _compute_sampled_logits( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + num_sampled=num_sampled, + num_classes=num_classes, + num_true=num_true, + sampled_values=sampled_values, + subtract_log_q=True, + remove_accidental_hits=remove_accidental_hits, + partition_strategy=partition_strategy, + name=name) + sampled_losses = sigmoid_cross_entropy_with_logits( + labels=labels, logits=logits, name="sampled_losses") + # sampled_losses is batch_size x {true_loss, sampled_losses...} + # We sum out true and sampled losses. + return _sum_rows(sampled_losses) + + +@tf_export("nn.sampled_softmax_loss", v1=[]) +@dispatch.add_dispatch_support +def sampled_softmax_loss_v2(weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=1, + sampled_values=None, + remove_accidental_hits=True, + seed=None, + name="sampled_softmax_loss"): + """Computes and returns the sampled softmax training loss. + + This is a faster way to train a softmax classifier over a huge number of + classes. + + This operation is for training only. It is generally an underestimate of + the full softmax loss. + + A common use case is to use this method for training, and calculate the full + softmax loss for evaluation or inference as in the following example: + + ```python + if mode == "train": + loss = tf.nn.sampled_softmax_loss( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + ...) + elif mode == "eval": + logits = tf.matmul(inputs, tf.transpose(weights)) + logits = tf.nn.bias_add(logits, biases) + labels_one_hot = tf.one_hot(labels, n_classes) + loss = tf.nn.softmax_cross_entropy_with_logits( + labels=labels_one_hot, + logits=logits) + ``` + + See our [Candidate Sampling Algorithms Reference] + (https://www.tensorflow.org/extras/candidate_sampling.pdf) + + Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007) + ([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math. + + Note: when doing embedding lookup on `weights` and `bias`, "div" partition + strategy will be used. Support for other partition strategy will be added + later. + + Args: + weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` + objects whose concatenation along dimension 0 has shape [num_classes, + dim]. The (possibly-sharded) class embeddings. + biases: A `Tensor` of shape `[num_classes]`. The class biases. + labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The + target classes. Note that this format differs from the `labels` argument + of `nn.softmax_cross_entropy_with_logits`. + inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of + the input network. + num_sampled: An `int`. The number of classes to randomly sample per batch. + num_classes: An `int`. The number of possible classes. + num_true: An `int`. The number of target classes per training example. + sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, + `sampled_expected_count`) returned by a `*_candidate_sampler` function. + (if None, we default to `log_uniform_candidate_sampler`) + remove_accidental_hits: A `bool`. whether to remove "accidental hits" + where a sampled class equals one of the target classes. Default is True. + seed: random seed for candidate sampling. Default to None, which doesn't set + the op-level random seed for candidate sampling. + name: A name for the operation (optional). + + Returns: + A `batch_size` 1-D tensor of per-example sampled softmax losses. + + """ + return sampled_softmax_loss( + weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=num_true, + sampled_values=sampled_values, + remove_accidental_hits=remove_accidental_hits, + partition_strategy="div", + name=name, + seed=seed) + + +@tf_export(v1=["nn.sampled_softmax_loss"]) +@dispatch.add_dispatch_support +def sampled_softmax_loss(weights, + biases, + labels, + inputs, + num_sampled, + num_classes, + num_true=1, + sampled_values=None, + remove_accidental_hits=True, + partition_strategy="mod", + name="sampled_softmax_loss", + seed=None): + """Computes and returns the sampled softmax training loss. + + This is a faster way to train a softmax classifier over a huge number of + classes. + + This operation is for training only. It is generally an underestimate of + the full softmax loss. + + A common use case is to use this method for training, and calculate the full + softmax loss for evaluation or inference. In this case, you must set + `partition_strategy="div"` for the two losses to be consistent, as in the + following example: + + ```python + if mode == "train": + loss = tf.nn.sampled_softmax_loss( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + ..., + partition_strategy="div") + elif mode == "eval": + logits = tf.matmul(inputs, tf.transpose(weights)) + logits = tf.nn.bias_add(logits, biases) + labels_one_hot = tf.one_hot(labels, n_classes) + loss = tf.nn.softmax_cross_entropy_with_logits( + labels=labels_one_hot, + logits=logits) + ``` + + See our Candidate Sampling Algorithms Reference + ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)). + Also see Section 3 of (Jean et al., 2014) for the math. + + Args: + weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` + objects whose concatenation along dimension 0 has shape + [num_classes, dim]. The (possibly-sharded) class embeddings. + biases: A `Tensor` of shape `[num_classes]`. The class biases. + labels: A `Tensor` of type `int64` and shape `[batch_size, + num_true]`. The target classes. Note that this format differs from + the `labels` argument of `nn.softmax_cross_entropy_with_logits`. + inputs: A `Tensor` of shape `[batch_size, dim]`. The forward + activations of the input network. + num_sampled: An `int`. The number of classes to randomly sample per batch. + num_classes: An `int`. The number of possible classes. + num_true: An `int`. The number of target classes per training example. + sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, + `sampled_expected_count`) returned by a `*_candidate_sampler` function. + (if None, we default to `log_uniform_candidate_sampler`) + remove_accidental_hits: A `bool`. whether to remove "accidental hits" + where a sampled class equals one of the target classes. Default is + True. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. + Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. + name: A name for the operation (optional). + seed: random seed for candidate sampling. Default to None, which doesn't set + the op-level random seed for candidate sampling. + + Returns: + A `batch_size` 1-D tensor of per-example sampled softmax losses. + + References: + On Using Very Large Target Vocabulary for Neural Machine Translation: + [Jean et al., 2014] + (https://aclanthology.coli.uni-saarland.de/papers/P15-1001/p15-1001) + ([pdf](http://aclweb.org/anthology/P15-1001)) + """ + logits, labels = _compute_sampled_logits( + weights=weights, + biases=biases, + labels=labels, + inputs=inputs, + num_sampled=num_sampled, + num_classes=num_classes, + num_true=num_true, + sampled_values=sampled_values, + subtract_log_q=True, + remove_accidental_hits=remove_accidental_hits, + partition_strategy=partition_strategy, + name=name, + seed=seed) + labels = array_ops.stop_gradient(labels, name="labels_stop_gradient") + sampled_losses = nn_ops.softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits) + # sampled_losses is a [batch_size] tensor. + return sampled_losses diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl_distribute.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl_distribute.py new file mode 100644 index 0000000000000000000000000000000000000000..b26115e2222f50b4e6c484451afe071e654a349a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_impl_distribute.py @@ -0,0 +1,142 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Implementation of Neural Net (NN) functions with distribution strategy.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.losses import util as losses_util +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("nn.scale_regularization_loss") +@dispatch.add_dispatch_support +def scale_regularization_loss(regularization_loss): + """Scales the sum of the given regularization losses by number of replicas. + + Usage with distribution strategy and custom training loop: + + ```python + with strategy.scope(): + def compute_loss(self, label, predictions): + per_example_loss = tf.keras.losses.sparse_categorical_crossentropy( + labels, predictions) + + # Compute loss that is scaled by sample_weight and by global batch size. + loss = tf.nn.compute_average_loss( + per_example_loss, + sample_weight=sample_weight, + global_batch_size=GLOBAL_BATCH_SIZE) + + # Add scaled regularization losses. + loss += tf.nn.scale_regularization_loss(tf.nn.l2_loss(weights)) + return loss + ``` + + Args: + regularization_loss: Regularization loss. + + Returns: + Scalar loss value. + """ # pylint: disable=g-doc-exception + if ( + distribute_lib.has_strategy() + and distribute_lib.in_cross_replica_context() + ): + raise RuntimeError( + "You are calling `scale_regularization_loss` in cross replica context, " + "while it was expected to be called in replica context." + ) + + num_replicas = distribute_lib.get_strategy().num_replicas_in_sync + return math_ops.reduce_sum(regularization_loss) / num_replicas + + +@tf_export("nn.compute_average_loss") +@dispatch.add_dispatch_support +def compute_average_loss( + per_example_loss, sample_weight=None, global_batch_size=None +): + """Scales per-example losses with sample_weights and computes their average. + + Usage with distribution strategy and custom training loop: + + ```python + with strategy.scope(): + def compute_loss(labels, predictions, sample_weight=None): + + # If you are using a `Loss` class instead, set reduction to `NONE` so that + # we can do the reduction afterwards and divide by global batch size. + per_example_loss = tf.keras.losses.sparse_categorical_crossentropy( + labels, predictions) + + # Compute loss that is scaled by sample_weight and by global batch size. + return tf.nn.compute_average_loss( + per_example_loss, + sample_weight=sample_weight, + global_batch_size=GLOBAL_BATCH_SIZE) + ``` + + Args: + per_example_loss: Per-example loss. + sample_weight: Optional weighting for each example. + global_batch_size: Optional global batch size value. Defaults to (size of + first dimension of `losses`) * (number of replicas). + + Returns: + Scalar loss value, obtained by summing the `per_example_loss` and dividing + by `global_batch_size`. If `global_batch_size` is zero, the result is zero. + """ # pylint: disable=g-doc-exception + per_example_loss = ops.convert_to_tensor(per_example_loss) + input_dtype = per_example_loss.dtype + + with losses_util.check_per_example_loss_rank(per_example_loss): + if sample_weight is not None: + sample_weight = ops.convert_to_tensor(sample_weight) + per_example_loss = losses_util.scale_losses_by_sample_weight( + per_example_loss, sample_weight + ) + per_example_loss = math_ops.cast(per_example_loss, input_dtype) + + if global_batch_size is None: + if ( + distribute_lib.has_strategy() + and distribute_lib.in_cross_replica_context() + ): + raise RuntimeError( + "You are calling `compute_average_loss` in cross replica context, " + "while it was expected to be called in replica context." + ) + + num_replicas = distribute_lib.get_strategy().num_replicas_in_sync + per_replica_batch_size = array_ops.shape_v2(per_example_loss)[0] + global_batch_size = per_replica_batch_size * num_replicas + + check_ops.assert_scalar_v2( + global_batch_size, message="global_batch_size must be scalar." + ) + check_ops.assert_integer_v2( + global_batch_size, message="global_batch_size must be an integer." + ) + check_ops.assert_non_negative_v2( + global_batch_size, message="global_batch_size must be non-negative." + ) + + loss = math_ops.reduce_sum(per_example_loss) + global_batch_size = math_ops.cast(global_batch_size, input_dtype) + return math_ops.div_no_nan(loss, global_batch_size) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f624e106bf931a85300c3f76a859678bc46f58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/nn_ops.py @@ -0,0 +1,6697 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Primitive Neural Net (NN) Operations. + +## Notes on padding + +Several neural network operations, such as `tf.nn.conv2d` and +`tf.nn.max_pool2d`, take a `padding` parameter, which controls how the input is +padded before running the operation. The input is padded by inserting values +(typically zeros) before and after the tensor in each spatial dimension. The +`padding` parameter can either be the string `'VALID'`, which means use no +padding, or `'SAME'` which adds padding according to a formula which is +described below. Certain ops also allow the amount of padding per dimension to +be explicitly specified by passing a list to `padding`. + +In the case of convolutions, the input is padded with zeros. In case of pools, +the padded input values are ignored. For example, in a max pool, the sliding +window ignores padded values, which is equivalent to the padded values being +`-infinity`. + +### `'VALID'` padding + +Passing `padding='VALID'` to an op causes no padding to be used. This causes the +output size to typically be smaller than the input size, even when the stride is +one. In the 2D case, the output size is computed as: + +```python +out_height = ceil((in_height - filter_height + 1) / stride_height) +out_width = ceil((in_width - filter_width + 1) / stride_width) +``` + +The 1D and 3D cases are similar. Note `filter_height` and `filter_width` refer +to the filter size after dilations (if any) for convolutions, and refer to the +window size for pools. + +### `'SAME'` padding + +With `'SAME'` padding, padding is applied to each spatial dimension. When the +strides are 1, the input is padded such that the output size is the same as the +input size. In the 2D case, the output size is computed as: + +```python +out_height = ceil(in_height / stride_height) +out_width = ceil(in_width / stride_width) +``` + +The amount of padding used is the smallest amount that results in the output +size. The formula for the total amount of padding per dimension is: + +```python +if (in_height % strides[1] == 0): + pad_along_height = max(filter_height - stride_height, 0) +else: + pad_along_height = max(filter_height - (in_height % stride_height), 0) +if (in_width % strides[2] == 0): + pad_along_width = max(filter_width - stride_width, 0) +else: + pad_along_width = max(filter_width - (in_width % stride_width), 0) +``` + +Finally, the padding on the top, bottom, left and right are: + +```python +pad_top = pad_along_height // 2 +pad_bottom = pad_along_height - pad_top +pad_left = pad_along_width // 2 +pad_right = pad_along_width - pad_left +``` + +Note that the division by 2 means that there might be cases when the padding on +both sides (top vs bottom, right vs left) are off by one. In this case, the +bottom and right sides always get the one additional padded pixel. For example, +when pad_along_height is 5, we pad 2 pixels at the top and 3 pixels at the +bottom. Note that this is different from existing libraries such as PyTorch and +Caffe, which explicitly specify the number of padded pixels and always pad the +same number of pixels on both sides. + +Here is an example of `'SAME'` padding: + +>>> in_height = 5 +>>> filter_height = 3 +>>> stride_height = 2 +>>> +>>> in_width = 2 +>>> filter_width = 2 +>>> stride_width = 1 +>>> +>>> inp = tf.ones((2, in_height, in_width, 2)) +>>> filter = tf.ones((filter_height, filter_width, 2, 2)) +>>> strides = [stride_height, stride_width] +>>> output = tf.nn.conv2d(inp, filter, strides, padding='SAME') +>>> output.shape[1] # output_height: ceil(5 / 2) +3 +>>> output.shape[2] # output_width: ceil(2 / 1) +2 + +### Explicit padding + +Certain ops, like `tf.nn.conv2d`, also allow a list of explicit padding amounts +to be passed to the `padding` parameter. This list is in the same format as what +is passed to `tf.pad`, except the padding must be a nested list, not a tensor. +For example, in the 2D case, the list is in the format `[[0, 0], [pad_top, +pad_bottom], [pad_left, pad_right], [0, 0]]` when `data_format` is its default +value of `'NHWC'`. The two `[0, 0]` pairs indicate the batch and channel +dimensions have no padding, which is required, as only spatial dimensions can +have padding. + +For example: + +>>> inp = tf.ones((1, 3, 3, 1)) +>>> filter = tf.ones((2, 2, 1, 1)) +>>> strides = [1, 1] +>>> padding = [[0, 0], [1, 2], [0, 1], [0, 0]] +>>> output = tf.nn.conv2d(inp, filter, strides, padding=padding) +>>> tuple(output.shape) +(1, 5, 3, 1) +>>> # Equivalently, tf.pad can be used, since convolutions pad with zeros. +>>> inp = tf.pad(inp, padding) +>>> # 'VALID' means to use no padding in conv2d (we already padded inp) +>>> output2 = tf.nn.conv2d(inp, filter, strides, padding='VALID') +>>> tf.debugging.assert_equal(output, output2) + +### Difference between convolution and pooling layers +How padding is used in convolution layers and pooling layers is different. For +convolution layers, padding is filled with values of zero, and padding is +multiplied with kernels. For pooling layers, padding is excluded from the +computation. For example when applying average pooling to a 4x4 grid, how much +padding is added will not impact the output. Here is an example that +demonstrates the difference. + +>>> x_in = np.array([[ +... [[2], [2]], +... [[1], [1]], +... [[1], [1]]]]) +>>> kernel_in = np.array([ # simulate the avg_pool with conv2d +... [ [[0.25]], [[0.25]] ], +... [ [[0.25]], [[0.25]] ]]) +>>> x = tf.constant(x_in, dtype=tf.float32) +>>> kernel = tf.constant(kernel_in, dtype=tf.float32) +>>> conv_out = tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding='SAME') +>>> pool_out = tf.nn.avg_pool(x, [2, 2], strides=[1, 1, 1, 1], padding='SAME') +>>> print(conv_out.shape, pool_out.shape) +(1, 3, 2, 1) (1, 3, 2, 1) +>>> tf.reshape(conv_out, [3, 2]).numpy() # conv2d takes account of padding +array([[1.5 , 0.75], + [1. , 0.5 ], + [0.5 , 0.25]], dtype=float32) +>>> tf.reshape(pool_out, [3, 2]).numpy() # avg_pool excludes padding +array([[1.5, 1.5], + [1. , 1. ], + [1. , 1. ]], dtype=float32) + +API docstring: tensorflow.nn +""" + +import functools +import numbers + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import graph_util +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import math_ops +# Ensure all gradients are registered for nn_ops +from tensorflow.python.ops import nn_grad # pylint: disable=unused-import +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.ops import variables as variables_lib +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_nn_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.platform import device_context +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.deprecation import deprecated_argument_lookup + +from tensorflow.python.util.tf_export import tf_export + +# Aliases for some automatically-generated names. +local_response_normalization = gen_nn_ops.lrn + +# pylint: disable=protected-access +# pylint: disable=g-classes-have-attributes + +# Acceptable channels last formats (robust to H, W, D order). +_CHANNELS_LAST_FORMATS = frozenset({ + "NWC", "NHC", "NHWC", "NWHC", "NDHWC", "NDWHC", "NHDWC", "NHWDC", "NWDHC", + "NWHDC" +}) + + +def _get_sequence(value, n, channel_index, name): + """Formats a value input for gen_nn_ops.""" + # Performance is fast-pathed for common cases: + # `None`, `list`, `tuple` and `int`. + if value is None: + return [1] * (n + 2) + + # Always convert `value` to a `list`. + if isinstance(value, list): + pass + elif isinstance(value, tuple): + value = list(value) + elif isinstance(value, int): + value = [value] + elif not isinstance(value, collections_abc.Sized): + value = [value] + else: + value = list(value) # Try casting to a list. + + len_value = len(value) + + # Fully specified, including batch and channel dims. + if len_value == n + 2: + return value + + # Apply value to spatial dims only. + if len_value == 1: + value = value * n # Broadcast to spatial dimensions. + elif len_value != n: + raise ValueError(f"{name} should be of length 1, {n} or {n + 2}. " + f"Received: {name}={value} of length {len_value}") + + # Add batch and channel dims (always 1). + if channel_index == 1: + return [1, 1] + value + else: + return [1] + value + [1] + + +def _non_atrous_convolution( + input, # pylint: disable=redefined-builtin + filter, # pylint: disable=redefined-builtin + padding, + data_format=None, # pylint: disable=redefined-builtin + strides=None, + name=None): + """Computes sums of N-D convolutions (actually cross correlation). + + It is required that 1 <= N <= 3. + + This is used to implement the more generic `convolution` function, which + extends the interface of this function with a `dilation_rate` parameter. + + Args: + + input: Rank N+2 tensor of type T of shape + `[batch_size] + input_spatial_shape + [in_channels]` if `data_format` + does not start with `"NC"`, or + `[batch_size, in_channels] + input_spatial_shape` if `data_format` starts + with `"NC"`. + filter: Rank N+2 tensor of type T of shape + `filter_spatial_shape + [in_channels, out_channels]`. Rank of either + `input` or `filter` must be known. + padding: Padding method to use, must be either "VALID" or "SAME". + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". + For N=3, the valid values are "NDHWC" (default) and "NCDHW". + strides: Sequence of N positive integers, defaults to `[1] * N`. + name: Name prefix to use. + + Returns: + Rank N+2 tensor of type T of shape + `[batch_size] + output_spatial_shape + [out_channels]`, where + if padding == "SAME": + output_spatial_shape = input_spatial_shape + if padding == "VALID": + output_spatial_shape = input_spatial_shape - filter_spatial_shape + 1. + + Raises: + ValueError: if ranks are incompatible. + + """ + with ops.name_scope(name, "non_atrous_convolution", [input, filter]) as scope: + input = ops.convert_to_tensor(input, name="input") # pylint: disable=redefined-builtin + input_shape = input.shape + filter = ops.convert_to_tensor(filter, name="filter") # pylint: disable=redefined-builtin + filter_shape = filter.shape + op = _NonAtrousConvolution( + input_shape, + filter_shape=filter_shape, + padding=padding, + data_format=data_format, + strides=strides, + name=scope) + return op(input, filter) + + +class _NonAtrousConvolution: + """Helper class for _non_atrous_convolution. + + Note that this class assumes that shapes of input and filter passed to + `__call__` are compatible with `input_shape` and filter_shape passed to the + constructor. + + Args: + input_shape: static input shape, i.e. input.shape. + filter_shape: static filter shape, i.e. filter.shape. + padding: see _non_atrous_convolution. + data_format: see _non_atrous_convolution. + strides: see _non_atrous_convolution. + name: see _non_atrous_convolution. + num_batch_dims: (Optional.) The number of batch dimensions in the input; + if not provided, the default of `1` is used. + """ + + def __init__( + self, + input_shape, + filter_shape, + padding, + data_format=None, + strides=None, + name=None, + num_batch_dims=1): + # filter shape is always rank num_spatial_dims + 2 + # and num_spatial_dims == input_shape.ndims - num_batch_dims - 1 + if input_shape.ndims is not None: + filter_shape = filter_shape.with_rank( + input_shape.ndims - num_batch_dims + 1) + self.padding = padding + self.name = name + # input shape is == num_spatial_dims + num_batch_dims + 1 + # and filter_shape is always rank num_spatial_dims + 2 + if filter_shape.ndims is not None: + input_shape = input_shape.with_rank( + filter_shape.ndims + num_batch_dims - 1) + if input_shape.ndims is None: + raise ValueError( + "Rank of convolution must be known. " + f"Received: input_shape={input_shape} of rank {input_shape.rank}") + if input_shape.ndims < 3 or input_shape.ndims - num_batch_dims + 1 > 5: + raise ValueError( + "`input_shape.rank - num_batch_dims + 1` must be at least 3 and at " + f"most 5. Received: input_shape.rank={input_shape.rank} and " + f"num_batch_dims={num_batch_dims}") + conv_dims = input_shape.ndims - num_batch_dims - 1 + if strides is None: + strides = [1] * conv_dims + elif len(strides) != conv_dims: + raise ValueError( + f"`len(strides)` should be {conv_dims}. " + f"Received: strides={strides} of length {len(strides)}") + if conv_dims == 1: + # conv1d uses the 2-d data format names + if data_format is None: + data_format = "NWC" + elif data_format not in {"NCW", "NWC", "NCHW", "NHWC"}: + raise ValueError("`data_format` must be 'NWC' or 'NCW'. " + f"Received: data_format={data_format}") + self.strides = strides[0] + self.data_format = data_format + self.conv_op = self._conv1d + elif conv_dims == 2: + if data_format is None or data_format == "NHWC": + data_format = "NHWC" + strides = [1] + list(strides) + [1] + elif data_format == "NCHW": + strides = [1, 1] + list(strides) + else: + raise ValueError("`data_format` must be 'NHWC' or 'NCHW'. " + f"Received: data_format={data_format}") + self.strides = strides + self.data_format = data_format + self.conv_op = conv2d + elif conv_dims == 3: + if data_format is None or data_format == "NDHWC": + strides = [1] + list(strides) + [1] + elif data_format == "NCDHW": + strides = [1, 1] + list(strides) + else: + raise ValueError("`data_format` must be 'NDHWC' or 'NCDHW'. " + f"Received: data_format={data_format}") + self.strides = strides + self.data_format = data_format + self.conv_op = _conv3d_expanded_batch + + # Note that we need this adapter since argument names for conv1d don't match + # those for gen_nn_ops.conv2d and gen_nn_ops.conv3d. + # pylint: disable=redefined-builtin + def _conv1d(self, input, filter, strides, padding, data_format, name): + return conv1d( + value=input, + filters=filter, + stride=strides, + padding=padding, + data_format=data_format, + name=name) + # pylint: enable=redefined-builtin + + def __call__(self, inp, filter): # pylint: disable=redefined-builtin + return self.conv_op( + input=inp, + filter=filter, + strides=self.strides, + padding=self.padding, + data_format=self.data_format, + name=self.name) + + +def squeeze_batch_dims(inp, op, inner_rank, name=None): + """Returns `unsqueeze_batch(op(squeeze_batch(inp)))`. + + Where `squeeze_batch` reshapes `inp` to shape + `[prod(inp.shape[:-inner_rank])] + inp.shape[-inner_rank:]` + and `unsqueeze_batch` does the reverse reshape but on the output. + + Args: + inp: A tensor with dims `batch_shape + inner_shape` where `inner_shape` + is length `inner_rank`. + op: A callable that takes a single input tensor and returns a single. + output tensor. + inner_rank: A python integer. + name: A string. + + Returns: + `unsqueeze_batch_op(squeeze_batch(inp))`. + """ + with ops.name_scope(name, "squeeze_batch_dims", [inp]): + inp = ops.convert_to_tensor(inp, name="input") + shape = inp.shape + + inner_shape = shape[-inner_rank:] + if not inner_shape.is_fully_defined(): + inner_shape = array_ops.shape(inp)[-inner_rank:] + + batch_shape = shape[:-inner_rank] + if not batch_shape.is_fully_defined(): + batch_shape = array_ops.shape(inp)[:-inner_rank] + + if isinstance(inner_shape, tensor_shape.TensorShape): + inp_reshaped = array_ops.reshape(inp, [-1] + inner_shape.as_list()) + else: + inp_reshaped = array_ops.reshape( + inp, array_ops.concat(([-1], inner_shape), axis=-1)) + + out_reshaped = op(inp_reshaped) + + out_inner_shape = out_reshaped.shape[-inner_rank:] + if not out_inner_shape.is_fully_defined(): + out_inner_shape = array_ops.shape(out_reshaped)[-inner_rank:] + + out = array_ops.reshape( + out_reshaped, array_ops.concat((batch_shape, out_inner_shape), axis=-1)) + + out.set_shape(inp.shape[:-inner_rank] + out.shape[-inner_rank:]) + return out + + +@tf_export("nn.dilation2d", v1=[]) +@dispatch.add_dispatch_support +def dilation2d_v2( + input, # pylint: disable=redefined-builtin + filters, # pylint: disable=redefined-builtin + strides, + padding, + data_format, + dilations, + name=None): + """Computes the grayscale dilation of 4-D `input` and 3-D `filters` tensors. + + The `input` tensor has shape `[batch, in_height, in_width, depth]` and the + `filters` tensor has shape `[filter_height, filter_width, depth]`, i.e., each + input channel is processed independently of the others with its own + structuring function. The `output` tensor has shape + `[batch, out_height, out_width, depth]`. The spatial dimensions of the output + tensor depend on the `padding` algorithm. We currently only support the + default "NHWC" `data_format`. + + In detail, the grayscale morphological 2-D dilation is the max-sum correlation + (for consistency with `conv2d`, we use unmirrored filters): + + output[b, y, x, c] = + max_{dy, dx} input[b, + strides[1] * y + rates[1] * dy, + strides[2] * x + rates[2] * dx, + c] + + filters[dy, dx, c] + + Max-pooling is a special case when the filter has size equal to the pooling + kernel size and contains all zeros. + + Note on duality: The dilation of `input` by the `filters` is equal to the + negation of the erosion of `-input` by the reflected `filters`. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, + `uint32`, `uint64`. + 4-D with shape `[batch, in_height, in_width, depth]`. + filters: A `Tensor`. Must have the same type as `input`. + 3-D with shape `[filter_height, filter_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + The stride of the sliding window for each dimension of the input + tensor. Must be: `[1, stride_height, stride_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A `string`, only `"NHWC"` is currently supported. + dilations: A list of `ints` that has length `>= 4`. + The input stride for atrous morphological dilation. Must be: + `[1, rate_height, rate_width, 1]`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + if data_format != "NHWC": + raise ValueError("`data_format` values other than 'NHWC' are not " + f"supported. Received: data_format={data_format}") + + return gen_nn_ops.dilation2d(input=input, + filter=filters, + strides=strides, + rates=dilations, + padding=padding, + name=name) + + +@tf_export(v1=["nn.dilation2d"]) +@dispatch.add_dispatch_support +def dilation2d_v1( # pylint: disable=missing-docstring + input, # pylint: disable=redefined-builtin + filter=None, # pylint: disable=redefined-builtin + strides=None, + rates=None, + padding=None, + name=None, + filters=None, + dilations=None): + filter = deprecated_argument_lookup("filters", filters, "filter", filter) + rates = deprecated_argument_lookup("dilations", dilations, "rates", rates) + return gen_nn_ops.dilation2d(input, filter, strides, rates, padding, name) + + +dilation2d_v1.__doc__ = gen_nn_ops.dilation2d.__doc__ + + +@tf_export("nn.with_space_to_batch") +@dispatch.add_dispatch_support +def with_space_to_batch( + input, # pylint: disable=redefined-builtin + dilation_rate, + padding, + op, + filter_shape=None, + spatial_dims=None, + data_format=None): + """Performs `op` on the space-to-batch representation of `input`. + + This has the effect of transforming sliding window operations into the + corresponding "atrous" operation in which the input is sampled at the + specified `dilation_rate`. + + In the special case that `dilation_rate` is uniformly 1, this simply returns: + + op(input, num_spatial_dims, padding) + + Otherwise, it returns: + + batch_to_space_nd( + op(space_to_batch_nd(input, adjusted_dilation_rate, adjusted_paddings), + num_spatial_dims, + "VALID") + adjusted_dilation_rate, + adjusted_crops), + + where: + + adjusted_dilation_rate is an int64 tensor of shape [max(spatial_dims)], + adjusted_{paddings,crops} are int64 tensors of shape [max(spatial_dims), 2] + + defined as follows: + + We first define two int64 tensors `paddings` and `crops` of shape + `[num_spatial_dims, 2]` based on the value of `padding` and the spatial + dimensions of the `input`: + + If `padding = "VALID"`, then: + + paddings, crops = required_space_to_batch_paddings( + input_shape[spatial_dims], + dilation_rate) + + If `padding = "SAME"`, then: + + dilated_filter_shape = + filter_shape + (filter_shape - 1) * (dilation_rate - 1) + + paddings, crops = required_space_to_batch_paddings( + input_shape[spatial_dims], + dilation_rate, + [(dilated_filter_shape - 1) // 2, + dilated_filter_shape - 1 - (dilated_filter_shape - 1) // 2]) + + Because `space_to_batch_nd` and `batch_to_space_nd` assume that the spatial + dimensions are contiguous starting at the second dimension, but the specified + `spatial_dims` may not be, we must adjust `dilation_rate`, `paddings` and + `crops` in order to be usable with these operations. For a given dimension, + if the block size is 1, and both the starting and ending padding and crop + amounts are 0, then space_to_batch_nd effectively leaves that dimension alone, + which is what is needed for dimensions not part of `spatial_dims`. + Furthermore, `space_to_batch_nd` and `batch_to_space_nd` handle this case + efficiently for any number of leading and trailing dimensions. + + For 0 <= i < len(spatial_dims), we assign: + + adjusted_dilation_rate[spatial_dims[i] - 1] = dilation_rate[i] + adjusted_paddings[spatial_dims[i] - 1, :] = paddings[i, :] + adjusted_crops[spatial_dims[i] - 1, :] = crops[i, :] + + All unassigned values of `adjusted_dilation_rate` default to 1, while all + unassigned values of `adjusted_paddings` and `adjusted_crops` default to 0. + + Note in the case that `dilation_rate` is not uniformly 1, specifying "VALID" + padding is equivalent to specifying `padding = "SAME"` with a filter_shape of + `[1]*N`. + + Advanced usage. Note the following optimization: A sequence of + `with_space_to_batch` operations with identical (not uniformly 1) + `dilation_rate` parameters and "VALID" padding + + net = with_space_to_batch(net, dilation_rate, "VALID", op_1) + ... + net = with_space_to_batch(net, dilation_rate, "VALID", op_k) + + can be combined into a single `with_space_to_batch` operation as follows: + + def combined_op(converted_input, num_spatial_dims, _): + result = op_1(converted_input, num_spatial_dims, "VALID") + ... + result = op_k(result, num_spatial_dims, "VALID") + + net = with_space_to_batch(net, dilation_rate, "VALID", combined_op) + + This eliminates the overhead of `k-1` calls to `space_to_batch_nd` and + `batch_to_space_nd`. + + Similarly, a sequence of `with_space_to_batch` operations with identical (not + uniformly 1) `dilation_rate` parameters, "SAME" padding, and odd filter + dimensions + + net = with_space_to_batch(net, dilation_rate, "SAME", op_1, filter_shape_1) + ... + net = with_space_to_batch(net, dilation_rate, "SAME", op_k, filter_shape_k) + + can be combined into a single `with_space_to_batch` operation as follows: + + def combined_op(converted_input, num_spatial_dims, _): + result = op_1(converted_input, num_spatial_dims, "SAME") + ... + result = op_k(result, num_spatial_dims, "SAME") + + net = with_space_to_batch(net, dilation_rate, "VALID", combined_op) + + Args: + input: Tensor of rank > max(spatial_dims). + dilation_rate: int32 Tensor of *known* shape [num_spatial_dims]. + padding: str constant equal to "VALID" or "SAME" + op: Function that maps (input, num_spatial_dims, padding) -> output + filter_shape: If padding = "SAME", specifies the shape of the convolution + kernel/pooling window as an integer Tensor of shape [>=num_spatial_dims]. + If padding = "VALID", filter_shape is ignored and need not be specified. + spatial_dims: Monotonically increasing sequence of `num_spatial_dims` + integers (which are >= 1) specifying the spatial dimensions of `input` + and output. Defaults to: `range(1, num_spatial_dims+1)`. + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". + For N=3, the valid values are "NDHWC" (default) and "NCDHW". + + Returns: + The output Tensor as described above, dimensions will vary based on the op + provided. + + Raises: + ValueError: if `padding` is invalid or the arguments are incompatible. + ValueError: if `spatial_dims` are invalid. + """ + input = ops.convert_to_tensor(input, name="input") # pylint: disable=redefined-builtin + input_shape = input.shape + + def build_op(num_spatial_dims, padding): + return lambda inp, _: op(inp, num_spatial_dims, padding) + + new_op = _WithSpaceToBatch( + input_shape, + dilation_rate, + padding, + build_op, + filter_shape=filter_shape, + spatial_dims=spatial_dims, + data_format=data_format) + return new_op(input, None) + + +class _WithSpaceToBatch: + """Helper class for with_space_to_batch. + + Note that this class assumes that shapes of input and filter passed to + `__call__` are compatible with `input_shape`, `filter_shape`, and + `spatial_dims` passed to the constructor. + + Arguments + input_shape: static shape of input. i.e. input.shape. + dilation_rate: see `with_space_to_batch`. + padding: see `with_space_to_batch`. + build_op: Function that maps (num_spatial_dims, paddings) -> (function that + maps (input, filter) -> output). + filter_shape: see `with_space_to_batch`. + spatial_dims: `see with_space_to_batch`. + data_format: see `with_space_to_batch`. + num_batch_dims: (Optional). Number of batch dims in `input_shape`. + """ + + def __init__(self, + input_shape, + dilation_rate, + padding, + build_op, + filter_shape=None, + spatial_dims=None, + data_format=None, + num_batch_dims=1): + """Helper class for _with_space_to_batch.""" + dilation_rate = ops.convert_to_tensor( + dilation_rate, dtypes.int32, name="dilation_rate") + if dilation_rate.shape.ndims not in (None, 1): + raise ValueError( + "`dilation_rate.shape.rank` must be 1. Received: " + f"dilation_rate={dilation_rate} of rank {dilation_rate.shape.rank}") + + if not dilation_rate.shape.is_fully_defined(): + raise ValueError( + "`dilation_rate.shape` must be fully defined. Received: " + f"dilation_rate={dilation_rate} with shape " + f"{dilation_rate.shape}") + + num_spatial_dims = dilation_rate.shape.dims[0].value + + if data_format is not None and data_format.startswith("NC"): + starting_spatial_dim = num_batch_dims + 1 + else: + starting_spatial_dim = num_batch_dims + + if spatial_dims is None: + spatial_dims = range(starting_spatial_dim, + num_spatial_dims + starting_spatial_dim) + orig_spatial_dims = list(spatial_dims) + spatial_dims = sorted(set(int(x) for x in orig_spatial_dims)) + if spatial_dims != orig_spatial_dims or any(x < 1 for x in spatial_dims): + raise ValueError( + "`spatial_dims` must be a monotonically increasing sequence of " + f"positive integers. Received: spatial_dims={orig_spatial_dims}") + + if data_format is not None and data_format.startswith("NC"): + expected_input_rank = spatial_dims[-1] + else: + expected_input_rank = spatial_dims[-1] + 1 + + try: + input_shape.with_rank_at_least(expected_input_rank) + except ValueError: + raise ValueError( + f"`input.shape.rank` must be at least {expected_input_rank}. " + f"Received: input.shape={input_shape} with rank {input_shape.rank}") + + const_rate = tensor_util.constant_value(dilation_rate) + rate_or_const_rate = dilation_rate + if const_rate is not None: + rate_or_const_rate = const_rate + if np.any(const_rate < 1): + raise ValueError( + "`dilation_rate` must be positive. " + f"Received: dilation_rate={const_rate}") + if np.all(const_rate == 1): + self.call = build_op(num_spatial_dims, padding) + return + + padding, explicit_paddings = convert_padding(padding) + + # We have two padding contributions. The first is used for converting "SAME" + # to "VALID". The second is required so that the height and width of the + # zero-padded value tensor are multiples of rate. + + # Padding required to reduce to "VALID" convolution + if padding == "SAME": + if filter_shape is None: + raise ValueError( + "`filter_shape` must be specified for `padding='SAME'`. " + f"Received: filter_shape={filter_shape} and padding={padding}") + filter_shape = ops.convert_to_tensor(filter_shape, name="filter_shape") + const_filter_shape = tensor_util.constant_value(filter_shape) + if const_filter_shape is not None: + filter_shape = const_filter_shape + self.base_paddings = _with_space_to_batch_base_paddings( + const_filter_shape, num_spatial_dims, rate_or_const_rate) + else: + self.num_spatial_dims = num_spatial_dims + self.rate_or_const_rate = rate_or_const_rate + self.base_paddings = None + elif padding == "VALID": + self.base_paddings = np.zeros([num_spatial_dims, 2], np.int32) + elif padding == "EXPLICIT": + base_paddings = (np.array(explicit_paddings) + .reshape([num_spatial_dims + 2, 2])) + # Remove batch and channel dimensions + if data_format is not None and data_format.startswith("NC"): + self.base_paddings = base_paddings[2:] + else: + self.base_paddings = base_paddings[1:-1] + else: + raise ValueError("`padding` must be one of 'SAME' or 'VALID'. " + f"Received: padding={padding}") + + self.input_shape = input_shape + self.spatial_dims = spatial_dims + self.dilation_rate = dilation_rate + self.data_format = data_format + self.op = build_op(num_spatial_dims, "VALID") + self.call = self._with_space_to_batch_call + + def _with_space_to_batch_call(self, inp, filter): # pylint: disable=redefined-builtin + """Call functionality for with_space_to_batch.""" + # Handle input whose shape is unknown during graph creation. + input_spatial_shape = None + input_shape = self.input_shape + spatial_dims = self.spatial_dims + if input_shape.ndims is not None: + input_shape_list = input_shape.as_list() + input_spatial_shape = [input_shape_list[i] for i in spatial_dims] + if input_spatial_shape is None or None in input_spatial_shape: + input_shape_tensor = array_ops.shape(inp) + input_spatial_shape = array_ops_stack.stack( + [input_shape_tensor[i] for i in spatial_dims]) + + base_paddings = self.base_paddings + if base_paddings is None: + # base_paddings could not be computed at build time since static filter + # shape was not fully defined. + filter_shape = array_ops.shape(filter) + base_paddings = _with_space_to_batch_base_paddings( + filter_shape, self.num_spatial_dims, self.rate_or_const_rate) + + paddings, crops = array_ops.required_space_to_batch_paddings( + input_shape=input_spatial_shape, + base_paddings=base_paddings, + block_shape=self.dilation_rate) + + dilation_rate = _with_space_to_batch_adjust(self.dilation_rate, 1, + spatial_dims) + paddings = _with_space_to_batch_adjust(paddings, 0, spatial_dims) + crops = _with_space_to_batch_adjust(crops, 0, spatial_dims) + input_converted = array_ops.space_to_batch_nd( + input=inp, block_shape=dilation_rate, paddings=paddings) + + result = self.op(input_converted, filter) + + result_converted = array_ops.batch_to_space_nd( + input=result, block_shape=dilation_rate, crops=crops) + + # Recover channel information for output shape if channels are not last. + if self.data_format is not None and self.data_format.startswith("NC"): + if not result_converted.shape.dims[1].value and filter is not None: + output_shape = result_converted.shape.as_list() + output_shape[1] = filter.shape[-1] + result_converted.set_shape(output_shape) + + return result_converted + + def __call__(self, inp, filter): # pylint: disable=redefined-builtin + return self.call(inp, filter) + + +def _with_space_to_batch_base_paddings(filter_shape, num_spatial_dims, + rate_or_const_rate): + """Helper function to compute base_paddings.""" + # Spatial dimensions of the filters and the upsampled filters in which we + # introduce (rate - 1) zeros between consecutive filter values. + filter_spatial_shape = filter_shape[:num_spatial_dims] + pad_extra_shape = (filter_spatial_shape - 1) * rate_or_const_rate + + # When full_padding_shape is odd, we pad more at end, following the same + # convention as conv2d. + pad_extra_start = pad_extra_shape // 2 + pad_extra_end = pad_extra_shape - pad_extra_start + base_paddings = array_ops_stack.stack( + [[pad_extra_start[i], pad_extra_end[i]] for i in range(num_spatial_dims)]) + return base_paddings + + +def _with_space_to_batch_adjust(orig, fill_value, spatial_dims): + """Returns an `adjusted` version of `orig` based on `spatial_dims`. + + Tensor of the same type as `orig` and with shape + `[max(spatial_dims), ...]` where: + + adjusted[spatial_dims[i] - 1, ...] = orig[i, ...] + + for 0 <= i < len(spatial_dims), and + + adjusted[j, ...] = fill_value + + for j != spatial_dims[i] - 1 for some i. + + If `orig` is a constant value, then the result will be a constant value. + + Args: + orig: Tensor of rank > max(spatial_dims). + fill_value: Numpy scalar (of same data type as `orig) specifying the fill + value for non-spatial dimensions. + spatial_dims: See with_space_to_batch. + + Returns: + `adjusted` tensor. + """ + fill_dims = orig.get_shape().as_list()[1:] + dtype = orig.dtype.as_numpy_dtype + parts = [] + const_orig = tensor_util.constant_value(orig) + const_or_orig = const_orig if const_orig is not None else orig + prev_spatial_dim = 0 + i = 0 + while i < len(spatial_dims): + start_i = i + start_spatial_dim = spatial_dims[i] + if start_spatial_dim > 1: + # Fill in any gap from the previous spatial dimension (or dimension 1 if + # this is the first spatial dimension) with `fill_value`. + parts.append( + np.full( + [start_spatial_dim - 1 - prev_spatial_dim] + fill_dims, + fill_value, + dtype=dtype)) + # Find the largest value of i such that: + # [spatial_dims[start_i], ..., spatial_dims[i]] + # == [start_spatial_dim, ..., start_spatial_dim + i - start_i], + # i.e. the end of a contiguous group of spatial dimensions. + while (i + 1 < len(spatial_dims) and + spatial_dims[i + 1] == spatial_dims[i] + 1): + i += 1 + parts.append(const_or_orig[start_i:i + 1]) + prev_spatial_dim = spatial_dims[i] + i += 1 + if const_orig is not None: + return np.concatenate(parts) + else: + return array_ops.concat(parts, 0) + + +def _get_strides_and_dilation_rate(num_spatial_dims, strides, dilation_rate): + """Helper function for verifying strides and dilation_rate arguments. + + This is used by `convolution` and `pool`. + + Args: + num_spatial_dims: int + strides: Optional. List of N ints >= 1. Defaults to `[1]*N`. If any value + of strides is > 1, then all values of dilation_rate must be 1. + dilation_rate: Optional. List of N ints >= 1. Defaults to `[1]*N`. If any + value of dilation_rate is > 1, then all values of strides must be 1. + + Returns: + Normalized (strides, dilation_rate) as int32 numpy arrays of shape + [num_spatial_dims]. + + Raises: + ValueError: if the parameters are invalid. + """ + if dilation_rate is None: + dilation_rate = [1] * num_spatial_dims + elif len(dilation_rate) != num_spatial_dims: + raise ValueError(f"`len(dilation_rate)` should be {num_spatial_dims}. " + f"Received: dilation_rate={dilation_rate} of length " + f"{len(dilation_rate)}") + dilation_rate = np.array(dilation_rate, dtype=np.int32) + if np.any(dilation_rate < 1): + raise ValueError("all values of `dilation_rate` must be positive. " + f"Received: dilation_rate={dilation_rate}") + + if strides is None: + strides = [1] * num_spatial_dims + elif len(strides) != num_spatial_dims: + raise ValueError(f"`len(strides)` should be {num_spatial_dims}. " + f"Received: strides={strides} of length {len(strides)}") + strides = np.array(strides, dtype=np.int32) + if np.any(strides < 1): + raise ValueError("all values of `strides` must be positive. " + f"Received: strides={strides}") + + if np.any(strides > 1) and np.any(dilation_rate > 1): + raise ValueError( + "`strides > 1` not supported in conjunction with `dilation_rate > 1`. " + f"Received: strides={strides} and dilation_rate={dilation_rate}") + return strides, dilation_rate + + +@tf_export(v1=["nn.convolution"]) +@dispatch.add_dispatch_support +def convolution( + input, # pylint: disable=redefined-builtin + filter, # pylint: disable=redefined-builtin + padding, + strides=None, + dilation_rate=None, + name=None, + data_format=None, + filters=None, + dilations=None): # pylint: disable=g-doc-args + """Computes sums of N-D convolutions (actually cross-correlation). + + This also supports either output striding via the optional `strides` parameter + or atrous convolution (also known as convolution with holes or dilated + convolution, based on the French word "trous" meaning holes in English) via + the optional `dilation_rate` parameter. Currently, however, output striding + is not supported for atrous convolutions. + + Specifically, in the case that `data_format` does not start with "NC", given + a rank (N+2) `input` Tensor of shape + + [num_batches, + input_spatial_shape[0], + ..., + input_spatial_shape[N-1], + num_input_channels], + + a rank (N+2) `filter` Tensor of shape + + [spatial_filter_shape[0], + ..., + spatial_filter_shape[N-1], + num_input_channels, + num_output_channels], + + an optional `dilation_rate` tensor of shape N (defaults to `[1]*N`) specifying + the filter upsampling/input downsampling rate, and an optional list of N + `strides` (defaults to `[1]*N`), this computes for each N-D spatial output + position `(x[0], ..., x[N-1])`: + + ``` + output[b, x[0], ..., x[N-1], k] = + sum_{z[0], ..., z[N-1], q} + filter[z[0], ..., z[N-1], q, k] * + padded_input[b, + x[0]*strides[0] + dilation_rate[0]*z[0], + ..., + x[N-1]*strides[N-1] + dilation_rate[N-1]*z[N-1], + q] + ``` + + where b is the index into the batch, k is the output channel number, q is the + input channel number, and z is the N-D spatial offset within the filter. Here, + `padded_input` is obtained by zero padding the input using an effective + spatial filter shape of `(spatial_filter_shape-1) * dilation_rate + 1` and + output striding `strides`. + + In the case that `data_format` does start with `"NC"`, the `input` and output + (but not the `filter`) are simply transposed as follows: + + ```python + convolution(input, data_format, **kwargs) = + tf.transpose(convolution(tf.transpose(input, [0] + range(2,N+2) + [1]), + **kwargs), + [0, N+1] + range(1, N+1)) + ``` + + It is required that 1 <= N <= 3. + + Args: + input: An (N+2)-D `Tensor` of type `T`, of shape + `[batch_size] + input_spatial_shape + [in_channels]` if data_format does + not start with "NC" (default), or + `[batch_size, in_channels] + input_spatial_shape` if data_format starts + with "NC". + filter: An (N+2)-D `Tensor` with the same type as `input` and shape + `spatial_filter_shape + [in_channels, out_channels]`. + padding: A string, either `"VALID"` or `"SAME"`. The padding algorithm. + `"valid"` means no padding. `"same"` results in padding evenly to + the left/right or up/down of the input such that output has the same + height/width dimension as the input when the strides are 1. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + strides: Optional. Sequence of N ints >= 1. Specifies the output stride. + Defaults to `[1]*N`. If any value of strides is > 1, then all values of + dilation_rate must be 1. + dilation_rate: Optional. Sequence of N ints >= 1. Specifies the filter + upsampling/input downsampling rate. In the literature, the same parameter + is sometimes called `input stride` or `dilation`. The effective filter + size used for the convolution will be `spatial_filter_shape + + (spatial_filter_shape - 1) * (rate - 1)`, obtained by inserting + (dilation_rate[i]-1) zeros between consecutive elements of the original + filter in each spatial dimension i. If any value of dilation_rate is > 1, + then all values of strides must be 1. + name: Optional name for the returned tensor. + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". + For N=3, the valid values are "NDHWC" (default) and "NCDHW". + + Returns: + A `Tensor` with the same type as `input` of shape + + `[batch_size] + output_spatial_shape + [out_channels]` + + if data_format is None or does not start with "NC", or + + `[batch_size, out_channels] + output_spatial_shape` + + if data_format starts with "NC", + where `output_spatial_shape` depends on the value of `padding`. + + If padding == "SAME": + output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i]) + + If padding == "VALID": + output_spatial_shape[i] = + ceil((input_spatial_shape[i] - + (spatial_filter_shape[i]-1) * dilation_rate[i]) + / strides[i]). + + Raises: + ValueError: If input/output depth does not match `filter` shape, if padding + is other than `"VALID"` or `"SAME"`, or if data_format is invalid. + + """ + filter = deprecated_argument_lookup("filters", filters, "filter", filter) + dilation_rate = deprecated_argument_lookup( + "dilations", dilations, "dilation_rate", dilation_rate) + return convolution_internal( + input, + filter, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilation_rate, + name=name) + + +@tf_export("nn.convolution", v1=[]) +@dispatch.add_dispatch_support +def convolution_v2( # pylint: disable=missing-docstring + input, # pylint: disable=redefined-builtin + filters, + strides=None, + padding="VALID", + data_format=None, + dilations=None, + name=None): + return convolution_internal( + input, # pylint: disable=redefined-builtin + filters, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + +convolution_v2.__doc__ = deprecation.rewrite_argument_docstring( + deprecation.rewrite_argument_docstring( + convolution.__doc__, "dilation_rate", "dilations"), + "filter", "filters") + + +def convolution_internal( + input, # pylint: disable=redefined-builtin + filters, + strides=None, + padding="VALID", + data_format=None, + dilations=None, + name=None, + call_from_convolution=True, + num_spatial_dims=None): + """Internal function which performs rank agnostic convolution. + + Args: + input: See `convolution`. + filters: See `convolution`. + strides: See `convolution`. + padding: See `convolution`. + data_format: See `convolution`. + dilations: See `convolution`. + name: See `convolution`. + call_from_convolution: See `convolution`. + num_spatial_dims: (Optional.). It is a integer describing the + rank of the spatial dimensions. For `1-D`, `2-D` and `3-D` convolutions, + the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively. + This argument is only required to disambiguate the rank of `batch_shape` + when `filter_shape.ndims is None` and `len(batch_shape) > 1`. For + backwards compatibility, if `num_spatial_dims is None` and + `filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be + `1` (i.e., the input is expected to be + `[batch_size, num_channels] + input_spatial_shape` + or `[batch_size] + input_spatial_shape + [num_channels]`. + + Returns: + A tensor of shape and dtype matching that of `input`. + + Raises: + ValueError: If input and filter both have unknown shapes, or if + `num_spatial_dims` is provided and incompatible with the value + estimated from `filters.shape`. + """ + if (not isinstance(filters, variables_lib.Variable) and + not tensor_util.is_tf_type(filters)): + with ops.name_scope("convolution_internal", None, [filters, input]): + filters = ops.convert_to_tensor(filters, name='filters') + if (not isinstance(input, tensor_lib.Tensor) and not tensor_util.is_tf_type( + input)): + with ops.name_scope("convolution_internal", None, [filters, input]): + input = ops.convert_to_tensor(input, name="input") + + filters_rank = filters.shape.rank + inputs_rank = input.shape.rank + if num_spatial_dims is None: + if filters_rank: + num_spatial_dims = filters_rank - 2 + elif inputs_rank: + num_spatial_dims = inputs_rank - 2 + else: + raise ValueError( + "When `num_spatial_dims` is not set, one of `input.shape.rank` or " + "`filters.shape.rank` must be known. " + f"Received: input.shape={input.shape} of rank {inputs_rank} and " + f"filters.shape={filters.shape} of rank {filters_rank}") + elif filters_rank and filters_rank - 2 != num_spatial_dims: + raise ValueError( + "`filters.shape.rank - 2` should equal `num_spatial_dims`. Received: " + f"filters.shape={filters.shape} of rank {filters_rank} and " + f"num_spatial_dims={num_spatial_dims}") + + if inputs_rank: + num_batch_dims = inputs_rank - num_spatial_dims - 1 # Channel dimension. + else: + num_batch_dims = 1 # By default, assume single batch dimension. + + if num_spatial_dims not in {1, 2, 3}: + raise ValueError( + "`num_spatial_dims` must be 1, 2, or 3. " + f"Received: num_spatial_dims={num_spatial_dims}.") + + if data_format is None or data_format in _CHANNELS_LAST_FORMATS: + channel_index = num_batch_dims + num_spatial_dims + else: + channel_index = num_batch_dims + + if dilations is None: + dilations = _get_sequence(dilations, num_spatial_dims, channel_index, + "dilations") + is_dilated_conv = False + else: + dilations = _get_sequence(dilations, num_spatial_dims, channel_index, + "dilations") + is_dilated_conv = any(i != 1 for i in dilations) + + strides = _get_sequence(strides, num_spatial_dims, channel_index, "strides") + has_tpu_context = device_context.enclosing_tpu_context() is not None + + if name: + default_name = None + elif not has_tpu_context or call_from_convolution: + default_name = "convolution" + elif num_spatial_dims == 2: # Most common case. + default_name = "Conv2D" + elif num_spatial_dims == 3: + default_name = "Conv3D" + else: + default_name = "conv1d" + + with ops.name_scope(name, default_name, [input, filters]) as name: + # Fast path for TPU or if no dilation, as gradient only supported on TPU + # for dilations. + if not is_dilated_conv or has_tpu_context: + if num_spatial_dims == 2: # Most common case. + op = _conv2d_expanded_batch + elif num_spatial_dims == 3: + op = _conv3d_expanded_batch + else: + op = conv1d + + return op( + input, + filters, + strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + else: + if channel_index == 1: + strides = strides[2:] + dilations = dilations[2:] + else: + strides = strides[1:-1] + dilations = dilations[1:-1] + + op = Convolution( + tensor_shape.as_shape(input.shape), + tensor_shape.as_shape(filters.shape), + padding, + strides=strides, + dilation_rate=dilations, + name=name, + data_format=data_format, + num_spatial_dims=num_spatial_dims) + return op(input, filters) + + +class Convolution: + """Helper class for convolution. + + Note that this class assumes that shapes of input and filter passed to + `__call__` are compatible with `input_shape`, `filter_shape`, and + `num_spatial_dims` passed to the constructor. + + Arguments + input_shape: static shape of input. i.e. input.shape. Its length is + `batch_shape + input_spatial_shape + [num_channels]` if `data_format` + does not start with `NC`, or + `batch_shape + [num_channels] + input_spatial_shape` if `data_format` + starts with `NC`. + filter_shape: static shape of the filter. i.e. filter.shape. + padding: The padding algorithm, must be "SAME" or "VALID". + strides: see convolution. + dilation_rate: see convolution. + name: see convolution. + data_format: A string or `None`. Specifies whether the channel dimension of + the `input` and output is the last dimension (if `data_format` is `None` + or does not start with `NC`), or the first post-batch dimension (i.e. if + `data_format` starts with `NC`). + num_spatial_dims: (Usually optional.) Python integer, the rank of the + spatial and channel dimensions. For `1-D`, `2-D` and `3-D` convolutions, + the value of `num_spatial_dims` is `1`, `2`, and `3`, respectively. + This argument is only required to disambiguate the rank of `batch_shape` + when `filter_shape.ndims is None` and `len(batch_shape) > 1`. For + backwards compatibility, if `num_spatial_dims is None` and + `filter_shape.ndims is None`, then `len(batch_shape)` is assumed to be + `1` (i.e., the input is expected to be + `[batch_size, num_channels] + input_spatial_shape` + or `[batch_size] + input_spatial_shape + [num_channels]`. + """ + + def __init__(self, + input_shape, + filter_shape, + padding, + strides=None, + dilation_rate=None, + name=None, + data_format=None, + num_spatial_dims=None): + """Helper function for convolution.""" + num_batch_dims = None + filter_shape = tensor_shape.as_shape(filter_shape) + input_shape = tensor_shape.as_shape(input_shape) + + if filter_shape.ndims is not None: + if (num_spatial_dims is not None and + filter_shape.ndims != num_spatial_dims + 2): + raise ValueError( + "`filters.shape.rank` must be `num_spatial_dims + 2`. Received: " + f"filters.shape={filter_shape} of rank {filter_shape.rank} and " + f"num_spatial_dims={num_spatial_dims}") + else: + num_spatial_dims = filter_shape.ndims - 2 + + if input_shape.ndims is not None and num_spatial_dims is not None: + num_batch_dims = input_shape.ndims - num_spatial_dims - 1 + + if num_spatial_dims is None: + num_spatial_dims = input_shape.ndims - 2 + else: + if input_shape.ndims is not None: + if input_shape.ndims < num_spatial_dims + 2: + raise ValueError( + "`input.shape.rank` must be >= than `num_spatial_dims + 2`. " + f"Received: input.shape={input_shape} of rank {input_shape.rank} " + f"and num_spatial_dims={num_spatial_dims}") + else: + if num_batch_dims is None: + num_batch_dims = input_shape.ndims - num_spatial_dims - 1 + + if num_spatial_dims is None: + raise ValueError( + "When `num_spatial_dims` is not set, one of `input.shape.rank` or " + "`filters.shape.rank` must be known. " + f"Received: input.shape={input_shape} of rank {input_shape.rank} and " + f"`filters.shape={filter_shape}` of rank {filter_shape.rank}") + + if num_batch_dims is None: + num_batch_dims = 1 + + if num_batch_dims < 1: + raise ValueError( + f"Batch dims should be >= 1, but found {num_batch_dims}. " + "Batch dims was estimated as " + "`input.shape.rank - num_spatial_dims - 1` and `num_spatial_dims` " + "was either provided or estimated as `filters.shape.rank - 2`. " + f"Received: input.shape={input_shape} of rank {input_shape.rank}, " + f"filters.shape={filter_shape} of rank {filter_shape.rank}, and " + f"num_spatial_dims={num_spatial_dims}") + + if data_format is None or not data_format.startswith("NC"): + input_channels_dim = tensor_shape.dimension_at_index( + input_shape, num_spatial_dims + num_batch_dims) + spatial_dims = range(num_batch_dims, num_spatial_dims + num_batch_dims) + else: + input_channels_dim = tensor_shape.dimension_at_index( + input_shape, num_batch_dims) + spatial_dims = range( + num_batch_dims + 1, num_spatial_dims + num_batch_dims + 1) + + filter_dim = tensor_shape.dimension_at_index(filter_shape, num_spatial_dims) + if not (input_channels_dim % filter_dim).is_compatible_with(0): + raise ValueError( + "The number of input channels is not divisible by the corresponding " + f"number of output filters. Received: input.shape={input_shape} with " + f"{input_channels_dim} channels and filters.shape={filter_shape} " + f"with {filter_dim} output filters.") + + strides, dilation_rate = _get_strides_and_dilation_rate( + num_spatial_dims, strides, dilation_rate) + + self.input_shape = input_shape + self.filter_shape = filter_shape + self.data_format = data_format + self.strides = strides + self.padding = padding + self.name = name + self.dilation_rate = dilation_rate + self.num_batch_dims = num_batch_dims + self.num_spatial_dims = num_spatial_dims + self.conv_op = _WithSpaceToBatch( + input_shape, + dilation_rate=dilation_rate, + padding=padding, + build_op=self._build_op, + filter_shape=filter_shape, + spatial_dims=spatial_dims, + data_format=data_format, + num_batch_dims=num_batch_dims) + + def _build_op(self, _, padding): + return _NonAtrousConvolution( + self.input_shape, + filter_shape=self.filter_shape, + padding=padding, + data_format=self.data_format, + strides=self.strides, + name=self.name, + num_batch_dims=self.num_batch_dims) + + def __call__(self, inp, filter): # pylint: disable=redefined-builtin + # TPU convolution supports dilations greater than 1. + if device_context.enclosing_tpu_context() is not None: + return convolution_internal( + inp, + filter, + strides=self.strides, + padding=self.padding, + data_format=self.data_format, + dilations=self.dilation_rate, + name=self.name, + call_from_convolution=False, + num_spatial_dims=self.num_spatial_dims) + else: + return self.conv_op(inp, filter) + + +@tf_export(v1=["nn.pool"]) +@dispatch.add_dispatch_support +def pool( + input, # pylint: disable=redefined-builtin + window_shape, + pooling_type, + padding, + dilation_rate=None, + strides=None, + name=None, + data_format=None, + dilations=None): + """Performs an N-D pooling operation. + + In the case that `data_format` does not start with "NC", computes for + 0 <= b < batch_size, + 0 <= x[i] < output_spatial_shape[i], + 0 <= c < num_channels: + + ``` + output[b, x[0], ..., x[N-1], c] = + REDUCE_{z[0], ..., z[N-1]} + input[b, + x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0], + ... + x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1], + c], + ``` + + where the reduction function REDUCE depends on the value of `pooling_type`, + and pad_before is defined based on the value of `padding` as described in + the "returns" section of `tf.nn.convolution` for details. + The reduction never includes out-of-bounds positions. + + In the case that `data_format` starts with `"NC"`, the `input` and output are + simply transposed as follows: + + ```python + pool(input, data_format, **kwargs) = + tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]), + **kwargs), + [0, N+1] + range(1, N+1)) + ``` + + Args: + input: Tensor of rank N+2, of shape + `[batch_size] + input_spatial_shape + [num_channels]` if data_format does + not start with "NC" (default), or + `[batch_size, num_channels] + input_spatial_shape` if data_format starts + with "NC". Pooling happens over the spatial dimensions only. + window_shape: Sequence of N ints >= 1. + pooling_type: Specifies pooling operation, must be "AVG" or "MAX". + padding: The padding algorithm, must be "SAME" or "VALID". + See the "returns" section of `tf.nn.convolution` for details. + dilation_rate: Optional. Dilation rate. List of N ints >= 1. + Defaults to `[1]*N`. If any value of dilation_rate is > 1, then all + values of strides must be 1. + strides: Optional. Sequence of N ints >= 1. Defaults to `[1]*N`. + If any value of strides is > 1, then all values of dilation_rate must be + 1. + name: Optional. Name of the op. + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". + For N=3, the valid values are "NDHWC" (default) and "NCDHW". + dilations: Alias for dilation_rate + + Returns: + Tensor of rank N+2, of shape + [batch_size] + output_spatial_shape + [num_channels] + + if data_format is None or does not start with "NC", or + + [batch_size, num_channels] + output_spatial_shape + + if data_format starts with "NC", + where `output_spatial_shape` depends on the value of padding: + + If padding = "SAME": + output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i]) + + If padding = "VALID": + output_spatial_shape[i] = + ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i]) + / strides[i]). + + Raises: + ValueError: if arguments are invalid. + + """ + dilation_rate = deprecated_argument_lookup( + "dilations", dilations, "dilation_rate", dilation_rate) + # pylint: enable=line-too-long + with ops.name_scope(name, "%s_pool" % (pooling_type.lower()), + [input]) as scope: + input = ops.convert_to_tensor(input, name="input") # pylint: disable=redefined-builtin + + num_spatial_dims = len(window_shape) + if num_spatial_dims < 1 or num_spatial_dims > 3: + raise ValueError("`len(window_shape)` must be 1, 2, or 3. Received: " + f"window_shape={window_shape} of length " + f"{len(window_shape)}") + + input.get_shape().with_rank(num_spatial_dims + 2) + + strides, dilation_rate = _get_strides_and_dilation_rate( + num_spatial_dims, strides, dilation_rate) + + if padding == "SAME" and np.any(dilation_rate > 1): + raise ValueError( + "pooling with 'SAME' padding is not implemented for " + f"`dilation_rate` > 1. Received: padding={padding} and " + f"dilation_rate={dilation_rate}") + + if np.any(strides > window_shape): + raise ValueError( + "`strides` > `window_shape` not supported due to inconsistency " + f"between CPU and GPU implementations. Received: strides={strides} " + f"and window_shape={window_shape}") + + pooling_ops = { + ("MAX", 1): max_pool, + ("MAX", 2): max_pool, + ("MAX", 3): max_pool3d, # pylint: disable=undefined-variable + ("AVG", 1): avg_pool, + ("AVG", 2): avg_pool, + ("AVG", 3): avg_pool3d, # pylint: disable=undefined-variable + } + op_key = (pooling_type, num_spatial_dims) + if op_key not in pooling_ops: + raise ValueError( + f"{num_spatial_dims}-D {pooling_type} pooling is not supported.") + + if data_format is None or not data_format.startswith("NC"): + adjusted_window_shape = [1] + list(window_shape) + [1] + adjusted_strides = [1] + list(strides) + [1] + spatial_dims = range(1, num_spatial_dims + 1) + else: + adjusted_window_shape = [1, 1] + list(window_shape) + adjusted_strides = [1, 1] + list(strides) + spatial_dims = range(2, num_spatial_dims + 2) + + if num_spatial_dims == 1: + if data_format is None or data_format == "NWC": + data_format_kwargs = dict(data_format="NHWC") + elif data_format == "NCW": + data_format_kwargs = dict(data_format="NCHW") + else: + raise ValueError("data_format must be either 'NWC' or 'NCW'. " + f"Received: data_format={data_format}") + adjusted_window_shape = [1] + adjusted_window_shape + adjusted_strides = [1] + adjusted_strides + else: + data_format_kwargs = dict(data_format=data_format) + + def op(converted_input, _, converted_padding): # pylint: disable=missing-docstring + if num_spatial_dims == 1: + converted_input = array_ops.expand_dims(converted_input, + spatial_dims[0]) + result = pooling_ops[op_key]( + converted_input, + adjusted_window_shape, + adjusted_strides, + converted_padding, + name=scope, + **data_format_kwargs) + if num_spatial_dims == 1: + result = array_ops.squeeze(result, [spatial_dims[0]]) + return result + + return with_space_to_batch( + input=input, + dilation_rate=dilation_rate, + padding=padding, + op=op, + spatial_dims=spatial_dims, + filter_shape=window_shape) + + +@tf_export("nn.pool", v1=[]) +@dispatch.add_dispatch_support +def pool_v2( + input, # pylint: disable=redefined-builtin + window_shape, + pooling_type, + strides=None, + padding="VALID", + data_format=None, + dilations=None, + name=None): + # pylint: disable=line-too-long + """Performs an N-D pooling operation. + + In the case that `data_format` does not start with "NC", computes for + 0 <= b < batch_size, + 0 <= x[i] < output_spatial_shape[i], + 0 <= c < num_channels: + + ``` + output[b, x[0], ..., x[N-1], c] = + REDUCE_{z[0], ..., z[N-1]} + input[b, + x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0], + ... + x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1], + c], + ``` + + where the reduction function REDUCE depends on the value of `pooling_type`, + and pad_before is defined based on the value of `padding` as described in + the "returns" section of `tf.nn.convolution` for details. + The reduction never includes out-of-bounds positions. + + In the case that `data_format` starts with `"NC"`, the `input` and output are + simply transposed as follows: + + ```python + pool(input, data_format, **kwargs) = + tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]), + **kwargs), + [0, N+1] + range(1, N+1)) + ``` + + Args: + input: Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape + + [num_channels]` if data_format does not start with "NC" (default), or + `[batch_size, num_channels] + input_spatial_shape` if data_format starts + with "NC". Pooling happens over the spatial dimensions only. + window_shape: Sequence of N ints >= 1. + pooling_type: Specifies pooling operation, must be "AVG" or "MAX". + strides: Optional. Sequence of N ints >= 1. Defaults to `[1]*N`. If any value of + strides is > 1, then all values of dilation_rate must be 1. + padding: The padding algorithm, must be "SAME" or "VALID". Defaults to "SAME". + See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For + N=3, the valid values are "NDHWC" (default) and "NCDHW". + dilations: Optional. Dilation rate. List of N ints >= 1. Defaults to + `[1]*N`. If any value of dilation_rate is > 1, then all values of strides + must be 1. + name: Optional. Name of the op. + + Returns: + Tensor of rank N+2, of shape + [batch_size] + output_spatial_shape + [num_channels] + + if data_format is None or does not start with "NC", or + + [batch_size, num_channels] + output_spatial_shape + + if data_format starts with "NC", + where `output_spatial_shape` depends on the value of padding: + + If padding = "SAME": + output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i]) + + If padding = "VALID": + output_spatial_shape[i] = + ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i]) + / strides[i]). + + Raises: + ValueError: if arguments are invalid. + """ + return pool( + input=input, + window_shape=window_shape, + pooling_type=pooling_type, + padding=padding, + dilation_rate=dilations, + strides=strides, + name=name, + data_format=data_format) + + +@tf_export("nn.atrous_conv2d") +@dispatch.add_dispatch_support +def atrous_conv2d(value, filters, rate, padding, name=None): + """Atrous convolution (a.k.a. convolution with holes or dilated convolution). + + This function is a simpler wrapper around the more general + `tf.nn.convolution`, and exists only for backwards compatibility. You can + use `tf.nn.convolution` to perform 1-D, 2-D, or 3-D atrous convolution. + + Computes a 2-D atrous convolution, also known as convolution with holes or + dilated convolution, given 4-D `value` and `filters` tensors. If the `rate` + parameter is equal to one, it performs regular 2-D convolution. If the `rate` + parameter is greater than one, it performs convolution with holes, sampling + the input values every `rate` pixels in the `height` and `width` dimensions. + This is equivalent to convolving the input with a set of upsampled filters, + produced by inserting `rate - 1` zeros between two consecutive values of the + filters along the `height` and `width` dimensions, hence the name atrous + convolution or convolution with holes (the French word trous means holes in + English). + + More specifically: + + ``` + output[batch, height, width, out_channel] = + sum_{dheight, dwidth, in_channel} ( + filters[dheight, dwidth, in_channel, out_channel] * + value[batch, height + rate*dheight, width + rate*dwidth, in_channel] + ) + ``` + + Atrous convolution allows us to explicitly control how densely to compute + feature responses in fully convolutional networks. Used in conjunction with + bilinear interpolation, it offers an alternative to `conv2d_transpose` in + dense prediction tasks such as semantic image segmentation, optical flow + computation, or depth estimation. It also allows us to effectively enlarge + the field of view of filters without increasing the number of parameters or + the amount of computation. + + For a description of atrous convolution and how it can be used for dense + feature extraction, please see: (Chen et al., 2015). The same operation is + investigated further in (Yu et al., 2016). Previous works that effectively + use atrous convolution in different ways are, among others, + (Sermanet et al., 2014) and (Giusti et al., 2013). + Atrous convolution is also closely related to the so-called noble identities + in multi-rate signal processing. + + There are many different ways to implement atrous convolution (see the refs + above). The implementation here reduces + + ```python + atrous_conv2d(value, filters, rate, padding=padding) + ``` + + to the following three operations: + + ```python + paddings = ... + net = space_to_batch(value, paddings, block_size=rate) + net = conv2d(net, filters, strides=[1, 1, 1, 1], padding="VALID") + crops = ... + net = batch_to_space(net, crops, block_size=rate) + ``` + + Advanced usage. Note the following optimization: A sequence of `atrous_conv2d` + operations with identical `rate` parameters, 'SAME' `padding`, and filters + with odd heights/ widths: + + ```python + net = atrous_conv2d(net, filters1, rate, padding="SAME") + net = atrous_conv2d(net, filters2, rate, padding="SAME") + ... + net = atrous_conv2d(net, filtersK, rate, padding="SAME") + ``` + + can be equivalently performed cheaper in terms of computation and memory as: + + ```python + pad = ... # padding so that the input dims are multiples of rate + net = space_to_batch(net, paddings=pad, block_size=rate) + net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding="SAME") + net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding="SAME") + ... + net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding="SAME") + net = batch_to_space(net, crops=pad, block_size=rate) + ``` + + because a pair of consecutive `space_to_batch` and `batch_to_space` ops with + the same `block_size` cancel out when their respective `paddings` and `crops` + inputs are identical. + + Args: + value: A 4-D `Tensor` of type `float`. It needs to be in the default "NHWC" + format. Its shape is `[batch, in_height, in_width, in_channels]`. + filters: A 4-D `Tensor` with the same type as `value` and shape + `[filter_height, filter_width, in_channels, out_channels]`. `filters`' + `in_channels` dimension must match that of `value`. Atrous convolution is + equivalent to standard convolution with upsampled filters with effective + height `filter_height + (filter_height - 1) * (rate - 1)` and effective + width `filter_width + (filter_width - 1) * (rate - 1)`, produced by + inserting `rate - 1` zeros along consecutive elements across the + `filters`' spatial dimensions. + rate: A positive int32. The stride with which we sample input values across + the `height` and `width` dimensions. Equivalently, the rate by which we + upsample the filter values by inserting zeros across the `height` and + `width` dimensions. In the literature, the same parameter is sometimes + called `input stride` or `dilation`. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + name: Optional name for the returned tensor. + + Returns: + A `Tensor` with the same type as `value`. + Output shape with `'VALID'` padding is: + + [batch, height - rate * (filter_width - 1), + width - rate * (filter_height - 1), out_channels]. + + Output shape with `'SAME'` padding is: + + [batch, height, width, out_channels]. + + Raises: + ValueError: If input/output depth does not match `filters`' shape, or if + padding is other than `'VALID'` or `'SAME'`. + + References: + Multi-Scale Context Aggregation by Dilated Convolutions: + [Yu et al., 2016](https://arxiv.org/abs/1511.07122) + ([pdf](https://arxiv.org/pdf/1511.07122.pdf)) + Semantic Image Segmentation with Deep Convolutional Nets and Fully + Connected CRFs: + [Chen et al., 2015](http://arxiv.org/abs/1412.7062) + ([pdf](https://arxiv.org/pdf/1412.7062)) + OverFeat - Integrated Recognition, Localization and Detection using + Convolutional Networks: + [Sermanet et al., 2014](https://arxiv.org/abs/1312.6229) + ([pdf](https://arxiv.org/pdf/1312.6229.pdf)) + Fast Image Scanning with Deep Max-Pooling Convolutional Neural Networks: + [Giusti et al., 2013] + (https://ieeexplore.ieee.org/abstract/document/6738831) + ([pdf](https://arxiv.org/pdf/1302.1700.pdf)) + """ + return convolution( + input=value, + filter=filters, + padding=padding, + dilation_rate=np.broadcast_to(rate, (2,)), + name=name) + + +def convert_padding(padding, expected_length=4): + """Converts Python padding to C++ padding for ops which take EXPLICIT padding. + + Args: + padding: the `padding` argument for a Python op which supports EXPLICIT + padding. + expected_length: Expected number of entries in the padding list when + explicit padding is used. + + Returns: + (padding, explicit_paddings) pair, which should be passed as attributes to a + C++ op. + + Raises: + ValueError: If padding is invalid. + """ + explicit_paddings = [] + if padding == "EXPLICIT": + raise ValueError("'EXPLICIT' is not a valid value for `padding`. To use " + "explicit padding, `padding` must be a list.") + if isinstance(padding, (list, tuple)): + for i, dim_paddings in enumerate(padding): + if not isinstance(dim_paddings, (list, tuple)): + raise ValueError("When `padding` is a list, each element of `padding` " + "must be a list/tuple of size 2. Received: " + f"padding={padding} with element at index {i} of type " + f"{type(dim_paddings)}") + if len(dim_paddings) != 2: + raise ValueError("When `padding` is a list, each element of `padding` " + "must be a list/tuple of size 2. Received: " + f"padding={padding} with element at index {i} of size " + f"{len(dim_paddings)}") + explicit_paddings.extend(dim_paddings) + if len(padding) != expected_length: + raise ValueError( + f"When padding is a list, it must be of size {expected_length}. " + f"Received: padding={padding} of size {len(padding)}") + padding = "EXPLICIT" + return padding, explicit_paddings + + +@tf_export(v1=["nn.conv1d"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_arg_values( + None, + "`NCHW` for data_format is deprecated, use `NCW` instead", + warn_once=True, + data_format="NCHW") +@deprecation.deprecated_arg_values( + None, + "`NHWC` for data_format is deprecated, use `NWC` instead", + warn_once=True, + data_format="NHWC") +def conv1d( + value=None, + filters=None, + stride=None, + padding=None, + use_cudnn_on_gpu=None, + data_format=None, + name=None, + input=None, # pylint: disable=redefined-builtin + dilations=None): + r"""Computes a 1-D convolution of input with rank `>=3` and a `3-D` filter. + + Given an input tensor of shape + `batch_shape + [in_width, in_channels]` + if `data_format` is `"NWC"`, or + `batch_shape + [in_channels, in_width]` + if `data_format` is `"NCW"`, + and a filter / kernel tensor of shape + `[filter_width, in_channels, out_channels]`, this op reshapes + the arguments to pass them to `conv2d` to perform the equivalent + convolution operation. + + Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`. + For example, if `data_format` does not start with "NC", a tensor of shape + `batch_shape + [in_width, in_channels]` + is reshaped to + `batch_shape + [1, in_width, in_channels]`, + and the filter is reshaped to + `[1, filter_width, in_channels, out_channels]`. + The result is then reshaped back to + `batch_shape + [out_width, out_channels]` + \(where out_width is a function of the stride and padding as in conv2d\) and + returned to the caller. + + Args: + value: A Tensor of rank at least 3. Must be of type `float16`, `float32`, or + `float64`. + filters: A Tensor of rank at least 3. Must have the same type as `value`. + stride: An int or list of `ints` that has length `1` or `3`. The number of + entries by which the filter is moved right at each step. + padding: 'SAME' or 'VALID' + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + data_format: An optional `string` from `"NWC", "NCW"`. Defaults to `"NWC"`, + the data is stored in the order of `batch_shape + [in_width, + in_channels]`. The `"NCW"` format stores data as `batch_shape + + [in_channels, in_width]`. + name: A name for the operation (optional). + input: Alias for value. + dilations: An int or list of `ints` that has length `1` or `3` which + defaults to 1. The dilation factor for each dimension of input. If set to + k > 1, there will be k-1 skipped cells between each filter element on that + dimension. Dilations in the batch and depth dimensions must be 1. + + Returns: + A `Tensor`. Has the same type as input. + + Raises: + ValueError: if `data_format` is invalid. + """ + value = deprecation.deprecated_argument_lookup("input", input, "value", value) + with ops.name_scope(name, "conv1d", [value, filters]) as name: + # Reshape the input tensor to batch_shape + [1, in_width, in_channels] + if data_format is None or data_format == "NHWC" or data_format == "NWC": + data_format = "NHWC" + spatial_start_dim = -3 + channel_index = 2 + elif data_format == "NCHW" or data_format == "NCW": + data_format = "NCHW" + spatial_start_dim = -2 + channel_index = 1 + else: + raise ValueError("`data_format` must be 'NWC' or 'NCW'. " + f"Received: data_format={data_format}") + strides = [1] + _get_sequence(stride, 1, channel_index, "stride") + dilations = [1] + _get_sequence(dilations, 1, channel_index, "dilations") + + value = array_ops.expand_dims(value, spatial_start_dim) + filters = array_ops.expand_dims(filters, 0) + if value.shape.ndims in (4, 3, 2, 1, 0, None): + result = gen_nn_ops.conv2d( + value, + filters, + strides, + padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format, + dilations=dilations, + name=name) + else: + result = squeeze_batch_dims( + value, + functools.partial( + gen_nn_ops.conv2d, + filter=filters, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format, + dilations=dilations, + ), + inner_rank=3, + name=name) + return array_ops.squeeze(result, [spatial_start_dim]) + + +@tf_export("nn.conv1d", v1=[]) +@dispatch.add_dispatch_support +def conv1d_v2( + input, # pylint: disable=redefined-builtin + filters, + stride, + padding, + data_format="NWC", + dilations=None, + name=None): + r"""Computes a 1-D convolution given 3-D input and filter tensors. + + Given an input tensor of shape + `batch_shape + [in_width, in_channels]` + if `data_format` is `"NWC"`, or + `batch_shape + [in_channels, in_width]` + if `data_format` is `"NCW"`, + and a filter / kernel tensor of shape + `[filter_width, in_channels, out_channels]`, this op reshapes + the arguments to pass them to `conv2d` to perform the equivalent + convolution operation. + + Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`. + For example, if `data_format` does not start with `"NC"`, a tensor of shape + `batch_shape + [in_width, in_channels]` + is reshaped to + `batch_shape + [1, in_width, in_channels]`, + and the filter is reshaped to + `[1, filter_width, in_channels, out_channels]`. + The result is then reshaped back to + `batch_shape + [out_width, out_channels]` + \(where out_width is a function of the stride and padding as in conv2d\) and + returned to the caller. + + Args: + input: A Tensor of rank at least 3. Must be of type `float16`, `float32`, or + `float64`. + filters: A Tensor of rank at least 3. Must have the same type as `input`. + stride: An int or list of `ints` that has length `1` or `3`. The number of + entries by which the filter is moved right at each step. + padding: 'SAME' or 'VALID'. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: An optional `string` from `"NWC", "NCW"`. Defaults to `"NWC"`, + the data is stored in the order of + `batch_shape + [in_width, in_channels]`. The `"NCW"` format stores data + as `batch_shape + [in_channels, in_width]`. + dilations: An int or list of `ints` that has length `1` or `3` which + defaults to 1. The dilation factor for each dimension of input. If set to + k > 1, there will be k-1 skipped cells between each filter element on that + dimension. Dilations in the batch and depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as input. + + Raises: + ValueError: if `data_format` is invalid. + """ + return conv1d( + input, # pylint: disable=redefined-builtin + filters, + stride, + padding, + use_cudnn_on_gpu=True, + data_format=data_format, + name=name, + dilations=dilations) + + +@tf_export("nn.conv1d_transpose") +@dispatch.add_dispatch_support +def conv1d_transpose( + input, # pylint: disable=redefined-builtin + filters, + output_shape, + strides, + padding="SAME", + data_format="NWC", + dilations=None, + name=None): + """The transpose of `conv1d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is actually the transpose (gradient) of `conv1d` + rather than an actual deconvolution. + + Args: + input: A 3-D `Tensor` of type `float` and shape + `[batch, in_width, in_channels]` for `NWC` data format or + `[batch, in_channels, in_width]` for `NCW` data format. + filters: A 3-D `Tensor` with the same type as `input` and shape + `[filter_width, output_channels, in_channels]`. `filter`'s + `in_channels` dimension must match that of `input`. + output_shape: A 1-D `Tensor`, containing three elements, representing the + output shape of the deconvolution op. + strides: An int or list of `ints` that has length `1` or `3`. The number of + entries by which the filter is moved right at each step. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string. `'NWC'` and `'NCW'` are supported. + dilations: An int or list of `ints` that has length `1` or `3` which + defaults to 1. The dilation factor for each dimension of input. If set to + k > 1, there will be k-1 skipped cells between each filter element on that + dimension. Dilations in the batch and depth dimensions must be 1. + name: Optional name for the returned tensor. + + Returns: + A `Tensor` with the same type as `input`. + + Raises: + ValueError: If input/output depth does not match `filter`'s shape, if + `output_shape` is not at 3-element vector, if `padding` is other than + `'VALID'` or `'SAME'`, or if `data_format` is invalid. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "conv1d_transpose", + [input, filters, output_shape]) as name: + # The format could be either NWC or NCW, map to NHWC or NCHW + if data_format is None or data_format == "NWC": + data_format = "NHWC" + spatial_start_dim = 1 + channel_index = 2 + elif data_format == "NCW": + data_format = "NCHW" + spatial_start_dim = 2 + channel_index = 1 + else: + raise ValueError("`data_format` must be 'NWC' or 'NCW'. " + f"Received: data_format={data_format}") + + # Reshape the input tensor to [batch, 1, in_width, in_channels] + strides = [1] + _get_sequence(strides, 1, channel_index, "stride") + dilations = [1] + _get_sequence(dilations, 1, channel_index, "dilations") + + input = array_ops.expand_dims(input, spatial_start_dim) + filters = array_ops.expand_dims(filters, 0) + output_shape = list(output_shape) if not isinstance( + output_shape, tensor_lib.Tensor) else output_shape + output_shape = array_ops.concat([output_shape[: spatial_start_dim], [1], + output_shape[spatial_start_dim:]], 0) + + result = gen_nn_ops.conv2d_backprop_input( + input_sizes=output_shape, + filter=filters, + out_backprop=input, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + return array_ops.squeeze(result, spatial_start_dim) + + +@tf_export("nn.conv2d", v1=[]) +@dispatch.add_dispatch_support +def conv2d_v2(input, # pylint: disable=redefined-builtin + filters, + strides, + padding, + data_format="NHWC", + dilations=None, + name=None): + # pylint: disable=line-too-long + r"""Computes a 2-D convolution given `input` and 4-D `filters` tensors. + + The `input` tensor may have rank `4` or higher, where shape dimensions `[:-3]` + are considered batch dimensions (`batch_shape`). + + Given an input tensor of shape + `batch_shape + [in_height, in_width, in_channels]` and a filter / kernel + tensor of shape `[filter_height, filter_width, in_channels, out_channels]`, + this op performs the following: + + 1. Flattens the filter to a 2-D matrix with shape + `[filter_height * filter_width * in_channels, output_channels]`. + 2. Extracts image patches from the input tensor to form a *virtual* + tensor of shape `[batch, out_height, out_width, + filter_height * filter_width * in_channels]`. + 3. For each patch, right-multiplies the filter matrix and the image patch + vector. + + In detail, with the default NHWC format, + + output[b, i, j, k] = + sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] * + filter[di, dj, q, k] + + Must have `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + + Usage Example: + + >>> x_in = np.array([[ + ... [[2], [1], [2], [0], [1]], + ... [[1], [3], [2], [2], [3]], + ... [[1], [1], [3], [3], [0]], + ... [[2], [2], [0], [1], [1]], + ... [[0], [0], [3], [1], [2]], ]]) + >>> kernel_in = np.array([ + ... [ [[2, 0.1]], [[3, 0.2]] ], + ... [ [[0, 0.3]], [[1, 0.4]] ], ]) + >>> x = tf.constant(x_in, dtype=tf.float32) + >>> kernel = tf.constant(kernel_in, dtype=tf.float32) + >>> tf.nn.conv2d(x, kernel, strides=[1, 1, 1, 1], padding='VALID') + + + Args: + input: A `Tensor`. Must be one of the following types: + `half`, `bfloat16`, `float32`, `float64`. + A Tensor of rank at least 4. The dimension order is interpreted according + to the value of `data_format`; with the all-but-inner-3 dimensions acting + as batch dimensions. See below for details. + filters: A `Tensor`. Must have the same type as `input`. + A 4-D tensor of shape + `[filter_height, filter_width, in_channels, out_channels]` + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the `H` and `W` dimension. By default + the `N` and `C` dimensions are set to 1. The dimension order is determined + by the value of `data_format`, see below for details. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. + Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + `batch_shape + [height, width, channels]`. + Alternatively, the format could be "NCHW", the data storage order of: + `batch_shape + [channels, height, width]`. + dilations: An int or list of `ints` that has length `1`, `2` or `4`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `H` and `W` dimension. By + default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 4-d tensor + must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input` and the same outer batch shape. + """ + # pylint: enable=line-too-long + return conv2d(input, # pylint: disable=redefined-builtin + filters, + strides, + padding, + use_cudnn_on_gpu=True, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export(v1=["nn.conv2d"]) +@dispatch.add_dispatch_support +def conv2d( # pylint: disable=redefined-builtin,dangerous-default-value + input, + filter=None, + strides=None, + padding=None, + use_cudnn_on_gpu=True, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None, + filters=None): + r"""Computes a 2-D convolution given 4-D `input` and `filter` tensors. + + Given an input tensor of shape `[batch, in_height, in_width, in_channels]` + and a filter / kernel tensor of shape + `[filter_height, filter_width, in_channels, out_channels]`, this op + performs the following: + + 1. Flattens the filter to a 2-D matrix with shape + `[filter_height * filter_width * in_channels, output_channels]`. + 2. Extracts image patches from the input tensor to form a *virtual* + tensor of shape `[batch, out_height, out_width, + filter_height * filter_width * in_channels]`. + 3. For each patch, right-multiplies the filter matrix and the image patch + vector. + + In detail, with the default NHWC format, + + output[b, i, j, k] = + sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] + * filter[di, dj, q, k] + + Must have `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertical strides, `strides = [1, stride, stride, 1]`. + + Args: + input: A `Tensor`. Must be one of the following types: + `half`, `bfloat16`, `float32`, `float64`. + A 4-D tensor. The dimension order is interpreted according to the value + of `data_format`, see below for details. + filter: A `Tensor`. Must have the same type as `input`. + A 4-D tensor of shape + `[filter_height, filter_width, in_channels, out_channels]` + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the `H` and `W` dimension. By default + the `N` and `C` dimensions are set to 1. The dimension order is determined + by the value of `data_format`, see below for details. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. When explicit padding is used and + data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, + pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used + and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. + Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, height, width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An int or list of `ints` that has length `1`, `2` or `4`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `H` and `W` dimension. By + default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 4-d tensor + must be 1. + name: A name for the operation (optional). + filters: Alias for filter. + + Returns: + A `Tensor`. Has the same type as `input`. + """ + filter = deprecation.deprecated_argument_lookup( + "filters", filters, "filter", filter) + padding, explicit_paddings = convert_padding(padding) + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + strides = _get_sequence(strides, 2, channel_index, "strides") + dilations = _get_sequence(dilations, 2, channel_index, "dilations") + + shape = input.shape + # shape object may lack ndims, e.g., if input is an np.ndarray. In that case, + # we fall back to len(shape). + ndims = getattr(shape, "ndims", -1) + if ndims == -1: + ndims = len(shape) + if ndims in (4, 3, 2, 1, 0, None): + # We avoid calling squeeze_batch_dims to reduce extra python function + # call slowdown in eager mode. This branch doesn't require reshapes. + return gen_nn_ops.conv2d( + input, + filter=filter, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + return squeeze_batch_dims( + input, + functools.partial( + gen_nn_ops.conv2d, + filter=filter, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations), + inner_rank=3, + name=name) + + +@tf_export(v1=["nn.conv2d_backprop_filter"]) +@dispatch.add_dispatch_support +def conv2d_backprop_filter( # pylint: disable=redefined-builtin,dangerous-default-value + input, + filter_sizes, + out_backprop, + strides, + padding, + use_cudnn_on_gpu=True, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None): + r"""Computes the gradients of convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: + `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape `[batch, in_height, in_width, in_channels]`. + filter_sizes: A `Tensor` of type `int32`. + An integer vector representing the tensor shape of `filter`, + where `filter` is a 4-D + `[filter_height, filter_width, in_channels, out_channels]` tensor. + out_backprop: A `Tensor`. Must have the same type as `input`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified + with format. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. When explicit padding is used and + data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, + pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used + and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. + Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by + the value of `data_format`, see above for details. Dilations in the batch + and depth dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + padding, explicit_paddings = convert_padding(padding) + return gen_nn_ops.conv2d_backprop_filter( + input, filter_sizes, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name) + + +@tf_export(v1=["nn.conv2d_backprop_input"]) +@dispatch.add_dispatch_support +def conv2d_backprop_input( # pylint: disable=redefined-builtin,dangerous-default-value + input_sizes, + filter=None, + out_backprop=None, + strides=None, + padding=None, + use_cudnn_on_gpu=True, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None, + filters=None): + r"""Computes the gradients of convolution with respect to the input. + + Args: + input_sizes: A `Tensor` of type `int32`. + An integer vector representing the shape of `input`, + where `input` is a 4-D `[batch, height, width, channels]` tensor. + filter: A `Tensor`. Must be one of the following types: + `half`, `bfloat16`, `float32`, `float64`. + 4-D with shape + `[filter_height, filter_width, in_channels, out_channels]`. + out_backprop: A `Tensor`. Must have the same type as `filter`. + 4-D with shape `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. + The stride of the sliding window for each dimension of the input + of the convolution. Must be in the same order as the dimension specified + with format. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. When explicit padding is used and + data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, + pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used + and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + use_cudnn_on_gpu: An optional `bool`. Defaults to `True`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. + Defaults to `"NHWC"`. + Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: + [batch, in_height, in_width, in_channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, in_channels, in_height, in_width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. + 1-D tensor of length 4. The dilation factor for each dimension of + `input`. If set to k > 1, there will be k-1 skipped cells between each + filter element on that dimension. The dimension order is determined by + the value of `data_format`, see above for details. Dilations in the batch + and depth dimensions must be 1. + name: A name for the operation (optional). + filters: Alias for filter. + + Returns: + A `Tensor`. Has the same type as `filter`. + """ + filter = deprecation.deprecated_argument_lookup( + "filters", filters, "filter", filter) + padding, explicit_paddings = convert_padding(padding) + return gen_nn_ops.conv2d_backprop_input( + input_sizes, filter, out_backprop, strides, padding, use_cudnn_on_gpu, + explicit_paddings, data_format, dilations, name) + + +@tf_export(v1=["nn.conv2d_transpose"]) +@dispatch.add_dispatch_support +def conv2d_transpose( + value=None, + filter=None, # pylint: disable=redefined-builtin + output_shape=None, + strides=None, + padding="SAME", + data_format="NHWC", + name=None, + input=None, # pylint: disable=redefined-builtin + filters=None, + dilations=None): + """The transpose of `conv2d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of `conv2d` + rather than an actual deconvolution. + + Args: + value: A 4-D `Tensor` of type `float` and shape + `[batch, height, width, in_channels]` for `NHWC` data format or + `[batch, in_channels, height, width]` for `NCHW` data format. + filter: A 4-D `Tensor` with the same type as `value` and shape + `[height, width, output_channels, in_channels]`. `filter`'s + `in_channels` dimension must match that of `value`. + output_shape: A 1-D `Tensor` representing the output shape of the + deconvolution op. + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the `H` and `W` dimension. By default + the `N` and `C` dimensions are set to 0. The dimension order is determined + by the value of `data_format`, see below for details. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. + See the "returns" section of `tf.nn.convolution` for details. + data_format: A string. 'NHWC' and 'NCHW' are supported. + name: Optional name for the returned tensor. + input: Alias for value. + filters: Alias for filter. + dilations: An int or list of `ints` that has length `1`, `2` or `4`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `H` and `W` dimension. By + default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 4-d tensor + must be 1. + + Returns: + A `Tensor` with the same type as `value`. + + Raises: + ValueError: If input/output depth does not match `filter`'s shape, or if + padding is other than `'VALID'` or `'SAME'`. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + value = deprecated_argument_lookup("input", input, "value", value) + filter = deprecated_argument_lookup("filters", filters, "filter", filter) + with ops.name_scope(name, "conv2d_transpose", + [value, filter, output_shape]) as name: + return conv2d_transpose_v2( + value, + filter, + output_shape, + strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export("nn.conv2d_transpose", v1=[]) +@dispatch.add_dispatch_support +def conv2d_transpose_v2( + input, # pylint: disable=redefined-builtin + filters, # pylint: disable=redefined-builtin + output_shape, + strides, + padding="SAME", + data_format="NHWC", + dilations=None, + name=None): + """The transpose of `conv2d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of + `atrous_conv2d` rather than an actual deconvolution. + + Args: + input: A 4-D `Tensor` of type `float` and shape `[batch, height, width, + in_channels]` for `NHWC` data format or `[batch, in_channels, height, + width]` for `NCHW` data format. + filters: A 4-D `Tensor` with the same type as `input` and shape `[height, + width, output_channels, in_channels]`. `filter`'s `in_channels` dimension + must match that of `input`. + output_shape: A 1-D `Tensor` representing the output shape of the + deconvolution op. + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the `H` and `W` dimension. By default + the `N` and `C` dimensions are set to 0. The dimension order is determined + by the value of `data_format`, see below for details. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: A string. 'NHWC' and 'NCHW' are supported. + dilations: An int or list of `ints` that has length `1`, `2` or `4`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `H` and `W` dimension. By + default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 4-d tensor + must be 1. + name: Optional name for the returned tensor. + + Returns: + A `Tensor` with the same type as `input`. + + Raises: + ValueError: If input/output depth does not match `filter`'s shape, or if + padding is other than `'VALID'` or `'SAME'`. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "conv2d_transpose", + [input, filter, output_shape]) as name: + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + strides = _get_sequence(strides, 2, channel_index, "strides") + dilations = _get_sequence(dilations, 2, channel_index, "dilations") + padding, explicit_paddings = convert_padding(padding) + + return gen_nn_ops.conv2d_backprop_input( + input_sizes=output_shape, + filter=filters, + out_backprop=input, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + + +def _conv2d_expanded_batch( + input, # pylint: disable=redefined-builtin + filters, + strides, + padding, + data_format, + dilations, + name): + """Helper function for `convolution_internal`; handles expanded batches.""" + # Try really hard to avoid modifying the legacy name scopes - return early. + input_rank = input.shape.rank + if input_rank is None or input_rank < 5: + # We avoid calling squeeze_batch_dims to reduce extra python function + # call slowdown in eager mode. This branch doesn't require reshapes. + return gen_nn_ops.conv2d( + input, + filter=filters, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + return squeeze_batch_dims( + input, + functools.partial( + gen_nn_ops.conv2d, + filter=filters, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations), + inner_rank=3, + name=name) + + +@tf_export("nn.atrous_conv2d_transpose") +@dispatch.add_dispatch_support +def atrous_conv2d_transpose(value, + filters, + output_shape, + rate, + padding, + name=None): + """The transpose of `atrous_conv2d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of + `atrous_conv2d` rather than an actual deconvolution. + + Args: + value: A 4-D `Tensor` of type `float`. It needs to be in the default `NHWC` + format. Its shape is `[batch, in_height, in_width, in_channels]`. + filters: A 4-D `Tensor` with the same type as `value` and shape + `[filter_height, filter_width, out_channels, in_channels]`. `filters`' + `in_channels` dimension must match that of `value`. Atrous convolution is + equivalent to standard convolution with upsampled filters with effective + height `filter_height + (filter_height - 1) * (rate - 1)` and effective + width `filter_width + (filter_width - 1) * (rate - 1)`, produced by + inserting `rate - 1` zeros along consecutive elements across the + `filters`' spatial dimensions. + output_shape: A 1-D `Tensor` of shape representing the output shape of the + deconvolution op, of form `[batch, out_height, out_width, out_channels]`. + rate: A positive int32. The stride with which we sample input values across + the `height` and `width` dimensions. Equivalently, the rate by which we + upsample the filter values by inserting zeros across the `height` and + `width` dimensions. In the literature, the same parameter is sometimes + called `input stride` or `dilation`. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + name: Optional name for the returned tensor. + + Returns: + A `Tensor` with the same type as `value`. + + Raises: + ValueError: If input/output depth does not match `filters`' shape, or if + padding is other than `'VALID'` or `'SAME'`, or if the `rate` is less + than one, or if the output_shape is not a tensor with 4 elements. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "atrous_conv2d_transpose", + [value, filters, output_shape]) as name: + value = ops.convert_to_tensor(value, name="value") + filters = ops.convert_to_tensor(filters, name="filters") + if not value.get_shape().dims[3].is_compatible_with(filters.get_shape()[3]): + raise ValueError( + "`value` channel count must be compatible with `filters` input " + f"channel count. Received: value.shape={value.get_shape()} with " + f"channel count {value.get_shape()[3]} and " + f"filters.shape={filters.get_shape()} with input channel count " + f"{filters.get_shape()[3]}.") + if rate < 1: + raise ValueError(f"`rate` cannot be less than one. Received: rate={rate}") + + if rate == 1: + return conv2d_transpose( + value, + filters, + output_shape, + strides=[1, 1, 1, 1], + padding=padding, + data_format="NHWC") + + output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape") + if not output_shape_.get_shape().is_compatible_with( + tensor_shape.TensorShape([4])): + raise ValueError("`output_shape` must have shape (4,). " + f"Received: output_shape={output_shape_.get_shape()}") + + if isinstance(output_shape, tuple): + output_shape = list(output_shape) + + if isinstance(output_shape, (list, np.ndarray)): + # output_shape's shape should be == [4] if reached this point. + if not filters.get_shape().dims[2].is_compatible_with(output_shape[3]): + raise ValueError( + "`output_shape` channel count must be compatible with `filters` " + f"output channel count. Received: output_shape={output_shape} with " + f"channel count {output_shape[3]} and " + f"filters.shape={filters.get_shape()} with output channel count " + f"{filters.get_shape()[3]}.") + + # We have two padding contributions. The first is used for converting "SAME" + # to "VALID". The second is required so that the height and width of the + # zero-padded value tensor are multiples of rate. + + # Padding required to reduce to "VALID" convolution + if padding == "SAME": + # Handle filters whose shape is unknown during graph creation. + if filters.get_shape().is_fully_defined(): + filter_shape = filters.get_shape().as_list() + else: + filter_shape = array_ops.shape(filters) + filter_height, filter_width = filter_shape[0], filter_shape[1] + + # Spatial dimensions of the filters and the upsampled filters in which we + # introduce (rate - 1) zeros between consecutive filter values. + filter_height_up = filter_height + (filter_height - 1) * (rate - 1) + filter_width_up = filter_width + (filter_width - 1) * (rate - 1) + + pad_height = filter_height_up - 1 + pad_width = filter_width_up - 1 + + # When pad_height (pad_width) is odd, we pad more to bottom (right), + # following the same convention as conv2d(). + pad_top = pad_height // 2 + pad_bottom = pad_height - pad_top + pad_left = pad_width // 2 + pad_right = pad_width - pad_left + elif padding == "VALID": + pad_top = 0 + pad_bottom = 0 + pad_left = 0 + pad_right = 0 + else: + raise ValueError("`padding` must be either 'VALID' or 'SAME'. " + f"Received: padding={padding}") + + in_height = output_shape[1] + pad_top + pad_bottom + in_width = output_shape[2] + pad_left + pad_right + + # More padding so that rate divides the height and width of the input. + pad_bottom_extra = (rate - in_height % rate) % rate + pad_right_extra = (rate - in_width % rate) % rate + + # The paddings argument to space_to_batch is just the extra padding + # component. + space_to_batch_pad = [[0, pad_bottom_extra], [0, pad_right_extra]] + + value = array_ops.space_to_batch( + input=value, paddings=space_to_batch_pad, block_size=rate) + + input_sizes = [ + rate * rate * output_shape[0], (in_height + pad_bottom_extra) // rate, + (in_width + pad_right_extra) // rate, output_shape[3] + ] + + value = gen_nn_ops.conv2d_backprop_input( + input_sizes=input_sizes, + filter=filters, + out_backprop=value, + strides=[1, 1, 1, 1], + padding="VALID", + data_format="NHWC") + + # The crops argument to batch_to_space includes both padding components. + batch_to_space_crop = [[pad_top, pad_bottom + pad_bottom_extra], + [pad_left, pad_right + pad_right_extra]] + + return array_ops.batch_to_space( + input=value, crops=batch_to_space_crop, block_size=rate) + + +@tf_export(v1=["nn.depthwise_conv2d_native"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("nn.depthwise_conv2d_native") +def depthwise_conv2d_native( # pylint: disable=redefined-builtin,dangerous-default-value + input, + filter, + strides, + padding, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None): + r"""Computes a 2-D depthwise convolution. + + Given an input tensor of shape `[batch, in_height, in_width, in_channels]` + and a filter / kernel tensor of shape + `[filter_height, filter_width, in_channels, channel_multiplier]`, containing + `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies + a different filter to each input channel (expanding from 1 channel to + `channel_multiplier` channels for each), then concatenates the results + together. Thus, the output has `in_channels * channel_multiplier` channels. + + ``` + for k in 0..in_channels-1 + for q in 0..channel_multiplier-1 + output[b, i, j, k * channel_multiplier + q] = + sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] * + filter[di, dj, k, q] + ``` + + Must have `strides[0] = strides[3] = 1`. For the most common case of the same + horizontal and vertices strides, `strides = [1, stride, stride, 1]`. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, + `float32`, `float64`. + filter: A `Tensor`. Must have the same type as `input`. + strides: A list of `ints`. 1-D of length 4. The stride of the sliding + window for each dimension of `input`. + padding: Controls how to pad the image before applying the convolution. Can + be the string `"SAME"` or `"VALID"` indicating the type of padding + algorithm to use, or a list indicating the explicit paddings at the start + and end of each dimension. When explicit padding is used and data_format + is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to + `"NHWC"`. Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: [batch, height, + width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D + tensor of length 4. The dilation factor for each dimension of `input`. If + set to k > 1, there will be k-1 skipped cells between each filter element + on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + padding, explicit_paddings = convert_padding(padding) + return gen_nn_ops.depthwise_conv2d_native( + input, + filter, + strides, + padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export( + "nn.depthwise_conv2d_backprop_input", + v1=[ + "nn.depthwise_conv2d_native_backprop_input", + "nn.depthwise_conv2d_backprop_input" + ]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("nn.depthwise_conv2d_native_backprop_input") +def depthwise_conv2d_native_backprop_input( # pylint: disable=redefined-builtin,dangerous-default-value + input_sizes, + filter, + out_backprop, + strides, + padding, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None): + r"""Computes the gradients of depthwise convolution with respect to the input. + + Args: + input_sizes: A `Tensor` of type `int32`. An integer vector representing the + shape of `input`, based on `data_format`. For example, if `data_format` + is 'NHWC' then `input` is a 4-D `[batch, height, width, channels]` tensor. + filter: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, + `float32`, `float64`. 4-D with shape `[filter_height, filter_width, + in_channels, depthwise_multiplier]`. + out_backprop: A `Tensor`. Must have the same type as `filter`. 4-D with + shape based on `data_format`. For example, if `data_format` is 'NHWC' + then out_backprop shape is `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. The stride of the sliding window for each + dimension of the input of the convolution. + padding: Controls how to pad the image before applying the convolution. Can + be the string `"SAME"` or `"VALID"` indicating the type of padding + algorithm to use, or a list indicating the explicit paddings at the start + and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to + `"NHWC"`. Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: [batch, height, + width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D + tensor of length 4. The dilation factor for each dimension of `input`. If + set to k > 1, there will be k-1 skipped cells between each filter element + on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `filter`. + """ + padding, explicit_paddings = convert_padding(padding) + return gen_nn_ops.depthwise_conv2d_native_backprop_input( + input_sizes, + filter, + out_backprop, + strides, + padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export( + "nn.depthwise_conv2d_backprop_filter", + v1=[ + "nn.depthwise_conv2d_native_backprop_filter", + "nn.depthwise_conv2d_backprop_filter" + ]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("nn.depthwise_conv2d_native_backprop_filter") +def depthwise_conv2d_native_backprop_filter( # pylint: disable=redefined-builtin,dangerous-default-value + input, + filter_sizes, + out_backprop, + strides, + padding, + data_format="NHWC", + dilations=[1, 1, 1, 1], + name=None): + r"""Computes the gradients of depthwise convolution with respect to the filter. + + Args: + input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, + `float32`, `float64`. 4-D with shape based on `data_format`. For example, + if `data_format` is 'NHWC' then `input` is a 4-D `[batch, in_height, + in_width, in_channels]` tensor. + filter_sizes: A `Tensor` of type `int32`. An integer vector representing the + tensor shape of `filter`, where `filter` is a 4-D `[filter_height, + filter_width, in_channels, depthwise_multiplier]` tensor. + out_backprop: A `Tensor`. Must have the same type as `input`. 4-D with shape + based on `data_format`. For example, if `data_format` is 'NHWC' then + out_backprop shape is `[batch, out_height, out_width, out_channels]`. + Gradients w.r.t. the output of the convolution. + strides: A list of `ints`. The stride of the sliding window for each + dimension of the input of the convolution. + padding: Controls how to pad the image before applying the convolution. Can + be the string `"SAME"` or `"VALID"` indicating the type of padding + algorithm to use, or a list indicating the explicit paddings at the start + and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. + data_format: An optional `string` from: `"NHWC", "NCHW"`. Defaults to + `"NHWC"`. Specify the data format of the input and output data. With the + default format "NHWC", the data is stored in the order of: [batch, height, + width, channels]. + Alternatively, the format could be "NCHW", the data storage order of: + [batch, channels, height, width]. + dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D + tensor of length 4. The dilation factor for each dimension of `input`. If + set to k > 1, there will be k-1 skipped cells between each filter element + on that dimension. The dimension order is determined by the value of + `data_format`, see above for details. Dilations in the batch and depth + dimensions must be 1. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + padding, explicit_paddings = convert_padding(padding) + return gen_nn_ops.depthwise_conv2d_native_backprop_filter( + input, + filter_sizes, + out_backprop, + strides, + padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + dilations=dilations, + name=name) + + +def _conv3d_expanded_batch( + input, # pylint: disable=redefined-builtin + filter, # pylint: disable=redefined-builtin + strides, + padding, + data_format, + dilations=None, + name=None): + """Helper function for `conv3d`; handles expanded batches.""" + shape = input.shape + # shape object may lack ndims, e.g., if input is an np.ndarray. In that case, + # we fall back to len(shape). + ndims = getattr(shape, "ndims", -1) + if ndims == -1: + ndims = len(shape) + if ndims in (5, 4, 3, 2, 1, 0, None): + # We avoid calling squeeze_batch_dims to reduce extra python function + # call slowdown in eager mode. This branch doesn't require reshapes. + return gen_nn_ops.conv3d( + input, + filter, + strides, + padding, + data_format=data_format, + dilations=dilations, + name=name) + else: + return squeeze_batch_dims( + input, + functools.partial( + gen_nn_ops.conv3d, + filter=filter, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations), + inner_rank=4, + name=name) + + +@tf_export("nn.conv3d", v1=[]) +@dispatch.add_dispatch_support +def conv3d_v2(input, # pylint: disable=redefined-builtin,missing-docstring + filters, + strides, + padding, + data_format="NDHWC", + dilations=None, + name=None): + if dilations is None: + dilations = [1, 1, 1, 1, 1] + return _conv3d_expanded_batch(input, filters, strides, padding, data_format, + dilations, name) + + +@tf_export(v1=["nn.conv3d"]) +@dispatch.add_dispatch_support +def conv3d_v1( # pylint: disable=missing-docstring,dangerous-default-value + input, # pylint: disable=redefined-builtin + filter=None, # pylint: disable=redefined-builtin + strides=None, + padding=None, + data_format="NDHWC", + dilations=[1, 1, 1, 1, 1], + name=None, + filters=None): + filter = deprecated_argument_lookup("filters", filters, "filter", filter) + return gen_nn_ops.conv3d( + input, filter, strides, padding, data_format, dilations, name) + + +conv3d_v2.__doc__ = deprecation.rewrite_argument_docstring( + gen_nn_ops.conv3d.__doc__, "filter", "filters") +conv3d_v1.__doc__ = gen_nn_ops.conv3d.__doc__ + + +@tf_export(v1=["nn.conv3d_transpose"]) +@dispatch.add_dispatch_support +def conv3d_transpose( + value, + filter=None, # pylint: disable=redefined-builtin + output_shape=None, + strides=None, + padding="SAME", + data_format="NDHWC", + name=None, + input=None, # pylint: disable=redefined-builtin + filters=None, + dilations=None): + """The transpose of `conv3d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d` + rather than an actual deconvolution. + + Args: + value: A 5-D `Tensor` of type `float` and shape + `[batch, depth, height, width, in_channels]`. + filter: A 5-D `Tensor` with the same type as `value` and shape + `[depth, height, width, output_channels, in_channels]`. `filter`'s + `in_channels` dimension must match that of `value`. + output_shape: A 1-D `Tensor` representing the output shape of the + deconvolution op. + strides: A list of ints. The stride of the sliding window for each + dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. + See the "returns" section of `tf.nn.convolution` for details. + data_format: A string, either `'NDHWC'` or `'NCDHW`' specifying the layout + of the input and output tensors. Defaults to `'NDHWC'`. + name: Optional name for the returned tensor. + input: Alias of value. + filters: Alias of filter. + dilations: An int or list of `ints` that has length `1`, `3` or `5`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `D`, `H` and `W` dimension. + By default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 5-d tensor + must be 1. + + Returns: + A `Tensor` with the same type as `value`. + + Raises: + ValueError: If input/output depth does not match `filter`'s shape, or if + padding is other than `'VALID'` or `'SAME'`. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + filter = deprecated_argument_lookup("filters", filters, "filter", filter) + value = deprecated_argument_lookup("input", input, "value", value) + return conv3d_transpose_v2( + value, + filter, + output_shape, + strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export("nn.conv3d_transpose", v1=[]) +@dispatch.add_dispatch_support +def conv3d_transpose_v2(input, # pylint: disable=redefined-builtin + filters, + output_shape, + strides, + padding="SAME", + data_format="NDHWC", + dilations=None, + name=None): + """The transpose of `conv3d`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d` + rather than an actual deconvolution. + + Args: + input: A 5-D `Tensor` of type `float` and shape `[batch, depth, height, + width, in_channels]` for `NDHWC` data format or `[batch, in_channels, + depth, height, width]` for `NCDHW` data format. + filters: A 5-D `Tensor` with the same type as `input` and shape `[depth, + height, width, output_channels, in_channels]`. `filter`'s `in_channels` + dimension must match that of `input`. + output_shape: A 1-D `Tensor` representing the output shape of the + deconvolution op. + strides: An int or list of `ints` that has length `1`, `3` or `5`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the `D`, `H` and `W` dimension. By + default the `N` and `C` dimensions are set to 0. The dimension order is + determined by the value of `data_format`, see below for details. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string. 'NDHWC' and 'NCDHW' are supported. + dilations: An int or list of `ints` that has length `1`, `3` or `5`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the `D`, `H` and `W` dimension. + By default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. Dilations in the batch and depth dimensions if a 5-d tensor + must be 1. + name: Optional name for the returned tensor. + + Returns: + A `Tensor` with the same type as `input`. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "conv3d_transpose", + [input, filter, output_shape]) as name: + if data_format is None: + data_format = "NDHWC" + channel_index = 1 if data_format.startswith("NC") else 4 + + strides = _get_sequence(strides, 3, channel_index, "strides") + dilations = _get_sequence(dilations, 3, channel_index, "dilations") + + return gen_nn_ops.conv3d_backprop_input_v2( + input_sizes=output_shape, + filter=filters, + out_backprop=input, + strides=strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + +CONV_TRANSPOSE_OPS = ( + conv1d_transpose, + conv2d_transpose_v2, + conv3d_transpose_v2, +) + + +@tf_export("nn.conv_transpose") +@dispatch.add_dispatch_support +def conv_transpose(input, # pylint: disable=redefined-builtin + filters, + output_shape, + strides, + padding="SAME", + data_format=None, + dilations=None, + name=None): + """The transpose of `convolution`. + + This operation is sometimes called "deconvolution" after + (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d` + rather than an actual deconvolution. + + Args: + input: An N+2 dimensional `Tensor` of shape + `[batch_size] + input_spatial_shape + [in_channels]` if data_format does + not start with "NC" (default), or + `[batch_size, in_channels] + input_spatial_shape` if data_format starts + with "NC". It must be one of the following types: + `half`, `bfloat16`, `float32`, `float64`. + filters: An N+2 dimensional `Tensor` with the same type as `input` and + shape `spatial_filter_shape + [in_channels, out_channels]`. + output_shape: A 1-D `Tensor` representing the output shape of the + deconvolution op. + strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The + stride of the sliding window for each dimension of `input`. If a single + value is given it is replicated in the spatial dimensions. By default + the `N` and `C` dimensions are set to 0. The dimension order is determined + by the value of `data_format`, see below for details. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string or None. Specifies whether the channel dimension of + the `input` and output is the last dimension (default, or if `data_format` + does not start with "NC"), or the second dimension (if `data_format` + starts with "NC"). For N=1, the valid values are "NWC" (default) and + "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". + For N=3, the valid values are "NDHWC" (default) and "NCDHW". + dilations: An int or list of `ints` that has length `1`, `N` or `N+2`, + defaults to 1. The dilation factor for each dimension of`input`. If a + single value is given it is replicated in the spatial dimensions. By + default the `N` and `C` dimensions are set to 1. If set to k > 1, there + will be k-1 skipped cells between each filter element on that dimension. + The dimension order is determined by the value of `data_format`, see above + for details. + name: A name for the operation (optional). If not specified "conv_transpose" + is used. + + Returns: + A `Tensor` with the same type as `value`. + + References: + Deconvolutional Networks: + [Zeiler et al., 2010] + (https://ieeexplore.ieee.org/abstract/document/5539957) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "conv_transpose", + [input, filter, output_shape]) as name: + if tensor_util.is_tf_type(output_shape): + n = output_shape.shape[0] - 2 + elif isinstance(output_shape, collections_abc.Sized): + n = len(output_shape) - 2 + else: + raise ValueError("`output_shape` must be a tensor or sized collection. " + f"Received: output_shape={output_shape}") + + if not 1 <= n <= 3: + raise ValueError( + f"`output_shape` must be of length 3, 4 or 5. " + f"Received: output_shape={output_shape} of length {n + 2}.") + + op = CONV_TRANSPOSE_OPS[n-1] + return op( + input, + filters, + output_shape, + strides, + padding=padding, + data_format=data_format, + dilations=dilations, + name=name) + + +@tf_export("nn.bias_add") +@dispatch.add_dispatch_support +def bias_add(value, bias, data_format=None, name=None): + """Adds `bias` to `value`. + + This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D. + Broadcasting is supported, so `value` may have any number of dimensions. + Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the + case where both types are quantized. + + Args: + value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, + `int16`, `int8`, `complex64`, or `complex128`. + bias: A 1-D `Tensor` with size matching the channel dimension of `value`. + Must be the same type as `value` unless `value` is a quantized type, + in which case a different quantized type may be used. + data_format: A string. 'N...C' and 'NC...' are supported. If `None` (the + default) is specified then 'N..C' is assumed. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as `value`. + + Raises: + ValueError if data format is unrecognized, if `value` has less than two + dimensions when `data_format` is 'N..C'/`None` or `value` has less + then three dimensions when `data_format` is `NC..`, if `bias` does not + have exactly one dimension (is a vector), or if the size of `bias` + does not match the size of the channel dimension of `value`. + """ + with ops.name_scope(name, "BiasAdd", [value, bias]) as name: + if data_format is not None: + if data_format.startswith("NC"): + data_format = "NCHW" + elif data_format.startswith("N") and data_format.endswith("C"): + data_format = "NHWC" + else: + raise ValueError("`data_format` must be of the form `N...C` or " + f"`NC...`. Received: data_format={data_format}") + + if not context.executing_eagerly(): + value = ops.convert_to_tensor(value, name="input") + bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") + + return gen_nn_ops.bias_add(value, bias, data_format=data_format, name=name) + + +def bias_add_v1(value, bias, name=None): + """Adds `bias` to `value`. + + This is a deprecated version of bias_add and will soon to be removed. + + This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D. + Broadcasting is supported, so `value` may have any number of dimensions. + Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the + case where both types are quantized. + + Args: + value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, + `int16`, `int8`, `complex64`, or `complex128`. + bias: A 1-D `Tensor` with size matching the last dimension of `value`. + Must be the same type as `value` unless `value` is a quantized type, + in which case a different quantized type may be used. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as `value`. + """ + with ops.name_scope(name, "BiasAddV1", [value, bias]) as name: + value = ops.convert_to_tensor(value, name="input") + bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") + return gen_nn_ops.bias_add_v1(value, bias, name=name) + + +@tf_export(v1=["nn.crelu"]) +@dispatch.add_dispatch_support +def crelu(features, name=None, axis=-1): + """Computes Concatenated ReLU. + + Concatenates a ReLU which selects only the positive part of the activation + with a ReLU which selects only the *negative* part of the activation. + Note that as a result this non-linearity doubles the depth of the activations. + Source: [Understanding and Improving Convolutional Neural Networks via + Concatenated Rectified Linear Units. W. Shang, et + al.](https://arxiv.org/abs/1603.05201) + + Args: + features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`, + `int16`, or `int8`. + name: A name for the operation (optional). + axis: The axis that the output values are concatenated along. Default is -1. + + Returns: + A `Tensor` with the same type as `features`. + + References: + Understanding and Improving Convolutional Neural Networks via Concatenated + Rectified Linear Units: + [Shang et al., 2016](http://proceedings.mlr.press/v48/shang16) + ([pdf](http://proceedings.mlr.press/v48/shang16.pdf)) + """ + with ops.name_scope(name, "CRelu", [features]) as name: + features = ops.convert_to_tensor(features, name="features") + c = array_ops.concat([features, -features], axis, name=name) # pylint: disable=invalid-unary-operand-type + return gen_nn_ops.relu(c) + + +@tf_export("nn.crelu", v1=[]) +@dispatch.add_dispatch_support +def crelu_v2(features, axis=-1, name=None): + return crelu(features, name=name, axis=axis) +crelu_v2.__doc__ = crelu.__doc__ + + +@tf_export("nn.relu6") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def relu6(features, name=None): + """Computes Rectified Linear 6: `min(max(features, 0), 6)`. + + In comparison with `tf.nn.relu`, relu6 activation functions have shown to + empirically perform better under low-precision conditions (e.g. fixed point + inference) by encouraging the model to learn sparse features earlier. + Source: [Convolutional Deep Belief Networks on CIFAR-10: Krizhevsky et al., + 2010](http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf). + + For example: + + >>> x = tf.constant([-3.0, -1.0, 0.0, 6.0, 10.0], dtype=tf.float32) + >>> y = tf.nn.relu6(x) + >>> y.numpy() + array([0., 0., 0., 6., 6.], dtype=float32) + + Args: + features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`, + `int16`, or `int8`. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as `features`. + + References: + Convolutional Deep Belief Networks on CIFAR-10: + Krizhevsky et al., 2010 + ([pdf](http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf)) + """ + with ops.name_scope(name, "Relu6", [features]) as name: + features = ops.convert_to_tensor(features, name="features") + return gen_nn_ops.relu6(features, name=name) + + +@tf_export("nn.leaky_relu") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def leaky_relu(features, alpha=0.2, name=None): + """Compute the Leaky ReLU activation function. + + Source: [Rectifier Nonlinearities Improve Neural Network Acoustic Models. + AL Maas, AY Hannun, AY Ng - Proc. ICML, 2013] + (https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf). + + Args: + features: A `Tensor` representing preactivation values. Must be one of + the following types: `float16`, `float32`, `float64`, `int32`, `int64`. + alpha: Slope of the activation function at x < 0. + name: A name for the operation (optional). + + Returns: + The activation value. + + References: + Rectifier Nonlinearities Improve Neural Network Acoustic Models: + [Maas et al., 2013] + (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.693.1422) + ([pdf] + (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.693.1422&rep=rep1&type=pdf)) + """ + with ops.name_scope(name, "LeakyRelu", [features, alpha]) as name: + features = ops.convert_to_tensor(features, name="features") + if features.dtype.is_integer: + features = math_ops.cast(features, dtypes.float32) + if isinstance(alpha, np.ndarray): + alpha = alpha.item() + return gen_nn_ops.leaky_relu(features, alpha=alpha, name=name) + + +@tf_export("nn.gelu", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def gelu(features, approximate=False, name=None): + """Compute the Gaussian Error Linear Unit (GELU) activation function. + + Gaussian error linear unit (GELU) computes + `x * P(X <= x)`, where `P(X) ~ N(0, 1)`. + The (GELU) nonlinearity weights inputs by their value, rather than gates + inputs by their sign as in ReLU. + + For example: + + >>> x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32) + >>> y = tf.nn.gelu(x) + >>> y.numpy() + array([-0.00404951, -0.15865529, 0. , 0.8413447 , 2.9959507 ], + dtype=float32) + >>> y = tf.nn.gelu(x, approximate=True) + >>> y.numpy() + array([-0.00363752, -0.15880796, 0. , 0.841192 , 2.9963627 ], + dtype=float32) + + Args: + features: A `float Tensor` representing preactivation values. + approximate: An optional `bool`. Defaults to `False`. Whether to enable + approximation. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same type as `features`. + + Raises: + ValueError: if `features` is not a floating point `Tensor`. + + References: + [Gaussian Error Linear Units (GELUs)](https://arxiv.org/abs/1606.08415). + """ + with ops.name_scope(name, "Gelu", [features]): + features = ops.convert_to_tensor(features, name="features") + if not features.dtype.is_floating: + raise ValueError( + "`features.dtype` must be a floating point tensor." + f"Received:features.dtype={features.dtype}") + if approximate: + coeff = math_ops.cast(0.044715, features.dtype) + return 0.5 * features * ( + 1.0 + math_ops.tanh(0.7978845608028654 * + (features + coeff * math_ops.pow(features, 3)))) + else: + return 0.5 * features * (1.0 + math_ops.erf( + features / math_ops.cast(1.4142135623730951, features.dtype))) + + +def _flatten_outer_dims(logits): + """Flattens logits' outer dimensions and keep its last dimension.""" + rank = array_ops.rank(logits) + last_dim_size = array_ops.slice( + array_ops.shape(logits), [math_ops.subtract(rank, 1)], [1]) + output = array_ops.reshape(logits, array_ops.concat([[-1], last_dim_size], 0)) + + # Set output shape if known. + if not context.executing_eagerly(): + shape = logits.get_shape() + if shape is not None and shape.dims is not None: + shape = shape.as_list() + product = 1 + product_valid = True + for d in shape[:-1]: + if d is None: + product_valid = False + break + else: + product *= d + if product_valid: + output_shape = [product, shape[-1]] + output.set_shape(output_shape) + + return output + + +def _wrap_2d_function(inputs, compute_op, dim=-1, name=None): + """Helper function for ops that accept and return 2d inputs of same shape. + + It reshapes and transposes the inputs into a 2-D Tensor and then invokes + the given function. The output would be transposed and reshaped back. + If the given function returns a tuple of tensors, each of them will be + transposed and reshaped. + + Args: + inputs: A non-empty `Tensor`. Must be one of the following types: `half`, + `float32`, `float64`. + compute_op: The function to wrap. Must accept the input tensor as its first + arugment, and a second keyword argument `name`. + dim: The dimension softmax would be performed on. The default is -1 which + indicates the last dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same shape as inputs. If compute_op returns multiple + tensors, each of them have the same shape as the input. + Raises: + InvalidArgumentError: if `inputs` is empty or `dim` is beyond the last + dimension of `inputs`. + """ + + def _swap_axis(input_tensor, dim_index, last_index, name=None): + """Swaps logits's dim_index and last_index.""" + return array_ops.transpose( + input_tensor, + array_ops.concat([ + math_ops.range(dim_index), [last_index], + math_ops.range(dim_index + 1, last_index), [dim_index] + ], 0), + name=name) + + inputs = ops.convert_to_tensor(inputs) + + # We need its original shape for shape inference. + shape = inputs.get_shape() + is_last_dim = (dim == -1) or (dim == shape.ndims - 1) + + if is_last_dim: + return compute_op(inputs, name=name) + + dim_val = dim + if isinstance(dim, tensor_lib.Tensor): + dim_val = tensor_util.constant_value(dim) + if dim_val is not None and not -shape.ndims <= dim_val < shape.ndims: + raise errors_impl.InvalidArgumentError( + None, None, + f"`dim` must be in the range [{-shape.ndims}, {shape.ndims}) where " + f"{shape.ndims} is the number of dimensions in the input. " + f"Received: dim={dim_val}") + + # If dim is not the last dimension, we have to do a transpose so that we can + # still perform the op on its last dimension. + + # In case dim is negative (and is not last dimension -1), add shape.ndims + ndims = array_ops.rank(inputs) + if not isinstance(dim, tensor_lib.Tensor): + if dim < 0: + dim += ndims + else: + dim = array_ops.where(math_ops.less(dim, 0), dim + ndims, dim) + + # Swap logits' dimension of dim and its last dimension. + input_rank = array_ops.rank(inputs) + dim_axis = dim % shape.ndims + inputs = _swap_axis(inputs, dim_axis, math_ops.subtract(input_rank, 1)) + + # Do the actual call on its last dimension. + def fix_output(output): + output = _swap_axis( + output, dim_axis, math_ops.subtract(input_rank, 1), name=name) + + # Make shape inference work since transpose may erase its static shape. + output.set_shape(shape) + return output + + outputs = compute_op(inputs) + if isinstance(outputs, tuple): + return tuple(fix_output(output) for output in outputs) + else: + return fix_output(outputs) + + +@tf_export("nn.softmax", "math.softmax", v1=[]) +@dispatch.add_dispatch_support +def softmax_v2(logits, axis=None, name=None): + """Computes softmax activations. + + Used for multi-class predictions. The sum of all outputs generated by softmax + is 1. + + This function performs the equivalent of + + ```python + softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis, keepdims=True) + ``` + Example usage: + + >>> softmax = tf.nn.softmax([-1, 0., 1.]) + >>> softmax + + >>> sum(softmax) + + + Args: + logits: A non-empty `Tensor`. Must be one of the following types: `half`, + `float32`, `float64`. + axis: The dimension softmax would be performed on. The default is -1 which + indicates the last dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type and shape as `logits`. + + Raises: + InvalidArgumentError: if `logits` is empty or `axis` is beyond the last + dimension of `logits`. + """ + if axis is None: + axis = -1 + return _wrap_2d_function(logits, gen_nn_ops.softmax, axis, name) + + +@tf_export(v1=["nn.softmax", "math.softmax"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "dim is deprecated, use axis instead", "dim") +def softmax(logits, axis=None, name=None, dim=None): + axis = deprecation.deprecated_argument_lookup("axis", axis, "dim", dim) + if axis is None: + axis = -1 + return _wrap_2d_function(logits, gen_nn_ops.softmax, axis, name) + + +softmax.__doc__ = softmax_v2.__doc__ + + +@tf_export(v1=["nn.log_softmax", "math.log_softmax"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "dim is deprecated, use axis instead", "dim") +def log_softmax(logits, axis=None, name=None, dim=None): + """Computes log softmax activations. + + For each batch `i` and class `j` we have + + logsoftmax = logits - log(reduce_sum(exp(logits), axis)) + + Args: + logits: A non-empty `Tensor`. Must be one of the following types: `half`, + `float32`, `float64`. + axis: The dimension softmax would be performed on. The default is -1 which + indicates the last dimension. + name: A name for the operation (optional). + dim: Deprecated alias for `axis`. + + Returns: + A `Tensor`. Has the same type as `logits`. Same shape as `logits`. + + Raises: + InvalidArgumentError: if `logits` is empty or `axis` is beyond the last + dimension of `logits`. + """ + axis = deprecation.deprecated_argument_lookup("axis", axis, "dim", dim) + if axis is None: + axis = -1 + return _wrap_2d_function(logits, gen_nn_ops.log_softmax, axis, name) + + +@tf_export("nn.log_softmax", "math.log_softmax", v1=[]) +@dispatch.add_dispatch_support +def log_softmax_v2(logits, axis=None, name=None): + """Computes log softmax activations. + + For each batch `i` and class `j` we have + + logsoftmax = logits - log(reduce_sum(exp(logits), axis)) + + Args: + logits: A non-empty `Tensor`. Must be one of the following types: `half`, + `float32`, `float64`. + axis: The dimension softmax would be performed on. The default is -1 which + indicates the last dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `logits`. Same shape as `logits`. + + Raises: + InvalidArgumentError: if `logits` is empty or `axis` is beyond the last + dimension of `logits`. + """ + if axis is None: + axis = -1 + return _wrap_2d_function(logits, gen_nn_ops.log_softmax, axis, name) + + +def _ensure_xent_args(name, labels, logits): + if labels is None or logits is None: + raise ValueError(f"Both `labels` and `logits` must be provided for {name}" + f"Received: labels={labels} and logits={logits}") + + +@tf_export("nn.softmax_cross_entropy_with_logits", v1=[]) +@dispatch.add_dispatch_support +def softmax_cross_entropy_with_logits_v2(labels, logits, axis=-1, name=None): + """Computes softmax cross entropy between `logits` and `labels`. + + Measures the probability error in discrete classification tasks in which the + classes are mutually exclusive (each entry is in exactly one class). For + example, each CIFAR-10 image is labeled with one and only one label: an image + can be a dog or a truck, but not both. + + **NOTE:** While the classes are mutually exclusive, their probabilities + need not be. All that is required is that each row of `labels` is + a valid probability distribution. If they are not, the computation of the + gradient will be incorrect. + + If using exclusive `labels` (wherein one and only + one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`. + + Usage: + + >>> logits = [[4.0, 2.0, 1.0], [0.0, 5.0, 1.0]] + >>> labels = [[1.0, 0.0, 0.0], [0.0, 0.8, 0.2]] + >>> tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) + + + **WARNING:** This op expects unscaled logits, since it performs a `softmax` + on `logits` internally for efficiency. Do not call this op with the + output of `softmax`, as it will produce incorrect results. + + A common use case is to have logits and labels of shape + `[batch_size, num_classes]`, but higher dimensions are supported, with + the `axis` argument specifying the class dimension. + + `logits` and `labels` must have the same dtype (either `float16`, `float32`, + or `float64`). + + Backpropagation will happen into both `logits` and `labels`. To disallow + backpropagation into `labels`, pass label tensors through `tf.stop_gradient` + before feeding it to this function. + + **Note that to avoid confusion, it is required to pass only named arguments to + this function.** + + Args: + labels: Each vector along the class dimension should hold a valid + probability distribution e.g. for the case in which labels are of shape + `[batch_size, num_classes]`, each row of `labels[i]` must be a valid + probability distribution. + logits: Per-label activations, typically a linear output. These activation + energies are interpreted as unnormalized log probabilities. + axis: The class dimension. Defaulted to -1 which is the last dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor` that contains the softmax cross entropy loss. Its type is the + same as `logits` and its shape is the same as `labels` except that it does + not have the last dimension of `labels`. + """ + return softmax_cross_entropy_with_logits_v2_helper( + labels=labels, logits=logits, axis=axis, name=name) + + +@tf_export(v1=["nn.softmax_cross_entropy_with_logits_v2"]) +@dispatch.add_dispatch_support +@deprecated_args(None, "dim is deprecated, use axis instead", "dim") +def softmax_cross_entropy_with_logits_v2_helper( + labels, logits, axis=None, name=None, dim=None): + """Computes softmax cross entropy between `logits` and `labels`. + + Measures the probability error in discrete classification tasks in which the + classes are mutually exclusive (each entry is in exactly one class). For + example, each CIFAR-10 image is labeled with one and only one label: an image + can be a dog or a truck, but not both. + + **NOTE:** While the classes are mutually exclusive, their probabilities + need not be. All that is required is that each row of `labels` is + a valid probability distribution. If they are not, the computation of the + gradient will be incorrect. + + If using exclusive `labels` (wherein one and only + one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`. + + **WARNING:** This op expects unscaled logits, since it performs a `softmax` + on `logits` internally for efficiency. Do not call this op with the + output of `softmax`, as it will produce incorrect results. + + A common use case is to have logits and labels of shape + `[batch_size, num_classes]`, but higher dimensions are supported, with + the `axis` argument specifying the class dimension. + + `logits` and `labels` must have the same dtype (either `float16`, `float32`, + or `float64`). + + Backpropagation will happen into both `logits` and `labels`. To disallow + backpropagation into `labels`, pass label tensors through `tf.stop_gradient` + before feeding it to this function. + + **Note that to avoid confusion, it is required to pass only named arguments to + this function.** + + Args: + labels: Each vector along the class dimension should hold a valid + probability distribution e.g. for the case in which labels are of shape + `[batch_size, num_classes]`, each row of `labels[i]` must be a valid + probability distribution. + logits: Unscaled log probabilities. + axis: The class dimension. Defaulted to -1 which is the last dimension. + name: A name for the operation (optional). + dim: Deprecated alias for axis. + + Returns: + A `Tensor` that contains the softmax cross entropy loss. Its type is the + same as `logits` and its shape is the same as `labels` except that it does + not have the last dimension of `labels`. + """ + # TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This + # could break users who call this with bad labels, but disregard the bad + # results. + axis = deprecated_argument_lookup("axis", axis, "dim", dim) + del dim + if axis is None: + axis = -1 + + with ops.name_scope(name, "softmax_cross_entropy_with_logits", + [logits, labels]) as name: + logits = ops.convert_to_tensor(logits, name="logits") + labels = ops.convert_to_tensor(labels, name="labels") + convert_to_float32 = ( + logits.dtype == dtypes.float16 or logits.dtype == dtypes.bfloat16) + precise_logits = math_ops.cast( + logits, dtypes.float32) if convert_to_float32 else logits + # labels and logits must be of the same type + labels = math_ops.cast(labels, precise_logits.dtype) + input_rank = array_ops.rank(precise_logits) + # For shape inference. + shape = logits.get_shape() + + # Move the dim to the end if dim is not the last dimension. + if axis != -1: + + def _move_dim_to_end(tensor, dim_index, rank): + return array_ops.transpose( + tensor, + array_ops.concat([ + math_ops.range(dim_index), + math_ops.range(dim_index + 1, rank), [dim_index] + ], 0)) + + precise_logits = _move_dim_to_end(precise_logits, axis, input_rank) + labels = _move_dim_to_end(labels, axis, input_rank) + + input_shape = array_ops.shape(precise_logits) + + # Make precise_logits and labels into matrices. + precise_logits = _flatten_outer_dims(precise_logits) + labels = _flatten_outer_dims(labels) + + # Do the actual op computation. + if config.is_op_determinism_enabled(): + log_probs = log_softmax_v2(precise_logits) + cost = -math_ops.reduce_sum(labels * log_probs, axis=1) + else: + # The second output tensor contains the gradients. We use it in + # CrossEntropyGrad() in nn_grad but not here. + cost, unused_backprop = gen_nn_ops.softmax_cross_entropy_with_logits( + precise_logits, labels, name=name) + + # The output cost shape should be the input minus axis. + output_shape = array_ops.slice(input_shape, [0], + [math_ops.subtract(input_rank, 1)]) + cost = array_ops.reshape(cost, output_shape) + + # Make shape inference work since reshape and transpose may erase its static + # shape. + if not context.executing_eagerly( + ) and shape is not None and shape.dims is not None: + shape = shape.as_list() + del shape[axis] + cost.set_shape(shape) + + if convert_to_float32: + return math_ops.cast(cost, logits.dtype) + else: + return cost + + +_XENT_DEPRECATION = """ +Future major versions of TensorFlow will allow gradients to flow +into the labels input on backprop by default. + +See `tf.nn.softmax_cross_entropy_with_logits_v2`. +""" + + +@tf_export(v1=["nn.softmax_cross_entropy_with_logits"]) +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions=_XENT_DEPRECATION) +def softmax_cross_entropy_with_logits( + labels=None, + logits=None, + dim=-1, + name=None, + axis=None): + """Computes softmax cross entropy between `logits` and `labels`. + + Measures the probability error in discrete classification tasks in which the + classes are mutually exclusive (each entry is in exactly one class). For + example, each CIFAR-10 image is labeled with one and only one label: an image + can be a dog or a truck, but not both. + + **NOTE:** While the classes are mutually exclusive, their probabilities + need not be. All that is required is that each row of `labels` is + a valid probability distribution. If they are not, the computation of the + gradient will be incorrect. + + If using exclusive `labels` (wherein one and only + one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`. + + **WARNING:** This op expects unscaled logits, since it performs a `softmax` + on `logits` internally for efficiency. Do not call this op with the + output of `softmax`, as it will produce incorrect results. + + A common use case is to have logits and labels of shape + `[batch_size, num_classes]`, but higher dimensions are supported, with + the `dim` argument specifying the class dimension. + + Backpropagation will happen only into `logits`. To calculate a cross entropy + loss that allows backpropagation into both `logits` and `labels`, see + `tf.nn.softmax_cross_entropy_with_logits_v2`. + + **Note that to avoid confusion, it is required to pass only named arguments to + this function.** + + Args: + labels: Each vector along the class dimension should hold a valid + probability distribution e.g. for the case in which labels are of shape + `[batch_size, num_classes]`, each row of `labels[i]` must be a valid + probability distribution. + logits: Per-label activations, typically a linear output. These activation + energies are interpreted as unnormalized log probabilities. + dim: The class dimension. Defaulted to -1 which is the last dimension. + name: A name for the operation (optional). + axis: Alias for dim. + + Returns: + A `Tensor` that contains the softmax cross entropy loss. Its type is the + same as `logits` and its shape is the same as `labels` except that it does + not have the last dimension of `labels`. + """ + dim = deprecated_argument_lookup("axis", axis, "dim", dim) + _ensure_xent_args("softmax_cross_entropy_with_logits", labels, logits) + + with ops.name_scope(name, "softmax_cross_entropy_with_logits_sg", + [logits, labels]) as name: + labels = array_ops.stop_gradient(labels, name="labels_stop_gradient") + + return softmax_cross_entropy_with_logits_v2( + labels=labels, logits=logits, axis=dim, name=name) + + +def _sparse_softmax_cross_entropy_with_rank_2_logits(logits, labels, name): + if config.is_op_determinism_enabled(): + # TODO(duncanriach): Implement a GPU-deterministic version of this op at + # the C++/CUDA level. + + # The actual op functionality + log_probs = log_softmax_v2(logits) + cost = math_ops.negative(array_ops.gather(log_probs, labels, batch_dims=1)) + + # Force the output to be NaN when the corresponding label is invalid. + # Without the selective gradient gating provided by the following code, + # backprop into the actual op functionality above, when there are invalid + # labels, leads to corruption of the gradients associated with valid labels. + # TODO(duncanriach): Uncover the source of the aforementioned corruption. + nan_tensor = constant_op.constant(float("Nan"), dtype=logits.dtype) + cost_all_nans = array_ops.broadcast_to(nan_tensor, array_ops.shape(cost)) + class_count = math_ops.cast(array_ops.shape(logits)[-1], labels.dtype) + cost = array_ops.where( + math_ops.logical_or( + math_ops.less(labels, 0), + math_ops.greater_equal(labels, class_count)), cost_all_nans, cost) + else: + # The second output tensor contains the gradients. We use it in + # _CrossEntropyGrad() in nn_grad but not here. + cost, _ = gen_nn_ops.sparse_softmax_cross_entropy_with_logits( + logits, labels, name=name) + return cost + + +@tf_export(v1=["nn.sparse_softmax_cross_entropy_with_logits"]) +@dispatch.add_dispatch_support +def sparse_softmax_cross_entropy_with_logits( + labels=None, + logits=None, + name=None): + """Computes sparse softmax cross entropy between `logits` and `labels`. + + Measures the probability error in discrete classification tasks in which the + classes are mutually exclusive (each entry is in exactly one class). For + example, each CIFAR-10 image is labeled with one and only one label: an image + can be a dog or a truck, but not both. + + **NOTE:** For this operation, the probability of a given label is considered + exclusive. That is, soft classes are not allowed, and the `labels` vector + must provide a single specific index for the true class for each row of + `logits` (each minibatch entry). For soft softmax classification with + a probability distribution for each entry, see + `softmax_cross_entropy_with_logits_v2`. + + **WARNING:** This op expects unscaled logits, since it performs a `softmax` + on `logits` internally for efficiency. Do not call this op with the + output of `softmax`, as it will produce incorrect results. + + A common use case is to have logits of shape + `[batch_size, num_classes]` and have labels of shape + `[batch_size]`, but higher dimensions are supported, in which + case the `dim`-th dimension is assumed to be of size `num_classes`. + `logits` must have the dtype of `float16`, `float32`, or `float64`, and + `labels` must have the dtype of `int32` or `int64`. + + **Note that to avoid confusion, it is required to pass only named arguments to + this function.** + + Args: + labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of + `labels` and result) and dtype `int32` or `int64`. Each entry in `labels` + must be an index in `[0, num_classes)`. Other values will raise an + exception when this op is run on CPU, and return `NaN` for corresponding + loss and gradient rows on GPU. + logits: Per-label activations (typically a linear output) of shape + `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32`, or + `float64`. These activation energies are interpreted as unnormalized log + probabilities. + name: A name for the operation (optional). + + Returns: + A `Tensor` of the same shape as `labels` and of the same type as `logits` + with the softmax cross entropy loss. + + Raises: + ValueError: If logits are scalars (need to have rank >= 1) or if the rank + of the labels is not equal to the rank of the logits minus one. + """ + _ensure_xent_args("sparse_softmax_cross_entropy_with_logits", labels, logits) + + # TODO(pcmurray) Raise an error when the label is not an index in + # [0, num_classes). Note: This could break users who call this with bad + # labels, but disregard the bad results. + + # Reshape logits and labels to rank 2. + with ops.name_scope(name, "SparseSoftmaxCrossEntropyWithLogits", + [labels, logits]): + labels = ops.convert_to_tensor(labels) + logits = ops.convert_to_tensor(logits) + precise_logits = math_ops.cast(logits, dtypes.float32) if (dtypes.as_dtype( + logits.dtype) == dtypes.float16) else logits + + # Store label shape for result later. + labels_static_shape = labels.get_shape() + labels_shape = array_ops.shape(labels) + static_shapes_fully_defined = ( + labels_static_shape.is_fully_defined() and + logits.get_shape()[:-1].is_fully_defined()) + if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0: + raise ValueError( + f"`logits` cannot be a scalar. Received logits={logits}`") + if logits.get_shape().ndims is not None and ( + labels_static_shape.ndims is not None and + labels_static_shape.ndims != logits.get_shape().ndims - 1): + raise ValueError( + "`labels.shape.rank` must equal `logits.shape.rank - 1`. " + f"Received: labels.shape={labels_static_shape} of rank " + f"{labels_static_shape.rank} and logits.shape={logits.get_shape()} " + f"of rank {logits.get_shape().rank}") + if (static_shapes_fully_defined and + labels_static_shape != logits.get_shape()[:-1]): + raise ValueError( + "`labels.shape` must equal `logits.shape` except for " + f"the last dimension. Received: labels.shape={labels_static_shape} " + f"and logits.shape={logits.get_shape()}") + # Check if no reshapes are required. + if logits.get_shape().ndims == 2: + cost = _sparse_softmax_cross_entropy_with_rank_2_logits( + precise_logits, labels, name=name) + if logits.dtype == dtypes.float16: + return math_ops.cast(cost, dtypes.float16) + else: + return cost + + # Perform a check of the dynamic shapes if the static shapes are not fully + # defined. + shape_checks = [] + if not static_shapes_fully_defined: + shape_checks.append( + check_ops.assert_equal( + array_ops.shape(labels), + array_ops.shape(logits)[:-1])) + with ops.control_dependencies(shape_checks): + # Reshape logits to 2 dim, labels to 1 dim. + num_classes = array_ops.shape(logits)[array_ops.rank(logits) - 1] + precise_logits = array_ops.reshape(precise_logits, [-1, num_classes]) + labels = array_ops.reshape(labels, [-1]) + cost = _sparse_softmax_cross_entropy_with_rank_2_logits( + precise_logits, labels, name=name) + cost = array_ops.reshape(cost, labels_shape) + cost.set_shape(labels_static_shape) + if logits.dtype == dtypes.float16: + return math_ops.cast(cost, dtypes.float16) + else: + return cost + + +@tf_export("nn.sparse_softmax_cross_entropy_with_logits", v1=[]) +@dispatch.add_dispatch_support +def sparse_softmax_cross_entropy_with_logits_v2(labels, logits, name=None): + """Computes sparse softmax cross entropy between `logits` and `labels`. + + Measures the probability error in discrete classification tasks in which the + classes are mutually exclusive (each entry is in exactly one class). For + example, each CIFAR-10 image is labeled with one and only one label: an image + can be a dog or a truck, but not both. + + Note: For this operation, the probability of a given label is considered + exclusive. That is, soft classes are not allowed, and the `labels` vector + must provide a single specific index for the true class for each row of + `logits` (each minibatch entry). For soft softmax classification with + a probability distribution for each entry, see + `softmax_cross_entropy_with_logits_v2`. + + Warning: This op expects unscaled logits, since it performs a `softmax` + on `logits` internally for efficiency. Do not call this op with the + output of `softmax`, as it will produce incorrect results. + + A common use case is to have logits of shape + `[batch_size, num_classes]` and have labels of shape + `[batch_size]`, but higher dimensions are supported, in which + case the `dim`-th dimension is assumed to be of size `num_classes`. + `logits` must have the dtype of `float16`, `float32`, or `float64`, and + `labels` must have the dtype of `int32` or `int64`. + + >>> logits = tf.constant([[2., -5., .5, -.1], + ... [0., 0., 1.9, 1.4], + ... [-100., 100., -100., -100.]]) + >>> labels = tf.constant([0, 3, 1]) + >>> tf.nn.sparse_softmax_cross_entropy_with_logits( + ... labels=labels, logits=logits).numpy() + array([0.29750752, 1.1448325 , 0. ], dtype=float32) + + To avoid confusion, passing only named arguments to this function is + recommended. + + Args: + labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of + `labels` and result) and dtype `int32` or `int64`. Each entry in `labels` + must be an index in `[0, num_classes)`. Other values will raise an + exception when this op is run on CPU, and return `NaN` for corresponding + loss and gradient rows on GPU. + logits: Unscaled log probabilities of shape `[d_0, d_1, ..., d_{r-1}, + num_classes]` and dtype `float16`, `float32`, or `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of the same shape as `labels` and of the same type as `logits` + with the softmax cross entropy loss. + + Raises: + ValueError: If logits are scalars (need to have rank >= 1) or if the rank + of the labels is not equal to the rank of the logits minus one. + """ + return sparse_softmax_cross_entropy_with_logits( + labels=labels, logits=logits, name=name) + + +@tf_export("nn.avg_pool", v1=["nn.avg_pool_v2"]) +@dispatch.add_dispatch_support +def avg_pool_v2(input, ksize, strides, padding, data_format=None, name=None): # pylint: disable=redefined-builtin + """Performs the avg pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Args: + input: Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape + + [num_channels]` if `data_format` does not start with "NC" (default), or + `[batch_size, num_channels] + input_spatial_shape` if data_format starts + with "NC". Pooling happens over the spatial dimensions only. + ksize: An int or list of `ints` that has length `1`, `N` or `N+2`. The size + of the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The + stride of the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string. Specifies the channel dimension. For N=1 it can be + either "NWC" (default) or "NCW", for N=2 it can be either "NHWC" (default) + or "NCHW" and for N=3 either "NDHWC" (default) or "NCDHW". + name: Optional name for the operation. + + Returns: + A `Tensor` of format specified by `data_format`. + The average pooled output tensor. + """ + if input.shape is not None: + n = len(input.shape) - 2 + elif data_format is not None: + n = len(data_format) - 2 + else: + raise ValueError( + "`input` must have a static shape or `data_format` must be given. " + f"Received: input.shape={input.shape} and " + f"data_format={data_format}") + if not 1 <= n <= 3: + raise ValueError( + f"`input.shape.rank` must be 3, 4 or 5. Received: " + f"input.shape={input.shape} of rank {n + 2}.") + + if data_format is None: + channel_index = n + 1 + else: + channel_index = 1 if data_format.startswith("NC") else n + 1 + + ksize = _get_sequence(ksize, n, channel_index, "ksize") + strides = _get_sequence(strides, n, channel_index, "strides") + + avg_pooling_ops = { + 1: avg_pool1d, + 2: gen_nn_ops.avg_pool, + 3: gen_nn_ops.avg_pool3d + } + + op = avg_pooling_ops[n] + return op( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + + +@tf_export(v1=["nn.avg_pool", "nn.avg_pool2d"]) +@dispatch.add_dispatch_support +def avg_pool(value, ksize, strides, padding, data_format="NHWC", + name=None, input=None): # pylint: disable=redefined-builtin + """Performs the average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Args: + value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type + `float32`, `float64`, `qint8`, `quint8`, or `qint32`. + ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of + the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. + See the "returns" section of `tf.nn.convolution` for details. + data_format: A string. 'NHWC' and 'NCHW' are supported. + name: Optional name for the operation. + input: Alias for value. + + Returns: + A `Tensor` with the same type as `value`. The average pooled output tensor. + """ + with ops.name_scope(name, "AvgPool", [value]) as name: + value = deprecation.deprecated_argument_lookup( + "input", input, "value", value) + + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + ksize = _get_sequence(ksize, 2, channel_index, "ksize") + strides = _get_sequence(strides, 2, channel_index, "strides") + + return gen_nn_ops.avg_pool( + value, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + + +@tf_export("nn.avg_pool2d", v1=[]) +@dispatch.add_dispatch_support +def avg_pool2d(input, ksize, strides, padding, data_format="NHWC", name=None): # pylint: disable=redefined-builtin + """Performs the average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Args: + input: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type + `float32`, `float64`, `qint8`, `quint8`, or `qint32`. + ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of + the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string. 'NHWC' and 'NCHW' are supported. + name: Optional name for the operation. + + Returns: + A `Tensor` with the same type as `value`. The average pooled output tensor. + """ + with ops.name_scope(name, "AvgPool2D", [input]) as name: + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + ksize = _get_sequence(ksize, 2, channel_index, "ksize") + strides = _get_sequence(strides, 2, channel_index, "strides") + + return gen_nn_ops.avg_pool( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + + +@tf_export("nn.avg_pool1d") +@dispatch.add_dispatch_support +def avg_pool1d(input, ksize, strides, padding, data_format="NWC", name=None): # pylint: disable=redefined-builtin + """Performs the average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Note internally this op reshapes and uses the underlying 2d operation. + + Args: + input: A 3-D `Tensor` of the format specified by `data_format`. + ksize: An int or list of `ints` that has length `1` or `3`. The size of the + window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1` or `3`. The stride of + the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: An optional string from: "NWC", "NCW". Defaults to "NWC". + name: A name for the operation (optional). + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + """ + with ops.name_scope(name, "AvgPool1D", [input]) as name: + if data_format is None: + data_format = "NWC" + channel_index = 1 if data_format.startswith("NC") else 2 + ksize = [1] + _get_sequence(ksize, 1, channel_index, "ksize") + strides = [1] + _get_sequence(strides, 1, channel_index, "strides") + + expanding_dim = 1 if data_format == "NWC" else 2 + data_format = "NHWC" if data_format == "NWC" else "NCHW" + + input = array_ops.expand_dims_v2(input, expanding_dim) + result = gen_nn_ops.avg_pool( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + return array_ops.squeeze(result, expanding_dim) + + +@tf_export("nn.avg_pool3d") +@dispatch.add_dispatch_support +def avg_pool3d(input, ksize, strides, padding, data_format="NDHWC", name=None): # pylint: disable=redefined-builtin + """Performs the average pooling on the input. + + Each entry in `output` is the mean of the corresponding size `ksize` + window in `value`. + + Args: + input: A 5-D `Tensor` of shape `[batch, depth, height, width, channels]` + and type `float32`, `float64`, `qint8`, `quint8`, or `qint32`. + ksize: An int or list of `ints` that has length `1`, `3` or `5`. The size of + the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `3` or `5`. The + stride of the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A string. 'NDHWC' and 'NCDHW' are supported. + name: Optional name for the operation. + + Returns: + A `Tensor` with the same type as `value`. The average pooled output tensor. + """ + with ops.name_scope(name, "AvgPool3D", [input]) as name: + if data_format is None: + data_format = "NDHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + ksize = _get_sequence(ksize, 3, channel_index, "ksize") + strides = _get_sequence(strides, 3, channel_index, "strides") + + return gen_nn_ops.avg_pool3d( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) + + +# pylint: disable=redefined-builtin +@tf_export("nn.max_pool", v1=["nn.max_pool_v2"]) +@dispatch.add_dispatch_support +def max_pool_v2(input, ksize, strides, padding, data_format=None, name=None): + """Performs max pooling on the input. + + For a given window of `ksize`, takes the maximum value within that window. + Used for reducing computation and preventing overfitting. + + Consider an example of pooling with 2x2, non-overlapping windows: + + >>> matrix = tf.constant([ + ... [0, 0, 1, 7], + ... [0, 2, 0, 0], + ... [5, 2, 0, 0], + ... [0, 0, 9, 8], + ... ]) + >>> reshaped = tf.reshape(matrix, (1, 4, 4, 1)) + >>> tf.nn.max_pool(reshaped, ksize=2, strides=2, padding="SAME") + + + We can adjust the window size using the `ksize` parameter. For example, if we + were to expand the window to 3: + + >>> tf.nn.max_pool(reshaped, ksize=3, strides=2, padding="SAME") + + + We've now picked up two additional large numbers (5 and 9) in two of the + pooled spots. + + Note that our windows are now overlapping, since we're still moving by 2 units + on each iteration. This is causing us to see the same 9 repeated twice, since + it is part of two overlapping windows. + + We can adjust how far we move our window with each iteration using the + `strides` parameter. Updating this to the same value as our window size + eliminates the overlap: + + >>> tf.nn.max_pool(reshaped, ksize=3, strides=3, padding="SAME") + + + Because the window does not neatly fit into our input, padding is added around + the edges, giving us the same result as when we used a 2x2 window. We can skip + padding altogether and simply drop the windows that do not fully fit into our + input by instead passing `"VALID"` to the `padding` argument: + + >>> tf.nn.max_pool(reshaped, ksize=3, strides=3, padding="VALID") + + + Now we've grabbed the largest value in the 3x3 window starting from the upper- + left corner. Since no other windows fit in our input, they are dropped. + + Args: + input: Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape + + [num_channels]` if `data_format` does not start with "NC" (default), or + `[batch_size, num_channels] + input_spatial_shape` if data_format starts + with "NC". Pooling happens over the spatial dimensions only. + ksize: An int or list of `ints` that has length `1`, `N` or `N+2`. The size + of the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `N` or `N+2`. The + stride of the sliding window for each dimension of the input tensor. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit + padding, the size of the paddings cannot be greater than the sliding + window size. + data_format: A string. Specifies the channel dimension. For N=1 it can be + either "NWC" (default) or "NCW", for N=2 it can be either "NHWC" (default) + or "NCHW" and for N=3 either "NDHWC" (default) or "NCDHW". + name: Optional name for the operation. + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + + Raises: + ValueError: If + - explicit padding is used with an input tensor of rank 5. + - explicit padding is used with data_format='NCHW_VECT_C'. + """ + if input.shape is not None: + n = len(input.shape) - 2 + elif data_format is not None: + n = len(data_format) - 2 + else: + raise ValueError( + "`input` must have a static shape or a data format must be given. " + f"Received: input.shape={input.shape} and " + f"data_format={data_format}") + if not 1 <= n <= 3: + raise ValueError( + f"`input.shape.rank` must be 3, 4 or 5. Received: " + f"input.shape={input.shape} of rank {n + 2}.") + if data_format is None: + channel_index = n + 1 + else: + channel_index = 1 if data_format.startswith("NC") else n + 1 + + if isinstance(padding, (list, tuple)) and data_format == "NCHW_VECT_C": + raise ValueError("`data_format='NCHW_VECT_C'` is not supported with " + f"explicit padding. Received: padding={padding}") + + ksize = _get_sequence(ksize, n, channel_index, "ksize") + strides = _get_sequence(strides, n, channel_index, "strides") + + if (isinstance(padding, (list, tuple)) and n == 3): + raise ValueError("Explicit padding is not supported with an input " + f"tensor of rank 5. Received: padding={padding}") + + max_pooling_ops = { + 1: max_pool1d, + 2: max_pool2d, + 3: gen_nn_ops.max_pool3d + } + + op = max_pooling_ops[n] + return op( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) +# pylint: enable=redefined-builtin + + +@tf_export(v1=["nn.max_pool"]) +@dispatch.add_dispatch_support +def max_pool(value, + ksize, + strides, + padding, + data_format="NHWC", + name=None, + input=None): # pylint: disable=redefined-builtin + """Performs the max pooling on the input. + + Args: + value: A 4-D `Tensor` of the format specified by `data_format`. + ksize: An int or list of `ints` that has length `1`, `2` or `4`. + The size of the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `2` or `4`. + The stride of the sliding window for each dimension of the input tensor. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. When explicit padding is used and + data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, + pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used + and data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit + padding, the size of the paddings cannot be greater than the sliding + window size. + data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported. + name: Optional name for the operation. + input: Alias for value. + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + """ + value = deprecation.deprecated_argument_lookup("input", input, "value", value) + with ops.name_scope(name, "MaxPool", [value]) as name: + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + ksize = _get_sequence(ksize, 2, channel_index, "ksize") + strides = _get_sequence(strides, 2, channel_index, "strides") + if isinstance(padding, (list, tuple)) and data_format == "NCHW_VECT_C": + raise ValueError("`data_format='NCHW_VECT_C'` is not supported with " + f"explicit padding. Received: padding={padding}") + padding, explicit_paddings = convert_padding(padding) + if ((np.isscalar(ksize) and ksize == 0) or + (isinstance(ksize, + (list, tuple, np.ndarray)) and any(v == 0 for v in ksize))): + raise ValueError(f"`ksize` cannot be zero. Received: ksize={ksize}") + + return gen_nn_ops.max_pool( + value, + ksize=ksize, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + name=name) + + +# pylint: disable=redefined-builtin +@tf_export("nn.max_pool1d") +@dispatch.add_dispatch_support +def max_pool1d(input, ksize, strides, padding, data_format="NWC", name=None): + """Performs the max pooling on the input. + + Note internally this op reshapes and uses the underlying 2d operation. + + Args: + input: A 3-D `Tensor` of the format specified by `data_format`. + ksize: An int or list of `ints` that has length `1` or `3`. The size of the + window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1` or `3`. The stride of + the sliding window for each dimension of the input tensor. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NWC"`, this should be in the form `[[0, 0], [pad_left, pad_right], [0, + 0]]`. When explicit padding used and data_format is `"NCW"`, this should + be in the form `[[0, 0], [0, 0], [pad_left, pad_right]]`. When using + explicit padding, the size of the paddings cannot be greater than the + sliding window size. + data_format: An optional string from: "NWC", "NCW". Defaults to "NWC". + name: A name for the operation (optional). + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + """ + with ops.name_scope(name, "MaxPool1d", [input]) as name: + if isinstance(padding, (list, tuple)) and data_format == "NCHW_VECT_C": + raise ValueError("`data_format='NCHW_VECT_C'` is not supported with " + f"explicit padding. Received: padding={padding}") + if data_format is None: + data_format = "NWC" + channel_index = 1 if data_format.startswith("NC") else 2 + ksize = [1] + _get_sequence(ksize, 1, channel_index, "ksize") + strides = [1] + _get_sequence(strides, 1, channel_index, "strides") + padding, explicit_paddings = convert_padding(padding, 3) + if padding == "EXPLICIT": + explicit_paddings = [0, 0] + explicit_paddings + + expanding_dim = 1 if data_format == "NWC" else 2 + data_format = "NHWC" if data_format == "NWC" else "NCHW" + + input = array_ops.expand_dims_v2(input, expanding_dim) + result = gen_nn_ops.max_pool( + input, + ksize=ksize, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + name=name) + return array_ops.squeeze(result, expanding_dim) +# pylint: enable=redefined-builtin + + +# pylint: disable=redefined-builtin +@tf_export("nn.max_pool2d") +@dispatch.add_dispatch_support +def max_pool2d(input, ksize, strides, padding, data_format="NHWC", name=None): + """Performs max pooling on 2D spatial data such as images. + + This is a more specific version of `tf.nn.max_pool` where the input tensor + is 4D, representing 2D spatial data such as images. Using these APIs are + equivalent + + Downsamples the input images along theirs spatial dimensions (height and + width) by taking its maximum over an input window defined by `ksize`. + The window is shifted by `strides` along each dimension. + + For example, for `strides=(2, 2)` and `padding=VALID` windows that extend + outside of the input are not included in the output: + + >>> x = tf.constant([[1., 2., 3., 4.], + ... [5., 6., 7., 8.], + ... [9., 10., 11., 12.]]) + >>> # Add the `batch` and `channels` dimensions. + >>> x = x[tf.newaxis, :, :, tf.newaxis] + >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2), + ... padding="VALID") + >>> result[0, :, :, 0] + + + With `padding=SAME`, we get: + + >>> x = tf.constant([[1., 2., 3., 4.], + ... [5., 6., 7., 8.], + ... [9., 10., 11., 12.]]) + >>> x = x[tf.newaxis, :, :, tf.newaxis] + >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2), + ... padding='SAME') + >>> result[0, :, :, 0] + + + We can also specify padding explicitly. The following example adds width-1 + padding on all sides (top, bottom, left, right): + + >>> x = tf.constant([[1., 2., 3., 4.], + ... [5., 6., 7., 8.], + ... [9., 10., 11., 12.]]) + >>> x = x[tf.newaxis, :, :, tf.newaxis] + >>> result = tf.nn.max_pool2d(x, ksize=(2, 2), strides=(2, 2), + ... padding=[[0, 0], [1, 1], [1, 1], [0, 0]]) + >>> result[0, :, :, 0] + + + For more examples and detail, see `tf.nn.max_pool`. + + Args: + input: A 4-D `Tensor` of the format specified by `data_format`. + ksize: An int or list of `ints` that has length `1`, `2` or `4`. The size of + the window for each dimension of the input tensor. If only one integer is + specified, then we apply the same window for all 4 dims. If two are + provided then we use those for H, W dimensions and keep N, C dimension + window size = 1. + strides: An int or list of `ints` that has length `1`, `2` or `4`. The + stride of the sliding window for each dimension of the input tensor. If + only one integer is specified, we apply the same stride to all 4 dims. If + two are provided we use those for the H, W dimensions and keep N, C of + stride = 1. + padding: Either the `string` `"SAME"` or `"VALID"` indicating the type of + padding algorithm to use, or a list indicating the explicit paddings at + the start and end of each dimension. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. When explicit padding is used and data_format is + `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], + [pad_left, pad_right], [0, 0]]`. When explicit padding used and + data_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], + [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit + padding, the size of the paddings cannot be greater than the sliding + window size. + data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported. + name: Optional name for the operation. + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + + Raises: + ValueError: If explicit padding is used with data_format='NCHW_VECT_C'. + """ + with ops.name_scope(name, "MaxPool2d", [input]) as name: + if data_format is None: + data_format = "NHWC" + channel_index = 1 if data_format.startswith("NC") else 3 + + ksize = _get_sequence(ksize, 2, channel_index, "ksize") + strides = _get_sequence(strides, 2, channel_index, "strides") + if isinstance(padding, (list, tuple)) and data_format == "NCHW_VECT_C": + raise ValueError("`data_format='NCHW_VECT_C'` is not supported with " + f"explicit padding. Received: padding={padding}") + padding, explicit_paddings = convert_padding(padding) + + return gen_nn_ops.max_pool( + input, + ksize=ksize, + strides=strides, + padding=padding, + explicit_paddings=explicit_paddings, + data_format=data_format, + name=name) +# pylint: enable=redefined-builtin + + +# pylint: disable=redefined-builtin +@tf_export("nn.max_pool3d") +@dispatch.add_dispatch_support +def max_pool3d(input, ksize, strides, padding, data_format="NDHWC", name=None): + """Performs the max pooling on the input. + + Args: + input: A 5-D `Tensor` of the format specified by `data_format`. + ksize: An int or list of `ints` that has length `1`, `3` or `5`. The size of + the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `3` or `5`. The + stride of the sliding window for each dimension of the input tensor. + padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". + The data format of the input and output data. With the default format + "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, + in_width, in_channels]. Alternatively, the format could be "NCDHW", the + data storage order is: [batch, in_channels, in_depth, in_height, + in_width]. + name: A name for the operation (optional). + + Returns: + A `Tensor` of format specified by `data_format`. + The max pooled output tensor. + """ + with ops.name_scope(name, "MaxPool3D", [input]) as name: + if data_format is None: + data_format = "NDHWC" + channel_index = 1 if data_format.startswith("NC") else 4 + + ksize = _get_sequence(ksize, 3, channel_index, "ksize") + strides = _get_sequence(strides, 3, channel_index, "strides") + + return gen_nn_ops.max_pool3d( + input, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format, + name=name) +# pylint: enable=redefined-builtin + + +@tf_export("nn.max_pool_with_argmax", v1=[]) +@dispatch.add_dispatch_support +def max_pool_with_argmax_v2( + input, # pylint: disable=redefined-builtin + ksize, + strides, + padding, + data_format="NHWC", + output_dtype=dtypes.int64, + include_batch_in_index=False, + name=None): + """Performs max pooling on the input and outputs both max values and indices. + + The indices in `argmax` are flattened, so that a maximum value at position + `[b, y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if + `include_batch_in_index` is False; + `((b * height + y) * width + x) * channels + c` + if `include_batch_in_index` is True. + + The indices returned are always in `[0, height) x [0, width)` before + flattening, even if padding is involved and the mathematically correct answer + is outside (either negative or too large). This is a bug, but fixing it is + difficult to do in a safe backwards compatible way, especially due to + flattening. + + Args: + input: A `Tensor`. Must be one of the following types: `float32`, `float64`, + `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, + `uint32`, `uint64`. + 4-D with shape `[batch, height, width, channels]`. Input to pool over. + ksize: An int or list of `ints` that has length `1`, `2` or `4`. + The size of the window for each dimension of the input tensor. + strides: An int or list of `ints` that has length `1`, `2` or `4`. + The stride of the sliding window for each dimension of the + input tensor. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: An optional `string`, must be set to `"NHWC"`. Defaults to + `"NHWC"`. + Specify the data format of the input and output data. + output_dtype: An optional `tf.DType` from: `tf.int32, tf.int64`. + Defaults to `tf.int64`. + The dtype of the returned argmax tensor. + include_batch_in_index: An optional `boolean`. Defaults to `False`. + Whether to include batch dimension in flattened index of `argmax`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output, argmax). + + output: A `Tensor`. Has the same type as `input`. + argmax: A `Tensor` of type `output_dtype`. + """ + + if data_format != "NHWC": + raise ValueError("`data_format` values other than 'NHWC' are not " + f"supported. Received: data_format={data_format}") + + ksize = _get_sequence(ksize, 2, 3, "ksize") + strides = _get_sequence(strides, 2, 3, "strides") + + return gen_nn_ops.max_pool_with_argmax( + input=input, + ksize=ksize, + strides=strides, + padding=padding, + Targmax=output_dtype, + include_batch_in_index=include_batch_in_index, + name=name) + + +@tf_export(v1=["nn.max_pool_with_argmax"]) +@dispatch.add_dispatch_support +def max_pool_with_argmax_v1( # pylint: disable=missing-docstring,invalid-name + input, # pylint: disable=redefined-builtin + ksize, + strides, + padding, + data_format="NHWC", + Targmax=None, + name=None, + output_dtype=None, + include_batch_in_index=False): + if data_format != "NHWC": + raise ValueError("`data_format` values other than 'NHWC' are not " + f"supported. Received: data_format={data_format}") + + Targmax = deprecated_argument_lookup( + "output_dtype", output_dtype, "Targmax", Targmax) + if Targmax is None: + Targmax = dtypes.int64 + return gen_nn_ops.max_pool_with_argmax( + input=input, + ksize=ksize, + strides=strides, + padding=padding, + Targmax=Targmax, + include_batch_in_index=include_batch_in_index, + name=name) + + +max_pool_with_argmax_v1.__doc__ = gen_nn_ops.max_pool_with_argmax.__doc__ + + +@ops.RegisterStatistics("Conv3D", "flops") +def _calc_conv3d_flops(graph, node): + """Calculates the compute resources needed for Conv3D.""" + input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + input_shape.assert_is_fully_defined() + filter_shape = graph_util.tensor_shape_from_node_def_name( + graph, node.input[1]) + filter_shape.assert_is_fully_defined() + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + filter_time = int(filter_shape[0]) + filter_height = int(filter_shape[1]) + filter_width = int(filter_shape[2]) + filter_in_depth = int(filter_shape[3]) + output_count = np.prod(output_shape.as_list(), dtype=np.int64) + return ops.OpStats("flops", (output_count * filter_in_depth * filter_time * + filter_height * filter_width * 2)) + + +@ops.RegisterStatistics("Conv2D", "flops") +def _calc_conv_flops(graph, node): + """Calculates the compute resources needed for Conv2D.""" + input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + input_shape.assert_is_fully_defined() + filter_shape = graph_util.tensor_shape_from_node_def_name( + graph, node.input[1]) + filter_shape.assert_is_fully_defined() + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + filter_height = int(filter_shape[0]) + filter_width = int(filter_shape[1]) + filter_in_depth = int(filter_shape[2]) + output_count = np.prod(output_shape.as_list(), dtype=np.int64) + return ops.OpStats( + "flops", + (output_count * filter_in_depth * filter_height * filter_width * 2)) + + +@ops.RegisterStatistics("DepthwiseConv2dNative", "flops") +def _calc_depthwise_conv_flops(graph, node): + """Calculates the compute resources needed for DepthwiseConv2dNative.""" + input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + input_shape.assert_is_fully_defined() + filter_shape = graph_util.tensor_shape_from_node_def_name( + graph, node.input[1]) + filter_shape.assert_is_fully_defined() + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + filter_height = int(filter_shape[0]) + filter_width = int(filter_shape[1]) + output_count = np.prod(output_shape.as_list(), dtype=np.int64) + return ops.OpStats("flops", (output_count * filter_height * filter_width * 2)) + + +@ops.RegisterStatistics("BiasAdd", "flops") +def _calc_bias_add_flops(graph, node): + """Calculates the computing needed for BiasAdd.""" + input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + input_shape.assert_is_fully_defined() + input_count = np.prod(input_shape.as_list()) + return ops.OpStats("flops", input_count) + + +@tf_export(v1=["nn.xw_plus_b"]) +@dispatch.add_dispatch_support +def xw_plus_b(x, weights, biases, name=None): # pylint: disable=invalid-name + """Computes matmul(x, weights) + biases. + + Args: + x: a 2D tensor. Dimensions typically: batch, in_units + weights: a 2D tensor. Dimensions typically: in_units, out_units + biases: a 1D tensor. Dimensions: out_units + name: A name for the operation (optional). If not specified + "xw_plus_b" is used. + + Returns: + A 2-D Tensor computing matmul(x, weights) + biases. + Dimensions typically: batch, out_units. + """ + with ops.name_scope(name, "xw_plus_b", [x, weights, biases]) as name: + x = ops.convert_to_tensor(x, name="x") + weights = ops.convert_to_tensor(weights, name="weights") + biases = ops.convert_to_tensor(biases, name="biases") + mm = math_ops.matmul(x, weights) + return bias_add(mm, biases, name=name) + + +def xw_plus_b_v1(x, weights, biases, name=None): + """Computes matmul(x, weights) + biases. + + This is a deprecated version of that will soon be removed. + + Args: + x: a 2D tensor. Dimensions typically: batch, in_units + weights: a 2D tensor. Dimensions typically: in_units, out_units + biases: a 1D tensor. Dimensions: out_units + name: A name for the operation (optional). If not specified + "xw_plus_b_v1" is used. + + Returns: + A 2-D Tensor computing matmul(x, weights) + biases. + Dimensions typically: batch, out_units. + """ + with ops.name_scope(name, "xw_plus_b_v1", [x, weights, biases]) as name: + x = ops.convert_to_tensor(x, name="x") + weights = ops.convert_to_tensor(weights, name="weights") + biases = ops.convert_to_tensor(biases, name="biases") + mm = math_ops.matmul(x, weights) + return bias_add_v1(mm, biases, name=name) + + +def _get_noise_shape(x, noise_shape): + # If noise_shape is none return immediately. + if noise_shape is None: + return array_ops.shape(x) + + try: + # Best effort to figure out the intended shape. + # If not possible, let the op to handle it. + # In eager mode exception will show up. + noise_shape_ = tensor_shape.as_shape(noise_shape) + except (TypeError, ValueError): + return noise_shape + + if x.shape.dims is not None and len(x.shape.dims) == len(noise_shape_.dims): + new_dims = [] + for i, dim in enumerate(x.shape.dims): + if noise_shape_.dims[i].value is None and dim.value is not None: + new_dims.append(dim.value) + else: + new_dims.append(noise_shape_.dims[i].value) + return tensor_shape.TensorShape(new_dims) + + return noise_shape + + +@tf_export(v1=["nn.dropout"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, "Please use `rate` instead of `keep_prob`. " + "Rate should be set to `rate = 1 - keep_prob`.", + "keep_prob") +def dropout(x, keep_prob=None, noise_shape=None, seed=None, name=None, + rate=None): + """Computes dropout. + + For each element of `x`, with probability `rate`, outputs `0`, and otherwise + scales up the input by `1 / (1-rate)`. The scaling is such that the expected + sum is unchanged. + + By default, each element is kept or dropped independently. If `noise_shape` + is specified, it must be + [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]` + will make independent decisions. For example, if `shape(x) = [k, l, m, n]` + and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be + kept independently and each row and column will be kept or not kept together. + + Args: + x: A floating point tensor. + keep_prob: (deprecated) A deprecated alias for `(1-rate)`. + noise_shape: A 1-D integer `Tensor`, representing the + shape for randomly generated keep/drop flags. + seed: A Python integer. Used to create random seeds. See + `tf.random.set_seed` for behavior. + name: A name for this operation (optional). + rate: A scalar `Tensor` with the same type as `x`. The probability that each + element of `x` is discarded. + + Returns: + A Tensor of the same shape of `x`. + + Raises: + ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating + point tensor. + """ + try: + rate_from_keep_prob = 1. - keep_prob if keep_prob is not None else None + except TypeError: + raise ValueError("`keep_prob` must be a floating point number or Tensor. " + f"Received: keep_prob={keep_prob}") + + rate = deprecation.deprecated_argument_lookup( + "rate", rate, + "keep_prob", rate_from_keep_prob) + + if rate is None: + raise ValueError(f"`rate` must be provided. Received: rate={rate}") + + return dropout_v2(x, rate, noise_shape=noise_shape, seed=seed, name=name) + + +@tf_export("nn.dropout", v1=[]) +@dispatch.add_dispatch_support +def dropout_v2(x, rate, noise_shape=None, seed=None, name=None): + """Computes dropout: randomly sets elements to zero to prevent overfitting. + + Warning: You should consider using + `tf.nn.experimental.stateless_dropout` instead of this function. The + difference between `tf.nn.experimental.stateless_dropout` and this + function is analogous to the difference between + `tf.random.stateless_uniform` and `tf.random.uniform`. Please see + [Random number + generation](https://www.tensorflow.org/guide/random_numbers) guide + for a detailed description of the various RNG systems in TF. As the + guide states, legacy stateful RNG ops like `tf.random.uniform` and + `tf.nn.dropout` are not deprecated yet but highly discouraged, + because their states are hard to control. + + Note: The behavior of dropout has changed between TensorFlow 1.x and 2.x. + When converting 1.x code, please use named arguments to ensure behavior stays + consistent. + + See also: `tf.keras.layers.Dropout` for a dropout layer. + + [Dropout](https://arxiv.org/abs/1207.0580) is useful for regularizing DNN + models. Inputs elements are randomly set to zero (and the other elements are + rescaled). This encourages each node to be independently useful, as it cannot + rely on the output of other nodes. + + More precisely: With probability `rate` elements of `x` are set to `0`. + The remaining elements are scaled up by `1.0 / (1 - rate)`, so that the + expected value is preserved. + + >>> tf.random.set_seed(0) + >>> x = tf.ones([3,5]) + >>> tf.nn.dropout(x, rate = 0.5, seed = 1).numpy() + array([[2., 0., 0., 2., 2.], + [2., 2., 2., 2., 2.], + [2., 0., 2., 0., 2.]], dtype=float32) + + >>> tf.random.set_seed(0) + >>> x = tf.ones([3,5]) + >>> tf.nn.dropout(x, rate = 0.8, seed = 1).numpy() + array([[0., 0., 0., 5., 5.], + [0., 5., 0., 5., 0.], + [5., 0., 5., 0., 5.]], dtype=float32) + + >>> tf.nn.dropout(x, rate = 0.0) == x + + + + By default, each element is kept or dropped independently. If `noise_shape` + is specified, it must be + [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]` + will make independent decisions. This is useful for dropping whole + channels from an image or sequence. For example: + + >>> tf.random.set_seed(0) + >>> x = tf.ones([3,10]) + >>> tf.nn.dropout(x, rate = 2/3, noise_shape=[1,10], seed=1).numpy() + array([[0., 0., 0., 3., 3., 0., 3., 3., 3., 0.], + [0., 0., 0., 3., 3., 0., 3., 3., 3., 0.], + [0., 0., 0., 3., 3., 0., 3., 3., 3., 0.]], dtype=float32) + + Args: + x: A floating point tensor. + rate: A scalar `Tensor` with the same type as x. The probability + that each element is dropped. For example, setting rate=0.1 would drop + 10% of input elements. + noise_shape: A 1-D integer `Tensor`, representing the + shape for randomly generated keep/drop flags. + seed: A Python integer. Used to create random seeds. See + `tf.random.set_seed` for behavior. + name: A name for this operation (optional). + + Returns: + A Tensor of the same shape of `x`. + + Raises: + ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point + tensor. `rate=1` is disallowed, because the output would be all zeros, + which is likely not what was intended. + """ + uniform_sampler = functools.partial(random_ops.random_uniform, seed=seed) + def dummy_rng_step(): + random_seed.get_seed(seed) + return _dropout(x=x, rate=rate, noise_shape=noise_shape, + uniform_sampler=uniform_sampler, + dummy_rng_step=dummy_rng_step, name=name, + default_name="dropout") + + +@tf_export("nn.experimental.stateless_dropout") +@dispatch.add_dispatch_support +def stateless_dropout(x, rate, seed, rng_alg=None, noise_shape=None, name=None): + """Computes dropout: randomly sets elements to zero to prevent overfitting. + + [Dropout](https://arxiv.org/abs/1207.0580) is useful for regularizing DNN + models. Inputs elements are randomly set to zero (and the other elements are + rescaled). This encourages each node to be independently useful, as it cannot + rely on the output of other nodes. + + More precisely: With probability `rate` elements of `x` are set to `0`. + The remaining elements are scaled up by `1.0 / (1 - rate)`, so that the + expected value is preserved. + + >>> x = tf.ones([3,5]) + >>> tf.nn.experimental.stateless_dropout(x, rate=0.5, seed=[1, 0]) + + + >>> x = tf.ones([3,5]) + >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0]) + + + >>> tf.nn.experimental.stateless_dropout(x, rate=0.0, seed=[1, 0]) == x + + + + This function is a stateless version of `tf.nn.dropout`, in the + sense that no matter how many times you call this function, the same + `seed` will lead to the same results, and different `seed` will lead + to different results. + + >>> x = tf.ones([3,5]) + >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0]) + + >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[1, 0]) + + >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[2, 0]) + + >>> tf.nn.experimental.stateless_dropout(x, rate=0.8, seed=[2, 0]) + + + Compare the above results to those of `tf.nn.dropout` below. The + second time `tf.nn.dropout` is called with the same seed, it will + give a different output. + + >>> tf.random.set_seed(0) + >>> x = tf.ones([3,5]) + >>> tf.nn.dropout(x, rate=0.8, seed=1) + + >>> tf.nn.dropout(x, rate=0.8, seed=1) + + >>> tf.nn.dropout(x, rate=0.8, seed=2) + + >>> tf.nn.dropout(x, rate=0.8, seed=2) + + + The difference between this function and `tf.nn.dropout` is + analogous to the difference between `tf.random.stateless_uniform` + and `tf.random.uniform`. Please see [Random number + generation](https://www.tensorflow.org/guide/random_numbers) guide + for a detailed description of the various RNG systems in TF. As the + guide states, legacy stateful RNG ops like `tf.random.uniform` and + `tf.nn.dropout` are not deprecated yet but highly discouraged, + because their states are hard to control. + + By default, each element is kept or dropped independently. If `noise_shape` + is specified, it must be + [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]` + will make independent decisions. This is useful for dropping whole + channels from an image or sequence. For example: + + >>> x = tf.ones([3,10]) + >>> tf.nn.experimental.stateless_dropout(x, rate=2/3, noise_shape=[1,10], + ... seed=[1, 0]) + + + Args: + x: A floating point tensor. + rate: A scalar `Tensor` with the same type as x. The probability + that each element is dropped. For example, setting rate=0.1 would drop + 10% of input elements. + seed: An integer tensor of shape `[2]`. The seed of the random numbers. + rng_alg: The algorithm used to generate the random numbers + (default to `"auto_select"`). See the `alg` argument of + `tf.random.stateless_uniform` for the supported values. + noise_shape: A 1-D integer `Tensor`, representing the + shape for randomly generated keep/drop flags. + name: A name for this operation. + + Returns: + A Tensor of the same shape and dtype of `x`. + + Raises: + ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point + tensor. `rate=1` is disallowed, because the output would be all zeros, + which is likely not what was intended. + """ + uniform_sampler = functools.partial( + stateless_random_ops.stateless_random_uniform, seed=seed, alg=rng_alg) + def dummy_rng_step(): + pass + return _dropout(x=x, rate=rate, noise_shape=noise_shape, + uniform_sampler=uniform_sampler, + dummy_rng_step=dummy_rng_step, name=name, + default_name="stateless_dropout") + + +@tf_export("nn.experimental.general_dropout") +@dispatch.add_dispatch_support +def general_dropout(x, rate, uniform_sampler, noise_shape=None, name=None): + """Computes dropout: randomly sets elements to zero to prevent overfitting. + + Please see `tf.nn.experimental.stateless_dropout` for an overview + of dropout. + + Unlike `tf.nn.experimental.stateless_dropout`, here you can supply a + custom sampler function `uniform_sampler` that (given a shape and a + dtype) generates a random, `Uniform[0, 1)`-distributed tensor (of + that shape and dtype). `uniform_sampler` can be + e.g. `tf.random.stateless_random_uniform` or + `tf.random.Generator.uniform`. + + For example, if you are using `tf.random.Generator` to generate + random numbers, you can use this code to do dropouts: + + >>> g = tf.random.Generator.from_seed(7) + >>> sampler = g.uniform + >>> x = tf.constant([1.1, 2.2, 3.3, 4.4, 5.5]) + >>> rate = 0.5 + >>> tf.nn.experimental.general_dropout(x, rate, sampler) + + >>> tf.nn.experimental.general_dropout(x, rate, sampler) + + + It has better performance than using + `tf.nn.experimental.stateless_dropout` and + `tf.random.Generator.make_seeds`: + + >>> g = tf.random.Generator.from_seed(7) + >>> x = tf.constant([1.1, 2.2, 3.3, 4.4, 5.5]) + >>> rate = 0.5 + >>> tf.nn.experimental.stateless_dropout(x, rate, g.make_seeds(1)[:, 0]) + + >>> tf.nn.experimental.stateless_dropout(x, rate, g.make_seeds(1)[:, 0]) + + + because generating and consuming seeds cost extra + computation. `tf.nn.experimental.general_dropout` can let you avoid + them. + + Args: + x: A floating point tensor. + rate: A scalar `Tensor` with the same type as x. The probability + that each element is dropped. For example, setting rate=0.1 would drop + 10% of input elements. + uniform_sampler: a callable of signature `(shape, dtype) -> + Tensor[shape, dtype]`, used to generate a tensor of uniformly-distributed + random numbers in the range `[0, 1)`, of the given shape and dtype. + noise_shape: A 1-D integer `Tensor`, representing the + shape for randomly generated keep/drop flags. + name: A name for this operation. + + Returns: + A Tensor of the same shape and dtype of `x`. + + Raises: + ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating point + tensor. `rate=1` is disallowed, because the output would be all zeros, + which is likely not what was intended. + """ + def dummy_rng_step(): + pass + return _dropout(x=x, rate=rate, noise_shape=noise_shape, + uniform_sampler=uniform_sampler, + dummy_rng_step=dummy_rng_step, name=name, + default_name="general_dropout") + + +def _dropout(x, rate, noise_shape, uniform_sampler, dummy_rng_step, name, + default_name): + """Shared implementation of the various dropout functions. + + Args: + x: same as the namesake in `dropout_v2`. + rate: same as the namesake in `dropout_v2`. + noise_shape: same as the namesake in `dropout_v2`. + uniform_sampler: a callable of signature `(shape, dtype) -> + Tensor`, used to generate a tensor of uniformly-distributed + random numbers in the range `[0, 1)`, of the given shape and dtype. + dummy_rng_step: a callable of signature `() -> None`, to make a + dummy RNG call in the fast path. In the fast path where rate is + 0, we don't need to generate random numbers, but some samplers + still require you to make an RNG call, to make sure that RNG + states won't depend on whether the fast path is taken. + name: same as the namesake in `dropout_v2`. + default_name: a default name in case `name` is `None`. + + Returns: + A Tensor of the same shape and dtype of `x`. + """ + with ops.name_scope(name, default_name, [x]) as name: + is_rate_number = isinstance(rate, numbers.Real) + if is_rate_number and (rate < 0 or rate >= 1): + raise ValueError("`rate` must be a scalar tensor or a float in the " + f"range [0, 1). Received: rate={rate}") + x = ops.convert_to_tensor(x, name="x") + x_dtype = x.dtype + if not x_dtype.is_floating: + raise ValueError( + "`x.dtype` must be a floating point tensor as `x` will be " + f"scaled. Received: x_dtype={x_dtype}") + if is_rate_number and rate == 0: + # Fast-path: Return the input immediately if rate is non-tensor & is `0`. + # We trigger this after all error checking + # and after `x` has been converted to a tensor, to prevent inconsistent + # tensor conversions/error raising if rate is changed to/from 0. + # + # We also explicitly call `dummy_rng_step` to make sure + # we don't change the random number generation behavior of + # stateful random ops by entering a fastpath, + # despite not generating a random tensor in the fastpath + dummy_rng_step() + return x + + is_executing_eagerly = context.executing_eagerly() + if not tensor_util.is_tf_type(rate): + if is_rate_number: + keep_prob = 1 - rate + scale = 1 / keep_prob + scale = ops.convert_to_tensor(scale, dtype=x_dtype) + ret = gen_math_ops.mul(x, scale) + else: + raise ValueError( + f"`rate` must be a scalar or scalar tensor. Received: rate={rate}") + else: + rate.get_shape().assert_has_rank(0) + rate_dtype = rate.dtype + if rate_dtype != x_dtype: + if not rate_dtype.is_compatible_with(x_dtype): + raise ValueError( + "`x.dtype` must be compatible with `rate.dtype`. " + f"Received: x.dtype={x_dtype} and rate.dtype={rate_dtype}") + rate = gen_math_ops.cast(rate, x_dtype, name="rate") + one_tensor = constant_op.constant(1, dtype=x_dtype) + ret = gen_math_ops.real_div(x, gen_math_ops.sub(one_tensor, rate)) + + noise_shape = _get_noise_shape(x, noise_shape) + # Sample a uniform distribution on [0.0, 1.0) and select values larger + # than or equal to `rate`. + random_tensor = uniform_sampler(shape=noise_shape, dtype=x_dtype) + keep_mask = random_tensor >= rate + zero_tensor = constant_op.constant(0, dtype=x_dtype) + ret = array_ops.where_v2(keep_mask, ret, zero_tensor) + if not is_executing_eagerly: + ret.set_shape(x.get_shape()) + return ret + + +@tf_export("math.top_k", "nn.top_k") +@dispatch.add_dispatch_support +def top_k(input, k=1, sorted=True, index_type=dtypes.int32, name=None): # pylint: disable=redefined-builtin + """Finds values and indices of the `k` largest entries for the last dimension. + + If the input is a vector (rank=1), finds the `k` largest entries in the vector + and outputs their values and indices as vectors. Thus `values[j]` is the + `j`-th largest entry in `input`, and its index is `indices[j]`. + + >>> result = tf.math.top_k([1, 2, 98, 1, 1, 99, 3, 1, 3, 96, 4, 1], + ... k=3) + >>> result.values.numpy() + array([99, 98, 96], dtype=int32) + >>> result.indices.numpy() + array([5, 2, 9], dtype=int32) + + For matrices (resp. higher rank input), computes the top `k` entries in each + row (resp. vector along the last dimension). Thus, + + >>> input = tf.random.normal(shape=(3,4,5,6)) + >>> k = 2 + >>> values, indices = tf.math.top_k(input, k=k) + >>> values.shape.as_list() + [3, 4, 5, 2] + >>> + >>> values.shape == indices.shape == input.shape[:-1] + [k] + True + + The indices can be used to `gather` from a tensor who's shape matches `input`. + + >>> gathered_values = tf.gather(input, indices, batch_dims=-1) + >>> assert tf.reduce_all(gathered_values == values) + + If two elements are equal, the lower-index element appears first. + + >>> result = tf.math.top_k([1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0], + ... k=3) + >>> result.indices.numpy() + array([0, 1, 3], dtype=int32) + + By default, indices are returned as type `int32`, however, this can be changed + by specifying the `index_type`. + + >>> result = tf.math.top_k([1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0], + ... k=3, index_type=tf.int16) + >>> result.indices.numpy() + array([0, 1, 3], dtype=int16) + + Args: + input: 1-D or higher `Tensor` with last dimension at least `k`. + k: 0-D `Tensor` of type `int16`, `int32` or `int64`. Number of top element + to look for along the last dimension (along each row for matrices). + sorted: If true the resulting `k` elements will be sorted by the values in + descending order. + index_type: Optional dtype for output indices. + name: Optional name for the operation. + + Returns: + A tuple with two named fields: + values: The `k` largest elements along each last dimensional slice. + indices: The indices of `values` within the last dimension of `input`. + """ + return gen_nn_ops.top_kv2( + input, k=k, sorted=sorted, index_type=index_type, name=name + ) + + +@tf_export("math.approx_max_k", "nn.approx_max_k") +@dispatch.add_dispatch_support +def approx_max_k(operand, + k, + reduction_dimension=-1, + recall_target=0.95, + reduction_input_size_override=-1, + aggregate_to_topk=True, + name=None): + """Returns max `k` values and their indices of the input `operand` in an approximate manner. + + See https://arxiv.org/abs/2206.14286 for the algorithm details. This op is + only optimized on TPU currently. + + Args: + operand : Array to search for max-k. Must be a floating number type. + k : Specifies the number of max-k. + reduction_dimension : Integer dimension along which to search. Default: -1. + recall_target : Recall target for the approximation. + reduction_input_size_override : When set to a positive value, it overrides + the size determined by `operand[reduction_dim]` for evaluating the recall. + This option is useful when the given `operand` is only a subset of the + overall computation in SPMD or distributed pipelines, where the true input + size cannot be deferred by the `operand` shape. + aggregate_to_topk : When true, aggregates approximate results to top-k. When + false, returns the approximate results. The number of the approximate + results is implementation defined and is greater equals to the specified + `k`. + name: Optional name for the operation. + + Returns: + Tuple of two arrays. The arrays are the max `k` values and the + corresponding indices along the `reduction_dimension` of the input + `operand`. The arrays' dimensions are the same as the input `operand` + except for the `reduction_dimension`: when `aggregate_to_topk` is true, + the reduction dimension is `k`; otherwise, it is greater equals to `k` + where the size is implementation-defined. + + We encourage users to wrap `approx_max_k` with jit. See the following + example for maximal inner production search (MIPS): + + >>> import tensorflow as tf + >>> @tf.function(jit_compile=True) + ... def mips(qy, db, k=10, recall_target=0.95): + ... dists = tf.einsum('ik,jk->ij', qy, db) + ... # returns (f32[qy_size, k], i32[qy_size, k]) + ... return tf.nn.approx_max_k(dists, k=k, recall_target=recall_target) + >>> + >>> qy = tf.random.uniform((256,128)) + >>> db = tf.random.uniform((2048,128)) + >>> dot_products, neighbors = mips(qy, db, k=20) + """ + return gen_nn_ops.approx_top_k( + operand, + k=k, + reduction_dimension=reduction_dimension, + recall_target=recall_target, + is_max_k=True, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, + name=name) + + +@tf_export("math.approx_min_k", "nn.approx_min_k") +@dispatch.add_dispatch_support +def approx_min_k(operand, + k, + reduction_dimension=-1, + recall_target=0.95, + reduction_input_size_override=-1, + aggregate_to_topk=True, + name=None): + """Returns min `k` values and their indices of the input `operand` in an approximate manner. + + See https://arxiv.org/abs/2206.14286 for the algorithm details. This op is + only optimized on TPU currently. + + Args: + operand : Array to search for min-k. Must be a floating number type. + k : Specifies the number of min-k. + reduction_dimension: Integer dimension along which to search. Default: -1. + recall_target: Recall target for the approximation. + reduction_input_size_override : When set to a positive value, it overrides + the size determined by `operand[reduction_dim]` for evaluating the recall. + This option is useful when the given `operand` is only a subset of the + overall computation in SPMD or distributed pipelines, where the true input + size cannot be deferred by the `operand` shape. + aggregate_to_topk: When true, aggregates approximate results to top-k. When + false, returns the approximate results. The number of the approximate + results is implementation defined and is greater equals to the specified + `k`. + name: Optional name for the operation. + + Returns: + Tuple of two arrays. The arrays are the least `k` values and the + corresponding indices along the `reduction_dimension` of the input + `operand`. The arrays' dimensions are the same as the input `operand` + except for the `reduction_dimension`: when `aggregate_to_topk` is true, + the reduction dimension is `k`; otherwise, it is greater equals to `k` + where the size is implementation-defined. + + We encourage users to wrap `approx_min_k` with jit. See the following example + for nearest neighbor search over the squared l2 distance: + + >>> import tensorflow as tf + >>> @tf.function(jit_compile=True) + ... def l2_ann(qy, db, half_db_norms, k=10, recall_target=0.95): + ... dists = half_db_norms - tf.einsum('ik,jk->ij', qy, db) + ... return tf.nn.approx_min_k(dists, k=k, recall_target=recall_target) + >>> + >>> qy = tf.random.uniform((256,128)) + >>> db = tf.random.uniform((2048,128)) + >>> half_db_norms = tf.norm(db, axis=1) / 2 + >>> dists, neighbors = l2_ann(qy, db, half_db_norms) + + In the example above, we compute `db_norms/2 - dot(qy, db^T)` instead of + `qy^2 - 2 dot(qy, db^T) + db^2` for performance reason. The former uses less + arithmetics and produces the same set of neighbors. + """ + return gen_nn_ops.approx_top_k( + operand, + k=k, + reduction_dimension=reduction_dimension, + recall_target=recall_target, + is_max_k=False, + reduction_input_size_override=reduction_input_size_override, + aggregate_to_topk=aggregate_to_topk, + name=name) + + +def nth_element(input, n, reverse=False, name=None): # pylint: disable=redefined-builtin + r"""Finds values of the `n`-th smallest value for the last dimension. + + Note that n is zero-indexed. + + If the input is a vector (rank-1), finds the entries which is the nth-smallest + value in the vector and outputs their values as scalar tensor. + + For matrices (resp. higher rank input), computes the entries which is the + nth-smallest value in each row (resp. vector along the last dimension). Thus, + + values.shape = input.shape[:-1] + + Args: + input: 1-D or higher `Tensor` with last dimension at least `n+1`. + n: A `Tensor` of type `int32`. + 0-D. Position of sorted vector to select along the last dimension (along + each row for matrices). Valid range of n is `[0, input.shape[:-1])` + reverse: An optional `bool`. Defaults to `False`. + When set to True, find the nth-largest value in the vector and vice + versa. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + The `n`-th order statistic along each last dimensional slice. + """ + return gen_nn_ops.nth_element(input, n, reverse=reverse, name=name) + + +@tf_export(v1=["nn.fractional_max_pool"]) +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="`seed2` and `deterministic` " + "args are deprecated. Use fractional_max_pool_v2.") +def fractional_max_pool(value, + pooling_ratio, + pseudo_random=False, + overlapping=False, + deterministic=False, + seed=0, + seed2=0, + name=None): # pylint: disable=redefined-builtin + r"""Performs fractional max pooling on the input. + + This is a deprecated version of `fractional_max_pool`. + + Fractional max pooling is slightly different than regular max pooling. In + regular max pooling, you downsize an input set by taking the maximum value of + smaller N x N subsections of the set (often 2x2), and try to reduce the set by + a factor of N, where N is an integer. Fractional max pooling, as you might + expect from the word "fractional", means that the overall reduction ratio N + does not have to be an integer. + + The sizes of the pooling regions are generated randomly but are fairly + uniform. For example, let's look at the height dimension, and the constraints + on the list of rows that will be pool boundaries. + + First we define the following: + + 1. input_row_length : the number of rows from the input set + 2. output_row_length : which will be smaller than the input + 3. alpha = input_row_length / output_row_length : our reduction ratio + 4. K = floor(alpha) + 5. row_pooling_sequence : this is the result list of pool boundary rows + + Then, row_pooling_sequence should satisfy: + + 1. a[0] = 0 : the first value of the sequence is 0 + 2. a[end] = input_row_length : the last value of the sequence is the size + 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size + 4. length(row_pooling_sequence) = output_row_length+1 + + Args: + value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for + each dimension of `value`, currently only supports row and col dimension + and should be >= 1.0. For example, a valid pooling ratio looks like [1.0, + 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't + allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling + ratio on height and width dimensions respectively. + pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`, + generates the pooling sequence in a pseudorandom fashion, otherwise, in a + random fashion. Check (Graham, 2015) for difference between + pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. When set to `True`, + it means when pooling, the values at the boundary of adjacent pooling + cells are used by both cells. For example: + `index 0 1 2 3 4` + `value 20 5 16 3 7` + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used + twice. The result would be [20, 16] for fractional max pooling. + deterministic: An optional `bool`. Deprecated; use `fractional_max_pool_v2` + instead. + seed: An optional `int`. Defaults to `0`. If set to be non-zero, the + random number generator is seeded by the given seed. Otherwise it is + seeded by a random seed. + seed2: An optional `int`. Deprecated; use `fractional_max_pool_v2` instead. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, + `col_pooling_sequence`). + output: Output `Tensor` after fractional max pooling. Has the same type as + `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + + Raises: + ValueError: If op determinism is enabled and either the seeds are not set or + the "deterministic" argument is False. + + References: + Fractional Max-Pooling: + [Graham, 2015](https://arxiv.org/abs/1412.6071) + ([pdf](https://arxiv.org/pdf/1412.6071.pdf)) + """ + if config.is_op_determinism_enabled() and (not seed or not seed2 or + not deterministic): + raise ValueError( + f'tf.compat.v1.nn.fractional_max_pool requires "seed" and ' + f'"seed2" to be non-zero and "deterministic" to be true when op ' + f"determinism is enabled. Please pass in such values, e.g. by passing" + f'"seed=1, seed2=1, deterministic=True". Got: seed={seed}, ' + f'seed2={seed2}, deterministic={deterministic}') + return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic, seed, seed2, + name) + + +@tf_export("nn.fractional_max_pool", v1=[]) +@dispatch.add_dispatch_support +def fractional_max_pool_v2(value, + pooling_ratio, + pseudo_random=False, + overlapping=False, + seed=0, + name=None): # pylint: disable=redefined-builtin + r"""Performs fractional max pooling on the input. + + Fractional max pooling is slightly different than regular max pooling. In + regular max pooling, you downsize an input set by taking the maximum value of + smaller N x N subsections of the set (often 2x2), and try to reduce the set by + a factor of N, where N is an integer. Fractional max pooling, as you might + expect from the word "fractional", means that the overall reduction ratio N + does not have to be an integer. + + The sizes of the pooling regions are generated randomly but are fairly + uniform. For example, let's look at the height dimension, and the constraints + on the list of rows that will be pool boundaries. + + First we define the following: + + 1. input_row_length : the number of rows from the input set + 2. output_row_length : which will be smaller than the input + 3. alpha = input_row_length / output_row_length : our reduction ratio + 4. K = floor(alpha) + 5. row_pooling_sequence : this is the result list of pool boundary rows + + Then, row_pooling_sequence should satisfy: + + 1. a[0] = 0 : the first value of the sequence is 0 + 2. a[end] = input_row_length : the last value of the sequence is the size + 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size + 4. length(row_pooling_sequence) = output_row_length+1 + + Args: + value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: An int or list of `ints` that has length `1`, `2` or `4`. + Pooling ratio for each dimension of `value`, currently only supports row + and col dimension and should be >= 1.0. For example, a valid pooling ratio + looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements must be 1.0 + because we don't allow pooling on batch and channels dimensions. 1.44 and + 1.73 are pooling ratio on height and width dimensions respectively. + pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`, + generates the pooling sequence in a pseudorandom fashion, otherwise, in a + random fashion. Check paper (Graham, 2015) for difference between + pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. When set to `True`, + it means when pooling, the values at the boundary of adjacent pooling + cells are used by both cells. For example: + `index 0 1 2 3 4` + `value 20 5 16 3 7` + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used + twice. The result would be [20, 16] for fractional max pooling. + seed: An optional `int`. Defaults to `0`. If set to be non-zero, the + random number generator is seeded by the given seed. Otherwise it is + seeded by a random seed. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, + `col_pooling_sequence`). + output: Output `Tensor` after fractional max pooling. Has the same type as + `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + + Raises: + ValueError: If no seed is specified and op determinism is enabled. + + References: + Fractional Max-Pooling: + [Graham, 2015](https://arxiv.org/abs/1412.6071) + ([pdf](https://arxiv.org/pdf/1412.6071.pdf)) + """ + if (isinstance(pooling_ratio, (list, tuple))): + if (pooling_ratio[0] != 1.0 or pooling_ratio[-1] != 1.0): + raise ValueError( + "`pooling_ratio` should have first and last elements with value 1.0. " + f"Received: pooling_ratio={pooling_ratio}") + for element in pooling_ratio: + if element < 1.0: + raise ValueError( + f"`pooling_ratio` elements should be >= 1.0. " + f"Received: pooling_ratio={pooling_ratio}") + elif (isinstance(pooling_ratio, (int, float))): + if pooling_ratio < 1.0: + raise ValueError( + "`pooling_ratio` should be >= 1.0. " + f"Received: pooling_ratio={pooling_ratio}") + else: + raise ValueError( + "`pooling_ratio` should be an int or a list of ints. " + f"Received: pooling_ratio={pooling_ratio}") + + pooling_ratio = _get_sequence(pooling_ratio, 2, 3, "pooling_ratio") + + if seed == 0: + if config.is_op_determinism_enabled(): + raise ValueError( + f"tf.nn.fractional_max_pool requires a non-zero seed to be passed in " + f"when determinism is enabled, but got seed={seed}. Please pass in a " + f'non-zero seed, e.g. by passing "seed=1".') + return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic=False, + seed=0, seed2=0, name=name) + else: + seed1, seed2 = random_seed.get_seed(seed) + return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic=True, + seed=seed1, seed2=seed2, name=name) + + +@tf_export(v1=["nn.fractional_avg_pool"]) +@dispatch.add_dispatch_support +@deprecation.deprecated(date=None, instructions="`seed2` and `deterministic` " + "args are deprecated. Use fractional_avg_pool_v2.") +def fractional_avg_pool(value, + pooling_ratio, + pseudo_random=False, + overlapping=False, + deterministic=False, + seed=0, + seed2=0, + name=None): # pylint: disable=redefined-builtin + r"""Performs fractional average pooling on the input. + + This is a deprecated version of `fractional_avg_pool`. + + Fractional average pooling is similar to Fractional max pooling in the pooling + region generation step. The only difference is that after pooling regions are + generated, a mean operation is performed instead of a max operation in each + pooling region. + + Args: + value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for + each dimension of `value`, currently only supports row and col dimension + and should be >= 1.0. For example, a valid pooling ratio looks like [1.0, + 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't + allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling + ratio on height and width dimensions respectively. + pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`, + generates the pooling sequence in a pseudorandom fashion, otherwise, in a + random fashion. Check paper (Graham, 2015) for difference between + pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. When set to `True`, + it means when pooling, the values at the boundary of adjacent pooling + cells are used by both cells. For example: + `index 0 1 2 3 4` + `value 20 5 16 3 7` + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used + twice. The result would be [20, 16] for fractional avg pooling. + deterministic: An optional `bool`. Deprecated; use `fractional_avg_pool_v2` + instead. + seed: An optional `int`. Defaults to `0`. If set to be non-zero, the + random number generator is seeded by the given seed. Otherwise it is + seeded by a random seed. + seed2: An optional `int`. Deprecated; use `fractional_avg_pool_v2` instead. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, + `col_pooling_sequence`). + output: Output `Tensor` after fractional avg pooling. Has the same type as + `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + + References: + Fractional Max-Pooling: + [Graham, 2015](https://arxiv.org/abs/1412.6071) + ([pdf](https://arxiv.org/pdf/1412.6071.pdf)) + """ + return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic, seed, seed2, + name=name) + + +@tf_export("nn.fractional_avg_pool", v1=[]) +@dispatch.add_dispatch_support +def fractional_avg_pool_v2(value, + pooling_ratio, + pseudo_random=False, + overlapping=False, + seed=0, + name=None): # pylint: disable=redefined-builtin + r"""Performs fractional average pooling on the input. + + Fractional average pooling is similar to Fractional max pooling in the pooling + region generation step. The only difference is that after pooling regions are + generated, a mean operation is performed instead of a max operation in each + pooling region. + + Args: + value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`. + pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for + each dimension of `value`, currently only supports row and col dimension + and should be >= 1.0. For example, a valid pooling ratio looks like [1.0, + 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't + allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling + ratio on height and width dimensions respectively. + pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`, + generates the pooling sequence in a pseudorandom fashion, otherwise, in a + random fashion. Check paper (Graham, 2015) for difference between + pseudorandom and random. + overlapping: An optional `bool`. Defaults to `False`. When set to `True`, + it means when pooling, the values at the boundary of adjacent pooling + cells are used by both cells. For example: + `index 0 1 2 3 4` + `value 20 5 16 3 7` + If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used + twice. The result would be [20, 16] for fractional avg pooling. + seed: An optional `int`. Defaults to `0`. If set to be non-zero, the + random number generator is seeded by the given seed. Otherwise it is + seeded by a random seed. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, + `col_pooling_sequence`). + output: Output `Tensor` after fractional avg pooling. Has the same type as + `value`. + row_pooling_sequence: A `Tensor` of type `int64`. + col_pooling_sequence: A `Tensor` of type `int64`. + + References: + Fractional Max-Pooling: + [Graham, 2015](https://arxiv.org/abs/1412.6071) + ([pdf](https://arxiv.org/pdf/1412.6071.pdf)) + """ + if seed == 0: + return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic=False, + seed=0, seed2=0, name=name) + else: + seed1, seed2 = random_seed.get_seed(seed) + return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random, + overlapping, deterministic=True, + seed=seed1, seed2=seed2, name=name) + + +@ops.RegisterStatistics("Dilation2D", "flops") +def _calc_dilation2d_flops(graph, node): + """Calculates the compute resources needed for Dilation2D.""" + input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + input_shape.assert_is_fully_defined() + filter_shape = graph_util.tensor_shape_from_node_def_name( + graph, node.input[1]) + filter_shape.assert_is_fully_defined() + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + filter_height = int(filter_shape[0]) + filter_width = int(filter_shape[1]) + output_count = np.prod(output_shape.as_list(), dtype=np.int64) + return ops.OpStats("flops", (output_count * filter_height * filter_width * 2)) + + +@tf_export(v1=["nn.erosion2d"]) +@dispatch.add_dispatch_support +def erosion2d(value, kernel, strides, rates, padding, name=None): + """Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors. + + The `value` tensor has shape `[batch, in_height, in_width, depth]` and the + `kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e., + each input channel is processed independently of the others with its own + structuring function. The `output` tensor has shape + `[batch, out_height, out_width, depth]`. The spatial dimensions of the + output tensor depend on the `padding` algorithm. We currently only support the + default "NHWC" `data_format`. + + In detail, the grayscale morphological 2-D erosion is given by: + + output[b, y, x, c] = + min_{dy, dx} value[b, + strides[1] * y - rates[1] * dy, + strides[2] * x - rates[2] * dx, + c] - + kernel[dy, dx, c] + + Duality: The erosion of `value` by the `kernel` is equal to the negation of + the dilation of `-value` by the reflected `kernel`. + + Args: + value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`. + kernel: A `Tensor`. Must have the same type as `value`. + 3-D with shape `[kernel_height, kernel_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + 1-D of length 4. The stride of the sliding window for each dimension of + the input tensor. Must be: `[1, stride_height, stride_width, 1]`. + rates: A list of `ints` that has length `>= 4`. + 1-D of length 4. The input stride for atrous morphological dilation. + Must be: `[1, rate_height, rate_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. + name: A name for the operation (optional). If not specified "erosion2d" + is used. + + Returns: + A `Tensor`. Has the same type as `value`. + 4-D with shape `[batch, out_height, out_width, depth]`. + Raises: + ValueError: If the `value` depth does not match `kernel`' shape, or if + padding is other than `'VALID'` or `'SAME'`. + """ + with ops.name_scope(name, "erosion2d", [value, kernel]) as name: + # Reduce erosion to dilation by duality. + return math_ops.negative( + gen_nn_ops.dilation2d( + input=math_ops.negative(value), + filter=array_ops.reverse_v2(kernel, [0, 1]), + strides=strides, + rates=rates, + padding=padding, + name=name)) + + +@tf_export("nn.erosion2d", v1=[]) +@dispatch.add_dispatch_support +def erosion2d_v2(value, + filters, + strides, + padding, + data_format, + dilations, + name=None): + """Computes the grayscale erosion of 4-D `value` and 3-D `filters` tensors. + + The `value` tensor has shape `[batch, in_height, in_width, depth]` and the + `filters` tensor has shape `[filters_height, filters_width, depth]`, i.e., + each input channel is processed independently of the others with its own + structuring function. The `output` tensor has shape + `[batch, out_height, out_width, depth]`. The spatial dimensions of the + output tensor depend on the `padding` algorithm. We currently only support the + default "NHWC" `data_format`. + + In detail, the grayscale morphological 2-D erosion is given by: + + output[b, y, x, c] = + min_{dy, dx} value[b, + strides[1] * y - dilations[1] * dy, + strides[2] * x - dilations[2] * dx, + c] - + filters[dy, dx, c] + + Duality: The erosion of `value` by the `filters` is equal to the negation of + the dilation of `-value` by the reflected `filters`. + + Args: + value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`. + filters: A `Tensor`. Must have the same type as `value`. + 3-D with shape `[filters_height, filters_width, depth]`. + strides: A list of `ints` that has length `>= 4`. + 1-D of length 4. The stride of the sliding window for each dimension of + the input tensor. Must be: `[1, stride_height, stride_width, 1]`. + padding: A `string` from: `"SAME", "VALID"`. + The type of padding algorithm to use. See + [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) + for more information. + data_format: A `string`, only `"NHWC"` is currently supported. + dilations: A list of `ints` that has length `>= 4`. + 1-D of length 4. The input stride for atrous morphological dilation. + Must be: `[1, rate_height, rate_width, 1]`. + name: A name for the operation (optional). If not specified "erosion2d" + is used. + + Returns: + A `Tensor`. Has the same type as `value`. + 4-D with shape `[batch, out_height, out_width, depth]`. + + Raises: + ValueError: If the `value` depth does not match `filters`' shape, or if + padding is other than `'VALID'` or `'SAME'`. + """ + if data_format != "NHWC": + raise ValueError("`data_format` values other than 'NHWC' are not " + f"supported. Received: data_format={data_format}") + + with ops.name_scope(name, "erosion2d", [value, filters]) as name: + # Reduce erosion to dilation by duality. + return math_ops.negative( + gen_nn_ops.dilation2d( + input=math_ops.negative(value), + filter=array_ops.reverse_v2(filters, [0, 1]), + strides=strides, + rates=dilations, + padding=padding, + name=name)) + + +@tf_export(v1=["math.in_top_k", "nn.in_top_k"]) +@dispatch.add_dispatch_support +def in_top_k(predictions, targets, k, name=None): + r"""Says whether the targets are in the top `K` predictions. + + This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the + prediction for the target class is finite (not inf, -inf, or nan) and among + the top `k` predictions among all predictions for example `i`. Note that the + behavior of `InTopK` differs from the `TopK` op in its handling of ties; if + multiple classes have the same prediction value and straddle the top-`k` + boundary, all of those classes are considered to be in the top `k`. + + More formally, let + + \\(predictions_i\\) be the predictions for all classes for example `i`, + \\(targets_i\\) be the target class for example `i`, + \\(out_i\\) be the output for example `i`, + + $$out_i = predictions_{i, targets_i} \in TopKIncludingTies(predictions_i)$$ + + Args: + predictions: A `Tensor` of type `float32`. + A `batch_size` x `classes` tensor. + targets: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A `batch_size` vector of class ids. + k: An `int`. Number of top elements to look at for computing precision. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. Computed Precision at `k` as a `bool Tensor`. + """ + with ops.name_scope(name, "in_top_k"): + return gen_nn_ops.in_top_kv2(predictions, targets, k, name=name) + + +@tf_export("math.in_top_k", "nn.in_top_k", v1=[]) +@dispatch.add_dispatch_support +def in_top_k_v2(targets, predictions, k, name=None): + """Outputs whether the targets are in the top `K` predictions. + + This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the + prediction for the target class is finite (not inf, -inf, or nan) and among + the top `k` predictions among all predictions for example `i`. + `predictions` does not have to be normalized. + + Note that the behavior of `InTopK` differs from the `TopK` op in its handling + of ties; if multiple classes have the same prediction value and straddle the + top-`k` boundary, all of those classes are considered to be in the top `k`. + + >>> target = tf.constant([0, 1, 3]) + >>> pred = tf.constant([ + ... [1.2, -0.3, 2.8, 5.2], + ... [0.1, 0.0, 0.0, 0.0], + ... [0.0, 0.5, 0.3, 0.3]], + ... dtype=tf.float32) + >>> print(tf.math.in_top_k(target, pred, 2)) + tf.Tensor([False True True], shape=(3,), dtype=bool) + + Args: + targets: A `batch_size` vector of class ids. Must be `int32` or `int64`. + predictions: A `batch_size` x `classes` tensor of type `float32`. + k: An `int`. The parameter to specify search space. + name: A name for the operation (optional). + + Returns: + A `Tensor` with the same shape of `targets` with type of `bool`. Each + element specifies if the target falls into top-k predictions. + """ + return in_top_k(predictions, targets, k, name) + + +quantized_avg_pool = tf_export(v1=["nn.quantized_avg_pool"])( + dispatch.add_dispatch_support(gen_nn_ops.quantized_avg_pool) +) +quantized_conv2d = tf_export(v1=["nn.quantized_conv2d"])( + dispatch.add_dispatch_support(gen_nn_ops.quantized_conv2d) +) +quantized_relu_x = tf_export(v1=["nn.quantized_relu_x"])( + dispatch.add_dispatch_support(gen_nn_ops.quantized_relu_x) +) +quantized_max_pool = tf_export(v1=["nn.quantized_max_pool"])( + dispatch.add_dispatch_support(gen_nn_ops.quantized_max_pool) +) + + +@tf_export("nn.isotonic_regression", v1=[]) +@dispatch.add_dispatch_support +def isotonic_regression(inputs, decreasing=True, axis=-1): + r"""Solves isotonic regression problems along the given axis. + + For each vector x, the problem solved is + + $$\argmin_{y_1 >= y_2 >= ... >= y_n} \sum_i (x_i - y_i)^2.$$ + + As the solution is component-wise constant, a second tensor is returned that + encodes the segments. The problems are solved over the given axis. + + Consider the following example, where we solve a batch of two problems. The + first input is [3, 1, 2], while the second [1, 3, 4] (as the axis is 1). + >>> x = tf.constant([[3, 1, 2], [1, 3, 4]], dtype=tf.float32) + >>> y, segments = tf.nn.isotonic_regression(x, axis=1) + >>> y # The solution. + + + Note that the first solution has two blocks [2] and [1.5, 1.5]. The second + solution is constant, and thus has a single segment. These segments are + exactly what the second returned tensor encodes: + + >>> segments + + + + Args: + inputs: A tensor holding the inputs. + decreasing: If set to False, the inequalities in the optimizing constrained + are flipped. + axis: The axis along which the problems should be solved. + + Returns: + output: The solutions, same shape as type as the input. + segments: An int32 tensor, same shape as the input indicating the segments + that have the same value. Specifically, those positions that have the same + value correspond to the same segment. These values start at zero, and are + monotonously increasing for each solution. + """ + type_promotions = { + # Float types get mapped to themselves, int8/16 to float32, rest to double + dtypes.float32: + dtypes.float32, + dtypes.half: + dtypes.half, + dtypes.bfloat16: + dtypes.bfloat16, + dtypes.int8: + dtypes.float32, + dtypes.int16: + dtypes.float32, + } + inputs = ops.convert_to_tensor(inputs) + try: + output_dtype = type_promotions[inputs.dtype] + except KeyError: + output_dtype = dtypes.float64 + + def compute_on_matrix(matrix, name=None): + iso_fn = functools.partial( + gen_nn_ops.isotonic_regression, output_dtype=output_dtype, name=name) + if decreasing: + return iso_fn(matrix) + else: + output, segments = iso_fn(-matrix) + return -output, segments + + return _wrap_2d_function(inputs, compute_on_matrix, axis) + + +# Register elementwise ops that don't have Python wrappers. +# Unary elementwise ops. +dispatch.register_unary_elementwise_api(gen_nn_ops.elu) +dispatch.register_unary_elementwise_api(gen_nn_ops.relu) +dispatch.register_unary_elementwise_api(gen_nn_ops.selu) +dispatch.register_unary_elementwise_api(gen_nn_ops.softsign) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numerics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numerics.py new file mode 100644 index 0000000000000000000000000000000000000000..f64f177e710cb27d7f25fc98361a1de1c8356255 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numerics.py @@ -0,0 +1,131 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Connects all half, float and double tensors to CheckNumericsOp.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["debugging.assert_all_finite", "verify_tensor_all_finite"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("verify_tensor_all_finite") +def verify_tensor_all_finite(t=None, msg=None, name=None, x=None, message=None): + """Assert that the tensor does not contain any NaN's or Inf's. + + Args: + t: Tensor to check. + msg: Message to log on failure. + name: A name for this operation (optional). + x: Alias for t. + message: Alias for msg. + + Returns: + Same tensor as `t`. + """ + x = deprecation.deprecated_argument_lookup("x", x, "t", t) + message = deprecation.deprecated_argument_lookup( + "message", message, "msg", msg) + return verify_tensor_all_finite_v2(x, message, name) + + +@tf_export("debugging.assert_all_finite", v1=[]) +@dispatch.add_dispatch_support +def verify_tensor_all_finite_v2(x, message, name=None): + """Assert that the tensor does not contain any NaN's or Inf's. + + >>> @tf.function + ... def f(x): + ... x = tf.debugging.assert_all_finite(x, 'Input x must be all finite') + ... return x + 1 + + >>> f(tf.constant([np.inf, 1, 2])) + Traceback (most recent call last): + ... + InvalidArgumentError: ... + + Args: + x: Tensor to check. + message: Message to log on failure. + name: A name for this operation (optional). + + Returns: + Same tensor as `x`. + """ + with ops.name_scope(name, "VerifyFinite", [x]) as name: + x = ops.convert_to_tensor(x, name="x") + with ops.colocate_with(x): + verify_input = array_ops.check_numerics(x, message=message) + out = control_flow_ops.with_dependencies([verify_input], x) + return out + + +@tf_export(v1=["add_check_numerics_ops"]) +def add_check_numerics_ops(): + """Connect a `tf.debugging.check_numerics` to every floating point tensor. + + `check_numerics` operations themselves are added for each `half`, `float`, + or `double` tensor in the current default graph. For all ops in the graph, the + `check_numerics` op for all of its (`half`, `float`, or `double`) inputs + is guaranteed to run before the `check_numerics` op on any of its outputs. + + Note: This API is not compatible with the use of `tf.cond` or + `tf.while_loop`, and will raise a `ValueError` if you attempt to call it + in such a graph. + + Returns: + A `group` op depending on all `check_numerics` ops added. + + Raises: + ValueError: If the graph contains any numeric operations in a control flow + structure. + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + Not compatible with eager execution. To check for `Inf`s and `NaN`s under + eager execution, call `tf.debugging.enable_check_numerics()` once before + executing the checked operations. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError( + "add_check_numerics_ops() is not compatible with eager execution. " + "To check for Inf's and NaN's under eager execution, call " + "tf.debugging.enable_check_numerics() once before executing the " + "checked operations.") + + check_op = [] + # This code relies on the ordering of ops in get_operations(). + # The producer of a tensor always comes before that tensor's consumer in + # this list. This is true because get_operations() returns ops in the order + # added, and an op can only be added after its inputs are added. + for op in ops.get_default_graph().get_operations(): + for output in op.outputs: + if output.dtype in [dtypes.float16, dtypes.float32, dtypes.float64]: + if op._get_control_flow_context() is not None: # pylint: disable=protected-access + raise ValueError("`tf.add_check_numerics_ops() is not compatible " + "with TensorFlow control flow operations such as " + "`tf.cond()` or `tf.while_loop()`.") + + message = op.name + ":" + str(output.value_index) + with ops.control_dependencies(check_op): + check_op = [array_ops.check_numerics(output, message=message)] + return control_flow_ops.group(*check_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15191f3b9341efd435a3c00d86d21d9fd1fba434 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/__init__.py @@ -0,0 +1,171 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""# tf.experimental.numpy: NumPy API on TensorFlow. + +This module provides a subset of NumPy API, built on top of TensorFlow +operations. APIs are based on and have been tested with NumPy 1.16 version. + +The set of supported APIs may be expanded over time. Also future releases may +change the baseline version of NumPy API being supported. A list of some +systematic differences with NumPy is listed later in the "Differences with +NumPy" section. + +## Getting Started + +Please also see [TensorFlow NumPy Guide]( +https://www.tensorflow.org/guide/tf_numpy). + +In the code snippets below, we will assume that `tf.experimental.numpy` is +imported as `tnp` and NumPy is imported as `np` + +```python +print(tnp.ones([2,1]) + np.ones([1, 2])) +``` + +## Types + +The module provides an `ndarray` class which wraps an immutable `tf.Tensor`. +Additional functions are provided which accept array-like objects. Here +array-like objects include `ndarrays` as defined by this module, as well as +`tf.Tensor`, in addition to types accepted by NumPy. + +A subset of NumPy dtypes are supported. Type promotion* follows NumPy +semantics. + +**Note**: A new type promotion that offers a lot of advantages over the old +type promotion is now available. Learn more about enabling the new +type promotion +[here](https://www.tensorflow.org/guide/tf_numpy_type_promotion). + +```python +print(tnp.ones([1, 2], dtype=tnp.int16) + tnp.ones([2, 1], dtype=tnp.uint8)) +``` + +## Array Interface + +The `ndarray` class implements the `__array__` interface. This should allow +these objects to be passed into contexts that expect a NumPy or array-like +object (e.g. matplotlib). + +```python +np.sum(tnp.ones([1, 2]) + np.ones([2, 1])) +``` + + +## TF Interoperability + +The TF-NumPy API calls can be interleaved with TensorFlow calls +without incurring Tensor data copies. This is true even if the `ndarray` or +`tf.Tensor` is placed on a non-CPU device. + +In general, the expected behavior should be on par with that of code involving +`tf.Tensor` and running stateless TensorFlow functions on them. + +```python +tnp.sum(tnp.ones([1, 2]) + tf.ones([2, 1])) +``` + +Note that the `__array_priority__` is currently chosen to be lower than +`tf.Tensor`. Hence the `+` operator above returns a `tf.Tensor`. + +Additional examples of interoperability include: + +* using `with tf.GradientTape()` scope to compute gradients through the + TF-NumPy API calls. +* using `tf.distribution.Strategy` scope for distributed execution +* using `tf.vectorized_map()` for speeding up code using auto-vectorization + + + +## Device Support + +Given that `ndarray` and functions wrap TensorFlow constructs, the code will +have GPU and TPU support on par with TensorFlow. Device placement can be +controlled by using `with tf.device` scopes. Note that these devices could +be local or remote. + +```python +with tf.device("GPU:0"): + x = tnp.ones([1, 2]) +print(tf.convert_to_tensor(x).device) +``` + +## Graph and Eager Modes + +Eager mode execution should typically match NumPy semantics of executing +op-by-op. However the same code can be executed in graph mode, by putting it +inside a `tf.function`. The function body can contain NumPy code, and the inputs +can be `ndarray` as well. + +```python +@tf.function +def f(x, y): + return tnp.sum(x + y) + +f(tnp.ones([1, 2]), tf.ones([2, 1])) +``` +Python control flow based on `ndarray` values will be translated by +[autograph](https://www.tensorflow.org/code/tensorflow/python/autograph/g3doc/reference/index.md) +into `tf.cond` and `tf.while_loop` constructs. The code can be XLA compiled +for further optimizations. + +However, note that graph mode execution can change behavior of certain +operations since symbolic execution may not have information that is computed +during runtime. Some differences are: + +* Shapes can be incomplete or unknown in graph mode. This means that + `ndarray.shape`, `ndarray.size` and `ndarray.ndim` can return `ndarray` + objects instead of returning integer (or tuple of integer) values. +* `__len__`, `__iter__` and `__index__` properties of `ndarray` + may similarly not be supported in graph mode. Code using these + may need to change to explicit shape operations or control flow + constructs. +* Also note the [autograph limitations]( +https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md). + + +## Mutation and Variables + +`ndarrays` currently wrap immutable `tf.Tensor`. Hence mutation +operations like slice assigns are not supported. This may change in the future. +Note however that one can directly construct a `tf.Variable` and use that with +the TF-NumPy APIs. + +```python +tf_var = tf.Variable(2.0) +tf_var.assign_add(tnp.square(tf_var)) +``` + +## Differences with NumPy + +Here is a non-exhaustive list of differences: + +* Not all dtypes are currently supported. e.g. `np.float96`, `np.float128`. + `np.object_`, `np.str_`, `np.recarray` types are not supported. +* `ndarray` storage is in C order only. Fortran order, views, `stride_tricks` + are not supported. +* Only a subset of functions and modules are supported. This set will be + expanded over time. For supported functions, some arguments or argument + values may not be supported. These differences are generally provided in the + function comments. Full `ufunc` support is also not provided. +* Buffer mutation is currently not supported. `ndarrays` wrap immutable + tensors. This means that output buffer arguments (e.g. `out` in ufuncs) are + not supported. +* NumPy C API is not supported. NumPy's Cython and Swig integration are not + supported. + +API docstring: tensorflow.experimental.numpy +""" +# TODO(wangpeng): Append `tf_export`ed symbols to the comments above. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3294161d1e0a34d0026b848e274b838341de7769 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_array_ops.py @@ -0,0 +1,2111 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Common array methods.""" +# pylint: disable=g-direct-tensorflow-import + +import builtins +import enum +import functools +import math +import numbers + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import manip_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops.numpy_ops import np_arrays +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.ops.numpy_ops import np_utils +from tensorflow.python.types import core as core_tf_types +from tensorflow.python.util import nest +from tensorflow.python.util import tf_export + + +newaxis = np.newaxis +tf_export.tf_export('experimental.numpy.newaxis', v1=[]).export_constant( + __name__, 'newaxis' +) + + +@tf_export.tf_export('experimental.numpy.empty', v1=[]) +@np_utils.np_doc('empty') +def empty(shape, dtype=float): # pylint: disable=redefined-outer-name + return zeros(shape, dtype) + + +@tf_export.tf_export('experimental.numpy.empty_like', v1=[]) +@np_utils.np_doc('empty_like') +def empty_like(a, dtype=None): + return zeros_like(a, dtype) + + +@tf_export.tf_export('experimental.numpy.zeros', v1=[]) +@np_utils.np_doc('zeros') +def zeros(shape, dtype=float): # pylint: disable=redefined-outer-name + dtype = ( + np_utils.result_type(dtype) if dtype else np_dtypes.default_float_type() + ) + return array_ops.zeros(shape, dtype=dtype) + + +@tf_export.tf_export('experimental.numpy.zeros_like', v1=[]) +@np_utils.np_doc('zeros_like') +def zeros_like(a, dtype=None): # pylint: disable=missing-docstring + dtype = np_utils.result_type_unary(a, dtype) + + dtype = dtypes.as_dtype(dtype) # Work around b/149877262 + return array_ops.zeros_like(a, dtype) + + +@tf_export.tf_export('experimental.numpy.ones', v1=[]) +@np_utils.np_doc('ones') +def ones(shape, dtype=float): # pylint: disable=redefined-outer-name + if dtype: + dtype = np_utils.result_type(dtype) + return array_ops.ones(shape, dtype=dtype) + + +@tf_export.tf_export('experimental.numpy.ones_like', v1=[]) +@np_utils.np_doc('ones_like') +def ones_like(a, dtype=None): + dtype = np_utils.result_type_unary(a, dtype) + return array_ops.ones_like(a, dtype) + + +@tf_export.tf_export('experimental.numpy.eye', v1=[]) +@np_utils.np_doc('eye') +def eye(N, M=None, k=0, dtype=float): # pylint: disable=invalid-name,missing-docstring + if dtype: + dtype = np_utils.result_type(dtype) + if not M: + M = N + # Making sure N, M and k are `int` + N = int(N) + M = int(M) + k = int(k) + if k >= M or -k >= N: + # tf.linalg.diag will raise an error in this case + return zeros([N, M], dtype=dtype) + if k == 0: + return linalg_ops.eye(N, M, dtype=dtype) + # We need the precise length, otherwise tf.linalg.diag will raise an error + diag_len = builtins.min(N, M) + if k > 0: + if N >= M: + diag_len -= k + elif N + k > M: + diag_len = M - k + elif k <= 0: + if M >= N: + diag_len += k + elif M - k > N: + diag_len = N + k + diagonal_ = array_ops.ones([diag_len], dtype=dtype) + return array_ops.matrix_diag(diagonal=diagonal_, num_rows=N, num_cols=M, k=k) + + +@tf_export.tf_export('experimental.numpy.identity', v1=[]) +@np_utils.np_doc('identity') +def identity(n, dtype=float): + return eye(N=n, M=n, dtype=dtype) + + +@tf_export.tf_export('experimental.numpy.full', v1=[]) +@np_utils.np_doc('full') +def full(shape, fill_value, dtype=None): # pylint: disable=redefined-outer-name + if not isinstance(shape, np_arrays.ndarray): + shape = asarray(np_arrays.convert_to_tensor(shape, dtype_hint=np.int32)) + shape = atleast_1d(shape) + fill_value = asarray(fill_value, dtype=dtype) + return array_ops.broadcast_to(fill_value, shape) + + +# Using doc only here since np full_like signature doesn't seem to have the +# shape argument (even though it exists in the documentation online). +@tf_export.tf_export('experimental.numpy.full_like', v1=[]) +@np_utils.np_doc_only('full_like') +def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): # pylint: disable=missing-docstring,redefined-outer-name + """order, subok and shape arguments mustn't be changed.""" + if order != 'K': + raise ValueError('Non-standard orders are not supported.') + if not subok: + raise ValueError('subok being False is not supported.') + if shape: + raise ValueError('Overriding the shape is not supported.') + + a = asarray(a) + dtype = dtype or np_utils.result_type(a) + fill_value = asarray(fill_value, dtype=dtype) + return array_ops.broadcast_to(fill_value, array_ops.shape(a)) + + +def _array_internal(val, dtype=None, copy=True, ndmin=0): # pylint: disable=redefined-outer-name + """Main implementation of np.array().""" + result_t = val + + if not isinstance(result_t, tensor_lib.Tensor): + dtype = np_utils.result_type_unary(result_t, dtype) + # We can't call `convert_to_tensor(result_t, dtype=dtype)` here because + # convert_to_tensor doesn't allow incompatible arguments such as (5.5, int) + # while np.array allows them. We need to convert-then-cast. + + # EagerTensor conversion complains about "mixed types" when converting + # tensors with no dtype information. This is because it infers types based + # on one selected item in the list. So e.g. when converting [2., 2j] + # to a tensor, it will select float32 as the inferred type and not be able + # to convert the list to a float 32 tensor. + # Since we have some information about the final dtype we care about, we + # supply that information so that convert_to_tensor will do best-effort + # conversion to that dtype first. + result_t = np_arrays.convert_to_tensor(result_t, dtype_hint=dtype) + result_t = math_ops.cast(result_t, dtype=dtype) + elif dtype: + result_t = math_ops.cast(result_t, dtype) + + if copy: + result_t = array_ops.identity(result_t) + + max_ndmin = 32 + if ndmin > max_ndmin: + raise ValueError( + f'ndmin bigger than allowable number of dimensions: {max_ndmin}.' + ) + + if ndmin == 0: + return result_t + + ndims = array_ops.rank(result_t) + + def true_fn(): + old_shape = array_ops.shape(result_t) + new_shape = array_ops.concat( + [array_ops.ones(ndmin - ndims, dtypes.int32), old_shape], axis=0 + ) + return array_ops.reshape(result_t, new_shape) + + result_t = np_utils.cond( + np_utils.greater(ndmin, ndims), true_fn, lambda: result_t + ) + return result_t + + +# TODO(wangpeng): investigate whether we can make `copy` default to False. +# pylint: disable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-doc-return-or-yield,g-doc-args +@tf_export.tf_export('experimental.numpy.array', v1=[]) +@np_utils.np_doc_only('array') +def array(val, dtype=None, copy=True, ndmin=0): # pylint: disable=redefined-outer-name + """Since Tensors are immutable, a copy is made only if val is placed on a + + different device than the current one. Even if `copy` is False, a new Tensor + may need to be built to satisfy `dtype` and `ndim`. This is used only if `val` + is an ndarray or a Tensor. + """ # pylint:disable=g-docstring-missing-newline + if dtype: + dtype = np_utils.result_type(dtype) + return _array_internal(val, dtype, copy, ndmin) + + +# pylint: enable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-doc-return-or-yield,g-doc-args + + +@tf_export.tf_export('experimental.numpy.asarray', v1=[]) +@np_utils.np_doc('asarray') +def asarray(a, dtype=None): + if dtype: + dtype = np_utils.result_type(dtype) + if isinstance(a, np_arrays.ndarray) and ( + not dtype or dtype == a.dtype.as_numpy_dtype + ): + return a + return array(a, dtype, copy=False) + + +@tf_export.tf_export('experimental.numpy.asanyarray', v1=[]) +@np_utils.np_doc('asanyarray') +def asanyarray(a, dtype=None): + return asarray(a, dtype) + + +@tf_export.tf_export('experimental.numpy.ascontiguousarray', v1=[]) +@np_utils.np_doc('ascontiguousarray') +def ascontiguousarray(a, dtype=None): + return array(a, dtype, ndmin=1) + + +# Numerical ranges. +@tf_export.tf_export('experimental.numpy.arange', v1=[]) +@np_utils.np_doc('arange') +def arange(start, stop=None, step=1, dtype=None): + """Returns `step`-separated values in the range [start, stop). + + Args: + start: Start of the interval. Included in the range. + stop: End of the interval. If not specified, `start` is treated as 0 and + `start` value is used as `stop`. If specified, it is not included in the + range if `step` is integer. When `step` is floating point, it may or may + not be included. + step: The difference between 2 consecutive values in the output range. It is + recommended to use `linspace` instead of using non-integer values for + `step`. + dtype: Optional. Type of the resulting ndarray. Could be a python type, a + NumPy type or a TensorFlow `DType`. If not provided, the largest type of + `start`, `stop`, `step` is used. + + Raises: + ValueError: If step is zero. + """ + if not step: + raise ValueError('step must be non-zero.') + if dtype: + dtype = np_utils.result_type(dtype) + else: + if stop is None: + dtype = np_utils.result_type(start, step) + else: + dtype = np_utils.result_type(start, step, stop) + if step > 0 and ( + (stop is not None and start > stop) or (stop is None and start < 0) + ): + return array([], dtype=dtype) + if step < 0 and ( + (stop is not None and start < stop) or (stop is None and start > 0) + ): + return array([], dtype=dtype) + # TODO(srbs): There are some bugs when start or stop is float type and dtype + # is integer type. + return math_ops.cast( + math_ops.range(start, limit=stop, delta=step), dtype=dtype + ) + + +# Building matrices. +@tf_export.tf_export('experimental.numpy.diag', v1=[]) +@np_utils.np_doc('diag') +def diag(v, k=0): # pylint: disable=missing-docstring + """Raises an error if input is not 1- or 2-d.""" + v = asarray(v) + v_rank = array_ops.rank(v) + + v.shape.with_rank_at_most(2) + + # TODO(nareshmodi): Consider a np_utils.Assert version that will fail during + # tracing time if the shape is known. + control_flow_assert.Assert( + np_utils.logical_or(math_ops.equal(v_rank, 1), math_ops.equal(v_rank, 2)), + [v_rank], + ) + + def _diag(v, k): + return np_utils.cond( + math_ops.equal(array_ops.size(v), 0), + lambda: array_ops.zeros([abs(k), abs(k)], dtype=v.dtype), + lambda: array_ops.matrix_diag(v, k=k), + ) + + def _diag_part(v, k): + v_shape = array_ops.shape(v) + v, k = np_utils.cond( + np_utils.logical_or( + np_utils.less_equal(k, -1 * np_utils.getitem(v_shape, 0)), + np_utils.greater_equal(k, np_utils.getitem(v_shape, 1)), + ), + lambda: (array_ops.zeros([0, 0], dtype=v.dtype), 0), + lambda: (v, k), + ) + result = array_ops.matrix_diag_part(v, k=k) + return result + + result = np_utils.cond( + math_ops.equal(v_rank, 1), lambda: _diag(v, k), lambda: _diag_part(v, k) + ) + return result + + +@tf_export.tf_export('experimental.numpy.diagonal', v1=[]) +@np_utils.np_doc('diagonal') +def diagonal(a, offset=0, axis1=0, axis2=1): # pylint: disable=missing-docstring + a = asarray(a) + + maybe_rank = a.shape.rank + if ( + maybe_rank is not None + and offset == 0 + and (axis1 == maybe_rank - 2 or axis1 == -2) + and (axis2 == maybe_rank - 1 or axis2 == -1) + ): + return array_ops.matrix_diag_part(a) + + a = moveaxis(a, (axis1, axis2), (-2, -1)) + + a_shape = array_ops.shape(a) + + def _zeros(): # pylint: disable=missing-docstring + return ( + array_ops.zeros( + array_ops.concat([a_shape[:-1], [0]], 0), dtype=a.dtype + ), + 0, + ) + + # All zeros since diag_part doesn't handle all possible k (aka offset). + # Written this way since cond will run shape inference on both branches, + # and diag_part shape inference will fail when offset is out of bounds. + a, offset = np_utils.cond( + np_utils.logical_or( + np_utils.less_equal(offset, -1 * np_utils.getitem(a_shape, -2)), + np_utils.greater_equal(offset, np_utils.getitem(a_shape, -1)), + ), + _zeros, + lambda: (a, offset), + ) + + a = array_ops.matrix_diag_part(a, k=offset) + return a + + +@tf_export.tf_export('experimental.numpy.diagflat', v1=[]) +@np_utils.np_doc('diagflat') +def diagflat(v, k=0): + v = asarray(v) + return diag(array_ops.reshape(v, [-1]), k) + + +def _promote_dtype(*arrays): + dtype = np_utils.result_type(*arrays) + + def _fast_asarray(a): + if isinstance(a, np_arrays.ndarray) and dtype == a.dtype.as_numpy_dtype: + return a + return _array_internal(a, dtype=dtype, copy=False) + + return [_fast_asarray(a) for a in arrays] + + +def _promote_dtype_binary(t1, t2): + dtype = np_utils._result_type_binary(t1, t2) # pylint: disable=protected-access + if not ( + isinstance(t1, np_arrays.ndarray) and dtype == t1.dtype.as_numpy_dtype + ): + t1 = _array_internal(t1, dtype=dtype, copy=False) + if not ( + isinstance(t2, np_arrays.ndarray) and dtype == t2.dtype.as_numpy_dtype + ): + t2 = _array_internal(t2, dtype=dtype, copy=False) + return t1, t2 + + +@tf_export.tf_export('experimental.numpy.all', v1=[]) +@np_utils.np_doc('all') +def all(a, axis=None, keepdims=None): # pylint: disable=redefined-builtin + a = asarray(a, dtype=bool) + return math_ops.reduce_all(input_tensor=a, axis=axis, keepdims=keepdims) + + +@tf_export.tf_export('experimental.numpy.any', v1=[]) +@np_utils.np_doc('any') +def any(a, axis=None, keepdims=None): # pylint: disable=redefined-builtin + a = asarray(a, dtype=bool) + return math_ops.reduce_any(input_tensor=a, axis=axis, keepdims=keepdims) + + +@tf_export.tf_export('experimental.numpy.compress', v1=[]) +@np_utils.np_doc('compress') +def compress(condition, a, axis=None): # pylint: disable=redefined-outer-name,missing-function-docstring + condition = asarray(condition, dtype=bool) + a = asarray(a) + + if condition.ndim != 1: + raise ValueError('condition must be a 1-d array.') + # `np.compress` treats scalars as 1-d arrays. + if a.ndim == 0: + a = ravel(a) + + if axis is None: + a = ravel(a) + axis = 0 + + if axis < 0: + axis += a.ndim + + assert axis >= 0 and axis < a.ndim + + # `tf.boolean_mask` requires the first dimensions of array and condition to + # match. `np.compress` pads condition with False when it is shorter. + condition_t = condition + a_t = a + if condition.shape[0] < a.shape[axis]: + padding = array_ops.fill([a.shape[axis] - condition.shape[0]], False) + condition_t = array_ops.concat([condition_t, padding], axis=0) + return array_ops.boolean_mask(tensor=a_t, mask=condition_t, axis=axis) + + +@tf_export.tf_export('experimental.numpy.copy', v1=[]) +@np_utils.np_doc('copy') +def copy(a): + return array(a, copy=True) + + +def _maybe_promote_to_int(a): + if dtypes.as_dtype(a.dtype).is_integer: + # If a is an integer type and its precision is less than that of `int`, + # the output type will be `int`. + a_numpy_dtype = a.dtype.as_numpy_dtype + output_type = np.promote_types(a_numpy_dtype, int) + if output_type != a_numpy_dtype: + a = asarray(a, dtype=output_type) + + return a + + +@tf_export.tf_export('experimental.numpy.cumprod', v1=[]) +@np_utils.np_doc('cumprod') +def cumprod(a, axis=None, dtype=None): # pylint: disable=missing-docstring + a = asarray(a, dtype=dtype) + + if dtype is None: + a = _maybe_promote_to_int(a) + + # If axis is None, the input is flattened. + if axis is None: + a = ravel(a) + axis = 0 + elif axis < 0: + axis += array_ops.rank(a) + return math_ops.cumprod(a, axis) + + +@tf_export.tf_export('experimental.numpy.cumsum', v1=[]) +@np_utils.np_doc('cumsum') +def cumsum(a, axis=None, dtype=None): # pylint: disable=missing-docstring + a = asarray(a, dtype=dtype) + + if dtype is None: + a = _maybe_promote_to_int(a) + + # If axis is None, the input is flattened. + if axis is None: + a = ravel(a) + axis = 0 + elif axis < 0: + axis += array_ops.rank(a) + return math_ops.cumsum(a, axis) + + +@tf_export.tf_export('experimental.numpy.imag', v1=[]) +@np_utils.np_doc('imag') +def imag(val): + val = asarray(val) + # TODO(srbs): np.imag returns a scalar if `val` is a scalar, whereas we always + # return an ndarray. + return math_ops.imag(val) + + +_TO_INT_ = 0 +_TO_FLOAT = 1 + + +def _reduce( + tf_fn, + a, + axis=None, + dtype=None, + keepdims=None, + promote_int=_TO_INT_, + tf_bool_fn=None, + preserve_bool=False, +): + """A general reduction function. + + Args: + tf_fn: the TF reduction function. + a: the array to be reduced. + axis: (optional) the axis along which to do the reduction. If None, all + dimensions are reduced. + dtype: (optional) the dtype of the result. + keepdims: (optional) whether to keep the reduced dimension(s). + promote_int: how to promote integer and bool inputs. There are three + choices. (1) `_TO_INT_` always promotes them to np.int_ or np.uint; (2) + `_TO_FLOAT` always promotes them to a float type (determined by + dtypes.default_float_type); (3) None: don't promote. + tf_bool_fn: (optional) the TF reduction function for bool inputs. It will + only be used if `dtype` is explicitly set to `np.bool_` or if `a`'s dtype + is `np.bool_` and `preserve_bool` is True. + preserve_bool: a flag to control whether to use `tf_bool_fn` if `a`'s dtype + is `np.bool_` (some reductions such as np.sum convert bools to integers, + while others such as np.max preserve bools. + + Returns: + An ndarray. + """ + if dtype: + dtype = np_utils.result_type(dtype) + if keepdims is None: + keepdims = False + a = asarray(a, dtype=dtype) + if ( + dtype == np.bool_ or preserve_bool and a.dtype == np.bool_ + ) and tf_bool_fn is not None: + return tf_bool_fn(input_tensor=a, axis=axis, keepdims=keepdims) + if dtype is None: + dtype = a.dtype.as_numpy_dtype + if np.issubdtype(dtype, np.integer) or dtype == np.bool_: + if promote_int == _TO_INT_: + # If a is an integer/bool type and whose bit width is less than np.int_, + # numpy up-casts it to np.int_ based on the documentation at + # https://numpy.org/doc/1.18/reference/generated/numpy.sum.html + if dtype == np.bool_: + is_signed = True + width = 8 # We can use any number here that is less than 64 + else: + is_signed = np.issubdtype(dtype, np.signedinteger) + width = np.iinfo(dtype).bits + # Numpy int_ and uint are defined as 'long' and 'unsigned long', so + # should have the same bit width. + if ops.is_auto_dtype_conversion_enabled(): + # We default to 32 bits when using auto dtype conversion semantics. + if width < np.iinfo(np.int32).bits: + if is_signed: + dtype = np.int32 + else: + dtype = np.uint32 + else: + if width < np.iinfo(np.int_).bits: + if is_signed: + dtype = np.int_ + else: + dtype = np.uint + a = math_ops.cast(a, dtype) + elif promote_int == _TO_FLOAT: + # Use a default float type. + a = math_ops.cast(a, np_utils.result_type(float)) + + if isinstance(axis, tensor_lib.Tensor) and axis.dtype not in ( + dtypes.int32, + dtypes.int64, + ): + axis = math_ops.cast(axis, dtypes.int64) + + return tf_fn(input_tensor=a, axis=axis, keepdims=keepdims) + + +# TODO (DarrenZhang01): Add `axis` support to the `size` API. +@tf_export.tf_export('experimental.numpy.size', v1=[]) +@np_utils.np_doc('size') +def size(x, axis=None): # pylint: disable=missing-docstring + if axis is not None: + raise NotImplementedError( + 'axis argument is not supported in the current `np.size` implementation' + ) + if isinstance(x, (int, float, np.int32, np.int64, np.float32, np.float64)): + return 1 + x = asarray(x) + if x.shape.is_fully_defined(): + return np.prod(x.shape.as_list(), dtype=int) + else: + return array_ops.size_v2(x) + + +@tf_export.tf_export('experimental.numpy.sum', v1=[]) +@np_utils.np_doc('sum') +def sum(a, axis=None, dtype=None, keepdims=None): # pylint: disable=redefined-builtin + return _reduce( + math_ops.reduce_sum, + a, + axis=axis, + dtype=dtype, + keepdims=keepdims, + tf_bool_fn=math_ops.reduce_any, + ) + + +@tf_export.tf_export('experimental.numpy.prod', v1=[]) +@np_utils.np_doc('prod') +def prod(a, axis=None, dtype=None, keepdims=None): + return _reduce( + math_ops.reduce_prod, + a, + axis=axis, + dtype=dtype, + keepdims=keepdims, + tf_bool_fn=math_ops.reduce_all, + ) + + +@tf_export.tf_export('experimental.numpy.mean', v1=[]) +@np_utils.np_doc('mean', unsupported_params=['out']) +def mean(a, axis=None, dtype=None, out=None, keepdims=None): + if out is not None: + raise ValueError('Setting out is not supported.') + return _reduce( + math_ops.reduce_mean, + a, + axis=axis, + dtype=dtype, + keepdims=keepdims, + promote_int=_TO_FLOAT, + ) + + +@tf_export.tf_export('experimental.numpy.amax', v1=[]) +@np_utils.np_doc('amax', unsupported_params=['out']) +def amax(a, axis=None, out=None, keepdims=None): + if out is not None: + raise ValueError('Setting out is not supported.') + return _reduce( + math_ops.reduce_max, + a, + axis=axis, + dtype=None, + keepdims=keepdims, + promote_int=None, + tf_bool_fn=math_ops.reduce_any, + preserve_bool=True, + ) + + +@tf_export.tf_export('experimental.numpy.amin', v1=[]) +@np_utils.np_doc('amin', unsupported_params=['out']) +def amin(a, axis=None, out=None, keepdims=None): + if out is not None: + raise ValueError('Setting out is not supported.') + return _reduce( + math_ops.reduce_min, + a, + axis=axis, + dtype=None, + keepdims=keepdims, + promote_int=None, + tf_bool_fn=math_ops.reduce_all, + preserve_bool=True, + ) + + +@tf_export.tf_export('experimental.numpy.var', v1=[]) +@np_utils.np_doc('var') +def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=None): # pylint: disable=missing-docstring + if dtype: + working_dtype = np_utils.result_type(a, dtype) + else: + working_dtype = None + if out is not None: + raise ValueError('Setting out is not supported.') + if ddof != 0: + # TF reduce_variance doesn't support ddof, so calculate it using raw ops. + def reduce_fn(input_tensor, axis, keepdims): + means = math_ops.reduce_mean(input_tensor, axis=axis, keepdims=True) + centered = input_tensor - means + if input_tensor.dtype in (dtypes.complex64, dtypes.complex128): + centered = math_ops.cast( + math_ops.real(centered * math_ops.conj(centered)), + input_tensor.dtype, + ) + else: + centered = math_ops.square(centered) + squared_deviations = math_ops.reduce_sum( + centered, axis=axis, keepdims=keepdims + ) + + if axis is None: + n = array_ops.size(input_tensor) + else: + if axis < 0: + axis += array_ops.rank(input_tensor) + n = math_ops.reduce_prod( + array_ops.gather(array_ops.shape(input_tensor), axis) + ) + n = math_ops.cast(n - ddof, input_tensor.dtype) + + return math_ops.cast(math_ops.divide(squared_deviations, n), dtype) + + else: + reduce_fn = math_ops.reduce_variance + + result = _reduce( + reduce_fn, + a, + axis=axis, + dtype=working_dtype, + keepdims=keepdims, + promote_int=_TO_FLOAT, + ) + if dtype: + result = math_ops.cast(result, dtype) + return result + + +@tf_export.tf_export('experimental.numpy.std', v1=[]) +@np_utils.np_doc('std') +def std(a, axis=None, keepdims=None): # pylint: disable=missing-function-docstring + return _reduce( + math_ops.reduce_std, + a, + axis=axis, + dtype=None, + keepdims=keepdims, + promote_int=_TO_FLOAT, + ) + + +@tf_export.tf_export('experimental.numpy.ravel', v1=[]) +@np_utils.np_doc('ravel') +def ravel(a): # pylint: disable=missing-docstring + a = asarray(a) + return array_ops.reshape(a, [-1]) + + +@tf_export.tf_export('experimental.numpy.real', v1=[]) +@np_utils.np_doc('real') +def real(val): + val = asarray(val) + # TODO(srbs): np.real returns a scalar if val is a scalar, whereas we always + # return an ndarray. + return math_ops.real(val) + + +@tf_export.tf_export('experimental.numpy.repeat', v1=[]) +@np_utils.np_doc('repeat') +def repeat(a, repeats, axis=None): # pylint: disable=missing-docstring + a = asarray(a) + original_shape = a._shape_as_list() # pylint: disable=protected-access + # Best effort recovery of the shape. + known_shape = original_shape is not None and None not in original_shape + if known_shape: + if not original_shape: + original_shape = (repeats,) + else: + repeats_np = np.ravel(np.array(repeats)) + if repeats_np.size == 1: + repeats_np = repeats_np.item() + if axis is None: + original_shape = (repeats_np * np.prod(original_shape),) + else: + original_shape[axis] = repeats_np * original_shape[axis] + else: + if axis is None: + original_shape = (repeats_np.sum(),) + else: + original_shape[axis] = repeats_np.sum() + + repeats = asarray(repeats) + result = array_ops.repeat(a, repeats, axis) + if known_shape: + result.set_shape(original_shape) + + return result + + +@tf_export.tf_export('experimental.numpy.around', v1=[]) +@np_utils.np_doc('around') +def around(a, decimals=0): # pylint: disable=missing-docstring + a = asarray(a) + dtype = a.dtype.as_numpy_dtype + factor = math.pow(10, decimals) + if np.issubdtype(dtype, np.inexact): + factor = math_ops.cast(factor, dtype) + else: + # Use float as the working dtype when a.dtype is exact (e.g. integer), + # because `decimals` can be negative. + float_dtype = np_utils.result_type(float) + a = a.astype(float_dtype) + factor = math_ops.cast(factor, float_dtype) + a = math_ops.multiply(a, factor) + a = math_ops.round(a) + a = math_ops.divide(a, factor) + return a.astype(dtype) + + +setattr(np_arrays.ndarray, '__round__', around) + + +@tf_export.tf_export('experimental.numpy.reshape', v1=[]) +@np_utils.np_doc('reshape') +def reshape(a, newshape, order='C'): + """order argument can only b 'C' or 'F'.""" + if order not in {'C', 'F'}: + raise ValueError('Unsupported order argument {}'.format(order)) + + a = asarray(a) + if isinstance(newshape, int): + newshape = [newshape] + + if order == 'F': + r = array_ops.transpose( + array_ops.reshape(array_ops.transpose(a), newshape[::-1]) + ) + else: + r = array_ops.reshape(a, newshape) + + return r + + +def _reshape_method_wrapper(a, *newshape, **kwargs): + order = kwargs.pop('order', 'C') + if kwargs: + raise ValueError('Unsupported arguments: {}'.format(kwargs.keys())) + + if len(newshape) == 1 and not isinstance(newshape[0], int): + newshape = newshape[0] + + return reshape(a, newshape, order=order) + + +@tf_export.tf_export('experimental.numpy.expand_dims', v1=[]) +@np_utils.np_doc('expand_dims') +def expand_dims(a, axis): + a = asarray(a) + return array_ops.expand_dims(a, axis=axis) + + +@tf_export.tf_export('experimental.numpy.squeeze', v1=[]) +@np_utils.np_doc('squeeze') +def squeeze(a, axis=None): + a = asarray(a) + return array_ops.squeeze(a, axis) + + +@tf_export.tf_export('experimental.numpy.flatten', v1=[]) +@np_utils.np_doc('flatten', link=np_utils.NoLink()) +def flatten(a, order='C'): + a = asarray(a) + if order == 'C' or order == 'A' or order == 'K': + # Row major. + return array_ops.reshape(a, [-1]) + elif order == 'F': + # Column major + return array_ops.reshape(array_ops.transpose(a), [-1]) + else: + raise ValueError( + 'order can only be C, A, K (all row major) or F (column major).' + ) + + +@tf_export.tf_export('experimental.numpy.transpose', v1=[]) +@np_utils.np_doc('transpose') +def transpose(a, axes=None): + a = asarray(a) + if axes is not None: + axes = asarray(axes) + return array_ops.transpose(a=a, perm=axes) + + +@tf_export.tf_export('experimental.numpy.swapaxes', v1=[]) +@np_utils.np_doc('swapaxes') +def swapaxes(a, axis1, axis2): # pylint: disable=missing-docstring + a = asarray(a) + + def adjust_axes(axes, rank): + def f(x): + if isinstance(x, int): + if x < 0: + x = x + rank + else: + x = array_ops.where_v2(x < 0, np_utils.add(x, a_rank), x) + return x + + return nest.map_structure(f, axes) + + if ( + a.shape.rank is not None + and isinstance(axis1, int) + and isinstance(axis2, int) + ): + # This branch makes sure `perm` is statically known, to avoid a + # not-compile-time-constant XLA error. + a_rank = a.shape.rank + axis1, axis2 = adjust_axes((axis1, axis2), a_rank) + perm = list(range(a_rank)) + perm[axis1] = axis2 + perm[axis2] = axis1 + else: + a_rank = array_ops.rank(a) + axis1, axis2 = adjust_axes((axis1, axis2), a_rank) + perm = math_ops.range(a_rank) + perm = array_ops.tensor_scatter_update( + perm, [[axis1], [axis2]], [axis2, axis1] + ) + a = array_ops.transpose(a, perm) + return a + + +@tf_export.tf_export('experimental.numpy.moveaxis', v1=[]) +@np_utils.np_doc('moveaxis') +def moveaxis(a, source, destination): # pylint: disable=missing-docstring + """Raises ValueError if source, destination not in (-ndim(a), ndim(a)).""" + if not source and not destination: + return a + + a = asarray(a) + + if isinstance(source, int): + source = (source,) + if isinstance(destination, int): + destination = (destination,) + if len(source) != len(destination): + raise ValueError('The lengths of source and destination must equal') + + a_rank = np_utils._maybe_static(array_ops.rank(a)) # pylint: disable=protected-access + + def _correct_axis(axis, rank): + if axis < 0: + return axis + rank + return axis + + source = tuple(_correct_axis(axis, a_rank) for axis in source) + destination = tuple(_correct_axis(axis, a_rank) for axis in destination) + + if a.shape.rank is not None: + perm = [i for i in range(a_rank) if i not in source] + for dest, src in sorted(zip(destination, source)): + assert dest <= len(perm) + perm.insert(dest, src) + else: + r = math_ops.range(a_rank) + + def _remove_indices(a, b): + """Remove indices (`b`) from `a`.""" + items = array_ops_stack.unstack( + sort_ops.sort(array_ops_stack.stack(b)), num=len(b) + ) + + i = 0 + result = [] + + for item in items: + result.append(a[i:item]) + i = item + 1 + + result.append(a[i:]) + + return array_ops.concat(result, 0) + + minus_sources = _remove_indices(r, source) + minus_dest = _remove_indices(r, destination) + + perm = array_ops.scatter_nd( + array_ops.expand_dims(minus_dest, 1), minus_sources, [a_rank] + ) + perm = array_ops.tensor_scatter_update( + perm, array_ops.expand_dims(destination, 1), source + ) + a = array_ops.transpose(a, perm) + + return a + + +@tf_export.tf_export('experimental.numpy.pad', v1=[]) +@np_utils.np_doc('pad') +def pad(array, pad_width, mode, **kwargs): # pylint: disable=redefined-outer-name + """Only supports modes 'constant', 'reflect' and 'symmetric' currently.""" + constant_values = kwargs.get('constant_values', 0) + if not (mode == 'constant' or mode == 'reflect' or mode == 'symmetric'): + raise ValueError('Unsupported padding mode: ' + mode) + mode = mode.upper() + array = asarray(array) + pad_width = asarray(pad_width, dtype=dtypes.int32) + return array_ops.pad( + tensor=array, + paddings=pad_width, + mode=mode, + constant_values=constant_values, + ) + + +@tf_export.tf_export('experimental.numpy.take', v1=[]) +@np_utils.np_doc('take') +def take(a, indices, axis=None, out=None, mode='clip'): + """out argument is not supported, and default mode is clip.""" + if out is not None: + raise ValueError('out argument is not supported in take.') + + if mode not in {'raise', 'clip', 'wrap'}: + raise ValueError("Invalid mode '{}' for take".format(mode)) + + a = asarray(a) + indices = asarray(indices) + + if axis is None: + a = array_ops.reshape(a, [-1]) + axis = 0 + + axis_size = array_ops.shape(a, out_type=indices.dtype)[axis] + if mode == 'clip': + indices = clip_ops.clip_by_value(indices, 0, axis_size - 1) + elif mode == 'wrap': + indices = math_ops.floormod(indices, axis_size) + else: + raise ValueError("The 'raise' mode to take is not supported.") + + return array_ops.gather(a, indices, axis=axis) + + +@tf_export.tf_export('experimental.numpy.where', v1=[]) +@np_utils.np_doc_only('where') +def where(condition, x=None, y=None): + """Raises ValueError if exactly one of x or y is not None.""" + condition = asarray(condition, dtype=np.bool_) + if x is None and y is None: + return nonzero(condition) + elif x is not None and y is not None: + x, y = _promote_dtype(x, y) + return array_ops.where_v2(condition, x, y) + raise ValueError('Both x and y must be ndarrays, or both must be None.') + + +@tf_export.tf_export('experimental.numpy.select', v1=[]) +@np_utils.np_doc('select') +def select(condlist, choicelist, default=0): # pylint: disable=missing-docstring + if len(condlist) != len(choicelist): + msg = 'condlist must have length equal to choicelist ({} vs {})' + raise ValueError(msg.format(len(condlist), len(choicelist))) + if not condlist: + raise ValueError('condlist must be non-empty') + choices = _promote_dtype(default, *choicelist) + choicelist = choices[1:] + output = choices[0] + # The traversal is in reverse order so we can return the first value in + # choicelist where condlist is True. + for cond, choice in zip(condlist[::-1], choicelist[::-1]): + output = where(cond, choice, output) + return output + + +@tf_export.tf_export('experimental.numpy.shape', v1=[]) +@np_utils.np_doc( + 'shape', + link=np_utils.Link( + 'https://numpy.org/doc/1.18/reference/generated/numpy.shape.html' + ), +) +def shape(a): + a = asarray(a) + return a.shape + + +@tf_export.tf_export('experimental.numpy.ndim', v1=[]) +@np_utils.np_doc('ndim', link=np_utils.NoLink()) +def ndim(a): + a = asarray(a) + return a.ndim + + +@tf_export.tf_export('experimental.numpy.isscalar', v1=[]) +@np_utils.np_doc('isscalar') +def isscalar(num): + return ndim(num) == 0 + + +def _boundaries_to_sizes(a, boundaries, axis): + """Converting boundaries of splits to sizes of splits. + + Args: + a: the array to be split. + boundaries: the boundaries, as in np.split. + axis: the axis along which to split. + + Returns: + A list of sizes of the splits, as in tf.split. + """ + if axis >= len(a.shape): + raise ValueError('axis %s is out of bound for shape %s' % (axis, a.shape)) + total_size = a.shape[axis] + sizes = [] + sizes_sum = 0 + prev = 0 + for i, b in enumerate(boundaries): + size = b - prev + if size < 0: + raise ValueError( + 'The %s-th boundary %s is smaller than the previous boundary %s' + % (i, b, prev) + ) + size = builtins.min(size, builtins.max(0, total_size - sizes_sum)) + sizes.append(size) + sizes_sum += size + prev = b + sizes.append(builtins.max(0, total_size - sizes_sum)) + return sizes + + +@tf_export.tf_export('experimental.numpy.split', v1=[]) +@np_utils.np_doc('split') +def split(ary, indices_or_sections, axis=0): + ary = asarray(ary) + if not isinstance(indices_or_sections, int): + indices_or_sections = _boundaries_to_sizes(ary, indices_or_sections, axis) + return array_ops.split(ary, indices_or_sections, axis=axis) + + +def _split_on_axis(np_fun_name, axis): # pylint: disable=missing-function-docstring + @np_utils.np_doc(np_fun_name) + def f(ary, indices_or_sections): + # for 1-D array, hsplit becomes vsplit + new_axis = np_utils.cond( + math_ops.equal(axis, 1), + lambda: np_utils.cond( # pylint: disable=g-long-lambda + math_ops.equal(array_ops.rank(ary), 1), lambda: 0, lambda: axis + ), + lambda: axis, + ) + if isinstance(indices_or_sections, int): + ary_shape = ary.shape[new_axis] + if ary_shape is not None and ary_shape % indices_or_sections: + raise ValueError('array split does not result in an equal division') + return split(ary, indices_or_sections, axis=new_axis) + + return f + + +vsplit = tf_export.tf_export('experimental.numpy.vsplit', v1=[])( + _split_on_axis('vsplit', axis=0) +) +hsplit = tf_export.tf_export('experimental.numpy.hsplit', v1=[])( + _split_on_axis('hsplit', axis=1) +) +dsplit = tf_export.tf_export('experimental.numpy.dsplit', v1=[])( + _split_on_axis('dsplit', axis=2) +) + + +@tf_export.tf_export('experimental.numpy.broadcast_to', v1=[]) +@np_utils.np_doc('broadcast_to') +def broadcast_to(array, shape): # pylint: disable=redefined-outer-name + return full(shape, array) + + +@tf_export.tf_export('experimental.numpy.stack', v1=[]) +@np_utils.np_doc('stack') +def stack(arrays, axis=0): # pylint: disable=missing-function-docstring + if isinstance(arrays, (np_arrays.ndarray, tensor_lib.Tensor)): + arrays = asarray(arrays) + if axis == 0: + return arrays + else: + return swapaxes(arrays, 0, axis) + arrays = _promote_dtype(*arrays) # pylint: disable=protected-access + unwrapped_arrays = [ + a if isinstance(a, np_arrays.ndarray) else a for a in arrays + ] + return asarray(array_ops_stack.stack(unwrapped_arrays, axis)) + + +@tf_export.tf_export('experimental.numpy.hstack', v1=[]) +@np_utils.np_doc('hstack') +def hstack(tup): + arrays = [atleast_1d(a) for a in tup] + arrays = _promote_dtype(*arrays) # pylint: disable=protected-access + unwrapped_arrays = [ + a if isinstance(a, np_arrays.ndarray) else a for a in arrays + ] + rank = array_ops.rank(unwrapped_arrays[0]) + return np_utils.cond( + math_ops.equal(rank, 1), + lambda: array_ops.concat(unwrapped_arrays, axis=0), + lambda: array_ops.concat(unwrapped_arrays, axis=1), + ) + + +@tf_export.tf_export('experimental.numpy.vstack', v1=[]) +@np_utils.np_doc('vstack') +def vstack(tup): + arrays = [atleast_2d(a) for a in tup] + arrays = _promote_dtype(*arrays) # pylint: disable=protected-access + unwrapped_arrays = [ + a if isinstance(a, np_arrays.ndarray) else a for a in arrays + ] + return array_ops.concat(unwrapped_arrays, axis=0) + + +@tf_export.tf_export('experimental.numpy.dstack', v1=[]) +@np_utils.np_doc('dstack') +def dstack(tup): + arrays = [atleast_3d(a) for a in tup] + arrays = _promote_dtype(*arrays) # pylint: disable=protected-access + unwrapped_arrays = [ + a if isinstance(a, np_arrays.ndarray) else a for a in arrays + ] + return array_ops.concat(unwrapped_arrays, axis=2) + + +def _pad_left_to(n, old_shape): + old_shape = asarray(old_shape, dtype=np.int32) + new_shape = array_ops.pad( + old_shape, + [[math_ops.maximum(n - array_ops.size(old_shape), 0), 0]], + constant_values=1, + ) + return asarray(new_shape) + + +def _atleast_nd(n, new_shape, *arys): + """Reshape arrays to be at least `n`-dimensional. + + Args: + n: The minimal rank. + new_shape: a function that takes `n` and the old shape and returns the + desired new shape. + *arys: ndarray(s) to be reshaped. + + Returns: + The reshaped array(s). + """ + + def f(x): + # pylint: disable=g-long-lambda + x = asarray(x) + return asarray( + np_utils.cond( + np_utils.greater(n, array_ops.rank(x)), + lambda: reshape(x, new_shape(n, array_ops.shape(x))), + lambda: x, + ) + ) + + arys = list(map(f, arys)) + if len(arys) == 1: + return arys[0] + else: + return arys + + +@tf_export.tf_export('experimental.numpy.atleast_1d', v1=[]) +@np_utils.np_doc('atleast_1d') +def atleast_1d(*arys): + return _atleast_nd(1, _pad_left_to, *arys) + + +@tf_export.tf_export('experimental.numpy.atleast_2d', v1=[]) +@np_utils.np_doc('atleast_2d') +def atleast_2d(*arys): + return _atleast_nd(2, _pad_left_to, *arys) + + +@tf_export.tf_export('experimental.numpy.atleast_3d', v1=[]) +@np_utils.np_doc('atleast_3d') +def atleast_3d(*arys): # pylint: disable=missing-docstring + def new_shape(_, old_shape): + # pylint: disable=g-long-lambda + ndim_ = array_ops.size(old_shape) + return np_utils.cond( + math_ops.equal(ndim_, 0), + lambda: constant_op.constant([1, 1, 1], dtype=dtypes.int32), + lambda: np_utils.cond( + math_ops.equal(ndim_, 1), + lambda: array_ops.pad(old_shape, [[1, 1]], constant_values=1), + lambda: array_ops.pad(old_shape, [[0, 1]], constant_values=1), + ), + ) + + return _atleast_nd(3, new_shape, *arys) + + +@tf_export.tf_export('experimental.numpy.nonzero', v1=[]) +@np_utils.np_doc('nonzero') +def nonzero(a): + a = atleast_1d(a) + if a.shape.rank is None: + raise ValueError( + "The rank of `a` is unknown, so we can't decide how many " + 'arrays to return.' + ) + return array_ops_stack.unstack( + array_ops.where_v2(math_ops.cast(a, dtypes.bool)), a.shape.rank, axis=1 + ) + + +@tf_export.tf_export('experimental.numpy.diag_indices', v1=[]) +@np_utils.np_doc('diag_indices') +def diag_indices(n, ndim=2): # pylint: disable=missing-docstring,redefined-outer-name + if n < 0: + raise ValueError( + 'n argument to diag_indices must be nonnegative, got {}'.format(n) + ) + if ndim < 0: + raise ValueError( + 'ndim argument to diag_indices must be nonnegative, got {}'.format(ndim) + ) + + return (math_ops.range(n),) * ndim + + +@tf_export.tf_export('experimental.numpy.tri', v1=[]) +@np_utils.np_doc('tri') +def tri(N, M=None, k=0, dtype=None): # pylint: disable=invalid-name,missing-docstring + M = M if M is not None else N + if dtype is not None: + dtype = np_utils.result_type(dtype) + else: + # Use a default float type. + dtype = np_utils.result_type(float) + + if k < 0: + lower = -k - 1 + if lower > N: + r = array_ops.zeros([N, M], dtype) + else: + # Keep as tf bool, since we create an upper triangular matrix and invert + # it. + o = array_ops.ones([N, M], dtype=dtypes.bool) + r = math_ops.cast( + math_ops.logical_not(array_ops.matrix_band_part(o, lower, -1)), dtype + ) + else: + o = array_ops.ones([N, M], dtype) + if k > M: + r = o + else: + r = array_ops.matrix_band_part(o, -1, k) + return r + + +@tf_export.tf_export('experimental.numpy.tril', v1=[]) +@np_utils.np_doc('tril') +def tril(m, k=0): # pylint: disable=missing-docstring + m = asarray(m) + if m.shape.ndims is None: + raise ValueError('Argument to tril should have known rank') + m_shape = m.shape.as_list() + + if len(m_shape) < 2: + raise ValueError('Argument to tril must have rank at least 2') + + if m_shape[-1] is None or m_shape[-2] is None: + raise ValueError( + 'Currently, the last two dimensions of the input array ' + 'need to be known.' + ) + + z = constant_op.constant(0, m.dtype) + + mask = tri(*m_shape[-2:], k=k, dtype=bool) + return array_ops.where_v2( + array_ops.broadcast_to(mask, array_ops.shape(m)), m, z + ) + + +@tf_export.tf_export('experimental.numpy.triu', v1=[]) +@np_utils.np_doc('triu') +def triu(m, k=0): # pylint: disable=missing-docstring + m = asarray(m) + if m.shape.ndims is None: + raise ValueError('Argument to triu should have known rank') + m_shape = m.shape.as_list() + + if len(m_shape) < 2: + raise ValueError('Argument to triu must have rank at least 2') + + if m_shape[-1] is None or m_shape[-2] is None: + raise ValueError( + 'Currently, the last two dimensions of the input array ' + 'need to be known.' + ) + + z = constant_op.constant(0, m.dtype) + + mask = tri(*m_shape[-2:], k=k - 1, dtype=bool) + return array_ops.where_v2( + array_ops.broadcast_to(mask, array_ops.shape(m)), z, m + ) + + +@tf_export.tf_export('experimental.numpy.flip', v1=[]) +@np_utils.np_doc('flip') +def flip(m, axis=None): # pylint: disable=missing-docstring + m = asarray(m) + + if axis is None: + return array_ops.reverse(m, math_ops.range(array_ops.rank(m))) + + axis = np_utils._canonicalize_axis(axis, array_ops.rank(m)) # pylint: disable=protected-access + + return array_ops.reverse(m, [axis]) + + +@tf_export.tf_export('experimental.numpy.flipud', v1=[]) +@np_utils.np_doc('flipud') +def flipud(m): # pylint: disable=missing-docstring + return flip(m, 0) + + +@tf_export.tf_export('experimental.numpy.fliplr', v1=[]) +@np_utils.np_doc('fliplr') +def fliplr(m): # pylint: disable=missing-docstring + return flip(m, 1) + + +@tf_export.tf_export('experimental.numpy.roll', v1=[]) +@np_utils.np_doc('roll') +def roll(a, shift, axis=None): # pylint: disable=missing-docstring + a = asarray(a) + + if axis is not None: + return manip_ops.roll(a, shift, axis) + + # If axis is None, the roll happens as a 1-d tensor. + original_shape = array_ops.shape(a) + a = manip_ops.roll(array_ops.reshape(a, [-1]), shift, 0) + return array_ops.reshape(a, original_shape) + + +@tf_export.tf_export('experimental.numpy.rot90', v1=[]) +@np_utils.np_doc('rot90') +def rot90(m, k=1, axes=(0, 1)): # pylint: disable=missing-docstring + m_rank = array_ops.rank(m) + ax1, ax2 = np_utils._canonicalize_axes(axes, m_rank) # pylint: disable=protected-access + + k = k % 4 + if k == 0: + return m + elif k == 2: + return flip(flip(m, ax1), ax2) + else: + perm = math_ops.range(m_rank) + perm = array_ops.tensor_scatter_update(perm, [[ax1], [ax2]], [ax2, ax1]) + + if k == 1: + return transpose(flip(m, ax2), perm) + else: + return flip(transpose(m, perm), ax2) + + +@tf_export.tf_export('experimental.numpy.vander', v1=[]) +@np_utils.np_doc('vander') +def vander(x, N=None, increasing=False): # pylint: disable=missing-docstring,invalid-name + x = asarray(x) + + x_shape = array_ops.shape(x) + if N is None: + N = x_shape[0] + + N_temp = np_utils.get_static_value(N) # pylint: disable=invalid-name + if N_temp is not None: + N = N_temp + if N < 0: + raise ValueError('N must be nonnegative') + else: + control_flow_assert.Assert(N >= 0, [N]) + + rank = array_ops.rank(x) + rank_temp = np_utils.get_static_value(rank) + if rank_temp is not None: + rank = rank_temp + if rank != 1: + raise ValueError('x must be a one-dimensional array') + else: + control_flow_assert.Assert(math_ops.equal(rank, 1), [rank]) + + if increasing: + start = 0 + limit = N + delta = 1 + else: + start = N - 1 + limit = -1 + delta = -1 + + x = array_ops.expand_dims(x, -1) + return math_ops.pow( + x, math_ops.cast(math_ops.range(start, limit, delta), dtype=x.dtype) + ) + + +@tf_export.tf_export('experimental.numpy.ix_', v1=[]) +@np_utils.np_doc('ix_') +def ix_(*args): # pylint: disable=missing-docstring + n = len(args) + output = [] + for i, a in enumerate(args): + a = asarray(a) + a_rank = array_ops.rank(a) + a_rank_temp = np_utils.get_static_value(a_rank) + if a_rank_temp is not None: + a_rank = a_rank_temp + if a_rank != 1: + raise ValueError( + 'Arguments must be 1-d, got arg {} of rank {}'.format(i, a_rank) + ) + else: + control_flow_assert.Assert(math_ops.equal(a_rank, 1), [a_rank]) + + new_shape = [1] * n + new_shape[i] = -1 + dtype = a.dtype + if dtype == dtypes.bool: + output.append(array_ops.reshape(nonzero(a)[0], new_shape)) + elif dtype.is_integer: + output.append(array_ops.reshape(a, new_shape)) + else: + raise ValueError( + 'Only integer and bool dtypes are supported, got {}'.format(dtype) + ) + + return output + + +@tf_export.tf_export('experimental.numpy.broadcast_arrays', v1=[]) +@np_utils.np_doc('broadcast_arrays') +def broadcast_arrays(*args, **kwargs): # pylint: disable=missing-docstring + subok = kwargs.pop('subok', False) + if subok: + raise ValueError('subok=True is not supported.') + if kwargs: + raise ValueError('Received unsupported arguments {}'.format(kwargs.keys())) + + args = [asarray(arg) for arg in args] + return np_utils.tf_broadcast(*args) + + +@tf_export.tf_export('experimental.numpy.sign', v1=[]) +@np_utils.np_doc_only('sign') +def sign(x, out=None, where=None, **kwargs): # pylint: disable=missing-docstring,redefined-outer-name + if out: + raise ValueError('tf.numpy doesnt support setting out.') + if where: + raise ValueError('tf.numpy doesnt support setting where.') + if kwargs: + raise ValueError('tf.numpy doesnt support setting {}'.format(kwargs.keys())) + + x = asarray(x) + dtype = x.dtype.as_numpy_dtype + if np.issubdtype(dtype, np.complexfloating): + result = math_ops.cast(math_ops.sign(math_ops.real(x)), dtype) + else: + result = math_ops.sign(x) + + return result + + +# Note that np.take_along_axis may not be present in some supported versions of +# numpy. +@tf_export.tf_export('experimental.numpy.take_along_axis', v1=[]) +@np_utils.np_doc('take_along_axis') +def take_along_axis(arr, indices, axis): # pylint: disable=missing-docstring + arr = asarray(arr) + indices = asarray(indices) + + if axis is None: + return take_along_axis(arr.ravel(), indices, 0) + + rank = array_ops.rank(arr) + axis = axis + rank if axis < 0 else axis + + # Broadcast shapes to match, ensure that the axis of interest is not + # broadcast. + arr_shape_original = array_ops.shape(arr, out_type=indices.dtype) + indices_shape_original = array_ops.shape(indices, out_type=indices.dtype) + arr_shape = array_ops.tensor_scatter_update(arr_shape_original, [[axis]], [1]) + indices_shape = array_ops.tensor_scatter_update( + indices_shape_original, [[axis]], [1] + ) + broadcasted_shape = array_ops.broadcast_dynamic_shape( + arr_shape, indices_shape + ) + arr_shape = array_ops.tensor_scatter_update( + broadcasted_shape, [[axis]], [arr_shape_original[axis]] + ) + indices_shape = array_ops.tensor_scatter_update( + broadcasted_shape, [[axis]], [indices_shape_original[axis]] + ) + arr = array_ops.broadcast_to(arr, arr_shape) + indices = array_ops.broadcast_to(indices, indices_shape) + + # Save indices shape so we can restore it later. + possible_result_shape = indices.shape + + # Correct indices since gather doesn't correctly handle negative indices. + indices = array_ops.where_v2(indices < 0, indices + arr_shape[axis], indices) + + swapaxes_ = lambda t: swapaxes(t, axis, -1) + + dont_move_axis_to_end = math_ops.equal(axis, np_utils.subtract(rank, 1)) + arr = np_utils.cond( + dont_move_axis_to_end, lambda: arr, lambda: swapaxes_(arr) + ) + indices = np_utils.cond( + dont_move_axis_to_end, lambda: indices, lambda: swapaxes_(indices) + ) + + arr_shape = array_ops.shape(arr) + arr = array_ops.reshape(arr, [-1, arr_shape[-1]]) + + indices_shape = array_ops.shape(indices) + indices = array_ops.reshape(indices, [-1, indices_shape[-1]]) + + result = array_ops.gather(arr, indices, batch_dims=1) + result = array_ops.reshape(result, indices_shape) + result = np_utils.cond( + dont_move_axis_to_end, lambda: result, lambda: swapaxes_(result) + ) + result.set_shape(possible_result_shape) + + return result + + +# pylint: disable=redefined-builtin,undefined-variable +@tf_export.tf_export('experimental.numpy.max', v1=[]) +@np_utils.np_doc('max', link=np_utils.AliasOf('amax')) +def max(a, axis=None, keepdims=None): + return amax(a, axis=axis, keepdims=keepdims) + + +@tf_export.tf_export('experimental.numpy.min', v1=[]) +@np_utils.np_doc('min', link=np_utils.AliasOf('amin')) +def min(a, axis=None, keepdims=None): + return amin(a, axis=axis, keepdims=keepdims) + + +@tf_export.tf_export('experimental.numpy.round', v1=[]) +@np_utils.np_doc('round', link=np_utils.AliasOf('around')) +def round(a, decimals=0): + return around(a, decimals=decimals) + + +# pylint: enable=redefined-builtin,undefined-variable + + +_SLICE_ERROR = ( + 'only integers, slices (`:`), ellipsis (`...`), ' + 'numpy.newaxis (`None`) and integer or boolean arrays are valid indices' +) + + +def _as_index(idx, need_scalar=True): + """Helper function to parse idx as an index. + + Args: + idx: index + need_scalar: If idx needs to be a scalar value. + + Returns: + A pair, (indx, bool). First one is the parsed index and can be a tensor, + or scalar integer / Dimension. Second one is True if rank is known to be 0. + + Raises: + IndexError: For incorrect indices. + """ + if isinstance(idx, (numbers.Integral, tensor_shape.Dimension)): + return idx, True + data = asarray(idx) + if data.dtype == dtypes.bool: + if data.shape.ndims != 1: + # TODO(agarwal): handle higher rank boolean masks. + raise NotImplementedError('Need rank 1 for bool index %s' % idx) + data = array_ops.where_v2(data) + data = array_ops.reshape(data, [-1]) + if need_scalar and data.shape.rank not in (None, 0): + raise IndexError(_SLICE_ERROR + ', got {!r}'.format(idx)) + np_dtype = data.dtype.as_numpy_dtype + if not np.issubdtype(np_dtype, np.integer): + raise IndexError(_SLICE_ERROR + ', got {!r}'.format(idx)) + if data.dtype not in (dtypes.int64, dtypes.int32): + # TF slicing can only handle int32/int64. So we need to cast. + promoted_dtype = np.promote_types(np.int32, np_dtype) + if promoted_dtype == np.int32: + data = math_ops.cast(data, dtypes.int32) + elif promoted_dtype == np.int64: + data = math_ops.cast(data, dtypes.int64) + else: + raise IndexError(_SLICE_ERROR + ', got {!r}'.format(idx)) + return data, data.shape.rank == 0 + + +class _UpdateMethod(enum.Enum): + UPDATE = 0 + ADD = 1 + MIN = 2 + MAX = 3 + + +def _slice_helper(tensor, slice_spec, update_method=None, updates=None): + """Helper function for __getitem__ and _with_index_update_helper. + + This function collects the indices in `slice_spec` into two buckets, which we + can call "idx1" and "idx2" here. idx1 is intended for `strided_slice`, idx2 + `gather`. They also correspond to "basic indices" and "advanced indices" in + numpy. This function supports both reading and writing at the indices. The + reading path can be summarized as `gather(stride_slice(tensor, idx1), + idx2)`. The writing path can be summarized as `strided_slice_update(tensor, + idx1, scatter(strided_slice(tensor, idx1), idx2, updates))`. (`gather` here + means `tf.gather` or `tf.gather_nd`; `scatter` here means + `tf.tensor_scatter_update`.) The writing path is inefficient because it needs + to first read out a portion (probably much larger than `updates`) of `tensor` + using `strided_slice`, update it, and then write the portion back. An + alternative approach is to only use `scatter`, which amounts to using the + indexing mechanism of gather/scatter to implement + strided_slice/strided_slice_update. This is feasible for XLA Gather/Scatter + because they support spans (e.g. `2:5`) in indices (as begin/end pairs), but + not TF gather/scatter because they don't support spans (except those that + cover entire dimensions, i.e. `:`). If we materialize spans into individual + indices, the size of the index tensor would explode. (Note that XLA + Gather/Scatter have a similar problem for stride > 1 because they don't + support strides. Indices such as `1:2:8` will need to be materialized into + individual indices such as [1, 3, 5, 7].) + + Args: + tensor: the tensor to be read from or write into. + slice_spec: the indices. + update_method: (optional) a member of `_UpdateMethod`, indicating how to + update the values (replacement, add, etc.). `None` indicates just reading. + updates: (optional) the new values to write into `tensor`. It must have the + same dtype as `tensor`. + + Returns: + The result of reading (if `update_method` is `None`) or the updated `tensor` + after writing. + """ + begin, end, strides = [], [], [] + new_axis_mask, shrink_axis_mask = 0, 0 + begin_mask, end_mask = 0, 0 + ellipsis_mask = 0 + advanced_indices = [] + shrink_indices = [] + for index, s in enumerate(slice_spec): + if isinstance(s, slice): + if s.start is not None: + begin.append(_as_index(s.start)[0]) + else: + begin.append(0) + begin_mask |= 1 << index + if s.stop is not None: + end.append(_as_index(s.stop)[0]) + else: + end.append(0) + end_mask |= 1 << index + if s.step is not None: + strides.append(_as_index(s.step)[0]) + else: + strides.append(1) + elif s is Ellipsis: + begin.append(0) + end.append(0) + strides.append(1) + ellipsis_mask |= 1 << index + elif s is array_ops.newaxis: + begin.append(0) + end.append(0) + strides.append(1) + new_axis_mask |= 1 << index + else: + s, is_scalar = _as_index(s, False) + if is_scalar: + begin.append(s) + end.append(s + 1) + strides.append(1) + shrink_axis_mask |= 1 << index + shrink_indices.append(index) + else: + begin.append(0) + end.append(0) + strides.append(1) + begin_mask |= 1 << index + end_mask |= 1 << index + advanced_indices.append((index, s, ellipsis_mask != 0)) + + # stack possibly involves no tensors, so we must use op_scope correct graph. + with ops.name_scope( + None, + 'strided_slice', + [tensor] + begin + end + strides, + skip_on_eager=False, + ) as name: + if begin: + packed_begin, packed_end, packed_strides = ( + array_ops_stack.stack(begin), + array_ops_stack.stack(end), + array_ops_stack.stack(strides), + ) + if ( + packed_begin.dtype == dtypes.int64 + or packed_end.dtype == dtypes.int64 + or packed_strides.dtype == dtypes.int64 + ): + if packed_begin.dtype != dtypes.int64: + packed_begin = math_ops.cast(packed_begin, dtypes.int64) + if packed_end.dtype != dtypes.int64: + packed_end = math_ops.cast(packed_end, dtypes.int64) + if packed_strides.dtype != dtypes.int64: + packed_strides = math_ops.cast(packed_strides, dtypes.int64) + else: + var_empty = constant_op.constant([], dtype=dtypes.int32) + packed_begin = packed_end = packed_strides = var_empty + if update_method == _UpdateMethod.UPDATE and not advanced_indices: + return array_ops.tensor_strided_slice_update( + tensor, + packed_begin, + packed_end, + packed_strides, + updates, + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask, + name=name, + ) + else: + # TODO(b/164251540): Find a better way to support update that does not + # involve one read + two writes. + if updates is not None: + original_tensor = tensor + # TODO(agarwal): set_shape on tensor to set rank. + tensor = array_ops.strided_slice( + tensor, + packed_begin, + packed_end, + packed_strides, + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask, + name=name, + ) + if not advanced_indices: + if update_method is None: + return tensor + assert update_method != _UpdateMethod.UPDATE + # TF lacks TensorStridedSliceAdd and alike, so we need to do + # read+add+update. + if update_method == _UpdateMethod.ADD: + update_op = math_ops.add + elif update_method == _UpdateMethod.MIN: + update_op = math_ops.minimum + elif update_method == _UpdateMethod.MAX: + update_op = math_ops.maximum + return array_ops.tensor_strided_slice_update( + original_tensor, + packed_begin, + packed_end, + packed_strides, + update_op(tensor, updates), + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask, + name=name + '_2', + ) + advanced_indices_map = {} + for index, data, had_ellipsis in advanced_indices: + if had_ellipsis: + num_shrink = len([x for x in shrink_indices if x > index]) + dim = index - len(slice_spec) + num_shrink + else: + num_shrink = len([x for x in shrink_indices if x < index]) + dim = index - num_shrink + advanced_indices_map[dim] = data + dims = sorted(advanced_indices_map.keys()) + dims_contiguous = True + if len(dims) > 1: + if dims[0] < 0 and dims[-1] >= 0: # not all same sign + dims_contiguous = False + else: + for i in range(len(dims) - 1): + if dims[i] + 1 != dims[i + 1]: + dims_contiguous = False + break + indices = [advanced_indices_map[x] for x in dims] + indices = _promote_dtype(*indices) + indices = np_utils.tf_broadcast(*indices) + stacked_indices = array_ops_stack.stack(indices, axis=-1) + # Skip the contiguous-dims optimization for update because there is no + # tf.*scatter* op that supports the `axis` argument. + if not dims_contiguous or updates is not None: + if range(len(dims)) != dims: + tensor = moveaxis(tensor, dims, range(len(dims))) + tensor_shape_prefix = array_ops.shape( + tensor, out_type=stacked_indices.dtype + )[: len(dims)] + stacked_indices = array_ops.where_v2( + stacked_indices < 0, + stacked_indices + tensor_shape_prefix, + stacked_indices, + ) + if updates is None: + return array_ops.gather_nd(tensor, stacked_indices) + else: + # We only need to move-axis `updates` in the contiguous case becausce + # only in this case the result dimensions of advanced indexing are in + # the middle of `updates`. In the non-contiguous case, those dimensions + # are always at the front. + if dims_contiguous: + # TODO(wangpeng): Support unknown rank (e.g. by partially flattening + # `updates`) + if stacked_indices.shape.rank is None: + raise NotImplementedError( + 'Rank of the advanced indices must currently be known' + ) + batch_size = stacked_indices.shape.rank - 1 + batch_start = dims[0] + if batch_start < 0: + batch_start += len(dims) - batch_size + + def range_(start, length): + return range(start, start + length) + + updates = moveaxis( + updates, range_(batch_start, batch_size), range(batch_size) + ) + if update_method == _UpdateMethod.UPDATE: + update_op = array_ops.tensor_scatter_update + elif update_method == _UpdateMethod.ADD: + update_op = array_ops.tensor_scatter_add + elif update_method == _UpdateMethod.MIN: + update_op = array_ops.tensor_scatter_min + elif update_method == _UpdateMethod.MAX: + update_op = array_ops.tensor_scatter_max + tensor = update_op(tensor, stacked_indices, updates) + if range(len(dims)) != dims: + tensor = moveaxis(tensor, range(len(dims)), dims) + return array_ops.tensor_strided_slice_update( + original_tensor, + packed_begin, + packed_end, + packed_strides, + tensor, + begin_mask=begin_mask, + end_mask=end_mask, + shrink_axis_mask=shrink_axis_mask, + new_axis_mask=new_axis_mask, + ellipsis_mask=ellipsis_mask, + name=name + '_2', + ) + # Note that gather_nd does not support gathering from inside the array. + # To avoid shuffling data back and forth, we transform the indices and + # do a gather instead. + rank = np_utils._maybe_static(array_ops.rank(tensor)) # pylint: disable=protected-access + dims = [(x + rank if x < 0 else x) for x in dims] + shape_tensor = array_ops.shape(tensor) + dim_sizes = array_ops.gather(shape_tensor, dims) + if len(dims) == 1: + stacked_indices = indices[0] + stacked_indices = math_ops.cast(stacked_indices, dtypes.int32) + stacked_indices = array_ops.where_v2( + stacked_indices < 0, stacked_indices + dim_sizes, stacked_indices + ) + axis = dims[0] + if len(dims) > 1: + index_scaling = math_ops.cumprod(dim_sizes, reverse=True, exclusive=True) + + def _tensordot(a, b): + # TODO(b/168657656): This function should be replaced by + # tensordot(axis=1) once MatMul has int32 XLA kernel. + b = array_ops.broadcast_to(b, array_ops.shape(a)) + return math_ops.reduce_sum(a * b, axis=-1) + + stacked_indices = _tensordot(stacked_indices, index_scaling) + flat_shape = array_ops.concat( + [shape_tensor[:axis], [-1], shape_tensor[axis + len(dims) :]], axis=0 + ) + tensor = array_ops.reshape(tensor, flat_shape) + + return array_ops.gather(tensor, stacked_indices, axis=axis) + + +def _as_spec_tuple(slice_spec): + """Convert slice_spec to tuple.""" + if isinstance(slice_spec, (list, tuple)) and not isinstance( + slice_spec, np.ndarray + ): + is_index = True + for s in slice_spec: + if s is None or s is Ellipsis or isinstance(s, (list, tuple, slice)): + is_index = False + break + elif isinstance(s, (np_arrays.ndarray, np.ndarray)) and s.ndim != 0: + is_index = False + break + if not is_index: + return tuple(slice_spec) + return (slice_spec,) + + +def _getitem(self, slice_spec): + """Implementation of ndarray.__getitem__.""" + if ( + isinstance(slice_spec, bool) + or ( + isinstance(slice_spec, core_tf_types.Tensor) + and slice_spec.dtype == dtypes.bool + ) + or ( + isinstance(slice_spec, (np.ndarray, np_arrays.ndarray)) + and slice_spec.dtype == np.bool_ + ) + ): + return array_ops.boolean_mask(tensor=self, mask=slice_spec) + + if not isinstance(slice_spec, tuple): + slice_spec = _as_spec_tuple(slice_spec) + + result_t = _slice_helper(self, slice_spec) + return result_t + + +def _with_index_update_helper(update_method, a, slice_spec, updates): + """Implementation of ndarray._with_index_*.""" + if ( + isinstance(slice_spec, bool) + or ( + isinstance(slice_spec, core_tf_types.Tensor) + and slice_spec.dtype == dtypes.bool + ) + or ( + isinstance(slice_spec, (np.ndarray, np_arrays.ndarray)) + and slice_spec.dtype == np.bool_ + ) + ): + slice_spec = nonzero(slice_spec) + + if not isinstance(slice_spec, tuple): + slice_spec = _as_spec_tuple(slice_spec) + + a_dtype = a.dtype + a, updates = _promote_dtype_binary(a, updates) + result_t = _slice_helper(a, slice_spec, update_method, updates) + return result_t.astype(a_dtype) + + +setattr(np_arrays.ndarray, '_numpy_style_getitem', _getitem) +setattr( + np_arrays.ndarray, + '_with_index_update', + functools.partial(_with_index_update_helper, _UpdateMethod.UPDATE), +) +setattr( + np_arrays.ndarray, + '_with_index_add', + functools.partial(_with_index_update_helper, _UpdateMethod.ADD), +) +setattr( + np_arrays.ndarray, + '_with_index_min', + functools.partial(_with_index_update_helper, _UpdateMethod.MIN), +) +setattr( + np_arrays.ndarray, + '_with_index_max', + functools.partial(_with_index_update_helper, _UpdateMethod.MAX), +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_arrays.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_arrays.py new file mode 100644 index 0000000000000000000000000000000000000000..78257ae37ec66b9fe872bef42c17a2b6e317e0ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_arrays.py @@ -0,0 +1,50 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""ndarray class.""" + +# pylint: disable=g-direct-tensorflow-import + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.ops.numpy_ops import np_dtypes + + +def convert_to_tensor(value, dtype=None, dtype_hint=None): + """Wrapper over `tf.convert_to_tensor`. + + Args: + value: value to convert + dtype: (optional) the type we would like it to be converted to. + dtype_hint: (optional) soft preference for the type we would like it to be + converted to. `tf.convert_to_tensor` will attempt to convert value to this + type first, but will not fail if conversion is not possible falling back + to inferring the type instead. + + Returns: + Value converted to tf.Tensor. + """ + # A safer version of `tf.convert_to_tensor` to work around b/149876037. + # TODO(wangpeng): Remove this function once the bug is fixed. + if (dtype is None and isinstance(value, int) and + value >= 2**63): + dtype = dtypes.uint64 + elif dtype is None and dtype_hint is None and isinstance(value, float): + dtype = np_dtypes.default_float_type() + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + value, dtype=dtype, dtype_hint=dtype_hint) + + +ndarray = tensor.Tensor diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a80c38e2975b61fb0b3b5fc4a81a1194934803 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_config.py @@ -0,0 +1,58 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Config functions for TF NumPy.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import weak_tensor_ops # pylint: disable=unused-import +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.ops.numpy_ops import np_math_ops +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import tf_export + + +@tf_export.tf_export( + "experimental.numpy.experimental_enable_numpy_behavior", v1=[] +) +def enable_numpy_behavior(prefer_float32=False, dtype_conversion_mode="legacy"): + """Enable NumPy behavior on Tensors. + + Enabling NumPy behavior has three effects: + * It adds to `tf.Tensor` some common NumPy methods such as `T`, + `reshape` and `ravel`. + * It changes dtype promotion in `tf.Tensor` operators to be + compatible with NumPy. For example, + `tf.ones([], tf.int32) + tf.ones([], tf.float32)` used to throw a + "dtype incompatible" error, but after this it will return a + float64 tensor (obeying NumPy's promotion rules). + * It enhances `tf.Tensor`'s indexing capability to be on par with + [NumPy's](https://numpy.org/doc/stable/reference/arrays.indexing.html). + + Args: + prefer_float32: Controls whether dtype inference will use float32 for Python + floats, or float64 (the default and the NumPy-compatible behavior). + dtype_conversion_mode: a string that specifies promotion mode. This string + corresponds to a PromoMode Enum and can be 'off', 'legacy', 'safe', or + 'all'. 'safe' or 'all' mode enables the auto dtype conversion semantics. + """ + if dtype_conversion_mode == "safe" or dtype_conversion_mode == "all": + tf_logging.warning( + "UserWarning: enabling the new type promotion must happen at the" + " beginning of the program. Please ensure no TF APIs have been used" + " yet." + ) + ops.set_dtype_conversion_mode(dtype_conversion_mode) + ops.enable_numpy_style_slicing() + np_math_ops.enable_numpy_methods_on_tensor() + np_dtypes.set_prefer_float32(prefer_float32) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_dtypes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..00e2cdfc22964b7cf9ac0892171a0239d96ba404 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_dtypes.py @@ -0,0 +1,208 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Dtypes and dtype utilities.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.util import tf_export + + +# We use numpy's dtypes instead of TF's, because the user expects to use them +# with numpy facilities such as `np.dtype(np.int64)` and +# `if x.dtype.type is np.int64`. +bool_ = np.bool_ +tf_export.tf_export('experimental.numpy.bool_', v1=[]).export_constant( + __name__, 'bool_' +) +complex_ = np.complex_ +tf_export.tf_export('experimental.numpy.complex_', v1=[]).export_constant( + __name__, 'complex_' +) +complex128 = np.complex128 +tf_export.tf_export('experimental.numpy.complex128', v1=[]).export_constant( + __name__, 'complex128' +) +complex64 = np.complex64 +tf_export.tf_export('experimental.numpy.complex64', v1=[]).export_constant( + __name__, 'complex64' +) +float_ = np.float_ +tf_export.tf_export('experimental.numpy.float_', v1=[]).export_constant( + __name__, 'float_' +) +float16 = np.float16 +tf_export.tf_export('experimental.numpy.float16', v1=[]).export_constant( + __name__, 'float16' +) +float32 = np.float32 +tf_export.tf_export('experimental.numpy.float32', v1=[]).export_constant( + __name__, 'float32' +) +float64 = np.float64 +tf_export.tf_export('experimental.numpy.float64', v1=[]).export_constant( + __name__, 'float64' +) +inexact = np.inexact +tf_export.tf_export('experimental.numpy.inexact', v1=[]).export_constant( + __name__, 'inexact' +) +int_ = np.int_ +tf_export.tf_export('experimental.numpy.int_', v1=[]).export_constant( + __name__, 'int_' +) +int16 = np.int16 +tf_export.tf_export('experimental.numpy.int16', v1=[]).export_constant( + __name__, 'int16' +) +int32 = np.int32 +tf_export.tf_export('experimental.numpy.int32', v1=[]).export_constant( + __name__, 'int32' +) +int64 = np.int64 +tf_export.tf_export('experimental.numpy.int64', v1=[]).export_constant( + __name__, 'int64' +) +int8 = np.int8 +tf_export.tf_export('experimental.numpy.int8', v1=[]).export_constant( + __name__, 'int8' +) +object_ = np.object_ +tf_export.tf_export('experimental.numpy.object_', v1=[]).export_constant( + __name__, 'object_' +) +string_ = np.string_ +tf_export.tf_export('experimental.numpy.string_', v1=[]).export_constant( + __name__, 'string_' +) +uint16 = np.uint16 +tf_export.tf_export('experimental.numpy.uint16', v1=[]).export_constant( + __name__, 'uint16' +) +uint32 = np.uint32 +tf_export.tf_export('experimental.numpy.uint32', v1=[]).export_constant( + __name__, 'uint32' +) +uint64 = np.uint64 +tf_export.tf_export('experimental.numpy.uint64', v1=[]).export_constant( + __name__, 'uint64' +) +uint8 = np.uint8 +tf_export.tf_export('experimental.numpy.uint8', v1=[]).export_constant( + __name__, 'uint8' +) +unicode_ = np.unicode_ +tf_export.tf_export('experimental.numpy.unicode_', v1=[]).export_constant( + __name__, 'unicode_' +) + + +iinfo = np.iinfo +tf_export.tf_export('experimental.numpy.iinfo', v1=[]).export_constant( + __name__, 'iinfo' +) + + +issubdtype = tf_export.tf_export('experimental.numpy.issubdtype', v1=[])( + np.issubdtype +) + + +_to_float32 = { + np.dtype('float64'): np.dtype('float32'), + np.dtype('complex128'): np.dtype('complex64'), +} + + +_cached_np_dtypes = {} + + +# Difference between is_prefer_float32 and is_allow_float64: is_prefer_float32 +# only decides which dtype to use for Python floats; is_allow_float64 decides +# whether float64 dtypes can ever appear in programs. The latter is more +# restrictive than the former. +_prefer_float32 = False + + +# TODO(b/178862061): Consider removing this knob +_allow_float64 = True + + +def is_prefer_float32(): + return _prefer_float32 + + +def set_prefer_float32(b): + global _prefer_float32 + _prefer_float32 = b + + +def is_allow_float64(): + return _allow_float64 + + +def set_allow_float64(b): + global _allow_float64 + _allow_float64 = b + + +def canonicalize_dtype(dtype): + if not _allow_float64: + try: + return _to_float32[dtype] + except KeyError: + pass + return dtype + + +def _result_type(*arrays_and_dtypes): + """Returns the resulting type given a set of arrays.""" + + def preprocess_float(x): + if is_prefer_float32(): + if isinstance(x, float): + return np.float32(x) + elif isinstance(x, complex): + return np.complex64(x) + return x + + arrays_and_dtypes = [preprocess_float(x) for x in arrays_and_dtypes] + dtype = np.result_type(*arrays_and_dtypes) + return dtypes.as_dtype(canonicalize_dtype(dtype)) + + +def _get_cached_dtype(dtype): + """Returns an np.dtype for the TensorFlow DType.""" + global _cached_np_dtypes + try: + return _cached_np_dtypes[dtype] + except KeyError: + pass + cached_dtype = np.dtype(dtype.as_numpy_dtype) + _cached_np_dtypes[dtype] = cached_dtype + return cached_dtype + + +def default_float_type(): + """Gets the default float type. + + Returns: + If `is_prefer_float32()` is false and `is_allow_float64()` is true, returns + float64; otherwise returns float32. + """ + if not is_prefer_float32() and is_allow_float64(): + return float64 + else: + return float32 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc80ae6c4cf88b7cdca0ef453b2c9b97caa73ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_math_ops.py @@ -0,0 +1,1642 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Mathematical operations.""" +# pylint: disable=g-direct-tensorflow-import + +import numbers +import sys + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import bitwise_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.numpy_ops import np_array_ops +from tensorflow.python.ops.numpy_ops import np_arrays +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.ops.numpy_ops import np_utils +from tensorflow.python.util import tf_export + + +pi = np.pi +tf_export.tf_export('experimental.numpy.pi', v1=[]).export_constant( + __name__, 'pi' +) +e = np.e +tf_export.tf_export('experimental.numpy.e', v1=[]).export_constant( + __name__, 'e' +) +inf = np.inf +tf_export.tf_export('experimental.numpy.inf', v1=[]).export_constant( + __name__, 'inf' +) + + +@tf_export.tf_export('experimental.numpy.dot', v1=[]) +@np_utils.np_doc_only('dot') +def dot(a, b): # pylint: disable=missing-docstring + def f(a, b): # pylint: disable=missing-docstring + return np_utils.cond( + np_utils.logical_or( + math_ops.equal(array_ops.rank(a), 0), + math_ops.equal(array_ops.rank(b), 0), + ), + lambda: a * b, + lambda: np_utils.cond( # pylint: disable=g-long-lambda + math_ops.equal(array_ops.rank(b), 1), + lambda: math_ops.tensordot(a, b, axes=[[-1], [-1]]), + lambda: math_ops.tensordot(a, b, axes=[[-1], [-2]]), + ), + ) + + return _bin_op(f, a, b) + + +# TODO(wangpeng): Make element-wise ops `ufunc`s +def _bin_op(tf_fun, a, b, promote=True): + if promote: + a, b = np_array_ops._promote_dtype_binary(a, b) # pylint: disable=protected-access + else: + a = np_array_ops.array(a) + b = np_array_ops.array(b) + return tf_fun(a, b) + + +@tf_export.tf_export('experimental.numpy.add', v1=[]) +@np_utils.np_doc('add') +def add(x1, x2): + def add_or_or(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + return math_ops.logical_or(x1, x2) + return math_ops.add(x1, x2) + + return _bin_op(add_or_or, x1, x2) + + +@tf_export.tf_export('experimental.numpy.subtract', v1=[]) +@np_utils.np_doc('subtract') +def subtract(x1, x2): + return _bin_op(math_ops.subtract, x1, x2) + + +@tf_export.tf_export('experimental.numpy.multiply', v1=[]) +@np_utils.np_doc('multiply') +def multiply(x1, x2): + def mul_or_and(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + return math_ops.logical_and(x1, x2) + return math_ops.multiply(x1, x2) + + return _bin_op(mul_or_and, x1, x2) + + +@tf_export.tf_export('experimental.numpy.true_divide', v1=[]) +@np_utils.np_doc('true_divide') +def true_divide(x1, x2): # pylint: disable=missing-function-docstring + def _avoid_float64(x1, x2): + if x1.dtype == x2.dtype and x1.dtype in (dtypes.int32, dtypes.int64): + x1 = math_ops.cast(x1, dtype=dtypes.float32) + x2 = math_ops.cast(x2, dtype=dtypes.float32) + return x1, x2 + + def f(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + float_ = np_utils.result_type(float) + x1 = math_ops.cast(x1, float_) + x2 = math_ops.cast(x2, float_) + if not np_dtypes.is_allow_float64(): + # math_ops.truediv in Python3 produces float64 when both inputs are int32 + # or int64. We want to avoid that when is_allow_float64() is False. + x1, x2 = _avoid_float64(x1, x2) + return math_ops.truediv(x1, x2) + + return _bin_op(f, x1, x2) + + +@tf_export.tf_export('experimental.numpy.divide', v1=[]) +@np_utils.np_doc('divide') +def divide(x1, x2): # pylint: disable=missing-function-docstring + return true_divide(x1, x2) + + +@tf_export.tf_export('experimental.numpy.floor_divide', v1=[]) +@np_utils.np_doc('floor_divide') +def floor_divide(x1, x2): # pylint: disable=missing-function-docstring + def f(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + x1 = math_ops.cast(x1, dtypes.int8) + x2 = math_ops.cast(x2, dtypes.int8) + return math_ops.floordiv(x1, x2) + + return _bin_op(f, x1, x2) + + +@tf_export.tf_export('experimental.numpy.mod', v1=[]) +@np_utils.np_doc('mod') +def mod(x1, x2): # pylint: disable=missing-function-docstring + def f(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + x1 = math_ops.cast(x1, dtypes.int8) + x2 = math_ops.cast(x2, dtypes.int8) + return math_ops.mod(x1, x2) + + return _bin_op(f, x1, x2) + + +@tf_export.tf_export('experimental.numpy.remainder', v1=[]) +@np_utils.np_doc('remainder') +def remainder(x1, x2): # pylint: disable=missing-function-docstring + return mod(x1, x2) + + +@tf_export.tf_export('experimental.numpy.divmod', v1=[]) +@np_utils.np_doc('divmod') +def divmod(x1, x2): # pylint: disable=redefined-builtin + return floor_divide(x1, x2), mod(x1, x2) + + +@tf_export.tf_export('experimental.numpy.maximum', v1=[]) +@np_utils.np_doc('maximum') +def maximum(x1, x2): # pylint: disable=missing-function-docstring + # Fast path for when maximum is used as relu. + if ( + isinstance(x2, numbers.Real) + and not isinstance(x2, bool) + and x2 == 0 + and isinstance(x1, np_arrays.ndarray) + and x1.dtype != dtypes.bool + ): + return nn_ops.relu(np_array_ops.asarray(x1)) + + def max_or_or(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + return math_ops.logical_or(x1, x2) + return math_ops.maximum(x1, x2) + + return _bin_op(max_or_or, x1, x2) + + +@tf_export.tf_export('experimental.numpy.minimum', v1=[]) +@np_utils.np_doc('minimum') +def minimum(x1, x2): + def min_or_and(x1, x2): + if x1.dtype == dtypes.bool: + assert x2.dtype == dtypes.bool + return math_ops.logical_and(x1, x2) + return math_ops.minimum(x1, x2) + + return _bin_op(min_or_and, x1, x2) + + +@tf_export.tf_export('experimental.numpy.clip', v1=[]) +@np_utils.np_doc('clip') +def clip(a, a_min, a_max): # pylint: disable=missing-docstring + if a_min is None and a_max is None: + raise ValueError('Not more than one of `a_min` and `a_max` may be `None`.') + if a_min is None: + return minimum(a, a_max) + elif a_max is None: + return maximum(a, a_min) + else: + a, a_min, a_max = np_array_ops._promote_dtype(a, a_min, a_max) # pylint: disable=protected-access + return clip_ops.clip_by_value(*np_utils.tf_broadcast(a, a_min, a_max)) + + +@tf_export.tf_export('experimental.numpy.matmul', v1=[]) +@np_utils.np_doc('matmul') +def matmul(x1, x2): # pylint: disable=missing-docstring + def f(x1, x2): + try: + if x1._rank() == 2 and x2._rank() == 2: # pylint: disable=protected-access + # Fast path for known ranks. + return gen_math_ops.mat_mul(x1, x2) + return np_utils.cond( + math_ops.equal(np_utils.tf_rank(x2), 1), + lambda: math_ops.tensordot(x1, x2, axes=1), + lambda: np_utils.cond( # pylint: disable=g-long-lambda + math_ops.equal(np_utils.tf_rank(x1), 1), + lambda: math_ops.tensordot( # pylint: disable=g-long-lambda + x1, x2, axes=[[0], [-2]] + ), + lambda: math_ops.matmul(x1, x2), + ), + ) + except errors.InvalidArgumentError as err: + raise ValueError(str(err)).with_traceback(sys.exc_info()[2]) + + return _bin_op(f, x1, x2) + + +# Exported so it can be called from Tensor.__matmul__. NumPy's matmul handles +# batched matmul as well, so simply including promotion in TF's current +# __matmul__ implementation was not sufficient. +setattr(np_arrays.ndarray, '_matmul', matmul) + + +@tf_export.tf_export('experimental.numpy.tensordot', v1=[]) +@np_utils.np_doc('tensordot') +def tensordot(a, b, axes=2): + return _bin_op(lambda a, b: math_ops.tensordot(a, b, axes=axes), a, b) + + +@tf_export.tf_export('experimental.numpy.inner', v1=[]) +@np_utils.np_doc_only('inner') +def inner(a, b): # pylint: disable=missing-function-docstring + def f(a, b): + return np_utils.cond( + np_utils.logical_or( + math_ops.equal(array_ops.rank(a), 0), + math_ops.equal(array_ops.rank(b), 0), + ), + lambda: a * b, + lambda: math_ops.tensordot(a, b, axes=[[-1], [-1]]), + ) + + return _bin_op(f, a, b) + + +@tf_export.tf_export('experimental.numpy.cross', v1=[]) +@np_utils.np_doc('cross') +def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): # pylint: disable=missing-docstring + def f(a, b): # pylint: disable=missing-docstring + # We can't assign to captured variable `axisa`, so make a new variable + if axis is None: + axis_a = axisa + axis_b = axisb + axis_c = axisc + else: + axis_a = axis + axis_b = axis + axis_c = axis + if axis_a < 0: + axis_a = np_utils.add(axis_a, array_ops.rank(a)) + if axis_b < 0: + axis_b = np_utils.add(axis_b, array_ops.rank(b)) + + def maybe_move_axis_to_last(a, axis): + def move_axis_to_last(a, axis): + return array_ops.transpose( + a, + array_ops.concat( + [ + math_ops.range(axis), + math_ops.range(axis + 1, array_ops.rank(a)), + [axis], + ], + axis=0, + ), + ) + + return np_utils.cond( + axis == np_utils.subtract(array_ops.rank(a), 1), + lambda: a, + lambda: move_axis_to_last(a, axis), + ) + + a = maybe_move_axis_to_last(a, axis_a) + b = maybe_move_axis_to_last(b, axis_b) + a_dim = np_utils.getitem(array_ops.shape(a), -1) + b_dim = np_utils.getitem(array_ops.shape(b), -1) + + def maybe_pad_0(a, size_of_last_dim): + def pad_0(a): + return array_ops.pad( + a, + array_ops.concat( + [ + array_ops.zeros([array_ops.rank(a) - 1, 2], dtypes.int32), + constant_op.constant([[0, 1]], dtypes.int32), + ], + axis=0, + ), + ) + + return np_utils.cond( + math_ops.equal(size_of_last_dim, 2), lambda: pad_0(a), lambda: a + ) + + a = maybe_pad_0(a, a_dim) + b = maybe_pad_0(b, b_dim) + c = math_ops.cross(*np_utils.tf_broadcast(a, b)) + if axis_c < 0: + axis_c = np_utils.add(axis_c, array_ops.rank(c)) + + def move_last_to_axis(a, axis): + r = array_ops.rank(a) + return array_ops.transpose( + a, + array_ops.concat( + [math_ops.range(axis), [r - 1], math_ops.range(axis, r - 1)], + axis=0, + ), + ) + + c = np_utils.cond( + (a_dim == 2) & (b_dim == 2), + lambda: c[..., 2], + lambda: np_utils.cond( # pylint: disable=g-long-lambda + axis_c == np_utils.subtract(array_ops.rank(c), 1), + lambda: c, + lambda: move_last_to_axis(c, axis_c), + ), + ) + return c + + return _bin_op(f, a, b) + + +@tf_export.tf_export('experimental.numpy.vdot', v1=[]) +@np_utils.np_doc_only('vdot') +def vdot(a, b): # pylint: disable=missing-docstring + a, b = np_array_ops._promote_dtype(a, b) # pylint: disable=protected-access + a = np_array_ops.reshape(a, [-1]) + b = np_array_ops.reshape(b, [-1]) + if a.dtype == np_dtypes.complex128 or a.dtype == np_dtypes.complex64: + a = conj(a) + return dot(a, b) + + +@tf_export.tf_export('experimental.numpy.power', v1=[]) +@np_utils.np_doc('power') +def power(x1, x2): + return _bin_op(math_ops.pow, x1, x2) + + +@tf_export.tf_export('experimental.numpy.float_power', v1=[]) +@np_utils.np_doc('float_power') +def float_power(x1, x2): + return power(x1, x2) + + +@tf_export.tf_export('experimental.numpy.arctan2', v1=[]) +@np_utils.np_doc('arctan2') +def arctan2(x1, x2): + return _bin_op(math_ops.atan2, x1, x2) + + +@tf_export.tf_export('experimental.numpy.nextafter', v1=[]) +@np_utils.np_doc('nextafter') +def nextafter(x1, x2): + return _bin_op(math_ops.nextafter, x1, x2) + + +@tf_export.tf_export('experimental.numpy.heaviside', v1=[]) +@np_utils.np_doc('heaviside') +def heaviside(x1, x2): # pylint: disable=missing-function-docstring + def f(x1, x2): + return array_ops.where_v2( + x1 < 0, + constant_op.constant(0, dtype=x2.dtype), + array_ops.where_v2(x1 > 0, constant_op.constant(1, dtype=x2.dtype), x2), + ) + + y = _bin_op(f, x1, x2) + if not np.issubdtype(y.dtype.as_numpy_dtype, np.inexact): + y = y.astype(np_utils.result_type(float)) + return y + + +@tf_export.tf_export('experimental.numpy.hypot', v1=[]) +@np_utils.np_doc('hypot') +def hypot(x1, x2): + return sqrt(square(x1) + square(x2)) + + +@tf_export.tf_export('experimental.numpy.kron', v1=[]) +@np_utils.np_doc('kron') +def kron(a, b): # pylint: disable=missing-function-docstring + # pylint: disable=protected-access,g-complex-comprehension + a, b = np_array_ops._promote_dtype(a, b) + t_a = np_utils.cond( + a.shape.rank < b.shape.rank, + lambda: np_array_ops.reshape( # pylint: disable=g-long-lambda + a, np_array_ops._pad_left_to(b.shape.rank, a.shape) + ), + lambda: a, + ) + t_b = np_utils.cond( + b.shape.rank < a.shape.rank, + lambda: np_array_ops.reshape( # pylint: disable=g-long-lambda + b, np_array_ops._pad_left_to(a.shape.rank, b.shape) + ), + lambda: b, + ) + + def _make_shape(shape, prepend): + ones = array_ops.ones_like(shape) + if prepend: + shapes = [ones, shape] + else: + shapes = [shape, ones] + return array_ops.reshape(array_ops_stack.stack(shapes, axis=1), [-1]) + + a_shape = array_ops.shape(t_a) + b_shape = array_ops.shape(t_b) + a_reshaped = np_array_ops.reshape(t_a, _make_shape(a_shape, False)) + b_reshaped = np_array_ops.reshape(t_b, _make_shape(b_shape, True)) + out_shape = a_shape * b_shape + return np_array_ops.reshape(a_reshaped * b_reshaped, out_shape) + + +@tf_export.tf_export('experimental.numpy.outer', v1=[]) +@np_utils.np_doc('outer') +def outer(a, b): + def f(a, b): + return array_ops.reshape(a, [-1, 1]) * array_ops.reshape(b, [-1]) + + return _bin_op(f, a, b) + + +# This can also be implemented via tf.reduce_logsumexp +@tf_export.tf_export('experimental.numpy.logaddexp', v1=[]) +@np_utils.np_doc('logaddexp') +def logaddexp(x1, x2): + amax = maximum(x1, x2) + delta = x1 - x2 + return np_array_ops.where( + isnan(delta), + x1 + x2, # NaNs or infinities of the same sign. + amax + log1p(exp(-abs(delta))), + ) + + +@tf_export.tf_export('experimental.numpy.logaddexp2', v1=[]) +@np_utils.np_doc('logaddexp2') +def logaddexp2(x1, x2): + amax = maximum(x1, x2) + delta = x1 - x2 + return np_array_ops.where( + isnan(delta), + x1 + x2, # NaNs or infinities of the same sign. + amax + log1p(exp2(-abs(delta))) / np.log(2), + ) + + +@tf_export.tf_export('experimental.numpy.polyval', v1=[]) +@np_utils.np_doc('polyval') +def polyval(p, x): # pylint: disable=missing-function-docstring + def f(p, x): + if p.shape.rank == 0: + p = array_ops.reshape(p, [1]) + p = array_ops_stack.unstack(p) + # TODO(wangpeng): Make tf version take a tensor for p instead of a list. + y = math_ops.polyval(p, x) + # If the polynomial is 0-order, numpy requires the result to be broadcast to + # `x`'s shape. + if len(p) == 1: + y = array_ops.broadcast_to(y, x.shape) + return y + + return _bin_op(f, p, x) + + +@tf_export.tf_export('experimental.numpy.isclose', v1=[]) +@np_utils.np_doc('isclose') +def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): # pylint: disable=missing-docstring + def f(a, b): # pylint: disable=missing-docstring + dtype = a.dtype + if np.issubdtype(dtype.as_numpy_dtype, np.inexact): + rtol_ = ops.convert_to_tensor(rtol, dtype.real_dtype) + atol_ = ops.convert_to_tensor(atol, dtype.real_dtype) + result = math_ops.abs(a - b) <= atol_ + rtol_ * math_ops.abs(b) + if equal_nan: + result = result | (math_ops.is_nan(a) & math_ops.is_nan(b)) + return result + else: + return a == b + + return _bin_op(f, a, b) + + +@tf_export.tf_export('experimental.numpy.allclose', v1=[]) +@np_utils.np_doc('allclose') +def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + return np_array_ops.all( + isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan) + ) + + +def _tf_gcd(x1, x2): # pylint: disable=missing-function-docstring + def _gcd_cond_fn(_, x2): + return math_ops.reduce_any(x2 != 0) + + def _gcd_body_fn(x1, x2): + # math_ops.mod will raise an error when any element of x2 is 0. To avoid + # that, we change those zeros to ones. Their values don't matter because + # they won't be used. + x2_safe = array_ops.where_v2(x2 != 0, x2, constant_op.constant(1, x2.dtype)) + x1, x2 = ( + array_ops.where_v2(x2 != 0, x2, x1), + array_ops.where_v2( + x2 != 0, + math_ops.mod(x1, x2_safe), + constant_op.constant(0, x2.dtype), + ), + ) + return ( + array_ops.where_v2(x1 < x2, x2, x1), + array_ops.where_v2(x1 < x2, x1, x2), + ) + + if not np.issubdtype( + x1.dtype.as_numpy_dtype, np.integer + ) or not np.issubdtype(x2.dtype.as_numpy_dtype, np.integer): + raise ValueError('Arguments to gcd must be integers.') + shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(x1), array_ops.shape(x2) + ) + x1 = array_ops.broadcast_to(x1, shape) + x2 = array_ops.broadcast_to(x2, shape) + value, _ = while_loop.while_loop( + _gcd_cond_fn, _gcd_body_fn, (math_ops.abs(x1), math_ops.abs(x2)) + ) + return value + + +# Note that np.gcd may not be present in some supported versions of numpy. +@tf_export.tf_export('experimental.numpy.gcd', v1=[]) +@np_utils.np_doc('gcd') +def gcd(x1, x2): + return _bin_op(_tf_gcd, x1, x2) + + +# Note that np.lcm may not be present in some supported versions of numpy. +@tf_export.tf_export('experimental.numpy.lcm', v1=[]) +@np_utils.np_doc('lcm') +def lcm(x1, x2): # pylint: disable=missing-function-docstring + def f(x1, x2): + d = _tf_gcd(x1, x2) + # Same as the `x2_safe` trick above + d_safe = array_ops.where_v2( + math_ops.equal(d, 0), constant_op.constant(1, d.dtype), d + ) + x1 = math_ops.abs(x1) + x2 = math_ops.abs(x2) + return array_ops.where_v2( + math_ops.equal(d, 0), + constant_op.constant(0, d.dtype), + x1 * (x2 // d_safe), + ) + + return _bin_op(f, x1, x2) + + +def _bitwise_binary_op(tf_fn, x1, x2): # pylint: disable=missing-function-docstring + def f(x1, x2): + is_bool = x1.dtype == dtypes.bool + if is_bool: + assert x2.dtype == dtypes.bool + x1 = math_ops.cast(x1, dtypes.int8) + x2 = math_ops.cast(x2, dtypes.int8) + r = tf_fn(x1, x2) + if is_bool: + r = math_ops.cast(r, dtypes.bool) + return r + + return _bin_op(f, x1, x2) + + +@tf_export.tf_export('experimental.numpy.bitwise_and', v1=[]) +@np_utils.np_doc('bitwise_and') +def bitwise_and(x1, x2): + return _bitwise_binary_op(bitwise_ops.bitwise_and, x1, x2) + + +@tf_export.tf_export('experimental.numpy.bitwise_or', v1=[]) +@np_utils.np_doc('bitwise_or') +def bitwise_or(x1, x2): + return _bitwise_binary_op(bitwise_ops.bitwise_or, x1, x2) + + +@tf_export.tf_export('experimental.numpy.bitwise_xor', v1=[]) +@np_utils.np_doc('bitwise_xor') +def bitwise_xor(x1, x2): + return _bitwise_binary_op(bitwise_ops.bitwise_xor, x1, x2) + + +@tf_export.tf_export('experimental.numpy.bitwise_not', v1=[]) +@np_utils.np_doc('bitwise_not', link=np_utils.AliasOf('invert')) +def bitwise_not(x): + def f(x): + if x.dtype == dtypes.bool: + return math_ops.logical_not(x) + return bitwise_ops.invert(x) + + return _scalar(f, x) + + +def _scalar(tf_fn, x, promote_to_float=False): + """Computes the tf_fn(x) for each element in `x`. + + Args: + tf_fn: function that takes a single Tensor argument. + x: array_like. Could be an ndarray, a Tensor or any object that can be + converted to a Tensor using `ops.convert_to_tensor`. + promote_to_float: whether to cast the argument to a float dtype if it is not + already. + + Returns: + An ndarray with the same shape as `x`. The default output dtype is + determined by `np_utils.result_type(float)`, unless x is an ndarray with a + floating point type, in which case the output type is same as x.dtype. + """ + x = np_array_ops.asarray(x) + if promote_to_float and not np.issubdtype(x.dtype.as_numpy_dtype, np.inexact): + x = x.astype(np_utils.result_type(float)) + return tf_fn(x) + + +@tf_export.tf_export('experimental.numpy.log', v1=[]) +@np_utils.np_doc('log') +def log(x): + return _scalar(math_ops.log, x, True) + + +@tf_export.tf_export('experimental.numpy.exp', v1=[]) +@np_utils.np_doc('exp') +def exp(x): + return _scalar(math_ops.exp, x, True) + + +@tf_export.tf_export('experimental.numpy.sqrt', v1=[]) +@np_utils.np_doc('sqrt') +def sqrt(x): + return _scalar(math_ops.sqrt, x, True) + + +@tf_export.tf_export('experimental.numpy.abs', v1=[]) +@np_utils.np_doc('abs', link=np_utils.AliasOf('absolute')) +def abs(x): # pylint: disable=redefined-builtin + return _scalar(math_ops.abs, x) + + +@tf_export.tf_export('experimental.numpy.absolute', v1=[]) +@np_utils.np_doc('absolute') +def absolute(x): + return abs(x) + + +@tf_export.tf_export('experimental.numpy.fabs', v1=[]) +@np_utils.np_doc('fabs') +def fabs(x): + return abs(x) + + +@tf_export.tf_export('experimental.numpy.ceil', v1=[]) +@np_utils.np_doc('ceil') +def ceil(x): + return _scalar(math_ops.ceil, x, True) + + +@tf_export.tf_export('experimental.numpy.floor', v1=[]) +@np_utils.np_doc('floor') +def floor(x): + return _scalar(math_ops.floor, x, True) + + +@tf_export.tf_export('experimental.numpy.conj', v1=[]) +@np_utils.np_doc('conj') +def conj(x): + return _scalar(math_ops.conj, x) + + +@tf_export.tf_export('experimental.numpy.negative', v1=[]) +@np_utils.np_doc('negative') +def negative(x): + return _scalar(math_ops.negative, x) + + +@tf_export.tf_export('experimental.numpy.reciprocal', v1=[]) +@np_utils.np_doc('reciprocal') +def reciprocal(x): + return _scalar(math_ops.reciprocal, x) + + +@tf_export.tf_export('experimental.numpy.signbit', v1=[]) +@np_utils.np_doc('signbit') +def signbit(x): + def f(x): + if x.dtype == dtypes.bool: + return array_ops.fill(array_ops.shape(x), False) + return x < 0 + + return _scalar(f, x) + + +@tf_export.tf_export('experimental.numpy.sin', v1=[]) +@np_utils.np_doc('sin') +def sin(x): + return _scalar(math_ops.sin, x, True) + + +@tf_export.tf_export('experimental.numpy.cos', v1=[]) +@np_utils.np_doc('cos') +def cos(x): + return _scalar(math_ops.cos, x, True) + + +@tf_export.tf_export('experimental.numpy.tan', v1=[]) +@np_utils.np_doc('tan') +def tan(x): + return _scalar(math_ops.tan, x, True) + + +@tf_export.tf_export('experimental.numpy.sinh', v1=[]) +@np_utils.np_doc('sinh') +def sinh(x): + return _scalar(math_ops.sinh, x, True) + + +@tf_export.tf_export('experimental.numpy.cosh', v1=[]) +@np_utils.np_doc('cosh') +def cosh(x): + return _scalar(math_ops.cosh, x, True) + + +@tf_export.tf_export('experimental.numpy.tanh', v1=[]) +@np_utils.np_doc('tanh') +def tanh(x): + return _scalar(math_ops.tanh, x, True) + + +@tf_export.tf_export('experimental.numpy.arcsin', v1=[]) +@np_utils.np_doc('arcsin') +def arcsin(x): + return _scalar(math_ops.asin, x, True) + + +@tf_export.tf_export('experimental.numpy.arccos', v1=[]) +@np_utils.np_doc('arccos') +def arccos(x): + return _scalar(math_ops.acos, x, True) + + +@tf_export.tf_export('experimental.numpy.arctan', v1=[]) +@np_utils.np_doc('arctan') +def arctan(x): + return _scalar(math_ops.atan, x, True) + + +@tf_export.tf_export('experimental.numpy.arcsinh', v1=[]) +@np_utils.np_doc('arcsinh') +def arcsinh(x): + return _scalar(math_ops.asinh, x, True) + + +@tf_export.tf_export('experimental.numpy.arccosh', v1=[]) +@np_utils.np_doc('arccosh') +def arccosh(x): + return _scalar(math_ops.acosh, x, True) + + +@tf_export.tf_export('experimental.numpy.arctanh', v1=[]) +@np_utils.np_doc('arctanh') +def arctanh(x): + return _scalar(math_ops.atanh, x, True) + + +@tf_export.tf_export('experimental.numpy.deg2rad', v1=[]) +@np_utils.np_doc('deg2rad') +def deg2rad(x): + def f(x): + return x * (np.pi / 180.0) + + return _scalar(f, x, True) + + +@tf_export.tf_export('experimental.numpy.rad2deg', v1=[]) +@np_utils.np_doc('rad2deg') +def rad2deg(x): + return x * (180.0 / np.pi) + + +_tf_float_types = [ + dtypes.bfloat16, + dtypes.float16, + dtypes.float32, + dtypes.float64, +] + + +@tf_export.tf_export('experimental.numpy.angle', v1=[]) +@np_utils.np_doc('angle') +def angle(z, deg=False): # pylint: disable=missing-function-docstring + def f(x): + if x.dtype in _tf_float_types: + # Workaround for b/147515503 + return array_ops.where_v2(x < 0, np.pi, 0) + else: + return math_ops.angle(x) + + y = _scalar(f, z, True) + if deg: + y = rad2deg(y) + return y + + +@tf_export.tf_export('experimental.numpy.cbrt', v1=[]) +@np_utils.np_doc('cbrt') +def cbrt(x): + def f(x): + # __pow__ can't handle negative base, so we use `abs` here. + rt = math_ops.abs(x) ** (1.0 / 3) + return array_ops.where_v2(x < 0, -rt, rt) + + return _scalar(f, x, True) + + +@tf_export.tf_export('experimental.numpy.conjugate', v1=[]) +@np_utils.np_doc('conjugate', link=np_utils.AliasOf('conj')) +def conjugate(x): + return _scalar(math_ops.conj, x) + + +@tf_export.tf_export('experimental.numpy.exp2', v1=[]) +@np_utils.np_doc('exp2') +def exp2(x): + def f(x): + return 2**x + + return _scalar(f, x, True) + + +@tf_export.tf_export('experimental.numpy.expm1', v1=[]) +@np_utils.np_doc('expm1') +def expm1(x): + return _scalar(math_ops.expm1, x, True) + + +@tf_export.tf_export('experimental.numpy.fix', v1=[]) +@np_utils.np_doc('fix') +def fix(x): + def f(x): + return array_ops.where_v2(x < 0, math_ops.ceil(x), math_ops.floor(x)) + + return _scalar(f, x, True) + + +@tf_export.tf_export('experimental.numpy.iscomplex', v1=[]) +@np_utils.np_doc('iscomplex') +def iscomplex(x): + return np_array_ops.imag(x) != 0 + + +@tf_export.tf_export('experimental.numpy.isreal', v1=[]) +@np_utils.np_doc('isreal') +def isreal(x): + return np_array_ops.imag(x) == 0 + + +@tf_export.tf_export('experimental.numpy.iscomplexobj', v1=[]) +@np_utils.np_doc('iscomplexobj') +def iscomplexobj(x): + x = np_array_ops.array(x) + return np.issubdtype(x.dtype.as_numpy_dtype, np.complexfloating) + + +@tf_export.tf_export('experimental.numpy.isrealobj', v1=[]) +@np_utils.np_doc('isrealobj') +def isrealobj(x): + return not iscomplexobj(x) + + +@tf_export.tf_export('experimental.numpy.isnan', v1=[]) +@np_utils.np_doc('isnan') +def isnan(x): + return _scalar(math_ops.is_nan, x, True) + + +def _make_nan_reduction(np_fun_name, reduction, init_val): + """Helper to generate nan* functions.""" + + @np_utils.np_doc(np_fun_name) + def nan_reduction(a, axis=None, dtype=None, keepdims=False): + a = np_array_ops.array(a) + v = np_array_ops.array(init_val, dtype=a.dtype) + return reduction( + np_array_ops.where(isnan(a), v, a), + axis=axis, + dtype=dtype, + keepdims=keepdims, + ) + + return nan_reduction + + +nansum = tf_export.tf_export('experimental.numpy.nansum', v1=[])( + _make_nan_reduction('nansum', np_array_ops.sum, 0) +) +nanprod = tf_export.tf_export('experimental.numpy.nanprod', v1=[])( + _make_nan_reduction('nanprod', np_array_ops.prod, 1) +) + + +@tf_export.tf_export('experimental.numpy.nanmean', v1=[]) +@np_utils.np_doc('nanmean') +def nanmean(a, axis=None, dtype=None, keepdims=None): # pylint: disable=missing-docstring + a = np_array_ops.array(a) + if np.issubdtype(a.dtype.as_numpy_dtype, np.bool_) or np.issubdtype( + a.dtype.as_numpy_dtype, np.integer + ): + return np_array_ops.mean(a, axis=axis, dtype=dtype, keepdims=keepdims) + nan_mask = logical_not(isnan(a)) + if dtype is None: + dtype = a.dtype.as_numpy_dtype + normalizer = np_array_ops.sum( + nan_mask, axis=axis, dtype=dtype, keepdims=keepdims + ) + return nansum(a, axis=axis, dtype=dtype, keepdims=keepdims) / normalizer + + +@tf_export.tf_export('experimental.numpy.isfinite', v1=[]) +@np_utils.np_doc('isfinite') +def isfinite(x): + return _scalar(math_ops.is_finite, x, True) + + +@tf_export.tf_export('experimental.numpy.isinf', v1=[]) +@np_utils.np_doc('isinf') +def isinf(x): + if x.dtype.is_floating: + return _scalar(math_ops.is_inf, x, True) + return False + + +@tf_export.tf_export('experimental.numpy.isneginf', v1=[]) +@np_utils.np_doc('isneginf') +def isneginf(x): + if x.dtype.is_floating: + return x == np_array_ops.full_like(x, -np.inf) + return False + + +@tf_export.tf_export('experimental.numpy.isposinf', v1=[]) +@np_utils.np_doc('isposinf') +def isposinf(x): + if x.dtype.is_floating: + return x == np_array_ops.full_like(x, np.inf) + return False + + +@tf_export.tf_export('experimental.numpy.log2', v1=[]) +@np_utils.np_doc('log2') +def log2(x): + return log(x) / np.log(2) + + +@tf_export.tf_export('experimental.numpy.log10', v1=[]) +@np_utils.np_doc('log10') +def log10(x): + return log(x) / np.log(10) + + +@tf_export.tf_export('experimental.numpy.log1p', v1=[]) +@np_utils.np_doc('log1p') +def log1p(x): + return _scalar(math_ops.log1p, x, True) + + +@tf_export.tf_export('experimental.numpy.positive', v1=[]) +@np_utils.np_doc('positive') +def positive(x): + return _scalar(lambda x: x, x) + + +@tf_export.tf_export('experimental.numpy.sinc', v1=[]) +@np_utils.np_doc('sinc') +def sinc(x): + def f(x): + pi_x = x * np.pi + return array_ops.where_v2( + x == 0, array_ops.ones_like(x), math_ops.sin(pi_x) / pi_x + ) + + return _scalar(f, x, True) + + +@tf_export.tf_export('experimental.numpy.square', v1=[]) +@np_utils.np_doc('square') +def square(x): + return _scalar(math_ops.square, x) + + +@tf_export.tf_export('experimental.numpy.diff', v1=[]) +@np_utils.np_doc('diff') +def diff(a, n=1, axis=-1): # pylint: disable=missing-function-docstring + def f(a): + # TODO(agarwal): transpose and reshape to N, H, 1 and do a 1D convolution + # TODO(agarwal): avoid depending on static rank. + nd = a.shape.rank + if nd is None: + raise ValueError( + 'Function `diff` currently requires a known rank for input `a`. ' + f'Received: a={a} (unknown rank)' + ) + if (axis + nd if axis < 0 else axis) >= nd: + raise ValueError( + f'Argument `axis` (received axis={axis}) is out of bounds ' + f'for input {a} of rank {nd}.' + ) + if n < 0: + raise ValueError( + f'Argument `order` must be a non-negative integer. Received: axis={n}' + ) + slice1 = [slice(None)] * nd + slice2 = [slice(None)] * nd + slice1[axis] = slice(1, None) + slice2[axis] = slice(None, -1) + slice1 = tuple(slice1) + slice2 = tuple(slice2) + op = math_ops.not_equal if a.dtype == dtypes.bool else math_ops.subtract + for _ in range(n): + a = op(a[slice1], a[slice2]) + return a + + return _scalar(f, a) + + +def _wrap(f, reverse=False): + """Wraps binary ops so they can be added as operator overloads on ndarray.""" + + def _f(a, b): + if reverse: + a, b = b, a + + if ( + getattr(b, '__array_priority__', 0) + > np_arrays.ndarray.__array_priority__ + ): + return NotImplemented + + return f(a, b) + + return _f + + +def _comparison(tf_fun, x1, x2, cast_bool_to_int=False): + """Helper function for comparision.""" + dtype = np_utils.result_type(x1, x2) + # Cast x1 and x2 to the result_type if needed. + x1 = np_array_ops.array(x1, dtype=dtype) + x2 = np_array_ops.array(x2, dtype=dtype) + if cast_bool_to_int and x1.dtype == dtypes.bool: + x1 = math_ops.cast(x1, dtypes.int32) + x2 = math_ops.cast(x2, dtypes.int32) + return tf_fun(x1, x2) + + +@tf_export.tf_export('experimental.numpy.equal', v1=[]) +@np_utils.np_doc('equal') +def equal(x1, x2): + return _comparison(math_ops.equal, x1, x2) + + +@tf_export.tf_export('experimental.numpy.not_equal', v1=[]) +@np_utils.np_doc('not_equal') +def not_equal(x1, x2): + return _comparison(math_ops.not_equal, x1, x2) + + +@tf_export.tf_export('experimental.numpy.greater', v1=[]) +@np_utils.np_doc('greater') +def greater(x1, x2): + return _comparison(math_ops.greater, x1, x2, True) + + +@tf_export.tf_export('experimental.numpy.greater_equal', v1=[]) +@np_utils.np_doc('greater_equal') +def greater_equal(x1, x2): + return _comparison(math_ops.greater_equal, x1, x2, True) + + +@tf_export.tf_export('experimental.numpy.less', v1=[]) +@np_utils.np_doc('less') +def less(x1, x2): + return _comparison(math_ops.less, x1, x2, True) + + +@tf_export.tf_export('experimental.numpy.less_equal', v1=[]) +@np_utils.np_doc('less_equal') +def less_equal(x1, x2): + return _comparison(math_ops.less_equal, x1, x2, True) + + +@tf_export.tf_export('experimental.numpy.array_equal', v1=[]) +@np_utils.np_doc('array_equal') +def array_equal(a1, a2): # pylint: disable=missing-function-docstring + def f(x1, x2): + return np_utils.cond( + math_ops.equal(array_ops.rank(x1), array_ops.rank(x2)), + lambda: np_utils.cond( # pylint: disable=g-long-lambda + np_utils.reduce_all( + math_ops.equal(array_ops.shape(x1), array_ops.shape(x2)) + ), + lambda: math_ops.reduce_all(math_ops.equal(x1, x2)), + lambda: constant_op.constant(False), + ), + lambda: constant_op.constant(False), + ) + + return _comparison(f, a1, a2) + + +def _logical_binary_op(tf_fun, x1, x2): + x1 = np_array_ops.array(x1, dtype=np.bool_) + x2 = np_array_ops.array(x2, dtype=np.bool_) + return tf_fun(x1, x2) + + +@tf_export.tf_export('experimental.numpy.logical_and', v1=[]) +@np_utils.np_doc('logical_and') +def logical_and(x1, x2): + return _logical_binary_op(math_ops.logical_and, x1, x2) + + +@tf_export.tf_export('experimental.numpy.logical_or', v1=[]) +@np_utils.np_doc('logical_or') +def logical_or(x1, x2): + return _logical_binary_op(math_ops.logical_or, x1, x2) + + +@tf_export.tf_export('experimental.numpy.logical_xor', v1=[]) +@np_utils.np_doc('logical_xor') +def logical_xor(x1, x2): + return _logical_binary_op(math_ops.logical_xor, x1, x2) + + +@tf_export.tf_export('experimental.numpy.logical_not', v1=[]) +@np_utils.np_doc('logical_not') +def logical_not(x): + x = np_array_ops.array(x, dtype=np.bool_) + return math_ops.logical_not(x) + + +@tf_export.tf_export('experimental.numpy.linspace', v1=[]) +@np_utils.np_doc('linspace') +def linspace( # pylint: disable=missing-docstring + start, stop, num=50, endpoint=True, retstep=False, dtype=float, axis=0 +): + if dtype: + dtype = np_utils.result_type(dtype) + start = np_array_ops.array(start, dtype=dtype) + stop = np_array_ops.array(stop, dtype=dtype) + if num < 0: + raise ValueError( + 'Argument `num` (number of samples) must be a non-negative integer. ' + f'Received: num={num}' + ) + step = ops.convert_to_tensor(np.nan) + if endpoint: + result = math_ops.linspace(start, stop, num, axis=axis) + if num > 1: + step = (stop - start) / (num - 1) + else: + # math_ops.linspace does not support endpoint=False so we manually handle it + # here. + if num > 0: + step = (stop - start) / num + if num > 1: + new_stop = math_ops.cast(stop, step.dtype) - step + start = math_ops.cast(start, new_stop.dtype) + result = math_ops.linspace(start, new_stop, num, axis=axis) + else: + result = math_ops.linspace(start, stop, num, axis=axis) + if dtype: + if dtype.is_integer: + # Since numpy 1.20, linspace's rounding is towards -inf instead of 0 + result = math_ops.floor(result) + result = math_ops.cast(result, dtype) + if retstep: + return (result, step) + else: + return result + + +@tf_export.tf_export('experimental.numpy.logspace', v1=[]) +@np_utils.np_doc('logspace') +def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0): + dtype = np_utils.result_type(start, stop, dtype) + result = linspace( + start, stop, num=num, endpoint=endpoint, dtype=dtype, axis=axis + ) + result = math_ops.pow(math_ops.cast(base, result.dtype), result) + if dtype: + result = math_ops.cast(result, dtype) + return result + + +@tf_export.tf_export('experimental.numpy.geomspace', v1=[]) +@np_utils.np_doc('geomspace') +def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): # pylint: disable=missing-docstring + dtype = ( + dtypes.as_dtype(dtype) # pylint: disable=g-long-ternary + if dtype + else np_utils.result_type( + start, stop, float(num), np_array_ops.zeros((), dtype) + ) + ) + computation_dtype = np.promote_types(dtype.as_numpy_dtype, np.float32) + start = np_array_ops.asarray(start, dtype=computation_dtype) + stop = np_array_ops.asarray(stop, dtype=computation_dtype) + # follow the numpy geomspace convention for negative and complex endpoints + start_sign = 1 - np_array_ops.sign(np_array_ops.real(start)) + stop_sign = 1 - np_array_ops.sign(np_array_ops.real(stop)) + signflip = 1 - start_sign * stop_sign // 2 + res = signflip * logspace( + log10(signflip * start), + log10(signflip * stop), + num, + endpoint=endpoint, + base=10.0, + dtype=computation_dtype, + axis=0, + ) + if axis != 0: + res = np_array_ops.moveaxis(res, 0, axis) + return math_ops.cast(res, dtype) + + +@tf_export.tf_export('experimental.numpy.ptp', v1=[]) +@np_utils.np_doc('ptp') +def ptp(a, axis=None, keepdims=None): + return np_array_ops.amax(a, axis=axis, keepdims=keepdims) - np_array_ops.amin( + a, axis=axis, keepdims=keepdims + ) + + +@tf_export.tf_export('experimental.numpy.concatenate', v1=[]) +@np_utils.np_doc_only('concatenate') +def concatenate(arys, axis=0): # pylint: disable=missing-function-docstring + if not isinstance(arys, (list, tuple)): + arys = [arys] + if not arys: + raise ValueError( + 'Need at least one array to concatenate. Received empty ' + f'input: arys={arys}' + ) + dtype = np_utils.result_type(*arys) + arys = [np_array_ops.array(array, dtype=dtype) for array in arys] + return array_ops.concat(arys, axis) + + +@tf_export.tf_export('experimental.numpy.tile', v1=[]) +@np_utils.np_doc_only('tile') +def tile(a, reps): # pylint: disable=missing-function-docstring + a = np_array_ops.array(a) + reps = array_ops.reshape(np_array_ops.array(reps, dtype=dtypes.int32), [-1]) + + a_rank = array_ops.rank(a) + reps_size = array_ops.size(reps) + reps = array_ops.pad( + reps, [[math_ops.maximum(a_rank - reps_size, 0), 0]], constant_values=1 + ) + a_shape = array_ops.pad( + array_ops.shape(a), + [[math_ops.maximum(reps_size - a_rank, 0), 0]], + constant_values=1, + ) + a = array_ops.reshape(a, a_shape) + + return array_ops.tile(a, reps) + + +@tf_export.tf_export('experimental.numpy.count_nonzero', v1=[]) +@np_utils.np_doc('count_nonzero') +def count_nonzero(a, axis=None): + return math_ops.count_nonzero(np_array_ops.array(a), axis) + + +@tf_export.tf_export('experimental.numpy.argsort', v1=[]) +@np_utils.np_doc('argsort') +def argsort(a, axis=-1, kind='quicksort', order=None): # pylint: disable=missing-docstring + # TODO(nareshmodi): make string tensors also work. + if kind not in ('quicksort', 'stable'): + raise ValueError( + 'Invalid value for argument `kind`. ' + 'Only kind="quicksort" and kind="stable" are supported. ' + f'Received: kind={kind}' + ) + if order is not None: + raise ValueError('The `order` argument is not supported. Pass order=None') + stable = kind == 'stable' + + a = np_array_ops.array(a) + + def _argsort(a, axis, stable): + if axis is None: + a = array_ops.reshape(a, [-1]) + axis = 0 + + return sort_ops.argsort(a, axis, stable=stable) + + tf_ans = np_utils.cond( + math_ops.equal(array_ops.rank(a), 0), + lambda: constant_op.constant([0]), + lambda: _argsort(a, axis, stable), + ) + + if ops.is_auto_dtype_conversion_enabled(): + return np_array_ops.array(tf_ans, dtype=int) + else: + return np_array_ops.array(tf_ans, dtype=np.intp) + + +@tf_export.tf_export('experimental.numpy.sort', v1=[]) +@np_utils.np_doc('sort') +def sort(a, axis=-1, kind='quicksort', order=None): # pylint: disable=missing-docstring + if kind != 'quicksort': + raise ValueError( + 'Invalid value for argument `kind`. ' + 'Only kind="quicksort" is supported. ' + f'Received: kind={kind}' + ) + if order is not None: + raise ValueError('The `order` argument is not supported. Pass order=None') + + a = np_array_ops.array(a) + + if axis is None: + return sort_ops.sort(array_ops.reshape(a, [-1]), 0) + else: + return sort_ops.sort(a, axis) + + +def _argminmax(fn, a, axis=None): + a = np_array_ops.array(a) + if axis is None: + # When axis is None numpy flattens the array. + a_t = array_ops.reshape(a, [-1]) + else: + a_t = np_array_ops.atleast_1d(a) + return fn(input=a_t, axis=axis) + + +@tf_export.tf_export('experimental.numpy.argmax', v1=[]) +@np_utils.np_doc('argmax') +def argmax(a, axis=None): + return _argminmax(math_ops.argmax, a, axis) + + +@tf_export.tf_export('experimental.numpy.argmin', v1=[]) +@np_utils.np_doc('argmin') +def argmin(a, axis=None): + return _argminmax(math_ops.argmin, a, axis) + + +@tf_export.tf_export('experimental.numpy.append', v1=[]) +@np_utils.np_doc('append') +def append(arr, values, axis=None): + if axis is None: + return concatenate([np_array_ops.ravel(arr), np_array_ops.ravel(values)], 0) + else: + return concatenate([arr, values], axis=axis) + + +@tf_export.tf_export('experimental.numpy.average', v1=[]) +@np_utils.np_doc('average') +def average(a, axis=None, weights=None, returned=False): # pylint: disable=missing-docstring + if axis is not None and not isinstance(axis, int): + # TODO(wangpeng): Support tuple of ints as `axis` + raise ValueError( + 'Argument `axis` must be an integer. ' + f'Received axis={axis} (of type {type(axis)})' + ) + a = np_array_ops.array(a) + default_float_type = np_utils.result_type(float) + if weights is None: # Treat all weights as 1 + if not np.issubdtype(a.dtype.as_numpy_dtype, np.inexact): + a = a.astype(np_utils.result_type(a.dtype, default_float_type)) + avg = math_ops.reduce_mean(a, axis=axis) + if returned: + if axis is None: + weights_sum = array_ops.size(a) + else: + weights_sum = array_ops.shape(a)[axis] + weights_sum = math_ops.cast(weights_sum, a.dtype) + else: + if np.issubdtype(a.dtype.as_numpy_dtype, np.inexact): + out_dtype = np_utils.result_type(a.dtype, weights) + else: + out_dtype = np_utils.result_type(a.dtype, weights, default_float_type) + a = np_array_ops.array(a, out_dtype) + weights = np_array_ops.array(weights, out_dtype) + + def rank_equal_case(): + control_flow_assert.Assert( + math_ops.reduce_all(array_ops.shape(a) == array_ops.shape(weights)), + [array_ops.shape(a), array_ops.shape(weights)], + ) + weights_sum = math_ops.reduce_sum(weights, axis=axis) + avg = math_ops.reduce_sum(a * weights, axis=axis) / weights_sum + return avg, weights_sum + + if axis is None: + avg, weights_sum = rank_equal_case() + else: + + def rank_not_equal_case(): + control_flow_assert.Assert( + array_ops.rank(weights) == 1, [array_ops.rank(weights)] + ) + weights_sum = math_ops.reduce_sum(weights) + axes = ops.convert_to_tensor([[axis], [0]]) + avg = math_ops.tensordot(a, weights, axes) / weights_sum + return avg, weights_sum + + # We condition on rank rather than shape equality, because if we do the + # latter, when the shapes are partially unknown but the ranks are known + # and different, np_utils.cond will run shape checking on the true branch, + # which will raise a shape-checking error. + avg, weights_sum = np_utils.cond( + math_ops.equal(array_ops.rank(a), array_ops.rank(weights)), + rank_equal_case, + rank_not_equal_case, + ) + + avg = np_array_ops.array(avg) + if returned: + weights_sum = np_array_ops.broadcast_to(weights_sum, array_ops.shape(avg)) + return avg, weights_sum + return avg + + +@tf_export.tf_export('experimental.numpy.trace', v1=[]) +@np_utils.np_doc('trace') +def trace(a, offset=0, axis1=0, axis2=1, dtype=None): # pylint: disable=missing-docstring + if dtype: + dtype = np_utils.result_type(dtype) + a = np_array_ops.asarray(a, dtype) + + if offset == 0: + a_shape = a.shape + if a_shape.rank is not None: + rank = len(a_shape) + if (axis1 == -2 or axis1 == rank - 2) and ( + axis2 == -1 or axis2 == rank - 1 + ): + return math_ops.trace(a) + + a = np_array_ops.diagonal(a, offset, axis1, axis2) + return np_array_ops.sum(a, -1, dtype) + + +@tf_export.tf_export('experimental.numpy.meshgrid', v1=[]) +@np_utils.np_doc('meshgrid') +def meshgrid(*xi, **kwargs): + """This currently requires copy=True and sparse=False.""" + sparse = kwargs.get('sparse', False) + if sparse: + raise ValueError( + 'Function `meshgrid` does not support returning sparse arrays yet. ' + f'Received: sparse={sparse}' + ) + + copy = kwargs.get('copy', True) + if not copy: + raise ValueError( + f'Function `meshgrid` only supports copy=True. Received: copy={copy}' + ) + + indexing = kwargs.get('indexing', 'xy') + + xi = [np_array_ops.asarray(arg) for arg in xi] + kwargs = {'indexing': indexing} + + outputs = array_ops.meshgrid(*xi, **kwargs) + + return outputs + + +# Uses np_doc_only here because np.einsum (in 1.16) doesn't have argument +# `subscripts`, even though the doc says it has. +@tf_export.tf_export('experimental.numpy.einsum', v1=[]) +@np_utils.np_doc_only('einsum') +def einsum(subscripts, *operands, **kwargs): # pylint: disable=missing-docstring + casting = kwargs.get('casting', 'safe') + optimize = kwargs.get('optimize', False) + if casting == 'safe': + operands = np_array_ops._promote_dtype(*operands) # pylint: disable=protected-access + elif casting == 'no': + operands = [np_array_ops.asarray(x) for x in operands] + else: + raise ValueError( + 'Invalid value for argument `casting`. ' + f'Expected casting="safe" or casting="no". Received: casting={casting}' + ) + if not optimize: + # TF doesn't have a "no optimization" option. + # TODO(wangpeng): Print a warning that np and tf use different + # optimizations. + tf_optimize = 'greedy' + elif optimize == True: # pylint: disable=singleton-comparison,g-explicit-bool-comparison + tf_optimize = 'greedy' + elif optimize == 'greedy': + tf_optimize = 'greedy' + elif optimize == 'optimal': + tf_optimize = 'optimal' + else: + raise ValueError( + 'Invalid value for argument `optimize`. ' + 'Expected one of {True, "greedy", "optimal"}. ' + f'Received: optimize={optimize}' + ) + + res = special_math_ops.einsum(subscripts, *operands, optimize=tf_optimize) + return res + + +def _tensor_t(self): + """Returns a Tensor which is the transpose of this Tensor.""" + return self.transpose() + + +def _tensor_ndim(self): + """Returns the rank of the Tensor.""" + return self.shape.ndims + + +def _tensor_pos(self): + """Returns self, for unary operator `+`.""" + return self + + +def _tensor_size(self): + """Returns the number of elements in this Tensor, if fully known.""" + if not self.shape.is_fully_defined(): + return None + return np.prod(self.shape.as_list()) + + +def _tensor_tolist(self): + if ops.is_symbolic_tensor(self): + raise ValueError('Symbolic Tensors do not support the tolist API.') + + return self._numpy().tolist() # pylint: disable=protected-access + + +def _enable_numpy_methods(tensor_class): + """A helper method for adding additional NumPy methods.""" + t = property(_tensor_t) + setattr(tensor_class, 'T', t) + + ndim = property(_tensor_ndim) + setattr(tensor_class, 'ndim', ndim) + + size = property(_tensor_size) + setattr(tensor_class, 'size', size) + + setattr(tensor_class, '__pos__', _tensor_pos) + setattr(tensor_class, 'tolist', _tensor_tolist) + + # TODO(b/178540516): Make a custom `setattr` that changes the method's + # docstring to the TF one. + setattr(tensor_class, 'transpose', np_array_ops.transpose) + setattr(tensor_class, 'flatten', np_array_ops.flatten) + setattr(tensor_class, 'reshape', np_array_ops._reshape_method_wrapper) # pylint: disable=protected-access + setattr(tensor_class, 'ravel', np_array_ops.ravel) + setattr(tensor_class, 'clip', clip) + setattr(tensor_class, 'astype', math_ops.cast) + setattr(tensor_class, '__round__', np_array_ops.around) + setattr(tensor_class, 'max', np_array_ops.amax) + setattr(tensor_class, 'mean', np_array_ops.mean) + setattr(tensor_class, 'min', np_array_ops.amin) + + # TODO(wangpeng): Remove `data` when all uses of it are removed + data = property(lambda self: self) + setattr(tensor_class, 'data', data) + + +def enable_numpy_methods_on_tensor(): + """Adds additional NumPy methods on tf.Tensor class.""" + _enable_numpy_methods(tensor.Tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_random.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_random.py new file mode 100644 index 0000000000000000000000000000000000000000..5c4c6661d007e6e31be85f1c9e80f85e71024607 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_random.py @@ -0,0 +1,137 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Random functions.""" + +# pylint: disable=g-direct-tensorflow-import + +import numpy as onp + +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.numpy_ops import np_array_ops +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.ops.numpy_ops import np_utils +from tensorflow.python.util import tf_export + +# TODO(agarwal): deprecate this. +DEFAULT_RANDN_DTYPE = onp.float32 + + +@tf_export.tf_export('experimental.numpy.random.seed', v1=[]) +@np_utils.np_doc('random.seed') +def seed(s): + """Sets the seed for the random number generator. + + Uses `tf.set_random_seed`. + + Args: + s: an integer. + """ + try: + s = int(s) + except TypeError: + # TODO(wangpeng): support this? + raise ValueError( + f'Argument `s` got an invalid value {s}. Only integers are supported.' + ) + random_seed.set_seed(s) + + +@tf_export.tf_export('experimental.numpy.random.randn', v1=[]) +@np_utils.np_doc('random.randn') +def randn(*args): + """Returns samples from a normal distribution. + + Uses `tf.random_normal`. + + Args: + *args: The shape of the output array. + + Returns: + An ndarray with shape `args` and dtype `float64`. + """ + return standard_normal(size=args) + + +@tf_export.tf_export('experimental.numpy.random.standard_normal', v1=[]) +@np_utils.np_doc('random.standard_normal') +def standard_normal(size=None): + # TODO(wangpeng): Use new stateful RNG + if size is None: + size = () + elif np_utils.isscalar(size): + size = (size,) + dtype = np_utils.result_type(float) + return random_ops.random_normal(size, dtype=dtype) + + +@tf_export.tf_export('experimental.numpy.random.uniform', v1=[]) +@np_utils.np_doc('random.uniform') +def uniform(low=0.0, high=1.0, size=None): + dtype = np_utils.result_type(float) + low = np_array_ops.asarray(low, dtype=dtype) + high = np_array_ops.asarray(high, dtype=dtype) + if size is None: + size = array_ops.broadcast_dynamic_shape(low.shape, high.shape) + return random_ops.random_uniform( + shape=size, minval=low, maxval=high, dtype=dtype + ) + + +@tf_export.tf_export('experimental.numpy.random.poisson', v1=[]) +@np_utils.np_doc('random.poisson') +def poisson(lam=1.0, size=None): + if size is None: + size = () + elif np_utils.isscalar(size): + size = (size,) + return random_ops.random_poisson(shape=size, lam=lam, dtype=np_dtypes.int_) + + +@tf_export.tf_export('experimental.numpy.random.random', v1=[]) +@np_utils.np_doc('random.random') +def random(size=None): + return uniform(0.0, 1.0, size) + + +@tf_export.tf_export('experimental.numpy.random.rand', v1=[]) +@np_utils.np_doc('random.rand') +def rand(*size): + return uniform(0.0, 1.0, size) + + +@tf_export.tf_export('experimental.numpy.random.randint', v1=[]) +@np_utils.np_doc('random.randint') +def randint(low, high=None, size=None, dtype=onp.int64): # pylint: disable=missing-function-docstring + low = int(low) + if high is None: + high = low + low = 0 + if size is None: + size = () + elif isinstance(size, int): + size = (size,) + dtype_orig = dtype + dtype = np_utils.result_type(dtype) + accepted_dtypes = (onp.int32, onp.int64) + if dtype not in accepted_dtypes: + raise ValueError( + f'Argument `dtype` got an invalid value {dtype_orig}. Only those ' + f'convertible to {accepted_dtypes} are supported.' + ) + return random_ops.random_uniform( + shape=size, minval=low, maxval=high, dtype=dtype + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7b36cb2345a42e062a39d7babc27b540bed350e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/numpy_ops/np_utils.py @@ -0,0 +1,715 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility functions for internal use.""" +# pylint: disable=g-direct-tensorflow-import + +import inspect +import numbers +import os +import re + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import flexible_dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.numpy_ops import np_arrays +from tensorflow.python.ops.numpy_ops import np_dtypes +from tensorflow.python.types import core +from tensorflow.python.util import nest +from tensorflow.python.util import tf_export + + +def _canonicalize_axis(axis, rank): + return _canonicalize_axes([axis], rank)[0] + + +def _canonicalize_axes(axes, rank): + rank = _maybe_static(rank) + + if isinstance(rank, core.Tensor): + canonicalizer = lambda axis: cond( # pylint: disable=g-long-lambda + axis < 0, lambda: axis + rank, lambda: axis + ) + else: + canonicalizer = lambda axis: axis + rank if axis < 0 else axis + + return [canonicalizer(axis) for axis in axes] + + +def _supports_signature(): + return hasattr(inspect, 'signature') + + +def _to_tf_type(dtype): + """Converts a native python or numpy type to TF DType. + + Args: + dtype: Could be a python type, a numpy type or a TF DType. + + Returns: + A tensorflow `DType`. + """ + return dtypes.as_dtype(dtype) + + +def _to_numpy_type(dtype): + """Converts a native python or TF DType to numpy type. + + Args: + dtype: Could be a python type, a numpy type or a TF DType. + + Returns: + A NumPy `dtype`. + """ + if isinstance(dtype, dtypes.DType): + return dtype.as_numpy_dtype + return np.dtype(dtype) + + +def isscalar(val): + """Returns whether `val` is a scalar value or scalar Tensor.""" + if isinstance(val, np_arrays.ndarray): + val = val.data + if isinstance(val, core.Tensor): + ndims = val.shape.ndims + if ndims is not None: + return ndims == 0 + else: + return math_ops.equal(array_ops.rank(val), 0) + else: + return np.isscalar(val) + + +def _has_docstring(f): + return ( + f and hasattr(f, '__doc__') and isinstance(f.__doc__, str) and f.__doc__ + ) + + +def _add_blank_line(s): + if s.endswith('\n'): + return s + '\n' + else: + return s + '\n\n' + + +def _np_signature(f): + """An enhanced inspect.signature that can handle numpy.ufunc.""" + # TODO(wangpeng): consider migrating away from inspect.signature. + # inspect.signature is supported in Python 3.3. + if not hasattr(inspect, 'signature'): + return None + if f is None: + return None + if not isinstance(f, np.ufunc): + try: + return inspect.signature(f) + except ValueError: + return None + + def names_from_num(prefix, n): + if n <= 0: + return [] + elif n == 1: + return [prefix] + else: + return [prefix + str(i + 1) for i in range(n)] + + input_names = names_from_num('x', f.nin) + output_names = names_from_num('out', f.nout) + keyword_only_params = [ + ('where', True), + ('casting', 'same_kind'), + ('order', 'K'), + ('dtype', None), + ('subok', True), + ('signature', None), + ('extobj', None), + ] + params = [] + params += [ + inspect.Parameter(name, inspect.Parameter.POSITIONAL_ONLY) + for name in input_names + ] + if f.nout > 1: + params += [ + inspect.Parameter(name, inspect.Parameter.POSITIONAL_ONLY, default=None) + for name in output_names + ] + params += [ + inspect.Parameter( + 'out', + inspect.Parameter.POSITIONAL_OR_KEYWORD, + default=None if f.nout == 1 else (None,) * f.nout, + ) + ] + params += [ + inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=default) + for name, default in keyword_only_params + ] + return inspect.Signature(params) + + +# Python 2 doesn't allow keyword-only argument. Python prior to 3.8 doesn't +# allow positional-only argument. So we conflate positional-only, keyword-only +# and positional-or-keyword arguments here. +def _is_compatible_param_kind(a, b): + def relax(k): + if k in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.KEYWORD_ONLY): + return inspect.Parameter.POSITIONAL_OR_KEYWORD + return k + + return relax(a) == relax(b) + + +def _prepare_np_fun_name_and_fun(np_fun_name, np_fun): + """Mutually propagates information between `np_fun_name` and `np_fun`. + + If one is None and the other is not, we'll try to make the former not None in + a best effort. + + Args: + np_fun_name: name for the np_fun symbol. At least one of np_fun or + np_fun_name shoud be set. + np_fun: the numpy function whose docstring will be used. + + Returns: + Processed `np_fun_name` and `np_fun`. + """ + if np_fun_name is not None: + assert isinstance(np_fun_name, str) + if np_fun is not None: + assert not isinstance(np_fun, str) + if np_fun is None: + assert np_fun_name is not None + try: + np_fun = getattr(np, str(np_fun_name)) + except AttributeError: + np_fun = None + if np_fun_name is None: + assert np_fun is not None + np_fun_name = np_fun.__name__ + return np_fun_name, np_fun + + +def _np_doc_helper( + f, np_f, np_fun_name=None, unsupported_params=None, link=None +): + """Helper to get docs.""" + assert np_f or np_fun_name + if not np_fun_name: + np_fun_name = np_f.__name__ + doc = "TensorFlow variant of NumPy's `%s`.\n\n" % np_fun_name + if unsupported_params: + doc += ( + 'Unsupported arguments: ' + + ', '.join('`' + name + '`' for name in unsupported_params) + + '.\n\n' + ) + if _has_docstring(f): + doc += f.__doc__ + doc = _add_blank_line(doc) + # TODO(wangpeng): Re-enable the following and choose inlined vs. link to numpy + # doc according to some global switch. + doc = _add_np_doc(doc, np_fun_name, np_f, link=link) + return doc + + +_np_doc_form = os.getenv('TF_NP_DOC_FORM', 'stable') + + +def get_np_doc_form(): + """Gets the form of the original numpy docstrings. + + Returns: + See `set_np_doc_form` for the list of valid values. + """ + return _np_doc_form + + +def set_np_doc_form(value): + r"""Selects the form of the original numpy docstrings. + + This function sets a global variable that controls how a tf-numpy symbol's + docstring should refer to the original numpy docstring. If `value` is + `'inlined'`, the numpy docstring will be verbatim copied into the tf-numpy + docstring. Otherwise, a link to the original numpy docstring will be + added. Which numpy version the link points to depends on `value`: + * `'stable'`: the current stable version; + * `'dev'`: the current development version; + * pattern `\d+(\.\d+(\.\d+)?)?`: `value` will be treated as a version number, + e.g. '1.16'. + + Args: + value: the value to set the global variable to. + """ + global _np_doc_form + _np_doc_form = value + + +class Link: + + def __init__(self, v): + self.value = v + + +class AliasOf: + + def __init__(self, v): + self.value = v + + +class NoLink: + pass + + +def generate_link(flag, np_fun_name): + """Generates link from numpy function name. + + Args: + flag: the flag to control link form. See `set_np_doc_form`. + np_fun_name: the numpy function name. + + Returns: + A string. + """ + # Only adds link in this case + if flag == 'dev': + template = 'https://numpy.org/devdocs/reference/generated/numpy.%s.html' + elif flag == 'stable': + template = 'https://numpy.org/doc/stable/reference/generated/numpy.%s.html' + elif re.match(r'\d+(\.\d+(\.\d+)?)?$', flag): + # `flag` is the version number + template = f'https://numpy.org/doc/{flag}/reference/generated/numpy.%s.html' + else: + return None + return template % np_fun_name + + +_is_check_link = os.getenv('TF_NP_CHECK_LINK', 'False') in ('True', 'true', '1') + + +def is_check_link(): + return _is_check_link + + +def set_check_link(value): + global _is_check_link + _is_check_link = value + + +def _add_np_doc(doc, np_fun_name, np_f, link): + """Appends the numpy docstring to `doc`, according to `set_np_doc_form`. + + See `set_np_doc_form` for how it controls the form of the numpy docstring. + + Args: + doc: the docstring to be appended to. + np_fun_name: the name of the numpy function. + np_f: (optional) the numpy function. + link: (optional) which link to use. See `np_doc` for details. + + Returns: + `doc` with numpy docstring appended. + """ + flag = get_np_doc_form() + if flag == 'inlined': + if _has_docstring(np_f): + doc += 'Documentation for `numpy.%s`:\n\n' % np_fun_name + # TODO(wangpeng): It looks like code snippets in numpy doc don't work + # correctly with doctest. Fix that and remove the reformatting of the np_f + # comment. + doc += np_f.__doc__.replace('>>>', '>') + elif isinstance(flag, str): + if link is None: + url = generate_link(flag, np_fun_name) + elif isinstance(link, AliasOf): + url = generate_link(flag, link.value) + elif isinstance(link, Link): + url = link.value + else: + url = None + if url is not None: + if is_check_link(): + # Imports locally because some builds may not have `requests` + import requests # pylint: disable=g-import-not-at-top + + r = requests.head(url) + if r.status_code != 200: + raise ValueError( + f'Check link failed at [{url}] with status code {r.status_code}. ' + f'Argument `np_fun_name` is {np_fun_name}.' + ) + doc += 'See the NumPy documentation for [`numpy.%s`](%s).' % ( + np_fun_name, + url, + ) + return doc + + +_is_sig_mismatch_an_error = os.getenv( + 'TF_NP_SIG_MISMATCH_IS_ERROR', 'False' +) in ('True', 'true', '1') + + +def is_sig_mismatch_an_error(): + return _is_sig_mismatch_an_error + + +def set_is_sig_mismatch_an_error(value): + global _is_sig_mismatch_an_error + _is_sig_mismatch_an_error = value + + +def np_doc(np_fun_name, np_fun=None, unsupported_params=None, link=None): + """Attachs numpy docstring to a function. + + Args: + np_fun_name: name for the np_fun symbol. At least one of np_fun or + np_fun_name shoud be set. + np_fun: (optional) the numpy function whose docstring will be used. + unsupported_params: (optional) the list of parameters not supported by + tf.numpy. + link: (optional) which link to use. If `None`, a default link generated from + `np_fun_name` will be used. If an instance of `AliasOf`, `link.value` will + be used in place of `np_fun_name` for the link generation. If an instance + of `Link`, `link.value` will be used as the whole link. If an instance of + `NoLink`, no link will be added. + + Returns: + A function decorator that attaches the docstring from `np_fun` to the + decorated function. + """ + np_fun_name_orig, np_fun_orig = np_fun_name, np_fun + np_fun_name, np_fun = _prepare_np_fun_name_and_fun(np_fun_name, np_fun) + np_sig = _np_signature(np_fun) + if unsupported_params is None: + unsupported_params = [] + + def decorator(f): + """The decorator.""" + if hasattr(inspect, 'signature') and np_sig is not None: + try: + sig = inspect.signature(f) + except ValueError: + sig = None + if sig is not None: + for name, param in sig.parameters.items(): + np_param = np_sig.parameters.get(name) + if np_param is None: + if is_sig_mismatch_an_error(): + raise TypeError( + f"Cannot find parameter {name} in the numpy function's " + 'signature (which has these parameters: ' + f'{list(np_sig.parameters.keys())}). Argument `np_fun_name` ' + f'is {np_fun_name_orig}. Argument `np_fun` is {np_fun_orig}.' + ) + else: + continue + if is_sig_mismatch_an_error() and not _is_compatible_param_kind( + param.kind, np_param.kind + ): + raise TypeError( + f'Parameter {name} is of kind {param.kind} while in numpy it ' + f'is of kind {np_param.kind}. Argument `np_fun_name` is ' + f'{np_fun_name_orig}. Argument `np_fun` is {np_fun_orig}.' + ) + has_default = param.default != inspect.Parameter.empty + np_has_default = np_param.default != inspect.Parameter.empty + if is_sig_mismatch_an_error() and has_default != np_has_default: + raise TypeError( + 'Parameter {} should{} have a default value. Argument ' + '`np_fun_name` is {}. Argument `np_fun` is {}.'.format( + name, + '' if np_has_default else ' not', + np_fun_name_orig, + np_fun_orig, + ) + ) + for name in np_sig.parameters: + if name not in sig.parameters: + unsupported_params.append(name) + f.__doc__ = _np_doc_helper( + f, + np_fun, + np_fun_name=np_fun_name, + unsupported_params=unsupported_params, + link=link, + ) + return f + + return decorator + + +def np_doc_only(np_fun_name, np_fun=None): + """Attachs numpy docstring to a function. + + This differs from np_doc in that it doesn't check for a match in signature. + + Args: + np_fun_name: name for the np_fun symbol. At least one of np_fun or + np_fun_name shoud be set. + np_fun: (optional) the numpy function whose docstring will be used. + + Returns: + A function decorator that attaches the docstring from `np_fun` to the + decorated function. + """ + np_fun_name, np_fun = _prepare_np_fun_name_and_fun(np_fun_name, np_fun) + + def decorator(f): + f.__doc__ = _np_doc_helper(f, np_fun, np_fun_name=np_fun_name) + return f + + return decorator + + +# pylint: disable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-docstring-missing-newline,g-doc-return-or-yield,g-doc-args +@tf_export.tf_export('experimental.numpy.finfo', v1=[]) +@np_doc('finfo') +def finfo(dtype): + """Note that currently it just forwards to the numpy namesake, while + + tensorflow and numpy dtypes may have different properties. + """ + return np.finfo(_to_numpy_type(dtype)) + + +# pylint: enable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-docstring-missing-newline,g-doc-return-or-yield,g-doc-args + + +def _maybe_get_dtype(x): + """Returns a numpy type if available from x. Skips if x is numpy.ndarray.""" + # Don't put np.ndarray in this list, because np.result_type looks at the + # value (not just dtype) of np.ndarray to decide the result type. + if isinstance(x, numbers.Real): + return x + if isinstance(x, indexed_slices.IndexedSlices) or tensor_util.is_tf_type(x): + return _to_numpy_type(x.dtype) + if isinstance(x, dtypes.DType): + return x.as_numpy_dtype + if isinstance(x, (list, tuple)): + raise ValueError( + 'Cannot find dtype for type inference from argument `x` of a sequence ' + f'type {type(x)}. For sequences, please call this function on each ' + 'element individually.' + ) + return x + + +@tf_export.tf_export('experimental.numpy.result_type', v1=[]) +# Can't use np_doc because np.result_type is a builtin function. +@np_doc_only('result_type') +def result_type(*arrays_and_dtypes): # pylint: disable=missing-function-docstring + if ops.is_auto_dtype_conversion_enabled(): + # Use auto dtype conversion semantics for type inference. + dtype, _ = flexible_dtypes.result_type(*arrays_and_dtypes) + return dtype + arrays_and_dtypes = [ + _maybe_get_dtype(x) for x in nest.flatten(arrays_and_dtypes) + ] + if not arrays_and_dtypes: + # If arrays_and_dtypes is an empty list, let numpy decide what the dtype is. + arrays_and_dtypes = [np.asarray([])] + return np_dtypes._result_type(*arrays_and_dtypes) # pylint: disable=protected-access + + +def result_type_unary(a, dtype): # pylint: disable=missing-function-docstring + """Find the result type from a single input and a dtype.""" + if dtype: + # We need to let np_utils.result_type decide the dtype, not tf.zeros_like + return result_type(dtype) + + # np_utils.result_type treats string inputs as dtype strings, not as strings. + # but for unary we want to treat it as a string input. + if isinstance(a, str): + return np.unicode_ + elif isinstance(a, bytes): + return np.bytes_ + + # TF and numpy has different interpretations of Python types such as + # `float`, so we let `np_utils.result_type` decide. + return result_type(a) + + +def _result_type_binary(t1, t2): # pylint: disable=missing-function-docstring + """A specialization of result_type for 2 arguments for performance reasons.""" + try: + return np_dtypes._result_type( # pylint: disable=protected-access + _maybe_get_dtype(t1), + _maybe_get_dtype(t2), + ) + except ValueError: + return result_type(t1, t2) + + +@tf_export.tf_export('experimental.numpy.promote_types', v1=[]) +@np_doc('promote_types') +def promote_types(type1, type2): # pylint: disable=missing-function-docstring + type1 = _to_numpy_type(type1) + type2 = _to_numpy_type(type2) + return np_dtypes.canonicalize_dtype(np.promote_types(type1, type2)) + + +def tf_broadcast(*args): + """Broadcast tensors. + + Args: + *args: a list of tensors whose shapes are broadcastable against each other. + + Returns: + Tensors broadcasted to the common shape. + """ + if len(args) <= 1: + return args + sh = array_ops.shape(args[0]) + for arg in args[1:]: + sh = array_ops.broadcast_dynamic_shape(sh, array_ops.shape(arg)) + return [array_ops.broadcast_to(arg, sh) for arg in args] + + +# TODO(wangpeng): Move the following functions to a separate file and check for +# float dtypes in each of them. + + +def get_static_value(x): + """A version of tf.get_static_value that returns None on float dtypes. + + It returns None on float dtypes in order to avoid breaking gradients. + + Args: + x: a tensor. + + Returns: + Same as `tf.get_static_value`, except that it returns None when `x` has a + float dtype. + """ + if isinstance(x, core.Tensor) and (x.dtype.is_floating or x.dtype.is_complex): + return None + return tensor_util.constant_value(x) + + +def _maybe_static(x): + value = get_static_value(x) + if value is None: + return x + else: + return value + + +# All the following functions exist becaues get_static_value can't handle +# their TF counterparts. + + +def cond(pred, true_fn, false_fn): + """A version of tf.cond that tries to evaluate the condition.""" + v = get_static_value(pred) + if v is None: + return tf_cond.cond(pred, true_fn, false_fn) + if v: + return true_fn() + else: + return false_fn() + + +def add(a, b): + """A version of tf.add that eagerly evaluates if possible.""" + return _maybe_static(a) + _maybe_static(b) + + +def subtract(a, b): + """A version of tf.subtract that eagerly evaluates if possible.""" + return _maybe_static(a) - _maybe_static(b) + + +def greater(a, b): + """A version of tf.greater that eagerly evaluates if possible.""" + return _maybe_static(a) > _maybe_static(b) + + +def greater_equal(a, b): + """A version of tf.greater_equal that eagerly evaluates if possible.""" + return _maybe_static(a) >= _maybe_static(b) + + +def less_equal(a, b): + """A version of tf.less_equal that eagerly evaluates if possible.""" + return _maybe_static(a) <= _maybe_static(b) + + +def logical_and(a, b): + """A version of tf.logical_and that eagerly evaluates if possible.""" + a_value = get_static_value(a) + if a_value is not None: + if np.isscalar(a_value): + if a_value: + return _maybe_static(b) + else: + return a_value + else: + return a_value & _maybe_static(b) + else: + return a & _maybe_static(b) + + +def logical_or(a, b): + """A version of tf.logical_or that eagerly evaluates if possible.""" + a_value = get_static_value(a) + if a_value is not None: + if np.isscalar(a_value): + if a_value: + return a_value + else: + return _maybe_static(b) + else: + return a_value | _maybe_static(b) + else: + return a | _maybe_static(b) + + +def getitem(a, slice_spec): + """A version of __getitem__ that eagerly evaluates if possible.""" + return _maybe_static(a)[slice_spec] + + +def reduce_all(input_tensor, axis=None, keepdims=False): + """A version of tf.reduce_all that eagerly evaluates if possible.""" + v = get_static_value(input_tensor) + if v is None: + return math_ops.reduce_all(input_tensor, axis=axis, keepdims=keepdims) + else: + return v.all(axis=axis, keepdims=keepdims) + + +def reduce_any(input_tensor, axis=None, keepdims=False): + """A version of tf.reduce_any that eagerly evaluates if possible.""" + v = get_static_value(input_tensor) + if v is None: + return math_ops.reduce_any(input_tensor, axis=axis, keepdims=keepdims) + else: + return v.any(axis=axis, keepdims=keepdims) + + +def tf_rank(t): + r = t.shape.rank + if r is not None: + return r + return array_ops.rank(t) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/op_selector.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/op_selector.py new file mode 100644 index 0000000000000000000000000000000000000000..3ddbe8c8f433ecdec008fe75430c3e169e9db16b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/op_selector.py @@ -0,0 +1,426 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tools for selecting ops in a graph.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.util import object_identity + + +def is_differentiable(op): + try: + return ops._gradient_registry.lookup(op.op_def.name) is not None # pylint: disable=protected-access + except LookupError: + return False + + +def is_iterable(obj): + """Return true if the object is iterable.""" + if isinstance(obj, tensor_lib.Tensor): + return False + try: + _ = iter(obj) + except Exception: # pylint: disable=broad-except + return False + return True + + +def concatenate_unique(la, lb): + """Add all the elements of `lb` to `la` if they are not there already. + + The elements added to `la` maintain ordering with respect to `lb`. + + Args: + la: List of Python objects. + lb: List of Python objects. + Returns: + `la`: The list `la` with missing elements from `lb`. + """ + la_set = set(la) + for l in lb: + if l not in la_set: + la.append(l) + la_set.add(l) + return la + + +def get_tensors(graph): + """get all the tensors which are input or output of an op in the graph. + + Args: + graph: a `tf.Graph`. + Returns: + A list of `tf.Tensor`. + Raises: + TypeError: if graph is not a `tf.Graph`. + """ + if not isinstance(graph, ops.Graph): + raise TypeError("Expected a graph, got: {}".format(type(graph))) + ts = [] + for op in graph.get_operations(): + ts += op.outputs + return ts + + +def get_unique_graph(tops, check_types=None, none_if_empty=False): + """Return the unique graph used by the all the elements in tops. + + Args: + tops: iterable of elements to check (usually a list of tf.Operation and/or + tf.Tensor). Or a tf.Graph. + check_types: check that the element in tops are of given type(s). If None, + the types (tf.Operation, tf.Tensor) are used. + none_if_empty: don't raise an error if tops is an empty list, just return + None. + Returns: + The unique graph used by all the tops. + Raises: + TypeError: if tops is not a iterable of tf.Operation. + ValueError: if the graph is not unique. + """ + if isinstance(tops, ops.Graph): + return tops + if not is_iterable(tops): + raise TypeError("{} is not iterable".format(type(tops))) + if check_types is None: + check_types = (ops.Operation, tensor_lib.Tensor) + elif not is_iterable(check_types): + check_types = (check_types,) + g = None + for op in tops: + if not isinstance(op, check_types): + raise TypeError("Expected a type in ({}), got: {}".format(", ".join([str( + t) for t in check_types]), type(op))) + if g is None: + g = op.graph + elif g._graph_key != op.graph._graph_key: # pylint: disable=protected-access + raise ValueError("Operation {} does not belong to given graph".format(op)) + if g is None and not none_if_empty: + raise ValueError("Can't find the unique graph of an empty list") + return g + + +def check_graphs(*args): + """Check that all the element in args belong to the same graph. + + Args: + *args: a list of object with a obj.graph property. + Raises: + ValueError: if all the elements do not belong to the same graph. + """ + graph = None + for i, sgv in enumerate(args): + if graph is None and sgv.graph is not None: + graph = sgv.graph + elif sgv.graph is not None and sgv.graph is not graph: + raise ValueError(f"args[{i}] does not belong to the same graph as " + "other arguments.") + + +def make_list_of_t(ts, check_graph=True, allow_graph=True, ignore_ops=False): + """Convert ts to a list of `tf.Tensor`. + + Args: + ts: can be an iterable of `tf.Tensor`, a `tf.Graph` or a single tensor. + check_graph: if `True` check if all the tensors belong to the same graph. + allow_graph: if `False` a `tf.Graph` cannot be converted. + ignore_ops: if `True`, silently ignore `tf.Operation`. + Returns: + A newly created list of `tf.Tensor`. + Raises: + TypeError: if `ts` cannot be converted to a list of `tf.Tensor` or, + if `check_graph` is `True`, if all the ops do not belong to the same graph. + """ + if isinstance(ts, ops.Graph): + if allow_graph: + return get_tensors(ts) + else: + raise TypeError("allow_graph is False: cannot convert a tf.Graph.") + else: + if not is_iterable(ts): + ts = [ts] + if not ts: + return [] + if check_graph: + check_types = None if ignore_ops else tensor_lib.Tensor + get_unique_graph(ts, check_types=check_types) + return [t for t in ts if isinstance(t, tensor_lib.Tensor)] + + +def get_generating_ops(ts): + """Return all the generating ops of the tensors in `ts`. + + Args: + ts: a list of `tf.Tensor` + Returns: + A list of all the generating `tf.Operation` of the tensors in `ts`. + Raises: + TypeError: if `ts` cannot be converted to a list of `tf.Tensor`. + """ + ts = make_list_of_t(ts, allow_graph=False) + return [t.op for t in ts] + + +def get_consuming_ops(ts): + """Return all the consuming ops of the tensors in ts. + + Args: + ts: a list of `tf.Tensor` + Returns: + A list of all the consuming `tf.Operation` of the tensors in `ts`. + Raises: + TypeError: if ts cannot be converted to a list of `tf.Tensor`. + """ + ts = make_list_of_t(ts, allow_graph=False) + tops = [] + for t in ts: + for op in t.consumers(): + if op not in tops: + tops.append(op) + return tops + + +def make_list_of_op(tops, check_graph=True, allow_graph=True, ignore_ts=False): + """Convert ops to a list of `tf.Operation`. + + Args: + tops: can be an iterable of `tf.Operation`, a `tf.Graph` or a single + operation. + check_graph: if `True` check if all the operations belong to the same graph. + allow_graph: if `False` a `tf.Graph` cannot be converted. + ignore_ts: if True, silently ignore `tf.Tensor`. + Returns: + A newly created list of `tf.Operation`. + Raises: + TypeError: if tops cannot be converted to a list of `tf.Operation` or, + if `check_graph` is `True`, if all the ops do not belong to the + same graph. + """ + if isinstance(tops, ops.Graph): + if allow_graph: + return tops.get_operations() + else: + raise TypeError("allow_graph is False: cannot convert a tf.Graph.") + else: + if not is_iterable(tops): + tops = [tops] + if not tops: + return [] + if check_graph: + check_types = None if ignore_ts else ops.Operation + get_unique_graph(tops, check_types=check_types) + return [op for op in tops if isinstance(op, ops.Operation)] + + +def _get_inputs(op, only_differentiable): + op_inputs = op.inputs + if only_differentiable: + return op_inputs if is_differentiable(op) else [] + else: + return op_inputs + + +def get_backward_walk_ops(seed_ops, + inclusive=True, + within_ops=None, + within_ops_fn=None, + stop_at_ts=(), + control_inputs=False, + only_differentiable=False): + """Do a backward graph walk and return all the visited ops. + + Args: + seed_ops: an iterable of operations from which the backward graph + walk starts. If a list of tensors is given instead, the seed_ops are set + to be the generators of those tensors. + inclusive: if True the given seed_ops are also part of the resulting set. + within_ops: an iterable of `tf.Operation` within which the search is + restricted. If `within_ops` is `None`, the search is performed within + the whole graph. + within_ops_fn: if provided, a function on ops that should return True iff + the op is within the graph traversal. This can be used along within_ops, + in which case an op is within if it is also in within_ops. + stop_at_ts: an iterable of tensors at which the graph walk stops. + control_inputs: if True, control inputs will be used while moving backward. + only_differentiable: if True, only traverse ops which are differentiable. + This includes natively differentiable ops, or ops with custom gradients. + Returns: + A Python set of all the `tf.Operation` behind `seed_ops`. + Raises: + TypeError: if `seed_ops` or `within_ops` cannot be converted to a list of + `tf.Operation`. + """ + control_inputs = control_inputs and (not only_differentiable) + + if not is_iterable(seed_ops): + seed_ops = [seed_ops] + + try: + first_seed_op = next(iter(seed_ops)) + except StopIteration: + # Empty iterable. + return [] + + if isinstance(first_seed_op, tensor_lib.Tensor): + ts = make_list_of_t(seed_ops, allow_graph=False) + seed_ops = get_generating_ops(ts) + else: + seed_ops = make_list_of_op(seed_ops, allow_graph=False) + + stop_at_ts = object_identity.ObjectIdentitySet(make_list_of_t(stop_at_ts)) + seed_ops = object_identity.ObjectIdentitySet(make_list_of_op(seed_ops)) + if within_ops: + within_ops = make_list_of_op(within_ops, allow_graph=False) + within_ops = object_identity.ObjectIdentitySet(within_ops) + seed_ops &= within_ops + + def is_within(op): + return (within_ops is None or op in within_ops) and ( + within_ops_fn is None or within_ops_fn(op)) + + result = list(seed_ops) + wave = set(seed_ops) + while wave: + new_wave = set() + for op in wave: + for new_t in _get_inputs(op, only_differentiable=only_differentiable): + if new_t in stop_at_ts: + continue + if new_t.op not in result and is_within(new_t.op): + new_wave.add(new_t.op) + if control_inputs: + for new_op in op.control_inputs: + if new_op not in result and is_within(new_op): + new_wave.add(new_op) + concatenate_unique(result, new_wave) + wave = new_wave + if not inclusive: + result = [op for op in result if op not in seed_ops] + return result + + +class UnliftableError(Exception): + """Raised if a Tensor cannot be lifted from the graph.""" + + # Prevent autograph from rewriting this error. + ag_pass_through = True + + +def _as_operation(op_or_tensor): + if isinstance(op_or_tensor, tensor_lib.Tensor): + return op_or_tensor.op + return op_or_tensor + + +def graph_inputs(op): + return [x.op for x in op.inputs] + list(op.control_inputs) + + +def show_path(from_op, tensors, sources): + """Find one path from `from_op` to any of `tensors`, ignoring `sources`. + + Args: + from_op: A `tf.Operation`. + tensors: A `tf.Operation`, a `tf.Tensor`, or a list thereof. + sources: A list of `tf.Tensor`. + + Returns: + A python string containing the path, or "??" if none is found. + """ + if isinstance(from_op, tensor_lib.Tensor): + from_op = from_op.op + + if not isinstance(tensors, list): + tensors = [tensors] + + final_ops = [_as_operation(tensor) for tensor in tensors] + + visited_ops = set(x.op for x in sources) + ops_to_visit = list(final_ops) + some_op_output = {} + while ops_to_visit: + op = ops_to_visit.pop() + if op in visited_ops: + continue + visited_ops.add(op) + if op == from_op: + path_op = op + path = [path_op] + while path_op not in final_ops: + path_op = some_op_output[path_op] + path.append(path_op) + return " <- ".join("%s (%s)" % (x.name, x.type) for x in reversed(path)) + else: + for inp in graph_inputs(op): + if inp not in visited_ops and inp not in sources: + some_op_output[inp] = op + ops_to_visit.append(inp) + return "??" + + +# TODO(jmenick) - there is considerable duplication of functionality between +# this function and get_backward_walk_ops(). Need to deduplicate. +def map_subgraph(init_tensor, sources, disallowed_placeholders, visited_ops, + op_outputs, add_sources): + """Walk a Graph and capture the subgraph between init_tensor and sources. + + Note: This function mutates visited_ops and op_outputs. + + Args: + init_tensor: A Tensor or Operation where the subgraph terminates. + sources: A set of Tensors where subgraph extraction should stop. + disallowed_placeholders: An optional set of ops which may not appear in the + lifted graph. Defaults to all placeholders. + visited_ops: A set of operations which were visited in a prior pass. + op_outputs: A defaultdict containing the outputs of an op which are to be + copied into the new subgraph. + add_sources: A boolean indicating whether placeholders which are not in + sources should be allowed. + + Returns: + The set of placeholders upon which init_tensor depends and are not in + sources. + + Raises: + UnliftableError: if init_tensor depends on a placeholder which is not in + sources and add_sources is False. + """ + ops_to_visit = [_as_operation(init_tensor)] + extra_sources = object_identity.ObjectIdentitySet() + while ops_to_visit: + op = ops_to_visit.pop() + if op in visited_ops: + continue + visited_ops.add(op) + + should_raise = False + if disallowed_placeholders is not None and op in disallowed_placeholders: + should_raise = True + elif op.type == "Placeholder": + if disallowed_placeholders is None and not add_sources: + should_raise = True + extra_sources.update(op.outputs) + + if should_raise: + raise UnliftableError( + "Unable to lift tensor %s because it depends transitively on " + "placeholder %s via at least one path, e.g.: %s" % + (repr(init_tensor), repr(op), show_path(op, init_tensor, sources))) + for inp in graph_inputs(op): + op_outputs[inp].add(op) + if inp not in visited_ops and inp not in (sources or extra_sources): + ops_to_visit.append(inp) + + return extra_sources diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/optional_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/optional_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..5702dae119d2f1ad04d4ffc8372e899208190673 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/optional_grad.py @@ -0,0 +1,30 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradient functions for optional ops.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_optional_ops + + +@ops.RegisterGradient("OptionalFromValue") +def _OptionalFromValueGrad(op, grad): + return gen_optional_ops.optional_get_value( + grad, [t.dtype for t in op.inputs], [t.shape for t in op.inputs] + ) + + +@ops.RegisterGradient("OptionalGetValue") +def _OptionalGetValueGrad(unused_op, *grads): + return gen_optional_ops.optional_from_value(grads) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..23c447a5abc80dcb377a6060896b933eada64539 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for pfor, for_loop, jacobian.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/control_flow_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/control_flow_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e65e4fdd1c1a2c9f9d21ca2a4c8113a3c7cf6814 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/control_flow_ops.py @@ -0,0 +1,582 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""for_loop and pfor ops.""" +# pylint: disable=g-direct-tensorflow-import + +import functools + +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.parallel_for.pfor import PFor +from tensorflow.python.ops.parallel_for.pfor import PForConfig +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +def for_loop(loop_fn, loop_fn_dtypes, iters, parallel_iterations=None): + """Runs `loop_fn` `iters` times and stacks the outputs. + + + Runs `loop_fn` `iters` times, with input values from 0 to `iters - 1`, and + stacks corresponding outputs of the different runs. + + Args: + loop_fn: A function that takes an int32 scalar tf.Tensor object representing + the iteration number, and returns a possibly nested structure of tensor + objects. The shape of these outputs should not depend on the input. + loop_fn_dtypes: dtypes for the outputs of `loop_fn`. + iters: Number of iterations for which to run `loop_fn`. + parallel_iterations: The number of iterations that can be dispatched in + parallel. This knob can be used to control the total memory usage. + + Returns: + Returns a nested structure of stacked output tensor objects with the same + nested structure as the output of `loop_fn`. + """ + + flat_loop_fn_dtypes = nest.flatten(loop_fn_dtypes) + is_none_list = [] + + def while_body(i, *ta_list): + """Body of while loop.""" + fn_conv = autograph.tf_convert(loop_fn, autograph_ctx.control_status_ctx()) + fn_output = nest.flatten(fn_conv(i)) + if len(fn_output) != len(flat_loop_fn_dtypes): + raise ValueError( + f"Number of expected outputs {len(flat_loop_fn_dtypes)}, does not " + f"match the number of actual outputs {len(fn_output)} from loop_fn: " + f"{loop_fn} with output {fn_output}.") + outputs = [] + del is_none_list[:] + is_none_list.extend(x is None for x in fn_output) + for out, ta in zip(fn_output, ta_list): + # TODO(agarwal): support returning Operation objects from loop_fn. + if out is not None: + # out may be a ref tensor, wrap it in identity to get a non-ref tensor. + ta = ta.write(i, out) + outputs.append(ta) + return tuple([i + 1] + outputs) + + if parallel_iterations is not None: + extra_args = {"parallel_iterations": parallel_iterations} + else: + extra_args = {} + ta_list = while_loop.while_loop(lambda i, *ta: i < iters, while_body, [0] + [ + tensor_array_ops.TensorArray(dtype.base_dtype, iters) + for dtype in flat_loop_fn_dtypes + ], **extra_args)[1:] + + # TODO(rachelim): enable this for sparse tensors + + output = [ + None if is_none else ta.stack() + for ta, is_none in zip(ta_list, is_none_list) + ] + assert len(output) in (0, len(flat_loop_fn_dtypes)) + if not output: + # This may happen for the case where iters == 0. + # Pack a list of empty tensors with the proper ranks to match pfor output on 0 iters + loop_var = array_ops.placeholder_with_default(0, shape=[]) + try: + loop_fn_out = loop_fn(loop_var) + out_shapes = [ + [0] + ops.convert_to_tensor(x).shape + for x in nest.flatten(loop_fn_out) + ] + output = [ + array_ops.zeros(out_shapes[i], dt) + for i, dt in enumerate(flat_loop_fn_dtypes) + ] + except Exception: + output = [array_ops.zeros([0])] + return nest.pack_sequence_as(loop_fn_dtypes, output) + + +def _flatten_first_two_dims(x): + """Flattens the first two dimensions of x into a single dimension.""" + old_shape = array_ops.shape(x) + new_shape = array_ops.concat([[old_shape[0] * old_shape[1]], old_shape[2:]], + axis=0) + return array_ops.reshape(x, new_shape) + + +PFOR_CONFIG_ARG = "pfor_config" + + +def _is_under_xla_context(): + """Check if we are currently inside an XLA compile context.""" + g = ops.get_default_graph() + while g is not None: + control_flow_context = g._get_control_flow_context() # pylint: disable=protected-access + while control_flow_context is not None: + if control_flow_context.IsXLAContext(): + return True + else: + control_flow_context = control_flow_context.outer_context + # If g is a FuncGraph, get its outer_graph. + g = getattr(g, "outer_graph", None) + return False + + +def pfor(loop_fn, + iters, + fallback_to_while_loop=True, + parallel_iterations=None, + warn=False): + """Equivalent to running `loop_fn` `iters` times and stacking the outputs. + + `pfor` has functionality similar to `for_loop`, i.e. running `loop_fn` `iters` + times, with input from 0 to `iters - 1`, and stacking corresponding output of + each iteration. However the implementation does not use a `tf.while_loop`. + Instead it adds new operations to the graph that collectively compute the same + value as what running `loop_fn` in a loop would compute. + + + This is an experimental feature and currently has a lot of limitations: + - There should be no data dependency between the different iterations. For + example, a future iteration should not depend on a value or side-effect of + a previous iteration. + - Stateful kernels may mostly not be supported since these often imply a + data dependency or ordering of the iterations. We do support a limited set + of such stateful kernels though (like RandomFoo, Variable operations like + reads, etc). + - Conversion works only on a limited set of kernels for which a converter + has been registered. + - `loop_fn` has limited support for control flow operations. `tf.cond` in + particular is not supported. + - `loop_fn` should return nested structure of Tensors or Operations. However + if an Operation is returned, it should have zero outputs. + - The shape and dtype of `loop_fn` outputs should not depend on the input + to loop_fn. + + Args: + loop_fn: A function that takes an int32 scalar tf.Tensor object representing + the iteration number, and optionally a keyword argument `pfor_config` set + to a PForConfig object. It returns a possibly nested structure of Tensor + or Operation objects. Note that if setting `parallel_iterations` argument + to something other than None, `loop_fn` may be called more than once + during graph construction. So it may need to avoid mutating global state. + iters: Number of iterations for which to run `loop_fn`. + fallback_to_while_loop: If true, on failing to vectorize an operation, pfor + fallbacks to using a `tf.while_loop` to dispatch the iterations. + parallel_iterations: A knob to control how many iterations are vectorized + and dispatched in parallel. The default value of None corresponds to + vectorizing all the iterations. If `parallel_iterations` is smaller than + `iters`, then chunks of at most that many iterations are dispatched in + sequence. This knob can be used to control the total memory usage. + warn: Whether or not to warn when falling back to while loops. + + Returns: + Returns a nested structure of stacked tensor objects with the same nested + structure as the output of `loop_fn`. + Raises: + ValueError: If parallel_iterations is not None and not an integer > 1. + """ + def f(): + return _pfor_impl( + loop_fn, + iters, + fallback_to_while_loop=fallback_to_while_loop, + parallel_iterations=parallel_iterations, + warn=warn) + # Note that we wrap into a tf.function if in eager execution mode or under + # XLA compilation. The latter is so that we don't compile operations like + # tf.placeholder that are created by the loop body. + functions_run_eagerly = None + if context.executing_eagerly() or _is_under_xla_context(): + functions_run_eagerly = def_function.functions_run_eagerly() + if functions_run_eagerly: + logging.warning( + "It looks like tf.function behavior was disabled, perhaps using " + "tf.config.run_functions_eagerly. Vectorization " + "primitives (e.g. tf.vectorized_map) require tf.function to work. " + "These primitives will override the disable.") + def_function.run_functions_eagerly(False) + f = def_function.function(f) + + outputs = f() + if functions_run_eagerly is not None: + def_function.run_functions_eagerly(functions_run_eagerly) + return outputs + + +def _should_expand_composite(value): + return (isinstance(value, composite_tensor.CompositeTensor) + # Leave sparse tensors to be converted by `PFor._convert_sparse`. + and not isinstance(value, sparse_tensor.SparseTensor) + and not isinstance(value, indexed_slices.IndexedSlices)) + + +# pylint: disable=protected-access +def _composite_to_tensors(value, is_batched=False): + """Converts a CompositeTensor into a list of stackable tensors.""" + if _should_expand_composite(value): + spec = value._type_spec + if not isinstance(spec, type_spec.BatchableTypeSpec): + raise ValueError(f"CompositeTensor instance {value} returned from " + "parallel_for or vectorized_map loop body must provide " + f"a `BatchableTypeSpec` (saw: {spec}).") + if is_batched: + return spec._to_batched_tensor_list(value) + return spec._to_tensor_list(value) + return value +# pylint: enable=protected-access + + +# pylint: disable=protected-access +def _composite_from_tensors(stacked_tensors, + preconverted_value, + batch_size): + """Converts a list of stacked tensors to a batch CompositeTensor.""" + if _should_expand_composite(preconverted_value): + batch_type_spec = preconverted_value._type_spec._batch(batch_size) + return batch_type_spec._from_compatible_tensor_list(stacked_tensors) + return stacked_tensors +# pylint: enable=protected-access + + +def _loop_fn_has_config(loop_fn): + """Test if `loop_fn` has a `pfor_config` argument.""" + if tf_inspect.isfunction(loop_fn): + argspec = tf_inspect.getargspec(loop_fn) + return PFOR_CONFIG_ARG in argspec.args + elif isinstance(loop_fn, functools.partial): + fn = loop_fn.func + argspec = tf_inspect.getargspec(fn) + return (PFOR_CONFIG_ARG in argspec.args and + PFOR_CONFIG_ARG not in loop_fn.keywords) + else: + loop_class = tf_decorator.unwrap(loop_fn)[1] + if not hasattr(loop_class, "__call__"): + raise ValueError("`loop_fn` object did not have a __call__ method") + argspec = tf_inspect.getargspec(loop_class.__call__) + return PFOR_CONFIG_ARG in argspec.args + + +def _pfor_impl(loop_fn, + iters, + fallback_to_while_loop, + parallel_iterations=None, + pfor_config=None, + warn=False): + """Implementation of pfor.""" + assert not context.executing_eagerly() + loop_fn_has_config = _loop_fn_has_config(loop_fn) + existing_ops = set(ops.get_default_graph().get_operations()) + iters_value = tensor_util.constant_value(iters) + # Run the loop body + with ops.name_scope("loop_body"): + loop_var = array_ops.placeholder_with_default(0, shape=[]) + if loop_fn_has_config: + if pfor_config is None: + pfor_config = PForConfig() + pfor_config._set_iters(iters) # pylint: disable=protected-access + loop_fn_outputs = loop_fn(loop_var, **{PFOR_CONFIG_ARG: pfor_config}) + else: + assert pfor_config is None + f = autograph.tf_convert(loop_fn, autograph_ctx.control_status_ctx()) + loop_fn_outputs = f(loop_var) + loop_fn_output_tensors = nest.map_structure(_composite_to_tensors, + loop_fn_outputs) + + # Convert outputs to Tensor if needed. + tmp_loop_fn_outputs = [] + for loop_fn_output in nest.flatten(loop_fn_output_tensors): + if (loop_fn_output is not None and not isinstance( + loop_fn_output, + (ops.Operation, tensor.Tensor, sparse_tensor.SparseTensor))): + if isinstance(loop_fn_output, indexed_slices.IndexedSlices): + logging.warn("Converting %s to a dense representation may make it slow." + " Alternatively, output the indices and values of the" + " IndexedSlices separately, and handle the vectorized" + " outputs directly." % loop_fn_output) + loop_fn_output = ops.convert_to_tensor(loop_fn_output) + else: + loop_fn_output = ops.convert_to_tensor(loop_fn_output) + tmp_loop_fn_outputs.append(loop_fn_output) + loop_fn_output_tensors = nest.pack_sequence_as(loop_fn_output_tensors, + tmp_loop_fn_outputs) + + new_ops = set(ops.get_default_graph().get_operations()) - existing_ops + iters = ops.convert_to_tensor(iters) + if parallel_iterations is not None: + if parallel_iterations < 1: + raise ValueError( + "Argument `parallel_iterations` must be None or a positive integer. " + f"Received: {parallel_iterations}.") + if parallel_iterations == 1: + raise ValueError( + "Found `parallel_iterations == 1`. Use `for_loop` instead.") + if iters_value is not None and iters_value < parallel_iterations: + parallel_iterations = None + if parallel_iterations is None: + with ops.name_scope("pfor"): + converter = PFor( + loop_var, + iters, + new_ops, + fallback_to_while_loop=fallback_to_while_loop, + pfor_config=pfor_config, + warn=warn) + flattened_output_tensors = [] + for loop_fn_output in nest.flatten(loop_fn_output_tensors): + output = converter.convert(loop_fn_output) + flattened_output_tensors.append(output) + else: + if pfor_config is not None and pfor_config._has_reductions(): # pylint: disable=protected-access + raise ValueError("Setting `parallel_iterations` currently unsupported if " + "reductions across iterations are performed.") + num_tiled_iterations = iters // parallel_iterations + num_remaining_iterations = iters % parallel_iterations + # TODO(agarwal): Avoid calling loop_fn twice. Generate the loop body inside + # a tf.function and extract the graph from there to vectorize it. + with ops.name_scope("pfor_untiled"): + converter = PFor(loop_var, num_remaining_iterations, new_ops, + fallback_to_while_loop=fallback_to_while_loop, + pfor_config=pfor_config) + remaining_output_tensors = [] + flattened_output_tensors = nest.flatten(loop_fn_output_tensors) + for loop_fn_output in flattened_output_tensors: + output = converter.convert(loop_fn_output) + remaining_output_tensors.append(output) + + with ops.name_scope("pfor_tiled"): + loop_fn_dtypes = [ops.convert_to_tensor(x).dtype + for x in flattened_output_tensors] + + def tiled_loop_body(j): + offset = j * parallel_iterations + num_remaining_iterations + + def tiled_loop_fn(i, pfor_config=None): + if loop_fn_has_config: + loop_fn_outputs = loop_fn(i + offset, pfor_config=pfor_config) + else: + loop_fn_outputs = loop_fn(i + offset) + return nest.flatten( + # Stacking across iterations requires explicit Tensors. + nest.map_structure(_composite_to_tensors, loop_fn_outputs)) + + return _pfor_impl( + tiled_loop_fn, + parallel_iterations, + fallback_to_while_loop=fallback_to_while_loop, + pfor_config=pfor_config) + + tiled_output_tensors = for_loop( + tiled_loop_body, loop_fn_dtypes, + num_tiled_iterations, parallel_iterations=1) + tiled_output_tensors = [ + _flatten_first_two_dims(y) for y in tiled_output_tensors] + + with ops.name_scope("pfor"): + if iters_value is None or iters_value % parallel_iterations: + output_tensors = cond.cond( + math_ops.equal(num_remaining_iterations, 0), + lambda: tiled_output_tensors, + lambda: [array_ops.concat([x, y], axis=0) # pylint: disable=g-long-lambda + for x, y in zip(remaining_output_tensors, + tiled_output_tensors)]) + else: + output_tensors = tiled_output_tensors + flattened_output_tensors = nest.flatten(output_tensors) + + for output, original_output in zip(flattened_output_tensors, + nest.flatten(loop_fn_output_tensors)): + # Restore any shape information lost from tiling. + # TODO(b/174254748): this may not be correct for stacked `variant`s. + output.set_shape( + tensor_shape.TensorShape([iters_value]).concatenate( + original_output.shape)) + return nest.map_structure_up_to( + loop_fn_outputs, + functools.partial(_composite_from_tensors, batch_size=iters_value), + nest.pack_sequence_as(loop_fn_output_tensors, + flattened_output_tensors), + loop_fn_outputs) + + +def _broadcasting_gather(x, i): + """Wrapper for gather that implicitly broadcasts unit dimensions.""" + static_first_dim = tensor_shape.dimension_value(x.shape[0]) + if static_first_dim == 1: + i = 0 + elif static_first_dim is None: + i = array_ops.where_v2(array_ops.shape(x)[0] > 1, i, 0) + result = array_ops.gather(x, i) + return result + + +# pylint: disable=protected-access +def _gather_from_tensor_or_composite(x, i): + """Wrapper for gather that handles CompositeTensors.""" + if _should_expand_composite(x): + spec = x._type_spec + gathered_tensors = [_broadcasting_gather(t, i) + for t in spec._to_batched_tensor_list(x)] + return spec._unbatch()._from_compatible_tensor_list(gathered_tensors) + return _broadcasting_gather(x, i) +# pylint: enable=protected-access + + +@tf_export("vectorized_map") +def vectorized_map(fn, elems, fallback_to_while_loop=True, warn=True): + """Parallel map on the list of tensors unpacked from `elems` on dimension 0. + + This method works similar to `tf.map_fn` but is optimized to run much faster, + possibly with a much larger memory footprint. The speedups are obtained by + vectorization (see [Auto-Vectorizing TensorFlow Graphs: Jacobians, + Auto-Batching and Beyond](https://arxiv.org/pdf/1903.04243.pdf)). The idea + behind vectorization is to semantically launch all the invocations of `fn` in + parallel and fuse corresponding operations across all these invocations. This + fusion is done statically at graph generation time and the generated code is + often similar in performance to a manually fused version. + + Because `tf.vectorized_map` fully parallelizes the batch, this method will + generally be significantly faster than using `tf.map_fn`, especially in eager + mode. However this is an experimental feature and currently has a lot of + limitations: + - There should be no data dependency between the different semantic + invocations of `fn`, i.e. it should be safe to map the elements of the + inputs in any order. + - Stateful kernels may mostly not be supported since these often imply a + data dependency. We do support a limited set of such stateful kernels + though (like RandomFoo, Variable operations like reads, etc). + - `fn` has limited support for control flow operations. + - `fn` should return nested structure of Tensors or Operations. However + if an Operation is returned, it should have zero outputs. + - The shape and dtype of any intermediate or output tensors in the + computation of `fn` should not depend on the input to `fn`. + + Examples: + ```python + def outer_product(a): + return tf.tensordot(a, a, 0) + + batch_size = 100 + a = tf.ones((batch_size, 32, 32)) + c = tf.vectorized_map(outer_product, a) + assert c.shape == (batch_size, 32, 32, 32, 32) + ``` + + ```python + # Computing per-example gradients + + batch_size = 10 + num_features = 32 + layer = tf.keras.layers.Dense(1) + + def model_fn(arg): + with tf.GradientTape() as g: + inp, label = arg + inp = tf.expand_dims(inp, 0) + label = tf.expand_dims(label, 0) + prediction = layer(inp) + loss = tf.nn.l2_loss(label - prediction) + return g.gradient(loss, (layer.kernel, layer.bias)) + + inputs = tf.random.uniform([batch_size, num_features]) + labels = tf.random.uniform([batch_size, 1]) + per_example_gradients = tf.vectorized_map(model_fn, (inputs, labels)) + assert per_example_gradients[0].shape == (batch_size, num_features, 1) + assert per_example_gradients[1].shape == (batch_size, 1) + ``` + + Args: + fn: The callable to be performed. It accepts one argument, which will have + the same (possibly nested) structure as `elems`, and returns a possibly + nested structure of Tensors and Operations, which may be different than + the structure of `elems`. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be mapped over by `fn`. The first dimensions of all + elements must broadcast to a consistent value; equivalently, each + element tensor must have first dimension of either `B` or `1`, for some + common batch size `B >= 1`. + fallback_to_while_loop: If true, on failing to vectorize an operation, + the unsupported op is wrapped in a tf.while_loop to execute the map + iterations. Note that this fallback only happens for unsupported ops and + other parts of `fn` are still vectorized. If false, on encountering an + unsupported op, a ValueError is thrown. Note that the fallbacks can result + in slowdowns since vectorization often yields speedup of one to two orders + of magnitude. + warn: If set to `false`, this will supress any warnings due to operation + conversions in the provided `fn` falling back to while loops. + + Returns: + A tensor or (possibly nested) sequence of tensors. Each tensor packs the + results of applying fn to tensors unpacked from elems along the first + dimension, from first to last. + + Although they are less common as user-visible inputs and outputs, note that + tensors of type `tf.variant` which represent tensor lists (for example from + `tf.raw_ops.TensorListFromTensor`) are vectorized by stacking the list + contents rather than the variant itself, and so the container tensor will + have a scalar shape when returned rather than the usual stacked shape. This + improves the performance of control flow gradient vectorization. + + Raises: + ValueError: If vectorization fails and fallback_to_while_loop is False. + """ + elems = variable_utils.convert_variables_to_tensors(elems) + elems = nest.map_structure(ops.convert_to_tensor, + elems, + expand_composites=True) + + def loop_fn(i): + gathered_elems = nest.map_structure( + lambda x: _gather_from_tensor_or_composite(x, i), elems) + return fn(gathered_elems) + + # Extract batch size from the maximum first dimension of any element. + flat_elems = nest.flatten( + nest.map_structure( + functools.partial(_composite_to_tensors, + is_batched=True), + elems)) + def _get_shape(x): + if x.shape.rank is None: + return None + return x.shape.as_list()[0] + static_first_dims = [_get_shape(elem) for elem in flat_elems] + if any(s is None for s in static_first_dims): + batch_size = math_ops.reduce_max( + [array_ops.shape(elem)[0] for elem in flat_elems]) + else: + batch_size = max(static_first_dims) + + return pfor( + loop_fn, + batch_size, + fallback_to_while_loop=fallback_to_while_loop, + warn=warn) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/gradients.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..da667a5e1bbde54f3e46be28d75d8c58fc700b1e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/gradients.py @@ -0,0 +1,144 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Jacobian ops.""" +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import gradients_impl as gradient_ops +from tensorflow.python.ops.parallel_for import control_flow_ops +from tensorflow.python.util import nest + + +def jacobian(output, inputs, use_pfor=True, parallel_iterations=None): + """Computes jacobian of `output` w.r.t. `inputs`. + + Args: + output: A tensor. + inputs: A tensor or a nested structure of tensor objects. + use_pfor: If true, uses pfor for computing the jacobian. Else uses + tf.while_loop. + parallel_iterations: A knob to control how many iterations and dispatched in + parallel. This knob can be used to control the total memory usage. + + Returns: + A tensor or a nested structure of tensors with the same structure as + `inputs`. Each entry is the jacobian of `output` w.r.t. to the corresponding + value in `inputs`. If output has shape [y_1, ..., y_n] and inputs_i has + shape [x_1, ..., x_m], the corresponding jacobian has shape + [y_1, ..., y_n, x_1, ..., x_m]. Note that in cases where the gradient is + sparse (IndexedSlices), jacobian function currently makes it dense and + returns a Tensor instead. This may change in the future. + """ + flat_inputs = nest.flatten(inputs) + output_tensor_shape = output.shape + output_shape = array_ops.shape(output) + output = array_ops.reshape(output, [-1]) + + def loop_fn(i): + y = array_ops.gather(output, i) + return gradient_ops.gradients(y, flat_inputs) + + try: + output_size = int(output.shape[0]) + except TypeError: + output_size = array_ops.shape(output)[0] + + if use_pfor: + pfor_outputs = control_flow_ops.pfor( + loop_fn, output_size, parallel_iterations=parallel_iterations) + else: + pfor_outputs = control_flow_ops.for_loop( + loop_fn, + [output.dtype] * len(flat_inputs), + output_size, + parallel_iterations=parallel_iterations) + + for i, out in enumerate(pfor_outputs): + if isinstance(out, tensor.Tensor): + new_shape = array_ops.concat( + [output_shape, array_ops.shape(out)[1:]], axis=0) + out = array_ops.reshape(out, new_shape) + out.set_shape(output_tensor_shape.concatenate(flat_inputs[i].shape)) + pfor_outputs[i] = out + + return nest.pack_sequence_as(inputs, pfor_outputs) + + +def batch_jacobian(output, inp, use_pfor=True, parallel_iterations=None): + """Computes and stacks jacobians of `output[i,...]` w.r.t. `input[i,...]`. + + e.g. + x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) + y = x * x + jacobian = batch_jacobian(y, x) + # => [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] + + Args: + output: A tensor with shape [b, y1, ..., y_n]. `output[i,...]` should + only depend on `inp[i,...]`. + inp: A tensor with shape [b, x1, ..., x_m] + use_pfor: If true, uses pfor for computing the Jacobian. Else uses a + tf.while_loop. + parallel_iterations: A knob to control how many iterations are vectorized + and dispatched in parallel. The default value of None, when use_pfor is + true, corresponds to vectorizing all the iterations. When use_pfor is + false, the default value of None corresponds to parallel_iterations=10. + This knob can be used to control the total memory usage. + + Returns: + A tensor `t` with shape [b, y_1, ..., y_n, x1, ..., x_m] where `t[i, ...]` + is the jacobian of `output[i, ...]` w.r.t. `inp[i, ...]`, i.e. stacked + per-example jacobians. + + Raises: + ValueError: if first dimension of `output` and `inp` do not match. + """ + output_shape = output.shape + if not output_shape[0].is_compatible_with(inp.shape[0]): + raise ValueError(f"Need first dimension of `output` shape ({output.shape}) " + f"and `inp` shape ({inp.shape}) to match.") + if output_shape.is_fully_defined(): + batch_size = int(output_shape[0]) + output_row_size = output_shape.num_elements() // batch_size + else: + output_shape = array_ops.shape(output) + batch_size = output_shape[0] + output_row_size = array_ops.size(output) // batch_size + inp_shape = array_ops.shape(inp) + # Flatten output to 2-D. + with ops.control_dependencies( + [check_ops.assert_equal(batch_size, inp_shape[0])]): + output = array_ops.reshape(output, [batch_size, output_row_size]) + + def loop_fn(i): + y = array_ops.gather(output, i, axis=1) + return gradient_ops.gradients(y, inp)[0] + + if use_pfor: + pfor_output = control_flow_ops.pfor(loop_fn, output_row_size, + parallel_iterations=parallel_iterations) + else: + pfor_output = control_flow_ops.for_loop( + loop_fn, output.dtype, + output_row_size, + parallel_iterations=parallel_iterations) + if pfor_output is None: + return None + pfor_output = array_ops.reshape(pfor_output, + [output_row_size, batch_size, -1]) + output = array_ops.transpose(pfor_output, [1, 0, 2]) + new_shape = array_ops.concat([output_shape, inp_shape[1:]], axis=0) + return array_ops.reshape(output, new_shape) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/pfor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/pfor.py new file mode 100644 index 0000000000000000000000000000000000000000..55fd22706714afef450eb605ee82bb170523d35d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/pfor.py @@ -0,0 +1,5210 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Compiled parallel-for loop.""" +# pylint: disable=missing-docstring,g-direct-tensorflow-import + +import collections +import functools +import string +import sys +import traceback +from typing import List + +import numpy as np + +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.core.framework import full_type_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import execute +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_switch_case +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import gen_list_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import gen_optional_ops +from tensorflow.python.ops import gen_parsing_ops +from tensorflow.python.ops import gen_random_ops +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.ops import gen_spectral_ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import manip_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import flags +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity + + +# TODO(agarwal): remove flag. +flags.DEFINE_bool( + "op_conversion_fallback_to_while_loop", True, + "DEPRECATED: Flag is ignored.") + + +def _variant_handle_data(t): + """Fetches handle data for a variant tensor `t`, or None if unavailable.""" + handle_data = resource_variable_ops.get_eager_safe_handle_data(t) + if not handle_data.is_set: + return None + return handle_data.shape_and_type + + +def _variant_type_id(t): + """Returns the full_type_pb2 type of `t`, or None if it is not available.""" + if t.dtype != dtypes.variant: + return None + shapes_and_types = _variant_handle_data(t) + if shapes_and_types is None or not shapes_and_types: + # TODO(b/169968286): Identify all variant tensors (e.g. maps) and we can + # make this an error instead of assuming TensorLists have handle data. + return None # Presumed not a TensorList/Optional + return shapes_and_types[0].type.type_id + + +_INTERNAL_STACKING_TYPE_IDS = ( + full_type_pb2.TFT_ARRAY, + full_type_pb2.TFT_OPTIONAL) + + +def _is_variant_with_internal_stacking(t): + """Identifies variant tensors which pfor always maintains as scalars. + + For these, the pfor tensor is recorded as "stacked" if the content of the + variant tensor (e.g. the elements of a TensorList) are all stacked. + + Args: + t: A tensor to identify. + Returns: + True if `t` is a TensorList/Optional, False not, None if unknown. + """ + type_id = _variant_type_id(t) + return type_id in _INTERNAL_STACKING_TYPE_IDS + + +def _parse_variant_shapes_and_types(t): + """Extracts shape and dtype information from a variant tensor `t`.""" + shapes_and_types = _variant_handle_data(t) + if shapes_and_types is None or not shapes_and_types: + raise ValueError("Required handle data not set for {!r}".format(t)) + if shapes_and_types[0].type.type_id == full_type_pb2.TFT_ARRAY: + return shapes_and_types + else: + if shapes_and_types[0].type.type_id == full_type_pb2.TFT_UNSET: + return shapes_and_types + else: + raise ValueError( + "Attempted to stack a variant-dtype tensor with no type set ({!r})" + .format(t)) + + +def _rank(t): + """Returns rank as an integer (when statically known) or as a tensor.""" + rank = t.get_shape().rank if isinstance(t, tensor_lib.Tensor) else None + return array_ops.rank(t) if rank is None else rank + + +def _size(t, dtype=None): + """Returns size as an integer (when statically known) or as a tensor.""" + size = ( + t.get_shape().num_elements() if isinstance(t, tensor_lib.Tensor) else None + ) + return array_ops.size(t, out_type=dtype) if size is None else size + + +def _expand_dims(t, axis, num_axes=1): + """Similar to `expand_dims` but supports insertion of multiple axes.""" + if isinstance(num_axes, int): + for _ in range(num_axes): + t = array_ops.expand_dims(t, axis) + else: + shape = array_ops.shape(t) + ones = array_ops.fill( + array_ops.reshape(num_axes, [1]), constant_op.constant(1, shape.dtype) + ) + new_shape = array_ops.concat([shape[:1], ones, shape[1:]], axis=0) + t = array_ops.reshape(t, new_shape) + return t + + +def _stack(t, length): + """stacks `t` `length` times.""" + # Note that this stacking may currently be triggered, for example, when a + # loop invariant tensor with dtype variant is input to a while_loop which then + # produces a loop dependent output. Simply stacking the variants may not be + # suitable since operations on stacked handles may expect a vectorized version + # of the variant. + if t.dtype == dtypes.variant: + shapes_and_types = _parse_variant_shapes_and_types(t) + if shapes_and_types[0].type.type_id == full_type_pb2.TFT_ARRAY: + if len(shapes_and_types) != 1: + raise ValueError( + f"Expected handle data of length 1, got {shapes_and_types!r} of " + f"length {len(shapes_and_types)}.") + return wrap( + _stack_tensor_list(t, shapes_and_types[0].dtype, length), + True) + else: + raise ValueError( + "Attempted to stack an unhandled variant-dtype tensor of " + f"type {shapes_and_types[0].type!r} ({t!r}).") + shape = array_ops.shape(t) + ones = array_ops.ones_like(shape) + ones = array_ops.reshape(ones, [-1]) + length = array_ops.reshape(length, [-1]) + length = math_ops.cast(length, shape.dtype) + multiples = array_ops.concat([length, ones], 0) + t = array_ops.tile(array_ops.expand_dims(t, 0), multiples) + return wrap(t, True) + + +# The following stateful ops can be safely called once, and with the same +# signature as the unconverted version, if their inputs are loop invariant. +# TODO(agarwal): implement a strategy for converting Variable reads/writes. The +# plan is to map each read/write in the loop_fn to a corresponding merged +# read/write in the converted graph. Writes need to be mergeable (e.g. +# AssignAdd) to be used in `pfor`. Given a certain read/write order in the +# loop_fn, doing a one-to-one conversion will simulate executing such +# instructions in lock-step across all iterations. +passthrough_stateful_ops = set([ + "VariableV2", + "VarHandleOp", + "VariableShape", + "ReadVariableOp", + "StackV2", + "TensorArrayWriteV3", + "TensorArrayReadV3", + "TensorArraySizeV3", +]) + + +# Ops which we will treat like stateful for the purpose of vectorization. +# Typically this is used to force pfor converters to run for these ops. +force_stateful_ops = set([ + # We vectorize this since we need to change the element shape set on the + # list. + "TensorListReserve", +]) + + +def _is_stateful_pfor_op(op): + if isinstance(op, WhileOp): + return op.is_stateful + if op.type == "Const": + # Const didn't have an op_def. + return False + if op.type in passthrough_stateful_ops: + return False + if op.type in force_stateful_ops: + return True + assert hasattr(op, "op_def") and op.op_def is not None, op + return op.op_def.is_stateful + + +# pylint: disable=protected-access +class WhileOp: + """Object for storing state for converting the outputs of a while_loop.""" + + def __init__( + self, + exit_node: tensor_lib.Tensor, + pfor_ops: List[ops.Operation], + fallback_to_while_loop: bool, + pfor_config: "PForConfig", + ): + """Initializer. + + Args: + exit_node: A tensor output from the while_loop. + pfor_ops: list of ops inside the current pfor loop. + fallback_to_while_loop: If True, fallback to while loop when conversion of + an op is not supported + pfor_config: PForConfig object used while constructing loop body. + """ + self._fallback_to_while_loop = fallback_to_while_loop + self._pfor_config = pfor_config + self._pfor_ops = set(pfor_ops) + self._pfor_op_ids = set(x._id for x in pfor_ops) + assert isinstance(exit_node, tensor_lib.Tensor) + self._while_context = exit_node.op._get_control_flow_context() + assert isinstance(self._while_context, control_flow_ops.WhileContext) + self._context_name = self._while_context.name + self._condition = self._while_context.pivot.op.inputs[0] + # Parts of an external while_loop could be created inside a pfor loop. + # However for the purpose here, we declare such loops to be external. Also + # note that we check if the condition was created inside or outside to + # determine if the while_loop was first created inside or outside. + # TODO(agarwal): check that the Enter and Exit of this loop are unstacked. + self._is_inside_loop = self.op_is_inside_loop(self._condition.op) + if self._is_inside_loop: + for e in self._while_context.loop_exits: + assert self.op_is_inside_loop(e.op) + + # Note the code below tries to reverse engineer an existing while_loop graph + # by assuming the following pattern of nodes. + # + # NextIteration <---- Body <--- Enter + # | ^ + # V ___| Y + # Enter -> Merge -> Switch___ + # ^ | N + # | V + # LoopCond Exit + + # Node that elements in the list below correspond one-to-one with each + # other. i.e. these lists are the same size, and the i_th entry corresponds + # to different Operations/Tensors of a single cycle as illustrated above. + # List of Switch ops (ops.Operation) that feed into an Exit Node. + self._exit_switches = [] + # List of inputs (tensor_lib.Tensor) to NextIteration. + self._body_outputs = [] + # List of list of control inputs of the NextIteration nodes. + self._next_iter_control_inputs = [] + # List of Merge ops (ops.Operation). + self._enter_merges = [] + # List of output (tensor_lib.Tensor) of Exit nodes. + self._outputs = [] + + # List of Enter Tensors. + # There are two types of Enter nodes: + # - The Enter nodes that are used in the `loop_vars` argument to + # `while_loop` (see + # https://www.tensorflow.org/api_docs/python/tf/while_loop). We collect + # these Enter nodes immediately below by tracing backwards from the Exit + # nodes via Exit <- Switch <- Merge <- Enter. You can see this chain in the + # diagram above. This allows us to have a 1:1 correspondence between the + # self._outputs and the first elements in self._enters. + # - The Enter nodes that are used only by the body. They don't appear in the + # `loop_vars` and are not returned from the `while_loop`. In Python code, + # they are usually captured by the body lambda. We collect them below by + # iterating over all the ops in the graph. They are appended to the end of + # self._enters or self._direct_enters, and don't correspond to any outputs + # in self._outputs. Note that we keep the resource/variant Enter nodes in + # self._direct_enters and the constructed while_loop's body uses them + # directly as opposed to passing them as loop variables. This is done + # because the while_body cannot partition the resource/variant Tensors, so + # it has to leave them unchanged. + self._enters = [] + self._direct_enters = [] + + for e in self._while_context.loop_exits: + self._outputs.append(e.op.outputs[0]) + switch = e.op.inputs[0].op + assert switch.type == "Switch", switch + self._exit_switches.append(switch) + merge = switch.inputs[0].op + assert merge.type == "Merge", merge + self._enter_merges.append(merge) + enter = merge.inputs[0].op + assert enter.type == "Enter", enter + self._enters.append(enter.outputs[0]) + next_iter = merge.inputs[1].op + assert next_iter.type == "NextIteration", next_iter + self._body_outputs.append(next_iter.inputs[0]) + self._next_iter_control_inputs.append(next_iter.control_inputs) + + # Collect all the Enter nodes that are not part of `loop_vars`, the second + # category described above. + # Also track whether the loop body has any stateful ops. + self._is_stateful = False + for op in ops.get_default_graph().get_operations(): + # TODO(agarwal): make sure this works with nested case. + control_flow_context = op._get_control_flow_context() + if control_flow_context is None: + continue + if control_flow_context.name == self._context_name: + self._is_stateful |= _is_stateful_pfor_op(op) + if op.type == "Enter": + output = op.outputs[0] + if output not in self._enters: + if output.dtype in (dtypes.resource, dtypes.variant): + if output not in self._direct_enters: + self._direct_enters.append(output) + else: + self._enters.append(output) + + def __str__(self) -> str: + """String representation.""" + return "while_loop(%s)" % self.name + + @property + def inputs(self): + """Input to all the Enter nodes.""" + return [x.op.inputs[0] for x in self._enters + self._direct_enters] + + @property + def control_inputs(self): + """Control input to all the Enter nodes.""" + control_inputs = [] + for x in self._enters + self._direct_enters: + control_inputs.extend(x.op.control_inputs) + return control_inputs + + @property + def outputs(self) -> List[tensor_lib.Tensor]: + """Outputs of all the Exit nodes.""" + return self._outputs + + @property + def name(self) -> str: + """Context name for the while loop.""" + return self._context_name + + @property + def is_inside_loop(self) -> bool: + """Returns true if the while_loop was created inside the pfor.""" + return self._is_inside_loop + + def op_is_inside_loop(self, op: ops.Operation) -> bool: + """True if op was created inside the pfor loop body.""" + assert isinstance(op, ops.Operation) + # Note that we use self._pfor_op_ids for the check and not self._pfor_ops + # since it appears there tensorflow API could return different python + # objects representing the same Operation node. + return op._id in self._pfor_op_ids + + @property + def is_stateful(self) -> bool: + return self._is_stateful + + @property + def pfor_converter(self) -> "WhileOp": + """Return a converter for the while loop.""" + return self + + def _init_pfor(self, parent_pfor, indices, cond_stacked, inputs, + inputs_stacked): + """Create a PFor object for converting parts of the while_loop. + + Args: + parent_pfor: PFor object being used for converting the while_loop. + indices: int32 Tensor of ids for the iterations that are still active + (i.e. did not exit the while_loop). + cond_stacked: True if the while_loop condition is stacked. + inputs: list of input Tensors corresponding 1-to-1 with self._enters. Note + that these Tensors are a subset of the loop variables for the generated + while_loop. + inputs_stacked: List of booleans corresponding 1-to-1 with `inputs`, + indicating if the value is stacked or not. + + Returns: + A PFor instance. The instance is initialized by adding conversion mappings + of nodes that will be external to the conversion that the returned + instance will be used for. e.g. Enter nodes as well as Merge and Switch + outputs are mapped to converted values. + """ + num_outputs = len(self._outputs) + assert len(inputs) == len(self._enters) + assert len(inputs_stacked) == len(self._enters) + loop_var = parent_pfor.loop_var + loop_len = array_ops.size(indices) + pfor = PFor( + loop_var, + loop_len, + pfor_ops=self._pfor_ops, + all_indices=indices, + all_indices_partitioned=cond_stacked, + fallback_to_while_loop=self._fallback_to_while_loop, + pfor_config=self._pfor_config) + # Map all inputs of Enter nodes in self._direct_enters to their converted + # values. + for enter in self._direct_enters: + enter_input = enter.op.inputs[0] + converted_enter, stacked, is_sparse_stacked = parent_pfor._convert_helper( + enter_input) + # Since these are resources / variants, they should be unstacked. + assert not stacked and not is_sparse_stacked, (enter, converted_enter) + pfor._add_conversion(enter, wrap(converted_enter, False)) + + # Map all Enter nodes to the inputs. + for enter, inp, stacked in zip(self._enters, inputs, inputs_stacked): + pfor._add_conversion(enter, wrap(inp, stacked)) + # Map outputs of Switch and Merge. + for i in range(num_outputs): + wrapped_inp = wrap(inputs[i], inputs_stacked[i]) + merge = self._enter_merges[i] + pfor._add_conversion(merge.outputs[0], wrapped_inp) + # Note that second output of Merge is typically not used, except possibly + # as a control dependency. To avoid trying to output the correct value, we + # employ a hack here. We output a dummy invalid value with an incorrect + # dtype. This will allow control dependency to work but if using it as an + # input, it should typically lead to errors during graph construction due + # to dtype mismatch. + # TODO(agarwal): Check in the original graph to see if there are any + # consumers of this Tensor that use it as an input. + pfor._add_conversion(merge.outputs[1], + wrap(constant_op.constant(-1.0), False)) + switch = self._exit_switches[i] + # Don't need to worry about switch.output[0] which will feed to Exit node. + pfor._add_conversion(switch.outputs[1], wrapped_inp) + return pfor + + def _convert_enter(self, parent_pfor: "PFor", enter): + """Converts an Enter node.""" + inp, stacked, _ = parent_pfor._convert_helper(enter.op.inputs[0]) + control_inputs = [] + for x in enter.op.control_inputs: + converted = parent_pfor._convert_helper(x) + if not isinstance(converted, ops.Operation): + converted = converted.t + control_inputs.append(converted) + if control_inputs: + with ops.control_dependencies(control_inputs): + inp = array_ops.identity(inp) + return inp, stacked + + def _maybe_stacked(self, cache, inp): + """Heuristic to figure out if the converting inp leads to a stacked value. + + + Args: + cache: map from Tensor to boolean indicating stacked/unstacked. + inp: input Tensor. + + Returns: + True if `inp` could get stacked. If the function returns False, the + converted value should be guaranteed to be unstacked. If returning True, + it may or may not be stacked. + """ + if inp in cache: + return cache[inp] + if not self.op_is_inside_loop(inp.op): + return False + op = inp.op + output = False + if op.type in [ + "OnesLike", + "Shape", + "Rank", + "ShapeN", + "ZerosLike", + "TensorArrayV3", + "TensorArraySizeV3", + ]: + output = False + elif _is_stateful_pfor_op(op): + # This may be fairly aggressive. + output = True + elif op.type == "Exit": + # This may be fairly aggressive. + output = True + else: + for t in op.inputs: + if self._maybe_stacked(cache, t): + output = True + break + cache[inp] = output + return output + + def _create_init_values(self, pfor_input: "_PforInput"): + """Create arguments passed to converted while_loop.""" + with ops.name_scope("while_init"): + loop_len_vector = pfor_input.pfor.loop_len_vector + loop_len = loop_len_vector[0] + num_outputs = len(self._outputs) + + inputs = [] + maybe_stacked_cache = {} + # Convert all the Enters. Need to do this before checking for stacking + # below. + for i, enter in enumerate(self._enters): + inp, stacked = self._convert_enter(pfor_input.pfor, enter) + inputs.append(inp) + maybe_stacked_cache[enter] = stacked + # Since this enter node is part of the `loop_vars`, it corresponds to an + # output and its preceding switch. We mark this switch's output the same + # stackness, to act at the base case for the logic below. Below, we will + # be going through the body figuring out which inputs might need to be + # stacked and which inputs can safely remain unstacked. + if i < num_outputs: + maybe_stacked_cache[self._exit_switches[i].outputs[1]] = stacked + + # Shape invariants for init_values corresponding to self._enters. + input_shape_invariants = [] + # TensorArrays for outputs of converted while loop + output_tas = [] + # Shape invariants for output TensorArrays. + ta_shape_invariants = [] + # List of booleans indicating stackness of inputs, i.e. tensors + # corresponding to self._enters. + inputs_stacked = [] + for i, inp in enumerate(inputs): + enter = self._enters[i] + inp_stacked = self._maybe_stacked(maybe_stacked_cache, enter) + # Note that even when an input is unstacked, the body could make it + # stacked. we use a heuristic below to figure out if body may be making + # it stacked. + if i < num_outputs: + body_output = self._body_outputs[i] + if enter.op in self._pfor_ops: + body_output_stacked = self._maybe_stacked(maybe_stacked_cache, + body_output) + else: + # If constructed outside of pfor loop, then the output would not be + # stacked. + body_output_stacked = False + if body_output_stacked and not inp_stacked: + inp = _stack(inp, loop_len_vector).t + inputs[i] = inp + inp_stacked = True + # TODO(agarwal): other attributes for the TensorArray ? + output_tas.append(tensor_array_ops.TensorArray(inp.dtype, loop_len)) + ta_shape_invariants.append(tensor_shape.TensorShape(None)) + + inputs_stacked.append(inp_stacked) + input_shape_invariants.append(tensor_shape.TensorShape(None)) + + # See documentation for __call__ for the structure of init_values. + init_values = [True, pfor_input.pfor.all_indices] + inputs + output_tas + # TODO(agarwal): try stricter shape invariants + shape_invariants = ( + [tensor_shape.TensorShape(None), + tensor_shape.TensorShape(None)] + input_shape_invariants + + ta_shape_invariants) + + return init_values, inputs_stacked, shape_invariants + + def _process_cond_unstacked(self, conditions, indices, inputs, output_tas): + """Handles case when condition is unstacked. + + Note that all iterations end together. So we don't need to partition the + inputs. When all iterations are done, we write the inputs to the + TensorArrays. Note that we only write to index 0 of output_tas. Since all + iterations end together, they can all be output together. + """ + not_all_done = array_ops.reshape(conditions, []) + new_output_tas = [] + # pylint: disable=cell-var-from-loop + for i, out_ta in enumerate(output_tas): + inp = inputs[i] + new_output_tas.append( + tf_cond.cond(not_all_done, lambda: out_ta, + lambda: out_ta.write(0, inp))) + # pylint: enable=cell-var-from-loop + return not_all_done, indices, inputs, new_output_tas + + def _process_cond_stacked(self, conditions, indices, inputs, inputs_stacked, + output_tas): + num_outputs = len(self._outputs) + # Compute if all iterations are done. + not_all_done = math_ops.reduce_any(conditions) + conditions_int = math_ops.cast(conditions, dtypes.int32) + # Partition the indices. + done_indices, new_indices = data_flow_ops.dynamic_partition( + indices, conditions_int, 2) + + new_inputs = [] + new_output_tas = [] + for i, (inp, stacked) in enumerate(zip(inputs, inputs_stacked)): + # Partition the inputs. + if stacked: + done_inp, new_inp = data_flow_ops.dynamic_partition( + inp, conditions_int, 2) + else: + # TODO(agarwal): avoid this stacking. See TODO earlier in + # _process_cond_unstacked. + done_inp = _stack(inp, [array_ops.size(done_indices)]).t + new_inp = inp + new_inputs.append(new_inp) + # For iterations that are done, write them to TensorArrays. + if i < num_outputs: + out_ta = output_tas[i] + # Note that done_indices can be empty. done_inp should also be empty in + # that case. + new_output_tas.append(out_ta.scatter(done_indices, done_inp)) + return not_all_done, new_indices, new_inputs, new_output_tas + + def _process_body( + self, + pfor_input: "_PforInput", + inputs_stacked, + new_indices, + cond_stacked, + new_inputs, + not_all_done, + ): + """Convert the body function.""" + + def true_fn(control_inputs, body_pfor, body_output, stacked): + """Converts the body function for all but last iteration. + + This essentially converts body_output. Additionally, it needs to handle + any control dependencies on the NextIteration node. So it creates another + Identity node with the converted dependencies. + """ + converted_control_inp = [] + for x in control_inputs: + for t in x.outputs: + converted_control_inp.append(body_pfor._convert_helper(t).t) + if stacked: + # Note convert always does the stacking. + output = body_pfor.convert(body_output) + else: + output, convert_stacked, _ = body_pfor._convert_helper(body_output) + assert convert_stacked == stacked, body_output + with ops.control_dependencies(converted_control_inp): + return array_ops.identity(output) + + body_pfor = self._init_pfor(pfor_input.pfor, new_indices, cond_stacked, + new_inputs, inputs_stacked) + new_outputs = [] + + for i, (body_output, + stacked) in enumerate(zip(self._body_outputs, inputs_stacked)): + control_inp = self._next_iter_control_inputs[i] + out_dtype = body_output.dtype + # Note that we want to run the body only if not all pfor iterations are + # done. If all are done, we return empty tensors since these values will + # not be used. Notice that the value returned by the loop is based on + # TensorArrays and not directly on these returned values. + # pylint: disable=cell-var-from-loop + new_output = tf_cond.cond( + not_all_done, + lambda: true_fn(control_inp, body_pfor, body_output, stacked), + lambda: constant_op.constant([], dtype=out_dtype)) + # pylint: enable=cell-var-from-loop + new_outputs.append(new_output) + return new_outputs + + def __call__(self, pfor_input: "_PforInput"): + """Converter for the while_loop. + + The conversion of a while_loop is another while_loop. + + The arguments to this converted while_loop are as follows: + not_all_done: Boolean scalar Tensor indicating if all the pfor iterations + are done. + indices: int32 1-D Tensor storing the id of the iterations that are not + done. + args: Remaining arguments. These can be divided into 3 categories: + - First set of arguments are the tensors that correspond to the initial + elements of self._enters. The elements that appear in original while + loop's `loop_vars`. + - The second set of arguments are the tensors that correspond to the + remaining elements of self._enters. These are the tensors that directly + enter the original while loop body. + - Finally, the last set of arguments are TensorArrays. These TensorArrays + correspond to the outputs of the original while_loop, i.e. to the + elements in self._outputs. Each TensorArray has `PFor.loop_len` + elements, i.e. the number of pfor iterations. At the end, the i'th + element of each TensorArray will contain the output computed by the + i'th iteration of pfor. Note that elements can be written into these + tensors arrays in any order, depending on when the corresponding pfor + iteration is done. + If the original while_loop had `k` tensors in its `loop_vars` and its body + directly captured `m` tensors, the `args` will contain `2 * k + m` values. + + In each iteration, the while_loop body recomputes the condition for all + active pfor iterations to see which of them are now done. It then partitions + all the inputs and passes them along to the converted body. Values for all + the iterations that are done are written to TensorArrays indexed by the pfor + iteration number. When all iterations are done, the TensorArrays are stacked + to get the final value. + + Args: + pfor_input: A PForInput object corresponding to the output of any Exit + node from this while loop. + + Returns: + List of converted outputs. + """ + # Create init_values that will be passed to the while_loop. + init_values, inputs_stacked, shape_invariants = self._create_init_values( + pfor_input) + # Note that we use a list as a hack since we need the nested function body + # to set the value of cond_is_stacked. python2.x doesn't support nonlocal + # variables. + cond_is_stacked = [None] + + def cond(not_all_done, *_): + return not_all_done + + def body(not_all_done, indices, *args): + # See documentation for __call__ for the structure of *args. + num_enters = len(self._enters) + inputs = args[:num_enters] + output_tas = args[num_enters:] + # TODO(agarwal): see which outputs have consumers and only populate the + # TensorArrays corresponding to those. Or do those paths get trimmed out + # from inside the while_loop body? + assert len(inputs) >= len(output_tas) + assert len(inputs) == len(inputs_stacked) + + # Convert condition + with ops.name_scope("while_cond"): + # Note that we set cond_stacked to True here. At this point we don't + # know if it could be loop invariant, hence the conservative value is + # to assume stacked. + cond_pfor = self._init_pfor( + pfor_input.pfor, + indices, + cond_stacked=True, + inputs=inputs, + inputs_stacked=inputs_stacked) + conditions, cond_stacked, _ = cond_pfor._convert_helper(self._condition) + cond_is_stacked[0] = cond_stacked + + # Recompute the new condition, write outputs of done iterations, and + # partition the inputs if needed. + if not cond_stacked: + (not_all_done, new_indices, new_inputs, + new_output_tas) = self._process_cond_unstacked(conditions, indices, + inputs, output_tas) + else: + (not_all_done, new_indices, new_inputs, + new_output_tas) = self._process_cond_stacked(conditions, indices, + inputs, inputs_stacked, + output_tas) + + # Convert body + with ops.name_scope("while_body"): + # Compute the outputs from the body. + new_outputs = self._process_body(pfor_input, inputs_stacked, + new_indices, cond_stacked, new_inputs, + not_all_done) + + # Note that the first num_outputs new values of inputs are computed using + # the body. Rest of them were direct Enters into the condition/body and + # the partitioning done earlier is sufficient to give the new value. + num_outputs = len(self._outputs) + new_args = ([not_all_done, new_indices] + new_outputs + + list(new_inputs[num_outputs:]) + new_output_tas) + return tuple(new_args) + + while_outputs = while_loop.while_loop( + cond, body, init_values, shape_invariants=shape_invariants) + output_tas = while_outputs[-len(self._outputs):] + outputs = [] + assert cond_is_stacked[0] is not None + for inp_stacked, ta in zip(inputs_stacked, output_tas): + if cond_is_stacked[0]: + outputs.append(wrap(ta.stack(), True)) + else: + # Note that if while_loop condition is unstacked, all iterations exit at + # the same time and we wrote those outputs in index 0 of the tensor + # array. + outputs.append(wrap(ta.read(0), inp_stacked)) + return outputs + + +class ConversionNotImplementedError(Exception): + pass + + +class _PforInput: + """Input object passed to registered pfor converters.""" + + __slots__ = ["pfor", "_op", "_inputs"] + + def __init__(self, pfor: "PFor", op: ops.Operation, inputs): + """Creates a _PforInput object. + + Args: + pfor: PFor converter object. + op: the Operation object that is being converted. + inputs: list of WrappedTensor objects representing converted values of the + inputs of `op`. + """ + self.pfor = pfor + self._op = op + self._inputs = inputs + + def stack_inputs(self, stack_indices=None, tile_variants=False): + """Stacks unstacked inputs at `stack_indices`. + + Args: + stack_indices: indices of inputs at which stacking is done. If None, + stacking is done at all indices. + tile_variants: If True, affected indices which have a variant dtype will + be tiled after this operation to match the expected shape of a + vectorized tensor. Variants generally need to be un-tiled when they are + inputs to operations and tiled when returned. + """ + if stack_indices is None: + stack_indices = range(len(self._inputs)) + length = self.pfor.loop_len_vector + for i in stack_indices: + inp = self._inputs[i] + is_variant = inp.t.dtype == dtypes.variant + if not inp.is_stacked: + self._inputs[i] = _stack(inp.t, length) + if tile_variants and is_variant: + self._inputs[i] = wrap( + _tile_variant_with_length(self._inputs[i].t, length), True) + elif not tile_variants and is_variant: + self._inputs[i] = wrap(_untile_variant(self._inputs[i].t), True) + + def expanddim_inputs_for_broadcast(self): + """Reshapes stacked inputs to prepare them for broadcast. + + Since stacked inputs have an extra leading dimension, automatic broadcasting + rules could incorrectly try to expand dimensions before that leading + dimension. To avoid that, we reshape these stacked inputs to the maximum + rank they will need to be broadcasted to. + + IMPORTANT: This function is heavily optimized for statically known ranks + because it's on the critical path of some huge training graphs. + """ + if len(self._inputs) < 2: + return + + ranks = [ + _rank(inp.t) if inp.is_stacked else (_rank(inp.t) + 1) + for inp in self._inputs + ] + if all(isinstance(rank, int) for rank in ranks): + max_rank = max(ranks) + else: + max_rank = functools.reduce(math_ops.maximum, ranks) + + for i, inp in enumerate(self._inputs): + if not inp.is_stacked: + continue + if isinstance(max_rank, int) and ranks[i] == max_rank: + continue + self._inputs[i] = wrap(_expand_dims(inp.t, 1, max_rank - ranks[i]), True) + + @property + def inputs(self): + return self._inputs + + @property + def num_inputs(self): + return len(self._inputs) + + def input(self, index): + assert len(self._inputs) > index, (index, self._inputs) + return self._inputs[index] + + def stacked_input(self, index): + t, is_stacked, _ = self.input(index) + if not is_stacked: + op_type = self.op_type + op_def = getattr(self._op, "op_def", None) + if op_def is None: + input_name = "at index %d" % index + else: + input_name = "\"%s\"" % op_def.input_arg[index].name + raise ConversionNotImplementedError( + f"Input {input_name} of op '{op_type}' expected to be not loop " + "invariant.") + return t + + def unstacked_input(self, index): + t, is_stacked, _ = self.input(index) + if is_stacked: + op_type = self.op_type + op_def = getattr(self._op, "op_def", None) + if op_def is None: + input_name = "at index %d" % index + else: + input_name = "\"%s\"" % op_def.input_arg[index].name + raise ConversionNotImplementedError( + f"Input {input_name} of op '{op_type}' expected to be loop " + "invariant.") + return t + + @property + def op(self) -> ops.Operation: + return self._op + + @property + def op_type(self): + return self._op.type + + def get_attr(self, attr): + return self._op.get_attr(attr) + + @property + def outputs(self): + return self._op.outputs + + def output(self, index): + assert index < len(self._op.outputs) + return self._op.outputs[index] + + +_pfor_converter_registry = {} + + +class RegisterPFor: + """Utility to register converters for pfor. + + Usage: + @RegisterPFor(foo_op_type) + def _foo_converter(pfor_input: _PforInput): + ... + + The above will register conversion function `_foo_converter` for handling + conversion of `foo_op_type`. These converters are called during vectorization + of a `pfor` loop body. For each operation node in this loop body, + the vectorization process will call the converter corresponding to the + operation type of the node. + + During conversion, the registered function will be called with a single + argument `pfor_input`, of type `PForInput`, which will contain state needed + for the conversion. When the converter is called for a node, all its inputs + should already have been converted and these converted values are stored in + `pfor_input.inputs`. This registered function should output a list of + WrappedTensor objects with the same length as the number of outputs of the + node being converted. If the node had zero outputs, then it should return an + ops.Operation object. These new sets of nodes should implement the + functionality of running that operation for the number of iterations specified + by `pfor_input.pfor.loop_len_vector[0]` where the inputs of the node for each + iteration are picked from `pfor_inputs.inputs()`. + + One tricky aspect of the conversion process is keeping track of, and + leveraging loop invariance of computation. Each converted input is a + WrappedTensor which indicates whether the input was loop invariant or not. If + the converted value is loop invariant, its rank should match the rank of the + corresponding tensor in the loop body, else its rank is larger by 1. The + converter should look at the loop invariance of the inputs and generate new + nodes based on that. Note that the converter will not be called if all inputs + are loop invariant and the operation is not stateful. The converter should + determine if its own output is loop invariant and `wrap` its output + accordingly. + + Example: + + Here, the converter is trying to convert a Reshape node in the loop body. This + node will have two inputs: the tensor to reshape, and the new shape. The + example here only handles the case where the shape is loop invariant. + + @RegisterPFor("Reshape") + def _convert_reshape(pfor_input: _PforInput): + # We assume that input is not loop invariant. Call to `stacked_input` + # asserts that and returns the converted value. This value will have a rank + # larger by 1 compared to the rank of the input in the loop body. + t = pfor_input.stacked_input(0) + + # We assume that shape input is loop invariant. Call to `unstacked_input` + # asserts that and returns the converted value. + shape = pfor_input.unstacked_input(1) + + # We compute `new_shape` by prepending the number of iterations to the + # original shape. + new_shape = array_ops.concat([pfor_input.pfor.loop_len_vector, shape], + axis=0) + + # The vectorized output involves reshaping the converted input `t` using + # `new_shape`. + new_output = array_ops.reshape(t, new_shape) + + # The converted output is marked as not loop invariant using the call to + # wrap. + return wrap(new_output, True) + """ + + def __init__(self, op_type): + """Creates an object to register a converter for op with type `op_type`.""" + self.op_type = op_type + + def __call__(self, converter): + name = self.op_type + assert name not in _pfor_converter_registry, "Re-registering %s " % name + _pfor_converter_registry[name] = converter + return converter + + +class RegisterPForWithArgs(RegisterPFor): + """Utility to register converters for pfor. + + Usage: + @RegisteRPFor(foo_op_type, foo=value, ....) + def _foo_converter(pfor_input, foo=None, ....): + ... + + See RegisterPFor for details on the conversion function. + `RegisterPForWithArgs` allows binding extra arguments to the + conversion function at registration time. + """ + + def __init__(self, op_type, *args, **kw_args): + super(RegisterPForWithArgs, self).__init__(op_type) + self._args = args + self._kw_args = kw_args + + def __call__(self, converter): + + def _f(pfor_input: _PforInput): + return converter(pfor_input, self.op_type, *self._args, **self._kw_args) + + super(RegisterPForWithArgs, self).__call__(_f) + return converter + + +# TODO(agarwal): call raw_ops instead of calling these low level routines. +def _create_op(op_type, inputs, op_dtypes, attrs=None): + """Utility to create an op.""" + op = ops.get_default_graph().create_op( + op_type, inputs, op_dtypes, attrs=attrs, compute_device=True) + flat_attrs = [] + # The tape expects an alternating flat list of names and attribute values. + for a in attrs: + flat_attrs.append(str(a)) + flat_attrs.append(op.get_attr(str(a))) + execute.record_gradient(op_type, op.inputs, tuple(flat_attrs), op.outputs[:]) + return op + + +WrappedTensor = collections.namedtuple("WrappedTensor", + ["t", "is_stacked", "is_sparse_stacked"]) +"""Wrapper around the result of a Tensor conversion. + +The additional fields are useful for keeping track of the conversion state as +data flows through the ops in the loop body. For every op whose output is a +Tensor, its converter should return either a WrappedTensor or a list of +WrappedTensors. + +Args: + t: The converted tensor + is_stacked: True if the tensor is stacked, i.e. represents the results of all + the iterations of the loop, where each row i of the tensor corresponds to + that op's output on iteration i of the loop. False if the tensor is not + stacked, i.e. represents the result of the op on of a single iteration of + the loop, where the result does not vary between iterations. + is_sparse_stacked: True if the tensor corresponds to a component tensor + (indices, values, or dense_shape) of a sparse tensor, and has been logically + stacked via a sparse conversion. +""" + + +def wrap(tensor, is_stacked=True, is_sparse_stacked=False): + """Helper to create a WrappedTensor object.""" + assert isinstance(is_stacked, bool) + assert isinstance(is_sparse_stacked, bool) + assert isinstance(tensor, tensor_lib.Tensor) + assert not is_sparse_stacked or is_stacked, ("If the wrapped tensor is " + "stacked via a sparse " + "conversion, it must also be " + "stacked.") + return WrappedTensor(tensor, is_stacked, is_sparse_stacked) + + +def _wrap_and_tile_variants(tensor, length): + if tensor.dtype == dtypes.variant: + tensor = _tile_variant_with_length(tensor, length) + return wrap(tensor) + + +def _fallback_converter(pfor_input: _PforInput, root_cause="", warn=False): + msg = ("Using a while_loop for converting " + f"{pfor_input.op_type} cause {root_cause}") + if warn: + logging.warning(msg) + else: + logging.debug(msg) + output_dtypes = [x.dtype for x in pfor_input.outputs] + iter_vec = pfor_input.pfor.loop_len_vector + # Use constant value if available, so that output shapes are static. + iter_vec_value = tensor_util.constant_value(iter_vec) + if iter_vec_value is not None: + iters = iter_vec_value[0].item() + else: + iters = iter_vec[0] + + def while_body(i, *ta_list): + """Body of while loop.""" + inputs = [ + x[i, ...] if stacked else x for x, stacked, _ in pfor_input.inputs + ] + op_outputs = _create_op( + pfor_input.op_type, + inputs, + output_dtypes, + attrs=pfor_input.op.node_def.attr).outputs + + outputs = [] + # TODO(agarwal): Add tf.debugging asserts to check that the shapes across + # the different iterations are the same. + for out, ta in zip(op_outputs, ta_list): + assert isinstance(out, tensor_lib.Tensor) + outputs.append(ta.write(i, out)) + return tuple([i + 1] + outputs) + + ta_list = while_loop.while_loop( + lambda i, *ta: i < iters, while_body, [0] + + [tensor_array_ops.TensorArray(dtype, iters) for dtype in output_dtypes + ])[1:] + return tuple([wrap(ta.stack(), True) for ta in ta_list]) + + +class PForConfig: + """A configuration object used to communicate with loop body function.""" + + def __init__(self): + # This may be set to the number of iterations. + self._maybe_iters = None + # Map from reduction node, created by `reduce`, to the bundle of reduction + # function and arguments. + self._reduce_map = {} + + def _has_reductions(self): + """True if some reductions where performed by loop body.""" + return len(self._reduce_map) + + def _set_iters(self, iters): + """Set number of pfor iterations.""" + if isinstance(iters, tensor_lib.Tensor): + iters = tensor_util.constant_value(iters) + self._maybe_iters = iters + + def reduce(self, fn, *args): + """Performs reduction `fn` on `args` vectorized across pfor iterations. + + Note that `fn` is traced once inside the loop function context. Hence any + captures or side-effects will happen in that context. Call to the traced + version of `fn` happens during the construction of the vectorized code. + + Note that this currently may not work inside a control flow construct. + Args: + fn: a reduction function. It will be called with arguments that have the + same structure as *args but with individual values whose rank may be + higher by 1 since they represent loop invariant vectorized versions of + the corresponding Tensors in *args. + *args: unvectorized Tensors. + + Returns: + The result of running `fn` on the vectorized versions of `*args`. These + outputs will be available as loop invariant values to all the iterations. + """ + assert not context.executing_eagerly() + # Creates a concrete function that will be used for reduction. + tensor_specs = [] + for arg in args: + if not isinstance(arg, tensor_lib.Tensor): + raise ValueError(f"Got a non-Tensor argument {arg} in reduce.") + batched_shape = tensor_shape.TensorShape([self._maybe_iters + ]).concatenate(arg.shape) + tensor_specs.append( + tensor_lib.TensorSpec(shape=batched_shape, dtype=arg.dtype)) + concrete_function = def_function.function(fn).get_concrete_function( + *tensor_specs) + + # Creates PlaceholderWithDefault and IdentityN nodes corresponding the + # reduction. + pl_outputs = [] + with ops.control_dependencies(args): + for output in concrete_function.outputs: + if not isinstance(output, tensor_lib.Tensor): + raise ValueError(f"Got a non-Tensor output {output} while running " + "reduce.") + # Note that we use placeholder_with_default just to make XLA happy since + # it does not like placeholder ops. + if output.shape.is_fully_defined(): + dummy = array_ops.zeros(output.shape.as_list(), dtype=output.dtype) + pl_outputs.append( + array_ops.placeholder_with_default(dummy, shape=output.shape)) + else: + # TODO(agarwal): support case when under XLA and output.shape is not + # fully defined. + pl_outputs.append( + array_ops.placeholder(output.dtype, shape=output.shape)) + + reduction_op = array_ops.identity_n(pl_outputs)[0].op + self._reduce_map[reduction_op] = (concrete_function, args) + if len(reduction_op.outputs) == 1: + return reduction_op.outputs[0] + else: + return tuple(reduction_op.outputs) + + # TODO(agarwal): handle reductions inside control flow constructs. + def reduce_concat(self, x): + """Performs a concat reduction on `x` across pfor iterations. + + Note that this currently may not work inside a control flow construct. + Args: + x: an unvectorized Tensor. + + Returns: + A Tensor that has rank one higher than `x`. The value is the vectorized + version of `x`, i.e. stacking the value of `x` across different pfor + iterations. + """ + return self.reduce(lambda y: y, x) + + def reduce_mean(self, x): + """Performs a mean reduction on `x` across pfor iterations. + + Note that this currently may not work inside a control flow construct. + Args: + x: an unvectorized Tensor. + + Returns: + A Tensor that has same rank as `x`. The value is the mean of the values + of `x` across the pfor iterations. + """ + return self.reduce(lambda y: math_ops.reduce_mean(y, axis=0), x) + + def reduce_sum(self, x): + """Performs a sum reduction on `x` across pfor iterations. + + Note that this currently may not work inside a control flow construct. + Args: + x: an unvectorized Tensor. + + Returns: + A Tensor that has same rank as `x`. The value is the sum of the values + of `x` across the pfor iterations. + """ + return self.reduce(lambda y: math_ops.reduce_sum(y, axis=0), x) + + def _lookup_reduction(self, t): + """Lookups Tensor `t` in the reduction maps.""" + assert isinstance(t, tensor_lib.Tensor), t + return self._reduce_map.get(t.op) + + +class PFor: + """Implementation of rewrite of parallel-for loops. + + This class takes a DAG or a set of DAGs representing the body of a + parallel-for loop, and adds new operations to the graph that implements + functionality equivalent to running that loop body for a specified number of + iterations. This new set of nodes may or may not use a tensorflow loop + construct. + + The process of conversion does not delete or change any existing operations. + It only adds operations that efficiently implement the equivalent + functionality. We refer to the added ops as "converted ops". + + The conversion process uses a simple greedy heuristic. It walks the loop body + and tries to express the functionality of running each node in a loop with a + new set of nodes. When converting an op several cases are possible: + - The op is not inside the loop body. Hence it can be used as is. + - The op does not depend on the iteration number and is stateless. In this + case, it can be used as is. + - The op is not stateful, and depends on iteration number only through control + dependencies. In this case, we can create a single op with same inputs and + attributes, but with "converted" control dependencies. + - The op is not stateful, and all its inputs are loop invariant. In this + case, similar to above, we can create a single op with same inputs and + attributes, but with "converted" control dependencies. + - The op is stateful or at least one of the inputs is not loop invariant. In + this case, we run the registered converter for that op to create a set of + converted ops. All nodes in the set will have converted control dependencies + corresponding to control dependencies of the original op. If the op returned + multiple outputs, "converted outputs" could be produced by different ops in + this set. + """ + + def __init__(self, + loop_var, + loop_len, + pfor_ops, + fallback_to_while_loop, + all_indices=None, + all_indices_partitioned=False, + pfor_config=None, + warn=False): + """Creates an object to rewrite a parallel-for loop. + + Args: + loop_var: Tensor output of a Placeholder operation. The value should + be an int32 scalar representing the loop iteration number. + loop_len: A scalar or scalar Tensor representing the number of iterations + the loop is run for. + pfor_ops: List of all ops inside the loop body. + fallback_to_while_loop: If True, on failure to vectorize an op, a while + loop is used to sequentially execute that op. + all_indices: If not None, an int32 vector with size `loop_len` + representing the iteration ids that are still active. These values + should be unique and sorted. However they may not be contiguous. This is + typically the case when inside a control flow construct which has + partitioned the indices of the iterations that are being converted. + all_indices_partitioned: If True, this object is being constructed from a + control flow construct where not all the pfor iterations are guaranteed + to be active. + pfor_config: PForConfig object used while constructing the loop body. + warn: Whether or not to warn on while loop conversions. + """ + assert isinstance(loop_var, tensor_lib.Tensor) + assert loop_var.op.type == "PlaceholderWithDefault" + self._loop_var = loop_var + loop_len_value = tensor_util.constant_value(loop_len) + if loop_len_value is not None: + loop_len = loop_len_value + self._loop_len_vector = ops.convert_to_tensor([loop_len]) + else: + self._loop_len_vector = array_ops.reshape(loop_len, [1]) + self._all_indices_partitioned = all_indices_partitioned + if all_indices_partitioned: + assert all_indices is not None + self.all_indices = ( + math_ops.range(loop_len) if all_indices is None else all_indices) + + self._conversion_map = object_identity.ObjectIdentityDictionary() + self._conversion_map[loop_var] = wrap(self.all_indices, True) + self._pfor_ops = set(pfor_ops) + self._pfor_op_ids = set(x._id for x in pfor_ops) + self._fallback_to_while_loop = fallback_to_while_loop + self._warn = warn + self._pfor_config = pfor_config + + def op_is_inside_loop(self, op): + """True if op was created inside the pfor loop body.""" + assert isinstance(op, ops.Operation) + # Note that we use self._pfor_op_ids for the check and not self._pfor_ops + # since it appears there tensorflow API could return different python + # objects representing the same Operation node. + return op._id in self._pfor_op_ids + + def _convert_sparse(self, y): + """Returns the converted value corresponding to SparseTensor y. + + For SparseTensors, instead of stacking the component tensors separately, + resulting in component tensors with shapes (N, m, rank), (N, m), and (N, + rank) respectively for indices, values, and dense_shape (where N is the loop + length and m is the number of sparse tensor values per loop iter), we want + to logically stack the SparseTensors, to create a SparseTensor whose + components are size (N * m, rank + 1), (N * m, ), and (rank + 1,) + respectively. + + Here, we try to get the conversion of each component tensor. + If the tensors are stacked via a sparse conversion, return the resulting + SparseTensor composed of the converted components. Otherwise, the component + tensors are either unstacked or stacked naively. In the latter case, we + unstack the component tensors to reform loop_len SparseTensor elements, + then correctly batch them. + + The unstacked tensors must have the same rank. Each dimension of each + SparseTensor will expand to be the largest among all SparseTensor elements + for that dimension. For example, if there are N SparseTensors of rank 3 + being stacked, with N dense shapes, where the i_th shape is (x_i, y_i, z_i), + the new dense shape will be (N, max_i(x_i), max_i(y_i), max_i(z_i)). + + Args: + y: A tf.sparse.SparseTensor. + + Returns: + A tf.sparse.SparseTensor that is the converted value corresponding to y. + """ + outputs = [ + self._convert_helper(t) for t in (y.indices, y.values, y.dense_shape) + ] + assert all(isinstance(o, WrappedTensor) for o in outputs) + + if all(w.is_sparse_stacked for w in outputs): + return sparse_tensor.SparseTensor(*[w.t for w in outputs]) + + assert not any(w.is_sparse_stacked for w in outputs), ( + "Error converting SparseTensor. All components should be logically " + "stacked, or none.") + + # If component tensors were not sparsely stacked, they are either unstacked + # or stacked without knowledge that they are components of sparse tensors. + # In this case, we have to restack them. + return self._restack_sparse_tensor_logically( + *[self._unwrap_or_tile(w) for w in outputs]) + + def _restack_sparse_tensor_logically(self, indices, values, shape): + sparse_tensor_rank = indices.get_shape().dims[-1].value + if sparse_tensor_rank is not None: + sparse_tensor_rank += 1 + + def fn(args): + res = gen_sparse_ops.serialize_sparse( + args[0], args[1], args[2], out_type=dtypes.variant) + return res + + # Applies a map function to the component tensors to serialize each + # sparse tensor element and batch them all, then deserializes the batch. + # TODO(rachelim): Try to do this without map_fn -- add the right offsets + # to shape and indices tensors instead. + result = map_fn.map_fn(fn, [indices, values, shape], dtype=dtypes.variant) + return sparse_ops.deserialize_sparse( + result, dtype=values.dtype, rank=sparse_tensor_rank) + + def _unwrap_or_tile(self, wrapped_tensor): + """Given a wrapped tensor, unwrap if stacked. Otherwise, tiles it.""" + output, is_stacked = wrapped_tensor.t, wrapped_tensor.is_stacked + if is_stacked: + return output + else: + return _stack(output, self._loop_len_vector).t + + def convert(self, y): + """Returns the converted value corresponding to y. + + Args: + y: A Tensor or a ops.Operation object. If latter, y should not have + any outputs. + + Returns: + If y does not need to be converted, it returns y as is. Else it returns + the "converted value" corresponding to y. + """ + if y is None: + return None + if isinstance(y, sparse_tensor.SparseTensor): + return self._convert_sparse(y) + assert isinstance(y, (tensor_lib.Tensor, ops.Operation)), y + output = self._convert_helper(y) + if isinstance(output, WrappedTensor): + assert isinstance(y, tensor_lib.Tensor) + return self._unwrap_or_tile(output) + else: + assert isinstance(y, ops.Operation) + assert not y.outputs + assert isinstance(output, ops.Operation) + return output + + def _was_converted(self, t): + """True if t is not a conversion of itself.""" + converted_t = self._conversion_map[t] + return converted_t.t is not t + + def _add_conversion(self, old_output, new_output): + assert isinstance( + old_output, (tensor_lib.Tensor, ops.Operation)), old_output + assert isinstance(new_output, (WrappedTensor, ops.Operation)), new_output + self._conversion_map[old_output] = new_output + + def _convert_reduction(self, y): + # Handle reductions. + if self._pfor_config is None or isinstance(y, ops.Operation): + return None + reduction = self._pfor_config._lookup_reduction(y) + if reduction is None: + return None + (reduction_fn, reduction_args) = reduction + batched_args = [] + for reduction_arg in reduction_args: + assert isinstance(reduction_arg, tensor_lib.Tensor), reduction_arg + # Tensor being reduced should already be converted due to a control + # dependency on the created placeholder. + # Note that in cases where reduction_arg is in an outer context, one + # needs to locate the corresponding Enter node and use that to lookup + # the conversion. + # TODO(agarwal): handle reductions inside control flow constructs. + assert reduction_arg in self._conversion_map, ( + "Unable to handle reduction of %s, possibly as it was used " + "inside a control flow construct. Note that reductions across " + "pfor iterations are currently not supported inside control flow " + "constructs." % reduction_arg) + batched_arg = self._conversion_map[reduction_arg] + batched_args.append(self._unwrap_or_tile(batched_arg)) + outputs = reduction_fn(*batched_args) + return [wrap(output, False) for output in nest.flatten(outputs)] + + def _convert_helper(self, op_or_tensor): + stack = collections.deque([op_or_tensor]) + while stack: + y = stack[0] + if y in self._conversion_map: + assert isinstance(self._conversion_map[y], + (WrappedTensor, ops.Operation)) + stack.popleft() + continue + if isinstance(y, ops.Operation): + assert not y.outputs, ( + "We only support converting Operation objects with no outputs. " + "Got %s", y) + y_op = y + else: + assert isinstance(y, tensor_lib.Tensor), y + y_op = y.op + + is_while_loop = y_op.type == "Exit" + if is_while_loop: + while_op = WhileOp( + y, pfor_ops=self._pfor_ops, + fallback_to_while_loop=self.fallback_to_while_loop, + pfor_config=self._pfor_config) + is_inside_loop = while_op.is_inside_loop + # If all nodes in the while_loop graph were created inside the pfor, we + # treat the whole loop subgraph as a single op (y_op) and try to convert + # it. For while_loops that are created completely or partially outside, + # we treat them as external and should be able to simply return the Exit + # node output as is without needing any conversion. Note that for + # while_loops that are partially constructed inside, we assume they will + # be loop invariant. If that is not the case, it will create runtime + # errors since the converted graph would depend on the self._loop_var + # placeholder. + if is_inside_loop: + y_op = while_op + else: + is_inside_loop = self.op_is_inside_loop(y_op) + + # If this op was not created inside the loop body, we will return as is. + # 1. Convert inputs and control inputs. + + def _add_to_stack(x): + if x not in self._conversion_map: + stack.appendleft(x) + return True + else: + return False + + if is_inside_loop: + added_to_stack = False + for inp in y_op.inputs: + added_to_stack |= _add_to_stack(inp) + for cinp in y_op.control_inputs: + if cinp.outputs: + for t in cinp.outputs: + added_to_stack |= _add_to_stack(t) + else: + added_to_stack |= _add_to_stack(cinp) + if added_to_stack: + continue + + converted_inputs = [self._conversion_map[inp] for inp in y_op.inputs] + some_input_converted = any(self._was_converted(x) for x in y_op.inputs) + some_input_stacked = any(x.is_stacked for x in converted_inputs) + + converted_control_ops = set() + some_control_input_converted = False + for cinp in y_op.control_inputs: + if cinp.outputs: + for t in cinp.outputs: + converted_t = self._conversion_map[t] + if self._was_converted(t): + some_control_input_converted = True + converted_control_ops.add(converted_t.t.op) + else: + converted_cinp = self._conversion_map[cinp] + assert isinstance(converted_cinp, ops.Operation) + if converted_cinp != cinp: + some_control_input_converted = True + converted_control_ops.add(converted_cinp) + converted_control_ops = list(converted_control_ops) + is_stateful = _is_stateful_pfor_op(y_op) + else: + converted_inputs = [] + converted_control_ops = [] + logging.vlog(3, "converting op:%s\ninputs:%s\ncontrol_inputs:%s", y_op, + converted_inputs, converted_control_ops) + + # 2. Convert y_op + # If converting a while_loop, we let the while_loop convertor deal with + # putting the control dependencies appropriately. + control_dependencies = [] if is_while_loop else converted_control_ops + with ops.control_dependencies(control_dependencies), ops.name_scope( + y_op.name + "/pfor/"), ops.get_default_graph()._original_op(y_op): + # Op is a placeholder for a reduction. + reduce_output = self._convert_reduction(y) + if reduce_output is not None: + new_outputs = reduce_output + # None of the inputs and control inputs were converted. + elif ((not is_inside_loop or + (not is_stateful and not some_input_converted and + not some_control_input_converted)) and + y.graph == ops.get_default_graph()): + if y is y_op: + assert not isinstance(y_op, WhileOp) + new_outputs = y_op + else: + new_outputs = [wrap(x, False) for x in y_op.outputs] + elif not (is_stateful or is_while_loop or some_input_stacked): + # All inputs are unstacked or unconverted but some control inputs are + # converted. + # TODO(rachelim): Handle the case where some inputs are sparsely + # stacked (i.e. any(x.is_sparse_stacked for x in converted_inputs)) + new_op = _create_op(y_op.type, [x.t for x in converted_inputs], + [x.dtype for x in y_op.outputs], + y_op.node_def.attr) + if y is y_op: + new_outputs = new_op + else: + new_outputs = [] + for old_output, new_output in zip(y_op.outputs, new_op.outputs): + handle_data_util.copy_handle_data(old_output, new_output) + new_outputs.append(wrap(new_output, False)) + else: + # Either some inputs are not loop invariant or op is stateful. + if hasattr(y_op, "pfor_converter"): + converter = y_op.pfor_converter + else: + converter = _pfor_converter_registry.get(y_op.type, None) + if converter is None: + root_cause = "there is no registered converter for this op." + has_variant_outputs = any(x.dtype == dtypes.variant for x in + y_op.outputs) + has_vectorized_variant_inputs = any( + _is_variant_with_internal_stacking(x) for x in + y_op.inputs) + if (self._fallback_to_while_loop and not has_variant_outputs + and not has_vectorized_variant_inputs): + converter = functools.partial( + _fallback_converter, root_cause=root_cause, warn=self._warn) + else: + message = (f"No pfor vectorization defined for {y_op.type}\n" + f"{y_op}\n inputs: {converted_inputs}.") + if not self._fallback_to_while_loop: + message += ("Consider enabling the fallback_to_while_loop " + "option to pfor, which may run slower.") + raise ValueError(message) + # TODO(rachelim): Handle the case where some inputs are sparsely + # stacked. We should only call the converter if it supports handling + # those inputs. + pfor_inputs = _PforInput(self, y_op, converted_inputs) + try: + try: + new_outputs = converter(pfor_inputs) + except ConversionNotImplementedError as e: + has_vectorized_variant_inputs = any( + _is_variant_with_internal_stacking(x) for x in + y_op.inputs) + if (self._fallback_to_while_loop + and not has_vectorized_variant_inputs): + new_outputs = _fallback_converter( + pfor_inputs, root_cause=str(e)) + else: + raise ValueError(str(e)).with_traceback(sys.exc_info()[2]) + except Exception as e: # pylint: disable=broad-except + logging.error( + f"Got error while pfor was converting op {y_op} with inputs " + f"{y_op.inputs[:]}\n, converted inputs {pfor_inputs.inputs}\n" + f"Here are the pfor conversion stack traces: {e}") + original_op = y_op + while isinstance(original_op, ops.Operation): + logging.error( + "%s\ncreated at:\n %s", original_op, + " ".join(traceback.format_list(original_op.traceback))) + original_op = original_op._original_op + raise + + if isinstance(new_outputs, WrappedTensor): + new_outputs = [new_outputs] + assert isinstance(new_outputs, + (list, tuple, ops.Operation)), new_outputs + logging.vlog(2, f"converted {y_op} {new_outputs}") + + # Insert into self._conversion_map + if y is y_op: + assert isinstance(new_outputs, ops.Operation) + self._add_conversion(y_op, new_outputs) + else: + assert len(y_op.outputs) == len(new_outputs), (y_op, y_op.outputs, + new_outputs) + for old_output, new_output in zip(y_op.outputs, new_outputs): + assert isinstance(new_output, WrappedTensor), (new_output, y, y_op) + assert old_output.dtype == new_output.t.dtype, (new_output, y, y_op) + # Set shape for converted output. + output_shape = old_output.shape + if not new_output.is_sparse_stacked: + if new_output.is_stacked: + loop_len = tensor_util.constant_value(self.loop_len_vector) + if loop_len is None: + batch_dim = tensor_shape.TensorShape([None]) + else: + batch_dim = tensor_shape.TensorShape(loop_len) + output_shape = batch_dim.concatenate(output_shape) + if _is_variant_with_internal_stacking(new_output.t): + new_output.t.set_shape([]) + else: + new_output.t.set_shape(output_shape) + self._add_conversion(old_output, new_output) + stack.popleft() + + return self._conversion_map[op_or_tensor] + + @property + def loop_len_vector(self): + """Returns a single element vector whose value is number of iterations.""" + return self._loop_len_vector + + @property + def loop_var(self): + """Returns placeholder loop variable.""" + return self._loop_var + + @property + def pfor_ops(self): + return self._pfor_ops + + @property + def pfor_config(self): + return self._pfor_config + + @property + def all_indices_partitioned(self): + """all_indices_partitioned property. + + Returns: + True if we are inside a control flow construct and not all pfor iterations + may be active. + """ + return self._all_indices_partitioned + + @property + def fallback_to_while_loop(self): + return self._fallback_to_while_loop + + +# The code below defines converters for different operations. Please see comment +# for RegisterPFor to see how converters should be defined. + + +# image_ops + + +@RegisterPFor("AdjustContrastv2") +def _convert_adjust_contrastv2(pfor_input: _PforInput): + images = pfor_input.stacked_input(0) + contrast_factor = pfor_input.unstacked_input(1) + return wrap(gen_image_ops.adjust_contrastv2(images, contrast_factor), True) + + +@RegisterPFor("AdjustHue") +def _convert_adjust_hue(pfor_input: _PforInput): + images = pfor_input.stacked_input(0) + delta = pfor_input.unstacked_input(1) + return wrap(gen_image_ops.adjust_hue(images, delta), True) + + +@RegisterPFor("AdjustSaturation") +def _convert_adjust_saturation(pfor_input: _PforInput): + images = pfor_input.stacked_input(0) + scale = pfor_input.unstacked_input(1) + return wrap(gen_image_ops.adjust_saturation(images, scale), True) + + +# nn_ops + + +def _flatten_first_two_dims(x): + """Merges first two dimensions.""" + old_shape = array_ops.shape(x) + first_dim = constant_op.constant([-1], dtype=old_shape.dtype) + new_shape = array_ops.concat([first_dim, old_shape[2:]], axis=0) + return array_ops.reshape(x, new_shape) + + +def _unflatten_first_dim(x, first_dim): + """Splits first dimension into [first_dim, -1].""" + old_shape = array_ops.shape(x) + first_dim = math_ops.cast(first_dim, old_shape.dtype) + second_dim = constant_op.constant([-1], dtype=old_shape.dtype) + new_shape = array_ops.concat([first_dim, second_dim, old_shape[1:]], axis=0) + return array_ops.reshape(x, new_shape) + + +def _inputs_with_flattening(pfor_input: _PforInput, input_indices): + """Stacks and flattens first dim of inputs at indices `input_indices`.""" + if input_indices is None: + input_indices = [] + pfor_input.stack_inputs(stack_indices=input_indices) + inputs = [] + for i in range(pfor_input.num_inputs): + if i in input_indices: + inp = pfor_input.stacked_input(i) + inp = _flatten_first_two_dims(inp) + else: + inp = pfor_input.unstacked_input(i) + inputs.append(inp) + return inputs + + +@RegisterPForWithArgs("Conv2D", dims=[0]) +@RegisterPForWithArgs("DepthToSpace", dims=[0]) +@RegisterPForWithArgs("AvgPool", dims=[0]) +@RegisterPForWithArgs("AvgPool3D", dims=[0]) +@RegisterPForWithArgs("MaxPool", dims=[0]) +@RegisterPForWithArgs("MaxPoolV2", dims=[0]) +@RegisterPForWithArgs("MaxPool3D", dims=[0]) +@RegisterPForWithArgs("MaxPool3DGrad", dims=[0, 1, 2]) +@RegisterPForWithArgs("MaxPoolGrad", dims=[0, 1, 2]) +@RegisterPForWithArgs("MaxPoolGradV2", dims=[0, 1, 2]) +@RegisterPForWithArgs("MaxPool3DGradGrad", dims=[0, 1, 2]) +@RegisterPForWithArgs("MaxPoolGradGrad", dims=[0, 1, 2]) +@RegisterPForWithArgs("MaxPoolGradGradV2", dims=[0, 1, 2]) +@RegisterPForWithArgs("SoftmaxCrossEntropyWithLogits", dims=[0, 1]) +@RegisterPForWithArgs("SparseSoftmaxCrossEntropyWithLogits", dims=[0, 1]) +@RegisterPForWithArgs("SpaceToDepth", dims=[0]) +def _convert_flatten_batch(pfor_input: _PforInput, op_type, dims): + del op_type + inputs = _inputs_with_flattening(pfor_input, dims) + outputs = _create_op( + pfor_input.op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + n = pfor_input.pfor.loop_len_vector + outputs = [_unflatten_first_dim(x, n) for x in outputs] + return [wrap(x, True) for x in outputs] + + +_channel_flatten_input_cache = {} + + +@RegisterPFor("BatchToSpaceND") +def _convert_batch_to_space_nd(pfor_input: _PforInput): + inp = pfor_input.stacked_input(0) + block_shape = pfor_input.unstacked_input(1) + crops = pfor_input.unstacked_input(2) + + inp_shape = array_ops.shape(inp) + n = math_ops.cast(pfor_input.pfor.loop_len_vector, inp_shape.dtype) + block_shape = math_ops.cast(block_shape, inp_shape.dtype) + + # Reshape and transpose to move the vectorization axis inside the axes that + # will move to space. + # Reshape to 4D and transpose + block_size = math_ops.reduce_prod(block_shape) + neg_one = constant_op.constant(-1, dtype=inp_shape.dtype) + new_shape = [n[0], block_size, inp_shape[1] // block_size, neg_one] + inp = array_ops.reshape(inp, new_shape) + + inp = array_ops.transpose(inp, [1, 0, 2, 3]) + # Reshape back to merge the block, vectorization and batch dimension, and + # restore the other dimensions. + new_shape = array_ops.concat([n * inp_shape[1], inp_shape[2:]], axis=0) + inp = array_ops.reshape(inp, new_shape) + + # Call batch_to_space and then split the new batch axis. + output = gen_array_ops.batch_to_space_nd(inp, block_shape, crops) + output = _unflatten_first_dim(output, n) + return wrap(output, True) + + +@RegisterPFor("SpaceToBatchND") +def _convert_space_to_batch_nd(pfor_input: _PforInput): + inp = pfor_input.stacked_input(0) + block_shape = pfor_input.unstacked_input(1) + paddings = pfor_input.unstacked_input(2) + + inp_shape = array_ops.shape(inp) + n = math_ops.cast(pfor_input.pfor.loop_len_vector, inp_shape.dtype) + block_shape = math_ops.cast(block_shape, inp_shape.dtype) + + inp = _flatten_first_two_dims(inp) + output = gen_array_ops.space_to_batch_nd(inp, block_shape, paddings) + output_shape = array_ops.shape(output) + + block_size = math_ops.reduce_prod(block_shape) + neg_one = constant_op.constant(-1, dtype=inp_shape.dtype) + new_shape = [block_size, n[0], neg_one] + output = array_ops.reshape(output, new_shape) + + output = array_ops.transpose(output, [1, 0, 2]) + new_shape = array_ops.concat( + [n, block_size * inp_shape[1:2], output_shape[1:]], axis=0) + output = array_ops.reshape(output, new_shape) + return wrap(output, True) + + +def _channel_flatten_input(x, data_format): + """Merge the stack dimension with the channel dimension. + + If S is pfor's stacking dimension, then, + - for SNCHW, we transpose to NSCHW. If N dimension has size 1, the transpose + should be cheap. + - for SNHWC, we transpose to NHWSC. + We then merge the S and C dimension. + + Args: + x: tensor_lib.Tensor to transform. + data_format: "NCHW" or "NHWC". + + Returns: + A 3-element tuple with the transformed value, along with the shape for + reshape and order for transpose required to transform back. + """ + + graph = ops.get_default_graph() + cache_key = (graph, x.ref(), data_format) + if cache_key not in _channel_flatten_input_cache: + x_shape = array_ops.shape(x) + neg_ones = constant_op.constant([-1], dtype=x_shape.dtype) + if data_format == b"NCHW": + order = [1, 0, 2, 3, 4] + shape = array_ops.concat([x_shape[1:2], neg_ones, x_shape[3:]], axis=0) + reverse_order = order + else: + order = [1, 2, 3, 0, 4] + shape = array_ops.concat([x_shape[1:4], neg_ones], axis=0) + reverse_order = [3, 0, 1, 2, 4] + # Move S dimension next to C dimension. + x = array_ops.transpose(x, order) + reverse_shape = array_ops.shape(x) + # Reshape to merge the S and C dimension. + x = array_ops.reshape(x, shape) + outputs = x, reverse_order, reverse_shape + _channel_flatten_input_cache[cache_key] = outputs + else: + outputs = _channel_flatten_input_cache[cache_key] + return outputs + + +# Note that with training=True, running FusedBatchNormV3 on individual examples +# is very different from running FusedBatchNormV3 on a batch of those examples. +# This is because, for the latter case, the operation can be considered as first +# computing the mean and variance over all the examples and then using these +# to scale all those examples. This creates a data dependency between these +# different "iterations" since the inputs to the scaling step depends on the +# statistics coming from all these inputs. +# As with other kernels, the conversion here effectively runs the kernel +# independently for each iteration, and returns outputs by stacking outputs from +# each of those iterations. +@RegisterPFor("FusedBatchNormV3") +def _convert_fused_batch_norm(pfor_input: _PforInput): + is_training = pfor_input.get_attr("is_training") + # When BatchNorm is used with training=False, mean and variance are provided + # externally and used as is by the op. Thus, we can merge the S and N + # dimensions as we do for regular operations. + # When BatchNorm is used with training=True, mean and variance are computed + # for each channel across the batch dimension (first one). If we merge S and N + # dimensions, mean and variances will be computed over a larger set. So, we + # merge the S and C dimensions instead. + if not is_training: + # We return zeros for batch_mean and batch_variance output. Note that CPU + # and GPU seem to have different behavior for those two outputs. CPU outputs + # zero because these values are not used during inference. GPU outputs + # something, probably real means and variances. + inputs = _inputs_with_flattening(pfor_input, [0]) + outputs = _create_op( + pfor_input.op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + y = outputs[0] + n = pfor_input.pfor.loop_len_vector + y = _unflatten_first_dim(y, n) + mean = pfor_input.unstacked_input(3) + zeros = array_ops.zeros_like(mean) + return [wrap(y, True)] + [wrap(zeros, False)] * 5 + + pfor_input.stack_inputs() + data_format = pfor_input.get_attr("data_format") + # We merge the first dimension with the "C" dimension, run FusedBatchNormV3, + # and then transpose back. + x = pfor_input.stacked_input(0) + x, reverse_order, reverse_shape = _channel_flatten_input(x, data_format) + # Note that we stack all the other inputs as well so that they are the same + # size as the new size of the channel dimension. + inputs = [x] + [ + array_ops.reshape(pfor_input.stacked_input(i), [-1]) + for i in range(1, pfor_input.num_inputs) + ] + outputs = _create_op( + pfor_input.op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + y = outputs[0] + y = array_ops.reshape(y, reverse_shape) + y = array_ops.transpose(y, reverse_order) + n = pfor_input.pfor.loop_len_vector + outputs = [_unflatten_first_dim(x, n) for x in outputs[1:]] + outputs = [y] + outputs + return [wrap(x, True) for x in outputs] + + +@RegisterPFor("FusedBatchNormGradV3") +def _convert_fused_batch_norm_grad(pfor_input: _PforInput): + pfor_input.stack_inputs() + data_format = pfor_input.get_attr("data_format") + y_backprop = pfor_input.stacked_input(0) + y_backprop, _, _ = _channel_flatten_input(y_backprop, data_format) + x = pfor_input.stacked_input(1) + x, x_reverse_order, x_reverse_shape = _channel_flatten_input(x, data_format) + inputs = [y_backprop, x] + [ + array_ops.reshape(pfor_input.stacked_input(i), [-1]) + for i in range(2, pfor_input.num_inputs) + ] + outputs = _create_op( + pfor_input.op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + x_backprop = outputs[0] + x_backprop = array_ops.reshape(x_backprop, x_reverse_shape) + x_backprop = array_ops.transpose(x_backprop, x_reverse_order) + n = pfor_input.pfor.loop_len_vector + outputs = [_unflatten_first_dim(x, n) for x in outputs[1:]] + outputs = [x_backprop] + outputs + return [wrap(output, True) for output in outputs] + + +@RegisterPForWithArgs("Conv2DBackpropInput", flatten_dims=[2], shape_dim=0) +@RegisterPForWithArgs("AvgPoolGrad", flatten_dims=[1], shape_dim=0) +@RegisterPForWithArgs("AvgPool3DGrad", flatten_dims=[1], shape_dim=0) +def _convert_flatten_batch_shape_input( + pfor_input: _PforInput, op_type, flatten_dims, shape_dim): + del op_type + inputs = _inputs_with_flattening(pfor_input, flatten_dims) + n = pfor_input.pfor.loop_len_vector + # Adjust the `input_sizes` input. + ones = array_ops.ones([array_ops.shape(inputs[shape_dim])[0] - 1], + dtype=n.dtype) + inputs[shape_dim] *= array_ops.concat([n, ones], axis=0) + outputs = _create_op( + pfor_input.op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + outputs = [_unflatten_first_dim(x, n) for x in outputs] + return [wrap(x, True) for x in outputs] + + +@RegisterPFor("Conv2DBackpropFilter") +def _convert_conv2d_backprop_filter(pfor_input: _PforInput): + pfor_input.stack_inputs(stack_indices=[2]) + inputs, inputs_stacked, _ = pfor_input.input(0) + filter_sizes = pfor_input.unstacked_input(1) + grads = pfor_input.stacked_input(2) + strides = pfor_input.get_attr("strides") + padding = pfor_input.get_attr("padding") + use_cudnn_on_gpu = pfor_input.get_attr("use_cudnn_on_gpu") + data_format = pfor_input.get_attr("data_format") + dilations = pfor_input.get_attr("dilations") + if inputs_stacked: + # TODO(agarwal): Implement this efficiently. + logging.warning("Conv2DBackpropFilter uses a while_loop. Fix that!") + + def while_body(i, ta): + inp_i = inputs[i, ...] + grad_i = grads[i, ...] + output = nn_ops.conv2d_backprop_filter( + inp_i, + filter_sizes, + grad_i, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format, + dilations=dilations) + return i + 1, ta.write(i, output) + + n = array_ops.reshape(pfor_input.pfor.loop_len_vector, []) + _, ta = while_loop.while_loop( + lambda i, ta: i < n, while_body, + (0, tensor_array_ops.TensorArray(inputs.dtype, n))) + output = ta.stack() + return wrap(output, True) + else: + # We merge the stack dimension with the channel dimension of the gradients + # and pretend we had a larger filter (see change to filter_sizes below). + # Once the filter backprop is computed, we reshape and transpose back + # appropriately. + grads, _, _ = _channel_flatten_input(grads, data_format) + n = pfor_input.pfor.loop_len_vector + old_filter_sizes = filter_sizes + filter_sizes *= array_ops.concat([[1, 1, 1], n], axis=0) + output = nn_ops.conv2d_backprop_filter( + inputs, + filter_sizes, + grads, + strides=strides, + padding=padding, + use_cudnn_on_gpu=use_cudnn_on_gpu, + data_format=data_format, + dilations=dilations) + new_filter_shape = array_ops.concat([old_filter_sizes[:3], n, [-1]], axis=0) + output = array_ops.reshape(output, new_filter_shape) + output = array_ops.transpose(output, [3, 0, 1, 2, 4]) + return wrap(output, True) + + +def _flatten_with_inner_dim(x, dim, x_rank): + """Merges the first dim with the specified dim.""" + shape = array_ops.shape(x) + x = array_ops.transpose(x, + list(range(1, dim)) + [0] + list(range(dim, x_rank))) + + if dim < x_rank - 1: + new_shape_pieces = [shape[1:dim], [-1], shape[dim + 1:]] + else: + new_shape_pieces = [shape[1:dim], [-1]] + new_shape = array_ops.concat(new_shape_pieces, axis=0) + return array_ops.reshape(x, new_shape) + + +def _unflatten_with_inner_dim(x, dim, x_rank, stack_size): + """Undoes _flatten_with_inner_dim.""" + shape = array_ops.shape(x) + if dim < x_rank - 1: + new_shape_pieces = [shape[:dim], [stack_size], [-1], shape[dim + 1:]] + else: + new_shape_pieces = [shape[:dim], [stack_size], [-1]] + new_shape = array_ops.concat(new_shape_pieces, axis=0) + x = array_ops.reshape(x, new_shape) + dims_permutation = [dim] + list(range(dim)) + list(range(dim + 1, x_rank + 1)) + return array_ops.transpose(x, dims_permutation) + + +@RegisterPFor("DepthwiseConv2dNative") +def _convert_depthwise_conv2d_native(pfor_input: _PforInput): + # Kernel can be vectorized, so folding to batch dimension does not work. We + # instead fold into the channel dimension because it is parallel. + stack_size = pfor_input.pfor.loop_len_vector[0] + data_format = pfor_input.get_attr("data_format") + c_dim = 1 if data_format == b"NCHW" else 3 + t = _flatten_with_inner_dim(pfor_input.stacked_input(0), c_dim + 1, 5) + kernel = _flatten_with_inner_dim(pfor_input.stacked_input(1), 3, 5) + conv = _create_op( + "DepthwiseConv2dNative", [t, kernel], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs[0] + return wrap(_unflatten_with_inner_dim(conv, c_dim, 4, stack_size), True) + + +@RegisterPFor("DepthwiseConv2dNativeBackpropInput") +def _convert_depthwise_conv2d_native_backprop_input(pfor_input: _PforInput): + stack_size = pfor_input.pfor.loop_len_vector[0] + input_sizes = pfor_input.unstacked_input(0) + data_format = pfor_input.get_attr("data_format") + c_dim = 1 if data_format == b"NCHW" else 3 + input_sizes_mutipliers = [ + constant_op.constant([1] * c_dim, dtype=dtypes.int32), [stack_size] + ] + if c_dim < 3: + input_sizes_mutipliers += [ + constant_op.constant([1] * (3 - c_dim), dtype=dtypes.int32) + ] + input_sizes *= array_ops.concat(input_sizes_mutipliers, axis=0) + kernel = _flatten_with_inner_dim(pfor_input.stacked_input(1), 3, 5) + out_backprop = _flatten_with_inner_dim( + pfor_input.stacked_input(2), c_dim + 1, 5) + result = _create_op( + "DepthwiseConv2dNativeBackpropInput", [input_sizes, kernel, out_backprop], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs[0] + return wrap(_unflatten_with_inner_dim(result, c_dim, 4, stack_size), True) + + +@RegisterPFor("DepthwiseConv2dNativeBackpropFilter") +def _convert_depthwise_conv2d_native_backprop_filter(pfor_input: _PforInput): + stack_size = pfor_input.pfor.loop_len_vector[0] + data_format = pfor_input.get_attr("data_format") + c_dim = 1 if data_format == b"NCHW" else 3 + inputs = _flatten_with_inner_dim(pfor_input.stacked_input(0), c_dim + 1, 5) + filter_sizes = pfor_input.unstacked_input(1) + filter_sizes_multipliers = [ + constant_op.constant([1, 1], dtype=dtypes.int32), [stack_size], + constant_op.constant([1], dtype=dtypes.int32) + ] + filter_sizes *= array_ops.concat(filter_sizes_multipliers, axis=0) + out_backprop = _flatten_with_inner_dim( + pfor_input.stacked_input(2), c_dim + 1, 5) + result = _create_op( + "DepthwiseConv2dNativeBackpropFilter", + [inputs, filter_sizes, out_backprop], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs[0] + return wrap(_unflatten_with_inner_dim(result, 2, 4, stack_size), True) + + +@RegisterPForWithArgs("LogSoftmax", gen_nn_ops.log_softmax) +@RegisterPForWithArgs("Softmax", gen_nn_ops.softmax) +def _convert_softmax(pfor_input: _PforInput, op_type, op_func): + del op_type + return wrap(op_func(pfor_input.stacked_input(0)), True) + + +# array_ops + + +@RegisterPForWithArgs("Identity", array_ops.identity) +@RegisterPForWithArgs("StopGradient", array_ops.stop_gradient) +@RegisterPForWithArgs("MatrixDiag", array_ops.matrix_diag) +@RegisterPForWithArgs("MatrixDiagPart", array_ops.matrix_diag_part) +@RegisterPForWithArgs("_EagerConst", array_ops.identity) +def _convert_identity(pfor_input: _PforInput, op_type, op_func): + del op_type + return wrap(op_func(*[x.t for x in pfor_input.inputs]), True) + + +@RegisterPFor("IdentityN") +def _convert_identity_n(pfor_input: _PforInput): + outputs = array_ops.identity_n([x.t for x in pfor_input.inputs]) + return [ + wrap(out, inp.is_stacked) for out, inp in zip(outputs, pfor_input.inputs) + ] + + +@RegisterPFor("Reshape") +def _convert_reshape(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + shape = pfor_input.unstacked_input(1) + n = math_ops.cast(pfor_input.pfor.loop_len_vector, shape.dtype) + new_shape = array_ops.concat([n, shape], axis=0) + return wrap(array_ops.reshape(t, new_shape), True) + + +@RegisterPFor("Fill") +def _convert_fill(pfor_input: _PforInput): + dims = pfor_input.unstacked_input(0) + value = pfor_input.stacked_input(1) + # Expand the rank of `value` + new_shape = array_ops.concat( + [[-1], array_ops.ones([array_ops.size(dims)], dtype=dtypes.int32)], + axis=0) + value = array_ops.reshape(value, new_shape) + # Compute the new output shape + new_dims = array_ops.concat([pfor_input.pfor.loop_len_vector, dims], axis=0) + # Broadcast + return wrap(array_ops.broadcast_to(value, new_dims), True) + + +@RegisterPFor("BroadcastTo") +def _convert_broadcast_to(pfor_input: _PforInput): + shape = pfor_input.unstacked_input(1) + n = math_ops.cast(pfor_input.pfor.loop_len_vector, shape.dtype) + new_shape = array_ops.concat([n, shape], axis=0) + new_rank = _size(new_shape, dtypes.int32) + + t = pfor_input.stacked_input(0) + t = _expand_dims(t, 1, new_rank - _rank(t)) + return wrap(array_ops.broadcast_to(t, new_shape), True) + + +@RegisterPFor("ExpandDims") +def _convert_expanddims(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + dim = pfor_input.unstacked_input(1) + dim += math_ops.cast(dim >= 0, dim.dtype) + return wrap(array_ops.expand_dims(t, axis=dim), True) + + +@RegisterPForWithArgs("LowerBound", gen_array_ops.lower_bound) +@RegisterPForWithArgs("UpperBound", gen_array_ops.upper_bound) +def _convert_searchsorted(pfor_input: _PforInput, _, op_func): + pfor_input.stack_inputs() + sorted_inputs = _flatten_first_two_dims(pfor_input.stacked_input(0)) + values = _flatten_first_two_dims(pfor_input.stacked_input(1)) + out_type = pfor_input.get_attr("out_type") + output = op_func(sorted_inputs, values, out_type) + return wrap( + _unflatten_first_dim(output, pfor_input.pfor.loop_len_vector), True) + + +@RegisterPFor("MatrixBandPart") +def _convert_matrix_band_part(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + num_lower = pfor_input.unstacked_input(1) + num_upper = pfor_input.unstacked_input(2) + return wrap( + array_ops.matrix_band_part(t, num_lower=num_lower, num_upper=num_upper), + True) + + +@RegisterPFor("MatrixSetDiag") +def _convert_matrix_set_diag(pfor_input: _PforInput): + pfor_input.stack_inputs() + t = pfor_input.stacked_input(0) + diag = pfor_input.stacked_input(1) + return wrap(array_ops.matrix_set_diag(t, diag), True) + + +# Registrations for Matrix{Diag,DiagPart,SetDiag}V2-3. +# The input orders defined in the OpKernel and the actual python API are +# different (for compatibility with V1), so we cannot use _convert_identity. +# v2 is not compatible with v3 and is never exposed on the public API. +@RegisterPFor("MatrixDiagV2") +@RegisterPFor("MatrixDiagV3") +def _convert_matrix_diag_v2(pfor_input: _PforInput): + params = { + "diagonal": pfor_input.stacked_input(0), + "k": pfor_input.unstacked_input(1), + "num_rows": pfor_input.unstacked_input(2), + "num_cols": pfor_input.unstacked_input(3), + "padding_value": pfor_input.unstacked_input(4) + } + if pfor_input.op_type == "MatrixDiagV2": + return wrap(array_ops.matrix_diag_v2(**params), True) + params["align"] = pfor_input.get_attr("align") + return wrap(array_ops.matrix_diag(**params), True) + + +@RegisterPFor("Diag") +def _convert_diag(pfor_input: _PforInput): + diag = pfor_input.stacked_input(0) + if diag.shape.ndims == 2: + # We can use matrix_diag. + return wrap(array_ops.matrix_diag(diag), True) + else: + # It is not clear if we can do better than a while loop here with existing + # kernels. + return _fallback_converter(pfor_input, warn=False) + + +# See notes for MatrixDiagV2 +@RegisterPFor("MatrixDiagPartV2") +@RegisterPFor("MatrixDiagPartV3") +def _convert_matrix_diag_part_v2(pfor_input: _PforInput): + params = { + "input": pfor_input.stacked_input(0), + "k": pfor_input.unstacked_input(1), + "padding_value": pfor_input.unstacked_input(2) + } + if pfor_input.op_type == "MatrixDiagPartV2": + return wrap(array_ops.matrix_diag_part_v2(**params), True) + params["align"] = pfor_input.get_attr("align") + return wrap(array_ops.matrix_diag_part(**params), True) + + +# See notes for MatrixDiagV2 +@RegisterPFor("MatrixSetDiagV2") +@RegisterPFor("MatrixSetDiagV3") +def _convert_matrix_set_diag_v2(pfor_input: _PforInput): + pfor_input.stack_inputs([0, 1]) + params = { + "input": pfor_input.stacked_input(0), + "diagonal": pfor_input.stacked_input(1), + "k": pfor_input.unstacked_input(2) + } + if pfor_input.op_type == "MatrixSetDiagV2": + return wrap(array_ops.matrix_set_diag_v2(**params), True) + params["align"] = pfor_input.get_attr("align") + return wrap(array_ops.matrix_set_diag(**params), True) + + +@RegisterPFor("DiagPart") +def _convert_diag_part(pfor_input: _PforInput): + inp = pfor_input.stacked_input(0) + if inp.shape.ndims == 3: + # We can use matrix_diag_part. + return wrap(array_ops.matrix_diag_part(inp), True) + else: + # It is not clear if we can do better than a while loop here with existing + # kernels. + return _fallback_converter(pfor_input, warn=False) + + +@RegisterPFor("OneHot") +def _convert_one_hot(pfor_input: _PforInput): + indices = pfor_input.stacked_input(0) + depth = pfor_input.unstacked_input(1) + on_value = pfor_input.unstacked_input(2) + off_value = pfor_input.unstacked_input(3) + axis = pfor_input.get_attr("axis") + if axis >= 0: + axis += 1 + return wrap( + array_ops.one_hot(indices, depth, on_value, off_value, axis), True) + + +@RegisterPFor("Slice") +def _convert_slice(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + begin, begin_stacked, _ = pfor_input.input(1) + size = pfor_input.unstacked_input(2) + if not begin_stacked: + begin = array_ops.concat([[0], begin], axis=0) + size = array_ops.concat([[-1], size], axis=0) + return wrap(array_ops.slice(t, begin, size), True) + else: + # Handle negative sizes. + # + # If the `begin` entry corresponding to a negative `size` is loop-variant, + # the output would be ragged. This case is not supported. But `size` having + # some negative values and some loop-variant `begin`s is OK (and it's hard + # to tell the difference statically). + t_shape = array_ops.shape(t) + size = math_ops.cast(size, t_shape.dtype) + begin = math_ops.cast(begin, t_shape.dtype) + n = math_ops.cast(pfor_input.pfor.loop_len_vector, t_shape.dtype) + original_unstacked_shape = _stack(t_shape[1:], n).t + broadcast_size = _stack(size, n).t + result_shape = array_ops.where( + math_ops.less(broadcast_size, 0), + original_unstacked_shape - begin + broadcast_size + 1, broadcast_size) + result_shape = math_ops.cast(math_ops.reduce_max(result_shape, axis=0), + dtypes.int64) + + # Now we enumerate points in the sliced region for each pfor iteration and + # gather them. + cumsize = math_ops.cumprod(result_shape, exclusive=True, reverse=True) + result_num_elements = math_ops.reduce_prod(result_shape) + # Offsets are loop-variant. We first compute loop-invariant gather + # coordinates, then broadcast-add the loop-variant `begin` offsets. + result_base_coordinates = ( + math_ops.range(result_num_elements, dtype=dtypes.int64)[:, None] + // cumsize[None, :]) % result_shape[None, :] + result_coordinates = ( + begin[:, None, :] + + math_ops.cast(result_base_coordinates, begin.dtype)[None, :, :]) + result_flat = array_ops.gather_nd(params=t, indices=result_coordinates, + batch_dims=1) + result_stacked_shape = array_ops.concat( + [math_ops.cast(pfor_input.pfor.loop_len_vector, result_shape.dtype), + result_shape], + axis=0) + return wrap(array_ops.reshape(result_flat, result_stacked_shape), True) + + +@RegisterPFor("Tile") +def _convert_tile(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + multiples = pfor_input.unstacked_input(1) + multiples = array_ops.concat([[1], multiples], 0) + return wrap(array_ops.tile(t, multiples), True) + + +@RegisterPFor("Pack") +def _convert_pack(pfor_input: _PforInput): + pfor_input.stack_inputs() + axis = pfor_input.get_attr("axis") + if axis >= 0: + axis += 1 + return wrap( + array_ops_stack.stack([x.t for x in pfor_input.inputs], axis=axis), True) + + +@RegisterPFor("Unpack") +def _convert_unpack(pfor_input: _PforInput): + value = pfor_input.stacked_input(0) + axis = pfor_input.get_attr("axis") + if axis >= 0: + axis += 1 + num = pfor_input.get_attr("num") + return [wrap(x, True) for x + in array_ops_stack.unstack(value, axis=axis, num=num)] + + +@RegisterPFor("Pad") +def _convert_pad(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + paddings = pfor_input.unstacked_input(1) + paddings = array_ops.concat([[[0, 0]], paddings], 0) + return wrap(array_ops.pad(t, paddings, mode="CONSTANT"), True) + + +@RegisterPFor("PadV2") +def _convert_pad_v2(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + paddings = pfor_input.unstacked_input(1) + paddings = array_ops.concat([[[0, 0]], paddings], 0) + return wrap(array_ops.pad_v2(t, paddings, mode="CONSTANT"), True) + + +@RegisterPFor("Split") +def _convert_split(pfor_input: _PforInput): + split_dim = pfor_input.unstacked_input(0) + t = pfor_input.stacked_input(1) + num_split = pfor_input.get_attr("num_split") + split_dim += math_ops.cast(split_dim >= 0, dtypes.int32) + return [wrap(x, True) for x in array_ops.split(t, num_split, axis=split_dim)] + + +@RegisterPFor("SplitV") +def _convert_split_v(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + splits = pfor_input.unstacked_input(1) + split_dim = pfor_input.unstacked_input(2) + split_dim += math_ops.cast(split_dim >= 0, dtypes.int32) + return [wrap(x, True) for x in array_ops.split(t, splits, axis=split_dim)] + + +@RegisterPFor("Squeeze") +def _convert_squeeze(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + squeeze_dims = pfor_input.get_attr("squeeze_dims") + squeeze_dims = [i + 1 if i >= 0 else i for i in squeeze_dims] + return wrap(array_ops.squeeze(t, axis=squeeze_dims), True) + + +@RegisterPFor("ReverseV2") +def _convert_reverse(pfor_input: _PforInput): + value = pfor_input.stacked_input(0) + axis = pfor_input.unstacked_input(1) + new_axis = array_ops.where_v2(axis >= 0, axis + 1, axis) + return wrap(gen_array_ops.reverse_v2(value, axis=new_axis), True) + + +@RegisterPForWithArgs("Transpose", gen_array_ops.transpose) +@RegisterPForWithArgs("ConjugateTranspose", gen_array_ops.conjugate_transpose) +def _convert_transpose(pfor_input: _PforInput, _, op_func): + t = pfor_input.stacked_input(0) + perm = pfor_input.unstacked_input(1) + new_perm = array_ops.concat([[0], perm + 1], axis=0) + return wrap(op_func(t, new_perm), True) + + +@RegisterPFor("ZerosLike") +def _convert_zeros_like(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + shape = array_ops.shape(t)[1:] + return wrap(array_ops.zeros(shape, dtype=t.dtype), False) + + +@RegisterPFor("OnesLike") +def _convert_ones_like(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + shape = array_ops.shape(t)[1:] + return wrap(array_ops.ones(shape, dtype=t.dtype), False) + + +@RegisterPFor("Gather") +@RegisterPFor("GatherV2") +def _convert_gather(pfor_input: _PforInput): + param, param_stacked, _ = pfor_input.input(0) + indices, indices_stacked, _ = pfor_input.input(1) + batch_dims = pfor_input.get_attr("batch_dims") + + op_type = pfor_input.op_type + if op_type == "Gather": + validate_indices = pfor_input.get_attr("validate_indices") + axis = 0 + else: + validate_indices = None + # Assume we will never have a Tensor with rank > 2**32. + axis = math_ops.cast(pfor_input.unstacked_input(2), dtypes.int32) + axis_value = tensor_util.constant_value(axis) + if axis_value is not None: + axis = axis_value + if indices_stacked and not param_stacked: + if indices is pfor_input.pfor.all_indices and axis == 0: + param_shape0 = tensor_shape.dimension_value(param.shape[0]) + indices_shape0 = tensor_shape.dimension_value(indices.shape[0]) + if param_shape0 is not None and indices_shape0 == param_shape0: + # Note that with loops and conditionals, indices may not be contiguous. + # However they will be sorted and unique. So if the shape matches, then + # it must be picking up all the rows of param. + return wrap(param, True) + + if batch_dims != 0: + # Convert `batch_dims` to its positive equivalent if necessary. + batch_dims_pos = batch_dims + if batch_dims < 0: + batch_dims_pos += array_ops.rank(indices) + # In order to maintain + # indices.shape[:batch_dims] == params.shape[:batch_dims] + # with stacked indices, we move the first dimension of `indices` to the + # `batch_dims + 1`th position. The (non-batch) index dimensions will be + # inserted into the shape of `output` at the `axis` dimension, which is + # then transposed to the front (below). + order = array_ops.concat([ + math_ops.range(1, batch_dims_pos + 1), + [0], + math_ops.range(batch_dims_pos + 1, array_ops.rank(indices))], axis=0) + indices = array_ops.transpose(indices, order) + + output = array_ops.gather( + param, indices, validate_indices=validate_indices, axis=axis, + batch_dims=batch_dims) + if axis != 0: + axis = smart_cond.smart_cond(axis < 0, + lambda: axis + array_ops.rank(param), + lambda: ops.convert_to_tensor(axis)) + order = array_ops.concat( + [[axis], + math_ops.range(axis), + math_ops.range(axis + 1, array_ops.rank(output))], + axis=0) + output = smart_cond.smart_cond( + math_ops.equal(axis, 0), lambda: output, + lambda: array_ops.transpose(output, order)) + return wrap(output, True) + if param_stacked: + pfor_input.stack_inputs(stack_indices=[1]) + indices = pfor_input.stacked_input(1) + if isinstance(axis, tensor_lib.Tensor): + axis = array_ops.where(axis >= 0, axis + 1, axis) + else: + axis = axis + 1 if axis >= 0 else axis + batch_dims = batch_dims + 1 if batch_dims >= 0 else batch_dims + output = array_ops.gather(param, indices, axis=axis, batch_dims=batch_dims) + return wrap(output, True) + + +@RegisterPFor("GatherNd") +def _convert_gather_nd(pfor_input: _PforInput): + # TODO(jmenick): Add support for unstacked params. + pfor_input.stack_inputs(stack_indices=[1]) + params = pfor_input.stacked_input(0) + indices = pfor_input.stacked_input(1) + stacked_result = array_ops.gather_nd(params, indices, batch_dims=1) + return wrap(stacked_result, True) + + +@RegisterPFor("ConcatV2") +def _convert_concatv2(pfor_input: _PforInput): + n = pfor_input.num_inputs + pfor_input.stack_inputs(stack_indices=range(n - 1)) + axis = pfor_input.unstacked_input(n - 1) + axis += math_ops.cast(axis >= 0, axis.dtype) + return wrap( + array_ops.concat([x.t for x in pfor_input.inputs[:n - 1]], axis=axis), + True) + + +@RegisterPFor("StridedSlice") +def _convert_strided_slice(pfor_input: _PforInput): + inp = pfor_input.stacked_input(0) + begin = pfor_input.unstacked_input(1) + end = pfor_input.unstacked_input(2) + strides = pfor_input.unstacked_input(3) + begin_mask = pfor_input.get_attr("begin_mask") + end_mask = pfor_input.get_attr("end_mask") + ellipsis_mask = pfor_input.get_attr("ellipsis_mask") + new_axis_mask = pfor_input.get_attr("new_axis_mask") + shrink_axis_mask = pfor_input.get_attr("shrink_axis_mask") + + begin = array_ops.concat([[0], begin], axis=0) + end = array_ops.concat([[0], end], axis=0) + strides = array_ops.concat([[1], strides], axis=0) + begin_mask = begin_mask << 1 | 1 + end_mask = end_mask << 1 | 1 + ellipsis_mask <<= 1 + new_axis_mask <<= 1 + shrink_axis_mask <<= 1 + return wrap( + array_ops.strided_slice( + inp, + begin, + end, + strides, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask), True) + + +@RegisterPFor("StridedSliceGrad") +def _convert_strided_slice_grad(pfor_input: _PforInput): + shape = pfor_input.unstacked_input(0) + begin = pfor_input.unstacked_input(1) + end = pfor_input.unstacked_input(2) + strides = pfor_input.unstacked_input(3) + dy = pfor_input.stacked_input(4) + begin_mask = pfor_input.get_attr("begin_mask") + end_mask = pfor_input.get_attr("end_mask") + ellipsis_mask = pfor_input.get_attr("ellipsis_mask") + new_axis_mask = pfor_input.get_attr("new_axis_mask") + shrink_axis_mask = pfor_input.get_attr("shrink_axis_mask") + + shape = array_ops.concat( + [math_ops.cast(pfor_input.pfor.loop_len_vector, shape.dtype), shape], + axis=0) + begin = array_ops.concat([[0], begin], axis=0) + end = array_ops.concat([[0], end], axis=0) + strides = array_ops.concat([[1], strides], axis=0) + begin_mask = begin_mask << 1 | 1 + end_mask = end_mask << 1 | 1 + ellipsis_mask <<= 1 + new_axis_mask <<= 1 + shrink_axis_mask <<= 1 + return wrap( + array_ops.strided_slice_grad( + shape, + begin, + end, + strides, + dy, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask), True) + + +@RegisterPFor("CheckNumerics") +def _convert_check_numerics(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + message = pfor_input.get_attr("message") + return wrap(gen_array_ops.check_numerics(t, message), True) + + +@RegisterPFor("EnsureShape") +def _convert_ensure_shape(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + shape = tensor_shape.TensorShape(pfor_input.get_attr("shape")) + return wrap(gen_array_ops.ensure_shape(t, [None] + shape), True) + + +# manip_ops + + +@RegisterPFor("Roll") +def _convert_roll(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + shift, shift_stacked, _ = pfor_input.input(1) + axis = pfor_input.unstacked_input(2) + if not shift_stacked: + return wrap(manip_ops.roll(t, shift, axis + 1), True) + else: + # `axis` and `shift` may both be vectors, with repeated axes summing the + # corresponding `shift`s. We scatter shifts into a dense array of shape + # [loop_len, num_unstacked_axes] indicating the offset for each axis. + num_unstacked_axes = math_ops.cast(array_ops.rank(t), dtypes.int64) - 1 + axis = math_ops.cast(array_ops.reshape(axis, [-1]), dtypes.int64) + loop_len = math_ops.cast(pfor_input.pfor.loop_len_vector[0], dtypes.int64) + shift = math_ops.cast(array_ops.reshape(shift, [loop_len, -1]), + dtypes.int64) + axis_segment_ids = ( + math_ops.range(loop_len, dtype=dtypes.int64)[:, None] + * num_unstacked_axes + axis[None, :]) + axis_offsets = array_ops.reshape( + math_ops.unsorted_segment_sum( + data=shift, segment_ids=axis_segment_ids, + num_segments=loop_len * num_unstacked_axes), + [loop_len, num_unstacked_axes]) + + # Determine the coordinates in the input array of each result and gather + # them. + unstacked_shape = array_ops.shape(t, out_type=dtypes.int64)[1:] + cumsize = math_ops.cumprod(unstacked_shape, exclusive=True, reverse=True) + num_unstacked_elements = math_ops.reduce_prod(unstacked_shape) + result_coordinates = ( + (math_ops.range(num_unstacked_elements, + dtype=dtypes.int64)[None, :, None] + // cumsize[None, None, :] - axis_offsets[:, None, :]) + % unstacked_shape[None, None, :]) + result_flat = array_ops.gather_nd(params=t, indices=result_coordinates, + batch_dims=1) + return wrap(array_ops.reshape(result_flat, array_ops.shape(t)), + True) + +# math_ops + + +@RegisterPFor("MatMul") +def _convert_matmul(pfor_input: _PforInput): + # TODO(agarwal): Check if tiling is faster than two transposes. + a, a_stacked, _ = pfor_input.input(0) + b, b_stacked, _ = pfor_input.input(1) + tr_a = pfor_input.get_attr("transpose_a") + tr_b = pfor_input.get_attr("transpose_b") + if a_stacked and b_stacked: + output = wrap(math_ops.matmul(a, b, adjoint_a=tr_a, adjoint_b=tr_b), True) + return output + elif a_stacked: + if tr_a: + a = array_ops.transpose(a, [0, 2, 1]) + if a.shape.is_fully_defined(): + x, y, z = a.shape + else: + x, y, z = [ + array_ops.reshape(i, []) + for i in array_ops.split(array_ops.shape(a), 3) + ] + a = array_ops.reshape(a, [x * y, z]) + prod = math_ops.matmul(a, b, transpose_b=tr_b) + return wrap(array_ops.reshape(prod, [x, y, -1]), True) + else: + assert b_stacked + if tr_b: + perm = [2, 0, 1] + b = array_ops.transpose(b, perm) + else: + # As an optimization, if one of the first two dimensions is 1, then we can + # reshape instead of transpose. + # TODO(agarwal): This check can be done inside Transpose kernel. + b_shape = array_ops.shape(b) + min_dim = math_ops.minimum(b_shape[0], b_shape[1]) + perm = array_ops.where( + math_ops.equal(min_dim, 1), [0, 1, 2], [1, 0, 2]) + new_shape = array_ops_stack.stack([b_shape[1], b_shape[0], b_shape[2]]) + b = array_ops.transpose(b, perm) + b = array_ops.reshape(b, new_shape) + + if b.shape.is_fully_defined(): + x, y, z = b.shape + else: + x, y, z = [ + array_ops.reshape(i, []) + for i in array_ops.split(array_ops.shape(b), 3) + ] + b = array_ops.reshape(b, [x, y * z]) + prod = math_ops.matmul(a, b, transpose_a=tr_a) + prod = array_ops.reshape(prod, [-1, y, z]) + prod = array_ops.transpose(prod, [1, 0, 2]) + return wrap(prod, True) + + +# TODO(rmlarsen): Use the converter of BatchMatMulV2 once compatibility window +# is met. +@RegisterPFor("BatchMatMul") +def _convert_batch_mat_mul(pfor_input: _PforInput): + # TODO(agarwal): There may be a more efficient way to do this instead of + # stacking the inputs. + pfor_input.stack_inputs() + x = pfor_input.stacked_input(0) + y = pfor_input.stacked_input(1) + adj_x = pfor_input.get_attr("adj_x") + adj_y = pfor_input.get_attr("adj_y") + + x = _flatten_first_two_dims(x) + y = _flatten_first_two_dims(y) + output = math_ops.matmul(x, y, adjoint_a=adj_x, adjoint_b=adj_y) + output = _unflatten_first_dim(output, pfor_input.pfor.loop_len_vector) + return wrap(output, True) + + +@RegisterPFor("BatchMatMulV2") +def _convert_batch_mat_mul_v2(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + x = pfor_input.input(0)[0] + y = pfor_input.input(1)[0] + adj_x = pfor_input.get_attr("adj_x") + adj_y = pfor_input.get_attr("adj_y") + + output = math_ops.matmul(x, y, adjoint_a=adj_x, adjoint_b=adj_y) + return wrap(output, True) + + +@RegisterPForWithArgs("Sum", math_ops.reduce_sum) +@RegisterPForWithArgs("Prod", math_ops.reduce_prod) +@RegisterPForWithArgs("Max", math_ops.reduce_max) +@RegisterPForWithArgs("Min", math_ops.reduce_min) +@RegisterPForWithArgs("Mean", math_ops.reduce_mean) +@RegisterPForWithArgs("All", math_ops.reduce_all) +@RegisterPForWithArgs("Any", math_ops.reduce_any) +def _convert_reduction(pfor_input: _PforInput, _, op_func): + t = pfor_input.stacked_input(0) + indices = pfor_input.unstacked_input(1) + # Shift positive indices by one to account for the extra dimension. + indices += math_ops.cast(indices >= 0, indices.dtype) + keep_dims = pfor_input.get_attr("keep_dims") + return wrap(op_func(t, indices, keepdims=keep_dims), True) + + +@RegisterPForWithArgs("ArgMax", math_ops.argmax) +@RegisterPForWithArgs("ArgMin", math_ops.argmin) +def _convert_argmax_argmin(pfor_input: _PforInput, _, op_func): + t = pfor_input.stacked_input(0) + dimension = pfor_input.unstacked_input(1) + dimension += math_ops.cast(dimension >= 0, dimension.dtype) + output_type = pfor_input.get_attr("output_type") + return wrap(op_func(t, axis=dimension, output_type=output_type), True) + + +@RegisterPFor("Bucketize") +def _convert_bucketize(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + boundaries = pfor_input.get_attr("boundaries") + return wrap(math_ops.bucketize(t, boundaries), True) + + +@RegisterPFor("ClipByValue") +def _convert_clip_by_value(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + clip_value_min = pfor_input.unstacked_input(1) + clip_value_max = pfor_input.unstacked_input(2) + return wrap(gen_math_ops._clip_by_value(t, clip_value_min, clip_value_max), + True) + + +@RegisterPForWithArgs("Cumsum", math_ops.cumsum) +@RegisterPForWithArgs("Cumprod", math_ops.cumprod) +def _convert_cumfoo(pfor_input: _PforInput, _, op_func): + t = pfor_input.stacked_input(0) + axis = pfor_input.unstacked_input(1) + # Shift positive indices by one to account for the extra dimension. + axis += math_ops.cast(axis >= 0, axis.dtype) + exclusive = pfor_input.get_attr("exclusive") + reverse = pfor_input.get_attr("reverse") + return wrap(op_func(t, axis, exclusive=exclusive, reverse=reverse), True) + + +@RegisterPFor("BiasAdd") +def _convert_biasadd(pfor_input: _PforInput): + t, t_stacked, _ = pfor_input.input(0) + bias, bias_stacked, _ = pfor_input.input(1) + data_format = pfor_input.get_attr("data_format").decode() + if bias_stacked: + # BiasAdd only supports 1-D biases, so cast bias to match value and use Add. + pfor_input.expanddim_inputs_for_broadcast() + t, _, _ = pfor_input.input(0) + bias = math_ops.cast(pfor_input.stacked_input(1), t.dtype) + if compat.as_bytes(data_format) == b"NCHW": + b_shape = array_ops.shape(bias) + new_b_shape = array_ops.concat( + [b_shape[:-3], b_shape[-1:], b_shape[-3:-1]], axis=0) + bias = array_ops.reshape(bias, new_b_shape) + return wrap(math_ops.add(t, bias), True) + else: + assert t_stacked, "At least one input to BiasAdd should be loop variant." + if compat.as_bytes(data_format) == b"NCHW": + shape = array_ops.shape(t) + flattened_shape = array_ops.concat([[-1], shape[2:]], axis=0) + t = array_ops.reshape(t, flattened_shape) + t = nn_ops.bias_add(t, bias, data_format="NCHW") + t = array_ops.reshape(t, shape) + return wrap(t, True) + return wrap(nn_ops.bias_add(t, bias, data_format=data_format), True) + + +@RegisterPForWithArgs("UnsortedSegmentSum", math_ops.unsorted_segment_sum) +@RegisterPForWithArgs("UnsortedSegmentMax", math_ops.unsorted_segment_max) +@RegisterPForWithArgs("UnsortedSegmentMin", math_ops.unsorted_segment_min) +@RegisterPForWithArgs("UnsortedSegmentProd", math_ops.unsorted_segment_prod) +def _convert_unsortedsegmentsum(pfor_input: _PforInput, _, op_func): + pfor_input.stack_inputs([0, 1]) + data = pfor_input.stacked_input(0) + segment_ids = pfor_input.stacked_input(1) + # TODO(agarwal): handle stacked? + num_segments = pfor_input.unstacked_input(2) + if segment_ids.dtype != num_segments.dtype: + segment_ids = math_ops.cast(segment_ids, dtypes.int64) + num_segments = math_ops.cast(num_segments, dtypes.int64) + dtype = segment_ids.dtype + segment_shape = array_ops.shape(segment_ids, out_type=dtype) + n = segment_shape[0] + ones = array_ops.ones_like(segment_shape, dtype=dtype)[1:] + segment_offset = num_segments * math_ops.range(n, dtype=dtype) + segment_offset = array_ops.reshape(segment_offset, + array_ops.concat([[n], ones], axis=0)) + segment_ids = array_ops.where( + segment_ids >= 0, segment_ids + segment_offset, segment_ids + ) + num_segments = math_ops.cast(num_segments, dtypes.int64) * math_ops.cast( + n, dtypes.int64) + output = op_func(data, segment_ids, num_segments) + new_output_shape = array_ops.concat( + [[n, -1], array_ops.shape(output)[1:]], axis=0) + output = array_ops.reshape(output, new_output_shape) + return wrap(output, True) + + +def _flatten_array_with_offset(ids, offset_delta, num_rows): + """Flattens a rank 2 tensor, adding an offset to each row.""" + # Note that if `ids` is rank 1, it is broadcast to rank 2. + offset_delta = math_ops.cast(offset_delta, ids.dtype) + n = math_ops.cast(num_rows, dtype=ids.dtype) + offsets = math_ops.range( + start=0, limit=n * offset_delta, delta=offset_delta, dtype=ids.dtype) + offsets = array_ops.expand_dims(offsets, -1) + ids += offsets + return array_ops.reshape(ids, [-1]) + + +@RegisterPForWithArgs("SparseSegmentSum", math_ops.sparse_segment_sum_v2) +@RegisterPForWithArgs("SparseSegmentMean", math_ops.sparse_segment_mean_v2) +@RegisterPForWithArgs("SparseSegmentSqrtN", math_ops.sparse_segment_sqrt_n_v2) +@RegisterPForWithArgs("SparseSegmentSumWithNumSegments", + math_ops.sparse_segment_sum_v2) +@RegisterPForWithArgs("SparseSegmentMeanWithNumSegments", + math_ops.sparse_segment_mean_v2) +@RegisterPForWithArgs("SparseSegmentSqrtNWithNumSegments", + math_ops.sparse_segment_sqrt_n_v2) +def _convert_sparse_segment(pfor_input: _PforInput, _, op_func): + _, segment_ids_stacked, _ = pfor_input.input(2) + if segment_ids_stacked: + pfor_input.stack_inputs([1]) + data, data_stacked, _ = pfor_input.input(0) + indices, _, _ = pfor_input.input(1) + num_inputs = len(pfor_input.inputs) + assert num_inputs in (3, 4) + if num_inputs == 3: + # `segment_ids` needs to be unstacked since otherwise output sizes could + # differ across pfor iterations. + segment_ids = pfor_input.unstacked_input(2) + num_segments = nn_ops.relu(math_ops.reduce_max(segment_ids) + 1) + else: + segment_ids, _, _ = pfor_input.input(2) + num_segments = pfor_input.unstacked_input(3) + + n = pfor_input.pfor.loop_len_vector[0] + if data_stacked: + indices = _flatten_array_with_offset(indices, array_ops.shape(data)[1], n) + data = _flatten_first_two_dims(data) + else: + indices = array_ops.reshape(indices, [-1]) + segment_ids = _flatten_array_with_offset(segment_ids, num_segments, n) + + if num_inputs == 3: + num_segments = None + else: + num_segments *= n + output = op_func(data, indices, segment_ids, num_segments=num_segments) + output = _unflatten_first_dim(output, [n]) + return wrap(output, True) + + +@RegisterPForWithArgs("SparseSegmentSumGrad", math_ops.sparse_segment_sum_grad) +@RegisterPForWithArgs("SparseSegmentMeanGrad", + math_ops.sparse_segment_mean_grad) +@RegisterPForWithArgs("SparseSegmentSqrtNGrad", + math_ops.sparse_segment_sqrt_n_grad) +def _convert_sparse_segment_grad(pfor_input: _PforInput, _, op_func): + grad = pfor_input.stacked_input(0) + indices = pfor_input.unstacked_input(1) + segment_ids = pfor_input.unstacked_input(2) + dim0 = pfor_input.unstacked_input(3) + + n = pfor_input.pfor.loop_len_vector[0] + indices = _flatten_array_with_offset(indices, dim0, n) + num_segments = nn_ops.relu(math_ops.reduce_max(segment_ids) + 1) + segment_ids = _flatten_array_with_offset(segment_ids, num_segments, n) + grad = _flatten_first_two_dims(grad) + dim0 *= n + output = op_func(grad, indices, segment_ids, dim0) + output = _unflatten_first_dim(output, [n]) + return wrap(output, True) + + +@RegisterPFor("Cast") +def _convert_cast(pfor_input: _PforInput): + inp = pfor_input.stacked_input(0) + dtype = pfor_input.get_attr("DstT") + return wrap(math_ops.cast(inp, dtype), True) + + +@RegisterPFor("Abs") +@RegisterPFor("Acos") +@RegisterPFor("Acosh") +@RegisterPFor("Add") +@RegisterPFor("AddV2") +@RegisterPFor("Angle") +@RegisterPFor("Asin") +@RegisterPFor("Asinh") +@RegisterPFor("Atan") +@RegisterPFor("Atan2") +@RegisterPFor("Atanh") +@RegisterPFor("BesselI0") +@RegisterPFor("BesselI1") +@RegisterPFor("BesselI0e") +@RegisterPFor("BesselI1e") +@RegisterPFor("BesselK0") +@RegisterPFor("BesselK1") +@RegisterPFor("BesselK0e") +@RegisterPFor("BesselK1e") +@RegisterPFor("BesselJ0") +@RegisterPFor("BesselJ1") +@RegisterPFor("BesselY0") +@RegisterPFor("BesselY1") +@RegisterPFor("BitwiseAnd") +@RegisterPFor("BitwiseOr") +@RegisterPFor("BitwiseXor") +@RegisterPFor("Ceil") +@RegisterPFor("Complex") +@RegisterPFor("ComplexAbs") +@RegisterPFor("Conj") +@RegisterPFor("Cos") +@RegisterPFor("Cosh") +@RegisterPFor("Dawsn") +@RegisterPFor("Digamma") +@RegisterPFor("Div") +@RegisterPFor("DivNoNan") +@RegisterPFor("Elu") +@RegisterPFor("Erf") +@RegisterPFor("Erfc") +@RegisterPFor("Erfinv") +@RegisterPFor("Exp") +@RegisterPFor("Expint") +@RegisterPFor("Expm1") +@RegisterPFor("Floor") +@RegisterPFor("FloorDiv") +@RegisterPFor("FloorMod") +@RegisterPFor("FresnelCos") +@RegisterPFor("FresnelSin") +@RegisterPFor("Greater") +@RegisterPFor("GreaterEqual") +@RegisterPFor("Igamma") +@RegisterPFor("IgammaGradA") +@RegisterPFor("Igammac") +@RegisterPFor("Imag") +@RegisterPFor("Inv") +@RegisterPFor("Invert") +@RegisterPFor("IsFinite") +@RegisterPFor("IsInf") +@RegisterPFor("IsNan") +@RegisterPFor("LeftShift") +@RegisterPFor("Less") +@RegisterPFor("LessEqual") +@RegisterPFor("Lgamma") +@RegisterPFor("Log") +@RegisterPFor("Log1p") +@RegisterPFor("LogicalAnd") +@RegisterPFor("LogicalNot") +@RegisterPFor("LogicalOr") +@RegisterPFor("LogicalXor") +@RegisterPFor("Maximum") +@RegisterPFor("Minimum") +@RegisterPFor("Mod") +@RegisterPFor("Mul") +@RegisterPFor("MulNoNan") +@RegisterPFor("Ndtri") +@RegisterPFor("Neg") +@RegisterPFor("Polygamma") +@RegisterPFor("Pow") +@RegisterPFor("Real") +@RegisterPFor("RealDiv") +@RegisterPFor("Reciprocal") +@RegisterPFor("Relu") +@RegisterPFor("Relu6") +@RegisterPFor("RightShift") +@RegisterPFor("Rint") +@RegisterPFor("Round") +@RegisterPFor("Rsqrt") +@RegisterPFor("Selu") +@RegisterPFor("Sigmoid") +@RegisterPFor("Sign") +@RegisterPFor("Sin") +@RegisterPFor("Sinh") +@RegisterPFor("Softplus") +@RegisterPFor("Softsign") +@RegisterPFor("Spence") +@RegisterPFor("Sqrt") +@RegisterPFor("Square") +@RegisterPFor("SquaredDifference") +@RegisterPFor("Sub") +@RegisterPFor("Tan") +@RegisterPFor("Tanh") +@RegisterPFor("TruncateDiv") +@RegisterPFor("TruncateMod") +@RegisterPFor("Xdivy") +@RegisterPFor("Xlogy") +@RegisterPFor("Xlog1py") +@RegisterPFor("Zeta") +def _convert_cwise(pfor_input: _PforInput): + if pfor_input.num_inputs > 1: + pfor_input.expanddim_inputs_for_broadcast() + + out = _create_op( + pfor_input.op_type, [x.t for x in pfor_input.inputs], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + assert len(out) == 1 + out = out[0] + + op_output = wrap(out, True) + return op_output + + +@RegisterPFor("XlaSharding") +def _convert_xla_sharding(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + sharding = pfor_input.get_attr("sharding") + return wrap(xla.sharding(t, sharding=sharding), True) + + +@RegisterPFor("LeakyRelu") +def _convert_leaky_relu(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + alpha = pfor_input.get_attr("alpha") + return wrap(gen_nn_ops.leaky_relu(t, alpha=alpha), True) + + +@RegisterPFor("Equal") +def _convert_equal(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + x = pfor_input.input(0)[0] + y = pfor_input.input(1)[0] + incompatible_shape_error = pfor_input.get_attr("incompatible_shape_error") + return wrap(gen_math_ops.equal( + x, y, incompatible_shape_error=incompatible_shape_error), True) + + +@RegisterPFor("NotEqual") +def _convert_not_equal(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + x = pfor_input.input(0)[0] + y = pfor_input.input(1)[0] + incompatible_shape_error = pfor_input.get_attr("incompatible_shape_error") + return wrap(gen_math_ops.not_equal( + x, y, incompatible_shape_error=incompatible_shape_error), True) + + +@RegisterPFor("ApproximateEqual") +def _convert_approximate_equal(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + x = pfor_input.input(0)[0] + y = pfor_input.input(1)[0] + tolerance = pfor_input.get_attr("tolerance") + return wrap(math_ops.approximate_equal(x, y, tolerance=tolerance), True) + + +@RegisterPFor("Shape") +def _convert_shape(pfor_input: _PforInput): + out_type = pfor_input.get_attr("out_type") + return wrap( + array_ops.shape(pfor_input.stacked_input(0), out_type=out_type)[1:], + False) + + +@RegisterPFor("ShapeN") +def _convert_shape_n(pfor_input: _PforInput): + out_type = pfor_input.get_attr("out_type") + shapes = [ + array_ops.shape(x, out_type=out_type)[1:] if stacked else array_ops.shape( + x, out_type=out_type) for x, stacked, _ in pfor_input.inputs + ] + return [wrap(x, False) for x in shapes] + + +@RegisterPFor("Size") +def _convert_size(pfor_input: _PforInput): + out_type = pfor_input.get_attr("out_type") + n = math_ops.cast(pfor_input.pfor.loop_len_vector[0], out_type) + return wrap( + array_ops.size(pfor_input.stacked_input(0), out_type=out_type) // n, + False) + + +@RegisterPFor("Rank") +def _convert_rank(pfor_input: _PforInput): + return wrap(array_ops.rank(pfor_input.stacked_input(0)) - 1, False) + + +@RegisterPFor("AddN") +def _convert_addn(pfor_input: _PforInput): + # AddN does not support broadcasting. + pfor_input.stack_inputs(tile_variants=False) + return _wrap_and_tile_variants( + math_ops.add_n([x.t for x in pfor_input.inputs]), + pfor_input.pfor.loop_len_vector) + + +@RegisterPFor("Cross") +def _convert_cross(pfor_input: _PforInput): + pfor_input.stack_inputs() + a = pfor_input.stacked_input(0) + b = pfor_input.stacked_input(1) + return wrap(math_ops.cross(a, b), True) + + +@RegisterPFor("BiasAddGrad") +def _convert_biasaddgrad(pfor_input: _PforInput): + grad = pfor_input.stacked_input(0) + fmt = pfor_input.get_attr("data_format") + if fmt == b"NCHW": + output = math_ops.reduce_sum(grad, axis=[1, 3, 4], keepdims=False) + else: + grad_shape = array_ops.shape(grad) + last_dim_shape = grad_shape[-1] + first_dim_shape = grad_shape[0] + output = array_ops.reshape(grad, [first_dim_shape, -1, last_dim_shape]) + output = math_ops.reduce_sum(output, axis=[1], keepdims=False) + return wrap(output, True) + + +# Some required ops are not exposed under the tf namespace. Hence relying on +# _create_op to create them. +@RegisterPForWithArgs("EluGrad") +@RegisterPForWithArgs("LeakyReluGrad") +@RegisterPForWithArgs("ReciprocalGrad") +@RegisterPForWithArgs("Relu6Grad") +@RegisterPForWithArgs("ReluGrad") +@RegisterPForWithArgs("RsqrtGrad") +@RegisterPForWithArgs("SeluGrad") +@RegisterPForWithArgs("SigmoidGrad") +@RegisterPForWithArgs("SoftplusGrad") +@RegisterPForWithArgs("SoftsignGrad") +@RegisterPForWithArgs("SqrtGrad") +@RegisterPForWithArgs("TanhGrad") +def _convert_grads(pfor_input: _PforInput, op_type, *args, **kw_args): + del args + del kw_args + # TODO(agarwal): Looks like these ops don't support broadcasting. Hence we + # have to use tiling here. + pfor_input.stack_inputs() + outputs = _create_op( + op_type, [x.t for x in pfor_input.inputs], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + return [wrap(x, True) for x in outputs] + + +@RegisterPFor("Select") +def _convert_select(pfor_input: _PforInput): + pfor_input.stack_inputs() + cond = pfor_input.stacked_input(0) + t = pfor_input.stacked_input(1) + e = pfor_input.stacked_input(2) + cond_rank = array_ops.rank(cond) + cond, t, e = smart_cond.smart_cond( + cond_rank > 1, lambda: _inputs_with_flattening(pfor_input, [0, 1, 2]), + lambda: [cond, t, e]) + outputs = _create_op( + pfor_input.op_type, [cond, t, e], [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + n = pfor_input.pfor.loop_len_vector + out = smart_cond.smart_cond(cond_rank > 1, + lambda: _unflatten_first_dim(outputs[0], n), + lambda: outputs[0]) + return [wrap(out, True) for x in outputs] + + +@RegisterPFor("SelectV2") +def _convert_selectv2(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + cond = pfor_input.input(0)[0] + t = pfor_input.input(1)[0] + e = pfor_input.input(2)[0] + out = array_ops.where_v2(cond, t, e) + return wrap(out, True) + + +# random_ops + + +def _transpose_dim_to_front(x, dim): + rank = array_ops.rank(x) + return array_ops.transpose( + x, + perm=array_ops.concat( + [[dim], math_ops.range(0, dim), + math_ops.range(dim + 1, rank)], + axis=0)) + + +@RegisterPForWithArgs("RandomUniform") +@RegisterPForWithArgs("RandomUniformInt") +@RegisterPForWithArgs("RandomStandardNormal") +@RegisterPForWithArgs("TruncatedNormal") +def _convert_random(pfor_input: _PforInput, op_type, *args, **kw_args): + del args + del kw_args + inputs = [pfor_input.unstacked_input(i) for i in range(pfor_input.num_inputs)] + # inputs[0] is "shape" + n = math_ops.cast(pfor_input.pfor.loop_len_vector, inputs[0].dtype) + inputs[0] = array_ops.concat([n, inputs[0]], axis=0) + # TODO(b/222761732): Turn this warning back on when legacy RNGs are + # deprecated. + # logging.warning( + # "Note that %s inside pfor op may not give same output as " + # "inside a sequential loop.", op_type) + outputs = _create_op( + op_type, + inputs, [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + return [wrap(x, True) for x in outputs] + + +@RegisterPFor("RandomGamma") +@RegisterPFor("RandomPoissonV2") +def _convert_random_with_param(pfor_input: _PforInput): + shape = pfor_input.unstacked_input(0) + # param is lam (Poisson rate) or alpha (Gamma shape). + param, param_stacked, _ = pfor_input.input(1) + # TODO(b/222761732): Turn this warning back on when legacy RNGs are + # deprecated. + # logging.warning( + # "Note that %s inside pfor op may not give same output as " + # "inside a sequential loop.", pfor_input.op_type) + + if param_stacked: + samples = _create_op( + pfor_input.op_type, + inputs=[shape, param], + op_dtypes=[x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs[0] + loop_dim = array_ops.shape(shape)[0] + stacked_samples = _transpose_dim_to_front(samples, loop_dim) + else: + n = math_ops.cast(pfor_input.pfor.loop_len_vector, shape.dtype) + shape = array_ops.concat([n, shape], axis=0) + stacked_samples = _create_op( + pfor_input.op_type, + inputs=[shape, param], + op_dtypes=[x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs[0] + + return wrap(stacked_samples, True) + + +@RegisterPFor("Multinomial") +def _convert_multinomial(pfor_input: _PforInput): + logits, logits_stacked, _ = pfor_input.input(0) + num_samples = pfor_input.unstacked_input(1) + seed = pfor_input.get_attr("seed") + seed2 = pfor_input.get_attr("seed2") + output_dtype = pfor_input.get_attr("output_dtype") + # TODO(b/222761732): Turn this warning back on when legacy RNGs are + # deprecated. + # logging.warning( + # "Note that Multinomial inside pfor op may not give same output as " + # "inside a sequential loop.") + + n = pfor_input.pfor.loop_len_vector[0] + if logits_stacked: + flattened_logits = _flatten_first_two_dims(logits) + samples = gen_random_ops.multinomial( + flattened_logits, + num_samples, + seed=seed, + seed2=seed2, + output_dtype=output_dtype) + stacked_samples = _unflatten_first_dim(samples, [n]) + else: + samples = gen_random_ops.multinomial( + logits, + num_samples * n, + seed=seed, + seed2=seed2, + output_dtype=output_dtype) + stacked_samples = array_ops.transpose( + array_ops.reshape(samples, [-1, n, num_samples]), [1, 0, 2]) + + return wrap(stacked_samples, True) + + +@RegisterPFor("StatelessMultinomial") +@RegisterPFor("StatelessParameterizedTruncatedNormal") +@RegisterPFor("StatelessRandomBinomial") +@RegisterPFor("StatelessRandomGammaV2") +@RegisterPFor("StatelessRandomNormal") +@RegisterPFor("StatelessRandomPoisson") +@RegisterPFor("StatelessRandomUniform") +@RegisterPFor("StatelessRandomUniformInt") +@RegisterPFor("StatelessRandomUniformFullInt") +@RegisterPFor("StatelessTruncatedNormal") +def _convert_stateless_multinomial(pfor_input: _PforInput): + # Unlike stateful random ops, for stateless ones we want better + # reproducibility based on seed. Hence we don't want to use a similar strategy + # as used for stateful ones where we generate a possibly different set of + # random numbers under vectorization. + # Unfortunately, the kernels currently are not necessarily setup to do this + # efficiently and hence we fallback to a sequential loop for vectorization. + return _fallback_converter(pfor_input, warn=False) + + +# linalg_ops + + +@RegisterPForWithArgs("XlaEinsum") +@RegisterPForWithArgs("Einsum") +def _convert_einsum(pfor_input: _PforInput, op_type): + # Einsum may have either 1 or 2 inputs. + inputs, input_stacked, _ = zip(*[ + pfor_input.input(i) + for i in range(pfor_input.num_inputs)]) + + # Parse the einsum equation. + equation = pfor_input.get_attr("equation").decode("utf-8") + input_expr, output_expr = equation.split("->") + input_exprs = input_expr.split(",") + + # Pick a placeholder symbol to use for the new axis. + chosen_symbol = None + for s in string.ascii_letters: + if s in equation: + continue + else: + chosen_symbol = s + break + + if chosen_symbol is None: + raise ValueError("Could not figure out what symbol to use for new axis.") + + assert any(input_stacked) + for i in range(len(inputs)): + if input_stacked[i]: + input_exprs[i] = "{}{}".format(chosen_symbol, input_exprs[i]) + output_expr = "{}{}".format(chosen_symbol, output_expr) + + new_equation = "{}->{}".format(",".join(input_exprs), output_expr) + + if op_type == "XlaEinsum": + if len(inputs) == 1: + result = xla.einsum(equation=new_equation, a=inputs[0]) + else: + result = xla.einsum(equation=new_equation, a=inputs[0], b=inputs[1]) + else: + assert op_type == "Einsum" + result = special_math_ops.einsum(new_equation, *inputs) + + return wrap(result, True) + + +@RegisterPFor("Cholesky") +def _convert_cholesky(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + return wrap(linalg_ops.cholesky(t), True) + + +@RegisterPFor("LogMatrixDeterminant") +def _convert_log_matrix_determinant(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + return [wrap(x, True) for x in linalg_ops.log_matrix_determinant(t)] + + +@RegisterPFor("MatrixInverse") +def _convert_matrix_inverse(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + adjoint = pfor_input.get_attr("adjoint") + return wrap(gen_linalg_ops.matrix_inverse(t, adjoint=adjoint), True) + + +@RegisterPFor("MatrixSolve") +def _convert_matrix_solve(pfor_input: _PforInput): + pfor_input.stack_inputs() + matrix = pfor_input.stacked_input(0) + rhs = pfor_input.stacked_input(1) + adjoint = pfor_input.get_attr("adjoint") + output = gen_linalg_ops.matrix_solve( + matrix, rhs, adjoint=adjoint) + return wrap(output, True) + + +@RegisterPFor("MatrixTriangularSolve") +def _convert_matrix_triangular_solve(pfor_input: _PforInput): + pfor_input.expanddim_inputs_for_broadcast() + matrix = pfor_input.input(0)[0] + rhs = pfor_input.input(1)[0] + lower = pfor_input.get_attr("lower") + adjoint = pfor_input.get_attr("adjoint") + output = linalg_ops.matrix_triangular_solve( + matrix, rhs, lower=lower, adjoint=adjoint) + return wrap(output, True) + + +@RegisterPFor("SelfAdjointEigV2") +def _convert_self_adjoint_eig(pfor_input: _PforInput): + t = pfor_input.stacked_input(0) + compute_v = pfor_input.get_attr("compute_v") + e, v = gen_linalg_ops.self_adjoint_eig_v2(t, compute_v=compute_v) + # If compute_v is False, v will have shape [0]. + return wrap(e, True), wrap(v, compute_v) + + +# logging_ops + + +@RegisterPFor("Assert") +def _convert_assert(pfor_input: _PforInput): + cond, cond_stacked, _ = pfor_input.input(0) + if cond_stacked: + cond = math_ops.reduce_all(cond) + + data_list = [x.t for x in pfor_input.inputs][1:] + return _create_op( + "Assert", [cond] + data_list, [], attrs=pfor_input.op.node_def.attr) + + +@RegisterPFor("Print") +def _convert_print(pfor_input: _PforInput): + # Note that we don't stack all the inputs. Hence unstacked values are printed + # once here vs multiple times in a while_loop. + pfor_input.stack_inputs([0]) + outputs = _create_op( + "Print", [x.t for x in pfor_input.inputs], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr).outputs + return [wrap(x, True) for x in outputs] + + +@RegisterPFor("PrintV2") +def _convert_print_v2(pfor_input: _PforInput): + # Print the full input Tensor(s), including the batch dimension if stacked. + return _create_op( + "PrintV2", [x.t for x in pfor_input.inputs], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr) + + +@RegisterPFor("StringFormat") +def _convert_string_format(pfor_input: _PforInput): + # Format using the full input Tensor(s), including the batch dimension if + # stacked. + op = _create_op( + "StringFormat", [x.t for x in pfor_input.inputs], + [x.dtype for x in pfor_input.outputs], + attrs=pfor_input.op.node_def.attr) + return [wrap(output, False) for output in op.outputs] + + +# data_flow_ops + +# TensorArray conversion is tricky since we don't support arrays of +# TensorArrays. For converting them, we consider two distinct cases: +# +# 1. The array is constructed outside the pfor call, and read/written inside the +# loop. +# This is an easier case since we don't need to make an array of TensorArrays. +# A correctness requirement is that these parallel iterations shouldn't attempt +# to write to the same location. Hence at conversion time we disallow indices to +# be loop-invariant as that would guarantee a collision. Even if the indices are +# not loop-invariant, they could conflict and that shall trigger runtime errors. +# +# 2. The array is constructed and used entirely inside each pfor iteration. +# For simplicity, here we require that the indices used for write/scatter are +# "unstacked". Otherwise it becomes hard to merge the TensorArrays created in +# different pfor iterations. We consider two sub_cases: +# +# 2a Elements written to the array are "stacked" +# To simulate multiple TensorArrays, we may increase the dimension of each +# element of the array. i.e. the i_th row of the j_th entry of the converted +# TensorArray corresponds to the j_th entry of the TensorArray in the i_th +# pfor iteration. +# +# 2b Elements written to the array are "unstacked" +# In this case we don't increase the dimensions to avoid redundant tiling. Each +# iteration is trying to write the same value. So we convert that to a single +# write. +# +# Here are some tricks used to implement the above: +# - TensorArrayV3 constructor encodes the element shape as an attr. Instead of +# trying to trace whether future writes are stacked or unstacked in order to set +# this attr, we set it to correspond to unknown shape. +# - We use the "flow" output of the different ops to track whether the array +# elements are stacked or unstacked. If a stacked write/scatter is done, we make +# the flow stacked as well. +# - We use some heuristic traversal of the graph to track whether the +# TensorArray handle was created inside or outside the pfor loop. + + +@RegisterPFor("TensorArrayV3") +def _convert_tensor_array_v3(pfor_input: _PforInput): + size = pfor_input.unstacked_input(0) + dtype = pfor_input.get_attr("dtype") + dynamic_size = pfor_input.get_attr("dynamic_size") + clear_after_read = pfor_input.get_attr("clear_after_read") + identical_element_shapes = pfor_input.get_attr("identical_element_shapes") + tensor_array_name = pfor_input.get_attr("tensor_array_name") + handle, flow = data_flow_ops.tensor_array_v3( + size, + dtype=dtype, + # We don't set element shape since we don't know if writes are stacked or + # not yet. + element_shape=None, + dynamic_size=dynamic_size, + clear_after_read=clear_after_read, + identical_element_shapes=identical_element_shapes, + tensor_array_name=tensor_array_name) + # Note we keep flow unstacked for now since we don't know if writes will be + # stacked or not. + return wrap(handle, False), wrap(flow, False) + + +@RegisterPFor("TensorArraySizeV3") +def _convert_tensor_array_size_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + flow, flow_stacked, _ = pfor_input.input(1) + if flow_stacked: + flow = _unstack_flow(flow) + size = data_flow_ops.tensor_array_size_v3(handle, flow) + return wrap(size, False) + + +def _handle_inside_pfor(pfor_input: _PforInput, handle): + """Returns True if handle was created inside the pfor loop.""" + # We use some heuristic to find the original TensorArray creation op. + # The logic should handle the common cases (except cond based subgraphs). + # In theory the user could perform different operations on the handle (like + # Reshape, stack multiple handles, etc) which could break this logic. + # TODO(agarwal): handle Switch/Merge. + while handle.op.type in ("Enter", "Identity"): + handle = handle.op.inputs[0] + if handle.op.type not in [ + "TensorArrayV3", "TensorArrayGradV3", "TensorArrayGradWithShape" + ]: + raise ValueError(f"Unable to find source for handle {handle}.") + else: + return pfor_input.pfor.op_is_inside_loop(handle.op) + + +def _unstack_flow(value): + # TODO(agarwal): consider looking if this is a Tile op then get its input. + # This may avoid running the Tile operations. + return array_ops.gather(value, 0) + + +@RegisterPFor("TensorArrayReadV3") +def _convert_tensor_array_read_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + index, index_stacked, _ = pfor_input.input(1) + dtype = pfor_input.get_attr("dtype") + flow, flow_stacked, _ = pfor_input.input(2) + if flow_stacked: + flow = _unstack_flow(flow) + + is_inside_pfor = _handle_inside_pfor(pfor_input, pfor_input.op.inputs[0]) + if is_inside_pfor: + # Note that if we are inside a control flow construct inside the pfor, and + # only some of the iterations are doing the read (i.e. + # `all_indices_partitioned` is True), then the read operation should only + # return values for the currently active pfor iterations (`all_indices` + # below). Hence, whenever the returned value is stacked (i.e. `flow` is + # stacked), we may need to do an extra gather after reading the values. Also + # note that if `is_inside` is false, then values in the tensor array are + # unstacked. So the check is only needed in this branch. + all_indices = pfor_input.pfor.all_indices + all_indices_partitioned = pfor_input.pfor.all_indices_partitioned + # Note: flow_stacked indicates if values in the TensorArray are stacked or + # not. + if index_stacked: + if flow_stacked: + raise ValueError( + "It looks like TensorArrayReadV3 was called on a TensorArray whose" + " values are not loop-invariant, and the read indices were also" + " not loop invariant. This is currently unsupported.") + value = data_flow_ops.tensor_array_gather_v3( + handle, index, flow, dtype=dtype) + return wrap(value, True) + value = data_flow_ops.tensor_array_read_v3(handle, index, flow, dtype=dtype) + if flow_stacked and all_indices_partitioned: + value = array_ops.gather(value, all_indices) + return wrap(value, flow_stacked) + # Values in the TensorArray should be unstacked (since different iterations + # couldn't write to the same location). So whether output is stacked or not + # depends on index_stacked. + if index_stacked: + value = data_flow_ops.tensor_array_gather_v3( + handle, index, flow, dtype=dtype) + else: + value = data_flow_ops.tensor_array_read_v3(handle, index, flow, dtype=dtype) + return wrap(value, index_stacked) + + +@RegisterPFor("TensorArrayWriteV3") +def _convert_tensor_array_write_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + index, index_stacked, _ = pfor_input.input(1) + value, value_stacked, _ = pfor_input.input(2) + flow, flow_stacked, _ = pfor_input.input(3) + if value_stacked and pfor_input.pfor.all_indices_partitioned: + # Looks like we are in a control flow in a pfor where not all iterations are + # active now. We don't allow that since that could lead to different indices + # having different shapes which will be hard to merge later. + raise ValueError("Writing non loop invariant values to TensorArray from " + "inside a while_loop/cond not supported.") + if flow_stacked: + flow = _unstack_flow(flow) + is_inside = _handle_inside_pfor(pfor_input, pfor_input.op.inputs[0]) + if is_inside: + if index_stacked: + raise ValueError(f"Need indices for {handle} to be loop invariant.") + if not flow_stacked and not value_stacked: + flow_out = data_flow_ops.tensor_array_write_v3(handle, index, value, flow) + return wrap(flow_out, False) + else: + if not value_stacked: + value = _stack(value, pfor_input.pfor.loop_len_vector).t + # TODO(agarwal): Note that if flow is unstacked and value is stacked, then + # this may or may not be a safe situation. flow is unstacked both for a + # freshly created TensorArray, as well as after unstacked values are + # written to it. If it is the latter, then we cannot write a stacked value + # now since that may cause runtime errors due to different shapes in the + # array. At the moment we are not able to handle this gracefully and + # distinguish between the two cases. That would require some heuristic + # traversal of the graph to figure out whether all the writes are + # unstacked or not. + flow_out = data_flow_ops.tensor_array_write_v3(handle, index, value, flow) + return _stack(flow_out, pfor_input.pfor.loop_len_vector) + else: + if not index_stacked: + raise ValueError(f"Need indices for {handle} to be not loop invariant.") + # Note that even when index_stacked is true, actual values in index may + # still not be unique. However that will cause runtime error when executing + # the scatter operation below. + if not value_stacked: + value = _stack(value, pfor_input.pfor.loop_len_vector).t + flow_out = data_flow_ops.tensor_array_scatter_v3(handle, index, value, flow) + return _stack(flow_out, pfor_input.pfor.loop_len_vector) + + +def _transpose_first_two_dims(value): + # TODO(agarwal): optimize if one of the dims == 1. + value_shape = array_ops.shape(value) + v0 = value_shape[0] + v1 = value_shape[1] + value = array_ops.reshape(value, [v0, v1, -1]) + value = array_ops.transpose(value, [1, 0, 2]) + new_shape = array_ops.concat([[v1, v0], value_shape[2:]], axis=0) + return array_ops.reshape(value, new_shape) + + +@RegisterPFor("TensorArrayGatherV3") +def _convert_tensor_array_gather_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + indices, indices_stacked, _ = pfor_input.input(1) + indices = array_ops.reshape(indices, [-1]) + flow, flow_stacked, _ = pfor_input.input(2) + if flow_stacked: + flow = _unstack_flow(flow) + dtype = pfor_input.get_attr("dtype") + # TODO(agarwal): support element_shape attr? + + n = pfor_input.pfor.loop_len_vector + value = data_flow_ops.tensor_array_gather_v3( + handle, indices, flow, dtype=dtype) + is_inside = _handle_inside_pfor(pfor_input, pfor_input.op.inputs[0]) + if is_inside: + # flow_stacked indicates if values in the TensorArray are stacked or not. + if indices_stacked: + if flow_stacked: + raise ValueError( + "It looks like TensorArrayGatherV3 was called on a TensorArray " + "whose values are not loop-invariant, and the indices were also " + "not loop invariant. This is currently unsupported.") + else: + value = _unflatten_first_dim(value, n) + return wrap(value, True) + else: + if flow_stacked: + # Since elements in this array are stacked and `value` was produced by + # gather, its first two dims are "gathered elements" and "stack + # dimension". Our semantics require these two to be flipped. + value = _transpose_first_two_dims(value) + return wrap(value, flow_stacked) + else: + # Values in the TensorArray should be unstacked (since different iterations + # couldn't write to the same location). So whether output is stacked or not + # depends on indices_stacked. + if indices_stacked: + value = _unflatten_first_dim(value, n) + return wrap(value, indices_stacked) + + +@RegisterPFor("TensorArrayScatterV3") +def _convert_tensor_array_scatter_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + indices, indices_stacked, _ = pfor_input.input(1) + indices = array_ops.reshape(indices, [-1]) + value, value_stacked, _ = pfor_input.input(2) + flow, flow_stacked, _ = pfor_input.input(3) + + if flow_stacked: + flow = _unstack_flow(flow) + + is_inside = _handle_inside_pfor(pfor_input, pfor_input.op.inputs[0]) + if is_inside: + if indices_stacked: + raise ValueError(f"Need indices for {handle} to be loop invariant.") + # Note that flow_stacked indicates if existing values in the array are + # stacked or not. + if not flow_stacked and not value_stacked: + flow_out = data_flow_ops.tensor_array_scatter_v3(handle, indices, value, + flow) + return wrap(flow_out, False) + if not value_stacked: + # TODO(agarwal): tile in the second dimension directly instead of + # transposing below. + value = _stack(value, pfor_input.pfor.loop_len_vector).t + + value = _transpose_first_two_dims(value) + # TODO(agarwal): Note that if a previous write was unstacked, flow will be + # unstacked, and a stacked value may be written here which may cause + # runtime error due to different elements having different shape. We do + # not try to prevent that. + flow_out = data_flow_ops.tensor_array_scatter_v3(handle, indices, value, + flow) + return _stack(flow_out, pfor_input.pfor.loop_len_vector) + if not indices_stacked: + raise ValueError(f"Need indices for {handle} to be not loop invariant.") + if not value_stacked: + value = _stack(value, pfor_input.pfor.loop_len_vector).t + value = _flatten_first_two_dims(value) + flow_out = data_flow_ops.tensor_array_scatter_v3(handle, indices, value, flow) + return _stack(flow_out, pfor_input.pfor.loop_len_vector) + + +@RegisterPFor("TensorArrayGradV3") +def _convert_tensor_array_grad_v3(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + flow, flow_stacked, _ = pfor_input.input(1) + if flow_stacked: + flow = _unstack_flow(flow) + source = pfor_input.get_attr("source") + # TODO(agarwal): For now, we assume that gradients are stacked if the + # TensorArrayGradV3 call is being done inside the pfor. Getting that wrong + # will give runtime error due to incorrect shape being written to the + # accumulator. It is difficult to know in advance if gradients written will be + # stacked or not. Note that flow being stacked is not indicative of the + # gradient being stacked or not. Revisit this later. + shape_to_prepend = pfor_input.pfor.loop_len_vector + grad_handle, flow_out = data_flow_ops.tensor_array_grad_with_shape( + handle=handle, + flow_in=flow, + shape_to_prepend=shape_to_prepend, + source=source) + flow_out = _stack(flow_out, pfor_input.pfor.loop_len_vector).t + return [wrap(grad_handle, False), wrap(flow_out, True)] + + +def _stack_tensor_list_shape(shape, first_dim): + shape_value = tensor_util.constant_value(shape) + # Note that negative values in the shape are used to signify unknown shapes + # and are handled in a special way. + if shape_value is not None: + shape_value = np.asarray(shape_value) + if -1 in shape_value: + return constant_op.constant(-1) + elif not shape_value.size: + return first_dim + else: + shape = array_ops.reshape(shape, [-1]) + return tf_cond.cond( + math_ops.reduce_any(shape < 0), + lambda: constant_op.constant(-1), + lambda: array_ops.concat([first_dim, shape], axis=0)) + + +def _tile_variant_with_length(t, length): + """stacks `t` `length` times.""" + if _is_variant_with_internal_stacking(t): + # The content of TensorLists is vectorized, not the variant itself. + return t + original_tensor = t + t.set_shape([]) + t = array_ops.reshape(t, [-1]) + with ops.device("CPU:0"): + result = array_ops.tile(t, length) + # TODO(b/169968286): Should regular shape functions do handle data + # propagation here? + handle_data_util.copy_handle_data(original_tensor, result) + return result + + +def _tile_variant(t, pfor_input: _PforInput): + """stacks `t` according to its loop context.""" + return _tile_variant_with_length(t, pfor_input.pfor.loop_len_vector) + + +def _untile_variant(t): + if _is_variant_with_internal_stacking(t): + # The content of TensorLists is vectorized, not the variant itself. + if not t.shape.is_compatible_with([]): + raise AssertionError( + ("Unexpectedly saw a vectorized variant (e.g. TensorList) with " + f"non-scalar shape: {t!r}")) + return t + return array_ops.gather(t, 0) + + +@RegisterPFor("OptionalFromValue") +def _convert_optional_from_value(pfor_input: _PforInput): + pfor_input.stack_inputs() + return wrap( + gen_optional_ops.optional_from_value([x.t for x in pfor_input.inputs]), + True, + ) + + +@RegisterPFor("OptionalGetValue") +def _convert_optional_get_value(pfor_input: _PforInput): + handle = pfor_input.stacked_input(0) + output_types = pfor_input.get_attr("output_types") + original_output_shapes = pfor_input.get_attr("output_shapes") + output_shapes = [] + for shape in original_output_shapes: + shape = tensor_shape.TensorShape(shape) + loop_len_value = tensor_util.constant_value(pfor_input.pfor.loop_len_vector) + loop_len_shape = tensor_shape.TensorShape( + [loop_len_value[0] if loop_len_value is not None else None] + ) + shape = loop_len_shape.concatenate(shape) + output_shapes.append(shape.as_proto()) + results = gen_optional_ops.optional_get_value( + handle, output_types, output_shapes + ) + return [wrap(t, True) for t in results] + + +@RegisterPFor("TensorListReserve") +def _convert_tensor_list_reserve(pfor_input: _PforInput): + element_shape = pfor_input.unstacked_input(0) + num_elements = pfor_input.unstacked_input(1) + element_dtype = pfor_input.get_attr("element_dtype") + + # Prepend a dimension to element_shape. + element_shape = _stack_tensor_list_shape(element_shape, + pfor_input.pfor.loop_len_vector) + handle = list_ops.tensor_list_reserve( + element_shape, num_elements, element_dtype=element_dtype) + + return wrap(_tile_variant(handle, pfor_input), True) + + +@RegisterPFor("TensorListElementShape") +def _convert_tensor_list_element_shape(pfor_input: _PforInput): + handle = _untile_variant(pfor_input.stacked_input(0)) + shape_type = pfor_input.get_attr("shape_type") + shape = list_ops.tensor_list_element_shape(handle, shape_type) + shape = array_ops.reshape(shape, [-1]) + shape = shape[1:] + return wrap(shape, False) + + +@RegisterPFor("TensorListLength") +def _convert_tensor_list_length(pfor_input: _PforInput): + handle = _untile_variant(pfor_input.stacked_input(0)) + return wrap(list_ops.tensor_list_length(handle), False) + + +def _stack_tensor_list(handle, dtype, loop_len_vector, element_shape=None): + if element_shape is None: + element_shape = list_ops.tensor_list_element_shape(handle, dtypes.int32) + length = list_ops.tensor_list_length(handle) + new_handle = list_ops.tensor_list_reserve( + _stack_tensor_list_shape(element_shape, loop_len_vector), length, dtype) + + def _body_fn(i, h): + elem = list_ops.tensor_list_get_item(handle, i, dtype, element_shape) + elem = _stack(elem, loop_len_vector).t + return i + 1, list_ops.tensor_list_set_item(h, i, elem) + + return while_loop.while_loop(lambda i, _: i < length, _body_fn, + [0, new_handle])[1] + + +@RegisterPFor("TensorListGetItem") +def _convert_tensor_list_get_item(pfor_input: _PforInput): + handle, handle_stacked, _ = pfor_input.input(0) + index, index_stacked, _ = pfor_input.input(1) + element_shape = pfor_input.unstacked_input(2) + element_dtype = pfor_input.get_attr("element_dtype") + + if handle_stacked: + handle = _untile_variant(handle) + element_shape = _stack_tensor_list_shape(element_shape, + pfor_input.pfor.loop_len_vector) + if index_stacked: + # We use a sequential loop since that may be more efficient than first + # gathering and concatenating all the element corresponding to `index`, + # and then doing a gather on it. + def _map_fn(i): + item_i = list_ops.tensor_list_get_item( + handle, + index[i], + element_dtype=element_dtype) + return array_ops.gather(item_i, i) + + output = map_fn.map_fn(_map_fn, pfor_input.pfor.all_indices) + return wrap(output, True) + else: + output = list_ops.tensor_list_get_item( + handle, + index, + element_shape=element_shape, + element_dtype=element_dtype) + return wrap(output, True) + else: + assert index_stacked + return wrap( + list_ops.tensor_list_gather( + handle, + index, + element_shape=element_shape, + element_dtype=element_dtype), True) + + +@RegisterPFor("TensorListSetItem") +def _convert_tensor_array_set_item(pfor_input: _PforInput): + handle, handle_stacked, _ = pfor_input.input(0) + index, index_stacked, _ = pfor_input.input(1) + item, item_stacked, _ = pfor_input.input(2) + + if not handle_stacked: + # Special case where we can statically guarantee that the indices are + # disjoint. + if index is pfor_input.pfor.all_indices: + if not item_stacked: + item = _stack(item, pfor_input.pfor.loop_len_vector).t + return wrap( + list_ops.tensor_list_scatter(item, index, input_handle=handle), False) + else: + handle = _stack_tensor_list(handle, item.dtype, + pfor_input.pfor.loop_len_vector) + else: + handle = _untile_variant(handle) + + if index_stacked: + # TODO(agarwal): handle this. + raise ValueError("Vectorizing writes to a TensorList with loop " + "variant indices is currently unsupported.") + + else: + if not item_stacked: + item = _stack(item, pfor_input.pfor.loop_len_vector).t + handle = list_ops.tensor_list_set_item(handle, index, item) + return wrap(_tile_variant(handle, pfor_input), True) + + +@RegisterPFor("TensorListPushBack") +def _convert_tensor_list_push_back(pfor_input: _PforInput): + handle, handle_stacked, _ = pfor_input.input(0) + tensor, tensor_stacked, _ = pfor_input.input(1) + if handle_stacked: + handle = _untile_variant(handle) + else: + handle = _stack_tensor_list(handle, tensor.dtype, + pfor_input.pfor.loop_len_vector) + if not tensor_stacked: + tensor = _stack(tensor, pfor_input.pfor.loop_len_vector).t + handle = list_ops.tensor_list_push_back(handle, tensor) + return wrap(_tile_variant(handle, pfor_input), True) + + +@RegisterPFor("TensorListPopBack") +def _convert_tensor_array_push_back(pfor_input: _PforInput): + handle = pfor_input.stacked_input(0) + element_shape = pfor_input.unstacked_input(1) + handle = _untile_variant(handle) + + if element_shape.shape.ndims == 0: + # Default / unspecified + vectorized_shape = -1 + else: + # PopBack has an element shape set when it's the gradient of PushBack, only + # used when the list is uninitialized. + n = math_ops.cast(pfor_input.pfor.loop_len_vector, element_shape.dtype) + vectorized_shape = array_ops.concat([n, element_shape], axis=0) + + output_handle, tensor = gen_list_ops.tensor_list_pop_back( + input_handle=handle, element_dtype=pfor_input.get_attr("element_dtype"), + element_shape=vectorized_shape) + return wrap(output_handle, True), wrap(tensor, True) + + +@RegisterPFor("TensorListConcatV2") +def _convert_tensor_list_concat_v2(pfor_input: _PforInput): + input_handle = pfor_input.stacked_input(0) + element_shape = pfor_input.unstacked_input(1) + leading_dims = pfor_input.unstacked_input(2) + element_dtype = pfor_input.get_attr("element_dtype") + + handle = _untile_variant(input_handle) + length = list_ops.tensor_list_length(handle) + # Note that element_shape attribute can have incomplete shapes. This doesn't + # seem to work well when creating another list and then doing a concat on it. + # Hence we try to find the dynamic shape here. + element_shape = tf_cond.cond( + length > 0, lambda: array_ops.shape( + list_ops.tensor_list_get_item(handle, 0, element_dtype, None)), + lambda: constant_op.constant([0, 0], dtype=dtypes.int32)) + # The code below creates a copy of the list with each elements' first two + # dimensions transposed. + new_element_shape = array_ops.concat( + [element_shape[1:2], element_shape[0:1], element_shape[2:]], axis=0) + + # Create a new TensorList with elements transposed. + def _transpose_elem(i, h): + elem = list_ops.tensor_list_get_item(handle, i, element_dtype, None) + elem = _transpose_first_two_dims(elem) + return i + 1, list_ops.tensor_list_set_item(h, i, elem) + + new_handle = list_ops.tensor_list_reserve(new_element_shape, length, + element_dtype) + new_handle = while_loop.while_loop(lambda i, _: i < length, _transpose_elem, + [0, new_handle])[1] + output, lengths = gen_list_ops.tensor_list_concat_v2( + input_handle=new_handle, + element_dtype=element_dtype, + element_shape=new_element_shape, + leading_dims=leading_dims) + output = _transpose_first_two_dims(output) + return wrap(output, True), wrap(lengths, False) + + +@RegisterPFor("TensorListStack") +def _convert_tensor_list_stack(pfor_input: _PforInput): + handle = pfor_input.stacked_input(0) + input_shape = pfor_input.unstacked_input(1) + element_dtype = pfor_input.get_attr("element_dtype") + num_elements = pfor_input.get_attr("num_elements") + + handle = _untile_variant(handle) + input_shape = _stack_tensor_list_shape(input_shape, + pfor_input.pfor.loop_len_vector) + output = list_ops.tensor_list_stack( + handle, + element_dtype, + element_shape=input_shape, + num_elements=num_elements) + output = _transpose_first_two_dims(output) + return wrap(output, True) + + +@RegisterPFor("TensorListGather") +def _convert_tensor_list_gather(pfor_input: _PforInput): + handle, handle_stacked, _ = pfor_input.input(0) + index, index_stacked, _ = pfor_input.input(1) + element_shape = pfor_input.unstacked_input(2) + element_dtype = pfor_input.get_attr("element_dtype") + + if handle_stacked: + handle = _untile_variant(handle) + element_shape = _stack_tensor_list_shape(element_shape, + pfor_input.pfor.loop_len_vector) + if index_stacked: + # We use a sequential loop since that may be more efficient than first + # gathering and concatenating all the element corresponding to `index`, + # and then doing a gather on it. + def _map_fn(i): + item_i = list_ops.tensor_list_gather( + handle, + index[i], + element_dtype=element_dtype) + axis = array_ops.rank(index) - 1 + return array_ops.gather(item_i, i, axis=axis) + + output = map_fn.map_fn(_map_fn, pfor_input.pfor.all_indices) + return wrap(output, True) + else: + output = list_ops.tensor_list_gather( + handle, + index, + element_shape=element_shape, + element_dtype=element_dtype) + return wrap(output, True) + else: + assert index_stacked + index_shape = array_ops.shape(index) + index = array_ops.reshape(index, [-1]) + values = list_ops.tensor_list_gather( + handle, index, element_shape=element_shape, element_dtype=element_dtype) + final_shape = array_ops.concat( + [index_shape, array_ops.shape(values)[1:]], axis=0) + return wrap(array_ops.reshape(values, final_shape), True) + + +@RegisterPFor("TensorListScatterIntoExistingList") +def _convert_tensor_list_scatter(pfor_input: _PforInput): + pfor_input.stack_inputs([1]) + handle, handle_stacked, _ = pfor_input.input(0) + item = pfor_input.stacked_input(1) + indices, indices_stacked, _ = pfor_input.input(2) + if handle_stacked: + handle = _untile_variant(handle) + else: + handle = _stack_tensor_list(handle, item.dtype, + pfor_input.pfor.loop_len_vector) + + item = _transpose_first_two_dims(item) + if indices_stacked: + # Pretend the list is a dense tensor: + # list_as_dense: Tensor[list_len, loop_len, ...] + # And indices are a tensor with shape (before transpose): + # indices: Tensor[loop_len, num_scatters] + # The item to scatter has shape (before transpose): + # item: Tensor[loop_len, num_scatters, ...] + # + # We want list_as_dense[indices[i, j], i] = item[i, j] + # + # Since we're not just indexing along the first axis of `list_as_dense`, we + # need to first extract the relevant list entries based on `indices`, + # scatter into them according to the loop index, and re-scatter the chunks + # we updated back into the list. + indices = _transpose_first_two_dims(indices) + indices_flat = array_ops.reshape(indices, [-1]) + # In many cases `indices` will be unique across pfor iterations, but this is + # not guaranteed. If there are duplicates, we need to map multiple updates + # to a single chunk extracted from the list. The last update should win. + unique_indices = array_ops.unique(indices_flat) + gathered_items = list_ops.tensor_list_gather( + handle, unique_indices.y, element_dtype=item.dtype, + element_shape=array_ops.shape(item)[1:]) + loop_idx = math_ops.range(pfor_input.pfor.loop_len_vector[0]) + scatters_per_op = array_ops.shape(indices)[0] + + unique_indices_loop_idx = array_ops.reshape(array_ops.tile( + loop_idx[None, :], [scatters_per_op, 1]), [-1]) + scatter_indices = array_ops_stack.stack( + [unique_indices.idx, unique_indices_loop_idx], + axis=1) + # This op does *not* guarantee last-update-wins on GPU, so semantics may not + # be exactly preserved for duplicate updates there. + scattered = array_ops.tensor_scatter_nd_update( + tensor=gathered_items, + indices=scatter_indices, + updates=_flatten_first_two_dims(item)) + handle = list_ops.tensor_list_scatter( + scattered, unique_indices.y, input_handle=handle) + else: + handle = list_ops.tensor_list_scatter(item, indices, input_handle=handle) + return wrap(_tile_variant(handle, pfor_input), True) + + +@RegisterPFor("TensorListFromTensor") +def _convert_tensor_list_from_tensor(pfor_input: _PforInput): + tensor = pfor_input.stacked_input(0) + element_shape = pfor_input.unstacked_input(1) + tensor = _transpose_first_two_dims(tensor) + element_shape = _stack_tensor_list_shape(element_shape, + pfor_input.pfor.loop_len_vector) + handle = list_ops.tensor_list_from_tensor(tensor, element_shape) + return wrap(_tile_variant(handle, pfor_input), True) + + +@RegisterPFor("TensorScatterUpdate") +def _convert_tensor_scatter_update(pfor_input: _PforInput): + pfor_input.stack_inputs([0, 1, 2]) + tensor = pfor_input.stacked_input(0) + indices = pfor_input.stacked_input(1) + updates = pfor_input.stacked_input(2) + + indices_shape = array_ops.shape(indices) + indices_rank = array_ops.rank(indices) + loop_length = indices_shape[0] + + # Create a loop count range and extend its dimensions to match `indices`. + loop_count_shape = array_ops.tensor_scatter_nd_update( + array_ops.ones([indices_rank], dtype=dtypes.int32), [[0]], [loop_length]) + loop_count = array_ops.reshape(math_ops.range(loop_length), loop_count_shape) + + # Tile the loop count range for the batch dimensions (all except the first and + # last dimensions of indices). + # Rank(indices) >= 3 always for this function so we always have at least 1. + tile_multiplier = array_ops.tensor_scatter_nd_update( + indices_shape, [[0], [indices_rank - 1]], [1, 1]) + meta_index = array_ops.tile(loop_count, tile_multiplier) + + # Insert the loop-identifying index. + indices = array_ops.concat([meta_index, indices], axis=-1) + + result = array_ops.tensor_scatter_nd_update(tensor, indices, updates) + return wrap(result, True) + +# StackV2 conversion is tricky since we don't have arrays of StackV2. So similar +# to TensorArrays, we convert them by changing the dimension of the elements +# inside the stack. +# +# We consider two cases: +# +# 1. StackV2 is constructed and used entirely inside the pfor loop. +# We keep a single Stack and perform the push/pop operations of all the +# iterations in lock-step. We also assume that all the iterations perform these +# operations. In case of dynamic control flow, if only some of the iterations +# try to perform a push/pop, then the conversion may not work correctly and may +# cause undefined behavior. +# TODO(agarwal): test StackV2 with dynamic control flow. +# +# 2. StackV2 is constructed outside the pfor loop. +# Performing stack push/pop in a parallel fashion is ill-defined. However given +# that reading stacks created externally is a common operation when computing +# jacobians, we provide some special semantics here as follows. +# - disallow push operations to the stack +# - pop operations are performed in lock step by all iterations, similar to the +# case when the stack is created inside. A single value is popped during the +# lock-step operation and broadcast to all the iterations. Values in the stack +# are assumed to be loop-invariant. +# +# Some other implementation details: +# We use an ugly logic to find whether values in Stack data structure are +# loop invariant or not. When converting push/pop operations, we keep track of +# whether the last conversion used a stacked value or not (see _stack_cache +# below). As a result if an unstacked value is written first, subsequent stacked +# writes are disallowed when they could have been allowed in theory. + +# Map from cache key based on StackV2 handle to a bool indicating whether values +# are stacked or not. +# TODO(agarwal): move _stack_cache inside pfor? +_stack_cache = {} + + +def _stack_cache_key(pfor_input: _PforInput): + """Create cache key corresponding to a stack handle.""" + op_type = pfor_input.op_type + assert op_type in ["StackPushV2", "StackPopV2"], op_type + orig_handle = pfor_input.op.inputs[0] + while orig_handle.op.type in ["Identity", "Enter"]: + orig_handle = orig_handle.op.inputs[0] + assert orig_handle.op.type == "StackV2", orig_handle.op + return ops.get_default_graph(), pfor_input.pfor, orig_handle + + +def _stack_handle_inside_pfor(handle, pfor_input: _PforInput): + while handle.op.type in ["Identity", "Enter"]: + handle = handle.op.inputs[0] + assert handle.op.type == "StackV2", ("Unable to find StackV2 op. Got %s" % + handle.op) + return pfor_input.pfor.op_is_inside_loop(handle.op) + + +@RegisterPFor("StackPushV2") +def _convert_stack_push_v2(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + elem, elem_stacked, _ = pfor_input.input(1) + swap_memory = pfor_input.get_attr("swap_memory") + + if not _stack_handle_inside_pfor(pfor_input.op.inputs[0], pfor_input): + raise ValueError("StackPushV2 not allowed on stacks created outside pfor.") + stack_cache_key = _stack_cache_key(pfor_input) + stacked = _stack_cache.get(stack_cache_key, None) + if stacked is None: + stacked = elem_stacked + _stack_cache[stack_cache_key] = stacked + else: + # If we previously made it unstacked then we can't revert to being stacked. + if not stacked and elem_stacked: + raise ValueError( + "It looks like the stack was previously determined to be loop " + "invariant, but we are now trying to push a loop dependent value " + "to it. This is currently unsupported.") + if stacked and not elem_stacked: + elem = _stack(elem, pfor_input.pfor.loop_len_vector).t + out = data_flow_ops.stack_push_v2(handle, elem, swap_memory=swap_memory) + return wrap(out, stacked) + + +# Note that inputs to this convertor will be unstacked. However it should get +# called since it is a stateful op. +@RegisterPFor("StackPopV2") +def _convert_stack_pop_v2(pfor_input: _PforInput): + handle = pfor_input.unstacked_input(0) + stack_cache_key = _stack_cache_key(pfor_input) + stacked = _stack_cache.get(stack_cache_key, None) + # If a StackPushV2 has not been converted yet, we default to unstacked since + # the push could be outside of pfor, or the convertor may not be called if the + # inputs are unconverted. + if stacked is None: + stacked = False + _stack_cache[stack_cache_key] = False + elem_type = pfor_input.get_attr("elem_type") + out = data_flow_ops.stack_pop_v2(handle, elem_type) + return wrap(out, stacked) + + +# parsing_ops + + +@RegisterPFor("DecodeCSV") +def _convert_decode_csv(pfor_input: _PforInput): + lines = pfor_input.stacked_input(0) + record_defaults = [ + pfor_input.unstacked_input(i) for i in range(1, pfor_input.num_inputs) + ] + field_delim = pfor_input.get_attr("field_delim") + use_quote_delim = pfor_input.get_attr("use_quote_delim") + select_cols = pfor_input.get_attr("select_cols") + if not select_cols: + select_cols = None + return [ + wrap(t, True) for t in gen_parsing_ops.decode_csv( + lines, + record_defaults, + field_delim=field_delim, + use_quote_delim=use_quote_delim, + select_cols=select_cols) + ] + + +@RegisterPFor("ParseSingleExample") +def _convert_parse_single_example(pfor_input: _PforInput): + serialized = pfor_input.stacked_input(0) + dense_defaults = [ + pfor_input.unstacked_input(i) for i in range(1, pfor_input.num_inputs) + ] + sparse_keys = pfor_input.get_attr("sparse_keys") + dense_keys = pfor_input.get_attr("dense_keys") + sparse_types = pfor_input.get_attr("sparse_types") + dense_shapes = pfor_input.get_attr("dense_shapes") + output = gen_parsing_ops.parse_example( + serialized=serialized, + names=[], + dense_defaults=dense_defaults, + sparse_keys=sparse_keys, + dense_keys=dense_keys, + sparse_types=sparse_types, + dense_shapes=dense_shapes) + return [wrap(t, True, True) for t in nest.flatten(output)] + + +@RegisterPFor("ParseExampleV2") +def _convert_parse_example_v2(pfor_input: _PforInput): + serialized = pfor_input.stacked_input(0) + sparse_keys = pfor_input.unstacked_input(2) + dense_keys = pfor_input.unstacked_input(3) + ragged_keys = pfor_input.unstacked_input(4) + dense_defaults = [ + pfor_input.unstacked_input(i) for i in range(5, pfor_input.num_inputs) + ] + num_sparse = pfor_input.get_attr("num_sparse") + sparse_types = pfor_input.get_attr("sparse_types") + ragged_value_types = pfor_input.get_attr("ragged_value_types") + ragged_split_types = pfor_input.get_attr("ragged_split_types") + dense_shapes = pfor_input.get_attr("dense_shapes") + if serialized.shape.ndims not in (None, 1): + raise ValueError("ParseExampleV2 can only be converted if `serialized` " + f"is scalar. Received shape: {serialized.shape}.") + output = gen_parsing_ops.parse_example_v2( + serialized=serialized, + names=[], + sparse_keys=sparse_keys, + dense_keys=dense_keys, + ragged_keys=ragged_keys, + dense_defaults=dense_defaults, + num_sparse=num_sparse, + sparse_types=sparse_types, + ragged_value_types=ragged_value_types, + ragged_split_types=ragged_split_types, + dense_shapes=dense_shapes) + return [wrap(t, True, True) for t in nest.flatten(output)] + + +# functional_ops + + +def _convert_function_call(func, converter, inputs): + assert isinstance(func.graph, func_graph.FuncGraph), func + assert isinstance(converter, PFor) + + graph_outputs = func.graph.outputs[:len(func.function_type.flat_outputs)] + # TODO(agarwal): consider caching this function definition. + @def_function.function + def f(*args): + assert all(isinstance(arg, WrappedTensor) for arg in args), args + assert len(args) == len(func.graph.inputs), (args, func.graph.inputs) + # Map inputs to function arguments. + for inp, arg in zip(func.graph.inputs, args): + converter._add_conversion(inp, arg) + # Convert output tensors. + return tuple([converter._convert_helper(x).t for x in graph_outputs]) + + call_outputs = f(*inputs) + assert len(call_outputs) == len(graph_outputs) + outputs = [] + for call_output, output_tensor in zip(call_outputs, graph_outputs): + func_output = converter._convert_helper(output_tensor) + outputs.append( + wrap(call_output, func_output.is_stacked, func_output.is_sparse_stacked) + ) + return outputs + + +@RegisterPFor("StatefulPartitionedCall") +@RegisterPFor("PartitionedCall") +def _convert_partitioned_call(pfor_input: _PforInput): + func_name = pfor_input.get_attr("f").name + func = pfor_input.op.graph._get_function(compat.as_bytes(func_name)) + assert isinstance(func.graph, func_graph.FuncGraph), ( + "Could not find FuncGraph object for %s. Got func %s" % (func_name, func)) + pfor = pfor_input.pfor + converter = PFor( + loop_var=pfor.loop_var, + loop_len=pfor.loop_len_vector[0], + pfor_ops=func.graph.get_operations(), + fallback_to_while_loop=pfor.fallback_to_while_loop, + all_indices=pfor.all_indices, + all_indices_partitioned=pfor.all_indices_partitioned, + pfor_config=pfor.pfor_config) + return _convert_function_call(func, converter, pfor_input.inputs) + + +def _partition_inputs_for_indices(inputs, indices): + new_inputs = [] + for inp in inputs: + if inp.is_stacked: + new_inputs.append(wrap(array_ops.gather(inp.t, indices), True)) + else: + new_inputs.append(inp) + return new_inputs + + +def _outputs_for_branch(func_name, indices, pfor_input: _PforInput, inputs): + if indices is None: + indices = pfor_input.pfor.all_indices + partitioned = pfor_input.pfor.all_indices_partitioned + else: + partitioned = True + func = pfor_input.op.graph._get_function(func_name) + converter = PFor( + loop_var=pfor_input.pfor.loop_var, + loop_len=array_ops.size(indices), + pfor_ops=func.graph.get_operations(), + fallback_to_while_loop=pfor_input.pfor.fallback_to_while_loop, + all_indices=indices, + all_indices_partitioned=partitioned, + pfor_config=pfor_input.pfor.pfor_config) + outputs = _convert_function_call(func, converter, inputs) + stacked_outputs = [] + for out in outputs: + if not out.is_stacked: + stacked_outputs.append(_stack(out.t, [array_ops.size(indices)]).t) + else: + stacked_outputs.append(out.t) + return stacked_outputs + + +# TODO(agarwal): Currently the converted code aggressively tiles loop variant +# outputs from the then/else branches. Instead, it could do so only if at least +# one of the branch outputs is loop variant. +@RegisterPFor("StatelessIf") +@RegisterPFor("If") +def _convert_if(pfor_input: _PforInput): + cond, cond_stacked, _ = pfor_input.input(0) + inputs = pfor_input.inputs[1:] + then_branch = pfor_input.get_attr("then_branch") + else_branch = pfor_input.get_attr("else_branch") + + if cond_stacked: + cond_int = math_ops.cast(cond, dtypes.int32) + # Compute loop indices for the different branches + false_indices, true_indices = data_flow_ops.dynamic_partition( + pfor_input.pfor.all_indices, cond_int, 2) + # Compute indices for cond being True or False. + if pfor_input.pfor.all_indices_partitioned: + else_indices, then_indices = data_flow_ops.dynamic_partition( + math_ops.range(pfor_input.pfor.loop_len_vector[0]), + cond_int, 2) + else: + else_indices, then_indices = false_indices, true_indices + # Partition inputs + then_inputs = _partition_inputs_for_indices(inputs, then_indices) + else_inputs = _partition_inputs_for_indices(inputs, else_indices) + + # Convert "then" branch. + then_outputs = _outputs_for_branch(then_branch.name, true_indices, + pfor_input, then_inputs) + + # Convert "else" branch. + else_outputs = _outputs_for_branch(else_branch.name, false_indices, + pfor_input, else_inputs) + + assert len(then_outputs) == len(else_outputs) + # Note that if the "then" and "else" branches are updating the same state, + # and possibly reading them as well, it could lead to undefined behavior + # since the ordering of those operations is not well defined. + # One possibility is to order all the "then" branches to execute before all + # the "else" branches so that the side-effects in the former are visible to + # the latter. For now, we leave that as undefined behavior. + outputs = [] + # Merge outputs + for then_output, else_output in zip(then_outputs, else_outputs): + out = data_flow_ops.dynamic_stitch([then_indices, else_indices], + [then_output, else_output]) + outputs.append(wrap(out, True)) + return outputs + else: + outputs = tf_cond.cond( + cond, + lambda: _outputs_for_branch(then_branch.name, None, pfor_input, inputs), + lambda: _outputs_for_branch(else_branch.name, None, pfor_input, inputs)) + return [wrap(t, True) for t in outputs] + + +@RegisterPFor("Case") +@RegisterPFor("StatelessCase") +def _convert_stateless_case(pfor_input: _PforInput): + branch_idx, is_stacked, _ = pfor_input.input(0) + branches = pfor_input.get_attr("branches") + inputs = pfor_input.inputs[1:] + + if is_stacked: + logging.info("Running stacked flow") + + # Compute loop indices for the different branches + switch_indices = data_flow_ops.dynamic_partition( + pfor_input.pfor.all_indices, branch_idx, len(branches)) + if pfor_input.pfor.all_indices_partitioned: + partitioned_indices = data_flow_ops.dynamic_partition( + math_ops.range(pfor_input.pfor.loop_len_vector[0]), branch_idx, + len(branches)) + else: + partitioned_indices = switch_indices + # Partition inputs + input_list = [] + for indices in partitioned_indices: + input_list.append(_partition_inputs_for_indices(inputs, indices)) + + outputs = [] + for (b, indices, inputs) in zip(branches, switch_indices, input_list): + out = _outputs_for_branch(b.name, indices, pfor_input, inputs) + outputs.extend(out) + + out = data_flow_ops.dynamic_stitch(partitioned_indices, outputs) + return [wrap(out, True)] + else: + new_branches = [] + for b in branches: + def new_function(func=b.name): + return _outputs_for_branch(func, None, pfor_input, + pfor_input.inputs[1:]) + + new_branches.append(new_function) + + outputs = [] + outputs = control_flow_switch_case.switch_case(branch_idx, new_branches) + return [wrap(t, True) for t in outputs] + + +class WhileV2: + """Object for vectorizing V2 while_loop op.""" + + def __init__(self, pfor_input: _PforInput): + self._pfor_input = pfor_input + self._pfor = pfor_input.pfor + cond_func_name = pfor_input.get_attr("cond").name + self._cond_func = pfor_input.op.graph._get_function(compat.as_bytes( + cond_func_name)) + body_func_name = pfor_input.get_attr("body").name + self._body_func = pfor_input.op.graph._get_function(compat.as_bytes( + body_func_name)) + if self._cond_func is None or self._body_func is None: + raise ValueError("Error extracting cond and body functions for op " + f"{self._pfor_input.op}.") + # Indices of inputs that are passed unchanged through the while loop body. + # Typically these are tensors captured from outside the body context. + self._body_pass_through_indices = set() + for i, (inp, out) in enumerate(zip(self._body_func.graph.inputs, + self._body_func.graph.outputs)): + if id(inp) == id(out): + self._body_pass_through_indices.add(i) + self._parallel_iterations = self._pfor_input.get_attr("parallel_iterations") + + def _output_shapes(self): + # Calculate output shape for vectorized loop. This will be used as + # shape_invariant. Merges shape inference outputs with the `output_shapes` + # attribute of the op. + output_shapes = [out.shape for out in self._pfor_input.op.outputs] + shapes = self._pfor_input.get_attr("output_shapes") + if not shapes: + shapes = [tensor_shape.TensorShape(None) for _ in output_shapes] + else: + shapes = [tensor_shape.TensorShape(shape) for shape in shapes] + for i, shape in enumerate(shapes): + shape = shape.merge_with(output_shapes[i]) + pfor_input = self._pfor_input.input(i) + if pfor_input.is_stacked: + if _is_variant_with_internal_stacking(pfor_input.t): + shape = tensor_shape.TensorShape([]).concatenate(shape) + else: + shape = tensor_shape.TensorShape([None]).concatenate(shape) + output_shapes[i] = shape + assert len(output_shapes) == self._pfor_input.num_inputs + return output_shapes + + def _init_values(self): + """Create arguments passed to converted while_loop.""" + loop_len = self._pfor.loop_len_vector[0] + inputs = [] + # TensorArrays for outputs of converted while loop + output_tas = [] + + with ops.name_scope("while_init"): + for inp in self._pfor_input.inputs: + inputs.append(inp.t) + variant_type_id = _variant_type_id(inp.t) + if variant_type_id in _INTERNAL_STACKING_TYPE_IDS: + if variant_type_id != full_type_pb2.TFT_ARRAY: + raise NotImplementedError( + "While loop conversion is only supported for TensorLists. Got " + f"another variant {inp.t}, probably an optional. Please file " + "a bug.") + + # For TensorLists, the input format is: + # + # List[user_list_len, Tensor[loop_len, ...]] + # + # rather than the usual + # + # Tensor[loop_len, ...] + # + # The body of the loop will take and return lists in this "internal + # vectorization" format, so we want to keep it that way as much as + # possible. We'll accumulate finished iterations (only relevant for + # pfor-loop-variant while_loop conditions) in an accumulator with + # type : + # + # List[user_list_len, List[loop_len, Tensor[...]]] + # + # This means that each while_loop iteration, we'll iterate over the + # length of the TensorList, dividing done/remaining pfor loop indices + # and scattering the done indices into the inner nested list of the + # accumulator. + element_shape = list_ops.tensor_list_element_shape( + inp.t, dtypes.int32) + if inp.is_stacked: + # Shapes may be tf.constant(-1) for fully dynamic, in which case + # slicing is an error. + element_shape = tf_cond.cond( + math_ops.equal(array_ops.rank(element_shape), 0), + lambda: element_shape, + lambda: element_shape[1:]) + dtype = _parse_variant_shapes_and_types(inp.t)[0].dtype + + def _init_loop_body(index, output_ta): + output_ta = output_ta.write( + index, + list_ops.tensor_list_reserve(element_shape, loop_len, dtype)) + return index + 1, output_ta + + length = list_ops.tensor_list_length(inp.t) + output_ta = tensor_array_ops.TensorArray( + inp.t.dtype, # Variant; this is a nested TensorList + size=length, + dynamic_size=True, + infer_shape=False) + _, output_ta = while_loop.while_loop(lambda index, _: index < length, + _init_loop_body, [0, output_ta]) + else: + output_ta = tensor_array_ops.TensorArray( + inp.t.dtype, + size=loop_len, + dynamic_size=False, + infer_shape=True) + output_tas.append(output_ta) + # See documentation for __call__ for the structure of init_values. + indices = ( + math_ops.range(self._pfor.loop_len_vector[0]) + if self._pfor.all_indices_partitioned else self._pfor.all_indices) + return [True, indices] + inputs + output_tas + + def _process_cond_unstacked(self, conditions, indices, inputs, output_tas): + """Handles case when condition is pfor loop invariant.""" + # Note that all iterations end together. So we don't need to partition the + # inputs. + not_all_done = array_ops.reshape(conditions, []) + return not_all_done, indices, inputs, output_tas + + def _process_cond_stacked(self, conditions, indices, inputs, inputs_stacked, + output_tas): + """Handles case when condition is pfor loop dependent.""" + # Compute if all iterations are done. + not_all_done = math_ops.reduce_any(conditions) + conditions_int = math_ops.cast(conditions, dtypes.int32) + # Partition the indices. + done_indices, new_indices = data_flow_ops.dynamic_partition( + indices, conditions_int, 2) + + new_inputs = [] + new_output_tas = [] + for i, (inp, stacked) in enumerate(zip(inputs, inputs_stacked)): + pass_through = i in self._body_pass_through_indices + if not pass_through and _variant_type_id(inp) == full_type_pb2.TFT_ARRAY: + shape_and_type = _parse_variant_shapes_and_types(inp)[0] + element_shape = list_ops.tensor_list_element_shape(inp, dtypes.int32) + user_list_len = list_ops.tensor_list_length(inp) + + def _split_vectorized_ta_element(index, new_inp, new_out_ta): + elem = list_ops.tensor_list_get_item(inp, index, shape_and_type.dtype, + element_shape) + if stacked: + done_elem, new_elem = data_flow_ops.dynamic_partition( + elem, conditions_int, 2) + new_inp = list_ops.tensor_list_set_item(new_inp, index, new_elem) + else: + done_elem = _stack(elem, [array_ops.size(done_indices)]).t + done_accum = new_out_ta.read(index) + done_accum = list_ops.tensor_list_scatter( + tensor=done_elem, indices=done_indices, input_handle=done_accum) + new_out_ta = new_out_ta.write(index, done_accum) + return index + 1, new_inp, new_out_ta + + length = list_ops.tensor_list_length(inp) + new_inp = list_ops.tensor_list_reserve( + tensor_shape.TensorShape([None]) + + tensor_shape.TensorShape(shape_and_type.shape)[1:], + user_list_len, shape_and_type.dtype) + _, new_inp, out_ta = while_loop.while_loop( + lambda index, unused_new_inp, unused_new_out_ta: index < length, + _split_vectorized_ta_element, [0, new_inp, output_tas[i]]) + else: + # Partition the inputs. + if stacked: + done_inp, new_inp = data_flow_ops.dynamic_partition( + inp, conditions_int, 2) + else: + if not pass_through: + done_inp = _stack(inp, [array_ops.size(done_indices)]).t + new_inp = inp + + out_ta = output_tas[i] + if not pass_through: + # Note that done_indices can be empty. done_inp should also be empty + # in that case. + out_ta = out_ta.scatter(done_indices, done_inp) + new_inputs.append(new_inp) + new_output_tas.append(out_ta) + + assert len(new_output_tas) == len(output_tas) + assert len(new_inputs) == len(inputs) + return not_all_done, new_indices, new_inputs, new_output_tas + + def _process_body(self, inputs_stacked, new_indices, cond_stacked, + new_inputs, not_all_done): + """Convert the body function.""" + # This is used to store the indices of inputs to the while op that need to + # be stacked. This stacking may be needed in cases where the input to the + # while_loop is loop_invariant but the corresponding output is not. + mismatching_stacked_indices = [] + + def true_fn(): + """Converts the body function for all but last iteration.""" + wrapped_inputs = [wrap(inp, stacked) for inp, stacked in + zip(new_inputs, inputs_stacked)] + # Note the iterative process below to figure out loop invariance. + # Here we iterate on vectorization process till a fixed point. The issue + # is that the while body can take pfor loop invariant inputs but return + # loop variant outputs. For any loop variant output, the corresponding + # input has to be then made loop variant (since subsequent while + # iterations will need to see loop variant values). + # However once we make a new input loop variant, we might make other + # outputs loop variant. Hence we need to iterate till we get fixed point. + while True: + if self._pfor.all_indices_partitioned: + indices = array_ops.gather(self._pfor.all_indices, new_indices) + else: + indices = new_indices + body_pfor = PFor( + loop_var=self._pfor.loop_var, + loop_len=array_ops.size(new_indices), + pfor_ops=self._body_func.graph.get_operations(), + fallback_to_while_loop=self._pfor.fallback_to_while_loop, + all_indices=indices, + all_indices_partitioned=(self._pfor.all_indices_partitioned or + cond_stacked), + pfor_config=self._pfor.pfor_config) + stacking_mismatch = False + outputs = _convert_function_call(self._body_func, + body_pfor, + wrapped_inputs) + for i, (out, inp) in enumerate(zip(outputs, wrapped_inputs)): + if out.is_stacked != inp.is_stacked: + stacking_mismatch = True + mismatching_stacked_indices.append(i) + stacked = _stack(inp.t, [array_ops.size(new_indices)]) + if inp.t.dtype == dtypes.variant: + stacked = wrap( + _tile_variant_with_length(stacked.t, + [array_ops.size(new_indices)])) + wrapped_inputs[i] = stacked + if not stacking_mismatch: + if mismatching_stacked_indices: + # We needed to stack some inputs. This code will be abandoned and + # should not get executed. Hence we simply return `new_inputs` to + # make sure the graph construction code completes. + with ops.control_dependencies([ + control_flow_assert.Assert( + False, ["pfor ERROR: this branch should never execute"]) + ]): + return [array_ops.identity(x) for x in new_inputs] + else: + return [out.t for out in outputs] + + # If all are done, we simply return `new_inputs`. Else we need to run the + # body function. + return tf_cond.cond( + not_all_done, + true_fn, + lambda: list(new_inputs)), mismatching_stacked_indices + + def __call__(self): + """Converter for the V2 while_loop. + + The conversion of a while_loop is another while_loop. + + The arguments to this converted while_loop are as follows: + not_all_done: Boolean scalar Tensor indicating if all the pfor iterations + are done. + indices: int32 1-D Tensor storing the id of the pfor iterations that are not + done. + args: Remaining arguments. These can be divided into 2 categories: + - The first set of arguments correspond one-to-one to the inputs to the + unvectorized while_loop. + - The second set are TensorArrays, corresponding one-to-one to each output + of the unvectorized while_loop. Each TensorArray has `PFor.loop_len` + elements, i.e. the number of pfor iterations. At the end, the i'th + element of each TensorArray will contain the output computed by the i'th + iteration of pfor. Note that elements can be written into these tensors + arrays in any order, depending on when the corresponding pfor iteration + is done. + In each iteration, the while_loop body recomputes the condition for all + active pfor iterations to see which of them are now done. It then partitions + all the inputs and passes them along to the converted body. Values for all + the iterations that are done are written to TensorArrays indexed by the pfor + iteration number. When all iterations are done, the TensorArrays are stacked + to get the final value. + + Returns: + List of converted outputs. + """ + output_shapes = self._output_shapes() + # Note that we use these lists as a hack since we need the `body` to compute + # these values during construction of the while_loop graph. + cond_is_stacked = [None] + indices_to_stack = [] + + def cond(not_all_done, *_): + return not_all_done + + def body(not_all_done, indices, *args): + # See documentation for __call__ for the structure of *args. + num_inputs = self._pfor_input.num_inputs + inputs = args[:num_inputs] + output_tas = args[num_inputs:] + inputs_stacked = [x.is_stacked for x in self._pfor_input.inputs] + assert len(inputs) >= len(output_tas) + assert len(inputs) == len(inputs_stacked) + # Convert condition + with ops.name_scope("while_cond"): + # Note that we set all_indices_partitioned to True here. At this point + # we don't know if indices will be partitioned. Hence we use the + # conservative value. + cond_pfor = PFor( + loop_var=self._pfor.loop_var, + loop_len=array_ops.size(indices), + pfor_ops=self._cond_func.graph.get_operations(), + fallback_to_while_loop=self._pfor.fallback_to_while_loop, + all_indices=indices, + all_indices_partitioned=True, + pfor_config=self._pfor.pfor_config) + + wrapped_inputs = [wrap(inp, stacked) for inp, stacked + in zip(inputs, inputs_stacked)] + conditions, cond_stacked, _ = _convert_function_call( + self._cond_func, + cond_pfor, + wrapped_inputs)[0] + cond_is_stacked[0] = cond_stacked + + # Recompute the new condition, write outputs of done iterations, and + # partition the inputs if needed. + if not cond_stacked: + (not_all_done, new_indices, new_inputs, + new_output_tas) = self._process_cond_unstacked(conditions, indices, + inputs, output_tas) + else: + (not_all_done, new_indices, new_inputs, + new_output_tas) = self._process_cond_stacked(conditions, indices, + inputs, inputs_stacked, + output_tas) + # Convert body + with ops.name_scope("while_body"): + # Compute the outputs from the body. + new_outputs, mismatching_stacked_indices = self._process_body( + inputs_stacked, new_indices, cond_stacked, new_inputs, not_all_done) + + indices_to_stack[:] = mismatching_stacked_indices + for i, new_output in enumerate(new_outputs): + new_output.set_shape(output_shapes[i]) + new_args = ([not_all_done, new_indices] + new_outputs + + list(new_output_tas)) + return tuple(new_args) + + # Note that we run the code below in a function since we might abandon the + # generated code in cases where the conversion dictates that some inputs be + # further stacked. Hence we run the graph construction using + # `get_concrete_function` and avoid calling the constructed function if not + # needed. + @def_function.function + def while_fn(): + # Create init_values that will be passed to the while_loop. + init_values = self._init_values() + ta_shape_invariants = [tensor_shape.TensorShape([]) for _ in + self._pfor_input.outputs] + shape_invariants = ( + [tensor_shape.TensorShape([]), tensor_shape.TensorShape([None])] + + output_shapes + ta_shape_invariants) + + while_outputs = while_loop.while_loop( + cond, + body, + init_values, + shape_invariants=shape_invariants, + parallel_iterations=self._parallel_iterations) + if indices_to_stack: + # This function will be abandoned. + return while_outputs + else: + num_inputs = self._pfor_input.num_inputs + new_inputs = while_outputs[2:num_inputs+2] + output_tas = while_outputs[num_inputs+2:] + assert cond_is_stacked[0] is not None + outputs = [] + for i, inp in enumerate(new_inputs): + if cond_is_stacked[0]: + if i in self._body_pass_through_indices: + outputs.append(init_values[i + 2]) + else: + ta = output_tas[i] + if _variant_type_id(inp) == full_type_pb2.TFT_ARRAY: + shape_and_type = _parse_variant_shapes_and_types(inp)[0] + length = list_ops.tensor_list_length(inp) + + # We have been accumulating values in a: + # + # List[user_list_len, List[loop_len, Tensor[...]]] + # + # We want to return an output in the same format as the input: + # + # List[user_list_len, Tensor[loop_len, ...]] + # + # So we need to loop over the list and stack its contents. + def _stack_loop_body(index, output_list): + current_value = ta.read(index) + output_list = list_ops.tensor_list_set_item( + output_list, index, + list_ops.tensor_list_stack( + current_value, shape_and_type.dtype)) + return index + 1, output_list + + output_list = list_ops.tensor_list_reserve( + tensor_shape.TensorShape(shape_and_type.shape), length, + shape_and_type.dtype) + _, output_list = while_loop.while_loop( + lambda index, _: index < length, _stack_loop_body, + [0, output_list]) + outputs.append(output_list) + else: + outputs.append(ta.stack()) + else: + outputs.append(inp) + return outputs + + _ = while_fn.get_concrete_function() + if indices_to_stack: + # Need to abandon the current conversion, stack some inputs and restart. + self._pfor_input.stack_inputs( + stack_indices=indices_to_stack, tile_variants=True) + # Note that this call will recurse at most one time. The first call will + # do the required stacking, based on the iterative procedure in + # _process_body, and the next invocation to __call__ should not need to do + # any more stacking. + # We invoke `self()` here as a way to discard any corrupted state. + return self() + else: + outputs = while_fn() + wrapped_outputs = [] + for i, (out, inp) in enumerate(zip(outputs, self._pfor_input.inputs)): + if i not in self._body_pass_through_indices and cond_is_stacked[0]: + wrapped_outputs.append(wrap(out, True)) + else: + wrapped_outputs.append(wrap(out, inp.is_stacked)) + return wrapped_outputs + + +@RegisterPFor("StatelessWhile") +@RegisterPFor("While") +def _convert_while(pfor_input: _PforInput): + converter = WhileV2(pfor_input) + return converter() + + +# spectral_ops + + +@RegisterPForWithArgs("FFT", gen_spectral_ops.fft) +@RegisterPForWithArgs("FFT2D", gen_spectral_ops.fft2d) +@RegisterPForWithArgs("FFT3D", gen_spectral_ops.fft3d) +@RegisterPForWithArgs("IFFT", gen_spectral_ops.ifft) +@RegisterPForWithArgs("IFFT2D", gen_spectral_ops.ifft2d) +@RegisterPForWithArgs("IFFT3D", gen_spectral_ops.ifft3d) +def _convert_fft(pfor_input: _PforInput, _, op_func): + return wrap(op_func(pfor_input.stacked_input(0)), True) + + +@RegisterPForWithArgs("RFFT", gen_spectral_ops.rfft, "Tcomplex") +@RegisterPForWithArgs("RFFT2D", gen_spectral_ops.rfft2d, "Tcomplex") +@RegisterPForWithArgs("RFFT3D", gen_spectral_ops.rfft3d, "Tcomplex") +@RegisterPForWithArgs("IRFFT", gen_spectral_ops.irfft, "Treal") +@RegisterPForWithArgs("IRFFT2D", gen_spectral_ops.irfft2d, "Treal") +@RegisterPForWithArgs("IRFFT3D", gen_spectral_ops.irfft3d, "Treal") +def _convert_rfft(pfor_input: _PforInput, _, op_func, attr_name): + inp = pfor_input.stacked_input(0) + fft_length = pfor_input.unstacked_input(1) + attr = pfor_input.get_attr(attr_name) + return wrap(op_func(inp, fft_length, attr), True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa3f4559d4bfcce3c3a4131a5e0b4164b2b055f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parallel_for/test_util.py @@ -0,0 +1,76 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Test utility.""" + +import numpy as np + +from tensorflow.python.ops import variables +from tensorflow.python.ops.parallel_for import control_flow_ops as pfor_control_flow_ops +from tensorflow.python.platform import test +from tensorflow.python.util import nest + + +class PForTestCase(test.TestCase): + """Base class for test cases.""" + + def _run_targets(self, targets1, targets2=None, run_init=True): + targets1 = nest.flatten(targets1) + targets2 = ([] if targets2 is None else nest.flatten(targets2)) + assert len(targets1) == len(targets2) or not targets2 + if run_init: + init = variables.global_variables_initializer() + self.evaluate(init) + return self.evaluate(targets1 + targets2) + + # TODO(agarwal): Allow tests to pass down tolerances. + def run_and_assert_equal(self, targets1, targets2, rtol=1e-4, atol=1e-5): + outputs = self._run_targets(targets1, targets2) + outputs = nest.flatten(outputs) # flatten SparseTensorValues + n = len(outputs) // 2 + for i in range(n): + if outputs[i + n].dtype != np.object_: + self.assertAllClose(outputs[i + n], outputs[i], rtol=rtol, atol=atol) + else: + self.assertAllEqual(outputs[i + n], outputs[i]) + + def _test_loop_fn(self, + loop_fn, + iters, + parallel_iterations=None, + fallback_to_while_loop=False, + rtol=1e-4, + atol=1e-5): + t1 = pfor_control_flow_ops.pfor( + loop_fn, + iters=iters, + fallback_to_while_loop=fallback_to_while_loop, + parallel_iterations=parallel_iterations) + loop_fn_dtypes = nest.map_structure(lambda x: x.dtype, t1) + t2 = pfor_control_flow_ops.for_loop(loop_fn, loop_fn_dtypes, iters=iters, + parallel_iterations=parallel_iterations) + + def _check_shape(a, b): + msg = ( + "Inferred static shapes are different between two loops:" + f" {a.shape} vs {b.shape}." + ) + # TODO(b/268146947): should assert bool(a.shape) == bool(b.shape), + # since both should be either defined or undefined. But it does not work. + if b.shape: + self.assertEqual(a.shape.as_list()[0], b.shape.as_list()[0], msg) + # TODO(b/268146947): self.assertShapeEqual(a, b, msg) does not work. + + nest.map_structure(_check_shape, t1, t2) + self.run_and_assert_equal(t1, t2, rtol=rtol, atol=atol) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8be4c9c79fc9889ca1413e39e683b48282f1b978 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_config.py @@ -0,0 +1,903 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Feature configuration for tf.io.parse_example.""" + +import collections +import re + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging +from tensorflow.python.util.tf_export import tf_export + + +# TODO(b/122887740) Refactor code: +# * Move input verification to feature configuration objects (e.g., +# VarLenFeature should check that dtype is a valid dtype). +# * Add an _add_feature() method to each feature configuration object +# (rather than using a dispatch table in _ParseOpParams._add_feature). +# * Update _construct_tensors_for_composite_features() to call a method +# on the feature object (rather than using dispatch). + + +@tf_export("io.VarLenFeature", v1=["VarLenFeature", "io.VarLenFeature"]) +class VarLenFeature(collections.namedtuple("VarLenFeature", ["dtype"])): + """Configuration for parsing a variable-length input feature. + + Fields: + dtype: Data type of input. + """ + pass + + +@tf_export("io.RaggedFeature") +class RaggedFeature( + collections.namedtuple( + "RaggedFeature", + ["dtype", "value_key", "partitions", "row_splits_dtype", "validate"])): + """Configuration for passing a RaggedTensor input feature. + + `value_key` specifies the feature key for a variable-length list of values; + and `partitions` specifies zero or more feature keys for partitioning those + values into higher dimensions. Each element of `partitions` must be one of + the following: + + * `tf.io.RaggedFeature.RowSplits(key: string)` + * `tf.io.RaggedFeature.RowLengths(key: string)` + * `tf.io.RaggedFeature.RowStarts(key: string)` + * `tf.io.RaggedFeature.RowLimits(key: string)` + * `tf.io.RaggedFeature.ValueRowIds(key: string)` + * `tf.io.RaggedFeature.UniformRowLength(length: int)`. + + Where `key` is a feature key whose values are used to partition the values. + Partitions are listed from outermost to innermost. + + * If `len(partitions) == 0` (the default), then: + + * A feature from a single `tf.Example` is parsed into a 1D `tf.Tensor`. + * A feature from a batch of `tf.Example`s is parsed into a 2D + `tf.RaggedTensor`, where the outer dimension is the batch dimension, and + the inner (ragged) dimension is the feature length in each example. + + * If `len(partitions) == 1`, then: + + * A feature from a single `tf.Example` is parsed into a 2D + `tf.RaggedTensor`, where the values taken from the `value_key` are + separated into rows using the partition key. + * A feature from a batch of `tf.Example`s is parsed into a 3D + `tf.RaggedTensor`, where the outer dimension is the batch dimension, + the two inner dimensions are formed by separating the `value_key` values + from each example into rows using that example's partition key. + + * If `len(partitions) > 1`, then: + + * A feature from a single `tf.Example` is parsed into a `tf.RaggedTensor` + whose rank is `len(partitions)+1`, and whose ragged_rank is + `len(partitions)`. + + * A feature from a batch of `tf.Example`s is parsed into a `tf.RaggedTensor` + whose rank is `len(partitions)+2` and whose ragged_rank is + `len(partitions)+1`, where the outer dimension is the batch dimension. + + There is one exception: if the final (i.e., innermost) element(s) of + `partitions` are `UniformRowLength`s, then the values are simply reshaped (as + a higher-dimensional `tf.Tensor`), rather than being wrapped in a + `tf.RaggedTensor`. + + #### Examples + + >>> import google.protobuf.text_format as pbtext + >>> example_batch = [ + ... pbtext.Merge(r''' + ... features { + ... feature {key: "v" value {int64_list {value: [3, 1, 4, 1, 5, 9]}}} + ... feature {key: "s1" value {int64_list {value: [0, 2, 3, 3, 6]}}} + ... feature {key: "s2" value {int64_list {value: [0, 2, 3, 4]}}} + ... }''', tf.train.Example()).SerializeToString(), + ... pbtext.Merge(r''' + ... features { + ... feature {key: "v" value {int64_list {value: [2, 7, 1, 8, 2, 8, 1]}}} + ... feature {key: "s1" value {int64_list {value: [0, 3, 4, 5, 7]}}} + ... feature {key: "s2" value {int64_list {value: [0, 1, 1, 4]}}} + ... }''', tf.train.Example()).SerializeToString()] + + >>> features = { + ... # Zero partitions: returns 1D tf.Tensor for each Example. + ... 'f1': tf.io.RaggedFeature(value_key="v", dtype=tf.int64), + ... # One partition: returns 2D tf.RaggedTensor for each Example. + ... 'f2': tf.io.RaggedFeature(value_key="v", dtype=tf.int64, partitions=[ + ... tf.io.RaggedFeature.RowSplits("s1")]), + ... # Two partitions: returns 3D tf.RaggedTensor for each Example. + ... 'f3': tf.io.RaggedFeature(value_key="v", dtype=tf.int64, partitions=[ + ... tf.io.RaggedFeature.RowSplits("s2"), + ... tf.io.RaggedFeature.RowSplits("s1")]) + ... } + + >>> feature_dict = tf.io.parse_single_example(example_batch[0], features) + >>> for (name, val) in sorted(feature_dict.items()): + ... print('%s: %s' % (name, val)) + f1: tf.Tensor([3 1 4 1 5 9], shape=(6,), dtype=int64) + f2: + f3: + + >>> feature_dict = tf.io.parse_example(example_batch, features) + >>> for (name, val) in sorted(feature_dict.items()): + ... print('%s: %s' % (name, val)) + f1: + f2: + f3: + + Fields: + dtype: Data type of the `RaggedTensor`. Must be one of: + `tf.dtypes.int64`, `tf.dtypes.float32`, `tf.dtypes.string`. + value_key: (Optional.) Key for a `Feature` in the input `Example`, whose + parsed `Tensor` will be the resulting `RaggedTensor.flat_values`. If + not specified, then it defaults to the key for this `RaggedFeature`. + partitions: (Optional.) A list of objects specifying the row-partitioning + tensors (from outermost to innermost). Each entry in this list must be + one of: + * `tf.io.RaggedFeature.RowSplits(key: string)` + * `tf.io.RaggedFeature.RowLengths(key: string)` + * `tf.io.RaggedFeature.RowStarts(key: string)` + * `tf.io.RaggedFeature.RowLimits(key: string)` + * `tf.io.RaggedFeature.ValueRowIds(key: string)` + * `tf.io.RaggedFeature.UniformRowLength(length: int)`. + Where `key` is a key for a `Feature` in the input `Example`, whose parsed + `Tensor` will be the resulting row-partitioning tensor. + row_splits_dtype: (Optional.) Data type for the row-partitioning tensor(s). + One of `int32` or `int64`. Defaults to `int32`. + validate: (Optional.) Boolean indicating whether or not to validate that + the input values form a valid RaggedTensor. Defaults to `False`. + """ + + # pylint: disable=invalid-name + RowSplits = collections.namedtuple("RowSplits", ["key"]) + RowLengths = collections.namedtuple("RowLengths", ["key"]) + RowStarts = collections.namedtuple("RowStarts", ["key"]) + RowLimits = collections.namedtuple("RowLimits", ["key"]) + ValueRowIds = collections.namedtuple("ValueRowIds", ["key"]) + UniformRowLength = collections.namedtuple("UniformRowLength", ["length"]) + # pylint: enable=invalid-name + + _PARTITION_TYPES = (RowSplits, RowLengths, RowStarts, RowLimits, ValueRowIds, + UniformRowLength) + + def __new__(cls, + dtype, + value_key=None, + partitions=(), + row_splits_dtype=dtypes.int32, + validate=False): + if value_key is not None: + if not isinstance(value_key, str): + raise ValueError( + f"Argument `value_key` must be a string; got {value_key}") + if not value_key: + raise ValueError("Argument `value_key` must not be empty") + dtype = dtypes.as_dtype(dtype) + if dtype not in (dtypes.int64, dtypes.float32, dtypes.string): + raise ValueError("Argument `dtype` must be int64, float32, or bytes; got " + f"{dtype!r}") + row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + if row_splits_dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("Argument `row_splits_dtype` must be int32 or int64; got" + f"{row_splits_dtype!r}") + if not isinstance(partitions, (list, tuple)): + raise TypeError("Argument `partitions` must be a list or tuple. Received" + f"partitions={partitions} of type " + f"{type(partitions).__name__}.") + for partition in partitions: + if not isinstance(partition, cls._PARTITION_TYPES): + raise TypeError("Argument `partitions` must be a list of partition " + f"objects {cls._PARTITION_TYPES}; got: {partition!r}") + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must be a bool; got {validate!r}") + return super(RaggedFeature, cls).__new__(cls, dtype, value_key, partitions, + row_splits_dtype, validate) + + +@tf_export("io.SparseFeature", v1=["io.SparseFeature", "SparseFeature"]) +class SparseFeature( + collections.namedtuple( + "SparseFeature", + ["index_key", "value_key", "dtype", "size", "already_sorted"])): + """Configuration for parsing a sparse input feature from an `Example`. + + Note, preferably use `VarLenFeature` (possibly in combination with a + `SequenceExample`) in order to parse out `SparseTensor`s instead of + `SparseFeature` due to its simplicity. + + Closely mimicking the `SparseTensor` that will be obtained by parsing an + `Example` with a `SparseFeature` config, a `SparseFeature` contains a + + * `value_key`: The name of key for a `Feature` in the `Example` whose parsed + `Tensor` will be the resulting `SparseTensor.values`. + + * `index_key`: A list of names - one for each dimension in the resulting + `SparseTensor` whose `indices[i][dim]` indicating the position of + the `i`-th value in the `dim` dimension will be equal to the `i`-th value in + the Feature with key named `index_key[dim]` in the `Example`. + + * `size`: A list of ints for the resulting `SparseTensor.dense_shape`. + + For example, we can represent the following 2D `SparseTensor` + + ```python + SparseTensor(indices=[[3, 1], [20, 0]], + values=[0.5, -1.0] + dense_shape=[100, 3]) + ``` + + with an `Example` input proto + + ```python + features { + feature { key: "val" value { float_list { value: [ 0.5, -1.0 ] } } } + feature { key: "ix0" value { int64_list { value: [ 3, 20 ] } } } + feature { key: "ix1" value { int64_list { value: [ 1, 0 ] } } } + } + ``` + + and `SparseFeature` config with 2 `index_key`s + + ```python + SparseFeature(index_key=["ix0", "ix1"], + value_key="val", + dtype=tf.float32, + size=[100, 3]) + ``` + + Fields: + index_key: A single string name or a list of string names of index features. + For each key the underlying feature's type must be `int64` and its length + must always match that of the `value_key` feature. + To represent `SparseTensor`s with a `dense_shape` of `rank` higher than 1 + a list of length `rank` should be used. + value_key: Name of value feature. The underlying feature's type must + be `dtype` and its length must always match that of all the `index_key`s' + features. + dtype: Data type of the `value_key` feature. + size: A Python int or list thereof specifying the dense shape. Should be a + list if and only if `index_key` is a list. In that case the list must be + equal to the length of `index_key`. Each for each entry `i` all values in + the `index_key`[i] feature must be in `[0, size[i])`. + already_sorted: A Python boolean to specify whether the values in + `value_key` are already sorted by their index position. If so skip + sorting. False by default (optional). + """ + + def __new__(cls, index_key, value_key, dtype, size, already_sorted=False): + return super(SparseFeature, cls).__new__( + cls, index_key, value_key, dtype, size, already_sorted) + + +@tf_export("io.FixedLenFeature", v1=["io.FixedLenFeature", "FixedLenFeature"]) +class FixedLenFeature(collections.namedtuple( + "FixedLenFeature", ["shape", "dtype", "default_value"])): + """Configuration for parsing a fixed-length input feature. + + To treat sparse input as dense, provide a `default_value`; otherwise, + the parse functions will fail on any examples missing this feature. + + Fields: + shape: Shape of input data. + dtype: Data type of input. + default_value: Value to be used if an example is missing this feature. It + must be compatible with `dtype` and of the specified `shape`. + """ + + def __new__(cls, shape, dtype, default_value=None): + return super(FixedLenFeature, cls).__new__( + cls, shape, dtype, default_value) + + +@tf_export("io.FixedLenSequenceFeature", + v1=["io.FixedLenSequenceFeature", "FixedLenSequenceFeature"]) +class FixedLenSequenceFeature(collections.namedtuple( + "FixedLenSequenceFeature", + ["shape", "dtype", "allow_missing", "default_value"])): + """Configuration for parsing a variable-length input feature into a `Tensor`. + + The resulting `Tensor` of parsing a single `SequenceExample` or `Example` has + a static `shape` of `[None] + shape` and the specified `dtype`. + The resulting `Tensor` of parsing a `batch_size` many `Example`s has + a static `shape` of `[batch_size, None] + shape` and the specified `dtype`. + The entries in the `batch` from different `Examples` will be padded with + `default_value` to the maximum length present in the `batch`. + + To treat a sparse input as dense, provide `allow_missing=True`; otherwise, + the parse functions will fail on any examples missing this feature. + + Fields: + shape: Shape of input data for dimension 2 and higher. First dimension is + of variable length `None`. + dtype: Data type of input. + allow_missing: Whether to allow this feature to be missing from a feature + list item. Is available only for parsing `SequenceExample` not for + parsing `Examples`. + default_value: Scalar value to be used to pad multiple `Example`s to their + maximum length. Irrelevant for parsing a single `Example` or + `SequenceExample`. Defaults to "" for dtype string and 0 otherwise + (optional). + """ + + def __new__(cls, shape, dtype, allow_missing=False, default_value=None): + return super(FixedLenSequenceFeature, cls).__new__( + cls, shape, dtype, allow_missing, default_value) + + +class _ParseOpParams: + """Raw parameters used by `gen_parsing_ops`. + + Attributes: + sparse_keys: A list of string keys in the examples' features. The results + for these keys will be returned as `SparseTensor` objects. + sparse_types: A list of `DTypes` of the same length as `sparse_keys`. Only + `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), and `tf.string` + (`BytesList`) are supported. + dense_keys: A list of string keys in the examples' features. The results for + these keys will be returned as `Tensor`s + dense_types: A list of DTypes of the same length as `dense_keys`. Only + `tf.float32` (`FloatList`), `tf.int64` (`Int64List`), and `tf.string` + (`BytesList`) are supported. + dense_defaults: A dict mapping string keys to `Tensor`s. The keys of the + dict must match the dense_keys of the feature. + dense_shapes: A list of tuples with the same length as `dense_keys`. The + shape of the data for each dense feature referenced by `dense_keys`. + Required for any input tensors identified by `dense_keys`. Must be either + fully defined, or may contain an unknown first dimension. An unknown first + dimension means the feature is treated as having a variable number of + blocks, and the output shape along this dimension is considered unknown at + graph build time. Padding is applied for minibatch elements smaller than + the maximum number of blocks for the given feature along this dimension. + ragged_keys: A list of string keys in the examples' features. The + results for these keys will be returned as `RaggedTensor` objects. + ragged_value_types: A list of `DTypes` of the same length as `ragged_keys`, + specifying the value type for each ragged feature. Must be one of: + `tf.float32`, `tf.int64`, `tf.string`. + ragged_split_types: A list of `DTypes` of the same length as `ragged_keys`, + specifying the row_splits type for each ragged feature. Must be one of: + `tf.int32`, `tf.int64`. + dense_shapes_as_proto: dense_shapes converted to TensorShapeProto. + dense_defaults_vec: A vector of `Tensor`s containing the default values, + corresponding 1:1 with `dense_keys`. + num_features: The total number of feature keys. + """ + + def __init__(self, + sparse_keys=None, + sparse_types=None, + dense_keys=None, + dense_types=None, + dense_defaults=None, + dense_shapes=None, + ragged_keys=None, + ragged_value_types=None, + ragged_split_types=None): + # Note: we use an OrderedDict for dense_defaults, to ensure consistent + # graph construction order for _e2e_test. + dense_defaults = ( + collections.OrderedDict() if dense_defaults is None else dense_defaults) + sparse_keys = [] if sparse_keys is None else sparse_keys + sparse_types = [] if sparse_types is None else sparse_types + dense_keys = [] if dense_keys is None else dense_keys + dense_types = [] if dense_types is None else dense_types + dense_shapes = ([[]] * + len(dense_keys) if dense_shapes is None else dense_shapes) + ragged_keys = [] if ragged_keys is None else ragged_keys + ragged_value_types = ([] + if ragged_value_types is None else ragged_value_types) + ragged_split_types = ([] + if ragged_split_types is None else ragged_split_types) + self.sparse_keys = sparse_keys + self.sparse_types = [dtypes.as_dtype(t) for t in sparse_types] + self.dense_keys = dense_keys + self.dense_types = [dtypes.as_dtype(t) for t in dense_types] + self.dense_shapes = [tensor_shape.as_shape(s) for s in dense_shapes] + self.dense_defaults = dense_defaults + self.ragged_keys = ragged_keys + self.ragged_value_types = [dtypes.as_dtype(t) for t in ragged_value_types] + self.ragged_split_types = [dtypes.as_dtype(t) for t in ragged_split_types] + self._validate() + + @classmethod + def from_features(cls, features, types): + """Builds _ParseOpParams for a given set of features and allowed types. + + Args: + features: A `dict` mapping feature keys to objects of a type in `types`. + types: Type of features to allow, among `FixedLenFeature`, + `VarLenFeature`, `SparseFeature`, and `FixedLenSequenceFeature`. + + Returns: + A `_ParseOpParams` containing the raw parameters for `gen_parsing_ops`. + + Raises: + ValueError: if `features` contains an item not in `types`, or an invalid + feature. + ValueError: if sparse and dense key sets intersect. + ValueError: if input lengths do not match up. + """ + params = cls() + if features: + # NOTE: We iterate over sorted keys to keep things deterministic. + for key in sorted(features.keys()): + feature = features[key] + if not isinstance(feature, tuple(types)): + raise ValueError( + f"Unsupported {type(feature).__name__} {feature} for key '{key}'") + params._add_feature(key, feature) # pylint: disable=protected-access + params._validate() # pylint: disable=protected-access + return params + + @property + def dense_shapes_as_proto(self): + return [shape.as_proto() for shape in self.dense_shapes] + + @property + def num_features(self): + return len(self.dense_keys) + len(self.sparse_keys) + len(self.ragged_keys) + + @property + def dense_defaults_vec(self): + return [ + self._make_dense_default(k, s, t) + for k, s, t in zip(self.dense_keys, self.dense_shapes, self.dense_types) + ] + + def _make_dense_default(self, key, shape, dtype): + """Construct the default value tensor for a specified dense feature. + + Args: + key: The key string identifying the dense feature. + shape: The dense feature's shape. + dtype: The dense feature's dtype. + + Returns: + A Tensor. + """ + default_value = self.dense_defaults.get(key) + if (shape.ndims is not None and shape.ndims > 0 and + shape.dims[0].value is None): + # Variable stride dense shape, the default value should be a + # scalar padding value. + if default_value is None: + default_value = ops.convert_to_tensor( + "" if dtype == dtypes.string else 0, dtype=dtype) + else: + # Reshape to a scalar to ensure user gets an error if they + # provide a tensor that's not intended to be a padding value + # (0 or 2+ elements). + key_name = "padding_" + re.sub("[^A-Za-z0-9_.\\-/]", "_", key) + default_value = ops.convert_to_tensor( + default_value, dtype=dtype, name=key_name) + default_value = array_ops.reshape(default_value, []) + else: + if default_value is None: + default_value = constant_op.constant([], dtype=dtype) + elif not isinstance(default_value, tensor.Tensor): + key_name = "key_" + re.sub("[^A-Za-z0-9_.\\-/]", "_", key) + default_value = ops.convert_to_tensor( + default_value, dtype=dtype, name=key_name) + default_value = array_ops.reshape(default_value, shape) + + return default_value + + def _add_feature(self, key, feature): + """Adds the specified feature to this ParseOpParams.""" + if isinstance(feature, VarLenFeature): + self._add_varlen_feature(key, feature) + elif isinstance(feature, SparseFeature): + self._add_sparse_feature(key, feature) + elif isinstance(feature, FixedLenFeature): + self._add_fixed_len_feature(key, feature) + elif isinstance(feature, FixedLenSequenceFeature): + self._add_fixed_len_sequence_feature(key, feature) + elif isinstance(feature, RaggedFeature): + self._add_ragged_feature(key, feature) + else: + raise ValueError(f"Invalid feature {key}:{feature}.") + + def _add_varlen_feature(self, key, feature): + """Adds a VarLenFeature.""" + if not feature.dtype: + raise ValueError( + f"Missing type for feature {key}. Received feature={feature}") + self._add_sparse_key(key, feature.dtype) + + def _add_sparse_key(self, key, dtype): + """Adds a sparse key & dtype, checking for duplicates.""" + if key in self.sparse_keys: + original_dtype = self.sparse_types[self.sparse_keys.index(key)] + if original_dtype != dtype: + raise ValueError( + f"Conflicting type {original_dtype} vs {dtype} for feature {key}.") + else: + self.sparse_keys.append(key) + self.sparse_types.append(dtype) + + def _add_sparse_feature(self, key, feature): + """Adds a SparseFeature.""" + + if not feature.index_key: + raise ValueError(f"Missing index_key for SparseFeature {feature}.") + if not feature.value_key: + raise ValueError(f"Missing value_key for SparseFeature {feature}.") + if not feature.dtype: + raise ValueError(f"Missing type for feature {key}. Received feature=" + f"{feature}.") + index_keys = feature.index_key + if isinstance(index_keys, str): + index_keys = [index_keys] + elif len(index_keys) > 1: + tf_logging.warning("SparseFeature is a complicated feature config " + "and should only be used after careful " + "consideration of VarLenFeature.") + for index_key in sorted(index_keys): + self._add_sparse_key(index_key, dtypes.int64) + self._add_sparse_key(feature.value_key, feature.dtype) + + def _add_fixed_len_feature(self, key, feature): + """Adds a FixedLenFeature.""" + if not feature.dtype: + raise ValueError(f"Missing type for feature {key}. Received feature=" + f"{feature}.") + if feature.shape is None: + raise ValueError(f"Missing shape for feature {key}. Received feature=" + f"{feature}.") + feature_tensor_shape = tensor_shape.as_shape(feature.shape) + if (feature.shape and feature_tensor_shape.ndims and + feature_tensor_shape.dims[0].value is None): + raise ValueError(f"First dimension of shape for feature {key} unknown. " + "Consider using FixedLenSequenceFeature. Received " + f"feature={feature}.") + if (feature.shape is not None and + not feature_tensor_shape.is_fully_defined()): + raise ValueError(f"All dimensions of shape for feature {key} need to be " + f"known but received {feature.shape!s}.") + self.dense_keys.append(key) + self.dense_shapes.append(tensor_shape.as_shape(feature.shape)) + self.dense_types.append(feature.dtype) + if feature.default_value is not None: + self.dense_defaults[key] = feature.default_value + + def _add_fixed_len_sequence_feature(self, key, feature): + """Adds a FixedLenSequenceFeature.""" + if not feature.dtype: + raise ValueError(f"Missing type for feature {key}. Received feature=" + f"{feature}.") + if feature.shape is None: + raise ValueError(f"Missing shape for feature {key}. Received feature=" + f"{feature}.") + self.dense_keys.append(key) + self.dense_shapes.append(tensor_shape.as_shape(feature.shape)) + self.dense_types.append(feature.dtype) + if feature.allow_missing: + self.dense_defaults[key] = None + if feature.default_value is not None: + self.dense_defaults[key] = feature.default_value + + def _add_ragged_key(self, key, value_type, split_type): + """Adds a ragged key & dtype, checking for duplicates.""" + if key in self.ragged_keys: + original_value_type = self.ragged_value_types[self.ragged_keys.index(key)] + original_split_type = self.ragged_split_types[self.ragged_keys.index(key)] + if original_value_type != value_type: + raise ValueError(f"Conflicting type {original_value_type} vs " + f"{value_type} for feature {key}.") + if original_split_type != split_type: + raise ValueError(f"Conflicting partition type {original_split_type} vs " + f"{split_type} for feature {key}.") + else: + self.ragged_keys.append(key) + self.ragged_value_types.append(value_type) + self.ragged_split_types.append(split_type) + + def _add_ragged_feature(self, key, feature): + """Adds a RaggedFeature.""" + value_key = key if feature.value_key is None else feature.value_key + self._add_ragged_key(value_key, feature.dtype, feature.row_splits_dtype) + for partition in feature.partitions: + if not isinstance(partition, RaggedFeature.UniformRowLength): + self._add_ragged_key(partition.key, dtypes.int64, + feature.row_splits_dtype) + + def _validate(self): + """Validates the features in this ParseOpParams.""" + if len(self.dense_shapes) != len(self.dense_keys): + raise ValueError("len(self.dense_shapes) != len(self.dense_keys): " + f"{len(self.dense_shapes)} vs {len(self.dense_keys)}.") + if len(self.dense_types) != len(self.dense_keys): + raise ValueError("len(self.dense_types) != len(self.dense_keys): " + f"{len(self.dense_types)} vs {len(self.dense_keys)}.") + if len(self.sparse_types) != len(self.sparse_keys): + raise ValueError("len(self.sparse_types) != len(self.sparse_keys): " + f"{len(self.sparse_types)} vs {len(self.sparse_keys)}.") + if len(self.ragged_value_types) != len(self.ragged_keys): + raise ValueError( + "len(self.ragged_value_types) != len(self.ragged_keys): " + f"{len(self.ragged_value_types)} vs {len(self.ragged_keys)}.") + if len(self.ragged_split_types) != len(self.ragged_keys): + raise ValueError( + "len(self.ragged_split_types) != len(self.ragged_keys): " + f"{len(self.ragged_split_types)} vs {len(self.ragged_keys)}.") + + dense_key_set = set(self.dense_keys) + sparse_key_set = set(self.sparse_keys) + ragged_key_set = set(self.ragged_keys) + if not dense_key_set.isdisjoint(sparse_key_set): + raise ValueError( + "Dense and sparse keys must not intersect; dense_keys: " + f"{self.dense_keys}, sparse_keys: {self.sparse_keys}, intersection: " + f"{dense_key_set.intersection(sparse_key_set)}") + if not dense_key_set.isdisjoint(ragged_key_set): + raise ValueError( + "Dense and ragged keys must not intersect; dense_keys: ", + f"{self.dense_keys}, ragged_keys: {self.ragged_keys}, intersection: " + f"{dense_key_set.intersection(ragged_key_set)}") + if not ragged_key_set.isdisjoint(sparse_key_set): + raise ValueError( + "Ragged and sparse keys must not intersect; ragged_keys: " + f"{self.ragged_keys}, sparse_keys: {self.sparse_keys}, intersection: " + f"{ragged_key_set.intersection(sparse_key_set)}") + + +def _construct_tensors_for_composite_features(features, tensor_dict): + """Creates tensors for SparseFeatures and RaggedFeatures. + + Constructs new dict based on `tensor_dict`. + + For each key in `features` whose value is a `SparseFeature`: + + * Looks up that SparseFeature's value_key and index_keys in tensor_dict. + * Uses those tensors to construct a single SparseTensor. + * Stores that SparseTensor in the output dict under the same key. + + For each key in `features` whose value is a `RaggedFeature`: + + * Looks up that RaggedFeature's value_key and partition keys in tensor_dict. + * Uses those tensors to construct a single RaggedTensor. + * Stores that RaggedTensor in the output dict under the same key. + + For any other key in `features`: + + * Copies that key and its value from tensor_dict to the output dictionary. + + Args: + features: A `dict` mapping feature keys to `SparseFeature` or + `RaggedFeature` values. Values of other types will be ignored. + tensor_dict: A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and + `RaggedTensor` values. Expected to contain keys of the `SparseFeature`s' + `index_key`s and `value_key`s and mapping them to `SparseTensor`s. + + Returns: + A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and + `RaggedTensor` values. Similar to `tensor_dict` except each `SparseFeature` + in `features` results in a single `SparseTensor`; and each `RaggedFeature` + in `features` results in a single `RaggedTensor`. + """ + tensor_dict = dict(tensor_dict) # Do not modify argument passed in. + updates = {} + for key in sorted(features.keys()): + feature = features[key] + if isinstance(feature, SparseFeature): + # Construct SparseTensors for SparseFeatures + if isinstance(feature.index_key, str): + sp_ids = tensor_dict[feature.index_key] + else: + sp_ids = [tensor_dict[index_key] for index_key in feature.index_key] + sp_values = tensor_dict[feature.value_key] + updates[key] = sparse_ops.sparse_merge( + sp_ids, + sp_values, + vocab_size=feature.size, + already_sorted=feature.already_sorted) + elif isinstance(feature, RaggedFeature): + # Construct RaggedTensors for RaggedFeatures. + value_key = key if feature.value_key is None else feature.value_key + rt = tensor_dict[value_key] + if isinstance(rt, ragged_tensor.RaggedTensor): + # We processed a batch of tf.Example or tf.SequenceExample, or single + # tf.SequenceExample. + if rt.ragged_rank > 1: + # We're processing a batch of SequenceExample, and we effectively have + # two batch dimensions. Cllapse those batch dimensions here, and + # restore them below (using outer_splits). + outer_splits = rt.row_splits + rt = rt.values + else: + outer_splits = None + for partition in reversed(feature.partitions): + rt = _add_batched_ragged_partition(rt, partition, tensor_dict, + key, feature.validate, + outer_splits) + if outer_splits is not None: + rt = ragged_tensor.RaggedTensor.from_row_splits( + rt, outer_splits, validate=feature.validate) + else: + # We processed a single tf.Example. + for partition in reversed(feature.partitions): + rt = _add_ragged_partition(rt, partition, tensor_dict, + feature.row_splits_dtype, feature.validate) + updates[key] = rt + + # Process updates after all composite tensors have been constructed (in case + # multiple features use the same value_key, and one uses that key as its + # feature key). + tensor_dict.update(updates) + + # Remove tensors from dictionary that were only used to construct + # tensors for SparseFeature or RaggedTensor. + for key in set(tensor_dict) - set(features): + del tensor_dict[key] + return tensor_dict + + +def _add_ragged_partition(values, partition, tensor_dict, row_splits_dtype, + validate): + """Creates a RaggedTensor from a values tensor and a partition tensor. + + Args: + values: The values tensor for the new RaggedTensor. + partition: The partition configuration object. Specifies the key that + should be used to look up the partition tensor (unless partition is a + RaggedFeature.UniformRowLength, in which case there is no partition + tensor). + tensor_dict: The dictionary mapping keys to tensors. + row_splits_dtype: The dtype for the partition tensor. + validate: Whether to validate that the values form a valid RaggedTensor. + + Returns: + A new RaggedTensor formed from the values and partition tensors. + """ + if isinstance(partition, RaggedFeature.UniformRowLength): + if isinstance(values, ragged_tensor.RaggedTensor): + length = ops.convert_to_tensor(partition.length, dtype=row_splits_dtype) + return ragged_tensor.RaggedTensor.from_uniform_row_length( + values, length, validate=validate) + else: + return array_ops.reshape(values, array_ops.concat( + [[-1, partition.length], array_ops.shape(values)[1:]], axis=0)) + else: + partition_t = math_ops.cast(tensor_dict[partition.key], row_splits_dtype) + if isinstance(partition, RaggedFeature.RowSplits): + return ragged_tensor.RaggedTensor.from_row_splits( + values, partition_t, validate=validate) + elif isinstance(partition, RaggedFeature.RowLengths): + return ragged_tensor.RaggedTensor.from_row_lengths( + values, partition_t, validate=validate) + elif isinstance(partition, RaggedFeature.RowStarts): + return ragged_tensor.RaggedTensor.from_row_starts( + values, partition_t, validate=validate) + elif isinstance(partition, RaggedFeature.RowLimits): + return ragged_tensor.RaggedTensor.from_row_limits( + values, partition_t, validate=validate) + elif isinstance(partition, RaggedFeature.ValueRowIds): + return ragged_tensor.RaggedTensor.from_value_rowids( + values, partition_t, validate=validate) + raise ValueError(f"Unhandled partition type {partition!r}") + + +def _add_batched_ragged_partition(rt, partition, tensor_dict, feature_key, + validate, outer_splits=None): + """Adds a batched ragged partition tensor to a batched ragged tensor. + + Args: + rt: A RaggedTensor with shape [batch_size, ...]. + partition: The partition configuration object. Specifies the key that + should be used to look up the partition tensor (unless partition is a + RaggedFeature.UniformRowLength, in which case there is no partition + tensor). The specified tensor must have shape [batch_size, ...]. + tensor_dict: The dictionary mapping keys to tensors. + feature_key: The name of the feature being parsed (for error messages). + validate: Whether to validate that the values form a valid RaggedTensor. + outer_splits: If not None, then we have two batch dimensions, and this + is the row-splits for the collapsed batch dimension. Every partition + tensor must have an outer row_splits that matches this value. + + Returns: + A new RaggedTensor where each batch item `rt[i]` has been partitioned + using the `partition_t[i]`. + """ + if isinstance(partition, RaggedFeature.UniformRowLength): + if rt.ragged_rank > 1: + length = ops.convert_to_tensor(partition.length, rt.row_splits.dtype) + return ragged_tensor.RaggedTensor.from_row_splits( + ragged_tensor.RaggedTensor.from_uniform_row_length( + rt.values, length, validate=validate), + rt.row_splits // length, + validate=validate) + else: + reshaped_vals = array_ops.reshape(rt.values, array_ops.concat( + [[-1, partition.length], array_ops.shape(rt.values)[1:]], axis=0)) + return ragged_tensor.RaggedTensor.from_row_splits( + reshaped_vals, rt.row_splits // partition.length, validate=validate) + + partition_t = tensor_dict[partition.key] + if partition_t.values.dtype != rt.row_splits.dtype: + partition_t = math_ops.cast(partition_t, rt.row_splits.dtype) + + checks = [] + if outer_splits is not None: + if validate: + checks.append(check_ops.assert_equal( + outer_splits, partition_t.row_splits, + message="Feature %s: values and partitions are not aligned" + % feature_key)) + partition_t = partition_t.values + + with ops.control_dependencies(checks): + if isinstance(partition, (RaggedFeature.RowSplits, + RaggedFeature.RowLimits)): + if isinstance(partition, RaggedFeature.RowSplits): + partition_t = partition_t[:, 1:] + adjusted_limits = partition_t.values + array_ops.repeat( + rt.row_starts(), partition_t.row_lengths()) + return partition_t.with_values( + ragged_tensor.RaggedTensor.from_row_limits( + rt.values, adjusted_limits, validate=validate)) + elif isinstance(partition, RaggedFeature.RowStarts): + adjusted_starts = partition_t.values + array_ops.repeat( + rt.row_starts(), partition_t.row_lengths()) + return partition_t.with_values( + ragged_tensor.RaggedTensor.from_row_starts( + rt.values, adjusted_starts, validate=validate)) + elif isinstance(partition, RaggedFeature.RowLengths): + return partition_t.with_values( + ragged_tensor.RaggedTensor.from_row_lengths( + rt.values, partition_t.values, validate=validate)) + elif isinstance(partition, RaggedFeature.ValueRowIds): + nrows = math_ops.maximum( # number of rows in each batch item + ragged_math_ops.reduce_max(partition_t + 1, axis=1), 0) + adjusted_rowids = partition_t.values + array_ops.repeat( + math_ops.cumsum(nrows, exclusive=True), partition_t.row_lengths()) + return ragged_tensor.RaggedTensor.from_row_lengths( + ragged_tensor.RaggedTensor.from_value_rowids( + rt.values, adjusted_rowids, validate=validate), + nrows, + validate=validate) + + raise ValueError(f"Unhandled partition type {partition!r}") + + +def _build_ragged_tensors(serialized_shape, + ragged_values, + ragged_row_splits, + ragged_inner_splits=None): + """Builds RaggedTensors from the outputs of a parse op.""" + if ragged_inner_splits is not None: + ragged_values = [ + ragged_tensor.RaggedTensor.from_row_splits(val, split, validate=False) + for (val, split) in zip(ragged_values, ragged_inner_splits) + ] + if serialized_shape.ndims == 0: + return ragged_values + else: + return [ + ragged_tensor.RaggedTensor.from_row_splits(val, split, validate=False) + for (val, split) in zip(ragged_values, ragged_row_splits) + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..66b2ea3576c18f3cf1b909e26151283f59f273b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/parsing_ops.py @@ -0,0 +1,1238 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Parsing Ops.""" +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_parsing_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import parsing_config +# go/tf-wildcard-import +# pylint: disable=wildcard-import,undefined-variable +from tensorflow.python.ops.gen_parsing_ops import * +# pylint: enable=wildcard-import,undefined-variable +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +ops.NotDifferentiable("DecodeRaw") +ops.NotDifferentiable("DecodePaddedRaw") +ops.NotDifferentiable("ParseTensor") +ops.NotDifferentiable("SerializeTensor") +ops.NotDifferentiable("StringToNumber") + + +VarLenFeature = parsing_config.VarLenFeature +RaggedFeature = parsing_config.RaggedFeature +SparseFeature = parsing_config.SparseFeature +FixedLenFeature = parsing_config.FixedLenFeature +FixedLenSequenceFeature = parsing_config.FixedLenSequenceFeature +# pylint: disable=protected-access +_ParseOpParams = parsing_config._ParseOpParams +_construct_tensors_for_composite_features = ( + parsing_config._construct_tensors_for_composite_features) +# pylint: enable=protected-access + + +# TODO(b/122887740) Switch files that use this private symbol to use new name. +_construct_sparse_tensors_for_sparse_features = \ + _construct_tensors_for_composite_features + + +def _prepend_none_dimension(features): + """Returns a copy of features with adjusted FixedLenSequenceFeature shapes.""" + if features: + modified_features = dict(features) # Create a copy to modify + for key, feature in features.items(): + if isinstance(feature, FixedLenSequenceFeature): + if not feature.allow_missing: + raise ValueError("Unsupported: FixedLenSequenceFeature requires " + "allow_missing to be True.") + modified_features[key] = FixedLenSequenceFeature( + [None] + list(feature.shape), + feature.dtype, + feature.allow_missing, + feature.default_value) + return modified_features + else: + return features + + +@tf_export("io.parse_example", v1=[]) +@dispatch.add_dispatch_support +def parse_example_v2(serialized, features, example_names=None, name=None): + # pylint: disable=line-too-long + """Parses `Example` protos into a `dict` of tensors. + + Parses a number of serialized [`Example`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto) + protos given in `serialized`. We refer to `serialized` as a batch with + `batch_size` many entries of individual `Example` protos. + + `example_names` may contain descriptive names for the corresponding serialized + protos. These may be useful for debugging purposes, but they have no effect on + the output. If not `None`, `example_names` must be the same length as + `serialized`. + + This op parses serialized examples into a dictionary mapping keys to `Tensor` + `SparseTensor`, and `RaggedTensor` objects. `features` is a Mapping from keys + to `VarLenFeature`, `SparseFeature`, `RaggedFeature`, and `FixedLenFeature` + objects. Each `VarLenFeature` and `SparseFeature` is mapped to a + `SparseTensor`; each `FixedLenFeature` is mapped to a `Tensor`; and each + `RaggedFeature` is mapped to a `RaggedTensor`. + + Each `VarLenFeature` maps to a `SparseTensor` of the specified type + representing a ragged matrix. Its indices are `[batch, index]` where `batch` + identifies the example in `serialized`, and `index` is the value's index in + the list of values associated with that feature and example. + + Each `SparseFeature` maps to a `SparseTensor` of the specified type + representing a Tensor of `dense_shape` `[batch_size] + SparseFeature.size`. + Its `values` come from the feature in the examples with key `value_key`. + A `values[i]` comes from a position `k` in the feature of an example at batch + entry `batch`. This positional information is recorded in `indices[i]` as + `[batch, index_0, index_1, ...]` where `index_j` is the `k-th` value of + the feature in the example at with key `SparseFeature.index_key[j]`. + In other words, we split the indices (except the first index indicating the + batch entry) of a `SparseTensor` by dimension into different features of the + `Example`. Due to its complexity a `VarLenFeature` should be preferred over a + `SparseFeature` whenever possible. + + Each `FixedLenFeature` `df` maps to a `Tensor` of the specified type (or + `tf.float32` if not specified) and shape `(serialized.size(),) + df.shape`. + + `FixedLenFeature` entries with a `default_value` are optional. With no default + value, we will fail if that `Feature` is missing from any example in + `serialized`. + + Each `FixedLenSequenceFeature` `df` maps to a `Tensor` of the specified type + (or `tf.float32` if not specified) and shape + `(serialized.size(), None) + df.shape`. + All examples in `serialized` will be padded with `default_value` along the + second dimension. + + Each `RaggedFeature` maps to a `RaggedTensor` of the specified type. It + is formed by stacking the `RaggedTensor` for each example, where the + `RaggedTensor` for each individual example is constructed using the tensors + specified by `RaggedTensor.values_key` and `RaggedTensor.partition`. See + the `tf.io.RaggedFeature` documentation for details and examples. + + Examples: + + For example, if one expects a `tf.float32` `VarLenFeature` `ft` and three + serialized `Example`s are provided: + + ``` + serialized = [ + features + { feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } }, + features + { feature []}, + features + { feature { key: "ft" value { float_list { value: [3.0] } } } + ] + ``` + + then the output will look like: + + ```python + {"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]], + values=[1.0, 2.0, 3.0], + dense_shape=(3, 2)) } + ``` + + If instead a `FixedLenSequenceFeature` with `default_value = -1.0` and + `shape=[]` is used then the output will look like: + + ```python + {"ft": [[1.0, 2.0], [3.0, -1.0]]} + ``` + + Given two `Example` input protos in `serialized`: + + ``` + [ + features { + feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } } + feature { key: "gps" value { float_list { value: [] } } } + }, + features { + feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } } + feature { key: "dank" value { int64_list { value: [ 42 ] } } } + feature { key: "gps" value { } } + } + ] + ``` + + And arguments + + ``` + example_names: ["input0", "input1"], + features: { + "kw": VarLenFeature(tf.string), + "dank": VarLenFeature(tf.int64), + "gps": VarLenFeature(tf.float32), + } + ``` + + Then the output is a dictionary: + + ```python + { + "kw": SparseTensor( + indices=[[0, 0], [0, 1], [1, 0]], + values=["knit", "big", "emmy"] + dense_shape=[2, 2]), + "dank": SparseTensor( + indices=[[1, 0]], + values=[42], + dense_shape=[2, 1]), + "gps": SparseTensor( + indices=[], + values=[], + dense_shape=[2, 0]), + } + ``` + + For dense results in two serialized `Example`s: + + ``` + [ + features { + feature { key: "age" value { int64_list { value: [ 0 ] } } } + feature { key: "gender" value { bytes_list { value: [ "f" ] } } } + }, + features { + feature { key: "age" value { int64_list { value: [] } } } + feature { key: "gender" value { bytes_list { value: [ "f" ] } } } + } + ] + ``` + + We can use arguments: + + ``` + example_names: ["input0", "input1"], + features: { + "age": FixedLenFeature([], dtype=tf.int64, default_value=-1), + "gender": FixedLenFeature([], dtype=tf.string), + } + ``` + + And the expected output is: + + ```python + { + "age": [[0], [-1]], + "gender": [["f"], ["f"]], + } + ``` + + An alternative to `VarLenFeature` to obtain a `SparseTensor` is + `SparseFeature`. For example, given two `Example` input protos in + `serialized`: + + ``` + [ + features { + feature { key: "val" value { float_list { value: [ 0.5, -1.0 ] } } } + feature { key: "ix" value { int64_list { value: [ 3, 20 ] } } } + }, + features { + feature { key: "val" value { float_list { value: [ 0.0 ] } } } + feature { key: "ix" value { int64_list { value: [ 42 ] } } } + } + ] + ``` + + And arguments + + ``` + example_names: ["input0", "input1"], + features: { + "sparse": SparseFeature( + index_key="ix", value_key="val", dtype=tf.float32, size=100), + } + ``` + + Then the output is a dictionary: + + ```python + { + "sparse": SparseTensor( + indices=[[0, 3], [0, 20], [1, 42]], + values=[0.5, -1.0, 0.0] + dense_shape=[2, 100]), + } + ``` + + See the `tf.io.RaggedFeature` documentation for examples showing how + `RaggedFeature` can be used to obtain `RaggedTensor`s. + + Args: + serialized: A vector (1-D Tensor) of strings, a batch of binary + serialized `Example` protos. + features: A mapping of feature keys to `FixedLenFeature`, + `VarLenFeature`, `SparseFeature`, and `RaggedFeature` values. + example_names: A vector (1-D Tensor) of strings (optional), the names of + the serialized protos in the batch. + name: A name for this operation (optional). + + Returns: + A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and + `RaggedTensor` values. + + Raises: + ValueError: if any feature is invalid. + """ + if not features: + raise ValueError("Argument `features` cannot be None.") + features = _prepend_none_dimension(features) + params = _ParseOpParams.from_features(features, [ + VarLenFeature, SparseFeature, FixedLenFeature, FixedLenSequenceFeature, + RaggedFeature + ]) + + outputs = _parse_example_raw(serialized, example_names, params, name=name) + return _construct_tensors_for_composite_features(features, outputs) + + +@tf_export(v1=["io.parse_example", "parse_example"]) +@dispatch.add_dispatch_support +def parse_example(serialized, features, name=None, example_names=None): + return parse_example_v2(serialized, features, example_names, name) + + +parse_example.__doc__ = parse_example_v2.__doc__ + + +def _parse_example_raw(serialized, names, params, name): + """Parses `Example` protos. + + Args: + serialized: A vector (1-D Tensor) of strings, a batch of binary + serialized `Example` protos. + names: A vector (1-D Tensor) of strings (optional), the names of + the serialized protos. + params: A `ParseOpParams` containing the parameters for the parse op. + name: A name for this operation (optional). + + Returns: + A `dict` mapping keys to `Tensor`s and `SparseTensor`s and `RaggedTensor`s. + + """ + if params.num_features == 0: + raise ValueError("Must provide at least one feature key.") + with ops.name_scope(name, "ParseExample", [serialized, names]): + names = [] if names is None else names + serialized = ops.convert_to_tensor(serialized, name="serialized") + if params.ragged_keys and serialized.shape.ndims is None: + raise ValueError("serialized must have statically-known rank to " + "parse ragged features.") + outputs = gen_parsing_ops.parse_example_v2( + serialized=serialized, + names=names, + sparse_keys=params.sparse_keys, + dense_keys=params.dense_keys, + ragged_keys=params.ragged_keys, + dense_defaults=params.dense_defaults_vec, + num_sparse=len(params.sparse_keys), + sparse_types=params.sparse_types, + ragged_value_types=params.ragged_value_types, + ragged_split_types=params.ragged_split_types, + dense_shapes=params.dense_shapes_as_proto, + name=name) + (sparse_indices, sparse_values, sparse_shapes, dense_values, + ragged_values, ragged_row_splits) = outputs + # pylint: disable=protected-access + ragged_tensors = parsing_config._build_ragged_tensors( + serialized.shape, ragged_values, ragged_row_splits) + + sparse_tensors = [ + sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape) + in zip(sparse_indices, sparse_values, sparse_shapes)] + + return dict( + zip(params.sparse_keys + params.dense_keys + params.ragged_keys, + sparse_tensors + dense_values + ragged_tensors)) + + +@tf_export(v1=["io.parse_single_example", "parse_single_example"]) +@dispatch.add_dispatch_support +def parse_single_example(serialized, features, name=None, example_names=None): + """Parses a single `Example` proto. + + Similar to `parse_example`, except: + + For dense tensors, the returned `Tensor` is identical to the output of + `parse_example`, except there is no batch dimension, the output shape is the + same as the shape given in `dense_shape`. + + For `SparseTensor`s, the first (batch) column of the indices matrix is removed + (the indices matrix is a column vector), the values vector is unchanged, and + the first (`batch_size`) entry of the shape vector is removed (it is now a + single element vector). + + One might see performance advantages by batching `Example` protos with + `parse_example` instead of using this function directly. + + Args: + serialized: A scalar string Tensor, a single serialized Example. + features: A mapping of feature keys to `FixedLenFeature` or + `VarLenFeature` values. + name: A name for this operation (optional). + example_names: (Optional) A scalar string Tensor, the associated name. + + Returns: + A `dict` mapping feature keys to `Tensor` and `SparseTensor` values. + + Raises: + ValueError: if any feature is invalid. + """ + return parse_single_example_v2(serialized, features, example_names, name) + + +@tf_export("io.parse_single_example", v1=[]) +@dispatch.add_dispatch_support +def parse_single_example_v2( + serialized, features, example_names=None, name=None + ): + """Parses a single `Example` proto. + + Similar to `parse_example`, except: + + For dense tensors, the returned `Tensor` is identical to the output of + `parse_example`, except there is no batch dimension, the output shape is the + same as the shape given in `dense_shape`. + + For `SparseTensor`s, the first (batch) column of the indices matrix is removed + (the indices matrix is a column vector), the values vector is unchanged, and + the first (`batch_size`) entry of the shape vector is removed (it is now a + single element vector). + + One might see performance advantages by batching `Example` protos with + `parse_example` instead of using this function directly. + + Args: + serialized: A scalar string Tensor, a single serialized Example. + features: A mapping of feature keys to `FixedLenFeature` or + `VarLenFeature` values. + example_names: (Optional) A scalar string Tensor, the associated name. + name: A name for this operation (optional). + + Returns: + A `dict` mapping feature keys to `Tensor` and `SparseTensor` values. + + Raises: + ValueError: if any feature is invalid. + """ + if not features: + raise ValueError("Invalid argument: features cannot be None.") + with ops.name_scope(name, "ParseSingleExample", [serialized, example_names]): + serialized = ops.convert_to_tensor(serialized, name="serialized") + serialized = _assert_scalar(serialized, "serialized") + return parse_example_v2(serialized, features, example_names, name) + + +@tf_export("io.parse_sequence_example") +@dispatch.add_dispatch_support +def parse_sequence_example(serialized, + context_features=None, + sequence_features=None, + example_names=None, + name=None): + # pylint: disable=line-too-long + """Parses a batch of `SequenceExample` protos. + + Parses a vector of serialized + [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto) + protos given in `serialized`. + + This op parses serialized sequence examples into a tuple of dictionaries, + each mapping keys to `Tensor` and `SparseTensor` objects. + The first dictionary contains mappings for keys appearing in + `context_features`, and the second dictionary contains mappings for keys + appearing in `sequence_features`. + + At least one of `context_features` and `sequence_features` must be provided + and non-empty. + + The `context_features` keys are associated with a `SequenceExample` as a + whole, independent of time / frame. In contrast, the `sequence_features` keys + provide a way to access variable-length data within the `FeatureList` section + of the `SequenceExample` proto. While the shapes of `context_features` values + are fixed with respect to frame, the frame dimension (the first dimension) + of `sequence_features` values may vary between `SequenceExample` protos, + and even between `feature_list` keys within the same `SequenceExample`. + + `context_features` contains `VarLenFeature`, `RaggedFeature`, and + `FixedLenFeature` objects. Each `VarLenFeature` is mapped to a + `SparseTensor`; each `RaggedFeature` is mapped to a `RaggedTensor`; and each + `FixedLenFeature` is mapped to a `Tensor`, of the specified type, shape, and + default value. + + `sequence_features` contains `VarLenFeature`, `RaggedFeature`, and + `FixedLenSequenceFeature` objects. Each `VarLenFeature` is mapped to a + `SparseTensor`; each `RaggedFeature` is mapped to a `RaggedTensor`; and + each `FixedLenSequenceFeature` is mapped to a `Tensor`, each of the specified + type. The shape will be `(B,T,) + df.dense_shape` for + `FixedLenSequenceFeature` `df`, where `B` is the batch size, and `T` is the + length of the associated `FeatureList` in the `SequenceExample`. For instance, + `FixedLenSequenceFeature([])` yields a scalar 2-D `Tensor` of static shape + `[None, None]` and dynamic shape `[B, T]`, while + `FixedLenSequenceFeature([k])` (for `int k >= 1`) yields a 3-D matrix `Tensor` + of static shape `[None, None, k]` and dynamic shape `[B, T, k]`. + + Like the input, the resulting output tensors have a batch dimension. This + means that the original per-example shapes of `VarLenFeature`s and + `FixedLenSequenceFeature`s can be lost. To handle that situation, this op also + provides dicts of shape tensors as part of the output. There is one dict for + the context features, and one for the feature_list features. Context features + of type `FixedLenFeature`s will not be present, since their shapes are already + known by the caller. In situations where the input `FixedLenSequenceFeature`s + are of different sequence lengths across examples, the shorter examples will + be padded with default datatype values: 0 for numeric types, and the empty + string for string types. + + Each `SparseTensor` corresponding to `sequence_features` represents a ragged + vector. Its indices are `[time, index]`, where `time` is the `FeatureList` + entry and `index` is the value's index in the list of values associated with + that time. + + `FixedLenFeature` entries with a `default_value` and `FixedLenSequenceFeature` + entries with `allow_missing=True` are optional; otherwise, we will fail if + that `Feature` or `FeatureList` is missing from any example in `serialized`. + + `example_name` may contain a descriptive name for the corresponding serialized + proto. This may be useful for debugging purposes, but it has no effect on the + output. If not `None`, `example_name` must be a scalar. + + Args: + serialized: A vector (1-D Tensor) of type string containing binary + serialized `SequenceExample` protos. + context_features: A mapping of feature keys to `FixedLenFeature` or + `VarLenFeature` or `RaggedFeature` values. These features are associated + with a `SequenceExample` as a whole. + sequence_features: A mapping of feature keys to + `FixedLenSequenceFeature` or `VarLenFeature` or `RaggedFeature` values. + These features are associated with data within the `FeatureList` section + of the `SequenceExample` proto. + example_names: A vector (1-D Tensor) of strings (optional), the name of the + serialized protos. + name: A name for this operation (optional). + + Returns: + A tuple of three `dict`s, each mapping keys to `Tensor`s, + `SparseTensor`s, and `RaggedTensor`. The first dict contains the context + key/values, the second dict contains the feature_list key/values, and the + final dict contains the lengths of any dense feature_list features. + + Raises: + ValueError: if any feature is invalid. + """ + if not (context_features or sequence_features): + raise ValueError("Both `context_features` and `sequence_features` argument " + "are None, but at least one should have values.") + context_params = _ParseOpParams.from_features( + context_features, [VarLenFeature, FixedLenFeature, RaggedFeature]) + feature_list_params = _ParseOpParams.from_features( + sequence_features, + [VarLenFeature, FixedLenSequenceFeature, RaggedFeature]) + + with ops.name_scope(name, "ParseSequenceExample", + [serialized, example_names]): + outputs = _parse_sequence_example_raw(serialized, example_names, + context_params, feature_list_params, + name) + context_output, feature_list_output, feature_list_lengths = outputs + + if context_params.ragged_keys: + context_output = _construct_tensors_for_composite_features( + context_features, context_output) + if feature_list_params.ragged_keys: + feature_list_output = _construct_tensors_for_composite_features( + sequence_features, feature_list_output) + + return context_output, feature_list_output, feature_list_lengths + + +def _parse_sequence_example_raw(serialized, + debug_name, + context, + feature_list, + name=None): + """Parses a vector of `SequenceExample` protos. + + Args: + serialized: A vector (1-D Tensor) of type string, containing binary + serialized `SequenceExample` protos. + debug_name: A vector (1-D Tensor) of strings (optional), the names of the + serialized protos. + context: A `ParseOpParams` containing the parameters for the parse + op for the context features. + feature_list: A `ParseOpParams` containing the parameters for the + parse op for the feature_list features. + name: A name for this operation (optional). + + Returns: + A tuple of three `dict`s, each mapping keys to `Tensor`s, `SparseTensor`s, + and `RaggedTensor`s. The first dict contains the context key/values, the + second dict contains the feature_list key/values, and the final dict + contains the lengths of any dense feature_list features. + + Raises: + TypeError: if feature_list.dense_defaults is not either None or a dict. + """ + if context.num_features + feature_list.num_features == 0: + raise ValueError("Must provide at least one feature key.") + with ops.name_scope(name, "ParseSequenceExample", [serialized]): + debug_name = [] if debug_name is None else debug_name + + # Internal + feature_list_dense_missing_assumed_empty = [] + for k, v in feature_list.dense_defaults.items(): + if v is not None: + raise ValueError("Value feature_list.dense_defaults[%s] must be None" % + k) + feature_list_dense_missing_assumed_empty.append(k) + + has_ragged = context.ragged_keys or feature_list.ragged_keys + serialized = ops.convert_to_tensor(serialized, name="serialized") + if has_ragged and serialized.shape.ndims is None: + raise ValueError("serialized must have statically-known rank to " + "parse ragged features.") + feature_list_dense_missing_assumed_empty_vector = [ + key in feature_list_dense_missing_assumed_empty + for key in feature_list.dense_keys + ] + outputs = gen_parsing_ops.parse_sequence_example_v2( + # Inputs + serialized=serialized, + debug_name=debug_name, + context_sparse_keys=context.sparse_keys, + context_dense_keys=context.dense_keys, + context_ragged_keys=context.ragged_keys, + feature_list_sparse_keys=feature_list.sparse_keys, + feature_list_dense_keys=feature_list.dense_keys, + feature_list_ragged_keys=feature_list.ragged_keys, + feature_list_dense_missing_assumed_empty=( + feature_list_dense_missing_assumed_empty_vector), + context_dense_defaults=context.dense_defaults_vec, + # Attrs + Ncontext_sparse=len(context.sparse_keys), + Nfeature_list_sparse=len(feature_list.sparse_keys), + Nfeature_list_dense=len(feature_list.dense_keys), + context_sparse_types=context.sparse_types, + context_ragged_value_types=context.ragged_value_types, + context_ragged_split_types=context.ragged_split_types, + feature_list_dense_types=feature_list.dense_types, + feature_list_sparse_types=feature_list.sparse_types, + feature_list_ragged_value_types=feature_list.ragged_value_types, + feature_list_ragged_split_types=feature_list.ragged_split_types, + context_dense_shapes=context.dense_shapes_as_proto, + feature_list_dense_shapes=feature_list.dense_shapes, + name=name) + (context_sparse_indices, context_sparse_values, context_sparse_shapes, + context_dense_values, context_ragged_values, context_ragged_row_splits, + feature_list_sparse_indices, feature_list_sparse_values, + feature_list_sparse_shapes, feature_list_dense_values, + feature_list_dense_lengths, feature_list_ragged_values, + feature_list_ragged_outer_splits, + feature_list_ragged_inner_splits) = outputs + # pylint: disable=protected-access + context_ragged_tensors = parsing_config._build_ragged_tensors( + serialized.shape, context_ragged_values, context_ragged_row_splits) + feature_list_ragged_tensors = parsing_config._build_ragged_tensors( + serialized.shape, feature_list_ragged_values, + feature_list_ragged_outer_splits, feature_list_ragged_inner_splits) + + # pylint: disable=g-complex-comprehension + context_sparse_tensors = [ + sparse_tensor.SparseTensor(ix, val, shape) + for (ix, val, + shape) in zip(context_sparse_indices, context_sparse_values, + context_sparse_shapes) + ] + + feature_list_sparse_tensors = [ + sparse_tensor.SparseTensor(ix, val, shape) + for (ix, val, shape + ) in zip(feature_list_sparse_indices, feature_list_sparse_values, + feature_list_sparse_shapes) + ] + # pylint: enable=g-complex-comprehension + + context_output = dict( + zip( + context.sparse_keys + context.dense_keys + context.ragged_keys, + context_sparse_tensors + context_dense_values + + context_ragged_tensors)) + feature_list_output = dict( + zip( + feature_list.sparse_keys + feature_list.dense_keys + + feature_list.ragged_keys, feature_list_sparse_tensors + + feature_list_dense_values + feature_list_ragged_tensors)) + feature_list_lengths = dict( + zip(feature_list.dense_keys, feature_list_dense_lengths)) + + return (context_output, feature_list_output, feature_list_lengths) + + +@tf_export("io.parse_single_sequence_example", + v1=["io.parse_single_sequence_example", + "parse_single_sequence_example"]) +@dispatch.add_dispatch_support +def parse_single_sequence_example( + serialized, context_features=None, sequence_features=None, + example_name=None, name=None): + # pylint: disable=line-too-long + """Parses a single `SequenceExample` proto. + + Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto) + proto given in `serialized`. + + This op parses a serialized sequence example into a tuple of dictionaries, + each mapping keys to `Tensor` and `SparseTensor` objects. + The first dictionary contains mappings for keys appearing in + `context_features`, and the second dictionary contains mappings for keys + appearing in `sequence_features`. + + At least one of `context_features` and `sequence_features` must be provided + and non-empty. + + The `context_features` keys are associated with a `SequenceExample` as a + whole, independent of time / frame. In contrast, the `sequence_features` keys + provide a way to access variable-length data within the `FeatureList` section + of the `SequenceExample` proto. While the shapes of `context_features` values + are fixed with respect to frame, the frame dimension (the first dimension) + of `sequence_features` values may vary between `SequenceExample` protos, + and even between `feature_list` keys within the same `SequenceExample`. + + `context_features` contains `VarLenFeature`, `RaggedFeature`, and + `FixedLenFeature` objects. Each `VarLenFeature` is mapped to a `SparseTensor`; + each `RaggedFeature` is mapped to a `RaggedTensor`; and each `FixedLenFeature` + is mapped to a `Tensor`, of the specified type, shape, and default value. + + `sequence_features` contains `VarLenFeature`, `RaggedFeature`, and + `FixedLenSequenceFeature` objects. Each `VarLenFeature` is mapped to a + `SparseTensor`; each `RaggedFeature` is mapped to a `RaggedTensor`; and each + `FixedLenSequenceFeature` is mapped to a `Tensor`, each of the specified type. + The shape will be `(T,) + df.dense_shape` for `FixedLenSequenceFeature` `df`, + where `T` is the length of the associated `FeatureList` in the + `SequenceExample`. For instance, `FixedLenSequenceFeature([])` yields a scalar + 1-D `Tensor` of static shape `[None]` and dynamic shape `[T]`, while + `FixedLenSequenceFeature([k])` (for `int k >= 1`) yields a 2-D matrix `Tensor` + of static shape `[None, k]` and dynamic shape `[T, k]`. + + Each `SparseTensor` corresponding to `sequence_features` represents a ragged + vector. Its indices are `[time, index]`, where `time` is the `FeatureList` + entry and `index` is the value's index in the list of values associated with + that time. + + `FixedLenFeature` entries with a `default_value` and `FixedLenSequenceFeature` + entries with `allow_missing=True` are optional; otherwise, we will fail if + that `Feature` or `FeatureList` is missing from any example in `serialized`. + + `example_name` may contain a descriptive name for the corresponding serialized + proto. This may be useful for debugging purposes, but it has no effect on the + output. If not `None`, `example_name` must be a scalar. + + Note that the batch version of this function, `tf.parse_sequence_example`, + is written for better memory efficiency and will be faster on large + `SequenceExample`s. + + Args: + serialized: A scalar (0-D Tensor) of type string, a single binary + serialized `SequenceExample` proto. + context_features: A mapping of feature keys to `FixedLenFeature` or + `VarLenFeature` or `RaggedFeature` values. These features are associated + with a `SequenceExample` as a whole. + sequence_features: A mapping of feature keys to + `FixedLenSequenceFeature` or `VarLenFeature` or `RaggedFeature` values. + These features are associated with data within the `FeatureList` section + of the `SequenceExample` proto. + example_name: A scalar (0-D Tensor) of strings (optional), the name of + the serialized proto. + name: A name for this operation (optional). + + Returns: + A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s + and `RaggedTensor`s. + + * The first dict contains the context key/values. + * The second dict contains the feature_list key/values. + + Raises: + ValueError: if any feature is invalid. + """ + # pylint: enable=line-too-long + if not (context_features or sequence_features): + raise ValueError("Both context_features and sequence_features are None, but" + " at least one should have values.") + context_params = _ParseOpParams.from_features( + context_features, [VarLenFeature, FixedLenFeature, RaggedFeature]) + feature_list_params = _ParseOpParams.from_features( + sequence_features, + [VarLenFeature, FixedLenSequenceFeature, RaggedFeature]) + + with ops.name_scope(name, "ParseSingleSequenceExample", + [serialized, example_name]): + context_output, feature_list_output = ( + _parse_single_sequence_example_raw(serialized, context_params, + feature_list_params, example_name, + name)) + + if context_params.ragged_keys: + context_output = _construct_tensors_for_composite_features( + context_features, context_output) + if feature_list_params.ragged_keys: + feature_list_output = _construct_tensors_for_composite_features( + sequence_features, feature_list_output) + + return context_output, feature_list_output + + +def _parse_single_sequence_example_raw(serialized, + context, + feature_list, + debug_name, + name=None): + """Parses a single `SequenceExample` proto. + + Args: + serialized: A scalar (0-D Tensor) of type string, a single binary serialized + `SequenceExample` proto. + context: A `ParseOpParams` containing the parameters for the parse op for + the context features. + feature_list: A `ParseOpParams` containing the parameters for the parse op + for the feature_list features. + debug_name: A scalar (0-D Tensor) of strings (optional), the name of the + serialized proto. + name: A name for this operation (optional). + + Returns: + A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s. + The first dict contains the context key/values. + The second dict contains the feature_list key/values. + + Raises: + TypeError: if feature_list.dense_defaults is not either None or a dict. + """ + with ops.name_scope(name, "ParseSingleExample", [serialized, debug_name]): + serialized = ops.convert_to_tensor(serialized, name="serialized") + serialized = _assert_scalar(serialized, "serialized") + return _parse_sequence_example_raw(serialized, debug_name, context, + feature_list, name)[:2] + + +@tf_export("io.decode_raw", v1=[]) +@dispatch.add_dispatch_support +def decode_raw(input_bytes, + out_type, + little_endian=True, + fixed_length=None, + name=None): + r"""Convert raw bytes from input tensor into numeric tensors. + + Every component of the input tensor is interpreted as a sequence of bytes. + These bytes are then decoded as numbers in the format specified by `out_type`. + + >>> tf.io.decode_raw(tf.constant("1"), tf.uint8) + + >>> tf.io.decode_raw(tf.constant("1,2"), tf.uint8) + + + Note that the rank of the output tensor is always one more than the input one: + + >>> tf.io.decode_raw(tf.constant(["1","2"]), tf.uint8).shape + TensorShape([2, 1]) + >>> tf.io.decode_raw(tf.constant([["1"],["2"]]), tf.uint8).shape + TensorShape([2, 1, 1]) + + This is because each byte in the input is converted to a new value on the + output (if output type is `uint8` or `int8`, otherwise chunks of inputs get + coverted to a new value): + + >>> tf.io.decode_raw(tf.constant("123"), tf.uint8) + + >>> tf.io.decode_raw(tf.constant("1234"), tf.uint8) + >> # chuncked output + >>> tf.io.decode_raw(tf.constant("12"), tf.uint16) + + >>> tf.io.decode_raw(tf.constant("1234"), tf.uint16) + >> # int64 output + >>> tf.io.decode_raw(tf.constant("12345678"), tf.int64) + + >>> tf.io.decode_raw(tf.constant("1234567887654321"), tf.int64) + + + The operation allows specifying endianness via the `little_endian` parameter. + + >>> tf.io.decode_raw(tf.constant("\x0a\x0b"), tf.int16) + + >>> hex(2826) + '0xb0a' + >>> tf.io.decode_raw(tf.constant("\x0a\x0b"), tf.int16, little_endian=False) + + >>> hex(2571) + '0xa0b' + + If the elements of `input_bytes` are of different length, you must specify + `fixed_length`: + + >>> tf.io.decode_raw(tf.constant([["1"],["23"]]), tf.uint8, fixed_length=4) + + + If the `fixed_length` value is larger that the length of the `out_type` dtype, + multiple values are generated: + + >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) + >> x=''.join([chr(1), chr(2), chr(3), chr(4)]) + >>> tf.io.decode_raw(x, tf.uint16, fixed_length=2) + + >>> hex(513) + '0x201' + + If `little_endian` and `fixed_length` are specified, truncation to the fixed + length occurs before endianness conversion: + + >>> x=''.join([chr(1), chr(2), chr(3), chr(4)]) + >>> tf.io.decode_raw(x, tf.uint16, fixed_length=2, little_endian=False) + + >>> hex(258) + '0x102' + + If input values all have the same length, then specifying `fixed_length` + equal to the size of the strings should not change output: + + >>> x = ["12345678", "87654321"] + >>> tf.io.decode_raw(x, tf.int16) + + >>> tf.io.decode_raw(x, tf.int16, fixed_length=len(x[0])) + + + Args: + input_bytes: + Each element of the input Tensor is converted to an array of bytes. + + Currently, this must be a tensor of strings (bytes), although semantically + the operation should support any input. + out_type: + `DType` of the output. Acceptable types are `half`, `float`, `double`, + `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`. + little_endian: + Whether the `input_bytes` data is in little-endian format. Data will be + converted into host byte order if necessary. + fixed_length: + If set, the first `fixed_length` bytes of each element will be converted. + Data will be zero-padded or truncated to the specified length. + + `fixed_length` must be a multiple of the size of `out_type`. + + `fixed_length` must be specified if the elements of `input_bytes` are of + variable length. + name: A name for the operation (optional). + + Returns: + A `Tensor` object storing the decoded bytes. + """ + if fixed_length is not None: + return gen_parsing_ops.decode_padded_raw( + input_bytes, + fixed_length=fixed_length, + out_type=out_type, + little_endian=little_endian, + name=name) + else: + return gen_parsing_ops.decode_raw( + input_bytes, out_type, little_endian=little_endian, name=name) + + +@tf_export(v1=["decode_raw", "io.decode_raw"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "bytes is deprecated, use input_bytes instead", + "bytes") +def decode_raw_v1( + input_bytes=None, + out_type=None, + little_endian=True, + name=None, + bytes=None # pylint: disable=redefined-builtin +): + """Convert raw byte strings into tensors. + + Args: + input_bytes: + Each element of the input Tensor is converted to an array of bytes. + out_type: + `DType` of the output. Acceptable types are `half`, `float`, `double`, + `int32`, `uint16`, `uint8`, `int16`, `int8`, `int64`. + little_endian: + Whether the `input_bytes` data is in little-endian format. Data will be + converted into host byte order if necessary. + name: A name for the operation (optional). + bytes: Deprecated parameter. Use `input_bytes` instead. + + Returns: + A `Tensor` object storing the decoded bytes. + """ + input_bytes = deprecation.deprecated_argument_lookup("input_bytes", + input_bytes, "bytes", + bytes) + + # out_type is a required positional argument in the original API, and had to + # be changed to a keyword argument in order to facilitate the transition from + # the reserved named `bytes` to `input_bytes`. Ensure it's still set. + if out_type is None: + raise ValueError( + "decode_raw_v1() missing 1 positional argument: 'out_type'") + + return gen_parsing_ops.decode_raw( + input_bytes, out_type, little_endian=little_endian, name=name) + + +# Swap `name` and `na_value` for backward compatibility. +@tf_export(v1=["io.decode_csv", "decode_csv"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("decode_csv") +def decode_csv(records, + record_defaults, + field_delim=",", + use_quote_delim=True, + name=None, + na_value="", + select_cols=None): + """Convert CSV records to tensors. Each column maps to one tensor. + + RFC 4180 format is expected for the CSV records. + (https://tools.ietf.org/html/rfc4180) + Note that we allow leading and trailing spaces with int or float field. + + Args: + records: A `Tensor` of type `string`. + Each string is a record/row in the csv and all records should have + the same format. + record_defaults: A list of `Tensor` objects with specific types. + Acceptable types are `float32`, `float64`, `int32`, `int64`, `string`. + One tensor per column of the input record, with either a + scalar default value for that column or an empty vector if the column is + required. + field_delim: An optional `string`. Defaults to `","`. + char delimiter to separate fields in a record. + use_quote_delim: An optional `bool`. Defaults to `True`. + If false, treats double quotation marks as regular + characters inside of the string fields (ignoring RFC 4180, Section 2, + Bullet 5). + name: A name for the operation (optional). + na_value: Additional string to recognize as NA/NaN. + select_cols: Optional sorted list of column indices to select. If specified, + only this subset of columns will be parsed and returned. + + Returns: + A list of `Tensor` objects. Has the same type as `record_defaults`. + Each tensor will have the same shape as records. + + Raises: + ValueError: If any of the arguments is malformed. + """ + return decode_csv_v2( + records, record_defaults, + field_delim, use_quote_delim, + na_value, select_cols, name + ) + + +@tf_export("io.decode_csv", v1=[]) +@dispatch.add_dispatch_support +def decode_csv_v2(records, + record_defaults, + field_delim=",", + use_quote_delim=True, + na_value="", + select_cols=None, + name=None): + """Convert CSV records to tensors. Each column maps to one tensor. + + RFC 4180 format is expected for the CSV records. + (https://tools.ietf.org/html/rfc4180) + Note that we allow leading and trailing spaces with int or float field. + + Args: + records: A `Tensor` of type `string`. + Each string is a record/row in the csv and all records should have + the same format. + record_defaults: A list of `Tensor` objects with specific types. + Acceptable types are `float32`, `float64`, `int32`, `int64`, `string`. + One tensor per column of the input record, with either a + scalar default value for that column or an empty vector if the column is + required. + field_delim: An optional `string`. Defaults to `","`. + char delimiter to separate fields in a record. + use_quote_delim: An optional `bool`. Defaults to `True`. + If false, treats double quotation marks as regular + characters inside of the string fields (ignoring RFC 4180, Section 2, + Bullet 5). + na_value: Additional string to recognize as NA/NaN. + select_cols: Optional sorted list of column indices to select. If specified, + only this subset of columns will be parsed and returned. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects. Has the same type as `record_defaults`. + Each tensor will have the same shape as records. + + Raises: + ValueError: If any of the arguments is malformed. + """ + if select_cols is not None and any(select_cols[i] >= select_cols[i + 1] + for i in range(len(select_cols) - 1)): + raise ValueError("select_cols is not strictly increasing.") + if select_cols is not None and select_cols[0] < 0: + raise ValueError("select_cols contains negative values.") + if select_cols is not None and len(select_cols) != len(record_defaults): + raise ValueError("Length of select_cols and record_defaults do not match.") + return gen_parsing_ops.decode_csv( + records=records, + record_defaults=record_defaults, + field_delim=field_delim, + use_quote_delim=use_quote_delim, + na_value=na_value, + name=name, + select_cols=select_cols, + ) + + +def _assert_scalar(value, name): + """Asserts that `value` is scalar, and returns `value`.""" + value_rank = value.shape.rank + if value_rank is None: + check = control_flow_assert.Assert( + math_ops.equal(array_ops.rank(value), 0), + ["Input %s must be a scalar" % name], + name="%sIsScalar" % name.capitalize()) + result = control_flow_ops.with_dependencies([check], + value, + name="%sDependencies" % name) + result.set_shape([]) + return result + elif value_rank == 0: + return value + else: + raise ValueError("Input %s must be a scalar" % name) + + +@tf_export("io.decode_json_example", + v1=["decode_json_example", "io.decode_json_example"]) +def decode_json_example(json_examples, name=None): + r"""Convert JSON-encoded Example records to binary protocol buffer strings. + + Note: This is **not** a general purpose JSON parsing op. + + This op converts JSON-serialized `tf.train.Example` (maybe created with + `json_format.MessageToJson`, following the + [standard JSON mapping]( + https://developers.google.com/protocol-buffers/docs/proto3#json)) + to a binary-serialized `tf.train.Example` (equivalent to + `Example.SerializeToString()`) suitable for conversion to tensors with + `tf.io.parse_example`. + + Here is a `tf.train.Example` proto: + + >>> example = tf.train.Example( + ... features=tf.train.Features( + ... feature={ + ... "a": tf.train.Feature( + ... int64_list=tf.train.Int64List( + ... value=[1, 1, 3]))})) + + Here it is converted to JSON: + + >>> from google.protobuf import json_format + >>> example_json = json_format.MessageToJson(example) + >>> print(example_json) + { + "features": { + "feature": { + "a": { + "int64List": { + "value": [ + "1", + "1", + "3" + ] + } + } + } + } + } + + This op converts the above json string to a binary proto: + + >>> example_binary = tf.io.decode_json_example(example_json) + >>> example_binary.numpy() + b'\n\x0f\n\r\n\x01a\x12\x08\x1a\x06\x08\x01\x08\x01\x08\x03' + + The OP works on string tensors of andy shape: + + >>> tf.io.decode_json_example([ + ... [example_json, example_json], + ... [example_json, example_json]]).shape.as_list() + [2, 2] + + This resulting binary-string is equivalent to `Example.SerializeToString()`, + and can be converted to Tensors using `tf.io.parse_example` and related + functions: + + >>> tf.io.parse_example( + ... serialized=[example_binary.numpy(), + ... example.SerializeToString()], + ... features = {'a': tf.io.FixedLenFeature(shape=[3], dtype=tf.int64)}) + {'a': } + + Args: + json_examples: A string tensor containing json-serialized `tf.Example` + protos. + name: A name for the op. + + Returns: + A string Tensor containing the binary-serialized `tf.Example` protos. + + Raises: + `tf.errors.InvalidArgumentError`: If the JSON could not be converted to a + `tf.Example` + """ + return gen_parsing_ops.decode_json_example(json_examples, name=name) + + +# Register elementwise ops that don't have Python wrappers. +dispatch.register_unary_elementwise_api(gen_parsing_ops.decode_compressed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/partitioned_variables.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/partitioned_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..81b9036e318b602deb09011b80363d447479b0df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/partitioned_variables.py @@ -0,0 +1,347 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Helper functions for creating partitioned variables. + +This is a convenient abstraction to partition a large variable across +multiple smaller variables that can be assigned to different devices. + +The full variable can be reconstructed by concatenating the smaller variables. +Using partitioned variables instead of a single variable is mostly a +performance choice. It however also has an impact on: + +1. Random initialization, as the random number generator is called once per + slice +2. Updates, as they happen in parallel across slices + +A key design goal is to allow a different graph to repartition a variable +with the same name but different slicings, including possibly no partitions. + +TODO(touts): If an initializer provides a seed, the seed must be changed +deterministically for each slice, maybe by adding one to it, otherwise each +slice will use the same values. Maybe this can be done by passing the +slice offsets to the initializer functions. + +Typical usage: + +```python +# Create a list of partitioned variables with: +vs = create_partitioned_variables( + , , , name=) + +# Pass the list as inputs to embedding_lookup for sharded, parallel lookup: +y = embedding_lookup(vs, ids, partition_strategy="div") + +# Or fetch the variables in parallel to speed up large matmuls: +z = matmul(x, concat(slice_dim, vs)) +``` +""" +import math + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import variable_scope +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +__all__ = [ + "create_partitioned_variables", + "variable_axis_size_partitioner", + "min_max_variable_partitioner", + "fixed_size_partitioner", +] + + +@tf_export(v1=["variable_axis_size_partitioner"]) +def variable_axis_size_partitioner( + max_shard_bytes, axis=0, bytes_per_string_element=16, max_shards=None): + """Get a partitioner for VariableScope to keep shards below `max_shard_bytes`. + + This partitioner will shard a Variable along one axis, attempting to keep + the maximum shard size below `max_shard_bytes`. In practice, this is not + always possible when sharding along only one axis. When this happens, + this axis is sharded as much as possible (i.e., every dimension becomes + a separate shard). + + If the partitioner hits the `max_shards` limit, then each shard may end up + larger than `max_shard_bytes`. By default `max_shards` equals `None` and no + limit on the number of shards is enforced. + + One reasonable value for `max_shard_bytes` is `(64 << 20) - 1`, or almost + `64MB`, to keep below the protobuf byte limit. + + Args: + max_shard_bytes: The maximum size any given shard is allowed to be. + axis: The axis to partition along. Default: outermost axis. + bytes_per_string_element: If the `Variable` is of type string, this provides + an estimate of how large each scalar in the `Variable` is. + max_shards: The maximum number of shards in int created taking precedence + over `max_shard_bytes`. + + Returns: + A partition function usable as the `partitioner` argument to + `variable_scope` and `get_variable`. + + Raises: + ValueError: If any of the byte counts are non-positive. + """ + if max_shard_bytes < 1 or bytes_per_string_element < 1: + raise ValueError( + "Both max_shard_bytes and bytes_per_string_element must be positive. " + f"Currently, max_shard_bytes is {max_shard_bytes} and" + f"bytes_per_string_element is {bytes_per_string_element}") + if max_shards and max_shards < 1: + raise ValueError( + "max_shards must be positive.") + + def _partitioner(shape, dtype): + """Partitioner that partitions shards to have max_shard_bytes total size. + + Args: + shape: A `TensorShape`. + dtype: A `DType`. + + Returns: + A tuple representing how much to slice each axis in shape. + + Raises: + ValueError: If shape is not a fully defined `TensorShape` or dtype is not + a `DType`. + """ + if not isinstance(shape, tensor_shape.TensorShape): + raise ValueError(f"shape is not a TensorShape: {shape}") + if not shape.is_fully_defined(): + raise ValueError(f"shape is not fully defined: {shape}") + if not isinstance(dtype, dtypes.DType): + raise ValueError(f"dtype is not a DType: {dtype}") + + if dtype.base_dtype == dtypes.string: + element_size = bytes_per_string_element + else: + element_size = dtype.size + + partitions = [1] * shape.ndims + bytes_per_slice = 1.0 * ( + shape.num_elements() / shape.dims[axis].value) * element_size + # How many slices can we fit on one shard of size at most max_shard_bytes? + # At least one slice is required. + slices_per_shard = max(1, math.floor(max_shard_bytes / bytes_per_slice)) + # How many shards do we need for axis given that each shard fits + # slices_per_shard slices from a total of shape[axis] slices? + axis_shards = int(math.ceil( + 1.0 * shape.dims[axis].value / slices_per_shard)) + if max_shards: + axis_shards = min(max_shards, axis_shards) + + partitions[axis] = axis_shards + + return partitions + + return _partitioner + + +@tf_export(v1=["min_max_variable_partitioner"]) +def min_max_variable_partitioner(max_partitions=1, axis=0, + min_slice_size=256 << 10, + bytes_per_string_element=16): + """Partitioner to allocate minimum size per slice. + + Returns a partitioner that partitions the variable of given shape and dtype + such that each partition has a minimum of `min_slice_size` slice of the + variable. The maximum number of such partitions (upper bound) is given by + `max_partitions`. + + Args: + max_partitions: Upper bound on the number of partitions. Defaults to 1. + axis: Axis along which to partition the variable. Defaults to 0. + min_slice_size: Minimum size of the variable slice per partition. Defaults + to 256K. + bytes_per_string_element: If the `Variable` is of type string, this provides + an estimate of how large each scalar in the `Variable` is. + + Returns: + A partition function usable as the `partitioner` argument to + `variable_scope` and `get_variable`. + + """ + def _partitioner(shape, dtype): + """Partitioner that partitions list for a variable of given shape and type. + + Ex: Consider partitioning a variable of type float32 with + shape=[1024, 1024]. + If `max_partitions` >= 16, this function would return + [(1024 * 1024 * 4) / (256 * 1024), 1] = [16, 1]. + If `max_partitions` < 16, this function would return + [`max_partitions`, 1]. + + Args: + shape: Shape of the variable. + dtype: Type of the variable. + + Returns: + List of partitions for each axis (currently only one axis can be + partitioned). + + Raises: + ValueError: If axis to partition along does not exist for the variable. + """ + if axis >= len(shape): + raise ValueError( + f"Cannot partition variable along axis {axis} when shape is " + f"only {shape}") + if dtype.base_dtype == dtypes.string: + bytes_per_element = bytes_per_string_element + else: + bytes_per_element = dtype.size + total_size_bytes = shape.num_elements() * bytes_per_element + partitions = total_size_bytes / min_slice_size + partitions_list = [1] * len(shape) + # We can not partition the variable beyond what its shape or + # `max_partitions` allows. + partitions_list[axis] = max(1, min(shape.dims[axis].value, + max_partitions, + int(math.ceil(partitions)))) + return partitions_list + return _partitioner + + +@tf_export(v1=["fixed_size_partitioner"]) +def fixed_size_partitioner(num_shards, axis=0): + """Partitioner to specify a fixed number of shards along given axis. + + @compatibility(TF2) + This API is deprecated in TF2. In TF2, partitioner is no longer part of + the variable declaration via `tf.Variable`. + [ParameterServer Training] + (https://www.tensorflow.org/tutorials/distribute/parameter_server_training) + handles partitioning of variables. The corresponding TF2 partitioner class of + `fixed_size_partitioner` is + `tf.distribute.experimental.partitioners.FixedShardsPartitioner`. + + Check the [migration guide] + (https://www.tensorflow.org/guide/migrate#2_use_python_objects_to_track_variables_and_losses) + on the differences in treatment of variables and losses between TF1 and TF2. + + Before: + + ``` + x = tf.compat.v1.get_variable( + "x", shape=(2,), partitioner=tf.compat.v1.fixed_size_partitioner(2) + ) + ``` + After: + + ``` + partitioner = ( + tf.distribute.experimental.partitioners.FixedShardsPartitioner( + num_shards=2) + ) + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=cluster_resolver, + variable_partitioner=partitioner) + + with strategy.scope(): + x = tf.Variable([1.0, 2.0]) + ``` + @end_compatibility + + Args: + num_shards: `int`, number of shards to partition variable. + axis: `int`, axis to partition on. + + Returns: + A partition function usable as the `partitioner` argument to + `variable_scope` and `get_variable`. + """ + def _partitioner(shape, **unused_args): + partitions_list = [1] * len(shape) + partitions_list[axis] = min(num_shards, shape.dims[axis].value) + return partitions_list + return _partitioner + + +@tf_export(v1=["create_partitioned_variables"]) +@deprecation.deprecated( + date=None, + instructions="Use `tf.get_variable` with a partitioner set.") +def create_partitioned_variables( + shape, slicing, initializer, dtype=dtypes.float32, + trainable=True, collections=None, name=None, reuse=None): + """Create a list of partitioned variables according to the given `slicing`. + + Currently only one dimension of the full variable can be sliced, and the + full variable can be reconstructed by the concatenation of the returned + list along that dimension. + + Args: + shape: List of integers. The shape of the full variable. + slicing: List of integers. How to partition the variable. + Must be of the same length as `shape`. Each value + indicate how many slices to create in the corresponding + dimension. Presently only one of the values can be more than 1; + that is, the variable can only be sliced along one dimension. + + For convenience, The requested number of partitions does not have to + divide the corresponding dimension evenly. If it does not, the + shapes of the partitions are incremented by 1 starting from partition + 0 until all slack is absorbed. The adjustment rules may change in the + future, but as you can save/restore these variables with different + slicing specifications this should not be a problem. + initializer: A `Tensor` of shape `shape` or a variable initializer + function. If a function, it will be called once for each slice, + passing the shape and data type of the slice as parameters. The + function must return a tensor with the same shape as the slice. + dtype: Type of the variables. Ignored if `initializer` is a `Tensor`. + trainable: If True also add all the variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. + collections: List of graph collections keys to add the variables to. + Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + name: Optional name for the full variable. Defaults to + `"PartitionedVariable"` and gets uniquified automatically. + reuse: Boolean or `None`; if `True` and name is set, it would reuse + previously created variables. if `False` it will create new variables. + if `None`, it would inherit the parent scope reuse. + + Returns: + A list of Variables corresponding to the slicing. + + Raises: + ValueError: If any of the arguments is malformed. + """ + if len(shape) != len(slicing): + raise ValueError( + "The 'shape' and 'slicing' of a partitioned Variable " + f"must have the length: shape: {shape}, slicing: {slicing}") + if len(shape) < 1: + raise ValueError("A partitioned Variable must have rank at least 1: " + f"shape: {shape}") + + # Legacy: we are provided the slicing directly, so just pass it to + # the partitioner. + partitioner = lambda **unused_kwargs: slicing + + with variable_scope.variable_scope( + name, "PartitionedVariable", reuse=reuse): + # pylint: disable=protected-access + partitioned_var = variable_scope._get_partitioned_variable( + name=None, + shape=shape, + dtype=dtype, + initializer=initializer, + trainable=trainable, + partitioner=partitioner, + collections=collections) + return list(partitioned_var) + # pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/proto_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/proto_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9517795e74ae7d6f03e065656f6210fa9dac91ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/proto_ops.py @@ -0,0 +1,25 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +# pylint: disable=wildcard-import,unused-import +"""Protocol Buffer encoding and decoding from tensors.""" +# pylint: disable=unused-import +from tensorflow.python.framework import ops +from tensorflow.python.ops.gen_decode_proto_ops import decode_proto_v2 as decode_proto +from tensorflow.python.ops.gen_encode_proto_ops import encode_proto +# pylint: enable=unused-import + +ops.NotDifferentiable("DecodeProtoV2") +ops.NotDifferentiable("EncodeProto") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d9a79dad753fb5d28e5b3361d9e6fcceb0f58f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ragged Tensors. + +This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`), +which are tensors with non-uniform shapes. In particular, each `RaggedTensor` +has one or more *ragged dimensions*, which are dimensions whose slices may have +different lengths. For example, the inner (column) dimension of +`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices +(`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed +description of ragged tensors, see the `tf.RaggedTensor` class documentation +and the [Ragged Tensor Guide](/guide/ragged_tensor). + +API docstring: tensorflow.ragged +""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/dynamic_ragged_shape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/dynamic_ragged_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..30b0534accb95d353baa4b2ad54edcf7d030ba07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/dynamic_ragged_shape.py @@ -0,0 +1,3292 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Shapes & broadcasting for RaggedTensors. + +TODO(martinz): make this suitable for output for tf.shape +TODO(martinz): replace ragged_tensor_shape with this. +""" + +import abc +from typing import Any, Iterable, Optional, Sequence, Tuple, Union + +import numpy as np +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import extension_type +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged.row_partition import RowPartition +from tensorflow.python.ops.ragged.row_partition import RowPartitionSpec +from tensorflow.python.types import core +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +class _DynamicRaggedShapeBatchEncoder(extension_type.ExtensionTypeBatchEncoder): + """A batch encoder for DynamicRaggedShape below.""" + + def batch(self, spec: "DynamicRaggedShape.Spec", + batch_size) -> "DynamicRaggedShape.Spec": + if spec.num_row_partitions: + new_head = _batch_rp_spec_head(spec._row_partitions[0], batch_size) # pylint:disable=protected-access + new_tail = [_batch_rp_spec(rp, batch_size) for rp in spec._row_partitions] # pylint:disable=protected-access + new_rp = [new_head] + new_tail + new_static_inner_shape = _batch_static_inner_shape( + spec._static_inner_shape, batch_size) # pylint:disable=protected-access + + return DynamicRaggedShape.Spec( + row_partitions=new_rp, + static_inner_shape=new_static_inner_shape, + dtype=spec.dtype) + elif batch_size is None: + if spec.inner_rank == 0: + return DynamicRaggedShape.Spec._from_tensor_shape( # pylint:disable=protected-access + [None], + 0, + dtype=spec.dtype) + else: + # Might be None + new_head = RowPartitionSpec( + uniform_row_length=spec._dimension(0), # pylint:disable=protected-access + dtype=spec.dtype) + new_static_inner_shape = _batch_static_inner_shape( + spec._static_inner_shape, batch_size) # pylint:disable=protected-access + return DynamicRaggedShape.Spec( + row_partitions=[new_head], + static_inner_shape=new_static_inner_shape, + dtype=spec.dtype) + else: + + return DynamicRaggedShape.Spec( + row_partitions=[], + static_inner_shape=_batch_tensor_shape( + spec._static_inner_shape, # pylint:disable=protected-access + batch_size), + dtype=spec.dtype) + + def unbatch(self, + spec: "DynamicRaggedShape.Spec") -> "DynamicRaggedShape.Spec": + if spec.num_row_partitions: + result = [] + head = spec._row_partitions[0] # pylint:disable=protected-access + scale = None if head.uniform_row_length is None else head.nrows + + for rp in spec._row_partitions[1:]: # pylint:disable=protected-access + if scale is None: + result.append( + RowPartitionSpec( + nrows=None, + nvals=None, + uniform_row_length=rp.uniform_row_length, + dtype=spec.dtype)) + else: + nrows = None if rp.nrows is None else rp.nrows // scale + if rp.uniform_row_length is None: + scale = None + result.append( + RowPartitionSpec( + nrows=nrows, + nvals=None, + uniform_row_length=None, + dtype=spec.dtype)) + else: + result.append( + RowPartitionSpec( + nrows=nrows, + nvals=rp.nvals // scale, + uniform_row_length=rp.uniform_row_length, + dtype=spec.dtype)) + return DynamicRaggedShape.Spec( + row_partitions=result, + static_inner_shape=_unbatch_static_inner_shape( + spec._static_inner_shape, scale), # pylint:disable=protected-access + dtype=spec.dtype) + else: # spec.num_row_partitions == 0 + return DynamicRaggedShape.Spec( + row_partitions=[], + static_inner_shape=spec._static_inner_shape[1:], # pylint:disable=protected-access + dtype=spec.dtype) + + def decode(self, spec: "DynamicRaggedShape.Spec", + encoding) -> "DynamicRaggedShape": + return DynamicRaggedShape.from_tensor(encoding, dtype=spec.dtype) + + def encode( + self, + spec: "DynamicRaggedShape.Spec", + value, + minimum_rank=0) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]: + return ones(value, dtype=dtypes.bool) + + def encoding_specs( + self, spec: "DynamicRaggedShape.Spec" + ) -> Union[ragged_tensor.RaggedTensorSpec, tensor_lib.TensorSpec]: + if spec.rank != 0: + ragged_rank = spec.num_row_partitions + else: + # special case: need to unbatch twice to get ragged tensor. + ragged_rank = -1 + return ragged_tensor.RaggedTensorSpec( + shape=spec._to_tensor_shape(), # pylint:disable=protected-access + dtype=dtypes.bool, + ragged_rank=ragged_rank, + row_splits_dtype=spec.dtype) + + +# TODO(martinz): allow inner_shape to be a fully defined TensorShape. +# A "fully defined TensorShape" means one where the rank and all dimensions are +# known. +# Allowing inner_shape might mean allowing inner_shape to be initialized by +# a fully defined TensorShape, or it might mean that you can actually store +# TensorShape in the inner_shape field. This could conceivably construct +# a DynamicRaggedShape that was dtype agnostic. +# +# TODO(martinz): unify the impl of the determination of index type across +# RowPartition and DynamicRaggedShape. +@tf_export("experimental.DynamicRaggedShape") +class DynamicRaggedShape(extension_type.BatchableExtensionType): + """The shape of a ragged or dense tensor. + + Ragged shapes are encoded using two fields: + + * `inner_shape`: An integer vector giving the shape of a dense tensor. + * `row_partitions`: A list of `RowPartition` objects, describing how + that flat shape should be partitioned to add ragged axes. + + If a DynamicRaggedShape is the shape of a RaggedTensor rt, then: + 1. row_partitions = rt._nested_row_partitions + (and thus len(row_partitions) > 0) + 2. inner_shape is the shape of rt.flat_values + + If a DynamicRaggedShape is the shape of a dense tensor t, then: + 1. row_partitions = [] + 2. inner_shape is the shape of t. + + Examples: + + The following table gives a few examples (where `RP(lengths)` is short + for `RowPartition.from_lengths(lengths)`): + + Row Partitions | Inner Shape | Example Tensor + --------------------------- | ------------ | ---------------------------- + [] | [2, 3] | `[[1, 2, 3], [4, 5, 6]]` + [RP([2, 0, 3])] | [5] | `[[1, 2], [], [3, 4, 5]]` + [RP([2, 1])] | [3, 2] | `[[[1, 2], [3, 4]], [[5, 6]]]` + [RP([2, 1]), RP([2, 1, 2])] | [5] | `[[[1, 2], [3]], [[4, 5]]]` + """ + _row_partitions: Tuple[RowPartition, ...] + _inner_shape: tensor_lib.Tensor + _static_inner_shape: tensor_shape.TensorShape + __batch_encoder__ = _DynamicRaggedShapeBatchEncoder() + __name__ = "tf.DynamicRaggedShape" + + def __init__(self, + row_partitions: Sequence[RowPartition], + inner_shape: core.TensorLike, + dtype: Optional[dtypes.DType] = None, + validate: bool = False, + static_inner_shape: ... = None): + """Core constructor for a DynamicRaggedShape. + + Create a DynamicRaggedShape. This can be used to construct a + DynamicRaggedShape representing a ragged or dense shape. If row_partitions + is an empty list, then this is equivalent to a dense shape. + + If row_partitions is specified, then the num_row_partitions will be equal + to len(row_partitions). There are several checks made. + Specifically: + 1. Consecutive row_partitions must have consistent nvals and nrows. + 2. The last row_partitions must have nvals equal to the first element of + inner_shape. + + The inner_shape is converted to a tensor. + All row_partitions and the inner_shape are converted to the same dtype + (int64 or int32). + + Args: + row_partitions: the row_partitions of the shape. + inner_shape: if len(row_partitions) > 0, the shape of the flat_values. + Otherwise, the shape of the tensor. + dtype: tf.int64, tf.int32, or None representing the preferred dtype. + validate: if true, dynamic validation is applied to the shape. + static_inner_shape: if len(row_partitions) > 0, the static shape of the + flat_values. Otherwise, the static shape of the tensor. Should be + convertible to a TensorShape. + """ + if not isinstance(row_partitions, Iterable): + raise TypeError( + "row_partitions should be a list of row partitions. Instead, got " + + str(row_partitions)) + for x in row_partitions: + if not isinstance(x, RowPartition): + raise TypeError("row_partitions contains " + str(x) + + " which is not a RowPartition") + dtype = _find_dtype_iterable(row_partitions, dtype) + dtype = _find_dtype(inner_shape, dtype) + if (isinstance(inner_shape, np.ndarray) and + inner_shape.dtype == np.int32 and dtype is None): + dtype = dtypes.int32 + dtype = _find_dtype(dtypes.int64, dtype) + + row_partitions = tuple([rp.with_dtype(dtype) for rp in row_partitions]) + self._row_partitions = row_partitions + self._inner_shape = ops.convert_to_tensor( + inner_shape, dtype_hint=dtype, name="inner_dim_sizes") + if self._inner_shape.dtype != dtype: + self._inner_shape = math_ops.cast(self._inner_shape, dtype) + + checks = [] + # Validate shapes. + if self._row_partitions: + for axis, rp in enumerate(self._row_partitions): + if axis > 0: + previous_row_partition = self._row_partitions[axis - 1] + msg = ("RowPartitions in DynamicRaggedShape do not align " + f"between {axis - 1} and {axis}") + static_nrows = rp.static_nrows + static_nvals = previous_row_partition.static_nvals + if (static_nrows is not None) and (static_nvals is not None): + if static_nrows != static_nvals: + raise ValueError(msg) + else: + continue + if validate: + checks.append( + check_ops.assert_equal( + previous_row_partition.nvals(), rp.nrows(), message=msg)) + + self._inner_shape.shape.assert_has_rank(1) + + self._static_inner_shape = tensor_util.constant_value_as_shape( + self._inner_shape) + if static_inner_shape is not None: + self._static_inner_shape = self._static_inner_shape.merge_with( + static_inner_shape) + + if row_partitions: + last_row_partition = row_partitions[-1] + static_nvals = last_row_partition.static_nvals + static_inner_shape_nvals = tensor_shape.dimension_value( + self._static_inner_shape[0]) + if static_nvals is not None and static_inner_shape_nvals is not None: + if static_nvals != static_inner_shape_nvals: + raise ValueError("Last row partition does not match inner_shape.") + elif validate: + checks.append( + check_ops.assert_equal( + last_row_partition.nvals(), + self._inner_shape[0], + message="Last row partition does not match inner_shape.")) + if checks: + self._inner_shape = control_flow_ops.with_dependencies( + checks, self._inner_shape, name="inner_shape_validated") + self._row_partitions = [ + rp._with_dependencies(checks) for rp in self._row_partitions # pylint: disable=protected-access + ] + + @classmethod + def from_lengths(cls, + lengths: Sequence[Union[Sequence[int], int]], + num_row_partitions=None, + dtype=dtypes.int64): + """Creates a shape with the given lengths and num_row_partitions. + + The lengths can either be a nonnegative int or a list of nonnegative ints. + + If num_row_partitions is None, then the minimal num_row_partitions is used. + + For example, [2, (3, 2)] is the shape of [[0, 0, 0], [0, 0]], and + [2, 2] is the shape of [[0, 0], [0, 0]] + + This chooses the minimal num_row_partitions required (including zero). + + The following table gives a few examples (where `RP(lengths)` is short + for `RowPartition.from_lengths(lengths)`): + + For example: + from_lengths | row_partitions | inner_shape + ---------------------- | --------------------------| ------------- + [] | [] | [] + [2, (3, 2)] | [RP([3, 2])] | [5] + [2, 2] | [] | [2, 2] + [2, (3, 2), 7] | [RP([3, 2])] | [5, 7] + [2, (2, 2), 3] | [RP([2, 2])] | [4, 3] + [2, 2, 3] | [] | [2, 2, 3] + [2, (2, 1), (2, 0, 3)] | [RP(2, 1), RP([2, 0, 3])] | [5] + + If we want the row partitions to end with uniform row partitions, then + we can set num_row_partitions. + + For example, + below URP(3, 12) is RowPartition.from_uniform_row_length(3, 12) + + from_lengths | num_row_partitions | row_partitions | inner_shape + ---------------| -------------------|--------------------------|------------ + [2, (3, 2), 2] | 2 | [RP([3, 2]), URP(2, 10)] | [10] + [2, 2] | 1 | [URP(2, 4)] | [4] + [2, 2, 3] | 0 | [] | [2, 2, 3] + [2, 2, 3] | 1 | [URP(2, 4)] | [4, 3] + [2, 2, 3] | 2 | [URP(2, 4), URP(3, 12)] | [12] + + + + Representing the shapes from init(): + + from_lengths | Tensor Example + ------------------------ | ------------------------------ + `[2, 3]` | `[[1, 2, 3], [4, 5, 6]]` + `[3, (2, 0, 3)]` | `[[1, 2], [], [3, 4, 5]]` + `[2, (2, 1), 2]` | `[[[1, 2], [3, 4]], [[5, 6]]]` + `[2, (2, 1), (2, 1, 2)]` | `[[[1, 2], [3]], [[4, 5]]]` + + Args: + lengths: the lengths of sublists along each axis. + num_row_partitions: the num_row_partitions of the result or None + indicating the minimum number of row_partitions. + dtype: the dtype of the shape (tf.int32 or tf.int64). + + Returns: + a new DynamicRaggedShape + """ + if not isinstance(lengths, list): + raise ValueError("lengths should be a list") + for x in lengths: + if not _is_int_or_tuple_of_ints(x): + raise ValueError( + "element of lengths should be int or tuple of ints: instead %r" % + (x,)) + + if num_row_partitions is None: + # Calculate the minimal num_row_partitions. + is_list = [not isinstance(x, int) for x in lengths] + if any(is_list): + # Last index when not a list. + num_row_partitions = len(is_list) - is_list[-1::-1].index(True) - 1 + else: + num_row_partitions = 0 + + if not isinstance(num_row_partitions, int): + raise ValueError("num_row_partitions should be an int or None") + + if not lengths: + if num_row_partitions > 0: + raise ValueError("num_row_partitions==0 for a scalar shape") + return DynamicRaggedShape([], [], dtype=dtype) + + if not num_row_partitions < len(lengths): + raise ValueError("num_row_partitions should be less than `len(lengths)` " + "if shape is not scalar.") + + if num_row_partitions > 0: + (row_partitions, nvals) = _to_row_partitions_and_nvals_from_lengths( + lengths[:num_row_partitions + 1]) + inner_shape = [nvals] + lengths[num_row_partitions + 1:] + return DynamicRaggedShape(row_partitions, inner_shape, dtype=dtype) + else: + return DynamicRaggedShape([], lengths, dtype=dtype) + + @classmethod + def from_row_partitions(cls, row_partitions, dtype=None): + """Create a shape from row_partitions. + + Args: + row_partitions: a nonempty list of RowPartition objects. + dtype: the dtype to use, or None to use the row_partitions dtype. + + Returns: + a DynamicRaggedShape with inner_rank==1. + """ + if not row_partitions: + raise ValueError("row_partitions cannot be empty") + inner_shape = [row_partitions[-1].nvals()] + return DynamicRaggedShape(row_partitions, inner_shape, dtype=dtype) + + @classmethod + def _from_inner_shape(cls, inner_shape, dtype=None): + """Create a shape from inner_shape, where num_row_partitions == 0.""" + return DynamicRaggedShape([], inner_shape, dtype=dtype) + + # pylint: disable=protected-access + @classmethod + def from_tensor(cls, t, dtype=None): + """Constructs a ragged shape for a potentially ragged tensor.""" + if ragged_tensor.is_ragged(t): + return DynamicRaggedShape( + t._nested_row_partitions, _flat_values_shape(t), dtype=dtype) + else: + return DynamicRaggedShape._from_inner_shape( + array_ops.shape(t), dtype=dtype) + + @property + def row_partitions(self): + """The row_partitions of the shape.""" + return self._row_partitions + + @property + def num_row_partitions(self): + """The number of row_partitions of the shape.""" + return len(self._row_partitions) + + @property + def dtype(self): + """The dtype of the shape -- one of tf.int32 or tf.int64.""" + return self._inner_shape.dtype + + def _static_inner_shape_as_list(self, truncate_first): + """Returns the lengths of the inner shape (if rank known), or [...].""" + if self._static_inner_shape.rank is None: + return [...] + result = self._static_inner_shape.as_list() + if truncate_first: + return result[1:] + return result + + def static_lengths(self, ragged_lengths=True): + """Returns a list of statically known axis lengths. + + This represents what values are known. For each row partition, it presents + either the uniform row length (if statically known), + the list of row lengths, or none if it is not statically known. + For the inner shape, if the rank is known, then each dimension is reported + if known, and None otherwise. If the rank of the inner shape is not known, + then the returned list ends with an ellipsis. + + Args: + ragged_lengths: If false, returns None for all ragged dimensions. + + Returns: + A Sequence[Union[Sequence[int],int, None]] of lengths, with a possible + Ellipsis at the end. + """ + if self.num_row_partitions == 0: + return self._static_inner_shape_as_list(False) + first_dim = self.row_partitions[0].static_nrows + if isinstance(first_dim, tensor_shape.Dimension): + first_dim = first_dim.value + rp_dims = [first_dim] + for rp in self.row_partitions: + if rp.is_uniform(): + rp_dims.append(rp.static_uniform_row_length) + elif ragged_lengths: + const_vals = tensor_util.constant_value(rp.row_lengths()) + if const_vals is None: + rp_dims.append(None) + else: + rp_dims.append(tuple(const_vals.tolist())) + else: + rp_dims.append(None) + + return rp_dims + self._static_inner_shape_as_list(True) + + def __repr__(self): + lengths = _list_with_ellipsis_to_str(self.static_lengths()) + return ("" % + (lengths, self.num_row_partitions)) + + def _to_tensor_shape(self) -> tensor_shape.TensorShape: + """Returns a TensorShape representation of the shape.""" + lengths = self.static_lengths(ragged_lengths=False) + if not lengths: + return tensor_shape.TensorShape(()) + if lengths[-1] == Ellipsis: + return tensor_shape.TensorShape(None) + return tensor_shape.TensorShape(lengths) + + def _slice_shape(self, start, stop): + """Returns a shape self[start:stop]. + + If start == 0, then this truncates dimensions after stop. + If start != 0, then this will return a shape with num_row_partitions == 0. + + See __getitem__. + + Args: + start: the first dimension. 0 <= start <= rank + stop: the last dimension (exclusive). 0 <= stop <= rank + """ + if stop <= start: + return DynamicRaggedShape._from_inner_shape([]) + elif start == 0: + if stop <= self.num_row_partitions: + if stop == 1: + return DynamicRaggedShape._from_inner_shape( + [self.row_partitions[0].nrows()]) + new_row_partitions = self.row_partitions[:stop - 1] + new_inner_shape = [new_row_partitions[-1].nvals()] + return DynamicRaggedShape(new_row_partitions, new_inner_shape) + else: + if self.rank is None: + new_inner_rank = stop - self.num_row_partitions + new_inner_shape = self.inner_shape[:new_inner_rank] + return DynamicRaggedShape( + row_partitions=self.row_partitions, + inner_shape=new_inner_shape, + static_inner_shape=None, + validate=False) + + elif self.rank <= stop: + return self + new_inner_rank = stop - self.num_row_partitions + new_inner_shape = self.inner_shape[:new_inner_rank] + return DynamicRaggedShape( + row_partitions=self.row_partitions, + inner_shape=new_inner_shape, + static_inner_shape=tensor_shape.TensorShape([None] * + new_inner_rank), + validate=False) + else: + if self.rank is None or stop < self.rank: + partial = self._slice_shape(0, stop) + else: + partial = self + + for x in partial.row_partitions: + if not x.is_uniform(): + raise ValueError("All relevant dimensions must be uniform") + if partial.rank is None: + # TODO(martinz): Implement _with_num_row_partitions(0) if rank is + # unknown, and remove. + raise NotImplementedError( + "__getitem__[start:stop] where start > 0 not implemented") + + return DynamicRaggedShape._from_inner_shape( + partial._with_num_row_partitions(0).inner_shape[start:]) + + def _dimension(self, index): + """Return a dimension, if the dimension is not ragged (see __getitem__).""" + rank = self.rank + if not isinstance(index, int): + raise TypeError("index should be an int") + if (self.num_row_partitions == 0 or index > self.num_row_partitions + 1): + # If num_row_partitions > 0 and index <= num_row_partitions + 1, then + # we are safe. + if rank is None: + raise ValueError( + "Rank must be known to use __getitem__ on a large index.") + if index >= rank: + raise IndexError("Index is too big: " + str(index) + ">=" + str(rank)) + if index < 0: + raise IndexError("Index must be non-negative: " + str(index)) + elif not self.is_uniform(index): + raise ValueError("Index " + str(index) + " is not uniform") + elif index == 0 and self.num_row_partitions > 0: + static_nrows = self.row_partitions[0].static_nrows + if static_nrows is not None: + return constant_op.constant(static_nrows, dtype=self.dtype) + return self.row_partitions[0].nrows() + elif self.num_row_partitions == 0: + static_result = tensor_shape.dimension_value( + self._static_inner_shape[index]) + if static_result is not None: + return constant_op.constant(static_result, dtype=self.dtype) + return self.inner_shape[index] + elif index > self.num_row_partitions: + static_result = tensor_shape.dimension_value( + self._static_inner_shape[index - self.num_row_partitions]) + if static_result is not None: + return constant_op.constant(static_result, dtype=self.dtype) + + return self.inner_shape[index - self.num_row_partitions] + else: + return self.row_partitions[index - 1].uniform_row_length() + + def __getitem__(self, index): + """Returns a dimension or a slice of the shape. + + Ragged shapes can have ragged dimensions that depend upon other dimensions. + Therefore, if you ask for a dimension that is ragged, this function returns + a ValueError. For similar reasons, if a slice is selected that includes + a ragged dimension without including the zero dimension, then this fails. + + Any slice that does not start at zero will return a shape + with num_row_partitions == 0. + + Args: + index: the index: can be an int or a slice. + + Raises: + IndexError: if the index is not in range. + ValueError: if the rank is unknown, or a ragged rank is requested + incorrectly. + """ + rank = self.rank + if isinstance(index, slice): + + if (index.step is not None) and (index.step != 1): + raise IndexError("Cannot stride through a shape") + start = index.start + stop = index.stop + if start is None: + start = 0 + start = _fix_start_index(start, rank, self.num_row_partitions) + stop = _fix_stop_index(stop, rank) + return self._slice_shape(start, stop) + elif isinstance(index, int): + if index < 0: + if rank is None: + raise ValueError( + "Rank must be known to use __getitem__ with a negative index.") + return self._dimension(rank + index) + return self._dimension(index) + else: + raise TypeError("Argument is not an int or a slice") + + def _num_elements(self): + """Number of elements in a shape. + + Returns: + The number of elements in the shape. + + """ + return math_ops.reduce_prod(self.inner_shape) + + def _num_slices_in_dimension(self, axis): + """The total size of a dimension (like nvals). + + Effectively, this is self[:axis+1]._num_elements() + + Example: + shape = DynamicRaggedShape._from_inner_shape([2, 3, 4]) + shape._num_slices_in_dimension(0) = 2 + shape._num_slices_in_dimension(1) = 6 + shape._num_slices_in_dimension(2) = 24 + shape._num_slices_in_dimension(-1) = 24 + shape._num_slices_in_dimension(-2) = 6 + shape._num_slices_in_dimension(-2) = 2 + + Args: + axis: the last axis to include in the number of elements. If negative, + then axis = axis + rank. + + Returns: + The number of elements in the shape. + """ + if not isinstance(axis, int): + raise TypeError("axis must be an integer") + if axis < 0: + rank = self.rank + if rank is None: + raise ValueError( + "You can't use negative values if the rank is undefined") + axis = axis + rank + if axis == 0: + return self._dimension(0) + if axis <= self.num_row_partitions: + return self.row_partitions[axis - 1].nvals() + # If self.num_row_partitions = 1, and + # self.inner_shape=[3,5,6], and axis=2, then you want: + # 15 = 3 * 5 = math_ops.reduce_prod(self.inner_shape[:2]) + # 2 = axis - (self.num_row_partitions - 1) + # If num_row_partitions=0, and + # self.inner_shape=[3,5,6] and axis=2, then you want: + # 90 = 3 * 5 * 6 = math_ops.reduce_prod(self.inner_shape[:3]) + # 3 = axis - (self.num_row_partitions - 1) + remainder = axis - (self.num_row_partitions - 1) + return _reduce_prod_patch(self.inner_shape[:remainder]) + + def is_uniform(self, axis): + """Returns true if the indicated dimension is uniform.""" + if not isinstance(axis, int): + raise TypeError("axis must be an integer") + rank = self.rank + if axis < 0: + raise IndexError("Negative axis values are not supported") + elif rank is not None and axis >= rank: + raise IndexError("Expected axis=%s < rank=%s" % (axis, rank)) + else: + return ((axis == 0 or axis > len(self._row_partitions)) # pylint:disable=superfluous-parens + or self._row_partitions[axis - 1].is_uniform()) + + @property + def rank(self): + """The number of dimensions in this shape, or None if unknown.""" + inner_rank = self.inner_rank + if inner_rank is None: + return None + else: + return self.num_row_partitions + inner_rank + + @property + def inner_shape(self): + """The inner dimension sizes for this shape. + + Returns: + A 1-D integer `Tensor`. + """ + return self._inner_shape + + @property + def inner_rank(self): + """The rank of inner_shape.""" + return tensor_shape.dimension_value(self._static_inner_shape.rank) + + def _alt_inner_shape(self, new_inner_rank): + """Get an alternative inner shape with higher or lower rank. + + For the rank of the inner shape to be be higher, the last few ragged + dimensions must have uniform_row_length. + + Args: + new_inner_rank: the new rank of the inner_shape + + Returns: + A new inner_shape of rank new_inner_rank. + """ + if new_inner_rank == 0: + raise ValueError("new_inner_rank cannot be zero") + elif self.inner_rank == 0: + raise ValueError("old inner_rank cannot be zero") + elif new_inner_rank == self.inner_rank: + return self.inner_shape + elif new_inner_rank < self.inner_rank: + if self._static_inner_shape.is_fully_defined(): + return _alt_inner_shape_from_tensor_shape(self._static_inner_shape, + self.dtype, new_inner_rank) + first_dimension = self._num_slices_in_dimension(-new_inner_rank) + if new_inner_rank == 1: + return array_ops.expand_dims(first_dimension, 0) + remaining_dimensions = self.inner_shape[1 - new_inner_rank:] + return array_ops.concat( + [array_ops.expand_dims(first_dimension, 0), remaining_dimensions], + axis=0) + else: + assert new_inner_rank > self.inner_rank + new_dimensions = new_inner_rank - self.inner_rank + if any( + [not x.is_uniform() for x in self.row_partitions[-new_dimensions:]]): + raise ValueError("Cannot get an inner shape over a ragged dimension") + first_dimension = self._num_slices_in_dimension(-new_inner_rank) + new_dimensions = new_inner_rank - self.inner_rank + new_dims = [first_dimension] + [ + x.uniform_row_length() for x in self.row_partitions[-new_dimensions:] + ] + return array_ops.concat( + [array_ops_stack.stack(new_dims), self.inner_shape[1:]], axis=0) + + def _inner_shape_dim(self, dimension): + """Returns an int or a tensor representing _inner_shape[dimension].""" + result = tensor_shape.dimension_value(self._static_inner_shape[dimension]) + return self._inner_shape[dimension] if result is None else result + + def _with_inner_rank(self, inner_rank): + """Returns the same shape but a different inner_rank. + + All dimensions that are to be represented in the inner_shape must be dense. + See inner_rank. + + Args: + inner_rank: the new inner_rank of the shape. + + Returns: + the same shape but a different inner_rank + + Raises: + ValueError if the new dense rank is invalid, or the old rank is unknown. + """ + rank = self.rank + if rank is None: + raise ValueError("Rank must be known to adjust inner_rank") + elif rank < 2: + if inner_rank == rank: + return self + raise ValueError("Cannot change inner_rank if rank < 2") + else: + # When self.rank is not None: + # self.rank = self.inner_rank + self.num_row_partitions + new_num_row_partitions = rank - inner_rank + return self._with_num_row_partitions(new_num_row_partitions) + + def _with_num_row_partitions(self, num_row_partitions): + """Creates an identical shape with the given num_row_partitions. + + Note that the shape must be statically refactorable to this rank. + In particular: + * rank must be known. + * num_row_partitions must be a nonnegative int. + * num_row_partitions must be less than the rank of the shape + * num_row_partitions must be greater or equal to the index of any ragged + dimension. + + Note that if the num_row_partitions is the same, self is returned. + + Args: + num_row_partitions: the target num_row_partitions (must be a nonnegative + int). + + Returns: + a shape with a (possibly) different num_row_partitions. + + Raises: + ValueError: if the rank is unknown, the argument is not a nonnegative int, + or there is a dimension that is nonuniform. + """ + rank = self.rank + if rank is None: + raise ValueError("Rank must be known to adjust num_row_partitions") + if not isinstance(num_row_partitions, int): + raise ValueError("num_row_partitions must be an int") + if num_row_partitions < 0: + raise ValueError("num_row_partitions must be nonnegative") + if num_row_partitions == self.num_row_partitions: + return self + if num_row_partitions >= rank: + raise ValueError("num_row_partitions must be less than rank") + if num_row_partitions > self.num_row_partitions: + num_row_partitions_diff = num_row_partitions - self.num_row_partitions + new_inner_rank = self.rank - num_row_partitions + nvals = self._inner_shape_dim(0) + more_rp = [] + for i in range(num_row_partitions_diff): + nrows = nvals + row_length = self._inner_shape_dim(i + 1) + nvals = nrows * row_length + rp = RowPartition.from_uniform_row_length( + row_length, nrows=nrows, dtype=self.dtype) + more_rp.append(rp) + alt_inner = self._alt_inner_shape(new_inner_rank) + return DynamicRaggedShape(list(self.row_partitions) + more_rp, alt_inner) + else: + assert num_row_partitions < self.num_row_partitions + return DynamicRaggedShape( + self.row_partitions[:num_row_partitions], + self._alt_inner_shape(self.rank - num_row_partitions)) + + def _merge_dims(self, outer_axis: int, + inner_axis: int) -> "DynamicRaggedShape": + """Merges outer_axis...inner_axis into a single dimension. + + Returns a copy of this shape with the specified range of dimensions + flattened into a single dimension, with elements in row-major order. + + #### Examples: + + >>> tf.experimental.DynamicRaggedShape.from_lengths([2, (2,1), + ... (1,2,3)])._merge_dims(0, 1) + + >>> tf.experimental.DynamicRaggedShape.from_lengths([2, (2,1), + ... (1,2,3)])._merge_dims(1, 2) + + >>> tf.experimental.DynamicRaggedShape.from_lengths([2, (2,1), + ... (1,2,3)])._merge_dims(0, 2) + + + To mimic the behavior of `np.flatten` (which flattens all dimensions), use + `rt.merge_dims(0, -1). To mimic the behavior of `tf.layers.Flatten` (which + flattens all dimensions except the outermost batch dimension), use + `rt.merge_dims(1, -1)`. + + Args: + outer_axis: `int`: The first dimension in the range of dimensions to + merge. May be negative if `self.shape.rank` is statically known. + inner_axis: `int`: The last dimension in the range of dimensions to merge. + May be negative if `self.shape.rank` is statically known. + + Returns: + A copy of this shape, with the specified dimensions merged into a + single dimension. The returned shape will be + `self.shape[:outer_axis] + [N] + self.shape[inner_axis + 1:]`, where `N` + is the total number of slices in the merged dimensions. + """ + outer_axis = array_ops.get_positive_axis( + outer_axis, self.rank, axis_name="outer_axis", ndims_name="rank(self)") + inner_axis = array_ops.get_positive_axis( + inner_axis, self.rank, axis_name="inner_axis", ndims_name="rank(self)") + if not outer_axis <= inner_axis: + raise ValueError(f"Expected outer_axis ({outer_axis}) to be less than or " + f"equal to inner_axis ({inner_axis}).") + if outer_axis == inner_axis: + return self + if self.num_row_partitions == 0: + # A dense tensor. + (new_inner_shape, + new_static_inner_shape) = _merge_inner_shape(self._inner_shape, + self._static_inner_shape, + outer_axis, inner_axis) + return DynamicRaggedShape([], + new_inner_shape, + dtype=self.dtype, + static_inner_shape=new_static_inner_shape) + if inner_axis <= self.num_row_partitions: + # Here, we are merging the row_partitions, + # but the inner_shape is unchanged. + if outer_axis == 0: + # There is no need to merge axes before the first, just truncate them. + return DynamicRaggedShape( + self._row_partitions[inner_axis:], + self.inner_shape, + dtype=self.dtype, + static_inner_shape=self._static_inner_shape) + prefix_rp = self._row_partitions[:outer_axis - 1] + suffix_rp = self._row_partitions[inner_axis:] + internal_rp = self._row_partitions[outer_axis - 1:inner_axis] + new_rp = prefix_rp + (_merge_row_partitions(internal_rp),) + suffix_rp + + return DynamicRaggedShape( + new_rp, + self.inner_shape, + dtype=self.dtype, + static_inner_shape=self._static_inner_shape) + elif outer_axis > self.num_row_partitions: + # In this scenario, only the inner_shape is changed. + # Example #1: + # if [2, (1, 2), 5, 3], num_row_partitions=1, outer_axis=2, inner_axis=3. + # Result: [2, (1, 2), 15], num_row_partitions=1, outer_axis=2, + # inner_axis=3. + (new_inner_shape, new_static_inner_shape) = _merge_inner_shape( + self._inner_shape, self._static_inner_shape, + outer_axis - self.num_row_partitions, + inner_axis - self.num_row_partitions) + return DynamicRaggedShape( + self._row_partitions, + new_inner_shape, + dtype=self.dtype, + static_inner_shape=new_static_inner_shape) + else: + # Here, both inner_shape and row_partitions are changed. + rank = self.rank + if rank is None: + raise ValueError("Cannot merge_dims of the inner shape if the " + + "dimension of inner_shape is unknown") + if outer_axis == 0: + new_inner_shape = self._alt_inner_shape(rank - inner_axis) + return DynamicRaggedShape._from_inner_shape(new_inner_shape) + else: + prefix = self._row_partitions[:outer_axis - 1] + suffix = _merge_row_partitions(self._row_partitions[outer_axis - 1:]) + new_inner_shape = self._alt_inner_shape(rank - inner_axis) + num_merged_inner = inner_axis - self.num_row_partitions + prod = _reduce_prod_patch(self._inner_shape[1:num_merged_inner + 1]) + tail_suffix = RowPartition.from_row_splits(suffix.row_splits() * prod) + return DynamicRaggedShape(prefix + (tail_suffix,), new_inner_shape) + + def with_dtype(self, dtype): + """Change the dtype of the shape.""" + if dtype == self.dtype: + return self + else: + return DynamicRaggedShape( + self.row_partitions, self.inner_shape, dtype=dtype) + + def _merge_with(self, other: "DynamicRaggedShape") -> "DynamicRaggedShape": + """Merge two shapes that are equal modulo num_row_partitions. + + The resulting num_row_partitions is the maximum of the two + num_row_partitions. + + Args: + other: a DynamicRaggedShape representing the same shape with a possibly + different number of row partitions. + + Returns: + A DynamicRaggedShape with the same shape and the maximum of the + num_row_partitions of the two shapes. + """ + max_num_row_partitions = max(self.num_row_partitions, + other.num_row_partitions) + a = self._with_num_row_partitions(max_num_row_partitions) + b = other._with_num_row_partitions(max_num_row_partitions) + new_row_partitions = [ + rp_a._merge_precomputed_encodings(rp_b) + for (rp_a, rp_b) in zip(a._row_partitions, b._row_partitions) + ] + new_dtype = b.dtype if a.dtype == dtypes.int32 else dtypes.int64 + + new_static_inner_shape = a._static_inner_shape.merge_with( + b._static_inner_shape) + new_inner_shape = a._inner_shape + return DynamicRaggedShape(new_row_partitions, new_inner_shape, new_dtype, + True, new_static_inner_shape) + + def _merge_with_spec( + self, other: "DynamicRaggedShape.Spec") -> "DynamicRaggedShape": + """Merge a spec with a DynamicRaggedShape.""" + # TODO(martinz): add tests for dynamic inconsistencies. + max_num_row_partitions = max(self.num_row_partitions, + other.num_row_partitions) + a = self._with_num_row_partitions(max_num_row_partitions) + b = other._with_num_row_partitions(max_num_row_partitions) + new_row_partitions = [ + rp_a._merge_with_spec(rp_b) + for (rp_a, rp_b) in zip(a._row_partitions, b._row_partitions) + ] + new_dtype = b.dtype if a.dtype == dtypes.int32 else dtypes.int64 + + new_static_inner_shape = a._static_inner_shape.merge_with( + b._static_inner_shape) + new_inner_shape = a._inner_shape + return DynamicRaggedShape(new_row_partitions, new_inner_shape, new_dtype, + True, new_static_inner_shape) + + def _as_row_partitions(self): + """Returns row partitions representing this shape. + + In order to represent a shape as row partitions, the rank of the shape + must be known, and the shape must have rank at least one. + + Returns: + A list of RowPartition objects. + Raises: + ValueError, if the shape cannot be represented by RowPartitions. + """ + rank = self.rank + if rank is None: + raise ValueError("rank must be known for _as_row_partitions") + elif rank < 1: + raise ValueError("rank must be >= 1 for _as_row_partitions") + fully_ragged = self._with_num_row_partitions(rank - 1) + return fully_ragged.row_partitions + + def _validate_flat_values_dynamically(self, flat_values): + """Test if flat_values have the right nvals dynamically.""" + if self.row_partitions: + assert_op = check_ops.assert_equal( + self.row_partitions[-1].nvals(), + array_ops.shape(flat_values, out_type=self.dtype)[0], + message="Last row partition does not match flat_values.") + return control_flow_ops.with_dependencies([assert_op], flat_values) + return flat_values + + def _validate_flat_values(self, flat_values): + """Test if flat_values have the right nvals.""" + if not isinstance(flat_values, tensor_lib.Tensor): + return flat_values + if self.row_partitions: + last_row_partition = self.row_partitions[-1] + flat_values_shape = flat_values.shape + if flat_values_shape is None: + return self._validate_flat_values_dynamically(flat_values) + first_dim_flat_values = flat_values_shape[0] + if isinstance(first_dim_flat_values, tensor_shape.Dimension): + first_dim_flat_values = first_dim_flat_values.value + if first_dim_flat_values is None: + return self._validate_flat_values_dynamically(flat_values) + static_nvals = last_row_partition.static_nvals + if static_nvals is None: + return self._validate_flat_values_dynamically(flat_values) + if first_dim_flat_values != static_nvals: + raise ValueError("Last row partition does not match flat_values.") + return flat_values + + def _add_row_partitions(self, flat_values, validate=False): + """Add row partitions to flat_values, if necessary. + + If the shape is truly ragged, then this adds the row_partitions. + + The shape is dense, then this just returns flat_values. + + Args: + flat_values: the flat_values of a ragged tensor with this shape, or a + dense tensor with this shape. + validate: validate the flat_values have the right first dimension. + + Returns: + flat_values reshaped to have row_partitions. + """ + if self.row_partitions: + if validate: + flat_values = self._validate_flat_values(flat_values) + return ragged_tensor.RaggedTensor._from_nested_row_partitions( + flat_values, self.row_partitions, validate=False) + else: + return flat_values + + class Spec: + """A Spec for DynamicRaggedShape: similar to a static shape.""" + + def __init__(self, row_partitions: Tuple[RowPartitionSpec, ...], + static_inner_shape: tensor_shape.TensorShape, + dtype: dtypes.DType): + """Create a Spec given row partitions, a static inner shape, and a dtype. + + Args: + row_partitions: A sequence of `RowPartitionSpec`s describing how the + ragged shape is partitioned. + static_inner_shape: The static shape of the flat_values. + dtype: The DType used to encode the shape (tf.int64 or tf.int32). + """ + # Independent validation and coercion of each argument. + if not isinstance(row_partitions, Iterable): + raise TypeError("row_partitions should be an Iterable") + + row_partitions = tuple(row_partitions) + + static_inner_shape = tensor_shape.as_shape(static_inner_shape) + + dtype = dtypes.as_dtype(dtype) + + if not all(isinstance(rp, RowPartitionSpec) for rp in row_partitions): + raise TypeError( + "row_partitions should be an Iterable of RowPartitionSpecs") + + if dtype != dtypes.int32 and dtype != dtypes.int64: + raise ValueError("dtype must be tf.int32 or tf.int64") + + # All fields are now typechecked and internally consistent. + for spec in row_partitions: + if spec.dtype != dtype: + raise ValueError( + f"dtype of {spec!r} is {spec.dtype!r}: expected {dtype!r}") + + row_partitions = tuple(row_partitions) + + inner_rank = static_inner_shape.rank + + if inner_rank == 0: + if row_partitions: + raise ValueError( + "If row_partitions are provided, must have inner_rank > 0") + else: + num_slices_in_dimension = [] # type: Sequence[tensor_shape.Dimension] + + # We first attempt to calculate num_slices_in_dimension through a + # forward pass, using nrows[k] = nrows[k-1] * uniform_row_length + # and other tricks. + for i in range(len(row_partitions)): + rp = row_partitions[i] + result = tensor_shape.Dimension(rp.nrows) + if i > 0: + previous_rp = row_partitions[i - 1] + result = result.merge_with(previous_rp.nvals) + result = result.merge_with(num_slices_in_dimension[-1] * + previous_rp.uniform_row_length) + num_slices_in_dimension.append(result) + # In the last step of the forward pass, + # we combine nvals and the first dimension in static_inner_shape. + if row_partitions: + last_rp = row_partitions[-1] + result = (num_slices_in_dimension[-1] * + last_rp.uniform_row_length).merge_with(last_rp.nvals) + if inner_rank is not None: + result = result.merge_with( + tensor_shape.dimension_at_index(static_inner_shape, 0)) + static_inner_shape = result + static_inner_shape[1:] + num_slices_in_dimension.append(result) + + # Now, we start a backward pass. + for i in range(len(num_slices_in_dimension) - 1, 0, -1): + num_slices_in_dimension[i - 1] = num_slices_in_dimension[ + i - 1].merge_with( + _safe_floor_div(num_slices_in_dimension[i], + row_partitions[i - 1].uniform_row_length)) + + # Finally, we construct the partitions. + row_partitions = [ + RowPartitionSpec( # pylint: disable=g-complex-comprehension + nrows=num_slices_in_dimension[i].value, + uniform_row_length=rp.uniform_row_length, + nvals=num_slices_in_dimension[i + 1].value, + dtype=rp.dtype) for i, rp in enumerate(row_partitions) + ] + + self._static_inner_shape = static_inner_shape + self._inner_shape = tensor_lib.TensorSpec([inner_rank], dtype=dtype) + self._row_partitions = row_partitions + + def __repr__(self): + return ( + f"DynamicRaggedShape.Spec(row_partitions={self._row_partitions!r}, " + + f"static_inner_shape={self._static_inner_shape!r}, " + + f"dtype={self.dtype!r})") + + @classmethod + def from_value(cls, value: Any) -> "DynamicRaggedShape.Spec": + """Create a Spec from a DynamicRaggedShape.""" + # super().from_value(...) creates an object, but there is no validation. + # No methods can be trusted on the object, just the properties. + initial = super(DynamicRaggedShape.Spec, cls).from_value(value) + + # However, since value is a DynamicRaggedShape, we + # can guarantee that initial._inner_shape.shape.rank == 1 + + # Moreover, if inner_shape.shape[0] is not None, then + # static_inner_shape.rank is not None. + + return DynamicRaggedShape.Spec( + row_partitions=initial._row_partitions, + static_inner_shape=initial._static_inner_shape, + dtype=initial._inner_shape.dtype) + + # TODO(martinz): it is unclear what the default uniformity of RowPartitions + # should be, so I am moving this to experimental until we figure it out. + # Also, while I have specified this is meant to represent a shape of a + # proper Tensor instead of a RaggedTensor, this is also subject to + # interpretation. + @classmethod + def _from_tensor_shape(cls, shape: Any, num_row_partitions: int, + dtype: dtypes.DType) -> "DynamicRaggedShape.Spec": + """Creates a `DynamicRaggedShape.Spec` corresponding to a `tf.TensorShape`. + + It is assumed that this is a `tf.TensorShape` coming from a + `tf.TensorSpec`, not from `RaggedTensor.shape`. + + In addition to the shape, we need to know the number of row partitions, + and the dtype used in the shape (tf.int32 or tf.int64). + + Within the dimensions that are partitioned, all dimensions are assumed + to be uniform. + + Args: + shape: a TensorShape. + num_row_partitions: the ragged rank of the RaggedShape. + dtype: the dtype of the shape (not the tensor); tf.int64 or tf.int32. + + Returns: + a DynamicRaggedShape.Spec representing a TensorShape. + """ + if dtype != dtypes.int32 and dtype != dtypes.int64: + raise ValueError("dtype must be tf.int32 or tf.int64") + + shape = tensor_shape.as_shape(shape) + if shape.rank is None: + row_partitions = [ + RowPartitionSpec(dtype=dtype) for _ in range(num_row_partitions) + ] + return DynamicRaggedShape.Spec( + row_partitions=row_partitions, + static_inner_shape=tensor_shape.TensorShape(None), + dtype=dtype) + + if shape.rank <= 1: + # Create a scalar or vector shape. + if num_row_partitions: + raise ValueError("num_row_partitions should be zero " + + "if shape is a scalar or vector.") + return DynamicRaggedShape.Spec( + row_partitions=[], static_inner_shape=shape, dtype=dtype) + + if shape.rank <= num_row_partitions: + raise ValueError("num_row_partitions must be less than rank") + + num_elements_so_far = tensor_shape.dimension_value(shape[0]) + rp_specs = [] + for i in range(num_row_partitions): + current_dim = tensor_shape.dimension_value(shape[i + 1]) + if current_dim is None or num_elements_so_far is None: + nvals = None + else: + nvals = num_elements_so_far * current_dim + rp_specs.append( + RowPartitionSpec( + nrows=num_elements_so_far, + nvals=nvals, + uniform_row_length=current_dim, + dtype=dtype)) + num_elements_so_far = nvals + + static_inner_shape = tensor_shape.TensorShape( + [num_elements_so_far]) + shape[num_row_partitions + 1:] + return DynamicRaggedShape.Spec( + row_partitions=rp_specs, + static_inner_shape=static_inner_shape, + dtype=dtype) + + @classmethod + def _from_spec( + cls, + spec: Union["DynamicRaggedShape.Spec", ragged_tensor.RaggedTensorSpec, + tensor_lib.TensorSpec], + dtype: dtypes.DType = dtypes.int64) -> "DynamicRaggedShape.Spec": + """Create a TypeSpec for the shape of an object with a given TypeSpec. + + I.e., if `x_spec = tf.type_spec_from_value(x)`, then + `DynamicRaggedShape.from_spec(x_spec)` returns a TypeSpec compatible with + `tf.type_spec_from_value(tf.shape(x))`. + + >>> rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) + >>> rt_spec = tf.type_spec_from_value(rt) + >>> rt_shape = DynamicRaggedShape.from_tensor(rt) + + >>> shape_spec_1 = tf.type_spec_from_value(rt_shape) + >>> shape_spec_2 = DynamicRaggedShape.Spec._from_spec(rt_spec) + >>> assert shape_spec_1.is_compatible_with(shape_spec_2) + + Args: + spec: a Spec of a Tensor or RaggedTensor. + dtype: the default dtype (if necessary). + + Returns: + A Spec of the shape of a Tensor or RaggedTensor. + + """ + # TODO(martinz): Add StructuredTensor.Spec when its easy. + if isinstance(spec, DynamicRaggedShape.Spec): + return spec + elif isinstance(spec, ragged_tensor.RaggedTensorSpec): + return cls._from_tensor_shape(spec.shape, spec.ragged_rank, + spec.row_splits_dtype) + elif isinstance(spec, tensor_lib.TensorSpec): + return cls._from_tensor_shape( + shape=spec.shape, num_row_partitions=0, dtype=dtype) + + @property + def dtype(self) -> dtypes.DType: + return self._inner_shape.dtype + + @property + def inner_rank(self) -> Optional[int]: + if self._static_inner_shape.rank is not None: + return self._static_inner_shape.rank + if self._inner_shape.shape.rank is None: + return None + return tensor_shape.dimension_value(self._inner_shape.shape[0]) + + @property + def num_row_partitions(self) -> int: + return len(self._row_partitions) + + @property + def rank(self) -> Optional[int]: + inner_rank = self.inner_rank + return None if inner_rank is None else inner_rank + self.num_row_partitions + + def _dimension(self, index: int) -> Optional[int]: + """Get the size of dimension index, if known statically.""" + if index == 0: + if self._row_partitions: + return self._row_partitions[0].nrows + elif self.inner_rank is None: + return None + elif self.inner_rank == 0: + raise ValueError("Index out of range: 0.") + else: + return tensor_shape.dimension_value(self._static_inner_shape[0]) + if index <= len(self._row_partitions): + return self._row_partitions[index - 1].uniform_row_length + + relative_index = index - self.num_row_partitions + + if self.inner_rank is None: + return None + elif self.inner_rank <= relative_index: + raise ValueError(f"Index out of range: {index}.") + else: + return tensor_shape.dimension_value( + self._static_inner_shape[relative_index]) + + def _num_slices_in_dimension(self, axis: int) -> Optional[int]: + """The total size of a dimension (like nvals). + + This is a static version of DynamicRaggedShape._num_slices_in_dimension() + + Example: + + ``` + shape = DynamicRaggedShape.Spec( + _row_partitions=[ + RowPartitionSpec(nrows=3, nvals=14, dtype=tf.int32) + RowPartitionSpec(nrows=14, nvals=25, dtype=tf.int32) + + ], + _static_inner_shape=tf.TensorShape([25, 3, 4]), + _inner_shape=tf.TensorSpec(tf.TensorShape([3]), dtype=tf.int32)) + shape._num_slices_in_dimension(0) = 3 + shape._num_slices_in_dimension(1) = 14 + shape._num_slices_in_dimension(2) = 25 + shape._num_slices_in_dimension(3) = 3 + shape._num_slices_in_dimension(4) = 4 + shape._num_slices_in_dimension(-2) = 3 + ``` + + Args: + axis: the last dimension to include. + + Returns: + the number of values in a dimension. + """ + if not isinstance(axis, int): + raise TypeError("axis must be an integer") + axis = array_ops.get_positive_axis(axis, self.rank, ndims_name="rank") + + if axis == 0: + return self._dimension(0) + if axis <= self.num_row_partitions: + # TODO(martinz): use nvals OR nrows, whichever is defined. + return self._row_partitions[axis - 1].nvals + remainder = axis - (self.num_row_partitions - 1) + head_inner_shape = self._static_inner_shape[:remainder] + return head_inner_shape.num_elements() + + def with_dtype(self, dtype: dtypes.DType) -> "DynamicRaggedShape.Spec": + """Return the same spec, but with a different DType.""" + new_rp_specs = [rp.with_dtype(dtype) for rp in self._row_partitions] + return DynamicRaggedShape.Spec( + row_partitions=new_rp_specs, + static_inner_shape=self._static_inner_shape, + dtype=dtype) + + def _merge_with( + self, other: "DynamicRaggedShape.Spec") -> "DynamicRaggedShape.Spec": + """Merges all information between two specs. + + Specs are expected to represent the same information modulo + num_row_partitons. + + If the specs are of different ranks, then fail. + + Args: + other: another Spec of the same rank. + + Returns: + a Spec with the union of information. + """ + max_num_row_partitions = max(self.num_row_partitions, + other.num_row_partitions) + a = self._with_num_row_partitions(max_num_row_partitions) + b = other._with_num_row_partitions(max_num_row_partitions) + + new_rp = [ + a._merge_with(b) + for (a, b) in zip(a._row_partitions, b._row_partitions) + ] + + new_static_inner_shape = a._static_inner_shape.merge_with( + b._static_inner_shape) + + dtype = b.dtype if (a.dtype == dtypes.int32) else dtypes.int64 + + return DynamicRaggedShape.Spec( + new_rp, new_static_inner_shape, dtype=dtype) + + def _with_num_row_partitions( + self, new_num_row_partitions: int) -> "DynamicRaggedShape.Spec": + """Change the number of row partitions in the spec.""" + rank = self.rank + if rank is None: + raise ValueError( + "Changing num_row_partitions with unknown rank unsupported") + if new_num_row_partitions > max(rank - 1, 0): + raise ValueError("Number of row partitions too large") + if new_num_row_partitions < 0: + raise ValueError("Number of row partitions negative") + if self.num_row_partitions == new_num_row_partitions: + return self + elif self.num_row_partitions < new_num_row_partitions: + # TODO(martinz): Consider swapping. + rp_delta = new_num_row_partitions - self.num_row_partitions + tail_shape = DynamicRaggedShape.Spec._from_tensor_shape( + self._static_inner_shape, rp_delta, self.dtype) + return DynamicRaggedShape.Spec( + row_partitions=self._row_partitions + tail_shape._row_partitions, + static_inner_shape=tail_shape._static_inner_shape, + dtype=self.dtype) + else: + assert self.num_row_partitions > new_num_row_partitions + new_row_partitions = self._row_partitions[:new_num_row_partitions] + last_row_partition = new_row_partitions[-1] + old_row_partitions = self._row_partitions[new_num_row_partitions:] + new_static_inner_shape = ( + tensor_shape.TensorShape( + [last_row_partition.nvals] + + [x.uniform_row_length for x in old_row_partitions]) + + self._static_inner_shape[1:]) + return DynamicRaggedShape.Spec(new_row_partitions, + new_static_inner_shape, self.dtype) + + def _set_rank_if_unknown(self, new_rank: int) -> "DynamicRaggedShape.Spec": + """Ensures this has a known rank at least new_rank.""" + if new_rank is None: + raise TypeError("new_rank is None, but expected int") + if new_rank < 0: + raise ValueError("Rank must be non-negative") + current_rank = self.rank + if current_rank is not None and current_rank < new_rank: + raise ValueError( + "Rank is {current_rank}, expected at least {new_rank}.".format( + current_rank=current_rank, new_rank=new_rank)) + + if current_rank is not None: + return self + + if self._row_partitions: + new_inner_rank = max(new_rank - self.num_row_partitions, 1) + first_dim = self._row_partitions[-1].nvals + static_inner_shape = tensor_shape.TensorShape([first_dim] + [None] * + (new_inner_rank - 1)) + else: + static_inner_shape = tensor_shape.TensorShape([None] * new_rank) + + return DynamicRaggedShape.Spec( + row_partitions=self._row_partitions, + static_inner_shape=static_inner_shape, + dtype=self.dtype) + + def _truncate(self, new_rank: int) -> "DynamicRaggedShape.Spec": + """Truncate a ragged shape spec. + + For example, if the original spec s was for a shape: + [3, [4, 1], 2, 7] + + Then truncate_dynamic_ragged_shape_spec(s, 3) is a spec for: + [3, [4, 1], 2] + + Args: + new_rank: the new rank + + Returns: + A truncated DynamicRaggedShape.Spec. + """ + if self.rank is None: + return self._set_rank_if_unknown(new_rank)._truncate(new_rank) + + if new_rank == 0: + return DynamicRaggedShape.Spec._from_tensor_shape([], 0, self.dtype) + + if new_rank == 1: + vector_size = self._dimension(0) + return DynamicRaggedShape.Spec._from_tensor_shape([vector_size], 0, + self.dtype) + + if new_rank < self.num_row_partitions + 1: + new_row_partitions = self._row_partitions[:new_rank - 1] + new_static_inner_shape = tensor_shape.TensorShape( + [new_row_partitions[-1].nvals]) + return DynamicRaggedShape.Spec( + row_partitions=new_row_partitions, + static_inner_shape=new_static_inner_shape, + dtype=self.dtype) + else: + remainder = new_rank - self.num_row_partitions + new_static_inner_shape = self._static_inner_shape[:remainder] + return DynamicRaggedShape.Spec( + row_partitions=self._row_partitions, + static_inner_shape=new_static_inner_shape, + dtype=self.dtype) + + def _to_tensor_shape(self): + """Get a tensor shape corresponding to this type.""" + alt = self + if alt._static_inner_shape.rank is None: + return tensor_shape.TensorShape(None) + if alt._static_inner_shape.rank == 0: + assert not alt._row_partitions + return alt._static_inner_shape + prefix = [alt._dimension(0)] + prefix.extend([rp.uniform_row_length for rp in alt._row_partitions]) + suffix = alt._static_inner_shape[1:] + return tensor_shape.TensorShape(prefix) + suffix + + +def broadcast_dynamic_shape(shape_x: DynamicRaggedShape, + shape_y: DynamicRaggedShape) -> DynamicRaggedShape: + """Returns the shape formed by broadcasting two shapes to be compatible. + + 1. If shape_x and shape_y both have row_partitions, then fail if their dtypes + don't match. + 2. If neither has row_partitions and they have different dtypes, + go with int64. + 3. If one has row_partitions, go with that dtype. + + Args: + shape_x: A `DynamicRaggedShape` + shape_y: A `DynamicRaggedShape` + + Returns: + A `DynamicRaggedShape`. + Raises: + ValueError: If `shape_x` and `shape_y` are not broadcast-compatible. + """ + if not isinstance(shape_x, DynamicRaggedShape): + raise TypeError("shape_x must be a DynamicRaggedShape") + if not isinstance(shape_y, DynamicRaggedShape): + raise TypeError("shape_y must be a DynamicRaggedShape") + + return broadcast_dynamic_shape_extended(shape_x, shape_y)[0] + + +def broadcast_to(rt_input, shape: DynamicRaggedShape): + """Broadcasts a potentially ragged tensor to a ragged shape. + + Tiles `rt_input` as necessary to match the given shape. + + Behavior is undefined if `rt_input` is not broadcast-compatible with `shape`. + + Args: + rt_input: The potentially ragged tensor to broadcast. + shape: A `DynamicRaggedShape` + + Returns: + A potentially ragged tensor whose values are taken from + `rt_input`, and whose shape matches `shape`. + """ + if not isinstance(shape, DynamicRaggedShape): + raise TypeError("shape must be a DynamicRaggedShape") + rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input) + origin_shape = None + if ragged_tensor.is_ragged(rt_input): + if shape.num_row_partitions != 0: + if rt_input.row_splits.dtype != shape.dtype: + raise ValueError("Cannot coerce row_splits.dtype") + else: + shape = shape.with_dtype(rt_input.row_splits.dtype) + origin_shape = DynamicRaggedShape.from_tensor(rt_input) + else: + if shape.num_row_partitions != 0: + origin_shape = DynamicRaggedShape.from_tensor(rt_input, dtype=shape.dtype) + else: + origin_shape = DynamicRaggedShape.from_tensor( + rt_input, dtype=dtypes.int64) + shape = shape.with_dtype(dtype=dtypes.int64) + + broadcaster = _get_broadcaster(origin_shape, shape) + return broadcaster.broadcast(rt_input) + + +def broadcast_dynamic_shape_extended( + a: DynamicRaggedShape, b: DynamicRaggedShape +): # -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster] + """Gets the smallest shape to which a and b can broadcast. + + In order to create the smallest shape, one must also do most of the + work to figure out how to transform from the shapes given. Thus, in addition + to returning the shape, it also creates transformations from the + original shapes to the result. + + This is the equivalent of: + + c = broadcast_dynamic_shape(a, b) + ac = get_broadcaster(a, c) + bc = get_broadcaster(b, c) + return (c, ac, bc) + + Args: + a: a DynamicRaggedShape + b: a DynamicRaggedShape + + Returns: + A triple of a shape and two broadcasters. + """ + if a.row_partitions and b.row_partitions: + if a.dtype != b.dtype: + raise ValueError("Dtypes don't match") + elif a.dtype != b.dtype: + if a.row_partitions: + b = b.with_dtype(a.dtype) + elif b.row_partitions: + a = a.with_dtype(b.dtype) + else: + a = a.with_dtype(dtypes.int64) + b = b.with_dtype(dtypes.int64) + + if (a.rank is None or b.rank is None): + raise ValueError("Unable to broadcast: unknown rank") + elif a.rank == 0: + return (b, _Broadcaster(a, b, []), _get_identity_broadcaster(b)) + elif b.rank == 0: + return (a, _get_identity_broadcaster(a), _Broadcaster(b, a, [])) + elif a.rank == 1 and b.rank == 1: + [a_layer, b_layer, + target] = _broadcast_dynamic_shape_one_layer(a.inner_shape, b.inner_shape) + target_shape = DynamicRaggedShape._from_inner_shape(target) # pylint: disable=protected-access + return (target_shape, _Broadcaster(a, target_shape, [a_layer]), + _Broadcaster(b, target_shape, [b_layer])) + + if a.rank > b.rank: + (c, bc, ac) = _broadcast_dynamic_shape_extended_helper(b, a) # pylint: disable=arguments-out-of-order + + return (c, ac, bc) + + return _broadcast_dynamic_shape_extended_helper(a, b) + + +def _row_partitions_identical(shape_a, shape_b): + """Returns True iff all row_partitions in shapes are identical.""" + return ((shape_a.num_row_partitions == shape_b.num_row_partitions) and all( + a is b for a, b in zip(shape_a.row_partitions, shape_b.row_partitions))) + + +# TODO(martinz): Preserve shapes better (see CL/414806185) +@dispatch.dispatch_for_binary_elementwise_apis(ragged_tensor.RaggedOrDense, + ragged_tensor.RaggedOrDense) +def ragged_binary_elementwise_op_impl(op, x, y): + """Binary elementwise api handler for RaggedTensors.""" + x_is_ragged = ragged_tensor.is_ragged(x) + y_is_ragged = ragged_tensor.is_ragged(y) + + # Convert args to tensors. + x = ragged_tensor.convert_to_tensor_or_ragged_tensor( + x, preferred_dtype=(y.dtype if y_is_ragged else None)) + y = ragged_tensor.convert_to_tensor_or_ragged_tensor( + y, preferred_dtype=x.dtype) + + if x_is_ragged and y_is_ragged: + x, y = ragged_tensor.match_row_splits_dtypes(x, y) + + if ((x_is_ragged and y_is_ragged) or + (x_is_ragged and x.flat_values.shape.ndims <= y.shape.ndims) or + (y_is_ragged and y.flat_values.shape.ndims <= x.shape.ndims)): + shape_x = DynamicRaggedShape.from_tensor(x) + shape_y = DynamicRaggedShape.from_tensor(y) + if shape_x.dtype != shape_y.dtype: + if not x_is_ragged: + shape_x = shape_x.with_dtype(shape_y.dtype) + elif not y_is_ragged: + shape_y = shape_y.with_dtype(shape_x.dtype) + + if _row_partitions_identical(shape_x, shape_y): + # At this point, both x and y must be ragged. + return shape_x._add_row_partitions( # pylint: disable=protected-access + op(x.flat_values, y.flat_values), + validate=False) + + (shape_z, bcast_xz, + bcast_yz) = broadcast_dynamic_shape_extended(shape_x, shape_y) + x_new_flat = bcast_xz.broadcast_flat_values(x, inner_dimensions=False) + y_new_flat = bcast_yz.broadcast_flat_values(y, inner_dimensions=False) + z_flat = op(x_new_flat, y_new_flat) + return shape_z._add_row_partitions(z_flat, validate=True) # pylint: disable=protected-access + + x_values = x.flat_values if ragged_tensor.is_ragged(x) else x + y_values = y.flat_values if ragged_tensor.is_ragged(y) else y + mapped_values = op(x_values, y_values) + if isinstance(mapped_values, bool): + return mapped_values # Special case for tensor_equals. + if ragged_tensor.is_ragged(x): + return x.with_flat_values(mapped_values) + else: + return y.with_flat_values(mapped_values) + + +@dispatch.dispatch_for_binary_elementwise_assert_apis( + ragged_tensor.RaggedOrDense, ragged_tensor.RaggedOrDense) +def ragged_binary_elementwise_assert_op_impl(op, x, y): + """Binary elementwise assert api handler for RaggedTensors. + + This handles binary assert operations for ragged tensors. Compared with + `ragged_binary_elementwise_op_impl`, this handler does not compute a ragged + tensor as output. Instead, it applies the assert operation `op` to input + tensors based on their ragged shapes and flat_values, and returns the result + of the assertion operation. + + Args: + op: a binary assert operation on Tensors. + x: something that can be coerced to a Tensor or RaggedTensor. + y: something that can be coerced to a Tensor or RaggedTensor. + + Returns: + the result of the assertion operation. + + """ + x_is_ragged = ragged_tensor.is_ragged(x) + y_is_ragged = ragged_tensor.is_ragged(y) + + # Convert args to tensors. + x = ragged_tensor.convert_to_tensor_or_ragged_tensor( + x, preferred_dtype=(y.dtype if y_is_ragged else None)) + y = ragged_tensor.convert_to_tensor_or_ragged_tensor( + y, preferred_dtype=x.dtype) + + if x_is_ragged and y_is_ragged: + x, y = ragged_tensor.match_row_splits_dtypes(x, y) + + if ((x_is_ragged and y_is_ragged) or + (x_is_ragged and x.flat_values.shape.ndims <= y.shape.ndims) or + (y_is_ragged and y.flat_values.shape.ndims <= x.shape.ndims)): + shape_x = DynamicRaggedShape.from_tensor(x) + shape_y = DynamicRaggedShape.from_tensor(y) + if shape_x.dtype != shape_y.dtype: + if not x_is_ragged: + shape_x = shape_x.with_dtype(shape_y.dtype) + elif not y_is_ragged: + shape_y = shape_y.with_dtype(shape_x.dtype) + + if _row_partitions_identical(shape_x, shape_y): + # At this point, both x and y must be ragged. + return op(x.flat_values, y.flat_values) + + (_, bcast_xz, bcast_yz) = broadcast_dynamic_shape_extended(shape_x, shape_y) + x_new_flat = bcast_xz.broadcast_flat_values(x, inner_dimensions=False) + y_new_flat = bcast_yz.broadcast_flat_values(y, inner_dimensions=False) + return op(x_new_flat, y_new_flat) + + x_values = x.flat_values if ragged_tensor.is_ragged(x) else x + y_values = y.flat_values if ragged_tensor.is_ragged(y) else y + return op(x_values, y_values) + + +def _find_dtype_helper(value, preferred): + """Helper for _find_dtype.""" + if preferred is not None: + return preferred + elif isinstance(value, RowPartition): + return value.dtype + elif isinstance(value, dtypes.DType): + return value + elif isinstance(value, int): + return None + elif isinstance(value, list): + return None + elif isinstance(value, tuple): + return None + elif isinstance(value, core.Tensor): + return value.dtype + return value.dtype + + +def _find_dtype(value, preferred): + """Returns the preferred dtype of value or preferred if preferred != None. + + This is used as an operator to pass over multiple objects in decreasing order + of priority until there is a preferred dtype for one. For example, if you were + adding three tensor-ish things (some tensors, some lists), and needed a + preferred dtype, you could use this as: + + def adding(a, b, c, dtype = None): + dtype = _find_dtype(a, dtype) + dtype = _find_dtype(b, dtype) + dtype = _find_dtype(c, dtype) + if dtype is None: + dtype = tf.float32 + ...Code continues here... + + Args: + value: a list, value, RowPartition, or tensor. + preferred: a given dtype. If not None, this will be returned. + + Returns: + an optional dtype. + """ + result = _find_dtype_helper(value, preferred) + if (result == dtypes.int64 or result == dtypes.int32 or result is None): + return result + raise ValueError("Illegal dtype: " + str(result)) + + +def _find_dtype_iterable( + iterable: Iterable[Any], + dtype: Optional[dtypes.DType]) -> Optional[dtypes.DType]: + """Find the preferred dtype of a list of objects. + + This will go over the iterable, and use the first object with a preferred + dtype. The dtype passed has highest priority if it is not None. + + Args: + iterable: an iterable with things that might have a dtype. + dtype: an overriding dtype, or None. + + Returns: + an optional dtype. + """ + if dtype is not None: + return dtype + for x in iterable: + dtype = _find_dtype(x, dtype) + return dtype + + +class _LayerBroadcaster(abc.ABC): + """A broadcaster of a single layer. + + Although this class does not literally contain a gather_index, the reference + implementation is defined through a gather_index. Thus, any subclasses should + first define the gather_index property. Other functions can be overridden + for optimization, but it should not change the behavior. + """ + + @property + @abc.abstractmethod + def gather_index(self): + """Returns a 1D tensor. + + The size of the 1D tensor is equal to the destination size. + + The ith element of the result is the index of the source of the ith element. + """ + pass + + @property + def dtype(self): + """Returns the dtype of the broadcast.""" + return self.gather_index.dtype + + @abc.abstractmethod + def with_dtype(self, dtype): + """Returns an identical _LayerBroadcaster with a different dtype.""" + pass + + def __repr__(self): + return str(self.gather_index) + + @classmethod + def from_gather_index(cls, gather_index): + """Create a broadcaster from a gather_index.""" + return _GatherLayerBroadcaster(gather_index) + + @classmethod + def first_layer(cls, nrows_source, nrows_target): + """Create a broadcaster from a gather_index.""" + gather_index = _first_layer_gather_index(nrows_source, nrows_target) + return _LayerBroadcaster.from_gather_index(gather_index) + + @classmethod + def get_singleton_broadcaster(cls, target_size): + """Broadcast from 1 element to target_size elements.""" + return _LayerBroadcaster.from_gather_index( + array_ops.zeros(target_size, dtype=target_size.dtype)) + + @abc.abstractmethod + def with_dependencies(self, checks): + """Add dependencies to a _LayerBroadcaster. + + Args: + checks: a list of ops that need to be run before any tensors from the + Broadcaster are used. + + Returns: + a copy of this _LayerBroadcaster with dependencies added. + """ + pass + + @classmethod + def get_identity_broadcaster(cls, nvals, dtype=None): + """Create an identity broadcaster. + + TODO(martinz): an identity broadcaster can be far more efficient than a + generic broadcaster. Add an optimized implementation. + Args: + nvals: the number of values for the broadcaster. + dtype: the dtype of the broadcaster, or None to use the dtype of nvals. + + Returns: + an identity broadcaster from [0....nvals-1] to [0...nvals-1] + """ + return _GatherLayerBroadcaster(math_ops.range(nvals, dtype=dtype)) + + def broadcast_tensor(self, tensor): + """Broadcast from a dense tensor. + + It is assumed that the first axis of the dense tensor is indexed by the + source shape, and at the end, the first axis of the dense tensor is + indexed by the destination shape. + + Args: + tensor: a dense tensor. + + Returns: + A dense tensor. + """ + return array_ops.gather(tensor, self.gather_index) + + def dest_nrows(self): + """Return the number of rows in the resulting gather, or None if tiling.""" + return math_ops.cast( + array_ops.shape(self.gather_index)[0], dtype=self.dtype) + + def broadcast_row_partition(self, rp): + """Return a new shape where the rows are broadcasted. + + *--self--->* + | | + rp result + | | + V V + *--------->* + + This is equivalent to: + return RowPartition.from_row_lengths(self.broadcast(rp.row_lengths())) + + However, if the shape has uniform row length, then that property is + maintained. + + Args: + rp: a row partition. + + Returns: + a RowPartition representing a broadcast version of this row partition. + """ + if not rp.is_uniform(): + return RowPartition.from_row_lengths( + self.broadcast_tensor(rp.row_lengths())) + else: + return RowPartition.from_uniform_row_length( + rp.uniform_row_length(), + nvals=rp.uniform_row_length() * self.dest_nrows(), + nrows=self.dest_nrows()) + + def next_layer(self, original_rp, broadcast_rp): + r"""Create the next layer gather_index whether or not a broadcast happens. + + *---------self------->* + | | + original_rp broadcast_rp + | | + \|/ \|/ + *--next_broadcaster-->* + Args: + original_rp: the original row partition. + broadcast_rp: the target row partition. + + Returns: + the gather_index for next_broadcaster. + + """ + gather_index = _next_layer_gather_index(self, original_rp, broadcast_rp) + return _LayerBroadcaster.from_gather_index(gather_index) + + +class _GatherLayerBroadcaster(_LayerBroadcaster): + """Implements _LayerBroadcaster with an explicit gather_index. + + For example, suppose that the source shape is: + [*],[*,*] + And the target shape is: + [*],[*,*],[*],[*,*] + Then, this can be represented with a map: + [0,1,2,0,1,2] + + """ + + def __init__(self, gather_index): + gather_index = ops.convert_to_tensor(gather_index) + if (gather_index.dtype != dtypes.int64 and + gather_index.dtype != dtypes.int32): + raise ValueError("gather_index must be int64 or int32") + self._gather_index = gather_index + + @property + def gather_index(self): + return self._gather_index + + def with_dtype(self, dtype): + return _GatherLayerBroadcaster(math_ops.cast(self._gather_index, dtype)) + + def with_dependencies(self, checks): + new_gather_index = control_flow_ops.with_dependencies( + checks, self._gather_index) + return _GatherLayerBroadcaster(new_gather_index) + + +class _Broadcaster: + """A _Broadcaster represents a transformation from one shape to another. + + It provides a transform for each axis of the source shape to the + corresponding axis of the destination shape. + + """ + + def __init__(self, + source_shape, + target_shape, + layer_broadcasters, + dtype=None): + """Create a broadcaster. + + Do not call directly. + The source_shape, target_shape, and layer_broadcasters are converted + to have the same dtype. + + Note: source_shape.rank and target_shape.rank must be known. + Args: + source_shape: the source DynamicRaggedShape + target_shape: the target DynamicRaggedShape + layer_broadcasters: List[_LayerBroadcaster] of length source_shape.rank. + dtype: the preferred dtype of the broadcaster. + + Raises: + TypeError: if the input types don't match. + """ + if not isinstance(source_shape, DynamicRaggedShape): + raise TypeError("source_shape is not a DynamicRaggedShape") + if not isinstance(target_shape, DynamicRaggedShape): + raise TypeError("target_shape is not a DynamicRaggedShape") + if not isinstance(layer_broadcasters, list): + raise TypeError("layer_broadcasters not a list: " + + str(layer_broadcasters)) + for bc in layer_broadcasters: + if not isinstance(bc, _LayerBroadcaster): + raise TypeError("Not a LayerBroadcaster: " + str(bc)) + + dtype = _find_dtype(source_shape, dtype) + dtype = _find_dtype(target_shape, dtype) + dtype = _find_dtype_iterable(layer_broadcasters, dtype) + dtype = _find_dtype(dtypes.int64, dtype) + self._source_shape = source_shape.with_dtype(dtype) + self._target_shape = target_shape.with_dtype(dtype) + self._layer_broadcasters = [x.with_dtype(dtype) for x in layer_broadcasters] + + def __repr__(self): + return ("{src_shape:" + str(self._source_shape) + ", target_shape:" + + str(self._target_shape) + " layer_broadcasters: " + + str(self._layer_broadcasters) + "}") + + def with_dtype(self, dtype): + """Return a copy of this Broadcaster with a different dtype.""" + return _Broadcaster(self._source_shape, self._target_shape, + self._layer_broadcasters, dtype) + + @property + def source_shape(self): + return self._source_shape + + @property + def target_shape(self): + return self._target_shape + + @property + def dtype(self): + return self._source_shape.dtype + + def _target_inner_shape_int32(self): + new_inner_shape = self.target_shape.inner_shape + if new_inner_shape.dtype == dtypes.int64: + new_inner_shape = math_ops.cast(new_inner_shape, dtype=dtypes.int32) + return new_inner_shape + + # pylint:disable=protected-access + def broadcast_flat_values(self, rt, inner_dimensions=True): + """flat_values of a ragged tensor broadcast to target_shape. + + If inner_dimensions==True, then the result is a dense tensor with shape + target_shape.inner_shape, the flat values of the broadcasted shape. + + If you add target_shape.row_partitions, you will get the full broadcasted + shape. + + If inner_dimensions==False, the result is a dense tensor that satsifies + certain properties: + 1. broadcast_to(result, target_shape.inner_shape) will give the result + if inner_dimensions==True. + 2. Either (a) (result.rank < target_shape.inner_rank) + or (b) (result.shape[0] == target_shape.inner_shape[0]). + 3. result.rank = min(target_shape.inner_rank, rt.rank) + 4. For i < target_shape.inner_rank - 1, and i < rt.rank, + and if rt.shape[-i]!=1, then result.shape[-i]=target_shape[-i]. + Args: + rt: a ragged or dense tensor. + inner_dimensions: if true, broadcast the inner dimensions as well. + + Returns: + a dense tensor + """ + if ragged_tensor.is_ragged(rt): + rt = rt.flat_values + # If rt was a regular tensor, it is its own flat_values. + if self.target_shape.rank == 0: + return rt + inner_rank = self.target_shape.inner_rank + if inner_rank > self._source_shape.rank: + # The dense rank is larger than the whole shape. So, we make the shape + # dense. + if self.source_shape.num_row_partitions > 0: + rt = array_ops.reshape( + rt, self.source_shape._alt_inner_shape(self.source_shape.rank)) + # rt.rank == self._source_shape.rank < inner_rank + # Here, property 2a holds. + if inner_dimensions: + return array_ops.broadcast_to(rt, self._target_inner_shape_int32()) + return rt + else: + if self._source_shape.inner_rank != inner_rank: + rt = array_ops.reshape(rt, + self._source_shape._alt_inner_shape(inner_rank)) # pylint:disable=protected-access + # After the reshape, rt is flat_values with inner_rank. + flat_broadcaster = self._layer_broadcasters[-inner_rank] + rt = flat_broadcaster.broadcast_tensor(rt) + # Here, property 2b holds. + if inner_dimensions: + rt = array_ops.broadcast_to(rt, self._target_inner_shape_int32()) + return rt + + def broadcast(self, rt): + """Broadcast a tensor of source_shape to target_shape.""" + flat_values = self.broadcast_flat_values(rt) + return self.target_shape._add_row_partitions(flat_values) # pylint:disable=protected-access + + +def _get_layer_broadcasters_from_rps(zero_broadcaster, source_rps, target_rps): + """Get LayerBroadcasters from RowPartitions. + + *--zero_broadcaster->* + | | + source_rps[0] target_rps[0] + | | + V V + *---result[1]------->* + | | + source_rps[1] target_rps[1] + | | + V V + *---result[2]------->* + . + . + . + *---result[k-1]----->* + | | + source_rps[k] target_rps[k] + | | + V V + *---result[k]------->* + + Note: result[0] = zero_broadcaster + + Args: + zero_broadcaster: a broadcaster between the source and target row + partitions' rows, and equal to result[0]. + source_rps: source row partitions. + target_rps: target row partitions (same length as source_rps). + + Returns: + result: a list of LayerBroadcasters. + """ + if not isinstance(zero_broadcaster, _LayerBroadcaster): + raise TypeError("Not a _LayerBroadcaster: " + str(zero_broadcaster)) + assert len(source_rps) == len(target_rps) + if not source_rps: + return [zero_broadcaster] + next_broadcaster = zero_broadcaster.next_layer(source_rps[0], target_rps[0]) + tail_broadcasters = _get_layer_broadcasters_from_rps(next_broadcaster, + source_rps[1:], + target_rps[1:]) + return [zero_broadcaster] + tail_broadcasters + + +def _get_broadcaster(source_shape, target_shape): + """Get a _Broadcaster from source_shape to target_shape.""" + if source_shape.dtype != target_shape.dtype: + raise ValueError("The source and target row_split dtypes should be equal") + + if (source_shape.rank is None or target_shape.rank is None): + raise ValueError("Rank of source and target must be statically known") + elif source_shape.rank > target_shape.rank: + raise ValueError("Cannot broadcast to a shape with smaller rank") + elif source_shape.rank == 0: + return _Broadcaster(source_shape, target_shape, []) + elif target_shape.rank == 1: + assert source_shape.rank == 1 + layer = _LayerBroadcaster.first_layer(source_shape.inner_shape[0], + target_shape.inner_shape[0]) + return _Broadcaster(source_shape, target_shape, [layer]) + + assert source_shape.rank <= target_shape.rank + assert target_shape.rank >= 2 + assert source_shape.rank >= 1 + + source_rps = source_shape._as_row_partitions() # pylint: disable=protected-access + + target_rps = target_shape._as_row_partitions() # pylint: disable=protected-access + + assert len(target_rps) >= 1 + assert len(source_rps) <= len(target_rps) + source_nrows = source_shape[0] + if len(source_rps) < len(target_rps): + # Note: this includes the case where len(source_rps)==0. + # Here we begin at -1, one dimension before source_rps[0]. + # neg_one_source_rp | neg_one_target_rp=target_rps[-(len(source_rps)+1)] + # source_rps[0] | target_rps[-len(source_rps)] + # source_rps[1] | target_rps[1-len(source_rps)] + # ... | ... + # source_rps[-1] | target_rps[-1] + neg_one_source_rp = RowPartition.from_uniform_row_length( + uniform_row_length=source_nrows, nrows=1, nvals=source_nrows) + neg_one_target_rp = target_rps[-(len(source_rps) + 1)] + neg_one_broadcaster = _LayerBroadcaster.get_singleton_broadcaster( + neg_one_target_rp.nrows()) + zeroth_broadcaster = neg_one_broadcaster.next_layer(neg_one_source_rp, + neg_one_target_rp) + target_rps_tail = target_rps[-len(source_rps):] if len( + source_rps) >= 1 else [] + + layers = _get_layer_broadcasters_from_rps(zeroth_broadcaster, source_rps, + target_rps_tail) + return _Broadcaster(source_shape, target_shape, layers) + else: + assert len(target_rps) == len(source_rps) + zeroth_broadcaster = _LayerBroadcaster.first_layer(source_rps[0].nrows(), + target_rps[0].nrows()) + layers = _get_layer_broadcasters_from_rps(zeroth_broadcaster, source_rps, + target_rps) + + return _Broadcaster(source_shape, target_shape, layers) + + +def _get_identity_broadcaster(shape): + """Gets a Broadcaster for two identical shapes.""" + if shape.rank is None: + raise ValueError("Shape must have a defined rank") + layers = [ + _LayerBroadcaster.get_identity_broadcaster( + shape._num_slices_in_dimension(i)) for i in range(shape.rank) # pylint: disable=protected-access + ] + return _Broadcaster(shape, shape, layers) + + +def _broadcast_dynamic_shape_one_layer(a, b): + """Broadcast two vectors, given their shapes. + + Args: + a: the number of rows in a. + b: the number of rows in b. + + Returns: + (layer_a, layer_b, target_shape) + layer_a is a _LayerBroadcaster from a to the target_shape. + layer_b is a _LayerBroadcaster from b to the target_shape. + target_shape is the target_shape + + Raises: + InvalidArgumentError if the shapes are not consistent. + """ + a_0 = a[0] + b_0 = b[0] + + def broadcast_from_a(): + # Assumes a_0 == 1 + a_layer = array_ops.zeros(b_0, dtype=b_0.dtype) + b_layer = math_ops.range(b_0) + target = b + return [a_layer, b_layer, target] + + a_static = tensor_util.constant_value(a) + if a_static is not None and a_static[0] == 1: + [a_gi, b_gi, target] = broadcast_from_a() + a_layer = _LayerBroadcaster.from_gather_index(a_gi) + b_layer = _LayerBroadcaster.from_gather_index(b_gi) + return [a_layer, b_layer, target] + + def broadcast_from_b(): + # Assumes b_0 == 1 + a_layer = math_ops.range(a_0) + b_layer = array_ops.zeros(a_0, dtype=a_0.dtype) + target = a + return [a_layer, b_layer, target] + + b_static = tensor_util.constant_value(b) + if b_static is not None and b_static[0] == 1: + [a_gi, b_gi, target] = broadcast_from_b() + a_layer = _LayerBroadcaster.from_gather_index(a_gi) + b_layer = _LayerBroadcaster.from_gather_index(b_gi) + return [a_layer, b_layer, target] + + def broadcast_noop(): + # Assumes a_0 == 1 + a_layer = math_ops.range(a_0) + b_layer = math_ops.range(b_0) + target = b + return [a_layer, b_layer, target] + + can_broadcast_from_a = math_ops.equal(a_0, 1) + can_broadcast_from_b = math_ops.equal(b_0, 1) + + def broadcast_not_from_a(): + return cond.cond( + can_broadcast_from_b, true_fn=broadcast_from_b, false_fn=broadcast_noop) + + nrows_equal = math_ops.equal(a_0, b_0) + can_broadcast = math_ops.logical_or( + can_broadcast_from_a, + math_ops.logical_or(can_broadcast_from_b, nrows_equal)) + + check_can_broadcast = check_ops.assert_equal( + can_broadcast, True, message="Cannot broadcast") + + results = cond.cond( + can_broadcast_from_a, + true_fn=broadcast_from_a, + false_fn=broadcast_not_from_a) + + results = [ + control_flow_ops.with_dependencies([check_can_broadcast], x) + for x in results + ] + [a_gi, b_gi, target] = results + a_layer = _LayerBroadcaster.from_gather_index(a_gi) + b_layer = _LayerBroadcaster.from_gather_index(b_gi) + return [a_layer, b_layer, target] + + +def _broadcast_dynamic_shape_first_layer(a_0, b_0): + """Broadcast the first layer of two dynamic shapes given the dimensions. + + Args: + a_0: the number of rows in a. + b_0: the number of rows in b. + + Returns: + (use_a, layer_a, layer_b) + where use_a is true if the target provably equals a, false otherwise. + layer_a is a _LayerBroadcaster from a to the target. + layer_b is a _LayerBroadcaster from b to the target. + """ + + def broadcast_from_a(): + # Assumes a_0 == 1 + a_layer = array_ops.zeros(b_0, dtype=b_0.dtype) + b_layer = math_ops.range(b_0) + return [a_layer, b_layer] + + static_a_0 = tensor_util.constant_value(a_0) + static_b_0 = tensor_util.constant_value(b_0) + if static_a_0 is not None: + if static_a_0 == static_b_0: + id_broadcaster = _LayerBroadcaster.get_identity_broadcaster( + static_a_0, dtype=a_0.dtype) + return [id_broadcaster, id_broadcaster] + elif static_a_0 == 1: + return [ + _LayerBroadcaster.get_singleton_broadcaster(b_0), + _LayerBroadcaster.get_identity_broadcaster(b_0) + ] + + if static_b_0 == 1: + return [ + _LayerBroadcaster.get_identity_broadcaster(a_0), + _LayerBroadcaster.get_singleton_broadcaster(a_0) + ] + + def broadcast_from_b(): + # Assumes b_0 == 1 + a_layer = math_ops.range(a_0) + b_layer = array_ops.zeros(a_0, dtype=a_0.dtype) + return [a_layer, b_layer] + + def broadcast_noop(): + # Assumes a_0 == b_0 + a_layer = math_ops.range(a_0) + b_layer = math_ops.range(b_0) + return [a_layer, b_layer] + + can_broadcast_from_a = math_ops.equal(a_0, constant_op.constant(1, a_0.dtype)) + can_broadcast_from_b = math_ops.equal(b_0, constant_op.constant(1, b_0.dtype)) + + def broadcast_not_from_a(): + return cond.cond( + can_broadcast_from_b, true_fn=broadcast_from_b, false_fn=broadcast_noop) + + # Ideally, this would only block control flow on broadcast_noop, but + # the control flow doesn't seem to work. + can_broadcast = math_ops.logical_or( + math_ops.logical_or(can_broadcast_from_a, can_broadcast_from_b), + math_ops.equal(a_0, b_0)) + + result = cond.cond( + can_broadcast_from_a, + true_fn=broadcast_from_a, + false_fn=broadcast_not_from_a) + + return [ + _LayerBroadcaster.from_gather_index( + control_flow_ops.with_dependencies( + [check_ops.assert_equal(can_broadcast, True)], x)) for x in result + ] + + +def _broadcast_half( + ac_0: _LayerBroadcaster, + a_1: RowPartition) -> Tuple[_LayerBroadcaster, RowPartition]: + """Does a NOOP broadcast of a_1. + + *-ac_0-->* + | | + a_1 c_1 + | | + V V + *-ac_1-->* + + Note that by definition this cannot fail: there is always a well-defined + NOOP broadcast. This is usually intended as half of broadcasting two shapes + together. + Args: + ac_0: previous LayerBroadcaster + a_1: previous RowPartition + + Returns: + [ac_1, c_1] where ac_1 is the next LayerBroadcaster, and c_1 is the + broadcast RowPartition + """ + c_1 = ac_0.broadcast_row_partition(a_1) + old_value_rowids = array_ops.gather(ac_0.gather_index, c_1.value_rowids()) + old_row_starts = array_ops.gather(a_1.row_splits(), old_value_rowids) + gather_index = old_row_starts + c_1.offsets_in_rows() + return [_LayerBroadcaster.from_gather_index(gather_index), c_1] + + +def _broadcast_dynamic_shape_next_layer_half_ragged( + ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, + b_1: RowPartition +) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: + r"""Broadcast target and next layer broadcaster of two dynamic shapes. + + a_1 is uniform, and b_1 is ragged. + *--ac_0-->*<--bc_0--* + | | | + a_1 c_1 b_1 + | | | + V V V + *--ac_1-->*<--bc_1--* + + Args: + ac_0: _LayerBroadcaster from a to c in the previous layer. + bc_0: _LayerBroadcaster from b to c in the previous layer. + a_1: a uniform RowPartition for the next layer of a. + b_1: a ragged RowPartition for the next layer of b. + + Returns: + (c_1, ac_1, bc_1) + c_1: a RowPartition for the next layer of the dynamic shape. + ac_1: _LayerBroadcaster from a to c in the next layer. + bc_1: _LayerBroadcaster from b to c in the next layer. + """ + if not isinstance(ac_0, _LayerBroadcaster): + raise TypeError("ac_0 should be a _LayerBroadcaster") + if not isinstance(bc_0, _LayerBroadcaster): + raise TypeError("bc_0 should be a _LayerBroadcaster") + if not isinstance(a_1, RowPartition): + raise TypeError("a_1 should be a RowPartition") + if not isinstance(b_1, RowPartition): + raise TypeError("b_1 should be a RowPartition") + + assert a_1.is_uniform() + assert not b_1.is_uniform() + + static_a_1 = tensor_util.constant_value(a_1.uniform_row_length()) + if static_a_1 == 1: + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) + c_1 = RowPartition.from_row_splits(c_1b.row_splits()) + ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) + bc_1 = _LayerBroadcaster.from_gather_index(bc_1.gather_index) + return [c_1, ac_1, bc_1] + + def broadcast_noop(): + # The sides must be "equal". + [ac_1, c_1a] = _broadcast_half(ac_0, a_1) + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + checks = [check_ops.assert_equal(c_1a.row_splits(), c_1b.row_splits())] + return [ + control_flow_ops.with_dependencies(checks, x) + for x in [a_1.row_splits(), ac_1.gather_index, bc_1.gather_index] + ] + + def broadcast_a(): + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) + return [ + c_1b.row_splits(), + ac_1_gather_index, + bc_1.gather_index, + ] + + can_broadcast_a = math_ops.equal(a_1.uniform_row_length(), 1) + + [c_1_row_splits, ac_1_gather_index, + bc_1_gather_index] = cond.cond( + can_broadcast_a, true_fn=broadcast_a, false_fn=broadcast_noop) + + c_1 = RowPartition.from_row_splits(c_1_row_splits) + ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) + bc_1 = _LayerBroadcaster.from_gather_index(bc_1_gather_index) + return [c_1, ac_1, bc_1] + + +def _broadcast_dynamic_shape_next_layer_both_uniform( + ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, + b_1: RowPartition +) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: + r"""Broadcast target and next layer broadcaster of two uniform dynamic shapes. + + *--ac_0-->*<--bc_0--* + | | | + a_1 c_1 b_1 + | | | + V V V + *--ac_1-->*<--bc_1--* + + Args: + ac_0: _LayerBroadcaster from a to c in the previous layer. + bc_0: _LayerBroadcaster from b to c in the previous layer. + a_1: a RowPartition for the next layer of a. + b_1: a RowPartition for the next layer of b. + + Returns: + (c_1, ac_1, bc_1) + c_1: a RowPartition for the next layer of the dynamic shape. + ac_1: _LayerBroadcaster from a to c in the next layer. + bc_1: _LayerBroadcaster from b to c in the next layer. + """ + if not isinstance(ac_0, _LayerBroadcaster): + raise TypeError("ac_0 should be a _LayerBroadcaster") + if not isinstance(bc_0, _LayerBroadcaster): + raise TypeError("bc_0 should be a _LayerBroadcaster") + if not isinstance(a_1, RowPartition): + raise TypeError("a_1 should be a RowPartition") + if not isinstance(b_1, RowPartition): + raise TypeError("b_1 should be a RowPartition") + assert a_1.is_uniform() + assert b_1.is_uniform() + + static_a_1 = tensor_util.constant_value(a_1.uniform_row_length()) + static_b_1 = tensor_util.constant_value(b_1.uniform_row_length()) + + if static_a_1 is not None: + if static_a_1 == static_b_1: + # Here, this dimension is the same, but we may have to broadcast previous + # dimensions. + [ac_1, _] = _broadcast_half(ac_0, a_1) + [bc_1, _] = _broadcast_half(bc_0, b_1) + c_1 = RowPartition.from_uniform_row_length( + static_a_1, nrows=ac_0.dest_nrows()) + return [c_1, ac_1, bc_1] + elif static_a_1 == 1: + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + ac_1 = _LayerBroadcaster.from_gather_index( + array_ops.gather(ac_0.gather_index, c_1b.value_rowids())) + c_1 = RowPartition.from_uniform_row_length( + b_1.uniform_row_length(), nrows=bc_0.dest_nrows()) + return [c_1, ac_1, bc_1] + + if static_b_1 == 1: + [ac_1, c_1a] = _broadcast_half(ac_0, a_1) + bc_1 = _LayerBroadcaster.from_gather_index( + array_ops.gather(bc_0.gather_index, c_1a.value_rowids())) + c_1 = RowPartition.from_uniform_row_length( + a_1.uniform_row_length(), nrows=ac_0.dest_nrows()) + return [c_1, ac_1, bc_1] + + def broadcast_noop(): + # Assumes a_1.uniform_row_length() == b_1.uniform_row_length() + # Both sides broadcast to a single shape. + [ac_1, _] = _broadcast_half(ac_0, a_1) + [bc_1, _] = _broadcast_half(bc_0, b_1) + return [a_1.uniform_row_length(), ac_1.gather_index, bc_1.gather_index] + + def broadcast_a(): + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) + return [ + b_1.uniform_row_length(), + ac_1_gather_index, + bc_1.gather_index, + ] + + def broadcast_b(): + [ac_1, c_1a] = _broadcast_half(ac_0, a_1) + bc_1_gather_index = array_ops.gather(bc_0.gather_index, c_1a.value_rowids()) + return [a_1.uniform_row_length(), ac_1.gather_index, bc_1_gather_index] + + can_broadcast_b = math_ops.equal(b_1.uniform_row_length(), 1) + + def no_broadcast_a(): + return cond.cond( + can_broadcast_b, true_fn=broadcast_b, false_fn=broadcast_noop) + + can_broadcast_a = math_ops.equal(a_1.uniform_row_length(), 1) + + broadcast_asserts = [ + check_ops.assert_equal( + math_ops.logical_or( + math_ops.logical_or(can_broadcast_a, can_broadcast_b), + math_ops.equal(a_1.uniform_row_length(), + b_1.uniform_row_length())), True) + ] + + result = cond.cond( + can_broadcast_a, true_fn=broadcast_a, false_fn=no_broadcast_a) + + [c_1_uniform_row_length, ac_1_gather_index, bc_1_gather_index] = [ + control_flow_ops.with_dependencies(broadcast_asserts, x) for x in result + ] + + c_1 = RowPartition.from_uniform_row_length( + c_1_uniform_row_length, + nvals=c_1_uniform_row_length * ac_0.dest_nrows(), + nrows=ac_0.dest_nrows()) + ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) + bc_1 = _LayerBroadcaster.from_gather_index(bc_1_gather_index) + return [c_1, ac_1, bc_1] + + +def _broadcast_dynamic_shape_next_layer( + ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, + b_1: RowPartition +) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: + r"""Broadcast target and next layer broadcaster of two dynamic shapes. + + *--ac_0-->*<--bc_0--* + | | | + a_1 c_1 b_1 + | | | + V V V + *--ac_1-->*<--bc_1--* + + Args: + ac_0: _LayerBroadcaster from a to c in the previous layer. + bc_0: _LayerBroadcaster from b to c in the previous layer. + a_1: a RowPartition for the next layer of a. + b_1: a RowPartition for the next layer of b. + + Returns: + (c_1, ac_1, bc_1) + c_1: a RowPartition for the next layer of the dynamic shape. + ac_1: _LayerBroadcaster from a to c in the next layer. + bc_1: _LayerBroadcaster from b to c in the next layer. + """ + if not isinstance(ac_0, _LayerBroadcaster): + raise TypeError("ac_0 should be a _LayerBroadcaster") + if not isinstance(bc_0, _LayerBroadcaster): + raise TypeError("bc_0 should be a _LayerBroadcaster") + if not isinstance(a_1, RowPartition): + raise TypeError("a_1 should be a RowPartition") + if not isinstance(b_1, RowPartition): + raise TypeError("b_1 should be a RowPartition") + + if a_1.is_uniform(): + if b_1.is_uniform(): + return _broadcast_dynamic_shape_next_layer_both_uniform( + ac_0, bc_0, a_1, b_1) + else: + return _broadcast_dynamic_shape_next_layer_half_ragged( + ac_0, bc_0, a_1, b_1) + else: + if b_1.is_uniform(): + [c_1, bc_1, ac_1] = _broadcast_dynamic_shape_next_layer_half_ragged( # pylint: disable=arguments-out-of-order + bc_0, ac_0, b_1, a_1) + return (c_1, ac_1, bc_1) + else: + # If neither shape is uniform, we cannot broadcast the dimension. + [ac_1, c_1a] = _broadcast_half(ac_0, a_1) + [bc_1, c_1b] = _broadcast_half(bc_0, b_1) + check_valid = [ + check_ops.assert_equal(c_1a.row_splits(), c_1b.row_splits()) + ] + return ( + c_1a._with_dependencies(check_valid), # pylint: disable=protected-access + ac_1.with_dependencies(check_valid), + bc_1.with_dependencies(check_valid)) + + +def _broadcast_dynamic_shape_from_rps( + a_zero: _LayerBroadcaster, b_zero: _LayerBroadcaster, + a_rps: Sequence[RowPartition], b_rps: Sequence[RowPartition] +) -> Tuple[Sequence[RowPartition], Sequence[_LayerBroadcaster], + Sequence[_LayerBroadcaster]]: + """Create BroadcastLayers from two shapes to a target shape. + + + *--a_zero->*<-b_zero-* + | | | + a_rps[0] c_rps[0] b_rps[0] + | | | + V V V + *--ac[1]-->*<-bc[1]--* + | | | + a_rps[1] c_rps[0] b_rps[1] + | | | + V V V + *--ac[2]-->*<-bc[2]--* + + Note: ac[0]=a_zero, and bc[0]=b_zero. + Args: + a_zero: broadcaster from rows of a_rps[0] to target shape. + b_zero: broadcaster from rows of b_rps[0] to target shape. + a_rps: RowPartitions of first shape. + b_rps: RowPartitions of second shape, equal in length to a_rps. + + Returns: + (c_rps, ac, bc) where: + c_rps: RowPartitions of target shape. + ac: layers broadcasting from the first shape. + bc: layers broadcasting from the second shape. + """ + assert len(a_rps) == len(b_rps) + if a_rps: + (c_1, ac_1, + bc_1) = _broadcast_dynamic_shape_next_layer(a_zero, b_zero, a_rps[0], + b_rps[0]) + (c_suffix, a_layers, + b_layers) = _broadcast_dynamic_shape_from_rps(ac_1, bc_1, a_rps[1:], + b_rps[1:]) + + return ([c_1] + c_suffix, [ac_1] + a_layers, [bc_1] + b_layers) + else: + return ([], [], []) + + +def _get_broadcast_num_row_partitions(a: DynamicRaggedShape, + b: DynamicRaggedShape): + """Returns broadcast_dynamic_shape(a, b).num_row_partitions.""" + # Assumes rank and num_row_partitions are not None. + if (a.num_row_partitions == 0 and b.num_row_partitions == 0): + return 0 + expanded_num_row_partitions_a = a.num_row_partitions + max(0, b.rank - a.rank) + expanded_num_row_partitions_b = b.num_row_partitions + max(0, a.rank - b.rank) + + if a.num_row_partitions == 0: + return expanded_num_row_partitions_b + + if b.num_row_partitions == 0: + return expanded_num_row_partitions_a + + return max(expanded_num_row_partitions_a, expanded_num_row_partitions_b) + + +# pylint: disable=protected-access +def _broadcast_dynamic_shape_extended_complete( + a: DynamicRaggedShape, b: DynamicRaggedShape, b_rps: Sequence[RowPartition], + c_suffix: Sequence[RowPartition], ac: Sequence[_LayerBroadcaster], + bc_suffix: Sequence[_LayerBroadcaster] +) -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster]: + """Helper for broadcast_dynamic_shape_extended.""" + c_prefix = b_rps[:-len(c_suffix)] + bc_prefix_length = b.rank - len(bc_suffix) + bc_prefix = [ + _LayerBroadcaster.get_identity_broadcaster(b._num_slices_in_dimension(i)) + for i in range(bc_prefix_length) + ] + c_num_row_partitions = _get_broadcast_num_row_partitions(a, b) + + c_raw = DynamicRaggedShape.from_row_partitions(c_prefix + tuple(c_suffix)) + c = c_raw._with_num_row_partitions(c_num_row_partitions) + return (c, _Broadcaster(a, c, ac), _Broadcaster(b, c, bc_prefix + bc_suffix)) + + +def _broadcast_dynamic_shape_extended_helper( + a: DynamicRaggedShape, b: DynamicRaggedShape +) -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster]: + """Helper for broadcast_dynamic_shape_extended. + + Here, we force: + a.rank <= b.rank + 2 <= b.rank + 1 <= a.rank + Args: + a: a DynamicRaggedShape + b: a DynamicRaggedShape + + Returns: + A triple of a shape and two broadcasters. + """ + assert a.rank <= b.rank + assert 2 <= b.rank + assert 1 <= a.rank + a_rps = a._as_row_partitions() # pylint: disable=protected-access + b_rps = b._as_row_partitions() # pylint: disable=protected-access + + if len(a_rps) < len(b_rps): + # Note: this includes the case where len(a_rps)==0. + # Here we begin at -1, one dimension before a_rps[0]. + # neg_one_a_rp | b_rps[-(len(a_rps)+1)] + # a_rps[0] | b_rps[-len(a_rps)] + # a_rps[1] | b_rps[1-len(a_rps)] + # ... | ... + # a_rps[-1] | b_rps[-1] + + a_nrows = a[0] + a_nrows_static = tensor_util.constant_value(a_nrows) + if a_nrows_static is not None: + a_nrows = a_nrows_static + + neg_one_a_rp = RowPartition.from_uniform_row_length( + uniform_row_length=a_nrows, nrows=1, nvals=a_nrows) + neg_one_b_rp = b_rps[-(len(a_rps) + 1)] + (neg_one_ac, neg_one_bc) = _broadcast_dynamic_shape_first_layer( + constant_op.constant(1, dtype=b_rps[0].dtype), neg_one_b_rp.nrows()) + + # The first part of the solution. + (c_zero, ac_zero, + bc_zero) = _broadcast_dynamic_shape_next_layer(neg_one_ac, neg_one_bc, + neg_one_a_rp, neg_one_b_rp) + b_rps_tail = b_rps[-len(a_rps):] if len(a_rps) >= 1 else [] + + (c_suffix, ac_layers, + bc_layers) = _broadcast_dynamic_shape_from_rps(ac_zero, bc_zero, a_rps, + b_rps_tail) + + return _broadcast_dynamic_shape_extended_complete( + a=a, + b=b, + b_rps=b_rps, + c_suffix=[c_zero] + c_suffix, + ac=[ac_zero] + ac_layers, + bc_suffix=[neg_one_bc, bc_zero] + bc_layers) + + else: + assert len(a_rps) == len(b_rps) + (ac_zero, + bc_zero) = _broadcast_dynamic_shape_first_layer(a_rps[0].nrows(), + b_rps[0].nrows()) + + (c_rps, a_layers, + b_layers) = _broadcast_dynamic_shape_from_rps(ac_zero, bc_zero, a_rps, + b_rps) + return _broadcast_dynamic_shape_extended_complete( + a=a, + b=b, + b_rps=b_rps, + c_suffix=c_rps, + ac=[ac_zero] + a_layers, + bc_suffix=[bc_zero] + b_layers) + + +def _fix_start_index(index, rank, num_row_partitions): + """Slice indexes are always silently truncated.""" + if index < 0: + if rank is None: + raise ValueError( + "Rank must be known to use __getitem__ on a negative index.") + index = rank + index + if index < 0: + index = 0 + if (num_row_partitions > 0 and index <= num_row_partitions + 1): + # The rank is always >= num_row_partitions + 1 if num_row_partitions > 0. + return index + if index == 0: + return index + if rank is None: + raise ValueError("Rank must be known to use __getitem__ on a large index.") + if index >= rank: + index = rank + return index + + +def _fix_stop_index(index, rank): + """Slice indexes are always silently truncated.""" + if index is None: + if rank is None: + raise ValueError("Rank must be known to use __getitem__ without a stop.") + index = rank + if index < 0: + if rank is None: + raise ValueError( + "Rank must be known to use __getitem__ on a negative index.") + index = rank + index + if index < 0: + index = 0 + if rank is not None: + index = min(rank, index) + return index + + +def _first_layer_gather_index(nrows_source, nrows_target): + """Return the first layer gather_index. + + Args: + nrows_source: the number of rows in the source. + nrows_target: the number of rows in the target. + + Returns: + A tensor, usable as a gather_index for a _LayerBroadcaster. + """ + + def gi_broadcast_first(): + return array_ops.zeros(nrows_target, dtype=nrows_target.dtype) + + def gi_no_broadcast_first(): + gather_index = math_ops.range(nrows_target, dtype=nrows_target.dtype) + return gather_index + + do_broadcast = math_ops.equal(nrows_source, + constant_op.constant(1, nrows_source.dtype)) + nrows_equal = math_ops.equal(nrows_source, nrows_target) + can_broadcast = check_ops.assert_equal( + math_ops.logical_or(do_broadcast, nrows_equal), + True, + message="Cannot broadcast") + + gather_index = cond.cond( + do_broadcast, true_fn=gi_broadcast_first, false_fn=gi_no_broadcast_first) + + return control_flow_ops.with_dependencies([can_broadcast], gather_index) + + +def _next_layer_gather_index(bc, original_rp, broadcast_rp): + r"""Create the next layer gather_index whether or not a broadcast happens. + + *----------bc-------->* + | | + original_rp broadcast_rp + | | + \|/ \|/ + *--next_broadcaster-->* + + Args: + bc: the old broadcaster. + original_rp: the original row partition. + broadcast_rp: the target row partition. + + Returns: + the gather_index for next_broadcaster. + Raises: + InvalidArgumentError if the shapes are incompatible. + """ + old_value_rowids = array_ops.gather(bc.gather_index, + broadcast_rp.value_rowids()) + + def gi_no_broadcast(): + # TODO(martinz): decide if row_splits or row_starts should be used here. + old_row_starts = array_ops.gather(original_rp.row_splits(), + old_value_rowids) + expected_row_lengths = array_ops.gather( + params=original_rp.row_lengths(), indices=bc.gather_index) + actual_row_lengths = broadcast_rp.row_lengths() + check_valid = check_ops.assert_equal( + expected_row_lengths, actual_row_lengths, message="Cannot broadcast") + gather_index = old_row_starts + broadcast_rp.offsets_in_rows() + return control_flow_ops.with_dependencies([check_valid], gather_index) + + def gi_broadcast(): + # Several optimizations can occur here. + # old_row_starts == old_value_rowids, because: + # if you are broadcasting, then the source has uniform row length of 1, + # implying original_rp.row_splits == tf.range(orgininal_rp.nvals + 1) + # When broadcasting, there is no need to add offsets to the + # source, because the source has size 1. + # Also, this is always valid, because we enforce source and destination + # have uniform_row_length. + return old_value_rowids + + if not original_rp.is_uniform(): + return gi_no_broadcast() + + do_broadcast = math_ops.equal(original_rp.uniform_row_length(), + constant_op.constant(1, original_rp.dtype)) + gather_index = cond.cond( + do_broadcast, true_fn=gi_broadcast, false_fn=gi_no_broadcast) + + return gather_index + + +def _flat_values_shape(rt): + if isinstance(rt, ragged_tensor.RaggedTensor): + return array_ops.shape(rt.flat_values) + return rt.flat_values.shape + + +def _to_row_partitions_and_nvals_from_lengths( + lengths: Sequence[Union[int, Sequence[int]]], + dtype=None) -> Tuple[Sequence[RowPartition], int]: + """Allow ragged and uniform shapes to be specified. + + For example, [2, [2,1], 2] represents a shape like: + [[[0, 0], [0, 0]], [[0, 0]]] + + Args: + lengths: a list of integers and lists of integers. + dtype: dtype of the shape (tf.int32 or tf.int64) + + Returns: + a sequence of RowPartitions, and the number of values of the last partition. + """ + size_so_far = lengths[0] + result = [] + for current_lengths in lengths[1:]: + if isinstance(current_lengths, int): + nrows = size_so_far + nvals = current_lengths * nrows + size_so_far = nvals + result.append( + RowPartition.from_uniform_row_length( + current_lengths, nvals, nrows=nrows, dtype_hint=dtype)) + else: + if size_so_far != len(current_lengths): + raise ValueError("Shape not consistent.") + result.append( + RowPartition.from_row_lengths(current_lengths, dtype_hint=dtype)) + size_so_far = sum(current_lengths) + return (result, size_so_far) + + +def _element_to_string(x): + """element to a string within a list.""" + if x is Ellipsis: + return "..." + if isinstance(x, str): + return "'" + x + "'" + return str(x) + + +def _list_tail_with_ellipsis(arr): + """Print the tail of a list where the list might have an ellipsis.""" + if not arr: + return "]" + else: + return ", " + _element_to_string(arr[0]) + _list_tail_with_ellipsis(arr[1:]) + + +def _list_with_ellipsis_to_str(arr): + """Print a list that might have ellipsis.""" + if not arr: + return "[]" + return "[" + _element_to_string(arr[0]) + _list_tail_with_ellipsis(arr[1:]) + + +def _is_int_or_tuple_of_ints(x): + if isinstance(x, int): + return True + if not isinstance(x, tuple): + return False + for y in x: + if not isinstance(y, int): + return False + return True + + +def _alt_inner_shape_from_tensor_shape(shape, dtype, new_inner_rank): + """Helper for _alt_inner_shape, used directly in _with_num_row_partitions.""" + if new_inner_rank == 1: + return constant_op.constant([shape.num_elements()], dtype=dtype) + new_inner_rank_tail_length = new_inner_rank - 1 + inner_shape_tail = shape[-new_inner_rank_tail_length:].as_list() + first_dim = shape[:-new_inner_rank_tail_length].num_elements() + return constant_op.constant([first_dim] + inner_shape_tail, dtype=dtype) + + +def _safe_floor_div(dividend: tensor_shape.Dimension, + divisor: tensor_shape.Dimension) -> tensor_shape.Dimension: + if tensor_shape.dimension_value(divisor) == 0: + return None + return dividend // divisor + + +# TODO(b/218932570) +def _reduce_prod_patch(x): + if x.dtype == dtypes.int64: + return math_ops.cast( + math_ops.reduce_prod(math_ops.cast(x, dtypes.int32)), dtypes.int64) + return math_ops.reduce_prod(x) + + +# Type alias for shape encoded as a DynamicRaggedShape or a Tensor. +DenseOrRaggedShape = Union[DynamicRaggedShape, core.TensorLike] + + +def _merge_row_partitions( + row_partitions: Sequence[RowPartition]) -> RowPartition: + # TODO(martinz): handle uniform splits. + # TODO(martinz): consider using value_row_ids if present. + # Note: this probably won't be called with len(row_partitions)==1, so no + # need to optimize. + row_splits = row_partitions[0].row_splits() + for rp in row_partitions[1:]: + row_splits = array_ops.gather(rp.row_splits(), row_splits) + return RowPartition.from_row_splits(row_splits) + + +def _merge_inner_shape( + inner_shape: tensor_lib.Tensor, + static_inner_shape: tensor_shape.TensorShape, + outer_axis: int, + inner_axis: int) -> Tuple[tensor_lib.Tensor, tensor_shape.TensorShape]: + """Merge the inner shape of a DynamicRaggedShape.""" + prefix = inner_shape[:outer_axis] + suffix = inner_shape[inner_axis + 1:] + + internal = inner_shape[outer_axis:inner_axis + 1] + internal_value = [_reduce_prod_patch(internal)] + new_internal = array_ops.concat([prefix, internal_value, suffix], axis=0) + prefix_static = static_inner_shape[:outer_axis] + suffix_static = static_inner_shape[inner_axis + 1:] + internal_static = static_inner_shape[outer_axis:inner_axis + 1] + internal_value_static = tensor_shape.TensorShape( + [internal_static.num_elements()]) + new_internal_static = prefix_static + internal_value_static + suffix_static + + return (new_internal, new_internal_static) + + +def _batch_rp_spec(rp_spec: RowPartitionSpec, + batch_size: Optional[int]) -> RowPartitionSpec: + """Batches a RowPartitionSpec. + + Given a RowPartitionSpec and a batch_size, create a RowPartitionSpec that + will be the spec for the concatenation of batch_size RowPartitions. + + A RowPartition can be considered a transformation from a list of a given + length to a list of lists. Assume rp_a is a map from list_a to nlist_a, + And rp_b is a map from list_b to nlist_b. concat(rp_a, rp_b) is a + transform of concat(list_a, list_b) to concat(nlist_a, nlist_b). + + If batch_size is None, then have the spec be able to handle an arbitrary + number of RowPartitions. + + Args: + rp_spec: a RowPartitionSpec for all the RowPartitions to be concatenated. + batch_size: the number of rp_specs to be concatenated. + + Returns: + a batched RowPartitionSpec. + """ + if batch_size is None: + return RowPartitionSpec( + uniform_row_length=rp_spec.uniform_row_length, dtype=rp_spec.dtype) + nrows = None if rp_spec.nrows is None else rp_spec.nrows * batch_size + nvals = None if rp_spec.nvals is None else rp_spec.nvals * batch_size + return RowPartitionSpec( + nrows=nrows, + nvals=nvals, + uniform_row_length=rp_spec.uniform_row_length, + dtype=rp_spec.dtype) + + +def _batch_rp_spec_head(old_head: RowPartitionSpec, + batch_size: Optional[int]) -> RowPartitionSpec: + """Creates a RowPartitionSpec representing the new dimension created.""" + nvals = None if (old_head.nrows is None or + batch_size is None) else batch_size * old_head.nrows + return RowPartitionSpec( + nrows=batch_size, + nvals=nvals, + uniform_row_length=old_head.nrows, + dtype=old_head.dtype) + + +def _batch_static_inner_shape( + old_shape: tensor_shape.TensorShape, + batch_size: Optional[int]) -> tensor_shape.TensorShape: + """Returns a copy of old_shape with axis=0 multiplied by batch_size. + + Only use if this is the inner_shape of a DynamicRaggedShape.Spec with one + or more row partitions. + + Args: + old_shape: the original inner_shape. + batch_size: the batch size. + + Returns: + a new shape. + """ + head_dim = tensor_shape.dimension_at_index(old_shape, 0) * batch_size + return head_dim + old_shape[1:] + + +def _batch_tensor_shape(old_shape: tensor_shape.TensorShape, + batch_size: int) -> tensor_shape.TensorShape: + return tensor_shape.TensorShape([batch_size]) + old_shape + + +def _unbatch_static_inner_shape( + old_shape: tensor_shape.TensorShape, + batch_size: Optional[int]) -> tensor_shape.TensorShape: + """Unbatch a static_inner_shape when num_row_partitions > 0.""" + head_dim = tensor_shape.dimension_at_index(old_shape, 0) // batch_size + return head_dim + old_shape[1:] + + +# Copied from ragged_array_ops.py +def ones(shape: DynamicRaggedShape, + dtype=dtypes.float32, + name: Optional[str] = None) -> ragged_tensor.RaggedOrDense: + """Returns ones shaped like x.""" + flat_values = array_ops.ones(shape.inner_shape, dtype=dtype, name=name) + return ragged_tensor.RaggedTensor._from_nested_row_partitions( # pylint: disable=protected-access + flat_values, shape.row_partitions) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6064da237ccea5bd928796d70f73a3e681d5e2c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_array_ops.py @@ -0,0 +1,1300 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Array operations for RaggedTensors.""" + +from typing import Optional +from typing import Union + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import gen_ragged_array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.ops.ragged import dynamic_ragged_shape +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_util +from tensorflow.python.ops.ragged import segment_id_ops +from tensorflow.python.types import core as core_types +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +# =============================================================================== +# Masking +# =============================================================================== + + +@tf_export('ragged.boolean_mask') +@dispatch.add_dispatch_support +def boolean_mask(data, mask, name=None): + """Applies a boolean mask to `data` without flattening the mask dimensions. + + Returns a potentially ragged tensor that is formed by retaining the elements + in `data` where the corresponding value in `mask` is `True`. + + * `output[a1...aA, i, b1...bB] = data[a1...aA, j, b1...bB]` + + Where `j` is the `i`th `True` entry of `mask[a1...aA]`. + + Note that `output` preserves the mask dimensions `a1...aA`; this differs + from `tf.boolean_mask`, which flattens those dimensions. + + Args: + data: A potentially ragged tensor. + mask: A potentially ragged boolean tensor. `mask`'s shape must be a prefix + of `data`'s shape. `rank(mask)` must be known statically. + name: A name prefix for the returned tensor (optional). + + Returns: + A potentially ragged tensor that is formed by retaining the elements in + `data` where the corresponding value in `mask` is `True`. + + * `rank(output) = rank(data)`. + * `output.ragged_rank = max(data.ragged_rank, rank(mask) - 1)`. + + Raises: + ValueError: if `rank(mask)` is not known statically; or if `mask.shape` is + not a prefix of `data.shape`. + + #### Examples: + + >>> # Aliases for True & False so data and mask line up. + >>> T, F = (True, False) + + >>> tf.ragged.boolean_mask( # Mask a 2D Tensor. + ... data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], + ... mask=[[T, F, T], [F, F, F], [T, F, F]]).to_list() + [[1, 3], [], [7]] + + >>> tf.ragged.boolean_mask( # Mask a 2D RaggedTensor. + ... tf.ragged.constant([[1, 2, 3], [4], [5, 6]]), + ... tf.ragged.constant([[F, F, T], [F], [T, T]])).to_list() + [[3], [], [5, 6]] + + >>> tf.ragged.boolean_mask( # Mask rows of a 2D RaggedTensor. + ... tf.ragged.constant([[1, 2, 3], [4], [5, 6]]), + ... tf.ragged.constant([True, False, True])).to_list() + [[1, 2, 3], [5, 6]] + """ + with ops.name_scope(name, 'RaggedMask', [data, mask]): + # Convert inputs to tensors. + data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data') + mask = ragged_tensor.convert_to_tensor_or_ragged_tensor( + mask, dtypes.bool, name='mask') + row_splits_dtype, (data, mask) = ragged_tensor.match_row_splits_dtypes( + data, mask, return_dtype=True) + + # Get static rank of mask. + if mask.shape.ndims is None: + raise ValueError('mask.shape.ndims must be known statically.') + elif mask.shape.ndims == 0: + raise ValueError('mask cannot be scalar.') + + # If mask is ragged, then recurse with a non-ragged mask. + if ragged_tensor.is_ragged(mask): + if not ragged_tensor.is_ragged(data): + data = ragged_tensor.RaggedTensor.from_tensor( + data, + ragged_rank=mask.ragged_rank, + row_splits_dtype=mask.row_splits.dtype) + # Check that mask.nested_row_splits is a prefix of + # data.nested_row_splits. + splits_list = [ + mask.nested_row_splits, data.nested_row_splits[:mask.ragged_rank] + ] + with ops.control_dependencies( + ragged_util.assert_splits_match(splits_list)): + # Strip off ragged `splits` until `mask` is non-ragged. Keep the splits + # that we strip off in `splits`, so we can add them back on after + # we recursively mask the non-ragged data. + splits = [] + while ragged_tensor.is_ragged(mask): + if mask.shape.ndims > 2: + splits.append(mask.row_splits) + else: + # Count the number of True mask values in each row to find the + # lengths of the filtered rows; then convert to splits. + int_mask = ragged_functional_ops.map_flat_values( + math_ops.cast, mask, dtype=row_splits_dtype) + masked_row_lengths = ragged_math_ops.reduce_sum(int_mask, axis=1) + splits.append(ragged_util.lengths_to_splits(masked_row_lengths)) + mask = mask.values + data = data.values + + # Recursively apply the nested non-ragged mask to the nested data. + masked_values = boolean_mask(data, mask) + + # Add the ragged `splits` back to the result. + masked_values = ragged_tensor.RaggedTensor.from_nested_row_splits( + masked_values, splits, validate=False) + + return masked_values + + # If mask is non-ragged and has rank 1, and data is ragged, then build a + # ragged tensor with the indicated rows. + elif ragged_tensor.is_ragged(data) and mask.shape.ndims == 1: + # Get the masked splits: first get the length of each row, then filter + # out the rows that we are deleting, and convert that filtered set of + # masks back to a splits tensor. + lengths = data.row_lengths() + masked_lengths = array_ops.boolean_mask(lengths, mask) + masked_splits = ragged_util.lengths_to_splits(masked_lengths) + + # Get the masked values: first get row ids corresponding to each + # value, then use tf.gather to build a boolean mask that's false for + # values that come from rows that we are deleting, and use that mask to + # construct the masked values tensor. + segment_ids = segment_id_ops.row_splits_to_segment_ids(data.row_splits) + segment_mask = array_ops.gather(mask, segment_ids) + masked_values = boolean_mask(data.values, segment_mask) + + return ragged_tensor.RaggedTensor.from_row_splits( + masked_values, masked_splits, validate=False) + + # If mask is non-ragged and has rank>1, then convert it to be ragged, + # with a ragged rank matching data. + if ragged_tensor.is_ragged(data): + mask = ragged_tensor.RaggedTensor.from_tensor( + mask, + ragged_rank=min(data.ragged_rank, mask.shape.ndims - 1), + row_splits_dtype=data.row_splits.dtype) + return boolean_mask(data, mask) + + # Otherwise, data and mask are both `Tensor`s. + else: + # Apply `boolean_mask` to get the masked values. + masked_values = array_ops.boolean_mask(data, mask) + + if mask.shape.ndims >= 2: + # Add the innermost ragged dimension. For each innermost cell, get the + # number of values it contains. Then flatten that to get a list of + # cell lengths, and convert it to splits. Finally, combine the splits + # and values to get the innermost ragged tensor. + masked_lengths = math_ops.count_nonzero( + mask, axis=-1, dtype=row_splits_dtype) + flattened_masked_lengths = array_ops.reshape(masked_lengths, [-1]) + masked_values = ragged_tensor.RaggedTensor.from_row_lengths( + masked_values, flattened_masked_lengths, validate=False) + + # Wrap remaining ragged dimensions. + if mask.shape.ndims > 2: + mask_shape = array_ops.shape(mask, out_type=row_splits_dtype) + split_size = math_ops.cumprod(mask_shape) + 1 + for dim in range(mask.shape.ndims - 3, -1, -1): + elt_size = mask_shape[dim + 1] + masked_splits = math_ops.range(split_size[dim]) * elt_size + masked_values = ragged_tensor.RaggedTensor.from_row_splits( + masked_values, masked_splits, validate=False) + + return masked_values + + +# =============================================================================== +# Tiling +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.tile) +def tile(input: ragged_tensor.Ragged, multiples, name=None): # pylint: disable=redefined-builtin + """Constructs a `RaggedTensor` by tiling a given `RaggedTensor`. + + The values of `input` are replicated `multiples[i]` times along the + `i`th dimension (for each dimension `i`). For every dimension `axis` in + `input`, the length of each output element in that dimension is the + length of corresponding input element multiplied by `multiples[axis]`. + + Args: + input: A `RaggedTensor`. + multiples: A 1-D integer `Tensor`. Length must be the same as the number of + dimensions in `input`. + name: A name for the operation (optional). + + Returns: + A `RaggedTensor` with the same type, rank, and ragged_rank as `input`. + + #### Example: + + >>> rt = tf.ragged.constant([[1, 2], [3]]) + >>> tf.tile(rt, [3, 2]).to_list() + [[1, 2, 1, 2], [3, 3], [1, 2, 1, 2], [3, 3], [1, 2, 1, 2], [3, 3]] + """ + with ops.name_scope(name, 'RaggedTile', [input, multiples]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input, name='input') + if not ragged_tensor.is_ragged(input): + return array_ops.tile(input, multiples, name) + multiples = ragged_util.convert_to_int_tensor( + multiples, name='multiples', dtype=input.row_splits.dtype) + multiples.shape.assert_has_rank(1) + + # If the constant value of `multiples` is available, then we can use it + # to skip tiling dimensions where `multiples=1`. + const_multiples = tensor_util.constant_value(multiples) + + return ragged_tensor.RaggedTensor.from_nested_row_splits( + _tile_ragged_values(input, multiples, const_multiples), + _tile_ragged_splits(input, multiples, const_multiples), + validate=False) + + +def _tile_ragged_values(rt_input, multiples, const_multiples=None): + """Builds flat_values tensor for a tiled `RaggedTensor`. + + Returns a tensor that repeats the values in + `rt_input.flat_values` in the + appropriate pattern to construct a `RaggedTensor` that tiles `rt_input` as + specified by `multiples`. + + Args: + rt_input: The `RaggedTensor` whose values should be repeated. + multiples: A 1-D integer `tensor`, indicating how many times each dimension + should be repeated. + const_multiples: Optional constant value for multiples. Used to skip tiling + dimensions where `multiples=1`. + + Returns: + A `Tensor` with the same type and rank as `rt_input.flat_values`. + + #### Example: + + >>> rt = tf.ragged.constant([[1, 2], [3]]) + >>> _tile_ragged_values(rt, tf.constant([3, 2])).numpy() + array([1, 2, 1, 2, 3, 3, 1, 2, 1, 2, 3, 3, 1, 2, 1, 2, 3, 3], dtype=int32) + """ + ragged_rank = rt_input.ragged_rank + nested_splits = rt_input.nested_row_splits + + # Pointers to the values in `rt_input.flat_values`. + inner_value_ids = math_ops.range(nested_splits[-1][-1]) + + # For each ragged dimension (working from the innermost to outermost), + # expand `inner_value_ids` as necessary to tile that dimension. + prev_splits = None + for axis in range(ragged_rank, 0, -1): + # Ragged splits for this dimension. + splits = nested_splits[axis - 1] + + # Adjust splits so they point into `inner_value_ids` (instead of just + # pointing into the next dimension's values). + if prev_splits is not None: # Not the first pass through the loop. + splits = array_ops.gather(prev_splits * multiples[axis + 1], splits) + + # Repeat each element in this ragged dimension `multiples[axis]` times. + if const_multiples is None or const_multiples[axis] != 1: + inner_value_ids = ragged_util.repeat_ranges(inner_value_ids, splits, + multiples[axis]) + + prev_splits = splits + + # Gather the tiled inner values. + ragged_tiled_values = array_ops.gather(rt_input.flat_values, inner_value_ids) + + # Tile the flat_values for the uniform dimensions (i.e., for `axis=0` plus + # `axis=range(ragged_rank, rank)`). + inner_repeats = array_ops.concat([multiples[:1], multiples[ragged_rank + 1:]], + axis=0) + return array_ops.tile(ragged_tiled_values, inner_repeats) + + +def _tile_ragged_splits(rt_input, multiples, const_multiples=None): + """Builds nested_split tensors for a tiled `RaggedTensor`. + + Returns a list of split tensors that can be used to construct the + `RaggedTensor` that tiles `rt_input` as specified by `multiples`. + + Args: + rt_input: The `RaggedTensor` that is being tiled. + multiples: A 1-D integer `tensor`, indicating how many times each dimension + should be repeated. + const_multiples: Optional constant value for multiples. Used to skip tiling + dimensions where `multiples=1`. + + Returns: + A list of 1-D integer `Tensor`s (one for each ragged dimension in + `rt_input`). + + #### Example: + + >>> rt = tf.ragged.constant([[1, 2], [3]]) + >>> _tile_ragged_splits(rt, [3, 2]) + [] + """ + ragged_rank = rt_input.ragged_rank + nested_splits = rt_input.nested_row_splits + + # projected_splits[src_axis, dst_axis] contains the split points that divide + # the rows from src_axis in the list of dst_axis values. E.g., + # projected_splits[i, i] = nested_splits[i], and + # projected_splits[i, i+1] = gather(nested_splits[i+1], nested_splits[i]). + projected_splits = [{i: nested_splits[i]} for i in range(ragged_rank)] + for src_axis in range(ragged_rank): + for dst_axis in range(src_axis + 1, ragged_rank - 1): + projected_splits[src_axis][dst_axis] = array_ops.gather( + nested_splits[dst_axis], projected_splits[src_axis][dst_axis - 1]) + + # For each ragged dimension: nested_splits[axis] -> result_splits[axis]. + result_splits = [] + for axis in range(ragged_rank): + # Get the length of each row for the input tensor for this dimension. + input_lengths = nested_splits[axis][1:] - nested_splits[axis][:-1] + + # Multiply those lengths by the `multiples` of dimension axis+1, since + # each value will be repeated that number of times. + output_lengths = input_lengths * multiples[axis + 1] + + # Repeat ranges of the row lengths as necessary for them to be tiled in + # each ragged dimension `d < axis`. (Start with dimension d=axis-1, and + # work our way up to dimension d=0.) + repeats = 1 + for d in range(axis - 1, -1, -1): + if const_multiples is None or const_multiples[d + 1] != 1: + splits = projected_splits[d][axis - 1] * repeats + output_lengths = ragged_util.repeat_ranges(output_lengths, splits, + multiples[d + 1]) + repeats *= multiples[d + 1] + + # Tile splits for the outermost (uniform) dimension. + output_lengths = array_ops.tile(output_lengths, multiples[:1]) + + # Convert to splits. + result_splits.append(ragged_util.lengths_to_splits(output_lengths)) + + return result_splits + + +# =============================================================================== +# Reshaping +# =============================================================================== + + +@dispatch.dispatch_for_api(array_ops.expand_dims_v2) +def expand_dims(input: ragged_tensor.Ragged, axis, name=None): # pylint: disable=redefined-builtin + """Inserts a dimension with shape 1 into a potentially ragged tensor's shape. + + Given a potentially ragged tenor `input`, this operation inserts a + dimension with size 1 at the dimension `axis` of `input`'s shape. + + The following table gives some examples showing how `ragged.expand_dims` + impacts the shapes of different input tensors. Ragged dimensions are + indicated by enclosing them in parentheses. + + input.shape | axis | result.shape + ----------------------- | ---- | ----------------------------- + `[D1, D2]` | `0` | `[1, D1, D2]` + `[D1, D2]` | `1` | `[D1, 1, D2]` + `[D1, D2]` | `2` | `[D1, D2, 1]` + `[D1, (D2), (D3), D4]` | `0` | `[1, D1, (D2), (D3), D4]` + `[D1, (D2), (D3), D4]` | `1` | `[D1, 1, (D2), (D3), D4]` + `[D1, (D2), (D3), D4]` | `2` | `[D1, (D2), 1, (D3), D4]` + `[D1, (D2), (D3), D4]` | `3` | `[D1, (D2), (D3), 1, D4]` + `[D1, (D2), (D3), D4]` | `4` | `[D1, (D2), (D3), D4, 1]` + + Args: + input: The potentially tensor that should be expanded with a new dimension. + axis: An integer constant indicating where the new dimension should be + inserted. + name: A name for the operation (optional). + + Returns: + A tensor with the same values as `input`, with an added dimension of + size 1 at `axis`. + + #### Examples: + + >>> rt = tf.ragged.constant([[1, 2], [3]]) + >>> print(rt.shape) + (2, None) + + >>> expanded = tf.expand_dims(rt, axis=0) + >>> print(expanded.shape, expanded) + (1, 2, None) + + >>> expanded = tf.expand_dims(rt, axis=1) + >>> print(expanded.shape, expanded) + (2, 1, None) + + >>> expanded = tf.expand_dims(rt, axis=2) + >>> print(expanded.shape, expanded) + (2, None, 1) + """ + with ops.name_scope(name, 'RaggedExpandDims', [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input, name='input') + + if not ragged_tensor.is_ragged(input): + return array_ops.expand_dims(input, axis) + + ndims = None if input.shape.ndims is None else input.shape.ndims + 1 + axis = array_ops.get_positive_axis(axis, ndims, ndims_name='rank(input)') + + if axis == 0: + return ragged_tensor.RaggedTensor.from_uniform_row_length( + input, uniform_row_length=input.nrows(), nrows=1, validate=False) + elif axis == 1: + return ragged_tensor.RaggedTensor.from_uniform_row_length( + input, uniform_row_length=1, nrows=input.nrows(), validate=False) + else: + if ragged_tensor.is_ragged(input.values): + return input.with_values(expand_dims(input.values, axis - 1)) + else: + return input.with_values(array_ops.expand_dims(input.values, axis - 1)) + + +@dispatch.dispatch_for_api(array_ops.expand_dims) +def _ragged_expand_dims_v1( + input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin + axis=None, + name=None, + dim=None): + if dim is not None: + axis = dim + return expand_dims(input=input, axis=axis, name=name) + + +# =============================================================================== +# RaggedTensor Size +# =============================================================================== + + +@dispatch.dispatch_for_api(array_ops.size_v2) +def size(input: ragged_tensor.Ragged, out_type=dtypes.int32, name=None): # pylint: disable=redefined-builtin + """Returns the size of a potentially ragged tensor. + + The size of a ragged tensor is the size of its inner values. + + #### Example: + + >>> tf.size(tf.ragged.constant([[1, 2], [3]])).numpy() + 3 + + Args: + input: A potentially ragged `Tensor`. + out_type: The numeric output type for the operation. + name: A name for the operation (optional). + + Returns: + A Tensor of type `out_type`. + """ + if ragged_tensor.is_ragged(input): + return array_ops.size(input.flat_values, out_type=out_type, name=name) + else: + return array_ops.size(input, out_type=out_type, name=name) + + +@dispatch.dispatch_for_api(array_ops.size) +def _ragged_size_v1( + input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin + name=None, + out_type=dtypes.int32): + return size(input=input, out_type=out_type, name=name) + + +# =============================================================================== +# ragged.rank +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.rank) +def rank(input: ragged_tensor.Ragged, name=None): # pylint: disable=redefined-builtin + """Returns the rank of a RaggedTensor. + + Returns a 0-D `int32` `Tensor` representing the rank of `input`. + + #### Example: + + >>> # shape of tensor 't' is [2, None, None] + >>> t = tf.ragged.constant([[[1], [2, 2]], [[3, 3, 3], [4, 4, 4, 4]]]) + >>> tf.rank(t).numpy() + 3 + + Args: + input: A `RaggedTensor` + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + with ops.name_scope(name, 'RaggedRank', [input]) as name: + if not ragged_tensor.is_ragged(input): + return array_ops.rank(input, name) + + return input.ragged_rank + array_ops.rank(input.flat_values) + + +# =============================================================================== +# ragged.one_hot +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.one_hot) +def ragged_one_hot(indices: ragged_tensor.Ragged, + depth, + on_value=None, + off_value=None, + axis=None, + dtype=None, + name=None): + """Applies tf.one_hot along the values of a RaggedTensor.""" + # Get the adjusted axis value for the call to array_ops.one_hot. + # Note: the only negative `axis` value supported by array_ops.one_hot is -1. + if isinstance(axis, int) and axis >= 0: + if axis <= indices.ragged_rank: + raise ValueError('axis (%d) must be greater than indices.ragged_rank ' + '(%d).' % (axis, indices.ragged_rank)) + axis -= indices.ragged_rank + + with ops.name_scope(name, 'RaggedOneHot', + [indices, depth, on_value, off_value, axis]): + indices = ragged_tensor.convert_to_tensor_or_ragged_tensor( + indices, name='indices') + return indices.with_flat_values( + array_ops.one_hot(indices.flat_values, depth, on_value, off_value, axis, + dtype, name)) + + +# =============================================================================== +# ragged.stack_dynamic_partitions +# =============================================================================== +@tf_export('ragged.stack_dynamic_partitions') +@dispatch.add_dispatch_support +def stack_dynamic_partitions(data, partitions, num_partitions, name=None): + """Stacks dynamic partitions of a Tensor or RaggedTensor. + + Returns a RaggedTensor `output` with `num_partitions` rows, where the row + `output[i]` is formed by stacking all slices `data[j1...jN]` such that + `partitions[j1...jN] = i`. Slices of `data` are stacked in row-major + order. + + If `num_partitions` is an `int` (not a `Tensor`), then this is equivalent to + `tf.ragged.stack(tf.dynamic_partition(data, partitions, num_partitions))`. + + #### Example: + + >>> data = ['a', 'b', 'c', 'd', 'e'] + >>> partitions = [ 3, 0, 2, 2, 3] + >>> num_partitions = 5 + >>> tf.ragged.stack_dynamic_partitions(data, partitions, num_partitions) + + + Args: + data: A `Tensor` or `RaggedTensor` containing the values to stack. + partitions: An `int32` or `int64` `Tensor` or `RaggedTensor` specifying the + partition that each slice of `data` should be added to. `partitions.shape` + must be a prefix of `data.shape`. Values must be greater than or equal to + zero, and less than `num_partitions`. `partitions` is not required to be + sorted. + num_partitions: An `int32` or `int64` scalar specifying the number of + partitions to output. This determines the number of rows in `output`. + name: A name prefix for the returned tensor (optional). + + Returns: + A `RaggedTensor` containing the stacked partitions. The returned tensor + has the same dtype as `data`, and its shape is + `[num_partitions, (D)] + data.shape[partitions.rank:]`, where `(D)` is a + ragged dimension whose length is the number of data slices stacked for + each `partition`. + """ + with ops.name_scope(name, 'SegmentStack', [data, partitions, num_partitions]): + # Convert inputs to tensors. + data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data') + row_splits_dtype = ( + data.row_splits.dtype + if isinstance(data, ragged_tensor.RaggedTensor) else None) + partitions = ragged_tensor.convert_to_tensor_or_ragged_tensor( + partitions, name='partitions', preferred_dtype=row_splits_dtype) + num_partitions = ops.convert_to_tensor( + num_partitions, name='num_partitions', preferred_dtype=partitions.dtype) + if row_splits_dtype is not None: + partitions = math_ops.cast(partitions, row_splits_dtype) + num_partitions = math_ops.cast(num_partitions, partitions.dtype) + + # Sanity-checks for shapes. + partitions_rank = partitions.shape.ndims + if partitions_rank is None: + raise ValueError('partitions must have known rank.') + num_partitions.shape.assert_has_rank(0) + partitions.shape.assert_is_compatible_with(data.shape[:partitions_rank]) + + if partitions_rank == 0: + # If partitions is a scalar, then just create a RaggedTensor containing + # that single the complete `data` value in the specified row. + return ragged_tensor.RaggedTensor.from_value_rowids( + values=array_ops_stack.stack([data]), + value_rowids=array_ops_stack.stack([partitions]), + nrows=num_partitions, + validate=False) + + elif partitions_rank == 1: + # If partitions is a vector (the typical case): we can just use data and + # partitions as the `values` and `value_rowids` for `from_value_rowids`, + # as long as we sort them first. + permutation = sort_ops.argsort(partitions, stable=True) + value_rowids = array_ops.gather(partitions, permutation) + values = array_ops.gather(data, permutation) + checks = [ + check_ops.assert_less( + value_rowids[-1:], num_partitions, + message='partitions must be less than num_partitions'), + check_ops.assert_non_negative( + partitions, message='partitions must be non-negative.') + ] + with ops.control_dependencies(checks): + return ragged_tensor.RaggedTensor.from_value_rowids( + values, value_rowids, nrows=num_partitions, validate=False) + + else: + # Handle higher-dimensional partitions via recursion. + if not isinstance(data, ragged_tensor.RaggedTensor): + data = ragged_tensor.RaggedTensor.from_tensor( + data, row_splits_dtype=partitions.dtype, ragged_rank=1) + if not isinstance(partitions, ragged_tensor.RaggedTensor): + partitions = ragged_tensor.RaggedTensor.from_tensor( + partitions, + row_splits_dtype=partitions.dtype, + ragged_rank=max(data.ragged_rank, partitions_rank - 1)) + check = check_ops.assert_equal( + data.row_splits, + partitions.row_splits, + message='data and partitions have incompatible ragged shapes') + with ops.control_dependencies([check]): + return stack_dynamic_partitions(data.values, partitions.values, + num_partitions) + + +# =============================================================================== +# Reverse +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.reverse) +def reverse(tensor: ragged_tensor.Ragged, axis, name=None): + """Reverses a RaggedTensor along the specified axes. + + #### Example: + + >>> data = tf.ragged.constant([ + ... [[1, 2], [3, 4]], [[5, 6]], [[7, 8], [9, 10], [11, 12]]]) + >>> tf.reverse(data, axis=[0, 2]) + + + Args: + tensor: A 'RaggedTensor' to reverse. + axis: A list or tuple of 'int' or a constant 1D 'tf.Tensor'. The indices of + the axes to reverse. + name: A name prefix for the returned tensor (optional). + + Returns: + A 'RaggedTensor'. + """ + type_error_msg = ('`axis` must be a list of int or a constant tensor' + 'when reversing axes in a ragged tensor') + + with ops.name_scope(name, 'Reverse', [tensor, axis]): + if isinstance(axis, tensor_lib.Tensor): + axis = tensor_util.constant_value(axis) + if axis is None: + raise TypeError(type_error_msg) + elif not (isinstance(axis, (list, tuple)) and + all(isinstance(dim, int) for dim in axis)): + raise TypeError(type_error_msg) + + tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor( + tensor, name='tensor') + + # Allow usage of negative values to specify innermost axes. + axis = [ + array_ops.get_positive_axis(dim, tensor.shape.rank, 'axis[%d]' % i, + 'rank(tensor)') + for i, dim in enumerate(axis) + ] + + # We only need to slice up to the max axis. If the axis list + # is empty, it should be 0. + slices = [slice(None)] * (max(axis) + 1 if axis else 0) + + for dim in axis: + slices[dim] = slice(None, None, -1) + + return tensor[tuple(slices)] + + +# =============================================================================== +# Cross +# =============================================================================== + + +@tf_export('ragged.cross') +@dispatch.add_dispatch_support +def cross(inputs, name=None): + """Generates feature cross from a list of tensors. + + The input tensors must have `rank=2`, and must all have the same number of + rows. The result is a `RaggedTensor` with the same number of rows as the + inputs, where `result[row]` contains a list of all combinations of values + formed by taking a single value from each input's corresponding row + (`inputs[i][row]`). Values are combined by joining their strings with '_X_'. + E.g.: + + >>> tf.ragged.cross([tf.ragged.constant([['a'], ['b', 'c']]), + ... tf.ragged.constant([['d'], ['e']]), + ... tf.ragged.constant([['f'], ['g']])]) + + + Args: + inputs: A list of `RaggedTensor` or `Tensor` or `SparseTensor`. + name: Optional name for the op. + + Returns: + A 2D `RaggedTensor` of type `string`. + """ + return _cross_internal(inputs=inputs, hashed_output=False, name=name) + + +@tf_export('ragged.cross_hashed') +@dispatch.add_dispatch_support +def cross_hashed(inputs, num_buckets=0, hash_key=None, name=None): + """Generates hashed feature cross from a list of tensors. + + The input tensors must have `rank=2`, and must all have the same number of + rows. The result is a `RaggedTensor` with the same number of rows as the + inputs, where `result[row]` contains a list of all combinations of values + formed by taking a single value from each input's corresponding row + (`inputs[i][row]`). Values are combined by hashing together their + fingerprints. E.g.: + + >>> tf.ragged.cross_hashed([tf.ragged.constant([['a'], ['b', 'c']]), + ... tf.ragged.constant([['d'], ['e']]), + ... tf.ragged.constant([['f'], ['g']])], + ... num_buckets=100) + + + Args: + inputs: A list of `RaggedTensor` or `Tensor` or `SparseTensor`. + num_buckets: A non-negative `int` that used to bucket the hashed values. If + `num_buckets != 0`, then `output = hashed_value % num_buckets`. + hash_key: Integer hash_key that will be used by the `FingerprintCat64` + function. If not given, a default key is used. + name: Optional name for the op. + + Returns: + A 2D `RaggedTensor` of type `int64`. + """ + return _cross_internal( + inputs=inputs, + hashed_output=True, + num_buckets=num_buckets, + hash_key=hash_key, + name=name) + + +_DEFAULT_CROSS_HASH_KEY = 0xDECAFCAFFE + + +def _cross_internal(inputs, + hashed_output=False, + num_buckets=0, + hash_key=None, + name=None): + """Generates feature cross from a list of ragged and dense tensors.""" + if not isinstance(inputs, (tuple, list)): + raise TypeError('Inputs must be a list') + + if hash_key is None: + hash_key = _DEFAULT_CROSS_HASH_KEY + + ragged_inputs = [] + sparse_inputs = [] + dense_inputs = [] + input_order = [] + with ops.name_scope(name, 'RaggedCross', inputs): + for i, t in enumerate(inputs): + if sparse_tensor.is_sparse(t): + t = sparse_tensor.SparseTensor.from_value(t) + else: + t = ragged_tensor.convert_to_tensor_or_ragged_tensor(t) + if t.dtype.is_integer: + t = math_ops.cast(t, dtypes.int64) + elif t.dtype != dtypes.string: + raise ValueError('Unexpected dtype for inputs[%d]: %s' % (i, t.dtype)) + if isinstance(t, ragged_tensor.RaggedTensor): + if t.ragged_rank != 1: + raise ValueError('tf.ragged.cross only supports inputs with rank=2') + ragged_inputs.append(t) + input_order.append('R') + elif isinstance(t, sparse_tensor.SparseTensor): + sparse_inputs.append(t) + input_order.append('S') + else: + dense_inputs.append(t) + input_order.append('D') + + out_values_type = dtypes.int64 if hashed_output else dtypes.string + if ragged_inputs and all( + t.row_splits.dtype == dtypes.int32 for t in ragged_inputs): + out_row_splits_type = dtypes.int32 + else: + out_row_splits_type = dtypes.int64 + + # Convert hash_key from uint64 -> int64, since we need to pass it via + # an int64 attr. + if hash_key > 2**63: + hash_key -= 2**64 + + values_out, splits_out = gen_ragged_array_ops.ragged_cross( + ragged_values=[rt.values for rt in ragged_inputs], + ragged_row_splits=[rt.row_splits for rt in ragged_inputs], + sparse_indices=[st.indices for st in sparse_inputs], + sparse_values=[st.values for st in sparse_inputs], + sparse_shape=[st.dense_shape for st in sparse_inputs], + dense_inputs=dense_inputs, + input_order=''.join(input_order), + hashed_output=hashed_output, + num_buckets=num_buckets, + hash_key=hash_key, + out_values_type=out_values_type.as_datatype_enum, + out_row_splits_type=out_row_splits_type.as_datatype_enum, + name=name) + + return ragged_tensor.RaggedTensor.from_row_splits( + values_out, splits_out, validate=False) + + +def fill_empty_rows(ragged_input, default_value, name=None): + """Fills empty rows in the input `RaggedTensor` with rank 2 with a default + + value. + + This op adds entries with the specified `default_value` for any row in the + input that does not already have a value. + + The op also returns an indicator vector such that + + empty_row_indicator[i] = True iff row i was an empty row. + + Args: + ragged_input: A `RaggedTensor` with rank 2. + default_value: The value to fill for empty rows, with the same type as + `ragged_input.` + name: A name prefix for the returned tensors (optional) + + Returns: + ragged_ordered_output: A `RaggedTensor`with all empty rows filled in with + `default_value`. + empty_row_indicator: A bool vector indicating whether each input row was + empty. + + Raises: + TypeError: If `ragged_input` is not a `RaggedTensor`. + """ + with ops.name_scope(name, 'RaggedFillEmptyRows', [ragged_input]): + if not isinstance(ragged_input, ragged_tensor.RaggedTensor): + raise TypeError( + 'ragged_input must be RaggedTensor, got' + f' {type(ragged_input)}' + ) + default_value = ops.convert_to_tensor( + default_value, dtype=ragged_input.dtype + ) + ( + output_value_rowids, + output_values, + empty_row_indicator, + unused_reverse_index_map, + ) = gen_ragged_array_ops.ragged_fill_empty_rows( + value_rowids=ragged_input.value_rowids(), + values=ragged_input.values, + nrows=ragged_input.nrows(), + default_value=default_value, + ) + return ( + ragged_tensor.RaggedTensor.from_value_rowids( + values=output_values, + value_rowids=output_value_rowids, + validate=False, + ), + empty_row_indicator, + ) + + +@ops.RegisterGradient('RaggedFillEmptyRows') +def _ragged_fill_empty_rows_grad( + op, + unused_grad_output_indices, + output_grad_values, + unused_grad_empty_row_indicator, + unused_grad_reverse_index_map, +): + """Gradients for RaggedFillEmptyRows.""" + reverse_index_map = op.outputs[3] + + d_values, d_default_value = gen_ragged_array_ops.ragged_fill_empty_rows_grad( + reverse_index_map=reverse_index_map, grad_values=output_grad_values + ) + + # d_value_rowids, d_values, d_nrows, d_default_value. + return [None, d_values, None, d_default_value] + + +# =============================================================================== +# dynamic_partition +# =============================================================================== +@dispatch.dispatch_for_api(data_flow_ops.dynamic_partition) +def dynamic_partition(data: ragged_tensor.RaggedOrDense, + partitions: ragged_tensor.RaggedOrDense, + num_partitions, + name=None): + """RaggedTensor dispatch override for tf.dynamic_partition.""" + if not isinstance(num_partitions, int) or num_partitions < 0: + raise TypeError('num_partitions must be a non-negative integer') + result = stack_dynamic_partitions(data, partitions, num_partitions, name) + return [result[i] for i in range(num_partitions)] + + +# =============================================================================== +# split +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.split) +def split(value: ragged_tensor.Ragged, + num_or_size_splits, + axis=0, + num=None, + name=None): + """Splits a RaggedTensor `value` into a list of sub RaggedTensors. + + If `num_or_size_splits` is an `int`, then it splits `value` along the + dimension `axis` into `num_or_size_splits` smaller RaggedTensors. This + requires that `value.shape[axis]` is divisible by `num_or_size_splits`. + + If `num_or_size_splits` is a 1-D Tensor (or list), then `value` is split into + `len(num_or_size_splits)` elements. The shape of the `i`-th element has the + same size as the `value` except along dimension `axis` where the size is + `num_or_size_splits[i]`. + + Splits along a ragged dimension is not allowed. + + For example: + + >>> rt = tf.RaggedTensor.from_row_lengths( + ... np.arange(6 * 3).reshape(6, 3), row_lengths=[1, 2, 2, 1]) + >>> rt.shape + TensorShape([4, None, 3]) + >>> + >>> rt1, rt2 = tf.split(rt, 2) # uniform splits + >>> rt1.shape + TensorShape([2, None, 3]) + >>> rt2.shape + TensorShape([2, None, 3]) + >>> + >>> rt3, rt4, rt5 = tf.split(rt, [1, 2, 1]) # ragged splits + >>> rt3.shape + TensorShape([1, None, 3]) + >>> rt4.shape + TensorShape([2, None, 3]) + >>> rt5.shape + TensorShape([1, None, 3]) + >>> + >>> rt6, rt7 = tf.split(rt, [1, 2], axis=2) # splits along axis 2 + >>> rt6.shape + TensorShape([4, None, 1]) + >>> rt7.shape + TensorShape([4, None, 2]) + + Args: + value: The `RaggedTensor` to split. + num_or_size_splits: Either an `int` indicating the number of splits + along `axis` or a 1-D integer `Tensor` or Python list containing the sizes + of each output tensor along `axis`. If a Python int, then it must evenly + divide `value.shape[axis]`; otherwise the sum of sizes along the split + axis must match that of the `value`. + axis: An `int` or scalar `int32` `Tensor`. The dimension along which + to split. Must be in the range `[-rank(value), rank(value))`. Defaults to + 0. + num: An `int` used to specify the number of outputs when + `num_or_size_splits` is a 1-D list or `Tensor` and its length is + statically unknown, e.g., specifying `tf.TensorSepc(None)` with + the `input_signature` argument of `tf.function` (optional). + name: A name for the operation (optional). + + Returns: + if `num_or_size_splits` is an `int` returns a list of `num_or_size_splits` + `RaggedTensor` objects; if `num_or_size_splits` is a 1-D Tensor returns + `num_or_size_splits.get_shape[0]` `RaggedTensor` objects resulting from + splitting `value`. + + Raises: + ValueError: If the dimension `axis` of `value` is a ragged dimension. + ValueError: If `num` is unspecified and cannot be inferred. + ValueError: If `num` is specified but doesn't match the length of + `num_or_size_splits`. + ValueError: If `num_or_size_splits` is an `int` and less than 1. + TypeError: If `num_or_size_splits` is not an `int` or 1-D + list or 1-D `Tensor`. + InvalidArgumentError: If the `axis` of `value` cannot be exactly splitted + by `num_or_size_splits`. + InvalidArgumentError: If `num_or_size_splits` is contains negative integers. + InvalidArgumentError: If `num_or_size_splits`'s static shape is unknown and + its dynamic shape is inconsistent `num`. + InvalidArgumentError: If `num_or_size_splits`'s static rank is unknown and + `axis` is a negative integer. + """ + with ops.name_scope(name, 'RaggedSplit'): + value = ragged_tensor.convert_to_tensor_or_ragged_tensor( + value, name='value') + if isinstance(num_or_size_splits, int) and num_or_size_splits == 1: + return [value] + + # static assert + check_ops.assert_integer_v2( + num_or_size_splits, + message=('`num_or_size_splits` must be an `int` or 1-D list or ' + '`Tensor` of integers.')) + value_shape = dynamic_ragged_shape.DynamicRaggedShape.from_tensor(value) + axis = array_ops.get_positive_axis(axis, value_shape.rank) + try: + dim_size = value_shape[axis] + except ValueError: + raise ValueError('Cannot split a ragged dimension. Got `value` with ' + f'shape {value_shape} and `axis` {axis}.') + if isinstance(num_or_size_splits, int): + # Uniform split + num_splits = num_or_size_splits + if num_splits < 1: + raise ValueError('`num_or_size_splits` must be >=1 if it is an `int`.' + f'Received {num_or_size_splits}.') + split_length = math_ops.floordiv(dim_size, num_splits) + split_lengths = array_ops.repeat(split_length, num_splits) + else: + # Ragged split + num_splits = None + split_lengths = ops.convert_to_tensor(num_or_size_splits) + if split_lengths.shape.ndims is not None: + if split_lengths.shape.ndims != 1: + raise TypeError('`num_or_size_splits` must be an `int` or 1-D list ' + f'or `Tensor`. Received {num_or_size_splits}.') + num_splits = tensor_shape.dimension_value(split_lengths.shape[0]) + + if num_splits is None: + if num is None: + raise ValueError('`num` must be specified as an `int` when the ' + 'size of `num_or_size_split` is statically ' + f'unknown. Received `num`: {num} and ' + f'`num_or_size_split`: {num_or_size_splits}.') + num_splits = num + else: + if num is not None and num != num_splits: + raise ValueError('`num` does not match the size of ' + f'`num_or_size_split`. Received `num`: {num} and ' + f'size of `num_or_size_split`: {num_splits}.') + + splits = array_ops.concat([[0], math_ops.cumsum(split_lengths)], axis=0) + checks = [] + checks.append( + check_ops.assert_non_negative_v2( + num_or_size_splits, + message='`num_or_size_splits` must be non-negative.')) + checks.append( + check_ops.assert_equal_v2( + num_splits, + array_ops.shape(split_lengths)[0], + message='`num` is inconsistent with `num_or_size_split.shape[0]`.')) + checks.append( + check_ops.assert_equal_v2( + math_ops.cast(dim_size, splits.dtype), + splits[-1], + message=('Cannot exactly split the `axis` dimension of `value` ' + 'with the given `num_or_size_split`.'))) + splits = control_flow_ops.with_dependencies(checks, splits) + splited_rts = [] + slices = [slice(None)] * (axis + 1) + for i in range(num_splits): + slices[-1] = slice(splits[i], splits[i + 1]) + splited_rts.append(value[tuple(slices)]) + return splited_rts + + +# =============================================================================== +# RaggedTensor shape operations +# =============================================================================== + + +@dispatch.dispatch_for_api(array_ops.reshape) +def ragged_reshape( + tensor: ragged_tensor.RaggedOrDense, + shape: dynamic_ragged_shape.DenseOrRaggedShape +) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]: + """Reshapes a tensor or ragged tensor.""" + tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor( + tensor, name='tensor') + if isinstance(tensor, ragged_tensor.RaggedTensor): + tensor = tensor.values + + if isinstance(shape, dynamic_ragged_shape.DynamicRaggedShape): + flat_values = array_ops.reshape(tensor, shape.inner_shape) + return ragged_tensor.RaggedTensor._from_nested_row_partitions( # pylint: disable=protected-access + flat_values, + shape.row_partitions, + validate=False) + else: + shape = ops.convert_to_tensor(shape, name='shape') + return array_ops.reshape(tensor, shape) + + +@dispatch.dispatch_for_api(array_ops.broadcast_to) +def broadcast_to( + input: ragged_tensor.RaggedOrDense, # pylint: disable=redefined-builtin + shape: dynamic_ragged_shape.DynamicRaggedShape +) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]: + """Broadcasts a potentially ragged tensor to a ragged shape. + + Tiles `input` as necessary to match the given shape. + + Behavior is undefined if `input` is not broadcast-compatible with `shape`. + + Args: + input: The potentially ragged tensor to broadcast. + shape: A `DynamicRaggedShape` + + Returns: + A potentially ragged tensor whose values are taken from + `input`, and whose shape matches `shape`. + """ + return dynamic_ragged_shape.broadcast_to(input, shape) + + +# Note: default value for out_type needs to be int32, to match the +# default for tf.shape's out_type parameter. +@dispatch.dispatch_for_api(array_ops.shape) +def ragged_shape( + input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin + name: Optional[str] = None, + out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape: + """Returns the shape of a RaggedTensor. + + Args: + input: A `RaggedTensor` + name: A name for the operation (optional). + out_type: dtype used to encode the shape. + + Returns: + A `tf.experimental.DynamicRaggedShape` + """ + with ops.name_scope(name, 'RaggedShape', [input]): + return dynamic_ragged_shape.DynamicRaggedShape.from_tensor(input, out_type) + + +@dispatch.dispatch_for_api(array_ops.broadcast_dynamic_shape) +def broadcast_dynamic_shape( + shape_x: dynamic_ragged_shape.DenseOrRaggedShape, + shape_y: dynamic_ragged_shape.DenseOrRaggedShape +) -> dynamic_ragged_shape.DynamicRaggedShape: + """Returns the shape formed by broadcasting two shapes to be compatible. + + 1. If shape_x and shape_y both have row_partitions, then fail if their dtypes + don't match. + 2. If neither has row_partitions and they have different dtypes, + go with int64. + 3. If one has row_partitions, go with that dtype. + + Args: + shape_x: A `DynamicRaggedShape` + shape_y: A `DynamicRaggedShape` + + Returns: + A `DynamicRaggedShape`. + Raises: + ValueError: If `shape_x` and `shape_y` are not broadcast-compatible. + """ + if not isinstance(shape_x, dynamic_ragged_shape.DynamicRaggedShape): + shape_x = dynamic_ragged_shape.DynamicRaggedShape([], shape_x) + if not isinstance(shape_y, dynamic_ragged_shape.DynamicRaggedShape): + shape_y = dynamic_ragged_shape.DynamicRaggedShape([], shape_y) + return dynamic_ragged_shape.broadcast_dynamic_shape(shape_x, shape_y) + + +@dispatch.dispatch_for_api(array_ops.ones) +def ones( + shape: dynamic_ragged_shape.DynamicRaggedShape, + dtype=dtypes.float32, + name=None, + layout=None, +) -> ragged_tensor.RaggedOrDense: + """Returns ones shaped like x.""" + if layout is not None and not layout.is_fully_replicated(): + raise ValueError( + f'RaggedTensor only allows replicated layout. got {layout}' + ) + flat_values = array_ops.ones( + shape.inner_shape, dtype=dtype, name=name, layout=layout + ) + return shape._add_row_partitions(flat_values) # pylint: disable=protected-access + + +@dispatch.dispatch_for_api(array_ops.zeros) +def zeros( + shape: dynamic_ragged_shape.DynamicRaggedShape, + dtype=dtypes.float32, + name=None, + layout=None, +) -> ragged_tensor.RaggedOrDense: + """Returns ones shaped like x.""" + if layout is not None and not layout.is_fully_replicated(): + raise ValueError( + f'RaggedTensor only allows replicated layout. got {layout}' + ) + flat_values = array_ops.zeros( + shape.inner_shape, dtype=dtype, name=name, layout=layout + ) + return shape._add_row_partitions(flat_values) # pylint: disable=protected-access + + +@dispatch.dispatch_for_api(array_ops.fill) +def fill( + dims: dynamic_ragged_shape.DynamicRaggedShape, + value: core_types.TensorLike, + name: Optional[str] = None, + layout=None, +) -> ragged_tensor.RaggedOrDense: + """Creates a tensor with shape `dims` and fills it with `value`.""" + if layout is not None and not layout.is_fully_replicated(): + raise ValueError( + f'RaggedTensor only allows replicated layout. got {layout}' + ) + flat_values = array_ops.fill( + dims.inner_shape, value, name=name, layout=layout + ) + return dims._add_row_partitions(flat_values) # pylint: disable=protected-access + + +# =============================================================================== +# bitcast +# =============================================================================== +@dispatch.dispatch_for_api(array_ops.bitcast) +def bitcast( + input: ragged_tensor.RaggedOrDense, # pylint: disable=redefined-builtin + type, # pylint: disable=redefined-builtin + name=None) -> ragged_tensor.RaggedOrDense: + """RaggedTensor dispatch override for tf.bitcast.""" + type = dtypes.as_dtype(type) + with ops.name_scope(name, 'Bitcast', [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input, name='input') + if (input.dtype.size < type.size and input.flat_values.shape.rank < 2): + raise ValueError('`input.flat_values` is required to have rank >= 2 when ' + 'input.dtype.size < type.size. Actual rank: ' + f'{input.flat_values.shape.rank}') + return input.with_flat_values(array_ops.bitcast(input.flat_values, type)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_autograph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_autograph.py new file mode 100644 index 0000000000000000000000000000000000000000..9e366d274069129adfe9b6b52a2eba522f4be237 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_autograph.py @@ -0,0 +1,73 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Autograph-specific overrides for ragged_tensor.""" +from tensorflow.python.autograph.operators import control_flow +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops.ragged import ragged_tensor + + +def _tf_ragged_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts +): + """Overload of for_stmt that iterates over TF ragged tensors.""" + init_vars = get_state() + control_flow.verify_loop_init_vars(init_vars, symbol_names) + + # TODO(mdan): Move this into len()? Requires eager support. + if iter_.shape and iter_.shape[0] is not None: + n = iter_.shape[0] + else: + n = iter_.row_lengths()[0] + + iterate_index = 0 + + def aug_get_state(): + return (iterate_index,) + get_state() + + def aug_set_state(aug_loop_vars): + nonlocal iterate_index + # TODO(b/171479293): Drop the lint override. + iterate_index, *loop_vars = aug_loop_vars # pylint:disable=unused-variable + # The iteration index is not "output" by the for loop. If the iteration + # index is used outside the loop, it will appear + # in the loop vars separately. + set_state(loop_vars) + + def aug_body(): + nonlocal iterate_index + body(iter_[iterate_index]) + iterate_index += 1 + + def aug_test(): + main_test = iterate_index < n + if extra_test is not None: + return tf_cond.cond(main_test, extra_test, lambda: False) + return main_test + + control_flow._add_max_iterations_hint(opts, n) # pylint: disable=protected-access + + control_flow._tf_while_stmt( # pylint: disable=protected-access + aug_test, + aug_body, + aug_get_state, + aug_set_state, + ('',) + symbol_names, + opts, + ) + + +control_flow.for_loop_registry.register( + ragged_tensor.RaggedTensor, _tf_ragged_for_stmt +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..c9482bc3cc02240fb0b86cb4865044c4181ab7f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_ops.py @@ -0,0 +1,60 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Batch gather operations for RaggedTensors.""" + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops.ragged import ragged_gather_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +#=============================================================================== +# ragged.batch_gather +#=============================================================================== +@dispatch.dispatch_for_api(array_ops.batch_gather) +def batch_gather(params: ragged_tensor.RaggedOrDense, + indices: ragged_tensor.RaggedOrDense, + name=None): + """Gathers slices from `params` according to `indices` with batch dims. + + This operation is similar to `gather`, but it assumes that the leading `N` + dimensions of `indices` and `params` are batch dimensions, and performs a + gather within each batch. In particular, when using this operation with `N` + batch dimensions `B1...BN`: + + * `indices` has shape `[B1...BN, I]` + * `params` has shape `[B1...BN, P1...PM]`. + * `result` has shape `[B1...BN, I, P2...PM]`. + * `result[b1...bN, i, p2...pM] = + params[b1...bN, indices[b1...bN, i], p2...pM]` + + Args: + params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`, + `M>0`). + indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`). + name: A name for the operation (optional). + + Returns: + A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`. + `result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`. + + #### Example: + + >>> params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']]) + >>> indices = tf.ragged.constant([[1, 2, 0], [], [], [0, 0]]) + >>> tf.compat.v1.batch_gather(params, indices) + + """ + return ragged_gather_ops.gather(params, indices, batch_dims=-1, name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8cfdc583f6801550ba501f4316a052855a0173 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_batch_gather_with_default_op.py @@ -0,0 +1,179 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Array operations for RaggedTensors.""" + + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_dispatch # pylint: disable=unused-import +from tensorflow.python.ops.ragged import ragged_operators # pylint: disable=unused-import +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_shape +from tensorflow.python.ops.ragged import ragged_where_op + + +#=============================================================================== +# ragged.batch_gather_with_default +#=============================================================================== +def batch_gather_with_default(params, + indices, + default_value='', + name=None): + """Same as `batch_gather` but inserts `default_value` for invalid indices. + + This operation is similar to `batch_gather` except that it will substitute + the value for invalid indices with `default_value` as the contents. + See `batch_gather` for more details. + + + Args: + params: A potentially ragged tensor with shape `[B1...BN, P1...PM]` (`N>=0`, + `M>0`). + indices: A potentially ragged tensor with shape `[B1...BN, I]` (`N>=0`). + default_value: A value to be inserted in places where `indices` are out of + bounds. Must be the same dtype as params and either a scalar or rank 1. + name: A name for the operation (optional). + + Returns: + A potentially ragged tensor with shape `[B1...BN, I, P2...PM]`. + `result.ragged_rank = max(indices.ragged_rank, params.ragged_rank)`. + + #### Example: + + >>> params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']]) + >>> indices = tf.ragged.constant([[1, 2, -1], [], [], [0, 10]]) + >>> batch_gather_with_default(params, indices, 'FOO') + + + """ + with ops.name_scope(name, 'RaggedBatchGatherWithDefault'): + params = ragged_tensor.convert_to_tensor_or_ragged_tensor( + params, name='params', + ) + indices = ragged_tensor.convert_to_tensor_or_ragged_tensor( + indices, name='indices', + ) + default_value = ragged_tensor.convert_to_tensor_or_ragged_tensor( + default_value, name='default_value', + ) + row_splits_dtype, (params, indices, default_value) = ( + ragged_tensor.match_row_splits_dtypes(params, indices, default_value, + return_dtype=True)) + # TODO(hterry): lift this restriction and support default_values of + # of rank > 1 + if default_value.shape.ndims not in (0, 1): + raise ValueError('"default_value" must be a scalar or vector') + upper_bounds = None + if indices.shape.ndims is None: + raise ValueError('Indices must have a known rank.') + if params.shape.ndims is None: + raise ValueError('Params must have a known rank.') + + num_batch_dimensions = indices.shape.ndims - 1 + pad = None + # The logic for this works as follows: + # - create a padded params, where: + # padded_params[b1...bn, 0] = default_value + # padded_params[b1...bn, i] = params[b1...bn, i-1] (i>0) + # - create an `upper_bounds` Tensor that contains the number of elements + # in each innermost rank. Broadcast `upper_bounds` to be the same shape + # as `indices`. + # - check to see which index in `indices` are out of bounds and substitute + # it with the index containing `default_value` (the first). + # - call batch_gather with the indices adjusted. + with ops.control_dependencies([ + check_ops.assert_greater_equal(array_ops.rank(params), + array_ops.rank(indices))]): + if ragged_tensor.is_ragged(params): + row_lengths = ragged_array_ops.expand_dims( + params.row_lengths(axis=num_batch_dimensions), + axis=-1) + upper_bounds = math_ops.cast(row_lengths, indices.dtype) + + pad_shape = _get_pad_shape(params, indices, row_splits_dtype) + + pad = ragged_tensor_shape.broadcast_to( + default_value, pad_shape) + else: + params_shape = array_ops.shape(params) + pad_shape = array_ops.concat([ + params_shape[:num_batch_dimensions], + [1], + params_shape[num_batch_dimensions + 1:params.shape.ndims] + ], 0) + upper_bounds = params_shape[num_batch_dimensions] + pad = array_ops.broadcast_to(default_value, pad_shape) + + # Add `default_value` as the first value in the innermost (ragged) rank. + pad = math_ops.cast(pad, params.dtype) + padded_params = array_ops.concat( + [pad, params], axis=num_batch_dimensions) + + # Adjust the indices by substituting out-of-bound indices to the + # default-value index (which is the first element) + shifted_indices = indices + 1 + is_out_of_bounds = (indices < 0) | (indices > upper_bounds) + adjusted_indices = ragged_where_op.where( + is_out_of_bounds, + x=array_ops.zeros_like(indices), y=shifted_indices, + ) + return array_ops.batch_gather( + params=padded_params, indices=adjusted_indices, name=name) + + +def _get_pad_shape(params, indices, row_splits_dtype): + """Gets the RaggedTensorDynamicShape for the pad tensor.""" + num_batch_dimensions = indices.shape.ndims - 1 + params_shape = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor( + params, dim_size_dtype=row_splits_dtype) + + # We want to create a pad tensor that can be concatenated with the params. + if params.shape.ndims == indices.shape.ndims: + # When params and indices are the same rank, the shape of the pad tensor is + # almost identical to params, except the last dimension which has size = 1. + if params_shape.num_inner_dimensions == 0: + pad_dims = params_shape.partitioned_dim_sizes[:-1] + ( + array_ops.ones_like(params_shape.partitioned_dim_sizes[-1]),) + return ragged_tensor_shape.RaggedTensorDynamicShape( + pad_dims, []) + else: + return ragged_tensor_shape.RaggedTensorDynamicShape( + params_shape.partitioned_dim_sizes, + array_ops.concat([params_shape.inner_dim_sizes[:-1], [1]], axis=0)) + else: + # When the rank of indices < params, the pad has the same dimension as + # params up to the 'num_batch_dimensions' rank. Every dimension after that + # has size 1. + pad_dims = None + if num_batch_dimensions == 0: + pad_dims = (constant_op.constant(1, dtype=row_splits_dtype),) + ( + constant_op.constant([1], dtype=row_splits_dtype),) * ( + params_shape.num_partitioned_dimensions - + num_batch_dimensions - 1) + else: + batch_dimensions = params_shape.partitioned_dim_sizes[ + :num_batch_dimensions] + gather_dimension = params_shape.partitioned_dim_sizes[ + num_batch_dimensions] + pad_dims = batch_dimensions + ( + array_ops.ones_like(gather_dimension),) * ( + params_shape.num_partitioned_dimensions - num_batch_dimensions) + + return ragged_tensor_shape.RaggedTensorDynamicShape( + pad_dims, params_shape.inner_dim_sizes) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_bincount_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_bincount_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7cae73ba66db8c3cabd2a52b4533a98173e1c9eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_bincount_ops.py @@ -0,0 +1,405 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# maxlengthations under the License. +# ============================================================================== +"""bincount ops for RaggedTensors.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import bincount_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import gen_count_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(bincount_ops.bincount) +def bincount(arr: ragged_tensor.RaggedTensor, + weights=None, + minlength=None, + maxlength=None, + dtype=dtypes.int32, + name=None, + axis=None, + binary_output=False): + """Counts the number of occurrences of each value in an integer array. + + If `minlength` and `maxlength` are not given, returns a vector with length + `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. + + >>> data = tf.ragged.constant([[1, 1], [2, 3, 2, 4, 4, 5]]) + >>> tf.math.bincount(data) + + + Vector length = Maximum element in vector `values` is 5. Adding 1, which is 6 + will be the vector length. + + Each bin value in the output indicates number of occurrences of the particular + index. Here, index 1 in output has a value 2. This indicates value 1 occurs + two times in `values`. + + **Bin-counting with weights** + + >>> data = tf.ragged.constant([[1, 1], [2, 3, 2, 4, 4, 5]]) + >>> weights = tf.ragged.constant([[1, 5], [0, 1, 0, 5, 4, 5]]) + >>> tf.math.bincount(data, weights=weights) + + + When `weights` is specified, bins will be incremented by the corresponding + weight instead of 1. Here, index 1 in output has a value 6. This is the + summation of `weights` corresponding to the value in `arr` (i.e. for index + 1, the first two values `arr` are 1 so the first two weights, 1 and 5, are + summed). + + There is an equivilance between bin-counting with weights and + `unsorted_segement_sum` where `data` is the weights and `segment_ids` are the + values. + + >>> data = tf.ragged.constant([[1, 1], [2, 3, 2, 4, 4, 5]]) + >>> weights = tf.ragged.constant([[1, 5], [0, 1, 0, 5, 4, 5]]) + >>> tf.math.unsorted_segment_sum(weights, data, num_segments=6).numpy() + array([0, 6, 0, 1, 9, 5], dtype=int32) + + On GPU, `bincount` with weights is only supported when XLA is enabled + (typically when a function decorated with `@tf.function(jit_compile=True)`). + `unsorted_segment_sum` can be used as a workaround for the non-XLA case on + GPU. + + **Bin-counting matrix rows independently** + + This example uses `axis=-1` with a 2 dimensional input and returns a + `Tensor` with bincounting where axis 0 is **not** flattened, i.e. an + independent bincount for each matrix row. + + >>> data = tf.ragged.constant([[1, 2], [3, 0, 0, 0, 1, 2]], dtype=np.int32) + >>> tf.math.bincount(data, axis=-1) + + + **Bin-counting with binary_output** + + This example gives binary output instead of counting the occurrence. + + >>> data = tf.ragged.constant([[1, 2], [3, 0, 0, 0, 1, 2]], dtype=np.int32) + >>> tf.math.bincount(data, axis=-1, binary_output=True) + + + Args: + arr: A RaggedTensor whose values should be counted. + These tensors must have a rank of 2 if `axis=-1`. + weights: If non-None, must be a RaggedTensor with the same row splits as + `arr`. For each value in `arr`, the bin will be incremented by the + corresponding weight instead of 1. If non-None, `binary_output` must be + False. + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `arr` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + dtype: If `weights` is None, determines the type of the output bins. + name: A name scope for the associated operations (optional). + axis: The axis to slice over. Axes at and below `axis` will be flattened + before bin counting. Currently, only `0`, and `-1` are supported. If None, + all axes will be flattened (identical to passing `0`). + binary_output: If True, this op will output 1 instead of the number of times + a token appears (equivalent to one_hot + reduce_any instead of one_hot + + reduce_add). Defaults to False. + + Returns: + A vector with the same dtype as `weights` or the given `dtype` containing + the bincount values. + + Raises: + `InvalidArgumentError` if negative values are provided as an input. + + """ + name = "bincount" if name is None else name + with ops.name_scope(name): + arr = ragged_tensor.convert_to_tensor_or_ragged_tensor(arr, name="arr") + if weights is not None: + if not isinstance(weights, sparse_tensor.SparseTensor): + weights = ragged_tensor.convert_to_tensor_or_ragged_tensor( + weights, name="weights") + + if weights is not None and binary_output: + raise ValueError("Arguments `binary_output` and `weights` are mutually " + "exclusive. Please specify only one.") + + if not arr.dtype.is_integer: + arr = math_ops.cast(arr, dtypes.int32) + if axis is None: + axis = 0 + + if axis not in [0, -1]: + raise ValueError(f"Unsupported value for argument axis={axis}. Only 0 and" + " -1 are currently supported.") + + array_is_nonempty = array_ops.size(arr) > 0 + output_size = math_ops.cast(array_is_nonempty, arr.dtype) * ( + math_ops.reduce_max(arr) + 1) + if minlength is not None: + minlength = ops.convert_to_tensor( + minlength, name="minlength", dtype=arr.dtype) + output_size = gen_math_ops.maximum(minlength, output_size) + if maxlength is not None: + maxlength = ops.convert_to_tensor( + maxlength, name="maxlength", dtype=arr.dtype) + output_size = gen_math_ops.minimum(maxlength, output_size) + + if axis == 0: + # Flatten RaggedTensors with multiple ragged dimensions which use a + # nested RaggedTensor for the values tensor. + while isinstance(arr, ragged_tensor.RaggedTensor): + if weights is not None: + weights = validate_ragged_weights(arr, weights, dtype) + arr = arr.values + + if isinstance(arr, ragged_tensor.RaggedTensor): + weights = validate_ragged_weights(arr, weights, dtype) + return gen_math_ops.ragged_bincount( + splits=arr.row_splits, + values=arr.values, + size=output_size, + weights=weights, + binary_output=binary_output) + else: + weights = bincount_ops.validate_dense_weights(arr, weights, dtype) + return gen_math_ops.dense_bincount( + input=arr, + size=output_size, + weights=weights, + binary_output=binary_output) + + +@dispatch.dispatch_for_api(sparse_ops.sparse_bincount) +def sparse_bincount(values: ragged_tensor.RaggedTensor, + weights=None, + axis=0, + minlength=None, + maxlength=None, + binary_output=False, + name=None): + """Count the number of times an integer value appears in a tensor. + + This op takes an N-dimensional `Tensor`, `RaggedTensor`, or `SparseTensor`, + and returns an N-dimensional int64 SparseTensor where element + `[i0...i[axis], j]` contains the number of times the value `j` appears in + slice `[i0...i[axis], :]` of the input tensor. Currently, only N=0 and + N=-1 are supported. + + Args: + values: A RaggedTensor whose values should be + counted. These tensors must have a rank of 2 if `axis=-1`. + weights: If non-None, must be a RaggedTensor with the same row splits as + `values`. For each value in `value`, the bin will be incremented by the + corresponding weight instead of 1. + axis: The axis to slice over. Axes at and below `axis` will be flattened + before bin counting. Currently, only `0`, and `-1` are supported. If None, + all axes will be flattened (identical to passing `0`). + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `values` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + binary_output: If True, this op will output 1 instead of the number of times + a token appears (equivalent to one_hot + reduce_any instead of one_hot + + reduce_add). Defaults to False. + name: A name for this op. + + Returns: + A SparseTensor with `output.shape = values.shape[:axis] + [N]`, where `N` is + * `maxlength` (if set); + * `minlength` (if set, and `minlength > reduce_max(values)`); + * `0` (if `values` is empty); + * `reduce_max(values) + 1` otherwise. + + Raises: + `InvalidArgumentError` if negative values are provided as an input. + + Examples: + + **Bin-counting every item in individual batches** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where the value of (i,j) is the + number of times value j appears in batch i. + + >>> data = tf.ragged.constant( + ... [[10, 20], [30, 20, 11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount(data, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 1 11] + [ 1 20] + [ 1 30] + [ 1 101] + [ 1 10001]], shape=(7, 2), dtype=int64), + values=tf.Tensor([1 1 2 1 1 1 1], shape=(7,), dtype=int64), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + **Bin-counting with defined output shape** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where the value of (i,j) is the + number of times value j appears in batch i. However, all values of j + above 'maxlength' are ignored. The dense_shape of the output sparse tensor + is set to 'minlength'. Note that, while the input is identical to the + example above, the value '10001' in batch item 2 is dropped, and the + dense shape is [2, 500] instead of [2,10002] or [2, 102]. + + >>> minlength = maxlength = 500 + >>> data = tf.ragged.constant( + ... [[10, 20], [30, 20, 11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount( + ... data, axis=-1, minlength=minlength, maxlength=maxlength) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 1 11] + [ 1 20] + [ 1 30] + [ 1 101]], shape=(6, 2), dtype=int64), + values=tf.Tensor([1 1 2 1 1 1], shape=(6,), dtype=int64), + dense_shape=tf.Tensor([ 2 500], shape=(2,), dtype=int64)) + + **Binary bin-counting** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where (i,j) is 1 if the value j + appears in batch i at least once and is 0 otherwise. Note that, even though + some values (like 20 in batch 1 and 11 in batch 2) appear more than once, + the 'values' tensor is all 1s. + + >>> data = tf.ragged.constant( + ... [[10, 20], [30, 20, 11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount(data, binary_output=True, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 1 11] + [ 1 20] + [ 1 30] + [ 1 101] + [ 1 10001]], shape=(7, 2), dtype=int64), + values=tf.Tensor([1 1 1 1 1 1 1], shape=(7,), dtype=int64), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + **Weighted bin-counting** + + This example takes two inputs - a values tensor and a weights tensor. These + tensors must be identically shaped, and have the same row splits or indices + in the case of RaggedTensors or SparseTensors. When performing a weighted + count, the op will output a SparseTensor where the value of (i, j) is the + sum of the values in the weight tensor's batch i in the locations where + the values tensor has the value j. In this case, the output dtype is the + same as the dtype of the weights tensor. + + >>> data = tf.ragged.constant( + ... [[10, 20], [30, 20, 11, 101, 11, 10001]], dtype=np.int64) + >>> weights = tf.ragged.constant( + ... [[2, 0.25], [15, 0.5, 2, 17, 3, 0.9]]) + >>> tf.sparse.bincount(data, weights=weights, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 1 11] + [ 1 20] + [ 1 30] + [ 1 101] + [ 1 10001]], shape=(7, 2), dtype=int64), + values=tf.Tensor([ 2. 0.25 5. 0.5 15. 17. 0.9 ], shape=(7,), dtype=float32), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + """ + with ops.name_scope(name, "count", [values, weights]): + values = ragged_tensor.convert_to_tensor_or_ragged_tensor( + values, name="values") + if weights is not None: + if not isinstance(weights, sparse_tensor.SparseTensor): + weights = ragged_tensor.convert_to_tensor_or_ragged_tensor( + weights, name="weights") + + if weights is not None and binary_output: + raise ValueError("Arguments `binary_output` and `weights` are mutually " + "exclusive. Please specify only one.") + + if axis is None: + axis = 0 + + if axis not in [0, -1]: + raise ValueError(f"Unsupported value for argument axis={axis}. Only 0 and" + " -1 are currently supported.") + + minlength_value = minlength if minlength is not None else -1 + maxlength_value = maxlength if maxlength is not None else -1 + + if axis == 0: + if weights is not None: + weights = validate_ragged_weights(values, weights) + values = values.values + + if isinstance(values, ragged_tensor.RaggedTensor): + weights = validate_ragged_weights(values, weights) + c_ind, c_val, c_shape = gen_count_ops.ragged_count_sparse_output( + values.row_splits, + values.values, + weights, + minlength=minlength_value, + maxlength=maxlength_value, + binary_output=binary_output) + else: + weights = bincount_ops.validate_dense_weights(values, weights) + c_ind, c_val, c_shape = gen_count_ops.dense_count_sparse_output( + values, + weights=weights, + minlength=minlength_value, + maxlength=maxlength_value, + binary_output=binary_output) + + return sparse_tensor.SparseTensor(c_ind, c_val, c_shape) + + +def validate_ragged_weights(values, weights, dtype=None): + """Validates the passed weight tensor or creates an empty one.""" + if weights is None: + if dtype: + return array_ops.constant([], dtype=dtype) + return array_ops.constant([], dtype=values.values.dtype) + + if not isinstance(weights, ragged_tensor.RaggedTensor): + raise ValueError( + "`weights` must be a RaggedTensor if `values` is a RaggedTensor. " + f"Received argument weights={weights} of type: " + f"{type(weights).__name__}.") + + checks = [] + if weights.row_splits is not values.row_splits: + checks.append( + check_ops.assert_equal( + weights.row_splits, + values.row_splits, + message="'weights' and 'values' must have the same row splits.")) + if checks: + with ops.control_dependencies(checks): + weights = array_ops.identity(weights.values) + else: + weights = weights.values + + return weights diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_check_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_check_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8b96abc618fcd21ed789750180201e19c1c329 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_check_ops.py @@ -0,0 +1,27 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Asserts and Boolean Checks for RaggedTensors.""" + +from tensorflow.python.ops import check_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(check_ops.assert_type) +def assert_type(tensor: ragged_tensor.Ragged, tf_type, message=None, name=None): + return check_ops.assert_type(tensor.flat_values, tf_type, + message=message, name=name) + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_concat_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_concat_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..04e9b29d8c3a87b4b7f07563c8fcfae60b448d1e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_concat_ops.py @@ -0,0 +1,330 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Concat and stack operations for RaggedTensors.""" + +import typing + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_gather_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_util +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@dispatch.dispatch_for_api(array_ops.concat) +def concat(values: typing.List[ragged_tensor.RaggedOrDense], axis, name=None): + """Concatenates potentially ragged tensors along one dimension. + + Given a list of tensors with the same rank `K` (`K >= axis`), returns a + rank-`K` `RaggedTensor` `result` such that `result[i0...iaxis]` is the + concatenation of `[rt[i0...iaxis] for rt in values]`. + + Args: + values: A list of potentially ragged tensors. May not be empty. All + `values` must have the same rank and the same dtype; but unlike + `tf.concat`, they can have arbitrary shapes. + axis: A python integer, indicating the dimension along which to concatenate. + (Note: Unlike `tf.concat`, the `axis` parameter must be statically known.) + Negative values are supported only if the rank of at least one + `values` value is statically known. + name: A name prefix for the returned tensor (optional). + + Returns: + A `RaggedTensor` with rank `K`. + `result.ragged_rank=max(axis, max(rt.ragged_rank for rt in values]))`. + + Raises: + ValueError: If `values` is empty, if `axis` is out of bounds or if + the input tensors have different ranks. + + #### Example: + + >>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]]) + >>> t2 = tf.ragged.constant([[6], [7, 8, 9]]) + >>> tf.concat([t1, t2], axis=0) + + >>> tf.concat([t1, t2], axis=1) + + """ + if not isinstance(values, (list, tuple)): + values = [values] + with ops.name_scope(name, 'RaggedConcat', values): + return _ragged_stack_concat_helper(values, axis, stack_values=False) + + +@tf_export('ragged.stack') +@dispatch.add_dispatch_support +@dispatch.dispatch_for_api(array_ops_stack.stack) +def stack(values: typing.List[ragged_tensor.RaggedOrDense], + axis=0, + name=None): + """Stacks a list of rank-`R` tensors into one rank-`(R+1)` `RaggedTensor`. + + Given a list of tensors or ragged tensors with the same rank `R` + (`R >= axis`), returns a rank-`R+1` `RaggedTensor` `result` such that + `result[i0...iaxis]` is `[value[i0...iaxis] for value in values]`. + + #### Examples: + + >>> # Stacking two ragged tensors. + >>> t1 = tf.ragged.constant([[1, 2], [3, 4, 5]]) + >>> t2 = tf.ragged.constant([[6], [7, 8, 9]]) + >>> tf.ragged.stack([t1, t2], axis=0) + + >>> tf.ragged.stack([t1, t2], axis=1) + + + >>> # Stacking two dense tensors with different sizes. + >>> t3 = tf.constant([[1, 2, 3], [4, 5, 6]]) + >>> t4 = tf.constant([[5], [6], [7]]) + >>> tf.ragged.stack([t3, t4], axis=0) + + + Args: + values: A list of `tf.Tensor` or `tf.RaggedTensor`. May not be empty. All + `values` must have the same rank and the same dtype; but unlike + `tf.stack`, they can have arbitrary dimension sizes. + axis: A python integer, indicating the dimension along which to stack. + (Note: Unlike `tf.stack`, the `axis` parameter must be statically known.) + Negative values are supported only if the rank of at least one + `values` value is statically known. + name: A name prefix for the returned tensor (optional). + + Returns: + A `RaggedTensor` with rank `R+1` (if `R>0`). + If `R==0`, then the result will be returned as a 1D `Tensor`, since + `RaggedTensor` can only be used when `rank>1`. + `result.ragged_rank=1+max(axis, max(rt.ragged_rank for rt in values]))`. + + Raises: + ValueError: If `values` is empty, if `axis` is out of bounds or if + the input tensors have different ranks. + """ + if not isinstance(values, (list, tuple)): + values = [values] + with ops.name_scope(name, 'RaggedConcat', values): + return _ragged_stack_concat_helper(values, axis, stack_values=True) + + +def _ragged_stack_concat_helper(rt_inputs, axis, stack_values): + """Helper function to concatenate or stack ragged tensors. + + Args: + rt_inputs: A list of RaggedTensors or Tensors to combine. + axis: The axis along which to concatenate or stack. + stack_values: A boolean -- if true, then stack values; otherwise, + concatenate them. + + Returns: + A RaggedTensor. + Raises: + ValueError: If rt_inputs is empty, or if axis is out of range. + """ + # Validate parameters. + if not rt_inputs: + raise ValueError('rt_inputs may not be empty.') + + # Convert input tensors. + rt_inputs = [ + ragged_tensor.convert_to_tensor_or_ragged_tensor( + rt_input, name='rt_input') for rt_input in rt_inputs + ] + row_splits_dtype, rt_inputs = ragged_tensor.match_row_splits_dtypes( + *rt_inputs, return_dtype=True) + rt_inputs = list(rt_inputs) + + # Special case: if there's only one input, then return it as-is. + if len(rt_inputs) == 1 and not stack_values: + return rt_inputs[0] + + # Check the rank (number of dimensions) of the input tensors. + ndims = None + for rt in rt_inputs: + if ndims is None: + ndims = rt.shape.ndims + else: + rt.shape.assert_has_rank(ndims) + + out_ndims = ndims if (ndims is None or not stack_values) else ndims + 1 + axis = array_ops.get_positive_axis(axis, out_ndims) + + if stack_values and ndims == 1 and axis == 0: + return ragged_tensor.RaggedTensor.from_row_lengths( + values=array_ops.concat(rt_inputs, axis=0), + row_lengths=array_ops.concat([array_ops.shape(r) for r in rt_inputs], + axis=0)) + + # If all the inputs are Tensors, and we're combining the final dimension, + # then we can delegate to the tf.stack/tf.concat operation, and return a + # Tensor. + if all(not ragged_tensor.is_ragged(rt) for rt in rt_inputs): + if ndims is not None and (axis == out_ndims - 1 or axis == ndims - 1): + if stack_values: + return array_ops_stack.stack(rt_inputs, axis) + else: + return array_ops.concat(rt_inputs, axis) + + # Convert any Tensor inputs to RaggedTensors. This makes it + # possible to concatenate Tensors and RaggedTensors together. + for i in range(len(rt_inputs)): + if not ragged_tensor.is_ragged(rt_inputs[i]): + rt_inputs[i] = ragged_tensor.RaggedTensor.from_tensor( + rt_inputs[i], ragged_rank=1, row_splits_dtype=row_splits_dtype) + + # Convert the input tensors to all have the same ragged_rank. + ragged_rank = max(max(rt.ragged_rank for rt in rt_inputs), 1) + rt_inputs = [_increase_ragged_rank_to(rt, ragged_rank, row_splits_dtype) + for rt in rt_inputs] + + if axis == 0: + return _ragged_stack_concat_axis_0(rt_inputs, stack_values) + elif axis == 1: + return _ragged_stack_concat_axis_1(rt_inputs, stack_values) + else: # axis > 1: recurse. + values = [rt.values for rt in rt_inputs] + splits = [[rt_input.row_splits] for rt_input in rt_inputs] + with ops.control_dependencies(ragged_util.assert_splits_match(splits)): + return ragged_tensor.RaggedTensor.from_row_splits( + _ragged_stack_concat_helper(values, axis - 1, stack_values), + splits[0][0], validate=False) + + +def _ragged_stack_concat_axis_0(rt_inputs, stack_values): + """Helper function to concatenate or stack ragged tensors along axis 0. + + Args: + rt_inputs: A list of RaggedTensors, all with the same rank and ragged_rank. + stack_values: Boolean. If true, then stack values; otherwise, concatenate + them. + + Returns: + A RaggedTensor. + """ + # Concatenate the inner values together. + flat_values = [rt.flat_values for rt in rt_inputs] + concatenated_flat_values = array_ops.concat(flat_values, axis=0) + + # Concatenate the splits together for each ragged dimension (adjusting + # split offsets as necessary). + nested_splits = [rt.nested_row_splits for rt in rt_inputs] + ragged_rank = rt_inputs[0].ragged_rank + concatenated_nested_splits = [ + _concat_ragged_splits([ns[dim] + for ns in nested_splits]) + for dim in range(ragged_rank) + ] + + # If we are performing a stack operation, then add another splits. + if stack_values: + stack_lengths = array_ops_stack.stack([rt.nrows() for rt in rt_inputs]) + stack_splits = ragged_util.lengths_to_splits(stack_lengths) + concatenated_nested_splits.insert(0, stack_splits) + + return ragged_tensor.RaggedTensor.from_nested_row_splits( + concatenated_flat_values, concatenated_nested_splits, validate=False) + + +def _ragged_stack_concat_axis_1(rt_inputs, stack_values): + """Helper function to concatenate or stack ragged tensors along axis 1. + + Args: + rt_inputs: A list of RaggedTensors, all with the same rank and ragged_rank. + stack_values: Boolean. If true, then stack values; otherwise, concatenate + them. + + Returns: + A RaggedTensor. + """ + num_inputs = len(rt_inputs) + + nrows_checks = [] + rt_nrows = rt_inputs[0].nrows() + for index, rt in enumerate(rt_inputs[1:]): + nrows_checks.append( + check_ops.assert_equal( + rt_nrows, + rt.nrows(), + message=( + f'Input tensors at index 0 (=x) and {index+1} (=y) have' + ' incompatible shapes.' + ), + ) + ) + + with ops.control_dependencies(nrows_checks): + # Concatenate the inputs together to put them in a single ragged tensor. + concatenated_rt = _ragged_stack_concat_axis_0(rt_inputs, stack_values=False) + + # Use ragged.gather to permute the rows of concatenated_rt. In particular, + # permuted_rt = [rt_inputs[0][0], ..., rt_inputs[N][0], + # rt_inputs[0][1], ..., rt_inputs[N][1], + # ..., + # rt_inputs[0][M], ..., rt_input[N][M]] + # where `N=num_inputs-1` and `M=rt_nrows-1`. + row_indices = math_ops.range(rt_nrows * num_inputs) + row_index_matrix = array_ops.reshape(row_indices, [num_inputs, -1]) + transposed_row_index_matrix = array_ops.transpose(row_index_matrix) + row_permutation = array_ops.reshape(transposed_row_index_matrix, [-1]) + permuted_rt = ragged_gather_ops.gather(concatenated_rt, row_permutation) + + if stack_values: + # Add a new splits tensor to group together the values. + stack_splits = math_ops.range(0, rt_nrows * num_inputs + 1, num_inputs) + _copy_row_shape(rt_inputs, stack_splits) + return ragged_tensor.RaggedTensor.from_row_splits( + permuted_rt, stack_splits, validate=False) + else: + # Merge together adjacent rows by dropping the row-split indices that + # separate them. + concat_splits = permuted_rt.row_splits[::num_inputs] + _copy_row_shape(rt_inputs, concat_splits) + return ragged_tensor.RaggedTensor.from_row_splits( + permuted_rt.values, concat_splits, validate=False) + + +def _copy_row_shape(rt_inputs, splits): + """Sets splits.shape to [rt[shape[0]+1] for each rt in rt_inputs.""" + for rt in rt_inputs: + if rt.shape[0] is not None: + splits.set_shape(tensor_shape.TensorShape(rt.shape[0] + 1)) + + +def _increase_ragged_rank_to(rt_input, ragged_rank, row_splits_dtype): + """Adds ragged dimensions to `rt_input` so it has the desired ragged rank.""" + if ragged_rank > 0: + if not ragged_tensor.is_ragged(rt_input): + rt_input = ragged_tensor.RaggedTensor.from_tensor( + rt_input, row_splits_dtype=row_splits_dtype) + if rt_input.ragged_rank < ragged_rank: + rt_input = rt_input.with_values( + _increase_ragged_rank_to(rt_input.values, ragged_rank - 1, + row_splits_dtype)) + return rt_input + + +def _concat_ragged_splits(splits_list): + """Concatenates a list of RaggedTensor splits to form a single splits.""" + pieces = [splits_list[0]] + splits_offset = splits_list[0][-1] + for splits in splits_list[1:]: + pieces.append(splits[1:] + splits_offset) + splits_offset += splits[-1] + return array_ops.concat(pieces, axis=0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cf19c5a62012f771122732ff8f7fb350ff5659f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_config.py @@ -0,0 +1,29 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Configuration parameters for RaggedTensors.""" + + +def auto_cast_partition_dtype(): + """Whether incompatible row-partitioning dtypes should be auto-converted. + + If true, then operations that combine RaggedTensors but have different + row-partitioning tensor dtypes will be automatically cast to a + compatible dtype (`tf.int64`). If false, then such operations will result + in an error. + + Returns: + `bool` + """ + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_conversion_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_conversion_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e71f5cad7929fc034eaa2bad2f6b81110c36b1ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_conversion_ops.py @@ -0,0 +1,180 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops to convert between RaggedTensors and other tensor types.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_ragged_conversion_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_tensor + + +def from_tensor(tensor, + lengths=None, + padding=None, + ragged_rank=1, + row_splits_dtype=dtypes.int64, + name=None): + if ragged_tensor.is_ragged(tensor): + return tensor + else: + return ragged_tensor.RaggedTensor.from_tensor( + tensor, + lengths=lengths, + padding=padding, + ragged_rank=ragged_rank, + row_splits_dtype=row_splits_dtype, + name=name) + + +def to_tensor(rt_input, default_value=None, name=None): + if ragged_tensor.is_ragged(rt_input): + return rt_input.to_tensor(default_value, name) + else: + return rt_input + + +def ragged_to_dense(rt_input, default_value=None, shape=None): + """Create a dense tensor from a ragged tensor.""" + return rt_input.to_tensor(default_value=default_value, shape=shape) + + +@ops.RegisterGradient("RaggedTensorToTensor") +def _ragged_tensor_to_tensor_grad(op, grad): + """Gradient for RaggedToTensor op.""" + # Extract inputs from the op. + flat_values = op.inputs[1] + default_value = op.inputs[2] + row_partition_tensors = op.inputs[3:] + row_partition_types = op.get_attr("row_partition_types") + flat_value_shape = array_ops.shape(flat_values) + ragged_rank = sum( + 1 for typ in row_partition_types if typ != b"FIRST_DIM_SIZE") + + # Create two tensors that correspond 1:1 with grad (and op.output): + # * indices[i1...iN] is the index in `flat_values` of the value used to + # populate output[i1...iN] (if the value came from `flat_values`) or + # -1 (if the value came from `default_value`). + # * mask[i1...iN] is true if output[i1...iN] came from `flat_values`, or + # false if it came from `default_value`. + indices = gen_ragged_conversion_ops.ragged_tensor_to_tensor( + shape=array_ops.shape(grad)[:1 + ragged_rank], + values=math_ops.range(flat_value_shape[0]), + default_value=-1, + row_partition_types=row_partition_types, + row_partition_tensors=row_partition_tensors) + mask = math_ops.not_equal(indices, -1) + + # Select out the gradients & indices that came from `flat_values`, and use + # those to construct the gradient for `flat_values` (as an IndexedSlices). + values_grad = indexed_slices.IndexedSlices( + values=array_ops.boolean_mask(grad, mask), + indices=array_ops.boolean_mask(indices, mask), + dense_shape=flat_value_shape) + + # Select out the gradients that came from `default_value`, and sum them to + # get the gradient for the default. Note that the default_value may have + # been broadcast as part of the RaggedTensorToTensor operation, so we also + # need to reduce any dimensions that might have been broadcast. + default_grads = array_ops.boolean_mask(grad, ~mask) + dims_to_reduce = math_ops.range( + array_ops.rank(default_grads) - + _rank_ignoring_leading_dims_with_size_1(default_value)) + default_grad = math_ops.reduce_sum(default_grads, axis=dims_to_reduce) + + # Restore any leading dims with size one. + default_grad = array_ops.reshape(default_grad, array_ops.shape(default_value)) + + return ([None, values_grad, default_grad] + + [None for _ in row_partition_tensors]) + + +def _rank_ignoring_leading_dims_with_size_1(value): + """Returns `rank(value)`, ignoring any leading dimensions with size 1.""" + # Compute the result using static shape, if possible. + if value.shape.rank is not None: + ndims = value.shape.rank + for dim in value.shape.dims: + if dim.value == 1: + ndims -= 1 + elif dim.value is None: + ndims = None # Can't compute the result using static shape. + break + else: + break + if ndims is not None: + return ndims + + # Otherwise, we need to compute the result dynamically. The math we use to + # do this is a bit round-about, so here's an example to illustrate: + # shape = [1, 1, 3, 5, 1, 4] # shape(value) + # dim_is_one = [1, 1, 0, 0, 1, 0] # equal(shape, 1) + # leading_ones = [1, 1, 0, 0, 0, 0] # cumprod(dim_is_one) + # num_leading_ones = 2 # reduce_sum(leading_ones) + # result = 4 # rank(value) - num_leading_ones + shape = array_ops.shape(value) + dim_is_one = math_ops.cast(math_ops.equal(shape, 1), dtypes.int32) + leading_ones = math_ops.cumprod(dim_is_one) + num_leading_ones = math_ops.reduce_sum(leading_ones) + return array_ops.rank(value) - num_leading_ones + + +def to_sparse(rt_input, name=None): + return rt_input.to_sparse(name) + + +def from_sparse(st_input, name=None): + return ragged_tensor.RaggedTensor.from_sparse(st_input, name) + + +@ops.RegisterGradient("RaggedTensorFromVariant") +def _ragged_tensor_from_variant_grad(op, *grads): + """Gradient for RaggedTensorFromVariant op.""" + + variant_rank = op.inputs[0].shape.rank + if variant_rank == 0: + batched_input = False + elif variant_rank == 1: + batched_input = True + elif variant_rank is None: + batched_input = (op.get_attr("output_ragged_rank") > 0) + else: + # TODO(edloper): Add a batch_dims argument to RaggedTensorToVariant, so + # we can support this. + raise ValueError("Unable to compute gradient: RaggedTensorToVariant " + "can currently only generate 0D or 1D output.") + return [ + gen_ragged_conversion_ops.ragged_tensor_to_variant( + rt_nested_splits=op.outputs[:-1], + rt_dense_values=grads[-1], + batched_input=batched_input) + ] + + +@ops.RegisterGradient("RaggedTensorToVariant") +def _ragged_tensor_to_variant_grad(op, encoded_ragged_grad): + """Gradient for RaggedTensorToVariant op.""" + dense_values = op.inputs[-1] + ragged_rank = len(op.inputs) - 1 + row_splits = 0 if ragged_rank == 0 else op.inputs[0] + values_grad = gen_ragged_conversion_ops.ragged_tensor_to_variant_gradient( + encoded_ragged_grad=encoded_ragged_grad, + row_splits=row_splits, + dense_values_shape=array_ops.shape(dense_values), + Tvalues=op.inputs[-1].dtype) + result = [None] * ragged_rank + [values_grad] + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_dispatch.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..176e18be3d7f520a2e648c7ad3b0d5c2a43fca9c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_dispatch.py @@ -0,0 +1,160 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operator dispatch for RaggedTensors.""" + +from tensorflow.python.ops import logging_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_shape +from tensorflow.python.util import dispatch +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_export +from tensorflow.python.util import tf_inspect + + +@dispatch.dispatch_for_unary_elementwise_apis(ragged_tensor.Ragged) +def ragged_unary_elementwise_op(op, x): + """Unary elementwise api handler for RaggedTensors.""" + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x) + return x.with_values(op(x.values)) + + +# TODO(martinz): This is deprecated. Delete. +def ragged_binary_elementwise_op(op, x, y): + """Binary elementwise api handler for RaggedTensors.""" + x_is_ragged = ragged_tensor.is_ragged(x) + y_is_ragged = ragged_tensor.is_ragged(y) + + # Convert args to tensors. + x = ragged_tensor.convert_to_tensor_or_ragged_tensor( + x, preferred_dtype=(y.dtype if y_is_ragged else None)) + y = ragged_tensor.convert_to_tensor_or_ragged_tensor( + y, preferred_dtype=x.dtype) + + if x_is_ragged and y_is_ragged: + x, y = ragged_tensor.match_row_splits_dtypes(x, y) + + # Perform broadcasting, when appropraite + if ((x_is_ragged and y_is_ragged) or + (x_is_ragged and x.flat_values.shape.ndims <= y.shape.ndims) or + (y_is_ragged and y.flat_values.shape.ndims <= x.shape.ndims)): + # If both x and y are ragged, they must have the same row_splits_dtype now. + if x_is_ragged: + dim_size_dtype = x.row_splits.dtype + else: + dim_size_dtype = y.row_splits.dtype + + shape_x = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor( + x, dim_size_dtype=dim_size_dtype) + shape_y = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor( + y, dim_size_dtype=dim_size_dtype) + bcast_shape = ragged_tensor_shape.broadcast_dynamic_shape(shape_x, shape_y) + x = ragged_tensor_shape.broadcast_to( + x, bcast_shape, broadcast_inner_dimensions=False) + y = ragged_tensor_shape.broadcast_to( + y, bcast_shape, broadcast_inner_dimensions=False) + + x_values = x.flat_values if ragged_tensor.is_ragged(x) else x + y_values = y.flat_values if ragged_tensor.is_ragged(y) else y + mapped_values = op(x_values, y_values) + if isinstance(mapped_values, bool): + return mapped_values # Special case for tensor_equals. + if ragged_tensor.is_ragged(x): + return x.with_flat_values(mapped_values) + else: + return y.with_flat_values(mapped_values) + + +# TODO(edloper): Update the documentation generation tools to automatically +# build lists of which types are supported by which ops (and then delete all +# the following code). + + +# We don't need to register a separate delegation handler for these v1 ops, +# since they delegate to the v2 ops (which already have a handler). But we +# still want to include them in the ragged_op_list() output. +_V2_OPS_THAT_ARE_DELEGATED_TO_FROM_V1_OPS = [ + math_ops.reduce_sum, + math_ops.reduce_prod, + math_ops.reduce_min, + math_ops.reduce_max, + math_ops.reduce_mean, + math_ops.reduce_variance, + math_ops.reduce_std, + math_ops.reduce_any, + math_ops.reduce_all, + string_ops.string_to_number, + string_ops.string_to_hash_bucket, + string_ops.reduce_join_v2, +] + + +def _ragged_op_signature(op, ragged_args, ragged_varargs=False): + """Returns a signature for the given op, marking ragged args in bold.""" + op_name = tf_export.get_canonical_name_for_symbol(op) + argspec = tf_inspect.getfullargspec(op) + arg_names = argspec.args + + # Mark ragged arguments in bold. + for pos in ragged_args: + arg_names[pos] = '**' + arg_names[pos] + '**' + + # Add argument defaults. + if argspec.defaults is not None: + for pos in range(-1, -len(argspec.defaults) - 1, -1): + arg_names[pos] += '=`{!r}`'.format(argspec.defaults[pos]) + + # Add varargs and keyword args + if argspec.varargs: + if ragged_varargs: + arg_names.append('***' + argspec.varargs + '**') + else: + arg_names.append('*' + argspec.varargs) + if argspec.varkw: + arg_names.append('**' + argspec.varkw) + + return '* `tf.{}`({})'.format(op_name, ', '.join(arg_names)) + + +def _op_is_in_tf_version(op, version): + if version == 1: + return (tf_export.get_v1_names(tf_decorator.unwrap(op)[1]) or + op in _V2_OPS_THAT_ARE_DELEGATED_TO_FROM_V1_OPS) + elif version == 2: + return tf_export.get_v2_names(tf_decorator.unwrap(op)[1]) + else: + raise ValueError('Expected version 1 or 2.') + + +def ragged_op_list(tf_version=2): + """Returns a string listing operations that have dispathers registered.""" + lines = [] + api_signatures = dispatch.type_based_dispatch_signatures_for( + ragged_tensor.RaggedTensor) + for api, signatures in api_signatures.items(): + arg_names = tf_inspect.getargspec(api).args + ragged_args = set() + for signature in signatures: + for arg in signature: + ragged_args.add(arg if isinstance(arg, int) else arg_names.index(arg)) + if _op_is_in_tf_version(api, tf_version): + lines.append(_ragged_op_signature(api, ragged_args)) + + lines.append( + _ragged_op_signature(logging_ops.print_v2, [], ragged_varargs=True)) + return ('\n\n### Additional ops that support `RaggedTensor`\n\n' + 'Arguments that accept `RaggedTensor`s are marked in **bold**.\n\n' + + '\n'.join(sorted(lines)) + 'n') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_embedding_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_embedding_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ea994bfa242d55b639461ed0f5eb0cc9fd4177 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_embedding_ops.py @@ -0,0 +1,432 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Embedding operations.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(embedding_ops.embedding_lookup) +def embedding_lookup( + params, + ids: ragged_tensor.Ragged, + partition_strategy="mod", + name=None, + validate_indices=True, # pylint: disable=unused-argument + max_norm=None, +): + """Look up the ragged ids in a list of embedding tensors. + + Args: + params: A tensor representing the complete embedding tensor having the shape + [e1, ...eM] + ragged_ids: A 'RaggedTensor' with type 'int32' or 'int64' containing the ids + to be looked up in 'params' of shape [r0, ..rN]. Values must be in the + range '[0, params.shape[0]]'. + partition_strategy: A string specifying the partitioning strategy. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value. + name: A name for the operation (optional) + + Returns: + A ragged tensor of shape [r0, r1, ...rN, e1, ...eM]. + + Raises: + ValueError: When params is empty or the type of the ids is not int32 or + int64. + """ + if params is None: + raise ValueError("params must be specified.") + if isinstance(params, (list, tuple)) and not params: + raise ValueError("params should not be empty.") + if ids.dtype != dtypes.int32 and ids.dtype != dtypes.int64: + raise ValueError( + "The values contained by the inputs have type " + f"{str(ids.dtype)}" + " and cannot be processed. All values" + " should be indices, either of type `int32` or `int64`." + ) + + with ops.name_scope(name, "embedding_lookup_ragged") as name: + looked_up_ragged = ragged_functional_ops.map_flat_values( + embedding_ops.embedding_lookup, + params=params, + ids=ids, + partition_strategy=partition_strategy, + max_norm=max_norm, + ) + + return looked_up_ragged + + +@dispatch.dispatch_for_api(embedding_ops.embedding_lookup_sparse) +def embedding_lookup_sparse( + params, + sp_ids: ragged_tensor.Ragged, + sp_weights, + partition_strategy="mod", + name=None, + combiner=None, + max_norm=None, + allow_fast_lookup=False, +): + """Looks up embeddings for the given ids and weights from a list of tensors. + + This op assumes that there is at least one id for each row in the dense tensor + represented by sp_ids (i.e. there are no rows with empty features), and that + all the indices of sp_ids are in canonical row-major order. + + `sp_ids` and `sp_weights` (if not None) are `RaggedTensor`s with rank of 2. + Embeddings are always aggregated along the last dimension. + + It also assumes that all id values lie in the range [0, p0), where p0 + is the sum of the size of params along dimension 0. + + Args: + params: A single tensor representing the complete embedding tensor, or a + list tensors all of same shape except for the first dimension, + representing sharded embedding tensors. Alternatively, a + `PartitionedVariable`, created by partitioning along dimension 0. Each + element must be appropriately sized for the given `partition_strategy`. + sp_ids: `RaggedTensor` with rank 2. The rank is not verified for performance + reasons. + sparse_weights: `RaggedTensor` of same type and shape as `sparse_ids`, + containing float / double weights corresponding to `sparse_ids`, or `None` + if all weights are assumed to be 1.0. + partition_strategy: A string specifying the partitioning strategy, relevant + if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default + is `"mod"`. See `tf.nn.embedding_lookup` for more details. + name: Optional name for the op. + combiner: A string specifying the reduction op. Currently "mean", "sqrtn" + and "sum" are supported. "sum" computes the weighted sum of the embedding + results for each row. "mean" is the weighted sum divided by the total + weight. "sqrtn" is the weighted sum divided by the square root of the sum + of the squares of the weights. Defaults to `mean`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value, before combining. + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sp_ids`, the op + looks up the embeddings for all ids in that row, multiplies them by the + corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined params) = [p0, p1, ..., pm]` + + and + + `shape(sp_ids) = shape(sp_weights) = [d0, d1]` + + then + + `shape(output) = [d0, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id 0, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + TypeError: If `sp_weights` is neither `None` nor of the same type as + `sp_ids`. + ValueError: If `combiner` is not one of {"mean", "sqrtn", "sum"}. + """ + rt_ids = sp_ids + rt_weights = sp_weights + if combiner is None: + combiner = "mean" + if combiner not in ("mean", "sqrtn", "sum"): + raise ValueError( + f"combiner must be one of 'mean', 'sqrtn' or 'sum', got {combiner}" + ) + if isinstance(params, variables.PartitionedVariable): + params = list(params) # Iterate to get the underlying Variables. + if not isinstance(params, list): + params = [params] + ignore_weights = rt_weights is None + if not ignore_weights: + if not isinstance(rt_weights, ragged_tensor.RaggedTensor): + raise TypeError( + f"sp_ids must be of the same type as sp_weights, " + f"received {{type(sp_ids).__name__!r}} for sp_ids and " + f"{{type(sp_weights).__name__!r}} for sp_weights." + ) + rt_ids.values.get_shape().assert_is_compatible_with( + rt_weights.values.get_shape() + ) + rt_ids.get_shape().assert_is_compatible_with(rt_weights.get_shape()) + + with ops.name_scope( + name, "embedding_lookup_sparse", params + [rt_ids] + ) as name: + segment_ids = rt_ids.value_rowids() + ids = rt_ids.flat_values + + return embedding_ops.embedding_lookup_sparse_impl( + params, + segment_ids, + sp_weights, + ids, + combiner, + ignore_weights, + max_norm, + allow_fast_lookup, + partition_strategy, + name, + ) + + +@dispatch.dispatch_for_api(embedding_ops.safe_embedding_lookup_sparse) +def safe_embedding_lookup_sparse( + embedding_weights, + sparse_ids: ragged_tensor.Ragged, + sparse_weights=None, + combiner="mean", + default_id=None, + name=None, + partition_strategy="div", + max_norm=None, + allow_fast_lookup=False, +): + """Lookup embedding results, accounting for invalid IDs and empty features. + + The partitioned embedding in `embedding_weights` must all be the same shape + except for the first dimension. The first dimension is allowed to vary as the + vocabulary size is not necessarily a multiple of `P`. `embedding_weights` + may be a `PartitionedVariable` as returned by using + `tf.compat.v1.get_variable()` with a + partitioner. + + Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs + with non-positive weight. For an entry with no features, the embedding vector + for `default_id` is returned, or the 0-vector if `default_id` is not supplied. + + The ids and weights may be multi-dimensional `SparseTensor`s or + `RaggedTensor`s with rank of 2. For `SpareTensor`s with left-aligned non-zero + entries which can be described as `RaggedTensor`s, use of `RaggedTensor`s can + yield higher performance. Embeddings are always aggregated along the last + dimension. + + Args: + embedding_weights: A single tensor representing the complete embedding + tensor, or a list tensors all of same shape except for the first + dimension, representing sharded embedding tensors. Alternatively, a + `PartitionedVariable`, created by partitioning along dimension 0. Each + element must be appropriately sized for the given `partition_strategy`. + sp_ids: `RaggedTensor` with rank 2. The rank is not verified for performance + reasons. + sparse_weights: `RaggedTensor` of same type and shape as `sparse_ids`, + containing float weights corresponding to `sparse_ids`, or `None` if all + weights are assumed to be 1.0. + combiner: A string specifying how to combine embedding results for each + entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the + default. + default_id: The id to use for an entry with no features. + name: A name for this operation (optional). + partition_strategy: A string specifying the partitioning strategy. Currently + `"div"` and `"mod"` are supported. Default is `"div"`. + max_norm: If not `None`, all embeddings are l2-normalized to max_norm before + combining. + allow_fast_lookup: An optional boolean specifying whether to allow + simplified embedding lookups when `params` is a single tensor and + `max_norm` is `None`. Setting this flag to `True` during training can + cause the use of dense gradients with increased memory footprint. + + Returns: + A dense tensor representing the combined embeddings for the + sparse ids. For each row in the dense tensor represented by `sp_ids`, the op + looks up the embeddings for all ids in that row, multiplies them by the + corresponding weight, and combines these embeddings as specified. + + In other words, if + + `shape(combined embedding_weights) = [p0, p1, ..., pm]` + + and + + `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]` + + then + + `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`. + + For instance, if params is a 10x20 matrix, and sp_ids / sp_weights are + + ```python + [0, 0]: id 1, weight 2.0 + [0, 1]: id 3, weight 0.5 + [1, 0]: id -1, weight 1.0 + [2, 3]: id 1, weight 3.0 + ``` + + `default_id` is 0. + + with `combiner`="mean", then the output will be a 3x20 matrix where + + ```python + output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5) + output[1, :] = (params[0, :] * 1.0) / 1.0 + output[2, :] = (params[1, :] * 3.0) / 3.0 + ``` + + Raises: + ValueError: if `embedding_weights` is empty. + """ + ragged_ids = sparse_ids + ragged_weights = sparse_weights + if embedding_weights is None: + raise ValueError(f"Missing embedding_weights {embedding_weights}.") + if isinstance(embedding_weights, variables.PartitionedVariable): + embedding_weights = list(embedding_weights) # get underlying Variables. + if not isinstance(embedding_weights, list): + embedding_weights = [embedding_weights] + if len(embedding_weights) < 1: + raise ValueError(f"Missing embedding_weights {embedding_weights}.") + + dtype = ragged_weights.dtype if ragged_weights is not None else None + embedding_weights = [ + w + if ( + resource_variable_ops.is_resource_variable(w) + and dtype in (None, w.dtype) + ) + else ops.convert_to_tensor(w, dtype=dtype) + for w in embedding_weights + ] + + with ops.name_scope( + name, "embedding_lookup", embedding_weights + [ragged_ids, ragged_weights] + ) as scope: + # Prune invalid ids and weights. + ragged_ids, ragged_weights = _prune_invalid_ids_ragged( + ragged_ids, ragged_weights + ) + if combiner != "sum": + ragged_ids, ragged_weights = _prune_invalid_weights_ragged( + ragged_ids, ragged_weights + ) + ragged_ids, is_row_empty = ragged_array_ops.fill_empty_rows( + ragged_ids, default_id or 0 + ) + if ragged_weights is not None: + ragged_weights, _ = ragged_array_ops.fill_empty_rows(ragged_weights, 1.0) + + result = embedding_lookup_sparse( + embedding_weights, + ragged_ids, + ragged_weights, + combiner=combiner, + partition_strategy=partition_strategy, + name=None if default_id is None else scope, + max_norm=max_norm, + allow_fast_lookup=allow_fast_lookup, + ) + + if default_id is None: + # Broadcast is_row_empty to the same shape as embedding_lookup_result, + # for use in Select. + is_row_empty = array_ops.tile( + array_ops.reshape(is_row_empty, [-1, 1]), + array_ops_stack.stack([1, array_ops.shape(result)[1]]), + ) + + result = array_ops.where( + is_row_empty, array_ops.zeros_like(result), result, name=scope + ) + + return result + + +def _prune_invalid_ids_ragged(ids, weights): + """Prune invalid IDs (< 0) from the input ids and weights.""" + is_id_valid = math_ops.greater_equal(ids.values, 0) + nrows = ids.nrows() + # TODO(philipphack): Consider calling ragged_array_ops.boolean_mask once the + # resulting performance is comparable to array_ops.boolean_mask. Currently, + # ragged_array_ops.boolean_mask constructs the returned RaggedTensor by + # calling its from_row_splits method which does not set value_row_ids and + # requires it to be computed on demand. + pruned_values = array_ops.boolean_mask_v2(ids.values, is_id_valid) + pruned_value_rowids = array_ops.boolean_mask_v2( + ids.value_rowids(), is_id_valid + ) + ids = ragged_tensor.RaggedTensor.from_value_rowids( + pruned_values, pruned_value_rowids, nrows=nrows, validate=False + ) + if weights is not None: + pruned_weights_values = array_ops.boolean_mask_v2( + weights.values, is_id_valid + ) + weights = ragged_tensor.RaggedTensor.from_value_rowids( + pruned_weights_values, pruned_value_rowids, nrows=nrows, validate=False + ) + + return ids, weights + + +def _prune_invalid_weights_ragged(ids, weights): + """Prune invalid weights (< 0) from the input ids and weights.""" + if weights is not None: + is_weights_valid = math_ops.greater(weights.values, 0) + nrows = ids.nrows() + # TODO(philipphack): Consider calling ragged_array_ops.boolean_mask once the + # resulting performance is comparable to array_ops.boolean_mask. Currently, + # ragged_array_ops.boolean_mask constructs the returned RaggedTensor by + # calling its from_row_splits method which does not set value_row_ids and + # requires it to be computed on demand. + pruned_values = array_ops.boolean_mask_v2(ids.values, is_weights_valid) + pruned_value_rowids = array_ops.boolean_mask_v2( + ids.value_rowids(), is_weights_valid + ) + ids = ragged_tensor.RaggedTensor.from_value_rowids( + pruned_values, pruned_value_rowids, nrows=nrows, validate=False + ) + + pruned_weights_values = array_ops.boolean_mask_v2( + weights.values, is_weights_valid + ) + weights = ragged_tensor.RaggedTensor.from_value_rowids( + pruned_weights_values, pruned_value_rowids, nrows=nrows, validate=False + ) + + return ids, weights diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_factory_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_factory_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9e096e01b56d7a03d3d237846d1a1bf2bd92a8a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_factory_ops.py @@ -0,0 +1,379 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for constructing RaggedTensors.""" + +from typing import Union + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +#=============================================================================== +# Op to construct a constant RaggedTensor from a nested Python list. +#=============================================================================== +@tf_export("ragged.constant") +@dispatch.add_dispatch_support +def constant( + pylist, + dtype=None, + ragged_rank=None, + inner_shape=None, + name=None, + row_splits_dtype=dtypes.int64, +) -> Union[ragged_tensor.RaggedTensor, ops._EagerTensorBase, ops.Operation]: + """Constructs a constant RaggedTensor from a nested Python list. + + Example: + + >>> tf.ragged.constant([[1, 2], [3], [4, 5, 6]]) + + + All scalar values in `pylist` must have the same nesting depth `K`, and the + returned `RaggedTensor` will have rank `K`. If `pylist` contains no scalar + values, then `K` is one greater than the maximum depth of empty lists in + `pylist`. All scalar values in `pylist` must be compatible with `dtype`. + + Args: + pylist: A nested `list`, `tuple` or `np.ndarray`. Any nested element that + is not a `list`, `tuple` or `np.ndarray` must be a scalar value + compatible with `dtype`. + dtype: The type of elements for the returned `RaggedTensor`. If not + specified, then a default is chosen based on the scalar values in + `pylist`. + ragged_rank: An integer specifying the ragged rank of the returned + `RaggedTensor`. Must be nonnegative and less than `K`. Defaults to + `max(0, K - 1)` if `inner_shape` is not specified. Defaults to + `max(0, K - 1 - len(inner_shape))` if `inner_shape` is specified. + inner_shape: A tuple of integers specifying the shape for individual inner + values in the returned `RaggedTensor`. Defaults to `()` if `ragged_rank` + is not specified. If `ragged_rank` is specified, then a default is chosen + based on the contents of `pylist`. + name: A name prefix for the returned tensor (optional). + row_splits_dtype: data type for the constructed `RaggedTensor`'s row_splits. + One of `tf.int32` or `tf.int64`. + + Returns: + A potentially ragged tensor with rank `K` and the specified `ragged_rank`, + containing the values from `pylist`. + + Raises: + ValueError: If the scalar values in `pylist` have inconsistent nesting + depth; or if ragged_rank or inner_shape are incompatible with `pylist`. + """ + def ragged_factory(values, row_splits): + row_splits = constant_op.constant(row_splits, dtype=row_splits_dtype) + return ragged_tensor.RaggedTensor.from_row_splits(values, row_splits, + validate=False) + + with ops.name_scope(name, "RaggedConstant"): + return _constant_value(ragged_factory, constant_op.constant, pylist, dtype, + ragged_rank, inner_shape) + + +@tf_export(v1=["ragged.constant_value"]) +@dispatch.add_dispatch_support +def constant_value( + pylist, + dtype=None, + ragged_rank=None, + inner_shape=None, + row_splits_dtype="int64", +) -> Union[ragged_tensor_value.RaggedTensorValue, np.ndarray]: + """Constructs a RaggedTensorValue from a nested Python list. + + Warning: This function returns a `RaggedTensorValue`, not a `RaggedTensor`. + If you wish to construct a constant `RaggedTensor`, use + [`ragged.constant(...)`](constant.md) instead. + + Example: + + >>> tf.compat.v1.ragged.constant_value([[1, 2], [3], [4, 5, 6]]) + tf.RaggedTensorValue(values=array([1, 2, 3, 4, 5, 6]), + row_splits=array([0, 2, 3, 6])) + + All scalar values in `pylist` must have the same nesting depth `K`, and the + returned `RaggedTensorValue` will have rank `K`. If `pylist` contains no + scalar values, then `K` is one greater than the maximum depth of empty lists + in `pylist`. All scalar values in `pylist` must be compatible with `dtype`. + + Args: + pylist: A nested `list`, `tuple` or `np.ndarray`. Any nested element that + is not a `list` or `tuple` must be a scalar value compatible with `dtype`. + dtype: `numpy.dtype`. The type of elements for the returned `RaggedTensor`. + If not specified, then a default is chosen based on the scalar values in + `pylist`. + ragged_rank: An integer specifying the ragged rank of the returned + `RaggedTensorValue`. Must be nonnegative and less than `K`. Defaults to + `max(0, K - 1)` if `inner_shape` is not specified. Defaults to `max(0, K + - 1 - len(inner_shape))` if `inner_shape` is specified. + inner_shape: A tuple of integers specifying the shape for individual inner + values in the returned `RaggedTensorValue`. Defaults to `()` if + `ragged_rank` is not specified. If `ragged_rank` is specified, then a + default is chosen based on the contents of `pylist`. + row_splits_dtype: data type for the constructed `RaggedTensorValue`'s + row_splits. One of `numpy.int32` or `numpy.int64`. + + Returns: + A `tf.RaggedTensorValue` or `numpy.array` with rank `K` and the specified + `ragged_rank`, containing the values from `pylist`. + + Raises: + ValueError: If the scalar values in `pylist` have inconsistent nesting + depth; or if ragged_rank or inner_shape are incompatible with `pylist`. + """ + if dtype is not None and isinstance(dtype, dtypes.DType): + dtype = dtype.as_numpy_dtype + row_splits_dtype = dtypes.as_dtype(row_splits_dtype).as_numpy_dtype + def _ragged_factory(values, row_splits): + row_splits = np.array(row_splits, dtype=row_splits_dtype) + return ragged_tensor_value.RaggedTensorValue(values, row_splits) + + def _inner_factory(pylist, dtype, shape, name=None): # pylint: disable=unused-argument + return np.reshape(np.array(pylist, dtype=dtype), shape) + + return _constant_value(_ragged_factory, _inner_factory, pylist, dtype, + ragged_rank, inner_shape) + + +def _constant_value(ragged_factory, inner_factory, pylist, dtype, ragged_rank, + inner_shape): + """Constructs a constant RaggedTensor or RaggedTensorValue. + + Args: + ragged_factory: A factory function with the signature: + `ragged_factory(values, row_splits)` + inner_factory: A factory function with the signature: `inner_factory(pylist, + dtype, shape, name)` + pylist: A nested `list`, `tuple` or `np.ndarray`. + dtype: Data type for returned value. + ragged_rank: Ragged rank for returned value. + inner_shape: Inner value shape for returned value. + + Returns: + A value returned by `ragged_factory` or `inner_factory`. + + Raises: + ValueError: If the scalar values in `pylist` have inconsistent nesting + depth; or if ragged_rank or inner_shape are incompatible with `pylist`. + """ + if ragged_tensor.is_ragged(pylist): + raise TypeError("pylist may not be a RaggedTensor or RaggedTensorValue.") + # np.ndim builds an array, so we short-circuit lists and tuples. + if not isinstance(pylist, (list, tuple)) and np.ndim(pylist) == 0: + # Scalar value + if ragged_rank is not None and ragged_rank != 0: + raise ValueError("Invalid pylist=%r: incompatible with ragged_rank=%d" % + (pylist, ragged_rank)) + if inner_shape is not None and inner_shape: + raise ValueError( + "Invalid pylist=%r: incompatible with dim(inner_shape)=%d" % + (pylist, len(inner_shape))) + return inner_factory(pylist, dtype, ()) + + if ragged_rank is not None and ragged_rank < 0: + raise ValueError( + "Invalid ragged_rank=%r: must be nonnegative" % ragged_rank) + + # Find the depth of scalar values in `pylist`. + scalar_depth, max_depth = _find_scalar_and_max_depth(pylist) + if scalar_depth is not None: + if max_depth > scalar_depth: + raise ValueError("Invalid pylist=%r: empty list nesting is greater " + "than scalar value nesting" % pylist) + if ragged_rank is not None and max_depth < ragged_rank: + raise ValueError(f"Invalid pylist={pylist}, max depth smaller than " + f"ragged_rank={ragged_rank}") + + # If both inner_shape and ragged_rank were specified, then check that + # they are compatible with pylist. + if inner_shape is not None and ragged_rank is not None: + expected_depth = ragged_rank + len(inner_shape) + 1 + if ((scalar_depth is not None and expected_depth != scalar_depth) or + (scalar_depth is None and expected_depth < max_depth)): + raise ValueError( + "Invalid pylist=%r: incompatible with ragged_rank=%d " + "and dim(inner_shape)=%d" % (pylist, ragged_rank, len(inner_shape))) + + # Check if the result is a `Tensor`. + if (ragged_rank == 0 or + (ragged_rank is None and + ((max_depth < 2) or + (inner_shape is not None and max_depth - len(inner_shape) < 2)))): + return inner_factory(pylist, dtype, inner_shape) + + # Compute default value for inner_shape. + if inner_shape is None: + if ragged_rank is None: + inner_shape = () + else: + inner_shape = _default_inner_shape_for_pylist(pylist, ragged_rank) + + # Compute default value for ragged_rank. + if ragged_rank is None: + if scalar_depth is None: + ragged_rank = max(1, max_depth - 1) + else: + ragged_rank = max(1, scalar_depth - 1 - len(inner_shape)) + + # Build the splits for each ragged rank, and concatenate the inner values + # into a single list. + nested_splits = [] + values = pylist + for dim in range(ragged_rank): + nested_splits.append([0]) + concatenated_values = [] + for row in values: + nested_splits[dim].append(nested_splits[dim][-1] + len(row)) + concatenated_values.extend(row) + values = concatenated_values + + values = inner_factory( + values, dtype=dtype, shape=(len(values),) + inner_shape, name="values") + for row_splits in reversed(nested_splits): + values = ragged_factory(values, row_splits) + return values + + +def _find_scalar_and_max_depth(pylist): + """Finds nesting depth of scalar values in pylist. + + Args: + pylist: A nested python `list` or `tuple`. + + Returns: + A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting + depth of scalar values in `pylist`, or `None` if `pylist` contains no + scalars. `max_depth` is the maximum depth of `pylist` (including + empty lists). + + Raises: + ValueError: If pylist has inconsistent nesting depths for scalars. + """ + # Check if pylist is not scalar. np.ndim builds an array, so we + # short-circuit lists and tuples. + if isinstance(pylist, (list, tuple)) or np.ndim(pylist) != 0: + scalar_depth = None + max_depth = 1 + for child in pylist: + child_scalar_depth, child_max_depth = _find_scalar_and_max_depth(child) + if child_scalar_depth is not None: + if scalar_depth is not None and scalar_depth != child_scalar_depth + 1: + raise ValueError("all scalar values must have the same nesting depth") + scalar_depth = child_scalar_depth + 1 + max_depth = max(max_depth, child_max_depth + 1) + return (scalar_depth, max_depth) + return (0, 0) + + +def _default_inner_shape_for_pylist(pylist, ragged_rank): + """Computes a default inner shape for the given python list.""" + + def get_inner_shape(item): + """Returns the inner shape for a python list `item`.""" + if not isinstance(item, (list, tuple)) and np.ndim(item) == 0: + return () + # Note that we need this check here in case `item` is not a Python list but + # fakes as being one (pylist). For a scenario of this, see test added in + # https://github.com/tensorflow/tensorflow/pull/48945 + elif len(item) > 0: # pylint: disable=g-explicit-length-test + return (len(item),) + get_inner_shape(item[0]) + return (0,) + + def check_inner_shape(item, shape): + """Checks that `item` has a consistent shape matching `shape`.""" + is_nested = isinstance(item, (list, tuple)) or np.ndim(item) != 0 + if is_nested != bool(shape): + raise ValueError("inner values have inconsistent shape") + if is_nested: + if shape[0] != len(item): + raise ValueError("inner values have inconsistent shape") + for child in item: + check_inner_shape(child, shape[1:]) + + # Collapse the ragged layers to get the list of inner values. + flat_values = pylist + for dim in range(ragged_rank): + if not all( + isinstance(v, (list, tuple)) or np.ndim(v) != 0 for v in flat_values): + raise ValueError("pylist has scalar values depth %d, but ragged_rank=%d " + "requires scalar value depth greater than %d" % + (dim + 1, ragged_rank, ragged_rank)) + flat_values = sum((list(v) for v in flat_values), []) + + # Compute the inner shape looking only at the leftmost elements; and then + # use check_inner_shape to verify that other elements have the same shape. + inner_shape = get_inner_shape(flat_values) + check_inner_shape(flat_values, inner_shape) + return inner_shape[1:] + + +@tf_export(v1=["ragged.placeholder"]) +@dispatch.add_dispatch_support +def placeholder(dtype, ragged_rank, value_shape=None, name=None): + """Creates a placeholder for a `tf.RaggedTensor` that will always be fed. + + **Important**: This ragged tensor will produce an error if evaluated. + Its value must be fed using the `feed_dict` optional argument to + `Session.run()`, `Tensor.eval()`, or `Operation.run()`. + + + Args: + dtype: The data type for the `RaggedTensor`. + ragged_rank: The ragged rank for the `RaggedTensor` + value_shape: The shape for individual flat values in the `RaggedTensor`. + name: A name for the operation (optional). + + Returns: + A `RaggedTensor` that may be used as a handle for feeding a value, but + not evaluated directly. + + Raises: + RuntimeError: if eager execution is enabled + + @compatibility(TF2) + This API is not compatible with eager execution and `tf.function`. To migrate + to TF2, rewrite the code to be compatible with eager execution. Check the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. In TF2, you can just pass tensors directly + into ops and layers. If you want to explicitly set up your inputs, also see + [Keras functional API](https://www.tensorflow.org/guide/keras/functional) on + how to use `tf.keras.Input` to replace `tf.compat.v1.ragged.placeholder`. + `tf.function` arguments also do the job of `tf.compat.v1.ragged.placeholder`. + For more details please read [Better + performance with tf.function](https://www.tensorflow.org/guide/function). + @end_compatibility + """ + if ragged_rank == 0: + return array_ops.placeholder(dtype, value_shape, name) + + with ops.name_scope(name, "RaggedPlaceholder", []): + flat_shape = tensor_shape.TensorShape([None]).concatenate(value_shape) + result = array_ops.placeholder(dtype, flat_shape, "flat_values") + for i in reversed(range(ragged_rank)): + row_splits = array_ops.placeholder(dtypes.int64, [None], + "row_splits_%d" % i) + result = ragged_tensor.RaggedTensor.from_row_splits(result, row_splits, + validate=False) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_functional_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_functional_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d011ce570397b32f7330ff68e96d2b0a7ef5a22d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_functional_ops.py @@ -0,0 +1,200 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Support for ragged tensors.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops.ragged import ragged_config +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("ragged.map_flat_values") +@dispatch.add_dispatch_support +def map_flat_values(op, *args, **kwargs): + """Applies `op` to the `flat_values` of one or more RaggedTensors. + + Replaces any `RaggedTensor` in `args` or `kwargs` with its `flat_values` + tensor (which collapses all ragged dimensions), and then calls `op`. Returns + a `RaggedTensor` that is constructed from the input `RaggedTensor`s' + `nested_row_splits` and the value returned by the `op`. + + If the input arguments contain multiple `RaggedTensor`s, then they must have + identical `nested_row_splits`. + + This operation is generally used to apply elementwise operations to each value + in a `RaggedTensor`. + + Warning: `tf.ragged.map_flat_values` does *not* apply `op` to each row of a + ragged tensor. This difference is important for non-elementwise operations, + such as `tf.reduce_sum`. If you wish to apply a non-elementwise operation to + each row of a ragged tensor, use `tf.map_fn` instead. (You may need to + specify an `output_signature` when using `tf.map_fn` with ragged tensors.) + + Examples: + + >>> rt = tf.ragged.constant([[1, 2, 3], [], [4, 5], [6]]) + >>> tf.ragged.map_flat_values(tf.ones_like, rt) + + >>> tf.ragged.map_flat_values(tf.multiply, rt, rt) + + >>> tf.ragged.map_flat_values(tf.add, rt, 5) + + + Example with a non-elementwise operation (note that `map_flat_values` and + `map_fn` return different results): + + >>> rt = tf.ragged.constant([[1.0, 3.0], [], [3.0, 6.0, 3.0]]) + >>> def normalized(x): + ... return x / tf.reduce_sum(x) + >>> tf.ragged.map_flat_values(normalized, rt) + + >>> tf.map_fn(normalized, rt) + + + Args: + op: The operation that should be applied to the RaggedTensor `flat_values`. + `op` is typically an element-wise operation (such as math_ops.add), but + any operation that preserves the size of the outermost dimension can be + used. I.e., `shape[0]` of the value returned by `op` must match + `shape[0]` of the `RaggedTensor`s' `flat_values` tensors. + *args: Arguments for `op`. + **kwargs: Keyword arguments for `op`. + + Returns: + A `RaggedTensor` whose `ragged_rank` matches the `ragged_rank` of all + input `RaggedTensor`s. + Raises: + ValueError: If args contains no `RaggedTensors`, or if the `nested_splits` + of the input `RaggedTensor`s are not identical. + """ + # Replace RaggedTensors with their values; and collect the partitions tensors + # from each RaggedTensor. + partition_lists = [] + flat_values_nrows = [] + inner_args = _replace_ragged_with_flat_values(args, partition_lists, + flat_values_nrows) + inner_kwargs = _replace_ragged_with_flat_values(kwargs, partition_lists, + flat_values_nrows) + if not partition_lists: + return op(*args, **kwargs) + + # If we can statically determine that the inputs are incompatible, then raise + # an error. (We can't guarantee full compatibility statically, so we need to + # perform some runtime checks too; but this allows us to fail sooner in some + # cases.) + if flat_values_nrows: + flat_values_nrows = set(flat_values_nrows) + if len(flat_values_nrows) != 1: + raise ValueError("Input RaggedTensors' flat_values must all have the " + "same outer-dimension size. Got sizes: %s" % + flat_values_nrows) + flat_values_nrows = flat_values_nrows.pop() # Get the single element + else: + flat_values_nrows = None + + partition_dtypes = set(p[0].dtype for p in partition_lists) + if len(partition_dtypes) > 1: + if not ragged_config.auto_cast_partition_dtype(): + raise ValueError("Input RaggedTensors have mismatched row partition " + "dtypes; use RaggedTensor.with_row_splits_dtype() to " + "convert them to compatible dtypes.") + + partition_lists = [ + [p.with_dtype(dtypes.int64) + for p in partition_list] # pylint: disable=g-complex-comprehension + for partition_list in partition_lists + ] + + # Delegate to `op` + op_output = op(*inner_args, **inner_kwargs) + # Check that the result has the expected shape (if known). + if flat_values_nrows is not None: + if not op_output.shape[:1].is_compatible_with([flat_values_nrows]): + raise ValueError( + "tf.ragged.map_flat_values requires that the output of `op` have " + "the same outer-dimension size as flat_values of any ragged " + "inputs. (output shape: %s; expected outer dimension size: %s)" % + (op_output.shape, flat_values_nrows)) + # Compose the result from the transformed values and the partitions. + return ragged_tensor.RaggedTensor._from_nested_row_partitions( # pylint: disable=protected-access + op_output, + _merge_partition_lists(partition_lists), + validate=False) + + +def _replace_ragged_with_flat_values(value, partition_lists, flat_values_nrows): + """Replace RaggedTensors with their flat_values, and record their partitions. + + Returns a copy of `value`, with any nested `RaggedTensor`s replaced by their + `flat_values` tensor. Looks inside lists, tuples, and dicts. + + Appends each `RaggedTensor`'s `RowPartition`s to `partition_lists`. + + Args: + value: The value that should be transformed by replacing `RaggedTensors`. + partition_lists: An output parameter used to record the row partitions + for any `RaggedTensors` that were replaced. + flat_values_nrows: An output parameter used to record the outer dimension + size for each replacement `flat_values` (when known). Contains a list of + int. + + Returns: + A copy of `value` with nested `RaggedTensors` replaced by their `values`. + """ + # Base case + if ragged_tensor.is_ragged(value): + value = ragged_tensor.convert_to_tensor_or_ragged_tensor(value) + partition_lists.append(value._nested_row_partitions) # pylint: disable=protected-access + nrows = tensor_shape.dimension_at_index(value.flat_values.shape, 0).value + if nrows is not None: + flat_values_nrows.append(nrows) + return value.flat_values + + # Recursion cases + def recurse(v): + return _replace_ragged_with_flat_values(v, partition_lists, + flat_values_nrows) + + if isinstance(value, list): + return [recurse(v) for v in value] + elif isinstance(value, tuple): + return tuple(recurse(v) for v in value) + elif isinstance(value, dict): + return dict((k, recurse(v)) for (k, v) in value.items()) + else: + return value + + +def _merge_partition_lists(partition_lists): + """Merges the given list of lists of RowPartitions. + + Args: + partition_lists: A list of lists of RowPartition. + + Returns: + A list of RowPartitions, where `result[i]` is formed by merging + `partition_lists[j][i]` for all `j`, using + `RowPartition._merge_precomputed_encodings`. + """ + dst = list(partition_lists[0]) + for src in partition_lists[1:]: + if len(src) != len(dst): + raise ValueError("All ragged inputs must have the same ragged_rank.") + for i in range(len(dst)): + # pylint: disable=protected-access + dst[i] = dst[i]._merge_precomputed_encodings(src[i]) + return dst diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_gather_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_gather_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..055b0a3d84c906f67fbe0f2913a479e830ce2705 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_gather_ops.py @@ -0,0 +1,520 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gather operations for RaggedTensors.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_ragged_array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +#=============================================================================== +# ragged_gather +#=============================================================================== +@dispatch.dispatch_for_api(array_ops.gather_v2) +def gather(params: ragged_tensor.RaggedOrDense, + indices: ragged_tensor.RaggedOrDense, + validate_indices=None, + axis=None, + batch_dims=0, + name=None): + """Gathers ragged slices from `params` axis `0` according to `indices`. + + See `tf.gather` for full documentation. (This version has the same API + as `tf.gather`, but supports ragged `params` and `indices`.) + + Examples: + + >>> params = tf.constant(['a', 'b', 'c', 'd', 'e']) + >>> indices = tf.constant([3, 1, 2, 1, 0]) + >>> ragged_params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']]) + >>> ragged_indices = tf.ragged.constant([[3, 1, 2], [1], [], [0]]) + + >>> tf.gather(params, ragged_indices) + + + >>> tf.gather(ragged_params, indices) + + + >>> tf.gather(ragged_params, ragged_indices) + + + Args: + params: The potentially ragged tensor from which to gather values. Must be + at least rank 1. + indices: The potentially ragged tensor indicating which values to gather. + Must have dtype `int32` or `int64`. Values must be in the range `[0, + params.shape[0]]`. + validate_indices: Ignored. + axis: The axis in `params` to gather `indices` from. + batch_dims: The number of batch dimensions. + name: A name for the operation (optional). + + Returns: + A `RaggedTensor`, where `output.dtype=params.dtype` and + `output.shape=indices.shape + params.shape[1:]` and + `output.ragged_rank=indices.shape.ndims + params.ragged_rank`. + + Raises: + ValueError: If indices.shape.ndims is not known statically. + """ + del validate_indices + + with ops.name_scope(name, 'RaggedGather', [params, indices]): + params = ragged_tensor.convert_to_tensor_or_ragged_tensor( + params, name='params') + indices = ragged_tensor.convert_to_tensor_or_ragged_tensor( + indices, name='indices') + params, indices = ragged_tensor.match_row_splits_dtypes(params, indices) + + if batch_dims != indices.shape.rank: + batch_dims = array_ops.get_positive_axis( + batch_dims, + indices.shape.rank, + axis_name='batch_dims', + ndims_name='rank(indices)') + if params.shape.rank is not None and batch_dims >= params.shape.rank: + raise ValueError('batch_dims must be less than rank(params)') + if axis is None: + axis = batch_dims + axis = array_ops.get_positive_axis( + axis, params.shape.rank, ndims_name='rank(params)') + if axis < batch_dims: + raise ValueError('axis must be greater than or equal to batch_dims') + if indices.shape.rank is not None: + if not 0 <= batch_dims <= indices.shape.rank: + raise ValueError( + 'batch_dims=%s must be between 0 and rank(indices)=%s' % + (batch_dims, indices.shape.rank)) + + return _gather(params, indices, axis, batch_dims) + + +def _gather(params, indices, axis, batch_dims): + """Helper that implements the body for ragged gather(). + + Assumes that `params` and `indices` have been converted to tensors or + ragged tensors, and that `axis` and `batch_dims` have been normalized to + be positive. (So these conversions & normalizations can be skipped in + recursive calls to _gather). + + Args: + params: The tensor from which to gather values. + indices: The indices of values to gather. + axis: The axis in `params` to gather `indices` from. + batch_dims: The number of batch dimensions. + + Returns: + A potentially ragged tensor. + """ + params_is_ragged = ragged_tensor.is_ragged(params) + indices_is_ragged = ragged_tensor.is_ragged(indices) + + if not (params_is_ragged or indices_is_ragged): + return array_ops.gather(params, indices, axis=axis, batch_dims=batch_dims) + + if batch_dims > 0: + return _batch_gather(params, indices, axis, batch_dims) + + if axis > 0: + return _axis_gather(params, indices, axis) + + if indices_is_ragged: + return indices.with_values(_gather(params, indices.values, 0, 0)) + + if indices.shape.ndims is None: + raise ValueError('rank(indices) must be known statically') + + out_ragged_rank = indices.shape.ndims + len(params.nested_row_splits) - 1 + result = gen_ragged_array_ops.ragged_gather( + indices=indices, + params_dense_values=params.flat_values, + params_nested_splits=params.nested_row_splits, + OUTPUT_RAGGED_RANK=out_ragged_rank) + + result = ragged_tensor.RaggedTensor.from_nested_row_splits( + result.output_dense_values, result.output_nested_splits, validate=False) + + # Inject uniform_row_lengths into the result RaggedTensors for dimensions + # corresponding to dense outer dimensions of `indices`. + # TODO(edloper): Change this to construct the result using RowPartition + # objects instead, so we don't need to modify private variables. + if indices.shape.ndims > 1: + target = result + indices_shape = array_ops.shape(indices, out_type=params.row_splits.dtype) + shape_cumprod = math_ops.cumprod(indices_shape) + for dim in range(indices.shape.ndims - 1): + # pylint: disable=protected-access + target._cached_nrows = shape_cumprod[dim] + target._uniform_row_length = indices_shape[dim + 1] + target = target.values + + return result + + +def _batch_gather(params, indices, axis, batch_dims): + """Helper that implements the body for ragged gather() when batch_dims>0. + + Args: + params: The tensor from which to gather values. + indices: The indices of values to gather. + axis: The axis in `params` to gather `indices` from. + batch_dims: The number of batch dimensions. + + Returns: + A potentially ragged tensor. + """ + # Perform static checks that `params` and `indices` have compatible batch + # dimensions. Note: we do not perform *runtime* checks that `params` and + # `indices` actually have the same row-splits (because we wish to avoid the + # runtime cost of those checks). If `params` and `indices` are + # incompatible, the resulting `RaggedTensor` may be nonsensical. + if not params.shape[:batch_dims].is_compatible_with( + indices.shape[:batch_dims]): + raise ValueError('batch shape from indices %s does not match params ' + 'shape %s' % (indices.shape[:batch_dims], params.shape)) + + if batch_dims > 1: + # Convert params & indices to ragged tensors. + if not isinstance(params, ragged_tensor.RaggedTensor): + if indices.uniform_row_length is None: + raise ValueError( + 'batch shape from indices does not match params shape: ragged ' + 'indices dimension corresponds to uniform params dimension') + params = ragged_tensor.RaggedTensor.from_tensor( + params, ragged_rank=1, row_splits_dtype=indices.row_splits.dtype) + if not isinstance(indices, ragged_tensor.RaggedTensor): + if params.uniform_row_length is None: + raise ValueError( + 'batch shape from indices does not match params shape: ragged ' + 'params dimension corresponds to uniform indices dimension') + indices = ragged_tensor.RaggedTensor.from_tensor( + indices, ragged_rank=1, row_splits_dtype=params.row_splits.dtype) + # Flatten the two outer batch dimensions into a single batch dimension, + # and recurse. + return params.with_values( + _gather(params.values, indices.values, axis - 1, batch_dims - 1)) + + if axis > 1: + # Convert an axis dimension into a batch dimension, by adding a dimension + # to `indices`, and tiling it to match `params`. E.g., if `params` + # had shape `[B, P1, P2]`, and `indices` had shape `[B, I1, I2]`, then we + # tile `indices` to have shape `[B, P1, I1, I2]`. That way, we can treat + # the `P1` dimension as a batch dimension. + if not isinstance(indices, ragged_tensor.RaggedTensor): + adjusted_indices = params.with_values( + array_ops.repeat(indices, params.row_lengths(), 0)) + else: + if not isinstance(params, ragged_tensor.RaggedTensor): + params = ragged_tensor.RaggedTensor.from_tensor( + params, ragged_rank=1, row_splits_dtype=indices.row_splits.dtype) + adjusted_indices = _gather( + indices, + params.with_values( + array_ops.repeat( + math_ops.range(params.nrows()), params.row_lengths())), 0, 0) + return _batch_gather(params, adjusted_indices, axis, batch_dims + 1) + + if indices.shape.rank is None: + raise ValueError('rank(indices) must be known statically') + + assert batch_dims == 1 + # If params.shape=[B, P1...PN] and indices.shape=[B, I1...IM], then: + # + # output[b, i1...im, p2...pn] = + # params[b, indices[b, i1...im], p2...pn] + # + # We construct `output` by flattening `params`, adjusting the `indices` to + # point into that flattened list, and recursively calling `gather`. + flat_params = _flatten_dims_0_and_1(params) + adjustments = _row_starts(params, indices.dtype) # offset for each batch + # increase adjustments's rank so it broadcasts w/ the outer dim of indices + adjustments = _increase_rank_to(adjustments, indices.shape.ndims) + adjusted_indices = indices + adjustments + return _gather(flat_params, adjusted_indices, axis - 1, 0) + + +def _axis_gather(params, indices, axis): + """Helper that implements ragged gather when axis>0 and batch_dims==0. + + Args: + params: The tensor from which to gather values. + indices: The indices of values to gather. + axis: The axis in `params` to gather `indices` from. + + Returns: + A potentially ragged tensor. + """ + if axis > 1: + if not isinstance(params, ragged_tensor.RaggedTensor): + params = ragged_tensor.RaggedTensor.from_tensor( + params, ragged_rank=1, row_splits_dtype=indices.row_splits.dtype) + # Recurse, using the flattened params (but do not flatten indices). + return params.with_values(_gather(params.values, indices, axis - 1, 0)) + + if indices.shape.rank is None: + raise ValueError('rank(indices) must be known statically') + + # Note: there is no checking of indices. If there is some index + # out of bounds, the results may be nonsensical. + + assert axis == 1 + # If params.shape=[P1...PN] and indices.shape=[I1...IM], then: + # + # output[p1, i1...im, p3...pn] = + # params[p1, indices[i1...im], p3...pn] + # + # We construct `output` by flattening `params`, adjusting the `indices` to + # have one additional dimension, and to point into that flattened list, and + # recursively calling `gather`. + flat_params = _flatten_dims_0_and_1(params) + adjustments = _row_starts(params, indices.dtype) # offset for each batch + adjustments = _increase_rank_to(adjustments, indices.shape.ndims + 1) + adjusted_indices = indices + adjustments + return _gather(flat_params, adjusted_indices, axis - 1, 0) + + +def _flatten_dims_0_and_1(t): + """Returns a copy of `t` with the outer two dimensions merged.""" + if isinstance(t, ragged_tensor.RaggedTensor): + return t.values + else: + t_shape = array_ops.shape(t) + return array_ops.reshape(t, array_ops.concat([[-1], t_shape[2:]], axis=0)) + + +def _row_starts(t, dtype): + """Returns the start indices for the rows in `t`.""" + if isinstance(t, ragged_tensor.RaggedTensor): + return math_ops.cast(t.row_starts(), dtype) + else: + t_shape = array_ops.shape(t, out_type=dtype) + return math_ops.range(t_shape[0]) * t_shape[1] + + +def _increase_rank_to(t, rank): + """Adds *trailing* size-1 dimensions to `t` until it has the given rank.""" + if isinstance(t, ragged_tensor.RaggedTensor): + return t.with_values(_increase_rank_to(t, rank - 1)) + else: + old_dims = array_ops.shape(t) + new_dims = array_ops.ones([rank - array_ops.rank(t)], old_dims.dtype) + new_shape = array_ops.concat([old_dims, new_dims], axis=0) + return array_ops.reshape(t, new_shape) + + +@dispatch.dispatch_for_api(array_ops.gather) +def _ragged_gather_v1(params: ragged_tensor.RaggedOrDense, + indices: ragged_tensor.RaggedOrDense, + validate_indices=None, + name=None, + axis=0, + batch_dims=0): + return gather(params, indices, validate_indices, axis, batch_dims, name) + + +#=============================================================================== +# ragged.gather_nd +#=============================================================================== +@dispatch.dispatch_for_api(array_ops.gather_nd_v2) +def gather_nd(params: ragged_tensor.RaggedOrDense, + indices: ragged_tensor.RaggedOrDense, + batch_dims=0, + name=None): + """Gather slices from `params` using `n`-dimensional indices. + + This operation is similar to `gather`, but it uses the innermost dimension + of `indices` to define a slice into `params`. In particular, if: + + * `indices` has shape `[A1...AN, I]` + * `params` has shape `[B1...BM]` + + Then: + + * `result` has shape `[A1...AN, B_{I+1}...BM]`. + * `result[a1...aN] = params[indices[a1...aN, :]]` + + Args: + params: A potentially ragged tensor with shape `[A1...AN, I]`. + indices: A potentially ragged tensor with shape `[B1...BM]`. + batch_dims: Must be zero. + name: A name for the operation (optional). + + Returns: + A potentially ragged tensor with shape `[A1...AN, B_{I+1}...BM]`. + + #### Examples: + + >>> params = tf.ragged.constant( + ... [ [ ['000', '001'], ['010' ] ], + ... [ ['100' ], ['110', '111', '112'], ['120'] ], + ... [ [ ], ['210' ] ] ]) + + >>> # Gather 2D slices from a 3D tensor + >>> tf.gather_nd(params, [[2], [0]]) + + + >>> # Gather 1D slices from a 3D tensor + >>> tf.gather_nd(params, [[2, 1], [0, 0]]) + + + >>> # Gather scalars from a 3D tensor + >>> tf.gather_nd(params, [[0, 0, 1], [1, 1, 2]]).numpy() + array([b'001', b'112'], dtype=object) + """ + if not isinstance(batch_dims, int) or batch_dims != 0: + raise ValueError('batch_dims != 0 is not supported for ragged gather yet.') + if not (ragged_tensor.is_ragged(params) or ragged_tensor.is_ragged(indices)): + return array_ops.gather_nd(params, indices, name) + + with ops.name_scope(name, 'RaggedGatherNd', [params, indices]): + + params = ragged_tensor.convert_to_tensor_or_ragged_tensor( + params, name='params') + indices = ragged_tensor.convert_to_tensor_or_ragged_tensor( + indices, name='indices') + params, indices = ragged_tensor.match_row_splits_dtypes(params, indices) + indices_shape = indices.shape + indices_ndims = indices_shape.ndims + if indices_ndims is None: + raise ValueError('indices.rank be statically known.') + if indices_ndims == 0: + raise ValueError('indices.rank must be at least 1.') + if (ragged_tensor.is_ragged(indices) and + indices_ndims == indices.ragged_rank + 1): + raise ValueError('The innermost dimension of indices may not be ragged') + + # `index_size` is the "n" in "gather_nd" -- i.e., the number of dimensions + # that each index slices into. + index_size = tensor_shape.dimension_value(indices_shape[-1]) + if index_size is None: + raise ValueError('indices.shape[-1] must be statically known.') + + # If `indices` has more than 2 dimensions, then recurse. If `indices` is + # dense, then we convert it to ragged before recursing, and then convert + # the result back to `dense` if appropriate. + if indices_ndims > 2: + indices_is_dense = not ragged_tensor.is_ragged(indices) + if indices_is_dense: + indices = ragged_tensor.RaggedTensor.from_tensor( + indices, ragged_rank=indices_ndims - 2, + row_splits_dtype=params.row_splits.dtype) + result = indices.with_flat_values(gather_nd(params, indices.flat_values)) + if (indices_is_dense and ragged_tensor.is_ragged(result) and + result.ragged_rank == indices_ndims - 2): + result = ragged_tensor.RaggedTensor.to_tensor(result) + return result + + # indices_ndims <= 2, and the innermost dimension of indices may not be + # ragged, so `indices` must not be ragged. + assert not ragged_tensor.is_ragged(indices) + assert ragged_tensor.is_ragged(params) + + # Handle corner case: An empty index tuple selects the entire `params` + # value. So if `index_size` is zero, then tile `params`. + if index_size == 0: + params_ndims = params.ragged_rank + array_ops.rank(params.flat_values) + for dim in range(indices_ndims - 1): + params = ragged_array_ops.expand_dims(params, axis=0) + multiples = array_ops.concat([ + array_ops.shape(indices)[:-1], + array_ops.ones([params_ndims], dtypes.int32) + ], + axis=0) + return ragged_array_ops.tile(params, multiples) + + # When index_size=1, we can just flatten the index tuples and use gather. + elif index_size == 1: + flattened_index_tuples = array_ops.reshape(indices, [-1]) + return gather(params, flattened_index_tuples) + + # Otherwise, params is a RaggedTensor, and indices is a 1D or 2D Tensor. + # Flatten both the index tuples and the params, such that the flattened + # index tuples point to the correct values in the flattened params; and + # then use ragged.gather on the flattened index tuples & params. + else: + indices = math_ops.cast(indices, params.row_splits.dtype) + + # Flatten the outermost 2 dimensions of the index tuples & params. + flattened_index_tuples = array_ops.gather(params.row_splits, + indices[..., 0]) + flattened_index_tuples += indices[..., 1] + flattened_params = params.values + + # Flatten any remaining dimensions. + for dim in range(2, index_size): + if not ragged_tensor.is_ragged(flattened_params): + flattened_index_tuples = array_ops.expand_dims( + flattened_index_tuples, axis=1) + flattened_index_tuples = array_ops.concat( + [flattened_index_tuples, indices[..., dim:]], axis=1) + return array_ops.gather_nd(flattened_params, flattened_index_tuples) + + flattened_index_tuples = array_ops.gather( + flattened_params.row_starts(), flattened_index_tuples) + flattened_index_tuples += indices[..., dim] + flattened_params = flattened_params.values + + # Gather using the flattened index tuples and params. + return gather(flattened_params, flattened_index_tuples) + + +@dispatch.dispatch_for_api(array_ops.gather_nd) +def _ragged_gather_nd_v1(params: ragged_tensor.RaggedOrDense, + indices: ragged_tensor.RaggedOrDense, + name=None, + batch_dims=0): + return gather_nd(params, indices, batch_dims, name) + + +#=============================================================================== +# Gradient for the RaggedGather kernel +#=============================================================================== +@ops.RegisterGradient('RaggedGather') +def _ragged_gather_grad(op, *grads): + """Gradient for RaggedGather op.""" + param_nested_splits = op.inputs[:-2] + param_inner_values = op.inputs[-2] + indices = op.inputs[-1] + grad_inner_values = grads[-1] + + # For each row in `params`, find the range of values in `params.inner_values` + # that is covered by that row. In particular, the values in row `i` are + # `param_inner_values[combined_splits[i]:combined_splits[i+1]`. + combined_splits = param_nested_splits[0] + for row_splits in param_nested_splits[1:]: + combined_splits = array_ops.gather(row_splits, combined_splits) + + # The outer dimensions of `indices` correspond 1:1 with the outer dimensions + # of `ragged_grad` that are encoded by `grad_nested_splits`. Thus, the + # flattened `indices` correspond 1:1 with `grad_inner_values`. + flat_indices = array_ops.reshape(indices, [-1]) + + # Build an IndexedSlices where the values are taken from `flat_grad`. + grad_indices = ragged_math_ops.range( + array_ops.gather(combined_splits, flat_indices), + array_ops.gather(combined_splits[1:], flat_indices)).values + + param_inner_values_grad = indexed_slices.IndexedSlices( + values=grad_inner_values, indices=grad_indices, + dense_shape=array_ops.shape(param_inner_values)) + return [None for _ in param_nested_splits] + [param_inner_values_grad, None] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_getitem.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_getitem.py new file mode 100644 index 0000000000000000000000000000000000000000..b7ceb9240be243fcdbe471c431337a712ea34a0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_getitem.py @@ -0,0 +1,477 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Python-style indexing and slicing for RaggedTensors.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_gather_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__operators__.ragged_getitem", v1=[]) +@dispatch.add_dispatch_support +def ragged_tensor_getitem(rt_input, key): + """Returns the specified piece of this RaggedTensor. + + Supports multidimensional indexing and slicing, with one restriction: + indexing into a ragged inner dimension is not allowed. This case is + problematic because the indicated value may exist in some rows but not + others. In such cases, it's not obvious whether we should (1) report an + IndexError; (2) use a default value; or (3) skip that value and return a + tensor with fewer rows than we started with. Following the guiding + principles of Python ("In the face of ambiguity, refuse the temptation to + guess"), we simply disallow this operation. + + Args: + rt_input: The RaggedTensor to slice. + key: Indicates which piece of the RaggedTensor to return, using standard + Python semantics (e.g., negative values index from the end). `key` + may have any of the following types: + + * `int` constant + * Scalar integer `Tensor` + * `slice` containing integer constants and/or scalar integer + `Tensor`s + * `Ellipsis` + * `tf.newaxis` + * `tuple` containing any of the above (for multidimensional indexing) + + Returns: + A `Tensor` or `RaggedTensor` object. Values that include at least one + ragged dimension are returned as `RaggedTensor`. Values that include no + ragged dimensions are returned as `Tensor`. See above for examples of + expressions that return `Tensor`s vs `RaggedTensor`s. + + Raises: + ValueError: If `key` is out of bounds. + ValueError: If `key` is not supported. + TypeError: If the indices in `key` have an unsupported type. + + Examples: + + >>> # A 2-D ragged tensor with 1 ragged dimension. + >>> rt = tf.ragged.constant([['a', 'b', 'c'], ['d', 'e'], ['f'], ['g']]) + >>> rt[0].numpy() # First row (1-D `Tensor`) + array([b'a', b'b', b'c'], dtype=object) + >>> rt[:3].to_list() # First three rows (2-D RaggedTensor) + [[b'a', b'b', b'c'], [b'd', b'e'], [b'f']] + >>> rt[3, 0].numpy() # 1st element of 4th row (scalar) + b'g' + + >>> # A 3-D ragged tensor with 2 ragged dimensions. + >>> rt = tf.ragged.constant([[[1, 2, 3], [4]], + ... [[5], [], [6]], + ... [[7]], + ... [[8, 9], [10]]]) + >>> rt[1].to_list() # Second row (2-D RaggedTensor) + [[5], [], [6]] + >>> rt[3, 0].numpy() # First element of fourth row (1-D Tensor) + array([8, 9], dtype=int32) + >>> rt[:, 1:3].to_list() # Items 1-3 of each row (3-D RaggedTensor) + [[[4]], [[], [6]], [], [[10]]] + >>> rt[:, -1:].to_list() # Last item of each row (3-D RaggedTensor) + [[[4]], [[6]], [[7]], [[10]]] + """ + if not isinstance(rt_input, ragged_tensor.RaggedTensor): + raise TypeError("Ragged __getitem__ expects a ragged_tensor.") + scope_tensors = [rt_input] + list(_tensors_in_key_list(key)) + if isinstance(key, (list, tuple)): + key = list(key) + else: + key = [key] + with ops.name_scope(None, "RaggedGetItem", scope_tensors): + return _ragged_getitem(rt_input, key) + + +def _ragged_getitem(rt_input, key_list): + """Helper for indexing and slicing ragged tensors with __getitem__(). + + Extracts the specified piece of the `rt_input`. See + `RaggedTensor.__getitem__` for examples and restrictions. + + Args: + rt_input: The `RaggedTensor` from which a piece should be returned. + key_list: The list of keys specifying which piece to return. Each key + corresponds with a separate dimension. + + Returns: + The indicated piece of rt_input. + + Raises: + ValueError: If `key_list` is not supported. + TypeError: If any keys in `key_list` have an unsupported type. + """ + if not key_list: + return rt_input + row_key = key_list[0] + inner_keys = key_list[1:] + + if row_key is Ellipsis: + expanded_key_list = _expand_ellipsis(key_list, rt_input.shape.ndims) + return _ragged_getitem(rt_input, expanded_key_list) + + # Adding a new axis: Get rt_input[inner_keys], and wrap it in a RaggedTensor + # that puts all values in a single row. + if row_key is array_ops.newaxis: + inner_rt = _ragged_getitem(rt_input, inner_keys) + nsplits = tensor_shape.dimension_at_index(inner_rt.row_splits.shape, 0) + if nsplits.value is not None: + nsplits = nsplits.value + else: + nsplits = array_ops.shape(inner_rt.row_splits, + out_type=inner_rt.row_splits.dtype)[0] + return ragged_tensor.RaggedTensor.from_uniform_row_length( + inner_rt, nsplits - 1, nrows=1, validate=False) + + # Slicing a range of rows: first slice the outer dimension, and then + # call `_ragged_getitem_inner_dimensions` to handle the inner keys. + if isinstance(row_key, slice): + sliced_rt_input = _slice_ragged_row_dimension(rt_input, row_key) + if rt_input.uniform_row_length is not None: + # If the inner dimension has uniform_row_length, then preserve it (by + # re-wrapping the values in a new RaggedTensor). Note that the row + # length won't have changed, since we're slicing a range of rows (and not + # slicing the rows themselves). + sliced_rt_input = ragged_tensor.RaggedTensor.from_uniform_row_length( + sliced_rt_input.values, rt_input.uniform_row_length, + nrows=sliced_rt_input.nrows()) + return _ragged_getitem_inner_dimensions(sliced_rt_input, inner_keys) + + # Indexing a single row: slice values to get the indicated row, and then + # use a recursive call to __getitem__ to handle the inner keys. + else: + starts = rt_input.row_splits[:-1] + limits = rt_input.row_splits[1:] + if context.executing_eagerly(): + # In python, __getitem__ should throw IndexError for out of bound + # indices. This will allow iteration run correctly as python will + # translate IndexError into StopIteration for next()/__next__(). + # Below is an example: + # import tensorflow as tf + # r = tf.ragged.constant([[1., 2.], [3., 4., 5.], [6.]]) + # for elem in r: + # print(elem) + # In non eager mode, the exception is thrown when session runs + # so we don't know if out of bound happens before. + # In eager mode, however, it is possible to find out when to + # throw out of bound IndexError. + # In the following row_key >= len(starts) is checked. In case of + # TypeError which happens when row_key is not an integer, the exception + # will simply be ignored as it will be processed later anyway. + try: + if int(row_key) >= len(starts): + raise IndexError("Row key {} out of bounds".format(row_key)) + except (TypeError, ValueError): + pass + row = rt_input.values[starts[row_key]:limits[row_key]] + return row.__getitem__(inner_keys) + + +def _slice_ragged_row_dimension(rt_input, row_key): + """Slice the outer dimension of `rt_input` according to the given `slice`. + + Args: + rt_input: The `RaggedTensor` to slice. + row_key: The `slice` object that should be used to slice `rt_input`. + + Returns: + A `RaggedTensor` containing the indicated slice of `rt_input`. + """ + if row_key.start is None and row_key.stop is None and row_key.step is None: + return rt_input + + # Use row_key to slice the starts & limits. + new_starts = rt_input.row_splits[:-1][row_key] + new_limits = rt_input.row_splits[1:][row_key] + zero_pad = array_ops.zeros([1], rt_input.row_splits.dtype) + + # If there's no slice step, then we can just select a single continuous + # span of `ragged.values(rt_input)`. + if row_key.step is None or row_key.step == 1: + # Construct the new splits. If new_starts and new_limits are empty, + # then this reduces to [0]. Otherwise, this reduces to: + # concat([[new_starts[0]], new_limits]) + new_splits = array_ops.concat( + [zero_pad[array_ops.size(new_starts):], new_starts[:1], new_limits], + axis=0) + values_start = new_splits[0] + values_limit = new_splits[-1] + return ragged_tensor.RaggedTensor.from_row_splits( + rt_input.values[values_start:values_limit], new_splits - values_start, + validate=False) + + # If there is a slice step (aka a strided slice), then use ragged_gather to + # collect the necessary elements of `ragged.values(rt_input)`. + else: + return _build_ragged_tensor_from_value_ranges(new_starts, new_limits, 1, + rt_input.values) + + +def _ragged_getitem_inner_dimensions(rt_input, key_list): + """Retrieve inner dimensions, keeping outermost dimension unchanged. + + Args: + rt_input: The `RaggedTensor` or `Tensor` from which a piece should be + extracted. + key_list: The __getitem__ keys for slicing the inner dimensions. + + Returns: + A `RaggedTensor`. + + Raises: + ValueError: If key_list is not supported. + """ + if not key_list: + return rt_input + + if not isinstance(rt_input, ragged_tensor.RaggedTensor): + return rt_input.__getitem__([slice(None, None, None)] + key_list) + + column_key = key_list[0] + if column_key is Ellipsis: + expanded_key_list = _expand_ellipsis(key_list, rt_input.values.shape.ndims) + return _ragged_getitem_inner_dimensions(rt_input, expanded_key_list) + + # Adding a new axis to a ragged inner dimension: recursively get the inner + # dimensions of rt_input with key_list[1:], and then wrap the result in a + # RaggedTensor that puts each value in its own row. + if column_key is array_ops.newaxis: + inner_rt = _ragged_getitem_inner_dimensions(rt_input, key_list[1:]) + nsplits = tensor_shape.dimension_at_index(inner_rt.row_splits.shape, 0) + if nsplits.value is not None: + nsplits = nsplits.value + else: + nsplits = array_ops.shape( + inner_rt.row_splits, out_type=inner_rt.row_splits.dtype + )[0] + return ragged_tensor.RaggedTensor.from_uniform_row_length( + inner_rt, 1, nrows=nsplits - 1, validate=False) + + # Slicing a range of columns in a ragged inner dimension. We use a + # recursive call to process the values, and then assemble a RaggedTensor + # with those values. + if isinstance(column_key, slice): + if (column_key.start is None and column_key.stop is None and + column_key.step is None): + # Trivial slice: recursively process all values, & splits is unchanged. + return rt_input.with_values( + _ragged_getitem_inner_dimensions(rt_input.values, key_list[1:])) + else: + if not ( + isinstance(column_key.start, (tensor_lib.Tensor, int, type(None))) + and isinstance(column_key.stop, (tensor_lib.Tensor, int, type(None))) + ): + raise TypeError("slice offsets must be integers or None") + + # Nontrivial slice: use ragged_gather to extract the indicated slice as + # a new RaggedTensor (inner_rt), and then recursively process its values. + starts = rt_input.row_splits[:-1] + limits = rt_input.row_splits[1:] + step = 1 if column_key.step is None else column_key.step + lower_bound = _if_ge_zero(step, lambda: starts, lambda: starts - 1) + upper_bound = _if_ge_zero(step, lambda: limits, lambda: limits - 1) + # inner_rt_starts[i] = index to start gathering for row i. + if column_key.start is None: + inner_rt_starts = _if_ge_zero(step, lambda: starts, lambda: limits - 1) + else: + start_offset = math_ops.cast(column_key.start, starts.dtype) + inner_rt_starts = _if_ge_zero( + column_key.start, + lambda: math_ops.minimum(starts + start_offset, upper_bound), + lambda: math_ops.maximum(limits + start_offset, lower_bound)) + # inner_rt_limits[i] = index to stop gathering for row i. + if column_key.stop is None: + inner_rt_limits = _if_ge_zero(step, lambda: limits, lambda: starts - 1) + else: + stop_offset = math_ops.cast(column_key.stop, starts.dtype) + inner_rt_limits = _if_ge_zero( + column_key.stop, + lambda: math_ops.minimum(starts + stop_offset, upper_bound), + lambda: math_ops.maximum(limits + stop_offset, lower_bound)) + inner_rt = _build_ragged_tensor_from_value_ranges( + inner_rt_starts, inner_rt_limits, column_key.step, rt_input.values) + # If the row dimension is uniform, then calculate the new + # uniform_row_length, and rebuild inner_rt using that uniform_row_lengths. + if rt_input.uniform_row_length is not None: + new_row_length = _slice_length(rt_input.uniform_row_length, column_key) + inner_rt = ragged_tensor.RaggedTensor.from_uniform_row_length( + inner_rt.values, new_row_length, rt_input.nrows()) + return inner_rt.with_values( + _ragged_getitem_inner_dimensions(inner_rt.values, key_list[1:])) + + # Indexing a single column in a ragged inner dimension: raise an Exception. + # See RaggedTensor.__getitem__.__doc__ for an explanation of why indexing + # into a ragged inner dimension is problematic. + if rt_input.uniform_row_length is None: + raise ValueError("Cannot index into an inner ragged dimension.") + + # Indexing a single column in a uniform inner dimension: check that the + # given index is in-bounds, and then use a strided slice over rt_input.values + # to take the indicated element from each row. + row_length = rt_input.uniform_row_length + column_key = math_ops.cast(column_key, row_length.dtype) + oob_err_msg = "Index out of bounds when indexing into a ragged tensor" + oob_checks = [ + check_ops.assert_greater_equal( + column_key, -row_length, message=oob_err_msg), + check_ops.assert_less(column_key, row_length, message=oob_err_msg), + ] + with ops.control_dependencies(oob_checks): + offset = _if_ge_zero(column_key, lambda: column_key, + lambda: row_length + column_key) + sliced_rt = rt_input.values[offset::row_length] + return _ragged_getitem_inner_dimensions(sliced_rt, key_list[1:]) + + +def _slice_length(value_length, slice_key): + """Computes the number of elements in a slice of a value with a given length. + + Returns the equivalent of: `len(range(value_length)[slice_key])` + + Args: + value_length: Scalar int `Tensor`: the length of the value being sliced. + slice_key: A `slice` object used to slice elements from the value. + + Returns: + The number of elements in the sliced value. + """ + # Note: we could compute the slice length without creating a zeros tensor + # with some variant of (stop-start)//step, but doing so would require more + # ops (for checking bounds, handling negative indices, negative step sizes, + # etc); and we expect this to be an uncommon operation, so we use this + # simpler implementation. + zeros = array_ops.zeros(value_length, dtype=dtypes.bool) + return array_ops.size(zeros[slice_key], out_type=value_length.dtype) + + +def _expand_ellipsis(key_list, num_remaining_dims): + """Expands the ellipsis at the start of `key_list`. + + Assumes that the first element of `key_list` is Ellipsis. This will either + remove the Ellipsis (if it corresponds to zero indices) or prepend a new + `slice(None, None, None)` (if it corresponds to more than zero indices). + + Args: + key_list: The arguments to `__getitem__()`. + num_remaining_dims: The number of dimensions remaining. + + Returns: + A copy of `key_list` with he ellipsis expanded. + Raises: + ValueError: If ragged_rank.shape.ndims is None + IndexError: If there are too many elements in `key_list`. + """ + if num_remaining_dims is None: + raise ValueError("Ellipsis not supported for unknown shape RaggedTensors") + num_indices = sum(1 for idx in key_list if idx is not array_ops.newaxis) + if num_indices > num_remaining_dims + 1: + raise IndexError("Too many indices for RaggedTensor") + elif num_indices == num_remaining_dims + 1: + return key_list[1:] + else: + return [slice(None, None, None)] + key_list + + +def _tensors_in_key_list(key_list): + """Generates all Tensors in the given slice spec.""" + if isinstance(key_list, tensor_lib.Tensor): + yield key_list + if isinstance(key_list, (list, tuple)): + for v in key_list: + for tensor in _tensors_in_key_list(v): + yield tensor + if isinstance(key_list, slice): + for tensor in _tensors_in_key_list(key_list.start): + yield tensor + for tensor in _tensors_in_key_list(key_list.stop): + yield tensor + for tensor in _tensors_in_key_list(key_list.step): + yield tensor + + +def _build_ragged_tensor_from_value_ranges(starts, limits, step, values): + """Returns a `RaggedTensor` containing the specified sequences of values. + + Returns a RaggedTensor `output` where: + + ```python + output.shape[0] = starts.shape[0] + output[i] = values[starts[i]:limits[i]:step] + ``` + + Requires that `starts.shape == limits.shape` and + `0 <= starts[i] <= limits[i] <= values.shape[0]`. + + Args: + starts: 1D integer Tensor specifying the start indices for the sequences of + values to include. + limits: 1D integer Tensor specifying the limit indices for the sequences of + values to include. + step: Integer value specifying the step size for strided slices. + values: The set of values to select from. + + Returns: + A `RaggedTensor`. + + Raises: + ValueError: Until the prerequisite ops are checked in. + """ + # Use `ragged_range` to get the index of each value we should include. + if step is None: + step = 1 + step = ops.convert_to_tensor(step, name="step") + if step.dtype.is_integer: + step = math_ops.cast(step, starts.dtype) + else: + raise TypeError("slice strides must be integers or None") + value_indices = ragged_math_ops.range(starts, limits, step, + row_splits_dtype=starts.dtype) + + # Use `ragged_gather` or `array_ops.gather` to collect the values. + if isinstance(values, ragged_tensor.RaggedTensor): + gathered_values = ragged_gather_ops.gather( + params=values, indices=value_indices.values) + else: + gathered_values = array_ops.gather( + params=values, indices=value_indices.values) + + # Assemble the RaggedTensor from splits & values. + return value_indices.with_values(gathered_values) + + +def _if_ge_zero(value, true_fn, false_fn): + """Returns `true_fn() if value >= 0 else false_fn()`.""" + # If `value` is statically known, then don't use a control flow op. + if isinstance(value, tensor_lib.Tensor): + const_value = tensor_util.constant_value(value) + if const_value is None: + return cond.cond(value >= 0, true_fn, false_fn) + else: + value = const_value + if value >= 0: + return true_fn() + else: + return false_fn() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_image_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_image_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f139b97f55eb52955cd9807094c3dc85b7cb51e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_image_ops.py @@ -0,0 +1,98 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Image operations for RaggedTensors.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(image_ops.resize_images_v2) +def resize_images_v2(images: ragged_tensor.RaggedTensor, + size, + method=image_ops.ResizeMethod.BILINEAR, + preserve_aspect_ratio=False, + antialias=False, + name=None): + """RaggedTensor dispatcher for tf.image.resize (tf-v2).""" + with ops.name_scope(name, "RaggedResizeImages", [images, size]): + return _resize_images( + image_ops.resize_images_v2, + images, + size, + method=method, + preserve_aspect_ratio=preserve_aspect_ratio, + antialias=antialias) + + +@dispatch.dispatch_for_api(image_ops.resize_images) +def resize_images_v1(images: ragged_tensor.RaggedTensor, + size, + method=image_ops.ResizeMethodV1.BILINEAR, + align_corners=False, + preserve_aspect_ratio=False, + name=None): + """RaggedTensor dispatcher for tf.image.resize (tf-v1).""" + with ops.name_scope(name, "RaggedResizeImages", [images, size]): + return _resize_images( + image_ops.resize_images, + images, + size, + method=method, + preserve_aspect_ratio=preserve_aspect_ratio, + align_corners=align_corners) + + +def _resize_images(resize_op, images, size, **kwargs): + """RaggedTensor dispatcher for tf.image.resize.""" + if images.shape.rank != 4: + raise ValueError( + "tf.image.resize: images.shape.rank must be 4 if images is ragged.") + + # Determine the output shape (excluding the batch dimension). + static_batch_size = tensor_shape.dimension_value(images.shape[0]) + size = ops.convert_to_tensor(size, dtypes.int32, "size") + size_as_shape = tensor_util.constant_value_as_shape(size).with_rank(2) + out_shape = size_as_shape + images.shape[-1:] + out_spec = tensor_spec.TensorSpec(out_shape, dtypes.float32) + + def resize_one(image): + if isinstance(image, ragged_tensor.RaggedTensor): + image = image.to_tensor() + return resize_op(image, size, **kwargs) + + def resize_with_map(): + return map_fn.map_fn_v2(resize_one, images, fn_output_signature=out_spec) + + def empty_result(): + channels = array_ops.shape(images.flat_values)[-1:] + return array_ops.zeros(array_ops.concat([[0], size, channels], axis=0)) + + if static_batch_size == 0: + return empty_result() + elif static_batch_size is not None: + return resize_with_map() + else: + empty_batch = math_ops.equal(images.nrows(), 0) + return cond.cond(empty_batch, empty_result, resize_with_map) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_map_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_map_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..06d9f0624d08306ecb1b3b4e838116f6fd86b0ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_map_ops.py @@ -0,0 +1,174 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Functional operations for RaggedTensors.""" + +from tensorflow.python.ops import map_fn as map_fn_lib +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import nest + + +def map_fn(fn, + elems, + dtype=None, + parallel_iterations=None, + back_prop=True, + swap_memory=False, + infer_shape=True, + name=None): + """map on the list of tensors unpacked from `elems` on dimension 0. + + The simplest version of `map_fn` repeatedly applies the callable `fn` to a + sequence of elements from first to last. The elements are made of the + tensors unpacked from `elems`. `dtype` is the data type of the return + value of `fn`. Users must provide `dtype` if it is different from + the data type of `elems`. + + Suppose that `elems` is unpacked into `values`, a list of tensors. The shape + of the result tensor is `[values.shape[0]] + fn(values[0]).shape`. + + This method also allows multi-arity `elems` and output of `fn`. If `elems` + is a (possibly nested) list or tuple of tensors, then each of these tensors + must have a matching first (unpack) dimension. The signature of `fn` may + match the structure of `elems`. That is, if `elems` is + `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: + `fn = lambda (t1, [t2, t3, [t4, t5]]):`. + + Furthermore, `fn` may emit a different structure than its input. For example, + `fn` may look like: `fn = lambda t1: return (t1 + 1, t1 - 1)`. In this case, + the `dtype` parameter is not optional: `dtype` must be a type or (possibly + nested) tuple of types matching the output of `fn`. + + To apply a functional operation to the nonzero elements of a SparseTensor + one of the following methods is recommended. First, if the function is + expressible as TensorFlow ops, use + + ```python + result = SparseTensor(input.indices, fn(input.values), input.dense_shape) + ``` + + If, however, the function is not expressible as a TensorFlow op, then use + + ```python + result = SparseTensor( + input.indices, map_fn(fn, input.values), input.dense_shape) + ``` + + instead. + + When executing eagerly, map_fn does not execute in parallel even if + `parallel_iterations` is set to a value > 1. You can still get the + performance benefits of running a function in parallel by using the + `tf.contrib.eager.defun` decorator, + + ```python + # Assume the function being used in map_fn is fn. + # To ensure map_fn calls fn in parallel, use the defun decorator. + @tf.contrib.eager.defun + def func(tensor): + return tf.map_fn(fn, tensor) + ``` + + Note that if you use the defun decorator, any non-TensorFlow Python code + that you may have written in your function won't get executed. See + `tf.contrib.eager.defun` for more details. The recommendation would be to + debug without defun but switch to defun to get performance benefits of + running map_fn in parallel. + + Args: + fn: The callable to be performed. It accepts one argument, which will have + the same (possibly nested) structure as `elems`. Its output must have the + same structure as `dtype` if one is provided, otherwise it must have the + same structure as `elems`. + elems: A tensor or (possibly nested) sequence of tensors, each of which will + be unpacked along their first dimension. The nested sequence of the + resulting slices will be applied to `fn`. + dtype: (optional) The output type(s) of `fn`. If `fn` returns a structure + of Tensors differing from the structure of `elems`, then `dtype` is not + optional and must have the same structure as the output of `fn`. Use + `RaggedTensorType` to declare an output of type `RaggedTensor`. + parallel_iterations: (optional) The number of iterations allowed to run in + parallel. When graph building, the default value is 10. While executing + eagerly, the default value is set to 1. + back_prop: (optional) True enables support for back propagation. + swap_memory: (optional) True enables GPU-CPU memory swapping. + infer_shape: (optional) False disables tests for consistent output shapes. + name: (optional) Name prefix for the returned tensors. + + Returns: + A possibly nested sequence of potentially ragged tensors. Each + tensor packs the results of applying `fn` to tensors unpacked from `elems` + along the first dimension, from first to last. + + Raises: + TypeError: if `fn` is not callable or the structure of the output of + `fn` and `dtype` do not match, or if elems is a SparseTensor. + ValueError: if the lengths of the output of `fn` and `dtype` do not match. + + #### Examples: + + ```python + elems = np.array([1, 2, 3, 4, 5, 6]) + squares = map_fn(lambda x: x * x, elems) + # squares == [1, 4, 9, 16, 25, 36] + ``` + + ```python + elems = (np.array([1, 2, 3]), np.array([-1, 1, -1])) + alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64) + # alternate == [-1, 2, -3] + ``` + + ```python + elems = np.array([1, 2, 3]) + alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64)) + # alternates[0] == [1, 2, 3] + # alternates[1] == [-1, -2, -3] + ``` + + ```python + elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]]) + mean = map_fn(tf.reduce_mean, elems) + # mean == [2, 4, 6] + ``` + + ```python + elems=ragged.constant([[1, 2, 3], [4, 5], [6, 7]], dtype=tf.int64) + out = map_fn(fn=lambda x: x+1, elems, + dtype=ragged.RaggedTensorType(type=tf.int64, ragged_rank=0)) + # out = tf.ragged.constant([[2, 3, 4], [5, 6], [7, 8]]) + ``` + """ + if dtype is None: + dtype = nest.map_structure(lambda e: e.dtype, elems) + dtype = nest.map_structure(_ragged_type_to_spec, dtype) + return map_fn_lib.map_fn(fn, + elems, + dtype, + parallel_iterations, + back_prop, + swap_memory, + infer_shape, + name) + + +def _ragged_type_to_spec(t): + if isinstance(t, ragged_tensor.RaggedTensorType): + # Note: need to adjust ragged_rank by 1, since RaggedTensorSpec gives the + # type for the mapped `fn` output, but RaggedTensorType gives the type for + # the result of stacking the mapped `fn` outputs. + return ragged_tensor.RaggedTensorSpec( + None, t.dtype, t.ragged_rank - 1, t.row_splits_dtype) + else: + return t diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ef98fb344aed2d6c7b113cfd47401bd6d0603ddd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_math_ops.py @@ -0,0 +1,1252 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Support for ragged tensors.""" + +import functools +import typing + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import gen_ragged_math_ops +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import segment_id_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +#=============================================================================== +# ragged.range +#=============================================================================== +# pylint: disable=redefined-builtin +@tf_export('ragged.range') +@dispatch.add_dispatch_support +def range(starts, + limits=None, + deltas=1, + dtype=None, + name=None, + row_splits_dtype=dtypes.int64): + """Returns a `RaggedTensor` containing the specified sequences of numbers. + + Each row of the returned `RaggedTensor` contains a single sequence: + + ```python + ragged.range(starts, limits, deltas)[i] == + tf.range(starts[i], limits[i], deltas[i]) + ``` + + If `start[i] < limits[i] and deltas[i] > 0`, then `output[i]` will be an + empty list. Similarly, if `start[i] > limits[i] and deltas[i] < 0`, then + `output[i]` will be an empty list. This behavior is consistent with the + Python `range` function, but differs from the `tf.range` op, which returns + an error for these cases. + + Examples: + + >>> tf.ragged.range([3, 5, 2]).to_list() + [[0, 1, 2], [0, 1, 2, 3, 4], [0, 1]] + >>> tf.ragged.range([0, 5, 8], [3, 3, 12]).to_list() + [[0, 1, 2], [], [8, 9, 10, 11]] + >>> tf.ragged.range([0, 5, 8], [3, 3, 12], 2).to_list() + [[0, 2], [], [8, 10]] + + The input tensors `starts`, `limits`, and `deltas` may be scalars or vectors. + The vector inputs must all have the same size. Scalar inputs are broadcast + to match the size of the vector inputs. + + Args: + starts: Vector or scalar `Tensor`. Specifies the first entry for each range + if `limits` is not `None`; otherwise, specifies the range limits, and the + first entries default to `0`. + limits: Vector or scalar `Tensor`. Specifies the exclusive upper limits for + each range. + deltas: Vector or scalar `Tensor`. Specifies the increment for each range. + Defaults to `1`. + dtype: The type of the elements of the resulting tensor. If not specified, + then a value is chosen based on the other args. + name: A name for the operation. + row_splits_dtype: `dtype` for the returned `RaggedTensor`'s `row_splits` + tensor. One of `tf.int32` or `tf.int64`. + + Returns: + A `RaggedTensor` of type `dtype` with `ragged_rank=1`. + """ + row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + if limits is None: + starts, limits = 0, starts + + with ops.name_scope(name, 'RaggedRange', [starts, limits, deltas]) as name: + starts = ops.convert_to_tensor(starts, dtype=dtype, name='starts') + limits = ops.convert_to_tensor(limits, dtype=dtype, name='limits') + deltas = ops.convert_to_tensor(deltas, dtype=dtype, name='deltas') + + # infer dtype if not explicitly provided + if dtype is None: + starts, limits, deltas = _infer_matching_dtype( + [starts, limits, deltas], + [dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64]) + + result = gen_ragged_math_ops.ragged_range( + starts, limits, deltas, Tsplits=row_splits_dtype, name=name) + return ragged_tensor.RaggedTensor.from_row_splits( + result.rt_dense_values, result.rt_nested_splits, validate=False) + + +def _infer_matching_dtype(tensors, dtype_hierarchy): + """Infers a matching dtype for tensors, and casts them to that dtype.""" + assert all(t.dtype in dtype_hierarchy for t in tensors) + inferred_dtype = max([t.dtype for t in tensors], key=dtype_hierarchy.index) + return [math_ops.cast(t, inferred_dtype) for t in tensors] + + +ops.no_gradient('RaggedRange') + +#=============================================================================== +# ragged_segment_ +#=============================================================================== + +# Docstring template used for the raggged_segment_ ops. +_RAGGED_SEGMENT_DOCSTRING = """\ +Computes the %(combination)s along segments of a RaggedTensor. + + Returns a RaggedTensor `output` with `num_segments` rows, where the row + `output[i]` is formed by taking the %(combination)s of all rows of `data` + whose corresponding `segment_id` is `i`. + + The length of the row `output[i]` will be the maximum of the lengths of + all rows of `data` whose corresponding `segment_id` is `i`. If no `data` + rows correspond to a given segment ID, then the output row for that segment + ID will be empty. + + Args: + data: A `RaggedTensor` containing the values to combine. + segment_ids: A `Tensor` or `RaggedTensor`. Must have type `int64` or + `int32`. `segment_ids.shape` must be a prefix of `data.shape`. + Must be greater than or equal to zero, and less than `num_segments`. + `segment_ids` is not required to be sorted. + num_segments: An `int32` or `int64` scalar specifying the number of + distinct segment ids. + name: A name prefix for the returned tensor (optional). + Returns: + A `RaggedTensor` containing the %(combined)s values. The returned tensor + has the same dtype as `data`, and its shape is + `[num_segments] + data.shape[segment_ids.rank:]`. + Raises: + ValueError: If `segment_ids.shape` is not a prefix of `data.shape`. +""" + + +def _ragged_segment_aggregate(unsorted_segment_op, + data, + segment_ids, + num_segments, + separator=None, + name=None): + """Aggregates along segments of a RaggedTensor using `unsorted_segment_op`. + + Returns a RaggedTensor `output` with `num_segments` rows, where the row + `output[i]` is formed by combining all rows of `data` whose corresponding + `segment_id` is `i`. The values in each row are combined using + `unsorted_segment_op`. + + The length of the row `output[i]` will be the maximum of the lengths of + all rows of `data` whose corresponding `segment_id` is `i`. If no `data` + rows correspond to a given segment ID, then the output row for that segment + ID will be empty. + + Args: + unsorted_segment_op: The tensorflow `op` that should be used to combine + values in each row. Must have the same signature and basic behavior as + `unsorted_segment_sum`, `unsorted_segment_max`, etc. + data: A `RaggedTensor` containing the values to be combined. + segment_ids: A `Tensor` or `RaggedTensor`. Must have type `int64` or + `int32`. `segment_ids.shape` must be a prefix of `data.shape`. + `segment_ids` is not required to be sorted. + num_segments: An `int32` or `int64` scalar. + separator: An optional string. Defaults to None. The separator to use when + joining. Only used for string types. + name: A name prefix for the returned tensor (optional). + + Returns: + A `RaggedTensor` containing the aggregated values. The returned tensor + has the same dtype as `data`, and its shape is + `[num_segments] + data.shape[segment_ids.rank:]`. + Raises: + ValueError: If segment_ids.shape is not a prefix of data.shape. + """ + if not (ragged_tensor.is_ragged(data) or + ragged_tensor.is_ragged(segment_ids)): + if separator is not None: + # It uses unsorted_segment_join. + return unsorted_segment_op(data, segment_ids, num_segments, separator, + name) + else: + return unsorted_segment_op(data, segment_ids, num_segments, name) + + with ops.name_scope(name, 'RaggedSegment', + [data, segment_ids, num_segments]) as name: + data = ragged_tensor.convert_to_tensor_or_ragged_tensor(data, name='data') + segment_ids = ragged_tensor.convert_to_tensor_or_ragged_tensor( + segment_ids, name='segment_ids') + data, segment_ids = ragged_tensor.match_row_splits_dtypes(data, segment_ids) + if segment_ids.dtype not in (dtypes.int32, dtypes.int64): + raise ValueError('segment_ids must have dtype int32 or int64.') + + if ragged_tensor.is_ragged(segment_ids): + if not ragged_tensor.is_ragged(data): + raise ValueError('segment_ids.shape must be a prefix of data.shape, ' + 'but segment_ids is ragged and data is not.') + check_splits = check_ops.assert_equal( + segment_ids.row_splits, + data.row_splits, + message='segment_ids.shape must be a prefix of data.shape') + with ops.control_dependencies([check_splits]): + return _ragged_segment_aggregate(unsorted_segment_op, data.values, + segment_ids.values, num_segments, + separator) + + # Find the length of each row in data. (shape=[data_nrows]) + data_row_lengths = data.row_splits[1:] - data.row_splits[:-1] + + # Find the length that each output row will have. The length of the row + # corresponding to segment `id` is `max(data_row_lengths[i])` where + # `segment_ids[i]=id`. (shape=[output_nrows]) + output_row_lengths = math_ops.maximum( + math_ops.unsorted_segment_max(data_row_lengths, segment_ids, + num_segments), 0) + + # Build the splits tensor for the output RaggedTensor. + output_splits = array_ops.concat([ + array_ops.zeros([1], output_row_lengths.dtype), + math_ops.cumsum(output_row_lengths) + ], + axis=0) + + # For each row in `data`, find the start & limit position where that row's + # values will be aggregated in output.values. + data_row_to_out_row_start = array_ops.gather(output_splits, segment_ids) + data_row_to_out_row_limit = data_row_to_out_row_start + data_row_lengths + + # For each value in `data.values`, find the position where it will + # aggregated in `output.values`. + # Get the target output values index for each data values index. + data_val_to_out_val_index = range(data_row_to_out_row_start, + data_row_to_out_row_limit).values + + # Recursively aggregate the values. + output_values = _ragged_segment_aggregate(unsorted_segment_op, data.values, + data_val_to_out_val_index, + output_splits[-1], separator) + return ragged_tensor.RaggedTensor.from_row_splits( + output_values, output_splits, validate=False) + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_sum) +def segment_sum(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + # For docs, see: _RAGGED_SEGMENT_DOCSTRING + return _ragged_segment_aggregate( + math_ops.unsorted_segment_sum, + data=data, + segment_ids=segment_ids, + num_segments=num_segments, + name=(name or 'RaggedSegmentSum')) + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_prod) +def segment_prod(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + # For docs, see: _RAGGED_SEGMENT_DOCSTRING + return _ragged_segment_aggregate( + math_ops.unsorted_segment_prod, + data=data, + segment_ids=segment_ids, + num_segments=num_segments, + name=(name or 'RaggedSegmentProd')) + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_min) +def segment_min(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + # For docs, see: _RAGGED_SEGMENT_DOCSTRING + return _ragged_segment_aggregate( + math_ops.unsorted_segment_min, + data=data, + segment_ids=segment_ids, + num_segments=num_segments, + name=(name or 'RaggedSegmentMin')) + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_max) +def segment_max(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + # For docs, see: _RAGGED_SEGMENT_DOCSTRING + return _ragged_segment_aggregate( + math_ops.unsorted_segment_max, + data=data, + segment_ids=segment_ids, + num_segments=num_segments, + name=(name or 'RaggedSegmentMax')) + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_mean) +def segment_mean(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + """For docs, see: _RAGGED_SEGMENT_DOCSTRING.""" + with ops.name_scope(name, 'RaggedSegmentMean', + [data, segment_ids, num_segments]): + total = segment_sum(data, segment_ids, num_segments) + ones = ragged_tensor.RaggedTensor.from_nested_row_splits( + array_ops.ones_like(data.flat_values), + data.nested_row_splits, + validate=False) + count = segment_sum(ones, segment_ids, num_segments) + if ragged_tensor.is_ragged(total): + return total.with_flat_values(total.flat_values / count.flat_values) + else: + return total / count + + +@dispatch.dispatch_for_api(math_ops.unsorted_segment_sqrt_n) +def segment_sqrt_n(data: ragged_tensor.RaggedOrDense, + segment_ids: ragged_tensor.RaggedOrDense, + num_segments, + name=None): + """For docs, see: _RAGGED_SEGMENT_DOCSTRING.""" + with ops.name_scope(name, 'RaggedSegmentSqrtN', + [data, segment_ids, num_segments]): + total = segment_sum(data, segment_ids, num_segments) + ones = ragged_tensor.RaggedTensor.from_nested_row_splits( + array_ops.ones_like(data.flat_values), + data.nested_row_splits, + validate=False) + count = segment_sum(ones, segment_ids, num_segments) + if ragged_tensor.is_ragged(total): + return total.with_flat_values(total.flat_values / + math_ops.sqrt(count.flat_values)) + else: + return total / math_ops.sqrt(count) + + +def _set_ragged_segment_docstring(func, combination, combined): + func.__doc__ = _RAGGED_SEGMENT_DOCSTRING % dict( + combination=combination, combined=combined) + + +_set_ragged_segment_docstring(segment_sum, 'sum', 'summed') +_set_ragged_segment_docstring(segment_prod, 'product', 'multiplied') +_set_ragged_segment_docstring(segment_min, 'minimum', 'minimized') +_set_ragged_segment_docstring(segment_max, 'maximum', 'maximized') +_set_ragged_segment_docstring(segment_mean, 'mean', 'averaged') +_set_ragged_segment_docstring(segment_sqrt_n, 'sum divided by sqrt(N)', + 'summed') + +#=============================================================================== +# ragged_reduce_ +#=============================================================================== + +# Docstring template used for ragged_reduce_ ops. +_RAGGED_REDUCE_DOCSTRING = """\ +Computes the %(combination)s of elements across dimensions of a `RaggedTensor`. + + Reduces `input_tensor` along the dimensions given in `axis` by taking the + %(combination)s of values. If a reduced dimension has no elements for + some index, then the value for that index will be %(default)s. + + The rank of the tensor is reduced by `1` for each entry in `axis`. If + `axis` is not specified, then all dimensions are reduced, and a scalar + value is returned. + Args: + input_tensor: A `RaggedTensor` containing the values to be %(combined)s. + axis: The dimensions to reduce. May be `None` (to reduce all axes), an + `int` (to reduce a single axis), a `list` or `tuple` of `int` (to reduce + a given set of axes), or a `Tensor` with a constant value. Must be in + the range `[0, input_tensor.rank]`. + name: A name prefix for the returned tensor (optional). + Returns: + A `RaggedTensor` containing the %(combined)s values. The returned tensor + has the same dtype as `data`, and its shape is given by removing the + dimensions specified in `axis` from `input_tensor.shape`. The `ragged_rank` + of the returned tensor is given by substracting any ragged dimensions + specified in `axis` from `input_tensor.ragged_rank`. + Raises: + ValueError: If `axis` contains a `Tensor` whose value is not constant. + ####Example: + %(example)s +""" +_RAGGED_REDUCE_SUM_EXAMPLE = """ + >>> rt = tf.ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]]) + >>> tf.reduce_sum(rt, axis=0).numpy() # = [3+1+9+2, 1+5+6, 4] + array([15, 12, 4], dtype=int32) + >>> tf.reduce_sum(rt, axis=1).numpy() # = [3+1+4, 1+5, 9, 2+6] + array([8, 6, 9, 8], dtype=int32) +""" +_RAGGED_REDUCE_PROD_EXAMPLE = """ + >>> rt = tf.ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]]) + >>> tf.reduce_prod(rt, axis=0).numpy() # = [3*1*9*2, 1*5*6, 4] + array([54, 30, 4], dtype=int32) + >>> tf.reduce_prod(rt, axis=1).numpy() # = [3*1*4, 1*5, 9, 2*6] + array([12, 5, 9, 12], dtype=int32) +""" +_RAGGED_REDUCE_MIN_EXAMPLE = """ + >>> rt = tf.ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]]) + >>> tf.reduce_min(rt, axis=0).numpy() + array([1, 1, 4], dtype=int32) + >>> tf.reduce_min(rt, axis=1).numpy() + array([1, 1, 9, 2], dtype=int32) +""" +_RAGGED_REDUCE_MAX_EXAMPLE = """ + >>> rt = tf.ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]]) + >>> tf.reduce_max(rt, axis=0).numpy() + array([9, 6, 4], dtype=int32) + >>> tf.reduce_max(rt, axis=1).numpy() + array([4, 5, 9, 6], dtype=int32) +""" +_RAGGED_REDUCE_MEAN_EXAMPLE = """ + >>> rt = tf.ragged.constant([[3, 1, 4], [1, 5], [9], [2, 6]]) + >>> tf.reduce_mean(rt, axis=0).numpy() + array([3.75, 4. , 4. ]) + >>> tf.reduce_mean(rt, axis=1).numpy() + array([2.66666667, 3. , 9. , 4. ]) +""" +_RAGGED_REDUCE_VARIANCE_EXAMPLE = """ + >>> rt = tf.ragged.constant([[1, 1, 4], [2, 1], [3], [4, 1]], + ... dtype=tf.float64) + >>> tf.math.reduce_variance(rt, axis=0).numpy() + array([1.25, 0., 0.]) + >>> tf.math.reduce_variance(rt, axis=1).numpy() + array([2., 0.25, 0., 2.25]) +""" +_RAGGED_REDUCE_STD_EXAMPLE = """ + >>> rt = tf.ragged.constant([[1, 0], [2, 1], [3], [4, 1]], + ... dtype=tf.float64) + >>> tf.math.reduce_std(rt, axis=0).numpy() + array([1.11803399, 0.47140452]) + >>> tf.math.reduce_std(rt, axis=1).numpy() + array([0.5, 0.5, 0., 1.5]) +""" +_RAGGED_REDUCE_ALL_EXAMPLE = """ + >>> rt = tf.ragged.constant([[True, True], [True, True, False, True], [False, True]]) + >>> tf.reduce_all(rt, axis=0).numpy() + array([False, True, False, True]) + >>> tf.reduce_all(rt, axis=1).numpy() + array([ True, False, False]) +""" +_RAGGED_REDUCE_ANY_EXAMPLE = """ + >>> rt = tf.ragged.constant([[True, True], [True, True, False, True], [False, True]]) + >>> tf.reduce_any(rt, axis=0).numpy() + array([ True, True, False, True]) + >>> tf.reduce_any(rt, axis=1).numpy() + array([ True, True, True]) +""" + + +def ragged_reduce_aggregate(reduce_op, + unsorted_segment_op, + rt_input, + axis, + keepdims, + separator=None, + name=None): + """Aggregates across axes of a RaggedTensor using the given `Tensor` ops. + + Reduces `rt_input` along the dimensions given in `axis`. The rank of the + tensor is reduced by 1 for each entry in `axis`. If `axis` is not specified, + then all dimensions are reduced, and a scalar value is returned. + + This op assumes that `reduce_op` and `unsorted_segment_op` are associative; + if not, then reducing multiple axes will return incorrect results. (In + particular, reducing multiple axes is currently implemented by reducing the + axes one at a time.) + + Args: + reduce_op: The tensorflow `op` that should be used to reduce values in + uniform dimensions. Must have the same signature and basic behavior as + `reduce_sum`, `reduce_max`, etc. + unsorted_segment_op: The tensorflow `op` that should be used to combine + values in ragged dimensions. Must have the same signature and basic + behavior as `unsorted_segment_sum`, `unsorted_segment_max`, etc. + rt_input: A `Tensor` or `RaggedTensor` containing the values to be reduced. + axis: The axis or axes to reduce. May be `None` (to reduce all axes), an + `int` (to reduce a single axis), a `list` or `tuple` of `int` (to reduce a + given set of axes), or a `Tensor` with a constant value. Must be in the + range `[0, rt_input.rank)`. + keepdims: If true, retains reduced dimensions with length 1. + separator: An optional string. Defaults to None. The separator to use when + joining. The separator must not be set for non-string data types. (i.e. if + separator is not None then it uses string ops) + name: A name prefix for the returned tensor (optional). + + Returns: + A `RaggedTensor` containing the reduced values. The returned tensor + has the same dtype as `data`, and its shape is given by removing the + dimensions specified in `axis` from `rt_input.shape`. The `ragged_rank` + of the returned tensor is given by substracting any ragged dimensions + specified in `axis` from `rt_input.ragged_rank`. + Raises: + ValueError: If `axis` contains a `Tensor` whose value is not constant. + """ + # When separator is not None, We infer that dtype is string and + # reduce_join will be called. + if separator is None: + maybe_separator = {} + else: + maybe_separator = {'separator': separator} + + if not ragged_tensor.is_ragged(rt_input): + return reduce_op( + rt_input, axis, keepdims=keepdims, name=name, **maybe_separator) + + if isinstance(axis, tensor.Tensor): + axis = tensor_util.constant_value(axis) + if axis is None: + raise ValueError('axis must be known at graph construction time.') + if isinstance(axis, np.ndarray): + axis = axis.tolist() + + # When reducing all axes, just ignore splits & reduce the inner values. + if axis is None: + result = reduce_op(rt_input.flat_values, None, keepdims=keepdims, + name=name, **maybe_separator) + if keepdims: + # Expand the result to the input number of dimensions. + for _ in rt_input.shape[1:]: + result = array_ops.expand_dims(result, axis=0) + return result + + with ops.name_scope(name, 'RaggedReduce', [rt_input, axis]): + if isinstance(axis, (tuple, list)): + if not axis: + return rt_input + elif len(axis) == 1: + axis = axis[0] + else: + # When reducing multiple axes, as we reduce one at a time (see below), + # the negative axis has to be converted to positive at the first run + # as the sort with negative axis will have different orders. + # See GitHub issue 27497. + axis = [ + array_ops.get_positive_axis(a, rt_input.shape.ndims, 'axis[%s]' % i, + 'rank(input_tensor)') + for i, a in enumerate(axis) + ] + # When reducing multiple axes, just reduce one at a time. This is less + # efficient, and only works for associative ops. (In particular, it + # does not work for reduce_mean.) However, reducing multiple axes at + # once will probably require a nontrivial c++ op. + axis = sorted(axis) + inner_reduced = ragged_reduce_aggregate(reduce_op, unsorted_segment_op, + rt_input, axis[-1], keepdims, + separator) + return ragged_reduce_aggregate(reduce_op, unsorted_segment_op, + inner_reduced, axis[:-1], keepdims, + separator) + + rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + rt_input, name='rt_input') + + axis = array_ops.get_positive_axis( + axis, rt_input.shape.ndims, ndims_name='rank(input_tensor)') + + if axis == 0: + # out[i_1, i_2, ..., i_N] = sum_{j} rt_input[j, i_1, i_2, ..., i_N] + row_lengths = rt_input.row_splits[1:] - rt_input.row_splits[:-1] + num_segments = math_ops.maximum(math_ops.reduce_max(row_lengths), 0) + segment_ids = range(row_lengths).values + result = _ragged_segment_aggregate(unsorted_segment_op, rt_input.values, + segment_ids, num_segments, separator) + if keepdims: + result = array_ops.expand_dims(result, axis=0) + return result + elif axis == 1: + # out[i_0, i_1, i_2, ..., i_N] = sum_{j} rt_input[i_0, j, i_2, ..., i_N] + num_segments = array_ops.shape(rt_input.row_splits)[0] - 1 + segment_ids = segment_id_ops.row_splits_to_segment_ids( + rt_input.row_splits) + result = _ragged_segment_aggregate(unsorted_segment_op, rt_input.values, + segment_ids, num_segments, separator) + if keepdims: + result = array_ops.expand_dims(result, axis=1) + return result + else: + # out[i_0, ..., i_[axis-1], i_axis+1], ..., i_N] = + # sum_{j} rt_input [i_0, ..., i_[axis-1], j, i_axis+1], ..., i_N] + return rt_input.with_values( + ragged_reduce_aggregate(reduce_op, unsorted_segment_op, + rt_input.values, axis - 1, keepdims, + separator)) + + +@dispatch.dispatch_for_api(math_ops.reduce_sum) +def reduce_sum(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + + return ragged_reduce_aggregate( + reduce_op=math_ops.reduce_sum, + unsorted_segment_op=math_ops.unsorted_segment_sum, + rt_input=input_tensor, + axis=axis, + keepdims=keepdims, + name=(name or 'RaggedReduceSum')) + + +@dispatch.dispatch_for_api(math_ops.reduce_prod) +def reduce_prod(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + return ragged_reduce_aggregate( + reduce_op=math_ops.reduce_prod, + unsorted_segment_op=math_ops.unsorted_segment_prod, + rt_input=input_tensor, + axis=axis, + keepdims=keepdims, + name=(name or 'RaggedReduceProd')) + + +@dispatch.dispatch_for_api(math_ops.reduce_min) +def reduce_min(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + return ragged_reduce_aggregate( + reduce_op=math_ops.reduce_min, + unsorted_segment_op=math_ops.unsorted_segment_min, + rt_input=input_tensor, + axis=axis, + keepdims=keepdims, + name=(name or 'RaggedReduceMin')) + + +@dispatch.dispatch_for_api(math_ops.reduce_max) +def reduce_max(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + return ragged_reduce_aggregate( + reduce_op=math_ops.reduce_max, + unsorted_segment_op=math_ops.unsorted_segment_max, + rt_input=input_tensor, + axis=axis, + keepdims=keepdims, + name=(name or 'RaggedReduceMax')) + + +@dispatch.dispatch_for_api(math_ops.reduce_mean) +def reduce_mean(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + with ops.name_scope(name, 'RaggedReduceMean', [input_tensor, axis]): + total = reduce_sum(input_tensor, axis, keepdims) + if ragged_tensor.is_ragged(input_tensor): + ones = ragged_tensor.RaggedTensor.from_nested_row_splits( + array_ops.ones_like(input_tensor.flat_values), + input_tensor.nested_row_splits, + validate=False) + else: + ones = array_ops.ones_like(input_tensor) + count = reduce_sum(ones, axis, keepdims) + if ragged_tensor.is_ragged(total): + return ragged_tensor.RaggedTensor.from_nested_row_splits( + total.flat_values / count.flat_values, + total.nested_row_splits, + validate=False) + else: + return total / count + + +@dispatch.dispatch_for_api(math_ops.reduce_variance) +def reduce_variance(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=False, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + with ops.name_scope(name, 'RaggedReduceVariance', [input_tensor, axis]): + input_tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input_tensor, name='input_tensor') + if input_tensor.dtype.is_complex: + raise ValueError( + 'reduce_variance is not supported for RaggedTensors with complex dtypes.' + ) + square_of_input = math_ops.square(input_tensor) + mean_of_square = reduce_mean(square_of_input, axis=axis, keepdims=keepdims) + mean = reduce_mean(input_tensor, axis=axis, keepdims=keepdims) + square_of_mean = math_ops.square(mean) + # Note: the above method of computing variance is not numerically stable, + # and can result in negative variances. Here we clip to >= 0. + return math_ops.maximum(mean_of_square - square_of_mean, 0) + + +@dispatch.dispatch_for_api(math_ops.reduce_std) +def reduce_std(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=False, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + with ops.name_scope(name, 'RaggedReduceStd', [input_tensor, axis]): + variance = reduce_variance(input_tensor, axis=axis, keepdims=keepdims) + return math_ops.sqrt(variance) + + +def _cast(input_tensor, dtype): + return ragged_functional_ops.map_flat_values(math_ops.cast, input_tensor, + dtype) + + +@dispatch.dispatch_for_api(math_ops.reduce_all) +def reduce_all(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + with ops.name_scope(name, 'RaggedReduceAll', [input_tensor, axis]): + return _cast( + reduce_prod(_cast(input_tensor, dtypes.int32), axis, keepdims), + dtypes.bool) + + +@dispatch.dispatch_for_api(math_ops.reduce_any) +def reduce_any(input_tensor: ragged_tensor.Ragged, + axis=None, + keepdims=None, + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + with ops.name_scope(name, 'RaggedReduceAny', [input_tensor, axis]): + return _cast( + reduce_sum(_cast(input_tensor, dtypes.int32), axis, keepdims), + dtypes.bool) + + +def _set_ragged_reduce_docstring(func, combination, combined, default, example): + func.__doc__ = _RAGGED_REDUCE_DOCSTRING % dict( + combination=combination, + combined=combined, + default=default, + example=example) + + +_set_ragged_reduce_docstring(reduce_sum, 'sum', 'summed', '0', + _RAGGED_REDUCE_SUM_EXAMPLE) +_set_ragged_reduce_docstring(reduce_prod, 'product', 'multiplied', '1', + _RAGGED_REDUCE_PROD_EXAMPLE) +_set_ragged_reduce_docstring(reduce_min, 'minimum', 'minimized', + '`input_tensor.dtype.min`', + _RAGGED_REDUCE_MIN_EXAMPLE) +_set_ragged_reduce_docstring(reduce_max, 'maximum', 'maximized', + '`input_tensor.dtype.max`', + _RAGGED_REDUCE_MAX_EXAMPLE) +_set_ragged_reduce_docstring(reduce_mean, 'mean', 'averaged', 'NaN', + _RAGGED_REDUCE_MEAN_EXAMPLE) +_set_ragged_reduce_docstring(reduce_variance, 'variance', 'averaged', 'NaN', + _RAGGED_REDUCE_VARIANCE_EXAMPLE) +_set_ragged_reduce_docstring(reduce_std, 'std', 'averaged', 'NaN', + _RAGGED_REDUCE_STD_EXAMPLE) +_set_ragged_reduce_docstring(reduce_all, 'logical and', 'and-ed', 'True', + _RAGGED_REDUCE_ALL_EXAMPLE) +_set_ragged_reduce_docstring(reduce_any, 'logical or', 'or-ed', 'False', + _RAGGED_REDUCE_ANY_EXAMPLE) + + +#=============================================================================== +# ragged.matmul +#=============================================================================== +@dispatch.dispatch_for_api(math_ops.matmul) +def matmul(a: ragged_tensor.RaggedOrDense, + b: ragged_tensor.RaggedOrDense, + transpose_a=False, + transpose_b=False, + adjoint_a=False, + adjoint_b=False, + a_is_sparse=False, + b_is_sparse=False, + output_type=None, + name=None): + """Multiplies matrix `a` by matrix `b`. + + If all transpose or adjoint attributes are `False` then: + + ``` + output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j]), for all indices i, j. + ``` + + The inputs `a` and `b` must have `rank >= 2`, where the outermost `rank - 2` + dimensions are batch dimensions. The inputs must have the same dtype. See + `tf.matmul` for more information. + + Args: + a: `tf.Tensor` or `RaggedTensor` with `rank > 1`. + b: `tf.Tensor` or `RaggedTensor` with same type and rank as `a`. + transpose_a: If `True`, `a` is transposed before multiplication. + transpose_b: If `True`, `b` is transposed before multiplication. + adjoint_a: If `True`, `a` is conjugated & transposed before multiplication. + adjoint_b: If `True`, `b` is conjugated & transposed before multiplication. + a_is_sparse: If `True`, optimize assuming `a` is mostly zero. + b_is_sparse: If `True`, optimize assuming `b` is mostly zero. + output_type: The output datatype (optional). + name: Name for the operation (optional). + + Returns: + A `Tensor` or `RaggedTensor` with the same rank and shape as `a`, where + each inner-most matrix is the product of the corresponding matrices in `a` + and `b`. + """ + if transpose_a and adjoint_a: + raise ValueError('Only one of transpose_a and adjoint_a can be True.') + if transpose_b and adjoint_b: + raise ValueError('Only one of transpose_b and adjoint_b can be True.') + + kwargs = dict( + transpose_a=transpose_a, + transpose_b=transpose_b, + adjoint_a=adjoint_a, + adjoint_b=adjoint_b, + a_is_sparse=a_is_sparse, + b_is_sparse=b_is_sparse, + output_type=output_type) + + with ops.name_scope(name, 'RaggedMatMul', [a, b]) as name: + a = ragged_tensor.convert_to_tensor_or_ragged_tensor(a, name='a') + b = ragged_tensor.convert_to_tensor_or_ragged_tensor(b, name='b') + + a_is_ragged = isinstance(a, ragged_tensor.RaggedTensor) + b_is_ragged = isinstance(b, ragged_tensor.RaggedTensor) + if not (a_is_ragged or b_is_ragged): + return math_ops.matmul(a, b, **kwargs) + + if a.dtype != b.dtype: + raise ValueError('`a` and `b` must have the same dtype.') + + # TODO(edloper): Support broadcasting inputs. (Broadcast support is not + # documented by https://www.tensorflow.org/api_docs/python/tf/linalg/matmul, + # but it is supported by the op.) + + # Find the rank of the input tensors. + if a.shape.rank is None: + if b.shape.rank is None: + raise ValueError('matmul requires at least one input to have known ' + 'rank if either input is ragged.') + rank = b.shape.rank + else: + if b.shape.rank is not None and a.shape.rank != b.shape.rank: + raise ValueError('`a` and `b` must have the same rank.') + rank = a.shape.rank + + # At least one of `a` and `b` is ragged; and ragged tensors always have + # rank>=2. + if rank < 2: + # This can happen if e.g. `a` is a 1D dense tensor and `b` is a + # ragged tensor with unknown rank. Since ragged tensors always have + # `rank>=2`, this implies that `a` and `b` have different ranks. + raise ValueError('`a` and `b` must have the same rank.') + + # Rank>3: We have multiple batch dimensions. Merge them into a single + # batch dimension, recursively call `matmul`, and then restore the original + # batch dimension (using a.row_splits). + if rank > 3: + shape_err = 'Batch dimensions of `a` and `b` do not have the same size.' + if not a_is_ragged: + a = ragged_tensor.RaggedTensor.from_tensor(a, ragged_rank=1) + if not b_is_ragged: + b = ragged_tensor.RaggedTensor.from_tensor(b, ragged_rank=1) + with ops.control_dependencies([ + check_ops.assert_equal(a.row_splits, b.row_splits, message=shape_err) + ]): + flat_result = matmul(a.values, b.values, **kwargs) + return a.with_values(flat_result) + + if rank == 2: + return _matmul_2d(a, b, **kwargs) + + assert rank == 3 # I.e., we have a single batch dimension. + + a_ragged_rank = a.ragged_rank if a_is_ragged else 0 + if a_ragged_rank == 1 and not (b_is_ragged or transpose_a or adjoint_a): + # If `a.shape=[B, (I), J]` and `b.shape=[B, J, K], then we can compute + # the result with a single dense `matmul`. + return _matmul_3d_with_batch_dim_folding(a, b, **kwargs) + else: + # Otherwie, fall back on using `map_fn`. + return _matmul_3d_with_map_fn(a, b, **kwargs) + + +def _matmul_2d(a, b, **kwargs): + """Multiplies potentially ragged 2D tensors. + + Args: + a: A 2D Tensor or RaggedTensor with `shape=[I, J]` + b: A 2D Tensor or RaggedTensor with `shape=[J, K]` + **kwargs: Additional arguments for `tf.matmul` (e.g. transpose_a). + + Returns: + A 2D Tensor with `shape=[I, K]`. + """ + # multiplying `a` and `b` is only well-defined if `a` and `b` are + # actually uniform (and just happened to be stored as ragged tensors). + # Check that they're uniform, convert them to tf.Tensor. + ragged_err = ('The matrices in `a` and `b` may not be ' + 'ragged in their innermost dimension.') + checks = [] + if isinstance(a, ragged_tensor.RaggedTensor): + original_size = array_ops.size(a.flat_values) + a = a.to_tensor() + checks.append( + check_ops.assert_equal( + original_size, array_ops.size(a), message=ragged_err)) + if isinstance(b, ragged_tensor.RaggedTensor): + original_size = array_ops.size(b.flat_values) + b = b.to_tensor() + checks.append( + check_ops.assert_equal( + original_size, array_ops.size(b), message=ragged_err)) + with ops.control_dependencies(checks): + return math_ops.matmul(a, b, **kwargs) + + +def _matmul_3d_with_map_fn(a, b, **kwargs): + """Multiplies batches of 2D matrices using map_fn. + + `output[n, i, k]` = sum_j (a[n, i, j] * b[n, j, k])` (for all `n`, `i`, `k`). + + Requires that `a[n, i].nrows()` == `b[n].nrows()` (for all `n` and `i`). + + Args: + a: A 3D Tensor or RaggedTensor with `shape=[B, I, J]`, where dimensions `I` + and `J` may be ragged. + b: A 3D Tensor or RaggedTensor with `shape=[B, J, K]`, where dimensions `J` + and `K` may be ragged. + **kwargs: Additional arguments for `tf.matmul` (e.g. transpose_a). + + Returns: + A 3D RaggedTensor with `shape=[B, (I), (K)]`. + """ + # Determine the ragged rank of the result. In the normal case, we have: + # [B, I, J] * [B, J, K] -> [B, I, K] + # Or if we're using transpose_b, then we have: + # [B, I, J] * [B, K, J] -> [B, I, K] + # In either case, output_ragged_rank=2 iff the K dimension is ragged. + if (isinstance(b, ragged_tensor.RaggedTensor) and + (b.ragged_rank == 2 or kwargs.get('transpose_b') or + kwargs.get('adjoint_b'))): + output_ragged_rank = 2 + else: + output_ragged_rank = 1 + + def single_batch_matmul(x): + out = _matmul_2d(x[0], x[1], **kwargs) + if output_ragged_rank == 2: + out = ragged_tensor.RaggedTensor.from_tensor(out) + return out + + fn_out_shape = None # Figure out proper shape. + row_splits_dtype = ( + a.row_splits.dtype + if isinstance(a, ragged_tensor.RaggedTensor) else b.row_splits.dtype) + output_type = kwargs['output_type'] + if output_type is None: + output_type = a.dtype + spec = ragged_tensor.RaggedTensorSpec( + shape=fn_out_shape, + dtype=output_type, + ragged_rank=output_ragged_rank - 1, + row_splits_dtype=row_splits_dtype) + result = map_fn.map_fn( + single_batch_matmul, elems=(a, b), fn_output_signature=spec) + + # map_fn loses shape information; restore it, where possible. + # pylint: disable=protected-access + if kwargs.get('transpose_a') or kwargs.get('adjoint_a'): + result._set_shape(a.shape[:-2] + a.shape[-1:] + [None]) + else: + result._set_shape(a.shape[:-2] + a.shape[-2:-1] + [None]) + if kwargs.get('transpose_b') or kwargs.get('adjoint_b'): + result._set_shape(b.shape[:-2] + [None] + b.shape[-2:-1]) + else: + result._set_shape(b.shape[:-2] + [None] + b.shape[-1:]) + + return result + + +def _matmul_3d_with_batch_dim_folding(a, b, **kwargs): + """Multiply batches of 2D matrices where only `a.shape[1]` is ragged. + + Args: + a: A RaggedTensor with `shape=[B, (I), J]`. (ragged_rank must be 1.) + b: A Tensor with `shape=[B, J, K]` + **kwargs: Additional arguments for `tf.matmul` (e.g. transpose_a). + transpose_a and adjoint_a must not be true. + + Returns: + A RaggedTensor with `shape=[B, (I), K]. + """ + # reshaped_a.shape = [sum(i_1, i_2, ..., i_B), 1, J] + reshaped_a = array_ops.expand_dims(a.values, 1) + # reshaped_b.shape = [sum(i_1, i_2, ..., i_B), J, K] + reshaped_b = array_ops.repeat(b, a.row_lengths(), axis=0) + # flat_result.shape = [sum(i_1, i_2, ..., i_B), 1, K] + flat_result = math_ops.matmul(reshaped_a, reshaped_b, **kwargs) + # result.shape = [B, (I), K] + return a.with_values(array_ops.squeeze(flat_result, axis=1)) + + +#=============================================================================== +# ragged.softmax +#=============================================================================== +@dispatch.dispatch_for_api(nn_ops.softmax_v2) +def softmax(logits: ragged_tensor.Ragged, axis=None, name=None): + """Computes softmax activations. + + Used for multi-class predictions. The sum of all outputs generated by softmax + is 1. + + This function performs the equivalent of + + softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis) + + Example usage: + + >>> softmax = tf.nn.softmax([-1, 0., 1.]) + >>> softmax + + >>> sum(softmax) + + + Args: + logits: A non-empty `Tensor`. Must be one of the following types: `half`, + `float32`, `float64`. + axis: The dimension softmax would be performed on. The default is -1 which + indicates the last dimension. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type and shape as `logits`. + + Raises: + InvalidArgumentError: if `logits` is empty or `axis` is beyond the last + dimension of `logits`. + """ + if axis is None: + axis = -1 + + with ops.name_scope(name, 'RaggedSoftmax', [logits]) as name: + max_input = reduce_max(logits, axis=axis, keepdims=True) + logits_exp = math_ops.exp(math_ops.subtract(logits, max_input)) + denominator = reduce_sum(logits_exp, axis=axis, keepdims=True) + return math_ops.divide(logits_exp, denominator) + + +#=============================================================================== +# ragged.add_n +#=============================================================================== +@dispatch.dispatch_for_api(math_ops.add_n) +def add_n(inputs: typing.List[ragged_tensor.RaggedOrDense], name=None): + """RaggedTensor implementation for tf.math.add_n.""" + if len(inputs) < 0: + raise ValueError('tf.add_n: expected at least one input.') + with ops.name_scope(name, 'RaggedAddN', inputs): + return ragged_functional_ops.map_flat_values(math_ops.add_n, inputs) + + +#=============================================================================== +# Ragged version of nn_ops.dropout +#=============================================================================== +@dispatch.dispatch_for_api(nn_ops.dropout) +def dropout_v1(x: ragged_tensor.Ragged, + keep_prob=None, + noise_shape=None, + seed=None, + name=None, + rate=None): + """Ragged dispatch target for tf.nn.dropout.""" + if noise_shape is not None: + raise ValueError('noise_shape is not supported yet for RaggedTensor x') + with ops.name_scope(name, 'RaggedNNDropout', [x, rate]): + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, name='x') + return x.with_flat_values( + nn_ops.dropout( + x.flat_values, keep_prob=keep_prob, seed=seed, rate=rate)) + + +@dispatch.dispatch_for_api(nn_ops.dropout_v2) +def dropout_v2(x: ragged_tensor.Ragged, + rate, + noise_shape=None, + seed=None, + name=None): + """Ragged dispatch target for tf.nn.dropout.""" + if noise_shape is not None: + raise ValueError('noise_shape is not supported yet for RaggedTensor x') + with ops.name_scope(name, 'RaggedNNDropout', [x, rate]): + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, name='x') + return x.with_flat_values( + nn_ops.dropout_v2(x.flat_values, rate=rate, seed=seed)) + + +@dispatch.dispatch_for_api(nn_ops.stateless_dropout) +def stateless_dropout(x: ragged_tensor.Ragged, + rate, + seed, + rng_alg=None, + noise_shape=None, + name=None): + """Ragged dispatch target for tf.nn.experimental.stateless_dropout.""" + if noise_shape is not None: + raise ValueError('noise_shape is not supported yet for RaggedTensor x') + with ops.name_scope(name, 'RaggedNNStatelessDropout', [x, rate]): + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, name='x') + return x.with_flat_values( + nn_ops.stateless_dropout( + x.flat_values, rate=rate, seed=seed, rng_alg=rng_alg)) + + +#=============================================================================== +# Ragged version of Tensor.__eq__ and Tensor.__ne__ +#=============================================================================== +@dispatch.dispatch_for_api(math_ops.tensor_equals) +def tensor_equals(self: ragged_tensor.RaggedOrDense, + other: ragged_tensor.RaggedOrDense): + """Ragged version of the operation invoked by `Tensor.__eq__`.""" + if other is None: + return False + elif _use_legacy_mode_for_tensor_equality(self): + return self is other + else: + try: + return math_ops.equal(self, other) + except (errors.InvalidArgumentError, ValueError): + return False # values are not broadcast-compatbile. + + +@dispatch.dispatch_for_api(math_ops.tensor_not_equals) +def tensor_not_equals(self: ragged_tensor.RaggedOrDense, + other: ragged_tensor.RaggedOrDense): + """Ragged version of the operation invoked by `Tensor.__ne__`.""" + if other is None: + return False + elif _use_legacy_mode_for_tensor_equality(self): + return self is not other + else: + try: + return math_ops.not_equal(self, other) + except (errors.InvalidArgumentError, ValueError): + return True # values are not broadcast-compatbile. + + +def _use_legacy_mode_for_tensor_equality(self): + g = getattr(self, 'graph', None) + return not (tensor.Tensor._USE_EQUALITY and # pylint: disable=protected-access + ops.executing_eagerly_outside_functions() and + (g is None or g.building_function)) + + +def _cumsum_flat_values_at_ragged_rank(last_rp, flat_values, exclusive=False, + reverse=False): + """Calculate flat_values for math_ops.cumsum when axis==ragged_rank.""" + if not exclusive: + partial = _cumsum_flat_values_at_ragged_rank( + last_rp, flat_values, exclusive=True, reverse=reverse) + return partial + flat_values + + if reverse: + youngest_sibling = array_ops.gather( + params=last_rp.row_splits(), indices=last_rp.value_rowids() + 1) - 1 + new_flat_values = math_ops.cumsum(flat_values, exclusive=True, reverse=True) + initial_values = array_ops.gather(params=new_flat_values, + indices=youngest_sibling) + + return new_flat_values - initial_values + else: + eldest_sibling = array_ops.gather( + params=last_rp.row_splits(), indices=last_rp.value_rowids()) + new_flat_values = math_ops.cumsum(flat_values, exclusive=True) + initial_values = array_ops.gather(params=new_flat_values, + indices=eldest_sibling) + return new_flat_values - initial_values + + +@dispatch.dispatch_for_api(math_ops.cumsum) +def ragged_cumsum(x: ragged_tensor.Ragged, + axis: int = 0, + exclusive: bool = False, + reverse: bool = False, + name: typing.Optional[str] = None): + """Calculate math_ops.cumsum for a RaggedTensor. + + Given a ragged tensor `x`, the `result` is a ragged tensor with the same + shape. One can calculate the value of `result[i_1...i_k]` as follows: + ``` + dense_result=tf.math.cumsum(rt.to_tensor(), axis=axis, exclusive=exclusive, + reverse=reverse) + result[i_1...i_k]=dense_result[i_1...i_k] + ``` + + Args: + x: the original ragged tensor to sum. + axis: the axis along which to sum, can range -rank<=axis x.ragged_rank: + new_axis = axis - x.ragged_rank + cumsum_bound = functools.partial( + math_ops.cumsum, axis=new_axis, exclusive=exclusive, reverse=reverse) + return ragged_functional_ops.map_flat_values(cumsum_bound, x) + else: + dense_version = x.to_tensor() + result = math_ops.cumsum( + dense_version, axis, exclusive=exclusive, reverse=reverse, name=name) + return ragged_tensor.RaggedTensor.from_tensor( + result, lengths=x.nested_row_lengths()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_operators.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..479442c3f4055a53045247a5a4ce9ef977a84b10 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_operators.py @@ -0,0 +1,342 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operator overloads for `RaggedTensor`.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_getitem +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import tf_decorator + + +# ============================================================================= +# Equality Docstring +# ============================================================================= +def ragged_eq(self, other): # pylint: disable=g-doc-args + """Returns result of elementwise `==` or False if not broadcast-compatible. + + Compares two ragged tensors elemewise for equality if they are + broadcast-compatible; or returns False if they are not + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html). + + Note that this behavior differs from `tf.math.equal`, which raises an + exception if the two ragged tensors are not broadcast-compatible. + + For example: + + >>> rt1 = tf.ragged.constant([[1, 2], [3]]) + >>> rt1 == rt1 + + + >>> rt2 = tf.ragged.constant([[1, 2], [4]]) + >>> rt1 == rt2 + + + >>> rt3 = tf.ragged.constant([[1, 2], [3, 4]]) + >>> # rt1 and rt3 are not broadcast-compatible. + >>> rt1 == rt3 + False + + >>> # You can also compare a `tf.RaggedTensor` to a `tf.Tensor`. + >>> t = tf.constant([[1, 2], [3, 4]]) + >>> rt1 == t + False + >>> t == rt1 + False + >>> rt4 = tf.ragged.constant([[1, 2], [3, 4]]) + >>> rt4 == t + + >>> t == rt4 + + + Args: + other: The right-hand side of the `==` operator. + + Returns: + The ragged tensor result of the elementwise `==` operation, or `False` if + the arguments are not broadcast-compatible. + """ + return math_ops.tensor_equals(self, other) + + +# ============================================================================= +# Ordering Docstring +# ============================================================================= +def ragged_ge(self, other): # pylint: disable=g-doc-args + """Elementwise `>=` comparison of two convertible-to-ragged-tensor values. + + Computes the elemewise `>=` comparison of two values that are convertible to + ragged tenors, with [broadcasting] + (http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) support. + Raises an exception if two values are not broadcast-compatible. + + For example: + + >>> rt1 = tf.ragged.constant([[1, 2], [3]]) + >>> rt1 >= rt1 + + + >>> rt2 = tf.ragged.constant([[2, 1], [3]]) + >>> rt1 >= rt2 + + + >>> rt3 = tf.ragged.constant([[1, 2], [3, 4]]) + >>> # rt1 and rt3 are not broadcast-compatible. + >>> rt1 >= rt3 + Traceback (most recent call last): + ... + InvalidArgumentError: ... + + >>> # You can also compare a `tf.RaggedTensor` to a `tf.Tensor`. + >>> rt4 = tf.ragged.constant([[1, 2],[3, 4]]) + >>> t1 = tf.constant([[2, 1], [4, 3]]) + >>> rt4 >= t1 + + >>> t1 >= rt4 + + + >>> # Compares a `tf.RaggedTensor` to a `tf.Tensor` with broadcasting. + >>> t2 = tf.constant([[2]]) + >>> rt4 >= t2 + + >>> t2 >= rt4 + + + Args: + other: The right-hand side of the `>=` operator. + + Returns: + A `tf.RaggedTensor` of dtype `tf.bool` with the shape that `self` and + `other` broadcast to. + + Raises: + InvalidArgumentError: If `self` and `other` are not broadcast-compatible. + """ + return math_ops.greater_equal(self, other) + + +# ============================================================================= +# Logical Docstring +# ============================================================================= + + +# ============================================================================= +# Arithmetic Docstring +# ============================================================================= +def ragged_abs(self, name=None): # pylint: disable=g-doc-args + r"""Computes the absolute value of a ragged tensor. + + Given a ragged tensor of integer or floating-point values, this operation + returns a ragged tensor of the same type, where each element contains the + absolute value of the corresponding element in the input. + + Given a ragged tensor `x` of complex numbers, this operation returns a tensor + of type `float32` or `float64` that is the absolute value of each element in + `x`. For a complex number \\(a + bj\\), its absolute value is computed as + \\(\sqrt{a^2 + b^2}\\). + + For example: + + >>> # real number + >>> x = tf.ragged.constant([[-2.2, 3.2], [-4.2]]) + >>> tf.abs(x) + + + >>> # complex number + >>> x = tf.ragged.constant([[-2.2 + 4.7j], [-3.2 + 5.7j], [-4.2 + 6.7j]]) + >>> tf.abs(x) + + + Args: + name: A name for the operation (optional). + + Returns: + A `RaggedTensor` of the same size and type as `x`, with absolute values. + Note, for `complex64` or `complex128` input, the returned `RaggedTensor` + will be of type `float32` or `float64`, respectively. + """ + return math_ops.abs(self, name=name) + + +# =========================================================================== +def ragged_and(self, y, name=None): # pylint: disable=g-doc-args + r"""Returns the truth value of elementwise `x & y`. + + Logical AND function. + + Requires that `x` and `y` have the same shape or have + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shapes. For example, `y` can be: + + - A single Python boolean, where the result will be calculated by applying + logical AND with the single element to each element in `x`. + - A `tf.Tensor` object of dtype `tf.bool` of the same shape or + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shape. In this case, the result will be the element-wise logical AND of + `x` and `y`. + - A `tf.RaggedTensor` object of dtype `tf.bool` of the same shape or + [broadcast-compatible](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) + shape. In this case, the result will be the element-wise logical AND of + `x` and `y`. + + For example: + + >>> # `y` is a Python boolean + >>> x = tf.ragged.constant([[True, False], [True]]) + >>> y = True + >>> x & y + + >>> tf.math.logical_and(x, y) # Equivalent of x & y + + >>> y & x + + >>> tf.math.reduce_all(x & y) # Reduce to a scalar bool Tensor. + + + >>> # `y` is a tf.Tensor of the same shape. + >>> x = tf.ragged.constant([[True, False], [True, False]]) + >>> y = tf.constant([[True, False], [False, True]]) + >>> x & y + + + >>> # `y` is a tf.Tensor of a broadcast-compatible shape. + >>> x = tf.ragged.constant([[True, False], [True]]) + >>> y = tf.constant([[True], [False]]) + >>> x & y + + + >>> # `y` is a `tf.RaggedTensor` of the same shape. + >>> x = tf.ragged.constant([[True, False], [True]]) + >>> y = tf.ragged.constant([[False, True], [True]]) + >>> x & y + + + >>> # `y` is a `tf.RaggedTensor` of a broadcast-compatible shape. + >>> x = tf.ragged.constant([[[True, True, False]], [[]], [[True, False]]]) + >>> y = tf.ragged.constant([[[True]], [[True]], [[False]]], ragged_rank=1) + >>> x & y + + + Args: + y: A Python boolean or a `tf.Tensor` or `tf.RaggedTensor` of dtype + `tf.bool`. + name: A name for the operation (optional). + + Returns: + A `tf.RaggedTensor` of dtype `tf.bool` with the shape that `x` and `y` + broadcast to. + """ + return math_ops.logical_and(self, y, name) + + +# Helper Methods. +def _right(operator): + """Right-handed version of an operator: swap args x and y.""" + return tf_decorator.make_decorator(operator, lambda y, x: operator(x, y)) + + +def ragged_hash(self): + """The operation invoked by the `RaggedTensor.__hash__` operator.""" + g = getattr(self.row_splits, "graph", None) + # pylint: disable=protected-access + if ( + tensor.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + and (g is None or g.building_function) + ): + raise TypeError("RaggedTensor is unhashable.") + else: + return id(self) + + +# Indexing +ragged_tensor.RaggedTensor.__getitem__ = ragged_getitem.ragged_tensor_getitem + +# Equality +ragged_tensor.RaggedTensor.__eq__ = ragged_eq +ragged_tensor.RaggedTensor.__ne__ = math_ops.tensor_not_equals +ragged_tensor.RaggedTensor.__hash__ = ragged_hash + +# Ordering operators +ragged_tensor.RaggedTensor.__ge__ = ragged_ge +ragged_tensor.RaggedTensor.__gt__ = math_ops.greater +ragged_tensor.RaggedTensor.__le__ = math_ops.less_equal +ragged_tensor.RaggedTensor.__lt__ = math_ops.less + +# Logical operators +ragged_tensor.RaggedTensor.__and__ = ragged_and +ragged_tensor.RaggedTensor.__rand__ = _right(ragged_and) + +ragged_tensor.RaggedTensor.__invert__ = math_ops.logical_not +ragged_tensor.RaggedTensor.__ror__ = _right(math_ops.logical_or) +ragged_tensor.RaggedTensor.__or__ = math_ops.logical_or +ragged_tensor.RaggedTensor.__xor__ = math_ops.logical_xor +ragged_tensor.RaggedTensor.__rxor__ = _right(math_ops.logical_xor) + +# Arithmetic operators +ragged_tensor.RaggedTensor.__abs__ = ragged_abs +ragged_tensor.RaggedTensor.__add__ = math_ops.add +ragged_tensor.RaggedTensor.__radd__ = _right(math_ops.add) +ragged_tensor.RaggedTensor.__div__ = math_ops.div +ragged_tensor.RaggedTensor.__rdiv__ = _right(math_ops.div) +ragged_tensor.RaggedTensor.__floordiv__ = math_ops.floordiv +ragged_tensor.RaggedTensor.__rfloordiv__ = _right(math_ops.floordiv) +ragged_tensor.RaggedTensor.__mod__ = math_ops.floormod +ragged_tensor.RaggedTensor.__rmod__ = _right(math_ops.floormod) +ragged_tensor.RaggedTensor.__mul__ = math_ops.multiply +ragged_tensor.RaggedTensor.__rmul__ = _right(math_ops.multiply) +ragged_tensor.RaggedTensor.__neg__ = math_ops.negative +ragged_tensor.RaggedTensor.__pow__ = math_ops.pow +ragged_tensor.RaggedTensor.__rpow__ = _right(math_ops.pow) +ragged_tensor.RaggedTensor.__sub__ = math_ops.subtract +ragged_tensor.RaggedTensor.__rsub__ = _right(math_ops.subtract) +ragged_tensor.RaggedTensor.__truediv__ = math_ops.truediv +ragged_tensor.RaggedTensor.__rtruediv__ = _right(math_ops.truediv) + + +def ragged_bool(self): # pylint: disable=g-doc-args + """Raises TypeError when a RaggedTensor is used as a Python bool. + + To prevent RaggedTensor from being used as a bool, this function always raise + TypeError when being called. + + For example: + + >>> x = tf.ragged.constant([[1, 2], [3]]) + >>> result = True if x else False # Evaluate x as a bool value. + Traceback (most recent call last): + ... + TypeError: RaggedTensor may not be used as a boolean. + + >>> x = tf.ragged.constant([[1]]) + >>> r = (x == 1) # tf.RaggedTensor [[True]] + >>> if r: # Evaluate r as a bool value. + ... pass + Traceback (most recent call last): + ... + TypeError: RaggedTensor may not be used as a boolean. + """ + raise TypeError("RaggedTensor may not be used as a boolean.") + + +ragged_tensor.RaggedTensor.__bool__ = ragged_bool # Python3 bool conversion. +ragged_tensor.RaggedTensor.__nonzero__ = ragged_bool # Python2 bool conversion. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0809d152bac3230f0bac37a0333cafde7130416e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_ops.py @@ -0,0 +1,51 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Import all modules in the `ragged` package that define exported symbols. + +Additional, import ragged_dispatch (which has the side-effect of registering +dispatch handlers for many standard TF ops) and ragged_operators (which has the +side-effect of overriding RaggedTensor operators, such as RaggedTensor.__add__). + +We don't import these modules from ragged/__init__.py, since we want to avoid +circular dependencies. +""" + + +# pylint: disable=unused-import +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_autograph +from tensorflow.python.ops.ragged import ragged_batch_gather_ops +from tensorflow.python.ops.ragged import ragged_batch_gather_with_default_op +from tensorflow.python.ops.ragged import ragged_bincount_ops +from tensorflow.python.ops.ragged import ragged_check_ops +from tensorflow.python.ops.ragged import ragged_concat_ops +from tensorflow.python.ops.ragged import ragged_conversion_ops +from tensorflow.python.ops.ragged import ragged_dispatch +from tensorflow.python.ops.ragged import ragged_embedding_ops +from tensorflow.python.ops.ragged import ragged_factory_ops +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_gather_ops +from tensorflow.python.ops.ragged import ragged_getitem +from tensorflow.python.ops.ragged import ragged_image_ops +from tensorflow.python.ops.ragged import ragged_map_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_operators +from tensorflow.python.ops.ragged import ragged_squeeze_op +from tensorflow.python.ops.ragged import ragged_string_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_shape +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.ops.ragged import ragged_where_op +from tensorflow.python.ops.ragged import segment_id_ops diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_squeeze_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_squeeze_op.py new file mode 100644 index 0000000000000000000000000000000000000000..6d35ffd493ecfb9823eaca70c349cc2b22a947b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_squeeze_op.py @@ -0,0 +1,133 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operator Squeeze for RaggedTensors.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged.ragged_tensor import RaggedTensor +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(array_ops.squeeze_v2) +def squeeze(input: ragged_tensor.Ragged, axis=None, name=None): # pylint: disable=redefined-builtin + """Ragged compatible squeeze. + + If `input` is a `tf.Tensor`, then this calls `tf.squeeze`. + + If `input` is a `tf.RaggedTensor`, then this operation takes `O(N)` time, + where `N` is the number of elements in the squeezed dimensions. + + Args: + input: A potentially ragged tensor. The input to squeeze. + axis: An optional list of ints. Defaults to `None`. If the `input` is + ragged, it only squeezes the dimensions listed. It fails if `input` is + ragged and axis is []. If `input` is not ragged it calls tf.squeeze. Note + that it is an error to squeeze a dimension that is not 1. It must be in + the range of [-rank(input), rank(input)). + name: A name for the operation (optional). + + Returns: + A potentially ragged tensor. Contains the same data as input, + but has one or more dimensions of size 1 removed. + """ + with ops.name_scope(name, 'RaggedSqueeze', [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor(input) + if isinstance(input, tensor.Tensor): + return array_ops.squeeze(input, axis, name) + + if axis is None: + raise ValueError('Ragged.squeeze must have an axis argument.') + if isinstance(axis, int): + axis = [axis] + elif ((not isinstance(axis, (list, tuple))) or + (not all(isinstance(d, int) for d in axis))): + raise TypeError('Axis must be a list or tuple of integers.') + + dense_dims = [] + ragged_dims = [] + # Normalize all the dims in axis to be positive + axis = [ + array_ops.get_positive_axis(d, input.shape.ndims, 'axis[%d]' % i, + 'rank(input)') for i, d in enumerate(axis) + ] + for dim in axis: + if dim > input.ragged_rank: + dense_dims.append(dim - input.ragged_rank) + else: + ragged_dims.append(dim) + + # Make sure the specified ragged dimensions are squeezable. + assertion_list = [] + scalar_tensor_one = constant_op.constant(1, dtype=input.row_splits.dtype) + for i, r in enumerate(input.nested_row_lengths()): + if i + 1 in ragged_dims: + assertion_list.append( + control_flow_assert.Assert( + math_ops.reduce_all(math_ops.equal(r, scalar_tensor_one)), + ['the given axis (axis = %d) is not squeezable!' % (i + 1)])) + if 0 in ragged_dims: + scalar_tensor_two = constant_op.constant(2, dtype=dtypes.int32) + assertion_list.append( + control_flow_assert.Assert( + math_ops.equal( + array_ops.size(input.row_splits), scalar_tensor_two), + ['the given axis (axis = 0) is not squeezable!'])) + + # Till now, we are sure that the ragged dimensions are squeezable. + squeezed_rt = None + squeezed_rt = control_flow_ops.with_dependencies(assertion_list, + input.flat_values) + + if dense_dims: + # Gives error if the dense dimension is not squeezable. + squeezed_rt = array_ops.squeeze(squeezed_rt, dense_dims) + + remaining_row_splits = [] + remaining_row_splits = list() + for i, row_split in enumerate(input.nested_row_splits): + # each row_splits tensor is for dimension #(i+1) . + if (i + 1) not in ragged_dims: + remaining_row_splits.append(row_split) + # Take care of the first row if it is to be squeezed. + if remaining_row_splits and 0 in ragged_dims: + remaining_row_splits.pop(0) + + squeezed_rt = RaggedTensor.from_nested_row_splits(squeezed_rt, + remaining_row_splits) + + # Corner case: when removing all the ragged dimensions and the output is + # a scalar tensor e.g. ragged.squeeze(ragged.constant([[[1]]])). + if set(range(0, input.ragged_rank + 1)).issubset(set(ragged_dims)): + squeezed_rt = array_ops.squeeze(squeezed_rt, [0], name) + + return squeezed_rt + + +@dispatch.dispatch_for_api(array_ops.squeeze) +def _ragged_squeeze_v1(input: ragged_tensor.Ragged, # pylint: disable=redefined-builtin + axis=None, + name=None, + squeeze_dims=None): + axis = deprecation.deprecated_argument_lookup('axis', axis, 'squeeze_dims', + squeeze_dims) + return squeeze(input, axis, name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_string_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_string_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..41f79781c7b4a8895d0ec050e7361edfb791371b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_string_ops.py @@ -0,0 +1,948 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ragged operations for working with string Tensors.""" + +import typing + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import gen_string_ops +from tensorflow.python.ops import map_fn as map_fn_lib +from tensorflow.python.ops import string_ops +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_math_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import compat as util_compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("strings.bytes_split") +@dispatch.add_dispatch_support +def string_bytes_split(input, name=None): # pylint: disable=redefined-builtin + """Split string elements of `input` into bytes. + + Examples: + + >>> tf.strings.bytes_split('hello').numpy() + array([b'h', b'e', b'l', b'l', b'o'], dtype=object) + >>> tf.strings.bytes_split(['hello', '123']) + + + Note that this op splits strings into bytes, not unicode characters. To + split strings into unicode characters, use `tf.strings.unicode_split`. + + See also: `tf.io.decode_raw`, `tf.strings.split`, `tf.strings.unicode_split`. + + Args: + input: A string `Tensor` or `RaggedTensor`: the strings to split. Must + have a statically known rank (`N`). + name: A name for the operation (optional). + + Returns: + A `RaggedTensor` of rank `N+1`: the bytes that make up the source strings. + """ + with ops.name_scope(name, "StringsByteSplit", [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor(input, + name="input") + if isinstance(input, ragged_tensor.RaggedTensor): + return input.with_flat_values(string_bytes_split(input.flat_values)) + + rank = input.shape.ndims + if rank is None: + raise ValueError("input must have a statically-known rank.") + + if rank == 0: + return string_bytes_split(array_ops_stack.stack([input]))[0] + elif rank == 1: + indices, values, shape = gen_string_ops.string_split( + input, delimiter="", skip_empty=False) + return ragged_tensor.RaggedTensor.from_value_rowids( + values=values, value_rowids=indices[:, 0], nrows=shape[0], + validate=False) + else: + return string_bytes_split(ragged_tensor.RaggedTensor.from_tensor(input)) + + +# pylint: disable=redefined-builtin +@tf_export("strings.unicode_encode") +@dispatch.add_dispatch_support +def unicode_encode(input, + output_encoding, + errors="replace", + replacement_char=65533, + name=None): + r"""Encodes each sequence of Unicode code points in `input` into a string. + + `result[i1...iN]` is the string formed by concatenating the Unicode + codepoints `input[1...iN, :]`, encoded using `output_encoding`. + + Args: + input: An `N+1` dimensional potentially ragged integer tensor with shape + `[D1...DN, num_chars]`. + output_encoding: Unicode encoding that should be used to encode each + codepoint sequence. Can be `"UTF-8"`, `"UTF-16-BE"`, or `"UTF-32-BE"`. + errors: Specifies the response when an invalid codepoint is encountered + (optional). One of: + * `'replace'`: Replace invalid codepoint with the + `replacement_char`. (default) + * `'ignore'`: Skip invalid codepoints. + * `'strict'`: Raise an exception for any invalid codepoint. + replacement_char: The replacement character codepoint to be used in place of + any invalid input when `errors='replace'`. Any valid unicode codepoint may + be used. The default value is the default unicode replacement character + which is 0xFFFD (U+65533). + name: A name for the operation (optional). + + Returns: + A `N` dimensional `string` tensor with shape `[D1...DN]`. + + #### Example: + + >>> input = tf.ragged.constant( + ... [[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]]) + >>> print(unicode_encode(input, 'UTF-8')) + tf.Tensor([b'G\xc3\xb6\xc3\xb6dnight' b'\xf0\x9f\x98\x8a'], + shape=(2,), dtype=string) + """ + with ops.name_scope(name, "UnicodeEncode", [input]): + input_tensor = ragged_tensor.convert_to_tensor_or_ragged_tensor(input) + if input_tensor.shape.ndims is None: + raise ValueError("Rank of input_tensor must be statically known.") + if ragged_tensor.is_ragged(input_tensor): + if input_tensor.flat_values.shape.ndims > 1: + # If the flat_values of our ragged tensor is multi-dimensional, we can + # process it separately and our output will have the same nested splits + # as our input. + return input_tensor.with_flat_values( + unicode_encode(input_tensor.flat_values, output_encoding, errors, + replacement_char)) + elif input_tensor.ragged_rank > 1: + # Recursively process the values of the ragged tensor. + return input_tensor.with_values( + unicode_encode(input_tensor.values, output_encoding, errors, + replacement_char)) + else: + # Our ragged tensor is of the correct shape (rank 1 flat_values tensor + # with ragged_rank of 1) so we can process it as normal. + return gen_string_ops.unicode_encode( + input_values=input_tensor.values, + input_splits=input_tensor.row_splits, + output_encoding=output_encoding, + errors=errors, + replacement_char=replacement_char) + else: + if input_tensor.shape.ndims == 2: + # The input tensor is of the correct 2-D shape, it's just not ragged. + return unicode_encode( + ragged_tensor.RaggedTensor.from_tensor(input_tensor), + output_encoding, errors, replacement_char) + elif input_tensor.shape.ndims > 2: + # We need to initially flatten the input tensor to 2-D, and then can + # reshape the output of our processed flattened tensor. + flat_input_tensor = array_ops.reshape( + input_tensor, + array_ops_stack.stack([-1, array_ops.shape(input_tensor)[-1]])) + flat_output_tensor = unicode_encode(flat_input_tensor, output_encoding, + errors, replacement_char) + return array_ops.reshape(flat_output_tensor, input_tensor.shape[:-1]) + elif input_tensor.shape.ndims == 0: + raise ValueError("input_tensor's rank must be at least 1.") + else: + # Our input tensor is rank 1, so we create a ragged tensor with an added + # dimension to create the correct input shape & type, and then remove + # the additional dimension from the output and return the string scalar. + ragged_input_tensor = ragged_tensor.RaggedTensor.from_row_splits( + input_tensor, + array_ops_stack.stack( + [0, array_ops.shape(input_tensor, out_type=dtypes.int32)[0]]), + validate=False) + output_tensor = unicode_encode(ragged_input_tensor, output_encoding, + errors, replacement_char) + return array_ops.reshape(output_tensor, []) + + +# pylint: disable=redefined-builtin +@tf_export("strings.unicode_decode") +@dispatch.add_dispatch_support +def unicode_decode(input, + input_encoding, + errors="replace", + replacement_char=0xFFFD, + replace_control_characters=False, + name=None): + r"""Decodes each string in `input` into a sequence of Unicode code points. + + `result[i1...iN, j]` is the Unicode codepoint for the `j`th character in + `input[i1...iN]`, when decoded using `input_encoding`. + + Args: + input: An `N` dimensional potentially ragged `string` tensor with shape + `[D1...DN]`. `N` must be statically known. + input_encoding: String name for the unicode encoding that should be used to + decode each string. + errors: Specifies the response when an input string can't be converted + using the indicated encoding. One of: + * `'strict'`: Raise an exception for any illegal substrings. + * `'replace'`: Replace illegal substrings with `replacement_char`. + * `'ignore'`: Skip illegal substrings. + replacement_char: The replacement codepoint to be used in place of invalid + substrings in `input` when `errors='replace'`; and in place of C0 control + characters in `input` when `replace_control_characters=True`. + replace_control_characters: Whether to replace the C0 control characters + `(U+0000 - U+001F)` with the `replacement_char`. + name: A name for the operation (optional). + + Returns: + A `N+1` dimensional `int32` tensor with shape `[D1...DN, (num_chars)]`. + The returned tensor is a `tf.Tensor` if `input` is a scalar, or a + `tf.RaggedTensor` otherwise. + + #### Example: + + >>> input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')] + >>> tf.strings.unicode_decode(input, 'UTF-8').to_list() + [[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]] + """ + with ops.name_scope(name, "UnicodeDecode", [input]): + return _unicode_decode(input, input_encoding, errors, replacement_char, + replace_control_characters, with_offsets=False) + + +@tf_export("strings.unicode_decode_with_offsets") +@dispatch.add_dispatch_support +def unicode_decode_with_offsets(input, + input_encoding, + errors="replace", + replacement_char=0xFFFD, + replace_control_characters=False, + name=None): + r"""Decodes each string into a sequence of code points with start offsets. + + This op is similar to `tf.strings.decode(...)`, but it also returns the + start offset for each character in its respective string. This information + can be used to align the characters with the original byte sequence. + + Returns a tuple `(codepoints, start_offsets)` where: + + * `codepoints[i1...iN, j]` is the Unicode codepoint for the `j`th character + in `input[i1...iN]`, when decoded using `input_encoding`. + * `start_offsets[i1...iN, j]` is the start byte offset for the `j`th + character in `input[i1...iN]`, when decoded using `input_encoding`. + + Args: + input: An `N` dimensional potentially ragged `string` tensor with shape + `[D1...DN]`. `N` must be statically known. + input_encoding: String name for the unicode encoding that should be used to + decode each string. + errors: Specifies the response when an input string can't be converted + using the indicated encoding. One of: + * `'strict'`: Raise an exception for any illegal substrings. + * `'replace'`: Replace illegal substrings with `replacement_char`. + * `'ignore'`: Skip illegal substrings. + replacement_char: The replacement codepoint to be used in place of invalid + substrings in `input` when `errors='replace'`; and in place of C0 control + characters in `input` when `replace_control_characters=True`. + replace_control_characters: Whether to replace the C0 control characters + `(U+0000 - U+001F)` with the `replacement_char`. + name: A name for the operation (optional). + + Returns: + A tuple of `N+1` dimensional tensors `(codepoints, start_offsets)`. + + * `codepoints` is an `int32` tensor with shape `[D1...DN, (num_chars)]`. + * `offsets` is an `int64` tensor with shape `[D1...DN, (num_chars)]`. + + The returned tensors are `tf.Tensor`s if `input` is a scalar, or + `tf.RaggedTensor`s otherwise. + + #### Example: + + >>> input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')] + >>> result = tf.strings.unicode_decode_with_offsets(input, 'UTF-8') + >>> result[0].to_list() # codepoints + [[71, 246, 246, 100, 110, 105, 103, 104, 116], [128522]] + >>> result[1].to_list() # offsets + [[0, 1, 3, 5, 6, 7, 8, 9, 10], [0]] + + """ + with ops.name_scope(name, "UnicodeDecodeWithOffsets", [input]): + return _unicode_decode(input, input_encoding, errors, replacement_char, + replace_control_characters, with_offsets=True) + + +@tf_export("strings.unicode_split") +@dispatch.add_dispatch_support +def unicode_split(input, + input_encoding, + errors="replace", + replacement_char=0xFFFD, + name=None): + r"""Splits each string in `input` into a sequence of Unicode code points. + + `result[i1...iN, j]` is the substring of `input[i1...iN]` that encodes its + `j`th character, when decoded using `input_encoding`. + + Args: + input: An `N` dimensional potentially ragged `string` tensor with shape + `[D1...DN]`. `N` must be statically known. + input_encoding: String name for the unicode encoding that should be used to + decode each string. + errors: Specifies the response when an input string can't be converted + using the indicated encoding. One of: + * `'strict'`: Raise an exception for any illegal substrings. + * `'replace'`: Replace illegal substrings with `replacement_char`. + * `'ignore'`: Skip illegal substrings. + replacement_char: The replacement codepoint to be used in place of invalid + substrings in `input` when `errors='replace'`. + name: A name for the operation (optional). + + Returns: + A `N+1` dimensional `int32` tensor with shape `[D1...DN, (num_chars)]`. + The returned tensor is a `tf.Tensor` if `input` is a scalar, or a + `tf.RaggedTensor` otherwise. + + #### Example: + + >>> input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')] + >>> tf.strings.unicode_split(input, 'UTF-8').to_list() + [[b'G', b'\xc3\xb6', b'\xc3\xb6', b'd', b'n', b'i', b'g', b'h', b't'], + [b'\xf0\x9f\x98\x8a']] + """ + with ops.name_scope(name, "UnicodeSplit", [input]): + codepoints = _unicode_decode(input, input_encoding, errors, + replacement_char, False, with_offsets=False) + return unicode_encode( + ragged_array_ops.expand_dims(codepoints, -1), + output_encoding=input_encoding, + errors=errors, + replacement_char=replacement_char) + + +@tf_export("strings.unicode_split_with_offsets") +@dispatch.add_dispatch_support +def unicode_split_with_offsets(input, + input_encoding, + errors="replace", + replacement_char=0xFFFD, + name=None): + r"""Splits each string into a sequence of code points with start offsets. + + This op is similar to `tf.strings.decode(...)`, but it also returns the + start offset for each character in its respective string. This information + can be used to align the characters with the original byte sequence. + + Returns a tuple `(chars, start_offsets)` where: + + * `chars[i1...iN, j]` is the substring of `input[i1...iN]` that encodes its + `j`th character, when decoded using `input_encoding`. + * `start_offsets[i1...iN, j]` is the start byte offset for the `j`th + character in `input[i1...iN]`, when decoded using `input_encoding`. + + Args: + input: An `N` dimensional potentially ragged `string` tensor with shape + `[D1...DN]`. `N` must be statically known. + input_encoding: String name for the unicode encoding that should be used to + decode each string. + errors: Specifies the response when an input string can't be converted + using the indicated encoding. One of: + * `'strict'`: Raise an exception for any illegal substrings. + * `'replace'`: Replace illegal substrings with `replacement_char`. + * `'ignore'`: Skip illegal substrings. + replacement_char: The replacement codepoint to be used in place of invalid + substrings in `input` when `errors='replace'`. + name: A name for the operation (optional). + + Returns: + A tuple of `N+1` dimensional tensors `(codepoints, start_offsets)`. + + * `codepoints` is an `int32` tensor with shape `[D1...DN, (num_chars)]`. + * `offsets` is an `int64` tensor with shape `[D1...DN, (num_chars)]`. + + The returned tensors are `tf.Tensor`s if `input` is a scalar, or + `tf.RaggedTensor`s otherwise. + + #### Example: + + >>> input = [s.encode('utf8') for s in (u'G\xf6\xf6dnight', u'\U0001f60a')] + >>> result = tf.strings.unicode_split_with_offsets(input, 'UTF-8') + >>> result[0].to_list() # character substrings + [[b'G', b'\xc3\xb6', b'\xc3\xb6', b'd', b'n', b'i', b'g', b'h', b't'], + [b'\xf0\x9f\x98\x8a']] + >>> result[1].to_list() # offsets + [[0, 1, 3, 5, 6, 7, 8, 9, 10], [0]] + + """ + with ops.name_scope(name, "UnicodeSplitWithOffsets", [input]): + codepoints, offsets = _unicode_decode(input, input_encoding, errors, + replacement_char, False, + with_offsets=True) + chars = unicode_encode( + ragged_array_ops.expand_dims(codepoints, -1), + output_encoding=input_encoding, + errors=errors, + replacement_char=replacement_char) + return chars, offsets + + +def _unicode_decode(input, input_encoding, errors, replacement_char, + replace_control_characters, with_offsets): + """Decodes each string into a sequence of codepoints.""" + input = ragged_tensor.convert_to_tensor_or_ragged_tensor(input, name="input") + input_ndims = input.shape.ndims + if input_ndims is None: + raise ValueError("Rank of `input` must be statically known.") + + if input_ndims > 1: + # Convert to a ragged tensor with ragged_rank = input_ndims - 1. + if not ragged_tensor.is_ragged(input): + input = ragged_tensor.RaggedTensor.from_tensor( + input, ragged_rank=input_ndims - 1) + elif input.ragged_rank < input_ndims - 1: + input = input.with_flat_values( + ragged_tensor.RaggedTensor.from_tensor( + input.flat_values, + ragged_rank=input_ndims - input.ragged_rank - 1)) + + # Reshape the input to a flat vector, and apply the gen_string_ops op. + if ragged_tensor.is_ragged(input): + flat_input = array_ops.reshape(input.flat_values, [-1]) + else: + flat_input = array_ops.reshape(input, [-1]) + + if with_offsets: + decode_op = gen_string_ops.unicode_decode_with_offsets + else: + decode_op = gen_string_ops.unicode_decode + flat_result = decode_op( + input=flat_input, + input_encoding=input_encoding, + errors=errors, + replacement_char=replacement_char, + replace_control_characters=replace_control_characters) + + if input_ndims == 0: + codepoints = flat_result.char_values + if with_offsets: + offsets = flat_result.char_to_byte_starts + else: + codepoints = ragged_tensor.RaggedTensor.from_row_splits( + flat_result.char_values, flat_result.row_splits, validate=False) + if input_ndims > 1: + codepoints = input.with_flat_values(codepoints) + if with_offsets: + offsets = ragged_tensor.RaggedTensor.from_row_splits( + flat_result.char_to_byte_starts, flat_result.row_splits, + validate=False) + if input_ndims > 1: + offsets = input.with_flat_values(offsets) + + if with_offsets: + return codepoints, offsets + else: + return codepoints + + +@tf_export("strings.split", v1=[]) +@dispatch.add_dispatch_support +def string_split_v2(input, sep=None, maxsplit=-1, name=None): # pylint: disable=redefined-builtin + """Split elements of `input` based on `sep` into a `RaggedTensor`. + + Let N be the size of `input` (typically N will be the batch size). Split each + element of `input` based on `sep` and return a `RaggedTensor` containing the + split tokens. Empty tokens are ignored. + + Example: + + >>> tf.strings.split('hello world').numpy() + array([b'hello', b'world'], dtype=object) + >>> tf.strings.split(['hello world', 'a b c']) + + + If `sep` is given, consecutive delimiters are not grouped together and are + deemed to delimit empty strings. For example, `input` of `"1<>2<><>3"` and + `sep` of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty + string, consecutive whitespace are regarded as a single separator, and the + result will contain no empty strings at the start or end if the string has + leading or trailing whitespace. + + Note that the above mentioned behavior matches python's str.split. + + Args: + input: A string `Tensor` of rank `N`, the strings to split. If + `rank(input)` is not known statically, then it is assumed to be `1`. + sep: `0-D` string `Tensor`, the delimiter string. + maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result. + name: A name for the operation (optional). + + Raises: + ValueError: If sep is not a string. + + Returns: + A `RaggedTensor` of rank `N+1`, the strings split according to the + delimiter. + """ + with ops.name_scope(name, "StringSplit", [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input, dtype=dtypes.string, name="input") + if isinstance(input, ragged_tensor.RaggedTensor): + return input.with_flat_values( + string_split_v2(input.flat_values, sep, maxsplit)) + + rank = input.shape.ndims + if rank == 0: + return string_split_v2(array_ops_stack.stack([input]), sep, maxsplit)[0] + elif rank == 1 or rank is None: + sparse_result = string_ops.string_split_v2( + input, sep=sep, maxsplit=maxsplit) + return ragged_tensor.RaggedTensor.from_value_rowids( + values=sparse_result.values, + value_rowids=sparse_result.indices[:, 0], + nrows=sparse_result.dense_shape[0], + validate=False) + else: + return string_split_v2( + ragged_tensor.RaggedTensor.from_tensor(input), sep, maxsplit) + + +@tf_export(v1=["string_split"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "delimiter is deprecated, please use sep instead.", + "delimiter") +def string_split(source, sep=None, skip_empty=True, delimiter=None, + result_type="SparseTensor", name=None): # pylint: disable=invalid-name + """Split elements of `source` based on `delimiter`. + + Let N be the size of `source` (typically N will be the batch size). Split each + element of `source` based on `delimiter` and return a `SparseTensor` + or `RaggedTensor` containing the split tokens. Empty tokens are ignored. + + If `sep` is an empty string, each element of the `source` is split + into individual strings, each containing one byte. (This includes splitting + multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is + treated as a set of delimiters with each considered a potential split point. + + Examples: + + >>> print(tf.compat.v1.string_split(['hello world', 'a b c'])) + SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...), + values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...), + dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64)) + + >>> print(tf.compat.v1.string_split(['hello world', 'a b c'], + ... result_type="RaggedTensor")) + + + Args: + source: `1-D` string `Tensor`, the strings to split. + sep: `0-D` string `Tensor`, the delimiter character, the string should + be length 0 or 1. Default is ' '. + skip_empty: A `bool`. If `True`, skip the empty strings from the result. + delimiter: deprecated alias for `sep`. + result_type: The tensor type for the result: one of `"RaggedTensor"` or + `"SparseTensor"`. + name: A name for the operation (optional). + + Raises: + ValueError: If delimiter is not a string. + + Returns: + A `SparseTensor` or `RaggedTensor` of rank `2`, the strings split according + to the delimiter. The first column of the indices corresponds to the row + in `source` and the second column corresponds to the index of the split + component in this row. + """ + with ops.name_scope(name, "StringSplit", [source]): + sparse_result = string_ops.string_split( + source, sep=sep, skip_empty=skip_empty, delimiter=delimiter) + if result_type == "SparseTensor": + return sparse_result + elif result_type == "RaggedTensor": + return ragged_tensor.RaggedTensor.from_value_rowids( + values=sparse_result.values, + value_rowids=sparse_result.indices[:, 0], + nrows=sparse_result.dense_shape[0], + validate=False) + else: + raise ValueError("result_type must be 'RaggedTensor' or 'SparseTensor'.") + + +# In TensorFlow 1.x, "tf.strings.split" uses the new signature (with maxsplit), +# but we need to add the result_type argument. +@tf_export(v1=["strings.split"]) +@dispatch.add_dispatch_support +def strings_split_v1(input=None, sep=None, maxsplit=-1, # pylint: disable=redefined-builtin + result_type="SparseTensor", source=None, name=None): + """Split elements of `input` based on `sep`. + + Let N be the size of `input` (typically N will be the batch size). Split each + element of `input` based on `sep` and return a `SparseTensor` or + `RaggedTensor` containing the split tokens. Empty tokens are ignored. + + Examples: + + >>> print(tf.compat.v1.strings.split(['hello world', 'a b c'])) + SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...), + values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...), + dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64)) + + >>> print(tf.compat.v1.strings.split(['hello world', 'a b c'], + ... result_type="RaggedTensor")) + + + If `sep` is given, consecutive delimiters are not grouped together and are + deemed to delimit empty strings. For example, `input` of `"1<>2<><>3"` and + `sep` of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty + string, consecutive whitespace are regarded as a single separator, and the + result will contain no empty strings at the start or end if the string has + leading or trailing whitespace. + + Note that the above mentioned behavior matches python's str.split. + + Args: + input: A string `Tensor` of rank `N`, the strings to split. If + `rank(input)` is not known statically, then it is assumed to be `1`. + sep: `0-D` string `Tensor`, the delimiter character. + maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result. + result_type: The tensor type for the result: one of `"RaggedTensor"` or + `"SparseTensor"`. + source: alias for "input" argument. + name: A name for the operation (optional). + + Raises: + ValueError: If sep is not a string. + + Returns: + A `SparseTensor` or `RaggedTensor` of rank `N+1`, the strings split + according to the delimiter. + """ + input = deprecation.deprecated_argument_lookup( + "input", input, "source", source) + with ops.name_scope(name, "StringSplit", [input]): + input = ragged_tensor.convert_to_tensor_or_ragged_tensor( + input, dtype=dtypes.string, name="input") + + if input.shape.rank == 0: + input = array_ops.expand_dims(input, 0) + + if result_type == "SparseTensor": + if input.shape.rank == 1: + return string_ops.string_split_v2(input, sep=sep, maxsplit=maxsplit) + else: + return string_split_v2(input, sep=sep, maxsplit=maxsplit).to_sparse() + elif result_type == "RaggedTensor": + return string_split_v2(input, sep=sep, maxsplit=maxsplit) + else: + raise ValueError("result_type must be 'RaggedTensor' or 'SparseTensor'.") + + +@dispatch.dispatch_for_api(string_ops.reduce_join_v2) +def reduce_join(inputs: ragged_tensor.Ragged, + axis=None, + keepdims=None, + separator="", + name=None): + """For docs, see: _RAGGED_REDUCE_DOCSTRING.""" + return ragged_math_ops.ragged_reduce_aggregate( + string_ops.reduce_join, string_ops.unsorted_segment_join, inputs, axis, + keepdims, separator, name or "RaggedSegmentJoin") + + +@tf_export("strings.ngrams") +@dispatch.add_dispatch_support +def ngrams(data, + ngram_width, + separator=" ", + pad_values=None, + padding_width=None, + preserve_short_sequences=False, + name=None): + """Create a tensor of n-grams based on `data`. + + Creates a tensor of n-grams based on `data`. The n-grams are created by + joining windows of `width` adjacent strings from the inner axis of `data` + using `separator`. + + The input data can be padded on both the start and end of the sequence, if + desired, using the `pad_values` argument. If set, `pad_values` should contain + either a tuple of strings or a single string; the 0th element of the tuple + will be used to pad the left side of the sequence and the 1st element of the + tuple will be used to pad the right side of the sequence. The `padding_width` + arg controls how many padding values are added to each side; it defaults to + `ngram_width-1`. + + If this op is configured to not have padding, or if it is configured to add + padding with `padding_width` set to less than ngram_width-1, it is possible + that a sequence, or a sequence plus padding, is smaller than the ngram + width. In that case, no ngrams will be generated for that sequence. This can + be prevented by setting `preserve_short_sequences`, which will cause the op + to always generate at least one ngram per non-empty sequence. + + Examples: + + >>> tf.strings.ngrams(["A", "B", "C", "D"], 2).numpy() + array([b'A B', b'B C', b'C D'], dtype=object) + >>> tf.strings.ngrams(["TF", "and", "keras"], 1).numpy() + array([b'TF', b'and', b'keras'], dtype=object) + + Args: + data: A Tensor or RaggedTensor containing the source data for the ngrams. + ngram_width: The width(s) of the ngrams to create. If this is a list or + tuple, the op will return ngrams of all specified arities in list order. + Values must be non-Tensor integers greater than 0. + separator: The separator string used between ngram elements. Must be a + string constant, not a Tensor. + pad_values: A tuple of (left_pad_value, right_pad_value), a single string, + or None. If None, no padding will be added; if a single string, then that + string will be used for both left and right padding. Values must be Python + strings. + padding_width: If set, `padding_width` pad values will be added to both + sides of each sequence. Defaults to `ngram_width`-1. Must be greater than + 0. (Note that 1-grams are never padded, regardless of this value.) + preserve_short_sequences: If true, then ensure that at least one ngram is + generated for each input sequence. In particular, if an input sequence is + shorter than `min(ngram_width) + 2*pad_width`, then generate a single + ngram containing the entire sequence. If false, then no ngrams are + generated for these short input sequences. + name: The op name. + + Returns: + A RaggedTensor of ngrams. If `data.shape=[D1...DN, S]`, then + `output.shape=[D1...DN, NUM_NGRAMS]`, where + `NUM_NGRAMS=S-ngram_width+1+2*padding_width`. + + Raises: + TypeError: if `pad_values` is set to an invalid type. + ValueError: if `pad_values`, `padding_width`, or `ngram_width` is set to an + invalid value. + """ + + with ops.name_scope(name, "StringNGrams", [data]): + if pad_values is None: + left_pad = "" + right_pad = "" + elif isinstance(pad_values, (list, tuple)): + if (not isinstance(pad_values[0], util_compat.bytes_or_text_types) or + not isinstance(pad_values[1], util_compat.bytes_or_text_types)): + raise TypeError( + "pad_values must be a string, tuple of strings, or None.") + left_pad = pad_values[0] + right_pad = pad_values[1] + else: + if not isinstance(pad_values, util_compat.bytes_or_text_types): + raise TypeError( + "pad_values must be a string, tuple of strings, or None.") + left_pad = pad_values + right_pad = pad_values + + if padding_width is not None and padding_width < 1: + raise ValueError("padding_width must be greater than 0.") + + if padding_width is not None and pad_values is None: + raise ValueError("pad_values must be provided if padding_width is set.") + + data = ragged_tensor.convert_to_tensor_or_ragged_tensor( + data, name="data", dtype=dtypes.string) + + # preserve the shape of the data if it is a tensor + to_tensor = False + if isinstance(data, tensor_lib.Tensor): + dense_shape = array_ops.concat([array_ops.shape(data)[:-1], [-1]], axis=0) + to_tensor = True + + if not isinstance(data, ragged_tensor.RaggedTensor): + if data.shape.ndims is None: + raise ValueError("Rank of data must be known.") + elif data.shape.ndims == 0: + raise ValueError("Data must have rank>0") + elif data.shape.ndims == 1: + rt = ragged_tensor.RaggedTensor.from_row_starts( + data, [0], validate=False) + return ngrams(rt, ngram_width, separator, pad_values, padding_width, + preserve_short_sequences, name)[0] + else: + data = ragged_tensor.RaggedTensor.from_tensor( + data, ragged_rank=data.shape.ndims - 1) + + if data.ragged_rank > 1: + output = data.with_values( + ngrams(data.values, ngram_width, separator, pad_values, padding_width, + preserve_short_sequences, name)) + return array_ops.reshape(output.flat_values, + dense_shape) if to_tensor else output + + if pad_values is None: + padding_width = 0 + + if pad_values is not None and padding_width is None: + padding_width = -1 + + if not isinstance(ngram_width, (list, tuple)): + ngram_widths = [ngram_width] + else: + ngram_widths = ngram_width + for width in ngram_widths: + if width < 1: + raise ValueError("All ngram_widths must be greater than 0. Got %s" % + ngram_width) + + output, output_splits = gen_string_ops.string_n_grams( + data=data.flat_values, + data_splits=data.row_splits, + separator=separator, + ngram_widths=ngram_widths, + left_pad=left_pad, + right_pad=right_pad, + pad_width=padding_width, + preserve_short_sequences=preserve_short_sequences) + + # if the input is Dense tensor, the output should also be a dense tensor + output = ragged_tensor.RaggedTensor.from_row_splits( + values=output, row_splits=output_splits, validate=False) + return array_ops.reshape(output.flat_values, + dense_shape) if to_tensor else output + + +@dispatch.dispatch_for_api(string_ops.string_format) +def string_format( + template: str, + inputs: typing.Union[ragged_tensor.Ragged, + typing.List[ragged_tensor.RaggedOrDense]], + placeholder="{}", + summarize=3, + name=None): + """Version of tf.strings.format that handles RaggedTensors.""" + if tensor_util.is_tf_type(inputs) or ragged_tensor.is_ragged(inputs): + inputs = [inputs] + + split_template = template.split(placeholder) + if len(inputs) != len(split_template) - 1: + raise ValueError("num placeholders in template and num inputs must match" + ": {} vs {}".format(len(split_template) - 1, len(inputs))) + + with ops.name_scope(name, "StringFormat", [inputs]): + output_pieces = [constant_op.constant(split_template[0])] + for i, input in enumerate(inputs): + if ragged_tensor.is_ragged(input): + output_pieces.append(ragged_tensor_to_string(input, summarize)) + else: + output_pieces.append(string_ops.string_format( + "{}", [input], summarize=summarize)) + output_pieces.append(constant_op.constant(split_template[i + 1])) + if len(output_pieces) == 1: + return output_pieces[0] + else: + return string_ops.reduce_join(output_pieces) + + +def ragged_tensor_to_string(rt, summarize=None): + """Returns a scalar string tensor with the contents of a RaggedTensor. + + Requires that `rt.shape.rank` is not `None`. + + Note: this converts the entire `RaggedTensor` into a single string scalar. + If you want to convert individual elements, use `tf.strings.as_string(rt)`. + + >>> rt1 = tf.ragged.constant([[1, 2, 3], [4, 5]]) + >>> ragged_tensor_to_string(rt1).numpy() + b'[[1, 2, 3], [4, 5]]' + + >>> rt2 = tf.ragged.constant([[['a'], ['b', 'c']], [['d', 'e', 'f'], []]]) + >>> ragged_tensor_to_string(rt2).numpy() + b"[[['a'], ['b', 'c']], [['d', 'e', 'f'], []]]" + + >>> rt3 = tf.ragged.constant([[1], [2, 3, 4, 5, 6], [], [], [7], [8, 9]]) + >>> ragged_tensor_to_string(rt3, summarize=2).numpy() + b'[[1], [2, 3, ..., 5, 6], ..., [7], [8, 9]]' + + Args: + rt: The RaggedTensor that should be converted to a string. + summarize: If specified, then only the first and last `summarize` elements + within each dimension are included in the string. If `-1` or `None`, then + all elements are included. + """ + if (summarize is not None and summarize != -1 and + not (isinstance(summarize, int) and summarize > 0)): + raise ValueError("Expected summarize to be -1 or a positive int, got %r" % + summarize) + with ops.name_scope(None, "AsString", [rt]): + rt = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt) + if rt.shape.rank is None: + raise ValueError("RaggedTensor to_string requires that rt.shape.rank " + "is not None.") + # Convert all elements of `rt` to strings. + if rt.dtype == dtypes.string: + escaped = string_ops.regex_replace(rt.flat_values, r"(['\\])", r"\\\1") + str_t = rt.with_flat_values("'" + escaped + "'") + else: + str_t = rt.with_flat_values(string_ops.as_string(rt.flat_values)) + + return _ragged_tensor_to_string(str_t, summarize) + + +def _ragged_tensor_to_string(string_tensor, summarize): + """Returns a scalar string tensor with the contents of `string_tensor`. + + Args: + string_tensor: A potentially ragged tensor with dtype=string. + summarize: Include only the first and last `summarize` elements of each + dimension. If `-1` or `None`, then include all elements. + + Returns: + A scalar string Tensor. + """ + if string_tensor.shape.rank == 1: + pieces = string_tensor + else: + pieces = map_fn_lib.map_fn( + lambda s: _ragged_tensor_to_string(s, summarize), + string_tensor, + fn_output_signature=tensor_lib.TensorSpec(None, dtypes.string)) + if summarize not in (-1, None): + pieces = cond.cond( + _nrows(string_tensor) <= 2 * summarize, + lambda: pieces, + lambda: array_ops.concat( # pylint: disable=g-long-lambda + [pieces[:summarize], ["..."], pieces[-summarize:]], + axis=0)) + return "[" + string_ops.reduce_join(pieces, separator=", ") + "]" + + +def _nrows(tensor, out_type=dtypes.int32): + if isinstance(tensor, ragged_tensor.RaggedTensor): + return tensor.nrows(out_type=out_type) + else: + return array_ops.shape(tensor, out_type=out_type)[0] + + +@dispatch.dispatch_for_api(string_ops.string_join) +def string_join(inputs: typing.List[ragged_tensor.RaggedOrDense], + separator="", + name=None): + """RaggedTensor implementation for tf.strings.join.""" + if len(inputs) < 0: + raise ValueError("tf.strings.join: expected at least one input.") + with ops.name_scope(name, "RaggedStringJoin", inputs): + return ragged_functional_ops.map_flat_values(string_ops.string_join, inputs, + separator) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..a92d425a4c748eab10ff468a432272912a0689b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor.py @@ -0,0 +1,3149 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Classes for storing ragged tensors and their values.""" + +import functools +import operator + +import typing +import numpy as np + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import tf2 +from tensorflow.python.client import session +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import gen_ragged_conversion_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_config +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.ops.ragged import ragged_util +from tensorflow.python.ops.ragged.row_partition import RowPartition +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import core as core_types +from tensorflow.python.types import internal as internal_types +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +# pylint: disable=protected-access +_convert_row_partition = RowPartition._convert_row_partition +# pylint: enable=protected-access + +# =============================================================================== +# RaggedTensor +# =============================================================================== + + +@tf_export("RaggedTensor") +class RaggedTensor( + composite_tensor.CompositeTensor, + internal_types.NativeObject, + internal_types.RaggedTensor, +): + """Represents a ragged tensor. + + A `RaggedTensor` is a tensor with one or more *ragged dimensions*, which are + dimensions whose slices may have different lengths. For example, the inner + (column) dimension of `rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, + since the column slices (`rt[0, :]`, ..., `rt[4, :]`) have different lengths. + Dimensions whose slices all have the same length are called *uniform + dimensions*. The outermost dimension of a `RaggedTensor` is always uniform, + since it consists of a single slice (and so there is no possibility for + differing slice lengths). + + The total number of dimensions in a `RaggedTensor` is called its *rank*, + and the number of ragged dimensions in a `RaggedTensor` is called its + *ragged-rank*. A `RaggedTensor`'s ragged-rank is fixed at graph creation + time: it can't depend on the runtime values of `Tensor`s, and can't vary + dynamically for different session runs. + + Note that the `__init__` constructor is private. Please use one of the + following methods to construct a `RaggedTensor`: + + * `tf.RaggedTensor.from_row_lengths` + * `tf.RaggedTensor.from_value_rowids` + * `tf.RaggedTensor.from_row_splits` + * `tf.RaggedTensor.from_row_starts` + * `tf.RaggedTensor.from_row_limits` + * `tf.RaggedTensor.from_nested_row_splits` + * `tf.RaggedTensor.from_nested_row_lengths` + * `tf.RaggedTensor.from_nested_value_rowids` + + ### Potentially Ragged Tensors + + Many ops support both `Tensor`s and `RaggedTensor`s + (see [tf.ragged](https://www.tensorflow.org/api_docs/python/tf/ragged) for a + full listing). The term "potentially ragged tensor" may be used to refer to a + tensor that might be either a `Tensor` or a `RaggedTensor`. The ragged-rank + of a `Tensor` is zero. + + ### Documenting RaggedTensor Shapes + + When documenting the shape of a RaggedTensor, ragged dimensions can be + indicated by enclosing them in parentheses. For example, the shape of + a 3-D `RaggedTensor` that stores the fixed-size word embedding for each + word in a sentence, for each sentence in a batch, could be written as + `[num_sentences, (num_words), embedding_size]`. The parentheses around + `(num_words)` indicate that dimension is ragged, and that the length + of each element list in that dimension may vary for each item. + + ### Component Tensors + + Internally, a `RaggedTensor` consists of a concatenated list of values that + are partitioned into variable-length rows. In particular, each `RaggedTensor` + consists of: + + * A `values` tensor, which concatenates the variable-length rows into a + flattened list. For example, the `values` tensor for + `[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is `[3, 1, 4, 1, 5, 9, 2, 6]`. + + * A `row_splits` vector, which indicates how those flattened values are + divided into rows. In particular, the values for row `rt[i]` are stored + in the slice `rt.values[rt.row_splits[i]:rt.row_splits[i+1]]`. + + Example: + + >>> print(tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_splits=[0, 4, 4, 7, 8, 8])) + + + ### Alternative Row-Partitioning Schemes + + In addition to `row_splits`, ragged tensors provide support for five other + row-partitioning schemes: + + * `row_lengths`: a vector with shape `[nrows]`, which specifies the length + of each row. + + * `value_rowids` and `nrows`: `value_rowids` is a vector with shape + `[nvals]`, corresponding one-to-one with `values`, which specifies + each value's row index. In particular, the row `rt[row]` consists of the + values `rt.values[j]` where `value_rowids[j]==row`. `nrows` is an + integer scalar that specifies the number of rows in the + `RaggedTensor`. (`nrows` is used to indicate trailing empty rows.) + + * `row_starts`: a vector with shape `[nrows]`, which specifies the start + offset of each row. Equivalent to `row_splits[:-1]`. + + * `row_limits`: a vector with shape `[nrows]`, which specifies the stop + offset of each row. Equivalent to `row_splits[1:]`. + + * `uniform_row_length`: A scalar tensor, specifying the length of every + row. This row-partitioning scheme may only be used if all rows have + the same length. + + Example: The following ragged tensors are equivalent, and all represent the + nested list `[[3, 1, 4, 1], [], [5, 9, 2], [6], []]`. + + >>> values = [3, 1, 4, 1, 5, 9, 2, 6] + >>> RaggedTensor.from_row_splits(values, row_splits=[0, 4, 4, 7, 8, 8]) + + >>> RaggedTensor.from_row_lengths(values, row_lengths=[4, 0, 3, 1, 0]) + + >>> RaggedTensor.from_value_rowids( + ... values, value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], nrows=5) + + >>> RaggedTensor.from_row_starts(values, row_starts=[0, 4, 4, 7, 8]) + + >>> RaggedTensor.from_row_limits(values, row_limits=[4, 4, 7, 8, 8]) + + >>> RaggedTensor.from_uniform_row_length(values, uniform_row_length=2) + + + ### Multiple Ragged Dimensions + + `RaggedTensor`s with multiple ragged dimensions can be defined by using + a nested `RaggedTensor` for the `values` tensor. Each nested `RaggedTensor` + adds a single ragged dimension. + + >>> inner_rt = RaggedTensor.from_row_splits( # =rt1 from above + ... values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]) + >>> outer_rt = RaggedTensor.from_row_splits( + ... values=inner_rt, row_splits=[0, 3, 3, 5]) + >>> print(outer_rt.to_list()) + [[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]] + >>> print(outer_rt.ragged_rank) + 2 + + The factory function `RaggedTensor.from_nested_row_splits` may be used to + construct a `RaggedTensor` with multiple ragged dimensions directly, by + providing a list of `row_splits` tensors: + + >>> RaggedTensor.from_nested_row_splits( + ... flat_values=[3, 1, 4, 1, 5, 9, 2, 6], + ... nested_row_splits=([0, 3, 3, 5], [0, 4, 4, 7, 8, 8])).to_list() + [[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]] + + ### Uniform Inner Dimensions + + `RaggedTensor`s with uniform inner dimensions can be defined + by using a multidimensional `Tensor` for `values`. + + >>> rt = RaggedTensor.from_row_splits(values=tf.ones([5, 3], tf.int32), + ... row_splits=[0, 2, 5]) + >>> print(rt.to_list()) + [[[1, 1, 1], [1, 1, 1]], + [[1, 1, 1], [1, 1, 1], [1, 1, 1]]] + >>> print(rt.shape) + (2, None, 3) + + ### Uniform Outer Dimensions + + `RaggedTensor`s with uniform outer dimensions can be defined by using + one or more `RaggedTensor` with a `uniform_row_length` row-partitioning + tensor. For example, a `RaggedTensor` with shape `[2, 2, None]` can be + constructed with this method from a `RaggedTensor` values with shape + `[4, None]`: + + >>> values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) + >>> print(values.shape) + (4, None) + >>> rt6 = tf.RaggedTensor.from_uniform_row_length(values, 2) + >>> print(rt6) + + >>> print(rt6.shape) + (2, 2, None) + + Note that `rt6` only contains one ragged dimension (the innermost + dimension). In contrast, if `from_row_splits` is used to construct a similar + `RaggedTensor`, then that `RaggedTensor` will have two ragged dimensions: + + >>> rt7 = tf.RaggedTensor.from_row_splits(values, [0, 2, 4]) + >>> print(rt7.shape) + (2, None, None) + + Uniform and ragged outer dimensions may be interleaved, meaning that a + tensor with any combination of ragged and uniform dimensions may be created. + For example, a RaggedTensor `t4` with shape `[3, None, 4, 8, None, 2]` could + be constructed as follows: + + ```python + t0 = tf.zeros([1000, 2]) # Shape: [1000, 2] + t1 = RaggedTensor.from_row_lengths(t0, [...]) # [160, None, 2] + t2 = RaggedTensor.from_uniform_row_length(t1, 8) # [20, 8, None, 2] + t3 = RaggedTensor.from_uniform_row_length(t2, 4) # [5, 4, 8, None, 2] + t4 = RaggedTensor.from_row_lengths(t3, [...]) # [3, None, 4, 8, None, 2] + ``` + + """ + + #============================================================================= + # Constructor (private) + #============================================================================= + @doc_controls.do_not_generate_docs + def __init__(self, values, row_partition, internal=False): + """Creates a `RaggedTensor` with a specified partitioning for `values`. + + This constructor is private -- please use one of the following ops to + build `RaggedTensor`s: + + * `tf.RaggedTensor.from_row_lengths` + * `tf.RaggedTensor.from_value_rowids` + * `tf.RaggedTensor.from_row_splits` + * `tf.RaggedTensor.from_row_starts` + * `tf.RaggedTensor.from_row_limits` + * `tf.RaggedTensor.from_nested_row_splits` + * `tf.RaggedTensor.from_nested_row_lengths` + * `tf.RaggedTensor.from_nested_value_rowids` + + Args: + values: A potentially ragged tensor of any dtype and shape `[nvals, ...]`. + row_partition: A `RowPartition` object, representing the arrangement of + the lists at the top level. + internal: True if the constructor is being called by one of the factory + methods. If false, an exception will be raised. + + Raises: + ValueError: If internal = False. Note that this method is intended only + for internal use. + TypeError: If values is not a `RaggedTensor` or `Tensor`, or + row_partition is not a `RowPartition`. + """ + + if not internal: + raise ValueError("RaggedTensor constructor is private; please use one " + "of the factory methods instead (e.g., " + "RaggedTensor.from_row_lengths())") + _assert_is_supported_ragged_values_type(values) + if not isinstance(row_partition, RowPartition): + raise TypeError(f"Argument `row_partition` must be a RowPartition. " + f"Received {row_partition}.") + + # Validate shapes. + values.shape.with_rank_at_least(1) + if isinstance(values, RaggedTensor): + # pylint: disable=protected-access + assert row_partition.dtype == values._row_partition.dtype + + self._values = values + self._row_partition = row_partition + + #============================================================================= + # Factory Methods + #============================================================================= + + @classmethod + def _from_row_partition(cls, values, row_partition, validate=True): + """Creates a `RaggedTensor` with a row partition. + + This is used as a way for RaggedTensors to share row partitions. + + The outer dimension of values must be equal to `partition.nvals()`. + + Args: + values: A potentially ragged tensor. + row_partition: a `RowPartition`: can be shared between tensors. + validate: If true, then use assertions to check that the arguments form a + valid `RaggedTensor`. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + Raises: + ValueError: If partition.nvals() != _nrows(values) + """ + if not isinstance(row_partition, RowPartition): + raise TypeError(f"Argument `row_partition` must be a RowPartition. " + f"Received {row_partition}.") + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + values, row_partition = cls._convert_values_and_partition( + values, row_partition, "partition") + if row_partition._has_precomputed_value_rowids(): # pylint: disable=protected-access + value_rowids_shape = row_partition.value_rowids().shape + values.shape[:1].assert_is_compatible_with(value_rowids_shape) + if validate: + msg = "Arguments to _from_row_partition do not form a valid RaggedTensor" + nvals = _nrows(values, row_partition.dtype) + checks = [ + check_ops.assert_equal( + math_ops.cast(row_partition.nvals(), row_partition.dtype), + nvals, + message=msg), + ] + if not isinstance(values, RaggedTensor): + checks.append(check_ops.assert_rank_at_least(values, 1)) + row_partition = row_partition._with_dependencies(checks) # pylint: disable=protected-access + return cls(values=values, internal=True, row_partition=row_partition) + + @classmethod + @dispatch.add_dispatch_support + def from_value_rowids(cls, + values, + value_rowids, + nrows=None, + name=None, + validate=True): + """Creates a `RaggedTensor` with rows partitioned by `value_rowids`. + + The returned `RaggedTensor` corresponds with the python list defined by: + + ```python + result = [[values[i] for i in range(len(values)) if value_rowids[i] == row] + for row in range(nrows)] + ``` + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + value_rowids: A 1-D integer tensor with shape `[nvals]`, which corresponds + one-to-one with `values`, and specifies each value's row index. Must be + nonnegative, and must be sorted in ascending order. + nrows: An integer scalar specifying the number of rows. This should be + specified if the `RaggedTensor` may containing empty training rows. Must + be greater than `value_rowids[-1]` (or zero if `value_rowids` is empty). + Defaults to `value_rowids[-1] + 1` (or zero if `value_rowids` is empty). + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + Raises: + ValueError: If `nrows` is incompatible with `value_rowids`. + + #### Example: + + >>> print(tf.RaggedTensor.from_value_rowids( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], + ... nrows=5)) + + + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + + with ops.name_scope(name, "RaggedFromValueRowIds", + [values, value_rowids, nrows]): + row_partition = RowPartition.from_value_rowids( + value_rowids=value_rowids, + nrows=nrows, + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_row_splits(cls, values, row_splits, name=None, validate=True): + """Creates a `RaggedTensor` with rows partitioned by `row_splits`. + + The returned `RaggedTensor` corresponds with the python list defined by: + + ```python + result = [values[row_splits[i]:row_splits[i + 1]] + for i in range(len(row_splits) - 1)] + ``` + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + row_splits: A 1-D integer tensor with shape `[nrows+1]`. Must not be + empty, and must be sorted in ascending order. `row_splits[0]` must be + zero and `row_splits[-1]` must be `nvals`. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + Raises: + ValueError: If `row_splits` is an empty list. + + #### Example: + + >>> print(tf.RaggedTensor.from_row_splits( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_splits=[0, 4, 4, 7, 8, 8])) + + + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + + with ops.name_scope(name, "RaggedFromRowSplits", [values, row_splits]): + row_partition = RowPartition.from_row_splits( + row_splits=row_splits, + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_row_lengths(cls, values, row_lengths, name=None, validate=True): + """Creates a `RaggedTensor` with rows partitioned by `row_lengths`. + + The returned `RaggedTensor` corresponds with the python list defined by: + + ```python + result = [[values.pop(0) for i in range(length)] + for length in row_lengths] + ``` + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + row_lengths: A 1-D integer tensor with shape `[nrows]`. Must be + nonnegative. `sum(row_lengths)` must be `nvals`. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + #### Example: + + >>> print(tf.RaggedTensor.from_row_lengths( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_lengths=[4, 0, 3, 1, 0])) + + + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + + with ops.name_scope(name, "RaggedFromRowLengths", [values, row_lengths]): + row_partition = RowPartition.from_row_lengths( + row_lengths=row_lengths, + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_row_starts(cls, values, row_starts, name=None, validate=True): + """Creates a `RaggedTensor` with rows partitioned by `row_starts`. + + Equivalent to: `from_row_splits(values, concat([row_starts, nvals]))`. + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + row_starts: A 1-D integer tensor with shape `[nrows]`. Must be + nonnegative and sorted in ascending order. If `nrows>0`, then + `row_starts[0]` must be zero. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + #### Example: + + >>> print(tf.RaggedTensor.from_row_starts( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_starts=[0, 4, 4, 7, 8])) + + + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + with ops.name_scope(name, "RaggedFromRowStarts", [values, row_starts]): + values = _convert_to_ragged_tensor_values(values) + row_partition = RowPartition.from_row_starts( + row_starts=row_starts, + nvals=_nrows(values), + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_row_limits(cls, values, row_limits, name=None, validate=True): + """Creates a `RaggedTensor` with rows partitioned by `row_limits`. + + Equivalent to: `from_row_splits(values, concat([0, row_limits]))`. + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + row_limits: A 1-D integer tensor with shape `[nrows]`. Must be sorted in + ascending order. If `nrows>0`, then `row_limits[-1]` must be `nvals`. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor`. `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + + #### Example: + + >>> print(tf.RaggedTensor.from_row_limits( + ... values=[3, 1, 4, 1, 5, 9, 2, 6], + ... row_limits=[4, 4, 7, 8, 8])) + + + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + with ops.name_scope(name, "RaggedFromRowLimits", [values, row_limits]): + values = _convert_to_ragged_tensor_values(values) + row_partition = RowPartition.from_row_limits( + row_limits=row_limits, + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_uniform_row_length(cls, + values, + uniform_row_length, + nrows=None, + validate=True, + name=None): + """Creates a `RaggedTensor` with rows partitioned by `uniform_row_length`. + + This method can be used to create `RaggedTensor`s with multiple uniform + outer dimensions. For example, a `RaggedTensor` with shape `[2, 2, None]` + can be constructed with this method from a `RaggedTensor` values with shape + `[4, None]`: + + >>> values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) + >>> print(values.shape) + (4, None) + >>> rt1 = tf.RaggedTensor.from_uniform_row_length(values, 2) + >>> print(rt1) + + >>> print(rt1.shape) + (2, 2, None) + + Note that `rt1` only contains one ragged dimension (the innermost + dimension). In contrast, if `from_row_splits` is used to construct a similar + `RaggedTensor`, then that `RaggedTensor` will have two ragged dimensions: + + >>> rt2 = tf.RaggedTensor.from_row_splits(values, [0, 2, 4]) + >>> print(rt2.shape) + (2, None, None) + + Args: + values: A potentially ragged tensor with shape `[nvals, ...]`. + uniform_row_length: A scalar integer tensor. Must be nonnegative. The + size of the outer axis of `values` must be evenly divisible by + `uniform_row_length`. + nrows: The number of rows in the constructed RaggedTensor. If not + specified, then it defaults to `nvals/uniform_row_length` (or `0` if + `uniform_row_length==0`). `nrows` only needs to be specified if + `uniform_row_length` might be zero. `uniform_row_length*nrows` must be + `nvals`. + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + name: A name prefix for the RaggedTensor (optional). + + Returns: + A `RaggedTensor` that corresponds with the python list defined by: + + ```python + result = [[values.pop(0) for i in range(uniform_row_length)] + for _ in range(nrows)] + ``` + + `result.rank = values.rank + 1`. + `result.ragged_rank = values.ragged_rank + 1`. + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + with ops.name_scope(name, "RaggedFromUniformRowLength", + [values, uniform_row_length, nrows]): + values = _convert_to_ragged_tensor_values(values) + uniform_row_length = _convert_row_partition( + uniform_row_length, "UniformRowLength", + _get_optional_partition_dtype(values)) + nvals = _nvals_uniform_row_length(values, uniform_row_length) + row_partition = RowPartition.from_uniform_row_length( + uniform_row_length=uniform_row_length, + nvals=nvals, + nrows=nrows, + validate=validate, + dtype_hint=_get_optional_partition_dtype(values)) + return cls._from_row_partition(values, row_partition, validate=validate) + + @classmethod + @dispatch.add_dispatch_support + def from_nested_value_rowids(cls, + flat_values, + nested_value_rowids, + nested_nrows=None, + name=None, + validate=True): + """Creates a `RaggedTensor` from a nested list of `value_rowids` tensors. + + Equivalent to: + + ```python + result = flat_values + for (rowids, nrows) in reversed(zip(nested_value_rowids, nested_nrows)): + result = from_value_rowids(result, rowids, nrows) + ``` + + Args: + flat_values: A potentially ragged tensor. + nested_value_rowids: A list of 1-D integer tensors. The `i`th tensor is + used as the `value_rowids` for the `i`th ragged dimension. + nested_nrows: A list of integer scalars. The `i`th scalar is used as the + `nrows` for the `i`th ragged dimension. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor` (or `flat_values` if `nested_value_rowids` is empty). + + Raises: + ValueError: If `len(nested_values_rowids) != len(nested_nrows)`. + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + if isinstance(nested_value_rowids, tensor_lib.Tensor): + raise TypeError(f"Argument `nested_value_rowids` must be a list of " + f"Tensors. Received {nested_value_rowids}.") + if nested_nrows is None: + nested_nrows = [None] * len(nested_value_rowids) + else: + if isinstance(nested_nrows, tensor_lib.Tensor): + raise TypeError(f"Argument `nested_nrows` must be a list of " + f"Tensors. Received {nested_nrows}.") + if len(nested_nrows) != len(nested_value_rowids): + raise ValueError( + f"Argument `nested_nrows` must have the same length as " + f"argument `nested_value_rowids`. len(nested_nrows) = " + f"{len(nested_nrows)} vs. len(nested_values_rowids) = " + f"{len(nested_value_rowids)}.") + + with ops.name_scope(name, "RaggedFromNestedValueRowIds", [flat_values] + + list(nested_value_rowids) + list(nested_nrows)): + result = flat_values + for value_rowids, nrows in reversed( + list(zip(nested_value_rowids, nested_nrows))): + result = cls.from_value_rowids( + result, value_rowids, nrows, validate=validate) + return result + + @classmethod + @dispatch.add_dispatch_support + def from_nested_row_splits(cls, + flat_values, + nested_row_splits, + name=None, + validate=True): + """Creates a `RaggedTensor` from a nested list of `row_splits` tensors. + + Equivalent to: + + ```python + result = flat_values + for row_splits in reversed(nested_row_splits): + result = from_row_splits(result, row_splits) + ``` + + Args: + flat_values: A potentially ragged tensor. + nested_row_splits: A list of 1-D integer tensors. The `i`th tensor is + used as the `row_splits` for the `i`th ragged dimension. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor` (or `flat_values` if `nested_row_splits` is empty). + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + if isinstance(nested_row_splits, tensor_lib.Tensor): + raise TypeError(f"Argument `nested_row_splits` must be a list of " + f"Tensors. Received {nested_row_splits}.") + with ops.name_scope(name, "RaggedFromNestedRowSplits", + [flat_values] + list(nested_row_splits)): + result = flat_values + for splits in reversed(nested_row_splits): + result = cls.from_row_splits(result, splits, validate=validate) + return result + + @classmethod + @dispatch.add_dispatch_support + def from_nested_row_lengths(cls, + flat_values, + nested_row_lengths, + name=None, + validate=True): + """Creates a `RaggedTensor` from a nested list of `row_lengths` tensors. + + Equivalent to: + + ```python + result = flat_values + for row_lengths in reversed(nested_row_lengths): + result = from_row_lengths(result, row_lengths) + ``` + + Args: + flat_values: A potentially ragged tensor. + nested_row_lengths: A list of 1-D integer tensors. The `i`th tensor is + used as the `row_lengths` for the `i`th ragged dimension. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor` (or `flat_values` if `nested_row_lengths` is empty). + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + if isinstance(nested_row_lengths, tensor_lib.Tensor): + raise TypeError(f"Argument `nested_row_lengths` must be a list of " + f"Tensors. Received {nested_row_lengths}.") + with ops.name_scope(name, "RaggedFromNestedRowlengths", + [flat_values] + list(nested_row_lengths)): + result = flat_values + for lengths in reversed(nested_row_lengths): + result = cls.from_row_lengths(result, lengths, validate=validate) + return result + + @classmethod + def _from_nested_row_partitions(cls, + flat_values, + nested_row_partitions, + name=None, + validate=True): + """Creates a `RaggedTensor` from a nested list of row partitions. + + Equivalent to: + + ```python + result = flat_values + for row_partition in reversed(nested_row_partitions): + result = _from_row_partition(result, row_partition) + ``` + + Args: + flat_values: A potentially ragged tensor. + nested_row_partitions: A list of row partitions. The `i`th element is + used as the row partition for the `i`th ragged dimension. + name: A name prefix for the RaggedTensor (optional). + validate: If true, then use assertions to check that the arguments form + a valid `RaggedTensor`. Note: these assertions incur a runtime cost, + since they must be checked for each tensor value. + + Returns: + A `RaggedTensor` (or `flat_values` if `nested_row_lengths` is empty). + """ + if not isinstance(validate, bool): + raise TypeError(f"Argument `validate` must have type bool. " + f"Received {validate}.") + if isinstance(nested_row_partitions, RowPartition): + raise TypeError(f"Argument `nested_row_partitions` must be a list of " + f"RowPartitions. Received {nested_row_partitions}.") + if isinstance(nested_row_partitions, tensor_lib.Tensor): + raise TypeError(f"Argument `nested_row_partitions` must be a list of " + f"RowPartitions. Received {nested_row_partitions}.") + with ops.name_scope(name, "RaggedFromNestedRowPartitions", + [flat_values] + list(nested_row_partitions)): + result = flat_values + for partition in reversed(nested_row_partitions): + result = cls._from_row_partition(result, partition, validate=validate) + return result + + @classmethod + def _convert_values_and_partition(cls, values, row_partition, name): + """Converts `values` and `partition` to Tensors. + + If `values` is a `RaggedTensor`, then converts `values` and `partition` + to have compatible row-partitioning dtypes. In particular, if any of the + row partitioning tensors are `int64`, then all of the other row + partitioning tensors wil be cast to `int64` (if auto_cast_partition_dtype() + is true) or an error will be raised (if auto_cast_partition_dtype() is + false). + + Args: + values: The `values` for the `RaggedTensor` being constructed. + row_partition: A RowPartition object for the `RaggedTensor` being + constructed. + name: The name of the RowPartition object. + + Returns: + A tuple (values, partition). + """ + if not isinstance(row_partition, RowPartition): + raise TypeError(f"Argument `row_partition` must be a RowPartition. " + f"Received {row_partition}.") + if isinstance(values, RaggedTensor): + # pylint: disable=protected-access + if values._row_partition.dtype != row_partition.dtype: + if not ragged_config.auto_cast_partition_dtype(): + # pylint: disable=protected-access + # TODO(edloper): get rid of the `name` parameter. + raise ValueError( + f"Argument `row_partition` of RaggedTensor with name: {name} " + f"must have same dtype as Argument `values`. " + f"({row_partition.dtype} vs. {values._row_partition.dtype}).") + values = values.with_row_splits_dtype(row_partition.dtype) + else: + values = _convert_to_ragged_tensor_values(values) + + return (values, row_partition) + + #============================================================================= + # Accessors + #============================================================================= + + @property + def dtype(self): + """The `DType` of values in this tensor.""" + return self._values.dtype + + @property + def shape(self): + """The statically known shape of this ragged tensor. + + Returns: + A `TensorShape` containing the statically known shape of this ragged + tensor. Ragged dimensions have a size of `None`. + + Examples: + + >>> tf.ragged.constant([[0], [1, 2]]).shape + TensorShape([2, None]) + + >>> tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1).shape + TensorShape([2, None, 2]) + + """ + nrows = self._row_partition.static_nrows + ncols = self._row_partition.static_uniform_row_length + value_shape = self._values.shape[1:] + return tensor_shape.TensorShape([nrows, ncols]).concatenate(value_shape) + + def get_shape(self) -> tensor_shape.TensorShape: + """The statically known shape of this ragged tensor. + + Returns: + A `TensorShape` containing the statically known shape of this ragged + tensor. Ragged dimensions have a size of `None`. + + Alias for `shape` property. + + Examples: + + >>> tf.ragged.constant([[0], [1, 2]]).get_shape() + TensorShape([2, None]) + + >>> tf.ragged.constant( + ... [[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1).get_shape() + TensorShape([2, None, 2]) + + """ + return self.shape + + @property + def ragged_rank(self): + """The number of times the RaggedTensor's flat_values is partitioned. + + Examples: + + >>> values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) + >>> values.ragged_rank + 1 + + >>> rt = tf.RaggedTensor.from_uniform_row_length(values, 2) + >>> rt.ragged_rank + 2 + + Returns: + A Python `int` indicating the number of times the underlying `flat_values` + Tensor has been partitioned to add a new dimension. + I.e., `tf.rank(rt) = tf.rank(rt.flat_values) + rt.ragged_rank`. + """ + values_is_ragged = isinstance(self._values, RaggedTensor) + return self._values.ragged_rank + 1 if values_is_ragged else 1 + + @property + def values(self): + """The concatenated rows for this ragged tensor. + + `rt.values` is a potentially ragged tensor formed by flattening the two + outermost dimensions of `rt` into a single dimension. + + `rt.values.shape = [nvals] + rt.shape[2:]` (where `nvals` is the + number of items in the outer two dimensions of `rt`). + + `rt.ragged_rank = self.ragged_rank - 1` + + Returns: + A potentially ragged tensor. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.values) + tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) + + """ + return self._values + + @property + def _nested_row_partitions(self): + """Returns the row partitions for this `RaggedTensor`.""" + partitions = [self._row_partition] + rt_values = self.values + while isinstance(rt_values, RaggedTensor): + # pylint: disable=protected-access + partitions.append(rt_values._row_partition) + rt_values = rt_values.values + return tuple(partitions) + + @property + def row_splits(self): + """The row-split indices for this ragged tensor's `values`. + + `rt.row_splits` specifies where the values for each row begin and end in + `rt.values`. In particular, the values for row `rt[i]` are stored in + the slice `rt.values[rt.row_splits[i]:rt.row_splits[i+1]]`. + + Returns: + A 1-D integer `Tensor` with shape `[self.nrows+1]`. + The returned tensor is non-empty, and is sorted in ascending order. + `self.row_splits[0]` is zero, and `self.row_splits[-1]` is equal to + `self.values.shape[0]`. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.row_splits) # indices of row splits in rt.values + tf.Tensor([0 4 4 7 8 8], shape=(6,), dtype=int64) + + """ + return self._row_partition.row_splits() + + @property + def uniform_row_length(self): + """The length of each row in this ragged tensor, or None if rows are ragged. + + >>> rt1 = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) + >>> print(rt1.uniform_row_length) # rows are ragged. + None + + >>> rt2 = tf.RaggedTensor.from_uniform_row_length( + ... values=rt1, uniform_row_length=2) + >>> print(rt2) + + >>> print(rt2.uniform_row_length) # rows are not ragged (all have size 2). + tf.Tensor(2, shape=(), dtype=int64) + + A RaggedTensor's rows are only considered to be uniform (i.e. non-ragged) + if it can be determined statically (at graph construction time) that the + rows all have the same length. + + Returns: + A scalar integer `Tensor`, specifying the length of every row in this + ragged tensor (for ragged tensors whose rows are uniform); or `None` + (for ragged tensors whose rows are ragged). + """ + return self._row_partition.uniform_row_length() + + @property + def flat_values(self): + """The innermost `values` tensor for this ragged tensor. + + Concretely, if `rt.values` is a `Tensor`, then `rt.flat_values` is + `rt.values`; otherwise, `rt.flat_values` is `rt.values.flat_values`. + + Conceptually, `flat_values` is the tensor formed by flattening the + outermost dimension and all of the ragged dimensions into a single + dimension. + + `rt.flat_values.shape = [nvals] + rt.shape[rt.ragged_rank + 1:]` + (where `nvals` is the number of items in the flattened dimensions). + + Returns: + A `Tensor`. + + #### Example: + + >>> rt = tf.ragged.constant([[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]) + >>> print(rt.flat_values) + tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) + + """ + rt_values = self.values + while isinstance(rt_values, RaggedTensor): + rt_values = rt_values.values + return rt_values + + @property + def nested_row_splits(self): + """A tuple containing the row_splits for all ragged dimensions. + + `rt.nested_row_splits` is a tuple containing the `row_splits` tensors for + all ragged dimensions in `rt`, ordered from outermost to innermost. In + particular, `rt.nested_row_splits = (rt.row_splits,) + value_splits` where: + + * `value_splits = ()` if `rt.values` is a `Tensor`. + * `value_splits = rt.values.nested_row_splits` otherwise. + + Returns: + A `tuple` of 1-D integer `Tensor`s. + + #### Example: + + >>> rt = tf.ragged.constant( + ... [[[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]]) + >>> for i, splits in enumerate(rt.nested_row_splits): + ... print('Splits for dimension %d: %s' % (i+1, splits.numpy())) + Splits for dimension 1: [0 3] + Splits for dimension 2: [0 3 3 5] + Splits for dimension 3: [0 4 4 7 8 8] + + """ + rt_nested_splits = [self.row_splits] + rt_values = self.values + while isinstance(rt_values, RaggedTensor): + rt_nested_splits.append(rt_values.row_splits) + rt_values = rt_values.values + return tuple(rt_nested_splits) + + def value_rowids(self, name=None): + """Returns the row indices for the `values` in this ragged tensor. + + `rt.value_rowids()` corresponds one-to-one with the outermost dimension of + `rt.values`, and specifies the row containing each value. In particular, + the row `rt[row]` consists of the values `rt.values[j]` where + `rt.value_rowids()[j] == row`. + + Args: + name: A name prefix for the returned tensor (optional). + + Returns: + A 1-D integer `Tensor` with shape `self.values.shape[:1]`. + The returned tensor is nonnegative, and is sorted in ascending order. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.values) + tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) + >>> print(rt.value_rowids()) # corresponds 1:1 with rt.values + tf.Tensor([0 0 0 0 2 2 2 3], shape=(8,), dtype=int64) + + """ + with ops.name_scope(name, "RaggedValueRowIds", [self]): + return self._row_partition.value_rowids() + + def nested_value_rowids(self, name=None): + """Returns a tuple containing the value_rowids for all ragged dimensions. + + `rt.nested_value_rowids` is a tuple containing the `value_rowids` tensors + for + all ragged dimensions in `rt`, ordered from outermost to innermost. In + particular, `rt.nested_value_rowids = (rt.value_rowids(),) + value_ids` + where: + + * `value_ids = ()` if `rt.values` is a `Tensor`. + * `value_ids = rt.values.nested_value_rowids` otherwise. + + Args: + name: A name prefix for the returned tensors (optional). + + Returns: + A `tuple` of 1-D integer `Tensor`s. + + #### Example: + + >>> rt = tf.ragged.constant( + ... [[[[3, 1, 4, 1], [], [5, 9, 2]], [], [[6], []]]]) + >>> for i, ids in enumerate(rt.nested_value_rowids()): + ... print('row ids for dimension %d: %s' % (i+1, ids.numpy())) + row ids for dimension 1: [0 0 0] + row ids for dimension 2: [0 0 0 2 2] + row ids for dimension 3: [0 0 0 0 2 2 2 3] + + """ + with ops.name_scope(name, "RaggedNestedValueRowIds", [self]): + rt_nested_ids = [self.value_rowids()] + rt_values = self.values + while isinstance(rt_values, RaggedTensor): + rt_nested_ids.append(rt_values.value_rowids()) + rt_values = rt_values.values + return tuple(rt_nested_ids) + + def nrows(self, out_type=None, name=None): + """Returns the number of rows in this ragged tensor. + + I.e., the size of the outermost dimension of the tensor. + + Args: + out_type: `dtype` for the returned tensor. Defaults to + `self.row_splits.dtype`. + name: A name prefix for the returned tensor (optional). + + Returns: + A scalar `Tensor` with dtype `out_type`. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.nrows()) # rt has 5 rows. + tf.Tensor(5, shape=(), dtype=int64) + + """ + with ops.name_scope(name, "RaggedNRows", [self]): + if out_type is None: + return self._row_partition.nrows() + else: + return math_ops.cast(self._row_partition.nrows(), dtype=out_type) + + def row_starts(self, name=None): + """Returns the start indices for rows in this ragged tensor. + + These indices specify where the values for each row begin in + `self.values`. `rt.row_starts()` is equal to `rt.row_splits[:-1]`. + + Args: + name: A name prefix for the returned tensor (optional). + + Returns: + A 1-D integer Tensor with shape `[nrows]`. + The returned tensor is nonnegative, and is sorted in ascending order. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.values) + tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) + >>> print(rt.row_starts()) # indices of row starts in rt.values + tf.Tensor([0 4 4 7 8], shape=(5,), dtype=int64) + + """ + with ops.name_scope(name, "RaggedRowStarts", [self]): + return self._row_partition.row_starts() + + def row_limits(self, name=None): + """Returns the limit indices for rows in this ragged tensor. + + These indices specify where the values for each row end in + `self.values`. `rt.row_limits(self)` is equal to `rt.row_splits[:-1]`. + + Args: + name: A name prefix for the returned tensor (optional). + + Returns: + A 1-D integer Tensor with shape `[nrows]`. + The returned tensor is nonnegative, and is sorted in ascending order. + + #### Example: + + >>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []]) + >>> print(rt.values) + tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32) + >>> print(rt.row_limits()) # indices of row limits in rt.values + tf.Tensor([4 4 7 8 8], shape=(5,), dtype=int64) + + """ + with ops.name_scope(name, "RaggedRowLimits", [self]): + return self._row_partition.row_limits() + + def row_lengths(self, axis=1, name=None): + """Returns the lengths of the rows in this ragged tensor. + + `rt.row_lengths()[i]` indicates the number of values in the + `i`th row of `rt`. + + Args: + axis: An integer constant indicating the axis whose row lengths should be + returned. + name: A name prefix for the returned tensor (optional). + + Returns: + A potentially ragged integer Tensor with shape `self.shape[:axis]`. + + Raises: + ValueError: If `axis` is out of bounds. + + #### Example: + + >>> rt = tf.ragged.constant( + ... [[[3, 1, 4], [1]], [], [[5, 9], [2]], [[6]], []]) + >>> print(rt.row_lengths()) # lengths of rows in rt + tf.Tensor([2 0 2 1 0], shape=(5,), dtype=int64) + >>> print(rt.row_lengths(axis=2)) # lengths of axis=2 rows. + + + """ + if axis == 0: + return self._row_partition.nrows() + + if axis == 1: + return self._row_partition.row_lengths() + + with ops.name_scope(name, "RaggedRowLengths", [self]): + axis = array_ops.get_positive_axis( + axis, self.shape.rank, ndims_name="rank(self)") + if axis == 0: + return self.nrows() + elif axis == 1: + splits = self.row_splits + return splits[1:] - splits[:-1] + elif isinstance(self.values, RaggedTensor): + return self.with_values(self.values.row_lengths(axis - 1)) + else: + shape = array_ops.shape(self.values, out_type=self._row_partition.dtype) + return self.with_values( + array_ops.ones(shape[:axis - 1], self._row_partition.dtype) * + shape[axis - 1]) + + def nested_row_lengths(self, name=None): + """Returns a tuple containing the row_lengths for all ragged dimensions. + + `rt.nested_row_lengths()` is a tuple containing the `row_lengths` tensors + for all ragged dimensions in `rt`, ordered from outermost to innermost. + + Args: + name: A name prefix for the returned tensors (optional). + + Returns: + A `tuple` of 1-D integer `Tensors`. The length of the tuple is equal to + `self.ragged_rank`. + """ + with ops.name_scope(name, "RaggedNestedRowLengths", [self]): + rt_nested_row_lengths = [] + rt = self + while isinstance(rt, RaggedTensor): + rt_nested_row_lengths.append(rt.row_lengths()) + rt = rt.values + return tuple(rt_nested_row_lengths) + + def bounding_shape(self, axis=None, name=None, out_type=None): + """Returns the tight bounding box shape for this `RaggedTensor`. + + Args: + axis: An integer scalar or vector indicating which axes to return the + bounding box for. If not specified, then the full bounding box is + returned. + name: A name prefix for the returned tensor (optional). + out_type: `dtype` for the returned tensor. Defaults to + `self.row_splits.dtype`. + + Returns: + An integer `Tensor` (`dtype=self.row_splits.dtype`). If `axis` is not + specified, then `output` is a vector with + `output.shape=[self.shape.ndims]`. If `axis` is a scalar, then the + `output` is a scalar. If `axis` is a vector, then `output` is a vector, + where `output[i]` is the bounding size for dimension `axis[i]`. + + #### Example: + + >>> rt = tf.ragged.constant([[1, 2, 3, 4], [5], [], [6, 7, 8, 9], [10]]) + >>> rt.bounding_shape().numpy() + array([5, 4]) + + """ + if out_type is None: + out_type = self._row_partition.dtype + else: + out_type = dtypes.as_dtype(out_type) + with ops.name_scope(name, "RaggedBoundingBox", [self, axis]): + nested_splits = self.nested_row_splits + rt_flat_values = self.flat_values + + # Optimized special cases for when axis=0 or axis=1: + if isinstance(axis, int): + if axis == 0: + return array_ops.shape(nested_splits[0], out_type=out_type)[0] - 1 + elif axis == 1: + result = math_ops.maximum(math_ops.reduce_max(self.row_lengths()), 0) + if out_type != self._row_partition.dtype: + result = math_ops.cast(result, out_type) + return result + + splits_shape = array_ops.shape(self.row_splits, out_type=out_type) + flat_values_shape = array_ops.shape(rt_flat_values, out_type=out_type) + + ragged_dimensions = [splits_shape[0] - 1] + [ + math_ops.maximum(math_ops.reduce_max(splits[1:] - splits[:-1]), 0) + for splits in nested_splits + ] + inner_dimensions = flat_values_shape[1:] + + if out_type != self._row_partition.dtype: + ragged_dimensions = [ + math_ops.cast(d, out_type) for d in ragged_dimensions + ] + bbox = array_ops.concat( + [array_ops_stack.stack(ragged_dimensions), inner_dimensions], axis=0) + return bbox if axis is None else array_ops.gather(bbox, axis) + + #============================================================================= + # Transformation + #============================================================================= + + def with_values(self, new_values): + """Returns a copy of `self` with `values` replaced by `new_value`. + + Preserves cached row-partitioning tensors such as `self.cached_nrows` and + `self.cached_value_rowids` if they have values. + + Args: + new_values: Potentially ragged tensor to use as the `values` for the + returned `RaggedTensor`. Must have `rank > 0`, and must have the same + number of rows as `self.values`. + + Returns: + A `RaggedTensor`. `result.rank = 1 + new_values.rank`. + `result.ragged_rank = 1 + new_values.ragged_rank` + """ + new_values = _convert_to_ragged_tensor_values(new_values) + new_values.shape.with_rank_at_least(1) + self.values.shape[:1].assert_is_compatible_with(new_values.shape[:1]) + if (isinstance(new_values, RaggedTensor) and + self._row_partition.dtype != new_values.row_splits.dtype): + if not ragged_config.auto_cast_partition_dtype(): + raise ValueError("self and new_values have mismatched row_splits " + "dtypes; use RaggedTensor.with_row_splits_dtype() to " + "convert them to compatible dtypes.") + new_values = new_values.with_row_splits_dtype(dtypes.int64) + return self.with_row_splits_dtype(dtypes.int64).with_values(new_values) + return RaggedTensor( + values=new_values, row_partition=self._row_partition, internal=True) + + def with_flat_values(self, new_values): + """Returns a copy of `self` with `flat_values` replaced by `new_value`. + + Preserves cached row-partitioning tensors such as `self.cached_nrows` and + `self.cached_value_rowids` if they have values. + + Args: + new_values: Potentially ragged tensor that should replace + `self.flat_values`. Must have `rank > 0`, and must have the same number + of rows as `self.flat_values`. + + Returns: + A `RaggedTensor`. + `result.rank = self.ragged_rank + new_values.rank`. + `result.ragged_rank = self.ragged_rank + new_values.ragged_rank`. + """ + if isinstance(self._values, RaggedTensor): + return self.with_values(self.values.with_flat_values(new_values)) + else: + new_values = _convert_to_ragged_tensor_values(new_values) + return self.with_values(new_values) + + def with_row_splits_dtype(self, dtype): + """Returns a copy of this RaggedTensor with the given `row_splits` dtype. + + For RaggedTensors with multiple ragged dimensions, the `row_splits` for all + nested `RaggedTensor` objects are cast to the given dtype. + + Args: + dtype: The dtype for `row_splits`. One of `tf.int32` or `tf.int64`. + + Returns: + A copy of this RaggedTensor, with the `row_splits` cast to the given + type. + """ + dtype = dtypes.as_dtype(dtype) + if dtype not in (dtypes.int32, dtypes.int64): + raise ValueError(f"Argument `row_splits` dtype must be int32 or int64. " + f"Received {dtype}.") + if self._row_partition.dtype == dtype: + return self + current_values = self._values + if isinstance(current_values, RaggedTensor): + return RaggedTensor( + values=current_values.with_row_splits_dtype(dtype), + row_partition=self._row_partition.with_dtype(dtype), + internal=True) + else: + return RaggedTensor( + values=current_values, + row_partition=self._row_partition.with_dtype(dtype), + internal=True) + + def merge_dims(self, outer_axis, inner_axis): + """Merges outer_axis...inner_axis into a single dimension. + + Returns a copy of this RaggedTensor with the specified range of dimensions + flattened into a single dimension, with elements in row-major order. + + #### Examples: + + >>> rt = tf.ragged.constant([[[1, 2], [3]], [[4, 5, 6]]]) + >>> print(rt.merge_dims(0, 1)) + + >>> print(rt.merge_dims(1, 2)) + + >>> print(rt.merge_dims(0, 2)) + tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32) + + To mimic the behavior of `np.flatten` (which flattens all dimensions), use + `rt.merge_dims(0, -1). To mimic the behavior of `tf.layers.Flatten` (which + flattens all dimensions except the outermost batch dimension), use + `rt.merge_dims(1, -1)`. + + Args: + outer_axis: `int`: The first dimension in the range of dimensions to + merge. May be negative if `self.shape.rank` is statically known. + inner_axis: `int`: The last dimension in the range of dimensions to merge. + May be negative if `self.shape.rank` is statically known. + + Returns: + A copy of this tensor, with the specified dimensions merged into a + single dimension. The shape of the returned tensor will be + `self.shape[:outer_axis] + [N] + self.shape[inner_axis + 1:]`, where `N` + is the total number of slices in the merged dimensions. + """ + outer_axis = array_ops.get_positive_axis( + outer_axis, + self.shape.rank, + axis_name="outer_axis", + ndims_name="rank(self)") + inner_axis = array_ops.get_positive_axis( + inner_axis, + self.shape.rank, + axis_name="inner_axis", + ndims_name="rank(self)") + if not outer_axis <= inner_axis: + raise ValueError(f"Expected outer_axis ({outer_axis}) to be less than or " + f"equal to inner_axis ({inner_axis}).") + return merge_dims(self, outer_axis, inner_axis) + + def _set_shape(self, shape): + """Updates the static shape of `self` to be `shape`. + + * If a dimension of `shape` has known rank, and is encoded via + partitioning, then this will update the corresponding partition to + define `_uniform_row_length` and `nrows`. + * If a dimension of `shape` has a known rank, and is encoded as one + of the `flat_values` dimensions, then `flat_values.set_shape()` will + be used to update its shape. + + Warning: Using this method to assert an incorrect shape for a RaggedTensor + (i.e., one that's not consistent with its actual shape) can cause + segmentation faults and very difficult-to-diagnose behavior. Only use this + method if you are certain that the shape is correct. + + Args: + shape: `tf.TensorShape` specifying the shape for this `RaggedTensor`. + """ + # TODO(edloper): Refactor this to not directly access private members + # of RowPartition. + # pylint: disable=protected-access + + shape = tensor_shape.as_shape(shape) + if shape.rank is None: + return # Nothing to do. + + shape = shape.as_list() + + # Outermost dimension + if shape[0] is not None: + self._row_partition._row_splits.set_shape(shape[0] + 1) + + # Partitioned dimensions + dtype = self._row_partition.dtype + for i, partition in enumerate(self._nested_row_partitions): + size = shape[i + 1] + if size is not None: + if partition._uniform_row_length is not None: + old_row_length = tensor_util.constant_value( + partition._uniform_row_length) + if old_row_length is not None: + if size == old_row_length: + continue # already have shape info for this axis. + else: + raise ValueError(f"Inconsistent size for axis {i + 1}: " + f"{old_row_length} vs. {size}.") + partition._uniform_row_length = ops.convert_to_tensor(size, dtype) + if partition._nrows is None: + partition._nrows = array_ops.size( + partition._row_splits, out_type=dtype) - 1 + + # self.flat_values could be a CompositeTensor and doesn't have set_shape. + if hasattr(self.flat_values, "set_shape"): + # Inner dimensions + flat_shape = tensor_shape.as_shape([None] + shape[self.ragged_rank + 1:]) + self.flat_values.set_shape(flat_shape) + + #============================================================================= + # Tensor Type Conversions + #============================================================================= + + @classmethod + @dispatch.add_dispatch_support + def from_tensor(cls, + tensor, + lengths=None, + padding=None, + ragged_rank=1, + name=None, + row_splits_dtype=dtypes.int64): + """Converts a `tf.Tensor` into a `RaggedTensor`. + + The set of absent/default values may be specified using a vector of lengths + or a padding value (but not both). If `lengths` is specified, then the + output tensor will satisfy `output[row] = tensor[row][:lengths[row]]`. If + 'lengths' is a list of lists or tuple of lists, those lists will be used + as nested row lengths. If `padding` is specified, then any row *suffix* + consisting entirely of `padding` will be excluded from the returned + `RaggedTensor`. If neither `lengths` nor `padding` is specified, then the + returned `RaggedTensor` will have no absent/default values. + + Examples: + + >>> dt = tf.constant([[5, 7, 0], [0, 3, 0], [6, 0, 0]]) + >>> tf.RaggedTensor.from_tensor(dt) + + >>> tf.RaggedTensor.from_tensor(dt, lengths=[1, 0, 3]) + + + >>> tf.RaggedTensor.from_tensor(dt, padding=0) + + + >>> dt = tf.constant([[[5, 0], [7, 0], [0, 0]], + ... [[0, 0], [3, 0], [0, 0]], + ... [[6, 0], [0, 0], [0, 0]]]) + >>> tf.RaggedTensor.from_tensor(dt, lengths=([2, 0, 3], [1, 1, 2, 0, 1])) + + + Args: + tensor: The `Tensor` to convert. Must have rank `ragged_rank + 1` or + higher. + lengths: An optional set of row lengths, specified using a 1-D integer + `Tensor` whose length is equal to `tensor.shape[0]` (the number of rows + in `tensor`). If specified, then `output[row]` will contain + `tensor[row][:lengths[row]]`. Negative lengths are treated as zero. You + may optionally pass a list or tuple of lengths to this argument, which + will be used as nested row lengths to construct a ragged tensor with + multiple ragged dimensions. + padding: An optional padding value. If specified, then any row suffix + consisting entirely of `padding` will be excluded from the returned + RaggedTensor. `padding` is a `Tensor` with the same dtype as `tensor` + and with `shape=tensor.shape[ragged_rank + 1:]`. + ragged_rank: Integer specifying the ragged rank for the returned + `RaggedTensor`. Must be greater than zero. + name: A name prefix for the returned tensors (optional). + row_splits_dtype: `dtype` for the returned `RaggedTensor`'s `row_splits` + tensor. One of `tf.int32` or `tf.int64`. + + Returns: + A `RaggedTensor` with the specified `ragged_rank`. The shape of the + returned ragged tensor is compatible with the shape of `tensor`. + + Raises: + ValueError: If both `lengths` and `padding` are specified. + ValueError: If the rank of `tensor` is 0 or 1. + """ + row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + if lengths is not None and padding is not None: + raise ValueError("Specify argument `lengths` or `padding`, but not both.") + if not isinstance(ragged_rank, int): + raise TypeError(f"Argument `ragged_rank` must be an int. " + f"Received {ragged_rank}.") + if ragged_rank <= 0: + raise ValueError(f"Argument `ragged_rank` must be greater than 0. " + f"Received {ragged_rank}.") + + with ops.name_scope(name, "RaggedFromTensor", [tensor, lengths, padding]): + tensor = ops.convert_to_tensor(tensor, name="tensor") + if tensor.shape.rank is not None and tensor.shape.rank < 2: + raise ValueError(f"The rank of a RaggedTensor must be greater than 1, " + f"i.e., a list of scalars won't have ragged " + f"dimensions. Received argument `tensor` with rank " + f"{tensor.shape.rank}.") + tensor.shape.with_rank_at_least(ragged_rank + 1) + input_shape = array_ops.shape(tensor, out_type=row_splits_dtype) + ncols = input_shape[1] + + # Handle nested row lengths. + if (lengths is not None and isinstance(lengths, (list, tuple)) and + len(lengths) and not isinstance(lengths[0], (int, float))): + if ragged_rank not in (1, len(lengths)): + # Note: we accept `ragged_rank=1` here because it's the default value; + # i.e., if the user passes in a tuple of lengths, but doesn't specify + # ragged_rank, then we should use that tuple to determine ragged_rank. + # We only want to complain if they pass in an explicit ragged_rank + # that doesn't match len(lengths). + raise ValueError(f"If Argument `lengths` is a tuple of row_lengths, " + f"argument `ragged_rank` must be " + f"len(lengths): {len(lengths)}. Received " + f"ragged_rank: {ragged_rank}.") + # Rather than reconstructing the tensor mask directly, we can + # recreate it as a boolean RaggedTensor, then densify that and use + # that as the mask to clear out the unused data in the passed tensor. + tensor.shape.with_rank_at_least(len(lengths) + 1) + num_tokens = math_ops.reduce_sum(lengths[-1]) + ones_mask = array_ops.ones([num_tokens], dtype=dtypes.bool) + ragged_mask = cls.from_nested_row_lengths( + ones_mask, lengths, validate=False) + dense_ragged_mask = ragged_mask.to_tensor(default_value=False) + masked_data = array_ops.boolean_mask(tensor, dense_ragged_mask) + return cls.from_nested_row_lengths(masked_data, lengths, validate=False) + + # Handle ragged_rank>1 via recursion: + # If the output should have multiple ragged dimensions, then first + # flatten the tensor to eliminate all but the last ragged dimension, + # and recursively convert that flattened tensor. Then add on the splits + # for the dimensions that we flattened out. + if ragged_rank > 1: + if tensor.shape.is_fully_defined(): + input_shape = tensor.shape.as_list() + # The total number of elements in each dimension. E.g., if + # input_shape=[3, 4, 5, 6], then dim[2] has 3*4*5 elements in total. + dim_size = np.cumprod(input_shape) + new_shape = [dim_size[ragged_rank - 1]] + input_shape[ragged_rank:] + else: + dim_size = math_ops.cumprod(input_shape) + new_shape = array_ops.concat( + [[dim_size[ragged_rank - 1]], input_shape[ragged_rank:]], axis=0) + flattened = array_ops.reshape(tensor, new_shape) + result = cls.from_tensor( + flattened, lengths, padding, row_splits_dtype=row_splits_dtype) + + for axis in range(ragged_rank - 1, 0, -1): + dim_len = tensor_shape.dimension_at_index(tensor.shape, axis).value + if dim_len is None: + dim_len = input_shape[axis] + else: + dim_len = constant_op.constant(dim_len, row_splits_dtype) + result = RaggedTensor.from_uniform_row_length( + values=result, + uniform_row_length=dim_len, + nrows=dim_size[axis - 1], + validate=False) + return result + + # If padding was specified, then use it to find row lengths. + if padding is not None: + padding = ops.convert_to_tensor( + padding, name="padding", dtype=tensor.dtype) + padding.shape.assert_is_compatible_with(tensor.shape[2:]) + + # Find places where the padding is equal to the tensor. (This will + # broadcast `padding` across the outermost 2 dimensions of `tensor`, + # so `has_default_value.shape = tensor.shape`.) + has_default_value = math_ops.equal(padding, tensor) + + # If the padding isn't a scalar, then require that all values in the + # padding match each item in the tensor. After this block of code, + # `has_default.shape = tensor.shape[:2]`. (Unfortunately, we can't just + # use reduce_all for both cases, becaue when you pass an empty `axis` + # list to reduce_all, it reduces all axes; but we want it to reduce no + # axes -- i.e., to be a no-op.) + tensor_rank = array_ops.rank(tensor) + reduce_axis = math_ops.range(2, tensor_rank) + has_default = cond.cond( + tensor_rank > 2, + lambda: math_ops.reduce_all(has_default_value, axis=reduce_axis), + lambda: has_default_value) + has_default.set_shape(tensor_shape.TensorShape([None, None])) + has_default.set_shape(tensor.shape[:2]) + + # Use has_default to find the length of each row: for each + # non-default item in a row, calculate the length that the row needs to + # have to include that item; and then take the max of those values + # (across each row). + has_nondefault = math_ops.logical_not(has_default) + has_nondefault = math_ops.cast(has_nondefault, row_splits_dtype) + length_for_nondefault_value = ( + has_nondefault * + array_ops.expand_dims(math_ops.range(1, ncols + 1), 0)) + lengths = math_ops.reduce_max(length_for_nondefault_value, axis=1) + + if lengths is not None: + # If we have lengths (either directly supplied, or computed from + # paddings), then use those to construct splits; and then use masking + # to get the corresponding values. + lengths = ragged_util.convert_to_int_tensor(lengths, "lengths", + row_splits_dtype) + lengths.shape.assert_has_rank(1) + lengths = math_ops.minimum(lengths, ncols) + lengths = math_ops.maximum(lengths, 0) + limits = math_ops.cumsum(lengths) + splits = array_ops.concat( + [array_ops.zeros([1], row_splits_dtype), limits], axis=0) + mask = array_ops.sequence_mask(lengths, maxlen=ncols) + values = array_ops.boolean_mask(tensor, mask) + return cls.from_row_splits(values, splits, validate=False) + + # If neither padding nor lengths were specified, then create a splits + # vector that contains no default values, and reshape the input tensor + # to form the values for the RaggedTensor. + values_shape = array_ops.concat( + [[input_shape[0] * input_shape[1]], input_shape[2:]], axis=0) + values = array_ops.reshape(tensor, values_shape) + const_nrows = tensor_shape.dimension_at_index(tensor.shape, 0).value + const_ncols = tensor_shape.dimension_at_index(tensor.shape, 1).value + if const_nrows is not None: + nrows = constant_op.constant(const_nrows, row_splits_dtype) + else: + nrows = input_shape[0] + if const_ncols is not None: + ncols = constant_op.constant(const_ncols, row_splits_dtype) + else: + ncols = input_shape[1] + return RaggedTensor.from_uniform_row_length( + values=values, uniform_row_length=ncols, nrows=nrows, validate=False) + + def to_tensor(self, default_value=None, name=None, shape=None): + """Converts this `RaggedTensor` into a `tf.Tensor`. + + If `shape` is specified, then the result is padded and/or truncated to + the specified shape. + + Examples: + + >>> rt = tf.ragged.constant([[9, 8, 7], [], [6, 5], [4]]) + >>> print(rt.to_tensor()) + tf.Tensor( + [[9 8 7] [0 0 0] [6 5 0] [4 0 0]], shape=(4, 3), dtype=int32) + >>> print(rt.to_tensor(shape=[5, 2])) + tf.Tensor( + [[9 8] [0 0] [6 5] [4 0] [0 0]], shape=(5, 2), dtype=int32) + + Args: + default_value: Value to set for indices not specified in `self`. Defaults + to zero. `default_value` must be broadcastable to + `self.shape[self.ragged_rank + 1:]`. + name: A name prefix for the returned tensors (optional). + shape: The shape of the resulting dense tensor. In particular, + `result.shape[i]` is `shape[i]` (if `shape[i]` is not None), or + `self.bounding_shape(i)` (otherwise).`shape.rank` must be `None` or + equal to `self.rank`. + + Returns: + A `Tensor` with shape `ragged.bounding_shape(self)` and the + values specified by the non-empty values in `self`. Empty values are + assigned `default_value`. + """ + with ops.name_scope(name, "RaggedToTensor", [self, default_value, shape]): + if default_value is not None: + default_value = ops.convert_to_tensor( + default_value, name="default_value", dtype=self.dtype) + type_tensor_pairs = _get_row_partition_type_tensor_pairs(self) + row_partition_types = [x[0] for x in type_tensor_pairs] + row_partition_tensors = [x[1] for x in type_tensor_pairs] + if default_value is None: + default_value = array_ops.zeros((), self.dtype) + + if (isinstance(shape, (list, tuple)) and + any(isinstance(v, tensor_lib.Tensor) for v in shape) and + all(isinstance(v, (int, tensor_lib.Tensor)) for v in shape)): + shape = array_ops_stack.stack(shape) + + shape_tensor = _shape_as_tensor(shape, row_partition_tensors[0].dtype) + tensor = gen_ragged_conversion_ops.ragged_tensor_to_tensor( + shape=shape_tensor, + values=self.flat_values, + default_value=default_value, + row_partition_types=row_partition_types, + row_partition_tensors=row_partition_tensors, + ) + + ragged_shape = self.shape + + if ragged_shape.rank is not None and not isinstance( + shape, tensor_lib.Tensor + ): + # Merged self.shape and shape, favoring the second one as it takes + # into account potential padding added to the output. + shape = tensor_shape.as_shape(shape) + if shape.rank is None: + output_shape = ragged_shape + else: + # At this point we can assume that hshape.rank == ragged_shape.rank + # because otherwise it would have failed earlier. + output_shape = [ + s1 if s1 is not None else s2 + for (s1, s2) in zip(shape.as_list(), ragged_shape.as_list()) + ] + tensor.set_shape(output_shape) + + return tensor + + @classmethod + @dispatch.add_dispatch_support + def from_sparse(cls, st_input, name=None, row_splits_dtype=dtypes.int64): + """Converts a 2D `tf.sparse.SparseTensor` to a `RaggedTensor`. + + Each row of the `output` `RaggedTensor` will contain the explicit values + from the same row in `st_input`. `st_input` must be ragged-right. If not + it is not ragged-right, then an error will be generated. + + Example: + + >>> indices = [[0, 0], [0, 1], [0, 2], [1, 0], [3, 0]] + >>> st = tf.sparse.SparseTensor(indices=indices, + ... values=[1, 2, 3, 4, 5], + ... dense_shape=[4, 3]) + >>> tf.RaggedTensor.from_sparse(st).to_list() + [[1, 2, 3], [4], [], [5]] + + Currently, only two-dimensional `SparseTensors` are supported. + + Args: + st_input: The sparse tensor to convert. Must have rank 2. + name: A name prefix for the returned tensors (optional). + row_splits_dtype: `dtype` for the returned `RaggedTensor`'s `row_splits` + tensor. One of `tf.int32` or `tf.int64`. + + Returns: + A `RaggedTensor` with the same values as `st_input`. + `output.ragged_rank = rank(st_input) - 1`. + `output.shape = [st_input.dense_shape[0], None]`. + Raises: + ValueError: If the number of dimensions in `st_input` is not known + statically, or is not two. + """ + row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + if not sparse_tensor.is_sparse(st_input): + raise TypeError(f"Argument `st_input` must be of type SparseTensor, but " + f"is of type {type(st_input).__name__}.") + with ops.name_scope(name, "RaggedFromSparse", [st_input]): + st_input = sparse_tensor.convert_to_tensor_or_sparse_tensor( + st_input, name="st_input") + + if st_input.dense_shape.shape.ndims is None: + static_rank_from_dense_shape = None + else: + static_rank_from_dense_shape = st_input.dense_shape.shape.dims[0].value + + if st_input.indices.shape.ndims is None: + static_rank_from_indices = None + else: + static_rank_from_indices = st_input.indices.shape.dims[1].value + + if static_rank_from_dense_shape != 2 and static_rank_from_indices != 2: + raise ValueError("rank(st_input) must be 2.") + + with ops.control_dependencies( + _assert_sparse_indices_are_ragged_right(st_input.indices)): + # Treat sparse row indices as segment ids to generate a splits tensor + # thta we can pair with the sparse tensor values. (Ignore sparse column + # indices.) + segment_ids = math_ops.cast(st_input.indices[:, 0], row_splits_dtype) + num_segments = math_ops.cast(st_input.dense_shape[0], row_splits_dtype) + return cls.from_value_rowids( + st_input.values, segment_ids, num_segments, validate=False) + + def to_sparse(self, name=None): + """Converts this `RaggedTensor` into a `tf.sparse.SparseTensor`. + + Example: + + >>> rt = tf.ragged.constant([[1, 2, 3], [4], [], [5, 6]]) + >>> print(rt.to_sparse()) + SparseTensor(indices=tf.Tensor( + [[0 0] [0 1] [0 2] [1 0] [3 0] [3 1]], + shape=(6, 2), dtype=int64), + values=tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32), + dense_shape=tf.Tensor([4 3], shape=(2,), dtype=int64)) + + Args: + name: A name prefix for the returned tensors (optional). + + Returns: + A SparseTensor with the same values as `self`. + """ + with ops.name_scope(name, "RaggedToSparse", [self]): + result = gen_ragged_conversion_ops.ragged_tensor_to_sparse( + self.nested_row_splits, self.flat_values, name=name) + return sparse_tensor.SparseTensor(result.sparse_indices, + result.sparse_values, + result.sparse_dense_shape) + + @classmethod + def _from_variant(cls, + variant, + dtype, + output_ragged_rank, + input_ragged_rank=None, + row_splits_dtype=dtypes.int64, + name=None): + """Converts a `variant` Tensor into a `RaggedTensor`. + + The input `variant` could be a scalar, meaning it encodes a single + `RaggedTensor` with ragged_rank `output_ragged_rank`. Alternatively it could + have an arbitrary rank, in which case each element is decoded into a + `RaggedTensor` with ragged_rank `input_ragged_rank` and these are then + stacked according to the input shape to output a single `RaggedTensor` + with ragged_rank `output_ragged_rank`. If `input_ragged_rank` is not + provided, it is inferred dynamically as `output_ragged_rank` - + `rank(variant)`. If `input_ragged_rank` is provided, the following must be + true: `output_ragged_rank` = `input_ragged_rank` + `rank(variant)`. + + Example: + + >>> rt = tf.ragged.constant([[0], [1, 2]]) + >>> et = rt._to_variant() + >>> stacked_et = tf.stack([et, et]) + >>> tf.RaggedTensor._from_variant( # scalar input. + ... et, dtype=tf.int32, output_ragged_rank=1).to_list() + [[0], [1, 2]] + >>> tf.RaggedTensor._from_variant( # batched input. + ... stacked_et, dtype=tf.int32, output_ragged_rank=2).to_list() + [[[0], [1, 2]], [[0], [1, 2]]] + + Args: + variant: A `variant` Tensor representing an encoded (possibly + nested-batched) `RaggedTensor`. + dtype: The dtype of the encoded `RaggedTensor`. + output_ragged_rank: The expected ragged rank of the output `RaggedTensor`. + input_ragged_rank: The ragged rank of each encoded `RaggedTensor`. This is + optional and inferred dynamically if not provided. + row_splits_dtype: `dtype` for the RaggedTensor's `row_splits` tensor. One + of `tf.int32` or `tf.int64`. + name: A name prefix for the returned tensors (optional). + + Returns: + A `RaggedTensor` of dtype `dtype` and ragged rank `output_ragged_rank`. + + Raises: + ValueError: If the input rank is known, `input_ragged_rank` is provided + and `output_ragged_rank` = `input_ragged_rank` + `rank(variant)` does + not hold. + """ + variant = ops.convert_to_tensor( + variant, name="variant", dtype=dtypes.variant) + if (variant.shape.ndims is not None and input_ragged_rank is not None and + output_ragged_rank != input_ragged_rank + variant.shape.ndims): + raise ValueError( + f"Argument `output_ragged_rank` ({output_ragged_rank}) must be equal " + f"to `input_ragged_rank` + `variant.shape.ndims` " + f"({input_ragged_rank} + {variant.shape.ndims}).") + input_ragged_rank = -1 if input_ragged_rank is None else input_ragged_rank + with ops.name_scope( + name, "RaggedFromVariant", + [variant, dtype, input_ragged_rank, output_ragged_rank]): + result = gen_ragged_conversion_ops.ragged_tensor_from_variant( + variant, input_ragged_rank, max(output_ragged_rank, 0), dtype, + row_splits_dtype, name) + return cls.from_nested_row_splits( + result.output_dense_values, + result.output_nested_splits, + validate=False) + + def _to_variant(self, batched_input=False, name=None): + """Converts this `RaggedTensor` into a `variant` Tensor. + + If `batched_input` is `True`, then the `RaggedTensor` is unbatched along the + zero-th dimension, each component `RaggedTensor` is encoded into a scalar + `variant` Tensor, and these are stacked to return a 1-D `variant` Tensor. + If `batched_input` is `False`, then the `RaggedTensor` is encoded as is and + a scalar `variant` Tensor is returned. + + Example: + >>> rt = tf.ragged.constant([[[0]], [[1]], [[2]]]) + >>> rt._to_variant().shape.as_list() + [] + >>> rt._to_variant(batched_input=True).shape.as_list() + [3] + + Args: + batched_input: If `True`, the `RaggedTensor` is unbatched and converted to + a `variant` vector. Set to `False` by default. + name: A name prefix for the returned tensors (optional). + + Returns: + A `variant` Tensor that encodes this `RaggedTensor`. + """ + with ops.name_scope(name, "RaggedToVariant", [self, batched_input]): + return gen_ragged_conversion_ops.ragged_tensor_to_variant( + self.nested_row_splits, self.flat_values, batched_input, name) + + #============================================================================= + # String Encoding + #============================================================================= + def __repr__(self): + if self._is_eager(): + # The np.array2string in _formatter provides a separator argument, but + # doesn't handle recursive calls correctly. The np.printoptions handles + # recursive calls correctly, but doesn't provide a separator argument. + # Combines them together to print elements separated by comma, while + # avoiding the redundant array prefixes and dtypes. For example, + # the value of tf.ragged.constant([[1, 2], [3, 4]]) will look like + # + # [[1, 2], + # [3, 4]] + with np.printoptions(formatter={"all": _formatter}): + value_text = _formatter(self.numpy()) + return f"" + else: + return "tf.RaggedTensor(values=%s, row_splits=%s)" % (self.values, + self.row_splits) + + #============================================================================= + # Eager Execution Mode + #============================================================================= + + def numpy(self): + """Returns a numpy `array` with the values for this `RaggedTensor`. + + Requires that this `RaggedTensor` was constructed in eager execution mode. + + Ragged dimensions are encoded using numpy `arrays` with `dtype=object` and + `rank=1`, where each element is a single row. + + #### Examples + + In the following example, the value returned by `RaggedTensor.numpy()` + contains three numpy `array` objects: one for each row (with `rank=1` and + `dtype=int64`), and one to combine them (with `rank=1` and `dtype=object`): + + >>> tf.ragged.constant([[1, 2, 3], [4, 5]], dtype=tf.int64).numpy() + array([array([1, 2, 3]), array([4, 5])], dtype=object) + + Uniform dimensions are encoded using multidimensional numpy `array`s. In + the following example, the value returned by `RaggedTensor.numpy()` contains + a single numpy `array` object, with `rank=2` and `dtype=int64`: + + >>> tf.ragged.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int64).numpy() + array([[1, 2, 3], [4, 5, 6]]) + + Returns: + A numpy `array`. + """ + if not self._is_eager(): + raise ValueError("RaggedTensor.numpy() is only supported in eager mode.") + values = self.values.numpy() + splits = self.row_splits.numpy() + rows = [values[splits[i]:splits[i + 1]] for i in range(len(splits) - 1)] + if not rows: + return np.zeros((0, 0) + values.shape[1:], dtype=values.dtype) + # Note: if `rows` have ragged lengths, then they will be stored in a + # np.ndarray with dtype=object and rank=1. If they have uniform lengths, + # they will be combined into a single np.ndarray with dtype=row.dtype and + # rank=row.rank+1. + # + # Manually set dtype as numpy now complains when given ragged rows. + has_variable_length_rows = any(len(row) != len(rows[0]) for row in rows) + dtype = np.object_ if has_variable_length_rows else None + return np.array(rows, dtype=dtype) + + def to_list(self): + """Returns a nested Python `list` with the values for this `RaggedTensor`. + + Requires that `rt` was constructed in eager execution mode. + + Returns: + A nested Python `list`. + """ + if not isinstance(self.row_splits, ops.EagerTensor): + raise ValueError("to_list can only be used in eager mode.") + row_splits = self.row_splits.numpy().tolist() + values = self.values + + if isinstance(values, RaggedTensor): + return [ + values[row_splits[i]:row_splits[i + 1]].to_list() + for i in range(len(row_splits) - 1) + ] + else: + # Convert values to a Python list. + if hasattr(values, "numpy"): + values_as_list = values.numpy().tolist() + elif hasattr(values, "to_list"): + values_as_list = values.to_list() + else: + raise ValueError("values must be convertible to a list") + + return [ + values_as_list[row_splits[i]:row_splits[i + 1]] + for i in range(len(row_splits) - 1) + ] + + def _eager_value(self): + """Returns a RaggedTensorValue for self. Requires self._is_eager()=true.""" + value = self.flat_values.numpy() + for row_splits in reversed(self.nested_row_splits): + value = ragged_tensor_value.RaggedTensorValue(value, row_splits.numpy()) + return value + + def _is_eager(self): + """Returns True if values & row_splits Tensors are all `EagerTensor`s.""" + rt = self + while isinstance(rt, RaggedTensor): + if not isinstance(rt.row_splits, ops.EagerTensor): + return False + rt = rt.values + return isinstance(rt, ops.EagerTensor) + + #============================================================================= + # Operators + #============================================================================= + # To avoid circular dependencies, we define stub methods for operators here, + # and then override them when the ragged_operators module is imported. + + def _overloaded_operator(name): # pylint: disable=no-self-argument + + def stub(*args, **kwargs): + del args, kwargs + raise ValueError( + f"You must import 'tensorflow.python.ops.ragged.ragged_ops' " + f"before using RaggedTensor.{name}.") + + return stub + + __getitem__ = _overloaded_operator("__getitem__") + __ge__ = _overloaded_operator("__ge__") + __gt__ = _overloaded_operator("__gt__") + __le__ = _overloaded_operator("__le__") + __lt__ = _overloaded_operator("__lt__") + __and__ = _overloaded_operator("__and__") + __rand__ = _overloaded_operator("__rand__") + __invert__ = _overloaded_operator("__invert__") + __ror__ = _overloaded_operator("__ror__") + __or__ = _overloaded_operator("__or__") + __xor__ = _overloaded_operator("__xor__") + __rxor__ = _overloaded_operator("__rxor__") + __abs__ = _overloaded_operator("__abs__") + __add__ = _overloaded_operator("__add__") + __radd__ = _overloaded_operator("__radd__") + __div__ = _overloaded_operator("__div__") + __rdiv__ = _overloaded_operator("__rdiv__") + __floordiv__ = _overloaded_operator("__floordiv__") + __rfloordiv__ = _overloaded_operator("__rfloordiv__") + __mod__ = _overloaded_operator("__mod__") + __rmod__ = _overloaded_operator("__rmod__") + __mul__ = _overloaded_operator("__mul__") + __rmul__ = _overloaded_operator("__rmul__") + __neg__ = _overloaded_operator("__neg__") + __pow__ = _overloaded_operator("__pow__") + __rpow__ = _overloaded_operator("__rpow__") + __sub__ = _overloaded_operator("__sub__") + __rsub__ = _overloaded_operator("__rsub__") + __truediv__ = _overloaded_operator("__truediv__") + __rtruediv__ = _overloaded_operator("__rtruediv__") + del _overloaded_operator + + #============================================================================= + # Name Scope + #============================================================================= + + # This private function is used by ops.name_scope to ensure that all of the + # input tensors for the scope belong to the same graph. Defining this means + # that you may include `RaggedTensor` objects in the name_scope `values` + # list. + def _as_graph_element(self): + """Convert `self` to a graph element.""" + values = self.values + while isinstance(values, RaggedTensor): + values = values.values + return values + + #============================================================================= + # Composite Tensor + #============================================================================= + + @property + def _type_spec(self): + return RaggedTensorSpec.from_value(self) + + def _shape_invariant_to_type_spec(self, shape): + return RaggedTensorSpec(shape, self.dtype, self.ragged_rank, + self.row_splits.dtype) + + def consumers(self): + return self._consumers() + + __composite_gradient__ = ( + composite_tensor_gradient.WithValuesCompositeTensorGradient()) + + +def is_ragged(value): + """Returns true if `value` is a ragged tensor or ragged tensor value.""" + return isinstance(value, + (RaggedTensor, ragged_tensor_value.RaggedTensorValue)) + + +def match_row_splits_dtypes(*tensors, **kwargs): + """Return a copy of `tensors` with row_splits all having the same dtype. + + Args: + *tensors: A list of Tensors or RaggedTensors. + **kwargs: If 'return_dtype=True', then return a tuple (dtype, tensors), + where `dtype` is the data type used by row-splits, and `tensors` is the + converted list of `Tensors` and `RaggedTensors`. + + Returns: + The converted list of `Tensors` and `RaggedTensors`. + """ + return_dtype = kwargs.pop("return_dtype", False) + if kwargs: + raise ValueError(f"Unexpected keyword args {kwargs}.") + + has_int32 = False + has_int64 = False + for tensor in tensors: + if isinstance(tensor, RaggedTensor): + if tensor.row_splits.dtype == dtypes.int32: + has_int32 = True + else: + has_int64 = True + + if has_int32 and has_int64: + if not ragged_config.auto_cast_partition_dtype(): + raise ValueError("Input RaggedTensors have mismatched row_splits dtypes; " + "use RaggedTensor.with_row_splits_dtype() to convert " + "them to compatible dtypes.") + dtype = dtypes.int64 + tensors = tuple( + t.with_row_splits_dtype(dtypes.int64) if isinstance(t, RaggedTensor + ) else t + for t in tensors) + + elif has_int32: + dtype = dtypes.int32 + else: + dtype = dtypes.int64 + + if return_dtype: + return (dtype, tensors) + else: + return tensors + + +# =============================================================================== +# RaggedTensorSpec +# =============================================================================== +@tf_export("RaggedTensorSpec") +@type_spec_registry.register("tf.RaggedTensorSpec") +class RaggedTensorSpec( + type_spec.BatchableTypeSpec, internal_types.RaggedTensorSpec): + """Type specification for a `tf.RaggedTensor`.""" + + __slots__ = [ + "_shape", "_dtype", "_ragged_rank", "_row_splits_dtype", + "_flat_values_spec" + ] + + @property + def dtype(self): + """The `tf.dtypes.DType` specified by this type for the RaggedTensor. + + Examples: + + >>> rt = tf.ragged.constant([["a"], ["b", "c"]], dtype=tf.string) + >>> tf.type_spec_from_value(rt).dtype + tf.string + + Returns: + A `tf.dtypes.DType` of the values in the RaggedTensor. + """ + return self._dtype + + @property + def shape(self): + """The statically known shape of the RaggedTensor. + + Examples: + + >>> rt = tf.ragged.constant([[0], [1, 2]]) + >>> tf.type_spec_from_value(rt).shape + TensorShape([2, None]) + + >>> rt = tf.ragged.constant([[[0, 1]], [[1, 2], [3, 4]]], ragged_rank=1) + >>> tf.type_spec_from_value(rt).shape + TensorShape([2, None, 2]) + + Returns: + A `tf.TensorShape` containing the statically known shape of the + RaggedTensor. Ragged dimensions have a size of `None`. + """ + return self._shape + + @property + def ragged_rank(self): + """The number of times the RaggedTensor's flat_values is partitioned. + + Defaults to `shape.ndims - 1`. + + Examples: + + >>> values = tf.ragged.constant([[1, 2, 3], [4], [5, 6], [7, 8, 9, 10]]) + >>> tf.type_spec_from_value(values).ragged_rank + 1 + + >>> rt1 = tf.RaggedTensor.from_uniform_row_length(values, 2) + >>> tf.type_spec_from_value(rt1).ragged_rank + 2 + + Returns: + A Python `int` indicating the number of times the underlying `flat_values` + Tensor has been partitioned to add a new dimension. + I.e., `tf.rank(rt) = tf.rank(rt.flat_values) + rt.ragged_rank`. + """ + return self._ragged_rank + + @property + def row_splits_dtype(self): + """The `tf.dtypes.DType` of the RaggedTensor's `row_splits`. + + Examples: + + >>> rt = tf.ragged.constant([[1, 2, 3], [4]], row_splits_dtype=tf.int64) + >>> tf.type_spec_from_value(rt).row_splits_dtype + tf.int64 + + Returns: + A `tf.dtypes.DType` for the RaggedTensor's `row_splits` tensor. One + of `tf.int32` or `tf.int64`. + """ + return self._row_splits_dtype + + @property + def flat_values_spec(self): + """The `TypeSpec` of the flat_values of RaggedTensor. + + Returns: + - The TypeSpec of flat_values. + - None when the flat_values is a Tensor. + """ + return self._flat_values_spec + + @property + def value_type(self): + return RaggedTensor if self._ragged_rank > 0 else tensor_lib.Tensor + + def __init__(self, + shape=None, + dtype=dtypes.float32, + ragged_rank=None, + row_splits_dtype=dtypes.int64, + flat_values_spec=None): + """Constructs a type specification for a `tf.RaggedTensor`. + + Args: + shape: The shape of the RaggedTensor, or `None` to allow any shape. If a + shape is specified, then all ragged dimensions must have size `None`. + dtype: `tf.DType` of values in the RaggedTensor. + ragged_rank: Python integer, the number of times the RaggedTensor's + flat_values is partitioned. Defaults to `shape.ndims - 1`. + row_splits_dtype: `dtype` for the RaggedTensor's `row_splits` tensor. One + of `tf.int32` or `tf.int64`. + flat_values_spec: TypeSpec for flat_value of the RaggedTensor. It shall be + provided when the flat_values is a CompositeTensor rather then Tensor. + If both `dtype` and `flat_values_spec` and are provided, `dtype` must + be the same as `flat_values_spec.dtype`. (experimental) + """ + self._shape = tensor_shape.as_shape(shape) + self._row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + if flat_values_spec is not None: + if dtype is None: + dtype = flat_values_spec.dtype + elif dtype != flat_values_spec.dtype: + raise ValueError("dtype must be the same as flat_values_spec.dtype") + elif dtype is None: + raise ValueError( + "At least one of dtype or flat_values_spec must be provided") + self._dtype = dtypes.as_dtype(dtype) + self._flat_values_spec = flat_values_spec + + rank = self._shape.ndims + if ragged_rank is None: + if rank is None: + raise ValueError("Must specify ragged_rank or " + "a shape with a known rank.") + ragged_rank = rank - 1 + self._ragged_rank = ragged_rank + if not isinstance(self._ragged_rank, int): + raise TypeError(f"Argument `ragged_rank` must be an int. " + f"Received {ragged_rank}.") + + if rank is not None: + if ragged_rank >= rank: + raise ValueError(f"Argument `ragged_rank` ({ragged_rank}) must be less " + f"than rank ({rank}).") + + def is_compatible_with(self, spec_or_value): + # RaggedTensor with ragged_rank 0 can be compatible with raw flat_values. + if self._ragged_rank == 0: + if self._flat_values_spec is None: + if isinstance( + spec_or_value, (tensor_lib.Tensor, tensor_lib.TensorSpec)): + return tensor_lib.TensorSpec( + self._shape, self._dtype).is_compatible_with(spec_or_value) + elif not isinstance(spec_or_value, (RaggedTensor, RaggedTensorSpec)): + return self._flat_values_spec.is_compatible_with(spec_or_value) + return super(RaggedTensorSpec, self).is_compatible_with(spec_or_value) + + def _serialize(self): + if self._flat_values_spec is None: + return (self._shape, self._dtype, self._ragged_rank, + self._row_splits_dtype) + else: + return (self._shape, self._dtype, self._ragged_rank, + self._row_splits_dtype, self._flat_values_spec) + + @property + def _component_specs(self): + if self._ragged_rank <= 0: + if self._flat_values_spec is not None: + return [self._flat_values_spec] + else: + return [tensor_lib.TensorSpec(self._shape, self._dtype)] + + flat_values_spec = self._flat_values_spec + if flat_values_spec is None: + flat_values_shape = tensor_shape.TensorShape([None]).concatenate( + self._shape[self._ragged_rank + 1:]) + flat_values_spec = tensor_lib.TensorSpec(flat_values_shape, self._dtype) + outer_dim = tensor_shape.dimension_at_index(self._shape, 0) + outer_splits_shape = [None if outer_dim is None else outer_dim + 1] + inner_splits_spec = tensor_lib.TensorSpec([None], self._row_splits_dtype) + + specs = ([ + flat_values_spec, + tensor_lib.TensorSpec(outer_splits_shape, self._row_splits_dtype) + ] + [inner_splits_spec for _ in range(self._ragged_rank - 1)]) + return specs + + def _to_components(self, value): + if is_ragged(value): + return [value.flat_values] + list(value.nested_row_splits) + else: + return [value] + + def _from_components(self, tensor_list): + result = tensor_list[0] + if (all(isinstance(t, np.ndarray) for t in tensor_list) and + not tf2.enabled()): + for row_splits in reversed(tensor_list[1:]): + result = ragged_tensor_value.RaggedTensorValue(result, row_splits) + else: + if isinstance(tensor_list[0], np.ndarray): + tensor_list = [ops.convert_to_tensor(t) for t in tensor_list] + result = tensor_list[0] + for row_splits in reversed(tensor_list[1:]): + result = RaggedTensor( + result, + RowPartition.from_row_splits(row_splits, validate=False), + internal=True) + if self._shape.ndims is not None: + if isinstance(result, RaggedTensor): + result._set_shape(self._shape) # pylint: disable=protected-access + # TODO(xjun): MaskedTensor doesn't implement set_shape. + if self.flat_values_spec is not None and hasattr(result.flat_values, + "set_shape"): + result.flat_values.set_shape(self.flat_values_spec.shape) + elif isinstance(result, tensor_lib.Tensor): + result.set_shape(self._shape) + return result + + # The RaggedTensorSpec tensor_list encoding uses to/from_variant ops + # to (un)box the component tensors in a way that allows for batching & + # unbatching. + @property + def _flat_tensor_specs(self): + # NOTE(mishragaurav): The default flat shape of a boxed `RaggedTensor` is + # `[]` (scalar), but a `RaggedTensorSpec` can also represent a batch of + # boxed `RaggedTensor` objects with shape `(...)` (and batches of batches, + # etc.), so the flat shape must be unknown. + return [tensor_lib.TensorSpec(None, dtypes.variant)] + + def _to_tensor_list(self, value): + # TODO(edloper): Update gen_ragged_conversion_ops that convert to and + # from variant to include all of the row-partitioning tensors. + if self._flat_values_spec is not None: + raise ValueError("Customized value_type is not supported.") + if isinstance(value, RaggedTensor): + if value.ragged_rank != self._ragged_rank: + raise ValueError( + f"Ragged rank of value {value.ragged_rank} does not match " + f"ragged rank of type {self._ragged_rank}.") + # pylint: disable=protected-access + return [value._to_variant(batched_input=False)] + else: + if self._ragged_rank > 0: + raise ValueError( + f"Expected a RaggedTensor if ragged rank={self._ragged_rank}" + f" but got {type(value).__name__}." + ) + return [ + gen_ragged_conversion_ops.ragged_tensor_to_variant( + (), value, batched_input=False) + ] + + def _to_batched_tensor_list(self, value): + if self._flat_values_spec is not None: + raise ValueError("Customized value_type is not supported.") + if isinstance(value, RaggedTensor): + if value.ragged_rank != self._ragged_rank: + raise ValueError( + f"Ragged rank of value {value.ragged_rank} does not match " + f"ragged rank of type {self._ragged_rank}.") + # pylint: disable=protected-access + return [value._to_variant(batched_input=True)] + else: + if self._ragged_rank > 0: + raise ValueError( + f"Expected a RaggedTensor if ragged rank={self._ragged_rank}" + f" but got {type(value).__name__}." + ) + return [ + gen_ragged_conversion_ops.ragged_tensor_to_variant( + rt_nested_splits=(), rt_dense_values=value, batched_input=True) + ] + + def _from_compatible_tensor_list(self, tensor_list): + if self._flat_values_spec is not None: + raise ValueError("Customized value_type is not supported.") + result = RaggedTensor._from_variant( # pylint: disable=protected-access + tensor_list[0], + dtype=self._dtype, + row_splits_dtype=self._row_splits_dtype, + output_ragged_rank=self._ragged_rank) + if self._shape.ndims is not None: + if isinstance(result, RaggedTensor): + result._set_shape(self._shape) # pylint: disable=protected-access + # TODO(xjun): MaskedTensor doesn't implement set_shape. + if self.flat_values_spec is not None and hasattr(self.flat_values, + "set_shape"): + result.flat_values.set_shape(self.flat_values_spec.shape) + else: + result.set_shape(self._shape) + return result + + def _batch(self, batch_size): + if self._flat_values_spec is not None: + raise ValueError("Customized value_type is not supported.") + return RaggedTensorSpec( + tensor_shape.TensorShape([batch_size]).concatenate(self._shape), + self._dtype, self._ragged_rank + 1, self._row_splits_dtype) + + def _unbatch(self): + if self._flat_values_spec is not None: + raise ValueError("Customized value_type is not supported.") + # Note: Negative ragged_rank is allowed here because the dataset could be + # subsequently batched again. If ragged_rank > 1, assume row_splits_dtype is + # consistent. Errors are handled in + # RaggedTensorSpec._from_compatible_tensor_list() + return RaggedTensorSpec(self._shape[1:], self._dtype, self._ragged_rank - 1, + self._row_splits_dtype) + + def _to_legacy_output_types(self): + return self._dtype + + def _to_legacy_output_shapes(self): + return self._shape + + def _to_legacy_output_classes(self): + return self + + @classmethod + def from_value(cls, value): + if (isinstance(value, ragged_tensor_value.RaggedTensorValue) or + isinstance(value.flat_values, tensor_lib.Tensor)): + return cls( + shape=value.shape, + dtype=value.values.dtype, + ragged_rank=value.ragged_rank, + row_splits_dtype=value.row_splits.dtype) + else: + flat_values_spec = type_spec.type_spec_from_value(value.flat_values) + # Relax shape[0] to None, as it is connected to dynamic ragged shapes. + flat_values_spec = flat_values_spec._unbatch()._batch(None) # pylint: disable=protected-access + return cls( + shape=value.shape, + dtype=value.values.dtype, + ragged_rank=value.ragged_rank, + row_splits_dtype=value.row_splits.dtype, + flat_values_spec=flat_values_spec) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + RaggedTensorSpec, struct_pb2.TypeSpecProto.RAGGED_TENSOR_SPEC + ) +) + + +type_spec.register_type_spec_from_value_converter( + ragged_tensor_value.RaggedTensorValue, RaggedTensorSpec.from_value) + + +# =============================================================================== +# Convert value -> tensor +# =============================================================================== +def convert_to_tensor_or_ragged_tensor(value, + dtype=None, + preferred_dtype=None, + name=None): + """Converts value to a `RaggedTensor` or `Tensor`. + + * If `value` is a `RaggedTensor`, then return it as-is. + * If `value` is a `RaggedTensorValue`, return a corresponding constant + `RaggedTensor`. + * Otherwise, use `convert_to_tensor` to convert `value` to a `Tensor`. + + Args: + value: A `RaggedTensor`, a `RaggedTensorValue`, or an object whose type has + a registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing the type + is inferred from the type of `value`. + preferred_dtype: Optional element type for the returned tensor, used when + dtype is None. This argument has no effect if `value` is already a + tensor, or when conversion is not possible. + name: Optional name to use if a new `Tensor` is created. + + Returns: + A `Tensor` or `RaggedTensor`. + """ + if isinstance(value, RaggedTensor): + if dtype and not dtype.is_compatible_with(value.dtype): + raise ValueError(f"Tensor conversion requested dtype {dtype.name} for " + f"RaggedTensor with dtype {value.dtype.name}: {value}.") + return value + elif isinstance(value, ragged_tensor_value.RaggedTensorValue): + with ops.name_scope(name, "ConvertToTensorOrRaggedTensor", []): + flat_values = ops.convert_to_tensor( + value=value.flat_values, + dtype=dtype, + dtype_hint=preferred_dtype, + name="flat_values") + return RaggedTensor.from_nested_row_splits( + flat_values, value.nested_row_splits, validate=False) + else: + return tensor_conversion.convert_to_tensor_v2_with_dispatch( + value=value, dtype=dtype, dtype_hint=preferred_dtype, name=name + ) + + +def _convert_to_ragged_tensor_values(value): + """Converts value to supported RaggedTensor value. + + * If `value` is an object of supported value type, then return it as-is. + * Otherwise convert it to Tensor or RaggedTensor. + + Args: + value: An object of `Tensor`, `RaggedTensor` or registerred RaggedTensor + value types, or an object whose type has a registered `Tensor` conversion + function. + + Returns: + An object of `Tensor`, `RaggedTensor` or registerred RaggedTensor + value types + """ + if _is_supported_ragged_values_type(value): + return value + else: + return convert_to_tensor_or_ragged_tensor(value, name="values") + + +# =============================================================================== +# Register RaggedTensor for use with session.run. +# =============================================================================== +def _ragged_tensor_value_from_components(components): + components = list(components) + value = components.pop() + while components: + value = ragged_tensor_value.RaggedTensorValue(value, components.pop()) + return value + + +def _ragged_tensor_session_fetch(rt): + components = rt.nested_row_splits + (rt.flat_values,) + return (components, _ragged_tensor_value_from_components) + + +def _ragged_tensor_session_feed(feed_key, feed_val): + key_components = feed_key.nested_row_splits + (feed_key.flat_values,) + val_components = feed_val.nested_row_splits + (feed_val.flat_values,) + return zip(key_components, val_components) + + +def _ragged_tensor_session_feed_for_partial_run(feed_key): + return feed_key.nested_row_splits + (feed_key.flat_values,) + + +session.register_session_run_conversion_functions( + RaggedTensor, _ragged_tensor_session_fetch, _ragged_tensor_session_feed, + _ragged_tensor_session_feed_for_partial_run) + + +# =============================================================================== +# RaggedTensorType +# =============================================================================== +class RaggedTensorType: + """Encoding of a static type for a `RaggedTensor`. + + Use this type to express/declare that an output must have the type of + `RaggedTensor`. + """ + + def __init__(self, dtype, ragged_rank, row_splits_dtype=dtypes.int64): + """Initializes a RaggedTensorType object. + + Args: + dtype: data type of the `RaggedTensor`'s inner values. + ragged_rank: ragged_rank of the declared `RaggedTensor`. + row_splits_dtype: data type for the `RaggedTensor`'s row splits. + One of: `tf.int32` or `tf.int64`. + """ + row_splits_dtype = dtypes.as_dtype(row_splits_dtype) + self._dtype = dtype + self._ragged_rank = ragged_rank + self._row_splits_dtype = row_splits_dtype + + dtype = property(lambda self: self._dtype) + ragged_rank = property(lambda self: self._ragged_rank) + row_splits_dtype = property(lambda self: self._row_splits_dtype) + + def __repr__(self): + return "RaggedTensorType(%r, %r, %r)" % (self.dtype, self.ragged_rank, + self.row_splits_dtype) + + +# =============================================================================== +# Helper Functions +# =============================================================================== +def _assert_sparse_indices_are_ragged_right(indices): + """Checks that the given SparseTensor.indices tensor is ragged-right. + + Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right + because the entry `[3, 1]` skips a cell. + + Args: + indices: The SparseTensor indices to check. + + Returns: + A list of control dependency op tensors. + """ + index_prefix = indices[:, :-1] + index_suffix = indices[:, -1] + + # Check whether each index is starting a new row in the innermost dimension + # (prefix[i] != prefix[i-1]) or continuing a row (prefix[i] == prefix[i-1]). + # (Note: this skips the first index; we will check that separately below.) + index_prefix_changed = math_ops.reduce_any( + math_ops.not_equal(index_prefix[1:], index_prefix[:-1]), axis=1) + + # Check two cases: + # * For indices that start a new row: index_suffix[i] must be zero. + # * For indices that continue a row: index_suffix[i] must be equal to + # index_suffix[i-1]+1. + index_ok = array_ops.where( + index_prefix_changed, math_ops.equal(index_suffix[1:], 0), + math_ops.equal(index_suffix[1:], index_suffix[:-1] + 1)) + + # Also check that the very first index didn't skip any cells. The first + # index starts a new row (by definition), so its suffix should be zero. + sparse_indices_are_ragged_right = math_ops.logical_and( + math_ops.reduce_all(math_ops.equal(index_suffix[:1], 0)), + math_ops.reduce_all(index_ok)) + + message = [ + "SparseTensor is not right-ragged", "SparseTensor.indices =", indices + ] + return [control_flow_assert.Assert(sparse_indices_are_ragged_right, message)] + + +@ops.RegisterGradient("RaggedTensorToSparse") +def _ragged_tensor_to_sparse_gradient(op, unused_sparse_indices_grad, + sparse_values_grad, + unused_sparse_shape_grad): + """Gradient for RaggedTensorToSparse.""" + op_inputs_nested_row_splits = op.inputs[:-1] + op_inputs_flat_values = op.inputs[-1] + + # No gradient for the RaggedTensor's nested_row_splits. + nested_row_splits_gradient = [None] * len(op_inputs_nested_row_splits) + + # Gradient for the RaggedTensor's flat_values is formed by reshaping + # the gradient for the SparseTensor's values. + flat_values_shape = array_ops.shape(op_inputs_flat_values) + flat_values_gradient = array_ops.reshape(sparse_values_grad, + flat_values_shape) + + return nested_row_splits_gradient + [flat_values_gradient] + + +def _assert_monotonic_increasing(tensor, message=None): + return check_ops.assert_non_negative( + tensor[1:] - tensor[:-1], message=message) + + +def _assert_zero(tensor, message=None): + return check_ops.assert_equal( + tensor, constant_op.constant(0, dtype=tensor.dtype), message=message) + + +def _nrows(tensor, out_type=dtypes.int32): + if isinstance(tensor, RaggedTensor): + return tensor.nrows(out_type=out_type) + else: + return array_ops.shape(tensor, out_type=out_type)[0] + + +def merge_dims(value, outer_axis, inner_axis): + """Merges value[outer_axis...inner_axis] into a single dimension. + + See `RaggedTensor.merge_dims()` for more details. This helper differs from + `RaggedTensor.merge_dims()` in that `value` may be a dense or ragged tensor. + + Args: + value: A `RaggedTensor` or `Tensor` + outer_axis: `int` + inner_axis: `int` + + Returns: + A flattened `RaggedTensor` or `Tensor`. + """ + if outer_axis == inner_axis: + return value + + # Flatten outer dimensions of a RaggedTensor by just taking its values. + while outer_axis == 0 and isinstance(value, RaggedTensor): + value = value.values + inner_axis -= 1 + if inner_axis == 0: + return value + + # Flatten non-Ragged tensors using tf.reshape(). + if not isinstance(value, RaggedTensor): + if value.shape.is_fully_defined(): + old_shape = value.shape.as_list() + new_shape = old_shape[:outer_axis] + [-1] + old_shape[inner_axis + 1:] + else: + old_shape = array_ops.shape(value) + new_shape = array_ops.concat( + [old_shape[:outer_axis], [-1], old_shape[inner_axis + 1:]], axis=0) + return array_ops.reshape(value, new_shape) + + # Handle outer_axis>1 via recursion. + if outer_axis > 1: + return value.with_values( + merge_dims(value.values, outer_axis - 1, inner_axis - 1)) + + # At this point, we know outer_axis == 1, and value is a RaggedTensor. + # So we need to flatten the values and build a corresponding splits tensor. + new_values = value.values + new_splits = value.row_splits + for axis in range(outer_axis, inner_axis): + if isinstance(new_values, RaggedTensor): + # Flatten a single ragged dimension. + new_splits = array_ops.gather(new_values.row_splits, new_splits) + new_values = new_values.values + else: + # Flatten all remaining dense dimensions. + shape_split = inner_axis - axis + 1 + if new_values.shape.is_fully_defined(): + old_shape = new_values.shape.as_list() + new_shape = [-1] + old_shape[shape_split:] + flat_size = _prod(old_shape[1:shape_split]) + else: + old_shape = array_ops.shape(new_values) + new_shape = array_ops.concat([[-1], old_shape[shape_split:]], axis=0) + flat_size = math_ops.cast( + math_ops.reduce_prod(old_shape[1:shape_split]), new_splits.dtype) + new_values = array_ops.reshape(new_values, new_shape) + new_splits = new_splits * flat_size + break + return RaggedTensor.from_row_splits(new_values, new_splits) + + +def _prod(lst): + """Returns the product of the numbers in a list.""" + return functools.reduce(operator.mul, lst, 1) + + +def _get_row_partition_type_tensor_pairs_tail(partition): + """Gets a row partition type tensor pair for the tail. + + If value_rowid is defined, then it is used. Otherwise, row_splits + are used. + + Args: + partition: a RowPartition. + + Returns: + A list of (row_partition_type, row_partition_tensor) pairs. + """ + if partition._has_precomputed_value_rowids(): # pylint: disable=protected-access + return ("VALUE_ROWIDS", partition.value_rowids()) + else: + return ("ROW_SPLITS", partition.row_splits()) + + +def _get_row_partition_type_tensor_pairs(rt_input): + """Gets a list of the row partitions for rt_input. + + If value_rowids are defined, then they are used. Otherwise, row_splits + are used. If the outermost level has value_rowids defind, then nrows is + also added. + + Args: + rt_input: a ragged tensor. + + Returns: + A list of (row_partition_type, row_partition_tensor) pairs. + """ + partitions = rt_input._nested_row_partitions # pylint: disable=protected-access + tail = [_get_row_partition_type_tensor_pairs_tail(x) for x in partitions[1:]] + + if partitions[0]._value_rowids is not None: # pylint: disable=protected-access + return [("FIRST_DIM_SIZE", partitions[0].nrows()), + ("VALUE_ROWIDS", partitions[0].value_rowids())] + tail + else: + return [("ROW_SPLITS", partitions[0].row_splits())] + tail + + +def _shape_as_tensor(shape, dtype): + """Takes shape and coerces it to a shape as a tensor. + + If the object is already a tensor, simply passes it on (result is guaranteed + to be int64 or int32, but not necessarily dtype). + If not, creates a tensor of type dtype. + + Result is either a scalar equal to -1 if the shape is unknown_rank. + Otherwise, it is a vector, where unknown dimensions are represented with a + value of -1. + + In C++, see TensorShapeFromTensor for parsing shapes in kernels, and + InferenceContext::MakeShapeFromShapeTensorTreatScalarAsUnknownShape, for + use in the shape inference function. + + Args: + shape: input to coerce from TensorShape, Tensor, None, List[Optional[Int]], + Tuple[Optional[Int]]. + dtype: tf.int64 or tf.int32 + + Returns: + a scalar or vector tensor of dtype tf.int32 or tf.int64. + """ + if dtype != dtypes.int64 and dtype != dtypes.int32: + raise ValueError(f"Expected int64 or int32 for dtype: got {dtype}.") + + if isinstance(shape, tensor_lib.Tensor): + if shape.dtype != dtypes.int64 and shape.dtype != dtypes.int32: + return math_ops.cast(shape, dtype) + return shape + shape = tensor_shape.as_shape(shape) + if not shape: + # Imply rank is unknown using a -1 scalar. + return constant_op.constant(-1, dtype=dtype) + shape = [(-1 if x is None else x) for x in shape.as_list()] + # At this point, shape is List[Int]. + return constant_op.constant(shape, dtype=dtype) + + +def _nvals_uniform_row_length(values, uniform_row_length): + """Get the number of values for uniform row length constructor.""" + const_nvals = tensor_shape.dimension_at_index(values.shape, 0).value + if const_nvals is not None: + nvals = constant_op.constant(const_nvals, uniform_row_length.dtype) + elif isinstance(values, RaggedTensor): + nvals = values.nrows(out_type=uniform_row_length.dtype) + else: + nvals = array_ops.shape(values, out_type=uniform_row_length.dtype)[0] + return nvals + + +def _get_optional_partition_dtype(values): + """Returns the partition dtype, or None if None exists.""" + if isinstance(values, RaggedTensor): + # pylint: disable=protected-access + return values._row_partition.dtype + return None + + +_SUPPORTED_RAGGED_VALUE_TYPES = (tensor_lib.Tensor, RaggedTensor) + + +# TODO(edloper): Consider whether we should change the registry to be on +# TypeSpecs rather than ValueTypes. +def _add_supported_value_type(cls): + """Register the `cls` as supported value type of RaggedTenosr. + + The cls must be a subclass of CompositeTensor, and must support: + - Spec: + The Spec must be a `BatchableTypeSpec` + - Properties: + - x.shape + - x.dtype + - Methods: + - x.__getitem__(idx) (method: returns a supported value type) + - x.set_shape(shape) + - Ops: + - tf.shape(x) -- tf.shape(x)[0] must be a tf.Tensor. + - tf.tile(x) + - assert_rank_at_least(x) + - tf.ones_like(x) + - tf.gather(params=x, indices=Tensor) + - tf.add(x, y) + - tf.boolean_mask(x, ...) + - @TODO(edloper): Complete this list + + Note: the following RaggedTensor, RaggedTensorSpec methods & ops are not + currently supported unless `rt.values` is a RaggedTensor or a tf.Tensor: + - rt.to_tensor() + - rt.to_sparse_tensor() + - rt._to_variant() + - rt._from_variant() + - tf.ragged.cross([rt]) + - tf.gather(params=x, indices=rt) # rt used for indices + - RaggedTensorSpec methods: + - _batch + - _unbatch + - _to_tensor_list + - _to_batched_tensor_list + - _from_compatible_tensor_list + + Args: + cls: The type to be added to supported value types. + """ + if not issubclass(cls, composite_tensor.CompositeTensor): + raise ValueError(f"cls ({cls}) must be a subclass of CompositeTensor.") + if not hasattr(cls, "shape"): + raise ValueError("cls must support the `shape` property.") + if not hasattr(cls, "dtype"): + raise ValueError("cls must support the `dtype` property.") + global _SUPPORTED_RAGGED_VALUE_TYPES + _SUPPORTED_RAGGED_VALUE_TYPES += (cls,) + + +def _is_supported_ragged_values_type(value): + return isinstance(value, _SUPPORTED_RAGGED_VALUE_TYPES) + + +def _assert_is_supported_ragged_values_type(value): + if not _is_supported_ragged_values_type(value): + ok_types = ", ".join(cls.__name__ for cls in _SUPPORTED_RAGGED_VALUE_TYPES) + raise TypeError(f"type(values) must be one of: {ok_types}, got {value}.") + + +def _formatter(x): + """Separate Numpy array elements with comma.""" + if isinstance(x, np.ndarray): + if x.size != 0: + return np.array2string(x, separator=", ") + else: + # When x.size==0, np.array2string always returns `[]`. This isn't always + # what we want. E.g., if `x.shape=[0, 3]`, then we want `[[], [], []]`. + return repr(x.tolist()) + else: + return str(x) + +# Type annotation indicating that a value is ragged. Includes RaggedTensor +# as well as the (deprecated) RaggedTensorValue class from TF 1.x. +Ragged = typing.Union[RaggedTensor, ragged_tensor_value.RaggedTensorValue] + +# Type annotation indicating that a value is a ragged tensor, a dense tensor, +# or a value that can be converted to a tensor (e.g. np.array). +# TODO(edloper): Add Variable to TensorLike, and remove it from here. +RaggedOrDense = typing.Union[Ragged, core_types.TensorLike] + +# RaggedTensor must import ragged_ops to ensure that all dispatched ragged ops +# are registered. Ragged ops import RaggedTensor, so import at bottom of the +# file to avoid a partially-initialized module error. +from tensorflow.python.ops.ragged import ragged_ops # pylint: disable=unused-import, g-bad-import-order, g-import-not-at-top diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_shape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb0c56e8ed6447fff091fc7ff2a1dc81d14c01c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_shape.py @@ -0,0 +1,628 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Shapes & broadcasting for RaggedTensors.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_array_ops +from tensorflow.python.ops.ragged import ragged_config +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_util + + +class RaggedTensorDynamicShape: + """A collection of tensors encoding the shape of a potentially ragged tensor. + + Each `RaggedTensorDynamicShape` consists of an ordered list of dimension + sizes. There are two dimension types: + + * "Uniform dimensions" are dimensions where all slices have the same + length. `RaggedTensorDynamicShape` records the size of each uniform + dimension using a single scalar integer. + + * "Ragged dimensions" are dimensions whose slices may have different + lengths. `RaggedTensorDynamicShape` records the size of each ragged + dimension using an integer vector containing the slice lengths for all + the slices across that dimension. + + Furthermore, there are two ways a dimension might be encoded: + + * "Partitioned dimensions" are dimensions that are encoded using a + `RaggedTensor`'s `nested_row_splits`. The outermostmost partitioned + dimension must be uniform, and the innermost partitioned dimension must + be ragged. + + * "Inner dimensions" are dimensions that are encoded using a + `RaggedTensor`'s `flat_values`. Inner dimensions are always uniform. + + The sizes of partitioned dimensions are recorded using `partitioned_dim_sizes` + and `inner_dim_sizes`: + + * `partitioned_dim_sizes` is a list of tensors (one for each partitioned + dimension). + + * For uniform dimensions, the tensor is an integer scalar specifying the + size of all slices across that dimension. + * For ragged dimensions, the tensor is an integer vector specifying the + size of each slice across that dimension. + + * `inner_dim_sizes` is a single integer vector, where each element + specifies the size of a single inner dimension. + + Examples: + + Tensor | Ragged | Partitioned Dim Sizes | Inner Dim + : Rank : : Sizes + ------------------------------ | ------ | ---------------------- | ---------- + `[[1, 2, 3], [4, 5, 6]]` | 0 | | `2, 3` + `[[1, 2], [], [3, 4, 5]]` | 1 | `3, (2, 0, 3)` | + `[[[1, 2], [3, 4]], [[5, 6]]]` | 1 | `2, (2, 1)` | 2 + `[[[1, 2], [3]], [[4, 5]]]` | 2 | `2, (2, 1), (2, 1, 2)` | + """ + + def __init__(self, partitioned_dim_sizes, inner_dim_sizes, + dim_size_dtype=None): + """Creates a RaggedTensorDynamicShape. + + Args: + partitioned_dim_sizes: A `list` of 0-D or 1-D integer `Tensor`, one for + each partitioned dimension. If dimension `d` is uniform, then + `partitioned_dim_sizes[d]` must be an integer scalar, specifying the + size of all slices across dimension `d`. If dimension `d` is ragged, + then `partitioned_dim_sizes[d]` must be an integer vector, specifying + the size of each slice across dimension `d`. + inner_dim_sizes: A 1-D integer `Tensor`, whose length is equal to the + number of inner dimensions. `inner_dim_sizes[n]` is the size of all + slices across the `n`th inner dimension (which is the + `(len(partitioned_dim_sizes)+n)`th dimension in the overall tensor. + dim_size_dtype: dtype for dimension sizes. If not specified, then it + is chosen based on the dtypes of `partitioned_dim_sizes` and + `inner_dim_sizes`. + """ + assert isinstance(partitioned_dim_sizes, (list, tuple)) + + with ops.name_scope(None, 'RaggedTensorDynamicShape', + (partitioned_dim_sizes, inner_dim_sizes)): + partitioned_dim_sizes = tuple( + ops.convert_to_tensor(size, name='partitioned_dimension_size_%d' % i) + for (i, size) in enumerate(partitioned_dim_sizes)) + inner_dim_sizes = ops.convert_to_tensor( + inner_dim_sizes, name='inner_dim_sizes') + + # Validate shapes. + if partitioned_dim_sizes: + for axis, dimension_size in enumerate(partitioned_dim_sizes): + if dimension_size.shape.ndims is None: + raise ValueError( + 'rank of partitioned_dim_sizes[%d] is unknown' % axis) + dimension_size.shape.with_rank_at_most(1) + if partitioned_dim_sizes[0].shape.ndims == 1: + raise ValueError('outermost partitioned dimension must be uniform') + if partitioned_dim_sizes[-1].shape.ndims == 0: + raise ValueError('innermost partitioned dimension must be ragged') + inner_dim_sizes.shape.assert_has_rank(1) + + # Convert dimension size tensors to a single dtype. + if dim_size_dtype is None: + dim_size_dtypes = set( + p.dtype for p in partitioned_dim_sizes if p.shape.ndims == 1) + if not dim_size_dtypes: + dim_size_dtype = dtypes.int64 + elif len(dim_size_dtypes) == 1: + dim_size_dtype = dim_size_dtypes.pop() + else: + if not ragged_config.auto_cast_partition_dtype(): + raise ValueError('partitioned_dim_sizes must have matching dtypes') + dim_size_dtype = dtypes.int64 + partitioned_dim_sizes = tuple(math_ops.cast(p, dim_size_dtype) + for p in partitioned_dim_sizes) + inner_dim_sizes = math_ops.cast(inner_dim_sizes, dim_size_dtype) + + self._partitioned_dim_sizes = partitioned_dim_sizes + self._inner_dim_sizes = inner_dim_sizes + + def __repr__(self): + return ('RaggedTensorDynamicShape' + '(partitioned_dim_sizes=%r, inner_dim_sizes=%r)' % + (self._partitioned_dim_sizes, self._inner_dim_sizes)) + + @staticmethod + def from_dim_sizes(dim_sizes): + """Constructs a ragged shape from a list of dimension sizes. + + This list contains a single tensor for each dimension, where the tensor + is a scalar if the dimension is uniform, or a vector if the dimension is + ragged. + + Args: + dim_sizes: List of int32 or int64 scalars or vectors. + + Returns: + A RaggedTensorDynamicShape. + """ + with ops.name_scope(None, 'RaggedTensorDynamicShapeFromDimensionSizes', + [dim_sizes]): + dim_sizes = tuple( + ops.convert_to_tensor(size, preferred_dtype=dtypes.int64, + name='dim_sizes') for size in dim_sizes) + # Split the dimensions into partitioned & inner dimensions. + inner_split = 0 + for dim, dim_size in enumerate(dim_sizes): + if dim_size.shape.ndims == 1: + inner_split = dim + 1 + elif dim_size.shape.ndims != 0: + raise ValueError('Each dim_size must be a scalar or a vector') + return RaggedTensorDynamicShape(dim_sizes[:inner_split], + dim_sizes[inner_split:]) + + @classmethod + def from_tensor(cls, rt_input, dim_size_dtype=None): + """Constructs a ragged shape for a potentially ragged tensor.""" + with ops.name_scope(None, 'RaggedTensorDynamicShapeFromTensor', [rt_input]): + rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input) + if not ragged_tensor.is_ragged(rt_input): + return cls([], array_ops.shape(rt_input), dim_size_dtype=dim_size_dtype) + else: + partitioned_dim_sizes = ( + (rt_input.nrows(),) + rt_input.nested_row_lengths()) + return RaggedTensorDynamicShape( + partitioned_dim_sizes, + array_ops.shape(rt_input.flat_values)[1:], + dim_size_dtype=dim_size_dtype) + + def dimension_size(self, axis): + """Returns the size of slices across the specified dimension.""" + if not isinstance(axis, int): + raise TypeError('axis must be an integer') + partitioned_ndims = len(self._partitioned_dim_sizes) + if axis < partitioned_ndims: + return self._partitioned_dim_sizes[axis] + else: + return self._inner_dim_sizes[axis - partitioned_ndims] + + def is_ragged(self, axis): + """Returns true if the indicated dimension is ragged.""" + if not isinstance(axis, int): + raise TypeError('axis must be an integer') + rank = self.rank + if axis < 0: + raise ValueError('Negative axis values are not supported') + elif rank is not None and axis >= rank: + raise ValueError('Expected axis=%s < rank=%s' % (axis, rank)) + else: + return (axis > 0 and axis < len(self._partitioned_dim_sizes) and + self._partitioned_dim_sizes[axis].shape.ndims == 1) + + @property + def rank(self): + """The number of dimensions in this shape, or None if unknown.""" + inner_ndims = tensor_shape.dimension_value(self._inner_dim_sizes.shape[0]) + if inner_ndims is None: + return None + else: + return len(self._partitioned_dim_sizes) + inner_ndims + + @property + def partitioned_dim_sizes(self): + """The partitioned dimension sizes for this shape. + + Returns: + A `list` of 0-D or 1-D integer `Tensor`. + """ + return self._partitioned_dim_sizes + + @property + def inner_dim_sizes(self): + """The inner dimension sizes for this shape. + + Returns: + A 1-D integer `Tensor`. + """ + return self._inner_dim_sizes + + @property + def num_partitioned_dimensions(self): + """The number of partitioned dimensions in this shape.""" + return len(self._partitioned_dim_sizes) + + @property + def num_inner_dimensions(self): + """The number of inner dimensions, or `None` if not statically known.""" + return tensor_shape.dimension_value(self._inner_dim_sizes.shape[0]) + + @property + def dim_size_dtype(self): + """DType used by this shape for dimension sizes.""" + return self._inner_dim_sizes.dtype + + def broadcast_to_rank(self, rank): + """Adds leading size-1 dimensions to broadcast `self` to the given rank. + + E.g., if `shape1` is `[3, (D2), 4]`, then `shape1.broadcast_to_rank(5)` + is `[1, 1, 3, (D2), 4]`. + + Args: + rank: The rank for the returned shape. + + Returns: + A RaggedTensorDynamicShape with `rank` dimensions, whose inner dimensions + have the same size as `self` and whose outer dimensions have size `1`. + + Raises: + ValueError: If `self.rank` is unknown or greater than `rank`. + """ + if self.rank is None: + raise ValueError('Unable to broadcast: self.rank is unknown') + dims_to_add = rank - self.rank + if dims_to_add < 0: + raise ValueError('Unable to broadcast: rank=%d must be greater than ' + 'self.rank=%d.' % (rank, self.rank)) + elif dims_to_add == 0: + return self + elif self._partitioned_dim_sizes: + partitioned_dims = (1,) * dims_to_add + self._partitioned_dim_sizes + return RaggedTensorDynamicShape(partitioned_dims, self.inner_dim_sizes, + self.dim_size_dtype) + else: + inner_dims = array_ops.concat( + [array_ops.ones([dims_to_add], self.dim_size_dtype), + self.inner_dim_sizes], + axis=0) + return RaggedTensorDynamicShape([], inner_dims, self.dim_size_dtype) + + def broadcast_dimension(self, axis, lengths): + """Returns a shape that is broadcast-compatible with self & lengths. + + * If dimension[axis] is uniform and lengths is a scalar, the check + that either lengths==1 or axis==1 or lengths==axis, and tile + dimension[axis] with tf.where(lengths==axis, 1, axis) repeats. + + * If dimension[axis] is uniform and lengths is a vector, then check + that dimension[axis]==1, and raggedly tile dimension[axis] with + lengths repeats. (we can skip tiling if we statically know that + slice_lengths == 1??) + + * If dimension[axis] is ragged and lengths is a scalar, then check + that lengths==1. + + * If dimension[axis] is ragged and lengths is a vector, then check + that self.dimension_size(axis) == lengths. + + Args: + axis: `int`. The dimension to broadcast. + lengths: 0-D or 1-D integer `Tensor`. + + Returns: + A `RaggedTensorDynamicShape`. + """ + lengths = ragged_util.convert_to_int_tensor( + lengths, name='lengths', dtype=self.dim_size_dtype) + # Check whether lengths is a scalar (for uniform dimensions) or + # vector (for ragged dimensions). + if lengths.shape.ndims is None: + raise ValueError('lengths must have a known rank.') + elif lengths.shape.ndims > 1: + raise ValueError('lengths must be a scalar or vector') + else: + lengths_is_scalar = (lengths.shape.ndims == 0) + + # Verify that the shapes are compatible. + if self.is_ragged(axis): + if lengths_is_scalar: + condition = math_ops.equal(lengths, 1) + else: + condition = math_ops.reduce_all( + math_ops.equal(lengths, self.dimension_size(axis))) + else: + axis_dim_size = self.dimension_size(axis) + if lengths_is_scalar: + condition = ( + math_ops.equal(lengths, 1) | math_ops.equal(axis_dim_size, 1) + | math_ops.equal(axis_dim_size, lengths)) + else: + condition = math_ops.equal(axis_dim_size, 1) + broadcast_err = [ + 'Unable to broadcast: dimension size mismatch in dimension', axis, + 'lengths=', lengths, 'dim_size=', + self.dimension_size(axis) + ] + broadcast_check = control_flow_assert.Assert( + condition, data=broadcast_err, summarize=10) + + with ops.control_dependencies([broadcast_check]): + # Partitioned dimensions: + if axis < self.num_partitioned_dimensions: + if self.is_ragged(axis): + # Use an identity op to make sure the check actually gets run. + return RaggedTensorDynamicShape( + self._partitioned_dim_sizes, + array_ops.identity(self.inner_dim_sizes), self.dim_size_dtype) + else: + return self._broadcast_uniform_partitioned_dimension(axis, lengths) + + # Inner dimensions: + else: + if lengths_is_scalar: + return self._broadcast_inner_dimension_to_uniform(axis, lengths) + else: + if axis == 0: + raise ValueError('Unable to broadcast: ' + 'outermost dimension must be uniform.') + return self._broadcast_inner_dimension_to_ragged(axis, lengths) + + def num_slices_in_dimension(self, axis): + """Returns the total number of slices across the indicated dimension.""" + if axis < 0: + return constant_op.constant(1, dtype=self.dim_size_dtype) + elif self.is_ragged(axis): + return math_ops.reduce_sum(self._partitioned_dim_sizes[axis]) + else: + return self.dimension_size(axis) * self.num_slices_in_dimension(axis - 1) + + def _broadcast_uniform_partitioned_dimension(self, axis, lengths): + """Broadcasts the partitioned dimension `axis` to match `lengths`.""" + axis_dim_size = self.dimension_size(axis) + partitioned_sizes = list(self._partitioned_dim_sizes[:axis]) + + if lengths.shape.ndims == 0: + lengths = array_ops.where( + math_ops.equal(axis_dim_size, 1), lengths, axis_dim_size) + repeats = array_ops.where(math_ops.equal(axis_dim_size, 1), lengths, 1) + splits = array_ops_stack.stack([0, self.num_slices_in_dimension(axis)]) + else: + splits = math_ops.range( + array_ops.size(lengths, out_type=self.dim_size_dtype) + 1) + repeats = lengths + + partitioned_sizes.append(lengths) + + for dim_size in self._partitioned_dim_sizes[axis + 1:]: + if dim_size.shape.ndims == 0: + partitioned_sizes.append(dim_size) + splits *= dim_size + else: + partitioned_sizes.append( + ragged_util.repeat_ranges(dim_size, splits, repeats)) + splits = array_ops.gather( + ragged_util.lengths_to_splits(dim_size), splits) + inner_sizes = self._inner_dim_sizes + return RaggedTensorDynamicShape(partitioned_sizes, inner_sizes, + self.dim_size_dtype) + + def _broadcast_inner_dimension_to_uniform(self, axis, length): + """Broadcasts the inner dimension `axis` to match `lengths`.""" + dim_size = self.dimension_size(axis) + axis_in_inner_dims = axis - self.num_partitioned_dimensions + partitioned_sizes = self._partitioned_dim_sizes + inner_sizes = array_ops.concat([ + self._inner_dim_sizes[:axis_in_inner_dims], + [array_ops.where(math_ops.equal(dim_size, 1), length, dim_size)], + self._inner_dim_sizes[axis_in_inner_dims + 1:] + ], + axis=0) + return RaggedTensorDynamicShape(partitioned_sizes, inner_sizes, + self.dim_size_dtype) + + def _broadcast_inner_dimension_to_ragged(self, axis, lengths): + axis_in_inner_dims = axis - self.num_partitioned_dimensions + partitioned_sizes = ( + self._partitioned_dim_sizes + tuple([ + self._inner_dim_sizes[i] for i in range(axis_in_inner_dims) + ]) + (lengths,)) + inner_sizes = self._inner_dim_sizes[axis_in_inner_dims + 1:] + return RaggedTensorDynamicShape(partitioned_sizes, inner_sizes) + + def with_dim_size_dtype(self, dtype): + if dtype not in (dtypes.int32, dtypes.int64): + raise ValueError('dtype must be int32 or int64') + if self.dim_size_dtype == dtype: + return self + return RaggedTensorDynamicShape( + [math_ops.cast(p, dtype) for p in self._partitioned_dim_sizes], + math_ops.cast(self._inner_dim_sizes, dtype)) + + +def broadcast_dynamic_shape(shape_x, shape_y): + """Returns the shape formed by broadcasting two shapes to be compatible. + + Args: + shape_x: A `RaggedTensorDynamicShape` + shape_y: A `RaggedTensorDynamicShape` + + Returns: + A `RaggedTensorDynamicShape`. + Raises: + ValueError: If `shape_x` and `shape_y` are not broadcast-compatible. + """ + if not isinstance(shape_x, RaggedTensorDynamicShape): + raise TypeError('shape_x must be a RaggedTensorDynamicShape') + if not isinstance(shape_y, RaggedTensorDynamicShape): + raise TypeError('shape_y must be a RaggedTensorDynamicShape') + + # Broadcast both shapes to have the same rank. + if shape_x.rank is None or shape_y.rank is None: + raise ValueError('Unable to broadcast: unknown rank') + broadcast_rank = max(shape_x.rank, shape_y.rank) + shape_x = shape_x.broadcast_to_rank(broadcast_rank) + shape_y = shape_y.broadcast_to_rank(broadcast_rank) + + # Broadcast dimensions one at a time, starting from the outermost dimension. + for axis in range(broadcast_rank): + shape_x = shape_x.broadcast_dimension(axis, shape_y.dimension_size(axis)) + shape_y = shape_y.broadcast_dimension(axis, shape_x.dimension_size(axis)) + + return shape_x + + +def broadcast_to(rt_input, shape, broadcast_inner_dimensions=True): + """Broadcasts a potentially ragged tensor to a ragged shape. + + Tiles `rt_input` as necessary to match the given shape. + + Behavior is undefined if `rt_input` is not broadcast-compatible with `shape`. + + Args: + rt_input: The potentially ragged tensor to broadcast. + shape: A `RaggedTensorDynamicShape` + broadcast_inner_dimensions: If false, then inner dimensions will not be + tiled. + + Returns: + A potentially ragged tensor whose values are taken from + `rt_input`, and whose shape matches `shape`. + """ + if not isinstance(shape, RaggedTensorDynamicShape): + raise TypeError('shape must be a RaggedTensorDynamicShape') + rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input) + + # Broadcasting to a uniform shape. + if shape.num_partitioned_dimensions == 0: + return _broadcast_to_uniform_shape(rt_input, shape, + broadcast_inner_dimensions) + else: + return _broadcast_to_ragged_shape(rt_input, shape, + broadcast_inner_dimensions) + + +def _broadcast_to_uniform_shape(rt_input, shape, broadcast_inner_dimensions): + """Broadcasts rt_input to the uniform shape `shape`.""" + if isinstance(rt_input, ragged_tensor.RaggedTensor): + raise ValueError('Incompatible with shape: ragged rank mismatch') + if broadcast_inner_dimensions: + return array_ops.broadcast_to(rt_input, shape.inner_dim_sizes) + else: + return rt_input + + +def _broadcast_to_ragged_shape(rt_input, dst_shape, broadcast_inner_dimensions): + """Broadcasts rt_input to the ragged shape `dst_shape`.""" + # Check that rt_input and dst_shape have the same row_splits dtype. + if (isinstance(rt_input, ragged_tensor.RaggedTensor) and + rt_input.row_splits.dtype != dst_shape.dim_size_dtype): + if not ragged_config.auto_cast_partition_dtype(): + raise ValueError('rt_input and dst_shape have different row_split ' + 'dtypes; use RaggedTensor.with_row_splits_dtype() or ' + 'RaggedTensorDynamicShape.with_dim_size_dtype() to ' + 'convert to a compatible dtype.') + rt_input = rt_input.with_row_splits_dtype(dtypes.int64) + dst_shape = dst_shape.with_dim_size_dtype(dtypes.int64) + + # dst_shape's rank and ragged_rank must be greater than or equal to rt_input's + if rt_input.shape.ndims is None or dst_shape.rank is None: + raise ValueError('Unable to broadcast: unknown rank') + if rt_input.shape.ndims > dst_shape.rank: + raise ValueError('Incompatible with shape: rank mismatch') + if (isinstance(rt_input, ragged_tensor.RaggedTensor) and + rt_input.ragged_rank >= dst_shape.num_partitioned_dimensions): + raise ValueError('Incompatible with shape: ragged rank mismatch') + + src_shape = RaggedTensorDynamicShape.from_tensor(rt_input) + src_shape = src_shape.broadcast_to_rank(dst_shape.rank) + + # Add dimensions to rt_input so its rank and ragged_rank matches dst_shape. + if dst_shape.rank > rt_input.shape.ndims: + if rt_input.shape.ndims < dst_shape.num_inner_dimensions + 1: + rt_input = array_ops.reshape( + rt_input, array_ops.concat([[-1], dst_shape.inner_dim_sizes], axis=0)) + for _ in range(dst_shape.rank - rt_input.shape.ndims): + if ragged_tensor.is_ragged(rt_input): + nrows = rt_input.nrows() + else: + nrows = array_ops.shape(rt_input, + out_type=dst_shape.dim_size_dtype)[0] + rt_input = ragged_tensor.RaggedTensor.from_row_lengths(rt_input, [nrows], + validate=False) + + # Add ragged dimensions to match dst_shape. + if ragged_tensor.is_ragged(rt_input): + inner_rank_diff = ( + rt_input.flat_values.shape.ndims - 1 - dst_shape.num_inner_dimensions) + if inner_rank_diff > 0: + rt_input = rt_input.with_flat_values( + ragged_tensor.RaggedTensor.from_tensor( + rt_input.flat_values, ragged_rank=inner_rank_diff, + row_splits_dtype=dst_shape.dim_size_dtype)) + else: + rt_input = ragged_tensor.RaggedTensor.from_tensor( + rt_input, ragged_rank=dst_shape.num_partitioned_dimensions - 1, + row_splits_dtype=dst_shape.dim_size_dtype) + + # Do broadcasting for any dimensions that will remain uniform. We can do + # these all at once, since they're independent of one another. + multiples = [1] * dst_shape.rank + for axis in range(dst_shape.num_partitioned_dimensions): + if not src_shape.is_ragged(axis) and not dst_shape.is_ragged(axis): + src_size = src_shape.dimension_size(axis) + dst_size = dst_shape.dimension_size(axis) + if ((tensor_util.constant_value(src_size) in (1, None)) and + (tensor_util.constant_value(dst_size) != 1)): + multiples[axis] = array_ops.where( + math_ops.equal(src_size, 1), dst_size, 1) + if not all(isinstance(v, int) and v == 1 for v in multiples): + multiples = array_ops_stack.stack(multiples, axis=0) + rt_input = ragged_array_ops.tile(rt_input, multiples) + + if broadcast_inner_dimensions: + new_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape( + rt_input.flat_values, out_type=dst_shape.dim_size_dtype), + array_ops.concat([[1], dst_shape.inner_dim_sizes], axis=0)) + rt_input = rt_input.with_flat_values( + array_ops.broadcast_to(rt_input.flat_values, new_shape)) + + # Do broadcasting for dimensions that become ragged. We must do these from + # outermost to innermost. + for axis in range(dst_shape.num_partitioned_dimensions): + if not src_shape.is_ragged(axis) and dst_shape.is_ragged(axis): + dst_size = dst_shape.dimension_size(axis) + rt_input = _ragged_tile_axis(rt_input, axis, dst_size, + dst_shape.dim_size_dtype) + + return rt_input + + +def _ragged_tile_axis(rt_input, axis, repeats, row_splits_dtype): + """Tile a dimension of a RaggedTensor to match a ragged shape.""" + assert axis > 0 # Outermost dimension may not be ragged. + + if not ragged_tensor.is_ragged(rt_input): + rt_input = ragged_tensor.RaggedTensor.from_tensor( + rt_input, ragged_rank=1, row_splits_dtype=row_splits_dtype) + + if axis > 1: + return rt_input.with_values( + _ragged_tile_axis(rt_input.values, axis - 1, repeats, + row_splits_dtype)) + else: + src_row_splits = rt_input.nested_row_splits + src_row_lengths = rt_input.nested_row_lengths() + splits = src_row_splits[0] + + dst_row_lengths = [repeats] + for i in range(1, len(src_row_lengths)): + dst_row_lengths.append( + ragged_util.repeat_ranges(src_row_lengths[i], splits, repeats)) + splits = array_ops.gather(src_row_splits[i], splits) + dst_values = ragged_util.repeat_ranges(rt_input.flat_values, splits, + repeats) + return ragged_tensor.RaggedTensor.from_nested_row_lengths( + dst_values, dst_row_lengths, validate=False) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_test_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..05c978e1deccd2fdfaad9c371bb3a6a3eca75229 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_test_ops.py @@ -0,0 +1,185 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""It lists ops of RaggedTensor for the interest of test.""" + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import gen_bitwise_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops import string_ops + + +# Constants listing various op types to test. Each operation +# should be included in at least one list below, or tested separately if +# necessary (e.g., because it expects additional arguments). +UNARY_FLOAT_OPS = [ + math_ops.abs, + math_ops.acos, + math_ops.acosh, + math_ops.angle, + math_ops.asin, + math_ops.asinh, + math_ops.atan, + math_ops.atanh, + math_ops.ceil, + math_ops.conj, + math_ops.cos, + math_ops.cosh, + math_ops.digamma, + math_ops.erf, + math_ops.erfc, + math_ops.erfcinv, + math_ops.erfinv, + math_ops.exp, + math_ops.expm1, + math_ops.floor, + math_ops.imag, + math_ops.is_finite, + math_ops.is_inf, + math_ops.is_nan, + math_ops.lgamma, + math_ops.log, + math_ops.log1p, + math_ops.log_sigmoid, + math_ops.ndtri, + math_ops.negative, + math_ops.real, + math_ops.reciprocal, + math_ops.reciprocal_no_nan, + math_ops.rint, + math_ops.round, + math_ops.rsqrt, + math_ops.sign, + math_ops.sigmoid, + math_ops.sin, + math_ops.sinh, + math_ops.softplus, + math_ops.sqrt, + math_ops.square, + math_ops.tan, + math_ops.tanh, + nn_ops.elu, + nn_ops.gelu, + nn_ops.leaky_relu, + nn_ops.log_softmax, + nn_ops.relu, + nn_ops.relu6, + nn_ops.selu, + nn_ops.softsign, + nn_impl.swish, + array_ops.ones_like, + array_ops.ones_like_v2, + array_ops.zeros_like, + array_ops.zeros_like_v2, + special_math_ops.bessel_i0, + special_math_ops.bessel_i0e, + special_math_ops.bessel_i1, + special_math_ops.bessel_j0, + special_math_ops.bessel_j1, + special_math_ops.bessel_i1e, + special_math_ops.bessel_k0, + special_math_ops.bessel_k0e, + special_math_ops.bessel_k1, + special_math_ops.bessel_k1e, + special_math_ops.bessel_y0, + special_math_ops.bessel_y1, + special_math_ops.dawsn, + special_math_ops.expint, + special_math_ops.fresnel_cos, + special_math_ops.fresnel_sin, + special_math_ops.spence, + string_ops.as_string, +] +UNARY_BOOL_OPS = [ + math_ops.logical_not, +] +UNARY_STRING_OPS = [ + string_ops.decode_base64, + string_ops.encode_base64, + string_ops.string_strip, + string_ops.string_lower, + string_ops.string_upper, + string_ops.string_length, + string_ops.string_length_v2, + parsing_ops.decode_compressed, +] +BINARY_FLOAT_OPS = [ + math_ops.add, + math_ops.atan2, + math_ops.complex, + math_ops.div, + math_ops.div_no_nan, + math_ops.divide, + math_ops.equal, + math_ops.floor_div, + math_ops.floordiv, + math_ops.floormod, + math_ops.greater, + math_ops.greater_equal, + math_ops.less, + math_ops.less_equal, + math_ops.maximum, + math_ops.minimum, + math_ops.multiply, + math_ops.multiply_no_nan, + math_ops.not_equal, + math_ops.pow, + math_ops.realdiv, + math_ops.squared_difference, + math_ops.subtract, + math_ops.truediv, + math_ops.xdivy, + math_ops.xlog1py, + math_ops.xlogy, + math_ops.zeta, +] +BINARY_BOOL_OPS = [ + math_ops.logical_and, + math_ops.logical_or, + math_ops.logical_xor, +] +UNARY_INT_OPS = [ + gen_bitwise_ops.invert, + string_ops.unicode_script, +] +BINARY_INT_OPS = [ + gen_bitwise_ops.bitwise_and, + gen_bitwise_ops.bitwise_or, + gen_bitwise_ops.bitwise_xor, + gen_bitwise_ops.left_shift, + gen_bitwise_ops.right_shift, + math_ops.truncatediv, + math_ops.truncatemod, +] +BINARY_ASSERT_OPS = [ + check_ops.assert_equal, + check_ops.assert_equal_v2, + check_ops.assert_near, + check_ops.assert_near_v2, + check_ops.assert_none_equal, + check_ops.assert_none_equal_v2, + check_ops.assert_greater, + check_ops.assert_greater_v2, + check_ops.assert_greater_equal, + check_ops.assert_greater_equal_v2, + check_ops.assert_less, + check_ops.assert_less_v2, + check_ops.assert_less_equal, + check_ops.assert_less_equal_v2, +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_value.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_value.py new file mode 100644 index 0000000000000000000000000000000000000000..638dc5207ee632a47ea264252a954c7413f4ae21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_tensor_value.py @@ -0,0 +1,114 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Value for RaggedTensor.""" + +import numpy as np + +from tensorflow.python.ops.ragged.row_partition import RowPartition +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["ragged.RaggedTensorValue"]) +@dispatch.register_dispatchable_type +class RaggedTensorValue: + """Represents the value of a `RaggedTensor`. + + Warning: `RaggedTensorValue` should only be used in graph mode; in + eager mode, the `tf.RaggedTensor` class contains its value directly. + + See `tf.RaggedTensor` for a description of ragged tensors. + """ + + def __init__(self, values, row_splits): + """Creates a `RaggedTensorValue`. + + Args: + values: A numpy array of any type and shape; or a RaggedTensorValue. + row_splits: A 1-D int32 or int64 numpy array. + """ + if not (isinstance(row_splits, (np.ndarray, np.generic)) and + row_splits.dtype in (np.int64, np.int32) and row_splits.ndim == 1): + raise TypeError("row_splits must be a 1D int32 or int64 numpy array") + if not isinstance(values, (np.ndarray, np.generic, RaggedTensorValue)): + raise TypeError("values must be a numpy array or a RaggedTensorValue") + if (isinstance(values, RaggedTensorValue) and + row_splits.dtype != values.row_splits.dtype): + raise ValueError("row_splits and values.row_splits must have " + "the same dtype") + self._values = values + self._row_splits = row_splits + + row_splits = property( + lambda self: self._row_splits, + doc="""The split indices for the ragged tensor value.""") + values = property( + lambda self: self._values, + doc="""The concatenated values for all rows in this tensor.""") + dtype = property( + lambda self: self._values.dtype, + doc="""The numpy dtype of values in this tensor.""") + + @property + def flat_values(self): + """The innermost `values` array for this ragged tensor value.""" + rt_values = self.values + while isinstance(rt_values, RaggedTensorValue): + rt_values = rt_values.values + return rt_values + + @property + def nested_row_splits(self): + """The row_splits for all ragged dimensions in this ragged tensor value.""" + rt_nested_splits = [self.row_splits] + rt_values = self.values + while isinstance(rt_values, RaggedTensorValue): + rt_nested_splits.append(rt_values.row_splits) + rt_values = rt_values.values + return tuple(rt_nested_splits) + + @property + def ragged_rank(self): + """The number of ragged dimensions in this ragged tensor value.""" + values_is_ragged = isinstance(self._values, RaggedTensorValue) + return self._values.ragged_rank + 1 if values_is_ragged else 1 + + @property + def shape(self): + """A tuple indicating the shape of this RaggedTensorValue.""" + return (self._row_splits.shape[0] - 1,) + (None,) + self._values.shape[1:] + + @property + def _nested_row_partitions(self): + """The row_partitions representing this shape.""" + return [RowPartition.from_row_splits(rs) for rs in self.nested_row_splits] + + def __str__(self): + return "" % self.to_list() + + def __repr__(self): + return "tf.RaggedTensorValue(values=%r, row_splits=%r)" % (self._values, + self._row_splits) + + def to_list(self): + """Returns this ragged tensor value as a nested Python list.""" + if isinstance(self._values, RaggedTensorValue): + values_as_list = self._values.to_list() + else: + values_as_list = self._values.tolist() + return [ + values_as_list[self._row_splits[i]:self._row_splits[i + 1]] + for i in range(len(self._row_splits) - 1) + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_util.py new file mode 100644 index 0000000000000000000000000000000000000000..81b91d0214ec2c07d2b66ac03e4d38bf6e65ecdc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_util.py @@ -0,0 +1,138 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Private convenience functions for RaggedTensors. + +None of these methods are exposed in the main "ragged" package. +""" + +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_ragged_math_ops +from tensorflow.python.ops import math_ops + + +def assert_splits_match(nested_splits_lists): + """Checks that the given splits lists are identical. + + Performs static tests to ensure that the given splits lists are identical, + and returns a list of control dependency op tensors that check that they are + fully identical. + + Args: + nested_splits_lists: A list of nested_splits_lists, where each split_list is + a list of `splits` tensors from a `RaggedTensor`, ordered from outermost + ragged dimension to innermost ragged dimension. + + Returns: + A list of control dependency op tensors. + Raises: + ValueError: If the splits are not identical. + """ + error_msg = "Inputs must have identical ragged splits" + for splits_list in nested_splits_lists: + if len(splits_list) != len(nested_splits_lists[0]): + raise ValueError(error_msg) + return [ + check_ops.assert_equal(s1, s2, message=error_msg) + for splits_list in nested_splits_lists[1:] + for (s1, s2) in zip(nested_splits_lists[0], splits_list) + ] + + +# Note: imported here to avoid circular dependency of array_ops. +get_positive_axis = array_ops.get_positive_axis +convert_to_int_tensor = array_ops.convert_to_int_tensor +repeat = array_ops.repeat_with_axis + + +def lengths_to_splits(lengths): + """Returns splits corresponding to the given lengths.""" + return array_ops.concat([[0], math_ops.cumsum(lengths)], axis=-1) + + +def repeat_ranges(params, splits, repeats): + """Repeats each range of `params` (as specified by `splits`) `repeats` times. + + Let the `i`th range of `params` be defined as + `params[splits[i]:splits[i + 1]]`. Then this function returns a tensor + containing range 0 repeated `repeats[0]` times, followed by range 1 repeated + `repeats[1]`, ..., followed by the last range repeated `repeats[-1]` times. + + Args: + params: The `Tensor` whose values should be repeated. + splits: A splits tensor indicating the ranges of `params` that should be + repeated. Elements should be non-negative integers. + repeats: The number of times each range should be repeated. Supports + broadcasting from a scalar value. Elements should be non-negative + integers. + + Returns: + A `Tensor` with the same rank and type as `params`. + + #### Example: + + >>> print(repeat_ranges( + ... params=tf.constant(['a', 'b', 'c']), + ... splits=tf.constant([0, 2, 3]), + ... repeats=tf.constant(3))) + tf.Tensor([b'a' b'b' b'a' b'b' b'a' b'b' b'c' b'c' b'c'], + shape=(9,), dtype=string) + """ + # Check if the input is valid + splits_checks = [ + check_ops.assert_non_negative( + splits, message="Input argument 'splits' must be non-negative" + ), + check_ops.assert_integer( + splits, + message=( + "Input argument 'splits' must be integer, but got" + f" {splits.dtype} instead" + ), + ), + ] + repeats_checks = [ + check_ops.assert_non_negative( + repeats, message="Input argument 'repeats' must be non-negative" + ), + check_ops.assert_integer( + repeats, + message=( + "Input argument 'repeats' must be integer, but got" + f" {repeats.dtype} instead" + ), + ), + ] + splits = control_flow_ops.with_dependencies(splits_checks, splits) + repeats = control_flow_ops.with_dependencies(repeats_checks, repeats) + + # Divide `splits` into starts and limits, and repeat them `repeats` times. + if repeats.shape.ndims != 0: + repeated_starts = repeat(splits[:-1], repeats, axis=0) + repeated_limits = repeat(splits[1:], repeats, axis=0) + else: + # Optimization: we can just call repeat once, and then slice the result. + repeated_splits = repeat(splits, repeats, axis=0) + n_splits = array_ops.shape(repeated_splits, out_type=repeats.dtype)[0] + repeated_starts = repeated_splits[:n_splits - repeats] + repeated_limits = repeated_splits[repeats:] + + # Get indices for each range from starts to limits, and use those to gather + # the values in the desired repetition pattern. + one = array_ops.ones((), repeated_starts.dtype) + offsets = gen_ragged_math_ops.ragged_range( + repeated_starts, repeated_limits, one) + return array_ops.gather(params, offsets.rt_dense_values) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_where_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_where_op.py new file mode 100644 index 0000000000000000000000000000000000000000..f638d51ea0b3a42d48bfd7d3a348632811853fd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/ragged_where_op.py @@ -0,0 +1,259 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""where operation for RaggedTensors.""" + +import typing + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_concat_ops +from tensorflow.python.ops.ragged import ragged_functional_ops +from tensorflow.python.ops.ragged import ragged_gather_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_shape +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(array_ops.where_v2) +def where_v2(condition: ragged_tensor.RaggedOrDense, + x: typing.Optional[ragged_tensor.RaggedOrDense] = None, + y: typing.Optional[ragged_tensor.RaggedOrDense] = None, + name=None): + """Return the elements where `condition` is `True`. + + : If both `x` and `y` are None: Retrieve indices of true elements. + + Returns the coordinates of true elements of `condition`. The coordinates + are returned in a 2-D tensor with shape + `[num_true_values, dim_size(condition)]`, where `result[i]` is the + coordinates of the `i`th true value (in row-major order). + + : If both `x` and `y` are non-`None`: Multiplex between `x` and `y`. + + Choose an output shape from the shapes of `condition`, `x`, and `y` that + all three shapes are broadcastable to; and then use the broadcasted + `condition` tensor as a mask that chooses whether the corredsponding element + in the output should be taken from `x` (if `condition` is true) or `y` (if + `condition` is false). + + >>> # Example: retrieve indices of true elements + >>> tf.where(tf.ragged.constant([[True, False], [True]])) + + + >>> # Example: multiplex between `x` and `y` + >>> tf.where(tf.ragged.constant([[True, False], [True, False, True]]), + ... tf.ragged.constant([['A', 'B'], ['C', 'D', 'E']]), + ... tf.ragged.constant([['a', 'b'], ['c', 'd', 'e']])) + + + Args: + condition: A potentially ragged tensor of type `bool` + x: A potentially ragged tensor (optional). + y: A potentially ragged tensor (optional). Must be specified if `x` is + specified. Must have the same rank and type as `x`. + name: A name of the operation (optional). + + Returns: + : If both `x` and `y` are `None`: + A `Tensor` with shape `(num_true, rank(condition))`. + : Otherwise: + A potentially ragged tensor with the same type as `x` and `y`, and whose + shape is broadcast-compatible with `x`, `y`, and `condition`. + + Raises: + ValueError: When exactly one of `x` or `y` is non-`None`; or when + `condition`, `x`, and `y` have incompatible shapes. + """ + if (x is None) != (y is None): + raise ValueError('x and y must be either both None or both non-None') + + with ops.name_scope('RaggedWhere', name, [condition, x, y]): + condition = ragged_tensor.convert_to_tensor_or_ragged_tensor( + condition, name='condition') + if x is None: + return _coordinate_where(condition) + else: + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, name='x') + y = ragged_tensor.convert_to_tensor_or_ragged_tensor(y, name='y') + condition, x, y = ragged_tensor.match_row_splits_dtypes(condition, x, y) + return _elementwise_where_v2(condition, x, y) + + +@dispatch.dispatch_for_api(array_ops.where) +def where(condition: ragged_tensor.RaggedOrDense, + x: typing.Optional[ragged_tensor.RaggedOrDense] = None, + y: typing.Optional[ragged_tensor.RaggedOrDense] = None, + name=None): + """Return the elements, either from `x` or `y`, depending on the `condition`. + + : If both `x` and `y` are `None`: + Returns the coordinates of true elements of `condition`. The coordinates + are returned in a 2-D tensor with shape + `[num_true_values, dim_size(condition)]`, where `result[i]` is the + coordinates of the `i`th true value (in row-major order). + + : If both `x` and `y` are non-`None`: + Returns a tensor formed by selecting values from `x` where condition is + true, and from `y` when condition is false. In particular: + + : If `condition`, `x`, and `y` all have the same shape: + + * `result[i1...iN] = x[i1...iN]` if `condition[i1...iN]` is true. + * `result[i1...iN] = y[i1...iN]` if `condition[i1...iN]` is false. + + : Otherwise: + + * `condition` must be a vector. + * `x` and `y` must have the same number of dimensions. + * The outermost dimensions of `condition`, `x`, and `y` must all have the + same size. + * `result[i] = x[i]` if `condition[i]` is true. + * `result[i] = y[i]` if `condition[i]` is false. + + Args: + condition: A potentially ragged tensor of type `bool` + x: A potentially ragged tensor (optional). + y: A potentially ragged tensor (optional). Must be specified if `x` is + specified. Must have the same rank and type as `x`. + name: A name of the operation (optional) + + Returns: + : If both `x` and `y` are `None`: + A `Tensor` with shape `(num_true, dim_size(condition))`. + : Otherwise: + A potentially ragged tensor with the same type, rank, and outermost + dimension size as `x` and `y`. + `result.ragged_rank = max(x.ragged_rank, y.ragged_rank)`. + + Raises: + ValueError: When exactly one of `x` or `y` is non-`None`; or when + `condition`, `x`, and `y` have incompatible shapes. + + #### Examples: + + >>> # Coordinates where condition is true. + >>> condition = tf.ragged.constant([[True, False, True], [False, True]]) + >>> print(where(condition)) + tf.Tensor( [[0 0] [0 2] [1 1]], shape=(3, 2), dtype=int64) + + >>> # Elementwise selection between x and y, based on condition. + >>> condition = tf.ragged.constant([[True, False, True], [False, True]]) + >>> x = tf.ragged.constant([['A', 'B', 'C'], ['D', 'E']]) + >>> y = tf.ragged.constant([['a', 'b', 'c'], ['d', 'e']]) + >>> print(where(condition, x, y)) + + + >>> # Row selection between x and y, based on condition. + >>> condition = [True, False] + >>> x = tf.ragged.constant([['A', 'B', 'C'], ['D', 'E']]) + >>> y = tf.ragged.constant([['a', 'b', 'c'], ['d', 'e']]) + >>> print(where(condition, x, y)) + + """ + if (x is None) != (y is None): + raise ValueError('x and y must be either both None or both non-None') + with ops.name_scope('RaggedWhere', name, [condition, x, y]): + condition = ragged_tensor.convert_to_tensor_or_ragged_tensor( + condition, name='condition') + if x is None: + return _coordinate_where(condition) + else: + x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, name='x') + y = ragged_tensor.convert_to_tensor_or_ragged_tensor(y, name='y') + condition, x, y = ragged_tensor.match_row_splits_dtypes(condition, x, y) + return _elementwise_where(condition, x, y) + + +def _elementwise_where(condition, x, y): + """Ragged version of tf.where(condition, x, y).""" + condition_is_ragged = isinstance(condition, ragged_tensor.RaggedTensor) + x_is_ragged = isinstance(x, ragged_tensor.RaggedTensor) + y_is_ragged = isinstance(y, ragged_tensor.RaggedTensor) + + if not (condition_is_ragged or x_is_ragged or y_is_ragged): + return array_ops.where(condition, x, y) + + elif condition_is_ragged and x_is_ragged and y_is_ragged: + return ragged_functional_ops.map_flat_values(array_ops.where, condition, x, + y) + elif not condition_is_ragged: + # Concatenate x and y, and then use `gather` to assemble the selected rows. + condition.shape.assert_has_rank(1) + x_and_y = ragged_concat_ops.concat([x, y], axis=0) + x_nrows = _nrows(x, out_type=x_and_y.row_splits.dtype) + y_nrows = _nrows(y, out_type=x_and_y.row_splits.dtype) + indices = array_ops.where(condition, math_ops.range(x_nrows), + x_nrows + math_ops.range(y_nrows)) + return ragged_gather_ops.gather(x_and_y, indices) + + else: + raise ValueError('Input shapes do not match.') + + +def _elementwise_where_v2(condition, x, y): + """Ragged version of tf.where_v2(condition, x, y).""" + # Broadcast x, y, and condition to have the same shape. + if not (condition.shape.is_fully_defined() and x.shape.is_fully_defined() and + y.shape.is_fully_defined() and x.shape == y.shape and + condition.shape == x.shape): + shape_c = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor( + condition) + shape_x = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor(x) + shape_y = ragged_tensor_shape.RaggedTensorDynamicShape.from_tensor(y) + shape = ragged_tensor_shape.broadcast_dynamic_shape( + shape_c, ragged_tensor_shape.broadcast_dynamic_shape(shape_x, shape_y)) + condition = ragged_tensor_shape.broadcast_to(condition, shape) + x = ragged_tensor_shape.broadcast_to(x, shape) + y = ragged_tensor_shape.broadcast_to(y, shape) + + condition_is_ragged = isinstance(condition, ragged_tensor.RaggedTensor) + x_is_ragged = isinstance(x, ragged_tensor.RaggedTensor) + y_is_ragged = isinstance(y, ragged_tensor.RaggedTensor) + if not (condition_is_ragged or x_is_ragged or y_is_ragged): + return array_ops.where_v2(condition, x, y) + + return ragged_functional_ops.map_flat_values(array_ops.where_v2, condition, x, + y) + + +def _coordinate_where(condition): + """Ragged version of tf.where(condition).""" + if not isinstance(condition, ragged_tensor.RaggedTensor): + return array_ops.where(condition) + + # The coordinate for each `true` value in condition.values. + selected_coords = _coordinate_where(condition.values) + + # Convert the first index in each coordinate to a row index and column index. + condition = condition.with_row_splits_dtype(selected_coords.dtype) + first_index = selected_coords[:, 0] + selected_rows = array_ops.gather(condition.value_rowids(), first_index) + selected_row_starts = array_ops.gather(condition.row_splits, selected_rows) + selected_cols = first_index - selected_row_starts + + # Assemble the row & column index with the indices for inner dimensions. + return array_ops.concat([ + array_ops.expand_dims(selected_rows, 1), + array_ops.expand_dims(selected_cols, 1), selected_coords[:, 1:] + ], + axis=1) + + +def _nrows(rt_input, out_type): + if isinstance(rt_input, ragged_tensor.RaggedTensor): + return rt_input.nrows(out_type=out_type) + else: + return array_ops.shape(rt_input, out_type=out_type)[0] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/row_partition.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/row_partition.py new file mode 100644 index 0000000000000000000000000000000000000000..43d739cc0cc4198fe2cc8effc8445263212086fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/row_partition.py @@ -0,0 +1,1495 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A class used to partition a sequence into contiguous subsequences ("rows"). +""" + + +# TODO(edloper): Make into a ExtensionType (if possible) + + +import numpy as np + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_ragged_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import segment_id_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util.tf_export import tf_export + +# =============================================================================== +# RowPartition +# =============================================================================== +# TODO(edloper): Consider removing row_starts and row_limits factory methods +# and accessors from RowPartition. In particular, these two encodings are +# "second-class citizens": we never cache them, and if you do construct a +# RowPartition from them then it may be more expensive than you might expect +# (because we append a value to the beginning/end to transform them into +# splits). If we do remove them from RowPartition, then we would still keep +# the from_row_starts and from_row_limits factory methods in RaggedTensor. + + +@tf_export("experimental.RowPartition") +class RowPartition(composite_tensor.CompositeTensor): + """Partitioning of a sequence of values into contiguous subsequences ("rows"). + + A `RowPartition` describes how a sequence with `nvals` items should be + divided into `nrows` contiguous subsequences ("rows"). For example, a + `RowPartition` could be used to partition the vector `[1, 2, 3, 4, 5]` into + subsequences `[[1, 2], [3], [], [4, 5]]`. Note that `RowPartition` stores + information about how values are partitioned, but does not include the + partitioned values themselves. `tf.RaggedTensor` is used to pair a `values` + tensor with one or more `RowPartition`s, providing a complete encoding for a + ragged tensor (i.e. a tensor with variable-length dimensions). + + `RowPartition`s may be defined using several different schemes: + + * `row_lengths`: an integer vector with shape `[nrows]`, which specifies + the length of each row. + + * `row_splits`: an integer vector with shape `[nrows+1]`, specifying the + "split points" between each row. + + * `row_starts`: an integer vector with shape `[nrows]`, which specifies + the start offset for each row. Equivalent to `row_splits[:-1]`. + + * `row_limits`: an integer vector with shape `[nrows]`, which specifies + the stop offset for each row. Equivalent to `row_splits[1:]`. + + * `value_rowids` is an integer vector with shape `[nvals]`, corresponding + one-to-one with sequence values, which specifies the row that each value + belongs to. If the partition has empty trailing rows, then `nrows` + must also be specified. + + * `uniform_row_length` is an integer scalar, specifying the length of every + row. This scheme may only be used if all rows have the same length. + + For example, the following `RowPartition`s all represent the partitioning of + 8 values into 5 sublists as follows: `[[*, *, *, *], [], [*, *, *], [*], []]`. + + >>> p1 = RowPartition.from_row_lengths([4, 0, 3, 1, 0]) + >>> p2 = RowPartition.from_row_splits([0, 4, 4, 7, 8, 8]) + >>> p3 = RowPartition.from_row_starts([0, 4, 4, 7, 8], nvals=8) + >>> p4 = RowPartition.from_row_limits([4, 4, 7, 8, 8]) + >>> p5 = RowPartition.from_value_rowids([0, 0, 0, 0, 2, 2, 2, 3], nrows=5) + + For more information about each scheme, see the documentation for the + its factory method. For additional examples, see the documentation on + `tf.RaggedTensor`. + + ### Precomputed Encodings + + `RowPartition` always stores at least one encoding of the partitioning, but + it can be configured to cache additional encodings as well. This can + avoid unnecessary recomputation in eager mode. (In graph mode, optimizations + such as common subexpression elimination will typically prevent these + unnecessary recomputations.) To check which encodings are precomputed, use + `RowPartition.has_precomputed_`. To cache an additional + encoding, use `RowPartition.with_precomputed_`. + """ + + # ============================================================================= + # Constructor (private) + # ============================================================================= + def __init__(self, + row_splits, + row_lengths=None, + value_rowids=None, + nrows=None, + uniform_row_length=None, + nvals=None, + internal=False): + """Creates a `RowPartition` from the specified encoding tensor(s). + + This constructor is private -- please use one of the following ops to + build `RowPartition`s: + + * `RowPartition.from_row_lengths` + * `RowPartition.from_value_rowids` + * `RowPartition.from_row_splits` + * `RowPartition.from_row_starts` + * `RowPartition.from_row_limits` + * `RowPartition.from_uniform_row_length` + + If row_splits is has a constant value, then all other arguments should + have a constant value. + + Args: + row_splits: A 1-D integer tensor with shape `[nrows+1]`. + row_lengths: A 1-D integer tensor with shape `[nrows]` + value_rowids: A 1-D integer tensor with shape `[nvals]`. + nrows: A 1-D integer scalar tensor. + uniform_row_length: A scalar tensor. + nvals: A scalar tensor. + internal: Private key value, required to ensure that this private + constructor is *only* called from the factory methods. + + Raises: + TypeError: If a row partitioning tensor has an inappropriate dtype. + TypeError: If exactly one row partitioning argument was not specified. + ValueError: If a row partitioning tensor has an inappropriate shape. + ValueError: If multiple partitioning arguments are specified. + ValueError: If nrows is specified but value_rowids is not None. + """ + if internal is not _row_partition_factory_key: + raise ValueError("RowPartition constructor is private; please use one " + "of the factory methods instead (e.g., " + "RowPartition.from_row_lengths())") + + # Validate the arguments. + if not isinstance(row_splits, tensor_lib.Tensor): + raise TypeError("Row-partitioning argument must be a Tensor, got %r" % + row_splits) + if row_splits.dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("Row-partitioning argument must be int32 or int64") + + # Validate shapes & dtypes. + row_splits.shape.assert_has_rank(1) + row_splits.set_shape([None]) + self._row_splits = row_splits + + # Store any cached tensors. These are used to avoid unnecessary + # round-trip conversions when a RowPartition is constructed from + # lengths or rowids, and we later want those lengths/rowids back. + for tensor in [row_lengths, value_rowids, nrows, uniform_row_length, nvals]: + if tensor is not None: + if not isinstance(tensor, tensor_lib.Tensor): + raise TypeError("Cached value must be a Tensor or None.") + elif tensor.dtype != row_splits.dtype: + raise ValueError(f"Inconsistent dtype for encoding tensors: " + f"{tensor} vs {row_splits}") + self._row_lengths = row_lengths + self._value_rowids = value_rowids + self._nrows = nrows + self._uniform_row_length = uniform_row_length + self._nvals = nvals + + # ============================================================================= + # Factory Methods + # ============================================================================= + + @classmethod + def from_value_rowids(cls, + value_rowids, + nrows=None, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `value_rowids`. + + This `RowPartition` divides a sequence `values` into rows by specifying + which row each value should be added to: + + ```python + partitioned_rows = [[] for _ in nrows] + for (value, rowid) in zip(values, value_rowids): + partitioned_rows[rowid].append(value) + ``` + + Args: + value_rowids: A 1-D integer tensor with shape `[nvals]`, which corresponds + one-to-one with `values`, and specifies each value's row index. Must be + nonnegative, and must be sorted in ascending order. + nrows: An integer scalar specifying the number of rows. This should be + specified if the `RowPartition` may containing empty training rows. Must + be greater than `value_rowids[-1]` (or greater than or equal to zero if + `value_rowids` is empty). Defaults to `value_rowids[-1] + 1` (or zero if + `value_rowids` is empty). + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `value_rowids`, dtype_hint, or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + + Raises: + ValueError: If `nrows` is incompatible with `value_rowids`. + + #### Example: + + >>> print(RowPartition.from_value_rowids( + ... value_rowids=[0, 0, 0, 0, 2, 2, 2, 3], + ... nrows=4)) + tf.RowPartition(row_splits=[0 4 4 7 8]) + """ + # Local import bincount_ops to avoid import-cycle since bincount_ops + # imports ragged_tensor. + from tensorflow.python.ops import bincount_ops # pylint: disable=g-import-not-at-top + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + with ops.name_scope(None, "RowPartitionFromValueRowIds", + [value_rowids, nrows]): + value_rowids = cls._convert_row_partition( + value_rowids, "value_rowids", dtype_hint=dtype_hint, dtype=dtype) + if nrows is None: + const_rowids = tensor_util.constant_value(value_rowids) + if const_rowids is None: + nrows = array_ops.concat([value_rowids[-1:], [-1]], axis=0)[0] + 1 + const_nrows = None + else: + const_nrows = const_rowids[-1] + 1 if const_rowids.size > 0 else 0 + nrows = ops.convert_to_tensor( + const_nrows, value_rowids.dtype, name="nrows") + else: + nrows = ops.convert_to_tensor(nrows, value_rowids.dtype, "nrows") + const_nrows = tensor_util.constant_value(nrows) + if const_nrows is not None: + if const_nrows < 0: + raise ValueError("Expected nrows >= 0; got %d" % const_nrows) + const_rowids = tensor_util.constant_value(value_rowids) + if const_rowids is not None and const_rowids.size > 0: + if not const_nrows >= const_rowids[-1] + 1: + raise ValueError( + "Expected nrows >= value_rowids[-1] + 1; got nrows=%d, " + "value_rowids[-1]=%d" % (const_nrows, const_rowids[-1])) + + value_rowids.shape.assert_has_rank(1) + nrows.shape.assert_has_rank(0) + + if validate: + msg = ("Arguments to from_value_rowids do not form a valid " + "RowPartition") + checks = [ + check_ops.assert_rank(value_rowids, 1, message=msg), + check_ops.assert_rank(nrows, 0, message=msg), + check_ops.assert_non_negative(value_rowids[:1], message=msg), + _assert_monotonic_increasing(value_rowids, message=msg), + check_ops.assert_less(value_rowids[-1:], nrows, message=msg), + ] + value_rowids = control_flow_ops.with_dependencies(checks, value_rowids) + + # Convert value_rowids & nrows to row_splits. + # Note: we don't use segment_ids_to_row_splits() here because we want + # to save the intermediate value `row_lengths`, so we can cache it. + # TODO(b/116708836) Upgrade bincount to accept int64 so we can skip the + # cast. + value_rowids_int32 = math_ops.cast(value_rowids, dtypes.int32) + nrows_int32 = math_ops.cast(nrows, dtypes.int32) + row_lengths = bincount_ops.bincount( + value_rowids_int32, + minlength=nrows_int32, + maxlength=nrows_int32, + dtype=value_rowids.dtype) + row_splits = array_ops.concat([[0], math_ops.cumsum(row_lengths)], axis=0) + if const_nrows is not None: + row_lengths.set_shape([const_nrows]) + row_splits.set_shape([const_nrows + 1]) + + return cls( + row_splits=row_splits, + row_lengths=row_lengths, + value_rowids=value_rowids, + nrows=nrows, + internal=_row_partition_factory_key) + + @classmethod + def from_row_splits(cls, + row_splits, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `row_splits`. + + This `RowPartition` divides a sequence `values` into rows by indicating + where each row begins and ends: + + ```python + partitioned_rows = [] + for i in range(len(row_splits) - 1): + row_start = row_splits[i] + row_end = row_splits[i + 1] + partitioned_rows.append(values[row_start:row_end]) + ``` + + Args: + row_splits: A 1-D integer tensor with shape `[nrows+1]`. Must not be + empty, and must be sorted in ascending order. `row_splits[0]` must be + zero. + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `row_splits`, dtype_hint, or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + + Raises: + ValueError: If `row_splits` is an empty list. + """ + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + if isinstance(row_splits, (list, tuple)) and not row_splits: + raise ValueError("row_splits tensor may not be empty.") + if isinstance(row_splits, tensor_lib.TensorSpec): + return cls(row_splits=row_splits, internal=_row_partition_factory_key) + + with ops.name_scope(None, "RowPartitionFromRowSplits", [row_splits]): + row_splits = cls._convert_row_partition( + row_splits, "row_splits", dtype_hint=dtype_hint, dtype=dtype) + row_splits.shape.assert_has_rank(1) + + if validate: + msg = "Arguments to from_row_splits do not form a valid RaggedTensor:" + checks = [ + check_ops.assert_rank(row_splits, 1, message=(msg + "rank")), + _assert_zero(row_splits[0], message=(msg + "zero")), + _assert_monotonic_increasing( + row_splits, message=(msg + "monotonic")), + ] + row_splits = control_flow_ops.with_dependencies(checks, row_splits) + + return cls(row_splits=row_splits, internal=_row_partition_factory_key) + + @classmethod + def from_row_lengths(cls, + row_lengths, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `row_lengths`. + + This `RowPartition` divides a sequence `values` into rows by indicating + the length of each row: + + ```python + partitioned_rows = [[values.pop(0) for _ in range(length)] + for length in row_lengths] + ``` + + Args: + row_lengths: A 1-D integer tensor with shape `[nrows]`. Must be + nonnegative. + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `row_lengths`, dtype_hint, or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + """ + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + with ops.name_scope(None, "RowPartitionFromRowLengths", [row_lengths]): + row_lengths = cls._convert_row_partition( + row_lengths, "row_lengths", dtype_hint=dtype_hint, dtype=dtype) + row_lengths.shape.assert_has_rank(1) + + if validate: + msg = "Arguments to from_row_lengths do not form a valid RowPartition" + checks = [ + check_ops.assert_rank(row_lengths, 1, message=msg), + check_ops.assert_non_negative(row_lengths, message=msg), + ] + row_lengths = control_flow_ops.with_dependencies(checks, row_lengths) + + row_limits = math_ops.cumsum(row_lengths) + row_splits = array_ops.concat([[0], row_limits], axis=0) + return cls( + row_splits=row_splits, + row_lengths=row_lengths, + internal=_row_partition_factory_key) + + @classmethod + def from_row_starts(cls, + row_starts, + nvals, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `row_starts`. + + Equivalent to: `from_row_splits(concat([row_starts, nvals], axis=0))`. + + Args: + row_starts: A 1-D integer tensor with shape `[nrows]`. Must be + nonnegative and sorted in ascending order. If `nrows>0`, then + `row_starts[0]` must be zero. + nvals: A scalar tensor indicating the number of values. + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `row_starts`, dtype_hint, or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + """ + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + with ops.name_scope(None, "RowPartitionFromRowStarts", [row_starts]): + row_starts = cls._convert_row_partition( + row_starts, "row_starts", dtype_hint=dtype_hint, dtype=dtype) + row_starts.shape.assert_has_rank(1) + # TODO(martinz): nvals and row_starts could be inconsistent at call time, + # even though they eventually end up the same type. + nvals = math_ops.cast(nvals, row_starts.dtype) + if validate: + msg = "Arguments to from_row_starts do not form a valid RaggedTensor" + checks = [ + check_ops.assert_rank(row_starts, 1, message=msg), + _assert_zero(row_starts[:1], message=msg), + _assert_monotonic_increasing(row_starts, message=msg), + check_ops.assert_less_equal(row_starts[-1:], nvals, message=msg), + ] + row_starts = control_flow_ops.with_dependencies(checks, row_starts) + + row_splits = array_ops.concat([row_starts, [nvals]], axis=0) + return cls(row_splits=row_splits, nvals=nvals, + internal=_row_partition_factory_key) + + @classmethod + def from_row_limits(cls, + row_limits, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `row_limits`. + + Equivalent to: `from_row_splits(values, concat([0, row_limits], axis=0))`. + + Args: + row_limits: A 1-D integer tensor with shape `[nrows]`. Must be sorted in + ascending order. + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `row_limits`, dtype_hint, or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + """ + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + with ops.name_scope(None, "RowPartitionFromRowLimits", [row_limits]): + row_limits = cls._convert_row_partition( + row_limits, "row_limits", dtype_hint=dtype_hint, dtype=dtype) + row_limits.shape.assert_has_rank(1) + + if validate: + msg = "Arguments to from_row_limits do not form a valid RaggedTensor" + checks = [ + check_ops.assert_rank(row_limits, 1, message=msg), + check_ops.assert_non_negative(row_limits[:1], message=msg), + _assert_monotonic_increasing(row_limits, message=msg), + ] + row_limits = control_flow_ops.with_dependencies(checks, row_limits) + + zero = array_ops.zeros([1], row_limits.dtype) + row_splits = array_ops.concat([zero, row_limits], axis=0) + return cls(row_splits=row_splits, internal=_row_partition_factory_key) + + @classmethod + def from_uniform_row_length(cls, + uniform_row_length, + nvals=None, + nrows=None, + validate=True, + dtype=None, + dtype_hint=None): + """Creates a `RowPartition` with rows partitioned by `uniform_row_length`. + + This `RowPartition` divides a sequence `values` into rows that all have + the same length: + + ```python + partitioned_rows = [[values.pop(0) for _ in range(uniform_row_length)] + for _ in range(nrows)] + ``` + + Note that either or both of nvals and nrows must be specified. + + Args: + uniform_row_length: A scalar integer tensor. Must be nonnegative. The + size of the outer axis of `values` must be evenly divisible by + `uniform_row_length`. + nvals: a non-negative scalar integer tensor for the number of values. + Must be specified if nrows is not specified. If not specified, + defaults to uniform_row_length*nrows + nrows: The number of rows in the constructed RowPartition. If not + specified, then it defaults to `nvals/uniform_row_length` (or `0` if + `uniform_row_length==0`). `nrows` only needs to be specified if + `uniform_row_length` might be zero. `uniform_row_length*nrows` must be + `nvals`. + validate: If true, then use assertions to check that the arguments form a + valid `RowPartition`. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `uniform_row_length`, dtype_hint, + or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A `RowPartition`. + """ + if not isinstance(validate, bool): + raise TypeError("validate must have type bool") + if nrows is None and nvals is None: + raise ValueError("Either (or both) of nvals and nrows must be specified") + with ops.name_scope(None, "RowPartitionFromUniformRowLength", + [uniform_row_length, nrows]): + [uniform_row_length, nvals, nrows + ] = _convert_all_to_tensors([(uniform_row_length, "uniform_row_length"), + (nvals, "nvals"), (nrows, "nrows")], + dtype=dtype, + dtype_hint=dtype_hint) + + uniform_row_length.shape.assert_has_rank(0) + + # Find nrows. + const_row_length = tensor_util.constant_value(uniform_row_length) + if nrows is None: + if const_row_length is None: + # Avoid division by zero if uniform_row_length==0 (and nvals==0). + rowlen_or_1 = math_ops.maximum( + uniform_row_length, + constant_op.constant(1, uniform_row_length.dtype)) + nrows = nvals // rowlen_or_1 + elif const_row_length == 0: + nrows = constant_op.constant(0, dtype=uniform_row_length.dtype) + else: + nrows = nvals // const_row_length + const_nrows = None if nrows is None else tensor_util.constant_value(nrows) + const_nvals = None if nvals is None else tensor_util.constant_value(nvals) + const_uniform_row_length = tensor_util.constant_value(uniform_row_length) + + checks = [] + + if const_nvals is None and const_nrows is not None and const_uniform_row_length is not None: + const_nvals = const_nrows * const_uniform_row_length + if nvals is not None and validate: + checks.append(check_ops.assert_equal(nvals, const_nvals)) + nvals = constant_op.constant(const_nvals, uniform_row_length.dtype) + + if nvals is None: + nvals = nrows * uniform_row_length + + # Find row_splits. + if const_nrows is not None and const_row_length is not None: + row_splits = [v * const_row_length for v in range(const_nrows + 1)] + row_splits = constant_op.constant(row_splits, uniform_row_length.dtype) + else: + row_splits = math_ops.range( + nrows + 1, dtype=uniform_row_length.dtype) * uniform_row_length + + if validate: + + if (const_nrows is None or const_row_length is None or + const_nvals is None): + checks.append( + check_ops.assert_equal( + nrows * uniform_row_length, nvals, + ("uniform_row_length", uniform_row_length, "times nrows", + nrows, "must equal nvals", nvals))) + else: + if const_nrows * const_row_length != const_nvals: + raise ValueError( + "uniform_row_length=%d times nrows=%d must equal nvals=%d" % + (const_row_length, const_nrows, const_nvals)) + + if uniform_row_length.shape.rank is None: + checks.append( + check_ops.assert_rank( + uniform_row_length, + 0, + message="uniform_row_length must be a scalar.")) + + const_row_length = tensor_util.constant_value(uniform_row_length) + if const_row_length is None: + checks.append( + check_ops.assert_greater_equal( + uniform_row_length, + constant_op.constant(0, uniform_row_length.dtype), + message="uniform_row_length must be >= 0.")) + else: + if const_row_length < 0: + raise ValueError("uniform_row_length must be >= 0.") + + row_splits = control_flow_ops.with_dependencies(checks, row_splits) + + return cls( + row_splits=row_splits, + uniform_row_length=uniform_row_length, + nrows=nrows, + nvals=nvals, + internal=_row_partition_factory_key) + + @classmethod + def _convert_row_partition(cls, partition, name, dtype=None, dtype_hint=None): + """Converts `partition` to Tensors. + + Args: + partition: A row-partitioning tensor for the `RowPartition` being + constructed. I.e., one of: row_splits, row_lengths, row_starts, + row_limits, value_rowids, uniform_row_length. + name: The name of the row-partitioning tensor. + dtype: Optional dtype for the RowPartition. If missing, the type + is inferred from the type of `uniform_row_length`, dtype_hint, + or tf.int64. + dtype_hint: Optional dtype for the RowPartition, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. + If the conversion to `dtype_hint` is not possible, this argument has no + effect. + + Returns: + A tensor equivalent to partition. + + Raises: + ValueError: if dtype is not int32 or int64. + """ + if dtype_hint is None: + dtype_hint = dtypes.int64 + if (isinstance(partition, np.ndarray) and + partition.dtype == np.int32 and dtype is None): + partition = ops.convert_to_tensor(partition, name=name) + else: + partition = tensor_conversion.convert_to_tensor_v2( + partition, dtype_hint=dtype_hint, dtype=dtype, name=name + ) + if partition.dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("%s must have dtype int32 or int64" % name) + + return partition + + def _with_dependencies(self, dependencies): + """Returns a new RowPartition equal to self with control dependencies. + + Specifically, self._row_splits is gated by the given control dependencies. + Used to add sanity checks to the constructors. + + Args: + dependencies: a list of tensors to use as dependencies. + + Returns: + A new RowPartition object. + """ + new_row_splits = control_flow_ops.with_dependencies(dependencies, + self._row_splits) + return RowPartition( + row_splits=new_row_splits, + row_lengths=self._row_lengths, + value_rowids=self._value_rowids, + nrows=self._nrows, + uniform_row_length=self._uniform_row_length, + internal=_row_partition_factory_key) + + # ============================================================================= + # Accessors + # ============================================================================= + + @property + def dtype(self): + """The `DType` used to encode the row partition (either int32 or int64).""" + return self._row_splits.dtype + + def row_splits(self): + """Returns the row-split indices for this row partition. + + `row_splits` specifies where the values for each row begin and end. + In particular, the values for row `i` are stored in the slice + `values[row_splits[i]:row_splits[i+1]]`. + + Returns: + A 1-D integer `Tensor` with shape `[self.nrows+1]`. + The returned tensor is non-empty, and is sorted in ascending order. + `self.row_splits()[0] == 0`. + `self.row_splits()[-1] == self.nvals()`. + """ + return self._row_splits + + def value_rowids(self): + """Returns the row indices for this row partition. + + `value_rowids` specifies the row index fo reach value. In particular, + `value_rowids[i]` is the row index for `values[i]`. + + Returns: + A 1-D integer `Tensor` with shape `[self.nvals()]`. + The returned tensor is nonnegative, and is sorted in ascending order. + """ + if self._value_rowids is not None: + return self._value_rowids + return segment_id_ops.row_splits_to_segment_ids(self._row_splits) + + def nvals(self): + """Returns the number of values partitioned by this `RowPartition`. + + If the sequence partitioned by this `RowPartition` is a tensor, then + `nvals` is the size of that tensor's outermost dimension -- i.e., + `nvals == values.shape[0]`. + + Returns: + scalar integer Tensor + """ + # TODO(martinz): Uncomment these lines. + # if self._nvals is not None: + # return self._nvals + return self._row_splits[-1] + + def nrows(self): + """Returns the number of rows created by this `RowPartition`. + + Returns: + scalar integer Tensor + """ + if self._nrows is not None: + return self._nrows + nsplits = tensor_shape.dimension_at_index(self._row_splits.shape, 0) + if nsplits.value is None: + return array_ops.shape(self._row_splits, out_type=self.dtype)[0] - 1 + else: + return constant_op.constant(nsplits.value - 1, dtype=self.dtype) + + def uniform_row_length(self): + """Returns the length of each row in this partition, if rows are uniform. + + If all rows in this `RowPartition` have the same length, then this returns + that length as a scalar integer `Tensor`. Otherwise, it returns `None`. + + Returns: + scalar Tensor with `type=self.dtype`, or `None`. + """ + return self._uniform_row_length + + def row_starts(self): + """Returns the start indices for rows in this row partition. + + These indices specify where the values for each row begin. + `partition.row_starts()` is equal to `partition.row_splits()[:-1]`. + + Returns: + A 1-D integer Tensor with shape `[self.nrows()]`. + The returned tensor is nonnegative, and is sorted in ascending order. + `self.row_starts()[0] == 0`. + `self.row_starts()[-1] <= self.nvals()`. + """ + return self._row_splits[:-1] + + def row_limits(self): + """Returns the limit indices for rows in this row partition. + + These indices specify where the values for each row end. + `partition.row_limits()` is equal to `partition.row_splits()[:-1]`. + + Returns: + A 1-D integer Tensor with shape `[self.nrows]`. + The returned tensor is nonnegative, and is sorted in ascending order. + `self.row_limits()[-1] == self.nvals()`. + """ + return self._row_splits[1:] + + def row_lengths(self): + """Returns the lengths of rows in this `RowPartition`. + + Returns: + A 1-D integer Tensor with shape `[self.nrows]`. + The returned tensor is nonnegative. + `tf.reduce_sum(self.row_lengths) == self.nvals()`. + """ + if self._row_lengths is not None: + return self._row_lengths + splits = self._row_splits + return splits[1:] - splits[:-1] + + @property + def static_nrows(self): + """The number of rows in this partition, if statically known. + + ```python + self.row_lengths().shape == [self.static_nrows] + self.row_starts().shape == [self.static_nrows] + self.row_limits().shape == [self.static_nrows] + self.row_splits().shape == [self.static_nrows + 1] + ``` + + Returns: + The number of rows in this partition as an `int` (if statically known); + or `None` (otherwise). + """ + if self._row_splits is not None: + nrows_plus_one = tensor_shape.dimension_value(self._row_splits.shape[0]) + if nrows_plus_one is not None: + return nrows_plus_one - 1 + if self._row_lengths is not None: + nrows = tensor_shape.dimension_value(self._row_lengths.shape[0]) + if nrows is not None: + return nrows + if self._nrows is not None: + return tensor_util.constant_value(self._nrows) + return None + + @property + def static_nvals(self): + """The number of values in this partition, if statically known. + + ```python + self.value_rowids().shape == [self.static_vals] + ``` + + Returns: + The number of values in this partition as an `int` (if statically known); + or `None` (otherwise). + """ + if self._nvals is not None: + nvals = tensor_util.constant_value(self._nvals) + if nvals is not None: + return nvals + if self._value_rowids is not None: + nvals = tensor_shape.dimension_at_index(self._value_rowids.shape, 0) + if nvals.value is not None: + return nvals.value + return None + + @property + def static_uniform_row_length(self): + """The number of values in each row of this partition, if statically known. + + Returns: + The number of values in each row of this partition as an `int` (if + statically known); or `None` (otherwise). + """ + if self._uniform_row_length is not None: + return tensor_util.constant_value(self._uniform_row_length) + return None + + def offsets_in_rows(self): + """Return the offset of each value. + + RowPartition takes an array x and converts it into sublists. + offsets[i] is the index of x[i] in its sublist. + Given a shape, such as: + [*,*,*],[*,*],[],[*,*] + This returns: + 0,1,2,0,1,0,1 + + Returns: + an offset for every value. + """ + return gen_ragged_math_ops.ragged_range( + starts=constant_op.constant(0, self.dtype), + limits=self.row_lengths(), + deltas=constant_op.constant(1, self.dtype)).rt_dense_values + + def is_uniform(self): + """Returns true if the partition is known to be uniform statically. + + This is based upon the existence of self._uniform_row_length. For example: + RowPartition.from_row_lengths([3,3,3]).is_uniform()==false + RowPartition.from_uniform_row_length(5, nvals=20).is_uniform()==true + RowPartition.from_row_lengths([2,0,2]).is_uniform()==false + + Returns: + Whether a RowPartition is known to be uniform statically. + """ + return self._uniform_row_length is not None + + def _static_check(self): + """Checks if the object is internally consistent. + + Raises: + ValueError if inconsistent. + """ + my_dtype = self.dtype + if self._uniform_row_length is not None: + if self._uniform_row_length.dtype != my_dtype: + raise ValueError("_uniform_row_length.dtype=" + + str(self._uniform_row_length.dtype) + ", not " + + str(my_dtype)) + + if self._row_lengths is not None and self._row_lengths.dtype != my_dtype: + raise ValueError("_row_lengths.dtype=" + str(self._row_lengths.dtype) + + ", not " + str(my_dtype)) + + if self._value_rowids is not None and self._value_rowids.dtype != my_dtype: + raise ValueError("_value_rowids.dtype=" + str(self._value_rowids.dtype) + + ", not " + str(my_dtype)) + + if self._nrows is not None and self._nrows.dtype != my_dtype: + raise ValueError("_nrows.dtype=" + str(self._nrows.dtype) + ", not " + + str(my_dtype)) + + # ============================================================================= + # Transformation + # ============================================================================= + + def with_dtype(self, dtype): + """Returns a copy of this RowPartition with the given encoding dtype. + + Args: + dtype: The dtype for encoding tensors, such as `row_splits` and `nrows`. + One of `tf.int32` or `tf.int64`. + + Returns: + A copy of this RowPartition, with the encoding tensors cast to the given + type. + """ + dtype = dtypes.as_dtype(dtype) + if dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("dtype must be int32 or int64") + if self.dtype == dtype: + return self + + return RowPartition( + row_splits=_cast_if_not_none(self._row_splits, dtype), + row_lengths=_cast_if_not_none(self._row_lengths, dtype), + value_rowids=_cast_if_not_none(self._value_rowids, dtype), + nrows=_cast_if_not_none(self._nrows, dtype), + uniform_row_length=_cast_if_not_none(self._uniform_row_length, dtype), + internal=_row_partition_factory_key) + + # ============================================================================= + # String Encoding + # ============================================================================= + + def __repr__(self): + if self._uniform_row_length is not None: + return (f"tf.RowPartition(nrows={self._nrows}, " + f"uniform_row_length={self._uniform_row_length})") + else: + return f"tf.RowPartition(row_splits={self._row_splits})" + + # ============================================================================= + # Precomputed Encodings + # ============================================================================= + + def _has_precomputed_row_splits(self): + """Returns true if `row_splits` has already been computed. + + If true, then `self.row_splits()` will return its value without calling + any TensorFlow ops. + """ + return self._row_splits is not None + + def _has_precomputed_row_lengths(self): + """Returns true if `row_lengths` has already been computed. + + If true, then `self.row_lengths()` will return its value without calling + any TensorFlow ops. + """ + return self._row_lengths is not None + + def _has_precomputed_value_rowids(self): + """Returns true if `value_rowids` has already been computed. + + If true, then `self.value_rowids()` will return its value without calling + any TensorFlow ops. + """ + return self._value_rowids is not None + + def _has_precomputed_nrows(self): + """Returns true if `nrows` has already been computed. + + If true, then `self.nrows()` will return its value without calling + any TensorFlow ops. + """ + return self._nrows is not None + + def _has_precomputed_nvals(self): + """Returns true if `nvals` has already been computed. + + If true, then `self.nvals()` will return its value without calling + any TensorFlow ops. + """ + return self._nvals is not None + + def _with_precomputed_row_splits(self): + """Returns a copy of `self` with `row_splits` precomputed.""" + return RowPartition( + row_splits=self.row_splits(), + row_lengths=self._row_lengths, + value_rowids=self._value_rowids, + nrows=self._nrows, + uniform_row_length=self._uniform_row_length, + nvals=self._nvals, + internal=_row_partition_factory_key) + + def _with_precomputed_row_lengths(self): + """Returns a copy of `self` with `row_lengths` precomputed.""" + return RowPartition( + row_splits=self._row_splits, + row_lengths=self.row_lengths(), + value_rowids=self._value_rowids, + nrows=self._nrows, + nvals=self._nvals, + uniform_row_length=self._uniform_row_length, + internal=_row_partition_factory_key) + + def _with_precomputed_value_rowids(self): + """Returns a copy of `self` with `value_rowids` precomputed.""" + return RowPartition( + row_splits=self._row_splits, + row_lengths=self._row_lengths, + value_rowids=self.value_rowids(), + nrows=self._nrows, + nvals=self._nvals, + uniform_row_length=self._uniform_row_length, + internal=_row_partition_factory_key) + + def _with_precomputed_nrows(self): + """Returns a copy of `self` with `nrows` precomputed.""" + return RowPartition( + row_splits=self._row_splits, + row_lengths=self._row_lengths, + value_rowids=self._value_rowids, + nrows=self.nrows(), + nvals=self._nvals, + uniform_row_length=self._uniform_row_length, + internal=_row_partition_factory_key) + + def _with_precomputed_nvals(self): + """Returns a copy of `self` with `row_splits` precomputed.""" + return RowPartition( + row_splits=self.row_splits(), + row_lengths=self._row_lengths, + value_rowids=self._value_rowids, + nrows=self._nrows, + nvals=self.nvals(), + uniform_row_length=self._uniform_row_length, + internal=_row_partition_factory_key) + + def _merge_with_spec(self, b): + """Merge with a TypeSpec to create a new RowPartition.""" + a_spec = self._type_spec + if not a_spec.is_compatible_with(b): + # TODO(martinz): Should a dynamic check be used here? + raise ValueError("RowPartition and RowPartitionSpec are not compatible") + nrows = constant_op.constant( + b.nrows, self.dtype) if b.nrows is not None else self._nrows + nvals = constant_op.constant( + b.nvals, self.dtype) if b.nvals is not None else self._nvals + uniform_row_length = constant_op.constant( + b.uniform_row_length, self.dtype + ) if b.uniform_row_length is not None else self._uniform_row_length + return RowPartition( + row_splits=self._row_splits, + row_lengths=self._row_lengths, + value_rowids=self._value_rowids, + nvals=nvals, + uniform_row_length=uniform_row_length, + nrows=nrows, + internal=_row_partition_factory_key) + + def _merge_precomputed_encodings(self, other, validate=True): + """Returns a RowPartition that merges encodings from `self` and `other`. + + Requires that `self` and `other` describe the same partition. + + Args: + other: A `RowPartition` that encodes the same partition as `self`. + validate: If true, then add runtime checks to verify that `self` and + `other` encode the same row partition. + + Returns: + A `RowPartition`. + """ + # pylint: disable=protected-access + if (self is other or # Fast path if row partitions are equal. + (self._row_splits is other._row_splits and + self._row_lengths is other._row_lengths and + self._value_rowids is other._value_rowids and + self._nrows is other._nrows and + self._nvals is other._nvals and + self._uniform_row_length is other._uniform_row_length)): + return self + + # Merge the component tensors. We only need to validate one encoding. + # We merge less-expensive encodings first (to avoid expensive validation). + nrows, nrows_validated = _merge_tensors(self._nrows, other._nrows, "nrows", + validate) + nvals, _ = _merge_tensors(self._nvals, other._nvals, "nvals", validate) + uniform_row_length, uniform_row_length_validated = _merge_tensors( + self._uniform_row_length, other._uniform_row_length, + "uniform_row_length", validate) + if uniform_row_length_validated and nrows_validated: + validate = False # Validation complete. + row_splits, row_splits_validated = _merge_tensors(self._row_splits, + other._row_splits, + "row_splits", validate) + if row_splits_validated: + validate = False # Validation complete. + row_lengths, row_lengths_validated = _merge_tensors(self._row_lengths, + other._row_lengths, + "row_lengths", validate) + if row_lengths_validated: + validate = False # Validation complete. + value_rowids, value_rowids_validated = _merge_tensors( + self._value_rowids, other._value_rowids, "value_rowids", validate) + if value_rowids_validated and nrows_validated: + validate = False # Validation complete. + # TODO(edloper): If we make the row_splits encoding optional, then there + # will be cases where we need to do validation at this point -- e.g. if + # self has only row_splits and other has only value_rowids. But for + # now, we are guaranteed to have done validation by this point. + + # Avoid creating new RowPartition objects if we don't need to. + if (row_splits is self._row_splits and row_lengths is self._row_lengths and + value_rowids is self._value_rowids and nrows is self._nrows and + uniform_row_length is self._uniform_row_length): + return self + if (row_splits is other._row_splits and + row_lengths is other._row_lengths and + value_rowids is other._value_rowids and nrows is other._nrows and + uniform_row_length is other._uniform_row_length): + return other + + return RowPartition( + row_splits=row_splits, + row_lengths=row_lengths, + value_rowids=value_rowids, + nrows=nrows, + uniform_row_length=uniform_row_length, + nvals=nvals, + internal=_row_partition_factory_key) + + # ============================================================================= + # Composite Tensor + # ============================================================================= + + @property + def _type_spec(self): + return RowPartitionSpec.from_value(self) + + +# =============================================================================== +# RowPartitionSpec +# =============================================================================== +# TODO(edloper): Consider refactoring RowPartitionSpec to allow any combination +# of precomputed row-partition encodings (rather than always using row_splits). + + +@type_spec_registry.register("tf.RowPartitionSpec") +class RowPartitionSpec(type_spec.TypeSpec): + """Type specification for a `tf.RowPartition`.""" + + __slots__ = ["_nrows", "_nvals", "_uniform_row_length", "_dtype"] + + value_type = property(lambda self: RowPartition) + + def __init__(self, + nrows=None, + nvals=None, + uniform_row_length=None, + dtype=dtypes.int64): + """Constructs a new RowPartitionSpec. + + Args: + nrows: The number of rows in the RowPartition, or `None` if unspecified. + nvals: The number of values partitioned by the RowPartition, or `None` if + unspecified. + uniform_row_length: The number of values in each row for this + RowPartition, or `None` if rows are ragged or row length is unspecified. + dtype: The data type used to encode the partition. One of `tf.int64` or + `tf.int32`. + """ + # Wrap dimension sizes in 1D TensorShapes so the default implementations + # of TypeSpec methods such as `is_compatile_with` will work. + nrows = tensor_shape.TensorShape([nrows]) + nvals = tensor_shape.TensorShape([nvals]) + if not isinstance(uniform_row_length, tensor_shape.TensorShape): + uniform_row_length = tensor_shape.TensorShape([uniform_row_length]) + else: + uniform_row_length = uniform_row_length.with_rank(1) + + self._nrows = nrows + self._nvals = nvals + self._uniform_row_length = uniform_row_length + self._dtype = dtypes.as_dtype(dtype) + if self._dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("dtype must be tf.int32 or tf.int64") + + # Check dimension consistency, & infer dimensions when possible. + nrows = tensor_shape.dimension_value(nrows[0]) + nvals = tensor_shape.dimension_value(nvals[0]) + ncols = tensor_shape.dimension_value(uniform_row_length[0]) + if nrows == 0: # no rows -> no values. + if nvals is None: + self._nvals = tensor_shape.TensorShape([0]) + elif nvals != 0: + raise ValueError("nvals=%s is not compatible with nrows=%s" % + (nvals, nrows)) + if ncols == 0: # there are no values in each row -> no values. + if nvals is None: + self._nvals = tensor_shape.TensorShape([0]) + elif nvals != 0: + raise ValueError("nvals=%s is not compatible with uniform_row_length" + "=%s" % (nvals, uniform_row_length)) + if ncols is not None and nvals is not None: + if ncols != 0 and nvals % ncols != 0: + raise ValueError("nvals=%s is not compatible with uniform_row_length" + "=%s (doesn't divide evenly)" % (nvals, ncols)) + if nrows is not None and nvals != ncols * nrows: + raise ValueError("nvals=%s is not compatible with nrows=%s and " + "uniform_row_length=%s" % (nvals, nrows, ncols)) + if nrows is None and ncols != 0: + self._nrows = tensor_shape.TensorShape([nvals // ncols]) + if ncols is not None and nrows is not None and nvals is None: + self._nvals = tensor_shape.TensorShape([ncols * nrows]) + + def is_compatible_with(self, other): + if not super(RowPartitionSpec, self).is_compatible_with(other): + return False + nrows = self._nrows.merge_with(other.nrows) + nvals = self._nvals.merge_with(other.nvals) + ncols = self._uniform_row_length.merge_with(other.uniform_row_length) + return self._dimensions_compatible(nrows, nvals, ncols) + + def _serialize(self): + return (self._nrows, self._nvals, self._uniform_row_length, self._dtype) + + @classmethod + def _deserialize(cls, serialization): + # Remove TensorShape wrappers from serialization. + (nrows, nvals, uniform_row_length, dtype) = serialization + nrows = tensor_shape.dimension_value(nrows[0]) + nvals = tensor_shape.dimension_value(nvals[0]) + return cls(nrows, nvals, uniform_row_length, dtype) + + @property + def nrows(self): + return tensor_shape.dimension_value(self._nrows[0]) + + @property + def nvals(self): + return tensor_shape.dimension_value(self._nvals[0]) + + @property + def uniform_row_length(self): + return tensor_shape.dimension_value(self._uniform_row_length[0]) + + @property + def dtype(self): + return self._dtype + + @property + def _component_specs(self): + row_splits_shape = tensor_shape.TensorShape( + [tensor_shape.dimension_at_index(self._nrows, 0) + 1]) + return tensor_lib.TensorSpec(row_splits_shape, self._dtype) + + def _to_components(self, value): + return value.row_splits() + + def _from_components(self, tensor): + return RowPartition.from_row_splits(tensor, validate=False) + + @classmethod + def from_value(cls, value): + if not isinstance(value, RowPartition): + raise TypeError("Expected `value` to be a `RowPartition`") + return cls(value.static_nrows, value.static_nvals, + value.static_uniform_row_length, value.dtype) + + def __repr__(self): + return ("RowPartitionSpec(nrows=%s, nvals=%s, uniform_row_length=%s, " + "dtype=%r)" % (self.nrows, self.nvals, self.uniform_row_length, + self.dtype)) + + @staticmethod + def _dimensions_compatible(nrows, nvals, uniform_row_length): + """Returns true if the given dimensions are compatible.""" + nrows = tensor_shape.dimension_value(nrows[0]) + nvals = tensor_shape.dimension_value(nvals[0]) + ncols = tensor_shape.dimension_value(uniform_row_length[0]) + if nrows == 0 and nvals not in (0, None): + return False # can't have values if we have no rows. + if ncols == 0 and nvals not in (0, None): + return False # can't have values if we have no values in each row. + if ncols is not None and nvals is not None: + if ncols != 0 and nvals % ncols != 0: + return False # rows aren't uniform. + if nrows is not None and nvals != ncols * nrows: + return False # inconsistent number of values. + return True + + def _merge_with(self, other): + """Merge two RowPartitionSpecs.""" + nrows = self._nrows.merge_with(other.nrows) + nvals = self._nvals.merge_with(other.nvals) + ncols = self._uniform_row_length.merge_with(other.uniform_row_length) + + if not RowPartitionSpec._dimensions_compatible(nrows, nvals, ncols): + raise ValueError("Merging incompatible RowPartitionSpecs") + + # NOTE: if the dtypes are unequal, behavior is unspecified. + if self.dtype != other.dtype: + raise ValueError("Merging RowPartitionSpecs with incompatible dtypes") + + return RowPartitionSpec(nrows=nrows[0], + nvals=nvals[0], + uniform_row_length=ncols[0], + dtype=self.dtype) + + def with_dtype(self, dtype): + nrows = tensor_shape.dimension_value(self._nrows[0]) + nvals = tensor_shape.dimension_value(self._nvals[0]) + return RowPartitionSpec(nrows, nvals, self._uniform_row_length, dtype) + + def __deepcopy__(self, memo): + del memo + dtype = self.dtype + nrows = tensor_shape.dimension_value(self._nrows[0]) + nvals = tensor_shape.dimension_value(self._nvals[0]) + uniform_row_length = (None if self._uniform_row_length is None else + tensor_shape.dimension_value( + self._uniform_row_length[0])) + return RowPartitionSpec(nrows, nvals, uniform_row_length, dtype) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + RowPartitionSpec, struct_pb2.TypeSpecProto.ROW_PARTITION_SPEC + ) +) + + +# =============================================================================== +# Helper Functions +# =============================================================================== + + +def _assert_monotonic_increasing(tensor, message=None): + return check_ops.assert_non_negative( + tensor[1:] - tensor[:-1], message=message) + + +def _assert_zero(tensor, message=None): + return check_ops.assert_equal( + tensor, constant_op.constant(0, dtype=tensor.dtype), message=message) + + +def _cast_if_not_none(tensor, dtype): + return None if tensor is None else math_ops.cast(tensor, dtype) + + +def _merge_tensors(t1, t2, name, validate): + """Merge two optional Tensors with equal values into a single Tensor. + + Args: + t1: tf.Tensor or None + t2: tf.Tensor or None + name: A name for the tensors (for error messages) + validate: If true, then check that `t1` is compatible with `t2` (if both are + non-None). + + Returns: + A pair `(merged_value, validated)`: + * `merged_value` is `t1` if it is not None; or `t2` otherwise. + * `validated` is true if we validated that t1 and t2 are equal (either + by adding a check, or because t1 is t2). + """ + if t1 is None: + return t2, False + elif t2 is None: + return t1, False + elif t1 is t2: + return t1, True + else: + err_msg = ("RowPartition._merge_precomputed_encodings: partitions " + "have incompatible %s" % name) + if not t1.shape.is_compatible_with(t2.shape): + raise ValueError(err_msg) + if validate: + checks = [check_ops.assert_equal(t1, t2, message=err_msg)] + return control_flow_ops.with_dependencies(checks, t1), True + else: + return t1, False + +_row_partition_factory_key = object() # unique private object + + +def _get_dtype_or_none(value): + if isinstance(value, tensor_lib.Tensor): + return value.dtype + return None + + +def _get_target_dtype(values, dtype=None, dtype_hint=None): + """Gets the target dtype of a family of values.""" + if dtype is not None: + return dtype + + for value in values: + if isinstance(value, tensor_lib.Tensor): + return value.dtype + + for value in values: + if isinstance(value, np.ndarray): + return dtypes.as_dtype(value.dtype) + + if dtype_hint is not None: + return dtype_hint + + return dtypes.int64 + + +def _convert_all_to_tensors(values, dtype=None, dtype_hint=None): + """Convert a list of objects to tensors of the same dtype.""" + target_dtype = _get_target_dtype([x for (x, _) in values], dtype, dtype_hint) + + # If dtype is None, we use convert behavior. + # If dtype is not None, we use cast behavior. + convert_behavior = dtype is None + + if convert_behavior: + return [ + None if x is None else ops.convert_to_tensor( + x, dtype=target_dtype, name=name) for (x, name) in values + ] + else: + return [ + None if x is None else math_ops.cast(x, dtype=target_dtype, name=name) + for (x, name) in values + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/segment_id_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/segment_id_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..52489678f54c42d6a560c5339494aa6b732568ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ragged/segment_id_ops.py @@ -0,0 +1,134 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for converting between row_splits and segment_ids.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import ragged_util +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +# For background on "segments" and "segment ids", see: +# https://www.tensorflow.org/api_docs/python/tf/math#Segmentation +@tf_export("ragged.row_splits_to_segment_ids") +@dispatch.add_dispatch_support +def row_splits_to_segment_ids(splits, name=None, out_type=None): + """Generates the segmentation corresponding to a RaggedTensor `row_splits`. + + Returns an integer vector `segment_ids`, where `segment_ids[i] == j` if + `splits[j] <= i < splits[j+1]`. Example: + + >>> print(tf.ragged.row_splits_to_segment_ids([0, 3, 3, 5, 6, 9])) + tf.Tensor([0 0 0 2 2 3 4 4 4], shape=(9,), dtype=int64) + + Args: + splits: A sorted 1-D integer Tensor. `splits[0]` must be zero. + name: A name prefix for the returned tensor (optional). + out_type: The dtype for the return value. Defaults to `splits.dtype`, + or `tf.int64` if `splits` does not have a dtype. + + Returns: + A sorted 1-D integer Tensor, with `shape=[splits[-1]]` + + Raises: + ValueError: If `splits` is invalid. + """ + with ops.name_scope(name, "RaggedSplitsToSegmentIds", [splits]) as name: + splits = ops.convert_to_tensor( + splits, name="splits", + preferred_dtype=dtypes.int64) + if splits.dtype not in (dtypes.int32, dtypes.int64): + raise ValueError("splits must have dtype int32 or int64") + splits.shape.assert_has_rank(1) + if tensor_shape.dimension_value(splits.shape[0]) == 0: + raise ValueError("Invalid row_splits: []") + if out_type is None: + out_type = splits.dtype + else: + out_type = dtypes.as_dtype(out_type) + row_lengths = splits[1:] - splits[:-1] + nrows = array_ops.shape(splits, out_type=out_type)[-1] - 1 + indices = math_ops.range(nrows) + return ragged_util.repeat(indices, repeats=row_lengths, axis=0) + + +# For background on "segments" and "segment ids", see: +# https://www.tensorflow.org/api_docs/python/tf/math#Segmentation +@tf_export("ragged.segment_ids_to_row_splits") +@dispatch.add_dispatch_support +def segment_ids_to_row_splits(segment_ids, num_segments=None, + out_type=None, name=None): + """Generates the RaggedTensor `row_splits` corresponding to a segmentation. + + Returns an integer vector `splits`, where `splits[0] = 0` and + `splits[i] = splits[i-1] + count(segment_ids==i)`. Example: + + >>> print(tf.ragged.segment_ids_to_row_splits([0, 0, 0, 2, 2, 3, 4, 4, 4])) + tf.Tensor([0 3 3 5 6 9], shape=(6,), dtype=int64) + + Args: + segment_ids: A 1-D integer Tensor. + num_segments: A scalar integer indicating the number of segments. Defaults + to `max(segment_ids) + 1` (or zero if `segment_ids` is empty). + out_type: The dtype for the return value. Defaults to `segment_ids.dtype`, + or `tf.int64` if `segment_ids` does not have a dtype. + name: A name prefix for the returned tensor (optional). + + Returns: + A sorted 1-D integer Tensor, with `shape=[num_segments + 1]`. + """ + # Local import bincount_ops to avoid import-cycle. + from tensorflow.python.ops import bincount_ops # pylint: disable=g-import-not-at-top + if out_type is None: + if isinstance(segment_ids, tensor.Tensor): + out_type = segment_ids.dtype + elif isinstance(num_segments, tensor.Tensor): + out_type = num_segments.dtype + else: + out_type = dtypes.int64 + else: + out_type = dtypes.as_dtype(out_type) + with ops.name_scope(name, "SegmentIdsToRaggedSplits", [segment_ids]) as name: + # Note: we cast int64 tensors to int32, since bincount currently only + # supports int32 inputs. + segment_ids = ragged_util.convert_to_int_tensor(segment_ids, "segment_ids", + dtype=dtypes.int32) + segment_ids.shape.assert_has_rank(1) + if num_segments is not None: + num_segments = ragged_util.convert_to_int_tensor(num_segments, + "num_segments", + dtype=dtypes.int32) + num_segments.shape.assert_has_rank(0) + + row_lengths = bincount_ops.bincount( + segment_ids, + minlength=num_segments, + maxlength=num_segments, + dtype=out_type) + splits = array_ops.concat([[0], math_ops.cumsum(row_lengths)], axis=0) + + # Update shape information, if possible. + if num_segments is not None: + const_num_segments = tensor_util.constant_value(num_segments) + if const_num_segments is not None: + splits.set_shape(tensor_shape.TensorShape([const_num_segments + 1])) + + return splits diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_crop_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_crop_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7c103493e3c681fd39dcaf2835d29f4f4616796e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_crop_ops.py @@ -0,0 +1,136 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for random tensor cropping.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("image.random_crop", v1=["image.random_crop", "random_crop"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_crop") +def random_crop(value, size, seed=None, name=None): + """Randomly crops a tensor to a given size. + + Slices a shape `size` portion out of `value` at a uniformly chosen offset. + Requires `value.shape >= size`. + + If a dimension should not be cropped, pass the full size of that dimension. + For example, RGB images can be cropped with + `size = [crop_height, crop_width, 3]`. + + Example usage: + + >>> image = [[1, 2, 3], [4, 5, 6]] + >>> result = tf.image.random_crop(value=image, size=(1, 3)) + >>> result.shape.as_list() + [1, 3] + + For producing deterministic results given a `seed` value, use + `tf.image.stateless_random_crop`. Unlike using the `seed` param with + `tf.image.random_*` ops, `tf.image.stateless_random_*` ops guarantee the same + results given the same seed independent of how many times the function is + called, and independent of global seed settings (e.g. tf.random.set_seed). + + Args: + value: Input tensor to crop. + size: 1-D tensor with size the rank of `value`. + seed: Python integer. Used to create a random seed. See + `tf.random.set_seed` + for behavior. + name: A name for this operation (optional). + + Returns: + A cropped tensor of the same rank as `value` and shape `size`. + """ + with ops.name_scope(name, "random_crop", [value, size]) as name: + value = ops.convert_to_tensor(value, name="value") + size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="size") + shape = array_ops.shape(value) + check = control_flow_assert.Assert( + math_ops.reduce_all(shape >= size), + ["Need value.shape >= size, got ", shape, size], + summarize=1000) + shape = control_flow_ops.with_dependencies([check], shape) + limit = shape - size + 1 + offset = random_ops.random_uniform( + array_ops.shape(shape), + dtype=size.dtype, + maxval=size.dtype.max, + seed=seed) % limit + return array_ops.slice(value, offset, size, name=name) + + +@tf_export("image.stateless_random_crop", v1=[]) +@dispatch.add_dispatch_support +def stateless_random_crop(value, size, seed, name=None): + """Randomly crops a tensor to a given size in a deterministic manner. + + Slices a shape `size` portion out of `value` at a uniformly chosen offset. + Requires `value.shape >= size`. + + If a dimension should not be cropped, pass the full size of that dimension. + For example, RGB images can be cropped with + `size = [crop_height, crop_width, 3]`. + + Guarantees the same results given the same `seed` independent of how many + times the function is called, and independent of global seed settings (e.g. + `tf.random.set_seed`). + + Usage Example: + + >>> image = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]] + >>> seed = (1, 2) + >>> tf.image.stateless_random_crop(value=image, size=(1, 2, 3), seed=seed) + + + Args: + value: Input tensor to crop. + size: 1-D tensor with size the rank of `value`. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + name: A name for this operation (optional). + + Returns: + A cropped tensor of the same rank as `value` and shape `size`. + """ + with ops.name_scope(name, "random_crop", [value, size]) as name: + value = ops.convert_to_tensor(value, name="value") + size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="size") + shape = array_ops.shape(value) + check = control_flow_assert.Assert( + math_ops.reduce_all(shape >= size), + ["Need value.shape >= size, got ", shape, size], + summarize=1000) + shape = control_flow_ops.with_dependencies([check], shape) + limit = shape - size + 1 + offset = stateless_random_ops.stateless_random_uniform( + array_ops.shape(shape), + dtype=size.dtype, + maxval=size.dtype.max, + seed=seed) % limit + return array_ops.slice(value, offset, size, name=name) + \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..a7984ff7cd5fca8bbc5f3763cc975deee74de2ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_grad.py @@ -0,0 +1,269 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in random_ops.py.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_random_ops +from tensorflow.python.ops import math_ops + + +def add_leading_unit_dimensions(x, num_dimensions): # pylint: disable=invalid-name + new_shape = array_ops.concat( + [array_ops.ones([num_dimensions], dtype=dtypes.int32), + array_ops.shape(x)], axis=0) + return array_ops.reshape(x, new_shape) + + +@ops.RegisterGradient("RandomGamma") +def _RandomGammaGrad(op: ops.Operation, grad): # pylint: disable=invalid-name + """Returns the gradient of a Gamma sample w.r.t. alpha. + + The gradient is computed using implicit differentiation + (Figurnov et al., 2018). + + Args: + op: A `RandomGamma` operation. We assume that the inputs to the operation + are `shape` and `alpha` tensors, and the output is the `sample` tensor. + grad: The incoming gradient `dloss / dsample` of the same shape as + `op.outputs[0]`. + + Returns: + A `Tensor` with derivatives `dloss / dalpha`. + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + shape = op.inputs[0] + alpha = op.inputs[1] + sample = op.outputs[0] + + with ops.control_dependencies([grad]): + # Make the parameters alpha broadcastable with samples by appending + # unit dimensions. + num_sample_dimensions = array_ops.shape(shape)[0] + alpha_broadcastable = add_leading_unit_dimensions( + alpha, num_sample_dimensions) + partial_a = gen_random_ops.random_gamma_grad(alpha_broadcastable, sample) + + # The first input is shape; the second input is alpha. + return (None, math_ops.reduce_sum( + grad * partial_a, axis=math_ops.range(num_sample_dimensions))) + + +@ops.RegisterGradient("StatelessRandomGammaV2") +def _StatelessRandomGammaV2Grad(op: ops.Operation, grad): # pylint: disable=invalid-name + """Returns the gradient of a Gamma sample w.r.t. alpha. + + The gradient is computed using implicit differentiation + (Figurnov et al., 2018). + + Args: + op: A `StatelessRandomGamma` operation. We assume that the inputs to the + operation are `shape`, `seed` and `alpha` tensors, and the output is the + `sample` tensor. + grad: The incoming gradient `dloss / dsample` of the same shape as + `op.outputs[0]`. + + Returns: + A `Tensor` with derivatives `dloss / dalpha`. + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + shape = op.inputs[0] + alpha = op.inputs[2] + sample = op.outputs[0] + + with ops.control_dependencies([grad]): + return (None, None, _StatelessGammaGradAlpha(shape, alpha, sample, grad)) + + +@ops.RegisterGradient("StatelessRandomGammaV3") +def _StatelessRandomGammaV3Grad(op: ops.Operation, grad): # pylint: disable=invalid-name + """Returns the gradient of a Gamma sample w.r.t. alpha. + + The gradient is computed using implicit differentiation + (Figurnov et al., 2018). + + Args: + op: A `StatelessRandomGamma` operation. We assume that the inputs to the + operation are `shape`, `key`, `counter`, `alg`, and `alpha` tensors, and + the output is the `sample` tensor. + grad: The incoming gradient `dloss / dsample` of the same shape as + `op.outputs[0]`. + + Returns: + A `Tensor` with derivatives `dloss / dalpha`. + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + shape = op.inputs[0] + alpha = op.inputs[4] + sample = op.outputs[0] + + with ops.control_dependencies([grad]): + return (None, None, None, None, + _StatelessGammaGradAlpha(shape, alpha, sample, grad)) + + +def _StatelessGammaGradAlpha(shape, alpha, sample, grad): + """Returns gradients of a gamma sampler wrt alpha.""" + # Note that the shape handling is slightly different for stateless_gamma, + # in particular num_sample_dimensions is different. + num_sample_dimensions = array_ops.shape(shape)[0] - array_ops.rank(alpha) + # Make the parameters alpha broadcastable with samples by appending + # unit dimensions. + alpha_broadcastable = add_leading_unit_dimensions(alpha, + num_sample_dimensions) + partial_a = gen_random_ops.random_gamma_grad(alpha_broadcastable, sample) + + # The first two inputs are shape, seed, third input is alpha. + return math_ops.reduce_sum( + grad * partial_a, axis=math_ops.range(num_sample_dimensions)) + + +def _Ndtr(x): + """Normal distribution function.""" + half_sqrt_2 = constant_op.constant( + 0.5 * np.sqrt(2.), dtype=x.dtype, name="half_sqrt_2") + w = x * half_sqrt_2 + z = math_ops.abs(w) + y = array_ops.where( + z < half_sqrt_2, + 1. + math_ops.erf(w), + array_ops.where( + w > 0., 2. - math_ops.erfc(z), math_ops.erfc(z))) + return 0.5 * y + + +@ops.RegisterGradient("StatelessParameterizedTruncatedNormal") +def _StatelessParameterizedTruncatedNormalGrad(op: ops.Operation, grad): # pylint: disable=invalid-name + """Returns the gradient of a TruncatedNormal sample w.r.t. parameters. + + The gradient is computed using implicit differentiation + (Figurnov et al., 2018). + + Args: + op: A `StatelessParameterizedTruncatedNormal` operation. We assume that the + inputs to the operation are `shape`, `seed`, `mean`, `stddev`, `minval`, + and `maxval` tensors, and the output is the `sample` tensor. + grad: The incoming gradient `dloss / dsample` of the same shape as + `op.outputs[0]`. + + Returns: + A list of `Tensor` with derivates with respect to each parameter. + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + shape = op.inputs[0] + mean = op.inputs[2] + stddev = op.inputs[3] + minval = op.inputs[4] + maxval = op.inputs[5] + sample = op.outputs[0] + + with ops.control_dependencies([grad]): + minval_std = (minval - mean) / stddev + maxval_std = (maxval - mean) / stddev + sample_std = (sample - mean) / stddev + + cdf_sample = (_Ndtr(sample_std) - _Ndtr(minval_std)) / ( + _Ndtr(maxval_std) - _Ndtr(minval_std)) + + # Clip to avoid zero argument for log_cdf expression + tiny = np.finfo(mean.dtype.as_numpy_dtype).tiny + eps = np.finfo(mean.dtype.as_numpy_dtype).eps + cdf_sample = clip_ops.clip_by_value(cdf_sample, tiny, 1 - eps) + + dmaxval = math_ops.exp(0.5 * (sample_std ** 2 - maxval_std ** 2) + + math_ops.log(cdf_sample)) + dminval = math_ops.exp(0.5 * (sample_std ** 2 - minval_std ** 2) + + math_ops.log1p(-cdf_sample)) + dmean = array_ops.ones_like(sample_std) + dstddev = sample_std + + # Reduce over extra dimensions caused by `shape`. We need to get the + # difference in rank from shape vs. the broadcasted rank. + + mean_shape = array_ops.shape(mean) + stddev_shape = array_ops.shape(stddev) + minval_shape = array_ops.shape(minval) + maxval_shape = array_ops.shape(maxval) + + broadcast_shape = array_ops.broadcast_dynamic_shape( + mean_shape, stddev_shape) + broadcast_shape = array_ops.broadcast_dynamic_shape( + minval_shape, broadcast_shape) + broadcast_shape = array_ops.broadcast_dynamic_shape( + maxval_shape, broadcast_shape) + extra_dims = math_ops.range( + array_ops.size(shape) - array_ops.size(broadcast_shape)) + + grad_mean = math_ops.reduce_sum(grad * dmean, axis=extra_dims) + grad_stddev = math_ops.reduce_sum(grad * dstddev, axis=extra_dims) + grad_minval = math_ops.reduce_sum(grad * dminval, axis=extra_dims) + grad_maxval = math_ops.reduce_sum(grad * dmaxval, axis=extra_dims) + + _, rmean = gen_array_ops.broadcast_gradient_args( + broadcast_shape, mean_shape) + _, rstddev = gen_array_ops.broadcast_gradient_args( + broadcast_shape, stddev_shape) + _, rminval = gen_array_ops.broadcast_gradient_args( + broadcast_shape, minval_shape) + _, rmaxval = gen_array_ops.broadcast_gradient_args( + broadcast_shape, maxval_shape) + + grad_mean = array_ops.reshape( + math_ops.reduce_sum(grad_mean, axis=rmean, keepdims=True), mean_shape) + + grad_stddev = array_ops.reshape( + math_ops.reduce_sum(grad_stddev, axis=rstddev, keepdims=True), + stddev_shape) + + grad_minval = array_ops.reshape( + math_ops.reduce_sum(grad_minval, axis=rminval, keepdims=True), + minval_shape) + + grad_maxval = array_ops.reshape( + math_ops.reduce_sum(grad_maxval, axis=rmaxval, keepdims=True), + maxval_shape) + + # The first two inputs are shape. + return (None, None, grad_mean, grad_stddev, grad_minval, grad_maxval) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..366b2e631ac2e3eb332188fc1ddb76d71a991b5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops.py @@ -0,0 +1,629 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for generating random numbers.""" + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_random_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import shape_util + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_random_ops import * +# pylint: enable=wildcard-import + +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("random.normal", v1=["random.normal", "random_normal"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_normal") +def random_normal(shape, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + seed=None, + name=None): + """Outputs random values from a normal distribution. + + Example that generates a new set of random values every time: + + >>> tf.random.set_seed(5); + >>> tf.random.normal([4], 0, 1, tf.float32) + + + Example that outputs a reproducible result: + + >>> tf.random.set_seed(5); + >>> tf.random.normal([2,2], 0, 1, tf.float32, seed=1) + + + In this case, we are setting both the global and operation-level seed to + ensure this result is reproducible. See `tf.random.set_seed` for more + information. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + mean: A Tensor or Python value of type `dtype`, broadcastable with `stddev`. + The mean of the normal distribution. + stddev: A Tensor or Python value of type `dtype`, broadcastable with `mean`. + The standard deviation of the normal distribution. + dtype: The float type of the output: `float16`, `bfloat16`, `float32`, + `float64`. Defaults to `float32`. + seed: A Python integer. Used to create a random seed for the distribution. + See + `tf.random.set_seed` + for behavior. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random normal values. + """ + with ops.name_scope(name, "random_normal", [shape, mean, stddev]) as name: + shape_tensor = shape_util.shape_tensor(shape) + mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + seed1, seed2 = random_seed.get_seed(seed) + rnd = gen_random_ops.random_standard_normal( + shape_tensor, dtype, seed=seed1, seed2=seed2) + mul = rnd * stddev_tensor + value = math_ops.add(mul, mean_tensor, name=name) + shape_util.maybe_set_static_shape(value, shape) + return value + + +ops.NotDifferentiable("RandomStandardNormal") + + +def parameterized_truncated_normal(shape, + means=0.0, + stddevs=1.0, + minvals=-2.0, + maxvals=2.0, + dtype=dtypes.float32, + seed=None, + name=None): + """Outputs random values from a truncated normal distribution. + + The generated values follow a normal distribution with specified mean and + standard deviation, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + means: A 0-D Tensor or Python value of type `dtype`. The mean of the + truncated normal distribution. + stddevs: A 0-D Tensor or Python value of type `dtype`. The standard + deviation of the truncated normal distribution. + minvals: A 0-D Tensor or Python value of type `dtype`. The minimum value of + the truncated normal distribution. + maxvals: A 0-D Tensor or Python value of type `dtype`. The maximum value of + the truncated normal distribution. + dtype: The type of the output. + seed: A Python integer. Used to create a random seed for the distribution. + See + `tf.random.set_seed` + for behavior. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random truncated normal values. + """ + with ops.name_scope(name, "parameterized_truncated_normal", + [shape, means, stddevs, minvals, maxvals]) as name: + shape_tensor = shape_util.shape_tensor(shape) + means_tensor = ops.convert_to_tensor(means, dtype=dtype, name="means") + stddevs_tensor = ops.convert_to_tensor(stddevs, dtype=dtype, name="stddevs") + minvals_tensor = ops.convert_to_tensor(minvals, dtype=dtype, name="minvals") + maxvals_tensor = ops.convert_to_tensor(maxvals, dtype=dtype, name="maxvals") + seed1, seed2 = random_seed.get_seed(seed) + rnd = gen_random_ops.parameterized_truncated_normal( + shape_tensor, + means_tensor, + stddevs_tensor, + minvals_tensor, + maxvals_tensor, + seed=seed1, + seed2=seed2) + shape_util.maybe_set_static_shape(rnd, shape) + return rnd + + +@tf_export("random.truncated_normal", + v1=["random.truncated_normal", "truncated_normal"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("truncated_normal") +def truncated_normal(shape, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + seed=None, + name=None): + """Outputs random values from a truncated normal distribution. + + The values are drawn from a normal distribution with specified mean and + standard deviation, discarding and re-drawing any samples that are more than + two standard deviations from the mean. + + Examples: + + >>> tf.random.truncated_normal(shape=[2]) + + + >>> tf.random.truncated_normal(shape=[2], mean=3, stddev=1, dtype=tf.float32) + + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + mean: A 0-D Tensor or Python value of type `dtype`. The mean of the + truncated normal distribution. + stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation + of the normal distribution, before truncation. + dtype: The type of the output. Restricted to floating-point types: + `tf.half`, `tf.float`, `tf.double`, etc. + seed: A Python integer. Used to create a random seed for the distribution. + See `tf.random.set_seed` for more information. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random truncated normal values. + """ + with ops.name_scope(name, "truncated_normal", [shape, mean, stddev]) as name: + shape_tensor = shape_util.shape_tensor(shape) + mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + seed1, seed2 = random_seed.get_seed(seed) + rnd = gen_random_ops.truncated_normal( + shape_tensor, dtype, seed=seed1, seed2=seed2) + mul = rnd * stddev_tensor + value = math_ops.add(mul, mean_tensor, name=name) + shape_util.maybe_set_static_shape(value, shape) + return value + + +ops.NotDifferentiable("ParameterizedTruncatedNormal") +ops.NotDifferentiable("TruncatedNormal") + + +@tf_export("random.uniform", v1=["random.uniform", "random_uniform"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_uniform") +def random_uniform(shape, + minval=0, + maxval=None, + dtype=dtypes.float32, + seed=None, + name=None): + """Outputs random values from a uniform distribution. + + The generated values follow a uniform distribution in the range + `[minval, maxval)`. The lower bound `minval` is included in the range, while + the upper bound `maxval` is excluded. + + For floats, the default range is `[0, 1)`. For ints, at least `maxval` must + be specified explicitly. + + In the integer case, the random integers are slightly biased unless + `maxval - minval` is an exact power of two. The bias is small for values of + `maxval - minval` significantly smaller than the range of the output (either + `2**32` or `2**64`). + + Examples: + + >>> tf.random.uniform(shape=[2]) + + >>> tf.random.uniform(shape=[], minval=-1., maxval=0.) + + >>> tf.random.uniform(shape=[], minval=5, maxval=10, dtype=tf.int64) + + + The `seed` argument produces a deterministic sequence of tensors across + multiple calls. To repeat that sequence, use `tf.random.set_seed`: + + >>> tf.random.set_seed(5) + >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) + + >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) + + >>> tf.random.set_seed(5) + >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) + + >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) + + + Without `tf.random.set_seed` but with a `seed` argument is specified, small + changes to function graphs or previously executed operations will change the + returned value. See `tf.random.set_seed` for details. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + minval: A Tensor or Python value of type `dtype`, broadcastable with + `shape` (for integer types, broadcasting is not supported, so it needs to + be a scalar). The lower bound on the range of random values to generate + (inclusive). Defaults to 0. + maxval: A Tensor or Python value of type `dtype`, broadcastable with + `shape` (for integer types, broadcasting is not supported, so it needs to + be a scalar). The upper bound on the range of random values to generate + (exclusive). Defaults to 1 if `dtype` is floating point. + dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`, + `int32`, or `int64`. Defaults to `float32`. + seed: A Python integer. Used in combination with `tf.random.set_seed` to + create a reproducible sequence of tensors across multiple calls. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random uniform values. + + Raises: + ValueError: If `dtype` is integral and `maxval` is not specified. + """ + dtype = dtypes.as_dtype(dtype) + accepted_dtypes = (dtypes.float16, dtypes.bfloat16, dtypes.float32, + dtypes.float64, dtypes.int32, dtypes.int64) + if dtype not in accepted_dtypes: + raise ValueError( + f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are " + f"{accepted_dtypes}.") + if maxval is None: + if dtype.is_integer: + raise ValueError("Must specify maxval for integer dtype %r" % dtype) + maxval = 1 + with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name: + shape = shape_util.shape_tensor(shape) + # In case of [0,1) floating results, minval and maxval is unused. We do an + # `is` comparison here since this is cheaper than isinstance or __eq__. + minval_is_zero = isinstance(minval, int) and minval == 0 + maxval_is_one = isinstance(maxval, int) and maxval == 1 + if not minval_is_zero or not maxval_is_one or dtype.is_integer: + minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") + maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") + seed1, seed2 = random_seed.get_seed(seed) + if dtype.is_integer: + result = gen_random_ops.random_uniform_int( + shape, minval, maxval, seed=seed1, seed2=seed2, name=name) + else: + result = gen_random_ops.random_uniform( + shape, dtype, seed=seed1, seed2=seed2) + if minval_is_zero: + if not maxval_is_one: + result = math_ops.multiply(result, maxval) + else: + result = math_ops.add(result * (maxval - minval), minval, name=name) + # TODO(b/132092188): C++ shape inference inside functional ops does not + # cross FuncGraph boundaries since that information is only available in + # python. So we manually get the static shape using + # `constant_value_as_shape` which *does* cross function boundaries. + shape_util.maybe_set_static_shape(result, shape) + return result + + +ops.NotDifferentiable("RandomUniform") + + +@tf_export("random.shuffle", v1=["random.shuffle", "random_shuffle"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_shuffle") +def random_shuffle(value, seed=None, name=None): + """Randomly shuffles a tensor along its first dimension. + + The tensor is shuffled along dimension 0, such that each `value[j]` is mapped + to one and only one `output[i]`. For example, a mapping that might occur for a + 3x2 tensor is: + + ```python + [[1, 2], [[5, 6], + [3, 4], ==> [1, 2], + [5, 6]] [3, 4]] + ``` + + Args: + value: A Tensor to be shuffled. + seed: A Python integer. Used to create a random seed for the distribution. + See + `tf.random.set_seed` + for behavior. + name: A name for the operation (optional). + + Returns: + A tensor of same shape and type as `value`, shuffled along its first + dimension. + """ + seed1, seed2 = random_seed.get_seed(seed) + return gen_random_ops.random_shuffle( + value, seed=seed1, seed2=seed2, name=name) + + +ops.NotDifferentiable("RandomShuffle") + + +@tf_export(v1=["random.multinomial", "multinomial"]) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, instructions="Use `tf.random.categorical` instead.") +def multinomial(logits, num_samples, seed=None, name=None, output_dtype=None): + """Draws samples from a multinomial distribution. + + Example: + + ```python + # samples has shape [1, 5], where each value is either 0 or 1 with equal + # probability. + samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5) + ``` + + Args: + logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice + `[i, :]` represents the unnormalized log-probabilities for all classes. + num_samples: 0-D. Number of independent samples to draw for each row slice. + seed: A Python integer. Used to create a random seed for the distribution. + See `tf.random.set_seed` for behavior. + name: Optional name for the operation. + output_dtype: The integer type of the output: `int32` or `int64`. Defaults + to `int64`. + + Returns: + The drawn samples of shape `[batch_size, num_samples]`. + """ + with ops.name_scope(name, "multinomial", [logits]): + return multinomial_categorical_impl(logits, num_samples, output_dtype, seed) + + +@tf_export("random.categorical") +@dispatch.add_dispatch_support +def categorical(logits, num_samples, dtype=None, seed=None, name=None): + """Draws samples from a categorical distribution. + + Example: + + ```python + # samples has shape [1, 5], where each value is either 0 or 1 with equal + # probability. + samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5) + ``` + + Args: + logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice + `[i, :]` represents the unnormalized log-probabilities for all classes. + num_samples: 0-D. Number of independent samples to draw for each row slice. + dtype: The integer type of the output: `int32` or `int64`. Defaults to + `int64`. + seed: A Python integer. Used to create a random seed for the distribution. + See `tf.random.set_seed` for behavior. + name: Optional name for the operation. + + Returns: + The drawn samples of shape `[batch_size, num_samples]`. + """ + with ops.name_scope(name, "categorical", [logits]): + return multinomial_categorical_impl(logits, num_samples, dtype, seed) + + +def multinomial_categorical_impl(logits, num_samples, dtype, seed): + """Implementation for random.categorical (v1) and random.categorical (v2).""" + logits = ops.convert_to_tensor(logits, name="logits") + dtype = dtypes.as_dtype(dtype) if dtype else dtypes.int64 + accepted_dtypes = (dtypes.int32, dtypes.int64) + if dtype not in accepted_dtypes: + raise ValueError( + f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are " + f"{accepted_dtypes}.") + seed1, seed2 = random_seed.get_seed(seed) + return gen_random_ops.multinomial( + logits, num_samples, seed=seed1, seed2=seed2, output_dtype=dtype) + + +ops.NotDifferentiable("Multinomial") + + +def _maybe_set_static_shape_helper(tensor, shape, postfix_tensor): + if (not context.executing_eagerly() and + ops.get_default_graph().building_function and + not tensor.shape.is_fully_defined()): + shape = shape_util.shape_tensor(shape) + const_shape = tensor_util.constant_value_as_shape(shape) + postfix_tensor = ops.convert_to_tensor(postfix_tensor) + tensor.set_shape(const_shape.concatenate(postfix_tensor.shape)) + + +@tf_export("random.gamma", v1=["random.gamma", "random_gamma"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_gamma") +def random_gamma(shape, + alpha, + beta=None, + dtype=dtypes.float32, + seed=None, + name=None): + """Draws `shape` samples from each of the given Gamma distribution(s). + + `alpha` is the shape parameter describing the distribution(s), and `beta` is + the inverse scale parameter(s). + + Note: Because internal calculations are done using `float64` and casting has + `floor` semantics, we must manually map zero outcomes to the smallest + possible positive floating-point value, i.e., `np.finfo(dtype).tiny`. This + means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise + should. This bias can only happen for small values of `alpha`, i.e., + `alpha << 1` or large values of `beta`, i.e., `beta >> 1`. + + The samples are differentiable w.r.t. alpha and beta. + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + Example: + + ```python + samples = tf.random.gamma([10], [0.5, 1.5]) + # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents + # the samples drawn from each distribution + + samples = tf.random.gamma([7, 5], [0.5, 1.5]) + # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] + # represents the 7x5 samples drawn from each of the two distributions + + alpha = tf.constant([[1.],[3.],[5.]]) + beta = tf.constant([[3., 4.]]) + samples = tf.random.gamma([30], alpha=alpha, beta=beta) + # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions. + + loss = tf.reduce_mean(tf.square(samples)) + dloss_dalpha, dloss_dbeta = tf.gradients(loss, [alpha, beta]) + # unbiased stochastic derivatives of the loss function + alpha.shape == dloss_dalpha.shape # True + beta.shape == dloss_dbeta.shape # True + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output samples + to be drawn per alpha/beta-parameterized distribution. + alpha: A Tensor or Python value or N-D array of type `dtype`. `alpha` + provides the shape parameter(s) describing the gamma distribution(s) to + sample. Must be broadcastable with `beta`. + beta: A Tensor or Python value or N-D array of type `dtype`. Defaults to 1. + `beta` provides the inverse scale parameter(s) of the gamma + distribution(s) to sample. Must be broadcastable with `alpha`. + dtype: The type of alpha, beta, and the output: `float16`, `float32`, or + `float64`. + seed: A Python integer. Used to create a random seed for the distributions. + See + `tf.random.set_seed` + for behavior. + name: Optional name for the operation. + + Returns: + samples: a `Tensor` of shape + `tf.concat([shape, tf.shape(alpha + beta)], axis=0)` with values of type + `dtype`. + + References: + Implicit Reparameterization Gradients: + [Figurnov et al., 2018] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients) + ([pdf] + (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf)) + """ + with ops.name_scope(name, "random_gamma", [shape, alpha, beta]): + shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32) + alpha = ops.convert_to_tensor(alpha, name="alpha", dtype=dtype) + beta = ops.convert_to_tensor( + beta if beta is not None else 1, name="beta", dtype=dtype) + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(alpha), array_ops.shape(beta)) + alpha_broadcast = array_ops.broadcast_to(alpha, broadcast_shape) + seed1, seed2 = random_seed.get_seed(seed) + result = math_ops.maximum( + np.finfo(alpha.dtype.as_numpy_dtype).tiny, + gen_random_ops.random_gamma( + shape, alpha_broadcast, seed=seed1, seed2=seed2) / beta) + _maybe_set_static_shape_helper(result, shape, alpha_broadcast) + return result + + +@tf_export(v1=["random.poisson", "random_poisson"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("random_poisson") +def random_poisson(lam, shape, dtype=dtypes.float32, seed=None, name=None): + """Draws `shape` samples from each of the given Poisson distribution(s). + + `lam` is the rate parameter describing the distribution(s). + + Example: + + ```python + samples = tf.random.poisson([0.5, 1.5], [10]) + # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents + # the samples drawn from each distribution + + samples = tf.random.poisson([12.2, 3.3], [7, 5]) + # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] + # represents the 7x5 samples drawn from each of the two distributions + ``` + + Args: + lam: A Tensor or Python value or N-D array of type `dtype`. + `lam` provides the rate parameter(s) describing the poisson + distribution(s) to sample. + shape: A 1-D integer Tensor or Python array. The shape of the output samples + to be drawn per "rate"-parameterized distribution. + dtype: The type of the output: `float16`, `float32`, `float64`, `int32` or + `int64`. + seed: A Python integer. Used to create a random seed for the distributions. + See + `tf.random.set_seed` + for behavior. + name: Optional name for the operation. + + Returns: + samples: a `Tensor` of shape `tf.concat([shape, tf.shape(lam)], axis=0)` + with values of type `dtype`. + """ + return random_poisson_v2(shape, lam, dtype, seed, name) + + +@tf_export("random.poisson", v1=[]) +@dispatch.add_dispatch_support +def random_poisson_v2(shape, lam, dtype=dtypes.float32, seed=None, name=None): + """Draws `shape` samples from each of the given Poisson distribution(s). + + `lam` is the rate parameter describing the distribution(s). + + Example: + + ```python + samples = tf.random.poisson([10], [0.5, 1.5]) + # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents + # the samples drawn from each distribution + + samples = tf.random.poisson([7, 5], [12.2, 3.3]) + # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] + # represents the 7x5 samples drawn from each of the two distributions + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output samples + to be drawn per "rate"-parameterized distribution. + lam: A Tensor or Python value or N-D array of type `dtype`. + `lam` provides the rate parameter(s) describing the poisson + distribution(s) to sample. + dtype: The type of the output: `float16`, `float32`, `float64`, `int32` or + `int64`. + seed: A Python integer. Used to create a random seed for the distributions. + See + `tf.random.set_seed` + for behavior. + name: Optional name for the operation. + + Returns: + samples: a `Tensor` of shape `tf.concat([shape, tf.shape(lam)], axis=0)` + with values of type `dtype`. + """ + with ops.name_scope(name, "random_poisson", [lam, shape]): + shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32) + seed1, seed2 = random_seed.get_seed(seed) + result = gen_random_ops.random_poisson_v2( + shape, lam, dtype=dtype, seed=seed1, seed2=seed2) + _maybe_set_static_shape_helper(result, shape, lam) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9eefcc920e316f5a4d0e45e03421c5830708ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/random_ops_util.py @@ -0,0 +1,208 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for random ops to share common usages.""" + +import enum + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import bitwise_ops +from tensorflow.python.ops import gen_stateless_random_ops_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("random.Algorithm", "random.experimental.Algorithm") +class Algorithm(enum.Enum): + """A random-number-generation (RNG) algorithm. + + Many random-number generators (e.g. the `alg` argument of + `tf.random.Generator` and `tf.random.stateless_uniform`) in TF allow + you to choose the algorithm used to generate the (pseudo-)random + numbers. You can set the algorithm to be one of the options below. + + * `PHILOX`: The Philox algorithm introduced in the paper ["Parallel + Random Numbers: As Easy as 1, 2, + 3"](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf). + * `THREEFRY`: The ThreeFry algorithm introduced in the paper + ["Parallel Random Numbers: As Easy as 1, 2, + 3"](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf). + * `AUTO_SELECT`: Allow TF to automatically select the algorithm + depending on the accelerator device. Note that with this option, + running the same TF program on different devices may result in + different random numbers. Also note that TF may select an + algorithm that is different from `PHILOX` and `THREEFRY`. + """ + + # The numbers here must match framework/rng_alg.h + PHILOX = 1 + THREEFRY = 2 + AUTO_SELECT = 3 + + +def convert_alg_to_int(alg): + """Converts algorithm to an integer. + + Args: + alg: can be one of these types: integer, Algorithm, Tensor, string. Allowed + strings are "philox" and "threefry". + + Returns: + An integer, unless the input is a Tensor in which case a Tensor is returned. + """ + if isinstance(alg, int): + return alg + if isinstance(alg, Algorithm): + return alg.value + if isinstance(alg, tensor.Tensor): + return alg + if isinstance(alg, str): + # canonicalized alg + canon_alg = alg.strip().lower().replace("-", "").replace("_", "") + if canon_alg == "philox": + return Algorithm.PHILOX.value + elif canon_alg == "threefry": + return Algorithm.THREEFRY.value + elif canon_alg == "autoselect": + return Algorithm.AUTO_SELECT.value + else: + raise ValueError(unsupported_alg_error_msg(alg)) + else: + raise TypeError( + f"Can't convert argument `alg` (of value {alg} and type {type(alg)}) " + "to int." + ) + + +def _get_key_counter(seed, alg): + """Calculates the key and counter to pass to raw RNG ops. + + This function calculates the key and counter that will be passed to + the raw RNG ops like `StatelessRandomUniformV2`. Depending on the + input `alg`, the key and counter may be scrambled or copied from + `seed`. If `alg` is `"auto_select"`, the key and counter will be + determined at runtime based on device type. + + Args: + seed: An integer tensor of shape [2]. The seed to calculate the key and + counter from. + alg: The RNG algorithm. See `tf.random.stateless_uniform` for an + explanation. + + Returns: + A pair (key, counter) suitable for V2 stateless RNG ops like + `StatelessRandomUniformV2`. + """ + if alg == Algorithm.AUTO_SELECT.value: + key, counter = gen_stateless_random_ops_v2.stateless_random_get_key_counter( + seed + ) + elif alg == Algorithm.PHILOX.value: + key, counter = _philox_scramble_seed(seed) + elif alg == Algorithm.THREEFRY.value: + key = array_ops.reshape( + _uint32s_to_uint64(math_ops.cast(seed, dtypes.uint32)), [1] + ) + counter = array_ops.zeros([1], dtypes.uint64) + else: + raise ValueError(unsupported_alg_error_msg(alg)) + return key, counter + + +def get_key_counter_alg(seed, alg): + """Calculates the key, counter and algorithm to pass to raw RNG ops. + + This function calculates the key and counter, and determines the algorithm + that will be passed to the raw RNG ops like `StatelessRandomUniformV2`. + Depending on the input `alg`, the key and counter may be scrambled or copied + from `seed`. If `alg` is `"auto_select"`, the key and counter will be + determined at runtime based on device type. + + Args: + seed: An integer tensor of shape [2]. The seed to calculate the key and + counter from. + alg: The RNG algorithm. See `tf.random.stateless_uniform` for an + explanation. + + Returns: + A pair (key, counter, algorithm) suitable for V2 stateless RNG ops like + `StatelessRandomUniformV2`. + """ + if alg is None: + alg = Algorithm.AUTO_SELECT.value + alg = convert_alg_to_int(alg) + key, counter = _get_key_counter(seed, alg) + return key, counter, alg + + +def _uint32s_to_uint64(x): + return bitwise_ops.bitwise_or( + math_ops.cast(x[0], dtypes.uint64), + bitwise_ops.left_shift( + math_ops.cast(x[1], dtypes.uint64), + constant_op.constant(32, dtypes.uint64), + ), + ) + + +def unsupported_alg_error_msg(alg): + """Produces the unsupported-algorithm error message.""" + if isinstance(alg, int): + philox = Algorithm.PHILOX.value + threefry = Algorithm.THREEFRY.value + auto_select = Algorithm.AUTO_SELECT.value + elif isinstance(alg, str): + philox = "philox" + threefry = "threefry" + auto_select = "auto_select" + else: + philox = Algorithm.PHILOX + threefry = Algorithm.THREEFRY + auto_select = Algorithm.AUTO_SELECT + return ( + f"Argument `alg` got unsupported value {alg}. Supported values are " + f"{philox} for the Philox algorithm, " + f"{threefry} for the ThreeFry algorithm, and " + f"{auto_select} for auto-selection." + ) + + +def _philox_scramble_seed(seed): + """Determines the key and counter for Philox PRNG with the given seed. + + Args: + seed: An integer tensor of shape [2]. The seed to calculate the key and + counter from. + + Returns: + A pair (key, counter) suitable for V2 stateless RNG ops like + `StatelessRandomUniformV2`. + """ + # the same scrambling procedure as core/kernels/stateless_random_ops.cc + key = constant_op.constant([0x02461E293EC8F720], dtypes.uint64) + counter = math_ops.cast(seed, dtypes.uint64) + mix = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2( + [4], + key=key, + counter=counter, + dtype=dtypes.uint32, + alg=Algorithm.PHILOX.value, + ) + key = array_ops.reshape(_uint32s_to_uint64(mix[:2]), [1]) + counter = array_ops_stack.stack([0, _uint32s_to_uint64(mix[2:])], axis=0) + return key, counter diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ref_variable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ref_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..aebba7307699b4f9cf5c8fe9a957a744dfb1f2bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/ref_variable.py @@ -0,0 +1,1350 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""RefVariable class.""" + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import variable_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_state_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import core +from tensorflow.python.util import compat +from tensorflow.python.util.deprecation import deprecated + + +def default_variable_creator(next_creator=None, **kwargs): + """Default variable creator.""" + assert next_creator is None + initial_value = kwargs.get("initial_value", None) + trainable = kwargs.get("trainable", None) + collections = kwargs.get("collections", None) + validate_shape = kwargs.get("validate_shape", True) + caching_device = kwargs.get("caching_device", None) + name = kwargs.get("name", None) + variable_def = kwargs.get("variable_def", None) + dtype = kwargs.get("dtype", None) + expected_shape = kwargs.get("expected_shape", None) + import_scope = kwargs.get("import_scope", None) + constraint = kwargs.get("constraint", None) + use_resource = kwargs.get("use_resource", None) + synchronization = kwargs.get("synchronization", None) + aggregation = kwargs.get("aggregation", None) + shape = kwargs.get("shape", None) + + if use_resource is None: + use_resource = variable_scope.get_variable_scope().use_resource + if use_resource is None: + use_resource = variable_scope._DEFAULT_USE_RESOURCE # pylint: disable=protected-access + use_resource = use_resource or context.executing_eagerly() + if use_resource: + distribute_strategy = kwargs.get("distribute_strategy", None) + return resource_variable_ops.ResourceVariable( + initial_value=initial_value, + trainable=trainable, + collections=collections, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + dtype=dtype, + constraint=constraint, + variable_def=variable_def, + import_scope=import_scope, + distribute_strategy=distribute_strategy, + synchronization=synchronization, + aggregation=aggregation, + shape=shape) + else: + return RefVariable( + initial_value=initial_value, + trainable=trainable, + collections=collections, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + dtype=dtype, + constraint=constraint, + variable_def=variable_def, + expected_shape=expected_shape, + import_scope=import_scope, + synchronization=synchronization, + aggregation=aggregation, + shape=shape) + + +variable_v1.default_variable_creator = default_variable_creator + + +def _to_proto_fn(v, export_scope=None): + """Converts Variable and ResourceVariable to VariableDef for collections.""" + return v.to_proto(export_scope=export_scope) + + +def _from_proto_fn(v, import_scope=None): + """Creates Variable or ResourceVariable from VariableDef as needed.""" + if v.is_resource: + return resource_variable_ops.ResourceVariable.from_proto( + v, import_scope=import_scope) + return variable_v1.VariableV1.from_proto(v, import_scope=import_scope) + + +ops.register_proto_function( + ops.GraphKeys.GLOBAL_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.TRAINABLE_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.MOVING_AVERAGE_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.LOCAL_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.MODEL_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.GLOBAL_STEP, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) +ops.register_proto_function( + ops.GraphKeys.METRIC_VARIABLES, + proto_type=variable_pb2.VariableDef, + to_proto=_to_proto_fn, + from_proto=_from_proto_fn) + + +# TODO(apassos): do not repeat all comments here +class RefVariable(variable_v1.VariableV1, core.Tensor): + """Ref-based implementation of variables.""" + + def __init__( + self, # pylint: disable=super-init-not-called + initial_value=None, + trainable=None, + collections=None, + validate_shape=True, + caching_device=None, + name=None, + variable_def=None, + dtype=None, + expected_shape=None, + import_scope=None, + constraint=None, + synchronization=None, + aggregation=None, + shape=None): + """Creates a new variable with value `initial_value`. + + The new variable is added to the graph collections listed in `collections`, + which defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + + If `trainable` is `True` the variable is also added to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. + + This constructor creates both a `variable` Op and an `assign` Op to set the + variable to its initial value. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. In + that case, `dtype` must be specified. (Note that initializer functions + from init_ops.py must first be bound to a shape before being used here.) + trainable: If `True`, also adds the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default + list of variables to use by the `Optimizer` classes. Defaults to `True`, + unless `synchronization` is set to `ON_READ`, in which case it defaults + to `False`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + caching_device: Optional device string describing where the Variable + should be cached for reading. Defaults to the Variable's device. If not + `None`, caches on another device. Typical use is to cache on the device + where the Ops using the Variable reside, to deduplicate copying through + `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + variable_def: `VariableDef` protocol buffer. If not `None`, recreates the + Variable object with its contents, referencing the variable's nodes in + the graph, which must already exist. The graph is not changed. + `variable_def` and the other arguments are mutually exclusive. + dtype: If set, initial_value will be converted to the given type. If + `None`, either the datatype will be kept (if `initial_value` is a + Tensor), or `convert_to_tensor` will decide. + expected_shape: A TensorShape. If set, initial_value is expected to have + this shape. + import_scope: Optional `string`. Name scope to add to the `Variable.` Only + used when initializing from protocol buffer. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + + Raises: + ValueError: If both `variable_def` and initial_value are specified. + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + RuntimeError: If eager execution is enabled. + """ + self._in_graph_mode = True + if variable_def: + # If variable_def is provided, recreates the variable from its fields. + if initial_value: + raise ValueError("variable_def and initial_value are mutually " + "exclusive.") + self._init_from_proto(variable_def, import_scope=import_scope) + else: + # Create from initial_value. + self._init_from_args( + initial_value=initial_value, + trainable=trainable, + collections=collections, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + dtype=dtype, + expected_shape=expected_shape, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + shape=shape) + + def __repr__(self): + if context.executing_eagerly() and not self._in_graph_mode: + return "" % ( + self.name, self.get_shape(), self.dtype.name, + ops.numpy_text(self.read_value(), is_repr=True)) + else: + return "" % ( + self.name, self.get_shape(), self.dtype.name) + + def _init_from_args(self, + initial_value=None, + trainable=None, + collections=None, + validate_shape=True, + caching_device=None, + name=None, + dtype=None, + expected_shape=None, + constraint=None, + synchronization=None, + aggregation=None, + shape=None): + """Creates a new variable from arguments. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. + (Note that initializer functions from init_ops.py must first be bound to + a shape before being used here.) + trainable: If `True`, also adds the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default + list of variables to use by the `Optimizer` classes. Defaults to `True`, + unless `synchronization` is set to `ON_READ`, in which case it defaults + to `False`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + dtype: If set, initial_value will be converted to the given type. If None, + either the datatype will be kept (if initial_value is a Tensor) or + float32 will be used (if it is a Python object convertible to a Tensor). + expected_shape: Deprecated. Ignored. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + + Raises: + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + RuntimeError: If lifted into the eager context. + """ + _ = expected_shape + if initial_value is None: + raise ValueError("initial_value must be specified.") + init_from_fn = callable(initial_value) + + if collections is None: + collections = [ops.GraphKeys.GLOBAL_VARIABLES] + if not isinstance(collections, (list, tuple, set)): + raise ValueError( + "collections argument to Variable constructor must be a list, tuple, " + "or set. Got %s of type %s" % (collections, type(collections))) + if constraint is not None and not callable(constraint): + raise ValueError("The `constraint` argument must be a callable.") + + # Store the graph key so optimizers know how to only retrieve variables from + # this graph. + self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access + if isinstance(initial_value, trackable.CheckpointInitialValue): + self._maybe_initialize_trackable() + self._update_uid = initial_value.checkpoint_position.restore_uid + initial_value = initial_value.wrapped_value + + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name)) + self._synchronization = synchronization + self._aggregation = aggregation + self._trainable = trainable + if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections: + collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES] + with ops.init_scope(): + # Ensure that we weren't lifted into the eager context. + if context.executing_eagerly(): + raise RuntimeError( + "Reference variables are not supported when eager execution is " + "enabled. Please run `tf.compat.v1.enable_resource_variables()` to " + "switch to resource variables.") + with ops.name_scope(name, "Variable", + [] if init_from_fn else [initial_value]) as name: + + if init_from_fn: + # Use attr_scope and device(None) to simulate the behavior of + # colocate_with when the variable we want to colocate with doesn't + # yet exist. + true_name = ops.name_from_scope_name(name) # pylint: disable=protected-access + attr = attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue( + s=[compat.as_bytes("loc:@%s" % true_name)])) + # pylint: disable=protected-access + with ops.get_default_graph()._attr_scope({"_class": attr}): + with ops.name_scope("Initializer"), ops.device(None): + initial_value = initial_value() + if isinstance(initial_value, trackable.CheckpointInitialValue): + self._maybe_initialize_trackable() + self._update_uid = initial_value.checkpoint_position.restore_uid + initial_value = initial_value.wrapped_value + self._initial_value = ops.convert_to_tensor( + initial_value, name="initial_value", dtype=dtype) + if shape is None: + shape = ( + self._initial_value.get_shape() + if validate_shape else tensor_shape.unknown_shape()) + self._variable = state_ops.variable_op_v2( + shape, self._initial_value.dtype.base_dtype, name=name) + # pylint: enable=protected-access + + # Or get the initial value from a Tensor or Python object. + else: + self._initial_value = ops.convert_to_tensor( + initial_value, name="initial_value", dtype=dtype) + # pylint: disable=protected-access + if self._initial_value.op._get_control_flow_context() is not None: + raise ValueError( + "Initializer for variable %s is from inside a control-flow " + "construct, such as a loop or conditional. When creating a " + "variable inside a loop or conditional, use a lambda as the " + "initializer." % name) + if shape is None: + # pylint: enable=protected-access + shape = ( + self._initial_value.get_shape() + if validate_shape else tensor_shape.unknown_shape()) + # In this case, the variable op can't be created until after the + # initial_value has been converted to a Tensor with a known type. + self._variable = state_ops.variable_op_v2( + shape, self._initial_value.dtype.base_dtype, name=name) + + # Cache the name in `self`, because some APIs call `Variable.name` in a + # tight loop, and this halves the cost. + self._name = self._variable.name + + # Manually overrides the variable's shape with the initial value's. + if validate_shape: + initial_value_shape = self._initial_value.get_shape() + if not initial_value_shape.is_fully_defined(): + raise ValueError("initial_value must have a shape specified: %s" % + self._initial_value) + + # If 'initial_value' makes use of other variables, make sure we don't + # have an issue if these other variables aren't initialized first by + # using their initialized_value() method. + self._initializer_op = state_ops.assign( + self._variable, + variables._try_guard_against_uninitialized_dependencies( # pylint: disable=protected-access + name, self._initial_value), + validate_shape=validate_shape).op + + # TODO(vrv): Change this class to not take caching_device, but + # to take the op to colocate the snapshot with, so we can use + # colocation rather than devices. + if caching_device is not None: + with ops.device(caching_device): + self._snapshot = array_ops.identity(self._variable, name="read") + else: + with ops.colocate_with(self._variable.op): + self._snapshot = array_ops.identity(self._variable, name="read") + ops.add_to_collections(collections, self) + + self._caching_device = caching_device + self._save_slice_info = None + self._constraint = constraint + + def _init_from_proto(self, variable_def, import_scope=None): + """Recreates the Variable object from a `VariableDef` protocol buffer. + + Args: + variable_def: `VariableDef` protocol buffer, describing a variable whose + nodes already exists in the graph. + import_scope: Optional `string`. Name scope to add. + """ + assert isinstance(variable_def, variable_pb2.VariableDef) + # Create from variable_def. + g = ops.get_default_graph() + self._variable = g.as_graph_element( + ops.prepend_name_scope( + variable_def.variable_name, import_scope=import_scope)) + self._name = self._variable.name + self._initializer_op = g.as_graph_element( + ops.prepend_name_scope( + variable_def.initializer_name, import_scope=import_scope)) + # Tests whether initial_value_name exists first for backwards compatibility. + if (hasattr(variable_def, "initial_value_name") and + variable_def.initial_value_name): + self._initial_value = g.as_graph_element( + ops.prepend_name_scope( + variable_def.initial_value_name, import_scope=import_scope)) + else: + self._initial_value = None + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + variable_def.synchronization, variable_def.aggregation, + variable_def.trainable, variable_def.variable_name)) + self._synchronization = synchronization + self._aggregation = aggregation + self._trainable = trainable + self._snapshot = g.as_graph_element( + ops.prepend_name_scope( + variable_def.snapshot_name, import_scope=import_scope)) + if variable_def.HasField("save_slice_info_def"): + self._save_slice_info = variables.Variable.SaveSliceInfo( + save_slice_info_def=variable_def.save_slice_info_def, + import_scope=import_scope) + else: + self._save_slice_info = None + self._caching_device = None + self._constraint = None + + def _as_graph_element(self): + """Conversion function for Graph.as_graph_element().""" + return self._variable + + def value(self): + """Returns the last snapshot of this variable. + + You usually do not need to call this method as all ops that need the value + of the variable call it automatically through a `convert_to_tensor()` call. + + Returns a `Tensor` which holds the value of the variable. You can not + assign a new value to this tensor as it is not a reference to the variable. + + To avoid copies, if the consumer of the returned value is on the same device + as the variable, this actually returns the live value of the variable, not + a copy. Updates to the variable are seen by the consumer. If the consumer + is on a different device it will get a copy of the variable. + + Returns: + A `Tensor` containing the value of the variable. + """ + return self._snapshot + + def read_value(self): + """Returns the value of this variable, read in the current context. + + Can be different from value() if it's on another device, with control + dependencies, etc. + + Returns: + A `Tensor` containing the value of the variable. + """ + return array_ops.identity(self._variable, name="read") + + def _ref(self): + """Returns a reference to this variable. + + You usually do not need to call this method as all ops that need a reference + to the variable call it automatically. + + Returns is a `Tensor` which holds a reference to the variable. You can + assign a new value to the variable by passing the tensor to an assign op. + See `tf.Variable.value` if you want to get the value of the + variable. + + Returns: + A `Tensor` that is a reference to the variable. + """ + return self._variable + + def set_shape(self, shape): + """Overrides the shape for this variable. + + Args: + shape: the `TensorShape` representing the overridden shape. + """ + self._ref().set_shape(shape) + self.value().set_shape(shape) + + @property + def trainable(self): + return self._trainable + + @property + def synchronization(self): + return self._synchronization + + @property + def aggregation(self): + return self._aggregation + + def eval(self, session=None): + """In a session, computes and returns the value of this variable. + + This is not a graph construction method, it does not add ops to the graph. + + This convenience method requires a session where the graph + containing this variable has been launched. If no session is + passed, the default session is used. See `tf.compat.v1.Session` for more + information on launching a graph and on sessions. + + ```python + v = tf.Variable([1, 2]) + init = tf.compat.v1.global_variables_initializer() + + with tf.compat.v1.Session() as sess: + sess.run(init) + # Usage passing the session explicitly. + print(v.eval(sess)) + # Usage with the default session. The 'with' block + # above makes 'sess' the default session. + print(v.eval()) + ``` + + Args: + session: The session to use to evaluate this variable. If none, the + default session is used. + + Returns: + A numpy `ndarray` with a copy of the value of this variable. + """ + return self._variable.eval(session=session) + + @property + def initial_value(self): + """Returns the Tensor used as the initial value for the variable. + + Note that this is different from `initialized_value()` which runs + the op that initializes the variable before returning its value. + This method returns the tensor that is used by the op that initializes + the variable. + + Returns: + A `Tensor`. + """ + return self._initial_value + + @property + def constraint(self): + """Returns the constraint function associated with this variable. + + Returns: + The constraint function that was passed to the variable constructor. + Can be `None` if no constraint was passed. + """ + return self._constraint + + def assign(self, value, use_locking=False, name=None, read_value=True): + """Assigns a new value to the variable. + + This is essentially a shortcut for `assign(self, value)`. + + Args: + value: A `Tensor`. The new value for this variable. + use_locking: If `True`, use locking during the assignment. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + A `Tensor` that will hold the new value of this variable after + the assignment has completed. + """ + assign = state_ops.assign( + self._variable, value, use_locking=use_locking, name=name) + if read_value: + return assign + return assign.op + + def assign_add(self, delta, use_locking=False, name=None, read_value=True): + """Adds a value to this variable. + + This is essentially a shortcut for `assign_add(self, delta)`. + + Args: + delta: A `Tensor`. The value to add to this variable. + use_locking: If `True`, use locking during the operation. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + A `Tensor` that will hold the new value of this variable after + the addition has completed. + """ + assign = state_ops.assign_add( + self._variable, delta, use_locking=use_locking, name=name) + if read_value: + return assign + return assign.op + + def assign_sub(self, delta, use_locking=False, name=None, read_value=True): + """Subtracts a value from this variable. + + This is essentially a shortcut for `assign_sub(self, delta)`. + + Args: + delta: A `Tensor`. The value to subtract from this variable. + use_locking: If `True`, use locking during the operation. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + A `Tensor` that will hold the new value of this variable after + the subtraction has completed. + """ + assign = state_ops.assign_sub( + self._variable, delta, use_locking=use_locking, name=name) + if read_value: + return assign + return assign.op + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + """Subtracts `tf.IndexedSlices` from this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be subtracted from this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered subtraction has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_sub( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + """Adds `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be added to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered addition has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_add( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the max of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of max with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered maximization has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_max( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the min of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of min with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered minimization has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_min( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + """Multiply this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to multiply this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered multiplication has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_mul( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + """Divide this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to divide this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered division has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_div( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered assignment has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) + return gen_state_ops.scatter_update( + self._variable, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable batch-wise. + + Analogous to `batch_gather`. This assumes that this variable and the + sparse_delta IndexedSlices have a series of leading dimensions that are the + same for all of them, and the updates are performed on the last dimension of + indices. In other words, the dimensions should be the following: + + `num_prefix_dims = sparse_delta.indices.ndims - 1` + `batch_dim = num_prefix_dims + 1` + `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[ + batch_dim:]` + + where + + `sparse_delta.updates.shape[:num_prefix_dims]` + `== sparse_delta.indices.shape[:num_prefix_dims]` + `== var.shape[:num_prefix_dims]` + + And the operation performed can be expressed as: + + `var[i_1, ..., i_n, + sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[ + i_1, ..., i_n, j]` + + When sparse_delta.indices is a 1D tensor, this operation is equivalent to + `scatter_update`. + + To avoid this operation one can looping over the first `ndims` of the + variable and using `scatter_update` on the subtensors that result of slicing + the first dimension. This is a valid option for `ndims = 1`, but less + efficient than this implementation. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered assignment has completed. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + return state_ops.batch_scatter_update( + self, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name) + + def scatter_nd_sub(self, indices, updates, name=None): + """Applies sparse subtraction to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + op = ref.scatter_nd_sub(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(op) + ``` + + The resulting update to ref would look like this: + + [1, -9, 3, -6, -6, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered subtraction has completed. + """ + return gen_state_ops.scatter_nd_sub( + self._variable, indices, updates, use_locking=True, name=name) + + def scatter_nd_add(self, indices, updates, name=None): + """Applies sparse addition to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + add = ref.scatter_nd_add(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(add) + ``` + + The resulting update to ref would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered addition has completed. + """ + return gen_state_ops.scatter_nd_add( + self._variable, indices, updates, use_locking=True, name=name) + + def scatter_nd_update(self, indices, updates, name=None): + """Applies sparse assignment to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + op = ref.scatter_nd_update(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(op) + ``` + + The resulting update to ref would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered assignment has completed. + """ + return gen_state_ops.scatter_nd_update( + self._variable, indices, updates, use_locking=True, name=name) + + def scatter_nd_max(self, indices, updates, name=None): + """Updates this variable with the max of `tf.IndexedSlices` and itself. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered addition has completed. + """ + return gen_state_ops.scatter_nd_max( + self._variable, indices, updates, use_locking=True, name=name) + + def scatter_nd_min(self, indices, updates, name=None): + """Updates this variable with the min of `tf.IndexedSlices` and itself. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + A `Tensor` that will hold the new value of this variable after + the scattered addition has completed. + """ + return gen_state_ops.scatter_nd_min( + self._variable, indices, updates, use_locking=True, name=name) + + def _strided_slice_assign(self, begin, end, strides, value, name, begin_mask, + end_mask, ellipsis_mask, new_axis_mask, + shrink_axis_mask): + return gen_array_ops.strided_slice_assign( + ref=self._ref(), + begin=begin, + end=end, + strides=strides, + value=value, + name=name, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask) + + @deprecated(None, "Prefer Dataset.range instead.") + def count_up_to(self, limit): + """Increments this variable until it reaches `limit`. + + When that Op is run it tries to increment the variable by `1`. If + incrementing the variable would bring it above `limit` then the Op raises + the exception `OutOfRangeError`. + + If no error is raised, the Op outputs the value of the variable before + the increment. + + This is essentially a shortcut for `count_up_to(self, limit)`. + + Args: + limit: value at which incrementing the variable raises an error. + + Returns: + A `Tensor` that will hold the variable value before the increment. If no + other Op modifies this variable, the values produced will all be + distinct. + """ + return state_ops.count_up_to(self._variable, limit=limit) + + # Conversion to tensor. + @staticmethod + def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name + """Utility function for converting a Variable to a Tensor.""" + _ = name + if dtype and not dtype.is_compatible_with(v.dtype): + raise ValueError( + "Incompatible type conversion requested to type '%s' for variable " + "of type '%s'" % (dtype.name, v.dtype.name)) + if as_ref: + return v._ref() # pylint: disable=protected-access + else: + return v.value() + + # NOTE(mrry): This enables the Variable's overloaded "right" binary + # operators to run when the left operand is an ndarray, because it + # accords the Variable class higher priority than an ndarray, or a + # numpy matrix. + # TODO(mrry): Convert this to using numpy's __numpy_ufunc__ + # mechanism, which allows more control over how Variables interact + # with ndarrays. + __array_priority__ = 100 + + @property + def name(self): + """The name of this variable.""" + return self._name + + @property + def initializer(self) -> ops.Operation: + """The initializer operation for this variable.""" + return self._initializer_op + + @property + def device(self): + """The device of this variable.""" + return self._variable.device + + @property + def dtype(self) -> dtypes.DType: + """The `DType` of this variable.""" + return self._variable.dtype + + @property + def op(self) -> ops.Operation: + """The `Operation` of this variable.""" + return self._variable.op + + @property + def graph(self) -> ops.Graph: + """The `Graph` of this variable.""" + return self._variable.graph + + @property + def _distribute_strategy(self): + """The `tf.distribute.Strategy` that this variable was created under.""" + return None # Ref variables are never created inside a strategy. + + @property + def shape(self): + """The `TensorShape` of this variable. + + Returns: + A `TensorShape`. + """ + return self._variable.get_shape() + + def to_proto(self, export_scope=None): + """Converts a `Variable` to a `VariableDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `VariableDef` protocol buffer, or `None` if the `Variable` is not + in the specified name scope. + """ + if (export_scope is None or self._variable.name.startswith(export_scope)): + var_def = variable_pb2.VariableDef() + var_def.variable_name = ops.strip_name_scope(self._variable.name, + export_scope) + if self._initial_value is not None: + # For backwards compatibility. + var_def.initial_value_name = ops.strip_name_scope( + self._initial_value.name, export_scope) + var_def.trainable = self.trainable + var_def.synchronization = self.synchronization.value + var_def.aggregation = self.aggregation.value + var_def.initializer_name = ops.strip_name_scope(self.initializer.name, + export_scope) + var_def.snapshot_name = ops.strip_name_scope(self._snapshot.name, + export_scope) + if self._save_slice_info: + var_def.save_slice_info_def.MergeFrom( + self._save_slice_info.to_proto(export_scope=export_scope)) + return var_def + else: + return None + + def __iadd__(self, other): + logging.log_first_n( + logging.WARN, "Variable += will be deprecated. Use variable.assign_add" + " if you want assignment to the variable value or 'x = x + y'" + " if you want a new python Tensor object.", 1) + return self + other + + def __isub__(self, other): + logging.log_first_n( + logging.WARN, "Variable -= will be deprecated. Use variable.assign_sub" + " if you want assignment to the variable value or 'x = x - y'" + " if you want a new python Tensor object.", 1) + return self - other + + def __imul__(self, other): + logging.log_first_n( + logging.WARN, + "Variable *= will be deprecated. Use `var.assign(var * other)`" + " if you want assignment to the variable value or `x = x * y`" + " if you want a new python Tensor object.", 1) + return self * other + + def __idiv__(self, other): + logging.log_first_n( + logging.WARN, + "Variable /= will be deprecated. Use `var.assign(var / other)`" + " if you want assignment to the variable value or `x = x / y`" + " if you want a new python Tensor object.", 1) + return self / other + + def __itruediv__(self, other): + logging.log_first_n( + logging.WARN, + "Variable /= will be deprecated. Use `var.assign(var / other)`" + " if you want assignment to the variable value or `x = x / y`" + " if you want a new python Tensor object.", 1) + return self / other + + def __irealdiv__(self, other): + logging.log_first_n( + logging.WARN, + "Variable /= will be deprecated. Use `var.assign(var / other)`" + " if you want assignment to the variable value or `x = x / y`" + " if you want a new python Tensor object.", 1) + return self / other + + def __ipow__(self, other): + logging.log_first_n( + logging.WARN, + "Variable **= will be deprecated. Use `var.assign(var ** other)`" + " if you want assignment to the variable value or `x = x ** y`" + " if you want a new python Tensor object.", 1) + return self**other + + def _serialize_to_tensors(self): + """Implements Trackable._serialize_to_tensors.""" + return {trackable.VARIABLE_VALUE_KEY: self} + + def _restore_from_tensors(self, restored_tensors): + """Implements Trackable._restore_from_tensors.""" + restored_tensor = restored_tensors[trackable.VARIABLE_VALUE_KEY] + return state_ops.assign( + self, + restored_tensor, + validate_shape=self.get_shape().is_fully_defined()) + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +tensor_conversion_registry.register_tensor_conversion_function( + RefVariable, RefVariable._TensorConversionFunction) # pylint: disable=protected-access + + +variable_v1.set_variable_from_proto_fn(RefVariable) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resource_variable_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resource_variable_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1a6b6280b10a72363c5043e0e5116f432468e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resource_variable_ops.py @@ -0,0 +1,2813 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops to use variables as resources.""" + +# pylint: disable=g-bad-name +import contextlib +import functools +import weakref + +import numpy as np + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import variable_pb2 +from tensorflow.core.function import trace_type +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.checkpoint import tensor_callable +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.compat import compat as forward_compat +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.eager import tape +from tensorflow.python.framework import auto_control_deps_utils as acd +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_module +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gen_state_ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variables +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_resource_variable_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import core +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import compat +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + +acd.register_read_only_resource_op("ReadVariableOp") +acd.register_read_only_resource_op("VariableShape") +acd.register_read_only_resource_op("ResourceGather") +acd.register_read_only_resource_op("ResourceGatherNd") +acd.register_read_only_resource_op("_ReadVariablesOp") + +# TODO(allenl): Remove this alias and migrate callers. +get_resource_handle_data = handle_data_util.get_resource_handle_data + + +def get_eager_safe_handle_data(handle): + """Get the data handle from the Tensor `handle`.""" + assert isinstance(handle, tensor_module.Tensor) + + if isinstance(handle, ops.EagerTensor): + return handle._handle_data # pylint: disable=protected-access + else: + return get_resource_handle_data(handle) + + +def _set_handle_shapes_and_types(tensor, handle_data, graph_mode): + """Sets the shape inference result HandleData on tensor. + + Args: + tensor: A `Tensor` or `EagerTensor`. + handle_data: A `CppShapeInferenceResult.HandleData`. + graph_mode: A python bool. + """ + tensor._handle_data = handle_data # pylint: disable=protected-access + if not graph_mode: + return + + # Not an EagerTensor, so a graph tensor. + shapes, types = zip( + *[(pair.shape, pair.dtype) for pair in handle_data.shape_and_type]) + ranks = [len(s.dim) if not s.unknown_rank else -1 for s in shapes] + shapes = [ + [d.size for d in s.dim] # pylint: disable=g-complex-comprehension + if not s.unknown_rank else None for s in shapes + ] + with tensor._op.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + pywrap_tf_session.TF_GraphSetOutputHandleShapesAndTypes_wrapper( + c_graph, + tensor._as_tf_output(), # pylint: disable=protected-access + shapes, + ranks, + types) + + +def _combine_handle_data(handle, initial_value): + """Concats HandleData from tensors `handle` and `initial_value`. + + Args: + handle: A `Tensor` of dtype `resource`. + initial_value: A `Tensor`. + + Returns: + A `CppShapeInferenceResult.HandleData`. If `initial_value` has dtype + `variant`, the `HandleData` contains the concatenation of the shape_and_type + from both `handle` and `initial_value`. + + Raises: + RuntimeError: If handle, which was returned by VarHandleOp, either has + no handle data, or its len(handle_data.shape_and_type) != 1. + """ + assert handle.dtype == dtypes.resource + + variable_handle_data = get_eager_safe_handle_data(handle) + + if initial_value.dtype != dtypes.variant: + return variable_handle_data + + extra_handle_data = get_eager_safe_handle_data(initial_value) + if extra_handle_data is not None and extra_handle_data.is_set: + if (variable_handle_data is None or not variable_handle_data.is_set or + len(variable_handle_data.shape_and_type) != 1): + raise RuntimeError( + "Expected VarHandleOp to return a length==1 shape_and_type, " + f"but saw: '{variable_handle_data}'") + variable_handle_data.shape_and_type.extend(extra_handle_data.shape_and_type) + return variable_handle_data + + +def _variable_handle_from_shape_and_dtype(shape, + dtype, + shared_name, + name, + graph_mode, + initial_value=None): + """Create a variable handle, copying in handle data from `initial_value`.""" + container = ops.get_default_graph()._container # pylint: disable=protected-access + if container is None: + container = "" + shape = tensor_shape.as_shape(shape) + dtype = dtypes.as_dtype(dtype) + if not graph_mode: + if shared_name is not None: + raise errors.InternalError( + node_def=None, + op=None, + message="Using an explicit shared_name is " + "not allowed when executing eagerly.") + shared_name = context.anonymous_name() + + handle = gen_resource_variable_ops.var_handle_op( + shape=shape, + dtype=dtype, + shared_name=shared_name, + debug_name=name, + name=name, + container=container) + if initial_value is None: + initial_value = handle + if graph_mode: + full_handle_data = _combine_handle_data(handle, initial_value) + _set_handle_shapes_and_types(handle, full_handle_data, graph_mode) + return handle + else: + handle_data = handle_data_util.create_handle_data(shape, dtype) + if initial_value is not None and initial_value.dtype == dtypes.variant: + extra_handle_data = get_eager_safe_handle_data(initial_value) + if extra_handle_data is not None and extra_handle_data.is_set: + if (not handle_data.is_set or len(handle_data.shape_and_type) != 1): + raise RuntimeError( + "Expected VarHandleOp to return a length==1 shape_and_type, " + f"but saw: '{handle_data}'") + handle_data.shape_and_type.extend(extra_handle_data.shape_and_type) + + _set_handle_shapes_and_types(handle, handle_data, graph_mode) + return handle + + +def eager_safe_variable_handle(initial_value, shape, shared_name, name, + graph_mode): + """Creates a variable handle with information to do shape inference. + + The dtype is read from `initial_value` and stored in the returned + resource tensor's handle data. + + If `initial_value.dtype == tf.variant`, we additionally extract the handle + data (if any) from `initial_value` and append it to the `handle_data`. + In this case, the returned tensor's handle data is in the form + + ``` + is_set: true + shape_and_type { + shape { + // initial_value.shape + } + dtype: DT_VARIANT + } + shape_and_type { + // handle_data(initial_value).shape_and_type[0] + } + shape_and_type { + // handle_data(initial_value).shape_and_type[1] + } + ... + ``` + + Ops that read from this tensor, such as `ReadVariableOp` and + `AssignVariableOp`, know that `handle_data(handle).shape_and_type[1:]` + correspond to the handle data of the variant(s) stored in the Variable. + + Args: + initial_value: A `Tensor`. + shape: The shape of the handle data. Can be `TensorShape(None)` (i.e. + unknown shape). + shared_name: A string. + name: A string. + graph_mode: A python bool. + + Returns: + The handle, a `Tensor` of type `resource`. + """ + dtype = initial_value.dtype.base_dtype + return _variable_handle_from_shape_and_dtype(shape, dtype, shared_name, name, + graph_mode, initial_value) + + +@contextlib.contextmanager +def _handle_graph(handle): + # Note: might have an eager tensor but not be executing eagerly when building + # functions. + if (context.executing_eagerly() or isinstance(handle, ops.EagerTensor) or + ops.has_default_graph()): + yield + else: + with handle.graph.as_default(): + yield + + +class EagerResourceDeleter: + """An object which cleans up a resource handle. + + An alternative to defining a __del__ method on an object. The intended use is + that ResourceVariables or other objects with resource handles will maintain a + single reference to this object. When the parent object is collected, this + object will be too. Even if the parent object is part of a reference cycle, + the cycle will be collectable. + """ + + __slots__ = ["_handle", "_handle_device", "_context"] + + def __init__(self, handle, handle_device): + if not isinstance(handle, tensor_module.Tensor): + raise ValueError( + (f"Passed handle={handle} to EagerResourceDeleter. Was expecting " + f"the handle to be a `tf.Tensor`.")) + self._handle = handle + self._handle_device = handle_device + # This is held since the __del__ function runs an op, and if the context() + # is collected before this object, there will be a segfault when running the + # op. + self._context = context.context() + + def __del__(self): + # Resources follow object-identity when executing eagerly, so it is safe to + # delete the resource we have a handle to. + try: + # A packed EagerTensor doesn't own any resource. + if isinstance(self._handle, ops.EagerTensor) and self._handle.is_packed: + return + # This resource was created in eager mode. However, this destructor may be + # running in graph mode (especially during unit tests). To clean up + # successfully, we switch back into eager mode temporarily. + with context.eager_mode(): + with ops.device(self._handle_device): + gen_resource_variable_ops.destroy_resource_op( + self._handle, ignore_lookup_error=True) + except TypeError: + # Suppress some exceptions, mainly for the case when we're running on + # module deletion. Things that can go wrong include the context module + # already being unloaded, self._handle._handle_data no longer being + # valid, and so on. Printing warnings in these cases is silly + # (exceptions raised from __del__ are printed as warnings to stderr). + pass # 'NoneType' object is not callable when the handle has been + # partially unloaded. + except AttributeError: + pass # 'NoneType' object has no attribute 'eager_mode' when context has + # been unloaded. Will catch other module unloads as well. + + +def shape_safe_assign_variable_handle(handle, shape, value, name=None): + """Helper that checks shape compatibility and assigns variable.""" + with _handle_graph(handle): + value_tensor = ops.convert_to_tensor(value) + shape.assert_is_compatible_with(value_tensor.shape) + return gen_resource_variable_ops.assign_variable_op( + handle, value_tensor, name=name) + + +def _maybe_set_handle_data(dtype, handle, tensor): + if dtype == dtypes.variant: + # For DT_VARIANT types, the handle's shape_and_type[1:] stores the + # variant's handle data. Extract it. + handle_data = get_eager_safe_handle_data(handle) + if handle_data.is_set and len(handle_data.shape_and_type) > 1: + tensor._handle_data = ( # pylint: disable=protected-access + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData( + is_set=True, shape_and_type=handle_data.shape_and_type[1:])) + + +def variable_accessed(variable): + """Records that `variable` was accessed for the tape and FuncGraph.""" + if hasattr(ops.get_default_graph(), "watch_variable"): + ops.get_default_graph().watch_variable(variable) + if variable.trainable: + tape.variable_accessed(variable) + + +def default_variable_creator_v2(next_creator=None, **kwargs): + """Default variable creator.""" + assert next_creator is None + initial_value = kwargs.get("initial_value", None) + trainable = kwargs.get("trainable", None) + validate_shape = kwargs.get("validate_shape", True) + caching_device = kwargs.get("caching_device", None) + name = kwargs.get("name", None) + variable_def = kwargs.get("variable_def", None) + dtype = kwargs.get("dtype", None) + import_scope = kwargs.get("import_scope", None) + constraint = kwargs.get("constraint", None) + distribute_strategy = kwargs.get("distribute_strategy", None) + synchronization = kwargs.get("synchronization", None) + aggregation = kwargs.get("aggregation", None) + shape = kwargs.get("shape", None) + experimental_enable_variable_lifting = kwargs.get( + "experimental_enable_variable_lifting", None) + + return ResourceVariable( + initial_value=initial_value, + trainable=trainable, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + dtype=dtype, + constraint=constraint, + variable_def=variable_def, + import_scope=import_scope, + distribute_strategy=distribute_strategy, + synchronization=synchronization, + aggregation=aggregation, + shape=shape, + experimental_enable_variable_lifting=experimental_enable_variable_lifting, + ) + + +variables.default_variable_creator_v2 = default_variable_creator_v2 + + +class BaseResourceVariable(variables.Variable, core.Tensor): + """A python variable from an existing handle.""" + + # TODO(wangpeng): Deprecate `constraint` when callers no long pass it in. + def __init__( # pylint: disable=super-init-not-called + self, + trainable=None, + shape=None, + dtype=None, + handle=None, + constraint=None, + synchronization=None, + aggregation=None, + distribute_strategy=None, + name=None, + unique_id=None, + handle_name=None, + graph_element=None, + initial_value=None, + initializer_op=None, + is_initialized_op=None, + cached_value=None, + save_slice_info=None, + caching_device=None, + in_graph_mode=None, + validate_shape=True, + **unused_kwargs): + """Creates a variable from a handle. + + Args: + trainable: If `True`, GradientTapes automatically watch uses of this + Variable. + shape: The variable's shape. This shape can be set to tf.TensorShape(None) + in order to assign values of different shapes to this variable. + Otherwise (i.e. if the shape is fully determined), it will trigger run + time checks to ensure that each assignment is of the same shape. + dtype: The variable's dtype. + handle: The variable's handle + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + distribute_strategy: The distribution strategy this variable was created + under. + name: The name for this variable. + unique_id: Internal. Unique ID for this variable's handle. + handle_name: The name for the variable's handle. + graph_element: Optional, required only in session.run-mode. Pre-created + tensor which reads this variable's value. + initial_value: Optional. Variable's initial value. + initializer_op: Operation which assigns the variable's initial value. + is_initialized_op: Pre-created operation to check whether this variable is + initialized. + cached_value: Pre-created operation to read this variable in a specific + device. + save_slice_info: Metadata for variable partitioning. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + in_graph_mode: whether we are executing in TF1 graph mode. If None, will + detect within the function. This is to avoid repeated init_scope() + conetxt entrances which can add up. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + """ + if in_graph_mode is None: + with ops.init_scope(): + self._in_graph_mode = not context.executing_eagerly() + else: + self._in_graph_mode = in_graph_mode + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name)) + self._trainable = trainable + self._synchronization = synchronization + self._aggregation = aggregation + self._save_slice_info = save_slice_info + self._initial_value = initial_value + self._initializer_op = initializer_op + self._is_initialized_op = is_initialized_op + self._graph_element = graph_element + self._caching_device = caching_device + self._cached_value = cached_value + self._distribute_strategy = distribute_strategy + # Store the graph key so optimizers know how to only retrieve variables from + # this graph. Guaranteed to be the same as the eager graph_key. + self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access + self._shape = tensor_shape.as_shape(shape) + self._dtype = dtypes.as_dtype(dtype) + self._handle = handle + self._unique_id = unique_id + if handle_name is None: + self._handle_name = "Variable:0" + else: + self._handle_name = handle_name + ":0" + self._constraint = constraint + self._cached_shape_as_list = None + self._validate_shape = validate_shape + + def __repr__(self): + if context.executing_eagerly() and not self._in_graph_mode: + # If we cannot read the value for any reason (e.g. variable uninitialized + # during tf.function tracing), still produce a __repr__. Note that for + # async eager, errors due to uninitialized variables will raise in + # ops.value_text when the handle is resolved, so we need to keep that + # under the try...except if we want to suppress them. + try: + with ops.device(self.device): + value_text = ops.value_text(self.read_value(), is_repr=True) + except: # pylint: disable=bare-except + value_text = "numpy=" + + return "" % ( + self.name, self.get_shape(), self.dtype.name, value_text) + else: + return "" % ( + self.name, self.get_shape(), self.dtype.name) + + def __tf_tracing_type__(self, signature_context): + alias_id = signature_context.alias_global_id(self._handle._id) # pylint:disable=protected-access + # TODO(xjun): Create variable placeholders directly from VariableSpec + # without using original values. + signature_context.add_placeholder(alias_id, self) + return VariableSpec(shape=self.shape, + dtype=self.dtype, + trainable=self.trainable, + alias_id=alias_id) + + @contextlib.contextmanager + def _assign_dependencies(self): + """Makes assignments depend on the cached value, if any. + + This prevents undefined behavior with reads not ordered wrt writes. + + Yields: + None. + """ + if self._cached_value is not None: + with ops.control_dependencies([self._cached_value]): + yield + else: + yield + + def __array__(self, dtype=None): + """Allows direct conversion to a numpy array. + + >>> np.array(tf.Variable([1.0])) + array([1.], dtype=float32) + + Returns: + The variable value as a numpy array. + """ + # You can't return `self.numpy()` here because for scalars + # that raises: + # ValueError: object __array__ method not producing an array + # Even `self.read_value().__array__()` and `self.read_value()._numpy()` give + # the same error. The `EagerTensor` class must be doing something behind the + # scenes to make `np.array(tf.constant(1))` work. + return np.asarray(self.numpy(), dtype=dtype) + + def __nonzero__(self): + return self.__bool__() + + def __bool__(self): + return bool(self.read_value()) + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + if not context.executing_eagerly(): + raise NotImplementedError( + "__deepcopy__() is only available when eager execution is enabled.") + copied_variable = ResourceVariable( + initial_value=self.read_value(), + trainable=self._trainable, + constraint=self._constraint, + dtype=self._dtype, + name=self._shared_name, + distribute_strategy=self._distribute_strategy, + synchronization=self.synchronization, + aggregation=self.aggregation) + memo[self._unique_id] = copied_variable + return copied_variable + + @property + def dtype(self): + """The dtype of this variable.""" + return self._dtype + + @property + def device(self): + """The device this variable is on.""" + return self.handle.device + + @property + def graph(self): + """The `Graph` of this variable.""" + return self.handle.graph + + @property + def name(self): + """The name of the handle for this variable.""" + return self._handle_name + + @property + def shape(self): + """The shape of this variable.""" + return self._shape + + def set_shape(self, shape): + self._shape = self._shape.merge_with(shape) + + def _shape_as_list(self): + if self.shape.ndims is None: + return None + return [dim.value for dim in self.shape.dims] + + def _shape_tuple(self): + shape = self._shape_as_list() + if shape is None: + return None + return tuple(shape) + + @property + def create(self): + """The op responsible for initializing this variable.""" + if not self._in_graph_mode: + raise RuntimeError("This operation is not supported " + "when eager execution is enabled.") + return self._initializer_op + + @property + def handle(self): + """The handle by which this variable can be accessed.""" + return self._handle + + def value(self): + """A cached operation which reads the value of this variable.""" + if self._cached_value is not None: + return self._cached_value + with ops.colocate_with(None, ignore_existing=True): + return self._read_variable_op() + + def _as_graph_element(self): + """Conversion function for Graph.as_graph_element().""" + return self._graph_element + + @property + def initializer(self): + """The op responsible for initializing this variable.""" + return self._initializer_op + + @property + def initial_value(self): + """Returns the Tensor used as the initial value for the variable.""" + if context.executing_eagerly(): + raise RuntimeError("This property is not supported " + "when eager execution is enabled.") + return self._initial_value + + @property + def constraint(self): + """Returns the constraint function associated with this variable. + + Returns: + The constraint function that was passed to the variable constructor. + Can be `None` if no constraint was passed. + """ + return self._constraint + + @property + def op(self) -> ops.Operation: + """The op for this variable.""" + return self.handle.op + + @property + def trainable(self): + return self._trainable + + @property + def synchronization(self): + return self._synchronization + + @property + def aggregation(self): + return self._aggregation + + def eval(self, session=None): + """Evaluates and returns the value of this variable.""" + if context.executing_eagerly(): + raise RuntimeError("This operation is not supported " + "when eager execution is enabled.") + return self._graph_element.eval(session=session) + + def numpy(self): + if context.executing_eagerly(): + return self.read_value().numpy() + raise NotImplementedError( + "numpy() is only available when eager execution is enabled.") + + @deprecated(None, "Prefer Dataset.range instead.") + def count_up_to(self, limit): + """Increments this variable until it reaches `limit`. + + When that Op is run it tries to increment the variable by `1`. If + incrementing the variable would bring it above `limit` then the Op raises + the exception `OutOfRangeError`. + + If no error is raised, the Op outputs the value of the variable before + the increment. + + This is essentially a shortcut for `count_up_to(self, limit)`. + + Args: + limit: value at which incrementing the variable raises an error. + + Returns: + A `Tensor` that will hold the variable value before the increment. If no + other Op modifies this variable, the values produced will all be + distinct. + """ + return gen_state_ops.resource_count_up_to( + self.handle, limit=limit, T=self.dtype) + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable`.""" + if self not in object_map: + # If not populated, initialize the cpu copy first. + op_device = pydev.DeviceSpec.from_string(self.device).replace( + device_type="CPU", device_index=0).to_string() + with ops.device(op_device): + # Use `op_device` to prevent cross-device communication for variables + # like `ShardedVariable` + new_var = UninitializedVariable( + trainable=self.trainable, + shape=self.shape, + dtype=self.dtype, + name=self._shared_name) # pylint: disable=protected-access + object_map[self] = new_var + + # Then copy value of self to the copy. + destination_var = object_map[self] + with ops.device(destination_var.device): + # Use `op_device` to prevent cross-device communication for variables + # like `ShardedVariable` + destination_var.assign(self.read_value()) + + def _export_to_saved_model_graph(self, object_map=None, tensor_map=None, + options=None, **kwargs): + """For implementing `Trackable`.""" + new_variable = None + if options.experimental_variable_policy._save_variable_devices(): # pylint:disable=protected-access + with ops.device(self.device): + new_variable = copy_to_graph_uninitialized(self) + else: + new_variable = copy_to_graph_uninitialized(self) + object_map[self] = new_variable + tensor_map[self.handle] = new_variable.handle + return [self.handle] + + def _serialize_to_tensors(self): + """Implements Trackable._serialize_to_tensors.""" + + def _read_variable_closure(): + v = self + with ops.device(v.device): + if context.executing_eagerly() and not v.is_initialized(): + # A SaveSpec tensor value of `None` indicates that the variable is + # uninitialized. + return None + # Read the variable without making a copy to limit memory usage. + x = v.read_value_no_copy() + # To allow variables placed on non-CPU devices to be checkpointed, + # we copy them to CPU on the same machine first. + with ops.device("/device:CPU:0"): + return array_ops.identity(x) + + return { + trackable.VARIABLE_VALUE_KEY: + tensor_callable.Callable( + _read_variable_closure, dtype=self.dtype, device=self.device) + } + + def _restore_from_tensors(self, restored_tensors): + """Implements Trackable._restore_from_tensors.""" + with ops.device(self.device): + restored_tensor = array_ops.identity( + restored_tensors[trackable.VARIABLE_VALUE_KEY]) + try: + assigned_variable = shape_safe_assign_variable_handle( + self.handle, self.shape, restored_tensor) + except ValueError as e: + raise ValueError( + f"Received incompatible tensor with shape {restored_tensor.shape} " + f"when attempting to restore variable with shape {self.shape} " + f"and name {self.name}.") from e + return assigned_variable + + def _read_variable_op(self, no_copy=False): + """Reads the value of the variable. + + If the variable is in copy-on-read mode and `no_copy` is True, the variable + is converted to copy-on-write mode before it is read. + + Args: + no_copy: Whether to prevent a copy of the variable. + + Returns: + The value of the variable. + """ + variable_accessed(self) + + def read_and_set_handle(no_copy): + if no_copy and forward_compat.forward_compatible(2022, 5, 3): + gen_resource_variable_ops.disable_copy_on_read(self.handle) + result = gen_resource_variable_ops.read_variable_op( + self.handle, self._dtype) + _maybe_set_handle_data(self._dtype, self.handle, result) + return result + + if getattr(self, "_caching_device", None) is not None: + with ops.colocate_with(None, ignore_existing=True): + with ops.device(self._caching_device): + result = read_and_set_handle(no_copy) + else: + result = read_and_set_handle(no_copy) + + if not context.executing_eagerly(): + # Note that if a control flow context is active the input of the read op + # might not actually be the handle. This line bypasses it. + record.record_operation( + "ReadVariableOp", [result], [self.handle], + backward_function=lambda x: [x], + forward_function=lambda x: [x]) + return result + + def read_value(self): + """Constructs an op which reads the value of this variable. + + Should be used when there are multiple reads, or when it is desirable to + read the value only after some condition is true. + + Returns: + The value of the variable. + """ + with ops.name_scope("Read"): + value = self._read_variable_op() + # Return an identity so it can get placed on whatever device the context + # specifies instead of the device where the variable is. + return array_ops.identity(value) + + def read_value_no_copy(self): + """Constructs an op which reads the value of this variable without copy. + + The variable is read without making a copy even when it has been sparsely + accessed. Variables in copy-on-read mode will be converted to copy-on-write + mode. + + Returns: + The value of the variable. + """ + with ops.name_scope("Read"): + value = self._read_variable_op(no_copy=True) + # Return an identity so it can get placed on whatever device the context + # specifies instead of the device where the variable is. + return array_ops.identity(value) + + def sparse_read(self, indices, name=None): + """Reads the value of this variable sparsely, using `gather`.""" + with ops.name_scope("Gather" if name is None else name) as name: + variable_accessed(self) + value = gen_resource_variable_ops.resource_gather( + self.handle, indices, dtype=self._dtype, name=name) + + if self._dtype == dtypes.variant: + # For DT_VARIANT types, the handle's shape_and_type[1:] stores the + # variant's handle data. Extract it. + handle_data = get_eager_safe_handle_data(self.handle) + if handle_data.is_set and len(handle_data.shape_and_type) > 1: + value._handle_data = ( # pylint: disable=protected-access + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData( + is_set=True, shape_and_type=handle_data.shape_and_type[1:])) + return array_ops.identity(value) + + return value + + def gather_nd(self, indices, name=None): + """Reads the value of this variable sparsely, using `gather_nd`.""" + with ops.name_scope("GatherNd" if name is None else name) as name: + if self.trainable: + variable_accessed(self) + value = gen_resource_variable_ops.resource_gather_nd( + self.handle, indices, dtype=self._dtype, name=name) + + return array_ops.identity(value) + + def to_proto(self, export_scope=None): + """Converts a `ResourceVariable` to a `VariableDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Raises: + RuntimeError: If run in EAGER mode. + + Returns: + A `VariableDef` protocol buffer, or `None` if the `Variable` is not + in the specified name scope. + """ + if context.executing_eagerly(): + raise RuntimeError("This operation is not supported " + "when eager execution is enabled.") + if export_scope is None or self.handle.name.startswith(export_scope): + var_def = variable_pb2.VariableDef() + var_def.variable_name = ops.strip_name_scope(self.handle.name, + export_scope) + if self._initial_value is not None: + # This is inside an if-statement for backwards compatibility, since + # self._initial_value might be None for variables constructed from old + # protos. + var_def.initial_value_name = ops.strip_name_scope( + self._initial_value.name, export_scope) + var_def.initializer_name = ops.strip_name_scope(self.initializer.name, + export_scope) + if self._cached_value is not None: + var_def.snapshot_name = ops.strip_name_scope(self._cached_value.name, + export_scope) + else: + # Store the graph_element here + var_def.snapshot_name = ops.strip_name_scope(self._graph_element.name, + export_scope) + var_def.is_resource = True + var_def.trainable = self.trainable + var_def.synchronization = self.synchronization.value + var_def.aggregation = self.aggregation.value + if self._save_slice_info: + var_def.save_slice_info_def.MergeFrom( + self._save_slice_info.to_proto(export_scope=export_scope)) + return var_def + else: + return None + + @staticmethod + def from_proto(variable_def, import_scope=None): + if context.executing_eagerly(): + raise RuntimeError("This operation is not supported " + "when eager execution is enabled.") + return ResourceVariable( + variable_def=variable_def, import_scope=import_scope) + + __array_priority__ = 100 + + def is_initialized(self, name=None): + """Checks whether a resource variable has been initialized. + + Outputs boolean scalar indicating whether the tensor has been initialized. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + return gen_resource_variable_ops.var_is_initialized_op(self.handle, name) + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + """Subtracts a value from this variable. + + Args: + delta: A `Tensor`. The value to subtract from this variable. + use_locking: If `True`, use locking during the operation. + name: The name to use for the operation. + read_value: A `bool`. Whether to read and return the new value of the + variable or not. + + Returns: + If `read_value` is `True`, this method will return the new value of the + variable after the assignment has completed. Otherwise, when in graph mode + it will return the `Operation` that does the assignment, and when in eager + mode it will return `None`. + """ + # TODO(apassos): this here and below is not atomic. Consider making it + # atomic if there's a way to do so without a performance cost for those who + # don't need it. + with _handle_graph(self.handle), self._assign_dependencies(): + assign_sub_op = gen_resource_variable_ops.assign_sub_variable_op( + self.handle, + ops.convert_to_tensor(delta, dtype=self.dtype), + name=name) + if read_value: + return self._lazy_read(assign_sub_op) + return assign_sub_op + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + """Adds a value to this variable. + + Args: + delta: A `Tensor`. The value to add to this variable. + use_locking: If `True`, use locking during the operation. + name: The name to use for the operation. + read_value: A `bool`. Whether to read and return the new value of the + variable or not. + + Returns: + If `read_value` is `True`, this method will return the new value of the + variable after the assignment has completed. Otherwise, when in graph mode + it will return the `Operation` that does the assignment, and when in eager + mode it will return `None`. + """ + with _handle_graph(self.handle), self._assign_dependencies(): + assign_add_op = gen_resource_variable_ops.assign_add_variable_op( + self.handle, + ops.convert_to_tensor(delta, dtype=self.dtype), + name=name) + if read_value: + return self._lazy_read(assign_add_op) + return assign_add_op + + def _lazy_read(self, op): + variable_accessed(self) + return _UnreadVariable( + handle=self.handle, + dtype=self.dtype, + shape=self._shape, + in_graph_mode=self._in_graph_mode, + parent_op=op, + unique_id=self._unique_id) + + def assign(self, value, use_locking=None, name=None, read_value=True): + """Assigns a new value to this variable. + + Args: + value: A `Tensor`. The new value for this variable. + use_locking: If `True`, use locking during the assignment. + name: The name to use for the assignment. + read_value: A `bool`. Whether to read and return the new value of the + variable or not. + + Returns: + If `read_value` is `True`, this method will return the new value of the + variable after the assignment has completed. Otherwise, when in graph mode + it will return the `Operation` that does the assignment, and when in eager + mode it will return `None`. + """ + # Note: not depending on the cached value here since this can be used to + # initialize the variable. + with _handle_graph(self.handle): + value_tensor = ops.convert_to_tensor(value, dtype=self.dtype) + if not self._shape.is_compatible_with(value_tensor.shape): + if self.name is None: + tensor_name = "" + else: + tensor_name = " " + str(self.name) + raise ValueError( + (f"Cannot assign value to variable '{tensor_name}': Shape mismatch." + f"The variable shape {self._shape}, and the " + f"assigned value shape {value_tensor.shape} are incompatible.")) + kwargs = {} + if forward_compat.forward_compatible(2022, 3, 23): + # If the shape is fully defined, we do a runtime check with the shape of + # value. + validate_shape = self._validate_shape and self._shape.is_fully_defined() + kwargs["validate_shape"] = validate_shape + assign_op = gen_resource_variable_ops.assign_variable_op( + self.handle, value_tensor, name=name, **kwargs) + if read_value: + return self._lazy_read(assign_op) + return assign_op + + def __reduce__(self): + # The implementation mirrors that of __deepcopy__. + return functools.partial( + ResourceVariable, + initial_value=self.numpy(), + trainable=self.trainable, + name=self._shared_name, + dtype=self.dtype, + constraint=self.constraint, + distribute_strategy=self._distribute_strategy), () + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + """Subtracts `tf.IndexedSlices` from this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be subtracted from this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_sub( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + """Adds `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be added to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_add( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the max of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of max with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_max( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the min of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of min with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_min( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + """Multiply this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to multiply this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_mul( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + """Divide this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to divide this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_div( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + gen_resource_variable_ops.resource_scatter_update( + self.handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, self.dtype), + name=name)) + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable batch-wise. + + Analogous to `batch_gather`. This assumes that this variable and the + sparse_delta IndexedSlices have a series of leading dimensions that are the + same for all of them, and the updates are performed on the last dimension of + indices. In other words, the dimensions should be the following: + + `num_prefix_dims = sparse_delta.indices.ndims - 1` + `batch_dim = num_prefix_dims + 1` + `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[ + batch_dim:]` + + where + + `sparse_delta.updates.shape[:num_prefix_dims]` + `== sparse_delta.indices.shape[:num_prefix_dims]` + `== var.shape[:num_prefix_dims]` + + And the operation performed can be expressed as: + + `var[i_1, ..., i_n, + sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[ + i_1, ..., i_n, j]` + + When sparse_delta.indices is a 1D tensor, this operation is equivalent to + `scatter_update`. + + To avoid this operation one can looping over the first `ndims` of the + variable and using `scatter_update` on the subtensors that result of slicing + the first dimension. This is a valid option for `ndims = 1`, but less + efficient than this implementation. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + if not isinstance(sparse_delta, indexed_slices.IndexedSlices): + raise TypeError(f"Argument `sparse_delta` must be a " + f"`tf.IndexedSlices`. Received arg: {sparse_delta}") + return self._lazy_read( + state_ops.batch_scatter_update( + self, + sparse_delta.indices, + sparse_delta.values, + use_locking=use_locking, + name=name)) + + def scatter_nd_sub(self, indices, updates, name=None): + """Applies sparse subtraction to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + op = ref.scatter_nd_sub(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(op) + ``` + + The resulting update to ref would look like this: + + [1, -9, 3, -6, -6, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + return self._lazy_read( + gen_state_ops.resource_scatter_nd_sub( + self.handle, + indices, + ops.convert_to_tensor(updates, self.dtype), + name=name)) + + def scatter_nd_add(self, indices, updates, name=None): + """Applies sparse addition to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + add = ref.scatter_nd_add(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(add) + ``` + + The resulting update to ref would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + return self._lazy_read( + gen_state_ops.resource_scatter_nd_add( + self.handle, + indices, + ops.convert_to_tensor(updates, self.dtype), + name=name)) + + def scatter_nd_update(self, indices, updates, name=None): + """Applies sparse assignment to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + op = ref.scatter_nd_update(indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(op) + ``` + + The resulting update to ref would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + return self._lazy_read( + gen_state_ops.resource_scatter_nd_update( + self.handle, + indices, + ops.convert_to_tensor(updates, self.dtype), + name=name)) + + def scatter_nd_max(self, indices, updates, name=None): + """Updates this variable with the max of `tf.IndexedSlices` and itself. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + return self._lazy_read( + gen_state_ops.resource_scatter_nd_max( + self.handle, + indices, + ops.convert_to_tensor(updates, self.dtype), + name=name)) + + def scatter_nd_min(self, indices, updates, name=None): + """Updates this variable with the min of `tf.IndexedSlices` and itself. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + return self._lazy_read( + gen_state_ops.resource_scatter_nd_min( + self.handle, + indices, + ops.convert_to_tensor(updates, self.dtype), + name=name)) + + def _write_object_proto(self, proto, options): + """Writes additional information of the variable into the SavedObject proto. + + Subclasses of ResourceVariables could choose to override this method to + customize extra information to provide when saving a SavedModel. + + Ideally, this should contain the logic in + write_object_proto_for_resource_variable but `DistributedValue` is an + outlier at the momemnt. Once `DistributedValue` becomes a proper + ResourceVariable, we should remove the helper method below. + + Args: + proto: `SavedObject` proto to update. + options: A `SaveOption` instance that configures save behavior. + """ + write_object_proto_for_resource_variable(self, proto, options) + + def _strided_slice_assign(self, begin, end, strides, value, name, begin_mask, + end_mask, ellipsis_mask, new_axis_mask, + shrink_axis_mask): + with _handle_graph(self.handle), self._assign_dependencies(): + return self._lazy_read( + gen_array_ops.resource_strided_slice_assign( + ref=self.handle, + begin=begin, + end=end, + strides=strides, + value=ops.convert_to_tensor(value, dtype=self.dtype), + name=name, + begin_mask=begin_mask, + end_mask=end_mask, + ellipsis_mask=ellipsis_mask, + new_axis_mask=new_axis_mask, + shrink_axis_mask=shrink_axis_mask)) + + def __complex__(self): + return complex(self.value().numpy()) + + def __int__(self): + return int(self.value().numpy()) + + def __long__(self): + return long(self.value().numpy()) + + def __float__(self): + return float(self.value().numpy()) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + del name + if dtype is not None and not dtype.is_compatible_with(self.dtype): + raise ValueError( + f"Incompatible type conversion requested to type {dtype.name} for " + f"`tf.Variable of type {self.dtype.name}. (Variable: {self})") + if as_ref: + return self.read_value().op.inputs[0] + else: + return self.value() + + def __iadd__(self, unused_other): + raise RuntimeError("`variable += value` with `tf.Variable`s is not " + "supported. Use `variable.assign_add(value)` to modify " + "the variable, or `out = variable + value` if you " + "need to get a new output Tensor.") + + def __isub__(self, unused_other): + raise RuntimeError("`variable -= value` with `tf.Variable`s is not " + "supported. Use `variable.assign_sub(value)` to modify " + "the variable, or `out = variable * value` if you " + "need to get a new output Tensor.") + + def __imul__(self, unused_other): + raise RuntimeError("`var *= value` with `tf.Variable`s is not " + "supported. Use `var.assign(var * value)` to modify " + "the variable, or `out = var * value` if you " + "need to get a new output Tensor.") + + def __idiv__(self, unused_other): + raise RuntimeError("`var /= value` with `tf.Variable`s is not " + "supported. Use `var.assign(var / value)` to modify " + "the variable, or `out = var / value` if you " + "need to get a new output Tensor.") + + def __itruediv__(self, unused_other): + raise RuntimeError("`var /= value` with `tf.Variable`s is not " + "supported. Use `var.assign(var / value)` to modify " + "the variable, or `out = var / value` if you " + "need to get a new output Tensor.") + + def __irealdiv__(self, unused_other): + raise RuntimeError("`var /= value` with `tf.Variable`s is not " + "supported. Use `var.assign(var / value)` to modify " + "the variable, or `out = var / value` if you " + "need to get a new output Tensor.") + + def __ipow__(self, unused_other): + raise RuntimeError("`var **= value` with `tf.Variable`s is not " + "supported. Use `var.assign(var ** value)` to modify " + "the variable, or `out = var ** value` if you " + "need to get a new output Tensor.") + + +class ResourceVariableGradient( + composite_tensor_gradient.CompositeTensorGradient): + """CompositeTensorGradient protocol for ResourceVariable.""" + + # TODO(b/246997907): update this method to return value.handle. + def get_gradient_components(self, value): + """Returns the components of `value` that should be included in gradients. + + For a ResourceVariable, its gradient component is its handle tensor. + For now, we return the ResourceVariable because the gradient infrastructure + has special logics to handle ResourceVariables. We should remove those + special logics and return the handle tensor. + + Args: + value: A `ResourceVariable`. + + Returns: + `value` itself. + """ + return value + + def replace_gradient_components(self, value, component_grads): + """Replaces the gradient components in `value` with `component_grads`. + + The gradient of a ResourceVariable is either None or a Tensor. So we don't + need `value`'s TypeSpec or non-gradient components in this method. + + Args: + value: A `ResourceVariable` with its gradient components compatible with + `component_grads`. + component_grads: A `Tensor` or None as the gradient result. + + Returns: + The `component_grads`, which is either a `Tensor` or None. + """ + return component_grads + + +class ResourceVariable(BaseResourceVariable, composite_tensor.CompositeTensor): + """Variable based on resource handles. + + See the [Variables How To](https://tensorflow.org/guide/variables) + for a high level overview. + + A `ResourceVariable` allows you to maintain state across subsequent calls to + session.run. + + The `ResourceVariable` constructor requires an initial value for the variable, + which can be a `Tensor` of any type and shape. The initial value defines the + type and shape of the variable. After construction, the type and shape of + the variable are fixed. The value can be changed using one of the assign + methods. + + Just like any `Tensor`, variables created with + `tf.Variable(use_resource=True)` can be used as inputs for other Ops in the + graph. Additionally, all the operators overloaded for the `Tensor` class are + carried over to variables, so you can also add nodes to the graph by just + doing arithmetic on variables. + + Unlike ref-based variable, a ResourceVariable has well-defined semantics. Each + usage of a ResourceVariable in a TensorFlow graph adds a read_value operation + to the graph. The Tensors returned by a read_value operation are guaranteed to + see all modifications to the value of the variable which happen in any + operation on which the read_value depends on (either directly, indirectly, or + via a control dependency) and guaranteed to not see any modification to the + value of the variable from operations that depend on the read_value operation. + Updates from operations that have no dependency relationship to the read_value + operation might or might not be visible to read_value. + + For example, if there is more than one assignment to a ResourceVariable in + a single session.run call there is a well-defined value for each operation + which uses the variable's value if the assignments and the read are connected + by edges in the graph. Consider the following example, in which two writes + can cause tf.Variable and tf.ResourceVariable to behave differently: + + ```python + a = tf.Variable(1.0, use_resource=True) + a.initializer.run() + + assign = a.assign(2.0) + with tf.control_dependencies([assign]): + b = a.read_value() + with tf.control_dependencies([b]): + other_assign = a.assign(3.0) + with tf.control_dependencies([other_assign]): + # Will print 2.0 because the value was read before other_assign ran. If + # `a` was a tf.Variable instead, 2.0 or 3.0 could be printed. + tf.compat.v1.Print(b, [b]).eval() + ``` + """ + + def __init__( + self, # pylint: disable=super-init-not-called + initial_value=None, + trainable=None, + collections=None, + validate_shape=True, # pylint: disable=unused-argument + caching_device=None, + name=None, + dtype=None, + variable_def=None, + import_scope=None, + constraint=None, + distribute_strategy=None, + synchronization=None, + aggregation=None, + shape=None, + handle=None, + experimental_enable_variable_lifting=None, + ): + """Creates a variable. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. Can also be a callable with + no argument that returns the initial value when called. (Note that + initializer functions from init_ops.py must first be bound to a shape + before being used here.) + trainable: If `True`, the default, also adds the variable to the graph + collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as + the default list of variables to use by the `Optimizer` classes. + Defaults to `True`, unless `synchronization` is set to `ON_READ`, in + which case it defaults to `False`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + dtype: If set, initial_value will be converted to the given type. If None, + either the datatype will be kept (if initial_value is a Tensor) or + float32 will be used (if it is a Python object convertible to a Tensor). + variable_def: `VariableDef` protocol buffer. If not None, recreates the + `ResourceVariable` object with its contents. `variable_def` and other + arguments (except for import_scope) are mutually exclusive. + import_scope: Optional `string`. Name scope to add to the + ResourceVariable. Only used when `variable_def` is provided. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + distribute_strategy: The tf.distribute.Strategy this variable is being + created inside of. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + handle: (optional) The handle of a `tf.Variable`. If provided, only + `trainable`, `shape`, `dtype`, and `handle` will be used to construct + this `tf.Variable`. + experimental_enable_variable_lifting: Whether to lift the variable out if + it's in a `tf.function`. Default is `True`. When this argument + is `True`, variable creation will follow the behavior and + restrictions described + [here](https://www.tensorflow.org/guide/function#creating_tfvariables). + If this argument is `False`, that description doesn't apply, + and you can freely create and use the variable in the + `tf.function`, as if it's a "mutable `tf.Tensor`". You can't + return the variable though. + + Raises: + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + + @compatibility(eager) + When Eager Execution is enabled, the default for the `collections` argument + is `None`, which signifies that this `Variable` will not be added to any + collections. + @end_compatibility + """ + if variable_def: + if initial_value is not None: + raise ValueError(f"The variable_def and initial_value args to " + f"`tf.Variable` are mutually exclusive, but got both: " + f"variable_def={variable_def},\n" + f"initial_value={initial_value}") + if context.executing_eagerly(): + raise ValueError(f"Creating a `tf.Variable` with a `variable_def` arg " + f"is not supported when eager execution is enabled. " + f"Got: variable_def={variable_def}") + self._init_from_proto( + variable_def, + import_scope=import_scope, + validate_shape=validate_shape) + elif handle is not None: + self._init_from_handle(trainable=trainable, + shape=shape, + dtype=dtype, + handle=handle) + else: + self._init_from_args( + initial_value=initial_value, + trainable=trainable, + collections=collections, + caching_device=caching_device, + name=name, + dtype=dtype, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + shape=shape, + distribute_strategy=distribute_strategy, + validate_shape=validate_shape, + experimental_enable_variable_lifting=experimental_enable_variable_lifting, + ) + + # CompositeTensor method + @property + def _type_spec(self): + return VariableSpec.from_value(self) + + # CompositeTensor method + def _shape_invariant_to_type_spec(self, shape): + return VariableSpec(shape, self.dtype, self.trainable) + + # CompositeTensorGradient protocol + __composite_gradient__ = ResourceVariableGradient() + + def _init_from_args( + self, + initial_value=None, + trainable=None, + collections=None, + caching_device=None, + name=None, + dtype=None, + constraint=None, + synchronization=None, + aggregation=None, + distribute_strategy=None, + shape=None, + validate_shape=True, + experimental_enable_variable_lifting=None, + ): + """Creates a variable. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. + (Note that initializer functions from init_ops.py must first be bound to + a shape before being used here.) + trainable: If `True`, the default, also adds the variable to the graph + collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as + the default list of variables to use by the `Optimizer` classes. + Defaults to `True`, unless `synchronization` is set to `ON_READ`, in + which case it defaults to `False`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + dtype: If set, initial_value will be converted to the given type. If None, + either the datatype will be kept (if initial_value is a Tensor) or + float32 will be used (if it is a Python object convertible to a Tensor). + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + distribute_strategy: DistributionStrategy under which this variable was + created. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + experimental_enable_variable_lifting: Whether to lift the variable out if + it's in a `tf.function`. Default is `True`. When this argument + is `True`, variable creation will follow the behavior and + restrictions described + [here](https://www.tensorflow.org/guide/function#creating_tfvariables). + If this argument is `False`, that description doesn't apply, + and you can freely create and use the variable in the + `tf.function`, as if it's a "mutable `tf.Tensor`". You can't + return the variable though. + + Raises: + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + + @compatibility(eager) + When Eager Execution is enabled, variables are never added to collections. + It is not implicitly added to the `GLOBAL_VARIABLES` or + `TRAINABLE_VARIABLES` collections, and the `collections` argument is + ignored. + @end_compatibility + """ + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name)) + if experimental_enable_variable_lifting is None: + experimental_enable_variable_lifting = True + if initial_value is None: + raise ValueError("The `initial_value` arg to `tf.Variable` must " + "be specified except when you are not providing a " + "`variable_def`. You provided neither.") + init_from_fn = callable(initial_value) + + if isinstance(initial_value, tensor_module.Tensor) and hasattr( + initial_value, "graph") and initial_value.graph.building_function: + raise ValueError(f"Argument `initial_value` ({initial_value}) could not " + "be lifted out of a `tf.function`. " + f"(Tried to create variable with name='{name}'). " + "To avoid this error, when constructing `tf.Variable`s " + "inside of `tf.function` you can create the " + "`initial_value` tensor in a " + "`tf.init_scope` or pass a callable `initial_value` " + "(e.g., `tf.Variable(lambda : " + "tf.truncated_normal([10, 40]))`). " + "Please file a feature request if this " + "restriction inconveniences you.") + + if collections is None: + collections = [ops.GraphKeys.GLOBAL_VARIABLES] + if not isinstance(collections, (list, tuple, set)): + raise ValueError( + f"collections argument to Variable constructor must be a list, " + f"tuple, or set. Got {collections} of type {type(collections)}") + if constraint is not None and not callable(constraint): + raise ValueError(f"Argument `constraint` must be None or a callable. " + f"a callable. Got a {type(constraint)}: {constraint}") + + if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections: + collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES] + with ops.init_scope(): + self._in_graph_mode = not context.executing_eagerly() + if experimental_enable_variable_lifting: + maybe_init_scope = ops.init_scope + else: + maybe_init_scope = contextlib.nullcontext + with maybe_init_scope(): + with ops.name_scope( + name, + "Variable", [] if init_from_fn else [initial_value], + skip_on_eager=False) as name: + # pylint: disable=protected-access + handle_name = ops.name_from_scope_name(name) + if self._in_graph_mode: + shared_name = handle_name + unique_id = shared_name + else: + # When in eager mode, use a uid for the shared_name, to prevent + # accidental sharing. + unique_id = "%s_%d" % (handle_name, ops.uid()) + shared_name = None # Never shared + # Use attr_scope and device(None) to simulate the behavior of + # colocate_with when the variable we want to colocate with doesn't + # yet exist. + device_context_manager = ( + ops.device if self._in_graph_mode else ops.NullContextmanager) + attr = attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue( + s=[compat.as_bytes("loc:@%s" % handle_name)])) + with ops.get_default_graph()._attr_scope({"_class": attr}): + with ops.name_scope("Initializer"), device_context_manager(None): + if init_from_fn: + initial_value = initial_value() + if isinstance(initial_value, trackable.CheckpointInitialValue): + self._maybe_initialize_trackable() + self._update_uid = initial_value.checkpoint_position.restore_uid + initial_value = initial_value.wrapped_value + initial_value = ops.convert_to_tensor( + initial_value, name="initial_value", dtype=dtype) + if shape is not None: + if not initial_value.shape.is_compatible_with(shape): + raise ValueError( + f"In this `tf.Variable` creation, the initial value's shape " + f"({initial_value.shape}) is not compatible with " + f"the explicitly supplied `shape` argument ({shape}).") + else: + shape = initial_value.shape + handle = eager_safe_variable_handle( + initial_value=initial_value, + shape=shape, + shared_name=shared_name, + name=name, + graph_mode=self._in_graph_mode) + handle._parent_trackable = weakref.ref(self) + handle._name = handle_name + ":0" + handle._unique_id = unique_id + # pylint: disable=protected-access + if (self._in_graph_mode and initial_value is not None and + initial_value.op._get_control_flow_context() is not None): + raise ValueError( + f"The `initial_value` passed to `tf.Variable` {name} is from " + f"inside a control-flow construct, such as a loop or " + f"conditional. When creating a " + f"`tf.Variable` inside a loop or conditional, use a lambda as " + f"the `initial_value`. Got: initial_value=({initial_value})") + # pylint: enable=protected-access + dtype = initial_value.dtype.base_dtype + + if self._in_graph_mode: + with ops.name_scope("IsInitialized"): + is_initialized_op = ( + gen_resource_variable_ops.var_is_initialized_op(handle)) + if initial_value is not None: + # pylint: disable=g-backslash-continuation + with ops.name_scope("Assign") as n, \ + ops.colocate_with(None, ignore_existing=True), \ + ops.device(handle.device): + # pylint: disable=protected-access + initializer_op = ( + gen_resource_variable_ops.assign_variable_op( + handle, + variables._try_guard_against_uninitialized_dependencies( + name, initial_value), + name=n)) + # pylint: enable=protected-access + # pylint: enable=g-backslash-continuation + with ops.name_scope("Read"): + # Manually assign reads to the handle's device to avoid log + # messages. + with ops.device(handle.device): + value = gen_resource_variable_ops.read_variable_op(handle, dtype) + _maybe_set_handle_data(dtype, handle, value) + graph_element = value + if caching_device is not None: + # Variables may be created in a tf.device() or ops.colocate_with() + # context. At the same time, users would expect caching device to + # be independent of this context, and/or would not expect the + # current device context to be merged with the caching device + # spec. Therefore we reset the colocation stack before creating + # the cached value. Note that resetting the colocation stack will + # also reset the device stack. + with ops.colocate_with(None, ignore_existing=True): + with ops.device(caching_device): + cached_value = array_ops.identity(value) + else: + cached_value = None + else: + gen_resource_variable_ops.assign_variable_op(handle, initial_value) + is_initialized_op = None + initializer_op = None + graph_element = None + if caching_device: + with ops.device(caching_device): + cached_value = gen_resource_variable_ops.read_variable_op( + handle, dtype) + _maybe_set_handle_data(dtype, handle, cached_value) + else: + cached_value = None + + if cached_value is not None: + # Store the variable object so that the original variable can be + # accessed to generate functions that are compatible with SavedModel. + cached_value._cached_variable = weakref.ref(self) # pylint: disable=protected-access + + if self._in_graph_mode: + # Eager variables are only added to collections if they are part of an + # eager variable store (otherwise in an interactive session they would + # hog memory and cause OOM). This is done in ops/variable_scope.py. + ops.add_to_collections(collections, self) + elif ops.GraphKeys.GLOBAL_STEP in collections: + ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, self) + initial_value = initial_value if self._in_graph_mode else None + super(ResourceVariable, self).__init__( + trainable=trainable, + shape=shape, + dtype=dtype, + handle=handle, + synchronization=synchronization, + constraint=constraint, + aggregation=aggregation, + distribute_strategy=distribute_strategy, + name=name, + unique_id=unique_id, + handle_name=handle_name, + graph_element=graph_element, + initial_value=initial_value, + initializer_op=initializer_op, + is_initialized_op=is_initialized_op, + cached_value=cached_value, + caching_device=caching_device, + validate_shape=validate_shape, + ) + + def _init_from_proto(self, + variable_def, + import_scope=None, + validate_shape=True): + """Initializes from `VariableDef` proto.""" + # Note that init_from_proto is currently not supported in Eager mode. + assert not context.executing_eagerly() + self._in_graph_mode = True + assert isinstance(variable_def, variable_pb2.VariableDef) + if not variable_def.is_resource: + raise ValueError(f"The `variable_def` you passed to `tf.Variable` is " + f"Trying to restore a TF 1.x Reference Variable " + f"as a TF 2.x ResourceVariable. This is unsupported. " + f"Got variable_def={variable_def}") + + # Create from variable_def. + g = ops.get_default_graph() + self._handle = g.as_graph_element( + ops.prepend_name_scope( + variable_def.variable_name, import_scope=import_scope), + allow_operation=False) + self._shape = tensor_shape.TensorShape(self._handle.op.get_attr("shape")) + self._handle_name = self._handle.name + self._unique_id = self._handle_name + self._initializer_op = g.as_graph_element( + ops.prepend_name_scope( + variable_def.initializer_name, import_scope=import_scope)) + # Check whether initial_value_name exists for backwards compatibility. + if (hasattr(variable_def, "initial_value_name") and + variable_def.initial_value_name): + self._initial_value = g.as_graph_element( + ops.prepend_name_scope( + variable_def.initial_value_name, import_scope=import_scope)) + else: + self._initial_value = None + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + variable_def.synchronization, variable_def.aggregation, + variable_def.trainable, variable_def.variable_name)) + self._synchronization = synchronization + self._aggregation = aggregation + self._trainable = trainable + if variable_def.snapshot_name: + snapshot = g.as_graph_element( + ops.prepend_name_scope( + variable_def.snapshot_name, import_scope=import_scope)) + if snapshot.op.type != "ReadVariableOp": + self._cached_value = snapshot + else: + self._cached_value = None + while snapshot.op.type != "ReadVariableOp": + snapshot = snapshot.op.inputs[0] + self._graph_element = snapshot + else: + self._cached_value = None + # Legacy case for protos without the snapshot name; assume it's the + # following. + self._graph_element = g.get_tensor_by_name(self._handle.op.name + + "/Read/ReadVariableOp:0") + if variable_def.HasField("save_slice_info_def"): + self._save_slice_info = variables.Variable.SaveSliceInfo( + save_slice_info_def=variable_def.save_slice_info_def, + import_scope=import_scope) + else: + self._save_slice_info = None + self._caching_device = None + self._dtype = dtypes.as_dtype(self._handle.op.get_attr("dtype")) + self._constraint = None + self._validate_shape = validate_shape + + def _init_from_handle(self, + trainable=None, + shape=None, + dtype=None, + handle=None): + handle_data = get_eager_safe_handle_data(handle) + if not handle_data.is_set: + # The handle may not have the handle shape and dtype if it was created + # using tf.placeholder. + handle_data = handle_data_util.create_handle_data(shape, dtype) + handle_data_util.set_handle_data(handle, handle_data) + # pylint: disable=protected-access + if hasattr(handle, "_name") and isinstance(handle._name, str): + handle_name = handle._name.rstrip(":0") + else: + handle_name = None + # pylint: enable=protected-access + unique_id = getattr(handle, "_unique_id", None) + super().__init__( + trainable=trainable, shape=shape, dtype=dtype, handle=handle, + unique_id=unique_id, handle_name=handle_name) + + +class UninitializedVariable(BaseResourceVariable): + """A variable with no initializer.""" + + def __init__( # pylint: disable=super-init-not-called + self, + trainable=None, + caching_device=None, + name=None, + shape=None, + dtype=None, + constraint=None, + synchronization=None, + aggregation=None, + extra_handle_data=None, + distribute_strategy=None, + **unused_kwargs): + """Creates the variable handle. + + Args: + trainable: If `True`, GradientTapes automatically watch uses of this + Variable. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + shape: The variable's shape. + dtype: The variable's dtype. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + extra_handle_data: Optional, another resource handle or Tensor with handle + data to merge with `shape` and `dtype`. + distribute_strategy: The tf.distribute.Strategy this variable is being + created inside of. + """ + with ops.init_scope(): + # Here we are detecting eagerness within an init_scope, so this will only + # be true when we are running in TF1 graph mode. + self._in_graph_mode = not context.executing_eagerly() + with ops.name_scope(name, "Variable", skip_on_eager=False) as name: + handle_name = ops.name_from_scope_name(name) + if self._in_graph_mode: + shared_name = handle_name + unique_id = shared_name + else: + unique_id = "%s_%d" % (handle_name, ops.uid()) + shared_name = None # Never shared + handle = _variable_handle_from_shape_and_dtype( + shape=shape, + dtype=dtype, + shared_name=shared_name, + name=name, + graph_mode=self._in_graph_mode, + initial_value=extra_handle_data) + handle._parent_trackable = weakref.ref(self) + handle._name = handle_name + ":0" + handle._unique_id = unique_id + + if self._in_graph_mode: + # We only need to add the read_variable_op in TF1. + with ops.name_scope("Read"): + # Manually assign reads to the handle's device to avoid log + # messages. + with ops.device(handle.device): + value = gen_resource_variable_ops.read_variable_op(handle, dtype) + _maybe_set_handle_data(dtype, handle, value) + graph_element = value + ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, self) + # Do *not* add to TRAINABLE_VARIABLES here, even if self._trainable, + # because retraining or frozen use of imported SavedModels is + # controlled at higher levels of model building. + else: + graph_element = None + super(UninitializedVariable, self).__init__( + distribute_strategy=distribute_strategy, + shape=shape, + dtype=dtype, + unique_id=unique_id, + handle_name=handle_name, + constraint=constraint, + handle=handle, + graph_element=graph_element, + trainable=trainable, + synchronization=synchronization, + aggregation=aggregation, + in_graph_mode=self._in_graph_mode, **unused_kwargs) + + +_pywrap_utils.RegisterType("ResourceVariable", ResourceVariable) +math_ops._resource_variable_type = ResourceVariable # pylint: disable=protected-access + + +def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +tensor_conversion_registry.register_tensor_conversion_function( + BaseResourceVariable, _dense_var_to_tensor) + + +class _UnreadVariable(BaseResourceVariable): + """Represents a future for a read of a variable. + + Pretends to be the tensor if anyone looks. + """ + + def __init__(self, handle, dtype, shape, in_graph_mode, parent_op, unique_id): + if isinstance(handle, ops.EagerTensor): + handle_name = "" + else: + handle_name = handle.name + # Only create a graph_element if we're in session.run-land as only + # session.run requires a preexisting tensor to evaluate. Otherwise we can + # avoid accidentally reading the variable. + if context.executing_eagerly() or ops.inside_function(): + graph_element = None + else: + with ops.control_dependencies([parent_op]): + graph_element = gen_resource_variable_ops.read_variable_op( + handle, dtype) + _maybe_set_handle_data(dtype, handle, graph_element) + super(_UnreadVariable, self).__init__( + handle=handle, + shape=shape, + handle_name=handle_name, + unique_id=unique_id, + dtype=dtype, + graph_element=graph_element) + self._parent_op = parent_op + + @property + def name(self): + if self._in_graph_mode: + return self._parent_op.name + else: + return "UnreadVariable" + + def value(self): + return self._read_variable_op() + + def read_value(self): + return self._read_variable_op() + + def _read_variable_op(self): + with ops.control_dependencies([self._parent_op]): + result = gen_resource_variable_ops.read_variable_op( + self._handle, self._dtype) + _maybe_set_handle_data(self._dtype, self._handle, result) + return result + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).assign_sub(delta, use_locking, name, + read_value) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).assign_add(delta, use_locking, name, + read_value) + + def assign(self, value, use_locking=None, name=None, read_value=True): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).assign(value, use_locking, name, + read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_sub(sparse_delta, use_locking, + name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_add(sparse_delta, use_locking, + name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_max(sparse_delta, use_locking, + name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_min(sparse_delta, use_locking, + name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_mul(sparse_delta, use_locking, + name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_div(sparse_delta, use_locking, + name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, + self).scatter_update(sparse_delta, use_locking, name) + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, + self).batch_scatter_update(sparse_delta, use_locking, name) + + def scatter_nd_sub(self, indices, updates, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_nd_sub(indices, updates, name) + + def scatter_nd_add(self, indices, updates, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_nd_add(indices, updates, name) + + def scatter_nd_update(self, indices, updates, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, + self).scatter_nd_update(indices, updates, name) + + def scatter_nd_max(self, indices, updates, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_nd_max(indices, updates, name) + + def scatter_nd_min(self, indices, updates, name=None): + with ops.control_dependencies([self._parent_op]): + return super(_UnreadVariable, self).scatter_nd_min(indices, updates, name) + + @property + def op(self) -> ops.Operation: + """The op for this variable.""" + return self._parent_op + + +@ops.RegisterGradient("ReadVariableOp") +def _ReadGrad(_, grad): + """Gradient for read op.""" + return grad + + +def variable_shape(handle, out_type=dtypes.int32): + handle_data = get_eager_safe_handle_data(handle) + if handle_data is None or not handle_data.is_set: + return gen_resource_variable_ops.variable_shape(handle, out_type=out_type) + shape_proto = handle_data.shape_and_type[0].shape + if shape_proto.unknown_rank or any(x.size == -1 for x in shape_proto.dim): + return gen_resource_variable_ops.variable_shape(handle, out_type=out_type) + return constant_op.constant([x.size for x in shape_proto.dim], dtype=out_type) + + +@ops.RegisterGradient("ResourceGather") +def _GatherGrad(op, grad): + """Gradient for gather op.""" + # Build appropriately shaped IndexedSlices + handle = op.inputs[0] + indices = op.inputs[1] + params_shape = variable_shape(handle) + size = array_ops.expand_dims(array_ops.size(indices), 0) + values_shape = array_ops.concat([size, params_shape[1:]], 0) + values = array_ops.reshape(grad, values_shape) + indices = array_ops.reshape(indices, size) + return (indexed_slices.IndexedSlices(values, indices, params_shape), None) + + +@tf_export("__internal__.ops.is_resource_variable", v1=[]) +def is_resource_variable(var): + """"Returns True if `var` is to be considered a ResourceVariable.""" + return isinstance(var, BaseResourceVariable) or hasattr( + var, "_should_act_as_resource_variable") + + +def copy_to_graph_uninitialized(var): + """Copies an existing variable to a new graph, with no initializer.""" + # Like ResourceVariable.__deepcopy__, but does not set an initializer on the + # new variable. + # pylint: disable=protected-access + new_variable = UninitializedVariable( + trainable=var.trainable, + constraint=var._constraint, + shape=var.shape, + dtype=var.dtype, + name=var._shared_name, + synchronization=var.synchronization, + aggregation=var.aggregation, + extra_handle_data=var.handle) + new_variable._maybe_initialize_trackable() + # pylint: enable=protected-access + return new_variable + + +ops.NotDifferentiable("Assert") +ops.NotDifferentiable("VarIsInitializedOp") +ops.NotDifferentiable("VariableShape") + + +# TODO(b/246356867): This is the draft implementation. Currently VariableSpec is +# the only class using them. Move them to a separate file when necessary. +class StructurePattern: + pass + + +class PLeaf(StructurePattern): + """Represents a singleton leaf StructurePattern.""" + + def __new__(cls): + if not hasattr(cls, "instance"): + cls.instance = super().__new__(cls) + return cls.instance + + +class PList(StructurePattern): + """Represents a list of StructurePatterns.""" + + def __init__(self, *components): + self.components = list(components) + + def __eq__(self, other): + return isinstance(other, PList) and self.components == other.components + + +class VariableSpec(tensor_module.DenseSpec): + """Describes a tf.Variable. + + A `VariableSpec` provides metadata describing the `tf.Variable` objects + accepted or returned by TensorFlow 2.x APIs. + """ + + __slots__ = ["trainable", "alias_id"] + + value_type = property(lambda self: ResourceVariable) + + def __init__(self, shape, dtype=dtypes.float32, trainable=True, + alias_id=None): + super(VariableSpec, self).__init__(shape, dtype=dtype) + self.trainable = trainable + self.alias_id = alias_id + + def is_compatible_with(self, spec_or_value): + """Returns True if `spec_or_value` is compatible with this `VariableSpec`. + + `spec_or_value` is considered to be compatible with this `VariableSpec` if + + * `spec_or_value` is a `Variable` or `VariableSpec`, + * their shapes are compatible, + * their dtypes are the same, + * they are both trainable or not trainable. + * they share the same alias_id if `spec_or_value` is a `VariableSpec`. + + Example: + + >>> v = tf.Variable([1., 2., 3.]) + >>> spec = VariableSpec([None]) + >>> spec.is_compatible_with(v) + True + >>> v = tf.Variable(1) + >>> spec.is_compatible_with(v) + False + + Args: + spec_or_value: A VariableSpec or Variable to compare against. + + Returns: + True if `spec_or_value` is compatible with this `VariableSpec`. + """ + if not isinstance(spec_or_value, (type(self), self.value_type)): + return False + compatible = (self.shape.is_compatible_with(spec_or_value.shape) and + self.dtype == spec_or_value.dtype and + self.trainable == spec_or_value.trainable) + if isinstance(spec_or_value, type(self)): + # alias_id must be the same to be compatible. + return compatible and self.alias_id == spec_or_value.alias_id + return compatible + + @classmethod + def from_value(cls, value): + """Creates a `VariableSpec` from the given `Variable`. + + `value`'s shape, dtype, and trainable attributes will be used to create + the new `VariableSpec`. + + Example: + + >>> v = tf.Variable([1., 2., 3.]) + >>> VariableSpec.from_value(v) + VariableSpec(shape=(3,), dtype=tf.float32, trainable=True, alias_id=None) + + Args: + value: A Variable. + + Returns: + A `VariableSpec` created from `value`. + """ + return cls(value.shape, dtype=value.dtype, trainable=value.trainable) + + def _to_components(self, value): + return [value.handle] + + def _from_components(self, components): + if not isinstance(components, (list, tuple)): + raise TypeError(f"Components of a ResourceVariable must be a list or " + f"tuple, got f{components} instead.") + if len(components) != 1: + raise ValueError(f"Components of a ResourceVariable must only contain " + f"its resource handle, got f{components} instead.") + handle = components[0] + if not isinstance( + handle, tensor_module.Tensor) or handle.dtype != dtypes.resource: + raise ValueError(f"The handle of a ResourceVariable must be a resource " + f"tensor, got {handle} instead.") + return ResourceVariable(trainable=self.trainable, + shape=self.shape, + dtype=self.dtype, + handle=handle) + + @property + def _component_specs(self): + return [ + tensor_module.TensorSpec( + [], + dtypes.DType( + dtypes.resource._type_enum, # pylint: disable=protected-access + dtypes.HandleData(alias_id=self.alias_id), + ), + ) + ] + + def _serialize(self): + return self.shape, self.dtype, self.trainable, self.alias_id + + # TraceType method + def is_subtype_of(self, other): + if type(self) is not type(other): + return False + + # Remove this once we add alias_id to all CompositeTensors with + # ResourceVariable components. + if self.alias_id is None and other.alias_id is None: + return super().is_subtype_of(other) + + if self.alias_id is None or other.alias_id is None: + raise NotImplementedError(f"VariableSpec.is_subtype_of doesn't support " + f"alias_id=None, got self: {self} and other: " + f"{other}.") + + return super().is_subtype_of(other) + + # TraceType method + def most_specific_common_supertype(self, others): + if any(type(self) is not type(other) for other in others): + return None + + # It is a special case for tf.nest, which often takes CompositeTensors and + # converts to TypeSpecs internally, such as tf.nest.assert_same_structure. + if (self.alias_id is None and + all(other.alias_id is None for other in others)): + return super().most_specific_common_supertype(others) + + if self.alias_id is None or any(other.alias_id is None for other in others): + raise NotImplementedError(f"VariableSpec.most_specific_common_supertype " + f"doesn't support alias_id=None, got self: " + f"{self} and others: {others}.") + + return super().most_specific_common_supertype(others) + + # TraceType method + def placeholder_value(self, placeholder_context): + if placeholder_context.unnest_only: + return self + + name = self.name or placeholder_context.naming_scope + context_graph = placeholder_context.context_graph + if placeholder_context.has_placeholder(self.alias_id): + # Get reference to the existing variable if alias_id already + # exists in the PlaceholderContext + variable = placeholder_context.get_placeholder(self.alias_id) + else: + spec = tensor_module.TensorSpec([], dtypes.resource) + spec_context = trace_type.InternalPlaceholderContext( + context_graph.outer_graph) + spec_context.update_naming_scope(name) + placeholder = spec.placeholder_value(spec_context) + variable = self._from_components([placeholder]) + # (b/262771247) ShardedVariable break without this and VariableSpecs + # without alias_id are not TraceTypes. + if self.alias_id is not None: + placeholder_context.add_placeholder(self.alias_id, variable) + # Capture the Variable's placeholder within the default graph of + # the current thread. + placeholder = context_graph.capture(variable.handle, name=name) + placeholder.op._set_attr( # pylint: disable=protected-access + "_user_specified_name", + attr_value_pb2.AttrValue(s=compat.as_bytes(name))) + return variable + + def to_tensors(self, value): + assert isinstance(value, BaseResourceVariable) + variable_accessed(value) + return [value.handle] + + def cast(self, value, _): + assert isinstance(value, BaseResourceVariable) + return value + + def _get_structure(self): + # shape, dtype, trainable, and alias_id are all leaves. + return PList(PLeaf(), PLeaf(), PLeaf(), PLeaf()) + + def __repr__(self): + return (f"{type(self).__name__}(shape={self.shape}, dtype={self.dtype!r}, " + f"trainable={self.trainable!r}, alias_id={self.alias_id!r})") + + def __hash__(self): + return hash((self.shape, self.dtype, self.trainable, self.alias_id)) + + def __eq__(self, other): + return (type(self) is type(other) and self.shape == other.shape and + self.dtype == other.dtype and self.trainable == other.trainable and + self.alias_id == other.alias_id) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + VariableSpec, struct_pb2.TypeSpecProto.VARIABLE_SPEC + ) +) + + +_pywrap_utils.RegisterType("VariableSpec", VariableSpec) + + +def write_object_proto_for_resource_variable(resource_variable, + proto, + options, + enforce_naming=True): + """Writes additional information of the variable into the SavedObject proto. + + This allows users to define a `hook` to provide extra information of the + variable to the SavedObject. + + For example, DistributedVariable class would fill in components in the + distributed context. + + Args: + resource_variable: A `ResourceVariable` or `DistributedValue` that has the + information to be saved into the proto. + proto: `SavedObject` proto to update. + options: A `SaveOption` instance that configures save behavior. + enforce_naming: A bool determining whether to check that names end in the + expected string ':0' + """ + proto.variable.SetInParent() + if enforce_naming and not resource_variable.name.endswith(":0"): + raise ValueError(f"Cowardly refusing to save variable " + f"{resource_variable.name} because of " + f"unexpected suffix in the name (expected ':0')" + f"which won't be restored.") + proto.variable.name = tensor_module.get_op_name(resource_variable.name) + proto.variable.trainable = resource_variable.trainable + proto.variable.dtype = resource_variable.dtype.as_datatype_enum + proto.variable.synchronization = resource_variable.synchronization.value + proto.variable.aggregation = resource_variable.aggregation.value + proto.variable.shape.CopyFrom(resource_variable.shape.as_proto()) + if options.experimental_variable_policy._save_variable_devices( # pylint: disable=protected-access + ): + if hasattr(resource_variable, "device"): + proto.variable.device = resource_variable.device diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resources.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..b1afb75d51f9a0308f4b3feff6bc26a94ecbc67b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/resources.py @@ -0,0 +1,117 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + + +"""Utilities for using generic resources.""" +# pylint: disable=g-bad-name +import collections +import os + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import tf_should_use + + +_Resource = collections.namedtuple("_Resource", + ["handle", "create", "is_initialized"]) + + +def register_resource(handle, create_op, is_initialized_op, is_shared=True): + """Registers a resource into the appropriate collections. + + This makes the resource findable in either the shared or local resources + collection. + + Args: + handle: op which returns a handle for the resource. + create_op: op which initializes the resource. + is_initialized_op: op which returns a scalar boolean tensor of whether + the resource has been initialized. + is_shared: if True, the resource gets added to the shared resource + collection; otherwise it gets added to the local resource collection. + + """ + resource = _Resource(handle, create_op, is_initialized_op) + if is_shared: + ops.add_to_collection(ops.GraphKeys.RESOURCES, resource) + else: + ops.add_to_collection(ops.GraphKeys.LOCAL_RESOURCES, resource) + + +def shared_resources(): + """Returns resources visible to all tasks in the cluster.""" + return ops.get_collection(ops.GraphKeys.RESOURCES) + + +def local_resources(): + """Returns resources intended to be local to this session.""" + return ops.get_collection(ops.GraphKeys.LOCAL_RESOURCES) + + +def report_uninitialized_resources(resource_list=None, + name="report_uninitialized_resources"): + """Returns the names of all uninitialized resources in resource_list. + + If the returned tensor is empty then all resources have been initialized. + + Args: + resource_list: resources to check. If None, will use shared_resources() + + local_resources(). + name: name for the resource-checking op. + + Returns: + Tensor containing names of the handles of all resources which have not + yet been initialized. + + """ + if resource_list is None: + resource_list = shared_resources() + local_resources() + with ops.name_scope(name): + # Run all operations on CPU + local_device = os.environ.get( + "TF_DEVICE_FOR_UNINITIALIZED_VARIABLE_REPORTING", "/cpu:0") + with ops.device(local_device): + if not resource_list: + # Return an empty tensor so we only need to check for returned tensor + # size being 0 as an indication of model ready. + return array_ops.constant([], dtype=dtypes.string) + # Get a 1-D boolean tensor listing whether each resource is initialized. + variables_mask = math_ops.logical_not( + array_ops_stack.stack([r.is_initialized for r in resource_list])) + # Get a 1-D string tensor containing all the resource names. + variable_names_tensor = array_ops.constant( + [s.handle.name for s in resource_list]) + # Return a 1-D tensor containing all the names of uninitialized resources. + return array_ops.boolean_mask(variable_names_tensor, variables_mask) + + +@tf_should_use.should_use_result +def initialize_resources(resource_list, name="init"): + """Initializes the resources in the given list. + + Args: + resource_list: list of resources to initialize. + name: name of the initialization op. + + Returns: + op responsible for initializing all resources. + """ + if resource_list: + return control_flow_ops.group(*[r.create for r in resource_list], name=name) + return control_flow_ops.no_op(name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c26ff539387f2360b40e2a8f3e807e4fac63bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn.py @@ -0,0 +1,1684 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""RNN helpers for TensorFlow models.""" +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import control_flow_util_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import rnn_cell_impl +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import while_loop +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# pylint: disable=protected-access +_concat = rnn_cell_impl._concat +# pylint: enable=protected-access + + +def _transpose_batch_time(x): + """Transposes the batch and time dimensions of a Tensor. + + If the input tensor has rank < 2 it returns the original tensor. Retains as + much of the static shape information as possible. + + Args: + x: A Tensor. + + Returns: + x transposed along the first two dimensions. + """ + x_static_shape = x.get_shape() + if x_static_shape.rank is not None and x_static_shape.rank < 2: + return x + + x_rank = array_ops.rank(x) + x_t = array_ops.transpose( + x, array_ops.concat(([1, 0], math_ops.range(2, x_rank)), axis=0)) + x_t.set_shape( + tensor_shape.TensorShape( + [x_static_shape.dims[1].value, + x_static_shape.dims[0].value]).concatenate(x_static_shape[2:])) + return x_t + + +def _best_effort_input_batch_size(flat_input): + """Get static input batch size if available, with fallback to the dynamic one. + + Args: + flat_input: An iterable of time major input Tensors of shape `[max_time, + batch_size, ...]`. All inputs should have compatible batch sizes. + + Returns: + The batch size in Python integer if available, or a scalar Tensor otherwise. + + Raises: + ValueError: if there is any input with an invalid shape. + """ + for input_ in flat_input: + shape = input_.shape + if shape.rank is None: + continue + if shape.rank < 2: + raise ValueError("Input tensor should have rank >= 2. Received input=" + f"{input_} of rank {shape.rank}") + batch_size = shape.dims[1].value + if batch_size is not None: + return batch_size + # Fallback to the dynamic batch size of the first input. + return array_ops.shape(flat_input[0])[1] + + +def _infer_state_dtype(explicit_dtype, state): + """Infer the dtype of an RNN state. + + Args: + explicit_dtype: explicitly declared dtype or None. + state: RNN's hidden state. Must be a Tensor or a nested iterable containing + Tensors. + + Returns: + dtype: inferred dtype of hidden state. + + Raises: + ValueError: if `state` has heterogeneous dtypes or is empty. + """ + if explicit_dtype is not None: + return explicit_dtype + elif nest.is_nested(state): + inferred_dtypes = [element.dtype for element in nest.flatten(state)] + if not inferred_dtypes: + raise ValueError(f"Unable to infer dtype from argument state={state}.") + all_same = all(x == inferred_dtypes[0] for x in inferred_dtypes) + if not all_same: + raise ValueError( + f"Argument state={state} has tensors of different inferred dtypes. " + "Unable to infer a single representative dtype. Dtypes received: " + f"{inferred_dtypes}") + return inferred_dtypes[0] + else: + return state.dtype + + +def _maybe_tensor_shape_from_tensor(shape): + if isinstance(shape, tensor.Tensor): + return tensor_shape.as_shape(tensor_util.constant_value(shape)) + else: + return shape + + +def _should_cache(): + """Returns True if a default caching device should be set, otherwise False.""" + if context.executing_eagerly(): + return False + # Don't set a caching device when running in a loop, since it is possible that + # train steps could be wrapped in a tf.while_loop. In that scenario caching + # prevents forward computations in loop iterations from re-reading the + # updated weights. + graph = ops.get_default_graph() + ctxt = graph._get_control_flow_context() # pylint: disable=protected-access + in_v1_while_loop = ( + control_flow_util.GetContainingWhileContext(ctxt) is not None) + in_v2_while_loop = control_flow_util_v2.in_while_loop_defun(graph) + return not in_v1_while_loop and not in_v2_while_loop + + +# pylint: disable=unused-argument +def _rnn_step(time, + sequence_length, + min_sequence_length, + max_sequence_length, + zero_output, + state, + call_cell, + state_size, + skip_conditionals=False): + """Calculate one step of a dynamic RNN minibatch. + + Returns an (output, state) pair conditioned on `sequence_length`. + When skip_conditionals=False, the pseudocode is something like: + + if t >= max_sequence_length: + return (zero_output, state) + if t < min_sequence_length: + return call_cell() + + # Selectively output zeros or output, old state or new state depending + # on whether we've finished calculating each row. + new_output, new_state = call_cell() + final_output = np.vstack([ + zero_output if time >= sequence_length[r] else new_output_r + for r, new_output_r in enumerate(new_output) + ]) + final_state = np.vstack([ + state[r] if time >= sequence_length[r] else new_state_r + for r, new_state_r in enumerate(new_state) + ]) + return (final_output, final_state) + + Args: + time: int32 `Tensor` scalar. + sequence_length: int32 `Tensor` vector of size [batch_size]. + min_sequence_length: int32 `Tensor` scalar, min of sequence_length. + max_sequence_length: int32 `Tensor` scalar, max of sequence_length. + zero_output: `Tensor` vector of shape [output_size]. + state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`, + or a list/tuple of such tensors. + call_cell: lambda returning tuple of (new_output, new_state) where + new_output is a `Tensor` matrix of shape `[batch_size, output_size]`. + new_state is a `Tensor` matrix of shape `[batch_size, state_size]`. + state_size: The `cell.state_size` associated with the state. + skip_conditionals: Python bool, whether to skip using the conditional + calculations. This is useful for `dynamic_rnn`, where the input tensor + matches `max_sequence_length`, and using conditionals just slows + everything down. + + Returns: + A tuple of (`final_output`, `final_state`) as given by the pseudocode above: + final_output is a `Tensor` matrix of shape [batch_size, output_size] + final_state is either a single `Tensor` matrix, or a tuple of such + matrices (matching length and shapes of input `state`). + + Raises: + ValueError: If the cell returns a state tuple whose length does not match + that returned by `state_size`. + """ + + # Convert state to a list for ease of use + flat_state = nest.flatten(state) + flat_zero_output = nest.flatten(zero_output) + + # Vector describing which batch entries are finished. + copy_cond = time >= sequence_length + + def _copy_one_through(output, new_output): + # TensorArray and scalar get passed through. + if isinstance(output, tensor_array_ops.TensorArray): + return new_output + if output.shape.rank == 0: + return new_output + # Otherwise propagate the old or the new value. + with ops.colocate_with(new_output): + return array_ops.where(copy_cond, output, new_output) + + def _copy_some_through(flat_new_output, flat_new_state): + # Use broadcasting select to determine which values should get + # the previous state & zero output, and which values should get + # a calculated state & output. + flat_new_output = [ + _copy_one_through(zero_output, new_output) + for zero_output, new_output in zip(flat_zero_output, flat_new_output) + ] + flat_new_state = [ + _copy_one_through(state, new_state) + for state, new_state in zip(flat_state, flat_new_state) + ] + return flat_new_output + flat_new_state + + def _maybe_copy_some_through(): + """Run RNN step. Pass through either no or some past state.""" + new_output, new_state = call_cell() + + nest.assert_same_structure(zero_output, new_output) + nest.assert_same_structure(state, new_state) + + flat_new_state = nest.flatten(new_state) + flat_new_output = nest.flatten(new_output) + return cond.cond( + # if t < min_seq_len: calculate and return everything + time < min_sequence_length, + lambda: flat_new_output + flat_new_state, + # else copy some of it through + lambda: _copy_some_through(flat_new_output, flat_new_state)) + + # TODO(ebrevdo): skipping these conditionals may cause a slowdown, + # but benefits from removing cond() and its gradient. We should + # profile with and without this switch here. + if skip_conditionals: + # Instead of using conditionals, perform the selective copy at all time + # steps. This is faster when max_seq_len is equal to the number of unrolls + # (which is typical for dynamic_rnn). + new_output, new_state = call_cell() + nest.assert_same_structure(zero_output, new_output) + nest.assert_same_structure(state, new_state) + new_state = nest.flatten(new_state) + new_output = nest.flatten(new_output) + final_output_and_state = _copy_some_through(new_output, new_state) + else: + empty_update = lambda: flat_zero_output + flat_state + final_output_and_state = cond.cond( + # if t >= max_seq_len: copy all state through, output zeros + time >= max_sequence_length, + empty_update, + # otherwise calculation is required: copy some or all of it through + _maybe_copy_some_through) + + if len(final_output_and_state) != len(flat_zero_output) + len(flat_state): + raise ValueError("Internal error: state and output were not concatenated " + f"correctly. Received state length: {len(flat_state)}, " + f"output length: {len(flat_zero_output)}. Expected " + f"contatenated length: {len(final_output_and_state)}.") + final_output = final_output_and_state[:len(flat_zero_output)] + final_state = final_output_and_state[len(flat_zero_output):] + + for output, flat_output in zip(final_output, flat_zero_output): + output.set_shape(flat_output.get_shape()) + for substate, flat_substate in zip(final_state, flat_state): + if not isinstance(substate, tensor_array_ops.TensorArray): + substate.set_shape(flat_substate.get_shape()) + + final_output = nest.pack_sequence_as( + structure=zero_output, flat_sequence=final_output) + final_state = nest.pack_sequence_as( + structure=state, flat_sequence=final_state) + + return final_output, final_state + + +def _reverse_seq(input_seq, lengths): + """Reverse a list of Tensors up to specified lengths. + + Args: + input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features) + or nested tuples of tensors. + lengths: A `Tensor` of dimension batch_size, containing lengths for each + sequence in the batch. If "None" is specified, simply reverses the list. + + Returns: + time-reversed sequence + """ + if lengths is None: + return list(reversed(input_seq)) + + flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq) + + flat_results = [[] for _ in range(len(input_seq))] + for sequence in zip(*flat_input_seq): + input_shape = tensor_shape.unknown_shape(rank=sequence[0].get_shape().rank) + for input_ in sequence: + input_shape.assert_is_compatible_with(input_.get_shape()) + input_.set_shape(input_shape) + + # Join into (time, batch_size, depth) + s_joined = array_ops_stack.stack(sequence) + + # Reverse along dimension 0 + s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1) + # Split again into list + result = array_ops_stack.unstack(s_reversed) + for r, flat_result in zip(result, flat_results): + r.set_shape(input_shape) + flat_result.append(r) + + results = [ + nest.pack_sequence_as(structure=input_, flat_sequence=flat_result) + for input_, flat_result in zip(input_seq, flat_results) + ] + return results + + +@deprecation.deprecated(None, "Please use `keras.layers.Bidirectional(" + "keras.layers.RNN(cell))`, which is equivalent to " + "this API") +@tf_export(v1=["nn.bidirectional_dynamic_rnn"]) +@dispatch.add_dispatch_support +def bidirectional_dynamic_rnn(cell_fw, + cell_bw, + inputs, + sequence_length=None, + initial_state_fw=None, + initial_state_bw=None, + dtype=None, + parallel_iterations=None, + swap_memory=False, + time_major=False, + scope=None): + """Creates a dynamic version of bidirectional recurrent neural network. + + Takes input and builds independent forward and backward RNNs. The input_size + of forward and backward cell must match. The initial state for both directions + is zero by default (but can be set optionally) and no intermediate states are + ever returned -- the network is fully unrolled for the given (passed in) + length(s) of the sequence(s) or completely unrolled if length(s) is not + given. + + Args: + cell_fw: An instance of RNNCell, to be used for forward direction. + cell_bw: An instance of RNNCell, to be used for backward direction. + inputs: The RNN inputs. + If time_major == False (default), this must be a tensor of shape: + `[batch_size, max_time, ...]`, or a nested tuple of such elements. + If time_major == True, this must be a tensor of shape: `[max_time, + batch_size, ...]`, or a nested tuple of such elements. + sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, + containing the actual lengths for each of the sequences in the batch. If + not provided, all batch entries are assumed to be full sequences; and time + reversal is applied from time `0` to `max_time` for each sequence. + initial_state_fw: (optional) An initial state for the forward RNN. This must + be a tensor of appropriate type and shape `[batch_size, + cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a + tuple of tensors having shapes `[batch_size, s] for s in + cell_fw.state_size`. + initial_state_bw: (optional) Same as for `initial_state_fw`, but using the + corresponding properties of `cell_bw`. + dtype: (optional) The data type for the initial states and expected output. + Required if initial_states are not provided or RNN states have a + heterogeneous dtype. + parallel_iterations: (Default: 32). The number of iterations to run in + parallel. Those operations which do not have any temporal dependency and + can be run in parallel, will be. This parameter trades off time for + space. Values >> 1 use more memory but take less time, while smaller + values use less memory but computations take longer. + swap_memory: Transparently swap the tensors produced in forward inference + but needed for back prop from GPU to CPU. This allows training RNNs which + would typically not fit on a single GPU, with very minimal (or no) + performance penalty. + time_major: The shape format of the `inputs` and `outputs` Tensors. If true, + these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false, + these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using + `time_major = True` is a bit more efficient because it avoids transposes + at the beginning and end of the RNN calculation. However, most TensorFlow + data is batch-major, so by default this function accepts input and emits + output in batch-major form. + scope: VariableScope for the created subgraph; defaults to + "bidirectional_rnn" + + Returns: + A tuple (outputs, output_states) where: + outputs: A tuple (output_fw, output_bw) containing the forward and + the backward rnn output `Tensor`. + If time_major == False (default), + output_fw will be a `Tensor` shaped: + `[batch_size, max_time, cell_fw.output_size]` + and output_bw will be a `Tensor` shaped: + `[batch_size, max_time, cell_bw.output_size]`. + If time_major == True, + output_fw will be a `Tensor` shaped: + `[max_time, batch_size, cell_fw.output_size]` + and output_bw will be a `Tensor` shaped: + `[max_time, batch_size, cell_bw.output_size]`. + It returns a tuple instead of a single concatenated `Tensor`, unlike + in the `bidirectional_rnn`. If the concatenated one is preferred, + the forward and backward outputs can be concatenated as + `tf.concat(outputs, 2)`. + output_states: A tuple (output_state_fw, output_state_bw) containing + the forward and the backward final states of bidirectional rnn. + + Raises: + TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. + """ + rnn_cell_impl.assert_like_rnncell("cell_fw", cell_fw) + rnn_cell_impl.assert_like_rnncell("cell_bw", cell_bw) + + with vs.variable_scope(scope or "bidirectional_rnn"): + # Forward direction + with vs.variable_scope("fw") as fw_scope: + output_fw, output_state_fw = dynamic_rnn( + cell=cell_fw, + inputs=inputs, + sequence_length=sequence_length, + initial_state=initial_state_fw, + dtype=dtype, + parallel_iterations=parallel_iterations, + swap_memory=swap_memory, + time_major=time_major, + scope=fw_scope) + + # Backward direction + if not time_major: + time_axis = 1 + batch_axis = 0 + else: + time_axis = 0 + batch_axis = 1 + + def _reverse(input_, seq_lengths, seq_axis, batch_axis): + if seq_lengths is not None: + return array_ops.reverse_sequence( + input=input_, + seq_lengths=seq_lengths, + seq_axis=seq_axis, + batch_axis=batch_axis) + else: + return array_ops.reverse(input_, axis=[seq_axis]) + + with vs.variable_scope("bw") as bw_scope: + + def _map_reverse(inp): + return _reverse( + inp, + seq_lengths=sequence_length, + seq_axis=time_axis, + batch_axis=batch_axis) + + inputs_reverse = nest.map_structure(_map_reverse, inputs) + tmp, output_state_bw = dynamic_rnn( + cell=cell_bw, + inputs=inputs_reverse, + sequence_length=sequence_length, + initial_state=initial_state_bw, + dtype=dtype, + parallel_iterations=parallel_iterations, + swap_memory=swap_memory, + time_major=time_major, + scope=bw_scope) + + output_bw = _reverse( + tmp, + seq_lengths=sequence_length, + seq_axis=time_axis, + batch_axis=batch_axis) + + outputs = (output_fw, output_bw) + output_states = (output_state_fw, output_state_bw) + + return (outputs, output_states) + + +@deprecation.deprecated( + None, + "Please use `keras.layers.RNN(cell)`, which is equivalent to this API") +@tf_export(v1=["nn.dynamic_rnn"]) +@dispatch.add_dispatch_support +def dynamic_rnn(cell, + inputs, + sequence_length=None, + initial_state=None, + dtype=None, + parallel_iterations=None, + swap_memory=False, + time_major=False, + scope=None): + """Creates a recurrent neural network specified by RNNCell `cell`. + + Performs fully dynamic unrolling of `inputs`. + + Example: + + ```python + # create a BasicRNNCell + rnn_cell = tf.compat.v1.nn.rnn_cell.BasicRNNCell(hidden_size) + + # 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size] + + # defining initial state + initial_state = rnn_cell.zero_state(batch_size, dtype=tf.float32) + + # 'state' is a tensor of shape [batch_size, cell_state_size] + outputs, state = tf.compat.v1.nn.dynamic_rnn(rnn_cell, input_data, + initial_state=initial_state, + dtype=tf.float32) + ``` + + ```python + # create 2 LSTMCells + rnn_layers = [tf.compat.v1.nn.rnn_cell.LSTMCell(size) for size in [128, 256]] + + # create a RNN cell composed sequentially of a number of RNNCells + multi_rnn_cell = tf.compat.v1.nn.rnn_cell.MultiRNNCell(rnn_layers) + + # 'outputs' is a tensor of shape [batch_size, max_time, 256] + # 'state' is a N-tuple where N is the number of LSTMCells containing a + # tf.nn.rnn_cell.LSTMStateTuple for each cell + outputs, state = tf.compat.v1.nn.dynamic_rnn(cell=multi_rnn_cell, + inputs=data, + dtype=tf.float32) + ``` + + + Args: + cell: An instance of RNNCell. + inputs: The RNN inputs. + If `time_major == False` (default), this must be a `Tensor` of shape: + `[batch_size, max_time, ...]`, or a nested tuple of such elements. + If `time_major == True`, this must be a `Tensor` of shape: `[max_time, + batch_size, ...]`, or a nested tuple of such elements. This may also be + a (possibly nested) tuple of Tensors satisfying this property. The + first two dimensions must match across all the inputs, but otherwise the + ranks and other shape components may differ. In this case, input to + `cell` at each time-step will replicate the structure of these tuples, + except for the time dimension (from which the time is taken). The input + to `cell` at each time step will be a `Tensor` or (possibly nested) + tuple of Tensors each with dimensions `[batch_size, ...]`. + sequence_length: (optional) An int32/int64 vector sized `[batch_size]`. Used + to copy-through state and zero-out outputs when past a batch element's + sequence length. This parameter enables users to extract the last valid + state and properly padded outputs, so it is provided for correctness. + initial_state: (optional) An initial state for the RNN. If `cell.state_size` + is an integer, this must be a `Tensor` of appropriate type and shape + `[batch_size, cell.state_size]`. If `cell.state_size` is a tuple, this + should be a tuple of tensors having shapes `[batch_size, s] for s in + cell.state_size`. + dtype: (optional) The data type for the initial state and expected output. + Required if initial_state is not provided or RNN state has a heterogeneous + dtype. + parallel_iterations: (Default: 32). The number of iterations to run in + parallel. Those operations which do not have any temporal dependency and + can be run in parallel, will be. This parameter trades off time for + space. Values >> 1 use more memory but take less time, while smaller + values use less memory but computations take longer. + swap_memory: Transparently swap the tensors produced in forward inference + but needed for back prop from GPU to CPU. This allows training RNNs which + would typically not fit on a single GPU, with very minimal (or no) + performance penalty. + time_major: The shape format of the `inputs` and `outputs` Tensors. If true, + these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false, + these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using + `time_major = True` is a bit more efficient because it avoids transposes + at the beginning and end of the RNN calculation. However, most TensorFlow + data is batch-major, so by default this function accepts input and emits + output in batch-major form. + scope: VariableScope for the created subgraph; defaults to "rnn". + + Returns: + A pair (outputs, state) where: + + outputs: The RNN output `Tensor`. + + If time_major == False (default), this will be a `Tensor` shaped: + `[batch_size, max_time, cell.output_size]`. + + If time_major == True, this will be a `Tensor` shaped: + `[max_time, batch_size, cell.output_size]`. + + Note, if `cell.output_size` is a (possibly nested) tuple of integers + or `TensorShape` objects, then `outputs` will be a tuple having the + same structure as `cell.output_size`, containing Tensors having shapes + corresponding to the shape data in `cell.output_size`. + + state: The final state. If `cell.state_size` is an int, this + will be shaped `[batch_size, cell.state_size]`. If it is a + `TensorShape`, this will be shaped `[batch_size] + cell.state_size`. + If it is a (possibly nested) tuple of ints or `TensorShape`, this will + be a tuple having the corresponding shapes. If cells are `LSTMCells` + `state` will be a tuple containing a `LSTMStateTuple` for each cell. + + Raises: + TypeError: If `cell` is not an instance of RNNCell. + ValueError: If inputs is None or an empty list. + + @compatibility(TF2) + `tf.compat.v1.nn.dynamic_rnn` is not compatible with eager execution and + `tf.function`. Please use `tf.keras.layers.RNN` instead for TF2 migration. + Take LSTM as an example, you can instantiate a `tf.keras.layers.RNN` layer + with `tf.keras.layers.LSTMCell`, or directly via `tf.keras.layers.LSTM`. Once + the keras layer is created, you can get the output and states by calling + the layer with input and states. Please refer to [this + guide](https://www.tensorflow.org/guide/keras/rnn) for more details about + Keras RNN. You can also find more details about the difference and comparison + between Keras RNN and TF compat v1 rnn in [this + document](https://github.com/tensorflow/community/blob/master/rfcs/20180920-unify-rnn-interface.md) + + #### Structural Mapping to Native TF2 + + Before: + + ```python + # create 2 LSTMCells + rnn_layers = [tf.compat.v1.nn.rnn_cell.LSTMCell(size) for size in [128, 256]] + + # create a RNN cell composed sequentially of a number of RNNCells + multi_rnn_cell = tf.compat.v1.nn.rnn_cell.MultiRNNCell(rnn_layers) + + # 'outputs' is a tensor of shape [batch_size, max_time, 256] + # 'state' is a N-tuple where N is the number of LSTMCells containing a + # tf.nn.rnn_cell.LSTMStateTuple for each cell + outputs, state = tf.compat.v1.nn.dynamic_rnn(cell=multi_rnn_cell, + inputs=data, + dtype=tf.float32) + ``` + + After: + + ```python + # RNN layer can take a list of cells, which will then stack them together. + # By default, keras RNN will only return the last timestep output and will not + # return states. If you need whole time sequence output as well as the states, + # you can set `return_sequences` and `return_state` to True. + rnn_layer = tf.keras.layers.RNN([tf.keras.layers.LSTMCell(128), + tf.keras.layers.LSTMCell(256)], + return_sequences=True, + return_state=True) + outputs, output_states = rnn_layer(inputs, states) + ``` + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------------- | + | `cell` | `cell` | In the RNN layer constructor | + | `inputs` | `inputs` | In the RNN layer `__call__` | + | `sequence_length` | Not used | Adding masking layer before RNN : + : : : to achieve the same result. : + | `initial_state` | `initial_state` | In the RNN layer `__call__` | + | `dtype` | `dtype` | In the RNN layer constructor | + | `parallel_iterations` | Not supported | | + | `swap_memory` | Not supported | | + | `time_major` | `time_major` | In the RNN layer constructor | + | `scope` | Not supported | | + @end_compatibility + """ + rnn_cell_impl.assert_like_rnncell("cell", cell) + + with vs.variable_scope(scope or "rnn") as varscope: + # Create a new scope in which the caching device is either + # determined by the parent scope, or is set to place the cached + # Variable using the same placement as for the rest of the RNN. + if _should_cache(): + if varscope.caching_device is None: + varscope.set_caching_device(lambda op: op.device) + + # By default, time_major==False and inputs are batch-major: shaped + # [batch, time, depth] + # For internal calculations, we transpose to [time, batch, depth] + flat_input = nest.flatten(inputs) + + if not time_major: + # (B,T,D) => (T,B,D) + flat_input = [ops.convert_to_tensor(input_) for input_ in flat_input] + flat_input = tuple(_transpose_batch_time(input_) for input_ in flat_input) + + parallel_iterations = parallel_iterations or 32 + if sequence_length is not None: + sequence_length = math_ops.cast(sequence_length, dtypes.int32) + if sequence_length.get_shape().rank not in (None, 1): + raise ValueError( + f"Argument sequence_length must be a vector of length batch_size." + f" Received sequence_length={sequence_length} of shape: " + f"{sequence_length.get_shape()}") + sequence_length = array_ops.identity( # Just to find it in the graph. + sequence_length, + name="sequence_length") + + batch_size = _best_effort_input_batch_size(flat_input) + + if initial_state is not None: + state = initial_state + else: + if not dtype: + raise ValueError("If no initial_state is provided, argument `dtype` " + "must be specified") + if getattr(cell, "get_initial_state", None) is not None: + state = cell.get_initial_state( + inputs=None, batch_size=batch_size, dtype=dtype) + else: + state = cell.zero_state(batch_size, dtype) + + def _assert_has_shape(x, shape): + x_shape = array_ops.shape(x) + packed_shape = array_ops_stack.stack(shape) + return control_flow_assert.Assert( + math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)), [ + "Expected shape for Tensor %s is " % x.name, packed_shape, + " but saw shape: ", x_shape + ]) + + if not context.executing_eagerly() and sequence_length is not None: + # Perform some shape validation + with ops.control_dependencies( + [_assert_has_shape(sequence_length, [batch_size])]): + sequence_length = array_ops.identity( + sequence_length, name="CheckSeqLen") + + inputs = nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input) + + (outputs, final_state) = _dynamic_rnn_loop( + cell, + inputs, + state, + parallel_iterations=parallel_iterations, + swap_memory=swap_memory, + sequence_length=sequence_length, + dtype=dtype) + + # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth]. + # If we are performing batch-major calculations, transpose output back + # to shape [batch, time, depth] + if not time_major: + # (T,B,D) => (B,T,D) + outputs = nest.map_structure(_transpose_batch_time, outputs) + + return (outputs, final_state) + + +def _dynamic_rnn_loop(cell, + inputs, + initial_state, + parallel_iterations, + swap_memory, + sequence_length=None, + dtype=None): + """Internal implementation of Dynamic RNN. + + Args: + cell: An instance of RNNCell. + inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested + tuple of such elements. + initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if + `cell.state_size` is a tuple, then this should be a tuple of tensors + having shapes `[batch_size, s] for s in cell.state_size`. + parallel_iterations: Positive Python int. + swap_memory: A Python boolean + sequence_length: (optional) An `int32` `Tensor` of shape [batch_size]. + dtype: (optional) Expected dtype of output. If not specified, inferred from + initial_state. + + Returns: + Tuple `(final_outputs, final_state)`. + final_outputs: + A `Tensor` of shape `[time, batch_size, cell.output_size]`. If + `cell.output_size` is a (possibly nested) tuple of ints or `TensorShape` + objects, then this returns a (possibly nested) tuple of Tensors matching + the corresponding shapes. + final_state: + A `Tensor`, or possibly nested tuple of Tensors, matching in length + and shapes to `initial_state`. + + Raises: + ValueError: If the input depth cannot be inferred via shape inference + from the inputs. + ValueError: If time_step is not the same for all the elements in the + inputs. + ValueError: If batch_size is not the same for all the elements in the + inputs. + """ + state = initial_state + assert isinstance(parallel_iterations, int), "parallel_iterations must be int" + + state_size = cell.state_size + + flat_input = nest.flatten(inputs) + flat_output_size = nest.flatten(cell.output_size) + + # Construct an initial output + input_shape = array_ops.shape(flat_input[0]) + time_steps = input_shape[0] + batch_size = _best_effort_input_batch_size(flat_input) + + inputs_got_shape = tuple( + input_.get_shape().with_rank_at_least(3) for input_ in flat_input) + + const_time_steps, const_batch_size = inputs_got_shape[0].as_list()[:2] + + for i, shape in enumerate(inputs_got_shape): + if not shape[2:].is_fully_defined(): + raise ValueError( + "Input size (depth of inputs) must be accessible via shape inference," + f" but saw value None for input={flat_input[i]}.") + got_time_steps = shape.dims[0].value + got_batch_size = shape.dims[1].value + if const_time_steps != got_time_steps: + raise ValueError( + "Time steps is not the same for all the elements in the input in a " + f"batch. Received time steps={got_time_steps} for input=" + f"{flat_input[i]}.") + if const_batch_size != got_batch_size: + raise ValueError( + "Batch_size is not the same for all the elements in the input. " + f"Received batch size={got_batch_size} for input={flat_input[i]}.") + + # Prepare dynamic conditional copying of state & output + def _create_zero_arrays(size): + size = _concat(batch_size, size) + return array_ops.zeros( + array_ops_stack.stack(size), _infer_state_dtype(dtype, state)) + + flat_zero_output = tuple( + _create_zero_arrays(output) for output in flat_output_size) + zero_output = nest.pack_sequence_as( + structure=cell.output_size, flat_sequence=flat_zero_output) + + if sequence_length is not None: + min_sequence_length = math_ops.reduce_min(sequence_length) + max_sequence_length = math_ops.reduce_max(sequence_length) + else: + max_sequence_length = time_steps + + time = array_ops.constant(0, dtype=dtypes.int32, name="time") + + with ops.name_scope("dynamic_rnn") as scope: + base_name = scope + + def _create_ta(name, element_shape, dtype): + return tensor_array_ops.TensorArray( + dtype=dtype, + size=time_steps, + element_shape=element_shape, + tensor_array_name=base_name + name) + + in_graph_mode = not context.executing_eagerly() + if in_graph_mode: + output_ta = tuple( + _create_ta( + "output_%d" % i, + element_shape=( + tensor_shape.TensorShape([const_batch_size]).concatenate( + _maybe_tensor_shape_from_tensor(out_size))), + dtype=_infer_state_dtype(dtype, state)) + for i, out_size in enumerate(flat_output_size)) + input_ta = tuple( + _create_ta( + "input_%d" % i, + element_shape=flat_input_i.shape[1:], + dtype=flat_input_i.dtype) + for i, flat_input_i in enumerate(flat_input)) + input_ta = tuple( + ta.unstack(input_) for ta, input_ in zip(input_ta, flat_input)) + else: + output_ta = tuple([0 for _ in range(time_steps.numpy())] + for i in range(len(flat_output_size))) + input_ta = flat_input + + def _time_step(time, output_ta_t, state): + """Take a time step of the dynamic RNN. + + Args: + time: int32 scalar Tensor. + output_ta_t: List of `TensorArray`s that represent the output. + state: nested tuple of vector tensors that represent the state. + + Returns: + The tuple (time + 1, output_ta_t with updated flow, new_state). + """ + + if in_graph_mode: + input_t = tuple(ta.read(time) for ta in input_ta) + # Restore some shape information + for input_, shape in zip(input_t, inputs_got_shape): + input_.set_shape(shape[1:]) + else: + input_t = tuple(ta[time.numpy()] for ta in input_ta) + + input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t) + # Keras RNN cells only accept state as list, even if it's a single tensor. + call_cell = lambda: cell(input_t, state) + + if sequence_length is not None: + (output, new_state) = _rnn_step( + time=time, + sequence_length=sequence_length, + min_sequence_length=min_sequence_length, + max_sequence_length=max_sequence_length, + zero_output=zero_output, + state=state, + call_cell=call_cell, + state_size=state_size, + skip_conditionals=True) + else: + (output, new_state) = call_cell() + + # Pack state if using state tuples + output = nest.flatten(output) + + if in_graph_mode: + output_ta_t = tuple( + ta.write(time, out) for ta, out in zip(output_ta_t, output)) + else: + for ta, out in zip(output_ta_t, output): + ta[time.numpy()] = out + + return (time + 1, output_ta_t, new_state) + + if in_graph_mode: + # Make sure that we run at least 1 step, if necessary, to ensure + # the TensorArrays pick up the dynamic shape. + loop_bound = math_ops.minimum(time_steps, + math_ops.maximum(1, max_sequence_length)) + else: + # Using max_sequence_length isn't currently supported in the Eager branch. + loop_bound = time_steps + + _, output_final_ta, final_state = while_loop.while_loop( + cond=lambda time, *_: time < loop_bound, + body=_time_step, + loop_vars=(time, output_ta, state), + parallel_iterations=parallel_iterations, + maximum_iterations=time_steps, + swap_memory=swap_memory) + + # Unpack final output if not using output tuples. + if in_graph_mode: + final_outputs = tuple(ta.stack() for ta in output_final_ta) + # Restore some shape information + for output, output_size in zip(final_outputs, flat_output_size): + shape = _concat([const_time_steps, const_batch_size], + output_size, + static=True) + output.set_shape(shape) + else: + final_outputs = output_final_ta + + final_outputs = nest.pack_sequence_as( + structure=cell.output_size, flat_sequence=final_outputs) + if not in_graph_mode: + final_outputs = nest.map_structure_up_to( + cell.output_size, + lambda x: array_ops_stack.stack(x, axis=0), final_outputs) + + return (final_outputs, final_state) + + +@tf_export(v1=["nn.raw_rnn"]) +@dispatch.add_dispatch_support +def raw_rnn(cell, + loop_fn, + parallel_iterations=None, + swap_memory=False, + scope=None): + """Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`. + + **NOTE: This method is still in testing, and the API may change.** + + This function is a more primitive version of `dynamic_rnn` that provides + more direct access to the inputs each iteration. It also provides more + control over when to start and finish reading the sequence, and + what to emit for the output. + + For example, it can be used to implement the dynamic decoder of a seq2seq + model. + + Instead of working with `Tensor` objects, most operations work with + `TensorArray` objects directly. + + The operation of `raw_rnn`, in pseudo-code, is basically the following: + + ```python + time = tf.constant(0, dtype=tf.int32) + (finished, next_input, initial_state, emit_structure, loop_state) = loop_fn( + time=time, cell_output=None, cell_state=None, loop_state=None) + emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype) + state = initial_state + while not all(finished): + (output, cell_state) = cell(next_input, state) + (next_finished, next_input, next_state, emit, loop_state) = loop_fn( + time=time + 1, cell_output=output, cell_state=cell_state, + loop_state=loop_state) + # Emit zeros and copy forward state for minibatch entries that are finished. + state = tf.where(finished, state, next_state) + emit = tf.where(finished, tf.zeros_like(emit_structure), emit) + emit_ta = emit_ta.write(time, emit) + # If any new minibatch entries are marked as finished, mark these. + finished = tf.logical_or(finished, next_finished) + time += 1 + return (emit_ta, state, loop_state) + ``` + + with the additional properties that output and state may be (possibly nested) + tuples, as determined by `cell.output_size` and `cell.state_size`, and + as a result the final `state` and `emit_ta` may themselves be tuples. + + A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this: + + ```python + inputs = tf.compat.v1.placeholder(shape=(max_time, batch_size, input_depth), + dtype=tf.float32) + sequence_length = tf.compat.v1.placeholder(shape=(batch_size,), + dtype=tf.int32) + inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time) + inputs_ta = inputs_ta.unstack(inputs) + + cell = tf.compat.v1.nn.rnn_cell.LSTMCell(num_units) + + def loop_fn(time, cell_output, cell_state, loop_state): + emit_output = cell_output # == None for time == 0 + if cell_output is None: # time == 0 + next_cell_state = cell.zero_state(batch_size, tf.float32) + else: + next_cell_state = cell_state + elements_finished = (time >= sequence_length) + finished = tf.reduce_all(elements_finished) + next_input = tf.cond( + finished, + lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32), + lambda: inputs_ta.read(time)) + next_loop_state = None + return (elements_finished, next_input, next_cell_state, + emit_output, next_loop_state) + + outputs_ta, final_state, _ = raw_rnn(cell, loop_fn) + outputs = outputs_ta.stack() + ``` + + Args: + cell: An instance of RNNCell. + loop_fn: A callable that takes inputs `(time, cell_output, cell_state, + loop_state)` and returns the tuple `(finished, next_input, + next_cell_state, emit_output, next_loop_state)`. Here `time` is an int32 + scalar `Tensor`, `cell_output` is a `Tensor` or (possibly nested) tuple of + tensors as determined by `cell.output_size`, and `cell_state` is a + `Tensor` or (possibly nested) tuple of tensors, as determined by the + `loop_fn` on its first call (and should match `cell.state_size`). + The outputs are: `finished`, a boolean `Tensor` of + shape `[batch_size]`, `next_input`: the next input to feed to `cell`, + `next_cell_state`: the next state to feed to `cell`, + and `emit_output`: the output to store for this iteration. Note that + `emit_output` should be a `Tensor` or (possibly nested) tuple of tensors + which is aggregated in the `emit_ta` inside the `while_loop`. For the + first call to `loop_fn`, the `emit_output` corresponds to the + `emit_structure` which is then used to determine the size of the + `zero_tensor` for the `emit_ta` (defaults to `cell.output_size`). For + the subsequent calls to the `loop_fn`, the `emit_output` corresponds to + the actual output tensor that is to be aggregated in the `emit_ta`. The + parameter `cell_state` and output `next_cell_state` may be either a + single or (possibly nested) tuple of tensors. The parameter + `loop_state` and output `next_loop_state` may be either a single or + (possibly nested) tuple of `Tensor` and `TensorArray` objects. This + last parameter may be ignored by `loop_fn` and the return value may be + `None`. If it is not `None`, then the `loop_state` will be propagated + through the RNN loop, for use purely by `loop_fn` to keep track of its + own state. The `next_loop_state` parameter returned may be `None`. The + first call to `loop_fn` will be `time = 0`, `cell_output = None`, + `cell_state = None`, and `loop_state = None`. For this call: The + `next_cell_state` value should be the value with which to initialize the + cell's state. It may be a final state from a previous RNN or it may be + the output of `cell.zero_state()`. It should be a (possibly nested) + tuple structure of tensors. If `cell.state_size` is an integer, this + must be a `Tensor` of appropriate type and shape `[batch_size, + cell.state_size]`. If `cell.state_size` is a `TensorShape`, this must be + a `Tensor` of appropriate type and shape `[batch_size] + + cell.state_size`. If `cell.state_size` is a (possibly nested) tuple of + ints or `TensorShape`, this will be a tuple having the corresponding + shapes. The `emit_output` value may be either `None` or a (possibly + nested) tuple structure of tensors, e.g., `(tf.zeros(shape_0, + dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`. If this first + `emit_output` return value is `None`, then the `emit_ta` result of + `raw_rnn` will have the same structure and dtypes as `cell.output_size`. + Otherwise `emit_ta` will have the same structure, shapes (prepended with + a `batch_size` dimension), and dtypes as `emit_output`. The actual + values returned for `emit_output` at this initializing call are ignored. + Note, this emit structure must be consistent across all time steps. + parallel_iterations: (Default: 32). The number of iterations to run in + parallel. Those operations which do not have any temporal dependency and + can be run in parallel, will be. This parameter trades off time for + space. Values >> 1 use more memory but take less time, while smaller + values use less memory but computations take longer. + swap_memory: Transparently swap the tensors produced in forward inference + but needed for back prop from GPU to CPU. This allows training RNNs which + would typically not fit on a single GPU, with very minimal (or no) + performance penalty. + scope: VariableScope for the created subgraph; defaults to "rnn". + + Returns: + A tuple `(emit_ta, final_state, final_loop_state)` where: + + `emit_ta`: The RNN output `TensorArray`. + If `loop_fn` returns a (possibly nested) set of Tensors for + `emit_output` during initialization, (inputs `time = 0`, + `cell_output = None`, and `loop_state = None`), then `emit_ta` will + have the same structure, dtypes, and shapes as `emit_output` instead. + If `loop_fn` returns `emit_output = None` during this call, + the structure of `cell.output_size` is used: + If `cell.output_size` is a (possibly nested) tuple of integers + or `TensorShape` objects, then `emit_ta` will be a tuple having the + same structure as `cell.output_size`, containing TensorArrays whose + elements' shapes correspond to the shape data in `cell.output_size`. + + `final_state`: The final cell state. If `cell.state_size` is an int, this + will be shaped `[batch_size, cell.state_size]`. If it is a + `TensorShape`, this will be shaped `[batch_size] + cell.state_size`. + If it is a (possibly nested) tuple of ints or `TensorShape`, this will + be a tuple having the corresponding shapes. + + `final_loop_state`: The final loop state as returned by `loop_fn`. + + Raises: + TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not + a `callable`. + """ + rnn_cell_impl.assert_like_rnncell("cell", cell) + + if not callable(loop_fn): + raise TypeError("Argument `loop_fn` must be a callable. Received: " + f"{loop_fn}.") + + parallel_iterations = parallel_iterations or 32 + + # Create a new scope in which the caching device is either + # determined by the parent scope, or is set to place the cached + # Variable using the same placement as for the rest of the RNN. + with vs.variable_scope(scope or "rnn") as varscope: + if _should_cache(): + if varscope.caching_device is None: + varscope.set_caching_device(lambda op: op.device) + + time = constant_op.constant(0, dtype=dtypes.int32) + (elements_finished, next_input, + initial_state, emit_structure, init_loop_state) = loop_fn( + time, None, None, None) # time, cell_output, cell_state, loop_state + flat_input = nest.flatten(next_input) + + # Need a surrogate loop state for the while_loop if none is available. + loop_state = ( + init_loop_state if init_loop_state is not None else + constant_op.constant(0, dtype=dtypes.int32)) + + input_shape = [input_.get_shape() for input_ in flat_input] + static_batch_size = tensor_shape.dimension_at_index(input_shape[0], 0) + + for input_shape_i in input_shape: + # Static verification that batch sizes all match + static_batch_size.assert_is_compatible_with( + tensor_shape.dimension_at_index(input_shape_i, 0)) + + batch_size = tensor_shape.dimension_value(static_batch_size) + const_batch_size = batch_size + if batch_size is None: + batch_size = array_ops.shape(flat_input[0])[0] + + nest.assert_same_structure(initial_state, cell.state_size) + state = initial_state + flat_state = nest.flatten(state) + flat_state = [ops.convert_to_tensor(s) for s in flat_state] + state = nest.pack_sequence_as(structure=state, flat_sequence=flat_state) + + if emit_structure is not None: + flat_emit_structure = nest.flatten(emit_structure) + flat_emit_size = [ + emit.shape if emit.shape.is_fully_defined() else array_ops.shape(emit) + for emit in flat_emit_structure + ] + flat_emit_dtypes = [emit.dtype for emit in flat_emit_structure] + else: + emit_structure = cell.output_size + flat_emit_size = nest.flatten(emit_structure) + flat_emit_dtypes = [flat_state[0].dtype] * len(flat_emit_size) + + flat_emit_ta = [ + tensor_array_ops.TensorArray( + dtype=dtype_i, + dynamic_size=True, + element_shape=(tensor_shape.TensorShape([ + const_batch_size + ]).concatenate(_maybe_tensor_shape_from_tensor(size_i))), + size=0, + name="rnn_output_%d" % i) + for i, (dtype_i, + size_i) in enumerate(zip(flat_emit_dtypes, flat_emit_size)) + ] + emit_ta = nest.pack_sequence_as( + structure=emit_structure, flat_sequence=flat_emit_ta) + flat_zero_emit = [ + array_ops.zeros(_concat(batch_size, size_i), dtype_i) + for size_i, dtype_i in zip(flat_emit_size, flat_emit_dtypes) + ] + zero_emit = nest.pack_sequence_as( + structure=emit_structure, flat_sequence=flat_zero_emit) + + def condition(unused_time, elements_finished, *_): + return math_ops.logical_not(math_ops.reduce_all(elements_finished)) + + def body(time, elements_finished, current_input, emit_ta, state, + loop_state): + """Internal while loop body for raw_rnn. + + Args: + time: time scalar. + elements_finished: batch-size vector. + current_input: possibly nested tuple of input tensors. + emit_ta: possibly nested tuple of output TensorArrays. + state: possibly nested tuple of state tensors. + loop_state: possibly nested tuple of loop state tensors. + + Returns: + Tuple having the same size as Args but with updated values. + """ + (next_output, cell_state) = cell(current_input, state) + + nest.assert_same_structure(state, cell_state) + nest.assert_same_structure(cell.output_size, next_output) + + next_time = time + 1 + (next_finished, next_input, next_state, emit_output, + next_loop_state) = loop_fn(next_time, next_output, cell_state, + loop_state) + + nest.assert_same_structure(state, next_state) + nest.assert_same_structure(current_input, next_input) + nest.assert_same_structure(emit_ta, emit_output) + + # If loop_fn returns None for next_loop_state, just reuse the + # previous one. + loop_state = loop_state if next_loop_state is None else next_loop_state + + def _copy_some_through(current, candidate): + """Copy some tensors through via array_ops.where.""" + + def copy_fn(cur_i, cand_i): + # TensorArray and scalar get passed through. + if isinstance(cur_i, tensor_array_ops.TensorArray): + return cand_i + if cur_i.shape.rank == 0: + return cand_i + # Otherwise propagate the old or the new value. + with ops.colocate_with(cand_i): + return array_ops.where(elements_finished, cur_i, cand_i) + + return nest.map_structure(copy_fn, current, candidate) + + emit_output = _copy_some_through(zero_emit, emit_output) + next_state = _copy_some_through(state, next_state) + + emit_ta = nest.map_structure(lambda ta, emit: ta.write(time, emit), + emit_ta, emit_output) + + elements_finished = math_ops.logical_or(elements_finished, next_finished) + + return (next_time, elements_finished, next_input, emit_ta, next_state, + loop_state) + + returned = while_loop.while_loop( + condition, + body, + loop_vars=[ + time, elements_finished, next_input, emit_ta, state, loop_state + ], + parallel_iterations=parallel_iterations, + swap_memory=swap_memory) + + (emit_ta, final_state, final_loop_state) = returned[-3:] + + if init_loop_state is None: + final_loop_state = None + + return (emit_ta, final_state, final_loop_state) + + +@deprecation.deprecated(None, + "Please use `keras.layers.RNN(cell, unroll=True)`, " + "which is equivalent to this API") +@tf_export(v1=["nn.static_rnn"]) +@dispatch.add_dispatch_support +def static_rnn(cell, + inputs, + initial_state=None, + dtype=None, + sequence_length=None, + scope=None): + """Creates a recurrent neural network specified by RNNCell `cell`. + + The simplest form of RNN network generated is: + + ```python + state = cell.zero_state(...) + outputs = [] + for input_ in inputs: + output, state = cell(input_, state) + outputs.append(output) + return (outputs, state) + ``` + However, a few other options are available: + + An initial state can be provided. + If the sequence_length vector is provided, dynamic calculation is performed. + This method of calculation does not compute the RNN steps past the maximum + sequence length of the minibatch (thus saving computational time), + and properly propagates the state at an example's sequence length + to the final state output. + + The dynamic calculation performed is, at time `t` for batch row `b`, + + ```python + (output, state)(b, t) = + (t >= sequence_length(b)) + ? (zeros(cell.output_size), states(b, sequence_length(b) - 1)) + : cell(input(b, t), state(b, t - 1)) + ``` + + Args: + cell: An instance of RNNCell. + inputs: A length T list of inputs, each a `Tensor` of shape `[batch_size, + input_size]`, or a nested tuple of such elements. + initial_state: (optional) An initial state for the RNN. If `cell.state_size` + is an integer, this must be a `Tensor` of appropriate type and shape + `[batch_size, cell.state_size]`. If `cell.state_size` is a tuple, this + should be a tuple of tensors having shapes `[batch_size, s] for s in + cell.state_size`. + dtype: (optional) The data type for the initial state and expected output. + Required if initial_state is not provided or RNN state has a heterogeneous + dtype. + sequence_length: Specifies the length of each sequence in inputs. An int32 + or int64 vector (tensor) size `[batch_size]`, values in `[0, T)`. + scope: VariableScope for the created subgraph; defaults to "rnn". + + Returns: + A pair (outputs, state) where: + + - outputs is a length T list of outputs (one for each input), or a nested + tuple of such elements. + - state is the final state + + Raises: + TypeError: If `cell` is not an instance of RNNCell. + ValueError: If `inputs` is `None` or an empty list, or if the input depth + (column size) cannot be inferred from inputs via shape inference. + """ + rnn_cell_impl.assert_like_rnncell("cell", cell) + if not nest.is_nested(inputs): + raise TypeError(f"Argument `inputs` must be a sequence. Received: {inputs}") + if not inputs: + raise ValueError("Argument `inputs` must not be empty.") + + outputs = [] + # Create a new scope in which the caching device is either + # determined by the parent scope, or is set to place the cached + # Variable using the same placement as for the rest of the RNN. + with vs.variable_scope(scope or "rnn") as varscope: + if _should_cache(): + if varscope.caching_device is None: + varscope.set_caching_device(lambda op: op.device) + + # Obtain the first sequence of the input + first_input = inputs + while nest.is_nested(first_input): + first_input = first_input[0] + + # Temporarily avoid EmbeddingWrapper and seq2seq badness + # TODO(lukaszkaiser): remove EmbeddingWrapper + if first_input.get_shape().rank != 1: + + input_shape = first_input.get_shape().with_rank_at_least(2) + fixed_batch_size = input_shape.dims[0] + + flat_inputs = nest.flatten(inputs) + for flat_input in flat_inputs: + input_shape = flat_input.get_shape().with_rank_at_least(2) + batch_size, input_size = tensor_shape.dimension_at_index( + input_shape, 0), input_shape[1:] + fixed_batch_size.assert_is_compatible_with(batch_size) + for i, size in enumerate(input_size.dims): + if tensor_shape.dimension_value(size) is None: + raise ValueError( + f"Input size (dimension {i} of input {flat_input}) must be " + "accessible via shape inference, but saw value None.") + else: + fixed_batch_size = first_input.get_shape().with_rank_at_least(1)[0] + + if tensor_shape.dimension_value(fixed_batch_size): + batch_size = tensor_shape.dimension_value(fixed_batch_size) + else: + batch_size = array_ops.shape(first_input)[0] + if initial_state is not None: + state = initial_state + else: + if not dtype: + raise ValueError("If no initial_state is provided, argument `dtype` " + "must be specified") + if getattr(cell, "get_initial_state", None) is not None: + state = cell.get_initial_state( + inputs=None, batch_size=batch_size, dtype=dtype) + else: + state = cell.zero_state(batch_size, dtype) + + if sequence_length is not None: # Prepare variables + sequence_length = ops.convert_to_tensor( + sequence_length, name="sequence_length") + if sequence_length.get_shape().rank not in (None, 1): + raise ValueError( + "Argument `sequence_length` must be a vector of length " + f"{batch_size}. Received sequence_length={sequence_length}.") + + def _create_zero_output(output_size): + # convert int to TensorShape if necessary + size = _concat(batch_size, output_size) + output = array_ops.zeros( + array_ops_stack.stack(size), _infer_state_dtype(dtype, state)) + shape = _concat( + tensor_shape.dimension_value(fixed_batch_size), + output_size, + static=True) + output.set_shape(tensor_shape.TensorShape(shape)) + return output + + output_size = cell.output_size + flat_output_size = nest.flatten(output_size) + flat_zero_output = tuple( + _create_zero_output(size) for size in flat_output_size) + zero_output = nest.pack_sequence_as( + structure=output_size, flat_sequence=flat_zero_output) + + sequence_length = math_ops.cast(sequence_length, dtypes.int32) + min_sequence_length = math_ops.reduce_min(sequence_length) + max_sequence_length = math_ops.reduce_max(sequence_length) + + for time, input_ in enumerate(inputs): + if time > 0: + varscope.reuse_variables() + # pylint: disable=cell-var-from-loop + call_cell = lambda: cell(input_, state) + # pylint: enable=cell-var-from-loop + if sequence_length is not None: + (output, state) = _rnn_step( + time=time, + sequence_length=sequence_length, + min_sequence_length=min_sequence_length, + max_sequence_length=max_sequence_length, + zero_output=zero_output, + state=state, + call_cell=call_cell, + state_size=cell.state_size) + else: + (output, state) = call_cell() + outputs.append(output) + + return (outputs, state) + + +@deprecation.deprecated(None, + "Please use `keras.layers.RNN(cell, stateful=True)`, " + "which is equivalent to this API") +@tf_export(v1=["nn.static_state_saving_rnn"]) +@dispatch.add_dispatch_support +def static_state_saving_rnn(cell, + inputs, + state_saver, + state_name, + sequence_length=None, + scope=None): + """RNN that accepts a state saver for time-truncated RNN calculation. + + Args: + cell: An instance of `RNNCell`. + inputs: A length T list of inputs, each a `Tensor` of shape `[batch_size, + input_size]`. + state_saver: A state saver object with methods `state` and `save_state`. + state_name: Python string or tuple of strings. The name to use with the + state_saver. If the cell returns tuples of states (i.e., `cell.state_size` + is a tuple) then `state_name` should be a tuple of strings having the same + length as `cell.state_size`. Otherwise it should be a single string. + sequence_length: (optional) An int32/int64 vector size [batch_size]. See the + documentation for rnn() for more details about sequence_length. + scope: VariableScope for the created subgraph; defaults to "rnn". + + Returns: + A pair (outputs, state) where: + outputs is a length T list of outputs (one for each input) + states is the final state + + Raises: + TypeError: If `cell` is not an instance of RNNCell. + ValueError: If `inputs` is `None` or an empty list, or if the arity and + type of `state_name` does not match that of `cell.state_size`. + """ + state_size = cell.state_size + state_is_tuple = nest.is_nested(state_size) + state_name_tuple = nest.is_nested(state_name) + + if state_is_tuple != state_name_tuple: + raise ValueError("Argument `state_name` should be the same type as " + f"`cell.state_size`. Received: state_name={state_name!s}, " + f"cell.state_size={state_size!s}.") + + if state_is_tuple: + state_name_flat = nest.flatten(state_name) + state_size_flat = nest.flatten(state_size) + + if len(state_name_flat) != len(state_size_flat): + raise ValueError("Number of elements in argument `state_name` and " + "`cell.state_size` are mismatched. Received " + f"state_name={state_name} with {len(state_name_flat)} " + f"elements and cell.state_size={cell.state_size} with " + f"{len(state_size_flat)} elements.") + + initial_state = nest.pack_sequence_as( + structure=state_size, + flat_sequence=[state_saver.state(s) for s in state_name_flat]) + else: + initial_state = state_saver.state(state_name) + + (outputs, state) = static_rnn( + cell, + inputs, + initial_state=initial_state, + sequence_length=sequence_length, + scope=scope) + + if state_is_tuple: + flat_state = nest.flatten(state) + state_name = nest.flatten(state_name) + save_state = [ + state_saver.save_state(name, substate) + for name, substate in zip(state_name, flat_state) + ] + else: + save_state = [state_saver.save_state(state_name, state)] + + with ops.control_dependencies(save_state): + last_output = outputs[-1] + flat_last_output = nest.flatten(last_output) + flat_last_output = [ + array_ops.identity(output) for output in flat_last_output + ] + outputs[-1] = nest.pack_sequence_as( + structure=last_output, flat_sequence=flat_last_output) + + if state_is_tuple: + state = nest.pack_sequence_as( + structure=state, + flat_sequence=[array_ops.identity(s) for s in flat_state]) + else: + state = array_ops.identity(state) + + return (outputs, state) + + +@deprecation.deprecated(None, "Please use `keras.layers.Bidirectional(" + "keras.layers.RNN(cell, unroll=True))`, which is " + "equivalent to this API") +@tf_export(v1=["nn.static_bidirectional_rnn"]) +@dispatch.add_dispatch_support +def static_bidirectional_rnn(cell_fw, + cell_bw, + inputs, + initial_state_fw=None, + initial_state_bw=None, + dtype=None, + sequence_length=None, + scope=None): + """Creates a bidirectional recurrent neural network. + + Similar to the unidirectional case above (rnn) but takes input and builds + independent forward and backward RNNs with the final forward and backward + outputs depth-concatenated, such that the output will have the format + [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of + forward and backward cell must match. The initial state for both directions + is zero by default (but can be set optionally) and no intermediate states are + ever returned -- the network is fully unrolled for the given (passed in) + length(s) of the sequence(s) or completely unrolled if length(s) is not given. + + Args: + cell_fw: An instance of RNNCell, to be used for forward direction. + cell_bw: An instance of RNNCell, to be used for backward direction. + inputs: A length T list of inputs, each a tensor of shape [batch_size, + input_size], or a nested tuple of such elements. + initial_state_fw: (optional) An initial state for the forward RNN. This must + be a tensor of appropriate type and shape `[batch_size, + cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a + tuple of tensors having shapes `[batch_size, s] for s in + cell_fw.state_size`. + initial_state_bw: (optional) Same as for `initial_state_fw`, but using the + corresponding properties of `cell_bw`. + dtype: (optional) The data type for the initial state. Required if either + of the initial states are not provided. + sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, + containing the actual lengths for each of the sequences. + scope: VariableScope for the created subgraph; defaults to + "bidirectional_rnn" + + Returns: + A tuple (outputs, output_state_fw, output_state_bw) where: + outputs is a length `T` list of outputs (one for each input), which + are depth-concatenated forward and backward outputs. + output_state_fw is the final state of the forward rnn. + output_state_bw is the final state of the backward rnn. + + Raises: + TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. + ValueError: If inputs is None or an empty list. + """ + rnn_cell_impl.assert_like_rnncell("cell_fw", cell_fw) + rnn_cell_impl.assert_like_rnncell("cell_bw", cell_bw) + if not nest.is_nested(inputs): + raise TypeError(f"Argument `inputs` must be a sequence. Received: {inputs}") + if not inputs: + raise ValueError("Argument `inputs` must not be empty.") + + with vs.variable_scope(scope or "bidirectional_rnn"): + # Forward direction + with vs.variable_scope("fw") as fw_scope: + output_fw, output_state_fw = static_rnn( + cell_fw, + inputs, + initial_state_fw, + dtype, + sequence_length, + scope=fw_scope) + + # Backward direction + with vs.variable_scope("bw") as bw_scope: + reversed_inputs = _reverse_seq(inputs, sequence_length) + tmp, output_state_bw = static_rnn( + cell_bw, + reversed_inputs, + initial_state_bw, + dtype, + sequence_length, + scope=bw_scope) + + output_bw = _reverse_seq(tmp, sequence_length) + # Concat each of the forward/backward outputs + flat_output_fw = nest.flatten(output_fw) + flat_output_bw = nest.flatten(output_bw) + + flat_outputs = tuple( + array_ops.concat([fw, bw], 1) + for fw, bw in zip(flat_output_fw, flat_output_bw)) + + outputs = nest.pack_sequence_as( + structure=output_fw, flat_sequence=flat_outputs) + + return (outputs, output_state_fw, output_state_bw) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc05e834cfb79f0745fd0aeeee2ce250e684a40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell.py @@ -0,0 +1,19 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module for constructing RNN Cells.""" +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.rnn_cell_impl import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..9cff803335c6a3ae418b958c3aba0353d11c79bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_cell_impl.py @@ -0,0 +1,179 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module implementing RNN Cells. + +This module provides a number of basic commonly used RNN cells, such as LSTM +(Long Short Term Memory) or GRU (Gated Recurrent Unit), and a number of +operators that allow adding dropouts, projections, or embeddings for inputs. +Constructing multi-layer cells is supported by the class `MultiRNNCell`, or by +calling the `rnn` ops several times. +""" +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras.layers.legacy_rnn import rnn_cell_impl +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest + +# Remove caller that rely on private symbol in future. +_BIAS_VARIABLE_NAME = "bias" +_WEIGHTS_VARIABLE_NAME = "kernel" + +BasicLSTMCell = rnn_cell_impl.BasicLSTMCell +BasicRNNCell = rnn_cell_impl.BasicRNNCell +DeviceWrapper = rnn_cell_impl.DeviceWrapper +DropoutWrapper = rnn_cell_impl.DropoutWrapper +GRUCell = rnn_cell_impl.GRUCell +LayerRNNCell = rnn_cell_impl.LayerRNNCell +LSTMCell = rnn_cell_impl.LSTMCell +LSTMStateTuple = rnn_cell_impl.LSTMStateTuple +MultiRNNCell = rnn_cell_impl.MultiRNNCell +ResidualWrapper = rnn_cell_impl.ResidualWrapper +RNNCell = rnn_cell_impl.RNNCell + + +def _zero_state_tensors(state_size, batch_size, dtype): + """Create tensors of zeros based on state_size, batch_size, and dtype.""" + + def get_state_shape(s): + """Combine s with batch_size to get a proper tensor shape.""" + c = _concat(batch_size, s) + size = array_ops.zeros(c, dtype=dtype) + if not context.executing_eagerly(): + c_static = _concat(batch_size, s, static=True) + size.set_shape(c_static) + return size + + return nest.map_structure(get_state_shape, state_size) + + +def _concat(prefix, suffix, static=False): + """Concat that enables int, Tensor, or TensorShape values. + + This function takes a size specification, which can be an integer, a + TensorShape, or a Tensor, and converts it into a concatenated Tensor + (if static = False) or a list of integers (if static = True). + + Args: + prefix: The prefix; usually the batch size (and/or time step size). + (TensorShape, int, or Tensor.) + suffix: TensorShape, int, or Tensor. + static: If `True`, return a python list with possibly unknown dimensions. + Otherwise return a `Tensor`. + + Returns: + shape: the concatenation of prefix and suffix. + + Raises: + ValueError: if `suffix` is not a scalar or vector (or TensorShape). + ValueError: if prefix or suffix was `None` and asked for dynamic + Tensors out. + """ + if isinstance(prefix, tensor.Tensor): + p = prefix + p_static = tensor_util.constant_value(prefix) + if p.shape.ndims == 0: + p = array_ops.expand_dims(p, 0) + elif p.shape.ndims != 1: + raise ValueError( + "prefix tensor must be either a scalar or vector, but saw tensor: %s" + % p + ) + else: + p = tensor_shape.TensorShape(prefix) + p_static = p.as_list() if p.ndims is not None else None + p = ( + constant_op.constant(p.as_list(), dtype=dtypes.int32) + if p.is_fully_defined() + else None + ) + if isinstance(suffix, tensor.Tensor): + s = suffix + s_static = tensor_util.constant_value(suffix) + if s.shape.ndims == 0: + s = array_ops.expand_dims(s, 0) + elif s.shape.ndims != 1: + raise ValueError( + "suffix tensor must be either a scalar or vector, but saw tensor: %s" + % s + ) + else: + s = tensor_shape.TensorShape(suffix) + s_static = s.as_list() if s.ndims is not None else None + s = ( + constant_op.constant(s.as_list(), dtype=dtypes.int32) + if s.is_fully_defined() + else None + ) + + if static: + shape = tensor_shape.TensorShape(p_static).concatenate(s_static) + shape = shape.as_list() if shape.ndims is not None else None + else: + if p is None or s is None: + raise ValueError( + "Provided a prefix or suffix of None: %s and %s" % (prefix, suffix) + ) + shape = array_ops.concat((p, s), 0) + return shape + + +def _hasattr(obj, attr_name): + try: + getattr(obj, attr_name) + except AttributeError: + return False + else: + return True + + +def assert_like_rnncell(cell_name, cell): + """Raises a TypeError if cell is not like an RNNCell. + + NOTE: Do not rely on the error message (in particular in tests) which can be + subject to change to increase readability. Use + ASSERT_LIKE_RNNCELL_ERROR_REGEXP. + + Args: + cell_name: A string to give a meaningful error referencing to the name of + the functionargument. + cell: The object which should behave like an RNNCell. + + Raises: + TypeError: A human-friendly exception. + """ + conditions = [ + _hasattr(cell, "output_size"), + _hasattr(cell, "state_size"), + _hasattr(cell, "get_initial_state") or _hasattr(cell, "zero_state"), + callable(cell), + ] + errors = [ + "'output_size' property is missing", + "'state_size' property is missing", + "either 'zero_state' or 'get_initial_state' method is required", + "is not callable", + ] + + if not all(conditions): + errors = [error for error, cond in zip(errors, conditions) if not cond] + raise TypeError( + "The argument {!r} ({}) is not an RNNCell: {}.".format( + cell_name, cell, ", ".join(errors) + ) + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..f2c420ef5352597e7d2de2e7175e8c85ecc58ed2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/rnn_grad.py @@ -0,0 +1,51 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for (block) GRU/LSTM operators.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_rnn_ops + + +def _block_lstm_grad(op, *grads): + """Gradient for the BlockLSTM op.""" + seq_len_max, x, cs_prev, h_prev, w, wci, wcf, wco, b = op.inputs + i, cs, f, o, ci, co, h = op.outputs + _, cs_grad, _, _, _, _, h_grad = grads + (x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, wco_grad, + b_grad) = gen_rnn_ops.block_lstm_grad( + seq_len_max=seq_len_max, + x=x, + cs_prev=cs_prev, + h_prev=h_prev, + w=w, + wci=wci, + wcf=wcf, + wco=wco, + b=b, + i=i, + cs=cs, + f=f, + o=o, + ci=ci, + co=co, + h=h, + cs_grad=cs_grad, + h_grad=h_grad, + use_peephole=op.get_attr("use_peephole")) + return (None, x_grad, cs_prev_grad, h_prev_grad, w_grad, wci_grad, wcf_grad, + wco_grad, b_grad) + + +ops.RegisterGradient("BlockLSTM")(_block_lstm_grad) +ops.RegisterGradient("BlockLSTMV2")(_block_lstm_grad) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/script_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/script_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a6d0a7f2f69dfbfabd2291f42922da80e36fee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/script_ops.py @@ -0,0 +1,1020 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Script Language Operators.""" + +# pylint: disable=g-bad-name +import functools +import threading + + +# Used by py_util.cc to get tracebacks. +import traceback # pylint: disable=unused-import +import weakref + +import numpy as np + +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.eager import backprop +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.lib.core import _pywrap_py_func +from tensorflow.python.ops import autograph_ops # pylint: disable=unused-import +from tensorflow.python.ops import gen_script_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +# Map from EagerPyFunc token to tuple (tape, eager args, eager outputs); +# used for differentiation. +tape_cache = {} + + +def _maybe_copy_to_context_device(tensor, device_name): + """Copy an EagerTensor to the current device if it's not on `device_name`.""" + in_device = tensor.backing_device + if device_name == in_device: + return tensor + else: + # Note that EagerTensor._copy bypasses the placer and copies to the context + # device, which means e.g. int32 Tensors which would normally be forced onto + # the CPU can instead be placed on the GPU. This is necessary so that the + # PyFunc kernel always returns Tensors on the device it's executing on. + return tensor._copy() # pylint: disable=protected-access + + +class EagerFunc: + """A wrapper for a function owned by an EagerPyFunc.""" + + def __init__(self, func, Tout, is_grad_func): + """Constructs an EagerFunc. + + Args: + func: The function to wrap. + Tout: A list of datatypes for the output; an empty list if the output is + None. + is_grad_func: Whether this EagerFunc is the gradient of another + EagerPyFunc. + """ + self._func = func + self._out_dtypes = Tout + self._is_grad_func = is_grad_func + self._support_graph_mode_gradient = False + + def set_support_graph_mode_gradient(self): + """Indicates the object shall support gradient ops. + + This function is internally used by _EagerPyFuncGrad to support + graph mode gradient of EagerFunc via tf.gradient(). + """ + self._support_graph_mode_gradient = True + + def _convert(self, value, dtype): + """Converts `value` to a tensor of type `dtype`, with error checking. + + Args: + value: The tensor to convert. + dtype: The desired dtype. + + Returns: + A tensor of type `dtype`, or a zeros tensor if value is None and + this function is in fact a gradient function. + + Raises: + RuntimeError: if `value` is a variable. + """ + + if isinstance(value, resource_variable_ops.ResourceVariable): + raise RuntimeError( + "Attempting to return a variable from an eagerly executed py_func. " + "Only numeric data structures like Tensors or NumPy arrays should " + "be returned; to return the value of a variable, make sure to obtain " + "the Tensor backing it by calling `.read_value()` on the variable in " + f"question: {value}") + if value is None and self._is_grad_func: + # Gradient functions may legitimately return a list that contains + # both Tensors and Python Nones. Unfortunately this breaks the + # OpKernel, so for now we replace None objects with zeros, which is + # mathematically correct but will prevent short-circuiting gradient + # computations. + # + # TODO(akshayka): Make it possible to return a list of both Tensors and + # Nones from an EagerPyFunc. + return constant_op.constant(0.0, dtype=dtype) + return ops.convert_to_tensor(value, dtype=dtype) + + def __call__(self, device, token, args): + """Calls `self._func` in eager mode, recording the tape if needed.""" + use_tape_cache = ( + self._support_graph_mode_gradient or record.could_possibly_record()) + + if use_tape_cache: + with backprop.GradientTape() as tape: + for tensor in args: + for t in nest.flatten(tensor): + if backprop_util.IsTrainable(t): + tape.watch(t) + outputs = self._call(device, args) + tape_cache[compat.as_bytes(token)] = (tape, args, outputs) + else: + outputs = self._call(device, args) + + return outputs + + def _call(self, device, args): + """Passes `args` to `self._func`, which is executed eagerly.""" + with context.eager_mode(): + ret = self._func(*args) + # copy the returned tensors to the PyFunc op's device if necessary. + device_name = device + if device_name is None: + # "None" here means "CPU", from the nullptr convention with C++ device + # pointers. + device_name = "/job:localhost/replica:0/task:0/device:CPU:0" + with ops.device(device): + if isinstance(ret, (tuple, list)): + outputs = [ + _maybe_copy_to_context_device(self._convert(x, dtype=dtype), + device_name) + for (x, dtype) in zip(ret, self._out_dtypes) + ] + elif ret is None: + outputs = None + else: + outputs = _maybe_copy_to_context_device( + self._convert(ret, dtype=self._out_dtypes[0]), device_name) + return outputs + + +class FuncRegistry: + """A helper class to keep track of registered py functions. + + FuncRegistry keeps a map from unique tokens (string) to python + functions, which takes numpy arrays and outputs numpy arrays. + """ + + def __init__(self): + self._lock = threading.Lock() + self._unique_id = 0 # GUARDED_BY(self._lock) + # Only store weakrefs to the functions. The strong reference is stored in + # the graph. + self._funcs = weakref.WeakValueDictionary() + + @property + def _ctx(self): + # N.B. This is needed to support calling py_func with GPU tensors, + # which must be transferred to CPU if used in any of the NumPy APIs. + context.ensure_initialized() + return context.context()._handle # pylint: disable=protected-access + + def insert(self, func): + """Registers `func` and returns a unique token for this entry.""" + token = self._next_unique_token() + # Store a weakref to the function + self._funcs[token] = func + return token + + def remove(self, token): + """Removes the registered function corresponding to `token`.""" + self._funcs.pop(token, None) + + def get(self, token, default=None): + """Gets the registered function corresponding to `token`.""" + return self._funcs.get(token, default) + + @staticmethod + def _convert(value, dtype=None): + """Converts an arg to numpy, avoiding dangerous string and unicode dtypes. + + Numpy pads with zeros when using string and unicode dtypes if different + components of a tensor have different lengths. This is bad: ignoring the + padding is wrong for text data, and removing the padding is wrong for binary + data. To avoid this bug, we redo the conversion using an object dtype. + Additionally, we convert unicode strings to (byte-)strings for + compatibility. + + Args: + value: Value to convert to a numpy array. + dtype: (Optional.) Desired NumPy type for the returned value. + + Returns: + A numpy array. + """ + result = np.asarray(value, dtype=dtype, order="C") + if result.dtype.char == "S" and result is not value: + return np.asarray(value, order="C", dtype=object) + elif result.dtype.char == "U" and result is not value: + value = np.vectorize(lambda x: x.encode("utf8"))(value) + return np.asarray(value, order="C", dtype=object) + elif result.dtype.char == "U": + return result.astype(np.bytes_) + else: + return result + + def __call__(self, token, device, args): + """Calls the registered function for `token` with args. + + Args: + token: A key into this `FuncRegistry` identifying which function to call. + device: Name of the device on which outputs of `token`'s corresponding + operation should be placed. Used iff the function registered for `token` + is an EagerPyFunc. + args: The arguments to pass to the function registered for `token`. + + Returns: + The output of the function registered for `token`. + + Raises: + ValueError: if no function is registered for `token`. + """ + func = self.get(token, None) + if func is None: + raise ValueError(f"Could not find callback with key={token} in the " + "registry.") + if isinstance(func, EagerFunc): + # NB: Different invocations of the same py_func will share the same + # token, and the entries they stash in the tape_cache will collide. + # In practice, when executing a graph, this should only happen if + # the py_func is in a while_loop whose iterations are run in parallel + # or if the graph is being driven by concurrent session.run() calls. + # + # TODO(akshayka): Key the tape cache in a thread-safe way. + return func(device, token, args) + else: + ret = func(*args) + # Strings seem to lead to a memory leak here if they're not wrapped in a + # list. + if isinstance(ret, bytes): + ret = [ret] + # Ensures that we return either a single numpy array or a list of numpy + # arrays. + if isinstance(ret, (tuple, list)): + return [self._convert(x) for x in ret] + else: + return self._convert(ret) + + def size(self): + """Returns how many functions are currently registered.""" + return len(self._funcs) + + def _next_unique_token(self): + """Returns a unique token.""" + with self._lock: + uid = self._unique_id + self._unique_id += 1 + return "pyfunc_%d" % uid + + +# Global registry for py functions. +_py_funcs = FuncRegistry() + +_pywrap_py_func.initialize_py_trampoline(_py_funcs) + + +def _internal_py_func(func, + inp, + Tout, + stateful=None, + use_eager_py_func=False, + is_grad_func=False, + name=None): + """See documentation for py_func and eager_py_func.""" + if not callable(func): + raise ValueError( + f"Expected func to be callable. Received func={func} of type " + f"{type(func)}.") + + original_func = func + func = autograph.do_not_convert(func) + inp = variable_utils.convert_variables_to_tensors(list(inp)) + + # Normalize Tout. + is_list_or_tuple = isinstance(Tout, (list, tuple)) + Tout = Tout if is_list_or_tuple else [Tout] + Tout = [_as_dtype_or_type_spec(t) for t in Tout] + + # Check if we need to handle CompositeTensor inputs or outputs. + handle_composite_tensors = ( + use_eager_py_func and + (any(isinstance(v, composite_tensor.CompositeTensor) for v in inp) or + any(isinstance(t, type_spec.TypeSpec) for t in Tout))) + if handle_composite_tensors: + func, inp, Tout, out_structure = _wrap_for_composites(func, inp, Tout) + + if use_eager_py_func: + func = EagerFunc(func, Tout, is_grad_func) + + # Tying the registered function's lifetime with the current default graph is + # not reliable. For example, Estimator-based binaries may switch graphs in + # between model training end evaluation, via saved_model. Those binaries work + # because the original function is global, and break once the registered + # function is an anonymous lambda, like the one produced by do_not_convert. + # To avoid breaking those cases, we attach the wrapper to the original + # function so that their lifetime is connected. + # TODO(b/144286616): Remove this. + if tf_inspect.isfunction(original_func): + # Note: this check is needed because original_func may be a descriptor + # (https://docs.python.org/3/howto/descriptor.html) + # and we can't attach attributes to those. + original_func.ag_dnc_wrapper__ = func + + token = _py_funcs.insert(func) + # We tie the registered function's lifetime with the current default graph, + # i.e., when the current graph is destroyed, we remove its py funcs. + graph = ops.get_default_graph() + + while True: + current_graph = graph + if isinstance(graph, function._FuncGraph): # pylint: disable=protected-access + graph = graph._outer_graph # pylint: disable=protected-access + elif isinstance(graph, func_graph.FuncGraph): + graph = graph.outer_graph + if graph is current_graph: + break + + # TODO(zhifengc): Consider adding a Graph method to collect + # `cleanup` objects in one of its member. + if not hasattr(graph, "_py_funcs_used_in_graph"): + graph._py_funcs_used_in_graph = [] # pylint: disable=protected-access + + # Store a reference to the function in the graph to ensure it stays alive + # as long as the graph lives. When the graph is destroyed, the function + # is left to the garbage collector for destruction as well. + graph._py_funcs_used_in_graph.append(func) # pylint: disable=protected-access + + if use_eager_py_func: + result = gen_script_ops.eager_py_func( + input=inp, + token=token, + is_async=context.is_async(), + Tout=Tout, + name=name) + else: + if stateful: + result = gen_script_ops.py_func( + input=inp, token=token, Tout=Tout, name=name) + else: + result = gen_script_ops.py_func_stateless( + input=inp, token=token, Tout=Tout, name=name) + + if handle_composite_tensors and Tout: + result = nest.pack_sequence_as( + out_structure, result, expand_composites=True) + + return result if is_list_or_tuple else result[0] + + +# TODO(akshayka): Implement higher-order derivatives. +@ops.RegisterGradient("EagerPyFunc") +def _EagerPyFuncGrad(op, *dy): + """Computes the gradient of an EagerPyFunc.""" + + token = op.get_attr("token") + + def eagerly_executed_grad(*dy): + tape, eager_inputs, eager_outputs = tape_cache.pop(compat.as_bytes(token)) + return tape.gradient(eager_outputs, eager_inputs, output_gradients=dy) + + with ops.control_dependencies(op.outputs): + gradient_op = _internal_py_func( + func=eagerly_executed_grad, + inp=dy, + Tout=[tensor.dtype for tensor in op.inputs], + use_eager_py_func=True, + is_grad_func=True) + + if not context.executing_eagerly(): + # In graph mode, we find the func object from its token and + # notify the eager func object it needs to support the gradients. + func = _py_funcs.get(token.decode()) + assert isinstance(func, EagerFunc), ( + f"EagerPyFuncGrad called on a non-EagerFunc object: {func}.") + func.set_support_graph_mode_gradient() + return gradient_op + + +def _check_args_and_maybe_make_decorator( + script_op, script_op_name, func=None, inp=None, Tout=None, **kwargs +): + """Checks the arguments and returns a decorator if func is None.""" + if Tout is None: + raise TypeError( + "Missing required argument: 'Tout'\n" + f" If using {script_op_name} as a decorator, set `Tout`\n" + " **by name** above the function:\n" + f" `@{script_op_name}(Tout=tout)`" + ) + + if func is None: + if inp is not None: + raise TypeError( + f"Don't set the `inp` argument when using {script_op_name} as a " + "decorator (`func=None`)." + ) + + def py_function_decorator(fun): + @functools.wraps(fun) + def py_function_wrapper(*args): + return script_op(fun, inp=args, Tout=Tout, **kwargs) + + return py_function_wrapper + + return py_function_decorator + + if inp is None: + raise TypeError( + "Missing argument `inp`:\n" + " You must set the `inp` argument (the list of arguments to the\n" + f" function), unless you use `{script_op_name}` as a decorator" + "(`func=None`)." + ) + + return None + + +@tf_export("py_function") +@dispatch.add_dispatch_support +def eager_py_func(func=None, inp=None, Tout=None, name=None): + """Wraps a python function into a TensorFlow op that executes it eagerly. + + Using `tf.py_function` inside a `tf.function` allows you to run a python + function using eager execution, inside the `tf.function`'s graph. + This has two main affects: + + 1. This allows you to use nofunc=None, inp=None, Tout=Nonen tensorflow code + inside your `tf.function`. + 2. It allows you to run python control logic in a `tf.function` without + relying on `tf.autograph` to convert the code to use tensorflow control logic + (tf.cond, tf.while_loop). + + Both of these features can be useful for debgging. + + Since `tf.py_function` operates on `Tensor`s it is still + differentiable (once). + + There are two ways to use this function: + + ### As a decorator + + Use `tf.py_function` as a decorator to ensure the function always runs + eagerly. + + When using `tf.py_function` as a decorator: + + * you must set `Tout` + * you may set `name` + * you must not set `func` or `inp` + + For example, you might use `tf.py_function` to + implement the log huber function. + + >>> @tf.py_function(Tout=tf.float32) + ... def py_log_huber(x, m): + ... print('Running with eager execution.') + ... if tf.abs(x) <= m: + ... return x**2 + ... else: + ... return m**2 * (1 - 2 * tf.math.log(m) + tf.math.log(x**2)) + + Under eager execution the function operates normally: + + >>> x = tf.constant(1.0) + >>> m = tf.constant(2.0) + >>> + >>> print(py_log_huber(x,m).numpy()) + Running with eager execution. + 1.0 + + Inside a `tf.function` the `tf.py_function` is not converted to a `tf.Graph`.: + + >>> @tf.function + ... def tf_wrapper(x): + ... print('Tracing.') + ... m = tf.constant(2.0) + ... return py_log_huber(x,m) + + The `tf.py_function` only executes eagerly, and only when the `tf.function` + is called: + + >>> print(tf_wrapper(x).numpy()) + Tracing. + Running with eager execution. + 1.0 + >>> print(tf_wrapper(x).numpy()) + Running with eager execution. + 1.0 + + + Gradients work as exeppcted: + + >>> with tf.GradientTape() as t: + ... t.watch(x) + ... y = tf_wrapper(x) + Running with eager execution. + >>> + >>> t.gradient(y, x).numpy() + 2.0 + + ### Inplace + + You can also skip the decorator and use `tf.py_function` inplace. + This form can a useful shortcut if you don't control the function's source, + but it is harder to read. + + >>> # No decorator + >>> def log_huber(x, m): + ... if tf.abs(x) <= m: + ... return x**2 + ... else: + ... return m**2 * (1 - 2 * tf.math.log(m) + tf.math.log(x**2)) + >>> + >>> x = tf.constant(1.0) + >>> m = tf.constant(2.0) + >>> + >>> tf.py_function(func=log_huber, inp=[x, m], Tout=tf.float32).numpy() + 1.0 + + ### More info + + You can also use `tf.py_function` to debug your models at runtime + using Python tools, i.e., you can isolate portions of your code that + you want to debug, wrap them in Python functions and insert `pdb` tracepoints + or print statements as desired, and wrap those functions in + `tf.py_function`. + + For more information on eager execution, see the + [Eager guide](https://tensorflow.org/guide/eager). + + `tf.py_function` is similar in spirit to `tf.numpy_function`, but unlike + the latter, the former lets you use TensorFlow operations in the wrapped + Python function. In particular, while `tf.compat.v1.py_func` only runs on CPUs + and wraps functions that take NumPy arrays as inputs and return NumPy arrays + as outputs, `tf.py_function` can be placed on GPUs and wraps functions + that take Tensors as inputs, execute TensorFlow operations in their bodies, + and return Tensors as outputs. + + Note: We recommend to avoid using `tf.py_function` outside of prototyping + and experimentation due to the following known limitations: + + * Calling `tf.py_function` will acquire the Python Global Interpreter Lock + (GIL) that allows only one thread to run at any point in time. This will + preclude efficient parallelization and distribution of the execution of the + program. + + * The body of the function (i.e. `func`) will not be serialized in a + `GraphDef`. Therefore, you should not use this function if you need to + serialize your model and restore it in a different environment. + + * The operation must run in the same address space as the Python program + that calls `tf.py_function()`. If you are using distributed + TensorFlow, you must run a `tf.distribute.Server` in the same process as the + program that calls `tf.py_function()` and you must pin the created + operation to a device in that server (e.g. using `with tf.device():`). + + * Currently `tf.py_function` is not compatible with XLA. Calling + `tf.py_function` inside `tf.function(jit_compile=True)` will raise an + error. + + Args: + func: A Python function that accepts `inp` as arguments, and returns a value + (or list of values) whose type is described by `Tout`. Do not set `func` + when using `tf.py_function` as a decorator. + inp: Input arguments for `func`. A list whose elements are `Tensor`s or + `CompositeTensors` (such as `tf.RaggedTensor`); or a single `Tensor` or + `CompositeTensor`. Do not set `inp` when using `tf.py_function` as a + decorator. + Tout: The type(s) of the value(s) returned by `func`. One of the following. + * If `func` returns a `Tensor` (or a value that can be converted to a + Tensor): the `tf.DType` for that value. + * If `func` returns a `CompositeTensor`: The `tf.TypeSpec` for that value. + * If `func` returns `None`: the empty list (`[]`). + * If `func` returns a list of `Tensor` and `CompositeTensor` values: a + corresponding list of `tf.DType`s and `tf.TypeSpec`s for each value. + name: A name for the operation (optional). + + Returns: + * If `func` is `None` this returns a decorator that will ensure the + decorated function will always run with eager execution even if called + from a `tf.function`/`tf.Graph`. + * If used `func` is not `None` this executes `func` with eager execution + and returns the result: a `Tensor`, `CompositeTensor`, or list of + `Tensor` and `CompositeTensor`; or an empty list if `func` returns `None`. + """ + decorator = _check_args_and_maybe_make_decorator( + eager_py_func, "tf.py_function", func=func, inp=inp, Tout=Tout, name=name + ) + if decorator is not None: + return decorator + + if ops.executing_eagerly_outside_functions(): + with ops.device(context.context().host_address_space()): + return _internal_py_func( + func=func, inp=inp, Tout=Tout, use_eager_py_func=True, name=name) + + return _internal_py_func( + func=func, inp=inp, Tout=Tout, use_eager_py_func=True, name=name) + + +def py_func_common(func, inp, Tout, stateful=True, name=None): + """Wraps a python function and uses it as a TensorFlow op. + + Given a python function `func`, which takes numpy arrays as its + arguments and returns numpy arrays as its outputs, wrap this function as an + operation in a TensorFlow graph. The following snippet constructs a simple + TensorFlow graph that invokes the `np.sinh()` NumPy function as a operation + in the graph: + + ```python + def my_func(x): + # x will be a numpy array with the contents of the placeholder below + return np.sinh(x) + input = tf.compat.v1.placeholder(tf.float32) + y = tf.compat.v1.py_func(my_func, [input], tf.float32) + ``` + + **N.B.** The `tf.compat.v1.py_func()` operation has the following known + limitations: + + * The body of the function (i.e. `func`) will not be serialized in a + `GraphDef`. Therefore, you should not use this function if you need to + serialize your model and restore it in a different environment. + + * The operation must run in the same address space as the Python program + that calls `tf.compat.v1.py_func()`. If you are using distributed + TensorFlow, you + must run a `tf.distribute.Server` in the same process as the program that + calls + `tf.compat.v1.py_func()` and you must pin the created operation to a device + in that + server (e.g. using `with tf.device():`). + + Note: It produces tensors of unknown shape and rank as shape inference + does not work on arbitrary Python code. + If you need the shape, you need to set it based on statically + available information. + + E.g. + ```python + import tensorflow as tf + import numpy as np + + def make_synthetic_data(i): + return np.cast[np.uint8](i) * np.ones([20,256,256,3], + dtype=np.float32) / 10. + + def preprocess_fn(i): + ones = tf.py_function(make_synthetic_data,[i],tf.float32) + ones.set_shape(tf.TensorShape([None, None, None, None])) + ones = tf.image.resize(ones, [224,224]) + return ones + + ds = tf.data.Dataset.range(10) + ds = ds.map(preprocess_fn) + ``` + + Args: + func: A Python function, which accepts `ndarray` objects as arguments and + returns a list of `ndarray` objects (or a single `ndarray`). This function + must accept as many arguments as there are tensors in `inp`, and these + argument types will match the corresponding `tf.Tensor` objects in `inp`. + The returns `ndarray`s must match the number and types defined `Tout`. + Important Note: Input and output numpy `ndarray`s of `func` are not + guaranteed to be copies. In some cases their underlying memory will be + shared with the corresponding TensorFlow tensors. In-place modification + or storing `func` input or return values in python datastructures + without explicit (np.)copy can have non-deterministic consequences. + inp: A list of `Tensor` objects. + Tout: A list or tuple of tensorflow data types or a single tensorflow data + type if there is only one, indicating what `func` returns. + stateful: (Boolean.) If True, the function should be considered stateful. If + a function is stateless, when given the same input it will return the same + output and have no observable side effects. Optimizations such as common + subexpression elimination are only performed on stateless operations. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` or a single `Tensor` which `func` computes. + + @compatibility(TF2) + + This name was deprecated and removed in TF2, but `tf.numpy_function` is a + near-exact replacement, just drop the `stateful` argument (all + `tf.numpy_function` calls are considered stateful). It is compatible with + eager execution and `tf.function`. + + `tf.py_function` is a close but not an exact replacement, passing TensorFlow + tensors to the wrapped function instead of NumPy arrays, which provides + gradients and can take advantage of accelerators. + + Before: + + >>> def fn_using_numpy(x): + ... x[0] = 0. + ... return x + >>> tf.compat.v1.py_func(fn_using_numpy, inp=[tf.constant([1., 2.])], + ... Tout=tf.float32, stateful=False) + + + After: + + >>> tf.numpy_function(fn_using_numpy, inp=[tf.constant([1., 2.])], + ... Tout=tf.float32) + + + @end_compatibility + + """ + if context.executing_eagerly(): + result = func(*[np.array(x) for x in inp]) + result = nest.flatten(result) + + result = [x if x is None else ops.convert_to_tensor(x) for x in result] + if len(result) == 1: + # Mimic the automatic unwrapping in graph-mode py_func + result, = result + return result + + if ops.executing_eagerly_outside_functions(): + with ops.device(context.context().host_address_space()): + return _internal_py_func( + func=func, + inp=inp, + Tout=Tout, + stateful=stateful, + use_eager_py_func=False, + name=name) + + return _internal_py_func( + func=func, + inp=inp, + Tout=Tout, + stateful=stateful, + use_eager_py_func=False, + name=name) + + +@deprecation.deprecated( + date=None, + instructions="""tf.py_func is deprecated in TF V2. Instead, there are two + options available in V2. + - tf.py_function takes a python function which manipulates tf eager + tensors instead of numpy arrays. It's easy to convert a tf eager tensor to + an ndarray (just call tensor.numpy()) but having access to eager tensors + means `tf.py_function`s can use accelerators such as GPUs as well as + being differentiable using a gradient tape. + - tf.numpy_function maintains the semantics of the deprecated tf.py_func + (it is not differentiable, and manipulates numpy arrays). It drops the + stateful argument making all functions stateful. + """) +@tf_export(v1=["py_func"]) +@dispatch.add_dispatch_support +def py_func(func, inp, Tout, stateful=True, name=None): + return py_func_common(func, inp, Tout, stateful, name=name) + + +py_func.__doc__ = "%s" % py_func_common.__doc__ + + +@tf_export("numpy_function") +@dispatch.add_dispatch_support +def numpy_function(func=None, inp=None, Tout=None, stateful=True, name=None): + """Wraps a python function and uses it as a TensorFlow op. + + Given a python function `func` wrap this function as an operation in a + `tf.function`. `func` must take numpy arrays as its arguments and + return numpy arrays as its outputs. + + There are two ways to use `tf.numpy_function`. + + ### As a decorator + + When using `tf.numpy_function` as a decorator: + + * you must set `Tout` + * you may set `name` + * you must not set `func` or `inp` + + >>> @tf.numpy_function(Tout=tf.float32) + ... def my_numpy_func(x): + ... # x will be a numpy array with the contents of the input to the + ... # tf.function + ... print(f'executing eagerly, {x=}') + ... return np.sinh(x) + + The function runs eagerly: + + >>> my_numpy_func(1.0).numpy() + executing eagerly, x=1.0 + 1.17520 + + The behavior doesn't change inside a `tf.function`: + + >>> @tf.function(input_signature=[tf.TensorSpec(None, tf.float32)]) + ... def tf_function(input): + ... y = tf.numpy_function(my_numpy_func, [input], tf.float32) + ... return y + >>> tf_function(tf.constant(1.)).numpy() + executing eagerly, x=array(1.) + 1.17520 + + ### Inplace + + This form can be useful if you don't control the function's source, + but it is harder to read. + + Here is the same function with no decorator: + + >>> def my_func(x): + ... # x will be a numpy array with the contents of the input to the + ... # tf.function + ... print(f'executing eagerly, {x=}') + ... return np.sinh(x) + + To run `tf.numpy_function` inplace, pass the function, its inputs, and the + output type in a single call to `tf.numpy_function`: + + >>> tf.numpy_function(my_func, [tf.constant(1.0)], tf.float32) + executing eagerly, x=array(1.) + 1.17520 + + ### More info + + Comparison to `tf.py_function`: + `tf.py_function` and `tf.numpy_function` are very similar, except that + `tf.numpy_function` takes numpy arrays, and not `tf.Tensor`s. If you want the + function to contain `tf.Tensors`, and have any TensorFlow operations executed + in the function be differentiable, please use `tf.py_function`. + + Note: We recommend to avoid using `tf.numpy_function` outside of + prototyping and experimentation due to the following known limitations: + + * Calling `tf.numpy_function` will acquire the Python Global Interpreter Lock + (GIL) that allows only one thread to run at any point in time. This will + preclude efficient parallelization and distribution of the execution of the + program. Therefore, you are discouraged to use `tf.numpy_function` outside + of prototyping and experimentation. + + * The body of the function (i.e. `func`) will not be serialized in a + `tf.SavedModel`. Therefore, you should not use this function if you need to + serialize your model and restore it in a different environment. + + * The operation must run in the same address space as the Python program + that calls `tf.numpy_function()`. If you are using distributed + TensorFlow, you must run a `tf.distribute.Server` in the same process as the + program that calls `tf.numpy_function` you must pin the created + operation to a device in that server (e.g. using `with tf.device():`). + + * Currently `tf.numpy_function` is not compatible with XLA. Calling + `tf.numpy_function` inside `tf.function(jit_compile=True)` will raise an + error. + + * Since the function takes numpy arrays, you cannot take gradients + through a numpy_function. If you require something that is differentiable, + please consider using tf.py_function. + + Args: + func: A Python function, which accepts `numpy.ndarray` objects as arguments + and returns a list of `numpy.ndarray` objects (or a single + `numpy.ndarray`). This function must accept as many arguments as there are + tensors in `inp`, and these argument types will match the corresponding + `tf.Tensor` objects in `inp`. The returns `numpy.ndarray`s must match the + number and types defined `Tout`. Important Note: Input and output + `numpy.ndarray`s of `func` are not guaranteed to be copies. In some cases + their underlying memory will be shared with the corresponding TensorFlow + tensors. In-place modification or storing `func` input or return values in + python datastructures without explicit (np.)copy can have + non-deterministic consequences. + inp: A list of `tf.Tensor` objects. + Tout: A list or tuple of tensorflow data types or a single tensorflow data + type if there is only one, indicating what `func` returns. + stateful: (Boolean.) Setting this argument to False tells the runtime to + treat the function as stateless, which enables certain optimizations. A + function is stateless when given the same input it will return the same + output and have no side effects; its only purpose is to have a return + value. The behavior for a stateful function with the `stateful` argument + False is undefined. In particular, caution should be taken when mutating + the input arguments as this is a stateful operation. + name: (Optional) A name for the operation. + + Returns: + * If `func` is `None` this returns a decorator that will ensure the + decorated function will always run with eager execution even if called + from a `tf.function`/`tf.Graph`. + * If used `func` is not `None` this executes `func` with eager execution + and returns the result: A single or list of `tf.Tensor` which `func` + computes. + """ + decorator = _check_args_and_maybe_make_decorator( + numpy_function, + "tf.numpy_function", + func=func, + inp=inp, + Tout=Tout, + stateful=stateful, + name=name, + ) + if decorator is not None: + return decorator + + return py_func_common(func, inp, Tout, stateful=stateful, name=name) + + +def _as_dtype_or_type_spec(t): + return t if isinstance(t, type_spec.TypeSpec) else dtypes.as_dtype(t) + + +def _wrap_for_composites(func, inp, Tout): + """Wraps user inputs to support composite tensors for `py_function`. + + 1. Flattens `inp` to a list of Tensors (by flattening any composite tensors). + 2. Creates a wrapper fuction for `func` that expects flat inputs and: + - Packs the inputs into the input structure expected by `func`. + - Calls `func` with the packed inputs. + - Checks that `func`'s output matches `Tout`. + - Flattens func`'s output to a list of Tensors (flattening any composite + tensors). + + Args: + func: The function to wrap (`func` argument to `py_function`). + inp: The input arguments for func (`inp` argument to `py_function`). + Tout: The expected output types for func (`Tout` argument to `py_function). + + Returns: + A tuple `(func, inp, Tout, out_structure)`, where `func` is the wrapped + function, `inp` is the flattened inputs, `Tout` is the list of expected + dtypes for the flattened outputs, and `out_structure` is the expected + output structure (which can be used to pack the output tensors). + """ + in_structure = [ + v if isinstance(v, composite_tensor.CompositeTensor) else 1 for v in inp + ] + inp = nest.flatten_up_to(in_structure, inp, expand_composites=True) + out_structure = Tout + Tout = [ + v.dtype if isinstance(v, tensor_spec.TensorSpec) else v + for v in nest.flatten(Tout, expand_composites=True) + ] + + def wrapped_func(*flat_inp): + structured_inp = nest.pack_sequence_as( + in_structure, flat_inp, expand_composites=True) + out = func(*structured_inp) + if not out_structure: + return [] # Ignore return value if none is requested/expected. + if not isinstance(out, (list, tuple)): + out = [out] # func may return a single value instead of a list. + flat_out = [] + for elt, expected_type in zip(out, out_structure): + if (isinstance(expected_type, type_spec.TypeSpec) and + not isinstance(expected_type, tensor_spec.TensorSpec)): + if not expected_type.is_compatible_with(elt): + # pylint: disable=protected-access + raise ValueError( + f"py_function: func={func} returned {out!r}, " + f"which did not match Tout={out_structure!r}.\nIn particular, " + f"{elt!r} is not compatible with {expected_type!r}.") + flat_out.extend(nest.flatten(elt, expand_composites=True)) + else: + # Pro-actively check if the return value is a composite tensor when + # we expect a Tensor. We would catch this later (when we call + # convert_to_tensor), but checking it here lets us give a better + # error message. + if isinstance(elt, composite_tensor.CompositeTensor): + raise ValueError( + f"py_function: func={func} returned {out!r}, " + f"which did not match Tout={out_structure!r}.\nIn particular, " + f"{elt!r} is not a Tensor.") + flat_out.append(elt) + return flat_out + + return wrapped_func, inp, Tout, out_structure + + +ops.NotDifferentiable("PyFunc") +ops.NotDifferentiable("PyFuncStateless") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sdca_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sdca_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..54b24a3fc0cbb5e94bb43680d581e9d80a14afbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sdca_ops.py @@ -0,0 +1,29 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed unde_sdca_opsr the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A Dual Coordinate Ascent optimizer library for training fast linear models. +""" + +# pylint: disable=g-bad-name +from tensorflow.python.framework import ops + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_sdca_ops import * +# pylint: enable=wildcard-import + +ops.NotDifferentiable("SdcaFprint") +ops.NotDifferentiable("SdcaOptimizer") +ops.NotDifferentiable("SdcaOptimizerV2") +ops.NotDifferentiable("SdcaShrinkL1") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/session_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/session_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef5794fb1a67c77c4818b9c189cbf1735b95f49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/session_ops.py @@ -0,0 +1,299 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Tensor Handle Operations.""" + +# pylint: disable=g-bad-name +import numpy as np + +from tensorflow.core.framework import resource_handle_pb2 +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + + +def encode_resource_handle(resource_handle): + """Encode a ResourceHandle proto as custom numpy struct type.""" + return np.asarray(bytearray(resource_handle.SerializeToString()), + dtype=dtypes.np_resource) + + +class TensorHandle: + """Represents a handle for a live tensor in a session.""" + + def __init__(self, handle, dtype, session): + """Constructs a new tensor handle. + + A tensor handle for a persistent tensor is a python string + that has the form of "tensor_name;unique_id;device_name". + + Args: + handle: A tensor handle. + dtype: The data type of the tensor represented by `handle`. + session: The session in which the tensor is produced. + """ + self._handle = compat.as_str_any(handle) + self._resource_handle = None + self._dtype = dtype + self._session = session + self._auto_gc_enabled = True + + def __del__(self): + if self._auto_gc_enabled: + self._session._register_dead_handle(self.handle) + + def __str__(self): + return self._handle + + def _get_resource_handle(self): + """The ResourceHandle representation of this handle.""" + if not self._resource_handle: + self._resource_handle = resource_handle_pb2.ResourceHandleProto() + self._resource_handle.device = self._handle.split(";")[-1] + self._resource_handle.container = (pywrap_tf_session.TENSOR_HANDLE_KEY) + self._resource_handle.name = self._handle + return self._resource_handle + + def to_numpy_array(self): + """Convert a TensorHandle object to a feedable numpy value. + + Returns: + A numpy array of a custom struct type that can be used as a feed value + to run(). + """ + return encode_resource_handle(self._get_resource_handle()) + + @property + def handle(self): + """The string representation of this handle.""" + return self._handle + + def eval(self): + """Return the value of the tensor represented by this handle.""" + if not self._auto_gc_enabled: + raise TypeError("Persistent tensor %s may have already been deleted." + % self.handle) + holder, reader = _get_handle_reader(self._session.graph, self._handle, + self._dtype) + return self._session.run(reader, feed_dict={holder: self._handle}) + + def delete(self): + """Force the deletion of this persistent tensor.""" + if not self._auto_gc_enabled: + raise TypeError("Persistent tensor %s may have already been deleted." + % self.handle) + self._auto_gc_enabled = False + holder, deleter = _get_handle_deleter(self._session.graph, 0, self._handle) + self._session.run(deleter, feed_dict={holder: self.handle}) + + def get_raw_handle(self): + """Return the raw handle of the tensor. + + Note that the method disables the automatic garbage collection of this + persistent tensor. The caller is now responsible for managing the life + time of the tensor. + """ + self._auto_gc_enabled = False + return self._handle + + @staticmethod + def _get_device_name(handle): + """The device name encoded in the handle.""" + handle_str = compat.as_str_any(handle) + return pydev.canonical_name(handle_str.split(";")[-1]) + + @staticmethod + def _get_reader_key(handle): + """The graph key for reader.""" + handle_parts = str(handle).split(";") + return handle_parts[0] + ";" + handle_parts[-1] + + @staticmethod + def _get_mover_key(feeder, handle): + """The graph key for mover.""" + return feeder.op.name + ";" + TensorHandle._get_reader_key(handle) + + +@tf_export(v1=["get_session_handle"]) +def get_session_handle(data, name=None): + """Return the handle of `data`. + + This is EXPERIMENTAL and subject to change. + + Keep `data` "in-place" in the runtime and create a handle that can be + used to retrieve `data` in a subsequent run(). + + Combined with `get_session_tensor`, we can keep a tensor produced in + one run call in place, and use it as the input in a future run call. + + Args: + data: A tensor to be stored in the session. + name: Optional name prefix for the return tensor. + + Returns: + A scalar string tensor representing a unique handle for `data`. + + Raises: + TypeError: if `data` is not a Tensor. + + Example: + + ```python + c = tf.multiply(a, b) + h = tf.compat.v1.get_session_handle(c) + h = sess.run(h) + + p, a = tf.compat.v1.get_session_tensor(h.handle, tf.float32) + b = tf.multiply(a, 10) + c = sess.run(b, feed_dict={p: h.handle}) + ``` + + """ + if not isinstance(data, tensor_lib.Tensor): + raise TypeError("`data` must be of type Tensor.") + + # Colocate this operation with data. + with ops.colocate_with(data): + return gen_data_flow_ops.get_session_handle(data, name=name) + + +@tf_export(v1=["get_session_tensor"]) +def get_session_tensor(handle, dtype, name=None): + """Get the tensor of type `dtype` by feeding a tensor handle. + + This is EXPERIMENTAL and subject to change. + + Get the value of the tensor from a tensor handle. The tensor + is produced in a previous run() and stored in the state of the + session. + + Args: + handle: The string representation of a persistent tensor handle. + dtype: The type of the output tensor. + name: Optional name prefix for the return tensor. + + Returns: + A pair of tensors. The first is a placeholder for feeding a + tensor handle and the second is the tensor in the session state + keyed by the tensor handle. + + Example: + + ```python + c = tf.multiply(a, b) + h = tf.compat.v1.get_session_handle(c) + h = sess.run(h) + + p, a = tf.compat.v1.get_session_tensor(h.handle, tf.float32) + b = tf.multiply(a, 10) + c = sess.run(b, feed_dict={p: h.handle}) + ``` + + """ + handle_device = TensorHandle._get_device_name(handle) + with ops.device(handle_device): + holder = array_ops.placeholder(dtypes.string) + _register_handle_feeder(holder.graph, holder, dtype) + tensor = gen_data_flow_ops.get_session_tensor(holder, dtype, name=name) + return (holder, tensor) + + +@tf_export(v1=["delete_session_tensor"]) +def delete_session_tensor(handle, name=None): + """Delete the tensor for the given tensor handle. + + This is EXPERIMENTAL and subject to change. + + Delete the tensor of a given tensor handle. The tensor is produced + in a previous run() and stored in the state of the session. + + Args: + handle: The string representation of a persistent tensor handle. + name: Optional name prefix for the return tensor. + + Returns: + A pair of graph elements. The first is a placeholder for feeding a + tensor handle and the second is a deletion operation. + """ + handle_device = TensorHandle._get_device_name(handle) + with ops.device(handle_device): + holder = array_ops.placeholder(dtypes.string) + deleter = gen_data_flow_ops.delete_session_tensor(holder, name=name) + return (holder, deleter) + + +def _register_handle_feeder(graph, feeder, dtype): + graph._handle_feeders[feeder.op.name] = dtype + + +def _get_handle_feeder(graph, feeder): + return graph._handle_feeders.get(feeder.op.name) + + +def _get_handle_reader(graph, handle, dtype): + """Return a read subgraph for this handle.""" + graph_key = TensorHandle._get_reader_key(handle) + result = graph._handle_readers.get(graph_key) + if result is None: + # Create reader if we haven't done it. + handle_device = TensorHandle._get_device_name(handle) + with graph.as_default(), graph.device(handle_device): + holder = array_ops.placeholder(dtypes.string) + _register_handle_feeder(holder.graph, holder, dtype) + reader = gen_data_flow_ops.get_session_tensor(holder, dtype) + result = (holder, reader) + graph._handle_readers[graph_key] = result + return result + + +def _get_handle_mover(graph, feeder, handle): + """Return a move subgraph for this pair of feeder and handle.""" + dtype = _get_handle_feeder(graph, feeder) + if dtype is None: + return None + handle_device = TensorHandle._get_device_name(handle) + if feeder.op.device == handle_device: + return None + # Now we know we have to move the tensor. + graph_key = TensorHandle._get_mover_key(feeder, handle) + result = graph._handle_movers.get(graph_key) + if result is None: + # Create mover if we haven't done it. + holder, reader = _get_handle_reader(graph, handle, dtype) + with graph.as_default(), graph.device(feeder.op.device): + mover = gen_data_flow_ops.get_session_handle(reader) + result = (holder, mover) + graph._handle_movers[graph_key] = result + return result + + +def _get_handle_deleter(graph, deleter_key, handle): + """Return a deletion subgraph for this handle.""" + result = graph._handle_deleters.get(deleter_key) + if result is None: + # Create deleter if we haven't done it. + handle_device = TensorHandle._get_device_name(handle) + with graph.as_default(), graph.device(handle_device): + holder = array_ops.placeholder(dtypes.string) + deleter = gen_data_flow_ops.delete_session_tensor(holder) + result = (holder, deleter) + graph._handle_deleters[deleter_key] = result + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..6c22dafc21d746496a8e238193583625c09e65de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets.py @@ -0,0 +1,23 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tensorflow set operations. + +API docstring: tensorflow.sets +""" + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.sets_impl import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..1f495afa70cd377fe38736606846ebf15d28f003 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sets_impl.py @@ -0,0 +1,365 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of tf.sets.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import gen_set_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + +_VALID_DTYPES = frozenset([ + dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8, + dtypes.uint16, dtypes.string +]) + + +@tf_export("sets.size", v1=["sets.size", "sets.set_size"]) +@dispatch.add_dispatch_support +def set_size(a, validate_indices=True): + """Compute number of unique elements along last dimension of `a`. + + Args: + a: `SparseTensor`, with indices sorted in row-major order. + validate_indices: Whether to validate the order and range of sparse indices + in `a`. Note that setting this to `false` allows for undefined behavior + when calling this function with invalid indices. + + Returns: + `int32` `Tensor` of set sizes. For `a` ranked `n`, this is a `Tensor` with + rank `n-1`, and the same 1st `n-1` dimensions as `a`. Each value is the + number of unique elements in the corresponding `[0...n-1]` dimension of `a`. + + Raises: + TypeError: If `a` is an invalid types. + """ + a = sparse_tensor.convert_to_tensor_or_sparse_tensor(a, name="a") + if not isinstance(a, sparse_tensor.SparseTensor): + raise TypeError("Expected `SparseTensor`, got %s." % a) + if a.values.dtype.base_dtype not in _VALID_DTYPES: + raise TypeError( + f"Invalid dtype `{a.values.dtype}` not in supported dtypes: " + f"`{_VALID_DTYPES}`.") + # pylint: disable=protected-access + return gen_set_ops.set_size(a.indices, a.values, a.dense_shape, + validate_indices) + + +ops.NotDifferentiable("SetSize") + +ops.NotDifferentiable("DenseToDenseSetOperation") +ops.NotDifferentiable("DenseToSparseSetOperation") +ops.NotDifferentiable("SparseToSparseSetOperation") + + +def _convert_to_tensors_or_sparse_tensors(a, b): + """Convert to tensor types, and flip order if necessary. + + Args: + a: `Tensor` or `SparseTensor` of the same type as `b`. + b: `Tensor` or `SparseTensor` of the same type as `a`. + + Returns: + Tuple of `(a, b, flipped)`, where `a` and `b` have been converted to + `Tensor` or `SparseTensor`, and `flipped` indicates whether the order has + been flipped to make it dense,sparse instead of sparse,dense (since the set + ops do not support the latter). + """ + a = sparse_tensor.convert_to_tensor_or_sparse_tensor(a, name="a") + if a.dtype.base_dtype not in _VALID_DTYPES: + raise TypeError( + f"'a' has invalid dtype `{a.dtype}` not in supported dtypes: " + f"`{_VALID_DTYPES}`.") + b = sparse_tensor.convert_to_tensor_or_sparse_tensor(b, name="b") + if b.dtype.base_dtype != a.dtype.base_dtype: + raise TypeError("Types don't match, %s vs %s." % (a.dtype, b.dtype)) + if (isinstance(a, sparse_tensor.SparseTensor) and + not isinstance(b, sparse_tensor.SparseTensor)): + return b, a, True + return a, b, False + + +def _set_operation(a, b, set_operation, validate_indices=True): + """Compute set operation of elements in last dimension of `a` and `b`. + + All but the last dimension of `a` and `b` must match. + + Args: + a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices + must be sorted in row-major order. + b: `Tensor` or `SparseTensor` of the same type as `a`. Must be + `SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be sorted + in row-major order. + set_operation: String indicating set operation. See + SetOperationOp::SetOperationFromContext for valid values. + validate_indices: Whether to validate the order and range of sparse indices + in `a` and `b`. + + Returns: + A `SparseTensor` with the same rank as `a` and `b`, and all but the last + dimension the same. Elements along the last dimension contain the results + of the set operation. + + Raises: + TypeError: If inputs are invalid types. + ValueError: If `a` is sparse and `b` is dense. + """ + if isinstance(a, sparse_tensor.SparseTensor): + if isinstance(b, sparse_tensor.SparseTensor): + indices, values, shape = gen_set_ops.sparse_to_sparse_set_operation( + a.indices, a.values, a.dense_shape, b.indices, b.values, + b.dense_shape, set_operation, validate_indices) + else: + raise ValueError("Sparse,Dense is not supported, but Dense,Sparse is. " + "Please flip the order of your inputs.") + elif isinstance(b, sparse_tensor.SparseTensor): + indices, values, shape = gen_set_ops.dense_to_sparse_set_operation( + a, b.indices, b.values, b.dense_shape, set_operation, validate_indices) + else: + indices, values, shape = gen_set_ops.dense_to_dense_set_operation( + a, b, set_operation, validate_indices) + return sparse_tensor.SparseTensor(indices, values, shape) + + +@tf_export( + "sets.intersection", v1=["sets.intersection", "sets.set_intersection"]) +@dispatch.add_dispatch_support +def set_intersection(a, b, validate_indices=True): + """Compute set intersection of elements in last dimension of `a` and `b`. + + All but the last dimension of `a` and `b` must match. + + Example: + + ```python + import tensorflow as tf + import collections + + # Represent the following array of sets as a sparse tensor: + # a = np.array([[{1, 2}, {3}], [{4}, {5, 6}]]) + a = collections.OrderedDict([ + ((0, 0, 0), 1), + ((0, 0, 1), 2), + ((0, 1, 0), 3), + ((1, 0, 0), 4), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ]) + a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()), + dense_shape=[2,2,2]) + + # b = np.array([[{1}, {}], [{4}, {5, 6, 7, 8}]]) + b = collections.OrderedDict([ + ((0, 0, 0), 1), + ((1, 0, 0), 4), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ((1, 1, 2), 7), + ((1, 1, 3), 8), + ]) + b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()), + dense_shape=[2, 2, 4]) + + # `tf.sets.intersection` is applied to each aligned pair of sets. + tf.sets.intersection(a, b) + + # The result will be equivalent to either of: + # + # np.array([[{1}, {}], [{4}, {5, 6}]]) + # + # collections.OrderedDict([ + # ((0, 0, 0), 1), + # ((1, 0, 0), 4), + # ((1, 1, 0), 5), + # ((1, 1, 1), 6), + # ]) + ``` + + Args: + a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices + must be sorted in row-major order. + b: `Tensor` or `SparseTensor` of the same type as `a`. If sparse, indices + must be sorted in row-major order. + validate_indices: Whether to validate the order and range of sparse indices + in `a` and `b`. + + Returns: + A `SparseTensor` whose shape is the same rank as `a` and `b`, and all but + the last dimension the same. Elements along the last dimension contain the + intersections. + """ + a, b, _ = _convert_to_tensors_or_sparse_tensors(a, b) + return _set_operation(a, b, "intersection", validate_indices) + + +@tf_export("sets.difference", v1=["sets.difference", "sets.set_difference"]) +@dispatch.add_dispatch_support +def set_difference(a, b, aminusb=True, validate_indices=True): + """Compute set difference of elements in last dimension of `a` and `b`. + + All but the last dimension of `a` and `b` must match. + + Example: + + ```python + import tensorflow as tf + import collections + + # Represent the following array of sets as a sparse tensor: + # a = np.array([[{1, 2}, {3}], [{4}, {5, 6}]]) + a = collections.OrderedDict([ + ((0, 0, 0), 1), + ((0, 0, 1), 2), + ((0, 1, 0), 3), + ((1, 0, 0), 4), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ]) + a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()), + dense_shape=[2, 2, 2]) + + # np.array([[{1, 3}, {2}], [{4, 5}, {5, 6, 7, 8}]]) + b = collections.OrderedDict([ + ((0, 0, 0), 1), + ((0, 0, 1), 3), + ((0, 1, 0), 2), + ((1, 0, 0), 4), + ((1, 0, 1), 5), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ((1, 1, 2), 7), + ((1, 1, 3), 8), + ]) + b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()), + dense_shape=[2, 2, 4]) + + # `set_difference` is applied to each aligned pair of sets. + tf.sets.difference(a, b) + + # The result will be equivalent to either of: + # + # np.array([[{2}, {3}], [{}, {}]]) + # + # collections.OrderedDict([ + # ((0, 0, 0), 2), + # ((0, 1, 0), 3), + # ]) + ``` + + Args: + a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices + must be sorted in row-major order. + b: `Tensor` or `SparseTensor` of the same type as `a`. If sparse, indices + must be sorted in row-major order. + aminusb: Whether to subtract `b` from `a`, vs vice versa. + validate_indices: Whether to validate the order and range of sparse indices + in `a` and `b`. + + Returns: + A `SparseTensor` whose shape is the same rank as `a` and `b`, and all but + the last dimension the same. Elements along the last dimension contain the + differences. + + Raises: + TypeError: If inputs are invalid types, or if `a` and `b` have + different types. + ValueError: If `a` is sparse and `b` is dense. + errors_impl.InvalidArgumentError: If the shapes of `a` and `b` do not + match in any dimension other than the last dimension. + """ + a, b, flipped = _convert_to_tensors_or_sparse_tensors(a, b) + if flipped: + aminusb = not aminusb + return _set_operation(a, b, "a-b" if aminusb else "b-a", validate_indices) + + +@tf_export("sets.union", v1=["sets.union", "sets.set_union"]) +@dispatch.add_dispatch_support +def set_union(a, b, validate_indices=True): + """Compute set union of elements in last dimension of `a` and `b`. + + All but the last dimension of `a` and `b` must match. + + Example: + + ```python + import tensorflow as tf + import collections + + # [[{1, 2}, {3}], [{4}, {5, 6}]] + a = collections.OrderedDict([ + ((0, 0, 0), 1), + ((0, 0, 1), 2), + ((0, 1, 0), 3), + ((1, 0, 0), 4), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ]) + a = tf.sparse.SparseTensor(list(a.keys()), list(a.values()), + dense_shape=[2, 2, 2]) + + # [[{1, 3}, {2}], [{4, 5}, {5, 6, 7, 8}]] + b = collections.OrderedDict([ + ((0, 0, 0), 1), + ((0, 0, 1), 3), + ((0, 1, 0), 2), + ((1, 0, 0), 4), + ((1, 0, 1), 5), + ((1, 1, 0), 5), + ((1, 1, 1), 6), + ((1, 1, 2), 7), + ((1, 1, 3), 8), + ]) + b = tf.sparse.SparseTensor(list(b.keys()), list(b.values()), + dense_shape=[2, 2, 4]) + + # `set_union` is applied to each aligned pair of sets. + tf.sets.union(a, b) + + # The result will be a equivalent to either of: + # + # np.array([[{1, 2, 3}, {2, 3}], [{4, 5}, {5, 6, 7, 8}]]) + # + # collections.OrderedDict([ + # ((0, 0, 0), 1), + # ((0, 0, 1), 2), + # ((0, 0, 2), 3), + # ((0, 1, 0), 2), + # ((0, 1, 1), 3), + # ((1, 0, 0), 4), + # ((1, 0, 1), 5), + # ((1, 1, 0), 5), + # ((1, 1, 1), 6), + # ((1, 1, 2), 7), + # ((1, 1, 3), 8), + # ]) + ``` + + Args: + a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices + must be sorted in row-major order. + b: `Tensor` or `SparseTensor` of the same type as `a`. If sparse, indices + must be sorted in row-major order. + validate_indices: Whether to validate the order and range of sparse indices + in `a` and `b`. + + Returns: + A `SparseTensor` whose shape is the same rank as `a` and `b`, and all but + the last dimension the same. Elements along the last dimension contain the + unions. + """ + a, b, _ = _convert_to_tensors_or_sparse_tensors(a, b) + return _set_operation(a, b, "union", validate_indices) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/shape_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/shape_util.py new file mode 100644 index 0000000000000000000000000000000000000000..bac8d8b7fa71850fb05ba391908bebf6ed24a71e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/shape_util.py @@ -0,0 +1,74 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tensor shape utilities.""" +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util + + +def shape_tensor(shape): # pylint: disable=invalid-name + """Convert to an int32 or int64 tensor, defaulting to int32 if empty.""" + dtype = None + if isinstance(shape, (tuple, list)): + if not shape: + dtype = dtypes.int32 + else: + # If there are Dimension objects in the shape, unwrap them. This can be a + # problem if v1 and v2 TensorShape objects get mixed up in partial + # conversions, leading to shapes such as (1, 2, Dimension(5)), which are + # not convertible to Tensors because of mixed content. + shape = tuple(map(tensor_shape.dimension_value, shape)) + return ops.convert_to_tensor(shape, dtype=dtype, name="shape") + + +# DO NOT USE: For testing only. +_ENABLE_MAYBE_SET_STATIC_SHAPE = True + + +def maybe_set_static_shape(tensor, shape): # pylint: disable=invalid-name + """Sets the shape of `tensor` to the `shape`'s constant value, if inferrable. + + This is a temporary workaround to fix shape inference across functional op + boundaries. E.g. + + ```python + shape = tf.constant([3]) + @tf.function + def f(): + u = tf.random_uniform(shape) + return u + ``` + + If we were to rely solely on C++ shape inference, the shape of `u` inside + `f` would be unknown because C++ shape inference is not aware of the outer + graph and all it sees is a Placeholder node when backtracing the captured + tensor for `shape`. `maybe_set_static_shape` computes the static shape value + of `shape` by traversing the `FuncGraph` boundaries and sets the correct + shape. + + A longer term solution would be to fix C++ shape inference. + + Args: + tensor: A tensor. + shape: A shape tensor. + """ + if (_ENABLE_MAYBE_SET_STATIC_SHAPE and not context.executing_eagerly() and + ops.get_default_graph().building_function and + not tensor.shape.is_fully_defined() and tensor_util.is_tensor(shape)): + shape = shape_tensor(shape) + const_shape = tensor_util.constant_value_as_shape(shape) + tensor.set_shape(const_shape) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..983351a7d159872a8c83619467ddacfffffa8d78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Signal processing operations. + +See the [tf.signal](https://tensorflow.org/api_guides/python/contrib.signal) +guide. + +@@frame +@@hamming_window +@@hann_window +@@inverse_stft +@@inverse_stft_window_fn +@@mfccs_from_log_mel_spectrograms +@@linear_to_mel_weight_matrix +@@overlap_and_add +@@stft + +[hamming]: https://en.wikipedia.org/wiki/Window_function#Hamming_window +[hann]: https://en.wikipedia.org/wiki/Window_function#Hann_window +[mel]: https://en.wikipedia.org/wiki/Mel_scale +[mfcc]: https://en.wikipedia.org/wiki/Mel-frequency_cepstrum +[stft]: https://en.wikipedia.org/wiki/Short-time_Fourier_transform + +API docstring: tensorflow.signal +""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/dct_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/dct_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a47080b1edb77d3e7d0fc1949617aebe895a70e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/dct_ops.py @@ -0,0 +1,256 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Discrete Cosine Transform ops.""" +import math as _math + +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops as _array_ops +from tensorflow.python.ops import math_ops as _math_ops +from tensorflow.python.ops.signal import fft_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def _validate_dct_arguments(input_tensor, dct_type, n, axis, norm): + """Checks that DCT/IDCT arguments are compatible and well formed.""" + if axis != -1: + raise NotImplementedError("axis must be -1. Got: %s" % axis) + if n is not None and n < 1: + raise ValueError("n should be a positive integer or None") + if dct_type not in (1, 2, 3, 4): + raise ValueError("Types I, II, III and IV (I)DCT are supported.") + if dct_type == 1: + if norm == "ortho": + raise ValueError("Normalization is not supported for the Type-I DCT.") + if input_tensor.shape[-1] is not None and input_tensor.shape[-1] < 2: + raise ValueError( + "Type-I DCT requires the dimension to be greater than one.") + + if norm not in (None, "ortho"): + raise ValueError( + "Unknown normalization. Expected None or 'ortho', got: %s" % norm) + + +# TODO(rjryan): Implement `axis` parameter. +@tf_export("signal.dct", v1=["signal.dct", "spectral.dct"]) +@dispatch.add_dispatch_support +def dct(input, type=2, n=None, axis=-1, norm=None, name=None): # pylint: disable=redefined-builtin + """Computes the 1D [Discrete Cosine Transform (DCT)][dct] of `input`. + + Types I, II, III and IV are supported. + Type I is implemented using a length `2N` padded `tf.signal.rfft`. + Type II is implemented using a length `2N` padded `tf.signal.rfft`, as + described here: [Type 2 DCT using 2N FFT padded (Makhoul)] + (https://dsp.stackexchange.com/a/10606). + Type III is a fairly straightforward inverse of Type II + (i.e. using a length `2N` padded `tf.signal.irfft`). + Type IV is calculated through 2N length DCT2 of padded signal and + picking the odd indices. + + @compatibility(scipy) + Equivalent to [scipy.fftpack.dct] + (https://docs.scipy.org/doc/scipy-1.4.0/reference/generated/scipy.fftpack.dct.html) + for Type-I, Type-II, Type-III and Type-IV DCT. + @end_compatibility + + Args: + input: A `[..., samples]` `float32`/`float64` `Tensor` containing the + signals to take the DCT of. + type: The DCT type to perform. Must be 1, 2, 3 or 4. + n: The length of the transform. If length is less than sequence length, + only the first n elements of the sequence are considered for the DCT. + If n is greater than the sequence length, zeros are padded and then + the DCT is computed as usual. + axis: For future expansion. The axis to compute the DCT along. Must be `-1`. + norm: The normalization to apply. `None` for no normalization or `'ortho'` + for orthonormal normalization. + name: An optional name for the operation. + + Returns: + A `[..., samples]` `float32`/`float64` `Tensor` containing the DCT of + `input`. + + Raises: + ValueError: If `type` is not `1`, `2`, `3` or `4`, `axis` is + not `-1`, `n` is not `None` or greater than 0, + or `norm` is not `None` or `'ortho'`. + ValueError: If `type` is `1` and `norm` is `ortho`. + + [dct]: https://en.wikipedia.org/wiki/Discrete_cosine_transform + """ + _validate_dct_arguments(input, type, n, axis, norm) + return _dct_internal(input, type, n, axis, norm, name) + + +def _dct_internal(input, type=2, n=None, axis=-1, norm=None, name=None): # pylint: disable=redefined-builtin + """Computes the 1D Discrete Cosine Transform (DCT) of `input`. + + This internal version of `dct` does not perform any validation and accepts a + dynamic value for `n` in the form of a rank 0 tensor. + + Args: + input: A `[..., samples]` `float32`/`float64` `Tensor` containing the + signals to take the DCT of. + type: The DCT type to perform. Must be 1, 2, 3 or 4. + n: The length of the transform. If length is less than sequence length, + only the first n elements of the sequence are considered for the DCT. + If n is greater than the sequence length, zeros are padded and then + the DCT is computed as usual. Can be an int or rank 0 tensor. + axis: For future expansion. The axis to compute the DCT along. Must be `-1`. + norm: The normalization to apply. `None` for no normalization or `'ortho'` + for orthonormal normalization. + name: An optional name for the operation. + + Returns: + A `[..., samples]` `float32`/`float64` `Tensor` containing the DCT of + `input`. + """ + with _ops.name_scope(name, "dct", [input]): + input = _ops.convert_to_tensor(input) + zero = _ops.convert_to_tensor(0.0, dtype=input.dtype) + + seq_len = ( + tensor_shape.dimension_value(input.shape[-1]) or + _array_ops.shape(input)[-1]) + if n is not None: + + def truncate_input(): + return input[..., 0:n] + + def pad_input(): + rank = len(input.shape) + padding = [[0, 0] for _ in range(rank)] + padding[rank - 1][1] = n - seq_len + padding = _ops.convert_to_tensor(padding, dtype=_dtypes.int32) + return _array_ops.pad(input, paddings=padding) + + input = smart_cond.smart_cond(n <= seq_len, truncate_input, pad_input) + + axis_dim = (tensor_shape.dimension_value(input.shape[-1]) + or _array_ops.shape(input)[-1]) + axis_dim_float = _math_ops.cast(axis_dim, input.dtype) + + if type == 1: + dct1_input = _array_ops.concat([input, input[..., -2:0:-1]], axis=-1) + dct1 = _math_ops.real(fft_ops.rfft(dct1_input)) + return dct1 + + if type == 2: + scale = 2.0 * _math_ops.exp( + _math_ops.complex( + zero, -_math_ops.range(axis_dim_float) * _math.pi * 0.5 / + axis_dim_float)) + + # TODO(rjryan): Benchmark performance and memory usage of the various + # approaches to computing a DCT via the RFFT. + dct2 = _math_ops.real( + fft_ops.rfft( + input, fft_length=[2 * axis_dim])[..., :axis_dim] * scale) + + if norm == "ortho": + n1 = 0.5 * _math_ops.rsqrt(axis_dim_float) + n2 = n1 * _math.sqrt(2.0) + # Use tf.pad to make a vector of [n1, n2, n2, n2, ...]. + weights = _array_ops.pad( + _array_ops.expand_dims(n1, 0), [[0, axis_dim - 1]], + constant_values=n2) + dct2 *= weights + + return dct2 + + elif type == 3: + if norm == "ortho": + n1 = _math_ops.sqrt(axis_dim_float) + n2 = n1 * _math.sqrt(0.5) + # Use tf.pad to make a vector of [n1, n2, n2, n2, ...]. + weights = _array_ops.pad( + _array_ops.expand_dims(n1, 0), [[0, axis_dim - 1]], + constant_values=n2) + input *= weights + else: + input *= axis_dim_float + scale = 2.0 * _math_ops.exp( + _math_ops.complex( + zero, + _math_ops.range(axis_dim_float) * _math.pi * 0.5 / + axis_dim_float)) + dct3 = _math_ops.real( + fft_ops.irfft( + scale * _math_ops.complex(input, zero), + fft_length=[2 * axis_dim]))[..., :axis_dim] + + return dct3 + + elif type == 4: + # DCT-2 of 2N length zero-padded signal, unnormalized. + dct2 = _dct_internal(input, type=2, n=2*axis_dim, axis=axis, norm=None) + # Get odd indices of DCT-2 of zero padded 2N signal to obtain + # DCT-4 of the original N length signal. + dct4 = dct2[..., 1::2] + if norm == "ortho": + dct4 *= _math.sqrt(0.5) * _math_ops.rsqrt(axis_dim_float) + + return dct4 + + +# TODO(rjryan): Implement `n` and `axis` parameters. +@tf_export("signal.idct", v1=["signal.idct", "spectral.idct"]) +@dispatch.add_dispatch_support +def idct(input, type=2, n=None, axis=-1, norm=None, name=None): # pylint: disable=redefined-builtin + """Computes the 1D [Inverse Discrete Cosine Transform (DCT)][idct] of `input`. + + Currently Types I, II, III, IV are supported. Type III is the inverse of + Type II, and vice versa. + + Note that you must re-normalize by 1/(2n) to obtain an inverse if `norm` is + not `'ortho'`. That is: + `signal == idct(dct(signal)) * 0.5 / signal.shape[-1]`. + When `norm='ortho'`, we have: + `signal == idct(dct(signal, norm='ortho'), norm='ortho')`. + + @compatibility(scipy) + Equivalent to [scipy.fftpack.idct] + (https://docs.scipy.org/doc/scipy-1.4.0/reference/generated/scipy.fftpack.idct.html) + for Type-I, Type-II, Type-III and Type-IV DCT. + @end_compatibility + + Args: + input: A `[..., samples]` `float32`/`float64` `Tensor` containing the + signals to take the DCT of. + type: The IDCT type to perform. Must be 1, 2, 3 or 4. + n: For future expansion. The length of the transform. Must be `None`. + axis: For future expansion. The axis to compute the DCT along. Must be `-1`. + norm: The normalization to apply. `None` for no normalization or `'ortho'` + for orthonormal normalization. + name: An optional name for the operation. + + Returns: + A `[..., samples]` `float32`/`float64` `Tensor` containing the IDCT of + `input`. + + Raises: + ValueError: If `type` is not `1`, `2` or `3`, `n` is not `None, `axis` is + not `-1`, or `norm` is not `None` or `'ortho'`. + + [idct]: + https://en.wikipedia.org/wiki/Discrete_cosine_transform#Inverse_transforms + """ + _validate_dct_arguments(input, type, n, axis, norm) + inverse_type = {1: 1, 2: 3, 3: 2, 4: 4}[type] + return _dct_internal( + input, type=inverse_type, n=n, axis=axis, norm=norm, name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/fft_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/fft_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7a292dc672a5b49df7d9f44dfe63414c2234813b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/fft_ops.py @@ -0,0 +1,696 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Fast-Fourier Transform ops.""" +import re + +import numpy as np + +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import tensor_util as _tensor_util +from tensorflow.python.ops import array_ops as _array_ops +from tensorflow.python.ops import array_ops_stack as _array_ops_stack +from tensorflow.python.ops import gen_spectral_ops +from tensorflow.python.ops import manip_ops +from tensorflow.python.ops import math_ops as _math_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def _infer_fft_length_for_fftn(input_tensor): + return _array_ops.shape(input_tensor)[-len(input_tensor.shape) :] + + +def _infer_fft_length_for_irfftn(input_tensor): + fft_shape = input_tensor.get_shape()[-len(input_tensor.shape) :] + fft_length = fft_shape.as_list() + fft_length[-1] = max(0, 2 * (fft_length[-1] - 1)) + return _ops.convert_to_tensor(fft_length, _dtypes.int32) + + +def _infer_axes_for_fftn(input_tensor): + return _ops.convert_to_tensor( + np.arange(len(input_tensor.shape)), _dtypes.int32 + ) + + +def _process_empty_axes(input_tensor, axes): + if axes is None: + axes = _infer_axes_for_fftn(input_tensor) + else: + axes = _ops.convert_to_tensor(axes, _dtypes.int32) + return axes + + +def _infer_fft_length_for_rfft(input_tensor, fft_rank): + """Infers the `fft_length` argument for a `rank` RFFT from `input_tensor`.""" + # A TensorShape for the inner fft_rank dimensions. + fft_shape = input_tensor.get_shape()[-fft_rank:] + + # If any dim is unknown, fall back to tensor-based math. + if not fft_shape.is_fully_defined(): + return _array_ops.shape(input_tensor)[-fft_rank:] + + # Otherwise, return a constant. + return _ops.convert_to_tensor(fft_shape.as_list(), _dtypes.int32) + + +def _infer_fft_length_for_irfft(input_tensor, fft_rank): + """Infers the `fft_length` argument for a `rank` IRFFT from `input_tensor`.""" + # A TensorShape for the inner fft_rank dimensions. + fft_shape = input_tensor.get_shape()[-fft_rank:] + + # If any dim is unknown, fall back to tensor-based math. + if not fft_shape.is_fully_defined(): + fft_length = _array_ops_stack.unstack( + _array_ops.shape(input_tensor)[-fft_rank:]) + fft_length[-1] = _math_ops.maximum(0, 2 * (fft_length[-1] - 1)) + return _array_ops_stack.stack(fft_length) + + # Otherwise, return a constant. + fft_length = fft_shape.as_list() + if fft_length: + fft_length[-1] = max(0, 2 * (fft_length[-1] - 1)) + return _ops.convert_to_tensor(fft_length, _dtypes.int32) + + +def _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length, is_reverse=False): + """Pads `input_tensor` to `fft_length` on its inner-most `fft_rank` dims.""" + fft_shape = _tensor_util.constant_value_as_shape(fft_length) + + # Edge case: skip padding empty tensors. + if (input_tensor.shape.ndims is not None and + any(dim.value == 0 for dim in input_tensor.shape.dims)): + return input_tensor + + # If we know the shapes ahead of time, we can either skip or pre-compute the + # appropriate paddings. Otherwise, fall back to computing paddings in + # TensorFlow. + if fft_shape.is_fully_defined() and input_tensor.shape.ndims is not None: + # Slice the last FFT-rank dimensions from input_tensor's shape. + input_fft_shape = input_tensor.shape[-fft_shape.ndims:] # pylint: disable=invalid-unary-operand-type + + if input_fft_shape.is_fully_defined(): + # In reverse, we only pad the inner-most dimension to fft_length / 2 + 1. + if is_reverse: + fft_shape = fft_shape[:-1].concatenate( + fft_shape.dims[-1].value // 2 + 1) + + paddings = [[0, max(fft_dim.value - input_dim.value, 0)] + for fft_dim, input_dim in zip( + fft_shape.dims, input_fft_shape.dims)] + if any(pad > 0 for _, pad in paddings): + outer_paddings = [[0, 0]] * max((input_tensor.shape.ndims - + fft_shape.ndims), 0) + return _array_ops.pad(input_tensor, outer_paddings + paddings) + return input_tensor + + # If we can't determine the paddings ahead of time, then we have to pad. If + # the paddings end up as zero, tf.pad has a special-case that does no work. + input_rank = _array_ops.rank(input_tensor) + input_fft_shape = _array_ops.shape(input_tensor)[-fft_rank:] + outer_dims = _math_ops.maximum(0, input_rank - fft_rank) + outer_paddings = _array_ops.zeros([outer_dims], fft_length.dtype) + # In reverse, we only pad the inner-most dimension to fft_length / 2 + 1. + if is_reverse: + fft_length = _array_ops.concat([fft_length[:-1], + fft_length[-1:] // 2 + 1], 0) + fft_paddings = _math_ops.maximum(0, fft_length - input_fft_shape) + paddings = _array_ops.concat([outer_paddings, fft_paddings], 0) + paddings = _array_ops_stack.stack( + [_array_ops.zeros_like(paddings), paddings], axis=1) + return _array_ops.pad(input_tensor, paddings) + + +def _rfft_wrapper(fft_fn, fft_rank, default_name): + """Wrapper around gen_spectral_ops.rfft* that infers fft_length argument.""" + + def _rfft(input_tensor, fft_length=None, name=None): + """Wrapper around gen_spectral_ops.rfft* that infers fft_length argument.""" + with _ops.name_scope(name, default_name, + [input_tensor, fft_length]) as name: + input_tensor = _ops.convert_to_tensor(input_tensor, + preferred_dtype=_dtypes.float32) + if input_tensor.dtype not in (_dtypes.float32, _dtypes.float64): + raise ValueError( + "RFFT requires tf.float32 or tf.float64 inputs, got: %s" % + input_tensor) + real_dtype = input_tensor.dtype + if real_dtype == _dtypes.float32: + complex_dtype = _dtypes.complex64 + else: + assert real_dtype == _dtypes.float64 + complex_dtype = _dtypes.complex128 + input_tensor.shape.with_rank_at_least(fft_rank) + if fft_length is None: + fft_length = _infer_fft_length_for_rfft(input_tensor, fft_rank) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length) + + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + return fft_fn(input_tensor, fft_length, Tcomplex=complex_dtype, name=name) + _rfft.__doc__ = re.sub(" Tcomplex.*?\n", "", fft_fn.__doc__) + return _rfft + + +def _irfft_wrapper(ifft_fn, fft_rank, default_name): + """Wrapper around gen_spectral_ops.irfft* that infers fft_length argument.""" + + def _irfft(input_tensor, fft_length=None, name=None): + """Wrapper irfft* that infers fft_length argument.""" + with _ops.name_scope(name, default_name, + [input_tensor, fft_length]) as name: + input_tensor = _ops.convert_to_tensor(input_tensor, + preferred_dtype=_dtypes.complex64) + input_tensor.shape.with_rank_at_least(fft_rank) + if input_tensor.dtype not in (_dtypes.complex64, _dtypes.complex128): + raise ValueError( + "IRFFT requires tf.complex64 or tf.complex128 inputs, got: %s" % + input_tensor) + complex_dtype = input_tensor.dtype + real_dtype = complex_dtype.real_dtype + if fft_length is None: + fft_length = _infer_fft_length_for_irfft(input_tensor, fft_rank) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length, + is_reverse=True) + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + return ifft_fn(input_tensor, fft_length, Treal=real_dtype, name=name) + + _irfft.__doc__ = re.sub("`input`", "`input_tensor`", + re.sub(" Treal.*?\n", "", ifft_fn.__doc__)) + return _irfft + + +def _fftn_wrapper(fft_n, default_name): + """Wrapper around gen_spectral_ops.fftn.""" + + def _fftn(input_tensor, fft_length=None, axes=None, norm=None, name=None): + """Wrapper around gen_spectral_ops.*fft that infers fft_length and axes arguments.""" + with _ops.name_scope( + name, default_name, [input_tensor, fft_length, axes] + ) as name: + axes = _process_empty_axes(input_tensor, axes) + fft_rank = axes.shape[0] + input_tensor = _ops.convert_to_tensor( + input_tensor, preferred_dtype=_dtypes.complex64 + ) + input_tensor.shape.with_rank_at_least(fft_rank) + if fft_length is None: + fft_length = _infer_fft_length_for_fftn(input_tensor) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length) + + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + if norm is None: + norm = "backward" + n = 1 + if norm != "backward": + for fft_length_i in fft_length: + n *= fft_length_i + if norm == "forward": + input_tensor /= n + elif norm == "ortho": + input_tensor /= np.sqrt(n) # should be sqrt(N) + return fft_n(input_tensor, fft_length, axes, name=name) + + _fftn.__doc__ = re.sub(r" Tcomplex.*?\n", "", fft_n.__doc__) + return _fftn + + +def _ifftn_wrapper(ifft_n, default_name): + """Wrapper around gen_spectral_ops.ifftn.""" + + def _ifftn(input_tensor, fft_length=None, axes=None, norm=None, name=None): + """Wrapper around gen_spectral_ops.*fft that infers fft_length and axes arguments.""" + with _ops.name_scope( + name, default_name, [input_tensor, fft_length, axes] + ) as name: + axes = _process_empty_axes(input_tensor, axes) + fft_rank = axes.shape[0] + input_tensor = _ops.convert_to_tensor( + input_tensor, preferred_dtype=_dtypes.complex64 + ) + input_tensor.shape.with_rank_at_least(fft_rank) + if fft_length is None: + fft_length = _infer_fft_length_for_fftn(input_tensor) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length) + + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + if norm is None: + norm = "backward" + n = 1 + if norm != "backward": + for fft_length_i in fft_length: + n *= fft_length_i + if norm == "forward": + input_tensor *= n + elif norm == "ortho": + input_tensor *= np.sqrt(n) # should be sqrt(N) + return ifft_n(input_tensor, fft_length, axes, name=name) + + _ifftn.__doc__ = re.sub(r" Tcomplex.*?\n", "", ifft_n.__doc__) + return _ifftn + + +def _rfftn_wrapper(rfft_n, default_name): + """Wrapper around gen_spectral_ops.rfftn.""" + + def _rfftn(input_tensor, fft_length=None, axes=None, norm=None, name=None): + """Wrapper around gen_spectral_ops.*fft that infers fft_length and axes arguments.""" + with _ops.name_scope( + name, default_name, [input_tensor, fft_length, axes] + ) as name: + axes = _process_empty_axes(input_tensor, axes) + fft_rank = axes.shape[0] + input_tensor = _ops.convert_to_tensor( + input_tensor, preferred_dtype=_dtypes.float32 + ) + if input_tensor.dtype not in (_dtypes.float32, _dtypes.float64): + raise ValueError( + "RFFT requires tf.float32 or tf.float64 inputs, got: %s" + % input_tensor + ) + real_dtype = input_tensor.dtype + if real_dtype == _dtypes.float32: + complex_dtype = _dtypes.complex64 + else: + assert real_dtype == _dtypes.float64 + complex_dtype = _dtypes.complex128 + input_tensor.shape.with_rank_at_least(fft_rank) + if fft_length is None: + fft_length = _infer_fft_length_for_fftn(input_tensor) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft(input_tensor, fft_rank, fft_length) + + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + if norm is None: + norm = "backward" + n = 1 + if norm != "backward": + for fft_length_i in fft_length: + n *= fft_length_i + if norm == "forward": + input_tensor /= n + elif norm == "ortho": + input_tensor /= np.sqrt(n) # should be sqrt(N) + return rfft_n( + input_tensor, + fft_length, + axes, + Tcomplex=complex_dtype, + name=name, + ) + + _rfftn.__doc__ = re.sub(r" Tcomplex.*?\n", "", rfft_n.__doc__) + return _rfftn + + +def _irfftn_wrapper(irfft_n, default_name): + """Wrapper around gen_spectral_ops.irfftn.""" + + def _irfftn(input_tensor, fft_length=None, axes=None, norm=None, name=None): + """Wrapper irfft* that infers fft_length argument.""" + with _ops.name_scope( + name, default_name, [input_tensor, fft_length] + ) as name: + axes = _process_empty_axes(input_tensor, axes) + fft_rank = axes.shape[0] + input_tensor = _ops.convert_to_tensor( + input_tensor, preferred_dtype=_dtypes.complex64 + ) + input_tensor.shape.with_rank_at_least(fft_rank) + if input_tensor.dtype not in (_dtypes.complex64, _dtypes.complex128): + raise ValueError( + "IRFFT requires tf.complex64 or tf.complex128 inputs, got: %s" + % input_tensor + ) + complex_dtype = input_tensor.dtype + real_dtype = complex_dtype.real_dtype + if fft_length is None: + fft_length = _infer_fft_length_for_irfftn(input_tensor) + else: + fft_length = _ops.convert_to_tensor(fft_length, _dtypes.int32) + input_tensor = _maybe_pad_for_rfft( + input_tensor, fft_rank, fft_length, is_reverse=True + ) + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + + if norm is None: + norm = "backward" + n = 1 + if norm != "backward": + for fft_length_i in fft_length: + n *= fft_length_i + if norm == "forward": + input_tensor *= n + elif norm == "ortho": + input_tensor *= np.sqrt(n) # should be sqrt(N) + return irfft_n( + input_tensor, fft_length, axes, Treal=real_dtype, name=name + ) + + _irfftn.__doc__ = re.sub( + "`input`", + "`input_tensor`", + re.sub(r" Treal.*?\n", "", irfft_n.__doc__), + ) + return _irfftn + + +# FFT/IFFT 1/2/3D are exported via +# third_party/tensorflow/core/api_def/python_api/ +fft = gen_spectral_ops.fft +ifft = gen_spectral_ops.ifft +fft2d = gen_spectral_ops.fft2d +ifft2d = gen_spectral_ops.ifft2d +fft3d = gen_spectral_ops.fft3d +ifft3d = gen_spectral_ops.ifft3d +fftnd = _fftn_wrapper(gen_spectral_ops.fftnd, "fftnd") +tf_export("signal.fftnd")( + dispatch.add_dispatch_support(fftnd) +) +ifftnd = _ifftn_wrapper(gen_spectral_ops.ifftnd, "ifftnd") +tf_export("signal.ifftnd")( + dispatch.add_dispatch_support(ifftnd) +) +rfft = _rfft_wrapper(gen_spectral_ops.rfft, 1, "rfft") +tf_export("signal.rfft", v1=["signal.rfft", "spectral.rfft"])( + dispatch.add_dispatch_support(rfft)) +irfft = _irfft_wrapper(gen_spectral_ops.irfft, 1, "irfft") +tf_export("signal.irfft", v1=["signal.irfft", "spectral.irfft"])( + dispatch.add_dispatch_support(irfft)) +rfft2d = _rfft_wrapper(gen_spectral_ops.rfft2d, 2, "rfft2d") +tf_export("signal.rfft2d", v1=["signal.rfft2d", "spectral.rfft2d"])( + dispatch.add_dispatch_support(rfft2d)) +irfft2d = _irfft_wrapper(gen_spectral_ops.irfft2d, 2, "irfft2d") +tf_export("signal.irfft2d", v1=["signal.irfft2d", "spectral.irfft2d"])( + dispatch.add_dispatch_support(irfft2d)) +rfft3d = _rfft_wrapper(gen_spectral_ops.rfft3d, 3, "rfft3d") +tf_export("signal.rfft3d", v1=["signal.rfft3d", "spectral.rfft3d"])( + dispatch.add_dispatch_support(rfft3d)) +irfft3d = _irfft_wrapper(gen_spectral_ops.irfft3d, 3, "irfft3d") +tf_export("signal.irfft3d", v1=["signal.irfft3d", "spectral.irfft3d"])( + dispatch.add_dispatch_support(irfft3d)) +rfftnd = _rfftn_wrapper(gen_spectral_ops.rfftnd, "rfftnd") +tf_export("signal.rfftnd")( + dispatch.add_dispatch_support(rfftnd) +) +irfftnd = _irfftn_wrapper(gen_spectral_ops.irfftnd, "irfftnd") +tf_export("signal.irfftnd")( + dispatch.add_dispatch_support(irfftnd) +) + + +def _fft_size_for_grad(grad, rank): + return _math_ops.reduce_prod(_array_ops.shape(grad)[-rank:]) + + +@_ops.RegisterGradient("FFT") +def _fft_grad(_, grad): + size = _math_ops.cast(_fft_size_for_grad(grad, 1), grad.dtype) + return ifft(grad) * size + + +@_ops.RegisterGradient("IFFT") +def _ifft_grad(_, grad): + rsize = _math_ops.cast( + 1. / _math_ops.cast(_fft_size_for_grad(grad, 1), grad.dtype.real_dtype), + grad.dtype) + return fft(grad) * rsize + + +@_ops.RegisterGradient("FFT2D") +def _fft2d_grad(_, grad): + size = _math_ops.cast(_fft_size_for_grad(grad, 2), grad.dtype) + return ifft2d(grad) * size + + +@_ops.RegisterGradient("IFFT2D") +def _ifft2d_grad(_, grad): + rsize = _math_ops.cast( + 1. / _math_ops.cast(_fft_size_for_grad(grad, 2), grad.dtype.real_dtype), + grad.dtype) + return fft2d(grad) * rsize + + +@_ops.RegisterGradient("FFT3D") +def _fft3d_grad(_, grad): + size = _math_ops.cast(_fft_size_for_grad(grad, 3), grad.dtype) + return ifft3d(grad) * size + + +@_ops.RegisterGradient("IFFT3D") +def _ifft3d_grad(_, grad): + rsize = _math_ops.cast( + 1. / _math_ops.cast(_fft_size_for_grad(grad, 3), grad.dtype.real_dtype), + grad.dtype) + return fft3d(grad) * rsize + + +def _rfft_grad_helper(rank, irfft_fn): + """Returns a gradient function for an RFFT of the provided rank.""" + # Can't happen because we don't register a gradient for RFFT3D. + assert rank in (1, 2), "Gradient for RFFT3D is not implemented." + + def _grad(op, grad): + """A gradient function for RFFT with the provided `rank` and `irfft_fn`.""" + fft_length = op.inputs[1] + complex_dtype = grad.dtype + real_dtype = complex_dtype.real_dtype + input_shape = _array_ops.shape(op.inputs[0]) + is_even = _math_ops.cast(1 - (fft_length[-1] % 2), complex_dtype) + + def _tile_for_broadcasting(matrix, t): + expanded = _array_ops.reshape( + matrix, + _array_ops.concat([ + _array_ops.ones([_array_ops.rank(t) - 2], _dtypes.int32), + _array_ops.shape(matrix) + ], 0)) + return _array_ops.tile( + expanded, _array_ops.concat([_array_ops.shape(t)[:-2], [1, 1]], 0)) + + def _mask_matrix(length): + """Computes t_n = exp(sqrt(-1) * pi * n^2 / line_len).""" + # TODO(rjryan): Speed up computation of twiddle factors using the + # following recurrence relation and cache them across invocations of RFFT. + # + # t_n = exp(sqrt(-1) * pi * n^2 / line_len) + # for n = 0, 1,..., line_len-1. + # For n > 2, use t_n = t_{n-1}^2 / t_{n-2} * t_1^2 + a = _array_ops.tile( + _array_ops.expand_dims(_math_ops.range(length), 0), (length, 1)) + b = _array_ops.transpose(a, [1, 0]) + return _math_ops.exp( + -2j * np.pi * _math_ops.cast(a * b, complex_dtype) / + _math_ops.cast(length, complex_dtype)) + + def _ymask(length): + """A sequence of [1+0j, -1+0j, 1+0j, -1+0j, ...] with length `length`.""" + return _math_ops.cast(1 - 2 * (_math_ops.range(length) % 2), + complex_dtype) + + y0 = grad[..., 0:1] + if rank == 1: + ym = grad[..., -1:] + extra_terms = y0 + is_even * ym * _ymask(input_shape[-1]) + elif rank == 2: + # Create a mask matrix for y0 and ym. + base_mask = _mask_matrix(input_shape[-2]) + + # Tile base_mask to match y0 in shape so that we can batch-matmul the + # inner 2 dimensions. + tiled_mask = _tile_for_broadcasting(base_mask, y0) + + y0_term = _math_ops.matmul(tiled_mask, _math_ops.conj(y0)) + extra_terms = y0_term + + ym = grad[..., -1:] + ym_term = _math_ops.matmul(tiled_mask, _math_ops.conj(ym)) + + inner_dim = input_shape[-1] + ym_term = _array_ops.tile( + ym_term, + _array_ops.concat([ + _array_ops.ones([_array_ops.rank(grad) - 1], _dtypes.int32), + [inner_dim] + ], 0)) * _ymask(inner_dim) + + extra_terms += is_even * ym_term + + # The gradient of RFFT is the IRFFT of the incoming gradient times a scaling + # factor, plus some additional terms to make up for the components dropped + # due to Hermitian symmetry. + input_size = _math_ops.cast( + _fft_size_for_grad(op.inputs[0], rank), real_dtype) + the_irfft = irfft_fn(grad, fft_length) + return 0.5 * (the_irfft * input_size + _math_ops.real(extra_terms)), None + + return _grad + + +def _irfft_grad_helper(rank, rfft_fn): + """Returns a gradient function for an IRFFT of the provided rank.""" + # Can't happen because we don't register a gradient for IRFFT3D. + assert rank in (1, 2), "Gradient for IRFFT3D is not implemented." + + def _grad(op, grad): + """A gradient function for IRFFT with the provided `rank` and `rfft_fn`.""" + # Generate a simple mask like [1.0, 2.0, ..., 2.0, 1.0] for even-length FFTs + # and [1.0, 2.0, ..., 2.0] for odd-length FFTs. To reduce extra ops in the + # graph we special-case the situation where the FFT length and last + # dimension of the input are known at graph construction time. + fft_length = op.inputs[1] + fft_length_static = _tensor_util.constant_value(fft_length) + if fft_length_static is not None: + fft_length = fft_length_static + real_dtype = grad.dtype + if real_dtype == _dtypes.float32: + complex_dtype = _dtypes.complex64 + elif real_dtype == _dtypes.float64: + complex_dtype = _dtypes.complex128 + is_odd = _math_ops.mod(fft_length[-1], 2) + input_last_dimension = _array_ops.shape(op.inputs[0])[-1] + mask = _array_ops.concat( + [[1.0], 2.0 * _array_ops.ones( + [input_last_dimension - 2 + is_odd], real_dtype), + _array_ops.ones([1 - is_odd], real_dtype)], 0) + + rsize = _math_ops.reciprocal(_math_ops.cast( + _fft_size_for_grad(grad, rank), real_dtype)) + + # The gradient of IRFFT is the RFFT of the incoming gradient times a scaling + # factor and a mask. The mask scales the gradient for the Hermitian + # symmetric components of the RFFT by a factor of two, since these + # components are de-duplicated in the RFFT. + the_rfft = rfft_fn(grad, fft_length) + return the_rfft * _math_ops.cast(rsize * mask, complex_dtype), None + + return _grad + + +@tf_export("signal.fftshift") +@dispatch.add_dispatch_support +def fftshift(x, axes=None, name=None): + """Shift the zero-frequency component to the center of the spectrum. + + This function swaps half-spaces for all axes listed (defaults to all). + Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. + + @compatibility(numpy) + Equivalent to numpy.fft.fftshift. + https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftshift.html + @end_compatibility + + For example: + + ```python + x = tf.signal.fftshift([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.]) + x.numpy() # array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) + ``` + + Args: + x: `Tensor`, input tensor. + axes: `int` or shape `tuple`, optional Axes over which to shift. Default is + None, which shifts all axes. + name: An optional name for the operation. + + Returns: + A `Tensor`, The shifted tensor. + """ + with _ops.name_scope(name, "fftshift") as name: + x = _ops.convert_to_tensor(x) + if axes is None: + axes = tuple(range(x.shape.ndims)) + shift = _array_ops.shape(x) // 2 + elif isinstance(axes, int): + shift = _array_ops.shape(x)[axes] // 2 + else: + rank = _array_ops.rank(x) + # allows negative axis + axes = _array_ops.where(_math_ops.less(axes, 0), axes + rank, axes) + shift = _array_ops.gather(_array_ops.shape(x), axes) // 2 + + return manip_ops.roll(x, shift, axes, name) + + +@tf_export("signal.ifftshift") +@dispatch.add_dispatch_support +def ifftshift(x, axes=None, name=None): + """The inverse of fftshift. + + Although identical for even-length x, + the functions differ by one sample for odd-length x. + + @compatibility(numpy) + Equivalent to numpy.fft.ifftshift. + https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.ifftshift.html + @end_compatibility + + For example: + + ```python + x = tf.signal.ifftshift([[ 0., 1., 2.],[ 3., 4., -4.],[-3., -2., -1.]]) + x.numpy() # array([[ 4., -4., 3.],[-2., -1., -3.],[ 1., 2., 0.]]) + ``` + + Args: + x: `Tensor`, input tensor. + axes: `int` or shape `tuple` Axes over which to calculate. Defaults to None, + which shifts all axes. + name: An optional name for the operation. + + Returns: + A `Tensor`, The shifted tensor. + """ + with _ops.name_scope(name, "ifftshift") as name: + x = _ops.convert_to_tensor(x) + if axes is None: + axes = tuple(range(x.shape.ndims)) + shift = -(_array_ops.shape(x) // 2) + elif isinstance(axes, int): + shift = -(_array_ops.shape(x)[axes] // 2) + else: + rank = _array_ops.rank(x) + # allows negative axis + axes = _array_ops.where(_math_ops.less(axes, 0), axes + rank, axes) + shift = -(_array_ops.gather(_array_ops.shape(x), axes) // 2) + + return manip_ops.roll(x, shift, axes, name) + + +_ops.RegisterGradient("RFFT")(_rfft_grad_helper(1, irfft)) +_ops.RegisterGradient("IRFFT")(_irfft_grad_helper(1, rfft)) +_ops.RegisterGradient("RFFT2D")(_rfft_grad_helper(2, irfft2d)) +_ops.RegisterGradient("IRFFT2D")(_irfft_grad_helper(2, rfft2d)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mel_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mel_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..47d85859ddd9b4b2266af5a3c0700f55be8c8dad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mel_ops.py @@ -0,0 +1,216 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""mel conversion ops.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.signal import shape_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +# mel spectrum constants. +_MEL_BREAK_FREQUENCY_HERTZ = 700.0 +_MEL_HIGH_FREQUENCY_Q = 1127.0 + + +def _mel_to_hertz(mel_values, name=None): + """Converts frequencies in `mel_values` from the mel scale to linear scale. + + Args: + mel_values: A `Tensor` of frequencies in the mel scale. + name: An optional name for the operation. + + Returns: + A `Tensor` of the same shape and type as `mel_values` containing linear + scale frequencies in Hertz. + """ + with ops.name_scope(name, 'mel_to_hertz', [mel_values]): + mel_values = ops.convert_to_tensor(mel_values) + return _MEL_BREAK_FREQUENCY_HERTZ * ( + math_ops.exp(mel_values / _MEL_HIGH_FREQUENCY_Q) - 1.0 + ) + + +def _hertz_to_mel(frequencies_hertz, name=None): + """Converts frequencies in `frequencies_hertz` in Hertz to the mel scale. + + Args: + frequencies_hertz: A `Tensor` of frequencies in Hertz. + name: An optional name for the operation. + + Returns: + A `Tensor` of the same shape and type of `frequencies_hertz` containing + frequencies in the mel scale. + """ + with ops.name_scope(name, 'hertz_to_mel', [frequencies_hertz]): + frequencies_hertz = ops.convert_to_tensor(frequencies_hertz) + return _MEL_HIGH_FREQUENCY_Q * math_ops.log( + 1.0 + (frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ)) + + +def _validate_arguments(num_mel_bins, sample_rate, + lower_edge_hertz, upper_edge_hertz, dtype): + """Checks the inputs to linear_to_mel_weight_matrix.""" + if num_mel_bins <= 0: + raise ValueError('num_mel_bins must be positive. Got: %s' % num_mel_bins) + if lower_edge_hertz < 0.0: + raise ValueError('lower_edge_hertz must be non-negative. Got: %s' % + lower_edge_hertz) + if lower_edge_hertz >= upper_edge_hertz: + raise ValueError('lower_edge_hertz %.1f >= upper_edge_hertz %.1f' % + (lower_edge_hertz, upper_edge_hertz)) + if not isinstance(sample_rate, tensor.Tensor): + if sample_rate <= 0.0: + raise ValueError('sample_rate must be positive. Got: %s' % sample_rate) + if upper_edge_hertz > sample_rate / 2: + raise ValueError('upper_edge_hertz must not be larger than the Nyquist ' + 'frequency (sample_rate / 2). Got %s for sample_rate: %s' + % (upper_edge_hertz, sample_rate)) + if not dtype.is_floating: + raise ValueError('dtype must be a floating point type. Got: %s' % dtype) + + +@tf_export('signal.linear_to_mel_weight_matrix') +@dispatch.add_dispatch_support +def linear_to_mel_weight_matrix(num_mel_bins=20, + num_spectrogram_bins=129, + sample_rate=8000, + lower_edge_hertz=125.0, + upper_edge_hertz=3800.0, + dtype=dtypes.float32, + name=None): + r"""Returns a matrix to warp linear scale spectrograms to the [mel scale][mel]. + + Returns a weight matrix that can be used to re-weight a `Tensor` containing + `num_spectrogram_bins` linearly sampled frequency information from + `[0, sample_rate / 2]` into `num_mel_bins` frequency information from + `[lower_edge_hertz, upper_edge_hertz]` on the [mel scale][mel]. + + This function follows the [Hidden Markov Model Toolkit + (HTK)](http://htk.eng.cam.ac.uk/) convention, defining the mel scale in + terms of a frequency in hertz according to the following formula: + + $$\textrm{mel}(f) = 2595 * \textrm{log}_{10}(1 + \frac{f}{700})$$ + + In the returned matrix, all the triangles (filterbanks) have a peak value + of 1.0. + + For example, the returned matrix `A` can be used to right-multiply a + spectrogram `S` of shape `[frames, num_spectrogram_bins]` of linear + scale spectrum values (e.g. STFT magnitudes) to generate a "mel spectrogram" + `M` of shape `[frames, num_mel_bins]`. + + # `S` has shape [frames, num_spectrogram_bins] + # `M` has shape [frames, num_mel_bins] + M = tf.matmul(S, A) + + The matrix can be used with `tf.tensordot` to convert an arbitrary rank + `Tensor` of linear-scale spectral bins into the mel scale. + + # S has shape [..., num_spectrogram_bins]. + # M has shape [..., num_mel_bins]. + M = tf.tensordot(S, A, 1) + + Args: + num_mel_bins: Python int. How many bands in the resulting mel spectrum. + num_spectrogram_bins: An integer `Tensor`. How many bins there are in the + source spectrogram data, which is understood to be `fft_size // 2 + 1`, + i.e. the spectrogram only contains the nonredundant FFT bins. + sample_rate: An integer or float `Tensor`. Samples per second of the input + signal used to create the spectrogram. Used to figure out the frequencies + corresponding to each spectrogram bin, which dictates how they are mapped + into the mel scale. + lower_edge_hertz: Python float. Lower bound on the frequencies to be + included in the mel spectrum. This corresponds to the lower edge of the + lowest triangular band. + upper_edge_hertz: Python float. The desired top edge of the highest + frequency band. + dtype: The `DType` of the result matrix. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[num_spectrogram_bins, num_mel_bins]`. + + Raises: + ValueError: If `num_mel_bins`/`num_spectrogram_bins`/`sample_rate` are not + positive, `lower_edge_hertz` is negative, frequency edges are incorrectly + ordered, `upper_edge_hertz` is larger than the Nyquist frequency. + + [mel]: https://en.wikipedia.org/wiki/Mel_scale + """ + with ops.name_scope(name, 'linear_to_mel_weight_matrix') as name: + # Convert Tensor `sample_rate` to float, if possible. + if isinstance(sample_rate, tensor.Tensor): + maybe_const_val = tensor_util.constant_value(sample_rate) + if maybe_const_val is not None: + sample_rate = maybe_const_val + + # Note: As num_spectrogram_bins is passed to `math_ops.linspace` + # and the validation is already done in linspace (both in shape function + # and in kernel), there is no need to validate num_spectrogram_bins here. + _validate_arguments(num_mel_bins, sample_rate, + lower_edge_hertz, upper_edge_hertz, dtype) + + # This function can be constant folded by graph optimization since there are + # no Tensor inputs. + sample_rate = math_ops.cast( + sample_rate, dtype, name='sample_rate') + lower_edge_hertz = ops.convert_to_tensor( + lower_edge_hertz, dtype, name='lower_edge_hertz') + upper_edge_hertz = ops.convert_to_tensor( + upper_edge_hertz, dtype, name='upper_edge_hertz') + zero = ops.convert_to_tensor(0.0, dtype) + + # HTK excludes the spectrogram DC bin. + bands_to_zero = 1 + nyquist_hertz = sample_rate / 2.0 + linear_frequencies = math_ops.linspace( + zero, nyquist_hertz, num_spectrogram_bins)[bands_to_zero:] + spectrogram_bins_mel = array_ops.expand_dims( + _hertz_to_mel(linear_frequencies), 1) + + # Compute num_mel_bins triples of (lower_edge, center, upper_edge). The + # center of each band is the lower and upper edge of the adjacent bands. + # Accordingly, we divide [lower_edge_hertz, upper_edge_hertz] into + # num_mel_bins + 2 pieces. + band_edges_mel = shape_ops.frame( + math_ops.linspace(_hertz_to_mel(lower_edge_hertz), + _hertz_to_mel(upper_edge_hertz), + num_mel_bins + 2), frame_length=3, frame_step=1) + + # Split the triples up and reshape them into [1, num_mel_bins] tensors. + lower_edge_mel, center_mel, upper_edge_mel = tuple(array_ops.reshape( + t, [1, num_mel_bins]) for t in array_ops.split( + band_edges_mel, 3, axis=1)) + + # Calculate lower and upper slopes for every spectrogram bin. + # Line segments are linear in the mel domain, not Hertz. + lower_slopes = (spectrogram_bins_mel - lower_edge_mel) / ( + center_mel - lower_edge_mel) + upper_slopes = (upper_edge_mel - spectrogram_bins_mel) / ( + upper_edge_mel - center_mel) + + # Intersect the line segments with each other and zero. + mel_weights_matrix = math_ops.maximum( + zero, math_ops.minimum(lower_slopes, upper_slopes)) + + # Re-add the zeroed lower bins we sliced out above. + return array_ops.pad( + mel_weights_matrix, [[bands_to_zero, 0], [0, 0]], name=name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mfcc_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mfcc_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec83b674aef258b6be2e147f7656d137e637bd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/mfcc_ops.py @@ -0,0 +1,107 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Mel-Frequency Cepstral Coefficients (MFCCs) ops.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.signal import dct_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('signal.mfccs_from_log_mel_spectrograms') +@dispatch.add_dispatch_support +def mfccs_from_log_mel_spectrograms(log_mel_spectrograms, name=None): + """Computes [MFCCs][mfcc] of `log_mel_spectrograms`. + + Implemented with GPU-compatible ops and supports gradients. + + [Mel-Frequency Cepstral Coefficient (MFCC)][mfcc] calculation consists of + taking the DCT-II of a log-magnitude mel-scale spectrogram. [HTK][htk]'s MFCCs + use a particular scaling of the DCT-II which is almost orthogonal + normalization. We follow this convention. + + All `num_mel_bins` MFCCs are returned and it is up to the caller to select + a subset of the MFCCs based on their application. For example, it is typical + to only use the first few for speech recognition, as this results in + an approximately pitch-invariant representation of the signal. + + For example: + + ```python + batch_size, num_samples, sample_rate = 32, 32000, 16000.0 + # A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1]. + pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) + + # A 1024-point STFT with frames of 64 ms and 75% overlap. + stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, + fft_length=1024) + spectrograms = tf.abs(stfts) + + # Warp the linear scale spectrograms into the mel-scale. + num_spectrogram_bins = stfts.shape[-1].value + lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80 + linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix( + num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, + upper_edge_hertz) + mel_spectrograms = tf.tensordot( + spectrograms, linear_to_mel_weight_matrix, 1) + mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate( + linear_to_mel_weight_matrix.shape[-1:])) + + # Compute a stabilized log to get log-magnitude mel-scale spectrograms. + log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6) + + # Compute MFCCs from log_mel_spectrograms and take the first 13. + mfccs = tf.signal.mfccs_from_log_mel_spectrograms( + log_mel_spectrograms)[..., :13] + ``` + + Args: + log_mel_spectrograms: A `[..., num_mel_bins]` `float32`/`float64` `Tensor` + of log-magnitude mel-scale spectrograms. + name: An optional name for the operation. + Returns: + A `[..., num_mel_bins]` `float32`/`float64` `Tensor` of the MFCCs of + `log_mel_spectrograms`. + + Raises: + ValueError: If `num_mel_bins` is not positive. + + [mfcc]: https://en.wikipedia.org/wiki/Mel-frequency_cepstrum + [htk]: https://en.wikipedia.org/wiki/HTK_(software) + """ + with ops.name_scope(name, 'mfccs_from_log_mel_spectrograms', + [log_mel_spectrograms]): + # Compute the DCT-II of the resulting log-magnitude mel-scale spectrogram. + # The DCT used in HTK scales every basis vector by sqrt(2/N), which is the + # scaling required for an "orthogonal" DCT-II *except* in the 0th bin, where + # the true orthogonal DCT (as implemented by scipy) scales by sqrt(1/N). For + # this reason, we don't apply orthogonal normalization and scale the DCT by + # `0.5 * sqrt(2/N)` manually. + log_mel_spectrograms = ops.convert_to_tensor(log_mel_spectrograms) + if (log_mel_spectrograms.shape.ndims and + log_mel_spectrograms.shape.dims[-1].value is not None): + num_mel_bins = log_mel_spectrograms.shape.dims[-1].value + if num_mel_bins == 0: + raise ValueError('num_mel_bins must be positive. Got: %s' % + log_mel_spectrograms) + else: + num_mel_bins = array_ops.shape(log_mel_spectrograms)[-1] + + dct2 = dct_ops.dct(log_mel_spectrograms, type=2) + return dct2 * math_ops.rsqrt( + math_ops.cast(num_mel_bins, dct2.dtype) * 2.0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/reconstruction_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/reconstruction_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..fdef247b2a78a649cdb689818d4bbf1204761007 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/reconstruction_ops.py @@ -0,0 +1,163 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Signal reconstruction via overlapped addition of frames.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("signal.overlap_and_add") +@dispatch.add_dispatch_support +def overlap_and_add(signal, frame_step, name=None): + """Reconstructs a signal from a framed representation. + + Adds potentially overlapping frames of a signal with shape + `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`. + The resulting tensor has shape `[..., output_size]` where + + output_size = (frames - 1) * frame_step + frame_length + + Args: + signal: A [..., frames, frame_length] `Tensor`. All dimensions may be + unknown, and rank must be at least 2. + frame_step: An integer or scalar `Tensor` denoting overlap offsets. Must be + less than or equal to `frame_length`. + name: An optional name for the operation. + + Returns: + A `Tensor` with shape `[..., output_size]` containing the overlap-added + frames of `signal`'s inner-most two dimensions. + + Raises: + ValueError: If `signal`'s rank is less than 2, or `frame_step` is not a + scalar integer. + """ + with ops.name_scope(name, "overlap_and_add", [signal, frame_step]): + signal = ops.convert_to_tensor(signal, name="signal") + signal.shape.with_rank_at_least(2) + frame_step = ops.convert_to_tensor(frame_step, name="frame_step") + frame_step.shape.assert_has_rank(0) + if not frame_step.dtype.is_integer: + raise ValueError("frame_step must be an integer. Got %s" % + frame_step.dtype) + frame_step_static = tensor_util.constant_value(frame_step) + frame_step_is_static = frame_step_static is not None + frame_step = frame_step_static if frame_step_is_static else frame_step + + signal_shape = array_ops.shape(signal) + signal_shape_static = tensor_util.constant_value(signal_shape) + if signal_shape_static is not None: + signal_shape = signal_shape_static + + # All dimensions that are not part of the overlap-and-add. Can be empty for + # rank 2 inputs. + outer_dimensions = signal_shape[:-2] + outer_rank = array_ops.size(outer_dimensions) + outer_rank_static = tensor_util.constant_value(outer_rank) + if outer_rank_static is not None: + outer_rank = outer_rank_static + + def full_shape(inner_shape): + return array_ops.concat([outer_dimensions, inner_shape], 0) + + frame_length = signal_shape[-1] + frames = signal_shape[-2] + + # Compute output length. + output_length = frame_length + frame_step * (frames - 1) + + # If frame_length is equal to frame_step, there's no overlap so just + # reshape the tensor. + if (frame_step_is_static and signal.shape.dims is not None and + frame_step == signal.shape.dims[-1].value): + output_shape = full_shape([output_length]) + return array_ops.reshape(signal, output_shape, name="fast_path") + + # The following code is documented using this example: + # + # frame_step = 2 + # signal.shape = (3, 5) + # a b c d e + # f g h i j + # k l m n o + + # Compute the number of segments, per frame. + segments = -(-frame_length // frame_step) # Divide and round up. + + # Pad the frame_length dimension to a multiple of the frame step. + # Pad the frames dimension by `segments` so that signal.shape = (6, 6) + # a b c d e 0 + # f g h i j 0 + # k l m n o 0 + # 0 0 0 0 0 0 + # 0 0 0 0 0 0 + # 0 0 0 0 0 0 + paddings = [[0, segments], [0, segments * frame_step - frame_length]] + outer_paddings = array_ops.zeros([outer_rank, 2], dtypes.int32) + paddings = array_ops.concat([outer_paddings, paddings], 0) + signal = array_ops.pad(signal, paddings) + + # Reshape so that signal.shape = (3, 6, 2) + # ab cd e0 + # fg hi j0 + # kl mn o0 + # 00 00 00 + # 00 00 00 + # 00 00 00 + shape = full_shape([frames + segments, segments, frame_step]) + signal = array_ops.reshape(signal, shape) + + # Transpose dimensions so that signal.shape = (3, 6, 2) + # ab fg kl 00 00 00 + # cd hi mn 00 00 00 + # e0 j0 o0 00 00 00 + perm = array_ops.concat( + [math_ops.range(outer_rank), outer_rank + [1, 0, 2]], 0) + perm_static = tensor_util.constant_value(perm) + perm = perm_static if perm_static is not None else perm + signal = array_ops.transpose(signal, perm) + + # Reshape so that signal.shape = (18, 2) + # ab fg kl 00 00 00 cd hi mn 00 00 00 e0 j0 o0 00 00 00 + shape = full_shape([(frames + segments) * segments, frame_step]) + signal = array_ops.reshape(signal, shape) + + # Truncate so that signal.shape = (15, 2) + # ab fg kl 00 00 00 cd hi mn 00 00 00 e0 j0 o0 + signal = signal[..., :(frames + segments - 1) * segments, :] + + # Reshape so that signal.shape = (3, 5, 2) + # ab fg kl 00 00 + # 00 cd hi mn 00 + # 00 00 e0 j0 o0 + shape = full_shape([segments, (frames + segments - 1), frame_step]) + signal = array_ops.reshape(signal, shape) + + # Now, reduce over the columns, to achieve the desired sum. + signal = math_ops.reduce_sum(signal, -3) + + # Flatten the array. + shape = full_shape([(frames + segments - 1) * frame_step]) + signal = array_ops.reshape(signal, shape) + + # Truncate to final length. + signal = signal[..., :output_length] + + return signal diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/shape_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/shape_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e4846b90a2f6db02cea4eba470b4504cf025bf4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/shape_ops.py @@ -0,0 +1,231 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""General shape ops for frames.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.signal import util_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def _infer_frame_shape(signal, frame_length, frame_step, pad_end, axis): + """Infers the shape of the return value of `frame`.""" + frame_length = tensor_util.constant_value(frame_length) + frame_step = tensor_util.constant_value(frame_step) + axis = tensor_util.constant_value(axis) + if signal.shape.ndims is None: + return None + if axis is None: + return [None] * (signal.shape.ndims + 1) + + signal_shape = signal.shape.as_list() + num_frames = None + frame_axis = signal_shape[axis] + outer_dimensions = signal_shape[:axis] + inner_dimensions = signal_shape[axis:][1:] + if signal_shape and frame_axis is not None: + if frame_step is not None and pad_end: + # Double negative is so that we round up. + num_frames = max(0, -(-frame_axis // frame_step)) + elif frame_step is not None and frame_length is not None: + assert not pad_end + num_frames = max( + 0, (frame_axis - frame_length + frame_step) // frame_step) + return outer_dimensions + [num_frames, frame_length] + inner_dimensions + + +@tf_export("signal.frame") +@dispatch.add_dispatch_support +def frame(signal, frame_length, frame_step, pad_end=False, pad_value=0, axis=-1, + name=None): + """Expands `signal`'s `axis` dimension into frames of `frame_length`. + + Slides a window of size `frame_length` over `signal`'s `axis` dimension + with a stride of `frame_step`, replacing the `axis` dimension with + `[frames, frame_length]` frames. + + If `pad_end` is True, window positions that are past the end of the `axis` + dimension are padded with `pad_value` until the window moves fully past the + end of the dimension. Otherwise, only window positions that fully overlap the + `axis` dimension are produced. + + For example: + + >>> # A batch size 3 tensor of 9152 audio samples. + >>> audio = tf.random.normal([3, 9152]) + >>> + >>> # Compute overlapping frames of length 512 with a step of 180 (frames overlap + >>> # by 332 samples). By default, only 49 frames are generated since a frame + >>> # with start position j*180 for j > 48 would overhang the end. + >>> frames = tf.signal.frame(audio, 512, 180) + >>> frames.shape.assert_is_compatible_with([3, 49, 512]) + >>> + >>> # When pad_end is enabled, the final two frames are kept (padded with zeros). + >>> frames = tf.signal.frame(audio, 512, 180, pad_end=True) + >>> frames.shape.assert_is_compatible_with([3, 51, 512]) + + If the dimension along `axis` is N, and `pad_end=False`, the number of frames + can be computed by: + ```python + num_frames = 1 + (N - frame_size) // frame_step + ``` + If `pad_end=True`, the number of frames can be computed by: + ```python + num_frames = -(-N // frame_step) # ceiling division + ``` + + Args: + signal: A `[..., samples, ...]` `Tensor`. The rank and dimensions + may be unknown. Rank must be at least 1. + frame_length: The frame length in samples. An integer or scalar `Tensor`. + frame_step: The frame hop size in samples. An integer or scalar `Tensor`. + pad_end: Whether to pad the end of `signal` with `pad_value`. + pad_value: An optional scalar `Tensor` to use where the input signal + does not exist when `pad_end` is True. + axis: A scalar integer `Tensor` indicating the axis to frame. Defaults to + the last axis. Supports negative values for indexing from the end. + name: An optional name for the operation. + + Returns: + A `Tensor` of frames with shape `[..., num_frames, frame_length, ...]`. + + Raises: + ValueError: If `frame_length`, `frame_step`, `pad_value`, or `axis` are not + scalar. + """ + with ops.name_scope(name, "frame", [signal, frame_length, frame_step, + pad_value]): + signal = ops.convert_to_tensor(signal, name="signal") + frame_length = ops.convert_to_tensor(frame_length, name="frame_length") + frame_step = ops.convert_to_tensor(frame_step, name="frame_step") + axis = ops.convert_to_tensor(axis, name="axis") + + signal.shape.with_rank_at_least(1) + frame_length.shape.assert_has_rank(0) + frame_step.shape.assert_has_rank(0) + axis.shape.assert_has_rank(0) + + result_shape = _infer_frame_shape(signal, frame_length, frame_step, pad_end, + axis) + + def maybe_constant(val): + val_static = tensor_util.constant_value(val) + return (val_static, True) if val_static is not None else (val, False) + + signal_shape, signal_shape_is_static = maybe_constant( + array_ops.shape(signal)) + axis, axis_is_static = maybe_constant(axis) + + if signal_shape_is_static and axis_is_static: + # Axis can be negative. Convert it to positive. + axis = range(len(signal_shape))[axis] + outer_dimensions, length_samples, inner_dimensions = np.split( + signal_shape, indices_or_sections=[axis, axis + 1]) + length_samples = length_samples.item() + else: + signal_rank = array_ops.rank(signal) + # Axis can be negative. Convert it to positive. + axis = math_ops.range(signal_rank)[axis] + outer_dimensions, length_samples, inner_dimensions = array_ops.split( + signal_shape, [axis, 1, signal_rank - 1 - axis]) + length_samples = array_ops.reshape(length_samples, []) + num_outer_dimensions = array_ops.size(outer_dimensions) + num_inner_dimensions = array_ops.size(inner_dimensions) + + # If padding is requested, pad the input signal tensor with pad_value. + if pad_end: + pad_value = ops.convert_to_tensor(pad_value, signal.dtype) + pad_value.shape.assert_has_rank(0) + + # Calculate number of frames, using double negatives to round up. + num_frames = -(-length_samples // frame_step) + + # Pad the signal by up to frame_length samples based on how many samples + # are remaining starting from last_frame_position. + pad_samples = math_ops.maximum( + 0, frame_length + frame_step * (num_frames - 1) - length_samples) + + # Pad the inner dimension of signal by pad_samples. + paddings = array_ops.concat([ + array_ops.zeros([num_outer_dimensions, 2], dtype=pad_samples.dtype), + ops.convert_to_tensor([[0, pad_samples]]), + array_ops.zeros([num_inner_dimensions, 2], dtype=pad_samples.dtype) + ], 0) + signal = array_ops.pad(signal, paddings, constant_values=pad_value) + + signal_shape = array_ops.shape(signal) + length_samples = signal_shape[axis] + else: + num_frames = math_ops.maximum( + constant_op.constant(0, dtype=frame_length.dtype), + 1 + (length_samples - frame_length) // frame_step) + + subframe_length, _ = maybe_constant(util_ops.gcd(frame_length, frame_step)) + subframes_per_frame = frame_length // subframe_length + subframes_per_hop = frame_step // subframe_length + num_subframes = length_samples // subframe_length + + slice_shape = array_ops.concat([outer_dimensions, + [num_subframes * subframe_length], + inner_dimensions], 0) + subframe_shape = array_ops.concat([outer_dimensions, + [num_subframes, subframe_length], + inner_dimensions], 0) + subframes = array_ops.reshape(array_ops.strided_slice( + signal, array_ops.zeros_like(signal_shape), + slice_shape), subframe_shape) + + # frame_selector is a [num_frames, subframes_per_frame] tensor + # that indexes into the appropriate frame in subframes. For example: + # [[0, 0, 0, 0], [2, 2, 2, 2], [4, 4, 4, 4]] + frame_selector = array_ops.reshape( + math_ops.range(num_frames, dtype=frame_length.dtype) * + subframes_per_hop, [num_frames, 1]) + + # subframe_selector is a [num_frames, subframes_per_frame] tensor + # that indexes into the appropriate subframe within a frame. For example: + # [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] + subframe_selector = array_ops.reshape( + math_ops.range(subframes_per_frame, dtype=frame_length.dtype), + [1, subframes_per_frame]) + + # Adding the 2 selector tensors together produces a [num_frames, + # subframes_per_frame] tensor of indices to use with tf.gather to select + # subframes from subframes. We then reshape the inner-most + # subframes_per_frame dimension to stitch the subframes together into + # frames. For example: [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7]]. + selector = frame_selector + subframe_selector + + # Dtypes have to match. + outer_dimensions = ops.convert_to_tensor(outer_dimensions) + inner_dimensions = ops.convert_to_tensor( + inner_dimensions, dtype=outer_dimensions.dtype) + mid_dimensions = ops.convert_to_tensor([num_frames, frame_length], + dtype=outer_dimensions.dtype) + + frames = array_ops.reshape( + array_ops.gather(subframes, selector, axis=axis), + array_ops.concat([outer_dimensions, mid_dimensions, inner_dimensions], + 0)) + + if result_shape: + frames.set_shape(result_shape) + return frames diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/signal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/signal.py new file mode 100644 index 0000000000000000000000000000000000000000..53d9e1f0a7bcafad341eca66fc89b0ac51aef985 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/signal.py @@ -0,0 +1,44 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Signal processing operations.""" + +# pylint: disable=unused-import +from tensorflow.python.ops import signal +from tensorflow.python.ops.signal.dct_ops import dct +from tensorflow.python.ops.signal.fft_ops import fft +from tensorflow.python.ops.signal.fft_ops import fft2d +from tensorflow.python.ops.signal.fft_ops import fft3d +from tensorflow.python.ops.signal.fft_ops import fftshift +from tensorflow.python.ops.signal.fft_ops import rfft +from tensorflow.python.ops.signal.fft_ops import rfft2d +from tensorflow.python.ops.signal.fft_ops import rfft3d +from tensorflow.python.ops.signal.dct_ops import idct +from tensorflow.python.ops.signal.fft_ops import ifft +from tensorflow.python.ops.signal.fft_ops import ifft2d +from tensorflow.python.ops.signal.fft_ops import ifft3d +from tensorflow.python.ops.signal.fft_ops import ifftshift +from tensorflow.python.ops.signal.fft_ops import irfft +from tensorflow.python.ops.signal.fft_ops import irfft2d +from tensorflow.python.ops.signal.fft_ops import irfft3d +from tensorflow.python.ops.signal.mel_ops import linear_to_mel_weight_matrix +from tensorflow.python.ops.signal.mfcc_ops import mfccs_from_log_mel_spectrograms +from tensorflow.python.ops.signal.reconstruction_ops import overlap_and_add +from tensorflow.python.ops.signal.shape_ops import frame +from tensorflow.python.ops.signal.spectral_ops import inverse_stft +from tensorflow.python.ops.signal.spectral_ops import inverse_stft_window_fn +from tensorflow.python.ops.signal.spectral_ops import stft +from tensorflow.python.ops.signal.window_ops import hamming_window +from tensorflow.python.ops.signal.window_ops import hann_window +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/spectral_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/spectral_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f10826b655d1f6553aa4c89efb705731f186b793 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/spectral_ops.py @@ -0,0 +1,449 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Spectral operations (e.g. Short-time Fourier Transform).""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.signal import dct_ops +from tensorflow.python.ops.signal import fft_ops +from tensorflow.python.ops.signal import reconstruction_ops +from tensorflow.python.ops.signal import shape_ops +from tensorflow.python.ops.signal import window_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('signal.stft') +@dispatch.add_dispatch_support +def stft(signals, frame_length, frame_step, fft_length=None, + window_fn=window_ops.hann_window, + pad_end=False, name=None): + """Computes the [Short-time Fourier Transform][stft] of `signals`. + + Implemented with TPU/GPU-compatible ops and supports gradients. + + Args: + signals: A `[..., samples]` `float32`/`float64` `Tensor` of real-valued + signals. + frame_length: An integer scalar `Tensor`. The window length in samples. + frame_step: An integer scalar `Tensor`. The number of samples to step. + fft_length: An integer scalar `Tensor`. The size of the FFT to apply. + If not provided, uses the smallest power of 2 enclosing `frame_length`. + window_fn: A callable that takes a window length and a `dtype` keyword + argument and returns a `[window_length]` `Tensor` of samples in the + provided datatype. If set to `None`, no windowing is used. + pad_end: Whether to pad the end of `signals` with zeros when the provided + frame length and step produces a frame that lies partially past its end. + name: An optional name for the operation. + + Returns: + A `[..., frames, fft_unique_bins]` `Tensor` of `complex64`/`complex128` + STFT values where `fft_unique_bins` is `fft_length // 2 + 1` (the unique + components of the FFT). + + Raises: + ValueError: If `signals` is not at least rank 1, `frame_length` is + not scalar, or `frame_step` is not scalar. + + [stft]: https://en.wikipedia.org/wiki/Short-time_Fourier_transform + """ + with ops.name_scope(name, 'stft', [signals, frame_length, + frame_step]): + signals = ops.convert_to_tensor(signals, name='signals') + signals.shape.with_rank_at_least(1) + frame_length = ops.convert_to_tensor(frame_length, name='frame_length') + frame_length.shape.assert_has_rank(0) + frame_step = ops.convert_to_tensor(frame_step, name='frame_step') + frame_step.shape.assert_has_rank(0) + + if fft_length is None: + fft_length = _enclosing_power_of_two(frame_length) + else: + fft_length = ops.convert_to_tensor(fft_length, name='fft_length') + + framed_signals = shape_ops.frame( + signals, frame_length, frame_step, pad_end=pad_end) + + # Optionally window the framed signals. + if window_fn is not None: + window = window_fn(frame_length, dtype=framed_signals.dtype) + framed_signals *= window + + # fft_ops.rfft produces the (fft_length/2 + 1) unique components of the + # FFT of the real windowed signals in framed_signals. + return fft_ops.rfft(framed_signals, [fft_length]) + + +@tf_export('signal.inverse_stft_window_fn') +@dispatch.add_dispatch_support +def inverse_stft_window_fn(frame_step, + forward_window_fn=window_ops.hann_window, + name=None): + """Generates a window function that can be used in `inverse_stft`. + + Constructs a window that is equal to the forward window with a further + pointwise amplitude correction. `inverse_stft_window_fn` is equivalent to + `forward_window_fn` in the case where it would produce an exact inverse. + + See examples in `inverse_stft` documentation for usage. + + Args: + frame_step: An integer scalar `Tensor`. The number of samples to step. + forward_window_fn: window_fn used in the forward transform, `stft`. + name: An optional name for the operation. + + Returns: + A callable that takes a window length and a `dtype` keyword argument and + returns a `[window_length]` `Tensor` of samples in the provided datatype. + The returned window is suitable for reconstructing original waveform in + inverse_stft. + """ + def inverse_stft_window_fn_inner(frame_length, dtype): + """Computes a window that can be used in `inverse_stft`. + + Args: + frame_length: An integer scalar `Tensor`. The window length in samples. + dtype: Data type of waveform passed to `stft`. + + Returns: + A window suitable for reconstructing original waveform in `inverse_stft`. + + Raises: + ValueError: If `frame_length` is not scalar, `forward_window_fn` is not a + callable that takes a window length and a `dtype` keyword argument and + returns a `[window_length]` `Tensor` of samples in the provided datatype + `frame_step` is not scalar, or `frame_step` is not scalar. + """ + with ops.name_scope(name, 'inverse_stft_window_fn', [forward_window_fn]): + frame_step_ = ops.convert_to_tensor(frame_step, name='frame_step') + frame_step_.shape.assert_has_rank(0) + frame_length = ops.convert_to_tensor(frame_length, name='frame_length') + frame_length.shape.assert_has_rank(0) + + # Use equation 7 from Griffin + Lim. + forward_window = forward_window_fn(frame_length, dtype=dtype) + denom = math_ops.square(forward_window) + overlaps = -(-frame_length // frame_step_) # Ceiling division. # pylint: disable=invalid-unary-operand-type + denom = array_ops.pad(denom, [(0, overlaps * frame_step_ - frame_length)]) + denom = array_ops.reshape(denom, [overlaps, frame_step_]) + denom = math_ops.reduce_sum(denom, 0, keepdims=True) + denom = array_ops.tile(denom, [overlaps, 1]) + denom = array_ops.reshape(denom, [overlaps * frame_step_]) + + return forward_window / denom[:frame_length] + return inverse_stft_window_fn_inner + + +@tf_export('signal.inverse_stft') +@dispatch.add_dispatch_support +def inverse_stft(stfts, + frame_length, + frame_step, + fft_length=None, + window_fn=window_ops.hann_window, + name=None): + """Computes the inverse [Short-time Fourier Transform][stft] of `stfts`. + + To reconstruct an original waveform, a complementary window function should + be used with `inverse_stft`. Such a window function can be constructed with + `tf.signal.inverse_stft_window_fn`. + Example: + + ```python + frame_length = 400 + frame_step = 160 + waveform = tf.random.normal(dtype=tf.float32, shape=[1000]) + stft = tf.signal.stft(waveform, frame_length, frame_step) + inverse_stft = tf.signal.inverse_stft( + stft, frame_length, frame_step, + window_fn=tf.signal.inverse_stft_window_fn(frame_step)) + ``` + + If a custom `window_fn` is used with `tf.signal.stft`, it must be passed to + `tf.signal.inverse_stft_window_fn`: + + ```python + frame_length = 400 + frame_step = 160 + window_fn = tf.signal.hamming_window + waveform = tf.random.normal(dtype=tf.float32, shape=[1000]) + stft = tf.signal.stft( + waveform, frame_length, frame_step, window_fn=window_fn) + inverse_stft = tf.signal.inverse_stft( + stft, frame_length, frame_step, + window_fn=tf.signal.inverse_stft_window_fn( + frame_step, forward_window_fn=window_fn)) + ``` + + Implemented with TPU/GPU-compatible ops and supports gradients. + + Args: + stfts: A `complex64`/`complex128` `[..., frames, fft_unique_bins]` + `Tensor` of STFT bins representing a batch of `fft_length`-point STFTs + where `fft_unique_bins` is `fft_length // 2 + 1` + frame_length: An integer scalar `Tensor`. The window length in samples. + frame_step: An integer scalar `Tensor`. The number of samples to step. + fft_length: An integer scalar `Tensor`. The size of the FFT that produced + `stfts`. If not provided, uses the smallest power of 2 enclosing + `frame_length`. + window_fn: A callable that takes a window length and a `dtype` keyword + argument and returns a `[window_length]` `Tensor` of samples in the + provided datatype. If set to `None`, no windowing is used. + name: An optional name for the operation. + + Returns: + A `[..., samples]` `Tensor` of `float32`/`float64` signals representing + the inverse STFT for each input STFT in `stfts`. + + Raises: + ValueError: If `stfts` is not at least rank 2, `frame_length` is not scalar, + `frame_step` is not scalar, or `fft_length` is not scalar. + + [stft]: https://en.wikipedia.org/wiki/Short-time_Fourier_transform + """ + with ops.name_scope(name, 'inverse_stft', [stfts]): + stfts = ops.convert_to_tensor(stfts, name='stfts') + stfts.shape.with_rank_at_least(2) + frame_length = ops.convert_to_tensor(frame_length, name='frame_length') + frame_length.shape.assert_has_rank(0) + frame_step = ops.convert_to_tensor(frame_step, name='frame_step') + frame_step.shape.assert_has_rank(0) + if fft_length is None: + fft_length = _enclosing_power_of_two(frame_length) + else: + fft_length = ops.convert_to_tensor(fft_length, name='fft_length') + fft_length.shape.assert_has_rank(0) + + real_frames = fft_ops.irfft(stfts, [fft_length]) + + # frame_length may be larger or smaller than fft_length, so we pad or + # truncate real_frames to frame_length. + frame_length_static = tensor_util.constant_value(frame_length) + # If we don't know the shape of real_frames's inner dimension, pad and + # truncate to frame_length. + if (frame_length_static is None or real_frames.shape.ndims is None or + real_frames.shape.as_list()[-1] is None): + real_frames = real_frames[..., :frame_length] + real_frames_rank = array_ops.rank(real_frames) + real_frames_shape = array_ops.shape(real_frames) + paddings = array_ops.concat( + [array_ops.zeros([real_frames_rank - 1, 2], + dtype=frame_length.dtype), + [[0, math_ops.maximum(0, frame_length - real_frames_shape[-1])]]], 0) + real_frames = array_ops.pad(real_frames, paddings) + # We know real_frames's last dimension and frame_length statically. If they + # are different, then pad or truncate real_frames to frame_length. + elif real_frames.shape.as_list()[-1] > frame_length_static: + real_frames = real_frames[..., :frame_length_static] + elif real_frames.shape.as_list()[-1] < frame_length_static: + pad_amount = frame_length_static - real_frames.shape.as_list()[-1] + real_frames = array_ops.pad(real_frames, + [[0, 0]] * (real_frames.shape.ndims - 1) + + [[0, pad_amount]]) + + # The above code pads the inner dimension of real_frames to frame_length, + # but it does so in a way that may not be shape-inference friendly. + # Restore shape information if we are able to. + if frame_length_static is not None and real_frames.shape.ndims is not None: + real_frames.set_shape([None] * (real_frames.shape.ndims - 1) + + [frame_length_static]) + + # Optionally window and overlap-add the inner 2 dimensions of real_frames + # into a single [samples] dimension. + if window_fn is not None: + window = window_fn(frame_length, dtype=stfts.dtype.real_dtype) + real_frames *= window + return reconstruction_ops.overlap_and_add(real_frames, frame_step) + + +def _enclosing_power_of_two(value): + """Return 2**N for integer N such that 2**N >= value.""" + value_static = tensor_util.constant_value(value) + if value_static is not None: + return constant_op.constant( + int(2**np.ceil(np.log(value_static) / np.log(2.0))), value.dtype) + return math_ops.cast( + math_ops.pow( + 2.0, + math_ops.ceil( + math_ops.log(math_ops.cast(value, dtypes.float32)) / + math_ops.log(2.0))), value.dtype) + + +@tf_export('signal.mdct') +@dispatch.add_dispatch_support +def mdct(signals, frame_length, window_fn=window_ops.vorbis_window, + pad_end=False, norm=None, name=None): + """Computes the [Modified Discrete Cosine Transform][mdct] of `signals`. + + Implemented with TPU/GPU-compatible ops and supports gradients. + + Args: + signals: A `[..., samples]` `float32`/`float64` `Tensor` of real-valued + signals. + frame_length: An integer scalar `Tensor`. The window length in samples + which must be divisible by 4. + window_fn: A callable that takes a frame_length and a `dtype` keyword + argument and returns a `[frame_length]` `Tensor` of samples in the + provided datatype. If set to `None`, a rectangular window with a scale of + 1/sqrt(2) is used. For perfect reconstruction of a signal from `mdct` + followed by `inverse_mdct`, please use `tf.signal.vorbis_window`, + `tf.signal.kaiser_bessel_derived_window` or `None`. If using another + window function, make sure that w[n]^2 + w[n + frame_length // 2]^2 = 1 + and w[n] = w[frame_length - n - 1] for n = 0,...,frame_length // 2 - 1 to + achieve perfect reconstruction. + pad_end: Whether to pad the end of `signals` with zeros when the provided + frame length and step produces a frame that lies partially past its end. + norm: If it is None, unnormalized dct4 is used, if it is "ortho" + orthonormal dct4 is used. + name: An optional name for the operation. + + Returns: + A `[..., frames, frame_length // 2]` `Tensor` of `float32`/`float64` + MDCT values where `frames` is roughly `samples // (frame_length // 2)` + when `pad_end=False`. + + Raises: + ValueError: If `signals` is not at least rank 1, `frame_length` is + not scalar, or `frame_length` is not a multiple of `4`. + + [mdct]: https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform + """ + with ops.name_scope(name, 'mdct', [signals, frame_length]): + signals = ops.convert_to_tensor(signals, name='signals') + signals.shape.with_rank_at_least(1) + frame_length = ops.convert_to_tensor(frame_length, name='frame_length') + frame_length.shape.assert_has_rank(0) + # Assert that frame_length is divisible by 4. + frame_length_static = tensor_util.constant_value(frame_length) + if frame_length_static is not None: + if frame_length_static % 4 != 0: + raise ValueError('The frame length must be a multiple of 4.') + frame_step = ops.convert_to_tensor(frame_length_static // 2, + dtype=frame_length.dtype) + else: + frame_step = frame_length // 2 + + framed_signals = shape_ops.frame( + signals, frame_length, frame_step, pad_end=pad_end) + + # Optionally window the framed signals. + if window_fn is not None: + window = window_fn(frame_length, dtype=framed_signals.dtype) + framed_signals *= window + else: + framed_signals *= 1.0 / np.sqrt(2) + + split_frames = array_ops.split(framed_signals, 4, axis=-1) + frame_firsthalf = -array_ops.reverse(split_frames[2], + [-1]) - split_frames[3] + frame_secondhalf = split_frames[0] - array_ops.reverse(split_frames[1], + [-1]) + frames_rearranged = array_ops.concat((frame_firsthalf, frame_secondhalf), + axis=-1) + # Below call produces the (frame_length // 2) unique components of the + # type 4 orthonormal DCT of the real windowed signals in frames_rearranged. + return dct_ops.dct(frames_rearranged, type=4, norm=norm) + + +@tf_export('signal.inverse_mdct') +@dispatch.add_dispatch_support +def inverse_mdct(mdcts, + window_fn=window_ops.vorbis_window, + norm=None, + name=None): + """Computes the inverse modified DCT of `mdcts`. + + To reconstruct an original waveform, the same window function should + be used with `mdct` and `inverse_mdct`. + + Example usage: + + >>> @tf.function + ... def compare_round_trip(): + ... samples = 1000 + ... frame_length = 400 + ... halflen = frame_length // 2 + ... waveform = tf.random.normal(dtype=tf.float32, shape=[samples]) + ... waveform_pad = tf.pad(waveform, [[halflen, 0],]) + ... mdct = tf.signal.mdct(waveform_pad, frame_length, pad_end=True, + ... window_fn=tf.signal.vorbis_window) + ... inverse_mdct = tf.signal.inverse_mdct(mdct, + ... window_fn=tf.signal.vorbis_window) + ... inverse_mdct = inverse_mdct[halflen: halflen + samples] + ... return waveform, inverse_mdct + >>> waveform, inverse_mdct = compare_round_trip() + >>> np.allclose(waveform.numpy(), inverse_mdct.numpy(), rtol=1e-3, atol=1e-4) + True + + Implemented with TPU/GPU-compatible ops and supports gradients. + + Args: + mdcts: A `float32`/`float64` `[..., frames, frame_length // 2]` + `Tensor` of MDCT bins representing a batch of `frame_length // 2`-point + MDCTs. + window_fn: A callable that takes a frame_length and a `dtype` keyword + argument and returns a `[frame_length]` `Tensor` of samples in the + provided datatype. If set to `None`, a rectangular window with a scale of + 1/sqrt(2) is used. For perfect reconstruction of a signal from `mdct` + followed by `inverse_mdct`, please use `tf.signal.vorbis_window`, + `tf.signal.kaiser_bessel_derived_window` or `None`. If using another + window function, make sure that w[n]^2 + w[n + frame_length // 2]^2 = 1 + and w[n] = w[frame_length - n - 1] for n = 0,...,frame_length // 2 - 1 to + achieve perfect reconstruction. + norm: If "ortho", orthonormal inverse DCT4 is performed, if it is None, + a regular dct4 followed by scaling of `1/frame_length` is performed. + name: An optional name for the operation. + + Returns: + A `[..., samples]` `Tensor` of `float32`/`float64` signals representing + the inverse MDCT for each input MDCT in `mdcts` where `samples` is + `(frames - 1) * (frame_length // 2) + frame_length`. + + Raises: + ValueError: If `mdcts` is not at least rank 2. + + [mdct]: https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform + """ + with ops.name_scope(name, 'inverse_mdct', [mdcts]): + mdcts = ops.convert_to_tensor(mdcts, name='mdcts') + mdcts.shape.with_rank_at_least(2) + half_len = math_ops.cast(mdcts.shape[-1], dtype=dtypes.int32) + + if norm is None: + half_len_float = math_ops.cast(half_len, dtype=mdcts.dtype) + result_idct4 = (0.5 / half_len_float) * dct_ops.dct(mdcts, type=4) + elif norm == 'ortho': + result_idct4 = dct_ops.dct(mdcts, type=4, norm='ortho') + split_result = array_ops.split(result_idct4, 2, axis=-1) + real_frames = array_ops.concat((split_result[1], + -array_ops.reverse(split_result[1], [-1]), + -array_ops.reverse(split_result[0], [-1]), + -split_result[0]), axis=-1) + + # Optionally window and overlap-add the inner 2 dimensions of real_frames + # into a single [samples] dimension. + if window_fn is not None: + window = window_fn(2 * half_len, dtype=mdcts.dtype) + real_frames *= window + else: + real_frames *= 1.0 / np.sqrt(2) + return reconstruction_ops.overlap_and_add(real_frames, half_len) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/util_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/util_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f3f2ef86bb58742ace1a504696fe4f43ad143c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/util_ops.py @@ -0,0 +1,69 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utility ops shared across tf.contrib.signal.""" + +import fractions # gcd is here for Python versions < 3 +import math # Get gcd here for Python versions >= 3 +import sys + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import while_loop + + +def gcd(a, b, name=None): + """Returns the greatest common divisor via Euclid's algorithm. + + Args: + a: The dividend. A scalar integer `Tensor`. + b: The divisor. A scalar integer `Tensor`. + name: An optional name for the operation. + + Returns: + A scalar `Tensor` representing the greatest common divisor between `a` and + `b`. + + Raises: + ValueError: If `a` or `b` are not scalar integers. + """ + with ops.name_scope(name, 'gcd', [a, b]): + a = ops.convert_to_tensor(a) + b = ops.convert_to_tensor(b) + + a.shape.assert_has_rank(0) + b.shape.assert_has_rank(0) + + if not a.dtype.is_integer: + raise ValueError('a must be an integer type. Got: %s' % a.dtype) + if not b.dtype.is_integer: + raise ValueError('b must be an integer type. Got: %s' % b.dtype) + + # TPU requires static shape inference. GCD is used for subframe size + # computation, so we should prefer static computation where possible. + const_a = tensor_util.constant_value(a) + const_b = tensor_util.constant_value(b) + if const_a is not None and const_b is not None: + if sys.version_info.major < 3: + math_gcd = fractions.gcd + else: + math_gcd = math.gcd + return ops.convert_to_tensor(math_gcd(const_a, const_b)) + + cond = lambda _, b: math_ops.greater(b, array_ops.zeros_like(b)) + body = lambda a, b: [b, math_ops.mod(a, b)] + a, b = while_loop.while_loop(cond, body, [a, b], back_prop=False) + return a diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/window_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/window_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c62d0ebef43b9d20b0c6fcca7136c96e346d77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/signal/window_ops.py @@ -0,0 +1,245 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Ops for computing common window functions.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +def _check_params(window_length, dtype): + """Check window_length and dtype params. + + Args: + window_length: A scalar value or `Tensor`. + dtype: The data type to produce. Must be a floating point type. + + Returns: + window_length converted to a tensor of type int32. + + Raises: + ValueError: If `dtype` is not a floating point type or window_length is not + a scalar. + """ + if not dtype.is_floating: + raise ValueError('dtype must be a floating point type. Found %s' % dtype) + window_length = ops.convert_to_tensor(window_length, dtype=dtypes.int32) + window_length.shape.assert_has_rank(0) + return window_length + + +@tf_export('signal.kaiser_window') +@dispatch.add_dispatch_support +def kaiser_window(window_length, beta=12., dtype=dtypes.float32, name=None): + """Generate a [Kaiser window][kaiser]. + + Args: + window_length: A scalar `Tensor` indicating the window length to generate. + beta: Beta parameter for Kaiser window, see reference below. + dtype: The data type to produce. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + [kaiser]: + https://docs.scipy.org/doc/numpy/reference/generated/numpy.kaiser.html + """ + with ops.name_scope(name, 'kaiser_window'): + window_length = _check_params(window_length, dtype) + window_length_const = tensor_util.constant_value(window_length) + if window_length_const == 1: + return array_ops.ones([1], dtype=dtype) + # tf.range does not support float16 so we work with float32 initially. + halflen_float = ( + math_ops.cast(window_length, dtype=dtypes.float32) - 1.0) / 2.0 + arg = math_ops.range(-halflen_float, halflen_float + 0.1, + dtype=dtypes.float32) + # Convert everything into given dtype which can be float16. + arg = math_ops.cast(arg, dtype=dtype) + beta = math_ops.cast(beta, dtype=dtype) + one = math_ops.cast(1.0, dtype=dtype) + halflen_float = math_ops.cast(halflen_float, dtype=dtype) + num = beta * math_ops.sqrt(nn_ops.relu( + one - math_ops.square(arg / halflen_float))) + window = math_ops.exp(num - beta) * ( + special_math_ops.bessel_i0e(num) / special_math_ops.bessel_i0e(beta)) + return window + + +@tf_export('signal.kaiser_bessel_derived_window') +@dispatch.add_dispatch_support +def kaiser_bessel_derived_window(window_length, beta=12., + dtype=dtypes.float32, name=None): + """Generate a [Kaiser Bessel derived window][kbd]. + + Args: + window_length: A scalar `Tensor` indicating the window length to generate. + beta: Beta parameter for Kaiser window. + dtype: The data type to produce. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + [kbd]: + https://en.wikipedia.org/wiki/Kaiser_window#Kaiser%E2%80%93Bessel-derived_(KBD)_window + """ + with ops.name_scope(name, 'kaiser_bessel_derived_window'): + window_length = _check_params(window_length, dtype) + halflen = window_length // 2 + kaiserw = kaiser_window(halflen + 1, beta, dtype=dtype) + kaiserw_csum = math_ops.cumsum(kaiserw) + halfw = math_ops.sqrt(kaiserw_csum[:-1] / kaiserw_csum[-1]) + window = array_ops.concat((halfw, halfw[::-1]), axis=0) + return window + + +@tf_export('signal.vorbis_window') +@dispatch.add_dispatch_support +def vorbis_window(window_length, dtype=dtypes.float32, name=None): + """Generate a [Vorbis power complementary window][vorbis]. + + Args: + window_length: A scalar `Tensor` indicating the window length to generate. + dtype: The data type to produce. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + [vorbis]: + https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform#Window_functions + """ + with ops.name_scope(name, 'vorbis_window'): + window_length = _check_params(window_length, dtype) + arg = math_ops.cast(math_ops.range(window_length), dtype=dtype) + window = math_ops.sin(np.pi / 2.0 * math_ops.pow(math_ops.sin( + np.pi / math_ops.cast(window_length, dtype=dtype) * + (arg + 0.5)), 2.0)) + return window + + +@tf_export('signal.hann_window') +@dispatch.add_dispatch_support +def hann_window(window_length, periodic=True, dtype=dtypes.float32, name=None): + """Generate a [Hann window][hann]. + + Args: + window_length: A scalar `Tensor` indicating the window length to generate. + periodic: A bool `Tensor` indicating whether to generate a periodic or + symmetric window. Periodic windows are typically used for spectral + analysis while symmetric windows are typically used for digital + filter design. + dtype: The data type to produce. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + Raises: + ValueError: If `dtype` is not a floating point type. + + [hann]: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows + """ + return _raised_cosine_window(name, 'hann_window', window_length, periodic, + dtype, 0.5, 0.5) + + +@tf_export('signal.hamming_window') +@dispatch.add_dispatch_support +def hamming_window(window_length, periodic=True, dtype=dtypes.float32, + name=None): + """Generate a [Hamming][hamming] window. + + Args: + window_length: A scalar `Tensor` indicating the window length to generate. + periodic: A bool `Tensor` indicating whether to generate a periodic or + symmetric window. Periodic windows are typically used for spectral + analysis while symmetric windows are typically used for digital + filter design. + dtype: The data type to produce. Must be a floating point type. + name: An optional name for the operation. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + Raises: + ValueError: If `dtype` is not a floating point type. + + [hamming]: + https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows + """ + return _raised_cosine_window(name, 'hamming_window', window_length, periodic, + dtype, 0.54, 0.46) + + +def _raised_cosine_window(name, default_name, window_length, periodic, + dtype, a, b): + """Helper function for computing a raised cosine window. + + Args: + name: Name to use for the scope. + default_name: Default name to use for the scope. + window_length: A scalar `Tensor` or integer indicating the window length. + periodic: A bool `Tensor` indicating whether to generate a periodic or + symmetric window. + dtype: A floating point `DType`. + a: The alpha parameter to the raised cosine window. + b: The beta parameter to the raised cosine window. + + Returns: + A `Tensor` of shape `[window_length]` of type `dtype`. + + Raises: + ValueError: If `dtype` is not a floating point type or `window_length` is + not scalar or `periodic` is not scalar. + """ + if not dtype.is_floating: + raise ValueError('dtype must be a floating point type. Found %s' % dtype) + + with ops.name_scope(name, default_name, [window_length, periodic]): + window_length = ops.convert_to_tensor(window_length, dtype=dtypes.int32, + name='window_length') + window_length.shape.assert_has_rank(0) + window_length_const = tensor_util.constant_value(window_length) + if window_length_const == 1: + return array_ops.ones([1], dtype=dtype) + periodic = math_ops.cast( + ops.convert_to_tensor(periodic, dtype=dtypes.bool, name='periodic'), + dtypes.int32) + periodic.shape.assert_has_rank(0) + even = 1 - math_ops.mod(window_length, 2) + + n = math_ops.cast(window_length + periodic * even - 1, dtype=dtype) + count = math_ops.cast(math_ops.range(window_length), dtype) + cos_arg = constant_op.constant(2 * np.pi, dtype=dtype) * count / n + + if window_length_const is not None: + return math_ops.cast(a - b * math_ops.cos(cos_arg), dtype=dtype) + return cond.cond( + math_ops.equal(window_length, 1), + lambda: array_ops.ones([window_length], dtype=dtype), + lambda: math_ops.cast(a - b * math_ops.cos(cos_arg), dtype=dtype)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sort_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sort_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..465a4cd2109c2d059c4f989fe94c6913c7eefc14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sort_ops.py @@ -0,0 +1,285 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Support for sorting tensors.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops as framework_ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('sort') +@dispatch.add_dispatch_support +def sort(values, axis=-1, direction='ASCENDING', name=None): + """Sorts a tensor. + + Usage: + + >>> a = [1, 10, 26.9, 2.8, 166.32, 62.3] + >>> tf.sort(a).numpy() + array([ 1. , 2.8 , 10. , 26.9 , 62.3 , 166.32], dtype=float32) + + >>> tf.sort(a, direction='DESCENDING').numpy() + array([166.32, 62.3 , 26.9 , 10. , 2.8 , 1. ], dtype=float32) + + For multidimensional inputs you can control which axis the sort is applied + along. The default `axis=-1` sorts the innermost axis. + + >>> mat = [[3,2,1], + ... [2,1,3], + ... [1,3,2]] + >>> tf.sort(mat, axis=-1).numpy() + array([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]], dtype=int32) + >>> tf.sort(mat, axis=0).numpy() + array([[1, 1, 1], + [2, 2, 2], + [3, 3, 3]], dtype=int32) + + See also: + + * `tf.argsort`: Like sort, but it returns the sort indices. + * `tf.math.top_k`: A partial sort that returns a fixed number of top values + and corresponding indices. + + + Args: + values: 1-D or higher **numeric** `Tensor`. + axis: The axis along which to sort. The default is -1, which sorts the last + axis. + direction: The direction in which to sort the values (`'ASCENDING'` or + `'DESCENDING'`). + name: Optional name for the operation. + + Returns: + A `Tensor` with the same dtype and shape as `values`, with the elements + sorted along the given `axis`. + + Raises: + tf.errors.InvalidArgumentError: If the `values.dtype` is not a `float` or + `int` type. + ValueError: If axis is not a constant scalar, or the direction is invalid. + """ + with framework_ops.name_scope(name, 'sort'): + return _sort_or_argsort(values, axis, direction, return_argsort=False) + + +@tf_export('argsort') +@dispatch.add_dispatch_support +def argsort(values, axis=-1, direction='ASCENDING', stable=False, name=None): + """Returns the indices of a tensor that give its sorted order along an axis. + + >>> values = [1, 10, 26.9, 2.8, 166.32, 62.3] + >>> sort_order = tf.argsort(values) + >>> sort_order.numpy() + array([0, 3, 1, 2, 5, 4], dtype=int32) + + For a 1D tensor: + + >>> sorted = tf.gather(values, sort_order) + >>> assert tf.reduce_all(sorted == tf.sort(values)) + + For higher dimensions, the output has the same shape as + `values`, but along the given axis, values represent the index of the sorted + element in that slice of the tensor at the given position. + + >>> mat = [[30,20,10], + ... [20,10,30], + ... [10,30,20]] + >>> indices = tf.argsort(mat) + >>> indices.numpy() + array([[2, 1, 0], + [1, 0, 2], + [0, 2, 1]], dtype=int32) + + If `axis=-1` these indices can be used to apply a sort using `tf.gather`: + + >>> tf.gather(mat, indices, batch_dims=-1).numpy() + array([[10, 20, 30], + [10, 20, 30], + [10, 20, 30]], dtype=int32) + + See also: + + * `tf.sort`: Sort along an axis. + * `tf.math.top_k`: A partial sort that returns a fixed number of top values + and corresponding indices. + + Args: + values: 1-D or higher **numeric** `Tensor`. + axis: The axis along which to sort. The default is -1, which sorts the last + axis. + direction: The direction in which to sort the values (`'ASCENDING'` or + `'DESCENDING'`). + stable: If True, equal elements in the original tensor will not be + re-ordered in the returned order. Unstable sort is not yet implemented, + but will eventually be the default for performance reasons. If you require + a stable order, pass `stable=True` for forwards compatibility. + name: Optional name for the operation. + + Returns: + An int32 `Tensor` with the same shape as `values`. The indices that would + sort each slice of the given `values` along the given `axis`. + + Raises: + ValueError: If axis is not a constant scalar, or the direction is invalid. + tf.errors.InvalidArgumentError: If the `values.dtype` is not a `float` or + `int` type. + """ + del stable # Unused. + with framework_ops.name_scope(name, 'argsort'): + return _sort_or_argsort(values, axis, direction, return_argsort=True) + + +def _sort_or_argsort(values, axis, direction, return_argsort): + """Internal sort/argsort implementation. + + Args: + values: The input values. + axis: The axis along which to sort. + direction: 'ASCENDING' or 'DESCENDING'. + return_argsort: Whether to return the argsort result. + + Returns: + Either the sorted values, or the indices of the sorted values in the + original tensor. See the `sort` and `argsort` docstrings. + + Raises: + ValueError: If axis is not a constant scalar, or the direction is invalid. + """ + if direction not in _SORT_IMPL: + valid_directions = ', '.join(sorted(_SORT_IMPL.keys())) + raise ValueError(f'Argument `direction` should be one of {valid_directions}' + f'. Received: direction={direction}') + # Axis must be an integer, not a Tensor. + axis = framework_ops.convert_to_tensor(axis, name='axis') + axis_static = tensor_util.constant_value(axis) + if axis.shape.ndims not in (None, 0) or axis_static is None: + raise ValueError( + f'Argument `axis` must be a constant scalar. Received: axis={axis}.') + axis_static = int(axis_static) # Avoids NumPy casting error + + values = framework_ops.convert_to_tensor(values, name='values') + + return _SORT_IMPL[direction](values, axis_static, return_argsort) + + +def _descending_sort(values, axis, return_argsort=False): + """Sorts values in reverse using `top_k`. + + Args: + values: Tensor of numeric values. + axis: Index of the axis which values should be sorted along. + return_argsort: If False, return the sorted values. If True, return the + indices that would sort the values. + + Returns: + The sorted values. + """ + # TODO(b/190410105): replace with a proper sort kernel. + k = array_ops.shape(values)[axis] + rank = array_ops.rank(values) + static_rank = values.shape.ndims + # Fast path: sorting the last axis. + if axis == -1 or axis + 1 == values.get_shape().ndims: + top_k_input = values + transposition = None + else: + # Otherwise, transpose the array. Swap axes `axis` and `rank - 1`. + if axis < 0: + # Calculate the actual axis index if counting from the end. Use the static + # rank if available, or else make the axis back into a tensor. + axis += static_rank or rank + if static_rank is not None: + # Prefer to calculate the transposition array in NumPy and make it a + # constant. + transposition = constant_op.constant( + np.r_[ + # Axes up to axis are unchanged. + np.arange(axis), + # Swap axis and rank - 1. + [static_rank - 1], + # Axes in [axis + 1, rank - 1) are unchanged. + np.arange(axis + 1, static_rank - 1), + # Swap axis and rank - 1. + [axis]], + name='transposition') + else: + # Generate the transposition array from the tensors. + transposition = array_ops.tensor_scatter_update( + math_ops.range(rank), [[axis], [rank-1]], [rank-1, axis]) + top_k_input = array_ops.transpose(values, transposition) + + values, indices = nn_ops.top_k(top_k_input, k) + return_value = indices if return_argsort else values + if transposition is not None: + # transposition contains a single cycle of length 2 (swapping 2 elements), + # so it is an involution (it is its own inverse). + return_value = array_ops.transpose(return_value, transposition) + return return_value + + +def _ascending_sort(values, axis, return_argsort=False): + """Sorts values in ascending order. + + Args: + values: Tensor of numeric values. + axis: Index of the axis which values should be sorted along. + return_argsort: If False, return the sorted values. If True, return the + indices that would sort the values. + + Returns: + The sorted values. + """ + # TODO(b/190410105): replace with a proper sort kernel. + # If values are integers, we need special handling. + dtype = values.dtype + if dtype.is_unsigned: + # Subtract values from dtype.max to reverse sort order. + offset = dtype.max + values_or_indices = _descending_sort(offset - values, axis, return_argsort) + return values_or_indices if return_argsort else offset - values_or_indices + + elif dtype.is_integer: + # Negate and subtract 1 to map dtype.min to dtype.max. Technically this + # will result in signed-integer-overflow UB for dtype.min, though + # practically should produce correct results on all systems. + # + # Casting to unsigned would be better, but uint* subtraction is not + # supported on all devices. + # + # Although more complex and slightly slower than descend+reverse, this + # approach preserves sort stability. + values_or_indices = _descending_sort(-values - 1, axis, return_argsort) + return values_or_indices if return_argsort else -values_or_indices - 1 + + else: + # Otherwise, negate the values and use descending sort. + values_or_indices = _descending_sort(-values, axis, return_argsort) + # If not argsort, negate the values again. + return values_or_indices if return_argsort else -values_or_indices + + +_SORT_IMPL = { + 'ASCENDING': _ascending_sort, + 'DESCENDING': _descending_sort, +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ac4cd73a6a65a9bb57c69759176747cdd5c115 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_grad.py @@ -0,0 +1,362 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in sparse_ops.py.""" +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops + +# TODO(b/31222613): This op may be differentiable, and there may be +# latent bugs here. +ops.NotDifferentiable("SparseAddGrad") +ops.NotDifferentiable("SparseConcat") + + +@ops.RegisterGradient("SparseReorder") +def _SparseReorderGrad( + op: ops.Operation, unused_output_indices_grad, output_values_grad +): + """Gradients for the SparseReorder op. + + Args: + op: the SparseReorder op + unused_output_indices_grad: the incoming gradients of the output indices + output_values_grad: the incoming gradients of the output values + + Returns: + Gradient for each of the 3 input tensors: + (input_indices, input_values, input_shape) + The gradients for input_indices and input_shape is None. + """ + input_indices = op.inputs[0] + input_shape = op.inputs[2] + + num_entries = array_ops.shape(input_indices)[0] + entry_indices = math_ops.range(num_entries) + sp_unordered = sparse_tensor.SparseTensor(input_indices, entry_indices, + input_shape) + sp_ordered = sparse_ops.sparse_reorder(sp_unordered) + inverted_permutation = array_ops.invert_permutation(sp_ordered.values) + + return (None, array_ops.gather(output_values_grad, + inverted_permutation), None) + + +@ops.RegisterGradient("SparseAdd") +def _SparseAddGrad(op: ops.Operation, *grads): + """The backward operator for the SparseAdd op. + + The SparseAdd op calculates A + B, where A, B, and the sum are all represented + as `SparseTensor` objects. This op takes in the upstream gradient w.r.t. + non-empty values of the sum, and outputs the gradients w.r.t. the non-empty + values of A and B. + + Args: + op: the SparseAdd op + *grads: the incoming gradients, one element per output of `op` + + Returns: + Gradient for each of the 6 input tensors of SparseAdd: + (a_indices, a_values, a_shape, b_indices, b_values, b_shape, thresh) + The gradients for the indices, shapes, and the threshold are None. + """ + val_grad = grads[1] + a_indices = op.inputs[0] + b_indices = op.inputs[3] + sum_indices = op.outputs[0] + # NOTE: we do not need to take `thresh` into account, since it simply affects + # the non-zero elements of the sum, and we will peek into `sum_indices` in the + # gradient op. + + a_val_grad, b_val_grad = gen_sparse_ops.sparse_add_grad( + val_grad, a_indices, b_indices, sum_indices) + a_val_grad.set_shape(op.inputs[1].get_shape()) + b_val_grad.set_shape(op.inputs[4].get_shape()) + # (a_indices, a_values, a_shape, b_indices, b_values, b_shape, thresh) + return (None, a_val_grad, None, None, b_val_grad, None, None) + + +@ops.RegisterGradient("SparseTensorDenseAdd") +def _SparseTensorDenseAddGrad(op: ops.Operation, out_grad): + sp_indices = op.inputs[0] + # (sparse_indices, sparse_values, sparse_shape, dense) + return (None, array_ops.gather_nd(out_grad, sp_indices), None, out_grad) + + +@ops.RegisterGradient("SparseReduceSum") +def _SparseReduceSumGrad(op: ops.Operation, out_grad): + """Similar to gradient for the Sum Op (i.e. tf.reduce_sum()).""" + sp_indices = op.inputs[0] + sp_shape = op.inputs[2] + output_shape_kept_dims = math_ops.reduced_shape(sp_shape, op.inputs[3]) + out_grad_reshaped = array_ops.reshape(out_grad, output_shape_kept_dims) + scale = sp_shape // math_ops.cast(output_shape_kept_dims, dtypes.int64) + # (sparse_indices, sparse_values, sparse_shape, reduction_axes) + return (None, array_ops.gather_nd(out_grad_reshaped, + sp_indices // scale), None, None) + + +@ops.RegisterGradient("SparseSlice") +def _SparseSliceGrad(op: ops.Operation, *grads): + """The backward operator for the SparseSlice op. + + This op takes in the upstream gradient w.r.t. non-empty values of + the sliced `SparseTensor`, and outputs the gradients w.r.t. + the non-empty values of input `SparseTensor`. + + Args: + op: the SparseSlice op + *grads: the incoming gradients, one element per output of `op` + + Returns: + Gradient for each of the 5 input tensors of SparseSlice: + (indices, values, shape, start, size) + The gradients for the indices, shape, start and the size are None. + """ + backprop_val_grad = grads[1] + input_indices = op.inputs[0] + input_start = op.inputs[3] + output_indices = op.outputs[0] + + val_grad = gen_sparse_ops.sparse_slice_grad(backprop_val_grad, input_indices, + input_start, output_indices) + val_grad.set_shape(op.inputs[1].get_shape()) + # (indices, values, shape, start, size) + return (None, val_grad, None, None, None) + + +@ops.RegisterGradient("SparseTensorDenseMatMul") +def _SparseTensorDenseMatMulGrad(op: ops.Operation, grad): + """Gradients for the dense tensor in the SparseTensorDenseMatMul op. + + Args: + op: the SparseTensorDenseMatMul op + grad: the incoming gradient + + Returns: + Gradient for each of the 4 input tensors: + (sparse_indices, sparse_values, sparse_shape, dense_tensor) + The gradients for indices and shape are None. + + Raises: + TypeError: When the two operands don't have the same type. + """ + a_indices, a_values, a_shape = op.inputs[:3] + b = op.inputs[3] + adj_a = op.get_attr("adjoint_a") + adj_b = op.get_attr("adjoint_b") + + a_type = a_values.dtype.base_dtype + b_type = b.dtype.base_dtype + if a_type != b_type: + raise TypeError( + f"SparseTensorDenseMatMul op received operands with different types: " + f"`{a_type}` and `{b_type}`.") + + # gradient w.r.t. dense + b_grad = gen_sparse_ops.sparse_tensor_dense_mat_mul( + a_indices, a_values, a_shape, grad, adjoint_a=not adj_a) + if adj_b: + b_grad = array_ops.matrix_transpose(b_grad, conjugate=True) + + # gradient w.r.t. sparse values + + # TODO(zongheng): these gather calls could potentially duplicate rows/cols in + # memory. If there is a need, we should look into implementing this more + # intelligently to avoid duplicating data. + + # With no adjoints, a_grad is matmul(grad, adjoint(b)). Since a is sparse, we + # just want to compute that matmul at the rows/columns of non-zero values. The + # (r, c) value is sum(grad[r, :] * adjoint(b)[:, c]), where the latter term is + # more conveniently written as conj(b)[c, :]. That expression is more + # efficient to calculate as a matmul, after expanding the two terms to be 2D + # (i.e. a row vector and a column vector). + # + # If adj_b then we replace conj(b) by transpose(b); if adj_a we need to + # adjoint the result, which is equivalent to swapping r and c and taking + # conjugates. + + # Get grad[r, :] and b[c, :] (or with r and c swapped if adj_a, or with + # transpose(b) if adj_b), as batches of vectors (with the batch dimension + # corresponding to the non-zero indices of a). + rows = a_indices[:, 0] + cols = a_indices[:, 1] + parts_a = array_ops.gather(grad, rows if not adj_a else cols) + parts_b = array_ops.gather( + b if not adj_b else array_ops.transpose(b), cols if not adj_a else rows) + + if not adj_a and not adj_b: + # grad[r, :] * conj(b[c, :]) = row(grad[r, :]) @ adjoint(row(b[c, :])) + a_values_grad = math_ops.matmul( + array_ops.expand_dims(parts_a, -2), + array_ops.expand_dims(parts_b, -2), + adjoint_b=True) + elif adj_a and not adj_b: + # conj(grad[c, :] * conj(b[r, :])) = adjoint(col(grad[c, :])) @ col(b[r, :]) + a_values_grad = math_ops.matmul( + array_ops.expand_dims(parts_a, -1), + array_ops.expand_dims(parts_b, -1), + adjoint_a=True) + elif not adj_a and adj_b: + # grad[r, :] * transpose(b)[c, :] = + # row(grad[r, :]) @ col(transpose(b)[c, :]) + a_values_grad = math_ops.matmul( + array_ops.expand_dims(parts_a, -2), array_ops.expand_dims(parts_b, -1)) + elif adj_a and adj_b: + # conj(grad[c, :] * transpose(b)[r, :]) = + # adjoint(col(grad[c, :])) @ adjoint(row(transpose(b)[r, :]) + a_values_grad = math_ops.matmul( + array_ops.expand_dims(parts_a, -1), + array_ops.expand_dims(parts_b, -2), + adjoint_a=True, + adjoint_b=True) + + # gradients w.r.t. (a_indices, a_values, a_shape, b) + return (None, array_ops.squeeze(a_values_grad, axis=[-2, -1]), None, b_grad) + + +@ops.RegisterGradient("SparseDenseCwiseAdd") +def _SparseDenseCwiseAddGrad(unused_op, unused_grad): + raise NotImplementedError( + "Gradient for SparseDenseCwiseAdd is not implemented.") + + +def _SparseDenseCwiseMulOrDivGrad(op: ops.Operation, grad, is_mul): + """Common code for SparseDenseCwise{Mul,Div} gradients.""" + x_indices = op.inputs[0] + x_shape = op.inputs[2] + y = op.inputs[3] + + y_shape = math_ops.cast(array_ops.shape(y), dtypes.int64) + num_added_dims = array_ops.expand_dims( + array_ops.size(x_shape) - array_ops.size(y_shape), 0) + augmented_y_shape = array_ops.concat( + [array_ops.ones(num_added_dims, ops.dtypes.int64), y_shape], 0) + + scaling = x_shape // augmented_y_shape + scaled_indices = x_indices // scaling + scaled_indices = array_ops.slice(scaled_indices, + array_ops.concat([[0], num_added_dims], 0), + [-1, -1]) + dense_vals = array_ops.gather_nd(y, scaled_indices) + + if is_mul: + dx = grad * dense_vals + dy_val = grad * op.inputs[1] + else: + dx = grad / dense_vals + dy_val = grad * (-op.inputs[1] / math_ops.square(dense_vals)) + # indices can repeat after scaling, so we can't use sparse_to_dense(). + dy = sparse_ops.sparse_add( + array_ops.zeros_like(y), + sparse_tensor.SparseTensor(scaled_indices, dy_val, y_shape)) + + # (sp_indices, sp_vals, sp_shape, dense) + return (None, dx, None, dy) + + +@ops.RegisterGradient("SparseDenseCwiseMul") +def _SparseDenseCwiseMulGrad(op: ops.Operation, grad): + """Gradients for SparseDenseCwiseMul.""" + return _SparseDenseCwiseMulOrDivGrad(op, grad, True) + + +@ops.RegisterGradient("SparseDenseCwiseDiv") +def _SparseDenseCwiseDivGrad(op: ops.Operation, grad): + """Gradients for SparseDenseCwiseDiv.""" + return _SparseDenseCwiseMulOrDivGrad(op, grad, False) + + +@ops.RegisterGradient("SparseSoftmax") +def _SparseSoftmaxGrad(op: ops.Operation, grad): + """Gradients for SparseSoftmax. + + The calculation is the same as SoftmaxGrad: + + grad_x = grad_softmax * softmax - sum(grad_softmax * softmax) * softmax + + where we now only operate on the non-zero values present in the SparseTensors. + + Args: + op: the SparseSoftmax op. + grad: the upstream gradient w.r.t. the non-zero SparseSoftmax output values. + + Returns: + Gradients w.r.t. the input (sp_indices, sp_values, sp_shape). + """ + indices, shape = op.inputs[0], op.inputs[2] + out_vals = op.outputs[0] + sp_output = sparse_tensor.SparseTensor(indices, out_vals, shape) + sp_grad = sparse_tensor.SparseTensor(indices, grad, shape) + sp_product = sparse_tensor.SparseTensor(indices, + sp_output.values * sp_grad.values, + shape) + + # [..., B, 1], dense. + sum_reduced = -sparse_ops.sparse_reduce_sum(sp_product, [-1], keepdims=True) + # sparse [..., B, C] + dense [..., B, 1] with broadcast; outputs sparse. + sp_sum = sparse_ops.sparse_dense_cwise_add(sp_grad, sum_reduced) + + grad_x = sp_sum.values * sp_output.values + return [None, grad_x, None] + + +@ops.RegisterGradient("SparseSparseMaximum") +def _SparseSparseMaximumGrad(unused_op: ops.Operation, unused_grad): + raise NotImplementedError( + "Gradient for SparseSparseMaximum is not implemented." + ) + + +@ops.RegisterGradient("SparseSparseMinimum") +def _SparseSparseMinimumGrad(unused_op: ops.Operation, unused_grad): + raise NotImplementedError( + "Gradient for SparseSparseMinimum is not implemented." + ) + + +@ops.RegisterGradient("SparseFillEmptyRows") +def _SparseFillEmptyRowsGrad( + op: ops.Operation, + unused_grad_output_indices, + output_grad_values, + unused_grad_empty_row_indicator, + unused_grad_reverse_index_map, +): + """Gradients for SparseFillEmptyRows.""" + reverse_index_map = op.outputs[3] + + d_values, d_default_value = gen_sparse_ops.sparse_fill_empty_rows_grad( + reverse_index_map=reverse_index_map, grad_values=output_grad_values + ) + + # d_indices, d_values, d_dense_shape, d_default_value. + return [None, d_values, None, d_default_value] + + +@ops.RegisterGradient("SparseToDense") +def _SparseToDenseGrad(op: ops.Operation, grad): + sparse_indices, output_shape, _, _ = op.inputs + + sparse_values_grad = array_ops.gather_nd(grad, sparse_indices) + default_value_grad = math_ops.reduce_sum(grad) - math_ops.reduce_sum( + sparse_values_grad) + return [ + array_ops.zeros_like(sparse_indices), + array_ops.zeros_like(output_shape), sparse_values_grad, default_value_grad + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..74cc5e4eddfd0a3af8d62587217351ebed3404b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/sparse_ops.py @@ -0,0 +1,3698 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=g-short-docstring-punctuation +"""Sparse Tensor Representation. + +See also `tf.sparse.SparseTensor`. + +API docstring: tensorflow.sparse +""" + +import numbers + +import numpy as np + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import bincount_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_count_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import special_math_ops +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_sparse_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import get_canonical_name_for_symbol +from tensorflow.python.util.tf_export import tf_export + + +def _convert_to_sparse_tensor(sp_input): + """Convert `sp_input` to `SparseTensor` and return it. + + Args: + sp_input: `SparseTensor` or `SparseTensorValue`. + + Returns: + `sp_input` converted to `SparseTensor`. + + Raises: + ValueError: if `sp_input` is neither `SparseTensor` nor `SparseTensorValue`. + """ + if isinstance(sp_input, sparse_tensor.SparseTensorValue): + return sparse_tensor.SparseTensor.from_value(sp_input) + if not isinstance(sp_input, sparse_tensor.SparseTensor): + raise TypeError("Input must be a SparseTensor.") + return sp_input + + +def _convert_to_sparse_tensors(sp_inputs): + """Convert `sp_inputs` to `SparseTensor` objects and return them. + + Args: + sp_inputs: `list` or `tuple` of `SparseTensor` or `SparseTensorValue` + objects. + + Returns: + `sp_inputs` converted to `SparseTensor` objects. + + Raises: + ValueError: if any item in `sp_inputs` is neither `SparseTensor` nor + `SparseTensorValue`. + """ + if isinstance(sp_inputs, list): + return [_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs] + if isinstance(sp_inputs, tuple): + return (_convert_to_sparse_tensor(sp_input) for sp_input in sp_inputs) + raise TypeError("Inputs must be a list or tuple.") + + +def _make_int64_tensor(value, name): + if isinstance(value, compat.integral_types): + return ops.convert_to_tensor(value, name=name, dtype=dtypes.int64) + if not isinstance(value, tensor_lib.Tensor): + raise TypeError("{} must be an integer value".format(name)) + if value.dtype == dtypes.int64: + return value + return math_ops.cast(value, dtypes.int64) + + +@tf_export("sparse.from_dense") +def from_dense(tensor, name=None): + """Converts a dense tensor into a sparse tensor. + + Only elements not equal to zero will be present in the result. The resulting + `SparseTensor` has the same dtype and shape as the input. + + >>> sp = tf.sparse.from_dense([0, 0, 3, 0, 1]) + >>> sp.shape.as_list() + [5] + >>> sp.values.numpy() + array([3, 1], dtype=int32) + >>> sp.indices.numpy() + array([[2], + [4]]) + + Args: + tensor: A dense `Tensor` to be converted to a `SparseTensor`. + name: Optional name for the op. + + Returns: + The `SparseTensor`. + """ + with ops.name_scope(name, "dense_to_sparse"): + tensor = ops.convert_to_tensor(tensor) + indices = array_ops.where_v2( + math_ops.not_equal(tensor, array_ops.zeros_like(tensor))) + values = array_ops.gather_nd(tensor, indices) + shape = array_ops.shape(tensor, out_type=dtypes.int64) + return sparse_tensor.SparseTensor(indices, values, shape) + + +@tf_export("sparse.expand_dims") +def sparse_expand_dims(sp_input, axis=None, name=None): + """Returns a tensor with an length 1 axis inserted at index `axis`. + + Given a tensor `input`, this operation inserts a dimension of length 1 at the + dimension index `axis` of `input`'s shape. The dimension index follows python + indexing rules: It's zero-based, a negative index it is counted backward + from the end. + + This operation is useful to: + + * Add an outer "batch" dimension to a single element. + * Align axes for broadcasting. + * To add an inner vector length axis to a tensor of scalars. + + For example: + + If you have a sparse tensor with shape `[height, width, depth]`: + + >>> sp = tf.sparse.SparseTensor(indices=[[3,4,1]], values=[7,], + ... dense_shape=[10,10,3]) + + You can add an outer `batch` axis by passing `axis=0`: + + >>> tf.sparse.expand_dims(sp, axis=0).shape.as_list() + [1, 10, 10, 3] + + The new axis location matches Python `list.insert(axis, 1)`: + + >>> tf.sparse.expand_dims(sp, axis=1).shape.as_list() + [10, 1, 10, 3] + + Following standard python indexing rules, a negative `axis` counts from the + end so `axis=-1` adds an inner most dimension: + + >>> tf.sparse.expand_dims(sp, axis=-1).shape.as_list() + [10, 10, 3, 1] + + Note: Unlike `tf.expand_dims` this function includes a default value for the + `axis`: `-1`. So if `axis is not specified, an inner dimension is added. + + >>> sp.shape.as_list() + [10, 10, 3] + >>> tf.sparse.expand_dims(sp).shape.as_list() + [10, 10, 3, 1] + + This operation requires that `axis` is a valid index for `input.shape`, + following python indexing rules: + + ``` + -1-tf.rank(input) <= axis <= tf.rank(input) + ``` + + This operation is related to: + + * `tf.expand_dims`, which provides this functionality for dense tensors. + * `tf.squeeze`, which removes dimensions of size 1, from dense tensors. + * `tf.sparse.reshape`, which provides more flexible reshaping capability. + + Args: + sp_input: A `SparseTensor`. + axis: 0-D (scalar). Specifies the dimension index at which to expand the + shape of `input`. Must be in the range `[-rank(sp_input) - 1, + rank(sp_input)]`. Defaults to `-1`. + name: The name of the output `SparseTensor`. + + Returns: + A `SparseTensor` with the same data as `sp_input`, but its shape has an + additional dimension of size 1 added. + """ + rank = sp_input.dense_shape.get_shape()[0] + if rank is None: + rank = array_ops.shape(sp_input.dense_shape)[0] + axis = -1 if axis is None else axis + + with ops.name_scope(name, default_name="expand_dims", values=[sp_input]): + if isinstance(axis, compat.integral_types): + axis = ops.convert_to_tensor(axis, name="axis", dtype=dtypes.int32) + elif not isinstance(axis, tensor_lib.Tensor): + raise TypeError("axis must be an integer value in range [-rank(sp_input)" + " - 1, rank(sp_input)]") + + # Convert axis to a positive value if it is negative. + axis = array_ops.where_v2(axis >= 0, axis, axis + rank + 1) + + # Create the new column of indices for the sparse tensor by slicing + # the indices and inserting a new column of indices for the new dimension. + column_size = array_ops.shape(sp_input.indices)[0] + new_index = array_ops.zeros([column_size, 1], dtype=dtypes.int64) + indices_before = array_ops.slice(sp_input.indices, [0, 0], [-1, axis]) + indices_after = array_ops.slice(sp_input.indices, [0, axis], [-1, -1]) + indices = array_ops.concat( + [indices_before, new_index, indices_after], axis=1) + + # Create the new dense shape by splicing the tensor [1] in the correct + # dimension of the existing shape. + shape_before = array_ops.slice(sp_input.dense_shape, [0], [axis]) + shape_after = array_ops.slice(sp_input.dense_shape, [axis], [-1]) + new_shape = ops.convert_to_tensor([1], name="new_shape", dtype=dtypes.int64) + shape = array_ops.concat([shape_before, new_shape, shape_after], axis=0) + + # Create the output sparse tensor. + return sparse_tensor.SparseTensor( + indices=indices, values=sp_input.values, dense_shape=shape) + + +@tf_export("sparse.eye") +def sparse_eye(num_rows, + num_columns=None, + dtype=dtypes.float32, + name=None): + """Creates a two-dimensional sparse tensor with ones along the diagonal. + + Args: + num_rows: Non-negative integer or `int32` scalar `tensor` giving the number + of rows in the resulting matrix. + num_columns: Optional non-negative integer or `int32` scalar `tensor` giving + the number of columns in the resulting matrix. Defaults to `num_rows`. + dtype: The type of element in the resulting `Tensor`. + name: A name for this `Op`. Defaults to "eye". + + Returns: + A `SparseTensor` of shape [num_rows, num_columns] with ones along the + diagonal. + """ + with ops.name_scope(name, default_name="eye", values=[num_rows, num_columns]): + num_rows = _make_int64_tensor(num_rows, "num_rows") + num_columns = num_rows if num_columns is None else _make_int64_tensor( + num_columns, "num_columns") + + # Create the sparse tensor. + diag_size = math_ops.minimum(num_rows, num_columns) + diag_range = math_ops.range(diag_size, dtype=dtypes.int64) + + return sparse_tensor.SparseTensor( + indices=array_ops_stack.stack([diag_range, diag_range], axis=1), + values=array_ops.ones(diag_size, dtype=dtype), + dense_shape=[num_rows, num_columns]) + + +# pylint: disable=protected-access +@tf_export(v1=["sparse.concat", "sparse_concat"]) +@deprecation.deprecated_endpoints("sparse_concat") +@deprecation.deprecated_args( + None, "concat_dim is deprecated, use axis instead", "concat_dim") +def sparse_concat(axis, + sp_inputs, + name=None, + expand_nonconcat_dim=False, + concat_dim=None, + expand_nonconcat_dims=None): + """Concatenates a list of `SparseTensor` along the specified dimension. + + Concatenation is with respect to the dense versions of each sparse input. + It is assumed that each inputs is a `SparseTensor` whose elements are ordered + along increasing dimension number. + + If expand_nonconcat_dim is False, all inputs' shapes must match, except for + the concat dimension. If expand_nonconcat_dim is True, then inputs' shapes are + allowed to vary among all inputs. + + The `indices`, `values`, and `shapes` lists must have the same length. + + If expand_nonconcat_dim is False, then the output shape is identical to the + inputs', except along the concat dimension, where it is the sum of the inputs' + sizes along that dimension. + + If expand_nonconcat_dim is True, then the output shape along the non-concat + dimensions will be expand to be the largest among all inputs, and it is the + sum of the inputs sizes along the concat dimension. + + The output elements will be resorted to preserve the sort order along + increasing dimension number. + + This op runs in `O(M log M)` time, where `M` is the total number of non-empty + values across all inputs. This is due to the need for an internal sort in + order to concatenate efficiently across an arbitrary dimension. + + For example, if `axis = 1` and the inputs are + + sp_inputs[0]: shape = [2, 3] + [0, 2]: "a" + [1, 0]: "b" + [1, 1]: "c" + + sp_inputs[1]: shape = [2, 4] + [0, 1]: "d" + [0, 2]: "e" + + then the output will be + + shape = [2, 7] + [0, 2]: "a" + [0, 4]: "d" + [0, 5]: "e" + [1, 0]: "b" + [1, 1]: "c" + + Graphically this is equivalent to doing + + [ a] concat [ d e ] = [ a d e ] + [b c ] [ ] [b c ] + + Another example, if 'axis = 1' and the inputs are + + sp_inputs[0]: shape = [3, 3] + [0, 2]: "a" + [1, 0]: "b" + [2, 1]: "c" + + sp_inputs[1]: shape = [2, 4] + [0, 1]: "d" + [0, 2]: "e" + + if expand_nonconcat_dim = False, this will result in an error. But if + expand_nonconcat_dim = True, this will result in: + + shape = [3, 7] + [0, 2]: "a" + [0, 4]: "d" + [0, 5]: "e" + [1, 0]: "b" + [2, 1]: "c" + + Graphically this is equivalent to doing + + [ a] concat [ d e ] = [ a d e ] + [b ] [ ] [b ] + [ c ] [ c ] + + + Args: + axis: Dimension to concatenate along. Must be in range [-rank, rank), + where rank is the number of dimensions in each input `SparseTensor`. + sp_inputs: List of `SparseTensor` to concatenate. + name: A name prefix for the returned tensors (optional). + expand_nonconcat_dim: Whether to allow the expansion in the non-concat + dimensions. Defaulted to False. + concat_dim: The old (deprecated) name for axis. + expand_nonconcat_dims: alias for expand_nonconcat_dim + + Returns: + A `SparseTensor` with the concatenated output. + + Raises: + TypeError: If `sp_inputs` is not a list of `SparseTensor`. + """ + expand_nonconcat_dim = deprecation.deprecated_argument_lookup( + "expand_nonconcat_dims", expand_nonconcat_dims, + "expand_nonconcat_dim", expand_nonconcat_dim) + if expand_nonconcat_dims is not None: + expand_nonconcat_dim = expand_nonconcat_dims + axis = deprecation.deprecated_argument_lookup("axis", axis, "concat_dim", + concat_dim) + return sparse_concat_v2(axis, sp_inputs, expand_nonconcat_dim, name) + + +@tf_export("sparse.concat", v1=[]) +def sparse_concat_v2(axis, sp_inputs, expand_nonconcat_dims=False, name=None): # pylint: disable=missing-docstring + sp_inputs = _convert_to_sparse_tensors(sp_inputs) + + if len(sp_inputs) == 1: # Degenerate case of one tensor. + return sp_inputs[0] + + inds = [sp_input.indices for sp_input in sp_inputs] + vals = [sp_input.values for sp_input in sp_inputs] + shapes = [sp_input.dense_shape for sp_input in sp_inputs] + + if expand_nonconcat_dims: + max_shape = math_ops.reduce_max( + array_ops.concat( + [array_ops.reshape(shape, [1, -1]) for shape in shapes], 0), 0) + shapes = [ + array_ops.concat([ + max_shape[:axis], shape[-1:] + if axis == -1 else shape[axis:axis + 1], [] + if axis == -1 else max_shape[axis + 1:] + ], 0) for shape in shapes + ] + + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_concat(inds, vals, shapes, axis, name=name)) + + input_shapes = [inp.shape for inp in sp_inputs] + if all(shape.rank is not None for shape in input_shapes): + if expand_nonconcat_dims: + static_output_shape = [] + for dim in range(input_shapes[0].rank): + static_output_shape.append( + max(tensor_shape.dimension_at_index(shape, dim) + for shape in input_shapes)) + else: + static_output_shape = input_shapes[0].as_list() + static_output_shape[axis] = sum( + tensor_shape.dimension_at_index(shape, axis) + for shape in input_shapes) + else: + static_output_shape = tensor_shape.unknown_shape() + if all(shape.is_fully_defined() for shape in input_shapes): + output_shape = ops.convert_to_tensor(static_output_shape, + dtype=dtypes.int64) + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + else: + # In case there are partially defined shape, we couldn't update the + # output_shape tensor value. We update the output._dense_shape_default, + # which populate output.shape as the best effort. + output = sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + output.set_shape(tensor_shape.TensorShape(static_output_shape)) + return output + + +sparse_concat_v2.__doc__ = sparse_concat.__doc__.replace( + " concat_dim: The old (deprecated) name for axis.\n", + "").replace(" expand_nonconcat_dims: alias for expand_nonconcat_dim\n", + "") + + +@tf_export(v1=["sparse.add", "sparse_add"]) +@deprecation.deprecated_endpoints("sparse_add") +@deprecation.deprecated_args( + None, "thresh is deprecated, use threshold instead", "thresh") +def sparse_add(a, b, threshold=None, thresh=None): + """Adds two tensors, at least one of each is a `SparseTensor`. + + If one `SparseTensor` and one `Tensor` are passed in, returns a `Tensor`. If + both arguments are `SparseTensor`s, this returns a `SparseTensor`. The order + of arguments does not matter. Use vanilla `tf.add()` for adding two dense + `Tensor`s. + + The shapes of the two operands must match: broadcasting is not supported. + + The indices of any input `SparseTensor` are assumed ordered in standard + lexicographic order. If this is not the case, before this step run + `SparseReorder` to restore index ordering. + + If both arguments are sparse, we perform "clipping" as follows. By default, + if two values sum to zero at some index, the output `SparseTensor` would still + include that particular location in its index, storing a zero in the + corresponding value slot. To override this, callers can specify `thresh`, + indicating that if the sum has a magnitude strictly smaller than `thresh`, its + corresponding value and index would then not be included. In particular, + `thresh == 0.0` (default) means everything is kept and actual thresholding + happens only for a positive value. + + For example, suppose the logical sum of two sparse operands is (densified): + + [ 2] + [.1 0] + [ 6 -.2] + + Then, + + * `thresh == 0` (the default): all 5 index/value pairs will be returned. + * `thresh == 0.11`: only .1 and 0 will vanish, and the remaining three + index/value pairs will be returned. + * `thresh == 0.21`: .1, 0, and -.2 will vanish. + + Args: + a: The first operand; `SparseTensor` or `Tensor`. + b: The second operand; `SparseTensor` or `Tensor`. At least one operand + must be sparse. + threshold: An optional 0-D `Tensor` (defaults to `0`). The magnitude + threshold that determines if an output value/index pair takes space. Its + dtype should match that of the values if they are real; if the latter are + complex64/complex128, then the dtype should be float32/float64, + correspondingly. + thresh: Deprecated alias for `threshold`. + + Returns: + A `SparseTensor` or a `Tensor`, representing the sum. + + Raises: + TypeError: If both `a` and `b` are `Tensor`s. Use `tf.add()` instead. + """ + threshold = deprecation.deprecated_argument_lookup("threshold", threshold, + "thresh", thresh) + if threshold is None: + threshold = 0 + return sparse_add_v2(a, b, threshold) + + +@tf_export("sparse.add", v1=[]) +def sparse_add_v2(a, b, threshold=0): + """Adds two tensors, at least one of each is a `SparseTensor`. + + If one `SparseTensor` and one `Tensor` are passed in, returns a `Tensor`. If + both arguments are `SparseTensor`s, this returns a `SparseTensor`. The order + of arguments does not matter. Use vanilla `tf.add()` for adding two dense + `Tensor`s. + + The shapes of the two operands must match: broadcasting is not supported. + + The indices of any input `SparseTensor` are assumed ordered in standard + lexicographic order. If this is not the case, before this step run + `SparseReorder` to restore index ordering. + + If both arguments are sparse, we perform "clipping" as follows. By default, + if two values sum to zero at some index, the output `SparseTensor` would still + include that particular location in its index, storing a zero in the + corresponding value slot. To override this, callers can specify `threshold`, + indicating that if the sum has a magnitude strictly smaller than `threshold`, + its corresponding value and index would then not be included. In particular, + `threshold == 0.0` (default) means everything is kept and actual thresholding + happens only for a positive value. + + For example, suppose the logical sum of two sparse operands is (densified): + + [ 2] + [.1 0] + [ 6 -.2] + + Then, + + * `threshold == 0` (the default): all 5 index/value pairs will be + returned. + * `threshold == 0.11`: only .1 and 0 will vanish, and the remaining three + index/value pairs will be returned. + * `threshold == 0.21`: .1, 0, and -.2 will vanish. + + Args: + a: The first operand; `SparseTensor` or `Tensor`. + b: The second operand; `SparseTensor` or `Tensor`. At least one operand + must be sparse. + threshold: A 0-D `Tensor`. The magnitude threshold that determines if an + output value/index pair takes space. Its dtype should match that of the + values if they are real; if the latter are complex64/complex128, then the + dtype should be float32/float64, correspondingly. + + Returns: + A `SparseTensor` or a `Tensor`, representing the sum. + + Raises: + TypeError: If both `a` and `b` are `Tensor`s. Use `tf.add()` instead. + """ + sparse_classes = (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue) + if not any(isinstance(inp, sparse_classes) for inp in [a, b]): + raise TypeError("At least one input should be SparseTensor; do you mean to" + " use tf.add()?") + + if all(isinstance(inp, sparse_classes) for inp in [a, b]): + a = _convert_to_sparse_tensor(a) + b = _convert_to_sparse_tensor(b) + threshold = ops.convert_to_tensor( + threshold, dtype=a.values.dtype.real_dtype.base_dtype, name="threshold") + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_add(a.indices, a.values, a.dense_shape, + b.indices, b.values, b.dense_shape, + threshold)) + + # Attempt to get output_shape statically. + a.get_shape().assert_is_compatible_with(b.get_shape()) + static_shape = array_ops.broadcast_static_shape(a.get_shape(), + b.get_shape()) + if static_shape.is_fully_defined(): + output_shape = static_shape.as_list() + + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + else: + # swap to make `a` the SparseTensor. + if isinstance(b, sparse_classes): + a, b = b, a + return gen_sparse_ops.sparse_tensor_dense_add(a.indices, a.values, + a.dense_shape, b) + + +@tf_export("sparse.cross") +def sparse_cross(inputs, name=None, separator=None): + """Generates sparse cross from a list of sparse and dense tensors. + + For example, if the inputs are + + * inputs[0]: SparseTensor with shape = [2, 2] + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + * inputs[1]: SparseTensor with shape = [2, 1] + [0, 0]: "d" + [1, 0]: "e" + * inputs[2]: Tensor [["f"], ["g"]] + + then the output will be: + + shape = [2, 2] + [0, 0]: "a_X_d_X_f" + [1, 0]: "b_X_e_X_g" + [1, 1]: "c_X_e_X_g" + + Customized separator "_Y_": + + >>> inp_0 = tf.constant([['a'], ['b']]) + >>> inp_1 = tf.constant([['c'], ['d']]) + >>> output = tf.sparse.cross([inp_0, inp_1], separator='_Y_') + >>> output.values + + + + Args: + inputs: An iterable of `Tensor` or `SparseTensor`. + name: Optional name for the op. + separator: A string added between each string being joined. Defaults to + '_X_'. + + Returns: + A `SparseTensor` of type `string`. + """ + if separator is None: + separator = "_X_" + separator = ops.convert_to_tensor(separator, dtypes.string) + indices, values, shapes, dense_inputs = _sparse_cross_internal_v2(inputs) + indices_out, values_out, shape_out = gen_sparse_ops.sparse_cross_v2( + indices=indices, + values=values, + shapes=shapes, + dense_inputs=dense_inputs, + sep=separator, + name=name) + return sparse_tensor.SparseTensor(indices_out, values_out, shape_out) + + +_sparse_cross = sparse_cross + + +@tf_export("sparse.cross_hashed") +def sparse_cross_hashed(inputs, num_buckets=0, hash_key=None, name=None): + """Generates hashed sparse cross from a list of sparse and dense tensors. + + For example, if the inputs are + + * inputs[0]: SparseTensor with shape = [2, 2] + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + * inputs[1]: SparseTensor with shape = [2, 1] + [0, 0]: "d" + [1, 0]: "e" + * inputs[2]: Tensor [["f"], ["g"]] + + then the output will be: + + shape = [2, 2] + [0, 0]: FingerprintCat64( + Fingerprint64("f"), FingerprintCat64( + Fingerprint64("d"), Fingerprint64("a"))) + [1, 0]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("b"))) + [1, 1]: FingerprintCat64( + Fingerprint64("g"), FingerprintCat64( + Fingerprint64("e"), Fingerprint64("c"))) + + Args: + inputs: An iterable of `Tensor` or `SparseTensor`. + num_buckets: An `int` that is `>= 0`. + output = hashed_value%num_buckets if num_buckets > 0 else hashed_value. + hash_key: Integer hash_key that will be used by the `FingerprintCat64` + function. If not given, will use a default key. + name: Optional name for the op. + + Returns: + A `SparseTensor` of type `int64`. + """ + return _sparse_cross_internal( + inputs=inputs, + hashed_output=True, + num_buckets=num_buckets, + hash_key=hash_key, + name=name) + + +_sparse_cross_hashed = sparse_cross_hashed + +_DEFAULT_HASH_KEY = 0xDECAFCAFFE + + +def _sparse_cross_internal_v2(inputs): + """See gen_sparse_ops.sparse_cross_v2.""" + if not isinstance(inputs, (tuple, list)): + raise TypeError("Inputs must be a list") + if not all( + isinstance( + i, sparse_tensor.SparseTensor) or isinstance(i, tensor_lib.Tensor) + for i in inputs): + raise TypeError("All inputs must be Tensor or SparseTensor.") + sparse_inputs = [ + i for i in inputs if isinstance(i, sparse_tensor.SparseTensor) + ] + dense_inputs = [ + i for i in inputs if not isinstance(i, sparse_tensor.SparseTensor) + ] + indices = [sp_input.indices for sp_input in sparse_inputs] + values = [sp_input.values for sp_input in sparse_inputs] + shapes = [sp_input.dense_shape for sp_input in sparse_inputs] + for i in range(len(values)): + if values[i].dtype != dtypes.string: + values[i] = math_ops.cast(values[i], dtypes.int64) + for i in range(len(dense_inputs)): + if dense_inputs[i].dtype != dtypes.string: + dense_inputs[i] = math_ops.cast(dense_inputs[i], dtypes.int64) + return indices, values, shapes, dense_inputs + + +def _sparse_cross_internal(inputs, + hashed_output=False, + num_buckets=0, + hash_key=None, + name=None): + """See gen_sparse_ops.sparse_cross.""" + if not isinstance(inputs, (tuple, list)): + raise TypeError("Inputs must be a list") + if not all( + isinstance( + i, sparse_tensor.SparseTensor) or isinstance(i, tensor_lib.Tensor) + for i in inputs): + raise TypeError("All inputs must be SparseTensors") + + sparse_inputs = [ + i for i in inputs if isinstance(i, sparse_tensor.SparseTensor) + ] + dense_inputs = [ + i for i in inputs if not isinstance(i, sparse_tensor.SparseTensor) + ] + + indices = [sp_input.indices for sp_input in sparse_inputs] + values = [sp_input.values for sp_input in sparse_inputs] + shapes = [sp_input.dense_shape for sp_input in sparse_inputs] + out_type = dtypes.int64 if hashed_output else dtypes.string + + internal_type = dtypes.string + for i in range(len(values)): + if values[i].dtype != dtypes.string: + values[i] = math_ops.cast(values[i], dtypes.int64) + internal_type = dtypes.int64 + for i in range(len(dense_inputs)): + if dense_inputs[i].dtype != dtypes.string: + dense_inputs[i] = math_ops.cast(dense_inputs[i], dtypes.int64) + internal_type = dtypes.int64 + + indices_out, values_out, shape_out = gen_sparse_ops.sparse_cross( + indices=indices, + values=values, + shapes=shapes, + dense_inputs=dense_inputs, + hashed_output=hashed_output, + num_buckets=num_buckets, + hash_key=hash_key or _DEFAULT_HASH_KEY, + out_type=out_type, + internal_type=internal_type, + name=name) + + return sparse_tensor.SparseTensor(indices_out, values_out, shape_out) + + +def sparse_dense_cwise_add(sp_t, dense_t): + """Adds up a SparseTensor and a dense Tensor, using these special rules: + + (1) Broadcasts the dense side to have the same shape as the sparse side, if + eligible; + (2) Then, only the dense values pointed to by the indices of the SparseTensor + participate in the cwise addition. + + By the rules, the result is a logical SparseTensor with exactly the same + indices and shape, but possibly with different non-zero values. The output of + this Op is the resultant non-zero values. + + Args: + sp_t: the SparseTensor operand. + dense_t: the dense Tensor operand; must have the same dtype and a + broadcast-compatible shape as `sp_t`. + + Returns: + output: the SparseTensor output. + """ + result = gen_sparse_ops.sparse_dense_cwise_add(sp_t.indices, sp_t.values, + sp_t.dense_shape, dense_t) + return sparse_tensor.SparseTensor(sp_t.indices, result, sp_t.dense_shape) + + +@tf_export("sparse.reorder", v1=["sparse.reorder", "sparse_reorder"]) +@deprecation.deprecated_endpoints("sparse_reorder") +def sparse_reorder(sp_input, name=None): + """Reorders a `SparseTensor` into the canonical, row-major ordering. + + Note that by convention, all sparse ops preserve the canonical ordering + along increasing dimension number. The only time ordering can be violated + is during manual manipulation of the indices and values to add entries. + + Reordering does not affect the shape of the `SparseTensor`. + + For example, if `sp_input` has shape `[4, 5]` and `indices` / `values`: + + [0, 3]: b + [0, 1]: a + [3, 1]: d + [2, 0]: c + + then the output will be a `SparseTensor` of shape `[4, 5]` and + `indices` / `values`: + + [0, 1]: a + [0, 3]: b + [2, 0]: c + [3, 1]: d + + Args: + sp_input: The input `SparseTensor`. + name: A name prefix for the returned tensors (optional) + + Returns: + A `SparseTensor` with the same shape and non-empty values, but in + canonical ordering. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + reordered_ind, reordered_val = ( + gen_sparse_ops.sparse_reorder( + sp_input.indices, sp_input.values, sp_input.dense_shape, name=name)) + + if sp_input.get_shape().is_fully_defined(): + dense_shape = sp_input.get_shape().as_list() + return sparse_tensor.SparseTensor(reordered_ind, reordered_val, dense_shape) + else: + dense_shape = array_ops.identity(sp_input.dense_shape) + sp_output = sparse_tensor.SparseTensor(reordered_ind, reordered_val, + dense_shape) + # propagate the static shape + sp_output.set_shape(sp_input.shape) + return sp_output + + +@tf_export("sparse.reshape", v1=["sparse.reshape", "sparse_reshape"]) +@deprecation.deprecated_endpoints("sparse_reshape") +@dispatch.add_dispatch_support +def sparse_reshape(sp_input, shape, name=None): + """Reshapes a `SparseTensor` to represent values in a new dense shape. + + This operation has the same semantics as `reshape` on the represented dense + tensor. The indices of non-empty values in `sp_input` are recomputed based + on the new dense shape, and a new `SparseTensor` is returned containing the + new indices and new shape. The order of non-empty values in `sp_input` is + unchanged. + + If one component of `shape` is the special value -1, the size of that + dimension is computed so that the total dense size remains constant. At + most one component of `shape` can be -1. The number of dense elements + implied by `shape` must be the same as the number of dense elements + originally represented by `sp_input`. + + For example, if `sp_input` has shape `[2, 3, 6]` and `indices` / `values`: + + [0, 0, 0]: a + [0, 0, 1]: b + [0, 1, 0]: c + [1, 0, 0]: d + [1, 2, 3]: e + + and `shape` is `[9, -1]`, then the output will be a `SparseTensor` of + shape `[9, 4]` and `indices` / `values`: + + [0, 0]: a + [0, 1]: b + [1, 2]: c + [4, 2]: d + [8, 1]: e + + Args: + sp_input: The input `SparseTensor`. + shape: A 1-D (vector) int64 `Tensor` specifying the new dense shape of the + represented `SparseTensor`. + name: A name prefix for the returned tensors (optional) + + Returns: + A `SparseTensor` with the same non-empty values but with indices calculated + by the new dense shape. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + ValueError: If argument `shape` requests a `SparseTensor` with a different + number of elements than `sp_input`. + ValueError: If `shape` has more than one inferred (== -1) dimension. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + shape = math_ops.cast(shape, dtype=dtypes.int64) + + with ops.name_scope(name, "SparseReshape", [sp_input]) as name: + reshaped_ind, reshaped_shape = gen_sparse_ops.sparse_reshape( + sp_input.indices, sp_input.dense_shape, shape, name=name) + + reshaped_shape_const = tensor_util.constant_value_as_shape(shape) + reshaped_shape_const = ( + reshaped_shape_const.as_list() if reshaped_shape_const.ndims is not None + else None) + + if (reshaped_shape_const is not None + and sp_input.shape.is_fully_defined()): + # constant_value_as_shape tends to get more information about the partial + # shape values, but here we specifically need to know if the *user* passed + # a shape with 2+ unknown dimensions; and for that constant_value + # provides either the user's direct value or None if only partial elements + # are known via the python shape inference code. + shape_const_by_user = tensor_util.constant_value(shape) + if shape_const_by_user is not None: + num_implied_by_user = sum(d == -1 for d in shape_const_by_user) + if num_implied_by_user > 1: + raise ValueError( + "At most one dimension can be inferred (-1). Found: %s" + % shape_const_by_user) + original_reshaped_shape = list(reshaped_shape_const) # A copy + in_shape_size = np.prod(sp_input.shape.as_list()) + num_implied = sum(dim is None for dim in reshaped_shape_const) + + # If there is a 0 dim in the user-provided shape, we cannot infer the + # unknown dim reliably. This is why we skip the `if` branch below when + # a 0 is present in `reshaped_shape_const`. Same below. + if num_implied == 1 and 0 not in reshaped_shape_const: + implied_idx = original_reshaped_shape.index(None) + non_implied_idx = ( + original_reshaped_shape[:implied_idx] + + original_reshaped_shape[implied_idx + 1:]) + reshaped_shape_const[implied_idx] = int( + in_shape_size // np.prod(non_implied_idx)) + if num_implied == 0 or (num_implied == 1 and + 0 not in reshaped_shape_const): + reshaped_size = np.prod(reshaped_shape_const) + if reshaped_size != in_shape_size: + raise ValueError( + "Cannot reshape a tensor with %d elements to shape %s " + "(%d elements)." % + (in_shape_size, original_reshaped_shape, reshaped_size)) + reshaped_shape = constant_op.constant( + reshaped_shape_const, dtype=dtypes.int64) + + return sparse_tensor.SparseTensor(reshaped_ind, + array_ops.identity(sp_input.values), + reshaped_shape) + + +# TODO(aselle): Remove keyword required once for 1.0 final +class KeywordRequired: + + def __repr__(self): + # This is needed to make documentation without fully qualified module paths + return "KeywordRequired()" + + +@tf_export(v1=["sparse.split", "sparse_split"]) +@deprecation.deprecated_endpoints("sparse_split") +@deprecation.deprecated_args( + None, "split_dim is deprecated, use axis instead", "split_dim") +def sparse_split(keyword_required=KeywordRequired(), + sp_input=None, + num_split=None, + axis=None, + name=None, + split_dim=None): + """Split a `SparseTensor` into `num_split` tensors along `axis`. + + If the `sp_input.dense_shape[axis]` is not an integer multiple of `num_split` + each slice starting from 0:`shape[axis] % num_split` gets extra one + dimension. For example, if `axis = 1` and `num_split = 2` and the + input is: + + input_tensor = shape = [2, 7] + [ a d e ] + [b c ] + + Graphically the output tensors are: + + output_tensor[0] = + [ a ] + [b c ] + + output_tensor[1] = + [ d e ] + [ ] + + Args: + keyword_required: Python 2 standin for * (temporary for argument reorder) + sp_input: The `SparseTensor` to split. + num_split: A Python integer. The number of ways to split. + axis: A 0-D `int32` `Tensor`. The dimension along which to split. Must be in + range [-rank, rank), where rank is the number of dimensions in the input + `SparseTensor`. + name: A name for the operation (optional). + split_dim: Deprecated old name for axis. + + Returns: + `num_split` `SparseTensor` objects resulting from splitting `value`. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + ValueError: If the deprecated `split_dim` and `axis` are both non None. + """ + if not isinstance(keyword_required, KeywordRequired): + raise ValueError("Keyword arguments are required for this function.") + if sp_input is None: + raise ValueError("sp_input is required") + if num_split is None: + raise ValueError("num_split is required") + if axis is None: + raise ValueError("axis is required") + axis = deprecation.deprecated_argument_lookup("axis", axis, "split_dim", + split_dim) + sp_input = _convert_to_sparse_tensor(sp_input) + + output_inds, output_vals, output_shapes = ( + gen_sparse_ops.sparse_split( + axis, + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + num_split, + name=name)) + sparse_tensors = [] + for i in range(0, num_split): + sparse_tensors.append( + sparse_tensor.SparseTensor(output_inds[i], output_vals[i], + output_shapes[i])) + return sparse_tensors + + +@tf_export("sparse.split", v1=[]) +def sparse_split_v2(sp_input=None, + num_split=None, + axis=None, + name=None): + """Split a `SparseTensor` into `num_split` tensors along `axis`. + + If the `sp_input.dense_shape[axis]` is not an integer multiple of `num_split` + each slice starting from 0:`shape[axis] % num_split` gets extra one + dimension. For example: + + >>> indices = [[0, 2], [0, 4], [0, 5], [1, 0], [1, 1]] + >>> values = [1, 2, 3, 4, 5] + >>> t = tf.sparse.SparseTensor(indices=indices, values=values, + ... dense_shape=[2, 7]) + >>> tf.sparse.to_dense(t) + + + >>> output = tf.sparse.split(sp_input=t, num_split=2, axis=1) + >>> tf.sparse.to_dense(output[0]) + + >>> tf.sparse.to_dense(output[1]) + + + >>> output = tf.sparse.split(sp_input=t, num_split=2, axis=0) + >>> tf.sparse.to_dense(output[0]) + + >>> tf.sparse.to_dense(output[1]) + + + >>> output = tf.sparse.split(sp_input=t, num_split=2, axis=-1) + >>> tf.sparse.to_dense(output[0]) + + >>> tf.sparse.to_dense(output[1]) + + + Args: + sp_input: The `SparseTensor` to split. + num_split: A Python integer. The number of ways to split. + axis: A 0-D `int32` `Tensor`. The dimension along which to split. Must be in + range [-rank, rank), where rank is the number of dimensions in the input + `SparseTensor`. + name: A name for the operation (optional). + + Returns: + `num_split` `SparseTensor` objects resulting from splitting `value`. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + return sparse_split(sp_input=sp_input, + num_split=num_split, + axis=axis, + name=name, + split_dim=None) + + +@tf_export("sparse.slice", v1=["sparse.slice", "sparse_slice"]) +@deprecation.deprecated_endpoints("sparse_slice") +def sparse_slice(sp_input, start, size, name=None): + """Slice a `SparseTensor` based on the `start` and `size`. + + For example, if the input is + + input_tensor = shape = [2, 7] + [ a d e ] + [b c ] + + Graphically the output tensors are: + + sparse.slice([0, 0], [2, 4]) = shape = [2, 4] + [ a ] + [b c ] + + sparse.slice([0, 4], [2, 3]) = shape = [2, 3] + [ d e ] + [ ] + + Args: + sp_input: The `SparseTensor` to split. + start: 1-D. tensor represents the start of the slice. + size: 1-D. tensor represents the size of the slice. + name: A name for the operation (optional). + + Returns: + A `SparseTensor` objects resulting from splicing. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + start = ops.convert_to_tensor(start, dtypes.int64) + size = ops.convert_to_tensor(size, dtypes.int64) + + with ops.name_scope(name, "SparseSlice", [sp_input]) as name: + output_indices, output_values, output_shape = gen_sparse_ops.sparse_slice( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + start, + size, + name=name) + + return sparse_tensor.SparseTensor(output_indices, output_values, + output_shape) + + +@tf_export(v1=["sparse_to_dense"]) +@dispatch.add_dispatch_support +@deprecation.deprecated( + None, + "Create a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.") +def sparse_to_dense(sparse_indices, + output_shape, + sparse_values, + default_value=0, + validate_indices=True, + name=None): + """Converts a sparse representation into a dense tensor. + + Builds an array `dense` with shape `output_shape` such that + + ```python + # If sparse_indices is scalar + dense[i] = (i == sparse_indices ? sparse_values : default_value) + + # If sparse_indices is a vector, then for each i + dense[sparse_indices[i]] = sparse_values[i] + + # If sparse_indices is an n by d matrix, then for each i in [0, n) + dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i] + ``` + + All other values in `dense` are set to `default_value`. If `sparse_values` + is a scalar, all sparse indices are set to this single value. + + Indices should be sorted in lexicographic order, and indices must not + contain any repeats. If `validate_indices` is True, these properties + are checked during execution. + + Args: + sparse_indices: A 0-D, 1-D, or 2-D `Tensor` of type `int32` or `int64`. + `sparse_indices[i]` contains the complete index where `sparse_values[i]` + will be placed. + output_shape: A 1-D `Tensor` of the same type as `sparse_indices`. Shape + of the dense output tensor. + sparse_values: A 0-D or 1-D `Tensor`. Values corresponding to each row of + `sparse_indices`, or a scalar value to be used for all sparse indices. + default_value: A 0-D `Tensor` of the same type as `sparse_values`. Value + to set for indices not specified in `sparse_indices`. Defaults to zero. + validate_indices: A boolean value. If True, indices are checked to make + sure they are sorted in lexicographic order and that there are no repeats. + name: A name for the operation (optional). + + Returns: + Dense `Tensor` of shape `output_shape`. Has the same type as + `sparse_values`. + """ + return gen_sparse_ops.sparse_to_dense( + sparse_indices, + output_shape, + sparse_values, + default_value=default_value, + validate_indices=validate_indices, + name=name) + + +@tf_export("sparse.reduce_max", v1=[]) +def sparse_reduce_max_v2( + sp_input, axis=None, keepdims=None, output_is_sparse=False, name=None): + """Computes `tf.sparse.maximum` of elements across dimensions of a SparseTensor. + + This is the reduction operation for the elementwise `tf.sparse.maximum` op. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_max()`. In particular, this Op also returns a dense `Tensor` + if `output_is_sparse` is `False`, or a `SparseTensor` if `output_is_sparse` + is `True`. + + Note: A gradient is not defined for this function, so it can't be used + in training models that need gradient descent. + + Reduces `sp_input` along the dimensions given in `axis`. Unless + `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in + `axis`. If `keepdims` is true, the reduced dimensions are retained + with length 1. + + If `axis` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + similar to the indexing rules in Python. + + The values not defined in `sp_input` don't participate in the reduce max, + as opposed to be implicitly assumed 0 -- hence it can return negative values + for sparse `axis`. But, in case there are no values in + `axis`, it will reduce to 0. See second example below. + + For example: + + # 'x' represents [[1, ?, 2] + # [?, 3, ?]] + # where ? is implicitly-zero. + + >>> x = tf.sparse.SparseTensor([[0, 0], [0, 2], [1, 1]], [1, 2, 3], [2, 3]) + >>> tf.sparse.reduce_max(x) + + >>> tf.sparse.reduce_max(x, 0) + + >>> tf.sparse.reduce_max(x, 1) + + >>> tf.sparse.reduce_max(x, 1, keepdims=True) + + >>> tf.sparse.reduce_max(x, [0, 1]) + + + # 'y' represents [[-7, ?] + # [ 4, 3] + # [ ?, ?] + + >>> y = tf.sparse.SparseTensor([[0, 0,], [1, 0], [1, 1]], [-7, 4, 3], + ... [3, 2]) + >>> tf.sparse.reduce_max(y, 1) + + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + output_is_sparse: If true, returns a `SparseTensor` instead of a dense + `Tensor` (the default). + name: A name for the operation (optional). + + Returns: + The reduced Tensor or the reduced SparseTensor if `output_is_sparse` is + True. + """ + if keepdims is None: + keepdims = False + + if output_is_sparse: + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_reduce_max_sparse( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), + keepdims, + name=name)) + + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + + return gen_sparse_ops.sparse_reduce_max( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), + keepdims, + name=name) + + +@tf_export(v1=["sparse.reduce_max", "sparse_reduce_max"]) +@deprecation.deprecated_endpoints("sparse_reduce_max") +@deprecation.deprecated_args( + None, "keep_dims is deprecated, use keepdims instead", "keep_dims") +@deprecation.deprecated_args( + None, "reduction_axes is deprecated, use axis instead", + "reduction_axes") +def sparse_reduce_max(sp_input, axis=None, keepdims=None, + reduction_axes=None, keep_dims=None): + """Computes `tf.sparse.maximum` of elements across dimensions of a SparseTensor. + + This is the reduction operation for the elementwise `tf.sparse.maximum` op. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_max()`. In particular, this Op also returns a dense `Tensor` + instead of a sparse one. + + Note: A gradient is not defined for this function, so it can't be used + in training models that need gradient descent. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + similar to the indexing rules in Python. + + The values not defined in `sp_input` don't participate in the reduce max, + as opposed to be implicitly assumed 0 -- hence it can return negative values + for sparse `reduction_axes`. But, in case there are no values in + `reduction_axes`, it will reduce to 0. See second example below. + + For example: + + # 'x' represents [[1, ?, 2] + # [?, 3, ?]] + # where ? is implicitly-zero. + + >>> x = tf.sparse.SparseTensor([[0, 0], [0, 2], [1, 1]], [1, 2, 3], [2, 3]) + >>> tf.sparse.reduce_max(x) + + >>> tf.sparse.reduce_max(x, 0) + + >>> tf.sparse.reduce_max(x, 1) + + >>> tf.sparse.reduce_max(x, 1, keepdims=True) + + >>> tf.sparse.reduce_max(x, [0, 1]) + + + # 'y' represents [[-7, ?] + # [ 4, 3] + # [ ?, ?] + + >>> y = tf.sparse.SparseTensor([[0, 0,], [1, 0], [1, 1]], [-7, 4, 3], + ... [3, 2]) + >>> tf.sparse.reduce_max(y, 1) + + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + reduction_axes: Deprecated name of `axis`. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced Tensor. + """ + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + axis = deprecation.deprecated_argument_lookup("axis", axis, "reduction_axes", + reduction_axes) + if keepdims is None: + keepdims = False + + return gen_sparse_ops.sparse_reduce_max( + sp_input.indices, sp_input.values, sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), keepdims) + + +@tf_export(v1=["sparse.reduce_max_sparse", "sparse_reduce_max_sparse"]) +@deprecation.deprecated_endpoints("sparse_reduce_max_sparse") +@deprecation.deprecated_args( + None, "keep_dims is deprecated, use keepdims instead", "keep_dims") +def sparse_reduce_max_sparse(sp_input, + axis=None, + keepdims=None, + reduction_axes=None, + keep_dims=None): + """Computes the max of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_max()`. In contrast to SparseReduceSum, this Op returns a + SparseTensor. + + Note: A gradient is not defined for this function, so it can't be used + in training models that need gradient descent. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + reduction_axes: Deprecated name of axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced SparseTensor. + """ + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + axis = deprecation.deprecated_argument_lookup("axis", axis, "reduction_axes", + reduction_axes) + if keepdims is None: + keepdims = False + + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_reduce_max_sparse( + sp_input.indices, sp_input.values, sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), keepdims)) + + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + + +@tf_export("sparse.reduce_sum", v1=[]) +def sparse_reduce_sum_v2( + sp_input, axis=None, keepdims=None, output_is_sparse=False, name=None): + """Computes `tf.sparse.add` of elements across dimensions of a SparseTensor. + + This is the reduction operation for the elementwise `tf.sparse.add` op. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor` + if `output_is_sparse` is `False`, or a `SparseTensor` if `output_is_sparse` + is `True`. + + Note: if `output_is_sparse` is True, a gradient is not defined for this + function, so it can't be used in training models that need gradient descent. + + Reduces `sp_input` along the dimensions given in `axis`. Unless `keepdims` is + true, the rank of the tensor is reduced by 1 for each entry in `axis`. If + `keepdims` is true, the reduced dimensions are retained with length 1. + + If `axis` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + similar to the indexing rules in Python. + + For example: + + # 'x' represents [[1, ?, 1] + # [?, 1, ?]] + # where ? is implicitly-zero. + + >>> x = tf.sparse.SparseTensor([[0, 0], [0, 2], [1, 1]], [1, 1, 1], [2, 3]) + >>> tf.sparse.reduce_sum(x) + + >>> tf.sparse.reduce_sum(x, 0) + + >>> tf.sparse.reduce_sum(x, 1) # Can also use -1 as the axis + + >>> tf.sparse.reduce_sum(x, 1, keepdims=True) + + >>> tf.sparse.reduce_sum(x, [0, 1]) + + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + output_is_sparse: If true, returns a `SparseTensor` instead of a dense + `Tensor` (the default). + name: A name for the operation (optional). + + Returns: + The reduced Tensor or the reduced SparseTensor if `output_is_sparse` is + True. + """ + if keepdims is None: + keepdims = False + + if output_is_sparse: + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_reduce_sum_sparse( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), + keepdims, + name=name)) + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + + return gen_sparse_ops.sparse_reduce_sum( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), + keepdims, + name=name) + + +@tf_export(v1=["sparse.reduce_sum", "sparse_reduce_sum"]) +@deprecation.deprecated_endpoints("sparse_reduce_sum") +@deprecation.deprecated_args( + None, "keep_dims is deprecated, use keepdims instead", "keep_dims") +@deprecation.deprecated_args( + None, "reduction_axes is deprecated, use axis instead", + "reduction_axes") +def sparse_reduce_sum(sp_input, axis=None, keepdims=None, + reduction_axes=None, keep_dims=None): + """Computes `tf.sparse.add` of elements across dimensions of a SparseTensor. + + This is the reduction operation for the elementwise `tf.sparse.add` op. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_sum()`. In particular, this Op also returns a dense `Tensor` + instead of a sparse one. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + similar to the indexing rules in Python. + + For example: + + # 'x' represents [[1, ?, 1] + # [?, 1, ?]] + # where ? is implicitly-zero. + + >>> x = tf.sparse.SparseTensor([[0, 0], [0, 2], [1, 1]], [1, 1, 1], [2, 3]) + >>> tf.sparse.reduce_sum(x) + + >>> tf.sparse.reduce_sum(x, 0) + + >>> tf.sparse.reduce_sum(x, 1) # Can also use -1 as the axis + + >>> tf.sparse.reduce_sum(x, 1, keepdims=True) + + >>> tf.sparse.reduce_sum(x, [0, 1]) + + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + reduction_axes: Deprecated name of `axis`. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced Tensor. + """ + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + axis = deprecation.deprecated_argument_lookup("axis", axis, "reduction_axes", + reduction_axes) + if keepdims is None: + keepdims = False + + return gen_sparse_ops.sparse_reduce_sum( + sp_input.indices, sp_input.values, sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), keepdims) + + +@tf_export(v1=["sparse.reduce_sum_sparse", "sparse_reduce_sum_sparse"]) +@deprecation.deprecated_endpoints("sparse_reduce_sum_sparse") +@deprecation.deprecated_args( + None, "keep_dims is deprecated, use keepdims instead", "keep_dims") +def sparse_reduce_sum_sparse(sp_input, + axis=None, + keepdims=None, + reduction_axes=None, + keep_dims=None): + """Computes the sum of elements across dimensions of a SparseTensor. + + This Op takes a SparseTensor and is the sparse counterpart to + `tf.reduce_sum()`. In contrast to SparseReduceSum, this Op returns a + SparseTensor. + + Note: A gradient is not defined for this function, so it can't be used + in training models that need gradient descent. + + Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless + `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in + `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained + with length 1. + + If `reduction_axes` has no entries, all dimensions are reduced, and a tensor + with a single element is returned. Additionally, the axes can be negative, + which are interpreted according to the indexing rules in Python. + + Args: + sp_input: The SparseTensor to reduce. Should have numeric type. + axis: The dimensions to reduce; list or scalar. If `None` (the + default), reduces all dimensions. + keepdims: If true, retain reduced dimensions with length 1. + reduction_axes: Deprecated name of axis. + keep_dims: Deprecated alias for `keepdims`. + + Returns: + The reduced SparseTensor. + """ + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + axis = deprecation.deprecated_argument_lookup("axis", axis, "reduction_axes", + reduction_axes) + if keepdims is None: + keepdims = False + + output_ind, output_val, output_shape = ( + gen_sparse_ops.sparse_reduce_sum_sparse( + sp_input.indices, sp_input.values, sp_input.dense_shape, + math_ops._ReductionDims(sp_input, axis), keepdims)) + + return sparse_tensor.SparseTensor(output_ind, output_val, output_shape) + + +@tf_export("sparse.to_dense", v1=["sparse.to_dense", "sparse_tensor_to_dense"]) +@deprecation.deprecated_endpoints("sparse_tensor_to_dense") +def sparse_tensor_to_dense(sp_input, + default_value=None, + validate_indices=True, + name=None): + """Converts a `SparseTensor` into a dense tensor. + + For this sparse tensor with three non-empty values: + + >>> sp_input = tf.sparse.SparseTensor( + ... dense_shape=[3, 5], + ... values=[7, 8, 9], + ... indices =[[0, 1], + ... [0, 3], + ... [2, 0]]) + + The output will be a dense `[3, 5]` tensor with values: + + >>> tf.sparse.to_dense(sp_input).numpy() + array([[0, 7, 0, 8, 0], + [0, 0, 0, 0, 0], + [9, 0, 0, 0, 0]], dtype=int32) + + Note: Indices must be without repeats. This is only tested if + `validate_indices` is `True`. + + Args: + sp_input: The input `SparseTensor`. + default_value: Scalar value to set for indices not specified in + `sp_input`. Defaults to zero. + validate_indices: A boolean value. If `True`, indices are checked to make + sure they are sorted in lexicographic order and that there are no repeats. + name: A name prefix for the returned tensors (optional). + + Returns: + A dense tensor with shape `sp_input.dense_shape` and values specified by + the non-empty values in `sp_input`. Indices not in `sp_input` are assigned + `default_value`. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + if default_value is None: + default_value = array_ops.zeros([], dtype=sp_input.dtype) + + return gen_sparse_ops.sparse_to_dense( + sp_input.indices, + sp_input.dense_shape, + sp_input.values, + default_value=default_value, + validate_indices=validate_indices, + name=name) + + +@tf_export( + "sparse.to_indicator", v1=["sparse.to_indicator", "sparse_to_indicator"]) +@deprecation.deprecated_endpoints("sparse_to_indicator") +def sparse_to_indicator(sp_input, vocab_size, name=None): + """Converts a `SparseTensor` of ids into a dense bool indicator tensor. + + The last dimension of `sp_input.indices` is discarded and replaced with + the values of `sp_input`. If `sp_input.dense_shape = [D0, D1, ..., Dn, K]`, + then `output.shape = [D0, D1, ..., Dn, vocab_size]`, where + + output[d_0, d_1, ..., d_n, sp_input[d_0, d_1, ..., d_n, k]] = True + + and False elsewhere in `output`. + + For example, if `sp_input.dense_shape = [2, 3, 4]` with non-empty values: + + [0, 0, 0]: 0 + [0, 1, 0]: 10 + [1, 0, 3]: 103 + [1, 1, 1]: 150 + [1, 1, 2]: 149 + [1, 1, 3]: 150 + [1, 2, 1]: 121 + + and `vocab_size = 200`, then the output will be a `[2, 3, 200]` dense bool + tensor with False everywhere except at positions + + (0, 0, 0), (0, 1, 10), (1, 0, 103), (1, 1, 149), (1, 1, 150), + (1, 2, 121). + + Note that repeats are allowed in the input SparseTensor. + This op is useful for converting `SparseTensor`s into dense formats for + compatibility with ops that expect dense tensors. + + The input `SparseTensor` must be in row-major order. + + Args: + sp_input: A `SparseTensor` with `values` property of type `int32` or + `int64`. + vocab_size: A scalar int64 Tensor (or Python int) containing the new size + of the last dimension, `all(0 <= sp_input.values < vocab_size)`. + name: A name prefix for the returned tensors (optional) + + Returns: + A dense bool indicator tensor representing the indices with specified value. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + with ops.name_scope(name, "SparseToIndicator", [sp_input]) as name: + num_entries = array_ops.shape(sp_input.indices)[0] + new_values = array_ops.fill(array_ops.expand_dims(num_entries, 0), True) + sp_values = sparse_tensor.SparseTensor(sp_input.indices, new_values, + sp_input.dense_shape) + + sp_new = sparse_merge_impl(sp_input, sp_values, vocab_size, name) + + # validate_indices may be False because we allow duplicates in new_indices: + # repeated indices are allowed when creating an indicator matrix. + return sparse_tensor_to_dense( + sp_new, default_value=False, validate_indices=False, name=name) + + +@tf_export(v1=["sparse.merge", "sparse_merge"]) +@deprecation.deprecated(None, "No similar op available at this time.") +def sparse_merge(sp_ids, sp_values, vocab_size, name=None, + already_sorted=False): + """Combines a batch of feature ids and values into a single `SparseTensor`. + + The most common use case for this function occurs when feature ids and + their corresponding values are stored in `Example` protos on disk. + `parse_example` will return a batch of ids and a batch of values, and this + function joins them into a single logical `SparseTensor` for use in + functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc. + + The `SparseTensor` returned by this function has the following properties: + + - `indices` is equivalent to `sp_ids.indices` with the last + dimension discarded and replaced with `sp_ids.values`. + - `values` is simply `sp_values.values`. + - If `sp_ids.dense_shape = [D0, D1, ..., Dn, K]`, then + `output.shape = [D0, D1, ..., Dn, vocab_size]`. + + For example, consider the following feature vectors: + + ```python + vector1 = [-3, 0, 0, 0, 0, 0] + vector2 = [ 0, 1, 0, 4, 1, 0] + vector3 = [ 5, 0, 0, 9, 0, 0] + ``` + + These might be stored sparsely in the following Example protos by storing + only the feature ids (column number if the vectors are treated as a matrix) + of the non-zero elements and the corresponding values: + + ```python + examples = [Example(features={ + "ids": Feature(int64_list=Int64List(value=[0])), + "values": Feature(float_list=FloatList(value=[-3]))}), + Example(features={ + "ids": Feature(int64_list=Int64List(value=[1, 4, 3])), + "values": Feature(float_list=FloatList(value=[1, 1, 4]))}), + Example(features={ + "ids": Feature(int64_list=Int64List(value=[0, 3])), + "values": Feature(float_list=FloatList(value=[5, 9]))})] + ``` + + The result of calling parse_example on these examples will produce a + dictionary with entries for "ids" and "values". Passing those two objects + to this function along with vocab_size=6, will produce a `SparseTensor` that + sparsely represents all three instances. Namely, the `indices` property will + contain the coordinates of the non-zero entries in the feature matrix (the + first dimension is the row number in the matrix, i.e., the index within the + batch, and the second dimension is the column number, i.e., the feature id); + `values` will contain the actual values. `shape` will be the shape of the + original matrix, i.e., (3, 6). For our example above, the output will be + equal to: + + ```python + SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]], + values=[-3, 1, 4, 1, 5, 9], + dense_shape=[3, 6]) + ``` + + This method generalizes to higher-dimensions by simply providing a list for + both the sp_ids as well as the vocab_size. + In this case the resulting `SparseTensor` has the following properties: + - `indices` is equivalent to `sp_ids[0].indices` with the last + dimension discarded and concatenated with + `sp_ids[0].values, sp_ids[1].values, ...`. + - `values` is simply `sp_values.values`. + - If `sp_ids.dense_shape = [D0, D1, ..., Dn, K]`, then + `output.shape = [D0, D1, ..., Dn] + vocab_size`. + + Args: + sp_ids: A single `SparseTensor` with `values` property of type `int32` + or `int64` or a Python list of such `SparseTensor`s or a list thereof. + sp_values: A `SparseTensor` of any type. + vocab_size: A scalar `int64` Tensor (or Python int) containing the new size + of the last dimension, `all(0 <= sp_ids.values < vocab_size)`. + Or a list thereof with `all(0 <= sp_ids[i].values < vocab_size[i])` for + all `i`. + name: A name prefix for the returned tensors (optional) + already_sorted: A boolean to specify whether the per-batch values in + `sp_values` are already sorted. If so skip sorting, False by default + (optional). + + Returns: + A `SparseTensor` compactly representing a batch of feature ids and values, + useful for passing to functions that expect such a `SparseTensor`. + + Raises: + TypeError: If `sp_values` is not a `SparseTensor`. Or if `sp_ids` is neither + a `SparseTensor` nor a list thereof. Or if `vocab_size` is not a + `Tensor` or a Python int and `sp_ids` is a `SparseTensor`. Or if + `vocab_size` is not a or list thereof and `sp_ids` is a list. + ValueError: If `sp_ids` and `vocab_size` are lists of different lengths. + """ + return sparse_merge_impl(sp_ids, sp_values, vocab_size, name, already_sorted) + + +def sparse_merge_impl(sp_ids, + sp_values, + vocab_size, + name=None, + already_sorted=False): + """Internal implementation for sparse_merge to avoid deprecation warnings.""" + if isinstance(sp_ids, sparse_tensor.SparseTensorValue) or isinstance( + sp_ids, sparse_tensor.SparseTensor): + sp_ids = [sp_ids] + if not (isinstance(vocab_size, tensor_lib.Tensor) or + isinstance(vocab_size, numbers.Integral)): + raise TypeError("vocab_size has to be a Tensor or Python int. Found %s" % + type(vocab_size)) + vocab_size = [vocab_size] + else: + if not isinstance(sp_ids, collections_abc.Iterable): + raise TypeError("sp_ids has to be a SparseTensor or list thereof. " + "Found %s" % type(sp_ids)) + if not isinstance(vocab_size, collections_abc.Iterable): + raise TypeError("vocab_size has to be a list of Tensors or Python ints. " + "Found %s" % type(vocab_size)) + for dim in vocab_size: + if not (isinstance( + dim, tensor_lib.Tensor) or isinstance(dim, numbers.Integral)): + raise TypeError( + "vocab_size has to be a list of Tensors or Python ints. Found %s" % + type(dim)) + if len(sp_ids) != len(vocab_size): + raise ValueError("sp_ids and vocab_size have to have equal lengths.") + + with ops.name_scope(name, "SparseMerge", [sp_ids, sp_values]): + sp_ids = [_convert_to_sparse_tensor(sp_ids_dim) for sp_ids_dim in sp_ids] + sp_values = _convert_to_sparse_tensor(sp_values) + ids = [] + for sp_ids_dim in sp_ids: + ids_dim = sp_ids_dim.values + if sp_ids_dim.dtype != dtypes.int64: + ids_dim = math_ops.cast(ids_dim, dtypes.int64) + ids += [array_ops.expand_dims(ids_dim, axis=1)] + + vocab_size = [math_ops.cast(x, dtypes.int64) for x in vocab_size] + + # Slice off the last dimension of indices, then tack on the ids + indices_columns_to_preserve = sp_ids[0].indices[:, :-1] + new_indices = array_ops.concat([indices_columns_to_preserve] + ids, 1) + + new_values = sp_values.values + new_shape = array_ops.concat([sp_ids[0].dense_shape[:-1], vocab_size], 0) + + result = sparse_tensor.SparseTensor(new_indices, new_values, new_shape) + if already_sorted: + return result + sorted_result = sparse_reorder(result) + return sparse_tensor.SparseTensor( + sorted_result.indices, sorted_result.values, new_shape) + + +@tf_export("sparse.retain", v1=["sparse.retain", "sparse_retain"]) +@deprecation.deprecated_endpoints("sparse_retain") +def sparse_retain(sp_input, to_retain): + """Retains specified non-empty values within a `SparseTensor`. + + For example, if `sp_input` has shape `[4, 5]` and 4 non-empty string values: + + [0, 1]: a + [0, 3]: b + [2, 0]: c + [3, 1]: d + + and `to_retain = [True, False, False, True]`, then the output will + be a `SparseTensor` of shape `[4, 5]` with 2 non-empty values: + + [0, 1]: a + [3, 1]: d + + Args: + sp_input: The input `SparseTensor` with `N` non-empty elements. + to_retain: A bool vector of length `N` with `M` true values. + + Returns: + A `SparseTensor` with the same shape as the input and `M` non-empty + elements corresponding to the true positions in `to_retain`. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + to_retain = ops.convert_to_tensor(to_retain) + + # Shape checking, if shape is known at graph construction time + retain_shape = to_retain.get_shape() + retain_shape.assert_has_rank(1) + if sp_input.values.get_shape().dims is not None: + sp_input.values.get_shape().dims[0].assert_is_compatible_with( + tensor_shape.dimension_at_index(retain_shape, 0)) + + where_true = array_ops.reshape(array_ops.where_v2(to_retain), [-1]) + new_indices = array_ops.gather(sp_input.indices, where_true) + new_values = array_ops.gather(sp_input.values, where_true) + return sparse_tensor.SparseTensor(new_indices, new_values, + array_ops.identity(sp_input.dense_shape)) + + +@tf_export( + "sparse.reset_shape", v1=["sparse.reset_shape", "sparse_reset_shape"]) +@deprecation.deprecated_endpoints("sparse_reset_shape") +def sparse_reset_shape(sp_input, new_shape=None): + """Resets the shape of a `SparseTensor` with indices and values unchanged. + + If `new_shape` is None, returns a copy of `sp_input` with its shape reset + to the tight bounding box of `sp_input`. This will be a shape consisting of + all zeros if sp_input has no values. + + If `new_shape` is provided, then it must be larger or equal in all dimensions + compared to the shape of `sp_input`. When this condition is met, the returned + SparseTensor will have its shape reset to `new_shape` and its indices and + values unchanged from that of `sp_input.` + + For example: + + Consider a `sp_input` with shape [2, 3, 5]: + + [0, 0, 1]: a + [0, 1, 0]: b + [0, 2, 2]: c + [1, 0, 3]: d + + - It is an error to set `new_shape` as [3, 7] since this represents a + rank-2 tensor while `sp_input` is rank-3. This is either a ValueError + during graph construction (if both shapes are known) or an OpError during + run time. + + - Setting `new_shape` as [2, 3, 6] will be fine as this shape is larger or + equal in every dimension compared to the original shape [2, 3, 5]. + + - On the other hand, setting new_shape as [2, 3, 4] is also an error: The + third dimension is smaller than the original shape [2, 3, 5] (and an + `InvalidArgumentError` will be raised). + + - If `new_shape` is None, the returned SparseTensor will have a shape + [2, 3, 4], which is the tight bounding box of `sp_input`. + + Args: + sp_input: The input `SparseTensor`. + new_shape: None or a vector representing the new shape for the returned + `SparseTensor`. + + Returns: + A `SparseTensor` indices and values unchanged from `sp_input`. Its shape is + `new_shape` if that is set. Otherwise it is the tight bounding box of + `sp_input` + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + ValueError: If `new_shape` represents a tensor with a different rank from + that of `sp_input` (if shapes are known when graph is constructed). + ValueError: If `new_shape` is determined during graph build to have + dimension sizes that are too small. + OpError: + - If `new_shape` has dimension sizes that are too small. + - If shapes are not known during graph construction time, and during run + time it is found out that the ranks do not match. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + in_indices = array_ops.identity(sp_input.indices) + in_values = array_ops.identity(sp_input.values) + in_shape = array_ops.identity(sp_input.dense_shape) + + if new_shape is None: + dim_low_bound = math_ops.reduce_max(in_indices, axis=0) + output_shape_tensor = math_ops.maximum( + array_ops.constant(0, dtype=dtypes.int64), + math_ops.add(dim_low_bound, array_ops.ones_like(in_shape))) + else: + output_shape_tensor = ops.convert_to_tensor(new_shape) + output_shape_tensor.get_shape().assert_has_rank(1) + output_shape_tensor = math_ops.cast(output_shape_tensor, dtypes.int64) + # For cases when shape is known during graph construction, this catches the + # error before the sparse_tensor.SparseTensor catches it. + if output_shape_tensor.get_shape().rank is not None: + output_shape_tensor.get_shape().dims[0].assert_is_compatible_with( + in_shape.get_shape().dims[0]) + + output_shape_tensor_const = tensor_util.constant_value(output_shape_tensor) + # For cases where all shapes are known during graph construction + if (output_shape_tensor_const is not None and + sp_input.get_shape().is_fully_defined()): + in_shape_const = np.array(sp_input.get_shape().as_list()) + if not np.all(in_shape_const <= output_shape_tensor_const): + raise ValueError( + "Requested new_shape should have dimension sizes >= sp_input.shape." + " Found new_shape (%s), sp_input.shape (%s)." % + (in_shape_const, output_shape_tensor_const)) + output_shape_tensor = output_shape_tensor_const + else: + # For cases where shape is not known during graph construction. + output_shape_tensor = control_flow_ops.with_dependencies([ + check_ops.assert_equal( + array_ops.shape(in_shape), array_ops.shape(output_shape_tensor)) + ], output_shape_tensor) + output_shape_tensor = control_flow_ops.with_dependencies( + [check_ops.assert_less_equal(in_shape, output_shape_tensor)], + output_shape_tensor) + + return sparse_tensor.SparseTensor(in_indices, in_values, output_shape_tensor) + + +@tf_export( + "sparse.fill_empty_rows", + v1=["sparse.fill_empty_rows", "sparse_fill_empty_rows"]) +@deprecation.deprecated_endpoints("sparse_fill_empty_rows") +def sparse_fill_empty_rows(sp_input, default_value, name=None): + """Fills empty rows in the input 2-D `SparseTensor` with a default value. + + This op adds entries with the specified `default_value` at index + `[row, 0]` for any row in the input that does not already have a value. + + For example, suppose `sp_input` has shape `[5, 6]` and non-empty values: + + [0, 1]: a + [0, 3]: b + [2, 0]: c + [3, 1]: d + + Rows 1 and 4 are empty, so the output will be of shape `[5, 6]` with values: + + [0, 1]: a + [0, 3]: b + [1, 0]: default_value + [2, 0]: c + [3, 1]: d + [4, 0]: default_value + + Note that the input may have empty columns at the end, with no effect on + this op. + + The output `SparseTensor` will be in row-major order and will have the + same shape as the input. + + This op also returns an indicator vector such that + + empty_row_indicator[i] = True iff row i was an empty row. + + Args: + sp_input: A `SparseTensor` with shape `[N, M]`. + default_value: The value to fill for empty rows, with the same type as + `sp_input.` + name: A name prefix for the returned tensors (optional) + + Returns: + sp_ordered_output: A `SparseTensor` with shape `[N, M]`, and with all empty + rows filled in with `default_value`. + empty_row_indicator: A bool vector of length `N` indicating whether each + input row was empty. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + with ops.name_scope(name, "SparseFillEmptyRows", [sp_input]): + default_value = ops.convert_to_tensor( + default_value, dtype=sp_input.values.dtype) + (output_indices, output_values, empty_row_indicator, + unused_reverse_index_map) = gen_sparse_ops.sparse_fill_empty_rows( + indices=sp_input.indices, + values=sp_input.values, + dense_shape=sp_input.dense_shape, + default_value=default_value) + return (sparse_tensor.SparseTensor( + indices=output_indices, + values=output_values, + dense_shape=sp_input.dense_shape), empty_row_indicator) + + +@tf_export(v1=["io.serialize_sparse", "serialize_sparse"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("serialize_sparse") +def serialize_sparse(sp_input, name=None, out_type=dtypes.string): + """Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object. + + Args: + sp_input: The input `SparseTensor`. + name: A name prefix for the returned tensors (optional). + out_type: The `dtype` to use for serialization. + + Returns: + A 3-vector (1-D `Tensor`), with each column representing the serialized + `SparseTensor`'s indices, values, and shape (respectively). + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + return serialize_sparse_v2(sp_input, out_type, name) + + +@tf_export("io.serialize_sparse", v1=[]) +@dispatch.add_dispatch_support +def serialize_sparse_v2(sp_input, out_type=dtypes.string, name=None): + """Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object. + + Args: + sp_input: The input `SparseTensor`. + out_type: The `dtype` to use for serialization. + name: A name prefix for the returned tensors (optional). + + Returns: + A 3-vector (1-D `Tensor`), with each column representing the serialized + `SparseTensor`'s indices, values, and shape (respectively). + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + return gen_sparse_ops.serialize_sparse( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + name=name, + out_type=out_type) + + +@tf_export(v1=["io.serialize_many_sparse", "serialize_many_sparse"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("serialize_many_sparse") +def serialize_many_sparse(sp_input, name=None, out_type=dtypes.string): + """Serialize `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor`. + + The `SparseTensor` must have rank `R` greater than 1, and the first dimension + is treated as the minibatch dimension. Elements of the `SparseTensor` + must be sorted in increasing order of this first dimension. The serialized + `SparseTensor` objects going into each row of the output `Tensor` will have + rank `R-1`. + + The minibatch size `N` is extracted from `sparse_shape[0]`. + + Args: + sp_input: The input rank `R` `SparseTensor`. + name: A name prefix for the returned tensors (optional). + out_type: The `dtype` to use for serialization. + + Returns: + A matrix (2-D `Tensor`) with `N` rows and `3` columns. Each column + represents serialized `SparseTensor`'s indices, values, and shape + (respectively). + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + return serialize_many_sparse_v2(sp_input, out_type, name) + + +@tf_export("io.serialize_many_sparse", v1=[]) +@dispatch.add_dispatch_support +def serialize_many_sparse_v2(sp_input, out_type=dtypes.string, name=None): + """Serialize `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor`. + + The `SparseTensor` must have rank `R` greater than 1, and the first dimension + is treated as the minibatch dimension. Elements of the `SparseTensor` + must be sorted in increasing order of this first dimension. The serialized + `SparseTensor` objects going into each row of the output `Tensor` will have + rank `R-1`. + + The minibatch size `N` is extracted from `sparse_shape[0]`. + + Args: + sp_input: The input rank `R` `SparseTensor`. + out_type: The `dtype` to use for serialization. + name: A name prefix for the returned tensors (optional). + + Returns: + A matrix (2-D `Tensor`) with `N` rows and `3` columns. Each column + represents serialized `SparseTensor`'s indices, values, and shape + (respectively). + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + return gen_sparse_ops.serialize_many_sparse( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + name=name, + out_type=out_type) + + +def deserialize_sparse(serialized_sparse, dtype, rank=None, name=None): + """Deserialize `SparseTensor` objects. + + The input `serialized_sparse` must have the shape `[?, ?, ..., ?, 3]` where + the last dimension stores serialized `SparseTensor` objects and the other N + dimensions (N >= 0) correspond to a batch. The ranks of the original + `SparseTensor` objects must all match. When the final `SparseTensor` is + created, its rank is the rank of the incoming `SparseTensor` objects plus N; + the sparse tensors have been concatenated along new dimensions, one for each + batch. + + The output `SparseTensor` object's shape values for the original dimensions + are the max across the input `SparseTensor` objects' shape values for the + corresponding dimensions. The new dimensions match the size of the batch. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `SparseReorder` to restore index ordering. + + For example, if the serialized input is a `[2 x 3]` matrix representing two + original `SparseTensor` objects: + + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + + and + + index = [ 2] + [10] + values = [4, 5] + shape = [30] + + then the final deserialized `SparseTensor` will be: + + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + + Args: + serialized_sparse: The serialized `SparseTensor` objects. + The last dimension must have 3 columns. + dtype: The `dtype` of the serialized `SparseTensor` objects. + rank: (optional) Python int, the rank of the `SparseTensor` objects. + name: A name prefix for the returned tensors (optional). + + Returns: + A `SparseTensor` representing the deserialized `SparseTensor` objects. + + """ + output_indices, output_values, output_shape = ( + gen_sparse_ops.deserialize_sparse(serialized_sparse, dtype, name=name)) + + # Feed rank data back in, if available + output_indices.set_shape([None, rank]) + output_shape.set_shape([rank]) + + return sparse_tensor.SparseTensor(output_indices, output_values, output_shape) + + +@tf_export( + "io.deserialize_many_sparse", + v1=["io.deserialize_many_sparse", "deserialize_many_sparse"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("deserialize_many_sparse") +def deserialize_many_sparse(serialized_sparse, dtype, rank=None, name=None): + """Deserialize and concatenate `SparseTensors` from a serialized minibatch. + + The input `serialized_sparse` must be a string matrix of shape `[N x 3]` where + `N` is the minibatch size and the rows correspond to packed outputs of + `serialize_sparse`. The ranks of the original `SparseTensor` objects + must all match. When the final `SparseTensor` is created, it has rank one + higher than the ranks of the incoming `SparseTensor` objects (they have been + concatenated along a new row dimension). + + The output `SparseTensor` object's shape values for all dimensions but the + first are the max across the input `SparseTensor` objects' shape values + for the corresponding dimensions. Its first shape value is `N`, the minibatch + size. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `sparse.reorder` to restore index ordering. + + For example, if the serialized input is a `[2, 3]` matrix representing two + original `SparseTensor` objects: + + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + + and + + index = [ 2] + [10] + values = [4, 5] + shape = [30] + + then the final deserialized `SparseTensor` will be: + + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + + Args: + serialized_sparse: 2-D `Tensor` of type `string` of shape `[N, 3]`. + The serialized and packed `SparseTensor` objects. + dtype: The `dtype` of the serialized `SparseTensor` objects. + rank: (optional) Python int, the rank of the `SparseTensor` objects. + name: A name prefix for the returned tensors (optional) + + Returns: + A `SparseTensor` representing the deserialized `SparseTensor`s, + concatenated along the `SparseTensor`s' first dimension. + + All of the serialized `SparseTensor`s must have had the same rank and type. + """ + output_indices, output_values, output_shape = ( + gen_sparse_ops.deserialize_many_sparse( + serialized_sparse, dtype, name=name)) + + # Feed rank data back in, if available + output_indices.set_shape([None, rank]) + output_shape.set_shape([rank]) + + return sparse_tensor.SparseTensor(output_indices, output_values, output_shape) + + +@tf_export("sparse.sparse_dense_matmul", + v1=["sparse.sparse_dense_matmul", "sparse.matmul", + "sparse_tensor_dense_matmul"]) +@deprecation.deprecated_endpoints("sparse_tensor_dense_matmul") +def sparse_tensor_dense_matmul(sp_a, + b, + adjoint_a=False, + adjoint_b=False, + name=None): + # pylint: disable=line-too-long + """Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix + + (or SparseTensor) "B". Please note that one and only one of the inputs MUST + be a SparseTensor and the other MUST be a dense matrix. + + The following input format is recommended (but not required) for optimal + performance: + + * If `adjoint_a == false`: `A` should be sorted in lexicographically + increasing order. Use `sparse.reorder` if you're not sure. + * If `adjoint_a == true`: `A` should be sorted in order of increasing + dimension 1 (i.e., "column major" order instead of "row major" order). + + Args: + sp_a: SparseTensor (or dense Matrix) A, of rank 2. + b: dense Matrix (or SparseTensor) B, with the same dtype as sp_a. + adjoint_a: Use the adjoint of A in the matrix multiply. If A is complex, + this is transpose(conj(A)). Otherwise it's transpose(A). + adjoint_b: Use the adjoint of B in the matrix multiply. If B is complex, + this is transpose(conj(B)). Otherwise it's transpose(B). + name: A name prefix for the returned tensors (optional) + + Returns: + A dense matrix (pseudo-code in dense np.matrix notation): + `A = A.H if adjoint_a else A` + `B = B.H if adjoint_b else B` + `return A*B` + + Notes: + + Using `tf.nn.embedding_lookup_sparse` for sparse multiplication: + + It's not obvious but you can consider `embedding_lookup_sparse` as another + sparse and dense multiplication. In some situations, you may prefer to use + `embedding_lookup_sparse` even though you're not dealing with embeddings. + + There are two questions to ask in the decision process: Do you need gradients + computed as sparse too? Is your sparse data represented as two + `SparseTensor`s: ids and values? There is more explanation about data format + below. If you answer any of these questions as yes, consider using + `tf.nn.embedding_lookup_sparse`. + + Following explains differences between the expected SparseTensors: + For example if dense form of your sparse data has shape `[3, 5]` and values: + + [[ a ] + [b c] + [ d ]] + + + `SparseTensor` format expected by `sparse_tensor_dense_matmul`: + `sp_a` (indices, values): + + [0, 1]: a + [1, 0]: b + [1, 4]: c + [2, 2]: d + + `SparseTensor` format expected by `embedding_lookup_sparse`: + `sp_ids` `sp_weights` + + [0, 0]: 1 [0, 0]: a + [1, 0]: 0 [1, 0]: b + [1, 1]: 4 [1, 1]: c + [2, 0]: 2 [2, 0]: d + + + Deciding when to use `sparse_tensor_dense_matmul` vs. + `matmul`(a_is_sparse=True): + + There are a number of questions to ask in the decision process, including: + + * Will the SparseTensor `A` fit in memory if densified? + * Is the column count of the product large (>> 1)? + * Is the density of `A` larger than approximately 15%? + + If the answer to several of these questions is yes, consider + converting the `SparseTensor` to a dense one and using `tf.matmul` with + `a_is_sparse=True`. + + This operation tends to perform well when `A` is more sparse, if the column + size of the product is small (e.g. matrix-vector multiplication), if + `sp_a.dense_shape` takes on large values. + + Below is a rough speed comparison between `sparse_tensor_dense_matmul`, + labeled 'sparse', and `matmul`(a_is_sparse=True), labeled 'dense'. For + purposes of the comparison, the time spent converting from a `SparseTensor` to + a dense `Tensor` is not included, so it is overly conservative with respect to + the time ratio. + + Benchmark system: + CPU: Intel Ivybridge with HyperThreading (6 cores) dL1:32KB dL2:256KB dL3:12MB + GPU: NVidia Tesla k40c + + Compiled with: + `-c opt --config=cuda --copt=-mavx` + + ``` + tensorflow/python/sparse_tensor_dense_matmul_op_test --benchmarks + A sparse [m, k] with % nonzero values between 1% and 80% + B dense [k, n] + + % nnz n gpu m k dt(dense) dt(sparse) dt(sparse)/dt(dense) + 0.01 1 True 100 100 0.000221166 0.00010154 0.459112 + 0.01 1 True 100 1000 0.00033858 0.000109275 0.322745 + 0.01 1 True 1000 100 0.000310557 9.85661e-05 0.317385 + 0.01 1 True 1000 1000 0.0008721 0.000100875 0.115669 + 0.01 1 False 100 100 0.000208085 0.000107603 0.51711 + 0.01 1 False 100 1000 0.000327112 9.51118e-05 0.290762 + 0.01 1 False 1000 100 0.000308222 0.00010345 0.335635 + 0.01 1 False 1000 1000 0.000865721 0.000101397 0.117124 + 0.01 10 True 100 100 0.000218522 0.000105537 0.482958 + 0.01 10 True 100 1000 0.000340882 0.000111641 0.327506 + 0.01 10 True 1000 100 0.000315472 0.000117376 0.372064 + 0.01 10 True 1000 1000 0.000905493 0.000123263 0.136128 + 0.01 10 False 100 100 0.000221529 9.82571e-05 0.44354 + 0.01 10 False 100 1000 0.000330552 0.000112615 0.340687 + 0.01 10 False 1000 100 0.000341277 0.000114097 0.334324 + 0.01 10 False 1000 1000 0.000819944 0.000120982 0.147549 + 0.01 25 True 100 100 0.000207806 0.000105977 0.509981 + 0.01 25 True 100 1000 0.000322879 0.00012921 0.400181 + 0.01 25 True 1000 100 0.00038262 0.00014158 0.370035 + 0.01 25 True 1000 1000 0.000865438 0.000202083 0.233504 + 0.01 25 False 100 100 0.000209401 0.000104696 0.499979 + 0.01 25 False 100 1000 0.000321161 0.000130737 0.407076 + 0.01 25 False 1000 100 0.000377012 0.000136801 0.362856 + 0.01 25 False 1000 1000 0.000861125 0.00020272 0.235413 + 0.2 1 True 100 100 0.000206952 9.69219e-05 0.46833 + 0.2 1 True 100 1000 0.000348674 0.000147475 0.422959 + 0.2 1 True 1000 100 0.000336908 0.00010122 0.300439 + 0.2 1 True 1000 1000 0.001022 0.000203274 0.198898 + 0.2 1 False 100 100 0.000207532 9.5412e-05 0.459746 + 0.2 1 False 100 1000 0.000356127 0.000146824 0.41228 + 0.2 1 False 1000 100 0.000322664 0.000100918 0.312764 + 0.2 1 False 1000 1000 0.000998987 0.000203442 0.203648 + 0.2 10 True 100 100 0.000211692 0.000109903 0.519165 + 0.2 10 True 100 1000 0.000372819 0.000164321 0.440753 + 0.2 10 True 1000 100 0.000338651 0.000144806 0.427596 + 0.2 10 True 1000 1000 0.00108312 0.000758876 0.70064 + 0.2 10 False 100 100 0.000215727 0.000110502 0.512231 + 0.2 10 False 100 1000 0.000375419 0.0001613 0.429653 + 0.2 10 False 1000 100 0.000336999 0.000145628 0.432132 + 0.2 10 False 1000 1000 0.00110502 0.000762043 0.689618 + 0.2 25 True 100 100 0.000218705 0.000129913 0.594009 + 0.2 25 True 100 1000 0.000394794 0.00029428 0.745402 + 0.2 25 True 1000 100 0.000404483 0.0002693 0.665788 + 0.2 25 True 1000 1000 0.0012002 0.00194494 1.62052 + 0.2 25 False 100 100 0.000221494 0.0001306 0.589632 + 0.2 25 False 100 1000 0.000396436 0.000297204 0.74969 + 0.2 25 False 1000 100 0.000409346 0.000270068 0.659754 + 0.2 25 False 1000 1000 0.00121051 0.00193737 1.60046 + 0.5 1 True 100 100 0.000214981 9.82111e-05 0.456836 + 0.5 1 True 100 1000 0.000415328 0.000223073 0.537101 + 0.5 1 True 1000 100 0.000358324 0.00011269 0.314492 + 0.5 1 True 1000 1000 0.00137612 0.000437401 0.317851 + 0.5 1 False 100 100 0.000224196 0.000101423 0.452386 + 0.5 1 False 100 1000 0.000400987 0.000223286 0.556841 + 0.5 1 False 1000 100 0.000368825 0.00011224 0.304318 + 0.5 1 False 1000 1000 0.00136036 0.000429369 0.31563 + 0.5 10 True 100 100 0.000222125 0.000112308 0.505608 + 0.5 10 True 100 1000 0.000461088 0.00032357 0.701753 + 0.5 10 True 1000 100 0.000394624 0.000225497 0.571422 + 0.5 10 True 1000 1000 0.00158027 0.00190898 1.20801 + 0.5 10 False 100 100 0.000232083 0.000114978 0.495418 + 0.5 10 False 100 1000 0.000454574 0.000324632 0.714146 + 0.5 10 False 1000 100 0.000379097 0.000227768 0.600817 + 0.5 10 False 1000 1000 0.00160292 0.00190168 1.18638 + 0.5 25 True 100 100 0.00023429 0.000151703 0.647501 + 0.5 25 True 100 1000 0.000497462 0.000598873 1.20386 + 0.5 25 True 1000 100 0.000460778 0.000557038 1.20891 + 0.5 25 True 1000 1000 0.00170036 0.00467336 2.74845 + 0.5 25 False 100 100 0.000228981 0.000155334 0.678371 + 0.5 25 False 100 1000 0.000496139 0.000620789 1.25124 + 0.5 25 False 1000 100 0.00045473 0.000551528 1.21287 + 0.5 25 False 1000 1000 0.00171793 0.00467152 2.71927 + 0.8 1 True 100 100 0.000222037 0.000105301 0.47425 + 0.8 1 True 100 1000 0.000410804 0.000329327 0.801664 + 0.8 1 True 1000 100 0.000349735 0.000131225 0.375212 + 0.8 1 True 1000 1000 0.00139219 0.000677065 0.48633 + 0.8 1 False 100 100 0.000214079 0.000107486 0.502085 + 0.8 1 False 100 1000 0.000413746 0.000323244 0.781261 + 0.8 1 False 1000 100 0.000348983 0.000131983 0.378193 + 0.8 1 False 1000 1000 0.00136296 0.000685325 0.50282 + 0.8 10 True 100 100 0.000229159 0.00011825 0.516017 + 0.8 10 True 100 1000 0.000498845 0.000532618 1.0677 + 0.8 10 True 1000 100 0.000383126 0.00029935 0.781336 + 0.8 10 True 1000 1000 0.00162866 0.00307312 1.88689 + 0.8 10 False 100 100 0.000230783 0.000124958 0.541452 + 0.8 10 False 100 1000 0.000493393 0.000550654 1.11606 + 0.8 10 False 1000 100 0.000377167 0.000298581 0.791642 + 0.8 10 False 1000 1000 0.00165795 0.00305103 1.84024 + 0.8 25 True 100 100 0.000233496 0.000175241 0.75051 + 0.8 25 True 100 1000 0.00055654 0.00102658 1.84458 + 0.8 25 True 1000 100 0.000463814 0.000783267 1.68875 + 0.8 25 True 1000 1000 0.00186905 0.00755344 4.04132 + 0.8 25 False 100 100 0.000240243 0.000175047 0.728625 + 0.8 25 False 100 1000 0.000578102 0.00104499 1.80763 + 0.8 25 False 1000 100 0.000485113 0.000776849 1.60138 + 0.8 25 False 1000 1000 0.00211448 0.00752736 3.55992 + ``` + + """ + # pylint: enable=line-too-long + + if isinstance(b, sparse_tensor.SparseTensor) \ + or isinstance(b, sparse_tensor.SparseTensorValue): + # We can do C * D where C is sparse but if we want to do A * B when + # B is sparse we have to transpose. But AB = (B'A')' so we have to feed in + # the transpose of the arguments as well. + if adjoint_a != adjoint_b: + return array_ops.transpose( + sparse_tensor_dense_matmul(b, sp_a, adjoint_a, adjoint_b)) + else: + return array_ops.transpose( + sparse_tensor_dense_matmul( + b, sp_a, adjoint_a=not adjoint_a, adjoint_b=not adjoint_b)) + + else: + sp_a = _convert_to_sparse_tensor(sp_a) + with ops.name_scope(name, "SparseTensorDenseMatMul", + [sp_a.indices, sp_a.values, b]) as name: + b = ops.convert_to_tensor(b, name="b") + return gen_sparse_ops.sparse_tensor_dense_mat_mul( + a_indices=sp_a.indices, + a_values=sp_a.values, + a_shape=sp_a.dense_shape, + b=b, + adjoint_a=adjoint_a, + adjoint_b=adjoint_b) + + +@tf_export("sparse.softmax", v1=["sparse.softmax", "sparse_softmax"]) +@deprecation.deprecated_endpoints("sparse_softmax") +def sparse_softmax(sp_input, name=None): + """Applies softmax to a batched N-D `SparseTensor`. + + The inputs represent an N-D SparseTensor with logical shape `[..., B, C]` + (where `N >= 2`), and with indices sorted in the canonical lexicographic + order. + + This op is equivalent to applying the normal `tf.nn.softmax()` to each + innermost logical submatrix with shape `[B, C]`, but with the catch that *the + implicitly zero elements do not participate*. Specifically, the algorithm is + equivalent to: + + (1) Applies `tf.nn.softmax()` to a densified view of each innermost + submatrix with shape `[B, C]`, along the size-C dimension; + (2) Masks out the original implicitly-zero locations; + (3) Renormalizes the remaining elements. + + Hence, the `SparseTensor` result has exactly the same non-zero indices and + shape. + + Example using a 3-D SparseTensor: + + >>> st = tf.sparse.from_dense( + ... [[[0., np.e], + ... [1., 0.]], + ... + ... [[np.e, 0.], + ... [np.e, np.e]]]) + >>> res = tf.sparse.softmax(st) + >>> res.indices + + >>> res.values + + >>> res.dense_shape + + >>> tf.sparse.to_dense(res) + + + Args: + sp_input: N-D `SparseTensor`, where `N >= 2`. + name: optional name of the operation. + Returns: + output: N-D `SparseTensor` representing the results. + """ + with ops.name_scope(name, "SparseSoftmax", + [sp_input.indices, sp_input.values]) as name: + out_vals = gen_sparse_ops.sparse_softmax(sp_input.indices, sp_input.values, + sp_input.dense_shape) + return sparse_tensor.SparseTensor(sp_input.indices, out_vals, + sp_input.dense_shape) + + +@tf_export("sparse.maximum", v1=["sparse.maximum", "sparse_maximum"]) +@deprecation.deprecated_endpoints("sparse_maximum") +def sparse_maximum(sp_a, sp_b, name=None): + """Returns the element-wise max of two SparseTensors. + + Assumes the two SparseTensors have the same shape, i.e., no broadcasting. + + Example: + + >>> sp_zero = tf.sparse.SparseTensor([[0]], [0], [7]) + >>> sp_one = tf.sparse.SparseTensor([[1]], [1], [7]) + >>> res = tf.sparse.maximum(sp_zero, sp_one) + >>> res.indices + + >>> res.values + + >>> res.dense_shape + + + The reduction version of this elementwise operation is `tf.sparse.reduce_max` + + Args: + sp_a: a `SparseTensor` operand whose dtype is real, and indices + lexicographically ordered. + sp_b: the other `SparseTensor` operand with the same requirements (and the + same shape). + name: optional name of the operation. + Returns: + output: the output SparseTensor. + """ + with ops.name_scope( + name, "SparseSparseMaximum", + [sp_a.indices, sp_a.values, sp_b.indices, sp_b.values]) as name: + out_indices, out_values = gen_sparse_ops.sparse_sparse_maximum( + sp_a.indices, + sp_a.values, + sp_a.dense_shape, + sp_b.indices, + sp_b.values, + sp_b.dense_shape, + name=name) + return sparse_tensor.SparseTensor(out_indices, out_values, sp_a.dense_shape) + + +@tf_export("sparse.minimum", v1=["sparse.minimum", "sparse_minimum"]) +@deprecation.deprecated_endpoints("sparse_minimum") +def sparse_minimum(sp_a, sp_b, name=None): + """Returns the element-wise min of two SparseTensors. + + Assumes the two SparseTensors have the same shape, i.e., no broadcasting. + + Example: + + >>> sp_zero = tf.sparse.SparseTensor([[0]], [0], [7]) + >>> sp_one = tf.sparse.SparseTensor([[1]], [1], [7]) + >>> res = tf.sparse.minimum(sp_zero, sp_one) + >>> res.indices + + >>> res.values + + >>> res.dense_shape + + + Args: + sp_a: a `SparseTensor` operand whose dtype is real, and indices + lexicographically ordered. + sp_b: the other `SparseTensor` operand with the same requirements (and the + same shape). + name: optional name of the operation. + Returns: + output: the output SparseTensor. + """ + with ops.name_scope( + name, "SparseSparseMinimum", + [sp_a.indices, sp_a.values, sp_b.indices, sp_b.values]) as name: + out_indices, out_values = gen_sparse_ops.sparse_sparse_minimum( + sp_a.indices, + sp_a.values, + sp_a.dense_shape, + sp_b.indices, + sp_b.values, + sp_b.dense_shape, + name=name) + return sparse_tensor.SparseTensor(out_indices, out_values, sp_a.dense_shape) + + +@tf_export("sparse.transpose", v1=["sparse.transpose", "sparse_transpose"]) +@deprecation.deprecated_endpoints("sparse_transpose") +def sparse_transpose(sp_input, perm=None, name=None): + """Transposes a `SparseTensor`. + + Permutes the dimensions according to the value of `perm`. This is the sparse + version of `tf.transpose`. + + The returned tensor's dimension `i` will correspond to the input dimension + `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank + of the input tensor. Hence, by default, this operation performs a regular + matrix transpose on 2-D input Tensors. + + For example: + + >>> x = tf.SparseTensor(indices=[[0, 1], [0, 3], [2, 3], [3, 1]], + ... values=[1.1, 2.2, 3.3, 4.4], + ... dense_shape=[4, 5]) + >>> print('x =', tf.sparse.to_dense(x)) + x = tf.Tensor( + [[0. 1.1 0. 2.2 0. ] + [0. 0. 0. 0. 0. ] + [0. 0. 0. 3.3 0. ] + [0. 4.4 0. 0. 0. ]], shape=(4, 5), dtype=float32) + + >>> x_transpose = tf.sparse.transpose(x) + >>> print('x_transpose =', tf.sparse.to_dense(x_transpose)) + x_transpose = tf.Tensor( + [[0. 0. 0. 0. ] + [1.1 0. 0. 4.4] + [0. 0. 0. 0. ] + [2.2 0. 3.3 0. ] + [0. 0. 0. 0. ]], shape=(5, 4), dtype=float32) + + Equivalently, you could call `tf.sparse.transpose(x, perm=[1, 0])`. The + `perm` argument is more useful for n-dimensional tensors where n > 2. + + >>> x = tf.SparseTensor(indices=[[0, 0, 1], [0, 0, 3], [1, 2, 3], [1, 3, 1]], + ... values=[1.1, 2.2, 3.3, 4.4], + ... dense_shape=[2, 4, 5]) + >>> print('x =', tf.sparse.to_dense(x)) + x = tf.Tensor( + [[[0. 1.1 0. 2.2 0. ] + [0. 0. 0. 0. 0. ] + [0. 0. 0. 0. 0. ] + [0. 0. 0. 0. 0. ]] + [[0. 0. 0. 0. 0. ] + [0. 0. 0. 0. 0. ] + [0. 0. 0. 3.3 0. ] + [0. 4.4 0. 0. 0. ]]], shape=(2, 4, 5), dtype=float32) + + As above, simply calling `tf.sparse.transpose` will default to `perm=[2,1,0]`. + + To take the transpose of a batch of sparse matrices, where 0 is the batch + dimension, you would set `perm=[0,2,1]`. + + >>> x_transpose = tf.sparse.transpose(x, perm=[0, 2, 1]) + >>> print('x_transpose =', tf.sparse.to_dense(x_transpose)) + x_transpose = tf.Tensor( + [[[0. 0. 0. 0. ] + [1.1 0. 0. 0. ] + [0. 0. 0. 0. ] + [2.2 0. 0. 0. ] + [0. 0. 0. 0. ]] + [[0. 0. 0. 0. ] + [0. 0. 0. 4.4] + [0. 0. 0. 0. ] + [0. 0. 3.3 0. ] + [0. 0. 0. 0. ]]], shape=(2, 5, 4), dtype=float32) + + Args: + sp_input: The input `SparseTensor`. + perm: A permutation vector of the dimensions of `sp_input`. + name: A name prefix for the returned tensors (optional). + + Returns: + A transposed `SparseTensor`. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + with ops.name_scope(name, "SparseTranspose", [sp_input]) as name: + if perm is None: + if sp_input.shape.rank is not None: + rank = sp_input.shape.rank + perm = (rank - 1) - np.arange(0, rank, 1) + else: + rank = array_ops.rank(sp_input) + perm = (rank - 1) - math_ops.range(0, rank, 1) + indices = sp_input.indices + transposed_indices = array_ops.transpose( + array_ops.gather(array_ops.transpose(indices), perm)) + + perm_ = tensor_util.constant_value(ops.convert_to_tensor(perm)) + if perm_ is not None and sp_input.get_shape().is_fully_defined(): + old_shape_ = sp_input.get_shape().as_list() + transposed_dense_shape = list(old_shape_) # Copy. + for i, p in enumerate(perm_): + transposed_dense_shape[i] = old_shape_[p] + else: + dense_shape = sp_input.dense_shape + transposed_dense_shape = array_ops.gather(dense_shape, perm) + transposed_st = sparse_tensor.SparseTensor( + transposed_indices, sp_input.values, transposed_dense_shape) + transposed_st = sparse_reorder(transposed_st) + return transposed_st + + +@tf_export("sparse.map_values", v1=[]) +@dispatch.add_dispatch_support +def map_values(op, *args, **kwargs): + """Applies `op` to the `.values` tensor of one or more `SparseTensor`s. + + Replaces any `SparseTensor` in `args` or `kwargs` with its `values` + tensor (which contains the non-default values for the SparseTensor), + and then calls `op`. Returns a `SparseTensor` that is constructed + from the input `SparseTensor`s' `indices`, `dense_shape`, and the + value returned by the `op`. + + If the input arguments contain multiple `SparseTensor`s, then they must have + equal `indices` and dense shapes. + + Examples: + + >>> s = tf.sparse.from_dense([[1, 2, 0], + ... [0, 4, 0], + ... [1, 0, 0]]) + >>> tf.sparse.to_dense(tf.sparse.map_values(tf.ones_like, s)).numpy() + array([[1, 1, 0], + [0, 1, 0], + [1, 0, 0]], dtype=int32) + + >>> tf.sparse.to_dense(tf.sparse.map_values(tf.multiply, s, s)).numpy() + array([[ 1, 4, 0], + [ 0, 16, 0], + [ 1, 0, 0]], dtype=int32) + + >>> tf.sparse.to_dense(tf.sparse.map_values(tf.add, s, 5)).numpy() + array([[6, 7, 0], + [0, 9, 0], + [6, 0, 0]], dtype=int32) + + Note: even though `tf.add(0, 5) != 0`, implicit zeros + will remain unchanged. However, if the sparse tensor contains any explicit + zeros, these will be affected by the mapping! + + Args: + op: The operation that should be applied to the SparseTensor `values`. `op` + is typically an element-wise operation (such as math_ops.add), but any + operation that preserves the shape can be used. + *args: Arguments for `op`. + **kwargs: Keyword arguments for `op`. + + Returns: + A `SparseTensor` whose `indices` and `dense_shape` matches the `indices` + and `dense_shape` of all input `SparseTensor`s. + Raises: + ValueError: If args contains no `SparseTensor`, or if the `indices` + or `dense_shape`s of the input `SparseTensor`s are not equal. + """ + sparse_list = [] + inner_args = _replace_sparse_with_values(args, sparse_list) + inner_kwargs = _replace_sparse_with_values(kwargs, sparse_list) + if not sparse_list: + raise ValueError("No SparseTensor in argument list of map_values") + + with ops.control_dependencies(_assert_sparse_compatible(sparse_list)): + # Delegate to op, and then compose the result from the transformed values + # and the known indices/dense shape. Since we ensure that indices and shape + # are identical, we can just use the first one. + return sparse_tensor.SparseTensor(sparse_list[0].indices, + op(*inner_args, **inner_kwargs), + sparse_list[0].dense_shape) + + +@dispatch.dispatch_for_api(bincount_ops.bincount) +def bincount(arr: sparse_tensor.SparseTensor, + weights=None, + minlength=None, + maxlength=None, + dtype=dtypes.int32, + name=None, + axis=None, + binary_output=False): + """Counts the number of occurrences of each value in an integer array. + + Only the values in the SparseTensor's `values` tensor are counted, + missing zeros are ignored. + + If `minlength` and `maxlength` are not given, returns a vector with length + `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [1, 7], [2, 4], [3, 0], + ... [4, 9], [5, 1], [6, 8], [7, 2]], + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[8, 10]) + >>> tf.math.bincount(data) + + + Vector length = Maximum element in vector `values` is 5. Adding 1, which is 6 + will be the vector length. + + Each bin value in the output indicates number of occurrences of the particular + index. Here, index 1 in output has a value 2. This indicates value 1 occurs + two times in `values`. + + **Bin-counting with weights** + + >>> indices=[[0, 3], [1, 7], [2, 4], [3, 0], [4, 9], [5, 1], [6, 8], [7, 2]] + >>> data = tf.sparse.SparseTensor( + ... indices=indices, + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[8, 10]) + >>> weights = tf.sparse.SparseTensor( + ... indices=indices, + ... values=[1,5,0,1,0,5,4,5], + ... dense_shape=[8, 10]) + >>> tf.math.bincount(data, weights=weights) + + + When `weights` is specified, bins will be incremented by the corresponding + weight instead of 1. Here, index 1 in output has a value 6. This is the + summation of `weights` corresponding to the value in `values` (i.e. for index + 1, the first two data values are 1 so the first two weights, 1 and 5, are + summed). + + On GPU, `bincount` with weights is only supported when `axis=0` and XLA is + enabled (typically when a function decorated with + `@tf.function(jit_compile=True)`). + + **Bin-counting matrix rows independently** + + This example uses `axis=-1` with a 2 dimensional input and returns a + `Tensor` with bincounting where axis 0 is **not** flattened, i.e. an + independent bincount for each matrix row. + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [0, 7], [1, 4], [1, 0], + ... [1, 9], [2, 1], [2, 8], [2, 2]], + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[3, 10]) + >>> tf.math.bincount(data, axis=-1) + + + **Bin-counting with binary_output** + + This example gives binary output instead of counting the occurrence. + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [0, 7], [1, 4], [1, 0], + ... [1, 9], [2, 1], [2, 8], [2, 2]], + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[3, 10]) + >>> tf.math.bincount(data, axis=-1, binary_output=True) + + + **Missing zeros in SparseTensor** + + Note that missing zeros (implict zeros) in SparseTensor are **NOT** counted. + This supports cases such as `0` in the values tensor indicates that index/id + `0`is present and a missing zero indicates that no index/id is present. + + If counting missing zeros is desired, there are workarounds. + For the `axis=0` case, the number of missing zeros can computed by subtracting + the number of elements in the SparseTensor's `values` tensor from the + number of elements in the dense shape, and this difference can be added to the + first element of the output of `bincount`. For all cases, the SparseTensor + can be converted to a dense Tensor with `tf.sparse.to_dense` before calling + `tf.math.bincount`. + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [1, 7], [2, 4], [3, 0], + ... [4, 9], [5, 1], [6, 8], [7, 2]], + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[8, 10]) + >>> counts = tf.math.bincount(data, dtype=tf.int64) + >>> dense_size = tf.math.reduce_prod(data.dense_shape) + >>> missing_zeros = dense_size - tf.size(data.values, out_type=tf.int64) + >>> tf.concat([[counts[0] + missing_zeros], counts[1:]], 0) + + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [1, 7], [2, 4], [3, 0], + ... [4, 9], [5, 1], [6, 8], [7, 2]], + ... values=[1,1,2,3,2,4,4,5], + ... dense_shape=[8, 10]) + >>> tf.math.bincount(tf.sparse.to_dense(data), dtype=tf.int64) + + + + Args: + arr: A SparseTensor whose values should be counted. + These tensors must have a rank of 2 if `axis=-1`. + weights: If non-None, must be a SparseTensor with the same dense shape and + same indices as `arr`. For each value in `arr`, the bin will be + incremented by the corresponding weight instead of 1. If non-None, + `binary_output` must be False. + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `arr` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + dtype: If `weights` is None, determines the type of the output bins. + name: A name scope for the associated operations (optional). + axis: The axis to slice over. Axes at and below `axis` will be flattened + before bin counting. Currently, only `0`, and `-1` are supported. If None, + all axes will be flattened (identical to passing `0`). XLA does not + support `axis=-1`. + binary_output: If True, this op will output 1 instead of the number of times + a token appears (equivalent to one_hot + reduce_any instead of one_hot + + reduce_add). Defaults to False. + + Returns: + A vector with the same dtype as `weights` or the given `dtype` containing + the bincount values. + + Raises: + `InvalidArgumentError` if negative values are provided as an input. + + """ + name = "bincount" if name is None else name + with ops.name_scope(name): + if weights is not None and binary_output: + raise ValueError("Arguments `binary_output` and `weights` are mutually " + "exclusive. Please specify only one.") + + if not arr.dtype.is_integer: + arr = math_ops.cast(arr, dtypes.int32) + if axis is None: + axis = 0 + + if axis not in [0, -1]: + raise ValueError(f"Unsupported value for argument axis={axis}. Only 0 and" + " -1 are currently supported.") + + total_size = array_ops.size(arr) + array_is_nonempty = total_size > 0 + # For the case where all values are implicit zeros, reduce_max + # returns the integer closest to negative infinity. + max_value = math_ops.maximum(math_ops.reduce_max(arr.values), -1) + output_size = math_ops.cast(array_is_nonempty, arr.dtype) * (max_value + 1) + if minlength is not None: + minlength = ops.convert_to_tensor( + minlength, name="minlength", dtype=arr.dtype) + output_size = gen_math_ops.maximum(minlength, output_size) + if maxlength is not None: + maxlength = ops.convert_to_tensor( + maxlength, name="maxlength", dtype=arr.dtype) + output_size = gen_math_ops.minimum(maxlength, output_size) + + if axis == 0: + if weights is not None: + weights = validate_sparse_weights(arr, weights, dtype) + arr = arr.values + + if isinstance(arr, sparse_tensor.SparseTensor): + # axis != 0 case + weights = validate_sparse_weights(arr, weights, dtype) + return gen_math_ops.sparse_bincount( + indices=arr.indices, + values=arr.values, + dense_shape=arr.dense_shape, + size=output_size, + weights=weights, + binary_output=binary_output) + else: + # axis == 0 case + weights = bincount_ops.validate_dense_weights(arr, weights, dtype) + return gen_math_ops.dense_bincount( + input=arr, + size=output_size, + weights=weights, + binary_output=binary_output) + + +@tf_export("sparse.bincount") +@dispatch.add_dispatch_support +def sparse_bincount(values, + weights=None, + axis=0, + minlength=None, + maxlength=None, + binary_output=False, + name=None): + """Count the number of times an integer value appears in a tensor. + + This op takes an N-dimensional `Tensor`, `RaggedTensor`, or `SparseTensor`, + and returns an N-dimensional int64 SparseTensor where element + `[i0...i[axis], j]` contains the number of times the value `j` appears in + slice `[i0...i[axis], :]` of the input tensor. Currently, only N=0 and + N=-1 are supported. + + Args: + values: A Tensor, RaggedTensor, or SparseTensor whose values should be + counted. These tensors must have a rank of 2 if `axis=-1`. + weights: If non-None, must be the same shape as `arr`. If `arr` is a + SparseTensor, `weights` must be a SparseTensor with the same dense shape + and same indices as `arr`. For each value in `value`, the bin will be + incremented by the corresponding weight instead of 1. + axis: The axis to slice over. Axes at and below `axis` will be flattened + before bin counting. Currently, only `0`, and `-1` are supported. If None, + all axes will be flattened (identical to passing `0`). + minlength: If given, ensures the output has length at least `minlength`, + padding with zeros at the end if necessary. + maxlength: If given, skips values in `values` that are equal or greater than + `maxlength`, ensuring that the output has length at most `maxlength`. + binary_output: If True, this op will output 1 instead of the number of times + a token appears (equivalent to one_hot + reduce_any instead of one_hot + + reduce_add). Defaults to False. + name: A name for this op. + + Returns: + A SparseTensor with `output.shape = values.shape[:axis] + [N]`, where `N` is + * `maxlength` (if set); + * `minlength` (if set, and `minlength > reduce_max(values)`); + * `0` (if `values` is empty); + * `reduce_max(values) + 1` otherwise. + + Raises: + `InvalidArgumentError` if negative values are provided as an input. + + Examples: + + **Bin-counting every item in individual batches** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where the value of (i,j) is the + number of times value j appears in batch i. + + >>> data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount(data, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 0 30] + [ 1 11] + [ 1 101] + [ 1 10001]], shape=(6, 2), dtype=int64), + values=tf.Tensor([1 2 1 2 1 1], shape=(6,), dtype=int64), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + This example shows a sparse tensor input. Missing zeros are not counted. + + >>> data = tf.sparse.SparseTensor( + ... indices=[[0, 3], [0, 7], [0, 8], [0, 11], + ... [1, 9], [1, 11], [1, 18], [1, 27]], + ... values=[10, 20, 30, 20, 11, 101, 11, 10001], + ... dense_shape=[2, 30]) + >>> tf.sparse.bincount(data, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 0 30] + [ 1 11] + [ 1 101] + [ 1 10001]], shape=(6, 2), dtype=int64), + values=tf.Tensor([1 2 1 2 1 1], shape=(6,), dtype=int32), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + **Bin-counting with defined output shape** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where the value of (i,j) is the + number of times value j appears in batch i. However, all values of j + above 'maxlength' are ignored. The dense_shape of the output sparse tensor + is set to 'minlength'. Note that, while the input is identical to the + example above, the value '10001' in batch item 2 is dropped, and the + dense shape is [2, 500] instead of [2,10002] or [2, 102]. + + >>> minlength = maxlength = 500 + >>> data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount( + ... data, axis=-1, minlength=minlength, maxlength=maxlength) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 0 30] + [ 1 11] + [ 1 101]], shape=(5, 2), dtype=int64), + values=tf.Tensor([1 2 1 2 1], shape=(5,), dtype=int64), + dense_shape=tf.Tensor([ 2 500], shape=(2,), dtype=int64)) + + **Binary bin-counting** + + This example takes an input (which could be a Tensor, RaggedTensor, or + SparseTensor) and returns a SparseTensor where (i,j) is 1 if the value j + appears in batch i at least once and is 0 otherwise. Note that, even though + some values (like 20 in batch 1 and 11 in batch 2) appear more than once, + the 'values' tensor is all 1s. + + >>> data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64) + >>> tf.sparse.bincount(data, binary_output=True, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 0 30] + [ 1 11] + [ 1 101] + [ 1 10001]], shape=(6, 2), dtype=int64), + values=tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int64), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + **Weighted bin-counting** + + This example takes two inputs - a values tensor and a weights tensor. These + tensors must be identically shaped, and have the same row splits or indices + in the case of RaggedTensors or SparseTensors. When performing a weighted + count, the op will output a SparseTensor where the value of (i, j) is the + sum of the values in the weight tensor's batch i in the locations where + the values tensor has the value j. In this case, the output dtype is the + same as the dtype of the weights tensor. + + >>> data = np.array([[10, 20, 30, 20], [11, 101, 11, 10001]], dtype=np.int64) + >>> weights = [[2, 0.25, 15, 0.5], [2, 17, 3, 0.9]] + >>> tf.sparse.bincount(data, weights=weights, axis=-1) + SparseTensor(indices=tf.Tensor( + [[ 0 10] + [ 0 20] + [ 0 30] + [ 1 11] + [ 1 101] + [ 1 10001]], shape=(6, 2), dtype=int64), + values=tf.Tensor([2. 0.75 15. 5. 17. 0.9], shape=(6,), dtype=float32), + dense_shape=tf.Tensor([ 2 10002], shape=(2,), dtype=int64)) + + """ + with ops.name_scope(name, "count", [values, weights]): + if not isinstance(values, sparse_tensor.SparseTensor): + values = tensor_conversion.convert_to_tensor_v2_with_dispatch( + values, name="values") + if weights is not None: + # Note that `weights` is not used for dispatch and if there is a type + # mismatch between `values` and `weights`, `weights` can be a RaggedTensor + # (or potentially some other kind of CompositeTensor) where conversion + # to a dense tensor fails. + if not isinstance(weights, composite_tensor.CompositeTensor): + weights = tensor_conversion.convert_to_tensor_v2_with_dispatch( + weights, name="weights") + + if weights is not None and binary_output: + raise ValueError("Arguments `binary_output` and `weights` are mutually " + "exclusive. Please specify only one.") + + if axis is None: + axis = 0 + + if axis not in [0, -1]: + raise ValueError(f"Unsupported value for argument axis={axis}. Only 0 and" + " -1 are currently supported.") + + minlength_value = minlength if minlength is not None else -1 + maxlength_value = maxlength if maxlength is not None else -1 + + if axis == 0: + if isinstance(values, sparse_tensor.SparseTensor): + if weights is not None: + weights = validate_sparse_weights(values, weights) + values = values.values + else: + if weights is not None: + weights = array_ops.reshape(weights, [-1]) + values = array_ops.reshape(values, [-1]) + + if isinstance(values, sparse_tensor.SparseTensor): + weights = validate_sparse_weights(values, weights) + c_ind, c_val, c_shape = gen_count_ops.sparse_count_sparse_output( + values.indices, + values.values, + values.dense_shape, + weights, + minlength=minlength_value, + maxlength=maxlength_value, + binary_output=binary_output) + else: + weights = bincount_ops.validate_dense_weights(values, weights) + c_ind, c_val, c_shape = gen_count_ops.dense_count_sparse_output( + values, + weights=weights, + minlength=minlength_value, + maxlength=maxlength_value, + binary_output=binary_output) + + return sparse_tensor.SparseTensor(c_ind, c_val, c_shape) + + +def validate_sparse_weights(values, weights, dtype=None): + """Validates the passed weight tensor or creates an empty one.""" + if weights is None: + if dtype: + return array_ops.constant([], dtype=dtype) + return array_ops.constant([], dtype=values.values.dtype) + + if not isinstance(weights, sparse_tensor.SparseTensor): + raise ValueError( + "Argument `weights` must be a SparseTensor if `values` is a " + f"SparseTensor. Received weights={weights} of type: " + f"{type(weights).__name__}") + + checks = [] + if weights.dense_shape is not values.dense_shape: + checks.append( + check_ops.assert_equal( + weights.dense_shape, + values.dense_shape, + message="'weights' and 'values' must have the same dense shape.")) + if weights.indices is not values.indices: + checks.append( + check_ops.assert_equal( + weights.indices, + values.indices, + message="'weights' and 'values' must have the same indices.") + ) + if checks: + with ops.control_dependencies(checks): + weights = array_ops.identity(weights.values) + else: + weights = weights.values + + return weights + + +def _assert_sparse_compatible(sparse_tensors): + """Check that all of `sparse_tensors` have same `indices` and `dense_shape`. + + Args: + sparse_tensors: A list of sparse tensors. + + Returns: + An op to be used as a control dependency. + """ + checks = [] + first = sparse_tensors[0] + for t in sparse_tensors[1:]: + checks.append( + check_ops.assert_equal( + first.dense_shape, t.dense_shape, message="Mismatched shapes!")) + checks.append( + check_ops.assert_equal( + first.indices, t.indices, message="Mismatched indices!")) + return checks + + +def _replace_sparse_with_values(value, sparse_list): + """Replace `SparseTensor`s with their values in `value` + + Each `SparseTensor` in `value` is replaced by its `values` tensor, and + collects all `SparseTensor`s in `sparse_list`. + + Args: + value: A structure of `Tensor`s and `SparseTensor`s + sparse_list: A list. Output parameter that collects all `SparseTensor`s in + `value`. + + Returns: + `value` with each SparseTensor replaced by its `.value` attribute. + """ + flat_vals = nest.flatten(value, expand_composites=False) + new_vals = [] + for v in flat_vals: + if isinstance(v, sparse_tensor.SparseTensor): + sparse_list.append(v) + new_vals.append(v.values) + else: + new_vals.append(v) + return nest.pack_sequence_as(value, new_vals, expand_composites=False) + + +def _add_sparse_to_tensors_map(sp_input, + container=None, + shared_name=None, + name=None): + """Add a `SparseTensor` to a `SparseTensorsMap` and return its handle. + + Args: + sp_input: The input `SparseTensor`. + container: The container for the underlying `SparseTensorsMap` (optional). + shared_name: The shared name for the underlying `SparseTensorsMap` + (optional, defaults to the name of the newly created op). + name: A name prefix for the returned tensors (optional). + + Returns: + A string 1-vector (1D `Tensor`), with the single element representing the + a unique handle to a `SparseTensor` stored by the `SparseTensorMap` + underlying this op. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + return gen_sparse_ops.add_sparse_to_tensors_map( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + container=container, + shared_name=shared_name, + name=name) + + +def _add_many_sparse_to_tensors_map(sp_input, + container=None, + shared_name=None, + name=None): + """Add a minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles. + + The `SparseTensor` must have rank `R` greater than 1, and the first dimension + is treated as the minibatch dimension. Elements of the `SparseTensor` + must be sorted in increasing order of this first dimension. The serialized + `SparseTensor` objects going into each row of the output `Tensor` will have + rank `R-1`. + + The minibatch size `N` is extracted from `sparse_shape[0]`. + + Args: + sp_input: The input rank `R` `SparseTensor`. + container: The container for the underlying `SparseTensorsMap` (optional). + shared_name: The shared name for the underlying `SparseTensorsMap` + (optional, defaults to the name of the newly created op). + name: A name prefix for the returned tensors (optional). + + Returns: + A string matrix (2-D `Tensor`) with `N` rows and `1` column. + Each row represents a unique handle to a `SparseTensor` stored by + the `SparseTensorMap` underlying this op. + + Raises: + TypeError: If `sp_input` is not a `SparseTensor`. + """ + sp_input = _convert_to_sparse_tensor(sp_input) + + return gen_sparse_ops.add_many_sparse_to_tensors_map( + sp_input.indices, + sp_input.values, + sp_input.dense_shape, + container=container, + shared_name=shared_name, + name=name) + + +def _take_many_sparse_from_tensors_map(sparse_map_op, + sparse_handles, + rank=None, + name=None): + """Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. + + The input `sparse_handles` must be a string matrix of shape `[N, 1]` where + `N` is the minibatch size and the rows correspond to packed outputs of + `add_sparse_to_tensors_map`. The ranks of the original `SparseTensor` objects + must all match. When the final `SparseTensor` is created, it has rank one + higher than the ranks of the incoming `SparseTensor` objects (they have been + concatenated along a new row dimension). + + The output `SparseTensor` object's shape values for all dimensions but the + first are the max across the input `SparseTensor` objects' shape values + for the corresponding dimensions. Its first shape value is `N`, the minibatch + size. + + The input `SparseTensor` objects' indices are assumed ordered in + standard lexicographic order. If this is not the case, after this + step run `sparse.reorder` to restore index ordering. + + For example, if the serialized input is a `[2, 3]` matrix representing two + original `SparseTensor` objects: + + index = [ 0] + [10] + [20] + values = [1, 2, 3] + shape = [50] + + and + + index = [ 2] + [10] + values = [4, 5] + shape = [30] + + then the final deserialized `SparseTensor` will be: + + index = [0 0] + [0 10] + [0 20] + [1 2] + [1 10] + values = [1, 2, 3, 4, 5] + shape = [2 50] + + Args: + sparse_map_op: The `Operation` that created the original handles. + Usually this is, e.g., `add_sparse_to_tensors_map(...).op`. + sparse_handles: 2-D `Tensor` of type `string` of shape `[N, 1]`. + The serialized and packed `SparseTensor` objects. + rank: (optional) Python int, the rank of the `SparseTensor` objects. + name: A name prefix for the returned tensors (optional) + + Returns: + A `SparseTensor` representing the deserialized `SparseTensor`s, + concatenated along the `SparseTensor`s' first dimension. + + All of the serialized `SparseTensor`s must have had the same rank and type. + """ + if not isinstance(sparse_map_op, ops.Operation): + raise TypeError("sparse_map_op be an Operation") + if sparse_map_op.type not in ("AddSparseToTensorsMap", + "AddManySparseToTensorsMap"): + raise TypeError( + "sparse_map_op must be one of AddSparseToTensorsMap or " + "AddSparseToTensorsMap. Instead, found `%s`." % sparse_map_op.type) + with ops.colocate_with(sparse_map_op): + shared_name = sparse_map_op.get_attr("shared_name") or sparse_map_op.name + output_indices, output_values, output_shape = ( + gen_sparse_ops.take_many_sparse_from_tensors_map( + sparse_handles, + dtype=sparse_map_op.get_attr("T"), + container=sparse_map_op.get_attr("container"), + shared_name=shared_name, + name=name)) + + # Feed rank data back in, if available + output_indices.set_shape([None, rank]) + output_shape.set_shape([rank]) + + return sparse_tensor.SparseTensor(output_indices, output_values, output_shape) + + +class _UnaryMapValueDispatcher(dispatch.OpDispatcher): + """OpDispatcher for unary ops that maps base function across sparse values.""" + + def __init__(self, original_func): + self._original_func = original_func + func_name = get_canonical_name_for_symbol(original_func) + arg_names = tf_inspect.getfullargspec(original_func)[0] + self._x = arg_names[0] + original_func.__doc__ = ( + original_func.__doc__.rstrip() + "\n\n" + + (" If `{x}` is a `SparseTensor`, returns\n" + " `SparseTensor({x}.indices, tf.{func}({x}.values, ...), " + "{x}.dense_shape)`").format(x=self._x, func=func_name)) + + def handle(self, args, kwargs): + if args: + x, args = args[0], args[1:] + else: + kwargs = kwargs.copy() + x = kwargs.pop(self._x, None) + if isinstance(x, sparse_tensor.SparseTensor): + return sparse_tensor.SparseTensor( + indices=x.indices, + values=self._original_func(x.values, *args, **kwargs), + dense_shape=x.dense_shape) + else: + return self.NOT_SUPPORTED + + +_UNARY_OPS = [ + # TODO(b/120307967) Add dispatchers for additional TensorFlow ops. + math_ops.abs, + math_ops.negative, + math_ops.sign, + math_ops.square, + math_ops.sqrt, + math_ops.erf, + math_ops.tanh, + # TODO(b/157272291) Add dispatchers for rest of special functions. + special_math_ops.bessel_i0e, + special_math_ops.bessel_i1e, +] +for unary_op in _UNARY_OPS: + _UnaryMapValueDispatcher(unary_op).register(unary_op) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/special_math_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/special_math_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee429a6783e27ecc9e267256bb0ded2e4f09b70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/special_math_ops.py @@ -0,0 +1,1341 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Arithmetic Operations that don't fit into math_ops due to dependencies. + +To avoid circular dependencies, some math_ops should go here. +""" + +import collections +import functools +import re +import string + +import numpy as np +import opt_einsum + + +from tensorflow.compiler.tf2xla.ops import gen_xla_ops +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import gen_special_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +# TODO(b/27419586) Change docstring for required dtype of x once int allowed +@tf_export('math.lbeta', v1=['math.lbeta', 'lbeta']) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints('lbeta') +def lbeta(x, name=None): + r"""Computes \\(ln(|Beta(x)|)\\), reducing along the last dimension. + + Given one-dimensional $z = [z_1,...,z_K]$, we define + + $$Beta(z) = \frac{\prod_j \Gamma(z_j)}{\Gamma(\sum_j z_j)},$$ + + where $\Gamma$ is the gamma function. + + And for $n + 1$ dimensional $x$ with shape $[N_1, ..., N_n, K]$, we define + + $$lbeta(x)[i_1, ..., i_n] = \log{|Beta(x[i_1, ..., i_n, :])|}.$$ + + In other words, the last dimension is treated as the $z$ vector. + + Note that if $z = [u, v]$, then + + $$Beta(z) = \frac{\Gamma(u)\Gamma(v)}{\Gamma(u + v)} + = \int_0^1 t^{u-1} (1 - t)^{v-1} \mathrm{d}t,$$ + + which defines the traditional bivariate beta function. + + If the last dimension is empty, we follow the convention that the sum over + the empty set is zero, and the product is one. + + Args: + x: A rank `n + 1` `Tensor`, `n >= 0` with type `float`, or `double`. + name: A name for the operation (optional). + + Returns: + The logarithm of \\(|Beta(x)|\\) reducing along the last dimension. + """ + # In the event that the last dimension has zero entries, we return -inf. + # This is consistent with a convention that the sum over the empty set 0, and + # the product is 1. + # This is standard. See https://en.wikipedia.org/wiki/Empty_set. + with ops.name_scope(name, 'lbeta', [x]): + x = ops.convert_to_tensor(x, name='x') + + # Note reduce_sum([]) = 0. + log_prod_gamma_x = math_ops.reduce_sum(math_ops.lgamma(x), axis=[-1]) + + # Note lgamma(0) = infinity, so if x = [] + # log_gamma_sum_x = lgamma(0) = infinity, and + # log_prod_gamma_x = lgamma(1) = 0, + # so result = -infinity + sum_x = math_ops.reduce_sum(x, axis=[-1]) + log_gamma_sum_x = math_ops.lgamma(sum_x) + result = log_prod_gamma_x - log_gamma_sum_x + + return result + + +@tf_export('math.special.dawsn') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def dawsn(x, name=None): + """Computes Dawson's integral of `x` element-wise. + + Dawson's integral is defined as `exp(-x**2)` times the integral of + `exp(t**2)` from `0` to `x`, with the domain of definition all real numbers. + + Dawson's function is odd. + >>> tf.math.special.dawsn([-1., -0.5, 0.5, 1.]).numpy() + array([-0.5380795, -0.4244364, 0.4244364, 0.5380795], dtype=float32) + + This implementation is based off of the Cephes math library. + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.dawsn + @end_compatibility + """ + with ops.name_scope(name, 'dawsn', [x]): + return gen_special_math_ops.dawsn(x) + + +@tf_export('math.special.expint') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def expint(x, name=None): + """Computes the Exponential integral of `x` element-wise. + + The Exponential integral is defined as the integral of `exp(t) / t` from + `-inf` to `x`, with the domain of definition all positive real numbers. + + >>> tf.math.special.expint([1., 1.1, 2.1, 4.1]).numpy() + array([ 1.8951179, 2.1673784, 5.3332353, 21.048464], dtype=float32) + + This implementation is based off of the Cephes math library. + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.expi + @end_compatibility + """ + with ops.name_scope(name, 'expint', [x]): + return gen_special_math_ops.expint(x) + + +@tf_export('math.special.fresnel_cos') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def fresnel_cos(x, name=None): + """Computes Fresnel's cosine integral of `x` element-wise. + + The Fresnel cosine integral is defined as the integral of `cos(t^2)` from + `0` to `x`, with the domain of definition all real numbers. + + The Fresnel cosine integral is odd. + >>> tf.math.special.fresnel_cos([-1., -0.1, 0.1, 1.]).numpy() + array([-0.7798934 , -0.09999753, 0.09999753, 0.7798934 ], dtype=float32) + + This implementation is based off of the Cephes math library. + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.fresnel second output. + @end_compatibility + """ + with ops.name_scope(name, 'fresnel_cos', [x]): + return gen_special_math_ops.fresnel_cos(x) + + +@tf_export('math.special.fresnel_sin') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def fresnel_sin(x, name=None): + """Computes Fresnel's sine integral of `x` element-wise. + + The Fresnel sine integral is defined as the integral of `sin(t^2)` from + `0` to `x`, with the domain of definition all real numbers. + + >>> tf.math.special.fresnel_sin([-1., -0.1, 0.1, 1.]).numpy() + array([-0.43825912, -0.00052359, 0.00052359, 0.43825912], dtype=float32) + + This implementation is based off of the Cephes math library. + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.fresnel first output. + @end_compatibility + """ + with ops.name_scope(name, 'fresnel_sin', [x]): + return gen_special_math_ops.fresnel_sin(x) + + +@tf_export('math.special.spence') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def spence(x, name=None): + """Computes Spence's integral of `x` element-wise. + + Spence's integral is defined as the integral of `log(t) / (1 - t)` from + `1` to `x`, with the domain of definition all non-negative real numbers. + + >>> tf.math.special.spence([0.5, 1., 2., 3.]).numpy() + array([ 0.58224034, 0. , -0.82246685, -1.4367464], dtype=float32) + + This implementation is based off of the Cephes math library. + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.spence + @end_compatibility + """ + with ops.name_scope(name, 'spence', [x]): + return gen_special_math_ops.spence(x) + + +@tf_export('math.bessel_i0', 'math.special.bessel_i0') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_i0(x, name=None): + """Computes the Bessel i0 function of `x` element-wise. + + Modified Bessel function of order 0. + + It is preferable to use the numerically stabler function `i0e(x)` instead. + + >>> tf.math.special.bessel_i0([-1., -0.5, 0.5, 1.]).numpy() + array([1.26606588, 1.06348337, 1.06348337, 1.26606588], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.i0 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_i0', [x]): + return gen_special_math_ops.bessel_i0(x) + + +@tf_export('math.bessel_i0e', 'math.special.bessel_i0e') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_i0e(x, name=None): + """Computes the Bessel i0e function of `x` element-wise. + + Modified Bessel function of order 0. + + >>> tf.math.special.bessel_i0e([-1., -0.5, 0.5, 1.]).numpy() + array([0.46575961, 0.64503527, 0.64503527, 0.46575961], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.i0e + @end_compatibility + """ + with ops.name_scope(name, 'bessel_i0e', [x]): + return gen_special_math_ops.bessel_i0e(x) + + +@tf_export('math.bessel_i1', 'math.special.bessel_i1') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_i1(x, name=None): + """Computes the Bessel i1 function of `x` element-wise. + + Modified Bessel function of order 1. + + It is preferable to use the numerically stabler function `i1e(x)` instead. + + >>> tf.math.special.bessel_i1([-1., -0.5, 0.5, 1.]).numpy() + array([-0.5651591 , -0.25789431, 0.25789431, 0.5651591 ], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.i1 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_i1', [x]): + return gen_special_math_ops.bessel_i1(x) + + +@tf_export('math.bessel_i1e', 'math.special.bessel_i1e') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_i1e(x, name=None): + """Computes the Bessel i1e function of `x` element-wise. + + Modified Bessel function of order 1. + + >>> tf.math.special.bessel_i1e([-1., -0.5, 0.5, 1.]).numpy() + array([-0.20791042, -0.15642083, 0.15642083, 0.20791042], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.i1e + @end_compatibility + """ + with ops.name_scope(name, 'bessel_i1e', [x]): + return gen_special_math_ops.bessel_i1e(x) + + +@tf_export('math.special.bessel_k0') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_k0(x, name=None): + """Computes the Bessel k0 function of `x` element-wise. + + Modified Bessel function of order 0. + + It is preferable to use the numerically stabler function `k0e(x)` instead. + + >>> tf.math.special.bessel_k0([0.5, 1., 2., 4.]).numpy() + array([0.92441907, 0.42102444, 0.11389387, 0.01115968], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.k0 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_k0', [x]): + return gen_special_math_ops.bessel_k0(x) + + +@tf_export('math.special.bessel_k0e') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_k0e(x, name=None): + """Computes the Bessel k0e function of `x` element-wise. + + Modified Bessel function of order 0. + + >>> tf.math.special.bessel_k0e([0.5, 1., 2., 4.]).numpy() + array([1.52410939, 1.14446308, 0.84156822, 0.60929767], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.k0e + @end_compatibility + """ + with ops.name_scope(name, 'bessel_k0e', [x]): + return gen_special_math_ops.bessel_k0e(x) + + +@tf_export('math.special.bessel_k1') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_k1(x, name=None): + """Computes the Bessel k1 function of `x` element-wise. + + Modified Bessel function of order 1. + + It is preferable to use the numerically stabler function `k1e(x)` instead. + + >>> tf.math.special.bessel_k1([0.5, 1., 2., 4.]).numpy() + array([1.65644112, 0.60190723, 0.13986588, 0.0124835 ], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.k1 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_k1', [x]): + return gen_special_math_ops.bessel_k1(x) + + +@tf_export('math.special.bessel_k1e') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_k1e(x, name=None): + """Computes the Bessel k1e function of `x` element-wise. + + Modified Bessel function of order 1. + + >>> tf.math.special.bessel_k1e([0.5, 1., 2., 4.]).numpy() + array([2.73100971, 1.63615349, 1.03347685, 0.68157595], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.k1e + @end_compatibility + """ + with ops.name_scope(name, 'bessel_k1e', [x]): + return gen_special_math_ops.bessel_k1e(x) + + +@tf_export('math.special.bessel_j0') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_j0(x, name=None): + """Computes the Bessel j0 function of `x` element-wise. + + Modified Bessel function of order 0. + + >>> tf.math.special.bessel_j0([0.5, 1., 2., 4.]).numpy() + array([ 0.93846981, 0.76519769, 0.22389078, -0.39714981], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.j0 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_j0', [x]): + return gen_special_math_ops.bessel_j0(x) + + +@tf_export('math.special.bessel_j1') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_j1(x, name=None): + """Computes the Bessel j1 function of `x` element-wise. + + Modified Bessel function of order 1. + + >>> tf.math.special.bessel_j1([0.5, 1., 2., 4.]).numpy() + array([ 0.24226846, 0.44005059, 0.57672481, -0.06604333], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.j1 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_j1', [x]): + return gen_special_math_ops.bessel_j1(x) + + +@tf_export('math.special.bessel_y0') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_y0(x, name=None): + """Computes the Bessel y0 function of `x` element-wise. + + Modified Bessel function of order 0. + + >>> tf.math.special.bessel_y0([0.5, 1., 2., 4.]).numpy() + array([-0.44451873, 0.08825696, 0.51037567, -0.01694074], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.y0 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_y0', [x]): + return gen_special_math_ops.bessel_y0(x) + + +@tf_export('math.special.bessel_y1') +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def bessel_y1(x, name=None): + """Computes the Bessel y1 function of `x` element-wise. + + Modified Bessel function of order 1. + + >>> tf.math.special.bessel_y1([0.5, 1., 2., 4.]).numpy() + array([-1.47147239, -0.78121282, -0.10703243, 0.39792571], dtype=float32) + + Args: + x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, + `float32`, `float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. + + @compatibility(scipy) + Equivalent to scipy.special.y1 + @end_compatibility + """ + with ops.name_scope(name, 'bessel_y1', [x]): + return gen_special_math_ops.bessel_y1(x) + + +@ops.RegisterGradient('XlaEinsum') +def _einsum_grad(op, grad): + equation = op.get_attr('equation') + if isinstance(equation, bytes): + equation = equation.decode() + + inputs, output = equation.split('->') + left, right = inputs.split(',') + + return [ + gen_xla_ops.xla_einsum( + grad, + op.inputs[1], + equation='{},{}->{}'.format(output, right, left), + name=None), + gen_xla_ops.xla_einsum( + grad, + op.inputs[0], + equation='{},{}->{}'.format(output, left, right), + name=None) + ] + + +def _enclosing_tpu_context(): + # pylint: disable=protected-access + context = ops.get_default_graph()._get_control_flow_context() + # pylint: enable=protected-access + while context is not None and not isinstance( + context, control_flow_ops.XLAControlFlowContext): + context = context.outer_context + return context + + +@tf_export('einsum', 'linalg.einsum') +@dispatch.add_dispatch_support +def einsum(equation, *inputs, **kwargs): + r"""Tensor contraction over specified indices and outer product. + + Einsum allows defining Tensors by defining their element-wise computation. + This computation is defined by `equation`, a shorthand form based on Einstein + summation. As an example, consider multiplying two matrices A and B to form a + matrix C. The elements of C are given by: + + $$ C_{i,k} = \sum_j A_{i,j} B_{j,k} $$ + + or + + ``` + C[i,k] = sum_j A[i,j] * B[j,k] + ``` + + The corresponding einsum `equation` is: + + ``` + ij,jk->ik + ``` + + In general, to convert the element-wise equation into the `equation` string, + use the following procedure (intermediate strings for matrix multiplication + example provided in parentheses): + + 1. remove variable names, brackets, and commas, (`ik = sum_j ij * jk`) + 2. replace "*" with ",", (`ik = sum_j ij , jk`) + 3. drop summation signs, and (`ik = ij, jk`) + 4. move the output to the right, while replacing "=" with "->". (`ij,jk->ik`) + + Note: If the output indices are not specified repeated indices are summed. + So `ij,jk->ik` can be simplified to `ij,jk`. + + Many common operations can be expressed in this way. For example: + + **Matrix multiplication** + + >>> m0 = tf.random.normal(shape=[2, 3]) + >>> m1 = tf.random.normal(shape=[3, 5]) + >>> e = tf.einsum('ij,jk->ik', m0, m1) + >>> # output[i,k] = sum_j m0[i,j] * m1[j, k] + >>> print(e.shape) + (2, 5) + + Repeated indices are summed if the output indices are not specified. + + >>> e = tf.einsum('ij,jk', m0, m1) # output[i,k] = sum_j m0[i,j] * m1[j, k] + >>> print(e.shape) + (2, 5) + + + **Dot product** + + >>> u = tf.random.normal(shape=[5]) + >>> v = tf.random.normal(shape=[5]) + >>> e = tf.einsum('i,i->', u, v) # output = sum_i u[i]*v[i] + >>> print(e.shape) + () + + **Outer product** + + >>> u = tf.random.normal(shape=[3]) + >>> v = tf.random.normal(shape=[5]) + >>> e = tf.einsum('i,j->ij', u, v) # output[i,j] = u[i]*v[j] + >>> print(e.shape) + (3, 5) + + **Transpose** + + >>> m = tf.ones(2,3) + >>> e = tf.einsum('ij->ji', m0) # output[j,i] = m0[i,j] + >>> print(e.shape) + (3, 2) + + **Diag** + + >>> m = tf.reshape(tf.range(9), [3,3]) + >>> diag = tf.einsum('ii->i', m) + >>> print(diag.shape) + (3,) + + **Trace** + + >>> # Repeated indices are summed. + >>> trace = tf.einsum('ii', m) # output[j,i] = trace(m) = sum_i m[i, i] + >>> assert trace == sum(diag) + >>> print(trace.shape) + () + + **Batch matrix multiplication** + + >>> s = tf.random.normal(shape=[7,5,3]) + >>> t = tf.random.normal(shape=[7,3,2]) + >>> e = tf.einsum('bij,bjk->bik', s, t) + >>> # output[a,i,k] = sum_j s[a,i,j] * t[a, j, k] + >>> print(e.shape) + (7, 5, 2) + + This method does not support broadcasting on named-axes. All axes with + matching labels should have the same length. If you have length-1 axes, + use `tf.squeeze` or `tf.reshape` to eliminate them. + + To write code that is agnostic to the number of indices in the input + use an ellipsis. The ellipsis is a placeholder for "whatever other indices + fit here". + + For example, to perform a NumPy-style broadcasting-batch-matrix multiplication + where the matrix multiply acts on the last two axes of the input, use: + + >>> s = tf.random.normal(shape=[11, 7, 5, 3]) + >>> t = tf.random.normal(shape=[11, 7, 3, 2]) + >>> e = tf.einsum('...ij,...jk->...ik', s, t) + >>> print(e.shape) + (11, 7, 5, 2) + + Einsum **will** broadcast over axes covered by the ellipsis. + + >>> s = tf.random.normal(shape=[11, 1, 5, 3]) + >>> t = tf.random.normal(shape=[1, 7, 3, 2]) + >>> e = tf.einsum('...ij,...jk->...ik', s, t) + >>> print(e.shape) + (11, 7, 5, 2) + + Args: + equation: a `str` describing the contraction, in the same format as + `numpy.einsum`. + *inputs: the inputs to contract (each one a `Tensor`), whose shapes should + be consistent with `equation`. + **kwargs: + - optimize: Optimization strategy to use to find contraction path using + opt_einsum. Must be 'greedy', 'optimal', 'branch-2', 'branch-all' or + 'auto'. (optional, default: 'greedy'). + - name: A name for the operation (optional). + + Returns: + The contracted `Tensor`, with shape determined by `equation`. + + Raises: + ValueError: If + - the format of `equation` is incorrect, + - number of inputs or their shapes are inconsistent with `equation`. + """ + return _einsum_v2(equation, *inputs, **kwargs) + + +def _einsum_v1(equation, *inputs, **kwargs): + """Legacy implementation of einsum without using EinsumOp.""" + name = kwargs.pop('name', None) + if kwargs: + raise TypeError( + f'Invalid keyword arguments for this function: ' + f'{", ".join([format(key) for key in sorted(list(kwargs.keys()))])}.' + f' Expected: name.') + with ops.name_scope(name, 'einsum', [equation, inputs]) as name: + inputs = list(inputs) + input_shapes = [x.shape for x in inputs] + input_axis_labels, output_axis_labels = ( + _einsum_v1_parse_and_resolve_equation(equation, input_shapes)) + + axis_labels = set(''.join(input_axis_labels) + output_axis_labels) + + for a in axis_labels: + for input_labels in input_axis_labels: + if (len(input_axis_labels) == 1 and input_labels.count(a) == 2 and + input_labels == input_labels[::-1] and '->' not in equation): + return math_ops.trace(inputs[0]) + if input_labels.count(a) > 1: + raise ValueError( + f'Subscript not supported: the axis {a} appears more than once' + f' in {input_labels}.') + for a in axis_labels: + input_count = sum(1 for s in input_axis_labels if a in s) + if input_count > 2 and a not in output_axis_labels: + logging.warn( + f'Falling back to exponential-space implementation of einsum()' + f' because index {a} is summed over more than two inputs.') + return _exponential_space_einsum_v1(equation, *inputs) + + # Use xla_einsum if executing on TPU and if the operation is a 2 input + # einsum supported by XlaEinsumOp. + if _enclosing_tpu_context() is not None and len(inputs) == 2: + return gen_xla_ops.xla_einsum( + inputs[0], inputs[1], input_axis_labels[0] + ',' + + input_axis_labels[1] + '->' + output_axis_labels) + temp = inputs[0] + temp_axis_labels = input_axis_labels[0] + for i in range(len(inputs) - 1): + axes_to_sum = ( + set(temp_axis_labels) & + set(input_axis_labels[i + 1]) - set(output_axis_labels)) + temp, temp_axis_labels = _einsum_v1_reduction(temp, temp_axis_labels, + inputs[i + 1], + input_axis_labels[i + 1], + axes_to_sum) + + missing_indices = set(temp_axis_labels) - set(output_axis_labels) + if missing_indices: + axis = [ + i for i, a in enumerate(temp_axis_labels) + if a not in output_axis_labels + ] + temp = math_ops.reduce_sum(temp, axis=axis) + temp_axis_labels = ''.join( + a for a in temp_axis_labels if a in output_axis_labels) + if sorted(temp_axis_labels) != sorted(output_axis_labels): + raise ValueError( + f'Invalid equation: {equation}. The computed and specified output ' + f'labels do not match: {temp_axis_labels} vs {output_axis_labels}.') + + perm = [temp_axis_labels.index(a) for a in output_axis_labels] + return _transpose_if_necessary(temp, perm) + + +def _einsum_v1_parse_and_resolve_equation(equation, input_shapes): + """Helper for einsum() that splits/resolves inputs & outputs. + + Args: + equation: Equation string given as argument to einsum(). + input_shapes: List of the shapes of all inputs given to einsum() + + Returns: + input_axis_labels, output_axis_labels where: + input_axis_labels: List of length len(input_shapes) of strings + representing the character label for each dimension of each given input, + resolving any broadcast (...) axes, + output_axis_labels: A string of character labels for each axes of output + tensor, filling in missing output subscripts and broadcast axes. + + Raises: + ValueError: If equation is in the uncorrect format, incorrect number of + inputs given or broadcast axes "..." or output axes could not be resolved. + """ + equation = equation.replace(' ', '') + match = re.match('^([a-zA-Z,.]+)(->[a-zA-Z.]*)?$', equation) + if not match: + raise ValueError(f'Indices have incorrect format. Received: {equation}.') + + input_axis_labels = match.group(1).split(',') + output_axis_labels = match.group(2)[2:] if match.group(2) else None + + if len(input_shapes) != len(input_axis_labels): + raise ValueError( + f'Got {len(input_shapes)} arguments for equation "{equation}", ' + f'expecting {len(input_axis_labels)}.') + + # Resolve Ellipsis + # Assign axes labels for unspecified dimensions in inputs. Labels taken + # from unused labels. Follow numpy einsum broadcasting conventions for + # tensors of different length and unlabeled output. + ellipsis_axes = '' + if '...' in equation: + unused = ''.join( + c for c in string.ascii_letters if c not in ''.join(input_axis_labels)) + for i, ax in enumerate(input_axis_labels): + if '...' in ax: + parts = ax.split('...') + if len(parts) != 2: + raise ValueError(f'Unable to resolve ellipsis. ' + f'Excess number found: {len(parts)-1} vs 1.') + if input_shapes[i].ndims is None: + raise ValueError('Unable to statically infer ellipsis axes. The ' + 'input shapes has a dynamic dimensionality.') + n = input_shapes[i].ndims - len(''.join(parts)) + if n < 0: + raise ValueError('Ellipses lengths do not match.') + if len(unused) < n: + raise ValueError( + 'Unable to resolve ellipsis, too many distinct labels.') + replace_axes = unused[-n:] if n > 0 else '' + input_axis_labels[i] = input_axis_labels[i].replace('...', + replace_axes) + if len(replace_axes) > len(ellipsis_axes): + ellipsis_axes = replace_axes + + if any('.' in ax for ax in input_axis_labels): + raise ValueError( + f'Period "." found outside of ellipsis in input {input_axis_labels}.') + + if output_axis_labels is not None: + output_axis_labels = output_axis_labels.replace('...', ellipsis_axes) + if '.' in output_axis_labels: + raise ValueError(f'Period "." found outside of ellipsis in output ' + f'{output_axis_labels}.') + + if output_axis_labels is None: + # infer the output subscripts if not given, assume alphabetical order, + # but always place ellipsis axes before given. + axis_labels = set(''.join(input_axis_labels)) - set(ellipsis_axes) + indices = ''.join(sorted(axis_labels)) + counts = {ax: 0 for ax in indices} + for axes_ in input_axis_labels: + for ax in axes_: + if ax not in ellipsis_axes: + counts[ax] += 1 + + output_axis_labels = ellipsis_axes + ''.join( + sorted(ax for ax in axis_labels if counts[ax] == 1)) + + return input_axis_labels, output_axis_labels + + +def _einsum_v1_reduction(t0, t0_axis_labels, t1, t1_axis_labels, axes_to_sum): + """Helper for einsum() that computes the result of a two-argument einsum(). + + Args: + t0: a `Tensor` + t0_axis_labels: a string of axis labels. This string's length must equal + the rank of t0. + t1: a `Tensor` + t1_axis_labels: a string to axis labels. This string's length must equal + the rank of t1. + axes_to_sum: set of labels of axes to be summed over + + Returns: + A `Tensor` whose elements are obtained by summing, over all axes in + `axes_to_sum`, the corresponding elements of `t0` and `t1`. + + For example, if t0_axis_labels == 'abijk', t1_axis_labels == 'acjkl', and + axes_to_sum == {j,k}, this will return a tensor x where + + out[a,b,c,i,l] = sum_j sum_k t0[a,b,i,j,k] * t1[a,c,j,k,l] + + Raises: + ValueError: if the rank of `t0` does not match the length of + `t0_axis_labels`, or that of `t1` does not match the length of + `t1_axis_labels`. + """ + if len(t0_axis_labels) != len(t0.shape): + raise ValueError( + f'Tensor `t0` of rank {len(t0.shape)} does not match einsum reduction ' + f'of length {len(t0_axis_labels)}.') + if len(t1_axis_labels) != len(t1.shape): + raise ValueError( + f'Tensor `t1` of rank {len(t1.shape)} does not match einsum reduction ' + f'of length {len(t1_axis_labels)}') + + # This function computes the result of a two-argument einsum() using batch + # matrix multiplication. This involves + # 1. transposing t0 and t1 so that axes are in the correct order for + # batch matrix multiplication, and + # 2. reshaping t0 and t1 so that they are both of rank 3. + + # First, we divide axes into three groups: + # * "preserved" axes are present in both inputs and the output + # * "summed" axes are present in both inputs but not the output + # * "broadcast" axes are present in exactly one input and the output + # + # As an example, if the einsum is abijk,acjkl->abcil, then "a" is a + # preserved axis, "b" and "c" are broadcast axes, and "j" and "k" are + # summed axes. + assert all(a in t0_axis_labels and a in t1_axis_labels for a in axes_to_sum) + preserved_axes = (set(t0_axis_labels) & set(t1_axis_labels)) - axes_to_sum + broadcast_axes = {} + for i, sym_list in enumerate([t0_axis_labels, t1_axis_labels]): + broadcast_axes[i] = set(sym_list) - preserved_axes - axes_to_sum + + # Reorder the axes so that: + # 1. preserved axes come first in both inputs + # 2. in input 0, broadcast axes come next, followed by summed axes + # 3. in input 1, summed axes come next, followed by broadcast axes + def sort_key(input_index, a): + if a in preserved_axes: + return (-1, a) + elif ((input_index == 0 and a in broadcast_axes[0]) or + (input_index == 1 and a in axes_to_sum)): + return (0, a) + else: + return (1, a) + + axis_labels = [t0_axis_labels, t1_axis_labels] + sorted_axes = [ + sorted(sym_list, key=lambda a: sort_key(i, a)) + for i, sym_list in enumerate(axis_labels) + ] + inputs = [t0, t1] + for i, axes_str in enumerate(axis_labels): + perm = [axes_str.find(a) for a in sorted_axes[i]] + inputs[i] = _transpose_if_necessary(inputs[i], perm) + t0, t1 = inputs + + if not axes_to_sum: + # In the special case where there are no axes to sum over, reduce to mul() + # rather than to batch matrix multiplication. + for _ in broadcast_axes[1]: + t0 = array_ops.expand_dims(t0, -1) + for _ in broadcast_axes[0]: + t1 = array_ops.expand_dims(t1, len(preserved_axes)) + product = math_ops.multiply(t0, t1) + product_axes = sorted_axes[0] + sorted_axes[1][len(preserved_axes):] + return product, ''.join(product_axes) + else: + # Reduce to matmul(). + + # Reshape both inputs so as to combine multiple broadcast axes + # into a single axis, and combine multiple summed axes into a + # single axis. + + t0_shape = _get_shape(t0) + num_broadcast_elements_t0 = _total_size( + t0_shape[len(preserved_axes):-len(axes_to_sum)]) + num_summed_elements = _total_size(t0_shape[-len(axes_to_sum):]) + new_shape = ( + t0_shape[:len(preserved_axes)] + + [num_broadcast_elements_t0, num_summed_elements]) + t0 = _reshape_if_necessary(t0, new_shape) + + t1_shape = _get_shape(t1) + num_broadcast_elements_t1 = _total_size( + t1_shape[len(preserved_axes) + len(axes_to_sum):]) + new_shape = ( + t1_shape[:len(preserved_axes)] + + [num_summed_elements, num_broadcast_elements_t1]) + t1 = _reshape_if_necessary(t1, new_shape) + + product = math_ops.matmul(t0, t1) + + # Undo compaction of broadcast axes + uncompacted_shape = ( + t0_shape[:len(preserved_axes) + len(broadcast_axes[0])] + + t1_shape[len(t1_shape) - len(broadcast_axes[1]):]) + product = _reshape_if_necessary(product, uncompacted_shape) + + product_axes = ( + sorted_axes[0][:len(preserved_axes) + len(broadcast_axes[0])] + + sorted_axes[1][len(sorted_axes[1]) - len(broadcast_axes[1]):]) + + return product, ''.join(product_axes) + + +def _transpose_if_necessary(tensor, perm): + """Like transpose(), but avoids creating a new tensor if possible.""" + if perm != list(range(len(perm))): + return array_ops.transpose(tensor, perm=perm) + else: + return tensor + + +def _reshape_if_necessary(tensor, new_shape): + """Like reshape(), but avoids creating a new tensor if possible.""" + # Accept None as an alias for -1 in new_shape. + new_shape = tuple(-1 if x is None else x for x in new_shape) + cur_shape = tuple(x.value for x in tensor.shape.dims) + if (len(new_shape) == len(cur_shape) and + all(not isinstance(d1, tensor_lib.Tensor) and (d0 == d1 or d1 == -1) + for d0, d1 in zip(cur_shape, new_shape))): + return tensor + else: + return array_ops.reshape(tensor, new_shape) + + +def _get_shape(tensor): + """Like get_shape().as_list(), but explicitly queries the shape of a tensor + if necessary to ensure that the returned value contains no unknown value.""" + + shape = tensor.shape.as_list() + none_indices = [i for i, d in enumerate(shape) if d is None] + if none_indices: + # Query the shape if shape contains None values + shape_tensor = array_ops.shape(tensor) + for i in none_indices: + shape[i] = shape_tensor[i] + return shape + + +def _total_size(shape_values): + """Given list of tensor shape values, returns total size. + If shape_values contains tensor values (which are results of + array_ops.shape), then it returns a scalar tensor. + If not, it returns an integer.""" + + result = 1 + for val in shape_values: + result *= val + return result + + +def _exponential_space_einsum_v1(equation, *inputs): + """Fallback implementation that supports summing an index over > 2 inputs.""" + inputs = list(inputs) + input_shapes = [x.shape for x in inputs] + idx_in, idx_out = _einsum_v1_parse_and_resolve_equation( + equation, input_shapes) + + idx_all = set(''.join(idx_in) + idx_out) + indices = ''.join(sorted(idx_all)) + + missing_idx = set(idx_out).difference(idx_all) + if missing_idx: + raise ValueError(f'Unknown output axes: {missing_idx}.') + + axis_order = {} + for ax in indices: + if ax not in idx_out: + axis_order[ax] = len(axis_order) + for ax in idx_out: + axis_order[ax] = len(axis_order) + + # transpose inputs so axes are in order + for i, (input_, axes_) in enumerate(zip(inputs, idx_in)): + if input_.shape.ndims != len(axes_): + raise ValueError( + f'Input {i} with axes {axes_} has incorrect number of dimensions ' + f'(expected {len(axes_)}, got {input_.shape.ndims}).') + + sorted_idx = sorted(axes_, key=axis_order.get) + + if len(set(axes_)) != len(axes_): + raise ValueError( + f'Subscript not supported: an axis appears more than once: {axes_}.') + + if list(axes_) != sorted_idx: + permuted = [axes_.find(ax) for ax in sorted_idx] + inputs[i] = array_ops.transpose(input_, permuted) + idx_in[i] = sorted_idx + + reduction_idx = [] + shapes = [[dim if dim else -1 + for dim in tensor.shape.as_list()] + for tensor in inputs] + + # validate shapes for broadcasting + for j, ax in enumerate(sorted(idx_all, key=axis_order.get)): + dims = [] + for i, idx in enumerate(idx_in): + if ax not in idx: + shapes[i].insert(j, 1) + else: + dim = shapes[i][j] + if isinstance(dim, int) and dim > 1: + dims.append(dim) + + if len(set(dims)) > 1: + raise ValueError(f'Dimension mismatch on axis: {ax}. ' + f'Found {len(set(dims))}, expected 1.') + + if ax not in idx_out: + reduction_idx.append(j) + + # reshape, multiply + expanded_inputs = [ + array_ops.reshape(input_, shape) for input_, shape in zip(inputs, shapes) + ] + expanded_output = 1 + for input_ in expanded_inputs: + expanded_output *= input_ + + # contract + return math_ops.reduce_sum(expanded_output, reduction_idx) + + +def _einsum_v2(equation, *inputs, **kwargs): + """Implementation of einsum utilizing opt_einsum and EinsumOp.""" + name = kwargs.pop('name', None) + optimize = kwargs.pop('optimize', 'greedy') + if kwargs: + raise TypeError( + f'Invalid keyword arguments for einsum: {", ".join(kwargs)}. ' + f'Valid arguments: name, optimize, greedy.') + + with ops.name_scope(name, 'einsum', [equation, inputs]) as name: + inputs = list(inputs) + input_shapes = [] + for operand in inputs: + if isinstance(operand.shape, tensor_shape.TensorShape): + input_shapes.append(operand.shape.as_list() if operand.shape else None) + else: + input_shapes.append(list(operand.shape)) + # Validate and sanitize the equation and resolve static input shapes, as + # opt_einsum requires that all shapes be a tuple of positive integers. + # Also remove ellipsis from the equation as opt_einsum will replace them + # with named labels. Then broadcasting between different shapes or ranks + # wouldn't work. (E.g. [1, 1, 2] wouldn't broadcast with [3, 1]). + resolved_equation, resolved_input_shapes, ellipsis_label = ( + _einsum_v2_parse_and_resolve_equation(equation, input_shapes)) + + if len(inputs) <= 2: # No need to call opt_einsum. + # Replace back ellipses that were removed for opt_einsum. + if ellipsis_label: + resolved_equation = resolved_equation.replace(ellipsis_label, '...') + return gen_linalg_ops.einsum(inputs, resolved_equation) + + # Send fully specified shapes to opt_einsum, since it cannot handle unknown + # dimensions. For unknown dimensions, we guess that the dimension equals 1. + # Instead of creating Tensors or NumPy arrays with the specified shape, + # create a dummy `shaped` object with a `shape` property. + shaped = collections.namedtuple('shaped', ['shape']) + shaped_inputs = tuple( + [shaped(tuple(shape)) for shape in resolved_input_shapes]) + # opt_einsum breaks down an n-ary einsum operation into n-1 binary einsums. + # Obtain the sequence of equations and the indices of operands involved in + # each einsum operation. + indices_and_equations = _get_opt_einsum_contract_path( + resolved_equation, shaped_inputs, optimize) + for operand_indices, binary_equation in indices_and_equations: + if ellipsis_label: + # Replace back ellipses that were removed for opt_einsum. + binary_equation = binary_equation.replace(ellipsis_label, '...') + operands = list(map(inputs.pop, operand_indices)) + inputs.append(gen_linalg_ops.einsum(operands, binary_equation)) + return inputs[0] + + +def _get_opt_einsum_contract_path(equation, shaped_inputs_tuple, optimize): + """Returns the (memoized) result of opt_einsum.contract_path.""" + # Note: We use einsum_call=True, which is an internal api for opt_einsum, + # to get the contraction path without having opt_einsum perform the actual + # contractions. + _, contractions = opt_einsum.contract_path( + equation, + *shaped_inputs_tuple, + optimize=optimize, + einsum_call=True, + use_blas=True) + # Return a tuple so that the cached value is not mutable. + indices_and_equations = tuple([(expr[0], expr[2]) for expr in contractions]) + return indices_and_equations + + +# Cache the possibly expensive opt_einsum.contract_path call using lru_cache +# from the Python3+ standard library. +_get_opt_einsum_contract_path = functools.lru_cache(maxsize=128)( + _get_opt_einsum_contract_path) + + +def _einsum_v2_parse_and_resolve_equation(equation, input_shapes): + """Helper which validates einsum equation and resolves input shapes.""" + resolved_equation = equation.replace(' ', '') + ellipsis_label = None + if '...' in equation: + # Replace ellipsis ('...') with '0' for (a) ease of parsing and (b) to + # prevent opt_einsum from resolving them into named labels; as it doesn't + # support broadcasting. + ellipsis_label = '0' + if ellipsis_label in resolved_equation: + raise ValueError( + f'Invalid character "{ellipsis_label}" in equation: {equation}.') + resolved_equation = resolved_equation.replace('...', ellipsis_label) + + # Ensure there are no non-alphanumeric characters in the equation, including + # periods (`.`) outside of ellipses, in the equation. This is not a hard + # requirement; except we use a special character '0' for ellipsis. + allowed_labels = 'a-zA-Z' + if ellipsis_label: + allowed_labels += ellipsis_label + match = re.match('^([{0},]*)(->[{0}]*)?$'.format(allowed_labels), + resolved_equation) + if not match: + raise ValueError( + 'Subscripts have incorrect format: {}'.format(resolved_equation)) + input_labels = match.group(1).split(',') + output_labels = match.group(2)[2:] if match.group(2) else None + + if len(input_shapes) != len(input_labels): + raise ValueError('Got {} inputs for equation "{}", expecting {}'.format( + len(input_shapes), equation, len(input_labels))) + + # Special case: if there are no '->', then we create output subscripts from + # labels appearing only once. + if '->' not in resolved_equation: + label_counts = collections.Counter(match.group(1)) + output_labels = ''.join([ + x for x in sorted(list(label_counts)) + if x != ',' and label_counts[x] == 1 + ]) + resolved_equation += '->' + output_labels + # Validate output_labels. + if output_labels and len(set(output_labels)) != len(output_labels): + raise ValueError( + 'Output subscripts contain a label appearing more than once: {}'.format( + equation)) + input_label_set = set(match.group(1)) + for label in output_labels: + if label != ellipsis_label and label not in input_label_set: + raise ValueError('Output subscripts contain the label {} not present ' + 'in the input subscripts.'.format(label)) + if ellipsis_label and output_labels: + num_output_ellipses = output_labels.count(ellipsis_label) + if num_output_ellipses > 1: + raise ValueError( + 'Output subscripts contain multiple ellipsis: {}'.format(equation)) + + # Early return if <= 2 inputs. Resolved shapes are not needed. + if len(input_shapes) <= 2: + return resolved_equation, None, ellipsis_label + + # Create a map from axis labels to known dimensions. This is used to infer + # unknown dimensions if a known dimension also has the same label. + label_to_dim = collections.defaultdict(lambda: 1) + for i, (labels, shape) in enumerate(zip(input_labels, input_shapes)): + if shape is None: + continue + ellipsis_start = labels.find(ellipsis_label) if ellipsis_label else -1 + if ellipsis_start != -1: # This input contains an ellipsis. + if ellipsis_start != labels.rfind(ellipsis_label): + raise ValueError(f'Too many ellipses in input label ' + f'{labels.replace(ellipsis_label, "...")}.') + if len(labels) > len(shape) + 1: + raise ValueError('Too many named labels in {}th subscript string of' + ' equation {} for input shape {} '.format( + i, equation, shape)) + ellipsis_end = ellipsis_start + len(shape) + 1 - len(labels) + shape[ellipsis_start:ellipsis_end] = ([ + np.prod( + list(filter(None, shape[ellipsis_start:ellipsis_end])), + dtype=np.int64) + ]) + else: + # This input does not contain an ellipsis. + if len(labels) != len(shape): + raise ValueError( + 'Number of named labels in input #{} of equation {} ' + 'must be equal to the number of dimensions in shape {}'.format( + i, equation, shape)) + for dim, label in zip(shape, labels): + if dim is not None: + label_to_dim[label] = max(label_to_dim[label], dim) + + resolved_shapes = [] + for labels in input_labels: + resolved_shapes.append([label_to_dim[label] for label in labels]) + return resolved_equation, resolved_shapes, ellipsis_label diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/standard_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/standard_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..dc70395c7a65fb58267daa687a69d1507ec4fdd9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/standard_ops.py @@ -0,0 +1,124 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=unused-import +"""Import names of Tensor Flow standard Ops.""" + +import platform as _platform +import sys as _sys + +from tensorflow.python import autograph + +# pylint: disable=g-bad-import-order +# Imports the following modules so that @RegisterGradient get executed. +from tensorflow.python.ops import array_grad +from tensorflow.python.ops import cudnn_rnn_grad +from tensorflow.python.ops import data_flow_grad +from tensorflow.python.ops import manip_grad +from tensorflow.python.ops import math_grad +from tensorflow.python.ops import random_grad +from tensorflow.python.ops import rnn_grad +from tensorflow.python.ops import sparse_grad +from tensorflow.python.ops import state_grad +from tensorflow.python.ops import tensor_array_grad + + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.array_ops import * # pylint: disable=redefined-builtin +from tensorflow.python.ops.check_ops import * +from tensorflow.python.ops.clip_ops import * +from tensorflow.python.ops.special_math_ops import * +# TODO(vrv): Switch to import * once we're okay with exposing the module. +from tensorflow.python.ops.cond import cond +from tensorflow.python.ops.confusion_matrix import confusion_matrix +from tensorflow.python.ops.control_flow_assert import Assert +from tensorflow.python.ops.control_flow_case import case +from tensorflow.python.ops.control_flow_ops import group +from tensorflow.python.ops.control_flow_ops import no_op +from tensorflow.python.ops.control_flow_ops import tuple # pylint: disable=redefined-builtin +# pylint: enable=redefined-builtin +from tensorflow.python.eager import wrap_function +from tensorflow.python.ops.while_loop import while_loop +from tensorflow.python.ops.batch_ops import * +from tensorflow.python.ops.critical_section_ops import * +from tensorflow.python.ops.data_flow_ops import * +from tensorflow.python.ops.functional_ops import * +from tensorflow.python.ops.gradients import * +from tensorflow.python.ops.histogram_ops import * +from tensorflow.python.ops.init_ops import * +from tensorflow.python.ops.io_ops import * +from tensorflow.python.ops.linalg_ops import * +from tensorflow.python.ops.logging_ops import Print +from tensorflow.python.ops.logging_ops import get_summary_op +from tensorflow.python.ops.logging_ops import timestamp +from tensorflow.python.ops.lookup_ops import initialize_all_tables +from tensorflow.python.ops.lookup_ops import tables_initializer +from tensorflow.python.ops.manip_ops import * +from tensorflow.python.ops.math_ops import * # pylint: disable=redefined-builtin +from tensorflow.python.ops.numerics import * +from tensorflow.python.ops.parsing_ops import * +from tensorflow.python.ops.partitioned_variables import * +from tensorflow.python.ops.proto_ops import * +from tensorflow.python.ops.ragged import ragged_batch_gather_ops +from tensorflow.python.ops.ragged import ragged_batch_gather_with_default_op +from tensorflow.python.ops.ragged import ragged_bincount_ops +from tensorflow.python.ops.ragged import ragged_check_ops +from tensorflow.python.ops.ragged import ragged_conversion_ops +from tensorflow.python.ops.ragged import ragged_dispatch as _ragged_dispatch +from tensorflow.python.ops.ragged import ragged_embedding_ops +from tensorflow.python.ops.ragged import ragged_image_ops +from tensorflow.python.ops.ragged import ragged_operators as _ragged_operators +from tensorflow.python.ops.ragged import ragged_squeeze_op +from tensorflow.python.ops.ragged import ragged_string_ops +from tensorflow.python.ops.random_ops import * +from tensorflow.python.ops.script_ops import py_func +from tensorflow.python.ops.session_ops import * +from tensorflow.python.ops.sort_ops import * +from tensorflow.python.ops.sparse_ops import * +from tensorflow.python.ops.state_ops import assign +from tensorflow.python.ops.state_ops import assign_add +from tensorflow.python.ops.state_ops import assign_sub +from tensorflow.python.ops.state_ops import count_up_to +from tensorflow.python.ops.state_ops import scatter_add +from tensorflow.python.ops.state_ops import scatter_div +from tensorflow.python.ops.state_ops import scatter_mul +from tensorflow.python.ops.state_ops import scatter_sub +from tensorflow.python.ops.state_ops import scatter_min +from tensorflow.python.ops.state_ops import scatter_max +from tensorflow.python.ops.state_ops import scatter_update +from tensorflow.python.ops.state_ops import scatter_nd_add +from tensorflow.python.ops.state_ops import scatter_nd_sub +# TODO(simister): Re-enable once binary size increase due to scatter_nd +# ops is under control. +# from tensorflow.python.ops.state_ops import scatter_nd_mul +# from tensorflow.python.ops.state_ops import scatter_nd_div +from tensorflow.python.ops.state_ops import scatter_nd_update +from tensorflow.python.ops.stateless_random_ops import * +from tensorflow.python.ops.string_ops import * +from tensorflow.python.ops.template import * +from tensorflow.python.ops.tensor_array_ops import * +from tensorflow.python.ops.variable_scope import * # pylint: disable=redefined-builtin +from tensorflow.python.ops.variables import * +from tensorflow.python.ops.parallel_for.control_flow_ops import vectorized_map + +from tensorflow.python.compiler.tensorrt import trt_convert as trt + +# pylint: enable=wildcard-import +# pylint: enable=g-bad-import-order + + +# These modules were imported to set up RaggedTensor operators and dispatchers: +del _ragged_dispatch, _ragged_operators diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9509f2d019c7e5cbae0084a69262f29afa3f38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_grad.py @@ -0,0 +1,52 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Gradients for operators defined in state_ops.py.""" + +from tensorflow.python.framework import ops + + +# TODO(b/31222613): These ops may be differentiable, and there may be +# latent bugs here. +ops.NotDifferentiable("Assign") + + +ops.NotDifferentiable("AssignAdd") + + +ops.NotDifferentiable("AssignSub") + + +ops.NotDifferentiable("ScatterAdd") + + +ops.NotDifferentiable("ScatterSub") + + +ops.NotDifferentiable("ScatterMul") + + +ops.NotDifferentiable("ScatterDiv") + + +ops.NotDifferentiable("ScatterNdUpdate") + +ops.NotDifferentiable("ScatterNdAdd") + +ops.NotDifferentiable("ScatterNdSub") + +ops.NotDifferentiable("ScatterNdMul") + +ops.NotDifferentiable("ScatterNdDiv") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b80487cd78c16992473aba8d374160096915394e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/state_ops.py @@ -0,0 +1,1043 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Variables. + +See the [Variables](https://www.tensorflow.org/guide/variables) guide. +""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gen_state_ops +from tensorflow.python.ops import state_grad # pylint: disable=unused-import +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.ops.gen_state_ops import * +# pylint: enable=wildcard-import +from tensorflow.python.util import deprecation +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=protected-access,g-doc-return-or-yield,g-doc-args +def variable_op(shape, dtype, name="Variable", set_shape=True, container="", + shared_name=""): + """Deprecated. Used variable_op_v2 instead.""" + if not set_shape: + shape = tensor_shape.unknown_shape() + ret = gen_state_ops.variable(shape=shape, dtype=dtype, name=name, + container=container, shared_name=shared_name) + # TODO(mrry): Move this to where it is used, so we can get rid of this op + # wrapper? + if set_shape: + ret.set_shape(shape) + return ret + + +def variable_op_v2(shape, dtype, name="Variable", container="", shared_name=""): + """Create a variable Operation. + + See also variables.Variable. + + Args: + shape: The shape of the tensor managed by this variable + dtype: The underlying type of the tensor values. + name: optional name to use for the variable op. + container: An optional string. Defaults to "". + If non-empty, this variable is placed in the given container. + Otherwise, a default container is used. + shared_name: An optional string. Defaults to "". + If non-empty, this variable is named in the given bucket + with this shared_name. Otherwise, the node name is used instead. + + Returns: + A variable tensor. + """ + return gen_state_ops.variable_v2( + shape=shape, + dtype=dtype, + name=name, + container=container, + shared_name=shared_name) + + +def init_variable(v, init, name="init"): + """Initializes variable with "init". + + This op does the following: + if init is a Tensor, v = init + if callable(init): v = init(VariableShape(v), v.dtype) + + Args: + v: Variable to initialize + init: Tensor to assign to v, + Or an object convertible to Tensor e.g. nparray, + Or an Initializer that generates a tensor given the shape and type of v. + An "Initializer" is a callable that returns a tensor that "v" should be + set to. It will be called as init(shape, dtype). + name: Optional name for the op. + + Returns: + The operation that initializes v. + """ + with ops.name_scope(None, v.op.name + "/", [v, init]): + with ops.name_scope(name) as scope: + with ops.colocate_with(v): + if callable(init): + assert v.get_shape().is_fully_defined(), "Variable shape unknown." + # TODO(mrry): Convert to v.shape when the property and + # accessor are reconciled (and all initializers support + # tf.TensorShape objects). + value = init(v.get_shape().as_list(), v.dtype.base_dtype) + value = ops.convert_to_tensor(value, name="value") + return gen_state_ops.assign(v, value, name=scope) + else: + init = ops.convert_to_tensor(init, name="init") + return gen_state_ops.assign(v, init, name=scope) + + +def is_variable_initialized(ref, name=None): + """Checks whether a tensor has been initialized. + + Outputs boolean scalar indicating whether the tensor has been initialized. + + Args: + ref: A mutable `Tensor`. + Should be from a `Variable` node. May be uninitialized. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.is_variable_initialized(ref=ref, name=name) + # Handle resource variables. + return ref.is_initialized(name=name) + + +@tf_export(v1=["assign_sub"]) +def assign_sub(ref, value, use_locking=None, name=None): + """Update `ref` by subtracting `value` from it. + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + Unlike `tf.math.subtract`, this op does not broadcast. `ref` and `value` + must have the same shape. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, + `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. Should be + from a `Variable` node. + value: A `Tensor`. Must have the same shape and dtype as `ref`. The value to + be subtracted to the variable. + use_locking: An optional `bool`. Defaults to `False`. If True, the + subtraction will be protected by a lock; otherwise the behavior is + undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + Same as `ref`. Returned as a convenience for operations that want + to use the new value after the variable has been updated. + + @compatibility(TF2) + `tf.compat.v1.assign_sub` is mostly compatible with eager + execution and `tf.function`. + + To switch to the native TF2 style, one could use method 'assign_sub' of + `tf.Variable`: + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `ref` | `self` | In `assign_sub()` method | + | `value` | `value` | In `assign_sub()` method | + | `use_locking` | `use_locking` | In `assign_sub()` method | + | `name` | `name` | In `assign_sub()` method | + | - | `read_value` | Set to True to replicate | + : : : behavior (True is default) : + + + #### Before & After Usage Example + + Before: + + >>> with tf.Graph().as_default(): + ... with tf.compat.v1.Session() as sess: + ... a = tf.compat.v1.Variable(1, dtype=tf.int64) + ... sess.run(a.initializer) + ... update_op = tf.compat.v1.assign_sub(a, 1) + ... res_a = sess.run(update_op) + ... res_a + 0 + + After: + + >>> b = tf.Variable(1, dtype=tf.int64) + >>> res_b = b.assign_sub(1) + >>> res_b.numpy() + 0 + + @end_compatibility + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.assign_sub( + ref, value, use_locking=use_locking, name=name) + return ref.assign_sub(value) + + +@tf_export(v1=["assign_add"]) +def assign_add(ref, value, use_locking=None, name=None): + """Update `ref` by adding `value` to it. + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + Unlike `tf.math.add`, this op does not broadcast. `ref` and `value` must have + the same shape. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, + `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. Should be + from a `Variable` node. + value: A `Tensor`. Must have the same shape and dtype as `ref`. The value to + be added to the variable. + use_locking: An optional `bool`. Defaults to `False`. If True, the addition + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + Same as `ref`. Returned as a convenience for operations that want + to use the new value after the variable has been updated. + + @compatibility(TF2) + `tf.compat.v1.assign_add` is mostly compatible with eager + execution and `tf.function`. + + To switch to the native TF2 style, one could use method 'assign_add' of + `tf.Variable`: + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `ref` | `self` | In `assign_add()` method | + | `value` | `value` | In `assign_add()` method | + | `use_locking` | `use_locking` | In `assign_add()` method | + | `name` | `name` | In `assign_add()` method | + | - | `read_value` | Set to True to replicate | + : : : behavior (True is default) : + + + #### Before & After Usage Example + + Before: + + >>> with tf.Graph().as_default(): + ... with tf.compat.v1.Session() as sess: + ... a = tf.compat.v1.Variable(0, dtype=tf.int64) + ... sess.run(a.initializer) + ... update_op = tf.compat.v1.assign_add(a, 1) + ... res_a = sess.run(update_op) + ... res_a + 1 + + After: + + >>> b = tf.Variable(0, dtype=tf.int64) + >>> res_b = b.assign_add(1) + >>> res_b.numpy() + 1 + + @end_compatibility + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.assign_add( + ref, value, use_locking=use_locking, name=name) + return ref.assign_add(value) + + +@tf_export(v1=["assign"]) +def assign(ref, value, validate_shape=None, use_locking=None, name=None): + """Update `ref` by assigning `value` to it. + + This operation outputs a Tensor that holds the new value of `ref` after + the value has been assigned. This makes it easier to chain operations that + need to use the reset value. + + Args: + ref: A mutable `Tensor`. Should be from a `Variable` node. May be + uninitialized. + value: A `Tensor`. Must have the same shape and dtype as `ref`. The value to + be assigned to the variable. + validate_shape: An optional `bool`. Defaults to `True`. If true, the + operation will validate that the shape of 'value' matches the shape of the + Tensor being assigned to. If false, 'ref' will take on the shape of + 'value'. + use_locking: An optional `bool`. Defaults to `True`. If True, the assignment + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + A `Tensor` that will hold the new value of `ref` after + the assignment has completed. + + @compatibility(TF2) + `tf.compat.v1.assign` is mostly compatible with eager + execution and `tf.function`. However, argument 'validate_shape' will be + ignored. To avoid shape validation, set 'shape' to tf.TensorShape(None) when + constructing the variable: + + >>> import tensorflow as tf + >>> a = tf.Variable([1], shape=tf.TensorShape(None)) + >>> tf.compat.v1.assign(a, [2,3]) + + To switch to the native TF2 style, one could use method 'assign' of + `tf.Variable`: + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `ref` | `self` | In `assign()` method | + | `value` | `value` | In `assign()` method | + | `validate_shape` | Not supported | Specify `shape` in the | + : : : constructor to replicate : + : : : behavior : + | `use_locking` | `use_locking` | In `assign()` method | + | `name` | `name` | In `assign()` method | + | - | `read_value` | Set to True to replicate | + : : : behavior (True is default) : + @end_compatibility + + + #### Before & After Usage Example + + Before: + + >>> with tf.Graph().as_default(): + ... with tf.compat.v1.Session() as sess: + ... a = tf.compat.v1.Variable(0, dtype=tf.int64) + ... sess.run(a.initializer) + ... update_op = tf.compat.v1.assign(a, 2) + ... res_a = sess.run(update_op) + ... res_a + 2 + + After: + + >>> b = tf.Variable(0, dtype=tf.int64) + >>> res_b = b.assign(2) + >>> res_b.numpy() + 2 + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.assign( + ref, value, use_locking=use_locking, name=name, + validate_shape=validate_shape) + return ref.assign(value, name=name) + + +@tf_export(v1=["count_up_to"]) +@deprecated(None, "Prefer Dataset.range instead.") +def count_up_to(ref, limit, name=None): + r"""Increments 'ref' until it reaches 'limit'. + + Args: + ref: A Variable. Must be one of the following types: `int32`, `int64`. + Should be from a scalar `Variable` node. + limit: An `int`. + If incrementing ref would bring it above limit, instead generates an + 'OutOfRange' error. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `ref`. + A copy of the input before increment. If nothing else modifies the + input, the values produced will all be distinct. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.count_up_to(ref, limit=limit, name=name) + return gen_state_ops.resource_count_up_to( + ref.handle, limit, T=ref.dtype, name=name) + + +@tf_export(v1=["scatter_update"]) +def scatter_update(ref, indices, updates, use_locking=True, name=None): + # pylint: disable=line-too-long + r"""Applies sparse updates to a variable reference. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] = updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] = updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + If values in `ref` is to be updated more than once, because there are + duplicate entries in `indices`, the order at which the updates happen + for each value is undefined. + + Requires `updates.shape = indices.shape + ref.shape[1:]`. + +
+ +
+ + Args: + ref: A `Variable`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to store in `ref`. + use_locking: An optional `bool`. Defaults to `True`. + If True, the assignment will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + Same as `ref`. Returned as a convenience for operations that want + to use the updated values after the update is done. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_update(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_update( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_nd_update"]) +def scatter_nd_update(ref, indices, updates, use_locking=True, name=None): + r"""Applies sparse `updates` to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. + ``` + + For example, say we want to update 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + update = tf.compat.v1.scatter_nd_update(ref, indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(update) + ``` + + The resulting update to ref would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A Variable. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A Tensor. Must have the same type as ref. A tensor of updated + values to add to ref. + use_locking: An optional `bool`. Defaults to `True`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + The value of the variable after the update. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_nd_update( + ref, indices, updates, use_locking, name) + return ref._lazy_read(gen_state_ops.resource_scatter_nd_update( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_add"]) +def scatter_add(ref, indices, updates, use_locking=False, name=None): + # pylint: disable=line-too-long + r"""Adds sparse updates to the variable referenced by `resource`. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] += updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] += updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] += updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the updated value. + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]`. + +
+ +
+ + Args: + ref: A `Variable`. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to store in `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the assignment will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + Same as `ref`. Returned as a convenience for operations that want + to use the updated values after the update is done. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_add(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_add( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_nd_add"]) +def scatter_nd_add(ref, indices, updates, use_locking=False, name=None): + r"""Applies sparse addition to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that addition would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1], [7]]) + updates = tf.constant([9, 10, 11, 12]) + add = tf.compat.v1.scatter_nd_add(ref, indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(add) + ``` + + The resulting update to ref would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, + `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, + `uint32`, `uint64`. A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to add to ref. + use_locking: An optional `bool`. Defaults to `False`. + If True, the assignment will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_nd_add( + ref, indices, updates, use_locking, name) + return ref._lazy_read(gen_state_ops.resource_scatter_nd_add( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_sub"]) +def scatter_sub(ref, indices, updates, use_locking=False, name=None): + r"""Subtracts sparse updates to a variable reference. + + ```python + # Scalar indices + ref[indices, ...] -= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] -= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their (negated) contributions add. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or + `updates.shape = []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, + `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, + `uint32`, `uint64`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to subtract from `ref`. + use_locking: An optional `bool`. Defaults to `False`. + If True, the subtraction will be protected by a lock; + otherwise the behavior is undefined, but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_sub(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_sub( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_nd_sub"]) +def scatter_nd_sub(ref, indices, updates, use_locking=False, name=None): + r"""Applies sparse subtraction to individual values or slices in a Variable. + + `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into `ref`. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of `ref`. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]] + ``` + + For example, say we want to subtract 4 scattered elements from a rank-1 tensor + with 8 elements. In Python, that update would look like this: + + ```python + ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + op = tf.compat.v1.scatter_nd_sub(ref, indices, updates) + with tf.compat.v1.Session() as sess: + print sess.run(op) + ``` + + The resulting update to ref would look like this: + + [1, -9, 3, -6, -6, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, + `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, + `uint32`, `uint64`. A mutable Tensor. Should be from a Variable node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + A tensor of indices into ref. + updates: A `Tensor`. Must have the same type as `ref`. + A tensor of updated values to add to ref. + use_locking: An optional `bool`. Defaults to `False`. + An optional bool. Defaults to True. If True, the assignment will + be protected by a lock; otherwise the behavior is undefined, + but may exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_nd_sub( + ref, indices, updates, use_locking, name) + return ref._lazy_read(gen_state_ops.resource_scatter_nd_sub( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_mul"]) +def scatter_mul(ref, indices, updates, use_locking=False, name=None): + # pylint: disable=line-too-long + r"""Multiplies sparse updates into a variable reference. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] *= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] *= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions multiply. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = + []`. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, + `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, + `uint32`, `uint64`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A + tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. A tensor of updated + values to multiply to `ref`. + use_locking: An optional `bool`. Defaults to `False`. If True, the operation + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_mul(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_mul( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_div"]) +def scatter_div(ref, indices, updates, use_locking=False, name=None): + # pylint: disable=line-too-long + r"""Divides a variable reference by sparse updates. + + This operation computes + + ```python + # Scalar indices + ref[indices, ...] /= updates[...] + + # Vector indices (for each i) + ref[indices[i], ...] /= updates[i, ...] + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...] + ``` + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions divide. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = + []`. + + Args: + ref: A mutable `Tensor`. Must be one of the following types: `float32`, + `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, + `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, + `uint32`, `uint64`. Should be from a `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A + tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. A tensor of values + that `ref` is divided by. + use_locking: An optional `bool`. Defaults to `False`. If True, the operation + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_div(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_div( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_max"]) +def scatter_max(ref, indices, updates, use_locking=False, name=None): + # pylint: disable=line-too-long + r"""Reduces sparse updates into a variable reference using the `max` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = max(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = max(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = max(ref[indices[i, ..., j], ...], + updates[i, ..., j, ...]) + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions combine. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = + []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `half`, + `bfloat16`, `float32`, `float64`, `int32`, `int64`. Should be from a + `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A + tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. A tensor of updated + values to reduce into `ref`. + use_locking: An optional `bool`. Defaults to `False`. If True, the update + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_max(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_max( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["scatter_min"]) +def scatter_min(ref, indices, updates, use_locking=False, name=None): + # pylint: disable=line-too-long + r"""Reduces sparse updates into a variable reference using the `min` operation. + + This operation computes + + # Scalar indices + ref[indices, ...] = min(ref[indices, ...], updates[...]) + + # Vector indices (for each i) + ref[indices[i], ...] = min(ref[indices[i], ...], updates[i, ...]) + + # High rank indices (for each i, ..., j) + ref[indices[i, ..., j], ...] = min(ref[indices[i, ..., j], ...], + updates[i, ..., j, ...]) + + This operation outputs `ref` after the update is done. + This makes it easier to chain operations that need to use the reset value. + + Duplicate entries are handled correctly: if multiple `indices` reference + the same location, their contributions combine. + + Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = + []`. + +
+ +
+ + Args: + ref: A mutable `Tensor`. Must be one of the following types: `half`, + `bfloat16`, `float32`, `float64`, `int32`, `int64`. Should be from a + `Variable` node. + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A + tensor of indices into the first dimension of `ref`. + updates: A `Tensor`. Must have the same type as `ref`. A tensor of updated + values to reduce into `ref`. + use_locking: An optional `bool`. Defaults to `False`. If True, the update + will be protected by a lock; otherwise the behavior is undefined, but may + exhibit less contention. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor`. Has the same type as `ref`. + """ + if ref.dtype._is_ref_dtype: + return gen_state_ops.scatter_min(ref, indices, updates, + use_locking=use_locking, name=name) + return ref._lazy_read(gen_resource_variable_ops.resource_scatter_min( # pylint: disable=protected-access + ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype), + name=name)) + + +@tf_export(v1=["batch_scatter_update"]) +@deprecation.deprecated( + "2018-11-29", "Use the batch_scatter_update method of Variable instead.") +def batch_scatter_update(ref, indices, updates, use_locking=True, name=None): + """Generalization of `tf.compat.v1.scatter_update` to axis different than 0. + + Analogous to `batch_gather`. This assumes that `ref`, `indices` and `updates` + have a series of leading dimensions that are the same for all of them, and the + updates are performed on the last dimension of indices. In other words, the + dimensions should be the following: + + `num_prefix_dims = indices.ndims - 1` + `batch_dim = num_prefix_dims + 1` + `updates.shape = indices.shape + var.shape[batch_dim:]` + + where + + `updates.shape[:num_prefix_dims]` + `== indices.shape[:num_prefix_dims]` + `== var.shape[:num_prefix_dims]` + + And the operation performed can be expressed as: + + `var[i_1, ..., i_n, indices[i_1, ..., i_n, j]] = updates[i_1, ..., i_n, j]` + + When indices is a 1D tensor, this operation is equivalent to + `tf.compat.v1.scatter_update`. + + To avoid this operation there would be 2 alternatives: + 1) Reshaping the variable by merging the first `ndims` dimensions. However, + this is not possible because `tf.reshape` returns a Tensor, which we + cannot use `tf.compat.v1.scatter_update` on. + 2) Looping over the first `ndims` of the variable and using + `tf.compat.v1.scatter_update` on the subtensors that result of slicing the + first + dimension. This is a valid option for `ndims = 1`, but less efficient than + this implementation. + + See also `tf.compat.v1.scatter_update` and `tf.compat.v1.scatter_nd_update`. + + Args: + ref: `Variable` to scatter onto. + indices: Tensor containing indices as described above. + updates: Tensor of updates to apply to `ref`. + use_locking: Boolean indicating whether to lock the writing operation. + name: Optional scope name string. + + Returns: + Ref to `variable` after it has been modified. + + Raises: + ValueError: If the initial `ndims` of `ref`, `indices`, and `updates` are + not the same. + """ + with ops.name_scope(name): + indices = ops.convert_to_tensor(indices, name="indices") + indices_shape = array_ops.shape(indices) + indices_dimensions = indices.get_shape().ndims + + if indices_dimensions is None: + raise ValueError("batch_gather does not allow indices with unknown " + "shape.") + + nd_indices = array_ops.expand_dims(indices, axis=-1) + nd_indices_list = [] + + # Scatter ND requires indices to have an additional dimension, in which the + # coordinates of the updated things are specified. For this to be adapted to + # the scatter_update with several leading dimensions, we simply make use of + # a tf.range for all the leading dimensions followed by concat of all the + # coordinates we created with the original indices. + + # For example if indices.shape = [2, 3, 4], we should generate the following + # indices for tf.compat.v1.scatter_nd_update: + # nd_indices[:, :, 0] = [[0, 0, 0], [1, 1, 1]] + # nd_indices[:, :, 1] = [[0, 1, 2], [0, 1, 2]] + # nd_indices[:, :, 2] = indices + for dimension in range(indices_dimensions - 1): + # In this loop we generate the following for the example (one for each + # iteration). + # nd_indices[:, :, 0] = [[0, 0, 0], [1, 1, 1]] + # nd_indices[:, :, 1] = [[0, 1, 2], [0, 1, 2]] + # This is done at every iteration with a tf.range over the size of the + # i-th dimension and using broadcasting over the desired shape. + dimension_size = indices_shape[dimension] + shape_to_broadcast = [1] * (indices_dimensions + 1) + shape_to_broadcast[dimension] = dimension_size + dimension_range = array_ops.reshape( + gen_math_ops._range(0, dimension_size, 1), shape_to_broadcast) + if dimension_range.dtype.base_dtype != nd_indices.dtype: + dimension_range = gen_math_ops.cast(dimension_range, nd_indices.dtype) + nd_indices_list.append( + dimension_range * array_ops.ones_like(nd_indices)) + # Add the original indices at the end, as described above, and concat. + nd_indices_list.append(nd_indices) + final_indices = array_ops.concat(nd_indices_list, axis=-1) + return scatter_nd_update( + ref, final_indices, updates, use_locking=use_locking) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateful_random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateful_random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..a33ea0c9f21a2ea3a46aa5f2c19b9167a006e860 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateful_random_ops.py @@ -0,0 +1,1031 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Operations for generating random numbers.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import sharded_variable +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_stateful_random_ops +from tensorflow.python.ops import gen_stateless_random_ops_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops_util +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.ops import variables +from tensorflow.python.trackable import autotrackable +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# A seed for random ops (stateful and stateless) will always be 1024 +# bits, all of which will be sent to the C++ code. The actual C++ +# implementation of some algorithms may only use a lower part of the bits. + +UINT64_HALF_SPAN = 2**63 +MAX_INT64 = UINT64_HALF_SPAN - 1 +MIN_INT64 = -UINT64_HALF_SPAN +UINT64_SPAN = UINT64_HALF_SPAN * 2 +# 'Variable' doesn't support uint32 or uint64 yet (due to reasons explained in +# b/111604096 and cl/171681867), so I use signed int here. I choose int64 +# instead of int32 here because `VarHandleOp` doesn't support int32 on GPU. +SEED_TYPE = "int64" +SEED_MIN = MIN_INT64 +SEED_MAX = MAX_INT64 +SEED_UINT_SPAN = UINT64_SPAN +SEED_TYPE_BITS = 64 +SEED_BIT_MASK = 0xFFFFFFFFFFFFFFFF +SEED_SIZE = 16 # in units of SEED_TYPE + + +STATE_TYPE = SEED_TYPE +ALGORITHM_TYPE = STATE_TYPE + + +# The following sizes are all in unit of uint64. +PHILOX_KEY_SIZE = 1 +THREEFRY_KEY_SIZE = 1 +PHILOX_COUNTER_SIZE = 2 +THREEFRY_COUNTER_SIZE = 1 +PHILOX_STATE_SIZE = PHILOX_COUNTER_SIZE + PHILOX_KEY_SIZE +THREEFRY_STATE_SIZE = THREEFRY_COUNTER_SIZE + THREEFRY_KEY_SIZE + + +RNG_ALG_PHILOX = random_ops_util.Algorithm.PHILOX.value +RNG_ALG_THREEFRY = random_ops_util.Algorithm.THREEFRY.value + + +DEFAULT_ALGORITHM = RNG_ALG_PHILOX + + +def non_deterministic_ints(shape, dtype=dtypes.int64): + """Non-deterministically generates some integers. + + This op may use some OS-provided source of non-determinism (e.g. an RNG), so + each execution will give different results. + + Args: + shape: the shape of the result. + dtype: (optional) the dtype of the result. + + Returns: + a tensor whose element values are non-deterministically chosen. + """ + return gen_stateful_random_ops.non_deterministic_ints( + shape=shape, dtype=dtype) + + +def _uint_to_int(n): + if isinstance(n, int) and n > SEED_MAX: + n = n - SEED_UINT_SPAN + return n + + +def _make_1d_state(state_size, seed): + """Makes a 1-D RNG state. + + Args: + state_size: an integer. + seed: an integer or 1-D tensor. + + Returns: + a 1-D tensor of shape [state_size] and dtype STATE_TYPE. + """ + if isinstance(seed, int): + # chop the Python integer (infinite precision) into chunks of SEED_TYPE + ls = [] + for _ in range(state_size): + ls.append(seed & SEED_BIT_MASK) + seed >>= SEED_TYPE_BITS + seed = ls + # to avoid overflow error from ops.convert_to_tensor + seed = nest.map_structure(_uint_to_int, seed) + seed = math_ops.cast(seed, STATE_TYPE) + seed = array_ops.reshape(seed, [-1]) + seed = seed[0:state_size] + # Padding with zeros on the *left* if too short. Padding on the right would + # cause a small seed to be used as the "counter" while the "key" is always + # zero (for counter-based RNG algorithms), because in the current memory + # layout counter is stored before key. In such a situation two RNGs with + # two different small seeds may generate overlapping outputs. + seed_size = seed.shape[0] + if seed_size is None: + seed_size = array_ops.shape(seed)[0] + padding_size = math_ops.maximum(state_size - seed_size, 0) + padding = array_ops.zeros([padding_size], seed.dtype) + # can't use `pad` because it doesn't support integer dtypes on GPU + seed = array_ops.concat([padding, seed], axis=0) + seed.set_shape([state_size]) + return seed + + +def _get_counter_size(alg): + if alg == random_ops_util.Algorithm.PHILOX.value: + return PHILOX_COUNTER_SIZE + elif alg == random_ops_util.Algorithm.THREEFRY.value: + return THREEFRY_COUNTER_SIZE + elif alg == random_ops_util.Algorithm.AUTO_SELECT.value: + # For AUTO_SELECT, we'll manage the counter as if it's for Philox. + return PHILOX_COUNTER_SIZE + else: + raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg)) + + +def _get_state_size(alg): + if alg == random_ops_util.Algorithm.PHILOX.value: + return PHILOX_STATE_SIZE + elif alg == random_ops_util.Algorithm.THREEFRY.value: + return THREEFRY_STATE_SIZE + elif alg == random_ops_util.Algorithm.AUTO_SELECT.value: + # For AUTO_SELECT, we'll manage the state as if it's for Philox. + return PHILOX_STATE_SIZE + else: + raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg)) + + +def _check_state_shape(shape, alg): + if isinstance(alg, tensor.Tensor) and not context.executing_eagerly(): + return + shape.assert_is_compatible_with([_get_state_size(int(alg))]) + + +def _make_state_from_seed(seed, alg): + return _make_1d_state(_get_state_size(alg), seed) + + +@tf_export("random.create_rng_state", "random.experimental.create_rng_state") +def create_rng_state(seed, alg): + """Creates a RNG state from an integer or a vector. + + Example: + + >>> tf.random.create_rng_state( + ... 1234, "philox") + + >>> tf.random.create_rng_state( + ... [12, 34], "threefry") + + + Args: + seed: an integer or 1-D numpy array. + alg: the RNG algorithm. Can be a string, an `Algorithm` or an integer. + + Returns: + a 1-D numpy array whose size depends on the algorithm. + """ + alg = random_ops_util.convert_alg_to_int(alg) + return _make_state_from_seed(seed, alg) + + +def _shape_tensor(shape): + """Convert to an int32 or int64 tensor, defaulting to int64 if empty.""" + if isinstance(shape, (tuple, list)) and not shape: + dtype = dtypes.int64 + else: + dtype = None + return ops.convert_to_tensor(shape, dtype=dtype, name="shape") + + +def _convert_to_state_tensor(t): + # to avoid out-of-range error from ops.convert_to_tensor + t = nest.map_structure(_uint_to_int, t) + return math_ops.cast(t, STATE_TYPE) + + +def get_replica_id(): + rctx = distribute_lib.get_replica_context() + if rctx is None: + return None + return rctx.replica_id_in_sync_group + + +@tf_export("random.Generator", "random.experimental.Generator") +class Generator(autotrackable.AutoTrackable): + """Random-number generator. + + Example: + + Creating a generator from a seed: + + >>> g = tf.random.Generator.from_seed(1234) + >>> g.normal(shape=(2, 3)) + + + Creating a generator from a non-deterministic state: + + >>> g = tf.random.Generator.from_non_deterministic_state() + >>> g.normal(shape=(2, 3)) + + + All the constructors allow explicitly choosing an Random-Number-Generation + (RNG) algorithm. Supported algorithms are `"philox"` and `"threefry"`. For + example: + + >>> g = tf.random.Generator.from_seed(123, alg="philox") + >>> g.normal(shape=(2, 3)) + + + CPU, GPU and TPU with the same algorithm and seed will generate the same + integer random numbers. Float-point results (such as the output of `normal`) + may have small numerical discrepancies between different devices. + + This class uses a `tf.Variable` to manage its internal state. Every time + random numbers are generated, the state of the generator will change. For + example: + + >>> g = tf.random.Generator.from_seed(1234) + >>> g.state + + >>> g.normal(shape=(2, 3)) + <...> + >>> g.state + + + The shape of the state is algorithm-specific. + + There is also a global generator: + + >>> g = tf.random.get_global_generator() + >>> g.normal(shape=(2, 3)) + + + When creating a generator inside a `tf.distribute.Strategy` scope, each + replica will get a different stream of random numbers. + + For example, in this code: + + ``` + strat = tf.distribute.MirroredStrategy(devices=["cpu:0", "cpu:1"]) + with strat.scope(): + g = tf.random.Generator.from_seed(1) + def f(): + return g.normal([]) + results = strat.run(f).values + ``` + + `results[0]` and `results[1]` will have different values. + + If the generator is seeded (e.g. created via `Generator.from_seed`), the + random numbers will be determined by the seed, even though different replicas + get different numbers. One can think of a random number generated on a + replica as a hash of the replica ID and a "master" random number that may be + common to all replicas. Hence, the whole system is still deterministic. + + (Note that the random numbers on different replicas are not correlated, even + if they are deterministically determined by the same seed. They are not + correlated in the sense that no matter what statistics one calculates on them, + there won't be any discernable correlation.) + + Generators can be freely saved and restored using `tf.train.Checkpoint`. The + checkpoint can be restored in a distribution strategy with a different number + of replicas than the original strategy. If a replica ID is present in both the + original and the new distribution strategy, its state will be properly + restored (i.e. the random-number stream from the restored point will be the + same as that from the saving point) unless the replicas have already diverged + in their RNG call traces before saving (e.g. one replica has made one RNG call + while another has made two RNG calls). We don't have such guarantee if the + generator is saved in a strategy scope and restored outside of any strategy + scope, or vice versa. + + When a generator is created within the scope of + `tf.distribute.experimental.ParameterServerStrategy`, the workers + will share the generator's state (placed on one of the parameter + servers). In this way the workers will still get different + random-number streams, as stated above. (This is similar to replicas + in a `tf.distribute.MirroredStrategy` sequentially accessing a + generator created outside the strategy.) Each RNG call on a worker + will incur a round-trip to a parameter server, which may have + performance impacts. When creating a + `tf.distribute.experimental.ParameterServerStrategy`, please make + sure that the `variable_partitioner` argument won't shard small + variables of shape `[2]` or `[3]` (because generator states must not + be sharded). Ways to avoid sharding small variables include setting + `variable_partitioner` to `None` or to + `tf.distribute.experimental.partitioners.MinSizePartitioner` with a + large enough `min_shard_bytes` (see + `tf.distribute.experimental.ParameterServerStrategy`'s documentation + for more details). + """ + + @classmethod + def from_state(cls, state, alg): + """Creates a generator from a state. + + See `__init__` for description of `state` and `alg`. + + Args: + state: the new state. + alg: the RNG algorithm. + + Returns: + The new generator. + """ + return cls(alg=alg, state=state) + + @classmethod + def from_seed(cls, seed, alg=None): + """Creates a generator from a seed. + + A seed is a 1024-bit unsigned integer represented either as a Python + integer or a vector of integers. Seeds shorter than 1024-bit will be + padded. The padding, the internal structure of a seed and the way a seed + is converted to a state are all opaque (unspecified). The only semantics + specification of seeds is that two different seeds are likely to produce + two independent generators (but no guarantee). + + Args: + seed: the seed for the RNG. + alg: (optional) the RNG algorithm. If None, it will be auto-selected. See + `__init__` for its possible values. + + Returns: + The new generator. + """ + if alg is None: + # TODO(b/170668986): more sophisticated algorithm selection + alg = DEFAULT_ALGORITHM + alg = random_ops_util.convert_alg_to_int(alg) + state = create_rng_state(seed, alg) + return cls(state=state, alg=alg) + + @classmethod + def from_non_deterministic_state(cls, alg=None): + """Creates a generator by non-deterministically initializing its state. + + The source of the non-determinism will be platform- and time-dependent. + + Args: + alg: (optional) the RNG algorithm. If None, it will be auto-selected. See + `__init__` for its possible values. + + Returns: + The new generator. + """ + if config.is_op_determinism_enabled(): + raise RuntimeError('"from_non_deterministic_state" cannot be called when ' # pylint: disable=g-doc-exception + "determinism is enabled.") + if alg is None: + # TODO(b/170668986): more sophisticated algorithm selection + alg = DEFAULT_ALGORITHM + alg = random_ops_util.convert_alg_to_int(alg) + state = non_deterministic_ints(shape=[_get_state_size(alg)], + dtype=SEED_TYPE) + return cls(state=state, alg=alg) + + @classmethod + def from_key_counter(cls, key, counter, alg): + """Creates a generator from a key and a counter. + + This constructor only applies if the algorithm is a counter-based algorithm. + See method `key` for the meaning of "key" and "counter". + + Args: + key: the key for the RNG, a scalar of type STATE_TYPE. + counter: a vector of dtype STATE_TYPE representing the initial counter for + the RNG, whose length is algorithm-specific., + alg: the RNG algorithm. If None, it will be auto-selected. See + `__init__` for its possible values. + + Returns: + The new generator. + """ + counter = _convert_to_state_tensor(counter) + key = _convert_to_state_tensor(key) + alg = random_ops_util.convert_alg_to_int(alg) + counter.shape.assert_is_compatible_with([_get_state_size(alg) - 1]) + key.shape.assert_is_compatible_with([]) + key = array_ops.reshape(key, [1]) + state = array_ops.concat([counter, key], 0) + return cls(state=state, alg=alg) + + def __init__(self, copy_from=None, state=None, alg=None): + """Creates a generator. + + The new generator will be initialized by one of the following ways, with + decreasing precedence: + (1) If `copy_from` is not None, the new generator is initialized by copying + information from another generator. + (2) If `state` and `alg` are not None (they must be set together), the new + generator is initialized by a state. + + Args: + copy_from: a generator to be copied from. + state: a vector of dtype STATE_TYPE representing the initial state of the + RNG, whose length and semantics are algorithm-specific. If it's a + variable, the generator will reuse it instead of creating a new + variable. + alg: the RNG algorithm. Possible values are + `tf.random.Algorithm.PHILOX` for the Philox algorithm and + `tf.random.Algorithm.THREEFRY` for the ThreeFry algorithm + (see paper 'Parallel Random Numbers: As Easy as 1, 2, 3' + [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]). + The string names `"philox"` and `"threefry"` can also be used. + Note `PHILOX` guarantees the same numbers are produced (given + the same random state) across all architectures (CPU, GPU, XLA etc). + """ + # TODO(b/175072242): Remove distribution-strategy dependencies in this file. + if distribute_lib.has_strategy(): + self._distribution_strategy = distribute_lib.get_strategy() + else: + self._distribution_strategy = None + if copy_from is not None: + # All other arguments should be None + assert (alg or state) is None + self._state_var = self._create_variable(copy_from.state, dtype=STATE_TYPE, + trainable=False) + self._alg = copy_from.algorithm + else: + assert alg is not None and state is not None + alg = random_ops_util.convert_alg_to_int(alg) + if isinstance(state, variables.Variable): + _check_state_shape(state.shape, alg) + self._state_var = state + else: + state = _convert_to_state_tensor(state) + _check_state_shape(state.shape, alg) + self._state_var = self._create_variable(state, dtype=STATE_TYPE, + trainable=False) + self._alg = alg + + def _create_variable(self, *args, **kwargs): + """Creates a variable. + + Args: + *args: positional arguments passed along to `variables.Variable. + **kwargs: keyword arguments passed along to `variables.Variable. + + Returns: + The created variable. + """ + with ops.name_scope("random_generator"): + # Make sure we don't change this name since Keras was using this name + # to filter out the state variable. + kwargs["name"] = "StateVar" + v = variables.Variable(*args, **kwargs) + if isinstance(v, sharded_variable.ShardedVariable): + # RNG state is an atomic entity representing a 128-bit or + # 192-bit value, so it mustn't be sharded. + raise ValueError( + "tf.random.Generator state is sharded, which is not allowed. When " + "creating a tf.distribute.experimental.ParameterServerStrategy, " + "please make sure that the `variable_partitioner` " + "argument won't shard a " + "small variable of shape [2] or [3]. Ways to avoid sharding small " + "variables include setting `variable_partitioner` to None or to " + "tf.distribute.experimental.partitioners.MinSizePartitioner with a " + "large enough `min_shard_bytes`.") + return v + + def reset(self, state): + """Resets the generator by a new state. + + See `__init__` for the meaning of "state". + + Args: + state: the new state. + """ + state = _convert_to_state_tensor(state) + state.shape.assert_is_compatible_with([_get_state_size(self.algorithm)]) + self._state_var.assign(state) + + def reset_from_seed(self, seed): + """Resets the generator by a new seed. + + See `from_seed` for the meaning of "seed". + + Args: + seed: the new seed. + """ + state = create_rng_state(seed, self.algorithm) + self._state_var.assign(state) + + def reset_from_key_counter(self, key, counter): + """Resets the generator by a new key-counter pair. + + See `from_key_counter` for the meaning of "key" and "counter". + + Args: + key: the new key. + counter: the new counter. + """ + counter = _convert_to_state_tensor(counter) + key = _convert_to_state_tensor(key) + counter.shape.assert_is_compatible_with( + [_get_state_size(self.algorithm) - 1]) + key.shape.assert_is_compatible_with([]) + key = array_ops.reshape(key, [1]) + state = array_ops.concat([counter, key], 0) + self._state_var.assign(state) + + @property + def state(self): + """The internal state of the RNG.""" + return self._state_var + + @property + def algorithm(self): + """The RNG algorithm id (a Python integer or scalar integer Tensor).""" + return self._alg + + def _standard_normal(self, shape, dtype): + key, counter = self._prepare_key_counter(shape) + return gen_stateless_random_ops_v2.stateless_random_normal_v2( + shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm) + + @property + def key(self): + """The 'key' part of the state of a counter-based RNG. + + For a counter-base RNG algorithm such as Philox and ThreeFry (as + described in paper 'Parallel Random Numbers: As Easy as 1, 2, 3' + [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]), + the RNG state consists of two parts: counter and key. The output is + generated via the formula: output=hash(key, counter), i.e. a hashing of + the counter parametrized by the key. Two RNGs with two different keys can + be thought as generating two independent random-number streams (a stream + is formed by increasing the counter). + + Returns: + A scalar which is the 'key' part of the state, if the RNG algorithm is + counter-based; otherwise it raises a ValueError. + """ + alg = self.algorithm + if alg in (a.value for a in random_ops_util.Algorithm): + return self._state_var[-1] + else: + raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg)) + + def _skip_single_var(self, var, delta): + resource_variable_ops.variable_accessed(var) + # TODO(wangpeng): Cache the cast algorithm instead of casting everytime. + return gen_stateful_random_ops.rng_read_and_skip( + var.handle, + alg=math_ops.cast(self.algorithm, dtypes.int32), + delta=math_ops.cast(delta, dtypes.uint64)) + + def skip(self, delta): + """Advance the counter of a counter-based RNG. + + Args: + delta: the amount of advancement. The state of the RNG after + `skip(n)` will be the same as that after `normal([n])` + (or any other distribution). The actual increment added to the + counter is an unspecified implementation detail. + + Returns: + A `Tensor` of type `int64`. + """ + + def update_fn(v): + return self._skip_single_var(v, delta) + # TODO(b/170515001): Always call strategy.extended.update after calling it + # from both replica context and cross-replica context is supported. + if values_util.is_saving_non_distributed(): + # Assumes replica context with replica_id=0, since we only save the first + # replica. + return update_fn(self.state) + if self._distribution_strategy is not None: + with distribute_lib.enter_or_assert_strategy(self._distribution_strategy): + if distribute_lib.in_cross_replica_context(): + # Code that operates on all replicas of a variable cannot be saved + # without retracing. + values_util.mark_as_unsaveable() + if (distribute_lib.in_cross_replica_context() or + "CentralStorage" in type(self._distribution_strategy).__name__): + # In cross-replica context we need to use strategy.extended.update. + # In CentralStorageStrategy we also need to use + # strategy.extended.update (even for replica context), + # because variable updates here must be within merge_call. + return distribute_lib.get_strategy().extended.update( + self.state, update_fn) + return update_fn(self.state) + + def _preprocess_key(self, key): + if self._distribution_strategy is None: + return key + with distribute_lib.enter_or_assert_strategy(self._distribution_strategy): + replica_id = get_replica_id() + if replica_id is not None: + replica_id = array_ops_stack.stack([replica_id, 0], axis=0) + replica_id = math_ops.cast(replica_id, dtypes.uint64) + # Conceptually: key = hash(key, replica_id) + key = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2( + shape=[1], key=key, counter=replica_id, dtype=dtypes.uint64, + alg=self.algorithm) + return key + + def _prepare_key_counter(self, shape): + delta = math_ops.reduce_prod(shape) + counter_key = self.skip(delta) + counter_size = _get_counter_size(self.algorithm) + counter = array_ops.bitcast(counter_key[:counter_size], dtypes.uint64) + key = array_ops.bitcast(counter_key[counter_size:counter_size + 1], + dtypes.uint64) + key = self._preprocess_key(key) + return key, counter + + # The following functions return a tensor and as a side effect update + # self._state_var. + def normal(self, shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, + name=None): + """Outputs random values from a normal distribution. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output + tensor. + mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal + distribution. + stddev: A 0-D Tensor or Python value of type `dtype`. The standard + deviation of the normal distribution. + dtype: The type of the output. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random normal values. + """ + with ops.name_scope(name, "stateful_normal", [shape, mean, stddev]) as name: + shape = _shape_tensor(shape) + mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + rnd = self._standard_normal(shape, dtype=dtype) + return math_ops.add(rnd * stddev, mean, name=name) + + def _truncated_normal(self, shape, dtype): + key, counter = self._prepare_key_counter(shape) + return gen_stateless_random_ops_v2.stateless_truncated_normal_v2( + shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm) + + def truncated_normal(self, shape, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + name=None): + """Outputs random values from a truncated normal distribution. + + The generated values follow a normal distribution with specified mean and + standard deviation, except that values whose magnitude is more than + 2 standard deviations from the mean are dropped and re-picked. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output + tensor. + mean: A 0-D Tensor or Python value of type `dtype`. The mean of the + truncated normal distribution. + stddev: A 0-D Tensor or Python value of type `dtype`. The standard + deviation of the normal distribution, before truncation. + dtype: The type of the output. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random truncated normal + values. + """ + with ops.name_scope( + name, "truncated_normal", [shape, mean, stddev]) as name: + shape_tensor = _shape_tensor(shape) + mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + rnd = self._truncated_normal(shape_tensor, dtype=dtype) + mul = rnd * stddev_tensor + return math_ops.add(mul, mean_tensor, name=name) + + def _uniform(self, shape, dtype): + key, counter = self._prepare_key_counter(shape) + return gen_stateless_random_ops_v2.stateless_random_uniform_v2( + shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm) + + def _uniform_full_int(self, shape, dtype, name=None): + key, counter = self._prepare_key_counter(shape) + return gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2( + shape=shape, + key=key, + counter=counter, + dtype=dtype, + alg=self.algorithm, + name=name) + + def uniform(self, shape, minval=0, maxval=None, + dtype=dtypes.float32, name=None): + """Outputs random values from a uniform distribution. + + The generated values follow a uniform distribution in the range + `[minval, maxval)`. The lower bound `minval` is included in the range, while + the upper bound `maxval` is excluded. (For float numbers especially + low-precision types like bfloat16, because of + rounding, the result may sometimes include `maxval`.) + + For floats, the default range is `[0, 1)`. For ints, at least `maxval` must + be specified explicitly. + + In the integer case, the random integers are slightly biased unless + `maxval - minval` is an exact power of two. The bias is small for values of + `maxval - minval` significantly smaller than the range of the output (either + `2**32` or `2**64`). + + For full-range random integers, pass `minval=None` and `maxval=None` with an + integer `dtype` (for integer dtypes, `minval` and `maxval` must be both + `None` or both not `None`). + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output + tensor. + minval: A Tensor or Python value of type `dtype`, broadcastable with + `shape` (for integer types, broadcasting is not supported, so it needs + to be a scalar). The lower bound (included) on the range of random + values to generate. Pass `None` for full-range integers. Defaults to 0. + maxval: A Tensor or Python value of type `dtype`, broadcastable with + `shape` (for integer types, broadcasting is not supported, so it needs + to be a scalar). The upper bound (excluded) on the range of random + values to generate. Pass `None` for full-range integers. Defaults to 1 + if `dtype` is floating point. + dtype: The type of the output. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random uniform values. + + Raises: + ValueError: If `dtype` is integral and `maxval` is not specified. + """ + dtype = dtypes.as_dtype(dtype) + if dtype.is_integer: + if (minval is None) != (maxval is None): + raise ValueError("For integer dtype {}, minval and maxval must be both " + "`None` or both non-`None`; got minval={} and " + "maxval={}".format(dtype, minval, maxval)) + elif maxval is None: + maxval = 1 + with ops.name_scope(name, "stateful_uniform", + [shape, minval, maxval]) as name: + shape = _shape_tensor(shape) + if dtype.is_integer and minval is None: + return self._uniform_full_int(shape=shape, dtype=dtype, name=name) + minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") + maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") + if dtype.is_integer: + key, counter = self._prepare_key_counter(shape) + return gen_stateless_random_ops_v2.stateless_random_uniform_int_v2( + shape=shape, + key=key, + counter=counter, + minval=minval, + maxval=maxval, + alg=self.algorithm, + name=name) + else: + rnd = self._uniform(shape=shape, dtype=dtype) + return math_ops.add(rnd * (maxval - minval), minval, name=name) + + def uniform_full_int(self, shape, dtype=dtypes.uint64, name=None): + """Uniform distribution on an integer type's entire range. + + This method is the same as setting `minval` and `maxval` to `None` in the + `uniform` method. + + Args: + shape: the shape of the output. + dtype: (optional) the integer type, default to uint64. + name: (optional) the name of the node. + + Returns: + A tensor of random numbers of the required shape. + """ + dtype = dtypes.as_dtype(dtype) + with ops.name_scope(name, "stateful_uniform_full_int", + [shape]) as name: + shape = _shape_tensor(shape) + return self._uniform_full_int(shape=shape, dtype=dtype, name=name) + + def binomial(self, shape, counts, probs, dtype=dtypes.int32, name=None): + """Outputs random values from a binomial distribution. + + The generated values follow a binomial distribution with specified count and + probability of success parameters. + + Example: + + ```python + counts = [10., 20.] + # Probability of success. + probs = [0.8] + + rng = tf.random.Generator.from_seed(seed=234) + binomial_samples = rng.binomial(shape=[2], counts=counts, probs=probs) + + + counts = ... # Shape [3, 1, 2] + probs = ... # Shape [1, 4, 2] + shape = [3, 4, 3, 4, 2] + rng = tf.random.Generator.from_seed(seed=1717) + # Sample shape will be [3, 4, 3, 4, 2] + binomial_samples = rng.binomial(shape=shape, counts=counts, probs=probs) + ``` + + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output + tensor. + counts: Tensor. The counts of the binomial distribution. Must be + broadcastable with `probs`, and broadcastable with the rightmost + dimensions of `shape`. + probs: Tensor. The probability of success for the + binomial distribution. Must be broadcastable with `counts` and + broadcastable with the rightmost dimensions of `shape`. + dtype: The type of the output. Default: tf.int32 + name: A name for the operation (optional). + + Returns: + samples: A Tensor of the specified shape filled with random binomial + values. For each i, each samples[i, ...] is an independent draw from + the binomial distribution on counts[i] trials with probability of + success probs[i]. + """ + dtype = dtypes.as_dtype(dtype) + with ops.name_scope(name, "binomial", [shape, counts, probs]) as name: + counts = ops.convert_to_tensor(counts, name="counts") + probs = ops.convert_to_tensor(probs, name="probs") + shape_tensor = _shape_tensor(shape) + return gen_stateful_random_ops.stateful_random_binomial( + self.state.handle, + self.algorithm, + shape=shape_tensor, + counts=counts, + probs=probs, + dtype=dtype, + name=name) + + # TODO(wangpeng): implement other distributions + + def _make_int64_keys(self, shape=()): + # New independent keys are generated via + # `new_key[i] = hash(old_key, counter+i)`, which is exactly what + # `uniform_full_int(dtype=int64)` does for PhiloxRandom_64_128_128 and + # ThreeFry_64_64_64. + return self.uniform_full_int(shape=shape, dtype=dtypes.int64) + + def make_seeds(self, count=1): + """Generates seeds for stateless random ops. + + For example: + + ```python + seeds = get_global_generator().make_seeds(count=10) + for i in range(10): + seed = seeds[:, i] + numbers = stateless_random_normal(shape=[2, 3], seed=seed) + ... + ``` + + Args: + count: the number of seed pairs (note that stateless random ops need a + pair of seeds to invoke). + + Returns: + A tensor of shape [2, count] and dtype int64. + """ + alg = self.algorithm + if alg in (a.value for a in random_ops_util.Algorithm): + keys = self._make_int64_keys(shape=[count]) + # The two seeds for stateless random ops don't have individual semantics + # and are scrambled together, so setting one to zero is fine. + zeros = array_ops.zeros_like(keys) + return array_ops_stack.stack([keys, zeros]) + else: + raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg)) + + def split(self, count=1): + """Returns a list of independent `Generator` objects. + + Two generators are independent of each other in the sense that the + random-number streams they generate don't have statistically detectable + correlations. The new generators are also independent of the old one. + The old generator's state will be changed (like other random-number + generating methods), so two calls of `split` will return different + new generators. + + For example: + + ```python + gens = get_global_generator().split(count=10) + for gen in gens: + numbers = gen.normal(shape=[2, 3]) + # ... + gens2 = get_global_generator().split(count=10) + # gens2 will be different from gens + ``` + + The new generators will be put on the current device (possible different + from the old generator's), for example: + + ```python + with tf.device("/device:CPU:0"): + gen = Generator(seed=1234) # gen is on CPU + with tf.device("/device:GPU:0"): + gens = gen.split(count=10) # gens are on GPU + ``` + + Args: + count: the number of generators to return. + + Returns: + A list (length `count`) of `Generator` objects independent of each other. + The new generators have the same RNG algorithm as the old one. + """ + def _key_to_state(alg, key): + # Padding with zeros on the left. The zeros will be the counter. + return [0] * (_get_state_size(alg) - 1) + [key] + + alg = self.algorithm + if alg in (a.value for a in random_ops_util.Algorithm): + keys = self._make_int64_keys(shape=[count]) + return [Generator(state=_key_to_state(alg, key), alg=alg) + for key in array_ops_stack.unstack(keys, num=count)] + else: + raise ValueError(stateless_random_ops.unsupported_alg_error_msg(alg)) + + +# It's not safe to create TF ops before `init_google` is called, so this is +# initialized to None and get a value the first time `get_global_generator` is +# called. +global_generator = None + + +@tf_export("random.get_global_generator", + "random.experimental.get_global_generator") +def get_global_generator(): + """Retrieves the global generator. + + This function will create the global generator the first time it is called, + and the generator will be placed at the default device at that time, so one + needs to be careful when this function is first called. Using a generator + placed on a less-ideal device will incur performance regression. + + Returns: + The global `tf.random.Generator` object. + """ + global global_generator + if global_generator is None: + if config.is_op_determinism_enabled(): + raise RuntimeError('"get_global_generator" cannot be called if ' # pylint: disable=g-doc-exception + "determinism is enabled, unless " + '"set_global_generator" has already been called. ' + 'Please call "set_global_generator" first.') + with ops.init_scope(): + global_generator = Generator.from_non_deterministic_state() + return global_generator + + +@tf_export("random.set_global_generator", + "random.experimental.set_global_generator") +def set_global_generator(generator): + """Replaces the global generator with another `Generator` object. + + This function replaces the global generator with the provided `generator` + object. + A random number generator utilizes a `tf.Variable` object to store its state. + The user shall be aware of caveats how `set_global_generator` interacts with + `tf.function`: + + - tf.function puts restrictions on Variable creation thus one cannot freely + create a new random generator instance inside `tf.function`. + To call `set_global_generator` inside `tf.function`, the generator instance + must have already been created eagerly. + - tf.function captures the Variable during trace-compilation, thus a compiled + f.function will not be affected `set_global_generator` as demonstrated by + random_test.py/RandomTest.testResetGlobalGeneratorBadWithDefun . + + For most use cases, avoid calling `set_global_generator` after program + initialization, and prefer to reset the state of the existing global generator + instead, such as, + + >>> rng = tf.random.get_global_generator() + >>> rng.reset_from_seed(30) + + + Args: + generator: the new `Generator` object. + """ + global global_generator + global_generator = generator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateless_random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateless_random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ddde1e25d66f82a4fb8153459dbb86b1b3b76f92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/stateless_random_ops.py @@ -0,0 +1,921 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stateless random ops which take seed as a tensor input.""" + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_random_index_shuffle_ops +from tensorflow.python.ops import gen_stateless_random_ops +from tensorflow.python.ops import gen_stateless_random_ops_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops_util +from tensorflow.python.ops import shape_util +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +ops.NotDifferentiable("StatelessMultinomial") +ops.NotDifferentiable("StatelessRandomBinomial") +ops.NotDifferentiable("StatelessRandomNormal") +ops.NotDifferentiable("StatelessRandomPoisson") +ops.NotDifferentiable("StatelessRandomUniform") +ops.NotDifferentiable("StatelessRandomUniformInt") +ops.NotDifferentiable("StatelessRandomUniformFullInt") +ops.NotDifferentiable("StatelessTruncatedNormal") +ops.NotDifferentiable("StatelessRandomNormalV2") +ops.NotDifferentiable("StatelessRandomUniformV2") +ops.NotDifferentiable("StatelessRandomUniformIntV2") +ops.NotDifferentiable("StatelessRandomUniformFullIntV2") +ops.NotDifferentiable("StatelessTruncatedNormalV2") +ops.NotDifferentiable("StatelessRandomShuffle") +ops.NotDifferentiable("RandomIndexShuffle") + + +@tf_export("random.split", "random.experimental.stateless_split") +@dispatch.add_dispatch_support +def split(seed, num=2, alg="auto_select"): + """Splits an RNG seed into `num` new seeds by adding a leading axis. + + Example: + + >>> seed = [1, 2] + >>> new_seeds = tf.random.split(seed, num=3) + >>> print(new_seeds) + tf.Tensor( + [[1105988140 1738052849] + [-335576002 370444179] + [ 10670227 -246211131]], shape=(3, 2), dtype=int32) + >>> tf.random.stateless_normal(shape=[3], seed=new_seeds[0, :]) + + + Args: + seed: an RNG seed (a tensor with shape [2] and dtype `int32` or `int64`). + (When using XLA, only `int32` is allowed.) + num: optional, a positive integer or scalar tensor indicating the number of + seeds to produce (default 2). + alg: The RNG algorithm used to generate the random numbers. See + `tf.random.stateless_uniform` for a detailed explanation. + + Returns: + A tensor with shape [num, 2] representing `num` new seeds. It will have the + same dtype as `seed` (if `seed` doesn't have an explict dtype, the dtype + will be determined by `tf.convert_to_tensor`). + """ + seed = ops.convert_to_tensor(seed) + return stateless_random_uniform( + shape=[num, 2], + seed=seed, + dtype=seed.dtype, + minval=None, + maxval=None, + alg=alg, + ) + + +@tf_export("random.fold_in", "random.experimental.stateless_fold_in") +@dispatch.add_dispatch_support +def fold_in(seed, data, alg="auto_select"): + """Folds in data to an RNG seed to form a new RNG seed. + + For example, in a distributed-training setting, suppose we have a master seed + and a replica ID. We want to fold the replica ID into the master seed to + form a "replica seed" to be used by that replica later on, so that different + replicas will generate different random numbers but the reproducibility of the + whole system can still be controlled by the master seed: + + >>> master_seed = [1, 2] + >>> replica_id = 3 + >>> replica_seed = tf.random.experimental.stateless_fold_in( + ... master_seed, replica_id) + >>> print(replica_seed) + tf.Tensor([1105988140 3], shape=(2,), dtype=int32) + >>> tf.random.stateless_normal(shape=[3], seed=replica_seed) + + + Args: + seed: an RNG seed (a tensor with shape [2] and dtype `int32` or `int64`). + (When using XLA, only `int32` is allowed.) + data: an `int32` or `int64` scalar representing data to be folded in to the + seed. + alg: The RNG algorithm used to generate the random numbers. See + `tf.random.stateless_uniform` for a detailed explanation. + + Returns: + A new RNG seed that is a deterministic function of the inputs and is + statistically safe for producing a stream of new pseudo-random values. It + will have the same dtype as `data` (if `data` doesn't have an explict dtype, + the dtype will be determined by `tf.convert_to_tensor`). + """ + data = ops.convert_to_tensor(data) + seed1 = stateless_random_uniform( + shape=[], seed=seed, dtype=data.dtype, minval=None, maxval=None, alg=alg + ) + return array_ops_stack.stack([seed1, data]) + + +@tf_export("random.experimental.index_shuffle") +@dispatch.add_dispatch_support +def index_shuffle(index, seed, max_index): + """Outputs the position of `index` in a permutation of `[0, ..., max_index]`. + + For each possible `seed` and `max_index` there is one pseudorandom + permutation of the sequence `S=[0, ..., max_index]`. Instead of + materializing the full array we can compute the new position of any + integer `i` (`0 <= i <= max_index`) in `S`. This can be useful for + very large `max_index`s by avoiding allocating large chunks of + memory. + + In the simplest case, `index` and `max_index` are scalars, and + `seed` is a length-2 vector (as typical for stateless RNGs). But + you can add a leading batch dimension to all of them. If some of + them don't have the batch dimension while others do, `index_shuffle` + will add a batch dimension to the former by broadcasting. + + The input `index` and output can be used as indices to shuffle a + vector. For example: + + >>> vector = tf.constant(['e0', 'e1', 'e2', 'e3']) + >>> indices = tf.random.experimental.index_shuffle( + ... index=tf.range(4), seed=[5, 9], max_index=3) + >>> print(indices) + tf.Tensor([2 0 1 3], shape=(4,), dtype=int32) + >>> shuffled_vector = tf.gather(vector, indices) + >>> print(shuffled_vector) + tf.Tensor([b'e2' b'e0' b'e1' b'e3'], shape=(4,), dtype=string) + + More usefully, it can be used in a streaming (aka online) scenario such as + `tf.data`, where each element of `vector` is processed individually and the + whole `vector` is never materialized in memory. + + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.map( + ... lambda idx: tf.random.experimental.index_shuffle(idx, [5, 8], 9)) + >>> print(list(dataset.as_numpy_iterator())) + [3, 8, 0, 1, 2, 7, 6, 9, 4, 5] + + This operation is stateless (like the `tf.random.stateless_*` + functions), meaning the output is fully determined by the `seed` + (other inputs being equal). Each `seed` choice corresponds to one + permutation, so when calling this function multiple times for the + same shuffling, please make sure to use the same `seed`. For + example: + + >>> seed = [5, 9] + >>> idx0 = tf.random.experimental.index_shuffle(0, seed, 3) + >>> idx1 = tf.random.experimental.index_shuffle(1, seed, 3) + >>> idx2 = tf.random.experimental.index_shuffle(2, seed, 3) + >>> idx3 = tf.random.experimental.index_shuffle(3, seed, 3) + >>> shuffled_vector = tf.gather(vector, [idx0, idx1, idx2, idx3]) + >>> print(shuffled_vector) + tf.Tensor([b'e2' b'e0' b'e1' b'e3'], shape=(4,), dtype=string) + + Args: + index: An integer scalar tensor or vector with values in `[0, max_index]`. + It can be seen as either a value `v` in the sequence `S=[0, ..., + max_index]` to be permutated, or as an index of an element `e` in a + shuffled vector. + seed: A tensor of shape [2] or [n, 2] with dtype `int32`, `uint32`, `int64` + or `uint64`. The RNG seed. If the rank is unknown during graph-building + time it must be 1 at runtime. + max_index: A non-negative tensor with the same shape and dtype as `index`. + The upper bound (inclusive). + + Returns: + If all inputs were scalar (shape [2] for `seed`), the output will + be a scalar with the same dtype as `index`. The output can be seen + as the new position of `v` in `S`, or as the index of `e` in the + vector before shuffling. If one or multiple inputs were vectors + (shape [n, 2] for `seed`), then the output will be a vector of the + same size which each element shuffled independently. Scalar values + are broadcasted in this case. + """ + # We expect users to pass a seed with shape [2] to be consistent with other + # stateless_* ops, but the raw op expects shape [3]. + seed = ops.convert_to_tensor(seed) + # Pad the first dimension with an arbitrary number since our raw op expects + # shape [3]. + if seed.shape.rank is None: + paddings = [[1, 0]] + else: + paddings = [[1, 0]] + (seed.shape.rank - 1) * [[0, 0]] + seed = array_ops.pad(seed, paddings, constant_values=498247692) + return gen_random_index_shuffle_ops.random_index_shuffle( + index, seed=seed, max_index=max_index, rounds=4 + ) + + +@tf_export("random.experimental.stateless_shuffle") +@dispatch.add_dispatch_support +def stateless_shuffle(value, seed, alg="auto_select", name=None): + """Randomly and deterministically shuffles a tensor along its first dimension. + + The tensor is shuffled along dimension 0, such that each `value[j]` is mapped + to one and only one `output[i]`. For example, a mapping that might occur for a + 3x2 tensor is: + + ```python + [[1, 2], [[5, 6], + [3, 4], ==> [1, 2], + [5, 6]] [3, 4]] + ``` + + >>> v = tf.constant([[1, 2], [3, 4], [5, 6]]) + >>> shuffled = tf.random.experimental.stateless_shuffle(v, seed=[8, 9]) + >>> print(shuffled) + tf.Tensor( + [[5 6] + [1 2] + [3 4]], shape=(3, 2), dtype=int32) + + This is a stateless version of `tf.random.shuffle`: if run twice with the + same `value` and `seed`, it will produce the same result. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + Args: + value: A Tensor to be shuffled. + seed: A shape [2] Tensor. The seed to the random number generator. Must have + dtype `int32` or `int64`. + alg: The RNG algorithm used to generate the random numbers. See + `tf.random.stateless_uniform` for a detailed explanation. + name: A name for the operation. + + Returns: + A tensor of same shape and type as `value`, shuffled along its first + dimension. + """ + with ops.name_scope(name, "stateless_shuffle", [value, seed]) as name: + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + return gen_stateless_random_ops_v2.stateless_shuffle( + value, key=key, counter=counter, alg=alg + ) + + +@tf_export("random.stateless_uniform") +@dispatch.add_dispatch_support +def stateless_random_uniform( + shape, + seed, + minval=0, + maxval=None, + dtype=dtypes.float32, + name=None, + alg="auto_select", +): + """Outputs deterministic pseudorandom values from a uniform distribution. + + This is a stateless version of `tf.random.uniform`: if run twice with the + same seeds and shapes, it will produce the same pseudorandom numbers. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + The generated values follow a uniform distribution in the range + `[minval, maxval)`. The lower bound `minval` is included in the range, while + the upper bound `maxval` is excluded. + + For floats, the default range is `[0, 1)`. For ints, at least `maxval` must + be specified explicitly. + + In the integer case, the random integers are slightly biased unless + `maxval - minval` is an exact power of two. The bias is small for values of + `maxval - minval` significantly smaller than the range of the output (either + `2**32` or `2**64`). + + For full-range (i.e. inclusive of both max and min) random integers, pass + `minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype + either both `minval` and `maxval` must be `None` or neither may be `None`. For + example: + ```python + ints = tf.random.stateless_uniform( + [10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32) + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + minval: A Tensor or Python value of type `dtype`, broadcastable with `shape` + (for integer types, broadcasting is not supported, so it needs to be a + scalar). The lower bound on the range of random values to generate. Pass + `None` for full-range integers. Defaults to 0. + maxval: A Tensor or Python value of type `dtype`, broadcastable with `shape` + (for integer types, broadcasting is not supported, so it needs to be a + scalar). The upper bound on the range of random values to generate. + Defaults to 1 if `dtype` is floating point. Pass `None` for full-range + integers. + dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`, + `int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both + `None`), `uint32` and `uint64` may be used. Defaults to `float32`. + name: A name for the operation (optional). + alg: The RNG algorithm used to generate the random numbers. Valid choices + are `"philox"` for [the Philox + algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf), + `"threefry"` for [the ThreeFry + algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf), + and `"auto_select"` (default) for the system to automatically select an + algorithm based the device type. Values of `tf.random.Algorithm` can also + be used. Note that with `"auto_select"`, the outputs of this function may + change when it is running on a different device. + + Returns: + A tensor of the specified shape filled with random uniform values. + + Raises: + ValueError: If `dtype` is integral and only one of `minval` or `maxval` is + specified. + """ + dtype = dtypes.as_dtype(dtype) + accepted_dtypes = ( + dtypes.float16, + dtypes.bfloat16, + dtypes.float32, + dtypes.float64, + dtypes.int32, + dtypes.int64, + dtypes.uint32, + dtypes.uint64, + ) + if dtype not in accepted_dtypes: + raise ValueError( + f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are " + f"{accepted_dtypes}." + ) + if dtype.is_integer: + if (minval is None) != (maxval is None): + raise ValueError( + f"For integer `dtype` argument {dtype}, argument `minval` and " + f"`maxval` must be both None or not None. Got `minval`={minval} and " + f"`maxval`={maxval}." + ) + if minval is not None and dtype in (dtypes.uint32, dtypes.uint64): + raise ValueError( + f"Argument `dtype` got invalid value {dtype} when argument `minval` " + "is not None. Please don't use unsigned integers in this case." + ) + elif maxval is None: + maxval = 1 + with ops.name_scope( + name, "stateless_random_uniform", [shape, seed, minval, maxval] + ) as name: + shape = shape_util.shape_tensor(shape) + if dtype.is_integer and minval is None: + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + result = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2( + shape, key=key, counter=counter, dtype=dtype, alg=alg, name=name + ) + else: + minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") + maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") + if dtype.is_integer: + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + result = gen_stateless_random_ops_v2.stateless_random_uniform_int_v2( + shape, + key=key, + counter=counter, + minval=minval, + maxval=maxval, + alg=alg, + name=name, + ) + else: + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + rnd = gen_stateless_random_ops_v2.stateless_random_uniform_v2( + shape, key=key, counter=counter, dtype=dtype, alg=alg + ) + result = math_ops.add(rnd * (maxval - minval), minval, name=name) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("random.stateless_binomial") +@dispatch.add_dispatch_support +def stateless_random_binomial( + shape, seed, counts, probs, output_dtype=dtypes.int32, name=None +): + """Outputs deterministic pseudorandom values from a binomial distribution. + + The generated values follow a binomial distribution with specified count and + probability of success parameters. + + This is a stateless version of `tf.random.Generator.binomial`: if run twice + with the same seeds and shapes, it will produce the same pseudorandom numbers. + The output is consistent across multiple runs on the same hardware (and + between CPU and GPU), but may change between versions of TensorFlow or on + non-CPU/GPU hardware. + + Example: + + ```python + counts = [10., 20.] + # Probability of success. + probs = [0.8] + + binomial_samples = tf.random.stateless_binomial( + shape=[2], seed=[123, 456], counts=counts, probs=probs) + + counts = ... # Shape [3, 1, 2] + probs = ... # Shape [1, 4, 2] + shape = [3, 4, 3, 4, 2] + # Sample shape will be [3, 4, 3, 4, 2] + binomial_samples = tf.random.stateless_binomial( + shape=shape, seed=[123, 456], counts=counts, probs=probs) + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + counts: Tensor. The counts of the binomial distribution. Must be + broadcastable with `probs`, and broadcastable with the rightmost + dimensions of `shape`. + probs: Tensor. The probability of success for the binomial distribution. + Must be broadcastable with `counts` and broadcastable with the rightmost + dimensions of `shape`. + output_dtype: The type of the output. Default: tf.int32 + name: A name for the operation (optional). + + Returns: + samples: A Tensor of the specified shape filled with random binomial + values. For each i, each samples[..., i] is an independent draw from + the binomial distribution on counts[i] trials with probability of + success probs[i]. + """ + with ops.name_scope( + name, "stateless_random_binomial", [shape, seed, counts, probs] + ) as name: + shape = shape_util.shape_tensor(shape) + probs = ops.convert_to_tensor( + probs, dtype_hint=dtypes.float32, name="probs" + ) + counts = ops.convert_to_tensor( + counts, dtype_hint=probs.dtype, name="counts" + ) + result = gen_stateless_random_ops.stateless_random_binomial( + shape=shape, seed=seed, counts=counts, probs=probs, dtype=output_dtype + ) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("random.stateless_gamma") +@dispatch.add_dispatch_support +def stateless_random_gamma( + shape, seed, alpha, beta=None, dtype=dtypes.float32, name=None +): + """Outputs deterministic pseudorandom values from a gamma distribution. + + The generated values follow a gamma distribution with specified concentration + (`alpha`) and inverse scale (`beta`) parameters. + + This is a stateless version of `tf.random.gamma`: if run twice with the same + seeds and shapes, it will produce the same pseudorandom numbers. The output is + consistent across multiple runs on the same hardware (and between CPU and + GPU), + but may change between versions of TensorFlow or on non-CPU/GPU hardware. + + A slight difference exists in the interpretation of the `shape` parameter + between `stateless_gamma` and `gamma`: in `gamma`, the `shape` is always + prepended to the shape of the broadcast of `alpha` with `beta`; whereas in + `stateless_gamma` the `shape` parameter must always encompass the shapes of + each of `alpha` and `beta` (which must broadcast together to match the + trailing dimensions of `shape`). + + Note: Because internal calculations are done using `float64` and casting has + `floor` semantics, we must manually map zero outcomes to the smallest + possible positive floating-point value, i.e., `np.finfo(dtype).tiny`. This + means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise + should. This bias can only happen for small values of `alpha`, i.e., + `alpha << 1` or large values of `beta`, i.e., `beta >> 1`. + + The samples are differentiable w.r.t. alpha and beta. + The derivatives are computed using the approach described in + (Figurnov et al., 2018). + + Example: + + ```python + samples = tf.random.stateless_gamma([10, 2], seed=[12, 34], alpha=[0.5, 1.5]) + # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents + # the samples drawn from each distribution + + samples = tf.random.stateless_gamma([7, 5, 2], seed=[12, 34], alpha=[.5, 1.5]) + # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] + # represents the 7x5 samples drawn from each of the two distributions + + alpha = tf.constant([[1.], [3.], [5.]]) + beta = tf.constant([[3., 4.]]) + samples = tf.random.stateless_gamma( + [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta) + # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions. + + with tf.GradientTape() as tape: + tape.watch([alpha, beta]) + loss = tf.reduce_mean(tf.square(tf.random.stateless_gamma( + [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta))) + dloss_dalpha, dloss_dbeta = tape.gradient(loss, [alpha, beta]) + # unbiased stochastic derivatives of the loss function + alpha.shape == dloss_dalpha.shape # True + beta.shape == dloss_dbeta.shape # True + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + alpha: Tensor. The concentration parameter of the gamma distribution. Must + be broadcastable with `beta`, and broadcastable with the rightmost + dimensions of `shape`. + beta: Tensor. The inverse scale parameter of the gamma distribution. Must be + broadcastable with `alpha` and broadcastable with the rightmost dimensions + of `shape`. + dtype: Floating point dtype of `alpha`, `beta`, and the output. + name: A name for the operation (optional). + + Returns: + samples: A Tensor of the specified shape filled with random gamma values. + For each i, each `samples[..., i] is an independent draw from the gamma + distribution with concentration alpha[i] and scale beta[i]. + """ + with ops.name_scope( + name, "stateless_random_gamma", [shape, seed, alpha, beta] + ) as name: + shape = shape_util.shape_tensor(shape) + alpha = ops.convert_to_tensor(alpha, dtype=dtype, name="alpha") + beta = ops.convert_to_tensor( + beta if beta is not None else 1, name="beta", dtype=dtype + ) + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(alpha), array_ops.shape(beta) + ) + alpha_broadcast = array_ops.broadcast_to(alpha, broadcast_shape) + alg = "auto_select" + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + rnd = gen_stateless_random_ops_v2.stateless_random_gamma_v3( + shape, key=key, counter=counter, alg=alg, alpha=alpha_broadcast + ) + result = math_ops.maximum( + np.finfo(alpha.dtype.as_numpy_dtype).tiny, rnd / beta + ) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("random.stateless_poisson") +@dispatch.add_dispatch_support +def stateless_random_poisson(shape, seed, lam, dtype=dtypes.int32, name=None): + """Outputs deterministic pseudorandom values from a Poisson distribution. + + The generated values follow a Poisson distribution with specified rate + parameter. + + This is a stateless version of `tf.random.poisson`: if run twice with the same + seeds and shapes, it will produce the same pseudorandom numbers. The output is + consistent across multiple runs on the same hardware, but may change between + versions of TensorFlow or on non-CPU/GPU hardware. + + A slight difference exists in the interpretation of the `shape` parameter + between `stateless_poisson` and `poisson`: in `poisson`, the `shape` is always + prepended to the shape of `lam`; whereas in `stateless_poisson` the shape of + `lam` must match the trailing dimensions of `shape`. + + Example: + + ```python + samples = tf.random.stateless_poisson([10, 2], seed=[12, 34], lam=[5, 15]) + # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents + # the samples drawn from each distribution + + samples = tf.random.stateless_poisson([7, 5, 2], seed=[12, 34], lam=[5, 15]) + # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] + # represents the 7x5 samples drawn from each of the two distributions + + rate = tf.constant([[1.], [3.], [5.]]) + samples = tf.random.stateless_poisson([30, 3, 1], seed=[12, 34], lam=rate) + # samples has shape [30, 3, 1], with 30 samples each of 3x1 distributions. + ``` + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + lam: Tensor. The rate parameter "lambda" of the Poisson distribution. Shape + must match the rightmost dimensions of `shape`. + dtype: Dtype of the samples (int or float dtypes are permissible, as samples + are discrete). Default: int32. + name: A name for the operation (optional). + + Returns: + samples: A Tensor of the specified shape filled with random Poisson values. + For each i, each `samples[..., i]` is an independent draw from the Poisson + distribution with rate `lam[i]`. + """ + with ops.name_scope( + name, "stateless_random_poisson", [shape, seed, lam] + ) as name: + shape = shape_util.shape_tensor(shape) + result = gen_stateless_random_ops.stateless_random_poisson( + shape, seed=seed, lam=lam, dtype=dtype + ) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("random.stateless_normal") +@dispatch.add_dispatch_support +def stateless_random_normal( + shape, + seed, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + name=None, + alg="auto_select", +): + """Outputs deterministic pseudorandom values from a normal distribution. + + This is a stateless version of `tf.random.normal`: if run twice with the + same seeds and shapes, it will produce the same pseudorandom numbers. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal + distribution. + stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation + of the normal distribution. + dtype: The float type of the output: `float16`, `bfloat16`, `float32`, + `float64`. Defaults to `float32`. + name: A name for the operation (optional). + alg: The RNG algorithm used to generate the random numbers. See + `tf.random.stateless_uniform` for a detailed explanation. + + Returns: + A tensor of the specified shape filled with random normal values. + """ + with ops.name_scope( + name, "stateless_random_normal", [shape, seed, mean, stddev] + ) as name: + shape = shape_util.shape_tensor(shape) + mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + rnd = gen_stateless_random_ops_v2.stateless_random_normal_v2( + shape, key=key, counter=counter, dtype=dtype, alg=alg + ) + result = math_ops.add(rnd * stddev, mean, name=name) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export("random.stateless_truncated_normal") +@dispatch.add_dispatch_support +def stateless_truncated_normal( + shape, + seed, + mean=0.0, + stddev=1.0, + dtype=dtypes.float32, + name=None, + alg="auto_select", +): + """Outputs deterministic pseudorandom values, truncated normally distributed. + + This is a stateless version of `tf.random.truncated_normal`: if run twice with + the same seeds and shapes, it will produce the same pseudorandom numbers. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + The generated values follow a normal distribution with specified mean and + standard deviation, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + Args: + shape: A 1-D integer Tensor or Python array. The shape of the output tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + mean: A 0-D Tensor or Python value of type `dtype`. The mean of the + truncated normal distribution. + stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation + of the normal distribution, before truncation. + dtype: The type of the output. + name: A name for the operation (optional). + alg: The RNG algorithm used to generate the random numbers. See + `tf.random.stateless_uniform` for a detailed explanation. + + Returns: + A tensor of the specified shape filled with random truncated normal values. + """ + with ops.name_scope( + name, "stateless_truncated_normal", [shape, seed, mean, stddev] + ) as name: + shape = shape_util.shape_tensor(shape) + mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") + stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") + key, counter, alg = random_ops_util.get_key_counter_alg(seed, alg) + rnd = gen_stateless_random_ops_v2.stateless_truncated_normal_v2( + shape, key=key, counter=counter, dtype=dtype, alg=alg + ) + result = math_ops.add(rnd * stddev, mean, name=name) + shape_util.maybe_set_static_shape(result, shape) + return result + + +@tf_export(v1=["random.stateless_multinomial"]) +@dispatch.add_dispatch_support +@deprecation.deprecated( + date=None, instructions="Use `tf.random.stateless_categorical` instead." +) +def stateless_multinomial( + logits, num_samples, seed, output_dtype=dtypes.int64, name=None +): + """Draws deterministic pseudorandom samples from a multinomial distribution. + + This is a stateless version of `tf.random.categorical`: if run twice with the + same seeds and shapes, it will produce the same pseudorandom numbers. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + Example: + + ```python + # samples has shape [1, 5], where each value is either 0 or 1 with equal + # probability. + samples = tf.random.stateless_categorical( + tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17]) + ``` + + Args: + logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, + :]` represents the unnormalized log-probabilities for all classes. + num_samples: 0-D. Number of independent samples to draw for each row slice. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + output_dtype: The integer type of the output: `int32` or `int64`. Defaults + to `int64`. + name: Optional name for the operation. + + Returns: + The drawn samples of shape `[batch_size, num_samples]`. + """ + with ops.name_scope(name, "stateless_multinomial", [logits, seed]): + return stateless_multinomial_categorical_impl( + logits, num_samples, output_dtype, seed + ) + + +@tf_export("random.stateless_categorical") +@dispatch.add_dispatch_support +def stateless_categorical( + logits, num_samples, seed, dtype=dtypes.int64, name=None +): + """Draws deterministic pseudorandom samples from a categorical distribution. + + This is a stateless version of `tf.categorical`: if run twice with the + same seeds and shapes, it will produce the same pseudorandom numbers. The + output is consistent across multiple runs on the same hardware (and between + CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU + hardware. + + + Example: + + ```python + # samples has shape [1, 5], where each value is either 0 or 1 with equal + # probability. + samples = tf.random.stateless_categorical( + tf.math.log([[0.5, 0.5]]), 5, seed=[7, 17]) + ``` + + Args: + logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, + :]` represents the unnormalized log-probabilities for all classes. + num_samples: 0-D. Number of independent samples to draw for each row slice. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + dtype: The integer type of the output: `int32` or `int64`. Defaults to + `int64`. + name: Optional name for the operation. + + Returns: + The drawn samples of shape `[batch_size, num_samples]`. + """ + with ops.name_scope(name, "stateless_categorical", [logits, seed]): + return stateless_multinomial_categorical_impl( + logits, num_samples, dtype, seed + ) + + +def stateless_multinomial_categorical_impl(logits, num_samples, dtype, seed): + """Implementation for stateless multinomial/categorical ops (v1/v2).""" + logits = ops.convert_to_tensor(logits, name="logits") + dtype = dtypes.as_dtype(dtype) if dtype else dtypes.int64 + accepted_dtypes = (dtypes.int32, dtypes.int64) + if dtype not in accepted_dtypes: + raise ValueError( + f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are " + f"{accepted_dtypes}." + ) + return gen_stateless_random_ops.stateless_multinomial( + logits, num_samples, seed, output_dtype=dtype + ) + + +@dispatch.add_dispatch_support +@tf_export("random.stateless_parameterized_truncated_normal") +def stateless_parameterized_truncated_normal( + shape, seed, means=0.0, stddevs=1.0, minvals=-2.0, maxvals=2.0, name=None +): + """Outputs random values from a truncated normal distribution. + + The generated values follow a normal distribution with specified mean and + standard deviation, except that values whose magnitude is more than 2 standard + deviations from the mean are dropped and re-picked. + + + Examples: + + Sample from a Truncated normal, with deferring shape parameters that + broadcast. + + >>> means = 0. + >>> stddevs = tf.math.exp(tf.random.uniform(shape=[2, 3])) + >>> minvals = [-1., -2., -1000.] + >>> maxvals = [[10000.], [1.]] + >>> y = tf.random.stateless_parameterized_truncated_normal( + ... shape=[10, 2, 3], seed=[7, 17], + ... means=means, stddevs=stddevs, minvals=minvals, maxvals=maxvals) + >>> y.shape + TensorShape([10, 2, 3]) + + Args: + shape: A 1-D integer `Tensor` or Python array. The shape of the output + tensor. + seed: A shape [2] Tensor, the seed to the random number generator. Must have + dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) + means: A `Tensor` or Python value of type `dtype`. The mean of the truncated + normal distribution. This must broadcast with `stddevs`, `minvals` and + `maxvals`, and the broadcasted shape must be dominated by `shape`. + stddevs: A `Tensor` or Python value of type `dtype`. The standard deviation + of the truncated normal distribution. This must broadcast with `means`, + `minvals` and `maxvals`, and the broadcasted shape must be dominated by + `shape`. + minvals: A `Tensor` or Python value of type `dtype`. The minimum value of + the truncated normal distribution. This must broadcast with `means`, + `stddevs` and `maxvals`, and the broadcasted shape must be dominated by + `shape`. + maxvals: A `Tensor` or Python value of type `dtype`. The maximum value of + the truncated normal distribution. This must broadcast with `means`, + `stddevs` and `minvals`, and the broadcasted shape must be dominated by + `shape`. + name: A name for the operation (optional). + + Returns: + A tensor of the specified shape filled with random truncated normal values. + """ + with ops.name_scope( + name, + "stateless_parameterized_truncated_normal", + [shape, means, stddevs, minvals, maxvals], + ) as name: + shape_tensor = shape_util.shape_tensor(shape) + means_tensor = ops.convert_to_tensor(means, name="means") + stddevs_tensor = ops.convert_to_tensor(stddevs, name="stddevs") + minvals_tensor = ops.convert_to_tensor(minvals, name="minvals") + maxvals_tensor = ops.convert_to_tensor(maxvals, name="maxvals") + rnd = gen_stateless_random_ops.stateless_parameterized_truncated_normal( + shape_tensor, + seed, + means_tensor, + stddevs_tensor, + minvals_tensor, + maxvals_tensor, + ) + shape_util.maybe_set_static_shape(rnd, shape) + return rnd diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/string_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/string_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3bb68e0c20f2bbae4bd73339aaa256c915d8dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/string_ops.py @@ -0,0 +1,655 @@ +# -*- coding: utf-8 -*- +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations for working with string Tensors. + +API docstring: tensorflow.strings +""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_parsing_ops +from tensorflow.python.ops import gen_string_ops +from tensorflow.python.ops import math_ops + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +# pylint: disable=g-bad-import-order +from tensorflow.python.ops.gen_string_ops import * +from tensorflow.python.util import compat as util_compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export +# pylint: enable=g-bad-import-order +# pylint: enable=wildcard-import + + +# pylint: disable=redefined-builtin +@tf_export("strings.regex_full_match") +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def regex_full_match(input, pattern, name=None): + r"""Match elements of `input` with regex `pattern`. + + Args: + input: string `Tensor`, the source strings to process. + pattern: string or scalar string `Tensor`, regular expression to use, + see more details at https://github.com/google/re2/wiki/Syntax + name: Name of the op. + + Returns: + bool `Tensor` of the same shape as `input` with match results. + """ + if isinstance(pattern, util_compat.bytes_or_text_types): + # When `pattern` is static through the life of the op we can + # use a version which performs the expensive regex compilation once at + # creation time. + return gen_string_ops.static_regex_full_match( + input=input, pattern=pattern, name=name) + return gen_string_ops.regex_full_match( + input=input, pattern=pattern, name=name) + +regex_full_match.__doc__ = gen_string_ops.regex_full_match.__doc__ + + +@tf_export( + "strings.regex_replace", v1=["strings.regex_replace", "regex_replace"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("regex_replace") +def regex_replace(input, pattern, rewrite, replace_global=True, name=None): + r"""Replace elements of `input` matching regex `pattern` with `rewrite`. + + >>> tf.strings.regex_replace("Text with tags.
contains html", + ... "<[^>]+>", " ") + + + Args: + input: string `Tensor`, the source strings to process. + pattern: string or scalar string `Tensor`, regular expression to use, + see more details at https://github.com/google/re2/wiki/Syntax + rewrite: string or scalar string `Tensor`, value to use in match + replacement, supports backslash-escaped digits (\1 to \9) can be to insert + text matching corresponding parenthesized group. + replace_global: `bool`, if `True` replace all non-overlapping matches, + else replace only the first match. + name: A name for the operation (optional). + + Returns: + string `Tensor` of the same shape as `input` with specified replacements. + """ + if (isinstance(pattern, util_compat.bytes_or_text_types) and + isinstance(rewrite, util_compat.bytes_or_text_types)): + # When `pattern` and `rewrite` are static through the life of the op we can + # use a version which performs the expensive regex compilation once at + # creation time. + return gen_string_ops.static_regex_replace( + input=input, pattern=pattern, + rewrite=rewrite, replace_global=replace_global, + name=name) + return gen_string_ops.regex_replace( + input=input, pattern=pattern, + rewrite=rewrite, replace_global=replace_global, + name=name) + + +@tf_export("strings.format") +@dispatch.add_dispatch_support +def string_format(template, inputs, placeholder="{}", summarize=3, name=None): + r"""Formats a string template using a list of tensors. + + Formats a string template using a list of tensors, abbreviating tensors by + only printing the first and last `summarize` elements of each dimension + (recursively). If formatting only one tensor into a template, the tensor does + not have to be wrapped in a list. + + Example: + Formatting a single-tensor template: + + >>> tensor = tf.range(5) + >>> tf.strings.format("tensor: {}, suffix", tensor) + + + Formatting a multi-tensor template: + + >>> tensor_a = tf.range(2) + >>> tensor_b = tf.range(1, 4, 2) + >>> tf.strings.format("a: {}, b: {}, suffix", (tensor_a, tensor_b)) + + + + Args: + template: A string template to format tensor values into. + inputs: A list of `Tensor` objects, or a single Tensor. + The list of tensors to format into the template string. If a solitary + tensor is passed in, the input tensor will automatically be wrapped as a + list. + placeholder: An optional `string`. Defaults to `{}`. + At each placeholder occurring in the template, a subsequent tensor + will be inserted. + summarize: An optional `int`. Defaults to `3`. + When formatting the tensors, show the first and last `summarize` + entries of each tensor dimension (recursively). If set to -1, all + elements of the tensor will be shown. + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. + + Raises: + ValueError: if the number of placeholders does not match the number of + inputs. + """ + # If there is only one tensor to format, we will automatically wrap it in a + # list to simplify the user experience + if tensor_util.is_tf_type(inputs): + inputs = [inputs] + if template.count(placeholder) != len(inputs): + raise ValueError(f"The template expects {template.count(placeholder)} " + f"tensors, but the inputs only has {len(inputs)}. " + "Please ensure the number of placeholders in template " + "matches inputs length.") + + return gen_string_ops.string_format(inputs, + template=template, + placeholder=placeholder, + summarize=summarize, + name=name) + + +# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which +# defines a wrapper for this function. +def string_split(source, sep=None, skip_empty=True, delimiter=None): # pylint: disable=invalid-name + """Split elements of `source` based on `delimiter` into a `SparseTensor`. + + Let N be the size of source (typically N will be the batch size). Split each + element of `source` based on `delimiter` and return a `SparseTensor` + containing the split tokens. Empty tokens are ignored. + + If `sep` is an empty string, each element of the `source` is split + into individual strings, each containing one byte. (This includes splitting + multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is + treated as a set of delimiters with each considered a potential split point. + + For example: + N = 2, source[0] is 'hello world' and source[1] is 'a b c', then the output + will be + + st.indices = [0, 0; + 0, 1; + 1, 0; + 1, 1; + 1, 2] + st.shape = [2, 3] + st.values = ['hello', 'world', 'a', 'b', 'c'] + + Args: + source: `1-D` string `Tensor`, the strings to split. + sep: `0-D` string `Tensor`, the delimiter character, the string should + be length 0 or 1. Default is ' '. + skip_empty: A `bool`. If `True`, skip the empty strings from the result. + delimiter: deprecated alias for `sep`. + + Raises: + ValueError: If delimiter is not a string. + + Returns: + A `SparseTensor` of rank `2`, the strings split according to the delimiter. + The first column of the indices corresponds to the row in `source` and the + second column corresponds to the index of the split component in this row. + """ + delimiter = deprecation.deprecated_argument_lookup( + "sep", sep, "delimiter", delimiter) + + if delimiter is None: + delimiter = " " + delimiter = ops.convert_to_tensor(delimiter, dtype=dtypes.string) + source = ops.convert_to_tensor(source, dtype=dtypes.string) + + indices, values, shape = gen_string_ops.string_split( + source, delimiter=delimiter, skip_empty=skip_empty) + indices.set_shape([None, 2]) + values.set_shape([None]) + shape.set_shape([2]) + return sparse_tensor.SparseTensor(indices, values, shape) + + +# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which +# defines a wrapper for this function. +def string_split_v2(source, sep=None, maxsplit=-1): + """Split elements of `source` based on `sep` into a `SparseTensor`. + + Let N be the size of source (typically N will be the batch size). Split each + element of `source` based on `sep` and return a `SparseTensor` + containing the split tokens. Empty tokens are ignored. + + For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c', + then the output will be + + st.indices = [0, 0; + 0, 1; + 1, 0; + 1, 1; + 1, 2] + st.shape = [2, 3] + st.values = ['hello', 'world', 'a', 'b', 'c'] + + If `sep` is given, consecutive delimiters are not grouped together and are + deemed to delimit empty strings. For example, source of `"1<>2<><>3"` and + sep of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty + string, consecutive whitespace are regarded as a single separator, and the + result will contain no empty strings at the start or end if the string has + leading or trailing whitespace. + + Note that the above mentioned behavior matches python's str.split. + + Args: + source: `1-D` string `Tensor`, the strings to split. + sep: `0-D` string `Tensor`, the delimiter character. + maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result. + + Raises: + ValueError: If sep is not a string. + + Returns: + A `SparseTensor` of rank `2`, the strings split according to the delimiter. + The first column of the indices corresponds to the row in `source` and the + second column corresponds to the index of the split component in this row. + """ + if sep is None: + sep = "" + sep = ops.convert_to_tensor(sep, dtype=dtypes.string) + source = ops.convert_to_tensor(source, dtype=dtypes.string) + + indices, values, shape = gen_string_ops.string_split_v2( + source, sep=sep, maxsplit=maxsplit) + indices.set_shape([None, 2]) + values.set_shape([None]) + shape.set_shape([2]) + return sparse_tensor.SparseTensor(indices, values, shape) + + +def _reduce_join_reduction_dims(x, axis): + """Returns range(rank(x) - 1, 0, -1) if axis is None; or axis otherwise.""" + if axis is not None: + return axis + else: + # Fast path: avoid creating Rank and Range ops if ndims is known. + if x.get_shape().ndims is not None: + return constant_op.constant( + np.arange(x.get_shape().ndims - 1, -1, -1), dtype=dtypes.int32) + + # Otherwise, we rely on Range and Rank to do the right thing at run-time. + return math_ops.range(array_ops.rank(x) - 1, -1, -1) + + +@tf_export(v1=["strings.reduce_join", "reduce_join"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_args(None, + "keep_dims is deprecated, use keepdims instead", + "keep_dims") +@deprecation.deprecated_endpoints("reduce_join") +def reduce_join(inputs, axis=None, # pylint: disable=missing-docstring + keep_dims=None, + separator="", + name=None, + reduction_indices=None, + keepdims=None): + keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims, + "keep_dims", keep_dims) + if keep_dims is None: + keep_dims = False + axis = deprecation.deprecated_argument_lookup("axis", axis, + "reduction_indices", + reduction_indices) + return reduce_join_v2( + inputs=inputs, + axis=axis, + keepdims=keepdims, + separator=separator, + name=name) + + +@tf_export("strings.reduce_join", v1=[]) +@dispatch.add_dispatch_support +def reduce_join_v2( # pylint: disable=missing-docstring + inputs, + axis=None, + keepdims=False, + separator="", + name=None): + """Joins all strings into a single string, or joins along an axis. + + This is the reduction operation for the elementwise `tf.strings.join` op. + + >>> tf.strings.reduce_join([['abc','123'], + ... ['def','456']]).numpy() + b'abc123def456' + >>> tf.strings.reduce_join([['abc','123'], + ... ['def','456']], axis=-1).numpy() + array([b'abc123', b'def456'], dtype=object) + >>> tf.strings.reduce_join([['abc','123'], + ... ['def','456']], + ... axis=-1, + ... separator=" ").numpy() + array([b'abc 123', b'def 456'], dtype=object) + + Args: + inputs: A `tf.string` tensor. + axis: Which axis to join along. The default behavior is to join all + elements, producing a scalar. + keepdims: If true, retains reduced dimensions with length 1. + separator: a string added between each string being joined. + name: A name for the operation (optional). + + Returns: + A `tf.string` tensor. + """ + with ops.name_scope(None, "ReduceJoin", [inputs, axis]): + inputs_t = ops.convert_to_tensor(inputs) + axis = _reduce_join_reduction_dims(inputs_t, axis) + return gen_string_ops.reduce_join( + inputs=inputs_t, + reduction_indices=axis, + keep_dims=keepdims, + separator=separator, + name=name) + +reduce_join.__doc__ = reduce_join_v2.__doc__ + + +# This wrapper provides backwards compatibility for code that predates the +# unit argument and that passed 'name' as a positional argument. +@tf_export(v1=["strings.length"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def string_length(input, name=None, unit="BYTE"): + """Computes the length of each string given in the input tensor. + + >>> strings = tf.constant(['Hello','TensorFlow', '🙂']) + >>> tf.strings.length(strings).numpy() # default counts bytes + array([ 5, 10, 4], dtype=int32) + >>> tf.strings.length(strings, unit="UTF8_CHAR").numpy() + array([ 5, 10, 1], dtype=int32) + + Args: + input: A `Tensor` of type `string`. The strings for which to compute the + length for each element. + name: A name for the operation (optional). + unit: An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to + `"BYTE"`. The unit that is counted to compute string length. One of: + `"BYTE"` (for the number of bytes in each string) or `"UTF8_CHAR"` (for + the number of UTF-8 encoded Unicode code points in each string). Results + are undefined if `unit=UTF8_CHAR` and the `input` strings do not contain + structurally valid UTF-8. + + Returns: + A `Tensor` of type `int32`, containing the length of the input string in + the same element of the input tensor. + """ + return gen_string_ops.string_length(input, unit=unit, name=name) + + +@tf_export("strings.length", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def string_length_v2(input, unit="BYTE", name=None): + return gen_string_ops.string_length(input, unit=unit, name=name) + + +string_length_v2.__doc__ = gen_string_ops.string_length.__doc__ + + +@tf_export(v1=["substr"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +@deprecation.deprecated(None, "Use `tf.strings.substr` instead of `tf.substr`.") +def substr_deprecated(input, pos, len, name=None, unit="BYTE"): + return substr(input, pos, len, name=name, unit=unit) + +substr_deprecated.__doc__ = gen_string_ops.substr.__doc__ + + +@tf_export(v1=["strings.substr"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def substr(input, pos, len, name=None, unit="BYTE"): + return gen_string_ops.substr(input, pos, len, unit=unit, name=name) + +substr.__doc__ = gen_string_ops.substr.__doc__ + + +@tf_export("strings.substr", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def substr_v2(input, pos, len, unit="BYTE", name=None): + return gen_string_ops.substr(input, pos, len, unit=unit, name=name) + +substr_v2.__doc__ = gen_string_ops.substr.__doc__ + + +ops.NotDifferentiable("RegexReplace") +ops.NotDifferentiable("StringToHashBucket") +ops.NotDifferentiable("StringToHashBucketFast") +ops.NotDifferentiable("StringToHashBucketStrong") +ops.NotDifferentiable("ReduceJoin") +ops.NotDifferentiable("StringJoin") +ops.NotDifferentiable("StringSplit") +ops.NotDifferentiable("AsString") +ops.NotDifferentiable("EncodeBase64") +ops.NotDifferentiable("DecodeBase64") + + +@tf_export("strings.to_number", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def string_to_number(input, out_type=dtypes.float32, name=None): + r"""Converts each string in the input Tensor to the specified numeric type. + + (Note that int32 overflow results in an error while float overflow + results in a rounded value.) + + Examples: + + >>> tf.strings.to_number("1.55") + + >>> tf.strings.to_number("3", tf.int32) + + + Args: + input: A `Tensor` of type `string`. + out_type: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, + tf.int64`. Defaults to `tf.float32`. + The numeric type to interpret each string in `string_tensor` as. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + return gen_parsing_ops.string_to_number(input, out_type, name) + + +@tf_export(v1=["strings.to_number", "string_to_number"]) +@dispatch.add_dispatch_support +def string_to_number_v1( + string_tensor=None, + out_type=dtypes.float32, + name=None, + input=None): + string_tensor = deprecation.deprecated_argument_lookup( + "input", input, "string_tensor", string_tensor) + return gen_parsing_ops.string_to_number(string_tensor, out_type, name) + +string_to_number_v1.__doc__ = gen_parsing_ops.string_to_number.__doc__ + + +@tf_export("strings.to_hash_bucket", v1=[]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def string_to_hash_bucket(input, num_buckets, name=None): + # pylint: disable=line-too-long + r"""Converts each string in the input Tensor to its hash mod by a number of buckets. + + The hash function is deterministic on the content of the string within the + process. + + Note that the hash function may change from time to time. + This functionality will be deprecated and it's recommended to use + `tf.strings.to_hash_bucket_fast()` or `tf.strings.to_hash_bucket_strong()`. + + Examples: + + >>> tf.strings.to_hash_bucket(["Hello", "TensorFlow", "2.x"], 3) + + + Args: + input: A `Tensor` of type `string`. + num_buckets: An `int` that is `>= 1`. The number of buckets. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + # pylint: enable=line-too-long + return gen_string_ops.string_to_hash_bucket(input, num_buckets, name) + + +@tf_export(v1=["strings.to_hash_bucket", "string_to_hash_bucket"]) +@dispatch.register_unary_elementwise_api +@dispatch.add_dispatch_support +def string_to_hash_bucket_v1( # pylint: disable=missing-function-docstring + string_tensor=None, + num_buckets=None, + name=None, + input=None): + string_tensor = deprecation.deprecated_argument_lookup( + "input", input, "string_tensor", string_tensor) + return gen_string_ops.string_to_hash_bucket(string_tensor, num_buckets, name) + +string_to_hash_bucket_v1.__doc__ = gen_string_ops.string_to_hash_bucket.__doc__ + + +@tf_export("strings.join", v1=["strings.join", "string_join"]) +@dispatch.add_dispatch_support +@deprecation.deprecated_endpoints("string_join") +def string_join(inputs, separator="", name=None): + """Perform element-wise concatenation of a list of string tensors. + + Given a list of string tensors of same shape, performs element-wise + concatenation of the strings of the same index in all tensors. + + + >>> tf.strings.join(['abc','def']).numpy() + b'abcdef' + >>> tf.strings.join([['abc','123'], + ... ['def','456'], + ... ['ghi','789']]).numpy() + array([b'abcdefghi', b'123456789'], dtype=object) + >>> tf.strings.join([['abc','123'], + ... ['def','456']], + ... separator=" ").numpy() + array([b'abc def', b'123 456'], dtype=object) + + The reduction version of this elementwise operation is + `tf.strings.reduce_join` + + Args: + inputs: A list of `tf.Tensor` objects of same size and `tf.string` dtype. + separator: A string added between each string being joined. + name: A name for the operation (optional). + + Returns: + A `tf.string` tensor. + """ + return gen_string_ops.string_join(inputs, separator=separator, name=name) + + +@tf_export("strings.unsorted_segment_join") +@dispatch.add_dispatch_support +def unsorted_segment_join(inputs, + segment_ids, + num_segments, + separator="", + name=None): + """Joins the elements of `inputs` based on `segment_ids`. + + Computes the string join along segments of a tensor. + + Given `segment_ids` with rank `N` and `data` with rank `N+M`: + + ``` + output[i, k1...kM] = strings.join([data[j1...jN, k1...kM]) + ``` + + where the join is over all `[j1...jN]` such that `segment_ids[j1...jN] = i`. + + Strings are joined in row-major order. + + For example: + + >>> inputs = ['this', 'a', 'test', 'is'] + >>> segment_ids = [0, 1, 1, 0] + >>> num_segments = 2 + >>> separator = ' ' + >>> tf.strings.unsorted_segment_join(inputs, segment_ids, num_segments, + ... separator).numpy() + array([b'this is', b'a test'], dtype=object) + + >>> inputs = [['Y', 'q', 'c'], ['Y', '6', '6'], ['p', 'G', 'a']] + >>> segment_ids = [1, 0, 1] + >>> num_segments = 2 + >>> tf.strings.unsorted_segment_join(inputs, segment_ids, num_segments, + ... separator=':').numpy() + array([[b'Y', b'6', b'6'], + [b'Y:p', b'q:G', b'c:a']], dtype=object) + + Args: + inputs: A list of `tf.Tensor` objects of type `tf.string`. + segment_ids: A tensor whose shape is a prefix of `inputs.shape` and whose + type must be `tf.int32` or `tf.int64`. Negative segment ids are not + supported. + num_segments: A scalar of type `tf.int32` or `tf.int64`. Must be + non-negative and larger than any segment id. + separator: The separator to use when joining. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `tf.string` tensor representing the concatenated values, using the given + separator. + """ + return gen_string_ops.unsorted_segment_join( + inputs, segment_ids, num_segments, separator=separator, name=name) + + +# Register elementwise ops that don't have Python wrappers. +dispatch.register_unary_elementwise_api(gen_string_ops.as_string) +dispatch.register_unary_elementwise_api(gen_string_ops.decode_base64) +dispatch.register_unary_elementwise_api(gen_string_ops.encode_base64) +dispatch.register_unary_elementwise_api(gen_string_ops.string_lower) +dispatch.register_unary_elementwise_api(gen_string_ops.string_upper) +dispatch.register_unary_elementwise_api(gen_string_ops.unicode_transcode) +dispatch.register_unary_elementwise_api(gen_string_ops.string_strip) +dispatch.register_unary_elementwise_api( + gen_string_ops.string_to_hash_bucket_fast) +dispatch.register_unary_elementwise_api( + gen_string_ops.string_to_hash_bucket_strong) +dispatch.register_unary_elementwise_api(gen_string_ops.unicode_script) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..9805418517399b622025884b9660ccd4f3415a87 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_array_ops.py @@ -0,0 +1,624 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""StructuredTensor array ops.""" + +from typing import Sequence + +from tensorflow.core.config import flags +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.ragged import dynamic_ragged_shape +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged.row_partition import RowPartition +from tensorflow.python.ops.structured.structured_tensor import StructuredTensor +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch + + +@dispatch.dispatch_for_api(array_ops.shape_v2) +def shape_v2(input: StructuredTensor, out_type=dtypes.int32, # pylint: disable=redefined-builtin + name=None) -> dynamic_ragged_shape.DynamicRaggedShape: + """Returns a DynamicRaggedShape containing the shape of the input.""" + del name + return input._ragged_shape.with_dtype(out_type) # pylint: disable=protected-access + + +@dispatch.dispatch_for_api(array_ops.shape) +def shape_v1(input: StructuredTensor, name=None, # pylint: disable=redefined-builtin + out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape: + """Returns a DynamicRaggedShape containing the shape of the input.""" + del name + return input._ragged_shape.with_dtype(out_type) # pylint: disable=protected-access + + +@dispatch.dispatch_for_types(array_ops.expand_dims, StructuredTensor) +@deprecation.deprecated_args(None, 'Use the `axis` argument instead', 'dim') +def expand_dims(input, axis=None, name=None, dim=None): # pylint: disable=redefined-builtin + """Creates a StructuredTensor with a length 1 axis inserted at index `axis`. + + This is an implementation of tf.expand_dims for StructuredTensor. Note + that the `axis` must be less than or equal to rank. + + >>> st = StructuredTensor.from_pyval([[{"x": 1}, {"x": 2}], [{"x": 3}]]) + >>> tf.expand_dims(st, 0).to_pyval() + [[[{'x': 1}, {'x': 2}], [{'x': 3}]]] + >>> tf.expand_dims(st, 1).to_pyval() + [[[{'x': 1}, {'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, 2).to_pyval() + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, -1).to_pyval() # -1 is the same as 2 + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + + Args: + input: the original StructuredTensor. + axis: the axis to insert the dimension: `-(rank + 1) <= axis <= rank` + name: the name of the op. + dim: deprecated: use axis. + + Returns: + a new structured tensor with larger rank. + + Raises: + an error if `axis < -(rank + 1)` or `rank < axis`. + """ + axis = deprecation.deprecated_argument_lookup('axis', axis, 'dim', dim) + return _expand_dims_impl(input, axis, name=name) + + +@dispatch.dispatch_for_types(array_ops.expand_dims_v2, StructuredTensor) +def expand_dims_v2(input, axis, name=None): # pylint: disable=redefined-builtin + """Creates a StructuredTensor with a length 1 axis inserted at index `axis`. + + This is an implementation of tf.expand_dims for StructuredTensor. Note + that the `axis` must be less than or equal to rank. + + >>> st = StructuredTensor.from_pyval([[{"x": 1}, {"x": 2}], [{"x": 3}]]) + >>> tf.expand_dims(st, 0).to_pyval() + [[[{'x': 1}, {'x': 2}], [{'x': 3}]]] + >>> tf.expand_dims(st, 1).to_pyval() + [[[{'x': 1}, {'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, 2).to_pyval() + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, -1).to_pyval() # -1 is the same as 2 + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + + Args: + input: the original StructuredTensor. + axis: the axis to insert the dimension: `-(rank + 1) <= axis <= rank` + name: the name of the op. + + Returns: + a new structured tensor with larger rank. + + Raises: + an error if `axis < -(rank + 1)` or `rank < axis`. + """ + return _expand_dims_impl(input, axis, name=name) + + +@dispatch.dispatch_for_types(array_ops.gather, StructuredTensor) +def gather(params, + indices, + validate_indices=None, + name=None, + axis=None, + batch_dims=0): + """tf.gather for structured tensors. + + Does not support (yet) checks on illegal axis values, et cetera. + + Indices must be a ragged or dense tensor. + Args: + params: a structured tensor to be gathered + indices: a ragged tensor or tensor to gather by. + validate_indices: whether to validate the indices + name: the name of the op(s). + axis: the axis in params to gather on. + batch_dims: the number of batch dimensions. + + Returns: + the params reorganized according to indices. + """ + if name is None: + name = 'gather' + with ops.name_scope(name): + if axis is None: + axis = batch_dims + axis = array_ops.get_positive_axis(axis, params.shape.rank, + ndims_name='params.shape.rank') + indices = ragged_tensor.convert_to_tensor_or_ragged_tensor( + indices, name='indices') + + def leaf_op(p): + return array_ops.gather( + p, + indices, + validate_indices=validate_indices, + axis=axis, + batch_dims=batch_dims, + name=None) + + return _extend_op_single(params, leaf_op) + + +@dispatch.dispatch_for_types(array_ops.concat, StructuredTensor) +def concat(values, axis, name: str = 'concat'): + """tf.concat for structured tensors. + + Does not support (yet) checks on illegal axis values, et cetera. + + Args: + values: a sequence of StructuredTensors. + axis: an axis to concatenate upon. + name: the name of the op(s). + + Returns: + the params reorganized according to indices. + """ + if name is None: + name = 'concat' + _assert_concat_compatible_structured_tensors(values) + def leaf_op(values): + return array_ops.concat(values, axis) + # TODO(martinz): handle axis when it is a tensor. + axis = array_ops.get_positive_axis(axis, values[0].rank) + with ops.name_scope(name, 'StructuredConcat', values): + return _extend_op(values, leaf_op) + + +@dispatch.dispatch_for_types(random_ops.random_shuffle, StructuredTensor) +def random_shuffle(value, seed=None, name=None): + """Shuffle a structured tensor on the zeroth axis. + + Args: + value: a structured tensor of rank at least one. + seed: the seed for shuffling. + name: the name for shuffle. + + Returns: + The shuffled structured tensor. + """ + with ops.name_scope(name, 'shuffle', [value, seed]): + if value.rank == 0: + raise ValueError('Cannot shuffle a scalar StructuredTensor') + first_dimension = value.nrows() + index = random_ops.random_shuffle(math_ops.range(first_dimension), + seed=seed) + return gather(value, index, axis=0) + + +@dispatch.dispatch_for_types(array_ops.size_v2, StructuredTensor) +def size_v2(input, out_type=None, name=None): + # pylint: disable=redefined-builtin + """Returns the size of a tensor.""" + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + return size(input, name=name, out_type=out_type) + + +# pylint: disable=protected-access +@dispatch.dispatch_for_types(array_ops.size, StructuredTensor) +def size(input, name=None, out_type=None): + # pylint: disable=redefined-builtin + """Returns the size of a tensor.""" + if out_type is None: + if flags.config().tf_shape_default_int64.value(): + out_type = dtypes.int64 + else: + out_type = dtypes.int32 + with ops.name_scope(name, 'size', [input]) as name: + if not input.row_partitions: + if input.nrows() is not None: + return math_ops.cast(input.nrows(), out_type) # vector. + else: + return math_ops.cast(1, out_type) # scalar. + # 2D and up. + nvals = input.row_partitions[-1].nvals() + if nvals is None or out_type is None: + return nvals + return math_ops.cast(nvals, dtype=out_type) + + +# pylint: disable=protected-access +@dispatch.dispatch_for_types(array_ops.zeros_like, StructuredTensor) +def zeros_like(tensor, dtype=None, name=None, optimize=True): + """Implementation of zeros_like for StructuredTensor for TF v1.""" + del optimize + return zeros_like_v2(tensor, dtype=dtype, name=name) + + +# pylint: disable=protected-access +@dispatch.dispatch_for_types(array_ops.zeros_like_v2, StructuredTensor) +def zeros_like_v2(input, dtype=None, name=None, layout=None): # pylint: disable=redefined-builtin + """Replace every object with a zero. + + Example: + >>> st = StructuredTensor.from_pyval([{"x":[3]}, {"x":[4,5]}]) + >>> tf.zeros_like(st) + + >>> st = StructuredTensor.from_pyval([[{"x":[3]}], [{"x":[4,5]}, {"x":[]}]]) + >>> tf.zeros_like(st, dtype=tf.int32) + + + Args: + input: a structured tensor. + dtype: the dtype of the resulting zeros. (default is tf.float32) + name: a name for the op. + layout: Optional Layout. Only supports replicated layout. + + Returns: + a tensor of zeros of the same shape. + """ + if layout is not None and not layout.is_fully_replicated(): + raise ValueError( + f'StructuredTensor only allows replicated layout. got {layout}' + ) + if dtype is None: + dtype = dtypes.float32 + with ops.name_scope(name, 'zeros_like', [input]) as name: + if not input.row_partitions: + if input.nrows() is not None: + return array_ops.zeros([input.nrows()], dtype, layout=layout) # vector. + else: + return array_ops.zeros([], dtype, layout=layout) # scalar. + # 2D and up. + last_row_partition = input.row_partitions[-1] + + result = ragged_tensor.RaggedTensor._from_nested_row_partitions( + array_ops.zeros(last_row_partition.nvals(), dtype=dtype), + input.row_partitions) + return result + + +# pylint: disable=protected-access +@dispatch.dispatch_for_types(array_ops.ones_like, StructuredTensor) +def ones_like(tensor, dtype=None, name=None, optimize=True): + """Implementation of zeros_like for StructuredTensor for TF v1.""" + del optimize + return ones_like_v2(tensor, dtype=dtype, name=name) + + +# pylint: disable=protected-access +@dispatch.dispatch_for_types(array_ops.ones_like_v2, StructuredTensor) +def ones_like_v2(input, dtype=None, name=None, layout=None): # pylint: disable=redefined-builtin + """Replace every object with a zero. + + Example: + >>> st = StructuredTensor.from_pyval([{"x":[3]}, {"x":[4,5]}]) + >>> tf.ones_like(st) + + >>> st = StructuredTensor.from_pyval([[{"x":[3]}], [{"x":[4,5]}, {"x":[]}]]) + >>> tf.ones_like(st, dtype=tf.int32) + + + Args: + input: a structured tensor. + dtype: the dtype of the resulting zeros. (default is tf.float32) + name: a name for the op. + layout: Optional Layout. Only supports replicated layout. + + Returns: + a tensor of zeros of the same shape. + """ + if layout is not None and not layout.is_fully_replicated(): + raise ValueError( + f'StructuredTensor only allows replicated layout. got {layout}' + ) + + if dtype is None: + dtype = dtypes.float32 + with ops.name_scope(name, 'ones_like', [input]) as name: + if not input.row_partitions: + if input.nrows() is not None: + return array_ops.ones([input.nrows()], dtype, layout=layout) # vector. + else: + return array_ops.ones([], dtype, layout=layout) # scalar. + # 2D and up. + last_row_partition = input.row_partitions[-1] + + result = ragged_tensor.RaggedTensor._from_nested_row_partitions( + array_ops.ones(last_row_partition.nvals(), dtype=dtype), + input.row_partitions) + return result + + +@dispatch.dispatch_for_types(array_ops.rank, StructuredTensor) +def rank(input, name=None): + # pylint: disable=redefined-builtin + """Returns the rank of a tensor.""" + with ops.name_scope(name, 'rank', [input]) as name: + return constant_op.constant(input.rank, dtype=dtypes.int32) + + +def _expand_dims_impl(st, axis, name=None): # pylint: disable=redefined-builtin + """Creates a StructuredTensor with a length 1 axis inserted at index `axis`. + + This is an implementation of tf.expand_dims for StructuredTensor. Note + that the `axis` must be less than or equal to rank. + + >>> st = StructuredTensor.from_pyval([[{"x": 1}, {"x": 2}], [{"x": 3}]]) + >>> tf.expand_dims(st, 0).to_pyval() + [[[{'x': 1}, {'x': 2}], [{'x': 3}]]] + >>> tf.expand_dims(st, 1).to_pyval() + [[[{'x': 1}, {'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, 2).to_pyval() + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + >>> tf.expand_dims(st, -1).to_pyval() # -1 is the same as 2 + [[[{'x': 1}], [{'x': 2}]], [[{'x': 3}]]] + + Args: + st: the original StructuredTensor. + axis: the axis to insert the dimension: `-(rank + 1) <= axis <= rank` + name: the name of the op. + + Returns: + a new structured tensor with larger rank. + + Raises: + an error if `axis < -(rank + 1)` or `rank < axis`. + """ + axis = array_ops.get_positive_axis( + axis, st.rank + 1, axis_name='axis', ndims_name='rank(st)') + with ops.name_scope(name, 'ExpandDims', [st, axis]): + new_fields = { + k: array_ops.expand_dims(v, axis) for (k, v) in st._fields.items() + } + new_shape = st.shape[:axis] + (1,) + st.shape[axis:] + new_row_partitions = _expand_st_row_partitions(st, axis) + new_nrows = st.nrows() if (axis > 0) else 1 + return StructuredTensor.from_fields( + new_fields, + shape=new_shape, + row_partitions=new_row_partitions, + nrows=new_nrows) + + +def _expand_st_row_partitions(st, axis): + """Create the row_partitions for expand_dims.""" + if axis == 0: + if st.shape.rank == 0: + return () + nvals = st.nrows() + new_partition = RowPartition.from_uniform_row_length( + nvals, nvals, nrows=1, validate=False) + return (new_partition,) + st.row_partitions + elif axis == st.rank: + nvals = ( + st.row_partitions[axis - 2].nvals() if (axis - 2 >= 0) else st.nrows()) + return st.row_partitions + (RowPartition.from_uniform_row_length( + 1, nvals, nrows=nvals, validate=False),) + else: + nvals = ( + st.row_partitions[axis - 1].nrows() if (axis - 1 >= 0) else st.nrows()) + return st.row_partitions[:axis - 1] + (RowPartition.from_uniform_row_length( + 1, nvals, nrows=nvals, validate=False),) + st.row_partitions[axis - 1:] + + +# TODO(martinz): consider allowing values to be nested. +def _extend_op(values, leaf_op, empty_st_op=None): + """Extend an op from RaggedTensor and Tensor to StructuredTensor. + + Visits all children of the structured tensor, and children of children, + applying leaf_op whenever it reaches a leaf, and empty_st_op whenever + it reaches an internal node without children. + + Args: + values: a list of structured tensors, ragged tensors, or tensors. All must + have the same type. If they are structured tensors, they must have the + same paths. + leaf_op: an op for handling non-structured tensor. + empty_st_op: op to create a structured tensor without fields. + + Returns: + the result of the extended op (a StructuredTensor, RaggedTensor, or Tensor) + + Raises: + ValueError: + If values is not a Sequence or is empty. + """ + if not isinstance(values, Sequence): + raise ValueError('Expected a list') + + if not values: + raise ValueError('List cannot be empty') + + if empty_st_op is None: + empty_st_op = empty_st_op_like_zeros(leaf_op) + # Use the structure of the first StructuredTensor. They are all assumed to + # be the same. + value = values[0] + + if isinstance(value, StructuredTensor): + # TODO(martinz): Calling empty_st_op may add unnecessary ops. Revisit later. + empty_result = empty_st_op(values) + if not value.field_names(): + return empty_result + new_fields = {} + for k in value.field_names(): + new_fields[k] = _extend_op([v.field_value(k) for v in values], leaf_op, + empty_st_op) + return StructuredTensor.from_fields(new_fields, shape=empty_result.shape) + else: + return leaf_op(values) + + +def _extend_op_single(value, leaf_op, empty_st_op=None): + """Extend an op to a value instead of a list of values.""" + + def to_list_op(element_op): + if element_op is None: + return None + + def list_op(values): + [value] = values + return element_op(value) + + return list_op + + return _extend_op([value], to_list_op(leaf_op), to_list_op(empty_st_op)) + + +def empty_st_op_like_zeros(leaf_op): + + def empty_st_op(values): + as_zeros = [ + zeros_like_v2(value, dtype=dtypes.int32) for value in values + ] + result = leaf_op(as_zeros) + return _structured_tensor_like(result) + + return empty_st_op + + +def _structured_tensor_from_dense_tensor(t): + """Create a structured tensor with the shape of a dense tensor.""" + # Note: If a tensor will have rank 0, + # it either has a fully defined shape or has unknown rank. + if t.shape.is_fully_defined(): + return StructuredTensor.from_fields({}, shape=t.shape) + elif t.shape.rank is None: + raise ValueError("Can't build StructuredTensor w/ unknown rank") + elif t.shape.rank == 1: + return StructuredTensor.from_fields({}, shape=t.shape, + nrows=array_ops.shape(t)[0]) + else: + rt = ragged_tensor.RaggedTensor.from_tensor(t) + return _structured_tensor_from_row_partitions(t.shape, + rt._nested_row_partitions) + + +def _structured_tensor_from_row_partitions(shape, row_partitions): + return StructuredTensor.from_fields({}, + shape=shape, + row_partitions=row_partitions) + + +# pylint: disable=protected_access +def _all_nested_row_partitions(rt): + """Returns all nested row partitions in rt, including for dense dimensions.""" + if isinstance(rt, tensor_lib.Tensor): + if rt.shape.rank <= 1: + return () + else: + rt2 = ragged_tensor.RaggedTensor.from_tensor(rt) + return rt2._nested_row_partitions + else: + tail_partitions = _all_nested_row_partitions(rt.flat_values) + head_partitions = rt._nested_row_partitions # pylint: disable=protected_access + return head_partitions + tail_partitions + + +def _structured_tensor_like(t): + """Create a StructuredTensor with the shape of a (composite) tensor.""" + if isinstance(t, tensor_lib.Tensor): + return _structured_tensor_from_dense_tensor(t) + if ragged_tensor.is_ragged(t): + return StructuredTensor.from_fields( + {}, shape=t.get_shape(), row_partitions=_all_nested_row_partitions(t)) + # here, it is a StructuredTensor + return StructuredTensor.from_fields({}, + shape=t.shape, + row_partitions=t.row_partitions, + nrows=t.nrows()) + + +def _get_all_paths(st): + """Get all the paths from a StructuredTensor.""" + fields = st.field_names() + all_paths = {()} + for k in fields: + v = st.field_value(k) + if isinstance(v, StructuredTensor): + all_paths = all_paths.union([(k,) + p for p in _get_all_paths(v)]) + else: + all_paths.add((k,)) + return all_paths + + +def _get_all_ranks(st): + """Get ranks of all submessages of a StructuredTensor.""" + fields = st.field_names() + all_ranks = {(): st.rank} + for k in fields: + v = st.field_value(k) + if isinstance(v, StructuredTensor): + for (k2, v2) in _get_all_ranks(v).items(): + all_ranks[(k,) + k2] = v2 + return all_ranks + + +def _assert_all_paths_match(values): + """Raises an error if the paths are not identical.""" + paths = [_get_all_paths(st) for st in values] + path_diff = set() + for other_paths in paths[1:]: + path_diff = path_diff.union(paths[0].symmetric_difference(other_paths)) + if path_diff: + raise ValueError( + 'Some paths are present in some, but not all, structured tensors: %r' % + (path_diff,)) + + +def _assert_all_ranks_match(values): + """Raises an error if the ranks of submessages are not identical.""" + ranks = [_get_all_ranks(st) for st in values] + for other_ranks in ranks[1:]: + if other_ranks != ranks[0]: + # TODO(martinz): If this becomes common, we can provide more detail. + # e.g.: which path is inconsistent. + raise ValueError('Ranks of sub-message do not match') + + +def _assert_concat_compatible_structured_tensors(values): + """Sometimes raises an error if concat doesn't make sense statically on values. + + values must be a sequence, and each element in values must be a structured + tensor, and must have the same paths. Additionally, each path that is a + submessage must have the same rank. + + These constraints are sufficient for concat on the fields to be the same + as concat on structured tensors. This is meant to capture scenarios like + paths that are not in the first structured tensor, but are in later + structured tensors, which will just be ignored by the recursive algorithm. + + If the rank of a submessage was different for two structured tensors, + then that is also a non-sensical merge. + + Note that all of these checks are static, as paths and submessage ranks + are known. + + Args: + values: a Sequence of StructuredTensors. + + Raises: + ValueError: if there is any inconsistency as described above. + """ + if not isinstance(values, Sequence): + raise ValueError('values must be a list of StructuredTensors (not a list)') + if not values: + raise ValueError('values must not be an empty list') + for st in values: + if not isinstance(st, StructuredTensor): + raise ValueError('values must be a list of StructuredTensors') + _assert_all_paths_match(values) + _assert_all_ranks_match(values) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0f9f52a29d710d04630f16e90275197219dd44 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_ops.py @@ -0,0 +1,24 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Import all modules in the `structured` package that define exported symbols. + +We don't import these modules from structured/__init__.py, since we want to +avoid circular dependencies. +""" + + +# pylint: disable=unused-import +from tensorflow.python.ops.structured import structured_array_ops +from tensorflow.python.ops.structured import structured_tensor diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..752d29895fe1a32bb841363632d9b581bbf4ccf5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor.py @@ -0,0 +1,1782 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Structured Tensors.""" + +import re +from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import extension_type +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.ragged import dynamic_ragged_shape +from tensorflow.python.ops.ragged import ragged_factory_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged.row_partition import RowPartition +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# Each field may contain one of the following types of Tensors. +_FieldValue = Union[ + tensor.Tensor, + ragged_tensor.RaggedTensor, + 'StructuredTensor', + extension_type.ExtensionType +] +# Function that takes a FieldValue as input and returns the transformed +# FieldValue. +_FieldFn = Callable[[_FieldValue], _FieldValue] + + +@tf_export('experimental.StructuredTensor') +class StructuredTensor(extension_type.BatchableExtensionType): + """A multidimensional collection of structures with the same schema. + + A **`StructuredTensor`** is a multi-dimensional collection of ***structures*** + with the same ***schema***, where: + + * A ***schema*** is a collection of fields, each of which has a name and type. + * A ***structure*** maps each field in the schema to a tensor value (which + could be a nested StructuredTensor). + + As an important special case, a 1D `StructuredTensor` encodes a 2D table, + where columns are heterogeneous `Tensor`s, and rows are the aligned elements + in each of those `Tensor`s. + + Internally, StructuredTensors use a "field-major" encoding: for each leaf + field, there is a single tensor that stores the value of that field for all + structures in the `StructuredTensor`. + + ### Examples + + >>> # A scalar StructuredTensor describing a single person. + >>> s1 = tf.experimental.StructuredTensor.from_pyval( + ... {"age": 82, "nicknames": ["Bob", "Bobby"]}) + >>> s1.shape + TensorShape([]) + >>> s1["age"] + + + >>> # A vector StructuredTensor describing three people. + >>> s2 = tf.experimental.StructuredTensor.from_pyval([ + ... {"age": 12, "nicknames": ["Josaphine"]}, + ... {"age": 82, "nicknames": ["Bob", "Bobby"]}, + ... {"age": 42, "nicknames": ["Elmo"]}]) + >>> s2.shape + TensorShape([3]) + >>> s2[0]["age"] + + + + ### Field Paths + + A *field path* is a tuple of field names, specifying the path to a nested + field. + """ + _fields: Mapping[str, _FieldValue] + _ragged_shape: dynamic_ragged_shape.DynamicRaggedShape + + __name__ = 'tf.StructuredTensor' + #============================================================================= + # Common Types + #============================================================================= + # pylint: disable=invalid-name + # Field names work as key, and they can be a sequence to refer to the + # sub-levels (embedded) StructuredTensor's. + FieldName = Union[str, Sequence[str]] + + # pylint: enable=invalid-name + + #============================================================================= + # Constructor & Factory Methods + #============================================================================= + def __init__(self, fields: Mapping[str, _FieldValue], + ragged_shape: dynamic_ragged_shape.DynamicRaggedShape): + self._fields = fields + self._ragged_shape = ragged_shape + + @classmethod + def _old_init(cls, fields, shape, nrows, row_partitions, internal=False): + """Private constructor -- use factory methods to create StructuredTensors. + + This constructor builds a `StructuredTensor` from the given attributes, + performing minimal validation. + + Args: + fields: A dictionary mapping from string to `Tensor`, `RaggedTensor`, or + `StructuredTensor`. (This dict is not copied, so the caller must ensure + that it does not get mutated via leaked references.) + shape: `tf.TensorShape` with statically known rank. + nrows: scalar integer `tf.Tensor`, or `None` if `shape.rank==0`. + row_partitions: tuple of `RowPartition`s, with length `shape.rank-1`. + internal: ignored argument. + + Returns: + a StructuredTensor. + """ + assert isinstance(fields, dict), fields + assert isinstance(shape, tensor_shape.TensorShape), shape + assert nrows is None or isinstance(nrows, tensor.Tensor), nrows + assert row_partitions is None or isinstance(row_partitions, + tuple), row_partitions + return StructuredTensor( + fields=fields, + ragged_shape=_dynamic_ragged_shape_init(fields, shape, nrows, + row_partitions)) + + @classmethod + def from_shape( + cls, ragged_shape: dynamic_ragged_shape.DynamicRaggedShape + ) -> 'StructuredTensor': + """Creates a `StructuredTensor` with no fields and ragged_shape. + + Args: + ragged_shape: the shape of the structured tensor. + + Returns: + a StructuredTensor with no fields and ragged_shape. + """ + return StructuredTensor(fields={}, ragged_shape=ragged_shape) + + @classmethod + def from_fields(cls, + fields, + shape=(), + nrows=None, + row_partitions=None, + validate=False): + """Creates a `StructuredTensor` from a dictionary of fields. + + Args: + fields: A dictionary mapping from string to `Tensor`, `RaggedTensor`, or + `StructuredTensor`, providing the values for individual fields in each + structure. If `shape.rank > 0`, then every tensor in `fields` must have + the same shape in the first `shape.rank` dimensions; and that shape must + be compatible with `shape`; and `result[i1...iN][key] = + fields[key][i1...iN]` (where `N==shape.rank`). + shape: A `TensorShape`: static information about the shape of the + `StructuredTensor`. Must have a known `rank`. Defaults to scalar shape + (i.e. `rank=0`). + nrows: scalar integer tensor containing the number of rows in this + `StructuredTensor`. Should only be specified if `shape.rank > 0`. + Default value is inferred from the `fields` values. If `fields` is + empty, then this must be specified. + row_partitions: A list of `RowPartition`s describing the (possibly ragged) + shape of this `StructuredTensor`. Should only be specified if + `shape.rank > 1`. Default value is inferred from the `fields` values. + If `fields` is empty, then this must be specified. + validate: If true, then add runtime validation ops that check that the + field values all have compatible shapes in the outer `shape.rank` + dimensions. + + Returns: + A `StructuredTensor`. + + Examples: + + >>> tf.experimental.StructuredTensor.from_fields({'x': 1, 'y': [1, 2, 3]}) + + + >>> tf.experimental.StructuredTensor.from_fields( + ... {'foo': [1, 2], 'bar': [3, 4]}, shape=[2]) + + """ + shape = tensor_shape.as_shape(shape) + rank = shape.rank + if rank is None: + raise ValueError("StructuredTensor's shape must have known rank.") + if not isinstance(fields, dict): + raise TypeError('fields must be a dictionary, got %s' % + type(fields).__name__) + if rank < 2 and row_partitions: + raise ValueError('row_partitions must be None or [] if shape.rank<2') + if rank == 0 and nrows is not None: + raise ValueError('nrows must be None if shape.rank==0') + if row_partitions is not None: + row_partitions = tuple(row_partitions) + if len(row_partitions) != max(0, rank - 1): + raise ValueError('len(row_partitions) must be shape.rank-1') + elif rank < 2: + row_partitions = () + + fields = dict(fields) # Make a private copy. + with ops.name_scope(None, 'StructuredTensor', fields.values()): + # TODO(martinz): Make this have better errors. + shape = _dynamic_ragged_shape_init(fields, shape, nrows, row_partitions) + + # TODO(martinz): This may not need to be done if all fields are dense. + if shape.rank > 1: + shape = shape._with_num_row_partitions(shape.rank - 1) + + # Validate keys and convert field values to tensors. + for key, value in fields.items(): + if not isinstance(key, str): + raise TypeError(f'Unexpected type for key in `fields`: {key}') + if not _FIELD_NAME_RE.match(key): + raise ValueError('Field name %r is not currently allowed.' % key) + fields[key] = _convert_to_structured_field_value(value) + + fields = dict([(k, _replace_row_partitions(v, row_partitions)) + for (k, v) in fields.items()]) + return cls(fields=fields, ragged_shape=shape) + + @classmethod + def from_fields_and_rank( + cls, + fields: Mapping[str, _FieldValue], + rank: int, + validate: bool = False, + dtype: Optional[dtypes.DType] = None) -> 'StructuredTensor': + """Creates a `StructuredTensor` from a nonempty dictionary of fields. + + Note that if the shape dtype is not specified, the shape dtype will be + inferred from any fields that have a shape dtype. If fields differ, then + int64 will be preferred to int32, because coercing from int32 to int64 is + safer than coercing from int64 to int32. + + If there are no ragged fields, then it will be int64 by default, but this + will be changed to int32 in the future. + + Args: + fields: A dictionary mapping from string to `Tensor`, `RaggedTensor`, or + `StructuredTensor`, providing the values for individual fields in each + structure. If `rank > 0`, then every tensor in `fields` must have the + same shape in the first `rank` dimensions. Cannot be empty. + rank: The rank of the resulting structured tensor. + validate: If true, then add runtime validation ops that check that the + field values all have compatible shapes in the outer `rank` dimensions. + dtype: If specified, then forces dtype of the shape to be this. + + Returns: + A `StructuredTensor`. + Examples: + >>> tf.experimental.StructuredTensor.from_fields_and_rank( + ... {'x': 1, 'y': [1, 2, 3]}, 0) + + >>> StructuredTensor.from_fields_and_rank({'foo': [1, 2], 'bar': [3, 4]}, + ... 1) + + """ + if not fields: + raise ValueError('Must provide at least one field') + if not isinstance(rank, int): + raise ValueError('rank must be an integer') + if rank < 0: + raise ValueError('rank must be nonnegative') + fields = { + k: _convert_to_structured_field_value(v) for (k, v) in fields.items() + } + if dtype is None: + dtype = _find_shape_dtype(fields, None, None) + fields = _fields_with_dtype(fields, dtype) + + shape = _shape_from_fields(fields, rank, dtype) + if rank > 1: + shape = shape._with_num_row_partitions(rank - 1) + new_rp = shape._row_partitions # pylint: disable=protected-access + fields = { + k: _replace_row_partitions(v, new_rp) for (k, v) in fields.items() + } + return StructuredTensor(fields=fields, ragged_shape=shape) + + def with_updates(self, + updates: Dict[FieldName, Union[_FieldValue, _FieldFn, None]], + validate: bool = False) -> 'StructuredTensor': + """Creates a new `StructuredTensor` with the updated fields. + + If this `StructuredTensor` is a scalar, and `k` is the `FieldName` being + updated and `v` the new value, then: + + ``` + result[k] = v # If (k, v) is in updates and v is a FieldValue + result[k] = f(self[k]) # If (k, f) is in updates and f is a FieldFn + result[k] = self[k] # If k is in self.field_names but not in updates + ``` + + If this `StructuredTensor` has rank `N` and shape `[D1...DN]`, then each + FieldValue `v` in `updates` must have shape `[D1...DN, ...]`, that is, + prefixed with the same shape as the `StructuredTensor`. Then the resulting + `StructuredTensor` will have: + + ``` + result[i1...iN][k] = v[i1...iN] # (k, v) in updates + result[i1...iN][k] = f(self.field_value(k))[i1...iN] # (k, f) in updates + result[i1...iN][k] = self[i1...iN][k] # k not in updates + ``` + + Note that `result.shape` is always equal to `self.shape` (but the shapes + of nested StructuredTensors may be changed if they are updated with new + values). + + Args: + updates: A dictionary mapping `FieldName` to either a `FieldValue` to be + used to update, or a `FieldFn` that will transform the value for the + given `FieldName`. `FieldName` can be a string for a direct field, or a + sequence of strings to refer to a nested sub-field. `FieldFn` is a + function that takes a `FieldValue` as input and should return a + `FieldValue`. All other fields are copied over to the new + `StructuredTensor`. New `FieldName` can be given (to add new fields), + but only to existing `StructuredTensor`, it won't automatically create + new nested structures -- but one can create a whole `StructureTensor` + sub-structure and set that into an existing structure. If the new value + is set to `None`, it is removed. + validate: If true, then add runtime validation ops that check that the + field values all have compatible shapes in the outer `shape.rank` + dimensions. + + Returns: + A `StructuredTensor`. + + Raises: + `ValueError`: If the any of the `FieldName` keys points to non-existent + sub-structures, if parent and child nodes are updated, if shapes + change, if a delete update is given for a non-existent field, or if a + `FieldFn` transforming function is given for a `FieldName` that doesn't + yet exist. + + Examples: + + >>> shoes_us = tf.experimental.StructuredTensor.from_pyval([ + ... {"age": 12, "nicknames": ["Josaphine"], + ... "shoes": {"sizes": [8.0, 7.5, 7.5]}}, + ... {"age": 82, "nicknames": ["Bob", "Bobby"], + ... "shoes": {"sizes": [11.0, 11.5, 12.0]}}, + ... {"age": 42, "nicknames": ["Elmo"], + ... "shoes": {"sizes": [9.0, 9.5, 10.0]}}]) + >>> def us_to_europe(t): + ... return tf.round(t * 2.54 + 17.0) # Rough approximation. + >>> shoe_sizes_key = ("shoes", "sizes") + >>> shoes_eu = shoes_us.with_updates({shoe_sizes_key: us_to_europe}) + >>> shoes_eu.field_value(shoe_sizes_key) + + """ + updates_items = [(_normalize_field_name_to_tuple(name), value) + for name, value in updates.items()] + + # Sort by keys and check for updates of both parent and child nodes. + updates_items = sorted(updates_items) + for i in range(1, len(updates_items)): + # Parent of a node would precede node in the sorted order. + name = updates_items[i][0] # item[0] is the name, item[1] is the value. + prev_name = updates_items[i - 1][0] + if name[:len(prev_name)] == prev_name: + raise ValueError( + '`StructuredTensor.with_updates` does not allow both parent and ' + 'child nodes to be updated: parent={}, child={}. If needed you can ' + 'update child nodes in the parent update value.'.format( + prev_name, name)) + return self._with_updates_impl((), updates_items, validate) + + def _with_updates_impl(self, error_prefix: Tuple[str, ...], + updates: List[Tuple[FieldName, Union[_FieldValue, + _FieldFn]]], + validate: bool) -> 'StructuredTensor': + """Recursive part of `with_updates` implementation.""" + # Get current fields. + new_fields = dict(self._fields) + + # Convert field name to string with full path for error messages. + def name_fullpath(name: Sequence[str]) -> str: + return str(error_prefix + (name,)) + + # Apply value if a function or the value itself. + def apply_value(name: str, value: Union[_FieldValue, + _FieldFn]) -> _FieldValue: + if callable(value): + # `value` is actually a transforming function. + if name not in new_fields: + raise ValueError( + '`StructuredTensor.with_updates` cannot update the field {} ' + 'because a transforming function was given, but that field ' + 'does not already exist.'.format(name_fullpath(name))) + value = value(new_fields[name]) + return value + + # Merge updates. + for name, value in updates: + if not name or not name[0]: + raise ValueError( + '`StructuredTensor.with_updates` does not allow empty names ' + '{}.'.format(name_fullpath(name))) + + if len(name) == 1: + name = name[0] + if value is None: + if name not in new_fields: + raise ValueError( + '`StructuredTensor.with_updates` cannot delete field ' + '{} because it is not present.'.format(name_fullpath(name))) + new_fields.pop(name) + else: + new_fields[name] = apply_value(name, value) + else: + # Recursive + prefix = name[0] + suffix = name[1:] + if prefix not in new_fields: + raise ValueError( + '`StructuredTensor.with_updates` cannot create new sub-field ' + '{} if parent field {} is not set.'.format( + error_prefix + tuple(name), name_fullpath(prefix))) + current_value = new_fields[prefix] + if not isinstance(current_value, StructuredTensor): + raise ValueError( + '`StructuredTensor.with_updates` cannot create new sub-field ' + '{} if parent structure {} is not a `StructuredTensor` that ' + 'can contain sub-structures -- it is a `{}`.'.format( + error_prefix + tuple(name), name_fullpath(prefix), + type(current_value))) + one_update = [(suffix, value)] + + # Accessing protected member in recursion. + # FutureWork: optimize by aggregating the recursions, instead of + # calling one at a time. + # pylint: disable=protected-access + value = current_value._with_updates_impl(error_prefix + (prefix,), + one_update, validate) + # pylint: enable=protected-access + new_fields[prefix] = value + + # TODO(edloper): When validate=True, only validate the modified fields. + try: + return StructuredTensor.from_fields( + new_fields, + shape=self.shape, + row_partitions=self.row_partitions, + nrows=self.nrows(), + validate=validate) + + except ValueError as e: + msg = '`StructuredTensor.with_updates` failed' + if error_prefix: + msg = '{} for field {}'.format(msg, error_prefix) + raise ValueError(msg) from e + + def _promote_helper(self, source_path, new_parent_path): + """Creates a promoted field without adding it to the structure. + + Args: + source_path: the source path in the structured tensor. + new_parent_path: the new parent path. Must be a prefix of source_path. + + Returns: + a composite tensor of source_path promoted. + Raises: + ValueError: if the shape of the field is unknown and the right strategy + cannot be determined. + """ + current_field = self.field_value(source_path) + new_parent_rank = self.field_value(new_parent_path).rank + parent_rank = self.field_value(source_path[:-1]).rank + if new_parent_rank == parent_rank: + return current_field + current_field_rank = current_field.shape.rank + if current_field_rank is None: + raise ValueError('Cannot determine if dimensions should be merged.') + inner_dim = min(parent_rank, current_field_rank - 1) + if inner_dim <= new_parent_rank: + return current_field + return _merge_dims_generic(current_field, new_parent_rank, inner_dim) + + def promote(self, source_path, new_name): + """Promotes a field, merging dimensions between grandparent and parent. + + >>> d = [ + ... {'docs': [{'tokens':[1, 2]}, {'tokens':[3]}]}, + ... {'docs': [{'tokens':[7]}]}] + >>> st = tf.experimental.StructuredTensor.from_pyval(d) + >>> st2 =st.promote(('docs','tokens'), 'docs_tokens') + >>> st2[0]['docs_tokens'] + + >>> st2[1]['docs_tokens'] + + + Args: + source_path: the path of the field or substructure to promote; must have + length at least 2. + new_name: the name of the new field (must be a string). + + Returns: + a modified structured tensor with the new field as a child of the + grandparent of the source_path. + + Raises: + ValueError: if source_path is not a list or a tuple or has a length + less than two, or new_name is not a string, or the rank + of source_path is unknown and it is needed. + """ + if not isinstance(new_name, str): + raise ValueError('new_name is not a string') + if not isinstance(source_path, (list, tuple)): + raise ValueError('source_path must be a list or tuple') + + if len(source_path) < 2: + raise ValueError('source_path must have length at least two') + + grandparent_path = source_path[:-2] + new_field = self._promote_helper(source_path, grandparent_path) + new_path = grandparent_path + (new_name,) + return self.with_updates({new_path: new_field}) + + #============================================================================= + # Properties + #============================================================================= + + @property + def rank(self): + """The rank of this StructuredTensor. Guaranteed not to be `None`.""" + return self._ragged_shape.rank + + @property + def shape(self): + """The static shape of this StructuredTensor. + + The returned `TensorShape` is guaranteed to have a known rank, but the + individual dimension sizes may be unknown. + + Returns: + `tf.TensorShape` + """ + return self._ragged_shape._to_tensor_shape() # pylint: disable=protected-access + + # TODO(martinz): for backwards compatibility + @property + def _row_partitions(self): + """Deprecated form of row_partitions.""" + return self.row_partitions + + # TODO(edloper): Make this a func instead of a property? Or make nrows + # a property instead of a func? Seems like these should be consistent. + @property + def row_partitions(self): + """A tuple of `RowPartition`s defining the shape of this `StructuredTensor`. + + When `self.rank <= 1`, this tuple will be empty. + + When `self.rank > 1`, these `RowPartitions` define the shape of the + `StructuredTensor` by describing how a flat (1D) list of structures can be + repeatedly partitioned to form a higher-dimensional object. In particular, + the flat list is first partitioned into sublists using `row_partitions[-1]`, + and then those sublists are further partitioned using `row_partitions[-2]`, + etc. The following examples show the row partitions used to describe + several different `StructuredTensor`, each of which contains 8 copies of + the same structure (`x`): + + >>> x = {'a': 1, 'b': ['foo', 'bar', 'baz']} # shape = [] (scalar) + + >>> s1 = [[x, x, x, x], [x, x, x, x]] # shape = [2, 4] + >>> tf.experimental.StructuredTensor.from_pyval(s1).row_partitions + (tf.RowPartition(row_splits=[0 4 8]),) + + >>> s2 = [[x, x], [x, x], [x, x], [x, x]] # shape = [4, 2] + >>> tf.experimental.StructuredTensor.from_pyval(s2).row_partitions + (tf.RowPartition(row_splits=[0 2 4 6 8]),) + + >>> s3 = [[x, x, x], [], [x, x, x, x], [x]] # shape = [2, None] + >>> tf.experimental.StructuredTensor.from_pyval(s3).row_partitions + (tf.RowPartition(row_splits=[0 3 3 7 8]),) + + >>> s4 = [[[x, x], [x, x]], [[x, x], [x, x]]] # shape = [2, 2, 2] + >>> tf.experimental.StructuredTensor.from_pyval(s4).row_partitions + (tf.RowPartition(row_splits=[0 2 4]), + tf.RowPartition(row_splits=[0 2 4 6 8])) + + + >>> s5 = [[[x, x], [x]], [[x, x]], [[x, x], [x]]] # shape = [3, None, None] + >>> tf.experimental.StructuredTensor.from_pyval(s5).row_partitions + (tf.RowPartition(row_splits=[0 2 3 5]), + tf.RowPartition(row_splits=[0 2 3 5 7 8])) + + Note that shapes for nested fields (such as `x['b']` in the above example) + are not considered part of the shape of a `StructuredTensor`, and are not + included in `row_partitions`. + + If this `StructuredTensor` has a ragged shape (i.e., if any of the + `row_partitions` is not uniform in size), then all fields will be encoded + as either `RaggedTensor`s or `StructuredTensor`s with these `RowPartition`s + used to define their outermost `self.rank` dimensions. + + Returns: + A `tuple` of `RowPartition` objects with length `self.rank - 1` + (or `0` if `self.rank < 2`) + + """ + if self.rank < 2: + return () + return self._ragged_shape._as_row_partitions() # pylint:disable=protected-access + + def nrows(self): + """The number of rows in this StructuredTensor (if rank>0). + + This means the length of the outer-most dimension of the StructuredTensor. + + Notice that if `self.rank > 1`, then this equals the number of rows + of the first row partition. That is, + `self.nrows() == self.row_partitions[0].nrows()`. + + Otherwise `self.nrows()` will be the first dimension of the field values. + + Returns: + A scalar integer `Tensor` (or `None` if `self.rank == 0`). + """ + if self.rank == 0: + return None + return self._ragged_shape[0] + + def with_shape_dtype(self, dtype: dtypes.DType) -> 'StructuredTensor': + if dtype == self._ragged_shape.dtype: + return self + return StructuredTensor( + fields=_fields_with_dtype(self._fields, dtype), + ragged_shape=self._ragged_shape.with_dtype(dtype)) + + def _is_eager(self): + """True if all fields are composed of eager tensors.""" + tensors = nest.flatten(self, expand_composites=True) + return all(isinstance(t, ops.EagerTensor) for t in tensors) + + #============================================================================= + # Encoding + #============================================================================= + + def field_names(self): + """Returns the string field names for this `StructuredTensor`.""" + return tuple(self._fields.keys()) + + def field_value(self, field_name): + """Returns the tensor value for the specified field or path. + + If `field_name` is a `string`, then it names a field directly owned by this + `StructuredTensor`. If this `StructuredTensor` has shape `[D1...DN]`, then + the returned tensor will have shape `[D1...DN, V1...VM]`, where the slice + `result[d1...dN]` contains the field value for the structure at + `self[d1...dN]`. + + If `field_name` is a `tuple` of `string`, then it specifies a path to a + field owned by nested `StructuredTensor`. In particular, + `struct.field_value((f1, f2, ..., fN))` is equivalent to + `struct.field_value(f1).field_value(f2)....field_value(fN)` + + Args: + field_name: `string` or `tuple` of `string`: The field whose values should + be returned. + + Returns: + `Tensor`, `StructuredTensor`, or `RaggedTensor`. + + Raises: + KeyError: If the given field_name is not found. + """ + if isinstance(field_name, (list, tuple)): + value = self + for f in field_name: + if not isinstance(value, StructuredTensor): + raise KeyError('Field path {} not found in {}'.format( + field_name, self)) + value = value.field_value(f) + return value + return self._fields[field_name] + + #============================================================================= + # Operators + #============================================================================= + + # TODO(edloper): Add support for ellipsis and/or newaxis? + def __getitem__(self, key): + """Returns the specified piece of this StructuredTensor. + + * If `struct_tensor` is scalar (i.e., a single structure), then + `struct_tensor[f]` returns the value of field `f` (where `f` must be a + string). + + * If `struct_tensor` is non-scalar (i.e., a vector or higher-dimensional + tensor of structures), `struct_tensor[i]` selects an element or slice of + the tensor using standard Python semantics (e.g., negative values index + from the end). `i` may have any of the following types: + + * `int` constant + * `string` constant + * scalar integer `Tensor` + * `slice` containing integer constants and/or scalar integer + `Tensor`s + + #### Multidimensional indexing + + `StructuredTensor` supports multidimensional indexing. I.e., `key` may be a + `tuple` of values, indexing or slicing multiple dimensions at once. For + example, if `people` is a vector of structures, each of which has a vector- + valued `names` field, then `people[3, 'names', 0]` is equivalent to + `people[3]['names'][0]`; and `people[:, 'names', :]` will return a (possibly + ragged) matrix of names, with shape `[num_people, num_names_per_person]`. + + Args: + key: Indicates which piece of the StructuredTensor to return. + + Returns: + A `Tensor`, `StructuredTensor`, or `RaggedTensor`. + """ + if isinstance(key, list): + key = tuple(key) + elif not isinstance(key, tuple): + key = (key,) + if not key: + return self + + if self.rank == 0: + return self._scalar_getitem(key) + else: + return self._tensor_getitem(key) + + def _scalar_getitem(self, key): + if (isinstance(key[0], slice) and key[0].start is None and + key[0].stop is None and key[0].step is None): + fields = dict((field_name, field_value.__getitem__(key[1:])) + for (field_name, field_value) in self._fields.items()) + return StructuredTensor.from_fields(fields, self.shape) + + elif not isinstance(key[0], compat.bytes_or_text_types): + raise ValueError('Key for indexing a StructuredTensor must be a ' + "string or a full slice (':')") + + return self._fields[key[0]].__getitem__(key[1:]) + + def _tensor_getitem(self, key): + rank = self.rank + if len(key) <= rank: + new_fields = dict((field_name, field_value.__getitem__(key)) + for (field_name, field_value) in self._fields.items()) + result_shape = self.shape.as_list() + for d, k in enumerate(key): + if isinstance(k, slice): + if not (k.start is None and k.stop is None and k.step is None): + # TODO(edloper): Better static shape analysis here. + result_shape[d] = None + elif isinstance(k, (int, tensor.Tensor)): + result_shape[d] = -1 # mark for deletion + elif k is None: + raise ValueError('Slicing not supported for tf.newaxis') + else: + # Ellipsis, tf.newaxis: + raise ValueError('Slicing not supported for %r' % k) + result_shape = [d for d in result_shape if d != -1] + return StructuredTensor.from_fields(new_fields, result_shape) + + else: + if not isinstance(key[rank], compat.bytes_or_text_types): + # TODO(edloper): Also support full slice here? + raise ValueError('Key for indexing a StructuredTensor must be a string') + return self._fields[key[rank]].__getitem__(key[:rank] + key[rank + 1:]) + + def __repr__(self): + fields = sorted(self._fields.items()) + fields = ((k, str(v).replace('\n', '\n ')) for k, v in fields) + fields = ('"{}": {}'.format(k, v) for k, v in fields) + dict_repr = ',\n '.join(fields) + return ('' % (dict_repr, self.shape)) + + #============================================================================= + # Conversion + #============================================================================= + + def to_pyval(self): + """Returns this StructuredTensor as a nested Python dict or list of dicts. + + Converts this `StructuredTensor` to a nested python value: + + * `StructTensors` with `rank=0` are converted into a dictionary, with an + entry for each field. Field names are used as keys and field values are + converted to python values. In particular: + + * Scalar Tensor fields are converted to simple values (such as + `int` or `float` or `string`) + * Non-scalar Tensor fields and RaggedTensor fields are converted to + nested lists of simple values. + * StructuredTensor fields are converted recursively using `to_pyval`. + + * `StructTensors` with `rank>0` are converted to nested python `list`s, + containing one dictionary for each structure (where each structure's + dictionary is defined as described above). + + Requires that all fields are Eager tensors. + + >>> tf.experimental.StructuredTensor.from_fields( + ... {'a': [1, 2, 3]}, [3]).to_pyval() + [{'a': 1}, {'a': 2}, {'a': 3}] + + Note that `StructuredTensor.from_pyval(pyval).to_pyval() == pyval`. + + Returns: + A nested Python dict or list of dicts. + """ + if not self._is_eager(): + raise ValueError( + 'StructuredTensor.to_pyval() is only supported in eager mode.') + + # Convert each field value to a nested list. + result = {} + for (key, value) in self._fields.items(): + if isinstance(value, ops.EagerTensor): + value = value.numpy() + if isinstance(value, np.ndarray): + value = value.tolist() + elif isinstance(value, ragged_tensor.RaggedTensor): + value = value.to_list() + elif isinstance(value, StructuredTensor): + value = value.to_pyval() + # TODO(edloper): Throw an exception if value is an unexpected type. + result[key] = value + + # If rank>0, then re-group each value from dict-of-list to list-of-dict. + if len(self.shape) > 0: # pylint: disable=g-explicit-length-test + if not result: # special-case for StructuredTensors w/ no fields. + return _empty_dict_pylist_from_row_partitions(self.row_partitions, + self.nrows()) + return _pyval_field_major_to_node_major( + list(result.keys()), list(result.values()), self.rank) + else: + return result + + @classmethod + def from_pyval(cls, pyval, typespec=None): + """Constructs a StructuredTensor from a nested Python structure. + + >>> tf.experimental.StructuredTensor.from_pyval( + ... {'a': [1, 2, 3], 'b': [[4, 5], [6, 7]]}) + }, + shape=())> + + Note that `StructuredTensor.from_pyval(pyval).to_pyval() == pyval`. + + Args: + pyval: The nested Python structure that should be used to create the new + `StructuredTensor`. + typespec: A `StructuredTensor.Spec` specifying the expected type for each + field. If not specified, then all nested dictionaries are turned into + StructuredTensors, and all nested lists are turned into Tensors (if + rank<2) or RaggedTensors (if rank>=2). + + Returns: + A `StructuredTensor`. + """ + return cls._from_pyval(pyval, typespec, ()) + + @classmethod + def _from_pyval(cls, pyval, typespec, path_so_far): + """Helper function for from_pyval. + + + Args: + pyval: The nested Python structure that should be used to create the new + `StructuredTensor`. + typespec: A `StructuredTensor.Spec` specifying the expected type for each + field. If not specified, then all nested dictionaries are turned into + StructuredTensors, and all nested lists are turned into Tensors (if + rank<2) or RaggedTensors (if rank>=2). + path_so_far: the path of fields that led here (for error messages). + + Returns: + A `StructuredTensor`. + """ + if isinstance(pyval, dict): + return cls._from_pydict(pyval, typespec, path_so_far) + elif isinstance(pyval, (list, tuple)): + keys = set() + rank = _pyval_find_struct_keys_and_depth(pyval, keys) + if rank is not None: + return cls._from_pylist_of_dict(pyval, keys, rank, typespec, + path_so_far) + else: + return cls._from_pylist_of_value(pyval, typespec, path_so_far) + else: + return cls._from_pyscalar(pyval, typespec, path_so_far) + + @classmethod + def _from_pydict(cls, pyval, typespec, path_so_far): + """Converts python dictionary `pyval` to a StructuredTensor with rank=0.""" + if typespec is None: + fields = dict((k, cls._from_pyval(v, None, path_so_far + (k,))) + for (k, v) in pyval.items()) + else: + spec_shape = typespec._shape # pylint: disable=protected-access + field_specs = typespec._field_specs # pylint: disable=protected-access + if not (isinstance(typespec, StructuredTensor.Spec) and + spec_shape.rank == 0 and set(pyval) == set(field_specs)): + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, pyval, typespec)) + fields = dict((k, cls._from_pyval(v, field_specs[k], path_so_far + (k,))) + for (k, v) in pyval.items()) + return StructuredTensor.from_fields(fields=fields, shape=(), validate=False) + + @classmethod + def _from_pylist_of_dict(cls, pyval, keys, rank, typespec, path_so_far): + """Converts python list `pyval` to a StructuredTensor with rank>1.""" + fields = dict((key, []) for key in keys) + for child in pyval: + _pyval_update_fields(child, fields, 1) + if typespec is None: + shape = tensor_shape.TensorShape([None] * rank) + for (key, target) in fields.items(): + fields[key] = cls._from_pyval(target, None, path_so_far + (key,)) + else: + field_specs = typespec._fields # pylint: disable=protected-access + if ((not isinstance(typespec, StructuredTensor.Spec)) or # pylint: disable=superfluous-parens + (set(fields) - set(field_specs))): + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, pyval, typespec)) + shape = typespec._shape + if shape.rank < rank: + raise ValueError('Value at %r does not match typespec (rank mismatch): ' + '%r vs %r' % (path_so_far, pyval, typespec)) + for (key, spec) in field_specs.items(): + fields[key] = cls._from_pyval( + fields.get(key, []), spec, path_so_far + (key,)) + try: + if not fields and typespec is None: + # TODO(b/183245576): handle cases where the typespec is known + # but the dictionary is empty. + return StructuredTensor._from_pylist_of_empty_dict(pyval, rank) + return StructuredTensor.from_fields( + fields=fields, shape=shape, validate=False) + except Exception as exc: + raise ValueError('Error parsing path %r' % (path_so_far,)) from exc + + @classmethod + def _from_pylist_of_empty_dict(cls, pyval, rank): + """Converts a pylist of empty dictionaries to StructuredTensors.""" + if rank == 0: + return StructuredTensor.from_fields(fields={}, shape=(), validate=False) + elif rank == 1: + nrows = len(pyval) + shape = (nrows,) + return StructuredTensor.from_fields(fields={}, shape=shape, nrows=nrows) + elif rank > 1: + ragged_zeros = ragged_factory_ops.constant(_dicts_to_zeros(pyval)) + nrows = len(pyval) + shape = tensor_shape.TensorShape([len(pyval)] + ([None] * (rank - 1))) + return StructuredTensor.from_fields( + fields={}, + shape=shape, + row_partitions=ragged_zeros._nested_row_partitions, # pylint:disable=protected-access + nrows=nrows) + + @classmethod + def _from_pylist_of_value(cls, pyval, typespec, path_so_far): + """Converts python list `pyval` to a Tensor or RaggedTensor with rank>1.""" + if typespec is None: + try: + return ragged_factory_ops.constant(pyval) + except Exception as exc: + raise ValueError('Error parsing path %r' % (path_so_far,)) from exc + elif isinstance(typespec, tensor.TensorSpec): + try: + result = constant_op.constant(pyval, typespec.dtype) + except Exception as exc: + raise ValueError('Error parsing path %r' % (path_so_far,)) from exc + if not typespec.shape.is_compatible_with(result.shape): + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, typespec, pyval)) + return result + elif isinstance(typespec, ragged_tensor.RaggedTensorSpec): + # pylint: disable=protected-access + try: + return ragged_factory_ops.constant( + pyval, + dtype=typespec._dtype, + ragged_rank=typespec._ragged_rank, + row_splits_dtype=typespec._row_splits_dtype, + inner_shape=typespec._shape[typespec._ragged_rank + 1:]) + except Exception as exc: + raise ValueError('Error parsing path %r' % (path_so_far,)) from exc + elif isinstance(typespec, StructuredTensor.Spec): + empty_rank = _pyval_empty_list_depth(pyval) + if empty_rank is None: + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, typespec, pyval)) + else: + return cls._from_pylist_of_dict(pyval, set(), empty_rank, typespec, + path_so_far) + else: + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, typespec, pyval)) + + @classmethod + def _from_pyscalar(cls, pyval, typespec, path_so_far): + """Converts python scalar value `pyval` to a Tensor.""" + if typespec is None: + try: + return constant_op.constant(pyval) + except Exception as exc: + raise ValueError('Error parsing path %r' % (path_so_far,)) from exc + else: + if not (isinstance(typespec, tensor.TensorSpec) and + typespec.shape.rank == 0): + raise ValueError('Value at %r does not match typespec: %r vs %r' % + (path_so_far, typespec, pyval)) + # TODO(edloper): Check that typespec.shape matches. + return constant_op.constant(pyval, typespec.dtype) + + #============================================================================= + # Transforms + #============================================================================= + + # TODO(edloper): Add a 'validate' option here? + # TODO(edloper): Unify nomenclature with RaggedTensor. Should RaggedTensor + # have a partition_outer_dimension method? + def partition_outer_dimension(self, row_partition): + """Partitions the outer dimension of this StructuredTensor. + + Returns a new `StructuredTensor` with the same values as `self`, where + the outer dimension is partitioned into two (possibly ragged) dimensions. + Requires that this StructuredTensor have an outer dimension (i.e., + `self.shape.rank > 0`). + + >>> st = tf.experimental.StructuredTensor.from_pyval( + ... [{'foo': 12}, {'foo': 33}, {'foo': 99}]) + >>> partition = RowPartition.from_row_lengths([2, 0, 1]) + >>> st.partition_outer_dimension(partition) + }, + shape=(3, None))> + + Args: + row_partition: A `RowPartition`. + + Returns: + A `StructuredTensor` with rank `values.rank + 1`. + """ + if not isinstance(row_partition, RowPartition): + raise TypeError('row_partition must be a RowPartition.') + if self.shape.rank == 0: + raise ValueError('Shape %s must have rank at least 1' % self.shape) + return _partition_outer_dimension(self, row_partition) + + def merge_dims(self, outer_axis, inner_axis): + """Merges outer_axis...inner_axis into a single dimension. + + Returns a copy of this RaggedTensor with the specified range of dimensions + flattened into a single dimension, with elements in row-major order. + + >>> st = tf.experimental.StructuredTensor.from_pyval( + ... [[{'foo': 12}, {'foo': 33}], [], [{'foo': 99}]]) + >>> st.merge_dims(0, 1) + + + Args: + outer_axis: `int`: The first dimension in the range of dimensions to + merge. May be negative (to index from the last dimension). + inner_axis: `int`: The last dimension in the range of dimensions to merge. + May be negative (to index from the last dimension). + + Returns: + A copy of this tensor, with the specified dimensions merged into a + single dimension. The shape of the returned tensor will be + `self.shape[:outer_axis] + [N] + self.shape[inner_axis + 1:]`, where `N` + is the total number of slices in the merged dimensions. + """ + outer_axis = array_ops.get_positive_axis( + outer_axis, + self.shape.rank, + axis_name='outer_axis', + ndims_name='rank(self)') + inner_axis = array_ops.get_positive_axis( + inner_axis, + self.shape.rank, + axis_name='inner_axis', + ndims_name='rank(self)') + if not outer_axis <= inner_axis: + raise ValueError('Expected outer_axis (%d) to be less than or equal to ' + 'inner_axis (%d)' % (outer_axis, inner_axis)) + return _merge_dims(self, outer_axis, inner_axis) + + class Spec: + """A spec for StructuredTensor.""" + + def __validate__(self): + assert self._ragged_shape is not None + + @classmethod + def _from_fields_and_rank(cls, fields, rank): + """Creates a spec of a StructuredTensor with fields and rank.""" + shape = None + for (k, v) in fields.items(): + field_shape_untruncated = _dynamic_ragged_shape_spec_from_spec(v) + if field_shape_untruncated is None: + raise ValueError(f'Cannot convert spec of {k}.') + untruncated_rank = field_shape_untruncated.rank + if (untruncated_rank is not None and untruncated_rank < rank): + raise ValueError(f'Rank of field {k} is {untruncated_rank}, ' + f'but must be at least {rank}.') + field_shape = field_shape_untruncated._truncate(rank) # pylint: disable=protected-access + if shape is None: + shape = field_shape + else: + shape = shape._merge_with(field_shape) + return StructuredTensor.Spec(_ragged_shape=shape, _fields=fields) + + @classmethod + def _from_shape( + cls, shape: dynamic_ragged_shape.DynamicRaggedShape + ) -> 'StructuredTensor.Spec': + """Creates the spec of an empty StructuredTensor.""" + return StructuredTensor.Spec(_ragged_shape=shape, _fields={}) + + # For backwards compatibility + @property + def _shape(self) -> tensor_shape.TensorShape: + return self._ragged_shape._to_tensor_shape() # pylint: disable=protected-access + + # For backwards compatibility + @property + def _field_specs(self) -> Dict[str, type_spec.TypeSpec]: + return self._fields + + # For backwards compatibility + @property + def shape(self) -> tensor_shape.TensorShape: + return self._shape + + # For backwards compatibility + @property + def rank(self): + return self._ragged_shape.rank + + +# Regular expression used to determine whether a string is a valid field name. +# Note: we plan to relax (or possibly eliminate) this in the future; you +# should not rely on the fact that some field names are currently disallowed. +_FIELD_NAME_RE = re.compile('^[a-zA-Z][a-zA-Z0-9_]*$') + +#============================================================================= +# Helper functions +#============================================================================= +# TODO(edloper): Move some of these helpers to row_partition.py? + + +def _convert_to_structured_field_value(value): + """Converts `value` to a Tensor, RaggedTensor, or StructuredTensor.""" + if isinstance(value, + (tensor.Tensor, ragged_tensor.RaggedTensor, StructuredTensor)): + return value + elif ragged_tensor.is_ragged(value): + return ragged_tensor.convert_to_tensor_or_ragged_tensor(value) + elif isinstance(value, extension_type.ExtensionType): + return value + else: + try: + return ops.convert_to_tensor(value) + except (ValueError, TypeError) as e: + raise TypeError('Unexpected type for value in `fields`: %r' % + value) from e + + +def _find_shape_dtype( + fields: Mapping[str, _FieldValue], nrows: Optional[tensor.Tensor], + row_partitions: Optional[Sequence[RowPartition]]) -> dtypes.DType: + """Return a consistent dtype for fields, nrows, & row_partitions. + + In the future, the default will switch from int64 to int32, but for now, + we stick with int64. + + Args: + fields: the fields of the StructuredTensor. + nrows: the nrows of the StructuredTensor + row_partitions: the row_partitions of the StructuredTensor. + + Returns: + If anything requires int64, then return int64. + If int32 is explicitly specified, return int32. Otherwise, return int64. + """ + field_dtypes = [_field_shape_dtype(v) for v in fields.values()] + nrows_dtypes = [nrows.dtype] if isinstance(nrows, tensor.Tensor) else [] + rp_dtypes = [] if row_partitions is None else [ + rp.dtype for rp in row_partitions + ] + + all_dtypes = field_dtypes + nrows_dtypes + rp_dtypes + + if dtypes.int64 in all_dtypes: + return dtypes.int64 + if dtypes.int32 in all_dtypes: + return dtypes.int32 + + # TODO(martinz): Eventually, shift this to tf.int32. + return dtypes.int64 + + +def _merge_nrows(nrows, static_nrows, value, dtype, validate): + """Merges `nrows` with `nrows(value)`. + + Checks that `value` has the expected number of rows (`nrows`), and returns + `nrows`. If `validate` is true, then add validation ops that check that + the `nrows` values match. + + Args: + nrows: scalar integer Tensor. + static_nrows: tf.Dimension: static value of nrows, if known. + value: Tensor or RaggedTensor or StructuredTensor + dtype: dtype for `nrows`. + validate: bool -- whether to add validation ops. + + Returns: + A tuple `(nrows, static_nrows)`. + """ + static_value_nrows = tensor_shape.dimension_at_index(value.shape, 0) + if isinstance(value, tensor.Tensor): + value_nrows = array_ops.shape(value, out_type=dtype)[0] + else: + value_nrows = value.nrows() + if nrows is None: + nrows = value_nrows + elif (static_value_nrows.value is not None and + static_nrows.value is not None): + if not static_value_nrows.is_compatible_with(static_nrows): + raise ValueError('fields have incompatible nrows') + nrows = value_nrows # No need to add an assertion op. + elif validate: + nrows = control_flow_ops.with_dependencies([ + check_ops.assert_equal( + nrows, value_nrows, message='fields have incompatible nrows') + ], nrows) + return nrows, static_nrows._merge_with(static_value_nrows) # pylint: disable=protected-access + + +def _merge_row_partitions(row_partitions, value, rank, dtype, validate): + """Merges `row_partitions` with `row_partitions(value)`.""" + if isinstance(value, tensor.Tensor): + value_row_partitions = _row_partitions_for_tensor(value, rank, dtype) + + elif isinstance(value, ragged_tensor.RaggedTensor): + value_row_partitions = _row_partitions_for_ragged_tensor(value, rank, dtype) + + else: + assert isinstance(value, StructuredTensor), type(value) + value_row_partitions = value.row_partitions[:rank - 1] + + assert len(value_row_partitions) == rank - 1 + if row_partitions is None: + return tuple(value_row_partitions) + else: + return tuple([ + p1._merge_precomputed_encodings(p2, validate) # pylint: disable=protected-access + for (p1, p2) in zip(row_partitions, value_row_partitions) + ]) + + +def _row_partitions_for_tensor(value, rank, dtype): + """Returns the row partitions for a tf.Tensor.""" + shape = array_ops.shape(value, out_type=dtype) + return _row_partitions_for_uniform_shape(shape, rank) + + +def _row_partitions_for_ragged_tensor(value, rank, dtype): + """Returns the row partitions for a tf.RaggedTensor.""" + assert rank > 1 + value_row_partitions = value._nested_row_partitions[:rank - 1] # pylint: disable=protected-access + if len(value_row_partitions) < (rank - 1): + value_row_partitions += _row_partitions_for_tensor( + value.flat_values, rank - len(value_row_partitions), dtype) + assert len(value_row_partitions) == rank - 1 + return value_row_partitions + + +def _row_partitions_for_uniform_shape(shape, rank): + """Returns row partitions for the given shape Tensor. + + Args: + shape: A vector describing a uniform shape. + rank: The number of dimensions to generate row partitions for + + Returns: + A list of (rank-1) `RowPartition`s with uniform row length. + """ + shape_cumprod = math_ops.cumprod(shape[:rank]) + # pylint: disable=g-complex-comprehension + return tuple([ + RowPartition.from_uniform_row_length( + uniform_row_length=shape[i + 1], + nvals=shape_cumprod[i + 1], + nrows=shape_cumprod[i]) for i in range(rank - 1) + ]) + + +def _pyval_field_major_to_node_major(keys, values, depth): + """Regroup each field (k, v) from dict-of-list to list-of-dict. + + Given a "field-major" encoding of the StructuredTensor (which maps each key to + a single nested list containing the values for all structs), return a + corresponding "node-major" encoding, consisting of a nested list of dicts. + + Args: + keys: The field names (list of string). Must not be empty. + values: The field values (list of python values). Must have the same length + as `keys`. + depth: The list depth at which dictionaries should be created. + + Returns: + A nested list of dict, with depth `depth`. + """ + assert keys + if depth == 0: + return dict(zip(keys, values)) + nvals = len(values[0]) + assert all(nvals == len(values[i]) for i in range(1, len(values))) + return [ + _pyval_field_major_to_node_major(keys, value_slice, depth - 1) + for value_slice in zip(*values) + ] + + +def _empty_dict_pylist_from_row_partitions(row_partitions, nrows): + """Returns a python list of empty dicts from the given row partitions. + + Args: + row_partitions: The row-partitions describing the ragged shape of the + result. + nrows: The number of rows in the outermost row-partition. (Or if + `len(row_partitions)==0`, then the number of empty dicts to return.) + + Returns: + A nested python list whose leaves (if any) are empty python dicts. + """ + if not row_partitions: + return [{} for _ in range(nrows)] + else: + values = _empty_dict_pylist_from_row_partitions( + row_partitions[1:], row_partitions[0].row_splits()[-1]) + splits = row_partitions[0].row_splits() + return [values[splits[i]:splits[i + 1]] for i in range(len(splits) - 1)] + + +def _pyval_find_struct_keys_and_depth(pyval, keys): + """Finds the keys & depth of nested dictionaries in `pyval`. + + Args: + pyval: A nested structure of lists, tuples, and dictionaries. + keys: (output parameter) A set, which will be updated with any keys that are + found in the nested dictionaries. + + Returns: + The nesting depth of dictionaries in `pyval`, or `None` if `pyval` does + not contain any dictionaries. + Raises: + ValueError: If dictionaries have inconsistent depth. + """ + if isinstance(pyval, dict): + keys.update(pyval.keys()) + return 0 + elif isinstance(pyval, (list, tuple)): + depth = None + for child in pyval: + child_depth = _pyval_find_struct_keys_and_depth(child, keys) + if child_depth is not None: + if depth is None: + depth = child_depth + 1 + elif depth != child_depth + 1: + raise ValueError('Inconsistent depth of dictionaries') + return depth + else: + return None + + +def _pyval_update_fields(pyval, fields, depth): + """Append the field values from `pyval` to `fields`. + + Args: + pyval: A python `dict`, or nested list/tuple of `dict`, whose value(s) + should be appended to `fields`. + fields: A dictionary mapping string keys to field values. Field values + extracted from `pyval` are appended to this dictionary's values. + depth: The depth at which `pyval` should be appended to the field values. + """ + if not isinstance(pyval, (dict, list, tuple)): + raise ValueError('Expected dict or nested list/tuple of dict') + + for (key, target) in fields.items(): + for _ in range(1, depth): + target = target[-1] + target.append(pyval[key] if isinstance(pyval, dict) else []) + + if isinstance(pyval, (list, tuple)): + for child in pyval: + _pyval_update_fields(child, fields, depth + 1) + + +def _pyval_empty_list_depth(pyval): + """Find the max depth for nested empty lists. + + Args: + pyval: A nested python list. + + Returns: + The maximum depth of empty lists in `pyval`, or None if `pyval` contains + anything other than nested empty lists. + """ + if isinstance(pyval, list): + if not pyval: + return 1 + depths = [_pyval_empty_list_depth(v) for v in pyval] + if any(depth is None for depth in depths): + return None + else: + return max(depths) + 1 + else: + return None + + +def _replace_row_partitions(value, new_partitions): + """Updates `value` to use `new_partitions` as its (outer) row partitions. + + This is used to ensure that all fields in a `StructuredTensor` use identical + `RowPartition` objects for the shared dimensions. In particular, + `StructuredTensor.from_fields` first merges all of the row partitions from + any fields, and then replaces the outer row partitions of all fields with + the merged row partitions (using this function). + + Args: + value: A `Tensor`, `RaggedTensor`, or `StructuredTensor`. + new_partitions: A list of row-partitions that should be used by `value`. + Must be equivalent to `value`'s current row partitions. + + Returns: + A value that is equivalent to `value`, where outer row partitions have been + replaced by `new_partitions`. + """ + if isinstance(value, tensor.Tensor) or not new_partitions: + return value + + elif isinstance(value, ragged_tensor.RaggedTensor): + return ragged_tensor.RaggedTensor._from_row_partition( # pylint: disable=protected-access + values=_replace_row_partitions(value.values, new_partitions[1:]), + row_partition=new_partitions[0]) + + else: + assert isinstance(value, StructuredTensor) + new_fields = dict((k, _replace_row_partitions(v, new_partitions)) + for (k, v) in value._fields.items()) + return StructuredTensor._old_init( # pylint: disable=protected-access + fields=new_fields, + shape=value.shape, + nrows=value.nrows(), + row_partitions=tuple(new_partitions) + + tuple(value.row_partitions[len(new_partitions):])) + + +def _partition_outer_dimension(value, row_partition): + """Partitions the outer dimension of `value` using `row_partitions`. + + Examples: + + >>> partition = RowPartition.from_row_lengths([2, 0, 1]) + >>> _partition_outer_dimension(tf.constant([1, 2, 3]), partition) + + + >>> struct_value = tf.experimental.StructuredTensor.from_pyval( + ... [{'x': 1}, {'x': 2}, {'x': 3}]) + >>> _partition_outer_dimension(struct_value, partition) + }, + shape=(3, None))> + + Args: + value: Tensor, RaggedTensor, or StructuredTensor + row_partition: RowPartition + + Returns: + A value with the same type as `value`, where + `result.rank = value.rank + 1`. + """ + is_ragged = row_partition.uniform_row_length() is None + if isinstance(value, tensor.Tensor) and not is_ragged: + new_shape = array_ops.concat( + [[row_partition.nrows(), + row_partition.uniform_row_length()], + array_ops.shape(value, out_type=row_partition.dtype)[1:]], + axis=0) + return array_ops.reshape(value, new_shape) + elif isinstance(value, (tensor.Tensor, ragged_tensor.RaggedTensor)): + return ragged_tensor.RaggedTensor._from_row_partition( # pylint: disable=protected-access + value, row_partition) + else: + assert isinstance(value, StructuredTensor) + nrows = row_partition.static_nrows + ncols = row_partition.static_uniform_row_length + shape = tensor_shape.TensorShape([nrows, + ncols]).concatenate(value.shape[1:]) + fields = dict((k, _partition_outer_dimension(v, row_partition)) + for (k, v) in value._fields.items()) + return StructuredTensor._old_init( # pylint: disable=protected-access + fields, shape, row_partition.nrows(), + (row_partition,) + value.row_partitions) + + +def _merge_dims(value, outer_axis, inner_axis): + """Merges `outer_axis...inner_axis` of `value` into a single dimension.""" + assert outer_axis < inner_axis + if isinstance(value, (tensor.Tensor, ragged_tensor.RaggedTensor)): + return ragged_tensor.merge_dims(value, outer_axis, inner_axis) + else: + assert isinstance(value, StructuredTensor) + fields = dict((k, _merge_dims(v, outer_axis, inner_axis)) + for (k, v) in value._fields.items()) + ragged_shape = value._ragged_shape._merge_dims( # pylint: disable=protected-access + outer_axis, inner_axis) + return StructuredTensor(fields, ragged_shape) + + +_structured_tensor_factory_key = object() # unique private object + + +def _dynamic_ragged_shape_spec_from_spec( + spec: Union[dynamic_ragged_shape.DynamicRaggedShape.Spec, + ragged_tensor.RaggedTensorSpec, StructuredTensor.Spec, + tensor.TensorSpec] +) -> dynamic_ragged_shape.DynamicRaggedShape.Spec: + if isinstance(spec, StructuredTensor.Spec): + return spec._ragged_shape # pylint: disable=protected-access + else: + return dynamic_ragged_shape.DynamicRaggedShape.Spec._from_spec(spec) # pylint: disable=protected-access + + +def _normalize_field_name_to_tuple(name: 'FieldName') -> Sequence[str]: + """FieldName can be given also as string, this normalizes it to a tuple.""" + if isinstance(name, str): + return (name,) + if isinstance(name, list): + return tuple(name) + assert isinstance(name, tuple) + return name + + +def _dicts_to_zeros(pyval): + """Replaces dictionaries zeros in a pylist.""" + if isinstance(pyval, dict): + return 0 + return [_dicts_to_zeros(x) for x in pyval] + + +def _merge_dims_generic(source, outer, inner): + """Merges outer_axis...inner_axis into a single dimension. + + If outer == inner, this is a NOOP. If inner < outer, then this fials. + If inner >= source.shape.rank, then the behavior is undefined. + + Args: + source: a tensor, ragged tensor, or structured tensor. + outer: a python int, indicating the first dimension to compress (must be + nonnegative). + inner: a python int, indicating the first dimension to keep (of the tail) + (must be nonnegative). + + Returns: + source with outer_axis...inner_axis merged into a single dimension. + + """ + if isinstance(source, StructuredTensor): + return source.merge_dims(outer, inner) + else: + return ragged_tensor.merge_dims(source, outer, inner) + + +def _dynamic_ragged_shape_from_tensor( + field, dtype=None) -> dynamic_ragged_shape.DynamicRaggedShape: + """Extension of DynamicRaggedShape.from_tensor to support StructuredTensor.""" + if isinstance(field, StructuredTensor): + return field._ragged_shape # pylint: disable=protected-access + shape = array_ops.shape_v2(field, out_type=dtype) + + if isinstance(shape, tensor.Tensor): + return dynamic_ragged_shape.DynamicRaggedShape( + row_partitions=[], inner_shape=shape) + elif isinstance(shape, dynamic_ragged_shape.DynamicRaggedShape): + return shape + # TODO(martinz): add a test for the following line. + raise TypeError(f'Expected shape tf.shape({field}) to return a Tensor or a ' + f'DynamicRaggedShape. Instead, got: {shape}.') + + +def _merge_with_optional( + a: Optional[dynamic_ragged_shape.DynamicRaggedShape], + b: Optional[dynamic_ragged_shape.DynamicRaggedShape] +) -> Optional[dynamic_ragged_shape.DynamicRaggedShape]: + if a is None: + return b + if b is None: + return a + return a._merge_with(b) # pylint: disable=protected-access + + +def _shape_from_fields( + fields, rank: int, + dtype: dtypes.DType) -> Optional[dynamic_ragged_shape.DynamicRaggedShape]: + """Given fields, rank, and dtype, create a shape.""" + + field_shape = None + for (k, field) in fields.items(): + try: + next_field_shape_raw = _dynamic_ragged_shape_from_tensor( + field, dtype=dtype) + next_field_shape = next_field_shape_raw[:rank] + field_shape = _merge_with_optional(field_shape, next_field_shape) + except Exception as err: + raise ValueError(f'Error in shape of {k}') from err + + return field_shape + + +def _field_shape_dtype(field: _FieldValue) -> Optional[dtypes.DType]: + if isinstance(field, ragged_tensor.RaggedTensor): + return field._row_partition.dtype # pylint: disable=protected-access + if isinstance(field, StructuredTensor): + return field._ragged_shape.dtype # pylint: disable=protected-access + return None + + +def _field_with_shape_dtype(field: _FieldValue, + dtype: dtypes.DType) -> _FieldValue: + if isinstance(field, ragged_tensor.RaggedTensor): + return field.with_row_splits_dtype(dtype) + if isinstance(field, StructuredTensor): + return field.with_shape_dtype(dtype) + + return field + + +def _fields_with_dtype(fields: Mapping[str, _FieldValue], + dtype: dtypes.DType) -> Mapping[str, _FieldValue]: + return {k: _field_with_shape_dtype(v, dtype) for (k, v) in fields.items()} + + +# pylint:disable=protected-access +def _dynamic_ragged_shape_init(fields, shape, nrows, row_partitions): + """Produce a DynamicRaggedShape for StructuredTensor.""" + assert isinstance(fields, dict), fields + assert isinstance(shape, tensor_shape.TensorShape), shape + assert nrows is None or isinstance(nrows, tensor.Tensor) or isinstance( + nrows, int), nrows + assert row_partitions is None or isinstance(row_partitions, + tuple), row_partitions + rank = shape.rank + + if rank is None: + raise TypeError("StructuredTensor's shape must have known rank.") + + # TODO(martinz): figure out whether to validate. + dtype = _find_shape_dtype(fields, nrows, row_partitions) + + fields = _fields_with_dtype(fields, dtype) + + result = None + if shape.is_fully_defined(): + result = dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape( + shape.as_list(), dtype=dtype) + + if rank == 0: + return dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape( + array_ops.zeros((0,), dtype=dtype)) + + result = _merge_with_optional(result, _shape_from_fields(fields, rank, dtype)) + if rank == 1: + alt_value = tensor_shape.dimension_value(shape[0]) + if alt_value is not None: + nrows = alt_value + if nrows is not None: + result = _merge_with_optional( + result, + dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape( + [nrows], dtype=dtype)) + if result is None: + raise ValueError('Must specify `nrows`, a fully specified `shape`,' + + ' or have `fields` if `rank=1`') + + return result + + if row_partitions: + result = _merge_with_optional( + result, + dynamic_ragged_shape.DynamicRaggedShape.from_row_partitions( + row_partitions, dtype=dtype)) + + if result is None: + raise ValueError('Must specify row_partitions, a fully specified shape, ' + + 'or have fields if rank > 1') + return result + + +# TODO(martinz): Drop this method or rename. +def StructuredTensorSpec(shape, field_specs): # pylint:disable=invalid-name + """A placeholder for the old StructuredTensorSpec.""" + if not isinstance(field_specs, dict): + raise TypeError('field_specs must be a dictionary.') + for k in field_specs.keys(): + if not isinstance(k, str): + raise TypeError('field_specs must be a dictionary with string keys.') + for v in field_specs.values(): + if not isinstance(v, type_spec.TypeSpec): + raise TypeError('field_specs must be a dictionary with TypeSpec values.') + + shape = dynamic_ragged_shape.DynamicRaggedShape.Spec._from_tensor_shape( + tensor_shape.as_shape(shape), 0, dtypes.int32) + rank = shape.rank + if rank is None: + raise TypeError("StructuredTensor's shape must have known rank.") + for (k, v) in field_specs.items(): + field_shape_untruncated = _dynamic_ragged_shape_spec_from_spec(v) + if field_shape_untruncated is None: + raise ValueError(f'Cannot convert spec of {k}.') + untruncated_rank = field_shape_untruncated.rank + if (untruncated_rank is not None and untruncated_rank < rank): + raise ValueError(f'Rank of field {k} is {untruncated_rank},' + f' but must be at least {rank}.') + field_shape = field_shape_untruncated._truncate(rank) + shape = shape._merge_with(field_shape) + return StructuredTensor.Spec(_ragged_shape=shape, _fields=field_specs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor_dynamic.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor_dynamic.py new file mode 100644 index 0000000000000000000000000000000000000000..8aa434831e616ac6548fd0e8b5986ce4641a837e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/structured/structured_tensor_dynamic.py @@ -0,0 +1,52 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Dynamic shape for structured Tensors.""" + +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops.ragged import dynamic_ragged_shape +from tensorflow.python.ops.structured.structured_tensor import _find_shape_dtype + + +# pylint:disable=protected-access +def _dynamic_ragged_shape_init(fields, shape, nrows, row_partitions): + """Produce a DynamicRaggedShape for StructuredTensor.""" + assert isinstance(fields, dict), fields + assert isinstance(shape, tensor_shape.TensorShape), shape + assert nrows is None or isinstance(nrows, tensor.Tensor), nrows + assert isinstance(row_partitions, tuple), row_partitions + + rank = shape.rank + if rank is None: + raise TypeError("StructuredTensor's shape must have known rank.") + + # TODO(martinz): figure out whether to validate. + dtype = _find_shape_dtype(fields, nrows, row_partitions) + if rank == 0: + return dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape( + array_ops.zeros((0,), dtype=dtype)) + + if rank == 1: + alt_value = shape[0] + if isinstance(alt_value, tensor_shape.Dimension): + alt_value = alt_value.value + if alt_value is not None: + nrows = alt_value + return dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape( + [nrows], dtype=dtype) + + return dynamic_ragged_shape.DynamicRaggedShape.from_row_partitions( + row_partitions, dtype=dtype) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_op_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_op_util.py new file mode 100644 index 0000000000000000000000000000000000000000..eb0c71082b8bf0fba1e050d6b1459338478a1ebb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_op_util.py @@ -0,0 +1,104 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +#============================================================================== +"""Contains utility functions used by summary ops.""" + +import contextlib +import re + +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging + + +def collect(val, collections, default_collections): + """Adds keys to a collection. + + Args: + val: The value to add per each key. + collections: A collection of keys to add. + default_collections: Used if collections is None. + """ + if collections is None: + collections = default_collections + for key in collections: + ops.add_to_collection(key, val) + + +_INVALID_TAG_CHARACTERS = re.compile(r'[^-/\w\.]') + + +def clean_tag(name): + """Cleans a tag. Removes illegal characters for instance. + + Args: + name: The original tag name to be processed. + + Returns: + The cleaned tag name. + """ + # In the past, the first argument to summary ops was a tag, which allowed + # arbitrary characters. Now we are changing the first argument to be the node + # name. This has a number of advantages (users of summary ops now can + # take advantage of the tf name scope system) but risks breaking existing + # usage, because a much smaller set of characters are allowed in node names. + # This function replaces all illegal characters with _s, and logs a warning. + # It also strips leading slashes from the name. + if name is not None: + new_name = _INVALID_TAG_CHARACTERS.sub('_', name) + new_name = new_name.lstrip('/') # Remove leading slashes + if new_name != name: + tf_logging.info('Summary name %s is illegal; using %s instead.' % + (name, new_name)) + name = new_name + return name + + +@contextlib.contextmanager +def summary_scope(name, family=None, default_name=None, values=None): + """Enters a scope used for the summary and yields both the name and tag. + + To ensure that the summary tag name is always unique, we create a name scope + based on `name` and use the full scope name in the tag. + + If `family` is set, then the tag name will be '/', where + `scope_name` is `//`. This ensures that `family` + is always the prefix of the tag (and unmodified), while ensuring the scope + respects the outer scope from this summary was created. + + Args: + name: A name for the generated summary node. + family: Optional; if provided, used as the prefix of the summary tag name. + default_name: Optional; if provided, used as default name of the summary. + values: Optional; passed as `values` parameter to name_scope. + + Yields: + A tuple `(tag, scope)`, both of which are unique and should be used for the + tag and the scope for the summary to output. + """ + name = clean_tag(name) + family = clean_tag(family) + # Use family name in the scope to ensure uniqueness of scope/tag. + scope_base_name = name if family is None else '{}/{}'.format(family, name) + with ops.name_scope( + scope_base_name, default_name, values, skip_on_eager=False) as scope: + if family is None: + tag = scope.rstrip('/') + else: + # Prefix our scope with family again so it displays in the right tab. + tag = '{}/{}'.format(family, scope.rstrip('/')) + # Note: tag is not 100% unique if the user explicitly enters a scope with + # the same name as family, then later enter it again before summaries. + # This is very contrived though, and we opt here to let it be a runtime + # exception if tags do indeed collide. + yield (tag, scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_ops_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_ops_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfa8a8b18c26077d8e613fc77f2b5f03a7f63c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/summary_ops_v2.py @@ -0,0 +1,1452 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations to emit summaries.""" + +import abc +import collections +import functools +import os +import re +import threading + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import summary_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.dtensor.python import api as dtensor_api +from tensorflow.dtensor.python import layout as layout_lib +from tensorflow.python.eager import context +from tensorflow.python.eager import profiler as _profiler +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gen_summary_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import summary_op_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import resource +from tensorflow.python.training import training_util +from tensorflow.python.util import deprecation +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + + +# Name for graph collection of summary writer init ops, which is only exposed +# as a legacy API for tf.contrib.summary in TF 1.x. +_SUMMARY_WRITER_INIT_COLLECTION_NAME = "_SUMMARY_WRITER_V2" + + +class _SummaryState(threading.local): + + def __init__(self): + super(_SummaryState, self).__init__() + self.is_recording = None + # TODO(slebedev): why a separate flag for DS and is it on by default? + self.is_recording_distribution_strategy = True + self.writer = None + self.step = None + + +_summary_state = _SummaryState() + + +class _SummaryContextManager: + """Context manager to implement SummaryWriter.as_default().""" + # Note: this is a class so that it's possible to implement `set_as_default()` + # simply via `as_default().__enter__()`. We can't do that with @contextmanager + # because the `finally` block will be executed when the generator is GCed. + + def __init__(self, writer, step=None): + self._writer = writer + self._step = step + self._old_writer = None + self._old_step = None + + def __enter__(self): + self._old_writer = _summary_state.writer + _summary_state.writer = self._writer + if self._step is not None: + self._old_step = _summary_state.step + _summary_state.step = self._step + return self._writer + + def __exit__(self, *exc): + # Flushes the summary writer in eager mode or in graph functions, but + # not in legacy graph mode (you're on your own there). + _summary_state.writer.flush() + _summary_state.writer = self._old_writer + if self._step is not None: + _summary_state.step = self._old_step + return False + + +def _should_record_summaries_internal(default_state): + """Returns boolean Tensor if summaries should/shouldn't be recorded. + + Now the summary condition is decided by logical "and" of below conditions: + First, summary writer must be set. Given this constraint is met, + ctx.summary_recording and ctx.summary_recording_distribution_strategy. + The former one is usually set by user, and the latter one is controlled + by DistributionStrategy (tf.distribute.ReplicaContext). + + Args: + default_state: can be True or False. The default summary behavior when + summary writer is set and the user does not specify + ctx.summary_recording and ctx.summary_recording_distribution_strategy + is True. + """ + if _summary_state.writer is None: + return constant_op.constant(False) + + if not callable(_summary_state.is_recording): + static_cond = tensor_util.constant_value(_summary_state.is_recording) + if static_cond is not None and not static_cond: + return constant_op.constant(False) + + resolve = lambda x: x() if callable(x) else x + cond_distributed = resolve(_summary_state.is_recording_distribution_strategy) + cond = resolve(_summary_state.is_recording) + if cond is None: + cond = default_state + return math_ops.logical_and(cond_distributed, cond) + + +@tf_export("summary.should_record_summaries", v1=[]) +def should_record_summaries(): + """Returns boolean Tensor which is True if summaries will be recorded. + + If no default summary writer is currently registered, this always returns + False. Otherwise, this reflects the recording condition has been set via + `tf.summary.record_if()` (except that it may return False for some replicas + when using `tf.distribute.Strategy`). If no recording condition is active, + it defaults to True. + """ + return _should_record_summaries_internal(default_state=True) + + +# Legacy symbol used by tf.contrib.summary.should_record_summaries. +def _legacy_contrib_should_record_summaries(): + """Returns boolean Tensor which is true if summaries should be recorded.""" + return _should_record_summaries_internal(default_state=False) + + +@tf_export("summary.record_if", v1=[]) +@tf_contextlib.contextmanager +def record_if(condition): + """Sets summary recording on or off per the provided boolean value. + + The provided value can be a python boolean, a scalar boolean Tensor, or + or a callable providing such a value; if a callable is passed it will be + invoked on-demand to determine whether summary writing will occur. Note that + when calling record_if() in an eager mode context, if you intend to provide a + varying condition like `step % 100 == 0`, you must wrap this in a + callable to avoid immediate eager evaluation of the condition. In particular, + using a callable is the only way to have your condition evaluated as part of + the traced body of an @tf.function that is invoked from within the + `record_if()` context. + + Args: + condition: can be True, False, a bool Tensor, or a callable providing such. + + Yields: + Returns a context manager that sets this value on enter and restores the + previous value on exit. + """ + old = _summary_state.is_recording + try: + _summary_state.is_recording = condition + yield + finally: + _summary_state.is_recording = old + + +def has_default_writer(): + """Returns a boolean indicating whether a default summary writer exists.""" + return _summary_state.writer is not None + + +# TODO(apassos) consider how to handle local step here. +def record_summaries_every_n_global_steps(n, global_step=None): + """Sets the should_record_summaries Tensor to true if global_step % n == 0.""" + if global_step is None: + global_step = training_util.get_or_create_global_step() + with ops.device("cpu:0"): + should = lambda: math_ops.equal(global_step % n, 0) + if not context.executing_eagerly(): + should = should() + return record_if(should) + + +def always_record_summaries(): + """Sets the should_record_summaries Tensor to always true.""" + return record_if(True) + + +def never_record_summaries(): + """Sets the should_record_summaries Tensor to always false.""" + return record_if(False) + + +@tf_export("summary.experimental.get_step", v1=[]) +def get_step(): + """Returns the default summary step for the current thread. + + Returns: + The step set by `tf.summary.experimental.set_step()` if one has been set, + otherwise None. + """ + return _summary_state.step + + +@tf_export("summary.experimental.set_step", v1=[]) +def set_step(step): + """Sets the default summary step for the current thread. + + For convenience, this function sets a default value for the `step` parameter + used in summary-writing functions elsewhere in the API so that it need not + be explicitly passed in every such invocation. The value can be a constant + or a variable, and can be retrieved via `tf.summary.experimental.get_step()`. + + Note: when using this with @tf.functions, the step value will be captured at + the time the function is traced, so changes to the step outside the function + will not be reflected inside the function unless using a `tf.Variable` step. + + Args: + step: An `int64`-castable default step value, or None to unset. + """ + _summary_state.step = step + + +@tf_export("summary.SummaryWriter", v1=[]) +class SummaryWriter(metaclass=abc.ABCMeta): + """Interface representing a stateful summary writer object.""" + + def set_as_default(self, step=None): + """Enables this summary writer for the current thread. + + For convenience, if `step` is not None, this function also sets a default + value for the `step` parameter used in summary-writing functions elsewhere + in the API so that it need not be explicitly passed in every such + invocation. The value can be a constant or a variable. + + Note: when setting `step` in a @tf.function, the step value will be + captured at the time the function is traced, so changes to the step outside + the function will not be reflected inside the function unless using + a `tf.Variable` step. + + Args: + step: An `int64`-castable default step value, or `None`. When not `None`, + the current step is modified to the given value. When `None`, the + current step is not modified. + """ + self.as_default(step).__enter__() + + def as_default(self, step=None): + """Returns a context manager that enables summary writing. + + For convenience, if `step` is not None, this function also sets a default + value for the `step` parameter used in summary-writing functions elsewhere + in the API so that it need not be explicitly passed in every such + invocation. The value can be a constant or a variable. + + Note: when setting `step` in a @tf.function, the step value will be + captured at the time the function is traced, so changes to the step outside + the function will not be reflected inside the function unless using + a `tf.Variable` step. + + For example, `step` can be used as: + + ```python + with writer_a.as_default(step=10): + tf.summary.scalar(tag, value) # Logged to writer_a with step 10 + with writer_b.as_default(step=20): + tf.summary.scalar(tag, value) # Logged to writer_b with step 20 + tf.summary.scalar(tag, value) # Logged to writer_a with step 10 + ``` + + Args: + step: An `int64`-castable default step value, or `None`. When not `None`, + the current step is captured, replaced by a given one, and the original + one is restored when the context manager exits. When `None`, the current + step is not modified (and not restored when the context manager exits). + + Returns: + The context manager. + """ + return _SummaryContextManager(self, step) + + def init(self): + """Initializes the summary writer.""" + raise NotImplementedError() + + def flush(self): + """Flushes any buffered data.""" + raise NotImplementedError() + + def close(self): + """Flushes and closes the summary writer.""" + raise NotImplementedError() + + +class _ResourceSummaryWriter(SummaryWriter): + """Implementation of SummaryWriter using a SummaryWriterInterface resource.""" + + def __init__(self, create_fn, init_op_fn, mesh=None): + if mesh is not None: + with dtensor_api.default_mesh(mesh.host_mesh()): + self._resource = create_fn() + self._init_op = init_op_fn(self._resource) + else: + self._resource = create_fn() + self._init_op = init_op_fn(self._resource) + + self._closed = False + if context.executing_eagerly(): + self._set_up_resource_deleter() + else: + ops.add_to_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME, self._init_op) + + self._mesh = mesh + + # Extension point to be overridden by subclasses to customize deletion. + + def _set_up_resource_deleter(self): + self._resource_deleter = resource_variable_ops.EagerResourceDeleter( + handle=self._resource, handle_device="cpu:0") + + def set_as_default(self, step=None): + """See `SummaryWriter.set_as_default`.""" + if context.executing_eagerly() and self._closed: + raise RuntimeError(f"SummaryWriter {self!r} is already closed") + super().set_as_default(step) + + def as_default(self, step=None): + """See `SummaryWriter.as_default`.""" + if context.executing_eagerly() and self._closed: + raise RuntimeError(f"SummaryWriter {self!r} is already closed") + return super().as_default(step) + + def init(self): + """See `SummaryWriter.init`.""" + if context.executing_eagerly() and self._closed: + raise RuntimeError(f"SummaryWriter {self!r} is already closed") + return self._init_op + + def flush(self): + """See `SummaryWriter.flush`.""" + if context.executing_eagerly() and self._closed: + return + with ops.device("cpu:0"): + return gen_summary_ops.flush_summary_writer(self._resource) + + def close(self): + """See `SummaryWriter.close`.""" + if context.executing_eagerly() and self._closed: + return + try: + with ops.control_dependencies([self.flush()]): + with ops.device("cpu:0"): + return gen_summary_ops.close_summary_writer(self._resource) + finally: + if context.executing_eagerly(): + self._closed = True + + +class _MultiMetaclass( + type(_ResourceSummaryWriter), type(resource.TrackableResource)): + pass + + +class _TrackableResourceSummaryWriter( + _ResourceSummaryWriter, + resource.TrackableResource, + metaclass=_MultiMetaclass): + """A `_ResourceSummaryWriter` subclass that implements `TrackableResource`.""" + + def __init__(self, create_fn, init_op_fn, mesh=None): + # Resolve multiple inheritance via explicit calls to __init__() on parents. + resource.TrackableResource.__init__(self, device="/CPU:0") + self._create_fn = create_fn + self._init_op_fn = init_op_fn + # Pass .resource_handle into _ResourceSummaryWriter parent class rather than + # create_fn, to ensure it accesses the resource handle only through the + # cached property so that everything is using a single resource handle. + _ResourceSummaryWriter.__init__( + self, + create_fn=lambda: self.resource_handle, + init_op_fn=init_op_fn, + mesh=mesh, + ) + + # Override for TrackableResource implementation. + def _create_resource(self): + return self._create_fn() + + # Override for TrackableResource implementation. + def _initialize(self): + return self._init_op_fn(self.resource_handle) + + # Override for TrackableResource implementation. + def _destroy_resource(self): + gen_resource_variable_ops.destroy_resource_op( + self.resource_handle, ignore_lookup_error=True) + + def _set_up_resource_deleter(self): + # Override to suppress ResourceSummaryWriter implementation; we don't need + # the deleter since TrackableResource.__del__() handles it for us. + pass + + +class _LegacyResourceSummaryWriter(SummaryWriter): + """Legacy resource-backed SummaryWriter for tf.contrib.summary.""" + + def __init__(self, resource, init_op_fn): + self._resource = resource + self._init_op_fn = init_op_fn + init_op = self.init() + if context.executing_eagerly(): + self._resource_deleter = resource_variable_ops.EagerResourceDeleter( + handle=self._resource, handle_device="cpu:0") + else: + ops.add_to_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME, init_op) + + def init(self): + """See `SummaryWriter.init`.""" + return self._init_op_fn(self._resource) + + def flush(self): + """See `SummaryWriter.flush`.""" + with ops.device("cpu:0"): + return gen_summary_ops.flush_summary_writer(self._resource) + + def close(self): + """See `SummaryWriter.close`.""" + with ops.control_dependencies([self.flush()]): + with ops.device("cpu:0"): + return gen_summary_ops.close_summary_writer(self._resource) + + +class _NoopSummaryWriter(SummaryWriter): + """A summary writer that does nothing, for create_noop_writer().""" + + def set_as_default(self, step=None): + pass + + @tf_contextlib.contextmanager + def as_default(self, step=None): + yield + + def init(self): + pass + + def flush(self): + pass + + def close(self): + pass + + +@tf_export(v1=["summary.initialize"]) +def initialize( + graph=None, # pylint: disable=redefined-outer-name + session=None): + """Initializes summary writing for graph execution mode. + + This operation is a no-op when executing eagerly. + + This helper method provides a higher-level alternative to using + `tf.contrib.summary.summary_writer_initializer_op` and + `tf.contrib.summary.graph`. + + Most users will also want to call `tf.compat.v1.train.create_global_step` + which can happen before or after this function is called. + + Args: + graph: A `tf.Graph` or `tf.compat.v1.GraphDef` to output to the writer. + This function will not write the default graph by default. When + writing to an event log file, the associated step will be zero. + session: So this method can call `tf.Session.run`. This defaults + to `tf.compat.v1.get_default_session`. + + Raises: + RuntimeError: If the current thread has no default + `tf.contrib.summary.SummaryWriter`. + ValueError: If session wasn't passed and no default session. + """ + if context.executing_eagerly(): + return + if _summary_state.writer is None: + raise RuntimeError("No default tf.contrib.summary.SummaryWriter found") + if session is None: + session = ops.get_default_session() + if session is None: + raise ValueError("Argument `session must be passed if no default " + "session exists") + session.run(summary_writer_initializer_op()) + if graph is not None: + data = _serialize_graph(graph) + x = array_ops.placeholder(dtypes.string) + session.run(graph_v1(x, 0), feed_dict={x: data}) + + +@tf_export("summary.create_file_writer", v1=[]) +def create_file_writer_v2( + logdir, + max_queue=None, + flush_millis=None, + filename_suffix=None, + name=None, + experimental_trackable=False, + experimental_mesh=None, +): + """Creates a summary file writer for the given log directory. + + Args: + logdir: a string specifying the directory in which to write an event file. + max_queue: the largest number of summaries to keep in a queue; will flush + once the queue gets bigger than this. Defaults to 10. + flush_millis: the largest interval between flushes. Defaults to 120,000. + filename_suffix: optional suffix for the event file name. Defaults to `.v2`. + name: a name for the op that creates the writer. + experimental_trackable: a boolean that controls whether the returned writer + will be a `TrackableResource`, which makes it compatible with SavedModel + when used as a `tf.Module` property. + experimental_mesh: a `tf.experimental.dtensor.Mesh` instance. When running + with DTensor, the mesh (experimental_mesh.host_mesh()) will be used for + bringing all the DTensor logging from accelerator to CPU mesh. + + Returns: + A SummaryWriter object. + """ + # TODO(b/291655717): Revisit the experimental_mesh once we have soft placment. + if logdir is None: + raise ValueError("Argument `logdir` cannot be None") + inside_function = ops.inside_function() + with ops.name_scope(name, "create_file_writer") as scope, ops.device("cpu:0"): + # Run init inside an init_scope() to hoist it out of tf.functions. + with ops.init_scope(): + if context.executing_eagerly(): + _check_create_file_writer_args( + inside_function, + logdir=logdir, + max_queue=max_queue, + flush_millis=flush_millis, + filename_suffix=filename_suffix) + logdir = ops.convert_to_tensor(logdir, dtype=dtypes.string) + if max_queue is None: + max_queue = constant_op.constant(10) + if flush_millis is None: + flush_millis = constant_op.constant(2 * 60 * 1000) + if filename_suffix is None: + filename_suffix = constant_op.constant(".v2") + + def create_fn(): + # Use unique shared_name to prevent resource sharing in eager mode, but + # otherwise use a fixed shared_name to allow SavedModel TF 1.x loading. + if context.executing_eagerly(): + shared_name = context.anonymous_name() + else: + shared_name = ops.name_from_scope_name(scope) # pylint: disable=protected-access + return gen_summary_ops.summary_writer( + shared_name=shared_name, name=name) + + init_op_fn = functools.partial( + gen_summary_ops.create_summary_file_writer, + logdir=logdir, + max_queue=max_queue, + flush_millis=flush_millis, + filename_suffix=filename_suffix) + if experimental_trackable: + return _TrackableResourceSummaryWriter( + create_fn=create_fn, init_op_fn=init_op_fn, mesh=experimental_mesh + ) + else: + return _ResourceSummaryWriter( + create_fn=create_fn, init_op_fn=init_op_fn, mesh=experimental_mesh + ) + + +def create_file_writer(logdir, + max_queue=None, + flush_millis=None, + filename_suffix=None, + name=None): + """Creates a summary file writer in the current context under the given name. + + Args: + logdir: a string, or None. If a string, creates a summary file writer + which writes to the directory named by the string. If None, returns + a mock object which acts like a summary writer but does nothing, + useful to use as a context manager. + max_queue: the largest number of summaries to keep in a queue; will + flush once the queue gets bigger than this. Defaults to 10. + flush_millis: the largest interval between flushes. Defaults to 120,000. + filename_suffix: optional suffix for the event file name. Defaults to `.v2`. + name: Shared name for this SummaryWriter resource stored to default + Graph. Defaults to the provided logdir prefixed with `logdir:`. Note: if a + summary writer resource with this shared name already exists, the returned + SummaryWriter wraps that resource and the other arguments have no effect. + + Returns: + Either a summary writer or an empty object which can be used as a + summary writer. + """ + if logdir is None: + return _NoopSummaryWriter() + logdir = str(logdir) + with ops.device("cpu:0"): + if max_queue is None: + max_queue = constant_op.constant(10) + if flush_millis is None: + flush_millis = constant_op.constant(2 * 60 * 1000) + if filename_suffix is None: + filename_suffix = constant_op.constant(".v2") + if name is None: + name = "logdir:" + logdir + resource = gen_summary_ops.summary_writer(shared_name=name) + return _LegacyResourceSummaryWriter( + resource=resource, + init_op_fn=functools.partial( + gen_summary_ops.create_summary_file_writer, + logdir=logdir, + max_queue=max_queue, + flush_millis=flush_millis, + filename_suffix=filename_suffix)) + + +@tf_export("summary.create_noop_writer", v1=[]) +def create_noop_writer(): + """Returns a summary writer that does nothing. + + This is useful as a placeholder in code that expects a context manager. + """ + return _NoopSummaryWriter() + + +def _cleanse_string(name, pattern, value): + if isinstance(value, str) and pattern.search(value) is None: + raise ValueError(f"{name} ({value}) must match {pattern.pattern}") + return ops.convert_to_tensor(value, dtypes.string) + + +def _nothing(): + """Convenient else branch for when summaries do not record.""" + return constant_op.constant(False) + + +@tf_export(v1=["summary.all_v2_summary_ops"]) +def all_v2_summary_ops(): + """Returns all V2-style summary ops defined in the current default graph. + + This includes ops from TF 2.0 tf.summary and TF 1.x tf.contrib.summary (except + for `tf.contrib.summary.graph` and `tf.contrib.summary.import_event`), but + does *not* include TF 1.x tf.summary ops. + + Returns: + List of summary ops, or None if called under eager execution. + """ + if context.executing_eagerly(): + return None + return ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access + + +def summary_writer_initializer_op(): + """Graph-mode only. Returns the list of ops to create all summary writers. + + Returns: + The initializer ops. + + Raises: + RuntimeError: If in Eager mode. + """ + if context.executing_eagerly(): + raise RuntimeError( + "tf.contrib.summary.summary_writer_initializer_op is only " + "supported in graph mode.") + return ops.get_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME) + + +_INVALID_SCOPE_CHARACTERS = re.compile(r"[^-_/.A-Za-z0-9]") + + +@tf_export("summary.experimental.summary_scope", v1=[]) +@tf_contextlib.contextmanager +def summary_scope(name, default_name="summary", values=None): + """Experimental context manager for use when defining a custom summary op. + + This behaves similarly to `tf.name_scope`, except that it returns a generated + summary tag in addition to the scope name. The tag is structurally similar to + the scope name - derived from the user-provided name, prefixed with enclosing + name scopes if any - but we relax the constraint that it be uniquified, as + well as the character set limitation (so the user-provided name can contain + characters not legal for scope names; in the scope name these are removed). + + This makes the summary tag more predictable and consistent for the user. + + For example, to define a new summary op called `my_op`: + + ```python + def my_op(name, my_value, step): + with tf.summary.summary_scope(name, "MyOp", [my_value]) as (tag, scope): + my_value = tf.convert_to_tensor(my_value) + return tf.summary.write(tag, my_value, step=step) + ``` + + Args: + name: string name for the summary. + default_name: Optional; if provided, used as default name of the summary. + values: Optional; passed as `values` parameter to name_scope. + + Yields: + A tuple `(tag, scope)` as described above. + """ + name = name or default_name + current_scope = ops.get_name_scope() + tag = current_scope + "/" + name if current_scope else name + # Strip illegal characters from the scope name, and if that leaves nothing, + # use None instead so we pick up the default name. + name = _INVALID_SCOPE_CHARACTERS.sub("", name) or None + with ops.name_scope(name, default_name, values, skip_on_eager=False) as scope: + yield tag, scope + + +@tf_export("summary.write", v1=[]) +def write(tag, tensor, step=None, metadata=None, name=None): + """Writes a generic summary to the default SummaryWriter if one exists. + + This exists primarily to support the definition of type-specific summary ops + like scalar() and image(), and is not intended for direct use unless defining + a new type-specific summary op. + + Args: + tag: string tag used to identify the summary (e.g. in TensorBoard), usually + generated with `tf.summary.summary_scope` + tensor: the Tensor holding the summary data to write or a callable that + returns this Tensor. If a callable is passed, it will only be called when + a default SummaryWriter exists and the recording condition specified by + `record_if()` is met. + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + metadata: Optional SummaryMetadata, as a proto or serialized bytes + name: Optional string name for this op. + + Returns: + True on success, or false if no summary was written because no default + summary writer was available. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + with ops.name_scope(name, "write_summary") as scope: + if _summary_state.writer is None: + return constant_op.constant(False) + if step is None: + step = get_step() + if metadata is None: + serialized_metadata = b"" + elif hasattr(metadata, "SerializeToString"): + serialized_metadata = metadata.SerializeToString() + else: + serialized_metadata = metadata + + def record(): + """Record the actual summary and return True.""" + if step is None: + raise ValueError("No step set. Please specify one either through the " + "`step` argument or through " + "tf.summary.experimental.set_step()") + + # Note the identity to move the tensor to the CPU. + with ops.device("cpu:0"): + summary_tensor = tensor() if callable(tensor) else array_ops.identity( + tensor) + # For DTensor, the device scope above doesn't work, we need to + # explicitly copy the resource tensor to host mesh, which is a cpu + # mesh. + writer = _summary_state.writer + summary_value = _maybe_convert_tensor_to_dtensor(writer, summary_tensor) + step_value = _maybe_convert_tensor_to_dtensor(writer, step) + + write_summary_op = gen_summary_ops.write_summary( + writer._resource, # pylint: disable=protected-access + step_value, + summary_value, + tag, + serialized_metadata, + name=scope, + ) + with ops.control_dependencies([write_summary_op]): + return constant_op.constant(True) + + op = smart_cond.smart_cond( + should_record_summaries(), record, _nothing, name="summary_cond") + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op) # pylint: disable=protected-access + return op + + +@tf_export("summary.experimental.write_raw_pb", v1=[]) +def write_raw_pb(tensor, step=None, name=None): + """Writes a summary using raw `tf.compat.v1.Summary` protocol buffers. + + Experimental: this exists to support the usage of V1-style manual summary + writing (via the construction of a `tf.compat.v1.Summary` protocol buffer) + with the V2 summary writing API. + + Args: + tensor: the string Tensor holding one or more serialized `Summary` protobufs + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + name: Optional string name for this op. + + Returns: + True on success, or false if no summary was written because no default + summary writer was available. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + with ops.name_scope(name, "write_raw_pb") as scope: + if _summary_state.writer is None: + return constant_op.constant(False) + if step is None: + step = get_step() + if step is None: + raise ValueError("No step set. Please specify one either through the " + "`step` argument or through " + "tf.summary.experimental.set_step()") + + def record(): + """Record the actual summary and return True.""" + # Note the identity to move the tensor to the CPU. + with ops.device("cpu:0"): + raw_summary_op = gen_summary_ops.write_raw_proto_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + step, + array_ops.identity(tensor), + name=scope) + with ops.control_dependencies([raw_summary_op]): + return constant_op.constant(True) + + with ops.device("cpu:0"): + op = smart_cond.smart_cond( + should_record_summaries(), record, _nothing, name="summary_cond") + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op) # pylint: disable=protected-access + return op + + +def summary_writer_function(name, tensor, function, family=None): + """Helper function to write summaries. + + Args: + name: name of the summary + tensor: main tensor to form the summary + function: function taking a tag and a scope which writes the summary + family: optional, the summary's family + + Returns: + The result of writing the summary. + """ + name_scope = ops.get_name_scope() + if name_scope: + # Add a slash to allow reentering the name scope. + name_scope += "/" + def record(): + with ops.name_scope(name_scope), summary_op_util.summary_scope( + name, family, values=[tensor]) as (tag, scope): + with ops.control_dependencies([function(tag, scope)]): + return constant_op.constant(True) + + if _summary_state.writer is None: + return control_flow_ops.no_op() + with ops.device("cpu:0"): + op = smart_cond.smart_cond( + _legacy_contrib_should_record_summaries(), record, _nothing, name="") + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op) # pylint: disable=protected-access + return op + + +def generic(name, tensor, metadata=None, family=None, step=None): + """Writes a tensor summary if possible.""" + + def function(tag, scope): + if metadata is None: + serialized_metadata = constant_op.constant("") + elif hasattr(metadata, "SerializeToString"): + serialized_metadata = constant_op.constant(metadata.SerializeToString()) + else: + serialized_metadata = metadata + # Note the identity to move the tensor to the CPU. + return gen_summary_ops.write_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + _choose_step(step), + array_ops.identity(tensor), + tag, + serialized_metadata, + name=scope) + return summary_writer_function(name, tensor, function, family=family) + + +def scalar(name, tensor, family=None, step=None): + """Writes a scalar summary if possible. + + Unlike `tf.contrib.summary.generic` this op may change the dtype + depending on the writer, for both practical and efficiency concerns. + + Args: + name: An arbitrary name for this summary. + tensor: A `tf.Tensor` Must be one of the following types: + `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`, + `int8`, `uint16`, `half`, `uint32`, `uint64`. + family: Optional, the summary's family. + step: The `int64` monotonic step variable, which defaults + to `tf.compat.v1.train.get_global_step`. + + Returns: + The created `tf.Operation` or a `tf.no_op` if summary writing has + not been enabled for this context. + """ + + def function(tag, scope): + # Note the identity to move the tensor to the CPU. + return gen_summary_ops.write_scalar_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + _choose_step(step), + tag, + array_ops.identity(tensor), + name=scope) + + return summary_writer_function(name, tensor, function, family=family) + + +def histogram(name, tensor, family=None, step=None): + """Writes a histogram summary if possible.""" + + def function(tag, scope): + # Note the identity to move the tensor to the CPU. + return gen_summary_ops.write_histogram_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + _choose_step(step), + tag, + array_ops.identity(tensor), + name=scope) + + return summary_writer_function(name, tensor, function, family=family) + + +def image(name, tensor, bad_color=None, max_images=3, family=None, step=None): + """Writes an image summary if possible.""" + + def function(tag, scope): + bad_color_ = (constant_op.constant([255, 0, 0, 255], dtype=dtypes.uint8) + if bad_color is None else bad_color) + # Note the identity to move the tensor to the CPU. + return gen_summary_ops.write_image_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + _choose_step(step), + tag, + array_ops.identity(tensor), + bad_color_, + max_images, + name=scope) + + return summary_writer_function(name, tensor, function, family=family) + + +def audio(name, tensor, sample_rate, max_outputs, family=None, step=None): + """Writes an audio summary if possible.""" + + def function(tag, scope): + # Note the identity to move the tensor to the CPU. + return gen_summary_ops.write_audio_summary( + _summary_state.writer._resource, # pylint: disable=protected-access + _choose_step(step), + tag, + array_ops.identity(tensor), + sample_rate=sample_rate, + max_outputs=max_outputs, + name=scope) + + return summary_writer_function(name, tensor, function, family=family) + + +def graph_v1(param, step=None, name=None): + """Writes a TensorFlow graph to the summary interface. + + The graph summary is, strictly speaking, not a summary. Conditions + like `tf.summary.should_record_summaries` do not apply. Only + a single graph can be associated with a particular run. If multiple + graphs are written, then only the last one will be considered by + TensorBoard. + + When not using eager execution mode, the user should consider passing + the `graph` parameter to `tf.compat.v1.summary.initialize` instead of + calling this function. Otherwise special care needs to be taken when + using the graph to record the graph. + + Args: + param: A `tf.Tensor` containing a serialized graph proto. When + eager execution is enabled, this function will automatically + coerce `tf.Graph`, `tf.compat.v1.GraphDef`, and string types. + step: The global step variable. This doesn't have useful semantics + for graph summaries, but is used anyway, due to the structure of + event log files. This defaults to the global step. + name: A name for the operation (optional). + + Returns: + The created `tf.Operation` or a `tf.no_op` if summary writing has + not been enabled for this context. + + Raises: + TypeError: If `param` isn't already a `tf.Tensor` in graph mode. + """ + if not context.executing_eagerly() and not isinstance( + param, tensor_lib.Tensor + ): + raise TypeError( + "graph() needs a argument `param` to be tf.Tensor " + "(e.g. tf.placeholder) in graph mode, but received " + f"param={param} of type {type(param).__name__}." + ) + writer = _summary_state.writer + if writer is None: + return control_flow_ops.no_op() + with ops.device("cpu:0"): + if isinstance(param, (ops.Graph, graph_pb2.GraphDef)): + tensor = ops.convert_to_tensor(_serialize_graph(param), dtypes.string) + else: + tensor = array_ops.identity(param) + return gen_summary_ops.write_graph_summary( + writer._resource, _choose_step(step), tensor, name=name) # pylint: disable=protected-access + + +@tf_export("summary.graph", v1=[]) +def graph(graph_data): + """Writes a TensorFlow graph summary. + + Write an instance of `tf.Graph` or `tf.compat.v1.GraphDef` as summary only + in an eager mode. Please prefer to use the trace APIs (`tf.summary.trace_on`, + `tf.summary.trace_off`, and `tf.summary.trace_export`) when using + `tf.function` which can automatically collect and record graphs from + executions. + + Usage Example: + ```py + writer = tf.summary.create_file_writer("/tmp/mylogs") + + @tf.function + def f(): + x = constant_op.constant(2) + y = constant_op.constant(3) + return x**y + + with writer.as_default(): + tf.summary.graph(f.get_concrete_function().graph) + + # Another example: in a very rare use case, when you are dealing with a TF v1 + # graph. + graph = tf.Graph() + with graph.as_default(): + c = tf.constant(30.0) + with writer.as_default(): + tf.summary.graph(graph) + ``` + + Args: + graph_data: The TensorFlow graph to write, as a `tf.Graph` or a + `tf.compat.v1.GraphDef`. + + Returns: + True on success, or False if no summary was written because no default + summary writer was available. + + Raises: + ValueError: `graph` summary API is invoked in a graph mode. + """ + if not context.executing_eagerly(): + raise ValueError("graph() cannot be invoked inside a graph context.") + writer = _summary_state.writer + if writer is None: + return constant_op.constant(False) + with ops.device("cpu:0"): + if not should_record_summaries(): + return constant_op.constant(False) + + if isinstance(graph_data, (ops.Graph, graph_pb2.GraphDef)): + tensor = ops.convert_to_tensor( + _serialize_graph(graph_data), dtypes.string) + else: + raise ValueError("Argument 'graph_data' is not tf.Graph or " + "tf.compat.v1.GraphDef. Received graph_data=" + f"{graph_data} of type {type(graph_data).__name__}.") + + gen_summary_ops.write_graph_summary( + writer._resource, # pylint: disable=protected-access + # Graph does not have step. Set to 0. + 0, + tensor, + ) + return constant_op.constant(True) + + +def import_event(tensor, name=None): + """Writes a `tf.compat.v1.Event` binary proto. + + This can be used to import existing event logs into a new summary writer sink. + Please note that this is lower level than the other summary functions and + will ignore the `tf.summary.should_record_summaries` setting. + + Args: + tensor: A `tf.Tensor` of type `string` containing a serialized + `tf.compat.v1.Event` proto. + name: A name for the operation (optional). + + Returns: + The created `tf.Operation`. + """ + return gen_summary_ops.import_event( + _summary_state.writer._resource, tensor, name=name) # pylint: disable=protected-access + + +@tf_export("summary.flush", v1=[]) +def flush(writer=None, name=None): + """Forces summary writer to send any buffered data to storage. + + This operation blocks until that finishes. + + Args: + writer: The `tf.summary.SummaryWriter` to flush. If None, the current + default writer will be used instead; if there is no current writer, this + returns `tf.no_op`. + name: Ignored legacy argument for a name for the operation. + + Returns: + The created `tf.Operation`. + """ + del name # unused + if writer is None: + writer = _summary_state.writer + if writer is None: + return control_flow_ops.no_op() + if isinstance(writer, SummaryWriter): + return writer.flush() + raise ValueError("Invalid argument to flush(): %r" % (writer,)) + + +def legacy_raw_flush(writer=None, name=None): + """Legacy version of flush() that accepts a raw resource tensor for `writer`. + + Do not use this function in any new code. Not supported and not part of the + public TF APIs. + + Args: + writer: The `tf.summary.SummaryWriter` to flush. If None, the current + default writer will be used instead; if there is no current writer, this + returns `tf.no_op`. For this legacy version only, also accepts a raw + resource tensor pointing to the underlying C++ writer resource. + name: Ignored legacy argument for a name for the operation. + + Returns: + The created `tf.Operation`. + """ + if writer is None or isinstance(writer, SummaryWriter): + # Forward to the TF2 implementation of flush() when possible. + return flush(writer, name) + else: + # Legacy fallback in case we were passed a raw resource tensor. + with ops.device("cpu:0"): + return gen_summary_ops.flush_summary_writer(writer, name=name) + + +def eval_dir(model_dir, name=None): + """Construct a logdir for an eval summary writer.""" + return os.path.join(model_dir, "eval" if not name else "eval_" + name) + + +@deprecation.deprecated(date=None, + instructions="Renamed to create_file_writer().") +def create_summary_file_writer(*args, **kwargs): + """Please use `tf.contrib.summary.create_file_writer`.""" + logging.warning("Deprecation Warning: create_summary_file_writer was renamed " + "to create_file_writer") + return create_file_writer(*args, **kwargs) + + +def _serialize_graph(arbitrary_graph): + if isinstance(arbitrary_graph, ops.Graph): + return arbitrary_graph.as_graph_def(add_shapes=True).SerializeToString() + else: + return arbitrary_graph.SerializeToString() + + +def _choose_step(step): + if step is None: + return training_util.get_or_create_global_step() + if not isinstance(step, tensor_lib.Tensor): + return ops.convert_to_tensor(step, dtypes.int64) + return step + + +def _check_create_file_writer_args(inside_function, **kwargs): + """Helper to check the validity of arguments to a create_file_writer() call. + + Args: + inside_function: whether the create_file_writer() call is in a tf.function + **kwargs: the arguments to check, as kwargs to give them names. + + Raises: + ValueError: if the arguments are graph tensors. + """ + for arg_name, arg in kwargs.items(): + if not isinstance(arg, ops.EagerTensor) and tensor_util.is_tf_type(arg): + if inside_function: + raise ValueError( + f"Invalid graph Tensor argument '{arg_name}={arg}' to " + "create_file_writer() inside an @tf.function. The create call will " + "be lifted into the outer eager execution context, so it cannot " + "consume graph tensors defined inside the function body.") + else: + raise ValueError( + f"Invalid graph Tensor argument '{arg_name}={arg}' to eagerly " + "executed create_file_writer().") + + +def run_metadata(name, data, step=None): + """Writes entire RunMetadata summary. + + A RunMetadata can contain DeviceStats, partition graphs, and function graphs. + Please refer to the proto for definition of each field. + + Args: + name: A name for this summary. The summary tag used for TensorBoard will be + this name prefixed by any active name scopes. + data: A RunMetadata proto to write. + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + + Returns: + True on success, or false if no summary was written because no default + summary writer was available. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + summary_metadata = summary_pb2.SummaryMetadata() + # Hard coding a plugin name. Please refer to go/tb-plugin-name-hardcode for + # the rationale. + summary_metadata.plugin_data.plugin_name = "graph_run_metadata" + # version number = 1 + summary_metadata.plugin_data.content = b"1" + + with summary_scope(name, + "graph_run_metadata_summary", + [data, step]) as (tag, _): + with ops.device("cpu:0"): + tensor = constant_op.constant(data.SerializeToString(), + dtype=dtypes.string) + return write( + tag=tag, + tensor=tensor, + step=step, + metadata=summary_metadata) + + +def run_metadata_graphs(name, data, step=None): + """Writes graphs from a RunMetadata summary. + + Args: + name: A name for this summary. The summary tag used for TensorBoard will be + this name prefixed by any active name scopes. + data: A RunMetadata proto to write. + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + + Returns: + True on success, or false if no summary was written because no default + summary writer was available. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + summary_metadata = summary_pb2.SummaryMetadata() + # Hard coding a plugin name. Please refer to go/tb-plugin-name-hardcode for + # the rationale. + summary_metadata.plugin_data.plugin_name = "graph_run_metadata_graph" + # version number = 1 + summary_metadata.plugin_data.content = b"1" + + data = config_pb2.RunMetadata( + function_graphs=data.function_graphs, + partition_graphs=data.partition_graphs) + + with summary_scope(name, + "graph_run_metadata_graph_summary", + [data, step]) as (tag, _): + with ops.device("cpu:0"): + tensor = constant_op.constant(data.SerializeToString(), + dtype=dtypes.string) + return write( + tag=tag, + tensor=tensor, + step=step, + metadata=summary_metadata) + + +_TraceContext = collections.namedtuple("TraceContext", ("graph", "profiler")) +_current_trace_context_lock = threading.Lock() +_current_trace_context = None + + +@tf_export("summary.trace_on", v1=[]) +def trace_on(graph=True, profiler=False): # pylint: disable=redefined-outer-name + """Starts a trace to record computation graphs and profiling information. + + Must be invoked in eager mode. + + When enabled, TensorFlow runtime will collect information that can later be + exported and consumed by TensorBoard. The trace is activated across the entire + TensorFlow runtime and affects all threads of execution. + + To stop the trace and export the collected information, use + `tf.summary.trace_export`. To stop the trace without exporting, use + `tf.summary.trace_off`. + + Args: + graph: If True, enables collection of executed graphs. It includes ones from + tf.function invocation and ones from the legacy graph mode. The default + is True. + profiler: If True, enables the advanced profiler. Enabling profiler + implicitly enables the graph collection. The profiler may incur a high + memory overhead. The default is False. + + """ + if ops.inside_function(): + logging.warn("Cannot enable trace inside a tf.function.") + return + if not context.executing_eagerly(): + logging.warn("Must enable trace in eager mode.") + return + + global _current_trace_context + with _current_trace_context_lock: + if _current_trace_context: + logging.warn("Trace already enabled") + return + + if graph and not profiler: + context.context().enable_graph_collection() + if profiler: + context.context().enable_run_metadata() + _profiler.start() + + _current_trace_context = _TraceContext(graph=graph, profiler=profiler) + + +@tf_export("summary.trace_export", v1=[]) +def trace_export(name, step=None, profiler_outdir=None): + """Stops and exports the active trace as a Summary and/or profile file. + + Stops the trace and exports all metadata collected during the trace to the + default SummaryWriter, if one has been set. + + Args: + name: A name for the summary to be written. + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + profiler_outdir: Output directory for profiler. It is required when profiler + is enabled when trace was started. Otherwise, it is ignored. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + # TODO(stephanlee): See if we can remove profiler_outdir and infer it from + # the SummaryWriter's logdir. + global _current_trace_context + + if ops.inside_function(): + logging.warn("Cannot export trace inside a tf.function.") + return + if not context.executing_eagerly(): + logging.warn("Can only export trace while executing eagerly.") + return + + with _current_trace_context_lock: + if _current_trace_context is None: + raise ValueError("Must enable trace before export through " + "tf.summary.trace_on.") + graph, profiler = _current_trace_context # pylint: disable=redefined-outer-name + if profiler and profiler_outdir is None: + raise ValueError("Argument `profiler_outdir` is not specified.") + + run_meta = context.context().export_run_metadata() + + if graph and not profiler: + run_metadata_graphs(name, run_meta, step) + else: + run_metadata(name, run_meta, step) + + if profiler: + _profiler.save(profiler_outdir, _profiler.stop()) + + trace_off() + + +@tf_export("summary.trace_off", v1=[]) +def trace_off(): + """Stops the current trace and discards any collected information.""" + global _current_trace_context + with _current_trace_context_lock: + if _current_trace_context is None: + return # tracing already off + graph, profiler = _current_trace_context # pylint: disable=redefined-outer-name, unpacking-non-sequence + _current_trace_context = None + + if graph: + # Disabling run_metadata disables graph collection as well. + context.context().disable_run_metadata() + + if profiler: + try: + _profiler.stop() + except _profiler.ProfilerNotRunningError: + pass + + +def _maybe_convert_tensor_to_dtensor(writer, tensor): + if getattr(writer, "_mesh", None) is not None: + mesh = writer._mesh.host_mesh() # pylint: disable=protected-access + tensor = dtensor_api.copy_to_mesh( + tensor, layout_lib.Layout.replicated(mesh, rank=tensor.shape.rank) + ) + return tensor diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/template.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/template.py new file mode 100644 index 0000000000000000000000000000000000000000..4e36b6b963176d0dd5337da0b7dbda30df4d4652 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/template.py @@ -0,0 +1,743 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Provides templates which allow variable sharing.""" +import functools +import traceback +from tensorflow.python.checkpoint import checkpoint as trackable_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + +__all__ = ["make_template"] + + +@tf_export(v1=["make_template"]) +def make_template(name_, + func_, + create_scope_now_=False, + unique_name_=None, + custom_getter_=None, + **kwargs): + """Given an arbitrary function, wrap it so that it does variable sharing. + + @compatibility(TF2) + `tf.compat.v1.make_template` is a legacy API that is only compatible + with eager execution enabled and `tf.function` if you combine it with + `tf.compat.v1.keras.utils.track_tf1_style_variables`. See the model mapping + migration guide section on `make_template` for more info: + + https://www.tensorflow.org/guide/migrate/model_mapping#using_tfcompatv1make_template_in_the_decorated_method + + Even if you use legacy apis for `variable_scope`-based variable reuse, + we recommend using + `tf.compat.v1.keras.utils.track_tf1_style_variables` directly and not using + `tf.compat.v1.make_template`, as it interoperates with eager execution in a + simpler and more predictable fashion than `make_template`. + + The TF2 API approach would be tracking your variables using + `tf.Module`s or Keras layers and models rather than relying on + `make_template`. + @end_compatibility + + This wraps `func_` in a Template and partially evaluates it. Templates are + functions that create variables the first time they are called and reuse them + thereafter. In order for `func_` to be compatible with a `Template` it must + have the following properties: + + * The function should create all trainable variables and any variables that + should be reused by calling `tf.compat.v1.get_variable`. If a trainable + variable is + created using `tf.Variable`, then a ValueError will be thrown. Variables + that are intended to be locals can be created by specifying + `tf.Variable(..., trainable=false)`. + * The function may use variable scopes and other templates internally to + create and reuse variables, but it shouldn't use + `tf.compat.v1.global_variables` to + capture variables that are defined outside of the scope of the function. + * Internal scopes and variable names should not depend on any arguments that + are not supplied to `make_template`. In general you will get a ValueError + telling you that you are trying to reuse a variable that doesn't exist + if you make a mistake. + + In the following example, both `z` and `w` will be scaled by the same `y`. It + is important to note that if we didn't assign `scalar_name` and used a + different name for z and w that a `ValueError` would be thrown because it + couldn't reuse the variable. + + ```python + def my_op(x, scalar_name): + var1 = tf.compat.v1.get_variable(scalar_name, + shape=[], + initializer=tf.compat.v1.constant_initializer(1)) + return x * var1 + + scale_by_y = tf.compat.v1.make_template('scale_by_y', my_op, scalar_name='y') + + z = scale_by_y(input1) + w = scale_by_y(input2) + ``` + + As a safe-guard, the returned function will raise a `ValueError` after the + first call if trainable variables are created by calling `tf.Variable`. + + If all of these are true, then 2 properties are enforced by the template: + + 1. Calling the same template multiple times will share all non-local + variables. + 2. Two different templates are guaranteed to be unique, unless you reenter the + same variable scope as the initial definition of a template and redefine + it. An examples of this exception: + + ```python + def my_op(x, scalar_name): + var1 = tf.compat.v1.get_variable(scalar_name, + shape=[], + initializer=tf.compat.v1.constant_initializer(1)) + return x * var1 + + with tf.compat.v1.variable_scope('scope') as vs: + scale_by_y = tf.compat.v1.make_template('scale_by_y', my_op, + scalar_name='y') + z = scale_by_y(input1) + w = scale_by_y(input2) + + # Creates a template that reuses the variables above. + with tf.compat.v1.variable_scope(vs, reuse=True): + scale_by_y2 = tf.compat.v1.make_template('scale_by_y', my_op, + scalar_name='y') + z2 = scale_by_y2(input1) + w2 = scale_by_y2(input2) + ``` + + Depending on the value of `create_scope_now_`, the full variable scope may be + captured either at the time of first call or at the time of construction. If + this option is set to True, then all Tensors created by repeated calls to the + template will have an extra trailing _N+1 to their name, as the first time the + scope is entered in the Template constructor no Tensors are created. + + Note: `name_`, `func_` and `create_scope_now_` have a trailing underscore to + reduce the likelihood of collisions with kwargs. + + Args: + name_: A name for the scope created by this template. If necessary, the name + will be made unique by appending `_N` to the name. + func_: The function to wrap. + create_scope_now_: Boolean controlling whether the scope should be created + when the template is constructed or when the template is called. Default + is False, meaning the scope is created when the template is called. + unique_name_: When used, it overrides name_ and is not made unique. If a + template of the same scope/unique_name already exists and reuse is false, + an error is raised. Defaults to None. + custom_getter_: Optional custom getter for variables used in `func_`. See + the `tf.compat.v1.get_variable` `custom_getter` documentation for more + information. + **kwargs: Keyword arguments to apply to `func_`. + + Returns: + A function to encapsulate a set of variables which should be created once + and reused. An enclosing scope will be created either when `make_template` + is called or when the result is called, depending on the value of + `create_scope_now_`. Regardless of the value, the first time the template + is called it will enter the scope with no reuse, and call `func_` to create + variables, which are guaranteed to be unique. All subsequent calls will + re-enter the scope and reuse those variables. + + Raises: + ValueError: if `name_` is None. + """ + return make_template_internal( + name_, + func_, + create_scope_now_, + unique_name_, + custom_getter_, + create_graph_function_=False, + **kwargs) + + +def make_template_internal(name_, + func_, + create_scope_now_=False, + unique_name_=None, + custom_getter_=None, + create_graph_function_=False, + **kwargs): + """Make a template, optionally compiling func_ into a graph function. + + See `make_template` for full documentation. + + Args: + name_: A name for the scope created by this template. If necessary, the name + will be made unique by appending `_N` to the name. + func_: The function to wrap. + create_scope_now_: Boolean controlling whether the scope should be created + when the template is constructed or when the template is called. Default + is False, meaning the scope is created when the template is called. + unique_name_: When used, it overrides name_ and is not made unique. If a + template of the same scope/unique_name already exists and reuse is false, + an error is raised. Defaults to None. If executing eagerly, must be None. + custom_getter_: Optional custom getter for variables used in `func_`. See + the `tf.compat.v1.get_variable` `custom_getter` documentation for more + information. + create_graph_function_: When True, `func_` will be executed as a graph + function. This implies that `func_` must satisfy the properties that + `function.defun` requires of functions: See the documentation of + `function.defun` for details. When executing eagerly, setting this flag + to True can improve performance. Regardless of whether eager execution + is enabled, enabling this flag gives the caller access to graph-function + semantics, i.e., accesses to variables are totally ordered and + side-effecting ops are not pruned. + **kwargs: Keyword arguments to apply to `func_`. + + Returns: + A function to encapsulate a set of variables which should be created once + and reused. An enclosing scope will be created either when `make_template` + is called or when the result is called, depending on the value of + `create_scope_now_`. Regardless of the value, the first time the template + is called it will enter the scope with no reuse, and call `func_` to create + variables, which are guaranteed to be unique. All subsequent calls will + re-enter the scope and reuse those variables. + + Raises: + ValueError: if `name_` is None. + ValueError: if `unique_name_` is not None and eager execution is enabled. + """ + + if kwargs: + func_ = functools.partial(func_, **kwargs) + + if context.executing_eagerly(): + if unique_name_ is not None: + raise ValueError( + "unique_name_ cannot be used when eager execution is enabled.") + return EagerTemplate( + name_, + func_, + create_scope_now=create_scope_now_, + custom_getter=custom_getter_, + create_graph_function=create_graph_function_) + return Template( + name_, + func_, + create_scope_now=create_scope_now_, + unique_name=unique_name_, + custom_getter=custom_getter_, + create_graph_function=create_graph_function_) + + +def _skip_common_stack_elements(stacktrace, base_case): + """Skips items that the target stacktrace shares with the base stacktrace.""" + for i, (trace, base) in enumerate(zip(stacktrace, base_case)): + if trace != base: + return stacktrace[i:] + return stacktrace[-1:] + + +class Template(trackable.Trackable): + """Wrap a function to aid in variable sharing. + + Templates are functions that create variables the first time they are called + and reuse them thereafter. See `make_template` for full documentation. + + Note: By default, the full variable scope is captured at the time of first + call. If `create_scope_now_` is passed as True to the constructor, the full + scope will be captured there, but no variables will created until the first + call. + """ + + def __init__(self, + name, + func, + create_scope_now=False, + unique_name=None, + custom_getter=None, + create_graph_function=False): + """Creates a template for the given function. + + Args: + name: A name for the scope created by this template. The name will be made + unique by appending `_N` to the it (see how + `tf.compat.v1.variable_scope` treats the `default_name` for details). + func: The function to apply each time. + create_scope_now: Whether to create the scope at Template construction + time, rather than first call. Defaults to false. Creating the scope at + construction time may be more convenient if the template is to passed + through much lower level code, and you want to be sure of the scope name + without knowing exactly where it will be first called. If set to True, + the scope will be created in the constructor, and all subsequent times + in `__call__`, leading to a trailing numeral being added to the names of + all created Tensors. If set to False, the scope will be created at the + first call location. + unique_name: When used, it overrides `name` and is not made unique. If a + template of the same scope/unique_name already exists and reuse is + false, an error is raised. Defaults to None. + custom_getter: optional custom getter to pass to `variable_scope()` + create_graph_function: When True, `func` will be executed as a graph + function. Enabling this flag gives the caller access to graph-function + semantics, i.e., accesses to variables are totally ordered and + side-effecting ops are not pruned. + + Raises: + ValueError: if `name` is None. + """ + if create_graph_function: + self._func = def_function.function(func) + else: + self._func = func + self._stacktrace = traceback.format_stack()[:-2] + self._name = name + self._unique_name = unique_name + self._custom_getter = custom_getter + if name is None: + raise ValueError("name cannot be None.") + if create_scope_now: + with variable_scope._pure_variable_scope( # pylint:disable=protected-access + (self._unique_name or + variable_scope._get_unique_variable_scope(self._name)), # pylint:disable=protected-access + custom_getter=self._custom_getter) as vs: + self._variable_scope = vs + else: + self._variable_scope = None + # This variable keeps track of whether the template has been called to + # completion, which is not the same as whether the scope has been created. + self._variables_created = False + # `MirroredStrategy` builds the graph with multiple threads. If a + # `merge_call` happens within a template, multiple calls may be in progress + # simultaneously. This variable keeps track of whether any call of the + # template has started. + self._first_call = True + + def _call_func(self, args, kwargs): + try: + if self._variables_created: + vars_at_start = len( + ops.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES)) + trainable_at_start = len( + ops.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES)) + + result = self._func(*args, **kwargs) + + # Variables were previously created, implying this is not the first + # time the template has been called. Check to make sure that no new + # trainable variables were created this time around. + trainable_variables = ops.get_collection_ref( + ops.GraphKeys.TRAINABLE_VARIABLES) + + # If a variable that we intend to train is created as a side effect + # of creating a template, then that is almost certainly an error. + if trainable_at_start != len(trainable_variables): + raise ValueError("Trainable variable created when calling a template " + "after the first time, perhaps you used tf.Variable " + "when you meant tf.get_variable: %s" % + (trainable_variables[trainable_at_start:],)) + + # Non-trainable tracking variables are a legitimate reason why a new + # variable would be created, but it is a relatively advanced use-case, + # so log it. + variables = ops.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES) + if vars_at_start != len(variables): + logging.info( + "New variables created when calling a template after " + "the first time, perhaps you used tf.Variable when you " + "meant tf.get_variable: %s", variables[vars_at_start:]) + elif self._first_call: + self._first_call = False + try: + # The first time we run, restore variables if necessary (via + # Trackable). + with trackable_util.capture_dependencies(template=self): + result = self._func(*args, **kwargs) + except: + self._first_call = True + raise + self._variables_created = True + else: # We are calling the template in parallel from another thread. + result = self._func(*args, **kwargs) + return result + except Exception as exc: + # Reraise the exception, but append the original definition to the + # trace. + args = exc.args + if not args: + arg0 = "" + else: + arg0 = args[0] + trace = "".join( + _skip_common_stack_elements(self._stacktrace, + traceback.format_stack())) + arg0 = "%s\n\noriginally defined at:\n%s" % (arg0, trace) + new_args = [arg0] + new_args.extend(args[1:]) + exc.args = tuple(new_args) + raise + + def __call__(self, *args, **kwargs): + if self._variable_scope: + # Only reuse variables if not on first call. + with variable_scope.variable_scope( + self._variable_scope, reuse=not self._first_call): + return self._call_func(args, kwargs) + else: + # The scope was not created at construction time, so create it here. + # Subsequent calls should reuse variables. + with variable_scope.variable_scope( + self._unique_name, self._name, + custom_getter=self._custom_getter) as vs: + self._variable_scope = vs + return self._call_func(args, kwargs) + + @property + def name(self): + """Returns the name given to this Template.""" + return self._name + + @property + def func(self): + """Returns the func given to this Template.""" + return self._func + + @property + def variable_scope(self): + """Returns the variable scope object created by this Template.""" + return self._variable_scope + + @property + def variable_scope_name(self): + """Returns the variable scope name created by this Template.""" + if self._variable_scope: + name = self._variable_scope.name + if not name or name[-1] == "/": + return name + else: + # To prevent partial matches on the scope_name, we add '/' at the end. + return name + "/" + + @property + def variables(self): + """Returns the list of global and local variables created by the Template.""" + return self.global_variables + self.local_variables + + @property + def trainable_variables(self): + """Returns the list of trainable variables created by the Template.""" + if self._variables_created: + return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES, + self.variable_scope_name) + else: + return [] + + @property + def non_trainable_variables(self): + """Returns the list of non-trainable variables created by the Template.""" + # TODO(apassos) Make sure it matches Eager when using local variables. + global_variables = self.global_variables + trainable_variables = set(self.trainable_variables) + return [x for x in global_variables if x not in trainable_variables] + + @property + def global_variables(self): + """Returns the list of global variables created by the Template.""" + if self._variables_created: + return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, + self.variable_scope_name) + else: + return [] + + @property + def local_variables(self): + """Returns the list of global variables created by the Template.""" + if self._variables_created: + return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, + self.variable_scope_name) + else: + return [] + + @property + def weights(self): + """List of weights/variables created by the Template.""" + return self.variables + + @property + def trainable_weights(self): + """List of trainable weights/variables created by the Template.""" + return self.trainable_variables + + @property + def non_trainable_weights(self): + """List of non-trainable weights/variables created by the Template.""" + return self.non_trainable_variables + + @property + @deprecated("2017-02-21", + "The .var_scope property is deprecated. Please change your " + "code to use the .variable_scope property") + def var_scope(self): + """Returns the variable scope object created by this Template.""" + return self._variable_scope + + +class _EagerTemplateVariableStore: + """Wrapper around EagerVariableStore to support nesting EagerTemplates.""" + + def __init__(self, variable_scope_name): + self._variable_scope_name = variable_scope_name + default = variable_scope._get_default_variable_store() # pylint: disable=protected-access + if default._store_eager_variables: # pylint: disable=protected-access + self._eager_variable_store = variable_scope.EagerVariableStore(default) + else: + # If no outer eager variable store has been made, + # the template needs to create one + self._eager_variable_store = variable_scope.EagerVariableStore() + self._used_once = False + + def set_variable_scope_name(self, variable_scope_name): + self._variable_scope_name = variable_scope_name + + @tf_contextlib.contextmanager + def as_default(self): + try: + if not self._used_once: + # If an outer eager VariableStore was explicitly created and set by + # the first time this template store was used (even if not at + # constructor time) then pick up the outer variable store. + default = variable_scope._get_default_variable_store() # pylint: disable=protected-access + if default._store_eager_variables: # pylint: disable=protected-access + self._eager_variable_store._store = default # pylint: disable=protected-access + self._used_once = True + with self._eager_variable_store.as_default(): # pylint: disable=protected-access + yield + finally: + # Each _EagerTemplateVariableStore object lives underneath a variable + # scope (see EagerTemplate.__call__). This variable scope's subscopes are + # closed when the EagerTemplate object returns from __call__. For + # top-level _EagerTemplateVariableStore objects, the variable store to + # which the variable scope is attached is different from the + # EagerVariableStore; as such it is necessary to close its subscopes + # here as well. + if self._variable_scope_name is None: + raise RuntimeError("A variable scope must be set before an " + "_EagerTemplateVariableStore object exits.") + variable_scope.get_variable_scope_store().close_variable_subscopes( + self._variable_scope_name) + + def _variables_in_scope(self, variable_list): + if self._variable_scope_name is None: + raise RuntimeError( + "A variable scope must be set before variables can be accessed.") + return [ + v for v in variable_list + if v.name.startswith(self._variable_scope_name + "/") + ] + + def variables(self): + return self._variables_in_scope(self._eager_variable_store.variables()) + + def trainable_variables(self): + return self._variables_in_scope( + self._eager_variable_store.trainable_variables()) + + def non_trainable_variables(self): + return self._variables_in_scope( + self._eager_variable_store.non_trainable_variables()) + + +class EagerTemplate(Template): + """Wrap a function to aid in variable sharing in Eager mode. + + Templates are functions that create variables the first time they are called + and reuse them thereafter. See `make_template` for full documentation. + + Note: By default, the full variable scope is captured at the time of first + call. If `create_scope_now` is passed as True to the constructor, the full + scope will be captured there, but no variables will be created until the first + call. + """ + + def __init__(self, + name, + func, + create_scope_now=False, + custom_getter=None, + create_graph_function=False): + """Creates a template for the given function. + + Args: + name: A name for the scope created by this template. The name will be made + unique by appending `_N` to the it (see how + `tf.compat.v1.variable_scope` treats the `default_name` for details). + func: The function to apply each time. + create_scope_now: Whether to create the scope at Template construction + time, rather than first call. Defaults to false. Creating the scope at + construction time may be more convenient if the template is passed + through much lower level code, and you want to be sure of the scope name + without knowing exactly where it will be first called. If set to True, + the scope will be created in the constructor, and all subsequent times + in `__call__`, leading to a trailing numeral being added to the names of + all created Tensors. If set to False, the scope will be created at the + first call location. + custom_getter: optional custom getter to pass to `variable_scope()` + create_graph_function: When True, `func` will be executed as a graph + function. Enabling this flag allows the caller to reap the performance + benefits associated with executing graphs, at the cost of sacrificing + debuggability; however, not all Python functions can be compiled into + graph functions. See the documentation for `function.defun` for details. + + Raises: + RuntimeError: if eager execution is not enabled. + """ + if not context.executing_eagerly(): + raise RuntimeError( + "{} objects can only be used when eager execution is enabled, use " + "tf.Template for graph construction".format(type(self))) + super(EagerTemplate, self).__init__(name, func, create_scope_now, None, + custom_getter, create_graph_function) + if self._variable_scope is not None: + variable_scope_name = self._variable_scope.name + else: + # Defer setting the variable scope name until the variable scope + # is created in __call__. + variable_scope_name = None + self._template_store = _EagerTemplateVariableStore(variable_scope_name) + self._variable_scope_context_manager = None + + def _call_func(self, args, kwargs): + try: + vars_at_start = self._template_store.variables() + trainable_at_start = self._template_store.trainable_variables() + if self._variables_created: + result = self._func(*args, **kwargs) + else: + # The first time we run, restore variables if necessary (via + # Trackable). + with trackable_util.capture_dependencies(template=self): + result = self._func(*args, **kwargs) + + if self._variables_created: + # Variables were previously created, implying this is not the first + # time the template has been called. Check to make sure that no new + # trainable variables were created this time around. + trainable_variables = self._template_store.trainable_variables() + # If a variable that we intend to train is created as a side effect + # of creating a template, then that is almost certainly an error. + if len(trainable_at_start) != len(trainable_variables): + raise ValueError( + "Trainable variable created when calling a template " + "after the first time, perhaps you used tf.Variable " + "when you meant tf.get_variable: %s" % list( + object_identity.ObjectIdentitySet(trainable_variables) - + object_identity.ObjectIdentitySet(trainable_at_start))) + + # Non-trainable tracking variables are a legitimate reason why a new + # variable would be created, but it is a relatively advanced use-case, + # so log it. + variables = self._template_store.variables() + if len(vars_at_start) != len(variables): + logging.info( + "New variables created when calling a template after " + "the first time, perhaps you used tf.Variable when you " + "meant tf.get_variable: %s", + list( + object_identity.ObjectIdentitySet(variables) - + object_identity.ObjectIdentitySet(vars_at_start))) + else: + self._variables_created = True + return result + except Exception as exc: + # Reraise the exception, but append the original definition to the + # trace. + args = exc.args + if not args: + arg0 = "" + else: + arg0 = args[0] + trace = "".join( + _skip_common_stack_elements(self._stacktrace, + traceback.format_stack())) + arg0 = "%s\n\noriginally defined at:\n%s" % (arg0, trace) + new_args = [arg0] + new_args.extend(args[1:]) + exc.args = tuple(new_args) + raise + + def __call__(self, *args, **kwargs): + # In both branches below, the template store is installed as default after + # the variable scope is opened in order to ensure that templates nested at + # the same level correctly uniquify lower variable scope names. + if self._variable_scope: + # Create a cache for the variable scope context manager the first time + # around so that we don't have to keep recreating it. + if not self._variable_scope_context_manager: + self._variable_scope_context_manager = variable_scope.variable_scope( + self._variable_scope, reuse=variable_scope.AUTO_REUSE) + with self._variable_scope_context_manager: + with self._template_store.as_default(): + return self._call_func(args, kwargs) + else: + # The scope was not created at construction time, so create it here. + # Subsequent calls should reuse variables. + with variable_scope.variable_scope( + self._unique_name, self._name, + custom_getter=self._custom_getter) as vs: + self._variable_scope = vs + # Because the scope was not created at construction time, the template + # store's variable scope name is unset; set it here. + self._template_store.set_variable_scope_name(vs.name) + with self._template_store.as_default(): + return self._call_func(args, kwargs) + + @property + def variables(self): + """Returns the list of variables created by the Template.""" + # Currently there is no local variable in Eager mode. + if not self._variables_created: + return [] + return self._template_store.variables() + + @property + def trainable_variables(self): + """Returns the list of trainable variables created by the Template.""" + # Currently there is no local variable in Eager mode. + if not self._variables_created: + return [] + return self._template_store.trainable_variables() + + @property + def non_trainable_variables(self): + """Returns the list of non-trainable variables created by the Template.""" + # Currently there is no local variable in Eager mode. + if not self._variables_created: + return [] + return self._template_store.non_trainable_variables() + + @property + def global_variables(self): + """Returns the list of global variables created by the Template.""" + # Currently there is no local variable in Eager mode. + if not self._variables_created: + return [] + return self.variables + + @property + def local_variables(self): + """Returns the list of global variables created by the Template.""" + # Currently there is no local variable in Eager mode. + return [] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..25ca3495416b7b05c0046c19fee1d366237c842a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_grad.py @@ -0,0 +1,263 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradients for operators defined in tensor_array_ops.py.""" +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import tensor_array_ops + +# TODO(b/31222613): These ops may be differentiable, and there may be +# latent bugs here. +ops.NotDifferentiable("TensorArray") +ops.NotDifferentiable("TensorArrayGrad") +ops.NotDifferentiable("TensorArraySize") +ops.NotDifferentiable("TensorArrayClose") + +ops.NotDifferentiable("TensorArrayV2") +ops.NotDifferentiable("TensorArrayGradV2") +ops.NotDifferentiable("TensorArraySizeV2") +ops.NotDifferentiable("TensorArrayCloseV2") + +ops.NotDifferentiable("TensorArrayV3") +ops.NotDifferentiable("TensorArrayGradV3") +ops.NotDifferentiable("TensorArrayGradWithShape") +ops.NotDifferentiable("TensorArraySizeV3") +ops.NotDifferentiable("TensorArrayCloseV3") + + +def _GetGradSource(op_or_tensor): + """Identify which call to tf.gradients created this gradient op or tensor. + + TensorArray gradient calls use an accumulator TensorArray object. If + multiple gradients are calculated and run in the same session, the multiple + gradient nodes may accidentally flow through the same accumulator TensorArray. + This double counting breaks the TensorArray gradient flow. + + The solution is to identify which gradient call this particular + TensorArray*Grad is being called in, by looking at the input gradient + tensor's name, and create or lookup an accumulator gradient TensorArray + associated with this specific call. This solves any confusion and ensures + different gradients from the same forward graph get their own accumulators. + + This function creates the unique label associated with the tf.gradients call + that is used to create the gradient TensorArray. + + Args: + op_or_tensor: `Tensor` or `Operation` which is an input to a + TensorArray*Grad call. + + Returns: + A python string, the unique label associated with this particular + gradients calculation. + + Raises: + ValueError: If not called within a gradients calculation. + """ + name_tokens = op_or_tensor.name.split("/") + grad_pos = [i for i, x in enumerate(name_tokens) if x.startswith("gradients")] + if not grad_pos: + raise ValueError( + "Expected op/tensor name to start with gradients (excluding scope)" + f", got: {op_or_tensor.name}. This means that a tf.gradients op with " + "this op in its dependency path has a custom name that does not start " + "with 'gradients'. Please make sure all calls to tf.gradients that " + "have non-empty `name` arguments use names that start with " + "'gradients'.") + return "/".join(name_tokens[:grad_pos[-1] + 1]) + + +@ops.RegisterGradient("TensorArrayRead") +@ops.RegisterGradient("TensorArrayReadV2") +@ops.RegisterGradient("TensorArrayReadV3") +def _TensorArrayReadGrad(op: ops.Operation, grad): + """Gradient for TensorArrayRead. + + Args: + op: Forward TensorArrayRead op. + grad: Gradient `Tensor` to TensorArrayRead. + + Returns: + A flow `Tensor`, which can be used in control dependencies to + force the write of `grad` to the gradient `TensorArray`. + """ + # Note: the forward flow dependency in the call to grad() is necessary for + # the case of dynamic sized TensorArrays. When creating the gradient + # TensorArray, the final size of the forward array must be known. + # For this we need to wait until it has been created by depending on + # the input flow of the original op. + handle = op.inputs[0] + index = op.inputs[1] + flow = op.inputs[2] + dtype = op.get_attr("dtype") + grad_source = _GetGradSource(grad) + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + w_g = g.write(index, grad) + return [None, None, w_g.flow] + + +@ops.RegisterGradient("TensorArrayWrite") +@ops.RegisterGradient("TensorArrayWriteV2") +@ops.RegisterGradient("TensorArrayWriteV3") +def _TensorArrayWriteGrad(op: ops.Operation, flow): + """Gradient for TensorArrayWrite. + + Args: + op: Forward TensorArrayWrite op. + flow: Gradient `Tensor` flow to TensorArrayWrite. + + Returns: + A grad `Tensor`, the gradient created in an upstream ReadGrad or PackGrad. + """ + # handle is the output store_handle of TensorArrayReadGrad or + # the handle output of TensorArrayWriteGrad. we must use this one. + handle = op.inputs[0] + index = op.inputs[1] + dtype = op.get_attr("T") + grad_source = _GetGradSource(flow) + flow_out = array_ops.identity(op.outputs[0], "flow_out") + # Avoid a race condition where the TensorArrayGrad op is executed before the + # final TensorArrayWrite by adding a control dependency on the output flow of + # the write to the input flow to the TensorArrayGrad. + with ops.control_dependencies([flow_out]): + flow = array_ops.identity(flow, "write_barrier") + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + grad = g.read(index) + return [None, None, grad, flow] + + +@ops.RegisterGradient("TensorArrayGather") +@ops.RegisterGradient("TensorArrayGatherV2") +@ops.RegisterGradient("TensorArrayGatherV3") +def _TensorArrayGatherGrad(op: ops.Operation, grad): + """Gradient for TensorArrayGather. + + Args: + op: Forward TensorArrayGather op. + grad: Gradient `Tensor` to TensorArrayGather. + + Returns: + A flow `Tensor`, which can be used in control dependencies to + force the write of `grad` to the gradient `TensorArray`. + """ + # Note: the forward flow dependency in the call to grad() is necessary for + # the case of dynamic sized TensorArrays. When creating the gradient + # TensorArray, the final size of the forward array must be known. + # For this we need to wait until it has been created by depending on + # the input flow of the original op. + handle = op.inputs[0] + indices = op.inputs[1] + flow = op.inputs[2] + dtype = op.get_attr("dtype") + grad_source = _GetGradSource(grad) + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + u_g = g.scatter(indices, grad) + return [None, None, u_g.flow] + + +@ops.RegisterGradient("TensorArrayScatter") +@ops.RegisterGradient("TensorArrayScatterV2") +@ops.RegisterGradient("TensorArrayScatterV3") +def _TensorArrayScatterGrad(op: ops.Operation, flow): + """Gradient for TensorArrayScatter. + + Args: + op: Forward TensorArrayScatter op. + flow: Gradient `Tensor` flow to TensorArrayScatter. + + Returns: + A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad. + """ + handle = op.inputs[0] + indices = op.inputs[1] + dtype = op.get_attr("T") + grad_source = _GetGradSource(flow) + flow_out = array_ops.identity(op.outputs[0], "flow_out") + # Avoid a race condition where the TensorArrayGrad op is executed before the + # TensorArrayScatter by adding a control dependency on the output flow of + # the scatter to the input flow to the TensorArrayGrad. + with ops.control_dependencies([flow_out]): + flow = array_ops.identity(flow, "write_barrier") + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + grad = g.gather(indices) + return [None, None, grad, flow] + + +@ops.RegisterGradient("TensorArrayConcat") +@ops.RegisterGradient("TensorArrayConcatV2") +@ops.RegisterGradient("TensorArrayConcatV3") +def _TensorArrayConcatGrad(op: ops.Operation, grad, unused_lengths_grad): + """Gradient for TensorArrayConcat. + + Args: + op: Forward TensorArrayConcat op. + grad: Gradient `Tensor` to TensorArrayConcat. + + Returns: + A flow `Tensor`, which can be used in control dependencies to + force the write of `grad` to the gradient `TensorArray`. + """ + # Note: the forward flow dependency in the call to grad() is necessary for + # the case of dynamic sized TensorArrays. When creating the gradient + # TensorArray, the final size of the forward array must be known. + # For this we need to wait until it has been created by depending on + # the input flow of the original op. + handle = op.inputs[0] + flow = op.inputs[1] + lengths = op.outputs[1] + dtype = op.get_attr("dtype") + grad_source = _GetGradSource(grad) + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + u_g = g.split(grad, lengths=lengths) + # handle, flow_in + return [None, u_g.flow] + + +@ops.RegisterGradient("TensorArraySplit") +@ops.RegisterGradient("TensorArraySplitV2") +@ops.RegisterGradient("TensorArraySplitV3") +def _TensorArraySplitGrad(op: ops.Operation, flow): + """Gradient for TensorArraySplit. + + Args: + op: Forward TensorArraySplit op. + flow: Gradient `Tensor` flow to TensorArraySplit. + + Returns: + A grad `Tensor`, the gradient created in upstream ReadGrads or PackGrad. + """ + handle = op.inputs[0] + dtype = op.get_attr("T") + grad_source = _GetGradSource(flow) + flow_out = array_ops.identity(op.outputs[0], "flow_out") + # Avoid a race condition where the TensorArrayGrad op is executed before the + # TensorArraySplit by adding a control dependency on the output flow of + # the split to the input flow to the TensorArrayGrad. + with ops.control_dependencies([flow_out]): + flow = array_ops.identity(flow, "write_barrier") + g = (tensor_array_ops.TensorArray(dtype=dtype, handle=handle, flow=flow, + colocate_with_first_write_call=False) + .grad(source=grad_source, flow=flow)) + grad = g.concat() + # handle, value, lengths, flow_in + return [None, grad, None, flow] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..287f789f5ab74f67295eec55720bd402979dbba7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/tensor_array_ops.py @@ -0,0 +1,1544 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorArray: a dynamically sized array of Tensors.""" +# Mixture of pep8 and non-pep8 names, so disable pylint bad-name +# pylint: disable=g-bad-name + +import contextlib +import traceback +import weakref + +import numpy as np + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import gen_control_flow_ops +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import trace +from tensorflow.python.util import tf_should_use +from tensorflow.python.util.tf_export import tf_export + + +# _GraphTensorArray accesses many of the hidden generated ops, but is in +# fact built to wrap these methods. +# pylint: disable=protected-access +class _GraphTensorArray: + """Graph-mode implementation of TensorArray.""" + + def __init__(self, + dtype, + size=None, + dynamic_size=None, + clear_after_read=None, + tensor_array_name=None, + handle=None, + flow=None, + infer_shape=True, + element_shape=None, + colocate_with_first_write_call=True, + name=None): + """Constructs a graph mode TensorArray. + + Args: + dtype: (required) data type of the TensorArray. + size: (optional) int32 scalar `Tensor`: the size of the TensorArray. + Required if handle is not provided. + dynamic_size: (optional) Python bool: If true, writes to the TensorArray + can grow the TensorArray past its initial size. Default: False. + clear_after_read: Boolean (optional, default: True). If True, clear + TensorArray values after reading them. This disables read-many + semantics, but allows early release of memory. + tensor_array_name: (optional) Python string: the name of the TensorArray. + This is used when creating the TensorArray handle. If this value is + set, handle should be None. + handle: (optional) A `Tensor` handle to an existing TensorArray. If this + is set, tensor_array_name should be None. Only supported in graph mode. + flow: (optional) A float `Tensor` scalar coming from an existing + `TensorArray.flow`. Only supported in graph mode. + infer_shape: (optional, default: True) If True, shape inference is + enabled. In this case, all elements must have the same shape. + element_shape: (optional, default: None) A `TensorShape` object specifying + the shape constraints of each of the elements of the TensorArray. Need + not be fully defined. + colocate_with_first_write_call: If `True`, the TensorArray will be + colocated on the same device as the Tensor used on its first write + (write operations include `write`, `unstack`, and `split`). If `False`, + the TensorArray will be placed on the device determined by the device + context available during its initialization. + name: A name for the operation (optional). + + Raises: + ValueError: if both handle and tensor_array_name are provided. + TypeError: if handle is provided but is not a Tensor. + """ + if handle is not None and tensor_array_name: + raise ValueError( + "Cannot provide both `handle` and `tensor_array_name` arguments at " + "the same time.") + if handle is not None and not isinstance(handle, tensor_lib.Tensor): + raise TypeError( + f"Expected `handle` to be a Tensor, but got `{handle}` of type " + f"`{type(handle)}` instead.") + if handle is None and size is None: + raise ValueError( + "Argument `size` must be provided if handle is not provided.") + if handle is not None and size is not None: + raise ValueError("Cannot provide both a `handle` and `size` arguments " + "at the same time.") + if handle is not None and element_shape is not None: + raise ValueError( + "Cannot provide both `handle` and `element_shape` arguments " + "at the same time.") + if handle is not None and dynamic_size is not None: + raise ValueError( + "Cannot provide both `handle` and `dynamic_size` arguments " + "at the same time.") + if handle is not None and clear_after_read is not None: + raise ValueError( + "Cannot provide both `handle` and `clear_after_read` arguments " + "at the same time.") + + if clear_after_read is None: + clear_after_read = True + self._dynamic_size = dynamic_size or False + self._dtype = dtypes.as_dtype(dtype).base_dtype + + # Used to keep track of what tensors the TensorArray should be + # colocated with. We choose to colocate the TensorArray with the + # first tensor written to it. + self._colocate_with_first_write_call = colocate_with_first_write_call + if colocate_with_first_write_call: + self._colocate_with = [] + else: + self._colocate_with = None + + # Record the current static shape for the array elements. The element + # shape is defined either by `element_shape` or the shape of the tensor + # of the first write. If `infer_shape` is true, all writes checks for + # shape equality. + self._element_shape = [tensor_shape.as_shape(element_shape)] + self._infer_shape = infer_shape + self._size = size + with ops.name_scope(name, "TensorArray", [handle, size, flow]) as scope: + if handle is not None: + self._handle = handle + if flow is None: + raise ValueError("flow must not be None if handle is not None.") + self._flow = flow + else: + # Construct the TensorArray with an empty device. The first + # write into the TensorArray from a Tensor with a set device + # will retroactively set the device value of this op. + def create(): + """Create the TensorArray op.""" + return gen_data_flow_ops.tensor_array_v3( + dtype=dtype, + size=size, + element_shape=element_shape, + identical_element_shapes=infer_shape, + dynamic_size=self._dynamic_size, + clear_after_read=clear_after_read, + tensor_array_name=tensor_array_name, + name=scope) + + if colocate_with_first_write_call: + with ops.device(None), ops.colocate_with(None, ignore_existing=True): + self._handle, self._flow = create() + else: + self._handle, self._flow = create() + + @property + def flow(self): + return self._flow + + @property + def dtype(self): + return self._dtype + + @property + def handle(self): + return self._handle + + @property + def element_shape(self): + return self._element_shape[0] + + def _check_element_shape(self, shape): + """Changes the element shape of the array given a shape to merge with. + + Args: + shape: A `TensorShape` object to merge with. + + Raises: + ValueError: if the provided shape is incompatible with the current + element shape of the `TensorArray`. + """ + if not shape.is_compatible_with(self.element_shape): + raise ValueError("Inconsistent shapes: saw %s but expected %s " % + (shape, self.element_shape)) + if self._infer_shape: + self._element_shape[0] = self.element_shape.merge_with(shape) + + @contextlib.contextmanager + def _maybe_colocate_with(self, value): + """Colocate operations with an internal colocation group or `value`. + + Args: + value: `Tensor`, the tensor to try to colocate with. + + Yields: + Does not yield anything, but the new context is a colocation context. + + If no internal colocation group is set, colocate with `value` and set + the internal colocation group to be value. + """ + if not self._colocate_with_first_write_call: + yield + else: + if not self._colocate_with: + self._colocate_with.append(value) + with ops.colocate_with(self._colocate_with[0]): + yield + + def identity(self): + """See TensorArray.""" + flow = array_ops.identity(self._flow) + return build_ta_with_new_flow(self, flow) + + def grad(self, source, flow=None, name=None): + """See TensorArray.""" + # tensor_array_grad requires a flow input when forward + # TensorArrays are dynamically sized. This forces the creation + # of the grad TensorArray only once the final forward array's size + # is fixed. + if flow is None: + flow = self.flow + with ops.name_scope(name, "TensorArrayGrad", [self._handle]): + with ops.colocate_with(self._handle): + g_handle, unused_flow = gen_data_flow_ops.tensor_array_grad_v3( + handle=self._handle, source=source, flow_in=flow, name=name) + with ops.control_dependencies([g_handle]): + flow = array_ops.identity(flow, name="gradient_flow") + g = TensorArray( + dtype=self._dtype, + handle=g_handle, + flow=flow, + infer_shape=self._infer_shape, + colocate_with_first_write_call=False) + # pylint: disable=protected-access + g._implementation._element_shape = self._element_shape + # pylint: enable=protected-access + return g + + def read(self, index, name=None): + """See TensorArray.""" + value = gen_data_flow_ops.tensor_array_read_v3( + handle=self._handle, + index=index, + flow_in=self._flow, + dtype=self._dtype, + name=name) + if self._element_shape: + value.set_shape(self._element_shape[0].dims) + return value + + def write(self, index, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayWrite", [self._handle, index, value]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + self._check_element_shape(value.shape) + with self._maybe_colocate_with(value): + flow_out = gen_data_flow_ops.tensor_array_write_v3( + handle=self._handle, + index=index, + value=value, + flow_in=self._flow, + name=name) + return build_ta_with_new_flow(self, flow_out) + + def stack(self, name=None): + """See TensorArray.""" + with ops.colocate_with(self._handle): + with ops.name_scope(name, "TensorArrayStack", [self._handle]): + value = self.gather(math_ops.range(0, self.size()), name=name) + if (self.element_shape and not self._dynamic_size and + self._size is not None): + value.set_shape([tensor_util.constant_value(self._size)] + + self.element_shape.dims) + return value + + def gather(self, indices, name=None): + """See TensorArray.""" + if self._element_shape: + element_shape = self._element_shape[0] + else: + element_shape = tensor_shape.unknown_shape(None) + value = gen_data_flow_ops.tensor_array_gather_v3( + handle=self._handle, + indices=indices, + flow_in=self._flow, + dtype=self._dtype, + name=name, + element_shape=element_shape) + if self.element_shape: + value.set_shape([None] + self.element_shape.dims) + return value + + def concat(self, name=None): + """See TensorArray.""" + value, _ = gen_data_flow_ops.tensor_array_concat_v3( + handle=self._handle, + flow_in=self._flow, + dtype=self._dtype, + name=name, + element_shape_except0=self.element_shape[1:]) + if self.element_shape: + dim0 = None + if self._infer_shape: + size = tensor_util.constant_value(self.size()) + if size is not None and self.element_shape[0] is not None: + dim0 = size * self.element_shape[0] + value.set_shape([dim0] + self.element_shape.dims[1:]) + return value + + @tf_should_use.should_use_result + def unstack(self, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayUnstack", [self._handle, value]): + num_elements = array_ops.shape(value)[0] + return self.scatter( + indices=math_ops.range(0, num_elements), value=value, name=name) + + @tf_should_use.should_use_result + def scatter(self, indices, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayScatter", + [self._handle, value, indices]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + if not context.executing_eagerly(): + self._check_element_shape(value.shape[1:]) + with self._maybe_colocate_with(value): + flow_out = gen_data_flow_ops.tensor_array_scatter_v3( + handle=self._handle, + indices=indices, + value=value, + flow_in=self._flow, + name=name) + return build_ta_with_new_flow(self, flow_out) + + @tf_should_use.should_use_result + def split(self, value, lengths, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArraySplit", + [self._handle, value, lengths]): + value = ops.convert_to_tensor(value, dtype=self._dtype, name="value") + with self._maybe_colocate_with(value): + lengths_64 = math_ops.cast(lengths, dtypes.int64) + if not context.executing_eagerly(): + clengths = tensor_util.constant_value(lengths_64) + if value.shape.dims is not None and clengths is not None: + if clengths.shape and clengths.max() == clengths.min(): + self._check_element_shape( + tensor_shape.TensorShape([clengths[0] + ]).concatenate(value.shape[1:])) + flow_out = gen_data_flow_ops.tensor_array_split_v3( + handle=self._handle, + value=value, + lengths=lengths_64, + flow_in=self._flow, + name=name) + return build_ta_with_new_flow(self, flow_out) + + def size(self, name=None): + """See TensorArray.""" + if not self._dynamic_size and self._size is not None: + return ops.convert_to_tensor(self._size, dtype=dtypes.int32) + else: + return gen_data_flow_ops.tensor_array_size_v3( + handle=self._handle, flow_in=self.flow, name=name) + + @tf_should_use.should_use_result + def close(self, name=None): + """See TensorArray.""" + return gen_data_flow_ops.tensor_array_close_v3( + handle=self._handle, name=name) + + +class _GraphTensorArrayV2: + """Graph-mode implementation of TensorArray backed by TensorLists. + + The backing tensor of this TensorArray is a TensorList variant tensor which is + stored in the `flow`. The `handle` is always none here. The reason we use the + `flow` field and not the `handle` field is to ensure backwards compatibility + with legacy control flow. + """ + + def __init__(self, + dtype, + size=None, + dynamic_size=None, + clear_after_read=None, + tensor_array_name=None, + handle=None, + flow=None, + infer_shape=True, + element_shape=None, + colocate_with_first_write_call=True, + name=None): + """Constructs a graph mode TensorArray. + + Args: + dtype: (required) data type of the TensorArray. + size: (optional) int32 scalar `Tensor`: the size of the TensorArray. + Required if flow is not provided. + dynamic_size: (optional) Python bool: If true, writes to the TensorArray + can grow the TensorArray past its initial size. Default: False. + clear_after_read: (optional) unused. Not supported in TensorLists. + tensor_array_name: (optional) unused. + handle: (optional) Must always be None. + flow: (optional) A variant `Tensor` scalar for a TensorList. + infer_shape: (optional, default: True) If True, shape inference is + enabled. In this case, all elements must have the same shape. + element_shape: (optional, default: None) A `TensorShape` object specifying + the shape constraints of each of the elements of the TensorArray. Need + not be fully defined. + colocate_with_first_write_call: (optional). unused. + name: (optional) A name for the operation. + + Raises: + ValueError: if both handle and tensor_array_name are provided. + TypeError: if handle is provided but is not a Tensor. + """ + assert handle is None + del handle + del clear_after_read + del tensor_array_name + del colocate_with_first_write_call + + self._dynamic_size = dynamic_size + self._size = size + + if flow is not None and ( + not isinstance(flow, tensor_lib.Tensor) or flow.dtype != dtypes.variant + ): + raise TypeError( + f"Expected `flow` to be a variant tensor, but received `{flow.dtype}`" + " instead." + ) + if flow is None and size is None: + raise ValueError( + "Argument `size` must be provided if argument `flow` is not provided." + ) + if flow is not None and size is not None: + raise ValueError( + "Cannot provide both `flow` and `size` arguments at the same time." + ) + if flow is not None and element_shape is not None: + raise ValueError( + "Cannot provide both `flow` and `element_shape` arguments" + "at the same time." + ) + + self._dtype = dtypes.as_dtype(dtype).base_dtype + + # Record the current static shape for the array elements. The element + # shape is defined either by `element_shape` or the shape of the tensor + # of the first write. If `infer_shape` is true, all writes checks for + # shape equality. + self._element_shape = [tensor_shape.as_shape(element_shape)] + self._infer_shape = infer_shape + with ops.name_scope(name, "TensorArrayV2", [size, flow]) as scope: + if flow is None: + self._flow = list_ops.tensor_list_reserve( + element_shape=element_shape, + num_elements=size, + element_dtype=dtype, + name=scope) + else: + self._flow = flow + + # For backwards compatibility. + self._colocate_with_first_write_call = None + self._colocate_with = None + + @property + def flow(self): + return self._flow + + @property + def dtype(self): + return self._dtype + + @property + def element_shape(self): + return self._element_shape[0] + + @property + def handle(self): + # We intentionally do not raise an error so that legacy while_loop does not + # complain. + return None + + def _check_element_shape(self, shape): + """Changes the element shape of the array given a shape to merge with. + + Args: + shape: A `TensorShape` object to merge with. + + Raises: + ValueError: if the provided shape is incompatible with the current + element shape of the `TensorArray`. + """ + if not shape.is_compatible_with(self.element_shape): + raise ValueError("Inconsistent shapes: saw %s but expected %s " % + (shape, self.element_shape)) + if self._infer_shape: + self._element_shape[0] = self.element_shape.merge_with(shape) + + def identity(self): + """See TensorArray.""" + flow = array_ops.identity(self._flow) + return build_ta_with_new_flow(self, flow) + + def grad(self, source, flow=None, name=None): + """Not supported.""" + raise NotImplementedError() + + def read(self, index, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayV2Read", [self._flow, index]): + value = list_ops.tensor_list_get_item( + input_handle=self._flow, + index=index, + element_dtype=self._dtype, + element_shape=self.element_shape, + name=name) + return value + + def write(self, index, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayV2Write", [self._flow, index, value]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + self._check_element_shape(value.shape) + flow_out = list_ops.tensor_list_set_item( + input_handle=self._flow, + index=index, + item=value, + resize_if_index_out_of_bounds=self._dynamic_size, + name=name) + return build_ta_with_new_flow(self, flow_out) + + def stack(self, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayV2Stack", [self._flow]): + # TODO(b/139941163): remove constant_value after changing num_elements to regular input + if not self._dynamic_size and self._size is not None: + ta_size = tensor_util.constant_value(self._size) + else: + ta_size = -1 + value = list_ops.tensor_list_stack( + input_handle=self._flow, + element_dtype=self._dtype, + num_elements=ta_size, + element_shape=self.element_shape) + return value + + def gather(self, indices, name=None): + """See TensorArray.""" + value = list_ops.tensor_list_gather( + input_handle=self._flow, + indices=indices, + element_dtype=self._dtype, + element_shape=self.element_shape, + name=name) + return value + + def concat(self, name=None): + """See TensorArray.""" + if self.element_shape: + element_shape = [None] + self.element_shape.dims[1:] + else: + element_shape = None + + value = list_ops.tensor_list_concat( + input_handle=self._flow, + element_dtype=self._dtype, + element_shape=element_shape, + name=name) + return value + + @tf_should_use.should_use_result + def unstack(self, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayUnstack", [self._flow, value]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + self._check_element_shape(value.shape[1:]) + flow_out = list_ops.tensor_list_from_tensor( + tensor=value, element_shape=value.shape[1:]) + return build_ta_with_new_flow(self, flow_out) + + @tf_should_use.should_use_result + def scatter(self, indices, value, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArrayScatter", + [self._flow, value, indices]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + self._check_element_shape(value.shape[1:]) + flow_out = list_ops.tensor_list_scatter( + tensor=value, + indices=indices, + element_shape=self.element_shape, + input_handle=self._flow) + return build_ta_with_new_flow(self, flow_out) + + @tf_should_use.should_use_result + def split(self, value, lengths, name=None): + """See TensorArray.""" + with ops.name_scope(name, "TensorArraySplit", [self._flow, value, lengths]): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + lengths_64 = math_ops.cast(lengths, dtypes.int64) + if not context.executing_eagerly(): + clengths = tensor_util.constant_value(lengths_64) + if value.shape.dims is not None and clengths is not None: + if clengths.shape and clengths.max() == clengths.min(): + self._check_element_shape( + tensor_shape.TensorShape([clengths[0] + ]).concatenate(value.shape[1:])) + flow_out = list_ops.tensor_list_split( + tensor=value, + lengths=lengths_64, + element_shape=self.element_shape, + name=name) + return build_ta_with_new_flow(self, flow_out) + + def size(self, name=None): + """See TensorArray.""" + if not self._dynamic_size and self._size is not None: + return ops.convert_to_tensor(self._size, dtype=dtypes.int32) + else: + return list_ops.tensor_list_length(input_handle=self._flow, name=name) + + def close(self, name=None): + """See TensorArray.""" + return gen_control_flow_ops.no_op(name=name) + + +# pylint: enable=protected-access + + +class _EagerTensorArray: + """Eager-compatible implementation of TensorArray.""" + + def __init__(self, + dtype, + size=None, + dynamic_size=None, + clear_after_read=None, + tensor_array_name=None, + handle=None, + flow=None, + infer_shape=True, + element_shape=None, + colocate_with_first_write_call=True, + name=None): + """Constructs a TensorArray compatible with eager execution. + + Args: + dtype: (required) data type of the TensorArray. + size: (optional) int32 scalar `Tensor`: the size of the TensorArray. + Required if handle is not provided. + dynamic_size: (optional) Python bool: If true, writes to the TensorArray + can grow the TensorArray past its initial size. Default: False. + clear_after_read: Boolean (optional, default: True). If True, clear + TensorArray values after reading them. This disables read-many + semantics, but allows early release of memory. + tensor_array_name: unused. + handle: unsupported. + flow: unsupported. + infer_shape: used for error checking, same semantics as TensorArray. + element_shape: used for error checking, same semantics as TensorArray. + colocate_with_first_write_call: unsupported. + name: unsupported. + + Raises: + ValueError: handle or flow are supplied, or if size is not supplied. + """ + + del (flow, tensor_array_name, name) # Unused. + + if handle is not None: + raise ValueError("TensorArray handles are not supported when eager " + "execution is enabled.") + if size is None: + raise ValueError("Size must be declared for TensorArrays when eager " + "execution is enabled.") + + # These attributes are not meaningful when eager is enabled, but some + # library functions (e.g., those in control_flow_ops.py) access them to + # create new tensor arrays; as such, we define them for the sake of + # compatibility. + self._handle = None + # we assign a dummy value to _flow in case other code assumes it to be + # a Tensor + self._flow = constant_op.constant(0, dtype=dtypes.int32) + self._infer_shape = infer_shape + self._element_shape = tensor_shape.as_shape(element_shape) + self._colocate_with_first_write_call = colocate_with_first_write_call + + self._dtype = dtypes.as_dtype(dtype).base_dtype + self._dynamic_size = dynamic_size or False + self._clear_after_read = (True + if clear_after_read is None else clear_after_read) + self._previously_read_indices = [] + + if isinstance(size, ops.EagerTensor): + size = size.numpy() + self._tensor_array = [None for _ in range(size)] + + @property + def flow(self): + """For compatibility; flows are not meaningful when eager is enabled.""" + return self._flow + + @property + def dtype(self): + return self._dtype + + @property + def handle(self): + """For compatibility; handles are not meaningful when eager is enabled.""" + return self._handle + + @property + def element_shape(self): + return self._element_shape + + def identity(self): + """See TensorArray.""" + return self.parent() + + def grad(self, source, flow=None, name=None): + raise NotImplementedError( + "TensorArray.grad is not supported when executing eagerly; eager's " + "gradient implementation does not use/need this function to compute " + "gradients of operations that use TensorArrays.") + + def read(self, index, name=None): + """See TensorArray.""" + del name # not meaningful when executing eagerly. + + if isinstance(index, ops.EagerTensor): + index = index.numpy() + + if index < 0: + raise errors_impl.OutOfRangeError( + None, None, + "Reading from negative indices (index %d) is not allowed." % index) + + if index >= len(self._tensor_array): + raise errors_impl.OutOfRangeError( + None, None, "Tried to read from index %d but array size is: %d " % + (index, len(self._tensor_array))) + + tensor = self._tensor_array[index] + if tensor is None: + if index in self._previously_read_indices: + raise errors_impl.InvalidArgumentError( + None, None, + "Could not read index %d twice because it was cleared after " + "a previous read (perhaps try setting clear_after_read = false?)" % + index) + else: + tensor = self._maybe_zero(index) + + if self._clear_after_read: + self._tensor_array[index] = None + self._previously_read_indices.append(index) + return tensor + + def _write(self, index, value): + """Writes `value` into index named by `index`. + + Args: + index: 0-D. int32 scalar with the index to write to. + value: N-D. Tensor of type `dtype`. The `Tensor` to write to `index`. + + Raises: + errors_impl.InvalidArgumentError: `value` dtype does not match dtype. + errors_impl.OutOfRangeError: `index` is out of bounds. + ValueError: shape of `value` is not consistent with inferred shape. + """ + + if isinstance(index, ops.EagerTensor): + index = index.numpy() + + if index < 0: + raise errors_impl.OutOfRangeError( + None, None, + "Writing to negative indices (index %d) is not allowed." % index) + + size = len(self._tensor_array) + if index >= size: + if not self._dynamic_size: + raise errors_impl.OutOfRangeError( + None, None, + "Tried to write to index %d but array is not resizeable and size " + "is: %d " % (index, size)) + self._tensor_array.extend(None for _ in range(index - size + 1)) + + if not isinstance(value, ops.EagerTensor): + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + + if self._dtype != value.dtype: + raise errors_impl.InvalidArgumentError( + None, None, + "TensorArray dtype is %s but Op is trying to write dtype %s " % + (self._dtype.name, value.dtype.name)) + + if not self._element_shape.is_compatible_with(value.shape): + raise ValueError("Incompatible shape for value (%s), expected (%s)" % + (value.shape, self._element_shape)) + + if self._infer_shape: + self._element_shape = self._element_shape.merge_with(value.shape) + + self._tensor_array[index] = value + + def write(self, index, value, name=None): + """See TensorArray.""" + del name # not meaningful when executing eagerly. + self._write(index, value) + return self.parent() + + def _maybe_zero(self, ix): + val = self._tensor_array[ix] + if val is None: + val = self._tensor_array[ix] = array_ops.zeros( + shape=self._element_shape, dtype=self._dtype) + return val + + def stack(self, name=None): + """See TensorArray.""" + if self._tensor_array: + for ix in range(len(self._tensor_array)): + self._maybe_zero(ix) + if not self._tensor_array and self._element_shape.is_fully_defined(): + return ops.convert_to_tensor( + np.ndarray([0] + self._element_shape), name=name, dtype=self._dtype) + else: + return ops.convert_to_tensor( + self._tensor_array, name=name, dtype=self._dtype) + + def gather(self, indices, name=None): + """See TensorArray.""" + del name # not meaningful when executing eagerly. + if isinstance(indices, ops.EagerTensor): + indices = indices.numpy() + return array_ops_stack.stack([self._maybe_zero(i) for i in indices]) + + def concat(self, name=None): + """See TensorArray.""" + try: + return array_ops.concat( + [self._maybe_zero(ix) for ix in range(len(self._tensor_array))], + 0, + name=name) + except errors_impl.OpError: + # Reproduce a subset of the error-handling for graph-mode TensorArrays. + shapes = [t.shape for t in self._tensor_array] + ndims = [s.ndims for s in shapes] + if 0 in ndims: + idx = ndims.index(0) + raise errors_impl.InvalidArgumentError( + None, None, "Concat saw a scalar shape at index %d but requires " + "at least vectors." % idx) + else: + raise + + def unstack(self, value, name=None): + """See TensorArray.""" + tensors = array_ops_stack.unstack(value, name=name) + if len(tensors) > len(self._tensor_array) and not self._dynamic_size: + raise ValueError( + "Cannot unstack %d tensors into a TensorArray of static size %d " % + (len(tensors), len(self._tensor_array))) + self._tensor_array = tensors + return self.parent() + + def scatter(self, indices, value, name=None): + """See TensorArray.""" + del name # not meaningful when executing eagerly. + if isinstance(indices, ops.EagerTensor): + indices = indices.numpy() + for index, val in zip(indices, array_ops_stack.unstack(value)): + self._write(index, val) # pylint: disable=protected-access + return self.parent() + + def split(self, value, lengths, name=None): + """See TensorArray.""" + # TODO(b/129870929): Fix after all callers provide proper init dtype. + value = ops.convert_to_tensor( + value, preferred_dtype=self._dtype, name="value") + _check_dtypes(value, self._dtype) + lengths = ops.convert_to_tensor(lengths) + sum_lengths = math_ops.reduce_sum(lengths) + if lengths.shape.ndims != 1: + raise errors_impl.InvalidArgumentError( + None, None, "Expected lengths to be a vector, received shape: %s " % + lengths.shape.as_list()) + elif value.shape.ndims == 0: + raise errors_impl.InvalidArgumentError( + None, None, "Expected value to be at least a vector, " + "but received shape: %s " % value.shape.as_list()) + elif sum_lengths.numpy() != value.shape.as_list()[0]: + raise errors_impl.InvalidArgumentError( + None, None, "Expected sum of lengths to be equal to " + "values.shape[0], but sum of lengths is %d and " + "value's shape is: %s " % (sum_lengths.numpy(), + value.shape.as_list())) + elif not self._dynamic_size and lengths.shape[0] != len(self._tensor_array): + raise errors_impl.InvalidArgumentError( + None, None, "TensorArray's size is not equal to the size of " + "lengths (%d vs. %d), and the TensorArray is not marked as " + "dynamically resizeable." % + (len(self._tensor_array), lengths.shape[0])) + else: + self._tensor_array = array_ops.split(value, lengths, name=name) + return self.parent() + + def size(self, name=None): + """See TensorArray.""" + del name # not meaningful when executing eagerly. + return constant_op.constant(len(self._tensor_array)) + + def close(self, name=None): + del name # not meaningful when executing eagerly. + del self._tensor_array[:] + + +# TensorArray is designed to hide an underlying implementation object +# and as such accesses many of that object's hidden fields. +# pylint: disable=protected-access +# pylint:disable=line-too-long +@tf_export("TensorArray") +class TensorArray: + """Class wrapping dynamic-sized, per-time-step, Tensor arrays. + + This class is meant to be used with dynamic iteration primitives such as + `while_loop` and `map_fn`. It supports gradient back-propagation via special + "flow" control flow dependencies. + + Note that although the array can be read multiple times and positions can be + overwritten, behavior may be undefined when storing multiple references to + the same array and clear_after_read is False. In particular, avoid using + methods like concat() to convert an intermediate TensorArray to a Tensor, + then further modifying the TensorArray, particularly if you need to backprop + through it later. + + Example 1: Plain reading and writing. + + >>> ta = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=False) + >>> ta = ta.write(0, 10) + >>> ta = ta.write(1, 20) + >>> ta = ta.write(2, 30) + >>> + >>> ta.read(0) + + >>> ta.read(1) + + >>> ta.read(2) + + >>> ta.stack() + + + Example 2: Fibonacci sequence algorithm that writes in a loop then returns. + + >>> @tf.function + ... def fibonacci(n): + ... ta = tf.TensorArray(tf.float32, size=0, dynamic_size=True) + ... ta = ta.unstack([0., 1.]) + ... + ... for i in range(2, n): + ... ta = ta.write(i, ta.read(i - 1) + ta.read(i - 2)) + ... + ... return ta.stack() + >>> + >>> fibonacci(7) + + + Example 3: A simple loop interacting with a `tf.Variable`. + + >>> v = tf.Variable(1) + >>> @tf.function + ... def f(x): + ... ta = tf.TensorArray(tf.int32, size=0, dynamic_size=True) + ... for i in tf.range(x): + ... v.assign_add(i) + ... ta = ta.write(i, v) + ... return ta.stack() + >>> f(5) + + """ + + def __init__(self, + dtype, + size=None, + dynamic_size=None, + clear_after_read=None, + tensor_array_name=None, + handle=None, + flow=None, + infer_shape=True, + element_shape=None, + colocate_with_first_write_call=True, + name=None): + """Construct a new TensorArray or wrap an existing TensorArray handle. + + A note about the parameter `name`: + + The name of the `TensorArray` (even if passed in) is uniquified: each time + a new `TensorArray` is created at runtime it is assigned its own name for + the duration of the run. This avoids name collisions if a `TensorArray` + is created within a `while_loop`. + + Args: + dtype: (required) data type of the TensorArray. + size: (optional) int32 scalar `Tensor`: the size of the TensorArray. + Required if handle is not provided. + dynamic_size: (optional) Python bool: If true, writes to the TensorArray + can grow the TensorArray past its initial size. Default: False. + clear_after_read: Boolean (optional, default: True). If True, clear + TensorArray values after reading them. This disables read-many + semantics, but allows early release of memory. + tensor_array_name: (optional) Python string: the name of the TensorArray. + This is used when creating the TensorArray handle. If this value is + set, handle should be None. + handle: (optional) A `Tensor` handle to an existing TensorArray. If this + is set, tensor_array_name should be None. Only supported in graph mode. + flow: (optional) A float `Tensor` scalar coming from an existing + `TensorArray.flow`. Only supported in graph mode. + infer_shape: (optional, default: True) If True, shape inference is + enabled. In this case, all elements must have the same shape. + element_shape: (optional, default: None) A `TensorShape` object specifying + the shape constraints of each of the elements of the TensorArray. Need + not be fully defined. + colocate_with_first_write_call: If `True`, the TensorArray will be + colocated on the same device as the Tensor used on its first write + (write operations include `write`, `unstack`, and `split`). If `False`, + the TensorArray will be placed on the device determined by the device + context available during its initialization. + name: A name for the operation (optional). + + Raises: + ValueError: if both handle and tensor_array_name are provided. + TypeError: if handle is provided but is not a Tensor. + """ + if (context.executing_eagerly() and + (flow is None or flow.dtype != dtypes.variant)): + # It is possible to create a Variant-style TensorArray even in eager mode, + # and this is fine but can have performance implications in eager. + # An example of when this happens is if a tf.function returns a + # TensorArray in its output; its flow variant object is returned to Eager. + # This can be wrapped back up in a Variant-style TensorArray. + implementation = _EagerTensorArray + elif (flow is not None and flow.dtype == dtypes.variant or + control_flow_util.EnableControlFlowV2(ops.get_default_graph())): + implementation = _GraphTensorArrayV2 + else: + implementation = _GraphTensorArray + self._implementation = implementation( + dtype, + size=size, + dynamic_size=dynamic_size, + clear_after_read=clear_after_read, + tensor_array_name=tensor_array_name, + handle=handle, + flow=flow, + infer_shape=infer_shape, + element_shape=element_shape, + colocate_with_first_write_call=colocate_with_first_write_call, + name=name) + + self._implementation.parent = weakref.ref(self) + + @property + def flow(self): + """The flow `Tensor` forcing ops leading to this TensorArray state.""" + return self._implementation._flow + + @property + def dtype(self): + """The data type of this TensorArray.""" + return self._implementation._dtype + + @property + def handle(self): + """The reference to the TensorArray.""" + return self._implementation.handle + + @property + def element_shape(self): + """The `tf.TensorShape` of elements in this TensorArray.""" + return self._implementation.element_shape + + @property + def dynamic_size(self): + """Python bool; if `True` the TensorArray can grow dynamically.""" + return self._implementation._dynamic_size + + @property + def _infer_shape(self): + # TODO(slebedev): consider making public or changing TensorArrayStructure + # to access _implementation directly. Note that dynamic_size is also + # only used by TensorArrayStructure. + return self._implementation._infer_shape + + def identity(self): + """Returns a TensorArray with the same content and properties. + + Returns: + A new TensorArray object with flow that ensures the control dependencies + from the contexts will become control dependencies for writes, reads, etc. + Use this object for all subsequent operations. + """ + return self._implementation.identity() + + def grad(self, source, flow=None, name=None): + return self._implementation.grad(source, flow=flow, name=name) + + def read(self, index, name=None): + """Read the value at location `index` in the TensorArray. + + Args: + index: 0-D. int32 tensor with the index to read from. + name: A name for the operation (optional). + + Returns: + The tensor at index `index`. + """ + return self._implementation.read(index, name=name) + + @tf_should_use.should_use_result(warn_in_eager=True) + def write(self, index, value, name=None): + """Write `value` into index `index` of the TensorArray. + + Args: + index: 0-D. int32 scalar with the index to write to. + value: N-D. Tensor of type `dtype`. The Tensor to write to this index. + name: A name for the operation (optional). + + Returns: + A new TensorArray object with flow that ensures the write occurs. + Use this object for all subsequent operations. + + Raises: + ValueError: if there are more writers than specified. + """ + return self._implementation.write(index, value, name=name) + + def stack(self, name=None): + """Return the values in the TensorArray as a stacked `Tensor`. + + All of the values must have been written and their shapes must all match. + If input shapes have rank-`R`, then output shape will have rank-`(R+1)`. + + For example: + + + >>> ta = tf.TensorArray(tf.int32, size=3) + >>> ta = ta.write(0, tf.constant([1, 2])) + >>> ta = ta.write(1, tf.constant([3, 4])) + >>> ta = ta.write(2, tf.constant([5, 6])) + >>> ta.stack() + + + + Args: + name: A name for the operation (optional). + + Returns: + All the tensors in the TensorArray stacked into one tensor. + """ + return self._implementation.stack(name=name) + + def gather(self, indices, name=None): + """Return selected values in the TensorArray as a packed `Tensor`. + + All of selected values must have been written and their shapes + must all match. + + Args: + indices: A `1-D` `Tensor` taking values in `[0, max_value)`. If the + `TensorArray` is not dynamic, `max_value=size()`. + name: A name for the operation (optional). + + Returns: + The tensors in the `TensorArray` selected by `indices`, packed into one + tensor. + """ + return self._implementation.gather(indices, name=name) + + def concat(self, name=None): + """Return the values in the TensorArray as a concatenated `Tensor`. + + All of the values must have been written, their ranks must match, and + and their shapes must all match for all dimensions except the first. + + Args: + name: A name for the operation (optional). + + Returns: + All the tensors in the TensorArray concatenated into one tensor. + """ + return self._implementation.concat(name=name) + + @tf_should_use.should_use_result + def unstack(self, value, name=None): + """Unstack the values of a `Tensor` in the TensorArray. + + If input value shapes have rank-`R`, then the output TensorArray will + contain elements whose shapes are rank-`(R-1)`. + + Args: + value: (N+1)-D. Tensor of type `dtype`. The Tensor to unstack. + name: A name for the operation (optional). + + Returns: + A new TensorArray object with flow that ensures the unstack occurs. + Use this object for all subsequent operations. + + Raises: + ValueError: if the shape inference fails. + """ + return self._implementation.unstack(value, name=name) + + @tf_should_use.should_use_result + def scatter(self, indices, value, name=None): + """Scatter the values of a `Tensor` in specific indices of a `TensorArray`. + + Args: + indices: A `1-D` `Tensor` taking values in `[0, max_value)`. If the + `TensorArray` is not dynamic, `max_value=size()`. + value: (N+1)-D. Tensor of type `dtype`. The Tensor to unpack. + name: A name for the operation (optional). + + Returns: + A new TensorArray object with flow that ensures the scatter occurs. + Use this object for all subsequent operations. + + Raises: + ValueError: if the shape inference fails. + """ + return self._implementation.scatter(indices, value, name=name) + + @tf_should_use.should_use_result + def split(self, value, lengths, name=None): + """Split the values of a `Tensor` into the TensorArray. + + Args: + value: (N+1)-D. Tensor of type `dtype`. The Tensor to split. + lengths: 1-D. int32 vector with the lengths to use when splitting `value` + along its first dimension. + name: A name for the operation (optional). + + Returns: + A new TensorArray object with flow that ensures the split occurs. + Use this object for all subsequent operations. + + Raises: + ValueError: if the shape inference fails. + """ + return self._implementation.split(value, lengths, name=name) + + def size(self, name=None): + """Return the size of the TensorArray.""" + return self._implementation.size(name=name) + + @tf_should_use.should_use_result + def close(self, name=None): + """Close the current TensorArray.""" + return self._implementation.close(name=name) + + def __tf_tracing_type__(self, _): + return TensorArrayTraceType(self) + + +def build_ta_with_new_flow(old_ta, flow): + """Builds a TensorArray with a new `flow` tensor.""" + # Sometimes we get old_ta as the implementation, sometimes it's the + # TensorArray wrapper object. + impl = (old_ta._implementation if isinstance(old_ta, TensorArray) else old_ta) + + if not context.executing_eagerly(): + if (not isinstance(impl, _GraphTensorArrayV2) and + control_flow_util.EnableControlFlowV2(ops.get_default_graph())): + raise NotImplementedError("Attempting to build a graph-mode TF2-style " + "TensorArray from either an eager-mode " + "TensorArray or a TF1-style TensorArray. " + "This is not currently supported. You may be " + "attempting to capture a TensorArray " + "inside a tf.function or tf.data map function. " + "Instead, construct a new TensorArray inside " + "the function.") + new_ta = TensorArray( + dtype=impl.dtype, + handle=impl.handle, + flow=flow, + infer_shape=impl._infer_shape, + colocate_with_first_write_call=impl._colocate_with_first_write_call) + new_impl = new_ta._implementation + new_impl._dynamic_size = impl._dynamic_size + new_impl._size = impl._size + new_impl._colocate_with = impl._colocate_with + new_impl._element_shape = impl._element_shape # Share _element_shape. + return new_ta + + +# pylint: enable=protected-access + + +def _check_dtypes(value, dtype): + if value.dtype != dtype: + logging.error("Error: Input value {} has dtype {}, but expected dtype {}. " + "This leads to undefined behavior and will be an error " + "in future versions of TensorFlow. Traceback:\n{}".format( + value, str(value.dtype), str(dtype), + "".join(traceback.format_stack()))) + + +@tf_export("TensorArraySpec") +@type_spec_registry.register("tf.TensorArraySpec") +class TensorArraySpec(type_spec.TypeSpec): + """Type specification for a `tf.TensorArray`.""" + + __slots__ = ["_element_shape", "_dtype", "_dynamic_size", "_infer_shape"] + + value_type = property(lambda self: TensorArray) + + def __init__(self, + element_shape=None, + dtype=dtypes.float32, + dynamic_size=False, + infer_shape=True): + """Constructs a type specification for a `tf.TensorArray`. + + Args: + element_shape: The shape of each element in the `TensorArray`. + dtype: Data type of the `TensorArray`. + dynamic_size: Whether the `TensorArray` can grow past its initial size. + infer_shape: Whether shape inference is enabled. + """ + self._element_shape = tensor_shape.as_shape(element_shape) + self._dtype = dtypes.as_dtype(dtype) + self._dynamic_size = dynamic_size + self._infer_shape = infer_shape + + def is_subtype_of(self, other): + # pylint: disable=protected-access + return (isinstance(other, TensorArraySpec) and + self._dtype == other._dtype and + self._dynamic_size == other._dynamic_size) + + def most_specific_common_supertype(self, others): + """Returns the most specific supertype of `self` and `others`. + + Args: + others: A Sequence of `TypeSpec`. + + Returns `None` if a supertype does not exist. + """ + # pylint: disable=protected-access + if not all(isinstance(other, TensorArraySpec) for other in others): + return False + + common_shape = self._element_shape.most_specific_common_supertype( + other._element_shape for other in others) + if common_shape is None: + return None + + if not all(self._dtype == other._dtype for other in others): + return None + + if not all(self._dynamic_size == other._dynamic_size for other in others): + return None + + infer_shape = self._infer_shape and all( + other._infer_shape for other in others) + + return TensorArraySpec(common_shape, self._dtype, self._dynamic_size, + infer_shape) + + def is_compatible_with(self, other): + # pylint: disable=protected-access + if not isinstance(other, type_spec.TypeSpec): + other = type_spec.type_spec_from_value(other) + + # Note: we intentionally exclude infer_shape in this check. + return (isinstance(other, TensorArraySpec) and + self._dtype.is_compatible_with(other._dtype) and + self._element_shape.is_compatible_with(other._element_shape) and + self._dynamic_size == other._dynamic_size) + + def _serialize(self): + return (self._element_shape, self._dtype, self._dynamic_size, + self._infer_shape) + + @property + def _component_specs(self): + return [tensor_lib.TensorSpec([], dtypes.variant)] + + def _to_components(self, value): + if not isinstance(value, TensorArray): + raise TypeError("Expected value to be a TensorArray, but got: `{}`".format( + type(value))) + if value.flow is not None and value.flow.dtype == dtypes.variant: + return [value.flow] + else: + # Convert to a TF2-style TensorArray. + # TODO(ebrevdo): Add an "_as_variant" method to TensorArray class, or + # "implementation / as_variant" arg to TensorArray constructor. + with ops.name_scope("convert_tensor_array"): + flow = list_ops.tensor_list_from_tensor( + tensor=value.stack(), element_shape=value.element_shape) + return [flow] + + def _from_components(self, tensor_list): + # This will return a TF2 Graph-style TensorArray because tensor_list[0] is + # a variant object. size == -1 implies unknown size. + ret = TensorArray( + dtype=self._dtype, + flow=tensor_list[0], + dynamic_size=self._dynamic_size, + infer_shape=self._infer_shape) + ret._implementation._element_shape = [self._element_shape] # pylint: disable=protected-access + return ret + + @staticmethod + def from_value(value): + if not isinstance(value, TensorArray): + raise TypeError("Expected value to be a TensorArray, but got: `{}`".format( + type(value))) + + return TensorArraySpec( + dtype=value.dtype, + element_shape=value.element_shape, + dynamic_size=value.dynamic_size, + infer_shape=value._infer_shape) # pylint: disable=protected-access + + def _to_legacy_output_types(self): + return self._dtype + + def _to_legacy_output_shapes(self): + # Sneak the dynamic_size and infer_shape values into the legacy shape. + return (tensor_shape.TensorShape([self._dynamic_size, self._infer_shape + ]).concatenate(self._element_shape)) + + def _to_legacy_output_classes(self): + return TensorArray + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + TensorArraySpec, struct_pb2.TypeSpecProto.TENSOR_ARRAY_SPEC + ) +) + + +# TODO(b/147450234): TensorArray has inconsistent tf.function semantics. +class TensorArrayTraceType(trace.TraceType): + """Represents TraceType of TensorArray.""" + + def __init__(self, value): + self._value = value + + def is_subtype_of(self, other): + return self == other + + def most_specific_common_supertype(self, types): + return self if all(self == other for other in types) else None + + def placeholder_value(self, placeholder_context): + return self._value + + def flatten(self): + return [tensor_lib.TensorSpec([], dtypes.variant)] + + def from_tensors(self, tensors): + return next(tensors) + + def __eq__(self, other): + if not isinstance(other, trace.TraceType): + return NotImplemented + + if not isinstance(other, TensorArrayTraceType): + return False + + # Retrace for each instance since equality between symbolic values is not + # defined. + return self._value is other._value + + def __hash__(self): + return id(self._value) + + def __repr__(self): + return f"{self.__class__.__name__}(value={self._value!r})" + + +# Register the TypeSpec for TensorArray. If TensorArray is updated to be a +# CompositeTensor, then this registration can be deleted. +type_spec.register_type_spec_from_value_converter( + TensorArray, TensorArraySpec.from_value, allow_subclass=True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/unconnected_gradients.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/unconnected_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc166e47c28d45d5bfb31f70a8e1a95d1d5fc57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/unconnected_gradients.py @@ -0,0 +1,39 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utilities for calculating gradients.""" +import enum + +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("UnconnectedGradients") +class UnconnectedGradients(enum.Enum): + """Controls how gradient computation behaves when y does not depend on x. + + The gradient of y with respect to x can be zero in two different ways: there + could be no differentiable path in the graph connecting x to y (and so we can + statically prove that the gradient is zero) or it could be that runtime values + of tensors in a particular execution lead to a gradient of zero (say, if a + relu unit happens to not be activated). To allow you to distinguish between + these two cases you can choose what value gets returned for the gradient when + there is no path in the graph from x to y: + + * `NONE`: Indicates that [None] will be returned if there is no path from x + to y + * `ZERO`: Indicates that a zero tensor will be returned in the shape of x. + """ + NONE = "none" + ZERO = "zero" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_scope.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..ad066f268a621f1daa8b26c8312b181380e7fb7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_scope.py @@ -0,0 +1,2850 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A class to store named variables and a scope operator to manage sharing.""" + +import copy +import enum +import functools +import sys +import threading +import traceback + +from tensorflow.python import tf2 +from tensorflow.python.client import session +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import core +from tensorflow.python.util import deprecation +from tensorflow.python.util import function_utils +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +__all__ = [ + "AUTO_REUSE", "VariableScope", "get_variable_scope", "get_variable", + "get_local_variable", "variable_scope", "variable_op_scope", + "no_regularizer", "VariableSynchronization", "VariableAggregation" +] + +_api_usage_gauge = monitoring.BoolGauge( + "/tensorflow/api/resource_variables", + "Whether variable_scope.enable_resource_variables() is called.") + + +class _PartitionInfo: + """Holds partition info used by initializer functions.""" + + __slots__ = ["_full_shape", "_var_offset"] + + def __init__(self, full_shape, var_offset): + """Constructor. + + Args: + full_shape: Tuple or list of `int` indicating the full combined shape of + the partitioned variables. + var_offset: Tuple or list of `int` specifying offset of this partition + with respect to the full variable for each dimension. + + Raises: + TypeError: If `full_shape` or `var_offset` is not a sequence. + ValueError: If `full_shape` or `var_offset` differ in length. If + `var_offset` exceeds `full_shape` in any dimension. + """ + if not isinstance(full_shape, (list, tuple)): + raise TypeError( + "`full_shape` must be a sequence (like tuple or list) instead of " + + type(full_shape).__name__) + + if not isinstance(var_offset, (list, tuple)): + raise TypeError( + "`var_offset` must be a sequence (like tuple or list) instead of " + + type(var_offset).__name__) + + if len(var_offset) != len(full_shape): + raise ValueError( + "Expected equal length, but `var_offset` is of length {} while " + "full_shape is of length {}.".format( + len(var_offset), len(full_shape))) + + for offset, shape in zip(var_offset, full_shape): + if offset < 0 or offset >= shape: + raise ValueError( + "Expected 0 <= offset < shape but found offset={}, shape={} for " + "var_offset={}, full_shape={}".format(offset, shape, var_offset, + full_shape)) + + self._full_shape = full_shape + self._var_offset = var_offset + + @property + def full_shape(self): + return self._full_shape + + @property + def var_offset(self): + return self._var_offset + + def single_offset(self, shape): + """Returns the offset when the variable is partitioned in at most one dim. + + Args: + shape: Tuple or list of `int` indicating the shape of one specific + variable partition. + + Returns: + `int` representing the offset in the dimension along which the variable is + partitioned. Returns 0 if the variable is not being partitioned. + + Raises: + ValueError: Depending on self.single_slice_dim(). + """ + + single_slice_dim = self.single_slice_dim(shape) + # If this variable is not being partitioned at all, single_slice_dim() could + # return None. + if single_slice_dim is None: + return 0 + return self.var_offset[single_slice_dim] + + def single_slice_dim(self, shape): + """Returns the slice dim when the variable is partitioned only in one dim. + + Args: + shape: Tuple or list of `int` indicating the shape of one specific + variable partition. + + Returns: + `int` representing the dimension that the variable is partitioned in, or + `None` if the variable doesn't seem to be partitioned at all. + + Raises: + TypeError: If `shape` is not a sequence. + ValueError: If `shape` is not the same length as `self.full_shape`. If + the variable is partitioned in more than one dimension. + """ + if not isinstance(shape, (tuple, list)): + raise TypeError( + "`shape` must be a sequence (like tuple or list) instead of " + + type(shape).__name__) + + if len(shape) != len(self.full_shape): + raise ValueError( + "Expected equal length, but received shape={} of length {} while " + "self.full_shape={} is of length {}.".format(shape, len(shape), + self.full_shape, + len(self.full_shape))) + + for i in range(len(shape)): + if self.var_offset[i] + shape[i] > self.full_shape[i]: + raise ValueError( + "With self.var_offset={}, a partition of shape={} would exceed " + "self.full_shape={} in dimension {}.".format( + self.var_offset, shape, self.full_shape, i)) + + slice_dim = None + for i in range(len(shape)): + if shape[i] == self.full_shape[i]: + continue + if slice_dim is not None: + raise ValueError( + "Cannot use single_slice_dim() with shape={} and " + "self.full_shape={} since slice dim could be either dimension {} " + "or {}.".format(shape, self.full_shape, i, slice_dim)) + slice_dim = i + + return slice_dim + + +class _ReuseMode(enum.Enum): + """Mode for variable access within a variable scope.""" + + # Indicates that variables are to be fetched if they already exist or + # otherwise created. + AUTO_REUSE = 1 + + # TODO(alive): For TensorFlow 2.0, Deprecate True/False/None API in favor of + # enum values. + # REUSE_FALSE = 2 + # REUSE_TRUE = 3 + + +# TODO(apassos) remove these forwarding symbols. +VariableSynchronization = variables.VariableSynchronization # pylint: disable=invalid-name +VariableAggregation = variables.VariableAggregation # pylint: disable=invalid-name + +AUTO_REUSE = _ReuseMode.AUTO_REUSE +tf_export(v1=["AUTO_REUSE"]).export_constant(__name__, "AUTO_REUSE") +AUTO_REUSE.__doc__ = """ +@compatibility(TF2) +`tf.compat.v1.AUTO_REUSE` is a legacy API that is a no-op when TF2 behaviors +are enabled. + +If you rely on `get_variable` and auto-reuse, see the +[model mapping guide](https://www.tensorflow.org/guide/migrate/model_mapping) +for more info on how to migrate your code. + +Note: when you use the `tf.compat.v1.keras.utils.track_tf1_style_variables` +API as described in the above guide, `get_variable` will always behave as if +`v1.AUTO_REUSE` is set. Without the decorator, reuse will be ignored and new +variables will always be created, regardless of if they have already been +created. +@end_compatibility + +When passed in as the value for the `reuse` flag, `AUTO_REUSE` indicates that +get_variable() should create the requested variable if it doesn't exist or, if +it does exist, simply return it. +""" + +_DEFAULT_USE_RESOURCE = tf2.enabled() + + +@tf_export(v1=["enable_resource_variables"]) +def enable_resource_variables(): + """Creates resource variables by default. + + Resource variables are improved versions of TensorFlow variables with a + well-defined memory model. Accessing a resource variable reads its value, and + all ops which access a specific read value of the variable are guaranteed to + see the same value for that tensor. Writes which happen after a read (by + having a control or data dependency on the read) are guaranteed not to affect + the value of the read tensor, and similarly writes which happen before a read + are guaranteed to affect the value. No guarantees are made about unordered + read/write pairs. + + Calling tf.enable_resource_variables() lets you opt-in to this TensorFlow 2.0 + feature. + """ + global _DEFAULT_USE_RESOURCE + _DEFAULT_USE_RESOURCE = True + logging.vlog(1, "Enabling resource variables") + _api_usage_gauge.get_cell().set(True) + + +@tf_export(v1=["resource_variables_enabled"]) +def resource_variables_enabled(): + """Returns `True` if resource variables are enabled. + + Resource variables are improved versions of TensorFlow variables with a + well-defined memory model. Accessing a resource variable reads its value, and + all ops which access a specific read value of the variable are guaranteed to + see the same value for that tensor. Writes which happen after a read (by + having a control or data dependency on the read) are guaranteed not to affect + the value of the read tensor, and similarly writes which happen before a read + are guaranteed to affect the value. No guarantees are made about unordered + read/write pairs. + + Calling tf.enable_resource_variables() lets you opt-in to this TensorFlow 2.0 + feature. + """ + global _DEFAULT_USE_RESOURCE + return _DEFAULT_USE_RESOURCE + + +@deprecation.deprecated( + None, "non-resource variables are not supported in the long term") +@tf_export(v1=["disable_resource_variables"]) +def disable_resource_variables(): + """Opts out of resource variables. + + If your code needs tf.disable_resource_variables() to be called to work + properly please file a bug. + """ + global _DEFAULT_USE_RESOURCE + _DEFAULT_USE_RESOURCE = False + logging.vlog(1, "Disabling resource variables") + _api_usage_gauge.get_cell().set(False) + + +def _needs_no_arguments(python_callable): + """Returns true if the callable needs no arguments to call.""" + # TODO(bfontain): Switch to inspect.signature when we are python 3 only. + # signature = inspect.signature(python_callable) + # return not [1 for param in signature.parameters.values() + # if param.default == param.empty] + num_arguments = len(tf_inspect.getargspec(python_callable).args) + if not tf_inspect.isfunction(python_callable) and not isinstance( + python_callable, functools.partial): + # getargspec includes self for function objects (which aren't + # functools.partial). This has no default so we need to remove it. + # It is not even an argument so its odd that getargspec returns this. + # Note that this is fixed with inspect.signature in Python 3. + num_arguments -= 1 + return num_arguments == len( + tf_inspect.getargspec(python_callable).defaults or []) + + +class _VariableStore: + """Variable store that carries a number of named Variables. + + New variable names and new variables can be created; all stored + variables are initialized with the initializer passed to __init__. + + Attributes: + vars: a dictionary with string names (same as passed in GetVar) as keys and + the corresponding TensorFlow Variables as values. + """ + + __slots__ = ["_vars", "_partitioned_vars", "_store_eager_variables"] + + def __init__(self): + """Create a variable store.""" + self._vars = {} # A dictionary of the stored TensorFlow variables. + self._partitioned_vars = {} # A dict of the stored PartitionedVariables. + self._store_eager_variables = False + + def get_variable(self, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + custom_getter=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Gets an existing variable with these parameters or create a new one. + + If a variable with the given name is already stored, we return the stored + variable. Otherwise, we create a new one. + + Set `reuse` to `True` when you only want to reuse existing Variables. + Set `reuse` to `False` when you only want to create new Variables. + Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want + variables to be created if they don't exist or returned if they do. + + If initializer is `None` (the default), the default initializer passed in + the constructor is used. If that one is `None` too, we use a new + `glorot_uniform_initializer`. If initializer is a Tensor, we use + it as a value and derive the shape from the initializer. + + If a partitioner is provided, a `PartitionedVariable` is returned. + Accessing this object as a `Tensor` returns the shards concatenated along + the partition axis. + + Some useful partitioners are available. See, e.g., + `variable_axis_size_partitioner` and `min_max_variable_partitioner`. + + Args: + name: The name of the new or existing variable. + shape: Shape of the new or existing variable. + dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). + initializer: Initializer for the variable. + regularizer: A (Tensor -> Tensor or None) function; the result of applying + it on a newly created variable will be added to the collection + GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. + reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of + variables. When eager execution is enabled this argument is always + forced to be False. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). `trainable` + defaults to `True`, unless `synchronization` is set to `ON_READ`, in + which case it defaults to `False`. + collections: List of graph collections keys to add the `Variable` to. + Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the `Variable` reside, to + deduplicate copying through `Switch` and other conditional statements. + partitioner: Optional callable that accepts a fully defined `TensorShape` + and dtype of the `Variable` to be created, and returns a list of + partitions for each axis (currently only one axis can be partitioned). + validate_shape: If False, allows the variable to be initialized with a + value of unknown shape. If True, the default, the shape of initial_value + must be known. + use_resource: If False, creates a regular Variable. If True, creates + instead an experimental ResourceVariable which has well-defined + semantics. Defaults to False (will later change to True). When eager + execution is enabled this argument is always forced to be true. + custom_getter: Callable that takes as a first argument the true getter, + and allows overwriting the internal get_variable method. The signature + of `custom_getter` should match that of this method, + but the most future-proof version will allow for changes: `def + custom_getter(getter, *args, **kwargs)`. Direct access to + all `get_variable` parameters is also allowed: `def + custom_getter(getter, name, *args, **kwargs)`. A simple identity + custom getter that simply creates variables with modified names is: + ```python + def custom_getter(getter, name, *args, **kwargs): return getter(name + + '_suffix', *args, **kwargs) ``` + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + Returns: + The created or existing `Variable` (or `PartitionedVariable`, if a + partitioner was used). + + Raises: + ValueError: when creating a new variable and shape is not declared, + when reusing a variable and specifying a conflicting shape, + or when violating reuse during variable creation. + RuntimeError: when eager execution is enabled and not called from an + EagerVariableStore. + """ + if custom_getter is not None and not callable(custom_getter): + raise ValueError("Passed a custom_getter which is not callable: %s" % + custom_getter) + + with ops.init_scope(): + if context.executing_eagerly(): + # Variable creation and initialization takes place in `init_scope`s; + # as such, if an `init_scope` lifts us into the eager context, then we + # need to use `ResourceVariable`s. + use_resource = True + + # Note that it's fine to reuse eager variables whose initialization was + # lifted from a function-building graph into the eager context (that's why + # the following clause is not wrapped in an `init_scope`); lifted variables + # are tracked by the graph's `VariableStore`. + if context.executing_eagerly(): + if not self._store_eager_variables and reuse: + raise RuntimeError( + "When eager execution is enabled variable reuse is only supported" + " when an EagerVariableStore is active. See the documentation on" + " EagerVariableStore for example usage.") + if self._store_eager_variables: + reuse = AUTO_REUSE + + # If a *_ref type is passed in an error would be triggered further down the + # stack. We prevent this using base_dtype to get a non-ref version of the + # type, before doing anything else. When _ref types are removed in favor of + # resources, this line can be removed. + try: + dtype = dtype.base_dtype + except AttributeError: + # .base_dtype not existing means that we will try and use the raw dtype + # which was passed in - this might be a NumPy type which is valid. + pass + + # This is the main logic of get_variable. However, custom_getter + # may override this logic. So we save it as a callable and pass + # it to custom_getter. + # Note: the parameters of _true_getter, and their documentation, match + # *exactly* item-for-item with the docstring of this method. + def _true_getter( # pylint: disable=missing-docstring + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + is_scalar = ( + shape is not None and isinstance(shape, collections_abc.Sequence) and + not shape) + # Partitioned variable case + if partitioner is not None and not is_scalar: + if not callable(partitioner): + raise ValueError("Partitioner must be callable, but received: %s" % + partitioner) + with ops.name_scope(None): + return self._get_partitioned_variable( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + # Special case for partitioned variable to allow reuse without having to + # specify partitioner. + if (reuse is True and partitioner is None + and name in self._partitioned_vars): + return self._get_partitioned_variable( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=None, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + # Single variable case + if "%s/part_0" % name in self._vars: + raise ValueError( + "No partitioner was provided, but a partitioned version of the " + "variable was found: %s/part_0. Perhaps a variable of the same " + "name was already created with partitioning?" % name) + + return self._get_single_variable( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + synchronization, aggregation, trainable, name)) + + if custom_getter is not None: + # Handle backwards compatibility with getter arguments that were added + # to the API after users started writing custom getters. + custom_getter_kwargs = { + "getter": _true_getter, + "name": name, + "shape": shape, + "dtype": dtype, + "initializer": initializer, + "regularizer": regularizer, + "reuse": reuse, + "trainable": trainable, + "collections": collections, + "caching_device": caching_device, + "partitioner": partitioner, + "validate_shape": validate_shape, + "use_resource": use_resource, + "synchronization": synchronization, + "aggregation": aggregation, + } + # `fn_args` and `has_kwargs` can handle functions, `functools.partial`, + # `lambda`. + if ("constraint" in function_utils.fn_args(custom_getter) or + function_utils.has_kwargs(custom_getter)): + custom_getter_kwargs["constraint"] = constraint + return custom_getter(**custom_getter_kwargs) + else: + return _true_getter( + name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + def _get_partitioned_variable(self, + name, + partitioner, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + validate_shape=True, + use_resource=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Gets or creates a sharded variable list with these parameters. + + The `partitioner` must be a callable that accepts a fully defined + `TensorShape` and returns a sequence of integers (the `partitions`). + These integers describe how to partition the given sharded `Variable` + along the given dimension. That is, `partitions[1] = 3` means split + the `Variable` into 3 shards along dimension 1. Currently, sharding along + only one axis is supported. + + If the list of variables with the given name (prefix) is already stored, + we return the stored variables. Otherwise, we create a new one. + + Set `reuse` to `True` when you only want to reuse existing Variables. + Set `reuse` to `False` when you only want to create new Variables. + Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want + variables to be created if they don't exist or returned if they do. + + If initializer is `None` (the default), the default initializer passed in + the constructor is used. If that one is `None` too, we use a new + `glorot_uniform_initializer`. If initializer is a Tensor, we use + it as a value and derive the shape from the initializer. + + If the initializer is a callable, then it will be called for each + shard. Otherwise the initializer should match the shape of the entire + sharded Variable, and it will be sliced accordingly for each shard. + + Some useful partitioners are available. See, e.g., + `variable_axis_size_partitioner` and `min_max_variable_partitioner`. + + Args: + name: the name of the new or existing sharded variable. + partitioner: Optional callable that accepts a fully defined `TensorShape` + and `dtype` of the Variable to be created, and returns a list of + partitions for each axis (currently only one axis can be partitioned). + shape: shape of the new or existing sharded variable. + dtype: type of the new or existing sharded variable (defaults to + `DT_FLOAT`). + initializer: initializer for the sharded variable. + regularizer: a (Tensor -> Tensor or None) function; the result of applying + it on a newly created variable will be added to the collection + GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. + reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of + variables. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + collections: List of graph collections keys to add the Variable to. + Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + validate_shape: If False, allows the variable to be initialized with a + value of unknown shape. If True, the default, the shape of initial_value + must be known. + use_resource: If False, creates a regular Variable. If True, creates an + experimental ResourceVariable which has well-defined semantics. Defaults + to False (will later change to True). + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + Returns: + A `PartitionedVariable` object. + + Raises: + ValueError: when creating a new variable and shape is not declared, + when reusing a variable and specifying a conflicting shape, + when violating reuse during variable creation, or if an existing + sharded variable exists for the given name but with different sharding. + """ + initializing_from_value = initializer is not None and isinstance( + initializer, tensor.Tensor) + if name in self._vars: + raise ValueError( + "A partitioner was provided, but an unpartitioned version of the " + "variable was found: %s. Perhaps a variable of the same name was " + "already created without partitioning?" % name) + + shape = tensor_shape.as_shape(shape) + if initializing_from_value: + shape = shape.merge_with(initializer.get_shape()) + + partitions = None + if not reuse or partitioner: + partitions = _call_partitioner(partitioner, shape, dtype) + + if name in self._partitioned_vars: + if reuse is False: + raise ValueError( + "Partitioned variable with name %s already exists. Did you mean to " + "set reuse=True or reuse=tf.AUTO_REUSE in VarScope?" % name) + + existing_var = self._partitioned_vars[name] + if not shape.is_compatible_with(existing_var.get_shape()): + raise ValueError( + "Trying to reuse partitioned variable %s, but specified shape %s " + "and found shape %s." % (name, shape, existing_var.get_shape())) + if not dtype.is_compatible_with(existing_var.dtype): + raise ValueError( + "Trying to reuse partitioned variable %s, but specified dtype %s " + "and found dtype %s." % (name, dtype.name, existing_var.dtype.name)) + + # pylint: disable=protected-access + if (partitions is not None and + existing_var._get_partitions() != partitions): + raise ValueError( + "Trying to reuse partitioned variable %s, but specified partitions " + "%s and found partitions %s." % + (name, partitions, existing_var._get_partitions())) + # pylint: enable=protected-access + + return existing_var + + if reuse is True: + raise ValueError("PartitionedVariable %s does not exist, or was not " + "created with tf.get_variable(). Did you mean to set " + "reuse=False or reuse=tf.AUTO_REUSE in VarScope?" % name) + + slice_dim, num_slices = _get_slice_dim_and_num_slices(partitions) + + if "%s/part_0" % name in self._vars: + if "%s/part_%d" % (name, num_slices - 1) not in self._vars: + raise ValueError( + "Partitioner returned a different partitioning than what was " + "already found. Partitioner returned %d shards, and shard " + "%s/part_0 was found, but %s/part_%d was not." % + (num_slices, name, name, num_slices - 1)) + if "%s/part_%d" % (name, num_slices) in self._vars: + raise ValueError( + "Partitioner returned a different partitioning than what was " + "already found. Partitioner returned %d shards, and shard " + "%s/part_0 was found, but so was the extra shard %s/part_%d." % + (num_slices, name, name, num_slices)) + + vs = [] + for i, (var_offset, var_shape) in enumerate( + _iter_slices(shape.as_list(), num_slices, slice_dim)): + partition_info = _PartitionInfo( + full_shape=shape.as_list(), var_offset=var_offset) + var_full_name = "%s/part_%d" % (name, i) + with ops.name_scope( + var_full_name + "/PartitionedInitializer", skip_on_eager=False): + # Create the tensor to initialize the variable with default value. + if initializer is None: + init, initializing_from_value = self._get_default_initializer( + name=name, shape=shape, dtype=dtype) + if initializing_from_value: + init_shape = None + else: + init_shape = var_shape + elif callable(initializer): + init = initializer + init_shape = var_shape + elif isinstance(initializer, tensor.Tensor): + init = array_ops.slice(initializer, var_offset, var_shape) + # Use the dtype of the given tensor. + dtype = init.dtype.base_dtype + init_shape = None + else: + init = ops.convert_to_tensor(initializer, dtype=dtype) + init = array_ops.slice(init, var_offset, var_shape) + init_shape = None + + with ops.name_scope(None): + var = self._get_single_variable( + name=var_full_name, + shape=init_shape, + dtype=dtype, + initializer=init, + partition_info=partition_info, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + ) + + # pylint: disable=protected-access + var._set_save_slice_info( + variables.Variable.SaveSliceInfo(name, shape.as_list(), var_offset, + var_shape)) + vs.append(var) + # pylint: enable=protected-access + + partitioned_var = variables.PartitionedVariable( + name=name, + shape=shape, + dtype=dtype, + variable_list=vs, + partitions=partitions) + if not context.executing_eagerly() or self._store_eager_variables: + self._partitioned_vars[name] = partitioned_var + return partitioned_var + + def _get_single_variable(self, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + regularizer=None, + partition_info=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + validate_shape=True, + use_resource=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Get or create a single Variable (e.g. + + a shard or entire variable). + + See the documentation of get_variable above (ignore partitioning components) + for details. + + Args: + name: see get_variable. + shape: see get_variable. + dtype: see get_variable. + initializer: see get_variable. + regularizer: see get_variable. + partition_info: _PartitionInfo object. + reuse: see get_variable. + trainable: see get_variable. + collections: see get_variable. + caching_device: see get_variable. + validate_shape: see get_variable. + use_resource: see get_variable. + constraint: see get_variable. + synchronization: see get_variable. + aggregation: see get_variable. + + Returns: + A Variable. See documentation of get_variable above. + + Raises: + ValueError: See documentation of get_variable above. + """ + # Set to true if initializer is a constant. + initializing_from_value = False + if initializer is not None and not callable(initializer): + initializing_from_value = True + if shape is not None and initializing_from_value: + raise ValueError("If initializer is a constant, do not specify shape.") + + dtype = dtypes.as_dtype(dtype) + if shape is not None: + shape = tensor_shape.as_shape(shape) + + if name in self._vars: + # Here we handle the case when returning an existing variable. + if reuse is False: + var = self._vars[name] + err_msg = ("Variable %s already exists, disallowed." + " Did you mean to set reuse=True or " + "reuse=tf.AUTO_REUSE in VarScope?" % name) + # ResourceVariables don't have an op associated with so no traceback + if isinstance(var, resource_variable_ops.ResourceVariable): + raise ValueError(err_msg) + tb = var.op.traceback[::-1] + # Throw away internal tf entries and only take a few lines. In some + # cases the traceback can be longer (e.g. if someone uses factory + # functions to create variables) so we take more than needed in the + # default case. + tb = [x for x in tb if "tensorflow/python" not in x[0]][:5] + raise ValueError("%s Originally defined at:\n\n%s" % + (err_msg, "".join(traceback.format_list(tb)))) + found_var = self._vars[name] + if shape is not None and not shape.is_compatible_with( + found_var.get_shape() + ): + raise ValueError("Trying to share variable %s, but specified shape %s" + " and found shape %s." % + (name, shape, found_var.get_shape())) + if not dtype.is_compatible_with(found_var.dtype): + dtype_str = dtype.name + found_type_str = found_var.dtype.name + raise ValueError("Trying to share variable %s, but specified dtype %s" + " and found dtype %s." % + (name, dtype_str, found_type_str)) + return found_var + + # The code below handles only the case of creating a new variable. + if reuse is True: + raise ValueError("Variable %s does not exist, or was not created with " + "tf.get_variable(). Did you mean to set " + "reuse=tf.AUTO_REUSE in VarScope?" % name) + + # Create the tensor to initialize the variable with default value. + if initializer is None: + if shape is None: + raise ValueError( + f"Variable {name} did not get an initializer, so its `shape`" + " argument must be specified." + ) + initializer, initializing_from_value = self._get_default_initializer( + name=name, shape=shape, dtype=dtype) + # Enter an init scope when creating the initializer. + with ops.init_scope(): + if initializing_from_value: + init_val = initializer + variable_dtype = None + else: + # Instantiate initializer if provided initializer is a type object. + if tf_inspect.isclass(initializer): + initializer = initializer() + if shape is not None and shape.is_fully_defined(): + if "partition_info" in tf_inspect.getargspec(initializer).args: + init_val = functools.partial(initializer, + shape.as_list(), + dtype=dtype, + partition_info=partition_info) + else: + init_val = functools.partial(initializer, + shape.as_list(), dtype=dtype) + variable_dtype = dtype.base_dtype + elif _needs_no_arguments(initializer): + init_val = initializer + variable_dtype = None + else: + raise ValueError("The initializer passed is not valid. It should " + "be a callable with no arguments and the " + "shape should not be provided or an instance of " + "`tf.keras.initializers.*' and `shape` should be " + "fully defined.") + + # Create the variable. + if use_resource is None: + # Set the default value if unspecified. + use_resource = _DEFAULT_USE_RESOURCE + v = _variable_v1( + initial_value=init_val, + name=name, + trainable=trainable, + collections=collections, + caching_device=caching_device, + dtype=variable_dtype, + validate_shape=validate_shape, + constraint=constraint, + use_resource=use_resource, + synchronization=synchronization, + aggregation=aggregation, + shape=shape, + ) + if context.executing_eagerly() and self._store_eager_variables: + if collections: + ops.add_to_collections(collections, v) + else: + ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, v) + if trainable: + ops.add_to_collection(ops.GraphKeys.TRAINABLE_VARIABLES, v) + + if not context.executing_eagerly() or self._store_eager_variables: + # In eager mode we do not want to keep default references to Variable + # objects as this will prevent their memory from being released. + self._vars[name] = v + logging.vlog(1, "Created variable %s with shape %s and init %s", v.name, + format(shape), initializer) + + # Run the regularizer if requested and save the resulting loss. + if regularizer: + def make_regularizer_op(): + with ops.colocate_with(v): + with ops.name_scope(name + "/Regularizer/"): + return regularizer(v) + + if regularizer(v) is not None: + lazy_eval_tensor = _LazyEvalTensor(make_regularizer_op) + ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, + lazy_eval_tensor) + + return v + + # Initialize variable when no initializer provided + def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32): + """Provide a default initializer and a corresponding value. + + Args: + name: see get_variable. + shape: see get_variable. + dtype: see get_variable. + + Returns: + initializer and initializing_from_value. See get_variable above. + + Raises: + ValueError: When giving unsupported dtype. + """ + del shape + # If dtype is DT_FLOAT, provide a uniform unit scaling initializer + if dtype.is_floating: + initializer = init_ops.glorot_uniform_initializer() + initializing_from_value = False + # If dtype is DT_INT/DT_UINT, provide a default value `zero` + # If dtype is DT_BOOL, provide a default value `FALSE` + elif (dtype.is_integer or dtype.is_unsigned or dtype.is_bool or + dtype == dtypes.string): + initializer = init_ops.zeros_initializer() + initializing_from_value = False + # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? + else: + raise ValueError("An initializer for variable %s of %s is required" % + (name, dtype.base_dtype)) + + return initializer, initializing_from_value + + +class _LazyEvalTensor(core.Tensor): + """A Tensor-like object that only evaluates its thunk when used.""" + + def __init__(self, thunk): + """Initializes a _LazyEvalTensor object. + + Args: + thunk: A callable. A thunk which computes the value of the tensor. + """ + self._thunk = thunk + self._master_tensor = thunk() + + def _as_tensor(self, dtype=None, name=None, as_ref=False): + del name + assert not as_ref + assert dtype in [None, self.dtype] + + return self._thunk() + + +def _make_master_property(name): + @property + def prop(self): + return getattr(self._master_tensor, name) # pylint: disable=protected-access + return prop + +_master_property_list = ("device", "dtype", "graph", "name", "op", "shape", + "value_index") +for _name in _master_property_list: + setattr(_LazyEvalTensor, _name, _make_master_property(_name)) + + +def _make_master_method(name): + def method(self, *args, **kwargs): + return getattr(self._master_tensor, name)(*args, **kwargs) # pylint: disable=protected-access + return method + +_master_method_list = ("get_shape", "__str__", "shape_as_list") +for _name in _master_method_list: + setattr(_LazyEvalTensor, _name, _make_master_method(_name)) + + +def _make_op_method(name): + def method(self, *args, **kwargs): + return getattr(self._as_tensor(), name)(*args, **kwargs) # pylint: disable=protected-access + return method + +_op_list = ("__abs__", "__add__", "__and__", "__bool__", "__div__", "__eq__", + "__floordiv__", "__ge__", "__getitem__", "__gt__", "__invert__", + "__iter__", "__le__", "__len__", "__lt__", "__matmul__", "__mod__", + "__mul__", "__ne__", "__neg__", "__nonzero__", "__or__", "__pow__", + "__radd__", "__rand__", "__rdiv__", "__rfloordiv__", "__rmatmul__", + "__rmod__", "__rmul__", "__ror__", "__rpow__", "__rsub__", + "__rtruediv__", "__rxor__", "__sub__", "__truediv__", "__xor__", + "eval", "numpy") +for _name in _op_list: + setattr(_LazyEvalTensor, _name, _make_op_method(_name)) + + +tensor_conversion_registry.register_tensor_conversion_function( + _LazyEvalTensor, + lambda val, dtype, name, as_ref: val._as_tensor(dtype, name, as_ref) # pylint: disable=protected-access + ) + +session.register_session_run_conversion_functions( + _LazyEvalTensor, + lambda fetch: ([fetch._master_tensor], lambda fetched_vals: fetched_vals[0]) # pylint: disable=protected-access + ) + + +# To stop regularization, use this regularizer +@tf_export(v1=["no_regularizer"]) +def no_regularizer(_): + """Use this function to prevent regularization of variables.""" + return None + + +# TODO(alive): support caching devices and partitioned variables in Eager mode. +@tf_export(v1=["VariableScope"]) +class VariableScope: + """Variable scope object to carry defaults to provide to `get_variable`. + + Many of the arguments we need for `get_variable` in a variable store are most + easily handled with a context. This object is used for the defaults. + + Attributes: + name: name of the current scope, used as prefix in get_variable. + initializer: default initializer passed to get_variable. + regularizer: default regularizer passed to get_variable. + reuse: Boolean, None, or tf.compat.v1.AUTO_REUSE, setting the reuse in + get_variable. When eager execution is enabled this argument is always + forced to be False. + caching_device: string, callable, or None: the caching device passed to + get_variable. + partitioner: callable or `None`: the partitioner passed to `get_variable`. + custom_getter: default custom getter passed to get_variable. + name_scope: The name passed to `tf.name_scope`. + dtype: default type passed to get_variable (defaults to DT_FLOAT). + use_resource: if False, create a normal Variable; if True create an + experimental ResourceVariable with well-defined semantics. Defaults to + False (will later change to True). When eager execution is enabled this + argument is always forced to be True. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + """ + + def __init__(self, + reuse, + name="", + initializer=None, + regularizer=None, + caching_device=None, + partitioner=None, + custom_getter=None, + name_scope="", + dtype=dtypes.float32, + use_resource=None, + constraint=None): + """Creates a new VariableScope with the given properties.""" + self._name = name + self._initializer = initializer + self._regularizer = regularizer + self._reuse = reuse + self._caching_device = caching_device + self._partitioner = partitioner + self._custom_getter = custom_getter + self._name_scope = name_scope + self._dtype = dtype + self._use_resource = use_resource + self._constraint = constraint + if context.executing_eagerly(): + if self._caching_device is not None: + raise NotImplementedError("Caching devices is not yet supported " + "when eager execution is enabled.") + self._reuse = AUTO_REUSE + self._use_resource = True + + @property + def name(self): + return self._name + + @property + def original_name_scope(self): + return self._name_scope + + @property + def reuse(self): + return self._reuse + + @property + def initializer(self): + return self._initializer + + @property + def dtype(self): + return self._dtype + + @property + def use_resource(self): + return self._use_resource + + @property + def regularizer(self): + return self._regularizer + + @property + def caching_device(self): + return self._caching_device + + @property + def partitioner(self): + return self._partitioner + + @property + def custom_getter(self): + return self._custom_getter + + @property + def constraint(self): + return self._constraint + + def reuse_variables(self): + """Reuse variables in this scope.""" + self._reuse = True + + def set_initializer(self, initializer): + """Set initializer for this scope.""" + self._initializer = initializer + + def set_dtype(self, dtype): + """Set data type for this scope.""" + self._dtype = dtype + + def set_use_resource(self, use_resource): + """Sets whether to use ResourceVariables for this scope.""" + if context.executing_eagerly() and not use_resource: + raise ValueError("When eager execution is enabled, " + "use_resource cannot be set to false.") + self._use_resource = use_resource + + def set_regularizer(self, regularizer): + """Set regularizer for this scope.""" + self._regularizer = regularizer + + def set_caching_device(self, caching_device): + """Set caching_device for this scope.""" + if context.executing_eagerly(): + raise NotImplementedError("Caching devices are not yet supported " + "when eager execution is enabled.") + self._caching_device = caching_device + + def set_partitioner(self, partitioner): + """Set partitioner for this scope.""" + self._partitioner = partitioner + + def set_custom_getter(self, custom_getter): + """Set custom getter for this scope.""" + self._custom_getter = custom_getter + + def get_collection(self, name): + """Get this scope's variables.""" + scope = self._name + "/" if self._name else "" + return ops.get_collection(name, scope) + + def trainable_variables(self): + """Get this scope's trainable variables.""" + return self.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) + + def global_variables(self): + """Get this scope's global variables.""" + return self.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) + + def local_variables(self): + """Get this scope's local variables.""" + return self.get_collection(ops.GraphKeys.LOCAL_VARIABLES) + + def get_variable(self, + var_store, + name, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + reuse=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + custom_getter=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Gets an existing variable with this name or create a new one.""" + if regularizer is None: + regularizer = self._regularizer + if caching_device is None: + caching_device = self._caching_device + if partitioner is None: + partitioner = self._partitioner + if custom_getter is None: + custom_getter = self._custom_getter + if context.executing_eagerly(): + reuse = False + use_resource = True + else: + if reuse is None: + reuse = self._reuse + if use_resource is None: + use_resource = self._use_resource + + full_name = self.name + "/" + name if self.name else name + # Variable names only depend on variable_scope (full_name here), + # not name_scope, so we reset it below for the time of variable creation. + with ops.name_scope(None, skip_on_eager=False): + # Check that `initializer` dtype and `dtype` are consistent before + # replacing them with defaults. + if (dtype is not None and initializer is not None and + not callable(initializer)): + init_dtype = ops.convert_to_tensor(initializer).dtype.base_dtype + if init_dtype != dtype: + raise ValueError("Initializer type '%s' and explicit dtype '%s' " + "don't match." % (init_dtype, dtype)) + if initializer is None: + initializer = self._initializer + if constraint is None: + constraint = self._constraint + if dtype is None: + dtype = self._dtype + return var_store.get_variable( + full_name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + custom_getter=custom_getter, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + def _get_partitioned_variable(self, + var_store, + name, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Gets an existing variable with this name or create a new one.""" + if initializer is None: + initializer = self._initializer + if regularizer is None: + regularizer = self._regularizer + if constraint is None: + constraint = self._constraint + if caching_device is None: + caching_device = self._caching_device + if partitioner is None: + partitioner = self._partitioner + if dtype is None: + dtype = self._dtype + if use_resource is None: + use_resource = self._use_resource + + if self._custom_getter is not None: + raise ValueError( + "Private access to _get_partitioned_variable is not allowed when " + "a custom getter is set. Current custom getter: %s. " + "It is likely that you're using create_partitioned_variables. " + "If so, consider instead using get_variable with a non-empty " + "partitioner parameter instead." % self._custom_getter) + + if partitioner is None: + raise ValueError("No partitioner was specified") + + # This allows the variable scope name to be used as the variable name if + # this function is invoked with an empty name arg, for backward + # compatibility with create_partitioned_variables(). + full_name_list = [] + if self.name: + full_name_list.append(self.name) + if name: + full_name_list.append(name) + full_name = "/".join(full_name_list) + + # Variable names only depend on variable_scope (full_name here), + # not name_scope, so we reset it below for the time of variable creation. + with ops.name_scope(None, skip_on_eager=False): + # pylint: disable=protected-access + return var_store._get_partitioned_variable( + full_name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + reuse=self.reuse, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + # pylint: enable=protected-access + + +_VARSTORE_KEY = ("__variable_store",) +_VARSCOPESTORE_KEY = ("__varscope",) + + +class _VariableScopeStore(threading.local): + """A thread local store for the current variable scope and scope counts.""" + + def __init__(self): + super(_VariableScopeStore, self).__init__() + self.current_scope = VariableScope(False) + self.variable_scopes_count = {} + + def open_variable_scope(self, scope_name): + if scope_name in self.variable_scopes_count: + self.variable_scopes_count[scope_name] += 1 + else: + self.variable_scopes_count[scope_name] = 1 + + def close_variable_subscopes(self, scope_name): + if scope_name is None: + for k in self.variable_scopes_count: + self.variable_scopes_count[k] = 0 + else: + startswith_check = scope_name + "/" + startswith_len = len(startswith_check) + for k in self.variable_scopes_count: + if k[:startswith_len] == startswith_check: + self.variable_scopes_count[k] = 0 + + def variable_scope_count(self, scope_name): + return self.variable_scopes_count.get(scope_name, 0) + + +def get_variable_scope_store(): + """Returns the variable scope store for current thread.""" + scope_store = ops.get_collection(_VARSCOPESTORE_KEY) + + if not scope_store: + scope_store = _VariableScopeStore() + ops.add_to_collection(_VARSCOPESTORE_KEY, scope_store) + else: + scope_store = scope_store[0] + + return scope_store + + +@tf_export(v1=["get_variable_scope"]) +def get_variable_scope(): + """Returns the current variable scope. + + @compatibility(TF2) + Although it is a legacy `compat.v1` api, + `tf.compat.v1.get_variable` is compatible with eager + execution and `tf.function` + + However, to maintain variable-scope based variable reuse + you will need to combine it with + `tf.compat.v1.keras.utils.track_tf1_style_variables`. (Though + it will behave as if reuse is always set to `tf.compat.v1.AUTO_REUSE`.) + + See the + [migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) + for more info. + + The TF2 equivalent, if you are just trying to track + variable name prefixes and not control `get_variable`-based variable reuse, + would be to use `tf.name_scope` and capture the output of opening the + scope (which represents the current name prefix). + + For example: + ```python + x = tf.name_scope('foo') as current_scope: + ... + ``` + @end_compatibility + """ + return get_variable_scope_store().current_scope + + +def _get_default_variable_store(): + store = ops.get_collection(_VARSTORE_KEY) + if store: + return store[0] + store = _VariableStore() + ops.add_to_collection(_VARSTORE_KEY, store) + return store + + +@tf_contextlib.contextmanager +def with_variable_store(store): + store_collection = ops.get_collection_ref(_VARSTORE_KEY) + old = list(store_collection) + store_collection[:] = [store] + try: + yield + finally: + store_collection[:] = old + + +class EagerVariableStore: + """Wrapper allowing functional layers to be used with eager execution. + + When eager execution is enabled Variables get deleted when they go out of + scope, and are not stored in global collections by default. A lot of code + (mostly the functional layers in tf.layers) assumes that variables are kept in + a global list. + + EagerVariableStore can be used in conjunction with this code to make it + eager-friendly. For example, to create a dense layer, use: + + ``` + container = tfe.EagerVariableStore() + for input in dataset_iterator: + with container.as_default(): + x = tf.compat.v1.layers.dense(input, name="l1") + print(container.variables) # Should print the variables used in the layer. + ``` + """ + + def __init__(self, store=None): + if store is not None: + if not store._store_eager_variables: # pylint: disable=protected-access + raise ValueError("Cannot construct EagerVariableStore from a " + "VariableStore object that does not hold eager " + "variables.") + self._store = store + else: + self._store = _VariableStore() + self._store._store_eager_variables = True # pylint: disable=protected-access + + def as_default(self): + return with_variable_store(self._store) + + def variables(self): + return sorted(self._store._vars.values(), key=lambda x: x.name) # pylint: disable=protected-access + + def trainable_variables(self): + # pylint: disable=protected-access + return sorted([x for x in self._store._vars.values() if x.trainable], + key=lambda x: x.name) + # pylint: enable=protected-access + + def non_trainable_variables(self): + # pylint: disable=protected-access + return sorted([x for x in self._store._vars.values() if not x.trainable], + key=lambda x: x.name) + # pylint: enable=protected-access + + def copy(self): + """Copy this variable store and all of its contents. + + Variables contained in this store will be copied over to the new variable + store, meaning that they can be modified without affecting the variables in + this store. + + Returns: + A new EagerVariableStore instance containing copied variables. + """ + # pylint: disable=protected-access + new_store = EagerVariableStore() + for key, var in self._store._vars.items(): + # Strip device out of variable name. + try: + index = var.name.index(":") + except ValueError: + stripped_var_name = var.name + else: + stripped_var_name = var.name[:index] + + # Create new variable with same value, name, and "trainable" flag. + new_var = resource_variable_ops.ResourceVariable( + var.read_value(), name=stripped_var_name, trainable=var.trainable) + new_store._store._vars[key] = new_var + return new_store + # pylint: enable=protected-access + + +# The argument list for get_variable must match arguments to get_local_variable. +# So, if you are updating the arguments, also update arguments to +# get_local_variable below. +@tf_export(v1=["get_variable"]) +def get_variable(name, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=None, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + custom_getter=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + return get_variable_scope().get_variable( + _get_default_variable_store(), + name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + custom_getter=custom_getter, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + + +get_variable_or_local_docstring = ("""%s + +@compatibility(TF2) +Although it is a legacy `compat.v1` api, +`tf.compat.v1.get_variable` is mostly compatible with eager +execution and `tf.function` but only if you combine it with the +`tf.compat.v1.keras.utils.track_tf1_style_variables` decorator. (Though +it will behave as if reuse is always set to `AUTO_REUSE`.) + +See the +[model migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) +for more info. + +If you do not combine it with +`tf.compat.v1.keras.utils.track_tf1_style_variables`, `get_variable` will create +a brand new variable every single time it is called and will never reuse +variables, regardless of variable names or `reuse` arguments. + +The TF2 equivalent of this symbol would be `tf.Variable`, but note +that when using `tf.Variable` you must make sure you track your variables +(and regularizer arguments) either manually or via `tf.Module` or +`tf.keras.layers.Layer` mechanisms. + +A section of the +[migration guide](https://www.tensorflow.org/guide/migrate/model_mapping#incremental_migration_to_native_tf2) +provides more details on incrementally migrating these usages to `tf.Variable` +as well. + +Note: The `partitioner` arg is not compatible with TF2 behaviors even when +using `tf.compat.v1.keras.utils.track_tf1_style_variables`. It can be replaced +by using `ParameterServerStrategy` and its partitioners. See the +[multi-gpu migration guide](https://www.tensorflow.org/guide/migrate/multi_worker_cpu_gpu_training) +and the ParameterServerStrategy guides it references for more info. +@end_compatibility + +%sThis function prefixes the name with the current variable scope +and performs reuse checks. See the +[Variable Scope How To](https://tensorflow.org/guide/variables) +for an extensive description of how reusing works. Here is a basic example: + +```python +def foo(): + with tf.variable_scope("foo", reuse=tf.AUTO_REUSE): + v = tf.get_variable("v", [1]) + return v + +v1 = foo() # Creates v. +v2 = foo() # Gets the same, existing v. +assert v1 == v2 +``` + +If initializer is `None` (the default), the default initializer passed in +the variable scope will be used. If that one is `None` too, a +`glorot_uniform_initializer` will be used. The initializer can also be +a Tensor, in which case the variable is initialized to this value and shape. + +Similarly, if the regularizer is `None` (the default), the default regularizer +passed in the variable scope will be used (if that is `None` too, +then by default no regularization is performed). + +If a partitioner is provided, a `PartitionedVariable` is returned. +Accessing this object as a `Tensor` returns the shards concatenated along +the partition axis. + +Some useful partitioners are available. See, e.g., +`variable_axis_size_partitioner` and `min_max_variable_partitioner`. + +Args: + name: The name of the new or existing variable. + shape: Shape of the new or existing variable. + dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). + initializer: Initializer for the variable if one is created. Can either be + an initializer object or a Tensor. If it's a Tensor, its shape must be known + unless validate_shape is False. + regularizer: A (Tensor -> Tensor or None) function; the result of + applying it on a newly created variable will be added to the collection + `tf.GraphKeys.REGULARIZATION_LOSSES` and can be used for regularization. + %scollections: List of graph collections keys to add the Variable to. + Defaults to `[%s]` (see `tf.Variable`). + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + partitioner: Optional callable that accepts a fully defined `TensorShape` + and `dtype` of the Variable to be created, and returns a list of + partitions for each axis (currently only one axis can be partitioned). + validate_shape: If False, allows the variable to be initialized with a + value of unknown shape. If True, the default, the shape of initial_value + must be known. For this to be used the initializer must be a Tensor and + not an initializer object. + use_resource: If False, creates a regular Variable. If true, creates an + experimental ResourceVariable instead with well-defined semantics. + Defaults to False (will later change to True). When eager execution is + enabled this argument is always forced to be True. + custom_getter: Callable that takes as a first argument the true getter, and + allows overwriting the internal get_variable method. + The signature of `custom_getter` should match that of this method, + but the most future-proof version will allow for changes: + `def custom_getter(getter, *args, **kwargs)`. Direct access to + all `get_variable` parameters is also allowed: + `def custom_getter(getter, name, *args, **kwargs)`. A simple identity + custom getter that simply creates variables with modified names is: + ```python + def custom_getter(getter, name, *args, **kwargs): + return getter(name + '_suffix', *args, **kwargs) + ``` + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value + (which must have the same shape). Constraints are not safe to + use when doing asynchronous distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + +Returns: + The created or existing `Variable` (or `PartitionedVariable`, if a + partitioner was used). + +Raises: + ValueError: when creating a new variable and shape is not declared, + when violating reuse during variable creation, or when `initializer` dtype + and `dtype` don't match. Reuse is set inside `variable_scope`. +""") +get_variable.__doc__ = get_variable_or_local_docstring % ( + "Gets an existing variable with these parameters or create a new one.", "", + "trainable: If `True` also add the variable to the graph collection\n" + " `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n ", + "GraphKeys.GLOBAL_VARIABLES") + + +# The argument list for get_local_variable must match arguments to get_variable. +# So, if you are updating the arguments, also update arguments to get_variable. +@tf_export(v1=["get_local_variable"]) +def get_local_variable( # pylint: disable=missing-docstring + name, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=False, # pylint: disable=unused-argument + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + custom_getter=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + if collections: + collections += [ops.GraphKeys.LOCAL_VARIABLES] + else: + collections = [ops.GraphKeys.LOCAL_VARIABLES] + return get_variable( + name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + trainable=False, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + synchronization=synchronization, + aggregation=aggregation, + custom_getter=custom_getter, + constraint=constraint) + + +get_local_variable.__doc__ = get_variable_or_local_docstring % ( + "Gets an existing *local* variable or creates a new one.", + "Behavior is the same as in `get_variable`, except that variables are\n" + "added to the `LOCAL_VARIABLES` collection and `trainable` is set to\n" + "`False`.\n", "", "GraphKeys.LOCAL_VARIABLES") + + +def _get_partitioned_variable(name, + shape=None, + dtype=None, + initializer=None, + regularizer=None, + trainable=True, + collections=None, + caching_device=None, + partitioner=None, + validate_shape=True, + use_resource=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE): + """Gets or creates a sharded variable list with these parameters. + + The `partitioner` must be a callable that accepts a fully defined + `TensorShape` and returns a sequence of integers (the `partitions`). + These integers describe how to partition the given sharded `Variable` + along the given dimension. That is, `partitions[1] = 3` means split + the `Variable` into 3 shards along dimension 1. Currently, sharding along + only one axis is supported. + + If the list of variables with the given name (prefix) is already stored, + we return the stored variables. Otherwise, we create a new one. + + If initializer is `None` (the default), the default initializer passed in + the constructor is used. If that one is `None` too, we use a new + `glorot_uniform_initializer`. If initializer is a Tensor, we use + it as a value and derive the shape from the initializer. + + If the initializer is a callable, then it will be called for each + shard. Otherwise the initializer should match the shape of the entire + sharded Variable, and it will be sliced accordingly for each shard. + + Some useful partitioners are available. See, e.g., + `variable_axis_size_partitioner` and `min_max_variable_partitioner`. + + Args: + name: The name of the new or existing variable. + shape: Shape of the new or existing variable. + dtype: Type of the new or existing variable (defaults to `DT_FLOAT`). + initializer: Initializer for the variable if one is created. + regularizer: A (Tensor -> Tensor or None) function; the result of applying + it on a newly created variable will be added to the collection + GraphKeys.REGULARIZATION_LOSSES and can be used for regularization. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + collections: List of graph collections keys to add the Variable to. Defaults + to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`). + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's device. + If not `None`, caches on another device. Typical use is to cache on the + device where the Ops using the Variable reside, to deduplicate copying + through `Switch` and other conditional statements. + partitioner: Optional callable that accepts a fully defined `TensorShape` + and `dtype` of the Variable to be created, and returns a list of + partitions for each axis (currently only one axis can be partitioned). + validate_shape: If False, allows the variable to be initialized with a value + of unknown shape. If True, the default, the shape of initial_value must be + known. + use_resource: If False, creates a regular Variable. If True, creates an + experimental ResourceVariable instead which has well-defined semantics. + Defaults to False (will later change to True). + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + Returns: + A tuple `(shards, partitions)` where `shards` is the list of `Variable` + shards and `partitions` is the output of the partitioner on the input + shape. + + Raises: + ValueError: when creating a new variable and shape is not declared, + or when violating reuse during variable creation. Reuse is set inside + `variable_scope`. + """ + # pylint: disable=protected-access + scope = get_variable_scope() + if scope.custom_getter is not None: + raise ValueError( + "Private access to _get_partitioned_variable is not allowed when " + "a custom getter is set. Current custom getter: %s. " + "It is likely that you're using create_partitioned_variables. " + "If so, consider instead using get_variable with a non-empty " + "partitioner parameter instead." % scope.custom_getter) + return scope._get_partitioned_variable( + _get_default_variable_store(), + name, + shape=shape, + dtype=dtype, + initializer=initializer, + regularizer=regularizer, + trainable=trainable, + collections=collections, + caching_device=caching_device, + partitioner=partitioner, + validate_shape=validate_shape, + use_resource=use_resource, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation) + # pylint: enable=protected-access + + +# Named like a function for compatibility with the previous +# @tf_contextlib.contextmanager definition. +class _pure_variable_scope: # pylint: disable=invalid-name + """A context for the variable_scope, see `variable_scope` for docs.""" + + def __init__(self, + name_or_scope, + reuse=None, + initializer=None, + regularizer=None, + caching_device=None, + partitioner=None, + custom_getter=None, + old_name_scope=None, + dtype=dtypes.float32, + use_resource=None, + constraint=None): + """Creates a context for the variable_scope, see `variable_scope` for docs. + + Note: this does not create a name scope. + + Args: + name_or_scope: `string` or `VariableScope`: the scope to open. + reuse: `True` or None, or tf.compat.v1.AUTO_REUSE; if `None`, we inherit + the parent scope's reuse flag. + initializer: default initializer for variables within this scope. + regularizer: default regularizer for variables within this scope. + caching_device: default caching device for variables within this scope. + partitioner: default partitioner for variables within this scope. + custom_getter: default custom getter for variables within this scope. + old_name_scope: the original name scope when re-entering a variable scope. + dtype: type of the variables within this scope (defaults to `DT_FLOAT`). + use_resource: If False, variables in this scope will be regular Variables. + If True, experimental ResourceVariables will be creates instead, with + well-defined semantics. Defaults to False (will later change to True). + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + """ + self._name_or_scope = name_or_scope + self._reuse = reuse + self._initializer = initializer + self._regularizer = regularizer + self._caching_device = caching_device + self._partitioner = partitioner + self._custom_getter = custom_getter + self._old_name_scope = old_name_scope + self._dtype = dtype + self._use_resource = use_resource + self._constraint = constraint + self._var_store = _get_default_variable_store() + self._var_scope_store = get_variable_scope_store() + self._last_variable_scope_object = None + if isinstance(self._name_or_scope, VariableScope): + self._new_name = self._name_or_scope.name + name_scope = self._name_or_scope._name_scope # pylint: disable=protected-access + # Handler for the case when we jump to a shared scope. We create a new + # VariableScope (self._var_scope_object) that contains a copy of the + # provided shared scope, possibly with changed reuse and initializer, if + # the user requested this. + variable_scope_object = VariableScope( + self._name_or_scope.reuse if not self._reuse else self._reuse, + name=self._new_name, + initializer=self._name_or_scope.initializer, + regularizer=self._name_or_scope.regularizer, + caching_device=self._name_or_scope.caching_device, + partitioner=self._name_or_scope.partitioner, + dtype=self._name_or_scope.dtype, + custom_getter=self._name_or_scope.custom_getter, + name_scope=name_scope, + use_resource=self._name_or_scope.use_resource, + constraint=self._constraint) + if self._initializer is not None: + variable_scope_object.set_initializer(self._initializer) + if self._regularizer is not None: + variable_scope_object.set_regularizer(self._regularizer) + if self._caching_device is not None: + variable_scope_object.set_caching_device(self._caching_device) + if self._partitioner is not None: + variable_scope_object.set_partitioner(self._partitioner) + if self._custom_getter is not None: + variable_scope_object.set_custom_getter( + _maybe_wrap_custom_getter(self._custom_getter, + self._name_or_scope.custom_getter)) + if self._dtype is not None: + variable_scope_object.set_dtype(self._dtype) + if self._use_resource is not None: + variable_scope_object.set_use_resource(self._use_resource) + self._cached_variable_scope_object = variable_scope_object + + def __enter__(self): + """Begins the scope block. + + Returns: + A VariableScope. + Raises: + ValueError: when trying to reuse within a create scope, or create within + a reuse scope, or if reuse is not `None` or `True`. + TypeError: when the types of some arguments are not appropriate. + """ + self._old = self._var_scope_store.current_scope + if isinstance(self._name_or_scope, VariableScope): + self._var_scope_store.open_variable_scope(self._new_name) + self._old_subscopes = copy.copy( + self._var_scope_store.variable_scopes_count) + variable_scope_object = self._cached_variable_scope_object + else: + # Handler for the case when we just prolong current variable scope. + # VariableScope with name extended by the provided one, and inherited + # reuse and initializer (except if the user provided values to set). + self._new_name = ( + self._old.name + "/" + + self._name_or_scope if self._old.name else self._name_or_scope) + self._reuse = (self._reuse or + self._old.reuse) # Re-using is inherited by sub-scopes. + if self._old_name_scope is None: + name_scope = self._name_or_scope + else: + name_scope = self._old_name_scope + variable_scope_object = VariableScope( + self._reuse, + name=self._new_name, + initializer=self._old.initializer, + regularizer=self._old.regularizer, + caching_device=self._old.caching_device, + partitioner=self._old.partitioner, + dtype=self._old.dtype, + use_resource=self._old.use_resource, + custom_getter=self._old.custom_getter, + name_scope=name_scope, + constraint=self._constraint) + if self._initializer is not None: + variable_scope_object.set_initializer(self._initializer) + if self._regularizer is not None: + variable_scope_object.set_regularizer(self._regularizer) + if self._caching_device is not None: + variable_scope_object.set_caching_device(self._caching_device) + if self._partitioner is not None: + variable_scope_object.set_partitioner(self._partitioner) + if self._custom_getter is not None: + variable_scope_object.set_custom_getter( + _maybe_wrap_custom_getter(self._custom_getter, + self._old.custom_getter)) + if self._dtype is not None: + variable_scope_object.set_dtype(self._dtype) + if self._use_resource is not None: + variable_scope_object.set_use_resource(self._use_resource) + self._var_scope_store.open_variable_scope(self._new_name) + self._var_scope_store.current_scope = variable_scope_object + self._last_variable_scope_object = variable_scope_object + return variable_scope_object + + def __exit__(self, type_arg, value_arg, traceback_arg): + if (self._var_scope_store.current_scope is + not self._last_variable_scope_object): + raise RuntimeError("Improper nesting of variable_scope.") + # If jumping out from a non-prolonged scope, restore counts. + if isinstance(self._name_or_scope, VariableScope): + self._var_scope_store.variable_scopes_count = self._old_subscopes + else: + self._var_scope_store.close_variable_subscopes(self._new_name) + self._var_scope_store.current_scope = self._old + + +def _maybe_wrap_custom_getter(custom_getter, old_getter): + """Wrap a call to a custom_getter to use the old_getter internally.""" + if old_getter is None: + return custom_getter + + # The new custom_getter should call the old one + def wrapped_custom_getter(getter, *args, **kwargs): + # Call: + # custom_getter( + # lambda: old_getter(true_getter, ...), *args, **kwargs) + # which means custom_getter will call old_getter, which + # will call the true_getter, perform any intermediate + # processing, and return the results to the current + # getter, which will also perform additional processing. + return custom_getter(functools.partial(old_getter, getter), *args, **kwargs) + + return wrapped_custom_getter + + +def _get_unique_variable_scope(prefix): + """Get a name with the given prefix unique in the current variable scope.""" + var_scope_store = get_variable_scope_store() + current_scope = get_variable_scope() + name = current_scope.name + "/" + prefix if current_scope.name else prefix + if var_scope_store.variable_scope_count(name) == 0: + return prefix + idx = 1 + while var_scope_store.variable_scope_count(name + ("_%d" % idx)) > 0: + idx += 1 + return prefix + ("_%d" % idx) + + +# Named like a function for backwards compatibility with the +# @tf_contextlib.contextmanager version, which was switched to a class to avoid +# some object creation overhead. +@tf_export(v1=["variable_scope"]) # pylint: disable=invalid-name +class variable_scope: + """A context manager for defining ops that creates variables (layers). + + @compatibility(TF2) + Although it is a legacy `compat.v1` api, + `tf.compat.v1.variable_scope` is mostly compatible with eager + execution and `tf.function` as long as you combine it with the + `tf.compat.v1.keras.utils.track_tf1_style_variables` decorator (though + it will behave as if reuse is always set to `AUTO_REUSE`.) + + See the + [model migration guide]( + https://www.tensorflow.org/guide/migrate/model_mapping) + for more info on + migrating code that relies on `variable_scope`-based variable reuse. + + When you use it with eager execution enabled but without + `tf.compat.v1.keras.utils.track_tf1_style_variables`, + `tf.compat.v1.variable_scope` will still be able to prefix the names + of variables created within the scope but it will not enable variable reuse + or error-raising checks around variable reuse (`get_variable` calls within + it would always create new variables). + + Once you have switched away from `get_variable`-based variable reuse + mechanisms, to switch to TF2 APIs you can just use + `tf.name_scope` to prefix variable names. + @end_compatibility + + This context manager validates that the (optional) `values` are from the same + graph, ensures that graph is the default graph, and pushes a name scope and a + variable scope. + + If `name_or_scope` is not None, it is used as is. If `name_or_scope` is None, + then `default_name` is used. In that case, if the same name has been + previously used in the same scope, it will be made unique by appending `_N` + to it. + + Variable scope allows you to create new variables and to share already created + ones while providing checks to not create or share by accident. For details, + see the [Variable Scope How To](https://tensorflow.org/guide/variables), here + we present only a few basic examples. + + The Variable Scope works as expected when the Eager Execution is Disabled. + + ```python + tf.compat.v1.disable_eager_execution() + ``` + + Simple example of how to create a new variable: + + ```python + with tf.compat.v1.variable_scope("foo"): + with tf.compat.v1.variable_scope("bar"): + v = tf.compat.v1.get_variable("v", [1]) + assert v.name == "foo/bar/v:0" + ``` + + Simple example of how to reenter a premade variable scope safely: + + ```python + with tf.compat.v1.variable_scope("foo") as vs: + pass + + # Re-enter the variable scope. + with tf.compat.v1.variable_scope(vs, + auxiliary_name_scope=False) as vs1: + # Restore the original name_scope. + with tf.name_scope(vs1.original_name_scope): + v = tf.compat.v1.get_variable("v", [1]) + assert v.name == "foo/v:0" + c = tf.constant([1], name="c") + assert c.name == "foo/c:0" + ``` + + Keep in mind that the counters for `default_name` are discarded once the + parent scope is exited. Therefore when the code re-enters the scope (for + instance by saving it), all nested default_name counters will be restarted. + + For instance: + + ```python + with tf.compat.v1.variable_scope("foo") as vs: + with tf.compat.v1.variable_scope(None, default_name="bar"): + v = tf.compat.v1.get_variable("a", [1]) + assert v.name == "foo/bar/a:0", v.name + with tf.compat.v1.variable_scope(None, default_name="bar"): + v = tf.compat.v1.get_variable("b", [1]) + assert v.name == "foo/bar_1/b:0" + + with tf.compat.v1.variable_scope(vs): + with tf.compat.v1.variable_scope(None, default_name="bar"): + v = tf.compat.v1.get_variable("c", [1]) + assert v.name == "foo/bar/c:0" # Uses bar instead of bar_2! + ``` + + Basic example of sharing a variable AUTO_REUSE: + + ```python + def foo(): + with tf.compat.v1.variable_scope("foo", reuse=tf.compat.v1.AUTO_REUSE): + v = tf.compat.v1.get_variable("v", [1]) + return v + + v1 = foo() # Creates v. + v2 = foo() # Gets the same, existing v. + assert v1 == v2 + ``` + + Basic example of sharing a variable with reuse=True: + + ```python + with tf.compat.v1.variable_scope("foo"): + v = tf.compat.v1.get_variable("v", [1]) + with tf.compat.v1.variable_scope("foo", reuse=True): + v1 = tf.compat.v1.get_variable("v", [1]) + assert v1 == v + ``` + + Sharing a variable by capturing a scope and setting reuse: + + ```python + with tf.compat.v1.variable_scope("foo") as scope: + v = tf.compat.v1.get_variable("v", [1]) + scope.reuse_variables() + v1 = tf.compat.v1.get_variable("v", [1]) + assert v1 == v + ``` + + To prevent accidental sharing of variables, we raise an exception when getting + an existing variable in a non-reusing scope. + + ```python + with tf.compat.v1.variable_scope("foo"): + v = tf.compat.v1.get_variable("v", [1]) + v1 = tf.compat.v1.get_variable("v", [1]) + # Raises ValueError("... v already exists ..."). + ``` + + Similarly, we raise an exception when trying to get a variable that does not + exist in reuse mode. + + ```python + with tf.compat.v1.variable_scope("foo", reuse=True): + v = tf.compat.v1.get_variable("v", [1]) + # Raises ValueError("... v does not exists ..."). + ``` + + Note that the `reuse` flag is inherited: if we open a reusing scope, then all + its sub-scopes become reusing as well. + + A note about name scoping: Setting `reuse` does not impact the naming of other + ops such as mult. See related discussion on + [github#6189](https://github.com/tensorflow/tensorflow/issues/6189) + + Note that up to and including version 1.0, it was allowed (though explicitly + discouraged) to pass False to the reuse argument, yielding undocumented + behaviour slightly different from None. Starting at 1.1.0 passing None and + False as reuse has exactly the same effect. + + A note about using variable scopes in multi-threaded environment: Variable + scopes are thread local, so one thread will not see another thread's current + scope. Also, when using `default_name`, unique scopes names are also generated + only on a per thread basis. If the same name was used within a different + thread, that doesn't prevent a new thread from creating the same scope. + However, the underlying variable store is shared across threads (within the + same graph). As such, if another thread tries to create a new variable with + the same name as a variable created by a previous thread, it will fail unless + reuse is True. + + Further, each thread starts with an empty variable scope. So if you wish to + preserve name prefixes from a scope from the main thread, you should capture + the main thread's scope and re-enter it in each thread. For e.g. + + ``` + main_thread_scope = variable_scope.get_variable_scope() + + # Thread's target function: + def thread_target_fn(captured_scope): + with variable_scope.variable_scope(captured_scope): + # .... regular code for this thread + + + thread = threading.Thread(target=thread_target_fn, args=(main_thread_scope,)) + ``` + """ + + def __init__(self, + name_or_scope, + default_name=None, + values=None, + initializer=None, + regularizer=None, + caching_device=None, + partitioner=None, + custom_getter=None, + reuse=None, + dtype=None, + use_resource=None, + constraint=None, + auxiliary_name_scope=True): + """Initialize the context manager. + + Args: + name_or_scope: `string` or `VariableScope`: the scope to open. + default_name: The default name to use if the `name_or_scope` argument is + `None`, this name will be uniquified. If name_or_scope is provided it + won't be used and therefore it is not required and can be None. + values: The list of `Tensor` arguments that are passed to the op function. + initializer: default initializer for variables within this scope. + regularizer: default regularizer for variables within this scope. + caching_device: default caching device for variables within this scope. + partitioner: default partitioner for variables within this scope. + custom_getter: default custom getter for variables within this scope. + reuse: `True`, None, or tf.compat.v1.AUTO_REUSE; if `True`, we go into + reuse mode for this scope as well as all sub-scopes; if + tf.compat.v1.AUTO_REUSE, we create variables if they do not exist, and + return them otherwise; if None, we inherit the parent scope's reuse + flag. When eager execution is enabled, new variables are always created + unless an EagerVariableStore or template is currently active. + dtype: type of variables created in this scope (defaults to the type in + the passed scope, or inherited from parent scope). + use_resource: If False, all variables will be regular Variables. If True, + experimental ResourceVariables with well-defined semantics will be used + instead. Defaults to False (will later change to True). When eager + execution is enabled this argument is always forced to be True. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + auxiliary_name_scope: If `True`, we create an auxiliary name scope with + the scope. If `False`, we don't create it. Note that the argument is not + inherited, and it only takes effect for once when creating. You should + only use it for re-entering a premade variable scope. + + Returns: + A scope that can be captured and reused. + + Raises: + ValueError: when trying to reuse within a create scope, or create within + a reuse scope. + TypeError: when the types of some arguments are not appropriate. + """ + self._name_or_scope = name_or_scope + self._default_name = default_name + self._values = values + self._initializer = initializer + self._regularizer = regularizer + self._caching_device = caching_device + self._partitioner = partitioner + self._custom_getter = custom_getter + self._reuse = reuse + self._dtype = dtype + self._use_resource = use_resource + self._constraint = constraint + if self._default_name is None and self._name_or_scope is None: + raise TypeError("If default_name is None then name_or_scope is required") + if self._reuse is False: + # We don't allow non-inheriting scopes, False = None here. + self._reuse = None + if not (self._reuse is True + or self._reuse is None + or self._reuse is AUTO_REUSE): + raise ValueError("The reuse parameter must be True or False or None.") + if self._values is None: + self._values = [] + self._in_graph_mode = not context.executing_eagerly() + if self._in_graph_mode: + self._graph = ops._get_graph_from_inputs(self._values) # pylint: disable=protected-access + self._cached_pure_variable_scope = None + self._current_name_scope = None + if not isinstance(auxiliary_name_scope, bool): + raise TypeError("The auxiliary_name_scope must be `True` or `False`, " + "while get {}".format(auxiliary_name_scope)) + self._auxiliary_name_scope = auxiliary_name_scope + + def __enter__(self): + # If the default graph is building a function, then we should not replace it + # with the cached graph. + if ops.get_default_graph().building_function: + self._building_function = True + else: + self._building_function = False + if self._in_graph_mode and not self._building_function: + self._graph_context_manager = self._graph.as_default() + self._graph_context_manager.__enter__() + if self._cached_pure_variable_scope is not None: + # Fast path for re-entering variable_scopes. We've held on to the pure + # variable scope from a previous successful __enter__, so we avoid some + # overhead by re-using that object. + if self._current_name_scope is not None: + self._current_name_scope.__enter__() + return self._cached_pure_variable_scope.__enter__() + + try: + return self._enter_scope_uncached() + except: + if (self._in_graph_mode and not self._building_function and + self._graph_context_manager is not None): + self._graph_context_manager.__exit__(*sys.exc_info()) + raise + + def _enter_scope_uncached(self): + """Enters the context manager when there is no cached scope yet. + + Returns: + The entered variable scope. + + Raises: + TypeError: A wrong type is passed as `scope` at __init__(). + ValueError: `reuse` is incorrectly set at __init__(). + """ + if self._auxiliary_name_scope: + # Create a new name scope later + current_name_scope = None + else: + # Reenter the current name scope + name_scope = ops.get_name_scope() + if name_scope: + # Hack to reenter + name_scope += "/" + current_name_scope = ops.name_scope(name_scope, skip_on_eager=False) + else: + # Root scope + current_name_scope = ops.name_scope(name_scope, skip_on_eager=False) + + # IMPORTANT: Only assign to self._cached_pure_variable_scope and + # self._current_name_scope after successful __enter__() calls. + if self._name_or_scope is not None: + if not isinstance(self._name_or_scope, (VariableScope, str)): + raise TypeError("VariableScope: name_or_scope must be a string or " + "VariableScope.") + if isinstance(self._name_or_scope, str): + name_scope = self._name_or_scope + else: + name_scope = self._name_or_scope.name.split("/")[-1] + if name_scope or current_name_scope: + current_name_scope = current_name_scope or ops.name_scope( + name_scope, skip_on_eager=False) + try: + current_name_scope_name = current_name_scope.__enter__() + except: + current_name_scope.__exit__(*sys.exc_info()) + raise + self._current_name_scope = current_name_scope + if isinstance(self._name_or_scope, str): + old_name_scope = current_name_scope_name + else: + old_name_scope = self._name_or_scope.original_name_scope + pure_variable_scope = _pure_variable_scope( + self._name_or_scope, + reuse=self._reuse, + initializer=self._initializer, + regularizer=self._regularizer, + caching_device=self._caching_device, + partitioner=self._partitioner, + custom_getter=self._custom_getter, + old_name_scope=old_name_scope, + dtype=self._dtype, + use_resource=self._use_resource, + constraint=self._constraint) + try: + entered_pure_variable_scope = pure_variable_scope.__enter__() + except: + pure_variable_scope.__exit__(*sys.exc_info()) + raise + self._cached_pure_variable_scope = pure_variable_scope + return entered_pure_variable_scope + else: + self._current_name_scope = None + # This can only happen if someone is entering the root variable scope. + pure_variable_scope = _pure_variable_scope( + self._name_or_scope, + reuse=self._reuse, + initializer=self._initializer, + regularizer=self._regularizer, + caching_device=self._caching_device, + partitioner=self._partitioner, + custom_getter=self._custom_getter, + dtype=self._dtype, + use_resource=self._use_resource, + constraint=self._constraint) + try: + entered_pure_variable_scope = pure_variable_scope.__enter__() + except: + pure_variable_scope.__exit__(*sys.exc_info()) + raise + self._cached_pure_variable_scope = pure_variable_scope + return entered_pure_variable_scope + + else: # Here name_or_scope is None. Using default name, but made unique. + if self._reuse: + raise ValueError("reuse=True cannot be used without a name_or_scope") + current_name_scope = current_name_scope or ops.name_scope( + self._default_name, skip_on_eager=False) + try: + current_name_scope_name = current_name_scope.__enter__() + except: + current_name_scope.__exit__(*sys.exc_info()) + raise + self._current_name_scope = current_name_scope + unique_default_name = _get_unique_variable_scope(self._default_name) + pure_variable_scope = _pure_variable_scope( + unique_default_name, + initializer=self._initializer, + regularizer=self._regularizer, + caching_device=self._caching_device, + partitioner=self._partitioner, + custom_getter=self._custom_getter, + old_name_scope=current_name_scope_name, + dtype=self._dtype, + use_resource=self._use_resource, + constraint=self._constraint) + try: + entered_pure_variable_scope = pure_variable_scope.__enter__() + except: + pure_variable_scope.__exit__(*sys.exc_info()) + raise + self._cached_pure_variable_scope = pure_variable_scope + return entered_pure_variable_scope + + def __exit__(self, type_arg, value_arg, traceback_arg): + try: + self._cached_pure_variable_scope.__exit__(type_arg, value_arg, + traceback_arg) + finally: + try: + if self._current_name_scope: + self._current_name_scope.__exit__(type_arg, value_arg, + traceback_arg) + finally: + if self._in_graph_mode and not self._building_function: + self._graph_context_manager.__exit__(type_arg, value_arg, + traceback_arg) + + +# pylint: disable=g-doc-return-or-yield +@tf_export(v1=["variable_op_scope"]) +@tf_contextlib.contextmanager +def variable_op_scope(values, + name_or_scope, + default_name=None, + initializer=None, + regularizer=None, + caching_device=None, + partitioner=None, + custom_getter=None, + reuse=None, + dtype=None, + use_resource=None, + constraint=None): + """Deprecated: context manager for defining an op that creates variables.""" + logging.warn("tf.variable_op_scope(values, name, default_name) is deprecated," + " use tf.variable_scope(name, default_name, values)") + with variable_scope( + name_or_scope, + default_name=default_name, + values=values, + initializer=initializer, + regularizer=regularizer, + caching_device=caching_device, + partitioner=partitioner, + custom_getter=custom_getter, + reuse=reuse, + dtype=dtype, + use_resource=use_resource, + constraint=constraint) as scope: + yield scope + + +def _call_partitioner(partitioner, shape, dtype): + """Call partitioner validating its inputs/output. + + Args: + partitioner: a function mapping `Tensor` shape and dtype to a list of + partitions. + shape: shape of the `Tensor` to partition, must have at least two + dimensions. + dtype: dtype of the elements in the `Tensor`. + + Returns: + A list with elements >=1 and exactly one >1. The index of that + element corresponds to the partitioning axis. + """ + if not shape.is_fully_defined(): + raise ValueError("Shape of a new partitioned variable must be " + "fully defined, but instead was %s." % (shape,)) + if shape.ndims < 1: + raise ValueError("A partitioned Variable must have rank at least 1, " + "shape: %s" % shape) + + slicing = partitioner(shape=shape, dtype=dtype) + if not isinstance(slicing, collections_abc.Sequence): + raise ValueError("Partitioner must return a sequence, but saw: %s" % + slicing) + if len(slicing) != shape.ndims: + raise ValueError( + "Partitioner returned a partition list that does not match the " + "Variable's rank: %s vs. %s" % (slicing, shape)) + if any(p < 1 for p in slicing): + raise ValueError("Partitioner returned zero partitions for some axes: %s" % + slicing) + if sum(p > 1 for p in slicing) > 1: + raise ValueError("Can only slice a variable along one dimension: " + "shape: %s, partitioning: %s" % (shape, slicing)) + return slicing + + +# TODO(slebedev): could be inlined, but +# `_VariableStore._get_partitioned_variable` is too complex even +# without this logic. +def _get_slice_dim_and_num_slices(slicing): + """Get slicing dimension and number of slices from the partitioner output.""" + for slice_dim, num_slices in enumerate(slicing): + if num_slices > 1: + break + else: + # Degenerate case: no partitioning applied. + slice_dim = 0 + num_slices = 1 + return slice_dim, num_slices + + +def _iter_slices(full_shape, num_slices, slice_dim): + """Slices a given a shape along the specified dimension.""" + num_slices_with_excess = full_shape[slice_dim] % num_slices + offset = [0] * len(full_shape) + min_slice_len = full_shape[slice_dim] // num_slices + for i in range(num_slices): + shape = full_shape[:] + shape[slice_dim] = min_slice_len + bool(i < num_slices_with_excess) + yield offset[:], shape + offset[slice_dim] += shape[slice_dim] + + +def _make_getter(captured_getter, captured_previous): + """Gets around capturing loop variables in python being broken.""" + return lambda **kwargs: captured_getter(captured_previous, **kwargs) + + +_variable_v1 = None + + +def set_variable_v1(variable_v1): + """Sets a reference to variable_v1.VariableV1.""" + global _variable_v1 + _variable_v1 = variable_v1 + + +@tf_export(v1=["variable_creator_scope"]) +@tf_contextlib.contextmanager +def variable_creator_scope_v1(variable_creator): + """Scope which defines a variable creation function to be used by variable(). + + variable_creator is expected to be a function with the following signature: + + ``` + def variable_creator(next_creator, **kwargs) + ``` + + The creator is supposed to eventually call the next_creator to create a + variable if it does want to create a variable and not call Variable or + ResourceVariable directly. This helps make creators composable. A creator may + choose to create multiple variables, return already existing variables, or + simply register that a variable was created and defer to the next creators in + line. Creators can also modify the keyword arguments seen by the next + creators. + + Custom getters in the variable scope will eventually resolve down to these + custom creators when they do create variables. + + The valid keyword arguments in kwds are: + + * initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. In + that case, `dtype` must be specified. (Note that initializer functions + from init_ops.py must first be bound to a shape before being used here.) + * trainable: If `True`, the default, also adds the variable to the graph + collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as + the default list of variables to use by the `Optimizer` classes. + `trainable` defaults to `True`, unless `synchronization` is + set to `ON_READ`, in which case it defaults to `False`. + * collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + * validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + * caching_device: Optional device string describing where the Variable + should be cached for reading. Defaults to the Variable's device. + If not `None`, caches on another device. Typical use is to cache + on the device where the Ops using the Variable reside, to deduplicate + copying through `Switch` and other conditional statements. + * name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + * dtype: If set, initial_value will be converted to the given type. + If `None`, either the datatype will be kept (if `initial_value` is + a Tensor), or `convert_to_tensor` will decide. + * constraint: A constraint function to be applied to the variable after + updates by some algorithms. + * use_resource: if True, a ResourceVariable is always created. + * synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. + * aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + This set may grow over time, so it's important the signature of creators is as + mentioned above. + + Args: + variable_creator: the passed creator + + Yields: + A scope in which the creator is active + """ + with ops.get_default_graph()._variable_creator_scope(variable_creator): # pylint: disable=protected-access + yield + + +# Note: only the docstrings differ between this and v1. +@tf_export("variable_creator_scope", v1=[]) +@tf_contextlib.contextmanager +def variable_creator_scope(variable_creator): + """Scope which defines a variable creation function to be used by variable(). + + variable_creator is expected to be a function with the following signature: + + ``` + def variable_creator(next_creator, **kwargs) + ``` + + The creator is supposed to eventually call the next_creator to create a + variable if it does want to create a variable and not call Variable or + ResourceVariable directly. This helps make creators composable. A creator may + choose to create multiple variables, return already existing variables, or + simply register that a variable was created and defer to the next creators in + line. Creators can also modify the keyword arguments seen by the next + creators. + + Custom getters in the variable scope will eventually resolve down to these + custom creators when they do create variables. + + The valid keyword arguments in kwds are: + + * initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. In + that case, `dtype` must be specified. (Note that initializer functions + from init_ops.py must first be bound to a shape before being used here.) + * trainable: If `True`, the default, GradientTapes automatically watch + uses of this Variable. + * validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + * caching_device: Optional device string describing where the Variable + should be cached for reading. Defaults to the Variable's device. + If not `None`, caches on another device. Typical use is to cache + on the device where the Ops using the Variable reside, to deduplicate + copying through `Switch` and other conditional statements. + * name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + dtype: If set, initial_value will be converted to the given type. + If `None`, either the datatype will be kept (if `initial_value` is + a Tensor), or `convert_to_tensor` will decide. + * constraint: A constraint function to be applied to the variable after + updates by some algorithms. + * synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses + when to synchronize. + * aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + + This set may grow over time, so it's important the signature of creators is as + mentioned above. + + Args: + variable_creator: the passed creator + + Yields: + A scope in which the creator is active + """ + with ops.get_default_graph()._variable_creator_scope(variable_creator): # pylint: disable=protected-access + yield diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d4f0e5daeee94e3dad9e52077b76edffdc3d62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variable_v1.py @@ -0,0 +1,325 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""VariableV1 class.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables +from tensorflow.python.util import tf_should_use +from tensorflow.python.util.tf_export import tf_export + + +_variable_from_proto_fn = None + + +def set_variable_from_proto_fn(variable_from_proto_fn): + """Set the variable class that variable proto defs will be converted to.""" + global _variable_from_proto_fn + _variable_from_proto_fn = variable_from_proto_fn + + +@tf_export(v1=["is_variable_initialized"]) +@tf_should_use.should_use_result +def is_variable_initialized(variable): + """Tests if a variable has been initialized. + + Args: + variable: A `Variable`. + + Returns: + Returns a scalar boolean Tensor, `True` if the variable has been + initialized, `False` otherwise. + """ + return state_ops.is_variable_initialized(variable) + + +def default_variable_creator(_, **kwds): + del kwds + raise NotImplementedError("ref_variable needs to be imported") + + +@tf_export(v1=["Variable"]) +class VariableV1(variables.Variable): + """See the [Variables Guide](https://tensorflow.org/guide/variables). + + A variable maintains state in the graph across calls to `run()`. You add a + variable to the graph by constructing an instance of the class `Variable`. + + The `Variable()` constructor requires an initial value for the variable, + which can be a `Tensor` of any type and shape. The initial value defines the + type and shape of the variable. After construction, the type and shape of + the variable are fixed. The value can be changed using one of the assign + methods. + + If you want to change the shape of a variable later you have to use an + `assign` Op with `validate_shape=False`. + + Just like any `Tensor`, variables created with `Variable()` can be used as + inputs for other Ops in the graph. Additionally, all the operators + overloaded for the `Tensor` class are carried over to variables, so you can + also add nodes to the graph by just doing arithmetic on variables. + + ```python + import tensorflow as tf + + # Create a variable. + w = tf.Variable(, name=) + + # Use the variable in the graph like any Tensor. + y = tf.matmul(w, ...another variable or tensor...) + + # The overloaded operators are available too. + z = tf.sigmoid(w + y) + + # Assign a new value to the variable with `assign()` or a related method. + w.assign(w + 1.0) + w.assign_add(1.0) + ``` + + When you launch the graph, variables have to be explicitly initialized before + you can run Ops that use their value. You can initialize a variable by + running its *initializer op*, restoring the variable from a save file, or + simply running an `assign` Op that assigns a value to the variable. In fact, + the variable *initializer op* is just an `assign` Op that assigns the + variable's initial value to the variable itself. + + ```python + # Launch the graph in a session. + with tf.compat.v1.Session() as sess: + # Run the variable initializer. + sess.run(w.initializer) + # ...you now can run ops that use the value of 'w'... + ``` + + The most common initialization pattern is to use the convenience function + `global_variables_initializer()` to add an Op to the graph that initializes + all the variables. You then run that Op after launching the graph. + + ```python + # Add an Op to initialize global variables. + init_op = tf.compat.v1.global_variables_initializer() + + # Launch the graph in a session. + with tf.compat.v1.Session() as sess: + # Run the Op that initializes global variables. + sess.run(init_op) + # ...you can now run any Op that uses variable values... + ``` + + If you need to create a variable with an initial value dependent on another + variable, use the other variable's `initialized_value()`. This ensures that + variables are initialized in the right order. + + All variables are automatically collected in the graph where they are + created. By default, the constructor adds the new variable to the graph + collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function + `global_variables()` returns the contents of that collection. + + When building a machine learning model it is often convenient to distinguish + between variables holding the trainable model parameters and other variables + such as a `global step` variable used to count training steps. To make this + easier, the variable constructor supports a `trainable=` parameter. If + `True`, the new variable is also added to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. The convenience function + `trainable_variables()` returns the contents of this collection. The + various `Optimizer` classes use this collection as the default list of + variables to optimize. + + WARNING: tf.Variable objects by default have a non-intuitive memory model. A + Variable is represented internally as a mutable Tensor which can + non-deterministically alias other Tensors in a graph. The set of operations + which consume a Variable and can lead to aliasing is undetermined and can + change across TensorFlow versions. Avoid writing code which relies on the + value of a Variable either changing or not changing as other operations + happen. For example, using Variable objects or simple functions thereof as + predicates in a `tf.cond` is dangerous and error-prone: + + ``` + v = tf.Variable(True) + tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken. + ``` + + Here, adding `use_resource=True` when constructing the variable will + fix any nondeterminism issues: + ``` + v = tf.Variable(True, use_resource=True) + tf.cond(v, lambda: v.assign(False), my_false_fn) + ``` + + To use the replacement for variables which does + not have these issues: + + * Add `use_resource=True` when constructing `tf.Variable`; + * Call `tf.compat.v1.get_variable_scope().set_use_resource(True)` inside a + `tf.compat.v1.variable_scope` before the `tf.compat.v1.get_variable()` call. + """ + + def __init__( + self, # pylint: disable=super-init-not-called + initial_value=None, + trainable=None, + collections=None, + validate_shape=True, + caching_device=None, + name=None, + variable_def=None, + dtype=None, + expected_shape=None, + import_scope=None, + constraint=None, + use_resource=None, + synchronization=variables.VariableSynchronization.AUTO, + aggregation=variables.VariableAggregation.NONE, + shape=None): + """Creates a new variable with value `initial_value`. + + The new variable is added to the graph collections listed in `collections`, + which defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + + If `trainable` is `True` the variable is also added to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. + + This constructor creates both a `variable` Op and an `assign` Op to set the + variable to its initial value. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. In + that case, `dtype` must be specified. (Note that initializer functions + from init_ops.py must first be bound to a shape before being used here.) + trainable: If `True`, also adds the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default + list of variables to use by the `Optimizer` classes. Defaults to `True`, + unless `synchronization` is set to `ON_READ`, in which case it defaults + to `False`. + collections: List of graph collections keys. The new variable is added to + these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + caching_device: Optional device string describing where the Variable + should be cached for reading. Defaults to the Variable's device. If not + `None`, caches on another device. Typical use is to cache on the device + where the Ops using the Variable reside, to deduplicate copying through + `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + variable_def: `VariableDef` protocol buffer. If not `None`, recreates the + Variable object with its contents, referencing the variable's nodes in + the graph, which must already exist. The graph is not changed. + `variable_def` and the other arguments are mutually exclusive. + dtype: If set, initial_value will be converted to the given type. If + `None`, either the datatype will be kept (if `initial_value` is a + Tensor), or `convert_to_tensor` will decide. + expected_shape: A TensorShape. If set, initial_value is expected to have + this shape. + import_scope: Optional `string`. Name scope to add to the `Variable.` Only + used when initializing from protocol buffer. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + use_resource: whether to use resource variables. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + + Raises: + ValueError: If both `variable_def` and initial_value are specified. + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + RuntimeError: If eager execution is enabled. + """ + + SaveSliceInfo = variables.Variable.SaveSliceInfo + + def initialized_value(self): + with ops.init_scope(): + return cond.cond( + is_variable_initialized(self), self.read_value, + lambda: self.initial_value) + + @staticmethod + def from_proto(variable_def, import_scope=None): + return _variable_from_proto_fn( + variable_def=variable_def, import_scope=import_scope) + + @classmethod + def _variable_call( + cls, + initial_value=None, + trainable=None, + validate_shape=True, + caching_device=None, + name=None, + variable_def=None, + dtype=None, + import_scope=None, + constraint=None, + synchronization=variables.VariableSynchronization.AUTO, + aggregation=variables.VariableAggregation.NONE, + shape=None, + experimental_enable_variable_lifting=None, + expected_shape=None, + collections=None, + use_resource=None, + **kwargs, + ): + """VariableV1 class getter. Useful to force the signature.""" + if cls is not VariableV1: + return None + previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) + for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access + previous_getter = variables._make_getter(getter, previous_getter) # pylint: disable=protected-access + + # Reset `aggregation` that is explicitly set as `None` to the enum NONE. + if aggregation is None: + aggregation = variables.VariableAggregation.NONE + return previous_getter( + initial_value=initial_value, + trainable=trainable, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + variable_def=variable_def, + dtype=dtype, + import_scope=import_scope, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + shape=shape, + experimental_enable_variable_lifting=experimental_enable_variable_lifting, + expected_shape=expected_shape, + collections=collections, + use_resource=use_resource, + ) + +variable_scope.set_variable_v1(VariableV1) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variables.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variables.py new file mode 100644 index 0000000000000000000000000000000000000000..d99b7e114aa3723c6881188d4f1493786ab3cf09 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/variables.py @@ -0,0 +1,2042 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Variable class.""" + +import abc +import enum +import functools +import itertools +import os + +from tensorflow.core.framework import variable_pb2 +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.trackable import base as trackable +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_should_use +from tensorflow.python.util import traceback_utils +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import tf_export + + +def default_variable_creator_v2(_, **kwds): + del kwds + raise NotImplementedError("resource_variable_ops needs to be imported") + + +def _make_getter(captured_getter, captured_previous): + """To avoid capturing loop variables.""" + + def getter(**kwargs): + return captured_getter(captured_previous, **kwargs) + + return getter + + +@tf_export("VariableSynchronization") +class VariableSynchronization(enum.Enum): + """Indicates when a distributed variable will be synced. + + * `AUTO`: Indicates that the synchronization will be determined by the current + `DistributionStrategy` (eg. With `MirroredStrategy` this would be + `ON_WRITE`). + * `NONE`: Indicates that there will only be one copy of the variable, so + there is no need to sync. + * `ON_WRITE`: Indicates that the variable will be updated across devices + every time it is written. + * `ON_READ`: Indicates that the variable will be aggregated across devices + when it is read (eg. when checkpointing or when evaluating an op that uses + the variable). + + Example: + >>> temp_grad=[tf.Variable([0.], trainable=False, + ... synchronization=tf.VariableSynchronization.ON_READ, + ... aggregation=tf.VariableAggregation.MEAN + ... )] + """ + AUTO = 0 + NONE = 1 + ON_WRITE = 2 + ON_READ = 3 + + +# LINT.IfChange +@tf_export("VariableAggregation", v1=[]) +class VariableAggregationV2(enum.Enum): + """Indicates how a distributed variable will be aggregated. + + `tf.distribute.Strategy` distributes a model by making multiple copies + (called "replicas") acting on different elements of the input batch in a + data parallel model. When performing some variable-update operation, + for example `var.assign_add(x)`, in a model, we need to resolve how to combine + the different values for `x` computed in the different replicas. + + * `NONE`: This is the default, giving an error if you use a + variable-update operation with multiple replicas. + * `SUM`: Add the updates across replicas. + * `MEAN`: Take the arithmetic mean ("average") of the updates across replicas. + * `ONLY_FIRST_REPLICA`: This is for when every replica is performing the same + update, but we only want to perform the update once. Used, e.g., for the + global step counter. + + For example: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> with strategy.scope(): + ... v = tf.Variable(5.0, aggregation=tf.VariableAggregation.MEAN) + >>> @tf.function + ... def update_fn(): + ... return v.assign_add(1.0) + >>> strategy.run(update_fn) + PerReplica:{ + 0: , + 1: + } + + """ + NONE = 0 + SUM = 1 + MEAN = 2 + ONLY_FIRST_REPLICA = 3 + + def __hash__(self): + return hash(self.value) + + def __eq__(self, other): + if self is other: + return True + elif isinstance(other, VariableAggregation): + return int(self.value) == int(other.value) + else: + return False + + +@tf_export(v1=["VariableAggregation"]) +class VariableAggregation(enum.Enum): + NONE = 0 + SUM = 1 + MEAN = 2 + ONLY_FIRST_REPLICA = 3 + ONLY_FIRST_TOWER = 3 # DEPRECATED + + def __hash__(self): + return hash(self.value) + + +# LINT.ThenChange(//tensorflow/core/framework/variable.proto) +# +# Note that we are currently relying on the integer values of the Python enums +# matching the integer values of the proto enums. + +VariableAggregation.__doc__ = ( + VariableAggregationV2.__doc__ + + "* `ONLY_FIRST_TOWER`: Deprecated alias for `ONLY_FIRST_REPLICA`.\n ") + + +def validate_synchronization_aggregation_trainable(synchronization, aggregation, + trainable, name): + """Given user-provided variable properties, sets defaults and validates.""" + if aggregation is None: + aggregation = VariableAggregation.NONE + else: + if not isinstance(aggregation, + (VariableAggregation, VariableAggregationV2)): + try: + aggregation = VariableAggregationV2(aggregation) + except ValueError: + raise ValueError( + "Invalid variable aggregation mode: {} for variable: {}".format( + aggregation, name)) + if synchronization is None: + synchronization = VariableSynchronization.AUTO + else: + try: + synchronization = VariableSynchronization(synchronization) + except ValueError: + raise ValueError( + "Invalid variable synchronization mode: {} for variable: {}".format( + synchronization, name)) + if trainable is None: + trainable = synchronization != VariableSynchronization.ON_READ + return synchronization, aggregation, trainable + + +class VariableMetaclass(abc.ABCMeta): + """Metaclass to allow construction of tf.Variable to be overridden.""" + + @traceback_utils.filter_traceback + def __call__(cls, *args, **kwargs): + if hasattr(cls, "_variable_call") and callable(cls._variable_call): + variable_call = cls._variable_call(*args, **kwargs) + if variable_call is not None: + return variable_call + return super(VariableMetaclass, cls).__call__(*args, **kwargs) + + +@tf_export("Variable", v1=[]) +# TODO(mdan): This should subclass core.Tensor, and not all its subclasses? +class Variable(trackable.Trackable, metaclass=VariableMetaclass): + """See the [variable guide](https://tensorflow.org/guide/variable). + + A variable maintains shared, persistent state manipulated by a program. + + The `Variable()` constructor requires an initial value for the variable, which + can be a `Tensor` of any type and shape. This initial value defines the type + and shape of the variable. After construction, the type and shape of the + variable are fixed. The value can be changed using one of the assign methods. + + >>> v = tf.Variable(1.) + >>> v.assign(2.) + + >>> v.assign_add(0.5) + + + The `shape` argument to `Variable`'s constructor allows you to construct a + variable with a less defined shape than its `initial_value`: + + >>> v = tf.Variable(1., shape=tf.TensorShape(None)) + >>> v.assign([[1.]]) + dtype=float32, numpy=array([[1.]], ...)> + + Just like any `Tensor`, variables created with `Variable()` can be used as + inputs to operations. Additionally, all the operators overloaded for the + `Tensor` class are carried over to variables. + + >>> w = tf.Variable([[1.], [2.]]) + >>> x = tf.constant([[3., 4.]]) + >>> tf.matmul(w, x) + + >>> tf.sigmoid(w + x) + + + When building a machine learning model it is often convenient to distinguish + between variables holding trainable model parameters and other variables such + as a `step` variable used to count training steps. To make this easier, the + variable constructor supports a `trainable=` + parameter. `tf.GradientTape` watches trainable variables by default: + + >>> with tf.GradientTape(persistent=True) as tape: + ... trainable = tf.Variable(1.) + ... non_trainable = tf.Variable(2., trainable=False) + ... x1 = trainable * 2. + ... x2 = non_trainable * 3. + >>> tape.gradient(x1, trainable) + + >>> assert tape.gradient(x2, non_trainable) is None # Unwatched + + Variables are automatically tracked when assigned to attributes of types + inheriting from `tf.Module`. + + >>> m = tf.Module() + >>> m.v = tf.Variable([1.]) + >>> m.trainable_variables + (,) + + This tracking then allows saving variable values to + [training checkpoints](https://www.tensorflow.org/guide/checkpoint), or to + [SavedModels](https://www.tensorflow.org/guide/saved_model) which include + serialized TensorFlow graphs. + + Variables are often captured and manipulated by `tf.function`s. This works the + same way the un-decorated function would have: + + >>> v = tf.Variable(0.) + >>> read_and_decrement = tf.function(lambda: v.assign_sub(0.1)) + >>> read_and_decrement() + + >>> read_and_decrement() + + + Variables created inside a `tf.function` must be owned outside the function + and be created only once: + + >>> class M(tf.Module): + ... @tf.function + ... def __call__(self, x): + ... if not hasattr(self, "v"): # Or set self.v to None in __init__ + ... self.v = tf.Variable(x) + ... return self.v * x + >>> m = M() + >>> m(2.) + + >>> m(3.) + + >>> m.v + + + See the `tf.function` documentation for details. + """ + + @deprecated_args( + None, "A variable's value can be manually cached by calling " + "tf.Variable.read_value() under a tf.device scope. The caching_device " + "argument does not work properly.", "caching_device") + def __init__(self, + initial_value=None, + trainable=None, + validate_shape=True, + caching_device=None, + name=None, + variable_def=None, + dtype=None, + import_scope=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE, + shape=None, + experimental_enable_variable_lifting=True, + ): + """Creates a new variable with value `initial_value`. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. In + that case, `dtype` must be specified. (Note that initializer functions + from init_ops.py must first be bound to a shape before being used here.) + trainable: If `True`, GradientTapes automatically watch uses of this + variable. Defaults to `True`, unless `synchronization` is set to + `ON_READ`, in which case it defaults to `False`. + validate_shape: If `False`, allows the variable to be initialized with a + value of unknown shape. If `True`, the default, the shape of + `initial_value` must be known. + caching_device: Note: This argument is only valid when using a v1-style + `Session`. Optional device string describing where the Variable should + be cached for reading. Defaults to the Variable's device. If not `None`, + caches on another device. Typical use is to cache on the device where + the Ops using the Variable reside, to deduplicate copying through + `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + variable_def: `VariableDef` protocol buffer. If not `None`, recreates the + Variable object with its contents, referencing the variable's nodes in + the graph, which must already exist. The graph is not changed. + `variable_def` and the other arguments are mutually exclusive. + dtype: If set, initial_value will be converted to the given type. If + `None`, either the datatype will be kept (if `initial_value` is a + Tensor), or `convert_to_tensor` will decide. + import_scope: Optional `string`. Name scope to add to the `Variable.` Only + used when initializing from protocol buffer. + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + synchronization: Indicates when a distributed a variable will be + aggregated. Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + experimental_enable_variable_lifting: Whether to lift the variable out if + it's in a `tf.function`. Default is `True`. When this argument + is `True`, variable creation will follow the behavior and + restrictions described + [here](https://www.tensorflow.org/guide/function#creating_tfvariables). + If this argument is `False`, that description doesn't apply, + and you can freely create and use the variable in the + `tf.function`, as if it's a "mutable `tf.Tensor`". You can't + return the variable though. + + Raises: + ValueError: If both `variable_def` and initial_value are specified. + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + """ + raise NotImplementedError + + def __repr__(self): + raise NotImplementedError + + def value(self): + """Returns the last snapshot of this variable. + + You usually do not need to call this method as all ops that need the value + of the variable call it automatically through a `convert_to_tensor()` call. + + Returns a `Tensor` which holds the value of the variable. You can not + assign a new value to this tensor as it is not a reference to the variable. + + To avoid copies, if the consumer of the returned value is on the same device + as the variable, this actually returns the live value of the variable, not + a copy. Updates to the variable are seen by the consumer. If the consumer + is on a different device it will get a copy of the variable. + + Returns: + A `Tensor` containing the value of the variable. + """ + raise NotImplementedError + + def read_value(self): + """Returns the value of this variable, read in the current context. + + Can be different from value() if it's on another device, with control + dependencies, etc. + + Returns: + A `Tensor` containing the value of the variable. + """ + raise NotImplementedError + + def set_shape(self, shape): + """Overrides the shape for this variable. + + Args: + shape: the `TensorShape` representing the overridden shape. + """ + raise NotImplementedError + + @property + def trainable(self): + raise NotImplementedError + + @property + def synchronization(self): + raise NotImplementedError + + @property + def aggregation(self): + raise NotImplementedError + + def eval(self, session=None): + """In a session, computes and returns the value of this variable. + + This is not a graph construction method, it does not add ops to the graph. + + This convenience method requires a session where the graph + containing this variable has been launched. If no session is + passed, the default session is used. See `tf.compat.v1.Session` for more + information on launching a graph and on sessions. + + ```python + v = tf.Variable([1, 2]) + init = tf.compat.v1.global_variables_initializer() + + with tf.compat.v1.Session() as sess: + sess.run(init) + # Usage passing the session explicitly. + print(v.eval(sess)) + # Usage with the default session. The 'with' block + # above makes 'sess' the default session. + print(v.eval()) + ``` + + Args: + session: The session to use to evaluate this variable. If none, the + default session is used. + + Returns: + A numpy `ndarray` with a copy of the value of this variable. + """ + raise NotImplementedError + + @deprecated( + None, "Use Variable.read_value. Variables in 2.X are initialized " + "automatically both in eager and graph (inside tf.defun) contexts.") + def initialized_value(self): + """Returns the value of the initialized variable. + + You should use this instead of the variable itself to initialize another + variable with a value that depends on the value of this variable. + + ```python + # Initialize 'v' with a random tensor. + v = tf.Variable(tf.random.truncated_normal([10, 40])) + # Use `initialized_value` to guarantee that `v` has been + # initialized before its value is used to initialize `w`. + # The random values are picked only once. + w = tf.Variable(v.initialized_value() * 2.0) + ``` + + Returns: + A `Tensor` holding the value of this variable after its initializer + has run. + """ + raise NotImplementedError + + @property + def initial_value(self): + """Returns the Tensor used as the initial value for the variable. + + Note that this is different from `initialized_value()` which runs + the op that initializes the variable before returning its value. + This method returns the tensor that is used by the op that initializes + the variable. + + Returns: + A `Tensor`. + """ + raise NotImplementedError + + @property + def constraint(self): + """Returns the constraint function associated with this variable. + + Returns: + The constraint function that was passed to the variable constructor. + Can be `None` if no constraint was passed. + """ + raise NotImplementedError + + def assign(self, value, use_locking=False, name=None, read_value=True): + """Assigns a new value to the variable. + + This is essentially a shortcut for `assign(self, value)`. + + Args: + value: A `Tensor`. The new value for this variable. + use_locking: If `True`, use locking during the assignment. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + The updated variable. If `read_value` is false, instead returns None in + Eager mode and the assign op in graph mode. + """ + raise NotImplementedError + + def assign_add(self, delta, use_locking=False, name=None, read_value=True): + """Adds a value to this variable. + + This is essentially a shortcut for `assign_add(self, delta)`. + + Args: + delta: A `Tensor`. The value to add to this variable. + use_locking: If `True`, use locking during the operation. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + The updated variable. If `read_value` is false, instead returns None in + Eager mode and the assign op in graph mode. + """ + raise NotImplementedError + + def assign_sub(self, delta, use_locking=False, name=None, read_value=True): + """Subtracts a value from this variable. + + This is essentially a shortcut for `assign_sub(self, delta)`. + + Args: + delta: A `Tensor`. The value to subtract from this variable. + use_locking: If `True`, use locking during the operation. + name: The name of the operation to be created + read_value: if True, will return something which evaluates to the new + value of the variable; if False will return the assign op. + + Returns: + The updated variable. If `read_value` is false, instead returns None in + Eager mode and the assign op in graph mode. + """ + raise NotImplementedError + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + """Subtracts `tf.IndexedSlices` from this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be subtracted from this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + """Adds `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be added to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the max of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of max with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + """Updates this variable with the min of `tf.IndexedSlices` and itself. + + Args: + sparse_delta: `tf.IndexedSlices` to use as an argument of min with this + variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + """Multiply this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to multiply this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + """Divide this variable by `tf.IndexedSlices`. + + Args: + sparse_delta: `tf.IndexedSlices` to divide this variable by. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + """Assigns `tf.IndexedSlices` to this variable batch-wise. + + Analogous to `batch_gather`. This assumes that this variable and the + sparse_delta IndexedSlices have a series of leading dimensions that are the + same for all of them, and the updates are performed on the last dimension of + indices. In other words, the dimensions should be the following: + + `num_prefix_dims = sparse_delta.indices.ndims - 1` + `batch_dim = num_prefix_dims + 1` + `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[ + batch_dim:]` + + where + + `sparse_delta.updates.shape[:num_prefix_dims]` + `== sparse_delta.indices.shape[:num_prefix_dims]` + `== var.shape[:num_prefix_dims]` + + And the operation performed can be expressed as: + + `var[i_1, ..., i_n, + sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[ + i_1, ..., i_n, j]` + + When sparse_delta.indices is a 1D tensor, this operation is equivalent to + `scatter_update`. + + To avoid this operation one can looping over the first `ndims` of the + variable and using `scatter_update` on the subtensors that result of slicing + the first dimension. This is a valid option for `ndims = 1`, but less + efficient than this implementation. + + Args: + sparse_delta: `tf.IndexedSlices` to be assigned to this variable. + use_locking: If `True`, use locking during the operation. + name: the name of the operation. + + Returns: + The updated variable. + + Raises: + TypeError: if `sparse_delta` is not an `IndexedSlices`. + """ + raise NotImplementedError + + def scatter_nd_sub(self, indices, updates, name=None): + """Applies sparse subtraction to individual values or slices in a Variable. + + Assuming the variable has rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into self. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of self. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + v.scatter_nd_sub(indices, updates) + print(v) + ``` + + After the update `v` would look like this: + + [1, -9, 3, -6, -4, 6, 7, -4] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + raise NotImplementedError + + def scatter_nd_add(self, indices, updates, name=None): + """Applies sparse addition to individual values or slices in a Variable. + + The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into self. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of self. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + v.scatter_nd_add(indices, updates) + print(v) + ``` + + The resulting update to v would look like this: + + [1, 13, 3, 14, 14, 6, 7, 20] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + raise NotImplementedError + + def scatter_nd_update(self, indices, updates, name=None): + """Applies sparse assignment to individual values or slices in a Variable. + + The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`. + + `indices` must be integer tensor, containing indices into self. + It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`. + + The innermost dimension of `indices` (with length `K`) corresponds to + indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th + dimension of self. + + `updates` is `Tensor` of rank `Q-1+P-K` with shape: + + ``` + [d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]]. + ``` + + For example, say we want to add 4 scattered elements to a rank-1 tensor to + 8 elements. In Python, that update would look like this: + + ```python + v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) + indices = tf.constant([[4], [3], [1] ,[7]]) + updates = tf.constant([9, 10, 11, 12]) + v.scatter_nd_update(indices, updates) + print(v) + ``` + + The resulting update to v would look like this: + + [1, 11, 3, 10, 9, 6, 7, 12] + + See `tf.scatter_nd` for more details about how to make updates to + slices. + + Args: + indices: The indices to be used in the operation. + updates: The values to be used in the operation. + name: the name of the operation. + + Returns: + The updated variable. + """ + raise NotImplementedError + + def sparse_read(self, indices, name=None): + r"""Gather slices from params axis axis according to indices. + + This function supports a subset of tf.gather, see tf.gather for details on + usage. + + Args: + indices: The index `Tensor`. Must be one of the following types: `int32`, + `int64`. Must be in range `[0, params.shape[axis])`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + raise AttributeError + + def gather_nd(self, indices, name=None): + r"""Gather slices from `params` into a Tensor with shape specified by `indices`. + + See tf.gather_nd for details. + + Args: + indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. + Index tensor. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `params`. + """ + raise AttributeError + + @deprecated(None, "Prefer Dataset.range instead.") + def count_up_to(self, limit): + """Increments this variable until it reaches `limit`. + + When that Op is run it tries to increment the variable by `1`. If + incrementing the variable would bring it above `limit` then the Op raises + the exception `OutOfRangeError`. + + If no error is raised, the Op outputs the value of the variable before + the increment. + + This is essentially a shortcut for `count_up_to(self, limit)`. + + Args: + limit: value at which incrementing the variable raises an error. + + Returns: + A `Tensor` that will hold the variable value before the increment. If no + other Op modifies this variable, the values produced will all be + distinct. + """ + raise NotImplementedError + + @deprecated(None, + "Prefer Variable.assign which has equivalent behavior in 2.X.") + def load(self, value, session=None): + """Load new value into this variable. + + Writes new value to variable's memory. Doesn't add ops to the graph. + + This convenience method requires a session where the graph + containing this variable has been launched. If no session is + passed, the default session is used. See `tf.compat.v1.Session` for more + information on launching a graph and on sessions. + + ```python + v = tf.Variable([1, 2]) + init = tf.compat.v1.global_variables_initializer() + + with tf.compat.v1.Session() as sess: + sess.run(init) + # Usage passing the session explicitly. + v.load([2, 3], sess) + print(v.eval(sess)) # prints [2 3] + # Usage with the default session. The 'with' block + # above makes 'sess' the default session. + v.load([3, 4], sess) + print(v.eval()) # prints [3 4] + ``` + + Args: + value: New variable value + session: The session to use to evaluate this variable. If none, the + default session is used. + + Raises: + ValueError: Session is not passed and no default session + """ + if context.executing_eagerly(): + self.assign(value) + else: + session = session or ops.get_default_session() + if session is None: + raise ValueError( + "Either session argument should be provided or default session " + "should be established") + session.run(self.initializer, {self.initializer.inputs[1]: value}) + + # Conversion to tensor. + @staticmethod + def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name + """Utility function for converting a Variable to a Tensor.""" + _ = name + if dtype and not dtype.is_compatible_with(v.dtype): + raise ValueError( + f"Incompatible type conversion requested to type '{dtype.name}' for " + f"variable of type '{v.dtype.name}' (Variable: {v}).") + if as_ref: + return v._ref() # pylint: disable=protected-access + else: + return v.value() + + @classmethod + def _OverloadAllOperators(cls): # pylint: disable=invalid-name + """Register overloads for all operators.""" + for operator in tensor_lib.Tensor.OVERLOADABLE_OPERATORS: + cls._OverloadOperator(operator) + # For slicing, bind getitem differently than a tensor (use SliceHelperVar + # instead) + # pylint: disable=protected-access + setattr(cls, "__getitem__", array_ops._SliceHelperVar) + + @classmethod + def _OverloadOperator(cls, operator): # pylint: disable=invalid-name + """Defer an operator overload to `tensor_lib.Tensor`. + + We pull the operator out of tensor_lib.Tensor dynamically to avoid ordering + issues. + + Args: + operator: string. The operator name. + """ + # We can't use the overload mechanism on __eq__ & __ne__ since __eq__ is + # called when adding a variable to sets. As a result we call a.value() which + # causes infinite recursion when operating within a GradientTape + # TODO(gjn): Consider removing this + if operator == "__eq__" or operator == "__ne__": + return + + tensor_oper = getattr(tensor_lib.Tensor, operator) + + def _run_op(a, *args, **kwargs): + # pylint: disable=protected-access + return tensor_oper(a.value(), *args, **kwargs) + + functools.update_wrapper(_run_op, tensor_oper) + setattr(cls, operator, _run_op) + + def __hash__(self): + if ( + tensor_lib.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + ): # pylint: disable=protected-access + raise TypeError( + "Variable is unhashable. " + f"Instead, use variable.ref() as the key. (Variable: {self})" + ) + else: + return id(self) + + # TODO(gjn): duplicate of math_ops.tensor_equals, consider removing + def __eq__(self, other): + """Compares two variables element-wise for equality.""" + if ( + tensor_lib.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + ): # pylint: disable=protected-access + return gen_math_ops.equal(self, other, incompatible_shape_error=False) + else: + # In legacy graph mode, tensor equality is object equality + return self is other + + # TODO(gjn): duplicate of math_ops.tensor_not_equals, consider removing + def __ne__(self, other): + """Compares two variables element-wise for equality.""" + if ( + tensor_lib.Tensor._USE_EQUALITY + and ops.executing_eagerly_outside_functions() + ): # pylint: disable=protected-access + return gen_math_ops.not_equal(self, other, incompatible_shape_error=False) + else: + # In legacy graph mode, tensor equality is object equality + return self is not other + + def __iter__(self): + """When executing eagerly, iterates over the value of the variable.""" + return iter(self.read_value()) + + # NOTE(mrry): This enables the Variable's overloaded "right" binary + # operators to run when the left operand is an ndarray, because it + # accords the Variable class higher priority than an ndarray, or a + # numpy matrix. + # TODO(mrry): Convert this to using numpy's __numpy_ufunc__ + # mechanism, which allows more control over how Variables interact + # with ndarrays. + __array_priority__ = 100 + + @property + def name(self): + """The name of this variable.""" + raise NotImplementedError + + @property + def _shared_name(self): + """The shared name of the variable. + + Unlike name(), shared_name doesn't have ":0" suffix. It is user-specified + name with name scope prefix. + + Returns: + variable name. + """ + return self.name[:self.name.index(":")] + + @property + def initializer(self): + """The initializer operation for this variable.""" + raise NotImplementedError + + @property + def device(self): + """The device of this variable.""" + raise NotImplementedError + + @property + def dtype(self): + """The `DType` of this variable.""" + raise NotImplementedError + + @property + def op(self): + """The `Operation` of this variable.""" + raise NotImplementedError + + @property + def graph(self): + """The `Graph` of this variable.""" + raise NotImplementedError + + @property + def shape(self): + """The `TensorShape` of this variable. + + Returns: + A `TensorShape`. + """ + raise NotImplementedError + + def get_shape(self) -> tensor_shape.TensorShape: + """Alias of `Variable.shape`.""" + return self.shape + + def _gather_saveables_for_checkpoint(self): + """For implementing `Trackable`. This object is saveable on its own.""" + return {trackable.VARIABLE_VALUE_KEY: self} + + def to_proto(self, export_scope=None): + """Converts a `Variable` to a `VariableDef` protocol buffer. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `VariableDef` protocol buffer, or `None` if the `Variable` is not + in the specified name scope. + """ + raise NotImplementedError + + @staticmethod + def from_proto(variable_def, import_scope=None): + """Returns a `Variable` object created from `variable_def`.""" + raise NotImplementedError + + def _set_save_slice_info(self, save_slice_info): + """Sets the slice info for this `Variable`. + + Args: + save_slice_info: A `Variable.SaveSliceInfo` object. + """ + self._save_slice_info = save_slice_info + + def _get_save_slice_info(self): + return self._save_slice_info + + @deprecated(None, "Use ref() instead.") + def experimental_ref(self): + return self.ref() + + def ref(self): + # tf.Tensor also has the same ref() API. If you update the + # documentation here, please update tf.Tensor.ref() as well. + """Returns a hashable reference object to this Variable. + + The primary use case for this API is to put variables in a set/dictionary. + We can't put variables in a set/dictionary as `variable.__hash__()` is no + longer available starting Tensorflow 2.0. + + The following will raise an exception starting 2.0 + + >>> x = tf.Variable(5) + >>> y = tf.Variable(10) + >>> z = tf.Variable(10) + >>> variable_set = {x, y, z} + Traceback (most recent call last): + ... + TypeError: Variable is unhashable. Instead, use tensor.ref() as the key. + >>> variable_dict = {x: 'five', y: 'ten'} + Traceback (most recent call last): + ... + TypeError: Variable is unhashable. Instead, use tensor.ref() as the key. + + Instead, we can use `variable.ref()`. + + >>> variable_set = {x.ref(), y.ref(), z.ref()} + >>> x.ref() in variable_set + True + >>> variable_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'} + >>> variable_dict[y.ref()] + 'ten' + + Also, the reference object provides `.deref()` function that returns the + original Variable. + + >>> x = tf.Variable(5) + >>> x.ref().deref() + + """ + return object_identity.Reference(self) + + @classmethod + def _variable_call( + cls, + initial_value=None, + trainable=None, + validate_shape=True, + caching_device=None, + name=None, + variable_def=None, + dtype=None, + import_scope=None, + constraint=None, + synchronization=VariableSynchronization.AUTO, + aggregation=VariableAggregation.NONE, + shape=None, + experimental_enable_variable_lifting=None, + **kwargs, + ): + """Variable class getter. Useful to force the signature.""" + if cls is not Variable: + return None + previous_getter = lambda **kws: default_variable_creator_v2(None, **kws) + for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access + previous_getter = _make_getter(getter, previous_getter) + + # Reset `aggregation` that is explicitly set as `None` to the enum NONE. + if aggregation is None: + aggregation = VariableAggregation.NONE + return previous_getter( + initial_value=initial_value, + trainable=trainable, + validate_shape=validate_shape, + caching_device=caching_device, + name=name, + variable_def=variable_def, + dtype=dtype, + import_scope=import_scope, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + shape=shape, + experimental_enable_variable_lifting=experimental_enable_variable_lifting, + **kwargs + ) + + class SaveSliceInfo: + """Information on how to save this Variable as a slice. + + Provides internal support for saving variables as slices of a larger + variable. This API is not public and is subject to change. + + Available properties: + + * full_name + * full_shape + * var_offset + * var_shape + """ + + def __init__(self, + full_name=None, + full_shape=None, + var_offset=None, + var_shape=None, + save_slice_info_def=None, + import_scope=None): + """Create a `SaveSliceInfo`. + + Args: + full_name: Name of the full variable of which this `Variable` is a + slice. + full_shape: Shape of the full variable, as a list of int. + var_offset: Offset of this `Variable` into the full variable, as a list + of int. + var_shape: Shape of this `Variable`, as a list of int. + save_slice_info_def: `SaveSliceInfoDef` protocol buffer. If not `None`, + recreates the SaveSliceInfo object its contents. `save_slice_info_def` + and other arguments are mutually exclusive. + import_scope: Optional `string`. Name scope to add. Only used when + initializing from protocol buffer. + """ + if save_slice_info_def: + assert isinstance(save_slice_info_def, variable_pb2.SaveSliceInfoDef) + self.full_name = ops.prepend_name_scope( + save_slice_info_def.full_name, import_scope=import_scope) + self.full_shape = list(save_slice_info_def.full_shape) + self.var_offset = list(save_slice_info_def.var_offset) + self.var_shape = list(save_slice_info_def.var_shape) + else: + self.full_name = full_name + self.full_shape = full_shape + self.var_offset = var_offset + self.var_shape = var_shape + + @property + def spec(self): + """Computes the spec string used for saving.""" + full_shape_str = " ".join("%d" % d for d in self.full_shape) + " " + sl_spec = ":".join( + "%d,%d" % (o, s) for o, s in zip(self.var_offset, self.var_shape)) + return full_shape_str + sl_spec + + def to_proto(self, export_scope=None): + """Returns a SaveSliceInfoDef() proto. + + Args: + export_scope: Optional `string`. Name scope to remove. + + Returns: + A `SaveSliceInfoDef` protocol buffer, or None if the `Variable` is not + in the specified name scope. + """ + if (export_scope is None or self.full_name.startswith(export_scope)): + save_slice_info_def = variable_pb2.SaveSliceInfoDef() + save_slice_info_def.full_name = ops.strip_name_scope( + self.full_name, export_scope) + for i in self.full_shape: + save_slice_info_def.full_shape.append(i) + for i in self.var_offset: + save_slice_info_def.var_offset.append(i) + for i in self.var_shape: + save_slice_info_def.var_shape.append(i) + return save_slice_info_def + else: + return None + + +Variable._OverloadAllOperators() # pylint: disable=protected-access +_pywrap_utils.RegisterType("Variable", Variable) + + +def _try_guard_against_uninitialized_dependencies(name, initial_value): + """Attempt to guard against dependencies on uninitialized variables. + + Replace references to variables in `initial_value` with references to the + variable's initialized values. The initialized values are essentially + conditional TensorFlow graphs that return a variable's value if it is + initialized or its `initial_value` if it hasn't been initialized. This + replacement is done on a best effort basis: + + - If the `initial_value` graph contains cycles, we don't do any + replacements for that graph. + - If the variables that `initial_value` depends on are not present in the + `GLOBAL_VARIABLES` or `LOCAL_VARIABLES` we don't replace them. + + In these cases, it is up to the caller to ensure that the `initial_value` + graph uses initialized variables or that they guard access to variables + using their `initialized_value` method. + + Args: + name: Variable name. + initial_value: `Tensor`. The initial value. + + Returns: + A `Tensor` suitable to initialize a variable. + Raises: + TypeError: If `initial_value` is not a `Tensor`. + """ + if not isinstance(initial_value, tensor_lib.Tensor): + raise TypeError("initial_value needs to be a Tensor: %s" % initial_value) + + # Don't modify initial_value if it contains any cyclic dependencies. + if _has_cycle(initial_value.op, state={}): + return initial_value + return _safe_initial_value_from_tensor(name, initial_value, op_cache={}) + + +_UNKNOWN, _STARTED, _FINISHED = range(3) + + +def _has_cycle(op, state): + """Detect cycles in the dependencies of `initial_value`.""" + op_state = state.get(op.name, _UNKNOWN) + if op_state == _STARTED: + return True + elif op_state == _FINISHED: + return False + + state[op.name] = _STARTED + for i in itertools.chain((i.op for i in op.inputs), op.control_inputs): + if _has_cycle(i, state): + return True + state[op.name] = _FINISHED + return False + + +def _safe_initial_value_from_tensor(name, tensor, op_cache): + """Replace dependencies on variables with their initialized values. + + Args: + name: Variable name. + tensor: A `Tensor`. The tensor to replace. + op_cache: A dict mapping operation names to `Operation`s. Used to memoize + the results so as to avoid creating redundant operations. + + Returns: + A `Tensor` compatible with `tensor`. Any inputs that lead to variable + values will be replaced with a corresponding graph that uses the + variable's initialized values. This is done on a best-effort basis. If no + modifications need to be made then `tensor` will be returned unchanged. + """ + op = tensor.op + new_op = op_cache.get(op.name) + if new_op is None: + new_op = _safe_initial_value_from_op(name, op, op_cache) + op_cache[op.name] = new_op + return new_op.outputs[tensor.value_index] + + +def _safe_initial_value_from_op(name, op, op_cache): + """Replace dependencies on variables with their initialized values. + + Args: + name: Variable name. + op: An `Operation`. The operation to replace. + op_cache: A dict mapping operation names to `Operation`s. Used to memoize + the results so as to avoid creating redundant operations. + + Returns: + An `Operation` compatible with `op`. Any inputs that lead to variable + values will be replaced with a corresponding graph that uses the + variable's initialized values. This is done on a best-effort basis. If no + modifications need to be made then `op` will be returned unchanged. + """ + op_type = op.node_def.op + if op_type in ("IsVariableInitialized", "VarIsInitializedOp", + "ReadVariableOp", "If"): + return op + + # Attempt to find the initialized_value of any variable reference / handles. + # TODO(b/70206927): Fix handling of ResourceVariables. + if op_type in ("Variable", "VariableV2", "VarHandleOp"): + initialized_value = _find_initialized_value_for_variable(op) + return op if initialized_value is None else initialized_value.op + + # Recursively build initializer expressions for inputs. + modified = False + new_op_inputs = [] + for op_input in op.inputs: + new_op_input = _safe_initial_value_from_tensor(name, op_input, op_cache) + new_op_inputs.append(new_op_input) + modified = modified or (new_op_input != op_input) + + # If at least one input was modified, replace the op. + if modified: + new_op_type = op_type + if new_op_type == "RefSwitch": + new_op_type = "Switch" + new_op_name = op.node_def.name + "_" + name + new_op_name = new_op_name.replace(":", "_") + return op.graph.create_op( + new_op_type, + new_op_inputs, + op._output_types, # pylint: disable=protected-access + name=new_op_name, + attrs=op.node_def.attr) + + return op + + +def _find_initialized_value_for_variable(variable_op): + """Find the initialized value for a variable op. + + To do so, lookup the variable op in the variables collection. + + Args: + variable_op: A variable `Operation`. + + Returns: + A `Tensor` representing the initialized value for the variable or `None` + if the initialized value could not be found. + """ + try: + var_names = [variable_op.node_def.name, variable_op.node_def.name + ":0"] + for collection_name in (ops.GraphKeys.GLOBAL_VARIABLES, + ops.GraphKeys.LOCAL_VARIABLES): + for var in variable_op.graph.get_collection(collection_name): + if var.name in var_names: + return var.initialized_value() + except AttributeError: + # Return None when an incomplete user-defined variable type was put in + # the collection. + return None + return None + + +class PartitionedVariable: + """A container for partitioned `Variable` objects. + + @compatibility(eager) `tf.PartitionedVariable` is not compatible with + eager execution. Use `tf.Variable` instead which is compatible + with both eager execution and graph construction. See [the + TensorFlow Eager Execution + guide](https://www.tensorflow.org/guide/eager#variables_and_optimizers) + for details on how variables work in eager execution. + @end_compatibility + """ + + def __init__(self, name, shape, dtype, variable_list, partitions): + """Creates a new partitioned variable wrapper. + + Variables passed via the variable_list must contain a save_slice_info + field. Concatenation and iteration is in lexicographic order according + to the var_offset property of the save_slice_info. + + Args: + name: String. Overall name of the variables. + shape: List of integers. Overall shape of the variables. + dtype: Type of the variables. + variable_list: List of `Variable` that comprise this partitioned variable. + partitions: List of integers. Number of partitions for each dimension. + + Raises: + TypeError: If `variable_list` is not a list of `Variable` objects, or + `partitions` is not a list. + ValueError: If `variable_list` is empty, or the `Variable` shape + information does not match `shape`, or `partitions` has invalid values. + """ + if not isinstance(variable_list, (list, tuple)): + raise TypeError("variable_list is not a list or tuple: %s" % + variable_list) + if not isinstance(partitions, (list, tuple)): + raise TypeError("partitions is not a list or tuple: %s" % partitions) + if not all(p >= 1 for p in partitions): + raise ValueError("partition values must be positive: %s" % partitions) + if not variable_list: + raise ValueError("variable_list may not be empty") + # pylint: disable=protected-access + for v in variable_list: + # Sort the variable_list lexicographically according to var offset value. + if not all(v._get_save_slice_info() is not None for v in variable_list): + raise ValueError( + "All variables must have a save_slice_info available: %s" % + [v.name for v in variable_list]) + if len(shape) != len(partitions): + raise ValueError("len(shape) != len(partitions): %s vs. %s" % + (shape, partitions)) + if v._get_save_slice_info().full_shape != shape: + raise ValueError("All variables' full shapes must match shape: %s; " + "but full shapes were: %s" % + (shape, str([v._get_save_slice_info().full_shape]))) + self._variable_list = sorted( + variable_list, key=lambda v: v._get_save_slice_info().var_offset) + # pylint: enable=protected-access + + self._name = name + self._shape = shape + self._dtype = dtype + self._partitions = partitions + self._as_tensor = None + + def __iter__(self): + """Return an iterable for accessing the underlying partition Variables.""" + return iter(self._variable_list) + + def __len__(self): + num_partition_axes = len(self._partition_axes()) + if num_partition_axes > 1: + raise ValueError("Cannot get a length for %d > 1 partition axes" % + num_partition_axes) + return len(self._variable_list) + + def _partition_axes(self): + if all(p == 1 for p in self._partitions): + return [0] + else: + return [i for i, p in enumerate(self._partitions) if p > 1] + + def _concat(self): + """Returns the overall concatenated value as a `Tensor`. + + This is different from using the partitioned variable directly as a tensor + (through tensor conversion and `as_tensor`) in that it creates a new set of + operations that keeps the control dependencies from its scope. + + Returns: + `Tensor` containing the concatenated value. + """ + if len(self._variable_list) == 1: + with ops.name_scope(None): + return array_ops.identity(self._variable_list[0], name=self._name) + + partition_axes = self._partition_axes() + + if len(partition_axes) > 1: + raise NotImplementedError( + "Cannot concatenate along more than one dimension: %s. " + "Multi-axis partition concat is not supported" % str(partition_axes)) + partition_ix = partition_axes[0] + + with ops.name_scope(self._name + "/ConcatPartitions/"): + concatenated = array_ops.concat(self._variable_list, partition_ix) + + with ops.name_scope(None): + return array_ops.identity(concatenated, name=self._name) + + def as_tensor(self): + """Returns the overall concatenated value as a `Tensor`. + + The returned tensor will not inherit the control dependencies from the scope + where the value is used, which is similar to getting the value of + `Variable`. + + Returns: + `Tensor` containing the concatenated value. + """ + with ops.control_dependencies(None): + return self._concat() + + @staticmethod + def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): + # pylint: disable=invalid-name + _ = name + if dtype is not None and not dtype.is_compatible_with(v.dtype): + raise ValueError( + "Incompatible type conversion requested to type '%s' for variable " + "of type '%s'" % (dtype.name, v.dtype.name)) + if as_ref: + raise NotImplementedError( + "PartitionedVariable doesn't support being used as a reference.") + else: + return v.as_tensor() + + @property + def name(self): + return self._name + + @property + def dtype(self): + return self._dtype + + @property + def shape(self): + return self.get_shape() + + @property + def _distribute_strategy(self): + """The `tf.distribute.Strategy` that this variable was created under.""" + # NOTE(yuefengz): Today, no partitioned variables in a distribute strategy. + return None + + def get_shape(self) -> tensor_shape.TensorShape: + return self._shape + + def _get_variable_list(self): + return self._variable_list + + def _get_partitions(self): + return self._partitions + + def _apply_assign_fn(self, assign_fn, value): + partition_axes = self._partition_axes() + if len(partition_axes) > 1: + raise NotImplementedError( + "Cannot do assign action along more than one dimension: %s. " + "Multi-axis partition assign action is not supported " % + str(partition_axes)) + if isinstance(value, list): + assert len(value) == len(self._variable_list) + value_list = value + elif isinstance(value, PartitionedVariable): + value_list = list(value) + else: + partition_ix = partition_axes[0] + size_splits_list = [ + tensor_shape.dimension_value(var.shape[partition_ix]) + for var in self._variable_list + ] + value_list = array_ops.split(value, size_splits_list, axis=partition_ix) + + op_list = [ + assign_fn(var, value_list[idx]) + for idx, var in enumerate(self._variable_list) + ] + return op_list + + def assign(self, value, use_locking=False, name=None, read_value=True): + assign_fn = lambda var, r_value: var.assign( + r_value, use_locking=use_locking, name=name, read_value=read_value) + assign_list = self._apply_assign_fn(assign_fn, value) + if read_value: + return assign_list + return [assign.op for assign in assign_list] + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + assign_fn = lambda var, r_value: var.assign_add( + r_value, use_locking=use_locking, name=name, read_value=read_value) + assign_list = self._apply_assign_fn(assign_fn, value) + if read_value: + return assign_list + return [assign.op for assign in assign_list] + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + assign_fn = lambda var, r_value: var.assign_sub( + r_value, use_locking=use_locking, name=name, read_value=read_value) + assign_list = self._apply_assign_fn(assign_fn, value) + if read_value: + return assign_list + return [assign.op for assign in assign_list] + + +@tf_export(v1=["global_variables"]) +def global_variables(scope=None): + """Returns global variables. + + Global variables are variables that are shared across machines in a + distributed environment. The `Variable()` constructor or `get_variable()` + automatically adds new variables to the graph collection + `GraphKeys.GLOBAL_VARIABLES`. + This convenience function returns the contents of that collection. + + An alternative to global variables are local variables. See + `tf.compat.v1.local_variables` + + @compatibility(TF2) + Not compatible with eager execution and `tf.function`. In particular, Graph + collections are deprecated in TF2. Instead please create a + [tf.Module](https://www.tensorflow.org/guide/intro_to_modules) + container for all your model state, including variables. + You can then list all the variables in your `tf.Module` through the + `variables` attribute. + @end_compatibility + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of `Variable` objects. + """ + return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope) + + +@tf_export(v1=["all_variables"]) +@deprecated("2017-03-02", "Please use tf.global_variables instead.") +def all_variables(): + """Use `tf.compat.v1.global_variables` instead.""" + return global_variables() + + +def _all_saveable_objects(scope=None): + """Returns all variables and `SaveableObject`s that must be checkpointed. + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of `Variable` and `SaveableObject` to be checkpointed + """ + # TODO(andreasst): make this function public once things are settled. + return (ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope) + + ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS, scope)) + + +@tf_export(v1=["local_variables"]) +def local_variables(scope=None): + """Returns local variables. + + Local variables - per process variables, usually not saved/restored to + checkpoint and used for temporary or intermediate values. + For example, they can be used as counters for metrics computation or + number of epochs this machine has read data. + The `tf.contrib.framework.local_variable()` function automatically adds the + new variable to `GraphKeys.LOCAL_VARIABLES`. + This convenience function returns the contents of that collection. + + An alternative to local variables are global variables. See + `tf.compat.v1.global_variables` + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of local `Variable` objects. + """ + return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, scope) + + +@tf_export(v1=["model_variables"]) +def model_variables(scope=None): + """Returns all variables in the MODEL_VARIABLES collection. + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of local Variable objects. + """ + return ops.get_collection(ops.GraphKeys.MODEL_VARIABLES, scope) + + +@tf_export(v1=["trainable_variables"]) +def trainable_variables(scope=None): + """Returns all variables created with `trainable=True`. + + When passed `trainable=True`, the `Variable()` constructor automatically + adds new variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES`. This convenience function returns the + contents of that collection. + + @compatibility(TF2) + Not compatible with eager execution and `tf.function`. In particular, Graph + collections are deprecated in TF2. Instead please create a `tf.Module` + container for all your model state, including variables. + You can then list all the trainable variables in your `tf.Module` through the + `trainable_variables` attribute. + @end_compatibility + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of Variable objects. + """ + return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES, scope) + + +@tf_export(v1=["moving_average_variables"]) +def moving_average_variables(scope=None): + """Returns all variables that maintain their moving averages. + + If an `ExponentialMovingAverage` object is created and the `apply()` + method is called on a list of variables, these variables will + be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection. + This convenience function returns the contents of that collection. + + Args: + scope: (Optional.) A string. If supplied, the resulting list is filtered to + include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a scope + is supplied. The choice of `re.match` means that a `scope` without special + tokens filters by prefix. + + Returns: + A list of Variable objects. + """ + return ops.get_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, scope) + + +@tf_export(v1=["initializers.variables", "variables_initializer"]) +def variables_initializer(var_list, name="init"): + """Returns an Op that initializes a list of variables. + + After you launch the graph in a session, you can run the returned Op to + initialize all the variables in `var_list`. This Op runs all the + initializers of the variables in `var_list` in parallel. + + Calling `initialize_variables()` is equivalent to passing the list of + initializers to `Group()`. + + If `var_list` is empty, however, the function still returns an Op that can + be run. That Op just has no effect. + + @compatibility(TF2) + In TF2, variables are initialized immediately when they are created. There is + no longer a need to run variable initializers before using them. + @end_compatibility + + Args: + var_list: List of `Variable` objects to initialize. + name: Optional name for the returned operation. + + Returns: + An Op that run the initializers of all the specified variables. + """ + if var_list and not context.executing_eagerly(): + return control_flow_ops.group(*[v.initializer for v in var_list], name=name) + return control_flow_ops.no_op(name=name) + + +@tf_export(v1=["initialize_variables"]) +@tf_should_use.should_use_result +@deprecated("2017-03-02", "Use `tf.variables_initializer` instead.") +def initialize_variables(var_list, name="init"): + """See `tf.compat.v1.variables_initializer`.""" + return variables_initializer(var_list, name=name) + + +@tf_export(v1=["initializers.global_variables", "global_variables_initializer"]) +def global_variables_initializer(): + """Returns an Op that initializes global variables. + + This is just a shortcut for `variables_initializer(global_variables())` + + @compatibility(TF2) + In TF2, variables are initialized immediately when they are created. There is + no longer a need to run variable initializers before using them. + @end_compatibility + + Returns: + An Op that initializes global variables in the graph. + """ + if context.executing_eagerly(): + return control_flow_ops.no_op(name="global_variables_initializer") + return variables_initializer(global_variables()) + + +@tf_export(v1=["initialize_all_variables"]) +@tf_should_use.should_use_result +@deprecated("2017-03-02", "Use `tf.global_variables_initializer` instead.") +def initialize_all_variables(): + """See `tf.compat.v1.global_variables_initializer`.""" + return global_variables_initializer() + + +@tf_export(v1=["initializers.local_variables", "local_variables_initializer"]) +def local_variables_initializer(): + """Returns an Op that initializes all local variables. + + This is just a shortcut for `variables_initializer(local_variables())` + + @compatibility(TF2) + In TF2, variables are initialized immediately when they are created. There is + no longer a need to run variable initializers before using them. + @end_compatibility + + Returns: + An Op that initializes all local variables in the graph. + """ + if context.executing_eagerly(): + return control_flow_ops.no_op(name="local_variables_initializer") + return variables_initializer(local_variables()) + + +@tf_export(v1=["initialize_local_variables"]) +@tf_should_use.should_use_result +@deprecated("2017-03-02", "Use `tf.local_variables_initializer` instead.") +def initialize_local_variables(): + """See `tf.compat.v1.local_variables_initializer`.""" + return local_variables_initializer() + + +@tf_export(v1=["assert_variables_initialized"]) +@tf_should_use.should_use_result +def assert_variables_initialized(var_list=None): + """Returns an Op to check if variables are initialized. + + NOTE: This function is obsolete and will be removed in 6 months. Please + change your implementation to use `report_uninitialized_variables()`. + + When run, the returned Op will raise the exception `FailedPreconditionError` + if any of the variables has not yet been initialized. + + Note: This function is implemented by trying to fetch the values of the + variables. If one of the variables is not initialized a message may be + logged by the C++ runtime. This is expected. + + Args: + var_list: List of `Variable` objects to check. Defaults to the value of + `global_variables().` + + Returns: + An Op, or None if there are no variables. + """ + if var_list is None: + var_list = global_variables() + local_variables() + # Backwards compatibility for old-style variables. TODO(touts): remove. + if not var_list: + var_list = [] + for op in ops.get_default_graph().get_operations(): + if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]: + var_list.append(op.outputs[0]) + if not var_list: + return None + else: + ranks = [] + for var in var_list: + with ops.colocate_with(var.op): + ranks.append(array_ops.rank_internal(var, optimize=False)) + if len(ranks) == 1: + return ranks[0] + else: + return array_ops_stack.stack(ranks) + + +@tf_export(v1=["report_uninitialized_variables"]) +@tf_should_use.should_use_result +def report_uninitialized_variables(var_list=None, + name="report_uninitialized_variables"): + """Adds ops to list the names of uninitialized variables. + + When run, it returns a 1-D tensor containing the names of uninitialized + variables if there are any, or an empty array if there are none. + + Args: + var_list: List of `Variable` objects to check. Defaults to the value of + `global_variables() + local_variables()` + name: Optional name of the `Operation`. + + Returns: + A 1-D tensor containing names of the uninitialized variables, or an empty + 1-D tensor if there are no variables or no uninitialized variables. + """ + if var_list is None: + var_list = global_variables() + local_variables() + # Backwards compatibility for old-style variables. TODO(touts): remove. + if not var_list: + var_list = [] + for op in ops.get_default_graph().get_operations(): + if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]: + var_list.append(op.outputs[0]) + with ops.name_scope(name): + # Run all operations on CPU + if var_list: + init_vars = [state_ops.is_variable_initialized(v) for v in var_list] + local_device = os.environ.get( + "TF_DEVICE_FOR_UNINITIALIZED_VARIABLE_REPORTING", "/cpu:0") + with ops.device(local_device): + if not var_list: + # Return an empty tensor so we only need to check for returned tensor + # size being 0 as an indication of model ready. + return array_ops.constant([], dtype=dtypes.string) + else: + # Get a 1-D boolean tensor listing whether each variable is initialized. + variables_mask = math_ops.logical_not(array_ops_stack.stack(init_vars)) + # Get a 1-D string tensor containing all the variable names. + variable_names_tensor = array_ops.constant( + [s.op.name for s in var_list]) + # Return a 1-D tensor containing all the names of + # uninitialized variables. + return array_ops.boolean_mask(variable_names_tensor, variables_mask) + + +tensor_conversion_registry.register_tensor_conversion_function( + PartitionedVariable, PartitionedVariable._TensorConversionFunction) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..eed1c073ee21c624c4cc770ed087fbd3a69af35e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_ops.py @@ -0,0 +1,603 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Support for WeakTensor in TF ops.""" + +import inspect + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import flexible_dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import weak_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_bitwise_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops.numpy_ops import np_array_ops +from tensorflow.python.ops.numpy_ops import np_math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import core +from tensorflow.python.util import dispatch +from tensorflow.python.util import tf_decorator + + +ResourceVariable = resource_variable_ops.ResourceVariable +# List of unary ops that have support for WeakTensor. +_TF_UNARY_APIS = [] +_TF_BINARY_APIS = [] + + +# ============================================================================== +# Utils to handle WeakTensor inputs and outputs. +# ============================================================================== +# pylint: disable=g-doc-args,g-doc-return-or-yield +def _convert_or_cast(x, dtype, name): + """Converts/casts the input x to dtype.""" + # math_ops.cast calls convert_to_tensor(x) under the hood, which can cause + # infinite recursion if non-Tensor inputs are passed into tf.constant. + # For example, tf.constant([1, 2, 3]) -> cast([1, 2, 3], tf.int32) -> + # convert_to_tensor([1, 2, 3]) -> tf.constant([1, 2, 3])... + if isinstance(x, weak_tensor.WeakTensor): + x = x.to_tensor() + # CompositeTensor needs to call math_ops.cast because math_ops.cast may + # have a dispatch for that CompositeTensor. + if isinstance(x, core.Tensor) or isinstance( + x, composite_tensor.CompositeTensor + ): + return math_ops.cast(x, dtype=dtype, name=name) + else: + return ops.convert_to_tensor(x, dtype=dtype, name=name) + + +def weak_tensor_unary_op_wrapper(op, x_arg_name=None): + """Infers input type and adds WeakTensor support to unary ops. + + This wrapper infers input type according to the auto dtype conversion + semantics - Tensor and NumPy inputs as Tensor of corresponding dtype and + WeakTensor and python inputs as WeakTensor of corresponding dtype. If the + inferred input dtype is "weak" and the op doesn't specify a return dtype, + returns WeakTensor. + """ + signature = inspect.signature(op) + if x_arg_name is None: + arg_names = iter(signature.parameters.keys()) + x_arg_name = next(arg_names) + + def wrapper(*args, **kwargs): + if not ops.is_auto_dtype_conversion_enabled(): + return op(*args, **kwargs) + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + bound_kwargs = bound_arguments.arguments + x = bound_kwargs[x_arg_name] + # No input/output handling needed when input is a Tensor or dtype arg is + # specified because it always outputs a Tensor. + if ( + isinstance(x, tensor.Tensor) + or bound_kwargs.get("dtype", None) is not None + ): + return op(**bound_kwargs) + # Infer input type and determine the result promotion type. + try: + target_type, is_weak = flexible_dtypes.result_type(x) + # NotImplementedError is thrown from result_type when x is an + # unsupported input type (e.g. CompositeTensor). + except NotImplementedError: + logging.warning( + "The new dtype semantics do not support" + f" {op.__module__}.{op.__name__}({type(x)}). Falling back to old" + " semantics." + ) + return op(**bound_kwargs) + bound_kwargs[x_arg_name] = _convert_or_cast(x, target_type, "x") + return weak_tensor.convert_to_weak_tensor_or_tensor( + op(**bound_kwargs), is_weak + ) + + wrapper = tf_decorator.make_decorator(op, wrapper) + + # Update dispatch dictionary to store monkey-patched op references. + _update_weak_tensor_patched_ops_in_dispatch_dict(wrapper) + + # Add the updated function to list of unary ops with WeakTensor support. + _TF_UNARY_APIS.append(wrapper) + return wrapper + + +def weak_tensor_binary_op_wrapper(op, y_arg_name=None, special_handling=None): + """Determines result promotion type and adds WeakTensor support to binary ops. + + This wrapper first infers dtype of any Tensor, WeakTensor, python/numpy + inputs. Then, both inputs are promoted to the correct promotion result dtype. + If the result promotion dtype is "weak", returns WeakTensor. + """ + signature = inspect.signature(op) + arg_names = iter(signature.parameters.keys()) + x_arg_name = next(arg_names) + if y_arg_name is None: + y_arg_name = next(arg_names) + + def wrapper(*args, **kwargs): + if not ops.is_auto_dtype_conversion_enabled(): + return op(*args, **kwargs) + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + bound_kwargs = bound_arguments.arguments + x = bound_kwargs[x_arg_name] + y = bound_kwargs[y_arg_name] + # Infer input type and determine the result promotion type. + try: + target_type, is_weak = flexible_dtypes.result_type(x, y) + # NotImplementedError is thrown from result_type when x or y is an + # unsupported input type (e.g. CompositeTensor). + except NotImplementedError: + logging.warning( + "The new dtype semantics do not support" + f" {op.__module__}.{op.__name__}({type(x)}, {type(y)}). Falling back" + " to old semantics." + ) + return op(**bound_kwargs) + + if special_handling == "variable_method": + # Variable dtypes cannot be mutated. Hence we only allow the conversion + # of `y` and disallow the conversion of `x`. + if target_type != x.dtype: + raise TypeError(f"Variable dtype is immutable. Calling {op.__name__} " + f"of Variable (with dtype {x.dtype}) on {y} requires " + f"converting {y} to {x.dtype}. This is disabled in the " + f"current promotion semantics. Please convert {y} " + f"manually before calling {op.__name__}.") + + bound_kwargs[y_arg_name] = _convert_or_cast(y, target_type, "y") + return op(**bound_kwargs) + # TODO(b/293935420): Remove this branch and make a separate patch function + # for tf.constant. + elif special_handling == "constant": + # Convert WeakTensor input to tensor because the dtype check in + # convert_to_eager_tensor only occurs if x is an EagerTensor. + if isinstance(x, weak_tensor.WeakTensor): + bound_kwargs[x_arg_name] = x.to_tensor() + # tf.constant(x, dtype) should always return a Tensor of specified dtype. + # Hence we only allow the one-way conversion from `x` to the dtype arg. + if y is not None: + is_weak = False + if target_type != y: + # If promtion is not successful, rely on tf.constant to handle the + # conversion. + return op(**bound_kwargs) + # Only need to explicity call convert_or_cast for Tensor/WeakTensor + # inputs. Other types are automatically converted to the specified + # dtype in tf.constant. + if isinstance(x, core.Tensor): + bound_kwargs[x_arg_name] = _convert_or_cast(x, target_type, "x") + else: + bound_kwargs["dtype"] = target_type + else: + bound_kwargs[x_arg_name] = _convert_or_cast(x, target_type, "x") + bound_kwargs[y_arg_name] = _convert_or_cast(y, target_type, "y") + if special_handling == "comparison-method": + # No need for "weak" return value for comparison method. + is_weak = False + return weak_tensor.convert_to_weak_tensor_or_tensor( + op(**bound_kwargs), is_weak + ) + + wrapper = tf_decorator.make_decorator(op, wrapper) + + # Update dispatch dictionary to store monkey-patched op references. + _update_weak_tensor_patched_ops_in_dispatch_dict(wrapper) + + # Add the updated function to list of binary ops with WeakTensor support. + _TF_BINARY_APIS.append(wrapper) + return wrapper + + +# TODO(b/290672237): Investigate if there is a more elegant solution. +def _update_weak_tensor_patched_ops_in_dispatch_dict(patched_op): + """Update dispatch dictionary to store WeakTensor patched op references. + + _TYPE_BASED_DISPATCH_SIGNATURES in dispatch.py stores mappings from op + reference to all the dispatchers it's registered with. We need to update + this dictionary to add a mapping from the patched-op reference to the + signature dictionary the unpatched-op reference is mapped to. This ensures + that dispatch can be reigstered and unregistered with monkey-patched ops. + """ + dispatch_dict = dispatch._TYPE_BASED_DISPATCH_SIGNATURES # pylint: disable=protected-access + unpatched_api = patched_op.__wrapped__ + if unpatched_api in dispatch_dict: + dispatch_dict[patched_op] = dispatch_dict[unpatched_api] + + +# ============================================================================== +# Monkey patching to add WeakTensor Support. +# ============================================================================== +# Elementwise unary ops +math_ops.abs = weak_tensor_unary_op_wrapper(math_ops.abs) +math_ops.softplus = weak_tensor_unary_op_wrapper(math_ops.softplus) +math_ops.sign = weak_tensor_unary_op_wrapper(math_ops.sign) +math_ops.real = weak_tensor_unary_op_wrapper(math_ops.real) +math_ops.imag = weak_tensor_unary_op_wrapper(math_ops.imag) +math_ops.angle = weak_tensor_unary_op_wrapper(math_ops.angle) +math_ops.round = weak_tensor_unary_op_wrapper(math_ops.round) +math_ops.sigmoid = weak_tensor_unary_op_wrapper(math_ops.sigmoid) +math_ops.log_sigmoid = weak_tensor_unary_op_wrapper(math_ops.log_sigmoid) +math_ops.conj = weak_tensor_unary_op_wrapper(math_ops.conj) +math_ops.reciprocal_no_nan = weak_tensor_unary_op_wrapper( + math_ops.reciprocal_no_nan +) +math_ops.erfinv = weak_tensor_unary_op_wrapper(math_ops.erfinv) +math_ops.ndtri = weak_tensor_unary_op_wrapper(math_ops.ndtri) +math_ops.erfcinv = weak_tensor_unary_op_wrapper(math_ops.erfcinv) +math_ops.ceil = weak_tensor_unary_op_wrapper(math_ops.ceil) +math_ops.sqrt = weak_tensor_unary_op_wrapper(math_ops.sqrt) +math_ops.exp = weak_tensor_unary_op_wrapper(math_ops.exp) +math_ops.rsqrt = weak_tensor_unary_op_wrapper(math_ops.rsqrt) +math_ops.acos = weak_tensor_unary_op_wrapper(math_ops.acos) +math_ops.floor = weak_tensor_unary_op_wrapper(math_ops.floor) +gen_bitwise_ops.invert = weak_tensor_unary_op_wrapper(gen_bitwise_ops.invert) +gen_math_ops.acosh = weak_tensor_unary_op_wrapper(gen_math_ops.acosh) +gen_math_ops.asin = weak_tensor_unary_op_wrapper(gen_math_ops.asin) +gen_math_ops.asinh = weak_tensor_unary_op_wrapper(gen_math_ops.asinh) +gen_math_ops.atan = weak_tensor_unary_op_wrapper(gen_math_ops.atan) +gen_math_ops.atanh = weak_tensor_unary_op_wrapper(gen_math_ops.atanh) +gen_math_ops.cos = weak_tensor_unary_op_wrapper(gen_math_ops.cos) +gen_math_ops.cosh = weak_tensor_unary_op_wrapper(gen_math_ops.cosh) +gen_math_ops.digamma = weak_tensor_unary_op_wrapper(gen_math_ops.digamma) +gen_math_ops.erf = weak_tensor_unary_op_wrapper(gen_math_ops.erf) +gen_math_ops.erfc = weak_tensor_unary_op_wrapper(gen_math_ops.erfc) +gen_math_ops.expm1 = weak_tensor_unary_op_wrapper(gen_math_ops.expm1) +gen_math_ops.lgamma = weak_tensor_unary_op_wrapper(gen_math_ops.lgamma) +gen_math_ops.log = weak_tensor_unary_op_wrapper(gen_math_ops.log) +gen_math_ops.log1p = weak_tensor_unary_op_wrapper(gen_math_ops.log1p) +gen_math_ops.neg = weak_tensor_unary_op_wrapper(gen_math_ops.neg) +gen_math_ops.reciprocal = weak_tensor_unary_op_wrapper(gen_math_ops.reciprocal) +gen_math_ops.rint = weak_tensor_unary_op_wrapper(gen_math_ops.rint) +gen_math_ops.sin = weak_tensor_unary_op_wrapper(gen_math_ops.sin) +gen_math_ops.sinh = weak_tensor_unary_op_wrapper(gen_math_ops.sinh) +gen_math_ops.square = weak_tensor_unary_op_wrapper(gen_math_ops.square) +gen_math_ops.tan = weak_tensor_unary_op_wrapper(gen_math_ops.tan) +gen_math_ops.tanh = weak_tensor_unary_op_wrapper(gen_math_ops.tanh) +array_ops.zeros_like = weak_tensor_unary_op_wrapper(array_ops.zeros_like) +array_ops.zeros_like_v2 = weak_tensor_unary_op_wrapper(array_ops.zeros_like_v2) +array_ops.ones_like = weak_tensor_unary_op_wrapper(array_ops.ones_like) +array_ops.ones_like_v2 = weak_tensor_unary_op_wrapper(array_ops.ones_like_v2) +gen_array_ops.check_numerics = weak_tensor_unary_op_wrapper( + gen_array_ops.check_numerics +) +nn_ops.relu6 = weak_tensor_unary_op_wrapper(nn_ops.relu6) +nn_ops.leaky_relu = weak_tensor_unary_op_wrapper(nn_ops.leaky_relu) +nn_ops.gelu = weak_tensor_unary_op_wrapper(nn_ops.gelu) +nn_ops.log_softmax = weak_tensor_unary_op_wrapper(nn_ops.log_softmax) +nn_ops.log_softmax_v2 = weak_tensor_unary_op_wrapper(nn_ops.log_softmax_v2) +nn_impl.swish = weak_tensor_unary_op_wrapper(nn_impl.swish) +nn_ops.elu = weak_tensor_unary_op_wrapper(nn_ops.elu) +nn_ops.relu = weak_tensor_unary_op_wrapper(nn_ops.relu) +nn_ops.selu = weak_tensor_unary_op_wrapper(nn_ops.selu) +nn_ops.softsign = weak_tensor_unary_op_wrapper(nn_ops.softsign) +image_ops.random_brightness = weak_tensor_unary_op_wrapper( + image_ops.random_brightness +) +image_ops.stateless_random_brightness = weak_tensor_unary_op_wrapper( + image_ops.stateless_random_brightness +) +image_ops.adjust_brightness = weak_tensor_unary_op_wrapper( + image_ops.adjust_brightness +) +image_ops.adjust_gamma = weak_tensor_unary_op_wrapper(image_ops.adjust_gamma) +clip_ops.clip_by_value = weak_tensor_unary_op_wrapper(clip_ops.clip_by_value) +special_math_ops.dawsn = weak_tensor_unary_op_wrapper(special_math_ops.dawsn) +special_math_ops.expint = weak_tensor_unary_op_wrapper(special_math_ops.expint) +special_math_ops.fresnel_cos = weak_tensor_unary_op_wrapper( + special_math_ops.fresnel_cos +) +special_math_ops.fresnel_sin = weak_tensor_unary_op_wrapper( + special_math_ops.fresnel_sin +) +special_math_ops.spence = weak_tensor_unary_op_wrapper(special_math_ops.spence) +special_math_ops.bessel_i0 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_i0 +) +special_math_ops.bessel_i0e = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_i0e +) +special_math_ops.bessel_i1 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_i1 +) +special_math_ops.bessel_i1e = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_i1e +) +special_math_ops.bessel_k0 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_k0 +) +special_math_ops.bessel_k0e = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_k0e +) +special_math_ops.bessel_k1 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_k1 +) +special_math_ops.bessel_k1e = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_k1e +) +special_math_ops.bessel_j0 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_j0 +) +special_math_ops.bessel_j1 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_j1 +) +special_math_ops.bessel_y0 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_y0 +) +special_math_ops.bessel_y1 = weak_tensor_unary_op_wrapper( + special_math_ops.bessel_y1 +) + +# TF Non-Elementwise Unary Ops +math_ops.reduce_euclidean_norm = weak_tensor_unary_op_wrapper( + math_ops.reduce_euclidean_norm +) +math_ops.reduce_logsumexp = weak_tensor_unary_op_wrapper( + math_ops.reduce_logsumexp +) +math_ops.reduce_max = weak_tensor_unary_op_wrapper(math_ops.reduce_max) +math_ops.reduce_max_v1 = weak_tensor_unary_op_wrapper(math_ops.reduce_max_v1) +math_ops.reduce_mean = weak_tensor_unary_op_wrapper(math_ops.reduce_mean) +math_ops.reduce_mean_v1 = weak_tensor_unary_op_wrapper(math_ops.reduce_mean_v1) +math_ops.reduce_min = weak_tensor_unary_op_wrapper(math_ops.reduce_min) +math_ops.reduce_min_v1 = weak_tensor_unary_op_wrapper(math_ops.reduce_min_v1) +math_ops.reduce_prod = weak_tensor_unary_op_wrapper(math_ops.reduce_prod) +math_ops.reduce_prod_v1 = weak_tensor_unary_op_wrapper(math_ops.reduce_prod_v1) +math_ops.reduce_std = weak_tensor_unary_op_wrapper(math_ops.reduce_std) +math_ops.reduce_sum = weak_tensor_unary_op_wrapper(math_ops.reduce_sum) +math_ops.reduce_sum_v1 = weak_tensor_unary_op_wrapper(math_ops.reduce_sum_v1) +math_ops.reduce_variance = weak_tensor_unary_op_wrapper( + math_ops.reduce_variance +) +math_ops.trace = weak_tensor_unary_op_wrapper(math_ops.trace) +array_ops.reshape = weak_tensor_unary_op_wrapper(array_ops.reshape) +array_ops.depth_to_space = weak_tensor_unary_op_wrapper( + array_ops.depth_to_space +) +array_ops.depth_to_space_v2 = weak_tensor_unary_op_wrapper( + array_ops.depth_to_space_v2 +) +array_ops.expand_dims = weak_tensor_unary_op_wrapper(array_ops.expand_dims) +array_ops.expand_dims_v2 = weak_tensor_unary_op_wrapper( + array_ops.expand_dims_v2 +) +array_ops.extract_image_patches = weak_tensor_unary_op_wrapper( + array_ops.extract_image_patches +) +array_ops.extract_image_patches_v2 = weak_tensor_unary_op_wrapper( + array_ops.extract_image_patches_v2 +) +array_ops.identity = weak_tensor_unary_op_wrapper(array_ops.identity) +array_ops.matrix_diag = weak_tensor_unary_op_wrapper(array_ops.matrix_diag) +array_ops.matrix_diag_part = weak_tensor_unary_op_wrapper( + array_ops.matrix_diag_part +) +array_ops.matrix_transpose = weak_tensor_unary_op_wrapper( + array_ops.matrix_transpose +) +array_ops.space_to_depth = weak_tensor_unary_op_wrapper( + array_ops.space_to_depth +) +array_ops.space_to_depth_v2 = weak_tensor_unary_op_wrapper( + array_ops.space_to_depth_v2 +) +array_ops.squeeze = weak_tensor_unary_op_wrapper(array_ops.squeeze) +array_ops.squeeze_v2 = weak_tensor_unary_op_wrapper(array_ops.squeeze_v2) +array_ops.stop_gradient = weak_tensor_unary_op_wrapper(array_ops.stop_gradient) +array_ops.tensor_diag_part = weak_tensor_unary_op_wrapper( + array_ops.tensor_diag_part +) +array_ops.transpose = weak_tensor_unary_op_wrapper(array_ops.transpose) +array_ops.transpose_v2 = weak_tensor_unary_op_wrapper(array_ops.transpose_v2) + +# TF NumPy Unary Ops +np_math_ops.abs = weak_tensor_unary_op_wrapper(np_math_ops.abs) +np_math_ops.absolute = weak_tensor_unary_op_wrapper(np_math_ops.absolute) +np_math_ops.angle = weak_tensor_unary_op_wrapper(np_math_ops.angle) +np_math_ops.arccos = weak_tensor_unary_op_wrapper(np_math_ops.arccos) +np_math_ops.arcsin = weak_tensor_unary_op_wrapper(np_math_ops.arcsin) +np_math_ops.arcsinh = weak_tensor_unary_op_wrapper(np_math_ops.arcsinh) +np_math_ops.arctan = weak_tensor_unary_op_wrapper(np_math_ops.arctan) +np_math_ops.arctanh = weak_tensor_unary_op_wrapper(np_math_ops.arctanh) +np_math_ops.bitwise_not = weak_tensor_unary_op_wrapper(np_math_ops.bitwise_not) +np_math_ops.cbrt = weak_tensor_unary_op_wrapper(np_math_ops.cbrt) +np_math_ops.ceil = weak_tensor_unary_op_wrapper(np_math_ops.ceil) +np_math_ops.conj = weak_tensor_unary_op_wrapper(np_math_ops.conj) +np_math_ops.conjugate = weak_tensor_unary_op_wrapper(np_math_ops.conjugate) +np_math_ops.cos = weak_tensor_unary_op_wrapper(np_math_ops.cos) +np_math_ops.cosh = weak_tensor_unary_op_wrapper(np_math_ops.cosh) +np_math_ops.deg2rad = weak_tensor_unary_op_wrapper(np_math_ops.deg2rad) +np_math_ops.exp = weak_tensor_unary_op_wrapper(np_math_ops.exp) +np_math_ops.exp2 = weak_tensor_unary_op_wrapper(np_math_ops.exp2) +np_math_ops.expm1 = weak_tensor_unary_op_wrapper(np_math_ops.expm1) +np_math_ops.fabs = weak_tensor_unary_op_wrapper(np_math_ops.fabs) +np_math_ops.fix = weak_tensor_unary_op_wrapper(np_math_ops.fix) +np_math_ops.floor = weak_tensor_unary_op_wrapper(np_math_ops.floor) +np_math_ops.log = weak_tensor_unary_op_wrapper(np_math_ops.log) +np_math_ops.negative = weak_tensor_unary_op_wrapper(np_math_ops.negative) +np_math_ops.rad2deg = weak_tensor_unary_op_wrapper(np_math_ops.rad2deg) +np_math_ops.reciprocal = weak_tensor_unary_op_wrapper(np_math_ops.reciprocal) +np_math_ops.sin = weak_tensor_unary_op_wrapper(np_math_ops.sin) +np_math_ops.sinh = weak_tensor_unary_op_wrapper(np_math_ops.sinh) +np_math_ops.sqrt = weak_tensor_unary_op_wrapper(np_math_ops.sqrt) +np_math_ops.tan = weak_tensor_unary_op_wrapper(np_math_ops.tan) +np_math_ops.tanh = weak_tensor_unary_op_wrapper(np_math_ops.tanh) +np_math_ops.nanmean = weak_tensor_unary_op_wrapper(np_math_ops.nanmean) +np_math_ops.log2 = weak_tensor_unary_op_wrapper(np_math_ops.log2) +np_math_ops.log10 = weak_tensor_unary_op_wrapper(np_math_ops.log10) +np_math_ops.log1p = weak_tensor_unary_op_wrapper(np_math_ops.log1p) +np_math_ops.positive = weak_tensor_unary_op_wrapper(np_math_ops.positive) +np_math_ops.sinc = weak_tensor_unary_op_wrapper(np_math_ops.sinc) +np_math_ops.square = weak_tensor_unary_op_wrapper(np_math_ops.square) +np_math_ops.diff = weak_tensor_unary_op_wrapper(np_math_ops.diff) +np_math_ops.sort = weak_tensor_unary_op_wrapper(np_math_ops.sort) +np_math_ops.average = weak_tensor_unary_op_wrapper(np_math_ops.average) +np_math_ops.trace = weak_tensor_unary_op_wrapper(np_math_ops.trace) +np_array_ops.amax = weak_tensor_unary_op_wrapper(np_array_ops.amax) +np_array_ops.amin = weak_tensor_unary_op_wrapper(np_array_ops.amin) +np_array_ops.around = weak_tensor_unary_op_wrapper(np_array_ops.around) +np_array_ops.arange = weak_tensor_unary_op_wrapper(np_array_ops.arange) +np_array_ops.array = weak_tensor_unary_op_wrapper(np_array_ops.array) +np_array_ops.asanyarray = weak_tensor_unary_op_wrapper(np_array_ops.asanyarray) +np_array_ops.asarray = weak_tensor_unary_op_wrapper(np_array_ops.asarray) +np_array_ops.ascontiguousarray = weak_tensor_unary_op_wrapper( + np_array_ops.ascontiguousarray +) +np_array_ops.copy = weak_tensor_unary_op_wrapper(np_array_ops.copy) +np_array_ops.cumprod = weak_tensor_unary_op_wrapper(np_array_ops.cumprod) +np_array_ops.cumsum = weak_tensor_unary_op_wrapper(np_array_ops.cumsum) +np_array_ops.diag = weak_tensor_unary_op_wrapper(np_array_ops.diag) +np_array_ops.diagflat = weak_tensor_unary_op_wrapper(np_array_ops.diagflat) +np_array_ops.diagonal = weak_tensor_unary_op_wrapper(np_array_ops.diagonal) +np_array_ops.empty_like = weak_tensor_unary_op_wrapper(np_array_ops.empty_like) +np_array_ops.expand_dims = weak_tensor_unary_op_wrapper( + np_array_ops.expand_dims +) +np_array_ops.flatten = weak_tensor_unary_op_wrapper(np_array_ops.flatten) +np_array_ops.flip = weak_tensor_unary_op_wrapper(np_array_ops.flip) +np_array_ops.fliplr = weak_tensor_unary_op_wrapper(np_array_ops.fliplr) +np_array_ops.flipud = weak_tensor_unary_op_wrapper(np_array_ops.flipud) +np_array_ops.full_like = weak_tensor_unary_op_wrapper(np_array_ops.full_like) +np_array_ops.imag = weak_tensor_unary_op_wrapper(np_array_ops.imag) +np_array_ops.max = weak_tensor_unary_op_wrapper(np_array_ops.max) +np_array_ops.mean = weak_tensor_unary_op_wrapper(np_array_ops.mean) +np_array_ops.min = weak_tensor_unary_op_wrapper(np_array_ops.min) +np_array_ops.moveaxis = weak_tensor_unary_op_wrapper(np_array_ops.moveaxis) +np_array_ops.ones_like = weak_tensor_unary_op_wrapper(np_array_ops.ones_like) +np_array_ops.prod = weak_tensor_unary_op_wrapper(np_array_ops.prod) +np_array_ops.ravel = weak_tensor_unary_op_wrapper(np_array_ops.ravel) +np_array_ops.real = weak_tensor_unary_op_wrapper(np_array_ops.real) +np_array_ops.reshape = weak_tensor_unary_op_wrapper(np_array_ops.reshape) +np_array_ops.repeat = weak_tensor_unary_op_wrapper(np_array_ops.repeat) +np_array_ops.rot90 = weak_tensor_unary_op_wrapper(np_array_ops.rot90) +np_array_ops.round = weak_tensor_unary_op_wrapper(np_array_ops.round) +np_array_ops.squeeze = weak_tensor_unary_op_wrapper(np_array_ops.squeeze) +np_array_ops.std = weak_tensor_unary_op_wrapper(np_array_ops.std) +np_array_ops.sum = weak_tensor_unary_op_wrapper(np_array_ops.sum) +np_array_ops.swapaxes = weak_tensor_unary_op_wrapper(np_array_ops.swapaxes) +np_array_ops.transpose = weak_tensor_unary_op_wrapper(np_array_ops.transpose) +np_array_ops.triu = weak_tensor_unary_op_wrapper(np_array_ops.triu) +np_array_ops.vander = weak_tensor_unary_op_wrapper(np_array_ops.vander) +np_array_ops.var = weak_tensor_unary_op_wrapper(np_array_ops.var) +np_array_ops.zeros_like = weak_tensor_unary_op_wrapper(np_array_ops.zeros_like) + +# Binary ops +math_ops.add = weak_tensor_binary_op_wrapper(math_ops.add) +gen_math_ops.sub = weak_tensor_binary_op_wrapper(gen_math_ops.sub) +math_ops.multiply = weak_tensor_binary_op_wrapper(math_ops.multiply) +math_ops.multiply_no_nan = weak_tensor_binary_op_wrapper( + math_ops.multiply_no_nan +) +math_ops.matmul = weak_tensor_binary_op_wrapper(math_ops.matmul) +np_math_ops.matmul = weak_tensor_binary_op_wrapper(np_math_ops.matmul) +# In scalar_mul(scalar, x), dtype should be solely inferred from the dtype of x. +math_ops.scalar_mul = weak_tensor_unary_op_wrapper(math_ops.scalar_mul, "x") +math_ops.divide = weak_tensor_binary_op_wrapper(math_ops.divide) +math_ops.div_no_nan = weak_tensor_binary_op_wrapper(math_ops.div_no_nan) +# pylint: disable=protected-access +math_ops._truediv_python3 = weak_tensor_binary_op_wrapper( + math_ops._truediv_python3 +) +gen_math_ops.real_div = weak_tensor_binary_op_wrapper(gen_math_ops.real_div) +gen_math_ops.truncate_div = weak_tensor_binary_op_wrapper( + gen_math_ops.truncate_div +) +gen_math_ops.floor_div = weak_tensor_binary_op_wrapper(gen_math_ops.floor_div) +gen_math_ops.truncate_mod = weak_tensor_binary_op_wrapper( + gen_math_ops.truncate_mod +) +gen_math_ops.floor_mod = weak_tensor_binary_op_wrapper(gen_math_ops.floor_mod) +gen_math_ops._pow = weak_tensor_binary_op_wrapper(gen_math_ops._pow) +gen_math_ops.maximum = weak_tensor_binary_op_wrapper( + gen_math_ops.maximum, special_handling="comparison-method" +) +gen_math_ops.minimum = weak_tensor_binary_op_wrapper( + gen_math_ops.minimum, special_handling="comparison-method" +) +gen_math_ops.equal = weak_tensor_binary_op_wrapper( + gen_math_ops.equal, special_handling="comparison-method" +) +# math_ops.maximum and minimum don't call from gen_math_ops. +math_ops.maximum = weak_tensor_binary_op_wrapper( + math_ops.maximum, special_handling="comparison-method" +) +math_ops.minimum = weak_tensor_binary_op_wrapper( + math_ops.minimum, special_handling="comparison-method" +) +ResourceVariable.assign = weak_tensor_binary_op_wrapper( + ResourceVariable.assign, special_handling="variable_method" +) +ResourceVariable.assign_add = weak_tensor_binary_op_wrapper( + ResourceVariable.assign_add, special_handling="variable_method" +) +ResourceVariable.assign_sub = weak_tensor_binary_op_wrapper( + ResourceVariable.assign_sub, special_handling="variable_method" +) +ops.convert_to_tensor_or_composite = weak_tensor_unary_op_wrapper( + ops.convert_to_tensor_or_composite) + +# Patching tf.constant does the following. +# (1) If dtype arg is not specified and the input is a Python nested type, +# return a WeakTensor. +# (2) If dtype arg is specified and the input is a Tensor/WeakTensor type, +# we allow one-way conversion from input's dtype to the specified dtype. +# e.g. tf.constant(tf.constant(1, int16), int32) previously threw a TypeError +# but with patching, tf.constant(tf.constant(1, tf.int16), tf.int32) -> +# tf.Tensor(1, tf.int32). +# (3) If none of the above conditions apply, the behavior is same as before. +constant_op.constant = weak_tensor_binary_op_wrapper( + constant_op.constant, y_arg_name="dtype", special_handling="constant" +) +# ============================================================================== +# Update old op references. +# ============================================================================== +math_ops.realdiv = gen_math_ops.real_div +math_ops.truncatediv = gen_math_ops.truncate_div +math_ops.floor_div = gen_math_ops.floor_div +math_ops.truncatemod = gen_math_ops.truncate_mod +math_ops.floormod = gen_math_ops.floor_mod + +# Set WeakTensor dunder methods. +# Tensor unary ops do not need WeakTensor support. +weak_tensor.WeakTensor.__invert__ = math_ops.invert_ +weak_tensor.WeakTensor.__neg__ = gen_math_ops.neg +weak_tensor.WeakTensor.__abs__ = math_ops.abs + +# Inherit rest of the dunder methods from Tensor. +unary_dunder_methods = ["__invert__", "__neg__", "__abs__"] +for operator in tensor.Tensor.OVERLOADABLE_OPERATORS: + if operator in unary_dunder_methods: + continue + tensor_oper = getattr(tensor.Tensor, operator) + setattr(weak_tensor.WeakTensor, operator, tensor_oper) + +# Add NumPy methods in WeakTensor. +np_math_ops._enable_numpy_methods(weak_tensor.WeakTensor) +setattr(weak_tensor.WeakTensor, "__round__", np_array_ops.around) +setattr(weak_tensor.WeakTensor, "_numpy_style_getitem", np_array_ops._getitem) +# Add support for batched matmul. +setattr(weak_tensor.WeakTensor, "_matmul", np_math_ops.matmul) +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7a67d99927200b9e7f5c04060c9b630d6b14ed40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weak_tensor_test_util.py @@ -0,0 +1,90 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utils for WeakTensor related tests.""" + +import numpy as np + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework.weak_tensor import WeakTensor + + +def get_test_input_for_op(val, dtype): + """Returns a list containing all the possible inputs with a given dtype. + + Args: + val: value to convert to test input. + dtype: a tuple of format (tf.Dtype, bool) where the bool value represents + whether the dtype is "weak" or not. + + Returns: + A list of all possible inputs given a value and a dtype. + """ + python_inferred_types = { + (dtypes.int32, True): 1, + (dtypes.float32, True): 1.0, + (dtypes.complex128, True): 1.0j, + } + dtype, weak = dtype + inputs = [] + if weak: + # WeakTensor and Python input types. + inputs.append(convert_to_input_type(val, "WeakTensor", dtype)) + if dtype in python_inferred_types: + # There are only 3 possible Python default types : int, float, complex. + val_in_dtype = val * python_inferred_types[dtype] + inputs.append(val_in_dtype) + inputs.append(convert_to_input_type(val_in_dtype, "Tensor", None)) + else: + # Tensor and NumPy input types. + inputs.append(convert_to_input_type(val, "Tensor", dtype)) + inputs.append(convert_to_input_type(val, "NumPy", dtype)) + return inputs + + +def convert_to_input_type(base_input, input_type, dtype=None): + if input_type == "WeakTensor": + return WeakTensor.from_tensor(constant_op.constant(base_input, dtype=dtype)) + elif input_type == "Tensor": + return constant_op.constant(base_input, dtype=dtype) + elif input_type == "NumPy": + dtype = dtype.as_numpy_dtype if isinstance(dtype, dtypes.DType) else dtype + return np.array(base_input, dtype=dtype) + elif input_type == "Python": + return base_input + else: + raise ValueError(f"The provided input_type {input_type} is not supported.") + + +def get_weak_tensor(*args, **kwargs): + return WeakTensor.from_tensor(constant_op.constant(*args, **kwargs)) + + +class DtypeConversionTestEnv: + """Test environment for different dtype conversion semantics.""" + + def __init__(self, promo_mode): + self._old_promo_mode = ops.promo_mode_enum_to_string( + ops.get_dtype_conversion_mode() + ) + self._new_promo_mode = promo_mode + + def __enter__(self): + ops.set_dtype_conversion_mode(self._new_promo_mode) + return self + + def __exit__(self, exc_type, exc_value, exc_traceback): + ops.set_dtype_conversion_mode(self._old_promo_mode) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weights_broadcast_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weights_broadcast_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..908558dc3923c3c8ee97bfc42f466124e851947d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/weights_broadcast_ops.py @@ -0,0 +1,177 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Weight broadcasting operations. + +In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. This +file includes operations for those broadcasting rules. +""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sets +from tensorflow.python.util.tf_export import tf_export + + +def _has_valid_dims(weights_shape, values_shape): + with ops.name_scope( + None, "has_invalid_dims", (weights_shape, values_shape)) as scope: + values_shape_2d = array_ops.expand_dims(values_shape, -1) + valid_dims = array_ops.concat( + (values_shape_2d, array_ops.ones_like(values_shape_2d)), axis=1) + weights_shape_2d = array_ops.expand_dims(weights_shape, -1) + invalid_dims = sets.set_difference(weights_shape_2d, valid_dims) + num_invalid_dims = array_ops.size( + invalid_dims.values, name="num_invalid_dims") + return math_ops.equal(0, num_invalid_dims, name=scope) + + +def _has_valid_nonscalar_shape( + weights_rank, weights_shape, values_rank, values_shape): + with ops.name_scope( + None, "has_valid_nonscalar_shape", + (weights_rank, weights_shape, values_rank, values_shape)) as scope: + is_same_rank = math_ops.equal( + values_rank, weights_rank, name="is_same_rank") + return cond.cond( + is_same_rank, + lambda: _has_valid_dims(weights_shape, values_shape), + lambda: is_same_rank, + name=scope) + + +_ASSERT_BROADCASTABLE_ERROR_PREFIX = "weights can not be broadcast to values." + + +def assert_broadcastable(weights, values): + """Asserts `weights` can be broadcast to `values`. + + In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We + let weights be either scalar, or the same rank as the target values, with each + dimension either 1, or the same as the corresponding values dimension. + + Args: + weights: `Tensor` of weights. + values: `Tensor` of values to which weights are applied. + + Returns: + `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. + `no_op` if static checks determine `weights` has correct shape. + + Raises: + ValueError: If static checks determine `weights` has incorrect shape. + """ + with ops.name_scope(None, "assert_broadcastable", (weights, values)) as scope: + with ops.name_scope(None, "weights", (weights,)) as weights_scope: + weights = ops.convert_to_tensor(weights, name=weights_scope) + weights_shape = array_ops.shape(weights, name="shape") + weights_rank = array_ops.rank(weights, name="rank") + weights_rank_static = tensor_util.constant_value(weights_rank) + + with ops.name_scope(None, "values", (values,)) as values_scope: + values = ops.convert_to_tensor(values, name=values_scope) + values_shape = array_ops.shape(values, name="shape") + values_rank = array_ops.rank(values, name="rank") + values_rank_static = tensor_util.constant_value(values_rank) + + # Try static checks. + if weights_rank_static is not None and values_rank_static is not None: + if weights_rank_static == 0: + return control_flow_ops.no_op(name="static_scalar_check_success") + if weights_rank_static != values_rank_static: + raise ValueError( + f"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} values.rank=" + f"{values_rank_static}. weights.rank={weights_rank_static}. " + f"values.shape={values.shape}. weights.shape={weights.shape}. " + f"Received weights={weights}, values={values}") + weights_shape_static = tensor_util.constant_value(weights_shape) + values_shape_static = tensor_util.constant_value(values_shape) + if weights_shape_static is not None and values_shape_static is not None: + # Sanity check, this should always be true since we checked rank above. + ndims = len(values_shape_static) + assert ndims == len(weights_shape_static) + + for i in range(ndims): + if weights_shape_static[i] not in (1, values_shape_static[i]): + raise ValueError( + f"{_ASSERT_BROADCASTABLE_ERROR_PREFIX} Mismatch at dim {i}. " + f"values.shape={values_shape_static}, weights.shape=" + f"{weights_shape_static}. Received weights={weights}, " + f"values={values}") + return control_flow_ops.no_op(name="static_dims_check_success") + + # Dynamic checks. + is_scalar = math_ops.equal(0, weights_rank, name="is_scalar") + data = ( + _ASSERT_BROADCASTABLE_ERROR_PREFIX, + "weights.shape=", weights.name, weights_shape, + "values.shape=", values.name, values_shape, + "is_scalar=", is_scalar, + ) + is_valid_shape = cond.cond( + is_scalar, + lambda: is_scalar, + lambda: _has_valid_nonscalar_shape( # pylint: disable=g-long-lambda + weights_rank, weights_shape, values_rank, values_shape), + name="is_valid_shape") + return control_flow_assert.Assert(is_valid_shape, data, name=scope) + + +@tf_export("__internal__.ops.broadcast_weights", v1=[]) +def broadcast_weights(weights, values): + """Broadcast `weights` to the same shape as `values`. + + This returns a version of `weights` following the same broadcast rules as + `mul(weights, values)`, but limited to the weights shapes allowed by + `assert_broadcastable`. When computing a weighted average, use this function + to broadcast `weights` before summing them; e.g., + `reduce_sum(w * v) / reduce_sum(_broadcast_weights(w, v))`. + + Args: + weights: `Tensor` whose shape is broadcastable to `values` according to the + rules of `assert_broadcastable`. + values: `Tensor` of any shape. + + Returns: + `weights` broadcast to `values` shape according to the rules of + `assert_broadcastable`. + """ + with ops.name_scope(None, "broadcast_weights", (weights, values)) as scope: + values = ops.convert_to_tensor(values, name="values") + weights = ops.convert_to_tensor( + weights, dtype=values.dtype.base_dtype, name="weights") + + # Try static check for exact match. + weights_shape = weights.get_shape() + values_shape = values.get_shape() + if (weights_shape.is_fully_defined() and + values_shape.is_fully_defined() and + weights_shape.is_compatible_with(values_shape)): + return weights + + # Skip the assert_broadcastable on TPU/GPU because asserts are not + # supported so it only causes unnecessary ops. Also skip it because it uses + # a DenseToDenseSetOperation op that is incompatible with the TPU/GPU when + # the shape(s) are dynamic. + if control_flow_ops.get_enclosing_xla_context() is not None: + return math_ops.multiply( + weights, array_ops.ones_like(values), name=scope) + with ops.control_dependencies((assert_broadcastable(weights, values),)): + return math_ops.multiply( + weights, array_ops.ones_like(values), name=scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_loop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef24e0a7ce9299df375a6c724aa655f6bc19839 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_loop.py @@ -0,0 +1,523 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""While loop for Control Flow Operations.""" + +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util as util +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_v2 +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +# @TODO(b/133606651) Replace "shape_invariants" with "loop_vars_signature". +# pylint: disable=redefined-outer-name +@tf_export("while_loop", v1=[]) +@deprecation.deprecated_arg_values( + None, + """back_prop=False is deprecated. Consider using tf.stop_gradient instead. +Instead of: +results = tf.while_loop(c, b, vars, back_prop=False) +Use: +results = tf.nest.map_structure(tf.stop_gradient, tf.while_loop(c, b, vars))""", + warn_once=True, + back_prop=False) +def while_loop_v2(cond, + body, + loop_vars, + shape_invariants=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + maximum_iterations=None, + name=None): + """Repeat `body` while the condition `cond` is true. + + Note: This op is automatically used in a `tf.function` to convert Python for- + and while- loops when the loop variable is a `tf.Tensor`, unless + `autograph=False` is explicitly specified in `tf.function` args. For example, + the following are equivalent: + + >>> @tf.function + ... def sumSquare(n): + ... i, result = tf.constant(0), tf.constant(0) + ... while i < n: # AutoGraph converts while-loop to tf.while_loop(). + ... result += i * i + ... i += 1 + ... return result + >>> sumSquare(10).numpy() + 285 + + >>> @tf.function + ... def sumSquare2(n): + ... i, result = tf.constant(0), tf.constant(0) + ... c = lambda i, _: tf.less(i, n) + ... b = lambda i, result: (i + 1, result + i * i) + ... return tf.while_loop(c, b, [i, result])[1] + >>> sumSquare2(10).numpy() + 285 + + For more information, see [tf.function and AutoGraph guide + ](https://www.tensorflow.org/guide/function#autograph_transformations). + + `cond` is a callable returning a boolean scalar tensor. `body` is a callable + returning a (possibly nested) tuple, namedtuple or list of tensors of the same + arity (length and structure) and types as `loop_vars`. `loop_vars` is a + (possibly nested) tuple, namedtuple or list of tensors that is passed to both + `cond` and `body`. `cond` and `body` both take as many arguments as there are + `loop_vars`. + + In addition to regular Tensors or IndexedSlices, the body may accept and + return TensorArray objects. The flows of the TensorArray objects will + be appropriately forwarded between loops and during gradient calculations. + + Note that `while_loop` calls `cond` and `body` *exactly once* (inside the + call to `while_loop`, and not at all during `Session.run()`). `while_loop` + stitches together the graph fragments created during the `cond` and `body` + calls with some additional graph nodes to create the graph flow that + repeats `body` until `cond` returns false. + + For correctness, `tf.while_loop()` strictly enforces shape invariants for + the loop variables. A shape invariant is a (possibly partial) shape that + is unchanged across the iterations of the loop. An error will be raised + if the shape of a loop variable after an iteration is determined to be more + general than or incompatible with its shape invariant. For example, a shape + of `[11, None]` is more general than a shape of `[11, 17]`, and `[11, 21]` is + not compatible with `[11, 17]`. By default (if the argument `shape_invariants` + is not specified), it is assumed that the initial shape of each tensor in + `loop_vars` is the same in every iteration. The `shape_invariants` argument + allows the caller to specify a less specific shape invariant for each loop + variable, which is needed if the shape varies between iterations. The + `tf.Tensor.set_shape` + function may also be used in the `body` function to indicate that + the output loop variable has a particular shape. The shape invariant for + SparseTensor and IndexedSlices are treated specially as follows: + + a) If a loop variable is a SparseTensor, the shape invariant must be + `TensorShape([r])` where `r` is the rank of the dense tensor represented + by the sparse tensor. It means the shapes of the three tensors of the + SparseTensor are `([None], [None, r], [r])`. NOTE: The shape invariant here + is the shape of the SparseTensor.dense_shape property. It must be the shape of + a vector. + + b) If a loop variable is an IndexedSlices, the shape invariant must be + a shape invariant of the values tensor of the IndexedSlices. It means + the shapes of the three tensors of the IndexedSlices are `(shape, [shape[0]], + [shape.ndims])`. + + `while_loop` implements non-strict semantics, enabling multiple iterations + to run in parallel. The maximum number of parallel iterations can be + controlled by `parallel_iterations`, which gives users some control over + memory consumption and execution order. For correct programs, `while_loop` + should return the same result for any `parallel_iterations > 0`. + + For training, TensorFlow stores the tensors that are produced in the + forward inference and are needed in back propagation. These tensors are a + main source of memory consumption and often cause OOM errors when training + on GPUs. When the flag swap_memory is true, we swap out these tensors from + GPU to CPU. This for example allows us to train RNN models with very long + sequences and large batches. + + Args: + cond: A callable that represents the termination condition of the loop. + body: A callable that represents the loop body. + loop_vars: A (possibly nested) tuple, namedtuple or list of numpy array, + `Tensor`, and `TensorArray` objects. + shape_invariants: The shape invariants for the loop variables. + parallel_iterations: The number of iterations allowed to run in parallel. It + must be a positive integer. + back_prop: (optional) Deprecated. False disables support for back + propagation. Prefer using `tf.stop_gradient` instead. + swap_memory: Whether GPU-CPU memory swap is enabled for this loop. + maximum_iterations: Optional maximum number of iterations of the while loop + to run. If provided, the `cond` output is AND-ed with an additional + condition ensuring the number of iterations executed is no greater than + `maximum_iterations`. + name: Optional name prefix for the returned tensors. + + Returns: + The output tensors for the loop variables after the loop. The return value + has the same structure as `loop_vars`. + + Raises: + TypeError: if `cond` or `body` is not callable. + ValueError: if `loop_vars` is empty. + + Example: + + >>> i = tf.constant(0) + >>> c = lambda i: tf.less(i, 10) + >>> b = lambda i: (tf.add(i, 1), ) + >>> r = tf.while_loop(c, b, [i])[0] + >>> r.numpy() + 10 + + Example with nesting and a namedtuple: + + >>> import collections + >>> Pair = collections.namedtuple('Pair', 'j, k') + >>> ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2))) + >>> c = lambda i, p: i < 10 + >>> b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k))) + >>> ijk_final = tf.while_loop(c, b, ijk_0)[1] + >>> ijk_final[0].numpy(), ijk_final[1].numpy() + (32, 64) + + Example using shape_invariants: + + >>> i0 = tf.constant(0) + >>> m0 = tf.ones([2, 2]) + >>> c = lambda i, m: i < 10 + >>> b = lambda i, m: [i+1, tf.concat([m, m], axis=0)] + >>> tf.while_loop( + ... c, b, loop_vars=[i0, m0], + ... shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])[1] + + + Example which demonstrates non-strict semantics: In the following + example, the final value of `counter` does not depend on `x`. So + the `while_loop` can increment the counter parallel to updates of `x`. + However, because the loop counter at one loop iteration depends + on the value at the previous iteration, the loop counter itself cannot + be incremented in parallel. Hence if we just want the final value of the + counter (which we print on the line `print(sess.run(i))`), then + `x` will never be incremented, but the counter will be updated on a + single thread. Conversely, if we want the value of the output (which we + print on the line `print(sess.run(out).shape)`), then the counter may be + incremented on its own thread, while `x` can be incremented in + parallel on a separate thread. In the extreme case, it is conceivable + that the thread incrementing the counter runs until completion before + `x` is incremented even a single time. The only thing that can never + happen is that the thread updating `x` can never get ahead of the + counter thread because the thread incrementing `x` depends on the value + of the counter. + + >>> with tf.compat.v1.Session() as sess: + ... n = 10 + ... c = lambda i, x: i < n + ... b = lambda i, x: ( + ... tf.compat.v1.Print(i + 1, [i], "Updating i based on i == "), + ... # Let x depend on i + ... tf.compat.v1.Print(x + i, [i], "Updating x based on i == ")) + ... + ... # Make x to be a big matrix so its updating thread would run slowly + ... x = tf.zeros([1000, 100], dtype=tf.int32) + ... counter = tf.constant(0) + ... counter_out, x_out = tf.while_loop(c, b, (counter, x)) + ... + ... # The following line may increment the counter and x in parallel. + ... # The counter thread may get ahead of the x thread, but not the + ... # other way around. For example, the log may contain these messages: + ... # ``` + ... # Updating i based on i == [9] + ... # Updating x based on i == [3] + ... # ``` + ... # meaning that the counter(i) thread is on iteration 9, + ... # while the x thread is on iteration 3. + ... print(sess.run(x_out).shape) + (1000, 100) + + """ + return while_loop( + cond=cond, + body=body, + loop_vars=loop_vars, + shape_invariants=shape_invariants, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory, + name=name, + maximum_iterations=maximum_iterations, + return_same_structure=True) + + +# pylint: disable=redefined-outer-name +@tf_export(v1=["while_loop"]) +def while_loop(cond, + body, + loop_vars, + shape_invariants=None, + parallel_iterations=10, + back_prop=True, + swap_memory=False, + name=None, + maximum_iterations=None, + return_same_structure=False): + """Repeat `body` while the condition `cond` is true. + + `cond` is a callable returning a boolean scalar tensor. `body` is a callable + returning a (possibly nested) tuple, namedtuple or list of tensors of the same + arity (length and structure) and types as `loop_vars`. `loop_vars` is a + (possibly nested) tuple, namedtuple or list of tensors that is passed to both + `cond` and `body`. `cond` and `body` both take as many arguments as there are + `loop_vars`. + + In addition to regular Tensors or IndexedSlices, the body may accept and + return TensorArray objects. The flows of the TensorArray objects will + be appropriately forwarded between loops and during gradient calculations. + + Note that `while_loop` calls `cond` and `body` *exactly once* (inside the + call to `while_loop`, and not at all during `Session.run()`). `while_loop` + stitches together the graph fragments created during the `cond` and `body` + calls with some additional graph nodes to create the graph flow that + repeats `body` until `cond` returns false. + + For correctness, `tf.while_loop()` strictly enforces shape invariants for + the loop variables. A shape invariant is a (possibly partial) shape that + is unchanged across the iterations of the loop. An error will be raised + if the shape of a loop variable after an iteration is determined to be more + general than or incompatible with its shape invariant. For example, a shape + of [11, None] is more general than a shape of [11, 17], and [11, 21] is not + compatible with [11, 17]. By default (if the argument `shape_invariants` is + not specified), it is assumed that the initial shape of each tensor in + `loop_vars` is the same in every iteration. The `shape_invariants` argument + allows the caller to specify a less specific shape invariant for each loop + variable, which is needed if the shape varies between iterations. The + `tf.Tensor.set_shape` + function may also be used in the `body` function to indicate that + the output loop variable has a particular shape. The shape invariant for + SparseTensor and IndexedSlices are treated specially as follows: + + a) If a loop variable is a SparseTensor, the shape invariant must be + TensorShape([r]) where r is the rank of the dense tensor represented + by the sparse tensor. It means the shapes of the three tensors of the + SparseTensor are ([None], [None, r], [r]). NOTE: The shape invariant here + is the shape of the SparseTensor.dense_shape property. It must be the shape of + a vector. + + b) If a loop variable is an IndexedSlices, the shape invariant must be + a shape invariant of the values tensor of the IndexedSlices. It means + the shapes of the three tensors of the IndexedSlices are (shape, [shape[0]], + [shape.ndims]). + + `while_loop` implements non-strict semantics, enabling multiple iterations + to run in parallel. The maximum number of parallel iterations can be + controlled by `parallel_iterations`, which gives users some control over + memory consumption and execution order. For correct programs, `while_loop` + should return the same result for any parallel_iterations > 0. + + For training, TensorFlow stores the tensors that are produced in the + forward inference and are needed in back propagation. These tensors are a + main source of memory consumption and often cause OOM errors when training + on GPUs. When the flag swap_memory is true, we swap out these tensors from + GPU to CPU. This for example allows us to train RNN models with very long + sequences and large batches. + + Args: + cond: A callable that represents the termination condition of the loop. + body: A callable that represents the loop body. + loop_vars: A (possibly nested) tuple, namedtuple or list of numpy array, + `Tensor`, and `TensorArray` objects. + shape_invariants: The shape invariants for the loop variables. + parallel_iterations: The number of iterations allowed to run in parallel. It + must be a positive integer. + back_prop: Whether backprop is enabled for this while loop. + swap_memory: Whether GPU-CPU memory swap is enabled for this loop. + name: Optional name prefix for the returned tensors. + maximum_iterations: Optional maximum number of iterations of the while loop + to run. If provided, the `cond` output is AND-ed with an additional + condition ensuring the number of iterations executed is no greater than + `maximum_iterations`. + return_same_structure: If True, output has same structure as `loop_vars`. If + eager execution is enabled, this is ignored (and always treated as True). + + Returns: + The output tensors for the loop variables after the loop. + If `return_same_structure` is True, the return value has the same + structure as `loop_vars`. + If `return_same_structure` is False, the return value is a Tensor, + TensorArray or IndexedSlice if the length of `loop_vars` is 1, or a list + otherwise. + + Raises: + TypeError: if `cond` or `body` is not callable. + ValueError: if `loop_vars` is empty. + + Example: + + ```python + i = tf.constant(0) + c = lambda i: tf.less(i, 10) + b = lambda i: tf.add(i, 1) + r = tf.while_loop(c, b, [i]) + ``` + + Example with nesting and a namedtuple: + + ```python + import collections + Pair = collections.namedtuple('Pair', 'j, k') + ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2))) + c = lambda i, p: i < 10 + b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k))) + ijk_final = tf.while_loop(c, b, ijk_0) + ``` + + Example using shape_invariants: + + ```python + i0 = tf.constant(0) + m0 = tf.ones([2, 2]) + c = lambda i, m: i < 10 + b = lambda i, m: [i+1, tf.concat([m, m], axis=0)] + tf.while_loop( + c, b, loop_vars=[i0, m0], + shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])]) + ``` + + Example which demonstrates non-strict semantics: In the following + example, the final value of the counter `i` does not depend on `x`. So + the `while_loop` can increment the counter parallel to updates of `x`. + However, because the loop counter at one loop iteration depends + on the value at the previous iteration, the loop counter itself cannot + be incremented in parallel. Hence if we just want the final value of the + counter (which we print on the line `print(sess.run(i))`), then + `x` will never be incremented, but the counter will be updated on a + single thread. Conversely, if we want the value of the output (which we + print on the line `print(sess.run(out).shape)`), then the counter may be + incremented on its own thread, while `x` can be incremented in + parallel on a separate thread. In the extreme case, it is conceivable + that the thread incrementing the counter runs until completion before + `x` is incremented even a single time. The only thing that can never + happen is that the thread updating `x` can never get ahead of the + counter thread because the thread incrementing `x` depends on the value + of the counter. + + ```python + import tensorflow as tf + + n = 10000 + x = tf.constant(list(range(n))) + c = lambda i, x: i < n + b = lambda i, x: (tf.compat.v1.Print(i + 1, [i]), tf.compat.v1.Print(x + 1, + [i], "x:")) + i, out = tf.while_loop(c, b, (0, x)) + with tf.compat.v1.Session() as sess: + print(sess.run(i)) # prints [0] ... [9999] + + # The following line may increment the counter and x in parallel. + # The counter thread may get ahead of the other thread, but not the + # other way around. So you may see things like + # [9996] x:[9987] + # meaning that the counter thread is on iteration 9996, + # while the other thread is on iteration 9987 + print(sess.run(out).shape) + ``` + """ + if not callable(cond): + raise TypeError("'cond' must be callable.") + if not callable(body): + raise TypeError("'body' must be callable.") + if parallel_iterations < 1: + raise TypeError("'parallel_iterations' must be a positive integer.") + + loop_vars = variable_utils.convert_variables_to_tensors(loop_vars) + + # Always enable control flow v2 if building a function, regardless of toggle. + executing_eagerly = context.executing_eagerly() + if (util.EnableControlFlowV2(ops.get_default_graph()) and + not executing_eagerly): + return while_v2.while_loop( + cond, + body, + loop_vars, + shape_invariants=shape_invariants, + parallel_iterations=parallel_iterations, + maximum_iterations=maximum_iterations, + name=name, + return_same_structure=return_same_structure, + back_prop=back_prop) + + with ops.name_scope(name, "while", loop_vars): + if not loop_vars: + raise ValueError("'loop_vars' must be provided.") + try_to_pack = (len(loop_vars) == 1 and not return_same_structure) + if maximum_iterations is not None: + maximum_iterations = ops.convert_to_tensor( + maximum_iterations, name="maximum_iterations") + if maximum_iterations.shape.ndims != 0: + raise ValueError("'maximum_iterations' must be a scalar. " + f"Received shape: {maximum_iterations.shape}") + + if executing_eagerly: + counter = 0 + maximum_iterations = int(maximum_iterations.numpy()) + else: + counter = constant_op.constant( + 0, dtype=maximum_iterations.dtype, name="iteration_counter") + orig_cond = cond + orig_body = body + if try_to_pack: + loop_vars = (counter, loop_vars[0]) + cond = lambda i, lv: ( # pylint: disable=g-long-lambda + math_ops.logical_and(i < maximum_iterations, orig_cond(lv))) + body = lambda i, lv: (i + 1, orig_body(lv)) + else: + loop_vars = (counter, loop_vars) + cond = lambda i, lv: ( # pylint: disable=g-long-lambda + math_ops.logical_and(i < maximum_iterations, orig_cond(*lv))) + body = lambda i, lv: (i + 1, orig_body(*lv)) + try_to_pack = False + + if executing_eagerly: + packed = False # whether the body result was packed into a 1-item tuple + + loop_var_structure = nest.map_structure(type_spec.type_spec_from_value, + list(loop_vars)) + while cond(*loop_vars): + loop_vars = body(*loop_vars) + if try_to_pack and not isinstance(loop_vars, (list, tuple)): + packed = True + loop_vars = (loop_vars,) + nest.assert_same_structure(loop_var_structure, list(loop_vars)) + + def convert(x): + if isinstance(x, tensor_array_ops.TensorArray): + return x + return ops.convert_to_tensor(x) + + loop_vars = nest.map_structure(convert, loop_vars, expand_composites=True) + if maximum_iterations is not None: + return loop_vars[1] + else: + return loop_vars[0] if packed else loop_vars + + if shape_invariants is not None: + if maximum_iterations is not None: + shape_invariants = (tensor_shape.TensorShape([]), shape_invariants) + + loop_context = control_flow_ops.WhileContext( + maximum_iterations=maximum_iterations, + parallel_iterations=parallel_iterations, + back_prop=back_prop, + swap_memory=swap_memory) + # Only add non-nested loops to the collection. Any nested control flow will + # be encapsulated in the root context. + if loop_context.outer_context is None: + ops.add_to_collection(ops.GraphKeys.WHILE_CONTEXT, loop_context) + result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants, + return_same_structure) + if maximum_iterations is not None: + return result[1] + else: + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..637adc81f431c9aea3ff5c513b2cd14a894daac0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2.py @@ -0,0 +1,1410 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""while_v2 and gradient. + +This is a version of while_loop that emits a single While op, as well as the +gradient function for While ops produced by while_loop. This will eventually +replace the current tf.while_loop implementation once it reaches feature and +performance parity. +""" +import collections + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.eager import backprop_util +from tensorflow.python.framework import auto_control_deps_utils as acd +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util as util_v1 +from tensorflow.python.ops import control_flow_util_v2 as util +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gradients_util +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_v2_indexed_slices_rewriter +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util import variable_utils + +# pylint: disable=protected-access + + +def while_loop(cond, + body, + loop_vars, + shape_invariants=None, + parallel_iterations=10, + maximum_iterations=None, + name=None, + return_same_structure=True, + back_prop=True): + """Like tf.while_loop, except emits a single While op.""" + loop_vars = variable_utils.convert_variables_to_tensors(loop_vars) + # Keep the original loop_vars around to know which args were TensorArrays. + orig_loop_vars = loop_vars + flat_orig_loop_vars = nest.flatten(orig_loop_vars, expand_composites=True) + # Cache its length since we use it at multiple places below. + len_orig_loop_vars = len(orig_loop_vars) + + # Convert TensorArrays to their flow variables. These get converted back to + # TensorArrays before calling `cond` and `body`. See `wrapped_cond` and + # `wrapped_body` below. + loop_vars = _tensor_array_to_flow(loop_vars) + loop_vars = nest.map_structure( + indexed_slices.internal_convert_to_tensor_or_indexed_slices, + loop_vars, + expand_composites=True) + + # `loop_vars_signature` is a structure of TypeSpecs and has the same + # structure with the `orig_loop_vars`. If `shape_invariants` is not None, its + # shape information comes from `shape_invariants` instead of `orig_loop_vars`. + # It is used to pack flattened vars into structured vars. + if shape_invariants is not None: + loop_vars_signature = nest.map_structure( + control_flow_ops._shape_invariant_to_type_spec, + loop_vars, shape_invariants) + else: + loop_vars_signature = nest.map_structure( + control_flow_ops._shape_invariant_to_type_spec, loop_vars) + + flat_shape_invariants = nest.map_structure( + lambda spec: spec.shape, + nest.flatten(loop_vars_signature, expand_composites=True)) + + if not name: + name = "while" + + with ops.name_scope(name) as scope: + with ops.name_scope(None): + cond_name = util.unique_fn_name(scope, "cond") + body_name = util.unique_fn_name(scope, "body") + maximum_iterations_loop_var = _build_maximum_iterations_loop_var( + maximum_iterations) + loop_counter = constant_op.constant( + 0, + dtype=maximum_iterations_loop_var.dtype + if maximum_iterations is not None else None, + name="loop_counter") + # Add loop counter needed for computing gradients. + loop_vars = [loop_counter, maximum_iterations_loop_var] + list(loop_vars) + + func_graph_signature = ( + [tensor_spec.TensorSpec.from_tensor(loop_counter), + tensor_spec.TensorSpec.from_tensor(maximum_iterations_loop_var)] + + list(loop_vars_signature)) + + # Automatic control dependencies are added in defuns, but not in v1 + # graphs. Propagate that behavior here. + add_control_dependencies = ops.get_default_graph()._add_control_dependencies + + def wrapped_cond(loop_counter, maximum_iterations_arg, *args): + """Extra `cond` wrapper that can handle the extra counter loop_var.""" + # Convert the flow variables in `args` to TensorArrays. `args` should + # already have the same structure as `orig_loop_vars` but currently there + # is no nest.zip so we call `_pack_sequence_as` which flattens `args`, + # converts flows in `args` to TensorArrays and packs it into the + # structure of `loop_vars_signature`. + pred = cond( + *_pack_sequence_as(loop_vars_signature, flat_orig_loop_vars, args)) + if (tensor_util.is_tf_type(pred) and + (pred.shape.dims is None or pred.shape.dims)): + pred = array_ops.squeeze_v2(pred) + + if maximum_iterations is None: + return pred + else: + return math_ops.logical_and( + loop_counter < maximum_iterations_arg, pred) + + # NOTE(skyewm): we set collections to the outer graph's collections for + # compatibility with TPUEstimator. + cond_graph = func_graph_module.func_graph_from_py_func( + cond_name, + wrapped_cond, + [], # We provide signature instead of args. + {}, + signature=func_graph_signature, + func_graph=util.WhileCondFuncGraph( + cond_name, collections=ops.get_default_graph()._collections), # pylint: disable=protected-access + add_control_dependencies=add_control_dependencies) + + def wrapped_body(loop_counter, maximum_iterations_arg, *args): + """Loop body augmented with counter update. + + Args: + loop_counter: Loop counter which needs to be incremented in the body. + maximum_iterations_arg: Maximum iterations of the loop. + *args: List of args + + Returns: + A list of tensors the same length as args. + """ + # The function was created with a signature rather than tensors, so + # internal placeholders were created without handle data. + _copy_handle_data(nest.flatten(loop_vars[2:], expand_composites=True), + nest.flatten(args, expand_composites=True)) + # Capture the tensors already captured in cond_graph so that they appear + # in the same order in body_graph.external_captures. + for t in cond_graph.external_captures: + ops.get_default_graph().capture(t) + + # Convert the flow variables in `args` to TensorArrays. `args` should + # already have the same structure as `orig_loop_vars` but currently there + # is no nest.zip so we call `_pack_sequence_as` which flattens `args`, + # converts flows in `args` to TensorArrays and packs it into the + # structure of `loop_vars_signature`. + outputs = body( + *_pack_sequence_as(loop_vars_signature, flat_orig_loop_vars, args)) + if not nest.is_nested(outputs): + outputs = [outputs] + try: + # The legacy while_loop considers list and tuple to be the same + # structure. + nest.assert_same_structure(outputs, orig_loop_vars, check_types=False, + expand_composites=True) + except ValueError: + # Traditionally we consider variables and tensors to be the same + # structure. + vars1 = variable_utils.convert_variables_to_tensors(outputs) + vars2 = variable_utils.convert_variables_to_tensors(orig_loop_vars) + nest.assert_same_structure(vars1, vars2, check_types=False, + expand_composites=True) + outputs = _tensor_array_to_flow(outputs) + + # TODO(srbs): Update lowering code to create _Enter nodes with + # is_constant=True for inputs that are directly passed to outputs. + return [loop_counter + 1, maximum_iterations_arg] + list(outputs) + + body_graph = func_graph_module.func_graph_from_py_func( + body_name, + wrapped_body, + [], # We provide signature instead of args. + {}, + signature=func_graph_signature, + func_graph=util.WhileBodyFuncGraph( + body_name, collections=ops.get_default_graph()._collections), # pylint: disable=protected-access + add_control_dependencies=add_control_dependencies) + # Add external captures of body to the list of loop vars. + # Note that external tensors will be treated as loop invariants, i.e., + # the value of that tensor in each iteration is the same as it was at the + # beginning of the loop execution. + deferred_external_captures = nest.flatten( + [c() for c in body_graph.deferred_external_captures], + expand_composites=True) + loop_vars = ( + loop_vars + body_graph.external_captures + deferred_external_captures) + # TODO(srbs): Update lowering code to create _Enter nodes with + # is_constant=True for inputs that are directly passed to outputs. + body_graph.outputs.extend(body_graph.internal_captures) + body_graph.outputs.extend(body_graph.deferred_internal_captures) + + # Capture the extra `external_captures` of `body_graph` in `cond_graph` so + # that it expects to receive those as arguments. + with cond_graph.as_default(): + num_cond_captures = len(cond_graph.external_captures) + assert (cond_graph.external_captures == + body_graph.external_captures[:num_cond_captures]) + _duplicate_body_captures_in_cond( + cond_graph, body_graph.external_captures[num_cond_captures:] + + deferred_external_captures) + + # Make sure that the shapes of the loop outputs are compatible with the + # shape invariants, or the shapes of the loop vars if the invariants are not + # specified. + num_flattened_outputs = len(nest.flatten(orig_loop_vars, + expand_composites=True)) + # First var is loop counter and second var is maximum_iterations. + first_loop_var_index = 2 + _check_shapes_compat( + body_graph.outputs[first_loop_var_index:first_loop_var_index + + num_flattened_outputs], + flat_shape_invariants, + nest.flatten(loop_vars[first_loop_var_index:first_loop_var_index + + len_orig_loop_vars], expand_composites=True)) + + num_original_outputs = len(body_graph.outputs) + if back_prop and util.output_all_intermediates(): + # Export all tensors in the loop body that may be needed for gradient + # computation. We do this by accumulating the intermediate values in + # TensorLists. + intermediate_tensors = _get_intermediates(body_graph) + + for intermediate_tensor in intermediate_tensors: + tensor_list = list_ops.empty_tensor_list( + element_dtype=intermediate_tensor.dtype, + element_shape=intermediate_tensor.shape, + max_num_elements=maximum_iterations) + loop_vars.append(tensor_list) + with cond_graph.as_default(): + # Add a placeholder to cond_graph's inputs corresponding to the + # tensor_list. + cond_graph.capture(tensor_list) + with body_graph.as_default(): + # Push the intermediate tensor to the tensor list. This captures the + # `tensor_list` as well. + appended_tensor_list = list_ops.tensor_list_push_back( + tensor_list, intermediate_tensor) + # Add this modified tensor list to the list of outputs. + body_graph.outputs.append(appended_tensor_list) + + flattened_loop_vars = nest.flatten(loop_vars, expand_composites=True) + _check_num_inputs_outputs(cond_graph, body_graph, + len(flattened_loop_vars)) + _check_inputs_outputs_types_match(body_graph, flattened_loop_vars) + + with ops.control_dependencies( + list(cond_graph.function_captures.control) + list( + body_graph.function_captures.control)): + output_shapes = [t.shape for t in body_graph.outputs] + orig_loop_vars_range = slice(first_loop_var_index, + first_loop_var_index + num_flattened_outputs) + output_shapes[orig_loop_vars_range] = flat_shape_invariants + + outputs = _build_while_op( + flattened_loop_vars, + cond_graph, + body_graph, + output_shapes=output_shapes, + parallel_iterations=parallel_iterations, + name=scope, + num_original_outputs=num_original_outputs) + if not ops.get_default_graph().building_function: + # In V1 graph mode, return identities for each output of the While op, + # rather than the output of the While op directly. This makes pruning work + # if the output of while_loop() is fetched: the lowering pass converts the + # While outputs into IdentityN outputs, which if fetched will cause all + # ops in the body to be run (since it takes all exit ops as input). After + # lowering, each output identity op will end up with only the appropriate + # exit op as input. + outputs = tuple(array_ops.identity(t) for t in outputs) + + output_loop_vars = outputs[first_loop_var_index:first_loop_var_index + + num_flattened_outputs] + if not back_prop: + output_loop_vars = [array_ops.stop_gradient(t) for t in output_loop_vars] + outputs = _pack_sequence_as( + loop_vars_signature, flat_orig_loop_vars, output_loop_vars) + + if return_same_structure: + return outputs + + flattened_outputs = nest.flatten(outputs, expand_composites=True) + if len(flattened_outputs) == 1: + return flattened_outputs[0] + else: + return outputs + + +@ops.RegisterGradient("StatelessWhile") +@ops.RegisterGradient("While") +def _WhileGrad(op: ops.Operation, *grads): # pylint: disable=invalid-name + """The gradient of a While op produced by while_loop.""" + # Note that op is not always the same as while_op because the gradient tape, + # for eager mode compatibility, forgets information about the proper op. Since + # the loop cannot run in eager mode, however, we can safely introspect into + # the graph here. + while_op = op.outputs[0].op + cond_graph = _get_graph(while_op, "cond", "_cond_graph") + body_graph = _get_graph(while_op, "body", "_body_graph") + orig_num_params = len(body_graph.outputs) + + maximum_iterations = op.inputs[1] + parallel_iterations = op.get_attr("parallel_iterations") + + try: + num_original_outputs = while_op.get_attr("_num_original_outputs") + except: # pylint: disable=bare-except + num_original_outputs = len(while_op.outputs) + + num_intermediates = len(while_op.outputs) - num_original_outputs + grads = [ + _preprocess_grad(grad, body_out, while_in, while_out) # pylint: disable=g-complex-comprehension + for grad, body_out, while_in, while_out in zip( + grads[:num_original_outputs], + body_graph.outputs[:num_original_outputs], + while_op.inputs[:num_original_outputs], + while_op.outputs[:num_original_outputs]) + ] + [None] * num_intermediates + + # Skip gradients with respect to the captures whenever possible. + if getattr(op, "skip_input_indices", None) is not None: + captures_start_index = ( + len(body_graph.inputs) - len(body_graph.internal_captures)) + for i in op.skip_input_indices: + if i >= captures_start_index: + grads[i] = None + + # We compute the gradient for the sub-graph between trainable ys and xs + # with non-None incoming gradients. We later pad the None's to the list of + # outputs. + ys, xs, non_none_grads = zip(*[(y, x, grad) for (y, x, grad) in zip( + body_graph.outputs, body_graph.inputs, grads) if grad is not None]) + + body_grad_graph, args = _create_grad_func( + ys, xs, non_none_grads, cond_graph, body_graph, + util.unique_grad_fn_name(body_graph.name), op, maximum_iterations) + + if body_grad_graph.while_op_needs_rewrite: + # Modify 'op' to output the intermediate accumulators needed by the grad + # function. + # NOTE(skyewm): if there are any active sessions, this modification to `op` + # may make them unrunnable! + + cond_graph.name += "_rewritten" + body_graph.name += "_rewritten" + + # `body_grad_graph.extra_inputs` here is equivalent to skimming off the new + # `body_graph.external_captures` added during `_create_grad_func`. + new_inputs = body_grad_graph.extra_inputs + new_outputs = body_graph.outputs[orig_num_params:] + + while_op._set_func_attr("cond", util.create_new_tf_function(cond_graph)) + while_op._set_func_attr("body", util.create_new_tf_function(body_graph)) + if len(body_graph.output_types) != len(while_op.inputs) + len(new_inputs): + # Continuing leads to an invalid graph with disconnected inputs. + raise AssertionError( + "Inputs and outputs constructed for the forward op of a While " + "gradient don't match with 'output_types' at " + f"{len(body_graph.output_types)},'inputs' at length " + f"{len(while_op.inputs)}, and 'new_inputs' at length " + f"{len(new_inputs)}. This doesn't make sense, please file a bug.") + while_op._set_type_list_attr("T", body_graph.output_types) + while_op._set_shape_list_attr("output_shapes", body_graph.output_shapes) + while_op._add_while_inputs(new_inputs) + while_op._add_outputs([t.dtype for t in new_outputs], + [t.shape for t in new_outputs]) + _copy_handle_data(new_outputs, while_op.outputs[orig_num_params:]) + + # Do not ignore grads wrt extra outputs when computing higher order + # derivatives. + while_op._set_attr("_num_original_outputs", + attr_value_pb2.AttrValue(i=len(while_op.outputs))) + + captured_inputs = _resolve_grad_captures(body_graph, body_grad_graph, + while_op) + loop_vars = args + captured_inputs + + # This modifies body_grad_graph. + loop_vars = while_v2_indexed_slices_rewriter.rewrite_grad_indexed_slices( + grads, body_grad_graph, loop_vars, while_op.inputs) + + def grad_cond(counter, unused_maximum_iterations_arg, forward_loop_iters, + *unused_args): + return counter < forward_loop_iters + + grad_cond_name = util.unique_grad_fn_name(op.get_attr("cond").name) + cond_grad_graph = func_graph_module.func_graph_from_py_func( + grad_cond_name, grad_cond, loop_vars, {}, + func_graph=util.WhileCondFuncGraph(grad_cond_name)) + + _check_num_inputs_outputs(cond_grad_graph, body_grad_graph, len(loop_vars)) + + outputs = _build_while_op( + loop_vars, + cond_grad_graph, + body_grad_graph, + output_shapes=[t.shape for t in body_grad_graph.outputs], + parallel_iterations=parallel_iterations, + name="%s_grad" % while_op.name, + num_original_outputs=len(body_grad_graph.outputs)) + + # See comment in while_loop. + outputs = [array_ops.identity(t) for t in outputs] + return _get_structured_grad_output(outputs, grads, body_grad_graph) + + +def _build_while_op(loop_vars, cond_graph, body_graph, output_shapes, + parallel_iterations, name, num_original_outputs): + """Builds the functional StatelessWhile/While op.""" + cond_stateful_ops = [ + op for op in cond_graph.get_operations() if op._is_stateful + ] + body_stateful_ops = [ + op for op in body_graph.get_operations() if op._is_stateful + ] + if (cond_stateful_ops or body_stateful_ops): + op_fn = gen_functional_ops._while + else: + op_fn = gen_functional_ops.stateless_while + + def _make_op(inputs): + while_op, tensors = util.get_op_and_outputs(op_fn( + inputs, + util.create_new_tf_function(cond_graph), + util.create_new_tf_function(body_graph), + output_shapes=output_shapes, + parallel_iterations=parallel_iterations, + name=name)) + _copy_handle_data(body_graph.outputs, tensors) + util.maybe_set_lowering_attr(while_op) + util.maybe_propagate_compile_time_consts_in_xla(while_op) + _set_read_only_resource_inputs_attr(while_op, [cond_graph, body_graph]) + # This is needed so we do not compute derivative wrt these extra outputs. + while_op._set_attr("_num_original_outputs", + attr_value_pb2.AttrValue(i=num_original_outputs)) + # The while op may be created inside a tf.function, in which case ops + # needs to capture "through" it when taking gradients; outer_graph is used + # as a sanity check that capturing only happens from parent to child. + cond_graph.outer_graph = ops.get_default_graph() + body_graph.outer_graph = ops.get_default_graph() + while_op._cond_graph = cond_graph + while_op._body_graph = body_graph + return tensors + return util.run_as_function_for_tape_gradients(_make_op, loop_vars) + + +def _get_intermediates(func_graph): + """Returns all tensors in `func_graph` that should be accumulated.""" + # We currently accumulate output tensors of most ops in the function and rely + # on the pruning pass to get rid of the unused accumulators at runtime. + # However, this can bloat the GraphDef and make debugging harder so we perform + # some optimizations. + # + # Optimization we currently perform: + # 1. We do not accumulate tensors which already have an accumulator + # in the loop body. + # 2. We do not accumulate outputs of Identity nodes. When building the + # FuncGraph, we add an Identity node for each output (see + # `AutomaticControlDependencies.mark_as_return`). Accumulating outputs + # of all these nodes bloats the GraphDef quite a bit so we remove those. + # Since the gradient of an Identity node does not rely on its forward op's + # input this is safe to do. + # + # Other possible optimizations: + # 1. Only accumulate tensors that will be required by the backward pass. + # This will require running the gradient pass and hence would increase the + # graph building time for the forward pass. + # 2. Do not accumulate Const nodes created inside the loop body. + # 3. Do not accumulate loop vars that are returned as-is just like captured + # tensors. + intermediates = [] + reverse_captures = dict((v.ref(), k) for k, v in func_graph.captures) + + for op in func_graph.get_operations(): + if op.type == "Identity": + continue + # Accumulating mutexes can cause deadlock. + if op.type == "MutexLock": + continue + for o in op.outputs: + if (o is not func_graph.inputs[0] and # Loop counter. + o.dtype != dtypes.resource and # Do not accumulate resource tensors. + _get_accumulator(o) is None and # Has existing accumulator. + o.ref() not in reverse_captures + ): # Captured value, hence loop invariant. + intermediates.append(o) + return intermediates + + +def _preprocess_grad(grad, body_graph_output, while_op_input, while_op_output): + """Returns the initial gradient to be used for a given output tensor. + + Args: + grad: the original gradient Tensor passed to the gradient function. + body_graph_output: the corresponding Tensor in the body graph. + while_op_input: the corresponding Tensor input of the While op. + while_op_output: the corresponding Tensor output of the While op. + + Returns: + A Tensor or None. + """ + # Set the incoming gradient of non-trainable inputs to None. It is possible + # that we receive non-None gradients for non-trainable types in nested while + # loops because we accumulate outputs of the inner while as variant tensors + # which are trainable and hence receive zeros_like tensors in the gradient + # pass. The non-trainable tensors then receive the popped zeros tensor from + # this zeros variant. The gradient for the loop vars corresponding to these + # tensors is None or zeros (this happens only if the loop var is accumulated + # as well) in _grad_fn so we reset these. + # TODO(b/118712257): Remove once we can handle None output grads in _grad_fn. + if not _is_trainable(body_graph_output): + return None + + # GradientTape initializes resource and variant grads as None instead of + # zeros. Set to zeros so _GradientsHelper computes the gradients instead of + # returning None. + # TODO(b/143286622): The supports_default_grad check is needed + # because While op emits non-differentiable resource tensors + # as outputs. Remove this check when that is not the case. + # Note: We use `while_op_input` instead of `while_op_output` for the call + # to `supports_default_grad` because `while_op_output` may be missing + # handle_data if the While is in a restored saved model. + if (while_op_output.dtype in (dtypes.resource, dtypes.variant) and + default_gradient.supports_default_grad(while_op_input) and grad is None): + return _zeros_like(while_op_input, while_op_output) + + # Convert IndexedSlices to dense tensors since it is unlikely that downstream + # gradient functions with properly handle indexed slices. This is similar to + # what we do in tf.function gradients. + if isinstance(grad, indexed_slices.IndexedSlices): + return ops.convert_to_tensor(grad) + + return grad + + +# TODO(skyewm): make this return constants if op_output's shape is fully +# defined (this can be done by checking the "shape" attr of resource vars). +def _zeros_like(op_input, op_output): + """Like array_ops.zeros_like() but also accepts resource var handles.""" + if op_output.dtype == dtypes.resource: + # Note: We use `op_input` instead of `op_output` to get the zeros dtype + # because `op_output` may be missing handle_data if the While is in a + # restored saved model. + return array_ops.zeros( + gen_resource_variable_ops.variable_shape(op_output), + dtype=default_gradient.get_zeros_dtype(op_input)) + return array_ops.zeros_like(op_output) + + +def _is_trainable(tensor): + """Returns whether the given tensor is trainable.""" + if not backprop_util.IsTrainable(tensor): + return False + + # Special case: untrainable accumulator output. The gradients algorithm + # doesn't know about tensor lists of untrainable elements. In theory the + # tensor list gradient functions should return None as appropriate, but + # because we can't return None from the gradient function we filter out + # untrainable accumulator output here to avoid computing the gradient at all. + if tensor.op.type == "TensorListPopBack" and tensor.value_index == 0: + assert tensor.dtype == dtypes.variant + element_type = tensor.op.get_attr("element_dtype") + return backprop_util.IsTrainable(element_type) + + return True + + +def _get_graph(while_op, func_attr_name, attr_graph_name): + """Returns `FuncGraph` for the given function attribute. + + Args: + while_op: The While Operation. + func_attr_name: string + attr_graph_name: cached forward graph name + + Returns: + `FuncGraph` + """ + func_graph = getattr(while_op, attr_graph_name, None) + if func_graph is None: + # TODO(srbs): Handle TensorShapeProto in function_def_to_graph.input_shapes. + input_shapes = [ + tensor_shape.TensorShape(s) for s in while_op.get_attr("output_shapes") + ] + func_name = while_op.get_attr(func_attr_name).name + func_graph = util.get_func_graph(while_op, input_shapes, func_name) + func_graph._while = while_op + return func_graph + + +def _create_grad_func(ys, xs, grads, cond_graph, body_graph, name, while_op, + maximum_iterations): + """Builds and returns the gradient FuncGraph of `func_graph` and its args. + + The returned grad_func_graph must be called with the returned + args + grad_func_graph.captures. + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + grads: The incoming grads for `ys`. + cond_graph: FuncGraph for the forward cond function. + body_graph: FuncGraph for the forward body function. + name: Name of the returned gradient function. + while_op: The forward While op. + maximum_iterations: Tensor. The maximum number of iterations. + + Returns: + 2-tuple of (grad_func_graph, args). + """ + assert len(ys) == len(grads) + + total_iters = while_op.outputs[0] + counter = constant_op.constant( + 0, dtype=total_iters.dtype, name="grad_counter") + + # Build frozen sets so that we do not have linear time lookups in + # `_is_loop_invariant`. Note: `body_graph.inputs` and `body_graph.outputs` + # may get updated during gradient computation because we add accumulators to + # the forward op. However, those are not loop invariants so wouldn't affect + # the output of `_is_loop_invariant`. Also we would never attempt to capture + # those accumulators so `_is_loop_invariant` should never receive those new + # tensors as args. + body_graph_inputs = object_identity.ObjectIdentitySet(body_graph.inputs) + body_graph_outputs = object_identity.ObjectIdentitySet(body_graph.outputs) + + args = [counter, maximum_iterations, total_iters] + list(grads) + # Note: The returned function does not have `args` in the list of + # `external_captures`. + grad_func_graph = func_graph_module.func_graph_from_py_func( + name, + lambda *args: _grad_fn(ys, xs, args, body_graph), + args, {}, + func_graph=_WhileBodyGradFuncGraph(name, cond_graph, body_graph, + maximum_iterations, while_op, + body_graph_inputs, body_graph_outputs)) + + # Update the list of outputs with tensors corresponding to the captured + # tensors. We capture 3 types of tensors when building the grad fn: + # 1. Accumulators for forward graph intermediates which are not loop + # invariants. The outputs corresponding to these are populated in + # `internal_capture_to_output` by `_WhileBodyGradFuncGraph`. + # 2. Resources, which are output as is. + # 3. Forward graph loop invariants, which are output as is. + for external_capture, internal_capture in grad_func_graph.captures: + if (ops.tensor_id(internal_capture) + in grad_func_graph.internal_capture_to_output): + new_output = grad_func_graph.internal_capture_to_output[ops.tensor_id( + internal_capture)] + else: + raise ValueError( + f"Tensor {str(internal_capture)} which captures " + f"{str(external_capture)} is in list of " + f"internal_captures but not in internal_capture_to_output.") + grad_func_graph.outputs.append(new_output) + grad_func_graph.structured_outputs.append(new_output) + + return grad_func_graph, args + + +def _grad_fn(ys, xs, args, func_graph): + """Computes the gradient of `func_graph` in the current graph. + + This function builds the gradient graph of the corresponding forward-pass + `func_graph` by differentiating `func_graph`'s outputs w.r.t. its inputs. + + Args: + ys: A `Tensor` or list of tensors to be differentiated. + xs: A `Tensor` or list of tensors to be used for differentiation. + args: The input arguments. + args[0] - Loop counter + args[1] - Total number of iterations. + args[2] - maximum_iterations. + args[3:] - Incoming gradients for `ys`. + func_graph: function.FuncGraph. The corresponding forward-pass function. + + Returns: + The output gradient Tensors. + """ + grad_ys = args[3:] + + # Build the gradient graph. Note that this builds the gradient computation of + # func_graph in the current graph, which requires capturing tensors from + # func_graph. The captured func_graph tensors are resolved to external tensors + # after the forward While op has been rewritten in _resolve_grad_captures. + # TODO(srbs): Mark GradientsHelper as public? + grad_outs = gradients_util._GradientsHelper( + ys, xs, grad_ys=grad_ys, src_graph=func_graph, + unconnected_gradients="zero") + + # TODO(b/118712257): Handle the case when grad_outs has None's e.g. when there + # is a tf.StopGradient in the loop body. + assert all(g is not None for g in grad_outs) + counter = args[0] + maximum_iterations = args[1] + total_iters = args[2] + return [counter + 1, maximum_iterations, total_iters] + grad_outs + + +def _resolve_grad_captures(body_graph, body_grad_graph, while_op): + """Returns the tensors to pass as captured inputs to `body_grad_graph`. + + `body_grad_graph` may have external references to: + 1. Its outer graph containing the input gradients. These are left as-is. + 2. Accumulators captured from the forward-pass graph. These should have been + added as `while_op` outputs after the gradient graph was built. We replace + these with the corresponding output of `while_op`, i.e. a tensor in + `body_graph.outer_graph`. In the case of nested control flow or functions, + the gradient logic handling `body_grad_graph.outer_graph` will make sure + the tensor from `body_graph.outer_graph` is also correctly captured. + + Args: + body_graph: FuncGraph. The forward-pass body function. + body_grad_graph: FuncGraph. The body gradients function. + while_op: The forward-pass While Operation calling `body_graph`. + + Returns: + A list of input tensors to be passed as the captured inputs to + `body_grad_graph`. + """ + new_capture_inputs = [] + for t in body_grad_graph.external_captures: + # Resolve tensors captured from the forward graph to the outputs of the + # forward while_op. + if t.graph == body_graph: + # Captured accumulator or loop invariant. + for i, output in enumerate(t.graph.outputs): + if output is t: + t = while_op.outputs[i] + break + + # Note: We rely on the capturing logic of the gradient While op graph to + # correctly capture the tensors in `body_graph.outer_graph`. Both cond_v2 + # and while_v2 handle this while building their gradient functions. + assert t.graph == body_graph.outer_graph + + new_capture_inputs.append(t) + return new_capture_inputs + + +def _get_structured_grad_output(outputs, grads, body_grad_graph): + """Returns the values that should be returned from the while grad function. + + Args: + outputs: the raw Tensor outputs of the grad While op. + grads: the input gradients to the gradient function. + body_grad_graph: _WhileBodyGradFuncGraph. + + Returns: + A list of gradient values. May include Nones. + """ + result = [] + # outputs[0] is the loop counter. + # outputs[1] is maximum_iterations. + # outputs[2] is the total number of loop iterations. + outputs_idx = 3 + structured_outputs_idx = 3 + for g in grads: + # Set None as the output gradient for tensors with None input gradient. + if g is None: + result.append(None) + continue + output = body_grad_graph.structured_outputs[structured_outputs_idx] + structured_outputs_idx += 1 + if isinstance(output, indexed_slices.IndexedSlices): + # TODO(skyewm): is there a more robust way to determine the order of + # flattened IndexedSlices components? + result.append(indexed_slices.IndexedSlices( + values=outputs[outputs_idx], + indices=outputs[outputs_idx + 1], + dense_shape=outputs[outputs_idx + 2])) + outputs_idx += 3 + else: + assert isinstance(output, tensor_lib.Tensor) + result.append(outputs[outputs_idx]) + outputs_idx += 1 + + return result + + +def _get_accumulator(tensor): + r"""Returns TensorList if any containing accumulated values of tensor. + + We try to find a pattern of the form: + + input_tl tensor + \ / + (TensorListPushBack) + | + output_tl + + which satisfies the following conditions: + + 1. input_tl must be in tensor.graph.inputs. + 2. output_tl or Identity(output_tl) must be in tensor.graph.outputs. + 3. tensor.graph.input_index(input_tl) == tensor.graph.output_index(output_t). + + output_tl or Identity(output_tl) (whichever is in tensor.graph.outputs) is + returned if such a pattern is found else None is returned. + + Args: + tensor: The Tensor to be accumulated. + + Returns: + A variant tensor in the same graph as `tensor` or None if no accumulator is + found. + """ + assert isinstance(tensor.graph, func_graph_module.FuncGraph) + + def get_func_graph_output(t): + """Returns t or Identity(t) whichever exists in graph outputs else None.""" + for output in tensor.graph.outputs: + if output is t: + return t + # tf.defun adds an Identity for each output, check whether that is the case. + identity_op = t.consumers()[0] + if (identity_op.type == "Identity" and + any(identity_op.outputs[0] is t for t in tensor.graph.outputs)): + return identity_op.outputs[0] + return None + + for consumer in tensor.consumers(): + # Find the consumer that is a TensorListPushBack node whose TensorList input + # is in the list of function inputs. + if consumer.type != "TensorListPushBack": + continue + + accum_input_idx = -1 + for accum_input_idx, inp in enumerate(tensor.graph.inputs): + if inp is consumer.inputs[0]: + break + else: + continue + + output = get_func_graph_output(consumer.outputs[0]) + if output is None: + # The TensorList output of `consumer` is not in the list of function + # outputs. + continue + + for accum_output_idx, out in enumerate(tensor.graph.outputs): + if out is output: + if accum_input_idx == accum_output_idx: + return output + break + + return None + + +OptimizedReductionOpsCacheKey = collections.namedtuple( + "OptimizedReductionOpsCacheKey", [ + "op_type", + "inputs", + "dtypes", + "input_types", + "name", + "attrs", + "op_def", + "compute_device", + ]) + + +class _WhileBodyGradFuncGraph(util.WhileBodyFuncGraph): + """FuncGraph for the gradient function of the body of a While op. + + Contains the logic for capturing the tensors from the body of the forward + While op which is as follows: + 1. If the tensor is of resource type (these are not accumulated): + a. Ensure that the tensor is a loop invariant, i.e., it exists in both loop + inputs and outputs at the same index. + b. Lookup the corresponding resource tensor in the forward outer graph and + try to capture that. + 2. If the tensor is not of resource type: + a. Create an accumulator for that tensor and output it from the forward + pass. Note this also requires adding it as an input to the forward pass. + b. Capture the accumulator from the forward pass in this FuncGraph. This + will later be resolved to the correct output of the forward While op. + c. Pop a value from the captured placeholder and use it as the captured + value for the forward pass tensor. + + This only allows capturing tensors in the forward graph. A ValueError is + raised if an attempt is made to capture a tensor not in the forward graph. + To manually capture a tensor that is not in the forward graph, call `capture` + with `allowlisted=True`. + + Note: The `captures` dict does not contain the forward tensor since it is not + directly captured. It contains the accumulator corresponding to this forward + tensor. + + Attributes: + while_op_needs_rewrite: True if any non-resource intermediates were + captured, meaning the forward While op needs to be rewritten to output the + corresponding accumulators. + extra_inputs: list of EmptyTensorList tensors to be used as initial input to + the new accumulators in the forward graph. It may also contain external + captures of the custom gradient function. + internal_capture_to_output: dict from a tensor_id(captured placeholder) to + the corresponding tensor that needs to be added to the list of outputs. + For instance, when capturing an accumulator TensorList this contains the + TensorList obtained after popping a tensor from the list. Other entries + in this dict are expected, though not enforced, to be identities. + This dict is needed because these output tensors need to be added to + FuncGraph.outputs "after" the tensors returned from the gradient function. + """ + + def __init__(self, name, forward_cond_graph, forward_body_graph, + maximum_iterations, forward_while_op, body_graph_inputs, + body_graph_outputs): + super(_WhileBodyGradFuncGraph, self).__init__(name) + self.extra_inputs = [] + self.internal_capture_to_output = {} + # FuncGraph for the body of the forward While op. + self._forward_graph = forward_body_graph + # FuncGraph for the cond of the forward While op. + self._forward_cond_graph = forward_cond_graph + self._maximum_iterations = maximum_iterations + self._forward_while_op = forward_while_op + # Dict from forward intermediate tensor to its indirectly captured tensor + # in this graph. Indirect capturing happens in two ways: + # 1. For non-resource tensors we capture their accumulators from the forward + # outer graph and pop values from that accumulator inside this graph + # using TensorListPopBack. + # 2. For resource tensors we directly capture their corresponding tensor + # in the forward outer graph. + self._indirect_captures = {} + + @property + def while_op_needs_rewrite(self): + return self.extra_inputs + + def _create_op_internal( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + # For a reduction op, if op is in the gradient body graph and its input is + # from the forward graph, moving op to the forward graph means we would + # store the tensor after the reduction as opposed to the tensor before + # reduction, and therefore could significantly reduce memory consumption. + # For now, we do this only for a few ops. + # + # We don't do this if any input tensor has already been accumulated. This + # can happen if we output all intermediates in the forward pass. + # + # If in XLA context, do not move constant ops to forward pass as pushing to + # and popping from a TensorList removes the constant property of an op and + # breaks XLA compilation, which requires certain inputs to be compile-time + # constant for certain ops. + # + # This optimization is currently also disabled when under a persistent tape, + # since it leads to an unbounded number of side outputs. With caching it may + # be possible to re-enable it. + optimized_reduction_ops = { + "Shape", "Size", "Rank", "TensorListElementShape", "TensorListLength" + } + if (op_type in optimized_reduction_ops and + not util.output_all_intermediates() and + all(input.graph is self._forward_graph for input in inputs) and + all(_get_accumulator(input) is None for input in inputs) and + not util_v1.GraphOrParentsInXlaContext(self._forward_graph) and + not util.graph_wrapped_for_higher_order_tape_gradients( + self._forward_graph)): + return self._move_op_to_forward_graph( + op_type, + inputs, + dtypes=dtypes, + input_types=input_types, + name=name, + attrs=attrs, + op_def=op_def, + compute_device=compute_device) + + return super(_WhileBodyGradFuncGraph, self)._create_op_internal( + op_type, + inputs, + dtypes=dtypes, + input_types=input_types, + name=name, + attrs=attrs, + op_def=op_def, + compute_device=compute_device) + + def _move_op_to_forward_graph( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + # We have a cache of reduction ops that have already been moved to the + # forward graph, and we will check it first to avoid moving an op twice. + if not hasattr(self._forward_graph, "_optimized_reduction_ops_cache"): + self._forward_graph._optimized_reduction_ops_cache = {} + cache_key = self._get_optimized_reduction_ops_cache_key( + op_type, inputs, dtypes, input_types, name, attrs, op_def, + compute_device) + cached_op = self._forward_graph._optimized_reduction_ops_cache.get( + cache_key) + if cached_op is not None: + # This op has already been moved to the forward graph and we have it in + # the cache. + return cached_op + + with self._forward_graph.as_default(): + # `name` was built using name_scope stack of gradient graph and may not + # be unique in the forward graph. `Graph.create_op` does not uniquify + # names which are name scopes i.e. end in `/`. To ensure that the op + # created gets a unique name in the forward graph we get rid of the + # trailing slash. + name = ops.name_from_scope_name(name) + result = self._forward_graph._create_op_internal( + op_type, + inputs, + dtypes=dtypes, + input_types=input_types, + name=name, + attrs=attrs, + op_def=op_def, + compute_device=compute_device) + + # Store the op we just moved to the forward graph so that it does + # not need to be added there again. + self._forward_graph._optimized_reduction_ops_cache[cache_key] = result + return result + + def _get_optimized_reduction_ops_cache_key( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + # We need all elements of CacheKey to be hashable. + inputs = tuple(map(lambda t: t.ref(), inputs)) + + if dtypes is not None: + dtypes = tuple(dtypes) + + if input_types is not None: + input_types = tuple(input_types) + + if attrs is not None: + hashable_attrs = [] + for attr_name, attr_value in sorted(attrs.items()): + hashable_attrs.append((attr_name, attr_value.SerializeToString())) + attrs = tuple(hashable_attrs) + + if op_def is not None: + op_def = op_def.SerializeToString() + + return OptimizedReductionOpsCacheKey(op_type, inputs, dtypes, input_types, + name, attrs, op_def, compute_device) + + def _capture_helper(self, tensor, name): + """Implements the capturing described in the class docstring.""" + captured_tensor = self._indirect_captures.get(ops.tensor_id(tensor)) + if captured_tensor is not None: + return captured_tensor + + if tensor.graph is not self._forward_graph: + already_captured = id(tensor) in self.function_captures.by_val_internal + captured_tensor = super(_WhileBodyGradFuncGraph, self)._capture_helper( + tensor, name) + if not already_captured: + # Adds the captured tensor to the list of outputs so that the input + # and output signatures match. + self.internal_capture_to_output[ops.tensor_id( + captured_tensor)] = captured_tensor + self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor + return captured_tensor + + while tensor.op.type == "Identity": + # We do not accumulate the output of identity nodes so we try to capture + # the input of the Identity node instead. + tensor = tensor.op.inputs[0] + + captured_tensor = self._indirect_captures.get(ops.tensor_id(tensor)) + if captured_tensor is not None: + return captured_tensor + + # No need to accumulate loop invariants. Capture them directly. + # The captured tensor gets resolved to the corresponding while output in + # `_resolve_grad_captures`. + if _is_loop_invariant(tensor, self._forward_graph.inputs, + self._forward_graph.outputs): + captured_tensor = super(_WhileBodyGradFuncGraph, + self)._capture_helper(tensor, name) + # Add to `internal_capture_to_output` so that this gets added to the list + # of outputs. + self.internal_capture_to_output[ops.tensor_id( + captured_tensor)] = captured_tensor + self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor + return captured_tensor + + # Do not accumulate Const nodes. Instead copy them directly in the backward + # graph. + # TODO(srbs): This just checks for `Const` nodes. Consider checking for + # graph compile time consts in general. + # TODO(srbs): Consider making this a loop input. + if constant_op.is_constant(tensor): + real_value = constant_op.constant( + tensor_util.constant_value(tensor), dtype=tensor.dtype) + self._indirect_captures[ops.tensor_id(tensor)] = real_value + return real_value + + # Resource tensors are not accumulated and handled specially. + if tensor.dtype == dtypes.resource: + return self._resource_capture_helper(tensor) + + # Create or find an existing accumulator output for `tensor` in the forward + # graph, and fetch from this accumulator in the gradient graph to get the + # raw intermediate value. + accumulator = _get_accumulator(tensor) + if accumulator is None: + # Create the initial empty tensor list. + # + # Note: We clear the control dependencies to avoid a cycle in case a + # control tensor has an input path to an output of the forward While. + # + # E.g.: + # x = tf.while_loop(...) + # y = f(x) + # with tf.control_dependencies([y]): + # tf.gradients(y, x) + # + # Since the EmptyTensorList is fed back into the forward While, not + # removing the control edge would cause a cycle. + with self._forward_graph.outer_graph.as_default(): + with util.clear_control_inputs(): + tensor_list = list_ops.empty_tensor_list( + element_dtype=tensor.dtype, + element_shape=tensor.shape, + max_num_elements=self._maximum_iterations, + name=_build_accumulator_name(tensor)) + self.extra_inputs.append(tensor_list) + + # Push the intermediate tensor to the tensor list. This captures + # `tensor_list`. + with self._forward_graph.as_default(): + accumulator = list_ops.tensor_list_push_back(tensor_list, tensor) + # Add the modified tensor list to the list of outputs. This output will be + # all the accumulated values. + self._forward_graph.outputs.append(accumulator) + + # Capture in the cond graph as well so the forward cond and body inputs + # match. + with self._forward_cond_graph.as_default(): + self._forward_cond_graph.capture(tensor_list) + + # Capture the accumulator tensor list in the gradient graph directly from + # the forward graph -- we'll later modify this to capture the final list + # output by the forward While op instead. + captured_accumulator = super(_WhileBodyGradFuncGraph, self)._capture_helper( + accumulator, name) + + # Pop the intermediate value from the tensor list in the gradient graph. + new_tensor_list, captured_tensor = list_ops.tensor_list_pop_back( + captured_accumulator, element_dtype=tensor.dtype) + + self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor + self.internal_capture_to_output[ops.tensor_id( + captured_accumulator)] = new_tensor_list + return captured_tensor + + def _resource_capture_helper(self, tensor): + """Returns the captured resource tensor. + + Resource-type tensors are not accumulated. If a resource tensor exists in + the loop body it must either be a loop input or an output of a nested While + op inside the loop body which had captured the external resource. + + Args: + tensor: the external resource Tensor to be captured. + + Returns: + Tensor in this graph. + """ + assert tensor.dtype == dtypes.resource + + forward_graph_input_names = [t.name for t in self._forward_graph.inputs] + forward_graph_name_to_opdef = { + op.name: op.node_def for op in self._forward_graph.get_operations()} + index = util.resource_input_index( + tensor.name, forward_graph_input_names, + forward_graph_name_to_opdef, + self._forward_graph._functions) + + input_placeholder = self._forward_graph.inputs[index] + tensor_in_outer_graph = self._forward_graph._while.inputs[index] + + assert input_placeholder.dtype == dtypes.resource + assert tensor_in_outer_graph.dtype == dtypes.resource + # This must be a loop invariant. However, infrastructure + # (e.g. tf.vectorized_map) may insert identity nodes, function calls, conds, + # etc. which take and return the resource tensor unmodified; this means that + # the Python objects may differ. + if index != util.resource_input_index( + self._forward_graph.outputs[index].name, forward_graph_input_names, + forward_graph_name_to_opdef, + self._forward_graph._functions): + raise AssertionError( + f"Resource tensors must be loop invariants {tensor_in_outer_graph}") + + self._indirect_captures[ops.tensor_id(tensor)] = self.capture( + tensor_in_outer_graph) + return self._indirect_captures[ops.tensor_id(tensor)] + + +def _check_shapes_compat(flat_output_tensors, flat_shape_invariants, + flat_input_tensors): + for (t, shape, input_t) in zip(flat_output_tensors, flat_shape_invariants, + flat_input_tensors): + if not control_flow_ops._ShapeLessThanOrEqual(t.shape, shape): + raise ValueError( + f"Input tensor `{input_t.name}` enters the loop with shape {shape}, " + f"but has shape {t.shape} after one iteration. To allow the shape to " + "vary across iterations, use the `shape_invariants` argument of " + "tf.while_loop to specify a less-specific shape.") + + +def _check_num_inputs_outputs(cond_graph, body_graph, num_flattened_loop_vars): + """Checks the number of inputs/outputs of `cond_graph` and `body_graph`.""" + assert len(cond_graph.inputs) == num_flattened_loop_vars, ( + "cond_graph takes %d inputs; Expected: %d" % (len(cond_graph.inputs), + num_flattened_loop_vars)) + assert len(cond_graph.outputs) == 1, ( + "cond_graph has %d outputs; Expected: 1" % len(cond_graph.outputs)) + assert len(body_graph.inputs) == num_flattened_loop_vars, ( + "body_graph takes %d inputs; Expected: %d" % (len(body_graph.inputs), + num_flattened_loop_vars)) + assert len(body_graph.outputs) == num_flattened_loop_vars, ( + "body_graph has %d outputs; Expected: %d" % (len(body_graph.outputs), + num_flattened_loop_vars)) + + +def _check_inputs_outputs_types_match(body_graph, flattened_loop_vars): + for inp, out, loop_var in zip(body_graph.inputs, body_graph.outputs, + flattened_loop_vars): + if inp.dtype != out.dtype: + raise TypeError( + f"Loop var {loop_var.name} enters the loop with type {inp.dtype} " + f"but has type {out.dtype} after 1 iteration. {loop_var.name} type " + "should remain constant.") + + +def _build_cond_placeholders_name_prefix(cond_graph): + return cond_graph.unique_name(cond_graph.name + "___redundant_placeholder") + + +def _duplicate_body_captures_in_cond(cond_graph, body_graph_captures): + """Creates placeholders for body captures in cond_graph. + + This is needed to match signatures of cond and body graphs. + + Args: + cond_graph: cond branch graph + body_graph_captures: Tensors which were captured when building the + `body_graph`. + """ + types = [t.dtype.as_datatype_enum for t in body_graph_captures] + # TODO(srbs): Providing a unique prefix does not ensure that there is no + # conflict between the placeholder names and existing nodes in the graph. + # However passing a list of strings may not be performant. + # Ideally we should move `Graph.unique_name` to C++ or make + # `Graph._names_in_use` a trie so that we can find a unique prefix. + # TODO(b/143286622): This should not be required once captures are separated + # from regular loop vars. + with cond_graph._c_graph.get() as c_graph: + placeholders = c_api.TF_CreatePlaceholders( + c_graph, types, + compat.as_str(_build_cond_placeholders_name_prefix(cond_graph))) + placeholder_ops = [ + ops.Operation._from_c_op(ph.oper, cond_graph) for ph in placeholders + ] + + tensors = [] + for op in placeholder_ops: + tensors.append(op.outputs[0]) + + # Update `cond_graph._captures` and `cond_graph.inputs` to contain the + # newly created placeholders. + tuples = zip(body_graph_captures, tensors) + keys = [id(t) for t in body_graph_captures] + for k, v in zip(keys, tuples): + cond_graph._function_captures.add_or_replace( + key=k, + external=v[0], + internal=v[1], + is_by_ref=False) + cond_graph.inputs.extend(tensors) + + +def _copy_handle_data(src_tensors, tgt_tensors): + for src_t, tgt_t in zip(src_tensors, tgt_tensors): + handle_data_util.copy_handle_data(src_t, tgt_t) + + +def _pack_sequence_as(loop_vars_signature, flat_orig_loop_vars, loop_vars): + """Like `nest.pack_sequence_as` but also replaces flows with TensorArrays.""" + + def flow_to_tensor_array(flow, ta): # pylint: disable=missing-docstring + return (tensor_array_ops.build_ta_with_new_flow(ta, flow) if isinstance( # pylint: disable=g-long-ternary + ta, tensor_array_ops.TensorArray) else flow) + + flattened_loop_vars = [ + flow_to_tensor_array(*z) + for z in zip(nest.flatten(loop_vars, expand_composites=True), + flat_orig_loop_vars) + ] + return nest.pack_sequence_as(loop_vars_signature, flattened_loop_vars, + expand_composites=True) + + +def _tensor_array_to_flow(loop_vars): + + def f(maybe_ta): + if isinstance(maybe_ta, tensor_array_ops.TensorArray): + return maybe_ta.flow + return maybe_ta + + return nest.map_structure(f, loop_vars, expand_composites=True) + + +def _build_maximum_iterations_loop_var(maximum_iterations): + if maximum_iterations is None: + # Default value for max_num_elements to EmptyTensorList meaning that the + # list size is unbounded. + maximum_iterations = -1 + # EmptyTensorList expects `max_num_elements` to be of type int32. + return ops.convert_to_tensor( + maximum_iterations, dtype=dtypes.int32, name="maximum_iterations") + + +def _build_accumulator_name(tensor): + # Tensor name may be of the form "pow/y:0". Name scope does not allow ":". + return "{}/accumulator".format(tensor.name).replace(":", "_") + + +def _is_loop_invariant(tensor, inputs, outputs): + return (any(tensor is t for t in inputs) and + any(tensor is t for t in outputs)) + + +def _set_read_only_resource_inputs_attr(op: ops.Operation, branch_graphs): + """Sets the list of resource inputs which are read-only. + + This is used by AutomaticControlDependencies. + + Args: + op: While Operation. + branch_graphs: List of branch FuncGraphs. + """ + read_only_indices = set(range(len(op.inputs))) + for branch_graph in branch_graphs: + if not read_only_indices: + break + branch_read_only_indices = acd.get_read_only_resource_input_indices_graph( + branch_graph) + read_only_indices = read_only_indices.intersection(branch_read_only_indices) + + ops.set_int_list_attr(op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR, + sorted(read_only_indices)) + +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2_indexed_slices_rewriter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2_indexed_slices_rewriter.py new file mode 100644 index 0000000000000000000000000000000000000000..56e352a63c4207c602eeba84ef4c316a4bca7b06 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/ops/while_v2_indexed_slices_rewriter.py @@ -0,0 +1,292 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Methods for rewriting while_v2 grad functions with IndexedSlices output.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.util import nest + + +def rewrite_grad_indexed_slices(grads, body_grad_graph, loop_vars, + forward_inputs): + """Handles special case of IndexedSlices returned from while gradient. + + Some gradient functions return IndexedSlices instead of a Tensor (e.g. the + gradient of Gather ops). When this happens in the gradient of a while body, + the resulting gradient body function will have mismatched inputs and outputs, + since the input is a single Tensor, but the IndexedSlices gets unnested into + three output Tensors. + + This function fixes this by rewriting the gradient body to have three inputs + to match the three outputs, i.e., it effectively converts the input Tensor + into an input IndexedSlices. It also returns new `loop_vars` to reflect the + new inputs. + + Args: + grads: the input gradient Tensors to the while gradient computation. + body_grad_graph: _WhileBodyGradFuncGraph. + loop_vars: list of Tensors. The inputs to body_grad_graph. + forward_inputs: list of Tensors. The (flat) inputs to the forward-pass While + op. + + Returns: + The new loop_vars to pass to body_grad_graph. + """ + # Match up body_grad_graph.structured_outputs with the corresponding + # forward_inputs. + # + # Note that we don't expect a gradient computation to have structured output + # (e.g. no nested lists), so no need to flatten + # body_grad_graph.structured_outputs. However, structured_outputs may still + # contain composite tensors such as IndexedSlices, unlike + # body_grad_graph.outputs, which contains flattened composite tensors. + inputs_with_grads = [ + t for g, t in zip(grads, forward_inputs) if g is not None + ] + # Skip loop counter, maximum_iterations and total number of loop iterations. + structured_outputs = body_grad_graph.structured_outputs[3:] + + for forward_input, output in zip(inputs_with_grads, structured_outputs): + if not isinstance(output, indexed_slices.IndexedSlices): + continue + + if forward_input.dtype == dtypes.resource: + # TODO(skyewm): In theory we should use this for all captured inputs, not + # just resource handles (which can only be captured). We can do this by + # checking that forward_input is passed straight through to its output. + loop_vars = _rewrite_input_as_indexed_slices(body_grad_graph, output, + forward_input, loop_vars) + else: + _rewrite_output_as_tensor(body_grad_graph, output) + + return loop_vars + + +def _get_tensor_index_in_iterable(iterable, t): + """Returns index of first occurence of `t`, raises ValueError if not found.""" + for i, elem in enumerate(iterable): + if t is elem: + return i + raise ValueError(f"Element `{t!r}` is not found in iterable `{iterable!r}`.") + + +def _rewrite_output_as_tensor(body_grad_graph, grad_output_slices): + """Rewrites grad_output_slices to be a Tensor output. + + Args: + body_grad_graph: _WhileBodyGradFuncGraph. + grad_output_slices: IndexedSlices output of body_grad_graph. + """ + with body_grad_graph.as_default(): + new_output = tensor_conversion.convert_to_tensor_v2(grad_output_slices) + + idx = _get_tensor_index_in_iterable(body_grad_graph.structured_outputs, + grad_output_slices) + body_grad_graph.structured_outputs[idx] = new_output + body_grad_graph.outputs = func_graph.flatten( + body_grad_graph.structured_outputs) + + +def _rewrite_input_as_indexed_slices(body_grad_graph, grad_output_slices, + forward_input, loop_vars): + """Rewrites grad_output_slices's corresponding input to be an IndexedSlices. + + This rewrite requires that forward_input was captured in the forward loop, + i.e. is not a user-specified loop variable. This is important because the + rewrite assumes that forward_input is passed through to its corresponding + output unchanged. This assumption is used in _rewrite_input_as_indexed_slices, + which depends on the exact gradient structure produced by the input's fanout. + + This can yield a more efficient computation than using + _rewrite_output_as_tensor, since it preserves the IndexedSlices structure + instead of converting the IndexedSlices to a dense Tensor. + + Args: + body_grad_graph: _WhileBodyGradFuncGraph. + grad_output_slices: IndexedSlices output of body_grad_graph. + forward_input: the corresponding Tensor input to the forward loop. + loop_vars: list of Tensors. The inputs to body_grad_graph. + + Returns: + The new loop_vars to pass to body_grad_graph. + """ + # Create initial IndexedSlices that will be the input to the grad While + # op. This will start as zeros, and accumulate the IndexedSlices grad output. + # Note that because forward_input is captured and not a loop var, its incoming + # gradient should always be zero. + init_slices = _create_grad_indexed_slices_init(grad_output_slices, + forward_input) + + # Create a new version of grad_output_slices's gradient computation that uses + # the new IndexedSlices input instead of the original Tensor input. We'll + # return the new computation and leave the old computation as dead code. + # TODO(skyewm): considering pruning body_grad_graph to remove the old + # computation. + with body_grad_graph.as_default(): + input_slices = indexed_slices.IndexedSlices( + values=body_grad_graph.capture(init_slices.values, allowlisted=True), + indices=body_grad_graph.capture(init_slices.indices, allowlisted=True), + dense_shape=body_grad_graph.capture( + init_slices.dense_shape, allowlisted=True)) + + # Remove the captured tensors from the function inputs. We'll add them back + # at the correct index in _update_indexed_slices_param. + for t in _flatten(init_slices): + captured_t = body_grad_graph.captures.pop(t) + body_grad_graph.inputs.remove(captured_t) + + new_output_slices = _rewrite_grad_indexed_slices_output( + grad_output_slices, input_slices) + + # Update body_grad_graph's inputs and outputs to reflect the new + # IndexedSlices computation. + return _update_indexed_slices_param(body_grad_graph, loop_vars, init_slices, + input_slices, new_output_slices, + grad_output_slices) + + +def _create_grad_indexed_slices_init(grad_output_slices, forward_input): + """Creates an IndexedSlices to pass as input to the while grad function. + + Args: + grad_output_slices: IndexedSlices. The corresponding while grad function + output. + forward_input: Tensor. The corresponding input to the forward while op. + + Returns: + Zeros IndexedSlices, created in current Graph. + """ + assert isinstance(grad_output_slices, indexed_slices.IndexedSlices) + assert isinstance(forward_input, tensor.Tensor) + values_out = grad_output_slices.values + indices_out = grad_output_slices.indices + + # Create the initial values tensor. + if values_out.shape.is_fully_defined(): + values_shape = tensor_shape.TensorShape([0] + + values_out.shape.as_list()[1:]) + values = array_ops.zeros( + values_shape, dtype=values_out.dtype, name="values_init") + else: + if forward_input.dtype == dtypes.resource: + forward_shape = gen_resource_variable_ops.variable_shape(forward_input) + else: + forward_shape = array_ops.shape(forward_input) + values_shape = array_ops.concat([[0], forward_shape[1:]], 0) + values = array_ops.zeros( + values_shape, dtype=values_out.dtype, name="values_init") + + # Create the initial indices tensor. + indices = constant_op.constant([], indices_out.dtype, name="indices_init") + + # Create the initial dense_shape tensor. We assume is the same shape as + # forward_input, since captured tensors don't change shape across loop + # iterations. + if forward_input.dtype == dtypes.resource: + shape = gen_resource_variable_ops.variable_shape( + forward_input, name="shape_init") + else: + shape = array_ops.shape(forward_input, name="shape_init") + + return indexed_slices.IndexedSlices( + values=values, indices=indices, dense_shape=shape) + + +def _rewrite_grad_indexed_slices_output(old_output_slices, new_input_slices): + """Creates a new version of old_output_slices with new_input_slices as input. + + This method assumes that old_output_slices.{values,indices} are produced by + concatenating the incoming gradient Tensor input with the IndexedSlices + produced by the gradient computation of the while body. See + backprop.aggregate_indexed_slices_gradients for where these concats are + constructed. We build new concats that use new_input_slices instead of the + original Tensor input. + + Args: + old_output_slices: original IndexedSlices output of while gradient. + new_input_slices: new IndexedSlices to use as input to while gradient. + + Returns: + A new IndexedSlices to replace old_output_slices. + """ + + def rewrite(old_output, new_input): + assert old_output.type == "Identity" + concat_op = old_output.inputs[0].op + assert concat_op.type == "ConcatV2" + # Don't include axis arg + old_concat_args = concat_op.inputs[:-1] + # We assume that the original gradient input was the first argument to the + # concat op. + # TODO(skyewm): do this in a more robust way. + return array_ops.concat([new_input] + old_concat_args[1:], 0) + + values = rewrite(old_output_slices.values.op, new_input_slices.values) + indices = rewrite(old_output_slices.indices.op, new_input_slices.indices) + return indexed_slices.IndexedSlices( + values=values, indices=indices, dense_shape=new_input_slices.dense_shape) + + +def _update_indexed_slices_param(graph, loop_vars, init_slices, input_slices, + output_slices, old_output_slices): + """Updates graph with new IndexedSlices input/output. + + Updates graph's metadata to output the gradient computation defined by + init_slices, input_slices, and output_slices, instead of outputting + old_output_slices. Also returns a new version of loop_vars with init_slices + replacing the old input. + + Args: + graph: _WhileBodyGradFuncGraph. + loop_vars: the inputs to graph. + init_slices: the new IndexedSlices to use as input to graph. + input_slices: the new IndexedSlices in graph that should be fed by + init_slices. + output_slices: the new IndexedSlices in graph that should be the + corresponding output to input_slices. + old_output_slices: the IndexedSlices in graph that are currently being + output. + + Returns: + New loop_vars to pass to graph. + """ + structured_idx = _get_tensor_index_in_iterable(graph.structured_outputs, + old_output_slices) + # We assume that the component tensors of old_output_slices appear + # sequentially in graph.outputs. We use the first of these tensors + # as the reference index. + flat_idx = _get_tensor_index_in_iterable( + graph.outputs, + func_graph.flatten(old_output_slices)[0]) + + graph.structured_outputs[structured_idx] = output_slices + graph.outputs = func_graph.flatten(graph.structured_outputs) + + graph.inputs = ( + graph.inputs[:flat_idx] + _flatten(input_slices) + + graph.inputs[flat_idx + 1:]) + + return loop_vars[:flat_idx] + _flatten(init_slices) + loop_vars[flat_idx + 1:] + + +def _flatten(arg): + return nest.flatten(arg, expand_composites=True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3f9e0fe7b51c30d09799839aed6f9cced8989977 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def InfoAboutUnusedCPUFeatures() -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_stacktrace_handler.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_stacktrace_handler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..317d50843544d7dddc4484829356dc3f42127a39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_stacktrace_handler.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def InstallStacktraceHandler() -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_tf2.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_tf2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd6c39347b6d2870cfa313148e8e33999a82d0cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_tf2.pyi @@ -0,0 +1,17 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def enable(arg0: bool) -> None: ... +def is_enabled() -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/analytics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/analytics.py new file mode 100644 index 0000000000000000000000000000000000000000..5c482cb4619e6ff70a824ad36e0be4eaf5896a01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/analytics.py @@ -0,0 +1,24 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Analytics helpers library.""" + +def track_usage(tool_id, tags): + """No usage tracking for external library. + + Args: + tool_id: A string identifier for tool to be tracked. + tags: list of string tags that will be added to the tracking. + """ + del tool_id, tags # Unused externally. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/app.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/app.py new file mode 100644 index 0000000000000000000000000000000000000000..a2b6dc86dcb140f91a017b538463d787d5544acf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/app.py @@ -0,0 +1,36 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Generic entry point script.""" +import sys as _sys + +from absl.app import run as _run + +from tensorflow.python.platform import flags +from tensorflow.python.util.tf_export import tf_export + + +def _parse_flags_tolerate_undef(argv): + """Parse args, returning any unknown flags (ABSL defaults to crashing).""" + return flags.FLAGS(_sys.argv if argv is None else argv, known_only=True) + + +@tf_export(v1=['app.run']) +def run(main=None, argv=None): + """Runs the program with an optional 'main' function and 'argv' list.""" + + main = main or _sys.modules['__main__'].main + + _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/benchmark.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c32b1e87ecdc761466cee4d4f0bcd2145ec8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/benchmark.py @@ -0,0 +1,489 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Utilities to run benchmarks.""" +import math +import numbers +import os +import re +import sys +import time +import types + +from absl import app + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.core.util import test_log_pb2 +from tensorflow.python.client import timeline +from tensorflow.python.framework import ops +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +# When a subclass of the Benchmark class is created, it is added to +# the registry automatically +GLOBAL_BENCHMARK_REGISTRY = set() + +# Environment variable that determines whether benchmarks are written. +# See also tensorflow/core/util/reporter.h TestReporter::kTestReporterEnv. +TEST_REPORTER_TEST_ENV = "TEST_REPORT_FILE_PREFIX" + +# Environment variable that lets the TensorFlow runtime allocate a new +# threadpool for each benchmark. +OVERRIDE_GLOBAL_THREADPOOL = "TF_OVERRIDE_GLOBAL_THREADPOOL" + + +def _rename_function(f, arg_num, name): + """Rename the given function's name appears in the stack trace.""" + func_code = f.__code__ + new_code = func_code.replace(co_argcount=arg_num, co_name=name) + return types.FunctionType(new_code, f.__globals__, name, f.__defaults__, + f.__closure__) + + +def _global_report_benchmark( + name, iters=None, cpu_time=None, wall_time=None, + throughput=None, extras=None, metrics=None): + """Method for recording a benchmark directly. + + Args: + name: The BenchmarkEntry name. + iters: (optional) How many iterations were run + cpu_time: (optional) Total cpu time in seconds + wall_time: (optional) Total wall time in seconds + throughput: (optional) Throughput (in MB/s) + extras: (optional) Dict mapping string keys to additional benchmark info. + metrics: (optional) A list of dict representing metrics generated by the + benchmark. Each dict should contain keys 'name' and'value'. A dict + can optionally contain keys 'min_value' and 'max_value'. + + Raises: + TypeError: if extras is not a dict. + IOError: if the benchmark output file already exists. + """ + logging.info("Benchmark [%s] iters: %d, wall_time: %g, cpu_time: %g," + "throughput: %g, extras: %s, metrics: %s", name, + iters if iters is not None else -1, + wall_time if wall_time is not None else -1, + cpu_time if cpu_time is not None else -1, + throughput if throughput is not None else -1, + str(extras) if extras else "None", + str(metrics) if metrics else "None") + + entries = test_log_pb2.BenchmarkEntries() + entry = entries.entry.add() + entry.name = name + if iters is not None: + entry.iters = iters + if cpu_time is not None: + entry.cpu_time = cpu_time + if wall_time is not None: + entry.wall_time = wall_time + if throughput is not None: + entry.throughput = throughput + if extras is not None: + if not isinstance(extras, dict): + raise TypeError("extras must be a dict") + for (k, v) in extras.items(): + if isinstance(v, numbers.Number): + entry.extras[k].double_value = v + else: + entry.extras[k].string_value = str(v) + if metrics is not None: + if not isinstance(metrics, list): + raise TypeError("metrics must be a list") + for metric in metrics: + if "name" not in metric: + raise TypeError("metric must has a 'name' field") + if "value" not in metric: + raise TypeError("metric must has a 'value' field") + + metric_entry = entry.metrics.add() + metric_entry.name = metric["name"] + metric_entry.value = metric["value"] + if "min_value" in metric: + metric_entry.min_value.value = metric["min_value"] + if "max_value" in metric: + metric_entry.max_value.value = metric["max_value"] + + test_env = os.environ.get(TEST_REPORTER_TEST_ENV, None) + if test_env is None: + # Reporting was not requested, just print the proto + print(str(entries)) + return + + serialized_entry = entries.SerializeToString() + + mangled_name = name.replace("/", "__") + output_path = "%s%s" % (test_env, mangled_name) + if gfile.Exists(output_path): + raise IOError("File already exists: %s" % output_path) + with gfile.GFile(output_path, "wb") as out: + out.write(serialized_entry) + + +class _BenchmarkRegistrar(type): + """The Benchmark class registrar. Used by abstract Benchmark class.""" + + def __new__(mcs, clsname, base, attrs): + newclass = type.__new__(mcs, clsname, base, attrs) + if not newclass.is_abstract(): + GLOBAL_BENCHMARK_REGISTRY.add(newclass) + return newclass + + +@tf_export("__internal__.test.ParameterizedBenchmark", v1=[]) +class ParameterizedBenchmark(_BenchmarkRegistrar): + """Metaclass to generate parameterized benchmarks. + + Use this class as a metaclass and override the `_benchmark_parameters` to + generate multiple benchmark test cases. For example: + + class FooBenchmark(metaclass=tf.test.ParameterizedBenchmark, + tf.test.Benchmark): + # The `_benchmark_parameters` is expected to be a list with test cases. + # Each of the test case is a tuple, with the first time to be test case + # name, followed by any number of the parameters needed for the test case. + _benchmark_parameters = [ + ('case_1', Foo, 1, 'one'), + ('case_2', Bar, 2, 'two'), + ] + + def benchmark_test(self, target_class, int_param, string_param): + # benchmark test body + + The example above will generate two benchmark test cases: + "benchmark_test__case_1" and "benchmark_test__case_2". + """ + + def __new__(mcs, clsname, base, attrs): + param_config_list = attrs["_benchmark_parameters"] + + def create_benchmark_function(original_benchmark, params): + return lambda self: original_benchmark(self, *params) + + for name in attrs.copy().keys(): + if not name.startswith("benchmark"): + continue + + original_benchmark = attrs[name] + del attrs[name] + + for param_config in param_config_list: + test_name_suffix = param_config[0] + params = param_config[1:] + benchmark_name = name + "__" + test_name_suffix + if benchmark_name in attrs: + raise Exception( + "Benchmark named {} already defined.".format(benchmark_name)) + + benchmark = create_benchmark_function(original_benchmark, params) + # Renaming is important because `report_benchmark` function looks up the + # function name in the stack trace. + attrs[benchmark_name] = _rename_function(benchmark, 1, benchmark_name) + + return super().__new__(mcs, clsname, base, attrs) + + +class Benchmark(metaclass=_BenchmarkRegistrar): + """Abstract class that provides helper functions for running benchmarks. + + Any class subclassing this one is immediately registered in the global + benchmark registry. + + Only methods whose names start with the word "benchmark" will be run during + benchmarking. + """ + + @classmethod + def is_abstract(cls): + # mro: (_BenchmarkRegistrar, Benchmark) means this is Benchmark + return len(cls.mro()) <= 2 + + def _get_name(self, overwrite_name=None): + """Returns full name of class and method calling report_benchmark.""" + + # Find the caller method (outermost Benchmark class) + stack = tf_inspect.stack() + calling_class = None + name = None + for frame in stack[::-1]: + f_locals = frame[0].f_locals + f_self = f_locals.get("self", None) + if isinstance(f_self, Benchmark): + calling_class = f_self # Get the outermost stack Benchmark call + name = frame[3] # Get the method name + break + if calling_class is None: + raise ValueError("Unable to determine calling Benchmark class.") + + # Use the method name, or overwrite_name is provided. + name = overwrite_name or name + # Prefix the name with the class name. + class_name = type(calling_class).__name__ + name = "%s.%s" % (class_name, name) + return name + + def report_benchmark( + self, + iters=None, + cpu_time=None, + wall_time=None, + throughput=None, + extras=None, + name=None, + metrics=None): + """Report a benchmark. + + Args: + iters: (optional) How many iterations were run + cpu_time: (optional) Median or mean cpu time in seconds. + wall_time: (optional) Median or mean wall time in seconds. + throughput: (optional) Throughput (in MB/s) + extras: (optional) Dict mapping string keys to additional benchmark info. + Values may be either floats or values that are convertible to strings. + name: (optional) Override the BenchmarkEntry name with `name`. + Otherwise it is inferred from the top-level method name. + metrics: (optional) A list of dict, where each dict has the keys below + name (required), string, metric name + value (required), double, metric value + min_value (optional), double, minimum acceptable metric value + max_value (optional), double, maximum acceptable metric value + """ + name = self._get_name(overwrite_name=name) + _global_report_benchmark( + name=name, iters=iters, cpu_time=cpu_time, wall_time=wall_time, + throughput=throughput, extras=extras, metrics=metrics) + + +@tf_export("test.benchmark_config") +def benchmark_config(): + """Returns a tf.compat.v1.ConfigProto for disabling the dependency optimizer. + + Returns: + A TensorFlow ConfigProto object. + """ + config = config_pb2.ConfigProto() + config.graph_options.rewrite_options.dependency_optimization = ( + rewriter_config_pb2.RewriterConfig.OFF) + return config + + +@tf_export("test.Benchmark") +class TensorFlowBenchmark(Benchmark): + """Abstract class that provides helpers for TensorFlow benchmarks.""" + + def __init__(self): + # Allow TensorFlow runtime to allocate a new threadpool with different + # number of threads for each new benchmark. + os.environ[OVERRIDE_GLOBAL_THREADPOOL] = "1" + super().__init__() + + @classmethod + def is_abstract(cls): + # mro: (_BenchmarkRegistrar, Benchmark, TensorFlowBenchmark) means + # this is TensorFlowBenchmark. + return len(cls.mro()) <= 3 + + def run_op_benchmark(self, + sess, + op_or_tensor, + feed_dict=None, + burn_iters=2, + min_iters=10, + store_trace=False, + store_memory_usage=True, + name=None, + extras=None, + mbs=0): + """Run an op or tensor in the given session. Report the results. + + Args: + sess: `Session` object to use for timing. + op_or_tensor: `Operation` or `Tensor` to benchmark. + feed_dict: A `dict` of values to feed for each op iteration (see the + `feed_dict` parameter of `Session.run`). + burn_iters: Number of burn-in iterations to run. + min_iters: Minimum number of iterations to use for timing. + store_trace: Boolean, whether to run an extra untimed iteration and + store the trace of iteration in returned extras. + The trace will be stored as a string in Google Chrome trace format + in the extras field "full_trace_chrome_format". Note that trace + will not be stored in test_log_pb2.TestResults proto. + store_memory_usage: Boolean, whether to run an extra untimed iteration, + calculate memory usage, and store that in extras fields. + name: (optional) Override the BenchmarkEntry name with `name`. + Otherwise it is inferred from the top-level method name. + extras: (optional) Dict mapping string keys to additional benchmark info. + Values may be either floats or values that are convertible to strings. + mbs: (optional) The number of megabytes moved by this op, used to + calculate the ops throughput. + + Returns: + A `dict` containing the key-value pairs that were passed to + `report_benchmark`. If `store_trace` option is used, then + `full_chrome_trace_format` will be included in return dictionary even + though it is not passed to `report_benchmark` with `extras`. + """ + for _ in range(burn_iters): + sess.run(op_or_tensor, feed_dict=feed_dict) + + deltas = [None] * min_iters + + for i in range(min_iters): + start_time = time.time() + sess.run(op_or_tensor, feed_dict=feed_dict) + end_time = time.time() + delta = end_time - start_time + deltas[i] = delta + + extras = extras if extras is not None else {} + unreported_extras = {} + if store_trace or store_memory_usage: + run_options = config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE) + run_metadata = config_pb2.RunMetadata() + sess.run(op_or_tensor, feed_dict=feed_dict, + options=run_options, run_metadata=run_metadata) + tl = timeline.Timeline(run_metadata.step_stats) + + if store_trace: + unreported_extras["full_trace_chrome_format"] = ( + tl.generate_chrome_trace_format()) + + if store_memory_usage: + step_stats_analysis = tl.analyze_step_stats(show_memory=True) + allocator_maximums = step_stats_analysis.allocator_maximums + for k, v in allocator_maximums.items(): + extras["allocator_maximum_num_bytes_%s" % k] = v.num_bytes + + def _median(x): + if not x: + return -1 + s = sorted(x) + l = len(x) + lm1 = l - 1 + return (s[l//2] + s[lm1//2]) / 2.0 + + def _mean_and_stdev(x): + if not x: + return -1, -1 + l = len(x) + mean = sum(x) / l + if l == 1: + return mean, -1 + variance = sum([(e - mean) * (e - mean) for e in x]) / (l - 1) + return mean, math.sqrt(variance) + + median_delta = _median(deltas) + + benchmark_values = { + "iters": min_iters, + "wall_time": median_delta, + "extras": extras, + "name": name, + "throughput": mbs / median_delta + } + self.report_benchmark(**benchmark_values) + + mean_delta, stdev_delta = _mean_and_stdev(deltas) + unreported_extras["wall_time_mean"] = mean_delta + unreported_extras["wall_time_stdev"] = stdev_delta + benchmark_values["extras"].update(unreported_extras) + return benchmark_values + + def evaluate(self, tensors): + """Evaluates tensors and returns numpy values. + + Args: + tensors: A Tensor or a nested list/tuple of Tensors. + + Returns: + tensors numpy values. + """ + sess = ops.get_default_session() or self.cached_session() + return sess.run(tensors) + + +def _run_benchmarks(regex): + """Run benchmarks that match regex `regex`. + + This function goes through the global benchmark registry, and matches + benchmark class and method names of the form + `module.name.BenchmarkClass.benchmarkMethod` to the given regex. + If a method matches, it is run. + + Args: + regex: The string regular expression to match Benchmark classes against. + + Raises: + ValueError: If no benchmarks were selected by the input regex. + """ + registry = list(GLOBAL_BENCHMARK_REGISTRY) + + selected_benchmarks = [] + # Match benchmarks in registry against regex + for benchmark in registry: + benchmark_name = "%s.%s" % (benchmark.__module__, benchmark.__name__) + attrs = dir(benchmark) + # Don't instantiate the benchmark class unless necessary + benchmark_instance = None + + for attr in attrs: + if not attr.startswith("benchmark"): + continue + candidate_benchmark_fn = getattr(benchmark, attr) + if not callable(candidate_benchmark_fn): + continue + full_benchmark_name = "%s.%s" % (benchmark_name, attr) + if regex == "all" or re.search(regex, full_benchmark_name): + selected_benchmarks.append(full_benchmark_name) + # Instantiate the class if it hasn't been instantiated + benchmark_instance = benchmark_instance or benchmark() + # Get the method tied to the class + instance_benchmark_fn = getattr(benchmark_instance, attr) + # Call the instance method + instance_benchmark_fn() + + if not selected_benchmarks: + raise ValueError("No benchmarks matched the pattern: '{}'".format(regex)) + + +def benchmarks_main(true_main, argv=None): + """Run benchmarks as declared in argv. + + Args: + true_main: True main function to run if benchmarks are not requested. + argv: the command line arguments (if None, uses sys.argv). + """ + if argv is None: + argv = sys.argv + found_arg = [ + arg + for arg in argv + if arg.startswith("--benchmark_filter=") + or arg.startswith("-benchmark_filter=") + ] + if found_arg: + # Remove --benchmark_filter arg from sys.argv + argv.remove(found_arg[0]) + + regex = found_arg[0].split("=")[1] + app.run(lambda _: _run_benchmarks(regex), argv=argv) + else: + true_main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/build_info.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/build_info.py new file mode 100644 index 0000000000000000000000000000000000000000..0a08ee42bd9e33d50656643c6a3d7d0ff14c301f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/build_info.py @@ -0,0 +1,19 @@ + +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Auto-generated module providing information about the build.""" +import collections + +build_info = collections.OrderedDict([('cpu_compiler', '/usr/lib/llvm-17/bin/clang'), ('cuda_compute_capabilities', ['sm_50', 'sm_60', 'sm_70', 'sm_75', 'compute_80']), ('cuda_version', '12.2'), ('cudnn_version', '8'), ('is_cuda_build', True), ('is_rocm_build', False), ('is_tensorrt_build', True)]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/device_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/device_context.py new file mode 100644 index 0000000000000000000000000000000000000000..d31902804b98aedf58d0dc3ff733467228ac52e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/device_context.py @@ -0,0 +1,18 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helpers to get device context.""" + +def enclosing_tpu_context(): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/flags.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/flags.py new file mode 100644 index 0000000000000000000000000000000000000000..56dd093e9a3ccf1881f3fb43564475bfa3b23830 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/flags.py @@ -0,0 +1,121 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Import router for absl.flags. See https://github.com/abseil/abseil-py.""" +import logging as _logging +import sys as _sys + +# go/tf-wildcard-import + +from absl.flags import * # pylint: disable=wildcard-import + +from tensorflow.python.util import tf_decorator + + +# Since we wrap absl.flags DEFINE functions, we need to declare this module +# does not affect key flags. +disclaim_key_flags() # pylint: disable=undefined-variable + + +_RENAMED_ARGUMENTS = { + 'flag_name': 'name', + 'default_value': 'default', + 'docstring': 'help', +} + + +def _wrap_define_function(original_function): + """Wraps absl.flags's define functions so tf.flags accepts old names.""" + + def wrapper(*args, **kwargs): + """Wrapper function that turns old keyword names to new ones.""" + has_old_names = False + for old_name, new_name in _RENAMED_ARGUMENTS.items(): + if old_name in kwargs: + has_old_names = True + value = kwargs.pop(old_name) + kwargs[new_name] = value + if has_old_names: + _logging.warning( + 'Use of the keyword argument names (flag_name, default_value, ' + 'docstring) is deprecated, please use (name, default, help) instead.') + return original_function(*args, **kwargs) + + return tf_decorator.make_decorator(original_function, wrapper) + + +class _FlagValuesWrapper: + """Wrapper class for absl.flags.FLAGS. + + The difference is that tf.flags.FLAGS implicitly parses flags with sys.argv + when accessing the FLAGS values before it's explicitly parsed, + while absl.flags.FLAGS raises an exception. + """ + + def __init__(self, flags_object): + self.__dict__['__wrapped'] = flags_object + + def __getattribute__(self, name): + if name == '__dict__': + return super().__getattribute__(name) + return self.__dict__['__wrapped'].__getattribute__(name) + + def __getattr__(self, name): + wrapped = self.__dict__['__wrapped'] + # To maintain backwards compatibility, implicitly parse flags when reading + # a flag. + if not wrapped.is_parsed(): + wrapped(_sys.argv) + return wrapped.__getattr__(name) + + def __setattr__(self, name, value): + return self.__dict__['__wrapped'].__setattr__(name, value) + + def __delattr__(self, name): + return self.__dict__['__wrapped'].__delattr__(name) + + def __dir__(self): + return self.__dict__['__wrapped'].__dir__() + + def __getitem__(self, name): + return self.__dict__['__wrapped'].__getitem__(name) + + def __setitem__(self, name, flag): + return self.__dict__['__wrapped'].__setitem__(name, flag) + + def __len__(self): + return self.__dict__['__wrapped'].__len__() + + def __iter__(self): + return self.__dict__['__wrapped'].__iter__() + + def __str__(self): + return self.__dict__['__wrapped'].__str__() + + def __call__(self, *args, **kwargs): + return self.__dict__['__wrapped'].__call__(*args, **kwargs) + + +# pylint: disable=invalid-name,used-before-assignment +# absl.flags APIs use `default` as the name of the default value argument. +# Allow the following functions continue to accept `default_value`. +DEFINE_string = _wrap_define_function(DEFINE_string) +DEFINE_boolean = _wrap_define_function(DEFINE_boolean) +DEFINE_bool = DEFINE_boolean +DEFINE_float = _wrap_define_function(DEFINE_float) +DEFINE_integer = _wrap_define_function(DEFINE_integer) +# pylint: enable=invalid-name,used-before-assignment + +FLAGS = _FlagValuesWrapper(FLAGS) # pylint: disable=used-before-assignment diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/gfile.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/gfile.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb9b4c81a7f550eb1363c60005a25f9473d270e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/gfile.py @@ -0,0 +1,135 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Import router for file_io.""" +# pylint: disable=unused-import +from tensorflow.python.lib.io.file_io import copy as Copy +from tensorflow.python.lib.io.file_io import create_dir as MkDir +from tensorflow.python.lib.io.file_io import delete_file as Remove +from tensorflow.python.lib.io.file_io import delete_recursively as DeleteRecursively +from tensorflow.python.lib.io.file_io import file_exists as Exists +from tensorflow.python.lib.io.file_io import FileIO as _FileIO +from tensorflow.python.lib.io.file_io import get_matching_files as Glob +from tensorflow.python.lib.io.file_io import is_directory as IsDirectory +from tensorflow.python.lib.io.file_io import list_directory as ListDirectory +from tensorflow.python.lib.io.file_io import recursive_create_dir as MakeDirs +from tensorflow.python.lib.io.file_io import rename as Rename +from tensorflow.python.lib.io.file_io import stat as Stat +from tensorflow.python.lib.io.file_io import walk as Walk +# pylint: enable=unused-import +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('io.gfile.GFile', v1=['gfile.GFile', 'gfile.Open', 'io.gfile.GFile']) +class GFile(_FileIO): + r"""File I/O wrappers without thread locking. + + The main roles of the `tf.io.gfile` module are: + + 1. To provide an API that is close to Python's file I/O objects, and + 2. To provide an implementation based on TensorFlow's C++ FileSystem API. + + The C++ FileSystem API supports multiple file system implementations, + including local files, Google Cloud Storage (using a `gs://` prefix, and + HDFS (using an `hdfs://` prefix). TensorFlow exports these as `tf.io.gfile`, + so that you can use these implementations for saving and loading checkpoints, + writing to TensorBoard logs, and accessing training data (among other uses). + However, if all your files are local, you can use the regular Python file + API without any problem. + + *Note*: though similar to Python's I/O implementation, there are semantic + differences to make `tf.io.gfile` more efficient for backing filesystems. For + example, a write mode file will not be opened until the first write call to + minimize RPC invocations in network filesystems. + + Once you obtain a `GFile` object, you can use it in most ways as you would any + Python's file object: + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdf") + 4 + >>> with tf.io.gfile.GFile("/tmp/x") as f: + ... f.read() + 'asdf' + + The difference is that you can specify URI schemes to use other filesystems + (e.g., `gs://` for GCS, `s3://` for S3, etc.), if they are supported. Using + `file://` as an example, we have: + + >>> with tf.io.gfile.GFile("file:///tmp/x", "w") as f: + ... f.write("qwert") + ... f.write("asdf") + >>> tf.io.gfile.GFile("file:///tmp/x").read() + 'qwertasdf' + + You can also read all lines of a file directly: + + >>> with tf.io.gfile.GFile("file:///tmp/x", "w") as f: + ... f.write("asdf\n") + ... f.write("qwer\n") + >>> tf.io.gfile.GFile("/tmp/x").readlines() + ['asdf\n', 'qwer\n'] + + You can iterate over the lines: + + >>> with tf.io.gfile.GFile("file:///tmp/x", "w") as f: + ... f.write("asdf\n") + ... f.write("qwer\n") + >>> for line in tf.io.gfile.GFile("/tmp/x"): + ... print(line[:-1]) # removes the end of line character + asdf + qwer + + Random access read is possible if the underlying filesystem supports it: + + >>> with open("/tmp/x", "w") as f: + ... f.write("asdfqwer") + >>> f = tf.io.gfile.GFile("/tmp/x") + >>> f.read(3) + 'asd' + >>> f.seek(4) + >>> f.tell() + 4 + >>> f.read(3) + 'qwe' + >>> f.tell() + 7 + >>> f.close() + """ + + def __init__(self, name, mode='r'): + super(GFile, self).__init__(name=name, mode=mode) + + +@tf_export(v1=['gfile.FastGFile']) +class FastGFile(_FileIO): + """File I/O wrappers without thread locking. + + Note, that this is somewhat like builtin Python file I/O, but + there are semantic differences to make it more efficient for + some backing filesystems. For example, a write mode file will + not be opened until the first write call (to minimize RPC + invocations in network filesystems). + """ + + @deprecated(None, 'Use tf.gfile.GFile.') + def __init__(self, name, mode='r'): + super(FastGFile, self).__init__(name=name, mode=mode) + + +# Does not alias to Open so that we use our version of GFile to strip +# 'b' mode. +Open = GFile diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/googletest.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/googletest.py new file mode 100644 index 0000000000000000000000000000000000000000..a72bd8c04ad0fe0e552cf5cb3d6f9b5192521af9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/googletest.py @@ -0,0 +1,269 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Imports absltest as a replacement for testing.pybase.googletest.""" +import atexit +import os +import sys +import tempfile + +# go/tf-wildcard-import +# pylint: disable=wildcard-import,redefined-builtin +from absl import app +from absl.testing.absltest import * +# pylint: enable=wildcard-import,redefined-builtin + +from tensorflow.python.framework import errors +from tensorflow.python.lib.io import file_io +from tensorflow.python.platform import benchmark +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +Benchmark = benchmark.TensorFlowBenchmark # pylint: disable=invalid-name + +absltest_main = main + +# We keep a global variable in this module to make sure we create the temporary +# directory only once per test binary invocation. +_googletest_temp_dir = '' + + +# pylint: disable=invalid-name +# pylint: disable=undefined-variable +def g_main(argv): + """Delegate to absltest.main.""" + + absltest_main(argv=argv) + + +# Redefine main to allow running benchmarks +def main(argv=None): # pylint: disable=function-redefined + def main_wrapper(): + args = argv + if args is None: + args = sys.argv + return app.run(main=g_main, argv=args) + + benchmark.benchmarks_main(true_main=main_wrapper, argv=argv) + + +def GetTempDir(): + """Return a temporary directory for tests to use.""" + global _googletest_temp_dir + if not _googletest_temp_dir: + if os.environ.get('TEST_TMPDIR'): + temp_dir = tempfile.mkdtemp(prefix=os.environ['TEST_TMPDIR']) + else: + first_frame = tf_inspect.stack()[-1][0] + temp_dir = os.path.join(tempfile.gettempdir(), + os.path.basename(tf_inspect.getfile(first_frame))) + temp_dir = tempfile.mkdtemp(prefix=temp_dir.rstrip('.py')) + + # Make sure we have the correct path separators. + temp_dir = temp_dir.replace('/', os.sep) + + def delete_temp_dir(dirname=temp_dir): + try: + file_io.delete_recursively(dirname) + except errors.OpError as e: + logging.error('Error removing %s: %s', dirname, e) + + atexit.register(delete_temp_dir) + + _googletest_temp_dir = temp_dir + + return _googletest_temp_dir + + +def test_src_dir_path(relative_path): + """Creates an absolute test srcdir path given a relative path. + + Args: + relative_path: a path relative to tensorflow root. + e.g. "contrib/session_bundle/example". + + Returns: + An absolute path to the linked in runfiles. + """ + return os.path.join(os.environ['TEST_SRCDIR'], + 'org_tensorflow/tensorflow', relative_path) + + +def StatefulSessionAvailable(): + return False + + +@tf_export(v1=['test.StubOutForTesting']) +class StubOutForTesting(object): + """Support class for stubbing methods out for unit testing. + + Sample Usage: + + You want os.path.exists() to always return true during testing. + + stubs = StubOutForTesting() + stubs.Set(os.path, 'exists', lambda x: 1) + ... + stubs.CleanUp() + + The above changes os.path.exists into a lambda that returns 1. Once + the ... part of the code finishes, the CleanUp() looks up the old + value of os.path.exists and restores it. + """ + + def __init__(self): + self.cache = [] + self.stubs = [] + + def __del__(self): + """Do not rely on the destructor to undo your stubs. + + You cannot guarantee exactly when the destructor will get called without + relying on implementation details of a Python VM that may change. + """ + self.CleanUp() + + # __enter__ and __exit__ allow use as a context manager. + def __enter__(self): + return self + + def __exit__(self, unused_exc_type, unused_exc_value, unused_tb): + self.CleanUp() + + def CleanUp(self): + """Undoes all SmartSet() & Set() calls, restoring original definitions.""" + self.SmartUnsetAll() + self.UnsetAll() + + def SmartSet(self, obj, attr_name, new_attr): + """Replace obj.attr_name with new_attr. + + This method is smart and works at the module, class, and instance level + while preserving proper inheritance. It will not stub out C types however + unless that has been explicitly allowed by the type. + + This method supports the case where attr_name is a staticmethod or a + classmethod of obj. + + Notes: + - If obj is an instance, then it is its class that will actually be + stubbed. Note that the method Set() does not do that: if obj is + an instance, it (and not its class) will be stubbed. + - The stubbing is using the builtin getattr and setattr. So, the __get__ + and __set__ will be called when stubbing (TODO: A better idea would + probably be to manipulate obj.__dict__ instead of getattr() and + setattr()). + + Args: + obj: The object whose attributes we want to modify. + attr_name: The name of the attribute to modify. + new_attr: The new value for the attribute. + + Raises: + AttributeError: If the attribute cannot be found. + """ + _, obj = tf_decorator.unwrap(obj) + if (tf_inspect.ismodule(obj) or + (not tf_inspect.isclass(obj) and attr_name in obj.__dict__)): + orig_obj = obj + orig_attr = getattr(obj, attr_name) + else: + if not tf_inspect.isclass(obj): + mro = list(tf_inspect.getmro(obj.__class__)) + else: + mro = list(tf_inspect.getmro(obj)) + + mro.reverse() + + orig_attr = None + found_attr = False + + for cls in mro: + try: + orig_obj = cls + orig_attr = getattr(obj, attr_name) + found_attr = True + except AttributeError: + continue + + if not found_attr: + raise AttributeError('Attribute not found.') + + # Calling getattr() on a staticmethod transforms it to a 'normal' function. + # We need to ensure that we put it back as a staticmethod. + old_attribute = obj.__dict__.get(attr_name) + if old_attribute is not None and isinstance(old_attribute, staticmethod): + orig_attr = staticmethod(orig_attr) + + self.stubs.append((orig_obj, attr_name, orig_attr)) + setattr(orig_obj, attr_name, new_attr) + + def SmartUnsetAll(self): + """Reverses SmartSet() calls, restoring things to original definitions. + + This method is automatically called when the StubOutForTesting() + object is deleted; there is no need to call it explicitly. + + It is okay to call SmartUnsetAll() repeatedly, as later calls have + no effect if no SmartSet() calls have been made. + """ + for args in reversed(self.stubs): + setattr(*args) + + self.stubs = [] + + def Set(self, parent, child_name, new_child): + """In parent, replace child_name's old definition with new_child. + + The parent could be a module when the child is a function at + module scope. Or the parent could be a class when a class' method + is being replaced. The named child is set to new_child, while the + prior definition is saved away for later, when UnsetAll() is + called. + + This method supports the case where child_name is a staticmethod or a + classmethod of parent. + + Args: + parent: The context in which the attribute child_name is to be changed. + child_name: The name of the attribute to change. + new_child: The new value of the attribute. + """ + old_child = getattr(parent, child_name) + + old_attribute = parent.__dict__.get(child_name) + if old_attribute is not None and isinstance(old_attribute, staticmethod): + old_child = staticmethod(old_child) + + self.cache.append((parent, old_child, child_name)) + setattr(parent, child_name, new_child) + + def UnsetAll(self): + """Reverses Set() calls, restoring things to their original definitions. + + This method is automatically called when the StubOutForTesting() + object is deleted; there is no need to call it explicitly. + + It is okay to call UnsetAll() repeatedly, as later calls have no + effect if no Set() calls have been made. + """ + # Undo calls to Set() in reverse order, in case Set() was called on the + # same arguments repeatedly (want the original call to be last one undone) + for (parent, old_child, child_name) in reversed(self.cache): + setattr(parent, child_name, old_child) + self.cache = [] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/remote_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/remote_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f4b24a7505d64db071ec0c2a16a3cc311afcb9ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/remote_utils.py @@ -0,0 +1,32 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Platform-specific helpers for connecting to remote servers.""" + + +def get_default_communication_protocol(): + return 'grpc' + + +def is_remote_path(_): + return False + + +def get_appendable_file_encoding(): + return '' + + +def coordination_service_type(*args, **kwargs): + del args, kwargs + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/resource_loader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/resource_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..808042e963d9cafa3747ba7c7a3537d6d1f62191 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/resource_loader.py @@ -0,0 +1,132 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Resource management library.""" +import os as _os +import sys as _sys + +from tensorflow.python.util import tf_inspect as _inspect +from tensorflow.python.util.tf_export import tf_export + +# pylint: disable=g-import-not-at-top +try: + from rules_python.python.runfiles import runfiles +except ImportError: + runfiles = None +# pylint: enable=g-import-not-at-top + + +@tf_export(v1=['resource_loader.load_resource']) +def load_resource(path): + """Load the resource at given path, where path is relative to tensorflow/. + + Args: + path: a string resource path relative to tensorflow/. + + Returns: + The contents of that resource. + + Raises: + IOError: If the path is not found, or the resource can't be opened. + """ + with open(get_path_to_datafile(path), 'rb') as f: + return f.read() + + +# pylint: disable=protected-access +@tf_export(v1=['resource_loader.get_data_files_path']) +def get_data_files_path(): + """Get a direct path to the data files colocated with the script. + + Returns: + The directory where files specified in data attribute of py_test + and py_binary are stored. + """ + return _os.path.dirname(_inspect.getfile(_sys._getframe(1))) + + +@tf_export(v1=['resource_loader.get_root_dir_with_all_resources']) +def get_root_dir_with_all_resources(): + """Get a root directory containing all the data attributes in the build rule. + + Returns: + The path to the specified file present in the data attribute of py_test + or py_binary. Falls back to returning the same as get_data_files_path if it + fails to detect a bazel runfiles directory. + """ + script_dir = get_data_files_path() + + # Create a history of the paths, because the data files are located relative + # to the repository root directory, which is directly under runfiles + # directory. + directories = [script_dir] + data_files_dir = '' + + while True: + candidate_dir = directories[-1] + current_directory = _os.path.basename(candidate_dir) + if '.runfiles' in current_directory: + # Our file should never be directly under runfiles. + # If the history has only one item, it means we are directly inside the + # runfiles directory, something is wrong, fall back to the default return + # value, script directory. + if len(directories) > 1: + data_files_dir = directories[-2] + + break + else: + new_candidate_dir = _os.path.dirname(candidate_dir) + # If we are at the root directory these two will be the same. + if new_candidate_dir == candidate_dir: + break + else: + directories.append(new_candidate_dir) + + return data_files_dir or script_dir + + +@tf_export(v1=['resource_loader.get_path_to_datafile']) +def get_path_to_datafile(path): + """Get the path to the specified file in the data dependencies. + + The path is relative to tensorflow/ + + Args: + path: a string resource path relative to tensorflow/ + + Returns: + The path to the specified file present in the data attribute of py_test + or py_binary. + + Raises: + IOError: If the path is not found, or the resource can't be opened. + """ + # First, try finding in the new path. + if runfiles: + r = runfiles.Create() + new_fpath = r.Rlocation( + _os.path.abspath(_os.path.join('tensorflow', path))) + if new_fpath is not None and _os.path.exists(new_fpath): + return new_fpath + + # Then, the old style path, as people became dependent on this buggy call. + old_filepath = _os.path.join( + _os.path.dirname(_inspect.getfile(_sys._getframe(1))), path) + return old_filepath + + +@tf_export(v1=['resource_loader.readahead_file_path']) +def readahead_file_path(path, readahead='128M'): # pylint: disable=unused-argument + """Readahead files not implemented; simply returns given path.""" + return path diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/self_check.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/self_check.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b40429b58d38eea23b570e3a141cfc21d8b8ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/self_check.py @@ -0,0 +1,64 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Platform-specific code for checking the integrity of the TensorFlow build.""" +import ctypes +import os + +MSVCP_DLL_NAMES = "msvcp_dll_names" + +try: + from tensorflow.python.platform import build_info +except ImportError: + raise ImportError("Could not import tensorflow. Do not import tensorflow " + "from its source directory; change directory to outside " + "the TensorFlow source tree, and relaunch your Python " + "interpreter from there.") + + +def preload_check(): + """Raises an exception if the environment is not correctly configured. + + Raises: + ImportError: If the check detects that the environment is not correctly + configured, and attempting to load the TensorFlow runtime will fail. + """ + if os.name == "nt": + # Attempt to load any DLLs that the Python extension depends on before + # we load the Python extension, so that we can raise an actionable error + # message if they are not found. + if MSVCP_DLL_NAMES in build_info.build_info: + missing = [] + for dll_name in build_info.build_info[MSVCP_DLL_NAMES].split(","): + try: + ctypes.WinDLL(dll_name) + except OSError: + missing.append(dll_name) + if missing: + raise ImportError( + "Could not find the DLL(s) %r. TensorFlow requires that these DLLs " + "be installed in a directory that is named in your %%PATH%% " + "environment variable. You may install these DLLs by downloading " + '"Microsoft C++ Redistributable for Visual Studio 2015, 2017 and ' + '2019" for your platform from this URL: ' + "https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads" + % " or ".join(missing)) + else: + # Load a library that performs CPU feature guard checking. Doing this here + # as a preload check makes it more likely that we detect any CPU feature + # incompatibilities before we trigger them (which would typically result in + # SIGILL). + from tensorflow.python.platform import _pywrap_cpu_feature_guard + _pywrap_cpu_feature_guard.InfoAboutUnusedCPUFeatures() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/sysconfig.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..9eebac9cfbb6a5bdb06522e6de327cfe79a3a72e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/sysconfig.py @@ -0,0 +1,144 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""System configuration library. + +API docstring: tensorflow.sysconfig +""" +import os.path as _os_path +import platform as _platform + +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.framework.versions import CXX11_ABI_FLAG as _CXX11_ABI_FLAG +from tensorflow.python.framework.versions import CXX_VERSION as _CXX_VERSION +from tensorflow.python.framework.versions import MONOLITHIC_BUILD as _MONOLITHIC_BUILD +from tensorflow.python.framework.versions import VERSION as _VERSION +from tensorflow.python.platform import build_info +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=g-import-not-at-top +@tf_export('sysconfig.get_include') +def get_include(): + """Get the directory containing the TensorFlow C++ header files. + + Returns: + The directory as string. + """ + # Import inside the function. + # sysconfig is imported from the tensorflow module, so having this + # import at the top would cause a circular import, resulting in + # the tensorflow module missing symbols that come after sysconfig. + import tensorflow as tf + return _os_path.join(_os_path.dirname(tf.__file__), 'include') + + +@tf_export('sysconfig.get_lib') +def get_lib(): + """Get the directory containing the TensorFlow framework library. + + Returns: + The directory as string. + """ + import tensorflow as tf + return _os_path.join(_os_path.dirname(tf.__file__)) + + +@tf_export('sysconfig.get_compile_flags') +def get_compile_flags(): + """Returns the compilation flags for compiling with TensorFlow. + + The returned list of arguments can be passed to the compiler for compiling + against TensorFlow headers. The result is platform dependent. + + For example, on a typical Linux system with Python 3.7 the following command + prints `['-I/usr/local/lib/python3.7/dist-packages/tensorflow/include', + '-D_GLIBCXX_USE_CXX11_ABI=1', '-DEIGEN_MAX_ALIGN_BYTES=64']` + + >>> print(tf.sysconfig.get_compile_flags()) + + Returns: + A list of strings for the compiler flags. + """ + flags = [] + flags.append('-I%s' % get_include()) + flags.append('-D_GLIBCXX_USE_CXX11_ABI=%d' % _CXX11_ABI_FLAG) + cxx_version_flag = None + if _CXX_VERSION == 201103: + cxx_version_flag = '--std=c++11' + elif _CXX_VERSION == 201402: + cxx_version_flag = '--std=c++14' + elif _CXX_VERSION == 201703: + cxx_version_flag = '--std=c++17' + elif _CXX_VERSION == 202002: + cxx_version_flag = '--std=c++20' + if cxx_version_flag: + flags.append(cxx_version_flag) + flags.append('-DEIGEN_MAX_ALIGN_BYTES=%d' % + pywrap_tf_session.get_eigen_max_align_bytes()) + return flags + + +@tf_export('sysconfig.get_link_flags') +def get_link_flags(): + """Returns the linker flags for linking with TensorFlow. + + The returned list of arguments can be passed to the linker for linking against + TensorFlow. The result is platform dependent. + + For example, on a typical Linux system with Python 3.7 the following command + prints `['-L/usr/local/lib/python3.7/dist-packages/tensorflow', + '-l:libtensorflow_framework.so.2']` + + >>> print(tf.sysconfig.get_link_flags()) + + Returns: + A list of strings for the linker flags. + """ + is_mac = _platform.system() == 'Darwin' + ver = _VERSION.split('.')[0] + flags = [] + if not _MONOLITHIC_BUILD: + flags.append('-L%s' % get_lib()) + if is_mac: + flags.append('-ltensorflow_framework.%s' % ver) + else: + flags.append('-l:libtensorflow_framework.so.%s' % ver) + return flags + + +@tf_export('sysconfig.get_build_info') +def get_build_info(): + """Get a dictionary describing TensorFlow's build environment. + + Values are generated when TensorFlow is compiled, and are static for each + TensorFlow package. The return value is a dictionary with string keys such as: + + - cuda_version + - cudnn_version + - is_cuda_build + - is_rocm_build + - msvcp_dll_names + - nvcuda_dll_name + - cudart_dll_name + - cudnn_dll_name + + Note that the actual keys and values returned by this function is subject to + change across different versions of TensorFlow or across platforms. + + Returns: + A Dictionary describing TensorFlow's build environment. + """ + return build_info.build_info diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/test.py new file mode 100644 index 0000000000000000000000000000000000000000..a88875890350a104b8bcff5822c822ed6eabc9c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/test.py @@ -0,0 +1,191 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Testing.""" + +import functools + +from unittest import mock + +# pylint: disable=g-bad-import-order +from tensorflow.python.framework import test_util as _test_util +from tensorflow.python.platform import googletest as _googletest + +# pylint: disable=unused-import +from tensorflow.python.framework.test_util import assert_equal_graph_def +from tensorflow.python.framework.test_util import create_local_cluster +from tensorflow.python.framework.test_util import TensorFlowTestCase as TestCase +from tensorflow.python.framework.test_util import gpu_device_name +from tensorflow.python.framework.test_util import is_gpu_available + +from tensorflow.python.ops.gradient_checker import compute_gradient_error +from tensorflow.python.ops.gradient_checker import compute_gradient +# pylint: enable=unused-import,g-bad-import-order + + +from tensorflow.python.util.tf_export import tf_export + +tf_export(v1=['test.mock'])(mock) + +# Import Benchmark class +Benchmark = _googletest.Benchmark # pylint: disable=invalid-name + +# Import StubOutForTesting class +StubOutForTesting = _googletest.StubOutForTesting # pylint: disable=invalid-name + + +@tf_export('test.main') +def main(argv=None): + """Runs all unit tests.""" + _test_util.InstallStackTraceHandler() + return _googletest.main(argv) + + +@tf_export(v1=['test.get_temp_dir']) +def get_temp_dir(): + """Returns a temporary directory for use during tests. + + There is no need to delete the directory after the test. + + @compatibility(TF2) + This function is removed in TF2. Please use `TestCase.get_temp_dir` instead + in a test case. + Outside of a unit test, obtain a temporary directory through Python's + `tempfile` module. + @end_compatibility + + Returns: + The temporary directory. + """ + return _googletest.GetTempDir() + + +@tf_export(v1=['test.test_src_dir_path']) +def test_src_dir_path(relative_path): + """Creates an absolute test srcdir path given a relative path. + + Args: + relative_path: a path relative to tensorflow root. + e.g. "core/platform". + + Returns: + An absolute path to the linked in runfiles. + """ + return _googletest.test_src_dir_path(relative_path) + + +@tf_export('test.is_built_with_cuda') +def is_built_with_cuda(): + """Returns whether TensorFlow was built with CUDA (GPU) support. + + This method should only be used in tests written with `tf.test.TestCase`. A + typical usage is to skip tests that should only run with CUDA (GPU). + + >>> class MyTest(tf.test.TestCase): + ... + ... def test_add_on_gpu(self): + ... if not tf.test.is_built_with_cuda(): + ... self.skipTest("test is only applicable on GPU") + ... + ... with tf.device("GPU:0"): + ... self.assertEqual(tf.math.add(1.0, 2.0), 3.0) + + TensorFlow official binary is built with CUDA. + """ + return _test_util.IsGoogleCudaEnabled() + + +@tf_export('test.is_built_with_rocm') +def is_built_with_rocm(): + """Returns whether TensorFlow was built with ROCm (GPU) support. + + This method should only be used in tests written with `tf.test.TestCase`. A + typical usage is to skip tests that should only run with ROCm (GPU). + + >>> class MyTest(tf.test.TestCase): + ... + ... def test_add_on_gpu(self): + ... if not tf.test.is_built_with_rocm(): + ... self.skipTest("test is only applicable on GPU") + ... + ... with tf.device("GPU:0"): + ... self.assertEqual(tf.math.add(1.0, 2.0), 3.0) + + TensorFlow official binary is NOT built with ROCm. + """ + return _test_util.IsBuiltWithROCm() + + +@tf_export('test.disable_with_predicate') +def disable_with_predicate(pred, skip_message): + """Disables the test if pred is true.""" + + def decorator_disable_with_predicate(func): + + @functools.wraps(func) + def wrapper_disable_with_predicate(self, *args, **kwargs): + if pred(): + self.skipTest(skip_message) + else: + return func(self, *args, **kwargs) + + return wrapper_disable_with_predicate + + return decorator_disable_with_predicate + + +@tf_export('test.is_built_with_gpu_support') +def is_built_with_gpu_support(): + """Returns whether TensorFlow was built with GPU (CUDA or ROCm) support. + + This method should only be used in tests written with `tf.test.TestCase`. A + typical usage is to skip tests that should only run with GPU. + + >>> class MyTest(tf.test.TestCase): + ... + ... def test_add_on_gpu(self): + ... if not tf.test.is_built_with_gpu_support(): + ... self.skipTest("test is only applicable on GPU") + ... + ... with tf.device("GPU:0"): + ... self.assertEqual(tf.math.add(1.0, 2.0), 3.0) + + TensorFlow official binary is built with CUDA GPU support. + """ + return is_built_with_cuda() or is_built_with_rocm() + + +@tf_export('test.is_built_with_xla') +def is_built_with_xla(): + """Returns whether TensorFlow was built with XLA support. + + This method should only be used in tests written with `tf.test.TestCase`. A + typical usage is to skip tests that should only run with XLA. + + >>> class MyTest(tf.test.TestCase): + ... + ... def test_add_on_xla(self): + ... if not tf.test.is_built_with_xla(): + ... self.skipTest("test is only applicable on XLA") + + ... @tf.function(jit_compile=True) + ... def add(x, y): + ... return tf.math.add(x, y) + ... + ... self.assertEqual(add(tf.ones(()), tf.ones(())), 2.0) + + TensorFlow official binary is built with XLA. + """ + return _test_util.IsBuiltWithXLA() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/tf_logging.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/tf_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..ea58dd71dd12265d7e71cd6a20101b18b1cb727e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/platform/tf_logging.py @@ -0,0 +1,372 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Logging utilities.""" +# pylint: disable=unused-import +# pylint: disable=g-bad-import-order +# pylint: disable=invalid-name +import logging as _logging +import os as _os +import sys as _sys +import _thread +import time as _time +import traceback as _traceback +from logging import DEBUG +from logging import ERROR +from logging import FATAL +from logging import INFO +from logging import WARN +import threading + +from tensorflow.python.util.tf_export import tf_export + +# Don't use this directly. Use get_logger() instead. +_logger = None +_logger_lock = threading.Lock() + + +def error_log(error_msg, level=ERROR): + """Empty helper method.""" + del error_msg, level + + +def _get_caller(offset=3): + """Returns a code and frame object for the lowest non-logging stack frame.""" + # Use sys._getframe(). This avoids creating a traceback object. + # pylint: disable=protected-access + f = _sys._getframe(offset) + # pylint: enable=protected-access + our_file = f.f_code.co_filename + f = f.f_back + while f: + code = f.f_code + if code.co_filename != our_file: + return code, f + f = f.f_back + return None, None + +# The definition of `findCaller` changed in Python 3.2, +# and further changed in Python 3.8 +if _sys.version_info.major >= 3 and _sys.version_info.minor >= 8: + + def _logger_find_caller(stack_info=False, stacklevel=1): # pylint: disable=g-wrong-blank-lines + code, frame = _get_caller(4) + sinfo = None + if stack_info: + sinfo = '\n'.join(_traceback.format_stack()) + if code: + return (code.co_filename, frame.f_lineno, code.co_name, sinfo) + else: + return '(unknown file)', 0, '(unknown function)', sinfo +elif _sys.version_info.major >= 3 and _sys.version_info.minor >= 2: + + def _logger_find_caller(stack_info=False): # pylint: disable=g-wrong-blank-lines + code, frame = _get_caller(4) + sinfo = None + if stack_info: + sinfo = '\n'.join(_traceback.format_stack()) + if code: + return (code.co_filename, frame.f_lineno, code.co_name, sinfo) + else: + return '(unknown file)', 0, '(unknown function)', sinfo +else: + def _logger_find_caller(): # pylint: disable=g-wrong-blank-lines + code, frame = _get_caller(4) + if code: + return (code.co_filename, frame.f_lineno, code.co_name) + else: + return '(unknown file)', 0, '(unknown function)' + + +@tf_export('get_logger') +def get_logger(): + """Return TF logger instance. + + Returns: + An instance of the Python logging library Logger. + + See Python documentation (https://docs.python.org/3/library/logging.html) + for detailed API. Below is only a summary. + + The logger has 5 levels of logging from the most serious to the least: + + 1. FATAL + 2. ERROR + 3. WARN + 4. INFO + 5. DEBUG + + The logger has the following methods, based on these logging levels: + + 1. fatal(msg, *args, **kwargs) + 2. error(msg, *args, **kwargs) + 3. warn(msg, *args, **kwargs) + 4. info(msg, *args, **kwargs) + 5. debug(msg, *args, **kwargs) + + The `msg` can contain string formatting. An example of logging at the `ERROR` + level + using string formating is: + + >>> tf.get_logger().error("The value %d is invalid.", 3) + + You can also specify the logging verbosity. In this case, the + WARN level log will not be emitted: + + >>> tf.get_logger().setLevel(ERROR) + >>> tf.get_logger().warn("This is a warning.") + """ + global _logger + + # Use double-checked locking to avoid taking lock unnecessarily. + if _logger: + return _logger + + _logger_lock.acquire() + + try: + if _logger: + return _logger + + # Scope the TensorFlow logger to not conflict with users' loggers. + logger = _logging.getLogger('tensorflow') + + # Override findCaller on the logger to skip internal helper functions + logger.findCaller = _logger_find_caller + + # Don't further configure the TensorFlow logger if the root logger is + # already configured. This prevents double logging in those cases. + if not _logging.getLogger().handlers: + # Determine whether we are in an interactive environment + _interactive = False + try: + # This is only defined in interactive shells. + if _sys.ps1: + _interactive = True + except AttributeError: + # Even now, we may be in an interactive shell with `python -i`. + _interactive = _sys.flags.interactive + + # If we are in an interactive environment (like Jupyter), set loglevel + # to INFO and pipe the output to stdout. + if _interactive: + logger.setLevel(INFO) + _logging_target = _sys.stdout + else: + _logging_target = _sys.stderr + + # Add the output handler. + _handler = _logging.StreamHandler(_logging_target) + _handler.setFormatter(_logging.Formatter(_logging.BASIC_FORMAT, None)) + logger.addHandler(_handler) + + _logger = logger + return _logger + + finally: + _logger_lock.release() + + +@tf_export(v1=['logging.log']) +def log(level, msg, *args, **kwargs): + get_logger().log(level, msg, *args, **kwargs) + + +@tf_export(v1=['logging.debug']) +def debug(msg, *args, **kwargs): + get_logger().debug(msg, *args, **kwargs) + + +@tf_export(v1=['logging.error']) +def error(msg, *args, **kwargs): + get_logger().error(msg, *args, **kwargs) + + +@tf_export(v1=['logging.fatal']) +def fatal(msg, *args, **kwargs): + get_logger().fatal(msg, *args, **kwargs) + + +@tf_export(v1=['logging.info']) +def info(msg, *args, **kwargs): + get_logger().info(msg, *args, **kwargs) + + +@tf_export(v1=['logging.warn']) +def warn(msg, *args, **kwargs): + get_logger().warning(msg, *args, **kwargs) + + +@tf_export(v1=['logging.warning']) +def warning(msg, *args, **kwargs): + get_logger().warning(msg, *args, **kwargs) + + +_level_names = { + FATAL: 'FATAL', + ERROR: 'ERROR', + WARN: 'WARN', + INFO: 'INFO', + DEBUG: 'DEBUG', +} + +# Mask to convert integer thread ids to unsigned quantities for logging +# purposes +_THREAD_ID_MASK = 2 * _sys.maxsize + 1 + +_log_prefix = None # later set to google2_log_prefix + +# Counter to keep track of number of log entries per token. +_log_counter_per_token = {} + + +@tf_export(v1=['logging.TaskLevelStatusMessage']) +def TaskLevelStatusMessage(msg): + error(msg) + + +@tf_export(v1=['logging.flush']) +def flush(): + raise NotImplementedError() + + +# Code below is taken from pyglib/logging +@tf_export(v1=['logging.vlog']) +def vlog(level, msg, *args, **kwargs): + get_logger().log(level, msg, *args, **kwargs) + + +def _GetNextLogCountPerToken(token): + """Wrapper for _log_counter_per_token. + + Args: + token: The token for which to look up the count. + + Returns: + The number of times this function has been called with + *token* as an argument (starting at 0) + """ + global _log_counter_per_token # pylint: disable=global-variable-not-assigned + _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1) + return _log_counter_per_token[token] + + +@tf_export(v1=['logging.log_every_n']) +def log_every_n(level, msg, n, *args): + """Log 'msg % args' at level 'level' once per 'n' times. + + Logs the 1st call, (N+1)st call, (2N+1)st call, etc. + Not threadsafe. + + Args: + level: The level at which to log. + msg: The message to be logged. + n: The number of times this should be called before it is logged. + *args: The args to be substituted into the msg. + """ + count = _GetNextLogCountPerToken(_GetFileAndLine()) + log_if(level, msg, not (count % n), *args) + + +@tf_export(v1=['logging.log_first_n']) +def log_first_n(level, msg, n, *args): # pylint: disable=g-bad-name + """Log 'msg % args' at level 'level' only first 'n' times. + + Not threadsafe. + + Args: + level: The level at which to log. + msg: The message to be logged. + n: The number of times this should be called before it is logged. + *args: The args to be substituted into the msg. + """ + count = _GetNextLogCountPerToken(_GetFileAndLine()) + log_if(level, msg, count < n, *args) + + +@tf_export(v1=['logging.log_if']) +def log_if(level, msg, condition, *args): + """Log 'msg % args' at level 'level' only if condition is fulfilled.""" + if condition: + vlog(level, msg, *args) + + +def _GetFileAndLine(): + """Returns (filename, linenumber) for the stack frame.""" + code, f = _get_caller() + if not code: + return ('', 0) + return (code.co_filename, f.f_lineno) + + +def google2_log_prefix(level, timestamp=None, file_and_line=None): + """Assemble a logline prefix using the google2 format.""" + # pylint: disable=global-variable-not-assigned + global _level_names + # pylint: enable=global-variable-not-assigned + + # Record current time + now = timestamp or _time.time() + now_tuple = _time.localtime(now) + now_microsecond = int(1e6 * (now % 1.0)) + + (filename, line) = file_and_line or _GetFileAndLine() + basename = _os.path.basename(filename) + + # Severity string + severity = 'I' + if level in _level_names: + severity = _level_names[level][0] + + s = '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] ' % ( + severity, + now_tuple[1], # month + now_tuple[2], # day + now_tuple[3], # hour + now_tuple[4], # min + now_tuple[5], # sec + now_microsecond, + _get_thread_id(), + basename, + line) + + return s + + +@tf_export(v1=['logging.get_verbosity']) +def get_verbosity(): + """Return how much logging output will be produced.""" + return get_logger().getEffectiveLevel() + + +@tf_export(v1=['logging.set_verbosity']) +def set_verbosity(v): + """Sets the threshold for what messages will be logged.""" + get_logger().setLevel(v) + + +def _get_thread_id(): + """Get id of current thread, suitable for logging as an unsigned quantity.""" + thread_id = _thread.get_ident() + return thread_id & _THREAD_ID_MASK + + +_log_prefix = google2_log_prefix + +tf_export(v1=['logging.DEBUG']).export_constant(__name__, 'DEBUG') +tf_export(v1=['logging.ERROR']).export_constant(__name__, 'ERROR') +tf_export(v1=['logging.FATAL']).export_constant(__name__, 'FATAL') +tf_export(v1=['logging.INFO']).export_constant(__name__, 'INFO') +tf_export(v1=['logging.WARN']).export_constant(__name__, 'WARN') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_profiler.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_profiler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f0ef4a9a0a87402cb059422da5f1db9c73f1702a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_profiler.pyi @@ -0,0 +1,26 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ProfilerSession: + def __init__(self) -> None: ... + def export_to_tb(self) -> None: ... + def start(self, arg0: str, arg1: dict) -> None: ... + def stop(self) -> bytes: ... + +def monitor(arg0: str, arg1: int, arg2: int, arg3: bool) -> str: ... +def start_server(arg0: int) -> None: ... +def trace(arg0: str, arg1: str, arg2: str, arg3: bool, arg4: int, arg5: int, arg6: dict) -> None: ... +def xspace_to_tools_data(arg0: list, arg1: str, arg2: dict = ...) -> tuple: ... +def xspace_to_tools_data_from_byte_string(arg0: list, arg1: list, arg2: str) -> tuple: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.pyi new file mode 100644 index 0000000000000000000000000000000000000000..105e2dce09d3a768fcb7267ba366db4b8d30593e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/_pywrap_traceme.pyi @@ -0,0 +1,19 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 TraceMe: + def __init__(self, arg0: str, **kwargs) -> None: ... + def SetMetadata(self, **kwargs) -> None: ... + def Stop(self) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/flops_registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/flops_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..18b30ee27d2167502f947def8d1ae346e03fc5d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/internal/flops_registry.py @@ -0,0 +1,480 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Register flops statistics for various TensorFlow operations. +""" +import numpy as np + +from tensorflow.python.framework import graph_util +from tensorflow.python.framework import ops + + +# List of all ops which have implemented flops statistics. +IMPLEMENTED_OPS = set([ + # Unary ops + "Reciprocal", "Square", "Rsqrt", "Log", "Neg", "AssignSub", "AssignAdd", + "L2Loss", "Softmax", + # Binary ops + "Add", "Sub", "Mul", "RealDiv", "Maximum", "Minimum", "Pow", "RsqrtGrad", + "GreaterEqual", "Greater", "LessEqual", "Less", "Equal", "NotEqual", + "SquaredDifference", "AddV2", + # Reduction ops + "Mean", "Sum", "ArgMax", "ArgMin", "BiasAddGrad", + # Convolution and pooling + "AvgPool", "MaxPool", "AvgPoolGrad", "MaxPoolGrad", "Conv2DBackpropInput", + "Conv2DBackpropFilter", + # Other ops + "AddN", "MatMul", + # Ops implemented in core tensorflow: + "Conv2D", "DepthwiseConv2dNative", "BiasAdd", "Dilation2D", +]) + + +def _zero_flops(graph, node): + """Returns zero flops.""" + del graph, node # graph and node are unused + return ops.OpStats("flops", 0) + + +def _list_product(lst): + """Computes product of element of the list.""" + result = 1 + for item in lst: + result *= item + return result + +################################################################################ +# Unary operations +################################################################################ + + +def _unary_op_flops(graph, node, ops_per_element=1): + """Common code which compute flops for unary operations.""" + in_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + in_shape.assert_is_fully_defined() + return ops.OpStats("flops", in_shape.num_elements() * ops_per_element) + + +@ops.RegisterStatistics("Reciprocal", "flops") +def _reciprocal_flops(graph, node): + """Compute flops for Reciprocal operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("Square", "flops") +def _square_flops(graph, node): + """Compute flops for Square operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("Rsqrt", "flops") +def _rsqrt_flops(graph, node): + """Compute flops for Rsqrt operation.""" + # Rsqrt(x) = 1 / sqrt(x) + return _unary_op_flops(graph, node, ops_per_element=2) + + +@ops.RegisterStatistics("Log", "flops") +def _log_flops(graph, node): + """Compute flops for Log operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("Neg", "flops") +def _neg_flops(graph, node): + """Compute flops for Neg operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("AssignSub", "flops") +def _assign_sub_flops(graph, node): + """Compute flops for AssignSub operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("AssignAdd", "flops") +def _assign_add_flops(graph, node): + """Compute flops for AssignAdd operation.""" + return _unary_op_flops(graph, node) + + +@ops.RegisterStatistics("L2Loss", "flops") +def _l2_loss_flops(graph, node): + """Compute flops for L2Loss operation.""" + in_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + in_shape.assert_is_fully_defined() + # Tensorflow uses inefficient implementation, with (3*N-1) flops: + # Optimal implementation is 2*N flops + return ops.OpStats("flops", in_shape.num_elements() * 3 - 1) + + +@ops.RegisterStatistics("Softmax", "flops") +def _softmax_flops(graph, node): + """Compute flops for Softmax operation.""" + # Softmax implemetation: + # + # Approximate flops breakdown: + # 2*n -- compute shifted logits + # n -- exp of shifted logits + # 2*n -- compute softmax from exp of shifted logits + return _unary_op_flops(graph, node, ops_per_element=5) + +################################################################################ +# Binary operations +################################################################################ + + +def _binary_per_element_op_flops(graph, node, ops_per_element=1): + """Common code which compute flops for binary operations.""" + out_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + out_shape.assert_is_fully_defined() + return ops.OpStats("flops", out_shape.num_elements() * ops_per_element) + + +@ops.RegisterStatistics("Add", "flops") +@ops.RegisterStatistics("AddV2", "flops") +def _add_flops(graph, node): + """Compute flops for Add operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Sub", "flops") +def _sub_flops(graph, node): + """Compute flops for Sub operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Mul", "flops") +def _mul_flops(graph, node): + """Compute flops for Mul operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("RealDiv", "flops") +def _real_div_flops(graph, node): + """Compute flops for RealDiv operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Maximum", "flops") +def _maximum_flops(graph, node): + """Compute flops for Maximum operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Minimum", "flops") +def _minimum_flops(graph, node): + """Compute flops for Minimum operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Pow", "flops") +def _pow_flops(graph, node): + """Compute flops for Pow operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("RsqrtGrad", "flops") +def _rsqrt_grad_flops(graph, node): + """Compute flops for RsqrtGrad operation.""" + return _binary_per_element_op_flops(graph, node, ops_per_element=4) + + +@ops.RegisterStatistics("GreaterEqual", "flops") +def _greater_equal_flops(graph, node): + """Compute flops for GreaterEqual operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Greater", "flops") +def _greater_flops(graph, node): + """Compute flops for Greater operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("LessEqual", "flops") +def _less_equal_flops(graph, node): + """Compute flops for LessEqual operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Less", "flops") +def _less_flops(graph, node): + """Compute flops for Less operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("Equal", "flops") +def _equal_flops(graph, node): + """Compute flops for Equal operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("NotEqual", "flops") +def _not_equal_flops(graph, node): + """Compute flops for NotEqual operation.""" + return _binary_per_element_op_flops(graph, node) + + +@ops.RegisterStatistics("SquaredDifference", "flops") +def _squared_difference_flops(graph, node): + """Compute flops for SquaredDifference operation.""" + return _binary_per_element_op_flops(graph, node, ops_per_element=2) + +################################################################################ +# Reduction ops +################################################################################ + + +def _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0): + """Common code which compute flops for reduction operations.""" + in_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + in_shape.assert_is_fully_defined() + out_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + out_shape.assert_is_fully_defined() + num_flops = (in_shape.num_elements() * reduce_flops + + out_shape.num_elements() * (finalize_flops - reduce_flops)) + return ops.OpStats("flops", num_flops) + + +@ops.RegisterStatistics("Mean", "flops") +def _mean_flops(graph, node): + """Compute flops for Mean operation.""" + # reduction - sum, finalization - divide + return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=1) + + +@ops.RegisterStatistics("Sum", "flops") +def _sum_flops(graph, node): + """Compute flops for Sum operation.""" + # reduction - sum, no finalization + return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0) + + +@ops.RegisterStatistics("ArgMax", "flops") +def _arg_max_flops(graph, node): + """Compute flops for ArgMax operation.""" + # reduction - comparison, no finalization + return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0) + + +@ops.RegisterStatistics("ArgMin", "flops") +def _arg_min_flops(graph, node): + """Compute flops for ArgMin operation.""" + # reduction - comparison, no finalization + return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0) + + +@ops.RegisterStatistics("BiasAddGrad", "flops") +def _bias_add_grad_flops(graph, node): + """Compute flops for BiasAddGrad operation.""" + # Implementation of BiasAddGrad, essentially it's a reduce sum and reshaping: + # So computing flops same way as for "Sum" + return _reduction_op_flops(graph, node, reduce_flops=1, finalize_flops=0) + +################################################################################ +# Convolution and pooling +# Note: all flops statistics are implemented only for NHWC data format +################################################################################ + + +def _verify_conv_data_format(node): + """Verifies data format for pooling and convolutional operations.""" + # TODO(xpan): P1: Support NCHW + if node.attr["data_format"].s != b"NHWC": + raise ValueError("Only NHWC format is supported in flops computations") + + +def _pool_flops(graph, node): + """Common code which compute flops for pooling operations.""" + # compute flops for average and max pooling + _verify_conv_data_format(node) + # + # Pooling declaration: + # Inputs: + # - value + # Outputs: + # - output + # Attributes: + # - ksize + # - strides + # - padding + # - data_format + # + # Pooling implemetation: + out_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + out_shape.assert_is_fully_defined() + kernel_shape = list(node.attr["ksize"].list.i) + kernel_area = _list_product(kernel_shape) + return ops.OpStats("flops", kernel_area * out_shape.num_elements()) + + +@ops.RegisterStatistics("AvgPool", "flops") +def _avg_pool_flops(graph, node): + """Compute flops for AvgPool operation.""" + return _pool_flops(graph, node) + + +@ops.RegisterStatistics("MaxPool", "flops") +def _max_pool_flops(graph, node): + """Compute flops for MaxPool operation.""" + return _pool_flops(graph, node) + + +@ops.RegisterStatistics("AvgPoolGrad", "flops") +def _avg_pool_grad_flops(graph, node): + """Compute flops for AvgPoolGrad operation.""" + _verify_conv_data_format(node) + # Pooling gradient implementation: + out_backprop_shape = graph_util.tensor_shape_from_node_def_name(graph, + node.input[1]) + out_backprop_shape.assert_is_fully_defined() + kernel_shape = list(node.attr["ksize"].list.i) + kernel_area = _list_product(kernel_shape) + # TensorFlow multiply each element of pooling window by coefficient, + # then sum up all of them, thus we have 2 flops per element: + # More optimal implementation - if division is done after. + return ops.OpStats("flops", + kernel_area * out_backprop_shape.num_elements() * 2) + + +@ops.RegisterStatistics("MaxPoolGrad", "flops") +def _max_pool_grad_flops(graph, node): + """Compute flops for MaxPoolGrad operation.""" + _verify_conv_data_format(node) + # + # MaxPoolGrad declaration: + # Inputs: + # - orig_input -- original input tensor (of max_pool) + # - orig_output -- original output tensor (of max_pool) + # - grad -- gradient with respect to output of max_pool + # Outputs: + # - output -- gradient with respect to input of max_pool + # Attributes: + # - ksize + # - strides + # - padding + # - data_format + # It computes MaxPool first, then one flop per each element of original output + # + kernel_shape = list(node.attr["ksize"].list.i) + kernel_area = _list_product(kernel_shape) + orig_out_shape = graph_util.tensor_shape_from_node_def_name(graph, + node.input[1]) + orig_out_shape.assert_is_fully_defined() + max_pool_ops = kernel_area * orig_out_shape.num_elements() + return ops.OpStats("flops", max_pool_ops + orig_out_shape.num_elements()) + + +@ops.RegisterStatistics("Conv2DBackpropInput", "flops") +def _conv_2d_backprop_input_flops(graph, node): + """Compute flops for Conv2DBackpropInput operation.""" + # Formula: + # batch_size * image_x_dim * image_y_dim * kernel_x_dim * kernel_y_dim + # * input_depth * output_depth * 2 / (image_x_stride * image_x_stride) + # + # Where: + # image_x_dim, image_y_dim and input_depth --- size of input to source (no + # backprop) convolution, in other words they are sizes of backprop output. + # output_depth --- number of filters in the original convolution, thus + # depth of backprop input. + # kernel_x_dim and kernel_y_dim --- sizes of filter in spatial dimension + # image_x_stride and image_x_stride --- strides of the convolution + # + _verify_conv_data_format(node) + # out_shape = [batch_size, image_y_dim, image_x_dim, input_depth] + out_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + out_shape.assert_is_fully_defined() + # kernel_shape = [kernel_y_dim, kernel_x_dim, input_depth, output_depth] + kernel_shape = graph_util.tensor_shape_from_node_def_name(graph, + node.input[1]) + kernel_shape.assert_is_fully_defined() + # strides + strides_shape = list(node.attr["strides"].list.i) + strides_product = strides_shape[1] * strides_shape[2] + return ops.OpStats("flops", + (2 * out_shape.num_elements() + * kernel_shape.num_elements() + / (out_shape.dims[-1].value * strides_product))) + + +@ops.RegisterStatistics("Conv2DBackpropFilter", "flops") +def _conv_2d_backprop_filter_flops(graph, node): + """Compute flops for Conv2DBackpropFilter operation.""" + # Formula same as for Conv2DBackpropInput: + # batch_size * image_x_dim * image_y_dim * kernel_x_dim * kernel_y_dim + # * input_depth * output_depth * 2 / (image_x_stride * image_x_stride) + # + _verify_conv_data_format(node) + # image_shape = [batch_size, image_y_dim, image_x_dim, input_depth] + image_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + image_shape.assert_is_fully_defined() + # kernel_shape = [kernel_y_dim, kernel_x_dim, input_depth, output_depth] + kernel_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + kernel_shape.assert_is_fully_defined() + # strides + strides_shape = list(node.attr["strides"].list.i) + strides_product = strides_shape[1] * strides_shape[2] + return ops.OpStats("flops", + (2 * image_shape.num_elements() + * kernel_shape.num_elements() + / (image_shape.dims[-1].value * strides_product))) + +################################################################################ +# Other ops +################################################################################ + + +@ops.RegisterStatistics("AddN", "flops") +def _add_n_flops(graph, node): + """Compute flops for AddN operation.""" + if not node.input: + return _zero_flops(graph, node) + in_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + in_shape.assert_is_fully_defined() + return ops.OpStats("flops", in_shape.num_elements() * (len(node.input) - 1)) + + +@ops.RegisterStatistics("MatMul", "flops") +def _calc_mat_mul_flops(graph, node): + """Calculates the compute resources needed for MatMul.""" + transpose_a = node.attr["transpose_a"].b + a_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + a_shape.assert_is_fully_defined() + if transpose_a: + k = int(a_shape[0]) + else: + k = int(a_shape[1]) + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + output_count = np.prod(output_shape.as_list()) + return ops.OpStats("flops", (k * output_count * 2)) + + +@ops.RegisterStatistics("BatchMatMul", "flops") +@ops.RegisterStatistics("BatchMatMulV2", "flops") +@ops.RegisterStatistics("BatchMatMulV3", "flops") +def _calc_batch_mat_mul_flops(graph, node): + """Calculates the compute resources needed for BatchMatMul.""" + transpose_a = node.attr["transpose_a"].b + a_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) + a_shape.assert_is_fully_defined() + if transpose_a: + k = int(a_shape[-2]) + else: + k = int(a_shape[-1]) + output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) + output_shape.assert_is_fully_defined() + output_count = np.prod(output_shape.as_list()) + return ops.OpStats("flops", (k * output_count * 2)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/model_analyzer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/model_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..b1993b192c78fe1604cdf66df0ad48b2547e8798 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/model_analyzer.py @@ -0,0 +1,422 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Model Analyzer. + +Analyze model, including shape, params, time, memory, structure, etc. +""" +import sys + +from google.protobuf import message +from tensorflow.core.profiler import tfprof_options_pb2 +from tensorflow.core.profiler import tfprof_output_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.profiler import option_builder +from tensorflow.python.profiler import tfprof_logger +from tensorflow.python.util import _pywrap_tfprof as print_mdl +from tensorflow.python.util.tf_export import tf_export + +_DEFAULT_PROFILE_OPTIONS = 0 +_DEFAULT_ADVISE_OPTIONS = 0 + +# The following options are for 'advise' cmd. +# Show all advice. +ALL_ADVICE = { + 'ExpensiveOperationChecker': {}, + 'AcceleratorUtilizationChecker': {}, + 'JobChecker': {}, # Only available internally. + 'OperationChecker': {}, +} + + +def _graph_string(graph): + """Helper to serialize a graph to string.""" + if graph: + return graph.as_graph_def(add_shapes=True).SerializeToString() + else: + return b'' + + +def _build_options(options): + """Build tfprof.OptionsProto. + + Args: + options: A dictionary of options. + + Returns: + tfprof.OptionsProto. + """ + opts = tfprof_options_pb2.OptionsProto() + opts.max_depth = options.get('max_depth', 10) + opts.min_bytes = options.get('min_bytes', 0) + opts.min_peak_bytes = options.get('min_peak_bytes', 0) + opts.min_residual_bytes = options.get('min_residual_bytes', 0) + opts.min_output_bytes = options.get('min_output_bytes', 0) + opts.min_micros = options.get('min_micros', 0) + opts.min_accelerator_micros = options.get('min_accelerator_micros', 0) + opts.min_cpu_micros = options.get('min_cpu_micros', 0) + opts.min_params = options.get('min_params', 0) + opts.min_float_ops = options.get('min_float_ops', 0) + opts.min_occurrence = options.get('min_occurrence', 0) + + opts.step = options.get('step', -1) + + opts.order_by = options.get('order_by', 'name') + + for p in options.get('account_type_regexes', []): + opts.account_type_regexes.append(p) + for p in options.get('start_name_regexes', []): + opts.start_name_regexes.append(p) + for p in options.get('trim_name_regexes', []): + opts.trim_name_regexes.append(p) + for p in options.get('show_name_regexes', []): + opts.show_name_regexes.append(p) + for p in options.get('hide_name_regexes', []): + opts.hide_name_regexes.append(p) + opts.account_displayed_op_only = options.get('account_displayed_op_only', + False) + + for p in options.get('select', []): + opts.select.append(p) + + opts.output = options.get('output', 'stdout') + opts.dump_to_file = options.get('dump_to_file', '') + + return opts + + +def _build_advisor_options(options): + """Build tfprof.AdvisorOptionsProto. + + Args: + options: A dictionary of options. See ALL_ADVICE example. + + Returns: + tfprof.AdvisorOptionsProto. + """ + opts = tfprof_options_pb2.AdvisorOptionsProto() + if options is None: + return opts + for checker, checker_opts in options.items(): + checker_ops_pb = tfprof_options_pb2.AdvisorOptionsProto.CheckerOption() + for k, v in checker_opts.items(): + checker_ops_pb[k] = v + opts.checkers[checker].MergeFrom(checker_ops_pb) + return opts + + +@tf_export(v1=['profiler.Profiler']) +class Profiler: + """TensorFlow multi-step profiler. + + + ```python + Typical use case: + # Currently we are only allowed to create 1 profiler per process. + profiler = Profiler(sess.graph) + + for i in range(total_steps): + if i % 10000 == 0: + run_meta = tf.compat.v1.RunMetadata() + _ = sess.run(..., + options=tf.compat.v1.RunOptions( + trace_level=tf.RunOptions.FULL_TRACE), + run_metadata=run_meta) + profiler.add_step(i, run_meta) + + # Profile the parameters of your model. + profiler.profile_name_scope(options=(option_builder.ProfileOptionBuilder + .trainable_variables_parameter())) + + # Or profile the timing of your model operations. + opts = option_builder.ProfileOptionBuilder.time_and_memory() + profiler.profile_operations(options=opts) + + # Or you can generate a timeline: + opts = (option_builder.ProfileOptionBuilder( + option_builder.ProfileOptionBuilder.time_and_memory()) + .with_step(i) + .with_timeline_output(filename).build()) + profiler.profile_graph(options=opts) + else: + _ = sess.run(...) + # Auto detect problems and generate advice. + profiler.advise() + ``` + """ + + def __init__(self, graph=None, op_log=None): + """Constructor. + + Args: + graph: tf.Graph. If None and eager execution is not enabled, use default + graph. + op_log: optional. tensorflow::tfprof::OpLogProto proto. Used to define + extra op types. + """ + if not graph and not context.executing_eagerly(): + graph = ops.get_default_graph() + self._coverage = 0.0 + self._graph = graph + # pylint: disable=protected-access + op_log = tfprof_logger.merge_default_with_oplog(self._graph, op_log=op_log) + # pylint: enable=protected-access + print_mdl.NewProfiler( + _graph_string(self._graph), op_log.SerializeToString()) + + def __del__(self): + print_mdl.DeleteProfiler() + + def add_step(self, step, run_meta): + """Add statistics of a step. + + Args: + step: int, An id used to group one or more different `run_meta` together. + When profiling with the profile_xxx APIs, user can use the `step` id in + the `options` to profile these `run_meta` together. + run_meta: RunMetadata proto that contains statistics of a session run. + """ + # pylint: disable=protected-access + op_log = tfprof_logger.merge_default_with_oplog( + self._graph, run_meta=run_meta) + # pylint: enable=protected-access + # TODO(xpan): P1: Better to find the current graph. + self._coverage = print_mdl.AddStep(step, _graph_string(self._graph), + run_meta.SerializeToString(), + op_log.SerializeToString()) + + def profile_python(self, options): + """Profile the statistics of the Python codes. + + By default, it shows the call stack from root. To avoid + redundant output, you may use options to filter as below + options['show_name_regexes'] = ['.*my_code.py.*'] + + Args: + options: A dict of options. See core/profiler/g3doc/options.md. + + Returns: + a MultiGraphNodeProto that records the results. + """ + opts = _build_options(options) + tfprof_node = tfprof_output_pb2.MultiGraphNodeProto() + try: + tfprof_node.ParseFromString( + print_mdl.Profile('code'.encode('utf-8'), opts.SerializeToString())) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + return tfprof_node + + def profile_operations(self, options): + """Profile the statistics of the Operation types (e.g. + + MatMul, Conv2D). + + Args: + options: A dict of options. See core/profiler/g3doc/options.md. + + Returns: + a MultiGraphNodeProto that records the results. + """ + opts = _build_options(options) + tfprof_node = tfprof_output_pb2.MultiGraphNodeProto() + try: + tfprof_node.ParseFromString( + print_mdl.Profile('op'.encode('utf-8'), opts.SerializeToString())) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + return tfprof_node + + def profile_name_scope(self, options): + """Profile the statistics of graph nodes, organized by name scope. + + Args: + options: A dict of options. See core/profiler/g3doc/options.md. + + Returns: + a GraphNodeProto that records the results. + """ + opts = _build_options(options) + tfprof_node = tfprof_output_pb2.GraphNodeProto() + try: + tfprof_node.ParseFromString( + print_mdl.Profile('scope'.encode('utf-8'), opts.SerializeToString())) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + return tfprof_node + + def profile_graph(self, options): + """Profile the statistics of graph nodes, organized by dataflow graph. + + Args: + options: A dict of options. See core/profiler/g3doc/options.md. + + Returns: + a GraphNodeProto that records the results. + """ + opts = _build_options(options) + tfprof_node = tfprof_output_pb2.GraphNodeProto() + try: + tfprof_node.ParseFromString( + print_mdl.Profile('graph'.encode('utf-8'), opts.SerializeToString())) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + return tfprof_node + + def advise(self, options): + """Automatically detect problems and generate reports. + + Args: + options: A dict of options. See ALL_ADVICE example above. + + Returns: + An Advise proto that contains the reports from all checkers. + """ + advise_pb = tfprof_output_pb2.AdviceProto() + opts = _build_advisor_options(options) + advise_pb.ParseFromString( + print_mdl.Profile('advise'.encode('utf-8'), opts.SerializeToString())) + return advise_pb + + def serialize_to_string(self): + """Serialize the ProfileProto to a binary string. + + Users can write it to file for offline analysis by tfprof commandline + or graphical interface. + + Returns: + ProfileProto binary string. + """ + return print_mdl.SerializeToString() + + def _write_profile(self, filename): + """Writes the profile to a file.""" + print_mdl.WriteProfile(filename) + + +@tf_export(v1=['profiler.profile']) +def profile(graph=None, + run_meta=None, + op_log=None, + cmd='scope', + options=_DEFAULT_PROFILE_OPTIONS): + """Profile model. + + Tutorials and examples can be found in: + https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/profiler/g3doc/python_api.md + + Args: + graph: tf.Graph. If None and eager execution is not enabled, use default + graph. + run_meta: optional tensorflow.RunMetadata proto. It is necessary to + support run time information profiling, such as time and memory. + op_log: tensorflow.tfprof.OpLogProto proto. User can assign "types" to graph + nodes with op_log. "types" allow user to flexibly group and account + profiles using options['accounted_type_regexes']. + cmd: string. Either 'op', 'scope', 'graph' or 'code'. 'op' view organizes + profile using operation type. (e.g. MatMul) 'scope' view organizes profile + using graph node name scope. 'graph' view organizes profile using graph + node inputs/outputs. 'code' view organizes profile using Python call + stack. + options: A dict of options. See core/profiler/g3doc/options.md. + + Returns: + If cmd is 'scope' or 'graph', returns GraphNodeProto proto. + If cmd is 'op' or 'code', returns MultiGraphNodeProto proto. + Side effect: stdout/file/timeline.json depending on options['output'] + """ + if not graph and not context.executing_eagerly(): + graph = ops.get_default_graph() + + if options == _DEFAULT_PROFILE_OPTIONS: + options = ( + option_builder.ProfileOptionBuilder.trainable_variables_parameter()) + # pylint: disable=protected-access + op_log = tfprof_logger.merge_default_with_oplog( + graph, op_log, run_meta, add_trace=cmd == 'code') + # pylint: enable=protected-access + + opts = _build_options(options) + + run_meta_str = run_meta.SerializeToString() if run_meta else b'' + + graph_str = _graph_string(graph) + + if cmd == 'code' or cmd == 'op': + tfprof_node = tfprof_output_pb2.MultiGraphNodeProto() + ret = print_mdl.PrintModelAnalysis(graph_str, run_meta_str, + op_log.SerializeToString(), + cmd.encode('utf-8'), + opts.SerializeToString()) + try: + tfprof_node.ParseFromString(ret) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + + elif cmd == 'graph' or cmd == 'scope': + tfprof_node = tfprof_output_pb2.GraphNodeProto() + ret = print_mdl.PrintModelAnalysis(graph_str, run_meta_str, + op_log.SerializeToString(), + cmd.encode('utf-8'), + opts.SerializeToString()) + try: + tfprof_node.ParseFromString(ret) + except message.DecodeError as e: + sys.stderr.write('Cannot parse returned proto: %s.\n' % e) + else: + raise errors.InvalidArgumentError(None, None, 'unknown cmd: %s\n' % cmd) + + return tfprof_node + + +@tf_export(v1=['profiler.advise']) +def advise(graph=None, run_meta=None, options=_DEFAULT_ADVISE_OPTIONS): + """Auto profile and advise. + + Builds profiles and automatically check anomalies of various + aspects. For more details: + https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/README.md + + Args: + graph: tf.Graph. If None and eager execution is not enabled, use default + graph. + run_meta: optional tensorflow.RunMetadata proto. It is necessary to + support run time information profiling, such as time and memory. + options: see ALL_ADVICE example above. Default checks everything. + + Returns: + Returns AdviceProto proto + """ + if not graph and not context.executing_eagerly(): + graph = ops.get_default_graph() + + if options == _DEFAULT_ADVISE_OPTIONS: + options = ALL_ADVICE.copy() + + # pylint: disable=protected-access + op_log = tfprof_logger.merge_default_with_oplog( + graph, None, run_meta, add_trace=True) + # pylint: enable=protected-access + + run_meta_str = run_meta.SerializeToString() if run_meta else b'' + + opts = _build_advisor_options(options) + ret = tfprof_output_pb2.AdviceProto() + ret.ParseFromString( + print_mdl.PrintModelAnalysis( + _graph_string(graph), run_meta_str, op_log.SerializeToString(), + 'advise'.encode('utf-8'), opts.SerializeToString())) + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/option_builder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/option_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..756e203e805d796b1f4f94b207b294bfc0c2c4f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/option_builder.py @@ -0,0 +1,461 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for building profiler options.""" +import copy + +from tensorflow.python.profiler import tfprof_logger +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['profiler.ProfileOptionBuilder']) +class ProfileOptionBuilder(object): + # pylint: disable=line-too-long + """Option Builder for Profiling API. + + For tutorial on the options, see + https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md + + ```python + # Users can use pre-built options: + opts = ( + tf.profiler.ProfileOptionBuilder.trainable_variables_parameter()) + + # Or, build your own options: + opts = (tf.compat.v1.profiler.ProfileOptionBuilder() + .with_max_depth(10) + .with_min_micros(1000) + .select(['accelerator_micros']) + .with_stdout_output() + .build() + + # Or customize the pre-built options: + opts = (tf.compat.v1.profiler.ProfileOptionBuilder( + tf.profiler.ProfileOptionBuilder.time_and_memory()) + .with_displaying_options(show_name_regexes=['.*rnn.*']) + .build()) + + # Finally, profiling with the options: + _ = tf.compat.v1.profiler.profile(tf.compat.v1.get_default_graph(), + run_meta=run_meta, + cmd='scope', + options=opts) + ``` + """ + # pylint: enable=line-too-long + + def __init__(self, options=None): + """Constructor. + + Args: + options: Optional initial option dict to start with. + """ + if options is not None: + self._options = copy.deepcopy(options) + else: + self._options = {'max_depth': 100, + 'min_bytes': 0, + 'min_micros': 0, + 'min_params': 0, + 'min_float_ops': 0, + 'min_occurrence': 0, + 'order_by': 'name', + 'account_type_regexes': ['.*'], + 'start_name_regexes': ['.*'], + 'trim_name_regexes': [], + 'show_name_regexes': ['.*'], + 'hide_name_regexes': [], + 'account_displayed_op_only': False, + 'select': ['micros'], + 'step': -1, + 'output': 'stdout'} + + @staticmethod + def trainable_variables_parameter(): + """Options used to profile trainable variable parameters. + + Normally used together with 'scope' view. + + Returns: + A dict of profiling options. + """ + return {'max_depth': 10000, + 'min_bytes': 0, + 'min_micros': 0, + 'min_params': 0, + 'min_float_ops': 0, + 'min_occurrence': 0, + 'order_by': 'name', + 'account_type_regexes': [tfprof_logger.TRAINABLE_VARIABLES], + 'start_name_regexes': ['.*'], + 'trim_name_regexes': [], + 'show_name_regexes': ['.*'], + 'hide_name_regexes': [], + 'account_displayed_op_only': True, + 'select': ['params'], + 'step': -1, + 'output': 'stdout'} + + @staticmethod + def float_operation(): + # pylint: disable=line-too-long + """Options used to profile float operations. + + Please see https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/profile_model_architecture.md + on the caveats of calculating float operations. + + Returns: + A dict of profiling options. + """ + # pylint: enable=line-too-long + return {'max_depth': 10000, + 'min_bytes': 0, + 'min_micros': 0, + 'min_params': 0, + 'min_float_ops': 1, + 'min_occurrence': 0, + 'order_by': 'float_ops', + 'account_type_regexes': ['.*'], + 'start_name_regexes': ['.*'], + 'trim_name_regexes': [], + 'show_name_regexes': ['.*'], + 'hide_name_regexes': [], + 'account_displayed_op_only': True, + 'select': ['float_ops'], + 'step': -1, + 'output': 'stdout'} + + @staticmethod + def time_and_memory(min_micros=1, min_bytes=1, min_accelerator_micros=0, + min_cpu_micros=0, min_peak_bytes=0, min_residual_bytes=0, + min_output_bytes=0): + """Show operation time and memory consumptions. + + Args: + min_micros: Only show profiler nodes with execution time + no less than this. It sums accelerator and cpu times. + min_bytes: Only show profiler nodes requested to allocate no less bytes + than this. + min_accelerator_micros: Only show profiler nodes spend no less than + this time on accelerator (e.g. GPU). + min_cpu_micros: Only show profiler nodes spend no less than + this time on cpu. + min_peak_bytes: Only show profiler nodes using no less than this bytes + at peak (high watermark). For profiler nodes consist of multiple + graph nodes, it sums the graph nodes' peak_bytes. + min_residual_bytes: Only show profiler nodes have no less than + this bytes not being de-allocated after Compute() ends. For + profiler nodes consist of multiple graph nodes, it sums the + graph nodes' residual_bytes. + min_output_bytes: Only show profiler nodes have no less than this bytes + output. The output are not necessarily allocated by this profiler + nodes. + Returns: + A dict of profiling options. + """ + return {'max_depth': 10000, + 'min_bytes': min_bytes, + 'min_peak_bytes': min_peak_bytes, + 'min_residual_bytes': min_residual_bytes, + 'min_output_bytes': min_output_bytes, + 'min_micros': min_micros, + 'min_accelerator_micros': min_accelerator_micros, + 'min_cpu_micros': min_cpu_micros, + 'min_params': 0, + 'min_float_ops': 0, + 'min_occurrence': 0, + 'order_by': 'micros', + 'account_type_regexes': ['.*'], + 'start_name_regexes': ['.*'], + 'trim_name_regexes': [], + 'show_name_regexes': ['.*'], + 'hide_name_regexes': [], + 'account_displayed_op_only': True, + 'select': ['micros', 'bytes'], + 'step': -1, + 'output': 'stdout'} + + def build(self): + """Build a profiling option. + + Returns: + A dict of profiling options. + """ + return copy.deepcopy(self._options) + + def with_max_depth(self, max_depth): + """Set the maximum depth of display. + + The depth depends on profiling view. For 'scope' view, it's the + depth of name scope hierarchy (tree), for 'op' view, it's the number + of operation types (list), etc. + + Args: + max_depth: Maximum depth of the data structure to display. + Returns: + self + """ + self._options['max_depth'] = max_depth + return self + + def with_min_memory(self, + min_bytes=0, + min_peak_bytes=0, + min_residual_bytes=0, + min_output_bytes=0): + """Only show profiler nodes consuming no less than 'min_bytes'. + + Args: + min_bytes: Only show profiler nodes requested to allocate no less bytes + than this. + min_peak_bytes: Only show profiler nodes using no less than this bytes + at peak (high watermark). For profiler nodes consist of multiple + graph nodes, it sums the graph nodes' peak_bytes. + min_residual_bytes: Only show profiler nodes have no less than + this bytes not being de-allocated after Compute() ends. For + profiler nodes consist of multiple graph nodes, it sums the + graph nodes' residual_bytes. + min_output_bytes: Only show profiler nodes have no less than this bytes + output. The output are not necessarily allocated by this profiler + nodes. + Returns: + self + """ + self._options['min_bytes'] = min_bytes + self._options['min_peak_bytes'] = min_peak_bytes + self._options['min_residual_bytes'] = min_residual_bytes + self._options['min_output_bytes'] = min_output_bytes + return self + + def with_min_execution_time(self, + min_micros=0, + min_accelerator_micros=0, + min_cpu_micros=0): + """Only show profiler nodes consuming no less than 'min_micros'. + + Args: + min_micros: Only show profiler nodes with execution time + no less than this. It sums accelerator and cpu times. + min_accelerator_micros: Only show profiler nodes spend no less than + this time on accelerator (e.g. GPU). + min_cpu_micros: Only show profiler nodes spend no less than + this time on cpu. + Returns: + self + """ + self._options['min_micros'] = min_micros + self._options['min_accelerator_micros'] = min_accelerator_micros + self._options['min_cpu_micros'] = min_cpu_micros + return self + + def with_min_parameters(self, min_params): + """Only show profiler nodes holding no less than 'min_params' parameters. + + 'Parameters' normally refers the weights of in TensorFlow variables. + It reflects the 'capacity' of models. + + Args: + min_params: Only show profiler nodes holding number parameters + no less than this. + Returns: + self + """ + self._options['min_params'] = min_params + return self + + def with_min_occurrence(self, min_occurrence): + # pylint: disable=line-too-long + """Only show profiler nodes including no less than 'min_occurrence' graph nodes. + + A "node" means a profiler output node, which can be a python line + (code view), an operation type (op view), or a graph node + (graph/scope view). A python line includes all graph nodes created by that + line, while an operation type includes all graph nodes of that type. + + Args: + min_occurrence: Only show nodes including no less than this. + Returns: + self + """ + # pylint: enable=line-too-long + self._options['min_occurrence'] = min_occurrence + return self + + def with_min_float_operations(self, min_float_ops): + # pylint: disable=line-too-long + """Only show profiler nodes consuming no less than 'min_float_ops'. + + Please see https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/profile_model_architecture.md + on the caveats of calculating float operations. + + Args: + min_float_ops: Only show profiler nodes with float operations + no less than this. + Returns: + self + """ + # pylint: enable=line-too-long + self._options['min_float_ops'] = min_float_ops + return self + + def with_accounted_types(self, account_type_regexes): + """Selectively counting statistics based on node types. + + Here, 'types' means the profiler nodes' properties. Profiler by default + consider device name (e.g. /job:xx/.../device:GPU:0) and operation type + (e.g. MatMul) as profiler nodes' properties. User can also associate + customized 'types' to profiler nodes through OpLogProto proto. + + For example, user can select profiler nodes placed on gpu:0 with: + `account_type_regexes=['.*gpu:0.*']` + + If none of a node's properties match the specified regexes, the node is + not displayed nor accounted. + + Args: + account_type_regexes: A list of regexes specifying the types. + Returns: + self. + """ + self._options['account_type_regexes'] = copy.copy(account_type_regexes) + return self + + def with_node_names(self, + start_name_regexes=None, + show_name_regexes=None, + hide_name_regexes=None, + trim_name_regexes=None): + """Regular expressions used to select profiler nodes to display. + + After 'with_accounted_types' is evaluated, 'with_node_names' are + evaluated as follows: + + For a profile data structure, profiler first finds the profiler + nodes matching 'start_name_regexes', and starts displaying profiler + nodes from there. Then, if a node matches 'show_name_regexes' and + doesn't match 'hide_name_regexes', it's displayed. If a node matches + 'trim_name_regexes', profiler stops further searching that branch. + + Args: + start_name_regexes: list of node name regexes to start displaying. + show_name_regexes: list of node names regexes to display. + hide_name_regexes: list of node_names regexes that should be hidden. + trim_name_regexes: list of node name regexes from where to stop. + Returns: + self + """ + if start_name_regexes is not None: + self._options['start_name_regexes'] = copy.copy(start_name_regexes) + if show_name_regexes is not None: + self._options['show_name_regexes'] = copy.copy(show_name_regexes) + if hide_name_regexes is not None: + self._options['hide_name_regexes'] = copy.copy(hide_name_regexes) + if trim_name_regexes is not None: + self._options['trim_name_regexes'] = copy.copy(trim_name_regexes) + return self + + def account_displayed_op_only(self, is_true): + """Whether only account the statistics of displayed profiler nodes. + + Args: + is_true: If true, only account statistics of nodes eventually + displayed by the outputs. + Otherwise, a node's statistics are accounted by its parents + as long as it's types match 'account_type_regexes', even if + it is hidden from the output, say, by hide_name_regexes. + Returns: + self + """ + self._options['account_displayed_op_only'] = is_true + return self + + def with_empty_output(self): + """Do not generate side-effect outputs.""" + self._options['output'] = 'none' + return self + + def with_stdout_output(self): + """Print the result to stdout.""" + self._options['output'] = 'stdout' + return self + + def with_file_output(self, outfile): + """Print the result to a file.""" + self._options['output'] = 'file:outfile=%s' % outfile + return self + + def with_timeline_output(self, timeline_file): + """Generate a timeline json file.""" + self._options['output'] = 'timeline:outfile=%s' % timeline_file + return self + + def with_pprof_output(self, pprof_file): + """Generate a pprof profile gzip file. + + To use the pprof file: + pprof -png --nodecount=100 --sample_index=1 + + Args: + pprof_file: filename for output, usually suffixed with .pb.gz. + Returns: + self. + """ + self._options['output'] = 'pprof:outfile=%s' % pprof_file + return self + + def order_by(self, attribute): + # pylint: disable=line-too-long + """Order the displayed profiler nodes based on a attribute. + + Supported attribute includes micros, bytes, occurrence, params, etc. + https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md + + Args: + attribute: An attribute the profiler node has. + Returns: + self + """ + # pylint: enable=line-too-long + self._options['order_by'] = attribute + return self + + def select(self, attributes): + # pylint: disable=line-too-long + """Select the attributes to display. + + See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md + for supported attributes. + + Args: + attributes: A list of attribute the profiler node has. + Returns: + self + """ + # pylint: enable=line-too-long + self._options['select'] = copy.copy(attributes) + return self + + def with_step(self, step): + """Which profile step to use for profiling. + + The 'step' here refers to the step defined by `Profiler.add_step()` API. + + Args: + step: When multiple steps of profiles are available, select which step's + profile to use. If -1, use average of all available steps. + Returns: + self + """ + self._options['step'] = step + return self diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1d34122c558011b0b05836bda649336e371911 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler.py @@ -0,0 +1,51 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""profiler python module provides APIs to profile TensorFlow models. +""" +# pylint: disable=unused-import +from tensorflow.core.profiler.tfprof_log_pb2 import OpLogProto +from tensorflow.core.profiler.tfprof_output_pb2 import AdviceProto +from tensorflow.core.profiler.tfprof_output_pb2 import GraphNodeProto +from tensorflow.core.profiler.tfprof_output_pb2 import MultiGraphNodeProto + +from tensorflow.python.profiler.model_analyzer import advise +from tensorflow.python.profiler.model_analyzer import profile +from tensorflow.python.profiler.model_analyzer import Profiler +from tensorflow.python.profiler.option_builder import ProfileOptionBuilder +from tensorflow.python.profiler.tfprof_logger import write_op_log + +from tensorflow.python.util.tf_export import tf_export + + +_allowed_symbols = [ + 'Profiler', + 'profile', + 'ProfileOptionBuilder', + 'advise', + 'write_op_log', +] + +_allowed_symbols.extend([ + 'GraphNodeProto', + 'MultiGraphNodeProto', + 'AdviceProto', + 'OpLogProto', +]) + +# Export protos +tf_export(v1=['profiler.GraphNodeProto'])(GraphNodeProto) +tf_export(v1=['profiler.MultiGraphNodeProto'])(MultiGraphNodeProto) +tf_export(v1=['profiler.AdviceProto'])(AdviceProto) +tf_export(v1=['profiler.OpLogProto'])(OpLogProto) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_client.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_client.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f76fc420680f72ba0c057913c48f11fe1fa907 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_client.py @@ -0,0 +1,172 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Profiler client APIs.""" + +from tensorflow.python.framework import errors +from tensorflow.python.profiler.internal import _pywrap_profiler + +from tensorflow.python.util.tf_export import tf_export + +_GRPC_PREFIX = 'grpc://' + + +@tf_export('profiler.experimental.client.trace', v1=[]) +def trace(service_addr, + logdir, + duration_ms, + worker_list='', + num_tracing_attempts=3, + options=None): + """Sends gRPC requests to one or more profiler servers to perform on-demand profiling. + + This method will block the calling thread until it receives responses from all + servers or until deadline expiration. Both single host and multiple host + profiling are supported on CPU, GPU, and TPU. + The profiled results will be saved by each server to the specified TensorBoard + log directory (i.e. the directory you save your model checkpoints). Use the + TensorBoard profile plugin to view the visualization and analysis results. + + Args: + service_addr: A comma delimited string of gRPC addresses of the workers to + profile. + e.g. service_addr='grpc://localhost:6009' + service_addr='grpc://10.0.0.2:8466,grpc://10.0.0.3:8466' + service_addr='grpc://localhost:12345,grpc://localhost:23456' + logdir: Path to save profile data to, typically a TensorBoard log directory. + This path must be accessible to both the client and server. + e.g. logdir='gs://your_tb_dir' + duration_ms: Duration of tracing or monitoring in milliseconds. Must be + greater than zero. + worker_list: An optional TPU only configuration. The list of workers to + profile in the current session. + num_tracing_attempts: Optional. Automatically retry N times when no trace + event is collected (default 3). + options: profiler.experimental.ProfilerOptions namedtuple for miscellaneous + profiler options. + + Raises: + InvalidArgumentError: For when arguments fail validation checks. + UnavailableError: If no trace event was collected. + + Example usage (CPU/GPU): + + ```python + # Start a profiler server before your model runs. + tf.profiler.experimental.server.start(6009) + # (Model code goes here). + # Send gRPC request to the profiler server to collect a trace of your model. + tf.profiler.experimental.client.trace('grpc://localhost:6009', + '/nfs/tb_log', 2000) + ``` + + Example usage (Multiple GPUs): + + ```python + # E.g. your worker IP addresses are 10.0.0.2, 10.0.0.3, 10.0.0.4, and you + # would like to schedule start of profiling 1 second from now, for a + # duration of 2 seconds. + options['delay_ms'] = 1000 + tf.profiler.experimental.client.trace( + 'grpc://10.0.0.2:8466,grpc://10.0.0.3:8466,grpc://10.0.0.4:8466', + 'gs://your_tb_dir', + 2000, + options=options) + ``` + + Example usage (TPU): + + ```python + # Send gRPC request to a TPU worker to collect a trace of your model. A + # profiler service has been started in the TPU worker at port 8466. + # E.g. your TPU IP address is 10.0.0.2 and you want to profile for 2 seconds + # . + tf.profiler.experimental.client.trace('grpc://10.0.0.2:8466', + 'gs://your_tb_dir', 2000) + ``` + + Example usage (Multiple TPUs): + + ```python + # Send gRPC request to a TPU pod to collect a trace of your model on + # multiple TPUs. A profiler service has been started in all the TPU workers + # at the port 8466. + # E.g. your TPU IP addresses are 10.0.0.2, 10.0.0.3, 10.0.0.4, and you want + # to profile for 2 seconds. + tf.profiler.experimental.client.trace( + 'grpc://10.0.0.2:8466', + 'gs://your_tb_dir', + 2000, + '10.0.0.2:8466,10.0.0.3:8466,10.0.0.4:8466') + ``` + + Launch TensorBoard and point it to the same logdir you provided to this API. + + ```shell + # logdir can be gs://your_tb_dir as in the above examples. + $ tensorboard --logdir=/tmp/tb_log + ``` + + Open your browser and go to localhost:6006/#profile to view profiling results. + + """ + if duration_ms <= 0: + raise errors.InvalidArgumentError(None, None, + 'duration_ms must be greater than zero.') + + opts = dict(options._asdict()) if options is not None else {} + _pywrap_profiler.trace( + _strip_addresses(service_addr, _GRPC_PREFIX), logdir, worker_list, True, + duration_ms, num_tracing_attempts, opts) + + +@tf_export('profiler.experimental.client.monitor', v1=[]) +def monitor(service_addr, duration_ms, level=1): + """Sends grpc requests to profiler server to perform on-demand monitoring. + + The monitoring result is a light weight performance summary of your model + execution. This method will block the caller thread until it receives the + monitoring result. This method currently supports Cloud TPU only. + + Args: + service_addr: gRPC address of profiler service e.g. grpc://10.0.0.2:8466. + duration_ms: Duration of monitoring in ms. + level: Choose a monitoring level between 1 and 2 to monitor your job. Level + 2 is more verbose than level 1 and shows more metrics. + + Returns: + A string of monitoring output. + + Example usage: + + ```python + # Continuously send gRPC requests to the Cloud TPU to monitor the model + # execution. + + for query in range(0, 100): + print( + tf.profiler.experimental.client.monitor('grpc://10.0.0.2:8466', 1000)) + ``` + + """ + return _pywrap_profiler.monitor( + _strip_prefix(service_addr, _GRPC_PREFIX), duration_ms, level, True) + + +def _strip_prefix(s, prefix): + return s[len(prefix):] if s.startswith(prefix) else s + + +def _strip_addresses(addresses, prefix): + return ','.join([_strip_prefix(s, prefix) for s in addresses.split(',')]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6715c07123b3558b3b0d539ac15b18355e300f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/profiler_v2.py @@ -0,0 +1,212 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorFlow 2.x Profiler. + +The profiler has two modes: +- Programmatic Mode: start(logdir), stop(), and Profiler class. Profiling starts + when calling start(logdir) or create a Profiler class. + Profiling stops when calling stop() to save to + TensorBoard logdir or destroying the Profiler class. +- Sampling Mode: start_server(). It will perform profiling after receiving a + profiling request. + +NOTE: Only one active profiler session is allowed. Use of simultaneous +Programmatic Mode and Sampling Mode is undefined and will likely fail. + +NOTE: The Keras TensorBoard callback will automatically perform sampled +profiling. Before enabling customized profiling, set the callback flag +"profile_batches=[]" to disable automatic sampled profiling. +""" + +import collections +import threading + +from tensorflow.python.framework import errors +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler.internal import _pywrap_profiler +from tensorflow.python.util.tf_export import tf_export + +_profiler = None +_profiler_lock = threading.Lock() + + +@tf_export('profiler.experimental.ProfilerOptions', v1=[]) +class ProfilerOptions( + collections.namedtuple('ProfilerOptions', [ + 'host_tracer_level', 'python_tracer_level', 'device_tracer_level', + 'delay_ms' + ])): + """Options for finer control over the profiler. + + Use `tf.profiler.experimental.ProfilerOptions` to control `tf.profiler` + behavior. + + Fields: + host_tracer_level: Adjust CPU tracing level. Values are: `1` - critical info + only, `2` - info, `3` - verbose. [default value is `2`] + python_tracer_level: Toggle tracing of Python function calls. Values are: + `1` - enabled, `0` - disabled [default value is `0`] + device_tracer_level: Adjust device (TPU/GPU) tracing level. Values are: + `1` - enabled, `0` - disabled [default value is `1`] + delay_ms: Requests for all hosts to start profiling at a timestamp that is + `delay_ms` away from the current time. `delay_ms` is in milliseconds. If + zero, each host will start profiling immediately upon receiving the + request. Default value is `None`, allowing the profiler guess the best + value. + """ + + def __new__(cls, + host_tracer_level=2, + python_tracer_level=0, + device_tracer_level=1, + delay_ms=None): + return super(ProfilerOptions, + cls).__new__(cls, host_tracer_level, python_tracer_level, + device_tracer_level, delay_ms) + + +@tf_export('profiler.experimental.start', v1=[]) +def start(logdir, options=None): + """Start profiling TensorFlow performance. + + Args: + logdir: Profiling results log directory. + options: `ProfilerOptions` namedtuple to specify miscellaneous profiler + options. See example usage below. + + Raises: + AlreadyExistsError: If a profiling session is already running. + + Example usage: + ```python + options = tf.profiler.experimental.ProfilerOptions(host_tracer_level = 3, + python_tracer_level = 1, + device_tracer_level = 1) + tf.profiler.experimental.start('logdir_path', options = options) + # Training code here + tf.profiler.experimental.stop() + ``` + + To view the profiling results, launch TensorBoard and point it to `logdir`. + Open your browser and go to `localhost:6006/#profile` to view profiling + results. + + """ + global _profiler + with _profiler_lock: + if _profiler is not None: + raise errors.AlreadyExistsError(None, None, + 'Another profiler is running.') + _profiler = _pywrap_profiler.ProfilerSession() + try: + # support for namedtuple in pybind11 is missing, we change it to + # dict type first. + opts = dict(options._asdict()) if options is not None else {} + _profiler.start(logdir, opts) + except errors.AlreadyExistsError: + logging.warning('Another profiler session is running which is probably ' + 'created by profiler server. Please avoid using profiler ' + 'server and profiler APIs at the same time.') + raise errors.AlreadyExistsError(None, None, + 'Another profiler is running.') + except Exception: + _profiler = None + raise + + +@tf_export('profiler.experimental.stop', v1=[]) +def stop(save=True): + """Stops the current profiling session. + + The profiler session will be stopped and profile results can be saved. + + Args: + save: An optional variable to save the results to TensorBoard. Default True. + + Raises: + UnavailableError: If there is no active profiling session. + """ + global _profiler + with _profiler_lock: + if _profiler is None: + raise errors.UnavailableError( + None, None, + 'Cannot export profiling results. No profiler is running.') + if save: + try: + _profiler.export_to_tb() + except Exception: + _profiler = None + raise + _profiler = None + + +def warmup(): + """Warm-up the profiler session. + + The profiler session will set up profiling context, including loading CUPTI + library for GPU profiling. This is used for improving the accuracy of + the profiling results. + + """ + start('') + stop(save=False) + + +@tf_export('profiler.experimental.server.start', v1=[]) +def start_server(port): + """Start a profiler grpc server that listens to given port. + + The profiler server will exit when the process finishes. The service is + defined in tensorflow/core/profiler/profiler_service.proto. + + Args: + port: port profiler server listens to. + Example usage: ```python tf.profiler.experimental.server.start(6009) # do + your training here. + """ + _pywrap_profiler.start_server(port) + + +@tf_export('profiler.experimental.Profile', v1=[]) +class Profile(object): + """Context-manager profile API. + + Profiling will start when entering the scope, and stop and save the results to + the logdir when exits the scope. Open TensorBoard profile tab to view results. + + Example usage: + ```python + with tf.profiler.experimental.Profile("/path/to/logdir"): + # do some work + ``` + """ + + def __init__(self, logdir, options=None): + """Creates a context manager object for profiler API. + + Args: + logdir: profile data will save to this directory. + options: An optional `tf.profiler.experimental.ProfilerOptions` can be + provided to fine tune the profiler's behavior. + """ + self._logdir = logdir + self._options = options + + def __enter__(self): + start(self._logdir, self._options) + + def __exit__(self, typ, value, tb): + stop() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/tfprof_logger.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/tfprof_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..876dc4525d5579453258f5f82e0b1dad7aa53913 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/tfprof_logger.py @@ -0,0 +1,215 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Logging tensorflow::tfprof::OpLogProto. + +OpLogProto is used to add extra model information for offline analysis. +""" +import os +import sys + +from tensorflow.core.profiler import tfprof_log_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.platform import gfile +from tensorflow.python.profiler.internal import flops_registry # pylint: disable=unused-import +from tensorflow.python.util.tf_export import tf_export + +TRAINABLE_VARIABLES = '_trainable_variables' +REGISTERED_FLOP_STATS = 'flops' + + +def _fill_missing_graph_shape(graph, run_meta): + """Fill Tensor shapes in 'graph' with run time shape from 'run_meta'.""" + for dev_stat in run_meta.step_stats.dev_stats: + for node_stat in dev_stat.node_stats: + if not node_stat.output: + continue + try: + op = graph.get_operation_by_name(node_stat.node_name) + except KeyError as e: + # Graph doesn't contains the node_stat, usually RecvTensor. + continue + if len(node_stat.output) != len(op.outputs): + # For example, conditional op has only 1 output at run time. + continue + for (i, node_stat_out) in enumerate(node_stat.output): + if op.outputs[i].get_shape().is_fully_defined(): + continue + node_stat_dims = node_stat_out.tensor_description.shape.dim + node_stat_shape = tensor_shape.TensorShape( + [d.size for d in node_stat_dims]) + try: + op.outputs[i].set_shape(op.outputs[i].get_shape().merge_with( + node_stat_shape)) + except ValueError as e: + sys.stderr.write('Node %s incompatible shapes: %s.\n' % + (node_stat.node_name, e)) + return graph + + +def _str_id(s, str_to_id): + """Maps string to id.""" + num = str_to_id.get(s, None) + if num is None: + num = len(str_to_id) + str_to_id[s] = num + return num + + +def _get_logged_ops(graph, run_meta=None, add_trace=True, + add_trainable_var=True): + """Extract trainable model parameters and FLOPs for ops from a Graph. + + Args: + graph: tf.Graph. + run_meta: RunMetadata proto used to complete shape information. + add_trace: Whether to add op trace information. + add_trainable_var: Whether to assign tf.compat.v1.trainable_variables() op + type '_trainable_variables'. + Returns: + logged_ops: dict mapping from op_name to OpLogEntry. + string_to_id: dict mapping from string to id. + """ + if run_meta: + graph = _fill_missing_graph_shape(graph, run_meta) + + op_missing_shape = 0 + logged_ops = {} + string_to_id = {} + string_to_id['none'] = len(string_to_id) + # TODO(xpan): Work with Profiler more efficiently. + for op in graph.get_operations(): + try: + stats = ops.get_stats_for_node_def( + graph, op.node_def, REGISTERED_FLOP_STATS) + except ValueError: + # Catch Exception When shape is incomplete. Skip it. + op_missing_shape += 1 + stats = None + + entry = tfprof_log_pb2.OpLogEntry() + entry.name = op.name + add_entry = False + if stats and stats.value: + entry.float_ops = int(stats.value) + add_entry = True + + if add_trace: + if op.traceback: + for filename, lineno, funcname, line in op.traceback: + trace = entry.code_def.traces.add() + trace.file_id = _str_id(filename, string_to_id) if filename else 0 + trace.lineno = lineno if lineno else -1 + trace.function_id = _str_id(funcname, string_to_id) if funcname else 0 + trace.line_id = _str_id(line, string_to_id) if line else 0 + # TODO(slebedev): remove this unused field from the proto. + trace.func_start_line = -1 + add_entry = True + + if add_entry: + logged_ops[entry.name] = entry + + if add_trainable_var: + for v in graph.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES): + if v.op.name not in logged_ops: + entry = tfprof_log_pb2.OpLogEntry() + entry.name = v.op.name + entry.types.append(TRAINABLE_VARIABLES) + logged_ops[entry.name] = entry + else: + logged_ops[v.op.name].types.append(TRAINABLE_VARIABLES) + + if op_missing_shape > 0 and not run_meta: + sys.stderr.write('%d ops no flops stats due to incomplete shapes.\n' % + op_missing_shape) + return logged_ops, string_to_id + + +def merge_default_with_oplog(graph, op_log=None, run_meta=None, + add_trace=True, add_trainable_var=True): + """Merge the tfprof default extra info with caller's op_log. + + Args: + graph: tf.Graph. If None and eager execution is not enabled, use + default graph. + op_log: OpLogProto proto. + run_meta: RunMetadata proto used to complete shape information. + add_trace: Whether to add op trace information. + add_trainable_var: Whether to assign tf.compat.v1.trainable_variables() op + type '_trainable_variables'. + Returns: + tmp_op_log: Merged OpLogProto proto. + """ + if not graph and not context.executing_eagerly(): + graph = ops.get_default_graph() + + tmp_op_log = tfprof_log_pb2.OpLogProto() + if not graph: + return tmp_op_log + + logged_ops, string_to_id = _get_logged_ops( + graph, run_meta, add_trace=add_trace, add_trainable_var=add_trainable_var) + + if not op_log: + tmp_op_log.log_entries.extend(logged_ops.values()) + else: + all_ops = {} + for entry in op_log.log_entries: + all_ops[entry.name] = entry + for op_name, entry in logged_ops.items(): + if op_name in all_ops: + all_ops[op_name].types.extend(entry.types) + if entry.float_ops > 0 and all_ops[op_name].float_ops == 0: + all_ops[op_name].float_ops = entry.float_ops + if entry.code_def.traces and not all_ops[op_name].code_def.traces: + all_ops[op_name].code_def.MergeFrom(entry.code_def) + else: + all_ops[op_name] = entry + tmp_op_log.log_entries.extend(all_ops.values()) + + for s, i in string_to_id.items(): + tmp_op_log.id_to_string[i] = s + return tmp_op_log + + +@tf_export(v1=['profiler.write_op_log']) +def write_op_log(graph, log_dir, op_log=None, run_meta=None, add_trace=True): + """Log provided 'op_log', and add additional model information below. + + The API also assigns ops in tf.compat.v1.trainable_variables() an op type + called '_trainable_variables'. + The API also logs 'flops' statistics for ops with op.RegisterStatistics() + defined. flops calculation depends on Tensor shapes defined in 'graph', + which might not be complete. 'run_meta', if provided, completes the shape + information with best effort. + + Args: + graph: tf.Graph. If None and eager execution is not enabled, use + default graph. + log_dir: directory to write the log file. + op_log: (Optional) OpLogProto proto to be written. If not provided, an new + one is created. + run_meta: (Optional) RunMetadata proto that helps flops computation using + run time shape information. + add_trace: Whether to add python code trace information. + Used to support "code" view. + """ + if not graph and not context.executing_eagerly(): + graph = ops.get_default_graph() + op_log = merge_default_with_oplog(graph, op_log, run_meta, add_trace) + + with gfile.Open(os.path.join(log_dir, 'tfprof_log'), 'w') as log: + log.write(op_log.SerializeToString()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/trace.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..6b6bc7ac243a75de041e7ae472cbabc65426178e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/profiler/trace.py @@ -0,0 +1,187 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Trace allows the profiler to trace Python events.""" + +import functools + +from tensorflow.python.profiler.internal import _pywrap_traceme +from tensorflow.python.util.tf_export import tf_export + +# This variable is modified by PythonHooks::Start/Stop() in C++. Such +# arrangement will reduce the number of calls through pybind11. +enabled = False + + +@tf_export('profiler.experimental.Trace', v1=[]) +class Trace(object): + """Context manager that generates a trace event in the profiler. + + A trace event will start when entering the context, and stop and save the + result to the profiler when exiting the context. Open TensorBoard Profile tab + and choose trace viewer to view the trace event in the timeline. + + Trace events are created only when the profiler is enabled. More information + on how to use the profiler can be found at + https://tensorflow.org/guide/profiler + + Example usage: + ```python + tf.profiler.experimental.start('logdir') + for step in range(num_steps): + # Creates a trace event for each training step with the step number. + with tf.profiler.experimental.Trace("Train", step_num=step, _r=1): + train_fn() + tf.profiler.experimental.stop() + ``` + """ + + def __init__(self, name, **kwargs): + """Creates a trace event in the profiler. + + Args: + name: The name of the trace event. + **kwargs: Keyword arguments added to the trace event. + Both the key and value are of types that + can be converted to strings, which will be + interpreted by the profiler according to the + traceme name. + + Example usage: + + ```python + + tf.profiler.experimental.start('logdir') + for step in range(num_steps): + # Creates a trace event for each training step with the + # step number. + with tf.profiler.experimental.Trace("Train", step_num=step): + train_fn() + tf.profiler.experimental.stop() + + ``` + The example above uses the keyword argument "step_num" to specify the + training step being traced. + """ + if enabled: + # Creating _pywrap_traceme.TraceMe starts the clock. + self._traceme = _pywrap_traceme.TraceMe(name, **kwargs) + else: + self._traceme = None + + def __enter__(self): + # Starting the TraceMe clock here would require an extra Python->C++ call. + return self + + def set_metadata(self, **kwargs): + """Sets metadata in this trace event. + + Args: + **kwargs: metadata in key-value pairs. + + This method enables setting metadata in a trace event after it is + created. + + Example usage: + + ```python + + def call(function): + with tf.profiler.experimental.Trace("call", + function_name=function.name) as tm: + binary, in_cache = jit_compile(function) + tm.set_metadata(in_cache=in_cache) + execute(binary) + + ``` + In this example, we want to trace how much time spent on + calling a function, which includes compilation and execution. + The compilation can be either getting a cached copy of the + binary or actually generating the binary, which is indicated + by the boolean "in_cache" returned by jit_compile(). We need + to use set_metadata() to pass in_cache because we did not know + the in_cache value when the trace was created (and we cannot + create the trace after jit_compile(), because we want + to measure the entire duration of call()). + """ + if self._traceme and kwargs: + self._traceme.SetMetadata(**kwargs) + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._traceme: + self._traceme.Stop() + + +def trace_wrapper(trace_name, **trace_kwargs): + """Decorator alternative to `with Trace(): ...`. It's faster. + + Args: + trace_name: The name of the trace event, or a callable to be traced, in + which case the name is inferred from qualname or name of the callable. + **trace_kwargs: Keyword arguments added to the trace event. Both the key and + value are of types that can be converted to strings, which will be + interpreted by the profiler according to the traceme name. + + Returns: + A decorator that can wrap a function and apply `Trace` scope if needed, + or a decorated function if used as a decorator directly. + + Example usage: + ```python + + @trace_wrapper('trace_name') + def func(x, y, z): + pass # code to execute and apply `Trace` if needed. + + # Equivalent to + # with Trace('trace_name'): + # func(1, 2, 3) + func(1, 2, 3) + ``` + + or + ```python + + @trace_wrapper + def func(x, y, z): + pass # code to execute and apply `Trace` if needed. + + # Equivalent to + # with Trace(func.__qualname__): + # func(1, 2, 3) + func(1, 2, 3) + ``` + + """ + + if callable(trace_name): + func = trace_name + name = getattr(func, '__qualname__', None) + if not name: + name = getattr(func, '__name__', 'unknown function') + + return trace_wrapper(name)(func) + + def inner_wrapper(func): + + @functools.wraps(func) + def wrapped(*args, **kwargs): + if enabled: + with Trace(trace_name, **trace_kwargs): + return func(*args, **kwargs) + return func(*args, **kwargs) + + return wrapped + + return inner_wrapper diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf09de5384848a9de11f66c81ff899fae2ccc0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder.py @@ -0,0 +1,25 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel builder. + +Builds a SavedModel that can be saved to storage, is language neutral, and +enables systems to produce, consume, or transform TensorFlow Models. + +""" + +# pylint: disable=unused-import +from tensorflow.python.saved_model.builder_impl import _SavedModelBuilder +from tensorflow.python.saved_model.builder_impl import SavedModelBuilder +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..18bdc53a3d77e86c6b67fbbc989fb10731663516 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/builder_impl.py @@ -0,0 +1,824 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel builder implementation.""" + +import functools +import os + +from google.protobuf.any_pb2 import Any + +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saved_model_pb2 +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging +from tensorflow.python.saved_model import fingerprinting_utils +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model.pywrap_saved_model import constants +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.training import saver as tf_saver +from tensorflow.python.util import compat +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import tf_export + +# API label for SavedModel metrics. +_SAVE_BUILDER_LABEL = "save_v1_builder" + + +# Base class for the SavedModelBuilder that is only used by Tensorflow +# internally. Please use tf.compat.v1.saved_model.SavedModelBuilder instead. +@tf_export("__internal__.saved_model.SavedModelBuilder", v1=[]) +class _SavedModelBuilder(object): + """Builds the `SavedModel` protocol buffer and saves variables and assets. + + The `SavedModelBuilder` class provides the functionality to build a + `SavedModel` protocol buffer. Specifically, this allows multiple meta + graphs to be saved as part of a single language-neutral `SavedModel`, + while sharing variables and assets. + + To build a SavedModel, the first meta graph must be saved with variables. + Subsequent meta graphs will simply be saved with their graph definitions. If + assets need to be saved and written or copied to disk, they can be provided + when the meta graph def is added. If multiple meta graph defs are associated + an asset of the same name, only the first version is retained. + + Each meta graph added to the SavedModel must be annotated with tags. The tags + provide a means to identify the specific meta graph to load and restore, along + with the shared set of variables and assets. + + Typical usage for the `SavedModelBuilder`: + + ```python + ... + builder = tf.compat.v1.saved_model.Builder(export_dir) + + with tf.compat.v1.Session(graph=tf.Graph()) as sess: + ... + builder.add_meta_graph_and_variables(sess, + ["foo-tag"], + signature_def_map=foo_signatures, + assets_list=foo_assets) + ... + + with tf.compat.v1.Session(graph=tf.Graph()) as sess: + ... + builder.add_meta_graph(["bar-tag", "baz-tag"]) + ... + + builder.save() + ``` + + Note: This function will only be available through the v1 compatibility + library as tf.compat.v1.saved_model.builder.SavedModelBuilder or + tf.compat.v1.saved_model.Builder. Tensorflow 2.0 will introduce a new + object-based method of creating SavedModels. + """ + + def __init__(self, export_dir): + self._saved_model = saved_model_pb2.SavedModel() + self._saved_model.saved_model_schema_version = ( + constants.SAVED_MODEL_SCHEMA_VERSION) + + self._export_dir = export_dir + if file_io.file_exists(export_dir): + if file_io.list_directory(export_dir): + raise AssertionError( + f"Export directory {export_dir} already exists, and isn't empty. " + "Please choose a different export directory, or delete all the " + "contents of the specified directory.") + else: + file_io.recursive_create_dir(self._export_dir) + + # Boolean to track whether variables and assets corresponding to the + # SavedModel have been saved. Specifically, the first meta graph to be added + # MUST use the add_meta_graph_and_variables() API. Subsequent add operations + # on the SavedModel MUST use the add_meta_graph() API which does not save + # weights. + self._has_saved_variables = False + self._saved_asset_files = set() + + def _save_and_write_assets(self, meta_graph_def, assets_list=None): + """Saves asset to the meta graph and writes asset files to disk. + + Args: + meta_graph_def: The meta graph def to which the assets will be added. + assets_list: The list where the asset paths are setup. + """ + # Creates a function that adds assets into the meta graph def. + write_fn = functools.partial(_add_asset_to_metagraph, meta_graph_def) + asset_filename_map = _maybe_save_assets(write_fn, assets_list) + + # Return if there are no assets to write. + if not asset_filename_map: + tf_logging.info("No assets to write.") + return + + # Copy assets from source path to destination path. + copy_assets_to_destination_dir(asset_filename_map, self._export_dir, + self._saved_asset_files) + + def _tag_and_add_meta_graph(self, meta_graph_def, tags, signature_def_map): + """Tags the meta graph def and adds it to the SavedModel. + + Tags the meta graph def with the supplied tags, adds signature defs to it if + provided and appends the meta graph def to the SavedModel proto. + + Args: + meta_graph_def: The meta graph def to add to the SavedModel. + tags: The set of tags to annotate the meta graph def with. + signature_def_map: The map of signature defs to be added to the meta graph + def. + """ + for tag in tags: + meta_graph_def.meta_info_def.tags.append(tag) + + if signature_def_map is not None: + for key in signature_def_map: + meta_graph_def.signature_def[key].CopyFrom(signature_def_map[key]) + + proto_meta_graph_def = self._saved_model.meta_graphs.add() + proto_meta_graph_def.CopyFrom(meta_graph_def) + + def _validate_tensor_info(self, tensor_info): + """Validates the `TensorInfo` proto. + + Checks if the `encoding` (`name` or `coo_sparse` or `type_spec`) and + `dtype` fields exist and are non-empty. + + Args: + tensor_info: `TensorInfo` protocol buffer to validate. + + Raises: + AssertionError: If the `encoding` or `dtype` fields of the supplied + `TensorInfo` proto are not populated. + """ + if tensor_info is None: + raise AssertionError( + "All TensorInfo protos used in the SignatureDefs must have the name " + "and dtype fields set.") + if tensor_info.WhichOneof("encoding") is None: + # TODO(soergel) validate each of the fields of coo_sparse + raise AssertionError( + f"Invalid `tensor_info`: {tensor_info}. All TensorInfo protos used " + "in the SignatureDefs must have one of the 'encoding' fields (e.g., " + "name or coo_sparse) set.") + if tensor_info.WhichOneof("encoding") == "composite_tensor": + for component in tensor_info.composite_tensor.components: + self._validate_tensor_info(component) + elif tensor_info.dtype == types_pb2.DT_INVALID: + raise AssertionError( + f"Invalid `tensor_info`: {tensor_info}. All TensorInfo protos used in" + " the SignatureDefs must have the dtype field set.") + + def _validate_signature_def_map(self, signature_def_map): + """Validates the `SignatureDef` entries in the signature def map. + + Validation of entries in the signature def map includes ensuring that the + `name` and `dtype` fields of the TensorInfo protos of the `inputs` and + `outputs` of each `SignatureDef` are populated. Also ensures that reserved + SignatureDef keys for the initialization and train ops are not used. + + Args: + signature_def_map: The map of signature defs to be validated. + + Raises: + AssertionError: If a TensorInfo is not valid. + KeyError: If a reserved signature key is used in the map. + """ + for signature_def_key in signature_def_map: + signature_def = signature_def_map[signature_def_key] + inputs = signature_def.inputs + outputs = signature_def.outputs + for inputs_key in inputs: + self._validate_tensor_info(inputs[inputs_key]) + for outputs_key in outputs: + self._validate_tensor_info(outputs[outputs_key]) + if constants.INIT_OP_SIGNATURE_KEY in signature_def_map: + raise KeyError( + f"SignatureDef map key \"{constants.INIT_OP_SIGNATURE_KEY}\" is " + "reserved for initialization. Please use a different key.") + if constants.TRAIN_OP_SIGNATURE_KEY in signature_def_map: + raise KeyError( + f"SignatureDef map key \"{constants.TRAIN_OP_SIGNATURE_KEY}\" is " + f"reserved for the train op. Please use a different key.") + + def _maybe_create_saver(self, saver=None): + """Creates a sharded saver if one does not already exist.""" + if not saver: + # Initialize a saver to generate a sharded output for all saveables in the + # current scope. + saver = tf_saver.Saver( + variables._all_saveable_objects(), # pylint: disable=protected-access + sharded=True, + write_version=saver_pb2.SaverDef.V2, + allow_empty=True) + return saver + + def add_meta_graph(self, + tags, + signature_def_map=None, + assets_list=None, + clear_devices=False, + init_op=None, + train_op=None, + saver=None): + """Adds the current meta graph to the SavedModel. + + Creates a Saver in the current scope and uses the Saver to export the meta + graph def. Invoking this API requires the `add_meta_graph_and_variables()` + API to have been invoked before. + + Args: + tags: The set of tags to annotate the meta graph def with. + signature_def_map: The map of signature defs to be added to the meta graph + def. + assets_list: Assets to be saved with SavedModel. Note + that this list should be a subset of the assets saved as part of + the first meta graph in the SavedModel. + clear_devices: Set to true if the device info on the default graph should + be cleared. + init_op: Op or group of ops to execute when the graph is loaded. Note + that when the init_op is specified it is run after the restore op at + load-time. + train_op: Op or group of opts that trains the model when run. This will + not be run automatically when the graph is loaded, instead saved in + a SignatureDef accessible through the exported MetaGraph. + saver: An instance of tf.compat.v1.train.Saver that will be used to export + the metagraph. If None, a sharded Saver that restores all variables will + be used. + + Raises: + AssertionError: If the variables for the SavedModel have not been saved + yet, or if the graph already contains one or more legacy init ops. + """ + if not self._has_saved_variables: + raise AssertionError( + "Graph state including variables and assets has not been saved yet. " + "Please invoke `add_meta_graph_and_variables()` first.") + + # Validate the signature def map to ensure all included TensorInfos are + # properly populated. + signature_def_map = signature_def_map or {} + self._validate_signature_def_map(signature_def_map) + + # Create a SignatureDef pointing to the graph initialization op, which will + # be added to the MetaGraphDef. + _add_op_to_signature_def_map(signature_def_map, init_op, + constants.INIT_OP_SIGNATURE_KEY) + _add_op_to_signature_def_map(signature_def_map, train_op, + constants.TRAIN_OP_SIGNATURE_KEY) + + saver = self._maybe_create_saver(saver) + + # The graph almost certainly previously contained at least one Saver, and + # possibly several (e.g. one for loading a pretrained embedding, and another + # for the model weights). Removing the preexisting ones was the + # motivation for the clear_extraneous_savers option, but it turns out that + # there are edge cases where that option breaks the graph. Until that is + # resolved, we just leave the option set to False for now. + # TODO(soergel): Reinstate clear_extraneous_savers=True when possible. + meta_graph_def = saver.export_meta_graph( + clear_devices=clear_devices, strip_default_attrs=True) + + # Save asset files and write them to disk, if any. + self._save_and_write_assets(meta_graph_def, assets_list) + + # Tag the meta graph def and add it to the SavedModel. + self._tag_and_add_meta_graph(meta_graph_def, tags, signature_def_map) + + def add_meta_graph_and_variables(self, + sess, + tags, + signature_def_map=None, + assets_list=None, + clear_devices=False, + init_op=None, + train_op=None, + strip_default_attrs=False, + saver=None): + # pylint: disable=line-too-long + """Adds the current meta graph to the SavedModel and saves variables. + + Creates a Saver to save the variables from the provided session. Exports the + corresponding meta graph def. This function assumes that the variables to be + saved have been initialized. For a given `SavedModelBuilder`, this API must + be called exactly once and for the first meta graph to save. For subsequent + meta graph defs to be added, the `add_meta_graph()` API must be used. + + Args: + sess: The TensorFlow session from which to save the meta graph and + variables. + tags: The set of tags with which to save the meta graph. + signature_def_map: The map of signature def map to add to the meta graph + def. + assets_list: Assets to be saved with SavedModel. + clear_devices: Set to true if the device info on the default graph should + be cleared. + init_op: Op or group of ops to execute when the graph is loaded. Note + that when the init_op is specified it is run after the restore op at + load-time. + train_op: Op or group of ops that trains the model when run. This will + not be run automatically when the graph is loaded, instead saved in + a SignatureDef accessible through the exported MetaGraph. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the NodeDefs. For a detailed guide, see + [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + saver: An instance of tf.compat.v1.train.Saver that will be used to export the + metagraph and save variables. If None, a sharded Saver that restores + all variables will be used. + + """ + # pylint: enable=line-too-long + if self._has_saved_variables: + raise AssertionError("Graph state including variables and assets has " + "already been saved. Please invoke " + "`add_meta_graph()` instead.") + + # Validate the signature def map to ensure all included TensorInfos are + # properly populated. + signature_def_map = signature_def_map or {} + self._validate_signature_def_map(signature_def_map) + + # Create a SignatureDef pointing to the graph initialization op, which will + # be added to the MetaGraphDef. + _add_op_to_signature_def_map(signature_def_map, init_op, + constants.INIT_OP_SIGNATURE_KEY) + _add_op_to_signature_def_map(signature_def_map, train_op, + constants.TRAIN_OP_SIGNATURE_KEY) + + path_helpers.get_or_create_variables_dir(self._export_dir) + variables_path = path_helpers.get_variables_path(self._export_dir) + + saver = self._maybe_create_saver(saver) + + # Save the variables. Also, disable writing the checkpoint state proto. The + # file is not used during SavedModel loading. In addition, since a + # SavedModel can be copied or moved, this avoids the checkpoint state to + # become outdated. + saver.save(sess, variables_path, write_meta_graph=False, write_state=False) + + # Export the meta graph def. + + # The graph almost certainly previously contained at least one Saver, and + # possibly several (e.g. one for loading a pretrained embedding, and another + # for the model weights). Removing the preexisting ones was the + # motivation for the clear_extraneous_savers option, but it turns out that + # there are edge cases where that option breaks the graph. Until that is + # resolved, we just leave the option set to False for now. + # TODO(soergel): Reinstate clear_extraneous_savers=True when possible. + meta_graph_def = saver.export_meta_graph( + clear_devices=clear_devices, strip_default_attrs=strip_default_attrs) + + # Save asset files and write them to disk, if any. + self._save_and_write_assets(meta_graph_def, assets_list) + + # Tag the meta graph def and add it to the SavedModel. + self._tag_and_add_meta_graph(meta_graph_def, tags, signature_def_map) + + # Mark this instance of SavedModel as having saved variables, such that + # subsequent attempts to save variables will fail. + self._has_saved_variables = True + + def save(self, as_text=False): + """Writes a `SavedModel` protocol buffer to disk. + + The function writes the SavedModel protocol buffer to the export directory + in a serialized format. + + Args: + as_text: Writes the SavedModel protocol buffer in text format to + disk. Protocol buffers in text format are useful for debugging, but + parsing fails when it encounters an unknown field and so is not forward + compatible. This means changes to TensorFlow may prevent deployment of + new text format SavedModels to existing serving binaries. Do not deploy + `as_text` SavedModels to production. + + Returns: + The path to which the SavedModel protocol buffer was written. + """ + metrics.IncrementWriteApi(_SAVE_BUILDER_LABEL) + if not file_io.file_exists(self._export_dir): + file_io.recursive_create_dir(self._export_dir) + + if as_text: + path = file_io.join( + compat.as_bytes(self._export_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT)) + file_io.write_string_to_file(path, str(self._saved_model)) + else: + path = file_io.join( + compat.as_bytes(self._export_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB)) + file_io.write_string_to_file( + path, self._saved_model.SerializeToString(deterministic=True)) + # Placeholder for internal TF1 model fingerprint write + tf_logging.info("SavedModel written to: %s", compat.as_text(path)) + metrics.IncrementWrite(write_version="1") + + return path + + +@tf_export(v1=["saved_model.Builder", "saved_model.builder.SavedModelBuilder"]) # pylint: disable=missing-docstring +class SavedModelBuilder(_SavedModelBuilder): + __doc__ = _SavedModelBuilder.__doc__.replace("assets_list", + "assets_collection") + + def __init__(self, export_dir): + super(SavedModelBuilder, self).__init__(export_dir=export_dir) + + def _add_collections(self, assets_collection, main_op, train_op): + """Add asset and op collections to be saved.""" + # Save asset files and write them to disk, if any. + self._save_and_write_assets(assets_collection) + + self._maybe_add_main_op(main_op) + + self._add_train_op(train_op) + + def _save_and_write_assets(self, assets_collection_to_add=None): + """Saves asset to the meta graph and writes asset files to disk. + + Args: + assets_collection_to_add: The collection where the asset paths are setup. + """ + # Add assets to the collection with key `saved_model.ASSETS_KEY`, in the + # graph. + asset_filename_map = _maybe_save_assets(_add_asset_to_collection, + assets_collection_to_add) + + # Return if there are no assets to write. + if not asset_filename_map: + tf_logging.info("No assets to write.") + return + + # Copy assets from source path to destination path. + copy_assets_to_destination_dir(asset_filename_map, self._export_dir, + self._saved_asset_files) + + def _maybe_add_main_op(self, main_op): + """Adds main op to the SavedModel. + + Args: + main_op: Main op to run as part of graph initialization. If None, no main + op will be added to the graph. + + Raises: + TypeError: If the main op is provided but is not of type `Operation`. + ValueError: if the Graph already contains an init op. + """ + if main_op is None: + return + + if not isinstance(main_op, ops.Operation): + raise TypeError(f"Expected {main_op} to be an Operation but got type " + f"{type(main_op)} instead.") + + # Validate that no other init ops have been added to this graph already. + # We check main_op and legacy_init_op for thoroughness and explicitness. + for init_op_key in (constants.MAIN_OP_KEY, constants.LEGACY_INIT_OP_KEY): + if ops.get_collection(init_op_key): + raise ValueError( + "Graph already contains one or more main ops under the " + f"collection {init_op_key}.") + + ops.add_to_collection(constants.MAIN_OP_KEY, main_op) + + def _add_train_op(self, train_op): + """Add train op to the SavedModel. + + Note that this functionality is in development, and liable to be + moved elsewhere. + + Args: + train_op: Op or group of ops that are used for training. These are stored + as a collection with key TRAIN_OP_KEY, but not executed. + + Raises: + TypeError if Train op is not of type `Operation`. + """ + if train_op is not None: + if (not isinstance(train_op, tensor.Tensor) and + not isinstance(train_op, ops.Operation)): + raise TypeError(f"`train_op` {train_op} needs to be a Tensor or Op.") + ops.add_to_collection(constants.TRAIN_OP_KEY, train_op) + + @deprecated_args(None, + "Pass your op to the equivalent parameter main_op instead.", + "legacy_init_op") + def add_meta_graph(self, + tags, + signature_def_map=None, + assets_collection=None, + legacy_init_op=None, + clear_devices=False, + main_op=None, + strip_default_attrs=False, + saver=None): + if not self._has_saved_variables: + raise AssertionError( + "Graph state including variables and assets has not been saved yet. " + "Please invoke `add_meta_graph_and_variables()` first.") + + # Validate the signature def map to ensure all included TensorInfos are + # properly populated. + signature_def_map = signature_def_map or {} + self._validate_signature_def_map(signature_def_map) + + # legacy_init_op is deprecated, and going away in TF 2.0. + # Re-mapping to main_op, as treatment is identical regardless. + main_op = main_op if main_op is not None else legacy_init_op + + # Add assets and ops + self._add_collections(assets_collection, main_op, None) + + saver = self._maybe_create_saver(saver) + + # The graph almost certainly previously contained at least one Saver, and + # possibly several (e.g. one for loading a pretrained embedding, and another + # for the model weights). Removing the preexisting ones was the + # motivation for the clear_extraneous_savers option, but it turns out that + # there are edge cases where that option breaks the graph. Until that is + # resolved, we just leave the option set to False for now. + # TODO(soergel): Reinstate clear_extraneous_savers=True when possible. + meta_graph_def = saver.export_meta_graph( + clear_devices=clear_devices, strip_default_attrs=strip_default_attrs) + + # Tag the meta graph def and add it to the SavedModel. + self._tag_and_add_meta_graph(meta_graph_def, tags, signature_def_map) + + @deprecated_args(None, + "Pass your op to the equivalent parameter main_op instead.", + "legacy_init_op") + def add_meta_graph_and_variables(self, + sess, + tags, + signature_def_map=None, + assets_collection=None, + legacy_init_op=None, + clear_devices=False, + main_op=None, + strip_default_attrs=False, + saver=None): + if self._has_saved_variables: + raise AssertionError("Graph state including variables and assets has " + "already been saved. Please invoke " + "`add_meta_graph()` instead.") + + # Validate the signature def map to ensure all included TensorInfos are + # properly populated. + signature_def_map = signature_def_map or {} + self._validate_signature_def_map(signature_def_map) + + # legacy_init_op is deprecated, and going away in TF 2.0. + # Re-mapping to main_op, as treatment is identical regardless. + main_op = main_op or legacy_init_op + + # Add assets and ops + self._add_collections(assets_collection, main_op, None) + + path_helpers.get_or_create_variables_dir(self._export_dir) + variables_path = path_helpers.get_variables_path(self._export_dir) + + saver = self._maybe_create_saver(saver) + + # Save the variables. Also, disable writing the checkpoint state proto. The + # file is not used during SavedModel loading. In addition, since a + # SavedModel can be copied or moved, this avoids the checkpoint state to + # become outdated. + saver.save(sess, variables_path, write_meta_graph=False, write_state=False) + + # Export the meta graph def. + + # The graph almost certainly previously contained at least one Saver, and + # possibly several (e.g. one for loading a pretrained embedding, and another + # for the model weights). Removing the preexisting ones was the + # motivation for the clear_extraneous_savers option, but it turns out that + # there are edge cases where that option breaks the graph. Until that is + # resolved, we just leave the option set to False for now. + # TODO(soergel): Reinstate clear_extraneous_savers=True when possible. + meta_graph_def = saver.export_meta_graph( + clear_devices=clear_devices, strip_default_attrs=strip_default_attrs) + + # Tag the meta graph def and add it to the SavedModel. + self._tag_and_add_meta_graph(meta_graph_def, tags, signature_def_map) + + # Mark this instance of SavedModel as having saved variables, such that + # subsequent attempts to save variables will fail. + self._has_saved_variables = True + + add_meta_graph.__doc__ = _SavedModelBuilder.add_meta_graph.__doc__.replace( + "assets_list", "assets_collection") + add_meta_graph_and_variables.__doc__ = \ + _SavedModelBuilder.add_meta_graph_and_variables.__doc__.replace( + "assets_list", "assets_collection") + + +def _maybe_save_assets(write_fn, assets_to_add=None): + """Saves assets to the meta graph. + + Args: + write_fn: A function callback that writes assets into meta graph. + assets_to_add: The list where the asset paths are setup. + + Returns: + A dict of asset basenames for saving to the original full path to the asset. + + Raises: + ValueError: Indicating an invalid filepath tensor. + """ + # Map of target file names to original filenames + asset_filename_map = {} + + if assets_to_add is None: + tf_logging.info("No assets to save.") + return asset_filename_map + + # Iterate over the supplied assets, build the `AssetFile` proto and add them + # to the meta graph. + for asset_tensor in assets_to_add: + asset_source_filepath = _asset_path_from_tensor(asset_tensor) + if not asset_source_filepath: + raise ValueError(f"Asset filepath tensor {asset_tensor} in is invalid.") + + asset_filename = get_asset_filename_to_add( + asset_source_filepath, asset_filename_map) + + # Call the passed-in function that builds AssetFileDef proto and adds it + # to either the collection or asset_file_def field of the meta graph. + # Note that this should be done even when the file is a duplicate of an + # already-added file, as the tensor reference should still exist. + write_fn(asset_filename, asset_tensor) + + # In the cases where we are adding a duplicate, this will result in the + # last of the filepaths being the one used for copying the file to the + # SavedModel. Since the files in question are the same, it doesn't matter + # either way. + asset_filename_map[asset_filename] = asset_source_filepath + + tf_logging.info("Assets added to graph.") + return asset_filename_map + + +def get_asset_filename_to_add(asset_filepath, asset_filename_map): + """Get a unique basename to add to the SavedModel if this file is unseen. + + Assets come from users as full paths, and we save them out to the + SavedModel as basenames. In some cases, the basenames collide. Here, + we dedupe asset basenames by first checking if the file is the same, + and, if different, generate and return an index-suffixed basename + that can be used to add the asset to the SavedModel. + + Args: + asset_filepath: the full path to the asset that is being saved + asset_filename_map: a dict of filenames used for saving the asset in + the SavedModel to full paths from which the filenames were derived. + + Returns: + Uniquified filename string if the file is not a duplicate, or the original + filename if the file has already been seen and saved. + """ + asset_filename = os.path.basename(asset_filepath) + + if asset_filename not in asset_filename_map: + # This is an unseen asset. Safe to add. + return asset_filename + + other_asset_filepath = asset_filename_map[asset_filename] + if other_asset_filepath == asset_filepath: + # This is the same file, stored twice in the list. No need + # to make unique. + return asset_filename + + # Else, asset_filename is in the map, and the filepath is different. Dedupe. + if not file_io.filecmp(asset_filepath, other_asset_filepath): + # Files are different; dedupe filenames. + return _get_unique_asset_filename(asset_filename, asset_filename_map) + + # Files are the same; don't make unique. + return asset_filename + + +def _get_unique_asset_filename(asset_filename, asset_filename_map): + i = 1 + unique_filename = asset_filename + while unique_filename in asset_filename_map: + unique_filename = compat.as_bytes("_").join( + [compat.as_bytes(asset_filename), compat.as_bytes(str(i))]) + i += 1 + return unique_filename + + +def _asset_path_from_tensor(path_tensor): + """Returns the filepath value stored in constant `path_tensor`. + + Args: + path_tensor: Tensor of a file-path. + + Returns: + The string value i.e. path of the tensor, if valid. + + Raises: + TypeError if tensor does not match expected op type, dtype or value. + """ + if not isinstance(path_tensor, tensor.Tensor): + raise TypeError(f"Asset path tensor {path_tensor} must be a Tensor.") + if path_tensor.op.type != "Const": + raise TypeError(f"Asset path tensor {path_tensor} must be of type constant." + f"Has type {path_tensor.op.type} instead.") + if path_tensor.dtype != dtypes.string: + raise TypeError(f"Asset path tensor {path_tensor}` must be of dtype string." + f"Has type {path_tensor.dtype} instead.") + str_values = path_tensor.op.get_attr("value").string_val + if len(str_values) != 1: + raise TypeError(f"Asset path tensor {path_tensor} must be a scalar.") + return str_values[0] + + +def _add_asset_to_metagraph(meta_graph_def, asset_filename, asset_tensor): + """Builds an asset proto and adds it to the meta graph def. + + Args: + meta_graph_def: The meta graph def to which the asset will be added. + asset_filename: The filename of the asset to be added. + asset_tensor: The asset tensor used to populate the tensor info of the asset + proto. + """ + asset_proto = meta_graph_def.asset_file_def.add() + asset_proto.filename = asset_filename + asset_proto.tensor_info.name = asset_tensor.name + + +def copy_assets_to_destination_dir(asset_filename_map, destination_dir, + saved_files=None): + """Copy all assets from source path to destination path. + + Args: + asset_filename_map: a dict of filenames used for saving the asset in + the SavedModel to full paths from which the filenames were derived. + destination_dir: the destination directory that assets are stored in. + saved_files: a set of destination filepaths that have already been copied + and will be skipped + """ + if saved_files is None: + saved_files = set() + + assets_destination_dir = path_helpers.get_or_create_assets_dir( + destination_dir) + + # Copy each asset from source path to destination path. + for asset_basename, asset_source_filepath in asset_filename_map.items(): + asset_destination_filepath = file_io.join( + compat.as_bytes(assets_destination_dir), + compat.as_bytes(asset_basename)) + + # Copy if source file exists, src & dst are not the same, and dst is not in + # saved_files + if (file_io.file_exists(asset_source_filepath) and + asset_source_filepath != asset_destination_filepath and + asset_destination_filepath not in saved_files): + file_io.copy( + asset_source_filepath, asset_destination_filepath, overwrite=True) + saved_files.add(asset_destination_filepath) + + tf_logging.info("Assets written to: %s", + compat.as_text(assets_destination_dir)) + + +def _add_asset_to_collection(asset_filename, asset_tensor): + """Builds an asset proto and adds it to the asset collection of the graph. + + Args: + asset_filename: The filename of the asset to be added. + asset_tensor: The asset tensor used to populate the tensor info of the + asset proto. + """ + asset_proto = meta_graph_pb2.AssetFileDef() + asset_proto.filename = asset_filename + asset_proto.tensor_info.name = asset_tensor.name + + asset_any_proto = Any() + asset_any_proto.Pack(asset_proto) + ops.add_to_collection(constants.ASSETS_KEY, asset_any_proto) + + +def _add_op_to_signature_def_map(signature_def_map, op, key): + if op is not None: + signature_def_map[key] = signature_def_utils.op_signature_def(op, key) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd3dbb7d591c4ddf045b68570ff200af0f4ccd0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/constants.py @@ -0,0 +1,135 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Constants for SavedModel save and restore operations. + +The source of truth for these constants is in +tensorflow/cc/saved_model/constants.h. + +""" +from tensorflow.python.saved_model.pywrap_saved_model import constants +from tensorflow.python.util.tf_export import tf_export + +# Subdirectory name containing the asset files. +ASSETS_DIRECTORY = constants.ASSETS_DIRECTORY +tf_export( + "saved_model.ASSETS_DIRECTORY", + v1=[ + "saved_model.ASSETS_DIRECTORY", "saved_model.constants.ASSETS_DIRECTORY" + ]).export_constant(__name__, "ASSETS_DIRECTORY") + +# Subdirectory name containing unmanaged files from higher-level APIs. +EXTRA_ASSETS_DIRECTORY = constants.EXTRA_ASSETS_DIRECTORY + +# CollectionDef key containing SavedModel assets. +ASSETS_KEY = constants.ASSETS_KEY +tf_export( + "saved_model.ASSETS_KEY", + v1=["saved_model.ASSETS_KEY", + "saved_model.constants.ASSETS_KEY"]).export_constant( + __name__, "ASSETS_KEY") + +# CollectionDef key for the legacy init op. +LEGACY_INIT_OP_KEY = constants.LEGACY_INIT_OP_KEY +tf_export( + v1=[ + "saved_model.LEGACY_INIT_OP_KEY", + "saved_model.constants.LEGACY_INIT_OP_KEY" + ]).export_constant(__name__, "LEGACY_INIT_OP_KEY") + +# CollectionDef key for the SavedModel main op. +MAIN_OP_KEY = constants.MAIN_OP_KEY +tf_export( + v1=["saved_model.MAIN_OP_KEY", + "saved_model.constants.MAIN_OP_KEY"]).export_constant( + __name__, "MAIN_OP_KEY") + +# CollectionDef key for the SavedModel train op. +# Not exported while export_all_saved_models is experimental. +TRAIN_OP_KEY = constants.TRAIN_OP_KEY + +# Schema version for SavedModel. +SAVED_MODEL_SCHEMA_VERSION = constants.SAVED_MODEL_SCHEMA_VERSION +tf_export( + "saved_model.SAVED_MODEL_SCHEMA_VERSION", + v1=[ + "saved_model.SAVED_MODEL_SCHEMA_VERSION", + "saved_model.constants.SAVED_MODEL_SCHEMA_VERSION" + ]).export_constant(__name__, "SAVED_MODEL_SCHEMA_VERSION") + +# File name prefix for SavedModel protocol buffer. +SAVED_MODEL_FILENAME_PREFIX = constants.SAVED_MODEL_FILENAME_PREFIX + +# File name for SavedModel protocol buffer. +SAVED_MODEL_FILENAME_PB = constants.SAVED_MODEL_FILENAME_PB +tf_export( + "saved_model.SAVED_MODEL_FILENAME_PB", + v1=[ + "saved_model.SAVED_MODEL_FILENAME_PB", + "saved_model.constants.SAVED_MODEL_FILENAME_PB" + ]).export_constant(__name__, "SAVED_MODEL_FILENAME_PB") + +# File name for SavedModel chunked protocol buffer (experimental). +SAVED_MODEL_FILENAME_CPB = constants.SAVED_MODEL_FILENAME_CPB + +# File name for text version of SavedModel protocol buffer. +SAVED_MODEL_FILENAME_PBTXT = constants.SAVED_MODEL_FILENAME_PBTXT +tf_export( + "saved_model.SAVED_MODEL_FILENAME_PBTXT", + v1=[ + "saved_model.SAVED_MODEL_FILENAME_PBTXT", + "saved_model.constants.SAVED_MODEL_FILENAME_PBTXT" + ]).export_constant(__name__, "SAVED_MODEL_FILENAME_PBTXT") + +# Subdirectory where debugging related files are written. +DEBUG_DIRECTORY = constants.DEBUG_DIRECTORY +tf_export( + "saved_model.DEBUG_DIRECTORY", + v1=[ + "saved_model.DEBUG_DIRECTORY", + "saved_model.constants.DEBUG_DIRECTORY", + ]).export_constant(__name__, "DEBUG_DIRECTORY") + +# File name for GraphDebugInfo protocol buffer which corresponds to the +# SavedModel. +DEBUG_INFO_FILENAME_PB = constants.DEBUG_INFO_FILENAME_PB +tf_export( + "saved_model.DEBUG_INFO_FILENAME_PB", + v1=[ + "saved_model.DEBUG_INFO_FILENAME_PB", + "saved_model.constants.DEBUG_INFO_FILENAME_PB" + ]).export_constant(__name__, "DEBUG_INFO_FILENAME_PB") + +# Subdirectory name containing the variables/checkpoint files. +VARIABLES_DIRECTORY = constants.VARIABLES_DIRECTORY +tf_export( + "saved_model.VARIABLES_DIRECTORY", + v1=[ + "saved_model.VARIABLES_DIRECTORY", + "saved_model.constants.VARIABLES_DIRECTORY" + ]).export_constant(__name__, "VARIABLES_DIRECTORY") + +# File name used for variables. +VARIABLES_FILENAME = constants.VARIABLES_FILENAME +tf_export( + "saved_model.VARIABLES_FILENAME", + v1=[ + "saved_model.VARIABLES_FILENAME", + "saved_model.constants.VARIABLES_FILENAME" + ]).export_constant(__name__, "VARIABLES_FILENAME") + +# The initialization and train ops for a MetaGraph are stored in the +# signature def map. The ops are added to the map with the following keys. +INIT_OP_SIGNATURE_KEY = constants.INIT_OP_SIGNATURE_KEY +TRAIN_OP_SIGNATURE_KEY = constants.TRAIN_OP_SIGNATURE_KEY diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8be59cfaa69476ced53041c73cf0ccb4bb3c97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting.py @@ -0,0 +1,176 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Methods for SavedModel fingerprinting. + +This module contains classes and functions for reading the SavedModel +fingerprint. +""" + +from tensorflow.core.protobuf import fingerprint_pb2 +from tensorflow.python.saved_model.pywrap_saved_model import fingerprinting as fingerprinting_pywrap +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("saved_model.experimental.Fingerprint", v1=[]) +class Fingerprint(object): + """The SavedModel fingerprint. + + Each attribute of this class is named after a field name in the + FingerprintDef proto and contains the value of the respective field in the + protobuf. + + Attributes: + saved_model_checksum: A uint64 containing the `saved_model_checksum`. + graph_def_program_hash: A uint64 containing `graph_def_program_hash`. + signature_def_hash: A uint64 containing the `signature_def_hash`. + saved_object_graph_hash: A uint64 containing the `saved_object_graph_hash`. + checkpoint_hash: A uint64 containing the`checkpoint_hash`. + version: An int32 containing the producer field of the VersionDef. + """ + + def __init__( + self, + saved_model_checksum=None, + graph_def_program_hash=None, + signature_def_hash=None, + saved_object_graph_hash=None, + checkpoint_hash=None, + version=None, + ): + """Initializes the instance based on values in the SavedModel fingerprint. + + Args: + saved_model_checksum: Value of the`saved_model_checksum`. + graph_def_program_hash: Value of the `graph_def_program_hash`. + signature_def_hash: Value of the `signature_def_hash`. + saved_object_graph_hash: Value of the `saved_object_graph_hash`. + checkpoint_hash: Value of the `checkpoint_hash`. + version: Value of the producer field of the VersionDef. + """ + self.saved_model_checksum = saved_model_checksum + self.graph_def_program_hash = graph_def_program_hash + self.signature_def_hash = signature_def_hash + self.saved_object_graph_hash = saved_object_graph_hash + self.checkpoint_hash = checkpoint_hash + self.version = version + + @classmethod + def from_proto(cls, proto): + """Constructs Fingerprint object from protocol buffer message.""" + if isinstance(proto, bytes): + proto = fingerprint_pb2.FingerprintDef.FromString(proto) + try: + return Fingerprint( + proto.saved_model_checksum, + proto.graph_def_program_hash, + proto.signature_def_hash, + proto.saved_object_graph_hash, + proto.checkpoint_hash, + proto.version) + except AttributeError as e: + raise ValueError( + f"Given proto could not be deserialized as fingerprint." + f"{e}") from None + + def __eq__(self, other): + if (isinstance(other, Fingerprint) or + isinstance(other, fingerprint_pb2.FingerprintDef)): + try: + return ( + self.saved_model_checksum == other.saved_model_checksum and + self.graph_def_program_hash == other.graph_def_program_hash and + self.signature_def_hash == other.signature_def_hash and + self.saved_object_graph_hash == other.saved_object_graph_hash and + self.checkpoint_hash == other.checkpoint_hash) + except AttributeError: + pass + return False + + def __str__(self): + return "\n".join([ + f"SavedModel Fingerprint", + f" saved_model_checksum: {self.saved_model_checksum}", + f" graph_def_program_hash: {self.graph_def_program_hash}", + f" signature_def_hash: {self.signature_def_hash}", + f" saved_object_graph_hash: {self.saved_object_graph_hash}", + f" checkpoint_hash: {self.checkpoint_hash}" + ]) + + def __repr__(self): + return (f"Fingerprint({self.saved_model_checksum}, " + f"{self.graph_def_program_hash}, " + f"{self.signature_def_hash}, " + f"{self.saved_object_graph_hash}, " + f"{self.checkpoint_hash})") + + def singleprint(self): + """Canonical fingerprinting ID for a SavedModel. + + Uniquely identifies a SavedModel based on the regularized fingerprint + attributes. (saved_model_checksum is sensitive to immaterial changes and + thus non-deterministic.) + + Returns: + The string concatenation of `graph_def_program_hash`, + `signature_def_hash`, `saved_object_graph_hash`, and `checkpoint_hash` + fingerprint attributes (separated by '/'). + + Raises: + ValueError: If the fingerprint fields cannot be used to construct the + singleprint. + """ + try: + return fingerprinting_pywrap.Singleprint(self.graph_def_program_hash, + self.signature_def_hash, + self.saved_object_graph_hash, + self.checkpoint_hash) + except (TypeError, fingerprinting_pywrap.FingerprintException) as e: + raise ValueError( + f"Encounted invalid fingerprint values when constructing singleprint." + f"graph_def_program_hash: {self.graph_def_program_hash}" + f"signature_def_hash: {self.signature_def_hash}" + f"saved_object_graph_hash: {self.saved_object_graph_hash}" + f"checkpoint_hash: {self.checkpoint_hash}" + f"{e}") from None + + +@tf_export("saved_model.experimental.read_fingerprint", v1=[]) +def read_fingerprint(export_dir): + """Reads the fingerprint of a SavedModel in `export_dir`. + + Returns a `tf.saved_model.experimental.Fingerprint` object that contains + the values of the SavedModel fingerprint, which is persisted on disk in the + `fingerprint.pb` file in the `export_dir`. + + Read more about fingerprints in the SavedModel guide at + https://www.tensorflow.org/guide/saved_model. + + Args: + export_dir: The directory that contains the SavedModel. + + Returns: + A `tf.saved_model.experimental.Fingerprint`. + + Raises: + FileNotFoundError: If no or an invalid fingerprint is found. + """ + try: + fingerprint = fingerprinting_pywrap.ReadSavedModelFingerprint(export_dir) + except fingerprinting_pywrap.FileNotFoundException as e: + raise FileNotFoundError(f"SavedModel Fingerprint Error: {e}") from None # pylint: disable=raise-missing-from + except fingerprinting_pywrap.FingerprintException as e: + raise RuntimeError(f"SavedModel Fingerprint Error: {e}") from None # pylint: disable=raise-missing-from + return Fingerprint.from_proto( + fingerprint_pb2.FingerprintDef().FromString(fingerprint)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..631b3e2e270fbc07251afc1473d7e42ede64492c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/fingerprinting_utils.py @@ -0,0 +1,152 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for SavedModel fingerprinting. + +This module contains utility classes and functions for working with the +SavedModel fingerprint. +""" + +from absl import logging + +from tensorflow.core.config import flags +from tensorflow.core.protobuf import fingerprint_pb2 +from tensorflow.python.lib.io import file_io +from tensorflow.python.saved_model import fingerprinting +from tensorflow.python.saved_model.pywrap_saved_model import constants +from tensorflow.python.saved_model.pywrap_saved_model import fingerprinting as fingerprinting_pywrap +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.util import compat + +FingerprintException = fingerprinting_pywrap.FingerprintException + + +def write_fingerprint(export_dir): + """Write fingerprint protobuf, if requested. + + Writes a `tf.saved_model.experimental.Fingerprint` object to a + `fingerprint.pb` file in the `export_dir` using the `saved_model.pb` file + contained in `export_dir`. + + Args: + export_dir: The directory in which to write the fingerprint. + """ + if flags.config().saved_model_fingerprinting.value(): + fingerprint_path = file_io.join( + compat.as_str(export_dir), + compat.as_str(constants.FINGERPRINT_FILENAME)) + logging.info("Writing fingerprint to %s", fingerprint_path) + + try: + fingerprint_serialized = fingerprinting_pywrap.CreateFingerprintDef( + export_dir) + except FingerprintException as e: + raise ValueError(e) from None + file_io.atomic_write_string_to_file(fingerprint_path, + fingerprint_serialized) + + metrics.SetWriteFingerprint(fingerprint=fingerprint_serialized) + try: + metrics.SetWritePathAndSingleprint( + path=export_dir, + singleprint=singleprint_from_fingerprint_proto(export_dir)) + except metrics.MetricException: + logging.info("path_and_singleprint metric could not be set. " + "Model saving will continue.") + + +def singleprint_from_saved_model_proto(export_dir): + """Returns the singleprint of `saved_model.pb` in `export_dir`. + + Args: + export_dir: The directory that contains `saved_model.pb`. + + Returns: + A string containing the singleprint of `saved_model.pb` in `export_dir`. + + Raises: + ValueError: If a valid singleprint cannot be constructed from + `saved_model.pb`. + """ + try: + return fingerprinting_pywrap.SingleprintFromSM(export_dir) + except FingerprintException as e: + raise ValueError(e) from None + + +def singleprint_from_fingerprint_proto(export_dir): + """Returns the singleprint of `fingerprint.pb` in `export_dir`. + + Args: + export_dir: The directory that contains `fingerprint.pb`. + + Returns: + A string containing the singleprint of `fingerprint.pb` in `export_dir`. + + Raises: + ValueError: If a valid singleprint cannot be constructed from + `fingerprint.pb`. + """ + try: + return fingerprinting_pywrap.SingleprintFromFP(export_dir) + except FingerprintException as e: + raise ValueError(e) from None + + +def singleprint_from_saved_model(export_dir): + """Returns the singleprint of the SavedModel in `export_dir`. + + First tries to construct the singleprint from `fingerprint.pb`, then from + `saved_model.pb`. Attempts to write the `fingerprint.pb` if not found, but + doesn't return an error if it isn't writeable. + + Args: + export_dir: The directory that contains the SavedModel. + + Returns: + A string containing the singleprint of the SavedModel in `export_dir`. + + Raises: + ValueError: If a valid singleprint cannot be constructed from the + SavedModel. + """ + # try generating the singleprint from `fingerprint.pb` + try: + return singleprint_from_fingerprint_proto(export_dir) + except FingerprintException: + pass + + # try creating `fingerprint.pb`, then generating the singleprint + try: + write_fingerprint(export_dir) + return singleprint_from_fingerprint_proto(export_dir) + except FingerprintException: + pass + + # try generating the singleprint from `saved_model.pb` + try: + return singleprint_from_saved_model_proto(export_dir) + except FingerprintException as e: + raise ValueError(e) from None + + +def to_proto(fingerprint): + if not isinstance(fingerprint, fingerprinting.Fingerprint): + raise TypeError("Supplied value is not a Fingerprint.") + return fingerprint_pb2.FingerprintDef( + saved_model_checksum=fingerprint.saved_model_checksum, + graph_def_program_hash=fingerprint.graph_def_program_hash, + signature_def_hash=fingerprint.signature_def_hash, + saved_object_graph_hash=fingerprint.saved_object_graph_hash, + checkpoint_hash=fingerprint.checkpoint_hash) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_deserialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1c57a746e2409f6b1341a467a3ad1c50e979c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_deserialization.py @@ -0,0 +1,715 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tools for deserializing `Function`s.""" + +import collections +import pprint +import re + +from absl import logging + +from tensorflow.core.function import trace_type +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.core.protobuf import saved_object_graph_pb2 +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as function_lib +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.framework import func_graph as func_graph_lib +from tensorflow.python.framework import function_def_to_graph as function_def_lib +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import custom_gradient +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect + + +def _is_tensor(t): + return isinstance( + t, (tensor.Tensor, resource_variable_ops.BaseResourceVariable)) + + +# TODO(b/205016027): Update this to just use ConcreteFunction.__call__ with the +# structured signature. +def _call_concrete_function(function, inputs): + """Calls a restored Function with structured inputs. + + This differs from `function.__call__` in that inputs and outputs are + structured and that it casts inputs to tensors if needed. + + Note: this does not checks that non-tensor inputs match. That should be + done before via `_concrete_function_callable_with`. + + Args: + function: ConcreteFunction to call. + inputs: Structured inputs compatible with + `function.graph.structured_input_signature`. + + Returns: + The structured function output. + """ + expected_structure = function.graph.structured_input_signature + flatten_inputs = nest.flatten_up_to( + expected_structure, inputs, expand_composites=True) + flatten_expected = nest.flatten(expected_structure, expand_composites=True) + tensor_inputs = [] + for arg, expected in zip(flatten_inputs, flatten_expected): + if isinstance(expected, tensor.TensorSpec): + tensor_inputs.append( + ops.convert_to_tensor(arg, dtype_hint=expected.dtype)) + elif isinstance(expected, resource_variable_ops.VariableSpec): + tensor_inputs.append(arg.handle) + result = function._call_flat(tensor_inputs, function.captured_inputs) # pylint: disable=protected-access + if isinstance(result, ops.Operation): + return None + return result + + +def _try_convert_to_tensor_spec(arg, dtype_hint): + """Returns None or TensorSpec obtained if `arg` is converted to tensor.""" + try: + # Note: try conversion in a FuncGraph to avoid polluting current context. + with func_graph_lib.FuncGraph(name="guess_conversion").as_default(): + result = ops.convert_to_tensor(arg, dtype_hint=dtype_hint) + return tensor.TensorSpec(shape=result.shape, dtype=result.dtype) + except (TypeError, ValueError): + return None + + +def _concrete_function_callable_with(function, inputs, allow_conversion): + """Returns whether concrete `function` can be called with `inputs`.""" + expected_structure = function.graph.structured_input_signature + try: + flatten_inputs = nest.flatten_up_to(expected_structure, inputs) + except (TypeError, ValueError): + return False + + for arg, expected in zip(flatten_inputs, nest.flatten(expected_structure)): + if isinstance(expected, tensor.TensorSpec): + if allow_conversion: + arg = _try_convert_to_tensor_spec(arg, dtype_hint=expected.dtype) + if not _is_tensor(arg) and not isinstance(arg, tensor.TensorSpec): + return False + if arg.dtype != expected.dtype: + return False + if not expected.shape.is_compatible_with(arg.shape): + return False + elif isinstance(expected, type_spec.TypeSpec): + if not expected.is_compatible_with(arg): + return False + elif _is_tensor(arg): + if id(arg) != id(expected): + return False + else: + if arg != expected: + return False + return True + + +def _deserialize_function_spec_as_nonmethod(function_spec_proto): + """Deserialize a FunctionSpec object from its proto representation.""" + typeless_fullargspec = nested_structure_coder.decode_proto( + function_spec_proto.fullargspec) + + # Convert a method function into a non method. + if function_spec_proto.is_method or ( + typeless_fullargspec.args and typeless_fullargspec.args[0] == "self" + ): + if not typeless_fullargspec.args: + raise NotImplementedError( + "Cannot deserialize a method function without a named " + "'self' argument.") + args = typeless_fullargspec.args[1:] + else: + args = typeless_fullargspec.args + + fullargspec = tf_inspect.FullArgSpec( + args=args, + varargs=typeless_fullargspec.varargs, + varkw=typeless_fullargspec.varkw, + defaults=typeless_fullargspec.defaults, + kwonlyargs=typeless_fullargspec.kwonlyargs, + kwonlydefaults=typeless_fullargspec.kwonlydefaults, + annotations=typeless_fullargspec.annotations) + input_signature = nested_structure_coder.decode_proto( + function_spec_proto.input_signature) + + # See `tf.function` and the JitCompile proto for details. + jit_compile = { + saved_object_graph_pb2.FunctionSpec.JitCompile.DEFAULT: None, + saved_object_graph_pb2.FunctionSpec.JitCompile.ON: True, + saved_object_graph_pb2.FunctionSpec.JitCompile.OFF: False, + }.get(function_spec_proto.jit_compile) + + return function_type_utils.FunctionSpec.from_fullargspec_and_signature( + fullargspec=fullargspec, + input_signature=input_signature, + jit_compile=jit_compile) + + +# TODO(b/203440205): Set FunctionType with ConcreteFunction constructor. +def set_preinitialized_function_spec(concrete_fn, spec): + """Set the FunctionType of the ConcreteFunction using FunctionSpec.""" + if spec is None: + concrete_fn._function_type = None # pylint: disable=protected-access + return + + unconstrained_type = function_type_lib.FunctionType( + [ + function_type_lib.Parameter(p.name, p.kind, p.optional, None) + for p in spec.function_type.parameters.values() + ] + ) + arg_specs, kwarg_specs = concrete_fn.structured_input_signature + + input_function_type, _ = function_type_lib.canonicalize_to_monomorphic( + arg_specs, + { + function_type_lib.sanitize_arg_name(k): v + for k, v in kwarg_specs.items() + }, + spec.default_values, + {}, + unconstrained_type, + ) + + output_type = trace_type.from_value(concrete_fn.graph.structured_outputs) + # Captures are restored later so we will update it then. + function_type = function_type_lib.FunctionType( + input_function_type.parameters.values(), + return_annotation=output_type, + ) + concrete_fn._function_type = function_type # pylint: disable=protected-access + + +# TODO(b/205016761): The fact that we can't derive ConcreteFunction calling +# conventions from the serialized input spec right now is unfortunate. Merging +# these would be good, maybe by adding TensorSpec names to cache keys so renamed +# keyword arguments would yield different ConcreteFunctions. +def setup_bare_concrete_function(saved_bare_concrete_function, + concrete_functions): + """Makes a restored bare concrete function callable.""" + concrete_function = concrete_functions[ + saved_bare_concrete_function.concrete_function_name] + # pylint: disable=protected-access + concrete_function._arg_keywords = ( + saved_bare_concrete_function.argument_keywords) + concrete_function._num_positional_args = ( + saved_bare_concrete_function.allowed_positional_arguments) + if saved_bare_concrete_function.HasField("function_spec"): + function_spec = _deserialize_function_spec_as_nonmethod( + saved_bare_concrete_function.function_spec) + set_preinitialized_function_spec(concrete_function, function_spec) + # pylint: enable=protected-access + concrete_function.add_to_graph() + return concrete_function + + +class RestoredFunction(def_function.Function): + """Wrapper class for a function that has been restored from saved state. + + See `def_function.Function`. + """ + + def __init__(self, python_function, name, function_spec, concrete_functions): + # TODO(b/205016819): We may enable autograph once exceptions are supported. + super(RestoredFunction, self).__init__( + python_function, + name, + autograph=False, + jit_compile=function_spec.jit_compile) + self.concrete_functions = concrete_functions + self._function_type = function_spec.function_type + self._default_values = function_spec.default_values + + # Prevent RestoredFunction from spamming users with frequent tracing + # warnings. + self._omit_frequent_tracing_warning = True + + @property + def _run_functions_eagerly(self): + # We do not have access to the original python function, and thus, we + # cannot meaningfully do anything but call our concrete function graphs + # under the hood. + # + # Attempting to call our bespoke python function (i.e. + # `restored_function_body`) will work so long as the user passes in all + # required and optional arguments. If an optional argument is missing, + # however, the call will break. For this reason, we instead skip the + # eager call path altogether if a user has enabled eager function execution + # via `tf.config.run_functions_eagerly`. + return False + + def _list_all_concrete_functions(self): + return self.concrete_functions + + def _list_all_concrete_functions_for_serialization(self): + return self.concrete_functions + + +def recreate_function(saved_function, concrete_functions): + """Creates a `Function` from a `SavedFunction`. + + Args: + saved_function: `SavedFunction` proto. + concrete_functions: map from function name to `ConcreteFunction`. As a side + effect of this function, the `FunctionSpec` from `saved_function` is added + to each `ConcreteFunction` in this map. + + Returns: + A `Function`. + """ + # TODO(b/205017389): Construct a `Function` with the cache populated + # instead of creating a new `Function` backed by a Python layer to + # glue things together. Current approach is nesting functions deeper for each + # serialization cycle. + + # Note: handling method functions is tricky since make_decorator does not + # allows control of "ismethod". Additionally since restored functions do + # not behave as methods i.e. they always use the same captured tensors + # independent of the object they are bound to, there is little value on + # propagating that correctly. + # + # Ideally this conversion should happen at serialization time. But since + # there are SavedModels which have "ismethod" populated and have an extra + # argument that they expect to be ignored, we do it at deserialization. + function_spec = _deserialize_function_spec_as_nonmethod( + saved_function.function_spec) + + def restored_function_body(*args, **kwargs): + """Calls a restored function or raises an error if no matching function.""" + if not saved_function.concrete_functions: + raise ValueError("Found zero restored functions for caller function.") + # This is the format of function.graph.structured_input_signature. At this + # point, the args and kwargs have already been canonicalized. + inputs = (args, kwargs) + + # First try to find a concrete function that can be called without input + # conversions. This allows one to pick a more specific trace in case there + # was also a more expensive one that supported tensors. + for allow_conversion in [False, True]: + for function_name in saved_function.concrete_functions: + function = concrete_functions[function_name] + if any([inp is None for inp in function.captured_inputs]): + raise ValueError("Looks like you are trying to run a loaded " + "non-Keras model that was trained using " + "tf.distribute.experimental.ParameterServerStrategy " + "with variable partitioning, which is not currently " + "supported. Try using Keras to define your model " + "if possible.") + if _concrete_function_callable_with(function, inputs, allow_conversion): + return _call_concrete_function(function, inputs) + + signature_descriptions = [] + + def _pretty_format_positional(positional): + return "Positional arguments ({} total):\n * {}".format( + len(positional), + "\n * ".join(pprint.pformat(a) for a in positional)) + + for index, function_name in enumerate(saved_function.concrete_functions): + concrete_function = concrete_functions[function_name] + positional, keyword = concrete_function.structured_input_signature + signature_descriptions.append( + "Option {}:\n {}\n Keyword arguments: {}".format( + index + 1, _pretty_format_positional(positional), keyword)) + raise ValueError( + "Could not find matching concrete function to call loaded from the " + f"SavedModel. Got:\n {_pretty_format_positional(args)}\n Keyword " + f"arguments: {kwargs}\n\n Expected these arguments to match one of the " + f"following {len(saved_function.concrete_functions)} option(s):\n\n" + f"{(chr(10)+chr(10)).join(signature_descriptions)}") + + concrete_function_objects = [] + for concrete_function_name in saved_function.concrete_functions: + concrete_function_objects.append(concrete_functions[concrete_function_name]) + + for cf in concrete_function_objects: + set_preinitialized_function_spec(cf, function_spec) + + restored_function = RestoredFunction(restored_function_body, + restored_function_body.__name__, + function_spec, concrete_function_objects) + + return tf_decorator.make_decorator( + restored_function_body, + restored_function, + decorator_argspec=function_spec.fullargspec) + + +def load_function_def_library(library, + saved_object_graph=None, + load_shared_name_suffix=None, + wrapper_function=None): + """Load a set of functions as concrete functions without captured inputs. + + Functions names are manipulated during load such that they do not overlap + with previously created ones. + + Gradients are re-registered under new names. Ops that reference the gradients + are updated to reflect the new registered names. + + Args: + library: FunctionDefLibrary proto message. + saved_object_graph: SavedObjectGraph proto message. If not passed in, + concrete function structured signatures and outputs will not be set. + load_shared_name_suffix: If specified, used to uniquify shared names. + Otherwise, a unique name is generated. + wrapper_function: An object that will be wrapped on newly created functions. + + Returns: + Map of original function names in the library to instances of + `ConcreteFunction` without captured inputs. + + Raises: + ValueError: if functions dependencies have a cycle. + """ + library_function_names = set(fdef.signature.name for fdef in library.function) + functions = {} + renamed_functions = {} + + # Our graph building code currently requires functions to be registered with + # some tf.Graph in order to import functions using the + # op-name-is-function-name calling convention. To avoid leaking memory into + # the global default graph when executing eagerly, we create a temporary + # Graph. + # + # TODO(b/205023033): Make this Graph creation unnecessary when executing + # eagerly by fixing function_def_to_graph_def. + if ops.executing_eagerly_outside_functions(): + graph = ops.Graph() + else: + graph = ops.get_default_graph() + + if load_shared_name_suffix is None: + load_shared_name_suffix = "_load_{}".format(ops.uid()) + + # Custom gradient functions must be re-registered under new UIDs. + library_gradient_names = {} # Maps old op type to old function name + new_gradient_op_types = {} # Maps old gradient op type to new op type. + gradients_to_register = {} # Maps old function name to new op type + for gdef in library.registered_gradients: + if gdef.registered_op_type: + new_op_type = custom_gradient.generate_name() + old_op_type = compat.as_bytes(gdef.registered_op_type) + + library_gradient_names[old_op_type] = gdef.gradient_func + new_gradient_op_types[old_op_type] = new_op_type + gradients_to_register[gdef.gradient_func] = new_op_type + + function_deps = {} + for fdef in library.function: + function_deps[fdef.signature.name] = _list_function_deps( + fdef, library_function_names, library_gradient_names) + + loaded_gradients = {} + for fdef in _sort_function_defs(library, function_deps): + orig_name = _fix_fdef_in_place(fdef, functions, load_shared_name_suffix, + new_gradient_op_types) + + # Setup function signatures and outputs + # + # When concrete functions are created normally (i.e. when they're originally + # created and not loaded via saved model), the inputs and outputs are + # calculated based on the values passed in by the user and returned from the + # original function, respectively. We don't have access to those anymore at + # restore time, so we must instead pass them to the FuncGraph explicitly. + structured_input_signature = None + structured_outputs = None + if (saved_object_graph is not None and + orig_name in saved_object_graph.concrete_functions): + # TODO(b/204324043): Offload the deserialization of the protos to the + # first class objects by passing the actual protos. This is blocked on + # importing `nested_structure_coder` in function.py causing a circular + # dependency. + proto = saved_object_graph.concrete_functions[orig_name] + structured_input_signature = nested_structure_coder.decode_proto( + proto.canonicalized_input_signature) + structured_outputs = nested_structure_coder.decode_proto( + proto.output_signature) + + # There is no need to copy all functions into the function def graph. It + # leads to a O(n^2) increase of memory when importing functions and the + # extra function definitions are a no-op since they already imported as a + # function before and passed in explicitly (due to the topologic sort + # import). + with graph.as_default(): + func_graph = function_def_lib.function_def_to_graph( + fdef, + structured_input_signature=structured_input_signature, + structured_outputs=structured_outputs) + # Restores gradients for function-call ops (not the same as ops that use + # custom gradients) + _restore_gradient_functions(func_graph, renamed_functions, loaded_gradients) + + for dep in function_deps[orig_name]: + functions[dep].add_to_graph(func_graph) + + # We do not initialize the new ConcreteFunction's function_spec and/or + # arg_keywords here (which are used to parse the structured and flat + # signatures, respectively). ConcreteFunction that are part of a saved + # function is set up later by recreate_function(); and bare ConcreteFunction + # is set up by by setup_bare_concrete_function(). + # However, we copy the FunctionDef attributes to the new ConcreteFunction, + # excluding the "_input_shapes", which may cause an error during input shape + # initialization at a later stage. + if "_input_shapes" in fdef.attr: + del fdef.attr["_input_shapes"] + function_type = function_type_lib.from_structured_signature( + func_graph.structured_input_signature, + func_graph.structured_outputs, + func_graph.function_captures.capture_types, + ) + func = function_lib.ConcreteFunction.from_func_graph( + func_graph, function_type, attrs=fdef.attr) + if wrapper_function: + func = wrapper_function(func) + func.add_to_graph(graph) + + functions[orig_name] = func + renamed_functions[func.name] = func + if any(op.type == "TRTEngineOp" for op in func_graph.get_operations()): + # TODO(b/150708051): Remove this hack once TensorRT SavedModel integration + # is fixed. Currently it's leaking memory to maintain bug compatibility + # with previous behavior. + func.add_to_graph(ops.get_default_graph()) + + if orig_name in gradients_to_register: + gradient_op_type = gradients_to_register[orig_name] + loaded_gradients[compat.as_bytes(gradient_op_type)] = func + ops.RegisterGradient(gradient_op_type)(_gen_gradient_func(func)) + + return functions + + +def _gen_gradient_func(func): + """Wraps a deserialized function.""" + + def gradient_func(unused_op, *result_grads): + # Replace all `None` arguments, because the traced custom gradient function + # expects tensors. Replacing with zeros is correct since the `None` values + # occur when the gradient is unconnected, and thus the gradient is + # "statically proven to be zero." See `tf.UnconnectedGradients` for details. + + def none_to_zero(x, t): + if x is not None: + return x + + shape, dtype = default_gradient.shape_and_dtype(t) + + if shape.is_fully_defined(): + return default_gradient.zeros_like(t) + + dims = [] + if shape.rank is not None: + dims = [1 if d is None else d for d in shape.as_list()] + + return array_ops.zeros(dims, dtype) + + result_grads = [ + none_to_zero(x, t) for (x, t) in zip(result_grads, func.graph.inputs) + ] + + return func(*result_grads) + + return gradient_func + + +def _restore_gradient_functions(func_graph, renamed_functions, + loaded_gradients): + """Populate function op's _gradient_function with default gradient.""" + for op in func_graph.get_operations(): + # TODO(b/205024208): This code assumes that the gradient registered for this + # function call is the default gradient for the function and not a custom + # one. + if op.type in ["StatefulPartitionedCall", "PartitionedCall"]: + function = renamed_functions[compat.as_bytes( + op.node_def.attr["f"].func.name)] + op._gradient_function = function._get_gradient_function() # pylint: disable=protected-access + try: + gradient_op_type = op.get_attr("_gradient_op_type") + except ValueError: + pass + else: + if gradient_op_type in loaded_gradients: + grad_fn = loaded_gradients[gradient_op_type] + grad_fn._num_positional_args = len(op.inputs) # pylint: disable=protected-access + grad_fn._arg_keywords = [inp.name for inp in op.inputs] # pylint: disable=protected-access + + +def _sort_function_defs(library, function_deps): + """Return a topologic sort of FunctionDefs in a library.""" + edges = collections.defaultdict(list) + in_count = collections.defaultdict(lambda: 0) + + for fname, deps in function_deps.items(): + for dep in deps: + edges[dep].append(fname) + in_count[fname] += 1 + ready = [ + fdef.signature.name + for fdef in library.function + if in_count[fdef.signature.name] == 0 + ] + output = [] + while ready: + node = ready.pop() + output.append(node) + for dest in edges[node]: + in_count[dest] -= 1 + if not in_count[dest]: + ready.append(dest) + + if len(output) != len(library.function): + failed_to_resolve = sorted(set(in_count.keys()) - set(output)) + raise ValueError("There is a cyclic dependency between functions. ", + f"Could not resolve {failed_to_resolve}.") + + reverse = {fdef.signature.name: fdef for fdef in library.function} + return [reverse[x] for x in output] + + +def _get_gradient_op_type(node_def): + """Returns the custom gradient op type.""" + if ("_gradient_op_type" in node_def.attr and + node_def.op not in ["StatefulPartitionedCall", "PartitionedCall"]): + return node_def.attr["_gradient_op_type"].s + return None + + +def fix_node_def(node_def, functions, shared_name_suffix): + """Replace functions calls and shared names in `node_def`.""" + if node_def.op in functions: + node_def.op = functions[node_def.op].name + for _, attr_value in node_def.attr.items(): + if attr_value.WhichOneof("value") == "func": + attr_value.func.name = functions[attr_value.func.name].name + elif attr_value.WhichOneof("value") == "list": + for fn in attr_value.list.func: + fn.name = functions[fn.name].name + + # Fix old table creation bug. + if node_def.op == "HashTableV2": + if ("use_node_name_sharing" not in node_def.attr or + not node_def.attr["use_node_name_sharing"].b): + node_def.attr["use_node_name_sharing"].b = True + # We are turning on node mame sharing, so have to make sure we don't + # accidentally share a table resource. + shared_name_suffix += "_{}".format(ops.uid()) + + # TODO(b/124205571): Avoid accidental sharing and destruction of restored + # resources. For now uniquify "shared_name" when loading functions to avoid + # sharing. + # TODO: Add regression test for b/150826922. + op_def = op_def_registry.get(node_def.op) + if op_def: + attr = next((a for a in op_def.attr if a.name == "shared_name"), None) + if attr: + shared_name = None + if "shared_name" in node_def.attr and node_def.attr["shared_name"].s: + shared_name = node_def.attr["shared_name"].s + elif attr.default_value.s: + shared_name = compat.as_bytes(attr.default_value.s) + if not shared_name: + shared_name = compat.as_bytes(node_def.name) + + node_def.attr["shared_name"].s = ( + shared_name + compat.as_bytes(shared_name_suffix)) + + +def _fix_fdef_in_place(fdef, functions, shared_name_suffix, + new_gradient_op_types): + """Fixes a FunctionDef proto to be loaded in current context. + + In particular, when loading a function library into an eager context, one + must rename the functions to avoid conflicts with existent functions. + + Args: + fdef: FunctionDef proto to fix. It is mutated in-place. + functions: map from function name to a ConcreteFunction instance. + shared_name_suffix: A unique string for this load which helps to avoid + `shared_name` collisions across loads. Two functions from the same load + using the same `shared_name` still need to share, but functions from + different loads with the same `shared_name` should not. + new_gradient_op_types: map from old gradient op type to newly generated op + type. + + Returns: + orig_name: original value of fdef.signature.name + """ + orig_name = fdef.signature.name + contains_unsaved_custom_gradients = False + + for node_def in fdef.node_def: + fix_node_def(node_def, functions, shared_name_suffix) + op_type = _get_gradient_op_type(node_def) + if op_type is not None: + if op_type in new_gradient_op_types: + node_def.attr["_gradient_op_type"].s = compat.as_bytes( + new_gradient_op_types[op_type]) + else: + contains_unsaved_custom_gradients = True + if contains_unsaved_custom_gradients: + logging.warning( + "Importing a function (%s) with ops with unsaved custom gradients. Will" + " likely fail if a gradient is requested.", fdef.signature.name) + + fdef.signature.name = _clean_function_name(fdef.signature.name) + return orig_name + + +def _list_function_deps(fdef, library_function_names, library_gradient_names): + """Find functions referenced in `fdef`.""" + # TODO(b/205023953): Recurse into list attributes and into NameAttrList attrs + # both when listing deps and when fixing them. `function_def_to_graph` also + # requires fixes. + deps = set() + for node_def in fdef.node_def: + grad_op_type = _get_gradient_op_type(node_def) + if node_def.op in library_function_names: + deps.add(node_def.op) + elif grad_op_type and grad_op_type in library_gradient_names: + deps.add(library_gradient_names[grad_op_type]) + else: + for _, attr_value in node_def.attr.items(): + if attr_value.WhichOneof("value") == "func": + deps.add(attr_value.func.name) + elif attr_value.WhichOneof("value") == "list": + for fn in attr_value.list.func: + deps.add(fn.name) + + return deps + + +_FUNCTION_WRAPPER_NAME_REGEX = r"^%s(.*)_\d+$" % (function_lib._INFERENCE_PREFIX + ) # pylint:disable=protected-access + + +def _clean_function_name(name): + """Vanity function to keep the function names comprehensible.""" + # Note: each time a function is wrapped into `function_lib.ConcreteFunction` + # its name becomes "__inference__xyz". + match = re.search(_FUNCTION_WRAPPER_NAME_REGEX, name) + if match: + return match.group(1) + else: + return name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..88ee7a4dd128c2abdf60795be0d6dfecd9153ab0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/function_serialization.py @@ -0,0 +1,220 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tools for serializing `Function`s.""" + +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.core.protobuf import saved_object_graph_pb2 +from tensorflow.python.eager import function as defun +from tensorflow.python.eager import wrap_function as wrap_function_lib +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import nest + + +def _serialize_function_spec(function_spec): + """Serialize a FunctionSpec object into its proto representation.""" + if ( + function_spec.fullargspec.args + and function_spec.fullargspec.args[0] == "self" + ): + raise TypeError( + "Can not serialize tf.function with unbound 'self' parameter." + ) + + proto = saved_object_graph_pb2.FunctionSpec() + + # Intentionally skip encoding annotations of a function because function + # annotations are mainly for optional type checking during development + # and does not affect runtime behavior. + # https://www.python.org/dev/peps/pep-3107/ + # https://docs.python.org/3/library/inspect.html#inspect.getfullargspec + proto.fullargspec.CopyFrom( + nested_structure_coder.encode_structure( + function_spec.fullargspec._replace(annotations={}))) + + proto.is_method = False + proto.input_signature.CopyFrom( + nested_structure_coder.encode_structure(function_spec.input_signature)) + + # See `tf.function` and the JitCompile proto for details. + proto.jit_compile = { + None: saved_object_graph_pb2.FunctionSpec.JitCompile.DEFAULT, + True: saved_object_graph_pb2.FunctionSpec.JitCompile.ON, + False: saved_object_graph_pb2.FunctionSpec.JitCompile.OFF, + }.get(function_spec.jit_compile) + + return proto + + +def serialize_concrete_function(concrete_function, node_ids): + """Build a SavedConcreteFunction.""" + bound_inputs = [] + try: + for capture in concrete_function.captured_inputs: + bound_inputs.append(node_ids[capture]) + except KeyError: + raise KeyError( + f"Failed to add concrete function '{concrete_function.name}' to object-" + f"based SavedModel as it captures tensor {capture!r} which is unsupported" + " or not reachable from root. " + "One reason could be that a stateful object or a variable that the " + "function depends on is not assigned to an attribute of the serialized " + "trackable object (see SaveTest.test_captures_unreachable_variable).") + concrete_function_proto = saved_object_graph_pb2.SavedConcreteFunction() + structured_outputs = func_graph_module.convert_structure_to_signature( + concrete_function.structured_outputs) + concrete_function_proto.canonicalized_input_signature.CopyFrom( + nested_structure_coder.encode_structure( + concrete_function.structured_input_signature)) + concrete_function_proto.output_signature.CopyFrom( + nested_structure_coder.encode_structure(structured_outputs)) + concrete_function_proto.bound_inputs.extend(bound_inputs) + return concrete_function_proto + + +# TODO(b/203440205): Support FunctionType directly. +def get_preinitialized_function_spec(concrete_function): + """Generates an unconstrained FunctionSpec from FunctionType.""" + # TODO(b/203440205): SavedModel does not support FunctionType on its own + # without a FuncGraph signature. + # WrappedFunctions are not supposed to have FunctionSpecs. + if concrete_function.structured_input_signature is None or isinstance( + concrete_function, wrap_function_lib.WrappedFunction + ): + return None + + function_type = concrete_function.function_type + if function_type is None: + return None + + unconstrained_type = function_type_lib.FunctionType( + [ + function_type_lib.Parameter(p.name, p.kind, p.optional, None) + for p in function_type.parameters.values() + ] + ) + default_values = { + p.default for p in function_type.parameters.values() if p.optional + } + return function_type_utils.FunctionSpec( + unconstrained_type, + default_values, + False, + name=concrete_function.name, + ) + + +def serialize_bare_concrete_function(concrete_function): + """Build a SavedBareConcreteFunction.""" + # pylint: disable=protected-access + proto = saved_object_graph_pb2.SavedBareConcreteFunction( + concrete_function_name=concrete_function.name, + allowed_positional_arguments=concrete_function._num_positional_args, + argument_keywords=concrete_function._arg_keywords) + function_spec = get_preinitialized_function_spec(concrete_function) + if function_spec is not None: + proto.function_spec.CopyFrom(_serialize_function_spec(function_spec)) + return proto + # pylint: enable=protected-access + + +def serialize_function(function, concrete_functions): + """Build a SavedFunction proto.""" + proto = saved_object_graph_pb2.SavedFunction() + + function_spec_proto = _serialize_function_spec(function.function_spec) + proto.function_spec.CopyFrom(function_spec_proto) + for concrete_function in concrete_functions: + proto.concrete_functions.append(concrete_function.name) + return proto + + +def wrap_cached_variables(concrete_function): + """Wraps the concrete function if it uses cached read tensors. + + This function creates a new concrete function that captures variables + instead of the cached read tensors. + + Args: + concrete_function: A Concrete function that maybe captures cached read + tensors. + + Returns: + A concrete function that wraps the original concrete function, which + captures variables instead. If the original function did not capture any + cached values, then the function is not wrapped and the original object is + returned. + """ + outer_graph = func_graph_module.FuncGraph( + "{}_no_cache".format(concrete_function.graph.name)) + mapped_captures = None + remapped_captures = {} + + # Update the external captures to use read tensors generated in the outer + # graph. + with outer_graph.as_default(): + for capture, placeholder in concrete_function.graph.captures: + cached_variable = getattr(capture, "_cached_variable", None) + if cached_variable is None: + continue + cached_variable = cached_variable() + new_cached_value = cached_variable.read_value() + key = id(capture) + external = concrete_function.graph.function_captures.by_val_external[key] + internal = concrete_function.graph.function_captures.by_val_internal[key] + remapped_captures[key] = [external, internal] + concrete_function.graph.function_captures.add_or_replace( + key=key, + external=new_cached_value, + internal=placeholder, + is_by_ref=False) + mapped_captures = True + + if not mapped_captures: + return concrete_function + + inner_concrete = defun.ConcreteFunction.from_func_graph( + concrete_function.graph, concrete_function.function_type, {} + ) + + def wrap_function(*args): + return inner_concrete._call_flat(list(args), inner_concrete.captured_inputs) # pylint:disable=protected-access + + args = nest.flatten(concrete_function.structured_input_signature, + expand_composites=True) + func_graph_module.func_graph_from_py_func( + None, wrap_function, args=tuple(args), kwargs={}, + func_graph=outer_graph) + + # Create concrete function, and copy the attributes necessary to serialize + # the function. + # pylint: disable=protected-access + fn = defun.ConcreteFunction.from_func_graph( + outer_graph, concrete_function.function_type, {} + ) + fn._arg_keywords = concrete_function._arg_keywords + fn._num_positional_args = concrete_function._num_positional_args + # pylint: enable=protected-access + + # Return the captures to their original values + for key, capture in remapped_captures.items(): + external, internal = capture + concrete_function.graph._function_captures.add_or_replace( # pylint: disable=protected-access + key=key, + external=external, + internal=internal, + is_by_ref=False) + return fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load.py new file mode 100644 index 0000000000000000000000000000000000000000..2be4ee77db7e6283be29e7b4c1a5ddab9529f360 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load.py @@ -0,0 +1,1146 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Import a trackable object from a SavedModel.""" + +import collections +import functools +import os +import sys + +from absl import logging + +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.core.function.capture import restore_captures +from tensorflow.python.checkpoint import checkpoint +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.checkpoint import graph_view +from tensorflow.python.checkpoint import restore +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.eager import function +from tensorflow.python.eager.polymorphic_function import saved_model_utils as function_saved_model_utils +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.saved_model import fingerprinting +from tensorflow.python.saved_model import fingerprinting_utils +from tensorflow.python.saved_model import function_deserialization +from tensorflow.python.saved_model import load_options +from tensorflow.python.saved_model import load_v1_in_v2 +from tensorflow.python.saved_model import loader_impl +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model import registration +from tensorflow.python.saved_model import revived_types +from tensorflow.python.saved_model import utils_impl as saved_model_utils +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import asset +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base +from tensorflow.python.trackable import data_structures +from tensorflow.python.trackable import resource +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# API label for SavedModel metrics. +_LOAD_V2_LABEL = "load_v2" +# Built-in registrations use the "oneof kind" field in the SavedObject proto, +# instead of "registered_name" field. The "kind" field has almost the same +# functionality as the registered_name, but only contains built-in TensorFlow +# types (like variable, functions, assets). +_BUILT_IN_REGISTRATIONS = { + "asset": asset.Asset, + "resource": resource.RestoredResource, + "constant": function_saved_model_utils.TrackableConstant} + + +def _unused_handle(): + """Returns a placeholder as a handle that is not supposed to be accessed.""" + error_message = ("Trying to access a placeholder that is not supposed to be " + "executed. This means you are executing a graph generated " + "from the cross-replica context in an in-replica context.") + save_error_message = ( + "It seems that you are trying to save a " + "tf.types.experimental.ConcreteFunction that involves a distributed " + "model, and the model contains parts that are loaded form a SavedModel. " + "It's not supported to save such tf.types.experimental.ConcreteFunction. " + "Try saving a tf.function with input_signature instead, and file a bug if" + " there are still issues.") + + assert_op = control_flow_assert.Assert( + array_ops.placeholder_with_default(False, shape=()), [error_message]) + if (not context.executing_eagerly() + ) and ops.get_default_graph().building_function: + ops.get_default_graph().mark_as_unsaveable(save_error_message) + + with ops.control_dependencies([assert_op]): + return array_ops.placeholder(dtype=dtypes.resource) + + +class _WrapperFunction(function.ConcreteFunction): + """A class wraps a concrete function to handle different distributed contexts. + + The reason for wrapping a concrete function is because the _captured_inputs + fields used for in-replica context and cross-replica context are different. + When `load()` is called from within a tf.distribute.strategy scope, the + captured inputs are distributed variables. When using these distributed + variables during calling the function, we need different approaches when it is + in-replica and when it is not in-replica. When it is in replica, naturally we + should use the corresponding component of the distributed variable; when it is + not in-replica, calling the function should mean that it is constructing a + graph that is not actually going to be used. A typical use case is when + constructing a functional model. In this case, return a placeholder with a + control dependency to ensure that is never accessed. + """ + + def __init__(self, concrete_function): + # Shallow copy the concrete_function + self.__dict__.update(vars(concrete_function)) + + def _call_flat(self, args, captured_inputs): + + def get_handle(x): + return x.handle if distribute_utils.is_distributed_variable(x) else x + + def get_unused_handle(x): + return _unused_handle() if distribute_utils.is_distributed_variable(x) \ + else x + + if (distribute_lib.get_replica_context() is not None or + values_util.is_saving_non_distributed()): + # If we're in the replica context or are saving a non-distributed version + # of the model, we resolve the captured variables to the corresponding + # resource handle. In both situation we call var.handle, but it has + # different behavior. In the replica context, var.handle resolves the + # replica local variable handle if the variable is replicated. When saving + # a non-distributed version of the model, var.handle resolves to the + # primary variable handle, since we only save one copy of a replicated + # variable. + captured_inputs = list(map(get_handle, captured_inputs)) + else: # cross-replica context + captured_inputs = list(map(get_unused_handle, captured_inputs)) + return super()._call_flat(args, captured_inputs) + + +class Loader(object): + """Helper class to load an object-based SavedModel.""" + + def __init__(self, object_graph_proto, saved_model_proto, export_dir, + ckpt_options, save_options, filters): + meta_graph = saved_model_proto.meta_graphs[0] + self._asset_file_def = meta_graph.asset_file_def + self._operation_attributes = { + node.name: node.attr for node in meta_graph.graph_def.node} + self._proto = object_graph_proto + self._export_dir = export_dir + self._concrete_functions = ( + function_deserialization.load_function_def_library( + library=meta_graph.graph_def.library, + saved_object_graph=self._proto, + wrapper_function=_WrapperFunction)) + # Store a set of all concrete functions that have been set up with + # captures. + self._restored_concrete_functions = set() + self._checkpoint_options = ckpt_options + self._save_options = save_options + + # Metagraph has a mapping from FunctionDef name to aliases + self._concrete_function_aliases = meta_graph.meta_info_def.function_aliases + self.function_aliases = {} + if self._save_options.experimental_load_function_aliases: + # Create a mapping from aliases to polymorphic restored functions or lists + # of concrete functions. This mapping can later be used with SaveOptions + # when re-saving the loaded object to a SavedModel. We start with a + # mapping from aliases to lists of concrete functions. Later in + # _recreate_function, on a entry by entry basis, we replace lists with + # polymorphic restored functions if the concrete function associated with + # a restored function is identical to a list of concrete functions in an + # entry. + concrete_func_list_by_alias = collections.defaultdict(list) + for concrete_func_name, alias in self._concrete_function_aliases.items(): + if concrete_func_name not in self._concrete_functions: + logging.warn( + ( + "ConcreteFunction `%s` is listed in function alias but it" + " is not found." + ), + concrete_func_name, + ) + continue + concrete_function = self._concrete_functions[concrete_func_name] + concrete_func_list_by_alias[alias].append(concrete_function) + self.function_aliases = dict(concrete_func_list_by_alias) + + self._pretty_printer = checkpoint.ObjectGraphProtoPrettyPrinter(self._proto) + + # Stores user-defined node_filters argument. + self._node_filters = filters + # Stores map of string paths to integers. + self._node_path_to_id = self._convert_node_paths_to_ints() + self._loaded_nodes = {} + if isinstance(filters, dict): + # If node_filters is a dict, then the values may contain already created + # trackable objects. In this case, create a dictionary mapping node IDs to + # the already created nodes. This dict will be updated in + # `_retrieve_all_filtered_nodes` with tracked children. + for node_path, node in filters.items(): + if isinstance(node, tuple): + self._loaded_nodes[self._node_path_to_id[node_path]] = node + else: + self._loaded_nodes[self._node_path_to_id[node_path]] = (node, setattr) + + # Get a list of all integer node ids to load, or None if all nodes should be + # loaded. This list includes ids of child nodes. + self._filtered_nodes = self._retrieve_all_filtered_nodes() + + # Order all nodes or filtered nodes using the dependencies. + self._ordered_node_ids = self._generate_ordered_node_ids() + + self._load_all() + + if not save_options.experimental_skip_checkpoint: + self._restore_checkpoint() + for node in self._nodes: + if isinstance(node, resource.CapturableResource): + init_op = node._initialize() # pylint: disable=protected-access + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op) + + def _convert_node_paths_to_ints(self): + """Maps all string node paths in node_filters to the int node ids.""" + if self._node_filters is None: + return None + path_to_int = {} + for node_id in self._node_filters: + int_node_id = None + if isinstance(node_id, str): + node_path = node_id.split(".") + if node_path[0] != "root": + raise ValueError( + "When passing string identifiers to node_filters, the first name" + f" must be root. Received {node_path[0]}.") + int_node_id = 0 + for n, name in enumerate(node_path[1:]): + int_node_id = self._find_node_child( + int_node_id, name, ".".join(node_path[:n+2])) + path_to_int[node_id] = int_node_id + else: + raise TypeError("Elements in node_filters must be strings.") + return path_to_int + + def _retrieve_all_filtered_nodes(self): + """Traverses through the object graph to get the IDs of all nodes to load. + + As a side-effect, if node_filters is a dictionary that contains already- + created objects, then the children tracked by those objects will be + added to node_filters. + + Returns: + List of all nodes to load, or None if all nodes should be loaded. + + """ + if self._node_filters is None: + return None # All nodes should be loaded. + + all_filtered_nodes = set() + nodes_to_visit = list(self._node_filters) + + while nodes_to_visit: + node_path = nodes_to_visit.pop(0) + node_id = self._node_path_to_id[node_path] + if node_id in all_filtered_nodes: + continue + all_filtered_nodes.add(node_id) + + node, setter = self._loaded_nodes.get(node_id, (None, None)) + if node is not None: + if not isinstance(node, base.Trackable): + raise TypeError( + "Error when processing dictionary values passed to nodes_to_load." + f"Object at {node_path} is expected to be a checkpointable (i.e. " + "'trackable') TensorFlow object (e.g. tf.Variable, tf.Module or " + "Keras layer).") + node._maybe_initialize_trackable() # pylint: disable=protected-access + + for reference in self._proto.nodes[node_id].children: + child_object, _ = self._loaded_nodes.get( + reference.node_id, (None, None)) + + # See if node already tracks the child reference, in which case add the + # child to the loaded_nodes dict. + if child_object is None and node is not None: + child_object = node._lookup_dependency(reference.local_name) # pylint: disable=protected-access + if isinstance(child_object, data_structures.TrackableDataStructure): + # Make setattr a noop to avoid overwriting already existing data + # structures. + setter = lambda *args: None + + self._loaded_nodes[reference.node_id] = (child_object, setter) + + child_path = "{}.{}".format(node_path, reference.local_name) + self._node_path_to_id[child_path] = reference.node_id + nodes_to_visit.append(child_path) + + if 0 in all_filtered_nodes: + return None + return all_filtered_nodes + + def _find_node_child(self, node_id, child_name, path): + for reference in self._proto.nodes[node_id].children: + if reference.local_name == child_name: + return reference.node_id + raise ValueError(f"Unable to find node {path}.") + + def _load_all(self): + """Loads all nodes and functions from the SavedModel and their edges.""" + self._load_nodes() + self._load_edges() + + # Set up concrete functions that aren't part of the object graph + # (e.g. gradient functions) + self._setup_remaining_functions() + self._load_checkpoint_save_and_restore_functions() + + def _load_checkpoint_save_and_restore_functions(self): + """Restores the checkpoint-related save/restore functions to all nodes.""" + temp_session = [None] + for node_id, proto in self._iter_all_nodes(): + node = self.get(node_id) + if proto.saveable_objects.keys() == { + trackable_utils.SERIALIZE_TO_TENSORS_NAME}: + # Restore Trackable serialize- and restore-from-tensor functions. + assert len(proto.saveable_objects) == 1 + saveable_object_proto = next(iter(proto.saveable_objects.values())) + save_fn_id = saveable_object_proto.save_function + restore_fn_id = saveable_object_proto.restore_function + node._serialize_to_tensors = self.get(save_fn_id) # pylint: disable=protected-access + node._restore_from_tensors = self.get(restore_fn_id) # pylint: disable=protected-access + else: + # Restore legacy SaveableObject functions. + saveable_fn_by_name = {} + for name, saveable_object_proto in proto.saveable_objects.items(): + save_fn_id = saveable_object_proto.save_function + restore_fn_id = saveable_object_proto.restore_function + saveable_fn_by_name[name] = (self.get(save_fn_id), + self.get(restore_fn_id)) + + node._self_saveable_object_factories = ( # pylint: disable=protected-access + saveable_object_util.recreate_saveable_objects(saveable_fn_by_name, + temp_session)) + + def _load_edges(self): + """Adds edges from objects to other objects and functions.""" + for node_id, object_proto in self._iter_all_nodes(): + self._add_object_graph_edges(object_proto, node_id) + + # If root object isn't loaded, then create edges from the root for + # checkpoint compatibility. + if self._filtered_nodes is not None and 0 not in self._filtered_nodes: + root = self.get(0) + for node_path in self._node_filters: + loaded_node = self._nodes[self._node_path_to_id[node_path]] + path = node_path.split(".") + current_node = root + for name in path[1:-1]: + if not hasattr(current_node, name): + setattr(current_node, name, self._recreate_base_user_object()[0]) + current_node = getattr(current_node, name) + if not hasattr(current_node, path[-1]): + setattr(current_node, path[-1], loaded_node) + + def _add_object_graph_edges(self, proto, node_id): + """Adds edges from an object to its children.""" + obj = self._nodes[node_id] + setter = self._node_setters[node_id] + + for reference in proto.children: + setter(obj, reference.local_name, self._nodes[reference.node_id]) + # Note: if an object has an attribute `__call__` add a class method + # that allows `obj()` syntax to work. This is done per-instance to + # allow `callable` to be used to find out if an object is callable. + if reference.local_name == "__call__" and not callable(obj): + setattr(type(obj), "__call__", _call_attribute) + + def _setup_remaining_functions(self): + concrete_function_names = sorted(self._proto.concrete_functions.keys()) + for name in concrete_function_names: + if name in self._restored_concrete_functions: + continue + self._setup_function_captures(name, self._nodes) + + def _setup_function_captures(self, concrete_function_name, nodes): + """Setup captures and variables in a restored function.""" + if concrete_function_name in self._restored_concrete_functions: + return + self._restored_concrete_functions.add(concrete_function_name) + concrete_function = self._concrete_functions[concrete_function_name] + proto = self._proto.concrete_functions[concrete_function_name] + inputs = [nodes[node_id] for node_id in proto.bound_inputs] + restore_captures.restore_captures(concrete_function, inputs) + + def _initialize_loaded_nodes(self): + nodes = {} + node_setters = {} + for node_id, (node, setter) in self._loaded_nodes.items(): + nodes[node_id] = node + node_setters[node_id] = setter + return nodes, node_setters + + def _get_node_dependencies(self, proto): + """Returns a dictionary of all dependencies of an object. + + Args: + proto: A SavedObject proto. + + Returns: + Dict mapping string dependency name *or* int node id to the node id. + The int node id key is used for mapping function captures. + """ + dependencies = {ref.local_name: ref.node_id for ref in proto.dependencies} + kind = proto.WhichOneof("kind") + if kind == "function": + concrete_functions = proto.function.concrete_functions + for fn_name in concrete_functions: + for bound_input in self._proto.concrete_functions[fn_name].bound_inputs: + dependencies[bound_input] = bound_input + elif kind == "bare_concrete_function": + fn_name = proto.bare_concrete_function.concrete_function_name + for bound_input in self._proto.concrete_functions[fn_name].bound_inputs: + dependencies[bound_input] = bound_input + elif kind == "resource": + # Make sure that the resource creator is listed as a dependency. + for child in proto.children: + if child.local_name == "_create_resource": + dependencies["_create_resource"] = child.node_id + return dependencies + + def _generate_ordered_node_ids(self): + """Orders the node ids so that dependencies appear first.""" + if self._filtered_nodes is None: + unordered_ids = range(len(self._proto.nodes)) + else: + unordered_ids = list(self._filtered_nodes) + + # Maps node ids -> list of dependencies (ids of other nodes that must be + # loaded before it). + dependency_map = collections.defaultdict(list) + for node_id in unordered_ids: + deps = dependency_map[node_id] + if self._loaded_nodes.get(node_id) is not None: + # Deps are only used if the node has not been created. + continue + proto = self._proto.nodes[node_id] + for dep in set(self._get_node_dependencies(proto).values()): + deps.append(dep) + if self._filtered_nodes is not None and dep not in self._filtered_nodes: + raise ValueError( + "Unable to partially load SavedModel since the specified filter " + "does not include all required objects for loading (e.g. " + "variables used in functions or deserialization dependencies). " + "Please include this path in the filter: " + f"{self._pretty_printer.node_names[dep]}") + + # Add optimizer slot variable to dependency map. + prev_slot = None + for slot_variable_proto in proto.slot_variables: + slot_variable_node_id = slot_variable_proto.slot_variable_node_id + # The optimizer and original variable must be created before the slot + # variable, since the slot variable is generated using the Optimizer's + # add_slot API. + slot_deps = dependency_map[slot_variable_node_id] + slot_deps.append(node_id) + slot_deps.append(slot_variable_proto.original_variable_node_id) + + if prev_slot is not None: + # Add previous slot to deps so that the optimizer slot variables are + # added in order. The ordering is needed because the slot name and + # variable are both added to ordered lists, which are exposed to the + # user via `Optimizer.get_slot_names()` and `Optimizer.weights`. + # TODO(kathywu): Maybe enforce some sort of deterministic ordering in + # `order_by_dependency` to avoid doing this? + slot_deps.append(prev_slot) + prev_slot = slot_variable_node_id + try: + return list(trackable_utils.order_by_dependency(dependency_map)) + except trackable_utils.CyclicDependencyError: + # This should not happen since there is already a validation for cycles + # when saving, but raise an error just in case. + raise ValueError("Encountered a cycle in the deserialization dependencies" + "in the SavedModel. This is extremely unexpected, please" + "file a bug and make sure you are not manually modifying" + " the SavedModel.") + + def _iter_all_nodes(self): + for node_id in self._ordered_node_ids: + yield node_id, self._proto.nodes[node_id] + + def _load_nodes(self): + """Load all saved objects.""" + # `nodes` maps from node ids to recreated objects + # `node_setters` maps from node ids to setter functions + # (same signature as setattr) for setting children. + nodes, node_setters = self._initialize_loaded_nodes() + + # Figure out which objects are slot variables. These objects are created + # with Optimizer.add_slot rather than _recreate_variable. + # Maps slot node id -> optimizer node id, SlotVariableReference proto + slot_variable_node_ids = {} + + for node_id, proto in self._iter_all_nodes(): + for slot_variable_proto in proto.slot_variables: + slot_variable_node_id = slot_variable_proto.slot_variable_node_id + slot_variable_node_ids[slot_variable_node_id] = (node_id, + slot_variable_proto) + + # Re-create everything. + for node_id, proto in self._iter_all_nodes(): + if nodes.get(node_id) is not None: + continue + elif node_id in slot_variable_node_ids: + # Use the public Optimizer interface when creating slot variables. + optimizer_node_id, slot_variable_proto = slot_variable_node_ids[node_id] + optimizer_object = nodes[optimizer_node_id] + optimized_variable = nodes[ + slot_variable_proto.original_variable_node_id] + slot_variable = optimizer_object.add_slot( + var=optimized_variable, + slot_name=slot_variable_proto.slot_name) + nodes[slot_variable_proto.slot_variable_node_id] = slot_variable + node_setters[slot_variable_proto.slot_variable_node_id] = setattr + else: + node, setter = self._recreate(proto, node_id, nodes) + nodes[node_id] = node + node_setters[node_id] = setter + + # If root object is not loaded, add a dummy root object for checkpoint + # compatibility. + if 0 not in nodes: + nodes[0] = self._recreate_base_user_object()[0] + + self._nodes = [nodes.get(node_id) + for node_id in range(len(self._proto.nodes))] + self._node_setters = node_setters + + def _restore_checkpoint(self): + """Load state from checkpoint into the deserialized objects.""" + variables_path = path_helpers.get_variables_path(self._export_dir) + # TODO(b/205010730): Clean use of private methods of TrackableSaver. + # pylint: disable=protected-access + saver = checkpoint.TrackableSaver(graph_view.ObjectGraphView(self.get(0))) + with ops.device("CPU"): + saver._file_prefix_placeholder = constant_op.constant(variables_path) + if self._save_options.allow_partial_checkpoint: + load_status = saver.restore(variables_path, + self._checkpoint_options).expect_partial() + load_status.assert_nontrivial_match() + else: + load_status = saver.restore(variables_path, self._checkpoint_options) + load_status.assert_existing_objects_matched() + ckpt = load_status._checkpoint + + if not context.executing_eagerly(): + reader = py_checkpoint_reader.NewCheckpointReader(variables_path) + + # When running in eager mode, the `restore` call above has already run and + # restored the state of trackables, and calling `position.restore_ops()` + # would re-run the restore. In graph mode, that will return a cached list + # of ops that must run to restore the object on that position. We have to + # wire them in the initializers of the objects so that they get + # initialized properly when using common practices (e.g. the ones used by + # ManagedSession) without further user action. + for object_id, obj in dict(ckpt.object_by_proto_id).items(): + position = restore.CheckpointPosition(checkpoint=ckpt, + proto_id=object_id) + registered_saver = position.get_registered_saver_name() + if registered_saver: + raise NotImplementedError( + "Loading a SavedModel that uses registered checkpoint saver is " + f"not supported in graph mode. The loaded object {obj} uses the " + f"saver registered with the name {registered_saver}.") + + restore_ops = position.restore_ops(reader) + if restore_ops: + if resource_variable_ops.is_resource_variable(obj): + if len(restore_ops) == 1: + obj._initializer_op = restore_ops[0] + else: + obj._initializer_op = control_flow_ops.group(*restore_ops) + elif (isinstance(obj, lookup_ops.LookupInterface) or + isinstance(obj, resource.CapturableResource)): + # We don't need to check for eager execution here, since this code + # path should only be taken if we are restoring in graph mode. + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, restore_ops) + else: + raise NotImplementedError( + f"Unable to restore state of object {obj} from the checkpoint.") + + def adjust_debug_info_func_names(self, debug_info): + """Rewrite func names in the debug info by using the concrete func names.""" + output_debug_info = graph_debug_info_pb2.GraphDebugInfo() + output_debug_info.files[:] = debug_info.files + for key in debug_info.traces: + node, func = key.split("@") + new_func = "" + if func in self._concrete_functions: + new_func = self._concrete_functions[func].function_def.signature.name + output_debug_info.traces[node + "@" + new_func].CopyFrom( + debug_info.traces[key]) + return output_debug_info + + def get(self, node_id): + if isinstance(node_id, str): + node_id = self._node_path_to_id[node_id] + return self._nodes[node_id] + + def _recreate(self, proto, node_id, nodes): + """Creates a Python object from a SavedObject protocol buffer. + + Args: + proto: a SavedObject proto + node_id: int, the index of this object in the SavedObjectGraph node list. + nodes: dict mapping int node_ids -> created objects. + + Returns: + The recreated object, and the set-attribute function for reconnecting + the trackable children. + """ + registered_class = registration.get_registered_class(proto.registered_name) + if registered_class is None: + registered_class = _BUILT_IN_REGISTRATIONS.get(proto.WhichOneof("kind")) + + dependencies = {} + for key, dep_node_id in self._get_node_dependencies(proto).items(): + dependencies[key] = nodes[dep_node_id] + + if registered_class: + obj = registered_class._deserialize_from_proto( # pylint: disable=protected-access + proto=proto.serialized_user_proto, + object_proto=proto, + dependencies=dependencies, + export_dir=self._export_dir, + asset_file_def=self._asset_file_def, + operation_attributes=self._operation_attributes) + if isinstance(obj, base.Trackable): + setter = type(obj)._add_trackable_child # pylint: disable=protected-access + else: + # Returned object may be non-Trackable (e.g. when restoring captures). + setter = setattr + return obj, setter + else: + return self._recreate_default(proto, node_id, dependencies) + + def _recreate_default(self, proto, node_id, deps): + """Creates a Python object from a SavedObject protocol buffer.""" + factory = { + "user_object": ( + lambda: self._recreate_user_object(proto.user_object, node_id)), + "function": lambda: self._recreate_function(proto.function, deps), + "bare_concrete_function": functools.partial( + self._recreate_bare_concrete_function, + proto=proto.bare_concrete_function, dependencies=deps), + "variable": lambda: self._recreate_variable(proto.variable), + "captured_tensor": functools.partial( + self._get_tensor_from_fn, proto.captured_tensor), + } + kind = proto.WhichOneof("kind") + if kind not in factory: + raise ValueError(f"Unknown SavedObject type: {kind}. Expected one of " + f"{list(factory.keys())}.") + return factory[kind]() + + def _recreate_user_object(self, proto, node_id): + """Instantiates a SavedUserObject.""" + if proto.identifier == "optimizer": + # Make sure that the Keras optimizers module is imported. This is needed + # to be able to load the "optimizer" object (OptimizerV2), which has + # special logic around adding slot variables with `add_slot` in this file. + try: + import tf_keras # pylint: disable=g-import-not-at-top,unused-import + try: + import tf_keras.optimizers.legacy as _ # pylint: disable=g-import-not-at-top + except ImportError: + try: + import tf_keras.optimizers.optimizer_v2 as _ # pylint: disable=g-import-not-at-top + except ImportError as e: + raise ImportError( + "Error when importing Keras. Unable to load SavedModel that " + "contains an optimizer without the Keras module.") from e + except ImportError: + try: + import keras.optimizers.legacy as _ # pylint: disable=g-import-not-at-top + except ImportError: + try: + import keras.optimizers.optimizer_v2 as _ # pylint: disable=g-import-not-at-top + except ImportError as e: + raise ImportError( + "Error when importing Keras. Unable to load SavedModel that " + "contains an optimizer without the Keras module.") from e + looked_up = revived_types.deserialize(proto) + if looked_up is None: + return self._recreate_base_user_object(proto, node_id) + return looked_up + + def _recreate_base_user_object(self, proto=None, node_id=None): + del proto, node_id + # Note: each user object has its own class. This allows making each one + # individually callable by adding a `__call__` method to the classes of + # the objects instances that have a `__call__` property. + + class _UserObject(autotrackable.AutoTrackable): + pass + + return _UserObject(), setattr + + def _recreate_function(self, proto, dependencies): + fn = function_deserialization.recreate_function( + proto, self._concrete_functions) + for name in proto.concrete_functions: + self._setup_function_captures(name, dependencies) + + # If the list of concrete functions associated with this polymorphic + # restored function is identical to a list of concrete functions found in + # the function alias mapping, we replace the latter with this restored + # function. Also see comments in the __init__ method. + if self._save_options.experimental_load_function_aliases: + if proto.concrete_functions and all( + name in self._concrete_function_aliases + for name in proto.concrete_functions + ): + alias = self._concrete_function_aliases[ + next(iter(proto.concrete_functions)) + ] + aliased = self.function_aliases.get(alias) + assert isinstance(aliased, list) + # Note that we cannot compare f.name below with proto.concrete_functions + # because the former is new name for the restored ConcreteFunction + # object while the latter is the old name in the original proto. + if set(f.name for f in aliased) == set( + f.name for f in fn._list_all_concrete_functions() # pylint: disable=protected-access + ): + self.function_aliases[alias] = fn + else: + logging.warn( + ( + "Not aliasing '%s' to polymorphic restored function because" + " of mismatched concrete functions: %s vs %s" + ), + alias, + set(f.name for f in aliased), + set(f.name for f in fn._list_all_concrete_functions()), # pylint: disable=protected-access + ) + + return fn, setattr + + def _recreate_bare_concrete_function(self, proto, dependencies): + fn = function_deserialization.setup_bare_concrete_function( + proto, self._concrete_functions) + self._setup_function_captures(proto.concrete_function_name, dependencies) + return fn, setattr + + def _recreate_variable(self, proto): + name = proto.name if proto.name else None + if name is not None: + dbg_name = name + else: + dbg_name = "" + synchronization, aggregation, trainable = ( + variables.validate_synchronization_aggregation_trainable( + proto.synchronization, proto.aggregation, proto.trainable, + name=dbg_name)) + + def uninitialized_variable_creator(next_creator, **kwargs): + """A variable creator that creates uninitialized variables.""" + del next_creator + return resource_variable_ops.UninitializedVariable(**kwargs) + + # Create a variable_creator_scope that creates uninitialized variables with + # a lower priority such that a potential distributed variable_creator_scope + # can take precedence. + with ops.get_default_graph()._variable_creator_scope( # pylint: disable=protected-access + uninitialized_variable_creator, + priority=50): + saved_device = proto.device + load_with_device = ( + self._save_options.experimental_variable_policy + ._save_variable_devices() and config.get_soft_device_placement() and + saved_device) + if load_with_device: + with ops.device(saved_device): + return variables.Variable( + shape=proto.shape, + dtype=proto.dtype, + name=name, + trainable=trainable, + synchronization=synchronization, + aggregation=aggregation), setattr + else: + return variables.Variable( + shape=proto.shape, + dtype=proto.dtype, + name=name, + trainable=trainable, + synchronization=synchronization, + aggregation=aggregation), setattr + + def _get_tensor_from_fn(self, proto): + outer_graph = self._concrete_functions[proto.concrete_function].graph + captured_tensor = outer_graph.get_tensor_by_name(proto.name) + return captured_tensor, setattr + + +def _call_attribute(instance, *args, **kwargs): + return instance.__call__(*args, **kwargs) + + +@tf_export("saved_model.load", v1=["saved_model.load_v2"]) +def load(export_dir, tags=None, options=None): + """Load a SavedModel from `export_dir`. + + Signatures associated with the SavedModel are available as functions: + + ```python + imported = tf.saved_model.load(path) + f = imported.signatures["serving_default"] + print(f(x=tf.constant([[1.]]))) + ``` + + Objects exported with `tf.saved_model.save` additionally have trackable + objects and functions assigned to attributes: + + ```python + exported = tf.train.Checkpoint(v=tf.Variable(3.)) + exported.f = tf.function( + lambda x: exported.v * x, + input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)]) + tf.saved_model.save(exported, path) + imported = tf.saved_model.load(path) + assert 3. == imported.v.numpy() + assert 6. == imported.f(x=tf.constant(2.)).numpy() + ``` + + _Loading Keras models_ + + Keras models are trackable, so they can be saved to SavedModel. The object + returned by `tf.saved_model.load` is not a Keras object (i.e. doesn't have + `.fit`, `.predict`, etc. methods). A few attributes and functions are still + available: `.variables`, `.trainable_variables` and `.__call__`. + + ```python + model = tf.keras.Model(...) + tf.saved_model.save(model, path) + imported = tf.saved_model.load(path) + outputs = imported(inputs) + ``` + + Use `tf.keras.models.load_model` to restore the Keras model. + + _Importing SavedModels from TensorFlow 1.x_ + + SavedModels from `tf.estimator.Estimator` or 1.x SavedModel APIs have a flat + graph instead of `tf.function` objects. These SavedModels will be loaded with + the following attributes: + + * `.signatures`: A dictionary mapping signature names to functions. + * `.prune(feeds, fetches) `: A method which allows you to extract + functions for new subgraphs. This is equivalent to importing the SavedModel + and naming feeds and fetches in a Session from TensorFlow 1.x. + + ```python + imported = tf.saved_model.load(path_to_v1_saved_model) + pruned = imported.prune("x:0", "out:0") + pruned(tf.ones([])) + ``` + + See `tf.compat.v1.wrap_function` for details. + * `.variables`: A list of imported variables. + * `.graph`: The whole imported graph. + * `.restore(save_path)`: A function that restores variables from a checkpoint + saved from `tf.compat.v1.Saver`. + + _Consuming SavedModels asynchronously_ + + When consuming SavedModels asynchronously (the producer is a separate + process), the SavedModel directory will appear before all files have been + written, and `tf.saved_model.load` will fail if pointed at an incomplete + SavedModel. Rather than checking for the directory, check for + "saved_model_dir/saved_model.pb". This file is written atomically as the last + `tf.saved_model.save` file operation. + + Args: + export_dir: The SavedModel directory to load from. + tags: A tag or sequence of tags identifying the MetaGraph to load. Optional + if the SavedModel contains a single MetaGraph, as for those exported from + `tf.saved_model.save`. + options: `tf.saved_model.LoadOptions` object that specifies options for + loading. + + Returns: + A trackable object with a `signatures` attribute mapping from signature + keys to functions. If the SavedModel was exported by `tf.saved_model.save`, + it also points to trackable objects, functions, debug info which it has been + saved. + + Raises: + ValueError: If `tags` don't match a MetaGraph in the SavedModel. + """ + if isinstance(export_dir, os.PathLike): + export_dir = os.fspath(export_dir) + result = load_partial(export_dir, None, tags, options)["root"] + return result + + +@tf_export("__internal__.saved_model.load_partial", v1=[]) +def load_partial(export_dir, filters, tags=None, options=None): + """Partially load a SavedModel (saved from V2). + + Similar to `tf.saved_model.load`, but with an additional argument that + lets you specify which nodes to load. + `tf.saved_model.load_partial(export_dir, ["root"])` and + `tf.saved_model.load(export_dir)` are equivalent. + + Note: This only works for SavedModels saved with TensorFlow V2 from + `tf.saved_model.save` or Keras. This will not load SavedModels save from + the Estimator API. + + In Tensorflow V2, SavedModel stores the **object graph** of the saved object. + The graph contains nodes (`tf.Module`, `tf.Variable`, `tf.function`, Keras + layers, etc.) and edges that are the name of the attributes connecting the + objects. + + *Example 1* + + ``` + model = tf.Module() + model.child_layer = tf.Module() + model.child_layer.v = tf.Variable(5.) + tf.saved_model.save(model, '/tmp/model') + loaded = tf.__internal__.saved_model.load_partial( + ... '/tmp/model', + ... ['root.child_layer', 'root.child_layer.v']) + loaded['root.child_layer'].v.numpy() + 5. + loaded['root.child_layer'].v is loaded['root.child_layer.v'] + True + + *Example 2* + model = tf.Module() + model.child_layer = tf.Module() + model.child_layer.v = tf.Variable(5.) + >>> + tf.saved_model.save(model, '/tmp/model') + # Create a variable + new_variable = tf.Variable(0.) + loaded = tf.__internal__.saved_model.load_partial( + ... '/tmp/model', + ... {'root.child_layer': None, 'root.child_layer.v': new_variable}) + loaded['root.child_layer'].v.numpy() + 5. + new_variable.numpy() + 5. + ``` + + **Loading under different distribution strategies** + You can load different parts of the model under different distribution + strategies. Note that this is very experimental so use with care. + + ``` + model = tf.Module() + model.layer_1 = tf.Module() + model.layer_1.v = tf.Variable(5.) + model.layer_2 = tf.Module() + model.layer_2.v = tf.Variable(7.) + tf.saved_model.save(model, '/tmp/model') + # Load with no strategy + loaded = tf.__internal__.saved_model.load_partial( + ... '/tmp/model', + ... ['root.layer_1']) + loaded['root.layer_1'].v + + strategy = tf.distribute.MirroredStrategy() + with strategy.scope(): + ... loaded2 = tf.__internal__.saved_model.load_partial( + ... '/tmp/model', + ... ['root.layer_2']) + loaded2['root.layer_2'].v + MirroredVariable:{ + 0: + } + ``` + + Args: + export_dir: The SavedModel directory to load from. + filters: A list or dictionary where each element or key is a string + path to nodes that should be loaded. Node paths consist of all the child + attribute names to reach that node in the form: `root.{attribute_name}`. + The loader will load all of the specified nodes and their recursive + descendants. When this option is defined, the loader will return a + dictionary mapping the node paths to the loaded objects. + tags: A tag or sequence of tags identifying the MetaGraph to load. Optional + if the SavedModel contains a single MetaGraph, as for those exported from + `tf.saved_model.save`. + options: `tf.saved_model.LoadOptions` object that specifies options for + loading. + + Returns: + A dictionary mapping node paths from the filter to loaded objects. + """ + options = options or load_options.LoadOptions() + if tags is not None and not isinstance(tags, set): + # Supports e.g. tags=SERVING and tags=[SERVING]. Sets aren't considered + # sequences for nest.flatten, so we put those through as-is. + tags = nest.flatten(tags) + saved_model_proto, debug_info = ( + loader_impl.parse_saved_model_with_debug_info(export_dir)) + + loader = None + if (len(saved_model_proto.meta_graphs) == 1 and + saved_model_proto.meta_graphs[0].HasField("object_graph_def")): + metrics.IncrementReadApi(_LOAD_V2_LABEL) + meta_graph_def = saved_model_proto.meta_graphs[0] + # tensor_content field contains raw bytes in litle endian format + # which causes problems when loaded on big-endian systems + # requiring byteswap + if sys.byteorder == "big": + saved_model_utils.swap_function_tensor_content(meta_graph_def, "little", + "big") + if (tags is not None + and set(tags) != set(meta_graph_def.meta_info_def.tags)): + raise ValueError( + f"Got an incompatible argument to `tags`: {tags}. The SavedModel at " + f"{export_dir} has one MetaGraph with tags " + f"{meta_graph_def.meta_info_def.tags}. You may omit the argument, " + "pass 'None', or pass matching tags.") + object_graph_proto = meta_graph_def.object_graph_def + + ckpt_options = checkpoint_options.CheckpointOptions( + experimental_io_device=options.experimental_io_device) + with ops.init_scope(): + try: + loader = Loader(object_graph_proto, saved_model_proto, export_dir, + ckpt_options, options, filters) + except errors.NotFoundError as err: + raise FileNotFoundError( + str(err) + "\n You may be trying to load on a different device " + "from the computational device. Consider setting the " + "`experimental_io_device` option in `tf.saved_model.LoadOptions` " + "to the io_device such as '/job:localhost'.") + root = loader.get(0) + root.graph_debug_info = loader.adjust_debug_info_func_names(debug_info) + root.tensorflow_version = meta_graph_def.meta_info_def.tensorflow_version + root.tensorflow_git_version = ( + meta_graph_def.meta_info_def.tensorflow_git_version) + metrics.IncrementRead(write_version="2") + + if options.experimental_load_function_aliases: + if hasattr(root, "function_aliases"): + raise ValueError( + "Could not load with experimental_load_function_aliases option" + " because the top-level object already has an attributed with name" + " 'function_aliases'" + ) + root.function_aliases = loader.function_aliases + else: + if filters: + raise ValueError("SavedModels saved from Tensorflow 1.x or Estimator (any" + " version) cannot be loaded with node filters.") + with ops.init_scope(): + root = load_v1_in_v2.load( + export_dir, tags, options.experimental_skip_checkpoint + ) + root.graph_debug_info = debug_info + # For privacy concerns, please see the note in + # tensorflow/cc/saved_model/metrics.h + metrics.SetReadPath(saved_model_path=str(export_dir)) + + # Read and log SavedModel checksum, if it is nonzero. + try: + fingerprint = fingerprinting.read_fingerprint(export_dir) + except FileNotFoundError: + metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintNotFound) + logging.info( + "Fingerprint not found. Saved model loading will continue.") + singleprint = "" + except RuntimeError: + metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintError) + logging.exception( + "Fingerprint was found, but there was an error when reading the proto. " + "Saved model loading will continue.") + singleprint = "" + else: + metrics.SetFoundFingerprintOnLoad(found_status=metrics.kFingerprintFound) + metrics.SetReadFingerprint( + fingerprint=fingerprinting_utils.to_proto( + fingerprint).SerializeToString()) + singleprint = fingerprint.singleprint() + + try: + metrics.SetReadPathAndSingleprint(path=export_dir, singleprint=singleprint) + except metrics.MetricException: + logging.info("path_and_singleprint metric could not be logged. " + "Saved model loading will continue.") + + if filters and loader is not None: + return {node_id: loader.get(node_id) for node_id in filters} + else: + return {"root": root} + + +def is_tf2_saved_model(export_dir): + """Identifies if an exported SavedModel is a TF2 SavedModel. + + There are differences in SavedModel semantics between TF1 and TF2 that are + documented here: + https://www.tensorflow.org/guide/migrate/saved_model#savedmodel. This helper + util function serves to distinguish the TF1 vs TF2 semantics used when + exporting SavedModels. + + Args: + export_dir: The SavedModel directory to load from. + + Returns: + True if TF2 SavedModel semantics are used, False if TF1 SavedModel semantics + are used. + """ + # Try reading the fingerprint first before parsing the SavedModel proto + try: + fingerprint = fingerprinting.read_fingerprint(export_dir) + if fingerprint.saved_object_graph_hash != 0: + logging.info("SavedModel at %s is a TF2 SavedModel", export_dir) + return True + except Exception: # pylint: disable=broad-exception-caught + logging.info( + "Failed to read fingerprint from SavedModel. Parsing MetaGraph ..." + ) + saved_model_proto = loader_impl.parse_saved_model(export_dir) + if len( + saved_model_proto.meta_graphs + ) == 1 and saved_model_proto.meta_graphs[0].HasField("object_graph_def"): + logging.info("SavedModel at %s is a TF2 SavedModel", export_dir) + return True + + logging.info("SavedModel at %s is a TF1 SavedModel", export_dir) + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_options.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_options.py new file mode 100644 index 0000000000000000000000000000000000000000..1981065131758a83dc3ad775acbbadc21612b15c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_options.py @@ -0,0 +1,125 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Options for saving SavedModels.""" + +from tensorflow.python.saved_model import save_options +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("saved_model.LoadOptions", v1=[]) +class LoadOptions(object): + """Options for loading a SavedModel. + + This function may be used in the `options` argument in functions that + load a SavedModel (`tf.saved_model.load`, `tf.keras.models.load_model`). + """ + + # Define object attributes in __slots__ for improved memory and performance. + __slots__ = ("allow_partial_checkpoint", "experimental_io_device", + "experimental_skip_checkpoint", "experimental_variable_policy", + "experimental_load_function_aliases") + + def __init__(self, + allow_partial_checkpoint=False, + experimental_io_device=None, + experimental_skip_checkpoint=False, + experimental_variable_policy=None, + experimental_load_function_aliases=False): + """Creates an object that stores options for SavedModel loading. + + *When to set `allow_partial_checkpoint=True`?* + + This can be used when loading a Keras model (`tf.keras.models.load_model`) + with custom objects. When new variables are added to the custom object + class, loading will fail the assertion check that all loaded variables have + been restored, because the SavedModel checkpoint only contains the variables + that were in original the custom object. + See the following example: + + ``` + class Custom(tf.keras.Model): + def __init__(self): + super(Custom, self).__init__() + self.v = tf.Variable(...) + + def call(self, inputs): + return ... + + model = Custom() + model.save(...) + ``` + + After saving, say that `Custom` is updated to include an additional + variable. + + ``` + class Custom(tf.keras.Model): + def __init__(self): + super(Custom, self).__init__() + self.v = tf.Variable(...) + self.w = tf.Variable(...) + + def call(self, inputs): + return ... + ``` + + `tf.keras.models.load_model(path, custom_objects={'Custom': Custom})` fails + to load since `Custom.w` does not exist in the SavedModel checkpoint. To + acknowledge that there are variables that are not restored from the + checkpoint and successfully load the model, call: + + ``` + tf.keras.models.load_model( + path, custom_objects={'Custom': Custom}, + options=tf.saved_model.LoadOptions(allow_partial_checkpoint=True)) + ``` + + Args: + allow_partial_checkpoint: bool. Defaults to `False`. When enabled, allows + the SavedModel checkpoint to not entirely match the loaded object. + experimental_io_device: string. Applies in a distributed setting. + Tensorflow device to use to access the filesystem. If `None` (default) + then for each variable the filesystem is accessed from the CPU:0 device + of the host where that variable is assigned. If specified, the + filesystem is instead accessed from that device for all variables. + This is for example useful if you want to load from a local directory, + such as "/tmp" when running in a distributed setting. In that case + pass a device for the host where the "/tmp" directory is accessible. + experimental_skip_checkpoint: bool. Defaults to `False`. If set to `True`, + checkpoints will not be restored. Note that this in the majority of + cases will generate an unusable model. + experimental_variable_policy: string. The policy to apply to variables + when loading. This is either a `saved_model.experimental.VariablePolicy` + enum instance or one of its value strings (case is not important). See + that enum documentation for details. A value of `None` corresponds to + the default policy. + experimental_load_function_aliases: bool. Defaults to `False`. If set to + `True`, a `function_aliases` attribute will be added to the loaded + SavedModel object. + + Example: + + load_options = tf.saved_model.LoadOptions(experimental_io_device= + '/job:localhost') + restoredmodel = tf.keras.models.load_model(saved_model_path, + options=load_options) + + """ + self.experimental_io_device = experimental_io_device + self.allow_partial_checkpoint = allow_partial_checkpoint + self.experimental_skip_checkpoint = experimental_skip_checkpoint + self.experimental_variable_policy = ( + save_options.VariablePolicy.from_obj(experimental_variable_policy)) + self.experimental_load_function_aliases = experimental_load_function_aliases diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_v1_in_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_v1_in_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..69dd40bd023ec021355d3a74935e966c5dab181e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/load_v1_in_v2.py @@ -0,0 +1,313 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Import a TF v1-style SavedModel when executing eagerly.""" + +import functools + +from tensorflow.python.eager import context +from tensorflow.python.eager import lift_to_graph +from tensorflow.python.eager import wrap_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import function_deserialization +from tensorflow.python.saved_model import loader_impl +from tensorflow.python.saved_model import signature_serialization +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import asset +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import resource +from tensorflow.python.training import monitored_session +from tensorflow.python.training import saver as tf_saver +from tensorflow.python.util import nest + +# API label for SavedModel metrics. +_LOAD_V1_V2_LABEL = "load_v1_in_v2" + + +class _Initializer(resource.CapturableResource): + """Represents an initialization operation restored from a SavedModel. + + Without this object re-export of imported 1.x SavedModels would omit the + original SavedModel's initialization procedure. + + Created when `tf.saved_model.load` loads a TF 1.x-style SavedModel with an + initialization op. This object holds a function that runs the + initialization. It does not require any manual user intervention; + `tf.saved_model.save` will see this object and automatically add it to the + exported SavedModel, and `tf.saved_model.load` runs the initialization + function automatically. + """ + + def __init__(self, init_fn, asset_paths): + super(_Initializer, self).__init__() + self._asset_paths = asset_paths + self._init_fn = init_fn + + def _create_resource(self): + # Return a constant here so that when re-saved, the traced `create_resource` + # has valid returns. + return constant_op.constant(1.0) + + def _initialize(self): + return self._init_fn(*[path.asset_path for path in self._asset_paths]) + + +class _EagerSavedModelLoader(loader_impl.SavedModelLoader): + """Loads a SavedModel without using Sessions.""" + + def get_meta_graph_def_from_tags(self, tags): + """Override to support implicit one-MetaGraph loading with tags=None.""" + if tags is None: + if len(self._saved_model.meta_graphs) != 1: + tag_sets = [ + mg.meta_info_def.tags for mg in self._saved_model.meta_graphs + ] + raise ValueError( + "Importing a SavedModel with `tf.saved_model.load` requires a " + "`tags=` argument if there is more than one MetaGraph. Got " + f"`tags=None`, but there are {len(self._saved_model.meta_graphs)} " + f"MetaGraphs in the SavedModel with tag sets: {tag_sets}. Pass a " + "`tags=` argument to load this SavedModel." + ) + return self._saved_model.meta_graphs[0] + return super(_EagerSavedModelLoader, self).get_meta_graph_def_from_tags( + tags + ) + + def load_graph(self, returns, meta_graph_def): + """Called from wrap_function to import `meta_graph_def`.""" + # pylint: disable=protected-access + saver, _ = tf_saver._import_meta_graph_with_return_elements(meta_graph_def) + # pylint: enable=protected-access + returns[0] = saver + + def _extract_saver_restore(self, wrapped, saver): + if saver is None: + return None + saver_def = saver.saver_def + filename_tensor = wrapped.graph.as_graph_element( + saver_def.filename_tensor_name + ) + # We both feed and fetch filename_tensor so we have an operation to use to + # feed into variable initializers (only relevant for v1 graph building). + return wrapped.prune( + feeds=[filename_tensor], + fetches=[ + filename_tensor, + wrapped.graph.as_graph_element(saver_def.restore_op_name), + ], + ) + + def restore_variables(self, wrapped, restore_from_saver): + """Restores variables from the checkpoint.""" + if restore_from_saver is not None: + initializer, _ = restore_from_saver( + constant_op.constant(self._variables_path) + ) + if not ops.executing_eagerly_outside_functions(): + # Add the initialization operation to the "saved_model_initializers" + # collection in case we don't have any lifted variables to attach it to. + ops.add_to_collection("saved_model_initializers", initializer) + one_unlifted = False + + for variable in wrapped.graph.get_collection_ref( + ops.GraphKeys.GLOBAL_VARIABLES + ): + if variable.graph is wrapped.graph: + one_unlifted = True + # pylint: disable=protected-access + variable._initializer_op = initializer + # pylint: enable=protected-access + if one_unlifted: + logging.warning( + "Some variables could not be lifted out of a loaded function. " + "Please run " + '`sess.run(tf.get_collection("saved_model_initializers"))`to ' + "restore these variables." + ) + + def _extract_signatures(self, wrapped, meta_graph_def): + """Creates ConcreteFunctions for signatures in `meta_graph_def`.""" + signature_functions = {} + for signature_key, signature_def in meta_graph_def.signature_def.items(): + if signature_def.inputs: + input_items = sorted( + signature_def.inputs.items(), key=lambda item: item[0] + ) + original_input_names, input_specs = zip(*input_items) + else: + original_input_names = [] + input_specs = [] + # TODO(b/205015292): Support optional arguments + feeds = [ + wrap_function._get_element_from_tensor_info(input_spec, wrapped.graph) # pylint: disable=protected-access + for input_spec in input_specs + ] + input_names = [] + input_tensors = [] + for original_input_name, feed in zip(original_input_names, feeds): + if isinstance(feed, sparse_tensor.SparseTensor): + # We have to give explicit name for SparseTensor arguments, because + # these are not present in the TensorInfo. + indices_name = "%s_indices" % original_input_name + values_name = "%s_values" % original_input_name + dense_shape_name = "%s_dense_shape" % original_input_name + input_names.extend([indices_name, values_name, dense_shape_name]) + input_tensors.extend([feed.indices, feed.values, feed.dense_shape]) + elif isinstance(feed, composite_tensor.CompositeTensor): + component_tensors = nest.flatten(feed, expand_composites=True) + input_names.extend( + "%s_component_%d" % (original_input_name, n) + for n in range(len(component_tensors)) + ) + input_tensors.extend(component_tensors) + else: + input_names.append(original_input_name) + input_tensors.append(feed) + fetches = {name: out for name, out in signature_def.outputs.items()} + try: + signature_fn = wrapped.prune(feeds=feeds, fetches=fetches) + except lift_to_graph.UnliftableError as ex: + # Mutate the exception to add a bit more detail. + args = ex.args + if not args: + message = "" + else: + message = args[0] + message = ( + "A SavedModel signature needs an input for each placeholder the " + "signature's outputs use. An output for signature '{}' depends on " + "a placeholder which is not an input (i.e. the placeholder is not " + "fed a value).\n\n" + ).format(signature_key) + message + ex.args = (message,) + args[1:] + raise + # pylint: disable=protected-access + signature_fn._arg_keywords = input_names + signature_fn._func_graph.structured_input_signature = ( + (), + func_graph.convert_structure_to_signature( + dict(zip(input_names, input_tensors)) + ), + ) + + if len(input_names) == 1: + # Allowing positional arguments does not create any ambiguity if there's + # only one. + signature_fn._num_positional_args = 1 + else: + signature_fn._num_positional_args = 0 + # pylint: enable=protected-access + signature_functions[signature_key] = signature_fn + return signature_functions + + def load(self, tags, skip_restoring_checkpoint=False): + """Creates an object from the MetaGraph identified by `tags`.""" + meta_graph_def = self.get_meta_graph_def_from_tags(tags) + load_shared_name_suffix = "_load_{}".format(ops.uid()) + functions = function_deserialization.load_function_def_library( + meta_graph_def.graph_def.library, + load_shared_name_suffix=load_shared_name_suffix, + ) + # Replace existing functions in the MetaGraphDef with renamed functions so + # we don't have duplicates or name collisions. + meta_graph_def.graph_def.library.Clear() + for function in functions.values(): + meta_graph_def.graph_def.library.function.add().CopyFrom( + function.function_def + ) + # We've renamed functions and shared names. We need the same operation on + # the GraphDef itself for consistency. + for node_def in meta_graph_def.graph_def.node: + function_deserialization.fix_node_def( + node_def, functions, load_shared_name_suffix + ) + + load_graph_returns = [None] + wrapped = wrap_function.wrap_function( + functools.partial(self.load_graph, load_graph_returns, meta_graph_def), + signature=[], + ) + (saver,) = load_graph_returns + restore_from_saver = self._extract_saver_restore(wrapped, saver) + + if not skip_restoring_checkpoint: + self.restore_variables(wrapped, restore_from_saver) + + with wrapped.graph.as_default(): + init_op = ( + loader_impl.get_init_op(meta_graph_def) + or monitored_session.Scaffold.default_local_init_op() + ) + # Add a dummy Tensor we know we can fetch to add control dependencies to. + init_anchor = constant_op.constant(0.0, name="dummy_fetch") + + root = autotrackable.AutoTrackable() + if restore_from_saver is not None: + root.restore = lambda path: restore_from_saver(constant_op.constant(path)) + asset_feed_tensors = [] + asset_paths = [] + for tensor_name, value in loader_impl.get_asset_tensors( + self._export_dir, meta_graph_def + ).items(): + asset_feed_tensors.append(wrapped.graph.as_graph_element(tensor_name)) + asset_paths.append(asset.Asset(value)) + init_fn = wrapped.prune( + feeds=asset_feed_tensors, + fetches=[init_anchor, wrapped.graph.as_graph_element(init_op)], + ) + initializer = _Initializer(init_fn, asset_paths) + # pylint: disable=protected-access + local_init_op, _ = initializer._initialize() + # pylint: enable=protected-access + with ops.init_scope(): + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, local_init_op) + for variable in wrapped.graph.get_collection_ref( + ops.GraphKeys.LOCAL_VARIABLES + ): + # pylint: disable=protected-access + variable._initializer_op = local_init_op + # pylint: enable=protected-access + root.initializer = initializer + root.asset_paths = asset_paths + signature_functions = self._extract_signatures(wrapped, meta_graph_def) + + root.signatures = signature_serialization.create_signature_map( + signature_functions + ) + root.variables = list(wrapped.graph.variables) + root.tensorflow_version = meta_graph_def.meta_info_def.tensorflow_version + root.tensorflow_git_version = ( + meta_graph_def.meta_info_def.tensorflow_git_version + ) + root.graph = wrapped.graph + root.prune = wrapped.prune + return root + + +def load(export_dir, tags, skip_restoring_checkpoint=False): + """Load a v1-style SavedModel as an object.""" + metrics.IncrementReadApi(_LOAD_V1_V2_LABEL) + loader = _EagerSavedModelLoader(export_dir) + result = loader.load( + tags=tags, skip_restoring_checkpoint=skip_restoring_checkpoint + ) + metrics.IncrementRead(write_version="1") + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..854be8da2487f89bce8c36beac7c3539bcc9d466 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader.py @@ -0,0 +1,65 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Loader functionality for SavedModel with hermetic, language-neutral exports. + +Load and restore capability for a SavedModel, which may include multiple meta +graph defs. Each SavedModel is associated with a single checkpoint. Each meta +graph def is saved with one or more tags, which are used to identify the exact +meta graph def to load. + +The `load` operation requires the session in which to restore the graph +definition and variables, the tags used to identify the meta graph def to +load and the location of the SavedModel. + +Upon a load, the subset of variables and assets supplied as part of the specific +meta graph def, will be restored into the supplied session. The values of the +variables though will correspond to the saved values from the first meta graph +added to the SavedModel using `add_meta_graph_and_variables(...)` in +`builder.py`. + +Typical usage: + +```python +... +builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(export_dir) + +with tf.compat.v1.Session(graph=tf.Graph()) as sess: + ... + builder.add_meta_graph_and_variables(sess, + ["foo-tag"], + signature_def_map=foo_signatures, + assets_collection=foo_assets) +... + +with tf.compat.v1.Session(graph=tf.Graph()) as sess: + ... + builder.add_meta_graph(["bar-tag", "baz-tag"], + assets_collection=bar_baz_assets) +... + +builder.save() + +... +with tf.compat.v1.Session(graph=tf.Graph()) as sess: + tf.compat.v1.saved_model.loader.load(sess, ["foo-tag"], export_dir) + ... + +``` +""" + +# pylint: disable=unused-import +from tensorflow.python.saved_model.loader_impl import load +from tensorflow.python.saved_model.loader_impl import maybe_saved_model_directory +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..3b86b89013a0b3673bb24a17ab7bfc3ac36957ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/loader_impl.py @@ -0,0 +1,513 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Loader implementation for SavedModel with hermetic, language-neutral exports. +""" + +import os +import sys + +from google.protobuf import message +from google.protobuf import text_format + +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saved_model_pb2 +from tensorflow.python.framework import ops +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import utils_impl as saved_model_utils +# Placeholder for protosplitter merger import. +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.training import saver as tf_saver +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +# API label for SavedModel metrics. +_LOADER_LABEL = "loader" + + +def parse_saved_model_with_debug_info(export_dir): + """Reads the savedmodel as well as the graph debug info. + + Args: + export_dir: Directory containing the SavedModel and GraphDebugInfo files. + + Returns: + `SavedModel` and `GraphDebugInfo` protocol buffers. + + Raises: + IOError: If the saved model file does not exist, or cannot be successfully + parsed. Missing graph debug info file is fine. + """ + saved_model = parse_saved_model(export_dir) + + debug_info_path = file_io.join( + path_helpers.get_debug_dir(export_dir), + constants.DEBUG_INFO_FILENAME_PB) + debug_info = graph_debug_info_pb2.GraphDebugInfo() + if file_io.file_exists(debug_info_path): + with file_io.FileIO(debug_info_path, "rb") as debug_file: + try: + debug_info.ParseFromString(debug_file.read()) + except message.DecodeError as e: + raise IOError(f"Cannot parse file {debug_info_path}: {e}.") + + return (saved_model, debug_info) + + +@tf_export("__internal__.saved_model.parse_saved_model", v1=[]) +def parse_saved_model(export_dir): + """Reads the savedmodel.pb or savedmodel.pbtxt file containing `SavedModel`. + + Args: + export_dir: String or Pathlike, path to the directory containing the + SavedModel file. + + Returns: + A `SavedModel` protocol buffer. + + Raises: + IOError: If the file does not exist, or cannot be successfully parsed. + """ + # Build the path to the SavedModel in pbtxt format. + path_to_pbtxt = file_io.join( + compat.as_bytes(compat.path_to_str(export_dir)), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT)) + # Build the path to the SavedModel in pb format. + path_to_pb = file_io.join( + compat.as_bytes(compat.path_to_str(export_dir)), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB)) + # Build the path to the SavedModel in cpb format. + path_to_cpb = file_io.join( + compat.as_bytes(compat.path_to_str(export_dir)), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_CPB)) + + # Parse the SavedModel protocol buffer. + saved_model = saved_model_pb2.SavedModel() + if file_io.file_exists(path_to_pb): + with file_io.FileIO(path_to_pb, "rb") as f: + file_content = f.read() + try: + saved_model.ParseFromString(file_content) + except message.DecodeError as e: + raise IOError(f"Cannot parse file {path_to_pb}: {str(e)}.") from e + elif file_io.file_exists(path_to_pbtxt): + with file_io.FileIO(path_to_pbtxt, "rb") as f: + file_content = f.read() + try: + text_format.Parse(file_content.decode("utf-8"), saved_model) + except text_format.ParseError as e: + raise IOError(f"Cannot parse file {path_to_pbtxt}: {str(e)}.") from e + else: + raise IOError( + f"SavedModel file does not exist at: {export_dir}{os.path.sep}" + f"{{{constants.SAVED_MODEL_FILENAME_PBTXT}|" + f"{constants.SAVED_MODEL_FILENAME_PB}}}") + return saved_model + + +def get_asset_tensors(export_dir, meta_graph_def_to_load, import_scope=None): + """Gets the asset tensors, if defined in the meta graph def to load. + + Args: + export_dir: Directory where the SavedModel is located. + meta_graph_def_to_load: The meta graph def from the SavedModel to be loaded. + import_scope: Optional `string` -- if specified, prepend this followed by + '/' to all returned asset tensor names. + + Returns: + A dictionary of asset tensors, keyed by the name of the asset tensor. The + value in the map corresponds to the absolute path of the asset file. + """ + # Collection-def that may contain the assets key. + collection_def = meta_graph_def_to_load.collection_def + + asset_tensor_dict = {} + asset_protos = [] + + if meta_graph_def_to_load.asset_file_def: + asset_protos = meta_graph_def_to_load.asset_file_def + elif constants.ASSETS_KEY in collection_def: + assets_any_proto = collection_def[constants.ASSETS_KEY].any_list.value + for asset_any_proto in assets_any_proto: + asset_proto = meta_graph_pb2.AssetFileDef() + asset_any_proto.Unpack(asset_proto) + asset_protos.append(asset_proto) + + # Location of the assets for SavedModel. + assets_directory = file_io.join( + compat.as_bytes(export_dir), compat.as_bytes(constants.ASSETS_DIRECTORY)) + # Process each asset and add it to the asset tensor dictionary. + for asset_proto in asset_protos: + tensor_name = asset_proto.tensor_info.name + if import_scope: + tensor_name = "%s/%s" % (import_scope, tensor_name) + asset_tensor_dict[tensor_name] = file_io.join( + compat.as_bytes(assets_directory), + compat.as_bytes(asset_proto.filename)) + + return asset_tensor_dict + + +def _get_main_op_tensor( + meta_graph_def_to_load, init_op_key=constants.MAIN_OP_KEY): + """Gets the main op tensor, if one exists. + + Args: + meta_graph_def_to_load: The meta graph def from the SavedModel to be loaded. + init_op_key: name of the collection to check; should be one of MAIN_OP_KEY + or the deprecated LEGACY_INIT_OP_KEY + + Returns: + The main op tensor, if it exists and `None` otherwise. + + Raises: + RuntimeError: If the collection def corresponding to the main op key has + other than exactly one tensor. + """ + # TODO(kathywu): Rename this method to _get_op_from_collection when + # dependency from SavedModelEstimator is removed. + collection_def = meta_graph_def_to_load.collection_def + init_op = None + if init_op_key in collection_def: + init_op_list = collection_def[init_op_key].node_list.value + if len(init_op_list) != 1: + raise RuntimeError("Expected exactly one SavedModel init op. " + f"Found {len(init_op_list)}: {init_op_list}.") + init_op = ops.get_collection(init_op_key)[0] + return init_op + + +def _get_op_from_collection(meta_graph_def, op_key): + return _get_main_op_tensor(meta_graph_def, op_key) + + +def _get_op_from_signature_def(meta_graph_def, op_signature_key, import_scope): + """Retrieve op stored in the imported meta graph's signature def.""" + if op_signature_key in meta_graph_def.signature_def: + return signature_def_utils.load_op_from_signature_def( + meta_graph_def.signature_def[op_signature_key], op_signature_key, + import_scope) + else: + return None + + +def get_init_op(meta_graph_def, import_scope=None): + return (_get_op_from_signature_def( + meta_graph_def, constants.INIT_OP_SIGNATURE_KEY, import_scope) or + _get_op_from_collection(meta_graph_def, constants.MAIN_OP_KEY) or + _get_op_from_collection(meta_graph_def, constants.LEGACY_INIT_OP_KEY)) + + +def get_train_op(meta_graph_def, import_scope=None): + train_op = _get_op_from_signature_def( + meta_graph_def, constants.TRAIN_OP_SIGNATURE_KEY, import_scope) + if train_op is None: + train_op = _get_op_from_collection(meta_graph_def, constants.TRAIN_OP_KEY) + return train_op + + +@tf_export(v1=[ + "saved_model.contains_saved_model", + "saved_model.maybe_saved_model_directory", + "saved_model.loader.maybe_saved_model_directory" +]) +@deprecation.deprecated_endpoints( + "saved_model.loader.maybe_saved_model_directory") +def maybe_saved_model_directory(export_dir): + """Checks whether the provided export directory could contain a SavedModel. + + Note that the method does not load any data by itself. If the method returns + `false`, the export directory definitely does not contain a SavedModel. If the + method returns `true`, the export directory may contain a SavedModel but + provides no guarantee that it can be loaded. + + Args: + export_dir: Absolute string path to possible export location. For example, + '/my/foo/model'. + + Returns: + True if the export directory contains SavedModel files, False otherwise. + """ + txt_path = file_io.join(export_dir, constants.SAVED_MODEL_FILENAME_PBTXT) + pb_path = file_io.join(export_dir, constants.SAVED_MODEL_FILENAME_PB) + return file_io.file_exists(txt_path) or file_io.file_exists(pb_path) + + +@tf_export("saved_model.contains_saved_model", v1=[]) +def contains_saved_model(export_dir): + """Checks whether the provided export directory could contain a SavedModel. + + Note that the method does not load any data by itself. If the method returns + `false`, the export directory definitely does not contain a SavedModel. If the + method returns `true`, the export directory may contain a SavedModel but + provides no guarantee that it can be loaded. + + Args: + export_dir: Absolute path to possible export location. For example, + '/my/foo/model'. + + Returns: + True if the export directory contains SavedModel files, False otherwise. + """ + if isinstance(export_dir, os.PathLike): + export_dir = os.fspath(export_dir) + return maybe_saved_model_directory(export_dir) + + +@tf_export(v1=["saved_model.load", "saved_model.loader.load"]) +@deprecation.deprecated( + None, + "Use `tf.saved_model.load` instead.") +def load(sess, tags, export_dir, import_scope=None, **saver_kwargs): + """Loads the model from a SavedModel as specified by tags. + + Args: + sess: The TensorFlow session to restore the variables. + tags: Set of string tags to identify the required MetaGraphDef. These should + correspond to the tags used when saving the variables using the + SavedModel `save()` API. + export_dir: Directory in which the SavedModel protocol buffer and variables + to be loaded are located. + import_scope: Optional `string` -- if specified, prepend this string + followed by '/' to all loaded tensor names. This scope is applied to + tensor instances loaded into the passed session, but it is *not* written + through to the static `MetaGraphDef` protocol buffer that is returned. + **saver_kwargs: Optional keyword arguments passed through to Saver. + + Returns: + The `MetaGraphDef` protocol buffer loaded in the provided session. This + can be used to further extract signature-defs, collection-defs, etc. + + Raises: + RuntimeError: MetaGraphDef associated with the tags cannot be found. + + @compatibility(TF2) + + `tf.compat.v1.saved_model.load` or `tf.compat.v1.saved_model.loader.load` is + not compatible with eager execution. Please use `tf.saved_model.load` instead + to load your model. You can refer to the [SavedModel guide] + (https://www.tensorflow.org/guide/saved_model) for more information as well as + "Importing SavedModels from TensorFlow 1.x" in the [`tf.saved_model.load`] + (https://www.tensorflow.org/api_docs/python/tf/saved_model/load) docstring. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :-------------------- | :-------------- | :------------------------- | + | `sess` | Not supported | - | + | `tags` | `tags` | - | + | `export_dir` | `export_dir` | - | + | `import_scope` | Not supported | Name scopes are not needed. + : : : By default, variables are : + : : : associated with the loaded : + : : : object and function names : + : : : are deduped. : + | `saver_kwargs` | Not supported | - | + + #### Before & After Usage Example + + Before: + + ``` + with tf.compat.v1.Session(graph=tf.Graph()) as sess: + tf.compat.v1.saved_model.loader.load(sess, ["foo-tag"], export_dir) + ``` + + After: + + ``` + model = tf.saved_model.load(export_dir, tags=["foo-tag"]) + ``` + @end_compatibility + """ + loader = SavedModelLoader(export_dir) + return loader.load(sess, tags, import_scope, **saver_kwargs) + + +class SavedModelLoader(object): + """Load graphs and restore variable values from a `SavedModel`.""" + + def __init__(self, export_dir): + """Creates a `SavedModelLoader`. + + Args: + export_dir: Directory in which the SavedModel protocol buffer and + variables to be loaded are located. + """ + self._export_dir = export_dir + self._variables_path = path_helpers.get_variables_path(export_dir) + self._saved_model = parse_saved_model(export_dir) + + @property + def export_dir(self): + """Directory containing the SavedModel.""" + return self._export_dir + + @property + def variables_path(self): + """Path to variable checkpoint files.""" + return self._variables_path + + @property + def saved_model(self): + """SavedModel object parsed from the export directory.""" + return self._saved_model + + def get_meta_graph_def_from_tags(self, tags): + """Return MetaGraphDef with the exact specified tags. + + Args: + tags: A list or set of string tags that identify the MetaGraphDef. + + Returns: + MetaGraphDef with the same tags. + + Raises: + RuntimeError: if no metagraphs were found with the associated tags. + """ + found_match = False + meta_graph_def_to_load = None + available_tags = [] + for meta_graph_def in self._saved_model.meta_graphs: + available_tags.append(set(meta_graph_def.meta_info_def.tags)) + if set(meta_graph_def.meta_info_def.tags) == set(tags): + meta_graph_def_to_load = meta_graph_def + found_match = True + break + + if not found_match: + raise RuntimeError( + f"MetaGraphDef associated with tags {str(tags).strip('[]')} " + "could not be found in SavedModel, with available tags " + f"'{available_tags}'. To inspect available tag-sets in" + " the SavedModel, please use the SavedModel CLI: `saved_model_cli`.") + return meta_graph_def_to_load + + def load_graph(self, graph, tags, import_scope=None, **saver_kwargs): + """Load ops and nodes from SavedModel MetaGraph into graph. + + Args: + graph: tf.Graph object. + tags: a set of string tags identifying a MetaGraphDef. + import_scope: Optional `string` -- if specified, prepend this string + followed by '/' to all loaded tensor names. This scope is applied to + tensor instances loaded into the passed session, but it is *not* written + through to the static `MetaGraphDef` protocol buffer that is returned. + **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph. + + Returns: + A tuple of + * Saver defined by the MetaGraph, which can be used to restore the + variable values. + * List of `Operation`/`Tensor` objects returned from + `tf.import_graph_def` (may be `None`). + """ + meta_graph_def = self.get_meta_graph_def_from_tags(tags) + if sys.byteorder == "big": + saved_model_utils.swap_function_tensor_content(meta_graph_def, "little", + "big") + with graph.as_default(): + return tf_saver._import_meta_graph_with_return_elements( # pylint: disable=protected-access + meta_graph_def, import_scope=import_scope, **saver_kwargs) + + def restore_variables(self, sess, saver, import_scope=None): + """Restore SavedModel variable values into the session. + + Args: + sess: tf.compat.v1.Session to restore variable values. + saver: a tf.compat.v1.train.Saver object. Can be None if there are no + variables in graph. This may be the saver returned by the load_graph() + function, or a default `tf.compat.v1.train.Saver()`. + import_scope: Optional `string` -- if specified, prepend this string + followed by '/' to all loaded tensor names. This scope is applied to + tensor instances loaded into the passed session, but it is *not* written + through to the static `MetaGraphDef` protocol buffer that is returned. + + Raises: + ValueError: if no saver was passed to the saver argument, and there are + variables in the graph. + """ + with sess.graph.as_default(): + if (saver is None and + not variables._all_saveable_objects(scope=import_scope)): # pylint: disable=protected-access + tf_logging.info("The specified SavedModel has no variables; no " + "checkpoints were restored.") + elif isinstance(saver, tf_saver.Saver): + saver.restore(sess, self._variables_path) + else: + raise ValueError( + "No tf.train.Saver object was passed to the function " + "`SavedModelLoader.restore_variables`. Since there are variables in" + " the graph, a saver is required.") + + def run_init_ops(self, sess, tags, import_scope=None): + """Run initialization ops defined in the `MetaGraphDef`. + + Args: + sess: tf.compat.v1.Session to restore variable values. + tags: a set of string tags identifying a MetaGraphDef. + import_scope: Optional `string` -- if specified, prepend this string + followed by '/' to all loaded tensor names. This scope is applied to + tensor instances loaded into the passed session, but it is *not* written + through to the static `MetaGraphDef` protocol buffer that is returned. + """ + meta_graph_def = self.get_meta_graph_def_from_tags(tags) + with sess.graph.as_default(): + # Get asset tensors, if any. + asset_tensors_dictionary = get_asset_tensors( + self._export_dir, meta_graph_def, import_scope=import_scope) + + init_op = get_init_op(meta_graph_def, import_scope) + if init_op is not None: + sess.run(fetches=[init_op], feed_dict=asset_tensors_dictionary) + + def load(self, sess, tags, import_scope=None, **saver_kwargs): + """Load the MetaGraphDef graph and restore variable values into the session. + + Args: + sess: tf.compat.v1.Session to restore variable values. + tags: a set of string tags identifying a MetaGraphDef. + import_scope: Optional `string` -- if specified, prepend this string + followed by '/' to all loaded tensor names. This scope is applied to + tensor instances loaded into the passed session, but it is *not* written + through to the static `MetaGraphDef` protocol buffer that is returned. + **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph. + + Returns: + `MetagraphDef` proto of the graph that was loaded. + """ + saved_model_proto = parse_saved_model(self._export_dir) + metrics.IncrementReadApi(_LOADER_LABEL) + + with sess.graph.as_default(): + saver, _ = self.load_graph(sess.graph, tags, import_scope, + **saver_kwargs) + self.restore_variables(sess, saver, import_scope) + self.run_init_ops(sess, tags, import_scope) + meta_graph_def = self.get_meta_graph_def_from_tags(tags) + + if (len(saved_model_proto.meta_graphs) == 1 and + saved_model_proto.meta_graphs[0].HasField("object_graph_def")): + metrics.IncrementRead(write_version="2") + else: + metrics.IncrementRead(write_version="1") + + return meta_graph_def diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op.py new file mode 100644 index 0000000000000000000000000000000000000000..4e3746b86df5feacb1d9ae4bd86d37e66d579566 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op.py @@ -0,0 +1,24 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel main op. + +Builds a main op that defines the sequence of ops to be run as part of the +SavedModel load/restore operations. +""" + +# pylint: disable=unused-import +from tensorflow.python.saved_model.main_op_impl import main_op +from tensorflow.python.saved_model.main_op_impl import main_op_with_restore +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..af5cb2f79ff54a82e4c1201ae69bfb23d8431640 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/main_op_impl.py @@ -0,0 +1,66 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel main op implementation.""" + +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import variables +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +_DEPRECATION_MSG = ( + 'This API was designed for TensorFlow v1. See ' + 'https://www.tensorflow.org/guide/migrate for instructions on how to ' + 'migrate your code to TensorFlow v2.') + + +@tf_export(v1=['saved_model.main_op.main_op']) +@deprecation.deprecated(None, _DEPRECATION_MSG) +def main_op(): + """Returns a main op to init variables and tables. + + Returns the main op including the group of ops that initializes all + variables, initializes local variables and initialize all tables. + + Returns: + The set of ops to be run as part of the main op upon the load operation. + """ + init = variables.global_variables_initializer() + init_local = variables.local_variables_initializer() + init_tables = lookup_ops.tables_initializer() + return control_flow_ops.group(init, init_local, init_tables) + + +# TODO(sukritiramesh): Integrate with Saver for complete restore functionality. +@tf_export(v1=['saved_model.main_op_with_restore', + 'saved_model.main_op.main_op_with_restore']) +@deprecation.deprecated(None, _DEPRECATION_MSG) +def main_op_with_restore(restore_op_name): + """Returns a main op to init variables, tables and restore the graph. + + Returns the main op including the group of ops that initializes all + variables, initialize local variables, initialize all tables and the restore + op name. + + Args: + restore_op_name: Name of the op to use to restore the graph. + + Returns: + The set of ops to be run as part of the main op upon the load operation. + """ + with ops.control_dependencies([main_op()]): + main_op_with_restore = control_flow_ops.group(restore_op_name) + return main_op_with_restore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/method_name_updater.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/method_name_updater.py new file mode 100644 index 0000000000000000000000000000000000000000..3e0bc8ce7d9297efe2755ac448256578315144a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/method_name_updater.py @@ -0,0 +1,143 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SignatureDef method name utility functions. + +Utility functions for manipulating signature_def.method_names. +""" + +from tensorflow.python.lib.io import file_io +from tensorflow.python.platform import tf_logging +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import loader_impl as loader +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + + +# TODO(jdchung): Consider integrated this into the saved_model_cli so that users +# could do this from the command line directly. +@tf_export(v1=["saved_model.signature_def_utils.MethodNameUpdater"]) +class MethodNameUpdater(object): + """Updates the method name(s) of the SavedModel stored in the given path. + + The `MethodNameUpdater` class provides the functionality to update the method + name field in the signature_defs of the given SavedModel. For example, it + can be used to replace the `predict` `method_name` to `regress`. + + Typical usages of the `MethodNameUpdater` + ```python + ... + updater = tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater( + export_dir) + # Update all signature_defs with key "foo" in all meta graph defs. + updater.replace_method_name(signature_key="foo", method_name="regress") + # Update a single signature_def with key "bar" in the meta graph def with + # tags ["serve"] + updater.replace_method_name(signature_key="bar", method_name="classify", + tags="serve") + updater.save(new_export_dir) + ``` + + Note: This function will only be available through the v1 compatibility + library as tf.compat.v1.saved_model.builder.MethodNameUpdater. + """ + + def __init__(self, export_dir): + """Creates an MethodNameUpdater object. + + Args: + export_dir: Directory containing the SavedModel files. + + Raises: + IOError: If the saved model file does not exist, or cannot be successfully + parsed. + """ + self._export_dir = export_dir + self._saved_model = loader.parse_saved_model(export_dir) + + def replace_method_name(self, signature_key, method_name, tags=None): + """Replaces the method_name in the specified signature_def. + + This will match and replace multiple sig defs iff tags is None (i.e when + multiple `MetaGraph`s have a signature_def with the same key). + If tags is not None, this will only replace a single signature_def in the + `MetaGraph` with matching tags. + + Args: + signature_key: Key of the signature_def to be updated. + method_name: new method_name to replace the existing one. + tags: A tag or sequence of tags identifying the `MetaGraph` to update. If + None, all meta graphs will be updated. + Raises: + ValueError: if signature_key or method_name are not defined or + if no metagraphs were found with the associated tags or + if no meta graph has a signature_def that matches signature_key. + """ + if not signature_key: + raise ValueError("`signature_key` must be defined.") + if not method_name: + raise ValueError("`method_name` must be defined.") + + if (tags is not None and not isinstance(tags, list)): + tags = [tags] + found_match = False + for meta_graph_def in self._saved_model.meta_graphs: + if tags is None or set(tags) == set(meta_graph_def.meta_info_def.tags): + if signature_key not in meta_graph_def.signature_def: + raise ValueError( + f"MetaGraphDef associated with tags {tags} " + f"does not have a signature_def with key: '{signature_key}'. " + "This means either you specified the wrong signature key or " + "forgot to put the signature_def with the corresponding key in " + "your SavedModel.") + meta_graph_def.signature_def[signature_key].method_name = method_name + found_match = True + + if not found_match: + raise ValueError( + f"MetaGraphDef associated with tags {tags} could not be found in " + "SavedModel. This means either you specified invalid tags or your " + "SavedModel does not have a MetaGraphDef with the specified tags.") + + def save(self, new_export_dir=None): + """Saves the updated `SavedModel`. + + Args: + new_export_dir: Path where the updated `SavedModel` will be saved. If + None, the input `SavedModel` will be overriden with the updates. + + Raises: + errors.OpError: If there are errors during the file save operation. + """ + + is_input_text_proto = file_io.file_exists( + file_io.join( + compat.as_bytes(self._export_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))) + if not new_export_dir: + new_export_dir = self._export_dir + + if is_input_text_proto: + # TODO(jdchung): Add a util for the path creation below. + path = file_io.join( + compat.as_bytes(new_export_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT)) + file_io.write_string_to_file(path, str(self._saved_model)) + else: + path = file_io.join( + compat.as_bytes(new_export_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB)) + file_io.write_string_to_file( + path, self._saved_model.SerializeToString(deterministic=True)) + tf_logging.info("SavedModel written to: %s", compat.as_text(path)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1138410164b33de6ea2af0476b546f01fa182ea3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Utils for saving a Keras Model or Estimator to the SavedModel format.""" +# pylint: disable=wildcard-import +from tensorflow.python.saved_model.model_utils.export_output import * +from tensorflow.python.saved_model.model_utils.export_utils import build_all_signature_defs +from tensorflow.python.saved_model.model_utils.export_utils import export_outputs_for_mode +from tensorflow.python.saved_model.model_utils.export_utils import EXPORT_TAG_MAP +from tensorflow.python.saved_model.model_utils.export_utils import get_export_outputs +from tensorflow.python.saved_model.model_utils.export_utils import get_temp_export_dir +from tensorflow.python.saved_model.model_utils.export_utils import get_timestamped_export_dir +from tensorflow.python.saved_model.model_utils.export_utils import SIGNATURE_KEY_MAP +# pylint: enable=wildcard-import +# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/__init__.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_output.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_output.py new file mode 100644 index 0000000000000000000000000000000000000000..8962392945eb88fe461834e1372261e23632ccce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_output.py @@ -0,0 +1,425 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Classes for different types of export output.""" + +import abc + + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.saved_model import signature_def_utils + + +class ExportOutput: + """Represents an output of a model that can be served. + + These typically correspond to model heads. + """ + + __metaclass__ = abc.ABCMeta + + _SEPARATOR_CHAR = '/' + + @abc.abstractmethod + def as_signature_def(self, receiver_tensors): + """Generate a SignatureDef proto for inclusion in a MetaGraphDef. + + The SignatureDef will specify outputs as described in this ExportOutput, + and will use the provided receiver_tensors as inputs. + + Args: + receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying + input nodes that will be fed. + """ + pass + + def _check_output_key(self, key, error_label): + # For multi-head models, the key can be a tuple. + if isinstance(key, tuple): + key = self._SEPARATOR_CHAR.join(key) + + if not isinstance(key, str): + raise ValueError( + '{} output key must be a string; got {}.'.format(error_label, key)) + return key + + def _wrap_and_check_outputs( + self, outputs, single_output_default_name, error_label=None): + """Wraps raw tensors as dicts and checks type. + + Note that we create a new dict here so that we can overwrite the keys + if necessary. + + Args: + outputs: A `Tensor` or a dict of string to `Tensor`. + single_output_default_name: A string key for use in the output dict + if the provided `outputs` is a raw tensor. + error_label: descriptive string for use in error messages. If none, + single_output_default_name will be used. + + Returns: + A dict of tensors + + Raises: + ValueError: if the outputs dict keys are not strings or tuples of strings + or the values are not Tensors. + """ + if not isinstance(outputs, dict): + outputs = {single_output_default_name: outputs} + + output_dict = {} + for key, value in outputs.items(): + error_name = error_label or single_output_default_name + key = self._check_output_key(key, error_name) + if not isinstance(value, tensor.Tensor): + raise ValueError( + '{} output value must be a Tensor; got {}.'.format( + error_name, value)) + + output_dict[key] = value + return output_dict + + +class ClassificationOutput(ExportOutput): + """Represents the output of a classification head. + + Either classes or scores or both must be set. + + The classes `Tensor` must provide string labels, not integer class IDs. + + If only classes is set, it is interpreted as providing top-k results in + descending order. + + If only scores is set, it is interpreted as providing a score for every class + in order of class ID. + + If both classes and scores are set, they are interpreted as zipped, so each + score corresponds to the class at the same index. Clients should not depend + on the order of the entries. + """ + + def __init__(self, scores=None, classes=None): + """Constructor for `ClassificationOutput`. + + Args: + scores: A float `Tensor` giving scores (sometimes but not always + interpretable as probabilities) for each class. May be `None`, but + only if `classes` is set. Interpretation varies-- see class doc. + classes: A string `Tensor` giving predicted class labels. May be `None`, + but only if `scores` is set. Interpretation varies-- see class doc. + + Raises: + ValueError: if neither classes nor scores is set, or one of them is not a + `Tensor` with the correct dtype. + """ + if (scores is not None + and not (isinstance(scores, tensor.Tensor) + and scores.dtype.is_floating)): + raise ValueError('Classification scores must be a float32 Tensor; ' + 'got {}'.format(scores)) + if (classes is not None + and not (isinstance(classes, tensor.Tensor) + and dtypes.as_dtype(classes.dtype) == dtypes.string)): + raise ValueError('Classification classes must be a string Tensor; ' + 'got {}'.format(classes)) + if scores is None and classes is None: + raise ValueError('Cannot create a ClassificationOutput with empty ' + 'arguments. At least one of `scores` and `classes` ' + 'must be defined.') + self._scores = scores + self._classes = classes + + @property + def scores(self): + return self._scores + + @property + def classes(self): + return self._classes + + def as_signature_def(self, receiver_tensors): + if len(receiver_tensors) != 1: + raise ValueError( + 'Classification signatures can only accept a single tensor input of ' + 'type tf.string. Please check to make sure that you have structured ' + 'the serving_input_receiver_fn so that it creates a single string ' + 'placeholder. If your model function expects multiple inputs, then ' + 'use `tf.io.parse_example()` to parse the string into multiple ' + f'tensors.\n Received: {receiver_tensors}') + (_, examples), = receiver_tensors.items() + if dtypes.as_dtype(examples.dtype) != dtypes.string: + raise ValueError( + 'Classification signatures can only accept a single tensor input of ' + 'type tf.string. Please check to make sure that you have structured ' + 'the serving_input_receiver_fn so that it creates a single string ' + 'placeholder. If your model function expects multiple inputs, then ' + 'use `tf.io.parse_example()` to parse the string into multiple ' + f'tensors.\n Received: {receiver_tensors}') + return signature_def_utils.classification_signature_def( + examples, self.classes, self.scores) + + +class RegressionOutput(ExportOutput): + """Represents the output of a regression head.""" + + def __init__(self, value): + """Constructor for `RegressionOutput`. + + Args: + value: a float `Tensor` giving the predicted values. Required. + + Raises: + ValueError: if the value is not a `Tensor` with dtype tf.float32. + """ + if not (isinstance(value, tensor.Tensor) and value.dtype.is_floating): + raise ValueError('Regression output value must be a float32 Tensor; ' + 'got {}'.format(value)) + self._value = value + + @property + def value(self): + return self._value + + def as_signature_def(self, receiver_tensors): + if len(receiver_tensors) != 1: + raise ValueError( + 'Regression signatures can only accept a single tensor input of ' + 'type tf.string. Please check to make sure that you have structured ' + 'the serving_input_receiver_fn so that it creates a single string ' + 'placeholder. If your model function expects multiple inputs, then ' + 'use `tf.io.parse_example()` to parse the string into multiple ' + f'tensors.\n Received: {receiver_tensors}') + (_, examples), = receiver_tensors.items() + if dtypes.as_dtype(examples.dtype) != dtypes.string: + raise ValueError( + 'Regression signatures can only accept a single tensor input of ' + 'type tf.string. Please check to make sure that you have structured ' + 'the serving_input_receiver_fn so that it creates a single string ' + 'placeholder. If your model function expects multiple inputs, then ' + 'use `tf.io.parse_example()` to parse the string into multiple ' + f'tensors.\n Received: {receiver_tensors}') + return signature_def_utils.regression_signature_def(examples, self.value) + + +class PredictOutput(ExportOutput): + """Represents the output of a generic prediction head. + + A generic prediction need not be either a classification or a regression. + + Named outputs must be provided as a dict from string to `Tensor`, + """ + _SINGLE_OUTPUT_DEFAULT_NAME = 'output' + + def __init__(self, outputs): + """Constructor for PredictOutput. + + Args: + outputs: A `Tensor` or a dict of string to `Tensor` representing the + predictions. + + Raises: + ValueError: if the outputs is not dict, or any of its keys are not + strings, or any of its values are not `Tensor`s. + """ + + self._outputs = self._wrap_and_check_outputs( + outputs, self._SINGLE_OUTPUT_DEFAULT_NAME, error_label='Prediction') + + @property + def outputs(self): + return self._outputs + + def as_signature_def(self, receiver_tensors): + return signature_def_utils.predict_signature_def(receiver_tensors, + self.outputs) + + +class _SupervisedOutput(ExportOutput): + """Represents the output of a supervised training or eval process.""" + __metaclass__ = abc.ABCMeta + + LOSS_NAME = 'loss' + PREDICTIONS_NAME = 'predictions' + METRICS_NAME = 'metrics' + + METRIC_VALUE_SUFFIX = 'value' + METRIC_UPDATE_SUFFIX = 'update_op' + + _loss = None + _predictions = None + _metrics = None + + def __init__(self, loss=None, predictions=None, metrics=None): + """Constructor for SupervisedOutput (ie, Train or Eval output). + + Args: + loss: dict of Tensors or single Tensor representing calculated loss. + predictions: dict of Tensors or single Tensor representing model + predictions. + metrics: Dict of metric results keyed by name. + The values of the dict can be one of the following: + (1) instance of `Metric` class. + (2) (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op. + + Raises: + ValueError: if any of the outputs' dict keys are not strings or tuples of + strings or the values are not Tensors (or Operations in the case of + update_op). + """ + + if loss is not None: + loss_dict = self._wrap_and_check_outputs(loss, self.LOSS_NAME) + self._loss = self._prefix_output_keys(loss_dict, self.LOSS_NAME) + if predictions is not None: + pred_dict = self._wrap_and_check_outputs( + predictions, self.PREDICTIONS_NAME) + self._predictions = self._prefix_output_keys( + pred_dict, self.PREDICTIONS_NAME) + if metrics is not None: + self._metrics = self._wrap_and_check_metrics(metrics) + + def _prefix_output_keys(self, output_dict, output_name): + """Prepend output_name to the output_dict keys if it doesn't exist. + + This produces predictable prefixes for the pre-determined outputs + of SupervisedOutput. + + Args: + output_dict: dict of string to Tensor, assumed valid. + output_name: prefix string to prepend to existing keys. + + Returns: + dict with updated keys and existing values. + """ + + new_outputs = {} + for key, val in output_dict.items(): + key = self._prefix_key(key, output_name) + new_outputs[key] = val + return new_outputs + + def _prefix_key(self, key, output_name): + if key.find(output_name) != 0: + key = output_name + self._SEPARATOR_CHAR + key + return key + + def _wrap_and_check_metrics(self, metrics): + """Handle the saving of metrics. + + Metrics is either a tuple of (value, update_op), or a dict of such tuples. + Here, we separate out the tuples and create a dict with names to tensors. + + Args: + metrics: Dict of metric results keyed by name. + The values of the dict can be one of the following: + (1) instance of `Metric` class. + (2) (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op. + + Returns: + dict of output_names to tensors + + Raises: + ValueError: if the dict key is not a string, or the metric values or ops + are not tensors. + """ + if not isinstance(metrics, dict): + metrics = {self.METRICS_NAME: metrics} + + outputs = {} + for key, value in metrics.items(): + if isinstance(value, tuple): + metric_val, metric_op = value + else: # value is a keras.Metrics object + metric_val = value.result() + assert len(value.updates) == 1 # We expect only one update op. + metric_op = value.updates[0] + key = self._check_output_key(key, self.METRICS_NAME) + key = self._prefix_key(key, self.METRICS_NAME) + + val_name = key + self._SEPARATOR_CHAR + self.METRIC_VALUE_SUFFIX + op_name = key + self._SEPARATOR_CHAR + self.METRIC_UPDATE_SUFFIX + if not isinstance(metric_val, tensor.Tensor): + raise ValueError( + '{} output value must be a Tensor; got {}.'.format( + key, metric_val)) + if not (tensor_util.is_tf_type(metric_op) or + isinstance(metric_op, ops.Operation)): + raise ValueError( + '{} update_op must be a Tensor or Operation; got {}.'.format( + key, metric_op)) + + # We must wrap any ops (or variables) in a Tensor before export, as the + # SignatureDef proto expects tensors only. See b/109740581 + metric_op_tensor = metric_op + if not isinstance(metric_op, tensor.Tensor): + with ops.control_dependencies([metric_op]): + metric_op_tensor = constant_op.constant([], name='metric_op_wrapper') + + outputs[val_name] = metric_val + outputs[op_name] = metric_op_tensor + + return outputs + + @property + def loss(self): + return self._loss + + @property + def predictions(self): + return self._predictions + + @property + def metrics(self): + return self._metrics + + @abc.abstractmethod + def _get_signature_def_fn(self): + """Returns a function that produces a SignatureDef given desired outputs.""" + pass + + def as_signature_def(self, receiver_tensors): + signature_def_fn = self._get_signature_def_fn() + return signature_def_fn( + receiver_tensors, self.loss, self.predictions, self.metrics) + + +class TrainOutput(_SupervisedOutput): + """Represents the output of a supervised training process. + + This class generates the appropriate signature def for exporting + training output by type-checking and wrapping loss, predictions, and metrics + values. + """ + + def _get_signature_def_fn(self): + return signature_def_utils.supervised_train_signature_def + + +class EvalOutput(_SupervisedOutput): + """Represents the output of a supervised eval process. + + This class generates the appropriate signature def for exporting + eval output by type-checking and wrapping loss, predictions, and metrics + values. + """ + + def _get_signature_def_fn(self): + return signature_def_utils.supervised_eval_signature_def diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..06f8fa7890bc31d7f92aeb2aebaf3cc0f6adc350 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/export_utils.py @@ -0,0 +1,411 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for creating SavedModels.""" + +import collections +import os +import time + +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import op_selector +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.saved_model import utils +from tensorflow.python.saved_model.model_utils import export_output as export_output_lib +from tensorflow.python.saved_model.model_utils import mode_keys +from tensorflow.python.saved_model.model_utils.mode_keys import KerasModeKeys as ModeKeys +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity + + +# Mapping of the modes to appropriate MetaGraph tags in the SavedModel. +EXPORT_TAG_MAP = mode_keys.ModeKeyMap(**{ + ModeKeys.PREDICT: [tag_constants.SERVING], + ModeKeys.TRAIN: [tag_constants.TRAINING], + ModeKeys.TEST: [tag_constants.EVAL]}) + +# For every exported mode, a SignatureDef map should be created using the +# functions `export_outputs_for_mode` and `build_all_signature_defs`. By +# default, this map will contain a single Signature that defines the input +# tensors and output predictions, losses, and/or metrics (depending on the mode) +# The default keys used in the SignatureDef map are defined below. +SIGNATURE_KEY_MAP = mode_keys.ModeKeyMap(**{ + ModeKeys.PREDICT: signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, + ModeKeys.TRAIN: signature_constants.DEFAULT_TRAIN_SIGNATURE_DEF_KEY, + ModeKeys.TEST: signature_constants.DEFAULT_EVAL_SIGNATURE_DEF_KEY}) + +# Default names used in the SignatureDef input map, which maps strings to +# TensorInfo protos. +SINGLE_FEATURE_DEFAULT_NAME = 'feature' +SINGLE_RECEIVER_DEFAULT_NAME = 'input' +SINGLE_LABEL_DEFAULT_NAME = 'label' + +### Below utilities are specific to SavedModel exports. + + +def _must_be_fed(op): + return op.type == 'Placeholder' + + +def _ensure_servable(input_tensors, names_to_output_tensor_infos): + """Check that the signature outputs don't depend on unreachable placeholders. + + Args: + input_tensors: An iterable of `Tensor`s specified as the signature's inputs. + names_to_output_tensor_infos: An mapping from output names to respective + `TensorInfo`s corresponding to the signature's output tensors. + + Raises: + ValueError: If any of the signature's outputs depend on placeholders not + provided as signature's inputs. + """ + plain_input_tensors = nest.flatten(input_tensors, expand_composites=True) + + graph = op_selector.get_unique_graph(plain_input_tensors) + + output_tensors = [ + utils.get_tensor_from_tensor_info(tensor, graph=graph) + for tensor in names_to_output_tensor_infos.values() + ] + plain_output_tensors = nest.flatten(output_tensors, expand_composites=True) + + dependency_ops = op_selector.get_backward_walk_ops( + plain_output_tensors, stop_at_ts=plain_input_tensors) + + fed_tensors = object_identity.ObjectIdentitySet(plain_input_tensors) + for dependency_op in dependency_ops: + if _must_be_fed(dependency_op) and (not all( + output in fed_tensors for output in dependency_op.outputs)): + input_tensor_names = [tensor.name for tensor in plain_input_tensors] + output_tensor_keys = list(names_to_output_tensor_infos.keys()) + output_tensor_names = [tensor.name for tensor in plain_output_tensors] + dependency_path = op_selector.show_path(dependency_op, + plain_output_tensors, + plain_input_tensors) + raise ValueError( + f'The signature\'s input tensors {input_tensor_names} are ' + f'insufficient to compute its output keys {output_tensor_keys} ' + f'(respectively, tensors {output_tensor_names}) because of the ' + f'dependency on `{dependency_op.name}` which is not given as ' + 'a signature input, as illustrated by the following dependency path: ' + f'{dependency_path}') + + +def build_all_signature_defs(receiver_tensors, + export_outputs, + receiver_tensors_alternatives=None, + serving_only=True): + """Build `SignatureDef`s for all export outputs. + + Args: + receiver_tensors: a `Tensor`, or a dict of string to `Tensor`, specifying + input nodes where this receiver expects to be fed by default. Typically, + this is a single placeholder expecting serialized `tf.Example` protos. + export_outputs: a dict of ExportOutput instances, each of which has + an as_signature_def instance method that will be called to retrieve + the signature_def for all export output tensors. + receiver_tensors_alternatives: a dict of string to additional + groups of receiver tensors, each of which may be a `Tensor` or a dict of + string to `Tensor`. These named receiver tensor alternatives generate + additional serving signatures, which may be used to feed inputs at + different points within the input receiver subgraph. A typical usage is + to allow feeding raw feature `Tensor`s *downstream* of the + tf.io.parse_example() op. Defaults to None. + serving_only: boolean; if true, resulting signature defs will only include + valid serving signatures. If false, all requested signatures will be + returned. + + Returns: + signature_def representing all passed args. + + Raises: + ValueError: if export_outputs is not a dict + """ + if not isinstance(receiver_tensors, dict): + receiver_tensors = {SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors} + if export_outputs is None or not isinstance(export_outputs, dict): + raise ValueError('`export_outputs` must be a dict. Received ' + f'{export_outputs} with type ' + f'{type(export_outputs).__name__}.') + + signature_def_map = {} + excluded_signatures = {} + input_tensors = receiver_tensors.values() + for output_key, export_output in export_outputs.items(): + signature_name = '{}'.format(output_key or 'None') + try: + signature = export_output.as_signature_def(receiver_tensors) + _ensure_servable(input_tensors, signature.outputs) + signature_def_map[signature_name] = signature + except ValueError as e: + excluded_signatures[signature_name] = str(e) + + if receiver_tensors_alternatives: + for receiver_name, receiver_tensors_alt in ( + receiver_tensors_alternatives.items()): + if not isinstance(receiver_tensors_alt, dict): + receiver_tensors_alt = { + SINGLE_RECEIVER_DEFAULT_NAME: receiver_tensors_alt + } + alt_input_tensors = receiver_tensors_alt.values() + for output_key, export_output in export_outputs.items(): + signature_name = '{}:{}'.format(receiver_name or 'None', output_key or + 'None') + try: + signature = export_output.as_signature_def(receiver_tensors_alt) + _ensure_servable(alt_input_tensors, signature.outputs) + signature_def_map[signature_name] = signature + except ValueError as e: + excluded_signatures[signature_name] = str(e) + + _log_signature_report(signature_def_map, excluded_signatures) + + # The above calls to export_output_lib.as_signature_def should return only + # valid signatures; if there is a validity problem, they raise a ValueError, + # in which case we exclude that signature from signature_def_map above. + # The is_valid_signature check ensures that the signatures produced are + # valid for serving, and acts as an additional sanity check for export + # signatures produced for serving. We skip this check for training and eval + # signatures, which are not intended for serving. + if serving_only: + signature_def_map = { + k: v + for k, v in signature_def_map.items() + if signature_def_utils.is_valid_signature(v) + } + return signature_def_map + + +_FRIENDLY_METHOD_NAMES = { + signature_constants.CLASSIFY_METHOD_NAME: 'Classify', + signature_constants.REGRESS_METHOD_NAME: 'Regress', + signature_constants.PREDICT_METHOD_NAME: 'Predict', + signature_constants.SUPERVISED_TRAIN_METHOD_NAME: 'Train', + signature_constants.SUPERVISED_EVAL_METHOD_NAME: 'Eval', +} + + +def _log_signature_report(signature_def_map, excluded_signatures): + """Log a report of which signatures were produced.""" + sig_names_by_method_name = collections.defaultdict(list) + + # We'll collect whatever method_names are present, but also we want to make + # sure to output a line for each of the three standard methods even if they + # have no signatures. + for method_name in _FRIENDLY_METHOD_NAMES: + sig_names_by_method_name[method_name] = [] + + for signature_name, sig in signature_def_map.items(): + sig_names_by_method_name[sig.method_name].append(signature_name) + + # TODO(b/67733540): consider printing the full signatures, not just names + for method_name, sig_names in sig_names_by_method_name.items(): + if method_name in _FRIENDLY_METHOD_NAMES: + method_name = _FRIENDLY_METHOD_NAMES[method_name] + logging.info('Signatures INCLUDED in export for {}: {}'.format( + method_name, sig_names if sig_names else 'None')) + + if excluded_signatures: + logging.info('Signatures EXCLUDED from export because they cannot be ' + 'be served via TensorFlow Serving APIs:') + for signature_name, message in excluded_signatures.items(): + logging.info('\'{}\' : {}'.format(signature_name, message)) + + if not signature_def_map: + logging.warn('Export includes no signatures!') + elif (signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY not in + signature_def_map): + logging.warn('Export includes no default signature!') + + +# When we create a timestamped directory, there is a small chance that the +# directory already exists because another process is also creating these +# directories. In this case we just wait one second to get a new timestamp and +# try again. If this fails several times in a row, then something is seriously +# wrong. +MAX_DIRECTORY_CREATION_ATTEMPTS = 10 + + +def get_timestamped_export_dir(export_dir_base): + """Builds a path to a new subdirectory within the base directory. + + Each export is written into a new subdirectory named using the + current time. This guarantees monotonically increasing version + numbers even across multiple runs of the pipeline. + The timestamp used is the number of seconds since epoch UTC. + + Args: + export_dir_base: A string containing a directory to write the exported + graph and checkpoints. + Returns: + The full path of the new subdirectory (which is not actually created yet). + + Raises: + RuntimeError: if repeated attempts fail to obtain a unique timestamped + directory name. + """ + attempts = 0 + while attempts < MAX_DIRECTORY_CREATION_ATTEMPTS: + timestamp = int(time.time()) + + result_dir = file_io.join( + compat.as_bytes(export_dir_base), compat.as_bytes(str(timestamp))) + if not gfile.Exists(result_dir): + # Collisions are still possible (though extremely unlikely): this + # directory is not actually created yet, but it will be almost + # instantly on return from this function. + return result_dir + time.sleep(1) + attempts += 1 + logging.warn('Directory {} already exists; retrying (attempt {}/{})'.format( + compat.as_str(result_dir), attempts, MAX_DIRECTORY_CREATION_ATTEMPTS)) + raise RuntimeError('Failed to obtain a unique export directory name after ' + f'{MAX_DIRECTORY_CREATION_ATTEMPTS} attempts.') + + +def get_temp_export_dir(timestamped_export_dir): + """Builds a directory name based on the argument but starting with 'temp-'. + + This relies on the fact that TensorFlow Serving ignores subdirectories of + the base directory that can't be parsed as integers. + + Args: + timestamped_export_dir: the name of the eventual export directory, e.g. + /foo/bar/ + + Returns: + A sister directory prefixed with 'temp-', e.g. /foo/bar/temp-. + """ + (dirname, basename) = os.path.split(timestamped_export_dir) + if isinstance(basename, bytes): + str_name = basename.decode('utf-8') + else: + str_name = str(basename) + temp_export_dir = file_io.join( + compat.as_bytes(dirname), compat.as_bytes('temp-{}'.format(str_name))) + return temp_export_dir + + +def export_outputs_for_mode( + mode, serving_export_outputs=None, predictions=None, loss=None, + metrics=None): + """Util function for constructing a `ExportOutput` dict given a mode. + + The returned dict can be directly passed to `build_all_signature_defs` helper + function as the `export_outputs` argument, used for generating a SignatureDef + map. + + Args: + mode: A `ModeKeys` specifying the mode. + serving_export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict or None. + predictions: A dict of Tensors or single Tensor representing model + predictions. This argument is only used if serving_export_outputs is not + set. + loss: A dict of Tensors or single Tensor representing calculated loss. + metrics: A dict of (metric_value, update_op) tuples, or a single tuple. + metric_value must be a Tensor, and update_op must be a Tensor or Op + + Returns: + Dictionary mapping the a key to an `tf.estimator.export.ExportOutput` object + The key is the expected SignatureDef key for the mode. + + Raises: + ValueError: if an appropriate ExportOutput cannot be found for the mode. + """ + if mode not in SIGNATURE_KEY_MAP: + raise ValueError( + f'Export output type not found for `mode`: {mode}. Expected one of: ' + f'{list(SIGNATURE_KEY_MAP.keys())}.\n' + 'One likely error is that V1 Estimator Modekeys were somehow passed to ' + 'this function. Please ensure that you are using the new ModeKeys.') + signature_key = SIGNATURE_KEY_MAP[mode] + if mode_keys.is_predict(mode): + return get_export_outputs(serving_export_outputs, predictions) + elif mode_keys.is_train(mode): + return {signature_key: export_output_lib.TrainOutput( + loss=loss, predictions=predictions, metrics=metrics)} + else: + return {signature_key: export_output_lib.EvalOutput( + loss=loss, predictions=predictions, metrics=metrics)} + + +def get_export_outputs(export_outputs, predictions): + """Validate export_outputs or create default export_outputs. + + Args: + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict or None. + predictions: Predictions `Tensor` or dict of `Tensor`. + + Returns: + Valid export_outputs dict + + Raises: + TypeError: if export_outputs is not a dict or its values are not + ExportOutput instances. + """ + if export_outputs is None: + default_output = export_output_lib.PredictOutput(predictions) + export_outputs = { + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: default_output} + + if not isinstance(export_outputs, dict): + raise TypeError( + f'`export_outputs` must be dict, received: {export_outputs}.') + for v in export_outputs.values(): + if not isinstance(v, export_output_lib.ExportOutput): + raise TypeError( + 'Values in `export_outputs` must be ExportOutput objects, ' + f'received: {export_outputs}.') + + _maybe_add_default_serving_output(export_outputs) + + return export_outputs + + +def _maybe_add_default_serving_output(export_outputs): + """Add a default serving output to the export_outputs if not present. + + Args: + export_outputs: Describes the output signatures to be exported to + `SavedModel` and used during serving. Should be a dict. + + Returns: + export_outputs dict with default serving signature added if necessary + + Raises: + ValueError: if multiple export_outputs were provided without a default + serving key. + """ + if len(export_outputs) == 1: + (key, value), = export_outputs.items() + if key != signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: + export_outputs[ + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = value + if len(export_outputs) > 1: + if (signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + not in export_outputs): + raise ValueError( + 'Multiple `export_outputs` were provided, but none of them are ' + 'specified as the default. Use' + '`tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY` to ' + 'specify a default.') + + return export_outputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/mode_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/mode_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..ac330d7cc60261e81ebbdf83b9d9282b841f6dd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/model_utils/mode_keys.py @@ -0,0 +1,107 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +# LINT.IfChange +"""Utils for managing different mode strings used by Keras and Estimator models. +""" + +from tensorflow.python.util.compat import collections_abc + + +class KerasModeKeys(object): + """Standard names for model modes. + + The following standard keys are defined: + + * `TRAIN`: training/fitting mode. + * `TEST`: testing/evaluation mode. + * `PREDICT`: prediction/inference mode. + """ + + TRAIN = 'train' + TEST = 'test' + PREDICT = 'predict' + + +# TODO(kathywu): Remove copy in Estimator after nightlies +class EstimatorModeKeys(object): + """Standard names for Estimator model modes. + + The following standard keys are defined: + + * `TRAIN`: training/fitting mode. + * `EVAL`: testing/evaluation mode. + * `PREDICT`: predication/inference mode. + """ + + TRAIN = 'train' + EVAL = 'eval' + PREDICT = 'infer' + + +def is_predict(mode): + return mode in [KerasModeKeys.PREDICT, EstimatorModeKeys.PREDICT] + + +def is_eval(mode): + return mode in [KerasModeKeys.TEST, EstimatorModeKeys.EVAL] + + +def is_train(mode): + return mode in [KerasModeKeys.TRAIN, EstimatorModeKeys.TRAIN] + + +class ModeKeyMap(collections_abc.Mapping): + """Map using ModeKeys as keys. + + This class creates an immutable mapping from modes to values. For example, + SavedModel export of Keras and Estimator models use this to map modes to their + corresponding MetaGraph tags/SignatureDef keys. + + Since this class uses modes, rather than strings, as keys, both "predict" + (Keras's PREDICT ModeKey) and "infer" (Estimator's PREDICT ModeKey) map to the + same value. + """ + + def __init__(self, **kwargs): + self._internal_dict = {} + self._keys = [] + for key in kwargs: + self._keys.append(key) + dict_key = self._get_internal_key(key) + if dict_key in self._internal_dict: + raise ValueError( + 'Error creating ModeKeyMap. Multiple keys/values found for {} mode.' + .format(dict_key)) + self._internal_dict[dict_key] = kwargs[key] + + def _get_internal_key(self, key): + """Return keys used for the internal dictionary.""" + if is_train(key): + return KerasModeKeys.TRAIN + if is_eval(key): + return KerasModeKeys.TEST + if is_predict(key): + return KerasModeKeys.PREDICT + raise ValueError('Invalid mode key: {}.'.format(key)) + + def __getitem__(self, key): + return self._internal_dict[self._get_internal_key(key)] + + def __iter__(self): + return iter(self._keys) + + def __len__(self): + return len(self._keys) +# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/mode_keys.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/nested_structure_coder.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/nested_structure_coder.py new file mode 100644 index 0000000000000000000000000000000000000000..bce787087a978f3b257a9ceeaed8ee50c52d5b50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/nested_structure_coder.py @@ -0,0 +1,514 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module that encodes (decodes) nested structures into (from) protos. + +The intended use is to serialize everything needed to restore a `Function` that +was saved into a SavedModel. This may include concrete function inputs and +outputs, signatures, function specs, etc. + +Example use: +# Encode into proto. +signature_proto = nested_structure_coder.encode_structure( + function.input_signature) +# Decode into a Python object. +restored_signature = nested_structure_coder.decode_proto(signature_proto) +""" + +import collections +import functools +import warnings + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.types import internal +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +class NotEncodableError(Exception): + """Error raised when a coder cannot encode an object.""" + + +def register_codec(x): + """Registers a codec to use for encoding/decoding. + + Args: + x: The codec object to register. The object must implement can_encode, + do_encode, can_decode, and do_decode. See the various _*Codec classes for + examples. + """ + _codecs.append(x) + + +def _get_encoders(): + return [(c.can_encode, c.do_encode) for c in _codecs] + + +def _get_decoders(): + return [(c.can_decode, c.do_decode) for c in _codecs] + + +def _map_structure(pyobj, coders): + # Iterate through the codecs in the reverse order they were registered in, + # as the most specific codec should be checked first. + for can, do in reversed(coders): + if can(pyobj): + recursion_fn = functools.partial(_map_structure, coders=coders) + return do(pyobj, recursion_fn) + raise NotEncodableError( + f"No encoder for object {str(pyobj)} of type {type(pyobj)}.") + + +@tf_export("__internal__.saved_model.encode_structure", v1=[]) +def encode_structure(nested_structure): + """Encodes nested structures composed of encodable types into a proto. + + Args: + nested_structure: Structure to encode. + + Returns: + Encoded proto. + + Raises: + NotEncodableError: For values for which there are no encoders. + """ + return _map_structure(nested_structure, _get_encoders()) + + +def can_encode(nested_structure): + """Determines whether a nested structure can be encoded into a proto. + + Args: + nested_structure: Structure to encode. + + Returns: + True if the nested structured can be encoded. + """ + try: + encode_structure(nested_structure) + except NotEncodableError: + return False + return True + + +@tf_export("__internal__.saved_model.decode_proto", v1=[]) +def decode_proto(proto): + """Decodes proto representing a nested structure. + + Args: + proto: Proto to decode. + + Returns: + Decoded structure. + + Raises: + NotEncodableError: For values for which there are no encoders. + """ + return _map_structure(proto, _get_decoders()) + + +class _ListCodec: + """Codec for lists.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, list) + + def do_encode(self, list_value, encode_fn): + encoded_list = struct_pb2.StructuredValue() + encoded_list.list_value.CopyFrom(struct_pb2.ListValue()) + for element in list_value: + encoded_list.list_value.values.add().CopyFrom(encode_fn(element)) + return encoded_list + + def can_decode(self, value): + return value.HasField("list_value") + + def do_decode(self, value, decode_fn): + return [decode_fn(element) for element in value.list_value.values] + + +def _is_tuple(obj): + return not _is_named_tuple(obj) and isinstance(obj, tuple) + + +def _is_named_tuple(instance): + """Returns True iff `instance` is a `namedtuple`. + + Args: + instance: An instance of a Python object. + + Returns: + True if `instance` is a `namedtuple`. + """ + if not isinstance(instance, tuple): + return False + return (hasattr(instance, "_fields") and + isinstance(instance._fields, collections_abc.Sequence) and + all(isinstance(f, str) for f in instance._fields)) + + +class _TupleCodec: + """Codec for tuples.""" + + def can_encode(self, pyobj): + return _is_tuple(pyobj) + + def do_encode(self, tuple_value, encode_fn): + encoded_tuple = struct_pb2.StructuredValue() + encoded_tuple.tuple_value.CopyFrom(struct_pb2.TupleValue()) + for element in tuple_value: + encoded_tuple.tuple_value.values.add().CopyFrom(encode_fn(element)) + return encoded_tuple + + def can_decode(self, value): + return value.HasField("tuple_value") + + def do_decode(self, value, decode_fn): + return tuple(decode_fn(element) for element in value.tuple_value.values) + + +class _DictCodec: + """Codec for dicts.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, dict) + + def do_encode(self, dict_value, encode_fn): + encoded_dict = struct_pb2.StructuredValue() + encoded_dict.dict_value.CopyFrom(struct_pb2.DictValue()) + for key, value in dict_value.items(): + encoded_dict.dict_value.fields[key].CopyFrom(encode_fn(value)) + return encoded_dict + + def can_decode(self, value): + return value.HasField("dict_value") + + def do_decode(self, value, decode_fn): + return {key: decode_fn(val) for key, val in value.dict_value.fields.items()} + + +class _NamedTupleCodec: + """Codec for namedtuples. + + Encoding and decoding a namedtuple reconstructs a namedtuple with a different + actual Python type, but with the same `typename` and `fields`. + """ + + def can_encode(self, pyobj): + return _is_named_tuple(pyobj) + + def do_encode(self, named_tuple_value, encode_fn): + encoded_named_tuple = struct_pb2.StructuredValue() + encoded_named_tuple.named_tuple_value.CopyFrom(struct_pb2.NamedTupleValue()) + encoded_named_tuple.named_tuple_value.name = \ + named_tuple_value.__class__.__name__ + for key in named_tuple_value._fields: + pair = encoded_named_tuple.named_tuple_value.values.add() + pair.key = key + pair.value.CopyFrom(encode_fn(named_tuple_value._asdict()[key])) + return encoded_named_tuple + + def can_decode(self, value): + return value.HasField("named_tuple_value") + + def do_decode(self, value, decode_fn): + key_value_pairs = value.named_tuple_value.values + items = [(pair.key, decode_fn(pair.value)) for pair in key_value_pairs] + named_tuple_type = collections.namedtuple(value.named_tuple_value.name, + [item[0] for item in items]) + return named_tuple_type(**dict(items)) + + +class _Float64Codec: + """Codec for floats.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, float) + + def do_encode(self, float64_value, encode_fn): + del encode_fn + value = struct_pb2.StructuredValue() + value.float64_value = float64_value + return value + + def can_decode(self, value): + return value.HasField("float64_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return value.float64_value + + +class _Int64Codec: + """Codec for Python integers (limited to 64 bit values).""" + + def can_encode(self, pyobj): + return not isinstance(pyobj, bool) and isinstance(pyobj, int) + + def do_encode(self, int_value, encode_fn): + del encode_fn + value = struct_pb2.StructuredValue() + value.int64_value = int_value + return value + + def can_decode(self, value): + return value.HasField("int64_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return int(value.int64_value) + + +class _StringCodec: + """Codec for strings. + + See StructuredValue.string_value in proto/struct.proto for more detailed + explanation. + """ + + def can_encode(self, pyobj): + return isinstance(pyobj, str) + + def do_encode(self, string_value, encode_fn): + del encode_fn + value = struct_pb2.StructuredValue() + value.string_value = string_value + return value + + def can_decode(self, value): + return value.HasField("string_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return compat.as_str(value.string_value) + + +class _NoneCodec: + """Codec for None.""" + + def can_encode(self, pyobj): + return pyobj is None + + def do_encode(self, none_value, encode_fn): + del encode_fn, none_value + value = struct_pb2.StructuredValue() + value.none_value.CopyFrom(struct_pb2.NoneValue()) + return value + + def can_decode(self, value): + return value.HasField("none_value") + + def do_decode(self, value, decode_fn): + del decode_fn, value + return None + + +class _BoolCodec: + """Codec for booleans.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, bool) + + def do_encode(self, bool_value, encode_fn): + del encode_fn + value = struct_pb2.StructuredValue() + value.bool_value = bool_value + return value + + def can_decode(self, value): + return value.HasField("bool_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return value.bool_value + + +class _TensorTypeCodec: + """Codec for `TensorType`.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, dtypes.DType) + + def do_encode(self, tensor_dtype_value, encode_fn): + del encode_fn + encoded_tensor_type = struct_pb2.StructuredValue() + encoded_tensor_type.tensor_dtype_value = tensor_dtype_value.as_datatype_enum + return encoded_tensor_type + + def can_decode(self, value): + return value.HasField("tensor_dtype_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return dtypes.DType(value.tensor_dtype_value) + + +class BuiltInTypeSpecCodec: + """Codec for built-in `TypeSpec` classes. + + Built-in TypeSpec's that do not require a custom codec implementation + register themselves by instantiating this class and passing it to + register_codec. + + Attributes: + type_spec_class: The built-in TypeSpec class that the + codec is instantiated for. + type_spec_proto_enum: The proto enum value for the built-in TypeSpec class. + """ + + _BUILT_IN_TYPE_SPEC_PROTOS = [] + _BUILT_IN_TYPE_SPECS = [] + + def __init__(self, type_spec_class, type_spec_proto_enum): + if not issubclass(type_spec_class, internal.TypeSpec): + raise ValueError( + f"The type '{type_spec_class}' does not subclass tf.TypeSpec.") + + if type_spec_class in self._BUILT_IN_TYPE_SPECS: + raise ValueError( + f"The type '{type_spec_class}' already has an instantiated codec.") + + if type_spec_proto_enum in self._BUILT_IN_TYPE_SPEC_PROTOS: + raise ValueError( + f"The proto value '{type_spec_proto_enum}' is already registered." + ) + + if (not isinstance(type_spec_proto_enum, int) + or type_spec_proto_enum <= 0 + or type_spec_proto_enum > 10): + raise ValueError(f"The proto value '{type_spec_proto_enum}' is invalid.") + + self.type_spec_class = type_spec_class + self.type_spec_proto_enum = type_spec_proto_enum + + self._BUILT_IN_TYPE_SPECS.append(type_spec_class) + self._BUILT_IN_TYPE_SPEC_PROTOS.append(type_spec_proto_enum) + + def can_encode(self, pyobj): + """Returns true if `pyobj` can be encoded as the built-in TypeSpec.""" + return isinstance(pyobj, self.type_spec_class) + + def do_encode(self, type_spec_value, encode_fn): + """Returns an encoded proto for the given built-in TypeSpec.""" + type_state = type_spec_value._serialize() # pylint: disable=protected-access + num_flat_components = len(nest.flatten( + type_spec_value._component_specs, expand_composites=True)) # pylint: disable=protected-access + encoded_type_spec = struct_pb2.StructuredValue() + encoded_type_spec.type_spec_value.CopyFrom( + struct_pb2.TypeSpecProto( + type_spec_class=self.type_spec_proto_enum, + type_state=encode_fn(type_state), + type_spec_class_name=self.type_spec_class.__name__, + num_flat_components=num_flat_components)) + return encoded_type_spec + + def can_decode(self, value): + """Returns true if `value` can be decoded into its built-in TypeSpec.""" + if value.HasField("type_spec_value"): + type_spec_class_enum = value.type_spec_value.type_spec_class + return type_spec_class_enum == self.type_spec_proto_enum + return False + + def do_decode(self, value, decode_fn): + """Returns the built in `TypeSpec` encoded by the proto `value`.""" + type_spec_proto = value.type_spec_value + # pylint: disable=protected-access + return self.type_spec_class._deserialize( + decode_fn(type_spec_proto.type_state) + ) + + +# TODO(b/238903802): Use TraceType serialization and specific protos. +class _TypeSpecCodec: + """Codec for `tf.TypeSpec`.""" + + def can_encode(self, pyobj): + """Returns true if `pyobj` can be encoded as a TypeSpec.""" + # Check if it's a registered type. + if isinstance(pyobj, internal.TypeSpec): + try: + type_spec_registry.get_name(type(pyobj)) + return True + except ValueError: + return False + + return False + + def do_encode(self, type_spec_value, encode_fn): + """Returns an encoded proto for the given `tf.TypeSpec`.""" + type_spec_class_name = type_spec_registry.get_name(type(type_spec_value)) + type_spec_class = struct_pb2.TypeSpecProto.REGISTERED_TYPE_SPEC + # Support for saving registered TypeSpecs is currently experimental. + # Issue a warning to indicate the limitations. + warnings.warn("Encoding a StructuredValue with type %s; loading this " + "StructuredValue will require that this type be " + "imported and registered." % type_spec_class_name) + + type_state = type_spec_value._serialize() # pylint: disable=protected-access + num_flat_components = len( + nest.flatten(type_spec_value._component_specs, expand_composites=True)) # pylint: disable=protected-access + encoded_type_spec = struct_pb2.StructuredValue() + encoded_type_spec.type_spec_value.CopyFrom( + struct_pb2.TypeSpecProto( + type_spec_class=type_spec_class, + type_state=encode_fn(type_state), + type_spec_class_name=type_spec_class_name, + num_flat_components=num_flat_components)) + return encoded_type_spec + + def can_decode(self, value): + """Returns true if `value` can be decoded into a `tf.TypeSpec`.""" + return value.HasField("type_spec_value") + + def do_decode(self, value, decode_fn): + """Returns the `tf.TypeSpec` encoded by the proto `value`.""" + type_spec_proto = value.type_spec_value + type_spec_class_enum = type_spec_proto.type_spec_class + class_name = type_spec_proto.type_spec_class_name + + if type_spec_class_enum == struct_pb2.TypeSpecProto.REGISTERED_TYPE_SPEC: + try: + type_spec_class = type_spec_registry.lookup(class_name) + except ValueError as e: + raise ValueError( + f"The type '{class_name}' has not been registered. It must be " + "registered before you load this object (typically by importing " + "its module).") from e + else: + raise ValueError( + f"The type '{class_name}' is not supported by this version of " + "TensorFlow. (The object you are loading must have been created " + "with a newer version of TensorFlow.)") + + # pylint: disable=protected-access + return type_spec_class._deserialize(decode_fn(type_spec_proto.type_state)) + + +_codecs = [ + _ListCodec(), + _TupleCodec(), + _NamedTupleCodec(), + _StringCodec(), + _Float64Codec(), + _NoneCodec(), + _Int64Codec(), + _BoolCodec(), + _DictCodec(), + _TypeSpecCodec(), + _TensorTypeCodec(), +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/path_helpers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/path_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfc356c71f031ab91eb69b8862f4e80f2de5830 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/path_helpers.py @@ -0,0 +1,82 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Path helpers utility functions.""" + +from tensorflow.python.lib.io import file_io +from tensorflow.python.saved_model import constants +from tensorflow.python.util import compat + + +def get_or_create_variables_dir(export_dir): + """Return variables sub-directory, or create one if it doesn't exist.""" + variables_dir = get_variables_dir(export_dir) + file_io.recursive_create_dir(variables_dir) + return variables_dir + + +def get_variables_dir(export_dir): + """Return variables sub-directory in the SavedModel.""" + return file_io.join( + compat.as_text(export_dir), compat.as_text(constants.VARIABLES_DIRECTORY)) + + +def get_variables_path(export_dir): + """Return the variables path, used as the prefix for checkpoint files.""" + return file_io.join( + compat.as_text(get_variables_dir(export_dir)), + compat.as_text(constants.VARIABLES_FILENAME)) + + +def get_or_create_assets_dir(export_dir): + """Return assets sub-directory, or create one if it doesn't exist.""" + assets_destination_dir = get_assets_dir(export_dir) + + file_io.recursive_create_dir(assets_destination_dir) + + return assets_destination_dir + + +def get_assets_dir(export_dir): + """Return path to asset directory in the SavedModel.""" + return file_io.join( + compat.as_text(export_dir), compat.as_text(constants.ASSETS_DIRECTORY)) + + +def get_or_create_debug_dir(export_dir): + """Returns path to the debug sub-directory, creating if it does not exist.""" + debug_dir = get_debug_dir(export_dir) + + file_io.recursive_create_dir(debug_dir) + + return debug_dir + + +def get_saved_model_pbtxt_path(export_dir): + return file_io.join( + compat.as_bytes(compat.path_to_str(export_dir)), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT)) + + +def get_saved_model_pb_path(export_dir): + return file_io.join( + compat.as_bytes(compat.path_to_str(export_dir)), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB)) + + +def get_debug_dir(export_dir): + """Returns path to the debug sub-directory in the SavedModel.""" + return file_io.join( + compat.as_text(export_dir), compat.as_text(constants.DEBUG_DIRECTORY)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/__init__.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..94e7a3f354791972bf246b28ce87d7b7d526c62d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/__init__.pyi @@ -0,0 +1,16 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +def Save(arg0: str) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/constants.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/constants.pyi new file mode 100644 index 0000000000000000000000000000000000000000..461a232097108a6bacb0b188415748c7df226b69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/constants.pyi @@ -0,0 +1,33 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +ASSETS_DIRECTORY: str +ASSETS_KEY: str +DEBUG_DIRECTORY: str +DEBUG_INFO_FILENAME_PB: str +EXTRA_ASSETS_DIRECTORY: str +FINGERPRINT_FILENAME: str +INIT_OP_SIGNATURE_KEY: str +LEGACY_INIT_OP_KEY: str +MAIN_OP_KEY: str +SAVED_MODEL_FILENAME_CPB: str +SAVED_MODEL_FILENAME_PB: str +SAVED_MODEL_FILENAME_PBTXT: str +SAVED_MODEL_FILENAME_PREFIX: str +SAVED_MODEL_SCHEMA_VERSION: int +TRAIN_OP_KEY: str +TRAIN_OP_SIGNATURE_KEY: str +VARIABLES_DIRECTORY: str +VARIABLES_FILENAME: str diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/fingerprinting.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/fingerprinting.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f1cbab2a737bd257914f50cef5d9df44f103a9d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/fingerprinting.pyi @@ -0,0 +1,24 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 FileNotFoundException(Exception): ... + +class FingerprintException(Exception): ... + +def CreateFingerprintDef(export_dir: str) -> bytes: ... +def ReadSavedModelFingerprint(export_dir: str) -> bytes: ... +def Singleprint(graph_def_program_hash: int, signature_def_hash: int, saved_object_graph_hash: int, checkpoint_hash: int) -> str: ... +def SingleprintFromFP(export_dir: str) -> str: ... +def SingleprintFromSM(export_dir: str) -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/merger.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/merger.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4023ce61ee5cb1257e11a3412653dc90de7ccbab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/merger.pyi @@ -0,0 +1,20 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import Any + +class MergerException(Exception): ... + +def MergerRead(*args, **kwargs) -> Any: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/metrics.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/metrics.pyi new file mode 100644 index 0000000000000000000000000000000000000000..803138cbe6a3916e1d66daf7f5a142a2c149182e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/pywrap_saved_model/metrics.pyi @@ -0,0 +1,56 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from typing import Any + +kFingerprintError: str +kFingerprintFound: str +kFingerprintNotFound: str + +class MetricException(Exception): ... + +def AddAsyncCheckpointWriteDuration(*args, **kwargs) -> Any: ... +def AddCheckpointReadDuration(*args, **kwargs) -> Any: ... +def AddCheckpointWriteDuration(*args, **kwargs) -> Any: ... +def AddTrainingTimeSaved(*args, **kwargs) -> Any: ... +def CalculateFileSize(arg0: str) -> int: ... +def GetAsyncCheckpointWriteDurations(*args, **kwargs) -> Any: ... +def GetCheckpointReadDurations(*args, **kwargs) -> Any: ... +def GetCheckpointSize(*args, **kwargs) -> Any: ... +def GetCheckpointWriteDurations(*args, **kwargs) -> Any: ... +def GetFoundFingerprintOnLoad() -> str: ... +def GetRead(*args, **kwargs) -> Any: ... +def GetReadApi(arg0: str) -> int: ... +def GetReadFingerprint() -> str: ... +def GetReadPath() -> str: ... +def GetReadPathAndSingleprint() -> tuple[str,str]: ... +def GetTrainingTimeSaved(*args, **kwargs) -> Any: ... +def GetWrite(*args, **kwargs) -> Any: ... +def GetWriteApi(arg0: str) -> int: ... +def GetWriteFingerprint() -> str: ... +def GetWritePath() -> str: ... +def GetWritePathAndSingleprint() -> tuple[str,str]: ... +def IncrementRead(*args, **kwargs) -> Any: ... +def IncrementReadApi(arg0: str) -> None: ... +def IncrementWrite(*args, **kwargs) -> Any: ... +def IncrementWriteApi(arg0: str) -> None: ... +def RecordCheckpointSize(*args, **kwargs) -> Any: ... +def SetFoundFingerprintOnLoad(*args, **kwargs) -> Any: ... +def SetReadFingerprint(*args, **kwargs) -> Any: ... +def SetReadPath(*args, **kwargs) -> Any: ... +def SetReadPathAndSingleprint(*args, **kwargs) -> Any: ... +def SetWriteFingerprint(*args, **kwargs) -> Any: ... +def SetWritePath(*args, **kwargs) -> Any: ... +def SetWritePathAndSingleprint(*args, **kwargs) -> Any: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..976e148381d796bceff2b7bf041f076b5e62e45d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/__init__.py @@ -0,0 +1,49 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for registering the saving/loading steps for advanced objects.""" + +from tensorflow.python.saved_model.registration.registration import get_registered_class +from tensorflow.python.saved_model.registration.registration import get_registered_class_name +from tensorflow.python.saved_model.registration.registration import get_registered_saver_name +from tensorflow.python.saved_model.registration.registration import get_restore_function +from tensorflow.python.saved_model.registration.registration import get_save_function +from tensorflow.python.saved_model.registration.registration import get_strict_predicate_restore + +# These are currently an evolving feature. Use with care. +from tensorflow.python.saved_model.registration.registration import register_checkpoint_saver +from tensorflow.python.saved_model.registration.registration import register_serializable + +from tensorflow.python.saved_model.registration.registration import RegisteredSaver +from tensorflow.python.saved_model.registration.registration import validate_restore_function + + +def register_tf_serializable(name=None, predicate=None): + """See the docstring for `register_serializable`.""" + return register_serializable(package="tf", name=name, predicate=predicate) + + +def register_tf_checkpoint_saver(name=None, + predicate=None, + save_fn=None, + restore_fn=None, + strict_predicate_restore=True): + """See the docstring for `register_checkpoint_saver`.""" + return register_checkpoint_saver( + package="tf", + name=name, + predicate=predicate, + save_fn=save_fn, + restore_fn=restore_fn, + strict_predicate_restore=strict_predicate_restore) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/registration.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/registration.py new file mode 100644 index 0000000000000000000000000000000000000000..f519c0981cc289ecacfe9dd1341c42b8d90ff46a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/registration/registration.py @@ -0,0 +1,382 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Serialization Registration for SavedModel. + +revived_types registration will be migrated to this infrastructure. + +See the Advanced saving section in go/savedmodel-configurability. +This API is approved for TF internal use only. +""" +import collections +import re + +from tensorflow.python.util import tf_inspect + + +# Only allow valid file/directory characters +_VALID_REGISTERED_NAME = re.compile(r"^[a-zA-Z0-9._-]+$") + + +class _PredicateRegistry(object): + """Registry with predicate-based lookup. + + See the documentation for `register_checkpoint_saver` and + `register_serializable` for reasons why predicates are required over a + class-based registry. + + Since this class is used for global registries, each object must be registered + to unique names (an error is raised if there are naming conflicts). The lookup + searches the predicates in reverse order, so that later-registered predicates + are executed first. + """ + __slots__ = ("_registry_name", "_registered_map", "_registered_predicates", + "_registered_names") + + def __init__(self, name): + self._registry_name = name + # Maps registered name -> object + self._registered_map = {} + # Maps registered name -> predicate + self._registered_predicates = {} + # Stores names in the order of registration + self._registered_names = [] + + @property + def name(self): + return self._registry_name + + def register(self, package, name, predicate, candidate): + """Registers a candidate object under the package, name and predicate.""" + if not isinstance(package, str) or not isinstance(name, str): + raise TypeError( + f"The package and name registered to a {self.name} must be strings, " + f"got: package={type(package)}, name={type(name)}") + if not callable(predicate): + raise TypeError( + f"The predicate registered to a {self.name} must be callable, " + f"got: {type(predicate)}") + registered_name = package + "." + name + if not _VALID_REGISTERED_NAME.match(registered_name): + raise ValueError( + f"Invalid registered {self.name}. Please check that the package and " + f"name follow the regex '{_VALID_REGISTERED_NAME.pattern}': " + f"(package='{package}', name='{name}')") + if registered_name in self._registered_map: + raise ValueError( + f"The name '{registered_name}' has already been registered to a " + f"{self.name}. Found: {self._registered_map[registered_name]}") + + self._registered_map[registered_name] = candidate + self._registered_predicates[registered_name] = predicate + self._registered_names.append(registered_name) + + def lookup(self, obj): + """Looks up the registered object using the predicate. + + Args: + obj: Object to pass to each of the registered predicates to look up the + registered object. + Returns: + The object registered with the first passing predicate. + Raises: + LookupError if the object does not match any of the predicate functions. + """ + return self._registered_map[self.get_registered_name(obj)] + + def name_lookup(self, registered_name): + """Looks up the registered object using the registered name.""" + try: + return self._registered_map[registered_name] + except KeyError: + raise LookupError(f"The {self.name} registry does not have name " + f"'{registered_name}' registered.") + + def get_registered_name(self, obj): + for registered_name in reversed(self._registered_names): + predicate = self._registered_predicates[registered_name] + if predicate(obj): + return registered_name + raise LookupError(f"Could not find matching {self.name} for {type(obj)}.") + + def get_predicate(self, registered_name): + try: + return self._registered_predicates[registered_name] + except KeyError: + raise LookupError(f"The {self.name} registry does not have name " + f"'{registered_name}' registered.") + + def get_registrations(self): + return self._registered_predicates + +_class_registry = _PredicateRegistry("serializable class") +_saver_registry = _PredicateRegistry("checkpoint saver") + + +def get_registered_class_name(obj): + try: + return _class_registry.get_registered_name(obj) + except LookupError: + return None + + +def get_registered_class(registered_name): + try: + return _class_registry.name_lookup(registered_name) + except LookupError: + return None + + +def register_serializable(package="Custom", name=None, predicate=None): # pylint: disable=unused-argument + """Decorator for registering a serializable class. + + THIS METHOD IS STILL EXPERIMENTAL AND MAY CHANGE AT ANY TIME. + + Registered classes will be saved with a name generated by combining the + `package` and `name` arguments. When loading a SavedModel, modules saved with + this registered name will be created using the `_deserialize_from_proto` + method. + + By default, only direct instances of the registered class will be saved/ + restored with the `serialize_from_proto`/`deserialize_from_proto` methods. To + extend the registration to subclasses, use the `predicate argument`: + + ```python + class A(tf.Module): + pass + + register_serializable( + package="Example", predicate=lambda obj: isinstance(obj, A))(A) + ``` + + Args: + package: The package that this class belongs to. + name: The name to serialize this class under in this package. If None, the + class's name will be used. + predicate: An optional function that takes a single Trackable argument, and + determines whether that object should be serialized with this `package` + and `name`. The default predicate checks whether the object's type exactly + matches the registered class. Predicates are executed in the reverse order + that they are added (later registrations are checked first). + + Returns: + A decorator that registers the decorated class with the passed names and + predicate. + """ + def decorator(arg): + """Registers a class with the serialization framework.""" + nonlocal predicate + if not tf_inspect.isclass(arg): + raise TypeError("Registered serializable must be a class: {}".format(arg)) + + class_name = name if name is not None else arg.__name__ + if predicate is None: + predicate = lambda x: isinstance(x, arg) + _class_registry.register(package, class_name, predicate, arg) + return arg + + return decorator + + +RegisteredSaver = collections.namedtuple( + "RegisteredSaver", ["name", "predicate", "save_fn", "restore_fn"]) +_REGISTERED_SAVERS = {} +_REGISTERED_SAVER_NAMES = [] # Stores names in the order of registration + + +def register_checkpoint_saver(package="Custom", + name=None, + predicate=None, + save_fn=None, + restore_fn=None, + strict_predicate_restore=True): + """Registers functions which checkpoints & restores objects with custom steps. + + If you have a class that requires complicated coordination between multiple + objects when checkpointing, then you will need to register a custom saver + and restore function. An example of this is a custom Variable class that + splits the variable across different objects and devices, and needs to write + checkpoints that are compatible with different configurations of devices. + + The registered save and restore functions are used in checkpoints and + SavedModel. + + Please make sure you are familiar with the concepts in the [Checkpointing + guide](https://www.tensorflow.org/guide/checkpoint), and ops used to save the + V2 checkpoint format: + + * io_ops.SaveV2 + * io_ops.MergeV2Checkpoints + * io_ops.RestoreV2 + + **Predicate** + + The predicate is a filter that will run on every `Trackable` object connected + to the root object. This function determines whether a `Trackable` should use + the registered functions. + + Example: `lambda x: isinstance(x, CustomClass)` + + **Custom save function** + + This is how checkpoint saving works normally: + 1. Gather all of the Trackables with saveable values. + 2. For each Trackable, gather all of the saveable tensors. + 3. Save checkpoint shards (grouping tensors by device) with SaveV2 + 4. Merge the shards with MergeCheckpointV2. This combines all of the shard's + metadata, and renames them to follow the standard shard pattern. + + When a saver is registered, Trackables that pass the registered `predicate` + are automatically marked as having saveable values. Next, the custom save + function replaces steps 2 and 3 of the saving process. Finally, the shards + returned by the custom save function are merged with the other shards. + + The save function takes in a dictionary of `Trackables` and a `file_prefix` + string. The function should save checkpoint shards using the SaveV2 op, and + list of the shard prefixes. SaveV2 is currently required to work a correctly, + because the code merges all of the returned shards, and the `restore_fn` will + only be given the prefix of the merged checkpoint. If you need to be able to + save and restore from unmerged shards, please file a feature request. + + Specification and example of the save function: + + ``` + def save_fn(trackables, file_prefix): + # trackables: A dictionary mapping unique string identifiers to trackables + # file_prefix: A unique file prefix generated using the registered name. + ... + # Gather the tensors to save. + ... + io_ops.SaveV2(file_prefix, tensor_names, shapes_and_slices, tensors) + return file_prefix # Returns a tensor or a list of string tensors + ``` + + The save function is executed before the unregistered save ops. + + **Custom restore function** + + Normal checkpoint restore behavior: + 1. Gather all of the Trackables that have saveable values. + 2. For each Trackable, get the names of the desired tensors to extract from + the checkpoint. + 3. Use RestoreV2 to read the saved values, and pass the restored tensors to + the corresponding Trackables. + + The custom restore function replaces steps 2 and 3. + + The restore function also takes a dictionary of `Trackables` and a + `merged_prefix` string. The `merged_prefix` is different from the + `file_prefix`, since it contains the renamed shard paths. To read from the + merged checkpoint, you must use `RestoreV2(merged_prefix, ...)`. + + Specification: + + ``` + def restore_fn(trackables, merged_prefix): + # trackables: A dictionary mapping unique string identifiers to Trackables + # merged_prefix: File prefix of the merged shard names. + + restored_tensors = io_ops.restore_v2( + merged_prefix, tensor_names, shapes_and_slices, dtypes) + ... + # Restore the checkpoint values for the given Trackables. + ``` + + The restore function is executed after the non-registered restore ops. + + Args: + package: Optional, the package that this class belongs to. + name: (Required) The name of this saver, which is saved to the checkpoint. + When a checkpoint is restored, the name and package are used to find the + the matching restore function. The name and package are also used to + generate a unique file prefix that is passed to the save_fn. + predicate: (Required) A function that returns a boolean indicating whether a + `Trackable` object should be checkpointed with this function. Predicates + are executed in the reverse order that they are added (later registrations + are checked first). + save_fn: (Required) A function that takes a dictionary of trackables and a + file prefix as the arguments, writes the checkpoint shards for the given + Trackables, and returns the list of shard prefixes. + restore_fn: (Required) A function that takes a dictionary of trackables and + a file prefix as the arguments and restores the trackable values. + strict_predicate_restore: If this is `True` (default), then an error will be + raised if the predicate fails during checkpoint restoration. If this is + `True`, checkpoint restoration will skip running the restore function. + This value is generally set to `False` when the predicate does not pass on + the Trackables after being saved/loaded from SavedModel. + + Raises: + ValueError: if the package and name are already registered. + """ + if not callable(save_fn): + raise TypeError(f"The save_fn must be callable, got: {type(save_fn)}") + if not callable(restore_fn): + raise TypeError(f"The restore_fn must be callable, got: {type(restore_fn)}") + + _saver_registry.register(package, name, predicate, (save_fn, restore_fn, + strict_predicate_restore)) + + +def get_registered_saver_name(trackable): + """Returns the name of the registered saver to use with Trackable.""" + try: + return _saver_registry.get_registered_name(trackable) + except LookupError: + return None + + +def get_save_function(registered_name): + """Returns save function registered to name.""" + return _saver_registry.name_lookup(registered_name)[0] + + +def get_restore_function(registered_name): + """Returns restore function registered to name.""" + return _saver_registry.name_lookup(registered_name)[1] + + +def get_strict_predicate_restore(registered_name): + """Returns if the registered restore can be ignored if the predicate fails.""" + return _saver_registry.name_lookup(registered_name)[2] + + +def validate_restore_function(trackable, registered_name): + """Validates whether the trackable can be restored with the saver. + + When using a checkpoint saved with a registered saver, that same saver must + also be also registered when loading. The name of that saver is saved to the + checkpoint and set in the `registered_name` arg. + + Args: + trackable: A `Trackable` object. + registered_name: String name of the expected registered saver. This argument + should be set using the name saved in a checkpoint. + + Raises: + ValueError if the saver could not be found, or if the predicate associated + with the saver does not pass. + """ + try: + _saver_registry.name_lookup(registered_name) + except LookupError: + raise ValueError( + f"Error when restoring object {trackable} from checkpoint. This " + "object was saved using a registered saver named " + f"'{registered_name}', but this saver cannot be found in the " + "current context.") + if not _saver_registry.get_predicate(registered_name)(trackable): + raise ValueError( + f"Object {trackable} was saved with the registered saver named " + f"'{registered_name}'. However, this saver cannot be used to restore the " + "object because the predicate does not pass.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/revived_types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/revived_types.py new file mode 100644 index 0000000000000000000000000000000000000000..cf31318b34487ce8d8341ca11ce2e76c4e243fbc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/revived_types.py @@ -0,0 +1,249 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Handles types registrations for tf.saved_model.load.""" + +import operator + +from tensorflow.core.framework import versions_pb2 +from tensorflow.core.protobuf import saved_object_graph_pb2 +from tensorflow.python.trackable import data_structures +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.saved_model.load.VersionedTypeRegistration", v1=[]) +class VersionedTypeRegistration(object): + """Holds information about one version of a revived type.""" + + def __init__(self, object_factory, version, min_producer_version, + min_consumer_version, bad_consumers=None, setter=setattr): + """Identify a revived type version. + + Args: + object_factory: A callable which takes a SavedUserObject proto and returns + a trackable object. Dependencies are added later via `setter`. + version: An integer, the producer version of this wrapper type. When + making incompatible changes to a wrapper, add a new + `VersionedTypeRegistration` with an incremented `version`. The most + recent version will be saved, and all registrations with a matching + identifier will be searched for the highest compatible version to use + when loading. + min_producer_version: The minimum producer version number required to use + this `VersionedTypeRegistration` when loading a proto. + min_consumer_version: `VersionedTypeRegistration`s with a version number + less than `min_consumer_version` will not be used to load a proto saved + with this object. `min_consumer_version` should be set to the lowest + version number which can successfully load protos saved by this + object. If no matching registration is available on load, the object + will be revived with a generic trackable type. + + `min_consumer_version` and `bad_consumers` are a blunt tool, and using + them will generally break forward compatibility: previous versions of + TensorFlow will revive newly saved objects as opaque trackable + objects rather than wrapped objects. When updating wrappers, prefer + saving new information but preserving compatibility with previous + wrapper versions. They are, however, useful for ensuring that + previously-released buggy wrapper versions degrade gracefully rather + than throwing exceptions when presented with newly-saved SavedModels. + bad_consumers: A list of consumer versions which are incompatible (in + addition to any version less than `min_consumer_version`). + setter: A callable with the same signature as `setattr` to use when adding + dependencies to generated objects. + """ + self.setter = setter + self.identifier = None # Set after registration + self._object_factory = object_factory + self.version = version + self._min_consumer_version = min_consumer_version + self._min_producer_version = min_producer_version + if bad_consumers is None: + bad_consumers = [] + self._bad_consumers = bad_consumers + + def to_proto(self): + """Create a SavedUserObject proto.""" + # For now wrappers just use dependencies to save their state, so the + # SavedUserObject doesn't depend on the object being saved. + # TODO(allenl): Add a wrapper which uses its own proto. + return saved_object_graph_pb2.SavedUserObject( + identifier=self.identifier, + version=versions_pb2.VersionDef( + producer=self.version, + min_consumer=self._min_consumer_version, + bad_consumers=self._bad_consumers)) + + def from_proto(self, proto): + """Recreate a trackable object from a SavedUserObject proto.""" + return self._object_factory(proto) + + def should_load(self, proto): + """Checks if this object should load the SavedUserObject `proto`.""" + if proto.identifier != self.identifier: + return False + if self.version < proto.version.min_consumer: + return False + if proto.version.producer < self._min_producer_version: + return False + for bad_version in proto.version.bad_consumers: + if self.version == bad_version: + return False + return True + + +# string identifier -> (predicate, [VersionedTypeRegistration]) +_REVIVED_TYPE_REGISTRY = {} +_TYPE_IDENTIFIERS = [] + + +@tf_export("__internal__.saved_model.load.register_revived_type", v1=[]) +def register_revived_type(identifier, predicate, versions): + """Register a type for revived objects. + + Args: + identifier: A unique string identifying this class of objects. + predicate: A Boolean predicate for this registration. Takes a + trackable object as an argument. If True, `type_registration` may be + used to save and restore the object. + versions: A list of `VersionedTypeRegistration` objects. + """ + # Keep registrations in order of version. We always use the highest matching + # version (respecting the min consumer version and bad consumers). + versions.sort(key=lambda reg: reg.version, reverse=True) + if not versions: + raise AssertionError("Need at least one version of a registered type.") + version_numbers = set() + for registration in versions: + # Copy over the identifier for use in generating protos + registration.identifier = identifier + if registration.version in version_numbers: + raise AssertionError( + f"Got multiple registrations with version {registration.version} for " + f"type {identifier}.") + version_numbers.add(registration.version) + + _REVIVED_TYPE_REGISTRY[identifier] = (predicate, versions) + _TYPE_IDENTIFIERS.append(identifier) + + +def serialize(obj): + """Create a SavedUserObject from a trackable object.""" + for identifier in _TYPE_IDENTIFIERS: + predicate, versions = _REVIVED_TYPE_REGISTRY[identifier] + if predicate(obj): + # Always uses the most recent version to serialize. + return versions[0].to_proto() + return None + + +def deserialize(proto): + """Create a trackable object from a SavedUserObject proto. + + Args: + proto: A SavedUserObject to deserialize. + + Returns: + A tuple of (trackable, assignment_fn) where assignment_fn has the same + signature as setattr and should be used to add dependencies to + `trackable` when they are available. + """ + _, type_registrations = _REVIVED_TYPE_REGISTRY.get( + proto.identifier, (None, None)) + if type_registrations is not None: + for type_registration in type_registrations: + if type_registration.should_load(proto): + return (type_registration.from_proto(proto), type_registration.setter) + return None + + +@tf_export("__internal__.saved_model.load.registered_identifiers", v1=[]) +def registered_identifiers(): + """Return all the current registered revived object identifiers. + + Returns: + A set of strings. + """ + return _REVIVED_TYPE_REGISTRY.keys() + + +@tf_export("__internal__.saved_model.load.get_setter", v1=[]) +def get_setter(proto): + """Gets the registered setter function for the SavedUserObject proto. + + See VersionedTypeRegistration for info about the setter function. + + Args: + proto: SavedUserObject proto + + Returns: + setter function + """ + _, type_registrations = _REVIVED_TYPE_REGISTRY.get( + proto.identifier, (None, None)) + if type_registrations is not None: + for type_registration in type_registrations: + if type_registration.should_load(proto): + return type_registration.setter + return None + + +register_revived_type( + "trackable_dict_wrapper", + # pylint: disable=protected-access + lambda obj: isinstance(obj, data_structures._DictWrapper), + versions=[ + VersionedTypeRegistration( + # Standard dependencies are enough to reconstruct the trackable + # items in dictionaries, so we don't need to save any extra + # information. + # pylint: disable=protected-access + object_factory=lambda proto: data_structures._DictWrapper({}), + version=1, + min_producer_version=1, + min_consumer_version=1, + setter=operator.setitem, + ) + ], +) + + +register_revived_type( + "trackable_list_wrapper", + lambda obj: isinstance(obj, data_structures.ListWrapper), + versions=[ + VersionedTypeRegistration( + object_factory=lambda proto: data_structures.ListWrapper([]), + version=1, + min_producer_version=1, + min_consumer_version=1, + setter=data_structures.set_list_item, + ) + ], +) + + +# Revive tuples as lists so we can append any dependencies during loading. +register_revived_type( + "trackable_tuple_wrapper", + # pylint: disable=protected-access + lambda obj: isinstance(obj, data_structures._TupleWrapper), + versions=[ + VersionedTypeRegistration( + object_factory=lambda proto: data_structures.ListWrapper([]), + version=1, + min_producer_version=1, + min_consumer_version=1, + setter=data_structures.set_tuple_item, + ) + ], +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save.py new file mode 100644 index 0000000000000000000000000000000000000000..88f840862f7f5c437e19f132b0b2630d5fa18ce2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save.py @@ -0,0 +1,1584 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Exports a SavedModel from a Trackable Python object.""" + +import collections +import os +import re +import sys +import traceback +from typing import Any, Callable, Dict, List, Tuple + +from absl import logging + +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import versions_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saved_model_pb2 +from tensorflow.core.protobuf import saved_object_graph_pb2 +from tensorflow.python.checkpoint import checkpoint +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.checkpoint import functional_saver +from tensorflow.python.checkpoint import graph_view +from tensorflow.python.checkpoint import save_util_v1 +from tensorflow.python.checkpoint import util as checkpoint_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun +from tensorflow.python.eager.polymorphic_function import concrete_function as cf +from tensorflow.python.eager.polymorphic_function import polymorphic_function +from tensorflow.python.eager.polymorphic_function import saved_model_exported_concrete +from tensorflow.python.eager.polymorphic_function import saved_model_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import function as framework_fn +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import versions +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import builder_impl +from tensorflow.python.saved_model import fingerprinting_utils +from tensorflow.python.saved_model import function_serialization +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model import pywrap_saved_model +from tensorflow.python.saved_model import registration +from tensorflow.python.saved_model import revived_types +from tensorflow.python.saved_model import save_context +from tensorflow.python.saved_model import save_options +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import signature_serialization +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.saved_model import tracing_utils +from tensorflow.python.saved_model import utils_impl +from tensorflow.python.saved_model.pywrap_saved_model import constants +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import asset +from tensorflow.python.trackable import base +from tensorflow.python.trackable import resource +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import trace_saveable_util +from tensorflow.python.types import core as types_core +from tensorflow.python.util import compat +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_stack +from tensorflow.python.util.tf_export import tf_export +# Placeholder for protosplitter import. + + +_UNCOPIABLE_DTYPES = frozenset((dtypes.resource, dtypes.variant)) + +# Container for tensors captured from external functions. +_CapturedTensor = collections.namedtuple("_CapturedTensor", + ["name", "concrete_function"]) + +# Number of untraced functions to display to user in warning message. +_NUM_DISPLAY_UNTRACED_FUNCTIONS = 5 + +# API label for SavedModel metrics. +_SAVE_V2_LABEL = "save_v2" + + +class _AugmentedGraphView(graph_view.ObjectGraphView): + """An extendable graph which also tracks functions attached to objects. + + Extensions through `add_object` appear in the object graph and any checkpoints + generated from it, even if they are not dependencies of the node they were + attached to in the saving program. For example a `.signatures` attribute is + added to exported SavedModel root objects without modifying the root object + itself. + + Also tracks functions attached to objects in the graph, through the caching + `_list_functions` method. Enumerating functions only through this method + ensures that we get a consistent view of functions, even if object attributes + create new functions every time they are accessed. + """ + + def __init__(self, root): + super(_AugmentedGraphView, self).__init__(root) + + # Cache the results of `GraphView.list_children()` to ensure that the + # `Trackable` children are gathered exactly once. + self._children_cache = object_identity.ObjectIdentityDictionary() + + # Cache shared between objects in the same object graph. This is passed to + # `Trackable._trackable_children()`. + self._serialization_cache = object_identity.ObjectIdentityDictionary() + + # Maps functions -> wrapped functions that capture non-cached variables. + self._wrapped_functions = {} + + self.untraced_functions = [] + + def set_signature( + self, + signature_map: signature_serialization._SignatureMap, + wrapped_functions: Dict[Callable[..., Any], Callable[..., Any]], + ): + """Attach signature to the root object. + + Args: + signature_map: An object that contains signature functions. + wrapped_functions: A dictionary mapping functions to functions that are + guaranteed to not capture cached variables (functions that capture + cached variables can't be saved). + """ + self.list_children(self.root) + # Overrides existing dependency. + name = signature_serialization.SIGNATURE_ATTRIBUTE_NAME + self._children_cache[self.root][name] = signature_map + self._wrapped_functions.update(wrapped_functions) + + def _breadth_first_traversal(self): + """Returns all trackable objects in the SavedObjectGraph.""" + # This method is overriden to merge all equivalent constant tensors and + # Assets in the object graph. + + trackable_objects, _ = ( + super(_AugmentedGraphView, self)._breadth_first_traversal()) + + asset_paths = object_identity.ObjectIdentityDictionary() + constant_captures = object_identity.ObjectIdentityDictionary() + for obj in trackable_objects: + if isinstance(obj, asset.Asset): + asset_paths[obj.asset_path] = obj + if isinstance(obj, saved_model_utils.TrackableConstant): + constant_captures[obj.capture] = obj + + def _get_merged_trackable(x): + if isinstance(x, asset.Asset): + return asset_paths[x.asset_path] + if isinstance(x, saved_model_utils.TrackableConstant): + if x.capture in asset_paths: + return asset_paths[x.capture] + else: + return constant_captures[x.capture] + return x + + for obj in list(self._children_cache.keys()): + if _get_merged_trackable(obj) is not obj: + del self._children_cache[obj] + continue + for name, child in self._children_cache[obj].items(): + self._children_cache[obj][name] = _get_merged_trackable(child) + + return super(_AugmentedGraphView, self)._breadth_first_traversal() + + def list_children(self, obj): + """Lists children of `obj` for SavedModel.""" + if obj not in self._children_cache: + children = self._children_cache[obj] = {} + + for name, child in super(_AugmentedGraphView, self).list_children( + obj, + save_type=base.SaveType.SAVEDMODEL, + cache=self._serialization_cache): + if isinstance(child, defun.ConcreteFunction): + child = self._maybe_uncache_variable_captures(child) + children[name] = child + + # Keep track of untraced functions for later reporting to the user. + if isinstance(obj, def_function.Function) and not children: + self.untraced_functions.append(obj.name) + + for name, child in self._children_cache[obj].items(): + yield base.TrackableReference(name, child) + + def get_child(self, obj, name: str): + return self._children_cache[obj][name] + + def _maybe_uncache_variable_captures( + self, concrete_function: cf.ConcreteFunction + ): + if concrete_function in self._wrapped_functions: + return self._wrapped_functions[concrete_function] + for capture in concrete_function.captured_inputs: + if hasattr(capture, "_cached_variable"): + if concrete_function not in self._wrapped_functions: + wrapped = self._wrapped_functions[concrete_function] = ( + function_serialization.wrap_cached_variables(concrete_function) + ) + return wrapped + return concrete_function + + def list_dependencies(self, obj): + """Yields `Trackables` that must be loaded before `obj`. + + Dependencies and children are both dictionaries of `Trackables`. Children + define the object graph structure (used in both checkpoints and SavedModel), + while dependency defines the order used to load the SavedModel + + Args: + obj: A `Trackable` object + + Yields: + Tuple of dependency names and trackable objects. + + Raises: + TypeError: if any of the returned dependencies are not instances of + `Trackable`. + """ + if obj not in self._children_cache: + # Slot variables do not appear in the children_cache. + children = {} + else: + children = self._children_cache[obj] + for name, dep in obj._deserialization_dependencies(children).items(): # pylint: disable=protected-access + if not isinstance(dep, base.Trackable): + raise TypeError( + f"The dependency of type {type(dep)} is not an instance `Trackable`" + ", and can't be saved to SavedModel. Please check the " + "implementation of `_deserialization_dependencies` in the parent " + f"object {obj}.") + yield name, dep + + +class _SaveableView(object): + """Provides a frozen view over a trackable root. + + This class helps to create a single stable view over an object to save. The + saving code should access properties and functions via this class and not via + the original object as there are cases where an object construct their + trackable attributes and functions dynamically per call and will yield + different objects if invoked more than once. + + Changes to the graph, for example adding objects, must happen in + `augmented_graph_view` (an `_AugmentedGraphView`) before the `_SaveableView` + is constructed. Changes after the `_SaveableView` has been constructed will be + ignored. + """ + + def __init__( + self, + augmented_graph_view: _AugmentedGraphView, + options: save_options.SaveOptions, + ): + """Initializes a SaveableView. + + Args: + augmented_graph_view: A GraphView object. + options: A SaveOptions instance. + """ + self.augmented_graph_view = augmented_graph_view + self._options = options + + (self._trackable_objects, self.node_paths, self.node_ids, + self._slot_variables, self.object_names) = ( + checkpoint_util.objects_ids_and_slot_variables_and_paths( + self.augmented_graph_view)) + + untraced_functions = self.augmented_graph_view.untraced_functions + if untraced_functions: + logging.info( + "Found untraced functions such as %s while saving (showing %d of %d)." + " These functions will not be directly callable after loading.", + ", ".join(untraced_functions[:_NUM_DISPLAY_UNTRACED_FUNCTIONS]), + min(_NUM_DISPLAY_UNTRACED_FUNCTIONS, len(untraced_functions)), + len(untraced_functions)) + + self._initialize_save_and_restore_functions() + self._initialize_nodes_and_concrete_functions() + + self.captured_tensor_node_ids = object_identity.ObjectIdentityDictionary() + + def _initialize_save_and_restore_functions(self): + """Generates all checkpoint save/restore functions. + + The save and restore functions are generated in the eager context (or in the + user's Graph/Session) before being copied to the exported GraphDef. These + functions record the ops for saving/restoring the entire object or + individual objects (e.g. variables and hash tables). + + The global save and restore functions are generated for compatibility with + TF1 and loading from C++, and is saved in the `MetaGraphDef.saver_def`. + + The individual functions are generated for the Python TF2 use case, where + users use the loaded SavedModel as-is, or compose new models using parts + of the object loaded from the SavedModel. These functions are recorded in + the `saveable_objects` map in the `SavedObject` proto. + """ + checkpoint_factory_map, registered_savers = ( + save_util_v1.get_checkpoint_factories_and_keys(self.object_names)) + self._obj_to_registered_saver = object_identity.ObjectIdentityDictionary() + for saver_name, trackables in registered_savers.items(): + for trackable in trackables.values(): + self._obj_to_registered_saver[trackable] = saver_name + self._saveable_objects_map = ( + _gen_save_and_restore_functions(checkpoint_factory_map)) + + def _initialize_nodes_and_concrete_functions(self): + """Creates graph with nodes for trackable objects and functions. + + Adds functions for each trackable object to `self.nodes` and associated + concrete functions to `self.concrete_functions` for serialization. + """ + self.nodes = list(self._trackable_objects) + self.gradient_functions = [] + self.gradient_defs = [] + + for obj in self.nodes: + if obj in self._saveable_objects_map: + for save_fn, restore_fn in self._saveable_objects_map[obj].values(): + self.node_ids[save_fn] = len(self.nodes) + self.nodes.append(save_fn) + + self.node_ids[restore_fn] = len(self.nodes) + self.nodes.append(restore_fn) + + self.concrete_functions = [ + obj for obj in self.nodes if isinstance(obj, defun.ConcreteFunction) + ] + + @property + def concrete_and_gradient_functions(self): + return self.concrete_functions + self.gradient_functions + + @property + def root(self): + return self.nodes[0] + + def fill_object_graph_proto( + self, proto: saved_object_graph_pb2.SavedObjectGraph + ): + """Populate the nodes, children and slot_variables of a SavedObjectGraph.""" + for node_id, node in enumerate(self.nodes): + assert self.node_ids[node] == node_id + object_proto = proto.nodes.add() + object_proto.slot_variables.extend(self._slot_variables.get(node, ())) + if isinstance(node, _CapturedTensor): + continue + for child in self.augmented_graph_view.list_children(node): + child_proto = object_proto.children.add() + child_proto.node_id = self.node_ids[child.ref] + child_proto.local_name = child.name + for name, ref in self.augmented_graph_view.list_dependencies(node): + child_proto = object_proto.dependencies.add() + child_proto.node_id = self.node_ids[ref] + child_proto.local_name = name + + if node in self._saveable_objects_map: + assert node not in self._obj_to_registered_saver, ( + "Objects can't have both SaveableObjects and a registered saver") + + for local_name, (save_fn, restore_fn) in ( + self._saveable_objects_map[node].items()): + saveable_object_proto = object_proto.saveable_objects[local_name] + saveable_object_proto.save_function = self.node_ids[save_fn] + saveable_object_proto.restore_function = self.node_ids[restore_fn] + + elif node in self._obj_to_registered_saver: + object_proto.registered_saver = self._obj_to_registered_saver[node] + + def map_resources(self): + """Makes new resource handle ops corresponding to existing resource tensors. + + Creates resource handle ops in the current default graph, whereas + `accessible_objects` will be from an eager context. Resource mapping adds + resource handle ops to the main GraphDef of a SavedModel, which allows the + C++ loader API to interact with resources. + + Returns: + A tuple of (object_map, tensor_map, asset_info): + object_map: A dictionary mapping from object in `accessible_objects` to + replacement objects created to hold the new resource tensors. + tensor_map: A dictionary mapping from resource tensors extracted from + `accessible_objects` to newly created resource tensors. + asset_info: An _AssetInfo tuple describing external assets referenced + from accessible_objects. + """ + # Only makes sense when adding to the export Graph + assert not context.executing_eagerly() + # TODO(b/205007558): Handle MirroredVariables and other types of variables + # which may need special casing. + object_map = object_identity.ObjectIdentityDictionary() + tensor_map = object_identity.ObjectIdentityDictionary() + asset_info = _AssetInfo( + asset_defs=[], + asset_initializers_by_resource=object_identity.ObjectIdentityDictionary(), + asset_filename_map={}, + asset_index={}) + + for node_id in _dependency_sorted_node_ids(self): + obj = self.nodes[node_id] + tensors = obj._export_to_saved_model_graph( # pylint: disable=protected-access + object_map=object_map, + tensor_map=tensor_map, + options=self._options) + if isinstance(obj, asset.Asset): + _add_asset_info(obj, asset_info, tensor_map[obj.asset_path]) + if tensors: + for tensor in tensors: + self.captured_tensor_node_ids[tensor] = node_id + + return object_map, tensor_map, asset_info + + def add_capture_and_node(self, capture, node): + node_id = len(self.nodes) + self.nodes.append(node) + self.node_ids[capture] = node_id + self.node_ids[node] = node_id + self.captured_tensor_node_ids[capture] = node_id + return node_id + + def get_concrete_resource_initializers(self): + concrete_initializers = [] + for obj in self.nodes: + if isinstance(obj, resource.CapturableResource): + concrete_initializers.append( + self.augmented_graph_view.get_child( + obj, "_initialize").get_concrete_function()) + return concrete_initializers + + +def _gen_save_and_restore_functions( + checkpoint_factory_map: object_identity.ObjectIdentityDictionary, +) -> object_identity.ObjectIdentityDictionary: + """Generates global and individual save/restore concrete functions. + + The global functions records the ops to save and restore the entire object to + a file prefix, while the individual functions save and restore value tensors + for resources. + + This function is intended to run on the output of + `save_util_v1.get_checkpoint_factories_and_keys(object_names)`, + which returns the generated a map of `_CheckpointFactoryData`. + + Args: + checkpoint_factory_map: A dictionary mapping trackable objects to + a list of `_CheckpointFactoryData`. + + Returns: + Tuple of ( + saveable_fn_map: Maps obj -> factory name -> (concrete save, restore) + ) + """ + # Maps obj -> factory attribute_name -> (concrete save, concrete restore) + # This + saveable_fn_map = object_identity.ObjectIdentityDictionary() + + for obj, factory_data_list in checkpoint_factory_map.items(): + if resource_variable_ops.is_resource_variable(obj) or not factory_data_list: + # There is no need to trace the save and restore functions for variables. + continue + + if factory_data_list[0].name == trackable_utils.SERIALIZE_TO_TENSORS_NAME: + # Trace Trackable save and restore functions. + assert len(factory_data_list) == 1 + saveable_fn_map[obj] = {trackable_utils.SERIALIZE_TO_TENSORS_NAME: ( + tracing_utils.trace_save_and_restore(obj))} + else: + # Trace deprecated SaveableObject save and restore functions. + saveable_fn_map[obj] = ( + trace_saveable_util.trace_save_restore_function_map( + obj, factory_data_list)) + return saveable_fn_map + + +def _tensor_dict_to_tensorinfo(tensor_dict): + return { + key: utils_impl.build_tensor_info_internal(value) + for key, value in tensor_dict.items() + } + + +def _to_safe_name_scope(signature_key: str, user_input_name: str): + """Creates a sanitized name scope from user signature and input names. + + Concatenates signature and input names, sanitizing as needed to be a valid + scope name. + + Args: + signature_key: The user-provided key for the signature. + user_input_name: The user-provided name for the input placeholder. + + Returns: + A name scope that is safe to be used in tf.name_scope(). + """ + name_scope = "{}_{}".format(signature_key, user_input_name) + if re.match(r"^[A-Za-z0-9.][A-Za-z0-9_.\\-]*$", name_scope): + return name_scope + invalid_prefix_stripped = re.sub(r"^[^A-Za-z0-9.]*", "", name_scope) + return re.sub(r"[^A-Za-z0-9_.\\-]", "_", invalid_prefix_stripped) + + +def _map_function_arguments_to_created_inputs( + function_arguments: List[Any], + signature_key: str, + function_name: bytes, + defaults=None, +): + """Creates exterior placeholders in the exported graph for function arguments. + + Functions have two types of inputs: tensors captured from the outside (eager) + context, and arguments to the function which we expect to receive from the + user at each call. `_map_captures_to_created_tensors` replaces + captured tensors with stand-ins (typically these are resource dtype tensors + associated with variables). `_map_function_inputs_to_created_inputs` runs over + every argument, creating a new placeholder for each which will belong to the + exported graph rather than the function body. + + Args: + function_arguments: A list of argument placeholders in the function body. + signature_key: The name of the signature being exported, for error messages. + function_name: The name of the function, for error messages. + defaults: A dictionary mapping signature_key to dictionary of + user_specified_name to Tensor representing default values. + + Returns: + A tuple of (mapped_inputs, exterior_placeholders) + mapped_inputs: A list with entries corresponding to `function_arguments` + containing all of the inputs of the function gathered from the exported + graph (both captured resources and arguments). + exterior_argument_placeholders: A dictionary mapping from argument names + to placeholders in the exported graph, containing the explicit arguments + to the function which a user is expected to provide. + + Raises: + ValueError: If argument names are not unique. + """ + # `exterior_argument_placeholders` holds placeholders which are outside the + # function body, directly contained in a MetaGraph of the SavedModel. The + # function body itself contains nearly identical placeholders used when + # running the function, but these exterior placeholders allow Session-based + # APIs to call the function using feeds and fetches which name Tensors in the + # MetaGraph. + exterior_argument_placeholders = {} + mapped_inputs = [] + for placeholder in function_arguments: + # `export_captures` contains an exhaustive set of captures, so if we don't + # find the input there then we now know we have an argument. + user_input_name = compat.as_str_any( + placeholder.op.get_attr("_user_specified_name")) + # If the internal placeholders for a function have names which were + # uniquified by TensorFlow, then a single user-specified argument name + # must refer to multiple Tensors. The resulting signatures would be + # confusing to call. Instead, we throw an exception telling the user to + # specify explicit names. + if user_input_name != placeholder.op.name: + # This should be unreachable, since concrete functions may not be + # generated with non-unique argument names. + raise ValueError( + "Got non-flat/non-unique argument names for SavedModel signature " + f"'{signature_key}': more than one argument to " + f"'{compat.as_str_any(function_name)}' was named " + f"'{user_input_name}'. " + "Signatures have one Tensor per named input, so to have " + "predictable names Python functions used to generate these " + "signatures should avoid *args and Tensors in nested " + "structures unless unique names are specified for each. Use " + "tf.TensorSpec(..., name=...) to provide a name for a Tensor " + "input.") + default_value = defaults.get(signature_key, {}).get(user_input_name) + if default_value is not None: + placeholder_with_default = array_ops.placeholder_with_default( + input=default_value.numpy(), + shape=placeholder.shape, + name=_to_safe_name_scope(signature_key, user_input_name), + ) + exterior_argument_placeholders[user_input_name] = placeholder_with_default + mapped_inputs.append(placeholder_with_default) + else: + arg_placeholder = array_ops.placeholder( + shape=placeholder.shape, + dtype=placeholder.dtype, + name=_to_safe_name_scope(signature_key, user_input_name), + ) + exterior_argument_placeholders[user_input_name] = arg_placeholder + mapped_inputs.append(arg_placeholder) + return mapped_inputs, exterior_argument_placeholders + + +def _generate_signatures( + signature_functions: dict[str, Callable[..., Any]], + object_map: object_identity.ObjectIdentityDictionary, + defaults=None, +): + """Validates and calls `signature_functions` in the exported graph. + + Args: + signature_functions: A dictionary mapping string keys to concrete TensorFlow + functions (e.g. from `signature_serialization.canonicalize_signatures`) + which will be used to generate SignatureDefs. + object_map: A dictionary that contains mappings from signature functions to + concrete functions in the exported graph. + defaults: A dictionary mapping signature_key to dictionary of + user_specified_name to Tensor representing default values. + + Returns: + Each function in the `signature_functions` dictionary is called with + placeholder Tensors, generating a function call operation and output + Tensors. The placeholder Tensors, the function call operation, and the + output Tensors from the function call are part of the default Graph. + + This function then returns a dictionary with the same structure as + `signature_functions`, with the concrete functions replaced by SignatureDefs + implicitly containing information about how to call each function from a + TensorFlow 1.x Session / the C++ Loader API. These SignatureDefs reference + the generated placeholders and Tensor outputs by name. + + The caller is expected to include the default Graph set while calling this + function as a MetaGraph in a SavedModel, including the returned + SignatureDefs as part of that MetaGraph. + """ + signatures = {} + for signature_key, function in sorted(signature_functions.items()): + if function.graph.captures: + argument_inputs = function.graph.inputs[:-len(function.graph.captures)] + else: + argument_inputs = function.graph.inputs + mapped_inputs, exterior_argument_placeholders = ( + _map_function_arguments_to_created_inputs( + argument_inputs, signature_key, function.name, defaults + ) + ) + kwarg_names = list( + sorted( + object_map[function].function.structured_input_signature[1].keys())) + outputs = object_map[function](**{ + kwarg_name: mapped_input + for kwarg_name, mapped_input in zip(kwarg_names, mapped_inputs) + }) + signatures[signature_key] = signature_def_utils.build_signature_def( + _tensor_dict_to_tensorinfo(exterior_argument_placeholders), + _tensor_dict_to_tensorinfo(outputs), + method_name=signature_constants.PREDICT_METHOD_NAME, + defaults=defaults.get(signature_key, None), + ) + return signatures + + +_AssetInfo = collections.namedtuple( + "_AssetInfo", + [ + # List of AssetFileDef protocol buffers + "asset_defs", + # Map from asset variable resource Tensors to their init ops + "asset_initializers_by_resource", + # Map from base asset filenames to full paths + "asset_filename_map", + # Map from Asset to index of corresponding AssetFileDef + "asset_index", + ], +) + + +def _add_asset_info( + trackable_asset, + asset_info: _AssetInfo, + mapped_path_variable: resource_variable_ops.ResourceVariable, +): + """Add `trackable_asset` to `asset_info`.""" + original_path_tensor = trackable_asset.asset_path + original_path = tensor_util.constant_value(original_path_tensor) + try: + original_path = str(original_path.astype(str)) + except AttributeError: + # Already a string rather than a numpy array + pass + + path = builder_impl.get_asset_filename_to_add( + asset_filepath=original_path, + asset_filename_map=asset_info.asset_filename_map) + asset_info.asset_filename_map[path] = original_path + asset_def = meta_graph_pb2.AssetFileDef() + asset_def.filename = path + asset_def.tensor_info.name = mapped_path_variable.initial_value.name + asset_info.asset_defs.append(asset_def) + asset_info.asset_initializers_by_resource[original_path_tensor] = ( + mapped_path_variable.initializer) + asset_info.asset_index[trackable_asset] = len(asset_info.asset_defs) - 1 + + +def _iterate_op_types(fn: Callable[..., Any]): + """Iterates through each op in the function and returns the op type and op.""" + if isinstance(fn, framework_fn._DefinedFunction): # pylint: disable=protected-access + for node in fn.definition.node_def: + op_type = node.attr["_gradient_op_type"].s + if op_type: + raise ValueError( + "Unable to save gradient functions when exporting a " + "_DefinedFunction (generally created through graph freezing utils " + "or through V1 graph importers). Please save with " + "`options=tf.SaveOptions(experimental_custom_gradients=False)`") + else: + for op in fn.graph.get_operations(): + try: + op_type = op.get_attr("_gradient_op_type") + except ValueError: + continue + yield op_type, op + + +def _get_outer_most_capture( + fn: Callable[..., Any], + capture: _CapturedTensor, + func_graph_map: Dict[ops.Graph, Callable[..., Any]], +): + """Tries to find the original captured tensor if capture more than once.""" + outer_fn = fn + while outer_fn is not None and not isinstance(capture, ops.EagerTensor): + if capture.graph is not outer_fn.graph: + outer_fn = func_graph_map.get(outer_fn.graph.outer_graph) + else: + try: + capture_index = outer_fn.graph.internal_captures.index(capture) + except ValueError: + break # Capture is a tensor inside function, and not captured from + # another external function + capture = outer_fn.graph.external_captures[capture_index] + outer_fn = func_graph_map.get(outer_fn.graph.outer_graph) + return outer_fn, capture + + +def _trace_gradient_functions(graph: ops.Graph, saveable_view: _SaveableView): + """Traces gradient functions and records them in the SaveableView.""" + functions = list(graph._functions.values()) # pylint: disable=protected-access + func_graph_map = {f.graph: f for f in functions if hasattr(f, "graph")} + seen_op_types = set() + + for fn in functions: + for op_type, op in _iterate_op_types(fn): + if op_type in seen_op_types: + continue + seen_op_types.add(op_type) + + try: + custom_gradient = ops.gradient_registry.lookup(op_type) + except LookupError: + continue + + try: + grad_fn = ( + def_function.function(custom_gradient).get_concrete_function( + None, *op.inputs)) + except Exception as exc: + traceback.print_exc() + raise ValueError( + "Error when tracing gradients for SavedModel.\n\n" + "Check the error log to see the error that was raised when " + "converting a gradient function to a concrete function. You may " + "need to update the custom gradient, or disable saving gradients " + "with the option " + "tf.saved_model.SaveOptions(experimental_custom_gradients=False)" + f".\n\tProblematic op name: {op.name}\n\tGradient inputs: " + f"{op.inputs}") from exc + + with graph.as_default(): + # The gradient function will capture all intermediate values. These + # captures be serialized so that they can be re-bound to the function + # when loading. + bad_captures = [] + for capture in grad_fn.captured_inputs: + if capture.dtype in _UNCOPIABLE_DTYPES: + continue + # Tries to find the outermost capture in case the tensor is a constant + # or not actually captured in the current function (this could happen + # if the function is a while loop body, in which case the captured + # input is not the internal captured tensor). + outer_fn, outer_capture = _get_outer_most_capture( + fn, capture, func_graph_map + ) + if outer_fn is None or isinstance(outer_capture, ops.EagerTensor): + if outer_capture not in saveable_view.captured_tensor_node_ids: + raise ValueError( + f"Found invalid capture {outer_capture} when " + "saving custom gradients." + ) + saveable_view.captured_tensor_node_ids[capture] = ( + saveable_view.captured_tensor_node_ids[outer_capture] + ) + elif outer_capture.graph is outer_fn.graph: + capture_name = outer_capture.name + # It's possible for AtomicFunctions to save different names + # for input tensors when serialized to FunctionDef (all + # non-alphanumeric characters are converted to '_'). + if isinstance(outer_fn, defun.AtomicFunction): # pylint:disable=protected-access + try: + arg_index = outer_fn.graph.inputs.index(outer_capture) + capture_name = ( + outer_fn.cached_definition.signature.input_arg[ + arg_index + ].name + + ":0" + ) + except ValueError: + pass + + node = _CapturedTensor(capture_name, outer_fn.name) + saveable_view.add_capture_and_node(capture, node) + else: + bad_captures.append(capture.name) + if not bad_captures: + grad_fn.add_to_graph(graph) + else: + raise ValueError( + f"Cannot save custom gradient {op_type} called in function {fn} " + "because SavedModel is unable to serialize the captured " + f"inputs: {bad_captures}" + ) + + saveable_view.gradient_functions.append(grad_fn) + func_graph_map[grad_fn.graph] = grad_fn + + grad_def = function_pb2.RegisteredGradient() + grad_def.gradient_func = grad_fn.name + grad_def.registered_op_type = op_type + saveable_view.gradient_defs.append(grad_def) + + +def _fill_meta_graph_def( + meta_graph_def: meta_graph_pb2.MetaGraphDef, + saveable_view: _SaveableView, + signature_functions: Dict[str, Callable[..., Any]], + namespace_whitelist: List[str], + save_custom_gradients: bool, + create_saver: bool, + defaults=None, +) -> Tuple[_AssetInfo, ops.Graph]: + """Generates a MetaGraph which calls `signature_functions`. + + Args: + meta_graph_def: The MetaGraphDef proto to fill. + saveable_view: The _SaveableView being exported. + signature_functions: A dictionary mapping signature keys to concrete + functions containing signatures to add to the MetaGraph. + namespace_whitelist: List of strings containing whitelisted op namespaces. + save_custom_gradients: Whether to save custom gradients. + create_saver: Whether to add SavedModel's native save and restore ops. + defaults: A dictionary mapping signature_key to dictionary of + user_specified_name to Tensor representing default values. + + Returns: + A tuple of (_AssetInfo, Graph) containing the captured assets and + exported Graph generated from tracing the saveable_view. + """ + # List objects from the eager context to make sure Optimizers give us the + # right Graph-dependent variables. + resource_initializers = saveable_view.get_concrete_resource_initializers() + exported_graph = ops.Graph() + resource_initializer_ops = [] + with exported_graph.as_default(): + object_map, tensor_map, asset_info = saveable_view.map_resources() + signatures = _generate_signatures(signature_functions, object_map, defaults) + if save_custom_gradients: + # Custom gradients functions must be traced in the same context as the + # when they are registered. + _trace_gradient_functions(exported_graph, saveable_view) + with exported_graph.as_default(): + # Create initializers for assets and resources. + for resource_initializer_function in resource_initializers: + asset_dependencies = [] + for capture in resource_initializer_function.graph.external_captures: + asset_initializer = asset_info.asset_initializers_by_resource.get( + capture, None) + if asset_initializer is not None: + asset_dependencies.append(asset_initializer) + with ops.control_dependencies(asset_dependencies): + mapped_initializer = object_map[resource_initializer_function] + resource_initializer_ops.append(mapped_initializer()) + resource_initializer_ops.extend( + asset_info.asset_initializers_by_resource.values()) + with ops.control_dependencies(resource_initializer_ops): + init_op = control_flow_ops.no_op() + # Add the same op to the main_op collection and to the init_op + # signature. The collection is for compatibility with older loader APIs; + # only one will be executed. + meta_graph_def.collection_def[constants.MAIN_OP_KEY].node_list.value.append( + init_op.name) + meta_graph_def.signature_def[constants.INIT_OP_SIGNATURE_KEY].CopyFrom( + signature_def_utils.op_signature_def(init_op, + constants.INIT_OP_SIGNATURE_KEY)) + + # Saving an object-based checkpoint again gathers variables. We need to do the + # gathering from the eager context so Optimizers save the right set of + # variables, but want any operations associated with the save/restore to be in + # the exported graph (thus the `to_graph` argument). + def call_with_mapped_captures(function, args): + if function in object_map: + return object_map[function](*args) + # Registered saver/restore functions do not appear in `object_map`, because + # they are not in the object graph. + return saved_model_exported_concrete.ExportedConcreteFunction( + function, tensor_map)(*args) + + for obj in object_map.values(): + obj._maybe_initialize_trackable() # pylint: disable=protected-access + named_saveable_objects, registered_savers = ( + save_util_v1.frozen_saveables_and_savers( + graph_view=saveable_view.augmented_graph_view, + object_map=object_map, + to_graph=exported_graph, + call_with_mapped_captures=call_with_mapped_captures)) + + if create_saver: + saver = functional_saver.MultiDeviceSaver.from_saveables( + named_saveable_objects, registered_savers, call_with_mapped_captures + ) + + with exported_graph.as_default(): + saver_def = saver.to_proto() + meta_graph_def.saver_def.CopyFrom(saver_def) + + # At this point all nodes that can be added to the SavedObjectGraph have been + # added, so run the following to validate deserialization dependencies. + _dependency_sorted_node_ids(saveable_view) + + graph_def, _ = exported_graph._as_graph_def( # pylint: disable=protected-access + add_shapes=True, use_pybind11_proto=False) + graph_def.library.registered_gradients.extend(saveable_view.gradient_defs) + _verify_ops(graph_def, namespace_whitelist) + + meta_graph_def.graph_def.CopyFrom(graph_def) + meta_graph_def.meta_info_def.tags.append(tag_constants.SERVING) + meta_graph_def.meta_info_def.tensorflow_version = versions.__version__ + meta_graph_def.meta_info_def.tensorflow_git_version = ( + versions.__git_version__) + # We currently always strip default attributes. + meta_graph_def.meta_info_def.stripped_default_attrs = True + meta_graph_def.meta_info_def.stripped_op_list.MergeFrom( + meta_graph.stripped_op_list_for_graph(meta_graph_def.graph_def)) + meta_graph_def.asset_file_def.extend(asset_info.asset_defs) + for signature_key, signature in signatures.items(): + meta_graph_def.signature_def[signature_key].CopyFrom(signature) + meta_graph.strip_graph_default_valued_attrs(meta_graph_def) + # store tensor_content in litle endian format + if sys.byteorder == "big": + utils_impl.swap_function_tensor_content(meta_graph_def, "big", "little") + return asset_info, exported_graph + + +def _verify_ops(graph_def: graph_pb2.GraphDef, namespace_whitelist): + """Verifies that all namespaced ops in the graph are whitelisted. + + Args: + graph_def: the GraphDef to validate. + namespace_whitelist: a list of namespaces to allow. If `None`, all will be + allowed. If an op does not have a namespace, it will be allowed. + + Raises: + ValueError: If the graph contains ops that violate the whitelist. + """ + # By default, if the user has not specified a whitelist, we want to allow + # everything. We check for None directly rather than falseness, since the + # user may instead want to pass an empty list to disallow all custom + # namespaced ops. + if namespace_whitelist is None: + return + + invalid_ops = [] + invalid_namespaces = set() + + all_operations = [] + all_operations.extend(meta_graph.ops_used_by_graph_def(graph_def)) + + for op in all_operations: + if ">" in op: + namespace = op.split(">")[0] + if namespace not in namespace_whitelist: + invalid_ops.append(op) + invalid_namespaces.add(namespace) + if invalid_ops: + raise ValueError( + "Attempted to save ops from non-whitelisted namespaces to SavedModel: " + f"{invalid_ops}.\nPlease verify that these ops should be saved, since " + "they must be available when loading the SavedModel. If loading from " + "Python, you must import the library defining these ops. From C++, " + "link the custom ops to the serving binary. Once you've confirmed this," + " add the following namespaces to the `namespace_whitelist` " + f"argument in tf.saved_model.SaveOptions: {invalid_namespaces}.") + + +def _dependency_sorted_node_ids(saveable_view: _SaveableView): + """Returns topologically sorted nodes, sorted by dependencies.""" + dependency_map = {} + for node in saveable_view.nodes: + node_id = saveable_view.node_ids[node] + deps = dependency_map[node_id] = [] + # TODO(kathywu): Remove once all of these have been converted to trackable. + if isinstance(node, _CapturedTensor): + continue # These are not `Trackable` and therefore have no dependencies. + for _, dep in saveable_view.augmented_graph_view.list_dependencies(node): + if dep not in saveable_view.node_ids: + node_path = trackable_utils.pretty_print_node_path( + saveable_view.node_paths[node]) + raise ValueError( + f"Found an untracked dependency. Object {node_path} depends " + f"on {dep}, but this dependency isn't listed as a child. " + "Please track this child by overriding `_trackable_children` " + "or use `._track_trackable`.") + deps.append(saveable_view.node_ids[dep]) + try: + return trackable_utils.order_by_dependency(dependency_map) + except trackable_utils.CyclicDependencyError as err: + pretty_printed_nodes = [] + pretty_printed_dependencies = [] + + for x, deps in err.leftover_dependency_map.items(): + node_path = trackable_utils.pretty_print_node_path( + saveable_view.node_paths[saveable_view.nodes[x]]) + pretty_printed_nodes.append( + f"\tNode {x} = {node_path} (type {type(saveable_view.nodes[x])})") + pretty_printed_dependencies.append(f"\tNode {x} depends on nodes {deps}") + pretty_printed_nodes = "\n".join(pretty_printed_nodes) + pretty_printed_dependencies = "\n".join(pretty_printed_dependencies) + raise ValueError( + "There is one or more dependency cycle in the saved Trackable object. " + "Saving cannot continue until this cycle is resolved." + f"\n>> Unresolved nodes:\n{pretty_printed_nodes}" + f"\n>> Unresolved cyclic dependencies:\n{pretty_printed_dependencies}") + + +def _serialize_object_graph( + saveable_view: _SaveableView, asset_file_def_index +): + """Save a SavedObjectGraph proto for `root`.""" + # SavedObjectGraph is similar to the TrackableObjectGraph proto in the + # checkpoint. It will eventually go into the SavedModel. + proto = saved_object_graph_pb2.SavedObjectGraph() + saveable_view.fill_object_graph_proto(proto) + + for concrete_function in saveable_view.concrete_and_gradient_functions: + name = compat.as_text(concrete_function.name) + serialized = function_serialization.serialize_concrete_function( + concrete_function, saveable_view.captured_tensor_node_ids + ) + if serialized is not None: + proto.concrete_functions[name].CopyFrom(serialized) + + for obj, obj_proto in zip(saveable_view.nodes, proto.nodes): + _write_object_proto( + obj, + obj_proto, + asset_file_def_index, + saveable_view.augmented_graph_view.list_children, + ) + return proto + + +def _write_object_proto( + obj, + proto: saved_object_graph_pb2.SavedObject, + asset_file_def_index, + list_children_fn, +): + """Saves an object into SavedObject proto.""" + if isinstance(obj, asset.Asset): + proto.asset.SetInParent() + proto.asset.asset_file_def_index = asset_file_def_index[obj] + elif resource_variable_ops.is_resource_variable(obj): + options = save_context.get_save_options() + obj._write_object_proto(proto, options) # pylint: disable=protected-access + elif isinstance(obj, def_function.Function): + proto.function.CopyFrom( + function_serialization.serialize_function( + obj, [x.ref for x in list_children_fn(obj)])) + elif isinstance(obj, defun.ConcreteFunction): + proto.bare_concrete_function.CopyFrom( + function_serialization.serialize_bare_concrete_function(obj)) + elif isinstance(obj, _CapturedTensor): + proto.captured_tensor.name = obj.name + proto.captured_tensor.concrete_function = obj.concrete_function + elif isinstance(obj, resource.CapturableResource): + proto.resource.device = obj._resource_device # pylint: disable=protected-access + else: + registered_type_proto = revived_types.serialize(obj) + if registered_type_proto is None: + # Fallback for types with no matching registration + # pylint:disable=protected-access + registered_type_proto = saved_object_graph_pb2.SavedUserObject( + identifier=obj._object_identifier, + version=versions_pb2.VersionDef( + producer=1, min_consumer=1, bad_consumers=[])) + # pylint:enable=protected-access + proto.user_object.CopyFrom(registered_type_proto) + + registered_name = registration.get_registered_class_name(obj) + if registered_name: + proto.registered_name = registered_name + serialized_user_proto = obj._serialize_to_proto(object_proto=proto) # pylint: disable=protected-access + if serialized_user_proto is not None: + proto.serialized_user_proto.Pack(serialized_user_proto) + + +def _export_debug_info(exported_graph: ops.Graph, export_dir: str): + """Exports debug information from graph to file. + + Creates and writes GraphDebugInfo with traces for ops in all functions of the + exported_graph. + + Args: + exported_graph: A Graph that has been created by tracing a saveable view. + export_dir: SavedModel directory in which to write the debug info. + """ + debug_builder = tf_stack.GraphDebugInfoBuilder() + for fn_name in exported_graph._functions: # pylint: disable=protected-access + fn = exported_graph._get_function(fn_name) # pylint: disable=protected-access + if not isinstance(fn, defun.AtomicFunction): # pylint: disable=protected-access + continue + debug_builder.AppendGraphDebugInfo(fn_name, fn.graph_debug_info) + + graph_debug_info = debug_builder.Build() + file_io.atomic_write_string_to_file( + file_io.join( + path_helpers.get_or_create_debug_dir(export_dir), + constants.DEBUG_INFO_FILENAME_PB), + graph_debug_info.SerializeToString(deterministic=True)) + + +@tf_export( + "saved_model.save", + v1=["saved_model.save", "saved_model.experimental.save"]) +def save( + obj, + export_dir: str, + signatures=None, + options: save_options.SaveOptions = None, +): + # pylint: disable=line-too-long + """Exports a [tf.Module](https://www.tensorflow.org/api_docs/python/tf/Module) (and subclasses) `obj` to [SavedModel format](https://www.tensorflow.org/guide/saved_model#the_savedmodel_format_on_disk). + + The `obj` must inherit from the [`Trackable` + class](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/trackable/base.py#L278). + + Example usage: + + >>> class Adder(tf.Module): + ... @tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.float32)]) + ... def add(self, x): + ... return x + x + + >>> model = Adder() + >>> tf.saved_model.save(model, '/tmp/adder') + + The resulting SavedModel is then servable with an input named "x", a scalar + with dtype float32. + + _Signatures_ + + Signatures define the input and output types for a computation. The optional + save `signatures` argument controls which methods in `obj` will be + available to programs which consume `SavedModel`s, for example, serving + APIs. Python functions may be decorated with + `@tf.function(input_signature=...)` and passed as signatures directly, or + lazily with a call to `get_concrete_function` on the method decorated with + `@tf.function`. + + Example: + + >>> class Adder(tf.Module): + ... @tf.function + ... def add(self, x): + ... return x + x + + >>> model = Adder() + >>> tf.saved_model.save( + ... model, '/tmp/adder',signatures=model.add.get_concrete_function( + ... tf.TensorSpec([], tf.float32))) + + If a `@tf.function` does not have an input signature and + `get_concrete_function` is not called on that method, the function will not + be directly callable in the restored SavedModel. + + Example: + + >>> class Adder(tf.Module): + ... @tf.function + ... def add(self, x): + ... return x + x + + >>> model = Adder() + >>> tf.saved_model.save(model, '/tmp/adder') + >>> restored = tf.saved_model.load('/tmp/adder') + >>> restored.add(1.) + Traceback (most recent call last): + ... + ValueError: Found zero restored functions for caller function. + + If the `signatures` argument is omitted, `obj` will be searched for + `@tf.function`-decorated methods. If exactly one traced `@tf.function` is + found, that method will be used as the default signature for the SavedModel. + Else, any `@tf.function` attached to `obj` or its dependencies will be + exported for use with `tf.saved_model.load`. + + When invoking a signature in an exported SavedModel, `Tensor` arguments are + identified by name. These names will come from the Python function's argument + names by default. They may be overridden by specifying a `name=...` argument + in the corresponding `tf.TensorSpec` object. Explicit naming is required if + multiple `Tensor`s are passed through a single argument to the Python + function. + + The outputs of functions used as `signatures` must either be flat lists, in + which case outputs will be numbered, or a dictionary mapping string keys to + `Tensor`, in which case the keys will be used to name outputs. + + Signatures are available in objects returned by `tf.saved_model.load` as a + `.signatures` attribute. This is a reserved attribute: `tf.saved_model.save` + on an object with a custom `.signatures` attribute will raise an exception. + + _Using `tf.saved_model.save` with Keras models_ + + While Keras has its own [saving and loading + API](https://www.tensorflow.org/guide/keras/save_and_serialize), + this function can be used to export Keras models. For example, exporting with + a signature specified: + + >>> class Adder(tf.keras.Model): + ... @tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.string)]) + ... def concat(self, x): + ... return x + x + + >>> model = Adder() + >>> tf.saved_model.save(model, '/tmp/adder') + + Exporting from a function without a fixed signature: + + >>> class Adder(tf.keras.Model): + ... @tf.function + ... def concat(self, x): + ... return x + x + + >>> model = Adder() + >>> tf.saved_model.save( + ... model, '/tmp/adder', + ... signatures=model.concat.get_concrete_function( + ... tf.TensorSpec(shape=[], dtype=tf.string, name="string_input"))) + + `tf.keras.Model` instances constructed from inputs and outputs already have a + signature and so do not require a `@tf.function` decorator or a `signatures` + argument. If neither are specified, the model's forward pass is exported. + + >>> x = tf.keras.layers.Input((4,), name="x") + >>> y = tf.keras.layers.Dense(5, name="out")(x) + >>> model = tf.keras.Model(x, y) + >>> tf.saved_model.save(model, '/tmp/saved_model/') + + The exported SavedModel takes "x" with shape [None, 4] and returns "out" + with shape [None, 5] + + _Variables and Checkpoints_ + + Variables must be tracked by assigning them to an attribute of a tracked + object or to an attribute of `obj` directly. TensorFlow objects (e.g. layers + from `tf.keras.layers`, optimizers from `tf.train`) track their variables + automatically. This is the same tracking scheme that `tf.train.Checkpoint` + uses, and an exported `Checkpoint` object may be restored as a training + checkpoint by pointing `tf.train.Checkpoint.restore` to the SavedModel's + "variables/" subdirectory. + + `tf.function` does not hard-code device annotations from outside the function + body, instead of using the calling context's device. This means for example + that exporting a model that runs on a GPU and serving it on a CPU will + generally work, with some exceptions: + + * `tf.device` annotations inside the body of the function will be hard-coded + in the exported model; this type of annotation is discouraged. + * Device-specific operations, e.g. with "cuDNN" in the name or with + device-specific layouts, may cause issues. + * For `ConcreteFunctions`, active distribution strategies will cause device + placements to be hard-coded in the function. + + SavedModels exported with `tf.saved_model.save` [strip default-valued + attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes) + automatically, which removes one source of incompatibilities when the consumer + of a SavedModel is running an older TensorFlow version than the + producer. There are however other sources of incompatibilities which are not + handled automatically, such as when the exported model contains operations + which the consumer does not have definitions for. + + Args: + obj: A trackable object (e.g. tf.Module or tf.train.Checkpoint) to export. + export_dir: A directory in which to write the SavedModel. + signatures: Optional, one of three types: + * A `tf.function` with an input signature specified, which will use the + default serving signature key. + * The result of `f.get_concrete_function` on a `@tf.function`-decorated + function `f`, in which case `f` will be used to generate a signature for + the SavedModel under the default serving signature key. + * A dictionary, which maps signature keys to either `tf.function` + instances with input signatures or concrete functions. Keys of such a + dictionary may be arbitrary strings, but will typically be from the + `tf.saved_model.signature_constants` module. + options: `tf.saved_model.SaveOptions` object for configuring save options. + + Raises: + ValueError: If `obj` is not trackable. + + @compatibility(eager) + Not well supported when graph building. From TensorFlow 1.x, + `tf.compat.v1.enable_eager_execution()` should run first. Calling + tf.saved_model.save in a loop when graph building from TensorFlow 1.x will + add new save operations to the default graph each iteration. + + May not be called from within a function body. + @end_compatibility + """ + if isinstance(export_dir, os.PathLike): + export_dir = os.fspath(export_dir) + # pylint: enable=line-too-long + metrics.IncrementWriteApi(_SAVE_V2_LABEL) + save_and_return_nodes(obj, export_dir, signatures, options) + + metrics.IncrementWrite(write_version="2") + + +def save_and_return_nodes( + obj, + export_dir, + signatures=None, + options: save_options.SaveOptions = None, + experimental_skip_checkpoint=False, +): + """Saves a SavedModel while returning all saved nodes and their paths. + + Please see `tf.saved_model.save` for details. + + Args: + obj: A trackable object to export. + export_dir: A directory in which to write the SavedModel. + signatures: A function or dictionary of functions to save in the SavedModel + as signatures. + options: `tf.saved_model.SaveOptions` object for configuring save options. + experimental_skip_checkpoint: If set to `True`, the checkpoint will not be + written. + + Returns: + A tuple of (a list of saved nodes in the order they are serialized to the + `SavedObjectGraph`, dictionary mapping nodes to one possible path from + the root node to the key node) + """ + options = options or save_options.SaveOptions() + saved_model = saved_model_pb2.SavedModel() + meta_graph_def = saved_model.meta_graphs.add() + + _, exported_graph, object_saver, asset_info, saved_nodes, node_paths = ( + _build_meta_graph(obj, signatures, options, meta_graph_def)) + saved_model.saved_model_schema_version = ( + constants.SAVED_MODEL_SCHEMA_VERSION) + + # Write the checkpoint, copy assets into the assets directory, and write out + # the SavedModel proto itself. + if not experimental_skip_checkpoint: + path_helpers.get_or_create_variables_dir(export_dir) + ckpt_options = checkpoint_options.CheckpointOptions( + experimental_io_device=options.experimental_io_device) + object_saver.save( + path_helpers.get_variables_path(export_dir), options=ckpt_options) + builder_impl.copy_assets_to_destination_dir(asset_info.asset_filename_map, + export_dir) + # Note that this needs to be the last file operation when saving the + # SavedModel. Users rely on checking saved_model_dir/saved_model.pb as an + # indication that the SavedModel is completely written. + if context.executing_eagerly(): + try: + context.async_wait() # Ensure save operations have completed. + except errors.NotFoundError as err: + raise FileNotFoundError( + f"{err}\n You may be trying to save on a different device from the " + "computational device. Consider setting the " + "`experimental_io_device` option in `tf.saved_model.SaveOptions` " + "to the io_device such as '/job:localhost'.") from err + + # We will slowly migrate code in this function to pywrap_saved_model.Save + # as we build up the C++ API. + pywrap_saved_model.Save(export_dir) + + if options.experimental_image_format: + prefix = file_io.join( + compat.as_str(export_dir), + "saved_model") + proto_splitter.SavedModelSplitter(saved_model).write(prefix) + else: + path = file_io.join( + compat.as_str(export_dir), + compat.as_str(constants.SAVED_MODEL_FILENAME_PB)) + file_io.atomic_write_string_to_file( + path, saved_model.SerializeToString(deterministic=True)) + fingerprinting_utils.write_fingerprint(export_dir) + + # Save debug info, if requested. + if options.save_debug_info: + _export_debug_info(exported_graph, export_dir) + # For privacy concerns, please see the note in + # tensorflow/cc/saved_model/metrics.h + metrics.SetWritePath(saved_model_path=str(export_dir)) + # Clean reference cycles so repeated export()s don't make work for the garbage + # collector. Before this point, we need to keep references to captured + # constants in the saved graph. + ops.dismantle_graph(exported_graph) + + return saved_nodes, node_paths + + +def export_meta_graph( + obj, + filename: str, + signatures=None, + options: save_options.SaveOptions = None, +): + """Exports the MetaGraph proto of the `obj` to a file. + + This function goes through the same procedures saved_model.save goes to + produce the given object's MetaGraph, then saves it to the given file. It + skips saving checkpoint information, and is useful when all one wants is the + graph defining the model. + + Args: + obj: A trackable object to build the MetaGraph from. + filename: The file into which to write the MetaGraph. + signatures: Optional, either a `tf.function` with an input signature + specified or the result of `f.get_concrete_function` on a + `@tf.function`-decorated function `f`, in which case `f` will be used to + generate a signature for the SavedModel under the default serving + signature key. `signatures` may also be a dictionary, in which case it + maps from signature keys to either `tf.function` instances with input + signatures or concrete functions. The keys of such a dictionary may be + arbitrary strings, but will typically be from the + `tf.saved_model.signature_constants` module. + options: Optional, `tf.saved_model.SaveOptions` object that specifies + options for saving. + """ + options = options or save_options.SaveOptions() + export_dir = os.path.dirname(filename) + meta_graph_def, exported_graph, _, _, _, _ = _build_meta_graph( + obj, signatures, options) + + file_io.atomic_write_string_to_file( + filename, meta_graph_def.SerializeToString(deterministic=True)) + + # Save debug info, if requested. + if options.save_debug_info: + _export_debug_info(exported_graph, export_dir) + + # Clean reference cycles so repeated export()s don't make work for the garbage + # collector. Before this point, we need to keep references to captured + # constants in the saved graph. + ops.dismantle_graph(exported_graph) + + +def _build_meta_graph_impl( + obj, signatures, options: save_options.SaveOptions, meta_graph_def=None +): + """Creates a MetaGraph containing the resources and functions of an object.""" + if ops.inside_function(): + raise AssertionError( + "`tf.saved_model.save` is not supported inside a traced @tf.function. " + "Move the call to the outer eagerly-executed context." + ) + # pylint: enable=line-too-long + if not isinstance(obj, base.Trackable): + raise ValueError( + "Expected an object of type `Trackable`, such as `tf.Module` or a " + f"subclass of the `Trackable` class, for export. Got {obj} " + f"with type {type(obj)}." + ) + meta_graph_def = meta_graph_def or meta_graph_pb2.MetaGraphDef() + + augmented_graph_view = _AugmentedGraphView(obj) + if signatures is None: + signatures = signature_serialization.find_function_to_export( + augmented_graph_view + ) + + signatures, wrapped_functions, defaults = ( + signature_serialization.canonicalize_signatures(signatures) + ) + signature_serialization.validate_augmented_graph_view(augmented_graph_view) + signature_map = signature_serialization.create_signature_map(signatures) + augmented_graph_view.set_signature(signature_map, wrapped_functions) + + # Use _SaveableView to provide a frozen listing of properties and functions. + saveable_view = _SaveableView(augmented_graph_view, options) + object_saver = checkpoint.TrackableSaver(augmented_graph_view) + asset_info, exported_graph = _fill_meta_graph_def( + meta_graph_def=meta_graph_def, + saveable_view=saveable_view, + signature_functions=signatures, + namespace_whitelist=options.namespace_whitelist, + save_custom_gradients=options.experimental_custom_gradients, + create_saver=not options.experimental_skip_saver, + defaults=defaults, + ) + if options.function_aliases: + function_aliases = meta_graph_def.meta_info_def.function_aliases + for alias, func in options.function_aliases.items(): + if isinstance(func, types_core.ConcreteFunction): + function_aliases[func.name] = alias + elif isinstance(func, polymorphic_function.Function): + for fdef in func._list_all_concrete_functions(): # pylint: disable=protected-access + function_aliases[fdef.name] = alias + elif isinstance(func, collections.abc.Iterable) and all( + isinstance(x, types_core.ConcreteFunction) for x in func + ): + for entry in func: + function_aliases[entry.name] = alias + else: + raise TypeError( + f"Unsupported type f{type(func)}. Functions in `function_aliases`" + " should be created by tf.function, or concrete functions, or" + " collections of concrete functions." + ) + object_graph_proto = _serialize_object_graph( + saveable_view, asset_info.asset_index + ) + meta_graph_def.object_graph_def.CopyFrom(object_graph_proto) + return ( + meta_graph_def, + exported_graph, + object_saver, + asset_info, + saveable_view.nodes, + saveable_view.node_paths, + ) + + +def _build_meta_graph( + obj, + signatures, + options: save_options.SaveOptions, + meta_graph_def: meta_graph_pb2.MetaGraphDef = None, +): + """Creates a MetaGraph under a save context. + + Args: + obj: A trackable object to build the MetaGraph from. + signatures: Can be a `tf.function` with an input signature specified or the + result of `f.get_concrete_function` on a `@tf.function`-decorated function + `f`. `signatures` may also be a dictionary, in which case it maps from + signature keys to `tf.function` instances. If None, finds signature to + export from the `@tf.function`-decorated methods in `obj`. + options: `tf.saved_model.SaveOptions` object that specifies options for + saving. + meta_graph_def: Optional, the MetaGraphDef proto fill. + + Raises: + AssertionError: If `export_meta_graph` is executing inside a `tf.function`. + ValueError: If `obj` is not trackable. + + Returns: + meta_graph_def: Filled MetaGraphDef proto + exported_graph: `tf.Graph` object generated from `obj`. + object_saver: `checkpoint.TrackableSaver` of the `obj` and its dependencies. + asset_info: `_AssetInfo` tuple containing external assets in the `obj`. + saveable_view.nodes: _SaveableView nodes. + saveable_view.node_paths: _SaveableView paths. + """ + + with save_context.save_context(options): + return _build_meta_graph_impl(obj, signatures, options, meta_graph_def) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_context.py new file mode 100644 index 0000000000000000000000000000000000000000..00f93e82f961abd69c228a1f74ff45781dc81e36 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_context.py @@ -0,0 +1,66 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Context for building SavedModel.""" + +import contextlib +import threading + + +class SaveContext(threading.local): + """A context for building a graph of SavedModel.""" + + def __init__(self): + super(SaveContext, self).__init__() + self._in_save_context = False + self._options = None + + def options(self): + if not self.in_save_context(): + raise ValueError("Not in a SaveContext.") + return self._options + + def enter_save_context(self, options): + self._in_save_context = True + self._options = options + + def exit_save_context(self): + self._in_save_context = False + self._options = None + + def in_save_context(self): + return self._in_save_context + +_save_context = SaveContext() + + +@contextlib.contextmanager +def save_context(options): + if in_save_context(): + raise ValueError("Already in a SaveContext.") + _save_context.enter_save_context(options) + try: + yield + finally: + _save_context.exit_save_context() + + +def in_save_context(): + """Returns whether under a save context.""" + return _save_context.in_save_context() + + +def get_save_options(): + """Returns the save options if under a save context.""" + return _save_context.options() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_options.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_options.py new file mode 100644 index 0000000000000000000000000000000000000000..729a2562d9f91ba7d2bfe04f7c5c2970f42b7731 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/save_options.py @@ -0,0 +1,214 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Options for saving SavedModels.""" + +import enum + +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + + +is_oss = True # Updated by copybara. + + +@tf_export("saved_model.experimental.VariablePolicy") +class VariablePolicy(enum.Enum): + """Enum defining options for variable handling when saving. + + NONE + No policy applied: Distributed variables are saved as one variable, with no + device attached. + + SAVE_VARIABLE_DEVICES + When saving variables, also save their device assignment. + This is useful if one wants to hardcode devices in saved models, but it also + makes them non-portable if soft device placement is disabled (more details + in `tf.config.set_soft_device_placement`). This is currently not + fully supported by `saved_model.load`, and is mainly intended to be used + when one will be reading the saved model at a lower API level. In the + example below, the graph saved by the call to `saved_model.save` will have + the variable devices correctly specified: + ```python + exported = tf.train.Checkpoint() + with tf.device('/GPU:0'): + exported.x_gpu = tf.Variable(1.0) + with tf.device('/CPU:0'): + exported.x_cpu = tf.Variable(1.0) + tf.saved_model.save(exported, export_dir, + options = tf.saved_model.SaveOptions( + experimental_variable_policy= + tf.saved_model.experimental.VariablePolicy.SAVE_VARIABLE_DEVICES)) + ``` + Distributed variables are still saved as one variable under this policy. + + EXPAND_DISTRIBUTED_VARIABLES + Distributed variables will be saved with information about their components, + allowing for their restoration on load. Also, the saved graph will contain + references to those variables. This is useful when one wants to use the + model for training in environments where the original distribution strategy + is not available. + """ + + NONE = None + + SAVE_VARIABLE_DEVICES = "save_variable_devices" + + EXPAND_DISTRIBUTED_VARIABLES = "expand_distributed_variables" + + def _save_variable_devices(self): + """Checks whether variable devices should be saved.""" + return self != VariablePolicy.NONE + + def _expand_distributed_variables(self): + """Checks whether distributed variables should be expanded.""" + return self == VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES + + @staticmethod + def from_obj(obj): + """Tries to convert `obj` to a VariablePolicy instance.""" + if obj is None: + return VariablePolicy.NONE + if isinstance(obj, VariablePolicy): + return obj + key = str(obj).lower() + for policy in VariablePolicy: + if key == policy.value: + return policy + raise ValueError(f"Received invalid VariablePolicy value: {obj}.") + + +@tf_export("saved_model.SaveOptions") +class SaveOptions: + """Options for saving to SavedModel. + + This function may be used in the `options` argument in functions that + save a SavedModel (`tf.saved_model.save`, `tf.keras.models.save_model`). + """ + + # Define object attributes in __slots__ for improved memory and performance. + __slots__ = ( + "namespace_whitelist", + "save_debug_info", + "function_aliases", + "experimental_io_device", + "experimental_variable_policy", + "experimental_custom_gradients", + "experimental_image_format", + "experimental_skip_saver", + ) + + def __init__( + self, + namespace_whitelist=None, + save_debug_info=False, + function_aliases=None, + experimental_io_device=None, + experimental_variable_policy=None, + experimental_custom_gradients=True, + experimental_image_format=False, + experimental_skip_saver=False, + ): + """Creates an object that stores options for SavedModel saving. + + Args: + namespace_whitelist: List of strings containing op namespaces to whitelist + when saving a model. Saving an object that uses namespaced ops must + explicitly add all namespaces to the whitelist. The namespaced ops must + be registered into the framework when loading the SavedModel. If no + whitelist is provided, all namespaced ops will be allowed. + save_debug_info: Boolean indicating whether debug information is saved. If + True, then a debug/saved_model_debug_info.pb file will be written with + the contents of a GraphDebugInfo binary protocol buffer containing stack + trace information for all ops and functions that are saved. + function_aliases: Python dict. Mapping from string to object returned by + @tf.function. A single tf.function can generate many ConcreteFunctions. + If a downstream tool wants to refer to all concrete functions generated + by a single tf.function you can use the `function_aliases` argument to + store a map from the alias name to all concrete function names. E.g. >>> + class Adder(tf.Module): ... @tf.function ... def double(self, x): + ... return x + x >>> model = Adder() >>> + model.double.get_concrete_function( ... tf.TensorSpec(shape=[], + dtype=tf.float32, name="float_input")) >>> + model.double.get_concrete_function( ... tf.TensorSpec(shape=[], + dtype=tf.string, name="string_input")) >>> options = + tf.saved_model.SaveOptions( ... function_aliases={'double': + model.double}) >>> tf.saved_model.save(model, '/tmp/adder', + options=options) + experimental_io_device: string. Applies in a distributed setting. + Tensorflow device to use to access the filesystem. If `None` (default) + then for each variable the filesystem is accessed from the CPU:0 device + of the host where that variable is assigned. If specified, the + filesystem is instead accessed from that device for all variables. This + is for example useful if you want to save to a local directory, such as + "/tmp" when running in a distributed setting. In that case pass a device + for the host where the "/tmp" directory is accessible. + experimental_variable_policy: The policy to apply to variables when + saving. This is either a `saved_model.experimental.VariablePolicy` enum + instance or one of its value strings (case is not important). See that + enum documentation for details. A value of `None` corresponds to the + default policy. + experimental_custom_gradients: Boolean. When True, will save traced + gradient functions for the functions decorated by `tf.custom_gradient`. + Defaults to `True`. + experimental_image_format: New (highly) experimental format that is + capable of saving models larger than the 2GB protobuf limit. Enabling + this option will likely break compatibility with downstream consumers. + This option is currently disabled in OSS. + experimental_skip_saver: If True, will prevent SavedModel from creating + its native checkpointing ops - this is for models that do not use + SavedModel's native checkpointing functionality to avoid the costs + associated with creating and serializing those ops. + """ + self.namespace_whitelist = _validate_namespace_whitelist( + namespace_whitelist + ) + self.save_debug_info = save_debug_info + self.function_aliases = function_aliases if function_aliases else dict() + self.experimental_custom_gradients = experimental_custom_gradients + self.experimental_io_device = experimental_io_device + self.experimental_variable_policy = VariablePolicy.from_obj( + experimental_variable_policy + ) + self.experimental_skip_saver = experimental_skip_saver + + # TODO(b/277279153): Enable image format in OSS after proto splitter is + # public. + if experimental_image_format and is_oss: + raise ValueError( + "The option `experimental_image_format` is disabled in OSS." + ) + self.experimental_image_format = experimental_image_format + + +def _validate_namespace_whitelist(namespace_whitelist): + """Validates namespace whitelist argument.""" + if namespace_whitelist is None: + return None + if not isinstance(namespace_whitelist, list): + raise TypeError( + "`namespace_whitelist` must be a list of strings. Got: " + f"{namespace_whitelist} with type " + f"{type(namespace_whitelist)}." + ) + + processed = [] + for namespace in namespace_whitelist: + if not isinstance(namespace, str): + raise ValueError( + "Whitelisted namespace must be a string. Got: " + f"{namespace} of type {type(namespace)}." + ) + processed.append(compat.as_str(namespace)) + return processed diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/saved_model.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/saved_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ec02a9dac795bb6f41aa29a766ae780ac7accd28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/saved_model.py @@ -0,0 +1,36 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Convenience functions to save a model. +""" + + +# pylint: disable=unused-import +from tensorflow.python.saved_model import builder +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import loader +from tensorflow.python.saved_model import main_op +from tensorflow.python.saved_model import method_name_updater +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.saved_model import utils +from tensorflow.python.saved_model.fingerprinting import Fingerprint +from tensorflow.python.saved_model.fingerprinting import read_fingerprint +from tensorflow.python.saved_model.load import load +from tensorflow.python.saved_model.save import save +# pylint: enable=unused-import +# pylint: disable=wildcard-import +from tensorflow.python.saved_model.simple_save import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ae9917958c1cad35c46e68d418d1a025ed0fd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_constants.py @@ -0,0 +1,143 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Signature constants for SavedModel save and restore operations. + +""" +from tensorflow.python.util.tf_export import tf_export + + +# Key in the signature def map for `default` serving signatures. The default +# signature is used in inference requests where a specific signature was not +# specified. +DEFAULT_SERVING_SIGNATURE_DEF_KEY = "serving_default" +tf_export( + "saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY", + v1=[ + "saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY", + "saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY" + ], +).export_constant(__name__, "DEFAULT_SERVING_SIGNATURE_DEF_KEY") + +################################################################################ +# Classification API constants. + +# Classification inputs. +CLASSIFY_INPUTS = "inputs" +tf_export( + "saved_model.CLASSIFY_INPUTS", + v1=[ + "saved_model.CLASSIFY_INPUTS", + "saved_model.signature_constants.CLASSIFY_INPUTS" + ]).export_constant(__name__, "CLASSIFY_INPUTS") + +# Classification method name used in a SignatureDef. +CLASSIFY_METHOD_NAME = "tensorflow/serving/classify" +tf_export( + "saved_model.CLASSIFY_METHOD_NAME", + v1=[ + "saved_model.CLASSIFY_METHOD_NAME", + "saved_model.signature_constants.CLASSIFY_METHOD_NAME" + ]).export_constant(__name__, "CLASSIFY_METHOD_NAME") + +# Classification classes output. +CLASSIFY_OUTPUT_CLASSES = "classes" +tf_export( + "saved_model.CLASSIFY_OUTPUT_CLASSES", + v1=[ + "saved_model.CLASSIFY_OUTPUT_CLASSES", + "saved_model.signature_constants.CLASSIFY_OUTPUT_CLASSES" + ]).export_constant(__name__, "CLASSIFY_OUTPUT_CLASSES") + +# Classification scores output. +CLASSIFY_OUTPUT_SCORES = "scores" +tf_export( + "saved_model.CLASSIFY_OUTPUT_SCORES", + v1=[ + "saved_model.CLASSIFY_OUTPUT_SCORES", + "saved_model.signature_constants.CLASSIFY_OUTPUT_SCORES" + ]).export_constant(__name__, "CLASSIFY_OUTPUT_SCORES") + +################################################################################ +# Prediction API constants. + +# Predict inputs. +PREDICT_INPUTS = "inputs" +tf_export( + "saved_model.PREDICT_INPUTS", + v1=[ + "saved_model.PREDICT_INPUTS", + "saved_model.signature_constants.PREDICT_INPUTS" + ]).export_constant(__name__, "PREDICT_INPUTS") + +# Prediction method name used in a SignatureDef. +PREDICT_METHOD_NAME = "tensorflow/serving/predict" +tf_export( + "saved_model.PREDICT_METHOD_NAME", + v1=[ + "saved_model.PREDICT_METHOD_NAME", + "saved_model.signature_constants.PREDICT_METHOD_NAME" + ]).export_constant(__name__, "PREDICT_METHOD_NAME") + +# Predict outputs. +PREDICT_OUTPUTS = "outputs" +tf_export( + "saved_model.PREDICT_OUTPUTS", + v1=[ + "saved_model.PREDICT_OUTPUTS", + "saved_model.signature_constants.PREDICT_OUTPUTS" + ]).export_constant(__name__, "PREDICT_OUTPUTS") + +################################################################################ +# Regression API constants. + +# Regression inputs. +REGRESS_INPUTS = "inputs" +tf_export( + "saved_model.REGRESS_INPUTS", + v1=[ + "saved_model.REGRESS_INPUTS", + "saved_model.signature_constants.REGRESS_INPUTS" + ]).export_constant(__name__, "REGRESS_INPUTS") + +# Regression method name used in a SignatureDef. +REGRESS_METHOD_NAME = "tensorflow/serving/regress" +tf_export( + "saved_model.REGRESS_METHOD_NAME", + v1=[ + "saved_model.REGRESS_METHOD_NAME", + "saved_model.signature_constants.REGRESS_METHOD_NAME" + ]).export_constant(__name__, "REGRESS_METHOD_NAME") + +# Regression outputs. +REGRESS_OUTPUTS = "outputs" +tf_export( + "saved_model.REGRESS_OUTPUTS", + v1=[ + "saved_model.REGRESS_OUTPUTS", + "saved_model.signature_constants.REGRESS_OUTPUTS" + ]).export_constant(__name__, "REGRESS_OUTPUTS") + +################################################################################ +# LINT.IfChange +# Train/Eval API constants. +# Not exported while export_all_saved_models is experimental. +DEFAULT_TRAIN_SIGNATURE_DEF_KEY = "train" + +DEFAULT_EVAL_SIGNATURE_DEF_KEY = "eval" + +SUPERVISED_TRAIN_METHOD_NAME = "tensorflow/supervised/training" + +SUPERVISED_EVAL_METHOD_NAME = "tensorflow/supervised/eval" +# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/unexported_constants.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6055de3cd74cf29546bb9a8089e7885b6aab7ac2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils.py @@ -0,0 +1,29 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SignatureDef utility functions. + +Utility functions for building and inspecting SignatureDef protos. +""" +# pylint: disable=unused-import +from tensorflow.python.saved_model.signature_def_utils_impl import build_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import classification_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import is_valid_signature +from tensorflow.python.saved_model.signature_def_utils_impl import load_op_from_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import op_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import predict_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import regression_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import supervised_eval_signature_def +from tensorflow.python.saved_model.signature_def_utils_impl import supervised_train_signature_def +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..5de175e2a85687662ba41e84fcad4db861739d09 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py @@ -0,0 +1,420 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SignatureDef utility functions implementation.""" + + +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import utils_impl as utils +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export( + v1=[ + 'saved_model.build_signature_def', + 'saved_model.signature_def_utils.build_signature_def' + ]) +@deprecation.deprecated_endpoints( + 'saved_model.signature_def_utils.build_signature_def') +def build_signature_def( + inputs=None, outputs=None, method_name=None, defaults=None +): + """Utility function to build a SignatureDef protocol buffer. + + Args: + inputs: Inputs of the SignatureDef defined as a proto map of string to + tensor info. + outputs: Outputs of the SignatureDef defined as a proto map of string to + tensor info. + method_name: Method name of the SignatureDef as a string. + defaults: Defaults of the SignatureDef defined as a proto map of string to + TensorProto. + + Returns: + A SignatureDef protocol buffer constructed based on the supplied arguments. + """ + signature_def = meta_graph_pb2.SignatureDef() + if inputs is not None: + for item in inputs: + signature_def.inputs[item].CopyFrom(inputs[item]) + if outputs is not None: + for item in outputs: + signature_def.outputs[item].CopyFrom(outputs[item]) + if method_name is not None: + signature_def.method_name = method_name + if defaults is not None: + for arg_name, default in defaults.items(): + if isinstance(default, ops.EagerTensor): + signature_def.defaults[arg_name].CopyFrom( + tensor_util.make_tensor_proto(default.numpy()) + ) + else: + if default.op.type == 'Const': + signature_def.defaults[arg_name].CopyFrom( + default.op.get_attr('value') + ) + else: + raise ValueError( + f'Unable to convert object {str(default)} of type {type(default)}' + ' to TensorProto.' + ) + return signature_def + + +@tf_export( + v1=[ + 'saved_model.regression_signature_def', + 'saved_model.signature_def_utils.regression_signature_def' + ]) +@deprecation.deprecated_endpoints( + 'saved_model.signature_def_utils.regression_signature_def') +def regression_signature_def(examples, predictions): + """Creates regression signature from given examples and predictions. + + This function produces signatures intended for use with the TensorFlow Serving + Regress API (tensorflow_serving/apis/prediction_service.proto), and so + constrains the input and output types to those allowed by TensorFlow Serving. + + Args: + examples: A string `Tensor`, expected to accept serialized tf.Examples. + predictions: A float `Tensor`. + + Returns: + A regression-flavored signature_def. + + Raises: + ValueError: If examples is `None`. + """ + if examples is None: + raise ValueError('Regression `examples` cannot be None.') + if not isinstance(examples, tensor_lib.Tensor): + raise ValueError('Expected regression `examples` to be of type Tensor. ' + f'Found `examples` of type {type(examples)}.') + if predictions is None: + raise ValueError('Regression `predictions` cannot be None.') + + input_tensor_info = utils.build_tensor_info(examples) + if input_tensor_info.dtype != types_pb2.DT_STRING: + raise ValueError('Regression input tensors must be of type string. ' + f'Found tensors with type {input_tensor_info.dtype}.') + signature_inputs = {signature_constants.REGRESS_INPUTS: input_tensor_info} + + output_tensor_info = utils.build_tensor_info(predictions) + if output_tensor_info.dtype != types_pb2.DT_FLOAT: + raise ValueError('Regression output tensors must be of type float. ' + f'Found tensors with type {output_tensor_info.dtype}.') + signature_outputs = {signature_constants.REGRESS_OUTPUTS: output_tensor_info} + + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.REGRESS_METHOD_NAME) + + return signature_def + + +@tf_export( + v1=[ + 'saved_model.classification_signature_def', + 'saved_model.signature_def_utils.classification_signature_def' + ]) +@deprecation.deprecated_endpoints( + 'saved_model.signature_def_utils.classification_signature_def') +def classification_signature_def(examples, classes, scores): + """Creates classification signature from given examples and predictions. + + This function produces signatures intended for use with the TensorFlow Serving + Classify API (tensorflow_serving/apis/prediction_service.proto), and so + constrains the input and output types to those allowed by TensorFlow Serving. + + Args: + examples: A string `Tensor`, expected to accept serialized tf.Examples. + classes: A string `Tensor`. Note that the ClassificationResponse message + requires that class labels are strings, not integers or anything else. + scores: a float `Tensor`. + + Returns: + A classification-flavored signature_def. + + Raises: + ValueError: If examples is `None`. + """ + if examples is None: + raise ValueError('Classification `examples` cannot be None.') + if not isinstance(examples, tensor_lib.Tensor): + raise ValueError('Classification `examples` must be a string Tensor. ' + f'Found `examples` of type {type(examples)}.') + if classes is None and scores is None: + raise ValueError('Classification `classes` and `scores` cannot both be ' + 'None.') + + input_tensor_info = utils.build_tensor_info(examples) + if input_tensor_info.dtype != types_pb2.DT_STRING: + raise ValueError('Classification input tensors must be of type string. ' + f'Found tensors of type {input_tensor_info.dtype}') + signature_inputs = {signature_constants.CLASSIFY_INPUTS: input_tensor_info} + + signature_outputs = {} + if classes is not None: + classes_tensor_info = utils.build_tensor_info(classes) + if classes_tensor_info.dtype != types_pb2.DT_STRING: + raise ValueError('Classification classes must be of type string Tensor. ' + f'Found tensors of type {classes_tensor_info.dtype}.`') + signature_outputs[signature_constants.CLASSIFY_OUTPUT_CLASSES] = ( + classes_tensor_info) + if scores is not None: + scores_tensor_info = utils.build_tensor_info(scores) + if scores_tensor_info.dtype != types_pb2.DT_FLOAT: + raise ValueError('Classification scores must be a float Tensor.') + signature_outputs[signature_constants.CLASSIFY_OUTPUT_SCORES] = ( + scores_tensor_info) + + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.CLASSIFY_METHOD_NAME) + + return signature_def + + +@tf_export( + v1=[ + 'saved_model.predict_signature_def', + 'saved_model.signature_def_utils.predict_signature_def' + ]) +@deprecation.deprecated_endpoints( + 'saved_model.signature_def_utils.predict_signature_def') +def predict_signature_def(inputs, outputs): + """Creates prediction signature from given inputs and outputs. + + This function produces signatures intended for use with the TensorFlow Serving + Predict API (tensorflow_serving/apis/prediction_service.proto). This API + imposes no constraints on the input and output types. + + Args: + inputs: dict of string to `Tensor`. + outputs: dict of string to `Tensor`. + + Returns: + A prediction-flavored signature_def. + + Raises: + ValueError: If inputs or outputs is `None`. + """ + if inputs is None or not inputs: + raise ValueError('Prediction `inputs` cannot be None or empty.') + if outputs is None or not outputs: + raise ValueError('Prediction `outputs` cannot be None or empty.') + + signature_inputs = {key: utils.build_tensor_info(tensor) + for key, tensor in inputs.items()} + signature_outputs = {key: utils.build_tensor_info(tensor) + for key, tensor in outputs.items()} + + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.PREDICT_METHOD_NAME) + + return signature_def + + +def supervised_train_signature_def( + inputs, loss, predictions=None, metrics=None): + return _supervised_signature_def( + signature_constants.SUPERVISED_TRAIN_METHOD_NAME, inputs, loss=loss, + predictions=predictions, metrics=metrics) + + +def supervised_eval_signature_def( + inputs, loss, predictions=None, metrics=None): + return _supervised_signature_def( + signature_constants.SUPERVISED_EVAL_METHOD_NAME, inputs, loss=loss, + predictions=predictions, metrics=metrics) + + +def _supervised_signature_def( + method_name, inputs, loss=None, predictions=None, + metrics=None): + """Creates a signature for training and eval data. + + This function produces signatures that describe the inputs and outputs + of a supervised process, such as training or evaluation, that + results in loss, metrics, and the like. Note that this function only requires + inputs to be not None. + + Args: + method_name: Method name of the SignatureDef as a string. + inputs: dict of string to `Tensor`. + loss: dict of string to `Tensor` representing computed loss. + predictions: dict of string to `Tensor` representing the output predictions. + metrics: dict of string to `Tensor` representing metric ops. + + Returns: + A train- or eval-flavored signature_def. + + Raises: + ValueError: If inputs or outputs is `None`. + """ + if inputs is None or not inputs: + raise ValueError(f'{method_name} `inputs` cannot be None or empty.') + + signature_inputs = {key: utils.build_tensor_info(tensor) + for key, tensor in inputs.items()} + + signature_outputs = {} + for output_set in (loss, predictions, metrics): + if output_set is not None: + sig_out = {key: utils.build_tensor_info(tensor) + for key, tensor in output_set.items()} + signature_outputs.update(sig_out) + + signature_def = build_signature_def( + signature_inputs, signature_outputs, method_name) + + return signature_def + + +@tf_export( + v1=[ + 'saved_model.is_valid_signature', + 'saved_model.signature_def_utils.is_valid_signature' + ]) +@deprecation.deprecated_endpoints( + 'saved_model.signature_def_utils.is_valid_signature') +def is_valid_signature(signature_def): + """Determine whether a SignatureDef can be served by TensorFlow Serving.""" + if signature_def is None: + return False + return (_is_valid_classification_signature(signature_def) or + _is_valid_regression_signature(signature_def) or + _is_valid_predict_signature(signature_def)) + + +def _is_valid_predict_signature(signature_def): + """Determine whether the argument is a servable 'predict' SignatureDef.""" + if signature_def.method_name != signature_constants.PREDICT_METHOD_NAME: + return False + if not signature_def.inputs.keys(): + return False + if not signature_def.outputs.keys(): + return False + return True + + +def _is_valid_regression_signature(signature_def): + """Determine whether the argument is a servable 'regress' SignatureDef.""" + if signature_def.method_name != signature_constants.REGRESS_METHOD_NAME: + return False + + if (set(signature_def.inputs.keys()) + != set([signature_constants.REGRESS_INPUTS])): + return False + if (signature_def.inputs[signature_constants.REGRESS_INPUTS].dtype != + types_pb2.DT_STRING): + return False + + if (set(signature_def.outputs.keys()) + != set([signature_constants.REGRESS_OUTPUTS])): + return False + if (signature_def.outputs[signature_constants.REGRESS_OUTPUTS].dtype != + types_pb2.DT_FLOAT): + return False + + return True + + +def _is_valid_classification_signature(signature_def): + """Determine whether the argument is a servable 'classify' SignatureDef.""" + if signature_def.method_name != signature_constants.CLASSIFY_METHOD_NAME: + return False + + if (set(signature_def.inputs.keys()) + != set([signature_constants.CLASSIFY_INPUTS])): + return False + if (signature_def.inputs[signature_constants.CLASSIFY_INPUTS].dtype != + types_pb2.DT_STRING): + return False + + allowed_outputs = set([signature_constants.CLASSIFY_OUTPUT_CLASSES, + signature_constants.CLASSIFY_OUTPUT_SCORES]) + + if not signature_def.outputs.keys(): + return False + if set(signature_def.outputs.keys()) - allowed_outputs: + return False + if (signature_constants.CLASSIFY_OUTPUT_CLASSES in signature_def.outputs + and + signature_def.outputs[signature_constants.CLASSIFY_OUTPUT_CLASSES].dtype + != types_pb2.DT_STRING): + return False + if (signature_constants.CLASSIFY_OUTPUT_SCORES in signature_def.outputs + and + signature_def.outputs[signature_constants.CLASSIFY_OUTPUT_SCORES].dtype != + types_pb2.DT_FLOAT): + return False + + return True + + +def op_signature_def(op, key): + """Creates a signature def with the output pointing to an op. + + Note that op isn't strictly enforced to be an Op object, and may be a Tensor. + It is recommended to use the build_signature_def() function for Tensors. + + Args: + op: An Op (or possibly Tensor). + key: Key to graph element in the SignatureDef outputs. + + Returns: + A SignatureDef with a single output pointing to the op. + """ + # Use build_tensor_info_from_op, which creates a TensorInfo from the element's + # name. + return build_signature_def(outputs={key: utils.build_tensor_info_from_op(op)}) + + +def load_op_from_signature_def(signature_def, key, import_scope=None): + """Load an Op from a SignatureDef created by op_signature_def(). + + Args: + signature_def: a SignatureDef proto + key: string key to op in the SignatureDef outputs. + import_scope: Scope used to import the op + + Returns: + Op (or possibly Tensor) in the graph with the same name as saved in the + SignatureDef. + + Raises: + NotFoundError: If the op could not be found in the graph. + """ + tensor_info = signature_def.outputs[key] + try: + # The init and train ops are not strictly enforced to be operations, so + # retrieve any graph element (can be either op or tensor). + return utils.get_element_from_tensor_info( + tensor_info, import_scope=import_scope) + except KeyError: + raise errors.NotFoundError( + None, None, + f'The key "{key}" could not be found in the graph. Please make sure the' + ' SavedModel was created by the internal _SavedModelBuilder. If you ' + 'are using the public API, please make sure the SignatureDef in the ' + f'SavedModel does not contain the key "{key}".') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7a0ff4d3e9fa834c449939823e8d3b03c88562 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/signature_serialization.py @@ -0,0 +1,377 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helpers for working with signatures in tf.saved_model.save.""" + +from absl import logging + +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun +from tensorflow.python.eager.polymorphic_function import attributes +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import function_serialization +from tensorflow.python.saved_model import revived_types +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.trackable import base +from tensorflow.python.types import core +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc + +DEFAULT_SIGNATURE_ATTR = "_default_save_signature" +SIGNATURE_ATTRIBUTE_NAME = "signatures" +# Max number of warnings to show if signature contains normalized input names. +_NUM_DISPLAY_NORMALIZED_SIGNATURES = 5 + + +def _get_signature(function): + if ( + isinstance(function, def_function.Function) + and function.input_signature is not None + ): + function = function._get_concrete_function_garbage_collected() # pylint: disable=protected-access + if not isinstance(function, defun.ConcreteFunction): + return None + return function + + +def _valid_signature(concrete_function): + """Returns whether concrete function can be converted to a signature.""" + if not concrete_function.outputs: + # Functions without outputs don't make sense as signatures. We just don't + # have any way to run an Operation with no outputs as a SignatureDef in the + # 1.x style. + return False + try: + _validate_inputs(concrete_function) + _normalize_outputs(concrete_function.structured_outputs, "unused", "unused") + except ValueError: + return False + return True + + +def _validate_inputs(concrete_function): + """Raises error if input type is tf.Variable.""" + if any( + isinstance(inp, resource_variable_ops.VariableSpec) + for inp in nest.flatten(concrete_function.structured_input_signature) + ): + raise ValueError( + f"Unable to serialize concrete_function '{concrete_function.name}'" + "with tf.Variable input. Functions that expect tf.Variable " + "inputs cannot be exported as signatures." + ) + + +def _get_signature_name_changes(concrete_function): + """Checks for user-specified signature input names that are normalized.""" + # Map of {user-given name: normalized name} if the names are un-identical. + name_changes = {} + for signature_input_name, graph_input in zip( + concrete_function.function_def.signature.input_arg, + concrete_function.graph.inputs, + ): + try: + user_specified_name = compat.as_str( + graph_input.op.get_attr("_user_specified_name") + ) + if signature_input_name.name != user_specified_name: + name_changes[user_specified_name] = signature_input_name.name + except ValueError: + # Signature input does not have a user-specified name. + pass + return name_changes + + +def find_function_to_export(saveable_view): + """Function to export, None if no suitable function was found.""" + # If the user did not specify signatures, check the root object for a function + # that can be made into a signature. + children = saveable_view.list_children(saveable_view.root) + + # TODO(b/205014194): Discuss removing this behaviour. It can lead to WTFs when + # a user decides to annotate more functions with tf.function and suddenly + # serving that model way later in the process stops working. + possible_signatures = [] + for name, child in children: + if not isinstance(child, (def_function.Function, defun.ConcreteFunction)): + continue + if name == DEFAULT_SIGNATURE_ATTR: + return child + concrete = _get_signature(child) + if concrete is not None and _valid_signature(concrete): + possible_signatures.append(concrete) + + if len(possible_signatures) == 1: + single_function = possible_signatures[0] + signature = _get_signature(single_function) + if signature and _valid_signature(signature): + return signature + return None + + +def canonicalize_signatures(signatures): + """Converts `signatures` into a dictionary of concrete functions.""" + if signatures is None: + return {}, {}, {} + if not isinstance(signatures, collections_abc.Mapping): + signatures = { + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signatures + } + num_normalized_signatures_counter = 0 + concrete_signatures = {} + wrapped_functions = {} + defaults = {} + for signature_key, function in signatures.items(): + original_function = signature_function = _get_signature(function) + if signature_function is None: + raise ValueError( + "Expected a TensorFlow function for which to generate a signature, " + f"but got {function}. Only `tf.functions` with an input signature or " + "concrete functions can be used as a signature." + ) + + wrapped_functions[original_function] = signature_function = ( + wrapped_functions.get(original_function) + or function_serialization.wrap_cached_variables(original_function) + ) + _validate_inputs(signature_function) + if num_normalized_signatures_counter < _NUM_DISPLAY_NORMALIZED_SIGNATURES: + signature_name_changes = _get_signature_name_changes(signature_function) + if signature_name_changes: + num_normalized_signatures_counter += 1 + logging.info( + "Function `%s` contains input name(s) %s with unsupported " + "characters which will be renamed to %s in the SavedModel.", + compat.as_str(signature_function.graph.name), + ", ".join(signature_name_changes.keys()), + ", ".join(signature_name_changes.values()), + ) + + # Re-wrap the function so that it returns a dictionary of Tensors. This + # matches the format of 1.x-style signatures. + # pylint: disable=cell-var-from-loop + def signature_wrapper(**kwargs): + structured_outputs = signature_function(**kwargs) + return _normalize_outputs( + structured_outputs, signature_function.name, signature_key + ) + + if hasattr(function, "__name__"): + signature_wrapper.__name__ = "signature_wrapper_" + function.__name__ + + # Extract experimental attributes and propagate it to the wrapped_function. + # At the moment only the `disable_summaries_at_runtime` attr needs to be + # propagated. + experimental_attributes = {} + for attr in attributes.POLYMORPHIC_FUNCTION_ALLOWLIST: + attr_value = signature_function.function_def.attr.get(attr, None) + if attr != attributes.NO_INLINE and attr_value is not None: + experimental_attributes[attr] = attr_value + if not experimental_attributes: + experimental_attributes = None + + wrapped_function = def_function.function( + signature_wrapper, experimental_attributes=experimental_attributes + ) + tensor_spec_signature = {} + if signature_function.structured_input_signature is not None: + # The structured input signature may contain other non-tensor arguments. + inputs = filter( + lambda x: isinstance(x, tensor.TensorSpec), + nest.flatten( + signature_function.structured_input_signature, + expand_composites=True, + ), + ) + else: + # Structured input signature isn't always defined for some functions. + inputs = signature_function.inputs + + for keyword, inp in zip( + signature_function._arg_keywords, # pylint: disable=protected-access + inputs, + ): + keyword = compat.as_str(keyword) + if isinstance(inp, tensor.TensorSpec): + spec = tensor.TensorSpec(inp.shape, inp.dtype, name=keyword) + else: + spec = tensor.TensorSpec.from_tensor(inp, name=keyword) + tensor_spec_signature[keyword] = spec + final_concrete = wrapped_function._get_concrete_function_garbage_collected( # pylint: disable=protected-access + **tensor_spec_signature + ) + # pylint: disable=protected-access + if len(final_concrete._arg_keywords) == 1: + # If there is only one input to the signature, a very common case, then + # ordering is unambiguous and we can let people pass a positional + # argument. Since SignatureDefs are unordered (protobuf "map") multiple + # arguments means we need to be keyword-only. + final_concrete._num_positional_args = 1 + else: + final_concrete._num_positional_args = 0 + # pylint: enable=protected-access + concrete_signatures[signature_key] = final_concrete + # pylint: enable=cell-var-from-loop + if isinstance(function, core.PolymorphicFunction): + flattened_defaults = nest.flatten( + function.function_spec.fullargspec.defaults # pylint: disable=protected-access + ) + len_default = len(flattened_defaults or []) + arg_names = list(tensor_spec_signature.keys()) + if len_default > 0: + # tensor_spec_signature uses the same nest.flatten() as + # flattened_defaults. + for arg, default in zip( + arg_names[-len_default:], # pylint: disable=protected-access + flattened_defaults or [], + ): + if not isinstance(default, tensor.Tensor): + continue + defaults.setdefault(signature_key, {})[arg] = default + return concrete_signatures, wrapped_functions, defaults + + +def _normalize_outputs(outputs, function_name, signature_key): + """Normalize outputs if necessary and check that they are tensors.""" + # Convert `outputs` to a dictionary (if it's not one already). + if not isinstance(outputs, collections_abc.Mapping): + # Check if `outputs` is a namedtuple. + if hasattr(outputs, "_asdict"): + outputs = outputs._asdict() + else: + if not isinstance(outputs, collections_abc.Sequence): + outputs = [outputs] + outputs = { + "output_{}".format(output_index): output + for output_index, output in enumerate(outputs) + } + + # Check that the keys of `outputs` are strings and the values are Tensors. + for key, value in outputs.items(): + if not isinstance(key, compat.bytes_or_text_types): + raise ValueError( + f"Got a dictionary with a non-string key {key!r} in the output of " + f"the function {compat.as_str_any(function_name)} used to generate " + f"the SavedModel signature {signature_key!r}." + ) + if not isinstance(value, (tensor.Tensor, composite_tensor.CompositeTensor)): + raise ValueError( + f"Got a non-Tensor value {value!r} for key {key!r} in the output of " + f"the function {compat.as_str_any(function_name)} used to generate " + f"the SavedModel signature {signature_key!r}. " + "Outputs for functions used as signatures must be a single Tensor, " + "a sequence of Tensors, or a dictionary from string to Tensor." + ) + return outputs + + +# _SignatureMap is immutable to ensure that users do not expect changes to be +# reflected in the SavedModel. Using public APIs, tf.saved_model.load() is the +# only way to create a _SignatureMap and there is no way to modify it. So we can +# safely ignore/overwrite ".signatures" attributes attached to objects being +# saved if they contain a _SignatureMap. A ".signatures" attribute containing +# any other type (e.g. a regular dict) will raise an exception asking the user +# to first "del obj.signatures" if they want it overwritten. +class _SignatureMap(collections_abc.Mapping, base.Trackable): + """A collection of SavedModel signatures.""" + + def __init__(self): + self._signatures = {} + + def _add_signature(self, name, concrete_function): + """Adds a signature to the _SignatureMap.""" + # Ideally this object would be immutable, but restore is streaming so we do + # need a private API for adding new signatures to an existing object. + self._signatures[name] = concrete_function + + def __getitem__(self, key): + return self._signatures[key] + + def __iter__(self): + return iter(self._signatures) + + def __len__(self): + return len(self._signatures) + + def __repr__(self): + return "_SignatureMap({})".format(self._signatures) + + def _trackable_children(self, save_type=base.SaveType.CHECKPOINT, **kwargs): + if save_type != base.SaveType.SAVEDMODEL: + return {} + + return { + key: value + for key, value in self.items() + if isinstance(value, (def_function.Function, defun.ConcreteFunction)) + } + + +revived_types.register_revived_type( + "signature_map", + lambda obj: isinstance(obj, _SignatureMap), + versions=[ + revived_types.VersionedTypeRegistration( + # Standard dependencies are enough to reconstruct the trackable + # items in dictionaries, so we don't need to save any extra + # information. + object_factory=lambda proto: _SignatureMap(), + version=1, + min_producer_version=1, + min_consumer_version=1, + setter=_SignatureMap._add_signature, # pylint: disable=protected-access + ) + ], +) + + +def create_signature_map(signatures): + """Creates an object containing `signatures`.""" + signature_map = _SignatureMap() + for name, func in signatures.items(): + # This true of any signature that came from canonicalize_signatures. Here as + # a sanity check on saving; crashing on load (e.g. in _add_signature) would + # be more problematic in case future export changes violated these + # assertions. + assert isinstance(func, defun.ConcreteFunction) + assert isinstance(func.structured_outputs, collections_abc.Mapping) + # pylint: disable=protected-access + if len(func._arg_keywords) == 1: + assert 1 == func._num_positional_args + else: + assert 0 == func._num_positional_args + signature_map._add_signature(name, func) + # pylint: enable=protected-access + return signature_map + + +def validate_augmented_graph_view(augmented_graph_view): + """Performs signature-related sanity checks on `augmented_graph_view`.""" + for name, dep in augmented_graph_view.list_children( + augmented_graph_view.root + ): + if name == SIGNATURE_ATTRIBUTE_NAME: + if not isinstance(dep, _SignatureMap): + raise ValueError( + f"Exporting an object {augmented_graph_view.root} which has an" + f" attribute named '{SIGNATURE_ATTRIBUTE_NAME}'. This is a reserved" + " attribute used to store SavedModel signatures in objects which" + " come from `tf.saved_model.load`. Delete this attribute (e.g." + f" `del obj.{SIGNATURE_ATTRIBUTE_NAME}`) before saving if this" + " shadowing is acceptable." + ) + break diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/simple_save.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/simple_save.py new file mode 100644 index 0000000000000000000000000000000000000000..f84e80402e09bfc57efe4062fc2337cad00270f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/simple_save.py @@ -0,0 +1,87 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel simple save functionality.""" + +from tensorflow.python.framework import ops +from tensorflow.python.saved_model import builder +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['saved_model.simple_save']) +@deprecation.deprecated( + None, + 'This API was designed for TensorFlow v1. See https://www.tensorflow.org/guide/migrate ' + 'for instructions on how to migrate your code to TensorFlow v2.') +def simple_save(session, export_dir, inputs, outputs, legacy_init_op=None): + """Convenience function to build a SavedModel suitable for serving. + + In many common cases, saving models for serving will be as simple as: + + simple_save(session, + export_dir, + inputs={"x": x, "y": y}, + outputs={"z": z}) + + Although in many cases it's not necessary to understand all of the many ways + to configure a SavedModel, this method has a few practical implications: + - It will be treated as a graph for inference / serving (i.e. uses the tag + `saved_model.SERVING`) + - The SavedModel will load in TensorFlow Serving and supports the + [Predict + API](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/predict.proto). + To use the Classify, Regress, or MultiInference APIs, please + use either + [tf.Estimator](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator) + or the lower level + [SavedModel + APIs](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md). + - Some TensorFlow ops depend on information on disk or other information + called "assets". These are generally handled automatically by adding the + assets to the `GraphKeys.ASSET_FILEPATHS` collection. Only assets in that + collection are exported; if you need more custom behavior, you'll need to + use the + [SavedModelBuilder](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/builder.py). + + More information about SavedModel and signatures can be found here: + https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md. + + Args: + session: The TensorFlow session from which to save the meta graph and + variables. + export_dir: The path to which the SavedModel will be stored. + inputs: dict mapping string input names to tensors. These are added + to the SignatureDef as the inputs. + outputs: dict mapping string output names to tensors. These are added + to the SignatureDef as the outputs. + legacy_init_op: Legacy support for op or group of ops to execute after the + restore op upon a load. + """ + signature_def_map = { + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: + signature_def_utils.predict_signature_def(inputs, outputs) + } + b = builder.SavedModelBuilder(export_dir) + b.add_meta_graph_and_variables( + session, + tags=[tag_constants.SERVING], + signature_def_map=signature_def_map, + assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS), + main_op=legacy_init_op, + clear_devices=True) + b.save() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tag_constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tag_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..879a1eda87a8bcb3827870df36615ffa670a1f65 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tag_constants.py @@ -0,0 +1,54 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Common tags used for graphs in SavedModel. + +""" +from tensorflow.python.util.tf_export import tf_export + + +# Tag for the `serving` graph. +SERVING = "serve" +tf_export( + "saved_model.SERVING", + v1=["saved_model.SERVING", + "saved_model.tag_constants.SERVING"]).export_constant( + __name__, "SERVING") + +# Tag for the `training` graph. +TRAINING = "train" +tf_export( + "saved_model.TRAINING", + v1=["saved_model.TRAINING", + "saved_model.tag_constants.TRAINING"]).export_constant( + __name__, "TRAINING") + +# LINT.IfChange +# Tag for the `eval` graph. Not exported while the export logic is in contrib. +EVAL = "eval" +# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/unexported_constants.py) + +# Tag for the `gpu` graph. +GPU = "gpu" +tf_export( + "saved_model.GPU", v1=["saved_model.GPU", + "saved_model.tag_constants.GPU"]).export_constant( + __name__, "GPU") + +# Tag for the `tpu` graph. +TPU = "tpu" +tf_export( + "saved_model.TPU", v1=["saved_model.TPU", + "saved_model.tag_constants.TPU"]).export_constant( + __name__, "TPU") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tracing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tracing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..84ea7b94c532f0c732f87e4d5f75fa2e3386eaa9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/tracing_utils.py @@ -0,0 +1,72 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tracing utilities used by SavedModel.""" + +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.checkpoint import tensor_callable +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun + + +def trace_save_and_restore(obj): + """Traces `Trackable` serialize- and restore-from-tensors functions. + + Args: + obj: A `Trackable` object. + + Returns: + A concrete Function. + """ + legacy_name = saveable_compat.get_saveable_name(obj) + + obj_save_fn = obj._serialize_to_tensors # pylint: disable=protected-access + obj_restore_fn = obj._restore_from_tensors # pylint: disable=protected-access + + if isinstance(obj_save_fn, defun.ConcreteFunction): + concrete_save = obj_save_fn + else: + @def_function.function + def save_fn(): + tensor_dict = obj_save_fn() + if any(isinstance(v, tensor_callable.Callable) + for v in tensor_dict.values()): + raise NotImplementedError( + f"Unable to export SavedModel with object of type {type(obj)} " + "because it returns a Callable in `_serialize_to_tensors`. " + "If you need this functionality please file a feature request.") + + if legacy_name: + # If there is a legacy decorator, append the name to the keys. + return {f"{legacy_name}{key}": value + for key, value in tensor_dict.items()} + return tensor_dict + + concrete_save = save_fn.get_concrete_function() + + if isinstance(obj_restore_fn, defun.ConcreteFunction): + concrete_restore = obj_restore_fn + else: + @def_function.function + def restore_fn(restored_tensors): + if legacy_name: + # Do the opposite operation of save_fn() + restored_tensors = {key[len(legacy_name):]: value + for key, value in restored_tensors.items()} + obj_restore_fn(restored_tensors) + + concrete_restore = restore_fn.get_concrete_function( + concrete_save.structured_outputs) + + return concrete_save, concrete_restore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fec3883b603bcda5c36db76773f47c5387ddecc0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils.py @@ -0,0 +1,23 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel utility functions. + +Utility functions to assist with setup and construction of the SavedModel proto. +""" +# pylint: disable=unused-import +from tensorflow.python.saved_model.utils_impl import build_tensor_info +from tensorflow.python.saved_model.utils_impl import build_tensor_info_from_op +from tensorflow.python.saved_model.utils_impl import get_tensor_from_tensor_info +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f5a6849ce27b3ae3b278f8e1ed98342d16dec2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/saved_model/utils_impl.py @@ -0,0 +1,214 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel utility functions implementation.""" + +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import byte_swap_tensor as bst +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# TensorInfo helpers. +_DEPRECATION_MSG = ( + "This API was designed for TensorFlow v1. See " + "https://www.tensorflow.org/guide/migrate for instructions on how to " + "migrate your code to TensorFlow v2.") + + +@tf_export( + v1=["saved_model.build_tensor_info", "saved_model.utils.build_tensor_info"]) +@deprecation.deprecated(None, _DEPRECATION_MSG) +def build_tensor_info(tensor): + """Utility function to build TensorInfo proto from a Tensor. + + Args: + tensor: Tensor or SparseTensor whose name, dtype and shape are used to + build the TensorInfo. For SparseTensors, the names of the three + constituent Tensors are used. + + Returns: + A TensorInfo protocol buffer constructed based on the supplied argument. + + Raises: + RuntimeError: If eager execution is enabled. + + @compatibility(TF2) + This API is not compatible with eager execution as `tensor` needs to be a + graph tensor, and there is no replacement for it in TensorFlow 2.x. To start + writing programs using TensorFlow 2.x, please refer to the [Effective + TensorFlow 2](https://www.tensorflow.org/guide/effective_tf2) guide. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError("`build_tensor_info` is not supported in eager " + "execution.") + return build_tensor_info_internal(tensor) + + +def build_tensor_info_internal(tensor): + """Utility function to build TensorInfo proto from a Tensor.""" + if (isinstance(tensor, composite_tensor.CompositeTensor) and + not isinstance(tensor, sparse_tensor.SparseTensor) and + not isinstance(tensor, resource_variable_ops.ResourceVariable)): + return _build_composite_tensor_info_internal(tensor) + + tensor_info = meta_graph_pb2.TensorInfo( + dtype=dtypes.as_dtype(tensor.dtype).as_datatype_enum, + tensor_shape=tensor.get_shape().as_proto()) + if isinstance(tensor, sparse_tensor.SparseTensor): + tensor_info.coo_sparse.values_tensor_name = tensor.values.name + tensor_info.coo_sparse.indices_tensor_name = tensor.indices.name + tensor_info.coo_sparse.dense_shape_tensor_name = tensor.dense_shape.name + else: + tensor_info.name = tensor.name + return tensor_info + + +def _build_composite_tensor_info_internal(tensor): + """Utility function to build TensorInfo proto from a CompositeTensor.""" + spec = tensor._type_spec # pylint: disable=protected-access + tensor_info = meta_graph_pb2.TensorInfo() + spec_proto = nested_structure_coder.encode_structure(spec) + tensor_info.composite_tensor.type_spec.CopyFrom(spec_proto.type_spec_value) + for component in nest.flatten(tensor, expand_composites=True): + tensor_info.composite_tensor.components.add().CopyFrom( + build_tensor_info_internal(component)) + return tensor_info + + +def build_tensor_info_from_op(op): + """Utility function to build TensorInfo proto from an Op. + + Note that this function should be used with caution. It is strictly restricted + to TensorFlow internal use-cases only. Please make sure you do need it before + using it. + + This utility function overloads the TensorInfo proto by setting the name to + the Op's name, dtype to DT_INVALID and tensor_shape as None. One typical usage + is for the Op of the call site for the defunned function: + ```python + @function.defun + def some_variable_initialization_fn(value_a, value_b): + a = value_a + b = value_b + + value_a = constant_op.constant(1, name="a") + value_b = constant_op.constant(2, name="b") + op_info = utils.build_op_info( + some_variable_initialization_fn(value_a, value_b)) + ``` + + Args: + op: An Op whose name is used to build the TensorInfo. The name that points + to the Op could be fetched at run time in the Loader session. + + Returns: + A TensorInfo protocol buffer constructed based on the supplied argument. + + Raises: + RuntimeError: If eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError( + "`build_tensor_info_from_op` is not supported in eager execution.") + return meta_graph_pb2.TensorInfo( + dtype=types_pb2.DT_INVALID, + tensor_shape=tensor_shape.unknown_shape().as_proto(), + name=op.name) + + +@tf_export(v1=["saved_model.get_tensor_from_tensor_info", + "saved_model.utils.get_tensor_from_tensor_info"]) +@deprecation.deprecated(None, _DEPRECATION_MSG) +def get_tensor_from_tensor_info(tensor_info, graph=None, import_scope=None): + """Returns the Tensor or CompositeTensor described by a TensorInfo proto. + + Args: + tensor_info: A TensorInfo proto describing a Tensor or SparseTensor or + CompositeTensor. + graph: The tf.Graph in which tensors are looked up. If None, the + current default graph is used. + import_scope: If not None, names in `tensor_info` are prefixed with this + string before lookup. + + Returns: + The Tensor or SparseTensor or CompositeTensor in `graph` described by + `tensor_info`. + + Raises: + KeyError: If `tensor_info` does not correspond to a tensor in `graph`. + ValueError: If `tensor_info` is malformed. + """ + graph = graph or ops.get_default_graph() + def _get_tensor(name): + return graph.get_tensor_by_name( + ops.prepend_name_scope(name, import_scope=import_scope)) + encoding = tensor_info.WhichOneof("encoding") + if encoding == "name": + return _get_tensor(tensor_info.name) + elif encoding == "coo_sparse": + return sparse_tensor.SparseTensor( + _get_tensor(tensor_info.coo_sparse.indices_tensor_name), + _get_tensor(tensor_info.coo_sparse.values_tensor_name), + _get_tensor(tensor_info.coo_sparse.dense_shape_tensor_name)) + elif encoding == "composite_tensor": + spec_proto = struct_pb2.StructuredValue( + type_spec_value=tensor_info.composite_tensor.type_spec) + spec = nested_structure_coder.decode_proto(spec_proto) + components = [_get_tensor(component.name) for component in + tensor_info.composite_tensor.components] + return nest.pack_sequence_as(spec, components, expand_composites=True) + else: + raise ValueError(f"Invalid TensorInfo.encoding: {encoding}. Expected `" + "coo_sparse`, `composite_tensor`, or `name` for a dense " + "tensor.") + + +def get_element_from_tensor_info(tensor_info, graph=None, import_scope=None): + """Returns the element in the graph described by a TensorInfo proto. + + Args: + tensor_info: A TensorInfo proto describing an Op or Tensor by name. + graph: The tf.Graph in which tensors are looked up. If None, the current + default graph is used. + import_scope: If not None, names in `tensor_info` are prefixed with this + string before lookup. + + Returns: + Op or tensor in `graph` described by `tensor_info`. + + Raises: + KeyError: If `tensor_info` does not correspond to an op or tensor in `graph` + """ + graph = graph or ops.get_default_graph() + return graph.as_graph_element( + ops.prepend_name_scope(tensor_info.name, import_scope=import_scope)) + + +def swap_function_tensor_content(meta_graph_def, from_endiness, to_endiness): + bst.swap_tensor_content_in_graph_function( + meta_graph_def, from_endiness, to_endiness + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/plugin_asset.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/plugin_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..e20971129174405b51e2dbaf19739a3240cdb07e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/plugin_asset.py @@ -0,0 +1,136 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TensorBoard Plugin asset abstract class. + +TensorBoard plugins may need to provide arbitrary assets, such as +configuration information for specific outputs, or vocabulary files, or sprite +images, etc. + +This module contains methods that allow plugin assets to be specified at graph +construction time. Plugin authors define a PluginAsset which is treated as a +singleton on a per-graph basis. The PluginAsset has an assets method which +returns a dictionary of asset contents. The tf.compat.v1.summary.FileWriter +(or any other Summary writer) will serialize these assets in such a way that +TensorBoard can retrieve them. +""" + +import abc + +from tensorflow.python.framework import ops + +_PLUGIN_ASSET_PREFIX = "__tensorboard_plugin_asset__" + + +def get_plugin_asset(plugin_asset_cls, graph=None): + """Acquire singleton PluginAsset instance from a graph. + + PluginAssets are always singletons, and are stored in tf Graph collections. + This way, they can be defined anywhere the graph is being constructed, and + if the same plugin is configured at many different points, the user can always + modify the same instance. + + Args: + plugin_asset_cls: The PluginAsset class + graph: (optional) The graph to retrieve the instance from. If not specified, + the default graph is used. + + Returns: + An instance of the plugin_asset_class + + Raises: + ValueError: If we have a plugin name collision, or if we unexpectedly find + the wrong number of items in a collection. + """ + if graph is None: + graph = ops.get_default_graph() + if not plugin_asset_cls.plugin_name: + raise ValueError("Class %s has no plugin_name" % plugin_asset_cls.__name__) + + name = _PLUGIN_ASSET_PREFIX + plugin_asset_cls.plugin_name + container = graph.get_collection(name) + if container: + if len(container) != 1: + raise ValueError("Collection for %s had %d items, expected 1" % + (name, len(container))) + instance = container[0] + if not isinstance(instance, plugin_asset_cls): + raise ValueError("Plugin name collision between classes %s and %s" % + (plugin_asset_cls.__name__, instance.__class__.__name__)) + else: + instance = plugin_asset_cls() + graph.add_to_collection(name, instance) + graph.add_to_collection(_PLUGIN_ASSET_PREFIX, plugin_asset_cls.plugin_name) + return instance + + +def get_all_plugin_assets(graph=None): + """Retrieve all PluginAssets stored in the graph collection. + + Args: + graph: Optionally, the graph to get assets from. If unspecified, the default + graph is used. + + Returns: + A list with all PluginAsset instances in the graph. + + Raises: + ValueError: if we unexpectedly find a collection with the wrong number of + PluginAssets. + + """ + if graph is None: + graph = ops.get_default_graph() + + out = [] + for name in graph.get_collection(_PLUGIN_ASSET_PREFIX): + collection = graph.get_collection(_PLUGIN_ASSET_PREFIX + name) + if len(collection) != 1: + raise ValueError("Collection for %s had %d items, expected 1" % + (name, len(collection))) + out.append(collection[0]) + return out + + +class PluginAsset(metaclass=abc.ABCMeta): + """This abstract base class allows TensorBoard to serialize assets to disk. + + Plugin authors are expected to extend the PluginAsset class, so that it: + - has a unique plugin_name + - provides an assets method that returns an {asset_name: asset_contents} + dictionary. For now, asset_contents are strings, although we may add + StringIO support later. + + LifeCycle of a PluginAsset instance: + - It is constructed when get_plugin_asset is called on the class for + the first time. + - It is configured by code that follows the calls to get_plugin_asset + - When the containing graph is serialized by the + tf.compat.v1.summary.FileWriter, the writer calls assets and the + PluginAsset instance provides its contents to be written to disk. + """ + + plugin_name = None + + @abc.abstractmethod + def assets(self): + """Provide all of the assets contained by the PluginAsset instance. + + The assets method should return a dictionary structured as + {asset_name: asset_contents}. asset_contents is a string. + + This method will be called by the tf.compat.v1.summary.FileWriter when it + is time to write the assets out to disk. + """ + raise NotImplementedError() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..161456a7aecae08baf0a11481912596a80708f33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary.py @@ -0,0 +1,857 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Operations for writing summary data, for use in analysis and visualization. + +See the [Summaries and +TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard) guide. + +API docstring: tensorflow.summary +""" + +import contextlib +import warnings + +from google.protobuf import json_format as _json_format + +# exports Summary, SummaryDescription, Event, TaggedRunMetadata, SessionLog +# pylint: disable=unused-import, g-importing-member +from tensorflow.core.framework.summary_pb2 import Summary +from tensorflow.core.framework.summary_pb2 import SummaryDescription +from tensorflow.core.framework.summary_pb2 import SummaryMetadata as _SummaryMetadata # pylint: enable=unused-import +from tensorflow.core.util.event_pb2 import Event +from tensorflow.core.util.event_pb2 import SessionLog +from tensorflow.core.util.event_pb2 import TaggedRunMetadata +# pylint: enable=unused-import + +from tensorflow.python.distribute import summary_op_util as _distribute_summary_op_util +from tensorflow.python.eager import context as _context +from tensorflow.python.framework import constant_op as _constant_op +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import ops as _ops +from tensorflow.python.ops import array_ops as _array_ops +from tensorflow.python.ops import gen_logging_ops as _gen_logging_ops +from tensorflow.python.ops import gen_summary_ops as _gen_summary_ops # pylint: disable=unused-import +from tensorflow.python.ops import summary_op_util as _summary_op_util +from tensorflow.python.ops import summary_ops_v2 as _summary_ops_v2 + +# exports FileWriter, FileWriterCache +# pylint: disable=unused-import +from tensorflow.python.summary.writer.writer import FileWriter +from tensorflow.python.summary.writer.writer_cache import FileWriterCache +# pylint: enable=unused-import + +from tensorflow.python.training import training_util as _training_util +from tensorflow.python.util import compat as _compat +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['summary.scalar']) +def scalar(name, tensor, collections=None, family=None): + """Outputs a `Summary` protocol buffer containing a single scalar value. + + The generated Summary has a Tensor.proto containing the input Tensor. + + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: A real numeric Tensor containing a single value. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + family: Optional; if provided, used as the prefix of the summary tag name, + which controls the tab name used for display on Tensorboard. + + Returns: + A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf. + + Raises: + ValueError: If tensor has the wrong shape or type. + + @compatibility(TF2) + For compatibility purposes, when invoked in TF2 where the outermost context is + eager mode, this API will check if there is a suitable TF2 summary writer + context available, and if so will forward this call to that writer instead. A + "suitable" writer context means that the writer is set as the default writer, + and there is an associated non-empty value for `step` (see + `tf.summary.SummaryWriter.as_default`, `tf.summary.experimental.set_step` or + alternatively `tf.compat.v1.train.create_global_step`). For the forwarded + call, the arguments here will be passed to the TF2 implementation of + `tf.summary.scalar`, and the return value will be an empty bytestring tensor, + to avoid duplicate summary writing. This forwarding is best-effort and not all + arguments will be preserved. + + To migrate to TF2, please use `tf.summary.scalar` instead. Please check + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x) for concrete + steps for migration. `tf.summary.scalar` can also log training metrics in + Keras, you can check [Logging training metrics in + Keras](https://www.tensorflow.org/tensorboard/scalars_and_keras) for details. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------ | :-------------- | :------------------------------------- | + | `name` | `name` | - | + | `tensor` | `data` | - | + | - | `step` | Explicit int64-castable monotonic step | + : : : value. If omitted, this defaults to : + : : : `tf.summary.experimental.get_step()`. : + | `collections` | Not Supported | - | + | `family` | Removed | Please use `tf.name_scope` instead to | + : : : manage summary name prefix. : + | - | `description` | Optional long-form `str` description | + : : : for the summary. Markdown is supported.: + : : : Defaults to empty. : + + @end_compatibility + """ + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + + # Special case: invoke v2 op for TF2 users who have a v2 writer. + if _should_invoke_v2_op(): + # Defer the import to happen inside the symbol to prevent breakage due to + # missing dependency. + from tensorboard.summary.v2 import scalar as scalar_v2 # pylint: disable=g-import-not-at-top + with _compat_summary_scope(name, family) as tag: + scalar_v2(name=tag, data=tensor, step=_get_step_for_v2()) + # Return an empty Tensor, which will be acceptable as an input to the + # `tf.compat.v1.summary.merge()` API. + return _constant_op.constant(b'') + + # Fall back to legacy v1 scalar implementation. + with _summary_op_util.summary_scope( + name, family, values=[tensor]) as (tag, scope): + val = _gen_logging_ops.scalar_summary(tags=tag, values=tensor, name=scope) + _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) + return val + + +@tf_export(v1=['summary.image']) +def image(name, tensor, max_outputs=3, collections=None, family=None): + """Outputs a `Summary` protocol buffer with images. + + The summary has up to `max_outputs` summary values containing images. The + images are built from `tensor` which must be 4-D with shape `[batch_size, + height, width, channels]` and where `channels` can be: + + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + + The images have the same number of channels as the input tensor. For float + input, the values are normalized one image at a time to fit in the range + `[0, 255]`. `uint8` values are unchanged. The op uses two different + normalization algorithms: + + * If the input values are all positive, they are rescaled so the largest one + is 255. + + * If any input value is negative, the values are shifted so input value 0.0 + is at 127. They are then rescaled so that either the smallest value is 0, + or the largest one is 255. + + The `tag` in the outputted Summary.Value protobufs is generated based on the + name, with a suffix depending on the max_outputs setting: + + * If `max_outputs` is 1, the summary value tag is '*name*/image'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*name*/image/0', '*name*/image/1', etc. + + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: A 4-D `uint8` or `float32` `Tensor` of shape `[batch_size, height, + width, channels]` where `channels` is 1, 3, or 4. + max_outputs: Max number of batch elements to generate images for. + collections: Optional list of ops.GraphKeys. The collections to add the + summary to. Defaults to [_ops.GraphKeys.SUMMARIES] + family: Optional; if provided, used as the prefix of the summary tag name, + which controls the tab name used for display on Tensorboard. + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + + @compatibility(TF2) + For compatibility purposes, when invoked in TF2 where the outermost context is + eager mode, this API will check if there is a suitable TF2 summary writer + context available, and if so will forward this call to that writer instead. A + "suitable" writer context means that the writer is set as the default writer, + and there is an associated non-empty value for `step` (see + `tf.summary.SummaryWriter.as_default`, `tf.summary.experimental.set_step` or + alternatively `tf.compat.v1.train.create_global_step`). For the forwarded + call, the arguments here will be passed to the TF2 implementation of + `tf.summary.image`, and the return value will be an empty bytestring tensor, + to avoid duplicate summary writing. This forwarding is best-effort and not all + arguments will be preserved. Additionally: + + * The TF2 op does not do any of the normalization steps described above. + Rather than rescaling data that's outside the expected range, it simply + clips it. + * The TF2 op just outputs the data under a single tag that contains multiple + samples, rather than multiple tags (i.e. no "/0" or "/1" suffixes). + + To migrate to TF2, please use `tf.summary.image` instead. Please check + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x) for concrete + steps for migration. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------ | :-------------- | :------------------------------------- | + | `name` | `name` | - | + | `tensor` | `data` | - | + | - | `step` | Explicit int64-castable monotonic step | + : : : value. If omitted, this defaults to : + : : : `tf.summary.experimental.get_step()`. : + | `max_outputs` | `max_outputs` | - | + | `collections` | Not Supported | - | + | `family` | Removed | Please use `tf.name_scope` instead | + : : : to manage summary name prefix. : + | - | `description` | Optional long-form `str` description | + : : : for the summary. Markdown is supported.: + : : : Defaults to empty. : + + @end_compatibility + """ + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + + # Special case: invoke v2 op for TF2 users who have a v2 writer. + if _should_invoke_v2_op(): + # Defer the import to happen inside the symbol to prevent breakage due to + # missing dependency. + from tensorboard.summary.v2 import image as image_v2 # pylint: disable=g-import-not-at-top + with _compat_summary_scope(name, family) as tag: + image_v2( + name=tag, + data=tensor, + step=_get_step_for_v2(), + max_outputs=max_outputs) + # Return an empty Tensor, which will be acceptable as an input to the + # `tf.compat.v1.summary.merge()` API. + return _constant_op.constant(b'') + + # Fall back to legacy v1 image implementation. + with _summary_op_util.summary_scope( + name, family, values=[tensor]) as (tag, scope): + val = _gen_logging_ops.image_summary( + tag=tag, tensor=tensor, max_images=max_outputs, name=scope) + _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) + return val + + +@tf_export(v1=['summary.histogram']) +def histogram(name, values, collections=None, family=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with a histogram. + + Adding a histogram summary makes it possible to visualize your data's + distribution in TensorBoard. You can see a detailed explanation of the + TensorBoard histogram dashboard + [here](https://www.tensorflow.org/get_started/tensorboard_histograms). + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + + This op reports an `InvalidArgument` error if any value is not finite. + + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + values: A real numeric `Tensor`. Any shape. Values to use to + build the histogram. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + family: Optional; if provided, used as the prefix of the summary tag name, + which controls the tab name used for display on Tensorboard. + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + + @compatibility(TF2) + For compatibility purposes, when invoked in TF2 where the outermost context is + eager mode, this API will check if there is a suitable TF2 summary writer + context available, and if so will forward this call to that writer instead. A + "suitable" writer context means that the writer is set as the default writer, + and there is an associated non-empty value for `step` (see + `tf.summary.SummaryWriter.as_default`, `tf.summary.experimental.set_step` or + alternatively `tf.compat.v1.train.create_global_step`). For the forwarded + call, the arguments here will be passed to the TF2 implementation of + `tf.summary.histogram`, and the return value will be an empty bytestring + tensor, to avoid duplicate summary writing. This forwarding is best-effort and + not all arguments will be preserved. + + To migrate to TF2, please use `tf.summary.histogram` instead. Please check + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x) for concrete + steps for migration. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------ | :-------------- | :------------------------------------- | + | `name` | `name` | - | + | `values` | `data` | - | + | - | `step` | Explicit int64-castable monotonic step | + : : : value. If omitted, this defaults to : + : : : `tf.summary.experimental.get_step()` : + | - | `buckets` | Optional positive `int` specifying | + : : : the histogram bucket number. : + | `collections` | Not Supported | - | + | `family` | Removed | Please use `tf.name_scope` instead | + : : : to manage summary name prefix. : + | - | `description` | Optional long-form `str` description | + : : : for the summary. Markdown is supported.: + : : : Defaults to empty. : + + @end_compatibility + """ + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + + # Special case: invoke v2 op for TF2 users who have a v2 writer. + if _should_invoke_v2_op(): + # Defer the import to happen inside the symbol to prevent breakage due to + # missing dependency. + from tensorboard.summary.v2 import histogram as histogram_v2 # pylint: disable=g-import-not-at-top + with _compat_summary_scope(name, family) as tag: + histogram_v2(name=tag, data=values, step=_get_step_for_v2()) + # Return an empty Tensor, which will be acceptable as an input to the + # `tf.compat.v1.summary.merge()` API. + return _constant_op.constant(b'') + + # Fall back to legacy v1 histogram implementation. + with _summary_op_util.summary_scope( + name, family, values=[values], + default_name='HistogramSummary') as (tag, scope): + val = _gen_logging_ops.histogram_summary( + tag=tag, values=values, name=scope) + _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) + return val + + +@tf_export(v1=['summary.audio']) +def audio(name, tensor, sample_rate, max_outputs=3, collections=None, + family=None): + # pylint: disable=line-too-long + """Outputs a `Summary` protocol buffer with audio. + + The summary has up to `max_outputs` summary values containing audio. The + audio is built from `tensor` which must be 3-D with shape `[batch_size, + frames, channels]` or 2-D with shape `[batch_size, frames]`. The values are + assumed to be in the range of `[-1.0, 1.0]` with a sample rate of + `sample_rate`. + + The `tag` in the outputted Summary.Value protobufs is generated based on the + name, with a suffix depending on the max_outputs setting: + + * If `max_outputs` is 1, the summary value tag is '*name*/audio'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*name*/audio/0', '*name*/audio/1', etc + + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: A 3-D `float32` `Tensor` of shape `[batch_size, frames, channels]` + or a 2-D `float32` `Tensor` of shape `[batch_size, frames]`. + sample_rate: A Scalar `float32` `Tensor` indicating the sample rate of the + signal in hertz. + max_outputs: Max number of batch elements to generate audio for. + collections: Optional list of ops.GraphKeys. The collections to add the + summary to. Defaults to [_ops.GraphKeys.SUMMARIES] + family: Optional; if provided, used as the prefix of the summary tag name, + which controls the tab name used for display on Tensorboard. + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + + @compatibility(TF2) + For compatibility purposes, when invoked in TF2 where the outermost context is + eager mode, this API will check if there is a suitable TF2 summary writer + context available, and if so will forward this call to that writer instead. A + "suitable" writer context means that the writer is set as the default writer, + and there is an associated non-empty value for `step` (see + `tf.summary.SummaryWriter.as_default`, `tf.summary.experimental.set_step` or + alternatively `tf.compat.v1.train.create_global_step`). For the forwarded + call, the arguments here will be passed to the TF2 implementation of + `tf.summary.audio`, and the return value will be an empty bytestring tensor, + to avoid duplicate summary writing. This forwarding is best-effort and not all + arguments will be preserved. Additionally: + + * The TF2 op just outputs the data under a single tag that contains multiple + samples, rather than multiple tags (i.e. no "/0" or "/1" suffixes). + + To migrate to TF2, please use `tf.summary.audio` instead. Please check + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x) for concrete + steps for migration. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------ | :-------------- | :------------------------------------- | + | `name` | `name` | - | + | `tensor` | `data` | Input for this argument now must be | + : : : three-dimensional `[k, t, c]`, where : + : : : `k` is the number of audio clips, `t` : + : : : is the number of frames, and `c` is : + : : : the number of channels. Two-dimensional: + : : : input is no longer supported. : + | `sample_rate` | `sample_rate` | - | + | - | `step` | Explicit int64-castable monotonic step | + : : : value. If omitted, this defaults to : + : : : `tf.summary.experimental.get_step()`. : + | `max_outputs` | `max_outputs` | - | + | `collections` | Not Supported | - | + | `family` | Removed | Please use `tf.name_scope` instead to | + : : : manage summary name prefix. : + | - | `encoding` | Optional constant str for the desired | + : : : encoding. Check the docs for : + : : : `tf.summary.audio` for latest supported: + : : : audio formats. : + | - | `description` | Optional long-form `str` description | + : : : for the summary. Markdown is supported.: + : : : Defaults to empty. : + + @end_compatibility + """ + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + + # Special case: invoke v2 op for TF2 users who have a v2 writer. + if _should_invoke_v2_op(): + # Defer the import to happen inside the symbol to prevent breakage due to + # missing dependency. + from tensorboard.summary.v2 import audio as audio_v2 # pylint: disable=g-import-not-at-top + if tensor.shape.rank == 2: + # TF2 op requires 3-D tensor, add the `channels` dimension. + tensor = _array_ops.expand_dims_v2(tensor, axis=2) + with _compat_summary_scope(name, family) as tag: + audio_v2( + name=tag, + data=tensor, + sample_rate=sample_rate, + step=_get_step_for_v2(), + max_outputs=max_outputs, + ) + # Return an empty Tensor, which will be acceptable as an input to the + # `tf.compat.v1.summary.merge()` API. + return _constant_op.constant(b'') + + # Fall back to legacy v1 audio implementation. + with _summary_op_util.summary_scope( + name, family=family, values=[tensor]) as (tag, scope): + sample_rate = _ops.convert_to_tensor( + sample_rate, dtype=_dtypes.float32, name='sample_rate') + val = _gen_logging_ops.audio_summary_v2( + tag=tag, tensor=tensor, max_outputs=max_outputs, + sample_rate=sample_rate, name=scope) + _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) + return val + + +@tf_export(v1=['summary.text']) +def text(name, tensor, collections=None): + """Summarizes textual data. + + Text data summarized via this plugin will be visible in the Text Dashboard + in TensorBoard. The standard TensorBoard Text Dashboard will render markdown + in the strings, and will automatically organize 1d and 2d tensors into tables. + If a tensor with more than 2 dimensions is provided, a 2d subarray will be + displayed along with a warning message. (Note that this behavior is not + intrinsic to the text summary api, but rather to the default TensorBoard text + plugin.) + + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: a string-type Tensor to summarize. + collections: Optional list of ops.GraphKeys. The collections to add the + summary to. Defaults to [_ops.GraphKeys.SUMMARIES] + + Returns: + A TensorSummary op that is configured so that TensorBoard will recognize + that it contains textual data. The TensorSummary is a scalar `Tensor` of + type `string` which contains `Summary` protobufs. + + Raises: + ValueError: If tensor has the wrong type. + + @compatibility(TF2) + For compatibility purposes, when invoked in TF2 where the outermost context is + eager mode, this API will check if there is a suitable TF2 summary writer + context available, and if so will forward this call to that writer instead. A + "suitable" writer context means that the writer is set as the default writer, + and there is an associated non-empty value for `step` (see + `tf.summary.SummaryWriter.as_default`, `tf.summary.experimental.set_step` or + alternatively `tf.compat.v1.train.create_global_step`). For the forwarded + call, the arguments here will be passed to the TF2 implementation of + `tf.summary.text`, and the return value will be an empty bytestring tensor, to + avoid duplicate summary writing. This forwarding is best-effort and not all + arguments will be preserved. + + To migrate to TF2, please use `tf.summary.text` instead. Please check + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x) for concrete + steps for migration. + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :------------ | :-------------- | :------------------------------------- | + | `name` | `name` | - | + | `tensor` | `data` | - | + | - | `step` | Explicit int64-castable monotonic step | + : : : value. If omitted, this defaults to : + : : : `tf.summary.experimental.get_step()`. : + | `collections` | Not Supported | - | + | - | `description` | Optional long-form `str` description | + : : : for the summary. Markdown is supported.: + : : : Defaults to empty. : + + @end_compatibility + """ + if tensor.dtype != _dtypes.string: + raise ValueError('Expected tensor %s to have dtype string, got %s' % + (tensor.name, tensor.dtype)) + + # Special case: invoke v2 op for TF2 users who have a v2 writer. + if _should_invoke_v2_op(): + # `skip_summary` check for v1 op case is done in `tensor_summary`. + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + # Defer the import to happen inside the symbol to prevent breakage due to + # missing dependency. + from tensorboard.summary.v2 import text as text_v2 # pylint: disable=g-import-not-at-top + text_v2(name=name, data=tensor, step=_get_step_for_v2()) + # Return an empty Tensor, which will be acceptable as an input to the + # `tf.compat.v1.summary.merge()` API. + return _constant_op.constant(b'') + + # Fall back to legacy v1 text implementation. + summary_metadata = _SummaryMetadata( + plugin_data=_SummaryMetadata.PluginData(plugin_name='text')) + t_summary = tensor_summary( + name=name, + tensor=tensor, + summary_metadata=summary_metadata, + collections=collections) + return t_summary + + +@tf_export(v1=['summary.tensor_summary']) +def tensor_summary(name, + tensor, + summary_description=None, + collections=None, + summary_metadata=None, + family=None, + display_name=None): + """Outputs a `Summary` protocol buffer with a serialized tensor.proto. + + Args: + name: A name for the generated node. If display_name is not set, it will + also serve as the tag name in TensorBoard. (In that case, the tag + name will inherit tf name scopes.) + tensor: A tensor of any type and shape to serialize. + summary_description: A long description of the summary sequence. Markdown + is supported. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + summary_metadata: Optional SummaryMetadata proto (which describes which + plugins may use the summary value). + family: Optional; if provided, used as the prefix of the summary tag, + which controls the name used for display on TensorBoard when + display_name is not set. + display_name: A string used to name this data in TensorBoard. If this is + not set, then the node name will be used instead. + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + + if summary_metadata is None: + summary_metadata = _SummaryMetadata() + + if summary_description is not None: + summary_metadata.summary_description = summary_description + + if display_name is not None: + summary_metadata.display_name = display_name + + serialized_summary_metadata = summary_metadata.SerializeToString() + + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + with _summary_op_util.summary_scope( + name, family, values=[tensor]) as (tag, scope): + val = _gen_logging_ops.tensor_summary_v2( + tensor=tensor, + tag=tag, + name=scope, + serialized_summary_metadata=serialized_summary_metadata) + _summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES]) + return val + + +@tf_export(v1=['summary.merge']) +def merge(inputs, collections=None, name=None): + # pylint: disable=line-too-long + """Merges summaries. + + This op creates a + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + protocol buffer that contains the union of all the values in the input + summaries. + + When the Op is run, it reports an `InvalidArgument` error if multiple values + in the summaries to merge use the same tag. + + Args: + inputs: A list of `string` `Tensor` objects containing serialized `Summary` + protocol buffers. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer resulting from the merging. + + Raises: + RuntimeError: If called with eager mode enabled. + + @compatibility(TF2) + This API is not compatible with eager execution or `tf.function`. To migrate + to TF2, this API can be omitted entirely, because in TF2 individual summary + ops, like `tf.summary.scalar()`, write directly to the default summary writer + if one is active. Thus, it's not necessary to merge summaries or to manually + add the resulting merged summary output to the writer. See the usage example + shown below. + + For a comprehensive `tf.summary` migration guide, please follow + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x). + + #### TF1 & TF2 Usage Example + + TF1: + + ```python + dist = tf.compat.v1.placeholder(tf.float32, [100]) + tf.compat.v1.summary.histogram(name="distribution", values=dist) + writer = tf.compat.v1.summary.FileWriter("/tmp/tf1_summary_example") + summaries = tf.compat.v1.summary.merge_all() + + sess = tf.compat.v1.Session() + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + summ = sess.run(summaries, feed_dict={dist: mean_moving_normal}) + writer.add_summary(summ, global_step=step) + ``` + + TF2: + + ```python + writer = tf.summary.create_file_writer("/tmp/tf2_summary_example") + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + with writer.as_default(step=step): + tf.summary.histogram(name='distribution', data=mean_moving_normal) + ``` + + @end_compatibility + """ + # pylint: enable=line-too-long + if _context.executing_eagerly(): + raise RuntimeError( + 'Merging tf.summary.* ops is not compatible with eager execution. ' + 'Use tf.contrib.summary instead.') + if _distribute_summary_op_util.skip_summary(): + return _constant_op.constant('') + name = _summary_op_util.clean_tag(name) + with _ops.name_scope(name, 'Merge', inputs): + val = _gen_logging_ops.merge_summary(inputs=inputs, name=name) + _summary_op_util.collect(val, collections, []) + return val + + +@tf_export(v1=['summary.merge_all']) +def merge_all(key=_ops.GraphKeys.SUMMARIES, scope=None, name=None): + """Merges all summaries collected in the default graph. + + Args: + key: `GraphKey` used to collect the summaries. Defaults to + `GraphKeys.SUMMARIES`. + scope: Optional scope used to filter the summary ops, using `re.match`. + name: A name for the operation (optional). + + Returns: + If no summaries were collected, returns None. Otherwise returns a scalar + `Tensor` of type `string` containing the serialized `Summary` protocol + buffer resulting from the merging. + + Raises: + RuntimeError: If called with eager execution enabled. + + @compatibility(TF2) + This API is not compatible with eager execution or `tf.function`. To migrate + to TF2, this API can be omitted entirely, because in TF2 individual summary + ops, like `tf.summary.scalar()`, write directly to the default summary writer + if one is active. Thus, it's not necessary to merge summaries or to manually + add the resulting merged summary output to the writer. See the usage example + shown below. + + For a comprehensive `tf.summary` migration guide, please follow + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x). + + #### TF1 & TF2 Usage Example + + TF1: + + ```python + dist = tf.compat.v1.placeholder(tf.float32, [100]) + tf.compat.v1.summary.histogram(name="distribution", values=dist) + writer = tf.compat.v1.summary.FileWriter("/tmp/tf1_summary_example") + summaries = tf.compat.v1.summary.merge_all() + + sess = tf.compat.v1.Session() + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + summ = sess.run(summaries, feed_dict={dist: mean_moving_normal}) + writer.add_summary(summ, global_step=step) + ``` + + TF2: + + ```python + writer = tf.summary.create_file_writer("/tmp/tf2_summary_example") + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + with writer.as_default(step=step): + tf.summary.histogram(name='distribution', data=mean_moving_normal) + ``` + + @end_compatibility + """ + if _context.executing_eagerly(): + raise RuntimeError( + 'Merging tf.summary.* ops is not compatible with eager execution. ' + 'Use tf.contrib.summary instead.') + summary_ops = _ops.get_collection(key, scope=scope) + if not summary_ops: + return None + else: + return merge(summary_ops, name=name) + + +@tf_export(v1=['summary.get_summary_description']) +def get_summary_description(node_def): + """Given a TensorSummary node_def, retrieve its SummaryDescription. + + When a Summary op is instantiated, a SummaryDescription of associated + metadata is stored in its NodeDef. This method retrieves the description. + + Args: + node_def: the node_def_pb2.NodeDef of a TensorSummary op + + Returns: + a summary_pb2.SummaryDescription + + Raises: + ValueError: if the node is not a summary op. + + @compatibility(eager) + Not compatible with eager execution. To write TensorBoard + summaries under eager execution, use `tf.contrib.summary` instead. + @end_compatibility + """ + + if node_def.op != 'TensorSummary': + raise ValueError("Can't get_summary_description on %s" % node_def.op) + description_str = _compat.as_str_any(node_def.attr['description'].s) + summary_description = SummaryDescription() + _json_format.Parse(description_str, summary_description) + return summary_description + + +def _get_step_for_v2(): + """Get step for v2 summary invocation in v1. + + In order to invoke v2 op in `tf.compat.v1.summary`, global step needs to be + set for the v2 summary writer. + + Returns: + The step set by `tf.summary.experimental.set_step` or + `tf.compat.v1.train.create_global_step`, or None is no step has been + set. + """ + step = _summary_ops_v2.get_step() + if step is not None: + return step + return _training_util.get_global_step() + + +def _should_invoke_v2_op(): + """Check if v2 op can be invoked. + + When calling TF1 summary op in eager mode, if the following conditions are + met, v2 op will be invoked: + - The outermost context is eager mode. + - A default TF2 summary writer is present. + - A step is set for the writer (using `tf.summary.SummaryWriter.as_default`, + `tf.summary.experimental.set_step` or + `tf.compat.v1.train.create_global_step`). + + Returns: + A boolean indicating whether v2 summary op should be invoked. + """ + # Check if in eager mode. + if not _ops.executing_eagerly_outside_functions(): + return False + # Check if a default summary writer is present. + if not _summary_ops_v2.has_default_writer(): + warnings.warn( + 'Cannot activate TF2 compatibility support for TF1 summary ops: ' + 'default summary writer not found.') + return False + # Check if a step is set for the writer. + if _get_step_for_v2() is None: + warnings.warn( + 'Cannot activate TF2 compatibility support for TF1 summary ops: ' + 'global step not set. To set step for summary writer, ' + 'use `tf.summary.SummaryWriter.as_default(step=_)`, ' + '`tf.summary.experimental.set_step()` or ' + '`tf.compat.v1.train.create_global_step()`.') + return False + return True + + +@contextlib.contextmanager +def _compat_summary_scope(name, family): + """Handles `family` argument for v2 op invocation in v1.""" + # Get a new summary tag name with the `family` arg. + with _summary_op_util.summary_scope(name, family) as (tag, _): + # Reset the root name scope with an empty summary_scope. + with _summary_op_util.summary_scope(name='', family=None): + yield tag diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary_iterator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0a8340b963b64ce4581722b7f49b86636d2e42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/summary_iterator.py @@ -0,0 +1,91 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Provides a method for reading events from an event file via an iterator.""" + +from tensorflow.core.util import event_pb2 +from tensorflow.python.lib.io import tf_record +from tensorflow.python.util.tf_export import tf_export + + +class _SummaryIterator(object): + """Yields `Event` protocol buffers from a given path.""" + + def __init__(self, path): + self._tf_record_iterator = tf_record.tf_record_iterator(path) + + def __iter__(self): + return self + + def __next__(self): + r = next(self._tf_record_iterator) + return event_pb2.Event.FromString(r) + + next = __next__ + + +@tf_export(v1=['train.summary_iterator']) +def summary_iterator(path): + # pylint: disable=line-too-long + """Returns a iterator for reading `Event` protocol buffers from an event file. + + You can use this function to read events written to an event file. It returns + a Python iterator that yields `Event` protocol buffers. + + Example: Print the contents of an events file. + + ```python + for e in tf.compat.v1.train.summary_iterator(path to events file): + print(e) + ``` + + Example: Print selected summary values. + + ```python + # This example supposes that the events file contains summaries with a + # summary value tag 'loss'. These could have been added by calling + # `add_summary()`, passing the output of a scalar summary op created with + # with: `tf.compat.v1.summary.scalar('loss', loss_tensor)`. + for e in tf.compat.v1.train.summary_iterator(path to events file): + for v in e.summary.value: + if v.tag == 'loss': + print(tf.make_ndarray(v.tensor)) + ``` + Example: Continuously check for new summary values. + + ```python + summaries = tf.compat.v1.train.summary_iterator(path to events file) + while True: + for e in summaries: + for v in e.summary.value: + if v.tag == 'loss': + print(tf.make_ndarray(v.tensor)) + # Wait for a bit before checking the file for any new events + time.sleep(wait time) + ``` + + See the protocol buffer definitions of + [Event](https://www.tensorflow.org/code/tensorflow/core/util/event.proto) + and + [Summary](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + for more information about their attributes. + + Args: + path: The path to an event file created by a `SummaryWriter`. + + Returns: + A iterator that yields `Event` protocol buffers + """ + return _SummaryIterator(path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7865c4d845ee2f01e337bc775f7b658ee5dd3f41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer.py @@ -0,0 +1,299 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Writes events to disk in a logdir.""" + +import collections +import os.path +import sys +import threading +import time + +from tensorflow.python.client import _pywrap_events_writer +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat + + +class EventFileWriter: + """Writes `Event` protocol buffers to an event file. + + The `EventFileWriter` class creates an event file in the specified directory, + and asynchronously writes Event protocol buffers to the file. The Event file + is encoded using the tfrecord format, which is similar to RecordIO. + + This class is not thread-safe. + """ + + def __init__(self, logdir, max_queue=10, flush_secs=120, + filename_suffix=None): + """Creates a `EventFileWriter` and an event file to write to. + + On construction the summary writer creates a new event file in `logdir`. + This event file will contain `Event` protocol buffers, which are written to + disk via the add_event method. + + The other arguments to the constructor control the asynchronous writes to + the event file: + + * `flush_secs`: How often, in seconds, to flush the added summaries + and events to disk. + * `max_queue`: Maximum number of summaries or events pending to be + written to disk before one of the 'add' calls block. + + Args: + logdir: A string. Directory where event file will be written. + max_queue: Integer. Size of the queue for pending events and summaries. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. + filename_suffix: A string. Every event file's name is suffixed with + `filename_suffix`. + """ + self._logdir = str(logdir) + gfile.MakeDirs(self._logdir) + self._max_queue = max_queue + self._flush_secs = flush_secs + self._flush_complete = threading.Event() + self._flush_sentinel = object() + self._close_sentinel = object() + self._ev_writer = _pywrap_events_writer.EventsWriter( + compat.as_bytes(os.path.join(self._logdir, "events"))) + if filename_suffix: + self._ev_writer.InitWithSuffix(compat.as_bytes(filename_suffix)) + self._initialize() + self._closed = False + + def _initialize(self): + """Initializes or re-initializes the queue and writer thread. + + The EventsWriter itself does not need to be re-initialized explicitly, + because it will auto-initialize itself if used after being closed. + """ + self._event_queue = CloseableQueue(self._max_queue) + self._worker = _EventLoggerThread(self._event_queue, self._ev_writer, + self._flush_secs, self._flush_complete, + self._flush_sentinel, + self._close_sentinel) + + self._worker.start() + + def get_logdir(self): + """Returns the directory where event file will be written.""" + return self._logdir + + def reopen(self): + """Reopens the EventFileWriter. + + Can be called after `close()` to add more events in the same directory. + The events will go into a new events file. + + Does nothing if the EventFileWriter was not closed. + """ + if self._closed: + self._initialize() + self._closed = False + + def add_event(self, event): + """Adds an event to the event file. + + Args: + event: An `Event` protocol buffer. + """ + if not self._closed: + self._try_put(event) + + def _try_put(self, item): + """Attempts to enqueue an item to the event queue. + + If the queue is closed, this will close the EventFileWriter and reraise the + exception that caused the queue closure, if one exists. + + Args: + item: the item to enqueue + """ + try: + self._event_queue.put(item) + except QueueClosedError: + self._internal_close() + if self._worker.failure_exc_info: + _, exception, _ = self._worker.failure_exc_info + raise exception from None + + def flush(self): + """Flushes the event file to disk. + + Call this method to make sure that all pending events have been written to + disk. + """ + if not self._closed: + # Request a flush operation by enqueuing a sentinel and then waiting for + # the writer thread to mark the flush as complete. + self._flush_complete.clear() + self._try_put(self._flush_sentinel) + self._flush_complete.wait() + if self._worker.failure_exc_info: + self._internal_close() + _, exception, _ = self._worker.failure_exc_info + raise exception + + def close(self): + """Flushes the event file to disk and close the file. + + Call this method when you do not need the summary writer anymore. + """ + if not self._closed: + self.flush() + self._try_put(self._close_sentinel) + self._internal_close() + + def _internal_close(self): + self._closed = True + self._worker.join() + self._ev_writer.Close() + + +class _EventLoggerThread(threading.Thread): + """Thread that logs events.""" + + def __init__(self, queue, ev_writer, flush_secs, flush_complete, + flush_sentinel, close_sentinel): + """Creates an _EventLoggerThread. + + Args: + queue: A CloseableQueue from which to dequeue events. The queue will be + closed just before the thread exits, whether due to `close_sentinel` or + any exception raised in the writing loop. + ev_writer: An event writer. Used to log brain events for + the visualizer. + flush_secs: How often, in seconds, to flush the + pending file to disk. + flush_complete: A threading.Event that will be set whenever a flush + operation requested via `flush_sentinel` has been completed. + flush_sentinel: A sentinel element in queue that tells this thread to + flush the writer and mark the current flush operation complete. + close_sentinel: A sentinel element in queue that tells this thread to + terminate and close the queue. + """ + threading.Thread.__init__(self, name="EventLoggerThread") + self.daemon = True + self._queue = queue + self._ev_writer = ev_writer + self._flush_secs = flush_secs + # The first event will be flushed immediately. + self._next_event_flush_time = 0 + self._flush_complete = flush_complete + self._flush_sentinel = flush_sentinel + self._close_sentinel = close_sentinel + # Populated when writing logic raises an exception and kills the thread. + self.failure_exc_info = () + + def run(self): + try: + while True: + event = self._queue.get() + if event is self._close_sentinel: + return + elif event is self._flush_sentinel: + self._ev_writer.Flush() + self._flush_complete.set() + else: + self._ev_writer.WriteEvent(event) + # Flush the event writer every so often. + now = time.time() + if now > self._next_event_flush_time: + self._ev_writer.Flush() + self._next_event_flush_time = now + self._flush_secs + except Exception as e: + logging.error("EventFileWriter writer thread error: %s", e) + self.failure_exc_info = sys.exc_info() + raise + finally: + # When exiting the thread, always complete any pending flush operation + # (to unblock flush() calls) and close the queue (to unblock add_event() + # calls, including those used by flush() and close()), which ensures that + # code using EventFileWriter doesn't deadlock if this thread dies. + self._flush_complete.set() + self._queue.close() + + +class CloseableQueue: + """Stripped-down fork of the standard library Queue that is closeable.""" + + def __init__(self, maxsize=0): + """Create a queue object with a given maximum size. + + Args: + maxsize: int size of queue. If <= 0, the queue size is infinite. + """ + self._maxsize = maxsize + self._queue = collections.deque() + self._closed = False + # Mutex must be held whenever queue is mutating; shared by conditions. + self._mutex = threading.Lock() + # Notify not_empty whenever an item is added to the queue; a + # thread waiting to get is notified then. + self._not_empty = threading.Condition(self._mutex) + # Notify not_full whenever an item is removed from the queue; + # a thread waiting to put is notified then. + self._not_full = threading.Condition(self._mutex) + + def get(self): + """Remove and return an item from the queue. + + If the queue is empty, blocks until an item is available. + + Returns: + an item from the queue + """ + with self._not_empty: + while not self._queue: + self._not_empty.wait() + item = self._queue.popleft() + self._not_full.notify() + return item + + def put(self, item): + """Put an item into the queue. + + If the queue is closed, fails immediately. + + If the queue is full, blocks until space is available or until the queue + is closed by a call to close(), at which point this call fails. + + Args: + item: an item to add to the queue + + Raises: + QueueClosedError: if insertion failed because the queue is closed + """ + with self._not_full: + if self._closed: + raise QueueClosedError() + if self._maxsize > 0: + while len(self._queue) == self._maxsize: + self._not_full.wait() + if self._closed: + raise QueueClosedError() + self._queue.append(item) + self._not_empty.notify() + + def close(self): + """Closes the queue, causing any pending or future `put()` calls to fail.""" + with self._not_full: + self._closed = True + self._not_full.notify_all() + + +class QueueClosedError(Exception): + """Raised when CloseableQueue.put() fails because the queue is closed.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..8f8d4790e509bfe7ca5ea5a99a98f2fa294e2790 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/event_file_writer_v2.py @@ -0,0 +1,136 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Writes events to disk in a logdir.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.platform import gfile + + +class EventFileWriterV2(object): + """Writes `Event` protocol buffers to an event file via the graph. + + The `EventFileWriterV2` class is backed by the summary file writer in the v2 + summary API (currently in tf.contrib.summary), so it uses a shared summary + writer resource and graph ops to write events. + + As with the original EventFileWriter, this class will asynchronously write + Event protocol buffers to the backing file. The Event file is encoded using + the tfrecord format, which is similar to RecordIO. + """ + + def __init__(self, session, logdir, max_queue=10, flush_secs=120, + filename_suffix=''): + """Creates an `EventFileWriterV2` and an event file to write to. + + On construction, this calls `tf.contrib.summary.create_file_writer` within + the graph from `session.graph` to look up a shared summary writer resource + for `logdir` if one exists, and create one if not. Creating the summary + writer resource in turn creates a new event file in `logdir` to be filled + with `Event` protocol buffers passed to `add_event`. Graph ops to control + this writer resource are added to `session.graph` during this init call; + stateful methods on this class will call `session.run()` on these ops. + + Note that because the underlying resource is shared, it is possible that + other parts of the code using the same session may interact independently + with the resource, e.g. by flushing or even closing it. It is the caller's + responsibility to avoid any undesirable sharing in this regard. + + The remaining arguments to the constructor (`flush_secs`, `max_queue`, and + `filename_suffix`) control the construction of the shared writer resource + if one is created. If an existing resource is reused, these arguments have + no effect. See `tf.contrib.summary.create_file_writer` for details. + + Args: + session: A `tf.compat.v1.Session`. Session that will hold shared writer + resource. The writer ops will be added to session.graph during this + init call. + logdir: A string. Directory where event file will be written. + max_queue: Integer. Size of the queue for pending events and summaries. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. + filename_suffix: A string. Every event file's name is suffixed with + `filename_suffix`. + """ + self._session = session + self._logdir = logdir + self._closed = False + gfile.MakeDirs(self._logdir) + + with self._session.graph.as_default(): + with ops.name_scope('filewriter'): + file_writer = summary_ops_v2.create_file_writer( + logdir=self._logdir, + max_queue=max_queue, + flush_millis=flush_secs * 1000, + filename_suffix=filename_suffix) + with summary_ops_v2.always_record_summaries(), file_writer.as_default(): + self._event_placeholder = array_ops.placeholder_with_default( + constant_op.constant('unused', dtypes.string), + shape=[]) + self._add_event_op = summary_ops_v2.import_event( + self._event_placeholder) + self._init_op = file_writer.init() # pylint: disable=assignment-from-no-return + self._flush_op = file_writer.flush() # pylint: disable=assignment-from-no-return + self._close_op = file_writer.close() # pylint: disable=assignment-from-no-return + self._session.run(self._init_op) + + def get_logdir(self): + """Returns the directory where event file will be written.""" + return self._logdir + + def reopen(self): + """Reopens the EventFileWriter. + + Can be called after `close()` to add more events in the same directory. + The events will go into a new events file. + + Does nothing if the EventFileWriter was not closed. + """ + if self._closed: + self._closed = False + self._session.run(self._init_op) + + def add_event(self, event): + """Adds an event to the event file. + + Args: + event: An `Event` protocol buffer. + """ + if not self._closed: + event_pb = event.SerializeToString() + self._session.run( + self._add_event_op, feed_dict={self._event_placeholder: event_pb}) + + def flush(self): + """Flushes the event file to disk. + + Call this method to make sure that all pending events have been written to + disk. + """ + self._session.run(self._flush_op) + + def close(self): + """Flushes the event file to disk and close the file. + + Call this method when you do not need the summary writer anymore. + """ + if not self._closed: + self.flush() + self._session.run(self._close_op) + self._closed = True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..13373d2f22db4b0715650c6df7ef849361545ce3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer.py @@ -0,0 +1,483 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Provides an API for generating Event protocol buffers.""" + +import os.path +import time +import warnings + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import summary_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.summary import plugin_asset +from tensorflow.python.summary.writer.event_file_writer import EventFileWriter +from tensorflow.python.summary.writer.event_file_writer_v2 import EventFileWriterV2 +from tensorflow.python.util.tf_export import tf_export + +_PLUGINS_DIR = "plugins" + + +class SummaryToEventTransformer(object): + """Abstractly implements the SummaryWriter API. + + This API basically implements a number of endpoints (add_summary, + add_session_log, etc). The endpoints all generate an event protobuf, which is + passed to the contained event_writer. + """ + + def __init__(self, event_writer, graph=None, graph_def=None): + """Creates a `SummaryWriter` and an event file. + + On construction the summary writer creates a new event file in `logdir`. + This event file will contain `Event` protocol buffers constructed when you + call one of the following functions: `add_summary()`, `add_session_log()`, + `add_event()`, or `add_graph()`. + + If you pass a `Graph` to the constructor it is added to + the event file. (This is equivalent to calling `add_graph()` later). + + TensorBoard will pick the graph from the file and display it graphically so + you can interactively explore the graph you built. You will usually pass + the graph from the session in which you launched it: + + ```python + ...create a graph... + # Launch the graph in a session. + sess = tf.compat.v1.Session() + # Create a summary writer, add the 'graph' to the event file. + writer = tf.compat.v1.summary.FileWriter(, sess.graph) + ``` + + + Args: + event_writer: An EventWriter. Implements add_event and get_logdir. + graph: A `Graph` object, such as `sess.graph`. + graph_def: DEPRECATED: Use the `graph` argument instead. + """ + self.event_writer = event_writer + # For storing used tags for session.run() outputs. + self._session_run_tags = {} + if graph is not None or graph_def is not None: + # Calling it with both graph and graph_def for backward compatibility. + self.add_graph(graph=graph, graph_def=graph_def) + # Also export the meta_graph_def in this case. + # graph may itself be a graph_def due to positional arguments + maybe_graph_as_def = (graph.as_graph_def(add_shapes=True) + if isinstance(graph, ops.Graph) else graph) + self.add_meta_graph( + meta_graph.create_meta_graph_def(graph_def=graph_def or + maybe_graph_as_def)) + + # This set contains tags of Summary Values that have been encountered + # already. The motivation here is that the SummaryWriter only keeps the + # metadata property (which is a SummaryMetadata proto) of the first Summary + # Value encountered for each tag. The SummaryWriter strips away the + # SummaryMetadata for all subsequent Summary Values with tags seen + # previously. This saves space. + self._seen_summary_tags = set() + + def add_summary(self, summary, global_step=None): + """Adds a `Summary` protocol buffer to the event file. + + This method wraps the provided summary in an `Event` protocol buffer + and adds it to the event file. + + You can pass the result of evaluating any summary op, using + `tf.Session.run` or + `tf.Tensor.eval`, to this + function. Alternatively, you can pass a `tf.compat.v1.Summary` protocol + buffer that you populate with your own data. The latter is + commonly done to report evaluation results in event files. + + Args: + summary: A `Summary` protocol buffer, optionally serialized as a string. + global_step: Number. Optional global step value to record with the + summary. + """ + if isinstance(summary, bytes): + summ = summary_pb2.Summary() + summ.ParseFromString(summary) + summary = summ + + # We strip metadata from values with tags that we have seen before in order + # to save space - we just store the metadata on the first value with a + # specific tag. + for value in summary.value: + if not value.metadata: + continue + + if value.tag in self._seen_summary_tags: + # This tag has been encountered before. Strip the metadata. + value.ClearField("metadata") + continue + + # We encounter a value with a tag we have not encountered previously. And + # it has metadata. Remember to strip metadata from future values with this + # tag string. + self._seen_summary_tags.add(value.tag) + + event = event_pb2.Event(summary=summary) + self._add_event(event, global_step) + + def add_session_log(self, session_log, global_step=None): + """Adds a `SessionLog` protocol buffer to the event file. + + This method wraps the provided session in an `Event` protocol buffer + and adds it to the event file. + + Args: + session_log: A `SessionLog` protocol buffer. + global_step: Number. Optional global step value to record with the + summary. + """ + event = event_pb2.Event(session_log=session_log) + self._add_event(event, global_step) + + def _add_graph_def(self, graph_def, global_step=None): + graph_bytes = graph_def.SerializeToString() + event = event_pb2.Event(graph_def=graph_bytes) + self._add_event(event, global_step) + + def add_graph(self, graph, global_step=None, graph_def=None): + """Adds a `Graph` to the event file. + + The graph described by the protocol buffer will be displayed by + TensorBoard. Most users pass a graph in the constructor instead. + + Args: + graph: A `Graph` object, such as `sess.graph`. + global_step: Number. Optional global step counter to record with the + graph. + graph_def: DEPRECATED. Use the `graph` parameter instead. + + Raises: + ValueError: If both graph and graph_def are passed to the method. + """ + + if graph is not None and graph_def is not None: + raise ValueError("Please pass only graph, or graph_def (deprecated), " + "but not both.") + + if isinstance(graph, ops.Graph) or isinstance(graph_def, ops.Graph): + # The user passed a `Graph`. + + # Check if the user passed it via the graph or the graph_def argument and + # correct for that. + if not isinstance(graph, ops.Graph): + logging.warning("When passing a `Graph` object, please use the `graph`" + " named argument instead of `graph_def`.") + graph = graph_def + + # Serialize the graph with additional info. + true_graph_def = graph.as_graph_def(add_shapes=True) + self._write_plugin_assets(graph) + elif (isinstance(graph, graph_pb2.GraphDef) or + isinstance(graph_def, graph_pb2.GraphDef)): + # The user passed a `GraphDef`. + logging.warning("Passing a `GraphDef` to the SummaryWriter is deprecated." + " Pass a `Graph` object instead, such as `sess.graph`.") + + # Check if the user passed it via the graph or the graph_def argument and + # correct for that. + if isinstance(graph, graph_pb2.GraphDef): + true_graph_def = graph + else: + true_graph_def = graph_def + + else: + # The user passed neither `Graph`, nor `GraphDef`. + raise TypeError("The passed graph must be an instance of `Graph` " + "or the deprecated `GraphDef`") + # Finally, add the graph_def to the summary writer. + self._add_graph_def(true_graph_def, global_step) + + def _write_plugin_assets(self, graph): + plugin_assets = plugin_asset.get_all_plugin_assets(graph) + logdir = self.event_writer.get_logdir() + for asset_container in plugin_assets: + plugin_name = asset_container.plugin_name + plugin_dir = os.path.join(logdir, _PLUGINS_DIR, plugin_name) + gfile.MakeDirs(plugin_dir) + assets = asset_container.assets() + for (asset_name, content) in assets.items(): + asset_path = os.path.join(plugin_dir, asset_name) + with gfile.Open(asset_path, "w") as f: + f.write(content) + + def add_meta_graph(self, meta_graph_def, global_step=None): + """Adds a `MetaGraphDef` to the event file. + + The `MetaGraphDef` allows running the given graph via + `saver.import_meta_graph()`. + + Args: + meta_graph_def: A `MetaGraphDef` object, often as returned by + `saver.export_meta_graph()`. + global_step: Number. Optional global step counter to record with the + graph. + + Raises: + TypeError: If both `meta_graph_def` is not an instance of `MetaGraphDef`. + """ + if not isinstance(meta_graph_def, meta_graph_pb2.MetaGraphDef): + raise TypeError("meta_graph_def must be type MetaGraphDef, saw type: %s" % + type(meta_graph_def)) + meta_graph_bytes = meta_graph_def.SerializeToString() + event = event_pb2.Event(meta_graph_def=meta_graph_bytes) + self._add_event(event, global_step) + + def add_run_metadata(self, run_metadata, tag, global_step=None): + """Adds a metadata information for a single session.run() call. + + Args: + run_metadata: A `RunMetadata` protobuf object. + tag: The tag name for this metadata. + global_step: Number. Optional global step counter to record with the + StepStats. + + Raises: + ValueError: If the provided tag was already used for this type of event. + """ + if tag in self._session_run_tags: + raise ValueError("The provided tag was already used for this event type") + self._session_run_tags[tag] = True + + tagged_metadata = event_pb2.TaggedRunMetadata() + tagged_metadata.tag = tag + # Store the `RunMetadata` object as bytes in order to have postponed + # (lazy) deserialization when used later. + tagged_metadata.run_metadata = run_metadata.SerializeToString() + event = event_pb2.Event(tagged_run_metadata=tagged_metadata) + self._add_event(event, global_step) + + def _add_event(self, event, step): + event.wall_time = time.time() + if step is not None: + event.step = int(step) + self.event_writer.add_event(event) + + +@tf_export(v1=["summary.FileWriter"]) +class FileWriter(SummaryToEventTransformer): + """Writes `Summary` protocol buffers to event files. + + The `FileWriter` class provides a mechanism to create an event file in a + given directory and add summaries and events to it. The class updates the + file contents asynchronously. This allows a training program to call methods + to add data to the file directly from the training loop, without slowing down + training. + + When constructed with a `tf.compat.v1.Session` parameter, a `FileWriter` + instead forms a compatibility layer over new graph-based summaries + to facilitate the use of new summary writing with + pre-existing code that expects a `FileWriter` instance. + + This class is not thread-safe. + + @compatibility(TF2) + This API is not compatible with eager execution or `tf.function`. To migrate + to TF2, please use `tf.summary.create_file_writer` instead for summary + management. To specify the summary step, you can manage the context with + `tf.summary.SummaryWriter`, which is returned by + `tf.summary.create_file_writer()`. Or, you can also use the `step` argument + of summary functions such as `tf.summary.histogram`. + See the usage example shown below. + + For a comprehensive `tf.summary` migration guide, please follow + [Migrating tf.summary usage to + TF 2.0](https://www.tensorflow.org/tensorboard/migrate#in_tf_1x). + + #### How to Map Arguments + + | TF1 Arg Name | TF2 Arg Name | Note | + | :---------------- | :---------------- | :-------------------------------- | + | `logdir` | `logdir` | - | + | `graph` | Not supported | - | + | `max_queue` | `max_queue` | - | + | `flush_secs` | `flush_millis` | The unit of time is changed | + : : : from seconds to milliseconds. : + | `graph_def` | Not supported | - | + | `filename_suffix` | `filename_suffix` | - | + | `name` | `name` | - | + + #### TF1 & TF2 Usage Example + + TF1: + + ```python + dist = tf.compat.v1.placeholder(tf.float32, [100]) + tf.compat.v1.summary.histogram(name="distribution", values=dist) + writer = tf.compat.v1.summary.FileWriter("/tmp/tf1_summary_example") + summaries = tf.compat.v1.summary.merge_all() + + sess = tf.compat.v1.Session() + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + summ = sess.run(summaries, feed_dict={dist: mean_moving_normal}) + writer.add_summary(summ, global_step=step) + ``` + + TF2: + + ```python + writer = tf.summary.create_file_writer("/tmp/tf2_summary_example") + for step in range(100): + mean_moving_normal = np.random.normal(loc=step, scale=1, size=[100]) + with writer.as_default(step=step): + tf.summary.histogram(name='distribution', data=mean_moving_normal) + ``` + + @end_compatibility + """ + + def __init__(self, + logdir, + graph=None, + max_queue=10, + flush_secs=120, + graph_def=None, + filename_suffix=None, + session=None): + """Creates a `FileWriter`, optionally shared within the given session. + + Typically, constructing a file writer creates a new event file in `logdir`. + This event file will contain `Event` protocol buffers constructed when you + call one of the following functions: `add_summary()`, `add_session_log()`, + `add_event()`, or `add_graph()`. + + If you pass a `Graph` to the constructor it is added to + the event file. (This is equivalent to calling `add_graph()` later). + + TensorBoard will pick the graph from the file and display it graphically so + you can interactively explore the graph you built. You will usually pass + the graph from the session in which you launched it: + + ```python + ...create a graph... + # Launch the graph in a session. + sess = tf.compat.v1.Session() + # Create a summary writer, add the 'graph' to the event file. + writer = tf.compat.v1.summary.FileWriter(, sess.graph) + ``` + + The `session` argument to the constructor makes the returned `FileWriter` a + compatibility layer over new graph-based summaries (`tf.summary`). + Crucially, this means the underlying writer resource and events file will + be shared with any other `FileWriter` using the same `session` and `logdir`. + In either case, ops will be added to `session.graph` to control the + underlying file writer resource. + + Args: + logdir: A string. Directory where event file will be written. + graph: A `Graph` object, such as `sess.graph`. + max_queue: Integer. Size of the queue for pending events and summaries. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. + graph_def: DEPRECATED: Use the `graph` argument instead. + filename_suffix: A string. Every event file's name is suffixed with + `suffix`. + session: A `tf.compat.v1.Session` object. See details above. + + Raises: + RuntimeError: If called with eager execution enabled. + + @compatibility(eager) + `v1.summary.FileWriter` is not compatible with eager execution. + To write TensorBoard summaries under eager execution, + use `tf.summary.create_file_writer` or + a `with v1.Graph().as_default():` context. + @end_compatibility + """ + if context.executing_eagerly(): + raise RuntimeError( + "v1.summary.FileWriter is not compatible with eager execution. " + "Use `tf.summary.create_file_writer`," + "or a `with v1.Graph().as_default():` context") + if session is not None: + event_writer = EventFileWriterV2( + session, logdir, max_queue, flush_secs, filename_suffix) + else: + event_writer = EventFileWriter(logdir, max_queue, flush_secs, + filename_suffix) + + self._closed = False + super(FileWriter, self).__init__(event_writer, graph, graph_def) + + def __enter__(self): + """Make usable with "with" statement.""" + return self + + def __exit__(self, unused_type, unused_value, unused_traceback): + """Make usable with "with" statement.""" + self.close() + + def get_logdir(self): + """Returns the directory where event file will be written.""" + return self.event_writer.get_logdir() + + def _warn_if_event_writer_is_closed(self): + if self._closed: + warnings.warn("Attempting to use a closed FileWriter. " + "The operation will be a noop unless the FileWriter " + "is explicitly reopened.") + + def _add_event(self, event, step): + self._warn_if_event_writer_is_closed() + super(FileWriter, self)._add_event(event, step) + + def add_event(self, event): + """Adds an event to the event file. + + Args: + event: An `Event` protocol buffer. + """ + self._warn_if_event_writer_is_closed() + self.event_writer.add_event(event) + + def flush(self): + """Flushes the event file to disk. + + Call this method to make sure that all pending events have been written to + disk. + """ + # Flushing a closed EventFileWriterV2 raises an exception. It is, + # however, a noop for EventFileWriter. + self._warn_if_event_writer_is_closed() + self.event_writer.flush() + + def close(self): + """Flushes the event file to disk and close the file. + + Call this method when you do not need the summary writer anymore. + """ + self.event_writer.close() + self._closed = True + + def reopen(self): + """Reopens the EventFileWriter. + + Can be called after `close()` to add more events in the same directory. + The events will go into a new events file. + + Does nothing if the EventFileWriter was not closed. + """ + self.event_writer.reopen() + self._closed = False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer_cache.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0724ca6e6cbbe2029fa05831ff8226ce06663b57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/summary/writer/writer_cache.py @@ -0,0 +1,60 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A cache for FileWriters.""" + +import threading + +from tensorflow.python.framework import ops +from tensorflow.python.summary.writer.writer import FileWriter +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=['summary.FileWriterCache']) +class FileWriterCache(object): + """Cache for file writers. + + This class caches file writers, one per directory. + """ + # Cache, keyed by directory. + _cache = {} + + # Lock protecting _FILE_WRITERS. + _lock = threading.RLock() + + @staticmethod + def clear(): + """Clear cached summary writers. Currently only used for unit tests.""" + with FileWriterCache._lock: + # Make sure all the writers are closed now (otherwise open file handles + # may hang around, blocking deletions on Windows). + for item in FileWriterCache._cache.values(): + item.close() + FileWriterCache._cache = {} + + @staticmethod + def get(logdir): + """Returns the FileWriter for the specified directory. + + Args: + logdir: str, name of the directory. + + Returns: + A `FileWriter`. + """ + with FileWriterCache._lock: + if logdir not in FileWriterCache._cache: + FileWriterCache._cache[logdir] = FileWriter( + logdir, graph=ops.get_default_graph()) + return FileWriterCache._cache[logdir] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/create_python_api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/create_python_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c856e8a6486e47f913b0d69bb9e2a6030c9ff5ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/create_python_api.py @@ -0,0 +1,856 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Generates and prints out imports and constants for new TensorFlow python api.""" +import argparse +import collections +import importlib +import os +import sys + +from tensorflow.python.tools.api.generator import doc_srcs +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_export + +API_ATTRS = tf_export.API_ATTRS +API_ATTRS_V1 = tf_export.API_ATTRS_V1 + +_LAZY_LOADING = False +_API_VERSIONS = [1, 2] +_COMPAT_MODULE_TEMPLATE = 'compat.v%d' +_SUBCOMPAT_MODULE_TEMPLATE = 'compat.v%d.compat.v%d' +_COMPAT_MODULE_PREFIX = 'compat.v' +_DEFAULT_PACKAGE = 'tensorflow.python' +_GENFILES_DIR_SUFFIX = 'genfiles/' +_SYMBOLS_TO_SKIP_EXPLICITLY = { + # Overrides __getattr__, so that unwrapping tf_decorator + # would have side effects. + 'tensorflow.python.platform.flags.FLAGS' +} +_GENERATED_FILE_HEADER = """# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. +\"\"\"%s +\"\"\" + +import sys as _sys + +""" +_GENERATED_FILE_FOOTER = '' +_DEPRECATION_FOOTER = """ +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "%s", public_apis=%s, deprecation=%s, + has_lite=%s) +""" +_LAZY_LOADING_MODULE_TEXT_TEMPLATE = """ +# Inform pytype that this module is dynamically populated (b/111239204). +_HAS_DYNAMIC_ATTRIBUTES = True +_PUBLIC_APIS = { +%s +} +""" + + +class SymbolExposedTwiceError(Exception): + """Raised when different symbols are exported with the same name.""" + pass + + +def get_canonical_import(import_set): + """Obtain one single import from a set of possible sources of a symbol. + + One symbol might come from multiple places as it is being imported and + reexported. To simplify API changes, we always use the same import for the + same module, and give preference based on higher priority and alphabetical + ordering. + + Args: + import_set: (set) Imports providing the same symbol. This is a set of tuples + in the form (import, priority). We want to pick an import with highest + priority. + + Returns: + A module name to import + """ + # We use the fact that list sorting is stable, so first we convert the set to + # a sorted list of the names and then we resort this list to move elements + # not in core tensorflow to the end. + # Here we sort by priority (higher preferred) and then alphabetically by + # import string. + import_list = sorted( + import_set, + key=lambda imp_and_priority: (-imp_and_priority[1], imp_and_priority[0])) + return import_list[0][0] + + +class _ModuleInitCodeBuilder(object): + """Builds a map from module name to imports included in that module.""" + + def __init__(self, + output_package, + api_version, + lazy_loading=_LAZY_LOADING, + use_relative_imports=False): + self._output_package = output_package + # Maps API module to API symbol name to set of tuples of the form + # (module name, priority). + # The same symbol can be imported from multiple locations. Higher + # "priority" indicates that import location is preferred over others. + self._module_imports = collections.defaultdict( + lambda: collections.defaultdict(set)) + self._dest_import_to_id = collections.defaultdict(int) + # Names that start with underscore in the root module. + self._underscore_names_in_root = set() + self._api_version = api_version + # Controls whether or not exported symbols are lazily loaded or statically + # imported. + self._lazy_loading = lazy_loading + self._use_relative_imports = use_relative_imports + + def _check_already_imported(self, symbol_id, api_name): + if (api_name in self._dest_import_to_id and + symbol_id != self._dest_import_to_id[api_name] and symbol_id != -1): + raise SymbolExposedTwiceError( + f'Trying to export multiple symbols with same name: {api_name}') + self._dest_import_to_id[api_name] = symbol_id + + def add_import(self, symbol, source_module_name, source_name, + dest_module_name, dest_name): + """Adds this import to module_imports. + + Args: + symbol: TensorFlow Python symbol. + source_module_name: (string) Module to import from. + source_name: (string) Name of the symbol to import. + dest_module_name: (string) Module name to add import to. + dest_name: (string) Import the symbol using this name. + + Raises: + SymbolExposedTwiceError: Raised when an import with the same + dest_name has already been added to dest_module_name. + """ + # modules_with_exports.py is only used during API generation and + # won't be available when actually importing tensorflow. + if source_module_name.endswith('python.modules_with_exports'): + source_module_name = symbol.__module__ + import_str = self.format_import(source_module_name, source_name, dest_name) + + # Check if we are trying to expose two different symbols with same name. + full_api_name = dest_name + if dest_module_name: + full_api_name = dest_module_name + '.' + full_api_name + symbol_id = -1 if not symbol else id(symbol) + self._check_already_imported(symbol_id, full_api_name) + + if not dest_module_name and dest_name.startswith('_'): + self._underscore_names_in_root.add(dest_name) + + # The same symbol can be available in multiple modules. + # We store all possible ways of importing this symbol and later pick just + # one. + priority = 0 + if symbol: + # Give higher priority to source module if it matches + # symbol's original module. + if hasattr(symbol, '__module__'): + priority = int(source_module_name == symbol.__module__) + # Give higher priority if symbol name matches its __name__. + if hasattr(symbol, '__name__'): + priority += int(source_name == symbol.__name__) + self._module_imports[dest_module_name][full_api_name].add( + (import_str, priority)) + + def _import_submodules(self): + """Add imports for all destination modules in self._module_imports.""" + # Import all required modules in their parent modules. + # For e.g. if we import 'foo.bar.Value'. Then, we also + # import 'bar' in 'foo'. + imported_modules = set(self._module_imports.keys()) + for module in imported_modules: + if not module: + continue + module_split = module.split('.') + parent_module = '' # we import submodules in their parent_module + + for submodule_index in range(len(module_split)): + if submodule_index > 0: + submodule = module_split[submodule_index - 1] + parent_module += '.' + submodule if parent_module else submodule + import_from = self._output_package + if self._lazy_loading: + import_from += '.' + '.'.join(module_split[:submodule_index + 1]) + self.add_import( + symbol=None, + source_module_name='', + source_name=import_from, + dest_module_name=parent_module, + dest_name=module_split[submodule_index]) + else: + if self._use_relative_imports: + import_from = '.' + elif submodule_index > 0: + import_from += '.' + '.'.join(module_split[:submodule_index]) + self.add_import( + symbol=None, + source_module_name=import_from, + source_name=module_split[submodule_index], + dest_module_name=parent_module, + dest_name=module_split[submodule_index]) + + def build(self): + """Get a map from destination module to __init__.py code for that module. + + Returns: + A dictionary where + key: (string) destination module (for e.g. tf or tf.consts). + value: (string) text that should be in __init__.py files for + corresponding modules. + """ + self._import_submodules() + module_text_map = {} + footer_text_map = {} + for dest_module, dest_name_to_imports in self._module_imports.items(): + # Sort all possible imports for a symbol and pick the first one. + imports_list = [ + get_canonical_import(imports) + for _, imports in dest_name_to_imports.items() + ] + if self._lazy_loading: + module_text_map[ + dest_module] = _LAZY_LOADING_MODULE_TEXT_TEMPLATE % '\n'.join( + sorted(imports_list)) + else: + module_text_map[dest_module] = '\n'.join(sorted(imports_list)) + + # Expose exported symbols with underscores in root module since we import + # from it using * import. Don't need this for lazy_loading because the + # underscore symbols are already included in __all__ when passed in and + # handled by TFModuleWrapper. + root_module_footer = '' + if not self._lazy_loading: + underscore_names_str = ', '.join( + '\'%s\'' % name for name in sorted(self._underscore_names_in_root)) + + root_module_footer = """ +_names_with_underscore = [%s] +__all__ = [_s for _s in dir() if not _s.startswith('_')] +__all__.extend([_s for _s in _names_with_underscore]) +""" % underscore_names_str + + # Add module wrapper if we need to print deprecation messages + # or if we use lazy loading. + if self._api_version == 1 or self._lazy_loading: + for dest_module, _ in self._module_imports.items(): + deprecation = 'False' + has_lite = 'False' + if self._api_version == 1: # Add 1.* deprecations. + if not dest_module.startswith(_COMPAT_MODULE_PREFIX): + deprecation = 'True' + # Workaround to make sure not load lite from lite/__init__.py + if (not dest_module and 'lite' in self._module_imports and + self._lazy_loading): + has_lite = 'True' + if self._lazy_loading: + public_apis_name = '_PUBLIC_APIS' + else: + public_apis_name = 'None' + footer_text_map[dest_module] = _DEPRECATION_FOOTER % ( + dest_module, public_apis_name, deprecation, has_lite) + + return module_text_map, footer_text_map, root_module_footer + + def format_import(self, source_module_name, source_name, dest_name): + """Formats import statement. + + Args: + source_module_name: (string) Source module to import from. + source_name: (string) Source symbol name to import. + dest_name: (string) Destination alias name. + + Returns: + An import statement string. + """ + if self._lazy_loading: + return " '%s': ('%s', '%s')," % (dest_name, source_module_name, + source_name) + else: + if source_module_name: + if source_name == dest_name: + return 'from %s import %s' % (source_module_name, source_name) + else: + return 'from %s import %s as %s' % (source_module_name, source_name, + dest_name) + else: + if source_name == dest_name: + return 'import %s' % source_name + else: + return 'import %s as %s' % (source_name, dest_name) + + def get_destination_modules(self): + return set(self._module_imports.keys()) + + def copy_imports(self, from_dest_module, to_dest_module): + self._module_imports[to_dest_module] = ( + self._module_imports[from_dest_module].copy()) + + +def add_nested_compat_imports(module_builder, compat_api_versions, + output_package): + """Adds compat.vN.compat.vK modules to module builder. + + To avoid circular imports, we want to add __init__.py files under + compat.vN.compat.vK and under compat.vN.compat.vK.compat. For all other + imports, we point to corresponding modules under compat.vK. + + Args: + module_builder: `_ModuleInitCodeBuilder` instance. + compat_api_versions: Supported compatibility versions. + output_package: Base output python package where generated API will be + added. + """ + imported_modules = module_builder.get_destination_modules() + + # Copy over all imports in compat.vK to compat.vN.compat.vK and + # all imports in compat.vK.compat to compat.vN.compat.vK.compat. + for v in compat_api_versions: + for sv in compat_api_versions: + subcompat_module = _SUBCOMPAT_MODULE_TEMPLATE % (v, sv) + compat_module = _COMPAT_MODULE_TEMPLATE % sv + module_builder.copy_imports(compat_module, subcompat_module) + module_builder.copy_imports('%s.compat' % compat_module, + '%s.compat' % subcompat_module) + + # Prefixes of modules under compatibility packages, for e.g. "compat.v1.". + compat_prefixes = tuple( + _COMPAT_MODULE_TEMPLATE % v + '.' for v in compat_api_versions) + + # Above, we only copied function, class and constant imports. Here + # we also add imports for child modules. + for imported_module in imported_modules: + if not imported_module.startswith(compat_prefixes): + continue + module_split = imported_module.split('.') + + # Handle compat.vN.compat.vK.compat.foo case. That is, + # import compat.vK.compat.foo in compat.vN.compat.vK.compat. + if len(module_split) > 3 and module_split[2] == 'compat': + src_module = '.'.join(module_split[:3]) + src_name = module_split[3] + assert src_name != 'v1' and src_name != 'v2', imported_module + else: # Handle compat.vN.compat.vK.foo case. + src_module = '.'.join(module_split[:2]) + src_name = module_split[2] + if src_name == 'compat': + continue # compat.vN.compat.vK.compat is handled separately + + for compat_api_version in compat_api_versions: + module_builder.add_import( + symbol=None, + source_module_name='%s.%s' % (output_package, src_module), + source_name=src_name, + dest_module_name='compat.v%d.%s' % (compat_api_version, src_module), + dest_name=src_name) + + +def _get_name_and_module(full_name): + """Split full_name into module and short name. + + Args: + full_name: Full name of symbol that includes module. + + Returns: + Full module name and short symbol name. + """ + name_segments = full_name.split('.') + return '.'.join(name_segments[:-1]), name_segments[-1] + + +def _join_modules(module1, module2): + """Concatenate 2 module components. + + Args: + module1: First module to join. + module2: Second module to join. + + Returns: + Given two modules aaa.bbb and ccc.ddd, returns a joined + module aaa.bbb.ccc.ddd. + """ + if not module1: + return module2 + if not module2: + return module1 + return '%s.%s' % (module1, module2) + + +def add_imports_for_symbol(module_code_builder, + symbol, + source_module_name, + source_name, + api_name, + api_version, + output_module_prefix=''): + """Add imports for the given symbol to `module_code_builder`. + + Args: + module_code_builder: `_ModuleInitCodeBuilder` instance. + symbol: A symbol. + source_module_name: Module that we can import the symbol from. + source_name: Name we can import the symbol with. + api_name: API name. Currently, must be either `tensorflow` or `estimator`. + api_version: API version. + output_module_prefix: Prefix to prepend to destination module. + """ + if api_version == 1: + names_attr = API_ATTRS_V1[api_name].names + constants_attr = API_ATTRS_V1[api_name].constants + else: + names_attr = API_ATTRS[api_name].names + constants_attr = API_ATTRS[api_name].constants + + # If symbol is _tf_api_constants attribute, then add the constants. + if source_name == constants_attr: + for exports, name in symbol: + for export in exports: + dest_module, dest_name = _get_name_and_module(export) + dest_module = _join_modules(output_module_prefix, dest_module) + module_code_builder.add_import(None, source_module_name, name, + dest_module, dest_name) + + # If symbol has _tf_api_names attribute, then add import for it. + if (hasattr(symbol, '__dict__') and names_attr in symbol.__dict__): + + # Generate import statements for symbols. + for export in getattr(symbol, names_attr): # pylint: disable=protected-access + dest_module, dest_name = _get_name_and_module(export) + dest_module = _join_modules(output_module_prefix, dest_module) + module_code_builder.add_import(symbol, source_module_name, source_name, + dest_module, dest_name) + + +def get_api_init_text(packages, + packages_to_ignore, + output_package, + api_name, + api_version, + compat_api_versions=None, + lazy_loading=_LAZY_LOADING, + use_relative_imports=False): + """Get a map from destination module to __init__.py code for that module. + + Args: + packages: Base python packages containing python with target tf_export + decorators. + packages_to_ignore: python packages to be ignored when checking for + tf_export decorators. + output_package: Base output python package where generated API will be + added. + api_name: API you want to generate (e.g. `tensorflow` or `estimator`). + api_version: API version you want to generate (1 or 2). + compat_api_versions: Additional API versions to generate under compat/ + directory. + lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is + produced and if `False`, static imports are used. + use_relative_imports: True if we should use relative imports when importing + submodules. + + Returns: + A dictionary where + key: (string) destination module (for e.g. tf or tf.consts). + value: (string) text that should be in __init__.py files for + corresponding modules. + """ + if compat_api_versions is None: + compat_api_versions = [] + module_code_builder = _ModuleInitCodeBuilder(output_package, api_version, + lazy_loading, + use_relative_imports) + + # Traverse over everything imported above. Specifically, + # we want to traverse over TensorFlow Python modules. + + def in_packages(m): + return any(package in m for package in packages) + + for module in list(sys.modules.values()): + # Only look at tensorflow modules. + if (not module or not hasattr(module, '__name__') or + module.__name__ is None or not in_packages(module.__name__)): + continue + if packages_to_ignore and any([p for p in packages_to_ignore + if p in module.__name__]): + continue + + # Do not generate __init__.py files for contrib modules for now. + if (('.contrib.' in module.__name__ or module.__name__.endswith('.contrib')) + and '.lite' not in module.__name__): + continue + + for module_contents_name in dir(module): + if (module.__name__ + '.' + + module_contents_name in _SYMBOLS_TO_SKIP_EXPLICITLY): + continue + attr = getattr(module, module_contents_name) + _, attr = tf_decorator.unwrap(attr) + + add_imports_for_symbol(module_code_builder, attr, module.__name__, + module_contents_name, api_name, api_version) + for compat_api_version in compat_api_versions: + add_imports_for_symbol(module_code_builder, attr, module.__name__, + module_contents_name, api_name, + compat_api_version, + _COMPAT_MODULE_TEMPLATE % compat_api_version) + + if compat_api_versions: + add_nested_compat_imports(module_code_builder, compat_api_versions, + output_package) + return module_code_builder.build() + + +def get_module(dir_path, relative_to_dir): + """Get module that corresponds to path relative to relative_to_dir. + + Args: + dir_path: Path to directory. + relative_to_dir: Get module relative to this directory. + + Returns: + Name of module that corresponds to the given directory. + """ + dir_path = dir_path[len(relative_to_dir):] + # Convert path separators to '/' for easier parsing below. + dir_path = dir_path.replace(os.sep, '/') + return dir_path.replace('/', '.').strip('.') + + +def get_module_docstring(module_name, package, api_name): + """Get docstring for the given module. + + This method looks for docstring in the following order: + 1. Checks if module has a docstring specified in doc_srcs. + 2. Checks if module has a docstring source module specified + in doc_srcs. If it does, gets docstring from that module. + 3. Checks if module with module_name exists under base package. + If it does, gets docstring from that module. + 4. Returns a default docstring. + + Args: + module_name: module name relative to tensorflow (excluding 'tensorflow.' + prefix) to get a docstring for. + package: Base python package containing python with target tf_export + decorators. + api_name: API you want to generate (e.g. `tensorflow` or `estimator`). + + Returns: + One-line docstring to describe the module. + """ + # Get the same module doc strings for any version. That is, for module + # 'compat.v1.foo' we can get docstring from module 'foo'. + for version in _API_VERSIONS: + compat_prefix = _COMPAT_MODULE_TEMPLATE % version + if module_name.startswith(compat_prefix): + module_name = module_name[len(compat_prefix):].strip('.') + + # Module under base package to get a docstring from. + docstring_module_name = module_name + + doc_sources = doc_srcs.get_doc_sources(api_name) + + if module_name in doc_sources: + docsrc = doc_sources[module_name] + if docsrc.docstring: + return docsrc.docstring + if docsrc.docstring_module_name: + docstring_module_name = docsrc.docstring_module_name + + if package != 'tf_keras': + docstring_module_name = package + '.' + docstring_module_name + if (docstring_module_name in sys.modules and + sys.modules[docstring_module_name].__doc__): + return sys.modules[docstring_module_name].__doc__ + + return 'Public API for tf.%s namespace.' % module_name + + +def create_primary_api_files(output_files, + packages, + packages_to_ignore, + root_init_template, + output_dir, + output_package, + api_name, + api_version, + compat_api_versions, + compat_init_templates, + lazy_loading=_LAZY_LOADING, + use_relative_imports=False): + """Creates __init__.py files for the Python API. + + Args: + output_files: List of __init__.py file paths to create. + packages: Base python packages containing python with target tf_export + decorators. + packages_to_ignore: python packages to be ignored when checking for + tf_export decorators. + root_init_template: Template for top-level __init__.py file. "# API IMPORTS + PLACEHOLDER" comment in the template file will be replaced with imports. + output_dir: output API root directory. + output_package: Base output package where generated API will be added. + api_name: API you want to generate (e.g. `tensorflow` or `estimator`). + api_version: API version to generate (`v1` or `v2`). + compat_api_versions: Additional API versions to generate in compat/ + subdirectory. + compat_init_templates: List of templates for top level compat init files in + the same order as compat_api_versions. + lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is + produced and if `False`, static imports are used. + use_relative_imports: True if we should use relative imports when import + submodules. + + Raises: + ValueError: if output_files list is missing a required file. + """ + module_name_to_file_path = {} + for output_file in output_files: + module_name = get_module(os.path.dirname(output_file), output_dir) + module_name_to_file_path[module_name] = os.path.normpath(output_file) + + # Create file for each expected output in genrule. + for module, file_path in module_name_to_file_path.items(): + if not os.path.isdir(os.path.dirname(file_path)): + os.makedirs(os.path.dirname(file_path)) + open(file_path, 'a').close() + + ( + module_text_map, + deprecation_footer_map, + root_module_footer, + ) = get_api_init_text(packages, packages_to_ignore, output_package, api_name, + api_version, compat_api_versions, lazy_loading, + use_relative_imports) + + # Add imports to output files. + missing_output_files = [] + # Root modules are "" and "compat.v*". + root_module = '' + compat_module_to_template = { + _COMPAT_MODULE_TEMPLATE % v: t + for v, t in zip(compat_api_versions, compat_init_templates) + } + for v in compat_api_versions: + compat_module_to_template.update({ + _SUBCOMPAT_MODULE_TEMPLATE % (v, vs): t + for vs, t in zip(compat_api_versions, compat_init_templates) + }) + + for module, text in module_text_map.items(): + # Make sure genrule output file list is in sync with API exports. + if module not in module_name_to_file_path: + module_file_path = '"%s/__init__.py"' % (module.replace('.', '/')) + missing_output_files.append(module_file_path) + continue + + contents = '' + if module == root_module and root_init_template: + # Read base init file for root module + with open(root_init_template, 'r') as root_init_template_file: + contents = root_init_template_file.read() + contents = contents.replace('# API IMPORTS PLACEHOLDER', text) + contents = contents.replace('# __all__ PLACEHOLDER', root_module_footer) + elif module in compat_module_to_template: + # Read base init file for compat module + with open(compat_module_to_template[module], 'r') as init_template_file: + contents = init_template_file.read() + contents = contents.replace('# API IMPORTS PLACEHOLDER', text) + else: + contents = ( + _GENERATED_FILE_HEADER % + get_module_docstring(module, packages[0], api_name) + text + + _GENERATED_FILE_FOOTER) + if module in deprecation_footer_map: + if '# WRAPPER_PLACEHOLDER' in contents: + contents = contents.replace('# WRAPPER_PLACEHOLDER', + deprecation_footer_map[module]) + else: + contents += deprecation_footer_map[module] + with open(module_name_to_file_path[module], 'w') as fp: + fp.write(contents) + + if missing_output_files: + missing_files = ',\n'.join(sorted(missing_output_files)) + raise ValueError( + f'Missing outputs for genrule:\n{missing_files}. Be sure to add these ' + 'targets to tensorflow/python/tools/api/generator/api_init_files_v1.bzl' + ' and tensorflow/python/tools/api/generator/api_init_files.bzl ' + '(tensorflow repo), tf_keras/api/api_init_files.bzl (tf_keras repo), ' + 'or tensorflow_estimator/python/estimator/api/api_gen.bzl (estimator ' + 'repo)') + + +def create_proxy_api_files(output_files, + proxy_module_root, + output_dir): + """Creates __init__.py files in proxy format for the Python API. + + Args: + output_files: List of __init__.py file paths to create. + proxy_module_root: Module root for proxy-import format. If specified, proxy + files with content like `from proxy_module_root.proxy_module import *` + will be created to enable import resolution under TensorFlow. + output_dir: output API root directory. + """ + for file_path in output_files: + module = get_module(os.path.dirname(file_path), output_dir) + if not os.path.isdir(os.path.dirname(file_path)): + os.makedirs(os.path.dirname(file_path)) + contents = f'from {proxy_module_root}.{module} import *' + with open(file_path, 'w') as fp: + fp.write(contents) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + 'outputs', + metavar='O', + type=str, + nargs='+', + help='If a single file is passed in, then we assume it contains a ' + 'semicolon-separated list of Python files that we expect this script to ' + 'output. If multiple files are passed in, then we assume output files ' + 'are listed directly as arguments.') + parser.add_argument( + '--packages', + default=_DEFAULT_PACKAGE, + type=str, + help='Base packages that import modules containing the target tf_export ' + 'decorators.') + parser.add_argument( + '--packages_to_ignore', + default='', + type=str, + help='Packages to exclude from the api generation. This is used to hide ' + 'certain packages from this script when multiple copy of code exists, ' + 'eg tf_keras. It is useful to avoid the SymbolExposedTwiceError.' + ) + parser.add_argument( + '--root_init_template', + default='', + type=str, + help='Template for top level __init__.py file. ' + '"#API IMPORTS PLACEHOLDER" comment will be replaced with imports.') + parser.add_argument( + '--apidir', + type=str, + required=True, + help='Directory where generated output files are placed. ' + 'gendir should be a prefix of apidir. Also, apidir ' + 'should be a prefix of every directory in outputs.') + parser.add_argument( + '--apiname', + required=True, + type=str, + choices=API_ATTRS.keys(), + help='The API you want to generate.') + parser.add_argument( + '--apiversion', + default=2, + type=int, + choices=_API_VERSIONS, + help='The API version you want to generate.') + parser.add_argument( + '--compat_apiversions', + default=[], + type=int, + action='append', + help='Additional versions to generate in compat/ subdirectory. ' + 'If set to 0, then no additional version would be generated.') + parser.add_argument( + '--compat_init_templates', + default=[], + type=str, + action='append', + help='Templates for top-level __init__ files under compat modules. ' + 'The list of init file templates must be in the same order as ' + 'list of versions passed with compat_apiversions.') + parser.add_argument( + '--output_package', + default='tensorflow', + type=str, + help='Root output package.') + parser.add_argument( + '--loading', + default='default', + type=str, + choices=['lazy', 'static', 'default'], + help='Controls how the generated __init__.py file loads the exported ' + 'symbols. \'lazy\' means the symbols are loaded when first used. ' + '\'static\' means all exported symbols are loaded in the ' + '__init__.py file. \'default\' uses the value of the ' + '_LAZY_LOADING constant in create_python_api.py.') + parser.add_argument( + '--use_relative_imports', + default=False, + type=bool, + help='Whether to import submodules using relative imports or absolute ' + 'imports') + parser.add_argument( + '--proxy_module_root', + default=None, + type=str, + help='Module root for proxy-import format. If specified, proxy files with ' + 'content like `from proxy_module_root.proxy_module import *` will be ' + 'created to enable import resolution under TensorFlow.') + args = parser.parse_args() + + if len(args.outputs) == 1: + # If we only get a single argument, then it must be a file containing + # list of outputs. + with open(args.outputs[0]) as output_list_file: + outputs = [line.strip() for line in output_list_file.read().split(';')] + else: + outputs = args.outputs + + # Populate `sys.modules` with modules containing tf_export(). + packages = args.packages.split(',') + for package in packages: + importlib.import_module(package) + packages_to_ignore = args.packages_to_ignore.split(',') + + # Determine if the modules shall be loaded lazily or statically. + if args.loading == 'default': + lazy_loading = _LAZY_LOADING + elif args.loading == 'lazy': + lazy_loading = True + elif args.loading == 'static': + lazy_loading = False + else: + # This should never happen (tm). + raise ValueError(f'Invalid value for --loading flag: {args.loading}. Must ' + 'be one of lazy, static, default.') + if args.proxy_module_root is None: + create_primary_api_files(outputs, packages, packages_to_ignore, + args.root_init_template, args.apidir, + args.output_package, args.apiname, args.apiversion, + args.compat_apiversions, + args.compat_init_templates, lazy_loading, + args.use_relative_imports) + else: + create_proxy_api_files(outputs, args.proxy_module_root, args.apidir) + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/doc_srcs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/doc_srcs.py new file mode 100644 index 0000000000000000000000000000000000000000..56ab8a1b221fdd6fa05a20d25a368dea18d4d0f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator/doc_srcs.py @@ -0,0 +1,146 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Specifies sources of doc strings for API modules.""" +from tensorflow.python.util import tf_export + + +class DocSource(object): + """Specifies docstring source for a module. + + Only one of docstring or docstring_module_name should be set. + * If docstring is set, then we will use this docstring when + for the module. + * If docstring_module_name is set, then we will copy the docstring + from docstring source module. + """ + + def __init__(self, docstring=None, docstring_module_name=None): + self.docstring = docstring + self.docstring_module_name = docstring_module_name + + if self.docstring is not None and self.docstring_module_name is not None: + raise ValueError('Only one of `docstring` or `docstring_module_name` can ' + 'be set.') + + +_TENSORFLOW_DOC_SOURCES = { + 'app': + DocSource(docstring='Import router for absl.app.'), + 'bitwise': + DocSource(docstring_module_name='ops.bitwise_ops'), + 'compat': + DocSource(docstring_module_name='util.compat'), + 'distribute': + DocSource(docstring_module_name='distribute'), + 'distributions': DocSource( + docstring='Core module for TensorFlow distribution objects and helpers.' + ), + 'errors': + DocSource(docstring_module_name='framework.errors'), + 'experimental.numpy': + DocSource(docstring_module_name='ops.numpy_ops'), + 'gfile': + DocSource(docstring='Import router for file_io.'), + 'graph_util': + DocSource(docstring_module_name='framework.graph_util'), + 'image': + DocSource(docstring_module_name='ops.image_ops'), + 'linalg': + DocSource(docstring_module_name='ops.linalg_ops'), + 'logging': + DocSource(docstring_module_name='ops.logging_ops'), + 'losses': DocSource( + docstring=( + 'Loss operations for use in neural networks. Note: All the losses' + ' are added to the `GraphKeys.LOSSES` collection by default.' + ) + ), + 'manip': + DocSource(docstring_module_name='ops.manip_ops'), + 'math': + DocSource(docstring_module_name='ops.math_ops'), + 'metrics': + DocSource(docstring='Evaluation-related metrics.'), + 'nest': + DocSource(docstring_module_name='util.nest'), + 'nn': + DocSource(docstring_module_name='ops.nn_ops'), + 'nn.rnn_cell': + DocSource(docstring='Module for constructing RNN Cells.'), + 'python_io': + DocSource(docstring_module_name='lib.io.python_io'), + 'ragged': + DocSource(docstring_module_name='ops.ragged'), + 'resource_loader': + DocSource(docstring='Resource management library.'), + 'sets': + DocSource(docstring_module_name='ops.sets'), + 'signal': + DocSource(docstring_module_name='ops.signal'), + 'sparse': + DocSource(docstring_module_name='ops.sparse_ops'), + 'strings': + DocSource(docstring_module_name='ops.string_ops'), + 'summary': DocSource( + docstring=( + 'Operations for writing summary data, for use in analysis and' + ' visualization. See the [Summaries and' + ' TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard)' + ' guide.' + ) + ), + 'sysconfig': + DocSource(docstring='System configuration library.'), + 'test': + DocSource(docstring='Testing.'), + 'train': DocSource( + docstring=( + 'Support for training models. See the' + ' [Training](https://tensorflow.org/api_guides/python/train) guide.' + ) + ), +} + +_ESTIMATOR_DOC_SOURCES = { + 'estimator': DocSource( + docstring_module_name='estimator_lib'), + 'estimator.export': DocSource( + docstring_module_name='export.export_lib'), + 'estimator.inputs': DocSource( + docstring_module_name='inputs.inputs'), +} + +_KERAS_DOC_SOURCES = { + 'keras.optimizers.experimental': + DocSource(docstring_module_name='optimizers.optimizer_experimental') +} + + +def get_doc_sources(api_name): + """Get a map from module to a DocSource object. + + Args: + api_name: API you want to generate (e.g. `tensorflow` or `estimator`). + + Returns: + Map from module name to DocSource object. + """ + if api_name == tf_export.TENSORFLOW_API_NAME: + return _TENSORFLOW_DOC_SOURCES + if api_name == tf_export.ESTIMATOR_API_NAME: + return _ESTIMATOR_DOC_SOURCES + if api_name == tf_export.KERAS_API_NAME: + return _KERAS_DOC_SOURCES + return {} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/extractor/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/extractor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/extractor/extractor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/extractor/extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..ccdd13099d13c48c9bcd954af151aec1d12285ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/extractor/extractor.py @@ -0,0 +1,363 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Extracts API information for a set of Python sources.""" + +import ast +from collections.abc import Sequence +import re +from typing import Any, Optional, Union, cast + +from absl import flags +from absl import logging + +from tensorflow.python.tools.api.generator2.shared import exported_api + +_OUTPUT = flags.DEFINE_string('output', '', 'File to output contents to.') +_DECORATOR = flags.DEFINE_string( + 'decorator', + '', + 'Full path to Python decorator function used for exporting API.', +) +_API_NAME = flags.DEFINE_string( + 'api_name', + '', + 'Prefix for all exported symbols and docstrings.', +) + +_DOCSTRING_PATTERN: re.Pattern[str] = re.compile( + r'\s*API\s+docstring:\s*([\w.]+)\s*' +) + + +class BadExportError(Exception): + """Exception for bad exports.""" + + +class Parser(ast.NodeVisitor): + """Parser for Python source files that extracts TF API exports.""" + + _exports: exported_api.ExportedApi + _decorator_package: str + _decorator_symbol: str + _api_name: str + _current_file: Optional[str] = None + _current_file_decorators: set[str] + + def __init__( + self, + exports: exported_api.ExportedApi, + decorator: str, + api_name: str, + ): + self._exports = exports + self._decorator_package, self._decorator_symbol = decorator.rsplit('.', 1) + self._api_name = api_name + + def process_file(self, filename: str) -> None: + """Finds exported APIs in filename.""" + try: + with open(filename, mode='r', encoding='utf-8') as f: + contents = f.read() + except Exception as e: # pylint: disable=broad-exception-caught + # log and ignore exceptions from read + logging.exception('Error reading %s: %s', filename, e) + else: + self.process(filename, contents) + + def process(self, filename: str, contents: str) -> None: + """Finds exported APIs in contents.""" + self._current_file_decorators = set() + self._current_file = filename + try: + parsed = ast.parse(contents, filename=filename) + except Exception as e: # pylint: disable=broad-exception-caught + # logging errors when parsing file + logging.exception('Error parsing %s: %s', filename, e) + else: + self.visit(parsed) + finally: + self._current_file = None + self._current_file_decorators = set() + + def visit_Module(self, node: ast.Module) -> None: # pylint: disable=invalid-name + for stmt in node.body: + self._process_stmt(stmt) + + def _process_stmt(self, node: ast.stmt) -> None: + """Process top-level statement for exported apis.""" + if isinstance(node, (ast.ClassDef, ast.FunctionDef)): + self._process_def(node) + elif isinstance(node, ast.Assign): + self._process_assign(node) + elif isinstance(node, ast.Expr): + self._process_expr(node) + else: + self.visit(node) + + def visit_Import(self, node: ast.Import) -> None: # pylint: disable=invalid-name + """Identifies imports of decorator.""" + for name in node.names: + if name.name == self._decorator_package: + if name.asname: + # import as + self._current_file_decorators.add( + name.asname + '.' + self._decorator_symbol + ) + else: + # import + _, module = self._decorator_package.rsplit('.', 1) + self._current_file_decorators.add( + module + '.' + self._decorator_symbol + ) + self.generic_visit(node) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: # pylint: disable=invalid-name + """Identifies imports of decorator.""" + if node.module == self._decorator_package: + for name in node.names: + if name.name == self._decorator_symbol: + if name.asname: + # from import as + self._current_file_decorators.add(name.asname) + else: + # from import + self._current_file_decorators.add(name.name) + else: + parent, module = self._decorator_package.rsplit('.', 1) + if node.module == parent: + for name in node.names: + if name.name == module: + if name.asname: + # from import as + self._current_file_decorators.add( + name.asname + '.' + self._decorator_symbol + ) + else: + # from import + self._current_file_decorators.add( + name.name + '.' + self._decorator_symbol + ) + self.generic_visit(node) + + def _process_def(self, node: Union[ast.ClassDef, ast.FunctionDef]) -> None: + """Process top-level [Class|Function]Def for potential symbol export.""" + # @tf_export(...) + # [class|def] : + for decorator in node.decorator_list: + if self._is_export_call(decorator): + self._add_exported_symbol(cast(ast.Call, decorator), node.name) + else: + self.visit(decorator) + + if isinstance(node, ast.ClassDef): + for base in node.bases: + self.visit(base) + for kw in node.keywords: + self.visit(kw) + elif isinstance(node, ast.FunctionDef): + self.visit(node.args) + if node.returns: + self.visit(node.returns) + + for stmt in node.body: + self.visit(stmt) + + def _process_assign(self, node: ast.Assign) -> None: + """Process top-level assign for potential symbol export.""" + if isinstance(node.value, ast.Call) and self._is_export_call( + node.value.func + ): + # id = tf_export(...)(...) + if len(node.targets) != 1: + raise BadExportError( + f'{self._current_file}:{node.lineno} export must be' + f' assigned to a single value: {ast.dump(node)}' + ) + symbol = self._name(node.targets[0]) + if not symbol: + raise BadExportError( + f'{self._current_file}:{node.lineno} export must be' + f' assigned to a single value: {ast.dump(node)}' + ) + self._add_exported_symbol(node.value.func, symbol) + else: + self.visit(node) + + def _process_expr(self, node: ast.Expr) -> None: + """Process top-level expression for potential symbol export.""" + if isinstance(node.value, ast.Call): + self._process_call(node.value) + elif isinstance(node.value, ast.Constant): + self._process_constant(node.value) + else: + self.visit(node) + + def _process_call(self, node: ast.Call) -> None: + """Process top-level call for potential symbol export.""" + func = node.func + if self._is_export_call(func): + func = cast(ast.Call, func) + # tf_export(...)(id) + if len(node.args) != 1 or node.keywords: + raise BadExportError( + f'{self._current_file}:{node.lineno} export must be' + f' called with a single value: {ast.dump(node)}' + ) + symbol = self._name(self._unwrap_simple_call(node.args[0])) + if not symbol: + raise BadExportError( + f'{self._current_file}:{node.lineno} export must be' + f' called with a single value: {ast.dump(node)}' + ) + self._add_exported_symbol(func, symbol) + elif ( + isinstance(func, ast.Attribute) + and func.attr == 'export_constant' + and self._is_export_call(func.value) + ): + # tf_export(...).export_constant(__name__, id) + if ( + len(node.args) != 2 + or node.keywords + or self._name(node.args[0]) != '__name__' + ): + raise BadExportError( + f'{self._current_file}:{node.lineno} export_constant must be' + f' called with __name__, : {ast.dump(node)}' + ) + self._add_exported_symbol(func.value, self._literal_value(node.args[1])) + else: + self.visit(node) + + def _process_constant(self, node: ast.Constant) -> None: + """Process top-level constant for a potential API docstring export.""" + if isinstance(node.value, str): + docstring, modules = self._extract_docstring(node.value) + if modules: + self._exports.add_doc( + exported_api.ExportedDoc.create( + file_name=self._current_file, + line_no=node.lineno, + modules=modules, + docstring=docstring, + ) + ) + else: + self.visit(node) + + def _extract_docstring(self, value: str) -> tuple[str, Sequence[str]]: + """Extract docstring and list of modules that it should be applied to.""" + docstring = '' + modules = [] + for line in value.splitlines(): + match = _DOCSTRING_PATTERN.match(line) + if match: + module = match.group(1).strip() + # API docstring: + if module == self._api_name or module.startswith(self._api_name + '.'): + modules.append(module) + else: + docstring += line + '\n' + return (docstring.strip(), modules) + + def visit_Call(self, node: ast.Call) -> None: # pylint: disable=invalid-name + if self._is_export_call(node): + raise BadExportError( + f'{self._current_file}:{node.lineno} export must be' + f' used at top level of file: {ast.dump(node)}' + ) + self.generic_visit(node) + + def visit_Constant(self, node: ast.Constant) -> None: + if isinstance(node.value, str): + _, modules = self._extract_docstring(node.value) + if modules: + raise BadExportError( + f'{self._current_file}:{node.lineno} API docstrings must be' + f' at top level of file: {ast.dump(node)}' + ) + self.generic_visit(node) + + def _is_export_call(self, node: ast.expr) -> bool: # TypeGuard[ast.Call] + return ( + isinstance(node, ast.Call) + and self._name(node.func) in self._current_file_decorators + ) + + def _name(self, node: ast.expr) -> Optional[str]: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + parent = self._name(node.value) + if parent: + return f'{parent}.{node.attr}' + + def _unwrap_simple_call(self, node: ast.expr) -> ast.expr: + """Unwraps a function call that takes a single unnamed parameter.""" + if isinstance(node, ast.Call) and len(node.args) == 1 and not node.keywords: + return self._unwrap_simple_call(node.args[0]) + return node + + def _literal_value(self, node: ast.expr) -> Any: + try: + return ast.literal_eval(node) + except Exception as e: + raise BadExportError( + f'{self._current_file}:{node.lineno} all arguments to' + f' export must be literal values: {ast.dump(node)}' + ) from e + + def _add_exported_symbol(self, node: ast.Call, symbol_name: str) -> None: + """Adds an exported symbol represented by the given call.""" + if symbol_name.find('.') != -1: + raise BadExportError( + f'{self._current_file}:{node.lineno} export called with symbol' + f' {symbol_name} not defined in current file: {ast.dump(node)}' + ) + v2_apis = tuple( + f'{self._api_name}.{self._literal_value(arg)}' for arg in node.args + ) + v1_apis = v2_apis + for kw in node.keywords: + if kw.arg == 'v1': + v1_apis = tuple( + f'{self._api_name}.{v}' for v in self._literal_value(kw.value) + ) + elif kw.arg == 'allow_multiple_exports': + # no-op kept for backward comapatibility of `tf-keras` with TF 2.13 + pass + else: + raise BadExportError( + f'{self._current_file}:{node.lineno} export called' + f' with unknown argument {kw.arg}: {ast.dump(node)}' + ) + self._exports.add_symbol( + exported_api.ExportedSymbol.create( + file_name=self._current_file, + line_no=node.lineno, + symbol_name=symbol_name, + v2_apis=v2_apis, + v1_apis=v1_apis, + ) + ) + + +def main(argv: Sequence[str]) -> None: + exporter = exported_api.ExportedApi() + p = Parser(exporter, _DECORATOR.value, _API_NAME.value) + for arg in argv[1:]: + p.process_file(arg) + + exporter.write(_OUTPUT.value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/generator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/generator/generator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/generator/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..8a2d01bf47e5a50b7de7145c84bd0630ac0d1b63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/generator/generator.py @@ -0,0 +1,761 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Library that generates the API for tensorflow.""" + +import collections +from collections.abc import Mapping, Sequence, Set +import dataclasses +import os +from typing import Optional + +from absl import app +from absl import flags + +from tensorflow.python.tools.api.generator2.shared import exported_api + +_OUTPUT_FILES = flags.DEFINE_list( + 'output_files', None, 'List of files expected to generate.' +) +_OUTPUT_DIR = flags.DEFINE_string( + 'output_dir', + None, + 'Directory where the generated output files are placed. This should be a' + ' prefix of every directory in "output_files".', +) +_ROOT_INIT_TEMPLATE = flags.DEFINE_string( + 'root_init_template', + None, + 'Template for top level __init__.py file. "#API IMPORTS PLACEHOLDER"' + ' comment will be replaced with imports.', +) +_API_VERSION = flags.DEFINE_integer( + 'apiversion', 2, 'The API version to generate. (1 or 2)' +) +_COMPAT_API_VERSIONS = flags.DEFINE_list( + 'compat_api_versions', + [], + 'Additional versions to generate in compat/ subdirectory.', +) +_COMPAT_INIT_TEMPLATES = flags.DEFINE_list( + 'compat_init_templates', + [], + 'Template for top-level __init__.py files under compat modules. This list' + ' must be in the same order as the list of versions in' + ' "compat_apiversions".', +) +_OUTPUT_PACKAGE = flags.DEFINE_string( + 'output_package', 'tensorflow', 'Root output package.' +) +_USE_LAZY_LOADING = flags.DEFINE_bool( + 'use_lazy_loading', + True, + 'If true, lazily load imports rather than loading them all in the' + ' __init__.py files. Defaults to true.', +) +_PROXY_MODULE_ROOT = flags.DEFINE_string( + 'proxy_module_root', + None, + 'Module root for proxy-import format. If specified, proxy files with `from' + ' proxy_module_root.proxy_module import *` will be created to enable import' + ' resolution under TensorFlow.', +) +_FILE_PREFIXES_TO_STRIP = flags.DEFINE_list( + 'file_prefixes_to_strip', + [], + "File prefixes to strip from the import paths. Ex: bazel's bin and genfile" + ' directories.', +) +_PACKAGES_TO_IGNORE = flags.DEFINE_list( + 'packages_to_ignore', + [], + 'Comma seperated list of packages to ignore tf_exports from. Ex:' + ' packages_to_ignore="tensorflow.python.framework.test_ops"' + ' will not export any tf_exports from test_ops', +) +_MODULE_PREFIX = flags.DEFINE_string( + 'module_prefix', '', 'Prefix to append to all imported modules.' +) +_ROOT_FILE_PATH = flags.DEFINE_string( + 'root_file_name', + '__init__.py', + 'The file name that should be generated for the top level API.', +) + +_GENERATED_FILE_HEADER = """# This file is MACHINE GENERATED! Do not edit. +# Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. +\"\"\"%s +\"\"\" + +import sys as _sys + +""" + +_LAZY_LOADING_MODULE_TEXT_TEMPLATE = """ +# Inform pytype that this module is dynamically populated (b/111239204). +_HAS_DYNAMIC_ATTRIBUTES = True +_PUBLIC_APIS = { +%s +} +""" +_DEPRECATION_FOOTER = """ +from tensorflow.python.util import module_wrapper as _module_wrapper + +if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper): + _sys.modules[__name__] = _module_wrapper.TFModuleWrapper( + _sys.modules[__name__], "%s", public_apis=%s, deprecation=%s, + has_lite=%s) +""" + + +class DocExportedTwiceError(Exception): + """Exception for when two docstrings are registered to a single module.""" + + +def _get_import_path( + file: str, file_prefixes_to_strip: Sequence[str], module_prefix: str +) -> str: + module_import_path = file + for prefix in file_prefixes_to_strip: + module_import_path = module_import_path.removeprefix(prefix) + module_import_path = module_import_path.removesuffix('.py') + module_import_path = module_import_path.removesuffix('__init__') + module_import_path = module_import_path.strip('/') + module_import_path = module_import_path.replace('/', '.') + + return module_prefix + module_import_path + + +@dataclasses.dataclass(frozen=True) +class _Entrypoint: + """An entrypoint that was exposed by the use of a decorator. + + Attributes: + module: The public module that the symbol was exposed to. For example: + tensorflow.io. + name: The name the symbol was exported as. For example: decode_png. + exported_symbol: The symbol that this entrypoint refers back to. + """ + + module: str + name: str + exported_symbol: exported_api.ExportedSymbol + + def get_import( + self, + file_prefixes_to_strip: Sequence[str], + module_prefix: str, + use_lazy_loading: bool, + ) -> str: + """Returns the import statement for this entrypoint. + + Args: + file_prefixes_to_strip: List of prefixes to strip from the file name. + module_prefix: A prefix to add to the import. + use_lazy_loading: Whether to use lazy loading or not. + """ + module_import_path = _get_import_path( + self.exported_symbol.file_name, file_prefixes_to_strip, module_prefix + ) + alias = '' + symbol_name = self.exported_symbol.symbol_name + if self.name != symbol_name: + alias = f' as {self.name}' + if not use_lazy_loading: + return ( + f'from {module_import_path} import' + f' {symbol_name}{alias} # line:' + f' {self.exported_symbol.line_no}' + ) + else: + return ( + f" '{self.name}': ('{module_import_path}'," + f" '{symbol_name}'), # line:" + f' {self.exported_symbol.line_no}' + ) + + +@dataclasses.dataclass(frozen=True) +class PublicAPI: + v1_entrypoints_by_module: Mapping[str, set[_Entrypoint]] + v2_entrypoints_by_module: Mapping[str, set[_Entrypoint]] + v1_generated_imports_by_module: Mapping[str, set[str]] + v2_generated_imports_by_module: Mapping[str, set[str]] + docs_by_module: Mapping[str, str] + + +def get_module(dir_path: str, relative_to_dir: str) -> str: + """Get module that corresponds to path relative to relative_to_dir. + + Args: + dir_path: Path to directory. + relative_to_dir: Get module relative to this directory. + + Returns: + Name of module that corresponds to the given directory. + """ + dir_path = dir_path[len(relative_to_dir) :] + # Convert path separators to '/' for easier parsing below. + dir_path = dir_path.replace(os.sep, '/') + return dir_path.replace('/', '.').strip('.') + + +def generate_proxy_api_files( + output_files: list[str], proxy_module_root: str, output_dir: str +): + """Creates __init__.py files in proxy format for the Python API. + + Args: + output_files: List of __init__.py file paths to create. + proxy_module_root: Module root for proxy-import format. If specified, proxy + files with content like `from proxy_module_root.proxy_module import *` + will be created to enable import resolution under TensorFlow. + output_dir: output API root directory. + """ + for file in output_files: + file_dir = os.path.dirname(file) + if not os.path.isdir(file_dir): + os.makedirs(file_dir) + module = get_module(file_dir, output_dir) + content = f'from {proxy_module_root}.{module} import *' + with open(file, 'w') as f: + f.write(content) + + +def _should_skip_file( + file: str, + file_prefixes_to_strip: Sequence[str], + packages_to_ignore: Sequence[str], + module_prefix: str, +) -> bool: + import_path = _get_import_path(file, file_prefixes_to_strip, module_prefix) + return any(import_path.startswith(package) for package in packages_to_ignore) + + +def get_public_api( + api_mapping_files: Sequence[str], + file_prefixes_to_strip: Sequence[str], + packages_to_ignore: Sequence[str], + output_package: str, + module_prefix: str, +) -> PublicAPI: + """Generates the structure of the public API from the given files. + + Args: + api_mapping_files: List of files containing the exported API mappings and + docstrings. + file_prefixes_to_strip: A list of prefixes to strip from files when + determining the packages to ignore. + packages_to_ignore: A list of python packages that should be ignored when + searching for tf_exports. + output_package: The package to use for the imports. + module_prefix: A prefix to add to the non-generated imports. + + Raises: + DocExportedTwiceError: Two docstrings are registered for the same module. + + Returns: + The public API structure. + """ + ea = exported_api.ExportedApi() + for f in api_mapping_files: + ea.read(f) + + v1_entrypoints_by_module = collections.defaultdict(set) + v2_entrypoints_by_module = collections.defaultdict(set) + + def add_exported_symbols( + api_names: list[str], + s: exported_api.ExportedSymbol, + entrypoints_by_module: Mapping[str, set[_Entrypoint]], + ): + for api_name in api_names: + index_of_last_dot = api_name.rfind('.') + index_of_first_dot = api_name.find('.') + module = output_package + if index_of_first_dot + 1 < index_of_last_dot: + module += f'.{api_name[index_of_first_dot + 1:index_of_last_dot]}' + name = api_name[index_of_last_dot + 1 :] + entrypoints_by_module[module].add(_Entrypoint(module, name, s)) + + for s in ea.symbols: + if _should_skip_file( + s.file_name, file_prefixes_to_strip, packages_to_ignore, module_prefix + ): + continue + add_exported_symbols(s.v1_apis, s, v1_entrypoints_by_module) + add_exported_symbols(s.v2_apis, s, v2_entrypoints_by_module) + + v1_generated_imports_by_module = collections.defaultdict(set) + v2_generated_imports_by_module = collections.defaultdict(set) + + def add_generated_imports( + entrypoints_by_module: Mapping[str, set[_Entrypoint]], + generated_imports_by_module: Mapping[str, set[str]], + ): + for module in entrypoints_by_module: + i = module.rfind('.') + if i == -1: + continue + while i != -1: + parent = module[:i] + generated_imports_by_module[parent].add(module) + module = parent + i = module.rfind('.') + + add_generated_imports( + v1_entrypoints_by_module, v1_generated_imports_by_module + ) + add_generated_imports( + v2_entrypoints_by_module, v2_generated_imports_by_module + ) + + docs_by_module = {} + + for d in ea.docs: + for m in d.modules: + if m in docs_by_module: + raise DocExportedTwiceError( + f'Docstring at {d.file_name}:{d.line_no} is registered for {m},' + ' which already has a registered docstring.' + ) + docs_by_module[m] = d.docstring + + return PublicAPI( + v1_entrypoints_by_module=v1_entrypoints_by_module, + v2_entrypoints_by_module=v2_entrypoints_by_module, + v1_generated_imports_by_module=v1_generated_imports_by_module, + v2_generated_imports_by_module=v2_generated_imports_by_module, + docs_by_module=docs_by_module, + ) + + +def _get_module_docstring( + docs_by_module: Mapping[str, str], module: str +) -> str: + if module in docs_by_module: + return docs_by_module[module] + module = module.replace('tensorflow', 'tf') + return f'Public API for {module} namespace' + + +def _get_imports_for_module( + module: str, + output_package: str, + symbols_by_module: Mapping[str, set[_Entrypoint]], + generated_imports_by_module: Mapping[str, set[str]], + file_prefixes_to_strip: Sequence[str], + module_prefix: str, + use_lazy_loading: bool, + subpackage_rewrite: Optional[str], +) -> str: + """Returns the imports for a module. + + Args: + module: The module to get imports for. + output_package: The package to use for the imports. + symbols_by_module: The symbols that should be exposed by each module. + generated_imports_by_module: The sub-modules that should be exposed by each + module. + file_prefixes_to_strip: The prefixes to strip from the file names of the + imports. + module_prefix: A prefix to add to the non-generated imports. + use_lazy_loading: Whether to use lazy loading or not. + subpackage_rewrite: The subpackage to use for the imports. + """ + content = '' + symbol_imports = list(symbols_by_module[module]) + symbol_imports = sorted( + symbol_imports, key=lambda s: f'{s.exported_symbol.file_name}:{s.name}' + ) + generated_imports = sorted(generated_imports_by_module[module]) + for imp in generated_imports: + if subpackage_rewrite: + imp = imp.replace(output_package, subpackage_rewrite) + last_dot = imp.rfind('.') + if use_lazy_loading: + content += f" '{imp[last_dot+1:]}': ('', '{imp}'),\n" + else: + content += f'from {imp[:last_dot]} import {imp[last_dot+1:]}\n' + for s in symbol_imports: + content += ( + f'{s.get_import(file_prefixes_to_strip, module_prefix, use_lazy_loading=use_lazy_loading)}\n' + ) + return content + + +def gen_public_api( + output_dir: str, + output_package: str, + root_init_template: str, + api_version: int, + compat_api_versions: Sequence[int], + compat_init_templates: Sequence[str], + use_lazy_loading: bool, + file_prefixes_to_strip: Sequence[str], + mapping_files: Sequence[str], + packages_to_ignore: Sequence[str], + module_prefix: str, + root_file_name: str, + output_files: Set[str], +): + """Generates the public API for tensorflow. + + Args: + output_dir: The directory to output the files to. + output_package: The package to use for the imports. + root_init_template: The template for the root init file. + api_version: The version of the API to generate. + compat_api_versions: The versions of the compat APIs to generate. + compat_init_templates: The templates for the compat init files. + use_lazy_loading: Whether to use lazy loading or not. + file_prefixes_to_strip: The prefixes to strip from the file names of the + imports. + mapping_files: The mapping files created by the API Extractor. + packages_to_ignore: A list of python packages that should be ignored when + searching for tf_exports. + module_prefix: A prefix to add to the non-generated imports. + root_file_name: The file name that should be generated for the top level + API. + output_files: List of files expected to generate. + """ + public_api = get_public_api( + mapping_files, + file_prefixes_to_strip, + packages_to_ignore, + output_package, + module_prefix, + ) + + root_entrypoints_by_module = public_api.v2_entrypoints_by_module + root_generated_imports_by_module = public_api.v2_generated_imports_by_module + if api_version == 1: + root_entrypoints_by_module = public_api.v1_entrypoints_by_module + root_generated_imports_by_module = public_api.v1_generated_imports_by_module + + for compat_version in compat_api_versions: + compat_package = f'{output_package}.compat' + compat_version_package = f'{compat_package}.v{compat_version}' + public_api.v2_generated_imports_by_module[compat_package].add( + compat_version_package + ) + public_api.v1_generated_imports_by_module[compat_package].add( + compat_version_package + ) + + _gen_init_files( + output_dir, + output_package, + api_version, + root_entrypoints_by_module, + root_generated_imports_by_module, + public_api.docs_by_module, + root_init_template, + file_prefixes_to_strip, + use_lazy_loading, + module_prefix, + output_files, + root_file_name=root_file_name, + ) + + for compat_index, compat_version in enumerate(compat_api_versions): + compat_output_dir = os.path.join(output_dir, 'compat', f'v{compat_version}') + os.makedirs(compat_output_dir, exist_ok=True) + compat_version = int(compat_version) + + compat_entrypoints_by_module = public_api.v2_entrypoints_by_module + compat_generated_imports_by_module = ( + public_api.v2_generated_imports_by_module + ) + if compat_version == 1: + compat_entrypoints_by_module = public_api.v1_entrypoints_by_module + compat_generated_imports_by_module = ( + public_api.v1_generated_imports_by_module + ) + + _gen_init_files( + compat_output_dir, + output_package, + compat_version, + compat_entrypoints_by_module, + compat_generated_imports_by_module, + public_api.docs_by_module, + compat_init_templates[compat_index] if compat_init_templates else '', + file_prefixes_to_strip, + use_lazy_loading, + module_prefix, + output_files, + subpackage_rewrite=f'{output_package}.compat.v{compat_version}', + ) + + for nested_compat_index, nested_compat_version in enumerate( + compat_api_versions + ): + nested_compat_version = int(nested_compat_version) + nested_compat_output_dir = os.path.join( + compat_output_dir, 'compat', f'v{nested_compat_version}' + ) + nested_compat_entrypoints_by_module = public_api.v2_entrypoints_by_module + nested_compat_generated_imports_by_module = ( + public_api.v2_generated_imports_by_module + ) + if nested_compat_version == 1: + nested_compat_entrypoints_by_module = ( + public_api.v1_entrypoints_by_module + ) + nested_compat_generated_imports_by_module = ( + public_api.v1_generated_imports_by_module + ) + os.makedirs(nested_compat_output_dir, exist_ok=True) + gen_nested_compat_files( + nested_compat_output_dir, + output_package, + nested_compat_version, + nested_compat_entrypoints_by_module, + nested_compat_generated_imports_by_module, + public_api.docs_by_module, + compat_init_templates[nested_compat_index] + if compat_init_templates + else '', + file_prefixes_to_strip, + use_lazy_loading, + compat_api_versions, + module_prefix, + output_files, + ) + + +def _get_module_wrapper( + module: str, + output_dir: str, + output_package: str, + api_version: int, + symbols_by_module: Mapping[str, set[_Entrypoint]], + use_lazy_loading: bool, +) -> str: + """Returns the module wrapper for the given module.""" + if api_version != 1 and not use_lazy_loading: + return '' + deprecated = 'False' + has_lite = 'False' + public_apis_name = 'None' + if api_version == 1 and not output_dir.strip('/').endswith('compat/v1'): + deprecated = 'True' + if 'lite' in symbols_by_module and use_lazy_loading: + has_lite = 'True' + if use_lazy_loading: + public_apis_name = '_PUBLIC_APIS' + return _DEPRECATION_FOOTER % ( + module.removeprefix(output_package).strip('.'), + public_apis_name, + deprecated, + has_lite, + ) + + +def _gen_init_files( + output_dir: str, + output_package: str, + api_version: int, + symbols_by_module: Mapping[str, set[_Entrypoint]], + generated_imports_by_module: Mapping[str, set[str]], + docs_by_module: Mapping[str, str], + root_template_path: str, + file_prefixes_to_strip: Sequence[str], + use_lazy_loading: bool, + module_prefix: str, + output_files: Set[str], + subpackage_rewrite: Optional[str] = None, + root_file_name='__init__.py', +): + """Generates the __init__.py files for the given API version.""" + modules = set(symbols_by_module.keys()) + modules.update(generated_imports_by_module.keys()) + for module in modules: + if len(module) < len(output_package): + continue + module_relative_to_package = module[len(output_package) + 1 :] + module_path = os.path.join( + output_dir, module_relative_to_package.replace('.', '/') + ) + os.makedirs(module_path, exist_ok=True) + module_file_path = os.path.join( + module_path, + root_file_name if not module_relative_to_package else '__init__.py', + ) + module_file_path = os.path.normpath(module_file_path) + if module_file_path not in output_files: + raise AssertionError( + f'Exported api attempted to write to "{module_file_path}" but it is' + ' not in output_files.' + ) + with open(module_file_path, 'w') as f: + module_imports = _get_imports_for_module( + module, + output_package, + symbols_by_module, + generated_imports_by_module, + file_prefixes_to_strip, + module_prefix, + use_lazy_loading, + subpackage_rewrite, + ) + if use_lazy_loading: + module_imports = _LAZY_LOADING_MODULE_TEXT_TEMPLATE % module_imports + # If this module is the root and there is a root template, use it + if module == output_package and root_template_path: + with open(root_template_path, 'r') as template: + content = template.read() + content = content.replace('# API IMPORTS PLACEHOLDER', module_imports) + + underscore_elements = [ + s.name + for s in symbols_by_module[module] + if s.name.startswith('_') + ] + for i in generated_imports_by_module[module]: + module_name = i[i.rfind('.') + 1 :] + if module_name.startswith('_'): + underscore_elements.append(module_name) + + root_module_footer = f""" +_names_with_underscore = [{', '.join(sorted([f"'{s}'" for s in underscore_elements]))}] +__all__ = [_s for _s in dir() if not _s.startswith('_')] +__all__.extend([_s for _s in _names_with_underscore]) + """ + + content = content.replace('# __all__ PLACEHOLDER', root_module_footer) + + content = content.replace( + '# WRAPPER_PLACEHOLDER', + _get_module_wrapper( + module, + output_dir, + output_package, + api_version, + symbols_by_module, + use_lazy_loading, + ), + ) + + f.write(content) + continue + + f.write( + _GENERATED_FILE_HEADER % _get_module_docstring(docs_by_module, module) + ) + + f.write(module_imports) + + f.write( + _get_module_wrapper( + module, + output_dir, + output_package, + api_version, + symbols_by_module, + use_lazy_loading, + ) + ) + + +def gen_nested_compat_files( + output_dir: str, + output_package: str, + api_version: int, + symbols_by_module: Mapping[str, set[_Entrypoint]], + generated_imports_by_module: Mapping[str, set[str]], + docs_by_module: Mapping[str, str], + root_template_path: str, + file_prefixes_to_strip: Sequence[str], + use_lazy_loading: bool, + compat_versions: Sequence[int], + module_prefix: str, + output_files: Set[str], +): + """Generates the nested compat __init__.py files.""" + nested_compat_symbols_by_module: dict[str, set[_Entrypoint]] = {} + nested_generated_imports_by_module: dict[str, set[str]] = {} + compat_module = f'{output_package}.compat' + # The nested compat files should only generate imports for the nested root + # package, and its corresponding compat package. + if output_package in symbols_by_module: + nested_compat_symbols_by_module[output_package] = symbols_by_module[ + output_package + ] + if compat_module in symbols_by_module: + nested_compat_symbols_by_module[compat_module] = symbols_by_module[ + compat_module + ] + if output_package in generated_imports_by_module: + nested_generated_imports_by_module[output_package] = ( + generated_imports_by_module[output_package] + ) + if compat_module in generated_imports_by_module: + nested_generated_imports_by_module[compat_module] = ( + generated_imports_by_module[compat_module] + ) + + _gen_init_files( + output_dir, + output_package, + api_version, + nested_compat_symbols_by_module, + nested_generated_imports_by_module, + docs_by_module, + root_template_path, + file_prefixes_to_strip, + use_lazy_loading, + module_prefix, + output_files, + f'{compat_module}.v{api_version}', + ) + + for compat_version in compat_versions: + nested_generated_imports_by_module[compat_module].add( + f'{output_package}.compat.v{compat_version}' + ) + + +def main(argv: Sequence[str]) -> None: + if not _OUTPUT_DIR.value or not _OUTPUT_FILES.value: + raise app.UsageError('--output_dir and --output_files are required') + + if _PROXY_MODULE_ROOT.value: + generate_proxy_api_files( + _OUTPUT_FILES.value, _PROXY_MODULE_ROOT.value, _OUTPUT_DIR.value + ) + return + + output_files = [os.path.normpath(f) for f in _OUTPUT_FILES.value] + + for out_file in output_files: + with open(out_file, 'w') as f: + f.write('') + + gen_public_api( + _OUTPUT_DIR.value, + _OUTPUT_PACKAGE.value, + _ROOT_INIT_TEMPLATE.value, + _API_VERSION.value, + [int(v) for v in _COMPAT_API_VERSIONS.value], + _COMPAT_INIT_TEMPLATES.value, + _USE_LAZY_LOADING.value, + _FILE_PREFIXES_TO_STRIP.value, + argv[1:], + _PACKAGES_TO_IGNORE.value, + _MODULE_PREFIX.value, + _ROOT_FILE_PATH.value, + set(output_files), + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/shared/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/shared/exported_api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/shared/exported_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8dc80b7e127d05ca2779de60a36f10a6050699 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/api/generator2/shared/exported_api.py @@ -0,0 +1,113 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Reads and writes files with TF Python exports metadata.""" + +from collections.abc import Iterable, Sequence +import json +from typing import Any, NamedTuple + + +class ExportedSymbol(NamedTuple): + """Information about a single tf_export instance.""" + + file_name: str + line_no: int + symbol_name: str + v1_apis: tuple[str, ...] + v2_apis: tuple[str, ...] + + @classmethod + def create( + cls, *, v1_apis: Sequence[str], v2_apis: Sequence[str], **kwargs + ) -> "ExportedSymbol": + return cls(v1_apis=tuple(v1_apis), v2_apis=tuple(v2_apis), **kwargs) + + +class ExportedDoc(NamedTuple): + """Information about an export Module docstring.""" + + file_name: str + line_no: int + modules: tuple[str, ...] + docstring: str + + @classmethod + def create(cls, *, modules: Sequence[str], **kwargs) -> "ExportedDoc": + return cls(modules=tuple(modules), **kwargs) + + +class ExportedApi(object): + """ExportedApi is a collection of ExportedSymbols.""" + + _docs: set[ExportedDoc] + _symbols: set[ExportedSymbol] + + def __init__( + self, + *, + docs: Iterable[ExportedDoc] = (), + symbols: Iterable[ExportedSymbol] = (), + ): + self._docs = set(docs) + self._symbols = set(symbols) + + def write(self, filename: str, **kwargs) -> None: + """Writes exports to filename.""" + with open(filename, mode="w", encoding="utf-8") as f: + json.dump( + { + "docs": [d._asdict() for d in sorted(self.docs)], + "symbols": [s._asdict() for s in sorted(self.symbols)], + }, + f, + **kwargs, + ) + + def read(self, filename: str) -> None: + """Reads exports from filename.""" + with open(filename, mode="r", encoding="utf-8") as f: + data = json.load(f) + self._docs.update(ExportedDoc.create(**d) for d in data["docs"]) + self._symbols.update(ExportedSymbol.create(**s) for s in data["symbols"]) + + def add_symbol(self, export: ExportedSymbol) -> None: + self._symbols.add(export) + + def add_doc(self, export: ExportedDoc) -> None: + self._docs.add(export) + + @property + def docs(self) -> Iterable[ExportedDoc]: + return self._docs + + @property + def symbols(self) -> Iterable[ExportedSymbol]: + return self._symbols + + def __str__(self) -> str: + return json.dumps({ + "docs": [d._asdict() for d in sorted(self.docs)], + "symbols": [s._asdict() for s in sorted(self.symbols)], + }) + + def __repr__(self) -> str: + return str(self) + + def __eq__(self, o: Any) -> bool: + return ( + type(self) is type(o) + and self.docs == o.docs + and self.symbols == o.symbols + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/freeze_graph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/freeze_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..63198d9df1db6677f6455ffd924ed17501ef887d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/freeze_graph.py @@ -0,0 +1,542 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Converts checkpoint variables into Const ops in a standalone GraphDef file. + +This script is designed to take a GraphDef proto, a SaverDef proto, and a set of +variable values stored in a checkpoint file, and output a GraphDef with all of +the variable ops converted into const ops containing the values of the +variables. + +It's useful to do this when we need to load a single file in C++, especially in +environments like mobile or embedded where we may not have access to the +RestoreTensor ops and file loading calls that they rely on. + +An example of command-line usage is: +bazel build tensorflow/python/tools:freeze_graph && \ +bazel-bin/tensorflow/python/tools/freeze_graph \ +--input_graph=some_graph_def.pb \ +--input_checkpoint=model.ckpt-8361242 \ +--output_graph=/tmp/frozen_graph.pb --output_node_names=softmax + +You can also look at freeze_graph_test.py for an example of how to use it. + +""" +import argparse +import re +import sys +from typing import List, Optional, Union + +from absl import app + +from google.protobuf import text_format +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.client import session +from tensorflow.python.framework import convert_to_constants +from tensorflow.python.framework import importer +from tensorflow.python.platform import gfile +from tensorflow.python.saved_model import loader +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.tools import saved_model_utils +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.training import saver as saver_lib + + +def _has_no_variables(sess: session.Session) -> bool: + """Determines if the graph has any variables. + + Args: + sess: TensorFlow Session. + + Returns: + Bool. + """ + for op in sess.graph.get_operations(): + if op.type.startswith("Variable") or op.type.endswith("VariableOp"): + return False + return True + + +def freeze_graph_with_def_protos( + input_graph_def: Optional[graph_pb2.GraphDef], + input_saver_def: Optional[saver_pb2.SaverDef], + input_checkpoint: Optional[str], + output_node_names: str, + restore_op_name: Optional[str], + filename_tensor_name: Optional[str], + output_graph: str, + clear_devices: bool, + initializer_nodes: str, + variable_names_whitelist: str = "", + variable_names_denylist: str = "", + input_meta_graph_def: Optional[meta_graph_pb2.MetaGraphDef] = None, + input_saved_model_dir: Optional[str] = None, + saved_model_tags: Optional[List[str]] = None, + checkpoint_version: int = saver_pb2.SaverDef.V2, +) -> graph_pb2.GraphDef: + """Converts all variables in a graph and checkpoint into constants. + + Args: + input_graph_def: A `GraphDef`. + input_saver_def: A `SaverDef` (optional). + input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking + priority. Typically the result of `Saver.save()` or that of + `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or + V1/V2. + output_node_names: The name(s) of the output nodes, comma separated. + restore_op_name: Unused. + filename_tensor_name: Unused. + output_graph: String where to write the frozen `GraphDef`. + clear_devices: A Bool whether to remove device specifications. + initializer_nodes: Comma separated string of initializer nodes to run before + freezing. + variable_names_whitelist: The set of variable names to convert (optional, by + default, all variables are converted). + variable_names_denylist: The set of variable names to omit converting to + constants (optional). + input_meta_graph_def: A `MetaGraphDef` (optional), + input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file and + variables (optional). + saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to + load, in string format (optional). + checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1 + or saver_pb2.SaverDef.V2) + + Returns: + Location of the output_graph_def. + """ + del restore_op_name, filename_tensor_name # Unused by updated loading code. + + # 'input_checkpoint' may be a prefix if we're using Saver V2 format + if not input_saved_model_dir and not checkpoint_management.checkpoint_exists( + input_checkpoint + ): + raise ValueError( + "Input checkpoint '" + input_checkpoint + "' doesn't exist!" + ) + + if not output_node_names: + raise ValueError( + "You need to supply the name of a node to --output_node_names." + ) + + # Remove all the explicit device specifications for this node. This helps to + # make the graph more portable. + if clear_devices: + if input_meta_graph_def: + for node in input_meta_graph_def.graph_def.node: + node.device = "" + elif input_graph_def: + for node in input_graph_def.node: + node.device = "" + + if input_graph_def: + _ = importer.import_graph_def(input_graph_def, name="") + with session.Session() as sess: + if input_saver_def: + saver = saver_lib.Saver( + saver_def=input_saver_def, write_version=checkpoint_version + ) + saver.restore(sess, input_checkpoint) + elif input_meta_graph_def: + restorer = saver_lib.import_meta_graph( + input_meta_graph_def, clear_devices=True + ) + restorer.restore(sess, input_checkpoint) + if initializer_nodes: + sess.run(initializer_nodes.replace(" ", "").split(",")) + elif input_saved_model_dir: + if saved_model_tags is None: + saved_model_tags = [] + loader.load(sess, saved_model_tags, input_saved_model_dir) + else: + var_list = {} + reader = py_checkpoint_reader.NewCheckpointReader(input_checkpoint) + var_to_shape_map = reader.get_variable_to_shape_map() + + # List of all partition variables. Because the condition is heuristic + # based, the list could include false positives. + all_partition_variable_names = [ + tensor.name.split(":")[0] + for op in sess.graph.get_operations() + for tensor in op.values() + if re.search(r"/part_\d+/", tensor.name) + ] + has_partition_var = False + + for key in var_to_shape_map: + try: + tensor = sess.graph.get_tensor_by_name(key + ":0") + if any(key in name for name in all_partition_variable_names): + has_partition_var = True + except KeyError: + # This tensor doesn't exist in the graph (for example it's + # 'global_step' or a similar housekeeping element) so skip it. + continue + var_list[key] = tensor + + try: + saver = saver_lib.Saver( + var_list=var_list, write_version=checkpoint_version + ) + except TypeError as e: + # `var_list` is required to be a map of variable names to Variable + # tensors. Partition variables are Identity tensors that cannot be + # handled by Saver. + if has_partition_var: + raise ValueError( + "Models containing partition variables cannot be converted " + "from checkpoint files. Please pass in a SavedModel using " + "the flag --input_saved_model_dir." + ) + # Models that have been frozen previously do not contain Variables. + elif _has_no_variables(sess): + raise ValueError( + "No variables were found in this model. It is likely the model " + "was frozen previously. You cannot freeze a graph twice." + ) + else: + raise e + + saver.restore(sess, input_checkpoint) + if initializer_nodes: + sess.run(initializer_nodes.replace(" ", "").split(",")) + + variable_names_whitelist = ( + variable_names_whitelist.replace(" ", "").split(",") + if variable_names_whitelist + else None + ) + variable_names_denylist = ( + variable_names_denylist.replace(" ", "").split(",") + if variable_names_denylist + else None + ) + + if input_meta_graph_def: + output_graph_def = convert_to_constants.convert_variables_to_constants( + sess, + input_meta_graph_def.graph_def, + output_node_names.replace(" ", "").split(","), + variable_names_whitelist=variable_names_whitelist, + variable_names_blacklist=variable_names_denylist, + ) + else: + output_graph_def = convert_to_constants.convert_variables_to_constants( + sess, + input_graph_def, + output_node_names.replace(" ", "").split(","), + variable_names_whitelist=variable_names_whitelist, + variable_names_blacklist=variable_names_denylist, + ) + + # Write GraphDef to file if output path has been given. + if output_graph: + with gfile.GFile(output_graph, "wb") as f: + f.write(output_graph_def.SerializeToString(deterministic=True)) + + return output_graph_def + + +def _parse_input_graph_proto( + input_graph: str, input_binary: bool +) -> graph_pb2.GraphDef: + """Parses input tensorflow graph into GraphDef proto.""" + if not gfile.Exists(input_graph): + raise IOError("Input graph file '" + input_graph + "' does not exist!") + input_graph_def = graph_pb2.GraphDef() + mode = "rb" if input_binary else "r" + with gfile.GFile(input_graph, mode) as f: + if input_binary: + input_graph_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read(), input_graph_def) + return input_graph_def + + +def _parse_input_meta_graph_proto( + input_graph: str, input_binary: bool +) -> meta_graph_pb2.MetaGraphDef: + """Parses input tensorflow graph into MetaGraphDef proto.""" + if not gfile.Exists(input_graph): + raise IOError("Input meta graph file '" + input_graph + "' does not exist!") + input_meta_graph_def = meta_graph_pb2.MetaGraphDef() + mode = "rb" if input_binary else "r" + with gfile.GFile(input_graph, mode) as f: + if input_binary: + input_meta_graph_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read(), input_meta_graph_def) + print("Loaded meta graph file '" + input_graph) + return input_meta_graph_def + + +def _parse_input_saver_proto(input_saver, input_binary): + """Parses input tensorflow Saver into SaverDef proto.""" + if not gfile.Exists(input_saver): + raise IOError("Input saver file '" + input_saver + "' does not exist!") + mode = "rb" if input_binary else "r" + with gfile.GFile(input_saver, mode) as f: + saver_def = saver_pb2.SaverDef() + if input_binary: + saver_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read(), saver_def) + return saver_def + + +def freeze_graph( + input_graph: Optional[str], + input_saver: str, + input_binary: bool, + input_checkpoint: Optional[str], + output_node_names: str, + restore_op_name: Optional[str], + filename_tensor_name: Optional[str], + output_graph: str, + clear_devices: bool, + initializer_nodes: str, + variable_names_whitelist: str = "", + variable_names_denylist: str = "", + input_meta_graph: Union[None, bool, str] = None, + input_saved_model_dir: Optional[str] = None, + saved_model_tags: str = tag_constants.SERVING, + checkpoint_version: int = saver_pb2.SaverDef.V2, +) -> graph_pb2.GraphDef: + """Converts all variables in a graph and checkpoint into constants. + + Args: + input_graph: A `GraphDef` file to load. + input_saver: A TensorFlow Saver file. + input_binary: A Bool. True means input_graph is .pb, False indicates .pbtxt. + input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking + priority. Typically the result of `Saver.save()` or that of + `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or + V1/V2. + output_node_names: The name(s) of the output nodes, comma separated. + restore_op_name: Unused. + filename_tensor_name: Unused. + output_graph: String where to write the frozen `GraphDef`. + clear_devices: A Bool whether to remove device specifications. + initializer_nodes: Comma separated list of initializer nodes to run before + freezing. + variable_names_whitelist: The set of variable names to convert (optional, by + default, all variables are converted), + variable_names_denylist: The set of variable names to omit converting to + constants (optional). + input_meta_graph: A `MetaGraphDef` file to load (optional). + input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file and + variables (optional). + saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to + load, in string format. + checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1 + or saver_pb2.SaverDef.V2). + + Returns: + String that is the location of frozen GraphDef. + """ + input_graph_def = None + if input_saved_model_dir: + input_graph_def = saved_model_utils.get_meta_graph_def( + input_saved_model_dir, saved_model_tags + ).graph_def + elif input_graph: + input_graph_def = _parse_input_graph_proto(input_graph, input_binary) + input_meta_graph_def = None + if input_meta_graph: + input_meta_graph_def = _parse_input_meta_graph_proto( + input_meta_graph, input_binary + ) + input_saver_def = None + if input_saver: + input_saver_def = _parse_input_saver_proto(input_saver, input_binary) + return freeze_graph_with_def_protos( + input_graph_def, + input_saver_def, + input_checkpoint, + output_node_names, + restore_op_name, + filename_tensor_name, + output_graph, + clear_devices, + initializer_nodes, + variable_names_whitelist, + variable_names_denylist, + input_meta_graph_def, + input_saved_model_dir, + [tag for tag in saved_model_tags.replace(" ", "").split(",") if tag], + checkpoint_version=checkpoint_version, + ) + + +def main(unused_args, flags): + if flags.checkpoint_version == 1: + checkpoint_version = saver_pb2.SaverDef.V1 + elif flags.checkpoint_version == 2: + checkpoint_version = saver_pb2.SaverDef.V2 + else: + raise ValueError( + "Invalid checkpoint version (must be '1' or '2'): %d" + % flags.checkpoint_version + ) + freeze_graph( + flags.input_graph, + flags.input_saver, + flags.input_binary, + flags.input_checkpoint, + flags.output_node_names, + flags.restore_op_name, + flags.filename_tensor_name, + flags.output_graph, + flags.clear_devices, + flags.initializer_nodes, + flags.variable_names_whitelist, + flags.variable_names_denylist, + flags.input_meta_graph, + flags.input_saved_model_dir, + flags.saved_model_tags, + checkpoint_version, + ) + + +def run_main(): + """Main function of freeze_graph.""" + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--input_graph", + type=str, + default="", + help="TensorFlow 'GraphDef' file to load.", + ) + parser.add_argument( + "--input_saver", + type=str, + default="", + help="TensorFlow saver file to load.", + ) + parser.add_argument( + "--input_checkpoint", + type=str, + default="", + help="TensorFlow variables file to load.", + ) + parser.add_argument( + "--checkpoint_version", + type=int, + default=2, + help="Tensorflow variable file format", + ) + parser.add_argument( + "--output_graph", + type=str, + default="", + help="Output 'GraphDef' file name.", + ) + parser.add_argument( + "--input_binary", + nargs="?", + const=True, + type="bool", + default=False, + help="Whether the input files are in binary format.", + ) + parser.add_argument( + "--output_node_names", + type=str, + default="", + help="The name of the output nodes, comma separated.", + ) + parser.add_argument( + "--restore_op_name", + type=str, + default="save/restore_all", + help="""\ + The name of the master restore operator. Deprecated, unused by updated \ + loading code. + """, + ) + parser.add_argument( + "--filename_tensor_name", + type=str, + default="save/Const:0", + help="""\ + The name of the tensor holding the save path. Deprecated, unused by \ + updated loading code. + """, + ) + parser.add_argument( + "--clear_devices", + nargs="?", + const=True, + type="bool", + default=True, + help="Whether to remove device specifications.", + ) + parser.add_argument( + "--initializer_nodes", + type=str, + default="", + help="Comma separated list of initializer nodes to run before freezing.", + ) + parser.add_argument( + "--variable_names_whitelist", + type=str, + default="", + help="""\ + Comma separated list of variables to convert to constants. If specified, \ + only those variables will be converted to constants.\ + """, + ) + parser.add_argument( + "--variable_names_denylist", + type=str, + default="", + help="""\ + Comma separated list of variables to skip converting to constants.\ + """, + ) + parser.add_argument( + "--input_meta_graph", + type=str, + default="", + help="TensorFlow 'MetaGraphDef' file to load.", + ) + parser.add_argument( + "--input_saved_model_dir", + type=str, + default="", + help="Path to the dir with TensorFlow 'SavedModel' file and variables.", + ) + parser.add_argument( + "--saved_model_tags", + type=str, + default="serve", + help="""\ + Group of tag(s) of the MetaGraphDef to load, in string format,\ + separated by \',\'. For tag-set contains multiple tags, all tags \ + must be passed in.\ + """, + ) + flags, unparsed = parser.parse_known_args() + + my_main = lambda unused_args: main(unused_args, flags) + app.run(main=my_main, argv=[sys.argv[0]] + unparsed) + + +if __name__ == "__main__": + run_main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/import_pb_to_tensorboard.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/import_pb_to_tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..abf1e93d2807b6efc9dbc15f47c822a3f4174ef1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/import_pb_to_tensorboard.py @@ -0,0 +1,90 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ================================ +"""Imports a protobuf model as a graph in Tensorboard.""" + +import argparse +import sys + +from absl import app + +from tensorflow.python.client import session +from tensorflow.python.framework import importer +from tensorflow.python.framework import ops +from tensorflow.python.summary import summary +from tensorflow.python.tools import saved_model_utils + +# Try importing TensorRT ops if available +# TODO(aaroey): ideally we should import everything from contrib, but currently +# tensorrt module would cause build errors when being imported in +# tensorflow/contrib/__init__.py. Fix it. +# pylint: disable=unused-import,g-import-not-at-top,wildcard-import +try: + from tensorflow.contrib.tensorrt.ops.gen_trt_engine_op import * +except ImportError: + pass +# pylint: enable=unused-import,g-import-not-at-top,wildcard-import + + +def import_to_tensorboard(model_dir, log_dir, tag_set): + """View an SavedModel as a graph in Tensorboard. + + Args: + model_dir: The directory containing the SavedModel to import. + log_dir: The location for the Tensorboard log to begin visualization from. + tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, + separated by ','. For tag-set contains multiple tags, all tags must be + passed in. + Usage: Call this function with your SavedModel location and desired log + directory. Launch Tensorboard by pointing it to the log directory. View your + imported SavedModel as a graph. + """ + with session.Session(graph=ops.Graph()) as sess: + input_graph_def = saved_model_utils.get_meta_graph_def(model_dir, + tag_set).graph_def + importer.import_graph_def(input_graph_def) + + pb_visual_writer = summary.FileWriter(log_dir) + pb_visual_writer.add_graph(sess.graph) + print("Model Imported. Visualize by running: " + "tensorboard --logdir={}".format(log_dir)) + + +def main(_): + import_to_tensorboard(FLAGS.model_dir, FLAGS.log_dir, FLAGS.tag_set) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--model_dir", + type=str, + default="", + required=True, + help="The directory containing the SavedModel to import.") + parser.add_argument( + "--log_dir", + type=str, + default="", + required=True, + help="The location for the Tensorboard log to begin visualization from.") + parser.add_argument( + "--tag_set", + type=str, + default="serve", + required=False, + help='tag-set of graph in SavedModel to load, separated by \',\'') + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/inspect_checkpoint.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/inspect_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..90f5752eebad001c9c6b37773df3aaac1608feaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/inspect_checkpoint.py @@ -0,0 +1,203 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A simple script for inspect checkpoint files.""" +import argparse +import re +import sys + +from absl import app +import numpy as np + +from tensorflow.python.framework import errors_impl +from tensorflow.python.platform import flags +from tensorflow.python.training import py_checkpoint_reader + +FLAGS = None + + +def _count_total_params(reader, count_exclude_pattern=""): + """Count total number of variables.""" + var_to_shape_map = reader.get_variable_to_shape_map() + + # Filter out tensors that we don't want to count + if count_exclude_pattern: + regex_pattern = re.compile(count_exclude_pattern) + new_var_to_shape_map = {} + exclude_num_tensors = 0 + exclude_num_params = 0 + for v in var_to_shape_map: + if regex_pattern.search(v): + exclude_num_tensors += 1 + exclude_num_params += np.prod(var_to_shape_map[v]) + else: + new_var_to_shape_map[v] = var_to_shape_map[v] + var_to_shape_map = new_var_to_shape_map + print("# Excluding %d tensors (%d params) that match %s when counting." % ( + exclude_num_tensors, exclude_num_params, count_exclude_pattern)) + + var_sizes = [np.prod(var_to_shape_map[v]) for v in var_to_shape_map] + return np.sum(var_sizes, dtype=int) + + +def print_tensors_in_checkpoint_file(file_name, tensor_name, all_tensors, + all_tensor_names=False, + count_exclude_pattern=""): + """Prints tensors in a checkpoint file. + + If no `tensor_name` is provided, prints the tensor names and shapes + in the checkpoint file. + + If `tensor_name` is provided, prints the content of the tensor. + + Args: + file_name: Name of the checkpoint file. + tensor_name: Name of the tensor in the checkpoint file to print. + all_tensors: Boolean indicating whether to print all tensors. + all_tensor_names: Boolean indicating whether to print all tensor names. + count_exclude_pattern: Regex string, pattern to exclude tensors when count. + """ + try: + reader = py_checkpoint_reader.NewCheckpointReader(file_name) + if all_tensors or all_tensor_names: + var_to_shape_map = reader.get_variable_to_shape_map() + var_to_dtype_map = reader.get_variable_to_dtype_map() + for key, value in sorted(var_to_shape_map.items()): + print("tensor: %s (%s) %s" % (key, var_to_dtype_map[key].name, value)) + if all_tensors: + try: + print(reader.get_tensor(key)) + except errors_impl.InternalError: + print("") + elif not tensor_name: + print(reader.debug_string().decode("utf-8", errors="ignore")) + else: + if not reader.has_tensor(tensor_name): + print("Tensor %s not found in checkpoint" % tensor_name) + return + + var_to_shape_map = reader.get_variable_to_shape_map() + var_to_dtype_map = reader.get_variable_to_dtype_map() + print("tensor: %s (%s) %s" % + (tensor_name, var_to_dtype_map[tensor_name].name, + var_to_shape_map[tensor_name])) + print(reader.get_tensor(tensor_name)) + + # Count total number of parameters + print("# Total number of params: %d" % _count_total_params( + reader, count_exclude_pattern=count_exclude_pattern)) + except Exception as e: # pylint: disable=broad-except + print(str(e)) + if "corrupted compressed block contents" in str(e): + print("It's likely that your checkpoint file has been compressed " + "with SNAPPY.") + if ("Data loss" in str(e) and + any(e in file_name for e in [".index", ".meta", ".data"])): + proposed_file = ".".join(file_name.split(".")[0:-1]) + v2_file_error_template = """ +It's likely that this is a V2 checkpoint and you need to provide the filename +*prefix*. Try removing the '.' and extension. Try: +inspect checkpoint --file_name = {}""" + print(v2_file_error_template.format(proposed_file)) + + +def parse_numpy_printoption(kv_str): + """Sets a single numpy printoption from a string of the form 'x=y'. + + See documentation on numpy.set_printoptions() for details about what values + x and y can take. x can be any option listed there other than 'formatter'. + + Args: + kv_str: A string of the form 'x=y', such as 'threshold=100000' + + Raises: + argparse.ArgumentTypeError: If the string couldn't be used to set any + nump printoption. + """ + k_v_str = kv_str.split("=", 1) + if len(k_v_str) != 2 or not k_v_str[0]: + raise argparse.ArgumentTypeError("'%s' is not in the form k=v." % kv_str) + k, v_str = k_v_str + printoptions = np.get_printoptions() + if k not in printoptions: + raise argparse.ArgumentTypeError("'%s' is not a valid printoption." % k) + v_type = type(printoptions[k]) + if v_type is type(None): + raise argparse.ArgumentTypeError( + "Setting '%s' from the command line is not supported." % k) + try: + v = ( + v_type(v_str) + if v_type is not bool else flags.BooleanParser().parse(v_str)) + except ValueError as e: + raise argparse.ArgumentTypeError(e.message) + np.set_printoptions(**{k: v}) + + +def main(unused_argv): + if not FLAGS.file_name: + print("Usage: inspect_checkpoint --file_name=checkpoint_file_name " + "[--tensor_name=tensor_to_print] " + "[--all_tensors] " + "[--all_tensor_names] " + "[--printoptions]") + sys.exit(1) + else: + print_tensors_in_checkpoint_file( + FLAGS.file_name, FLAGS.tensor_name, + FLAGS.all_tensors, FLAGS.all_tensor_names, + count_exclude_pattern=FLAGS.count_exclude_pattern) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--file_name", + type=str, + default="", + help="Checkpoint filename. " + "Note, if using Checkpoint V2 format, file_name is the " + "shared prefix between all files in the checkpoint.") + parser.add_argument( + "--tensor_name", + type=str, + default="", + help="Name of the tensor to inspect") + parser.add_argument( + "--count_exclude_pattern", + type=str, + default="", + help="Pattern to exclude tensors, e.g., from optimizers, when counting.") + parser.add_argument( + "--all_tensors", + nargs="?", + const=True, + type="bool", + default=False, + help="If True, print the names and values of all the tensors.") + parser.add_argument( + "--all_tensor_names", + nargs="?", + const=True, + type="bool", + default=False, + help="If True, print the names of all the tensors.") + parser.add_argument( + "--printoptions", + nargs="*", + type=parse_numpy_printoption, + help="Argument for numpy.set_printoptions(), in the form 'k=v'.") + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/module_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/module_util.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6e9007dc6c7ed8be6eb84761977bac8a96245c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/module_util.py @@ -0,0 +1,48 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper functions for modules.""" +import os + +import importlib + + +def get_parent_dir(module): + return os.path.abspath(os.path.join(os.path.dirname(module.__file__), "..")) + + +def get_parent_dir_for_name(module_name): + """Get parent directory for module with the given name. + + Args: + module_name: Module name for e.g. + tensorflow_estimator.python.estimator.api._v1.estimator. + + Returns: + Path to the parent directory if module is found and None otherwise. + Given example above, it should return: + /pathtoestimator/tensorflow_estimator/python/estimator/api/_v1. + """ + name_split = module_name.split(".") + if not name_split: + return None + + try: + spec = importlib.util.find_spec(name_split[0]) + except ValueError: + return None + if not spec or not spec.origin: + return None + base_path = os.path.dirname(spec.origin) + return os.path.join(base_path, *name_split[1:-1]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..d580e75bed4a1f22396e89ce616e56eac3f4b3b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference.py @@ -0,0 +1,161 @@ +# pylint: disable=g-bad-file-header +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Removes parts of a graph that are only needed for training. + +There are several common transformations that can be applied to GraphDefs +created to train a model, that help reduce the amount of computation needed when +the network is used only for inference. These include: + + - Removing training-only operations like checkpoint saving. + + - Stripping out parts of the graph that are never reached. + + - Removing debug operations like CheckNumerics. + + - Folding batch normalization ops into the pre-calculated weights. + + - Fusing common operations into unified versions. + +This script takes either a frozen binary GraphDef file (where the weight +variables have been converted into constants by the freeze_graph script), or a +text GraphDef proto file (the weight variables are stored in a separate +checkpoint file), and outputs a new GraphDef with the optimizations applied. + +If the input graph is a text graph file, make sure to include the node that +restores the variable weights in output_names. That node is usually named +"restore_all". + +An example of command-line usage is: + +bazel build tensorflow/python/tools:optimize_for_inference && \ +bazel-bin/tensorflow/python/tools/optimize_for_inference \ +--input=frozen_inception_graph.pb \ +--output=optimized_inception_graph.pb \ +--frozen_graph=True \ +--input_names=Mul \ +--output_names=softmax + + +""" + +import argparse +import os +import sys + +from absl import app + +from google.protobuf import text_format +from tensorflow.core.framework import graph_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import graph_io +from tensorflow.python.platform import gfile +from tensorflow.python.tools import optimize_for_inference_lib + +FLAGS = None + + +def main(unused_args): + if not gfile.Exists(FLAGS.input): + print("Input graph file '" + FLAGS.input + "' does not exist!") + return -1 + + input_graph_def = graph_pb2.GraphDef() + with gfile.Open(FLAGS.input, "rb") as f: + data = f.read() + if FLAGS.frozen_graph: + input_graph_def.ParseFromString(data) + else: + text_format.Merge(data.decode("utf-8"), input_graph_def) + + output_graph_def = optimize_for_inference_lib.optimize_for_inference( + input_graph_def, + FLAGS.input_names.split(","), + FLAGS.output_names.split(","), + _parse_placeholder_types(FLAGS.placeholder_type_enum), + FLAGS.toco_compatible) + + if FLAGS.frozen_graph: + f = gfile.GFile(FLAGS.output, "w") + f.write(output_graph_def.SerializeToString()) + else: + graph_io.write_graph(output_graph_def, + os.path.dirname(FLAGS.output), + os.path.basename(FLAGS.output)) + return 0 + + +def _parse_placeholder_types(values): + """Extracts placeholder types from a comma separate list.""" + values = [int(value) for value in values.split(",")] + return values if len(values) > 1 else values[0] + + +def parse_args(): + """Parses command line arguments.""" + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--input", + type=str, + default="", + help="TensorFlow \'GraphDef\' file to load.") + parser.add_argument( + "--output", + type=str, + default="", + help="File to save the output graph to.") + parser.add_argument( + "--input_names", + type=str, + default="", + help="Input node names, comma separated.") + parser.add_argument( + "--output_names", + type=str, + default="", + help="Output node names, comma separated.") + parser.add_argument( + "--frozen_graph", + nargs="?", + const=True, + type="bool", + default=True, + help="""\ + If true, the input graph is a binary frozen GraphDef + file; if false, it is a text GraphDef proto file.\ + """) + parser.add_argument( + "--placeholder_type_enum", + type=str, + default=str(dtypes.float32.as_datatype_enum), + help="""\ + The AttrValue enum to use for placeholders. + Or a comma separated list, one value for each placeholder.\ + """) + parser.add_argument( + "--toco_compatible", + type=bool, + default=False, + help="""\ + If true, only use ops compatible with Tensorflow + Lite Optimizing Converter.\ + """) + return parser.parse_known_args() + + +if __name__ == "__main__": + FLAGS, unparsed = parse_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..53edbf2b522ae3919de2aa650f997e616f108e54 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/optimize_for_inference_lib.py @@ -0,0 +1,594 @@ +# pylint: disable=g-bad-file-header +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Removes parts of a graph that are only needed for training. + +There are several common transformations that can be applied to GraphDefs +created to train a model, that help reduce the amount of computation needed when +the network is used only for inference. These include: + + - Removing training-only operations like checkpoint saving. + + - Stripping out parts of the graph that are never reached. + + - Removing debug operations like CheckNumerics. + + - Folding batch normalization ops into the pre-calculated weights. + + - Fusing common operations into unified versions. + +This script takes a frozen GraphDef file (where the weight variables have been +converted into constants by the freeze_graph script) and outputs a new GraphDef +with the optimizations applied. + +An example of command-line usage is: + +bazel build tensorflow/python/tools:optimize_for_inference && \ +bazel-bin/tensorflow/python/tools/optimize_for_inference \ +--input_graph=some_graph_def.pb \ +--output_graph=/tmp/optimized_graph.pb \ +--input_names=Mul \ +--output_names=softmax + +""" + +import collections +import math +import re +from typing import Mapping, Sequence + +import numpy as np + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import graph_util +from tensorflow.python.framework import tensor_util +from tensorflow.python.platform import flags as flags_lib +from tensorflow.python.platform import tf_logging +from tensorflow.python.tools import strip_unused_lib + +flags = flags_lib +FLAGS = flags.FLAGS + + +# Support folding two types of batch norm ops: +# BatchNormWithGlobalNormalization and FusedBatchNorm. The two types only +# differ in input order and attribute names, so we've collected their +# differences up front. +INPUT_ORDER = { + # Order of inputs for BatchNormWithGlobalNormalization. + "BatchNormWithGlobalNormalization": [ + "conv_op", + "mean_op", + "var_op", + "beta_op", + "gamma_op", + ], + # Order of inputs for FusedBatchNorm. + "FusedBatchNorm": ["conv_op", "gamma_op", "beta_op", "mean_op", "var_op"], + # Order of inputs for FusedBatchNormV3. + "FusedBatchNormV3": ["conv_op", "gamma_op", "beta_op", "mean_op", "var_op"], +} +# Name of the attribute epsilon value is stored in. +EPSILON_ATTR = { + "BatchNormWithGlobalNormalization": "variance_epsilon", + "FusedBatchNorm": "epsilon", + "FusedBatchNormV3": "epsilon", +} + + +def optimize_for_inference( + input_graph_def: graph_pb2.GraphDef, + input_node_names: Sequence[str], + output_node_names: Sequence[str], + placeholder_type_enum: int, + toco_compatible: bool = False, +) -> graph_pb2.GraphDef: + """Applies a series of inference optimizations on the input graph. + + Args: + input_graph_def: A GraphDef containing a training model. + input_node_names: A list of names of the nodes that are fed inputs during + inference. + output_node_names: A list of names of the nodes that produce the final + results. + placeholder_type_enum: The AttrValue enum for the placeholder data type, or + a list that specifies one value per input node name. + toco_compatible: Boolean, if True, only runs optimizations that result in + TOCO compatible graph operations (default=False). + + Returns: + An optimized version of the input graph. + """ + ensure_graph_is_valid(input_graph_def) + optimized_graph_def = input_graph_def + optimized_graph_def = strip_unused_lib.strip_unused( + optimized_graph_def, + input_node_names, + output_node_names, + placeholder_type_enum, + ) + optimized_graph_def = graph_util.remove_training_nodes( + optimized_graph_def, output_node_names + ) + optimized_graph_def = fold_batch_norms(optimized_graph_def) + if not toco_compatible: + optimized_graph_def = fuse_resize_and_conv( + optimized_graph_def, output_node_names + ) + ensure_graph_is_valid(optimized_graph_def) + return optimized_graph_def + + +def ensure_graph_is_valid(graph_def: graph_pb2.GraphDef) -> None: + """Makes sure that the graph is internally consistent. + + Checks basic properties of the graph def and raises an exception if there are + input references to missing nodes, duplicated names, or other logic errors. + + Args: + graph_def: Definition of a graph to be checked. + + Raises: + ValueError: If the graph is incorrectly constructed. + """ + node_map = {} + for node in graph_def.node: + if node.name not in node_map: + node_map[node.name] = node + else: + raise ValueError("Duplicate node names detected for ", node.name) + for node in graph_def.node: + for input_name in node.input: + input_node_name = node_name_from_input(input_name) + if input_node_name not in node_map: + raise ValueError("Input for ", node.name, " not found: ", input_name) + + +def node_name_from_input(node_name: str) -> str: + """Strips off ports and other decorations to get the underlying node name.""" + if node_name.startswith("^"): + node_name = node_name[1:] + m = re.search(r"(.*):\d+$", node_name) + if m: + node_name = m.group(1) + return node_name + + +def node_from_map( + node_map: Mapping[str, node_def_pb2.NodeDef], name: str +) -> node_def_pb2.NodeDef: + """Pulls a node def from a dictionary for a given name. + + Args: + node_map: Dictionary containing an entry indexed by name for every node. + name: Identifies the node we want to find. + + Returns: + NodeDef of the node with the given name. + + Raises: + ValueError: If the node isn't present in the dictionary. + """ + stripped_name = node_name_from_input(name) + if stripped_name not in node_map: + raise ValueError("No node named '%s' found in map." % name) + return node_map[stripped_name] + + +def values_from_const(node_def: node_def_pb2.NodeDef) -> np.ndarray: + """Extracts the values from a const NodeDef as a numpy ndarray. + + Args: + node_def: Const NodeDef that has the values we want to access. + + Returns: + Numpy ndarray containing the values. + + Raises: + ValueError: If the node isn't a Const. + """ + if node_def.op != "Const": + raise ValueError( + "Can not extract constant value from a node that is not Const. Got:\n" + f"{node_def}" + ) + input_tensor = node_def.attr["value"].tensor + tensor_value = tensor_util.MakeNdarray(input_tensor) + return tensor_value + + +# Whether to scale by gamma after normalization. +def scale_after_normalization(node: node_def_pb2.NodeDef) -> bool: + if node.op == "BatchNormWithGlobalNormalization": + return node.attr["scale_after_normalization"].b + return True + + +def fold_batch_norms(input_graph_def: graph_pb2.GraphDef) -> graph_pb2.GraphDef: + """Removes batch normalization ops by folding them into convolutions. + + Batch normalization during training has multiple dynamic parameters that are + updated, but once the graph is finalized these become constants. That means + there's an opportunity to reduce the computations down to a scale and + addition, rather than the more expensive multiple ops, and even bake the + scaling into the convolution weights. This function identifies the typical + pattern of batch normalization subgraphs, and performs the transformation to + fold the computations down into a simpler form. It currently only supports + batch normalization that's performed by the BatchNormWithGlobalNormalization + FusedBatchNorm and FusedBatchNormV3 ops, and will need to be extended in the + future to handle the newer style. + + Args: + input_graph_def: A GraphDef containing a model. + + Returns: + Modified graph with BN ops removed, and modified weights. + + Raises: + ValueError: If the graph is badly formed with duplicate node names. + """ + input_node_map = {} + for node in input_graph_def.node: + if node.name not in input_node_map: + input_node_map[node.name] = node + else: + raise ValueError("Duplicate node names detected for ", node.name) + + nodes_to_skip = {} + new_ops = [] + for node in input_graph_def.node: + if node.op not in ( + "BatchNormWithGlobalNormalization", + "FusedBatchNorm", + "FusedBatchNormV3", + ): + continue + + bias = None + conv_op = node_from_map( + input_node_map, node.input[INPUT_ORDER[node.op].index("conv_op")] + ) + # There might be an Add/BiasAdd op between the conv and the batchnorm, + # which we can fold into the mean param of the batchnorm. + if conv_op.op in ["BiasAdd", "Add", "AddV2"]: + add_op = conv_op + # Follow the first input of the add to get to the conv. + conv_op = node_from_map(input_node_map, add_op.input[0]) + bias = node_from_map(input_node_map, add_op.input[1]) + if conv_op.op not in ["Conv2D", "DepthwiseConv2dNative"]: + # Follow the second input of the add to get to the conv. + conv_op = node_from_map(input_node_map, add_op.input[1]) + bias = node_from_map(input_node_map, add_op.input[0]) + if bias and bias.op != "Const": + tf_logging.warning( + "The bias %s after the conv %s was not a constant. " + "Maybe because freeze_graph wasn't " + "run first?" % (bias.name, conv_op.name) + ) + continue + if conv_op.op not in ["Conv2D", "DepthwiseConv2dNative"]: + tf_logging.warning( + "Didn't find expected Conv2D or DepthwiseConv2dNative input to '%s'" + % node.name + ) + continue + + weights_op = node_from_map(input_node_map, conv_op.input[1]) + if weights_op.op != "Const": + tf_logging.warning( + "Didn't find expected conv Constant input to '%s'," + " found %s instead. Maybe because freeze_graph wasn't" + " run first?" % (conv_op.name, weights_op) + ) + continue + weights = values_from_const(weights_op) + if conv_op.op == "Conv2D": + channel_count = weights.shape[3] + elif conv_op.op == "DepthwiseConv2dNative": + channel_count = weights.shape[2] * weights.shape[3] + + mean_op = node_from_map( + input_node_map, node.input[INPUT_ORDER[node.op].index("mean_op")] + ) + if mean_op.op != "Const": + tf_logging.warning( + "Didn't find expected mean Constant input to '%s'," + " found %s instead. Maybe because freeze_graph wasn't" + " run first?" % (node.name, mean_op) + ) + continue + mean_value = values_from_const(mean_op) + if mean_value.shape != (channel_count,): + tf_logging.warning( + "Incorrect shape for mean, found %s, expected %s, for node %s" + % (str(mean_value.shape), str((channel_count,)), node.name) + ) + continue + if bias is not None: + # Adjust the mean of the batchnorm based on the add op in-between the conv + # and the batchnorm. + mean_value = mean_value - values_from_const(bias) + + var_op = node_from_map( + input_node_map, node.input[INPUT_ORDER[node.op].index("var_op")] + ) + if var_op.op != "Const": + tf_logging.warning( + "Didn't find expected var Constant input to '%s'," + " found %s instead. Maybe because freeze_graph wasn't" + " run first?" % (node.name, var_op) + ) + continue + var_value = values_from_const(var_op) + if var_value.shape != (channel_count,): + tf_logging.warning( + "Incorrect shape for var, found %s, expected %s, for node %s" + % (str(var_value.shape), str((channel_count,)), node.name) + ) + continue + + beta_op = node_from_map( + input_node_map, node.input[INPUT_ORDER[node.op].index("beta_op")] + ) + if beta_op.op != "Const": + tf_logging.warning( + "Didn't find expected beta Constant input to '%s'," + " found %s instead. Maybe because freeze_graph wasn't" + " run first?" % (node.name, beta_op) + ) + continue + beta_value = values_from_const(beta_op) + if beta_value.shape != (channel_count,): + tf_logging.warning( + "Incorrect shape for beta, found %s, expected %s, for node %s" + % (str(beta_value.shape), str((channel_count,)), node.name) + ) + continue + + gamma_op = node_from_map( + input_node_map, node.input[INPUT_ORDER[node.op].index("gamma_op")] + ) + if gamma_op.op != "Const": + tf_logging.warning( + "Didn't find expected gamma Constant input to '%s'," + " found %s instead. Maybe because freeze_graph wasn't" + " run first?" % (node.name, gamma_op) + ) + continue + gamma_value = values_from_const(gamma_op) + if gamma_value.shape != (channel_count,): + tf_logging.warning( + "Incorrect shape for gamma, found %s, expected %s, for node %s" + % (str(gamma_value.shape), str((channel_count,)), node.name) + ) + continue + + variance_epsilon_value = node.attr[EPSILON_ATTR[node.op]].f + nodes_to_skip[node.name] = True + nodes_to_skip[weights_op.name] = True + nodes_to_skip[conv_op.name] = True + if bias is not None: + nodes_to_skip[add_op.name] = True + + if scale_after_normalization(node): + scale_value = ( + 1.0 / np.vectorize(math.sqrt)(var_value + variance_epsilon_value) + ) * gamma_value + else: + scale_value = 1.0 / np.vectorize(math.sqrt)( + var_value + variance_epsilon_value + ) + offset_value = (-mean_value * scale_value) + beta_value + scaled_weights = np.copy(weights) + it = np.nditer( + scaled_weights, flags=["multi_index"], op_flags=["readwrite"] + ) + if conv_op.op == "Conv2D": + while not it.finished: + current_scale = scale_value[it.multi_index[3]] + it[0] *= current_scale + it.iternext() + elif conv_op.op == "DepthwiseConv2dNative": + channel_multiplier = weights.shape[3] + while not it.finished: + current_scale = scale_value[ + it.multi_index[2] * channel_multiplier + it.multi_index[3] + ] + it[0] *= current_scale + it.iternext() + scaled_weights_op = node_def_pb2.NodeDef() + scaled_weights_op.op = "Const" + scaled_weights_op.name = conv_op.name + "_weights" + scaled_weights_op.attr["dtype"].CopyFrom(weights_op.attr["dtype"]) + scaled_weights_op.attr["value"].CopyFrom( + attr_value_pb2.AttrValue( + tensor=tensor_util.make_tensor_proto( + scaled_weights, weights.dtype.type, weights.shape + ) + ) + ) + # Replace the weights node with scaled weights node + for i, weights_node in enumerate(conv_op.input): + if weights_node == weights_op.name: + conv_op.input[i] = scaled_weights_op.name + + new_conv_op = node_def_pb2.NodeDef() + new_conv_op.CopyFrom(conv_op) + offset_op = node_def_pb2.NodeDef() + offset_op.op = "Const" + offset_op.name = conv_op.name + "_bn_offset" + offset_op.attr["dtype"].CopyFrom(mean_op.attr["dtype"]) + offset_op.attr["value"].CopyFrom( + attr_value_pb2.AttrValue( + tensor=tensor_util.make_tensor_proto( + offset_value, mean_value.dtype.type, offset_value.shape + ) + ) + ) + bias_add_op = node_def_pb2.NodeDef() + bias_add_op.op = "BiasAdd" + bias_add_op.name = node.name + bias_add_op.attr["T"].CopyFrom(conv_op.attr["T"]) + bias_add_op.attr["data_format"].CopyFrom(conv_op.attr["data_format"]) + bias_add_op.input.extend([new_conv_op.name, offset_op.name]) + new_ops.extend([scaled_weights_op, new_conv_op, offset_op, bias_add_op]) + + result_graph_def = graph_pb2.GraphDef() + for node in input_graph_def.node: + if node.name in nodes_to_skip: + continue + new_node = node_def_pb2.NodeDef() + new_node.CopyFrom(node) + retained_input = [] + for input_node in new_node.input: + if not input_node.startswith("^") or input_node[1:] not in nodes_to_skip: + retained_input.append(input_node) + new_node.input[:] = retained_input + + result_graph_def.node.extend([new_node]) + + result_graph_def.node.extend(new_ops) + result_graph_def.versions.CopyFrom(input_graph_def.versions) + return result_graph_def + + +def fuse_resize_and_conv( + input_graph_def: graph_pb2.GraphDef, output_node_names: Sequence[str] +) -> graph_pb2.GraphDef: + """Merges preceding resize and mirror pad ops into a specialized convolution. + + There's a common pattern of enlarging the input to a convolution using a + resize operation, and also using MirrorPad to extend the boundaries to that + zero edge pixels don't bleed inwards when convolving. This routine looks for + that pattern of operations, and fuses them together into a Conv2DWithResizeOp. + + Args: + input_graph_def: A GraphDef containing a model. + output_node_names: A list of names of the nodes that produce the final + results. + + Returns: + Modified graph with resize and pad ops merged. + + Raises: + ValueError: If the graph is badly formed with duplicate node names. + """ + + input_node_map = {} + for node in input_graph_def.node: + if node.name not in input_node_map: + input_node_map[node.name] = node + else: + raise ValueError("Duplicate node names detected for ", node.name) + + node_reference_count = collections.defaultdict(int) + for node in input_graph_def.node: + for input_name in node.input: + stripped_name = node_name_from_input(input_name) + node_reference_count[stripped_name] += 1 + for output_name in output_node_names: + node_reference_count[output_name] += 1 + + new_ops = [] + for node in input_graph_def.node: + if node.op != "Conv2D": + continue + conv_op = node + + input_op = node_from_map(input_node_map, conv_op.input[0]) + if input_op.op == "MirrorPad": + mirror_pad_op = input_op + resize_op = node_from_map(input_node_map, mirror_pad_op.input[0]) + if resize_op.op != "ResizeBilinear": + resize_op = None + else: + mirror_pad_op = None + if input_op.op == "ResizeBilinear": + resize_op = input_op + else: + resize_op = None + + # There are no ops to be fused into the conv, so skip replacing this one. + if not mirror_pad_op and not resize_op: + continue + + # We're replacing this node, so make sure the old one is removed. + node_reference_count[conv_op.name] = 0 + if mirror_pad_op: + node_reference_count[mirror_pad_op.name] -= 1 + if resize_op: + node_reference_count[resize_op.name] -= 1 + + fused_conv_op = node_def_pb2.NodeDef() + if resize_op: + fused_conv_op.op = "FusedResizeAndPadConv2D" + else: + fused_conv_op.op = "FusedPadConv2D" + fused_conv_op.name = conv_op.name + if mirror_pad_op: + mirror_paddings_name = mirror_pad_op.input[1] + mirror_paddings_mode = mirror_pad_op.attr["mode"] + else: + # If there was no MirrorPad op, then create settings that make the padding + # stage of the fused operation a no-op. + paddings_op = node_def_pb2.NodeDef() + paddings_op.op = "Const" + paddings_op.name = conv_op.name + "_dummy_paddings" + paddings_op.attr["dtype"].CopyFrom( + attr_value_pb2.AttrValue(type=dtypes.int32.as_datatype_enum) + ) + paddings_op.attr["value"].CopyFrom( + attr_value_pb2.AttrValue( + tensor=tensor_util.make_tensor_proto( + [0, 0, 0, 0, 0, 0, 0, 0], dtypes.int32, [4, 2] + ) + ) + ) + new_ops.extend([paddings_op]) + mirror_paddings_name = paddings_op.name + mirror_paddings_mode = attr_value_pb2.AttrValue(s=b"REFLECT") + if resize_op: + fused_conv_op.input.extend([ + resize_op.input[0], + resize_op.input[1], + mirror_paddings_name, + conv_op.input[1], + ]) + fused_conv_op.attr["resize_align_corners"].CopyFrom( + resize_op.attr["align_corners"] + ) + else: + fused_conv_op.input.extend( + [mirror_pad_op.input[0], mirror_paddings_name, conv_op.input[1]] + ) + fused_conv_op.attr["T"].CopyFrom(conv_op.attr["T"]) + fused_conv_op.attr["mode"].CopyFrom(mirror_paddings_mode) + fused_conv_op.attr["strides"].CopyFrom(conv_op.attr["strides"]) + fused_conv_op.attr["padding"].CopyFrom(conv_op.attr["padding"]) + new_ops.extend([fused_conv_op]) + + result_graph_def = graph_pb2.GraphDef() + for node in input_graph_def.node: + if node_reference_count[node.name] < 1: + continue + new_node = node_def_pb2.NodeDef() + new_node.CopyFrom(node) + result_graph_def.node.extend([new_node]) + + result_graph_def.node.extend(new_ops) + return result_graph_def diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/print_selective_registration_header.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/print_selective_registration_header.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae04c137e4eb4623ad2e6f0ec29e1e565cfca4b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/print_selective_registration_header.py @@ -0,0 +1,78 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Prints a header file to be used with SELECTIVE_REGISTRATION. + +An example of command-line usage is: + bazel build tensorflow/python/tools:print_selective_registration_header && \ + bazel-bin/tensorflow/python/tools/print_selective_registration_header \ + --graphs=path/to/graph.pb > ops_to_register.h + +Then when compiling tensorflow, include ops_to_register.h in the include search +path and pass -DSELECTIVE_REGISTRATION and -DSUPPORT_SELECTIVE_REGISTRATION + - see core/framework/selective_registration.h for more details. + +When compiling for Android: + bazel build -c opt --copt="-DSELECTIVE_REGISTRATION" \ + --copt="-DSUPPORT_SELECTIVE_REGISTRATION" \ + //tensorflow/tools/android/inference_interface:libtensorflow_inference.so \ + --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \ + --crosstool_top=//external:android/crosstool --cpu=armeabi-v7a +""" + +import argparse +import sys + +from absl import app +from tensorflow.python.tools import selective_registration_header_lib + +FLAGS = None + + +def main(unused_argv): + graphs = FLAGS.graphs.split(',') + print( + selective_registration_header_lib.get_header(graphs, + FLAGS.proto_fileformat, + FLAGS.default_ops)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.register('type', 'bool', lambda v: v.lower() == 'true') + parser.add_argument( + '--graphs', + type=str, + default='', + help='Comma-separated list of paths to model files to be analyzed.', + required=True) + parser.add_argument( + '--proto_fileformat', + type=str, + default='rawproto', + help='Format of proto file, either textproto, rawproto or ops_list. The ' + 'ops_list is the file contains the list of ops in JSON format. Ex: ' + '"[["Add", "BinaryOp>"]]".') + parser.add_argument( + '--default_ops', + type=str, + default='NoOp:NoOp,_Recv:RecvOp,_Send:SendOp', + help='Default operator:kernel pairs to always include implementation for.' + 'Pass "all" to have all operators and kernels included; note that this ' + 'should be used only when it is useful compared with simply not using ' + 'selective registration, as it can in some cases limit the effect of ' + 'compilation caches') + + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_aot_compile.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_aot_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..099bc0795a256d7d40a2fa2b25c46d14f33987e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_aot_compile.py @@ -0,0 +1,524 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Helper utilities for AOT compilation.""" + +import collections +import copy +import os +import re +import shlex +from typing import List, Tuple + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.python.client import session +from tensorflow.python.framework import convert_to_constants +from tensorflow.python.framework import ops as ops_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import versions +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import sysconfig as sysconfig_lib +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import saver as saver_lib + +try: + from tensorflow.python import _pywrap_tfcompile # pylint: disable=g-import-not-at-top +except ImportError as e: + _pywrap_tfcompile_import_error = ImportError( + 'Unable to import _pywrap_tfcompile; you must build TensorFlow ' + 'with XLA. You may need to build tensorflow with flag ' + '--define=with_xla_support=true. Original error: {}'.format(str(e))) +else: + _pywrap_tfcompile_import_error = None + + +_READ_ONLY_VARIABLE_OPS = ( + 'ReadVariableOp', + 'IsVariableInitializedOp', + 'ResourceGather', + 'ResourceGatherNd', + 'VariableShape', +) + +_PASS_THROUGH_VARIABLE_OPS = ('Identity', 'IdentityN') + + +def _shlex_quote(s): + return shlex.quote(s) + + +def _sysconfig_module(): + """Load tf.sysconfig if available and working (i.e., inside a pip package).""" + try: + _ = sysconfig_lib.get_include() + except (ImportError, ValueError): + # ValueError may come from saved_model_cli_test trying to enable + # eager mode twice. + return None + return sysconfig_lib + + +def _parse_tensor_name(name): + """Convert a tensor name like 'tensor:0' into a tuple ('tensor', 0).""" + if ':' in name and not name.endswith(':'): + node_name = name[:name.rfind(':')] + output_slot = int(name[name.rfind(':') + 1:]) + return node_name, output_slot + else: + return name, None + + +_XLA_MAKEFILE_TEMPLATE = """ +INC = -I{tensorflow_includes} +LIB = -L{compiled_dir} +CXXFLAGS = {cxx_flags} +""" + + +def _xla_makefile_string(output_prefix): + """Returns a Makefile string with variables for using XLA binary object files. + + Attempts to identify the right include header paths when run from either + an installed TensorFlow pip package, or from bazel run. + + Args: + output_prefix: A string containing the output prefix for the XLA AOT + compiled header + object files. + + Returns: + A string containing a filled out `_XLA_MAKEFILE_TEMPLATE`. + """ + sysconfig = _sysconfig_module() + output_dir, _ = os.path.split(output_prefix) + if sysconfig: + tensorflow_includes = _shlex_quote(sysconfig.get_include()) + else: + # Try hard to find the real source directory if this is a local bazel run. + if os.path.islink(__file__): + this_file = __file__ + while os.path.islink(this_file): + this_file = os.readlink(this_file) + base = os.path.realpath( + os.path.join(os.path.dirname(this_file), *([os.path.pardir] * 3))) + else: + try: + base = test.test_src_dir_path('') + except KeyError: # Can't find TEST_SRCDIR in environment path. + base = os.path.realpath( + os.path.join(os.path.dirname(__file__), *([os.path.pardir] * 3))) + expected_header = os.path.join( + base, 'tensorflow', 'compiler', 'tf2xla', 'xla_compiled_cpu_function.h') + if not os.path.exists(expected_header): + logging.error( + 'Could not find includes path. Missing file: {}' + .format(expected_header)) + tensorflow_includes = base + + return _XLA_MAKEFILE_TEMPLATE.format( + tensorflow_includes=tensorflow_includes, + compiled_dir=_shlex_quote(output_dir), + cxx_flags='-D_GLIBCXX_USE_CXX11_ABI={}'.format( + versions.CXX11_ABI_FLAG)) + + +def _get_variable_nodes_from_graph_def(graph_def): + """Get the list of Variable nodes from `graph_def`. + + Args: + graph_def: An instance of `GraphDef`. This GraphDef *must* + have already been optimized by Grappler. In particular, function + inlining must have already happened. + + Returns: + A dict mapping string names of variables to tuples `(node_def, modified)`, + where `node_def` is the `NodeDef` corresponding to variable, and `modified` + is a python bool describing whether the variable is modified during runtime. + """ + variables = [n for n in graph_def.node if n.op == 'VarHandleOp'] + variable_name_map = dict((n.name, n) for n in variables) + child_map = collections.defaultdict(lambda: []) + for n in graph_def.node: + for inp in n.input: + if not inp.startswith('^'): + child_map[inp].append(n) + variables = {} + for (v_name, v_node) in variable_name_map.items(): + queue = list(child_map[v_name]) + processed = set([]) + while queue: + n_current = queue.pop() + if n_current.name in processed: + continue + processed.add(n_current.name) + if n_current.op in _PASS_THROUGH_VARIABLE_OPS: + children = child_map.get(n_current.name, []) + queue.extend(children) + elif n_current.op not in _READ_ONLY_VARIABLE_OPS: + variables[v_name] = (v_node, True) + queue = [] + if v_name not in variables: + variables[v_name] = (v_node, False) + + return variables + + +def _prune_removed_feed_nodes(signature_def, graph_def): + """Identify the inputs in the signature no longer in graph_def, prune them. + + Args: + signature_def: A `SignatureDef` instance. + graph_def: A `GraphDef` instance. + + Returns: + A new pruned `SignatureDef`. + """ + node_names = set([n.name for n in graph_def.node]) + new_signature_def = meta_graph_pb2.SignatureDef() + new_signature_def.CopyFrom(signature_def) + for (k, v) in signature_def.inputs.items(): + tensor_name, _ = _parse_tensor_name(v.name) + if tensor_name not in node_names: + logging.warn( + 'Signature input key \'{}\', tensor name \'{}\', has been pruned ' + 'while freezing the graph. Removing it from the compiled signatures.' + .format(k, tensor_name)) + del new_signature_def.inputs[k] + return new_signature_def + + +def freeze_model(checkpoint_path: str, + meta_graph_def: meta_graph_pb2.MetaGraphDef, + output_prefix: str, signature_def_key: str, + variables_to_feed: List[str]) -> Tuple[str, str]: + """Freeze a `MetaGraphDef` in preparation for tfcompile`. + + The graph is always optimized with grappler, and optionally (by default) + variables are frozen as constants, before compilation happens. + + Args: + checkpoint_path: Python string. Path to checkpoints/variables. + meta_graph_def: Instance of `MetaGraphDef`. + output_prefix: Python string. Path prefix for outputs. + signature_def_key: String, the signature_def to use in the SavedModel. + variables_to_feed: A list of strings, the variables that will be fed by the + user; these won't be frozen. If `None`, then we will extract all the + variables in the graph and mark them as to-feed. The default behavior is + an empty tuple: all variables must be frozen. + Returns: + a pair containing the path to the frozen model and the path to the config. + Raises: + RuntimeError: If tensorflow was not built with XLA. + ImportError: If tensorflow was built with XLA but there was another + issue importing the tfcompile python wrapper. + ValueError: If `meta_graph_def.signature_def[signature_def_key]` is + missing or has empty outputs. + """ + if _pywrap_tfcompile_import_error: + raise _pywrap_tfcompile_import_error # pylint: disable=raising-bad-type + + signature_def_map = meta_graph_def.signature_def + if signature_def_key not in signature_def_map: + raise ValueError( + f"Unable to find signature_def_key '{signature_def_key}' in signature " + 'def map of `meta_graph_def`. Available keys: ' + f'{list(signature_def_map.keys())}') + signature_def = signature_def_map[signature_def_key] + if not signature_def.outputs: + raise ValueError( + f'Signature key {signature_def_key} must have outputs, but saw none:\n' + f'{str(signature_def)}') + + file_io.recursive_create_dir(output_prefix) + if logging.get_verbosity() >= logging.INFO: + original_graph_def_location = os.path.join(output_prefix, + 'original_graph.pb') + with file_io.FileIO(original_graph_def_location, 'wb') as graph_writer: + graph_writer.write(meta_graph_def.graph_def.SerializeToString()) + + # This updates graph_def in place. + _replace_input_placeholders_with_default_values( + meta_graph_def.graph_def, signature_def) + + graph_def = _optimize_graph(meta_graph_def, signature_def) + + all_variables = _get_variable_nodes_from_graph_def(graph_def) + if variables_to_feed is None: + variable_nodes_to_feed = list(all_variables.values()) + else: + not_in_graph = set(variables_to_feed).difference(list(all_variables)) + if not_in_graph: + raise ValueError('Asked to feed variables that were not found in graph: ' + f'{not_in_graph}. Variables contained in the graph: ' + f'{list(all_variables)}') + variable_nodes_to_feed = [ + all_variables[name] for name in variables_to_feed + ] + + if logging.get_verbosity() >= logging.INFO: + prefrozen_graph_def_location = os.path.join(output_prefix, + 'prefrozen_graph.pb') + with file_io.FileIO(prefrozen_graph_def_location, 'wb') as graph_writer: + graph_writer.write(graph_def.SerializeToString()) + + # Load the Variables so that we can freeze the graph. + with session.Session(graph=ops_lib.Graph()) as sess: + restorer = saver_lib.import_meta_graph(meta_graph_def, clear_devices=True) + if restorer is not None: + restorer.restore(sess, checkpoint_path) + graph_def.CopyFrom( + convert_to_constants.convert_variables_to_constants( + sess, + graph_def, + output_node_names=[ + _parse_tensor_name(n.name)[0] + for n in signature_def.outputs.values() + ], + variable_names_blacklist=[ + n.name for n, _ in variable_nodes_to_feed + ], + )) + + signature_def = _prune_removed_feed_nodes(signature_def, graph_def) + + frozen_graph_def_location = os.path.join(output_prefix, 'frozen_graph.pb') + config_pbtxt_location = os.path.join(output_prefix, 'config.pbtxt') + logging.info('Writing graph def to: {}'.format(frozen_graph_def_location)) + with file_io.FileIO(frozen_graph_def_location, 'wb') as graph_writer: + graph_writer.write(graph_def.SerializeToString()) + config = _signature_to_tf2xla_config( + signature_def, variable_nodes_to_feed=variable_nodes_to_feed) + logging.info('Writing config_pbtxt to: {}'.format(config_pbtxt_location)) + with file_io.FileIO(config_pbtxt_location, mode='w') as config_writer: + config_writer.write(str(config)) + return frozen_graph_def_location, config_pbtxt_location + + +def aot_compile_cpu_meta_graph_def(checkpoint_path, + meta_graph_def, + output_prefix, + signature_def_key, + cpp_class, + target_triple, + target_cpu, + variables_to_feed=(), + multithreading=False): + """Compile a `MetaGraphDef` to header+object files in `output_prefix`. + + Use XLA AOT (`tfcompile`) to convert the given meta graph and + signature into a header + object files. Also create an include makefile + that helps identify the appropriate necessary include and library paths + to incorporate these files into your C++ program. + + Freezing a graph entails restoring the checkpoint and replacing any inputs and + variables with constants. If values are feed, those are used, else inputs are + replaced with default all-zero constants. Finally, the graph is pruned and + then optimized with grappler. + + If the `freeze_graph` is `True`, all variables are embedded as constants + into the graph and binary objects. If it is `False`, then the variable + values become inputs and outputs of the compiled class and the C++ + caller must set these values manually. + + Args: + checkpoint_path: Python string. Path to checkpoints/variables. + meta_graph_def: Instance of `MetaGraphDef`. + output_prefix: Python string. Path prefix for outputs. + signature_def_key: String, the signature_def to use in the SavedModel. + cpp_class: String, Name of output C++ class. + target_triple: String, LLVM target triple. + target_cpu: String, LLVM target cpu name. + variables_to_feed: A list of strings, the variables that will be fed by the + user; these won't be frozen. If `None`, then we will extract all the + variables in the graph and mark them as to-feed. The default behavior is + an empty tuple: all variables must be frozen. + multithreading: Whether to enable multithreading in the compiled + computation. Note that if using this option, the resulting object files + may have external dependencies on multithreading libraries like nsync. + + Raises: + RuntimeError: If tensorflow was not built with XLA. + ImportError: If tensorflow was built with XLA but there was another + issue importing the tfcompile python wrapper. + ValueError: If `meta_graph_def.signature_def[signature_def_key]` is + missing or has empty outputs. + """ + if _pywrap_tfcompile_import_error: + raise _pywrap_tfcompile_import_error # pylint: disable=raising-bad-type + + else: + # TODO(ebrevdo): Pipe DebugOptions through tfcompile::Main and pywrap + # so that we can set these directly instead of relying on env vars. + xla_flags = os.environ.get('XLA_FLAGS') + if not xla_flags: + xla_flags = '--xla_cpu_multi_thread_eigen={}'.format( + 'true' if multithreading else 'false') + else: + xla_flags += ' --xla_cpu_multi_thread_eigen={}'.format( + 'true' if multithreading else 'false') + os.environ['XLA_FLAGS'] = xla_flags + + temp_dir = test.get_temp_dir() + file_io.recursive_create_dir(temp_dir) + frozen_graph_def_location, config_pbtxt_location = freeze_model( + checkpoint_path=checkpoint_path, + meta_graph_def=meta_graph_def, + output_prefix=temp_dir, + signature_def_key=signature_def_key, + variables_to_feed=variables_to_feed) + output_dir = os.path.dirname(output_prefix) + file_io.recursive_create_dir(output_dir) + + entry_point = re.sub( + '[^0-9a-zA-Z]+', '_', + '__xla_' + output_prefix + '__' + cpp_class) + + logging.info('Generating XLA AOT artifacts in: {}'.format(output_dir)) + + makefile_inc_location = '{}_makefile.inc'.format(output_prefix) + with file_io.FileIO(makefile_inc_location, mode='w') as makefile_writer: + makefile_writer.write(_xla_makefile_string(output_prefix)) + + output_prefix = _shlex_quote(output_prefix) + + _pywrap_tfcompile.Compile( + graph=frozen_graph_def_location, + config=config_pbtxt_location, + cpp_class=cpp_class, + target_triple=target_triple, + target_cpu=target_cpu, + entry_point=entry_point, + out_function_object='{}.o'.format(output_prefix), + out_header='{}.h'.format(output_prefix), + out_metadata_object='{}_metadata.o'.format(output_prefix), + gen_name_to_index=True, + # ProgramShape isn't uniquefied by entry_point. + gen_program_shape=False) + + +def _optimize_graph(meta_graph_def, signature_def): + """Optimize `meta_graph_def` using grappler. Returns a `GraphDef`.""" + # We need to add a collection called 'train_op' so that grappler + # knows what the outputs are. + new_meta_graph_def = copy.deepcopy(meta_graph_def) + fetch_collection = meta_graph_pb2.CollectionDef() + for tensor_info in ( + list(signature_def.inputs.values()) + + list(signature_def.outputs.values())): + fetch_collection.node_list.value.append(tensor_info.name) + + new_meta_graph_def.collection_def['train_op'].CopyFrom(fetch_collection) + # We freeze the graph, so consider all variables to be readonly. + new_meta_graph_def.ClearField('saver_def') + config = config_pb2.ConfigProto() + rewrite_options = config.graph_options.rewrite_options + rewrite_options.min_graph_nodes = -1 # do not skip small graphs + return tf_optimizer.OptimizeGraph(config, new_meta_graph_def) + + +def _replace_input_placeholders_with_default_values(graph_def, signature_def): + """Replace graphdef's `tf.placeholder` input ops with all-zero constants.""" + name_to_node_map = dict((n.name, n) for n in graph_def.node) + processed_nodes = set([]) + for name, input_ in signature_def.inputs.items(): + tensor_name, _ = _parse_tensor_name(input_.name) + if tensor_name in processed_nodes: + continue + processed_nodes.add(tensor_name) + if tensor_name not in name_to_node_map: + raise RuntimeError( + f"Unable to find input signature tensor '{tensor_name}' in optimized " + f'GraphDef. Graph nodes are: {list(name_to_node_map.keys())}') + node = name_to_node_map[tensor_name] + if node.op not in ('Placeholder', 'PlaceholderV2'): + logging.info( + 'Tried to convert SavedModel input node \'{}\' from a placeholder, ' + 'but it doesn\'t look like a placeholder: {}'.format(tensor_name, + node)) + continue + shape = tensor_shape.TensorShape(input_.tensor_shape) + if not shape.is_fully_defined(): + raise ValueError( + f"Expected fully defined input shape for signature_def '{name}', " + f"tensor name: '{tensor_name}'; but shape is: {shape}.") + temp_graph = ops_lib.Graph() + with temp_graph.as_default(): + const = array_ops.zeros( + shape, dtype=input_.dtype, name=tensor_name) + node.CopyFrom(const.op.node_def) + # Sometimes zeros() also creates additional nodes + for op in temp_graph.get_operations(): + if op.name == const.op.name: # We just inserted this one. + continue + graph_def.node.append(op.node_def) + name_to_node_map[op.node_def.name] = op.node_def + + +def _signature_to_tf2xla_config(signature_def, variable_nodes_to_feed): + """Convert `signature_def` to tf2xla config. Returns a `tf2xla.Config` proto. + + Args: + signature_def: Instance of `SignatureDef`. + variable_nodes_to_feed: List of tuples of form `(node_def, modified)` + corresponding to VarHandleOp, and a boolean `modified` that describes + whether the variable was modified during execution. + + Returns: + An instance of `tf2xla.Config` proto. + + Raises: + RuntimeError: If TensorFlow was not compiled with XLA. + """ + from tensorflow.compiler.tf2xla import tf2xla_pb2 # pylint: disable=g-import-not-at-top + + config = tf2xla_pb2.Config() + tensor_id = tf2xla_pb2.TensorId + + for name, input_ in signature_def.inputs.items(): + name = name.replace('/', '_') + name = 'feed_{}'.format(name) + (node_name, output_index) = _parse_tensor_name(input_.name) + output_index = int(output_index) + config.feed.append( + tf2xla_pb2.Feed( + id=tensor_id(node_name=node_name, output_index=output_index), + name=name, + type=input_.dtype, + shape=input_.tensor_shape)) + for name, output_ in signature_def.outputs.items(): + name = name.replace('/', '_') + name = 'fetch_{}'.format(name) + (node_name, output_index) = _parse_tensor_name(output_.name) + output_index = int(output_index) + config.fetch.append( + tf2xla_pb2.Fetch( + id=tensor_id(node_name=node_name, output_index=output_index), + name=name, + type=output_.dtype, + shape=output_.tensor_shape)) + for (node, modified) in variable_nodes_to_feed: + name = node.name.replace('/', '_') + name = 'param_{}'.format(name) + config.variable.append( + tf2xla_pb2.Variable( + node_name=node.name, + name=name, + type=node.attr['dtype'].type, + shape=node.attr['shape'].shape, + readonly=not modified)) + + return config diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_cli.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..79267431642109a16ccb110c5b5327ed85cf2c99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_cli.py @@ -0,0 +1,1333 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Command-line interface to inspect and execute a graph in a SavedModel. + +For detailed usages and examples, please refer to: +https://www.tensorflow.org/guide/saved_model#cli_to_inspect_and_execute_savedmodel + +""" + +import argparse +import platform + +import ast +import os +import re + +from absl import app # pylint: disable=unused-import +from absl import flags +from absl.flags import argparse_flags +import numpy as np + +from tensorflow.core.example import example_pb2 +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session +from tensorflow.python.debug.wrappers import local_cli_wrapper +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as defun +from tensorflow.python.framework import meta_graph as meta_graph_lib +from tensorflow.python.framework import ops as ops_lib +from tensorflow.python.framework import tensor_spec +from tensorflow.python.lib.io import file_io +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import load +from tensorflow.python.saved_model import loader +from tensorflow.python.saved_model import save +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.tools import saved_model_aot_compile +from tensorflow.python.tools import saved_model_utils +from tensorflow.python.tpu import tpu +from tensorflow.python.util.compat import collections_abc + + +_XLA_DEBUG_OPTIONS_URL = ( + 'https://github.com/tensorflow/tensorflow/blob/master/' + 'tensorflow/compiler/xla/debug_options_flags.cc') + + +# Set of ops to denylist. +_OP_DENYLIST = set(['WriteFile', 'ReadFile', 'PrintV2']) + + +# Custom SavedModel CLI flags +_SMCLI_DIR = flags.DEFINE_string( + name='dir', default=None, help='Directory containing the SavedModel.') + +_SMCLI_ALL = flags.DEFINE_bool( + name='all', default=False, + help='If set, outputs all available information in the given SavedModel.') + +_SMCLI_TAG_SET = flags.DEFINE_string( + name='tag_set', default=None, + help='Comma-separated set of tags that identify variant graphs in the ' + 'SavedModel.') + +_SMCLI_SIGNATURE_DEF = flags.DEFINE_string( + name='signature_def', default=None, + help='Specifies a SignatureDef (by key) within the SavedModel to display ' + 'input(s) and output(s) for.') + +_SMCLI_LIST_OPS = flags.DEFINE_bool( + name='list_ops', default=False, + help='If set, will output ops used by a MetaGraphDef specified by tag_set.') + +_SMCLI_INPUTS = flags.DEFINE_string( + name='inputs', default='', + help='Specifies input data files to pass to numpy.load(). Format should be ' + '\'=\' or \'=[]\',' + ' separated by \';\'. File formats are limited to .npy, .npz, or pickle.') + +_SMCLI_INPUT_EXPRS = flags.DEFINE_string( + name='input_exprs', default='', + help='Specifies Python literal expressions or numpy functions. Format ' + 'should be "=\'\'", separated by \';\'. Numpy' + ' can be accessed with \'np\'. Note that expressions are passed to ' + 'literal_eval(), making this flag susceptible to code injection. Overrides ' + 'duplicate input keys provided with the --inputs flag.') + +_SMCLI_INPUT_EXAMPLES = flags.DEFINE_string( + name='input_examples', default='', + help='Specifies tf.train.Example objects as inputs. Format should be ' + '\'=[{{feature0:value_list,feature1:value_list}}]\', where input' + ' keys are separated by \';\'. Overrides duplicate input keys provided with' + ' the --inputs and --input_exprs flags.') + +_SMCLI_OUTDIR = flags.DEFINE_string( + name='outdir', default=None, + help='If specified, writes CLI output to the given directory.') + +_SMCLI_OVERWRITE = flags.DEFINE_bool( + name='overwrite', default=False, + help='If set, overwrites output file if it already exists.') + +_SMCLI_TF_DEBUG = flags.DEFINE_bool( + name='tf_debug', default=False, + help='If set, uses the Tensorflow Debugger (tfdbg) to watch intermediate ' + 'Tensors and runtime GraphDefs while running the SavedModel.') + +_SMCLI_WORKER = flags.DEFINE_string( + name='worker', default=None, + help='If specified, runs the session on the given worker (bns or gRPC ' + 'path).') + +_SMCLI_INIT_TPU = flags.DEFINE_bool( + name='init_tpu', default=False, + help='If set, calls tpu.initialize_system() on the session. ' + 'Should only be set if the specified worker is a TPU job.') + +_SMCLI_USE_TFRT = flags.DEFINE_bool( + name='use_tfrt', default=False, + help='If set, runs a TFRT session, instead of a TF1 session.') + +_SMCLI_OP_DENYLIST = flags.DEFINE_string( + name='op_denylist', default=None, + help='If specified, detects and reports the given ops. List of ops should ' + 'be comma-separated. If not specified, the default list of ops is ' + '[WriteFile, ReadFile, PrintV2]. To specify an empty list, pass in the ' + 'empty string.') + +_SMCLI_OUTPUT_DIR = flags.DEFINE_string( + name='output_dir', default=None, + help='Output directory for the SavedModel.') + +_SMCLI_MAX_WORKSPACE_SIZE_BYTES = flags.DEFINE_integer( + name='max_workspace_size_bytes', default=2 << 20, + help='The maximum temporary GPU memory which the TensorRT engine can use at' + ' execution time.') + +_SMCLI_PRECISION_MODE = flags.DEFINE_enum( + name='precision_mode', default='FP32', enum_values=['FP32', 'FP16', 'INT8'], + help='TensorRT data precision. One of FP32, FP16, or INT8.') + +_SMCLI_MINIMUM_SEGMENT_SIZE = flags.DEFINE_integer( + name='minimum_segment_size', default=3, + help='The minimum number of nodes required for a subgraph to be replaced in' + ' a TensorRT node.') + +_SMCLI_CONVERT_TF1_MODEL = flags.DEFINE_bool( + name='convert_tf1_model', default=False, + help='Support TensorRT conversion for TF1 models.') + +_SMCLI_OUTPUT_PREFIX = flags.DEFINE_string( + name='output_prefix', default=None, + help='Output directory + filename prefix for the resulting header(s) and ' + 'object file(s).') + +_SMCLI_SIGNATURE_DEF_KEY = flags.DEFINE_string( + name='signature_def_key', + default=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, + help='SavedModel SignatureDef key to use.') + +_SMCLI_CHECKPOINT_PATH = flags.DEFINE_string( + name='checkpoint_path', default=None, + help='Custom checkpoint to use. Uses SavedModel variables by default.') + +_SMCLI_VARIABLES_TO_FEED = flags.DEFINE_string( + name='variables_to_feed', default='', + help='Names of the variables that will be fed into the SavedModel graph. ' + 'Pass in \'\' to feed no variables, \'all\' to feed all variables, or a ' + 'comma-separated list of variable names. Variables not fed will be frozen. ' + '*NOTE* Variables passed here must be set *by the user*. These variables ' + 'will NOT be frozen, and their values will be uninitialized in the compiled' + ' object.') + +if platform.machine() == 's390x': + _SMCLI_TARGET_TRIPLE = flags.DEFINE_string( + name='target_triple', + default='', + help=( + 'Triple identifying a target variation, containing information suchas' + ' processor architecture, vendor, operating system, and environment.' + " Defaults to ''." + ), + ) +else: + _SMCLI_TARGET_TRIPLE = flags.DEFINE_string( + name='target_triple', + default='x86_64-pc-linux', + help=( + 'Triple identifying a target variation, containing information such' + ' as processor architecture, vendor, operating system, and' + " environment. Defaults to 'x86_64-pc-linux'." + ), + ) + +_SMCLI_TARGET_CPU = flags.DEFINE_string( + name='target_cpu', default='', + help='Target CPU name for LLVM during AOT compilation. Examples include ' + '\'x86_64\', \'skylake\', \'haswell\', \'westmere\', \'\' (unknown).') + +_SMCLI_CPP_CLASS = flags.DEFINE_string( + name='cpp_class', default=None, + help='The name of the generated C++ class, wrapping the generated function.' + ' Format should be [[::],...], i.e. the ' + 'same syntax as C++ for specifying a class. This class will be generated in' + ' the given namespace(s), or, if none are specified, the global namespace.') + +_SMCLI_MULTITHREADING = flags.DEFINE_string( + name='multithreading', default='False', + help='Enable multithreading in the compiled computation. Note that with ' + 'this flag enabled, the resulting object files may have external ' + 'dependencies on multithreading libraries, such as \'nsync\'.') + +command_required_flags = { + 'show': ['dir'], + 'run': ['dir', 'tag_set', 'signature_def'], + 'scan': ['dir'], + 'convert': ['dir', 'output_dir', 'tag_set'], + 'freeze_model': ['dir', 'output_prefix', 'tag_set'], + 'aot_compile_cpu': ['cpp_class'], +} + + +def _show_tag_sets(saved_model_dir): + """Prints the tag-sets stored in SavedModel directory. + + Prints all the tag-sets for MetaGraphs stored in SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + """ + tag_sets = saved_model_utils.get_saved_model_tag_sets(saved_model_dir) + print('The given SavedModel contains the following tag-sets:') + for tag_set in sorted(tag_sets): + print('%r' % ', '.join(sorted(tag_set))) + + +def _get_ops_in_metagraph(meta_graph_def): + """Returns a set of the ops in the MetaGraph. + + Returns the set of all the ops used in the MetaGraphDef indicated by the + tag_set stored in SavedModel directory. + + Args: + meta_graph_def: MetaGraphDef to list the ops of. + + Returns: + A set of ops. + """ + return set(meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def)) + + +def _show_ops_in_metagraph_mgd(meta_graph_def): + all_ops_set = _get_ops_in_metagraph(meta_graph_def) + print( + 'The MetaGraph with tag set %s contains the following ops:' + % meta_graph_def.meta_info_def.tags, + all_ops_set, + ) + + +def _show_ops_in_metagraph(saved_model_dir, tag_set): + """Prints the ops in the MetaGraph. + + Prints all the ops used in the MetaGraphDef indicated by the tag_set stored in + SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + tag_set: Group of tag(s) of the MetaGraphDef in string format, separated by + ','. For tag-set contains multiple tags, all tags must be passed in. + """ + meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, + tag_set) + _show_ops_in_metagraph_mgd(meta_graph_def) + + +def _show_signature_def_map_keys(saved_model_dir, tag_set): + """Prints the keys for each SignatureDef in the SignatureDef map. + + Prints the list of SignatureDef keys from the SignatureDef map specified by + the given tag-set and SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + tag_set: Group of tag(s) of the MetaGraphDef to get SignatureDef map from, + in string format, separated by ','. For tag-set contains multiple tags, + all tags must be passed in. + """ + signature_def_map = get_signature_def_map(saved_model_dir, tag_set) + print('The given SavedModel MetaGraphDef contains SignatureDefs with the ' + 'following keys:') + for signature_def_key in sorted(signature_def_map.keys()): + print('SignatureDef key: \"%s\"' % signature_def_key) + + +def _get_inputs_tensor_info_from_meta_graph_def(meta_graph_def, + signature_def_key): + """Gets TensorInfo for all inputs of the SignatureDef. + + Returns a dictionary that maps each input key to its TensorInfo for the given + signature_def_key in the meta_graph_def + + Args: + meta_graph_def: MetaGraphDef protocol buffer with the SignatureDef map to + look up SignatureDef key. + signature_def_key: A SignatureDef key string. + + Returns: + A dictionary that maps input tensor keys to TensorInfos. + + Raises: + ValueError if `signature_def_key` is not found in the MetaGraphDef. + """ + if signature_def_key not in meta_graph_def.signature_def: + raise ValueError( + f'Could not find signature "{signature_def_key}". Please choose from: ' + f'{", ".join(meta_graph_def.signature_def.keys())}') + return meta_graph_def.signature_def[signature_def_key].inputs + + +def _get_outputs_tensor_info_from_meta_graph_def(meta_graph_def, + signature_def_key): + """Gets TensorInfos for all outputs of the SignatureDef. + + Returns a dictionary that maps each output key to its TensorInfo for the given + signature_def_key in the meta_graph_def. + + Args: + meta_graph_def: MetaGraphDef protocol buffer with the SignatureDefmap to + look up signature_def_key. + signature_def_key: A SignatureDef key string. + + Returns: + A dictionary that maps output tensor keys to TensorInfos. + """ + return meta_graph_def.signature_def[signature_def_key].outputs + + +def _show_inputs_outputs_mgd(meta_graph_def, signature_def_key, indent): + """Prints input and output TensorInfos. + + Prints the details of input and output TensorInfos for the SignatureDef mapped + by the given signature_def_key. + + Args: + meta_graph_def: MetaGraphDef to inspect. + signature_def_key: A SignatureDef key string. + indent: How far (in increments of 2 spaces) to indent each line of output. + """ + inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( + meta_graph_def, signature_def_key + ) + outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( + meta_graph_def, signature_def_key) + + indent_str = ' ' * indent + def in_print(s): + print(indent_str + s) + + in_print('The given SavedModel SignatureDef contains the following input(s):') + for input_key, input_tensor in sorted(inputs_tensor_info.items()): + in_print(' inputs[\'%s\'] tensor_info:' % input_key) + _print_tensor_info(input_tensor, indent+1) + + in_print('The given SavedModel SignatureDef contains the following ' + 'output(s):') + for output_key, output_tensor in sorted(outputs_tensor_info.items()): + in_print(' outputs[\'%s\'] tensor_info:' % output_key) + _print_tensor_info(output_tensor, indent+1) + + in_print('Method name is: %s' % + meta_graph_def.signature_def[signature_def_key].method_name) + + +def _show_inputs_outputs(saved_model_dir, tag_set, signature_def_key, indent=0): + """Prints input and output TensorInfos. + + Prints the details of input and output TensorInfos for the SignatureDef mapped + by the given signature_def_key. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + tag_set: Group of tag(s) of the MetaGraphDef, in string format, separated by + ','. For tag-set contains multiple tags, all tags must be passed in. + signature_def_key: A SignatureDef key string. + indent: How far (in increments of 2 spaces) to indent each line of output. + """ + meta_graph_def = saved_model_utils.get_meta_graph_def( + saved_model_dir, tag_set + ) + _show_inputs_outputs_mgd(meta_graph_def, signature_def_key, indent) + + +def _show_defined_functions(saved_model_dir, meta_graphs): + """Prints the callable concrete and polymorphic functions of the Saved Model. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + meta_graphs: Already-extracted MetaGraphDef of the SavedModel. + """ + has_object_graph_def = False + + for meta_graph_def in meta_graphs: + has_object_graph_def |= meta_graph_def.HasField('object_graph_def') + if not has_object_graph_def: + return + with ops_lib.Graph().as_default(): + trackable_object = load.load(saved_model_dir) + + print('\nConcrete Functions:', end='') + children = list( + save._AugmentedGraphView(trackable_object) # pylint: disable=protected-access + .list_children(trackable_object)) + children = sorted(children, key=lambda x: x.name) + for name, child in children: + concrete_functions = [] + if isinstance(child, defun.ConcreteFunction): + concrete_functions.append(child) + elif isinstance(child, def_function.Function): + concrete_functions.extend( + child._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access + else: + continue + print('\n Function Name: \'%s\'' % name) + concrete_functions = sorted(concrete_functions, key=lambda x: x.name) + for index, concrete_function in enumerate(concrete_functions, 1): + args, kwargs = None, None + if concrete_function.structured_input_signature: + args, kwargs = concrete_function.structured_input_signature + elif concrete_function._arg_keywords: # pylint: disable=protected-access + # For pure ConcreteFunctions we might have nothing better than + # _arg_keywords. + args = concrete_function._arg_keywords # pylint: disable=protected-access + if args: + print(' Option #%d' % index) + print(' Callable with:') + _print_args(args, indent=4) + if kwargs: + _print_args(kwargs, 'Named Argument', indent=4) + + +def _print_args(arguments, argument_type='Argument', indent=0): + """Formats and prints the argument of the concrete functions defined in the model. + + Args: + arguments: Arguments to format print. + argument_type: Type of arguments. + indent: How far (in increments of 2 spaces) to indent each line of + output. + """ + indent_str = ' ' * indent + + def _maybe_add_quotes(value): + is_quotes = '\'' * isinstance(value, str) + return is_quotes + str(value) + is_quotes + + def in_print(s, end='\n'): + print(indent_str + s, end=end) + + for index, element in enumerate(arguments, 1): + if indent == 4: + in_print('%s #%d' % (argument_type, index)) + if isinstance(element, str): + in_print(' %s' % element) + elif isinstance(element, tensor_spec.TensorSpec): + print((indent + 1) * ' ' + '%s: %s' % (element.name, repr(element))) + elif (isinstance(element, collections_abc.Iterable) and + not isinstance(element, dict)): + in_print(' DType: %s' % type(element).__name__) + in_print(' Value: [', end='') + for value in element: + print('%s' % _maybe_add_quotes(value), end=', ') + print('\b\b]') + elif isinstance(element, dict): + in_print(' DType: %s' % type(element).__name__) + in_print(' Value: {', end='') + for (key, value) in element.items(): + print('\'%s\': %s' % (str(key), _maybe_add_quotes(value)), end=', ') + print('\b\b}') + else: + in_print(' DType: %s' % type(element).__name__) + in_print(' Value: %s' % str(element)) + + +def _print_tensor_info(tensor_info, indent=0): + """Prints details of the given tensor_info. + + Args: + tensor_info: TensorInfo object to be printed. + indent: How far (in increments of 2 spaces) to indent each line output + """ + indent_str = ' ' * indent + def in_print(s): + print(indent_str + s) + + in_print(' dtype: ' + + {value: key + for (key, value) in types_pb2.DataType.items()}[tensor_info.dtype]) + # Display shape as tuple. + if tensor_info.tensor_shape.unknown_rank: + shape = 'unknown_rank' + else: + dims = [str(dim.size) for dim in tensor_info.tensor_shape.dim] + shape = ', '.join(dims) + shape = '(' + shape + ')' + in_print(' shape: ' + shape) + in_print(' name: ' + tensor_info.name) + + +def _show_all(saved_model_dir): + """Prints tag-set, ops, SignatureDef, and Inputs/Outputs of SavedModel. + + Prints all tag-set, ops, SignatureDef and Inputs/Outputs information stored in + SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + """ + saved_model = saved_model_utils.read_saved_model(saved_model_dir) + for meta_graph_def in sorted( + saved_model.meta_graphs, + key=lambda meta_graph_def: list(meta_graph_def.meta_info_def.tags), + ): + tag_set = meta_graph_def.meta_info_def.tags + print("\nMetaGraphDef with tag-set: '%s' " + "contains the following SignatureDefs:" % ', '.join(tag_set)) + + tag_set = ','.join(tag_set) + signature_def_map = meta_graph_def.signature_def + for signature_def_key in sorted(signature_def_map.keys()): + print('\nsignature_def[\'' + signature_def_key + '\']:') + _show_inputs_outputs_mgd(meta_graph_def, signature_def_key, indent=1) + _show_ops_in_metagraph_mgd(meta_graph_def) + _show_defined_functions(saved_model_dir, saved_model.meta_graphs) + + +def get_meta_graph_def(saved_model_dir, tag_set): + """DEPRECATED: Use saved_model_utils.get_meta_graph_def instead. + + Gets MetaGraphDef from SavedModel. Returns the MetaGraphDef for the given + tag-set and SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect or execute. + tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, + separated by ','. For tag-set contains multiple tags, all tags must be + passed in. + + Raises: + RuntimeError: An error when the given tag-set does not exist in the + SavedModel. + + Returns: + A MetaGraphDef corresponding to the tag-set. + """ + return saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) + + +def get_signature_def_map(saved_model_dir, tag_set): + """Gets SignatureDef map from a MetaGraphDef in a SavedModel. + + Returns the SignatureDef map for the given tag-set in the SavedModel + directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect or execute. + tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in + string format, separated by ','. For tag-set contains multiple tags, all + tags must be passed in. + + Returns: + A SignatureDef map that maps from string keys to SignatureDefs. + """ + meta_graph = saved_model_utils.get_meta_graph_def(saved_model_dir, tag_set) + return meta_graph.signature_def + + +def _get_op_denylist_set(op_denylist): + # Note: Discard empty ops so that "" can mean the empty denylist set. + set_of_denylisted_ops = set([op for op in op_denylist.split(',') if op]) + return set_of_denylisted_ops + + +def scan_meta_graph_def(meta_graph_def, op_denylist): + """Scans meta_graph_def and reports if there are ops on denylist. + + Print ops if they are on denylist, or print success if no denylisted ops + found. + + Args: + meta_graph_def: MetaGraphDef protocol buffer. + op_denylist: set of ops to scan for. + """ + ops_in_metagraph = set( + meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def)) + denylisted_ops = op_denylist & ops_in_metagraph + if denylisted_ops: + # TODO(yifeif): print more warnings + print( + 'MetaGraph with tag set %s contains the following denylisted ops:' % + meta_graph_def.meta_info_def.tags, denylisted_ops) + else: + print( + 'MetaGraph with tag set %s does not contain the default denylisted ops:' + % meta_graph_def.meta_info_def.tags, op_denylist) + + +def run_saved_model_with_feed_dict(saved_model_dir, + tag_set, + signature_def_key, + input_tensor_key_feed_dict, + outdir, + overwrite_flag, + worker=None, + init_tpu=False, + use_tfrt=False, + tf_debug=False): + """Runs SavedModel and fetch all outputs. + + Runs the input dictionary through the MetaGraphDef within a SavedModel + specified by the given tag_set and SignatureDef. Also save the outputs to file + if outdir is not None. + + Args: + saved_model_dir: Directory containing the SavedModel to execute. + tag_set: Group of tag(s) of the MetaGraphDef with the SignatureDef map, in + string format, separated by ','. For tag-set contains multiple tags, all + tags must be passed in. + signature_def_key: A SignatureDef key string. + input_tensor_key_feed_dict: A dictionary maps input keys to numpy ndarrays. + outdir: A directory to save the outputs to. If the directory doesn't exist, + it will be created. + overwrite_flag: A boolean flag to allow overwrite output file if file with + the same name exists. + worker: If provided, the session will be run on the worker. Valid worker + specification is a bns or gRPC path. + init_tpu: If true, the TPU system will be initialized after the session + is created. + use_tfrt: If true, TFRT session will be used. + tf_debug: A boolean flag to use TensorFlow Debugger (TFDBG) to observe the + intermediate Tensor values and runtime GraphDefs while running the + SavedModel. + + Raises: + ValueError: When any of the input tensor keys is not valid. + RuntimeError: An error when output file already exists and overwrite is not + enabled. + """ + # Get a list of output tensor names. + meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir, + tag_set) + + # Re-create feed_dict based on input tensor name instead of key as session.run + # uses tensor name. + inputs_tensor_info = _get_inputs_tensor_info_from_meta_graph_def( + meta_graph_def, signature_def_key) + + # Check if input tensor keys are valid. + for input_key_name in input_tensor_key_feed_dict.keys(): + if input_key_name not in inputs_tensor_info: + raise ValueError( + '"%s" is not a valid input key. Please choose from %s, or use ' + '--show option.' % + (input_key_name, '"' + '", "'.join(inputs_tensor_info.keys()) + '"')) + + inputs_feed_dict = { + inputs_tensor_info[key].name: tensor + for key, tensor in input_tensor_key_feed_dict.items() + } + # Get outputs + outputs_tensor_info = _get_outputs_tensor_info_from_meta_graph_def( + meta_graph_def, signature_def_key) + # Sort to preserve order because we need to go from value to key later. + output_tensor_keys_sorted = sorted(outputs_tensor_info.keys()) + output_tensor_names_sorted = [ + outputs_tensor_info[tensor_key].name + for tensor_key in output_tensor_keys_sorted + ] + + config = None + if use_tfrt: + logging.info('Using TFRT session.') + config = config_pb2.ConfigProto( + experimental=config_pb2.ConfigProto.Experimental(use_tfrt=True)) + with session.Session(worker, graph=ops_lib.Graph(), config=config) as sess: + if init_tpu: + print('Initializing TPU System ...') + # This is needed for freshly started worker, or if the job + # restarts after a preemption. + sess.run(tpu.initialize_system()) + + loader.load(sess, tag_set.split(','), saved_model_dir) + + if tf_debug: + sess = local_cli_wrapper.LocalCLIDebugWrapperSession(sess) + + outputs = sess.run(output_tensor_names_sorted, feed_dict=inputs_feed_dict) + + for i, output in enumerate(outputs): + output_tensor_key = output_tensor_keys_sorted[i] + print('Result for output key %s:\n%s' % (output_tensor_key, output)) + + # Only save if outdir is specified. + if outdir: + # Create directory if outdir does not exist + if not os.path.isdir(outdir): + os.makedirs(outdir) + output_full_path = os.path.join(outdir, output_tensor_key + '.npy') + + # If overwrite not enabled and file already exist, error out + if not overwrite_flag and os.path.exists(output_full_path): + raise RuntimeError( + 'Output file %s already exists. Add \"--overwrite\" to overwrite' + ' the existing output files.' % output_full_path) + + np.save(output_full_path, output) + print('Output %s is saved to %s' % (output_tensor_key, + output_full_path)) + + +def preprocess_inputs_arg_string(inputs_str): + """Parses input arg into dictionary that maps input to file/variable tuple. + + Parses input string in the format of, for example, + "input1=filename1[variable_name1],input2=filename2" into a + dictionary looks like + {'input_key1': (filename1, variable_name1), + 'input_key2': (file2, None)} + , which maps input keys to a tuple of file name and variable name(None if + empty). + + Args: + inputs_str: A string that specified where to load inputs. Inputs are + separated by semicolons. + * For each input key: + '=' or + '=[]' + * The optional 'variable_name' key will be set to None if not specified. + + Returns: + A dictionary that maps input keys to a tuple of file name and variable name. + + Raises: + RuntimeError: An error when the given input string is in a bad format. + """ + input_dict = {} + inputs_raw = inputs_str.split(';') + for input_raw in filter(bool, inputs_raw): # skip empty strings + # Format of input=filename[variable_name]' + match = re.match(r'([^=]+)=([^\[\]]+)\[([^\[\]]+)\]$', input_raw) + + if match: + input_dict[match.group(1)] = match.group(2), match.group(3) + else: + # Format of input=filename' + match = re.match(r'([^=]+)=([^\[\]]+)$', input_raw) + if match: + input_dict[match.group(1)] = match.group(2), None + else: + raise RuntimeError( + '--inputs "%s" format is incorrect. Please follow' + '"=", or' + '"=[]"' % input_raw) + + return input_dict + + +def preprocess_input_exprs_arg_string(input_exprs_str, safe=True): + """Parses input arg into dictionary that maps input key to python expression. + + Parses input string in the format of 'input_key=' into a + dictionary that maps each input_key to its python expression. + + Args: + input_exprs_str: A string that specifies python expression for input keys. + Each input is separated by semicolon. For each input key: + 'input_key=' + safe: Whether to evaluate the python expression as literals or allow + arbitrary calls (e.g. numpy usage). + + Returns: + A dictionary that maps input keys to their values. + + Raises: + RuntimeError: An error when the given input string is in a bad format. + """ + input_dict = {} + + for input_raw in filter(bool, input_exprs_str.split(';')): + if '=' not in input_exprs_str: + raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow' + '"="' % input_exprs_str) + input_key, expr = input_raw.split('=', 1) + if safe: + try: + input_dict[input_key] = ast.literal_eval(expr) + except Exception as exc: + raise RuntimeError( + f'Expression "{expr}" is not a valid python literal.') from exc + else: + # ast.literal_eval does not work with numpy expressions + input_dict[input_key] = eval(expr) # pylint: disable=eval-used + return input_dict + + +def preprocess_input_examples_arg_string(input_examples_str): + """Parses input into dict that maps input keys to lists of tf.Example. + + Parses input string in the format of 'input_key1=[{feature_name: + feature_list}];input_key2=[{feature_name:feature_list}];' into a dictionary + that maps each input_key to its list of serialized tf.Example. + + Args: + input_examples_str: A string that specifies a list of dictionaries of + feature_names and their feature_lists for each input. + Each input is separated by semicolon. For each input key: + 'input=[{feature_name1: feature_list1, feature_name2:feature_list2}]' + items in feature_list can be the type of float, int, long or str. + + Returns: + A dictionary that maps input keys to lists of serialized tf.Example. + + Raises: + ValueError: An error when the given tf.Example is not a list. + """ + input_dict = preprocess_input_exprs_arg_string(input_examples_str) + for input_key, example_list in input_dict.items(): + if not isinstance(example_list, list): + raise ValueError( + 'tf.Example input must be a list of dictionaries, but "%s" is %s' % + (example_list, type(example_list))) + input_dict[input_key] = [ + _create_example_string(example) for example in example_list + ] + return input_dict + + +def _create_example_string(example_dict): + """Create a serialized tf.example from feature dictionary.""" + example = example_pb2.Example() + for feature_name, feature_list in example_dict.items(): + if not isinstance(feature_list, list): + raise ValueError('feature value must be a list, but %s: "%s" is %s' % + (feature_name, feature_list, type(feature_list))) + if isinstance(feature_list[0], float): + example.features.feature[feature_name].float_list.value.extend( + feature_list) + elif isinstance(feature_list[0], str): + example.features.feature[feature_name].bytes_list.value.extend( + [f.encode('utf8') for f in feature_list]) + elif isinstance(feature_list[0], bytes): + example.features.feature[feature_name].bytes_list.value.extend( + feature_list) + elif isinstance(feature_list[0], int): + example.features.feature[feature_name].int64_list.value.extend( + feature_list) + else: + raise ValueError( + 'Type %s for value %s is not supported for tf.train.Feature.' % + (type(feature_list[0]), feature_list[0])) + return example.SerializeToString() + + +def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, + input_examples_str): + """Parses input arg strings and create inputs feed_dict. + + Parses '--inputs' string for inputs to be loaded from file, and parses + '--input_exprs' string for inputs to be evaluated from python expression. + '--input_examples' string for inputs to be created from tf.example feature + dictionary list. + + Args: + inputs_str: A string that specified where to load inputs. Each input is + separated by semicolon. + * For each input key: + '=' or + '=[]' + * The optional 'variable_name' key will be set to None if not specified. + * File specified by 'filename' will be loaded using numpy.load. Inputs + can be loaded from only .npy, .npz or pickle files. + * The "[variable_name]" key is optional depending on the input file type + as descripted in more details below. + When loading from a npy file, which always contains a numpy ndarray, the + content will be directly assigned to the specified input tensor. If a + variable_name is specified, it will be ignored and a warning will be + issued. + When loading from a npz zip file, user can specify which variable within + the zip file to load for the input tensor inside the square brackets. If + nothing is specified, this function will check that only one file is + included in the zip and load it for the specified input tensor. + When loading from a pickle file, if no variable_name is specified in the + square brackets, whatever that is inside the pickle file will be passed + to the specified input tensor, else SavedModel CLI will assume a + dictionary is stored in the pickle file and the value corresponding to + the variable_name will be used. + input_exprs_str: A string that specifies python expressions for inputs. + * In the format of: '='. + * numpy module is available as np. + input_examples_str: A string that specifies tf.Example with dictionary. + * In the format of: '=<[{feature:value list}]>' + + Returns: + A dictionary that maps input tensor keys to numpy ndarrays. + + Raises: + RuntimeError: An error when a key is specified, but the input file contains + multiple numpy ndarrays, none of which matches the given key. + RuntimeError: An error when no key is specified, but the input file contains + more than one numpy ndarrays. + """ + tensor_key_feed_dict = {} + + inputs = preprocess_inputs_arg_string(inputs_str) + input_exprs = preprocess_input_exprs_arg_string(input_exprs_str) + input_examples = preprocess_input_examples_arg_string(input_examples_str) + + for input_tensor_key, (filename, variable_name) in inputs.items(): + data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # pylint: disable=unexpected-keyword-arg + + # When a variable_name key is specified for the input file + if variable_name: + # if file contains a single ndarray, ignore the input name + if isinstance(data, np.ndarray): + logging.warn( + 'Input file %s contains a single ndarray. Name key \"%s\" ignored.' + % (filename, variable_name)) + tensor_key_feed_dict[input_tensor_key] = data + else: + if variable_name in data: + tensor_key_feed_dict[input_tensor_key] = data[variable_name] + else: + raise RuntimeError( + 'Input file %s does not contain variable with name \"%s\".' % + (filename, variable_name)) + # When no key is specified for the input file. + else: + # Check if npz file only contains a single numpy ndarray. + if isinstance(data, np.lib.npyio.NpzFile): + variable_name_list = data.files + if len(variable_name_list) != 1: + raise RuntimeError( + 'Input file %s contains more than one ndarrays. Please specify ' + 'the name of ndarray to use.' % filename) + tensor_key_feed_dict[input_tensor_key] = data[variable_name_list[0]] + else: + tensor_key_feed_dict[input_tensor_key] = data + + # When input is a python expression: + for input_tensor_key, py_expr_evaluated in input_exprs.items(): + if input_tensor_key in tensor_key_feed_dict: + logging.warn( + 'input_key %s has been specified with both --inputs and --input_exprs' + ' options. Value in --input_exprs will be used.' % input_tensor_key) + tensor_key_feed_dict[input_tensor_key] = py_expr_evaluated + + # When input is a tf.Example: + for input_tensor_key, example in input_examples.items(): + if input_tensor_key in tensor_key_feed_dict: + logging.warn( + 'input_key %s has been specified in multiple options. Value in ' + '--input_examples will be used.' % input_tensor_key) + tensor_key_feed_dict[input_tensor_key] = example + return tensor_key_feed_dict + + +def show(): + """Function triggered by show command.""" + # If all tag is specified, display all information. + if _SMCLI_ALL.value: + _show_all(_SMCLI_DIR.value) + else: + # If no tag is specified, display all tag_sets. + # If a tag set is specified: + # # If list_ops is set, display all ops in the specified MetaGraphDef. + # # If no signature_def key is specified, display all SignatureDef keys. + # # If a signature_def is specified, show its corresponding input output + # # tensor information. + if _SMCLI_TAG_SET.value is None: + if _SMCLI_LIST_OPS.value: + print('--list_ops must be paired with a tag-set or with --all.') + _show_tag_sets(_SMCLI_DIR.value) + else: + if _SMCLI_LIST_OPS.value: + _show_ops_in_metagraph(_SMCLI_DIR.value, _SMCLI_TAG_SET.value) + if _SMCLI_SIGNATURE_DEF.value is None: + _show_signature_def_map_keys(_SMCLI_DIR.value, _SMCLI_TAG_SET.value) + else: + _show_inputs_outputs( + _SMCLI_DIR.value, _SMCLI_TAG_SET.value, _SMCLI_SIGNATURE_DEF.value) + + +def run(): + """Function triggered by run command. + + Raises: + AttributeError: An error when neither --inputs nor --input_exprs is passed + to run command. + """ + if ( + not _SMCLI_INPUTS.value + and not _SMCLI_INPUT_EXPRS.value + and not _SMCLI_INPUT_EXAMPLES.value + ): + raise AttributeError( + 'At least one of --inputs, --input_exprs or --input_examples must be ' + 'required') + tensor_key_feed_dict = load_inputs_from_input_arg_string( + _SMCLI_INPUTS.value, + _SMCLI_INPUT_EXPRS.value, + _SMCLI_INPUT_EXAMPLES.value) + run_saved_model_with_feed_dict( + _SMCLI_DIR.value, + _SMCLI_TAG_SET.value, + _SMCLI_SIGNATURE_DEF.value, + tensor_key_feed_dict, + _SMCLI_OUTDIR.value, + _SMCLI_OVERWRITE.value, + worker=_SMCLI_WORKER.value, + init_tpu=_SMCLI_INIT_TPU.value, + use_tfrt=_SMCLI_USE_TFRT.value, + tf_debug=_SMCLI_TF_DEBUG.value) + + +def scan(): + """Function triggered by scan command.""" + if _SMCLI_TAG_SET.value and _SMCLI_OP_DENYLIST.value: + scan_meta_graph_def( + saved_model_utils.get_meta_graph_def( + _SMCLI_DIR.value, _SMCLI_TAG_SET.value), + _get_op_denylist_set(_SMCLI_OP_DENYLIST.value)) + elif _SMCLI_TAG_SET.value: + scan_meta_graph_def( + saved_model_utils.get_meta_graph_def( + _SMCLI_DIR.value, _SMCLI_TAG_SET.value), + _OP_DENYLIST) + else: + saved_model = saved_model_utils.read_saved_model(_SMCLI_DIR.value) + if _SMCLI_OP_DENYLIST.value: + for meta_graph_def in saved_model.meta_graphs: + scan_meta_graph_def(meta_graph_def, + _get_op_denylist_set(_SMCLI_OP_DENYLIST.value)) + else: + for meta_graph_def in saved_model.meta_graphs: + scan_meta_graph_def(meta_graph_def, _OP_DENYLIST) + + +def convert_with_tensorrt(): + """Function triggered by 'convert tensorrt' command.""" + # Import here instead of at top, because this will crash if TensorRT is + # not installed + from tensorflow.python.compiler.tensorrt import trt_convert as trt # pylint: disable=g-import-not-at-top + + if not _SMCLI_CONVERT_TF1_MODEL.value: + params = trt.DEFAULT_TRT_CONVERSION_PARAMS._replace( + max_workspace_size_bytes=_SMCLI_MAX_WORKSPACE_SIZE_BYTES.value, + precision_mode=_SMCLI_PRECISION_MODE.value, + minimum_segment_size=_SMCLI_MINIMUM_SEGMENT_SIZE.value) + try: + converter = trt.TrtGraphConverterV2( + input_saved_model_dir=_SMCLI_DIR.value, + input_saved_model_tags=_SMCLI_TAG_SET.value.split(','), + **params._asdict()) + converter.convert() + except Exception as exc: + raise RuntimeError( + '{}. Try passing "--convert_tf1_model=True".'.format(exc)) from exc + converter.save(output_saved_model_dir=_SMCLI_OUTPUT_DIR.value) + else: + trt.create_inference_graph( + None, + None, + max_batch_size=1, + max_workspace_size_bytes=_SMCLI_MAX_WORKSPACE_SIZE_BYTES.value, + precision_mode=_SMCLI_PRECISION_MODE.value, + minimum_segment_size=_SMCLI_MINIMUM_SEGMENT_SIZE.value, + is_dynamic_op=True, + input_saved_model_dir=_SMCLI_DIR.value, + input_saved_model_tags=_SMCLI_TAG_SET.value.split(','), + output_saved_model_dir=_SMCLI_OUTPUT_DIR.value) + + +def freeze_model(): + """Function triggered by freeze_model command.""" + checkpoint_path = ( + _SMCLI_CHECKPOINT_PATH.value + or os.path.join(_SMCLI_DIR.value, 'variables/variables')) + if not _SMCLI_VARIABLES_TO_FEED.value: + variables_to_feed = [] + elif _SMCLI_VARIABLES_TO_FEED.value.lower() == 'all': + variables_to_feed = None # We will identify them after. + else: + variables_to_feed = _SMCLI_VARIABLES_TO_FEED.value.split(',') + + saved_model_aot_compile.freeze_model( + checkpoint_path=checkpoint_path, + meta_graph_def=saved_model_utils.get_meta_graph_def( + _SMCLI_DIR.value, _SMCLI_TAG_SET.value), + signature_def_key=_SMCLI_SIGNATURE_DEF_KEY.value, + variables_to_feed=variables_to_feed, + output_prefix=_SMCLI_OUTPUT_PREFIX.value) + + +def aot_compile_cpu(): + """Function triggered by aot_compile_cpu command.""" + checkpoint_path = ( + _SMCLI_CHECKPOINT_PATH.value + or os.path.join(_SMCLI_DIR.value, 'variables/variables')) + if not _SMCLI_VARIABLES_TO_FEED.value: + variables_to_feed = [] + elif _SMCLI_VARIABLES_TO_FEED.value.lower() == 'all': + variables_to_feed = None # We will identify them after. + else: + variables_to_feed = _SMCLI_VARIABLES_TO_FEED.value.split(',') + + saved_model_aot_compile.aot_compile_cpu_meta_graph_def( + checkpoint_path=checkpoint_path, + meta_graph_def=saved_model_utils.get_meta_graph_def( + _SMCLI_DIR.value, _SMCLI_TAG_SET.value), + signature_def_key=_SMCLI_SIGNATURE_DEF_KEY.value, + variables_to_feed=variables_to_feed, + output_prefix=_SMCLI_OUTPUT_PREFIX.value, + target_triple=_SMCLI_TARGET_TRIPLE.value, + target_cpu=_SMCLI_TARGET_CPU.value, + cpp_class=_SMCLI_CPP_CLASS.value, + multithreading=( + _SMCLI_MULTITHREADING.value.lower() not in ('f', 'false', '0'))) + + +def add_show_subparser(subparsers): + """Add parser for `show`.""" + show_msg = ( + 'Usage examples:\n' + 'To show all tag-sets in a SavedModel:\n' + '$saved_model_cli show --dir /tmp/saved_model\n\n' + 'To show all available SignatureDef keys in a ' + 'MetaGraphDef specified by its tag-set:\n' + '$saved_model_cli show --dir /tmp/saved_model --tag_set serve\n\n' + 'For a MetaGraphDef with multiple tags in the tag-set, all tags must be ' + 'passed in, separated by \';\':\n' + '$saved_model_cli show --dir /tmp/saved_model --tag_set serve,gpu\n\n' + 'To show all inputs and outputs TensorInfo for a specific' + ' SignatureDef specified by the SignatureDef key in a' + ' MetaGraph.\n' + '$saved_model_cli show --dir /tmp/saved_model --tag_set serve' + ' --signature_def serving_default\n\n' + 'To show all ops in a MetaGraph.\n' + '$saved_model_cli show --dir /tmp/saved_model --tag_set serve' + ' --list_ops\n\n' + 'To show all available information in the SavedModel:\n' + '$saved_model_cli show --dir /tmp/saved_model --all') + parser_show = subparsers.add_parser( + 'show', + description=show_msg, + formatter_class=argparse.RawTextHelpFormatter) + parser_show.set_defaults(func=show) + + +def add_run_subparser(subparsers): + """Add parser for `run`.""" + run_msg = ('Usage example:\n' + 'To run input tensors from files through a MetaGraphDef and save' + ' the output tensors to files:\n' + '$saved_model_cli show --dir /tmp/saved_model --tag_set serve \\\n' + ' --signature_def serving_default \\\n' + ' --inputs input1_key=/tmp/124.npz[x],input2_key=/tmp/123.npy ' + '\\\n' + ' --input_exprs \'input3_key=np.ones(2)\' \\\n' + ' --input_examples ' + '\'input4_key=[{"id":[26],"weights":[0.5, 0.5]}]\' \\\n' + ' --outdir=/out\n\n' + 'For more information about input file format, please see:\n' + 'https://www.tensorflow.org/guide/saved_model_cli\n') + parser_run = subparsers.add_parser( + 'run', description=run_msg, formatter_class=argparse.RawTextHelpFormatter) + parser_run.set_defaults(func=run) + + +def add_scan_subparser(subparsers): + """Add parser for `scan`.""" + scan_msg = ('Usage example:\n' + 'To scan for default denylisted ops in SavedModel:\n' + '$saved_model_cli scan --dir /tmp/saved_model\n' + 'To scan for a specific set of ops in SavedModel:\n' + '$saved_model_cli scan --dir /tmp/saved_model --op_denylist ' + 'OpName,OpName,OpName\n' + 'To scan a specific MetaGraph, pass in --tag_set\n') + parser_scan = subparsers.add_parser( + 'scan', + description=scan_msg, + formatter_class=argparse.RawTextHelpFormatter) + parser_scan.set_defaults(func=scan) + + +def add_convert_subparser(subparsers): + """Add parser for `convert`.""" + convert_msg = ('Usage example:\n' + 'To convert the SavedModel to one that have TensorRT ops:\n' + '$saved_model_cli convert \\\n' + ' --dir /tmp/saved_model \\\n' + ' --tag_set serve \\\n' + ' --output_dir /tmp/saved_model_trt \\\n' + ' tensorrt \n') + parser_convert = subparsers.add_parser( + 'convert', + description=convert_msg, + formatter_class=argparse.RawTextHelpFormatter) + convert_subparsers = parser_convert.add_subparsers( + title='conversion methods', + description='valid conversion methods', + help='the conversion to run with the SavedModel') + parser_convert_with_tensorrt = convert_subparsers.add_parser( + 'tensorrt', + description='Convert the SavedModel with Tensorflow-TensorRT integration', + formatter_class=argparse.RawTextHelpFormatter) + parser_convert_with_tensorrt.set_defaults(func=convert_with_tensorrt) + + +def add_freeze_model_subparser(subparsers): + """Add parser for `freeze_model`.""" + compile_msg = '\n'.join( + ['Usage example:', + 'To freeze a SavedModel in preparation for tfcompile:', + '$saved_model_cli freeze_model \\', + ' --dir /tmp/saved_model \\', + ' --tag_set serve \\', + ' --output_prefix /tmp/saved_model_xla_aot', + ]) + + parser_compile = subparsers.add_parser( + 'freeze_model', + description=compile_msg, + formatter_class=argparse.RawTextHelpFormatter) + parser_compile.set_defaults(func=freeze_model) + + +def add_aot_compile_cpu_subparser(subparsers): + """Add parser for `aot_compile_cpu`.""" + compile_msg = '\n'.join( + ['Usage example:', + 'To compile a SavedModel signature via (CPU) XLA AOT:', + '$saved_model_cli aot_compile_cpu \\', + ' --dir /tmp/saved_model \\', + ' --tag_set serve \\', + ' --output_dir /tmp/saved_model_xla_aot', + '', '', + 'Note: Additional XLA compilation options are available by setting the ', + 'XLA_FLAGS environment variable. See the XLA debug options flags for ', + 'all the options: ', + ' {}'.format(_XLA_DEBUG_OPTIONS_URL), + '', + 'For example, to disable XLA fast math when compiling:', + '', + 'XLA_FLAGS="--xla_cpu_enable_fast_math=false" $saved_model_cli ', + 'aot_compile_cpu ...', + '', + 'Some possibly useful flags:', + ' --xla_cpu_enable_fast_math=false', + ' --xla_force_host_platform_device_count=', + ' (useful in conjunction with disabling multi threading)' + ]) + + parser_compile = subparsers.add_parser( + 'aot_compile_cpu', + description=compile_msg, + formatter_class=argparse.RawTextHelpFormatter) + + parser_compile.set_defaults(func=aot_compile_cpu) + + +def create_parser(): + """Creates a parser that parse the command line arguments. + + Returns: + A namespace parsed from command line arguments. + """ + parser = argparse_flags.ArgumentParser( + description='saved_model_cli: Command-line interface for SavedModel', + conflict_handler='resolve') + parser.add_argument('-v', '--version', action='version', version='0.1.0') + + subparsers = parser.add_subparsers( + title='commands', description='valid commands', help='additional help') + + # show command + add_show_subparser(subparsers) + + # run command + add_run_subparser(subparsers) + + # scan command + add_scan_subparser(subparsers) + + # tensorrt convert command + add_convert_subparser(subparsers) + + # aot_compile_cpu command + add_aot_compile_cpu_subparser(subparsers) + + # freeze_model command + add_freeze_model_subparser(subparsers) + return parser + + +def main(): + logging.set_verbosity(logging.INFO) + + def smcli_main(argv): + parser = create_parser() + if len(argv) < 2: + parser.error('Too few arguments.') + flags.mark_flags_as_required(command_required_flags[argv[1]]) + args = parser.parse_args() + args.func() + + app.run(smcli_main) + + +if __name__ == '__main__': + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6a848ca40cad29992d28643498bf435955bc2780 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/saved_model_utils.py @@ -0,0 +1,127 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""SavedModel utils.""" + +import os + +from google.protobuf import message +from google.protobuf import text_format +from tensorflow.core.protobuf import saved_model_pb2 +from tensorflow.python.lib.io import file_io +from tensorflow.python.saved_model import constants +from tensorflow.python.util import compat + + +def read_saved_model(saved_model_dir): + """Reads the saved_model.pb or saved_model.pbtxt file containing `SavedModel`. + + Args: + saved_model_dir: Directory containing the SavedModel file. + + Returns: + A `SavedModel` protocol buffer. + + Raises: + IOError: If the file does not exist, or cannot be successfully parsed. + """ + # Build the path to the SavedModel in pbtxt format. + path_to_pbtxt = os.path.join( + compat.as_bytes(saved_model_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT)) + # Build the path to the SavedModel in pb format. + path_to_pb = os.path.join( + compat.as_bytes(saved_model_dir), + compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB)) + + # Ensure that the SavedModel exists at either path. + if not file_io.file_exists(path_to_pbtxt) and not file_io.file_exists( + path_to_pb): + raise IOError("SavedModel file does not exist at: %s" % saved_model_dir) + + # Parse the SavedModel protocol buffer. + saved_model = saved_model_pb2.SavedModel() + if file_io.file_exists(path_to_pb): + with file_io.FileIO(path_to_pb, "rb") as f: + file_content = f.read() + try: + saved_model.ParseFromString(file_content) + return saved_model + except message.DecodeError as e: + raise IOError("Cannot parse proto file %s: %s." % (path_to_pb, str(e))) + elif file_io.file_exists(path_to_pbtxt): + with file_io.FileIO(path_to_pbtxt, "rb") as f: + file_content = f.read() + try: + text_format.Merge(file_content.decode("utf-8"), saved_model) + return saved_model + except text_format.ParseError as e: + raise IOError("Cannot parse pbtxt file %s: %s." % (path_to_pbtxt, str(e))) + else: + raise IOError("SavedModel file does not exist at: %s/{%s|%s}" % + (saved_model_dir, constants.SAVED_MODEL_FILENAME_PBTXT, + constants.SAVED_MODEL_FILENAME_PB)) + + +def get_saved_model_tag_sets(saved_model_dir): + """Retrieves all the tag-sets available in the SavedModel. + + Args: + saved_model_dir: Directory containing the SavedModel. + + Returns: + List of all tag-sets in the SavedModel, where a tag-set is represented as a + list of strings. + """ + saved_model = read_saved_model(saved_model_dir) + all_tags = [] + for meta_graph_def in saved_model.meta_graphs: + all_tags.append(list(meta_graph_def.meta_info_def.tags)) + return all_tags + + +def get_meta_graph_def(saved_model_dir, tag_set): + """Gets MetaGraphDef from SavedModel. + + Returns the MetaGraphDef for the given tag-set and SavedModel directory. + + Args: + saved_model_dir: Directory containing the SavedModel to inspect. + tag_set: Group of tag(s) of the MetaGraphDef to load, in string format, + separated by ','. The empty string tag is ignored so that passing '' + means the empty tag set. For tag-set contains multiple tags, all tags + must be passed in. + + Raises: + RuntimeError: An error when the given tag-set does not exist in the + SavedModel. + + Returns: + A MetaGraphDef corresponding to the tag-set. + """ + saved_model = read_saved_model(saved_model_dir) + # Note: Discard empty tags so that "" can mean the empty tag set. + set_of_tags = set([tag for tag in tag_set.split(",") if tag]) + + valid_tags = [] + for meta_graph_def in saved_model.meta_graphs: + meta_graph_tags = set(meta_graph_def.meta_info_def.tags) + if meta_graph_tags == set_of_tags: + return meta_graph_def + else: + valid_tags.append(",".join(meta_graph_tags)) + + raise RuntimeError( + f"MetaGraphDef associated with tag-set {tag_set} could not be found in " + f"the SavedModel. Please use one of the following tag-sets: {valid_tags}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/selective_registration_header_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/selective_registration_header_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..2476d9924a9db1105c577e15f80b942b8164b9bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/selective_registration_header_lib.py @@ -0,0 +1,248 @@ +# Copyright 2016 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Computes a header file to be used with SELECTIVE_REGISTRATION. + +See the executable wrapper, print_selective_registration_header.py, for more +information. +""" + +import json +import os +import sys + +from google.protobuf import text_format +from tensorflow.core.framework import graph_pb2 +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging +from tensorflow.python.util import _pywrap_kernel_registry + +# Usually, we use each graph node to induce registration of an op and +# corresponding kernel; nodes without a corresponding kernel (perhaps due to +# attr types) generate a warning but are otherwise ignored. Ops in this set are +# registered even if there's no corresponding kernel. +OPS_WITHOUT_KERNEL_ALLOWLIST = frozenset([ + # AccumulateNV2 is rewritten away by AccumulateNV2RemovePass; see + # core/common_runtime/accumulate_n_optimizer.cc. + 'AccumulateNV2' +]) +FLEX_PREFIX = b'Flex' +FLEX_PREFIX_LENGTH = len(FLEX_PREFIX) + + +def _get_ops_from_ops_list(input_file): + """Gets the ops and kernels needed from the ops list file.""" + ops = set() + ops_list_str = gfile.GFile(input_file, 'r').read() + if not ops_list_str: + raise Exception('Input file should not be empty') + ops_list = json.loads(ops_list_str) + for op, kernel in ops_list: + op_and_kernel = (op, kernel if kernel else None) + ops.add(op_and_kernel) + return ops + + +def _get_ops_from_graphdef(graph_def): + """Gets the ops and kernels needed from the tensorflow model.""" + ops = set() + ops.update(_get_ops_from_nodedefs(graph_def.node)) + + for function in graph_def.library.function: + ops.update(_get_ops_from_nodedefs(function.node_def)) + return ops + + +def get_ops_from_nodedef(node_def): + """Gets the op and kernel needed from the given NodeDef. + + Args: + node_def: TF NodeDef to get op/kernel information. + + Returns: + A tuple of (op_name, kernel_name). If the op is not in the allowlist of ops + without kernel and there is no kernel found, then return None. + """ + if not node_def.device: + node_def.device = '/cpu:0' + kernel_class = _pywrap_kernel_registry.TryFindKernelClass( + node_def.SerializeToString()) + op = str(node_def.op) + if kernel_class or op in OPS_WITHOUT_KERNEL_ALLOWLIST: + return (op, str(kernel_class.decode('utf-8')) if kernel_class else None) + else: + tf_logging.warning('Warning: no kernel found for op %s', op) + return None + + +def _get_ops_from_nodedefs(node_defs): + """Gets the ops and kernels needed from the list of NodeDef. + + If a NodeDef's op is not in the allowlist of ops without kernel and there is + no kernel found for this NodeDef, then skip that NodeDef and proceed to the + next one. + + Args: + node_defs: list of NodeDef's to get op/kernel information. + + Returns: + A set of (op_name, kernel_name) tuples. + """ + ops = set() + for node_def in node_defs: + op_and_kernel = get_ops_from_nodedef(node_def) + if op_and_kernel: + ops.add(op_and_kernel) + return ops + + +def get_ops_and_kernels(proto_fileformat, proto_files, default_ops_str): + """Gets the ops and kernels needed from the model files.""" + ops = set() + + for proto_file in proto_files: + tf_logging.info('Loading proto file %s', proto_file) + # Load ops list file. + if proto_fileformat == 'ops_list': + ops = ops.union(_get_ops_from_ops_list(proto_file)) + continue + + # Load GraphDef. + file_data = gfile.GFile(proto_file, 'rb').read() + if proto_fileformat == 'rawproto': + graph_def = graph_pb2.GraphDef.FromString(file_data) + else: + assert proto_fileformat == 'textproto' + graph_def = text_format.Parse(file_data, graph_pb2.GraphDef()) + ops = ops.union(_get_ops_from_graphdef(graph_def)) + + # Add default ops. + if default_ops_str and default_ops_str != 'all': + for s in default_ops_str.split(','): + op, kernel = s.split(':') + op_and_kernel = (op, kernel) + if op_and_kernel not in ops: + ops.add(op_and_kernel) + + return sorted(ops) + + +def get_header_from_ops_and_kernels(ops_and_kernels, + include_all_ops_and_kernels): + """Returns a header for use with tensorflow SELECTIVE_REGISTRATION. + + Args: + ops_and_kernels: a set of (op_name, kernel_class_name) pairs to include. + include_all_ops_and_kernels: if True, ops_and_kernels is ignored and all op + kernels are included. + + Returns: + the string of the header that should be written as ops_to_register.h. + """ + ops_and_kernels = sorted(ops_and_kernels) + ops = set(op for op, _ in ops_and_kernels) + result_list = [] + + def append(s): + result_list.append(s) + + _, script_name = os.path.split(sys.argv[0]) + append('// This file was autogenerated by %s' % script_name) + append('#ifndef OPS_TO_REGISTER') + append('#define OPS_TO_REGISTER') + + if include_all_ops_and_kernels: + append('#define SHOULD_REGISTER_OP(op) true') + append('#define SHOULD_REGISTER_OP_KERNEL(clz) true') + append('#define SHOULD_REGISTER_OP_GRADIENT true') + else: + line = """ + namespace { + constexpr const char* skip(const char* x) { + return (*x) ? (*x == ' ' ? skip(x + 1) : x) : x; + } + + constexpr bool isequal(const char* x, const char* y) { + return (*skip(x) && *skip(y)) + ? (*skip(x) == *skip(y) && isequal(skip(x) + 1, skip(y) + 1)) + : (!*skip(x) && !*skip(y)); + } + + template + struct find_in { + static constexpr bool f(const char* x, const char* const y[N]) { + return isequal(x, y[0]) || find_in::f(x, y + 1); + } + }; + + template<> + struct find_in<0> { + static constexpr bool f(const char* x, const char* const y[]) { + return false; + } + }; + } // end namespace + """ + line += 'constexpr const char* kNecessaryOpKernelClasses[] = {\n' + for _, kernel_class in ops_and_kernels: + if kernel_class is None: + continue + line += '"%s",\n' % kernel_class + line += '};' + append(line) + append('#define SHOULD_REGISTER_OP_KERNEL(clz) ' + '(find_in::f(clz, ' + 'kNecessaryOpKernelClasses))') + append('') + + append('constexpr inline bool ShouldRegisterOp(const char op[]) {') + append(' return false') + for op in sorted(ops): + append(' || isequal(op, "%s")' % op) + append(' ;') + append('}') + append('#define SHOULD_REGISTER_OP(op) ShouldRegisterOp(op)') + append('') + + append('#define SHOULD_REGISTER_OP_GRADIENT ' + + ('true' if 'SymbolicGradient' in ops else 'false')) + + append('#endif') + return '\n'.join(result_list) + + +def get_header(graphs, + proto_fileformat='rawproto', + default_ops='NoOp:NoOp,_Recv:RecvOp,_Send:SendOp'): + """Computes a header for use with tensorflow SELECTIVE_REGISTRATION. + + Args: + graphs: a list of paths to GraphDef files to include. + proto_fileformat: optional format of proto file, either 'textproto', + 'rawproto' (default) or ops_list. The ops_list is the file contain the + list of ops in JSON format, Ex: "[["Transpose", "TransposeCpuOp"]]". + default_ops: optional comma-separated string of operator:kernel pairs to + always include implementation for. Pass 'all' to have all operators and + kernels included. Default: 'NoOp:NoOp,_Recv:RecvOp,_Send:SendOp'. + + Returns: + the string of the header that should be written as ops_to_register.h. + """ + ops_and_kernels = get_ops_and_kernels(proto_fileformat, graphs, default_ops) + if not ops_and_kernels: + print('Error reading graph!') + return 1 + + return get_header_from_ops_and_kernels(ops_and_kernels, default_ops == 'all') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused.py new file mode 100644 index 0000000000000000000000000000000000000000..d7477c6777fd5915aeec8e9ddfcf690de3aa0138 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused.py @@ -0,0 +1,104 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Removes unneeded nodes from a GraphDef file. + +This script is designed to help streamline models, by taking the input and +output nodes that will be used by an application and figuring out the smallest +set of operations that are required to run for those arguments. The resulting +minimal graph is then saved out. + +The advantages of running this script are: + - You may be able to shrink the file size. + - Operations that are unsupported on your platform but still present can be + safely removed. +The resulting graph may not be as flexible as the original though, since any +input nodes that weren't explicitly mentioned may not be accessible any more. + +An example of command-line usage is: +bazel build tensorflow/python/tools:strip_unused && \ +bazel-bin/tensorflow/python/tools/strip_unused \ +--input_graph=some_graph_def.pb \ +--output_graph=/tmp/stripped_graph.pb \ +--input_node_names=input0 +--output_node_names=softmax + +You can also look at strip_unused_test.py for an example of how to use it. + +""" +import argparse +import sys + +from absl import app + +from tensorflow.python.framework import dtypes +from tensorflow.python.tools import strip_unused_lib + +FLAGS = None + + +def main(unused_args): + strip_unused_lib.strip_unused_from_files(FLAGS.input_graph, + FLAGS.input_binary, + FLAGS.output_graph, + FLAGS.output_binary, + FLAGS.input_node_names, + FLAGS.output_node_names, + FLAGS.placeholder_type_enum) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.register('type', 'bool', lambda v: v.lower() == 'true') + parser.add_argument( + '--input_graph', + type=str, + default='', + help='TensorFlow \'GraphDef\' file to load.') + parser.add_argument( + '--input_binary', + nargs='?', + const=True, + type='bool', + default=False, + help='Whether the input files are in binary format.') + parser.add_argument( + '--output_graph', + type=str, + default='', + help='Output \'GraphDef\' file name.') + parser.add_argument( + '--output_binary', + nargs='?', + const=True, + type='bool', + default=True, + help='Whether to write a binary format graph.') + parser.add_argument( + '--input_node_names', + type=str, + default='', + help='The name of the input nodes, comma separated.') + parser.add_argument( + '--output_node_names', + type=str, + default='', + help='The name of the output nodes, comma separated.') + parser.add_argument( + '--placeholder_type_enum', + type=int, + default=dtypes.float32.as_datatype_enum, + help='The AttrValue enum to use for placeholders.') + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..7b36dc5b1b59be94f93f1da132bdbdcf166bb32b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tools/strip_unused_lib.py @@ -0,0 +1,121 @@ +# pylint: disable=g-bad-file-header +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities to remove unneeded nodes from a GraphDefs.""" + +import copy + +from google.protobuf import text_format + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python.framework import graph_util +from tensorflow.python.platform import gfile + + +def strip_unused(input_graph_def, input_node_names, output_node_names, + placeholder_type_enum): + """Removes unused nodes from a GraphDef. + + Args: + input_graph_def: A graph with nodes we want to prune. + input_node_names: A list of the nodes we use as inputs. + output_node_names: A list of the output nodes. + placeholder_type_enum: The AttrValue enum for the placeholder data type, or + a list that specifies one value per input node name. + + Returns: + A `GraphDef` with all unnecessary ops removed. + + Raises: + ValueError: If any element in `input_node_names` refers to a tensor instead + of an operation. + KeyError: If any element in `input_node_names` is not found in the graph. + """ + for name in input_node_names: + if ":" in name: + raise ValueError(f"Name '{name}' appears to refer to a Tensor, not an " + "Operation.") + + # Here we replace the nodes we're going to override as inputs with + # placeholders so that any unused nodes that are inputs to them are + # automatically stripped out by extract_sub_graph(). + not_found = {name for name in input_node_names} + inputs_replaced_graph_def = graph_pb2.GraphDef() + for node in input_graph_def.node: + if node.name in input_node_names: + not_found.remove(node.name) + placeholder_node = node_def_pb2.NodeDef() + placeholder_node.op = "Placeholder" + placeholder_node.name = node.name + if isinstance(placeholder_type_enum, list): + input_node_index = input_node_names.index(node.name) + placeholder_node.attr["dtype"].CopyFrom( + attr_value_pb2.AttrValue(type=placeholder_type_enum[ + input_node_index])) + else: + placeholder_node.attr["dtype"].CopyFrom( + attr_value_pb2.AttrValue(type=placeholder_type_enum)) + if "_output_shapes" in node.attr: + placeholder_node.attr["_output_shapes"].CopyFrom(node.attr[ + "_output_shapes"]) + if "shape" in node.attr: + placeholder_node.attr["shape"].CopyFrom(node.attr["shape"]) + inputs_replaced_graph_def.node.extend([placeholder_node]) + else: + inputs_replaced_graph_def.node.extend([copy.deepcopy(node)]) + + if not_found: + raise KeyError(f"The following input nodes were not found: {not_found}.") + + output_graph_def = graph_util.extract_sub_graph(inputs_replaced_graph_def, + output_node_names) + return output_graph_def + + +def strip_unused_from_files(input_graph, input_binary, output_graph, + output_binary, input_node_names, output_node_names, + placeholder_type_enum): + """Removes unused nodes from a graph file.""" + + if not gfile.Exists(input_graph): + print("Input graph file '" + input_graph + "' does not exist!") + return -1 + + if not output_node_names: + print("You need to supply the name of a node to --output_node_names.") + return -1 + + input_graph_def = graph_pb2.GraphDef() + mode = "rb" if input_binary else "r" + with gfile.GFile(input_graph, mode) as f: + if input_binary: + input_graph_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read(), input_graph_def) + + output_graph_def = strip_unused(input_graph_def, + input_node_names.split(","), + output_node_names.split(","), + placeholder_type_enum) + + if output_binary: + with gfile.GFile(output_graph, "wb") as f: + f.write(output_graph_def.SerializeToString()) + else: + with gfile.GFile(output_graph, "w") as f: + f.write(text_format.MessageToString(output_graph_def)) + print("%d ops in the final graph." % len(output_graph_def.node)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2652b57cb6e989ef79e659ae876d610785e1420b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Ops related to Tensor Processing Units.""" + +import os +os.environ['TPU_ML_PLATFORM'] = 'Tensorflow' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/api.py new file mode 100644 index 0000000000000000000000000000000000000000..196c8779658fa7cf19a45cabcee8c76085f2a077 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/api.py @@ -0,0 +1,32 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Modules that need to be exported to the API. + +List TPU modules that aren't included elsewhere here so that they can be scanned +for tf_export decorations. +""" + +# pylint: disable=unused-import +from tensorflow.python.tpu import bfloat16 +from tensorflow.python.tpu import feature_column_v2 +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_embedding +from tensorflow.python.tpu import tpu_embedding_for_serving +from tensorflow.python.tpu import tpu_embedding_v1 +from tensorflow.python.tpu import tpu_embedding_v2 +from tensorflow.python.tpu import tpu_embedding_v2_utils +from tensorflow.python.tpu import tpu_hardware_feature +from tensorflow.python.tpu import tpu_optimizer +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/async_checkpoint.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/async_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..768e46e79e0941d8c338c742fe2dcad9b0a3b48b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/async_checkpoint.py @@ -0,0 +1,269 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Hook for asynchronous checkpointing. + +This hook dispatches checkpoint writing operations in a separate thread to +allow execution to continue on the main thread. +""" + +import os +import threading +import time +from typing import Any, List, Optional, Text + +from tensorflow.core.util import event_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.framework import meta_graph +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import monitored_session +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.training import session_run_hook +from tensorflow.python.training import training_util +from tensorflow.python.training.summary_io import SummaryWriterCache + + +# Captures the timestamp of the first Saver object instantiation or end of a +# save operation. Can be accessed by multiple Saver instances. +_END_TIME_OF_LAST_WRITE = None +_END_TIME_OF_LAST_WRITE_LOCK = threading.Lock() + +# API label for cell names used in TF1 async checkpoint metrics. +_ASYNC_CHECKPOINT_V1 = "async_checkpoint_v1" + + +def _get_duration_microseconds(start_time_seconds, end_time_seconds) -> int: + """Returns the duration between start and end time in microseconds.""" + return max(int((end_time_seconds - start_time_seconds) * 1000000), 0) + + +class AsyncCheckpointSaverHook(basic_session_run_hooks.CheckpointSaverHook): + """Saves checkpoints every N steps or seconds.""" + + def __init__(self, + checkpoint_dir: Text, + save_secs: Optional[int] = None, + save_steps: Optional[int] = None, + saver: Optional[saver_lib.Saver] = None, + checkpoint_basename: Text = "model.ckpt", + scaffold: Optional[monitored_session.Scaffold] = None, + listeners: Optional[List[ + basic_session_run_hooks.CheckpointSaverListener]] = None): + """Initializes a `CheckpointSaverHook`. + + Args: + checkpoint_dir: `str`, base directory for the checkpoint files. + save_secs: `int`, save every N secs. + save_steps: `int`, save every N steps. + saver: `Saver` object, used for saving. + checkpoint_basename: `str`, base name for the checkpoint files. + scaffold: `Scaffold`, use to get saver object. + listeners: List of `CheckpointSaverListener` subclass instances. Used for + callbacks that run immediately before or after this hook saves the + checkpoint. + + Raises: + ValueError: One of `save_steps` or `save_secs` should be set. + ValueError: At most one of `saver` or `scaffold` should be set. + """ + save_path = os.path.join(checkpoint_dir, checkpoint_basename) + logging.info("Create AsyncCheckpointSaverHook saving to path\n%s", + save_path) + if listeners: + logging.info(" with %d listener(s).", len(listeners)) + if saver is not None and scaffold is not None: + raise ValueError("You cannot provide both saver and scaffold.") + self._saver = saver + self._save_thread = None + self._write_graph_thread = None + self._checkpoint_dir = checkpoint_dir + self._save_path = save_path + self._scaffold = scaffold + self._timer = basic_session_run_hooks.SecondOrStepTimer( + every_secs=save_secs, every_steps=save_steps) + self._listeners = listeners or [] + self._steps_per_run = 1 + self._summary_writer = None + self._global_step_tensor = None + + self._last_checkpoint_step = None + + # Initialize the first timestamp for _END_TIME_OF_LAST_WRITE. + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + if _END_TIME_OF_LAST_WRITE is None: + _END_TIME_OF_LAST_WRITE = time.time() + + def _set_steps_per_run(self, steps_per_run): + self._steps_per_run = steps_per_run + + def begin(self): + self._summary_writer = SummaryWriterCache.get(self._checkpoint_dir) + self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access + if self._global_step_tensor is None: + raise RuntimeError( + "Global step should be created to use CheckpointSaverHook.") + for l in self._listeners: + l.begin() + + def after_create_session(self, session: session_lib.Session, coord: Any): + global_step = session.run(self._global_step_tensor) + + # We do write graph and saver_def at the first call of before_run. + # We cannot do this in begin, since we let other hooks to change graph and + # add variables in begin. Graph is finalized after all begin calls. + def _write_graph_fn(self): + training_util.write_graph( + ops.get_default_graph().as_graph_def(add_shapes=True), + self._checkpoint_dir, "graph.pbtxt") + self._write_graph_thread = threading.Thread(target=_write_graph_fn, + args=[self]) + self._write_graph_thread.start() + + saver_def = self._get_saver().saver_def if self._get_saver() else None + graph = ops.get_default_graph() + meta_graph_def = meta_graph.create_meta_graph_def( + graph_def=graph.as_graph_def(add_shapes=True), saver_def=saver_def) + if self._summary_writer is None: + raise ValueError("Summary writer is not initialised") + self._summary_writer.add_graph(graph) + self._summary_writer.add_meta_graph(meta_graph_def) + # The checkpoint saved here is the state at step "global_step". + self._save(session, global_step) + self._timer.update_last_triggered_step(global_step) + + def before_run(self, run_context: Any): # pylint: disable=unused-argument + return session_run_hook.SessionRunArgs(self._global_step_tensor) + + def after_run(self, run_context: session_run_hook.SessionRunContext, + run_values: Any): + global_step = run_context.session.run(self._global_step_tensor) + if self._timer.should_trigger_for_step(global_step): + self._timer.update_last_triggered_step(global_step) + logging.info("Triggering checkpoint. %s", global_step) + if self._save(run_context.session, global_step): + run_context.request_stop() + + def end(self, session: session_lib.Session): + if self._save_thread: + logging.info("Waiting for any pending checkpoints to finish.") + self._save_thread.join() + if self._write_graph_thread: + logging.info("Waiting for any pending write_graph to finish.") + self._write_graph_thread.join() + + last_step = session.run(self._global_step_tensor) + + if self._last_checkpoint_step != last_step: + self._save(session, last_step, asynchronous=False) + + for l in self._listeners: + l.end(session, last_step) + + def _save(self, session, step, asynchronous=True): + """Saves the latest checkpoint, returns should_stop.""" + + def _save_fn(): + """Run the saver process.""" + logging.info("Saving checkpoints for %d into %s.", step, self._save_path) + + start_time = time.time() + for l in self._listeners: + l.before_save(session, step) + + self._get_saver().save(session, self._save_path, global_step=step) + if self._summary_writer is None: + raise ValueError("Summary writer is not initialised") + self._summary_writer.add_session_log( + event_pb2.SessionLog( + status=event_pb2.SessionLog.CHECKPOINT, + checkpoint_path=self._save_path), step) + + for l in self._listeners: + l.after_save(session, step) + + # Measure the async checkpoint write duration, i.e., non-blocking time. + end_time = time.time() + metrics.AddAsyncCheckpointWriteDuration( + api_label=_ASYNC_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(start_time, end_time)) + + # Measure the elapsed time since the last checkpoint. + # Due to the nature of async checkpoint, here it actually captures the + # duration between the start_time of the previous checkpoint and the start + # time of this checkpoint. As a result, the duration of the final async + # checkpoint is excluded, which is fine since it does not take much time. + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + metrics.AddTrainingTimeSaved( + api_label=_ASYNC_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(_END_TIME_OF_LAST_WRITE, + start_time)) + _END_TIME_OF_LAST_WRITE = start_time + + logging.info("Checkpoint actual writing time: (%.3f sec)", + end_time - start_time) + logging.info("Checkpoint finished for %d into %s.", step, self._save_path) + + # Measure the checkpoint write duration that is blocking the main thread. + blocking_start_time = time.time() + def end_of_blocking_time(): + blocking_end_time = time.time() + metrics.AddCheckpointWriteDuration( + api_label=_ASYNC_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(blocking_start_time, + blocking_end_time)) + + if not asynchronous: + self._last_checkpoint_step = step + _save_fn() + end_of_blocking_time() + return + + if self._save_thread is not None: + self._save_thread.join(timeout=0.1) + if self._save_thread.is_alive(): + logging.info("Saver thread still in progress, skipping checkpoint.") + end_of_blocking_time() + return + + self._last_checkpoint_step = step + self._save_thread = threading.Thread(target=_save_fn) + self._save_thread.start() + end_of_blocking_time() + + def _get_saver(self): + if self._saver is not None: + return self._saver + elif self._scaffold is not None: + return self._scaffold.saver + + # Get saver from the SAVERS collection if present. + collection_key = ops.GraphKeys.SAVERS + savers = ops.get_collection(collection_key) + if not savers: + raise RuntimeError( + "No items in collection {}. Please add a saver to the collection " + "or provide a saver or scaffold.".format(collection_key)) + elif len(savers) > 1: + raise RuntimeError( + "More than one item in collection {}. " + "Please indicate which one to use by passing it to the constructor." + .format(collection_key)) + + self._saver = savers[0] + return savers[0] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/bfloat16.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/bfloat16.py new file mode 100644 index 0000000000000000000000000000000000000000..284695158f8fc35fdbd14abdb1a1ac96d3ce43bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/bfloat16.py @@ -0,0 +1,88 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Helper context for running models with bfloat16.""" + +from typing import Generator, Optional, Text + +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + + +def _get_custom_getter(): + """Returns a custom getter that this class's methods must be called under. + + All methods of this class must be called under a variable scope that was + passed this custom getter. Example: + + ```python + network = ConvNetBuilder(...) + with tf.compat.v1.variable_scope('cg', + custom_getter=network.get_custom_getter()): + network.conv(...) + # Call more methods of network here + ``` + + Currently, this custom getter only does anything if self.use_tf_layers is + True. In that case, it causes variables to be stored as dtype + self.variable_type, then casted to the requested dtype, instead of directly + storing the variable as the requested dtype. + """ + + def inner_custom_getter(getter, *args, **kwargs): + """Custom getter that forces variables to have type self.variable_type.""" + cast_to_bfloat16 = False + requested_dtype = kwargs['dtype'] + if requested_dtype == dtypes.bfloat16: + # Only change the variable dtype if doing so does not decrease variable + # precision. + kwargs['dtype'] = dtypes.float32 + cast_to_bfloat16 = True + var = getter(*args, **kwargs) + # This if statement is needed to guard the cast, because batch norm + # assigns directly to the return value of this custom getter. The cast + # makes the return value not a variable so it cannot be assigned. Batch + # norm variables are always in fp32 so this if statement is never + # triggered for them. + if cast_to_bfloat16: + var = math_ops.cast(var, dtypes.bfloat16) + return var + + return inner_custom_getter + + +@tf_export(v1=['tpu.bfloat16_scope']) +@tf_contextlib.contextmanager +def bfloat16_scope( + name: Optional[Text] = None +) -> Generator[variable_scope.variable_scope, None, None]: + """Scope class for bfloat16 variables so that the model uses custom getter. + + This enables variables to be read as bfloat16 type when using get_variable. + + Arguments: + name: Name to use for scope. + + Yields: + a variable scope. + """ + if name is None: + name = '' + with variable_scope.variable_scope( + name, custom_getter=_get_custom_getter()) as varscope: + yield varscope diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/datasets.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..3481acc0eb895c154652e246dcb99b86e7c15d0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/datasets.py @@ -0,0 +1,202 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Library of Cloud TPU helper functions for data loading.""" + +from typing import Callable, Optional, Text, Union + +from tensorflow.python.data.experimental.ops import interleave_ops +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import readers +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.ops import functional_ops +from tensorflow.python.types import data as data_types + + +def _TextLineDataset(filename: Text) -> dataset_ops.Dataset: + buffer_size = 8 * 1024 * 1024 # 8 MiB per file + dataset = readers.TextLineDataset(filename, buffer_size=buffer_size) + return dataset + + +def _TFRecordDataset(filename: Text) -> dataset_ops.Dataset: + buffer_size = 8 * 1024 * 1024 # 8 MiB per file + dataset = readers.TFRecordDataset(filename, buffer_size=buffer_size) + return dataset + + +_FILETYPE_MAP = { + 'tfrecord': _TFRecordDataset, + 'textline': _TextLineDataset, + 'text': _TextLineDataset, +} + + +def StreamingFilesDataset( + files: Union[Text, dataset_ops.Dataset], + filetype: Optional[Union[Text, Callable[[Text], + dataset_ops.Dataset]]] = None, + file_reader_job: Optional[Text] = None, + worker_job: Optional[Text] = None, + num_epochs: Optional[int] = None, + filename_shuffle_buffer_size: Optional[Union[int, bool]] = None, + num_parallel_reads: Optional[int] = None, + batch_transfer_size: Optional[Union[int, bool]] = None, + sloppy: bool = True) -> dataset_ops.Dataset: + """StreamingFilesDataset constructs a dataset to stream from workers (GCE VM). + + Because Cloud TPUs are allocated over the network, a Cloud TPU cannot read + files local to your GCE VM. In order to train using files stored on your local + VM (e.g. on local SSD for extreme performance), use the StreamingFilesDataset + helper to generate a dataset to feed your Cloud TPU with files from your GCE + VM. + + The resulting dataset may return an OutOfRangeError if there are no files + found as a result of the fileglob expansion. + + Note: StreamingFilesDataset assumes that the session is using a + TPUClusterResolver and has therefore a worker and a coordinator job. File + loading will be done on the coordinator job. + + Args: + files: A string glob to match files, or a `tf.data.Dataset` generating file + names. + filetype: A string (one of 'tfrecord', or 'textline') or a single-argument + TensorFlow function that when given a filename returns a dataset. + file_reader_job: An optional string that corresponds to the job that should + perform the file reads. + worker_job: An optional string that corresponds to the job that should + process the tensors (i.e. your GPU or TPU worker). + num_epochs: The number of epochs through the training set that should be + generated. By default, it will repeat infinitely. + filename_shuffle_buffer_size: An optional integer whose value controls the + shuffling of the file names. If you would like to read from the files in + the same order, set to 0 or False. + num_parallel_reads: An optional integer controlling the number of files to + read from concurrently. (Set to 1 for no parallelism.) + batch_transfer_size: An optional integer controlling the batching used to + amortize the remote function invocation overhead. Set to a very large + number to increase throughput. Set to a very small number to reduce memory + consumption. Set to False to skip batching. + sloppy: (Optional.) If `False`, read input data while maintaining a + deterministic order. (This may have significant performance impacts.) + sloppy defaults to: True. + Returns: + A `tf.data.Dataset` with an infinite stream of elements generated by a + parallel interleaving of the set of files matched (or generated) by `files` + with a type is the output of the dataset specified by `filetype`. + + Raises: + ValueError: if any argument is not of the expected type. + """ + if filetype is None: + filetype = 'tfrecord' + + if isinstance(filetype, str): + if filetype not in _FILETYPE_MAP: + raise ValueError( + f'Unexpected filetype. Received: {filetype}. Expected one of ' + f'{list(_FILETYPE_MAP.keys())}') + reader_fn = _FILETYPE_MAP[filetype] + elif callable(filetype): + reader_fn = filetype + else: + raise ValueError(f'Argument `filetype` should be a string or a callable. ' + f'Received: {filetype} of type {type(filetype)}.') + + file_reader_job = file_reader_job or 'coordinator' + + worker_job = worker_job or 'worker' + + if filename_shuffle_buffer_size is None: + filename_shuffle_buffer_size = 4096 + + num_parallel_reads = num_parallel_reads or 8 + + if batch_transfer_size is None: + batch_transfer_size = 256 + + if file_reader_job == 'coordinator': + file_reader_device = '/job:coordinator/task:0' + else: + file_reader_device = '/job:%s' % file_reader_job + + with ops.device(file_reader_device): + if isinstance(files, str): + source_dataset = dataset_ops.Dataset.list_files(files) + elif isinstance(files, data_types.DatasetV2): + source_dataset = files + else: + raise ValueError( + 'Argument `files` should be a string or a `tf.data.Dataset` ' + f'instance. Received: {files}') + + if filename_shuffle_buffer_size: + source_dataset = source_dataset.shuffle( + buffer_size=filename_shuffle_buffer_size) + + source_dataset = source_dataset.apply( + interleave_ops.parallel_interleave( + reader_fn, cycle_length=num_parallel_reads, sloppy=sloppy)) + + source_dataset = source_dataset.repeat(num_epochs) + + if batch_transfer_size: + source_dataset = source_dataset.batch(batch_transfer_size) + + source_dataset = source_dataset.prefetch(1) + + source_iterator = dataset_ops.make_one_shot_iterator(source_dataset) + source_handle = source_iterator.string_handle() + + @function.Defun(dtypes.string) + def LoadingFunc(h): + remote_iterator = iterator_ops.Iterator.from_string_handle( + h, dataset_ops.get_legacy_output_types(source_dataset), + dataset_ops.get_legacy_output_shapes(source_dataset)) + return remote_iterator.get_next() + + def MapFn(unused_input): + source_dataset_output_types = dataset_ops.get_legacy_output_types( + source_dataset) + if isinstance(source_dataset_output_types, dtypes.DType): + output_types = [source_dataset_output_types] + elif isinstance(source_dataset_output_types, (list, tuple)): + output_types = source_dataset_output_types + else: + raise ValueError('Source dataset has invalid output types. Only ' + 'list/tuples or TensorFlow tensor types are accepted.') + remote_calls = functional_ops.remote_call( + args=[source_handle], + Tout=output_types, + f=LoadingFunc, + target='/job:%s/replica:0/task:0/cpu:0' % file_reader_job) + if len(remote_calls) == 1: + return remote_calls[0] + else: + return remote_calls + + with ops.device('/job:%s' % worker_job): + output_dataset = dataset_ops.Dataset.range(2).repeat().map( + MapFn, num_parallel_calls=4 if sloppy else None) + output_dataset = output_dataset.prefetch(1) + + if batch_transfer_size: + # Undo the batching used during the transfer. + output_dataset = output_dataset.unbatch().prefetch(1) + + return output_dataset diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/device_assignment.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/device_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..390aa7210fa2be62a331fa59fdf0d44e665b473f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/device_assignment.py @@ -0,0 +1,569 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Library of TPU helper functions.""" + +import enum +import math +from typing import List, Optional, Tuple + +import numpy as np + +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu.topology import Topology +from tensorflow.python.util.tf_export import tf_export + + +SINGLE_CORE_ASSIGNMENT = [[[0, 0, 0, 0]]] + + +def _compute_task_and_cores_to_replicas(core_assignment, topology): + """Computes a nested dict which maps task and logical core to replicas.""" + task_and_cores_to_replicas = {} + for replica in range(core_assignment.shape[0]): + for logical_core in range(core_assignment.shape[1]): + coordinates = core_assignment[replica, logical_core, :] + task_id = topology.task_ordinal_at_coordinates(coordinates) + if task_id not in task_and_cores_to_replicas: + task_and_cores_to_replicas[task_id] = {} + if logical_core not in task_and_cores_to_replicas[task_id]: + task_and_cores_to_replicas[task_id][logical_core] = set() + + task_and_cores_to_replicas[task_id][logical_core].add(replica) + + task_to_sorted_replica_id = {} + + for task, core_to_replicas in task_and_cores_to_replicas.items(): + core_to_sorted_replicas = {} + for core, replicas in core_to_replicas.items(): + core_to_sorted_replicas[core] = sorted(replicas) + + task_to_sorted_replica_id[task] = core_to_sorted_replicas + return task_to_sorted_replica_id + + +@tf_export("tpu.experimental.DeviceOrderMode") +class DeviceOrderMode(enum.IntEnum): + """The way of determining device orders when computing device assignment.""" + # By default the mode is set to AUTO, the library will choose to form rings + # when that is possible. + AUTO = 0 + # Form rings for replicas and model-parallel cores. + RING = 1 + # Form meshes for replicas and/or model-parallel cores. + MESH = 2 + + +@tf_export("tpu.experimental.DeviceAssignment") +class DeviceAssignment(object): + """Mapping from logical cores in a computation to the physical TPU topology. + + Prefer to use the `DeviceAssignment.build()` helper to construct a + `DeviceAssignment`; it is easier if less flexible than constructing a + `DeviceAssignment` directly. + """ + + def __init__(self, topology: Topology, core_assignment: np.ndarray): + """Constructs a `DeviceAssignment` object. + + Args: + topology: A `Topology` object that describes the physical TPU topology. + core_assignment: A logical to physical core mapping, represented as a + rank 3 numpy array. See the description of the `core_assignment` + property for more details. + + Raises: + ValueError: If `topology` is not `Topology` object. + ValueError: If `core_assignment` is not a rank 3 numpy array. + """ + if not isinstance(topology, Topology): + raise ValueError("topology must be a Topology object, got {}".format( + type(topology))) + core_assignment = np.asarray(core_assignment, dtype=np.int32) + + self._topology = topology + + if core_assignment.ndim != 3: + raise ValueError("core_assignment must be a rank 3 numpy array, " + f"got shape {core_assignment.shape}") + + self._num_replicas = core_assignment.shape[0] + self._num_cores_per_replica = core_assignment.shape[1] + + if core_assignment.shape[-1] != topology.mesh_rank: + raise ValueError( + "core_assignment.shape[-1] must have size equal to topology " + f"rank ({topology.mesh_rank}), got " + f"core_assignment.shape={core_assignment.shape}") + + self._core_assignment = core_assignment + self._task_and_cores_to_replicas = _compute_task_and_cores_to_replicas( + self._core_assignment, topology) + + @property + def topology(self) -> Topology: + """A `Topology` that describes the TPU topology.""" + return self._topology + + @property + def num_cores_per_replica(self) -> int: + """The number of cores per replica.""" + return self._num_cores_per_replica + + @property + def num_replicas(self) -> int: + """The number of replicas of the computation.""" + return self._num_replicas + + @property + def core_assignment(self) -> np.ndarray: + """The logical to physical core mapping. + + Returns: + An integer numpy array of rank 3, with shape + `[num_replicas, num_cores_per_replica, topology_rank]`. Maps + (replica, logical core) pairs to physical topology coordinates. + """ + return self._core_assignment + + def coordinates(self, replica: int, logical_core: int) -> Tuple: # pylint:disable=g-bare-generic + """Returns the physical topology coordinates of a logical core.""" + return tuple(self.core_assignment[replica, logical_core, :]) + + def lookup_replicas(self, task_id: int, logical_core: int) -> List[int]: + """Lookup replica ids by task number and logical core. + + Args: + task_id: TensorFlow task number. + logical_core: An integer, identifying a logical core. + Returns: + A sorted list of the replicas that are attached to that task and + logical_core. + Raises: + ValueError: If no replica exists in the task which contains the logical + core. + """ + try: + return self._task_and_cores_to_replicas[task_id][logical_core] + except KeyError: + raise ValueError( + "Can not find any replica in task: {} contains logical_core: {} ". + format(task_id, logical_core)) + + def tpu_ordinal(self, replica: int = 0, logical_core: int = 0) -> int: + """Returns the ordinal of the TPU device assigned to a logical core.""" + coordinates = self.coordinates(replica, logical_core) + return self._topology.tpu_device_ordinal_at_coordinates(coordinates) + + def host_device(self, + replica: int = 0, + logical_core: int = 0, + job: Optional[str] = None) -> str: + """Returns the CPU device attached to a logical core.""" + coordinates = self.coordinates(replica, logical_core) + return self._topology.cpu_device_name_at_coordinates(coordinates, job=job) + + def tpu_device(self, + replica: int = 0, + logical_core: int = 0, + job: Optional[str] = None) -> str: + """Returns the name of the TPU device assigned to a logical core.""" + coordinates = self.coordinates(replica, logical_core) + return self._topology.tpu_device_name_at_coordinates(coordinates, job=job) + + @classmethod + def build( + cls, + topology: Topology, + computation_shape: Optional[np.ndarray] = None, + computation_stride: Optional[np.ndarray] = None, + num_replicas: int = 1, + device_order_mode: DeviceOrderMode = DeviceOrderMode.AUTO, + ) -> "DeviceAssignment": + return device_assignment( + topology=topology, + computation_shape=computation_shape, + computation_stride=computation_stride, + num_replicas=num_replicas, + device_order_mode=device_order_mode, + ) + + +def _open_ring_2d(x_size: int, y_size: int, + z_coord: int) -> List[Tuple[int, int, int]]: + """Ring-order of a X by Y mesh, with a fixed Z coordinate. + + For example, in a 4x4 mesh, this returns the following order. + 0 -- 1 -- 2 -- 3 + | | | | + 15-- 6 -- 5 -- 4 + | | | | + 14-- 7 -- 8 -- 9 + | | | | + 13-- 12-- 11-- 10 + + Note that chip 0 is not included in the output. + + Args: + x_size: An integer represents the mesh size in the x-dimension. Must be + larger than 1. + y_size: An integer represents the mesh size in the y-dimension. Must be + larger than 1. + z_coord: An integer represents the z-coordinate to use for the chips in the + ring. + + Returns: + A list of (x,y,z) triples in ring order. + """ + ret = [] + for i in range(y_size // 2): + for j in range(1, x_size): + ret.append((j, 2 * i, z_coord)) + for j in range(x_size - 1, 0, -1): + ret.append((j, 2 * i + 1, z_coord)) + for i in range(y_size - 1, 0, -1): + ret.append((0, i, z_coord)) + return ret + + +def _ring_3d(x_size: int, y_size: int, + z_size: int) -> List[Tuple[int, int, int]]: + """Ring-order of a X by Y by Z mesh. + + Constructs the 3d ring from 2d rings that are stacked in the Z dimension and + joined in one corner. + + z == 0: + 0 -- 1 -- 2 -- 3 + | | | | + 15 - 6 -- 5 -- 4 + | | | | + 14 - 7 -- 8 -- 9 + | | | | + 13 - 12 - 11 - 10 + z == 1: + 63 - 30 - 29 - 28 + | | | | + 16 - 25 - 26 - 27 + | | | | + 17 - 24 - 23 - 22 + | | | | + 18 - 19 - 20 - 21 + z == 2: + 62 - 31 - 32 - 33 + | | | | + 45 - 36 - 35 - 34 + | | | | + 44 - 37 - 38 - 39 + | | | | + 43 - 42 - 41 - 40 + z == 3: + 61 - 60 - 59 - 58 + | | | | + 46 - 55 - 56 - 57 + | | | | + 47 - 54 - 53 - 52 + | | | | + 48 - 49 - 50 - 51 + + Args: + x_size: An integer represents the mesh size in the x-dimension. Must be + larger than 1. + y_size: An integer represents the mesh size in the y-dimension. Must be + larger than 1. + z_size: An integer represents the mesh size in the z-dimension. Must be + larger than 1. For example, in a 4x4x4 mesh, this returns the following + order. + + Returns: + A list of (x,y,z) triples in ring order. + """ + + # Handle the case where 2 dimensions are size 1. + if x_size == 1 and y_size == 1: + return [(0, 0, i) for i in range(z_size)] + if x_size == 1 and z_size == 1: + return [(0, i, 0) for i in range(y_size)] + if y_size == 1 and z_size == 1: + return [(i, 0, 0) for i in range(x_size)] + + # Handle odd mesh dimensions. This never happens in practice, so we don't + # bother to try building something optimal. + if (x_size > 1 and x_size % 2 != 0) or (y_size > 1 and + y_size % 2 != 0) or (z_size > 1 and + z_size % 2 != 0): + logging.warning("Odd dimension") + ret = [] + for z in range(z_size): + for y in range(y_size): + ret.extend((x, y, z) for x in range(x_size)) + return ret + + # Always start with chip 0. + ret = [(0, 0, 0)] + # Handle the case where one dimension is size 1. We just build a flat, 2d + # ring. + if z_size == 1: + ret.extend(_open_ring_2d(x_size, y_size, 0)) + return ret + if y_size == 1: + ret = [(0, 0, 0)] + ret.extend((x, y, z) for (x, z, y) in _open_ring_2d(x_size, z_size, 0)) + return ret + if x_size == 1: + ret = [(0, 0, 0)] + ret.extend((x, y, z) for (y, z, x) in _open_ring_2d(y_size, z_size, 0)) + return ret + + # Handle the case where all dimensions have size > 1 and even. + ret = [(0, 0, 0)] + for i in range(0, z_size): + r = _open_ring_2d(x_size, y_size, i) + if i % 2 == 0: + ret.extend(r) + else: + ret.extend(reversed(r)) + for i in range(z_size - 1, 0, -1): + ret.append((0, 0, i)) + return ret + + +def device_assignment( + topology: Topology, + computation_shape: Optional[np.ndarray] = None, + computation_stride: Optional[np.ndarray] = None, + num_replicas: int = 1, + device_order_mode: DeviceOrderMode = DeviceOrderMode.AUTO, +) -> DeviceAssignment: + """Computes a device_assignment of a computation across a TPU topology. + + Attempts to choose a compact grid of cores for locality. + + Returns a `DeviceAssignment` that describes the cores in the topology assigned + to each core of each replica. + + `computation_shape` and `computation_stride` values should be powers of 2 for + optimal packing. + + Args: + topology: A `Topology` object that describes the TPU cluster topology. To + obtain a TPU topology, evaluate the `Tensor` returned by + `initialize_system` using `Session.run`. Either a serialized + `TopologyProto` or a `Topology` object may be passed. Note: you must + evaluate the `Tensor` first; you cannot pass an unevaluated `Tensor` + here. + computation_shape: A rank 1 int32 numpy array with size equal to the + topology rank, describing the shape of the computation's block of cores. + If None, the `computation_shape` is `[1] * topology_rank`. + computation_stride: A rank 1 int32 numpy array of size `topology_rank`, + describing the inter-core spacing of the `computation_shape` cores in the + TPU topology. If None, the `computation_stride` is `[1] * topology_rank`. + num_replicas: The number of computation replicas to run. The replicas will + be packed into the free spaces of the topology. + device_order_mode: An enum of `DeviceOrderMode` class which indicates + whether to assign devices to form rings or meshes, or let the library to + choose. + + Returns: + A DeviceAssignment object, which describes the mapping between the logical + cores in each computation replica and the physical cores in the TPU + topology. + + Raises: + ValueError: If `topology` is not a valid `Topology` object. + ValueError: If `computation_shape` or `computation_stride` are not 1D int32 + numpy arrays with shape [3] where all values are positive. + ValueError: If computation's replicas cannot fit into the TPU topology. + """ + # Deserialize the Topology proto, if it is a string. + if isinstance(topology, bytes): + topology = Topology(serialized=topology) + + if not isinstance(topology, Topology): + raise ValueError( + f"`topology` is not a Topology object; got {type(topology)}") + + topology_rank = len(topology.mesh_shape) + mesh_shape = topology.mesh_shape + if computation_shape is None: + computation_shape = np.array([1] * topology_rank, dtype=np.int32) + else: + computation_shape = np.asarray(computation_shape, dtype=np.int32) + + if computation_stride is None: + computation_stride = np.array([1] * topology_rank, dtype=np.int32) + else: + computation_stride = np.asarray(computation_stride, dtype=np.int32) + + if computation_shape.shape != (topology_rank,): + raise ValueError( + f"computation_shape must have shape [{topology_rank}]; " + f"got {computation_shape.shape}" + ) + if computation_stride.shape != (topology_rank,): + raise ValueError( + f"computation_stride must have shape [{topology_rank}]; " + f"got {computation_stride.shape}" + ) + + if any(computation_shape < 1): + raise ValueError( + "computation_shape must be positive; got computation_shape={}".format( + computation_shape)) + if any(computation_stride < 1): + raise ValueError( + "computation_stride must be positive; got computation_stride={}".format( + computation_stride)) + + # Computes the physical size of one computation instance. + computation_footprint = computation_shape * computation_stride + if any(computation_footprint > mesh_shape): + raise ValueError( + "computation footprint {} does not fit in TPU topology shape {}".format( + computation_footprint, mesh_shape)) + + # Computes how many copies of the computation footprint fit in the mesh. + block_counts = mesh_shape // computation_footprint + + replica_counts = block_counts * computation_stride + max_replicas = np.prod(replica_counts) + if num_replicas > max_replicas: + raise ValueError( + "requested {} replicas but only {} replicas with shape {} and " + "computation_stride {} fit in a TPU mesh of shape {}".format( + num_replicas, max_replicas, computation_shape, computation_stride, + mesh_shape)) + + def ceil_of_ratio(n, m): + return (n + m - 1) // m + + if topology.missing_devices.size == 0: + replica_shape = [0] * topology_rank + if num_replicas > 0: + remaining_replicas = num_replicas + remaining_dims = topology_rank + + # Choose dimensions as close to an equal cube as possible, + # in order of increasing dimension size. By visiting dimensions + # in increasing size, we assign the most constrained dimension + # first, so we won't make infeasible choices. + # + # As a secondary sort order, visit the last dimension (core index) first, + # then the other dimensions in increasing order. This means we try to use + # both cores on the same chip in preference to two cores on different + # chips. We visit the x dimension first, and the z dimension last, so + # that we prefer to arrange adjacent replicas on the same machine when + # possible. + # + # For example, if num_replicas == 4, we prefer to use a replica_shape of + # (2,1,1,2) over (1,1,2,2). + + for x, ni in sorted(((x, ((i + 1) % topology_rank)) + for (i, x) in enumerate(replica_counts))): + i = (ni + topology_rank - 1) % topology_rank + target_size = int(math.ceil(remaining_replicas**(1.0 / remaining_dims))) + replica_shape[i] = min(target_size, x) + remaining_replicas = ceil_of_ratio(remaining_replicas, replica_shape[i]) + remaining_dims -= 1 + + assert remaining_replicas == 1 and remaining_dims == 0 + + # Assigns an offset to each replica such that no two replicas overlap. + replica_offsets = np.full([num_replicas, topology_rank], -1, dtype=np.int32) + + enable_3d_tiling = ( + topology_rank == 4 and + computation_shape[-1] == mesh_shape[-1] # Only handle 3D case. + and np.prod(computation_stride) == 1 # Ensure no stride. + and num_replicas == max_replicas) # Full replication. + + if device_order_mode != DeviceOrderMode.AUTO: + if device_order_mode == DeviceOrderMode.RING and not enable_3d_tiling: + raise ValueError( + "device_order_mode=DeviceOrderMode.RING is not compatible with the " + "3D tiling current topology. Try setting " + "device_order_mode=DeviceOrderMode.AUTO" + ) + enable_3d_tiling = device_order_mode == DeviceOrderMode.RING + + if enable_3d_tiling: + assignment = [] + inner_ring = _ring_3d(computation_shape[0], computation_shape[1], + computation_shape[2]) + outer_ring = _ring_3d(replica_shape[0], replica_shape[1], + replica_shape[2]) + + for replica in range(num_replicas): + outer_x, outer_y, outer_z = outer_ring[replica] + per_replica_assignment = [] + for index in range(np.prod(computation_shape)): + inner_x, inner_y, inner_z = inner_ring[index // mesh_shape[-1]] + px = outer_x * computation_shape[0] + inner_x + py = outer_y * computation_shape[1] + inner_y + pz = outer_z * computation_shape[2] + inner_z + pi = index % mesh_shape[-1] + per_replica_assignment.append([px, py, pz, pi]) + assignment.append(per_replica_assignment) + else: + for replica in range(num_replicas): + # Chooses a replica number in each axis. + t = replica + pos = [] + # Visit the core number first. + for dim in np.concatenate([[replica_shape[-1]], replica_shape[:-1]]): + pos.append(t % dim) + t //= dim + replica_pos = np.concatenate([pos[1:], [pos[0]]]) + + # Determines where that replica starts in each axis. + outer = replica_pos // computation_stride + inner = replica_pos % computation_stride + replica_offsets[replica, :] = outer * computation_footprint + inner + + # Computes a logical core -> physical core mapping for each replica. + indices = [ + np.arange(0, computation_shape[i] * computation_stride[i], + computation_stride[i]) for i in range(topology_rank) + ] + indices = np.concatenate( + [i[..., np.newaxis] for i in np.meshgrid(*indices, indexing="ij")], + axis=-1) + indices = indices.reshape((-1, topology_rank)) + assignment = indices + replica_offsets[:, np.newaxis, :] + else: + # We have a slice with missing chips. We define a simple assignment by + # ignoring computation stride. This assignment should enable a consistent + # and correct device assignment on degraded slices. It is optimal when + # weights are not sharded. But this device assignment may be sub-optimal for + # other model parallelism scenarios. + assert np.prod(computation_stride) == 1 + # Next, we check if we have sufficient devices. + assert num_replicas * np.prod( + computation_shape) <= topology.num_tasks * topology.num_tpus_per_task + # Map replicas to physical devices in task order. + device_coordinates = topology.device_coordinates + assignment = [] + devices_per_replica = np.prod(computation_shape) + for rindex in range(num_replicas): + replica_assignment = [] + for index in range(devices_per_replica): + logical_id = rindex * devices_per_replica + index + # Pick logical cores in task order + task = logical_id // topology.num_tpus_per_task + device = logical_id % topology.num_tpus_per_task + # Append physical cores to the replica assignment + replica_assignment.append(device_coordinates[task, device, :]) + assignment.append(replica_assignment) + + return DeviceAssignment(topology, core_assignment=assignment) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/error_handling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/error_handling.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6660af511bc1c7a4bd0fe405c95e5c0a6a77bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/error_handling.py @@ -0,0 +1,19 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stub file to maintain backwards compatibility.""" + +# pylint: disable=wildcard-import,unused-import +from tensorflow_estimator.python.estimator.tpu.error_handling import * +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column.py new file mode 100644 index 0000000000000000000000000000000000000000..2dffcebf24e88e469909a97751fb7ecac4c7bf04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column.py @@ -0,0 +1,725 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""TPU Feature Column Library.""" +import math + +from tensorflow.python.feature_column import feature_column as fc +from tensorflow.python.feature_column import feature_column_lib as fc_lib +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_function +from tensorflow.python.tpu import tpu_replication +# pylint: disable=protected-access + + +_TPU_FC_TO_SCOPE = '_tpu_feature_column_scope' +_SUPPORTED_SEQUENCE_COLUMNS = (fc._SequenceCategoricalColumn, + fc_lib.SequenceCategoricalColumn) + + +# For V2 columns, we support anything that inherits from CategoricalColumn +# other than those in the denylist. User-provided columns that inherit from +# CategoricalColumn may or may not be compatible; it is up to the user to +# manage TPU compatibility for custom columns. +_SUPPORTED_CATEGORICAL_COLUMNS_V2 = (fc_lib.CategoricalColumn,) +_DENYLISTED_CATEGORICAL_COLUMNS_V2 = (fc_lib.HashedCategoricalColumn, + fc_lib.BucketizedColumn, + fc_lib.CrossedColumn) +_SUPPORTED_CATEGORICAL_COLUMNS = (fc._IdentityCategoricalColumn, + fc._VocabularyFileCategoricalColumn, + fc._VocabularyListCategoricalColumn, + fc._WeightedCategoricalColumn, + fc._SequenceCategoricalColumn + ) + _SUPPORTED_CATEGORICAL_COLUMNS_V2 +_SEQUENCE_FEATURE_LENGTH_POSTFIX = '_seq_length_' + + +def embedding_column(categorical_column, + dimension, + combiner='mean', + initializer=None, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + """TPU embedding_column for `tf.feature_column.embedding_column`. + + Note that the interface for TPU embedding_column is different from the non-TPU + version. The following args available for the non-TPU version are NOT + supported: ckpt_to_load_from, tensor_name_in_ckp, max_norm and trainable. + + Args: + categorical_column: A categorical_column returned from + categorical_column_with_identity, weighted_categorical_column, + categorical_column_with_vocabulary_file, + categorical_column_with_vocabulary_list, + sequence_categorical_column_with_identity, + sequence_categorical_column_with_vocabulary_file, + sequence_categorical_column_with_vocabulary_list + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries + in a single row for a non-sequence column. For more information, see + `tf.feature_column.embedding_column`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and + standard deviation `1/sqrt(dimension)`. + max_sequence_length: An non-negative integer specifying the max sequence + length. Any sequence shorter then this will be padded with 0 embeddings + and any sequence longer will be truncated. This must be positive for + sequence features and 0 for non-sequence features. + learning_rate_fn: A function that takes global step and returns learning + rate for the embedding table. If you intend to use the same learning rate + for multiple embedding tables, please ensure that you pass the exact same + python function to all calls of embedding_column, otherwise performence + may suffer. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A _TPUEmbeddingColumn. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if `initializer` is specified but not callable. + TypeError: if categorical_column is not a supported type. + """ + if isinstance(categorical_column, _DENYLISTED_CATEGORICAL_COLUMNS_V2): + raise TypeError('categorical_column for tpu ' + ' embedding_column was ' + f'denylisted type {type(categorical_column)}') + if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS): + raise TypeError( + 'categorical_column for tpu ' + ' embedding_column must be type {}, got {}.'.format(' or '.join([ + cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS + ]), type(categorical_column))) + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ' + 'Embedding of column_name: {}'.format( + categorical_column.name)) + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + embedding_shape = categorical_column._num_buckets, dimension # pylint: disable=protected-access + + def _creator(weight_collections, scope): + embedding_column_layer = fc._EmbeddingColumnLayer( + embedding_shape=embedding_shape, + initializer=initializer, + weight_collections=weight_collections, + trainable=True, + name='embedding_column_layer') + return embedding_column_layer(None, scope=scope) # pylint: disable=not-callable + + column = _TPUEmbeddingColumn( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + layer_creator=_creator, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + use_safe_embedding_lookup=use_safe_embedding_lookup) + # For Embedding column, the initializer is hidden inside the creator Fn, which + # is not accessible later. So, we attach it to a special field. Also note + # that non-TPU Embedding column and non-TPU shared Embedding column handle the + # initializer differently. See shared_embedding_columns for details. + column._tpu_initializer = initializer + return column + + +def shared_embedding_columns(categorical_columns, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + max_sequence_lengths=None, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + """List of dense columns that convert from sparse, categorical input. + + Note that the interface for TPU embedding_column is different from the non-TPU + version. The following args available for the non-TPU version are NOT + supported: ckpt_to_load_from, tensor_name_in_ckp, max_norm and trainable. + + Args: + categorical_columns: A list of categorical_columns returned from + categorical_column_with_identity, weighted_categorical_column, + categorical_column_with_vocabulary_file, + categorical_column_with_vocabulary_list, + sequence_categorical_column_with_identity, + sequence_categorical_column_with_vocabulary_file, + sequence_categorical_column_with_vocabulary_list + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries + in a single row for a non-sequence column. For more information, see + `tf.feature_column.embedding_column`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.truncated_normal_initializer` with mean `0.0` and standard deviation + `1/sqrt(dimension)`. + shared_embedding_collection_name: Optional name of the collection where + shared embedding weights are added. If not given, a reasonable name will + be chosen based on the names of `categorical_columns`. This is also used + in `variable_scope` when creating shared embedding weights. + max_sequence_lengths: An list of non-negative integers, either None or + empty or the same length as the argument categorical_columns. Entries + corresponding to non-sequence columns must be 0 and entries corresponding + to sequence columns specify the max sequence length for the column. Any + sequence shorter then this will be padded with 0 embeddings and any + sequence longer will be truncated. + learning_rate_fn: A function that takes global step and returns learning + rate for the embedding table. If you intend to use the same learning rate + for multiple embedding tables, please ensure that you pass the exact same + python function to all calls of shared_embedding_columns, otherwise + performence may suffer. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A _TPUEmbeddingColumn. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if `initializer` is specified but not callable. + ValueError: if `max_sequence_lengths` is specified and not the same length + as `categorical_columns`. + ValueError: if `max_sequence_lengths` is positive for a non sequence column + or 0 for a sequence column. + """ + for categorical_column in categorical_columns: + if isinstance(categorical_column, _DENYLISTED_CATEGORICAL_COLUMNS_V2): + raise TypeError('categorical_column for tpu ' + ' embedding_column was denylisted type ' + f'{type(categorical_column)}') + if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS): + raise TypeError( + 'categorical_column for tpu ' + ' shared_embedding_columns must be type {}, got {}.'.format( + ' or '.join( + [cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS]), + type(categorical_column))) + + if not max_sequence_lengths: + max_sequence_lengths = [0] * len(categorical_columns) + if len(max_sequence_lengths) != len(categorical_columns): + raise ValueError('max_sequence_lengths and categorical_columns must be of ' + 'the same length. len(max_sequence_lengths)={} ' + 'len(categorical_columns)={}.'.format( + len(max_sequence_lengths), len(categorical_columns))) + + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ') + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + # Sort the columns so the default collection name is deterministic even if the + # user passes columns from an unsorted collection, such as dict.values(). + sorted_columns = sorted(categorical_columns, key=lambda x: x.name) + num_buckets = sorted_columns[0]._num_buckets # pylint: disable=protected-access + + for c in sorted_columns[1:]: + if num_buckets != c._num_buckets: # pylint: disable=protected-access + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same number of buckets. Given column: {} with buckets: {} does ' + 'not match column: {} with buckets: {}'.format( + sorted_columns[0], num_buckets, c, c._num_buckets)) # pylint: disable=protected-access + + if not shared_embedding_collection_name: + shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) + shared_embedding_collection_name += '_shared_embedding' + + tpu_columns = [] + + # Create the state (_SharedEmbeddingColumnLayer) here. + for categorical_column, max_sequence_length in zip( + categorical_columns, max_sequence_lengths): + column = _TPUSharedEmbeddingColumn( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + initializer=initializer, + shared_embedding_collection_name=shared_embedding_collection_name, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + use_safe_embedding_lookup=use_safe_embedding_lookup) + tpu_columns.append(column) + + return tpu_columns + + +class _TPUBaseEmbeddingColumn(object): + """Base class for TPU Embedding Column.""" + + def __init__(self, + categorical_column, + max_sequence_length=0, + learning_rate_fn=None): + self._tpu_categorical_column = categorical_column + self._max_sequence_length = max_sequence_length + self._learning_rate_fn = learning_rate_fn + if (self.is_sequence_column() and max_sequence_length < 1): + raise ValueError('max_sequence_length must be greater than 0 for ' + 'sequence columns. Got max_sequence_length={} for ' + 'sequence column {}.'.format(max_sequence_length, + categorical_column.name)) + if (not self.is_sequence_column() and max_sequence_length != 0): + raise ValueError('Non zero max_seq_length={} specified for non ' + 'sequence column {}.'.format(max_sequence_length, + categorical_column.name)) + + def get_combiner(self): + """Returns the embedding combiner.""" + raise NotImplementedError('not implemented') + + def get_embedding_table_size(self): + """Returns the embedding table size, tuple of vocab size and dimension.""" + raise NotImplementedError('not implemented') + + def get_feature_key_name(self): + """Returns the feature key name in the features dict.""" + raise NotImplementedError('not impl') + + def get_weight_key_name(self): + """Return the key name for weights.""" + raise NotImplementedError('not impl') + + def get_embedding_var_name(self): + """Returns the embedding variable name. + + Feature key name and embedding variable name are usually one-to-one mapping. + But for shared embedding columns, it is many-to-one mapping. + """ + raise NotImplementedError('not impl') + + def get_initializer(self): + """Returns the initializer.""" + raise NotImplementedError('not impl') + + def is_categorical_column_weighted(self): + """Check if the categorical column of the embedding column is weighted.""" + raise NotImplementedError('not impl') + + def is_sequence_column(self): + return isinstance(self._tpu_categorical_column, _SUPPORTED_SEQUENCE_COLUMNS) + + def get_max_sequence_length(self): + return self._max_sequence_length + + def get_learning_rate_fn(self): + return self._learning_rate_fn + + def get_sequence_length_feature_key_name(self): + """Get the key for the associated sequence length feature.""" + return get_sequence_length_feature_key_name_from_feature_key_name( + self.get_feature_key_name()) + + +class _TPUEmbeddingColumn(_TPUBaseEmbeddingColumn, fc._EmbeddingColumn): + """Core Embedding Column.""" + + def __new__(cls, + categorical_column, + dimension, + combiner='mean', + layer_creator=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True, + bypass_scope_validation=False): + # Note, args ckpt_to_load_from, tensor_name_in_ckpt, max_norm and trainable + # are not supported on TPU. They are solely for matching the signature of + # __new__ of parent class fc._EmbeddingColumn. + del bypass_scope_validation + # pylint: disable=redundant-keyword-arg + return fc._EmbeddingColumn.__new__( + cls, + categorical_column, + dimension, + combiner=combiner, + layer_creator=layer_creator, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + def __init__(self, + categorical_column, + dimension, + combiner='mean', + layer_creator=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True, + bypass_scope_validation=False): + _TPUBaseEmbeddingColumn.__init__( + self, + categorical_column, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn) + self._key = None + # If true, scope validation is skipped to allow the same column to be used + # in multiple variable scopes. By default, this is False, and we expect a + # 1:1 mapping between feature columns and scopes. + self._bypass_scope_validation = bypass_scope_validation + + def get_combiner(self): + return self.combiner + + def get_embedding_table_size(self): + """Returns num_ids and width.""" + return (self.categorical_column._num_buckets, self.dimension) + + def get_feature_key_name(self): + """get_feature_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.categorical_column.name + return self.categorical_column.name + + def get_weight_key_name(self): + """get_weight_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.weight_feature_key + return None + + def get_embedding_var_name(self): + """get_embedding_var_name.""" + return self.categorical_column.name + + def get_initializer(self): + return self._tpu_initializer + + def is_categorical_column_weighted(self): + """Check if the categorical column of the embedding column is weighted.""" + if isinstance( + self.categorical_column, + ( + fc._WeightedCategoricalColumn, # pylint: disable=protected-access + fc_lib.WeightedCategoricalColumn)): + return True + return False + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc._EmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc._EmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + # TPU mode + # Get the embeddings from the LazyBuilder. + tensor = inputs.get(self.get_feature_key_name()) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + bypass_scope_validation=self._bypass_scope_validation) + + return tensor + + def _get_sequence_dense_tensor( + self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc._EmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc._EmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + tensor = inputs.get(self.get_feature_key_name()) + tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) + + # inputs is a _LazyBuilder and for rank 1 tensors, it calls expand_dims(-1). + # We need to undo this to match the standard CPU sequence embedding. + tensor_lengths = array_ops.squeeze(tensor_lengths, -1) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + bypass_scope_validation=self._bypass_scope_validation) + + return fc._SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=tensor, sequence_length=tensor_lengths) + + +class _TPUSharedEmbeddingColumn(_TPUBaseEmbeddingColumn, + fc._SharedEmbeddingColumn): + """Core Shared Embedding Column.""" + + def __new__(cls, + categorical_column, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + return fc._SharedEmbeddingColumn.__new__( + cls, + categorical_column, + dimension, + combiner=combiner, + initializer=initializer, + shared_embedding_collection_name=shared_embedding_collection_name, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + def __init__(self, + categorical_column, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + + _TPUBaseEmbeddingColumn.__init__( + self, + categorical_column, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn) + self._key = None + + def get_combiner(self): + return self.combiner + + def get_embedding_table_size(self): + """Returns num_ids and width.""" + return (self.categorical_column._num_buckets, self.dimension) + + def get_feature_key_name(self): + """get_feature_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.categorical_column.name + return self.categorical_column.name + + def get_weight_key_name(self): + """get_weight_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.weight_feature_key + return None + + def get_embedding_var_name(self): + """get_embedding_var_name.""" + return self.shared_embedding_collection_name + + def get_initializer(self): + return self.initializer + + def is_categorical_column_weighted(self): + """Check if the categorical column of the embedding column is weighted.""" + if isinstance( + self.categorical_column, + ( + fc._WeightedCategoricalColumn, # pylint: disable=protected-access + fc_lib.WeightedCategoricalColumn)): + return True + return False + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc._SharedEmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc._SharedEmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + # TPU mode + # Get the embeddings from the LazyBuilder. + tensor = inputs.get(self.get_feature_key_name()) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + is_shared_embedding=True) + return tensor + + def _get_sequence_dense_tensor( + self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc._SharedEmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc._SharedEmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + tensor = inputs.get(self.get_feature_key_name()) + tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + is_shared_embedding=True) + + return fc._SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=tensor, sequence_length=tensor_lengths) + + +def _record_variable_scope_and_name(embedding_var_name, + embedding_var_name_in_fc, + is_shared_embedding=False, + bypass_scope_validation=False): + """Add embedding variable name and scope to collection.""" + g = ops.get_default_graph() + collection = g.get_collection_ref(_TPU_FC_TO_SCOPE) + if not collection: + collection.append({}) + + var_def_dict = collection[0] + + captured_scope = variable_scope.get_variable_scope() + captured_scope_name = captured_scope.name + + if embedding_var_name in var_def_dict: + if (var_def_dict[embedding_var_name][0] != captured_scope_name and + not is_shared_embedding and not bypass_scope_validation): + raise ValueError( + 'For embedding var name {}, the variable scope name is different, ' + 'got {}; expected {}'.format(embedding_var_name, + captured_scope_name, + var_def_dict[embedding_var_name][0])) + if var_def_dict[embedding_var_name][1] != embedding_var_name_in_fc: + raise ValueError( + 'For embedding var name {}, the embedding name is different, ' + 'got {}; expected {}'.format(embedding_var_name, + embedding_var_name_in_fc, + var_def_dict[embedding_var_name][1])) + else: + var_def_dict[embedding_var_name] = (captured_scope_name, + embedding_var_name_in_fc) + + +def _is_running_on_cpu(): + """Returns True if the current context is CPU model.""" + return tpu_function.get_tpu_context().number_of_shards is None + + +def get_sequence_length_feature_key_name_from_feature_key_name(feature_name): + """Gets the name of the sequence length feature from that of the base feature. + + Args: + feature_name: The feature key of a sequence column. + + Returns: + A string which is the feature key for the associated feature length column. + """ + return feature_name + _SEQUENCE_FEATURE_LENGTH_POSTFIX + + +def split_sequence_columns(feature_columns): + """Split a list of _TPUEmbeddingColumn into sequence and non-sequence columns. + + For use in a TPUEstimator model_fn function. E.g. + + def model_fn(features): + sequence_columns, feature_columns = ( + tf.tpu.feature_column.split_sequence_columns(feature_columns)) + input = tf.feature_column.input_layer( + features=features, feature_columns=feature_columns) + sequence_features, sequence_lengths = ( + tf.contrib.feature_column.sequence_input_layer( + features=features, feature_columns=sequence_columns)) + + Args: + feature_columns: A list of _TPUEmbeddingColumns to split. + + Returns: + Two lists of _TPUEmbeddingColumns, the first is the sequence columns and the + second is the non-sequence columns. + """ + sequence_columns = [] + non_sequence_columns = [] + for column in feature_columns: + if not isinstance(column, (_TPUEmbeddingColumn, _TPUSharedEmbeddingColumn)): + raise TypeError( + 'column must be a _TPUEmbeddingColumn or _TPUSharedEmbeddingColumn ' + f'but got {type(column)} instead.') + if column.is_sequence_column(): + sequence_columns.append(column) + else: + non_sequence_columns.append(column) + return sequence_columns, non_sequence_columns diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b8f8012747305cf99458246d9a80f9a03172ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/feature_column_v2.py @@ -0,0 +1,1097 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""TPU Feature Column Library.""" +import copy +import enum +import math +from tensorflow.python.feature_column import feature_column as fc +from tensorflow.python.feature_column import feature_column_lib as fc_lib +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.tpu.feature_column import _is_running_on_cpu +from tensorflow.python.tpu.feature_column import _record_variable_scope_and_name +from tensorflow.python.tpu.feature_column import _SUPPORTED_CATEGORICAL_COLUMNS_V2 +from tensorflow.python.tpu.feature_column import _SUPPORTED_SEQUENCE_COLUMNS +from tensorflow.python.tpu.feature_column import _TPUBaseEmbeddingColumn +from tensorflow.python.util.tf_export import tf_export +# pylint: disable=protected-access + +_ALLOWED_DEVICES = ['cpu', 'tpu_tensor_core', 'tpu_embedding_core'] +_TENSOR_CORE_MASK_KEY_SUFFIX = '__TENSOR_CORE_MASK' + + +class EmbeddingDevice(enum.Enum): + CPU = 1 + TPU_TENSOR_CORE = 2 + TPU_EMBEDDING_CORE = 3 + + +@tf_export(v1=['tpu.experimental.embedding_column']) +def embedding_column_v2(categorical_column, + dimension, + combiner='mean', + initializer=None, + max_sequence_length=0, + learning_rate_fn=None, + embedding_lookup_device=None, + tensor_core_shape=None, + use_safe_embedding_lookup=True): + """TPU version of `tf.compat.v1.feature_column.embedding_column`. + + Note that the interface for `tf.tpu.experimental.embedding_column` is + different from that of `tf.compat.v1.feature_column.embedding_column`: The + following arguments are NOT supported: `ckpt_to_load_from`, + `tensor_name_in_ckpt`, `max_norm` and `trainable`. + + Use this function in place of `tf.compat.v1.feature_column.embedding_column` + when you want to use the TPU to accelerate your embedding lookups via TPU + embeddings. + + ``` + column = tf.feature_column.categorical_column_with_identity(...) + tpu_column = tf.tpu.experimental.embedding_column(column, 10) + ... + def model_fn(features): + dense_feature = tf.keras.layers.DenseFeature(tpu_column) + embedded_feature = dense_feature(features) + ... + + estimator = tf.estimator.tpu.TPUEstimator( + model_fn=model_fn, + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + column=[tpu_column], + ...)) + ``` + + Args: + categorical_column: A categorical column returned from + `categorical_column_with_identity`, `weighted_categorical_column`, + `categorical_column_with_vocabulary_file`, + `categorical_column_with_vocabulary_list`, + `sequence_categorical_column_with_identity`, + `sequence_categorical_column_with_vocabulary_file`, + `sequence_categorical_column_with_vocabulary_list` + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries + in a single row for a non-sequence column. For more information, see + `tf.feature_column.embedding_column`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and + standard deviation `1/sqrt(dimension)`. + max_sequence_length: An non-negative integer specifying the max sequence + length. Any sequence shorter then this will be padded with 0 embeddings + and any sequence longer will be truncated. This must be positive for + sequence features and 0 for non-sequence features. + learning_rate_fn: A function that takes global step and returns learning + rate for the embedding table. If you intend to use the same learning rate + for multiple embedding tables, please ensure that you pass the exact same + python function to all calls of embedding_column, otherwise performence + may suffer. + embedding_lookup_device: The device on which to run the embedding lookup. + Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". + If specifying "tpu_tensor_core", a tensor_core_shape must be supplied. + If not specified, the default behavior is embedding lookup on + "tpu_embedding_core" for training and "cpu" for inference. + Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] + Valid options for serving : ["cpu", "tpu_tensor_core"] + For training, tpu_embedding_core is good for large embedding vocab (>1M), + otherwise, tpu_tensor_core is often sufficient. + For serving, doing embedding lookup on tpu_tensor_core during serving is + a way to reduce host cpu usage in cases where that is a bottleneck. + tensor_core_shape: If supplied, a list of integers which specifies + the intended dense shape to run embedding lookup for this feature on + TensorCore. The batch dimension can be left None or -1 to indicate + a dynamic shape. Only rank 2 shapes currently supported. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A `_TPUEmbeddingColumnV2`. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if `initializer` is specified but not callable. + """ + + if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS_V2): + raise TypeError( + 'categorical_column for tpu ' + 'embedding_column must be type {}, got {}.'.format(' or '.join([ + cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS_V2 + ]), type(categorical_column))) + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if tensor_core_shape and len(tensor_core_shape) != 2: + raise ValueError( + 'tensor_core_shape must be size 2. Got {}.'.format(tensor_core_shape)) + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ' + 'Embedding of column_name: {}'.format( + categorical_column.name)) + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + if (embedding_lookup_device and + embedding_lookup_device not in _ALLOWED_DEVICES): + raise ValueError( + f'If set, embedding_lookup_device must be in {_ALLOWED_DEVICES}') + + if embedding_lookup_device == 'cpu': + embedding_lookup_device = EmbeddingDevice.CPU + elif embedding_lookup_device == 'tpu_tensor_core': + embedding_lookup_device = EmbeddingDevice.TPU_TENSOR_CORE + elif embedding_lookup_device == 'tpu_embedding_core': + embedding_lookup_device = EmbeddingDevice.TPU_EMBEDDING_CORE + + if embedding_lookup_device == EmbeddingDevice.TPU_TENSOR_CORE: + if not tensor_core_shape: + raise ValueError('Using embedding_lookup_device=tpu_tensor_core requires ' + 'tensor_core_shape to be set.') + if isinstance(categorical_column, _SUPPORTED_SEQUENCE_COLUMNS): + raise ValueError('embedding_lookup_device=tpu_tensor_core currently does ' + 'not support sequence columns.') + + if not embedding_lookup_device: + return _TPUEmbeddingColumnV2( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + initializer=initializer, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + use_safe_embedding_lookup=use_safe_embedding_lookup) + else: + return _TPUDeviceSpecificEmbeddingColumnV2( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + initializer=initializer, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + embedding_lookup_device=embedding_lookup_device, + tensor_core_shape=tensor_core_shape, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + +@tf_export(v1=['tpu.experimental.shared_embedding_columns']) +def shared_embedding_columns_v2(categorical_columns, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + max_sequence_lengths=None, + learning_rate_fn=None, + embedding_lookup_device=None, + tensor_core_shape=None, + use_safe_embedding_lookup=True): + """TPU version of `tf.compat.v1.feature_column.shared_embedding_columns`. + + Note that the interface for `tf.tpu.experimental.shared_embedding_columns` is + different from that of `tf.compat.v1.feature_column.shared_embedding_columns`: + The following arguments are NOT supported: `ckpt_to_load_from`, + `tensor_name_in_ckpt`, `max_norm` and `trainable`. + + Use this function in place of + tf.compat.v1.feature_column.shared_embedding_columns` when you want to use the + TPU to accelerate your embedding lookups via TPU embeddings. + + ``` + column_a = tf.feature_column.categorical_column_with_identity(...) + column_b = tf.feature_column.categorical_column_with_identity(...) + tpu_columns = tf.tpu.experimental.shared_embedding_columns( + [column_a, column_b], 10) + ... + def model_fn(features): + dense_feature = tf.keras.layers.DenseFeature(tpu_columns) + embedded_feature = dense_feature(features) + ... + + estimator = tf.estimator.tpu.TPUEstimator( + model_fn=model_fn, + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + column=tpu_columns, + ...)) + ``` + + Args: + categorical_columns: A list of categorical columns returned from + `categorical_column_with_identity`, `weighted_categorical_column`, + `categorical_column_with_vocabulary_file`, + `categorical_column_with_vocabulary_list`, + `sequence_categorical_column_with_identity`, + `sequence_categorical_column_with_vocabulary_file`, + `sequence_categorical_column_with_vocabulary_list` + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries in + a single row for a non-sequence column. For more information, see + `tf.feature_column.embedding_column`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.truncated_normal_initializer` with mean `0.0` and standard deviation + `1/sqrt(dimension)`. + shared_embedding_collection_name: Optional name of the collection where + shared embedding weights are added. If not given, a reasonable name will + be chosen based on the names of `categorical_columns`. This is also used + in `variable_scope` when creating shared embedding weights. + max_sequence_lengths: An list of non-negative integers, either None or empty + or the same length as the argument categorical_columns. Entries + corresponding to non-sequence columns must be 0 and entries corresponding + to sequence columns specify the max sequence length for the column. Any + sequence shorter then this will be padded with 0 embeddings and any + sequence longer will be truncated. + learning_rate_fn: A function that takes global step and returns learning + rate for the embedding table. If you intend to use the same learning rate + for multiple embedding tables, please ensure that you pass the exact same + python function to all calls of shared_embedding_columns, otherwise + performence may suffer. + embedding_lookup_device: The device on which to run the embedding lookup. + Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". If + specifying "tpu_tensor_core", a tensor_core_shape must be supplied. + Defaults to "cpu". If not specified, the default behavior is embedding + lookup on "tpu_embedding_core" for training and "cpu" for inference. + Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] + Valid options for serving : ["cpu", "tpu_tensor_core"] + For training, tpu_embedding_core is good for large embedding vocab (>1M), + otherwise, tpu_tensor_core is often sufficient. + For serving, doing embedding lookup on tpu_tensor_core during serving is + a way to reduce host cpu usage in cases where that is a bottleneck. + tensor_core_shape: If supplied, a list of integers which specifies the + intended dense shape to run embedding lookup for this feature on + TensorCore. The batch dimension can be left None or -1 to indicate a + dynamic shape. Only rank 2 shapes currently supported. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A list of `_TPUSharedEmbeddingColumnV2`. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if `initializer` is specified but not callable. + ValueError: if `max_sequence_lengths` is specified and not the same length + as `categorical_columns`. + ValueError: if `max_sequence_lengths` is positive for a non sequence column + or 0 for a sequence column. + """ + + for categorical_column in categorical_columns: + if not isinstance(categorical_column, _SUPPORTED_CATEGORICAL_COLUMNS_V2): + raise TypeError( + 'categorical_column for tpu ' + ' shared_embedding_columns must be type {}, got {}.'.format( + ' or '.join( + [cc.__name__ for cc in _SUPPORTED_CATEGORICAL_COLUMNS_V2]), + type(categorical_column))) + + if not max_sequence_lengths: + max_sequence_lengths = [0] * len(categorical_columns) + if len(max_sequence_lengths) != len(categorical_columns): + raise ValueError('max_sequence_lengths and categorical_columns must be of ' + 'the same length. len(max_sequence_lengths)={} ' + 'len(categorical_columns)={}.'.format( + len(max_sequence_lengths), len(categorical_columns))) + + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if tensor_core_shape and len(tensor_core_shape) != 2: + raise ValueError( + 'tensor_core_shape must be size 2. Got {}.'.format(tensor_core_shape)) + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ') + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + # Sort the columns so the default collection name is deterministic even if the + # user passes columns from an unsorted collection, such as dict.values(). + sorted_columns = sorted(categorical_columns, key=lambda x: x.name) + num_buckets = sorted_columns[0]._num_buckets # pylint: disable=protected-access + + for c in sorted_columns[1:]: + if num_buckets != c._num_buckets: # pylint: disable=protected-access + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same number of buckets. Given column: {} with buckets: {} does ' + 'not match column: {} with buckets: {}'.format( + sorted_columns[0], num_buckets, c, c._num_buckets)) # pylint: disable=protected-access + + if not shared_embedding_collection_name: + shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) + shared_embedding_collection_name += '_shared_embedding' + + tpu_columns = [] + + column_creator = fc_lib.SharedEmbeddingColumnCreator( + dimension=dimension, initializer=initializer, ckpt_to_load_from=None, + tensor_name_in_ckpt=None, num_buckets=num_buckets, trainable=None, + name=shared_embedding_collection_name) + + if (embedding_lookup_device and + embedding_lookup_device not in _ALLOWED_DEVICES): + raise ValueError( + f'If set, embedding_lookup_device must be in {_ALLOWED_DEVICES}') + + if embedding_lookup_device == 'cpu': + embedding_lookup_device = EmbeddingDevice.CPU + elif embedding_lookup_device == 'tpu_tensor_core': + embedding_lookup_device = EmbeddingDevice.TPU_TENSOR_CORE + elif embedding_lookup_device == 'tpu_embedding_core': + embedding_lookup_device = EmbeddingDevice.TPU_EMBEDDING_CORE + + if embedding_lookup_device == EmbeddingDevice.TPU_TENSOR_CORE: + if not tensor_core_shape: + raise ValueError('Using embedding_lookup_device=tpu_tensor_core requires ' + 'tensor_core_shape to be set.') + for c in sorted_columns: + if isinstance(c, _SUPPORTED_SEQUENCE_COLUMNS): + raise ValueError('embedding_lookup_device=tpu_tensor_core currently ' + 'does not support sequence columns.') + + # Create the state (_SharedEmbeddingColumnLayer) here. + for categorical_column, max_sequence_length in zip( + categorical_columns, max_sequence_lengths): + if not embedding_lookup_device: + column = _TPUSharedEmbeddingColumnV2( + categorical_column=categorical_column, + shared_embedding_column_creator=column_creator, + combiner=combiner, + initializer=initializer, + shared_embedding_collection_name=shared_embedding_collection_name, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + use_safe_embedding_lookup=use_safe_embedding_lookup) + else: + column = _TPUSharedDeviceSpecificEmbeddingColumnV2( + categorical_column=categorical_column, + shared_embedding_column_creator=column_creator, + combiner=combiner, + initializer=initializer, + shared_embedding_collection_name=shared_embedding_collection_name, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn, + embedding_lookup_device=embedding_lookup_device, + tensor_core_shape=tensor_core_shape, + use_safe_embedding_lookup=use_safe_embedding_lookup) + tpu_columns.append(column) + + return tpu_columns + + +class _TPUEmbeddingColumnV2(_TPUBaseEmbeddingColumn, fc_lib.EmbeddingColumn): + """Core Embedding Column.""" + + def __new__(cls, + categorical_column, + dimension, + combiner='mean', + initializer=None, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True, + bypass_scope_validation=False): + del bypass_scope_validation + # pylint: disable=redundant-keyword-arg + return fc_lib.EmbeddingColumn.__new__( + cls, + categorical_column, + dimension, + combiner=combiner, + initializer=initializer, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + def __getnewargs__(self): + return (self._tpu_categorical_column, self.dimension, self.combiner, + self.initializer, self._max_sequence_length, self._learning_rate_fn, + self.use_safe_embedding_lookup, self._bypass_scope_validation) + + def __deepcopy__(self, memo): + return _TPUEmbeddingColumnV2( + *(copy.deepcopy(a, memo) for a in self.__getnewargs__())) + + def __init__(self, + categorical_column, + dimension, + combiner='mean', + initializer=None, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True, + bypass_scope_validation=False): + _TPUBaseEmbeddingColumn.__init__( + self, + categorical_column, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn) + self._key = None + # If true, scope validation is skipped to allow the same column to be used + # in multiple variable scopes. By default, this is False, and we expect a + # 1:1 mapping between feature columns and scopes. + self._bypass_scope_validation = bypass_scope_validation + + def get_combiner(self): + return self.combiner + + def get_embedding_table_size(self): + """Returns num_ids and width.""" + return (self.categorical_column._num_buckets, self.dimension) + + def get_feature_key_name(self): + """get_feature_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.categorical_column.name + return self.categorical_column.name + + def get_weight_key_name(self): + """get_weight_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.weight_feature_key + return None + + def get_embedding_var_name(self): + """get_embedding_var_name.""" + return self.categorical_column.name + + def get_initializer(self): + return self.initializer + + def is_categorical_column_weighted(self): + """Check if the categorical column of the embedding column is weighted.""" + if isinstance( + self.categorical_column, + ( + fc._WeightedCategoricalColumn, # pylint: disable=protected-access + fc_lib.WeightedCategoricalColumn)): + return True + return False + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.EmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.EmbeddingColumn._get_dense_tensor( + self, inputs, weight_collections, trainable) + + # TPU mode + # Get the embeddings from the LazyBuilder. + tensor = inputs.get(self.get_feature_key_name()) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + bypass_scope_validation=self._bypass_scope_validation) + + return tensor + + def create_state(self, state_manager): + if _is_running_on_cpu(): + return fc_lib.EmbeddingColumn.create_state( + self, state_manager) + + # Create state is called for the EmbeddingColumn to create its embedding + # variables under feature column V2, if we are on TPU so record the scope + # here. + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + bypass_scope_validation=self._bypass_scope_validation) + + def get_dense_tensor(self, transformation_cache, state_manager): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.EmbeddingColumn.get_dense_tensor( + self, transformation_cache, state_manager) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.EmbeddingColumn.get_dense_tensor( + self, transformation_cache, state_manager) + + # TPU mode + # Get the embeddings from the FeatureTransformationCache. + tensor = transformation_cache.get(self.get_feature_key_name(), + state_manager) + + return tensor + + def _get_sequence_dense_tensor( + self, inputs, weight_collections=None, trainable=None): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.EmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.EmbeddingColumn._get_sequence_dense_tensor( + self, inputs, weight_collections, trainable) + + tensor = inputs.get(self.get_feature_key_name()) + tensor_lengths = inputs.get(self.get_sequence_length_feature_key_name()) + + # inputs is a _LazyBuilder and for rank 1 tensors, it calls expand_dims(-1). + # We need to undo this to match the standard CPU sequence embedding. + tensor_lengths = array_ops.squeeze(tensor_lengths, -1) + + # Add to collection for _create_tpu_embedding_variables_and_ops + _record_variable_scope_and_name( + self.get_embedding_var_name(), + 'embedding_weights', + bypass_scope_validation=self._bypass_scope_validation) + + return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=tensor, sequence_length=tensor_lengths) + + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.EmbeddingColumn.get_sequence_dense_tensor( + self, transformation_cache, state_manager) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.EmbeddingColumn.get_sequence_dense_tensor( + self, transformation_cache, state_manager) + + tensor = transformation_cache.get(self.get_feature_key_name(), + state_manager) + tensor_lengths = transformation_cache.get( + self.get_sequence_length_feature_key_name(), + state_manager) + + # FeatureTransformationCache expands rank 1 tensors (like sequence length) + # to rank 2. We need to undo this to match the standard CPU sequence + # embedding. + tensor_lengths = array_ops.squeeze(tensor_lengths, -1) + + return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=tensor, sequence_length=tensor_lengths) + + +class _TPUSharedEmbeddingColumnV2(_TPUBaseEmbeddingColumn, + fc_lib.SharedEmbeddingColumn): + """Core Shared Embedding Column.""" + + def __new__(cls, + categorical_column, + shared_embedding_column_creator, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + # pylint: disable=redundant-keyword-arg + return fc_lib.SharedEmbeddingColumn.__new__( + cls, + categorical_column, + combiner=combiner, + shared_embedding_column_creator=shared_embedding_column_creator, + max_norm=None, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + def __getnewargs__(self): + return (self._tpu_categorical_column, self.shared_embedding_column_creator, + self.combiner, self._initializer, + self._shared_embedding_collection_name, self._max_sequence_length, + self._learning_rate_fn) + + def __deepcopy__(self, memo): + return _TPUSharedEmbeddingColumnV2( + *(copy.deepcopy(a, memo) for a in self.__getnewargs__())) + + def __init__(self, + categorical_column, + shared_embedding_column_creator, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + max_sequence_length=0, + learning_rate_fn=None, + use_safe_embedding_lookup=True): + + _TPUBaseEmbeddingColumn.__init__( + self, + categorical_column, + max_sequence_length=max_sequence_length, + learning_rate_fn=learning_rate_fn) + self._initializer = initializer + self._shared_embedding_collection_name = shared_embedding_collection_name + + def get_combiner(self): + return self.combiner + + def get_embedding_table_size(self): + """Returns num_ids and width.""" + return (self.categorical_column._num_buckets, + self.shared_embedding_column_creator.dimension) + + def get_feature_key_name(self): + """get_feature_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.categorical_column.name + return self.categorical_column.name + + def get_weight_key_name(self): + """get_weight_key_name.""" + if self.is_categorical_column_weighted(): + return self.categorical_column.weight_feature_key + return None + + def get_embedding_var_name(self): + """get_embedding_var_name.""" + return self._shared_embedding_collection_name + + def get_initializer(self): + return self._initializer + + def is_categorical_column_weighted(self): + """Check if the categorical column of the embedding column is weighted.""" + if isinstance( + self.categorical_column, + ( + fc._WeightedCategoricalColumn, # pylint: disable=protected-access + fc_lib.WeightedCategoricalColumn)): + return True + return False + + def _get_dense_tensor_internal( + self, transformation_cache, state_manager): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.SharedEmbeddingColumn._get_dense_tensor_internal( + self, transformation_cache, state_manager) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.SharedEmbeddingColumn._get_dense_tensor_internal( + self, transformation_cache, state_manager) + + # TPU mode + # Get the embeddings from the FeatureTransformationCache. + tensor = transformation_cache.get(self.get_feature_key_name(), + state_manager) + + # Add to collection for _create_tpu_embedding_variables_and_ops + # Note that in Feature Column V2, shared embeddings have no scope. + _record_variable_scope_and_name( + self.get_embedding_var_name(), + self.shared_embedding_column_creator._name, + is_shared_embedding=True) + return tensor + + def get_sequence_dense_tensor( + self, transformation_cache, state_manager): + if tpu.under_tpu_inference_context(): + def host_computation(): + return fc_lib.SharedEmbeddingColumn.get_sequence_dense_tensor( + self, transformation_cache, state_manager) + + return tpu_replication.outside_compilation(host_computation) + + if _is_running_on_cpu(): + return fc_lib.SharedEmbeddingColumn.get_sequence_dense_tensor( + self, transformation_cache, state_manager) + + tensor = self._get_dense_tensor_internal( + transformation_cache, state_manager) + tensor_lengths = transformation_cache.get( + self.get_sequence_length_feature_key_name(), + state_manager) + + # FeatureTransformationCache expands rank 1 tensors (like sequence length) + # to rank 2. We need to undo this to match the standard CPU sequence + # embedding. + tensor_lengths = array_ops.squeeze(tensor_lengths, -1) + + return fc_lib.SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=tensor, sequence_length=tensor_lengths) + + +def split_sequence_columns_v2(feature_columns): + """Split a list of _TPUEmbeddingColumn into sequence and non-sequence columns. + + For use in a TPUEstimator model_fn function. E.g. + + def model_fn(features): + sequence_columns, feature_columns = ( + tf.tpu.feature_column.split_sequence_columns(feature_columns)) + input = tf.feature_column.input_layer( + features=features, feature_columns=feature_columns) + sequence_features, sequence_lengths = ( + tf.contrib.feature_column.sequence_input_layer( + features=features, feature_columns=sequence_columns)) + + Args: + feature_columns: A list of _TPUEmbeddingColumns to split. + + Returns: + Two lists of _TPUEmbeddingColumns, the first is the sequence columns and the + second is the non-sequence columns. + """ + sequence_columns = [] + non_sequence_columns = [] + for column in feature_columns: + if not isinstance(column, (_TPUEmbeddingColumnV2, + _TPUSharedEmbeddingColumnV2)): + raise TypeError( + 'column must be a _TPUEmbeddingColumnV2 or ' + f'_TPUSharedEmbeddingColumnV2 but got {type(column)} instead.') + if column.is_sequence_column(): + sequence_columns.append(column) + else: + non_sequence_columns.append(column) + return sequence_columns, non_sequence_columns + + +def sparse_embedding_aggregate_slice(params, + values_and_values_mask, + combiner='mean', + name='sparse_embedding_aggregate_slice'): + """Uses XLA's dynamic slice operations to perform embedding lookups. + + From third_party/cloud_tpu/models/movielens/tpu_embedding.py + + Args: + params: Tensor of embedding table. Rank 2 (table_size x embedding dim) + values_and_values_mask: is a two-tuple that contains: values - Tensor of + embedding indices. Rank 2 (batch x n_indices) values_mask - Tensor of mask + / weights. Rank 2 (batch x n_indices) + combiner: The combiner to use for the embedding lookup. Currently supports + 'sum' and 'mean'. + name: Optional name scope for created ops + + Returns: + Rank 2 tensor of aggregated (per batch element) embedding vectors. + + Raises: + ValueError: Combiner is not supported. + """ + values, values_mask = values_and_values_mask # unpack the two-tuple + with ops.name_scope(name): + _, embedding_dimension = params.get_shape().as_list() + n_batch, n_indices_padded = values.get_shape().as_list() + if not n_batch: + n_batch = -1 + + emb_lookup = array_ops.reshape( + embedding_ops.embedding_lookup( + params, array_ops.reshape(values, [n_batch, n_indices_padded])), + [n_batch, n_indices_padded, embedding_dimension]) + + values_mask_broadcast = array_ops.reshape(values_mask, + [n_batch, n_indices_padded, 1]) + aggregate_emb = math_ops.reduce_sum( + emb_lookup * values_mask_broadcast, axis=1) + if combiner == 'sum': + return aggregate_emb + elif combiner == 'mean': + # In the case we have an empty row, both aggregate_emb and + # math_ops.reduce_sum(values_mask_broadcast, axis=1) will be 0. Thus, + # we can take max it with a non-zero value to prevent NaNs. Note that + # math_ops.reduce_sum(values_mask_broadcast, axis=1) will have integer + # values so 1.0 is the smallest value. + return aggregate_emb / math_ops.maximum( + math_ops.reduce_sum(values_mask_broadcast, axis=1), 1.0) + else: + raise ValueError('Dense TPU Embedding does not support combiner ' + 'other than sum and mean.') + + +def pad_sparse_embedding_lookup_indices(sparse_indices, padded_size): + """Creates statically-sized Tensors containing indices and weights. + + From third_party/cloud_tpu/models/movielens/tpu_embedding.py + + Also computes sparse_indices.values % embedding_table_size, for equivalent + functionality to sparse_column_with_integerized_feature. The returned + padded weight Tensor also doubles as a mask indicating which values in + the returned padded indices Tensor are indices versus padded zeros. + + Args: + sparse_indices: SparseTensor of embedding lookup indices. + padded_size: Number of columns of the returned Tensors. Indices which fall + out of bounds will be truncated to the padded size. + + Returns: + (sparse_indices.values padded to the specified size, + a mask the same size as the returned padded values in which 0s + indicate padded locations and 1s (or values from sparse_weights) + indicate actual values) + """ + batch_size = sparse_indices.dense_shape[0] + sparse_indices = sparse_ops.sparse_slice(sparse_indices, [0, 0], + [batch_size, padded_size]) + indices, values = sparse_indices.indices, sparse_indices.values + + padded_values = array_ops.scatter_nd( + indices, + math_ops.cast(values, dtypes.int32), + shape=(batch_size, padded_size)) + + weights = array_ops.ones_like(values, dtype=dtypes.float32) + padded_mask = array_ops.scatter_nd( + indices, weights, shape=(batch_size, padded_size)) + + return padded_values, padded_mask + + +def _check_invalid_cases(embedding_lookup_device): + """Checks for invalid embedding_lookup_device configurations.""" + if (tpu.under_tpu_inference_context() and + embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE): + raise ValueError( + 'Using embedding_lookup_device=tpu_embedding_core during inference ' + 'is not supported.') + if embedding_lookup_device == EmbeddingDevice.CPU: + if not tpu.under_tpu_inference_context(): + raise ValueError( + 'Using TPUEmbeddingColumn with embedding_lookup_device="cpu" ' + 'during training is not supported.') + + +class _TPUDeviceSpecificEmbeddingColumnV2(_TPUEmbeddingColumnV2): + """TPUEmbeddingColumn which allows serving on TensorCore.""" + + def __new__(cls, *args, **kwargs): + # For __new__, just capture the inference dense shape and call parent. + if 'tensor_core_shape' in kwargs: + cls._tensor_core_shape = kwargs['tensor_core_shape'] + del kwargs['tensor_core_shape'] + if 'embedding_lookup_device' in kwargs: + cls._embedding_lookup_device = kwargs['embedding_lookup_device'] + del kwargs['embedding_lookup_device'] + return _TPUEmbeddingColumnV2.__new__(cls, *args, **kwargs) # pytype: disable=wrong-keyword-args # always-use-return-annotations + + def __init__(self, *args, **kwargs): + # For __init__, just capture the inference dense shape and call parent. + if 'tensor_core_shape' in kwargs: + self._tensor_core_shape = kwargs['tensor_core_shape'] + del kwargs['tensor_core_shape'] + if 'embedding_lookup_device' in kwargs: + self._embedding_lookup_device = kwargs['embedding_lookup_device'] + del kwargs['embedding_lookup_device'] + _TPUEmbeddingColumnV2.__init__(self, *args, **kwargs) + + def __deepcopy__(self, memo): + return _TPUDeviceSpecificEmbeddingColumnV2( + *(copy.deepcopy(a, memo) for a in self.__getnewargs__()), + tensor_core_shape=self._tensor_core_shape, + embedding_lookup_device=self._embedding_lookup_device) + + def create_state(self, state_manager): + _check_invalid_cases(self._embedding_lookup_device) + # CPU case. + is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU + is_cpu = is_cpu or _is_running_on_cpu() + if is_cpu: + return fc_lib.EmbeddingColumn.create_state(self, state_manager) + # TPU_EMBEDDING_CORE case. + elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: + return super(_TPUDeviceSpecificEmbeddingColumnV2, + self).create_state(state_manager) + + # TPU_EMBEDDING_CORE case. + return fc_lib.EmbeddingColumn.create_state(self, state_manager) + + def get_dense_tensor(self, transformation_cache, state_manager): + """Private method that follows get_dense_tensor.""" + _check_invalid_cases(self._embedding_lookup_device) + # CPU Case. + is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU + is_cpu = is_cpu or _is_running_on_cpu() + if is_cpu: + return super(_TPUDeviceSpecificEmbeddingColumnV2, + self).get_dense_tensor(transformation_cache, state_manager) + # TPU_EMBEDDING_CORE case. + elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: + return super(_TPUDeviceSpecificEmbeddingColumnV2, + self).get_dense_tensor(transformation_cache, state_manager) + + # TPU_EMBEDDING_CORE cases. + if tpu.under_tpu_inference_context(): + # For inference, use outside compile to densify and pad the input tensors. + sparse_tensor = transformation_cache.get(self.categorical_column.name, + state_manager) + + def host_computation(): + return pad_sparse_embedding_lookup_indices(sparse_tensor, + self._tensor_core_shape[1]) + + values, mask = tpu_replication.outside_compilation(host_computation) + else: + # For training, the inputs should already have been densified and padded. + values = transformation_cache.get(self.categorical_column.name, + state_manager) + mask = transformation_cache.get( + self.categorical_column.name + _TENSOR_CORE_MASK_KEY_SUFFIX, + state_manager) + embedding_weights = state_manager.get_variable( + self, name='embedding_weights') + return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), + self.get_combiner()) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + _check_invalid_cases(self._embedding_lookup_device) + # CPU Case. + is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU + is_cpu = is_cpu or _is_running_on_cpu() + if is_cpu: + return super(_TPUDeviceSpecificEmbeddingColumnV2, + self)._get_dense_tensor(inputs, weight_collections, + trainable) + # TPU_EMBEDDING_CORE case. + elif self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: + return super(_TPUDeviceSpecificEmbeddingColumnV2, + self)._get_dense_tensor(inputs, weight_collections, + trainable) + + # TPU_EMBEDDING_CORE cases. + if tpu.under_tpu_inference_context(): + # For inference, use outside compile to densify and pad the input tensors. + sparse_tensor = inputs.get(self.get_feature_key_name()) + + def host_computation(): + return pad_sparse_embedding_lookup_indices(sparse_tensor, + self._tensor_core_shape[1]) + + values, mask = tpu_replication.outside_compilation(host_computation) + else: + # For training, the inputs should already have been densified and padded. + values = inputs.get(self.get_feature_key_name()) + mask = inputs.get(self.get_feature_key_name() + + _TENSOR_CORE_MASK_KEY_SUFFIX) + + embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access + if (weight_collections and + ops.GraphKeys.GLOBAL_VARIABLES not in weight_collections): + weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES) + embedding_weights = variable_scope.get_variable( + name='embedding_weights', + shape=embedding_shape, + dtype=dtypes.float32, + initializer=self.initializer, + trainable=self.trainable and trainable, + collections=weight_collections) + return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), + self.get_combiner()) + + +class _TPUSharedDeviceSpecificEmbeddingColumnV2(_TPUSharedEmbeddingColumnV2): + """TPUSharedEmbeddingColumnV2 which allows serving on TensorCore.""" + + def __new__(cls, *args, **kwargs): + # For __new__, just capture the inference dense shape and call parent. + if 'tensor_core_shape' in kwargs: + cls._tensor_core_shape = kwargs['tensor_core_shape'] + del kwargs['tensor_core_shape'] + if 'embedding_lookup_device' in kwargs: + cls._embedding_lookup_device = kwargs['embedding_lookup_device'] + del kwargs['embedding_lookup_device'] + + return _TPUSharedEmbeddingColumnV2.__new__(cls, *args, **kwargs) # pytype: disable=wrong-keyword-args # always-use-return-annotations + + def __init__(self, *args, **kwargs): + # For __init__, just capture the inference dense shape and call parent. + if 'tensor_core_shape' in kwargs: + self._tensor_core_shape = kwargs['tensor_core_shape'] + del kwargs['tensor_core_shape'] + if 'embedding_lookup_device' in kwargs: + self._embedding_lookup_device = kwargs['embedding_lookup_device'] + del kwargs['embedding_lookup_device'] + _TPUSharedEmbeddingColumnV2.__init__(self, *args, **kwargs) + + def __deepcopy__(self, memo): + return _TPUSharedDeviceSpecificEmbeddingColumnV2( + *(copy.deepcopy(a, memo) for a in self.__getnewargs__()), + tensor_core_shape=self._tensor_core_shape, + embedding_lookup_device=self._embedding_lookup_device) + + def _get_dense_tensor_internal(self, transformation_cache, state_manager): + """Private method that follows _get_dense_tensor_internal.""" + _check_invalid_cases(self._embedding_lookup_device) + # CPU Case. + is_cpu = self._embedding_lookup_device == EmbeddingDevice.CPU + is_cpu = is_cpu or _is_running_on_cpu() + if is_cpu: + return super(_TPUSharedDeviceSpecificEmbeddingColumnV2, + self)._get_dense_tensor_internal(transformation_cache, + state_manager) + # TPU_EMBEDDING_CORE case. + if self._embedding_lookup_device == EmbeddingDevice.TPU_EMBEDDING_CORE: + return super(_TPUSharedDeviceSpecificEmbeddingColumnV2, + self)._get_dense_tensor_internal(transformation_cache, + state_manager) + + # TPU_EMBEDDING_CORE cases. + if tpu.under_tpu_inference_context(): + # For inference, use outside compile to densify and pad the input tensors. + sparse_tensor = transformation_cache.get(self.categorical_column.name, + state_manager) + + def host_computation(): + return pad_sparse_embedding_lookup_indices(sparse_tensor, + self._tensor_core_shape[1]) + + values, mask = tpu_replication.outside_compilation(host_computation) + else: + # For training, the inputs should already have been densified and padded. + values = transformation_cache.get(self.categorical_column.name, + state_manager) + mask = transformation_cache.get( + self.categorical_column.name + _TENSOR_CORE_MASK_KEY_SUFFIX, + state_manager) + + # Do a dense embedding lookup on TensorCore. + embedding_weights = self.shared_embedding_column_creator.embedding_weights + return sparse_embedding_aggregate_slice(embedding_weights, (values, mask), + self.get_combiner()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/functional.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..6afdff26fca3ecc41951a4ca3f86a961b9de42ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/functional.py @@ -0,0 +1,19 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Functional operations.""" + +from tensorflow.python.tpu.ops import tpu_ops + +TPUPartitionedCall = tpu_ops.tpu_partitioned_call # pylint: disable=invalid-name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/preempted_hook.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/preempted_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bedb9343e76295ddf4c4db064f65768aebdd1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/preempted_hook.py @@ -0,0 +1,89 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of the SessionRunHook for preemptible Cloud TPUs.""" + +import logging as _logging +import os +import threading +import time + +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import session_run_hook + + +class CloudTPUPreemptedHook(session_run_hook.SessionRunHook): + """The SessionRunHook for preemptible Cloud TPUs. + + This is an implementation of SessionRunHook for the pre-emptible Google Cloud + TPU service. It attempts to close the session if the TPU is preempted, and + exits the coordinator process if the session cannot be closed. + """ + + def __init__(self, cluster): + self._cluster = cluster + + def after_create_session(self, session, coord): + if tpu_cluster_resolver.is_running_in_gce(): + self._tpu_poller = _TPUPollingThread(self._cluster, session) + self._tpu_poller.start() + + def end(self, session): + self._tpu_poller.stop() + + +class _TPUPollingThread(threading.Thread): + """A thread that polls the state of a TPU node. + + When the node transitions into a TERMINAL state (PREEMPTED, TERMINATED) + that's considered as not recoverable by the underlying infrastructure, + it attempts to close the session, and exits the entire process if the + session.close() stucks. + """ + + def __init__(self, cluster, session): + super(_TPUPollingThread, self).__init__() + + self.daemon = True + self._running = True + self._session_closed = False + self._cluster = cluster + self._session = session + self._interval = 30 + + # Some of the Google API libraries are quite chatty, so disable them. + for name in ['googleapiclient.discovery', 'oauth2client.client']: + _logging.getLogger(name).setLevel(_logging.WARNING) + + def stop(self): + self._running = False + self._session_closed = True + self.join() + + def run(self): + if not tpu_cluster_resolver.is_running_in_gce(): + logging.warning( + 'TPUPollingThread is running in a non-GCE environment, exiting...') + self._running = False + return + + while self._running: + recoverable = self._cluster._cloud_tpu_client.recoverable() # pylint: disable=protected-access + if not recoverable: + logging.warning( + 'TPUPollingThread found TPU %s in state %s', + self._cluster._tpu, self._cluster._cloud_tpu_client.state()) # pylint: disable=protected-access + os._exit(1) # pylint: disable=protected-access + time.sleep(self._interval) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/session_support.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/session_support.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2a337a2a68aaa6d91c9e7f0501372dcb3c4b86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/session_support.py @@ -0,0 +1,448 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the 'License'); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an 'AS IS' BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Operations for handling session logging and shutdown notifications.""" + +import threading + +import time +from google.protobuf import text_format + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.training import session_run_hook +from tensorflow.python.training import training_util + +_WATCHDOG = None + + +class CoordinatorResetError(errors.AbortedError): + """Raised when the monitored session should reset.""" + + def __init__(self): + errors.AbortedError.__init__( + self, None, None, 'Resetting session loop due to worker shutdown.') + + +def _clone_session(session, graph=None): + return session_lib.Session( + target=session.sess_str, + config=session._config, # pylint: disable=protected-access + graph=graph if graph else session.graph) + + +class WorkerHeartbeatManager(object): + """Manages the status/heartbeat monitor for a set of workers.""" + + def __init__(self, session, devices, heartbeat_ops, request_placeholder): + """Construct a new WorkerHeartbeatManager. + + (Prefer using `WorkerHeartbeatManager.from_devices` when possible.) + + Args: + session: `tf.compat.v1.Session`, session to use for heartbeat operations. + devices: `list[string]` Set of devices to connect to. + heartbeat_ops: `list[tf.Operation]` Heartbeat operations. + request_placeholder: `tf.Placeholder[String]` Placeholder used to specify + the WorkerHeartbeatRequest protocol buffer. + """ + self._session = session + self._devices = devices + self._ops = heartbeat_ops + self._request_placeholder = request_placeholder + + @staticmethod + def from_devices(session, devices): + """Construct a heartbeat manager for the given devices.""" + if not devices: + logging.error('Trying to create heartbeat manager with no devices?') + + logging.info('Creating heartbeat manager for %s', devices) + request_placeholder = array_ops.placeholder( + name='worker_heartbeat_request', dtype=dtypes.string) + + heartbeat_ops = [] + for device in devices: + with ops.device(device): + heartbeat_ops.append(tpu_ops.worker_heartbeat(request_placeholder)) + + return WorkerHeartbeatManager(session, devices, heartbeat_ops, + request_placeholder) + + def num_workers(self): + return len(self._devices) + + def configure(self, message): + """Configure heartbeat manager for all devices. + + Args: + message: `event_pb2.WorkerHeartbeatRequest` + Returns: `None` + """ + logging.info('Configuring worker heartbeat: %s', + text_format.MessageToString(message)) + self._session.run(self._ops, + {self._request_placeholder: message.SerializeToString()}) + + def ping(self, request=None, timeout_in_ms=60000): + """Ping all workers, returning the parsed status results.""" + if request is None: + request = event_pb2.WorkerHeartbeatRequest() + + options = config_pb2.RunOptions(timeout_in_ms=timeout_in_ms) + results = self._session.run( + self._ops, + feed_dict={self._request_placeholder: request.SerializeToString()}, + options=options) + parsed_results = [ + event_pb2.WorkerHeartbeatResponse.FromString(res_pb) + for res_pb in results + ] + logging.debug('Ping results: %s', parsed_results) + return parsed_results + + def lame_workers(self): + """Ping all workers, returning manager containing lame workers (or None).""" + ping_results = self.ping() + lame_workers = [] + + for ping_response, device, op in zip(ping_results, self._devices, + self._ops): + if ping_response.health_status != event_pb2.OK: + lame_workers.append((device, op)) + + if not lame_workers: + return None + + bad_devices, bad_ops = zip(*lame_workers) + return WorkerHeartbeatManager(self._session, bad_devices, bad_ops, + self._request_placeholder) + + def __repr__(self): + return 'HeartbeatManager(%s)' % ','.join(self._devices) + + # Default timeout is set to allow other shutdown triggered operations (log + # flushing etc) to finish before terminating the worker. + def shutdown(self, wait_time_in_ms=60000, exit_code=0): + """Shutdown all workers after `shutdown_timeout_secs`.""" + logging.info('Shutting down %s.', self) + req = event_pb2.WorkerHeartbeatRequest( + watchdog_config=event_pb2.WatchdogConfig(timeout_ms=wait_time_in_ms), + shutdown_mode=event_pb2.SHUTDOWN_AFTER_TIMEOUT, + exit_code=event_pb2.RequestedExitCode(exit_code=exit_code)) + self.configure(req) + + # Wait for workers to shutdown. + sleep_sec = 10.0 + wait_time_in_ms / 1000 + logging.info('Waiting %.2f seconds for worker shutdown.', sleep_sec) + time.sleep(sleep_sec) + + +def all_worker_devices(session): + """Return a list of devices for each worker in the system.""" + devices = session.list_devices() + + devices_that_support_heartbeats = [] + + for device in devices: + name = device.name + # Pick devices that have a TPU but target the attached CPU + if ':TPU:0' in name and 'coordinator' not in name: + devices_that_support_heartbeats.append(name.replace('TPU', 'CPU')) + + return devices_that_support_heartbeats + + +class WatchdogManager(threading.Thread): + """Configures worker watchdog timer and handles periodic pings. + + Usage: + # Ping workers every minute, shutting down workers if they haven't received + # a ping after 1 hour. + watchdog_manager = WatchdogManager( + ping_interval=60, shutdown_timeout=3600 + ) + + # Use as a context manager, resetting watchdog on context exit: + with watchdog_manager: + session.run(...) + + # Or setup globally; watchdog will remain active until program exit. + watchdog_manager.configure_and_run() + """ + + def __init__(self, + session, + devices=None, + ping_interval=60, + shutdown_timeout=2 * 3600): + """Initialize a watchdog manager. + + Args: + session: Session connected to worker devices. A cloned session and graph + will be created for managing worker pings. + devices: Set of devices to monitor. If none, all workers will be + monitored. + ping_interval: Time, in seconds, between watchdog pings. + shutdown_timeout: Time, in seconds, before watchdog timeout. + """ + threading.Thread.__init__(self) + self.ping_interval = ping_interval + self.shutdown_timeout = shutdown_timeout + self.daemon = True + self._config = session._config # pylint: disable=protected-access + self._target = session.sess_str + self._running = False + self._devices = devices + + self._graph = None + self._session = None + self._worker_manager = None + + def _reset_manager(self, stopping=False): + """Reset the graph, session and worker manager.""" + self._graph = ops.Graph() + self._session = session_lib.Session( + target=self._target, + graph=self._graph, + config=self._config, + ) + + if self._devices is None: + self._devices = all_worker_devices(self._session) + + with self._graph.as_default(): + self._worker_manager = WorkerHeartbeatManager.from_devices( + self._session, self._devices) + + if stopping: + timeout_ms = -1 + shutdown_mode = event_pb2.NOT_CONFIGURED + else: + timeout_ms = self.shutdown_timeout * 1000 + shutdown_mode = event_pb2.WAIT_FOR_COORDINATOR + + self._worker_manager.configure( + event_pb2.WorkerHeartbeatRequest( + watchdog_config=event_pb2.WatchdogConfig(timeout_ms=timeout_ms), + shutdown_mode=shutdown_mode)) + + def configure_and_run(self): + logging.info( + 'Enabling watchdog timer with %d second timeout ' + 'and %d second ping interval.', self.shutdown_timeout, + self.ping_interval) + self._reset_manager() + self._running = True + self.start() + + def stop(self): + logging.info('Stopping worker watchdog.') + self._reset_manager(stopping=True) + self._running = False + self.join() + + def __enter__(self): + self.configure_and_run() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.stop() + + def run(self): + # Don't fetch logs or adjust timing: just ping the watchdog. + # + # If we hit an exception, reset our session as it is likely broken. + while self._running: + try: + self._worker_manager.ping(request=None) # pytype: disable=attribute-error + time.sleep(self.ping_interval) + except errors.OpError as e: + # Catch any TF errors that occur so we don't stop sending heartbeats + logging.debug('Caught error while sending heartbeat: %s', e) + self._reset_manager() + + +def start_worker_watchdog(session, + devices=None, + ping_interval=60, + shutdown_timeout=3600): + """Start global worker watchdog to shutdown workers on coordinator exit.""" + global _WATCHDOG + if _WATCHDOG is None: + # Ensure we can send a few pings before we timeout! + ping_interval = min(shutdown_timeout / 10., ping_interval) + _WATCHDOG = WatchdogManager(session, devices, ping_interval, + shutdown_timeout) + _WATCHDOG.configure_and_run() + + +def stop_worker_watchdog(): + """Stop global worker watchdog.""" + global _WATCHDOG + if _WATCHDOG is not None: + _WATCHDOG.stop() + _WATCHDOG = None + + +class GracefulShutdownHook(session_run_hook.SessionRunHook): + """Session hook that watches for shutdown events. + + If a shutdown is indicated, `saver.save(checkpoint_prefix)` is executed, and a + SystemShutdown exception is raised to terminate the main session. If `saver` + is None the `SAVERS` collection will be read to find a saver. + + `on_shutdown_hooks` is an optional list of functions that should be called + after checkpointing. The function is called with (`run_context`, + `all_workers`, `lame_workers`). + + If `heartbeat_group` is not specified, it will default to all CPU workers + in the system. + """ + + def __init__(self, checkpoint_prefix, saver=None, on_shutdown_hooks=None): + self._saver = saver + self._checkpoint_prefix = checkpoint_prefix + self._on_shutdown_hooks = on_shutdown_hooks if on_shutdown_hooks else [] + + # Worker heartbeats are managed independently of the main training graph. + self._graph = ops.Graph() + self._workers = None + self._session = None + self._heartbeat_supported = False + + def after_create_session(self, training_session, coord): # pylint: disable=unused-argument + # N.B. We have to pull the global step here to avoid it being unavailable + # at checkpoint time; the graph has been frozen at that point. + if training_util.get_global_step() is None and self.saver() is not None: + raise ValueError( + 'Saver defined but no global step. Run `get_or_create_global_step()`' + ' in your model definition to allow checkpointing.') + + with self._graph.as_default(): + logging.info('Installing graceful shutdown hook.') + self._session = _clone_session(training_session, self._graph) + self._workers = WorkerHeartbeatManager.from_devices( + self._session, all_worker_devices(self._session)) + self._heartbeat_supported = self._workers.num_workers() > 0 + if self._heartbeat_supported: + try: + self._workers.configure( + event_pb2.WorkerHeartbeatRequest( + shutdown_mode=event_pb2.WAIT_FOR_COORDINATOR)) + except errors.InvalidArgumentError: + logging.warn( + 'TPU device does not support heartbeats. Failure ' + 'handling will be disabled.') + self._heartbeat_supported = False + else: + logging.warn( + 'No workers support heartbeats. Failure handling will be disabled.') + + def saver(self): + if self._saver: + return self._saver + + savers = ops.get_collection(ops.GraphKeys.SAVERS) + if not savers: + return None + + if not isinstance(savers, list): + return savers + + if len(savers) > 1: + logging.error( + 'Multiple savers in the SAVERS collection. On-demand checkpointing ' + 'will be disabled. Pass an explicit `saver` to the constructor to ' + 'override this behavior.') + return None + + return savers[0] + + def after_run(self, run_context, run_values): + del run_values + if not self._heartbeat_supported: + return + + lame_workers = self._workers.lame_workers() + + if lame_workers: + logging.info('ShutdownHook: lame workers found: %s', lame_workers) + + if self.saver(): + logging.info('ShutdownHook: saving checkpoint to %s', + self._checkpoint_prefix) + self.saver().save( + run_context.session, + self._checkpoint_prefix, + global_step=training_util.get_global_step(), + write_state=True, + ) + else: + logging.info('ShutdownHook: no Saver defined.') + + for fn in self._on_shutdown_hooks: + fn(run_context, self._workers, lame_workers) + + +class ResetComputation(object): + """Hook to reset a TPUEstimator computation loop. + + This hook shuts down all workers and resets the monitored session loop by + throwing a CoordinatorResetError. + """ + + def __init__(self): + pass + + def __call__(self, run_context, all_workers, lame_workers): + del run_context, lame_workers + all_workers.shutdown(exit_code=42) + + logging.info('Resetting coordinator.') + raise CoordinatorResetError() + + +class ShutdownLameWorkers(object): + """Shutdown lamed workers. + + Processing will continue normally (typically by waiting for the down + workers to be restarted). + """ + + def __init__(self): + pass + + def __call__(self, run_context, all_workers, lame_workers): + lame_workers.shutdown(exit_code=42) + + +class ShutdownAllWorkers(object): + """Shutdown all workers. + + Processing will continue normally (typically by waiting for the down + workers to be restarted). + """ + + def __init__(self): + pass + + def __call__(self, run_context, all_workers, lame_workers): + all_workers.shutdown(exit_code=42) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..e8550ddeb1de8708bb7241b59a6453d18856e650 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer.py @@ -0,0 +1,2314 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== +"""A utility to trace tensor values on TPU.""" + +import collections +import hashlib +import operator +import os +import os.path +import sys + +import numpy as np + +from tensorflow.core.framework import summary_pb2 +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import function +from tensorflow.python.framework import graph_io +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_case +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import logging_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops import summary_ops_v2 as summary +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import analytics +from tensorflow.python.platform import gfile +from tensorflow.python.platform import remote_utils +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.summary import summary_iterator +from tensorflow.python.tpu import tensor_tracer_flags +from tensorflow.python.tpu import tensor_tracer_report +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.training import training_util + +_DEVICE_TYPE_TPU = 'tpu' +_DEVICE_TYPE_CPU = 'cpu' +_TRACE_MODE_PART_TENSOR_SIZE = 3 + +_REASON_OUTSIDE_OP_RANGE = 'not-traced-outside-op-range' +_REASON_UNSAFE_OP = 'not-traced-unsafe-op' +_REASON_WHILELOOP_OP = 'not-traced-special-whileloop-op' +_REASON_CONTROLFLOW_OP = 'not-traced-control-flow-op' +_REASON_IN_CONTROL_FLOW = 'not-traced-in-control-flow' +_REASON_UNSAFE_SCALAR = 'not-traced-unsafe-scalar' +_REASON_SKIP_SCALAR = 'not-traced-scalar' +_REASON_LESS_INTERESTING_OP = 'not-traced-less-interesting-op' +_REASON_DEVICE_MISMATCH = 'not-traced-device-mismatch' +_REASON_DYNAMIC_SHAPE = 'not-traced-dynamic-shape' +_REASON_SCALAR_GET_TRACED = 'traced-scalar' +_REASON_TENSOR_GET_TRACED = 'traced-tensor' +_REASON_USER_INCLUDED = 'traced-user-included' +_REASON_USER_EXCLUDED = 'not-traced-user-excluded' +_REASON_NOT_EXECUTED = 'not-traced-not-in-exec-path' +_REASON_NON_NUMERIC_TENSOR = 'not-traced-non-numeric-tensor' +_REASON_FEEDS_WHILELOOP_OP = 'not-traced-feeds-special-whileloop-op' + +_OUTPUT_STREAM_ESCAPE = 'file://' +_TENSOR_TRACER_COLLECTION = 'tensor_tracer_variables' +TENSOR_TRACER_SUMMARY_COLLECTION = 'tensor_tracer_summary_writers' +_TRACE_FILE_NAME = 'trace.all' +_COMPACT_TRACE_FILE_PREFIX = 'compact_trace.' +_COMPACT_TRACE_ENTRY_INIT_VALUE = -1.0 +_TENSOR_TRACER_STORAGE = 'tensor_tracer_storage' +_TT_SNAPSHOT = 'tensor_tracer_snapshot' +_REPLICA_ID_TAG = '#replica-id: ' +_SKIP_REPORT_FILE = 'None' # Do not write report proto if --report_file=None + +_TT_SUMMARY_NORM = tensor_tracer_flags.TT_SUMMARY_NORM +_TT_SUMMARY_MAX = tensor_tracer_flags.TT_SUMMARY_MAX +_TT_SUMMARY_MAX_ABS = tensor_tracer_flags.TT_SUMMARY_MAX_ABS +_TT_SUMMARY_MIN = tensor_tracer_flags.TT_SUMMARY_MIN +_TT_SUMMARY_MEAN = tensor_tracer_flags.TT_SUMMARY_MEAN +_TT_SUMMARY_VAR = tensor_tracer_flags.TT_SUMMARY_VAR +_TT_SUMMARY_SIZE = tensor_tracer_flags.TT_SUMMARY_SIZE +_TT_SUMMARY_SPARSITY = tensor_tracer_flags.TT_SUMMARY_SPARSITY + +_TT_SUMMARY_TAG = 'tensor_tracer_summary' +_TT_TENSORBOARD_PLUGIN_NAME = 'tensor_tracer' +_TT_HOSTCALL_KEY = 'tensor_tracer_host_call' +_TT_EVENT_FILE_SUFFIX = '.tensor_tracer' + +_TT_SUMMARY_MAX_QUEUE = 10 + +tt_gauge = monitoring.BoolGauge('/tensorflow/api/tensor_tracer/v1', + 'tensor tracer usage', 'method') + + +def _graph_summary_tag(graph): + """Generates and returns a summary tag name for the given graph.""" + + if graph is None: + raise RuntimeError('graph is None') + # The chance of collision with md5 is effectively 0. + hash_id = hashlib.md5() + hash_id.update(repr(graph).encode('utf-8')) + # hexdigest() returns a string. + return hash_id.hexdigest() + + +def set_parameters(tensor_tracer_params=None): + """Enables tensor tracer and sets its parameters. + + Example usage: + tensor_tracer_parameters = {'trace_dir': '/usr/tmp/trace_dir', + 'trace_mode': 'norm', + 'report_file': '/usr/tmp/trace_dir/report.all'} + tensor_tracer.set_parameters(tensor_tracer_parameters) + + This sets up the parameters for tensor tracer. A call to tensor tracer as + below is necessary to enable debugging on CPUs and GPUs. On TPUs below can be + skipped as this call is hooked into tpu.rewrite. + tt = tensor_tracer.TensorTracer() + loss = tt.trace_cpu(tf.get_default_graph(), tensor_fetches=loss) + + Args: + tensor_tracer_params: Tensor tracer parameter dictionary. Below gives + examples of these parameters: See tensor_tracer_report.py for all + parameters. + - enable: If set, tensor tracer will be enabled. Calling + enable_tensor_tracer automatically adds this parameters. + - trace_mode: The trace_mode to be used by tensor tracer. These include: + - summary: Collects multiple statistics for traced tensors, and writes + them a summary file that can be visualized using tensorboard. This + mode currently only works for TPUEstimator. It can be also be used + for other models, but outfeed must be handled by the user. + - norm: Collects norm of each traced tensor and writes them into a + text file pointed by 'trace_dir' flag. (Default mode). + - nan-inf: Checks the existince of NaNs and Infs in the tensor, and + writes a boolean value to a text file pointed by 'trace_dir' flag. + Note that 'norm' mode can also capture this information with more + numerical info. + - max-abs: Collects the absolute max for each traced tensors and + writes it into a text file pointed by 'trace_dir' flag. + - full-tensor: Writes the full tensor content of the traced tensors + into a text file pointed by 'trace_dir' flag. + - part-tensor: Writes a part of the tensor content of the traced + tensors into a text file pointed by 'trace_dir' flag. + - full_tensor_summary: Writes the full tensors as binary event files. + The outputs can be read using: trace = + tensor_tracer.read_tensor_tracer_event_file(event_file_path) + + - report_file: Path to the metadata file that is written during graph + construction. If not set, metadata will be printed to stdout during + graph construction. + - trace_dir: Path where the execution traces will be written during the + graph execution. If not set, trace will be printed to stderr. + - trace_level: Tensor tracer aims to trace everything it can. This + introduces some overhead on graph execution and graph compilation + times. Using trace_level parameter, it is possible to trace operation + based on their priorities. For example, - trace_level=7 is the highest + trace_level, in which every op is traced. - trace_level=6 will skip + constant operations such as tf.constant. - trace_level=5 will skip + less important ops such as tf.identities. - The default trace_level=3, + that will skip concat ops, or random number generators. - To reduce + the graph compile time overhead, trace_level can be set to 0, that + will skip additions, and substractions, and multiplications as well. + - excluded_opnames: If set, any matching op name will not be traced. + excluded_opnames can be set as a regular expression. E.g, + excluded_opnames=.* will exclude everything. + - excluded_optypes: If set, any matching op type will not be traced. + excluded_optypes can be set as a regular expression. E.g, + excluded_optypes=.* will exclude everything. excluded_optypes=MatMul + will exclude all MatMul ops from tracing. + - included_opnames: If set, any matching op name will be forced to be + traced. included_opnames can be set as a regular expression. E.g, + '--included_opnames=some_op --excluded_opname=*.' will only trace + some_op. + - included_optypes: If set, any matching op type will be forced to be + traced. included_optypes can be set as a regular expression. E.g, + '--included_optypes=some_op_type --excluded_optypes=*.' will trace + only the ops with type 'some_op_type' + - flush_summaries: If summary mode is used, flush_summaries=1 will + flush summaries using outside compilation. Note that, if used with + low level APIs, flush_summaries=1 is necessary to obtain results. + Advanced Flags: + - trace_scalar: Scalar values are not traced by default. If this flag is + set, scalar values will also be traced. + - op_range: In the form of '%d:%d' that limits the tracing to the ops + within this limit. --op_range='5:10' will trace only the ops that have + topological order between 5-10. + - submode: 'brief' or 'detailed'. If the trace mode is not compact, + brief mode will print only the id of each traced tensor to save some + space. 'detailed' mode prints the full tensor name. + - use_fingerprint_subdirectory: The trace directory will be chosen as + using the fingerprint of the trace metadata under the provided + trace_dir. + """ + enable_flags = '--%s=1' % tensor_tracer_flags.FLAG_NAME_ENABLE + if tensor_tracer_params: + for key, value in tensor_tracer_params.items(): + enable_flags += ' --%s=%s' % (key, value) + os.environ[tensor_tracer_flags.FLAGS_ENV_VAR] = enable_flags + + +def op_priority(op_type): + """Returns the priority of the op. + + If the priority of the op is k, it will be traced if trace_level>=k. + Args: + op_type: String name of the operation type. + Returns: + Integer value corresponding the priority of the op. + """ + if op_type in ('Const', 'Shape', 'BroadcastGradientArgs', 'Range', + 'VariableShape', 'Fill', 'OneHot', 'ShapeN'): + # Lowest priority ops, e.g., constant ops across different steps, + # They will be traced only if trace_level>=7 + return 7 + + if op_type in ('Identity', 'Cast', 'Reshape', 'ExpandDims', 'StopGradient', + 'PreventGradient', 'Squeeze', 'Gather', 'GatherNd'): + # Operations without numerical effects. + # They will be only if trace_level>=6 + return 6 + if op_type in ('ConcatV2', 'Concat', 'StridedSlice', 'Slice', 'Pack', 'Tile', + 'CollectivePermute', 'SplitV', 'DynamicPartition'): + # Operations that merge or slice an input, will be traced if trace_level>=5 + return 5 + if op_type in ('Pad', 'RandomUniformInt', 'GreaterEqual'): + # Operations less likely to provide useful information, + # will be traced if trace_level>=4 + return 4 + if op_type in ('Sum', 'AddV2', 'Add', 'AddN', 'BiasAdd', 'CrossReplicaSum'): + # Add operations that are less likely create any issues, will be traced + # if trace_level>=3 (default=3) + return 3 + if op_type in ('Neg', 'Sub'): + # Sub operations that are less likely create any issues, will be traced + # trace_level>=2 + return 2 + if op_type in ('Mul', 'Square', 'MatMul', 'RandomUniform', 'Select', + 'Maximum', 'Mean', 'Variance', 'Exp', 'Rsqrt'): + # Multiplication and some other operations, will be traced if trace_level>=1 + return 1 + + # Unclassified op_types default to being traced at level 2 and above. + return 2 + + +def read_tensor_tracer_event_file(event_file): + """Reads the event file written by tensor tracer. + + This can be used to read the full tensors written into binary event files by + by TensorTracer with trace_mode=full_tensor_summary. + + Example usage: + result_dict_list = tensor_tracer.read_tensor_tracer_event_file( + event_file_path) + for result_dict in result_dict_list: + for step, tensor_dict in result_dict.items(): + for tensor_name, full_tensor_content in tensor_dict.items(): + logging.info(tensor_name, full_tensor_content) + + Args: + event_file: Path to the event file that contains only tensor tracer events. + Returns: + A list of event dictionaries, each of which with the form: + {step_number: {tensor_name: tensor_content}}. This is a list instead of + a single event dictionary because it is possible that an event file may + have multiple event traces, each of them covering the same step ranges. + Raises: + ValueError: If an unexpected trace is found. + """ + + # Keeps track of how many times that a step number shows up in these events. + step_occurrence_count = collections.defaultdict(int) + + # List of step occurrences. + step_occurrence_list = [] + + for trace_event in summary_iterator.summary_iterator(event_file): + # First event is an event with file_version: "brain.Event:2" + if not trace_event.HasField('summary'): + continue + if len(trace_event.summary.value) != 1: + raise ValueError('Single step contains %d summary values,' + ' expected 1.' % len(trace_event.summary.value)) + step = trace_event.step + step_occurrence_count[step] += 1 # a new occurrence for this step. + + occurrence_idx = step_occurrence_count[step] - 1 + occurrence_size = len(step_occurrence_list) + + if occurrence_idx == occurrence_size: + # This particular occurrence isn't yet recorded on step_occurrence_list. + # So append this new occurrence to the end of step_occurrence_list. + new_occurrence = collections.defaultdict(dict) + step_occurrence_list.append(new_occurrence) + else: + # This particular occurrence must be already recorded on + # step_occurrence_list (i.e. occurrence_idx < occurrence_size). + if occurrence_idx > occurrence_size: + raise ValueError('Unexpected: occurrence_idx (%d) > ' + 'occurrence_size (%d)' % (occurrence_idx, + occurrence_size)) + tensor_value = trace_event.summary.value[0] + tensor_name = tensor_value.tag + + real_shape = [d.size for d in tensor_value.tensor.tensor_shape.dim] + tensor_content = np.frombuffer( + tensor_value.tensor.tensor_content, + dtypes.DType(tensor_value.tensor.dtype).as_numpy_dtype() + ).reshape(real_shape) + step_occurrence_list[occurrence_idx][step][tensor_name] = tensor_content + return step_occurrence_list + + +def trace_tensor(tensor, tracepoint_name=None): + """Programmatic interface to trace a tensor with Tensor Tracer. + + Tensor Tracer, by default, traces all tensors in the execution. This function + can be used to limit traced tensors. If this function is called for a subset + of the tensors, only those will be traced. + + For example, Tensor Traacer will only trace c below. + c = tf.MatMul(a, b) + tensor_tracer.trace_tensor(c) + d = tf.add(c, 1) + Args: + tensor: the tensor object for which the tracing is requested. + tracepoint_name: an optional tensor tracepoint name string. A tracepoint + name is an Tensor Tracer internal name for the tensor. It is useful when + comparing equivalent traces from different models that have different + tensor namings. Equivalent tensors (with different names) can be mapped + to each other by assigning a common tracepoint_name. + + Returns: + The provided tensor. + """ + if tracepoint_name is None: + tracepoint_name = tensor.name + tensor.graph.get_collection(_TENSOR_TRACER_COLLECTION) + tensor.graph.add_to_collection(_TENSOR_TRACER_COLLECTION, + (tensor, tracepoint_name)) + return tensor + + +def keras_layer_tracepoint(layer, checkpoint_name): + """An interface for adding the tensor outputs of a keras layer. + + Encapsulates trace_tensor. + + Args: + layer: A keras layer. + checkpoint_name: a string name for the checkpoint. This name has to be a + unique name if used within model comparison. The tensors that have the same + checkpoint identifier is compared in model comparison. + + Returns: + The provided layer. + """ + try: + outputs = layer.output + if tensor_util.is_tf_type(outputs): + trace_tensor(outputs, '%s' % (checkpoint_name)) + else: + idx = 0 + for output_tensor in outputs: + if tensor_util.is_tf_type(outputs): + trace_tensor(output_tensor, '%s_%d' % (checkpoint_name, idx)) + idx += 1 + except AttributeError: + pass + except RuntimeError: + pass + return layer + + +class TensorTracer: + """A software construct for tracing tensor values in a TF graph. + + This utility is disabled by default. It is hooked into tpu.rewrite, so it can + easily be enabled on TPUs by setting the TENSOR_TRACER_FLAGS env variable as + below without a code change. + export TENSOR_TRACER_FLAGS="--enable=1" + + Below is the use example to enable it on CPUs or GPUs, or for more advance use + cases on TPUs. + + a = x + 1 + b = a * 2 + rs = tf.reduce_sum(b) + tensor_tracer.set_parameters({'trace_dir': 'path/to/trace_dir', + 'report_file: 'path/to/report/file'}) + tt = tensor_tracer.TensorTracer() + if on_tpu: + rs = tt.trace_tpu(tf.get_default_graph(), + tensor_fetches=rs) + else: + rs = tt.trace_cpu(tf.get_default_graph(), + tensor_fetches=rs) + session.run(rs) + + If it is enabled, it will trace the output tensor values of + selected Ops in the graph. It has two outputs: (1) the traces and (2) + a report. The traces are dumped to a specified directory during the graph + execution, while the report is dumped during the graph construction. + By passing options via the env variable, users can change: + (1) the trace mode (e.g., detecting NaN/Inf, printing partial or + full tensor values) + (2) which Ops to be traced (via op.name or op.type) + (3) output trace file path. + + """ + # The set of graphs that are rewritten by tensor tracer. + _traced_graphs = set() + + @staticmethod + def is_enabled(): + """Returns True if TensorTracer is enabled.""" + try: + enable = tensor_tracer_flags.TTParameters().is_enabled() + # Add metrics to determine API usage. + if enable: tt_gauge.get_cell('is_enabled').set(True) + return enable + except (ValueError, RuntimeError) as e: + logging.warning( + 'Tensor Tracer V1 flags processing error encountered in is_enabled ' + 'check. %s', e) + # TODO(b/210212559): Find a more robust fix. + # Should only produce exception if Tensor Tracer is enabled. + return True + + @staticmethod + def check_device_type(device_type): + """Checks if the given device type is valid.""" + + if device_type not in (_DEVICE_TYPE_TPU, _DEVICE_TYPE_CPU): + raise ValueError('Invalid device_type "%s"'%device_type) + + @staticmethod + def check_trace_mode(device_type, trace_mode): + """Checks if the given trace mode work on the given device type. + + Args: + device_type: Device type, TPU, GPU, CPU. + trace_mode: Tensor tracer trace mode. + Raises: + ValueError: If the given trace mode is not supported for the device. + """ + if trace_mode == tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY: + if device_type != _DEVICE_TYPE_TPU: + raise ValueError('Device_type "%s" is not yet supported for ' + 'trace mode "%s"' % (device_type, trace_mode)) + + @staticmethod + def loop_cond_op(op): + return op.type in ('LoopCond', 'RefLoopCond') + + @staticmethod + def while_loop_op(op): + """Returns true if op is one of the special ops of in a while loop. + + Args: + op: A tf.Operation. + + Returns: + True if the given op is one of [Switch, Merge, Enter, Exit, + NextIteration, LoopCond], which are all building blocks for TF while + loops. + """ + return (control_flow_util.IsLoopSwitch(op) or + control_flow_util.IsLoopMerge(op) or + control_flow_util.IsLoopEnter(op) or + control_flow_util.IsLoopExit(op) or + TensorTracer.loop_cond_op(op) or + op.type in ('RefNextIteration', 'NextIteration')) + + @staticmethod + def control_flow_op(op): + """Returns true if op is one of the special ops of in a while loop. + + Args: + op: A tf.Operation. + + Returns: + True if the given op is one of [Switch, Merge, Enter, Exit, + NextIteration, LoopCond], which are all building blocks for TF while + loops. + """ + return (control_flow_util.IsSwitch(op) or + control_flow_util.IsMerge(op)) + + @staticmethod + def unsafe_op(op): + """Returns True if this op is not safe to be traced.""" + + # Reasons for not including following op types: + # Assign: cause incorrect result with CPU tracing. + if op.type == 'Assign': + return True + return False + + @staticmethod + def device_mismatch(device_type, op): + if device_type == _DEVICE_TYPE_TPU: + # pylint: disable=protected-access + return tpu_replication._TPU_REPLICATE_ATTR not in op.node_def.attr + # pylint: enable=protected-access + return False + + @staticmethod + def unsafe_scalar_trace(op): + """Return true if scalar output tensor from Op is not safe to be traced.""" + + # Tracing the following causes cycle in the graph on TPU. + if op.type in ('LoopCond', 'Enter', 'Merge', 'Const', + 'Switch', 'Less', 'ReadVariableOp'): + return True + # Tracing the following will cause casting-issue + # with the norm tracing mode or other compilation issues on CPU. + if op.type in ('VarHandleOp', 'IteratorToStringHandle', + 'IteratorGetNext', 'OneShotIterator', + 'IteratorV2', 'MakeIterator', + 'BatchDatasetV2', 'MapDataset', + 'FixedLengthRecordDataset', 'TakeDataset', 'ZipDataset', + 'Placeholder', 'PlaceholderWithDefault', 'StridedSlice'): + return True + return False + + def _is_interesting_op(self, op): + """Returns True if the given op is not an interesting one to be traced.""" + return op_priority(op.type) <= self._parameters.trace_level + + @staticmethod + def reason(op_idx, details): + """Returns reason why the Op at op_idx is traced or not.""" + + return '%d %s'%(op_idx, details) + + def __init__(self): + """Initializes a TensorTracer. + + Sets the various member fields from the flags (if given) or the defaults. + """ + self._replica_id = None + self._tt_config = tensor_tracer_report.TensorTracerConfig() + self._parameters = tensor_tracer_flags.TTParameters() + self._host_call_fn = {} + # _cache_variables is a dict (key = graph, value = dicts + # (key = name, value = tensors)) + self._cache_variables = {} + self._history_value_cache = {} + + self._traced_op_names = set() + self._report_proto = None + # _temp_cache_var is a dict (key = graph, value = []) + self._temp_cache_var = {} + self._report_proto_path = '' + self._outmost_context = None + + def report_proto(self): + """Getter for tensor_tracer.proto object for summary and full_tensor_summary modes. + + Returns: + A tensor_tracer.proto object. + Raises: + ValueError if called before tracing happens, or when trace mode is not + summary or full_tensor_summary. + """ + if self._report_proto: + return self._report_proto + else: + raise ValueError('Call to report_proto must be done after tracing.' + 'Report proto only exists for ' + 'trace_mode=[summary|full_tensor_summary]') + + def report_proto_path(self): + """Getter for path where tensor_tracer.proto object should be written. + + Returns: + A string path. + """ + return self._report_proto_path + + def _escape_namescopes(self, variable_name): + return variable_name.replace('/', '_').replace(':', '_') + + def _cache_variable_for_graph(self, graph): + if graph not in self._cache_variables: + self._cache_variables[graph] = {} + return self._cache_variables[graph] + + def _create_or_get_tensor_history_values_cache(self, + cache_name, + graph, + shape=None, + dtype=dtypes.float32): + """Creates a variable as the cache to store historic intermediate tensor values. + + Args: + cache_name: Name to be given to the cache (an instance of tf.variable). + graph: Tensorflow graph. + shape: A list of dimensions. + dtype: Data type of created cache. + Returns: + A ref to newly created or existing cache with the given dimensions. + Raises: + ValueError: + (1) If graph is None, or + (2) shape is None when a new cache needs to be created. + """ + if graph is None: + raise ValueError('Invalid graph.') + + if graph not in self._history_value_cache: + self._history_value_cache[graph] = {} + + if cache_name not in self._history_value_cache[graph]: + if shape is None: + raise ValueError('shape must be provided at cache creation.') + if dtype.is_integer: + init_val = int(_COMPACT_TRACE_ENTRY_INIT_VALUE) + else: + init_val = _COMPACT_TRACE_ENTRY_INIT_VALUE + + # Create in proper graph and base name_scope. + with graph.as_default() as g, g.name_scope(None): + self._history_value_cache[graph][ + cache_name] = variable_scope.get_variable( + 'tt_history' + '_' + self._escape_namescopes(cache_name), + shape=shape, + dtype=dtype, + initializer=init_ops.constant_initializer(init_val), + trainable=False, + use_resource=True, + collections=[ + _TENSOR_TRACER_STORAGE, ops.GraphKeys.LOCAL_VARIABLES + ]) + + return self._history_value_cache[graph][cache_name] + + def _create_or_get_tensor_values_cache(self, cache_name, graph, + shape=None, dtype=dtypes.float32): + """Creates a variable as the cache to store intermediate tensor values. + + Args: + cache_name: Name to be given to the cache (an instance of tf.variable). + graph: Tensorflow graph. + shape: A list of dimensions. + dtype: Data type of created cache. + Returns: + A ref to newly created or existing cache with the given dimensions. + Raises: + ValueError: + (1) If graph is None, or + (2) shape is None when a new cache needs to be created. + """ + if graph is None: + raise ValueError('Invalid graph.') + + graph_cache_var = self._cache_variable_for_graph(graph) + + if cache_name not in graph_cache_var: + if shape is None: + raise ValueError('shape must be provided at cache creation.') + if dtype.is_integer: + init_val = int(_COMPACT_TRACE_ENTRY_INIT_VALUE) + else: + init_val = _COMPACT_TRACE_ENTRY_INIT_VALUE + + # Create in proper graph and base name_scope. + with graph.as_default() as g, g.name_scope(None): + graph_cache_var[cache_name] = variable_scope.get_variable( + _TT_SNAPSHOT + '_' + self._escape_namescopes(cache_name), + shape=shape, dtype=dtype, + initializer=init_ops.constant_initializer(init_val), + trainable=False, + use_resource=True, + collections=[_TENSOR_TRACER_STORAGE, ops.GraphKeys.LOCAL_VARIABLES]) + return graph_cache_var[cache_name] + + def _add_replica_id_to_graph(self): + """Adds nodes for computing the replica ID to the graph.""" + + if self._tt_config.num_replicas: + with ops.control_dependencies(None): + # Uses None as dependency to run outside of TPU graph rewrites. + self._replica_id = tpu_ops.tpu_replicated_input( + list(range(self._tt_config.num_replicas)), + name='tt_replica_id') + else: + self._replica_id = 'unknown' + + def _inside_op_range(self, idx): + """Return True if the given index is inside the selected range.""" + + if idx < self._parameters.op_range[0]: + return False + return (self._parameters.op_range[1] < 0 or + idx <= self._parameters.op_range[1]) + + def _is_user_included_op(self, op): + """Checks whether the op is included in the tensor tracer flags. + + Args: + op: tf Operation + Returns: + True, if the op is included. + An op is included if: + - Its op name is given in included_opnames + - Its op type is given in included_optypes + - The op is at most _trace_ops_before_included hops before an included op + - The op is at most _trace_ops_after_included hops after an included op + """ + for opname_re in self._parameters.included_opname_re_list: + if opname_re.match(op.name): + return True + + for optype_re in self._parameters.included_optype_re_list: + if optype_re.match(op.type): + return True + return False + + def _is_user_excluded_op(self, op): + for opname_re in self._parameters.excluded_opname_re_list: + if opname_re.match(op.name): + return True + for optype_re in self._parameters.excluded_optype_re_list: + if optype_re.match(op.type): + return True + return False + + def _signature_types(self): + """Returns a dictionary holding the order of signatures in the cache for the selected trace mode.""" + if self._parameters.trace_mode in set([ + tensor_tracer_flags.TRACE_MODE_NAN_INF, + tensor_tracer_flags.TRACE_MODE_NORM, + tensor_tracer_flags.TRACE_MODE_HISTORY, + tensor_tracer_flags.TRACE_MODE_MAX_ABS]): + return {self._parameters.trace_mode: 0} + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY: + return self._parameters.summary_signatures + return {} + + def _num_signature_dimensions(self): + return len(self._signature_types()) + + def _use_temp_cache(self): + """Returns true if the intermediate values should be stacked instead of being stored in a tf.Variable. + + Returns: + A boolean, denoting whether to use a temporary cache or not. + """ + # If full tensors need to be stored tf.variables, then do not use temp + # variables to store them. + if self._use_tensor_buffer(): + return False + if self._use_tensor_values_cache(): + return self._parameters.use_temp_cache_var + else: + # Temporary caches only replaces tf.Variables caches. If no cache is used + # return False. + return False + + def _use_tensor_values_cache(self): + """Returns True if immediate tensors should be first saved to a cache.""" + return self._parameters.use_compact_trace + + def _use_tensor_buffer(self): + """Returns true if the whole tensor needs to be cached/buffered in memory.""" + return (self._parameters.trace_mode == + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY) + + def _merge_tensor_signatures(self, signatures): + """Returns a tensor that merges the given signatures. + + Args: + signatures: A dictionary of the signature updates from signature name to + a tensor of dimension [1]. + Returns: + A tensor that concats the signature values in a predefined order. + Raises: + ValueError: Unable to merge signatures. + """ + sorted_update = [] + if self._num_signature_dimensions() > 1: + signature_indices = self._signature_types() + for _, val in sorted(signatures.items(), + key=lambda item: signature_indices[item[0]]): + sorted_update.append(val) + updates = array_ops_stack.stack( + sorted_update, axis=0, name='merge_single_op_signatures') + elif self._num_signature_dimensions() == 1: + # Avoid stack operation if there is only a single signature. + (_, val), = signatures.items() + updates = val + else: + raise ValueError('Cannot merge 0 signatures. Check the value passed for ' + 'flag --signatures.') + return updates + + def _save_tensor_value_to_tmp_cache(self, cache_idx, updates, graph): + """Returns an op that will save the given updates to an entry in the cache. + + Args: + cache_idx: The cache index of the tensor within the cache. + updates: A dictionary of the signature updates from signature name to + a tensor of dimension [1]. + graph: A TensorFlow graph. + Raises: + RuntimeError: + (1) graph is not already in self._temp_cache_var, or + (2) cache_idx is out of range. + """ + updates = self._merge_tensor_signatures(updates) + updates = array_ops.reshape(updates, + [self._num_signature_dimensions()]) + if graph not in self._temp_cache_var: + raise RuntimeError('graph is not in self._temp_cache_var') + if cache_idx >= len(self._temp_cache_var[graph]): + raise RuntimeError('cache_idx (%d) is out of range (%d)' % ( + cache_idx, len(self._temp_cache_var[graph]))) + self._temp_cache_var[graph][cache_idx] = updates + + def _save_tensor_value_to_cache_op(self, cache_idx, updates, graph): + """Returns an op that will save the given updates to an entry in the cache. + + Args: + cache_idx: The cache index of the tensor within the cache. + updates: A dictionary of the signature updates. + graph: A TensorFlow graph. + Returns: + Cache update operation. + """ + # state_ops.scatter_update allows updates only along the first dimension. + # Make a compact array by concatenating different signatures, and update + # them all together. + updates = self._merge_tensor_signatures(updates) + updates = array_ops.reshape(updates, + [1, self._num_signature_dimensions()]) + indices = constant_op.constant([cache_idx]) + cache = self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG, graph) + return state_ops.scatter_update(cache, indices, updates).op + + def _snapshot_tensor(self, tensor): + """Creates a new tf.Variable and a new tf.Operation that assigns the value of the tensor to this variable. + + Args: + tensor: tensor whose values will be stored in a new tf.Variable. + Returns: + An assignment operation. + """ + + snapshot_variable = self._create_or_get_tensor_values_cache( + tensor.name, tensor.op.graph, + tensor.shape.as_list(), tensor.dtype) + return state_ops.assign(snapshot_variable, tensor).op + + def _preprocess_traced_tensor(self, tensor): + """Computes NAN/Norm/Max on TPUs before sending to CPU. + + Args: + tensor: The tensor to be traced. + Returns: + A tensor that should be input to the trace_function. + Raises: + RuntimeError: If the signature is invalid. + """ + + def _detect_nan_inf(tensor): + """Trace function for detecting any NaN/Inf in the tensor.""" + + if tensor.dtype.is_floating: + mask = math_ops.reduce_any( + gen_math_ops.logical_or( + gen_math_ops.is_nan(tensor), gen_math_ops.is_inf(tensor))) + output_tensor = cond.cond( + mask, + lambda: constant_op.constant([1.0]), + lambda: constant_op.constant([0.0])) + else: + output_tensor = constant_op.constant([0.0]) + return output_tensor + + def _compute_signature(tensor, tf_op, cast_to_f32=True): + if cast_to_f32: + tensor = math_ops.cast(tensor, dtypes.float32) + output_tensor = tf_op(tensor) + # Return type should be scalar. Set it if it does not have the + # information. + if not output_tensor.get_shape().is_fully_defined(): + output_tensor = array_ops.reshape(output_tensor, []) + return output_tensor + + def _show_size(tensor): + # In order to check the size of a tensor. + # Not all sizes are known at the compile time, also, different replicas + # sometimes get different sizes of tensors. + # Collect it here to be used in merging replica data. + tsize = _compute_signature(tensor, array_ops.size, cast_to_f32=False) + # Cast to float32, so that it can be placed into same cache with other + # signatures. + return math_ops.cast(tsize, dtypes.float32) + + def _show_max(tensor, cast_to_f32=True): + # returns -inf for empty tensor + return _compute_signature(tensor, math_ops.reduce_max, cast_to_f32) + + def _show_min(tensor, cast_to_f32=True): + # returns inf for empty tensor + return _compute_signature(tensor, math_ops.reduce_min, cast_to_f32) + + def _show_norm(tensor, cast_to_f32=True): + # returns 0 for empty tensor + return _compute_signature(tensor, linalg_ops.norm, cast_to_f32) + + def _show_sparsity(tensor, cast_to_f32=True, tolerance=1e-06): + # returns nan for empty tensor and treats nans as non-zero numbers + def sparsity_fn(tensor): + non_zeros = math_ops.greater_equal(math_ops.abs(tensor), tolerance) + nans = math_ops.is_nan(tensor) + return nn_impl.zero_fraction(math_ops.logical_or(non_zeros, nans)) + + return _compute_signature(tensor, sparsity_fn, cast_to_f32) + + def _show_mean_and_variance(tensor, cast_to_f32=True): + """Returns the mean and variance of the given tensor.""" + if cast_to_f32: + tensor = math_ops.cast(tensor, dtypes.float32) + # returns nan for empty tensor + mean, var = nn_impl.moments(array_ops.reshape(tensor, [-1]), axes=[0]) + # The shape has to be 1. Set it if it does not have the information. + if not mean.get_shape().is_fully_defined(): + mean = array_ops.reshape(mean, []) + if not var.get_shape().is_fully_defined(): + var = array_ops.reshape(var, []) + return mean, var + + def _show_max_abs(tensor, cast_to_f32=True): + return _compute_signature( + tensor, lambda t: math_ops.reduce_max(math_ops.abs(t)), cast_to_f32) + + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NAN_INF: + return {self._parameters.trace_mode: _detect_nan_inf(tensor)} + if (self._parameters.trace_mode == + tensor_tracer_flags.TRACE_MODE_PART_TENSOR): + return {self._parameters.trace_mode: tensor} + if (self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR, + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)): + return {self._parameters.trace_mode: tensor} + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NORM: + return {self._parameters.trace_mode: array_ops.reshape( + _show_norm(tensor), [1])} + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_HISTORY: + return {self._parameters.trace_mode: array_ops.reshape( + _show_norm(tensor), [1])} + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_MAX_ABS: + return {self._parameters.trace_mode: _show_max_abs(tensor)} + + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY: + tensor = math_ops.cast(tensor, dtypes.float32) + result_dict = {} + # Call mean and variance computation here to avoid adding the same nodes + # twice. + if (_TT_SUMMARY_MEAN in self._signature_types() or + _TT_SUMMARY_VAR in self._signature_types()): + mean, variance = _show_mean_and_variance(tensor, cast_to_f32=False) + + for signature_name, _ in sorted(self._signature_types().items(), + key=lambda x: x[1]): + if signature_name == _TT_SUMMARY_NORM: + signature_result_tensor = _show_norm(tensor, cast_to_f32=False) + elif signature_name == _TT_SUMMARY_MAX: + signature_result_tensor = _show_max(tensor, cast_to_f32=False) + elif signature_name == _TT_SUMMARY_MAX_ABS: + signature_result_tensor = _show_max_abs(tensor, cast_to_f32=False) + elif signature_name == _TT_SUMMARY_MIN: + signature_result_tensor = _show_min(tensor, cast_to_f32=False) + elif signature_name == _TT_SUMMARY_SPARSITY: + signature_result_tensor = _show_sparsity(tensor) + elif signature_name == _TT_SUMMARY_SIZE: + signature_result_tensor = _show_size(tensor) + elif signature_name == _TT_SUMMARY_MEAN: + signature_result_tensor = mean + elif signature_name == _TT_SUMMARY_VAR: + signature_result_tensor = variance + else: + raise ValueError('Unknown signature type :%s.' % signature_name) + + result_dict[signature_name] = signature_result_tensor + return result_dict + + raise RuntimeError( + 'Unsupported signature for trace mode %s.' + % self._parameters.trace_mode) + + def _make_tensor_trace_fun(self, tensor_name, tensor_trace_order): + """Makes the tensor tracing function called by outside compilation. + + Args: + tensor_name: name of the tensor being traced. + tensor_trace_order: TensorTraceOrder object holding tensorname to id map. + Returns: + A function to be passed as the first argument to outside compilation. + + Raises: + RuntimeError: If the trace mode is invalid. + """ + + def _print_tensor(tensor_name, num_elements, tensor, output_tensor): + """Prints a tensor value to a file. + + Args: + tensor_name: name of the tensor being traced. + num_elements: number of elements to print (-1 means print all). + tensor: the tensor needs to be returned. + output_tensor: the tensor needs to be printed. + + Returns: + The same tensor passed via the "tensor" argument. + + Raises: + ValueError: If tensor_name is not already in + tensor_trace_order.tensorname_to_cache_idx. + """ + + if self._parameters.is_brief_mode(): + if tensor_name not in tensor_trace_order.tensorname_to_cache_idx: + raise ValueError( + 'Tensor %s with name %s is not in the tensorname_to_cache_idx' % + (tensor, tensor_name)) + msg = '%d' % tensor_trace_order.tensorname_to_cache_idx[tensor_name] + else: + msg = '"%s"' % tensor_name + + if self._parameters.trace_dir: + output_path = os.path.join( + self._parameters.trace_dir, + _TRACE_FILE_NAME + self._get_outfile_suffix()) + output_stream = _OUTPUT_STREAM_ESCAPE + output_path + else: + output_stream = sys.stderr + return logging_ops.print_v2(msg, array_ops.shape(output_tensor), + '@', self._replica_id, + '\n', output_tensor, '\n', + summarize=num_elements, + output_stream=output_stream) + + def _show_part_tensor(tensor): + """Trace function for printing part of the tensor.""" + + return _print_tensor(tensor_name, _TRACE_MODE_PART_TENSOR_SIZE, + tensor, tensor) + + def _show_full_tensor(tensor): + """Trace function for printing the entire tensor.""" + + return _print_tensor(tensor_name, -1, tensor, tensor) + + if (self._parameters.trace_mode == + tensor_tracer_flags.TRACE_MODE_PART_TENSOR): + return _show_part_tensor + # The input tensor has a shape of "[1]" for TRACE_MODE_NAN_INF, + # TRACE_MODE_NORM, and TRACE_MODE_MAX_ABS, as related computations are + # performed within TPUs and only their results are transferred to CPU. + # Simply, print the full tensor for these trace modes. + if self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_NAN_INF, + tensor_tracer_flags.TRACE_MODE_NORM, + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR, + tensor_tracer_flags.TRACE_MODE_MAX_ABS, + tensor_tracer_flags.TRACE_MODE_SUMMARY, + tensor_tracer_flags.TRACE_MODE_HISTORY + ): + return _show_full_tensor + + raise RuntimeError('Full tensor support is not available with trace mode %s' + %self._parameters.trace_mode) + + def _is_in_control_flow(self, op): + """Returns true if the given op is inside a tf.cond or in tf.while_loop. + + Args: + op: A tensorflow op that should be checked whether in control flow or not. + Returns: + A boolean value whether the op is in control flow or not. + """ + return control_flow_util.IsInCond(op) + + def _is_in_outmost_while_loop(self, op): + """Returns true if the op is at the same level with the training loop. + + Returns false if the op is in an inner while loop or if it is outside of the + training loop. + Args: + op: tf.Operation + + Returns: + A boolean. + """ + ctxt = self._get_op_control_flow_context(op) + outer_while_context = control_flow_util.GetContainingWhileContext(ctxt) + return outer_while_context == control_flow_util.GetContainingWhileContext( + self._outmost_context) + + def _should_trace_in_control_flow(self): + """Returns false incase it is not safe to trace ops in tf.cond or tf.while_loop.""" + # As different from the other trace modes, TRACE_MODE_OPTIONAL_SUMMARY + # forces the execution of the traced tensors. We should not trace the ops + # that may not be executed due to control flow. + if self._use_temp_cache(): + return False + elif self._tt_config.device_type == _DEVICE_TYPE_TPU: + # On TPUs do not trace in control flow unless we use caches to store + # intermediate values as calling outside compilation within an inner loop + # causes errors. + return self._use_tensor_values_cache() or self._use_tensor_buffer() + return True + + def _skip_op(self, op_id, op, ops_in_exec_path, report_handler): + """Returns True if we should not trace Op. + + Args: + op_id: Topological index of the op. + op: tf.Operation + ops_in_exec_path: Set of operations that are in the execution path. + report_handler: An instance of tensor_tracer_report.TTReportHandle. + Returns: + True if the op should not be traced, false otherwise. + """ + if TensorTracer.while_loop_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_WHILELOOP_OP)) + return True + if TensorTracer.control_flow_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_CONTROLFLOW_OP)) + return True + if TensorTracer.unsafe_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_UNSAFE_OP)) + return True + if TensorTracer.device_mismatch(self._tt_config.device_type, op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_DEVICE_MISMATCH)) + return True + if op not in ops_in_exec_path: + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_NOT_EXECUTED)) + return True + # TensorTracer will not trace the operations that are in an inner while loop + # or tf.cond when a temporary cache is used. Temporary cache adds direct + # data dependencies to traced operations, and needs a static number of + # traced operations. For these cases, + # - We do not know the number of slots required when there are inner while + # loops. TensorTracer can only trace the result of a while loop. + # - We do not know ahead of time which branch of the tf.cond + # will be taken, so we avoid introducing data dependencies for the + # operations inside a tf.cond. + # - We also cannot have a data dependency to an operation in a different + # while context. + if self._is_in_control_flow(op) or not self._is_in_outmost_while_loop(op): + if not self._should_trace_in_control_flow(): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_IN_CONTROL_FLOW)) + return True + if self._is_user_included_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_USER_INCLUDED)) + if tensor_tracer_flags.TT_CHECK_FILTER.value: + logging.info('USER_INCLUDED op %s', op.name) + return False + + if not self._inside_op_range(op_id): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_OUTSIDE_OP_RANGE)) + return True + if not self._is_interesting_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_LESS_INTERESTING_OP)) + return True + if self._is_user_excluded_op(op): + report_handler.instrument_op( + op, TensorTracer.reason(op_id, _REASON_USER_EXCLUDED)) + if tensor_tracer_flags.TT_CHECK_FILTER.value: + logging.info('USER_EXCLUDED op %s', op.name) + return True + return False + + def _skip_tensor(self, op_id, out_tensor, report_handler): + """Returns True if we should not trace out_tensor. + + Args: + op_id: Topological index of the op producing tensor. + out_tensor: tf.Tensor + report_handler: An instance of tensor_tracer_report.TTReportHandle. + Returns: + True if the tensor should not be traced, false otherwise. + """ + + # Skips a tensor if the tensor has a non-numeric type. + # Note: we cannot use check_ops.is_numeric_tensor(out_tensor) + # because it also excludes tensors with dtypes, bool, and + # float32_ref, which we actually want to trace. + non_numeric_tensor_types = set([dtypes.variant, dtypes.resource, + dtypes.string]) + if out_tensor.dtype in non_numeric_tensor_types: + + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_NON_NUMERIC_TENSOR)) + return True + # Skip a tensor if it feeds a special while loop op. + if [consumer for consumer in out_tensor.consumers() if + TensorTracer.while_loop_op(consumer)]: + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_FEEDS_WHILELOOP_OP)) + return True + if self._is_user_included_op(out_tensor.op): + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_USER_INCLUDED)) + if tensor_tracer_flags.TT_CHECK_FILTER.value: + logging.info('USER_INCLUDED tensor %s', out_tensor.name) + return False + if self._is_user_excluded_op(out_tensor.op): + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_USER_EXCLUDED)) + if tensor_tracer_flags.TT_CHECK_FILTER.value: + logging.info('USER_EXCLUDED tensor %s', out_tensor.name) + return True + if not out_tensor.get_shape().is_fully_defined(): + # If trace mode is nan-inf, norm or max, then the tensor will be reduced + # to a scalar before the outside compilation call. + if self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_NAN_INF, + tensor_tracer_flags.TRACE_MODE_NORM, + tensor_tracer_flags.TRACE_MODE_HISTORY, + tensor_tracer_flags.TRACE_MODE_MAX_ABS, + tensor_tracer_flags.TRACE_MODE_SUMMARY + ): + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_TENSOR_GET_TRACED)) + return False + else: + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_DYNAMIC_SHAPE)) + return True + rank = len(out_tensor.shape) + if rank < 1: + # scalar + if self._parameters.trace_scalar_ops: + if TensorTracer.unsafe_scalar_trace(out_tensor.op): + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_UNSAFE_SCALAR)) + return True + else: + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_SCALAR_GET_TRACED)) + return False + else: + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_SKIP_SCALAR)) + return True + else: + # tensor + report_handler.instrument_tensor( + out_tensor, TensorTracer.reason(op_id, _REASON_TENSOR_GET_TRACED)) + return False + + def _filter_execution_path_operations(self, operations, fetches): + """Returns the set of ops in the execution path to compute given fetches.""" + + # If no fetch provided, then return all operations. + if fetches is None: + return set(operations) + # Convert to list, if a single element is provided. + if not isinstance(fetches, (list, tuple)): + fetches = [fetches] + # If a tensor is given as fetch, convert it to op. + op_fetches = [] + for fetch in fetches: + if isinstance(fetch, ops.Operation): + op_fetches.append(fetch) + elif isinstance(fetch, tensor_lib.Tensor): + op_fetches.append(fetch.op) + else: + raise RuntimeError('Given fetch:%s is neither a tensor nor an op.' + %fetch) + + execution_path_operations = set(op_fetches) + traverse_stack = list(op_fetches) + while True: + if not traverse_stack: + break + head_op = traverse_stack.pop() + input_ops = [tensor_input.op for tensor_input in head_op.inputs] + input_ops.extend(head_op.control_inputs) + + for input_op in input_ops: + if input_op not in execution_path_operations: + # Filter out loop condition operations, tracing them causes a cycle. + # Trace only the loop-body. + if TensorTracer.loop_cond_op(input_op): + continue + execution_path_operations.add(input_op) + traverse_stack.append(input_op) + return execution_path_operations + + def _determine_and_instrument_traced_tensors(self, graph_order, + ops_in_exec_path, + tensor_trace_points, + report_handler): + """Determines the tensors to trace and instruments the trace details. + + Args: + graph_order: graph_order tuple containing graph (tf.graph), operations + (list of operations), op_to_idx (op id mapping), (tensors) list of + tensors, tensor_to_idx (tensor id mapping), contains_cycle (whether + there is a cycle in the graph), topological_order_or_cycle (list of ops + in topological order or list of ops creating a cycle). + ops_in_exec_path: Set of ops in the execution path. + tensor_trace_points: Collection of programatic tensor trace points. + report_handler: An instance of tensor_tracer_report.TTReportHandle. + Returns: + List of tensors to be traced. + """ + + traced_tensors = [] + checkpoint_operations = set([tensor.op + for (tensor, _) in tensor_trace_points]) + for op_id, op in enumerate(graph_order.operations): + if checkpoint_operations and op not in checkpoint_operations: + continue + if self._skip_op(op_id, op, ops_in_exec_path, report_handler): + continue + for i in range(len(op.outputs)): + out_tensor = op.outputs[i] + if not self._skip_tensor(op_id, out_tensor, report_handler): + traced_tensors.append(out_tensor) + return traced_tensors + + def _check_trace_files(self): + """Checks if any requirements for trace files are satisfied.""" + + if not self._parameters.trace_dir: + # traces will be written to stderr. No need to check trace files. + return + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY: + # Output files are handled by tf.summary operations, no need to precreate + # them. + return + if not gfile.Exists(self._parameters.trace_dir): + file_io.recursive_create_dir(self._parameters.trace_dir) + if not gfile.Exists(self._parameters.trace_dir): + raise RuntimeError('Failed to create trace directory at %s' % + self._parameters.trace_dir) + + def _create_temp_cache(self, num_traced_tensors, num_signatures, graph): + """Creates a temporary cache with the given dimensions. + + Fills the self._temp_cache_var with num_traced_tensors tf.constant() ops + that have shape of [num_signatures]. + Args: + num_traced_tensors: Int, denoting total number of traced tensors. + num_signatures: Int, denoting the number of statistics collected per + tensors. + graph: TensorFlow graph. + """ + init_value = constant_op.constant(_COMPACT_TRACE_ENTRY_INIT_VALUE, + dtype=dtypes.float32, + shape=[num_signatures]) + self._temp_cache_var[graph] = [ + init_value for _ in range(num_traced_tensors)] + + def _determine_trace_and_create_report(self, graph, ops_in_exec_path, + graph_summary_tag): + """Work needs to be done prior to TPU or CPU tracing. + + Args: + graph: tf.graph + ops_in_exec_path: Set of operations in the execution path. + graph_summary_tag: the summary tag name for the given graph. + Returns: + An instance of tensor_tracer_report.TensorTraceOrder, containing list of + tensors to be traced with their topological order information. + Raises: + RuntimeError: If opname filtering is incorrectly set. + """ + + self._check_trace_files() + + graph_order = tensor_tracer_report.sort_tensors_and_ops(graph) + tensor_trace_points = graph.get_collection(_TENSOR_TRACER_COLLECTION) + + report_handler = tensor_tracer_report.TTReportHandle() + traced_tensors = self._determine_and_instrument_traced_tensors( + graph_order, ops_in_exec_path, tensor_trace_points, report_handler) + logging.info('TensorTracer is tracing %d tensors.', len(traced_tensors)) + if traced_tensors and tensor_tracer_flags.TT_CHECK_FILTER.value: + raise RuntimeError('Verify ops being traced by tensor tracer.') + + tensor_trace_order = tensor_tracer_report.TensorTraceOrder(graph_order, + traced_tensors) + num_signatures = self._num_signature_dimensions() + # Create a cache variable if compact_tracing is used. + if num_signatures and self._use_tensor_values_cache(): + if self._use_temp_cache(): + self._create_temp_cache(len(traced_tensors), num_signatures, graph) + else: + self._create_or_get_tensor_values_cache( + _TT_SUMMARY_TAG, graph, [len(traced_tensors), num_signatures]) + if self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_HISTORY): + self._create_or_get_tensor_history_values_cache( + _TT_SUMMARY_TAG, graph, [len(traced_tensors), num_signatures]) + if self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_SUMMARY, + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY): + self._report_proto = report_handler.create_report_proto( + self._tt_config, self._parameters, tensor_trace_order, + tensor_trace_points, self._signature_types()) + if self._parameters.use_fingerprint_subdir: + self._parameters.trace_dir = os.path.join( + self._parameters.trace_dir, self._report_proto.fingerprint) + logging.info('TensorTracer updating trace_dir to %s', + self._parameters.trace_dir) + self._report_proto_path = report_handler.report_proto_path( + self._parameters.trace_dir, graph_summary_tag) + + if self._parameters.report_file_path != _SKIP_REPORT_FILE: + report_handler.write_report_proto(self._report_proto_path, + self._report_proto, self._parameters) + else: + if self._parameters.trace_mode not in ( + tensor_tracer_flags.TRACE_MODE_HISTORY): + report_handler.create_report(self._tt_config, self._parameters, + tensor_trace_order, tensor_trace_points) + return tensor_trace_order + + def _create_host_call(self): + return self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_SUMMARY, + tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY) + + def _inspect_summary_cache(self, cache, replica_id, step_num, output_stream, + tensor_trace_order): + """Generates a print operation to print trace inspection. + + Args: + cache: Tensor storing the trace results for the step. + replica_id: Tensor storing the replica id of the running core. + step_num: Step number. + output_stream: Where to print the outputs, e.g., file path, or sys.stderr. + tensor_trace_order: TensorTraceOrder object holding tensorname to id map. + + Returns: + The Op to flush the cache to file. + """ + def _inspect_tensor(tensor): + """Returns the text to be printed for inspection output.""" + if (self._parameters.trace_mode == + tensor_tracer_flags.TRACE_MODE_NAN_INF): + return cond.cond( + math_ops.greater(tensor, 0.0), + lambda: 'has NaNs/Infs!', + lambda: 'has no NaNs or Infs.') + else: + return tensor + + # Check if there are graph operations being profiled. + if not tensor_trace_order.traced_tensors: + logging.warn('Inspect mode has no tensors in the cache to check.') + return control_flow_ops.no_op + + # Check if the cache includes any nan or inf + if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NAN_INF: + # Cache has 1s or 0s if the mode is NaN_INF + step_has_nan_or_inf = math_ops.greater(math_ops.reduce_sum(cache), 0.0) + else: + # Cache has the actual numerics for other modes. + step_has_nan_or_inf = math_ops.reduce_any( + gen_math_ops.logical_or( + gen_math_ops.is_nan(cache), gen_math_ops.is_inf(cache))) + + # Summarizing message for each step. + step_error_message = cond.cond( + step_has_nan_or_inf, + lambda: 'NaNs or Infs in the step!', + lambda: 'No numerical issues have been found for the step.') + + # No need to print core numbers if the cache is merged already. + if self._parameters.collect_summary_per_core: + stats = ['\n\n', 'core:', replica_id, ',', 'step:', step_num, '-->', + step_error_message, + 'Printing tensors for mode:%s...' % self._parameters.trace_mode] + else: + stats = ['\n\n', 'step:', step_num, '-->', step_error_message, + 'Printing tensors for mode:%s...' % self._parameters.trace_mode] + + for tensor_name, cache_idx in sorted( + tensor_trace_order.tensorname_to_cache_idx.items(), + key=lambda item: item[1]): + if self._parameters.collect_summary_per_core: + stats.extend([ + '\n', 'core:', replica_id, ',', 'step:', step_num, ',', + tensor_name, '-->', _inspect_tensor(cache[cache_idx, 0])]) + else: + stats.extend([ + '\n', 'step:', step_num, ',', + tensor_name, '-->', _inspect_tensor(cache[cache_idx, 0])]) + return logging_ops.print_v2(*stats, summarize=-1, + output_stream=output_stream) + + def _inspect_history_cache(self, cache, replica_id, step_num, + tensor_trace_order): + """Generates a conditional print operation to log differences in tensor values. + + Args: + cache: Tensor storing the trace results for the step. + replica_id: Tensor storing the replica id of the running core. + step_num: Step number. + tensor_trace_order: TensorTraceOrder object holding tensorname to id map. + + Returns: + The Op to flush the cache to file. + """ + # Check if there are graph operations being profiled. + if not tensor_trace_order.traced_tensors: + logging.warn('TT history mode has no tensors in the cache to check.') + return control_flow_ops.no_op + + stats = ['\n\n', 'core:', replica_id, ',', 'step:', step_num] + diffs = [] + for tensor_name, cache_idx in sorted( + tensor_trace_order.tensorname_to_cache_idx.items(), + key=lambda item: item[1]): + + tensor_to_write = cache[cache_idx, 0] + snapshot_variable = self._create_or_get_tensor_history_values_cache( + tensor_to_write.name, tensor_to_write.op.graph, + tensor_to_write.shape.as_list(), tensor_to_write.dtype) + + with ops.control_dependencies([snapshot_variable]): + old_value = state_ops.assign_add(snapshot_variable, 0.0) + + with ops.control_dependencies([old_value]): + new_value = math_ops.cast(tensor_to_write, dtypes.float32) + delta = math_ops.abs(math_ops.subtract(old_value, new_value)) + updated = state_ops.assign(snapshot_variable, new_value) + diffs.append(delta) + with ops.control_dependencies([updated]): + new_value_from_var = state_ops.assign_add(snapshot_variable, 0.0) + + stats.extend([ + '\n', 'core:', replica_id, ',', 'step:', step_num, ',', + tensor_name, '-->', old_value, new_value_from_var, delta]) + + diff_stack = array_ops_stack.stack(diffs) + step_max = math_ops.reduce_max(diff_stack) + + return cond.cond( + math_ops.greater(step_max, tensor_tracer_flags.DELTA_THRESHOLD.value), + lambda: logging_ops.print_v2(*stats, summarize=-1), + lambda: control_flow_ops.no_op()) # pylint: disable=unnecessary-lambda + + def _get_outfile_suffix(self): + if remote_utils.is_remote_path(self._parameters.trace_dir): + return remote_utils.get_appendable_file_encoding() + else: + return '' + + def _generate_flush_cache_op(self, num_replicas, on_tpu, + tensor_trace_order, graph): + """Generates an Op that will flush the cache to file. + + Args: + num_replicas: total number of replicas. + on_tpu: if the graph is executed on TPU. + tensor_trace_order: TensorTraceOrder object holding tensorname to id map. + graph: TensorFlow graph. + + Returns: + The Op to flush the cache to file. + """ + + def _flush_fun(cache, replica_id, step_num): + """Flushes the cache to a file corresponding to replica_id.""" + + def _f(file_index): + """Generates a func that flushes the cache to a file.""" + def _print_cache(): + """Flushes the cache to a file.""" + replica_str = ('%d' % file_index) + if self._parameters.trace_dir: + output_path = (os.path.join(self._parameters.trace_dir, + _COMPACT_TRACE_FILE_PREFIX) + + replica_str + self._get_outfile_suffix()) + output_stream = _OUTPUT_STREAM_ESCAPE + output_path + else: + output_stream = sys.stderr + + new_step_line = _REPLICA_ID_TAG + replica_str + print_ops = [] + if self._parameters.inspect_trace: + if self._num_signature_dimensions() > 1: + raise ValueError('Inspecting multi signatures are not supported.') + if self._parameters.trace_mode in ( + tensor_tracer_flags.TRACE_MODE_HISTORY): + print_ops.append( + self._inspect_history_cache( + cache=cache, + replica_id=replica_id, + step_num=step_num, + tensor_trace_order=tensor_trace_order)) + else: + print_ops.append( + self._inspect_summary_cache( + cache=cache, + replica_id=replica_id, + step_num=step_num, + output_stream=output_stream, + tensor_trace_order=tensor_trace_order)) + else: + for i in range(self._num_signature_dimensions()): + print_ops.append(logging_ops.print_v2( + new_step_line, '\n', + cache[:, i], '\n', + summarize=-1, + output_stream=output_stream)) + with ops.control_dependencies(print_ops): + return constant_op.constant(0).op + return _print_cache + + def _eq(file_index): + return math_ops.equal(replica_id, file_index) + + flush_op_cases = {} + flush_op_cases[_eq(0)] = _f(0) + for i in range(1, num_replicas): + if on_tpu and not self._parameters.collect_summary_per_core: + # If this is the case, the cache is already merged for all cores. + # Only first core flushes the cache. + flush_op_cases[_eq(i)] = control_flow_ops.no_op + else: + flush_op_cases[_eq(i)] = _f(i) + # Each replica needs to determine where to write their output. + # To do this, we check if replica_id is 0, then 1, ..., and then + # num_replicas - 1 statically; and return the corresponding static file + # name. We cannot simply set the file name in python, as replica_id is + # only known during tf runtime, and we cannot create dynamic filenames. + return control_flow_case.case(flush_op_cases, exclusive=True) + + cache = self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG, graph) + if self._use_temp_cache(): + cache_val = cache + else: + cache_val = cache.value() + + if on_tpu: + # If we do not need to collect traces for all cores, merge and aggregate + # per core trace. + if not self._parameters.collect_summary_per_core: + cache_val = self.merge_caches_on_tpu(cache_val) + cache_val = self.aggregate_global_cache(cache_val)[0] + + flush_op = tpu_replication.outside_compilation( + _flush_fun, cache_val, self._replica_id, + array_ops.identity(training_util.get_or_create_global_step())) + else: + global_step = training_util.get_or_create_global_step() + flush_op = _flush_fun(cache_val, self._replica_id, global_step) + + if self._use_temp_cache(): + with ops.control_dependencies([flush_op]): + return constant_op.constant(0).op + else: + # Re-initialize the local cache variable. + with ops.control_dependencies([flush_op]): + reset_value = constant_op.constant(_COMPACT_TRACE_ENTRY_INIT_VALUE, + dtype=cache.dtype, + shape=cache.shape) + assign_op = state_ops.assign(cache, reset_value).op + with ops.control_dependencies([assign_op]): + return constant_op.constant(0).op + + def _flush_tensor_values_cache(self, tensor_fetches, op_fetches, on_tpu, + tensor_trace_order, graph): + """Flushes the intermediate tensor values in the graph to the cache. + + Args: + tensor_fetches: list of tensor results returned by the model_fn. + op_fetches: list of ops that are returned by the model_fn, e.g., train_op. + on_tpu: if the graph is executed on TPU. + tensor_trace_order: TensorTraceOrder object holding tensorname to id map. + graph: TensorFlow graph. + + Returns: + An identical copy of tensor_fetches. + """ + # Add a dependency to op and tensor fetches to make sure that all tracing + # ops are executed before flushing trace results. + if not tensor_trace_order.traced_tensors: + logging.warn('No tensor values being traced. No flush cache op added.') + return tensor_fetches + with ops.control_dependencies(op_fetches + + [tensor.op for tensor in tensor_fetches]): + flush_cache_op = self._generate_flush_cache_op( + self._tt_config.num_replicas, on_tpu, tensor_trace_order, graph) + return control_flow_ops.tuple(tensor_fetches, + control_inputs=[flush_cache_op]) + + def _process_tensor_fetches(self, tensor_fetches): + """Check that tensor_fetches is not empty and have valid tensors.""" + # If none or empty list. + if tensor_fetches is None: + raise RuntimeError('tensor_fetches provided to tensor_tracer cannot be ' + 'None.') + if not isinstance(tensor_fetches, (list, tuple)): + tensor_fetches = [tensor_fetches] + elif not tensor_fetches: + raise RuntimeError('tensor_fetches provided to tensor_tracer cannot be ' + 'empty list.') + fetches = [] + for fetch in tensor_fetches: + if isinstance(fetch, tensor_lib.Tensor): + fetches.append(fetch) + else: + raise RuntimeError('Given tensor_fetch:%s is not a tensor.' % fetch) + return fetches + + def _process_op_fetches(self, op_fetches): + """Check that op_fetches have valid ops.""" + if op_fetches is None: + return [] + + if not isinstance(op_fetches, (list, tuple)): + op_fetches = [op_fetches] + + fetches = [] + for fetch in op_fetches: + if isinstance(fetch, ops.Operation): + fetches.append(fetch) + elif isinstance(fetch, tensor_lib.Tensor): + fetches.append(fetch.op) + else: + logging.warning('Ignoring the given op_fetch:%s, which is not an op.' % + fetch) + return fetches + + def _convert_fetches_to_input_format(self, input_fetches, current_fetches): + """Changes current_fetches' format, so that it matches input_fetches.""" + if isinstance(input_fetches, tensor_lib.Tensor): + if len(current_fetches) != 1: + raise RuntimeError('Tensor tracer input/output fetches do not match.') + return current_fetches[0] + else: + if len(current_fetches) != len(current_fetches): + raise RuntimeError('Tensor tracer input/output fetches do not match.') + elif isinstance(input_fetches, tuple): + return tuple(current_fetches) + else: + return current_fetches + + def _get_op_control_flow_context(self, op): + """Returns the control flow of the given op. + + Args: + op: tf.Operation for which the control flow context is requested. + Returns: + op_control_flow_context: which the is control flow context of the given + op. If the operation type is LoopExit, returns the outer control flow + context. + """ + # pylint: disable=protected-access + op_control_flow_context = op._control_flow_context + # pylint: enable=protected-access + if control_flow_util.IsLoopExit(op): + op_control_flow_context = op_control_flow_context.outer_context + return op_control_flow_context + + def merge_caches_on_tpu(self, local_tpu_cache_tensor): + """Merges the given caches on tpu. + + Args: + local_tpu_cache_tensor: A local tensor that needs to be merged + by concanting data from other tpu cores. + Returns: + A merged tf.Tensor. + """ + x = array_ops.broadcast_to( + local_tpu_cache_tensor, + shape=[self._tt_config.num_replicas] + + local_tpu_cache_tensor.shape.as_list()) + + if tensor_tracer_flags.TT_SINGLE_CORE_SUMMARIES.value: + return x + + return tpu_ops.all_to_all( + x, concat_dimension=0, split_dimension=0, + split_count=self._tt_config.num_replicas, + group_assignment=[list(range(self._tt_config.num_replicas))]) + + def aggregate_global_cache(self, global_tt_summary_cache): + """Merges the given caches on tpu. + + Args: + global_tt_summary_cache: The global tensor tracer summary cache tensor + with shape (num_cores, num_traced_tensors, num_traced_signatures). First + dimension corresponds to core_id, where global_tpu_cache_tensor[i] + correspond to the local cache from core-i. + Returns: + An aggregated tf.Tensor. + Raises: + RuntimeError: if there is no aggregate function defined for a signature. + """ + + # Merge only statistics tensor, if it is any other tensor we simply, + # concatenate them. + agg_fn_map = self._parameters.get_signature_to_agg_fn_map() + signature_idx_map = self._signature_types() + aggregation_result = [] + for signature, idx in sorted(signature_idx_map.items(), + key=operator.itemgetter(1)): + if signature not in agg_fn_map: + raise RuntimeError('No aggregation function is defined for ' + 'signature %s.' % signature) + # The dimensions of the statistics tensor is + # num_cores x num_traced_tensors x num_signatures + # value[:,:,idx] will return the portion of the tensor related + # to signature. + signature_tensor = global_tt_summary_cache[:, :, idx] + # Merge it along the first (core) axis. + agg_fn = agg_fn_map[signature] + agg_tensor = agg_fn(signature_tensor, axis=0) + aggregation_result.append(agg_tensor) + # Merge results corresponding to different signatures + + merged_signatures = array_ops_stack.stack(aggregation_result) + # merged_signatures has dimensions + # num_signatures x num_traced_tensors, transpose it so that it + # will match with the original structure + # num_traced_tensors x num_signatures. + transposed_signatures = array_ops.transpose(merged_signatures) + # Expand 1 more dimension so that it will match with the expected + # structure num_cores x num_traced_tensors x num_signatures. + return array_ops.expand_dims(transposed_signatures, axis=0) + + def _prepare_host_call_fn(self, processed_t_fetches, + op_fetches, graph, graph_summary_tag): + """Creates a host call function that will write the cache as tb summary. + + Args: + processed_t_fetches: List of tensor provided to session.run. + op_fetches: List of operations provided to session.run. + graph: TensorFlow graph. + graph_summary_tag: the summary_tag name for the given graph. + Raises: + ValueError if trace_dir is not set. + """ + if self._parameters.trace_dir is None: + raise ValueError('Provide a trace_dir for tensor tracer in summary mode. ' + '--trace_dir=/model/dir') + + def _write_cache(step, event_file_suffix=None, **kwargs): + """Writes the given caches as tensor summary. + + Args: + step: Step tensor with dimension [num_cores]. + event_file_suffix: Event filename suffix tensor. + **kwargs: The dictionary of tensors that needs to be written as + summaries. Key and value pairs within kwargs correspond to the tag + name, and tensor content that will be written using summary.write. + The trace_modes that use this function are: + - summary: In summary mode, kwargs includes a single (tag, content) + pair which are, _TT_SUMMARY_TAG and a tf.float32 signature_cache + variable. The dimension of the signature_cache is: + num_cores x num_traced_tensors x num_signatures. + - full_tensor_summary: kwargs will include all traced tensors. Tag + and content correspond to the name of the tensor, and its actual + content. + Returns: + A tf.Operation that needs to be executed for the host call dependencies. + """ + file_suffix = _TT_EVENT_FILE_SUFFIX + if event_file_suffix is not None: + file_suffix = string_ops.string_join([file_suffix, event_file_suffix], + separator='.') + # TODO(deveci): Parametrize max_queue, so that flushing op can be called + # less frequently. + # Setting max_queue to 100 appears to be safe even when the number of + # iterations are much lower, as the destructor of the writer flushes it. + summary_write_ops = [] + summary_writer = summary.create_file_writer_v2( + self._parameters.trace_dir, + filename_suffix=file_suffix, + max_queue=_TT_SUMMARY_MAX_QUEUE) + graph.add_to_collection( + TENSOR_TRACER_SUMMARY_COLLECTION, summary_writer) + + step_value = step[0] + dt = step_value.dtype + + # The step parameter to a summary write call must be 64-bit. + if dt.__ne__(dtypes.int64) and dt.__ne__( + dtypes.uint64) and dt.__ne__(dtypes.float64): + step_value = math_ops.cast(step_value, dtypes.int64) + + with summary_writer.as_default(): + summary_metadata = summary_pb2.SummaryMetadata( + plugin_data=summary_pb2.SummaryMetadata.PluginData( + plugin_name=_TT_TENSORBOARD_PLUGIN_NAME)) + for key, value in kwargs.items(): + # Check whether we need to compute aggregated statistics that merge + # all cores statistics. + if not self._parameters.collect_summary_per_core: + # Merge only statistics tensor, if it is any other tensor we simply, + # concatenate them. + # Also, if there is only a single core (first dim. is 0), then skip + # aggregation. + if key == _TT_SUMMARY_TAG and value.shape.as_list()[0] != 1: + value = self.aggregate_global_cache(value) + with ops.control_dependencies([summary_writer.init()]): + summary_write_ops.append(summary.write( + _TT_SUMMARY_TAG + '/' + key + '.' + graph_summary_tag, + value, metadata=summary_metadata, + step=step_value)) + return control_flow_ops.group(summary_write_ops) + + global_step = training_util.get_or_create_global_step() + step = array_ops.reshape(global_step, [1]) + self._host_call_fn = {} + + host_call_deps = op_fetches + [tensor.op for tensor in processed_t_fetches] + + caches_to_write = {} + with ops.control_dependencies(host_call_deps): + all_caches = self._cache_variable_for_graph(graph) + for cache_name, cache_variable in all_caches.items(): + # Increase the cache rank by 1, so that when host call concatenates + # tensors from different replicas, we can identify them with [core_id]. + new_cache_shape = [1] + new_cache_shape.extend(cache_variable.shape.as_list()) + cache = array_ops.reshape(cache_variable, new_cache_shape) + caches_to_write[cache_name] = cache + # Add step to parameter dictionary. + caches_to_write['step'] = step + # Other options without adding step to parameter dictionary are + # * host_call_fn = (_write_cache(step, caches_to_write)) : fails as it + # considers caches_to_write as a single parameter, rather than a keyword + # parameters. + # * host_call_fn = (_write_cache(step, **caches_to_write)) : fails with + # a syntax error. + self._host_call_fn[_TT_HOSTCALL_KEY] = (_write_cache, caches_to_write) + + def host_call_deps_and_fn(self): + return self._host_call_fn + + def get_traced_op_names(self): + """Returns the set of traced op names.""" + return self._traced_op_names + + def _trace_execution(self, graph, + tensor_fetches, + op_fetches=None, + on_tpu=True): + """Commong tracing function for both CPU and TPUs. + + The caller function should set device_type, num_replicas, + num_replicas_per_host, num_hosts and replica_id before calling + _trace_execution. + + + Args: + graph: the graph of Ops executed on the TPU. + tensor_fetches: a (list,tuple,or a single object) of tensor fetches + returned by model_fn given to session.run. Function must be provided + with as least one tensor to fetch. + op_fetches: A list of op fetches returned by model_fn given to + session.run. op_fetches and tensor_fetches are used to determine the + nodes that will be executed. Can be None. + on_tpu: True if executing on TPU. + + Returns: + tensor_fetches: an exact copy of tensor_fetches that has additional + dependencies. + Raises: + RuntimeError: If tensor_fetches is None or empty. + """ + def _cast_unsupported_dtypes(tensor): + """Casts tensor to a supported type.""" + + if tensor.dtype.__eq__(dtypes.int64): + # outside-compilation doesn't support int64 input yet. + return math_ops.cast(tensor, dtypes.int32) + if tensor.dtype.__eq__(dtypes.bfloat16) or tensor.dtype.__eq__( + dtypes.float16): + # Since host can't handle bf16, convert tensor to f32. + return math_ops.cast(tensor, dtypes.float32) + return tensor + + trace_mode = self._parameters.trace_mode + device_type = self._tt_config.device_type + # pylint: disable=protected-access + self._outmost_context = graph._get_control_flow_context() + # pylint: enable=protected-access + + analytics.track_usage('tensor_tracer', [trace_mode, device_type]) + TensorTracer.check_device_type(device_type) + TensorTracer.check_trace_mode(device_type, trace_mode) + # Check in_tensor_fetches, and op_fetches and convert them to lists. + processed_t_fetches = self._process_tensor_fetches(tensor_fetches) + op_fetches = self._process_op_fetches(op_fetches) + all_fetches = op_fetches + [tensor.op for tensor in processed_t_fetches] + + # Filter out the operations that won't be executed. + # if fetches=None, then ops_in_exec_path = set(operations) + exec_op_set = self._filter_execution_path_operations(graph.get_operations(), + all_fetches) + graph_summary_tag = _graph_summary_tag(graph) + + # Write report file, and determine the traced tensors. + tensor_trace_order = self._determine_trace_and_create_report( + graph, exec_op_set, graph_summary_tag) + + tensor_fetch_set = set(processed_t_fetches) + tracing_ops = [] + + sorted_exec_op_list = list(exec_op_set) + sorted_exec_op_list.sort(key=lambda op: op.name) + # Trace ops only if they are in the execution path. + for op in sorted_exec_op_list: + for i in range(len(op.outputs)): + out_tensor = op.outputs[i] + tensor_name = out_tensor.name + if tensor_name not in tensor_trace_order.tensorname_to_cache_idx: + continue + self._traced_op_names.add(op.name) + # Create the list of consumers before calling _preprocess_traced_tensor. + # Otherwise, adding control input below, will introduce a cycle in the + # graph. + consumers = out_tensor.consumers() + # Not all consumers may be in the exec path. Filter out the consumers + # to keep the graph simpler. + consumers = [cop for cop in consumers if cop in exec_op_set] + + # If there is no consumer of the tensor, there is no need to trace it; + # unless the tensor itself is one of the fetches. + is_a_fetched_tensor = out_tensor in tensor_fetch_set + if (not consumers) and (not is_a_fetched_tensor): + continue + + op_control_flow_context = self._get_op_control_flow_context(op) + if op_control_flow_context: + # pylint: disable=protected-access + graph._set_control_flow_context(op_control_flow_context) + # pylint: enable=protected-access + + processed_tensors = self._preprocess_traced_tensor(out_tensor) + + if on_tpu: + for signature in processed_tensors.keys(): + processed_tensors[signature] = _cast_unsupported_dtypes( + processed_tensors[signature]) + + if self._use_tensor_values_cache(): + # Use a small cache (either temp cache or tf local variable) to store + # the characteristics of the tensor. + if self._use_temp_cache(): + cache_idx = tensor_trace_order.tensorname_to_cache_idx[tensor_name] + self._save_tensor_value_to_tmp_cache(cache_idx, + processed_tensors, + graph) + trace_op = None + else: + cache_idx = tensor_trace_order.tensorname_to_cache_idx[tensor_name] + trace_op = self._save_tensor_value_to_cache_op(cache_idx, + processed_tensors, + graph) + elif self._use_tensor_buffer(): + if len(processed_tensors) != 1: + raise RuntimeError('Multiple stats are only allowed in compact ' + 'mode.') + processed_out_tensor = list(processed_tensors.values())[0] + # Store the whole tensor in a buffer. + trace_op = self._snapshot_tensor(processed_out_tensor) + else: + + def tpu_wrap_trace_fn(tensor, out_tensor_name): + """Wraps the trace_fn with outside compilation if on TPUs.""" + tensor_trace_fn = self._make_tensor_trace_fun(out_tensor_name, + tensor_trace_order) + if on_tpu: + return tpu_replication.outside_compilation( + tensor_trace_fn, tensor) + else: + return tensor_trace_fn(tensor) + + if len(processed_tensors) != 1: + raise RuntimeError('Multiple stats are only allowed in compact ' + 'mode.') + # Collecting multiple statistics are only supported in the summary + # mode that uses compact format(self._use_tensor_values_cache = true). + # Non-compact mode currently allows single stat per tensor. + processed_out_tensor = next(iter(processed_tensors.values())) + trace_op = tpu_wrap_trace_fn(processed_out_tensor, tensor_name) + + if op_control_flow_context: + # pylint: disable=protected-access + graph._set_control_flow_context(self._outmost_context) + # pylint: enable=protected-access + if trace_op: + if is_a_fetched_tensor: + tracing_ops.append(trace_op) + continue + # Add it to all consumers, as some consumers may not be executed if + # they are in a control flow. + for consumer_op in consumers: + # pylint: disable=protected-access + consumer_op._add_control_input(trace_op) + # pylint: enable=protected-access + + # pylint: disable=protected-access + graph._set_control_flow_context(self._outmost_context) + # pylint: enable=protected-access + if tracing_ops: + # If we are tracing a fetched tensor, their dependency is stored in + # tracing_ops. + processed_t_fetches = control_flow_ops.tuple(processed_t_fetches, + control_inputs=tracing_ops) + if self._use_tensor_values_cache() or self._use_tensor_buffer(): + if self._use_temp_cache(): + # Create the temporary tf cache variable by concantanating all + # statistics. + graph_cache_var = self._cache_variable_for_graph(graph) + if graph not in self._temp_cache_var: + raise RuntimeError('graph is not in self._temp_cache_var') + graph_cache_var[_TT_SUMMARY_TAG] = array_ops_stack.stack( + self._temp_cache_var[graph], axis=0, name='stack_all_op_signatures') + if self._create_host_call(): + self._prepare_host_call_fn(processed_t_fetches, op_fetches, graph, + graph_summary_tag) + if not on_tpu: + write_cache, caches_to_write = self._host_call_fn[_TT_HOSTCALL_KEY] + cache_write_op = write_cache(**caches_to_write) + processed_t_fetches = control_flow_ops.tuple( + processed_t_fetches, control_inputs=[cache_write_op]) + del self._host_call_fn[_TT_HOSTCALL_KEY] + elif self._parameters.flush_summaries_with_outside_compile: + write_cache, caches_to_write = self._host_call_fn[_TT_HOSTCALL_KEY] + if (_TT_SUMMARY_TAG in caches_to_write and 'step' in caches_to_write): + step = caches_to_write['step'] + tensor_tracer_summary = caches_to_write[_TT_SUMMARY_TAG] + tt_core_summary = self.merge_caches_on_tpu(tensor_tracer_summary[0]) + if not self._parameters.collect_summary_per_core: + tt_core_summary = self.aggregate_global_cache(tt_core_summary) + + def write_if_core_0(step, replica_id, tt_summary): + + return cond.cond( + math_ops.equal(replica_id, 0), + lambda: write_cache(step=step, event_file_suffix=None, # pylint: disable=g-long-lambda + tensor_tracer_summary=tt_summary), + control_flow_ops.no_op) + + write_op = tpu_replication.outside_compilation( + write_if_core_0, + step=step, + replica_id=self._replica_id, + tt_summary=tt_core_summary) + processed_t_fetches = control_flow_ops.tuple( + processed_t_fetches, control_inputs=[write_op]) + del self._host_call_fn[_TT_HOSTCALL_KEY] + else: + raise ValueError('Outside compiled flush in only supported for ' + 'summary mode') + else: + processed_t_fetches = self._flush_tensor_values_cache( + processed_t_fetches, op_fetches, on_tpu=on_tpu, + tensor_trace_order=tensor_trace_order, + graph=graph) + + # processed_t_fetches is a list at this point. Convert it to the same + # format as given in tensor_fetches. + return self._convert_fetches_to_input_format(tensor_fetches, + processed_t_fetches) + + def trace_tpu(self, graph, + tensor_fetches, + op_fetches=None, + num_replicas=None, + num_replicas_per_host=None, + num_hosts=None): + """Traces the tensors generated by TPU Ops in a TF graph. + + Args: + graph: the graph of Ops executed on the TPU. + tensor_fetches: a (list,tuple,or a single object) of tensor fetches + returned by model_fn given to session.run. Function must be provided + with as least one tensor to fetch. + op_fetches: A list of op fetches returned by model_fn given to + session.run. op_fetches and tensor_fetches are used to determine the + nodes that will be executed. Can be None. + num_replicas: number of replicas used on the TPU. + num_replicas_per_host: number of replicas per TPU host. + num_hosts: total number of TPU hosts. + + Returns: + tensor_fetches: an exact copy of tensor_fetches that has additional + dependencies. + """ + if isinstance(graph, func_graph.FuncGraph) or isinstance( + graph, function._FuncGraph): # pylint: disable=protected-access + logging.warning('Tensor Tracer is not supported for tracing FuncGraphs. ' + 'Ignoring tracing.') + return tensor_fetches + + if graph in TensorTracer._traced_graphs: + logging.warning('Graph is already rewritten with tensor tracer, ignoring ' + 'multiple calls.') + return tensor_fetches + else: + TensorTracer._traced_graphs.add(graph) + # Reset the parameters in case parameters are changed. + self._parameters = tensor_tracer_flags.TTParameters() + self._tt_config.device_type = _DEVICE_TYPE_TPU + self._tt_config.num_replicas = num_replicas + self._tt_config.num_replicas_per_host = num_replicas_per_host + self._tt_config.num_hosts = num_hosts + if self._tt_config.num_replicas is not None: + if self._tt_config.num_replicas_per_host is None: + self._tt_config.num_replicas_per_host = 8 + if self._tt_config.num_hosts is None: + self._tt_config.num_hosts = ( + num_replicas // self._tt_config.num_replicas_per_host + + (num_replicas % self._tt_config.num_replicas_per_host > 0)) + + if self._parameters.graph_dump_path: + graph_io.write_graph(graph, self._parameters.graph_dump_path, + 'graph_before_tt.pbtxt') + with graph.as_default(): + self._add_replica_id_to_graph() + tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches, + on_tpu=True) + if self._parameters.graph_dump_path: + graph_io.write_graph(graph, self._parameters.graph_dump_path, + 'graph_after_tt.pbtxt') + return tensor_fetches + + def trace_cpu(self, graph, tensor_fetches, op_fetches=None): + """Traces the tensors generated by CPU Ops in a TF graph. + + Args: + graph: the graph of Ops executed on the CPU. + tensor_fetches: a (list,tuple,or a single object) of tensor fetches + returned by model_fn given to session.run. Function must be provided + with as least one tensor to fetch. + op_fetches: A list of op fetches returned by model_fn given to + session.run. op_fetches and tensor_fetches are used to determine the + nodes that will be executed. Can be None. + + Returns: + tensor_fetches: an exact copy of tensor_fetches that has additional + dependencies. + """ + if isinstance(graph, func_graph.FuncGraph) or isinstance( + graph, function._FuncGraph): # pylint: disable=protected-access + logging.warning('Tensor Tracer is not supported for tracing FuncGraphs. ' + 'Ignoring tracing.') + return tensor_fetches + + if graph in TensorTracer._traced_graphs: + logging.warning('Graph is already rewritten with tensor tracer, ignoring ' + 'multiple calls.') + return tensor_fetches + else: + TensorTracer._traced_graphs.add(graph) + # Reset the parameters in case parameters are changed. + self._parameters = tensor_tracer_flags.TTParameters() + + self._tt_config.device_type = _DEVICE_TYPE_CPU + self._tt_config.num_replicas = 1 + self._tt_config.num_replicas_per_host = 1 + self._tt_config.num_hosts = 1 + self._replica_id = 0 + if self._parameters.graph_dump_path: + graph_io.write_graph(graph, self._parameters.graph_dump_path, + 'graph_before_tt.pbtxt') + with graph.as_default(): + tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches, + on_tpu=False) + if self._parameters.graph_dump_path: + graph_io.write_graph(graph, self._parameters.graph_dump_path, + 'graph_after_tt.pbtxt') + return tensor_fetches diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_flags.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_flags.py new file mode 100644 index 0000000000000000000000000000000000000000..e9617ce4178774278d6a48d0cd5a8946bfc6ab4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_flags.py @@ -0,0 +1,504 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== +"""Utilities to handle tensor tracer parameters.""" + + +import os +import os.path +import re +from absl import flags +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging + +TRACE_MODE_PART_TENSOR = 'part-tensor' +TRACE_MODE_FULL_TENSOR = 'full-tensor' +TRACE_MODE_FULL_TENSOR_SUMMARY = 'full_tensor_summary' + +TRACE_MODE_NAN_INF = 'nan-inf' +TRACE_MODE_NORM = 'norm' +TRACE_MODE_MAX_ABS = 'max-abs' +TRACE_MODE_SUMMARY = 'summary' +TRACE_MODE_HISTORY = 'history' +# summary mode to collects a finite set of signatures for each traced tensor, +# (such as norm, max, min, mean) and dumps it using tb summaries. + +# Full tensor mode dumps the whole tensor values for the traced tensors without +# any processing on them; using tb summaries. + +_SUBMODE_BRIEF = 'brief' +_SUBMODE_DETAILED = 'detailed' + +_FLAG_SINGLE_QUOTE_PAT = re.compile(r"\s*--([^=]+)='([^']*)'") +_FLAG_DOUBLE_QUOTE_PAT = re.compile(r'\s*--([^=]+)="([^"]*)"') +_FLAG_NO_QUOTE_PAT = re.compile(r'\s*--([^=]+)=(\S*)') +_FLAG_NO_EQUAL_PAT = re.compile(r'\s*--([^=]+)\s*') + +FLAGS_ENV_VAR = 'TENSOR_TRACER_FLAGS' +FLAG_NAME_ENABLE = 'enable' +FLAG_NAME_TRACE_MODE = 'trace_mode' +FLAG_NAME_TRACE_SCALAR_OPS = 'trace_scalar' +FLAG_NAME_SUBMODE = 'submode' +FLAG_NAME_EXCLUDED_OPNAMES = 'excluded_opnames' +FLAG_NAME_EXCLUDED_OPTYPES = 'excluded_optypes' +FLAG_NAME_INCLUDED_OPNAMES = 'included_opnames' +FLAG_NAME_INCLUDED_OPTYPES = 'included_optypes' +FLAG_NAME_TRACE_LEVEL = 'trace_level' +FLAG_NAME_TRACE_DIR = 'trace_dir' +FLAG_NAME_REPORT_FILE = 'report_file' +FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR = 'use_test_undeclared_outputs_dir' +FLAG_NAME_OP_RANGE = 'op_range' +# Folder to dump the pre (before tensor tracer updates) and post graphs (after +# tensor tracer updates). +FLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS = 'dump_graphs' +FLAG_NAME_SUMMARY_SIGNATURES = 'signatures' +FLAG_NAME_SUMMARY_PER_CORE = 'collect_summary_per_core' +FLAG_NAME_TEMP_CACHE_VAR = 'use_temp_cache' +FLAG_NAME_INSPECT_TRACE = 'inspect_trace' +FLAG_NAME_FINGERPRINT_DIR = 'use_fingerprint_subdirectory' +FLAG_FLUSH_SUMMARY = 'flush_summaries' + + +VALID_FLAG_NAMES = [ + FLAG_NAME_ENABLE, FLAG_NAME_TRACE_MODE, + FLAG_NAME_TRACE_SCALAR_OPS, + FLAG_NAME_SUBMODE, FLAG_NAME_EXCLUDED_OPNAMES, + FLAG_NAME_EXCLUDED_OPTYPES, FLAG_NAME_INCLUDED_OPNAMES, + FLAG_NAME_INCLUDED_OPTYPES, FLAG_NAME_TRACE_DIR, + FLAG_NAME_REPORT_FILE, + FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR, + FLAG_NAME_OP_RANGE, + FLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS, FLAG_NAME_TRACE_LEVEL, + FLAG_NAME_SUMMARY_SIGNATURES, FLAG_NAME_SUMMARY_PER_CORE, + FLAG_NAME_TEMP_CACHE_VAR, FLAG_NAME_FINGERPRINT_DIR, + FLAG_NAME_INSPECT_TRACE, FLAG_FLUSH_SUMMARY, +] + +_OP_RANGE_PAT = re.compile(r'(\d+):(\d+)') +_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR = 'TEST_UNDECLARED_OUTPUTS_DIR' + +_TT_DEFAULT_TRACE_LEVEL = 3 +_TT_PREFIX = 'tensor_tracer' + +_TT_NORM = 'norm' +_TT_MAX = 'max' +_TT_MAX_ABS = 'max-abs' +_TT_MIN = 'min' +_TT_SPARSITY = 'sparsity' +_TT_MEAN = 'mean' +_TT_VAR = 'var' +_TT_SIZE = 'size' + +TT_SUMMARY_NORM = '%s_%s' % (_TT_PREFIX, _TT_NORM) +TT_SUMMARY_MAX = '%s_%s' % (_TT_PREFIX, _TT_MAX) +TT_SUMMARY_MAX_ABS = '%s_%s' % (_TT_PREFIX, _TT_MAX_ABS) +TT_SUMMARY_MIN = '%s_%s' % (_TT_PREFIX, _TT_MIN) +TT_SUMMARY_SPARSITY = '%s_%s' % (_TT_PREFIX, _TT_SPARSITY) +TT_SUMMARY_MEAN = '%s_%s' % (_TT_PREFIX, _TT_MEAN) +TT_SUMMARY_VAR = '%s_%s' % (_TT_PREFIX, _TT_VAR) +TT_SUMMARY_SIZE = '%s_%s' % (_TT_PREFIX, _TT_SIZE) + +TT_SUMMARY_SIGNATURES = (TT_SUMMARY_NORM, TT_SUMMARY_MAX, TT_SUMMARY_MIN, + TT_SUMMARY_SPARSITY, TT_SUMMARY_MEAN, TT_SUMMARY_VAR, + TT_SUMMARY_SIZE, TT_SUMMARY_MAX_ABS) + +FLAGS = flags.FLAGS + +DELTA_THRESHOLD = flags.DEFINE_float( + 'delta_threshold', + default=0.5, + help=('Log if history based diff crosses this threshold.')) +TT_CHECK_FILTER = flags.DEFINE_bool( + 'tt_check_filter', + default=False, + help='Terminate early to check op name filtering.') +TT_SINGLE_CORE_SUMMARIES = flags.DEFINE_bool( + 'tt_single_core_summaries', + default=False, + help='Report single core metric and avoid aggregation.') + + +class TTParameters(object): + """A class that handles the parameters of Tensor Tracer.""" + + def __init__(self, env=None): + if env: + self._env = env + else: + self._env = os.environ + self._validate_flag_names() + self.trace_mode = self._get_trace_mode() + self.submode = self._get_submode() + self.trace_dir = self._get_trace_dir() + self.report_file_path = self._get_report_filepath() + self.op_range = self._get_op_range() + self.excluded_opname_re_list = self._flag_value_to_re_list( + FLAG_NAME_EXCLUDED_OPNAMES) + self.excluded_optype_re_list = self._flag_value_to_re_list( + FLAG_NAME_EXCLUDED_OPTYPES) + + self.included_opname_re_list = self._flag_value_to_re_list( + FLAG_NAME_INCLUDED_OPNAMES) + self.included_optype_re_list = self._flag_value_to_re_list( + FLAG_NAME_INCLUDED_OPTYPES) + + self.trace_scalar_ops = self.is_flag_on(FLAG_NAME_TRACE_SCALAR_OPS) + self.use_compact_trace = self.trace_mode in (TRACE_MODE_NAN_INF, + TRACE_MODE_NORM, + TRACE_MODE_HISTORY, + TRACE_MODE_MAX_ABS, + TRACE_MODE_SUMMARY) + self.use_temp_cache_var = self.is_flag_on(FLAG_NAME_TEMP_CACHE_VAR) + self.inspect_trace = self.is_flag_on(FLAG_NAME_INSPECT_TRACE) + self.use_fingerprint_subdir = self.is_flag_on(FLAG_NAME_FINGERPRINT_DIR) + + _, self.graph_dump_path = self.get_flag_value( + FLAG_NAME_DUMP_BEFORE_AFTER_GRAPHS) + self.trace_level = self._get_flag_int_value(FLAG_NAME_TRACE_LEVEL, + _TT_DEFAULT_TRACE_LEVEL) + self.summary_signatures = self._get_summary_signatures() + self.collect_summary_per_core = self.is_flag_on(FLAG_NAME_SUMMARY_PER_CORE) + # TODO(b/199284834): Will be resolved with referenced bug. + if self.collect_summary_per_core: + logging.warning('Aggregate signatures are approximate for mean, variance' + ' and sparsity.') + self.flush_summaries_with_outside_compile = self.is_flag_on( + FLAG_FLUSH_SUMMARY) + # Do not produce errors or warnings if Tensor Tracer is not enabled. + if self.is_enabled(): + self._check_flag_errors() + + def _check_flag_errors(self): + if self.trace_mode in (TRACE_MODE_SUMMARY, TRACE_MODE_FULL_TENSOR_SUMMARY): + if not self.trace_dir: + raise ValueError('trace_dir must be explicitly provided in ' + 'TENSOR_TRACER_FLAGS when summary mode is used.') + + def _get_report_filepath(self): + """Sets the path of the output report file.""" + + found, report_file_path = self.get_flag_value(FLAG_NAME_REPORT_FILE) + if found and report_file_path and self.use_test_undeclared_outputs_dir(): + if os.path.isabs(report_file_path): + raise ValueError('If use_test_undeclared_outputs_dir is set,' + 'report_file_path cannot be an absolute path (%s)' + %report_file_path) + outputs_dir = self._env.get(_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR) + report_file_path = os.path.join(outputs_dir, report_file_path) + return report_file_path + + def _get_op_range(self): + """Sets the index range of the Ops that we will consider tracing.""" + found, op_range = self.get_flag_value(FLAG_NAME_OP_RANGE) + if not found or not op_range: + op_range = (-1, -1) # this means including all ops. + return op_range + match = _OP_RANGE_PAT.match(op_range) + if not match: + op_range = (-1, -1) # this means including all ops. + return op_range + op_range = (int(match.group(1)), int(match.group(2))) + return op_range + + def _get_trace_dir(self): + found, trace_dir = self.get_flag_value(FLAG_NAME_TRACE_DIR) + if found and trace_dir and self.use_test_undeclared_outputs_dir(): + raise ValueError( + 'Cannot not use --%s and --%s at the same time' % + (FLAG_NAME_TRACE_DIR, FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR)) + if self.use_test_undeclared_outputs_dir(): + trace_dir = self._env.get(_TEST_UNDECLARED_OUTPUTS_DIR_ENV_VAR) + return trace_dir + + def _get_trace_mode(self): + """Checks if the given trace mode is valid.""" + + found, trace_mode = self.get_flag_value(FLAG_NAME_TRACE_MODE) + if not found or not trace_mode: + trace_mode = TRACE_MODE_NORM + valid_trace_modes = [ + TRACE_MODE_NAN_INF, TRACE_MODE_PART_TENSOR, TRACE_MODE_FULL_TENSOR, + TRACE_MODE_NORM, TRACE_MODE_MAX_ABS, + TRACE_MODE_SUMMARY, TRACE_MODE_FULL_TENSOR_SUMMARY, + TRACE_MODE_HISTORY + ] + if trace_mode not in valid_trace_modes: + raise ValueError('Invalid trace mode "%s" given to the Tensor_Tracer.' + 'Valid trace modes are: %s'%(trace_mode, + valid_trace_modes)) + return trace_mode + + def is_brief_mode(self): + return self.submode == _SUBMODE_BRIEF + + def _get_submode(self): + """Checks if the given submode is valid.""" + + found, submode = self.get_flag_value(FLAG_NAME_SUBMODE) + if not found or not submode: + submode = _SUBMODE_DETAILED + if not submode: + return + valid_submodes = [_SUBMODE_DETAILED, _SUBMODE_BRIEF] + if submode not in valid_submodes: + raise ValueError('Invalid submode "%s" given to the Tensor_Tracer.' + 'Valid submodes are: %s'%(submode, + valid_submodes)) + return submode + + @staticmethod + def match_next_flag(tt_flags, pos): + """Returns the match for the next TensorTracer flag. + + Args: + tt_flags: a string that contains the flags. + pos: where in flags to start the search. + + Returns: + A pair where the first element is the regular-expression + match found and the second element indicates if the match + has a value. + """ + + match = _FLAG_DOUBLE_QUOTE_PAT.match(tt_flags, pos) + if match: + return match, True + match = _FLAG_SINGLE_QUOTE_PAT.match(tt_flags, pos) + if match: + return match, True + match = _FLAG_NO_QUOTE_PAT.match(tt_flags, pos) + if match: + return match, True + match = _FLAG_NO_EQUAL_PAT.match(tt_flags, pos) + if match: + # The flag is found but is not given a value. + return match, False + # The flag is not found. + return None, False + + def _validate_flag_names(self): + """Validates if the TensorTrace flags passed are valid.""" + tensor_tracer_flags = self._env.get(FLAGS_ENV_VAR) + if not tensor_tracer_flags: + return + pos = 0 + while True: + match, _ = TTParameters.match_next_flag(tensor_tracer_flags, pos) + if not match: + break + flag_name = match.group(1) + if flag_name not in VALID_FLAG_NAMES: + raise ValueError( + 'The flag name "%s" passed via the environment variable "%s" ' + 'is invalid. Valid flag names are:' + '\n%s' % (flag_name, FLAGS_ENV_VAR, VALID_FLAG_NAMES)) + pos = match.end() + + def _supported_signatures(self): + """Returns a tuple of supported signatures.""" + return TT_SUMMARY_SIGNATURES + + def _get_summary_signatures(self): + """Verifies and returns the summary signatures. + + Returns: + A dictionary of the signature identifiers {signature: index} that will be + computed when trace_mode is summary. + """ + signatures = self._flag_value_as_list(FLAG_NAME_SUMMARY_SIGNATURES) + supported_signatures = self._supported_signatures() + + tt_signatures = [] + for signature in signatures: + signature_with_prefix = '%s_%s' % (_TT_PREFIX, signature) + if signature in supported_signatures: + tt_signatures.append(signature) + elif signature_with_prefix in supported_signatures: + tt_signatures.append(signature_with_prefix) + else: + logging.warning('Unknown signature:%s. Supported signatures: %s' % + (signature, supported_signatures)) + if not tt_signatures: + # Default case collects norm and max only. + return {TT_SUMMARY_MAX_ABS: 0, TT_SUMMARY_NORM: 1} + else: + return {signature: idx for idx, signature in enumerate(tt_signatures)} + + def get_signature_to_agg_fn_map(self): + """Returns a map that contains the aggregate function for each signature.""" + # TODO(b/199284834): Aggregations are not accurate for mean and sparsity if + # cores have a different number of elements. Variance uses the maximal core + # variance. + return {TRACE_MODE_NORM: linalg_ops.norm, + TRACE_MODE_HISTORY: math_ops.reduce_max, + TRACE_MODE_MAX_ABS: math_ops.reduce_max, + TRACE_MODE_NAN_INF: math_ops.reduce_max, + TT_SUMMARY_NORM: linalg_ops.norm, + TT_SUMMARY_MAX: math_ops.reduce_max, + TT_SUMMARY_MAX_ABS: + lambda t, axis=0: math_ops.reduce_max(math_ops.abs(t), # pylint: disable=g-long-lambda + axis=axis), + TT_SUMMARY_MIN: math_ops.reduce_min, + # Exact if each part has the same number of values. + TT_SUMMARY_SPARSITY: math_ops.reduce_mean, + TT_SUMMARY_MEAN: math_ops.reduce_mean, + TT_SUMMARY_VAR: math_ops.reduce_max, # Simply reduce max variance. + TT_SUMMARY_SIZE: math_ops.reduce_sum} + + def _flag_value_as_list(self, wanted_flag_name): + """Returns the string list of a TensorTracer flag. + + Args: + wanted_flag_name: the name of the flag we are looking for. + + Returns: + The list value of the flag. + """ + string_value_list = [] + found, flag_value = self.get_flag_value(wanted_flag_name) + + if found: + assert flag_value is not None + string_value_list = flag_value.split(',') + return string_value_list + + def _flag_value_as_int_list(self, wanted_flag_name): + """Returns the integer list of a TensorTracer flag. + + Args: + wanted_flag_name: the name of the flag we are looking for. + + Returns: + the value of the flag. + Raises: + RuntimeError: If supposedly deadcode is reached. + """ + int_list = [] + found, flag_value = self.get_flag_value(wanted_flag_name) + + if found and flag_value: + try: + integer_values = flag_value.split(',') + int_list = [int(int_val) for int_val in integer_values] + except ValueError: + logging.warning('Cannot convert %s to int for flag %s', int_list, + wanted_flag_name) + return int_list + + def _get_flag_int_value(self, wanted_flag_name, default_value): + """Returns the int value of a TensorTracer flag. + + Args: + wanted_flag_name: the name of the flag we are looking for. + default_value: the default value for the flag, if not provided. + Returns: + the value of the flag. + Raises: + RuntimeError: If supposedly deadcode is reached. + """ + flag_int_value = default_value + found, flag_value = self.get_flag_value(wanted_flag_name) + + if found: + try: + flag_int_value = int(flag_value) + except ValueError: + logging.warning('Cannot convert %s to int for flag %s' % ( + flag_int_value, wanted_flag_name)) + return flag_int_value + + def get_flag_value(self, wanted_flag_name): + """Returns the value of a TensorTracer flags. + + Args: + wanted_flag_name: the name of the flag we are looking for. + + Returns: + A pair where the first element indicates if the flag is + found and the second element is the value of the flag. + + Raises: + RuntimeError: If supposedly deadcode is reached. + """ + + tensor_tracer_flags = self._env.get(FLAGS_ENV_VAR) + if not tensor_tracer_flags: + return False, None + pos = 0 + while True: + match, has_value = TTParameters.match_next_flag( + tensor_tracer_flags, pos) + if not match: + return False, None + flag_name = match.group(1) + if has_value: + flag_value = match.group(2) + else: + flag_value = None + if flag_name == wanted_flag_name: + return True, flag_value + pos = match.end() + raise RuntimeError('Invalid tensor tracer flag. Could not recognize %s.' % + flag_name) + + def _flag_value_to_re_list(self, flag_name): + """Converts list of strings to compiled RE.""" + + re_list = [] + found, flag_value = self.get_flag_value(flag_name) + if not found or not flag_value: + return re_list + list_of_values = flag_value.split(',') + for v in list_of_values: + r = re.compile(v) + re_list.append(r) + return re_list + + def is_flag_on(self, flag_name): + """Returns True if the given flag is on.""" + + found, flag_value = self.get_flag_value(flag_name) + if not found: + return False + if flag_value is None: + return True + # Depends on the flag value. + flag_value = flag_value.lower() + enabled = flag_value in ['1', 't', 'true', 'y', 'yes'] + return enabled + + def is_enabled(self): + """Returns True if TensorTracer is enabled.""" + + if self.is_flag_on(FLAG_NAME_ENABLE): + logging.debug('Tensor Tracer is enabled with flags %s.', + self._env.get(FLAGS_ENV_VAR)) + return True + else: + return False + + def use_test_undeclared_outputs_dir(self): + """Decides the output directory of the report and trace files. + + Args: + None. + + Returns: + True if the output files should be written to the + test-undeclared-outputs-directory defined via an + env variable. + """ + + return self.is_flag_on(FLAG_NAME_USE_TEST_UNDECLARED_OUTPUTS_DIR) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ebeb6f38b4cd29029003abd204d404c4343714 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_pb2.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/tpu/tensor_tracer.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.core.framework import graph_pb2 as tensorflow_dot_core_dot_framework_dot_graph__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n)tensorflow/python/tpu/tensor_tracer.proto\x12\ntensorflow\x1a%tensorflow/core/framework/graph.proto\"\xb4\t\n\x12TensorTracerReport\x12\x41\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\x31.tensorflow.TensorTracerReport.TensorTracerConfig\x12&\n\x08graphdef\x18\x02 \x01(\x0b\x32\x14.tensorflow.GraphDef\x12@\n\ttensordef\x18\x03 \x03(\x0b\x32-.tensorflow.TensorTracerReport.TensordefEntry\x12\x13\n\x0b\x66ingerprint\x18\x04 \x01(\t\x12\x1e\n\x16\x63oncrete_function_name\x18\x05 \x01(\t\x12\x1c\n\x14last_common_frame_no\x18\x06 \x01(\x05\x12\x0f\n\x07outputs\x18\x07 \x03(\t\x12\x42\n\rtracing_stats\x18\x08 \x01(\x0b\x32+.tensorflow.TensorTracerReport.TracingStats\x1a`\n\x0eTensordefEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12=\n\x05value\x18\x02 \x01(\x0b\x32..tensorflow.TensorTracerReport.TracedTensorDef:\x02\x38\x01\x1a\xc8\x01\n\x12TensorTracerConfig\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x0e\n\x06\x64\x65vice\x18\x02 \x01(\t\x12\x12\n\ntrace_mode\x18\x03 \x01(\t\x12\x11\n\tnum_cores\x18\x04 \x01(\x05\x12\x11\n\tnum_hosts\x18\x05 \x01(\x05\x12\x0f\n\x07submode\x18\x06 \x01(\t\x12\x1a\n\x12num_cores_per_host\x18\x07 \x01(\x05\x12\x16\n\x0eincluded_cores\x18\x08 \x03(\x05\x12\x12\n\nsignatures\x18\t \x03(\t\x1a\xef\x01\n\x0cTracingStats\x12\x15\n\rtotal_tensors\x18\x01 \x01(\x05\x12\x16\n\x0etraced_tensors\x18\x02 \x01(\x05\x12_\n\x13traced_tensor_types\x18\x03 \x03(\x0b\x32\x42.tensorflow.TensorTracerReport.TracingStats.TracedTensorTypesEntry\x12\x15\n\radded_tensors\x18\x04 \x01(\x05\x1a\x38\n\x16TracedTensorTypesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\xa9\x02\n\x0fTracedTensorDef\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x63\x61\x63he_index\x18\x02 \x01(\x05\x12\x18\n\x10trace_point_name\x18\x03 \x01(\t\x12\x11\n\tis_traced\x18\x04 \x01(\x08\x12\x13\n\x0b\x65xplanation\x18\x05 \x01(\t\x12K\n\rop_stack_info\x18\x06 \x01(\x0b\x32\x34.tensorflow.TensorTracerReport.TracedTensorDef.Stack\x1a\x64\n\x05Stack\x12\x16\n\x0estack_fn_names\x18\x01 \x03(\t\x12\x13\n\x0bstack_lines\x18\x02 \x03(\t\x12\x17\n\x0fstack_filenames\x18\x03 \x03(\t\x12\x15\n\rstack_linenos\x18\x04 \x03(\x05\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.tpu.tensor_tracer_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _TENSORTRACERREPORT_TENSORDEFENTRY._options = None + _TENSORTRACERREPORT_TENSORDEFENTRY._serialized_options = b'8\001' + _TENSORTRACERREPORT_TRACINGSTATS_TRACEDTENSORTYPESENTRY._options = None + _TENSORTRACERREPORT_TRACINGSTATS_TRACEDTENSORTYPESENTRY._serialized_options = b'8\001' + _TENSORTRACERREPORT._serialized_start=97 + _TENSORTRACERREPORT._serialized_end=1301 + _TENSORTRACERREPORT_TENSORDEFENTRY._serialized_start=460 + _TENSORTRACERREPORT_TENSORDEFENTRY._serialized_end=556 + _TENSORTRACERREPORT_TENSORTRACERCONFIG._serialized_start=559 + _TENSORTRACERREPORT_TENSORTRACERCONFIG._serialized_end=759 + _TENSORTRACERREPORT_TRACINGSTATS._serialized_start=762 + _TENSORTRACERREPORT_TRACINGSTATS._serialized_end=1001 + _TENSORTRACERREPORT_TRACINGSTATS_TRACEDTENSORTYPESENTRY._serialized_start=945 + _TENSORTRACERREPORT_TRACINGSTATS_TRACEDTENSORTYPESENTRY._serialized_end=1001 + _TENSORTRACERREPORT_TRACEDTENSORDEF._serialized_start=1004 + _TENSORTRACERREPORT_TRACEDTENSORDEF._serialized_end=1301 + _TENSORTRACERREPORT_TRACEDTENSORDEF_STACK._serialized_start=1201 + _TENSORTRACERREPORT_TRACEDTENSORDEF_STACK._serialized_end=1301 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_report.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_report.py new file mode 100644 index 0000000000000000000000000000000000000000..2d47a7ddb258be37107865c7f8104df83bee5e26 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tensor_tracer_report.py @@ -0,0 +1,436 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== +"""Tensor Tracer report generation utilities.""" + +import collections +import hashlib +import os + +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tensor_tracer_pb2 + +_TRACER_LOG_PREFIX = ' [>>>TT>>>]' +_MARKER_SECTION_BEGIN = '!!!!!!! section-begin:' +_MARKER_SECTION_END = '!!!!!!! section-end:' + +_SECTION_NAME_CONFIG = 'configuration' +_SECTION_NAME_REASON = 'reason' +_SECTION_NAME_OP_LIST = 'op-list' +_SECTION_NAME_TENSOR_LIST = 'tensor-list' +_SECTION_NAME_CACHE_INDEX_MAP = 'cache-index-map' +_SECTION_NAME_GRAPH = 'graph' +_SECTION_NAME_TENSOR_TRACER_CHECKPOINT = 'tensor_tracer_checkpoint' + +_FIELD_NAME_VERSION = 'version:' +_FIELD_NAME_DEVICE = 'device:' +_FIELD_NAME_TRACE_MODE = 'trace-mode:' +_FIELD_NAME_SUBMODE = 'submode:' +_FIELD_NAME_NUM_REPLICAS = 'num-replicas:' +_FIELD_NAME_NUM_REPLICAS_PER_HOST = 'num-replicas-per-host:' +_FIELD_NAME_NUM_HOSTS = 'num-hosts:' +_FIELD_NAME_NUM_OPS = 'number-of-ops:' +_FIELD_NAME_NUM_TENSORS = 'number-of-tensors:' +_FIELD_NAME_NUM_CACHE_INDICES = 'number-of-indices:' +_FIELD_NAME_TOPOLOGICAL_SORT_SUCCEED = 'topological-sort-succeed:' + +_CURRENT_VERSION = 'use-outside-compilation' + +_TT_REPORT_PROTO = 'tensor_tracer_report.report_pb' + + +def topological_sort(g): + """Performs topological sort on the given graph. + + Args: + g: the graph. + + Returns: + A pair where the first element indicates if the topological + sort succeeded (True if there is no cycle found; False if a + cycle is found) and the second element is either the sorted + list of nodes or the cycle of nodes found. + """ + def _is_loop_edge(op): + """Returns true if the op is the end of a while-loop creating a cycle.""" + return op.type in ['NextIteration'] + + def _in_op_degree(op): + """Returns the number of incoming edges to the given op. + + The edge calculation skips the edges that come from 'NextIteration' ops. + NextIteration creates a cycle in the graph. We break cycles by treating + this op as 'sink' and ignoring all outgoing edges from it. + Args: + op: Tf.Operation + Returns: + the number of incoming edges. + """ + count = 0 + for op in op.control_inputs + [in_tensor.op for in_tensor in op.inputs]: + if not _is_loop_edge(op): + count += 1 + return count + + sorted_ops = [] + op_in_degree = {op: _in_op_degree(op) for op in g.get_operations()} + + frontier = [op for (op, degree) in op_in_degree.items() if degree == 0] + frontier.sort(key=lambda op: op.name) + while frontier: + op = frontier.pop() + # Remove the op from graph, and remove its outgoing edges. + sorted_ops.append(op) + if _is_loop_edge(op): + continue + # pylint: disable=protected-access + consumers = list(op._control_outputs) + # pylint: enable=protected-access + for out_tensor in op.outputs: + consumers += [consumer_op for consumer_op in out_tensor.consumers()] + consumers.sort(key=lambda op: op.name) + for consumer in consumers: + # For each deleted edge shift the bucket of the vertex. + op_in_degree[consumer] -= 1 + if op_in_degree[consumer] == 0: + frontier.append(consumer) + if op_in_degree[consumer] < 0: + raise ValueError('consumer:%s degree mismatch'%consumer.name) + + left_ops = set(op for (op, degree) in op_in_degree.items() if degree > 0) + if left_ops: + return (True, left_ops) + else: + assert len(g.get_operations()) == len(sorted_ops) + return (False, sorted_ops) + + +class TensorTracerConfig(object): + """Tensor Tracer config object.""" + + def __init__(self): + self.version = _CURRENT_VERSION + self.device_type = None + self.num_replicas = None + self.num_replicas_per_host = None + self.num_hosts = None + + +class TensorTraceOrder(object): + """Class that is responsible from storing the trace-id of the tensors.""" + + def __init__(self, graph_order, traced_tensors): + self.graph_order = graph_order + self.traced_tensors = traced_tensors + self._create_tensor_maps() + + def _create_tensor_maps(self): + """Creates tensor to cache id maps.""" + self.tensorname_to_cache_idx = {} + self.cache_idx_to_tensor_idx = [] + for out_tensor in self.traced_tensors: + tensor_name = out_tensor.name + if tensor_name in self.tensorname_to_cache_idx: + raise ValueError('Tensor name {} should not be already in ' + 'tensorname_to_cache_idx'.format(tensor_name)) + if tensor_name not in self.graph_order.tensor_to_idx: + raise ValueError( + 'Tensor name {} is not in the tensor_to_idx, tensor_to_idx={} ' + .format(tensor_name, self.graph_order.tensor_to_idx)) + tensor_idx = self.graph_order.tensor_to_idx[tensor_name] + cache_idx = len(self.tensorname_to_cache_idx) + self.tensorname_to_cache_idx[tensor_name] = cache_idx + self.cache_idx_to_tensor_idx.append(tensor_idx) + if len(self.tensorname_to_cache_idx) != len( + self.cache_idx_to_tensor_idx): + raise RuntimeError( + 'len(self.tensorname_to_cache_idx) must equal' + 'len(self.cache_idx_to_tensor_idx), got ' + 'len(self.tensorname_to_cache_idx)={}, ' + 'len(self.cache_idx_to_tensor_idx)={}' + .format( + len(self.tensorname_to_cache_idx), + len(self.cache_idx_to_tensor_idx))) + + +def sort_tensors_and_ops(graph): + """Returns a wrapper that has consistent tensor and op orders.""" + graph_wrapper = collections.namedtuple('GraphWrapper', + ['graph', 'operations', 'op_to_idx', + 'tensors', 'tensor_to_idx', + 'contains_cycle', + 'topological_order_or_cycle']) + contains_cycle, topological_order_or_cycle = topological_sort(graph) + if not contains_cycle: + operations = topological_order_or_cycle + else: + operations = graph.get_operations() + op_to_idx = {op.name: index for index, op + in enumerate(operations)} + tensors = [] + for op in operations: + tensors.extend(op.outputs) + tensor_to_idx = {tensor.name: index for index, tensor in + enumerate(tensors)} + return graph_wrapper(graph=graph, operations=operations, op_to_idx=op_to_idx, + tensors=tensors, tensor_to_idx=tensor_to_idx, + contains_cycle=contains_cycle, + topological_order_or_cycle=topological_order_or_cycle) + + +class OpenReportFile(object): + """Context manager for writing report file.""" + + def __init__(self, tt_parameters): + if not tt_parameters.report_file_path: + self._report_file = None + return + try: + self._report_file = gfile.Open(tt_parameters.report_file_path, 'w') + except IOError as e: + raise e + + def __enter__(self): + return self._report_file + + def __exit__(self, unused_type, unused_value, unused_traceback): + if self._report_file: + self._report_file.close() + + +def proto_fingerprint(message_proto): + serialized_message = message_proto.SerializeToString() + hasher = hashlib.sha256(serialized_message) + return hasher.hexdigest() + + +class TTReportHandle(object): + """Utility class responsible from creating a tensor tracer report.""" + + def __init__(self): + self.instrument_records = {} + self._report_file = None + + def instrument(self, name, explanation): + self.instrument_records[name] = explanation + + def instrument_op(self, op, explanation): + self.instrument(op.name, explanation) + + def instrument_tensor(self, tensor, explanation): + self.instrument(tensor.name, explanation) + + def create_report_proto(self, tt_config, tt_parameters, tensor_trace_order, + tensor_trace_points, collected_signature_types): + """Creates and returns a proto that stores tensor tracer configuration. + + Args: + tt_config: TensorTracerConfig object holding information about the run + environment (device, # cores, # hosts), and tensor tracer version + information. + tt_parameters: TTParameters objects storing the user provided parameters + for tensor tracer. + tensor_trace_order: TensorTraceOrder object storing a topological order of + the graph. + tensor_trace_points: Progromatically added trace_points/checkpoints. + collected_signature_types: The signature types collected, e,g, norm, + max, min, mean... + Returns: + TensorTracerReport proto. + """ + report = tensor_tracer_pb2.TensorTracerReport() + report.config.version = tt_config.version + report.config.device = tt_config.device_type + report.config.num_cores = tt_config.num_replicas + report.config.num_hosts = tt_config.num_hosts + report.config.num_cores_per_host = tt_config.num_replicas_per_host + report.config.submode = tt_parameters.submode + report.config.trace_mode = tt_parameters.trace_mode + + for signature_name, _ in sorted(collected_signature_types.items(), + key=lambda x: x[1]): + report.config.signatures.append(signature_name) + + for tensor in tensor_trace_order.graph_order.tensors: + tensor_def = tensor_tracer_pb2.TensorTracerReport.TracedTensorDef() + tensor_def.name = tensor.name + if tensor.name in tensor_trace_order.tensorname_to_cache_idx: + tensor_def.is_traced = True + tensor_def.cache_index = ( + tensor_trace_order.tensorname_to_cache_idx[tensor.name]) + else: + # To prevent small changes affecting the fingerprint calculation, avoid + # writing the untraced tensors to metadata. Fingerprints will be + # different only when the list of the traced tensors are different. + if tt_parameters.use_fingerprint_subdir: + continue + tensor_def.is_traced = False + + if tensor.name in tensor_trace_points: + tensor_def.trace_point_name = tensor_trace_points[tensor.name] + if tensor.name in self.instrument_records: + tensor_def.explanation = self.instrument_records[tensor.name] + elif tensor.op.name in self.instrument_records: + tensor_def.explanation = self.instrument_records[tensor.op.name] + report.tensordef[tensor.name].CopyFrom(tensor_def) + report.fingerprint = proto_fingerprint(report) + logging.info('TensorTracerProto fingerprint is %s.', + report.fingerprint) + tf_graph = tensor_trace_order.graph_order.graph + report.graphdef.CopyFrom(tf_graph.as_graph_def()) + return report + + def report_proto_path(self, trace_dir, summary_tag_name): + """Returns the path where report proto should be written. + + Args: + trace_dir: String denoting the trace directory. + summary_tag_name: Name of the unique tag that relates to + the report. + Returns: + A string denoting the path to the report proto. + """ + filename = _TT_REPORT_PROTO + '.' + summary_tag_name.replace('/', '_') + return os.path.join(trace_dir, filename) + + def write_report_proto(self, report_path, report_proto, tt_parameters): + """Writes the given report proto under trace_dir.""" + gfile.MakeDirs(tt_parameters.trace_dir) + with gfile.GFile(report_path, 'wb') as f: + f.write(report_proto.SerializeToString()) + + def create_report(self, tt_config, tt_parameters, + tensor_trace_order, tensor_trace_points): + """Creates a report file and writes the trace information.""" + with OpenReportFile(tt_parameters) as self._report_file: + self._write_config_section(tt_config, tt_parameters) + self._write_op_list_section(tensor_trace_order.graph_order) + self._write_tensor_list_section(tensor_trace_order.graph_order) + self._write_trace_points(tensor_trace_points) + self._write_cache_index_map_section(tensor_trace_order) + self._write_reason_section() + self._write_graph_section(tensor_trace_order.graph_order) + + def _write_trace_points(self, tensor_trace_points): + """Writes the list of checkpoints.""" + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, + _SECTION_NAME_TENSOR_TRACER_CHECKPOINT)) + for (tensor, checkpoint_name) in tensor_trace_points: + self._write_report('%s %s\n'%(tensor.name, checkpoint_name)) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, + _SECTION_NAME_TENSOR_TRACER_CHECKPOINT)) + + def _write_report(self, content): + """Writes the given content to the report.""" + + line = '%s %s'%(_TRACER_LOG_PREFIX, content) + if self._report_file: + self._report_file.write(line) + else: + logging.info(line) + + def _write_config_section(self, tt_config, tt_parameters): + """Writes the config section of the report.""" + + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_CONFIG)) + self._write_report('%s %s\n'%(_FIELD_NAME_VERSION, tt_config.version)) + self._write_report('%s %s\n'%(_FIELD_NAME_DEVICE, tt_config.device_type)) + self._write_report('%s %s\n'%(_FIELD_NAME_TRACE_MODE, + tt_parameters.trace_mode)) + self._write_report('%s %s\n'%(_FIELD_NAME_SUBMODE, + tt_parameters.submode)) + self._write_report('%s %s\n'%(_FIELD_NAME_NUM_REPLICAS, + tt_config.num_replicas)) + self._write_report('%s %s\n'%(_FIELD_NAME_NUM_REPLICAS_PER_HOST, + tt_config.num_replicas_per_host)) + self._write_report('%s %s\n'%(_FIELD_NAME_NUM_HOSTS, tt_config.num_hosts)) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_CONFIG)) + + def _write_reason_section(self): + """Writes the reason section of the report.""" + + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_REASON)) + for key in sorted(self.instrument_records): + self._write_report('"%s" %s\n'%(key, self.instrument_records[key])) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_REASON)) + + def _write_op_list_section(self, graph_order): + """Writes the Op-list section of the report.""" + + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_OP_LIST)) + self._write_report('%s %d\n'%(_FIELD_NAME_NUM_OPS, + len(graph_order.operations))) + for i in range(0, len(graph_order.operations)): + op = graph_order.operations[i] + line = '%d "%s" %s'%(i, op.name, op.type) + for out_tensor in op.outputs: + if out_tensor.name not in graph_order.tensor_to_idx: + raise ValueError( + 'out_tensor is not in tensor_to_idx. out_tensor={}, ' + 'tensor_to_idx={}' + .format(out_tensor.name, graph_order.tensor_to_idx)) + line += ' %d'%graph_order.tensor_to_idx[out_tensor.name] + line += '\n' + self._write_report(line) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_OP_LIST)) + + def _write_tensor_list_section(self, graph_order): + """Writes the tensor-list section of the report.""" + + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, + _SECTION_NAME_TENSOR_LIST)) + self._write_report('%s %d\n'%(_FIELD_NAME_NUM_TENSORS, + len(graph_order.tensors))) + for i in range(0, len(graph_order.tensors)): + tensor = graph_order.tensors[i] + line = '%d "%s"'%(i, tensor.name) + consumers = tensor.consumers() + consumers.sort(key=lambda op: op.name) + for consumer_op in consumers: + if consumer_op.name not in graph_order.op_to_idx: + raise ValueError( + 'consumer_op is not in op_to_idx. ' + 'got consumer_op={}, op_to_idx={}' + .format(consumer_op.name, graph_order.op_to_idx)) + line += ' %d'%graph_order.op_to_idx[consumer_op.name] + line += '\n' + self._write_report(line) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, + _SECTION_NAME_TENSOR_LIST)) + + def _write_cache_index_map_section(self, tensor_trace_order): + """Writes the mapping from cache index to tensor index to the report.""" + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, + _SECTION_NAME_CACHE_INDEX_MAP)) + self._write_report('%s %d\n'%( + _FIELD_NAME_NUM_CACHE_INDICES, + len(tensor_trace_order.cache_idx_to_tensor_idx))) + for cache_idx in range(0, len(tensor_trace_order.cache_idx_to_tensor_idx)): + tensor_idx = tensor_trace_order.cache_idx_to_tensor_idx[cache_idx] + line = '%d %d\n'%(cache_idx, tensor_idx) + self._write_report(line) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, + _SECTION_NAME_CACHE_INDEX_MAP)) + + def _write_graph_section(self, graph_order): + """Writes the graph section of the report.""" + + self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_GRAPH)) + self._write_report('%s %s\n'%(_FIELD_NAME_TOPOLOGICAL_SORT_SUCCEED, + not graph_order.contains_cycle)) + l = list(graph_order.topological_order_or_cycle) + for i in range(0, len(l)): + self._write_report('%d "%s"\n'%(i, l[i].name)) + self._write_report('%s %s\n'%(_MARKER_SECTION_END, _SECTION_NAME_GRAPH)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/topology.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/topology.py new file mode 100644 index 0000000000000000000000000000000000000000..49bdd996c129fa15e008db7d9be4947f78d60fdb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/topology.py @@ -0,0 +1,239 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Defines the `Topology` class, that describes a TPU fabric topology.""" + +import numpy as np + +from tensorflow.core.protobuf.tpu import topology_pb2 +from tensorflow.python.util.tf_export import tf_export + + +def _tpu_device_name(job, task, device): + """Returns the device name for the TPU `device` on `task` of `job`.""" + if job is None: + return "/task:%d/device:TPU:%d" % (task, device) + else: + return "/job:%s/task:%d/device:TPU:%d" % (job, task, device) + + +def _tpu_host_device_name(job, task): + """Returns the device name for the CPU device on `task` of `job`.""" + if job is None: + return "/task:%d/device:CPU:0" % task + else: + return "/job:%s/task:%d/device:CPU:0" % (job, task) + + +@tf_export("tpu.experimental.Topology") +class Topology(object): + """Describes a set of TPU devices. + + Represents both the shape of the physical mesh, and the mapping between + TensorFlow TPU devices to physical mesh coordinates. + """ + + def __init__(self, serialized=None, mesh_shape=None, device_coordinates=None): + """Builds a Topology object. + + If `serialized` is not `None`, the topology is parsed from `serialized` and + the other arguments are ignored. Otherwise, the topology is computed from + `mesh_shape` and `device_coordinates`. + + Args: + serialized: A serialized `TopologyProto`, or `None`. If not `None`, the + serialized proto is parsed to discover the topology. + mesh_shape: A sequence of 4 positive integers, or `None`. If not `None`, + the shape of the TPU topology, in number of cores. Ignored if + `serialized` is not `None`. + device_coordinates: A rank 3 numpy array that describes the mapping from + TensorFlow TPU devices to TPU fabric coordinates, or `None`. If + specified, array is a rank 3 int32 array with shape + `[tasks, devices, axis]`. `tasks` is the number of tasks in the TPU + cluster, `devices` is the number of TPU devices per task, and `axis` is + the number of axes in the TPU cluster topology. Each entry gives the + `axis`-th coordinate in the topology of a task/device pair. TPU + topologies are 4-dimensional, with dimensions `(x, y, z, core number)`. + This arg is ignored if `serialized is not `None`. + + Raises: + ValueError: If `serialized` does not describe a well-formed topology. + ValueError: If `serialized` is `None` and `mesh_shape` is not a sequence + of 4 positive integers. + ValueError: If `serialized` is `None` and `device_coordinates` is not a + rank 3 numpy int32 array that describes a valid coordinate mapping. + """ + + self._serialized = serialized + + if serialized: + self._parse_topology(serialized) + else: + self._mesh_shape = np.asarray(mesh_shape, dtype=np.int32) + self._device_coordinates = np.asarray(device_coordinates, np.int32) + if len(self._mesh_shape) != 4 or any(self._mesh_shape < 1): + raise ValueError("`mesh_shape` must be a sequence of 4 positive " + f"entries; got `mesh_shape={self._mesh_shape}`") + + if (len(self._device_coordinates.shape) != 3 or + self._device_coordinates.shape[2] != len(self._mesh_shape)): + raise ValueError( + "`device_coordinates` must be a rank 3 int32 array " + "with minor dimension equal to the `mesh_shape` rank" + "got device_coordinates.shape={} len(device_coordinates.shape)={} device_coordinates.shape[2]={} mesh_shape={}, len(mesh_shape)={}" + .format(self._device_coordinates.shape, + len(self._device_coordinates.shape), + self._device_coordinates.shape[2], self._mesh_shape, + len(self._mesh_shape))) + + self._topology_tasks, self._topology_devices = self._invert_topology() + + # Coordinates of devices that are missing + self._missing_devices = np.argwhere(self._topology_tasks < 0) + + def _parse_topology(self, serialized): + """Parses a serialized `TopologyProto` into `self`.""" + proto = topology_pb2.TopologyProto() + proto.ParseFromString(serialized) + + self._mesh_shape = np.array(proto.mesh_shape, dtype=np.int32) + if len(self._mesh_shape) != 4 or any(self._mesh_shape < 1): + raise ValueError("`mesh_shape` must be a vector of size 4 with positive " + "entries; got {}".format(self._mesh_shape)) + + if proto.num_tasks < 0: + raise ValueError("`num_tasks` must be >= 0; got {}".format( + proto.num_tasks)) + if proto.num_tpu_devices_per_task < 0: + raise ValueError("`num_tpu_devices_per_task` must be >= 0; got {}".format( + proto.num_tpu_devices_per_task)) + + expected_coordinates_size = ( + proto.num_tasks * proto.num_tpu_devices_per_task * len( + proto.mesh_shape)) + if len(proto.device_coordinates) != expected_coordinates_size: + raise ValueError("`device_coordinates` must have shape num_tasks ({}) * " + "num_tpu_devices_per_task ({}) * len(mesh_shape) ({}); " + "got shape {}".format(proto.num_tasks, + proto.num_tpu_devices_per_task, + proto.mesh_shape, + len(proto.device_coordinates))) + + coords = np.array(proto.device_coordinates, dtype=np.int32) + if any(coords < 0): + raise ValueError( + "All values in `device_coordinates` must be >= 0, got {}" + .format(coords)) + coords = coords.reshape((proto.num_tasks, proto.num_tpu_devices_per_task, + len(proto.mesh_shape))) + self._device_coordinates = coords + + def _invert_topology(self): + """Inverts a [task,device,axis] topology to [x,y,z] -> task/device maps.""" + tasks = np.full(list(self.mesh_shape), -1, dtype=np.int32) + devices = np.full(list(self.mesh_shape), -1, dtype=np.int32) + for task in range(self.device_coordinates.shape[0]): + for device in range(self.device_coordinates.shape[1]): + x, y, z, core = self.device_coordinates[task, device, :] + tasks[x, y, z, core] = task + devices[x, y, z, core] = device + return tasks, devices + + @property + def mesh_shape(self): + """A rank 1 int32 array describing the shape of the TPU topology.""" + return self._mesh_shape + + @property + def mesh_rank(self): + """Returns the number of dimensions in the mesh.""" + return len(self._mesh_shape) + + @property + def device_coordinates(self): + """Describes the mapping from TPU devices to topology coordinates. + + Returns: + A rank 3 int32 array with shape `[tasks, devices, axis]`. + `tasks` is the number of tasks in the TPU cluster, `devices` is the number + of TPU devices per task, and `axis` is the number of axes in the TPU + cluster topology. Each entry gives the `axis`-th coordinate in the + topology of a task/device pair. TPU topologies are 4-dimensional, with + dimensions `(x, y, z, core number)`. + """ + return self._device_coordinates + + @property + def missing_devices(self): + """Array of indices of missing devices.""" + return self._missing_devices + + def task_ordinal_at_coordinates(self, device_coordinates): + """Returns the TensorFlow task number attached to `device_coordinates`. + + Args: + device_coordinates: An integer sequence describing a device's physical + coordinates in the TPU fabric. + + Returns: + Returns the TensorFlow task number that contains the TPU device with those + physical coordinates. + """ + return self._topology_tasks[tuple(device_coordinates)] + + def tpu_device_ordinal_at_coordinates(self, device_coordinates): + """Returns the TensorFlow device number at `device_coordinates`. + + Args: + device_coordinates: An integer sequence describing a device's physical + coordinates in the TPU fabric. + + Returns: + Returns the TensorFlow device number within the task corresponding to + attached to the device with those physical coordinates. + """ + return self._topology_devices[tuple(device_coordinates)] + + def cpu_device_name_at_coordinates(self, device_coordinates, job=None): + """Returns the CPU device attached to a logical core.""" + return _tpu_host_device_name( + job, self._topology_tasks[tuple(device_coordinates)]) + + def tpu_device_name_at_coordinates(self, device_coordinates, job=None): + """Returns the name of the TPU device assigned to a logical core.""" + return _tpu_device_name(job, + self._topology_tasks[tuple(device_coordinates)], + self._topology_devices[tuple(device_coordinates)]) + + @property + def num_tasks(self): + """Returns the number of TensorFlow tasks in the TPU slice.""" + return self._device_coordinates.shape[0] + + @property + def num_tpus_per_task(self): + """Returns the number of TPU devices per task in the TPU slice.""" + return self._device_coordinates.shape[1] + + def serialized(self): + """Returns the serialized form of the topology.""" + if self._serialized is None: + proto = topology_pb2.TopologyProto() + proto.mesh_shape[:] = list(self._mesh_shape) + proto.num_tasks = self._device_coordinates.shape[0] + proto.num_tpu_devices_per_task = self._device_coordinates.shape[1] + proto.device_coordinates.extend(list(self._device_coordinates.flatten())) + self._serialized = proto.SerializeToString() + + return self._serialized diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..cc830a68dc427d642b52c0e5bba226b9fca0a5ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu.py @@ -0,0 +1,1686 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== + +"""Library of TPU helper functions.""" + +import collections +import enum +from typing import Any, Callable, Iterable, List, Optional, Text, Tuple, Union + +from absl import logging +import numpy as np + +from tensorflow.compiler.tf2xla.python import xla as tf2xla +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.protobuf.tpu import dynamic_padding_pb2 as dynamic_padding +from tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2 as embedding_pb2 +from tensorflow.python import tf2 +from tensorflow.python.compiler.xla import xla +from tensorflow.python.framework import auto_control_deps +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.tpu import device_assignment as device_assignment_lib +from tensorflow.python.tpu import tensor_tracer +from tensorflow.python.tpu import tpu_feed +from tensorflow.python.tpu import tpu_function +from tensorflow.python.tpu import tpu_name_util +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.types import core as core_types +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util import traceback_utils +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +# Ops which can be safely pruned from XLA compile if they have no consumers. +# These ops should also have no inputs. +_UNCONNECTED_OPS_TO_PRUNE = set(["Placeholder", "VarHandleOp"]) + +_POST_DEVICE_REWRITE_ATTR = "_post_device_rewrite" +_TPU_COMPILATION_STATUS_ATTR = "_tpu_compilation_status" +_PIVOT_FOR_CLUSTER = "_pivot_for_cluster" + + +core = tpu_name_util.core + + +def _tpu_system_device_name(job: Optional[Text]) -> Text: + """Returns the device name for the TPU_SYSTEM device of `job`.""" + if job is None: + return "/device:TPU_SYSTEM:0" + else: + return "/job:%s/device:TPU_SYSTEM:0" % job + + +@tf_export(v1=["tpu.initialize_system"]) +def initialize_system( + embedding_config: Optional[embedding_pb2.TPUEmbeddingConfiguration] = None, + job: Optional[Text] = None, + compilation_failure_closes_chips: bool = True, + tpu_cancellation_closes_chips: Optional[bool] = None, +) -> core_types.Tensor: + """Initializes a distributed TPU system for use with TensorFlow. + + Args: + embedding_config: If not None, a `TPUEmbeddingConfiguration` proto + describing the desired configuration of the hardware embedding lookup + tables. If embedding_config is None, no hardware embeddings can be used. + job: The job (the XXX in TensorFlow device specification /job:XXX) that + contains the TPU devices that will be initialized. If job=None it is + assumed there is only one job in the TensorFlow flock, and an error will + be returned if this assumption does not hold. + compilation_failure_closes_chips: Set the configuration whether + we want to close TPU chips when there is a compilation failure. + tpu_cancellation_closes_chips: Set the configuration whether + we want to close TPU chips when a TPU execution is cancelled. If the value + is None, the behavior will be determined by the command line flag + `tpu_cancellation_closes_chips` for the TPU worker. WARNING: this argument + only applies to TFRT TPU runtime. + Returns: + A serialized `TopologyProto` that describes the TPU system. Note: + the topology must be evaluated using `Session.run` before it can be used. + """ + config_string = ("" if embedding_config is None else + embedding_config.SerializeToString()) + + # The enum is defined in core/tpu/kernels/tpu_execute_op_options.h. + tpu_cancellation_closes_chips_enum = 0 + if tpu_cancellation_closes_chips is not None: + if tpu_cancellation_closes_chips: + tpu_cancellation_closes_chips_enum = 1 + else: + tpu_cancellation_closes_chips_enum = 2 + + with ops.device(_tpu_system_device_name(job)): + topology = tpu_ops.configure_distributed_tpu( + compilation_failure_closes_chips=compilation_failure_closes_chips, + tpu_cancellation_closes_chips=tpu_cancellation_closes_chips_enum, + ) + + if embedding_config is None: + return topology + + # This set of control dependencies is needed as this function is expected to + # return an op which will return the topology when executed, but we need to + # call the embedding initialization op between initializing the TPU and + # returning the topology. + with ops.control_dependencies([topology]): + embedding_init = tpu_ops.configure_tpu_embedding(config=config_string) + with ops.control_dependencies([embedding_init]): + return array_ops.identity(topology, name="tpu_init_identity") + + +def initialize_system_for_tpu_embedding( + embedding_config: embedding_pb2.TPUEmbeddingConfiguration, + job: Optional[Text] = None, +) -> ops.Operation: + """Initializes a distributed TPU Embedding system for use with TensorFlow. + + The following two are equivalent: + 1. initialize_system() with embedding_config. + 2. initialize_system() without embedding_config, then + initialize_system_for_tpu_embedding(). + initialize_system() should not be called with embedding_config if + initialize_system_for_tpu_embedding() is meant to be called later. + + Args: + embedding_config: a `TPUEmbeddingConfiguration` proto describing the desired + configuration of the hardware embedding lookup tables. + job: The job (the XXX in TensorFlow device specification /job:XXX) that + contains the TPU devices that will be initialized. If job=None it is + assumed there is only one job in the TensorFlow flock, and an error will + be returned if this assumption does not hold. + + Returns: + A no-op. + """ + config_string = embedding_config.SerializeToString() + with ops.device(_tpu_system_device_name(job)): + return tpu_ops.configure_tpu_embedding(config=config_string) + + +@tf_export(v1=["tpu.shutdown_system"]) +def shutdown_system(job: Optional[Text] = None) -> ops.Operation: + """Shuts down a running a distributed TPU system. + + Args: + job: The job (the XXX in TensorFlow device specification /job:XXX) that + contains the TPU devices that will be shutdown. If job=None it is + assumed there is only one job in the TensorFlow flock, and an error will + be returned if this assumption does not hold. + """ + with ops.device(_tpu_system_device_name(job)): + shutdown_distributed_tpu = tpu_ops.shutdown_distributed_tpu() + return shutdown_distributed_tpu + + +@auto_control_deps.register_acd_resource_resolver +def tpu_replicated_input_resolver( + op: ops.Operation, + resource_reads: object_identity.ObjectIdentitySet, + resource_writes: object_identity.ObjectIdentitySet) -> bool: + """Replaces TPUReplicatedInput outputs with its inputs in resource_inputs.""" + # Ignore TPUReplicatedInput for ACD purposes since we will be directly adding + # control deps on the replicated inputs. + if op.type == "TPUReplicatedInput": + if resource_reads or resource_writes: + resource_reads.clear() + resource_writes.clear() + return True + else: + return False + # Replace tensors in `resource_inputs` which are outputs of TPUReplicatedInput + # with the actual replicated inputs. This allows ACD to correct add control + # deps when there are multiple calls to `run` in a + # `tf.function`. + def replace_with_unreplicated_resources(resource_inputs): + """Replaces handles in `resource_inputs` with their unreplicated inputs.""" + to_remove = [] + to_add = [] + for resource in resource_inputs: + if resource.op.type == "TPUReplicatedInput": + to_remove.append(resource) + to_add.extend(resource.op.inputs) + for t in to_remove: + resource_inputs.discard(t) + resource_inputs.update(to_add) + return to_add or to_remove + + return bool(replace_with_unreplicated_resources(resource_reads) or + replace_with_unreplicated_resources(resource_writes)) + + +@tf_export(v1=["tpu.PaddingSpec"]) +class PaddingSpec(enum.IntEnum): + """Represents the type of padding policies for tpu.replicate.""" + # By default the policy is set to AUTO, the dynamic input shape dimension will + # be pad to maximum of all the replicas. + AUTO = 0 + # Bucketize the dynamic input shape dimension into a power of 2. + POWER_OF_TWO = 1 + + +@tf_export("tpu.XLAOptions") +class XLAOptions( + collections.namedtuple("XLAOptions", [ + "use_spmd_for_xla_partitioning", + "enable_xla_dynamic_padder", + ])): + """XLA compilation options. + + Attributes: + use_spmd_for_xla_partitioning: Boolean. Whether to use XLA's SPMD + partitioner instead of MPMD partitioner when compiler partitioning is + requested. + enable_xla_dynamic_padder: Boolean. Whether to enable XLA dynamic padder + infrastructure to handle dynamic shapes inputs inside XLA. True by + default. Disabling this may cause correctness issues with dynamic shapes + inputs, as XLA will just assume the inputs are with padded shapes. However + users can optionally set it to False to improve device time if masking is + already handled in the user side. + """ + + def __new__(cls, + use_spmd_for_xla_partitioning=True, + enable_xla_dynamic_padder=True): + return super(XLAOptions, cls).__new__(cls, use_spmd_for_xla_partitioning, + enable_xla_dynamic_padder) + + +@tf_export(v1=["tpu.replicate"]) +@traceback_utils.filter_traceback +def replicate( + computation: Callable[..., Any], + inputs: Optional[List[List[core_types.Tensor]]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + maximum_shapes: Optional[Any] = None, + padding_spec: Optional[PaddingSpec] = None, + xla_options: Optional[XLAOptions] = None) -> List[Any]: + """Builds a graph operator that runs a replicated TPU computation. + + Example for the basic usage that `inputs` has static shape: + + ```python + + def computation(x): + x = x + 1 + return tf.math.reduce_mean(x) + + x = tf.convert_to_tensor([1., 2., 3.]) + y = tf.convert_to_tensor([4., 5., 6.]) + tf.compat.v1.tpu.replicate(computation, inputs=[[x], [y]]) + ``` + + If the `inputs` has dynamic shapes and you would like to automatically + bucketize the inputs to avoid XLA recompilation. See the advanced example + below: + + ```python + + def computation(x): + x = x + 1 + return tf.math.reduce_mean(x) + + # Assume input tensors in two replicas `x` and `y` both have dynamic shape + # ([None, 2]). + tf.compat.v1.tpu.replicate( + computation, + inputs=[x, y], + maximum_shapes=[tf.TensorShape([None, None])], + padding_spec=tf.compat.v1.tpu.PaddingSpec.POWER_OF_TWO) + ``` + + Args: + computation: A Python function that builds the computation to replicate. + inputs: A list of lists of input tensors or `None` (equivalent to + `[[]]`), indexed by `[replica_num][input_num]`. All replicas must + have the same number of inputs. Each input can be a nested structure + containing values that are convertible to tensors. Note that passing an + N-dimension list of compatible values will result in a N-dimension list of + scalar tensors rather than a single Rank-N tensors. If you need different + behavior, convert part of inputs to tensors with `tf.convert_to_tensor`. + infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple + of arguments as inputs to computation. + device_assignment: If not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. Uses a default device assignment if `None`. The + `DeviceAssignment` may be omitted if each replica of the computation uses + only one core, and there is either only one replica, or the number of + replicas is equal to the number of cores in the TPU system. + name: (Deprecated) Does nothing. + maximum_shapes: A nested structure of tf.TensorShape representing the shape + to which the respective component of each input element in each replica + should be padded. Any unknown dimensions (e.g. + tf.compat.v1.Dimension(None) in a tf.TensorShape or -1 in a tensor-like + object) will be padded to the maximum size of that dimension over all + replicas. The structure of `maximum_shapes` needs to be the same as + `inputs[0]`. + padding_spec: An enum specified by `tpu.PaddingSpec`. This describes the + padding policy when the `inputs` to `tpu.replicate` is dynamic. + One usage is to enable automatic bucketizing on the inputs by setting the + value to `tpu.PaddingSpec.POWER_OF_TWO`, which can help to reduce the + recompilation in the XLA side. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + Returns: + A list of outputs, indexed by `[replica_num]` each output can be a nested + structure same as what computation() returns with a few exceptions. + + Exceptions include: + 1) None output: a NoOp would be returned which control-depends on + computation. + 2) Single value output: A tuple containing the value would be returned. + 3) Operation-only outputs: a NoOp would be returned which + control-depends on computation. + TODO(b/121383831): Investigate into removing these special cases. + + Raises: + ValueError: If all replicas do not have equal numbers of input tensors. + ValueError: If the number of inputs per replica does not match + the number of formal parameters to `computation`. + ValueError: If the static `inputs` dimensions don't match with the values + given in `maximum_shapes`. + ValueError: If the structure of inputs per replica does not match + the structure of `maximum_shapes`. + """ + return split_compile_and_replicate( + computation, + inputs, + infeed_queue, + device_assignment, + name, + maximum_shapes=maximum_shapes, + padding_spec=padding_spec, + xla_options=xla_options)[1] + + +def _ceil_to_pow_of_n(x, n): + """Ceil input `x` to power of `n`.""" + x = math_ops.cast(x, dtypes.float32) + lognx = math_ops.log(x) / math_ops.log(n * 1.0) + lognx = math_ops.ceil(lognx) + result = math_ops.pow(n * 1.0, lognx) + result = math_ops.cast(result, dtypes.int32) + return result + + +def _pad_all_input( + inputs: Iterable[core_types.Tensor], + padded_shapes: List[Optional[tensor_shape.TensorShape]], + padding_spec: PaddingSpec +) -> Tuple[List[List[Any]], List[dynamic_padding.PaddingMap]]: + """Pad all input tensors given padded_shapes. + + The real shape tensors will be concatenated with the padded original inputs. + + Args: + inputs: The original inputs. + padded_shapes: A list of padded shapes for each input. If an entry is None, + no padding is performed. + padding_spec: An enum specified by `tpu.PaddingSpec`. This describes the + padding policy when the `inputs` to `tf.tpu.replicate` is dynamic. + One usage is to enable automatic bucketizing on the inputs by setting the + value to `tpu.PaddingSpec.POWER_OF_TWO`, which can help to reduce the + recompilation in the XLA side. + + Returns: + The padded inputs and a PaddingMap list which maps the padded input + dimension to the real shape argument index. + """ + # maximum_static_shapes[idx][i] indicates the maximum static size of ith + # dimension of the idx input among all the replicas. + maximum_static_shapes = [] + # need_padding[idx][i] indicates whether the ith dimension of the idx input + # needs padding. + need_padding = [] + input_shape_tensors = [] + for core_idx, inputs_per_core in enumerate(inputs): + for idx, input_tensor in enumerate(inputs_per_core): + input_shape = input_tensor.get_shape().as_list() + if core_idx == 0: + input_shape_tensors.append([]) + maximum_static_shapes.append(input_shape) + need_padding.append(np.full_like(input_shape, False, dtype=bool)) + else: + for i, s in enumerate(input_shape): + if s is None or s != maximum_static_shapes[idx][i]: + need_padding[idx][i] = True + maximum_static_shapes[idx] = max(input_shape, + maximum_static_shapes[idx]) + + # Append _POST_DEVICE_REWRITE_ATTR attributes to the real shape ops. + real_input_shape = array_ops.shape(input_tensor) + real_input_shape.op._set_attr( # pylint: disable=protected-access + _POST_DEVICE_REWRITE_ATTR, + attr_value_pb2.AttrValue(b=True)) + input_shape_tensors[idx].append(real_input_shape) + + maximum_shapes = [] + for shapes_per_input in input_shape_tensors: + maximum_shapes.append( + math_ops.reduce_max(array_ops_stack.stack(shapes_per_input), axis=0)) + + padded_inputs = [] + real_shapes = [] + padding_maps = [] + for core_idx, inputs_per_core in enumerate(inputs): + padded_inputs.append([]) + real_shapes.append([]) + real_shape_idx = len(inputs_per_core) - 1 + for idx, input_tensor in enumerate(inputs_per_core): + input_shape_tensor = input_shape_tensors[idx][core_idx] + input_shape = input_tensor.get_shape().as_list() + padded_shape = padded_shapes[idx] + + # If we have no padded_shape, then skip padding. + if any(need_padding[idx]) and padded_shape is not None: + for i, s in enumerate(input_shape): + if need_padding[idx][i]: + if core_idx == 0: + real_shape_idx += 1 + padding_map = dynamic_padding.PaddingMap() + padding_map.arg_index = idx + padding_map.shape_index = i + padding_map.padding_arg_index = real_shape_idx + padding_maps.append(padding_map) + real_shapes[core_idx].append( + math_ops.cast(input_shape_tensor[i], dtypes.int32)) + + paddings = [] + for i, s in enumerate(padded_shape.dims): + if need_padding[idx][i]: + # The minimum padded dimension size is 2 as XLA doesn't support size + # 1 dynamic size. + minimum_dynamic_dim_size = 2 + if s.value is not None: + # Pad to the given maximum value. + max_dim_size = max(s.value, minimum_dynamic_dim_size) + else: + # If maximum value is not given, then pad to the maximum dimension + # among all the cores. + max_dim_size = math_ops.maximum(maximum_shapes[idx][i], + minimum_dynamic_dim_size) + if padding_spec == PaddingSpec.POWER_OF_TWO: + max_dim_size = _ceil_to_pow_of_n(max_dim_size, 2) + # Pad to the given maximum value. + padding = [0, max_dim_size - input_shape_tensor[i]] + else: + padding = [0, 0] + paddings.append(padding) + + if input_tensor.get_shape().is_fully_defined(): + # TODO(rxsang): This is a hack to make sure padded_input has dynamic + # shapes, so any tf.size/tf.shape op performed on it won't be constant + # folded. Do we have better ways to do it? + padded_input = cond.cond( + array_ops.constant(True), + lambda: array_ops.pad(input_tensor, paddings), # pylint: disable=cell-var-from-loop + lambda: input_tensor) + else: + padded_input = array_ops.pad(input_tensor, paddings) + + # Append _POST_DEVICE_REWRITE_ATTR attributes to all padded inputs. + padded_input.op._set_attr( # pylint: disable=protected-access + _POST_DEVICE_REWRITE_ATTR, + attr_value_pb2.AttrValue(b=True)) + + padded_inputs[core_idx].append(padded_input) + else: + padded_inputs[core_idx].append(input_tensor) + + num_replicas = len(padded_inputs) + for i in range(num_replicas): + padded_inputs[i].extend(real_shapes[i]) + + return padded_inputs, padding_maps + + +def _flatten_and_filter_composite(maybe_composite, non_composite_output, + composite_output=None): + """For an input, replaced the input by a tuple if the input is composite. + + If `maybe_composite` is not composite, return the parameter + `non_composite_output` otherwise return a tuple which consists of the value of + the parameter `composite_output` the same number of times as there are + components of the composite tensor. + + This is useful for computing a mask when flattening nested data with + `expand_composites=True`. For example + + ```python + nest.flatten(data, expand_composites=True) + ``` + + and + + ```python + nest.flatten(nest.map( + data, lambda x: _flatten_and_filter_composite(x, False, True))) + ``` + + will have the same length and second will be True if the tensor in the first + is derived from a expanding a composite tensor. + + Args: + maybe_composite: A value to test for being a composite tensor. + non_composite_output: The value to return when `maybe_composite` is not a + composite. + composite_output: the value to fill the output tuple with if + `maybe_composite` is a composite. + + Returns: + `non_composite_output` or a tuple with multiple copies of + `composite_output`. + """ + + if isinstance(maybe_composite, composite_tensor.CompositeTensor): + num_components = len(nest.flatten(maybe_composite, expand_composites=True)) + return (composite_output,) * num_components + return non_composite_output + + +def split_compile_and_replicate( + computation: Callable[..., Any], + inputs: Optional[List[List[core_types.Tensor]]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + use_tpu: bool = True, + maximum_shapes: Optional[Any] = None, + padding_spec: Optional[PaddingSpec] = None, + xla_options: Optional[XLAOptions] = None, +) -> List[List[core_types.Tensor]]: + """Builds graph operators that runs compilation and replicated computation. + + This is a lower level interface than replicate that returns a separate compile + and execute output tensor. In the generated graph the compile op feeds into + the execute op and no additional compilation is incurred when running the + compile op before the execute op. The compile op returns additional + information about the compilation but does not return the compiled program. + + Args: + computation: A Python function that builds the computation to replicate. + inputs: A list of lists of input tensors or `None` (equivalent to + `[[]]`), indexed by `[replica_num][input_num]`. All replicas must + have the same number of inputs. Each input can be a nested structure + containing values that are convertible to tensors. Note that passing an + N-dimension list of compatible values will result in a N-dimension list of + scalar tensors rather than a single Rank-N tensors. If you need different + behavior, convert part of inputs to tensors with `tf.convert_to_tensor`. + infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple + of arguments as inputs to computation. + device_assignment: If not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. Uses a default device assignment if `None`. The + `DeviceAssignment` may be omitted if each replica of the computation uses + only one core, and there is either only one replica, or the number of + replicas is equal to the number of cores in the TPU system. + name: (Deprecated) Does nothing. + use_tpu: When false, the input `computation` is executed on the XLA CPU/GPU + backends. Currently, only supports a default placement (computation is + placed on GPU if one is available, and on CPU if not). + maximum_shapes: A nested structure of tf.TensorShape representing the shape + to which the respective component of each input element in each replica + should be padded. Any unknown dimensions (e.g. + tf.compat.v1.Dimension(None) in a tf.TensorShape or -1 in a tensor-like + object) will be padded to the maximum size of that dimension over all + replicas. The structure of `maximum_shapes` needs to be the same as + `inputs[0]`. + padding_spec: An enum specified by `tf.tpu.PaddingSpec`. This describes the + padding policy when the `inputs` to `tf.tpu.replicate` is dynamic. + One usage is to enable automatic bucketizing on the inputs by setting the + value to `tpu.PaddingSpec.POWER_OF_TWO`, which can help to reduce the + recompilation in the XLA side. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + + Returns: + A list of lists with the first list corresponding to the compile op and the + second a list of output tensors, indexed by `[replica_num][output_num]`. + Raises: + ValueError: If all replicas do not have equal numbers of input tensors. + ValueError: If the number of inputs per replica does not match + the number of formal parameters to `computation`. + ValueError: If the static `inputs` dimensions don't match with the values + given in `maximum_shapes`. + ValueError: If the structure of inputs per replica does not match + the structure of `maximum_shapes`. + """ + del name + inputs = [[]] if inputs is None else inputs + xla_options = xla_options or XLAOptions() + + metadata_kwargs = {} + if device_assignment is not None: + # Turn the Numpy array into a flattened list so we can pass it as an + # operator attribute. + metadata_kwargs = { + "topology": + device_assignment.topology.serialized(), + "device_assignment": + device_assignment.core_assignment.flatten().tolist() + } + metadata_kwargs["num_cores_per_replica"] = ( + device_assignment.num_cores_per_replica) + + # This entry is used for enabling automatic outside compilation. + metadata_kwargs["allow_soft_placement"] = config.get_soft_device_placement() + if config.get_soft_device_placement(): + logging.info("Automatic outside compilation is enabled. " + "Ops without XLA kernels will be automatically " + "placed on CPU.") + + if not isinstance(inputs, list): + raise TypeError("tpu.replicate() inputs must be a list of lists/tuples, " + f"received {type(inputs)}") + if any(not isinstance(inp, (list, tuple)) for inp in inputs): + raise TypeError( + "tpu.replicate() inputs must be a list of lists/tuples, " + f"received types: {[type(inp) for inp in inputs]}") + + num_replicas = len(inputs) + + # No replicas? Nothing to do. + if num_replicas == 0: + return [] + + # Checks all replicas have the same structure. + for i in range(1, num_replicas): + nest.assert_same_structure(inputs[0], inputs[i]) + + # Explicitly read variables. + inputs = variable_utils.convert_variables_to_tensors(inputs) + # Flatten inputs. This structure may contain None values, which will be + # handled later. + flat_inputs_with_nones = [ + nest.flatten(per_replica_input, expand_composites=True) + for per_replica_input in inputs + ] + # Mask parallel to one replica's inputs with True for tensors coming from + # composites. + is_composite = nest.flatten(nest.map_structure( + lambda x: _flatten_and_filter_composite(x, False, True), inputs[0])) + + # Converts inputs to Tensors, replacing Nones with a placeholder 0 since + # tpu_ops.tpu_replicated_input() can't handle non-Tensor values. + flat_inputs = [] + for inp in flat_inputs_with_nones: + flat_inputs.append([ + constant_op.constant(0) if x is None else ops.convert_to_tensor(x) + for x in inp + ]) + + # Verifies that all replicas have matching numbers and types of inputs + flat_input_types = [x.dtype for x in flat_inputs[0]] + input_arity = len(inputs[0]) + flat_input_arity = len(flat_input_types) + for i in range(num_replicas): + if len(inputs[i]) != input_arity: + raise ValueError("Replicas must have the same number of inputs. " + "Replica 0 had {} inputs, replica {} had {} " + "inputs.".format(input_arity, i, len(inputs[i]))) + + types = [x.dtype for x in flat_inputs[i]] + if types != flat_input_types: + raise ValueError("Replicas must have matching input types. Replica 0 had " + "input types {}, replica {} had input types {}".format( + flat_input_types, i, types)) + + arg_error = xla.check_function_argument_count( + computation, input_arity, infeed_queue) + if arg_error is not None: + if infeed_queue is None: + raise TypeError( + "Supplied computation cannot be called with the specified inputs. " + f"You specified {input_arity} inputs: {[i.name for i in inputs[0]]}, " + f"but the computation needs {arg_error}") + else: + raise TypeError( + "Supplied computation cannot be called with the specified inputs. " + f"You specified {input_arity} inputs: {[i.name for i in inputs[0]]} ", + f"and {infeed_queue.number_of_tuple_elements} additional inputs " + f"from infeed, but the computation needs {arg_error}") + + dynamic_shape_inputs = False + if maximum_shapes: + if infeed_queue: + raise ValueError( + "Dynamic input shapes are not supported with infeed queues") + + # Make sure maximum_shapes has the same structure as inputs. + nest.assert_same_structure(inputs[0], maximum_shapes, check_types=False) + + # Flatten padded shapes: + # For composite tensor components, we don't want to pad them. For each + # entry of maximum_shapes that corresponds to a composite tensor, replace it + # by a tuple of Nones of the same length as the number of components of the + # composite tensor. When we flatten a second time, this makes + # flat_maximum_shapes have the same length as flat_inputs[i]. We can then + # avoid padding these tensors. The assumption is that they will be used by + # outside compilation or that the components are statically shaped and will + # be used by tpu compatible ops. + flat_maximum_shapes = nest.flatten( + [_flatten_and_filter_composite(x, y) + for x, y in zip(nest.flatten(inputs[0]), + nest.flatten(maximum_shapes))]) + flat_maximum_shapes = [ + tensor_shape.TensorShape(s) if s is not None else None + for s in flat_maximum_shapes + ] + nest.assert_same_structure(flat_inputs[0], flat_maximum_shapes, + check_types=False) + + unpadded_inputs = flat_inputs + flat_inputs, padding_maps = _pad_all_input(unpadded_inputs, + flat_maximum_shapes, + padding_spec) + if padding_maps: + dynamic_shape_inputs = True + logging.info("TPU has inputs with dynamic shapes: %s", inputs[0]) + + metadata_kwargs["step_marker_location"] = getattr( + computation, "step_marker_location", "STEP_MARK_AT_ENTRY") + metadata_kwargs["use_spmd_for_xla_partitioning"] = \ + xla_options.use_spmd_for_xla_partitioning + + graph = ops.get_default_graph() + + # Fan-in: Builds a TPUReplicatedInput node for each input. + flat_replicated_inputs = [] + for i in range(0, len(flat_inputs[0])): + replicas = [flat_inputs[replica][i] for replica in range(num_replicas)] + flat_replicated_inputs.append( + tpu_ops.tpu_replicated_input( + replicas, name="input{}".format(i))) + if isinstance(graph, func_graph.FuncGraph): + # When we are in Tensorflow 2.0 function, 'graph' will be a FuncGraph + # object. If both outside graph and this function have a TPU cluster, + # they will have the same cluster name and it will cause problems (because + # we lower functional ops in Tensorflow 2.0). Append function name to + # 'cluster_name' to avoid cluster name collision. + cluster_name = graph.unique_name("cluster_" + graph.name) + else: + cluster_name = graph.unique_name("cluster") + pivot = control_flow_ops.no_op(name=cluster_name + "/pivot") + pivot._set_attr(_PIVOT_FOR_CLUSTER, # pylint: disable=protected-access + attr_value_pb2.AttrValue(s=compat.as_bytes(cluster_name))) + context = tpu_replication.TPUReplicateContext( + name=cluster_name, num_replicas=num_replicas, pivot=pivot) + try: + context.Enter() + + metadata = tpu_ops.tpu_replicate_metadata( + num_replicas=num_replicas, use_tpu=use_tpu, **metadata_kwargs) + + with tpu_function.tpu_shard_context( + num_replicas), ops.control_dependencies([metadata]): + + if dynamic_shape_inputs and xla_options.enable_xla_dynamic_padder: + for padding_map in padding_maps: + input_shape = flat_replicated_inputs[padding_map.arg_index].shape + flat_replicated_inputs[ + padding_map.arg_index] = tf2xla.set_dynamic_dimension_size( + flat_replicated_inputs[padding_map.arg_index], + padding_map.shape_index, + flat_replicated_inputs[padding_map.padding_arg_index]) + flat_replicated_inputs[padding_map.arg_index].set_shape(input_shape) + + # Add identity ops so even unused inputs are "consumed" by the + # computation. This is to avoid orphaned TPUReplicatedInput nodes. + # TODO(phawkins): consider instead pruning unused TPUReplicatedInput + # and eliding trivial TPUReplicatedInput/TPUReplicatedOutput pairs. + flat_replicated_inputs = [ + array_ops.identity(x, name="replicated_input_{}".format(i)) + for i, x in enumerate(flat_replicated_inputs) + ] + for i, composite in zip(flat_replicated_inputs, is_composite): + # pylint: disable=protected-access + # Add an attribute to the identity node so that they could be removed in + # encapsulate TPU computation pass if unused. However we don't remove + # inputs when dynamic padding is enabled. + # TODO(rxsang): Use other ways except argument index in padding_map so + # outside compilation can work with dynamic padding correctly. + if not dynamic_shape_inputs or composite: + i.op._set_attr("_tpu_input_identity", + attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + + # Clobber replicated placeholders with Nones. + computation_inputs = [ + None if inp is None else replicated for replicated, inp in zip( + flat_replicated_inputs, flat_inputs_with_nones[0]) + ] + + # Unflatten the computation inputs to match original input structure. + computation_inputs = nest.pack_sequence_as( + structure=inputs[0], + flat_sequence=computation_inputs[:flat_input_arity], + expand_composites=True) + + # If there is an infeed queue, adds the dequeued values to the + # computation's inputs. + if infeed_queue is not None: + infeed_queue.set_number_of_shards(num_replicas) + for t in infeed_queue.generate_dequeue_op(): + computation_inputs.append(t) + + # Only resource variables work inside a TPU computation, so turn on + # resource variables for the computation. + # TODO(phawkins): consider removing this code. It will + # be less confusing to clients if they knowingly choose to use resource + # variables. + # Partitioned variables is not supported (b/112311320). + vscope = variable_scope.get_variable_scope() + saved_use_resource = vscope.use_resource + saved_custom_getter = vscope.custom_getter + + def custom_getter(getter, name, *args, **kwargs): + """Variables on TPU have a few restrictions.""" + partitioner = kwargs.get("partitioner", None) + if partitioner is not None: + kwargs["partitioner"] = None + logging.warning( + "Partitioned variables are not supported on TPU. Got " + "`partitioner` that is %s for variable %s. " + "Setting `partitioner` to `None`.", partitioner, name) + if saved_custom_getter is None: + return getter(name, *args, **kwargs) + else: + return saved_custom_getter(getter, name, *args, **kwargs) + + vscope.set_use_resource(True) + vscope.set_custom_getter(custom_getter) + + outputs = computation(*computation_inputs) + + vscope.set_use_resource(saved_use_resource) + vscope.set_custom_getter(saved_custom_getter) + + outputs = variable_utils.convert_variables_to_tensors(outputs) + + need_spmd_partitioning = ( + xla_options.use_spmd_for_xla_partitioning and + device_assignment is not None and + device_assignment.num_cores_per_replica > 1) + outputs_is_flat = xla.is_flat(outputs) + if outputs_is_flat: + output_tensors, control_deps, pack_template = _postprocess_flat_outputs( + outputs, need_spmd_partitioning) + else: + output_tensors, control_deps, pack_template = ( + _postprocess_non_flat_outputs(outputs, need_spmd_partitioning)) + + if tensor_tracer.TensorTracer.is_enabled(): + if tf2.enabled(): + logging.warn("TF API ver >= 2.0 detected. " + "Tensor Tracer v1 is not enabled.") + else: + tt = tensor_tracer.TensorTracer() + output_tensors = tt.trace_tpu(ops.get_default_graph(), + output_tensors, control_deps, + num_replicas) + + context.ExitResult(output_tensors) + finally: + context.report_unsupported_operations() + context.Exit() + host_compute_core = context.HostComputeCore() + + if host_compute_core: + attr_value = attr_value_pb2.AttrValue() + attr_value.list.s.extend(compat.as_bytes(x) for x in host_compute_core) + metadata._set_attr("host_compute_core", attr_value) # pylint: disable=protected-access + + with ops.control_dependencies([metadata]): + if use_tpu: + compile_status = tpu_ops.tpu_compilation_result() + op = compile_status.op + attr_value = attr_value_pb2.AttrValue(s=compat.as_bytes(cluster_name)) + op._set_attr(_TPU_COMPILATION_STATUS_ATTR, attr_value) # pylint: disable=protected-access + else: + compile_status = control_flow_ops.no_op(name="compilation_status") + + if not output_tensors: + # Returns a list of NoOps dependent on the replication Op, indexed by + # [replica_num]. + return [ + compile_status, + [ + control_flow_ops.group(control_deps, name="shard_%d" % i) + for i in range(num_replicas) + ] + ] + + # Fan-out: Builds a TPUReplicatedOutput node for each output. + replicated_outputs = [[] for i in range(num_replicas)] + for i, t in enumerate(output_tensors): + + # None values returned by the computation can't be sent to + # tpu_ops.tpu_replicated_output(), we handle them specially here. We can + # avoid the placeholder 0 routine required on the inputs since outputs are + # replicated per-tensor, not per-replica, so we can skip replication. + if t is None: + for replica in range(num_replicas): + replicated_outputs[replica].append(None) + continue + + # Fan-out: Builds a TPUReplicatedOutput node for each output. + ys = tpu_ops.tpu_replicated_output( + t, num_replicas, name="output{}".format(i)) + + # Wraps the outputs in identity operators so the names of any possible + # `fetch` nodes are preserved by the replication rewrite. + with ops.control_dependencies(control_deps): + for replica in range(num_replicas): + replicated_outputs[replica].append( + array_ops.identity( + ys[replica], name="output_%d_shard_%d" % (i, replica))) + + replicated_outputs = [ + nest.pack_sequence_as(pack_template, replica_outs, expand_composites=True) + for replica_outs in replicated_outputs + ] + + return [compile_status, replicated_outputs] + + +def _postprocess_flat_outputs( + outputs: Any, + need_spmd_partitioning: bool +) -> Tuple[List[Optional[core_types.Tensor]], List[ops.Operation], List[Any]]: + """Validates non-flat outputs, add backs device assignments and other attrs. + + Args: + outputs: Output from `computation` inside `tpu.rewrite`. + need_spmd_partitioning: Whether XLA SPMD partitioning is needed. + + Returns: + - Tensors extracted from outputs. + - Operations extracted from outputs. + - A pack template for use with nest.pack_sequence_as to pack the tensors. + """ + # Following code segment is to preserve legacy behavior. Previously we only + # supported flat outputs and thus for consistency it was nice to convert even + # single element into a tuple. But now that we support arbitrary output + # structure, this is no longer necessary. + # TODO(b/121383831): Migrate all legacy use cases and delete this special + # case. + # If the computation returns `None`, make it an empty tuple. + if outputs is None: + outputs = tuple() + + # For legacy / backwards compatibility reasons we return a list for "flat" + # output values (even if the user's flat return value was a different type or + # even just a scalar value) so use nest.flatten to compute a flat list pack + # template. + pack_template = nest.flatten(outputs, expand_composites=False) + + # Even though outputs is already "flat", we flatten any composites so their + # component tensors can be tagged and replicated. The pack_template will be + # used by the caller to repack the composite tensors. + outputs = nest.flatten(outputs, expand_composites=True) + + # Append `no_op` here so that fetching any return value of this function + # will trigger TPUExecute node. + outputs += (control_flow_ops.no_op(),) + + maybe_convert = lambda x: None if x is None else ops.convert_to_tensor(x) + try: + if need_spmd_partitioning: + outputs = [ + o if isinstance(o, ops.Operation) else maybe_convert(o) + for o in outputs + ] + else: + with ops.device(core(0)): + outputs = [ + o if isinstance(o, ops.Operation) else maybe_convert(o) + for o in outputs + ] + except Exception as e: + raise ValueError( + "TPU function return values must all either be Operations or " + f"convertible to Tensors. Got error: {e}") + + # Separates the returned Operations and Tensors. + output_operations = [o for o in outputs if isinstance(o, ops.Operation)] + output_tensors = [o for o in outputs if not isinstance(o, ops.Operation)] + + if outputs != output_tensors + output_operations: + raise ValueError( + "TPU functions must return zero-or more Tensor values followed by " + "zero or more Operations.") + + # Trim operations off the end of the pack template. output_operations has 1 + # extra element due to the no-op that is added. + if len(output_operations) > 1: + pack_template = pack_template[:1 - len(output_operations)] + + # Wraps outputs in Identity ops. Otherwise a replicated input copied + # straight to an output would bypass the replicate(). This would be bad + # because the TPUReplicatedInput/TPUReplicatedOutput operator would not + # be rewritten away, leading to a runtime error. + # TODO(phawkins): extend the rewrite to elide these nodes instead. + new_output_tensors = [] + for t in output_tensors: + if t is None: + new_output_tensors.append(None) + elif need_spmd_partitioning: + o = array_ops.identity(t) + # pylint: disable=protected-access + o.op._set_attr("_tpu_output_identity", attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + new_output_tensors.append(o) + else: + with ops.device(t.device if t.device else core(0)): + o = array_ops.identity(t) + # pylint: disable=protected-access + o.op._set_attr("_tpu_output_identity", attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + new_output_tensors.append(o) + return new_output_tensors, output_operations, pack_template + + +def _postprocess_non_flat_outputs( + outputs: Any, + need_spmd_partitioning: bool +) -> Tuple[List[Optional[core_types.Tensor]], List[ops.Operation], List[Any]]: + """Validates non-flat outputs, add backs device assignments and other attrs. + + Args: + outputs: Output from `computation` inside `tpu.rewrite`. + need_spmd_partitioning: Whether XLA SPMD partitioning is needed. + + Returns: + - Tensors extracted from outputs. + - An empty Operations list because Operations are not allowed in non-flat + outputs. + - A pack template for use with nest.pack_sequence_as to pack the tensors. + """ + + # Flatten output items. + flat_outputs = nest.flatten(outputs, expand_composites=True) + + # Convert all non-None non-Operation outputs to Tensors. + for i, o in enumerate(flat_outputs): + if o is None: + flat_outputs[i] = None + continue + + if isinstance(o, ops.Operation): + raise ValueError( + "tpu.rewrite does not support Operation as return value in non-flat " + "output structure. You can set returned Operations as control " + "dependencies of returned Tensors so Operations are triggered when " + f'Tensors are evaluated. Operation found: "{o.name}"') + + try: + o = ops.convert_to_tensor(o) + except Exception as e: + raise ValueError( + "TPU function return values must all either be Operations or " + f'convertible to Tensors. Got error: "{e}"') + + # Wraps outputs in Identity ops. Otherwise a replicated input copied + # straight to an output would bypass the replicate(). This would be bad + # because the TPUReplicatedInput/TPUReplicatedOutput operator would not + # be rewritten away, leading to a runtime error. + # TODO(phawkins): extend the rewrite to elide these nodes instead. + if need_spmd_partitioning: + o = array_ops.identity(o) + # pylint: disable=protected-access + o.op._set_attr("_tpu_output_identity", attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + flat_outputs[i] = array_ops.identity(o) + else: + with ops.device(o.device if o.device else core(0)): + o = array_ops.identity(o) + # pylint: disable=protected-access + o.op._set_attr("_tpu_output_identity", attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + flat_outputs[i] = array_ops.identity(o) + + # All flat_outputs are Tensors, and no Operations. + return flat_outputs, [], outputs + + +def split_compile_and_shard( + computation: Callable[..., Any], + inputs: Optional[List[List[Optional[core_types.Tensor]]]] = None, + num_shards: int = 1, + input_shard_axes: Optional[List[int]] = None, + outputs_from_all_shards: Union[bool, List[bool]] = True, + output_shard_axes: Optional[List[int]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + xla_options: Optional[XLAOptions] = None, + ) -> Tuple[ops.Operation, List[core_types.Tensor]]: + """Shards `computation` for parallel execution. + + `inputs` must be a list of Tensors or None (equivalent to an empty list), each + of which has a corresponding split axis (from `input_shard_axes`). Each input + is split into `num_shards` pieces along the corresponding axis, and + computation is applied to each shard in parallel. + + Tensors are broadcast to all shards if they are lexically captured by + `computation`. e.g., + + x = tf.constant(7) + def computation(): + return x + 3 + ... = shard(computation, ...) + + If `outputs_from_all_shards` is true, the outputs from all shards of + `computation` are concatenated back together along their `output_shard_axes`. + Otherwise, each output is taken from an arbitrary shard. + + Inputs and outputs of the computation must be at least rank-1 Tensors. + + Args: + computation: A Python function that builds a computation to apply to each + shard of the input. + inputs: A list of input tensors or None (equivalent to an empty list). Each + input tensor has a corresponding shard axes, given by `input_shard_axes`, + which must have size divisible by `num_shards`. + num_shards: The number of shards. + input_shard_axes: A list of dimensions along which to shard `inputs`, or + `None`. `None` means "shard all inputs along dimension 0". If not `None`, + there must be one dimension per input. + outputs_from_all_shards: Boolean or list of boolean. For each output, if + `True`, outputs from all shards are concatenated along the corresponding + `output_shard_axes` entry. Otherwise, each output is taken + from an arbitrary shard. If the argument is a boolean, the argument's + value is used for each output. + output_shard_axes: A list of dimensions along which to concatenate the + outputs of `computation`, or `None`. `None` means "concatenate all outputs + along dimension 0". If not `None`, there must be one dimension per output. + Ignored if `outputs_from_all_shards` is False. + infeed_queue: If not `None`, the `InfeedQueue` to use to augment the inputs + of `computation`. + device_assignment: If not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. Uses a default device assignment if `None`. The + `DeviceAssignment` may be omitted if each shard of the computation uses + only one core, and there is either only one shard, or the number of shards + is equal to the number of cores in the TPU system. + name: (Deprecated) Does nothing. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + Returns: + A tuple of (compile op, [output tensors]). + Raises: + ValueError: If num_shards <= 0 + ValueError: If len(input_shard_axes) != len(inputs) + ValueError: If len(output_shard_axes) != len(outputs from `computation`) + """ + # TODO(phawkins): consider adding support for broadcasting Tensors passed as + # inputs. + + if num_shards <= 0: + raise ValueError( + f"num_shards must be a positive integer. Received {num_shards}") + + inputs = [] if inputs is None else inputs + if not isinstance(inputs, list): + raise TypeError("tpu.shard()'s inputs must be a list of Tensors or None. " + f"Received {type(inputs)}") + + # Converts inputs to Tensors. + inputs = [ops.convert_to_tensor(x) for x in inputs] + + if input_shard_axes is None: + input_shard_axes = [0] * len(inputs) + if len(inputs) != len(input_shard_axes): + raise ValueError("Length of input_shard_axes must be equal to the number " + f"of inputs. Received {len(inputs)} inputs and " + f"{len(input_shard_axes)} input_shard_axes.") + + if inputs: + # Splits the `inputs` along the corresponding `input_shard_axes`, giving + # lists with layout [input][shard] + split_inputs = [ + array_ops.split(x, num_shards, axis=axis) + for (axis, x) in zip(input_shard_axes, inputs)] + + # Transposes the input lists to have layout [shard][input] + transposed_inputs = [list(i) for i in zip(*split_inputs)] + else: + transposed_inputs = [[]] * num_shards + + compile_op, outputs = split_compile_and_replicate( + computation, + transposed_inputs, + infeed_queue=infeed_queue, + device_assignment=device_assignment, + name=name, + xla_options=xla_options) + + # There must be at least one shard since num_shards > 0. + # TODO(b/36647078) remove disable when pylint bug is fixed. + # pylint: disable=indexing-exception + if isinstance(outputs[0], ops.Operation): + # pylint: enable=indexing-exception + # There were no outputs from the computation and replicate returned a list + # of NoOps with control dependencies on the computation. Return the first + # one so it can be used as a control dependency or fetch node. + # TODO(b/36647078) remove disable when pylint bug is fixed. + # pylint: disable=indexing-exception + return compile_op, [outputs[0]] + # pylint: enable=indexing-exception + + # TODO(b/36647078) remove disable when pylint bug is fixed. + # pylint: disable=indexing-exception + num_outputs = len(outputs[0]) + # pylint: enable=indexing-exception + + if output_shard_axes is None: + output_shard_axes = [0] * num_outputs + if num_outputs != len(output_shard_axes): + raise ValueError("Length of output_shard_axes must be equal to the number " + f"of outputs. Received {num_outputs} outputs " + f"and {len(output_shard_axes)} output_shard_axes.") + + if isinstance(outputs_from_all_shards, bool): + outputs_from_all_shards = [outputs_from_all_shards] * num_outputs + + if num_outputs != len(outputs_from_all_shards): + raise ValueError( + "Length of outputs_from_all_shards must be equal to the number of " + f"outputs. Received {num_outputs} outputs and " + f"{len(outputs_from_all_shards)} outputs_from_all_shards.") + + results = [] + for (axis, all_shards, x) in zip(output_shard_axes, outputs_from_all_shards, + zip(*outputs)): + if all_shards: + # Concatenate all of the outputs together (use stack for scalars). + shape = x[0].shape + is_scalar = shape is not None and (shape.ndims == 0) + results.append((array_ops_stack.stack(list(x)) if is_scalar + else array_ops.concat(list(x), axis=axis))) + else: + # TODO(phawkins): use a smarter policy, e.g., round-robin across shards. + results.append(x[0]) + + return compile_op, results + + +@tf_export(v1=["tpu.shard"]) +@traceback_utils.filter_traceback +def shard( + computation: Callable[..., Any], + inputs: Optional[List[core_types.Tensor]] = None, + num_shards: int = 1, + input_shard_axes: Optional[List[int]] = None, + outputs_from_all_shards: Union[bool, List[bool]] = True, + output_shard_axes: Optional[List[int]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + xla_options: Optional[XLAOptions] = None) -> List[core_types.Tensor]: + """Shards `computation` for parallel execution. + + `inputs` must be a list of Tensors or None (equivalent to an empty list), each + of which has a corresponding split axis (from `input_shard_axes`). Each input + is split into `num_shards` pieces along the corresponding axis, and + computation is applied to each shard in parallel. + + Tensors are broadcast to all shards if they are lexically captured by + `computation`. e.g., + + x = tf.constant(7) + def computation(): + return x + 3 + ... = shard(computation, ...) + + TODO(phawkins): consider adding support for broadcasting Tensors passed + as inputs. + + If `outputs_from_all_shards` is true, the outputs from all shards of + `computation` are concatenated back together along their `output_shard_axes`. + Otherwise, each output is taken from an arbitrary shard. + + Inputs and outputs of the computation must be at least rank-1 Tensors. + + Args: + computation: A Python function that builds a computation to apply to each + shard of the input. + inputs: A list of input tensors or None (equivalent to an empty list). Each + input tensor has a corresponding shard axes, given by `input_shard_axes`, + which must have size divisible by `num_shards`. + num_shards: The number of shards. + input_shard_axes: A list of dimensions along which to shard `inputs`, or + `None`. `None` means "shard all inputs along dimension 0". If not `None`, + there must be one dimension per input. + outputs_from_all_shards: Boolean or list of boolean. For each output, if + `True`, outputs from all shards are concatenated along the corresponding + `output_shard_axes` entry. Otherwise, each output is taken + from an arbitrary shard. If the argument is a boolean, the argument's + value is used for each output. + output_shard_axes: A list of dimensions along which to concatenate the + outputs of `computation`, or `None`. `None` means "concatenate all outputs + along dimension 0". If not `None`, there must be one dimension per output. + Ignored if `outputs_from_all_shards` is False. + infeed_queue: If not `None`, the `InfeedQueue` to use to augment the inputs + of `computation`. + device_assignment: If not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. Uses a default device assignment if `None`. The + `DeviceAssignment` may be omitted if each shard of the computation uses + only one core, and there is either only one shard, or the number of shards + is equal to the number of cores in the TPU system. + name: (Deprecated) Does nothing. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + Returns: + A list of output tensors. + Raises: + ValueError: If num_shards <= 0 + ValueError: If len(input_shard_axes) != len(inputs) + ValueError: If len(output_shard_axes) != len(outputs from `computation`) + """ + return split_compile_and_shard( + computation, + inputs=inputs, + num_shards=num_shards, + input_shard_axes=input_shard_axes, + outputs_from_all_shards=outputs_from_all_shards, + output_shard_axes=output_shard_axes, + infeed_queue=infeed_queue, + device_assignment=device_assignment, + name=name, + xla_options=xla_options)[1] + + +@tf_export(v1=["tpu.batch_parallel"]) +@traceback_utils.filter_traceback +def batch_parallel( + computation: Callable[..., Any], + inputs: Optional[List[List[Optional[core_types.Tensor]]]] = None, + num_shards: int = 1, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + xla_options: Optional[XLAOptions] = None): + """Shards `computation` along the batch dimension for parallel execution. + + Convenience wrapper around shard(). + + `inputs` must be a list of Tensors or None (equivalent to an empty list). + Each input is split into `num_shards` pieces along the 0-th dimension, and + computation is applied to each shard in parallel. + + Tensors are broadcast to all shards if they are lexically captured by + `computation`. e.g., + + x = tf.constant(7) + def computation(): + return x + 3 + ... = shard(computation, ...) + + The outputs from all shards are concatenated back together along their 0-th + dimension. + + Inputs and outputs of the computation must be at least rank-1 Tensors. + + Args: + computation: A Python function that builds a computation to apply to each + shard of the input. + inputs: A list of input tensors or None (equivalent to an empty list). The + 0-th dimension of each Tensor must have size divisible by `num_shards`. + num_shards: The number of shards. + infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple + of arguments as inputs to `computation`. + device_assignment: If not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. Uses a default device assignment if `None`. The + `DeviceAssignment` may be omitted if each shard of the computation uses + only one core, and there is either only one shard, or the number of shards + is equal to the number of cores in the TPU system. + name: (Deprecated) Does nothing. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + Returns: + A list of output tensors. + Raises: + ValueError: If `num_shards <= 0` + """ + return shard( + computation, + inputs, + num_shards=num_shards, + infeed_queue=infeed_queue, + device_assignment=device_assignment, + name=name, + xla_options=xla_options) + + +@tf_export(v1=["tpu.rewrite"]) +@traceback_utils.filter_traceback +def rewrite( + computation: Callable[..., Any], + inputs: Optional[List[List[Optional[core_types.Tensor]]]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None, + xla_options: Optional[XLAOptions] = None) -> Any: + """Rewrites `computation` for execution on a TPU system. + + Args: + computation: A Python function that builds a computation to apply to the + input. If the function takes n inputs, 'inputs' should be a list of n + tensors. + + `computation` may return a list of operations and tensors. Tensors must + come before operations in the returned list. The return value of + `rewrite` is a list of tensors corresponding to the tensors from the + output of `computation`. + + All `Operation`s constructed during `computation` will be executed when + evaluating any of the returned output tensors, not just the ones returned. + inputs: A list of input tensors or `None` (equivalent to an empty list). + Each input can be a nested structure containing values that are + convertible to tensors. Note that passing an N-dimension list of + compatible values will result in a N-dimension list of scalar tensors + rather than a single Rank-N tensors. If you need different behavior, + convert part of inputs to tensors with `tf.convert_to_tensor`. + infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple + of arguments as inputs to `computation`. + device_assignment: if not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. May be omitted for a single-core computation, in which + case the core attached to task 0, TPU device 0 is used. + name: (Deprecated) Does nothing. + xla_options: An instance of `tpu.XLAOptions` which indicates the options + passed to XLA compiler. Use `None` for default options. + Returns: + Same data structure as if computation(*inputs) is called directly with some + exceptions for correctness. Exceptions include: + 1) None output: a NoOp would be returned which control-depends on + computation. + 2) Single value output: A tuple containing the value would be returned. + 3) Operation-only outputs: a NoOp would be returned which + control-depends on computation. + TODO(b/121383831): Investigate into removing these special cases. + """ + # TODO(b/36647078) remove disable when pylint bug is fixed. + # pylint: disable=indexing-exception + return replicate( + computation, + None if inputs is None else [inputs], + infeed_queue=infeed_queue, + device_assignment=device_assignment, + name=name, + xla_options=xla_options)[0] + # pylint: enable=indexing-exception + + # Operations that indicate some error in the user's inference graph. + + +_DENYLISTED_INFERENCE_OPS = set([ + "ReadVariableOp", + "AssignVariableOp", + "AssignAddVariableOp", + "AssignSubVariableOp", + "VarHandleOp", + "Variable", + "VariableV2", +]) + + +def under_tpu_inference_context() -> bool: + """Check if it is currently under `_TPUInferenceContext`.""" + graph = ops.get_default_graph() + while graph: + context = graph._get_control_flow_context() # pylint: disable=protected-access + while context: + if isinstance(context, _TPUInferenceContext): + return True + context = context.outer_context + if isinstance(graph, function._FuncGraph): # pylint: disable=protected-access + graph = graph._outer_graph # pylint: disable=protected-access + elif isinstance(graph, func_graph.FuncGraph): + graph = graph.outer_graph + else: + return False + + +class _TPUInferenceContext(control_flow_ops.XLAControlFlowContext): + """A `ControlFlowContext` for nodes inside a TPU inference computation. + + The primary role of `_TPUInferenceContext` is to indicate the mode of + operation and possibly sanity check operators inside a + tpu.rewrite_for_inference() computation. + """ + + def __init__(self, name: Text, check_ops: bool = True): + super(_TPUInferenceContext, self).__init__() + self._name = name + self._check_ops = check_ops + + def AddOp(self, op): + self._AddOpInternal(op) + + def _AddOpInternal(self, op): + # pylint: disable=protected-access + if self._check_ops and op.type in _DENYLISTED_INFERENCE_OPS: + raise NotImplementedError( + f"Operation of type {op.type} ({op.name}) is not supported on the " + "TPU for inference. Execution will fail if this op is used in the " + "graph. Make sure your variables are using variable_scope.") + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def AddValue(self, val): + result = val + if self._outer_context: + result = self._outer_context.AddValue(val) + return result + + def AddInnerOp(self, op): + self._AddOpInternal(op) + + @property + def grad_state(self): + return None + + +def validate_inference_rewrite_for_variables(graph: ops.Graph): + """Validates whether rewrite_for_inference() 'worked' for variables. + + The rewrite_for_inference() method is supposed to append GuaranteeConstOps + after ReadVariableOps, but this mechanism works only if you are using + tf.compat.v1.get_variable() to create and access variables in your tpu + computation. This validation method can be called immediately after calling + tpu.rewrite_for_inference() to check whether GuaranteeConstOps where added + to the graph. + + Typical usages: + tpu.validate_inference_rewrite_for_variables( + tf.compat.v1.get_default_graph()) + + tpu.validate_inference_rewrite_for_variables(sess.graph) + + Args: + graph: The graph which needs to be validated. + Raises: + RuntimeError: if validation failed. + """ + if not any(x.type == "GuaranteeConst" for x in graph.get_operations()): + raise RuntimeError( + "No GuaranteeConst ops found in the graph after running " + "tpu.rewrite_for_inference(...). Please check that you are using " + "tf.get_variable() to create and access variables in your tpu " + "computation.") + + +def rewrite_for_inference( + computation: Callable[..., Any], + inputs: Optional[List[core_types.Tensor]] = None, + infeed_queue: Optional[tpu_feed.InfeedQueue] = None, + device_assignment: Optional[device_assignment_lib.DeviceAssignment] = None, + name: Optional[Text] = None) -> List[core_types.Tensor]: + """Rewrites `computation` for inference on a TPU system. + + Other than 'rewriting' the computation to run on a TPU, if using variables + in your computation, it moves the ReadVariableOps outside the TPU + computation, and adds GuaranteeConst ops just after the ReadVariableOps. + This mechanism works only if you are using tf.compat.v1.get_variable() to + create and access variables in your tpu computation. You can validate + whether this worked, by calling validate_inference_rewrite_for_variables() + method immediately after this method to check whether GuaranteeConstOps + where added to the graph. + + Args: + computation: A Python function that builds a computation to apply to the + input. If the function takes n inputs, 'inputs' should be a list of n + tensors. If the function returns m outputs, rewrite will return a list of + m tensors. + inputs: A list of input tensors or `None` (equivalent to an empty list). + infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple + of arguments as inputs to `computation`. + device_assignment: if not `None`, a `DeviceAssignment` describing the + mapping between logical cores in the computation with physical cores in + the TPU topology. May be omitted for a single-core computation, in which + case the core attached to task 0, TPU device 0 is used. + name: The name of the operator. + Returns: + A list of output tensors. + """ + + def guarantee_const_getter(getter, name, *args, **kwargs): + with ops.control_dependencies(None): + return array_ops.guarantee_const( + getter(name, *args, **kwargs), name=name + "/GuaranteeConst") + + def wrapped_computation(*args, **kwargs): + """Execute computation under `_TPUInferenceContext`.""" + context = _TPUInferenceContext( + name=ops.get_default_graph().unique_name("rewrite_for_inference")) + try: + context.Enter() + + vscope = variable_scope.get_variable_scope() + prev_custom_getter = vscope.custom_getter + prev_caching_device = vscope.caching_device + vscope.set_custom_getter(guarantee_const_getter) + vscope.set_caching_device(lambda op: op.device) + + result = computation(*args, **kwargs) + + vscope.set_custom_getter(prev_custom_getter) + vscope.set_caching_device(prev_caching_device) + finally: + context.Exit() + return result + + # pylint: disable=undefined-variable + return rewrite( + wrapped_computation, + inputs=inputs, + infeed_queue=infeed_queue, + device_assignment=device_assignment, + name=name) + # pylint: enable=undefined-variable + + +def prune_unconnected_ops_from_xla(prune_graph: ops.Graph): + """Prunes unconnected ops as listed in _UNCONNECTED_OPS_TO_PRUNE. + + Args: + prune_graph: A tensorflow graph from which we wish to prune unconnected ops + as listed in _UNCONNECTED_OPS_TO_PRUNE. In general, these ops should have + no inputs and no consumers. These can often be left behind due to graph + construction rewiring (for instance TF-Hub). While they never execute, + they will cause XLA compile to fail so we strip them from XLA compile by + removing the tpu_replicate attribute. + """ + # Scan over the top level graph and all function graphs. + for graph in [prune_graph] + [ + f for f in prune_graph._functions.values() # pylint: disable=protected-access + ]: + if not isinstance(graph, ops.Graph): + continue + for op in graph.get_operations(): + if op.type not in _UNCONNECTED_OPS_TO_PRUNE: + continue + outputs_consumed = False + for output in op.outputs: + if output.consumers(): + outputs_consumed = True + break + if not outputs_consumed: + logging.info( + "Pruning OP %s of type %s from XLA Compile due to " + "it being disconnected.", op.name, op.type) + op._clear_attr(tpu_replication._TPU_REPLICATE_ATTR) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_config.py new file mode 100644 index 0000000000000000000000000000000000000000..eda3717520f7a878b2f4017968e628c69d402aa7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_config.py @@ -0,0 +1,19 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stub file to maintain backwards compatibility.""" + +# pylint: disable=wildcard-import,unused-import +from tensorflow_estimator.python.estimator.tpu.tpu_config import * +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_context.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f3ee55723df3767ae4b0383b3f59f45d3907dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_context.py @@ -0,0 +1,19 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stub file to maintain backwards compatibility.""" + +# pylint: disable=wildcard-import,unused-import +from tensorflow_estimator.python.estimator.tpu.tpu_context import * +# pylint: enable=wildcard-import,unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..1ef23a0b6242f7715245e51846f78ed73317907a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding.py @@ -0,0 +1,3025 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TPU embedding APIs.""" + +import collections +import copy +import math +import re +from typing import Optional + +from tensorflow.core.protobuf.tpu import optimization_parameters_pb2 +from tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2 as elc +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import partitioned_variables +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tpu_system_metadata as tpu_system_metadata_lib +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.util.tf_export import tf_export + +TRAINING = elc.TPUEmbeddingConfiguration.TRAINING +INFERENCE = elc.TPUEmbeddingConfiguration.INFERENCE + + +# TODO(shizhiw): a more future-proof way is to have optimization_parameter such +# as AdagradParameters etc instead of learning_rate. +class TableConfig( + collections.namedtuple('TableConfig', [ + 'vocabulary_size', + 'dimension', + 'initializer', + 'combiner', + 'hot_id_replication', + 'learning_rate', + 'learning_rate_fn', + 'optimization_parameters', + ])): + """Embedding table configuration.""" + + def __new__(cls, + vocabulary_size, + dimension, + initializer=None, + combiner='mean', + hot_id_replication=False, + learning_rate=None, + learning_rate_fn=None, + optimization_parameters=None): + """Embedding table configuration. + + Args: + vocabulary_size: Number of vocabulary (/rows) in the table. + dimension: The embedding dimension. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and standard + deviation `1/sqrt(dimension)`. + combiner: A string specifying how to reduce if there are multiple entries + in a single row. Currently 'mean', 'sqrtn', 'sum' and None are + supported, with 'mean' the default. 'sqrtn' often achieves good + accuracy, in particular with bag-of-words columns. For more information, + see `tf.nn.embedding_lookup_sparse`. None is only valid for dense rather + than sparse tensors. + hot_id_replication: If true, enables hot id replication, which can make + embedding lookups faster if there are some hot rows in the table. + learning_rate: float, static learning rate for this table. If + learning_rate and learning_rate_fn are both `None`, static learning rate + as specified in local `optimization_parameters` will be used. In case + local `optimization_parameters` is `None`, global + `optimization_parameters` in `TPUEmbedding` constructor will be used. + `learning_rate_fn` must be `None` if `learning_rate` is not `None. + learning_rate_fn: string, use dynamic learning rate given by the function. + This function will be passed the current global step. If learning_rate + and learning_rate_fn are both `None`, static learning rate as specified + in `optimization_parameters` is used. `learning_rate` must be `None` if + `learning_rate_fn` is not `None. + optimization_parameters: `AdagradParameters`, `AdamParameters`, + `Stochasticgradientdescentparameters`. Specifies table level optimizer. + If it's `None` global optimizer in `TPUEmbedding` constructor is used. + + Returns: + `TableConfig`. + + Raises: + ValueError: if `vocabulary_size` is not positive integer. + ValueError: if `dimension` is not positive integer. + ValueError: if `initializer` is specified and is not callable. + ValueError: if `combiner` is not supported. + ValueError: if `learning_rate` and `learning_rate_fn` are both not + `None`. + """ + if not isinstance(vocabulary_size, int) or vocabulary_size < 1: + raise ValueError(f'vocabulary_size must >= 1. ' + f'Received: {vocabulary_size}.') + + if not isinstance(dimension, int) or dimension < 1: + raise ValueError( + f'dimension must be a positive int. Received: {dimension}.') + + if (initializer is not None) and (not callable(initializer)): + raise ValueError(f'initializer must be callable if specified. ' + f'Received: {initializer}.') + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + if combiner not in ('mean', 'sum', 'sqrtn', None): + raise ValueError(f'combiner must be "mean", "sum", "sqrtn" or None. ' + f'Received: {combiner}.') + + if learning_rate is not None and learning_rate_fn is not None: + raise ValueError('At most one of learning_rate and learning_rate_fn ' + 'can be None. Received: {} and {}'.format( + learning_rate, learning_rate_fn)) + + if optimization_parameters is not None: + if not isinstance(optimization_parameters, _OptimizationParameters): + raise ValueError(f'`optimization_parameters` must inherit from ' + f'`_OptimizationParameters`. ' + f'Received: `type(optimization_parameters)`=' + f'{type(optimization_parameters)}.') + + return super().__new__(cls, vocabulary_size, dimension, initializer, + combiner, hot_id_replication, learning_rate, + learning_rate_fn, optimization_parameters) + + +class FeatureConfig( + collections.namedtuple('FeatureConfig', + ['table_id', 'max_sequence_length', 'weight_key'])): + """Feature configuration.""" + + def __new__(cls, table_id, max_sequence_length=0, weight_key=None): + """Feature configuration. + + Args: + table_id: Which table the feature is uses for embedding lookups. + max_sequence_length: If positive, the feature is a sequence feature with + the corresponding maximum sequence length. If the sequence is longer + than this, it will be truncated. If 0, the feature is not a sequence + feature. + weight_key: If using weights for the combiner, this key specifies which + input feature contains the weights. + + Returns: + `FeatureConfig`. + + Raises: + ValueError: if `max_sequence_length` non-integer or negative. + """ + if not isinstance(max_sequence_length, int) or max_sequence_length < 0: + raise ValueError(f'max_sequence_length must be zero or a positive int, ' + f'got {max_sequence_length}.') + + return super().__new__(cls, table_id, max_sequence_length, weight_key) + + +class EnqueueData( + collections.namedtuple( + 'EnqueueData', + ['embedding_indices', 'sample_indices', 'aggregation_weights'])): + """Data to be enqueued through generate_enqueue_ops().""" + + def __new__(cls, + embedding_indices, + sample_indices=None, + aggregation_weights=None): + """Data to be enqueued through generate_enqueue_ops(). + + Args: + embedding_indices: A rank 1 Tensor, indices into the embedding tables. It + corresponds to sp_ids.values in embedding_lookup_sparse(). Both int32 + and int64 are allowed and will be converted to int32 internally. + sample_indices: A rank 2 Tensor specifying the training example to which + the corresponding embedding_indices and aggregation_weights values + belong. It corresponds to sp_ids.indices in embedding_lookup_sparse(). + If it is None, we assume each embedding_indices belongs to a different + sample. Both int32 and int64 are allowed and will be converted to int32 + internally. + aggregation_weights: A rank 1 Tensor containing aggregation weights. It + corresponds to sp_weights.values in embedding_lookup_sparse(). If it is + None, we assume all weights are 1. Both float32 and float64 are allowed + and will be converted to float32 internally. + + Returns: + An EnqueueData tuple. + + """ + return super().__new__(cls, embedding_indices, sample_indices, + aggregation_weights) + + @staticmethod + def from_sparse_tensor(sp_tensor, weights=None): + return EnqueueData( + sp_tensor.values, + sp_tensor.indices, + aggregation_weights=weights.values if weights is not None else None) + + +class RaggedEnqueueData( + collections.namedtuple( + 'RaggedEnqueueData', + ['embedding_indices', 'row_splits', 'aggregation_weights'])): + """RaggedTensor Data to be enqueued through generate_enqueue_ops().""" + + def __new__(cls, + embedding_indices, + row_splits=None, + aggregation_weights=None): + """Data to be enqueued through generate_enqueue_ops(). + + Args: + embedding_indices: A rank 1 Tensor, indices into the embedding tables. It + corresponds to ids.values in embedding_lookup(), when ids is a + RaggedTensor. Both int32 and int64 are allowed and will be converted to + int32 internally. + row_splits: A rank 1 Tensor specifying the length of the break points for + splitting embedding_indices and aggregation_weights. It corresponds to + ids.row_splits in embedding_lookup(), when ids is a RaggedTensor. Both + int32 and int64 are allowed and will be converted to int32 internally. + aggregation_weights: A rank 1 Tensor containing per training example + aggregation weights. It corresponds to the values field of a + RaggedTensor with the same row_splits as ids in embedding_lookup(), when + ids is a RaggedTensor. + + Returns: + An RaggedEnqueueData tuple. + + """ + return super().__new__(cls, embedding_indices, row_splits, + aggregation_weights) + + @staticmethod + def from_ragged_tensor(rg_tensor, weights=None): + return RaggedEnqueueData( + rg_tensor.values, + rg_tensor.row_splits, + aggregation_weights=weights.values if weights is not None else None) + + +def get_enqueue_datas_list_from_sparse_tensors_list(sp_tensors_list): + """Convenient function for generate_enqueue_ops(). + + Args: + sp_tensors_list: a list of dictionary mapping from string of feature names + to SparseTensor. Each dictionary is for one TPU core. Dictionaries for the + same host should be contiguous on the list. + + Returns: + enqueue_datas_list: a list of dictionary mapping from string + of feature names to EnqueueData. Each dictionary is for one + TPU core. Dictionaries for the same host should be contiguous + on the list. + + """ + enqueue_datas_list = [] + for sp_tensors in sp_tensors_list: + enqueue_datas = collections.OrderedDict( + (k, EnqueueData.from_sparse_tensor(v)) for k, v in sp_tensors.items()) + enqueue_datas_list.append(enqueue_datas) + return enqueue_datas_list + + +def get_enqueue_datas_list_from_ragged_tensors_list(rg_tensors_list): + """Convenient function for generate_enqueue_ops(). + + Args: + rg_tensors_list: a list of dictionary mapping from string of feature names + to RaggedTensor. Each dictionary is for one TPU core. Dictionaries for the + same host should be contiguous on the list. + + Returns: + enqueue_datas_list: a list of dictionary mapping from string + of feature names to RaggedEnqueueData. Each dictionary is for one + TPU core. Dictionaries for the same host should be contiguous + on the list. + + """ + enqueue_datas_list = [] + for rg_tensors in rg_tensors_list: + enqueue_datas = collections.OrderedDict( + (k, RaggedEnqueueData.from_ragged_tensor(v)) + for k, v in rg_tensors.items()) + enqueue_datas_list.append(enqueue_datas) + return enqueue_datas_list + + +AdamSlotVariableNames = collections.namedtuple('AdamSlotVariableNames', + ['m', 'v']) + +AdagradSlotVariableNames = collections.namedtuple('AdagradSlotVariableNames', + ['accumulator']) + +MomentumSlotVariableNames = collections.namedtuple('MomentumSlotVariableNames', + ['momenta']) + +AdagradMomentumSlotVariableNames = collections.namedtuple( + 'AdagradMomentumSlotVariableNames', ['accumulator', 'momenta']) + +RMSPropSlotVariableNames = collections.namedtuple('RMSPropSlotVariableNames', + ['ms', 'mom']) + +ProximalAdagradSlotVariableNames = collections.namedtuple( + 'ProximalAdagradSlotVariableNames', ['accumulator']) + +FtrlSlotVariableNames = collections.namedtuple('FtrlSlotVariableNames', + ['accumulator', 'linear']) + +ProximalYogiSlotVariableNames = collections.namedtuple( + 'ProximalYogiSlotVariableNames', ['v', 'm']) + +FrequencyEstimatorSlotVariableNames = collections.namedtuple( + 'FrequencyEstimatorSlotVariableNames', ['last_hit_step']) + +AdamSlotVariables = collections.namedtuple('AdamSlotVariables', ['m', 'v']) + +MomentumSlotVariables = collections.namedtuple('MomentumSlotVariables', + ['momenta']) + +AdagradMomentumSlotVariables = collections.namedtuple( + 'AdagradMomentumSlotVariables', ['accumulator', 'momenta']) + +RMSPropSlotVariables = collections.namedtuple('RMSPropSlotVariables', + ['ms', 'mom']) + +AdagradSlotVariables = collections.namedtuple('AdagradSlotVariables', + ['accumulator']) + +ProximalAdagradSlotVariables = collections.namedtuple( + 'ProximalAdagradSlotVariables', ['accumulator']) + +FtrlSlotVariable = collections.namedtuple('FtrlSlotVariable', + ['accumulator', 'linear']) + +ProximalYogiSlotVariables = collections.namedtuple('ProximalYogiSlotVariables', + ['v', 'm']) + +FrequencyEstimatorSlotVariables = collections.namedtuple( + 'FrequencyEstimatorSlotVariables', ['last_hit_step']) + +VariablesAndOps = collections.namedtuple('VariablesAndOps', [ + 'embedding_variables_by_table', 'slot_variables_by_table', 'load_ops', + 'retrieve_ops' +]) + + +class _OptimizationParameters: + """Parameters common to all optimizations.""" + + def __init__( + self, + learning_rate: float, + use_gradient_accumulation: bool, + clip_weight_min: Optional[float], + clip_weight_max: Optional[float], + weight_decay_factor: Optional[float], + multiply_weight_decay_factor_by_learning_rate: Optional[bool], + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + self.learning_rate = learning_rate + self.use_gradient_accumulation = use_gradient_accumulation + self.clip_weight_min = clip_weight_min + self.clip_weight_max = clip_weight_max + self.weight_decay_factor = weight_decay_factor + self.multiply_weight_decay_factor_by_learning_rate = ( + multiply_weight_decay_factor_by_learning_rate) + self.clip_gradient_min = clip_gradient_min + self.clip_gradient_max = clip_gradient_max + + if not use_gradient_accumulation and (clip_gradient_min is not None or + clip_gradient_max is not None): + raise ValueError('When using gradient clipping limits, gradient ' + 'accumulation must be enabled.') + + +@tf_export(v1=['tpu.experimental.AdagradParameters']) +class AdagradParameters(_OptimizationParameters): + """Optimization parameters for Adagrad with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.AdagradParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + initial_accumulator: float = 0.1, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Adagrad. + + Args: + learning_rate: used for updating embedding table. + initial_accumulator: initial accumulator for Adagrad. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if initial_accumulator <= 0: + raise ValueError( + f'Adagrad initial_accumulator must be greater than zero. ' + f'Received: {initial_accumulator}.') + self.initial_accumulator = initial_accumulator + + +class AdagradMomentumParameters(_OptimizationParameters): + """Optimization parameters for Adagrad + Momentum with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.AdagradMomentumParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + momentum: float, + use_nesterov: bool = False, + exponent: float = 2, + beta2: float = 1, + epsilon: float = 1e-10, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Adagrad. + + Args: + learning_rate: used for updating embedding table. + momentum: Moving average parameter for the momentum accumulator. + use_nesterov: Whether to use the Nesterov variant of momentum. See + Sutskever et al., 2013. + exponent: Exponent for the Adagrad accumulator. + beta2: Moving average parameter for the Adagrad accumulator. + epsilon: initial accumulator for Adagrad accumulator. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if epsilon <= 0: + raise ValueError('Adagrad momentum: epsilon must be positive') + if exponent <= 0: + raise ValueError('Adagrad momentum: Precondition exponent must >0') + self.momentum = momentum + self.use_nesterov = use_nesterov + self.exponent = exponent + self.beta2 = beta2 + self.epsilon = epsilon + + +class ProximalAdagradParameters(_OptimizationParameters): + """Optimization parameters for ProximalAdagrad with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + """ + + def __init__( + self, + learning_rate: float, + initial_accumulator: float = 0.1, + l1_regularization_strength: float = 0.0, + l2_regularization_strength: float = 0.0, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Adagrad. + + Args: + learning_rate: used for updating embedding table. + initial_accumulator: initial accumulator for Adagrad. + l1_regularization_strength: A float value, must be greater than or equal + to zero. + l2_regularization_strength: A float value, must be greater than or equal + to zero. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if initial_accumulator <= 0: + raise ValueError(f'Adagrad initial_accumulator must be positive. ' + f'Received: {initial_accumulator}.') + if l1_regularization_strength < 0.: + raise ValueError('l1_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l1_regularization_strength)) + + if l2_regularization_strength < 0.: + raise ValueError('l2_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l2_regularization_strength)) + + self.initial_accumulator = initial_accumulator + self.l1_regularization_strength = l1_regularization_strength + self.l2_regularization_strength = l2_regularization_strength + + +@tf_export(v1=['tpu.experimental.AdamParameters']) +class AdamParameters(_OptimizationParameters): + """Optimization parameters for Adam with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.AdamParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + beta1: float = 0.9, + beta2: float = 0.999, + epsilon: float = 1e-08, + lazy_adam: bool = True, + sum_inside_sqrt: bool = True, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Adam. + + Args: + learning_rate: a floating point value. The learning rate. + beta1: A float value. The exponential decay rate for the 1st moment + estimates. + beta2: A float value. The exponential decay rate for the 2nd moment + estimates. + epsilon: A small constant for numerical stability. + lazy_adam: Use lazy Adam instead of Adam. Lazy Adam trains faster. See + `optimization_parameters.proto` for details. + sum_inside_sqrt: This improves training speed. Please see + `optimization_parameters.proto` for details. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if beta1 < 0. or beta1 >= 1.: + raise ValueError('beta1 must be between 0. and 1; got {}.'.format(beta1)) + if beta2 < 0. or beta2 >= 1.: + raise ValueError('beta2 must be between 0. and 1; got {}.'.format(beta2)) + if epsilon <= 0.: + raise ValueError('epsilon must be positive; got {}.'.format(epsilon)) + if not use_gradient_accumulation and not lazy_adam: + raise ValueError( + 'When disabling Lazy Adam, gradient accumulation must be used.') + + self.beta1 = beta1 + self.beta2 = beta2 + self.epsilon = epsilon + self.lazy_adam = lazy_adam + self.sum_inside_sqrt = sum_inside_sqrt + + +@tf_export(v1=['tpu.experimental.FtrlParameters']) +class FtrlParameters(_OptimizationParameters): + """Optimization parameters for Ftrl with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.FtrlParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + learning_rate_power: float = -0.5, + initial_accumulator_value: float = 0.1, + l1_regularization_strength: float = 0.0, + l2_regularization_strength: float = 0.0, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + multiply_linear_by_learning_rate: bool = False, + beta: float = 0, + allow_zero_accumulator: bool = False, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Ftrl. + + Implements FTRL as described in the following [paper]( + https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/41159.pdf) + + Args: + learning_rate: a floating point value. The learning rate. + learning_rate_power: A float value, must be less or equal to zero. + Controls how the learning rate decreases during training. Use zero for a + fixed learning rate. See section 3.1 in the + [paper](https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf). + initial_accumulator_value: The starting value for accumulators. Only zero + or positive values are allowed. + l1_regularization_strength: A float value, must be greater than or equal + to zero. + l2_regularization_strength: A float value, must be greater than or equal + to zero. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + multiply_linear_by_learning_rate: When true, multiplies the usages of the + linear slot in the weight update by the learning rate. This is useful + when ramping up learning rate from 0 (which would normally produce + NaNs). + beta: The beta parameter for FTRL. + allow_zero_accumulator: Changes the implementation of the square root to + allow for the case of initial_accumulator_value being zero. This will + cause a slight performance drop. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if learning_rate_power > 0.: + raise ValueError('learning_rate_power must be less than or equal to 0. ' + 'got {}.'.format(learning_rate_power)) + + if initial_accumulator_value < 0.: + raise ValueError('initial_accumulator_value must be greater than or equal' + ' to 0. got {}.'.format(initial_accumulator_value)) + + if l1_regularization_strength < 0.: + raise ValueError('l1_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l1_regularization_strength)) + + if l2_regularization_strength < 0.: + raise ValueError('l2_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l2_regularization_strength)) + + self.learning_rate_power = learning_rate_power + self.initial_accumulator_value = initial_accumulator_value + self.initial_linear_value = 0.0 + self.l1_regularization_strength = l1_regularization_strength + self.l2_regularization_strength = l2_regularization_strength + self.multiply_linear_by_learning_rate = multiply_linear_by_learning_rate + self.beta = beta + self.allow_zero_accumulator = allow_zero_accumulator + + +class ProximalYogiParameters(_OptimizationParameters): + # pylint: disable=line-too-long + """Optimization parameters for Proximal Yogi with TPU embeddings. + + Implements the Yogi optimizer as described in + [Adaptive Methods for Nonconvex + Optimization](https://papers.nips.cc/paper/8186-adaptive-methods-for-nonconvex-optimization). + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + """ + + # pylint: enable=line-too-long + + def __init__( + self, + learning_rate: float = 0.01, + beta1: float = 0.9, + beta2: float = 0.999, + epsilon: float = 1e-3, + l1_regularization_strength: float = 0.0, + l2_regularization_strength: float = 0.0, + initial_accumulator_value: float = 1e-6, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for Proximal Yogi. + + Args: + learning_rate: a floating point value. The learning rate. + beta1: A float value. The exponential decay rate for the 1st moment + estimates. + beta2: A float value. The exponential decay rate for the 2nd moment + estimates. + epsilon: A small constant for numerical stability. + l1_regularization_strength: A float value, must be greater than or equal + to zero. + l2_regularization_strength: A float value, must be greater than or equal + to zero. + initial_accumulator_value: The starting value for accumulators. Only zero + or positive values are allowed. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + if beta1 < 0. or beta1 >= 1.: + raise ValueError('beta1 must be between 0. and 1; got {}.'.format(beta1)) + if beta2 < 0. or beta2 >= 1.: + raise ValueError('beta2 must be between 0. and 1; got {}.'.format(beta2)) + if epsilon <= 0.: + raise ValueError('epsilon must be positive; got {}.'.format(epsilon)) + if l1_regularization_strength < 0.: + raise ValueError('l1_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l1_regularization_strength)) + if l2_regularization_strength < 0.: + raise ValueError('l2_regularization_strength must be greater than or ' + 'equal to 0. got {}.'.format(l2_regularization_strength)) + + self.beta1 = beta1 + self.beta2 = beta2 + self.epsilon = epsilon + self.l1_regularization_strength = l1_regularization_strength + self.l2_regularization_strength = l2_regularization_strength + self.initial_accumulator_value = initial_accumulator_value + + +class MomentumParameters(_OptimizationParameters): + """Optimization parameters for Momentum with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.MomentumParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + momentum: float, + use_nesterov: bool = False, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for momentum. + + Args: + learning_rate: a floating point value. The learning rate. + momentum: a floating point value. The momentum. + use_nesterov: If `True` use Nesterov Momentum. See (Sutskever et al., + 2013). This implementation always computes gradients at the value of the + variable(s) passed to the optimizer. Using Nesterov Momentum makes the + variable(s) track the values called `theta_t + mu*v_t` in the paper. + This implementation is an approximation of the original formula, valid + for high values of momentum. It will compute the "adjusted gradient" in + NAG by assuming that the new gradient will be estimated by the current + average gradient plus the product of momentum and the change in the + average gradient. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + self.momentum = momentum + self.use_nesterov = use_nesterov + + +class RMSPropParameters(_OptimizationParameters): + """Optimization parameters for RMSProp with TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=tf.tpu.experimental.MomentumParameters(0.1), + ...)) + ``` + + """ + + def __init__( + self, + learning_rate: float, + rho: float, + momentum: float, + epsilon: float, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for RMS prop. + + Args: + learning_rate: a floating point value. The learning rate. + rho: Discounting factor for the history/coming gradient + momentum: A scalar tensor. + epsilon: Small value to avoid zero denominator. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + Gradient accumulation must be set to true if this is set. + clip_gradient_max: the maximum value to clip by; None means +infinity. + Gradient accumulation must be set to true if this is set. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + self.rho = rho + self.momentum = momentum + self.epsilon = epsilon + + +@tf_export(v1=['tpu.experimental.StochasticGradientDescentParameters']) +class StochasticGradientDescentParameters(_OptimizationParameters): + """Optimization parameters for stochastic gradient descent for TPU embeddings. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=( + tf.tpu.experimental.StochasticGradientDescentParameters(0.1)))) + ``` + + """ + + def __init__( + self, + learning_rate: float, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, + clip_gradient_min: Optional[float] = None, + clip_gradient_max: Optional[float] = None, + ): + """Optimization parameters for stochastic gradient descent. + + Args: + learning_rate: a floating point value. The learning rate. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. Please see + `optimization_parameters.proto` for details. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clip_gradient_min: the minimum value to clip by; None means -infinity. + clip_gradient_max: the maximum value to clip by; None means +infinity. + """ + super().__init__( + learning_rate=learning_rate, + use_gradient_accumulation=use_gradient_accumulation, + clip_weight_min=clip_weight_min, + clip_weight_max=clip_weight_max, + weight_decay_factor=weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate=( + multiply_weight_decay_factor_by_learning_rate), + clip_gradient_min=clip_gradient_min, + clip_gradient_max=clip_gradient_max, + ) + + +class FrequencyEstimatorParameters(_OptimizationParameters): + """Optimization parameters for Frequency Estimator TPU embeddings. + + This is a non-standard optimizer, which returns the estimated frequency of + lookup for the feature passed to it. It should only be used on a table of + width 1. The gradient fed back to the TPU embedding should always be zero. + This can be acomplished via using `tf.stop_gradients` on the feature before + using it. + + You must use the dynamic learning rate mechanism to set the 'learning rate' + for this table to be the a float32 cast of the global training step counter. + + See `tensorflow/core/protobuf/tpu/optimization_parameters.proto` for more + details on this optimizer. + + Pass this to `tf.estimator.tpu.experimental.EmbeddingConfigSpec` via the + `optimization_parameters` argument to set the optimizer and its parameters. + See the documentation for `tf.estimator.tpu.experimental.EmbeddingConfigSpec` + for more details. + + ``` + estimator = tf.estimator.tpu.TPUEstimator( + ... + embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( + ... + optimization_parameters=FrequencyEstimatorParameters(0.1), + ...)) + ``` + + """ + + def __init__(self, tau: float, max_delta: float, outlier_threshold: float, + weight_exponent: float): + """Optimization parameters for frequency estimator. + + Args: + tau: Learning rate between (0, 1) that is used to update the array. + max_delta: Maximum value of delta, the difference between the current + global step and the last global step at which the row was sampled. + outlier_threshold: Threshold used to determine whether the current update + is an outlier. + weight_exponent: The weight exponent used to transform the estimated delta + into weights. + """ + super().__init__( + learning_rate=1.0, + use_gradient_accumulation=True, + clip_weight_min=None, + clip_weight_max=None, + weight_decay_factor=None, + multiply_weight_decay_factor_by_learning_rate=None, + ) + self.tau = tau + self.max_delta = max_delta + self.outlier_threshold = outlier_threshold + self.weight_exponent = weight_exponent + + +DeviceConfig = collections.namedtuple('DeviceConfig', + ['num_hosts', 'num_cores', 'job_name']) + + +class TPUEmbedding: + """API for using TPU for embedding. + + Example: + ``` + table_config_user = tpu_embedding.TableConfig( + vocabulary_size=4, dimension=2, + initializer=initializer, combiner='mean') + table_to_config_dict = {'video': table_config_video, + 'user': table_config_user} + feature_to_config_dict = {'watched': tpu_embedding.FeatureConfig('video'), + 'favorited': tpu_embedding.FeatureConfig('video'), + 'friends': tpu_embedding.FeatureConfig('user')} + batch_size = 4 + num_hosts = 1 + optimization_parameters = tpu_embedding.AdagradParameters(1., 1.) + mode = tpu_embedding.TRAINING + embedding = tpu_embedding.TPUEmbedding( + table_to_config_dict, feature_to_config_dict, + batch_size, num_hosts, mode, optimization_parameters) + + batch_size_per_core = embedding.batch_size_per_core + sparse_features_list = [] + for host in hosts: + with ops.device(host): + for _ in range(embedding.num_cores_per_host): + sparse_features = {} + sparse_features['watched'] = sparse_tensor.SparseTensor(...) + sparse_features['favorited'] = sparse_tensor.SparseTensor(...) + sparse_features['friends'] = sparse_tensor.SparseTensor(...) + sparse_features_list.append(sparse_features) + + enqueue_ops = embedding.generate_enqueue_ops(sparse_features_list) + embedding_variables_and_ops = embedding.create_variables_and_ops() + + def computation(): + activations = embedding.get_activations() + loss = compute_loss(activations) + + base_optimizer = gradient_descent.GradientDescentOptimizer( + learning_rate=1) + cross_shard_optimizer = tpu_optimizer.CrossShardOptimizer( + base_optimizer) + + train_op = cross_shard_optimizer.minimize(loss) + gradients = ( + tpu_embedding_gradient.get_gradients_through_compute_gradients( + cross_shard_optimizer, loss, activations) + send_gradients_op = embedding.generate_send_gradients_op(gradients) + with ops.control_dependencies([train_op, send_gradients_op]): + loss = array_ops.identity(loss) + + loss = tpu.shard(computation, + num_shards=embedding.num_cores) + + with self.test_session() as sess: + sess.run(tpu.initialize_system(embedding_config= + embedding.config_proto)) + sess.run(variables.global_variables_initializer()) + sess.run(embedding_variables_and_ops.load_ops()) + sess.run(enqueue_ops) + loss_val = sess.run(loss) + ``` + + Example with weight decay: + + >>> def learning_rate_fn(global_step): + ... return tf.compat.v1.train.polynomial_decay( + ... learning_rate=5e-5, + ... global_step=global_step, + ... decay_steps=100000, + ... end_learning_rate=0.0) + >>> wordpiece_table_config = TableConfig( + ... vocabulary_size=119547, + ... dimension=256, + ... learning_rate_fn=learning_rate_fn) + >>> wordpiece_feature_config = FeatureConfig( + ... table_id='bert/embeddings/word_embeddings', + ... max_sequence_length=512) + >>> optimization_parameters = AdamParameters( + ... learning_rate=5e-5, + ... epsilon=1e-6, + ... weight_decay_factor=0.01, + ... multiply_weight_decay_factor_by_learning_rate=True) + >>> tpu_embedding = TPUEmbedding( + ... table_to_config_dict={ + ... 'bert/embeddings/word_embeddings': wordpiece_table_config, + ... }, + ... feature_to_config_dict={'input_ids': wordpiece_feature_config}, + ... batch_size=128, + ... mode=TRAINING, + ... optimization_parameters=optimization_parameters, + ... master='') + >>> with tf.Graph().as_default(): + ... init_tpu_op = tf.compat.v1.tpu.initialize_system( + ... embedding_config=tpu_embedding.config_proto) + ... tf.compat.v1.Session().run(init_tpu_op) + """ + + # TODO(shizhiw): Consider adding a field to FeatureConfig that indicates that + # the feature should not be used to update embedding table (cr/204852758, + # cr/204940540). Also, this can support different combiners for different + # features within the same table. + # TODO(shizhiw, b/118512626): Remove `batch_size` from `__init__` and move it + # to `FeatureConfig`? + + # TODO(shizhiw): will it be cleaner to make `table_to_config_dict` and + # `feature_to_config_dict` lists of `TableSpec` and `FeatureSpec` + # respectively? + + # TODO(shizhiw): Consider adding `input_fn` as an option to remove boilerplate + # for-loops around construction of inputs. + + # `optimization_parameter` applies to all tables. If the need arises, + # we can add `optimization_parameters` to `TableConfig` to override this + # global setting. + def __init__(self, + table_to_config_dict, + feature_to_config_dict, + batch_size, + mode, + master=None, + optimization_parameters=None, + cluster_def=None, + pipeline_execution_with_tensor_core=False, + partition_strategy='div', + profile_data_directory=None, + device_config=None, + master_job_name=None): + """API for using TPU for embedding lookups. + + Args: + table_to_config_dict: A dictionary mapping from string of table name to + `TableConfig`. Table refers to an embedding table, e.g. `params` + argument to `tf.nn.embedding_lookup_sparse()`. + feature_to_config_dict: A dictionary mapping from string of feature name + to `FeatureConfig`. Feature refers to ids to lookup in embedding table, + e.g. `sp_ids` argument to `tf.nn.embedding_lookup_sparse()`. + batch_size: An `int` representing the global batch size. + mode: `TRAINING` or `INFERENCE`. + master: A `string` representing the TensorFlow master to use. + optimization_parameters: `AdagradParameters`, `AdamParameters`, + `Stochasticgradientdescentparameters`. Must be set in training unless + all tables specify their own optimizers. And it must be `None` in + inference. + cluster_def: A ClusterDef object describing the TPU cluster. + pipeline_execution_with_tensor_core: setting this to `True` makes training + faster, but trained model will be different if step N and step N+1 + involve the same set of embedding IDs. Please see + `tpu_embedding_configuration.proto` for details. + partition_strategy: A string, either 'mod' or 'div', specifying how to map + the lookup id to the embedding tensor. For more information see + `tf.nn.embedding_lookup_sparse`. + profile_data_directory: Directory where embedding lookup statistics are + stored. These statistics summarize information about the inputs to the + embedding lookup operation, in particular, the average number of + embedding IDs per example and how well the embedding IDs are load + balanced across the system. The lookup statistics are used during TPU + initialization for embedding table partitioning. Collection of lookup + statistics is done at runtime by profiling the embedding inputs, only a + small fraction of input samples are profiled to minimize host CPU + overhead. Once a suitable number of samples are profiled, the lookup + statistics are saved to table-specific files in the profile data + directory generally at the end of a TPU training loop. The filename + corresponding to each table is obtained by hashing table specific + parameters (e.g., table name and number of features) and global + configuration parameters (e.g., sharding strategy and task count). The + same profile data directory can be shared among several models to reuse + embedding lookup statistics. + device_config: A DeviceConfig instance, used when `master` and + `cluster_def` are both `None`. + master_job_name: if set, overrides the master job name used to schedule + embedding ops. + + Raises: + ValueError: if any input is invalid. + """ + if partition_strategy not in ('div', 'mod'): + raise ValueError(f'partition_strategy must be "div" or "mod". ' + f'Received: {partition_strategy}.') + self._partition_strategy = partition_strategy + + self._profile_data_directory = profile_data_directory + + _validate_table_to_config_dict(table_to_config_dict) + # Avoid nondeterminism from `Dict` iteration order by using `OrderedDict`. + self._table_to_config_dict = _create_ordered_dict(table_to_config_dict) + + _validate_feature_to_config_dict(table_to_config_dict, + feature_to_config_dict) + self._feature_to_config_dict = _create_ordered_dict(feature_to_config_dict) + self._table_to_features_dict = ( + _create_table_to_features_dict(self._feature_to_config_dict)) + self._combiners = _create_combiners(self._table_to_config_dict, + self._table_to_features_dict) + + self._batch_size = batch_size + + if master is None and cluster_def is None: + if device_config is None: + raise ValueError('When master and cluster_def are both None,' + 'device_config must be set but is not.') + if device_config.num_cores % device_config.num_hosts: + raise ValueError('num_hosts ({}) should divide num_cores ({}) ' + 'but does not.'.format(device_config.num_cores, + device_config.num_hosts)) + self._num_hosts = device_config.num_hosts + self._num_cores = device_config.num_cores + self._num_cores_per_host = self._num_cores // self._num_hosts + self._hosts = [ + '{}/replica:0/task:{}/device:CPU:0'.format(device_config.job_name, i) + for i in range(self._num_hosts) + ] + else: + tpu_system_metadata = ( + tpu_system_metadata_lib._query_tpu_system_metadata( # pylint: disable=protected-access + master, + cluster_def=cluster_def)) + if tpu_system_metadata.num_cores == 0: + raise ValueError('TPUEmbedding needs TPUs, but master {} does not have ' + 'TPUs.'.format(master)) + self._num_hosts = tpu_system_metadata.num_hosts + if master_job_name is None: + try: + master_job_name = tpu_system_metadata_lib.master_job( + master, cluster_def) + except ValueError as e: + raise ValueError(str(e) + ' Please specify a master_job_name.') + self._hosts = [] + for device in tpu_system_metadata.devices: + if 'device:CPU:' in device.name and (master_job_name is None or + master_job_name in device.name): + self._hosts.append(device.name) + self._num_cores_per_host = tpu_system_metadata.num_of_cores_per_host + self._num_cores = tpu_system_metadata.num_cores + + _validate_batch_size(self._batch_size, self._num_cores) + self._batch_size_per_core = self._batch_size // self._num_cores + + # TODO(shizhiw): remove `mode`? + if mode == TRAINING: + _validate_optimization_parameters(optimization_parameters, + self._table_to_config_dict) + self._optimization_parameters = optimization_parameters + elif mode == INFERENCE: + if optimization_parameters is not None: + raise ValueError(f'`optimization_parameters` should be `None` ' + f'for inference mode. ' + f'Received: {optimization_parameters}.') + self._optimization_parameters = (StochasticGradientDescentParameters(1.)) + else: + raise ValueError('`mode` only supports {} and {}; got {}.'.format( + TRAINING, INFERENCE, mode)) + self._mode = mode + + # TODO(shizhiw): move `optimization_parameters` into `_optimizer_handler` + # and create special handler for inference that inherits from + # StochasticGradientDescentHandler with more user-friendly error message + # on get_slot(). + self._optimizer_handler_dict = self._get_optimizer_handler_by_table() + + self._pipeline_execution_with_tensor_core = ( + pipeline_execution_with_tensor_core) + self._learning_rate_fn = list( + set(c.learning_rate_fn + for c in self._table_to_config_dict.values() + if c.learning_rate_fn is not None)) + self._learning_rate_fn_to_tag = { + fn: id for id, fn in enumerate(self._learning_rate_fn) + } + + self._config_proto = self._create_config_proto() + + @property + def hosts(self): + """A list of device names for CPU hosts. + + Returns: + A list of device names for CPU hosts. + """ + return copy.copy(self._hosts) + + # TODO(shizhiw): change to num_tensor_cores_per_host to be more explicit and + # to be consistent with `tpu_embedding_configuration.proto`. + @property + def num_cores_per_host(self): + """Number of TPU cores on a CPU host. + + Returns: + Number of TPU cores on a CPU host. + """ + return self._num_cores_per_host + + @property + def num_cores(self): + """Total number of TPU cores on all hosts. + + Returns: + Total number of TPU cores on all hosts. + """ + return self._num_cores + + @property + def batch_size_per_core(self): + """Batch size for each TPU core. + + The sparse tensors in `sparse_features_list` to `generate_enqueue_ops` + must have batch dimension equal to this. + + Returns: + Batch size for each TPU core. + """ + return self._batch_size_per_core + + @property + def config_proto(self): + """Create embedding config proto for `tpu.initialize_system()`. + + Returns: + an `TPUEmbeddingConfiguration` proto describing the desired + configuration of the hardware embedding lookup tables, which + is passed to `tpu.initialize_system()`. + """ + return self._config_proto + + @property + def table_to_config_dict(self): + return copy.copy(self._table_to_config_dict) + + @property + def feature_to_config_dict(self): + return copy.copy(self._feature_to_config_dict) + + @property + def table_to_features_dict(self): + return copy.copy(self._table_to_features_dict) + + @property + def optimization_parameters(self): + return self._optimization_parameters + + def _create_config_proto(self): + """Create `TPUEmbeddingConfiguration`.""" + config_proto = elc.TPUEmbeddingConfiguration() + for table in self._table_to_config_dict: + table_descriptor = config_proto.table_descriptor.add() + table_descriptor.name = table + + table_config = self._table_to_config_dict[table] + # For small tables, we pad to the number of hosts so that at least one + # id will be assigned to each host. + table_descriptor.vocabulary_size = max(table_config.vocabulary_size, + len(self.hosts)) + table_descriptor.dimension = table_config.dimension + + optimization_parameters = ( + self._optimizer_handler_dict[table].get_optimization_parameters()) + + parameters = table_descriptor.optimization_parameters + if table_config.learning_rate: + parameters.learning_rate.constant = table_config.learning_rate + elif table_config.learning_rate_fn: + parameters.learning_rate.dynamic.tag = ( + self._learning_rate_fn_to_tag[table_config.learning_rate_fn]) + else: + parameters.learning_rate.constant = ( + optimization_parameters.learning_rate) + parameters.gradient_accumulation_status = ( + optimization_parameters_pb2.GradientAccumulationStatus.ENABLED + if optimization_parameters.use_gradient_accumulation else + optimization_parameters_pb2.GradientAccumulationStatus.DISABLED) + + if optimization_parameters.clip_gradient_min is not None: + parameters.gradient_clipping_limits.lower.value = ( + optimization_parameters.clip_gradient_min) + if optimization_parameters.clip_gradient_max is not None: + parameters.gradient_clipping_limits.upper.value = ( + optimization_parameters.clip_gradient_max) + + if optimization_parameters.clip_weight_min is not None: + parameters.clipping_limits.lower.value = ( + optimization_parameters.clip_weight_min) + if optimization_parameters.clip_weight_max is not None: + parameters.clipping_limits.upper.value = ( + optimization_parameters.clip_weight_max) + if optimization_parameters.weight_decay_factor: + parameters.weight_decay_factor = ( + optimization_parameters.weight_decay_factor) + if (optimization_parameters + .multiply_weight_decay_factor_by_learning_rate): + parameters.multiply_weight_decay_factor_by_learning_rate = True + if table_config.hot_id_replication: + parameters.hot_id_replication_configuration.status = ( + optimization_parameters_pb2.HotIdReplicationConfiguration.ENABLED) + optimizer_handler = self._optimizer_handler_dict[table] + optimizer_handler.set_optimization_parameters(table_descriptor) + + table_to_id = { + table: i for i, table in enumerate(self._table_to_config_dict) + } + + # Set feature descriptor field in the config proto. + for table in self._table_to_features_dict: + features = self._table_to_features_dict[table] + for feature in features: + feature_descriptor = config_proto.feature_descriptor.add() + + feature_descriptor.table_id = table_to_id[ + self._feature_to_config_dict[feature].table_id] + if self._feature_to_config_dict[feature].max_sequence_length > 0: + feature_descriptor.input_shape.extend([ + self._batch_size_per_core, + self._feature_to_config_dict[feature].max_sequence_length + ]) + else: + feature_descriptor.input_shape.extend([self._batch_size_per_core]) + + config_proto.mode = self._mode + config_proto.num_hosts = self._num_hosts + config_proto.num_tensor_cores = self._num_cores + config_proto.sharding_strategy = ( + elc.TPUEmbeddingConfiguration.DIV_DEFAULT if self._partition_strategy + == 'div' else elc.TPUEmbeddingConfiguration.MOD) + config_proto.pipeline_execution_with_tensor_core = ( + self._pipeline_execution_with_tensor_core) + if self._profile_data_directory: + config_proto.profile_data_directory = self._profile_data_directory + + return config_proto + + def create_variables_and_ops(self, + embedding_variable_name_by_table=None, + slot_variable_names_by_table=None): + """Create embedding and slot variables, with ops to load and retrieve them. + + N.B.: the retrieve embedding variables (including slot variables) ops are + returned as lambda fn, as the call side might want to impose control + dependencies between the TPU computation and retrieving actions. For + example, the following code snippet ensures the TPU computation finishes + first, and then we pull the variables back from TPU to CPU. + + ``` + updates_ops = [] + with ops.control_dependencies([loss]): + for op_fn in retrieve_parameters_op_fns: + update_ops.append(op_fn()) + ``` + + Args: + embedding_variable_name_by_table: A dictionary mapping from string of + table name to string of embedding variable name. If `None`, defaults + from `get_default_slot_variable_names()` will be used. + slot_variable_names_by_table: A dictionary mapping from string of table + name to `AdamSlotVariableNames`, `AdagradSlotVariableNames` etc. If + `None`, defaults from `get_default_slot_variable_names()` will be used. + + Returns: + `tpu_embedding.VariablesAndOps` with: + A dictionary mapping from string of table name to embedding variables, + A dictionary mapping from string of table name to AdagradSlotVariables, + AdamSlotVariables etc with slot variables, + A function which returns a list of ops to load embedding and slot + variables from CPU to TPU. + A function which returns a list of ops to retrieve embedding and slot + variables from TPU to CPU. + """ + embedding_variables_by_table = {} + slot_variables_by_table = {} + load_op_fns = [] + retrieve_op_fns = [] + + for i, table in enumerate(self._table_to_config_dict): + if embedding_variable_name_by_table: + embedding_variable_name = embedding_variable_name_by_table[table] + else: + embedding_variable_name = table + if slot_variable_names_by_table: + slot_variable_names = slot_variable_names_by_table[table] + else: + optimizer_handler = self._optimizer_handler_dict[table] + slot_variable_names = ( + optimizer_handler.get_default_slot_variable_names(table)) + + # TODO(b/139144091): Multi-host support for mid-level API in + # eager context (TF 2.0) + # Workaround below allows single-host use case in TF 2.0 + if context.executing_eagerly(): + device = '' + else: + device = _create_device_fn(self._hosts) + + with ops.device(device): + table_variables = _create_partitioned_variables( + name=embedding_variable_name, + num_hosts=self._num_hosts, + vocabulary_size=self._table_to_config_dict[table].vocabulary_size, + embedding_dimension=self._table_to_config_dict[table].dimension, + initializer=self._table_to_config_dict[table].initializer, + collections=[ops.GraphKeys.GLOBAL_VARIABLES]) + embedding_variables_by_table[table] = table_variables + + # Only loads embedding config to load/retrieve nodes for the first table + # on the first host, other nodes would use config from the first node. + config = None if i else self.config_proto.SerializeToString() + slot_variables_for_table, load_ops_fn, retrieve_ops_fn = ( + self._optimizer_handler_dict[table].create_variables_and_ops( + table, slot_variable_names, self._num_hosts, + self._table_to_config_dict[table], table_variables, config)) + slot_variables_by_table[table] = slot_variables_for_table + load_op_fns.append(load_ops_fn) + retrieve_op_fns.append(retrieve_ops_fn) + + def load_ops(): + """Calls and returns the load ops for each embedding table. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_ops_list = [] + for load_op_fn in load_op_fns: + load_ops_list.extend(load_op_fn()) + return load_ops_list + + def retrieve_ops(): + """Calls and returns the retrieve ops for each embedding table. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_ops_list = [] + for retrieve_op_fn in retrieve_op_fns: + retrieve_ops_list.extend(retrieve_op_fn()) + return retrieve_ops_list + + return VariablesAndOps(embedding_variables_by_table, + slot_variables_by_table, load_ops, retrieve_ops) + + def generate_enqueue_ops( + self, + enqueue_datas_list, + mode_override=None, + ragged=False, + ): + """Generate enqueue ops. + + Args: + enqueue_datas_list: a list of dictionary mapping from string of feature + names to EnqueueData. Each dictionary is for one TPU core. Dictionaries + for the same host should be contiguous in the list. + mode_override: A string input that overrides the mode specified in the + TPUEmbeddingConfiguration. Supported values are {'unspecified', + 'inference', 'training', 'backward_pass_only'}. When set to + 'unspecified', the mode set in TPUEmbeddingConfiguration is used, + otherwise mode_override is used (optional). + ragged: If True, creates RaggedTensor enqueue ops rather than + SparseTensor. + + Returns: + Ops to enqueue to TPU for embedding. + """ + self._validate_generate_enqueue_ops_enqueue_datas_list(enqueue_datas_list) + return [ + self._generate_enqueue_op( # pylint: disable=g-complex-comprehension + enqueue_datas, + device_ordinal=i % self._num_cores_per_host, + mode_override=mode_override, + ragged=ragged, + ) for i, enqueue_datas in enumerate(enqueue_datas_list) + ] + + def _validate_generate_enqueue_ops_enqueue_datas_list(self, + enqueue_datas_list): + """Validate `enqueue_datas_list`.""" + + def _check_agreement(data, name, feature, enqueue_data): + """Helper function to check device agreement.""" + if (data is not None and + data.device != enqueue_data.embedding_indices.device): + raise ValueError('Device of {0} does not agree with that of' + 'embedding_indices for feature {1}.'.format( + name, feature)) + + feature_set = set(self._feature_to_config_dict.keys()) + contiguous_device = None + for i, enqueue_datas in enumerate(enqueue_datas_list): + used_feature_set = set(enqueue_datas.keys()) + + # Check features are valid. + missing_feature_set = feature_set - used_feature_set + if missing_feature_set: + raise ValueError('`enqueue_datas_list[{}]` misses a feature that is ' + 'in `feature_to_config_dict`: {}.'.format( + i, missing_feature_set)) + + extra_feature_set = used_feature_set - feature_set + if extra_feature_set: + raise ValueError('`enqueue_datas_list[{}]` has a feature that is not ' + 'in `feature_to_config_dict`: {}.'.format( + i, extra_feature_set)) + + device = None + device_feature = None + for feature, enqueue_data in enqueue_datas.items(): + combiner = self._table_to_config_dict[ + self._feature_to_config_dict[feature].table_id].combiner + + if isinstance(enqueue_data, EnqueueData): + if enqueue_data.sample_indices is None and combiner: + logging.warn( + 'No sample indices set for features %f table %f but ' + 'combiner is set to %s.', feature, + self._feature_to_config_dict[feature].table_id, combiner) + _check_agreement(enqueue_data.sample_indices, 'sample_indices', + feature, enqueue_data) + _check_agreement(enqueue_data.aggregation_weights, + 'aggregation_weights', feature, enqueue_data) + + elif isinstance(enqueue_data, RaggedEnqueueData): + if enqueue_data.row_splits is None and combiner: + logging.warn( + 'No row splits set for features %f table %f but ' + 'combiner is set to %s.', feature, + self._feature_to_config_dict[feature].table_id, combiner) + _check_agreement(enqueue_data.row_splits, 'row_splits', feature, + enqueue_data) + _check_agreement(enqueue_data.aggregation_weights, + 'aggregation_weights', feature, enqueue_data) + else: + raise ValueError( + '`enqueue_datas_list[{}]` has a feature that is not mapped to ' + '`EnqueueData` or `RaggedEnqueueData`. `feature`: {}'.format( + i, feature)) + # Check all features are on the same device. + if device is None: + device = enqueue_data.embedding_indices.device + device_feature = feature + else: + if device != enqueue_data.embedding_indices.device: + raise ValueError('Devices are different between features in ' + '`enqueue_datas_list[{}]`; ' + 'devices: {}, {}; features: {}, {}.'.format( + i, device, + enqueue_data.embedding_indices.device, feature, + device_feature)) + + if i % self._num_cores_per_host: + if device != contiguous_device: + raise ValueError('We expect the `enqueue_datas` which are on the ' + 'same host to be contiguous in ' + '`enqueue_datas_list`, ' + '`enqueue_datas_list[{}]` is on device {}, ' + 'but is expected to be on device {}.'.format( + i, device, contiguous_device)) + else: + contiguous_device = device + + def _generate_enqueue_op(self, + enqueue_datas, + device_ordinal, + mode_override=None, + ragged=False): + """Creates op for enqueuing batch to TPU.""" + enqueue_data0 = list(enqueue_datas.values())[0] + with ops.colocate_with(enqueue_data0.embedding_indices): + return tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch( + device_ordinal=device_ordinal, + combiners=self._combiners, + mode_override=mode_override, + **self._format_for_tpu_embedding_arbitrary_tensor_batch( + enqueue_datas, ragged)) + + def _format_for_tpu_embedding_arbitrary_tensor_batch(self, enqueue_datas, + ragged): + """Format features for `enqueue_tpu_embedding_arbitrary_tensor_batch()`. + + Args: + enqueue_datas: a `Dict` of `RaggedEnqueueData` objects for embedding. + ragged: If True, extract row splits from the data rather than sample + indices. + + Returns: + Dict of arguments for `enqueue_tpu_embedding_arbitrary_tensor_batch()`. + """ + + kwargs = { + 'sample_indices_or_row_splits': [], + 'embedding_indices': [], + 'aggregation_weights': [], + } + int_zeros = array_ops.zeros((0,), dtype=dtypes.int64) + float_zeros = array_ops.zeros((0,), dtype=dtypes.float32) + for table in self._table_to_features_dict: + features = self._table_to_features_dict[table] + for feature in features: + enqueue_data = enqueue_datas[feature] + if ragged: + kwargs['sample_indices_or_row_splits'].append( + enqueue_data.row_splits if enqueue_data + .row_splits is not None else int_zeros) + else: + if (self._feature_to_config_dict[feature].max_sequence_length > 0 and + enqueue_data.sample_indices is not None and + enqueue_data.sample_indices.shape[1] == 2): + # Pad the sample indices as if the enqueued sparse tensor is rank 2. + sample_indices = array_ops.pad( + enqueue_data.sample_indices, paddings=[[0, 0], [0, 1]]) + kwargs['sample_indices_or_row_splits'].append(sample_indices) + else: + # If the sample_indices is rank 1 or not present, treat it as dense + # tensor. + if (enqueue_data.sample_indices is None or + enqueue_data.sample_indices.shape[1] == 1): + kwargs['sample_indices_or_row_splits'].append(int_zeros) + else: + kwargs['sample_indices_or_row_splits'].append( + enqueue_data.sample_indices) + + kwargs['aggregation_weights'].append( + enqueue_data.aggregation_weights if enqueue_data + .aggregation_weights is not None else float_zeros) + + kwargs['embedding_indices'].append(enqueue_data.embedding_indices) + return kwargs + + def get_activations(self): + """Get activations for features. + + This should be called within `computation` that is passed to + `tpu.replicate` and friends. + + Returns: + A dictionary mapping from `String` of feature name to `Tensor` + of activation. + """ + recv_activations = tpu_ops.recv_tpu_embedding_activations( + num_outputs=len(self._feature_to_config_dict), + config=self._config_proto.SerializeToString()) + + activations = collections.OrderedDict() + index = 0 + for table in self._table_to_features_dict: + for feature in self._table_to_features_dict[table]: + activations[feature] = recv_activations[index] + index += 1 + return activations + + def generate_send_gradients_op(self, feature_to_gradient_dict, step=None): + """Send gradient to TPU embedding. + + Args: + feature_to_gradient_dict: dict mapping feature names to gradient wrt + activations. + step: the current global step, used for dynamic learning rate. + + Returns: + SendTPUEmbeddingGradients Op. + + Raises: + RuntimeError: If `mode` is not `TRAINING`. + """ + if self._mode != TRAINING: + raise RuntimeError('Only in training mode gradients need to ' + 'be sent to TPU embedding; got mode {}.'.format( + self._mode)) + if step is None and self._learning_rate_fn: + raise ValueError('There are dynamic learning rates but step is None.') + + gradients = [] + for table in self._table_to_features_dict: + for feature in self._table_to_features_dict[table]: + gradients.append(feature_to_gradient_dict[feature]) + + return tpu_ops.send_tpu_embedding_gradients( + inputs=gradients, + learning_rates=[ + math_ops.cast(fn(step), dtype=dtypes.float32) + for fn in self._learning_rate_fn + ], + config=self.config_proto.SerializeToString()) + + def _get_optimizer_handler_by_table(self): + optimizer_handlers = {} + for table, table_config in self.table_to_config_dict.items(): + if table_config.optimization_parameters is not None: + optimizer = table_config.optimization_parameters + else: + optimizer = self._optimization_parameters + optimizer_handlers[table] = _get_optimization_handler(optimizer) + + return optimizer_handlers + + +def _validate_table_to_config_dict(table_to_config_dict): + """Validate `table_to_config_dict`.""" + for k, v in table_to_config_dict.items(): + if not isinstance(v, TableConfig): + raise ValueError('Value of `table_to_config_dict` must be of type ' + '`TableConfig`, got {} for {}.'.format(type(v), k)) + + +def _validate_feature_to_config_dict(table_to_config_dict, + feature_to_config_dict): + """Validate `feature_to_config_dict`.""" + used_table_set = set( + [feature.table_id for feature in feature_to_config_dict.values()]) + table_set = set(table_to_config_dict.keys()) + + unused_table_set = table_set - used_table_set + if unused_table_set: + raise ValueError( + '`table_to_config_dict` specifies table that is not ' + 'used in `feature_to_config_dict`: {}.'.format(unused_table_set)) + + extra_table_set = used_table_set - table_set + if extra_table_set: + raise ValueError( + '`feature_to_config_dict` refers to a table that is not ' + 'specified in `table_to_config_dict`: {}.'.format(extra_table_set)) + + +def _validate_batch_size(batch_size, num_cores): + if batch_size % num_cores: + raise ValueError('`batch_size` is not a multiple of number of ' + 'cores. `batch_size`={}, `_num_cores`={}.'.format( + batch_size, num_cores)) + + +def _validate_optimization_parameters(optimization_parameters, + table_to_config_dict): + """Validate global optimization_parameters and per table optimizers. + + If global optimizer is `None`, all table optimizers should be non `None`. + + Args: + optimization_parameters: global optimizer provided in `TPUEmbedding` + constructor. + table_to_config_dict: A dictionary mapping from string of table name to + `TableConfig`. + """ + tbl_optimizer_missing = False + for _, table_config in table_to_config_dict.items(): + if table_config.optimization_parameters is None: + tbl_optimizer_missing = True + break + + if optimization_parameters: + if not isinstance(optimization_parameters, _OptimizationParameters): + raise ValueError('`optimization_parameters` must inherit from ' + '`_OptimizationParameters`. ' + '`type(optimization_parameters)`={}'.format( + type(optimization_parameters))) + else: + # Missing global optimization_parameters. + if tbl_optimizer_missing: + raise ValueError('`optimization_parameters` is missing.') + + +class _OptimizerHandler: + """Interface class for handling optimizer specific logic.""" + + def __init__(self, optimization_parameters): + self._optimization_parameters = optimization_parameters + + def get_optimization_parameters(self): + return self._optimization_parameters + + def set_optimization_parameters(self, table_descriptor): + raise NotImplementedError() + + def get_default_slot_variable_names(self, table): + raise NotImplementedError() + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + raise NotImplementedError() + + +class _AdagradHandler(_OptimizerHandler): + """Handles Adagrad specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.adagrad.SetInParent() + + def get_default_slot_variable_names(self, table): + return AdagradSlotVariableNames('{}/{}'.format(table, 'Adagrad')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + accumulator_initializer = init_ops.constant_initializer( + self._optimization_parameters.initial_accumulator) + accumulator_variables = _create_partitioned_variables( + name=slot_variable_names.accumulator, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=accumulator_initializer) + slot_variables = AdagradSlotVariables(accumulator_variables) + + def load_ops_fn(): + """Returns the retrieve ops for AdaGrad embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + config = config_proto + load_op_list = [] + for host_id, table_variable, accumulator_variable in zip( + range(num_hosts), table_variables, accumulator_variables): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_adagrad_parameters( + parameters=table_variable, + accumulators=accumulator_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for AdaGrad embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + config = config_proto + retrieve_op_list = [] + for host_id, table_variable, accumulator_variable in (zip( + range(num_hosts), table_variables, accumulator_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_accumulator = ( + tpu_ops.retrieve_tpu_embedding_adagrad_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(accumulator_variable, retrieved_accumulator)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _AdagradMomentumHandler(_OptimizerHandler): + """Handles Adagrad with Momentum specific logic. + + Creates slot variables and defines their initializers. Defines load/retrieve + operations to be used for loading variables into TPU memory (from host memory) + and retrieving variables from TPU memory (into host memory). + """ + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.adagrad_momentum.SetInParent() + table_descriptor.optimization_parameters.adagrad_momentum.momentum = ( + self._optimization_parameters.momentum) + table_descriptor.optimization_parameters.adagrad_momentum.use_nesterov = ( + self._optimization_parameters.use_nesterov) + table_descriptor.optimization_parameters.adagrad_momentum.exponent = ( + self._optimization_parameters.exponent) + table_descriptor.optimization_parameters.adagrad_momentum.beta2 = ( + self._optimization_parameters.beta2) + table_descriptor.optimization_parameters.adagrad_momentum.epsilon = ( + self._optimization_parameters.epsilon) + + def get_default_slot_variable_names(self, table): + return AdagradMomentumSlotVariableNames( + '{}/{}/Accumulator'.format(table, 'AdagradMomentum'), + '{}/{}/Momentum'.format(table, 'AdagradMomentum')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + accumulator_initializer = init_ops.zeros_initializer() + accumulator_variables = _create_partitioned_variables( + name=slot_variable_names.accumulator, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=accumulator_initializer) + momenta_initializer = init_ops.zeros_initializer() + momenta_variables = _create_partitioned_variables( + name=slot_variable_names.momenta, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=momenta_initializer) + slot_variables = AdagradMomentumSlotVariables(accumulator_variables, + momenta_variables) + + def load_ops_fn(): + """Returns the load ops for AdaGrad with momentum embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + config = config_proto + load_op_list = [] + for host_id, table_variable, accumulator_variable, momenta_variable in zip( + range(num_hosts), table_variables, accumulator_variables, + momenta_variables): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_adagrad_momentum_parameters( + parameters=table_variable, + accumulators=accumulator_variable, + momenta=momenta_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for AdaGrad with momentum embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + config = config_proto + retrieve_op_list = [] + for host_id, table_variable, accumulator_variable, momenta_variable in ( + zip( + range(num_hosts), table_variables, accumulator_variables, + momenta_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_accumulator, retrieved_momenta = ( + tpu_ops.retrieve_tpu_embedding_adagrad_momentum_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(accumulator_variable, retrieved_accumulator), + state_ops.assign(momenta_variable, retrieved_momenta)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _ProximalAdagradHandler(_OptimizerHandler): + """Handles ProximalAdagrad specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.proximal_adagrad.SetInParent() + table_descriptor.optimization_parameters.proximal_adagrad.l1 = ( + self._optimization_parameters.l1_regularization_strength) + table_descriptor.optimization_parameters.proximal_adagrad.l2 = ( + self._optimization_parameters.l2_regularization_strength) + + def get_default_slot_variable_names(self, table): + return ProximalAdagradSlotVariableNames('{}/{}'.format( + table, 'ProximalAdagrad')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + accumulator_initializer = init_ops.constant_initializer( + self._optimization_parameters.initial_accumulator) + accumulator_variables = _create_partitioned_variables( + name=slot_variable_names.accumulator, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=accumulator_initializer) + slot_variables = ProximalAdagradSlotVariables(accumulator_variables) + + def load_ops_fn(): + """Returns the retrieve ops for Proximal AdaGrad embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + config = config_proto + load_op_list = [] + for host_id, table_variable, accumulator_variable in zip( + range(num_hosts), table_variables, accumulator_variables): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_proximal_adagrad_parameters( + parameters=table_variable, + accumulators=accumulator_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Proximal AdaGrad embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + config = config_proto + retrieve_op_list = [] + for host_id, table_variable, accumulator_variable in (zip( + range(num_hosts), table_variables, accumulator_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_accumulator = ( + tpu_ops.retrieve_tpu_embedding_proximal_adagrad_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(accumulator_variable, retrieved_accumulator)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _AdamHandler(_OptimizerHandler): + """Handles Adam specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.adam.beta1 = ( + self._optimization_parameters.beta1) + table_descriptor.optimization_parameters.adam.beta2 = ( + self._optimization_parameters.beta2) + table_descriptor.optimization_parameters.adam.epsilon = ( + self._optimization_parameters.epsilon) + table_descriptor.optimization_parameters.adam.use_non_lazy_adam = ( + not self._optimization_parameters.lazy_adam) + table_descriptor.optimization_parameters.adam.use_sum_inside_sqrt = ( + self._optimization_parameters.sum_inside_sqrt) + + def get_default_slot_variable_names(self, table): + return AdamSlotVariableNames('{}/{}/m'.format(table, 'Adam'), + '{}/{}/v'.format(table, 'Adam')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + m_initializer = init_ops.zeros_initializer() + m_variables = _create_partitioned_variables( + name=slot_variable_names.m, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=m_initializer) + v_initializer = init_ops.zeros_initializer() + v_variables = _create_partitioned_variables( + name=slot_variable_names.v, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=v_initializer) + slot_variables = AdamSlotVariables(m_variables, v_variables) + + def load_ops_fn(): + """Returns the retrieve ops for AdaGrad embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable, m_variable, v_variable in (zip( + range(num_hosts), table_variables, m_variables, v_variables)): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_adam_parameters( + parameters=table_variable, + momenta=m_variable, + velocities=v_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + # Set config to None to enforce that config is only loaded to the first + # table. + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Adam embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable, m_variable, v_variable in (zip( + range(num_hosts), table_variables, m_variables, v_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_m, retrieved_v = ( + tpu_ops.retrieve_tpu_embedding_adam_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(m_variable, retrieved_m), + state_ops.assign(v_variable, retrieved_v)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _FtrlHandler(_OptimizerHandler): + """Handles Ftrl specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.ftrl.lr_power = ( + self._optimization_parameters.learning_rate_power) + table_descriptor.optimization_parameters.ftrl.l1 = ( + self._optimization_parameters.l1_regularization_strength) + table_descriptor.optimization_parameters.ftrl.l2 = ( + self._optimization_parameters.l2_regularization_strength) + table_descriptor.optimization_parameters.ftrl.multiply_linear_by_lr = ( + self._optimization_parameters.multiply_linear_by_learning_rate) + table_descriptor.optimization_parameters.ftrl.beta = ( + self._optimization_parameters.beta) + table_descriptor.optimization_parameters.ftrl.allow_zero_accumulator = ( + self._optimization_parameters.allow_zero_accumulator) + + def get_default_slot_variable_names(self, table): + # These match the default slot variable names created by + # tf.train.FtrlOptimizer. + return FtrlSlotVariableNames( + '{}/{}'.format(table, 'Ftrl'), # accumulator + '{}/{}'.format(table, 'Ftrl_1')) # linear + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + accumulator_initializer = init_ops.constant_initializer( + self._optimization_parameters.initial_accumulator_value) + accumulator_variables = _create_partitioned_variables( + name=slot_variable_names.accumulator, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=accumulator_initializer) + linear_initializer = init_ops.constant_initializer( + self._optimization_parameters.initial_linear_value) + linear_variables = _create_partitioned_variables( + name=slot_variable_names.linear, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=linear_initializer) + slot_variables = FtrlSlotVariable(accumulator_variables, linear_variables) + + def load_ops_fn(): + """Returns the retrieve ops for Ftrl embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + config = config_proto + load_op_list = [] + for host_id, table_variable, accumulator_variable, linear_variable in zip( + range(num_hosts), table_variables, accumulator_variables, + linear_variables): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_ftrl_parameters( + parameters=table_variable, + accumulators=accumulator_variable, + linears=linear_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Ftrl embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + config = config_proto + retrieve_op_list = [] + for host_id, table_variable, accumulator_variable, linear_variable in zip( + range(num_hosts), table_variables, accumulator_variables, + linear_variables): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_accumulator, retrieved_linear = ( + tpu_ops.retrieve_tpu_embedding_ftrl_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(accumulator_variable, retrieved_accumulator), + state_ops.assign(linear_variable, retrieved_linear)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _ProximalYogiHandler(_OptimizerHandler): + """Handles Proximal Yogi specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.proximal_yogi.SetInParent() + table_descriptor.optimization_parameters.proximal_yogi.beta1 = ( + self._optimization_parameters.beta1) + table_descriptor.optimization_parameters.proximal_yogi.beta2 = ( + self._optimization_parameters.beta2) + table_descriptor.optimization_parameters.proximal_yogi.epsilon = ( + self._optimization_parameters.epsilon) + table_descriptor.optimization_parameters.proximal_yogi.l1 = ( + self._optimization_parameters.l1_regularization_strength) + table_descriptor.optimization_parameters.proximal_yogi.l2 = ( + self._optimization_parameters.l2_regularization_strength) + + def get_default_slot_variable_names(self, table): + return ProximalYogiSlotVariableNames( + '{}/{}'.format(table, 'ProximalYogi'), # v + '{}/{}_1'.format(table, 'ProximalYogi')) # m + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + v_initializer = init_ops.constant_initializer( + self._optimization_parameters.initial_accumulator_value) + v_variables = _create_partitioned_variables( + name=slot_variable_names.v, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=v_initializer) + m_initializer = init_ops.zeros_initializer() + m_variables = _create_partitioned_variables( + name=slot_variable_names.m, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=m_initializer) + slot_variables = ProximalYogiSlotVariables(v_variables, m_variables) + + def load_ops_fn(): + """Returns the load ops for Proximal Yogi embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable, v_variable, m_variable in (zip( + range(num_hosts), table_variables, v_variables, m_variables)): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_proximal_yogi_parameters( + parameters=table_variable, + v=v_variable, + m=m_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + # Set config to None to enforce that config is only loaded to the first + # table. + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Proximal Yogi embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable, v_variable, m_variable in (zip( + range(num_hosts), table_variables, v_variables, m_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_v, retrieved_m = ( + tpu_ops.retrieve_tpu_embedding_proximal_yogi_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(v_variable, retrieved_v), + state_ops.assign(m_variable, retrieved_m)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _MomentumHandler(_OptimizerHandler): + """Handles Momentum specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + (table_descriptor.optimization_parameters.momentum.SetInParent()) + table_descriptor.optimization_parameters.momentum.momentum = ( + self._optimization_parameters.momentum) + table_descriptor.optimization_parameters.momentum.use_nesterov = ( + self._optimization_parameters.use_nesterov) + + def get_default_slot_variable_names(self, table): + return MomentumSlotVariableNames('{}/{}'.format(table, 'Momentum')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + + momenta_initializer = init_ops.zeros_initializer() + momenta_variables = _create_partitioned_variables( + name=slot_variable_names.momenta, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=momenta_initializer) + slot_variables = MomentumSlotVariables(momenta_variables) + + def load_ops_fn(): + """Returns the retrieve ops for Momentum embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable, momenta_variable in (zip( + range(num_hosts), table_variables, momenta_variables)): + with ops.colocate_with(table_variable): + load_parameters_op = tpu_ops.load_tpu_embedding_momentum_parameters( + parameters=table_variable, + momenta=momenta_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config, + ) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Momentum embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable, momenta_variable in (zip( + range(num_hosts), table_variables, momenta_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_momenta = ( + tpu_ops.retrieve_tpu_embedding_momentum_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config, + )) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(momenta_variable, retrieved_momenta)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _RMSPropHandler(_OptimizerHandler): + """Handles RMS prop specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + (table_descriptor.optimization_parameters.rms_prop.SetInParent()) + table_descriptor.optimization_parameters.rms_prop.rho = ( + self._optimization_parameters.rho) + table_descriptor.optimization_parameters.rms_prop.epsilon = ( + self._optimization_parameters.epsilon) + table_descriptor.optimization_parameters.rms_prop.momentum = ( + self._optimization_parameters.momentum) + + def get_default_slot_variable_names(self, table): + return RMSPropSlotVariableNames('{}/{}/ms'.format(table, 'RMSProp'), + '{}/{}/mom'.format(table, 'RMSProp')) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + + ms_variables = _create_partitioned_variables( + name=slot_variable_names.ms, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=init_ops.zeros_initializer(), + ) + mom_variables = _create_partitioned_variables( + name=slot_variable_names.mom, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=init_ops.zeros_initializer(), + ) + slot_variables = RMSPropSlotVariables(ms_variables, mom_variables) + + def load_ops_fn(): + """Returns the retrieve ops for RMS Prop embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable, ms_variable, mom_variable in (zip( + range(num_hosts), table_variables, ms_variables, mom_variables)): + with ops.colocate_with(table_variable): + load_parameters_op = tpu_ops.load_tpu_embedding_rms_prop_parameters( + parameters=table_variable, + ms=ms_variable, + mom=mom_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config, + ) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for RMS Prop embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable, ms_variable, mom_variable in (zip( + range(num_hosts), table_variables, ms_variables, mom_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_ms, retrieved_mom = ( + tpu_ops.retrieve_tpu_embedding_rms_prop_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config, + )) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(ms_variable, retrieved_ms), + state_ops.assign(mom_variable, retrieved_mom)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _FrequencyEstimatorHandler(_OptimizerHandler): + """Handles frequency estimator specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + table_descriptor.optimization_parameters.frequency_estimator.SetInParent() + freq = table_descriptor.optimization_parameters.frequency_estimator + freq.tau = self._optimization_parameters.tau + freq.max_delta = self._optimization_parameters.max_delta + freq.outlier_threshold = self._optimization_parameters.outlier_threshold + freq.weight_exponent = self._optimization_parameters.weight_exponent + + def get_default_slot_variable_names(self, table): + return FrequencyEstimatorSlotVariableNames( + '{}/FrequencyEstimator'.format(table)) + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + if table_config.dimension != 1: + raise ValueError('FrequencyEstimator tables should only have a dimension ' + 'of 1. Received dimension {}'.format( + table_config.dimension)) + + last_hit_step_variables = _create_partitioned_variables( + name=slot_variable_names.last_hit_step, + num_hosts=num_hosts, + vocabulary_size=table_config.vocabulary_size, + embedding_dimension=table_config.dimension, + collections=[ops.GraphKeys.GLOBAL_VARIABLES], + initializer=init_ops.zeros_initializer(), + ) + slot_variables = FrequencyEstimatorSlotVariables(last_hit_step_variables) + + def load_ops_fn(): + """Returns the retrieve ops for Frequency Estimator embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable, last_hit_step_variable in (zip( + range(num_hosts), table_variables, last_hit_step_variables)): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_frequency_estimator_parameters( + parameters=table_variable, + last_hit_step=last_hit_step_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for Frequency Estimator embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable, last_hit_step_variable in (zip( + range(num_hosts), table_variables, last_hit_step_variables)): + with ops.colocate_with(table_variable): + retrieved_table, retrieved_last_hit_step = ( + tpu_ops.retrieve_tpu_embedding_frequency_estimator_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config, + )) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table), + state_ops.assign(last_hit_step_variable, retrieved_last_hit_step)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return slot_variables, load_ops_fn, retrieve_ops_fn + + +class _StochasticGradientDescentHandler(_OptimizerHandler): + """Handles stochastic gradient descent specific logic.""" + + def set_optimization_parameters(self, table_descriptor): + (table_descriptor.optimization_parameters.stochastic_gradient_descent + .SetInParent()) + + def get_default_slot_variable_names(self, table): + return None + + def create_variables_and_ops(self, table, slot_variable_names, num_hosts, + table_config, table_variables, config_proto): + del table_config + + def load_ops_fn(): + """Returns the retrieve ops for AdaGrad embedding tables. + + Returns: + A list of ops to load embedding and slot variables from CPU to TPU. + """ + load_op_list = [] + config = config_proto + for host_id, table_variable in enumerate(table_variables): + with ops.colocate_with(table_variable): + load_parameters_op = ( + tpu_ops.load_tpu_embedding_stochastic_gradient_descent_parameters( + parameters=table_variable, + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + config = None + load_op_list.append(load_parameters_op) + return load_op_list + + def retrieve_ops_fn(): + """Returns the retrieve ops for SGD embedding tables. + + Returns: + A list of ops to retrieve embedding and slot variables from TPU to CPU. + """ + retrieve_op_list = [] + config = config_proto + for host_id, table_variable in enumerate(table_variables): + with ops.colocate_with(table_variable): + retrieved_table = ( + tpu_ops + .retrieve_tpu_embedding_stochastic_gradient_descent_parameters( + table_name=table, + num_shards=num_hosts, + shard_id=host_id, + config=config)) + retrieve_parameters_op = control_flow_ops.group( + state_ops.assign(table_variable, retrieved_table)) + config = None + retrieve_op_list.append(retrieve_parameters_op) + return retrieve_op_list + + return None, load_ops_fn, retrieve_ops_fn + + +def _get_optimization_handler(optimization_parameters): + """Gets the optimization handler given the parameter type.""" + if isinstance(optimization_parameters, AdagradParameters): + return _AdagradHandler(optimization_parameters) + elif isinstance(optimization_parameters, AdagradMomentumParameters): + return _AdagradMomentumHandler(optimization_parameters) + elif isinstance(optimization_parameters, ProximalAdagradParameters): + return _ProximalAdagradHandler(optimization_parameters) + elif isinstance(optimization_parameters, AdamParameters): + return _AdamHandler(optimization_parameters) + elif isinstance(optimization_parameters, FtrlParameters): + return _FtrlHandler(optimization_parameters) + elif isinstance(optimization_parameters, ProximalYogiParameters): + return _ProximalYogiHandler(optimization_parameters) + elif isinstance(optimization_parameters, StochasticGradientDescentParameters): + return _StochasticGradientDescentHandler(optimization_parameters) + elif isinstance(optimization_parameters, MomentumParameters): + return _MomentumHandler(optimization_parameters) + elif isinstance(optimization_parameters, RMSPropParameters): + return _RMSPropHandler(optimization_parameters) + elif isinstance(optimization_parameters, FrequencyEstimatorParameters): + return _FrequencyEstimatorHandler(optimization_parameters) + return NotImplementedError() + + +def _create_ordered_dict(d): + """Create an OrderedDict from Dict.""" + return collections.OrderedDict((k, d[k]) for k in sorted(d)) + + +def _create_combiners(table_to_config_dict, table_to_features_dict): + """Create a per feature list of combiners, ordered by table.""" + combiners = [] + for table in table_to_config_dict: + combiner = table_to_config_dict[table].combiner or 'sum' + combiners.extend([combiner] * len(table_to_features_dict[table])) + return combiners + + +def _create_table_to_features_dict(feature_to_config_dict): + """Create mapping from table to a list of its features.""" + table_to_features_dict_tmp = {} + for feature, feature_config in feature_to_config_dict.items(): + if feature_config.table_id in table_to_features_dict_tmp: + table_to_features_dict_tmp[feature_config.table_id].append(feature) + else: + table_to_features_dict_tmp[feature_config.table_id] = [feature] + + table_to_features_dict = collections.OrderedDict() + for table in sorted(table_to_features_dict_tmp): + table_to_features_dict[table] = sorted(table_to_features_dict_tmp[table]) + return table_to_features_dict + + +def _create_device_fn(hosts): + """Create device_fn() to use with _create_partitioned_variables().""" + + def device_fn(op): + """Returns the `device` for `op`.""" + part_match = re.match(r'.*/part_(\d+)(/|$)', op.name) + dummy_match = re.match(r'.*dummy_(\d+).*', op.name) + if not part_match and not dummy_match: + raise RuntimeError( + 'Internal Error: Expected {} to contain /part_* or dummy_*'.format( + op.name)) + + if part_match: + idx = int(part_match.group(1)) + else: + idx = int(dummy_match.group(1)) # pytype: disable=attribute-error + + device = hosts[idx] + logging.debug('assigning {} to {}.', op, device) + return device + + return device_fn + + +def _create_partitioned_variables(name, + num_hosts, + vocabulary_size, + embedding_dimension, + initializer, + collections=None): # pylint: disable=redefined-outer-name + """Creates PartitionedVariables based on `num_hosts` for `table`.""" + + num_slices = min(vocabulary_size, num_hosts) + + var_list = list( + variable_scope.get_variable( + name, + shape=(vocabulary_size, embedding_dimension), + partitioner=partitioned_variables.fixed_size_partitioner(num_slices), + dtype=dtypes.float32, + initializer=initializer, + collections=collections, + trainable=False)) + + if vocabulary_size >= num_hosts: + return var_list + + # For padded part, define the dummy variable to be loaded into TPU system. + for idx in range(num_hosts - vocabulary_size): + var_list.append( + variable_scope.get_variable( + 'dummy_{}_{}'.format(vocabulary_size + idx, name), + shape=(1, embedding_dimension), + dtype=dtypes.float32, + initializer=initializer, + collections=[ops.GraphKeys.LOCAL_VARIABLES], + trainable=False)) + + return var_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1f064359d77631b6de47634eeab7954b477cdf49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_base.py @@ -0,0 +1,145 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base Class for TPU Embeddings Mid level APIs.""" + +import functools +from typing import Any, Dict, Iterable, Optional, Union, Text + +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.tpu import tpu_embedding_v2_utils +from tensorflow.python.trackable import autotrackable +from tensorflow.python.util import nest + + +class TPUEmbeddingBase(autotrackable.AutoTrackable): + """The TPUEmbedding Base class. + + This class only contains the basic logic to check the feature config and table + config for the tpu embedding mid level APIs. + """ + + def __init__( + self, + feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable], # pylint:disable=g-bare-generic + optimizer: Optional[tpu_embedding_v2_utils._Optimizer] = None): # pylint:disable=protected-access + """Creates the TPUEmbeddingBase object.""" + self._feature_config = feature_config + self._output_shapes = [] + for feature in nest.flatten(feature_config): + self._output_shapes.append(feature.output_shape) + # Set table order here to the order of the first occurrence of the table in + # a feature provided by the user. The order of this struct must be fixed + # to provide the user with deterministic behavior over multiple + # instantiations. + self._table_config = [] + for feature in nest.flatten(feature_config): + if feature.table not in self._table_config: + self._table_config.append(feature.table) + + # Ensure tables have unique names. Also error check the optimizer as we + # specifically don't do that in the TableConfig class to allow high level + # APIs that are built on this to use strings/other classes to represent + # optimizers (before they are passed to this class). + table_names = [] + for i, table in enumerate(self._table_config): + if table.optimizer is None: + # TODO(bfontain) Should we allow some sort of optimizer merging here? + table.optimizer = optimizer + if (table.optimizer is not None and + not isinstance(table.optimizer, tpu_embedding_v2_utils._Optimizer)): # pylint: disable=protected-access + raise ValueError("{} is an unsupported optimizer class. Please pass an " + "instance of one of the optimizer classes under " + "tf.tpu.experimental.embedding.".format( + type(table.optimizer))) + if table.name is None: + table.name = "table_{}".format(i) + if table.name in table_names: + raise ValueError("Tables must have a unique name. " + f"Multiple tables with name {table.name} found.") + table_names.append(table.name) + + self._built = False + + @property + def embedding_tables(self): + """Returns a dict of embedding tables, keyed by `TableConfig`.""" + raise NotImplementedError + + def _create_variables(self, table: tpu_embedding_v2_utils.TableConfig, + trainable: bool) -> Dict[Text, tf_variables.Variable]: + """Create all variables including table variables and slot variables.""" + variable_shape = (table.vocabulary_size, table.dim) + + def getter(name, shape, dtype, initializer, trainable): + del shape + # _add_variable_with_custom_getter clears the shape sometimes, so we + # take the global shape from outside the getter. + initial_value = functools.partial( + initializer, variable_shape, dtype=dtype) + return tf_variables.Variable( + name=name, + initial_value=initial_value, + shape=variable_shape, + dtype=dtype, + trainable=trainable) + + def variable_creator(name, initializer, trainable=True): + # Use add_variable_with_custom_getter here so that we take advantage of + # the checkpoint loading to allow restore before the variables get + # created which avoids double initialization. + return self._add_variable_with_custom_getter( + name=name, + initializer=initializer, + shape=variable_shape, + dtype=dtypes.float32, + getter=getter, + trainable=trainable) + + parameters = variable_creator( + table.name, table.initializer, trainable=trainable) + + def slot_creator(name, initializer): + return variable_creator(table.name + "/" + name, initializer, False) + + if table.optimizer is not None: + slot_vars = table.optimizer._create_slots(parameters, slot_creator) # pylint: disable=protected-access + else: + slot_vars = {} + slot_vars["parameters"] = parameters + return slot_vars + + def _create_variables_and_slots(self): + """Create variables and slots variables for TPU embeddings.""" + raise NotImplementedError + + def build(self): + """Create variables and slots variables for TPU embeddings.""" + if self._built: + return + self._variables = self._create_variables_and_slots() + self._built = True + + def __call__(self, features: Any, weights: Optional[Any] = None) -> Any: + """Call the mid level api to do embedding lookup.""" + if not self._built: + self.build() + return self.embedding_lookup(features, weights) + + def embedding_lookup(self, + features: Any, + weights: Optional[Any] = None) -> Any: + """Lookup the embedding table using the input features.""" + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_for_serving.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_for_serving.py new file mode 100644 index 0000000000000000000000000000000000000000..c35ac0958930adfe6c79fd3702c9374ca5bf12a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_for_serving.py @@ -0,0 +1,569 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Mid level API for Serving TPU Embeddings.""" +import functools +from typing import Any, Dict, Iterable, Optional, Union + +from absl import logging + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.tpu import tpu_embedding_base +from tensorflow.python.tpu import tpu_embedding_v2_utils +from tensorflow.python.trackable import base as trackable_base +from tensorflow.python.types import core +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("tpu.experimental.embedding.TPUEmbeddingForServing") +class TPUEmbeddingForServing(tpu_embedding_base.TPUEmbeddingBase): + """The TPUEmbedding mid level API running on CPU for serving. + + Note: This class is intended to be used for embedding tables that are trained + on TPU and to be served on CPU. Therefore the class should be only initialized + under non-TPU strategy. Otherwise an error will be raised. + + You can first train your model using the TPUEmbedding class and save the + checkpoint. Then use this class to restore the checkpoint to do serving. + + First train a model and save the checkpoint. + ```python + model = model_fn(...) + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + + # Your custom training code. + + checkpoint = tf.train.Checkpoint(model=model, embedding=embedding) + checkpoint.save(...) + + ``` + + Then restore the checkpoint and do serving. + ```python + + # Restore the model on CPU. + model = model_fn(...) + embedding = tf.tpu.experimental.embedding.TPUEmbeddingForServing( + feature_config=feature_config, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + + checkpoint = tf.train.Checkpoint(model=model, embedding=embedding) + checkpoint.restore(...) + + result = embedding(...) + table = embedding.embedding_table + ``` + + NOTE: This class can also be used to do embedding training on CPU. But it + requires the conversion between keras optimizer and embedding optimizers so + that the slot variables can stay consistent between them. + """ + + def __init__( + self, + feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable], # pylint:disable=g-bare-generic + optimizer: Optional[tpu_embedding_v2_utils._Optimizer], + experimental_sparsecore_restore_info: Optional[Dict[str, Any]] = None): # pylint:disable=protected-access + """Creates the TPUEmbeddingForServing mid level API object. + + ```python + embedding = tf.tpu.experimental.embedding.TPUEmbeddingForServing( + feature_config=tf.tpu.experimental.embedding.FeatureConfig( + table=tf.tpu.experimental.embedding.TableConfig( + dim=..., + vocabulary_size=...))) + ``` + + Args: + feature_config: A nested structure of + `tf.tpu.experimental.embedding.FeatureConfig` configs. + optimizer: An instance of one of `tf.tpu.experimental.embedding.SGD`, + `tf.tpu.experimental.embedding.Adagrad` or + `tf.tpu.experimental.embedding.Adam`. When not created under TPUStrategy + may be set to None to avoid the creation of the optimizer slot + variables, useful for optimizing memory consumption when exporting the + model for serving where slot variables aren't needed. + experimental_sparsecore_restore_info: Information from the sparse core + training, required to restore from checkpoint for serving (like number + of TPU devices used `num_tpu_devices`.) + + Raises: + RuntimeError: If created under TPUStrategy. + """ + super(TPUEmbeddingForServing, self).__init__(feature_config, optimizer) + self._strategy = distribute_lib.get_strategy() + self._experimental_sparsecore_restore_info = ( + experimental_sparsecore_restore_info + ) + if isinstance(self._strategy, + (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV2)): + raise RuntimeError("Serving on TPU is not yet supported.") + + @property + def embedding_tables( + self) -> Dict[tpu_embedding_v2_utils.TableConfig, tf_variables.Variable]: + """Returns a dict of embedding tables, keyed by `TableConfig`.""" + self._maybe_build() + # Only return the tables and not the slot variables. + return { + table: self._variables[table.name]["parameters"] + for table in self._table_config + } + + def _maybe_build(self): + if not self._built: + # This can be called while tracing a function, so we wrap the + # initialization code with init_scope so it runs eagerly, this means that + # it will not be included the function graph generated by tracing so that + # we can be sure that we only initialize the TPU for embeddings exactly + # once. + with ops.init_scope(): + self.build() + + def _unshuffle_from_sc_to_cpu(self, t: tensor.Tensor) -> tensor.Tensor: + if self._experimental_sparsecore_restore_info is None: + return t + if "num_tpu_devices" not in self._experimental_sparsecore_restore_info: + raise ValueError( + "Missing `num_tpu_devices` in `experimental_sparsecore_restore_info`" + ) + if "num_sc_chips_per_tpu" not in self._experimental_sparsecore_restore_info: + raise ValueError( + "Missing `num_sc_chips_per_tpu` in" + " `experimental_sparsecore_restore_info`" + ) + num_sc_devices = ( + self._experimental_sparsecore_restore_info["num_tpu_devices"] + * self._experimental_sparsecore_restore_info["num_sc_chips_per_tpu"] + ) + old_shape = t.shape + # The width of the table must be a multiple of number of SC devices. The + # tpu strategy does this round off at training time so we expect the + # checkpoints value to meet this requirement. + assert t.shape[0] % num_sc_devices == 0 + intermediate_tensor = array_ops.reshape( + t, (num_sc_devices, t.shape[0] // num_sc_devices, t.shape[1]) + ) + intermediate_tensor = array_ops.transpose(intermediate_tensor, (1, 0, 2)) + return array_ops.reshape(intermediate_tensor, old_shape) + + def _remove_padding_from_sc( + self, value_in_checkpoint: tensor.Tensor, variable_shape: tuple[int, int] + ) -> tensor.Tensor: + checkpoint_value_shape = value_in_checkpoint.shape.as_list() + # If the checkpoint shape is at least the size of the variable, we conclude + # that the extra rows and cols must be padding. + is_init_value_padded = all( + [i >= j for i, j in zip(checkpoint_value_shape, variable_shape)] + ) + if not is_init_value_padded: + return value_in_checkpoint + # checkpoint has padding so we can remove it. + begin = [0] * len(checkpoint_value_shape) + return array_ops.slice( + value_in_checkpoint, begin=begin, size=variable_shape + ) + + def _create_variables( + self, table: tpu_embedding_v2_utils.TableConfig, trainable: bool + ) -> Dict[str, tf_variables.Variable]: + """Create all variables including table variables and slot variables.""" + variable_shape = (table.vocabulary_size, table.dim) + + def getter(name, shape, dtype, initializer, trainable): + # _add_variable_with_custom_getter clears the shape sometimes, so we + # take the global shape from outside the getter. + del shape + if isinstance(initializer, trackable_base.CheckpointInitialValueCallable): + checkpoint_init_value = initializer(variable_shape).wrapped_value + restore_uid = initializer.restore_uid + unshuffled = self._unshuffle_from_sc_to_cpu(checkpoint_init_value) + truncated = self._remove_padding_from_sc(unshuffled, variable_shape) + var = tf_variables.Variable( + name=name, + initial_value=truncated, + shape=variable_shape, + dtype=dtype, + trainable=trainable, + ) + # Maybe initialize the variable + var._maybe_initialize_trackable() # pylint:disable=protected-access + # Update the uid for this variable from the checkpoint init value. + # This lets the checkpoint deferred restoration code know that this + # variable was restored while creation, so no need to restore it from + # the checkpoint later. + if restore_uid is not None: + var._update_uid = initializer.restore_uid # pylint:disable=protected-access + return var + + initial_value = functools.partial( + initializer, variable_shape, dtype=dtype + ) + return tf_variables.Variable( + name=name, + initial_value=initial_value, + shape=variable_shape, + dtype=dtype, + trainable=trainable, + ) + + def variable_creator(name, initializer, shape, trainable=True): + # Use add_variable_with_custom_getter here so that we take advantage of + # the checkpoint loading to allow restore before the variables get + # created which avoids double initialization. + return self._add_variable_with_custom_getter( + name=name, + initializer=initializer, + shape=shape, + dtype=dtypes.float32, + getter=getter, + trainable=trainable, + ) + + parameters = variable_creator( + table.name, table.initializer, variable_shape, trainable=trainable + ) + + def slot_creator(name, initializer): + return variable_creator(table.name + "/" + name, initializer, False) + + if table.optimizer is not None: + slot_vars = table.optimizer._create_slots(parameters, slot_creator) # pylint: disable=protected-access + else: + slot_vars = {} + slot_vars["parameters"] = parameters + return slot_vars + + def _create_variables_and_slots( + self, + ) -> Dict[str, Dict[str, tf_variables.Variable]]: + """Create variables for TPU embeddings. + + Returns: + A dict of dicts. The outer dict is keyed by the table names and the inner + dicts are keyed by 'parameters' and the slot variable names. + """ + variables = {} + for table in self._table_config: + variables[table.name] = self._create_variables(table, trainable=True) + return variables + + def embedding_lookup(self, + features: Any, + weights: Optional[Any] = None) -> Any: + """Apply standard lookup ops on CPU. + + Args: + features: A nested structure of `tf.Tensor`s, `tf.SparseTensor`s or + `tf.RaggedTensor`s, with the same structure as `feature_config`. Inputs + will be downcast to `tf.int32`. Only one type out of `tf.SparseTensor` + or `tf.RaggedTensor` is supported per call. + weights: If not `None`, a nested structure of `tf.Tensor`s, + `tf.SparseTensor`s or `tf.RaggedTensor`s, matching the above, except + that the tensors should be of float type (and they will be downcast to + `tf.float32`). For `tf.SparseTensor`s we assume the `indices` are the + same for the parallel entries from `features` and similarly for + `tf.RaggedTensor`s we assume the row_splits are the same. + + Returns: + A nested structure of Tensors with the same structure as input features. + """ + return cpu_embedding_lookup(features, weights, self.embedding_tables, + self._feature_config) + + +def _ragged_embedding_lookup_with_reduce( + table: tf_variables.Variable, + ragged: ragged_tensor.RaggedTensor, + weights: ragged_tensor.RaggedTensor, + combiner: str, +) -> core.Tensor: + """Compute a ragged lookup followed by a reduce on axis 1. + + Args: + table: The embedding table. + ragged: A RaggedTensor of ids to look up. + weights: A RaggedTensor of weights (or None). + combiner: One of "mean", "sum", "sqrtn". + + Returns: + A Tensor. + """ + if weights is None: + weights = array_ops.ones_like(ragged, dtype=table.dtype) + weights = array_ops.expand_dims(weights, axis=2) + ragged_result = embedding_ops.embedding_lookup(table, ragged) + ragged_result = math_ops.reduce_sum(ragged_result * weights, axis=1) + if combiner == "mean": + ragged_result = math_ops.div_no_nan(ragged_result, + math_ops.reduce_sum(weights, axis=1)) + elif combiner == "sqrtn": + ragged_result = math_ops.div_no_nan( + ragged_result, + math_ops.sqrt(math_ops.reduce_sum(weights * weights, axis=1))) + return ragged_result + + +@tf_export("tpu.experimental.embedding.serving_embedding_lookup") +def cpu_embedding_lookup( + inputs: Any, + weights: Optional[Any], + tables: Dict[tpu_embedding_v2_utils.TableConfig, tf_variables.Variable], + feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable] # pylint:disable=g-bare-generic +) -> Any: + """Apply standard lookup ops with `tf.tpu.experimental.embedding` configs. + + This function is a utility which allows using the + `tf.tpu.experimental.embedding` config objects with standard lookup functions. + This can be used when exporting a model which uses + `tf.tpu.experimental.embedding.TPUEmbedding` for serving on CPU. In particular + `tf.tpu.experimental.embedding.TPUEmbedding` only supports lookups on TPUs and + should not be part of your serving graph. + + Note that TPU specific options (such as `max_sequence_length`) in the + configuration objects will be ignored. + + In the following example we take a trained model (see the documentation for + `tf.tpu.experimental.embedding.TPUEmbedding` for the context) and create a + saved model with a serving function that will perform the embedding lookup and + pass the results to your model: + + ```python + model = model_fn(...) + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=1024, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + checkpoint = tf.train.Checkpoint(model=model, embedding=embedding) + checkpoint.restore(...) + + @tf.function(input_signature=[{'feature_one': tf.TensorSpec(...), + 'feature_two': tf.TensorSpec(...), + 'feature_three': tf.TensorSpec(...)}]) + def serve_tensors(embedding_features): + embedded_features = tf.tpu.experimental.embedding.serving_embedding_lookup( + embedding_features, None, embedding.embedding_tables, + feature_config) + return model(embedded_features) + + model.embedding_api = embedding + tf.saved_model.save(model, + export_dir=..., + signatures={'serving_default': serve_tensors}) + + ``` + + NOTE: It's important to assign the embedding API object to a member of your + model as `tf.saved_model.save` only supports saving variables as one + `Trackable` object. Since the model's weights are in `model` and the + embedding table are managed by `embedding`, we assign `embedding` to an + attribute of `model` so that tf.saved_model.save can find the embedding + variables. + + NOTE: The same `serve_tensors` function and `tf.saved_model.save` call will + work directly from training. + + Args: + inputs: a nested structure of Tensors, SparseTensors or RaggedTensors. + weights: a nested structure of Tensors, SparseTensors or RaggedTensors or + None for no weights. If not None, structure must match that of inputs, but + entries are allowed to be None. + tables: a dict of mapping TableConfig objects to Variables. + feature_config: a nested structure of FeatureConfig objects with the same + structure as inputs. + + Returns: + A nested structure of Tensors with the same structure as inputs. + """ + + nest.assert_same_structure(inputs, feature_config) + + flat_inputs = nest.flatten(inputs) + flat_weights = [None] * len(flat_inputs) + if weights is not None: + nest.assert_same_structure(inputs, weights) + flat_weights = nest.flatten(weights) + flat_features = nest.flatten_with_joined_string_paths(feature_config) + + outputs = [] + for inp, weight, (path, feature) in zip(flat_inputs, flat_weights, + flat_features): + table = tables[feature.table] + + if weight is not None: + if isinstance(inp, tensor.Tensor): + raise ValueError( + "Weight specified for {}, but input is dense.".format(path)) + elif type(weight) is not type(inp): + raise ValueError( + "Weight for {} is of type {} but it does not match type of the " + "input which is {}.".format(path, type(weight), type(inp))) + elif feature.max_sequence_length > 0: + raise ValueError("Weight specified for {}, but this is a sequence " + "feature.".format(path)) + + if isinstance(inp, tensor.Tensor): + if feature.max_sequence_length > 0: + raise ValueError("Feature {} is a sequence feature but a dense tensor " + "was passed.".format(path)) + outputs.append(embedding_ops.embedding_lookup_v2(table, inp)) + + elif isinstance(inp, sparse_tensor.SparseTensor): + outputs.append( + _embedding_lookup_for_sparse_tensor(inp, weight, table, feature)) + elif isinstance(inp, ragged_tensor.RaggedTensor): + outputs.append( + _embedding_lookup_for_ragged_tensor(inp, weight, table, feature)) + else: + raise ValueError("Input {} is type {}. Tensor, SparseTensor or " + "RaggedTensor expected.".format(path, type(inp))) + return nest.pack_sequence_as(feature_config, outputs) + + +def _embedding_lookup_for_sparse_tensor( + inp: sparse_tensor.SparseTensor, + weight: Optional[sparse_tensor.SparseTensor], table: tf_variables.Variable, + feature: tpu_embedding_v2_utils.FeatureConfig) -> tensor.Tensor: + """Embedding lookup for sparse tensor based on its feature config. + + Args: + inp: a single SparseTensor input. + weight: None or SparseTensor which has the same shape of the input. + table: a table variable. + feature: a feature config. + + Returns: + Embedding lookup result. + """ + inp_rank = inp.shape.rank + # The input rank can be None for sequence input tensor. + if ( + not feature.output_shape + and feature.max_sequence_length > 0 + and (inp_rank is None or inp_rank == 2) + ): + batch_size = math_ops.cast(array_ops.shape(inp)[0], dtype=dtypes.int64) + sparse_shape = array_ops_stack.stack( + [batch_size, feature.max_sequence_length], axis=0 + ) + # TPU Embedding truncates sequences to max_sequence_length, and if we + # don't truncate, scatter_nd will error out if the index was out of + # bounds. + truncated_inp = sparse_ops.sparse_slice( + inp, start=[0, 0], size=sparse_shape) + + dense_output_shape = array_ops_stack.stack( + [batch_size, feature.max_sequence_length, feature.table.dim], axis=0) + return array_ops.scatter_nd( + truncated_inp.indices, + array_ops.gather(table.read_value(), truncated_inp.values), + dense_output_shape) + else: + if feature.max_sequence_length > 0: + logging.warning( + ( + "max_sequence_length setting will be ignored because the rank of" + " the input tensor is %d which is not 2." + ), + inp_rank, + ) + if (not feature.validate_weights_and_indices and inp_rank is not None and + inp_rank <= 2): + return embedding_ops.embedding_lookup_sparse_v2( + table, inp, sp_weights=weight, combiner=feature.table.combiner) + else: + return embedding_ops.safe_embedding_lookup_sparse_v2( + table, inp, sparse_weights=weight, combiner=feature.table.combiner) + + +def _embedding_lookup_for_ragged_tensor( + inp: ragged_tensor.RaggedTensor, + weight: Optional[ragged_tensor.RaggedTensor], table: tf_variables.Variable, + feature: tpu_embedding_v2_utils.FeatureConfig) -> tensor.Tensor: + """Embedding lookup for ragged tensor based on its feature config. + + Args: + inp: a single rank 2 RaggedTensor input. + weight: None or RaggedTensor which has the same shape of the input. + table: a table variable. + feature: a feature config. + + Returns: + Embedding lookup result. + + Raises: + ValueError: if input ragged tensor is not rank 2 or output shape set in the + feature config doesn't match with the first dim size of the input. + """ + if inp.shape.rank != 2: + raise ValueError( + "Only rank 2 ragged tensor is supported, but got rank {}".format( + inp.shape.rank)) + batch_size = inp.shape[0] + if feature.output_shape: + output_batch_size = math_ops.reduce_prod(feature.output_shape) + # If the output batch size matches the data batch size, treat it as + # normal ragged input. + if output_batch_size == batch_size: + ragged_output = _ragged_embedding_lookup_with_reduce( + table, inp, weight, feature.table.combiner) + ragged_output = array_ops.reshape( + ragged_output, shape=feature.output_shape + [feature.table.dim]) + # If the data batch size is a factor of the output batch size, the + # divide result will be the sequence length. Ignore the weights and + # combiner. + elif output_batch_size > batch_size and output_batch_size % batch_size == 0: + ragged_output = embedding_ops.embedding_lookup_v2(table, inp) + # Pad or truncate in the sequence dimension + ragged_output = ragged_output.to_tensor(shape=[ + batch_size, output_batch_size // batch_size, feature.table.dim + ]) + # Reshape to desire output shape. + ragged_output = array_ops.reshape( + ragged_output, feature.output_shape + [feature.table.dim]) + else: + raise ValueError( + "Output shape set in the FeatureConfig should be the factor of " + "the input data batch size. But instead got output shape {}, " + "input data batch size {}".format(feature.output_shape, batch_size)) + else: + if feature.max_sequence_length > 0: + output_shape = [ + batch_size, feature.max_sequence_length, feature.table.dim + ] + ragged_lookup = embedding_ops.embedding_lookup_v2(table, inp) + # Unlike scatter_nd, RaggedTensor.to_tensor truncates to the given + # shape. + ragged_output = ragged_lookup.to_tensor(shape=output_shape) + else: + ragged_output = _ragged_embedding_lookup_with_reduce( + table, inp, weight, feature.table.combiner) + return ragged_output diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_gradient.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..cb272c296341bbae1acb5b960e55b23f4149a109 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_gradient.py @@ -0,0 +1,184 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== +"""Optional helper for gradient handling.""" + +import collections + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu.ops import tpu_ops + + +def get_gradients_through_compute_gradients(optimizer, loss, activations): + """Compute gradients to send to TPU embedding. + + Args: + optimizer: a subclass of optimizer.Optimizer, usually CrossShardOptimizer. + Used to call compute_gradients(). + loss: a Tensor to call optimizer.compute_gradients() on. + activations: an OrderedDict mapping feature_name to Tensors of activations. + + Returns: + An OrderedDict mapping from feature name Strings to Tensors of gradients of + the loss wrt the activations of the features. + """ + activation_list = activations.values() + grads_and_vars = optimizer.compute_gradients(loss, activation_list) + grads = [grad for grad, _ in grads_and_vars] + feature_to_gradient_dict = collections.OrderedDict( + zip(activations.keys(), grads)) + return feature_to_gradient_dict + + +def create_dummy_table_variables(tpu_embedding): + """Create dummy embedding table variables. + + The sole purpose of these dummy variables are to trigger gradient + calculation wrt them so that the gradients wrt activation can be captured + and later sent to TPU embedding. + + Args: + tpu_embedding: TPUEmbedding, dummy table variables will be created for use + with tpu_embedding. + + Returns: + A tuple of dummy variables and their initializer. + + Raises: + RuntimeError: if collection to store gradients already exists and is not + empty. + """ + dummy_table_variables = collections.OrderedDict() + for table_id, table in enumerate(tpu_embedding.table_to_features_dict): + dummy_table_variables[table] = ( + # Explicitly specifying collections prevents this variable from + # being added to the GLOBAL_VARIABLES collection, so that Saver() + # ignores it. + # But Tensorflow optimizer creates slot variable for these dummy + # variable, e.g. tpu_embedding_dummy_table_variable_mlp_user/Adam{_1}, + # which will be in GLOBAL_VARIABLES collection, + variable_scope.get_variable( + 'tpu_embedding_dummy_table_variable_{}'.format(table), + dtype=dtypes.float32, + shape=[1], + use_resource=True, + trainable=True, + collections=['tpu_embedding_dummy_table_variables'])) + + g = ops.get_default_graph() + table_gradients = g.get_collection_ref( + 'tpu_embedding_gradients_table_{}'.format(table_id)) + if table_gradients: + raise RuntimeError( + 'tpu_embedding_gradients_table_{} is not empty.'.format(table_id)) + num_features = len(tpu_embedding.table_to_features_dict[table]) + table_gradients.extend([None for _ in range(num_features)]) + + return (dummy_table_variables, + variables.variables_initializer( + dummy_table_variables.values(), + name='tpu_embedding_dummy_table_variables_init')) + + +def hook_dummy_table_variables_to_activations(tpu_embedding, activations, + dummy_table_variables): + """Have activations depend on dummy table variables for gradient intercept. + + Args: + tpu_embedding: TPUEmbedding, activations and dummy_table_variables are from + tpu_embedding. + activations: An OrderedDict of feature name String to activation tensors. + dummy_table_variables: An OrderedDict of table name String to dummy table + variables. + + Returns: + An OrderedDict of feature name String to activation tensors, which can be + used just as the activations input. + """ + new_activations = collections.OrderedDict() + for feature in activations: + table = tpu_embedding.feature_to_config_dict[feature].table_id + new_activations[feature] = tpu_ops.tpu_embedding_activations( + dummy_table_variables[table], + activations[feature], + table_id=list(tpu_embedding.table_to_config_dict).index(table), + lookup_id=tpu_embedding.table_to_features_dict[table].index(feature)) + return new_activations + + +def get_gradients_through_dummy_table_variables(tpu_embedding): + """Get gradients wrt the activations of each feature. + + Args: + tpu_embedding: TPUEmbedding, create dummy table variable to be used with + tpu_embedding. + + Returns: + An OrderedDict mapping feature name to gradient. + + Raises: + ValueError: if some gradients are not defined. + """ + g = ops.get_default_graph() + gradients_found = False + for table_id, table in enumerate(tpu_embedding.table_to_config_dict): + table_gradients = g.get_collection( + 'tpu_embedding_gradients_table_{}'.format(table_id)) + if any(gradient is None for gradient in table_gradients): + # TODO(bfontain): create a white-list for optimizers which are compatible + # with `tf.stop_gradient`. + logging.warn( + 'Table {} with id {} has undefined gradients: this is probably ' + 'because the model asked TPUEmbedding to compute activations that ' + 'were not used, or tf.stop_gradient() is applied. Gradients of zeros ' + 'are sent back to TPUEmbedding instead. Gradients of zeros and no ' + 'gradients are equivalent for SGD, AdaGrad, FTRL, etc, but ' + 'might differ for other optimizers due to implementation of TPU ' + 'embedding optimizers.'.format(table, table_id)) + gradients_found = gradients_found or any( + gradient is not None for gradient in table_gradients) + + if not gradients_found: + logging.warn( + 'All tables have undefined gradients: this is probably because the ' + 'model asked TPUEmbedding to compute activations that were not used. ' + 'If all TPUEmbedding features have stop_gradients, consider using the ' + 'INFERENCE mode instead.') + + feature_to_gradient_dict = collections.OrderedDict() + for table_id, table in enumerate(tpu_embedding.table_to_config_dict): + table_gradients = g.get_collection( + 'tpu_embedding_gradients_table_{}'.format(table_id)) + for feature, gradient in zip(tpu_embedding.table_to_features_dict[table], + table_gradients): + if gradient is not None: + feature_to_gradient_dict[feature] = gradient + else: + dimension = tpu_embedding.table_to_config_dict[table].dimension + batch_size = tpu_embedding.batch_size_per_core + max_sequence_length = ( + tpu_embedding.feature_to_config_dict[feature].max_sequence_length) + if max_sequence_length: + feature_to_gradient_dict[feature] = array_ops.zeros( + [batch_size, max_sequence_length, dimension]) + else: + feature_to_gradient_dict[feature] = array_ops.zeros( + [batch_size, dimension]) + + return feature_to_gradient_dict diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..259650cd9f83963926ccf76491cdbfa01cd46049 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v1.py @@ -0,0 +1,445 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Mid level API for TPU Embeddings without Embedding Accelerator.""" + +from typing import Any, Dict, Iterable, Optional, Text, Union + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.tpu import tpu_embedding_base +from tensorflow.python.tpu import tpu_embedding_v2_utils +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("tpu.experimental.embedding.TPUEmbeddingV0") +class TPUEmbeddingV0(tpu_embedding_base.TPUEmbeddingBase): + """The TPUEmbedding mid level API running on TPU without Embedding accelerator. + + NOTE: This mid level API is not intended for large embedding table lookup. + Embedding tables will be replicated across devices rather than sharding + across them. To do large embedding table lookup, please use the + `tpu.experimental.embedding.TPUEmbedding` class. This class is an alternative + way to do embedding lookups when the TPU doesn't support any version of + embedding feature. See + `tpu.experimental.tpu_hardware_feature.embedding_feature` for a detailed + explanation. + + This class has to be created under the `TPUStrategy`, Otherwise a RuntimeError + will be raised. + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbeddingV0( + feature_config=feature_config, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + ``` + When creating a distributed dataset that is to be passed to the lookup + operation a special input option must be specified: + + ```python + distributed_dataset = ( + strategy.distribute_datasets_from_function( + dataset_fn=..., + options=tf.distribute.InputOptions( + experimental_fetch_to_device=False)) + dataset_iterator = iter(distributed_dataset) + ``` + + Below is an example of a training and evaluation step: + + ```python + optimizer = tf.keras.optimizers.SGD(0.1) + + @tf.function + def training_step(dataset_iterator, num_steps): + def tpu_step(embedding_features): + with tf.GradientTape() as tape: + tape.watch(embedding.embedding_table.values()) + activation = embedding(embedding_features) + model_output = model(activations) + loss = ... # some function of labels and model_output + + embedding_gradients = tape.gradient(loss, + embedding.embedding_table.values()) + optimizer.apply_gradients(list(zip(gradients, + mid_level_api.embedding_tables.values()))) + # Insert your model gradient and optimizer application here + + for _ in tf.range(num_steps): + strategy.run(tpu_step, args=(next(dataset_iterator), )) + + @tf.function + def evalution_step(dataset_iterator, num_steps): + def tpu_step(embedding_features): + activations = embedding(embedding_features) + model_output = model(activations) + # Insert your evaluation code here. + + for _ in tf.range(num_steps): + strategy.run(tpu_step, args=(next(dataset_iterator), )) + ``` + + NOTE: The optimizer used here is a Keras optimizer. In order to make the slot + variable creation stay consistent between Keras optimizers and + embedding optimizers, the `slot_variable_creation_fn` argument of the + embedding optimizers has to be passed with the Keras `add_slot` function. Also + note that the slot names might be slightly different between them. + + ```python + optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.1) + + def slot_variable_creation_fn(table, slot_names, slot_initializers): + slots = {} + for slot, initializer in zip(slot_names, slot_initializers): + slots[slot] = optimizer.add_slot(table, slot, initializer) + return slots + + embedding_optimizer = tf.experimental.embedding.Adagrad( + learning_rate=0.1, + slot_variable_creation_fn=slot_variable_creation_fn) + + # Use the embedding optimizer to create mid level api and keras optimizer to + # apply gradients. + ``` + """ + + def __init__( + self, + feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable], # pylint:disable=g-bare-generic + optimizer: Optional[tpu_embedding_v2_utils._Optimizer]): # pylint:disable=protected-access + super(TPUEmbeddingV0, self).__init__(feature_config, optimizer) + self._strategy = distribute_lib.get_strategy() + if not isinstance(self._strategy, + (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV2)): + raise RuntimeError( + "TPUEmbeddingV0 should be created under TPUStrategy but found {}." + .format(self._strategy)) + self._built = False + + @property + def embedding_tables( + self) -> Dict[tpu_embedding_v2_utils.TableConfig, tf_variables.Variable]: + """Returns a dict of embedding tables, keyed by `TableConfig`.""" + self._maybe_build() + # Only return the tables and not the slot variables. + return { + table: self._variables[table.name]["parameters"] + for table in self._table_config + } + + def _create_variables_and_slots( + self) -> Dict[Text, Dict[Text, tf_variables.Variable]]: + """Create variables for TPU embeddings. + + Note that this will always ensure that the variable is created under the + TPUStrategy. + + Returns: + A dict of dicts. The outer dict is keyed by the table names and the inner + dicts are keyed by 'parameters' and the slot variable names. + """ + variables = {} + for table in self._table_config: + # created TPUDistributedVariable. + variables[table.name] = self._create_variables(table, trainable=True) + return variables + + def _maybe_build(self): + if not self._built: + # This can be called while tracing a function, so we wrap the + # initialization code with init_scope so it runs eagerly, this means that + # it will not be included in the function graph generated by tracing so + # that we can be sure that we only initialize the TPU for embeddings + # exactly once. + with ops.init_scope(): + self.build() + + def _apply_combiner_to_embeddings( + self, + embeddings: tensor.Tensor, + weight: tensor.Tensor, + combiner: Optional[Text] = None) -> tensor.Tensor: + """Apply the combiner to the embedding look up result on second to last axis. + + Args: + embeddings: A Tensor of the embedding lookup result. + weight: A Tensor of weight which has the same shape of the embeddings. + combiner: One of "mean", "sum", "sqrtn". Defaults to "mean". + + Raises: + ValueError: If the combiner is not one of 'mean', 'sqrtn' or 'sum'. + Returns: + A Tensor. + """ + if combiner is None: + combiner = "mean" + if combiner == "sum": + embeddings = math_ops.reduce_sum(embeddings, axis=-2) + elif combiner == "mean": + embeddings = math_ops.reduce_sum(embeddings, axis=-2) + weight_sum = math_ops.reduce_sum(weight, axis=-2) + embeddings = math_ops.div_no_nan(embeddings, weight_sum) + elif combiner == "sqrtn": + embeddings = math_ops.reduce_sum(embeddings, axis=-2) + weight_squared = math_ops.pow(weight, 2) + weight_sum = math_ops.reduce_sum(weight_squared, axis=-2) + weight_sum_sqrt = math_ops.sqrt(weight_sum) + embeddings = math_ops.div_no_nan(embeddings, weight_sum_sqrt) + else: + raise ValueError( + f"combiner must be one of 'mean', 'sqrtn' or 'sum', got {combiner}") + return embeddings + + def _pad_or_truncate_with_sequence_length( + self, embeddings: tensor.Tensor, sequence_length: int + ) -> tensor.Tensor: + """Pad or truncate the embedding lookup result based on the sequence length. + + Args: + embeddings: A rank 3 Tensor of the embedding lookup result. + sequence_length: number of the max sequence length set in the feature + config. + + Returns: + A Tensor with second last axis padded or truncated. + """ + original_sequence_length = embeddings.shape[1] + if original_sequence_length > sequence_length: + embeddings = array_ops.slice( + embeddings, begin=[0, 0, 0], size=[-1, sequence_length, -1]) + else: + embeddings = array_ops.pad( + embeddings, + paddings=[[0, 0], [0, sequence_length - original_sequence_length], + [0, 0]]) + return embeddings + + def embedding_lookup(self, + features: Any, + weights: Optional[Any] = None) -> Any: + """Apply embedding lookup on TPUs using Tensorcore. + + Note that all the sparse and ragged tensors will be converted to dense + tensors on CPU and then passed to the TPU to do embedding look up. Large + embedding lookup is not supported by this API, use the TPUEmbedding mid + level api instead. + + Args: + features: a nested structure of Tensors, SparseTensors or RaggedTensors. + weights: a nested structure of Tensors, SparseTensors or RaggedTensors or + None for no weights. If not None, structure must match that of inputs, + but entries are allowed to be None. + + Returns: + A nested structure of Tensors with the same structure as inputs. + """ + if not self._built: + self.build() + nest.assert_same_structure(features, self._feature_config) + + flat_inputs = nest.flatten(features) + flat_weights = [None] * len(flat_inputs) + if weights is not None: + nest.assert_same_structure(features, weights) + flat_weights = nest.flatten(weights) + flat_features = nest.flatten_with_joined_string_paths(self._feature_config) + + outputs = [] + for inp, weight, (path, feature) in zip(flat_inputs, flat_weights, + flat_features): + table = self.embedding_tables[feature.table] + + if weight is not None: + if isinstance(inp, tensor.Tensor): + raise ValueError( + "Weight specified for {}, but input is dense.".format(path)) + elif type(weight) is not type(inp): + raise ValueError( + "Weight for {} is of type {} but it does not match type of the " + "input which is {}.".format(path, type(weight), type(inp))) + elif feature.max_sequence_length > 0: + raise ValueError("Weight specified for {}, but this is a sequence " + "feature.".format(path)) + + if isinstance(inp, tensor.Tensor): + if feature.max_sequence_length > 0: + raise ValueError( + "Feature {} is a sequence feature but a dense tensor " + "was passed.".format(path)) + outputs.append(embedding_ops.embedding_lookup_v2(table, inp)) + + elif isinstance(inp, sparse_tensor.SparseTensor): + outputs.append( + self._embedding_lookup_for_sparse_tensor(inp, weight, table, + feature)) + elif isinstance(inp, ragged_tensor.RaggedTensor): + outputs.append( + self._embedding_lookup_for_ragged_tensor(inp, weight, table, + feature)) + else: + raise ValueError("Input {} is type {}. Tensor, SparseTensor or " + "RaggedTensor expected.".format(path, type(inp))) + return nest.pack_sequence_as(self._feature_config, outputs) + + def _embedding_lookup_for_sparse_tensor( + self, inp: sparse_tensor.SparseTensor, + weight: Optional[sparse_tensor.SparseTensor], + table: tf_variables.Variable, + feature: tpu_embedding_v2_utils.FeatureConfig) -> tensor.Tensor: + """Embedding lookup for sparse tensor based on its feature config. + + Args: + inp: a single SparseTensor input. + weight: None or SparseTensor which has the same shape of the input. + table: a table variable. + feature: a feature config. + + Returns: + Embedding lookup result. + """ + + # This computation needs to placed outside of tpu as the size of the + # indices and values can change for different batch which can cause + # the program to re-compile. + def sparse_to_dense_computation(inp, weight): + if weight is None: + weight = sparse_tensor.SparseTensor( + inp.indices, + array_ops.ones_like(inp.values, dtype=dtypes.float32), + dense_shape=inp.dense_shape) + # Pad the sparse tensor to be dense tensor. + inp = sparse_ops.sparse_tensor_to_dense(inp) + weight = sparse_ops.sparse_tensor_to_dense(weight) + return inp, weight + + inp, weight = tpu_replication.outside_compilation( + sparse_to_dense_computation, inp=inp, weight=weight) + + embeddings = embedding_ops.embedding_lookup_v2(table, inp) + weight = array_ops.expand_dims(weight, -1) + embeddings *= weight + if not feature.output_shape and feature.max_sequence_length > 0: + embeddings = self._pad_or_truncate_with_sequence_length( + embeddings, feature.max_sequence_length) + else: + embeddings = self._apply_combiner_to_embeddings(embeddings, weight, + feature.table.combiner) + return embeddings + + def _embedding_lookup_for_ragged_tensor( + self, inp: ragged_tensor.RaggedTensor, + weight: Optional[ragged_tensor.RaggedTensor], + table: tf_variables.Variable, + feature: tpu_embedding_v2_utils.FeatureConfig) -> tensor.Tensor: + """Embedding lookup for ragged tensor based on its feature config. + + Args: + inp: a single rank 2 RaggedTensor input. + weight: None or RaggedTensor which has the same shape of the input. + table: a table variable. + feature: a feature config. + + Returns: + Embedding lookup result. + + Raises: + ValueError: if input ragged tensor is not rank 2 or output shape set in + the feature config doesn't match with the first dim size of the input. + """ + if inp.shape.rank != 2: + raise ValueError( + "Only rank 2 ragged tensor is supported, but got rank {}".format( + inp.shape.rank)) + batch_size = inp.shape[0] + + # This computation needs to placed outside of tpu as the size of the row + # splits and values can change for different batch which can cause + # the program to re-compile. + def ragged_to_dense_outside_compilation(inp, weight, batch_size, feature): + if weight is None: + weight = ragged_tensor.RaggedTensor.from_row_splits( + array_ops.ones_like(inp.values, dtype=dtypes.float32), + inp.row_splits) + if not feature.output_shape and feature.max_sequence_length > 0: + inp = inp.to_tensor(shape=(batch_size, feature.max_sequence_length)) + # Ignore weight if it is a sequence feature. + weight = array_ops.ones_like(inp, dtype=dtypes.float32) + elif feature.output_shape: + # Eagerly run the following op as the result as to be a number in + # order to use it as part of the output shape. + with ops.init_scope(): + output_batch_size = math_ops.reduce_prod(feature.output_shape).numpy() + # If the output batch size matches the data batch size, treat it as + # normal ragged input. + if output_batch_size == batch_size: + inp, weight = inp.to_tensor(), weight.to_tensor() + # If the data batch size is a factor of the output batch size, the + # divide result will be the sequence length. Ignore the weights and + # combiner. + elif ( + output_batch_size > batch_size + and output_batch_size % batch_size == 0 + ): + # Pad or truncate in the sequence dimension + seq_length = output_batch_size // batch_size + inp = inp.to_tensor(shape=(batch_size, seq_length)) + # Ignore weight if it is a sequence feature. + weight = array_ops.ones_like(inp, dtype=dtypes.float32) + else: + raise ValueError( + "Output shape set in the FeatureConfig should be the factor of " + "the input data batch size. But instead got output shape {}, " + "input data batch size {}".format(feature.output_shape, + batch_size)) + else: + inp, weight = inp.to_tensor(), weight.to_tensor() + return inp, weight + + inp, weight = tpu_replication.outside_compilation( + ragged_to_dense_outside_compilation, + inp=inp, + weight=weight, + batch_size=batch_size, + feature=feature) + + embeddings = embedding_ops.embedding_lookup_v2(table, inp) + weight = array_ops.expand_dims(weight, -1) + embeddings *= weight + + if feature.output_shape: + with ops.init_scope(): + output_batch_size = math_ops.reduce_prod(feature.output_shape).numpy() + if output_batch_size == batch_size: + embeddings = self._apply_combiner_to_embeddings(embeddings, weight, + feature.table.combiner) + embeddings = array_ops.reshape( + embeddings, shape=feature.output_shape + [feature.table.dim]) + else: + if feature.max_sequence_length == 0: + embeddings = self._apply_combiner_to_embeddings(embeddings, weight, + feature.table.combiner) + return embeddings diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..bf954ac0a55e77d6cbe95ac15f6bde2317ac1d07 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2.py @@ -0,0 +1,1762 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Mid level API for TPU Embeddings.""" + +import functools +from typing import Any, Callable, Dict, Iterable, List, Optional, Text, Tuple, Union + +from absl import logging + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2 +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import sharded_variable +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework.tensor_shape import TensorShape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.saved_model import registration +from tensorflow.python.saved_model import save_context +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_embedding_v2_utils +from tensorflow.python.tpu import tpu_replication +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base +from tensorflow.python.types import internal as internal_types +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +_HOOK_KEY = "TPUEmbedding_saveable" +_NAME_KEY = "_tpu_embedding_layer" + + +class TPUEmbeddingVariable(sharded_variable.ShardedVariableMixin): + """A ShardedVariable class for TPU.""" + + @property + def _in_graph_mode(self): + return self.variables[0]._in_graph_mode # pylint: disable=protected-access + + +def _add_key_attr(op, name): + op._set_attr(_NAME_KEY, attr_value_pb2.AttrValue(s=compat.as_bytes(name))) # pylint: disable=protected-access + + +@tf_export("tpu.experimental.embedding.TPUEmbedding") +class TPUEmbedding(autotrackable.AutoTrackable): + """The TPUEmbedding mid level API. + + NOTE: When instantiated under a TPUStrategy, this class can only be created + once per call to `tf.tpu.experimental.initialize_tpu_system`. If you wish to + re-initialize the embedding engine you must re-initialize the tpu as well. + Doing this will clear any variables from TPU, so ensure you have checkpointed + before you do this. If a further instances of the class are needed, + set the `initialize_tpu_embedding` argument to `False`. + + This class can be used to support training large embeddings on TPU. When + creating an instance of this class, you must specify the complete set of + tables and features you expect to lookup in those tables. See the + documentation of `tf.tpu.experimental.embedding.TableConfig` and + `tf.tpu.experimental.embedding.FeatureConfig` for more details on the complete + set of options. We will cover the basic usage here. + + NOTE: multiple `FeatureConfig` objects can use the same `TableConfig` object, + allowing different features to share the same table: + + ```python + table_config_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + table_config_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + feature_config = { + 'feature_one': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_two': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_three': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_two)} + ``` + + There are two modes under which the `TPUEmbedding` class can used. This + depends on if the class was created under a `TPUStrategy` scope or not. + + Under `TPUStrategy`, we allow access to the method `enqueue`, `dequeue` and + `apply_gradients`. We will show examples below of how to use these to train + and evaluate your model. Under CPU, we only access to the `embedding_tables` + property which allow access to the embedding tables so that you can use them + to run model evaluation/prediction on CPU. + + First lets look at the `TPUStrategy` mode. Initial setup looks like: + + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + ``` + + When creating a distributed dataset that is to be passed to the enqueue + operation a special input option must be specified: + + ```python + distributed_dataset = ( + strategy.distribute_datasets_from_function( + dataset_fn=..., + options=tf.distribute.InputOptions( + experimental_fetch_to_device=False)) + dataset_iterator = iter(distributed_dataset) + ``` + + Different feature inputs can have different shapes. For dense and sparse + tensor, rank 2 and above is supported. For ragged tensor, although only rank 2 + is supported, you can specify the output shape to be rank 2 and above. The + output shape specified in the FeatureConfig has the first priority. The input + shape passed in build method has second priority and the input shapes + auto detected from input feature has the lowest priority. The latter two will + be converted to output shapes by omitting the last dimension. If the lower + priority one has output shapes which don't match the former one. A ValueError + will be raised. Only when the former one has undefined output shapes, the + latter one can override. + + NOTE: All batches passed to the layer can have different input shapes. But + these input shapes need to match with the output shapes set by either + `FeatureConfig` or build method except for ragged tensor. Only 2D + ragged tensor with output shape set to higher dimensions is allowed as + long as the total number of elements matches. All subsequent calls must have + the same input shapes. In the event that the input shapes cannot be + automatically determined by the enqueue method, you must call + the build method with the input shapes or provide output shapes in the + `FeatureConfig` to initialize the layer. + + To use this API on TPU you should use a custom training loop. Below is an + example of a training and evaluation step: + + ```python + @tf.function + def training_step(dataset_iterator, num_steps): + def tpu_step(tpu_features): + with tf.GradientTape() as tape: + activations = embedding.dequeue() + tape.watch(activations) + model_output = model(activations) + loss = ... # some function of labels and model_output + + embedding_gradients = tape.gradient(loss, activations) + embedding.apply_gradients(embedding_gradients) + # Insert your model gradient and optimizer application here + + for _ in tf.range(num_steps): + embedding_features, tpu_features = next(dataset_iterator) + embedding.enqueue(embedding_features, training=True) + strategy.run(tpu_step, args=(tpu_features, )) + + @tf.function + def evaluation_step(dataset_iterator, num_steps): + def tpu_step(tpu_features): + activations = embedding.dequeue() + model_output = model(activations) + # Insert your evaluation code here. + + for _ in tf.range(num_steps): + embedding_features, tpu_features = next(dataset_iterator) + embedding.enqueue(embedding_features, training=False) + strategy.run(tpu_step, args=(tpu_features, )) + ``` + + NOTE: The calls to `enqueue` have `training` set to `True` when + `embedding.apply_gradients` is used and set to `False` when + `embedding.apply_gradients` is not present in the function. If you don't + follow this pattern you may cause an error to be raised or the tpu may + deadlock. + + In the above examples, we assume that the user has a dataset which returns + a tuple where the first element of the tuple matches the structure of what + was passed as the `feature_config` argument to the object initializer. Also we + utilize `tf.range` to get a `tf.while_loop` in order to increase performance. + + When checkpointing your model, you should include your + `tf.tpu.experimental.embedding.TPUEmbedding` object in the checkpoint. It is a + trackable object and saving it will save the embedding tables and their + optimizer slot variables: + + ```python + checkpoint = tf.train.Checkpoint(model=model, embedding=embedding) + checkpoint.save(...) + ``` + + On CPU, only the `embedding_table` property is usable. This will allow you to + restore a checkpoint to the object and have access to the table variables: + + ```python + model = model_fn(...) + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + checkpoint = tf.train.Checkpoint(model=model, embedding=embedding) + checkpoint.restore(...) + + tables = embedding.embedding_tables + ``` + + You can now use table in functions like `tf.nn.embedding_lookup` to perform + your embedding lookup and pass to your model. + + """ + + def __init__( + self, + feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable], # pylint:disable=g-bare-generic + optimizer: Optional[tpu_embedding_v2_utils._Optimizer], # pylint:disable=protected-access + pipeline_execution_with_tensor_core: bool = False): + """Creates the TPUEmbedding mid level API object. + + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=tf.tpu.experimental.embedding.FeatureConfig( + table=tf.tpu.experimental.embedding.TableConfig( + dim=..., + vocabulary_size=...))) + ``` + + Args: + feature_config: A nested structure of + `tf.tpu.experimental.embedding.FeatureConfig` configs. + optimizer: An instance of one of `tf.tpu.experimental.embedding.SGD`, + `tf.tpu.experimental.embedding.Adagrad` or + `tf.tpu.experimental.embedding.Adam`. When not created under + TPUStrategy may be set to None to avoid the creation of the optimizer + slot variables, useful for optimizing memory consumption when exporting + the model for serving where slot variables aren't needed. + pipeline_execution_with_tensor_core: If True, the TPU embedding + computations will overlap with the TensorCore computations (and hence + will be one step old). Set to True for improved performance. + + Raises: + ValueError: If optimizer is not one of tf.tpu.experimental.embedding.(SGD, + Adam or Adagrad) or None when created under a TPUStrategy. + """ + self._strategy = distribute_lib.get_strategy() + self._using_tpu = isinstance(self._strategy, (tpu_strategy.TPUStrategy, + tpu_strategy.TPUStrategyV2)) + self._pipeline_execution_with_tensor_core = ( + pipeline_execution_with_tensor_core) + + self._feature_config = feature_config + self._output_shapes = [] + for feature in nest.flatten(feature_config): + self._output_shapes.append(feature.output_shape) + + device_assignment = getattr( + self._strategy.extended, "_device_assignment", None + ) + self._num_cores_per_replica = ( + device_assignment.num_cores_per_replica if device_assignment else None + ) + + # The TPU embedding ops are slightly inconsistent with how they refer to + # tables: + # * The enqueue op takes a parallel list of tensors for input, one of those + # is the table id for the feature which matches the integer index of the + # table in the proto created by _create_config_proto(). + # * The recv_tpu_embedding_activations op emits lookups per table in the + # order from the config proto. + # * The send_tpu_embedding_gradients expects input tensors to be per table + # in the same order as the config proto. + # * Per optimizer load and retrieve ops are specified per table and take the + # table name rather than the table id. + # Thus we must fix a common order to tables and ensure they have unique + # names. + + # Set table order here to the order of the first occurence of the table in a + # feature provided by the user. The order of this struct must be fixed + # to provide the user with deterministic behavior over multiple + # instantiations. + self._table_config = [] + for feature in nest.flatten(feature_config): + if feature.table not in self._table_config: + self._table_config.append(feature.table) + + # Ensure tables have unique names. Also error check the optimizer as we + # specifically don't do that in the TableConfig class to allow high level + # APIs that are built on this to use strings/other classes to represent + # optimizers (before they are passed to this class). + table_names = [] + for i, table in enumerate(self._table_config): + if table.optimizer is None: + # TODO(bfontain) Should we allow some sort of optimizer merging here? + table.optimizer = optimizer + if ((table.optimizer is not None or self._using_tpu) and + not isinstance(table.optimizer, tpu_embedding_v2_utils._Optimizer)): # pylint: disable=protected-access + raise ValueError("{} is an unsupported optimizer class. Please pass an " + "instance of one of the optimizer classes under " + "tf.tpu.experimental.embedding.".format( + type(table.optimizer))) + if table.name is None: + table.name = "table_{}".format(i) + if table.name in table_names: + raise ValueError("Tables must have a unique name. " + f"Multiple tables with name {table.name} found.") + table_names.append(table.name) + + if self._using_tpu: + # Extract a list of callable learning rates also in fixed order. Each + # table in the config proto will get an index into this list, and we will + # pass this list in the same order after evaluation to the + # send_tpu_embedding_gradients op. + self._dynamic_learning_rates = [] + for table in self._table_config: + if (callable(table.optimizer.learning_rate) and + table.optimizer.learning_rate not in self._dynamic_learning_rates): + self._dynamic_learning_rates.append(table.optimizer.learning_rate) + + # We need to list of host devices for the load/retrieve operations. + self._hosts = tpu_embedding_v2_utils.get_list_of_hosts(self._strategy) + + self._built = False + self._verify_output_shapes_on_enqueue = True + + def build(self, per_replica_input_shapes=None, per_replica_batch_size=None): # pylint:disable=g-bare-generic + """Create the underlying variables and initializes the TPU for embeddings. + + This method creates the underlying variables (including slot variables). If + created under a TPUStrategy, this will also initialize the TPU for + embeddings. + + This function will automatically get called by enqueue, which will try to + determine your output shapes. If this fails, you must manually + call this method before you call enqueue. + + Args: + per_replica_input_shapes: A nested structure of The per replica input + shapes that matches the structure of the feature config. The input + shapes should be the same as the input shape of the feature (except for + ragged tensor) Note that it is fixed and the same per replica input + shapes must be used for both training and evaluation. If you want to + calculate this from the global input shapes, you can use + `num_replicas_in_sync` property of your strategy object. May be set to + None if not created under a TPUStrategy. + per_replica_batch_size: (Deprecated) The per replica batch size that you + intend to use. Note that is fixed and the same batch size must be used + for both training and evaluation. If you want to calculate this from the + global batch size, you can use `num_replicas_in_sync` property of your + strategy object. May be set to None if not created under a TPUStrategy. + + Raises: + ValueError: If per_replica_input_shapes is inconsistent with the output + shapes stored in the feature config or the output shapes get from the + input shapes are not fully defined. + RuntimeError: If tpu embedding is already initialized on TPU. + """ + if self._built: + return + + if self._using_tpu: + # If the tpu embedding is already initialized on TPU, raise runtime error. + # Below logic is not added in `initialize_system_for_tpu_embedding` + # because doing exception control flow in graph mode is difficult. + if tpu_ops.is_tpu_embedding_initialized(): + raise RuntimeError( + "TPU is already initialized for embeddings. This may be caused by " + "using multiple TPUEmbedding instances in a TPU scope which is " + "unsupported") + self._get_and_update_output_shapes_from_input(per_replica_input_shapes, + per_replica_batch_size) + + self._config_proto = self._create_config_proto() + + logging.info("Initializing TPU Embedding engine.") + tpu_embedding_v2_utils.log_tpu_embedding_configuration(self._config_proto) + + @def_function.function + def load_config(): + tpu.initialize_system_for_tpu_embedding(self._config_proto) + + load_config() + logging.info("Done initializing TPU Embedding engine.") + + # Create and load variables and slot variables into the TPU. + # Note that this is a dict of dicts. Keys to the first dict are table names. + # We would prefer to use TableConfigs, but then these variables won't be + # properly tracked by the tracking API. + self._variables = self._create_variables_and_slots() + + self._built = True + + # This is internally conditioned self._built and self._using_tpu + self._load_variables() + + def _maybe_build(self, + output_shapes: Optional[Union[List[int], Iterable]] = None): # pylint:disable=g-bare-generic + if not self._built: + # This can be called while tracing a function, so we wrap the + # initialization code with init_scope so it runs eagerly, this means that + # it will not be included the function graph generated by tracing so that + # we can be sure that we only initialize the TPU for embeddings exactly + # once. + with ops.init_scope(): + self.build(output_shapes) + + def _get_and_update_output_shapes_from_input( + self, + per_replica_input_shapes: Optional[List[TensorShape]] = None, + per_replica_batch_size: Optional[int] = None): + """Get and update the per replica output shapes from the input.""" + per_replica_output_shapes = None + if per_replica_batch_size and per_replica_input_shapes is None: + logging.warning( + "per_replica_batch_size argument will be deprecated, please specify " + "all the input shapes using per_replica_input_shapes argument.") + per_replica_output_shapes = self._get_output_shapes_from_batch_size( + per_replica_batch_size) + + # Update the input shapes if provided. + if per_replica_input_shapes is not None: + if isinstance(per_replica_input_shapes, int): + logging.warning( + "Passing batch size to per_replica_input_shapes argument will be" + " deprecated, please specify all the input shapes using" + " per_replica_input_shapes argument.") + per_replica_output_shapes = self._get_output_shapes_from_batch_size( + per_replica_input_shapes) + else: + nest.assert_same_structure( + nest.flatten(per_replica_input_shapes), + nest.flatten(self._feature_config)) + + # Convert the nested structure to list. + per_replica_input_shapes = nest.flatten(per_replica_input_shapes) + + per_replica_output_shapes = self._get_output_shapes_from_input_shapes( + per_replica_input_shapes) + + if per_replica_output_shapes is not None: + + # Check the output shapes with existing output shapes setting. + self._check_output_shapes(per_replica_output_shapes) + + # Update the output shapes with existing output shapes setting. + # This is necessary Because the output shapes might be missing from + # the feature config, the usr can set it: + # 1. calling the build method + # 2. output shapes auto detected when calling the dequeue method for + # for the first time. The dequeue method will call build method + # with the output shapes. + # Either these two situations will lead to an update to the existing + # output shapes. + self._update_output_shapes(per_replica_output_shapes) + + # Check if the output shapes are fully defined. This is required in order + # to set them in the feature descriptor field of the tpu embedding config + # proto. + self._check_output_shapes_fully_defined() + + def _get_output_shapes_from_input_shapes( + self, input_shapes: List[TensorShape]) -> List[TensorShape]: + """Get output shapes from the flattened input shapes list.""" + output_shapes = [] + for input_shape, feature in zip(input_shapes, + nest.flatten(self._feature_config)): + if input_shape.rank is None or input_shape.rank < 1: + raise ValueError( + "Received input tensor of shape {}. Rank must be 1 and above" + .format(input_shape)) + # Update the input shape with the max sequence length. Only update when + # 1. Input feature is 2D ragged or sparse tensor. + # 2. Output shape is not set in the feature config and the max sequence + # length is set. + if (len(input_shape) == 2 and input_shape[-1] != 1 and + not feature.output_shape and feature.max_sequence_length > 0): + input_shape_list = input_shape.as_list() + input_shape_list.insert( + len(input_shape_list) - 1, feature.max_sequence_length) + input_shape = TensorShape(input_shape_list) + if input_shape.rank == 1: + output_shapes.append(input_shape) + else: + output_shapes.append(input_shape[:-1]) + return output_shapes + + @property + def embedding_tables( + self + ) -> Dict[tpu_embedding_v2_utils.TableConfig, tf_variables.Variable]: + """Returns a dict of embedding tables, keyed by `TableConfig`. + + This property only works when the `TPUEmbedding` object is created under a + non-TPU strategy. This is intended to be used to for CPU based lookup when + creating a serving checkpoint. + + Returns: + A dict of embedding tables, keyed by `TableConfig`. + + Raises: + RuntimeError: If object was created under a `TPUStrategy`. + """ + # We don't support returning tables on TPU due to their sharded nature and + # the fact that when using a TPUStrategy: + # 1. Variables are stale and are only updated when a checkpoint is made. + # 2. Updating the variables won't affect the actual tables on the TPU. + if self._using_tpu: + if save_context.in_save_context(): + return {table: self._variables[table.name]["parameters"].variables[0] + for table in self._table_config} + raise RuntimeError("Unable to retrieve embedding tables when using a TPU " + "strategy. If you need access, save your model, " + "create this object under a CPU strategy and restore.") + + self._maybe_build(None) + + # Only return the tables and not the slot variables. On CPU this are honest + # tf.Variables. + return {table: self._variables[table.name]["parameters"] + for table in self._table_config} + + def _create_config_proto( + self + ) -> tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration: + """Creates the TPUEmbeddingConfiguration proto. + + This proto is used to initialize the TPU embedding engine. + + Returns: + A TPUEmbeddingConfiguration proto. + """ + + config_proto = tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration() + + # Map each callable dynamic learning rate to its in index in the list. + # The learning rate index is the index of the dynamic learning rate for this + # table (if it exists) in the list we created at initialization. We don't + # simply create one learning rate index per table as this has extremely bad + # performance characteristics. The more separate optimization configurations + # we have, the worse the performance will be. + learning_rate_index = {r: i for i, r in enumerate( + self._dynamic_learning_rates)} + + for table in self._table_config: + table._set_table_descriptor( # pylint: disable=protected-access + config_proto.table_descriptor.add(), + self._strategy.extended.num_hosts, + learning_rate_index) + + table_to_id = {table: i for i, table in enumerate(self._table_config)} + + # Set feature descriptor field in the config proto. + for feature, output_shape in zip( + nest.flatten(self._feature_config), self._output_shapes): + feature_descriptor = config_proto.feature_descriptor.add() + + if feature.name: + feature_descriptor.name = feature.name + + feature_descriptor.table_id = table_to_id[feature.table] + # The input shape of the feature is the actual shape of the input tensor + # except the last dimension because the last dimension will always be + # reduced. + feature_descriptor.input_shape.extend(output_shape.as_list()) + + # Always set mode to training, we override the mode during enqueue. + config_proto.mode = ( + tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration.TRAINING) + + num_replica = self._strategy.num_replicas_in_sync + num_cores_per_replica = self._num_cores_per_replica or 1 + + config_proto.num_hosts = self._strategy.extended.num_hosts + config_proto.num_tensor_cores = num_replica * num_cores_per_replica + + # TODO(bfontain): Allow users to pick MOD for the host sharding. + config_proto.sharding_strategy = ( + tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration.DIV_DEFAULT) + config_proto.pipeline_execution_with_tensor_core = ( + self._pipeline_execution_with_tensor_core) + + if self._num_cores_per_replica: + config_proto.spmd_sharding.enabled = True + config_proto.spmd_sharding.num_cores_per_replica = ( + self._num_cores_per_replica + ) + + return config_proto + + def apply_gradients(self, gradients, name: Optional[Text] = None): + """Applies the gradient update to the embedding tables. + + If a gradient of `None` is passed in any position of the nested structure, + then an gradient update with a zero gradient is applied for that feature. + For optimizers like SGD or Adagrad, this is the same as applying no update + at all. For lazy Adam and other sparsely applied optimizers with decay, + ensure you understand the effect of applying a zero gradient. + + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding(...) + + distributed_dataset = ( + strategy.distribute_datasets_from_function( + dataset_fn=..., + options=tf.distribute.InputOptions( + experimental_fetch_to_device=False)) + dataset_iterator = iter(distributed_dataset) + + @tf.function + def training_step(): + def tpu_step(tpu_features): + with tf.GradientTape() as tape: + activations = embedding.dequeue() + tape.watch(activations) + + loss = ... # some computation involving activations + + embedding_gradients = tape.gradient(loss, activations) + embedding.apply_gradients(embedding_gradients) + + embedding_features, tpu_features = next(dataset_iterator) + embedding.enqueue(embedding_features, training=True) + strategy.run(tpu_step, args=(tpu_features, )) + + training_step() + ``` + + Args: + gradients: A nested structure of gradients, with structure matching the + `feature_config` passed to this object. + name: A name for the underlying op. + + Raises: + RuntimeError: If called when object wasn't created under a `TPUStrategy` + or if not built (either by manually calling build or calling enqueue). + ValueError: If a non-`tf.Tensor` non-`None` gradient is passed in, or a + `tf.Tensor` of the incorrect shape is passed in. Also if + the size of any sequence in `gradients` does not match corresponding + sequence in `feature_config`. + TypeError: If the type of any sequence in `gradients` does not match + corresponding sequence in `feature_config`. + """ + if not self._using_tpu: + raise RuntimeError("apply_gradients is not valid when TPUEmbedding " + "object is not created under a TPUStrategy.") + + if not self._built: + raise RuntimeError("apply_gradients called on unbuilt TPUEmbedding " + "object. Please either call enqueue first or manually " + "call the build method.") + + num_cores_per_replica = self._num_cores_per_replica or 1 + + nest.assert_same_structure(self._feature_config, gradients) + updated_gradients = [] + for (path, gradient), feature, output_shape in zip( + nest.flatten_with_joined_string_paths(gradients), + nest.flatten(self._feature_config), self._output_shapes): + full_output_shape = [x * num_cores_per_replica for x in output_shape] + [ + feature.table.dim + ] + if gradient is not None and not isinstance(gradient, tensor_lib.Tensor): + raise ValueError( + f"found non-tensor type: {type(gradient)} at path {path}.") + if gradient is not None: + if gradient.shape != full_output_shape: + raise ValueError("Found gradient of shape {} at path {}. Expected " + "shape {}.".format(gradient.shape, path, + full_output_shape)) + else: + # No gradient for this feature, since we must give a gradient for all + # features, pass in a zero tensor here. Note that this is not correct + # for all optimizers. + logging.warning( + "No gradient passed for feature %s, sending zero " + "gradient. This may not be correct behavior for certain " + "optimizers like Adam.", path) + gradient = array_ops.zeros(full_output_shape, dtype=dtypes.float32) + # Some gradients can be passed with op which shape is not correctly set. + # This ensures that the shape of the gradient is correctly set. + updated_gradients.append( + array_ops.reshape(gradient, shape=gradient.shape)) + op = tpu_ops.send_tpu_embedding_gradients( + inputs=updated_gradients, + learning_rates=[ + math_ops.cast(fn(), dtype=dtypes.float32) + for fn in self._dynamic_learning_rates + ], + config=self._config_proto.SerializeToString()) + + # Apply the name tag to the op. + if name is not None: + _add_key_attr(op, name) + + def dequeue(self, name: Optional[Text] = None): + """Get the embedding results. + + Returns a nested structure of `tf.Tensor` objects, matching the structure of + the `feature_config` argument to the `TPUEmbedding` class. The output shape + of the tensors is `(*output_shape, dim)`, `dim` is the dimension of the + corresponding `TableConfig`. For output_shape, there are three places where + it can be set. + 1. FeatureConfig provided in the __init__ function. + 2. Per_replica_output_shapes by directly calling the build method + after initializing the tpu embedding class. + 3. Auto detected from the shapes of the input feature. + The priority of these places is the exact same order. + + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding(...) + + distributed_dataset = ( + strategy.distribute_datasets_from_function( + dataset_fn=..., + options=tf.distribute.InputOptions( + experimental_fetch_to_device=False)) + dataset_iterator = iter(distributed_dataset) + + @tf.function + def training_step(): + def tpu_step(tpu_features): + with tf.GradientTape() as tape: + activations = embedding.dequeue() + tape.watch(activations) + + loss = ... # some computation involving activations + + embedding_gradients = tape.gradient(loss, activations) + embedding.apply_gradients(embedding_gradients) + + embedding_features, tpu_features = next(dataset_iterator) + embedding.enqueue(embedding_features, training=True) + strategy.run(tpu_step, args=(tpu_features, )) + + training_step() + ``` + + Args: + name: A name for the underlying op. + + Returns: + A nested structure of tensors, with the same structure as `feature_config` + passed to this instance of the `TPUEmbedding` object. + + Raises: + RuntimeError: If called when object wasn't created under a `TPUStrategy` + or if not built (either by manually calling build or calling enqueue). + """ + if not self._using_tpu: + raise RuntimeError("dequeue is not valid when TPUEmbedding object is not " + "created under a TPUStrategy.") + + if not self._built: + raise RuntimeError("dequeue called on unbuilt TPUEmbedding object. " + "Please either call enqueue first or manually call " + "the build method.") + + # The activations returned by this op are per feature. + activations = tpu_ops.recv_tpu_embedding_activations( + num_outputs=len(self._config_proto.feature_descriptor), + config=self._config_proto.SerializeToString()) + + # Apply the name tag to the op. + if name is not None: + _add_key_attr(activations[0].op, name) + + # Pack the list back into the same nested structure as the features. + return nest.pack_sequence_as(self._feature_config, activations) + + def _create_variables_and_slots( + self + ) -> Dict[Text, Dict[Text, tf_variables.Variable]]: + """Create variables for TPU embeddings. + + Note under TPUStrategy this will ensure that all creations happen within a + variable creation scope of the sharded variable creator. + + Returns: + A dict of dicts. The outer dict is keyed by the table names and the inner + dicts are keyed by 'parameters' and the slot variable names. + """ + + def create_variables(table): + """Create all variables.""" + variable_shape = (table.vocabulary_size, table.dim) + + def getter(name, shape, dtype, initializer, trainable): + del shape + # _add_variable_with_custom_getter clears the shape sometimes, so we + # take the global shape from outside the getter. + initial_value = functools.partial(initializer, variable_shape, + dtype=dtype) + return tf_variables.Variable( + name=name, + initial_value=initial_value, + shape=variable_shape, + dtype=dtype, + trainable=trainable) + + def variable_creator(name, initializer, trainable=True): + # use add_variable_with_custom_getter here so that we take advantage of + # the checkpoint loading to allow restore before the variables get + # created which avoids double initialization. + return self._add_variable_with_custom_getter( + name=name, + initializer=initializer, + shape=variable_shape, + dtype=dtypes.float32, + getter=getter, + trainable=trainable) + + parameters = variable_creator(table.name, table.initializer, + trainable=not self._using_tpu) + + def slot_creator(name, initializer): + return variable_creator(table.name + "/" + name, + initializer, + False) + + if table.optimizer is not None: + slot_vars = table.optimizer._create_slots(parameters, slot_creator) # pylint: disable=protected-access + else: + slot_vars = {} + slot_vars["parameters"] = parameters + return slot_vars + + # Store tables based on name rather than TableConfig as we can't track + # through dicts with non-string keys, i.e. we won't be able to save. + variables = {} + for table in self._table_config: + if not self._using_tpu: + variables[table.name] = create_variables(table) + else: + with variable_scope.variable_creator_scope( + make_sharded_variable_creator(self._hosts)): + variables[table.name] = create_variables(table) + + return variables + + def _load_variables(self): + # Only load the variables if we are: + # 1) Using TPU + # 2) Variables are created + # 3) Not in save context (except if running eagerly) + if self._using_tpu and self._built and not ( + not context.executing_eagerly() and save_context.in_save_context()): + _load_variables_impl(self._config_proto.SerializeToString(), + self._hosts, + self._variables, + self._table_config) + + def _retrieve_variables(self): + # Only retrieve the variables if we are: + # 1) Using TPU + # 2) Variables are created + # 3) Not in save context (except if running eagerly) + if self._using_tpu and self._built and not ( + not context.executing_eagerly() and save_context.in_save_context()): + _retrieve_variables_impl(self._config_proto.SerializeToString(), + self._hosts, + self._variables, + self._table_config) + + # Some helper functions for the below enqueue function. + def _add_data_for_tensor(self, tensor, weight, indices, values, weights, + int_zeros, float_zeros, path): + if weight is not None: + raise ValueError( + "Weight specified for dense input {}, which is not allowed. " + "Weight will always be 1 in this case.".format(path)) + # For tensors, there are no indices and no weights. + indices.append(int_zeros) + values.append(math_ops.cast(array_ops.reshape(tensor, [-1]), dtypes.int64)) + weights.append(float_zeros) + + def _add_data_for_sparse_tensor(self, tensor, weight, indices, values, + weights, int_zeros, float_zeros, path, + feature): + sample_indices = math_ops.cast(tensor.indices, dtypes.int32) + if tensor.shape.rank == 2: + if not feature.output_shape and feature.max_sequence_length > 0: + # Add one dimension to the last axis. + sample_indices = array_ops.pad( + sample_indices, paddings=[[0, 0], [0, 1]]) + else: + if feature.max_sequence_length > 0: + logging.warning( + ( + "Input tensor is rank %d which is above 2, the" + " max_sequence_length setting will be ignored." + ), + tensor.shape.rank, + ) + indices.append(sample_indices) + values.append(math_ops.cast(tensor.values, dtypes.int64)) + # If we have weights they must be a SparseTensor. + if weight is not None: + if not isinstance(weight, sparse_tensor.SparseTensor): + raise ValueError("Weight for {} is type {} which does not match " + "type input which is SparseTensor.".format( + path, type(weight))) + weights.append(math_ops.cast(weight.values, dtypes.float32)) + else: + weights.append(float_zeros) + + def _add_data_for_ragged_tensor(self, tensor, weight, row_splits, values, + weights, int_zeros, float_zeros, path, + feature): + row_splits.append(math_ops.cast(tensor.row_splits, dtypes.int32)) + values.append(math_ops.cast(tensor.values, dtypes.int64)) + # If we have weights they must be a RaggedTensor. + if weight is not None: + if not isinstance(weight, ragged_tensor.RaggedTensor): + raise ValueError("Weight for {} is type {} which does not match " + "type input which is RaggedTensor.".format( + path, type(weight))) + weights.append(math_ops.cast(weight.values, dtypes.float32)) + else: + weights.append(float_zeros) + + def _generate_enqueue_op( + self, + flat_inputs: List[internal_types.NativeObject], + flat_weights: List[Optional[internal_types.NativeObject]], + flat_features: List[tpu_embedding_v2_utils.FeatureConfig], + device_ordinal: int, + mode_override: Text + ) -> ops.Operation: + """Outputs a the enqueue op given the inputs and weights. + + Args: + flat_inputs: A list of input tensors. + flat_weights: A list of input weights (or None) of the same length as + flat_inputs. + flat_features: A list of FeatureConfigs of the same length as flat_inputs. + device_ordinal: The device to create the enqueue op for. + mode_override: A tensor containing the string "train" or "inference". + + Returns: + The enqueue op. + """ + # Combiners are per table, list in the same order as the table order. + combiners = [table.combiner for table in self._table_config] + + # These parallel arrays will be the inputs to the enqueue op. + # sample_indices for sparse, row_splits for ragged. + indices_or_row_splits = [] + values = [] + weights = [] + + # We have to supply a empty/zero tensor in a list position where we don't + # have data (e.g. indices for standard Tensor input, weight when no weight + # is specified). We create one op here per call, so that we reduce the + # graph size. + int_zeros = array_ops.zeros((0,), dtype=dtypes.int32) + float_zeros = array_ops.zeros((0,), dtype=dtypes.float32) + + # In the following loop we insert casts so that everything is either int32 + # or float32. This is because op inputs which are lists of tensors must be + # of the same type within the list. Moreover the CPU implementations of + # these ops cast to these types anyway, so we don't lose any data by casting + # early. + for inp, weight, (path, feature) in zip( + flat_inputs, flat_weights, flat_features): + if isinstance(inp, tensor_lib.Tensor): + self._add_data_for_tensor(inp, weight, indices_or_row_splits, values, + weights, int_zeros, float_zeros, path) + elif isinstance(inp, sparse_tensor.SparseTensor): + self._add_data_for_sparse_tensor(inp, weight, indices_or_row_splits, + values, weights, int_zeros, + float_zeros, path, feature) + elif isinstance(inp, ragged_tensor.RaggedTensor): + self._add_data_for_ragged_tensor(inp, weight, indices_or_row_splits, + values, weights, int_zeros, + float_zeros, path, feature) + else: + raise ValueError("Input {} is of unknown type {}. Please only pass " + "Tensor, SparseTensor or RaggedTensor as input to " + "enqueue.".format(path, type(inp))) + + return tpu_ops.enqueue_tpu_embedding_arbitrary_tensor_batch( + sample_indices_or_row_splits=indices_or_row_splits, + embedding_indices=values, + aggregation_weights=weights, + mode_override=mode_override, + device_ordinal=device_ordinal, + combiners=combiners) + + def _raise_error_for_incorrect_control_flow_context(self): + """Raises an error if we are not in the TPUReplicateContext.""" + # Do not allow any XLA control flow (i.e. control flow in between a + # TPUStrategy's run call and the call to this function), as we can't + # extract the enqueue from the head when in XLA control flow. + graph = ops.get_default_graph() + in_tpu_ctx = False + while graph is not None: + ctx = graph._get_control_flow_context() # pylint: disable=protected-access + while ctx is not None: + if isinstance(ctx, tpu_replication.TPUReplicateContext): + in_tpu_ctx = True + break + ctx = ctx.outer_context + if in_tpu_ctx: + break + graph = getattr(graph, "outer_graph", None) + if graph != ops.get_default_graph() and in_tpu_ctx: + raise RuntimeError( + "Current graph {} does not match graph which contains " + "TPUReplicateContext {}. This is most likely due to the fact that " + "enqueueing embedding data is called inside control flow or a " + "tf.function inside `strategy.run`. This is not supported because " + "outside compilation fails to extract the enqueue ops as the head of " + "a computation.".format(ops.get_default_graph(), graph)) + return in_tpu_ctx + + def _raise_error_for_non_direct_inputs(self, features): + """Checks all tensors in features to see if they are a direct input.""" + + # expand_composites here is important: as composite tensors pass through + # tpu.replicate, they get 'flattened' into their component tensors and then + # repacked before being passed to the tpu function. In means that it is the + # component tensors which are produced by an op with the + # "_tpu_input_identity" attribute. + for path, input_tensor in nest.flatten_with_joined_string_paths( + features, expand_composites=True): + if input_tensor.op.type == "Placeholder": + continue + try: + is_input = input_tensor.op.get_attr("_tpu_input_identity") + except ValueError: + is_input = False + if not is_input: + raise ValueError( + "Received input tensor {} which is the output of op {} (type {}) " + "which does not have the `_tpu_input_identity` attr. Please " + "ensure that the inputs to this layer are taken directly from " + "the arguments of the function called by " + "strategy.run. Two possible causes are: dynamic batch size " + "support or you are using a keras layer and are not passing " + "tensors which match the dtype of the `tf.keras.Input`s." + "If you are triggering dynamic batch size support, you can " + "disable it by passing tf.distribute.RunOptions(" + "experimental_enable_dynamic_batch_size=False) to the options " + "argument of strategy.run().".format(path, + input_tensor.op.name, + input_tensor.op.type)) + + def _raise_error_for_inputs_not_on_cpu(self, flat_inputs, flat_paths): + """Checks all tensors in features to see are placed on the CPU.""" + + def check_device(path, device_string): + spec = tf_device.DeviceSpec.from_string(device_string) + if spec.device_type == "TPU": + raise ValueError( + "Received input tensor {} which is on a TPU input device {}. Input " + "tensors for TPU embeddings must be placed on the CPU. Please " + "ensure that your dataset is prefetching tensors to the host by " + "setting the 'experimental_fetch_to_device' option of the " + "dataset distribution function. See the documentation of the " + "enqueue method for an example.".format(path, device_string)) + + # expand_composites here is important, we need to check the device of each + # underlying tensor. + for input_tensor, input_path in zip(flat_inputs, flat_paths): + if nest.is_nested_or_composite(input_tensor): + input_tensors = nest.flatten(input_tensor, expand_composites=True) + else: + input_tensors = [input_tensor] + for t in input_tensors: + if (t.op.type == "Identity" and + t.op.inputs[0].op.type == "TPUReplicatedInput"): + for tensor in t.op.inputs[0].op.inputs: + check_device(input_path, tensor.device) + else: + check_device(input_path, t.device) + + def enqueue( + self, + features, + weights=None, + training: bool = True, + name: Optional[Text] = None, + device: Optional[Text] = None): + """Enqueues id tensors for embedding lookup. + + This function enqueues a structure of features to be looked up in the + embedding tables. We expect that the input shapes of each of the tensors in + features matches the output shapes set via FeatureConfig or build method + (if any). the output shapes will be auto detected based on the input shapes + with the max_sequence_length or output shape setting in the FeatureConfig. + Note that the output shapes is based on per replica batch size. + If your input dataset is batched to the global batch size and you use + `tf.distribute.TPUStrategy`'s `experimental_distribute_dataset` + or if you use `distribute_datasets_from_function` and batch + to the per core batch size computed by the context passed to your input + function, the output shapes should match automatically. + + The auto detected the output shapes: + 1. For dense tensor, if rank 2 or above, make sure the tensor has last + dimension as 1. The output shape will be the input shape excluding + the last dimension. + 2. For sparse tensor, make sure the tensor has rank 2 and above. + a. If feature config has max_sequence_length equals 0 or output shape + set (the max_sequence_length setting will be ignored), the + output shape will be the input shape excluding the last dimension. + b. Otherwise, if the tensor is rank 2, the output shape will be input + shape with last dimension set as max_sequence_length. If the + tensor is above rank 2, the output shape will be the input shape + excluding the last dimension and the last dimension of the output + shape will be set to max_sequence_length. + 3. For ragged tensor, make sure the tensor has rank 2. + a. If feature config has max_sequence_length equals 0 or output shape + set (the max_sequence_length setting will be ignored), the + output shape will be the input shape excluding the last dimension. + b. Otherwise, the output shape will be the input shape excluding the + last dimension and the last dimension of the output shape will be + set to max_sequence_length. + + ```python + strategy = tf.distribute.TPUStrategy(...) + with strategy.scope(): + embedding = tf.tpu.experimental.embedding.TPUEmbedding(...) + + distributed_dataset = ( + strategy.distribute_datasets_from_function( + dataset_fn=..., + options=tf.distribute.InputOptions( + experimental_fetch_to_device=False)) + dataset_iterator = iter(distributed_dataset) + + @tf.function + def training_step(): + def tpu_step(tpu_features): + with tf.GradientTape() as tape: + activations = embedding.dequeue() + tape.watch(activations) + + loss = ... # some computation involving activations + + embedding_gradients = tape.gradient(loss, activations) + embedding.apply_gradients(embedding_gradients) + + embedding_features, tpu_features = next(dataset_iterator) + embedding.enqueue(embedding_features, training=True) + strategy.run(tpu_step, args=(tpu_features,)) + + training_step() + ``` + + NOTE: You should specify `training=True` when using + `embedding.apply_gradients` as above and `training=False` when not using + `embedding.apply_gradients` (e.g. for frozen embeddings or when doing + evaluation). + + For finer grained control, in the above example the line + + ``` + embedding.enqueue(embedding_features, training=True) + ``` + + may be replaced with + + ``` + per_core_embedding_features = self.strategy.experimental_local_results( + embedding_features) + + def per_core_enqueue(ctx): + core_id = ctx.replica_id_in_sync_group + device = strategy.extended.worker_devices[core_id] + embedding.enqueue(per_core_embedding_features[core_id], + device=device) + + strategy.experimental_distribute_values_from_function( + per_core_queue_inputs) + ``` + + Args: + features: A nested structure of `tf.Tensor`s, `tf.SparseTensor`s or + `tf.RaggedTensor`s, with the same structure as `feature_config`. Inputs + will be downcast to `tf.int32`. Only one type out of `tf.SparseTensor` + or `tf.RaggedTensor` is supported per call. + weights: If not `None`, a nested structure of `tf.Tensor`s, + `tf.SparseTensor`s or `tf.RaggedTensor`s, matching the above, except + that the tensors should be of float type (and they will be downcast to + `tf.float32`). For `tf.SparseTensor`s we assume the `indices` are the + same for the parallel entries from `features` and similarly for + `tf.RaggedTensor`s we assume the row_splits are the same. + training: Defaults to `True`. If `False`, enqueue the batch as inference + batch (forward pass only). Do not call `apply_gradients` when this is + `False` as this may lead to a deadlock. + name: A name for the underlying op. + device: The device name (e.g. '/task:0/device:TPU:2') where this batch + should be enqueued. This should be set if and only if features is not a + `tf.distribute.DistributedValues` and enqueue is not being called + inside a TPU context (e.g. inside `TPUStrategy.run`). + + Raises: + ValueError: When called inside a strategy.run call and input is not + directly taken from the args of the `strategy.run` call. Also if + the size of any sequence in `features` does not match corresponding + sequence in `feature_config`. Similarly for `weights`, if not `None`. + If input shapes of features is unequal or different from a previous + call. + RuntimeError: When called inside a strategy.run call and inside XLA + control flow. If batch_size is not able to be determined and build was + not called. + TypeError: If the type of any sequence in `features` does not match + corresponding sequence in `feature_config`. Similarly for `weights`, if + not `None`. + """ + if not self._using_tpu: + raise RuntimeError("enqueue is not valid when TPUEmbedding object is not " + "created under a TPUStrategy.") + + in_tpu_context = self._raise_error_for_incorrect_control_flow_context() + + nest.assert_same_structure(self._feature_config, features) + + if not self._verify_output_shapes_on_enqueue: + if not self._output_shapes or not self._built: + raise ValueError( + "Configured not to check output shapes on each enqueue() call; please " + "ensure build() was called with output shapes to initialize " + "the TPU for embeddings.") + else: + per_replica = device is None + input_shapes = self._get_input_shapes( + features, per_replica, in_tpu_context + ) + + self._maybe_build(input_shapes) + # If is already built, we still need to check if the output shapes matches + # with the previous ones. + self._check_output_shapes( + self._get_output_shapes_from_input_shapes(input_shapes)) + + flat_inputs = nest.flatten(features) + flat_weights = [None] * len(flat_inputs) + if weights is not None: + nest.assert_same_structure(self._feature_config, weights) + flat_weights = nest.flatten(weights) + flat_features = nest.flatten_with_joined_string_paths(self._feature_config) + flat_paths, _ = zip(*flat_features) + + self._raise_error_for_inputs_not_on_cpu(flat_inputs, flat_paths) + # If we are in a tpu_context, automatically apply outside compilation. + if in_tpu_context: + self._raise_error_for_non_direct_inputs(features) + + def generate_enqueue_ops(): + """Generate enqueue ops for outside compilation.""" + # Note that we put array_ops.where_v2 rather than a python if so that + # the op is explicitly create and the constant ops are both in the graph + # even though we don't expect training to be a tensor (and thus generate + # control flow automatically). This need to make it easier to re-write + # the graph later if we need to fix which mode needs to be used. + mode_override = array_ops.where_v2(training, + constant_op.constant("train"), + constant_op.constant("inference")) + # Device ordinal is -1 here, a later rewrite will fix this once the op + # is expanded by outside compilation. + enqueue_op = self._generate_enqueue_op( + flat_inputs, flat_weights, flat_features, device_ordinal=-1, + mode_override=mode_override) + + # Apply the name tag to the op. + if name is not None: + _add_key_attr(enqueue_op, name) + + tpu_replication.outside_compilation(generate_enqueue_ops) + + elif device is None: + mode_override = "train" if training else "inference" + # We generate enqueue ops per device, so we need to gather the all + # features for a single device in to a dict. + # We rely here on the fact that the devices in the PerReplica value occur + # in the same (standard) order as self._strategy.extended.worker_devices. + enqueue_ops = [] + + def _split_fn(ts, idx): + if ts is None: + return None + elif isinstance(ts, tensor_lib.Tensor): + return array_ops.split( + ts, + num_or_size_splits=self._num_cores_per_replica, + axis=0)[idx] + elif isinstance(ts, sparse_tensor.SparseTensor): + return sparse_ops.sparse_split_v2( + sp_input=ts, + num_split=self._num_cores_per_replica, + axis=0)[idx] + else: + raise ValueError("SPMD does not support raggedTensor yet.") + + def _maybe_split(ts_inputs, core_id): + if self._num_cores_per_replica is None: + return ts_inputs + else: + splitter = functools.partial(_split_fn, idx=core_id) + return nest.map_structure(splitter, ts_inputs) + + for replica_id in range(self._strategy.num_replicas_in_sync): + replica_inputs = distribute_utils.select_replica(replica_id, + flat_inputs) + replica_weights = distribute_utils.select_replica(replica_id, + flat_weights) + + if self._num_cores_per_replica: + tpu_devices = self._strategy.extended._tpu_devices[replica_id] # pylint: disable=protected-access + else: + tpu_devices = [self._strategy.extended.worker_devices[replica_id]] + # TPU devices string are like /job:worker/replica:0/task:0/device:TPU:0 + # the device ordinal is the last number + + for core_id in range(self._num_cores_per_replica or 1): + tpu_device = tpu_devices[core_id] + device_ordinal = ( + tf_device.DeviceSpec.from_string(tpu_device).device_index) + + with ops.device(device_util.get_host_for_device(tpu_device)): + enqueue_op = self._generate_enqueue_op( + _maybe_split(replica_inputs, core_id), + _maybe_split(replica_weights, core_id), + flat_features, + device_ordinal=device_ordinal, mode_override=mode_override) + + # Apply the name tag to the op. + if name is not None: + _add_key_attr(enqueue_op, name) + enqueue_ops.append(enqueue_op) + else: + mode_override = "train" if training else "inference" + device_spec = tf_device.DeviceSpec.from_string(device) + if device_spec.device_type != "TPU": + raise ValueError( + "Non-TPU device {} passed to enqueue.".format(device)) + + with ops.device(device_util.get_host_for_device(device)): + enqueue_op = self._generate_enqueue_op( + flat_inputs, flat_weights, flat_features, + device_ordinal=device_spec.device_index, + mode_override=mode_override) + + # Apply the name tag to the op. + if name is not None: + _add_key_attr(enqueue_op, name) + + def _get_input_shapes( + self, tensors, per_replica: bool, in_tpu_context: bool + ) -> List[TensorShape]: + """Get the input shapes from the input tensor.""" + input_shapes = [] + for (path, maybe_tensor), feature in zip( + nest.flatten_with_joined_string_paths(tensors), + nest.flatten(self._feature_config)): + if not in_tpu_context: + tensor = distribute_utils.select_replica(0, maybe_tensor) + else: + tensor = maybe_tensor + + if isinstance(tensor, tensor_lib.Tensor): + input_shapes.append( + self._get_input_shape_for_tensor(tensor, feature, per_replica, path) + ) + elif isinstance(tensor, sparse_tensor.SparseTensor): + input_shapes.append( + self._get_input_shape_for_sparse_tensor( + tensor, feature, per_replica, path + ) + ) + elif isinstance(tensor, ragged_tensor.RaggedTensor): + input_shapes.append( + self._get_input_shape_for_ragged_tensor( + tensor, feature, per_replica, path + ) + ) + return input_shapes + + def _get_input_shape_for_tensor( + self, tensor, feature, per_replica, path + ) -> TensorShape: + """Get the input shape for the dense tensor.""" + shape = tensor.shape.as_list() + if len(shape) < 1: + raise ValueError("Only rank 1 and above dense tensor is supported," + " find rank {} sparse tensor for input {}".format( + len(shape), path)) + if len(shape) > 1 and shape[-1] != 1: + raise ValueError( + "Rank 2 or above dense tensor should have last dimension as 1 " + "as the last dimension will always be reduced. " + "Instead got dense tensor as shape {}".format(shape)) + + if self._num_cores_per_replica and per_replica: + shape[0] = shape[0] // self._num_cores_per_replica + + return TensorShape(shape) + + def _get_input_shape_for_sparse_tensor( + self, tensor, feature, per_replica, path + ) -> TensorShape: + """Get the input shape for the sparse tensor.""" + shape = tensor.shape.as_list() + # Only 2 and above rank sparse tensor is supported. + if len(shape) < 2: + raise ValueError("Only rank 2 and above sparse tensor is supported," + " find rank {} sparse tensor for input {}".format( + len(shape), path)) + if not feature.output_shape and feature.max_sequence_length > 0: + # If the max_sequence_length is set and the output shape for FeatureConfig + # is not set, we modify the shape of the input feature. Only rank 2 + # feature output shape is modified + if len(shape) == 2: + # If the sparse tensor is 2D and max_sequence_length is set, + # we need to add one dimension to the input feature. + shape.insert(len(shape) - 1, feature.max_sequence_length) + + if self._num_cores_per_replica and per_replica and shape[0]: + shape[0] = shape[0] // self._num_cores_per_replica + + return TensorShape(shape) + + def _get_input_shape_for_ragged_tensor( + self, tensor, feature, per_replica, path + ) -> TensorShape: + """Get the input shape for the ragged tensor.""" + del per_replica # unused. + shape = tensor.shape.as_list() + # Only rank 2 ragged tensor is supported. + if len(shape) != 2: + raise ValueError("Only rank 2 ragged tensor is supported," + " find rank {} ragged tensor for input {}".format( + len(shape), path)) + if not feature.output_shape and feature.max_sequence_length > 0: + # If the max_sequence_length is set and the output shape for FeatureConfig + # is not set, add the sequence length as second last dimension of + # the ragged tensor. + shape.insert(len(shape) - 1, feature.max_sequence_length) + + return TensorShape(shape) + + def _update_output_shapes(self, incoming_output_shapes: List[TensorShape]): + """Update the existing output shapes based on the new output shapes. + + The existing output shapes always have higher piority than the new incoming + output shapes. + Args: + incoming_output_shapes: nested structure of TensorShape to override the + existing output shapes. + """ + nest.assert_same_structure(self._output_shapes, incoming_output_shapes) + updated_output_shapes = [] + for old_output_shape, incoming_output_shape in zip(self._output_shapes, + incoming_output_shapes): + if old_output_shape: + updated_output_shapes.append(old_output_shape) + else: + updated_output_shapes.append(incoming_output_shape) + self._output_shapes = updated_output_shapes + + def _check_output_shapes(self, incoming_output_shapes: List[TensorShape]): + """Check the incoming output shapes against the output shapes stored.""" + # The incoming output shape should have the same structure with the existing + # output shapes. + nest.assert_same_structure(self._output_shapes, incoming_output_shapes) + + for (path, _), old_output_shape, incoming_output_shape in zip( + nest.flatten_with_joined_string_paths(self._feature_config), + self._output_shapes, incoming_output_shapes): + # First check if both shapes are not None. + if old_output_shape and incoming_output_shape: + # We skip the check when the incoming output shape is rank 1 or 2 and + # rank of the old output shape is larger. This can happen for + # (sequence) ragged tensor, we push the check down to the enqueue op. + if (len(incoming_output_shape) == 1 or len(incoming_output_shape) + == 2) and len(old_output_shape) > len(incoming_output_shape): + continue + if len(old_output_shape) != len( + incoming_output_shape) or not self._is_tensor_shape_match( + old_output_shape, incoming_output_shape): + raise ValueError( + f"Inconsistent shape founded for input feature {path}, " + f"Output shape is set to be {old_output_shape}, " + f"But got incoming output shape {incoming_output_shape}") + + def _check_output_shapes_fully_defined(self): + """Check if the output shape is fully defined.""" + for (path, _), output_shape in zip( + nest.flatten_with_joined_string_paths(self._feature_config), + self._output_shapes): + if not output_shape.is_fully_defined(): + raise ValueError( + f"Input Feature {path} has output shape set as " + f"{output_shape} which is not fully defined. " + "Please specify the fully defined shape in either FeatureConfig " + "or for the build method.") + + def _is_tensor_shape_match(self, shape_a: TensorShape, + shape_b: TensorShape) -> bool: + """Check if shape b matches with shape a.""" + for s_a, s_b in zip(shape_a.as_list(), shape_b.as_list()): + if s_a and s_b and s_a != s_b: + return False + return True + + def _get_output_shapes_from_batch_size(self, per_replica_batch_size): + """Get the output shapes from the batch size.""" + output_shapes = [] + for feature in nest.flatten(self._feature_config): + if not feature.output_shape and feature.max_sequence_length > 0: + output_shapes.append( + TensorShape([per_replica_batch_size, feature.max_sequence_length])) + else: + output_shapes.append(TensorShape(per_replica_batch_size)) + return output_shapes + + def _create_copy_for_async_checkpoint( + self, feature_config, optimizer, pipeline_execution_with_tensor_core): + """Create a TPUEmbedding copy for checkpoint/async_checkpoint_helper.py.""" + return TPUEmbedding( + feature_config=feature_config, + optimizer=optimizer, + pipeline_execution_with_tensor_core=pipeline_execution_with_tensor_core) + + +@def_function.function +def _load_variables_impl( + config: Text, + hosts: List[Tuple[int, Text]], + variables: Dict[Text, Dict[Text, tf_variables.Variable]], + table_config: tpu_embedding_v2_utils.TableConfig): + """Load embedding tables to onto TPU for each table and host. + + Args: + config: A serialized TPUEmbeddingConfiguration proto. + hosts: A list of CPU devices, on per host. + variables: A dictionary of dictionaries of TPUEmbeddingVariables. First key + is the table name, second key is 'parameters' or the optimizer slot name. + table_config: A list of tf.tpu.experimental.embedding.TableConfig objects. + """ + def select_fn(host_id): + + def select_or_zeros(x): + if host_id >= len(x.variables): + # In the edge case where we have more hosts than variables, due to using + # a small number of rows, we load zeros for the later hosts. We copy + # the shape of the first host's variables, which we assume is defined + # because TableConfig guarantees at least one row. + return array_ops.zeros_like(x.variables[0]) + return x.variables[host_id] + + return select_or_zeros + + for host_id, host in enumerate(hosts): + with ops.device(host): + host_variables = nest.map_structure(select_fn(host_id), variables) + for table in table_config: + table.optimizer._load()( # pylint: disable=protected-access + table_name=table.name, + num_shards=len(hosts), + shard_id=host_id, + config=config, + **host_variables[table.name]) + # Ensure that only the first table/first host gets a config so that we + # don't bloat graph by attaching this large string to each op. + # We have num tables * num hosts of these so for models with a large + # number of tables training on a large slice, this can be an issue. + config = None + + +@def_function.function +def _retrieve_variables_impl( + config: Text, + hosts: List[Tuple[int, Text]], + variables: Dict[Text, Dict[Text, tf_variables.Variable]], + table_config: tpu_embedding_v2_utils.TableConfig): + """Retrieve embedding tables from TPU to host memory. + + Args: + config: A serialized TPUEmbeddingConfiguration proto. + hosts: A list of all the host CPU devices. + variables: A dictionary of dictionaries of TPUEmbeddingVariables. First key + is the table name, second key is 'parameters' or the optimizer slot name. + table_config: A list of tf.tpu.experimental.embedding.TableConfig objects. + """ + for host_id, host in enumerate(hosts): + with ops.device(host): + for table in table_config: + retrieved = table.optimizer._retrieve()( # pylint: disable=protected-access + table_name=table.name, + num_shards=len(hosts), + shard_id=host_id, + config=config) + # When there are no slot variables (e.g with SGD) this returns a + # single tensor rather than a tuple. In this case we put the tensor in + # a list to make the following code easier to write. + if not isinstance(retrieved, tuple): + retrieved = (retrieved,) + + for i, slot in enumerate(["parameters"] + + table.optimizer._slot_names()): # pylint: disable=protected-access + # We must assign the CPU variables the values of tensors that were + # returned from the TPU. + sharded_var = variables[table.name][slot] + if host_id < len(sharded_var.variables): + # In the edge case where we have more hosts than variables, due to + # using a small number of rows, we skip the later hosts. + sharded_var.variables[host_id].assign(retrieved[i]) + # Ensure that only the first table/first host gets a config so that we + # don't bloat graph by attaching this large string to each op. + # We have num tables * num hosts of these so for models with a large + # number of tables training on a large slice, this can be an issue. + config = None + + +def _save_callback(trackables, **unused_kwargs): + for trackable in trackables.values(): + trackable._retrieve_variables() # pylint: disable=protected-access + return [] + + +def _restore_callback(trackables, **unused_kwargs): + for trackable in trackables.values(): + trackable._load_variables() # pylint: disable=protected-access + + +registration.register_tf_checkpoint_saver( + "TPUEmbeddingCallback", + predicate=lambda x: isinstance(x, TPUEmbedding), + save_fn=_save_callback, + restore_fn=_restore_callback, + # Set strict_predicate_restore to `False` to because the isinstance + # predicate check does not pass after a TPUEmbedding object is loaded from + # SavedModel. + strict_predicate_restore=False +) + + +def extract_variable_info( + kwargs) -> Tuple[Text, Tuple[int, ...], dtypes.DType, Callable[[], Any]]: + """Extracts the variable creation attributes from the kwargs. + + Args: + kwargs: a dict of keyword arguments that were passed to a variable creator + scope. + + Returns: + A tuple of variable name, shape, dtype, initialization function. + """ + if (isinstance(kwargs["initial_value"], functools.partial) and ( + "shape" in kwargs["initial_value"].keywords or + kwargs["initial_value"].args)): + # Sometimes shape is passed positionally, sometimes it's passed as a kwarg. + if "shape" in kwargs["initial_value"].keywords: + shape = kwargs["initial_value"].keywords["shape"] + else: + shape = kwargs["initial_value"].args[0] + return (kwargs["name"], shape, + kwargs["initial_value"].keywords.get("dtype", kwargs["dtype"]), + kwargs["initial_value"].func) + elif "shape" not in kwargs or kwargs["shape"] is None or not callable( + kwargs["initial_value"]): + raise ValueError( + "Unable to extract initializer function and shape from {}. Please " + "either pass a function that expects a shape and dtype as the " + "initial value for your variable or functools.partial object with " + "the shape and dtype kwargs set. This is needed so that we can " + "initialize the shards of the ShardedVariable locally.".format( + kwargs["initial_value"])) + else: + return (kwargs["name"], kwargs["shape"], kwargs["dtype"], + kwargs["initial_value"]) + + +def make_sharded_variable_creator( + hosts: List[Text]) -> Callable[..., TPUEmbeddingVariable]: + """Makes a sharded variable creator given a list of hosts. + + Args: + hosts: a list of tensorflow devices on which to shard the tensors. + + Returns: + A variable creator function. + """ + + def sharded_variable_creator( + next_creator: Callable[..., tf_variables.Variable], *args, **kwargs): + """The sharded variable creator.""" + kwargs["skip_mirrored_creator"] = True + + num_hosts = len(hosts) + name, shape, dtype, unwrapped_initial_value = extract_variable_info(kwargs) + initial_value = kwargs["initial_value"] + rows = shape[0] + cols = shape[1] + partial_partition = rows % num_hosts + full_rows_per_host = rows // num_hosts + # We partition as if we were using MOD sharding: at least + # `full_rows_per_host` rows to `num_hosts` hosts, where the first + # `partial_partition` hosts get an additional row when the number of rows + # is not cleanly divisible. Note that `full_rows_per_host` may be zero. + partitions = ( + [full_rows_per_host + 1] * partial_partition + + [full_rows_per_host] * (num_hosts - partial_partition)) + variables = [] + sharding_aware = "shard_info" in tf_inspect.getargspec(initial_value).args + + # Keep track of offset for sharding aware initializers. + offset = 0 + kwargs["dtype"] = dtype + for i, p in enumerate(partitions): + if p == 0: + # Skip variable creation for empty partitions, resulting from the edge + # case of 'rows < num_hosts'. This is safe because both load/restore + # can handle the missing values. + continue + with ops.device(hosts[i]): + kwargs["name"] = "{}_{}".format(name, i) + kwargs["shape"] = (p, cols) + if sharding_aware: + shard_info = base.ShardInfo(kwargs["shape"], (offset, 0)) + kwargs["initial_value"] = functools.partial( + initial_value, shard_info=shard_info) + offset += p + else: + kwargs["initial_value"] = functools.partial( + unwrapped_initial_value, kwargs["shape"], dtype=dtype) + variables.append(next_creator(*args, **kwargs)) + return TPUEmbeddingVariable(variables, name=name) + return sharded_variable_creator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..53fec7c18f619d2117ca0e27d8bf973ea4d02905 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_embedding_v2_utils.py @@ -0,0 +1,1324 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Companion classes for mid level API for TPU Embeddings in TF2.""" + +import abc +import math +import typing +from typing import Any, Dict, Callable, Iterable, List, Optional, Text, Tuple, TypeVar, Union + +from absl import logging + +from tensorflow.core.protobuf.tpu import optimization_parameters_pb2 +from tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2 +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import sharded_variable +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.framework import device_spec +from tensorflow.python.framework import ops +from tensorflow.python.framework.tensor_shape import TensorShape +from tensorflow.python.ops import init_ops_v2 +from tensorflow.python.ops import variables as tf_variables +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.types import core +from tensorflow.python.util.tf_export import tf_export + + +TableVariable = TypeVar("TableVariable", sharded_variable.ShardedVariable, + tf_variables.Variable) +SlotVarCreationFnType = Callable[ + [TableVariable, List[Text], List[init_ops_v2.Initializer]], + Dict[Text, TableVariable]] +ClipValueType = Union[Tuple[float, float], float] + + +class _Optimizer(metaclass=abc.ABCMeta): + """Base class for all optimizers, with common parameters.""" + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]], + use_gradient_accumulation: bool, + clip_weight_min: Optional[float], + clip_weight_max: Optional[float], + weight_decay_factor: Optional[float], + multiply_weight_decay_factor_by_learning_rate: bool, + clipvalue: Optional[ClipValueType] = None, + slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None, + low_dimensional_packing_status: bool = False, + ): + self.learning_rate = learning_rate + self.use_gradient_accumulation = use_gradient_accumulation + self.clip_weight_min = clip_weight_min + self.clip_weight_max = clip_weight_max + if not use_gradient_accumulation and clipvalue is not None: + raise ValueError( + f"When `use_gradient_accumulation` is False, gradient clipping " + f"cannot be used and `clipvalue` should be left as None. " + f"Received value {clipvalue} for argument `clipvalue`.") + if clipvalue is None: + clipvalue = (None, None) + elif not isinstance(clipvalue, tuple): + clipvalue = (-1. * clipvalue, clipvalue) + self.clip_gradient_min, self.clip_gradient_max = clipvalue + + self.weight_decay_factor = weight_decay_factor + self.multiply_weight_decay_factor_by_learning_rate = ( + multiply_weight_decay_factor_by_learning_rate) + + if (slot_variable_creation_fn is not None and + not callable(slot_variable_creation_fn)): + raise ValueError( + f"Argument `slot_variable_creation_fn` must be either None or a " + f"callable. Received: {slot_variable_creation_fn}") + self.slot_variable_creation_fn = slot_variable_creation_fn + self.low_dimensional_packing_status = low_dimensional_packing_status + + @abc.abstractmethod + def _slot_names(self) -> List[Text]: + """Returns the name of all the slot variables. + + This does not include the 'parameters' variable and these names must match + the names of the slots variables as used in the corresponding + `tpu_ops.load_tpu_embedding_*` ops. + """ + raise NotImplementedError + + @abc.abstractmethod + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + """Returns initializers for slot variables. + + This returns a parallel list to self._slot_names(). + """ + raise NotImplementedError + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters): + """Sets the optimizer fields in the OptimizationParameters.""" + if self.use_gradient_accumulation: + parameters.gradient_accumulation_status = ( + optimization_parameters_pb2.GradientAccumulationStatus.ENABLED) + else: + parameters.gradient_accumulation_status = ( + optimization_parameters_pb2.GradientAccumulationStatus.DISABLED) + + if self.clip_weight_min is not None: + parameters.clipping_limits.lower.value = self.clip_weight_min + + if self.clip_weight_max is not None: + parameters.clipping_limits.upper.value = self.clip_weight_max + + if self.clip_gradient_min is not None: + parameters.gradient_clipping_limits.lower.value = self.clip_gradient_min + + if self.clip_gradient_max is not None: + parameters.gradient_clipping_limits.upper.value = self.clip_gradient_max + + if self.weight_decay_factor: + parameters.weight_decay_factor = self.weight_decay_factor + if self.multiply_weight_decay_factor_by_learning_rate: + parameters.multiply_weight_decay_factor_by_learning_rate = True + + parameters.low_dimensional_packing_status = ( + self.low_dimensional_packing_status + ) + + @abc.abstractmethod + def _load(self) -> Callable[..., ops.Operation]: + """Returns the load function for the optimizer.""" + raise NotImplementedError + + @abc.abstractmethod + def _retrieve(self) -> Callable[..., core.Tensor]: + """Returns the retrieve function for the optimizer.""" + raise NotImplementedError + + def _create_slots( + self, table: "TableConfig", + variable_creator: Callable[[Text, init_ops_v2.Initializer], + tf_variables.Variable] + ) -> Dict[Text, tf_variables.Variable]: + """Creates slot variables for table. + + Args: + table: The table variable to create slots for. + variable_creator: A function which creates variables. Takes parameters + 'name', 'initializer'. + + Returns: + A dict of variables, keyed by self._slot_names(). + """ + if self.slot_variable_creation_fn is not None: + return self.slot_variable_creation_fn(table, self._slot_names(), + self._slot_initializers()) + else: + slots = {} + for slot, initializer in zip(self._slot_names(), + self._slot_initializers()): + slots[slot] = variable_creator(slot, initializer) + return slots + + def __eq__(self, other: Any) -> Union[Any, bool]: + if isinstance(other, self.__class__): + return all([ + attr1 == attr2 + for attr1, attr2 in zip(self.__dict__.items(), other.__dict__.items()) + ]) + else: + return False + + def __hash__(self) -> int: + return hash(tuple(self.__dict__.items())) + + +@tf_export("tpu.experimental.embedding.SGD") +class SGD(_Optimizer): + """Optimization parameters for stochastic gradient descent for TPU embeddings. + + Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` + argument to set the global optimizer and its parameters: + + ``` + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + ... + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + ``` + + This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the + optimizer parameter to set a table specific optimizer. This will override the + optimizer and parameters for global embedding optimizer defined above: + + ``` + table_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=..., + optimizer=tf.tpu.experimental.embedding.SGD(0.2)) + table_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + + feature_config = ( + tf.tpu.experimental.embedding.FeatureConfig( + table=table_one), + tf.tpu.experimental.embedding.FeatureConfig( + table=table_two)) + + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.SGD(0.1)) + ``` + + In the above example, the first feature will be looked up in a table that has + a learning rate of 0.2 while the second feature will be looked up in a table + that has a learning rate of 0.1. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + """ + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]] = 0.01, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: bool = None, + clipvalue: Optional[ClipValueType] = None, + low_dimensional_packing_status: bool = False, + ): + """Optimization parameters for stochastic gradient descent. + + Args: + learning_rate: The learning rate. It should be a floating point value or a + callable taking no arguments for a dynamic learning rate. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. Weights are decayed by multiplying the weight + by this factor each step. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + clipvalue: Controls clipping of the gradient. Set to either a single + positive scalar value to get clipping or a tiple of scalar values (min, + max) to set a separate maximum or minimum. If one of the two entries is + None, then there will be no clipping that direction. Note if this is + set, you may see a decrease in performance as gradient accumulation + will be enabled (it is normally off for SGD as it has no affect on + accuracy). See + 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for more + information on gradient accumulation and its impact on tpu embeddings. + low_dimensional_packing_status: Status of the low-dimensional embedding + packing optimization controls whether to optimize the packing of + 1-dimensional, 2-dimensional, and 4-dimensional embedding tables in + memory. + """ + super().__init__( + learning_rate, + use_gradient_accumulation, + clip_weight_min, + clip_weight_max, + weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate, + clipvalue, + None, + low_dimensional_packing_status, + ) + + def _slot_names(self) -> List[Text]: + return [] + + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + return [] + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters): + super()._set_optimization_parameters(parameters) + parameters.stochastic_gradient_descent.SetInParent() + + def _load(self) -> Callable[..., ops.Operation]: + return tpu_ops.load_tpu_embedding_stochastic_gradient_descent_parameters + + def _retrieve(self) -> Callable[..., core.Tensor]: + return tpu_ops.retrieve_tpu_embedding_stochastic_gradient_descent_parameters + + +@tf_export("tpu.experimental.embedding.Adagrad") +class Adagrad(_Optimizer): + """Optimization parameters for Adagrad with TPU embeddings. + + Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` + argument to set the global optimizer and its parameters: + + ```python + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + ... + optimizer=tf.tpu.experimental.embedding.Adagrad(0.1)) + ``` + + This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the + optimizer parameter to set a table specific optimizer. This will override the + optimizer and parameters for global embedding optimizer defined above: + + ```python + table_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=..., + optimizer=tf.tpu.experimental.embedding.Adagrad(0.2)) + table_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + + feature_config = ( + tf.tpu.experimental.embedding.FeatureConfig( + table=table_one), + tf.tpu.experimental.embedding.FeatureConfig( + table=table_two)) + + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.Adagrad(0.1)) + ``` + + In the above example, the first feature will be looked up in a table that has + a learning rate of 0.2 while the second feature will be looked up in a table + that has a learning rate of 0.1. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + """ + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]] = 0.001, + initial_accumulator_value: float = 0.1, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: bool = None, + slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None, + clipvalue: Optional[ClipValueType] = None, + low_dimensional_packing_status: bool = False, + ): + """Optimization parameters for Adagrad. + + Args: + learning_rate: The learning rate. It should be a floating point value or a + callable taking no arguments for a dynamic learning rate. + initial_accumulator_value: initial accumulator for Adagrad. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + slot_variable_creation_fn: If you wish do directly control the creation of + the slot variables, set this to a callable taking three parameters: a + table variable, a list of slot names to create for it, and a list of + initializers. This function should return a dict with the slot names as + keys and the created variables as values with types matching the table + variable. When set to None (the default), uses the built-in variable + creation. + clipvalue: Controls clipping of the gradient. Set to either a single + positive scalar value to get clipping or a tuple of scalar values (min, + max) to set a separate maximum or minimum. If one of the two entries is + None, then there will be no clipping that direction. + low_dimensional_packing_status: Status of the low-dimensional embedding + packing optimization controls whether to optimize the packing of + 1-dimensional, 2-dimensional, and 4-dimensional embedding tables in + memory. + """ + super().__init__( + learning_rate, + use_gradient_accumulation, + clip_weight_min, + clip_weight_max, + weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate, + clipvalue, + slot_variable_creation_fn, + low_dimensional_packing_status, + ) + if initial_accumulator_value <= 0: + raise ValueError( + f"Argument `initial_accumulator_value` must be a positive float. " + f"Received: {initial_accumulator_value}") + self.initial_accumulator_value = initial_accumulator_value + + def _slot_names(self) -> List[Text]: + return ["accumulators"] + + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + return [ + init_ops_v2.Constant( + self.initial_accumulator_value, support_partition=True + ) + ] + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters): + super()._set_optimization_parameters(parameters) + parameters.adagrad.SetInParent() + + def _load(self) -> Callable[..., ops.Operation]: + return tpu_ops.load_tpu_embedding_adagrad_parameters + + def _retrieve(self) -> Callable[..., core.Tensor]: + return tpu_ops.retrieve_tpu_embedding_adagrad_parameters + + +@tf_export("tpu.experimental.embedding.AdagradMomentum") +class AdagradMomentum(_Optimizer): + """Optimization parameters for Adagrad + Momentum with TPU embeddings. + + Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` + argument to set the global optimizer and its parameters: + + ```python + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + ... + optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.1)) + ``` + + This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the + optimizer parameter to set a table specific optimizer. This will override the + optimizer and parameters for global embedding optimizer defined above: + + ```python + table_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=..., + optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.2)) + table_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + + feature_config = ( + tf.tpu.experimental.embedding.FeatureConfig( + table=table_one), + tf.tpu.experimental.embedding.FeatureConfig( + table=table_two)) + + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.AdagradMomentum(0.1)) + ``` + + In the above example, the first feature will be looked up in a table that has + a learning rate of 0.2 while the second feature will be looked up in a table + that has a learning rate of 0.1. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + """ + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]] = 0.001, + momentum: float = 0.0, + use_nesterov: bool = False, + exponent: float = 2, + beta2: float = 1, + epsilon: float = 1e-10, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: bool = None, + slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None, + clipvalue: Optional[ClipValueType] = None, + low_dimensional_packing_status: bool = False, + ): + """Optimization parameters for Adagrad + Momentum. + + Args: + learning_rate: The learning rate. It should be a floating point value or a + callable taking no arguments for a dynamic learning rate. + momentum: Moving average parameter for the momentum accumulator. + use_nesterov: Whether to use the Nesterov variant of momentum. See + Sutskever et al., 2013. + exponent: Exponent for the Adagrad accumulator. + beta2: Moving average parameter for the Adagrad accumulator. + epsilon: initial accumulator for Adagrad accumulator. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + slot_variable_creation_fn: If you wish do directly control the creation of + the slot variables, set this to a callable taking three parameters: a + table variable, a list of slot names to create for it, and a list of + initializers. This function should return a dict with the slot names as + keys and the created variables as values with types matching the table + variable. When set to None (the default), uses the built-in variable + creation. + clipvalue: Controls clipping of the gradient. Set to either a single + positive scalar value to get clipping or a tuple of scalar values (min, + max) to set a separate maximum or minimum. If one of the two entries is + None, then there will be no clipping that direction. + low_dimensional_packing_status: Status of the low-dimensional embedding + packing optimization controls whether to optimize the packing of + 1-dimensional, 2-dimensional, and 4-dimensional embedding tables in + memory. + """ + super().__init__( + learning_rate, + use_gradient_accumulation, + clip_weight_min, + clip_weight_max, + weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate, + clipvalue, + slot_variable_creation_fn, + low_dimensional_packing_status, + ) + if epsilon <= 0: + raise ValueError("Adagrad momentum: epsilon must be positive") + if exponent <= 0: + raise ValueError("Adagrad momentum: Precondition exponent must >0") + self.momentum = momentum + self.use_nesterov = use_nesterov + self.exponent = exponent + self.beta2 = beta2 + self.epsilon = epsilon + + def _slot_names(self) -> List[Text]: + return ["accumulators", "momenta"] + + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + return [ + init_ops_v2.Constant(support_partition=True), + init_ops_v2.Constant(support_partition=True), + ] + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters + ): + super()._set_optimization_parameters(parameters) + parameters.adagrad_momentum.SetInParent() + parameters.adagrad_momentum.momentum = self.momentum + parameters.adagrad_momentum.use_nesterov = self.use_nesterov + parameters.adagrad_momentum.exponent = self.exponent + parameters.adagrad_momentum.beta2 = self.beta2 + parameters.adagrad_momentum.epsilon = self.epsilon + + def _load(self) -> Callable[..., ops.Operation]: + return tpu_ops.load_tpu_embedding_adagrad_momentum_parameters + + def _retrieve(self) -> Callable[..., core.Tensor]: + return tpu_ops.retrieve_tpu_embedding_adagrad_momentum_parameters + + +@tf_export("tpu.experimental.embedding.FTRL") +class FTRL(_Optimizer): + """Optimization parameters for FTRL with TPU embeddings. + + See Algorithm 1 of this + [paper](https://research.google.com/pubs/archive/41159.pdf). + + Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` + argument to set the global optimizer and its parameters: + + ```python + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + ... + optimizer=tf.tpu.experimental.embedding.FTRL(0.1)) + ``` + + This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the + optimizer parameter to set a table specific optimizer. This will override the + optimizer and parameters for global embedding optimizer defined above: + + ```python + table_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=..., + optimizer=tf.tpu.experimental.embedding.FTRL(0.2)) + table_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + + feature_config = ( + tf.tpu.experimental.embedding.FeatureConfig( + table=table_one), + tf.tpu.experimental.embedding.FeatureConfig( + table=table_two)) + + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.FTRL(0.1)) + ``` + + In the above example, the first feature will be looked up in a table that has + a learning rate of 0.2 while the second feature will be looked up in a table + that has a learning rate of 0.1. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + """ + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]] = 0.001, + learning_rate_power: float = -0.5, + l1_regularization_strength: float = 0.0, + l2_regularization_strength: float = 0.0, + beta: float = 0.0, + initial_accumulator_value: float = 0.1, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: bool = None, + slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None, + clipvalue: Optional[ClipValueType] = None, + multiply_linear_by_learning_rate: bool = False, + allow_zero_accumulator: bool = False, + low_dimensional_packing_status: bool = False, + ): + """Optimization parameters for Adagrad. + + Args: + learning_rate: The learning rate. It should be a floating point value or a + callable taking no arguments for a dynamic learning rate. + learning_rate_power: A float value, must be less or equal to zero. + Controls how the learning rate decreases during training. Use zero for a + fixed learning rate. + l1_regularization_strength: A float value, must be greater than or equal + to zero. + l2_regularization_strength: A float value, must be greater than or equal + to zero. + beta: A float value, representing the beta value from the paper. + initial_accumulator_value: The starting value for accumulators. Only zero + or positive values are allowed. + use_gradient_accumulation: setting this to `False` makes embedding + gradients calculation less accurate but faster. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + slot_variable_creation_fn: If you wish do directly control the creation of + the slot variables, set this to a callable taking three parameters: a + table variable, a list of slot names to create for it, and a list of + initializers. This function should return a dict with the slot names as + keys and the created variables as values with types matching the table + variable. When set to None (the default), uses the built-in variable + creation. + clipvalue: Controls clipping of the gradient. Set to either a single + positive scalar value to get clipping or a tuple of scalar values (min, + max) to set a separate maximum or minimum. If one of the two entries is + None, then there will be no clipping that direction. + multiply_linear_by_learning_rate: If set to True, a modified formula is + used for FTRL that treats the "linear" accumulator as being + pre-multiplied by the learning rate (i.e., the accumulator named + "linear" actually stores "linear * learning_rate"). Other than + checkpoint compatibility, this is mathematically equivalent for a static + learning rate; for a dynamic learning rate, it is nearly the same as + long as the learning rate does not change quickly. The benefit of this + is that the modified formula handles zero and near-zero learning rates + without producing NaNs, improving flexibility for learning rate ramp-up. + allow_zero_accumulator: If set to True, changes some internal formulas to + allow zero and near-zero accumulator values at the cost of some + performance; this only needs to be set if you are using an initial + accumulator value of zero, which is uncommon. + low_dimensional_packing_status: Status of the low-dimensional embedding + packing optimization controls whether to optimize the packing of + 1-dimensional, 2-dimensional, and 4-dimensional embedding tables in + memory. + """ + super().__init__( + learning_rate, + use_gradient_accumulation, + clip_weight_min, + clip_weight_max, + weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate, + clipvalue, + slot_variable_creation_fn, + low_dimensional_packing_status, + ) + if initial_accumulator_value <= 0: + raise ValueError( + f"Argument `initial_accumulator_value` must be a positive float. " + f"Received: {initial_accumulator_value}") + self.initial_accumulator_value = initial_accumulator_value + self.learning_rate_power = learning_rate_power + self.l1_regularization_strength = l1_regularization_strength + self.l2_regularization_strength = l2_regularization_strength + self.beta = beta + self.multiply_linear_by_learning_rate = multiply_linear_by_learning_rate + self.allow_zero_accumulator = allow_zero_accumulator + + def _slot_names(self) -> List[Text]: + return ["accumulators", "linears"] + + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + return [ + init_ops_v2.Constant( + self.initial_accumulator_value, support_partition=True + ), + init_ops_v2.Constant(support_partition=True), + ] + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters + ): + super()._set_optimization_parameters(parameters) + ftrl = parameters.ftrl + ftrl.l1 = self.l1_regularization_strength + ftrl.l2 = self.l2_regularization_strength + ftrl.lr_power = self.learning_rate_power + ftrl.beta = self.beta + ftrl.multiply_linear_by_lr = self.multiply_linear_by_learning_rate + ftrl.allow_zero_accumulator = self.allow_zero_accumulator + + def _load(self) -> Callable[..., ops.Operation]: + return tpu_ops.load_tpu_embedding_ftrl_parameters + + def _retrieve(self) -> Callable[..., core.Tensor]: + return tpu_ops.retrieve_tpu_embedding_ftrl_parameters + + +@tf_export("tpu.experimental.embedding.Adam") +class Adam(_Optimizer): + """Optimization parameters for Adam with TPU embeddings. + + Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer` + argument to set the global optimizer and its parameters: + + NOTE: By default this optimizer is lazy, i.e. it will not apply the gradient + update of zero to rows that were not looked up. You can change this behavior + by setting `lazy_adam` to `False`. + + ```python + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + ... + optimizer=tf.tpu.experimental.embedding.Adam(0.1)) + ``` + + This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the + optimizer parameter to set a table specific optimizer. This will override the + optimizer and parameters for global embedding optimizer defined above: + + ```python + table_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=..., + optimizer=tf.tpu.experimental.embedding.Adam(0.2)) + table_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + + feature_config = ( + tf.tpu.experimental.embedding.FeatureConfig( + table=table_one), + tf.tpu.experimental.embedding.FeatureConfig( + table=table_two)) + + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.Adam(0.1)) + ``` + + In the above example, the first feature will be looked up in a table that has + a learning rate of 0.2 while the second feature will be looked up in a table + that has a learning rate of 0.1. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + """ + + def __init__( + self, + learning_rate: Union[float, Callable[[], float]] = 0.001, + beta_1: float = 0.9, + beta_2: float = 0.999, + epsilon: float = 1e-07, + lazy_adam: bool = True, + sum_inside_sqrt: bool = True, + use_gradient_accumulation: bool = True, + clip_weight_min: Optional[float] = None, + clip_weight_max: Optional[float] = None, + weight_decay_factor: Optional[float] = None, + multiply_weight_decay_factor_by_learning_rate: bool = None, + slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None, + clipvalue: Optional[ClipValueType] = None, + low_dimensional_packing_status: bool = False, + ): + """Optimization parameters for Adam. + + See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a + complete description of these parameters and their impacts on the optimizer + algorithm. + + Args: + learning_rate: The learning rate. It should be a floating point value or a + callable taking no arguments for a dynamic learning rate. + beta_1: A float value. The exponential decay rate for the 1st moment + estimates. + beta_2: A float value. The exponential decay rate for the 2nd moment + estimates. + epsilon: A small constant for numerical stability. + lazy_adam: Use lazy Adam instead of Adam. Lazy Adam trains faster. + sum_inside_sqrt: When this is true, the Adam update formula is changed + from `m / (sqrt(v) + epsilon)` to `m / sqrt(v + epsilon**2)`. This + option improves the performance of TPU training and is not expected to + harm model quality. + use_gradient_accumulation: Setting this to `False` makes embedding + gradients calculation less accurate but faster. + clip_weight_min: the minimum value to clip by; None means -infinity. + clip_weight_max: the maximum value to clip by; None means +infinity. + weight_decay_factor: amount of weight decay to apply; None means that the + weights are not decayed. + multiply_weight_decay_factor_by_learning_rate: if true, + `weight_decay_factor` is multiplied by the current learning rate. + slot_variable_creation_fn: If you wish do directly control the creation of + the slot variables, set this to a callable taking three parameters: a + table variable, a list of slot names to create for it, and a list of + initializers. This function should return a dict with the slot names as + keys and the created variables as values with types matching the table + variable. When set to None (the default), uses the built-in variable + creation. + clipvalue: Controls clipping of the gradient. Set to either a single + positive scalar value to get clipping or a tiple of scalar values (min, + max) to set a separate maximum or minimum. If one of the two entries is + None, then there will be no clipping that direction. + low_dimensional_packing_status: Status of the low-dimensional embedding + packing optimization controls whether to optimize the packing of + 1-dimensional, 2-dimensional, and 4-dimensional embedding tables in + memory. + """ + super(Adam, self).__init__( + learning_rate, + use_gradient_accumulation, + clip_weight_min, + clip_weight_max, + weight_decay_factor, + multiply_weight_decay_factor_by_learning_rate, + clipvalue, + slot_variable_creation_fn, + low_dimensional_packing_status, + ) + if beta_1 < 0. or beta_1 >= 1.: + raise ValueError( + f"Argument `beta_1` must be >= 0 and < 1. Received: {beta_1}.") + if beta_2 < 0. or beta_2 >= 1.: + raise ValueError( + f"Argument `beta_2` must be >= 0 and < 1. Received: {beta_1}.") + if epsilon <= 0.: + raise ValueError("epsilon must be positive; got {}.".format(epsilon)) + if not use_gradient_accumulation and not lazy_adam: + raise ValueError( + "When disabling lazy Adam (`lazy_adam=False`), " + "gradient accumulation must be used. " + "Set `use_gradient_accumulation` to False.") + + self.beta_1 = beta_1 + self.beta_2 = beta_2 + self.epsilon = epsilon + self.lazy_adam = lazy_adam + self.sum_inside_sqrt = sum_inside_sqrt + + def _slot_names(self) -> List[Text]: + return ["momenta", "velocities"] + + def _slot_initializers(self) -> List[init_ops_v2.Initializer]: + return [ + init_ops_v2.Constant(support_partition=True), + init_ops_v2.Constant(support_partition=True), + ] + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters + ): + super(Adam, self)._set_optimization_parameters(parameters) + parameters.adam.beta1 = self.beta_1 + parameters.adam.beta2 = self.beta_2 + parameters.adam.epsilon = self.epsilon + parameters.adam.use_non_lazy_adam = not self.lazy_adam + parameters.adam.use_sum_inside_sqrt = self.sum_inside_sqrt + + def _load(self) -> Callable[..., ops.Operation]: + return tpu_ops.load_tpu_embedding_adam_parameters + + def _retrieve(self) -> Callable[..., core.Tensor]: + return tpu_ops.retrieve_tpu_embedding_adam_parameters + + +@tf_export("tpu.experimental.embedding.QuantizationConfig") +class QuantizationConfig: + """Settings for simulated quantization of the tpu embedding table. + + When simulated quantization is enabled, the results of the embedding lookup + are clipped and quantized according to the settings here before the combiner + is applied. + + For example, to quantize `input` the following is done: + ```python + if input < lower + input = lower + if input > upper + input = upper + quantum = (upper - lower) / (num_buckets - 1) + input = math.floor((input - lower) / quantum + 0.5) * quantium + lower + ``` + + See tensorflow/core/protobuf/tpu/optimization_parameters.proto for more + details. + + NOTE: This does not change the storage type of the embedding table, that will + continue to be float32 as will the saved variable in the checkpoint. You will + have to manually quantize the variable (typically with the same algorithm and + settings as above) manually. + """ + + def __init__(self, num_buckets: int, lower: float, upper: float): + """Simulated quantizaiton configuration. + + Args: + num_buckets: The number of quantization buckets, must be atleast 2. + lower: The lower bound for the quantization range. + upper: The upper bound for the quantization range. + + Returns: + `QuantizationConfig`. + + Raises: + ValueError: if `num_buckets` is less than 2. + """ + if num_buckets < 2: + raise ValueError(f"num_buckets is {num_buckets}, must be at least 2 for " + f"simulated quantization.") + + self.num_buckets = num_buckets + self.lower = lower + self.upper = upper + + def _set_optimization_parameters( + self, parameters: optimization_parameters_pb2.OptimizationParameters): + parameters.simulated_quantization.enabled = True + parameters.simulated_quantization.num_buckets = self.num_buckets + parameters.simulated_quantization.clipping_limits.lower.value = self.lower + parameters.simulated_quantization.clipping_limits.upper.value = self.upper + + def __repr__(self): + return ("QuantizationConfig(num_buckets={num_buckets!r}, lower={lower!r}, " + "upper={upper!r})".format( + num_buckets=self.num_buckets, + lower=self.lower, + upper=self.upper)) + + +@tf_export("tpu.experimental.embedding.TableConfig") +class TableConfig: + """Configuration data for one embedding table. + + This class holds the configuration data for a single embedding table. It is + used as the `table` parameter of a + `tf.tpu.experimental.embedding.FeatureConfig`. Multiple + `tf.tpu.experimental.embedding.FeatureConfig` objects can use the same + `tf.tpu.experimental.embedding.TableConfig` object. In this case a shared + table will be created for those feature lookups. + + ```python + table_config_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + table_config_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + feature_config = { + 'feature_one': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_two': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_three': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_two)} + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.Adam(0.1)) + ``` + + The above configuration has 2 tables, and three features. The first two + features will be looked up in the first table and the third feature will be + looked up in the second table. + + """ + + def __init__(self, + vocabulary_size: int, + dim: int, + initializer: Optional[Callable[[Any], None]] = None, + optimizer: Optional[_Optimizer] = None, + combiner: Text = "mean", + name: Optional[Text] = None, + quantization_config: QuantizationConfig = None): + """Embedding table configuration. + + Args: + vocabulary_size: Size of the table's vocabulary (number of rows). + dim: The embedding dimension (width) of the table. + initializer: A callable initializer taking one parameter, the shape of the + variable that will be initialized. Will be called once per task, to + initialize that task's shard of the embedding table. If not specified, + defaults to `truncated_normal_initializer` with mean `0.0` and standard + deviation `1/sqrt(dim)`. + optimizer: An optional instance of an optimizer parameters class, instance + of one of `tf.tpu.experimental.embedding.SGD`, + `tf.tpu.experimental.embedding.Adagrad` or + `tf.tpu.experimental.embedding.Adam`. If set will override the global + optimizer passed to `tf.tpu.experimental.embedding.TPUEmbedding`. + combiner: A string specifying how to reduce if there are multiple entries + in a single row. Currently 'mean', 'sqrtn', 'sum' are supported, with + 'mean' the default. 'sqrtn' often achieves good accuracy, in particular + with bag-of-words columns. For more information, see + `tf.nn.embedding_lookup_sparse`. + name: An optional string used to name the table. Must be defined if + running on SparseCore. + quantization_config: The simulated quantization config. An instance of + `tf.tpu.experimental.embedding.QuantizationConfig`. See the class for + more documentation. + + Returns: + `TableConfig`. + + Raises: + ValueError: if `vocabulary_size` is not a positive integer. + ValueError: if `dim` is not a positive integer. + ValueError: if `initializer` is specified and is not callable. + ValueError: if `combiner` is not supported. + """ + if not isinstance(vocabulary_size, int) or vocabulary_size < 1: + raise ValueError( + f"Argument `vocabulary_size` must be an int and must be >= 1. " + f"Received: {vocabulary_size}") + + if not isinstance(dim, int) or dim < 1: + raise ValueError( + f"Argument `dim` (embedding dimension) " + f"must be an int and must be >= 1. Received: {dim}") + + if (initializer is not None) and (not callable(initializer)): + raise ValueError( + f"Argument `initializer` must be a callable (or None). " + f"Received: {initializer}") + if initializer is None: + initializer = init_ops_v2.TruncatedNormal(mean=0.0, + stddev=1/math.sqrt(dim)) + accepted_combiners = ("mean", "sum", "sqrtn") + if combiner not in accepted_combiners: + raise ValueError( + f"Argument `combiner` must be one of {accepted_combiners}. " + f"Received: {combiner}") + + if name is None: + logging.warning( + "Name of the table config must be specified for running on" + " SparseCore. Different table configs must have unique names." + ) + + self.vocabulary_size = vocabulary_size + self.dim = dim + self.initializer = initializer + self.optimizer = optimizer + self.combiner = combiner + self.name = name + self.quantization_config = quantization_config + + def __repr__(self): + # If using the default initializer, just print "None" for clarity. + initializer = self.initializer + + if isinstance(initializer, init_ops_v2.TruncatedNormal): + # PY2 type checking can't infer type of initializer even after if. + initializer = typing.cast(init_ops_v2.TruncatedNormal, initializer) + if (initializer.mean == 0.0 + and math.isclose(initializer.stddev, 1/math.sqrt(self.dim))): + initializer = None + + return ("TableConfig(vocabulary_size={vocabulary_size!r}, dim={dim!r}, " + "initializer={initializer!r}, optimizer={optimizer!r}, " + "combiner={combiner!r}, name={name!r}, " + "quantization_config={quantization!r})".format( + vocabulary_size=self.vocabulary_size, + dim=self.dim, + initializer=initializer, + optimizer=self.optimizer, + combiner=self.combiner, + name=self.name, + quantization=self.quantization_config, + )) + + def _set_table_descriptor( + self, + table_descriptor: tpu_embedding_configuration_pb2 + .TPUEmbeddingConfiguration.TableDescriptor, + num_hosts: int, + learning_rate_index: Dict[Callable[[], Any], int]): + """Set the table descriptor from the table data.""" + table_descriptor.name = self.name + + # For small tables, we pad to the number of hosts so that at least one + # id will be assigned to each host. + table_descriptor.vocabulary_size = max(self.vocabulary_size, num_hosts) + table_descriptor.dimension = self.dim + + parameters = table_descriptor.optimization_parameters + + # We handle the learning rate separately here and don't allow the + # optimization class to handle this, as it doesn't know about dynamic + # rates. + if self.optimizer: + if callable(self.optimizer.learning_rate): + parameters.learning_rate.dynamic.tag = ( + learning_rate_index[self.optimizer.learning_rate]) + else: + parameters.learning_rate.constant = self.optimizer.learning_rate + if self.optimizer.low_dimensional_packing_status: + parameters.low_dimensional_packing_status = ( + optimization_parameters_pb2.LowDimensionalPackingStatus.Status.ENABLED + ) + # Use optimizer to handle the rest of the parameters. + self.optimizer._set_optimization_parameters(parameters) # pylint: disable=protected-access + + if self.quantization_config: + self.quantization_config._set_optimization_parameters(parameters) # pylint: disable=protected-access + + +@tf_export("tpu.experimental.embedding.FeatureConfig") +class FeatureConfig: + """Configuration data for one embedding feature. + + This class holds the configuration data for a single embedding feature. The + main use is to assign features to `tf.tpu.experimental.embedding.TableConfig`s + via the table parameter: + + ```python + table_config_one = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + table_config_two = tf.tpu.experimental.embedding.TableConfig( + vocabulary_size=..., + dim=...) + feature_config = { + 'feature_one': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_two': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_one), + 'feature_three': tf.tpu.experimental.embedding.FeatureConfig( + table=table_config_two)} + embedding = tf.tpu.experimental.embedding.TPUEmbedding( + feature_config=feature_config, + batch_size=... + optimizer=tf.tpu.experimental.embedding.Adam(0.1)) + ``` + + The above configuration has 2 tables, and three features. The first two + features will be looked up in the first table and the third feature will be + looked up in the second table. + + You can also specify the output shape for each feature. The output shape + should be the expected activation shape excluding the table dimension. For + dense and sparse tensor, the output shape should be the same as the input + shape excluding the last dimension. For ragged tensor, the output shape can + mismatch the input shape. + + NOTE: The `max_sequence_length` will be only used when the input tensor has + rank 2 and the `output_shape` is not set in the feature config. + + When feeding features into `embedding.enqueue` they can be `tf.Tensor`s, + `tf.SparseTensor`s or `tf.RaggedTensor`s. When the argument + `max_sequence_length` is 0, the default, you should expect a output of + `embedding.dequeue` for this feature of shape `(batch_size, dim)`. If + `max_sequence_length` is greater than 0, the feature is embedded as a sequence + and padded up to the given length. The shape of the output for this feature + will be `(batch_size, max_sequence_length, dim)`. + """ + + def __init__(self, + table: TableConfig, + max_sequence_length: int = 0, + validate_weights_and_indices: bool = True, + output_shape: Optional[Union[List[int], TensorShape]] = None, + name: Optional[Text] = None): + """Feature configuration. + + Args: + table: An instance of `tf.tpu.experimental.embedding.TableConfig`, + describing the table in which this feature should be looked up. + max_sequence_length: If positive, the feature is a sequence feature with + the corresponding maximum sequence length. If the sequence is longer + than this, it will be truncated. If 0, the feature is not a sequence + feature. + validate_weights_and_indices: If true, uses safe_embedding_lookup during + serving which ensures there are no empty rows and all weights and ids + are positive at the expense of extra compute cost. + output_shape: Optional argument to config the output shape of the feature + activation. If provided, the feature feeding to the `embedding.enqueue` + has to match the shape (for ragged tensor, the input shape and output + shape can mismatch). If not provided, the shape can be either provided + to the `embedding.build` or auto detected at the runtime. + name: An optional string used to name the table. Must be defined if + running on SparseCore. + + Returns: + `FeatureConfig`. + + Raises: + ValueError: if `table` is not an instance of + `tf.tpu.experimental.embedding.TableConfig`. + ValueError: if `max_sequence_length` not an integer or is negative. + """ + if not isinstance(table, TableConfig): + raise ValueError(f"Argument `table` has invalid type {type(table)}. " + "Expected `tf.tpu.experimental.embedding.TableConfig`.") + + if not isinstance(max_sequence_length, int) or max_sequence_length < 0: + raise ValueError( + f"Argument `max_sequence_length` must be an int and must be >= 0. " + f"Received: {max_sequence_length}") + if name is None: + logging.warning( + "Name of the Feature config must be specified for running on" + " SparseCore. Different feature configs must have unique names." + ) + + self.table = table + self.max_sequence_length = max_sequence_length + self.name = name + self.output_shape = TensorShape(output_shape) + + if not isinstance( + validate_weights_and_indices, bool): + raise ValueError( + f"Argument `validate_weights_and_indices` must be a boolean. " + f"Received: {validate_weights_and_indices}") + + self.validate_weights_and_indices = validate_weights_and_indices + + def __repr__(self): + return ("FeatureConfig(table={table!r}, " + "max_sequence_length={max_sequence_length!r}, " + "validate_weights_and_indices={validate_weights_and_indices!r}, " + "output_shape={output_shape!r}, name={name!r})".format( + table=self.table, + max_sequence_length=self.max_sequence_length, + validate_weights_and_indices=self.validate_weights_and_indices, + output_shape=self.output_shape, + name=self.name)) + + +def log_tpu_embedding_configuration( + config: tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration) -> None: + """Logs a TPUEmbeddingConfiguration proto across multiple statements. + + Args: + config: TPUEmbeddingConfiguration proto to log. Necessary because + logging.info has a maximum length to each log statement, which + particularly large configs can exceed. + """ + logging.info("Beginning log of TPUEmbeddingConfiguration.") + for line in str(config).splitlines(): + logging.info(line) + logging.info("Done with log of TPUEmbeddingConfiguration.") + + +def _sort_device_spec_strings(device_strings: Iterable[str]) -> List[str]: + sorted_specs = sorted( + (device_spec.DeviceSpecV2.from_string(spec) for spec in device_strings), + key=lambda s: (s.replica, s.task, s.device_index), + ) + return [spec.to_string() for spec in sorted_specs] + + +def get_list_of_hosts(strategy: tpu_strategy.TPUStrategy) -> List[Text]: + """Returns a sorted list of CPU devices for the remote jobs. + + Args: + strategy: A TPUStrategy object. + + Returns: + A sorted list of device host strings. + """ + + list_of_hosts = [] + # Elsewehere we assume that the list of hosts is sorted. + for tpu_device in _sort_device_spec_strings(strategy.extended.worker_devices): + host = device_util.get_host_for_device(tpu_device) + if host not in list_of_hosts: + list_of_hosts.append(host) + assert len(list_of_hosts) == strategy.extended.num_hosts + return list_of_hosts diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..f28db848e56252ab3f70a9ba21ff22ccc16410a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_estimator.py @@ -0,0 +1,29 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Stub file to maintain backwards compatibility.""" + +# pylint: disable=wildcard-import,unused-import,redefined-builtin +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import * +# used by tests +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _clone_export_output_with_tensors +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _create_global_step +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _export_output_to_tensors +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _get_scaffold +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _Inputs +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _ITERATIONS_PER_LOOP_VAR +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_ENQUEUE_OPS +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_ESTIMATOR +from tensorflow_estimator.python.estimator.tpu.tpu_estimator import _TPU_TRAIN_OP +# pylint: enable=wildcard-import,unused-import,redefined-builtin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_feed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_feed.py new file mode 100644 index 0000000000000000000000000000000000000000..23441ccaaad413bc60b3aeaa181907beabe282f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_feed.py @@ -0,0 +1,956 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# =================================================================== + +"""Helper library for handling infeed between hosts and TPUs. +""" + +import itertools + +import numpy as np + +from tensorflow.python.compiler.xla.experimental import xla_sharding +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.tpu import tpu_name_util +from tensorflow.python.tpu import tpu_sharding +from tensorflow.python.tpu.ops import tpu_ops + +from tensorflow.python.util import nest + + +def partition_or_replicate_on_host(tensor, dims): + """Partitions or replicates the input tensor. + + The ops inside this function are placed on the host side. + + Args: + tensor: The input tensor which will be partitioned or replicated. + dims: A list of integer describes how to partition the input tensor. + + Returns: + An iterator of `Tensor`s or a list of partitioned tensors. + """ + if dims is None: + return itertools.repeat(tensor) + dims = np.array(dims) + output = [tensor] + shape_list = np.array(tensor.shape.as_list()) + quotients, remainders = np.divmod(shape_list, dims) + for axis, (quotient, remainder, dim, original_size) in enumerate( + zip(quotients, remainders, dims, shape_list)): + if dim <= 1: + continue + if remainder > 0: + # For each dimension, when it cannot be evenly partitioned, XLA assumes + # tensors are partitioned in a greedy manner by using + # ceil_ratio(size/dim) first. E.g. 2D tensor with shape (5, 14) and dims + # are (2, 4). Since 5 % 2 = 1 and 14 % 4 = 2, [5, 14] => + # [[(3, 4), (3, 4), (2, 4), (2, 2)], + # [(2, 4), (2, 4), (2, 4), (2, 2)]] + ceil_ratio = quotient + 1 + num_full_slots, left_over = np.divmod(original_size, ceil_ratio) + num_or_size_splits = [ceil_ratio] * num_full_slots + [left_over] + if len(num_or_size_splits) < dim: + num_or_size_splits += [0] * (dim - len(num_or_size_splits)) + new_output = [] + for x in output: + new_output.append( + array_ops.split( + x, num_or_size_splits=num_or_size_splits, axis=axis)) + output = new_output + else: + output = [array_ops.split(x, int(dim), axis=axis) for x in output] + output = nest.flatten(output) + return output + + +def _tag_sharding_attribute_for_dequeued_tensor(tensor, dims): + """Tags appropriate XLA sharding attribute to the dequeued tensor. + + The sharding attribute of the dequeued tensor will be a tuple. + + Args: + tensor: The dequeued tensor on TPU. + dims: A list of integer describes how the tensor is partitioned. + + Returns: + The same tensor with the xla_sharding attribute. + """ + if dims is None: + return xla_sharding.replicate(tensor, assign_tuple_sharding=True) + elif np.prod(dims) == 1: + return xla_sharding.assign_device(tensor, 0, assign_tuple_sharding=True) + else: + tile_assignment = np.arange(np.prod(dims)).reshape(dims) + return xla_sharding.tile( + tensor=tensor, + tile_assignment=tile_assignment, + assign_tuple_sharding=True) + + +def tag_sharding_attribute_for_dequeued_tensors(dequeues, dims): + """Tags appropriate XLA sharding attribute to the dequeued tensors. + + Args: + dequeues: A list of dequeued tensors on TPU. + dims: A list of integer describes how the tensor is partitioned. + + Returns: + The same dequeues with appropriate xla_sharding attribute. + """ + nest.assert_shallow_structure(dequeues, dims) + return nest.map_structure_up_to( + dequeues, _tag_sharding_attribute_for_dequeued_tensor, dequeues, dims) + + +class InfeedQueue(object): + """A helper object to build a device infeed queue. + + The InfeedQueue builds the host-side and device-side Ops to enqueue and + dequeue elements, respectively, and ensures that their types and + shapes match. + """ + + def __init__(self, + number_of_tuple_elements=None, + tuple_types=None, + tuple_shapes=None, + shard_dimensions=None, + number_of_partitions=None, + name=None): + """Creates a new InfeedQueue with the given configuration. + + The configuration need not be fully specified at creation since it + can be modified subsequently by methods that set the values + explicitly or infer them from the shapes of inputs. + + Args: + number_of_tuple_elements: the number of Tensors fed atomically through the + queue, must be present unless it can be inferred from other arguments. + tuple_types: if not None, a list of types of the elements of the queue. + tuple_shapes: if not None, a list of shapes of the elements of the queue. + shard_dimensions: if not None, a list of dimensions on which the + elements of the queue should be sharded during automatic + parallelization. + number_of_partitions: if > 1, the infeed dequeue shape will contain + the full shape that includes all partitions and add corresponding XLA + annotation on the infeed dequeue op. In this case, the infeed is still + data parallel that feeds per-core batch size to each core while the XLA + computation may be partitioned. As XLA requires infeed dequeue shape to + be per-replica shape, thus we need number_of_partitions here to + calculate the per-replica unpartitioned shape. + name: the name of the queue. + + Raises: + ValueError: if number_of_tuple_elements <= 0; or + number_of_tuple_arguments, tuple_types, tuple_shapes, and + shard_dimensions are all None; or the length of tuple_types, + tuple_shapes, or shard_dimensions is not equal to + number_of_tuple_elements; or any element of shard_dimensions + can't be converted to a Dimension. + TypeError: if any element of tuple_types or tuple_shapes can't + be converted to a dtype or TensorShape, respectively. + """ + self._frozen = False + self._generated_enqueue_ops = False + self._generated_dequeue_op = False + self._name = "InfeedQueue" if name is None else name + if number_of_partitions is None: + self._number_of_partitions = 1 + else: + self._number_of_partitions = number_of_partitions + if number_of_tuple_elements is None: + if tuple_types is not None: + number_of_tuple_elements = len(tuple_types) + elif tuple_shapes is not None: + number_of_tuple_elements = len(tuple_shapes) + elif shard_dimensions is not None: + number_of_tuple_elements = len(shard_dimensions) + else: + raise ValueError( + "number of tuple elements cannot be inferred from InfeedQueue " + "constructor") + if number_of_tuple_elements <= 0: + raise ValueError(f"number_of_tuple_elements {number_of_tuple_elements} " + "must be > 0") + # Make an empty sharding policy for each tuple element. + self._sharding_policies = [ + tpu_sharding.ShardingPolicy() for _ in range(number_of_tuple_elements) + ] + if tuple_types is not None: + self.set_tuple_types(tuple_types) + else: + self._tuple_types = None + if tuple_shapes is not None: + self.set_tuple_shapes(tuple_shapes) + else: + self._tuple_shapes = None + if shard_dimensions is not None: + self.set_shard_dimensions(shard_dimensions) + self._validate() + + def _validate(self): + """Checks that the configuration is self-consistent. + + Raises: + ValueError: if the shapes and sharding policies don't match. + """ + if self.tuple_shapes is not None: + for (policy, shape) in zip(self._sharding_policies, self._tuple_shapes): + # Raise an error if the policy is incompatible with the shape. + _ = policy.get_sharded_shape(shape) + + @property + def number_of_tuple_elements(self): + """Returns the number of InfeedQueue tuple elements.""" + return len(self._sharding_policies) + + @property + def tuple_types(self): + """Returns the types of the InfeedQueue tuple elements.""" + return self._tuple_types + + def set_tuple_types(self, tuple_types): + """Sets the type of each element of the queue. + + tuple_types must be a list of length + self.number_of_tuple_elements, and each element must be + convertible to a dtype. + + Args: + tuple_types: the types of each queue element. + + Raises: + ValueError: if tuple_types is not of length + self.number_of_tuple_elements. + TypeError: if an element of tuple_types cannot be converted to a + dtype. + """ + if len(tuple_types) != self.number_of_tuple_elements: + raise ValueError( + f"tuple_types is {str(tuple_types)}, but must be a list of " + f"length {self.number_of_tuple_elements}" + ) + if self._frozen: + for (frozen, updated) in zip(self._tuple_types, tuple_types): + if frozen != updated: + raise ValueError( + "Trying to update InfeedQueue with frozen configuration with an " + f"incompatible type. Frozen types are {str(self._tuple_types)}, " + f"updated types are {str(tuple_types)}") + else: + try: + self._tuple_types = [dtypes.as_dtype(t) for t in tuple_types] + except (TypeError) as e: + raise TypeError( + f"tuple_types is {str(tuple_types)}, but must be a list of " + f"elements each convertible to dtype: got error {str(e)}") from e + + @property + def tuple_shapes(self): + """Returns the shapes of the InfeedQueue tuple elements.""" + return self._tuple_shapes + + def set_tuple_shapes(self, tuple_shapes): + """Sets the shape of each element of the queue. + + tuple_shapes must be a list of length + self.number_of_tuple_elements, and each element must be + convertible to a TensorShape. + + Args: + tuple_shapes: the shapes of each queue element. + + Raises: + ValueError: if tuple_shapes is not of length + self.number_of_tuple_elements. + TypeError: if an element of tuple_shapes cannot be converted to + a TensorShape. + """ + if len(tuple_shapes) != self.number_of_tuple_elements: + raise ValueError( + f"tuple_shapes is {str(tuple_shapes)}, but must be a list of " + f"length {self.number_of_tuple_elements}" + ) + try: + tuple_shapes = [tensor_shape.as_shape(shape) for shape in tuple_shapes] + except (ValueError, TypeError) as e: + raise TypeError( + f"tuple_shapes is {str(tuple_shapes)}, but must be a list of " + "elements each convertible to TensorShape: got error " + f"{str(e)}") from e + if self._frozen: + for (frozen, updated) in zip(self._tuple_shapes, tuple_shapes): + if frozen != updated: + raise ValueError( + "Trying to update InfeedQueue with frozen configuration with an " + "incompatible shape. Frozen shapes are " + f"{str(self._tuple_shapes)}, updated shapes are " + f"{str(tuple_shapes)}") + + else: + self._tuple_shapes = tuple_shapes + self._validate() + + @property + def sharding_policies(self): + """Returns the sharding policies of the InfeedQueue tuple elements.""" + return self._sharding_policies + + @property + def shard_dimensions(self): + """Gets the shard dimension of each tuple element. + + Returns: + A list of length number_of_tuple_elements, where each list entry + is the shard dimension of that tuple element or None if the + shard dimension has not been set. + """ + # The number of shards is always the same for all the policies. + return [policy.shard_dimension for policy in self._sharding_policies] + + def set_shard_dimensions(self, shard_dimensions): + """Sets the shard_dimension of each element of the queue. + + shard_dimensions must be a list of length + self.number_of_tuple_elements, and each element must be + convertible to a Dimension compatible with self.tuple_shapes. + + Args: + shard_dimensions: the dimensions of each queue element. + + Raises: + ValueError: if shard_dimensions is not of length + self.number_of_tuple_elements; or an element of + shard_dimensions cannot be converted to a Dimension; or an + element of shard_dimensions is a Dimension that is out of + range for the corresponding tuple element shape. + """ + if len(shard_dimensions) != self.number_of_tuple_elements: + raise ValueError(f"shard_dimensions is {str(shard_dimensions)}, but must " + f"be a list of length {self.number_of_tuple_elements}") + for (policy, dimension) in zip(self._sharding_policies, shard_dimensions): + policy.set_shard_dimension(dimension) + self._validate() + + @property + def number_of_shards(self): + """Gets the number of shards to use for the InfeedQueue. + + Returns: + Number of shards or None if the number of shards has not been set. + """ + # The number of shards is always the same for all the policies. + return self._sharding_policies[0].number_of_shards + + def set_number_of_shards(self, number_of_shards): + """Sets the number of shards to use for the InfeedQueue. + + Args: + number_of_shards: number of ways to shard the InfeedQueue. + + Raises: + ValueError: if number_of_shards is not > 0; or the policies have + been frozen and number_of_shards was already set to something + else. + """ + for policy in self._sharding_policies: + policy.set_number_of_shards(number_of_shards) + policy.set_number_of_partitions(self._number_of_partitions) + self._validate() + + def set_configuration_from_input_tensors(self, input_tensors): + """Sets the shapes and types of the queue tuple elements. + + input_tensors is a list of Tensors whose types and shapes are used + to set the queue configuration. + + Args: + input_tensors: list of Tensors of the same types and shapes as + the desired queue Tuple. + + Raises: + ValueError: if input_tensors is not a list of length + self.number_of_tuple_elements + """ + if len(input_tensors) != self.number_of_tuple_elements: + raise ValueError(f"input_tensors is {str(input_tensors)}, but should be " + f"a list of {self.number_of_tuple_elements} Tensors") + self.set_tuple_shapes([t.shape for t in input_tensors]) + self.set_tuple_types([t.dtype for t in input_tensors]) + + def set_configuration_from_sharded_input_tensors(self, input_tensors): + """Sets the shapes and types of the queue tuple elements. + + input_tensors is a list of lists of Tensors whose types and shapes are used + to set the queue configuration. The length of the outer list is the number + of shards required, and each inner list is the tuple of Tensors to use to + determine the types and shapes of the corresponding shard. This method + depends on the shard dimension, and calling it freezes the shard policy. + + Args: + input_tensors: list of lists of Tensors. The outer list length corresponds + to the desired number of shards, and each inner list is the size + and shape of the desired configuration of the corresponding shard. + + Raises: + ValueError: if any inner list is not a list of length + self.number_of_tuple_elements; or the inner lists do not combine to + form a consistent unsharded shape. + TypeError: if the types of the Tensors in the inner lists do not match. + """ + if not self._frozen: + # Unset the tuple shapes in case the configuration becomes + # transiently inconsistent. + self._tuple_shapes = None + number_of_shards = len(input_tensors) + self.set_number_of_shards(number_of_shards) + for t in input_tensors: + if len(t) != self.number_of_tuple_elements: + raise ValueError( + f"input_tensors is {str(input_tensors)} but must be a list of " + "lists, where each inner list has length " + f"number_of_tuple_elements={self.number_of_tuple_elements}") + # Transpose the inputs to make a list of shard shapes for each tuple + # element. + sharded_shapes = [[t[i].shape + for t in input_tensors] + for i in range(self.number_of_tuple_elements)] + # For each tuple, get the unsharded shape using that tuple's policy. + unsharded_shapes = [ + policy.get_unsharded_shape(s) + for (policy, s) in zip(self._sharding_policies, sharded_shapes) + ] + self.set_tuple_shapes(unsharded_shapes) + for i in range(1, self.number_of_shards): + for (t1, t2) in zip(input_tensors[0], input_tensors[i]): + if t1.dtype != t2.dtype: + raise TypeError( + "types of the tuple elements of input_tensors " + f"{str(input_tensors)} are not consistent") + self.set_tuple_types([t.dtype for t in input_tensors[0]]) + + def freeze(self): + """Freezes the InfeedQueue so it can no longer be modified. + + The configuration is implicitly frozen before any host-side or + device-side Ops are generated. The configuration cannot be frozen + until the types and shapes of the tuple elements have been set. + + Raises: + ValueError: if the types or shapes of the tuple elements have not been + set. + """ + self._frozen = True + if self._tuple_types is None: + raise ValueError( + "Can't freeze an InfeedQueue without setting all tuple types.") + if self._tuple_shapes is None: + raise ValueError( + "Can't freeze an InfeedQueue without setting all tuple shapes.") + for shape in self._tuple_shapes: + if shape.dims is None: + raise ValueError( + "Can't freeze an InfeedQueue without setting all tuple shapes.") + for policy in self._sharding_policies: + policy.freeze() + self._validate() + + def generate_dequeue_op(self, tpu_device=0): + """Generates the device-side Op to dequeue a tuple from the queue. + + Implicitly freezes the queue configuration if it is not already + frozen, which will raise errors if the shapes and types have not + been fully specified. + + Args: + tpu_device: The TPU device ordinal where the infeed instruction should be + placed. If None, no explicit placement will be performed, and it is up + to the user to call this API from within a proper TPU device scope. + The XLA code will fail if the TPU dequeue instruction is not bound to + any device. + + Returns: + A list of Outputs corresponding to a shard of infeed dequeued + into XLA, suitable for use within a replicated block. + + Raises: + ValueError: if the types or shapes of the tuple elements have not been + set; or if a dequeue op has already been generated. + """ + self.freeze() + if self._generated_dequeue_op and not ops.inside_function(): + raise ValueError("Can't generate two dequeue Ops from the same queue") + self._generated_dequeue_op = True + full_name = "%s/dequeue" % self._name + sharded_shapes = [ + policy.get_unpartitioned_shape(policy.get_sharded_shape(shape)) + for (shape, policy) in zip(self._tuple_shapes, self._sharding_policies) + ] + if tpu_device is not None: + with ops.device(tpu_name_util.core(tpu_device)): + dequeue_op = tpu_ops.infeed_dequeue_tuple( + dtypes=self._tuple_types, shapes=sharded_shapes, name=full_name) + else: + dequeue_op = tpu_ops.infeed_dequeue_tuple( + dtypes=self._tuple_types, shapes=sharded_shapes, name=full_name) + if self._number_of_partitions <= 1: + return dequeue_op + partitions = [ + policy.get_unpartitioned_shape([1] * shape.ndims).as_list() + for (shape, policy) in zip(self._tuple_shapes, self._sharding_policies) + ] + return tag_sharding_attribute_for_dequeued_tensors(dequeue_op, partitions) + + def _generate_enqueue_op(self, + inputs, + name_prefix, + index, + device=None, + tpu_ordinal=-1): + """Generate a host-side Op to enqueue a tuple to the queue. + + If device is None the inputs are all required to have the same + device specification, and the enqueue Op is colocated with + inputs[0]. Otherwise the enqueue Op is placed on 'device'. + + Args: + inputs: a list of Tensors with the types and shapes of the tuple elements. + name_prefix: the base name for the Op. + index: the shard index, used to uniquify the Op name. + device: device to place the Op on, or None if it should be + colocated with the inputs. + tpu_ordinal: ordinal of the TPU device on the host to use for + infeed if device is a CPU device. Should be set to -1 if device + is a TPU device. + + Returns: + An Op corresponding to a shard of infeed enqueued at the host, + suitable for use within a replicated block. + + Raises: + ValueError: if device is None and inputs do not all have the + same device specification. + """ + full_name = "%s/%d" % (name_prefix, index) + shapes = [t.shape for t in inputs] + if device is None: + devices = [t.device for t in inputs] + for i in range(1, self.number_of_tuple_elements): + if devices[0] != devices[i]: + raise ValueError( + f"input devices for shard {index} are {str(devices)}, but should " + "all be the same") + with ops.colocate_with(inputs[0]): + return tpu_ops.infeed_enqueue_tuple( + inputs=inputs, + shapes=shapes, + name=full_name, + device_ordinal=tpu_ordinal) + else: + with ops.device(device): + return tpu_ops.infeed_enqueue_tuple( + inputs=inputs, + shapes=shapes, + name=full_name, + device_ordinal=tpu_ordinal) + + def generate_enqueue_ops(self, + sharded_inputs, + tpu_ordinal_function=None, + placement_function=None): + """Generates the host-side Ops to enqueue the shards of a tuple. + + sharded_inputs is a list, one for each shard, of lists of + Tensors. sharded_inputs[i] is the tuple of Tensors to use to feed + shard i of the queue. Returns the host-side Ops that must be run to + enqueue the sharded tuple. The Op for shard i is colocated with the inputs + for shard i. + + Implicitly freezes the queue configuration if it is not already + frozen. If the configuration has already been frozen, and is not + compatible with the types and shapes of sharded_inputs, an error + will be raised. + + Args: + sharded_inputs: a list of lists of Tensors. The length of the outer list + determines the number of shards. Each inner list indicates the types + and shapes of the tuples in the corresponding shard. + tpu_ordinal_function: if not None, a function that takes the + shard index as input and returns the ordinal of the TPU device + the shard's infeed should be placed on. tpu_ordinal_function must be + set if the inputs are placed on CPU devices. + placement_function: if not None, a function that takes the shard index as + input and returns the host device where the enqueue op should be placed + on. + + Returns: + A list of host-side Ops, one for each shard, that when executed together + will enqueue a full-size element of infeed. + + Raises: + ValueError: if the queue configuration has previously been frozen and the + shapes of the elements of sharded_inputs are not compatible with the + frozen configuration; or if the shapes of the elements of sharded_inputs + don't form a consistent unsharded tuple; or if the elements of a tuple + have different device constraints. + TypeError: if the queue configuration has previously been frozen and the + types of the elements of sharded_inputs are not compatible with the + frozen configuration; or if the types of the elements of sharded_inputs + don't form a consistent unsharded tuple. + """ + self.set_configuration_from_sharded_input_tensors(sharded_inputs) + self.freeze() + if self._generated_enqueue_ops and not ops.inside_function(): + raise ValueError("Can't generate two enqueue Ops from the same queue") + self._generated_enqueue_ops = True + if tpu_ordinal_function is None: + tpu_ordinal_function = lambda index: -1 + name_prefix = "%s/enqueue" % self._name + return [ + self._generate_enqueue_op( + shard, + name_prefix, + index, + tpu_ordinal=tpu_ordinal_function(index), + device=placement_function(index) if placement_function else None) + for (shard, index) in zip(sharded_inputs, range(self.number_of_shards)) + ] + + # TODO(misard) Generalize this to the case of systems that don't + # have 8 devices per host, and figure out what to do with + # model-parallelism. + def _default_placement_function(self, index): + return "/task:%d/device:CPU:0" % (index / 8) + + def _default_ordinal_function(self, index): + return index % 8 + + # TODO(b/36470756) remove this from tutorials once we have a better story + # for automatic placement of input pipelines. + def split_inputs_and_generate_enqueue_ops(self, + inputs, + device_assignment=None, + placement_function=None, + tpu_ordinal_function=None): + """POORLY-PERFORMING ON MULTI-HOST SYSTEMS. + + Generates the host-side Ops to enqueue a tuple. + + This method performs poorly because it takes an entire input on a single + host, splits it, and distributes it to all of the cores. It is present only + to simplify tutorial examples. + + inputs is a list of Tensors to use to feed the queue. Each input is split + into self.number_of_shards shards. Returns an Op for each shard to enqueue + the shard. The Op for shard i is placed on device placement_function(i). + + Implicitly freezes the queue configuration if it is not already + frozen. If the configuration has already been frozen, and is not + compatible with the types and shapes of inputs, an error + will be raised. + + Args: + inputs: a list of Tensors which indicates the types and shapes of the + queue tuple. + device_assignment: if not `None`, a TPU `DeviceAssignment`. If + device_assignment is not `None`, but `placement_function` and + `ordinal_function` are None, then `device_assignment` will be used to + place infeeds on the first k TPU shards, where k is the number of shards + in the queue. If all three are `None`, then default placement and + ordinal functions are used. + placement_function: if not None, a function that takes the shard + index as input and returns a device string indicating which + device the shard's infeed should be placed on. If placement_function + and tpu_ordinal_function are None, inputs are sharded round-robin + across the devices in the system. + tpu_ordinal_function: if not None, a function that takes the + shard index as input and returns the ordinal of the TPU device + the shard's infeed should be placed on. If placement_function + and tpu_ordinal_function are None, inputs are sharded round-robin + across the devices in the system. + + Returns: + A list of host-side Ops, one for each shard, that when executed together + will enqueue a full-size element of infeed. + + Raises: + ValueError: if the queue configuration has previously been frozen and the + shapes of the elements of inputs are not compatible with the frozen + configuration. + TypeError: if the queue configuration has previously been frozen and the + types of the elements of inputs are not compatible with the frozen + configuration. + """ + if device_assignment is None: + if placement_function is None: + placement_function = self._default_placement_function + if tpu_ordinal_function is None: + tpu_ordinal_function = self._default_ordinal_function + else: + + def _placement_function_from_map(index): + return device_assignment.host_device(replica=index) + + def _ordinal_function_from_map(index): + return device_assignment.tpu_ordinal(replica=index) + + if placement_function is None: + placement_function = _placement_function_from_map + if tpu_ordinal_function is None: + tpu_ordinal_function = _ordinal_function_from_map + self.set_configuration_from_input_tensors(inputs) + self.freeze() + if self._generated_enqueue_ops and not ops.inside_function(): + raise ValueError("Can't generate two enqueue Ops from the same queue") + self._generated_enqueue_ops = True + split_name_prefix = "%s/split" % self._name + if self.number_of_shards == 1: + transposed_sharded_inputs = [[inp] for inp in inputs] + else: + + def split_fn(inp, num_shards, axis, name): + with ops.colocate_with(inp): + return array_ops.split(inp, num_shards, axis=axis, name=name) + + transposed_sharded_inputs = [ + split_fn( + inp, + self.number_of_shards, + axis=policy.shard_dimension, + name="%s/%d" % (split_name_prefix, index)) + for (inp, policy, index) in zip(inputs, self._sharding_policies, + range(self.number_of_tuple_elements)) + ] + sharded_inputs = [[shard[i] + for shard in transposed_sharded_inputs] + for i in range(self.number_of_shards)] + name_prefix = "%s/enqueue" % self._name + return [ + self._generate_enqueue_op( + shard, + name_prefix, + index, + device=placement_function(index), + tpu_ordinal=tpu_ordinal_function(index)) + for (shard, index) in zip(sharded_inputs, range(self.number_of_shards)) + ] + + +class _PartitionedInfeedQueue(InfeedQueue): + """A helper object to build a device infeed queue with input partition. + + Args: + number_of_tuple_elements: the number of Tensors fed atomically through the + queue, must be present unless it can be inferred from other arguments. + device_assignment: A TPU `DeviceAssignment` which is used to place all the + partitions to different TPU infeed queues. + host_id: The id of the host machine. + input_partition_dims: A nested list/tuple of integers. Each inner + list/tuple describes how to partition the corresponding input tensor. + tuple_types: If not None, a list of types of the elements of the queue. + tuple_shapes: If not None, a list of shapes of the elements of the queue. + name: The name of the queue. + """ + + def __init__(self, + number_of_tuple_elements, + device_assignment, + host_id, + input_partition_dims=None, + tuple_types=None, + tuple_shapes=None, + name=None): + super(_PartitionedInfeedQueue, self).__init__( + number_of_tuple_elements=number_of_tuple_elements, + tuple_types=tuple_types, + tuple_shapes=None, + shard_dimensions=None, + name="PartitionedInfeedQueue" if name is None else name) + self._input_partition_dims = input_partition_dims + self._host_id = host_id + self._device_assignment = device_assignment + + def generate_dequeue_op(self, tpu_device=0): + """Generate TPU dequeue ops. + + Args: + tpu_device: The TPU device ordinal where the infeed instruction should be + placed. + + Returns: + A list of Outputs corresponding to a partition of infeed dequeued + into XLA, suitable for use within a replicated block. + + Raises: + ValueError: if the types or shapes of the tuple elements have not been + set; or if a dequeue op has already been generated. + """ + self.freeze() + if self._generated_dequeue_op and not ops.inside_function(): + raise ValueError("Can't generate two dequeue Ops from the same queue") + self._generated_dequeue_op = True + full_name = "%s/dequeue" % self._name + sharded_shapes = [ + policy.get_sharded_shape(shape) + for (shape, policy) in zip(self._tuple_shapes, self._sharding_policies) + ] + with ops.device(tpu_name_util.core(tpu_device)): + values = tpu_ops.infeed_dequeue_tuple( + dtypes=self._tuple_types, shapes=sharded_shapes, name=full_name) + return tag_sharding_attribute_for_dequeued_tensors( + values, self._input_partition_dims) + + def generate_enqueue_ops(self, sharded_inputs): # pytype: disable=signature-mismatch # overriding-parameter-count-checks + """Generates the host-side Ops to enqueue the partitioned inputs. + + sharded_inputs is a list, one for each replica, of lists of + Tensors. sharded_inputs[i] is the tuple of Tensors to use to feed + replica i. + sharded_inputs[i][j] is partitioned by self._input_partition_dims[j]. + + For example, if sharded_inputs[i][j] is a 2-D Tensor: + [[A, B, C, D], + [E ,F, G, H]] + self._input_partition_dims[j] is [2, 4]. + + sharded_inputs[i][j] will be partitioned and flattened into: + [A, B, C, D, E, F, G, H] and fed into the logical core ids: + [0, 1, 2, 3, 4, 5, 6, 7] respectively. + + Args: + sharded_inputs: a list of lists of Tensors. The length of the + outer list determines the number of shards. Each inner list indicates + the types and shapes of the tuples in the corresponding shard. + + Returns: + A list of host-side Ops, one for each shard, that when executed together + will enqueue a full-size element of infeed. + + Raises: + ValueError: if the queue configuration has previously been frozen and the + shapes of the elements of sharded_inputs are not compatible with the + frozen configuration; or if the shapes of the elements of sharded_inputs + don't form a consistent unsharded tuple; or if the elements of a tuple + have different device constraints; or if the partition dims are invalid. + TypeError: if the queue configuration has previously been frozen and the + types of the elements of sharded_inputs are not compatible with the + frozen configuration; or if the types of the elements of sharded_inputs + don't form a consistent unsharded tuple. + """ + self.set_configuration_from_sharded_input_tensors(sharded_inputs) + number_of_replicas = len(sharded_inputs) + number_of_tuple_elements = len(sharded_inputs[0]) + + assert len(self._input_partition_dims) == number_of_tuple_elements + enqueue_ops = [] + + for replica_index in range(number_of_replicas): + flattened_inputs = sharded_inputs[replica_index] + inputs_part_dims_flat = nest.flatten_up_to(flattened_inputs, + self._input_partition_dims) + inputs_parted_iters = [ + iter(self._check_dims_and_partition_or_replicate_on_host(x, dims)) + for x, dims in zip(sharded_inputs[replica_index], + inputs_part_dims_flat) + ] + + # Find the replica_id of the host's logical core 0. + # The self._host_id is guaranteed to contain the logical core 0, + # even when num_cores_per_replica > num_cores_per_host -- the function + # caller makes sure that this host_id will must be receiving data (calls + # input_fn). + replica_id = self._device_assignment.lookup_replicas( + task_id=self._host_id, logical_core=0)[replica_index] + for logical_core in range(self._device_assignment.num_cores_per_replica): + # Places different partitions to different logic cores. + # Since there can be multiple hosts per replica, we need to find + # the actual host (device) of this logical core. + device = self._device_assignment.host_device( + replica=replica_id, logical_core=logical_core) + + with ops.device(device): + ordinal = self._device_assignment.tpu_ordinal( + replica=replica_id, logical_core=logical_core) + infeed_inputs = [] + for it in inputs_parted_iters: + input_for_device = next(it, None) + if input_for_device is not None: + infeed_inputs.append(input_for_device) + + if infeed_inputs: + enqueue_ops.append( + tpu_ops.infeed_enqueue_tuple( + inputs=infeed_inputs, + shapes=[x.shape for x in infeed_inputs], + name="enqueue/replica_{0}/input_{1}".format( + replica_index, logical_core), + device_ordinal=ordinal)) + return enqueue_ops + + def _check_input_partition_dims(self, tensor, dims): + """Checks that input partition dims are valid for the `Tensor`. + + Args: + tensor: Input tensor for partitioning. + dims: A list of integer describes how to partition the input tensor. + + Raises: + ValueError: If the tensor can't be partitioned by dims or the + num_cores_per_replica doesn't match the number of + partitions(dims.prod()). + """ + # No partitioning specified, so don't perform further checks. + if dims is None: + return + + dims = np.array(dims) + + if (dims < 1).any(): + raise ValueError("All input partition dims must be >= 1.") + + # No partitioning, so don't perform further checks. + if dims.prod() == 1: + return + + if dims.prod() != self._device_assignment.num_cores_per_replica: + raise ValueError( + "The product of each input partition dim should equal to " + "num_cores_per_replica. (dim = {}, num_cores_per_replica " + "= {})".format(dims, self._device_assignment.num_cores_per_replica)) + if dims.shape[0] != tensor.shape.ndims: + raise ValueError( + "Input partition dims must have the same number of dimensions " + "as the `Tensor` to be partitioned. (tensor shape = {}, input " + "partition dims = {}).".format(tensor.shape.as_list(), dims)) + + tensor.shape.assert_is_fully_defined() + + def _check_dims_and_partition_or_replicate_on_host(self, tensor, dims): + """Checks dims and partitions or replicates the input tensor. + + The ops inside this function are placed on the host side. + + Args: + tensor: The input tensor which will be partitioned or replicated. + dims: A list of integer describes how to partition the input tensor. + + Returns: + An iterator of `Tensor`s or a list of partitioned tensors. + """ + self._check_input_partition_dims(tensor, dims) + return partition_or_replicate_on_host(tensor, dims) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_function.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5fe03c784be262ead60dbdcb72152133935eda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_function.py @@ -0,0 +1,69 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Helper library for functions used during TPU compilation.""" + +import contextlib +import threading + + +class TpuContext(threading.local): + """A context object holding state about the TPU computation being built.""" + + def __init__(self): + """Creates a new TpuContext.""" + self._number_of_shards = None + + @property + def number_of_shards(self): + return self._number_of_shards + + def set_number_of_shards(self, number_of_shards): + self._number_of_shards = number_of_shards + + +# The Tpu context holds the number of shards when a sharded computation is +# being built, or None if no computation is being built. +_current_tpu_context = TpuContext() + + +@contextlib.contextmanager +def tpu_shard_context(number_of_shards): + """A context manager setting current number of shards.""" + if _current_tpu_context.number_of_shards is not None: + raise NotImplementedError( + "tpu_shard_context cannot be nested." + "If you're using TPUEstimator with inference_on_tpu, " + "make sure you have set " + "export_saved_model_api_version=ExportSavedModelApiVersion.V2 in " + "the creation of TPUEstimator.") + try: + _current_tpu_context.set_number_of_shards(number_of_shards) + yield + finally: + _current_tpu_context.set_number_of_shards(None) + + +def get_tpu_context(): + return _current_tpu_context + + +# Decorator function for tpu computation func that was passed to tpu.rewrite() +# if there is an embedded training loop in this func, trace tools will generate +# step markers for each iteration. +def on_device_training_loop(func): + # Value for this attribute is from tensorflow.compiler.xla.DebugOptions.StepMarkerLocation. + setattr(func, "step_marker_location", "STEP_MARK_AT_TOP_LEVEL_WHILE_LOOP") + return func diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_hardware_feature.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_hardware_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..23ff5658e1d27253f1377f18697c8e670dd1a076 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_hardware_feature.py @@ -0,0 +1,81 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""TPU hardware feature info.""" +import enum +from tensorflow.core.protobuf.tpu import topology_pb2 +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("tpu.experimental.HardwareFeature") +class HardwareFeature(object): + """class holds all the feature info about the TPU.""" + + def __init__(self, tpu_hardware_feature_proto): + """Store TPU hardware feature info. + + Args: + tpu_hardware_feature_proto: protobuf which describe the tpu hardware + feature. + """ + self.tpu_hardware_feature_proto = tpu_hardware_feature_proto + + class EmbeddingFeature(enum.Enum): + """Embedding feature flag strings. + + UNSUPPORTED: No embedding lookup accelerator available on the tpu. + V1: Embedding lookup accelerator V1. The embedding lookup operation can only + be placed at the beginning of computation. Only one instance of + embedding + lookup layer is allowed. + V2: Embedding lookup accelerator V2. The embedding lookup operation can be + placed anywhere of the computation. Multiple instances of embedding + lookup layer is allowed. + """ + UNSUPPORTED = "UNSUPPORTED" + V1 = "V1" + V2 = "V2" + + @classmethod + def _embedding_feature_proto_to_string(cls, embedding_feature_proto): + """Convert the embedding feature proto to enum string.""" + embedding_feature_proto_to_string_map = { + topology_pb2.TPUHardwareFeature.EmbeddingFeature.UNSUPPORTED: + HardwareFeature.EmbeddingFeature.UNSUPPORTED, + topology_pb2.TPUHardwareFeature.EmbeddingFeature.V1: + HardwareFeature.EmbeddingFeature.V1, + topology_pb2.TPUHardwareFeature.EmbeddingFeature.V2: + HardwareFeature.EmbeddingFeature.V2 + } + return embedding_feature_proto_to_string_map.get( + embedding_feature_proto, HardwareFeature.EmbeddingFeature.UNSUPPORTED) + + @property + def embedding_feature(self): + """TPU embedding feature. + + Returns: + An EmbeddingFeature enum. + """ + return HardwareFeature._embedding_feature_proto_to_string( + self.tpu_hardware_feature_proto.embedding_feature) + + @property + def num_embedding_devices_per_chip(self): + """Number of embedding accelerator devices per chip. + + Returns: + Number of embedding devices per chip. + """ + return self.tpu_hardware_feature_proto.num_embedding_devices_per_chip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_name_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_name_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a201fe2d20830180b80fdafbbb2f0a861fecc86a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tpu/tpu_name_util.py @@ -0,0 +1,31 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ====================================== +"""Helper functions for TPU device names.""" + +from typing import Text +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["tpu.core"]) +def core(num: int) -> Text: + """Returns the device name for a core in a replicated TPU computation. + + Args: + num: the virtual core number within each replica to which operators should + be assigned. + Returns: + A device name, suitable for passing to `tf.device()`. + """ + return "device:TPU_REPLICATED_CORE:{}".format(num)